From 52fbb1f75d884f4572bdeecdc7e28a0a1fe7236e Mon Sep 17 00:00:00 2001 From: nicholaschen Date: Wed, 18 Mar 2015 11:12:04 -0400 Subject: [PATCH 001/180] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4b198efa..5c557b96 100644 --- a/README.md +++ b/README.md @@ -127,4 +127,5 @@ suds_client.service.mutate([operation]) ##Authors: - jdilallo@google.com (Joseph DiLallo) + Nicholas Chen + Mark Saniscalchi From 5231623f0e654658374cc24e856a26bf8d79e397 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 27 Apr 2015 18:00:23 -0400 Subject: [PATCH 002/180] Removing v201406. --- ChangeLog | 5 + README.md | 3 +- examples/adwords/v201406/__init__.py | 0 .../v201406/account_management/__init__.py | 0 .../account_management/create_account.py | 67 --- .../account_management/get_account_alerts.py | 86 --- .../account_management/get_account_changes.py | 102 ---- .../get_account_hierarchy.py | 98 ---- .../v201406/advanced_operations/__init__.py | 0 .../advanced_operations/add_ad_customizer.py | 251 --------- .../add_ad_group_bid_modifier.py | 78 --- .../add_click_to_download_ad.py | 113 ---- ..._google_my_business_location_extensions.py | 140 ----- .../advanced_operations/add_site_links.py | 261 --------- .../add_text_ad_with_upgraded_urls.py | 114 ---- .../get_ad_group_bid_modifier.py | 76 --- .../advanced_operations/update_site_links.py | 168 ------ .../upload_offline_conversions.py | 101 ---- .../use_shared_bidding_strategy.py | 180 ------ .../v201406/basic_operations/__init__.py | 0 .../v201406/basic_operations/add_ad_groups.py | 116 ---- .../v201406/basic_operations/add_campaigns.py | 141 ----- .../v201406/basic_operations/add_keywords.py | 95 ---- .../v201406/basic_operations/add_text_ads.py | 98 ---- .../v201406/basic_operations/get_ad_groups.py | 80 --- .../v201406/basic_operations/get_campaigns.py | 77 --- .../get_campaigns_with_awql.py | 68 --- .../v201406/basic_operations/get_keywords.py | 81 --- .../v201406/basic_operations/get_text_ads.py | 85 --- .../v201406/basic_operations/pause_ad.py | 65 --- .../v201406/basic_operations/remove_ad.py | 66 --- .../basic_operations/remove_ad_group.py | 62 -- .../basic_operations/remove_campaign.py | 62 -- .../basic_operations/remove_keyword.py | 72 --- .../basic_operations/update_ad_group.py | 62 -- .../basic_operations/update_campaign.py | 62 -- .../basic_operations/update_keyword.py | 87 --- .../v201406/campaign_management/__init__.py | 0 .../add_campaign_labels.py | 70 --- .../campaign_management/add_experiment.py | 132 ----- .../add_keywords_in_bulk.py | 141 ----- .../add_location_extension.py | 114 ---- .../get_all_disapproved_ads.py | 78 --- .../get_all_disapproved_ads_with_awql.py | 67 --- .../get_campaigns_by_label.py | 88 --- .../campaign_management/promote_experiment.py | 65 --- .../campaign_management/set_ad_parameters.py | 105 ---- .../set_criterion_bid_modifier.py | 82 --- .../campaign_management/validate_text_ad.py | 89 --- .../v201406/error_handling/__init__.py | 0 .../error_handling/handle_partial_failures.py | 124 ---- .../handle_policy_violation_error.py | 117 ---- examples/adwords/v201406/misc/__init__.py | 0 .../v201406/misc/get_all_images_and_videos.py | 80 --- examples/adwords/v201406/misc/upload_image.py | 70 --- .../adwords/v201406/optimization/__init__.py | 0 .../optimization/estimate_keyword_traffic.py | 122 ---- .../get_keyword_bid_simulations.py | 88 --- .../v201406/optimization/get_keyword_ideas.py | 94 ---- .../optimization/get_placement_ideas.py | 81 --- .../adwords/v201406/remarketing/__init__.py | 0 .../v201406/remarketing/add_audience.py | 107 ---- .../remarketing/add_conversion_tracker.py | 77 --- .../adwords/v201406/reporting/__init__.py | 0 .../reporting/download_criteria_report.py | 65 --- .../download_criteria_report_as_stream.py | 77 --- ...oad_criteria_report_as_stream_with_awql.py | 80 --- .../download_criteria_report_as_string.py | 64 --- ...oad_criteria_report_as_string_with_awql.py | 58 -- .../download_criteria_report_with_awql.py | 61 -- .../v201406/reporting/get_report_fields.py | 56 -- .../shopping/add_product_partition_tree.py | 285 ---------- .../v201406/shopping/add_product_scope.py | 107 ---- .../v201406/shopping/add_shopping_campaign.py | 127 ----- .../shopping/get_product_category_taxonomy.py | 99 ---- .../shopping/set_product_sales_channel.py | 71 --- .../adwords/v201406/targeting/__init__.py | 0 .../add_campaign_targeting_criteria.py | 159 ------ .../add_demographic_targeting_criteria.py | 99 ---- .../get_campaign_targeting_criteria.py | 89 --- .../get_targetable_languages_and_carriers.py | 60 -- .../v201406/targeting/lookup_location.py | 86 --- .../advanced_operations/add_ad_customizer.py | 4 +- .../migrate_to_extension_settings.py | 528 +++++++++++++++++ .../download_criteria_report_as_stream.py | 5 +- ...oad_criteria_report_as_stream_with_awql.py | 4 +- .../advanced_operations/add_ad_customizer.py | 332 +++++------ ...ind_and_remove_criteria_from_shared_set.py | 2 +- .../add_location_extension.py | 114 ---- .../extensions/add_site_links_using_feeds.py | 70 +-- .../migrate_to_extension_settings.py | 529 ++++++++++++++++++ .../download_criteria_report_as_stream.py | 5 +- ...oad_criteria_report_as_stream_with_awql.py | 4 +- examples/adxbuyer/v201406/__init__.py | 0 .../v201406/basic_operations/__init__.py | 0 .../v201406/basic_operations/add_ad_groups.py | 91 --- .../v201406/basic_operations/add_campaigns.py | 129 ----- .../basic_operations/add_placements.py | 90 --- .../add_third_party_redirect_ad.py | 102 ---- .../basic_operations/get_placements.py | 78 --- .../get_third_party_redirect_ads.py | 83 --- .../basic_operations/remove_placement.py | 71 --- .../basic_operations/update_placement.py | 83 --- .../v201406/campaign_management/__init__.py | 0 .../add_placements_in_bulk.py | 138 ----- .../v201406/error_handling/__init__.py | 0 .../error_handling/handle_partial_failures.py | 117 ---- .../adxbuyer/v201406/optimization/__init__.py | 0 .../optimization/get_placement_ideas.py | 80 --- googleads/adwords.py | 146 ++--- googleads/common.py | 2 +- tests/adwords_test.py | 41 +- 112 files changed, 1362 insertions(+), 8342 deletions(-) delete mode 100644 examples/adwords/v201406/__init__.py delete mode 100644 examples/adwords/v201406/account_management/__init__.py delete mode 100755 examples/adwords/v201406/account_management/create_account.py delete mode 100755 examples/adwords/v201406/account_management/get_account_alerts.py delete mode 100755 examples/adwords/v201406/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201406/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201406/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201406/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201406/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201406/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201406/advanced_operations/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201406/advanced_operations/add_site_links.py delete mode 100755 examples/adwords/v201406/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201406/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201406/advanced_operations/update_site_links.py delete mode 100755 examples/adwords/v201406/advanced_operations/upload_offline_conversions.py delete mode 100755 examples/adwords/v201406/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201406/basic_operations/__init__.py delete mode 100755 examples/adwords/v201406/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201406/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201406/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201406/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201406/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201406/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201406/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201406/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201406/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201406/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201406/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201406/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201406/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201406/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201406/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201406/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201406/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201406/campaign_management/__init__.py delete mode 100755 examples/adwords/v201406/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201406/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201406/campaign_management/add_keywords_in_bulk.py delete mode 100755 examples/adwords/v201406/campaign_management/add_location_extension.py delete mode 100755 examples/adwords/v201406/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201406/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201406/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201406/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201406/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201406/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201406/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201406/error_handling/__init__.py delete mode 100755 examples/adwords/v201406/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201406/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201406/misc/__init__.py delete mode 100755 examples/adwords/v201406/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201406/misc/upload_image.py delete mode 100644 examples/adwords/v201406/optimization/__init__.py delete mode 100755 examples/adwords/v201406/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201406/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201406/optimization/get_keyword_ideas.py delete mode 100755 examples/adwords/v201406/optimization/get_placement_ideas.py delete mode 100644 examples/adwords/v201406/remarketing/__init__.py delete mode 100755 examples/adwords/v201406/remarketing/add_audience.py delete mode 100755 examples/adwords/v201406/remarketing/add_conversion_tracker.py delete mode 100644 examples/adwords/v201406/reporting/__init__.py delete mode 100755 examples/adwords/v201406/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201406/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201406/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201406/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201406/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201406/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201406/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201406/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201406/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201406/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201406/shopping/get_product_category_taxonomy.py delete mode 100755 examples/adwords/v201406/shopping/set_product_sales_channel.py delete mode 100644 examples/adwords/v201406/targeting/__init__.py delete mode 100755 examples/adwords/v201406/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201406/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201406/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201406/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201406/targeting/lookup_location.py create mode 100755 examples/adwords/v201409/migration/migrate_to_extension_settings.py delete mode 100755 examples/adwords/v201502/campaign_management/add_location_extension.py create mode 100755 examples/adwords/v201502/migration/migrate_to_extension_settings.py delete mode 100644 examples/adxbuyer/v201406/__init__.py delete mode 100644 examples/adxbuyer/v201406/basic_operations/__init__.py delete mode 100755 examples/adxbuyer/v201406/basic_operations/add_ad_groups.py delete mode 100755 examples/adxbuyer/v201406/basic_operations/add_campaigns.py delete mode 100755 examples/adxbuyer/v201406/basic_operations/add_placements.py delete mode 100755 examples/adxbuyer/v201406/basic_operations/add_third_party_redirect_ad.py delete mode 100755 examples/adxbuyer/v201406/basic_operations/get_placements.py delete mode 100755 examples/adxbuyer/v201406/basic_operations/get_third_party_redirect_ads.py delete mode 100755 examples/adxbuyer/v201406/basic_operations/remove_placement.py delete mode 100755 examples/adxbuyer/v201406/basic_operations/update_placement.py delete mode 100644 examples/adxbuyer/v201406/campaign_management/__init__.py delete mode 100755 examples/adxbuyer/v201406/campaign_management/add_placements_in_bulk.py delete mode 100644 examples/adxbuyer/v201406/error_handling/__init__.py delete mode 100755 examples/adxbuyer/v201406/error_handling/handle_partial_failures.py delete mode 100644 examples/adxbuyer/v201406/optimization/__init__.py delete mode 100755 examples/adxbuyer/v201406/optimization/get_placement_ideas.py diff --git a/ChangeLog b/ChangeLog index 005d9385..408308d9 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +3.3.0 - 3/25/2015 +* Fixed issue #47. +* Removed support for AdWords v201406. +* Removed examples for AdWords v201406. + 3.2.0 - 3/12/2015 * Added support for v201502 of the AdWords Client Library. * Removed CampaignAdExtensionService (from v201502). diff --git a/README.md b/README.md index 5c557b96..4b198efa 100644 --- a/README.md +++ b/README.md @@ -127,5 +127,4 @@ suds_client.service.mutate([operation]) ##Authors: - Nicholas Chen - Mark Saniscalchi + jdilallo@google.com (Joseph DiLallo) diff --git a/examples/adwords/v201406/__init__.py b/examples/adwords/v201406/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/account_management/__init__.py b/examples/adwords/v201406/account_management/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/account_management/create_account.py b/examples/adwords/v201406/account_management/create_account.py deleted file mode 100755 index ce1e5d6b..00000000 --- a/examples/adwords/v201406/account_management/create_account.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/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. - -"""This example illustrates how to create an account. - -Note by default this account will only be accessible via parent MCC. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CreateAccountService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from datetime import datetime - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201406') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/account_management/get_account_alerts.py b/examples/adwords/v201406/account_management/get_account_alerts.py deleted file mode 100755 index 0fef7d71..00000000 --- a/examples/adwords/v201406/account_management/get_account_alerts.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/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. - -"""This example gets all alerts for all clients of an MCC account. - -This example assumes the email and password belong to an MCC. - -Note: this code example won't work with test accounts. See -https://developers.google.com/adwords/api/docs/test-accounts - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AlertService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - alert_service = client.GetService('AlertService', version='v201406') - - # Construct selector and get all alerts. - offset = 0 - selector = { - 'query': { - 'clientSpec': 'ALL', - 'filterSpec': 'ALL', - 'types': ['ACCOUNT_BUDGET_BURN_RATE', 'ACCOUNT_BUDGET_ENDING', - 'ACCOUNT_ON_TARGET', 'CAMPAIGN_ENDED', 'CAMPAIGN_ENDING', - 'CREDIT_CARD_EXPIRING', 'DECLINED_PAYMENT', - 'KEYWORD_BELOW_MIN_CPC', 'MANAGER_LINK_PENDING', - 'MISSING_BANK_REFERENCE_NUMBER', 'PAYMENT_NOT_ENTERED', - 'TV_ACCOUNT_BUDGET_ENDING', 'TV_ACCOUNT_ON_TARGET', - 'TV_ZERO_DAILY_SPENDING_LIMIT', 'USER_INVITE_ACCEPTED', - 'USER_INVITE_PENDING', 'ZERO_DAILY_SPENDING_LIMIT'], - 'severities': ['GREEN', 'YELLOW', 'RED'], - 'triggerTimeSpec': 'ALL_TIME' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = alert_service.get(selector) - # Display results. - if 'entries' in page: - for alert in page['entries']: - print ('Alert of type \'%s\' and severity \'%s\' for account \'%s\' was' - ' found.' % (alert['alertType'], alert['alertSeverity'], - alert['clientCustomerId'])) - else: - print 'No alerts were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/account_management/get_account_changes.py b/examples/adwords/v201406/account_management/get_account_changes.py deleted file mode 100755 index 66f5de64..00000000 --- a/examples/adwords/v201406/account_management/get_account_changes.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/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. - -"""This example gets the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CustomerSyncService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import datetime - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201406') - campaign_service = client.GetService('CampaignService', version='v201406') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - print ' Added ad extensions: %s' % data.get('addedAdExtensions') - print ' Removed ad extensions: %s' % data.get('deletedAdExtensions') - print (' Added campaign criteria: %s' - % data.get('addedCampaignCriteria')) - print (' Removed campaign criteria: %s' - % data.get('deletedCampaignCriteria')) - print (' Campaign targeting changed: %s' - % data.get('campaignTargetingChanged')) - if data.get('changedAdGroups'): - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - print ' Changed ads: %s' % ad_group_data['changedAds'] - print (' Changed criteria: %s' - % ad_group_data['changedCriteria']) - print (' Removed criteria: %s' - % ad_group_data['deletedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/account_management/get_account_hierarchy.py b/examples/adwords/v201406/account_management/get_account_hierarchy.py deleted file mode 100755 index a077c122..00000000 --- a/examples/adwords/v201406/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/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. - -"""This example gets the account hierarchy under the current account. - -Note: this code example won't work with test accounts. See -https://developers.google.com/adwords/api/docs/test-accounts - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ServicedAccountService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s, %s' % (prefix, account['login'], account['customerId'], - account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201406') - - # Construct selector to get all accounts. - selector = { - 'fields': ['Login', 'CustomerId', 'Name'] - } - # Get serviced account graph. - graph = managed_customer_service.get(selector) - if 'entries' in graph and graph['entries']: - # Create map from customerId to parent and child links. - child_links = {} - parent_links = {} - if 'links' in graph: - for link in graph['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Create map from customerID to account and find root account. - accounts = {} - root_account = None - for account in graph['entries']: - accounts[account['customerId']] = account - if account['customerId'] not in parent_links: - root_account = account - # Display account tree. - if root_account: - print 'Login, CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - else: - print 'No serviced accounts were found' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/advanced_operations/__init__.py b/examples/adwords/v201406/advanced_operations/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/advanced_operations/add_ad_customizer.py b/examples/adwords/v201406/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 53aa536c..00000000 --- a/examples/adwords/v201406/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,251 +0,0 @@ -#!/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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that -uses the feed to populate dynamic data. - -Tags: CustomerFeedService.mutate, FeedItemService.mutate -Tags: FeedMappingService.mutate, FeedService.mutate -Tags: AdGroupAdService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'yufeng.dev@gmail.com (Yufeng Guo)') - -# Import appropriate classes from the client library. -from googleads import adwords - -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_AD_CUSTOMIZER = '10' -PLACEHOLDER_FIELD_INTEGER = '1' -PLACEHOLDER_FIELD_FLOAT = '2' -PLACEHOLDER_FIELD_PRICE = '3' -PLACEHOLDER_FIELD_DATE = '4' -PLACEHOLDER_FIELD_STRING = '5' - -ADGROUPS = [ - 'INSERT_ADGROUP_ID_HERE', - 'INSERT_ADGROUP_ID_HERE' -] - -FEEDNAME = 'INSERT_FEED_NAME_HERE' - - -def main(client, adgroups): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201406') - feed_item_service = client.GetService('FeedItemService', version='v201406') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201406') - feed_service = client.GetService('FeedService', version='v201406') - - # First, create a customizer feed. One feed per account can be used for all - # ads. - customizer_feed = { - 'name': FEEDNAME, - 'attributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['id'], - 'nameId': feed['attributes'][0]['id'], - 'priceId': feed['attributes'][1]['id'], - 'dateId': feed['attributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['name'], feed['id'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - else: - raise Exception('No feeds were added') - - # Creating feed mapping to map the fields with customizer IDs. - feed_mapping = { - 'placeholderType': PLACEHOLDER_AD_CUSTOMIZER, - 'feedId': feed_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': feed_data['nameId'], - 'fieldId': PLACEHOLDER_FIELD_STRING - }, - { - 'feedAttributeId': feed_data['priceId'], - 'fieldId': PLACEHOLDER_FIELD_PRICE - }, - { - 'feedAttributeId': feed_data['dateId'], - 'fieldId': PLACEHOLDER_FIELD_DATE - } - ] - } - - feed_mapping_operation = { - 'operator': 'ADD', - 'operand': feed_mapping - } - - response = feed_mapping_service.mutate([feed_mapping_operation]) - - if response and 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.') % (feed_mapping['feedMappingId'], - feed_mapping['placeholderType'], - feed_mapping['feedId']) - else: - raise Exception('No feed mappings were added.') - - # Now adding feed items -- the values we'd like to place. - items_data = [ - { - 'name': 'Mars', - 'price': '$1234.56', - 'date': '20140601 000000', - 'adGroupId': adgroups[0] - }, - { - 'name': 'Venus', - 'price': '$1450.00', - 'date': '20140615 120000', - 'adGroupId': adgroups[1] - } - ] - - feed_items = [{'feedId': feed_data['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': item['adGroupId'] - }, - 'attributeValues': [ - { - 'feedAttributeId': feed_data['nameId'], - 'stringValue': item['name'] - }, - { - 'feedAttributeId': feed_data['priceId'], - 'stringValue': item['price'] - }, - { - 'feedAttributeId': feed_data['dateId'], - 'stringValue': item['date'] - } - ]} for item in items_data] - - feed_item_operations = [{ - 'operator': 'ADD', - 'operand': feed_item - } for feed_item in feed_items] - - response = feed_item_service.mutate(feed_item_operations) - - if response and 'value' in response: - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - else: - raise Exception('No feed items were added.') - - # Finally, creating a customer (account-level) feed with a matching function - # that determines when to use this feed. For this case we use the "IDENTITY" - # matching function that is always 'true' just to associate this feed with - # the customer. The targeting is done within the feed items using the - # :campaign_targeting, :ad_group_targeting, or :keyword_targeting attributes. - matching_function = { - 'operator': 'IDENTITY', - 'lhsOperand': [ - { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': 'true' - } - ] - } - - customer_feed = { - 'feedId': feed_data['feedId'], - 'matchingFunction': matching_function, - 'placeholderTypes': [PLACEHOLDER_AD_CUSTOMIZER] - } - - customer_feed_operation = { - 'operator': 'ADD', - 'operand': customer_feed - } - - response = customer_feed_service.mutate([customer_feed_operation]) - - if response and 'value' in response: - feed = response['value'][0] - print 'Customer feed with ID %s was added.' % feed['feedId'] - else: - raise Exception('No customer feeds were added.') - - # All set! We can now create ads with customizations. - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % FEEDNAME, - 'description1': 'Only {=%s.Price}' % FEEDNAME, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % FEEDNAME, - 'url': 'http://www.example.com', - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroups] - - print operations - - response = ad_group_ad_service.mutate(operations) - - print '===ad group ad service===' - print response - - if response and 'value' in response: - for ad in response['value']: - print ('\tCreated an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise Exception('No ads were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201406/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201406/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 2b7f40f6..00000000 --- a/examples/adwords/v201406/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupBidModifierService.mutate -""" - -__author__ = 'Joseph DiLallo' - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201406') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201406/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201406/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 1eb5d81f..00000000 --- a/examples/adwords/v201406/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/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. - -"""This code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Joseph DiLallo' - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'url': ('http://play.google.com/store/apps/details?' - 'id=com.example.demogame'), - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad to ad group ID \'%s\' ' - 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['url'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/advanced_operations/add_google_my_business_location_extensions.py b/examples/adwords/v201406/advanced_operations/add_google_my_business_location_extensions.py deleted file mode 100755 index 07e1e11c..00000000 --- a/examples/adwords/v201406/advanced_operations/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CustomerFeedService.mutate, FeedService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' -# To obtain an access token for your Places account, you can run the -# generate_refresh_token.py example and manually replace the scope with -# "https://www.google.com/local/add". -GMB_ACCESS_TOKEN = 'INSERT_GMB_OAUTH_ACCESS_TOKEN_HERE' - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'Places feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.google.com/local/add', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201406').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'FunctionArgumentOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201406') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN) diff --git a/examples/adwords/v201406/advanced_operations/add_site_links.py b/examples/adwords/v201406/advanced_operations/add_site_links.py deleted file mode 100755 index fe3e52ea..00000000 --- a/examples/adwords/v201406/advanced_operations/add_site_links.py +++ /dev/null @@ -1,261 +0,0 @@ -#!/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. - -"""This example adds a sitelinks feed and associates it with a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignFeedService.mutate, FeedItemService.mutate -Tags: FeedMappingService.mutate, FeedService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Joseph DiLallo' - -import uuid - -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_URL = '2' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201406') - feed_item_service = client.GetService('FeedItemService', version='v201406') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201406') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201406') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL', 'name': 'Link URL'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - link_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, link_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['linkUrlFeedId'] = link_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'url': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'url': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'url': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'url': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'url': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About', 'url': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2'} - ] - - feed_items = [] - for item in items_data: - feed_items.append({ - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['linkUrlFeedId'], - 'stringValue': item['url'] - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - - # Optional: use the 'scheduling' key to specify time and days of the - # week for feed to deliver. This is a Beta feature. - }) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['linkUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_URL - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Create site links campaign feed. - operands = [] - for feed_item_id in sitelinks_data['feedItemIds']: - operands.append({ - 'xsi_type': 'ConstantOperand', - 'type': 'LONG', - 'longValue': feed_item_id - }) - - feed_item_function = { - 'operator': 'IN', - 'lhsOperand': [ - {'xsi_type': 'RequestContextOperand', 'contextType': 'FEED_ITEM_ID'} - ], - 'rhsOperand': operands - } - - # Optional: to target to a platform, define a function and 'AND' it with the - # feed item ID link: - platform_function = { - 'operator': 'EQUALS', - 'lhsOperand': [ - { - 'xsi_type': 'RequestContextOperand', - 'contextType': 'DEVICE_PLATFORM' - } - ], - 'rhsOperand': [ - { - 'xsi_type': 'ConstantOperand', - 'type': 'STRING', - 'stringValue': 'Mobile' - } - ] - } - combined_function = { - 'operator': 'AND', - 'lhsOperand': [ - {'xsi_type': 'FunctionOperand', 'value': feed_item_function}, - {'xsi_type': 'FunctionOperand', 'value': platform_function} - ] - } - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': combined_function, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201406/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index c5e7dd94..00000000 --- a/examples/adwords/v201406/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/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. - -"""This examples adds a text add that uses upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = 'Mark Saniscalchi' - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201406/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201406/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 705108e3..00000000 --- a/examples/adwords/v201406/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupBidModifierService.get -""" - -__author__ = 'Joseph DiLallo' - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201406') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/advanced_operations/update_site_links.py b/examples/adwords/v201406/advanced_operations/update_site_links.py deleted file mode 100755 index f4439e1e..00000000 --- a/examples/adwords/v201406/advanced_operations/update_site_links.py +++ /dev/null @@ -1,168 +0,0 @@ -#!/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. - -"""This example updates an existing sitelinks feed. - -Specifically, it does the following: - * Adds FeedItemAttributes for line 1 and line 2 descriptions to the Feed - * Populates the new FeedItemAttributes on FeedItems in the Feed - * Replaces the Feed's existing FeedMapping with one that contains the new - set of FeedItemAttributes - -The end result of this is that any campaign or ad group whose CampaignFeed -or AdGroupFeed points to the Feed's ID will now serve line 1 and line 2 -descriptions in its sitelinks. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: FeedItemService.mutate -Tags: FeedMappingService.mutate, FeedService.mutate -""" - -__author__ = 'Joseph DiLallo' - -from googleads import adwords - -FEED_ID = 'FEED_ID' -FEED_ITEM_DESCRIPTIONS = { - 'INSERT_FEED_ITEM_A_ID_HERE': [ - 'INSERT_FEED_ITEM_A_LINE1_DESC_HERE', - 'INSERT_FEED_ITEM_A_LINE2_DESC_HERE' - ], - 'INSERT_FEED_ITEM_B_ID_HERE': [ - 'INSERT_FEED_ITEM_B_LINE1_DESC_HERE', - 'INSERT_FEED_ITEM_B_LINE2_DESC_HERE' - ] -} - -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_FIELD_LINE_1_TEXT = 3 -PLACEHOLDER_FIELD_LINE_2_TEXT = 4 - - -def main(client, feed_id, feed_item_descriptions): - feed_service = client.GetService('FeedService', 'v201406') - feed_item_service = client.GetService('FeedItemService', 'v201406') - feed_mapping_service = client.GetService('FeedMappingService', 'v201406') - - feed_selector = { - 'fields': ['Id', 'Attributes'], - 'predicates': [ - {'field': 'Id', 'operator': 'EQUALS', 'values': [feed_id]} - ] - } - - feed = feed_service.get(feed_selector)['entries'][0] - - # Add new line1 and line2 feed attributes. - next_attribute_index = len(feed['attributes']) - - feed['attributes'] = [ - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - - mutated_feed_result = feed_service.mutate([ - {'operator': 'SET', 'operand': feed} - ]) - - mutated_feed = mutated_feed_result['value'][0] - line_1_attribute = mutated_feed['attributes'][next_attribute_index] - line_2_attribute = mutated_feed['attributes'][next_attribute_index + 1] - - # Update feed items. - feed_item_ids = feed_item_descriptions.keys() - item_selector = { - 'fields': ['FeedId', 'FeedItemId', 'AttributeValues'], - 'predicates': [ - {'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed_id]}, - {'field': 'FeedItemId', 'operator': 'IN', 'values': feed_item_ids} - ] - } - - feed_items = feed_item_service.get(item_selector)['entries'] - - item_operations = [] - for feed_item in feed_items: - feed_item['attributeValues'] = [ - { - 'feedAttributeId': line_1_attribute['id'], - 'stringValue': feed_item_descriptions[feed_item['feedItemId']][0] - }, - { - 'feedAttributeId': line_2_attribute['id'], - 'stringValue': feed_item_descriptions[feed_item['feedItemId']][1] - } - ] - - item_operations.append({'operator': 'SET', 'operand': feed_item}) - - items_update_result = feed_item_service.mutate(item_operations) - print 'Updated %d items' % len(items_update_result['value']) - - # Update feed mapping. - mapping_selector = { - 'fields': [ - 'FeedId', - 'FeedMappingId', - 'PlaceholderType', - 'AttributeFieldMappings' - ], - 'predicates': [ - {'field': 'FeedId', 'operator': 'EQUALS', 'values': [feed_id]} - ] - } - feed_mapping_results = feed_mapping_service.get(mapping_selector) - feed_mapping = feed_mapping_results['entries'][0] - - # Feed mappings are immutable, so we have to delete it and re-add - # it with modifications. - feed_mapping = feed_mapping_service.mutate([ - {'operator': 'REMOVE', 'operand': feed_mapping} - ])['value'][0] - - feed_mapping['attributeFieldMappings'].push( - { - 'feedAttributeId': line_1_attribute['id'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': line_2_attribute['id'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ) - mapping_update_result = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - - mutated_mapping = mapping_update_result['value'][0] - print ('Updated field mappings for feedId %d and feedMappingId %d to:' % - (mutated_mapping['feedId'], mutated_mapping['feedMappingId'])) - for field_mapping in mutated_mapping['attributeFieldMappings']: - print ('\tfeedAttributeId %d --> fieldId %d' % - (field_mapping['feedAttributeId'], field_mapping['fieldId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, FEED_ID, FEED_ITEM_DESCRIPTIONS) diff --git a/examples/adwords/v201406/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201406/advanced_operations/upload_offline_conversions.py deleted file mode 100755 index 0a21d330..00000000 --- a/examples/adwords/v201406/advanced_operations/upload_offline_conversions.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ConversionTrackerService.mutate, OfflineConversionFeedService.mutate -""" - -__author__ = 'Joseph DiLallo' - -from googleads import adwords - - -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - conversion_tracker_service = client.GetService('ConversionTrackerService', - version='v201406') - - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201406') - - # Once created, this entry will be visible under - # Tools and Analysis->Conversion and will have "Source = Import". - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'category': 'PAGE_VIEW', - 'name': conversion_name, - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90' - } - - upload_conversion_operation = { - 'operator': 'ADD', - 'operand': upload_conversion - } - - response = conversion_tracker_service.mutate( - [upload_conversion_operation]) - new_upload_conversion = response['value'] - - print ('New upload conversion type with name \'%s\' and ID \'%s\' was ' - 'created.' % (new_upload_conversion['name'], - new_upload_conversion['id'])) - - # Associate offline conversions with the upload conversion we created. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201406/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201406/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 377c7fee..00000000 --- a/examples/adwords/v201406/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: BiddingStrategyService.mutate -Tags: BudgetService.mutate, CampaignService.mutate -""" - -__author__ = 'Joseph DiLallo' - -import uuid - -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201406') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201406') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'period': 'DAILY', - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201406') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'settings': [{ - 'xsi_type': 'KeywordMatchSetting', - 'optIn': 'true' - }], - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201406/basic_operations/__init__.py b/examples/adwords/v201406/basic_operations/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/basic_operations/add_ad_groups.py b/examples/adwords/v201406/basic_operations/add_ad_groups.py deleted file mode 100755 index 4c7e95b4..00000000 --- a/examples/adwords/v201406/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/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. - -"""This example adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README.. - -Tags: AdGroupService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import uuid - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201406') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings - these settings only affect - # serving for the Display Network. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/basic_operations/add_campaigns.py b/examples/adwords/v201406/basic_operations/add_campaigns.py deleted file mode 100755 index 6c5547fd..00000000 --- a/examples/adwords/v201406/basic_operations/add_campaigns.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/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. - -"""This example adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -Tags: BudgetService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import datetime -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201406') - budget_service = client.GetService('BudgetService', version='v201406') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - }, - { - 'xsi_type': 'KeywordMatchSetting', - 'optIn': 'false' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY', - 'settings': [ - { - 'xsi_type': 'KeywordMatchSetting', - 'optIn': 'false' - } - ] - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/basic_operations/add_keywords.py b/examples/adwords/v201406/basic_operations/add_keywords.py deleted file mode 100755 index f510e8cf..00000000 --- a/examples/adwords/v201406/basic_operations/add_keywords.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/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. - -"""This example adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'destinationUrl': 'http://example.com/mars' - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/basic_operations/add_text_ads.py b/examples/adwords/v201406/basic_operations/add_text_ads.py deleted file mode 100755 index 036e0149..00000000 --- a/examples/adwords/v201406/basic_operations/add_text_ads.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/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. - -"""This example adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/basic_operations/get_ad_groups.py b/examples/adwords/v201406/basic_operations/get_ad_groups.py deleted file mode 100755 index a2a1f822..00000000 --- a/examples/adwords/v201406/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/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. - -"""This example gets all ad groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201406') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/basic_operations/get_campaigns.py b/examples/adwords/v201406/basic_operations/get_campaigns.py deleted file mode 100755 index 9bbf338e..00000000 --- a/examples/adwords/v201406/basic_operations/get_campaigns.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/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. - -"""This example gets all campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.get -""" - -__author__ = 'Joseph DiLallo' - -import logging -import time - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201406') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201406/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 4bb219f9..00000000 --- a/examples/adwords/v201406/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/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. - -"""This example gets all campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.query -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import time - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201406') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/basic_operations/get_keywords.py b/examples/adwords/v201406/basic_operations/get_keywords.py deleted file mode 100755 index 492af1dd..00000000 --- a/examples/adwords/v201406/basic_operations/get_keywords.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/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. - -"""This example gets all ad group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['AdGroupId', 'Id', 'Text', 'KeywordMatchType', 'PlacementUrl'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for criterion in page['entries']: - print ('Keyword ad group criterion with ad group id \'%s\', criterion ' - 'id \'%s\', text \'%s\', and match type \'%s\' was found.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/basic_operations/get_text_ads.py b/examples/adwords/v201406/basic_operations/get_text_ads.py deleted file mode 100755 index 11986346..00000000 --- a/examples/adwords/v201406/basic_operations/get_text_ads.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/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. - -"""This example gets all text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/basic_operations/pause_ad.py b/examples/adwords/v201406/basic_operations/pause_ad.py deleted file mode 100755 index 3b9b9c5a..00000000 --- a/examples/adwords/v201406/basic_operations/pause_ad.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/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. - -"""This example updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201406/basic_operations/remove_ad.py b/examples/adwords/v201406/basic_operations/remove_ad.py deleted file mode 100755 index 722ccc6b..00000000 --- a/examples/adwords/v201406/basic_operations/remove_ad.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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. - -"""This example deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201406/basic_operations/remove_ad_group.py b/examples/adwords/v201406/basic_operations/remove_ad_group.py deleted file mode 100755 index cd126cb3..00000000 --- a/examples/adwords/v201406/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""This example deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201406') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/basic_operations/remove_campaign.py b/examples/adwords/v201406/basic_operations/remove_campaign.py deleted file mode 100755 index 3243e86a..00000000 --- a/examples/adwords/v201406/basic_operations/remove_campaign.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""This example deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201406') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/basic_operations/remove_keyword.py b/examples/adwords/v201406/basic_operations/remove_keyword.py deleted file mode 100755 index 23f94eb5..00000000 --- a/examples/adwords/v201406/basic_operations/remove_keyword.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/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. - -"""This example deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201406/basic_operations/update_ad_group.py b/examples/adwords/v201406/basic_operations/update_ad_group.py deleted file mode 100755 index 4893d505..00000000 --- a/examples/adwords/v201406/basic_operations/update_ad_group.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""This example updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201406') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/basic_operations/update_campaign.py b/examples/adwords/v201406/basic_operations/update_campaign.py deleted file mode 100755 index f93143e3..00000000 --- a/examples/adwords/v201406/basic_operations/update_campaign.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""This example updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201406') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/basic_operations/update_keyword.py b/examples/adwords/v201406/basic_operations/update_keyword.py deleted file mode 100755 index c6b2e5ab..00000000 --- a/examples/adwords/v201406/basic_operations/update_keyword.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/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. - -"""This example updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201406/campaign_management/__init__.py b/examples/adwords/v201406/campaign_management/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/campaign_management/add_campaign_labels.py b/examples/adwords/v201406/campaign_management/add_campaign_labels.py deleted file mode 100755 index cfc87dd2..00000000 --- a/examples/adwords/v201406/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/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. - -"""This example adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutateLabel -""" - -__author__ = 'Mark Saniscalchi' - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201406') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201406/campaign_management/add_experiment.py b/examples/adwords/v201406/campaign_management/add_experiment.py deleted file mode 100755 index 51975763..00000000 --- a/examples/adwords/v201406/campaign_management/add_experiment.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/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. - -"""This example creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ExperimentService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import datetime -import uuid - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201406') - ad_group_service = client.GetService('AdGroupService', version='v201406') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201406/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201406/campaign_management/add_keywords_in_bulk.py deleted file mode 100755 index e4ddc91b..00000000 --- a/examples/adwords/v201406/campaign_management/add_keywords_in_bulk.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/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. - -"""This code sample illustrates how to perform asynchronous requests. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: MutateJobService.mutate -Tags: MutateJobService.get -Tags: MutateJobService.getResult -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import random -import re -import time - -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -KEYWORD_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201406') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add keywords. - for i in range(KEYWORD_NUMBER): - keyword = 'mars%d' % i - if random.randint(1, 10) == 1: - keyword += '!!!' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': keyword - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - keyword = operations[index]['operand']['criterion']['text'] - print ('ERROR - keyword \'%s\' failed due to \'%s\'' % - (keyword, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/campaign_management/add_location_extension.py b/examples/adwords/v201406/campaign_management/add_location_extension.py deleted file mode 100755 index 96b2a4df..00000000 --- a/examples/adwords/v201406/campaign_management/add_location_extension.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -*- coding: UTF-8 -*- -# -# 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. - -"""This example adds a campaign ad extension to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: GeoLocationService.get, CampaignAdExtensionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - geo_location_service = client.GetService( - 'GeoLocationService', version='v201406') - campaign_ad_extension_service = client.GetService( - 'CampaignAdExtensionService', version='v201406') - - # Construct selector and get geo location info for given addresses. - selector = { - 'addresses': [ - { - 'streetAddress': '1600 Amphitheatre Parkway', - 'cityName': 'Mountain View', - 'provinceCode': 'US-CA', - 'provinceName': 'California', - 'postalCode': '94043', - 'countryCode': 'US' - }, - { - 'streetAddress': u'38 avenue de l\'Opéra', - 'cityName': 'Paris', - 'postalCode': '75002', - 'countryCode': 'FR' - } - ] - } - geo_locations = geo_location_service.get(selector) - - # Construct operations and add campaign ad extension. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'CampaignAdExtension', - 'campaignId': campaign_id, - 'adExtension': { - 'xsi_type': 'LocationExtension', - 'address': geo_locations[0]['address'], - 'geoPoint': geo_locations[0]['geoPoint'], - 'encodedLocation': geo_locations[0]['encodedLocation'], - 'source': 'ADWORDS_FRONTEND', - # Optional fields. - 'companyName': 'ACME Inc.', - 'phoneNumber': '(650) 253-0000' - } - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'CampaignAdExtension', - 'campaignId': campaign_id, - 'adExtension': { - 'xsi_type': 'LocationExtension', - 'address': geo_locations[1]['address'], - 'geoPoint': geo_locations[1]['geoPoint'], - 'encodedLocation': geo_locations[1]['encodedLocation'], - 'source': 'ADWORDS_FRONTEND' - } - } - } - ] - ad_extensions = campaign_ad_extension_service.mutate(operations) - - # Display results. - for ad_extension in ad_extensions['value']: - print ('Campaign ad extension with id \'%s\' and status \'%s\' was added.' - % (ad_extension['adExtension']['id'], ad_extension['status'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201406/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index bad1d446..00000000 --- a/examples/adwords/v201406/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/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. - -"""This example gets all disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201406/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 925864be..00000000 --- a/examples/adwords/v201406/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/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. - -"""This example gets all disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201406/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 53938687..00000000 --- a/examples/adwords/v201406/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/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. - -"""This example gets all campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.get -""" - -__author__ = 'Mark Saniscalchi' - -import time - -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201406') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201406/campaign_management/promote_experiment.py b/examples/adwords/v201406/campaign_management/promote_experiment.py deleted file mode 100755 index d74e24c0..00000000 --- a/examples/adwords/v201406/campaign_management/promote_experiment.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/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. - -"""This example promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ExperimentService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201406') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201406/campaign_management/set_ad_parameters.py b/examples/adwords/v201406/campaign_management/set_ad_parameters.py deleted file mode 100755 index 01ca3178..00000000 --- a/examples/adwords/v201406/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# 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. - -"""This example adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate, AdParamService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - ad_param_service = client.GetService('AdParamService', version='v201406') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201406/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201406/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index 29c790d6..00000000 --- a/examples/adwords/v201406/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/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. - -"""This example sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.mutate -""" - -__author__ = ('api.dklimkin@gmail.com (Danial Klimkin)', - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201406') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201406/campaign_management/validate_text_ad.py b/examples/adwords/v201406/campaign_management/validate_text_ad.py deleted file mode 100755 index cadcd25c..00000000 --- a/examples/adwords/v201406/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/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. - -"""This example shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/error_handling/__init__.py b/examples/adwords/v201406/error_handling/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/error_handling/handle_partial_failures.py b/examples/adwords/v201406/error_handling/handle_partial_failures.py deleted file mode 100755 index c801d34e..00000000 --- a/examples/adwords/v201406/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/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. - -"""This example demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import re - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/error_handling/handle_policy_violation_error.py b/examples/adwords/v201406/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 8fe69907..00000000 --- a/examples/adwords/v201406/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/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. - -"""This example demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = 'Joseph DiLallo' - -import re - -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201406') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'url': 'http://www.example.com', - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - operation = operations[int(operation_index[0])] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) - else: - # Non-policy error returned, re-throw exception. - raise e - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/misc/__init__.py b/examples/adwords/v201406/misc/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/misc/get_all_images_and_videos.py b/examples/adwords/v201406/misc/get_all_images_and_videos.py deleted file mode 100755 index 831e76b6..00000000 --- a/examples/adwords/v201406/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/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. - -"""This example gets all images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: MediaService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201406') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - print ('Media with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], image['mimeType'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/misc/upload_image.py b/examples/adwords/v201406/misc/upload_image.py deleted file mode 100755 index 53d9810b..00000000 --- a/examples/adwords/v201406/misc/upload_image.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/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. - -"""This example uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: MediaService.upload -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import base64 - -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201406') - - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201406/optimization/__init__.py b/examples/adwords/v201406/optimization/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/optimization/estimate_keyword_traffic.py b/examples/adwords/v201406/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 49540b23..00000000 --- a/examples/adwords/v201406/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/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. - -"""This example retrieves keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: TrafficEstimatorService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201406') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - selector = { - 'campaignEstimateRequests': [{ - 'adGroupEstimateRequests': [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }], - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ] - }] - } - estimates = traffic_estimator_service.get(selector) - - # Display results. - ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] - keyword_estimates = ad_group_estimate['keywordEstimates'] - for index in xrange(len(keyword_estimates)): - keyword = keyword_estimate_requests[index]['keyword'] - estimate = keyword_estimates[index] - if keyword_estimate_requests[index].get('isNegative', False): - continue - - # Find the mean of the min and max values. - mean_avg_cpc = (long(estimate['min']['averageCpc']['microAmount']) + - long(estimate['max']['averageCpc']['microAmount'])) / 2 - mean_avg_pos = (float(estimate['min']['averagePosition']) + - float(estimate['max']['averagePosition'])) / 2 - mean_clicks = (float(estimate['min']['clicksPerDay']) + - float(estimate['max']['clicksPerDay'])) / 2 - mean_total_cost = (long(estimate['min']['totalCost']['microAmount']) + - long(estimate['max']['totalCost']['microAmount'])) / 2 - - print ('Results for the keyword with text \'%s\' and match type \'%s\':' - % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % mean_avg_cpc - print ' Estimated ad position: %s' % mean_avg_pos - print ' Estimated daily clicks: %s' % mean_clicks - print ' Estimated daily cost: %s' % mean_total_cost - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201406/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index 9842789e..00000000 --- a/examples/adwords/v201406/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/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. - -"""This example gets a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: BidLandscapeService.getBidLandscape -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201406') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'MarginalCpc', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, marginalCpc: %s, ' - 'impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['marginalCpc']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201406/optimization/get_keyword_ideas.py b/examples/adwords/v201406/optimization/get_keyword_ideas.py deleted file mode 100755 index a21567b2..00000000 --- a/examples/adwords/v201406/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/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. - -"""This example retrieves keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: TargetingIdeaService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201406') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = attribute['value'] - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/optimization/get_placement_ideas.py b/examples/adwords/v201406/optimization/get_placement_ideas.py deleted file mode 100755 index 9ee071ac..00000000 --- a/examples/adwords/v201406/optimization/get_placement_ideas.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/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 urls that have content keywords related to a given website. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: TargetingIdeaService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201406') - - # Construct selector object and retrieve related placements. - offset = 0 - url = 'http://mars.google.com' - selector = { - 'searchParameters': [{ - 'xsi_type': 'RelatedToUrlSearchParameter', - 'urls': [url], - 'includeSubUrls': 'false' - }], - 'ideaType': 'PLACEMENT', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['SAMPLE_URL'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - result = result['data'][0]['value'] - print 'Related content keywords were found at \'%s\' url.' % result - print - print ('Total urls found with content keywords related to keywords at ' - '\'%s\': %s' % (url, page['totalNumEntries'])) - else: - print 'No content keywords were found at \'%s\'.' % url - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/remarketing/__init__.py b/examples/adwords/v201406/remarketing/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/remarketing/add_audience.py b/examples/adwords/v201406/remarketing/add_audience.py deleted file mode 100755 index cb947c1b..00000000 --- a/examples/adwords/v201406/remarketing/add_audience.py +++ /dev/null @@ -1,107 +0,0 @@ -#!/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. - -"""This example adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: UserListService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201406') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201406') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/remarketing/add_conversion_tracker.py b/examples/adwords/v201406/remarketing/add_conversion_tracker.py deleted file mode 100755 index 1c1f5269..00000000 --- a/examples/adwords/v201406/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/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. - -"""This example adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ConversionTrackerService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201406') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'markupLanguage': 'HTML', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'isProductAdsChargeable': 'true', - 'productAdsChargeableConversionWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/reporting/__init__.py b/examples/adwords/v201406/reporting/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/reporting/download_criteria_report.py b/examples/adwords/v201406/reporting/download_criteria_report.py deleted file mode 100755 index 6bb30cc6..00000000 --- a/examples/adwords/v201406/reporting/download_criteria_report.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Joseph DiLallo' - -import logging -import sys - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201406') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport(report, sys.stdout) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201406/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index 8105415d..00000000 --- a/examples/adwords/v201406/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/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. - -"""This example retrieves the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Mark Saniscalchi' - -import logging -import sys - -from googleads import adwords -import StringIO - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201406') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream(report) - - try: - while True: - chunk = stream_data.read(adwords.CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201406/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index ee9a33fe..00000000 --- a/examples/adwords/v201406/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import logging -import sys - -from googleads import adwords -import StringIO - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201406') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV') - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(adwords.CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/reporting/download_criteria_report_as_string.py b/examples/adwords/v201406/reporting/download_criteria_report_as_string.py deleted file mode 100755 index 0b494d15..00000000 --- a/examples/adwords/v201406/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Mark Saniscalchi' - -import logging -import sys - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201406') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString(report) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201406/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201406/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index e02e8115..00000000 --- a/examples/adwords/v201406/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201406') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201406/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 7a8937df..00000000 --- a/examples/adwords/v201406/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201406') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql(report_query, 'CSV', output_file) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201406/reporting/get_report_fields.py b/examples/adwords/v201406/reporting/get_report_fields.py deleted file mode 100755 index 0595cafe..00000000 --- a/examples/adwords/v201406/reporting/get_report_fields.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/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. - -"""This example gets report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.getReportFields -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201406') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201406/shopping/add_product_partition_tree.py b/examples/adwords/v201406/shopping/add_product_partition_tree.py deleted file mode 100755 index d885ae36..00000000 --- a/examples/adwords/v201406/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,285 +0,0 @@ -#!/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. - -"""This example creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) - diff --git a/examples/adwords/v201406/shopping/add_product_scope.py b/examples/adwords/v201406/shopping/add_product_scope.py deleted file mode 100755 index e9b3bb14..00000000 --- a/examples/adwords/v201406/shopping/add_product_scope.py +++ /dev/null @@ -1,107 +0,0 @@ -#!/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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201406') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/shopping/add_shopping_campaign.py b/examples/adwords/v201406/shopping/add_shopping_campaign.py deleted file mode 100755 index 44c6cc44..00000000 --- a/examples/adwords/v201406/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/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. - -"""This example adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate, AdGroupService.mutate, AdGroupAdService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201406') - ad_group_service = client.GetService('AdGroupService', version='v201406') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set shared budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # Set keyword matching setting (required) - { - 'xsi_type': 'KeywordMatchSetting', - 'optIn': 'false' - }, - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201406/shopping/get_product_category_taxonomy.py b/examples/adwords/v201406/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 47e27963..00000000 --- a/examples/adwords/v201406/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/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. - -"""This example fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ConstantDataService.getProductBiddingCategoryData -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201406') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/shopping/set_product_sales_channel.py b/examples/adwords/v201406/shopping/set_product_sales_channel.py deleted file mode 100755 index 245fa722..00000000 --- a/examples/adwords/v201406/shopping/set_product_sales_channel.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/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. - -"""This example sets the product sales channel. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - -# ProductSalesChannel is a fixedId criterion, with the possible values -# defined here. -ONLINE = '200' -LOCAL = '201' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201406') - - product_sales_channel = { - 'xsi_type': 'ProductSalesChannel', - 'id': ONLINE - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_sales_channel - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Added ProductSalesChannel CampaignCriterion with ID: %s' - % (criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/targeting/__init__.py b/examples/adwords/v201406/targeting/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201406/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201406/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 538b5661..00000000 --- a/examples/adwords/v201406/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/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. - -"""This example adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201406') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - florida_downtown = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'PlacesOfInterestOperand', - # Other valid options: AIRPORT, UNIVERSITY. - 'category': 'DOWNTOWN', - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - } - } - # Distance targeting. Area of 10 miles around targets above. - distance_10_miles = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - - }] - } - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - - # Create operations - operations = [] - for criterion in [california, mexico, english, spanish, florida_tier3, - florida_downtown, distance_10_miles]: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201406/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201406/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 77b77b29..00000000 --- a/examples/adwords/v201406/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/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. - -"""This example adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = 'Joseph Dilallo' - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201406/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201406/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index e1ea10c0..00000000 --- a/examples/adwords/v201406/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/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. - -"""This example illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201406') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201406/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index a22c345b..00000000 --- a/examples/adwords/v201406/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ConstantDataService.getLanguageCriterion -Tags: ConstantDataService.getCarrierCriterion -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201406') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201406/targeting/lookup_location.py b/examples/adwords/v201406/targeting/lookup_location.py deleted file mode 100755 index a49d2055..00000000 --- a/examples/adwords/v201406/targeting/lookup_location.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/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. - -"""This example gets all LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: LocationCriterionService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201406') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/advanced_operations/add_ad_customizer.py b/examples/adwords/v201409/advanced_operations/add_ad_customizer.py index c2ad3b64..41042287 100755 --- a/examples/adwords/v201409/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201409/advanced_operations/add_ad_customizer.py @@ -41,8 +41,8 @@ PLACEHOLDER_FIELD_STRING = '5' ADGROUPS = [ - 'INSERT_ADGROUP_ID_HERE', - 'INSERT_ADGROUP_ID_HERE' + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' ] FEEDNAME = 'INSERT_FEED_NAME_HERE' diff --git a/examples/adwords/v201409/migration/migrate_to_extension_settings.py b/examples/adwords/v201409/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..9b76ebd2 --- /dev/null +++ b/examples/adwords/v201409/migration/migrate_to_extension_settings.py @@ -0,0 +1,528 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: FeedService.get, FeedMappingService.get, FeedItemService.get +Tags: CampaignExtensionSettingService.mutate, CampaignFeedService.get, +Tags: CampaignFeedService.mutate +Api: AdWordsOnly +""" + +__author__ = 'Mark Saniscalchi' + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201409') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201409') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201409') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201409') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201409') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201409') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + if ('lhsOperand' in campaign_feed['matchingFunction'] and + campaign_feed['matchingFunction']['lhsOperand'][0]['xsi_type'] == + 'RequestContextOperand'): + request_context_operand = campaign_feed['matchingFunction']['lhsOperand'][0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201409') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings['attributeValue']['feedAttributeId']: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py index 62dccee1..88ef3f8b 100755 --- a/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py @@ -38,6 +38,9 @@ logging.basicConfig(level=logging.INFO) logging.getLogger('suds.transport').setLevel(logging.DEBUG) +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + def main(client): report_downloader = client.GetReportDownloader(version='v201409') @@ -62,7 +65,7 @@ def main(client): try: while True: - chunk = stream_data.read(adwords.CHUNK_SIZE) + chunk = stream_data.read(CHUNK_SIZE) if not chunk: break report_data.write(chunk.decode() if sys.version_info[0] == 3 and getattr(report_data, 'mode', 'w') == 'w' else chunk) diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py index d0151e8c..ad854202 100755 --- a/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py @@ -43,6 +43,8 @@ # Specify where to download the file here. PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 def main(client): @@ -65,7 +67,7 @@ def main(client): try: while True: - chunk = stream_data.read(adwords.CHUNK_SIZE) + chunk = stream_data.read(CHUNK_SIZE) if not chunk: break report_data.write(chunk.decode() if sys.version_info[0] == 3 and getattr(report_data, 'mode', 'w') == 'w' else chunk) diff --git a/examples/adwords/v201502/advanced_operations/add_ad_customizer.py b/examples/adwords/v201502/advanced_operations/add_ad_customizer.py index 09282e58..1c85f1fd 100755 --- a/examples/adwords/v201502/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201502/advanced_operations/add_ad_customizer.py @@ -16,53 +16,89 @@ """Adds an ad customizer feed. -Associates the feed with customer and adds an ad that -uses the feed to populate dynamic data. +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. -Tags: CustomerFeedService.mutate, FeedItemService.mutate -Tags: FeedMappingService.mutate, FeedService.mutate -Tags: AdGroupAdService.mutate +Tags: AdCustomizerFeedService.mutate, AdGroupAdService.mutate +Tags: FeedItemService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'yufeng.dev@gmail.com (Yufeng Guo)') +__author__ = 'api.msaniscalchi@gmail.com (Mark Saniscalchi)' + +from datetime import datetime +from uuid import uuid4 # Import appropriate classes from the client library. from googleads import adwords +from googleads import errors -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_AD_CUSTOMIZER = '10' -PLACEHOLDER_FIELD_INTEGER = '1' -PLACEHOLDER_FIELD_FLOAT = '2' -PLACEHOLDER_FIELD_PRICE = '3' -PLACEHOLDER_FIELD_DATE = '4' -PLACEHOLDER_FIELD_STRING = '5' +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() ADGROUPS = [ - 'INSERT_ADGROUP_ID_HERE', - 'INSERT_ADGROUP_ID_HERE' + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' ] -FEEDNAME = 'INSERT_FEED_NAME_HERE' +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates TextAds that use ad customizations for the specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add TextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no TextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService') + + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'description1': 'Only {=%s.Price}' % feed_name, + 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com' + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. -def main(client, adgroups): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201502') - feed_item_service = client.GetService('FeedItemService', version='v201502') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201502') - feed_service = client.GetService('FeedService', version='v201502') + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') - # First, create a customizer feed. One feed per account can be used for all - # ads. customizer_feed = { - 'name': FEEDNAME, - 'attributes': [ + 'feedName': feed_name, + 'feedAttributes': [ {'type': 'STRING', 'name': 'Name'}, {'type': 'STRING', 'name': 'Price'}, {'type': 'DATE_TIME', 'name': 'Date'} @@ -74,175 +110,113 @@ def main(client, adgroups): 'operand': customizer_feed } - response = feed_service.mutate([feed_service_operation]) + response = ad_customizer_feed_service.mutate([feed_service_operation]) if response and 'value' in response: feed = response['value'][0] feed_data = { - 'feedId': feed['id'], - 'nameId': feed['attributes'][0]['id'], - 'priceId': feed['attributes'][1]['id'], - 'dateId': feed['attributes'][2]['id'] + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] } - print ('Feed with name \'%s\' and ID %s was added with:' + print ('Feed with name \'%s\' and ID %s was added with:\n' '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['name'], feed['id'], feed_data['nameId'], + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], feed_data['priceId'], feed_data['dateId']) + return feed else: - raise Exception('No feeds were added') - - # Creating feed mapping to map the fields with customizer IDs. - feed_mapping = { - 'placeholderType': PLACEHOLDER_AD_CUSTOMIZER, - 'feedId': feed_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': feed_data['nameId'], - 'fieldId': PLACEHOLDER_FIELD_STRING - }, - { - 'feedAttributeId': feed_data['priceId'], - 'fieldId': PLACEHOLDER_FIELD_PRICE - }, - { - 'feedAttributeId': feed_data['dateId'], - 'fieldId': PLACEHOLDER_FIELD_DATE - } - ] - } - - feed_mapping_operation = { - 'operator': 'ADD', - 'operand': feed_mapping - } - - response = feed_mapping_service.mutate([feed_mapping_operation]) - - if response and 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.') % (feed_mapping['feedMappingId'], - feed_mapping['placeholderType'], - feed_mapping['feedId']) - else: - raise Exception('No feed mappings were added.') - - # Now adding feed items -- the values we'd like to place. - items_data = [ - { - 'name': 'Mars', - 'price': '$1234.56', - 'date': '20140601 000000', - 'adGroupId': adgroups[0] - }, - { - 'name': 'Venus', - 'price': '$1450.00', - 'date': '20140615 120000', - 'adGroupId': adgroups[1] - } + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) ] - feed_items = [{'feedId': feed_data['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': item['adGroupId'] - }, - 'attributeValues': [ - { - 'feedAttributeId': feed_data['nameId'], - 'stringValue': item['name'] - }, - { - 'feedAttributeId': feed_data['priceId'], - 'stringValue': item['price'] - }, - { - 'feedAttributeId': feed_data['dateId'], - 'stringValue': item['date'] - } - ]} for item in items_data] - - feed_item_operations = [{ - 'operator': 'ADD', - 'operand': feed_item - } for feed_item in feed_items] - response = feed_item_service.mutate(feed_item_operations) - if response and 'value' in response: + if 'value' in response: for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] else: - raise Exception('No feed items were added.') - - # Finally, creating a customer (account-level) feed with a matching function - # that determines when to use this feed. For this case we use the "IDENTITY" - # matching function that is always 'true' just to associate this feed with - # the customer. The targeting is done within the feed items using the - # :campaign_targeting, :ad_group_targeting, or :keyword_targeting attributes. - matching_function = { - 'operator': 'IDENTITY', - 'lhsOperand': [ + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': 'true' + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date } ] } - customer_feed = { - 'feedId': feed_data['feedId'], - 'matchingFunction': matching_function, - 'placeholderTypes': [PLACEHOLDER_AD_CUSTOMIZER] - } - - customer_feed_operation = { - 'operator': 'ADD', - 'operand': customer_feed - } - - response = customer_feed_service.mutate([customer_feed_operation]) + return {'operator': 'ADD', 'operand': feed_item} - if response and 'value' in response: - feed = response['value'][0] - print 'Customer feed with ID %s was added.' % feed['feedId'] - else: - raise Exception('No customer feeds were added.') +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) # All set! We can now create ads with customizations. - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % FEEDNAME, - 'description1': 'Only {=%s.Price}' % FEEDNAME, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % FEEDNAME, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroups] - - print operations - - response = ad_group_ad_service.mutate(operations) - - print '===ad group ad service===' - print response - - if response and 'value' in response: - for ad in response['value']: - print ('\tCreated an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise Exception('No ads were added.') + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) if __name__ == '__main__': diff --git a/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py index c4c46225..e366d28a 100755 --- a/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -76,7 +76,7 @@ def main(client, campaign_id): while page['totalNumEntries'] > offset: page = campaign_shared_set_service.get(selector) - if page['entries']: + if 'entries' in page: for shared_set in page['entries']: print 'Campaign shared set ID %d and name "%s"' % ( shared_set['sharedSetId'], shared_set['sharedSetName'] diff --git a/examples/adwords/v201502/campaign_management/add_location_extension.py b/examples/adwords/v201502/campaign_management/add_location_extension.py deleted file mode 100755 index f0e3e963..00000000 --- a/examples/adwords/v201502/campaign_management/add_location_extension.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -*- coding: UTF-8 -*- -# -# Copyright 2015 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 adds a campaign ad extension to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: GeoLocationService.get, CampaignAdExtensionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - geo_location_service = client.GetService( - 'GeoLocationService', version='v201502') - campaign_ad_extension_service = client.GetService( - 'CampaignAdExtensionService', version='v201502') - - # Construct selector and get geo location info for given addresses. - selector = { - 'addresses': [ - { - 'streetAddress': '1600 Amphitheatre Parkway', - 'cityName': 'Mountain View', - 'provinceCode': 'US-CA', - 'provinceName': 'California', - 'postalCode': '94043', - 'countryCode': 'US' - }, - { - 'streetAddress': u'38 avenue de l\'Opéra', - 'cityName': 'Paris', - 'postalCode': '75002', - 'countryCode': 'FR' - } - ] - } - geo_locations = geo_location_service.get(selector) - - # Construct operations and add campaign ad extension. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'CampaignAdExtension', - 'campaignId': campaign_id, - 'adExtension': { - 'xsi_type': 'LocationExtension', - 'address': geo_locations[0]['address'], - 'geoPoint': geo_locations[0]['geoPoint'], - 'encodedLocation': geo_locations[0]['encodedLocation'], - 'source': 'ADWORDS_FRONTEND', - # Optional fields. - 'companyName': 'ACME Inc.', - 'phoneNumber': '(650) 253-0000' - } - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'CampaignAdExtension', - 'campaignId': campaign_id, - 'adExtension': { - 'xsi_type': 'LocationExtension', - 'address': geo_locations[1]['address'], - 'geoPoint': geo_locations[1]['geoPoint'], - 'encodedLocation': geo_locations[1]['encodedLocation'], - 'source': 'ADWORDS_FRONTEND' - } - } - } - ] - ad_extensions = campaign_ad_extension_service.mutate(operations) - - # Display results. - for ad_extension in ad_extensions['value']: - print ('Campaign ad extension with id \'%s\' and status \'%s\' was added.' - % (ad_extension['adExtension']['id'], ad_extension['status'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py b/examples/adwords/v201502/extensions/add_site_links_using_feeds.py index 9dadf591..575739a0 100755 --- a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201502/extensions/add_site_links_using_feeds.py @@ -31,6 +31,7 @@ __author__ = 'Joseph DiLallo' +import re import uuid from googleads import adwords @@ -41,7 +42,7 @@ # https://developers.google.com/adwords/api/docs/appendix/placeholders.html PLACEHOLDER_SITELINKS = '1' PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URL = '5' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' PLACEHOLDER_FIELD_LINE_1_TEXT = '3' PLACEHOLDER_FIELD_LINE_2_TEXT = '4' @@ -96,17 +97,17 @@ def main(client, campaign_id): # Create site links feed items. items_data = [ - {'text': 'Home', 'url': 'http://www.example.com', + {'text': 'Home', 'finalUrls': 'http://www.example.com', 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'url': 'http://www.example.com/stores', + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'url': 'http://www.example.com/sale', + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'url': 'http://www.example.com/support', + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'url': 'http://www.example.com/products', + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About', 'url': 'http://www.example.com/about', + {'text': 'About', 'finalUrls': 'http://www.example.com/about', 'line1': 'About line 1', 'line2': 'About line 2'} ] @@ -121,7 +122,7 @@ def main(client, campaign_id): }, { 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValue': item['url'] + 'stringValue': item['finalUrls'] }, { 'feedAttributeId': sitelinks_data['line1FeedId'], @@ -170,7 +171,7 @@ def main(client, campaign_id): }, { 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URL + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS }, { 'feedAttributeId': sitelinks_data['line1FeedId'], @@ -195,53 +196,18 @@ def main(client, campaign_id): else: raise errors.GoogleAdsError('No feed mappings were added.') - # Create site links campaign feed. - operands = [] - for feed_item_id in sitelinks_data['feedItemIds']: - operands.append({ - 'xsi_type': 'ConstantOperand', - 'type': 'LONG', - 'longValue': feed_item_id - }) - - feed_item_function = { - 'operator': 'IN', - 'lhsOperand': [ - {'xsi_type': 'RequestContextOperand', 'contextType': 'FEED_ITEM_ID'} - ], - 'rhsOperand': operands - } - - # Optional: to target to a platform, define a function and 'AND' it with the - # feed item ID link: - platform_function = { - 'operator': 'EQUALS', - 'lhsOperand': [ - { - 'xsi_type': 'RequestContextOperand', - 'contextType': 'DEVICE_PLATFORM' - } - ], - 'rhsOperand': [ - { - 'xsi_type': 'ConstantOperand', - 'type': 'STRING', - 'stringValue': 'Mobile' - } - ] - } - combined_function = { - 'operator': 'AND', - 'lhsOperand': [ - {'xsi_type': 'FunctionOperand', 'value': feed_item_function}, - {'xsi_type': 'FunctionOperand', 'value': platform_function} - ] - } + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) campaign_feed = { 'feedId': sitelinks_data['feedId'], 'campaignId': campaign_id, - 'matchingFunction': combined_function, + 'matchingFunction': {'functionString': matching_function_string}, # Specifying placeholder types on the CampaignFeed allows the same feed # to be used for different placeholders in different Campaigns. 'placeholderTypes': [PLACEHOLDER_SITELINKS] diff --git a/examples/adwords/v201502/migration/migrate_to_extension_settings.py b/examples/adwords/v201502/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..0b134549 --- /dev/null +++ b/examples/adwords/v201502/migration/migrate_to_extension_settings.py @@ -0,0 +1,529 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: FeedService.get, FeedMappingService.get, FeedItemService.get +Tags: CampaignExtensionSettingService.mutate, CampaignFeedService.get, +Tags: CampaignFeedService.mutate +Api: AdWordsOnly +""" + +__author__ = 'Mark Saniscalchi' + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201502') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201502') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201502') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201502') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201502') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201502') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + if ('lhsOperand' in campaign_feed['matchingFunction'] and + campaign_feed['matchingFunction']['lhsOperand'][0]['xsi_type'] == + 'RequestContextOperand'): + request_context_operand = campaign_feed['matchingFunction']['lhsOperand'][0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201502') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings['attributeValue']['feedAttributeId']: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py index 964b6e38..a32af291 100755 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py @@ -39,6 +39,9 @@ logging.basicConfig(level=logging.INFO) logging.getLogger('suds.transport').setLevel(logging.DEBUG) +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + def main(client): report_downloader = client.GetReportDownloader(version='v201502') @@ -63,7 +66,7 @@ def main(client): try: while True: - chunk = stream_data.read(adwords.CHUNK_SIZE) + chunk = stream_data.read(CHUNK_SIZE) if not chunk: break report_data.write(chunk.decode() if sys.version_info[0] == 3 and getattr(report_data, 'mode', 'w') == 'w' else chunk) diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py index 960740aa..8846265d 100755 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py @@ -43,6 +43,8 @@ # Specify where to download the file here. PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 def main(client): @@ -65,7 +67,7 @@ def main(client): try: while True: - chunk = stream_data.read(adwords.CHUNK_SIZE) + chunk = stream_data.read(CHUNK_SIZE) if not chunk: break report_data.write(chunk.decode() if sys.version_info[0] == 3 and getattr(report_data, 'mode', 'w') == 'w' else chunk) diff --git a/examples/adxbuyer/v201406/__init__.py b/examples/adxbuyer/v201406/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201406/basic_operations/__init__.py b/examples/adxbuyer/v201406/basic_operations/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201406/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201406/basic_operations/add_ad_groups.py deleted file mode 100755 index fa9da495..00000000 --- a/examples/adxbuyer/v201406/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupService.mutate -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -import uuid - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201406') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adxbuyer/v201406/basic_operations/add_campaigns.py b/examples/adxbuyer/v201406/basic_operations/add_campaigns.py deleted file mode 100755 index 566c05cc..00000000 --- a/examples/adxbuyer/v201406/basic_operations/add_campaigns.py +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds campaigns. To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -Tags: BudgetService.mutate -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -import datetime -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201406') - budget_service = client.GetService('BudgetService', version='v201406') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'DISPLAY', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPM', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'settings': [{ - 'xsi_type': 'RealTimeBiddingSetting', - 'optIn': 'true' - }, { - 'xsi_type': 'KeywordMatchSetting', - 'optIn': 'false' - }], - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - } - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise Banners #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'DISPLAY', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPM', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'settings': [{ - 'xsi_type': 'RealTimeBiddingSetting', - 'optIn': 'true' - }, { - 'xsi_type': 'KeywordMatchSetting', - 'optIn': 'false' - }], - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adxbuyer/v201406/basic_operations/add_placements.py b/examples/adxbuyer/v201406/basic_operations/add_placements.py deleted file mode 100755 index 0f3f7bc0..00000000 --- a/examples/adxbuyer/v201406/basic_operations/add_placements.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct keyword ad group criterion object. - placement1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'http://mars.google.com' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'destinationUrl': 'http://example.com/mars' - } - - placement2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'http://example.com/pluto' - }, - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': placement1 - }, - { - 'operator': 'ADD', - 'operand': placement2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Placement ad group criterion with ad group id \'%s\', criterion ' - 'id \'%s\', and url \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201406/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201406/basic_operations/add_third_party_redirect_ad.py deleted file mode 100755 index e9f55258..00000000 --- a/examples/adxbuyer/v201406/basic_operations/add_third_party_redirect_ad.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds several third party ads to a given ad group. - -To get an ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct operations and add ads. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ThirdPartyRedirectAd', - 'name': 'Example third party ad #%s' % uuid.uuid4(), - 'url': 'http://www.example.com', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - # This field normally contains the javascript ad tag. - 'snippet': (''), - 'certifiedVendorFormatId': '232', - 'isCookieTargeted': 'false', - 'isUserInterestTargeted': 'false', - 'isTagged': 'false', - 'richMediaAdType': 'STANDARD', - 'expandingDirections': ['EXPANDING_UP', 'EXPANDING_DOWN'], - 'adAttributes': ['ROLL_OVER_TO_EXPAND'] - } - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ThirdPartyRedirectAd', - 'name': 'Example third party ad #%s' % uuid.uuid4(), - 'url': 'http://www.example.com', - 'adDuration': '15000', - 'sourceUrl': ('http://ad.doubleclick.net/pfadx/N270.126913.' - '6102203221521/B3876671.21;dcadv=2215309;' - 'sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml'), - 'certifiedVendorFormatId': '303', - 'richMediaAdType': 'IN_STREAM_VIDEO' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with ID \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201406/basic_operations/get_placements.py b/examples/adxbuyer/v201406/basic_operations/get_placements.py deleted file mode 100755 index 2d4c4bd4..00000000 --- a/examples/adxbuyer/v201406/basic_operations/get_placements.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 group criteria in an account. - -To add placements, run add_placements.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.get -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['AdGroupId', 'Id', 'PlacementUrl'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['PLACEMENT'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for criterion in page['entries']: - print ('Placement ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\' and url \'%s\'.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) - else: - print 'No placements were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adxbuyer/v201406/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201406/basic_operations/get_third_party_redirect_ads.py deleted file mode 100755 index 1d865860..00000000 --- a/examples/adxbuyer/v201406/basic_operations/get_third_party_redirect_ads.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 third party ads for a given ad group. - -To add a third party ad, add_third_party_redirect_ad.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.get -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201406') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['THIRD_PARTY_REDIRECT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201406/basic_operations/remove_placement.py b/examples/adxbuyer/v201406/basic_operations/remove_placement.py deleted file mode 100755 index 2d9cd989..00000000 --- a/examples/adxbuyer/v201406/basic_operations/remove_placement.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_placements.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adxbuyer/v201406/basic_operations/update_placement.py b/examples/adxbuyer/v201406/basic_operations/update_placement.py deleted file mode 100755 index 3cfd2935..00000000 --- a/examples/adxbuyer/v201406/basic_operations/update_placement.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 updates the bid of a placement. - -To add a placement, run add_placements.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_PLACEMENT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct operations and update bids. - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' had its bid set to \'%s\'.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['bids']['maxCpc']['amount']['microAmount'])) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adxbuyer/v201406/campaign_management/__init__.py b/examples/adxbuyer/v201406/campaign_management/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201406/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201406/campaign_management/add_placements_in_bulk.py deleted file mode 100755 index eff4095d..00000000 --- a/examples/adxbuyer/v201406/campaign_management/add_placements_in_bulk.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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. - -"""Illustrates how to perform asynchronous requests using the MutateJobService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: MutateJobService.mutate -Tags: MutateJobService.get -Tags: MutateJobService.getResult -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -import random -import re -import time - -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -PLACEMENT_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201406') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add placements. - for i in range(PLACEMENT_NUMBER): - url = 'www.example.com/mars%d' % i - if random.randint(1, 10) == 1: - url = 'NOT_@_URL' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': url - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - url = operations[index]['operand']['criterion']['url'] - print ('ERROR - placement \'%s\' failed due to \'%s\'' % - (url, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201406/error_handling/__init__.py b/examples/adxbuyer/v201406/error_handling/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201406/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201406/error_handling/handle_partial_failures.py deleted file mode 100755 index 7fd16a96..00000000 --- a/examples/adxbuyer/v201406/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -import re - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201406') - - # Construct placement ad group criteria objects. - placements = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'www.example.com/something' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'INVALID!!_URL' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'www.example.com/somethingelse' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'BAD!!_URL' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for placement in placements: - operations.append( - { - 'operator': 'ADD', - 'operand': placement - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added placement ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\' and url \'%s\'' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Placement ad group criterion with ad group id \'%s\' and url ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (placements[int(index[0])]['adGroupId'], - placements[int(index[0])]['criterion']['url'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201406/optimization/__init__.py b/examples/adxbuyer/v201406/optimization/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201406/optimization/get_placement_ideas.py b/examples/adxbuyer/v201406/optimization/get_placement_ideas.py deleted file mode 100755 index 6ee5ff13..00000000 --- a/examples/adxbuyer/v201406/optimization/get_placement_ideas.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 placements that are related to a given placement. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: TargetingIdeaService.get -""" - -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201406') - - # Construct selector object and retrieve related placements. - offset = 0 - url = 'mars.google.com' - selector = { - 'searchParameters': [{ - 'xsi_type': 'RelatedToUrlSearchParameter', - 'urls': [url] - }], - 'ideaType': 'PLACEMENT', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['CRITERION'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - result = result['data'][0]['value'] - print ('Placement with url \'%s\' was found.' - % (result['value']['url'])) - print - print ('Total placements found related to \'%s\': %s' - % (url, page['totalNumEntries'])) - else: - print 'No placements found related to \'%s\'.' % url - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/googleads/adwords.py b/googleads/adwords.py index 859f7719..58dee818 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -18,7 +18,6 @@ import io import os -import StringIO import sys import urllib import urllib2 @@ -31,51 +30,9 @@ import googleads.common import googleads.errors -# The chunk size used for report downloads. -CHUNK_SIZE = 16 * 1024 # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201406': { - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'AlertService': 'mcm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignAdExtensionService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'GeoLocationService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'MutateJobService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - }, 'v201409': { 'AdCustomizerFeedService': 'cm', 'AdGroupAdService': 'cm', @@ -378,6 +335,7 @@ def SetHeaders(self, suds_client): headers=self._adwords_client.oauth2_client.CreateHttpHeader()) def GetReportDownloadHeaders(self, skip_report_header=None, + skip_column_header=None, skip_report_summary=None): """Returns a dictionary of headers for a report download request. @@ -385,6 +343,9 @@ def GetReportDownloadHeaders(self, skip_report_header=None, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -404,6 +365,9 @@ def GetReportDownloadHeaders(self, skip_report_header=None, if skip_report_header: headers.update({'skipReportHeader': str(skip_report_header)}) + if skip_column_header: + headers.update({'skipColumnHeader': str(skip_column_header)}) + if skip_report_summary: headers.update({'skipReportSummary': str(skip_report_summary)}) @@ -471,7 +435,8 @@ def _DownloadReportCheckFormat(self, file_format, output): ' output for GZIPPED formats.') def DownloadReport(self, report_definition, output=sys.stdout, - skip_report_header=None, skip_report_summary=None): + skip_report_header=None, skip_column_header=None, + skip_report_summary=None): """Downloads an AdWords report using a report definition. The report contents will be written to the given output. @@ -487,6 +452,9 @@ def DownloadReport(self, report_definition, output=sys.stdout, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -501,10 +469,11 @@ def DownloadReport(self, report_definition, output=sys.stdout, """ self._DownloadReportCheckFormat(report_definition['downloadFormat'], output) self._DownloadReport(self._SerializeReportDefinition(report_definition), - output, skip_report_header, skip_report_summary) + output, skip_report_header, skip_column_header, + skip_report_summary) def DownloadReportAsStream(self, report_definition, skip_report_header=None, - skip_report_summary=None): + skip_column_header=None, skip_report_summary=None): """Downloads an AdWords report using a report definition. This will return a stream, allowing you to retrieve the report contents. @@ -517,6 +486,9 @@ def DownloadReportAsStream(self, report_definition, skip_report_header=None, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -534,10 +506,11 @@ def DownloadReportAsStream(self, report_definition, skip_report_header=None, """ return self._DownloadReportAsStream( self._SerializeReportDefinition(report_definition), skip_report_header, - skip_report_summary) + skip_column_header, skip_report_summary) def DownloadReportAsStreamWithAwql(self, query, file_format, skip_report_header=None, + skip_column_header=None, skip_report_summary=None): """Downloads an AdWords report using an AWQL query. @@ -553,6 +526,9 @@ def DownloadReportAsStreamWithAwql(self, query, file_format, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -569,10 +545,12 @@ def DownloadReportAsStreamWithAwql(self, query, file_format, network error. """ return self._DownloadReportAsStream(self._SerializeAwql(query, file_format), - skip_report_header, skip_report_summary) + skip_report_header, skip_column_header, + skip_report_summary) def DownloadReportAsString(self, report_definition, - skip_report_header=None, skip_report_summary=None): + skip_report_header=None, skip_column_header=None, + skip_report_summary=None): """Downloads an AdWords report using a report definition. The report contents will be returned as a string. @@ -585,6 +563,9 @@ def DownloadReportAsString(self, report_definition, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -600,16 +581,19 @@ def DownloadReportAsString(self, report_definition, AdWordsReportError: if the request fails for any other reason; e.g. a network error. """ + response = None try: - response = StringIO.StringIO() - self._DownloadReport(self._SerializeReportDefinition(report_definition), - response, skip_report_header, skip_report_summary) - return response.getvalue() + response = self._DownloadReportAsStream( + self._SerializeReportDefinition(report_definition), + skip_report_header, skip_column_header, skip_report_summary) + return response.read().decode() finally: - response.close() + if response: + response.close() def DownloadReportAsStringWithAwql(self, query, file_format, skip_report_header=None, + skip_column_header=None, skip_report_summary=None): """Downloads an AdWords report using an AWQL query. @@ -625,6 +609,9 @@ def DownloadReportAsStringWithAwql(self, query, file_format, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -640,16 +627,19 @@ def DownloadReportAsStringWithAwql(self, query, file_format, AdWordsReportError: if the request fails for any other reason; e.g. a network error. """ + response = None try: - response = StringIO.StringIO() - self._DownloadReport(self._SerializeAwql(query, file_format), response, - skip_report_header, skip_report_summary) - return response.getvalue() + response = self.DownloadReportAsStreamWithAwql( + query, file_format, skip_report_header, skip_column_header, + skip_report_summary) + return response.read().decode() finally: - response.close() + if response: + response.close() def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, - skip_report_header=None, skip_report_summary=None): + skip_report_header=None, skip_column_header=None, + skip_report_summary=None): """Downloads an AdWords report using an AWQL query. The report contents will be written to the given output. @@ -667,6 +657,9 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -681,10 +674,11 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, """ self._DownloadReportCheckFormat(file_format, output) self._DownloadReport(self._SerializeAwql(query, file_format), output, - skip_report_header, skip_report_summary) + skip_report_header, skip_column_header, + skip_report_summary) def _DownloadReport(self, post_body, output, skip_report_header, - skip_report_summary): + skip_column_header, skip_report_summary): """Downloads an AdWords report, writing the contents to the given file. Args: @@ -695,6 +689,9 @@ def _DownloadReport(self, post_body, output, skip_report_header, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -707,20 +704,21 @@ def _DownloadReport(self, post_body, output, skip_report_header, AdWordsReportError: if the request fails for any other reason; e.g. a network error. """ - response = self._DownloadReportAsStream(post_body, skip_report_header, - skip_report_summary) - - while True: - chunk = response.read(CHUNK_SIZE) - if not chunk: - break - output.write(chunk.decode() if sys.version_info[0] == 3 + response = None + try: + response = self._DownloadReportAsStream(post_body, skip_report_header, + skip_column_header, + skip_report_summary) + output.write(response.read().decode() if sys.version_info[0] == 3 and (getattr(output, 'mode', 'w') == 'w' and type(output) is not io.BytesIO) - else chunk) + else response.read()) + finally: + if response: + response.close() def _DownloadReportAsStream(self, post_body, skip_report_header, - skip_report_summary): + skip_column_header, skip_report_summary): """Downloads an AdWords report, returning a stream. Args: @@ -729,6 +727,9 @@ def _DownloadReportAsStream(self, post_body, skip_report_header, skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. + skip_column_header: A boolean indicating whether to include column names + in reports. If false or not specified, report output will include the + column names. skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. @@ -749,6 +750,7 @@ def _DownloadReportAsStream(self, post_body, skip_report_header, request = urllib2.Request( self._end_point, post_body, self._header_handler.GetReportDownloadHeaders(skip_report_header, + skip_column_header, skip_report_summary)) try: return self.url_opener.open(request) diff --git a/googleads/common.py b/googleads/common.py index 337733e5..198fe2b1 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -28,7 +28,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.2.0' +VERSION = '3.3.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d' % (sys.version_info[0], sys.version_info[1]) diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 8da8e9be..375c49b7 100755 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -104,7 +104,38 @@ def testGetReportDownloadHeaders(self): oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( - skip_report_header=False, skip_report_summary=False)) + skip_report_header=False, skip_column_header=False, + skip_report_summary=False)) + + def testGetReportDownloadHeadersWithOptionalHeaders(self): + ccid = 'client customer id' + dev_token = 'developer token' + user_agent = 'user agent!' + oauth_header = {'Authorization': 'header'} + self.adwords_client.client_customer_id = ccid + self.adwords_client.developer_token = dev_token + self.adwords_client.user_agent = user_agent + self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( + oauth_header) + expected_return_value = { + 'Content-type': 'application/x-www-form-urlencoded', + 'developerToken': dev_token, + 'clientCustomerId': ccid, + 'Authorization': 'header', + 'User-Agent': ''.join([ + user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + ',gzip']), + 'skipReportHeader': 'True', + 'skipColumnHeader': 'True', + 'skipReportSummary': 'True' + } + + self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( + oauth_header) + self.assertEqual(expected_return_value, + self.header_handler.GetReportDownloadHeaders( + skip_report_header=True, skip_column_header=True, + skip_report_summary=True)) class AdWordsClientTest(unittest.TestCase): @@ -246,7 +277,7 @@ def testDownloadReport(self): mock_content.return_value) self.assertEqual(content, output_file.getvalue()) self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None) + None, None, None) def testDownloadReportCheckFormat_CSVStringSuccess(self): output_file = io.StringIO() @@ -317,7 +348,7 @@ def testDownloadReport_failure(self): mock_content.return_value) self.assertEqual('', output_file.getvalue()) self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None) + None, None, None) def testDownloadReportWithAwql(self): output_file = io.StringIO() @@ -345,7 +376,7 @@ def testDownloadReportWithAwql(self): self.assertEqual(content, output_file.getvalue()) self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None) + None, None, None) def testDownloadReportWithBytesIO(self): output_file = io.BytesIO() @@ -376,7 +407,7 @@ def testDownloadReportWithBytesIO(self): mock_content.return_value) self.assertEqual(content, output_file.getvalue().decode('utf-8')) self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None) + None, None, None) def testExtractError_badRequest(self): response = mock.Mock() From 6ecdc8deceb264f25d17a0e9e4f7d17d356108a4 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 27 Apr 2015 18:02:10 -0400 Subject: [PATCH 003/180] Commiting latest changes. From 113024ab656f6bf6e0da6006bde681953c2fa0e0 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 19 May 2015 14:58:50 -0400 Subject: [PATCH 004/180] add v201505 support for DFP --- ChangeLog | 4 + .../dfp/v201405/contact_service/__init__.py | 15 --- .../__init__.py | 15 --- .../dfp/v201405/content_service/__init__.py | 15 --- .../dfp/v201405/creative_service/__init__.py | 15 --- .../v201405/creative_set_service/__init__.py | 15 --- .../creative_template_service/__init__.py | 15 --- .../v201405/custom_field_service/__init__.py | 15 --- .../custom_targeting_service/__init__.py | 15 --- .../dfp/v201405/inventory_service/__init__.py | 15 --- .../dfp/v201405/label_service/__init__.py | 15 --- .../__init__.py | 15 --- .../dfp/v201405/line_item_service/__init__.py | 15 --- .../dfp/v201405/network_service/__init__.py | 15 --- .../dfp/v201405/order_service/__init__.py | 15 --- .../__init__.py | 15 --- .../dfp/v201405/report_service/__init__.py | 15 --- .../run_merged_delivery_report.py | 70 ---------- .../suggested_ad_unit_service/__init__.py | 15 --- examples/dfp/v201405/team_service/__init__.py | 15 --- examples/dfp/v201405/user_service/__init__.py | 15 --- .../user_team_association_service/__init__.py | 15 --- .../activity_group_service/__init__.py | 2 +- .../create_activity_groups.py | 4 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 2 +- .../activity_service/create_activities.py | 4 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../audience_segment_service/__init__.py | 2 +- .../create_audience_segments.py | 6 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../base_rate_service}/__init__.py | 2 +- .../create_product_base_rates.py | 65 ++++++++++ .../create_product_template_base_rates.py | 65 ++++++++++ .../base_rate_service/get_all_base_rates.py | 61 +++++++++ .../get_base_rates_for_a_rate_card.py | 71 ++++++++++ .../base_rate_service/update_base_rates.py | 84 ++++++++++++ .../dfp/v201505/company_service/__init__.py | 15 +++ .../company_service/create_companies.py | 4 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../dfp/v201505/contact_service/__init__.py | 15 +++ .../contact_service/create_contacts.py | 4 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../__init__.py | 15 +++ ...create_content_metadata_key_hierarchies.py | 4 +- ...delete_content_metadata_key_hierarchies.py | 4 +- ...et_all_content_metadata_key_hierarchies.py | 4 +- ...update_content_metadata_key_hierarchies.py | 4 +- .../dfp/v201505/content_service/__init__.py | 15 +++ .../content_service/get_all_content.py | 4 +- .../get_content_by_category.py | 8 +- .../dfp/v201505/creative_service/__init__.py | 15 +++ .../create_creative_from_template.py | 6 +- .../creative_service/create_creatives.py | 6 +- .../create_custom_creative.py | 6 +- .../creative_service/get_all_creatives.py | 6 +- .../get_creatives_by_statement.py | 6 +- .../creative_service/update_creatives.py | 4 +- .../v201505/creative_set_service/__init__.py | 15 +++ .../associate_creative_set_to_line_item.py | 4 +- .../create_creative_set.py | 4 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_by_statement.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 15 +++ .../get_all_creative_templates.py | 4 +- .../get_creative_templates_by_statement.py | 4 +- .../create_creative_wrappers.py | 4 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../v201505/custom_field_service/__init__.py | 15 +++ .../create_custom_field_options.py | 4 +- .../create_custom_fields.py | 4 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_all_line_item_custom_fields.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 15 +++ ...create_custom_targeting_keys_and_values.py | 4 +- .../delete_custom_targeting_keys.py | 4 +- .../delete_custom_targeting_values.py | 4 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- .../get_custom_targeting_keys_by_statement.py | 4 +- ...et_custom_targeting_values_by_statement.py | 4 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../v201505/exchange_rate_service/__init__.py | 15 +++ .../create_exchange_rates.py | 60 +++++++++ .../get_all_exchange_rates.py | 62 +++++++++ .../get_exchange_rates_by_currency_code.py | 73 +++++++++++ .../update_exchange_rates.py | 79 ++++++++++++ .../get_availability_forecast.py} | 57 ++++++--- ...et_availability_forecast_for_line_item.py} | 27 ++-- .../get_delivery_forecast_for_line_items.py | 54 ++++++++ .../dfp/v201505/inventory_service/__init__.py | 15 +++ .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 4 +- .../get_ad_unit_hierarchy.py | 4 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../dfp/v201505/label_service/__init__.py | 15 +++ .../label_service/create_labels.py | 4 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/get_labels_by_statement.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 15 +++ .../create_licas.py | 4 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_by_statement.py | 4 +- .../update_licas.py | 4 +- .../dfp/v201505/line_item_service/__init__.py | 15 +++ .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 10 +- .../create_video_line_item.py | 44 +++---- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_by_statement.py | 13 +- .../get_recently_updated_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../dfp/v201505/network_service/__init__.py | 15 +++ .../network_service/get_all_networks.py | 4 +- .../network_service/get_current_network.py | 4 +- .../network_service/make_test_network.py | 4 +- .../dfp/v201505/order_service/__init__.py | 15 +++ .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 4 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_by_statement.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../get_placements_by_statement.py | 4 +- .../placement_service/update_placements.py | 4 +- .../v201505/premium_rate_service/__init__.py | 15 +++ .../create_premium_rates.py | 84 ++++++++++++ .../get_all_premium_rates.py | 60 +++++++++ .../get_premium_rates_for_a_rate_card.py | 70 ++++++++++ .../update_premium_rates.py | 94 ++++++++++++++ .../dfp/v201505/product_service/__init__.py | 15 +++ .../product_service/get_all_products.py | 55 ++++++++ .../get_products_for_product_template.py | 64 +++++++++ .../product_service/update_products.py | 75 +++++++++++ .../product_template_service/__init__.py | 15 +++ .../activate_product_templates.py | 82 ++++++++++++ .../create_product_templates.py | 108 ++++++++++++++++ .../get_all_product_templates.py | 57 +++++++++ .../get_sponsorship_product_templates.py | 63 +++++++++ .../update_product_templates.py | 101 +++++++++++++++ .../proposal_line_item_service/__init__.py | 15 +++ .../archive_proposal_line_items.py | 82 ++++++++++++ .../create_proposal_line_items.py | 121 ++++++++++++++++++ .../get_all_proposal_line_items.py | 58 +++++++++ .../get_proposal_line_items_for_proposal.py | 71 ++++++++++ .../update_proposal_line_items.py | 78 +++++++++++ .../dfp/v201505/proposal_service/__init__.py | 15 +++ .../proposal_service/create_proposals.py | 77 +++++++++++ .../proposal_service/get_all_proposals.py | 53 ++++++++ .../get_proposals_by_statement.py | 61 +++++++++ .../submit_proposals_for_approval.py | 73 +++++++++++ .../proposal_service/update_proposals.py | 72 +++++++++++ .../__init__.py | 15 +++ .../fetch_match_tables.py | 4 +- .../get_geo_targets.py | 6 +- .../get_line_items_named_like.py | 4 +- .../dfp/v201505/rate_card_service/__init__.py | 15 +++ .../rate_card_service/get_all_rate_cards.py | 55 ++++++++ .../get_rate_cards_priced_with_currency.py | 64 +++++++++ .../dfp/v201505/report_service/__init__.py | 15 +++ .../report_service/run_delivery_report.py | 8 +- .../report_service/run_inventory_report.py | 6 +- .../report_service/run_reach_report.py | 4 +- .../run_report_with_custom_fields.py | 6 +- .../report_service/run_sales_report.py | 4 +- .../suggested_ad_unit_service/__init__.py | 15 +++ .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- .../get_suggested_ad_units_by_statement.py | 4 +- examples/dfp/v201505/team_service/__init__.py | 15 +++ .../team_service/create_teams.py | 4 +- .../team_service/get_all_teams.py | 4 +- .../team_service/get_teams_by_statement.py | 4 +- .../team_service/update_teams.py | 4 +- examples/dfp/v201505/user_service/__init__.py | 15 +++ .../user_service/create_users.py | 4 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 4 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 4 +- .../user_service/get_users_by_statement.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 15 +++ .../create_user_team_associations.py | 4 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- .../workflow_request_service/__init__.py | 15 +++ .../approve_workflow_approval_requests.py | 100 +++++++++++++++ ...workflow_approval_requests_by_statement.py | 69 ++++++++++ ...xternal_condition_requests_by_statement.py | 69 ++++++++++ ...er_workflow_external_condition_requests.py | 103 +++++++++++++++ googleads/common.py | 2 +- googleads/dfp.py | 32 ++++- tests/dfp_test.py | 13 +- 223 files changed, 3624 insertions(+), 708 deletions(-) delete mode 100755 examples/dfp/v201405/contact_service/__init__.py delete mode 100755 examples/dfp/v201405/content_metadata_key_hierarchy_service/__init__.py delete mode 100755 examples/dfp/v201405/content_service/__init__.py delete mode 100755 examples/dfp/v201405/creative_service/__init__.py delete mode 100755 examples/dfp/v201405/creative_set_service/__init__.py delete mode 100755 examples/dfp/v201405/creative_template_service/__init__.py delete mode 100755 examples/dfp/v201405/custom_field_service/__init__.py delete mode 100755 examples/dfp/v201405/custom_targeting_service/__init__.py delete mode 100755 examples/dfp/v201405/inventory_service/__init__.py delete mode 100755 examples/dfp/v201405/label_service/__init__.py delete mode 100755 examples/dfp/v201405/line_item_creative_association_service/__init__.py delete mode 100755 examples/dfp/v201405/line_item_service/__init__.py delete mode 100755 examples/dfp/v201405/network_service/__init__.py delete mode 100755 examples/dfp/v201405/order_service/__init__.py delete mode 100755 examples/dfp/v201405/publisher_query_language_service/__init__.py delete mode 100755 examples/dfp/v201405/report_service/__init__.py delete mode 100755 examples/dfp/v201405/report_service/run_merged_delivery_report.py delete mode 100755 examples/dfp/v201405/suggested_ad_unit_service/__init__.py delete mode 100755 examples/dfp/v201405/team_service/__init__.py delete mode 100755 examples/dfp/v201405/user_service/__init__.py delete mode 100755 examples/dfp/v201405/user_team_association_service/__init__.py rename examples/dfp/{v201405 => v201505}/activity_group_service/__init__.py (91%) rename examples/dfp/{v201405 => v201505}/activity_group_service/create_activity_groups.py (95%) rename examples/dfp/{v201405 => v201505}/activity_group_service/get_active_activity_groups.py (95%) rename examples/dfp/{v201405 => v201505}/activity_group_service/get_all_activity_groups.py (94%) rename examples/dfp/{v201405 => v201505}/activity_group_service/update_activity_groups.py (96%) rename examples/dfp/{v201405 => v201505}/activity_service/__init__.py (91%) rename examples/dfp/{v201405 => v201505}/activity_service/create_activities.py (97%) rename examples/dfp/{v201405 => v201505}/activity_service/get_active_activities.py (97%) rename examples/dfp/{v201405 => v201505}/activity_service/get_all_activities.py (96%) rename examples/dfp/{v201405 => v201505}/activity_service/update_activities.py (97%) rename examples/dfp/{v201405 => v201505}/audience_segment_service/__init__.py (91%) rename examples/dfp/{v201405 => v201505}/audience_segment_service/create_audience_segments.py (96%) rename examples/dfp/{v201405 => v201505}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/dfp/{v201405 => v201505}/audience_segment_service/get_first_party_audience_segments.py (95%) rename examples/dfp/{v201405 => v201505}/audience_segment_service/populate_first_party_audience_segments.py (96%) rename examples/dfp/{v201405 => v201505}/audience_segment_service/update_audience_segments.py (96%) rename examples/dfp/{v201405/company_service => v201505/base_rate_service}/__init__.py (91%) create mode 100755 examples/dfp/v201505/base_rate_service/create_product_base_rates.py create mode 100755 examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py create mode 100755 examples/dfp/v201505/base_rate_service/get_all_base_rates.py create mode 100755 examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py create mode 100755 examples/dfp/v201505/base_rate_service/update_base_rates.py create mode 100755 examples/dfp/v201505/company_service/__init__.py rename examples/dfp/{v201405 => v201505}/company_service/create_companies.py (96%) rename examples/dfp/{v201405 => v201505}/company_service/get_advertisers.py (97%) rename examples/dfp/{v201405 => v201505}/company_service/get_all_companies.py (96%) rename examples/dfp/{v201405 => v201505}/company_service/update_companies.py (97%) create mode 100755 examples/dfp/v201505/contact_service/__init__.py rename examples/dfp/{v201405 => v201505}/contact_service/create_contacts.py (97%) rename examples/dfp/{v201405 => v201505}/contact_service/get_all_contacts.py (96%) rename examples/dfp/{v201405 => v201505}/contact_service/get_uninvited_contacts.py (97%) rename examples/dfp/{v201405 => v201505}/contact_service/update_contacts.py (97%) create mode 100755 examples/dfp/v201505/content_metadata_key_hierarchy_service/__init__.py rename examples/dfp/{v201405 => v201505}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201405 => v201505}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201405 => v201505}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (95%) rename examples/dfp/{v201405 => v201505}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (97%) create mode 100755 examples/dfp/v201505/content_service/__init__.py rename examples/dfp/{v201405 => v201505}/content_service/get_all_content.py (97%) rename examples/dfp/{v201405 => v201505}/content_service/get_content_by_category.py (96%) create mode 100755 examples/dfp/v201505/creative_service/__init__.py rename examples/dfp/{v201405 => v201505}/creative_service/create_creative_from_template.py (96%) rename examples/dfp/{v201405 => v201505}/creative_service/create_creatives.py (95%) rename examples/dfp/{v201405 => v201505}/creative_service/create_custom_creative.py (95%) rename examples/dfp/{v201405 => v201505}/creative_service/get_all_creatives.py (94%) rename examples/dfp/{v201405 => v201505}/creative_service/get_creatives_by_statement.py (94%) rename examples/dfp/{v201405 => v201505}/creative_service/update_creatives.py (97%) create mode 100755 examples/dfp/v201505/creative_set_service/__init__.py rename examples/dfp/{v201405 => v201505}/creative_set_service/associate_creative_set_to_line_item.py (94%) rename examples/dfp/{v201405 => v201505}/creative_set_service/create_creative_set.py (95%) rename examples/dfp/{v201405 => v201505}/creative_set_service/get_all_creative_sets.py (94%) rename examples/dfp/{v201405 => v201505}/creative_set_service/get_creative_sets_by_statement.py (95%) rename examples/dfp/{v201405 => v201505}/creative_set_service/update_creative_set.py (96%) create mode 100755 examples/dfp/v201505/creative_template_service/__init__.py rename examples/dfp/{v201405 => v201505}/creative_template_service/get_all_creative_templates.py (95%) rename examples/dfp/{v201405 => v201505}/creative_template_service/get_creative_templates_by_statement.py (95%) rename examples/dfp/{v201405 => v201505}/creative_wrapper_service/create_creative_wrappers.py (95%) rename examples/dfp/{v201405 => v201505}/creative_wrapper_service/deactivate_creative_wrapper.py (96%) rename examples/dfp/{v201405 => v201505}/creative_wrapper_service/get_active_creative_wrappers.py (95%) rename examples/dfp/{v201405 => v201505}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/dfp/{v201405 => v201505}/creative_wrapper_service/update_creative_wrappers.py (96%) create mode 100755 examples/dfp/v201505/custom_field_service/__init__.py rename examples/dfp/{v201405 => v201505}/custom_field_service/create_custom_field_options.py (95%) rename examples/dfp/{v201405 => v201505}/custom_field_service/create_custom_fields.py (95%) rename examples/dfp/{v201405 => v201505}/custom_field_service/deactivate_all_line_item_custom_fields.py (96%) rename examples/dfp/{v201405 => v201505}/custom_field_service/get_all_custom_fields.py (95%) rename examples/dfp/{v201405 => v201505}/custom_field_service/get_all_line_item_custom_fields.py (95%) rename examples/dfp/{v201405 => v201505}/custom_field_service/set_line_item_custom_field_value.py (95%) rename examples/dfp/{v201405 => v201505}/custom_field_service/update_custom_fields.py (96%) create mode 100755 examples/dfp/v201505/custom_targeting_service/__init__.py rename examples/dfp/{v201405 => v201505}/custom_targeting_service/create_custom_targeting_keys_and_values.py (97%) rename examples/dfp/{v201405 => v201505}/custom_targeting_service/delete_custom_targeting_keys.py (96%) rename examples/dfp/{v201405 => v201505}/custom_targeting_service/delete_custom_targeting_values.py (96%) rename examples/dfp/{v201405 => v201505}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (96%) rename examples/dfp/{v201405 => v201505}/custom_targeting_service/get_custom_targeting_keys_by_statement.py (94%) rename examples/dfp/{v201405 => v201505}/custom_targeting_service/get_custom_targeting_values_by_statement.py (95%) rename examples/dfp/{v201405 => v201505}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/dfp/{v201405 => v201505}/custom_targeting_service/update_custom_targeting_values.py (96%) create mode 100755 examples/dfp/v201505/exchange_rate_service/__init__.py create mode 100755 examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py create mode 100755 examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py create mode 100755 examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py create mode 100755 examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py rename examples/dfp/{v201405/forecast_service/get_forecast.py => v201505/forecast_service/get_availability_forecast.py} (64%) rename examples/dfp/{v201405/forecast_service/get_forecast_by_id.py => v201505/forecast_service/get_availability_forecast_for_line_item.py} (73%) create mode 100755 examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py create mode 100755 examples/dfp/v201505/inventory_service/__init__.py rename examples/dfp/{v201405 => v201505}/inventory_service/archive_ad_units.py (97%) rename examples/dfp/{v201405 => v201505}/inventory_service/create_ad_units.py (96%) rename examples/dfp/{v201405 => v201505}/inventory_service/get_ad_unit_hierarchy.py (98%) rename examples/dfp/{v201405 => v201505}/inventory_service/get_all_ad_unit_sizes.py (96%) rename examples/dfp/{v201405 => v201505}/inventory_service/get_all_ad_units.py (96%) rename examples/dfp/{v201405 => v201505}/inventory_service/get_top_level_ad_units.py (96%) rename examples/dfp/{v201405 => v201505}/inventory_service/update_ad_units.py (97%) create mode 100755 examples/dfp/v201505/label_service/__init__.py rename examples/dfp/{v201405 => v201505}/label_service/create_labels.py (96%) rename examples/dfp/{v201405 => v201505}/label_service/deactivate_labels.py (97%) rename examples/dfp/{v201405 => v201505}/label_service/get_all_labels.py (96%) rename examples/dfp/{v201405 => v201505}/label_service/get_labels_by_statement.py (96%) rename examples/dfp/{v201405 => v201505}/label_service/update_labels.py (97%) create mode 100755 examples/dfp/v201505/line_item_creative_association_service/__init__.py rename examples/dfp/{v201405 => v201505}/line_item_creative_association_service/create_licas.py (94%) rename examples/dfp/{v201405 => v201505}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/dfp/{v201405 => v201505}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/dfp/{v201405 => v201505}/line_item_creative_association_service/get_licas_by_statement.py (94%) rename examples/dfp/{v201405 => v201505}/line_item_creative_association_service/update_licas.py (94%) create mode 100755 examples/dfp/v201505/line_item_service/__init__.py rename examples/dfp/{v201405 => v201505}/line_item_service/activate_line_items.py (97%) rename examples/dfp/{v201405 => v201505}/line_item_service/create_line_items.py (96%) rename examples/dfp/{v201405 => v201505}/line_item_service/create_video_line_item.py (79%) rename examples/dfp/{v201405 => v201505}/line_item_service/get_all_line_items.py (96%) rename examples/dfp/{v201405 => v201505}/line_item_service/get_line_items_by_statement.py (89%) rename examples/dfp/{v201405 => v201505}/line_item_service/get_recently_updated_line_items.py (97%) rename examples/dfp/{v201405 => v201505}/line_item_service/target_custom_criteria.py (98%) rename examples/dfp/{v201405 => v201505}/line_item_service/update_line_items.py (97%) create mode 100755 examples/dfp/v201505/network_service/__init__.py rename examples/dfp/{v201405 => v201505}/network_service/get_all_networks.py (96%) rename examples/dfp/{v201405 => v201505}/network_service/get_current_network.py (95%) rename examples/dfp/{v201405 => v201505}/network_service/make_test_network.py (96%) create mode 100755 examples/dfp/v201505/order_service/__init__.py rename examples/dfp/{v201405 => v201505}/order_service/approve_orders.py (97%) rename examples/dfp/{v201405 => v201505}/order_service/create_orders.py (96%) rename examples/dfp/{v201405 => v201505}/order_service/get_all_orders.py (96%) rename examples/dfp/{v201405 => v201505}/order_service/get_orders_by_statement.py (96%) rename examples/dfp/{v201405 => v201505}/order_service/update_orders.py (97%) rename examples/dfp/{v201405 => v201505}/placement_service/create_placements.py (97%) rename examples/dfp/{v201405 => v201505}/placement_service/deactivate_placements.py (96%) rename examples/dfp/{v201405 => v201505}/placement_service/get_all_placements.py (96%) rename examples/dfp/{v201405 => v201505}/placement_service/get_placements_by_statement.py (96%) rename examples/dfp/{v201405 => v201505}/placement_service/update_placements.py (97%) create mode 100755 examples/dfp/v201505/premium_rate_service/__init__.py create mode 100755 examples/dfp/v201505/premium_rate_service/create_premium_rates.py create mode 100755 examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py create mode 100755 examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py create mode 100755 examples/dfp/v201505/premium_rate_service/update_premium_rates.py create mode 100755 examples/dfp/v201505/product_service/__init__.py create mode 100755 examples/dfp/v201505/product_service/get_all_products.py create mode 100755 examples/dfp/v201505/product_service/get_products_for_product_template.py create mode 100755 examples/dfp/v201505/product_service/update_products.py create mode 100755 examples/dfp/v201505/product_template_service/__init__.py create mode 100755 examples/dfp/v201505/product_template_service/activate_product_templates.py create mode 100755 examples/dfp/v201505/product_template_service/create_product_templates.py create mode 100755 examples/dfp/v201505/product_template_service/get_all_product_templates.py create mode 100755 examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py create mode 100755 examples/dfp/v201505/product_template_service/update_product_templates.py create mode 100755 examples/dfp/v201505/proposal_line_item_service/__init__.py create mode 100755 examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py create mode 100755 examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py create mode 100755 examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py create mode 100755 examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py create mode 100755 examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py create mode 100755 examples/dfp/v201505/proposal_service/__init__.py create mode 100755 examples/dfp/v201505/proposal_service/create_proposals.py create mode 100755 examples/dfp/v201505/proposal_service/get_all_proposals.py create mode 100755 examples/dfp/v201505/proposal_service/get_proposals_by_statement.py create mode 100755 examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py create mode 100755 examples/dfp/v201505/proposal_service/update_proposals.py create mode 100755 examples/dfp/v201505/publisher_query_language_service/__init__.py rename examples/dfp/{v201405 => v201505}/publisher_query_language_service/fetch_match_tables.py (94%) rename examples/dfp/{v201405 => v201505}/publisher_query_language_service/get_geo_targets.py (92%) rename examples/dfp/{v201405 => v201505}/publisher_query_language_service/get_line_items_named_like.py (93%) create mode 100755 examples/dfp/v201505/rate_card_service/__init__.py create mode 100755 examples/dfp/v201505/rate_card_service/get_all_rate_cards.py create mode 100755 examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py create mode 100755 examples/dfp/v201505/report_service/__init__.py rename examples/dfp/{v201405 => v201505}/report_service/run_delivery_report.py (95%) rename examples/dfp/{v201405 => v201505}/report_service/run_inventory_report.py (95%) rename examples/dfp/{v201405 => v201505}/report_service/run_reach_report.py (94%) rename examples/dfp/{v201405 => v201505}/report_service/run_report_with_custom_fields.py (96%) rename examples/dfp/{v201405 => v201505}/report_service/run_sales_report.py (94%) create mode 100755 examples/dfp/v201505/suggested_ad_unit_service/__init__.py rename examples/dfp/{v201405 => v201505}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (96%) rename examples/dfp/{v201405 => v201505}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/dfp/{v201405 => v201505}/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py (95%) create mode 100755 examples/dfp/v201505/team_service/__init__.py rename examples/dfp/{v201405 => v201505}/team_service/create_teams.py (93%) rename examples/dfp/{v201405 => v201505}/team_service/get_all_teams.py (94%) rename examples/dfp/{v201405 => v201505}/team_service/get_teams_by_statement.py (94%) rename examples/dfp/{v201405 => v201505}/team_service/update_teams.py (95%) create mode 100755 examples/dfp/v201505/user_service/__init__.py rename examples/dfp/{v201405 => v201505}/user_service/create_users.py (93%) rename examples/dfp/{v201405 => v201505}/user_service/deactivate_users.py (95%) rename examples/dfp/{v201405 => v201505}/user_service/get_all_roles.py (91%) rename examples/dfp/{v201405 => v201505}/user_service/get_all_users.py (93%) rename examples/dfp/{v201405 => v201505}/user_service/get_current_user.py (91%) rename examples/dfp/{v201405 => v201505}/user_service/get_users_by_statement.py (93%) rename examples/dfp/{v201405 => v201505}/user_service/update_users.py (94%) create mode 100755 examples/dfp/v201505/user_team_association_service/__init__.py rename examples/dfp/{v201405 => v201505}/user_team_association_service/create_user_team_associations.py (95%) rename examples/dfp/{v201405 => v201505}/user_team_association_service/delete_user_team_associations.py (96%) rename examples/dfp/{v201405 => v201505}/user_team_association_service/get_all_user_team_associations.py (95%) rename examples/dfp/{v201405 => v201505}/user_team_association_service/get_user_team_associations_for_user.py (95%) rename examples/dfp/{v201405 => v201505}/user_team_association_service/update_user_team_associations.py (96%) create mode 100755 examples/dfp/v201505/workflow_request_service/__init__.py create mode 100755 examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py create mode 100755 examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py create mode 100755 examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py create mode 100755 examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py diff --git a/ChangeLog b/ChangeLog index 408308d9..5926156f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +3.4.0 - 5/19/2015 +* Added support for v201505. +* Removed examples for v201405. + 3.3.0 - 3/25/2015 * Fixed issue #47. * Removed support for AdWords v201406. diff --git a/examples/dfp/v201405/contact_service/__init__.py b/examples/dfp/v201405/contact_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/contact_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201405/content_metadata_key_hierarchy_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/content_service/__init__.py b/examples/dfp/v201405/content_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/content_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/creative_service/__init__.py b/examples/dfp/v201405/creative_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/creative_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/creative_set_service/__init__.py b/examples/dfp/v201405/creative_set_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/creative_set_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/creative_template_service/__init__.py b/examples/dfp/v201405/creative_template_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/creative_template_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/custom_field_service/__init__.py b/examples/dfp/v201405/custom_field_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/custom_field_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/custom_targeting_service/__init__.py b/examples/dfp/v201405/custom_targeting_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/custom_targeting_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/inventory_service/__init__.py b/examples/dfp/v201405/inventory_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/inventory_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/label_service/__init__.py b/examples/dfp/v201405/label_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/label_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/line_item_creative_association_service/__init__.py b/examples/dfp/v201405/line_item_creative_association_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/line_item_creative_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/line_item_service/__init__.py b/examples/dfp/v201405/line_item_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/line_item_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/network_service/__init__.py b/examples/dfp/v201405/network_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/network_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/order_service/__init__.py b/examples/dfp/v201405/order_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/order_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/publisher_query_language_service/__init__.py b/examples/dfp/v201405/publisher_query_language_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/publisher_query_language_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/report_service/__init__.py b/examples/dfp/v201405/report_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/report_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/report_service/run_merged_delivery_report.py b/examples/dfp/v201405/report_service/run_merged_delivery_report.py deleted file mode 100755 index e1feec25..00000000 --- a/examples/dfp/v201405/report_service/run_merged_delivery_report.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/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. - -"""This code example runs a report that an upgraded publisher would use to -include statistics before the upgrade. -""" - -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp -from googleads import errors - - -def main(client): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201405') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['ORDER_ID', 'ORDER_NAME'], - 'columns': ['MERGED_AD_SERVER_IMPRESSIONS', 'MERGED_AD_SERVER_CLICKS', - 'MERGED_AD_SERVER_CTR', - 'MERGED_AD_SERVER_CPM_AND_CPC_REVENUE', - 'MERGED_AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'LAST_MONTH' - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201405/suggested_ad_unit_service/__init__.py b/examples/dfp/v201405/suggested_ad_unit_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/suggested_ad_unit_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/team_service/__init__.py b/examples/dfp/v201405/team_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/team_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/user_service/__init__.py b/examples/dfp/v201405/user_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/user_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/user_team_association_service/__init__.py b/examples/dfp/v201405/user_team_association_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201405/user_team_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201405/activity_group_service/__init__.py b/examples/dfp/v201505/activity_group_service/__init__.py similarity index 91% rename from examples/dfp/v201405/activity_group_service/__init__.py rename to examples/dfp/v201505/activity_group_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201405/activity_group_service/__init__.py +++ b/examples/dfp/v201505/activity_group_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201405/activity_group_service/create_activity_groups.py b/examples/dfp/v201505/activity_group_service/create_activity_groups.py similarity index 95% rename from examples/dfp/v201405/activity_group_service/create_activity_groups.py rename to examples/dfp/v201505/activity_group_service/create_activity_groups.py index f828c977..2421c463 100755 --- a/examples/dfp/v201405/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201505/activity_group_service/create_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201405') + version='v201505') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201405/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201505/activity_group_service/get_active_activity_groups.py similarity index 95% rename from examples/dfp/v201405/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201505/activity_group_service/get_active_activity_groups.py index 92a75cef..3bf1d009 100755 --- a/examples/dfp/v201405/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201505/activity_group_service/get_active_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201405') + version='v201505') # Create statement object to only select active activity groups. values = [{ diff --git a/examples/dfp/v201405/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201505/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/dfp/v201405/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201505/activity_group_service/get_all_activity_groups.py index 2ffd28d7..43778b20 100755 --- a/examples/dfp/v201405/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201505/activity_group_service/get_all_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201405') + version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/activity_group_service/update_activity_groups.py b/examples/dfp/v201505/activity_group_service/update_activity_groups.py similarity index 96% rename from examples/dfp/v201405/activity_group_service/update_activity_groups.py rename to examples/dfp/v201505/activity_group_service/update_activity_groups.py index 64c6c6fa..2b228e41 100755 --- a/examples/dfp/v201405/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201505/activity_group_service/update_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201405') + version='v201505') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201405/activity_service/__init__.py b/examples/dfp/v201505/activity_service/__init__.py similarity index 91% rename from examples/dfp/v201405/activity_service/__init__.py rename to examples/dfp/v201505/activity_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201405/activity_service/__init__.py +++ b/examples/dfp/v201505/activity_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201405/activity_service/create_activities.py b/examples/dfp/v201505/activity_service/create_activities.py similarity index 97% rename from examples/dfp/v201405/activity_service/create_activities.py rename to examples/dfp/v201505/activity_service/create_activities.py index 48bff97e..9dc5e957 100755 --- a/examples/dfp/v201405/activity_service/create_activities.py +++ b/examples/dfp/v201505/activity_service/create_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201405') + activity_service = client.GetService('ActivityService', version='v201505') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201405/activity_service/get_active_activities.py b/examples/dfp/v201505/activity_service/get_active_activities.py similarity index 97% rename from examples/dfp/v201405/activity_service/get_active_activities.py rename to examples/dfp/v201505/activity_service/get_active_activities.py index 7416ce96..0fa25b1d 100755 --- a/examples/dfp/v201405/activity_service/get_active_activities.py +++ b/examples/dfp/v201505/activity_service/get_active_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201405') + activity_service = client.GetService('ActivityService', version='v201505') # Create statement object to only select active activities. values = [{ diff --git a/examples/dfp/v201405/activity_service/get_all_activities.py b/examples/dfp/v201505/activity_service/get_all_activities.py similarity index 96% rename from examples/dfp/v201405/activity_service/get_all_activities.py rename to examples/dfp/v201505/activity_service/get_all_activities.py index 24057333..ce6a9904 100755 --- a/examples/dfp/v201405/activity_service/get_all_activities.py +++ b/examples/dfp/v201505/activity_service/get_all_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201405') + activity_service = client.GetService('ActivityService', version='v201505') # Create statement object to select only all activities. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/activity_service/update_activities.py b/examples/dfp/v201505/activity_service/update_activities.py similarity index 97% rename from examples/dfp/v201405/activity_service/update_activities.py rename to examples/dfp/v201505/activity_service/update_activities.py index 21f96ad5..f859ec21 100755 --- a/examples/dfp/v201405/activity_service/update_activities.py +++ b/examples/dfp/v201505/activity_service/update_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -39,7 +39,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201405') + activity_service = client.GetService('ActivityService', version='v201505') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201405/audience_segment_service/__init__.py b/examples/dfp/v201505/audience_segment_service/__init__.py similarity index 91% rename from examples/dfp/v201405/audience_segment_service/__init__.py rename to examples/dfp/v201505/audience_segment_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201405/audience_segment_service/__init__.py +++ b/examples/dfp/v201505/audience_segment_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201405/audience_segment_service/create_audience_segments.py b/examples/dfp/v201505/audience_segment_service/create_audience_segments.py similarity index 96% rename from examples/dfp/v201405/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201505/audience_segment_service/create_audience_segments.py index a5622118..53ccdccc 100755 --- a/examples/dfp/v201405/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/create_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,8 +34,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201405') - network_service = client.GetService('NetworkService', version='v201405') + 'AudienceSegmentService', version='v201505') + network_service = client.GetService('NetworkService', version='v201505') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201405/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/dfp/v201405/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py index 721c7a16..1bd90120 100755 --- a/examples/dfp/v201405/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201405') + 'AudienceSegmentService', version='v201505') # Create statement object to select all audience segments. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py similarity index 95% rename from examples/dfp/v201405/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py index 60d8bc6f..0a96536f 100755 --- a/examples/dfp/v201405/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201405') + 'AudienceSegmentService', version='v201505') # Create statement object to only select first party audience segments. values = [{ diff --git a/examples/dfp/v201405/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py similarity index 96% rename from examples/dfp/v201405/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py index 7a348cb0..83ddcd42 100755 --- a/examples/dfp/v201405/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201405') + 'AudienceSegmentService', version='v201505') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201405/audience_segment_service/update_audience_segments.py b/examples/dfp/v201505/audience_segment_service/update_audience_segments.py similarity index 96% rename from examples/dfp/v201405/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201505/audience_segment_service/update_audience_segments.py index db92594e..59d70194 100755 --- a/examples/dfp/v201405/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/update_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201405') + 'AudienceSegmentService', version='v201505') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201405/company_service/__init__.py b/examples/dfp/v201505/base_rate_service/__init__.py similarity index 91% rename from examples/dfp/v201405/company_service/__init__.py rename to examples/dfp/v201505/base_rate_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201405/company_service/__init__.py +++ b/examples/dfp/v201505/base_rate_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201505/base_rate_service/create_product_base_rates.py b/examples/dfp/v201505/base_rate_service/create_product_base_rates.py new file mode 100755 index 00000000..fdf4fbbf --- /dev/null +++ b/examples/dfp/v201505/base_rate_service/create_product_base_rates.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates a product base rate. + +To determine which base rates exist, run get_all_base_rates.py. + +Tags: BaseRateService.createBaseRates +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, product_id, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService( + 'BaseRateService', version='v201505') + + # Create a product base rate. + product_base_rate = { + 'xsi_type': 'ProductBaseRate', + 'rateCardId': rate_card_id, + 'productId': product_id, + # Set the rate to be $2. + 'rate': { + 'currencyCode': 'USD', + 'microAmount': 2000000 + } + } + + # Create base rates on the server. + base_rates = base_rate_service.createBaseRates( + [product_base_rate]) + + if base_rates: + for base_rate in base_rates: + print ('A product base rate with ID \'%s\' and rate \'%.2f\' %s was ' + 'created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py new file mode 100755 index 00000000..715d2db5 --- /dev/null +++ b/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates a product template base rate. + +To determine which base rates exist, run get_all_base_rates.py. + +Tags: BaseRateService.createBaseRates +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, product_template_id, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService( + 'BaseRateService', version='v201505') + + # Create a product template base rate. + product_template_base_rate = { + 'xsi_type': 'ProductTemplateBaseRate', + 'rateCardId': rate_card_id, + 'productTemplateId': product_template_id, + # Set the rate to be $2. + 'rate': { + 'currencyCode': 'USD', + 'microAmount': 2000000 + } + } + + # Create base rates on the server. + base_rates = base_rate_service.createBaseRates( + [product_template_base_rate]) + + if base_rates: + for base_rate in base_rates: + print ('A product template base rate with ID \'%s\' and rate \'%.2f\' %s' + ' was created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201505/base_rate_service/get_all_base_rates.py b/examples/dfp/v201505/base_rate_service/get_all_base_rates.py new file mode 100755 index 00000000..0763d4b9 --- /dev/null +++ b/examples/dfp/v201505/base_rate_service/get_all_base_rates.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2015 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 base rates. + +To create product base rates, run create_product_base_rates.py +To create product template base rates, run +create_product_template_base_rates.py. + +Tags: BaseRateService.getBaseRatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201505') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get base rates by statement. + while True: + response = base_rate_service.getBaseRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for base_rate in response['results']: + print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' + 'rate card ID \'%s\' was found.' % ( + base_rate['id'], + dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py new file mode 100755 index 00000000..c2b7b29d --- /dev/null +++ b/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2015 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 base rates. + +To create product base rates, run create_product_base_rates.py +To create product template base rates, run +create_product_template_base_rates.py. + +Tags: BaseRateService.getBaseRatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201505') + + # Create a filter statement for base rates for a single rate card. + values = [{ + 'key': 'rateCardId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': rate_card_id + } + }] + query = 'where rateCardId = :rateCardId ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + # Get base rates by statement. + while True: + response = base_rate_service.getBaseRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for base_rate in response['results']: + print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' + 'rate card ID \'%s\' was found.' % ( + base_rate['id'], + dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201505/base_rate_service/update_base_rates.py b/examples/dfp/v201505/base_rate_service/update_base_rates.py new file mode 100755 index 00000000..a7b8da8d --- /dev/null +++ b/examples/dfp/v201505/base_rate_service/update_base_rates.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a base rate's value. + +To determine which base rates exist, run get_all_base_rates.py. + +Tags: BaseRateService.getBaseRatesByStatement +Tags: BaseRateService.updateBaseRates +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' + + +def main(client, base_rate_id): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201505') + + # Create a filter statement for base rates for a single rate card. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': base_rate_id + } + }] + query = 'where id = :id ORDER BY id ASC' + statement = dfp.FilterStatement(query, values, 1) + + # Get single base rate by statement. + response = base_rate_service.getBaseRatesByStatement( + statement.ToStatement()) + + if 'results' in response: + # Update each local base rate object by changing its value to $3 USD. + new_rate = { + 'currencyCode': 'USD', + 'microAmount': 3000000 + } + + updated_base_rates = [] + for base_rate in response['results']: + base_rate['rate'] = new_rate + updated_base_rates.append(base_rate) + + # Update base rates remotely. + base_rates = base_rate_service.updateBaseRates(updated_base_rates) + + # Display results. + if base_rates: + for base_rate in base_rates: + print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' + 'rate card ID \'%s\' was updated.' % ( + base_rate['id'], + dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) + else: + print 'No base rates were updated.' + else: + print 'No base rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, BASE_RATE_ID) diff --git a/examples/dfp/v201505/company_service/__init__.py b/examples/dfp/v201505/company_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/company_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/company_service/create_companies.py b/examples/dfp/v201505/company_service/create_companies.py similarity index 96% rename from examples/dfp/v201405/company_service/create_companies.py rename to examples/dfp/v201505/company_service/create_companies.py index 02cd259c..4b9fc756 100755 --- a/examples/dfp/v201405/company_service/create_companies.py +++ b/examples/dfp/v201505/company_service/create_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201405') + company_service = client.GetService('CompanyService', version='v201505') # Create company objects. companies = [ diff --git a/examples/dfp/v201405/company_service/get_advertisers.py b/examples/dfp/v201505/company_service/get_advertisers.py similarity index 97% rename from examples/dfp/v201405/company_service/get_advertisers.py rename to examples/dfp/v201505/company_service/get_advertisers.py index 6aa1853d..1c4db812 100755 --- a/examples/dfp/v201405/company_service/get_advertisers.py +++ b/examples/dfp/v201505/company_service/get_advertisers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201405') + company_service = client.GetService('CompanyService', version='v201505') # Create statement object to only select companies that are advertisers. values = [{ diff --git a/examples/dfp/v201405/company_service/get_all_companies.py b/examples/dfp/v201505/company_service/get_all_companies.py similarity index 96% rename from examples/dfp/v201405/company_service/get_all_companies.py rename to examples/dfp/v201505/company_service/get_all_companies.py index 0adc4355..5082af52 100755 --- a/examples/dfp/v201405/company_service/get_all_companies.py +++ b/examples/dfp/v201505/company_service/get_all_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201405') + company_service = client.GetService('CompanyService', version='v201505') # Create statement object to select all companies. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/company_service/update_companies.py b/examples/dfp/v201505/company_service/update_companies.py similarity index 97% rename from examples/dfp/v201405/company_service/update_companies.py rename to examples/dfp/v201505/company_service/update_companies.py index 955ad22b..425fddfc 100755 --- a/examples/dfp/v201405/company_service/update_companies.py +++ b/examples/dfp/v201505/company_service/update_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201405') + company_service = client.GetService('CompanyService', version='v201505') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201505/contact_service/__init__.py b/examples/dfp/v201505/contact_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/contact_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/contact_service/create_contacts.py b/examples/dfp/v201505/contact_service/create_contacts.py similarity index 97% rename from examples/dfp/v201405/contact_service/create_contacts.py rename to examples/dfp/v201505/contact_service/create_contacts.py index ffe5edc2..9cfd31ae 100755 --- a/examples/dfp/v201405/contact_service/create_contacts.py +++ b/examples/dfp/v201505/contact_service/create_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -43,7 +43,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201405') + contact_service = client.GetService('ContactService', version='v201505') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201405/contact_service/get_all_contacts.py b/examples/dfp/v201505/contact_service/get_all_contacts.py similarity index 96% rename from examples/dfp/v201405/contact_service/get_all_contacts.py rename to examples/dfp/v201505/contact_service/get_all_contacts.py index dc04fb53..39ff20dc 100755 --- a/examples/dfp/v201405/contact_service/get_all_contacts.py +++ b/examples/dfp/v201505/contact_service/get_all_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201405') + contact_service = client.GetService('ContactService', version='v201505') # Create statement object to get all contacts. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/contact_service/get_uninvited_contacts.py b/examples/dfp/v201505/contact_service/get_uninvited_contacts.py similarity index 97% rename from examples/dfp/v201405/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201505/contact_service/get_uninvited_contacts.py index a92fa524..eccb4170 100755 --- a/examples/dfp/v201405/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201505/contact_service/get_uninvited_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201405') + contact_service = client.GetService('ContactService', version='v201505') # Create statement object to only select contacts that are uninvited. values = [{ diff --git a/examples/dfp/v201405/contact_service/update_contacts.py b/examples/dfp/v201505/contact_service/update_contacts.py similarity index 97% rename from examples/dfp/v201405/contact_service/update_contacts.py rename to examples/dfp/v201505/contact_service/update_contacts.py index 1aa2b6a9..2ca3e06c 100755 --- a/examples/dfp/v201405/contact_service/update_contacts.py +++ b/examples/dfp/v201505/contact_service/update_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -39,7 +39,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201405') + contact_service = client.GetService('ContactService', version='v201505') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201405/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 33bcb53d..65d02493 100755 --- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -45,7 +45,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201405') + 'ContentMetadataKeyHierarchyService', version='v201505') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201405/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 76329f98..4d430b0b 100755 --- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -44,7 +44,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201405') + 'ContentMetadataKeyHierarchyService', version='v201505') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 95% rename from examples/dfp/v201405/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 85a72d91..e504fbff 100755 --- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201405') + 'ContentMetadataKeyHierarchyService', version='v201505') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201405/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index cc154a7a..e8746427 100755 --- a/examples/dfp/v201405/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -46,7 +46,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201405') + 'ContentMetadataKeyHierarchyService', version='v201505') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201505/content_service/__init__.py b/examples/dfp/v201505/content_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/content_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/content_service/get_all_content.py b/examples/dfp/v201505/content_service/get_all_content.py similarity index 97% rename from examples/dfp/v201405/content_service/get_all_content.py rename to examples/dfp/v201505/content_service/get_all_content.py index 88b3d0c9..0bd6c25b 100755 --- a/examples/dfp/v201405/content_service/get_all_content.py +++ b/examples/dfp/v201505/content_service/get_all_content.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201405') + content_service = client.GetService('ContentService', version='v201505') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/content_service/get_content_by_category.py b/examples/dfp/v201505/content_service/get_content_by_category.py similarity index 96% rename from examples/dfp/v201405/content_service/get_content_by_category.py rename to examples/dfp/v201505/content_service/get_content_by_category.py index ab2fcc6b..b5fca4a3 100755 --- a/examples/dfp/v201405/content_service/get_content_by_category.py +++ b/examples/dfp/v201505/content_service/get_content_by_category.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,10 +36,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201405') - network_service = client.GetService('NetworkService', version='v201405') + content_service = client.GetService('ContentService', version='v201505') + network_service = client.GetService('NetworkService', version='v201505') custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') # Get the network's content browse custom targeting key. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201505/creative_service/__init__.py b/examples/dfp/v201505/creative_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/creative_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/creative_service/create_creative_from_template.py b/examples/dfp/v201505/creative_service/create_creative_from_template.py similarity index 96% rename from examples/dfp/v201405/creative_service/create_creative_from_template.py rename to examples/dfp/v201505/creative_service/create_creative_from_template.py index d6a8e3fd..60e35029 100755 --- a/examples/dfp/v201405/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201505/creative_service/create_creative_from_template.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -44,7 +44,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201405') + creative_service = client.GetService('CreativeService', version='v201505') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' @@ -95,7 +95,7 @@ def main(client, advertiser_id): # Display results. print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201405/creative_service/create_creatives.py b/examples/dfp/v201505/creative_service/create_creatives.py similarity index 95% rename from examples/dfp/v201405/creative_service/create_creatives.py rename to examples/dfp/v201505/creative_service/create_creatives.py index 507692d3..56d3240f 100755 --- a/examples/dfp/v201405/creative_service/create_creatives.py +++ b/examples/dfp/v201505/creative_service/create_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -43,7 +43,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201405') + creative_service = client.GetService('CreativeService', version='v201505') # Create creative objects. creatives = [] @@ -85,7 +85,7 @@ def main(client, advertiser_id): for creative in creatives: print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201405/creative_service/create_custom_creative.py b/examples/dfp/v201505/creative_service/create_custom_creative.py similarity index 95% rename from examples/dfp/v201405/creative_service/create_custom_creative.py rename to examples/dfp/v201505/creative_service/create_custom_creative.py index fe474983..7bf92ad5 100755 --- a/examples/dfp/v201405/creative_service/create_custom_creative.py +++ b/examples/dfp/v201505/creative_service/create_custom_creative.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -44,7 +44,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201405') + creative_service = client.GetService('CreativeService', version='v201505') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', @@ -81,7 +81,7 @@ def main(client, advertiser_id): if creative: print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201405/creative_service/get_all_creatives.py b/examples/dfp/v201505/creative_service/get_all_creatives.py similarity index 94% rename from examples/dfp/v201405/creative_service/get_all_creatives.py rename to examples/dfp/v201505/creative_service/get_all_creatives.py index 3833a0e4..37f6e0fc 100755 --- a/examples/dfp/v201405/creative_service/get_all_creatives.py +++ b/examples/dfp/v201505/creative_service/get_all_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201405') + creative_service = client.GetService('CreativeService', version='v201505') # Create statement object to select all creatives. statement = dfp.FilterStatement() @@ -49,7 +49,7 @@ def main(client): for creative in response['results']: print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'found.' % (creative['id'], creative['name'], - creative['Creative.Type'])) + dfp.DfpClassType(creative))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201405/creative_service/get_creatives_by_statement.py b/examples/dfp/v201505/creative_service/get_creatives_by_statement.py similarity index 94% rename from examples/dfp/v201405/creative_service/get_creatives_by_statement.py rename to examples/dfp/v201505/creative_service/get_creatives_by_statement.py index 58060128..466dcfd3 100755 --- a/examples/dfp/v201405/creative_service/get_creatives_by_statement.py +++ b/examples/dfp/v201505/creative_service/get_creatives_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201405') + creative_service = client.GetService('CreativeService', version='v201505') # Create statement object to only select image creatives. values = [{ @@ -59,7 +59,7 @@ def main(client): for creative in creatives: print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'found.' % (creative['id'], creative['name'], - creative['Creative.Type'])) + dfp.DfpClassType(creative))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201405/creative_service/update_creatives.py b/examples/dfp/v201505/creative_service/update_creatives.py similarity index 97% rename from examples/dfp/v201405/creative_service/update_creatives.py rename to examples/dfp/v201505/creative_service/update_creatives.py index 19e2d64c..855169e9 100755 --- a/examples/dfp/v201405/creative_service/update_creatives.py +++ b/examples/dfp/v201505/creative_service/update_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201405') + creative_service = client.GetService('CreativeService', version='v201505') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201505/creative_set_service/__init__.py b/examples/dfp/v201505/creative_set_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/creative_set_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py similarity index 94% rename from examples/dfp/v201405/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py index aed79ecc..3981bd81 100755 --- a/examples/dfp/v201405/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201405') + 'LineItemCreativeAssociationService', version='v201505') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201405/creative_set_service/create_creative_set.py b/examples/dfp/v201505/creative_set_service/create_creative_set.py similarity index 95% rename from examples/dfp/v201405/creative_set_service/create_creative_set.py rename to examples/dfp/v201505/creative_set_service/create_creative_set.py index 6a595d7e..3326489d 100755 --- a/examples/dfp/v201405/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201505/creative_set_service/create_creative_set.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201405') + version='v201505') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201405/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201505/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/dfp/v201405/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201505/creative_set_service/get_all_creative_sets.py index ed98c0c7..ad200999 100755 --- a/examples/dfp/v201405/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201505/creative_set_service/get_all_creative_sets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201405') + version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py similarity index 95% rename from examples/dfp/v201405/creative_set_service/get_creative_sets_by_statement.py rename to examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py index 4a5ce727..dea7f147 100755 --- a/examples/dfp/v201405/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201405') + version='v201505') # Create statement object to only select creative sets that have the given # master creative. diff --git a/examples/dfp/v201405/creative_set_service/update_creative_set.py b/examples/dfp/v201505/creative_set_service/update_creative_set.py similarity index 96% rename from examples/dfp/v201405/creative_set_service/update_creative_set.py rename to examples/dfp/v201505/creative_set_service/update_creative_set.py index 7a217338..623444c5 100755 --- a/examples/dfp/v201405/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201505/creative_set_service/update_creative_set.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201405') + version='v201505') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201505/creative_template_service/__init__.py b/examples/dfp/v201505/creative_template_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/creative_template_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201505/creative_template_service/get_all_creative_templates.py similarity index 95% rename from examples/dfp/v201405/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201505/creative_template_service/get_all_creative_templates.py index ecb87f6e..9ffd0131 100755 --- a/examples/dfp/v201405/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201505/creative_template_service/get_all_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201405') + 'CreativeTemplateService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py similarity index 95% rename from examples/dfp/v201405/creative_template_service/get_creative_templates_by_statement.py rename to examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py index 30385d02..348a6d5e 100755 --- a/examples/dfp/v201405/creative_template_service/get_creative_templates_by_statement.py +++ b/examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201405') + 'CreativeTemplateService', version='v201505') # Create statement object to only select system defined creative templates. values = [{ diff --git a/examples/dfp/v201405/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py similarity index 95% rename from examples/dfp/v201405/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py index 26765892..288c8af2 100755 --- a/examples/dfp/v201405/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201405') + version='v201505') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201405/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 96% rename from examples/dfp/v201405/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py index 1e3e55ee..2e1a8004 100755 --- a/examples/dfp/v201405/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201405') + version='v201505') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201405/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py similarity index 95% rename from examples/dfp/v201405/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py index 76906aa6..09453ff8 100755 --- a/examples/dfp/v201405/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201405') + version='v201505') # Create statement object to only select active creative wrappers. values = [{ diff --git a/examples/dfp/v201405/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/dfp/v201405/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py index f5438edd..9ec01abb 100755 --- a/examples/dfp/v201405/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201405') + version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py similarity index 96% rename from examples/dfp/v201405/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py index 926cb14f..0974cc5f 100755 --- a/examples/dfp/v201405/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201405') + version='v201505') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201505/custom_field_service/__init__.py b/examples/dfp/v201505/custom_field_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/custom_field_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/custom_field_service/create_custom_field_options.py b/examples/dfp/v201505/custom_field_service/create_custom_field_options.py similarity index 95% rename from examples/dfp/v201405/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201505/custom_field_service/create_custom_field_options.py index 756a80cd..8e0e6e98 100755 --- a/examples/dfp/v201405/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201505/custom_field_service/create_custom_field_options.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201405') + 'CustomFieldService', version='v201505') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201405/custom_field_service/create_custom_fields.py b/examples/dfp/v201505/custom_field_service/create_custom_fields.py similarity index 95% rename from examples/dfp/v201405/custom_field_service/create_custom_fields.py rename to examples/dfp/v201505/custom_field_service/create_custom_fields.py index 7ceff6be..e006939b 100755 --- a/examples/dfp/v201405/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/create_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201405') + 'CustomFieldService', version='v201505') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201405/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 96% rename from examples/dfp/v201405/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py index ed0985c0..6a0cfdfc 100755 --- a/examples/dfp/v201405/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201405') + 'CustomFieldService', version='v201505') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201405/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201505/custom_field_service/get_all_custom_fields.py similarity index 95% rename from examples/dfp/v201405/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201505/custom_field_service/get_all_custom_fields.py index 775ed8bd..695121cb 100755 --- a/examples/dfp/v201405/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/get_all_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201405') + 'CustomFieldService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py similarity index 95% rename from examples/dfp/v201405/custom_field_service/get_all_line_item_custom_fields.py rename to examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py index e968eb82..9a334105 100755 --- a/examples/dfp/v201405/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201405') + 'CustomFieldService', version='v201505') # Create statement to select only custom fields that apply to line items. values = [{ diff --git a/examples/dfp/v201405/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py similarity index 95% rename from examples/dfp/v201405/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py index cac1e042..917d405a 100755 --- a/examples/dfp/v201405/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -46,9 +46,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201405') + 'CustomFieldService', version='v201505') - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # Create statement to get a custom field. custom_field_values = [{ @@ -139,11 +139,11 @@ def main(client, custom_field_id, drop_down_custom_field_id, for line_item in line_items: custom_field_value_strings = [] for value in line_item['customFieldValues']: - if value['BaseCustomFieldValue.Type'] == 'CustomFieldValue': + if dfp.DfpClassType(value) == 'CustomFieldValue': custom_field_value_string = ( '{ID: \'%s\', value: \'%s\'}' % (value['customFieldId'], value['value']['value'])) - elif value['BaseCustomFieldValue.Type'] == 'DropDownCustomFieldValue': + elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( '{ID: \'%s\', custom field option ID: \'%s\'}' % (value['customFieldId'], value['customFieldOptionId'])) diff --git a/examples/dfp/v201405/custom_field_service/update_custom_fields.py b/examples/dfp/v201505/custom_field_service/update_custom_fields.py similarity index 96% rename from examples/dfp/v201405/custom_field_service/update_custom_fields.py rename to examples/dfp/v201505/custom_field_service/update_custom_fields.py index b9d08219..2fa529c3 100755 --- a/examples/dfp/v201405/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/update_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201405') + 'CustomFieldService', version='v201505') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201505/custom_targeting_service/__init__.py b/examples/dfp/v201505/custom_targeting_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/custom_targeting_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 97% rename from examples/dfp/v201405/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py index aaf013e3..e3ccf0a6 100755 --- a/examples/dfp/v201405/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -39,7 +39,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py similarity index 96% rename from examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py index 255bb15d..8096ed5c 100755 --- a/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -39,7 +39,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') values = [{ 'key': 'name', diff --git a/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py similarity index 96% rename from examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py index d673a16d..615e1d3b 100755 --- a/examples/dfp/v201405/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201405/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 96% rename from examples/dfp/v201405/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 6a979a5d..c3ffd814 100755 --- a/examples/dfp/v201405/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') # Create statement to get all targeting keys. targeting_key_statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py similarity index 94% rename from examples/dfp/v201405/custom_targeting_service/get_custom_targeting_keys_by_statement.py rename to examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py index a6c07bff..9632a185 100755 --- a/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') values = [{ 'key': 'type', diff --git a/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py similarity index 95% rename from examples/dfp/v201405/custom_targeting_service/get_custom_targeting_values_by_statement.py rename to examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py index 23fd92b8..5fb874ce 100755 --- a/examples/dfp/v201405/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ b/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/dfp/v201405/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py index 07e4325c..e8cf1b3e 100755 --- a/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py similarity index 96% rename from examples/dfp/v201405/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py index 47004023..ebdd5bc8 100755 --- a/examples/dfp/v201405/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201405') + 'CustomTargetingService', version='v201505') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201505/exchange_rate_service/__init__.py b/examples/dfp/v201505/exchange_rate_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/exchange_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py new file mode 100755 index 00000000..beac31c7 --- /dev/null +++ b/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates an exchange rate. + +To determine which exchange rates exist, run get_all_exchange_rates.py. + + +Tags: ExchangeRateService.createExchangeRates +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201505') + + # Create a new fixed exchange rate with currency code 'AUD', with direction + # FROM_NETWORK with a value of 1.5. + exchange_rate = { + 'currencyCode': 'AUD', + 'direction': 'FROM_NETWORK', + 'exchangeRate': long(15000000000), + 'refreshRate': 'FIXED' + } + + created_exchange_rate = exchange_rate_service.createExchangeRates( + [exchange_rate])[0] + + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was created.' % (created_exchange_rate['id'], + created_exchange_rate['currencyCode'], + created_exchange_rate['direction'], + (float(created_exchange_rate['exchangeRate']) / + 10000000000))) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py new file mode 100755 index 00000000..2ede79a8 --- /dev/null +++ b/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all exchange rates. + +To create exchange rates, run create_exchange_rates.py. + +Tags: ExchangeRateService.getExchangeRatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201505') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get all exchange rates by statement. + while True: + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for exchange_rate in response['results']: + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was found.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py new file mode 100755 index 00000000..d67a475b --- /dev/null +++ b/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py @@ -0,0 +1,73 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the exchange rate for a specific currency code. + +To create exchange rates, run create_exchange_rates.py. + +Tags: ExchangeRateService.getExchangeRatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' + + +def main(client, currency_code): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201505') + + # Create a statement to get exchange rates for the specified currency code. + values = [{ + 'key': 'currencyCode', + 'value': { + 'xsi_type': 'TextValue', + 'value': currency_code + } + }] + query = 'WHERE currencyCode = :currencyCode' + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + + # Get rate cards by statement. + while True: + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for exchange_rate in response['results']: + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was found.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, CURRENCY_CODE) diff --git a/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py new file mode 100755 index 00000000..acee7f9b --- /dev/null +++ b/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates the value of an exchange rate. + +To create exchange rates, run create_exchange_rates.py. + +Tags: ExchangeRateService.getExchangeRatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' + + +def main(client, exchange_rate_id): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201505') + + # Create a statement to get an exchange rate by its ID. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': exchange_rate_id + } + }] + query = 'WHERE id = :id' + # Create a filter statement. + statement = dfp.FilterStatement(query, values, 1) + + # Get rate cards by statement. + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + + if 'results' in response: + exchange_rate = response['results'][0] + + # Update the exchange rate value to 1.5. + exchange_rate['exchangeRate'] = long(15000000000) + + exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) + + if exchange_rates: + for exchange_rate in exchange_rates: + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was updated.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) + else: + print 'No exchange rates were updated.' + else: + print 'No exchange rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, EXCHANGE_RATE_ID) diff --git a/examples/dfp/v201405/forecast_service/get_forecast.py b/examples/dfp/v201505/forecast_service/get_availability_forecast.py similarity index 64% rename from examples/dfp/v201405/forecast_service/get_forecast.py rename to examples/dfp/v201505/forecast_service/get_availability_forecast.py index b8025e9c..77e12afb 100755 --- a/examples/dfp/v201405/forecast_service/get_forecast.py +++ b/examples/dfp/v201505/forecast_service/get_availability_forecast.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -14,31 +14,43 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets a forecast for a prospective line item. +"""This example gets a forecast for a prospective line item. -To determine which placements exist, run get_all_placements.py.""" +The prospective line item targets the entire network. The targeting can be +modified to determine forecasts for other criteria such as custom criteria +targeting (in addition to targeting the whole network). See +create_line_items.py for an example of how to create more complex targeting. -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') +Tags: ForecastService.getAvailabilityForecast +Tags: NetworkService.getCurrentNetwork +""" + +__author__ = 'Nicholas Chen' from datetime import date # Import appropriate modules from the client library. from googleads import dfp -# Set the placement that the prospective line item will target. -TARGET_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE'] - -def main(client, target_placement_ids): +def main(client): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201405') + forecast_service = client.GetService('ForecastService', version='v201505') + network_service = client.GetService('NetworkService', version='v201505') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] # Create prospective line item. line_item = { 'targeting': { 'inventoryTargeting': { - 'targetedPlacementIds': target_placement_ids + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] } }, 'creativePlaceholders': [ @@ -65,7 +77,8 @@ def main(client, target_placement_ids): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/New_York' }, 'costType': 'CPM', 'costPerUnit': { @@ -74,15 +87,27 @@ def main(client, target_placement_ids): }, 'primaryGoal': { 'units': '50', - 'unitType': 'IMPRESSIONS' + 'unitType': 'IMPRESSIONS', + 'goalType': 'DAILY' }, 'contractedUnitsBought': '100', 'creativeRotationType': 'EVEN', 'discountType': 'PERCENTAGE', } + prospective_line_item = { + 'lineItem': line_item + } + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } + # Get forecast. - forecast = forecast_service.getForecast(line_item) + forecast = forecast_service.getAvailabilityForecast( + prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) available_percent = (((long(forecast['availableUnits'])/ (matched * 1.0)) * 100) @@ -95,11 +120,11 @@ def main(client, target_placement_ids): print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) print '%d contending line items.' % len(contending_line_items) - if 'possibleUnits' in forecast: + if 'possibleUnits' in forecast and matched: possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TARGET_PLACEMENT_IDS) + main(dfp_client) diff --git a/examples/dfp/v201405/forecast_service/get_forecast_by_id.py b/examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py similarity index 73% rename from examples/dfp/v201405/forecast_service/get_forecast_by_id.py rename to examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py index 6145f92b..6085cc02 100755 --- a/examples/dfp/v201405/forecast_service/get_forecast_by_id.py +++ b/examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -14,26 +14,35 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets a forecast for an existing line item. +"""This code example gets an availability forecast for an existing line item. -To determine which line items exist, run get_all_line_items.py.""" +To determine which line items exist, run get_all_line_items.py. -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') +Tags: ForecastService.getAvailabilityForecastById +""" + +__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp # Set the line item to get a forecast for. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID' +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201405') + forecast_service = client.GetService('ForecastService', version='v201505') + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } # Get forecast for line item. - forecast = forecast_service.getForecastById(line_item_id) + forecast = forecast_service.getAvailabilityForecastById( + line_item_id, forecast_options) matched = long(forecast['matchedUnits']) available_percent = (((long(forecast['availableUnits'])/ (matched * 1.0)) * 100) @@ -46,7 +55,7 @@ def main(client, line_item_id): print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) print '%d contending line items.' % len(contending_line_items) - if 'possibleUnits' in forecast: + if 'possibleUnits' in forecast and matched: possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) diff --git a/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py new file mode 100755 index 00000000..6585a95b --- /dev/null +++ b/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py @@ -0,0 +1,54 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets a delivery forecast for two existing line items. + +To determine which line items exist, run get_all_line_items.py. + +Tags: ForecastService.getDeliveryForecastByIds +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the line items to get forecasts for. +LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_ID_1_HERE' +LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_ID_2_HERE' + + +def main(client, line_item_id1, line_item_id2): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201505') + + # Get forecast for line item. + forecast = forecast_service.getDeliveryForecastByIds( + [line_item_id1, line_item_id2], None) + + for single_forecast in forecast['lineItemDeliveryForecasts']: + unit_type = single_forecast['unitType'] + print ('Forecast for line item %d:%n%t%d %s matched%n%t%d %s delivered%n%t' + '%d %s predicted%n' % ( + single_forecast['lineItemId'], single_forecast['matchedUnits'], + unit_type, single_forecast['deliveredUnits'], unit_type, + single_forecast['predictedDeliveryUnits'], unit_type)) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201505/inventory_service/__init__.py b/examples/dfp/v201505/inventory_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/inventory_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/inventory_service/archive_ad_units.py b/examples/dfp/v201505/inventory_service/archive_ad_units.py similarity index 97% rename from examples/dfp/v201405/inventory_service/archive_ad_units.py rename to examples/dfp/v201505/inventory_service/archive_ad_units.py index 3abf0610..2d5c01b8 100755 --- a/examples/dfp/v201405/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201505/inventory_service/archive_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201405') + inventory_service = client.GetService('InventoryService', version='v201505') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201405/inventory_service/create_ad_units.py b/examples/dfp/v201505/inventory_service/create_ad_units.py similarity index 96% rename from examples/dfp/v201405/inventory_service/create_ad_units.py rename to examples/dfp/v201505/inventory_service/create_ad_units.py index 910aeb01..ac1edaec 100755 --- a/examples/dfp/v201405/inventory_service/create_ad_units.py +++ b/examples/dfp/v201505/inventory_service/create_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -39,7 +39,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201405') + inventory_service = client.GetService('InventoryService', version='v201505') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201405/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py similarity index 98% rename from examples/dfp/v201405/inventory_service/get_ad_unit_hierarchy.py rename to examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py index 901e36b2..65c6b793 100755 --- a/examples/dfp/v201405/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201405') + inventory_service = client.GetService('InventoryService', version='v201505') statement = dfp.FilterStatement() all_ad_units = [] diff --git a/examples/dfp/v201405/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py similarity index 96% rename from examples/dfp/v201405/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py index e8440f98..7a719155 100755 --- a/examples/dfp/v201405/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201405') + inventory_service = client.GetService('InventoryService', version='v201505') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201405/inventory_service/get_all_ad_units.py b/examples/dfp/v201505/inventory_service/get_all_ad_units.py similarity index 96% rename from examples/dfp/v201405/inventory_service/get_all_ad_units.py rename to examples/dfp/v201505/inventory_service/get_all_ad_units.py index ead5f4c8..f6d78437 100755 --- a/examples/dfp/v201405/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201505/inventory_service/get_all_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201405') + inventory_service = client.GetService('InventoryService', version='v201505') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201405/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201505/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/dfp/v201405/inventory_service/get_top_level_ad_units.py rename to examples/dfp/v201505/inventory_service/get_top_level_ad_units.py index 241907a1..d6b85c74 100755 --- a/examples/dfp/v201405/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201505/inventory_service/get_top_level_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,8 +35,8 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201405') - network_service = client.GetService('NetworkService', version='v201405') + inventory_service = client.GetService('InventoryService', version='v201505') + network_service = client.GetService('NetworkService', version='v201505') root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201405/inventory_service/update_ad_units.py b/examples/dfp/v201505/inventory_service/update_ad_units.py similarity index 97% rename from examples/dfp/v201405/inventory_service/update_ad_units.py rename to examples/dfp/v201505/inventory_service/update_ad_units.py index 18f5556d..db8a1633 100755 --- a/examples/dfp/v201405/inventory_service/update_ad_units.py +++ b/examples/dfp/v201505/inventory_service/update_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201405') + inventory_service = client.GetService('InventoryService', version='v201505') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201505/label_service/__init__.py b/examples/dfp/v201505/label_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/label_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/label_service/create_labels.py b/examples/dfp/v201505/label_service/create_labels.py similarity index 96% rename from examples/dfp/v201405/label_service/create_labels.py rename to examples/dfp/v201505/label_service/create_labels.py index fe8dcb84..2347eeb5 100755 --- a/examples/dfp/v201405/label_service/create_labels.py +++ b/examples/dfp/v201505/label_service/create_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201405') + label_service = client.GetService('LabelService', version='v201505') # Create label objects. labels = [] diff --git a/examples/dfp/v201405/label_service/deactivate_labels.py b/examples/dfp/v201505/label_service/deactivate_labels.py similarity index 97% rename from examples/dfp/v201405/label_service/deactivate_labels.py rename to examples/dfp/v201505/label_service/deactivate_labels.py index cb6cc5be..f278e5fc 100755 --- a/examples/dfp/v201405/label_service/deactivate_labels.py +++ b/examples/dfp/v201505/label_service/deactivate_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201405') + label_service = client.GetService('LabelService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201405/label_service/get_all_labels.py b/examples/dfp/v201505/label_service/get_all_labels.py similarity index 96% rename from examples/dfp/v201405/label_service/get_all_labels.py rename to examples/dfp/v201505/label_service/get_all_labels.py index 394b6a66..0d704227 100755 --- a/examples/dfp/v201405/label_service/get_all_labels.py +++ b/examples/dfp/v201505/label_service/get_all_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201405') + label_service = client.GetService('LabelService', version='v201505') # Create statement to get all labels statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/label_service/get_labels_by_statement.py b/examples/dfp/v201505/label_service/get_labels_by_statement.py similarity index 96% rename from examples/dfp/v201405/label_service/get_labels_by_statement.py rename to examples/dfp/v201505/label_service/get_labels_by_statement.py index e8a156e6..a4364ee0 100755 --- a/examples/dfp/v201405/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201505/label_service/get_labels_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201405') + label_service = client.GetService('LabelService', version='v201505') # Create statement to get all labels statement = dfp.FilterStatement('ORDER BY name') diff --git a/examples/dfp/v201405/label_service/update_labels.py b/examples/dfp/v201505/label_service/update_labels.py similarity index 97% rename from examples/dfp/v201405/label_service/update_labels.py rename to examples/dfp/v201505/label_service/update_labels.py index 5d6ab5f1..70c125c8 100755 --- a/examples/dfp/v201405/label_service/update_labels.py +++ b/examples/dfp/v201505/label_service/update_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201405') + label_service = client.GetService('LabelService', version='v201505') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201505/line_item_creative_association_service/__init__.py b/examples/dfp/v201505/line_item_creative_association_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/line_item_creative_association_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/line_item_creative_association_service/create_licas.py b/examples/dfp/v201505/line_item_creative_association_service/create_licas.py similarity index 94% rename from examples/dfp/v201405/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201505/line_item_creative_association_service/create_licas.py index 19956e3b..b5d2c0cf 100755 --- a/examples/dfp/v201405/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201505/line_item_creative_association_service/create_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201405') + 'LineItemCreativeAssociationService', version='v201505') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201405/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/dfp/v201405/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py index 26adbcdb..b51fc2a1 100755 --- a/examples/dfp/v201405/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201405') + 'LineItemCreativeAssociationService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201405/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/dfp/v201405/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py index 8d3b2ba1..5eb41be5 100755 --- a/examples/dfp/v201405/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201405') + 'LineItemCreativeAssociationService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py similarity index 94% rename from examples/dfp/v201405/line_item_creative_association_service/get_licas_by_statement.py rename to examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py index 5cfa4119..390ddded 100755 --- a/examples/dfp/v201405/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201405') + 'LineItemCreativeAssociationService', version='v201505') # Create statement object to only select LICAs for the given line item id. values = [{ diff --git a/examples/dfp/v201405/line_item_creative_association_service/update_licas.py b/examples/dfp/v201505/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/dfp/v201405/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201505/line_item_creative_association_service/update_licas.py index 77b06aa4..1464a1e4 100755 --- a/examples/dfp/v201405/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201505/line_item_creative_association_service/update_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201405') + 'LineItemCreativeAssociationService', version='v201505') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/line_item_service/__init__.py b/examples/dfp/v201505/line_item_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/line_item_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/line_item_service/activate_line_items.py b/examples/dfp/v201505/line_item_service/activate_line_items.py similarity index 97% rename from examples/dfp/v201405/line_item_service/activate_line_items.py rename to examples/dfp/v201505/line_item_service/activate_line_items.py index 47f0ba84..2a6b604b 100755 --- a/examples/dfp/v201405/line_item_service/activate_line_items.py +++ b/examples/dfp/v201505/line_item_service/activate_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201405/line_item_service/create_line_items.py b/examples/dfp/v201505/line_item_service/create_line_items.py similarity index 96% rename from examples/dfp/v201405/line_item_service/create_line_items.py rename to examples/dfp/v201505/line_item_service/create_line_items.py index b48a32b9..8f587e1d 100755 --- a/examples/dfp/v201405/line_item_service/create_line_items.py +++ b/examples/dfp/v201505/line_item_service/create_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # Create line item objects. line_items = [] @@ -137,7 +137,8 @@ def main(client, order_id, targeted_placement_ids): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'costType': 'CPM', 'costPerUnit': { @@ -146,7 +147,8 @@ def main(client, order_id, targeted_placement_ids): }, 'primaryGoal': { 'units': '50', - 'unitType': 'IMPRESSIONS' + 'unitType': 'IMPRESSIONS', + 'goalType': 'LIFETIME' }, 'contractedUnitsBought': '100', 'creativeRotationType': 'EVEN', diff --git a/examples/dfp/v201405/line_item_service/create_video_line_item.py b/examples/dfp/v201505/line_item_service/create_video_line_item.py similarity index 79% rename from examples/dfp/v201405/line_item_service/create_video_line_item.py rename to examples/dfp/v201505/line_item_service/create_video_line_item.py index bd73c567..c64c1d3c 100755 --- a/examples/dfp/v201405/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201505/line_item_service/create_video_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,40 +36,30 @@ ORDER_ID = 'INSERT_ORDER_ID_HERE' TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE' -# Set the custom targeting key ID and value ID representing the metadata on the -# content to target. This would typically be a key representing a 'genre' and -# a value representing something like 'comedy'. -CONTENT_CUSTOM_TARGETING_KEY_ID = 'INSERT_CONTENT_CUSTOM_TARGETING_KEY_ID_HERE' +# Set the custom targeting value ID representing the metadata +# on the content to target. This would typically be from a key representing +# a "genre" and the value representing something like "comedy". The value +# must be from a key in a content metadata key hierarchy. CONTENT_CUSTOM_TARGETING_VALUE_ID = \ 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE' def main(client, order_id, targeted_video_ad_unit_id, - content_custom_targeting_key_id, content_custom_targeting_value_id): + content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') - - # create custom criteria for the content metadata targeting. - custom_criteria = { - 'xsi_type': 'CustomCriteria', - 'keyId': content_custom_targeting_key_id, - 'valueIds': [content_custom_targeting_value_id], - 'operator': 'IS' - } - - # Create the custom criteria set. - top_set = { - 'xsi_type': 'CustomCriteriaSet', - 'logicalOperator': 'OR', - 'children': [custom_criteria] - } + line_item_service = client.GetService('LineItemService', version='v201505') # Create line item object. line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, 'targeting': { - 'customTargeting': top_set, + 'contentTargeting': { + 'targetedContentMetadata': [ + {'customTargetingValueIds': [ + content_custom_targeting_value_id]} + ] + }, 'inventoryTargeting': { 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id, 'includeDescendants': 'true'}] @@ -118,7 +108,8 @@ def main(client, order_id, targeted_video_ad_unit_id, }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'costType': 'CPM', 'costPerUnit': { @@ -127,7 +118,8 @@ def main(client, order_id, targeted_video_ad_unit_id, }, 'primaryGoal': { 'units': '50', - 'unitType': 'IMPRESSIONS' + 'unitType': 'IMPRESSIONS', + 'goalType': 'DAILY' }, 'contractedUnitsBought': '100', 'creativeRotationType': 'OPTIMIZED', @@ -147,4 +139,4 @@ def main(client, order_id, targeted_video_ad_unit_id, # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, - CONTENT_CUSTOM_TARGETING_KEY_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID) + CONTENT_CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201405/line_item_service/get_all_line_items.py b/examples/dfp/v201505/line_item_service/get_all_line_items.py similarity index 96% rename from examples/dfp/v201405/line_item_service/get_all_line_items.py rename to examples/dfp/v201505/line_item_service/get_all_line_items.py index 146f3299..3b325864 100755 --- a/examples/dfp/v201405/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201505/line_item_service/get_all_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201505/line_item_service/get_line_items_by_statement.py similarity index 89% rename from examples/dfp/v201405/line_item_service/get_line_items_by_statement.py rename to examples/dfp/v201505/line_item_service/get_line_items_by_statement.py index 49362200..d17bc71b 100755 --- a/examples/dfp/v201405/line_item_service/get_line_items_by_statement.py +++ b/examples/dfp/v201505/line_item_service/get_line_items_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # Create statement object to only select line items that need creatives from a # given order. @@ -42,13 +42,14 @@ def main(client, order_id): 'value': order_id } }, { - 'key': 'status', + 'key': 'isMissingCreatives', 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' + 'xsi_type': 'BooleanValue', + 'value': 'true' } }] - query = 'WHERE orderId = :orderId AND status = :status' + query = 'WHERE orderId = :orderId AND ' + 'isMissingCreatives = :isMissingCreatives' statement = dfp.FilterStatement(query, values) while True: diff --git a/examples/dfp/v201405/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py similarity index 97% rename from examples/dfp/v201405/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py index cd06b15d..b7b78e5b 100755 --- a/examples/dfp/v201405/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # Create statement object to only select line items belonging to the order and # have been modified in the last 3 days. diff --git a/examples/dfp/v201405/line_item_service/target_custom_criteria.py b/examples/dfp/v201505/line_item_service/target_custom_criteria.py similarity index 98% rename from examples/dfp/v201405/line_item_service/target_custom_criteria.py rename to examples/dfp/v201505/line_item_service/target_custom_criteria.py index bc896dd0..91717ef3 100755 --- a/examples/dfp/v201405/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201505/line_item_service/target_custom_criteria.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201405/line_item_service/update_line_items.py b/examples/dfp/v201505/line_item_service/update_line_items.py similarity index 97% rename from examples/dfp/v201405/line_item_service/update_line_items.py rename to examples/dfp/v201505/line_item_service/update_line_items.py index d2d5f68a..c67bf761 100755 --- a/examples/dfp/v201405/line_item_service/update_line_items.py +++ b/examples/dfp/v201505/line_item_service/update_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201505/network_service/__init__.py b/examples/dfp/v201505/network_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/network_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/network_service/get_all_networks.py b/examples/dfp/v201505/network_service/get_all_networks.py similarity index 96% rename from examples/dfp/v201405/network_service/get_all_networks.py rename to examples/dfp/v201505/network_service/get_all_networks.py index d1e2091f..d70a65ae 100755 --- a/examples/dfp/v201405/network_service/get_all_networks.py +++ b/examples/dfp/v201505/network_service/get_all_networks.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201405') + network_service = client.GetService('NetworkService', version='v201505') # Get all networks that you have access to with the current login credentials. networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201405/network_service/get_current_network.py b/examples/dfp/v201505/network_service/get_current_network.py similarity index 95% rename from examples/dfp/v201405/network_service/get_current_network.py rename to examples/dfp/v201505/network_service/get_current_network.py index d7d2124b..52138ce9 100755 --- a/examples/dfp/v201405/network_service/get_current_network.py +++ b/examples/dfp/v201505/network_service/get_current_network.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201405') + network_service = client.GetService('NetworkService', version='v201505') # Get the current network. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201405/network_service/make_test_network.py b/examples/dfp/v201505/network_service/make_test_network.py similarity index 96% rename from examples/dfp/v201405/network_service/make_test_network.py rename to examples/dfp/v201505/network_service/make_test_network.py index fa4432a9..a5649823 100755 --- a/examples/dfp/v201405/network_service/make_test_network.py +++ b/examples/dfp/v201505/network_service/make_test_network.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201405') + network_service = client.GetService('NetworkService', version='v201505') # Create a test network. network = network_service.MakeTestNetwork() diff --git a/examples/dfp/v201505/order_service/__init__.py b/examples/dfp/v201505/order_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/order_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/order_service/approve_orders.py b/examples/dfp/v201505/order_service/approve_orders.py similarity index 97% rename from examples/dfp/v201405/order_service/approve_orders.py rename to examples/dfp/v201505/order_service/approve_orders.py index eb2ad033..1c5888bc 100755 --- a/examples/dfp/v201405/order_service/approve_orders.py +++ b/examples/dfp/v201505/order_service/approve_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201405') + order_service = client.GetService('OrderService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201405/order_service/create_orders.py b/examples/dfp/v201505/order_service/create_orders.py similarity index 96% rename from examples/dfp/v201405/order_service/create_orders.py rename to examples/dfp/v201505/order_service/create_orders.py index 8152dc93..24d967e3 100755 --- a/examples/dfp/v201405/order_service/create_orders.py +++ b/examples/dfp/v201505/order_service/create_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201405') + order_service = client.GetService('OrderService', version='v201505') # Create order objects. orders = [] diff --git a/examples/dfp/v201405/order_service/get_all_orders.py b/examples/dfp/v201505/order_service/get_all_orders.py similarity index 96% rename from examples/dfp/v201405/order_service/get_all_orders.py rename to examples/dfp/v201505/order_service/get_all_orders.py index 8d397303..41bfa575 100755 --- a/examples/dfp/v201405/order_service/get_all_orders.py +++ b/examples/dfp/v201505/order_service/get_all_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201405') + order_service = client.GetService('OrderService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/order_service/get_orders_by_statement.py b/examples/dfp/v201505/order_service/get_orders_by_statement.py similarity index 96% rename from examples/dfp/v201405/order_service/get_orders_by_statement.py rename to examples/dfp/v201505/order_service/get_orders_by_statement.py index 9cd835ae..95d8e174 100755 --- a/examples/dfp/v201405/order_service/get_orders_by_statement.py +++ b/examples/dfp/v201505/order_service/get_orders_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201405') + order_service = client.GetService('OrderService', version='v201505') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201405/order_service/update_orders.py b/examples/dfp/v201505/order_service/update_orders.py similarity index 97% rename from examples/dfp/v201405/order_service/update_orders.py rename to examples/dfp/v201505/order_service/update_orders.py index 5004019e..d9192f19 100755 --- a/examples/dfp/v201405/order_service/update_orders.py +++ b/examples/dfp/v201505/order_service/update_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201405') + order_service = client.GetService('OrderService', version='v201505') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201405/placement_service/create_placements.py b/examples/dfp/v201505/placement_service/create_placements.py similarity index 97% rename from examples/dfp/v201405/placement_service/create_placements.py rename to examples/dfp/v201505/placement_service/create_placements.py index 59579383..0688c620 100755 --- a/examples/dfp/v201405/placement_service/create_placements.py +++ b/examples/dfp/v201505/placement_service/create_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,8 +30,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201405') - inventory_service = client.GetService('InventoryService', version='v201405') + placement_service = client.GetService('PlacementService', version='v201505') + inventory_service = client.GetService('InventoryService', version='v201505') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201405/placement_service/deactivate_placements.py b/examples/dfp/v201505/placement_service/deactivate_placements.py similarity index 96% rename from examples/dfp/v201405/placement_service/deactivate_placements.py rename to examples/dfp/v201505/placement_service/deactivate_placements.py index c17ce803..c4726bad 100755 --- a/examples/dfp/v201405/placement_service/deactivate_placements.py +++ b/examples/dfp/v201505/placement_service/deactivate_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201405') + placement_service = client.GetService('PlacementService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201405/placement_service/get_all_placements.py b/examples/dfp/v201505/placement_service/get_all_placements.py similarity index 96% rename from examples/dfp/v201405/placement_service/get_all_placements.py rename to examples/dfp/v201505/placement_service/get_all_placements.py index ed6a8be9..bfdb34ae 100755 --- a/examples/dfp/v201405/placement_service/get_all_placements.py +++ b/examples/dfp/v201505/placement_service/get_all_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201405') + placement_service = client.GetService('PlacementService', version='v201505') # Create statement to fetch all placements. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/placement_service/get_placements_by_statement.py b/examples/dfp/v201505/placement_service/get_placements_by_statement.py similarity index 96% rename from examples/dfp/v201405/placement_service/get_placements_by_statement.py rename to examples/dfp/v201505/placement_service/get_placements_by_statement.py index aa6cf237..9281f234 100755 --- a/examples/dfp/v201405/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201505/placement_service/get_placements_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201405') + placement_service = client.GetService('PlacementService', version='v201505') # Create a statement to only select active placements. values = [{ diff --git a/examples/dfp/v201405/placement_service/update_placements.py b/examples/dfp/v201505/placement_service/update_placements.py similarity index 97% rename from examples/dfp/v201405/placement_service/update_placements.py rename to examples/dfp/v201505/placement_service/update_placements.py index 5d8cacee..dc2877b9 100755 --- a/examples/dfp/v201405/placement_service/update_placements.py +++ b/examples/dfp/v201505/placement_service/update_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201405') + placement_service = client.GetService('PlacementService', version='v201505') # Create query. values = [{ 'key': 'placementId', diff --git a/examples/dfp/v201505/premium_rate_service/__init__.py b/examples/dfp/v201505/premium_rate_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/premium_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201505/premium_rate_service/create_premium_rates.py b/examples/dfp/v201505/premium_rate_service/create_premium_rates.py new file mode 100755 index 00000000..445b86bd --- /dev/null +++ b/examples/dfp/v201505/premium_rate_service/create_premium_rates.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates new premium_rates. + +To determine which premium_rates exist, run get_all_premium_rates.py. +""" + +__author__ = 'Nicholas Chen' + + +# Import appropriate modules from the client library. +from googleads import dfp + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate services. + premium_rate_service = client.GetService('PremiumRateService', + version='v201505') + + # Create an ad unit premium to apply to the rate card. + ad_unit_premium_feature = { + 'xsi_type': 'AdUnitPremiumFeature' + } + + # Create a CPC based premium rate value with adjustments in milli amounts. + # This will adjust a CPC priced proposal line item that has + # inventory targeting specified by 10% of the cost associated with the rate + # card (this comes from a percentage adjustment). + cpc_premium_rate_value = { + 'premiumFeature': ad_unit_premium_feature, + 'rateType': 'CPC', + 'adjustmentSize': 10000, + 'adjustmentType': 'PERCENTAGE' + } + + # Create a CPM based premium rate value with adjustments in micro amounts. + # This will adjust a CPM priced proposal line item that has + # inventory targeting specified by 2 units of the currency associated with + # the rate card (this comes from absolute value adjustment). + cpm_premium_rate_value = { + 'premiumFeature': ad_unit_premium_feature, + 'rateType': 'CPM', + 'adjustmentSize': 2000000, + 'adjustmentType': 'ABSOLUTE_VALUE' + } + + # Create premium_rate objects. + premium_rate = { + 'rateCardId': rate_card_id, + 'pricingMethod': 'ANY_VALUE', + 'premiumFeature': ad_unit_premium_feature, + 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value] + } + + # Add premium_rates. + premium_rates = premium_rate_service.createPremiumRates([premium_rate]) + + # Display results. + for premium_rate in premium_rates: + print ('A premium rate for \'%s\' was added to the rate card with ID' + ' of \'%s\'.\n' + % (dfp.DfpClassType(premium_rate['premiumFeature']), + premium_rate['id'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py new file mode 100755 index 00000000..cbee9eb5 --- /dev/null +++ b/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all premium rates. + +To create premium rates, run create_premium_rates.py. + +Tags: PremiumRateService.getPremiumRatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + premium_rate_service = client.GetService('PremiumRateService', + version='v201505') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get premium rates by statement. + while True: + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for premium_rate in response['results']: + print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' + ' rate card with ID \'%s\' was found.\n' % ( + premium_rate['id'], + dfp.DfpClassType(premium_rate['premiumFeature']), + premium_rate['rateCardId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py new file mode 100755 index 00000000..5fc8fcdf --- /dev/null +++ b/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all premium rates belonging to a specific rate card. + +To create premium rates, run create_premium_rates.py. + +Tags: PremiumRateService.getPremiumRatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate service. + premium_rate_service = client.GetService('PremiumRateService', + version='v201505') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'rateCardId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': rate_card_id + } + }] + query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + # Get premium rates by statement. + while True: + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for premium_rate in response['results']: + print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' + ' rate card with ID \'%s\' was found.\n' % ( + premium_rate['id'], + dfp.DfpClassType(premium_rate['premiumFeature']), + premium_rate['rateCardId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201505/premium_rate_service/update_premium_rates.py b/examples/dfp/v201505/premium_rate_service/update_premium_rates.py new file mode 100755 index 00000000..ec936060 --- /dev/null +++ b/examples/dfp/v201505/premium_rate_service/update_premium_rates.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a premium rate to add a flat fee to an existing feature. + +To determine which premium rates exist, run get_all_premium_rates.py. + +Tags: PremiumRateService.getPremiumRatesByStatement +Tags: PremiumRateService.updatePremiumRates +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' + + +def main(client, premium_rate_id): + # Initialize appropriate service. + premium_rate_service = client.GetService('PremiumRateService', + version='v201505') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': premium_rate_id + } + }] + query = 'WHERE id = :id ORDER BY id ASC' + statement = dfp.FilterStatement(query, values, 1) + + # Get the premium rate. + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + + if 'results' in response: + updated_premium_rates = [] + for premium_rate in response['results']: + # Create a flat fee based premium rate value with a 10% increase. + new_flat_fee_rate = { + 'premiumFeature': premium_rate['premiumFeature'], + 'rateType': 'CPM', + 'adjustmentSize': 10000, + 'adjustmentType': 'PERCENTAGE' + } + + # Update the premium rate's premiumRateValues to include a flat fee + # premium rate. + + existing_premium_rate_value = ( + [] if 'premiumRateValues' not in premium_rate else + premium_rate['premiumRateValues']) + existing_premium_rate_value.append(new_flat_fee_rate) + premium_rate['premiumRateValues'] = existing_premium_rate_value + + updated_premium_rates.append(premium_rate) + + # Update products remotely. + premium_rates = premium_rate_service.updatePremiumRates( + updated_premium_rates) + + # Display results. + if premium_rates: + for premium_rate in premium_rates: + print ('Premium rate with ID \'%s\', associated with rate card id' + ' \'%s\' was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) + else: + print 'No premium rates were updated.' + else: + print 'No premium rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PREMIUM_RATE_ID) diff --git a/examples/dfp/v201505/product_service/__init__.py b/examples/dfp/v201505/product_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/product_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201505/product_service/get_all_products.py b/examples/dfp/v201505/product_service/get_all_products.py new file mode 100755 index 00000000..34bc3e24 --- /dev/null +++ b/examples/dfp/v201505/product_service/get_all_products.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all products. + +Products are created automatically from product templates. + +Tags: ProductService.getProductsByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201505') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get products by statement. + while True: + response = product_service.getProductsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for product in response['results']: + print ('Product with id \'%s\' and name \'%s\' was found.' % ( + product['id'], product['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/product_service/get_products_for_product_template.py b/examples/dfp/v201505/product_service/get_products_for_product_template.py new file mode 100755 index 00000000..2c07c8a4 --- /dev/null +++ b/examples/dfp/v201505/product_service/get_products_for_product_template.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2015 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 products created from a product template. + +Tags: ProductService.getProductsByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201505') + + # Create a filter statement to select only products created from a single + # a product template. + values = [{ + 'key': 'productTemplateId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_template_id + } + }] + query = 'WHERE productTemplateId = :productTemplateId ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + # Get products by statement. + while True: + response = product_service.getProductsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for product in response['results']: + print ('Product with id \'%s\' and name \'%s\' was found.' % ( + product['id'], product['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201505/product_service/update_products.py b/examples/dfp/v201505/product_service/update_products.py new file mode 100755 index 00000000..900dbbd9 --- /dev/null +++ b/examples/dfp/v201505/product_service/update_products.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a product's notes. + +To determine which products exist, run get_all_products.py. + +Tags: ProductService.getProductsByStatement +Tags: ProductService.updateProducts +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, product_id): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201505') + + # Create statement object to select a single product by an ID. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + # Get products by statement. + response = product_service.getProductsByStatement(statement.ToStatement()) + + if 'results' in response: + # Update each local product object by changing its notes. + updated_products = [] + for product in response['results']: + product['notes'] = 'Product needs further review before activation.' + updated_products.append(product) + + # Update products remotely. + products = product_service.updateProducts(updated_products) + + # Display results. + if products: + for product in products: + print ('Product with id \'%s\', name \'%s\', and ' + 'notes \'%s\' was updated.' + % (product['id'], product['name'], product['notes'])) + else: + print 'No products were updated.' + else: + print 'No products found to update.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201505/product_template_service/__init__.py b/examples/dfp/v201505/product_template_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/product_template_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201505/product_template_service/activate_product_templates.py b/examples/dfp/v201505/product_template_service/activate_product_templates.py new file mode 100755 index 00000000..7d2a919f --- /dev/null +++ b/examples/dfp/v201505/product_template_service/activate_product_templates.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example activates a product template. + +To determine which product templates exist, run get_all_product_templates.py. + +Tags: ProductTemplateService.getProductTemplatesByStatement +Tags: ProductTemplateService.performProductTemplateAction +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the product template to activate. +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201505') + + # Create query. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_template_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + product_templates_activated = 0 + + # Get product_templates by statement. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response: + for product_template in response['results']: + print ('Product template with id \'%s\' and name \'%s\' will be ' + 'activated.' % (product_template['id'], + product_template['name'])) + + # Perform action. + result = product_template_service.performProductTemplateAction( + {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + product_templates_activated += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if product_templates_activated > 0: + print ('Number of product templates ' + 'activated: %s' % product_templates_activated) + else: + print 'No product templates were activated.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201505/product_template_service/create_product_templates.py b/examples/dfp/v201505/product_template_service/create_product_templates.py new file mode 100755 index 00000000..7ccaad2b --- /dev/null +++ b/examples/dfp/v201505/product_template_service/create_product_templates.py @@ -0,0 +1,108 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates a product template. + +To determine which product templates exist, run get_all_product_templates.py. + +Tags: ProductTemplateService.createProductTemplates +Tags: NetworkService.getCurrentNetwork +""" + +__author__ = 'Nicholas Chen' + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201505') + network_service = client.GetService( + 'NetworkService', version='v201505') + + # Create a product template. + product_template = { + 'name': ('Product template #%d' % uuid.uuid4()), + 'description': ('This product template creates standard proposal line ' + 'items targeting Chrome browsers with product ' + 'segmentation on ad units and geo targeting.'), + 'nameMacro': (' - - ' + ' - '), + 'productType': 'DFP', + 'rateType': 'CPM', + 'roadblockingType': 'ONE_OR_MORE', + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'lineItemType': 'STANDARD', + 'targeting': { + # Set browser targeting to Chrome. + 'browserTargeting': [ + { + 'browsers': [ + { + 'id': '500072' + } + ] + } + ] + }, + 'productSegmentation': { + 'geoSegment': { + 'targetedLocations': [ + {'id': '2840', + 'displayName': 'US'}, + {'id': '2344', + 'displayName': 'Hong Kong'} + ] + }, + 'adUnitSegments': [{ + 'adUnitId': (network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId']), + 'includeDescendants': 'true' + }] + } + } + + # Create product templates on the server. + product_templates = product_template_service.createProductTemplates( + [product_template]) + + if product_templates: + for product_template in product_templates: + print ('A product template with ID \'%s\' and name \'%s\' was ' + 'created.' % (product_template['id'], product_template['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/product_template_service/get_all_product_templates.py b/examples/dfp/v201505/product_template_service/get_all_product_templates.py new file mode 100755 index 00000000..b0391890 --- /dev/null +++ b/examples/dfp/v201505/product_template_service/get_all_product_templates.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all product templates. + +To create product templates, run create_product_template_templates.py. + +Tags: ProductTemplateService.getProductTemplatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201505') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get product templates by statement. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for product_template in response['results']: + print ('Product template with id \'%s\' and name \'%s\' was found.' % ( + product_template['id'], product_template['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py new file mode 100755 index 00000000..4366e842 --- /dev/null +++ b/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all sponsorship product templates. + +Tags: ProductTemplateService.getProductTemplatesByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201505') + + # Create a statement to select all sponsorship product templates. + values = [{ + 'key': 'lineItemType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'SPONSORSHIP' + } + }] + query = 'WHERE lineItemType = :lineItemType ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + # Get product templates by statement. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for product_template in response['results']: + print ('Product template with id \'%s\' and name \'%s\' was found.' % ( + product_template['id'], product_template['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/product_template_service/update_product_templates.py b/examples/dfp/v201505/product_template_service/update_product_templates.py new file mode 100755 index 00000000..4144c7e7 --- /dev/null +++ b/examples/dfp/v201505/product_template_service/update_product_templates.py @@ -0,0 +1,101 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a product template's GeoTargeting. + +To determine which product templates exist, run get_all_product_templates.py. + +Tags: ProductTemplateService.getProductTemplatesByStatement +Tags: ProductTemplateService.updateProductTemplates +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201505') + + # Create a statement to select a single product template by ID. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_template_id + } + }] + query = 'WHERE id = :id ORDER BY id ASC' + statement = dfp.FilterStatement(query, values, 1) + + # Get product templates by statement. + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + + if 'results' in response: + # Update each local product template object by appending a new geo-target. + for product_template in response['results']: + # Create geo-targeting for Canada to append. + location = { + 'id': '2124', + 'displayName': 'Canada' + } + + try: + targeting = product_template['targeting'] + + if 'geoTargeting' in targeting: + geo_targeting = targeting['geoTargeting'] + + if 'targetedLocations' in geo_targeting: + geo_targeting['targetedLocations'].append(location) + else: + geo_targeting['targetedLocations'] = [location] + else: + targeting['geoTargeting'] = { + 'targetedLocations': [location] + } + except KeyError: + product_template['targeting'] = { + 'geoTargeting': { + 'targetedLocations': [location] + } + } + + # Update products remotely. + product_templates = product_template_service.updateProductTemplates( + [product_template]) + + # Display results. + if product_templates: + for product_template in product_templates: + print ('Product template with id \'%s\' and name \'%s\' was ' + 'updated.' % (product_template['id'], product_template['name'])) + else: + print 'No product templates were updated.' + else: + print 'No product templates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201505/proposal_line_item_service/__init__.py b/examples/dfp/v201505/proposal_line_item_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/proposal_line_item_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py new file mode 100755 index 00000000..5213530b --- /dev/null +++ b/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example archives a proposal line item. + +To determine which proposal line items exist, run +get_all_proposal_line_items.py. +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the proposal line item to archive. +PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' + + +def main(client, proposal_line_item_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201505') + + # Create query. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': proposal_line_item_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + proposal_line_items_archived = 0 + + # Get proposal line items by statement. + while True: + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + if 'results' in response: + for proposal_line_item in response['results']: + print ('Proposal line item with id \'%s\', ' + 'belonging to proposal id \'%s\', and ' + 'name \'%s\' will be archived.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + # Perform action. + result = proposal_line_item_service.performProposalLineItemAction( + {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposal_line_items_archived += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if proposal_line_items_archived > 0: + print ('Number of proposal line items ' + 'archived: %s' % proposal_line_items_archived) + else: + print 'No proposal line items were archived.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py new file mode 100755 index 00000000..f12a681e --- /dev/null +++ b/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py @@ -0,0 +1,121 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates a new run-of-network proposal line item. + +To determine which proposal line items exist, run +get_all_proposal_line_items.py. To determine which proposals exist, run +get_all_proposals.py. +""" + +__author__ = 'Nicholas Chen' + +from datetime import date +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set proposal that the created proposal line item will belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + +# Set the ID of the rate card the proposal line items should be priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, proposal_id, product_id, rate_card_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201505') + network_service = client.GetService('NetworkService', version='v201505') + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single proposal line item. + proposal_line_item = { + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'rateCardId': rate_card_id, + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': { + 'date': { + 'year': str(date.today().year), + 'month': str(date.today().month), + 'day': str(date.today().day) + }, + 'hour': '23', + 'minute': '59', + 'second': '59' + }, + 'endDateTime': { + 'date': { + 'year': str(date.today().year + 1), + 'month': '9', + 'day': '30' + }, + 'hour': '0', + 'minute': '0', + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' + }, + 'deliveryRateType': 'EVENLY', + 'creativeRotationType': 'OPTIMIZED', + 'billingCap': 'CAPPED_CUMULATIVE', + 'billingSource': 'THIRD_PARTY_VOLUME', + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'cost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Proposal line item with id \'%s\', belonging to proposal id \'%s\'' + ', and named \'%s\' was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + diff --git a/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py new file mode 100755 index 00000000..b0b02594 --- /dev/null +++ b/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all proposal line items. + +To create proposal line items, run create_proposal_line_items.py. +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201505') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get proposal line items by statement. + while True: + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for idx, proposal_line_item in enumerate(response['results'], + start=statement.offset): + print ('%s) Proposal line item with id \'%s\', belonging to proposal id' + ' \'%s\', and named \'%s\' was found.' % + (idx, proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py new file mode 100755 index 00000000..cafb9e41 --- /dev/null +++ b/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all proposal line items that belong to a proposal. + +To create proposal line items, run create_proposal_line_items.py.""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the proposal to get proposal line items from. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201505') + + # Create statement object to only select proposal line items belonging to a + # given proposal. + values = [{ + 'key': 'proposalId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': proposal_id + } + }] + query = 'WHERE proposalId = :proposalId ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + while True: + # Get proposal line items by statement. + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + + if 'results' in response: + # Display results. + for idx, proposal_line_item in enumerate(response['results'], + start=statement.offset): + print ('%s) Line item with id \'%s\', belonging to proposal id \'%s\', ' + 'and named \'%s\' was found.' % ( + idx, proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py new file mode 100755 index 00000000..3b152be0 --- /dev/null +++ b/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example updates a proposal line item's notes. + +To determine which proposal line items exist, +run get_all_proposal_line_items.py. +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set id of the proposal line item to update. +PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' + + +def main(client, proposal_line_item_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201505') + + # Create statement to select a proposal line item. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': proposal_line_item_id + } + }] + + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + # Get proposal line items by statement. + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + + if 'results' in response: + # Update each the proposal line item's notes field. + proposal_line_item = response['results'][0] + proposal_line_item['notes'] = 'Proposal line item ready for submission.' + + # Update proposal line items remotely. + proposal_line_items = proposal_line_item_service.updateProposalLineItems( + [proposal_line_item]) + + # Display results. + if proposal_line_items: + for proposal_line_item in proposal_line_items: + print ('Line item with id \'%s\', belonging to proposal id \'%s\' and,' + ' named \'%s\' was updated.' % ( + proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + else: + print 'No proposal line items were updated.' + else: + print 'No proposal line items found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201505/proposal_service/__init__.py b/examples/dfp/v201505/proposal_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/proposal_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201505/proposal_service/create_proposals.py b/examples/dfp/v201505/proposal_service/create_proposals.py new file mode 100755 index 00000000..bb8047d8 --- /dev/null +++ b/examples/dfp/v201505/proposal_service/create_proposals.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates new proposals. + +To determine which proposals exist, run get_all_proposals.py.""" + +__author__ = 'Nicholas Chen' + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' + + +def main(client, advertiser_id, primary_salesperson_id, + secondary_salesperson_id, primary_trafficker_id): + # Initialize appropriate services. + proposal_service = client.GetService('ProposalService', version='v201505') + network_service = client.GetService('NetworkService', version='v201505') + + # Create proposal objects. + proposal = { + 'name': 'Proposal #%s' % uuid.uuid4(), + 'advertiser': { + 'companyId': advertiser_id, + 'type': 'ADVERTISER' + }, + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '75000' + }, + 'secondarySalespeople': [{ + 'userId': secondary_salesperson_id, + 'split': '25000' + }], + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + 'budget': { + 'microAmount': '100000000', + 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] + }, + 'billingCap': 'CAPPED_CUMULATIVE', + 'billingSource': 'DFP_VOLUME' + } + + # Add proposals. + proposals = proposal_service.createProposals([proposals]) + + # Display results. + for proposal in proposals: + print ('Proposal with id \'%s\' and name \'%s\' was created.' + % (proposal['id'], proposal['name'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201505/proposal_service/get_all_proposals.py b/examples/dfp/v201505/proposal_service/get_all_proposals.py new file mode 100755 index 00000000..a5f79d79 --- /dev/null +++ b/examples/dfp/v201505/proposal_service/get_all_proposals.py @@ -0,0 +1,53 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all proposals. + +To create proposals, run create_proposals.py. +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201505') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for proposal in response['results']: + print ('Proposal with id \'%s\' and name \'%s\' was found.' % ( + proposal['id'], proposal['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py new file mode 100755 index 00000000..7aae86c2 --- /dev/null +++ b/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all proposals that are currently 'PENDING_APPROVAL.' + +To create proposals, run create_proposals.py.""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201505') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PENDING_APPROVAL' + } + }] + query = 'WHERE status = :status ORDER BY id ASC' + + statement = dfp.FilterStatement(query, values) + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for proposal in response['results']: + print ('Proposal with id \'%s\' name \'%s\' was found.' + % (proposal['id'], proposal['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py new file mode 100755 index 00000000..87f3e0f4 --- /dev/null +++ b/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py @@ -0,0 +1,73 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example approves a single proposal. + +To determine which proposals exist, run get_all_proposals.py.""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201505') + + # Create query. + values = [{ + 'key': 'proposalId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + } + }] + query = 'WHERE id = :proposalId' + + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + proposals_approved = 0 + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for proposal in response['results']: + print ('Proposal with id \'%s\', name \'%s\', and status \'%s\' will be' + ' approved.' % (proposal['id'], proposal['name'], + proposal['status'])) + # Perform action. + result = proposal_service.performProposalAction( + {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposals_approved += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if proposals_approved > 0: + print '\nNumber of proposals approved: %s' % proposals_approved + else: + print '\nNo proposals were approved.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201505/proposal_service/update_proposals.py b/examples/dfp/v201505/proposal_service/update_proposals.py new file mode 100755 index 00000000..d166abbc --- /dev/null +++ b/examples/dfp/v201505/proposal_service/update_proposals.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example updates the notes of a single proposal specified by ID. + +To determine which proposals exist, run get_all_proposals.py.""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201505') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'proposalId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': proposal_id + } + }] + query = 'WHERE id = :proposalId' + + statement = dfp.FilterStatement(query, values, 1) + + # Get proposals by statement. + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + + if 'results' in response: + # Update each local proposal object by changing its notes. + updated_proposals = [] + for proposal in response['results']: + proposal['notes'] = 'Proposal needs further review before approval.' + updated_proposals.append(proposal) + + # Update proposals remotely. + proposals = proposal_service.updateProposals(updated_proposals) + + # Display results. + if proposals: + for proposal in proposals: + print ('Proposal with id \'%s\', name \'%s\', and ' + 'notes \'%s\' was updated.' + % (proposal['id'], proposal['name'], proposal['notes'])) + else: + print 'No proposals were updated.' + else: + print 'No proposals found to update.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201505/publisher_query_language_service/__init__.py b/examples/dfp/v201505/publisher_query_language_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/publisher_query_language_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py similarity index 94% rename from examples/dfp/v201405/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py index eaab1613..b7c3d3b9 100755 --- a/examples/dfp/v201405/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201405') + report_downloader = client.GetDataDownloader(version='v201505') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201405/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py similarity index 92% rename from examples/dfp/v201405/publisher_query_language_service/get_geo_targets.py rename to examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py index 89af2842..24cdbff9 100755 --- a/examples/dfp/v201405/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,7 +20,7 @@ 'Postal_Code', and 'DMA_Region' (i.e. Metro). A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201405/PublisherQueryLanguageService +https://developers.google.com/doubleclick-publishers/docs/reference/v201505/PublisherQueryLanguageService """ __author__ = ('Nicholas Chen', @@ -34,7 +34,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201405') + report_downloader = client.GetDataDownloader(version='v201505') output_file = tempfile.NamedTemporaryFile( prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201405/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py similarity index 93% rename from examples/dfp/v201405/publisher_query_language_service/get_line_items_named_like.py rename to examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py index 0ad3e7d1..66812bdd 100755 --- a/examples/dfp/v201405/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201405') + report_downloader = client.GetDataDownloader(version='v201505') output_file = tempfile.NamedTemporaryFile( prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201505/rate_card_service/__init__.py b/examples/dfp/v201505/rate_card_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/rate_card_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py new file mode 100755 index 00000000..7ee584da --- /dev/null +++ b/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all rate cards. + +Tags: RateCardService.getRateCardsByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201505') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get rate cards by statement. + while True: + response = rate_card_service.getRateCardsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for rate_card in response['results']: + print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' + 'was found.' % (rate_card['id'], rate_card['name'], + rate_card['currencyCode'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py new file mode 100755 index 00000000..c81bbd5b --- /dev/null +++ b/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2015 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 rate cards that have a currency in US dollars. + +Tags: RateCardService.getRateCardsByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201505') + + # Create a statement to get all rate cards using USD as currency. + values = [{ + 'key': 'currencyCode', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'USD' + } + }] + query = 'WHERE currencyCode = :currencyCode' + + statement = dfp.FilterStatement(query, values) + + # Get rate cards by statement. + while True: + response = rate_card_service.getRateCardsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for rate_card in response['results']: + print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' + 'was found.' % (rate_card['id'], rate_card['name'], + rate_card['currencyCode'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/report_service/__init__.py b/examples/dfp/v201505/report_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/report_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/report_service/run_delivery_report.py b/examples/dfp/v201505/report_service/run_delivery_report.py similarity index 95% rename from examples/dfp/v201405/report_service/run_delivery_report.py rename to examples/dfp/v201505/report_service/run_delivery_report.py index 859262da..8038b0bd 100755 --- a/examples/dfp/v201405/report_service/run_delivery_report.py +++ b/examples/dfp/v201505/report_service/run_delivery_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,9 +30,6 @@ def main(client, order_id): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201405') - # Create statement object to filter for an order. values = [{ 'key': 'id', @@ -58,6 +55,9 @@ def main(client, order_id): } } + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201505') + try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) diff --git a/examples/dfp/v201405/report_service/run_inventory_report.py b/examples/dfp/v201505/report_service/run_inventory_report.py similarity index 95% rename from examples/dfp/v201405/report_service/run_inventory_report.py rename to examples/dfp/v201505/report_service/run_inventory_report.py index 00d278a4..b04b0968 100755 --- a/examples/dfp/v201405/report_service/run_inventory_report.py +++ b/examples/dfp/v201505/report_service/run_inventory_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,9 +29,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201405') + network_service = client.GetService('NetworkService', version='v201505') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201405') + report_downloader = client.GetDataDownloader(version='v201505') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201405/report_service/run_reach_report.py b/examples/dfp/v201505/report_service/run_reach_report.py similarity index 94% rename from examples/dfp/v201405/report_service/run_reach_report.py rename to examples/dfp/v201505/report_service/run_reach_report.py index ff626d4b..d84c43ef 100755 --- a/examples/dfp/v201405/report_service/run_reach_report.py +++ b/examples/dfp/v201505/report_service/run_reach_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201405') + report_downloader = client.GetDataDownloader(version='v201505') # Create report job. report_job = { diff --git a/examples/dfp/v201405/report_service/run_report_with_custom_fields.py b/examples/dfp/v201505/report_service/run_report_with_custom_fields.py similarity index 96% rename from examples/dfp/v201405/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201505/report_service/run_report_with_custom_fields.py index d1d776fe..c3c46e91 100755 --- a/examples/dfp/v201405/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201505/report_service/run_report_with_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,9 +32,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201405') + line_item_service = client.GetService('LineItemService', version='v201505') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201405') + report_downloader = client.GetDataDownloader(version='v201505') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201405/report_service/run_sales_report.py b/examples/dfp/v201505/report_service/run_sales_report.py similarity index 94% rename from examples/dfp/v201405/report_service/run_sales_report.py rename to examples/dfp/v201505/report_service/run_sales_report.py index c3ee6b3c..2539aaad 100755 --- a/examples/dfp/v201405/report_service/run_sales_report.py +++ b/examples/dfp/v201505/report_service/run_sales_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201405') + report_downloader = client.GetDataDownloader(version='v201505') # Create report job. report_job = { diff --git a/examples/dfp/v201505/suggested_ad_unit_service/__init__.py b/examples/dfp/v201505/suggested_ad_unit_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/suggested_ad_unit_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 96% rename from examples/dfp/v201405/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py index cc2f450e..ce54ff15 100755 --- a/examples/dfp/v201405/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201405') + 'SuggestedAdUnitService', version='v201505') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201405/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/dfp/v201405/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py index d8d588fc..775e4239 100755 --- a/examples/dfp/v201405/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201405') + 'SuggestedAdUnitService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py similarity index 95% rename from examples/dfp/v201405/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py rename to examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py index 1634a7bb..180fc082 100755 --- a/examples/dfp/v201405/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201405') + 'SuggestedAdUnitService', version='v201505') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201505/team_service/__init__.py b/examples/dfp/v201505/team_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/team_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/team_service/create_teams.py b/examples/dfp/v201505/team_service/create_teams.py similarity index 93% rename from examples/dfp/v201405/team_service/create_teams.py rename to examples/dfp/v201505/team_service/create_teams.py index 13e76d8e..51119ecc 100755 --- a/examples/dfp/v201405/team_service/create_teams.py +++ b/examples/dfp/v201505/team_service/create_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201405') + team_service = client.GetService('TeamService', version='v201505') # Create team objects. teams = [] diff --git a/examples/dfp/v201405/team_service/get_all_teams.py b/examples/dfp/v201505/team_service/get_all_teams.py similarity index 94% rename from examples/dfp/v201405/team_service/get_all_teams.py rename to examples/dfp/v201505/team_service/get_all_teams.py index 25b21756..463d9ca0 100755 --- a/examples/dfp/v201405/team_service/get_all_teams.py +++ b/examples/dfp/v201505/team_service/get_all_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201405') + team_service = client.GetService('TeamService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/team_service/get_teams_by_statement.py b/examples/dfp/v201505/team_service/get_teams_by_statement.py similarity index 94% rename from examples/dfp/v201405/team_service/get_teams_by_statement.py rename to examples/dfp/v201505/team_service/get_teams_by_statement.py index 9780c17a..d877329f 100755 --- a/examples/dfp/v201405/team_service/get_teams_by_statement.py +++ b/examples/dfp/v201505/team_service/get_teams_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201405') + team_service = client.GetService('TeamService', version='v201505') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201405/team_service/update_teams.py b/examples/dfp/v201505/team_service/update_teams.py similarity index 95% rename from examples/dfp/v201405/team_service/update_teams.py rename to examples/dfp/v201505/team_service/update_teams.py index 418df851..d4dafdf3 100755 --- a/examples/dfp/v201405/team_service/update_teams.py +++ b/examples/dfp/v201505/team_service/update_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -39,7 +39,7 @@ def main(client, ad_unit_id, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201405') + team_service = client.GetService('TeamService', version='v201505') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201505/user_service/__init__.py b/examples/dfp/v201505/user_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/user_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/user_service/create_users.py b/examples/dfp/v201505/user_service/create_users.py similarity index 93% rename from examples/dfp/v201405/user_service/create_users.py rename to examples/dfp/v201505/user_service/create_users.py index 2a432563..f7da0e8c 100755 --- a/examples/dfp/v201405/user_service/create_users.py +++ b/examples/dfp/v201505/user_service/create_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201405') + user_service = client.GetService('UserService', version='v201505') # Create user objects. users = [ diff --git a/examples/dfp/v201405/user_service/deactivate_users.py b/examples/dfp/v201505/user_service/deactivate_users.py similarity index 95% rename from examples/dfp/v201405/user_service/deactivate_users.py rename to examples/dfp/v201505/user_service/deactivate_users.py index 6bbd4224..350950d8 100755 --- a/examples/dfp/v201405/user_service/deactivate_users.py +++ b/examples/dfp/v201505/user_service/deactivate_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201405') + user_service = client.GetService('UserService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201405/user_service/get_all_roles.py b/examples/dfp/v201505/user_service/get_all_roles.py similarity index 91% rename from examples/dfp/v201405/user_service/get_all_roles.py rename to examples/dfp/v201505/user_service/get_all_roles.py index fe260859..e82db9ce 100755 --- a/examples/dfp/v201405/user_service/get_all_roles.py +++ b/examples/dfp/v201505/user_service/get_all_roles.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201405') + user_service = client.GetService('UserService', version='v201505') # Get all roles. roles = user_service.getAllRoles() diff --git a/examples/dfp/v201405/user_service/get_all_users.py b/examples/dfp/v201505/user_service/get_all_users.py similarity index 93% rename from examples/dfp/v201405/user_service/get_all_users.py rename to examples/dfp/v201505/user_service/get_all_users.py index 6ca0c61a..9249baf5 100755 --- a/examples/dfp/v201405/user_service/get_all_users.py +++ b/examples/dfp/v201505/user_service/get_all_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201405') + user_service = client.GetService('UserService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/user_service/get_current_user.py b/examples/dfp/v201505/user_service/get_current_user.py similarity index 91% rename from examples/dfp/v201405/user_service/get_current_user.py rename to examples/dfp/v201505/user_service/get_current_user.py index 9669a5e7..6ec54e10 100755 --- a/examples/dfp/v201405/user_service/get_current_user.py +++ b/examples/dfp/v201505/user_service/get_current_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201405') + user_service = client.GetService('UserService', version='v201505') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201405/user_service/get_users_by_statement.py b/examples/dfp/v201505/user_service/get_users_by_statement.py similarity index 93% rename from examples/dfp/v201405/user_service/get_users_by_statement.py rename to examples/dfp/v201505/user_service/get_users_by_statement.py index 9ed23fed..8496c62a 100755 --- a/examples/dfp/v201405/user_service/get_users_by_statement.py +++ b/examples/dfp/v201505/user_service/get_users_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201405') + user_service = client.GetService('UserService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201405/user_service/update_users.py b/examples/dfp/v201505/user_service/update_users.py similarity index 94% rename from examples/dfp/v201405/user_service/update_users.py rename to examples/dfp/v201505/user_service/update_users.py index 65fab866..7786c469 100755 --- a/examples/dfp/v201405/user_service/update_users.py +++ b/examples/dfp/v201505/user_service/update_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201405') + user_service = client.GetService('UserService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201505/user_team_association_service/__init__.py b/examples/dfp/v201505/user_team_association_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/user_team_association_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201405/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201505/user_team_association_service/create_user_team_associations.py similarity index 95% rename from examples/dfp/v201405/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201505/user_team_association_service/create_user_team_associations.py index 4587fcd6..8710c07f 100755 --- a/examples/dfp/v201405/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201505/user_team_association_service/create_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201405') + 'UserTeamAssociationService', version='v201505') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201405/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py similarity index 96% rename from examples/dfp/v201405/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py index adebf479..47e23734 100755 --- a/examples/dfp/v201405/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201405') + 'UserTeamAssociationService', version='v201505') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201405/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py similarity index 95% rename from examples/dfp/v201405/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py index 1b034a74..4ea6956b 100755 --- a/examples/dfp/v201405/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201405') + 'UserTeamAssociationService', version='v201505') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201405/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py similarity index 95% rename from examples/dfp/v201405/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py index ef6ef0bb..fb2f99b5 100755 --- a/examples/dfp/v201405/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201405') + 'UserTeamAssociationService', version='v201505') # Create query. values = [{ diff --git a/examples/dfp/v201405/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201505/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/dfp/v201405/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201505/user_team_association_service/update_user_team_associations.py index faa6041f..0ad6b314 100755 --- a/examples/dfp/v201405/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201505/user_team_association_service/update_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201405') + 'UserTeamAssociationService', version='v201505') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201505/workflow_request_service/__init__.py b/examples/dfp/v201505/workflow_request_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201505/workflow_request_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py new file mode 100755 index 00000000..64ec3783 --- /dev/null +++ b/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# +# Copyright 2015 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 approves all workflow approval requests belonging to a proposal. + +To determine which workflow approval requests exist, run +get_all_workflow_approval_requests.py. + +Tags: WorkflowRequestService.getWorkflowRequestsByStatement +Tags: WorkflowRequestService.performWorkflowRequestAction +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201505') + + # Create query. + values = [ + { + 'key': 'entityId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + } + }, + { + 'key': 'entityType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PROPOSAL' + } + }, + { + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_APPROVAL_REQUEST' + } + } + ] + query = ('WHERE entityId = :entityId and entityType = :entityType ' + 'and type = :type') + + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + workflow_approval_requests_approved = 0 + + # Get workflow approval requests by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for workflow_approval_request in response['results']: + print ('Workflow approval request with id \'%s\' will be' + ' approved.' % workflow_approval_request['id']) + # Perform action. + result = workflow_request_service.performWorkflowRequestAction( + {'xsi_type': 'ApproveWorkflowApprovalRequests', + 'comment': 'This workflow has now been approved for submission.'}, + statement.ToStatement()) + if result and int(result['numChanges']) > 0: + workflow_approval_requests_approved += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if workflow_approval_requests_approved > 0: + print ('\nNumber of workflow approval requests approved: %s' % + workflow_approval_requests_approved) + else: + print '\nNo workflow approval requests were approved.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py new file mode 100755 index 00000000..cfae6c8c --- /dev/null +++ b/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# +# Copyright 2015 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 workflow approval requests. + +Workflow approval requests must be approved or rejected for a workflow to +finish. + +Tags: WorkflowRequestService.getWorkflowRequestsByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201505') + + # Create statement object to select all workflow approval requests. + values = [{ + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_APPROVAL_REQUEST' + } + }] + query = 'WHERE type = :type' + + statement = dfp.FilterStatement(query, values) + + # Get proposals by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for workflow_request in response['results']: + print ('Workflow approval request with id \'%s\' for %s with id \'%s\' ' + 'was found.' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py new file mode 100755 index 00000000..1f1a9b8c --- /dev/null +++ b/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# +# Copyright 2015 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 workflow external condition requests. + +Workflow external condition requests must be triggered or skipped for a workflow +to finish. + +Tags: WorkflowRequestService.getWorkflowRequestsByStatement +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201505') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' + } + }] + query = 'WHERE type = :type' + + statement = dfp.FilterStatement(query, values) + + # Get proposals by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for workflow_request in response['results']: + print ('Workflow external condition request with id \'%s\' for %s ' + 'with id \'%s\' was found.' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py new file mode 100755 index 00000000..01f03c8d --- /dev/null +++ b/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -0,0 +1,103 @@ +#!/usr/bin/python +# +# Copyright 2015 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 triggers all workflow external condition requests for a proposal. + +Workflow external condition requests must be triggered or skipped for a workflow +to finish. To determine which proposals exist, run get_all_proposals.py. + +Tags: WorkflowRequestService.getWorkflowRequestsByStatement +Tags: WorkflowRequestService.performWorkflowRequestAction +""" + +__author__ = 'Nicholas Chen' + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201505') + + # Create query. + values = [ + { + 'key': 'entityId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + } + }, + { + 'key': 'entityType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PROPOSAL' + } + }, + { + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' + } + } + ] + query = ('WHERE entityId = :entityId and entityType = :entityType ' + 'and type = :type') + + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + workflow_external_condition_requests_triggered = 0 + + # Get workflow external condition requests by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for workflow_request in response['results']: + print ('Workflow external condition request with id \'%s\' for %s ' + 'with id \'%s\' will be triggered.' % + (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + # Perform action. + result = workflow_request_service.performWorkflowRequestAction( + {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, + statement.ToStatement()) + if result and int(result['numChanges']) > 0: + workflow_external_condition_requests_triggered += int( + result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if workflow_external_condition_requests_triggered > 0: + print ('\nNumber of workflow external condition requests triggered: %s' % + workflow_external_condition_requests_triggered) + else: + print '\nNo workflow external condition requests were triggered.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/googleads/common.py b/googleads/common.py index 198fe2b1..57670790 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -28,7 +28,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.3.0' +VERSION = '3.4.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d' % (sys.version_info[0], sys.version_info[1]) diff --git a/googleads/dfp.py b/googleads/dfp.py index 28a261fd..e7c30d87 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -134,6 +134,26 @@ 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), + 'v201505': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', + 'CompanyService', 'ContactService', 'ContentBundleService', + 'ContentMetadataKeyHierarchyService', 'ContentService', + 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', + 'CreativeWrapperService', 'CustomFieldService', + 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', + 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'RateCardService', + 'ReconciliationOrderReportService', 'ReconciliationReportRowService', + 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', + 'SuggestedAdUnitService', 'TeamService', 'UserService', + 'UserTeamAssociationService', 'WorkflowRequestService'), } @@ -390,11 +410,19 @@ def WaitForReport(self, report_job): """ service = self._GetReportService() report_job_id = service.runReportJob(report_job)['id'] - status = service.getReportJob(report_job_id)['reportJobStatus'] + + if self._version > 'v201502': + status = service.getReportJobStatus(report_job_id) + else: + status = service.getReportJob(report_job_id)['reportJobStatus'] + while status != 'COMPLETED' and status != 'FAILED': logging.debug('Report job status: %s', status) time.sleep(30) - status = service.getReportJob(report_job_id)['reportJobStatus'] + if self._version > 'v201502': + status = service.getReportJobStatus(report_job_id) + else: + status = service.getReportJob(report_job_id)['reportJobStatus'] if status == 'FAILED': raise googleads.errors.DfpReportError(report_job_id) diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 7b1e89e1..7995c450 100755 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -416,22 +416,19 @@ def testDownloadPqlResultToList_NoRows(self): def testWaitForReport_success(self): id_ = '1g684' - input_ = {'query': 'something', 'id': id_} - incomplete_response = {'reportJobStatus': 'PROCESSING', 'id': id_} - complete_response = {'reportJobStatus': 'COMPLETED', 'id': id_} - self.report_service.getReportJob.side_effect = [incomplete_response, - complete_response] + input_ = {'reportQuery': 'something', 'id': id_} + self.report_service.getReportJobStatus.side_effect = ['IN_PROGRESS', + 'COMPLETED'] self.report_service.runReportJob.return_value = input_ with mock.patch('time.sleep') as mock_sleep: rval = self.report_downloader.WaitForReport(input_) mock_sleep.assert_called_once_with(30) self.assertEqual(id_, rval) - self.report_service.getReportJob.assert_any_call(id_) + self.report_service.getReportJobStatus.assert_any_call(id_) def testWaitForReport_failure(self): - self.report_service.getReportJob.return_value = { - 'reportJobStatus': 'FAILED'} + self.report_service.getReportJobStatus.return_value = 'FAILED' self.report_service.runReportJob.return_value = {'id': '782yt97r2'} self.assertRaises( From 6736f6048b4dcc642c45911c1dee72adebf17e22 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 19 May 2015 15:00:03 -0400 Subject: [PATCH 005/180] Commiting latest changes. From 126ced4a16c24902cf778f95bb20a112f7c71ffa Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Fri, 22 May 2015 15:00:02 -0400 Subject: [PATCH 006/180] "Fixing issue #55" --- ChangeLog | 8 ++- .../extensions/add_site_links_using_feeds.py | 2 +- googleads/adwords.py | 4 +- googleads/common.py | 2 +- tests/adwords_test.py | 57 ++++++++++++++++++- 5 files changed, 66 insertions(+), 7 deletions(-) diff --git a/ChangeLog b/ChangeLog index 5926156f..83ba0e86 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,6 +1,10 @@ +3.4.1 - 5/22/2015 +* Fixed issue #55 +* Fixed issue #57 + 3.4.0 - 5/19/2015 -* Added support for v201505. -* Removed examples for v201405. +* Added support for DFP v201505. +* Removed examples for DFP v201405. 3.3.0 - 3/25/2015 * Fixed issue #47. diff --git a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py b/examples/adwords/v201502/extensions/add_site_links_using_feeds.py index 575739a0..8bf899b0 100755 --- a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201502/extensions/add_site_links_using_feeds.py @@ -122,7 +122,7 @@ def main(client, campaign_id): }, { 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValue': item['finalUrls'] + 'stringValues': [item['finalUrls']] }, { 'feedAttributeId': sitelinks_data['line1FeedId'], diff --git a/googleads/adwords.py b/googleads/adwords.py index 58dee818..425846eb 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -586,7 +586,7 @@ def DownloadReportAsString(self, report_definition, response = self._DownloadReportAsStream( self._SerializeReportDefinition(report_definition), skip_report_header, skip_column_header, skip_report_summary) - return response.read().decode() + return response.read().decode('utf-8') finally: if response: response.close() @@ -632,7 +632,7 @@ def DownloadReportAsStringWithAwql(self, query, file_format, response = self.DownloadReportAsStreamWithAwql( query, file_format, skip_report_header, skip_column_header, skip_report_summary) - return response.read().decode() + return response.read().decode('utf-8') finally: if response: response.close() diff --git a/googleads/common.py b/googleads/common.py index 57670790..013612f6 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -28,7 +28,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.4.0' +VERSION = '3.4.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d' % (sys.version_info[0], sys.version_info[1]) diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 375c49b7..62012329 100755 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -279,6 +279,61 @@ def testDownloadReport(self): self.header_handler.GetReportDownloadHeaders.assert_called_once_with( None, None, None) + def testDownloadReportAsString(self): + report_definition = {'table': 'campaigns', + 'downloadFormat': 'CSV'} + serialized_report = 'nuinbwuign' + post_body = urllib.urlencode({'__rdxml': serialized_report}) + if not PYTHON2: + post_body = bytes(post_body, 'utf-8') + headers = {'Authorization': 'ya29.something'} + self.header_handler.GetReportDownloadHeaders.return_value = headers + content = u'CONTENT STRING アングリーバード' + fake_request = io.BytesIO() + fake_request.write(content.encode('utf-8') if PYTHON2 + else bytes(content, 'utf-8')) + fake_request.seek(0) + self.marshaller.process.return_value = serialized_report + + with mock.patch('suds.mx.Content') as mock_content: + with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: + self.opener.open.return_value = fake_request + s = self.report_downloader.DownloadReportAsString(report_definition) + mock_request.assert_called_once_with( + ('https://adwords.google.com/api/adwords/reportdownload/%s' + % self.version), post_body, headers) + self.opener.open.assert_called_once_with(mock_request.return_value) + self.marshaller.process.assert_called_once_with( + mock_content.return_value) + self.assertEqual(content, s) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with( + None, None, None) + + def testDownloadReportAsStringWithAwql(self): + query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' + file_format = 'CSV' + post_body = urllib.urlencode({'__fmt': file_format, '__rdquery': query}) + if not PYTHON2: + post_body = bytes(post_body, 'utf-8') + headers = {'Authorization': 'ya29.something'} + self.header_handler.GetReportDownloadHeaders.return_value = headers + content = u'CONTENT STRING アングリーバード' + fake_request = io.BytesIO() + fake_request.write(content.encode('utf-8') if PYTHON2 + else bytes(content, 'utf-8')) + fake_request.seek(0) + with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: + self.opener.open.return_value = fake_request + s = self.report_downloader.DownloadReportAsStringWithAwql(query, + file_format) + mock_request.assert_called_once_with( + ('https://adwords.google.com/api/adwords/reportdownload/%s' + % self.version), post_body, headers) + self.opener.open.assert_called_once_with(mock_request.return_value) + self.assertEqual(content, s) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with( + None, None, None) + def testDownloadReportCheckFormat_CSVStringSuccess(self): output_file = io.StringIO() @@ -359,7 +414,7 @@ def testDownloadReportWithAwql(self): post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers - content = u'CONTENT STRING' + content = u'CONTENT STRING 广告客户' fake_request = io.StringIO() if PYTHON2 else io.BytesIO() fake_request.write(content if PYTHON2 else bytes(content, 'utf-8')) fake_request.seek(0) From b3a12c6d4801fc8bde4e951c7241128111b71b66 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Fri, 22 May 2015 15:01:16 -0400 Subject: [PATCH 007/180] Commiting latest changes. From 0b0452e327537f3bf3c5f6779ce987a80a9da4d1 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 9 Jul 2015 10:11:10 -0400 Subject: [PATCH 008/180] AdWords v201506 release --- ChangeLog | 6 + README.md | 2 +- examples/adwords/v201506/__init__.py | 15 + .../v201506/account_management/__init__.py | 15 + .../account_management/create_account.py | 67 +++ .../account_management/get_account_changes.py | 100 ++++ .../get_account_hierarchy.py | 97 ++++ .../v201506/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 225 ++++++++ .../add_ad_group_bid_modifier.py | 78 +++ .../add_click_to_download_ad.py | 114 ++++ .../add_text_ad_with_upgraded_urls.py | 114 ++++ .../create_and_attach_shared_keyword_set.py | 132 +++++ ...ind_and_remove_criteria_from_shared_set.py | 158 ++++++ .../get_ad_group_bid_modifier.py | 76 +++ .../upload_offline_conversions.py | 101 ++++ .../use_shared_bidding_strategy.py | 176 ++++++ .../v201506/basic_operations/__init__.py | 15 + .../v201506/basic_operations/add_ad_groups.py | 116 ++++ .../v201506/basic_operations/add_campaigns.py | 131 +++++ .../v201506/basic_operations/add_keywords.py | 97 ++++ .../v201506/basic_operations/add_text_ads.py | 98 ++++ .../v201506/basic_operations/get_ad_groups.py | 80 +++ .../v201506/basic_operations/get_campaigns.py | 77 +++ .../get_campaigns_with_awql.py | 68 +++ .../v201506/basic_operations/get_keywords.py | 81 +++ .../v201506/basic_operations/get_text_ads.py | 85 +++ .../v201506/basic_operations/pause_ad.py | 65 +++ .../v201506/basic_operations/remove_ad.py | 66 +++ .../basic_operations/remove_ad_group.py | 62 ++ .../basic_operations/remove_campaign.py | 62 ++ .../basic_operations/remove_keyword.py | 72 +++ .../basic_operations/update_ad_group.py | 62 ++ .../basic_operations/update_campaign.py | 62 ++ .../basic_operations/update_keyword.py | 87 +++ .../v201506/campaign_management/__init__.py | 15 + .../add_campaign_labels.py | 70 +++ .../campaign_management/add_experiment.py | 132 +++++ .../add_keywords_in_bulk.py | 141 +++++ .../get_all_disapproved_ads.py | 78 +++ .../get_all_disapproved_ads_with_awql.py | 67 +++ .../get_campaigns_by_label.py | 88 +++ .../campaign_management/promote_experiment.py | 65 +++ .../campaign_management/set_ad_parameters.py | 107 ++++ .../set_criterion_bid_modifier.py | 82 +++ .../campaign_management/validate_text_ad.py | 91 +++ .../v201506/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 124 ++++ .../handle_policy_violation_error.py | 117 ++++ .../adwords/v201506/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 162 ++++++ .../v201506/extensions/add_site_links.py | 128 +++++ .../extensions/add_site_links_using_feeds.py | 231 ++++++++ .../adwords/v201506/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 533 ++++++++++++++++++ .../v201506/migration/upgrade_ad_url.py | 82 +++ examples/adwords/v201506/misc/__init__.py | 15 + .../v201506/misc/get_all_images_and_videos.py | 89 +++ examples/adwords/v201506/misc/upload_image.py | 70 +++ .../adwords/v201506/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 137 +++++ .../get_keyword_bid_simulations.py | 86 +++ .../v201506/optimization/get_keyword_ideas.py | 95 ++++ .../adwords/v201506/remarketing/__init__.py | 15 + .../v201506/remarketing/add_audience.py | 107 ++++ .../remarketing/add_conversion_tracker.py | 77 +++ .../remarketing/add_rule_based_user_lists.py | 186 ++++++ .../adwords/v201506/reporting/__init__.py | 15 + .../reporting/download_criteria_report.py | 65 +++ .../download_criteria_report_as_stream.py | 81 +++ ...oad_criteria_report_as_stream_with_awql.py | 86 +++ .../download_criteria_report_as_string.py | 63 +++ ...oad_criteria_report_as_string_with_awql.py | 60 ++ .../download_criteria_report_with_awql.py | 64 +++ .../v201506/reporting/get_report_fields.py | 56 ++ examples/adwords/v201506/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 285 ++++++++++ .../v201506/shopping/add_product_scope.py | 107 ++++ .../v201506/shopping/add_shopping_campaign.py | 124 ++++ .../shopping/get_product_category_taxonomy.py | 99 ++++ .../adwords/v201506/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 165 ++++++ .../add_demographic_targeting_criteria.py | 99 ++++ .../get_campaign_targeting_criteria.py | 89 +++ .../get_targetable_languages_and_carriers.py | 60 ++ .../v201506/targeting/lookup_location.py | 86 +++ examples/adxbuyer/v201506/__init__.py | 15 + .../v201506/basic_operations/__init__.py | 15 + .../v201506/basic_operations/add_ad_groups.py | 91 +++ .../v201506/basic_operations/add_campaigns.py | 123 ++++ .../basic_operations/add_placements.py | 90 +++ .../add_third_party_redirect_ad.py | 102 ++++ .../basic_operations/get_placements.py | 78 +++ .../get_third_party_redirect_ads.py | 83 +++ .../basic_operations/remove_placement.py | 71 +++ .../basic_operations/update_placement.py | 83 +++ .../v201506/campaign_management/__init__.py | 15 + .../add_placements_in_bulk.py | 138 +++++ .../v201506/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 117 ++++ ...et_all_custom_targeting_keys_and_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- googleads/adwords.py | 176 ++++-- googleads/common.py | 3 +- setup.py | 22 +- tests/adwords_test.py | 52 +- 108 files changed, 8974 insertions(+), 84 deletions(-) create mode 100644 examples/adwords/v201506/__init__.py create mode 100644 examples/adwords/v201506/account_management/__init__.py create mode 100755 examples/adwords/v201506/account_management/create_account.py create mode 100755 examples/adwords/v201506/account_management/get_account_changes.py create mode 100755 examples/adwords/v201506/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201506/advanced_operations/__init__.py create mode 100755 examples/adwords/v201506/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201506/advanced_operations/upload_offline_conversions.py create mode 100755 examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201506/basic_operations/__init__.py create mode 100755 examples/adwords/v201506/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201506/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201506/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201506/basic_operations/add_text_ads.py create mode 100755 examples/adwords/v201506/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201506/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201506/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201506/basic_operations/get_text_ads.py create mode 100755 examples/adwords/v201506/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201506/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201506/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201506/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201506/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201506/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201506/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201506/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201506/campaign_management/__init__.py create mode 100755 examples/adwords/v201506/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201506/campaign_management/add_experiment.py create mode 100755 examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py create mode 100755 examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201506/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201506/campaign_management/promote_experiment.py create mode 100755 examples/adwords/v201506/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201506/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201506/error_handling/__init__.py create mode 100755 examples/adwords/v201506/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201506/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201506/extensions/__init__.py create mode 100755 examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201506/extensions/add_site_links.py create mode 100755 examples/adwords/v201506/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201506/migration/__init__.py create mode 100755 examples/adwords/v201506/migration/migrate_to_extension_settings.py create mode 100755 examples/adwords/v201506/migration/upgrade_ad_url.py create mode 100644 examples/adwords/v201506/misc/__init__.py create mode 100755 examples/adwords/v201506/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201506/misc/upload_image.py create mode 100644 examples/adwords/v201506/optimization/__init__.py create mode 100755 examples/adwords/v201506/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201506/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201506/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201506/remarketing/__init__.py create mode 100755 examples/adwords/v201506/remarketing/add_audience.py create mode 100755 examples/adwords/v201506/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201506/remarketing/add_rule_based_user_lists.py create mode 100644 examples/adwords/v201506/reporting/__init__.py create mode 100755 examples/adwords/v201506/reporting/download_criteria_report.py create mode 100755 examples/adwords/v201506/reporting/download_criteria_report_as_stream.py create mode 100755 examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201506/reporting/download_criteria_report_as_string.py create mode 100755 examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201506/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201506/reporting/get_report_fields.py create mode 100644 examples/adwords/v201506/shopping/__init__.py create mode 100755 examples/adwords/v201506/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201506/shopping/add_product_scope.py create mode 100755 examples/adwords/v201506/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201506/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201506/targeting/__init__.py create mode 100755 examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201506/targeting/lookup_location.py create mode 100644 examples/adxbuyer/v201506/__init__.py create mode 100644 examples/adxbuyer/v201506/basic_operations/__init__.py create mode 100755 examples/adxbuyer/v201506/basic_operations/add_ad_groups.py create mode 100755 examples/adxbuyer/v201506/basic_operations/add_campaigns.py create mode 100755 examples/adxbuyer/v201506/basic_operations/add_placements.py create mode 100755 examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py create mode 100755 examples/adxbuyer/v201506/basic_operations/get_placements.py create mode 100755 examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py create mode 100755 examples/adxbuyer/v201506/basic_operations/remove_placement.py create mode 100755 examples/adxbuyer/v201506/basic_operations/update_placement.py create mode 100644 examples/adxbuyer/v201506/campaign_management/__init__.py create mode 100755 examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py create mode 100644 examples/adxbuyer/v201506/error_handling/__init__.py create mode 100755 examples/adxbuyer/v201506/error_handling/handle_partial_failures.py diff --git a/ChangeLog b/ChangeLog index 83ba0e86..76392266 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +3.5.0 - 6/26/2015 +* Added support for v201506 of the AdWords Client Library. +* Reporting parameters in ReportDownloader utility now in **kwargs. +* Added new "include_zero_impressions" reporting parameter as keyword argument + for ReportDownloader utility methods. + 3.4.1 - 5/22/2015 * Fixed issue #55 * Fixed issue #57 diff --git a/README.md b/README.md index 4b198efa..14fb84ce 100644 --- a/README.md +++ b/README.md @@ -127,4 +127,4 @@ suds_client.service.mutate([operation]) ##Authors: - jdilallo@google.com (Joseph DiLallo) + msaniscalchi@google.com (Mark Saniscalchi) diff --git a/examples/adwords/v201506/__init__.py b/examples/adwords/v201506/__init__.py new file mode 100644 index 00000000..41f5a52e --- /dev/null +++ b/examples/adwords/v201506/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201506/account_management/__init__.py b/examples/adwords/v201506/account_management/__init__.py new file mode 100644 index 00000000..fb8c03ea --- /dev/null +++ b/examples/adwords/v201506/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201506/account_management/create_account.py b/examples/adwords/v201506/account_management/create_account.py new file mode 100755 index 00000000..273f311b --- /dev/null +++ b/examples/adwords/v201506/account_management/create_account.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2015 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 illustrates how to create an account. + +Note by default this account will only be accessible via parent MCC. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CreateAccountService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from datetime import datetime + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201506') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201506/account_management/get_account_changes.py b/examples/adwords/v201506/account_management/get_account_changes.py new file mode 100755 index 00000000..2515b979 --- /dev/null +++ b/examples/adwords/v201506/account_management/get_account_changes.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CustomerSyncService.get +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import datetime + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201506') + campaign_service = client.GetService('CampaignService', version='v201506') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + print ' Added ad extensions: %s' % data.get('addedAdExtensions') + print ' Removed ad extensions: %s' % data.get('deletedAdExtensions') + print (' Added campaign criteria: %s' + % data.get('addedCampaignCriteria')) + print (' Removed campaign criteria: %s' + % data.get('deletedCampaignCriteria')) + if data.get('changedAdGroups'): + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + print ' Changed ads: %s' % ad_group_data['changedAds'] + print (' Changed criteria: %s' + % ad_group_data['changedCriteria']) + print (' Removed criteria: %s' + % ad_group_data['deletedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201506/account_management/get_account_hierarchy.py b/examples/adwords/v201506/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..e901c6a9 --- /dev/null +++ b/examples/adwords/v201506/account_management/get_account_hierarchy.py @@ -0,0 +1,97 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the account hierarchy under the current account. + +Note: this code example won't work with test accounts. See +https://developers.google.com/adwords/api/docs/test-accounts + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ServicedAccountService.get +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201506') + + # Construct selector to get all accounts. + selector = { + 'fields': ['CustomerId', 'Name'] + } + # Get serviced account graph. + graph = managed_customer_service.get(selector) + if 'entries' in graph and graph['entries']: + # Create map from customerId to parent and child links. + child_links = {} + parent_links = {} + if 'links' in graph: + for link in graph['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Create map from customerID to account and find root account. + accounts = {} + root_account = None + for account in graph['entries']: + accounts[account['customerId']] = account + if account['customerId'] not in parent_links: + root_account = account + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + else: + print 'No serviced accounts were found' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201506/advanced_operations/__init__.py b/examples/adwords/v201506/advanced_operations/__init__.py new file mode 100644 index 00000000..7e57b8b3 --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201506/advanced_operations/add_ad_customizer.py b/examples/adwords/v201506/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..1c85f1fd --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/add_ad_customizer.py @@ -0,0 +1,225 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +Tags: AdCustomizerFeedService.mutate, AdGroupAdService.mutate +Tags: FeedItemService.mutate +""" + +__author__ = 'api.msaniscalchi@gmail.com (Mark Saniscalchi)' + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates TextAds that use ad customizations for the specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add TextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no TextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService') + + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'description1': 'Only {=%s.Price}' % feed_name, + 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com' + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..b5be64fe --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupBidModifierService.mutate +""" + +__author__ = 'Joseph DiLallo' + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201506') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..fb6a9c2b --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,114 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.mutate +Api: AdWordsOnly +""" + +__author__ = 'Joseph DiLallo' + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad to ad group ID \'%s\' ' + 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..cca69d0c --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -0,0 +1,114 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a text add that uses advanced features of upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.mutate +""" + +__author__ = 'Mark Saniscalchi' + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Create the text ad + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print ('AdGroupAd with ID %s and display URL \'%s\'was added.' + % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..a0b0dce9 --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,132 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignSharedSetService.mutate, SharedCriterionService.mutate, + SharedSetService.mutate +""" + +__author__ = 'Mark Saniscalchi' + +import uuid + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201506') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201506') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201506') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..e72ccd64 --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,158 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignSharedSetService.get, SharedCriterionService.get, + SharedCriterionService.mutate +""" + +__author__ = 'Mark Saniscalchi' + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201506') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201506') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if page['entries']: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..57397379 --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupBidModifierService.get +""" + +__author__ = 'Joseph DiLallo' + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201506') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py new file mode 100755 index 00000000..c4782d27 --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py @@ -0,0 +1,101 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ConversionTrackerService.mutate, OfflineConversionFeedService.mutate +""" + +__author__ = 'Joseph DiLallo' + +from googleads import adwords + + +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + conversion_tracker_service = client.GetService('ConversionTrackerService', + version='v201506') + + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201506') + + # Once created, this entry will be visible under + # Tools and Analysis->Conversion and will have "Source = Import". + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'category': 'PAGE_VIEW', + 'name': conversion_name, + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90' + } + + upload_conversion_operation = { + 'operator': 'ADD', + 'operand': upload_conversion + } + + response = conversion_tracker_service.mutate( + [upload_conversion_operation]) + new_upload_conversion = response['value'] + + print ('New upload conversion type with name \'%s\' and ID \'%s\' was ' + 'created.' % (new_upload_conversion['name'], + new_upload_conversion['id'])) + + # Associate offline conversions with the upload conversion we created. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..ad044d12 --- /dev/null +++ b/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,176 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: BiddingStrategyService.mutate +Tags: BudgetService.mutate, CampaignService.mutate +""" + +__author__ = 'Joseph DiLallo' + +import uuid + +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201506') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201506') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'period': 'DAILY', + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201506') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201506/basic_operations/__init__.py b/examples/adwords/v201506/basic_operations/__init__.py new file mode 100644 index 00000000..80acbea9 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201506/basic_operations/add_ad_groups.py b/examples/adwords/v201506/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..12abf5a1 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/add_ad_groups.py @@ -0,0 +1,116 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README.. + +Tags: AdGroupService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import uuid + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201506') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings - these settings only affect + # serving for the Display Network. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/basic_operations/add_campaigns.py b/examples/adwords/v201506/basic_operations/add_campaigns.py new file mode 100755 index 00000000..a7671bba --- /dev/null +++ b/examples/adwords/v201506/basic_operations/add_campaigns.py @@ -0,0 +1,131 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.mutate +Tags: BudgetService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import datetime +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201506') + budget_service = client.GetService('BudgetService', version='v201506') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'period': 'DAILY' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/basic_operations/add_keywords.py b/examples/adwords/v201506/basic_operations/add_keywords.py new file mode 100755 index 00000000..874d507a --- /dev/null +++ b/examples/adwords/v201506/basic_operations/add_keywords.py @@ -0,0 +1,97 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/add_text_ads.py b/examples/adwords/v201506/basic_operations/add_text_ads.py new file mode 100755 index 00000000..462fd680 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/add_text_ads.py @@ -0,0 +1,98 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds several text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct operations and add ads. + # If needed, you could specify an exemption request here, e.g.: + # 'exemptionRequests': [{ + # # This comes back in a PolicyViolationError. + # 'key' { + # 'policyName': '...', + # 'violatingText': '...' + # } + # }] + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + }, + # Optional fields. + 'status': 'PAUSED' + } + }, + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Enjoy your stay at Red Planet.', + 'description2': 'Buy your tickets now!', + 'headline': 'Luxury Cruise to Mars' + } + } + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad with id \'%s\' and of type \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/get_ad_groups.py b/examples/adwords/v201506/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..00532ccf --- /dev/null +++ b/examples/adwords/v201506/basic_operations/get_ad_groups.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2015 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupService.get +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201506') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/basic_operations/get_campaigns.py b/examples/adwords/v201506/basic_operations/get_campaigns.py new file mode 100755 index 00000000..79926ab8 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/get_campaigns.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2015 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.get +""" + +__author__ = 'Joseph DiLallo' + +import logging +import time + +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201506') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..a7fc93dc --- /dev/null +++ b/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,68 @@ +#!/usr/bin/python +# +# Copyright 2015 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.query +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import time + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201506') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201506/basic_operations/get_keywords.py b/examples/adwords/v201506/basic_operations/get_keywords.py new file mode 100755 index 00000000..6d99c0a0 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/get_keywords.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2015 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.get +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['AdGroupId', 'Id', 'Text', 'KeywordMatchType', 'PlacementUrl'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for criterion in page['entries']: + print ('Keyword ad group criterion with ad group id \'%s\', criterion ' + 'id \'%s\', text \'%s\', and match type \'%s\' was found.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/basic_operations/get_text_ads.py b/examples/adwords/v201506/basic_operations/get_text_ads.py new file mode 100755 index 00000000..e2376f6e --- /dev/null +++ b/examples/adwords/v201506/basic_operations/get_text_ads.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2015 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 text ads for a given ad group. + +To add an ad, run add_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.get +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/pause_ad.py b/examples/adwords/v201506/basic_operations/pause_ad.py new file mode 100755 index 00000000..ebf11f50 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/pause_ad.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201506/basic_operations/remove_ad.py b/examples/adwords/v201506/basic_operations/remove_ad.py new file mode 100755 index 00000000..554e902a --- /dev/null +++ b/examples/adwords/v201506/basic_operations/remove_ad.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2015 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201506/basic_operations/remove_ad_group.py b/examples/adwords/v201506/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..fa2e8437 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/remove_ad_group.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201506') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/remove_campaign.py b/examples/adwords/v201506/basic_operations/remove_campaign.py new file mode 100755 index 00000000..cccae255 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/remove_campaign.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201506') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/basic_operations/remove_keyword.py b/examples/adwords/v201506/basic_operations/remove_keyword.py new file mode 100755 index 00000000..266a8020 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/remove_keyword.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2015 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201506/basic_operations/update_ad_group.py b/examples/adwords/v201506/basic_operations/update_ad_group.py new file mode 100755 index 00000000..c7a01151 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/update_ad_group.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201506') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/update_campaign.py b/examples/adwords/v201506/basic_operations/update_campaign.py new file mode 100755 index 00000000..2162e056 --- /dev/null +++ b/examples/adwords/v201506/basic_operations/update_campaign.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201506') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/basic_operations/update_keyword.py b/examples/adwords/v201506/basic_operations/update_keyword.py new file mode 100755 index 00000000..51eaa44a --- /dev/null +++ b/examples/adwords/v201506/basic_operations/update_keyword.py @@ -0,0 +1,87 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201506/campaign_management/__init__.py b/examples/adwords/v201506/campaign_management/__init__.py new file mode 100644 index 00000000..db098bda --- /dev/null +++ b/examples/adwords/v201506/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201506/campaign_management/add_campaign_labels.py b/examples/adwords/v201506/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..8fee3a55 --- /dev/null +++ b/examples/adwords/v201506/campaign_management/add_campaign_labels.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.mutateLabel +""" + +__author__ = 'Mark Saniscalchi' + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201506') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201506/campaign_management/add_experiment.py b/examples/adwords/v201506/campaign_management/add_experiment.py new file mode 100755 index 00000000..534a6c9d --- /dev/null +++ b/examples/adwords/v201506/campaign_management/add_experiment.py @@ -0,0 +1,132 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates an experiment. + +The created experiment is using a query percentage of 10, which defines what +fraction of auctions should go to the control split (90%) vs. the experiment +split (10%), then adds experimental bid changes for an ad group, and adds an +experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad +groups, run get_ad_groups.py. To get keywords, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ExperimentService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import datetime +import uuid + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, campaign_id, ad_group_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201506') + ad_group_service = client.GetService('AdGroupService', version='v201506') + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct operations and add experiment. + tomorrow = datetime.datetime.now() + datetime.timedelta(1) + thirty_days = datetime.datetime.now() + datetime.timedelta(30) + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), + 'queryPercentage': '10', + 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), + # Optional fields. + 'status': 'ENABLED', + 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was added.' + % (experiment['name'], experiment['id'])) + + # Construct operations and update ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'experimentData': { + 'xsi_type': 'AdGroupExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'MODIFIED', + 'experimentBidMultipliers': { + 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', + 'maxCpcMultiplier': { + 'multiplier': '0.5' + } + } + } + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' + 'experiment.' % (ad_group['name'], ad_group['id'])) + + # Construct operations and add ad group crierion. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + }, + 'experimentData': { + 'xsi_type': 'BiddableAdGroupCriterionExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'EXPERIMENT_ONLY' + } + } + }] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\' and criterion ' + 'id \'%s\' was added to the experiment.' + % (criterion['adGroupId'], criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py new file mode 100755 index 00000000..d1e25e14 --- /dev/null +++ b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py @@ -0,0 +1,141 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code sample illustrates how to perform asynchronous requests. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: MutateJobService.mutate +Tags: MutateJobService.get +Tags: MutateJobService.getResult +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import random +import re +import time + +from googleads import adwords +from googleads import errors + + +RETRY_INTERVAL = 10 +RETRIES_COUNT = 30 +KEYWORD_NUMBER = 100 +INDEX_REGEX = r'operations\[(\d+)\].operand' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + mutate_job_service = client.GetService('MutateJobService', version='v201506') + + # Create list of all operations for the job. + operations = [] + + # Create AdGroupCriterionOperations to add keywords. + for i in range(KEYWORD_NUMBER): + keyword = 'mars%d' % i + if random.randint(1, 10) == 1: + keyword += '!!!' + operations.append({ + 'xsi_type': 'AdGroupCriterionOperation', + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': keyword + } + } + }) + + # You can specify up to 3 job IDs that must successfully complete before + # this job can be processed. + policy = { + 'prerequisiteJobIds': [] + } + + # Call mutate to create a new job. + response = mutate_job_service.mutate(operations, policy) + + if not response: + raise errors.GoogleAdsError('Failed to submit a job; aborting.') + + job_id = response['id'] + print 'Job with ID %s was successfully created.' % job_id + + # Create selector to retrieve job status and wait for it to complete. + selector = { + 'xsi_type': 'BulkMutateJobSelector', + 'jobIds': [job_id] + } + + time.sleep(RETRY_INTERVAL) + # Poll for job status until it's finished. + print 'Retrieving job status...' + for i in range(RETRIES_COUNT): + job_status_response = mutate_job_service.get(selector) + status = job_status_response[0]['status'] + if status in ('COMPLETED', 'FAILED'): + break + print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % + (i, status, RETRY_INTERVAL)) + time.sleep(RETRY_INTERVAL) + + if status == 'FAILED': + raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % + job_status_response[0]['failure_reason']) + if status in ('PROCESSING', 'PENDING'): + raise errors.GoogleAdsError('Job did not complete within %d seconds' % + (RETRY_INTERVAL * (RETRIES_COUNT - 1))) + + # Status must be COMPLETED. + # Get the job result. Here we re-use the same selector. + result_response = mutate_job_service.getResult(selector) + + # Output results. + index = 0 + for result in result_response['SimpleMutateResult']['results']: + if 'PlaceHolder' in result: + print 'Operation [%d] - FAILED' % index + else: + print 'Operation [%d] - SUCCEEDED' % index + index += 1 + + # Output errors + for error in result_response['SimpleMutateResult']['errors']: + index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) + reason = error['reason'] + keyword = operations[index]['operand']['criterion']['text'] + print ('ERROR - keyword \'%s\' failed due to \'%s\'' % + (keyword, reason)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..d507a02f --- /dev/null +++ b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2015 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.get +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct selector and get all ads for a given ad group. + selector = { + 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'AdGroupCreativeApprovalStatus', + 'operator': 'IN', + 'values': ['DISAPPROVED'] + } + ] + } + ads = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..ad9b73fc --- /dev/null +++ b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2015 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.get +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, AdGroupAdDisapprovalReasons ' + 'WHERE CampaignId = %s AND ' + 'AdGroupCreativeApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % campaign_id) + ads = ad_group_ad_service.query(query) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..85d371d9 --- /dev/null +++ b/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,88 @@ +#!/usr/bin/python +# +# Copyright 2015 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.get +""" + +__author__ = 'Mark Saniscalchi' + +import time + +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201506') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201506/campaign_management/promote_experiment.py b/examples/adwords/v201506/campaign_management/promote_experiment.py new file mode 100755 index 00000000..c2b48c6c --- /dev/null +++ b/examples/adwords/v201506/campaign_management/promote_experiment.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Copyright 2015 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 promotes an experiment. + +Promoting an experiment permanently applies all the experimental changes made to +its related ad groups, criteria and ads. To add an experiment, run +add_experiment.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ExperimentService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' + + +def main(client, experiment_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201506') + + # Construct operations and promote experiment. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': experiment_id, + 'status': 'PROMOTED' + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was promoted.' + % (experiment['name'], experiment['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201506/campaign_management/set_ad_parameters.py b/examples/adwords/v201506/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..a88f204b --- /dev/null +++ b/examples/adwords/v201506/campaign_management/set_ad_parameters.py @@ -0,0 +1,107 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2015 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.mutate, AdParamService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + ad_param_service = client.GetService('AdParamService', version='v201506') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': { + 'urls': ['http://www.example.com'] + }, + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..a6673363 --- /dev/null +++ b/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2015 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignCriterionService.mutate +""" + +__author__ = ('api.dklimkin@gmail.com (Danial Klimkin)', + 'Joseph DiLallo') + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201506') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201506/campaign_management/validate_text_ad.py b/examples/adwords/v201506/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..534772d5 --- /dev/null +++ b/examples/adwords/v201506/campaign_management/validate_text_ad.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2015 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 shows how to use validateOnly SOAP header. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct operations to add a text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': { + 'urls': ['http://www.example.com'] + }, + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'url': 'http://www.example.com', + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for all astronauts in orbit', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/error_handling/__init__.py b/examples/adwords/v201506/error_handling/__init__.py new file mode 100644 index 00000000..b5203c57 --- /dev/null +++ b/examples/adwords/v201506/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201506/error_handling/handle_partial_failures.py b/examples/adwords/v201506/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..a22f64ed --- /dev/null +++ b/examples/adwords/v201506/error_handling/handle_partial_failures.py @@ -0,0 +1,124 @@ +#!/usr/bin/python +# +# Copyright 2015 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import re + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) + if index: + print ('Keyword ad group criterion with ad group id \'%s\' and text ' + '\'%s\' triggered a failure for the following reason: \'%s\'.' + % (keywords[int(index[0])]['adGroupId'], + keywords[int(index[0])]['criterion']['text'], + error['errorString'])) + else: + print 'The following failure has occurred: \'%s\'.' % error['errorString'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/error_handling/handle_policy_violation_error.py b/examples/adwords/v201506/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..53640a42 --- /dev/null +++ b/examples/adwords/v201506/error_handling/handle_policy_violation_error.py @@ -0,0 +1,117 @@ +#!/usr/bin/python +# +# Copyright 2015 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.mutate +""" + +__author__ = 'Joseph DiLallo' + +import re + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201506') + + # Create text ad. + text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'TextAd', + 'headline': 'Mars Cruise!!!', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com', + } + } + } + + operations = [text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + if error['ApiError.Type'] == 'PolicyViolationError': + operation_index = re.findall(r'operations\[(.*)\]\.', + error['fieldPath']) + if operation_index: + operation = operations[int(operation_index[0])] + print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % + (operation['operand']['ad']['headline'], + 'exemptable' if error['isExemptable'] else 'non-exemptable', + error['externalPolicyName'])) + if error['isExemptable'].lower() == 'true': + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text ' + '\'%s\'.' % + (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({ + 'key': error['key'] + }) + else: + # Remove non-exemptable operation + print 'Removing the operation from the request.' + operations.delete(operation) + else: + # Non-policy error returned, re-throw exception. + raise e + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/extensions/__init__.py b/examples/adwords/v201506/extensions/__init__.py new file mode 100644 index 00000000..b4d63e00 --- /dev/null +++ b/examples/adwords/v201506/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..00741ce9 --- /dev/null +++ b/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,162 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CustomerFeedService.mutate, FeedService.mutate +""" + +__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', + 'Joseph DiLallo') + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201506').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201506') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201506/extensions/add_site_links.py b/examples/adwords/v201506/extensions/add_site_links.py new file mode 100755 index 00000000..4dd8520b --- /dev/null +++ b/examples/adwords/v201506/extensions/add_site_links.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignExtensionSettingService.mutate, CustomerService.get +Api: AdWordsOnly +""" + +__author__ = 'Mark Saniscalchi' + +from datetime import datetime + + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201506') + customer_service = client.GetService('CustomerService', version='v201506') + + customer_tz = timezone(customer_service.get()['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkUrl': 'http://www.example.com/storehours' + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkUrl': 'http://www.example.com/thanksgiving', + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt) + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkUrl': 'http://www.example.com/mobile/wifi', + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'} + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkUrl': 'http://www.example.com/happyhours', + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..cce0de02 --- /dev/null +++ b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py @@ -0,0 +1,231 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignFeedService.mutate, FeedItemService.mutate +Tags: FeedMappingService.mutate, FeedService.mutate +Api: AdWordsOnly +""" + +__author__ = 'Joseph DiLallo' + +import re +import uuid + +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_1_TEXT = '3' +PLACEHOLDER_FIELD_LINE_2_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201506') + feed_item_service = client.GetService('FeedItemService', version='v201506') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201506') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201506') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 1 Description'}, + {'type': 'STRING', 'name': 'Line 2 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_1_feed_attribute_id = feed['attributes'][2]['id'] + line_2_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % + (line_1_feed_attribute_id, line_2_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line1FeedId'] = line_1_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line1': 'Home line 1', 'line2': 'Home line 2'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line1': 'Support line 1', 'line2': 'Support line 2'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line1': 'Products line 1', 'line2': 'Products line 2'}, + {'text': 'About', 'finalUrls': 'http://www.example.com/about', + 'line1': 'About line 1', 'line2': 'About line 2'} + ] + + feed_items = [] + for item in items_data: + feed_items.append({ + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'stringValue': item['line1'] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + + # Optional: use the 'scheduling' key to specify time and days of the + # week for feed to deliver. This is a Beta feature. + }) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/migration/__init__.py b/examples/adwords/v201506/migration/__init__.py new file mode 100644 index 00000000..5de8ecca --- /dev/null +++ b/examples/adwords/v201506/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201506/migration/migrate_to_extension_settings.py b/examples/adwords/v201506/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..c54fc6e0 --- /dev/null +++ b/examples/adwords/v201506/migration/migrate_to_extension_settings.py @@ -0,0 +1,533 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: FeedService.get, FeedMappingService.get, FeedItemService.get +Tags: CampaignExtensionSettingService.mutate, CampaignFeedService.get, +Tags: CampaignFeedService.mutate +Api: AdWordsOnly +""" + +__author__ = 'Mark Saniscalchi' + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201506') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201506') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201506') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201506') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201506') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201506') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201506') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/migration/upgrade_ad_url.py b/examples/adwords/v201506/migration/upgrade_ad_url.py new file mode 100755 index 00000000..1a9c1b4f --- /dev/null +++ b/examples/adwords/v201506/migration/upgrade_ad_url.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2015 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 upgrades an ad to use upgraded URLs. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.get, AdGroupAdService.upgradeUrl +""" + +__author__ = 'Mark Saniscalchi' + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, adgroup_id, ad_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201506') + + selector = { + 'fields': ['Id', 'Url'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [ad_id] + } + ] + } + + page = adgroup_ad_service.get(selector) + + adgroup_ad = page['entries'][0] if page['entries'] else None + + if not adgroup_ad: + raise errors.GoogleAdsError('Ad not found.') + + ad_url_upgrade = { + 'adId': adgroup_ad['ad']['id'], + 'finalUrl': adgroup_ad['ad']['url'] + } + + adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] + + if adgroup_ad: + print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' + % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201506/misc/__init__.py b/examples/adwords/v201506/misc/__init__.py new file mode 100644 index 00000000..30d42e87 --- /dev/null +++ b/examples/adwords/v201506/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201506/misc/get_all_images_and_videos.py b/examples/adwords/v201506/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..428017d8 --- /dev/null +++ b/examples/adwords/v201506/misc/get_all_images_and_videos.py @@ -0,0 +1,89 @@ +#!/usr/bin/python +# +# Copyright 2015 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: MediaService.get +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201506') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/misc/upload_image.py b/examples/adwords/v201506/misc/upload_image.py new file mode 100755 index 00000000..267d14fe --- /dev/null +++ b/examples/adwords/v201506/misc/upload_image.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2015 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: MediaService.upload +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import base64 + +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201506') + + with open(image_filename, 'r') as image_handle: + image_data = base64.encodestring(image_handle.read()) + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201506/optimization/__init__.py b/examples/adwords/v201506/optimization/__init__.py new file mode 100644 index 00000000..2e0ca689 --- /dev/null +++ b/examples/adwords/v201506/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..b35e68b8 --- /dev/null +++ b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py @@ -0,0 +1,137 @@ +#!/usr/bin/python +# +# Copyright 2015 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: TrafficEstimatorService.get +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201506') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + selector = { + 'campaignEstimateRequests': [{ + 'adGroupEstimateRequests': [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }], + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ] + }] + } + estimates = traffic_estimator_service.get(selector) + + # Display results. + ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] + keyword_estimates = ad_group_estimate['keywordEstimates'] + for index in xrange(len(keyword_estimates)): + keyword = keyword_estimate_requests[index]['keyword'] + estimate = keyword_estimates[index] + if keyword_estimate_requests[index].get('isNegative', False): + continue + + # Find the mean of the min and max values. + mean_avg_cpc = (calc_mean(estimate['min']['averageCpc']['microAmount'], + estimate['max']['averageCpc']['microAmount']) + if 'averageCpc' in estimate['min'] else 'N/A') + mean_avg_pos = calc_mean(estimate['min']['averagePosition'], + estimate['max']['averagePosition']) + mean_clicks = calc_mean(estimate['min']['clicksPerDay'], + estimate['max']['clicksPerDay']) + mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], + estimate['max']['totalCost']['microAmount']) + + print ('Results for the keyword with text \'%s\' and match type \'%s\':' + % (keyword['text'], keyword['matchType'])) + print ' Estimated average CPC: %s' % mean_avg_cpc + print ' Estimated ad position: %s' % mean_avg_pos + print ' Estimated daily clicks: %s' % mean_clicks + print ' Estimated daily cost: %s' % mean_total_cost + + +def fmt_mean(mean): + if mean: + return '%.2f' % mean + else: + return None + + +def calc_mean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..34a18888 --- /dev/null +++ b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2015 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: BidLandscapeService.getBidLandscape +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201506') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201506/optimization/get_keyword_ideas.py b/examples/adwords/v201506/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..5b9d7757 --- /dev/null +++ b/examples/adwords/v201506/optimization/get_keyword_ideas.py @@ -0,0 +1,95 @@ +#!/usr/bin/python +# +# Copyright 2015 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: TargetingIdeaService.get +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201506') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/remarketing/__init__.py b/examples/adwords/v201506/remarketing/__init__.py new file mode 100644 index 00000000..b39776a8 --- /dev/null +++ b/examples/adwords/v201506/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201506/remarketing/add_audience.py b/examples/adwords/v201506/remarketing/add_audience.py new file mode 100755 index 00000000..2939dd56 --- /dev/null +++ b/examples/adwords/v201506/remarketing/add_audience.py @@ -0,0 +1,107 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: UserListService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201506') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201506') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/remarketing/add_conversion_tracker.py b/examples/adwords/v201506/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..7801ab0e --- /dev/null +++ b/examples/adwords/v201506/remarketing/add_conversion_tracker.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ConversionTrackerService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201506') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'markupLanguage': 'HTML', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'isProductAdsChargeable': 'true', + 'productAdsChargeableConversionWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..b54feeaf --- /dev/null +++ b/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,186 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdwordsUserListService.mutate +""" + +__author__ = 'Mark Saniscalchi' + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201506') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords will logically OR the + # groups together. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/reporting/__init__.py b/examples/adwords/v201506/reporting/__init__.py new file mode 100644 index 00000000..85eee62f --- /dev/null +++ b/examples/adwords/v201506/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201506/reporting/download_criteria_report.py b/examples/adwords/v201506/reporting/download_criteria_report.py new file mode 100755 index 00000000..21420b9e --- /dev/null +++ b/examples/adwords/v201506/reporting/download_criteria_report.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ReportDefinitionService.mutate +Api: AdWordsOnly +""" + +__author__ = 'Mark Saniscalchi' + +import logging +import sys + +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201506') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py new file mode 100755 index 00000000..3543c6f5 --- /dev/null +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ReportDefinitionService.mutate +Api: AdWordsOnly +""" + +__author__ = 'Mark Saniscalchi' + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201506') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..a0c5aaa7 --- /dev/null +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ReportDefinitionService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +import logging +import StringIO +import sys + + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201506') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py new file mode 100755 index 00000000..cbc6e56c --- /dev/null +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ReportDefinitionService.mutate +Api: AdWordsOnly +""" + +__author__ = 'Mark Saniscalchi' + +import logging + +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201506') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..800a8076 --- /dev/null +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ReportDefinitionService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201506') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..a2f69a59 --- /dev/null +++ b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ReportDefinitionService.mutate +Api: AdWordsOnly +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client, path): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201506') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + with open(path, 'w') as output_file: + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', output_file, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=False) + + print 'Report was downloaded to \'%s\'.' % path + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, PATH) diff --git a/examples/adwords/v201506/reporting/get_report_fields.py b/examples/adwords/v201506/reporting/get_report_fields.py new file mode 100755 index 00000000..eeb64ccb --- /dev/null +++ b/examples/adwords/v201506/reporting/get_report_fields.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# +# Copyright 2015 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ReportDefinitionService.getReportFields +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201506') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201506/shopping/__init__.py b/examples/adwords/v201506/shopping/__init__.py new file mode 100644 index 00000000..96422728 --- /dev/null +++ b/examples/adwords/v201506/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201506/shopping/add_product_partition_tree.py b/examples/adwords/v201506/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..f36770fb --- /dev/null +++ b/examples/adwords/v201506/shopping/add_product_partition_tree.py @@ -0,0 +1,285 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +""" + +__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', + 'Joseph DiLallo') + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) + diff --git a/examples/adwords/v201506/shopping/add_product_scope.py b/examples/adwords/v201506/shopping/add_product_scope.py new file mode 100755 index 00000000..d8376d45 --- /dev/null +++ b/examples/adwords/v201506/shopping/add_product_scope.py @@ -0,0 +1,107 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignCriterionService.mutate +""" + +__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', + 'Joseph DiLallo') + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201506') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/shopping/add_shopping_campaign.py b/examples/adwords/v201506/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..21663a93 --- /dev/null +++ b/examples/adwords/v201506/shopping/add_shopping_campaign.py @@ -0,0 +1,124 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.mutate, AdGroupService.mutate, AdGroupAdService.mutate +""" + +__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', + 'Joseph DiLallo') + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id): + campaign_service = client.GetService('CampaignService', version='v201506') + ad_group_service = client.GetService('AdGroupService', version='v201506') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Set shared budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + adgroup = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group_result = ad_group_service.mutate(adgroup_operations) + + for adgroup in ad_group_result['value']: + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (adgroup['name'], adgroup['id'])) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': adgroup['id'], + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201506/shopping/get_product_category_taxonomy.py b/examples/adwords/v201506/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..da3a7d23 --- /dev/null +++ b/examples/adwords/v201506/shopping/get_product_category_taxonomy.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2015 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ConstantDataService.getProductBiddingCategoryData +""" + +__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', + 'Joseph DiLallo') + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201506') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/targeting/__init__.py b/examples/adwords/v201506/targeting/__init__.py new file mode 100644 index 00000000..2c027ccc --- /dev/null +++ b/examples/adwords/v201506/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..3476019e --- /dev/null +++ b/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,165 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignCriterionService.mutate +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201506') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create location groups. The IDs can be found in the documentation or + # retrieved with the LocationCriterionService. + florida_tier3 = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'IncomeOperand', + # Tiers are numbered 1-10, and represent 10% segments of earners. + # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. + # Tiers 6 through 10 are grouped into TIER_6_TO_10. + 'tier': 'TIER_3' + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + }, + } + florida_downtown = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'PlacesOfInterestOperand', + # Other valid options: AIRPORT, UNIVERSITY. + 'category': 'DOWNTOWN', + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + } + } + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish, florida_tier3, + florida_downtown] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..0ff8e703 --- /dev/null +++ b/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +""" + +__author__ = 'Joseph Dilallo' + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..3e2e65d5 --- /dev/null +++ b/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,89 @@ +#!/usr/bin/python +# +# Copyright 2015 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignCriterionService.get +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201506') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..88532997 --- /dev/null +++ b/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2015 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: ConstantDataService.getLanguageCriterion +Tags: ConstantDataService.getCarrierCriterion +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201506') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201506/targeting/lookup_location.py b/examples/adwords/v201506/targeting/lookup_location.py new file mode 100755 index 00000000..4de1b3eb --- /dev/null +++ b/examples/adwords/v201506/targeting/lookup_location.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2015 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: LocationCriterionService.get +""" + +__author__ = ('api.kwinter@gmail.com (Kevin Winter)' + 'Joseph DiLallo') + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201506') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adxbuyer/v201506/__init__.py b/examples/adxbuyer/v201506/__init__.py new file mode 100644 index 00000000..55fdaeac --- /dev/null +++ b/examples/adxbuyer/v201506/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Examples for DoubleClick Ad Exchange Buyer SOAP API.""" diff --git a/examples/adxbuyer/v201506/basic_operations/__init__.py b/examples/adxbuyer/v201506/basic_operations/__init__.py new file mode 100644 index 00000000..80acbea9 --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Basic operations examples.""" diff --git a/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..36643b17 --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2013 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupService.mutate +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +import uuid + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201506') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpmBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + } + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpmBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/add_campaigns.py b/examples/adxbuyer/v201506/basic_operations/add_campaigns.py new file mode 100755 index 00000000..f869d252 --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/add_campaigns.py @@ -0,0 +1,123 @@ +#!/usr/bin/python +# +# Copyright 2013 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 adds campaigns. To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: CampaignService.mutate +Tags: BudgetService.mutate +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +import datetime +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201506') + budget_service = client.GetService('BudgetService', version='v201506') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'period': 'DAILY' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'DISPLAY', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPM', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'settings': [{ + 'xsi_type': 'RealTimeBiddingSetting', + 'optIn': 'true' + }], + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + } + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise Banners #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'DISPLAY', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPM', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'settings': [{ + 'xsi_type': 'RealTimeBiddingSetting', + 'optIn': 'true' + }], + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adxbuyer/v201506/basic_operations/add_placements.py b/examples/adxbuyer/v201506/basic_operations/add_placements.py new file mode 100755 index 00000000..73a1eb83 --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/add_placements.py @@ -0,0 +1,90 @@ +#!/usr/bin/python +# +# Copyright 2013 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct keyword ad group criterion object. + placement1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'url': 'http://mars.google.com' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'destinationUrl': 'http://example.com/mars' + } + + placement2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'url': 'http://example.com/pluto' + }, + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': placement1 + }, + { + 'operator': 'ADD', + 'operand': placement2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Placement ad group criterion with ad group id \'%s\', criterion ' + 'id \'%s\', and url \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['url'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py new file mode 100755 index 00000000..0e7d3432 --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py @@ -0,0 +1,102 @@ +#!/usr/bin/python +# +# Copyright 2013 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 adds several third party ads to a given ad group. + +To get an ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.mutate +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct operations and add ads. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ThirdPartyRedirectAd', + 'name': 'Example third party ad #%s' % uuid.uuid4(), + 'url': 'http://www.example.com', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + # This field normally contains the javascript ad tag. + 'snippet': (''), + 'certifiedVendorFormatId': '232', + 'isCookieTargeted': 'false', + 'isUserInterestTargeted': 'false', + 'isTagged': 'false', + 'richMediaAdType': 'STANDARD', + 'expandingDirections': ['EXPANDING_UP', 'EXPANDING_DOWN'], + 'adAttributes': ['ROLL_OVER_TO_EXPAND'] + } + } + }, + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ThirdPartyRedirectAd', + 'name': 'Example third party ad #%s' % uuid.uuid4(), + 'url': 'http://www.example.com', + 'adDuration': '15000', + 'sourceUrl': ('http://ad.doubleclick.net/pfadx/N270.126913.' + '6102203221521/B3876671.21;dcadv=2215309;' + 'sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml'), + 'certifiedVendorFormatId': '303', + 'richMediaAdType': 'IN_STREAM_VIDEO' + } + } + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad with ID \'%s\' and of type \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/get_placements.py b/examples/adxbuyer/v201506/basic_operations/get_placements.py new file mode 100755 index 00000000..1ff485e3 --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/get_placements.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2013 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 group criteria in an account. + +To add placements, run add_placements.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.get +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['AdGroupId', 'Id', 'PlacementUrl'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['PLACEMENT'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for criterion in page['entries']: + print ('Placement ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\' and url \'%s\'.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['url'])) + else: + print 'No placements were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py new file mode 100755 index 00000000..5da3b45f --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py @@ -0,0 +1,83 @@ +#!/usr/bin/python +# +# Copyright 2013 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 third party ads for a given ad group. + +To add a third party ad, add_third_party_redirect_ad.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupAdService.get +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['THIRD_PARTY_REDIRECT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/remove_placement.py b/examples/adxbuyer/v201506/basic_operations/remove_placement.py new file mode 100755 index 00000000..f056f2b3 --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/remove_placement.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2013 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_placements.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/update_placement.py b/examples/adxbuyer/v201506/basic_operations/update_placement.py new file mode 100755 index 00000000..0821a436 --- /dev/null +++ b/examples/adxbuyer/v201506/basic_operations/update_placement.py @@ -0,0 +1,83 @@ +#!/usr/bin/python +# +# Copyright 2013 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 updates the bid of a placement. + +To add a placement, run add_placements.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_PLACEMENT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct operations and update bids. + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpmBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' had its bid set to \'%s\'.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['bids']['maxCpc']['amount']['microAmount'])) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adxbuyer/v201506/campaign_management/__init__.py b/examples/adxbuyer/v201506/campaign_management/__init__.py new file mode 100644 index 00000000..db098bda --- /dev/null +++ b/examples/adxbuyer/v201506/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Campaign management examples.""" diff --git a/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py new file mode 100755 index 00000000..031c83e5 --- /dev/null +++ b/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py @@ -0,0 +1,138 @@ +#!/usr/bin/python +# +# Copyright 2013 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. + +"""Illustrates how to perform asynchronous requests using the MutateJobService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: MutateJobService.mutate +Tags: MutateJobService.get +Tags: MutateJobService.getResult +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +import random +import re +import time + +from googleads import adwords +from googleads import errors + + +RETRY_INTERVAL = 10 +RETRIES_COUNT = 30 +PLACEMENT_NUMBER = 100 +INDEX_REGEX = r'operations\[(\d+)\].operand' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + mutate_job_service = client.GetService('MutateJobService', version='v201506') + + # Create list of all operations for the job. + operations = [] + + # Create AdGroupCriterionOperations to add placements. + for i in range(PLACEMENT_NUMBER): + url = 'www.example.com/mars%d' % i + if random.randint(1, 10) == 1: + url = 'NOT_@_URL' + operations.append({ + 'xsi_type': 'AdGroupCriterionOperation', + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'url': url + } + } + }) + + # You can specify up to 3 job IDs that must successfully complete before + # this job can be processed. + policy = { + 'prerequisiteJobIds': [] + } + + # Call mutate to create a new job. + response = mutate_job_service.mutate(operations, policy) + + if not response: + raise errors.GoogleAdsError('Failed to submit a job; aborting.') + + job_id = response['id'] + print 'Job with ID %s was successfully created.' % job_id + + # Create selector to retrieve job status and wait for it to complete. + selector = { + 'xsi_type': 'BulkMutateJobSelector', + 'jobIds': [job_id] + } + + time.sleep(RETRY_INTERVAL) + # Poll for job status until it's finished. + print 'Retrieving job status...' + for i in range(RETRIES_COUNT): + job_status_response = mutate_job_service.get(selector) + status = job_status_response[0]['status'] + if status in ('COMPLETED', 'FAILED'): + break + print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % + (i, status, RETRY_INTERVAL)) + time.sleep(RETRY_INTERVAL) + + if status == 'FAILED': + raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % + job_status_response[0]['failure_reason']) + if status in ('PROCESSING', 'PENDING'): + raise errors.GoogleAdsError('Job did not complete within %d seconds' % + (RETRY_INTERVAL * (RETRIES_COUNT - 1))) + + # Status must be COMPLETED. + # Get the job result. Here we re-use the same selector. + result_response = mutate_job_service.getResult(selector) + + # Output results. + index = 0 + for result in result_response['SimpleMutateResult']['results']: + if 'PlaceHolder' in result: + print 'Operation [%d] - FAILED' % index + else: + print 'Operation [%d] - SUCCEEDED' % index + index += 1 + + # Output errors + for error in result_response['SimpleMutateResult']['errors']: + index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) + reason = error['reason'] + url = operations[index]['operand']['criterion']['url'] + print ('ERROR - placement \'%s\' failed due to \'%s\'' % + (url, reason)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201506/error_handling/__init__.py b/examples/adxbuyer/v201506/error_handling/__init__.py new file mode 100644 index 00000000..b5203c57 --- /dev/null +++ b/examples/adxbuyer/v201506/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Error handling examples.""" diff --git a/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..88057e6b --- /dev/null +++ b/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py @@ -0,0 +1,117 @@ +#!/usr/bin/python +# +# Copyright 2013 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Tags: AdGroupCriterionService.mutate +""" + +__author__ = 'api.kwinter@gmail.com (Kevin Winter)' + +import re + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201506') + + # Construct placement ad group criteria objects. + placements = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'url': 'www.example.com/something' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'url': 'INVALID!!_URL' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'url': 'www.example.com/somethingelse' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Placement', + 'url': 'BAD!!_URL' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for placement in placements: + operations.append( + { + 'operator': 'ADD', + 'operand': placement + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added placement ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\' and url \'%s\'' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['url'])) + + for error in result['partialFailureErrors']: + index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) + if index: + print ('Placement ad group criterion with ad group id \'%s\' and url ' + '\'%s\' triggered a failure for the following reason: \'%s\'.' + % (placements[int(index[0])]['adGroupId'], + placements[int(index[0])]['criterion']['url'], + error['errorString'])) + else: + print 'The following failure has occurred: \'%s\'.' % error['errorString'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index a2955679..0440a514 100755 --- a/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -52,7 +52,7 @@ def main(client): # Create statement to get all targeting values. query = ('WHERE customTargetingKeyId IN (%s)' - % ', '.join([key['id'] for key in all_keys])) + % ', '.join([str(key['id']) for key in all_keys])) targeting_value_statement = dfp.FilterStatement(query) # Get custom targeting values by statement. diff --git a/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 464c2ac9..afa13419 100755 --- a/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -52,7 +52,7 @@ def main(client): # Create statement to get all targeting values. query = ('WHERE customTargetingKeyId IN (%s)' - % ', '.join([key['id'] for key in all_keys])) + % ', '.join([str(key['id']) for key in all_keys])) targeting_value_statement = dfp.FilterStatement(query) # Get custom targeting values by statement. diff --git a/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 814fd723..f1751cb1 100755 --- a/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -52,7 +52,7 @@ def main(client): # Create statement to get all targeting values. query = ('WHERE customTargetingKeyId IN (%s)' - % ', '.join([key['id'] for key in all_keys])) + % ', '.join([str(key['id']) for key in all_keys])) targeting_value_statement = dfp.FilterStatement(query) # Get custom targeting values by statement. diff --git a/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index c3ffd814..2252e51d 100755 --- a/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -52,7 +52,7 @@ def main(client): # Create statement to get all targeting values. query = ('WHERE customTargetingKeyId IN (%s)' - % ', '.join([key['id'] for key in all_keys])) + % ', '.join([str(key['id']) for key in all_keys])) targeting_value_statement = dfp.FilterStatement(query) # Get custom targeting values by statement. diff --git a/googleads/adwords.py b/googleads/adwords.py index 425846eb..09814278 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -118,9 +118,58 @@ 'SharedSetService': 'cm', 'TargetingIdeaService': 'o', 'TrafficEstimatorService': 'o', + }, + 'v201506': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'ExperimentService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'GeoLocationService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'MutateJobService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', } } +# Supported kwargs for params sent in the report header. +_REPORT_HEADER_KWARGS = {'include_zero_impressions': 'includeZeroImpressions', + 'skip_report_header': 'skipReportHeader', + 'skip_column_header': 'skipColumnHeader', + 'skip_report_summary': 'skipReportSummary'} + # The endpoint used by default when making AdWords API requests. _DEFAULT_ENDPOINT = 'https://adwords.google.com' @@ -215,6 +264,7 @@ def __init__( """ self.developer_token = developer_token self.oauth2_client = oauth2_client + self.oauth2_client.Refresh() self.user_agent = user_agent self.client_customer_id = client_customer_id self.validate_only = validate_only @@ -334,12 +384,15 @@ def SetHeaders(self, suds_client): soapheaders=header, headers=self._adwords_client.oauth2_client.CreateHttpHeader()) - def GetReportDownloadHeaders(self, skip_report_header=None, - skip_column_header=None, - skip_report_summary=None): + def GetReportDownloadHeaders(self, kwargs): """Returns a dictionary of headers for a report download request. Args: + kwargs: A dictionary containing optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -362,14 +415,13 @@ def GetReportDownloadHeaders(self, skip_report_header=None, ',gzip']) }) - if skip_report_header: - headers.update({'skipReportHeader': str(skip_report_header)}) - - if skip_column_header: - headers.update({'skipColumnHeader': str(skip_column_header)}) - - if skip_report_summary: - headers.update({'skipReportSummary': str(skip_report_summary)}) + for kw in kwargs: + try: + headers.update({_REPORT_HEADER_KWARGS[kw]: str(kwargs[kw])}) + except KeyError: + raise googleads.errors.GoogleAdsValueError( + 'The provided keyword "%s" is invalid. Accepted keywords are: %s' + % (kw, _REPORT_HEADER_KWARGS.keys())) return headers @@ -434,9 +486,7 @@ def _DownloadReportCheckFormat(self, file_format, output): raise googleads.errors.GoogleAdsValueError('Need to specify a binary' ' output for GZIPPED formats.') - def DownloadReport(self, report_definition, output=sys.stdout, - skip_report_header=None, skip_column_header=None, - skip_report_summary=None): + def DownloadReport(self, report_definition, output=sys.stdout, **kwargs): """Downloads an AdWords report using a report definition. The report contents will be written to the given output. @@ -449,6 +499,11 @@ def DownloadReport(self, report_definition, output=sys.stdout, output: A writable object where the contents of the report will be written to. If the report is gzip compressed, you need to specify an output that can write binary data. + **kwargs: Optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -469,11 +524,9 @@ def DownloadReport(self, report_definition, output=sys.stdout, """ self._DownloadReportCheckFormat(report_definition['downloadFormat'], output) self._DownloadReport(self._SerializeReportDefinition(report_definition), - output, skip_report_header, skip_column_header, - skip_report_summary) + output, kwargs) - def DownloadReportAsStream(self, report_definition, skip_report_header=None, - skip_column_header=None, skip_report_summary=None): + def DownloadReportAsStream(self, report_definition, **kwargs): """Downloads an AdWords report using a report definition. This will return a stream, allowing you to retrieve the report contents. @@ -482,7 +535,11 @@ def DownloadReportAsStream(self, report_definition, skip_report_header=None, report_definition: A dictionary or instance of the ReportDefinition class generated from the schema. This defines the contents of the report that will be downloaded. - [optional] + **kwargs: Optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -505,13 +562,9 @@ def DownloadReportAsStream(self, report_definition, skip_report_header=None, network error. """ return self._DownloadReportAsStream( - self._SerializeReportDefinition(report_definition), skip_report_header, - skip_column_header, skip_report_summary) + self._SerializeReportDefinition(report_definition), kwargs) - def DownloadReportAsStreamWithAwql(self, query, file_format, - skip_report_header=None, - skip_column_header=None, - skip_report_summary=None): + def DownloadReportAsStreamWithAwql(self, query, file_format, **kwargs): """Downloads an AdWords report using an AWQL query. The report contents will be returned as a stream. @@ -522,7 +575,11 @@ def DownloadReportAsStreamWithAwql(self, query, file_format, file_format: A string representing the output format for your report. Acceptable values can be found in our API documentation: https://developers.google.com/adwords/api/docs/guides/reporting - [optional] + **kwargs: Optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -545,12 +602,9 @@ def DownloadReportAsStreamWithAwql(self, query, file_format, network error. """ return self._DownloadReportAsStream(self._SerializeAwql(query, file_format), - skip_report_header, skip_column_header, - skip_report_summary) + kwargs) - def DownloadReportAsString(self, report_definition, - skip_report_header=None, skip_column_header=None, - skip_report_summary=None): + def DownloadReportAsString(self, report_definition, **kwargs): """Downloads an AdWords report using a report definition. The report contents will be returned as a string. @@ -559,7 +613,11 @@ def DownloadReportAsString(self, report_definition, report_definition: A dictionary or instance of the ReportDefinition class generated from the schema. This defines the contents of the report that will be downloaded. - [optional] + **kwargs: Optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -584,17 +642,13 @@ def DownloadReportAsString(self, report_definition, response = None try: response = self._DownloadReportAsStream( - self._SerializeReportDefinition(report_definition), - skip_report_header, skip_column_header, skip_report_summary) + self._SerializeReportDefinition(report_definition), kwargs) return response.read().decode('utf-8') finally: if response: response.close() - def DownloadReportAsStringWithAwql(self, query, file_format, - skip_report_header=None, - skip_column_header=None, - skip_report_summary=None): + def DownloadReportAsStringWithAwql(self, query, file_format, **kwargs): """Downloads an AdWords report using an AWQL query. The report contents will be returned as a string. @@ -605,7 +659,11 @@ def DownloadReportAsStringWithAwql(self, query, file_format, file_format: A string representing the output format for your report. Acceptable values can be found in our API documentation: https://developers.google.com/adwords/api/docs/guides/reporting - [optional] + **kwargs: Optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -629,17 +687,15 @@ def DownloadReportAsStringWithAwql(self, query, file_format, """ response = None try: - response = self.DownloadReportAsStreamWithAwql( - query, file_format, skip_report_header, skip_column_header, - skip_report_summary) + response = self._DownloadReportAsStream( + self._SerializeAwql(query, file_format), kwargs) return response.read().decode('utf-8') finally: if response: response.close() def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, - skip_report_header=None, skip_column_header=None, - skip_report_summary=None): + **kwargs): """Downloads an AdWords report using an AWQL query. The report contents will be written to the given output. @@ -654,6 +710,11 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, output: A writable object where the contents of the report will be written to. If the report is gzip compressed, you need to specify an output that can write binary data. + **kwargs: Optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -674,11 +735,9 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, """ self._DownloadReportCheckFormat(file_format, output) self._DownloadReport(self._SerializeAwql(query, file_format), output, - skip_report_header, skip_column_header, - skip_report_summary) + kwargs) - def _DownloadReport(self, post_body, output, skip_report_header, - skip_column_header, skip_report_summary): + def _DownloadReport(self, post_body, output, kwargs): """Downloads an AdWords report, writing the contents to the given file. Args: @@ -686,6 +745,11 @@ def _DownloadReport(self, post_body, output, skip_report_header, string. output: A writable object where the contents of the report will be written to. + kwargs: A dictionary containing optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -706,9 +770,7 @@ def _DownloadReport(self, post_body, output, skip_report_header, """ response = None try: - response = self._DownloadReportAsStream(post_body, skip_report_header, - skip_column_header, - skip_report_summary) + response = self._DownloadReportAsStream(post_body, kwargs) output.write(response.read().decode() if sys.version_info[0] == 3 and (getattr(output, 'mode', 'w') == 'w' and type(output) is not io.BytesIO) @@ -717,13 +779,17 @@ def _DownloadReport(self, post_body, output, skip_report_header, if response: response.close() - def _DownloadReportAsStream(self, post_body, skip_report_header, - skip_column_header, skip_report_summary): + def _DownloadReportAsStream(self, post_body, kwargs): """Downloads an AdWords report, returning a stream. Args: post_body: The contents of the POST request's body as a URL encoded string. + kwargs: A dictionary containing optional keyword arguments. + + Keyword Arguments: + include_zero_impressions: A boolean indicating whether the report should + show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row containing the report name and date range. If false or not specified, report output will include the header row. @@ -749,9 +815,7 @@ def _DownloadReportAsStream(self, post_body, skip_report_header, post_body = bytes(post_body, 'utf8') request = urllib2.Request( self._end_point, post_body, - self._header_handler.GetReportDownloadHeaders(skip_report_header, - skip_column_header, - skip_report_summary)) + self._header_handler.GetReportDownloadHeaders(kwargs)) try: return self.url_opener.open(request) except urllib2.HTTPError, e: diff --git a/googleads/common.py b/googleads/common.py index 013612f6..d853bbac 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -31,7 +31,8 @@ VERSION = '3.4.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' -_PYTHON_VERSION = 'Python/%d.%d' % (sys.version_info[0], sys.version_info[1]) +_PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], + sys.version_info[2]) # The keys in the authentication dictionary that are used to construct OAuth 2.0 # credentials. diff --git a/setup.py b/setup.py index 2d453a1d..cd0785d6 100755 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ """Setup script for the Google Ads Python Client Library.""" -__author__ = 'Joseph Dilallo' +__author__ = 'Mark Saniscalchi' import os import re @@ -28,6 +28,13 @@ DEPENDENCIES = ['httplib2', 'oauth2client', 'suds-jurko', 'pysocks', 'pytz', 'PyYAML'] +CLASSIFIERS = [ + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3.4' +] + def GetVersion(): """Gets the version from googleads/common.py. @@ -57,6 +64,14 @@ def GetVersion(): You can find more information about the Google Ads Python Client Libraries `here `_. +Supported Python Versions +========================= + +This library is supported for Python 2 and 3, for versions 2.7+ and 3.4+ +respectively. It is recommended that Python 2 users use python 2.7.9+ to take +advantage of the SSL Certificate Validation feature that is not included in +earlier versions. + Installation ============ @@ -92,13 +107,14 @@ def GetVersion(): setup(name='googleads', version=GetVersion(), description='Google Ads Python Client Library', - author='Joseph DiLallo', - author_email='jdilallo@google.com', + author='Mark Saniscalchi', + author_email='msaniscalchi@google.com', url='https://github.com/googleads/googleads-python-lib', license='Apache License 2.0', long_description=long_description, packages=PACKAGES, platforms='any', keywords='adwords adxbuyer dfp dfa google', + classifiers=CLASSIFIERS, install_requires=DEPENDENCIES, **extra_params) diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 62012329..bffad2f8 100755 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -97,15 +97,32 @@ def testGetReportDownloadHeaders(self): 'Authorization': 'header', 'User-Agent': ''.join([ user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, - ',gzip']) + ',gzip']), + 'skipReportHeader': 'False', + 'skipColumnHeader': 'False', + 'skipReportSummary': 'False' } self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( - skip_report_header=False, skip_column_header=False, - skip_report_summary=False)) + {'skip_report_header': False, + 'skip_column_header': False, + 'skip_report_summary': False})) + + def testGetReportDownloadHeadersWithInvalidKeyword(self): + ccid = 'client customer id' + dev_token = 'developer token' + user_agent = 'user agent!' + self.adwords_client.client_customer_id = ccid + self.adwords_client.developer_token = dev_token + self.adwords_client.user_agent = user_agent + + self.assertRaises( + googleads.errors.GoogleAdsValueError, + self.header_handler.GetReportDownloadHeaders, + {'invalid_key_word': True}) def testGetReportDownloadHeadersWithOptionalHeaders(self): ccid = 'client customer id' @@ -127,15 +144,18 @@ def testGetReportDownloadHeadersWithOptionalHeaders(self): ',gzip']), 'skipReportHeader': 'True', 'skipColumnHeader': 'True', - 'skipReportSummary': 'True' + 'skipReportSummary': 'True', + 'includeZeroImpressions': 'True' } self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( - skip_report_header=True, skip_column_header=True, - skip_report_summary=True)) + {'skip_report_header': True, + 'skip_column_header': True, + 'skip_report_summary': True, + 'include_zero_impressions': True})) class AdWordsClientTest(unittest.TestCase): @@ -161,7 +181,7 @@ def testLoadFromStorage(self): with mock.patch('googleads.common.LoadFromStorage') as mock_load: mock_load.return_value = { 'developer_token': 'abcdEFghIjkLMOpqRs', - 'oauth2_client': True, + 'oauth2_client': self.oauth2_client, 'user_agent': 'unit testing' } self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage(), @@ -276,8 +296,7 @@ def testDownloadReport(self): self.marshaller.process.assert_called_once_with( mock_content.return_value) self.assertEqual(content, output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None, None) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) def testDownloadReportAsString(self): report_definition = {'table': 'campaigns', @@ -306,8 +325,7 @@ def testDownloadReportAsString(self): self.marshaller.process.assert_called_once_with( mock_content.return_value) self.assertEqual(content, s) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None, None) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) def testDownloadReportAsStringWithAwql(self): query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' @@ -331,8 +349,7 @@ def testDownloadReportAsStringWithAwql(self): % self.version), post_body, headers) self.opener.open.assert_called_once_with(mock_request.return_value) self.assertEqual(content, s) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None, None) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) def testDownloadReportCheckFormat_CSVStringSuccess(self): output_file = io.StringIO() @@ -402,8 +419,7 @@ def testDownloadReport_failure(self): self.marshaller.process.assert_called_once_with( mock_content.return_value) self.assertEqual('', output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None, None) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) def testDownloadReportWithAwql(self): output_file = io.StringIO() @@ -430,8 +446,7 @@ def testDownloadReportWithAwql(self): self.opener.open.assert_called_once_with(mock_request.return_value) self.assertEqual(content, output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None, None) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) def testDownloadReportWithBytesIO(self): output_file = io.BytesIO() @@ -461,8 +476,7 @@ def testDownloadReportWithBytesIO(self): self.marshaller.process.assert_called_once_with( mock_content.return_value) self.assertEqual(content, output_file.getvalue().decode('utf-8')) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - None, None, None) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) def testExtractError_badRequest(self): response = mock.Mock() From a1252010ebd89b5ad647e4ba55e74f3ce690d000 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 9 Jul 2015 10:12:08 -0400 Subject: [PATCH 009/180] Commiting latest changes. From 49c29275adf0c2d4c9242b9c783117bd0f221619 Mon Sep 17 00:00:00 2001 From: nicholaschen Date: Mon, 27 Jul 2015 14:09:47 +0900 Subject: [PATCH 010/180] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 14fb84ce..d8994387 100644 --- a/README.md +++ b/README.md @@ -127,4 +127,5 @@ suds_client.service.mutate([operation]) ##Authors: - msaniscalchi@google.com (Mark Saniscalchi) + Mark Saniscalchi + Nicholas Chen From 8fdc701ceb1a6148a0c1d4234608124e82c0a7ca Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Fri, 31 Jul 2015 10:24:00 -0400 Subject: [PATCH 011/180] Remove v201409 from AdWords --- ChangeLog | 4 + README.md | 3 +- examples/adwords/v201409/__init__.py | 0 .../v201409/account_management/__init__.py | 0 .../account_management/create_account.py | 67 --- .../account_management/get_account_changes.py | 102 ---- .../get_account_hierarchy.py | 97 ---- .../v201409/advanced_operations/__init__.py | 0 .../advanced_operations/add_ad_customizer.py | 251 --------- .../add_ad_group_bid_modifier.py | 78 --- .../add_click_to_download_ad.py | 114 ---- .../add_text_ad_with_upgraded_urls.py | 114 ---- .../get_ad_group_bid_modifier.py | 76 --- .../upload_offline_conversions.py | 101 ---- .../use_shared_bidding_strategy.py | 176 ------ .../v201409/basic_operations/__init__.py | 0 .../v201409/basic_operations/add_ad_groups.py | 116 ---- .../v201409/basic_operations/add_campaigns.py | 131 ----- .../v201409/basic_operations/add_keywords.py | 97 ---- .../v201409/basic_operations/add_text_ads.py | 98 ---- .../v201409/basic_operations/get_ad_groups.py | 80 --- .../v201409/basic_operations/get_campaigns.py | 77 --- .../get_campaigns_with_awql.py | 68 --- .../v201409/basic_operations/get_keywords.py | 81 --- .../v201409/basic_operations/get_text_ads.py | 85 --- .../v201409/basic_operations/pause_ad.py | 65 --- .../v201409/basic_operations/remove_ad.py | 66 --- .../basic_operations/remove_ad_group.py | 62 -- .../basic_operations/remove_campaign.py | 62 -- .../basic_operations/remove_keyword.py | 72 --- .../basic_operations/update_ad_group.py | 62 -- .../basic_operations/update_campaign.py | 62 -- .../basic_operations/update_keyword.py | 87 --- .../v201409/campaign_management/__init__.py | 0 .../add_campaign_labels.py | 70 --- .../campaign_management/add_experiment.py | 132 ----- .../add_keywords_in_bulk.py | 141 ----- .../add_location_extension.py | 114 ---- .../get_all_disapproved_ads.py | 78 --- .../get_all_disapproved_ads_with_awql.py | 67 --- .../get_campaigns_by_label.py | 88 --- .../campaign_management/promote_experiment.py | 65 --- .../campaign_management/set_ad_parameters.py | 107 ---- .../set_criterion_bid_modifier.py | 82 --- .../campaign_management/validate_text_ad.py | 91 --- .../v201409/error_handling/__init__.py | 0 .../error_handling/handle_partial_failures.py | 124 ---- .../handle_policy_violation_error.py | 117 ---- .../adwords/v201409/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 158 ------ .../v201409/extensions/add_site_links.py | 128 ----- .../extensions/add_site_links_using_feeds.py | 265 --------- .../adwords/v201409/migration/__init__.py | 0 .../migrate_to_extension_settings.py | 528 ------------------ .../v201409/migration/upgrade_ad_url.py | 82 --- examples/adwords/v201409/misc/__init__.py | 0 .../v201409/misc/get_all_images_and_videos.py | 80 --- examples/adwords/v201409/misc/upload_image.py | 70 --- .../adwords/v201409/optimization/__init__.py | 0 .../optimization/estimate_keyword_traffic.py | 131 ----- .../get_keyword_bid_simulations.py | 88 --- .../v201409/optimization/get_keyword_ideas.py | 95 ---- .../adwords/v201409/remarketing/__init__.py | 0 .../v201409/remarketing/add_audience.py | 107 ---- .../remarketing/add_conversion_tracker.py | 77 --- .../remarketing/add_rule_based_user_lists.py | 186 ------ .../adwords/v201409/reporting/__init__.py | 0 .../reporting/download_criteria_report.py | 65 --- .../download_criteria_report_as_stream.py | 80 --- ...oad_criteria_report_as_stream_with_awql.py | 84 --- .../download_criteria_report_as_string.py | 64 --- ...oad_criteria_report_as_string_with_awql.py | 58 -- .../download_criteria_report_with_awql.py | 61 -- .../v201409/reporting/get_report_fields.py | 56 -- .../shopping/add_product_partition_tree.py | 285 ---------- .../v201409/shopping/add_product_scope.py | 107 ---- .../v201409/shopping/add_shopping_campaign.py | 122 ---- .../shopping/get_product_category_taxonomy.py | 99 ---- .../adwords/v201409/targeting/__init__.py | 0 .../add_campaign_targeting_criteria.py | 159 ------ .../add_demographic_targeting_criteria.py | 99 ---- .../get_campaign_targeting_criteria.py | 89 --- .../get_targetable_languages_and_carriers.py | 60 -- .../v201409/targeting/lookup_location.py | 86 --- googleads.yaml | 3 +- googleads/adwords.py | 43 -- googleads/common.py | 2 +- 87 files changed, 8 insertions(+), 7454 deletions(-) delete mode 100644 examples/adwords/v201409/__init__.py delete mode 100644 examples/adwords/v201409/account_management/__init__.py delete mode 100755 examples/adwords/v201409/account_management/create_account.py delete mode 100755 examples/adwords/v201409/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201409/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201409/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201409/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201409/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201409/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201409/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201409/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201409/advanced_operations/upload_offline_conversions.py delete mode 100755 examples/adwords/v201409/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201409/basic_operations/__init__.py delete mode 100755 examples/adwords/v201409/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201409/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201409/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201409/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201409/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201409/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201409/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201409/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201409/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201409/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201409/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201409/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201409/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201409/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201409/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201409/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201409/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201409/campaign_management/__init__.py delete mode 100755 examples/adwords/v201409/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201409/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py delete mode 100755 examples/adwords/v201409/campaign_management/add_location_extension.py delete mode 100755 examples/adwords/v201409/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201409/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201409/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201409/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201409/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201409/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201409/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201409/error_handling/__init__.py delete mode 100755 examples/adwords/v201409/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201409/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201409/extensions/__init__.py delete mode 100755 examples/adwords/v201409/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201409/extensions/add_site_links.py delete mode 100755 examples/adwords/v201409/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201409/migration/__init__.py delete mode 100755 examples/adwords/v201409/migration/migrate_to_extension_settings.py delete mode 100755 examples/adwords/v201409/migration/upgrade_ad_url.py delete mode 100644 examples/adwords/v201409/misc/__init__.py delete mode 100755 examples/adwords/v201409/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201409/misc/upload_image.py delete mode 100644 examples/adwords/v201409/optimization/__init__.py delete mode 100755 examples/adwords/v201409/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201409/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201409/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201409/remarketing/__init__.py delete mode 100755 examples/adwords/v201409/remarketing/add_audience.py delete mode 100755 examples/adwords/v201409/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201409/remarketing/add_rule_based_user_lists.py delete mode 100644 examples/adwords/v201409/reporting/__init__.py delete mode 100755 examples/adwords/v201409/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201409/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201409/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201409/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201409/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201409/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201409/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201409/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201409/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201409/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201409/targeting/__init__.py delete mode 100755 examples/adwords/v201409/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201409/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201409/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201409/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201409/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 76392266..bec5d4a8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +3.6.0 - 7/31/2015 +* Removed support for AdWords v201409. +* Removed examples for AdWords v201409. + 3.5.0 - 6/26/2015 * Added support for v201506 of the AdWords Client Library. * Reporting parameters in ReportDownloader utility now in **kwargs. diff --git a/README.md b/README.md index d8994387..14fb84ce 100644 --- a/README.md +++ b/README.md @@ -127,5 +127,4 @@ suds_client.service.mutate([operation]) ##Authors: - Mark Saniscalchi - Nicholas Chen + msaniscalchi@google.com (Mark Saniscalchi) diff --git a/examples/adwords/v201409/__init__.py b/examples/adwords/v201409/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/account_management/__init__.py b/examples/adwords/v201409/account_management/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/account_management/create_account.py b/examples/adwords/v201409/account_management/create_account.py deleted file mode 100755 index 363deb80..00000000 --- a/examples/adwords/v201409/account_management/create_account.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/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. - -"""This example illustrates how to create an account. - -By default this account will only be accessible via parent MCC. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CreateAccountService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from datetime import datetime - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201409') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201409/account_management/get_account_changes.py b/examples/adwords/v201409/account_management/get_account_changes.py deleted file mode 100755 index a7817923..00000000 --- a/examples/adwords/v201409/account_management/get_account_changes.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/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. - -"""This example gets the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CustomerSyncService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import datetime - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201409') - campaign_service = client.GetService('CampaignService', version='v201409') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - print ' Added ad extensions: %s' % data.get('addedAdExtensions') - print ' Removed ad extensions: %s' % data.get('deletedAdExtensions') - print (' Added campaign criteria: %s' - % data.get('addedCampaignCriteria')) - print (' Removed campaign criteria: %s' - % data.get('deletedCampaignCriteria')) - print (' Campaign targeting changed: %s' - % data.get('campaignTargetingChanged')) - if data.get('changedAdGroups'): - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - print ' Changed ads: %s' % ad_group_data['changedAds'] - print (' Changed criteria: %s' - % ad_group_data['changedCriteria']) - print (' Removed criteria: %s' - % ad_group_data['deletedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201409/account_management/get_account_hierarchy.py b/examples/adwords/v201409/account_management/get_account_hierarchy.py deleted file mode 100755 index 7b5f1ae4..00000000 --- a/examples/adwords/v201409/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/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. - -"""This example gets the account hierarchy under the current account. - -Note: this code example won't work with test accounts. See -https://developers.google.com/adwords/api/docs/test-accounts - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ServicedAccountService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201409') - - # Construct selector to get all accounts. - selector = { - 'fields': ['CustomerId', 'Name'] - } - # Get serviced account graph. - graph = managed_customer_service.get(selector) - if 'entries' in graph and graph['entries']: - # Create map from customerId to parent and child links. - child_links = {} - parent_links = {} - if 'links' in graph: - for link in graph['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Create map from customerID to account and find root account. - accounts = {} - root_account = None - for account in graph['entries']: - accounts[account['customerId']] = account - if account['customerId'] not in parent_links: - root_account = account - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - else: - print 'No serviced accounts were found' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201409/advanced_operations/__init__.py b/examples/adwords/v201409/advanced_operations/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/advanced_operations/add_ad_customizer.py b/examples/adwords/v201409/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 41042287..00000000 --- a/examples/adwords/v201409/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,251 +0,0 @@ -#!/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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that -uses the feed to populate dynamic data. - -Tags: CustomerFeedService.mutate, FeedItemService.mutate -Tags: FeedMappingService.mutate, FeedService.mutate -Tags: AdGroupAdService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'yufeng.dev@gmail.com (Yufeng Guo)') - -# Import appropriate classes from the client library. -from googleads import adwords - -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_AD_CUSTOMIZER = '10' -PLACEHOLDER_FIELD_INTEGER = '1' -PLACEHOLDER_FIELD_FLOAT = '2' -PLACEHOLDER_FIELD_PRICE = '3' -PLACEHOLDER_FIELD_DATE = '4' -PLACEHOLDER_FIELD_STRING = '5' - -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - -FEEDNAME = 'INSERT_FEED_NAME_HERE' - - -def main(client, adgroups): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201409') - feed_item_service = client.GetService('FeedItemService', version='v201409') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201409') - feed_service = client.GetService('FeedService', version='v201409') - - # First, create a customizer feed. One feed per account can be used for all - # ads. - customizer_feed = { - 'name': FEEDNAME, - 'attributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['id'], - 'nameId': feed['attributes'][0]['id'], - 'priceId': feed['attributes'][1]['id'], - 'dateId': feed['attributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['name'], feed['id'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - else: - raise Exception('No feeds were added') - - # Creating feed mapping to map the fields with customizer IDs. - feed_mapping = { - 'placeholderType': PLACEHOLDER_AD_CUSTOMIZER, - 'feedId': feed_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': feed_data['nameId'], - 'fieldId': PLACEHOLDER_FIELD_STRING - }, - { - 'feedAttributeId': feed_data['priceId'], - 'fieldId': PLACEHOLDER_FIELD_PRICE - }, - { - 'feedAttributeId': feed_data['dateId'], - 'fieldId': PLACEHOLDER_FIELD_DATE - } - ] - } - - feed_mapping_operation = { - 'operator': 'ADD', - 'operand': feed_mapping - } - - response = feed_mapping_service.mutate([feed_mapping_operation]) - - if response and 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.') % (feed_mapping['feedMappingId'], - feed_mapping['placeholderType'], - feed_mapping['feedId']) - else: - raise Exception('No feed mappings were added.') - - # Now adding feed items -- the values we'd like to place. - items_data = [ - { - 'name': 'Mars', - 'price': '$1234.56', - 'date': '20140601 000000', - 'adGroupId': adgroups[0] - }, - { - 'name': 'Venus', - 'price': '$1450.00', - 'date': '20140615 120000', - 'adGroupId': adgroups[1] - } - ] - - feed_items = [{'feedId': feed_data['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': item['adGroupId'] - }, - 'attributeValues': [ - { - 'feedAttributeId': feed_data['nameId'], - 'stringValue': item['name'] - }, - { - 'feedAttributeId': feed_data['priceId'], - 'stringValue': item['price'] - }, - { - 'feedAttributeId': feed_data['dateId'], - 'stringValue': item['date'] - } - ]} for item in items_data] - - feed_item_operations = [{ - 'operator': 'ADD', - 'operand': feed_item - } for feed_item in feed_items] - - response = feed_item_service.mutate(feed_item_operations) - - if response and 'value' in response: - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - else: - raise Exception('No feed items were added.') - - # Finally, creating a customer (account-level) feed with a matching function - # that determines when to use this feed. For this case we use the "IDENTITY" - # matching function that is always 'true' just to associate this feed with - # the customer. The targeting is done within the feed items using the - # :campaign_targeting, :ad_group_targeting, or :keyword_targeting attributes. - matching_function = { - 'operator': 'IDENTITY', - 'lhsOperand': [ - { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': 'true' - } - ] - } - - customer_feed = { - 'feedId': feed_data['feedId'], - 'matchingFunction': matching_function, - 'placeholderTypes': [PLACEHOLDER_AD_CUSTOMIZER] - } - - customer_feed_operation = { - 'operator': 'ADD', - 'operand': customer_feed - } - - response = customer_feed_service.mutate([customer_feed_operation]) - - if response and 'value' in response: - feed = response['value'][0] - print 'Customer feed with ID %s was added.' % feed['feedId'] - else: - raise Exception('No customer feeds were added.') - - # All set! We can now create ads with customizations. - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % FEEDNAME, - 'description1': 'Only {=%s.Price}' % FEEDNAME, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % FEEDNAME, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroups] - - print operations - - response = ad_group_ad_service.mutate(operations) - - print '===ad group ad service===' - print response - - if response and 'value' in response: - for ad in response['value']: - print ('\tCreated an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise Exception('No ads were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201409/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201409/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 16cac4c7..00000000 --- a/examples/adwords/v201409/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupBidModifierService.mutate -""" - -__author__ = 'Joseph DiLallo' - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201409') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201409/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201409/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index a6cf1956..00000000 --- a/examples/adwords/v201409/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/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. - -"""This code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Joseph DiLallo' - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad to ad group ID \'%s\' ' - 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201409/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index d9675246..00000000 --- a/examples/adwords/v201409/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/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. - -"""This example adds a text add that uses advanced features of upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = 'Mark Saniscalchi' - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201409/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201409/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 7bd8e214..00000000 --- a/examples/adwords/v201409/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupBidModifierService.get -""" - -__author__ = 'Joseph DiLallo' - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201409') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201409/advanced_operations/upload_offline_conversions.py deleted file mode 100755 index b45759c6..00000000 --- a/examples/adwords/v201409/advanced_operations/upload_offline_conversions.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ConversionTrackerService.mutate, OfflineConversionFeedService.mutate -""" - -__author__ = 'Joseph DiLallo' - -from googleads import adwords - - -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - conversion_tracker_service = client.GetService('ConversionTrackerService', - version='v201409') - - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201409') - - # Once created, this entry will be visible under - # Tools and Analysis->Conversion and will have "Source = Import". - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'category': 'PAGE_VIEW', - 'name': conversion_name, - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90' - } - - upload_conversion_operation = { - 'operator': 'ADD', - 'operand': upload_conversion - } - - response = conversion_tracker_service.mutate( - [upload_conversion_operation]) - new_upload_conversion = response['value'] - - print ('New upload conversion type with name \'%s\' and ID \'%s\' was ' - 'created.' % (new_upload_conversion['name'], - new_upload_conversion['id'])) - - # Associate offline conversions with the upload conversion we created. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201409/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201409/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 6e880095..00000000 --- a/examples/adwords/v201409/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,176 +0,0 @@ -#!/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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: BiddingStrategyService.mutate -Tags: BudgetService.mutate, CampaignService.mutate -""" - -__author__ = 'Joseph DiLallo' - -import uuid - -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201409') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201409') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'period': 'DAILY', - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201409') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201409/basic_operations/__init__.py b/examples/adwords/v201409/basic_operations/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/basic_operations/add_ad_groups.py b/examples/adwords/v201409/basic_operations/add_ad_groups.py deleted file mode 100755 index e3fff74d..00000000 --- a/examples/adwords/v201409/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/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. - -"""This example adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README.. - -Tags: AdGroupService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import uuid - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201409') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings - these settings only affect - # serving for the Display Network. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/basic_operations/add_campaigns.py b/examples/adwords/v201409/basic_operations/add_campaigns.py deleted file mode 100755 index 58baacff..00000000 --- a/examples/adwords/v201409/basic_operations/add_campaigns.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/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. - -"""This example adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -Tags: BudgetService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import datetime -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201409') - budget_service = client.GetService('BudgetService', version='v201409') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/basic_operations/add_keywords.py b/examples/adwords/v201409/basic_operations/add_keywords.py deleted file mode 100755 index 588bde53..00000000 --- a/examples/adwords/v201409/basic_operations/add_keywords.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/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. - -"""This example adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/basic_operations/add_text_ads.py b/examples/adwords/v201409/basic_operations/add_text_ads.py deleted file mode 100755 index 2b5ad425..00000000 --- a/examples/adwords/v201409/basic_operations/add_text_ads.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/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. - -"""This example adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/basic_operations/get_ad_groups.py b/examples/adwords/v201409/basic_operations/get_ad_groups.py deleted file mode 100755 index 3355c3af..00000000 --- a/examples/adwords/v201409/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/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. - -"""This example gets all ad groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201409') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/basic_operations/get_campaigns.py b/examples/adwords/v201409/basic_operations/get_campaigns.py deleted file mode 100755 index b931e7b2..00000000 --- a/examples/adwords/v201409/basic_operations/get_campaigns.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/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. - -"""This example gets all campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.get -""" - -__author__ = 'Joseph DiLallo' - -import logging -import time - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201409') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201409/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201409/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index e3c38e47..00000000 --- a/examples/adwords/v201409/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/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. - -"""This example gets all campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.query -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import time - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201409') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201409/basic_operations/get_keywords.py b/examples/adwords/v201409/basic_operations/get_keywords.py deleted file mode 100755 index ee83c7e3..00000000 --- a/examples/adwords/v201409/basic_operations/get_keywords.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/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. - -"""This example gets all ad group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['AdGroupId', 'Id', 'Text', 'KeywordMatchType', 'PlacementUrl'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for criterion in page['entries']: - print ('Keyword ad group criterion with ad group id \'%s\', criterion ' - 'id \'%s\', text \'%s\', and match type \'%s\' was found.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/basic_operations/get_text_ads.py b/examples/adwords/v201409/basic_operations/get_text_ads.py deleted file mode 100755 index 10186fb3..00000000 --- a/examples/adwords/v201409/basic_operations/get_text_ads.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/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. - -"""This example gets all text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/basic_operations/pause_ad.py b/examples/adwords/v201409/basic_operations/pause_ad.py deleted file mode 100755 index e47e1c69..00000000 --- a/examples/adwords/v201409/basic_operations/pause_ad.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/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. - -"""This example updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201409/basic_operations/remove_ad.py b/examples/adwords/v201409/basic_operations/remove_ad.py deleted file mode 100755 index 5003d458..00000000 --- a/examples/adwords/v201409/basic_operations/remove_ad.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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. - -"""This example deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201409/basic_operations/remove_ad_group.py b/examples/adwords/v201409/basic_operations/remove_ad_group.py deleted file mode 100755 index 8f2b245c..00000000 --- a/examples/adwords/v201409/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""This example deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201409') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/basic_operations/remove_campaign.py b/examples/adwords/v201409/basic_operations/remove_campaign.py deleted file mode 100755 index b93021d0..00000000 --- a/examples/adwords/v201409/basic_operations/remove_campaign.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""This example deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201409') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/basic_operations/remove_keyword.py b/examples/adwords/v201409/basic_operations/remove_keyword.py deleted file mode 100755 index 5189f67e..00000000 --- a/examples/adwords/v201409/basic_operations/remove_keyword.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/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. - -"""This example deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201409/basic_operations/update_ad_group.py b/examples/adwords/v201409/basic_operations/update_ad_group.py deleted file mode 100755 index 56708e1a..00000000 --- a/examples/adwords/v201409/basic_operations/update_ad_group.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""This example updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201409') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/basic_operations/update_campaign.py b/examples/adwords/v201409/basic_operations/update_campaign.py deleted file mode 100755 index 8d8bd43c..00000000 --- a/examples/adwords/v201409/basic_operations/update_campaign.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""This example updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201409') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/basic_operations/update_keyword.py b/examples/adwords/v201409/basic_operations/update_keyword.py deleted file mode 100755 index 2f5382b1..00000000 --- a/examples/adwords/v201409/basic_operations/update_keyword.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/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. - -"""This example updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201409/campaign_management/__init__.py b/examples/adwords/v201409/campaign_management/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/campaign_management/add_campaign_labels.py b/examples/adwords/v201409/campaign_management/add_campaign_labels.py deleted file mode 100755 index 55f5e3ff..00000000 --- a/examples/adwords/v201409/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/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. - -"""This example adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutateLabel -""" - -__author__ = 'Mark Saniscalchi' - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201409') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201409/campaign_management/add_experiment.py b/examples/adwords/v201409/campaign_management/add_experiment.py deleted file mode 100755 index 564cb7b4..00000000 --- a/examples/adwords/v201409/campaign_management/add_experiment.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/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. - -"""This example creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ExperimentService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import datetime -import uuid - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201409') - ad_group_service = client.GetService('AdGroupService', version='v201409') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py deleted file mode 100755 index f7fe5fa9..00000000 --- a/examples/adwords/v201409/campaign_management/add_keywords_in_bulk.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/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. - -"""This code sample illustrates how to perform asynchronous requests. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: MutateJobService.mutate -Tags: MutateJobService.get -Tags: MutateJobService.getResult -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import random -import re -import time - -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -KEYWORD_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201409') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add keywords. - for i in range(KEYWORD_NUMBER): - keyword = 'mars%d' % i - if random.randint(1, 10) == 1: - keyword += '!!!' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': keyword - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - keyword = operations[index]['operand']['criterion']['text'] - print ('ERROR - keyword \'%s\' failed due to \'%s\'' % - (keyword, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/campaign_management/add_location_extension.py b/examples/adwords/v201409/campaign_management/add_location_extension.py deleted file mode 100755 index 17c6dfa9..00000000 --- a/examples/adwords/v201409/campaign_management/add_location_extension.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -*- coding: UTF-8 -*- -# -# 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. - -"""This example adds a campaign ad extension to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: GeoLocationService.get, CampaignAdExtensionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - geo_location_service = client.GetService( - 'GeoLocationService', version='v201409') - campaign_ad_extension_service = client.GetService( - 'CampaignAdExtensionService', version='v201409') - - # Construct selector and get geo location info for given addresses. - selector = { - 'addresses': [ - { - 'streetAddress': '1600 Amphitheatre Parkway', - 'cityName': 'Mountain View', - 'provinceCode': 'US-CA', - 'provinceName': 'California', - 'postalCode': '94043', - 'countryCode': 'US' - }, - { - 'streetAddress': u'38 avenue de l\'Opéra', - 'cityName': 'Paris', - 'postalCode': '75002', - 'countryCode': 'FR' - } - ] - } - geo_locations = geo_location_service.get(selector) - - # Construct operations and add campaign ad extension. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'CampaignAdExtension', - 'campaignId': campaign_id, - 'adExtension': { - 'xsi_type': 'LocationExtension', - 'address': geo_locations[0]['address'], - 'geoPoint': geo_locations[0]['geoPoint'], - 'encodedLocation': geo_locations[0]['encodedLocation'], - 'source': 'ADWORDS_FRONTEND', - # Optional fields. - 'companyName': 'ACME Inc.', - 'phoneNumber': '(650) 253-0000' - } - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'CampaignAdExtension', - 'campaignId': campaign_id, - 'adExtension': { - 'xsi_type': 'LocationExtension', - 'address': geo_locations[1]['address'], - 'geoPoint': geo_locations[1]['geoPoint'], - 'encodedLocation': geo_locations[1]['encodedLocation'], - 'source': 'ADWORDS_FRONTEND' - } - } - } - ] - ad_extensions = campaign_ad_extension_service.mutate(operations) - - # Display results. - for ad_extension in ad_extensions['value']: - print ('Campaign ad extension with id \'%s\' and status \'%s\' was added.' - % (ad_extension['adExtension']['id'], ad_extension['status'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201409/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index ce70f54f..00000000 --- a/examples/adwords/v201409/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/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. - -"""This example gets all disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201409/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 4937b293..00000000 --- a/examples/adwords/v201409/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/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. - -"""This example gets all disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201409/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 151c7836..00000000 --- a/examples/adwords/v201409/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/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. - -"""This example gets all campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.get -""" - -__author__ = 'Mark Saniscalchi' - -import time - -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201409') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201409/campaign_management/promote_experiment.py b/examples/adwords/v201409/campaign_management/promote_experiment.py deleted file mode 100755 index cc7441f0..00000000 --- a/examples/adwords/v201409/campaign_management/promote_experiment.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/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. - -"""This example promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ExperimentService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201409') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201409/campaign_management/set_ad_parameters.py b/examples/adwords/v201409/campaign_management/set_ad_parameters.py deleted file mode 100755 index 2d250429..00000000 --- a/examples/adwords/v201409/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,107 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# 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. - -"""This example adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate, AdParamService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - ad_param_service = client.GetService('AdParamService', version='v201409') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': { - 'urls': ['http://www.example.com'] - }, - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201409/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201409/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index dabdb07b..00000000 --- a/examples/adwords/v201409/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/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. - -"""This example sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.mutate -""" - -__author__ = ('api.dklimkin@gmail.com (Danial Klimkin)', - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201409') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201409/campaign_management/validate_text_ad.py b/examples/adwords/v201409/campaign_management/validate_text_ad.py deleted file mode 100755 index f3b67794..00000000 --- a/examples/adwords/v201409/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/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. - -"""This example shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': { - 'urls': ['http://www.example.com'] - }, - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/error_handling/__init__.py b/examples/adwords/v201409/error_handling/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/error_handling/handle_partial_failures.py b/examples/adwords/v201409/error_handling/handle_partial_failures.py deleted file mode 100755 index a3c3c246..00000000 --- a/examples/adwords/v201409/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/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. - -"""This example demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import re - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/error_handling/handle_policy_violation_error.py b/examples/adwords/v201409/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 16aa6e22..00000000 --- a/examples/adwords/v201409/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/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. - -"""This example demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.mutate -""" - -__author__ = 'Joseph DiLallo' - -import re - -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201409') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - operation = operations[int(operation_index[0])] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) - else: - # Non-policy error returned, re-throw exception. - raise e - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/extensions/__init__.py b/examples/adwords/v201409/extensions/__init__.py deleted file mode 100644 index b4d63e00..00000000 --- a/examples/adwords/v201409/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201409/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201409/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index d3408644..00000000 --- a/examples/adwords/v201409/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CustomerFeedService.mutate, FeedService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' -# To obtain an access token for your Places account, you can run the -# generate_refresh_token.py example and manually replace the scope with -# "https://www.google.com/local/add". -GMB_ACCESS_TOKEN = 'INSERT_GMB_OAUTH_ACCESS_TOKEN_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201409').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201409') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201409/extensions/add_site_links.py b/examples/adwords/v201409/extensions/add_site_links.py deleted file mode 100755 index e1c6079e..00000000 --- a/examples/adwords/v201409/extensions/add_site_links.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignExtensionSettingService.mutate, CustomerService.get -Api: AdWordsOnly -""" - -__author__ = 'Mark Saniscalchi' - -from datetime import datetime - - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201409') - customer_service = client.GetService('CustomerService', version='v201409') - - customer_tz = timezone(customer_service.get()['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkUrl': 'http://www.example.com/storehours' - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkUrl': 'http://www.example.com/thanksgiving', - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt) - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkUrl': 'http://www.example.com/mobile/wifi', - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'} - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkUrl': 'http://www.example.com/happyhours', - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/extensions/add_site_links_using_feeds.py b/examples/adwords/v201409/extensions/add_site_links_using_feeds.py deleted file mode 100755 index 7049faaa..00000000 --- a/examples/adwords/v201409/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,265 +0,0 @@ -#!/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. - -"""This example adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignFeedService.mutate, FeedItemService.mutate -Tags: FeedMappingService.mutate, FeedService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Joseph DiLallo' - -import uuid - -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URL = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201409') - feed_item_service = client.GetService('FeedItemService', version='v201409') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201409') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201409') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'url': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'url': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'url': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'url': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'url': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About', 'url': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2'} - ] - - feed_items = [] - for item in items_data: - feed_items.append({ - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValue': item['url'] - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - - # Optional: use the 'scheduling' key to specify time and days of the - # week for feed to deliver. This is a Beta feature. - }) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URL - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Create site links campaign feed. - operands = [] - for feed_item_id in sitelinks_data['feedItemIds']: - operands.append({ - 'xsi_type': 'ConstantOperand', - 'type': 'LONG', - 'longValue': feed_item_id - }) - - feed_item_function = { - 'operator': 'IN', - 'lhsOperand': [ - {'xsi_type': 'RequestContextOperand', 'contextType': 'FEED_ITEM_ID'} - ], - 'rhsOperand': operands - } - - # Optional: to target to a platform, define a function and 'AND' it with the - # feed item ID link: - platform_function = { - 'operator': 'EQUALS', - 'lhsOperand': [ - { - 'xsi_type': 'RequestContextOperand', - 'contextType': 'DEVICE_PLATFORM' - } - ], - 'rhsOperand': [ - { - 'xsi_type': 'ConstantOperand', - 'type': 'STRING', - 'stringValue': 'Mobile' - } - ] - } - combined_function = { - 'operator': 'AND', - 'lhsOperand': [ - {'xsi_type': 'FunctionOperand', 'value': feed_item_function}, - {'xsi_type': 'FunctionOperand', 'value': platform_function} - ] - } - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': combined_function, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/migration/__init__.py b/examples/adwords/v201409/migration/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/migration/migrate_to_extension_settings.py b/examples/adwords/v201409/migration/migrate_to_extension_settings.py deleted file mode 100755 index 9b76ebd2..00000000 --- a/examples/adwords/v201409/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,528 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: FeedService.get, FeedMappingService.get, FeedItemService.get -Tags: CampaignExtensionSettingService.mutate, CampaignFeedService.get, -Tags: CampaignFeedService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Mark Saniscalchi' - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201409') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201409') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201409') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201409') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201409') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201409') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - if ('lhsOperand' in campaign_feed['matchingFunction'] and - campaign_feed['matchingFunction']['lhsOperand'][0]['xsi_type'] == - 'RequestContextOperand'): - request_context_operand = campaign_feed['matchingFunction']['lhsOperand'][0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201409') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings['attributeValue']['feedAttributeId']: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/migration/upgrade_ad_url.py b/examples/adwords/v201409/migration/upgrade_ad_url.py deleted file mode 100755 index ffeba4ba..00000000 --- a/examples/adwords/v201409/migration/upgrade_ad_url.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 upgrades an ad to use upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupAdService.get, AdGroupAdService.upgradeUrl -""" - -__author__ = 'Mark Saniscalchi' - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, adgroup_id, ad_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201409') - - selector = { - 'fields': ['Id', 'Url'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [ad_id] - } - ] - } - - page = adgroup_ad_service.get(selector) - - adgroup_ad = page['entries'][0] if page['entries'] else None - - if not adgroup_ad: - raise errors.GoogleAdsError('Ad not found.') - - ad_url_upgrade = { - 'adId': adgroup_ad['ad']['id'], - 'finalUrl': adgroup_ad['ad']['url'] - } - - adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] - - if adgroup_ad: - print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' - % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201409/misc/__init__.py b/examples/adwords/v201409/misc/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/misc/get_all_images_and_videos.py b/examples/adwords/v201409/misc/get_all_images_and_videos.py deleted file mode 100755 index 194af246..00000000 --- a/examples/adwords/v201409/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/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. - -"""This example gets all images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: MediaService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201409') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - print ('Media with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], image['mimeType'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/misc/upload_image.py b/examples/adwords/v201409/misc/upload_image.py deleted file mode 100755 index 7b9aa88b..00000000 --- a/examples/adwords/v201409/misc/upload_image.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/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. - -"""This example uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: MediaService.upload -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import base64 - -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201409') - - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201409/optimization/__init__.py b/examples/adwords/v201409/optimization/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/optimization/estimate_keyword_traffic.py b/examples/adwords/v201409/optimization/estimate_keyword_traffic.py deleted file mode 100755 index d1bae290..00000000 --- a/examples/adwords/v201409/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/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. - -"""This example retrieves keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: TrafficEstimatorService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201409') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - selector = { - 'campaignEstimateRequests': [{ - 'adGroupEstimateRequests': [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }], - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ] - }] - } - estimates = traffic_estimator_service.get(selector) - - # Display results. - ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] - keyword_estimates = ad_group_estimate['keywordEstimates'] - for index in xrange(len(keyword_estimates)): - keyword = keyword_estimate_requests[index]['keyword'] - estimate = keyword_estimates[index] - if keyword_estimate_requests[index].get('isNegative', False): - continue - - # Find the mean of the min and max values. - if (estimate['min']['clicksPerDay'] and estimate['max']['clicksPerDay'] and - estimate['min']['impressionsPerDay'] and - estimate['max']['impressionsPerDay']): - mean_avg_cpc = (int(estimate['min']['averageCpc']['microAmount']) + - int(estimate['max']['averageCpc']['microAmount'])) / 2 - mean_avg_pos = (float(estimate['min']['averagePosition']) + - float(estimate['max']['averagePosition'])) / 2 - mean_clicks = (float(estimate['min']['clicksPerDay']) + - float(estimate['max']['clicksPerDay'])) / 2 - mean_total_cost = (int(estimate['min']['totalCost']['microAmount']) + - int(estimate['max']['totalCost']['microAmount'])) / 2 - else: - # Default to 0 if no clicks/impressions per day. - mean_avg_cpc = 0 - mean_avg_pos = 0 - mean_clicks = 0 - mean_total_cost = 0 - - print ('Results for the keyword with text \'%s\' and match type \'%s\':' - % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % mean_avg_cpc - print ' Estimated ad position: %s' % mean_avg_pos - print ' Estimated daily clicks: %s' % mean_clicks - print ' Estimated daily cost: %s' % mean_total_cost - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201409/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index 4e0197b1..00000000 --- a/examples/adwords/v201409/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/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. - -"""This example gets a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: BidLandscapeService.getBidLandscape -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201409') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'MarginalCpc', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, marginalCpc: %s, ' - 'impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['marginalCpc']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201409/optimization/get_keyword_ideas.py b/examples/adwords/v201409/optimization/get_keyword_ideas.py deleted file mode 100755 index ec91a490..00000000 --- a/examples/adwords/v201409/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/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. - -"""This example retrieves keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: TargetingIdeaService.get -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201409') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/remarketing/__init__.py b/examples/adwords/v201409/remarketing/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/remarketing/add_audience.py b/examples/adwords/v201409/remarketing/add_audience.py deleted file mode 100755 index 36dd9f02..00000000 --- a/examples/adwords/v201409/remarketing/add_audience.py +++ /dev/null @@ -1,107 +0,0 @@ -#!/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. - -"""This example adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: UserListService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201409') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201409') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/remarketing/add_conversion_tracker.py b/examples/adwords/v201409/remarketing/add_conversion_tracker.py deleted file mode 100755 index f21bdeb6..00000000 --- a/examples/adwords/v201409/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/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. - -"""This example adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ConversionTrackerService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201409') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'markupLanguage': 'HTML', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'isProductAdsChargeable': 'true', - 'productAdsChargeableConversionWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201409/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index d4cdada1..00000000 --- a/examples/adwords/v201409/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/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. - -"""This example adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdwordsUserListService.mutate -""" - -__author__ = 'Mark Saniscalchi' - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201409') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/reporting/__init__.py b/examples/adwords/v201409/reporting/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/reporting/download_criteria_report.py b/examples/adwords/v201409/reporting/download_criteria_report.py deleted file mode 100755 index 3211018e..00000000 --- a/examples/adwords/v201409/reporting/download_criteria_report.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Joseph DiLallo' - -import logging -import sys - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201409') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport(report, sys.stdout) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index 88ef3f8b..00000000 --- a/examples/adwords/v201409/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/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. - -"""This example retrieves the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Mark Saniscalchi' - -import logging -import sys - -from googleads import adwords -import StringIO - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201409') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream(report) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index ad854202..00000000 --- a/examples/adwords/v201409/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -import logging -import StringIO -import sys - - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201409') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV') - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_string.py b/examples/adwords/v201409/reporting/download_criteria_report_as_string.py deleted file mode 100755 index f6ba8c74..00000000 --- a/examples/adwords/v201409/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = 'Mark Saniscalchi' - -import logging -import sys - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201409') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString(report) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201409/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201409/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index f07df0f9..00000000 --- a/examples/adwords/v201409/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201409') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201409/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 627d3cf0..00000000 --- a/examples/adwords/v201409/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/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. - -"""This example downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.mutate -Api: AdWordsOnly -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201409') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql(report_query, 'CSV', output_file) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201409/reporting/get_report_fields.py b/examples/adwords/v201409/reporting/get_report_fields.py deleted file mode 100755 index 5cb7e131..00000000 --- a/examples/adwords/v201409/reporting/get_report_fields.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/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. - -"""This example gets report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ReportDefinitionService.getReportFields -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201409') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201409/shopping/add_product_partition_tree.py b/examples/adwords/v201409/shopping/add_product_partition_tree.py deleted file mode 100755 index 9bc821a3..00000000 --- a/examples/adwords/v201409/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,285 +0,0 @@ -#!/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. - -"""This example creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) - diff --git a/examples/adwords/v201409/shopping/add_product_scope.py b/examples/adwords/v201409/shopping/add_product_scope.py deleted file mode 100755 index 690e26d4..00000000 --- a/examples/adwords/v201409/shopping/add_product_scope.py +++ /dev/null @@ -1,107 +0,0 @@ -#!/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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201409') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/shopping/add_shopping_campaign.py b/examples/adwords/v201409/shopping/add_shopping_campaign.py deleted file mode 100755 index 0748cc24..00000000 --- a/examples/adwords/v201409/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,122 +0,0 @@ -#!/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. - -"""This example adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignService.mutate, AdGroupService.mutate, AdGroupAdService.mutate -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201409') - ad_group_service = client.GetService('AdGroupService', version='v201409') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set shared budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201409/shopping/get_product_category_taxonomy.py b/examples/adwords/v201409/shopping/get_product_category_taxonomy.py deleted file mode 100755 index b544d5f6..00000000 --- a/examples/adwords/v201409/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/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. - -"""This example fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ConstantDataService.getProductBiddingCategoryData -""" - -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201409') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/targeting/__init__.py b/examples/adwords/v201409/targeting/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adwords/v201409/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201409/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index e446c210..00000000 --- a/examples/adwords/v201409/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/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. - -"""This example adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.mutate -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201409') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - florida_downtown = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'PlacesOfInterestOperand', - # Other valid options: AIRPORT, UNIVERSITY. - 'category': 'DOWNTOWN', - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - } - } - # Distance targeting. Area of 10 miles around targets above. - distance_10_miles = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - - }] - } - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - - # Create operations - operations = [] - for criterion in [california, mexico, english, spanish, florida_tier3, - florida_downtown, distance_10_miles]: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201409/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201409/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 59fb8194..00000000 --- a/examples/adwords/v201409/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/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. - -"""This example adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: AdGroupCriterionService.mutate -""" - -__author__ = 'Joseph Dilallo' - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201409/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201409/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index af886c92..00000000 --- a/examples/adwords/v201409/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/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. - -"""This example illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: CampaignCriterionService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201409') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201409/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index c0a83892..00000000 --- a/examples/adwords/v201409/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: ConstantDataService.getLanguageCriterion -Tags: ConstantDataService.getCarrierCriterion -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201409') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201409/targeting/lookup_location.py b/examples/adwords/v201409/targeting/lookup_location.py deleted file mode 100755 index 164901c9..00000000 --- a/examples/adwords/v201409/targeting/lookup_location.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/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. - -"""This example gets all LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Tags: LocationCriterionService.get -""" - -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201409') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/googleads.yaml b/googleads.yaml index f2362f43..b4c0abfb 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -14,7 +14,8 @@ dfp: client_id: INSERT_OAUTH_2_CLIENT_ID_HERE client_secret: INSERT_CLIENT_SECRET_HERE refresh_token: INSERT_REFRESH_TOKEN_HERE -# The following values are optional: +# The following values are required for all services except NetworkService, +# unless the network code is set directly on the DfpClient object: # network_code: INSERT_NETWORK_CODE_HERE dfa: diff --git a/googleads/adwords.py b/googleads/adwords.py index 09814278..93749ada 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -33,49 +33,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201409': { - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignAdExtensionService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'GeoLocationService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'MutateJobService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - }, 'v201502': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', diff --git a/googleads/common.py b/googleads/common.py index d853bbac..fd0e3ba7 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -28,7 +28,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.4.1' +VERSION = '3.6.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], From 8ff151f0efba94e1ecf731a42a9659fe2f35d03d Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Fri, 31 Jul 2015 23:25:39 +0900 Subject: [PATCH 012/180] Commiting latest changes. From 0f79457fabb5cc658253604a61844abe2b187c18 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 25 Aug 2015 14:34:03 -0400 Subject: [PATCH 013/180] Releasing v201508 of the DFP API --- ChangeLog | 5 + README.md | 26 +++- .../adwords_appengine_demo/demo/__init__.py | 3 - .../adwords_appengine_demo/demo/main.py | 1 - .../handlers/api_handler.py | 1 - .../handlers/ndb_handler.py | 1 - .../adwords_appengine_demo/models/app_user.py | 1 - .../adwords_appengine_demo/views/__init__.py | 1 - .../views/add_adgroup_view.py | 1 - .../views/add_campaign_view.py | 1 - .../adwords_appengine_demo/views/init_view.py | 1 - .../views/show_accounts_view.py | 1 - .../views/show_adgroups_view.py | 1 - .../views/show_budget_view.py | 1 - .../views/show_campaigns_view.py | 1 - .../views/show_credentials_view.py | 1 - .../views/update_budget_view.py | 1 - .../views/update_credentials_view.py | 1 - ...ate_adwords_client_with_service_account.py | 1 - .../create_adwords_client_without_yaml.py | 1 - .../authentication/generate_refresh_token.py | 1 - .../account_management/create_account.py | 3 - .../account_management/get_account_changes.py | 3 - .../get_account_hierarchy.py | 3 - .../advanced_operations/add_ad_customizer.py | 3 - .../add_ad_group_bid_modifier.py | 2 - .../add_click_to_download_ad.py | 4 - .../add_text_ad_with_upgraded_urls.py | 2 - .../create_and_attach_shared_keyword_set.py | 3 - ...ind_and_remove_criteria_from_shared_set.py | 3 - .../get_ad_group_bid_modifier.py | 2 - .../upload_offline_conversions.py | 2 - .../use_shared_bidding_strategy.py | 3 - .../v201502/basic_operations/add_ad_groups.py | 3 - .../v201502/basic_operations/add_campaigns.py | 4 - .../v201502/basic_operations/add_keywords.py | 3 - .../v201502/basic_operations/add_text_ads.py | 3 - .../v201502/basic_operations/get_ad_groups.py | 3 - .../v201502/basic_operations/get_campaigns.py | 2 - .../get_campaigns_with_awql.py | 3 - .../v201502/basic_operations/get_keywords.py | 3 - .../v201502/basic_operations/get_text_ads.py | 3 - .../v201502/basic_operations/pause_ad.py | 3 - .../v201502/basic_operations/remove_ad.py | 3 - .../basic_operations/remove_ad_group.py | 3 - .../basic_operations/remove_campaign.py | 3 - .../basic_operations/remove_keyword.py | 3 - .../basic_operations/update_ad_group.py | 3 - .../basic_operations/update_campaign.py | 3 - .../basic_operations/update_keyword.py | 3 - .../add_campaign_labels.py | 2 - .../campaign_management/add_experiment.py | 3 - .../add_keywords_in_bulk.py | 5 - .../get_all_disapproved_ads.py | 3 - .../get_all_disapproved_ads_with_awql.py | 3 - .../get_campaigns_by_label.py | 2 - .../campaign_management/promote_experiment.py | 3 - .../campaign_management/set_ad_parameters.py | 3 - .../set_criterion_bid_modifier.py | 4 - .../campaign_management/validate_text_ad.py | 3 - .../error_handling/handle_partial_failures.py | 3 - .../handle_policy_violation_error.py | 2 - ..._google_my_business_location_extensions.py | 3 - .../v201502/extensions/add_site_links.py | 2 - .../extensions/add_site_links_using_feeds.py | 3 - .../migrate_to_extension_settings.py | 4 - .../v201502/migration/upgrade_ad_url.py | 2 - .../v201502/misc/get_all_images_and_videos.py | 3 - examples/adwords/v201502/misc/upload_image.py | 3 - .../optimization/estimate_keyword_traffic.py | 3 - .../get_keyword_bid_simulations.py | 3 - .../v201502/optimization/get_keyword_ideas.py | 3 - .../v201502/remarketing/add_audience.py | 3 - .../remarketing/add_conversion_tracker.py | 3 - .../remarketing/add_rule_based_user_lists.py | 2 - .../reporting/download_criteria_report.py | 2 - .../download_criteria_report_as_stream.py | 2 - ...oad_criteria_report_as_stream_with_awql.py | 3 - .../download_criteria_report_as_string.py | 2 - ...oad_criteria_report_as_string_with_awql.py | 3 - .../download_criteria_report_with_awql.py | 3 - .../v201502/reporting/get_report_fields.py | 3 - .../shopping/add_product_partition_tree.py | 3 - .../v201502/shopping/add_product_scope.py | 3 - .../v201502/shopping/add_shopping_campaign.py | 3 - .../shopping/get_product_category_taxonomy.py | 3 - .../add_campaign_targeting_criteria.py | 3 - .../add_demographic_targeting_criteria.py | 2 - .../get_campaign_targeting_criteria.py | 3 - .../get_targetable_languages_and_carriers.py | 4 - .../v201502/targeting/lookup_location.py | 3 - .../account_management/create_account.py | 3 - .../account_management/get_account_changes.py | 3 - .../get_account_hierarchy.py | 3 - .../advanced_operations/add_ad_customizer.py | 3 - .../add_ad_group_bid_modifier.py | 2 - .../add_click_to_download_ad.py | 4 - .../add_text_ad_with_upgraded_urls.py | 2 - .../create_and_attach_shared_keyword_set.py | 3 - ...ind_and_remove_criteria_from_shared_set.py | 3 - .../get_ad_group_bid_modifier.py | 2 - .../upload_offline_conversions.py | 2 - .../use_shared_bidding_strategy.py | 3 - .../v201506/basic_operations/add_ad_groups.py | 3 - .../v201506/basic_operations/add_campaigns.py | 4 - .../v201506/basic_operations/add_keywords.py | 3 - .../v201506/basic_operations/add_text_ads.py | 3 - .../v201506/basic_operations/get_ad_groups.py | 3 - .../v201506/basic_operations/get_campaigns.py | 2 - .../get_campaigns_with_awql.py | 3 - .../v201506/basic_operations/get_keywords.py | 3 - .../v201506/basic_operations/get_text_ads.py | 3 - .../v201506/basic_operations/pause_ad.py | 3 - .../v201506/basic_operations/remove_ad.py | 3 - .../basic_operations/remove_ad_group.py | 3 - .../basic_operations/remove_campaign.py | 3 - .../basic_operations/remove_keyword.py | 3 - .../basic_operations/update_ad_group.py | 3 - .../basic_operations/update_campaign.py | 3 - .../basic_operations/update_keyword.py | 3 - .../add_campaign_labels.py | 2 - .../campaign_management/add_experiment.py | 3 - .../add_keywords_in_bulk.py | 5 - .../get_all_disapproved_ads.py | 3 - .../get_all_disapproved_ads_with_awql.py | 3 - .../get_campaigns_by_label.py | 2 - .../campaign_management/promote_experiment.py | 3 - .../campaign_management/set_ad_parameters.py | 3 - .../set_criterion_bid_modifier.py | 4 - .../campaign_management/validate_text_ad.py | 3 - .../error_handling/handle_partial_failures.py | 3 - .../handle_policy_violation_error.py | 2 - ..._google_my_business_location_extensions.py | 3 - .../v201506/extensions/add_site_links.py | 2 - .../extensions/add_site_links_using_feeds.py | 3 - .../migrate_to_extension_settings.py | 4 - .../v201506/migration/upgrade_ad_url.py | 2 - .../v201506/misc/get_all_images_and_videos.py | 3 - examples/adwords/v201506/misc/upload_image.py | 3 - .../optimization/estimate_keyword_traffic.py | 3 - .../get_keyword_bid_simulations.py | 3 - .../v201506/optimization/get_keyword_ideas.py | 3 - .../v201506/remarketing/add_audience.py | 3 - .../remarketing/add_conversion_tracker.py | 3 - .../remarketing/add_rule_based_user_lists.py | 2 - .../reporting/download_criteria_report.py | 2 - .../download_criteria_report_as_stream.py | 2 - ...oad_criteria_report_as_stream_with_awql.py | 3 - .../download_criteria_report_as_string.py | 2 - ...oad_criteria_report_as_string_with_awql.py | 3 - .../download_criteria_report_with_awql.py | 3 - .../v201506/reporting/get_report_fields.py | 3 - .../shopping/add_product_partition_tree.py | 3 - .../v201506/shopping/add_product_scope.py | 3 - .../v201506/shopping/add_shopping_campaign.py | 3 - .../shopping/get_product_category_taxonomy.py | 3 - .../add_campaign_targeting_criteria.py | 3 - .../add_demographic_targeting_criteria.py | 2 - .../get_campaign_targeting_criteria.py | 3 - .../get_targetable_languages_and_carriers.py | 4 - .../v201506/targeting/lookup_location.py | 3 - .../v201409/basic_operations/add_ad_groups.py | 2 - .../v201409/basic_operations/add_campaigns.py | 3 - .../basic_operations/add_placements.py | 2 - .../add_third_party_redirect_ad.py | 2 - .../basic_operations/get_placements.py | 2 - .../get_third_party_redirect_ads.py | 2 - .../basic_operations/remove_placement.py | 2 - .../basic_operations/update_placement.py | 2 - .../add_placements_in_bulk.py | 4 - .../error_handling/handle_partial_failures.py | 2 - .../v201502/basic_operations/add_ad_groups.py | 2 - .../v201502/basic_operations/add_campaigns.py | 3 - .../basic_operations/add_placements.py | 2 - .../add_third_party_redirect_ad.py | 2 - .../basic_operations/get_placements.py | 2 - .../get_third_party_redirect_ads.py | 2 - .../basic_operations/remove_placement.py | 2 - .../basic_operations/update_placement.py | 2 - .../add_placements_in_bulk.py | 4 - .../error_handling/handle_partial_failures.py | 2 - .../v201506/basic_operations/add_ad_groups.py | 2 - .../v201506/basic_operations/add_campaigns.py | 3 - .../basic_operations/add_placements.py | 2 - .../add_third_party_redirect_ad.py | 2 - .../basic_operations/get_placements.py | 2 - .../get_third_party_redirect_ads.py | 2 - .../basic_operations/remove_placement.py | 2 - .../basic_operations/update_placement.py | 2 - .../add_placements_in_bulk.py | 4 - .../error_handling/handle_partial_failures.py | 2 - .../create_dfa_client_with_service_account.py | 1 - .../create_dfa_client_without_yaml.py | 1 - .../authentication/generate_refresh_token.py | 1 - .../dfa/v1_20/add_advertiser_user_filter.py | 2 - .../assign_advertisers_to_advertiser_group.py | 2 - .../v1_20/assign_creatives_to_placements.py | 2 - examples/dfa/v1_20/create_advertiser.py | 2 - examples/dfa/v1_20/create_advertiser_group.py | 2 - examples/dfa/v1_20/create_campaign.py | 2 - examples/dfa/v1_20/create_content_category.py | 2 - examples/dfa/v1_20/create_creative_field.py | 2 - .../dfa/v1_20/create_creative_field_value.py | 2 - examples/dfa/v1_20/create_creative_group.py | 2 - .../dfa/v1_20/create_flash_inpage_creative.py | 2 - examples/dfa/v1_20/create_html_asset.py | 2 - examples/dfa/v1_20/create_image_asset.py | 2 - .../v1_20/create_in_stream_video_creative.py | 2 - examples/dfa/v1_20/create_placement.py | 2 - .../dfa/v1_20/create_placement_strategy.py | 2 - examples/dfa/v1_20/create_rotation_group.py | 2 - .../dfa/v1_20/create_spotlight_activity.py | 2 - .../v1_20/create_spotlight_activity_group.py | 2 - examples/dfa/v1_20/create_subnetwork.py | 2 - examples/dfa/v1_20/create_user_role.py | 2 - examples/dfa/v1_20/download_tags.py | 2 - examples/dfa/v1_20/get_activity_groups.py | 2 - examples/dfa/v1_20/get_activity_types.py | 2 - examples/dfa/v1_20/get_ad_types.py | 2 - examples/dfa/v1_20/get_advertiser_groups.py | 2 - examples/dfa/v1_20/get_advertisers.py | 2 - .../dfa/v1_20/get_available_permissions.py | 2 - examples/dfa/v1_20/get_campaigns.py | 2 - .../v1_20/get_change_log_for_advertiser.py | 2 - .../dfa/v1_20/get_change_log_object_types.py | 2 - examples/dfa/v1_20/get_content_categories.py | 2 - examples/dfa/v1_20/get_countries.py | 2 - examples/dfa/v1_20/get_creative_field.py | 2 - .../dfa/v1_20/get_creative_field_values.py | 2 - examples/dfa/v1_20/get_creative_groups.py | 2 - examples/dfa/v1_20/get_creative_types.py | 2 - examples/dfa/v1_20/get_creatives.py | 2 - examples/dfa/v1_20/get_dfa_site.py | 2 - .../dfa/v1_20/get_placement_strategies.py | 2 - examples/dfa/v1_20/get_placement_types.py | 2 - examples/dfa/v1_20/get_placements.py | 2 - examples/dfa/v1_20/get_pricing_types.py | 2 - examples/dfa/v1_20/get_size.py | 2 - examples/dfa/v1_20/get_subnetworks.py | 2 - examples/dfa/v1_20/get_tag_method_types.py | 2 - examples/dfa/v1_20/get_user_filter_types.py | 2 - examples/dfa/v1_20/get_user_roles.py | 2 - examples/dfa/v1_20/get_users.py | 2 - .../create_dfp_client_with_service_account.py | 1 - .../create_dfp_client_without_yaml.py | 1 - .../authentication/generate_refresh_token.py | 1 - .../dfp/v201408/contact_service/__init__.py | 15 -- .../__init__.py | 15 -- .../dfp/v201408/content_service/__init__.py | 15 -- .../dfp/v201408/creative_service/__init__.py | 15 -- .../v201408/creative_set_service/__init__.py | 15 -- .../creative_template_service/__init__.py | 15 -- .../v201408/custom_field_service/__init__.py | 15 -- .../custom_targeting_service/__init__.py | 15 -- .../dfp/v201408/inventory_service/__init__.py | 15 -- .../dfp/v201408/label_service/__init__.py | 15 -- .../__init__.py | 15 -- .../dfp/v201408/line_item_service/__init__.py | 15 -- .../dfp/v201408/network_service/__init__.py | 15 -- .../dfp/v201408/order_service/__init__.py | 15 -- .../__init__.py | 15 -- .../dfp/v201408/report_service/__init__.py | 15 -- .../suggested_ad_unit_service/__init__.py | 15 -- examples/dfp/v201408/team_service/__init__.py | 15 -- examples/dfp/v201408/user_service/__init__.py | 15 -- .../user_team_association_service/__init__.py | 15 -- .../create_activity_groups.py | 3 - .../get_active_activity_groups.py | 3 - .../get_all_activity_groups.py | 3 - .../update_activity_groups.py | 4 - .../activity_service/create_activities.py | 3 - .../activity_service/get_active_activities.py | 3 - .../activity_service/get_all_activities.py | 3 - .../activity_service/update_activities.py | 4 - .../create_audience_segments.py | 2 - .../get_all_audience_segments.py | 2 - .../get_first_party_audience_segments.py | 2 - .../populate_first_party_audience_segments.py | 2 - .../update_audience_segments.py | 2 - .../create_product_base_rates.py | 2 - .../create_product_template_base_rates.py | 2 - .../base_rate_service/get_all_base_rates.py | 2 - .../get_base_rates_for_a_rate_card.py | 2 - .../base_rate_service/update_base_rates.py | 3 - .../company_service/create_companies.py | 3 - .../company_service/get_advertisers.py | 3 - .../company_service/get_all_companies.py | 3 - .../company_service/update_companies.py | 3 - .../contact_service/create_contacts.py | 3 - .../contact_service/get_all_contacts.py | 3 - .../contact_service/get_uninvited_contacts.py | 3 - .../contact_service/update_contacts.py | 4 - ...create_content_metadata_key_hierarchies.py | 3 - ...delete_content_metadata_key_hierarchies.py | 4 - ...et_all_content_metadata_key_hierarchies.py | 3 - ...update_content_metadata_key_hierarchies.py | 4 - .../content_service/get_all_content.py | 3 - .../get_content_by_category.py | 3 - .../create_creative_from_template.py | 5 +- .../creative_service/create_creatives.py | 3 - .../create_custom_creative.py | 3 - .../creative_service/get_all_creatives.py | 3 - .../get_creatives_by_statement.py | 3 - .../creative_service/update_creatives.py | 4 - .../associate_creative_set_to_line_item.py | 3 - .../create_creative_set.py | 3 - .../get_all_creative_sets.py | 3 - .../get_creative_sets_by_statement.py | 3 - .../update_creative_set.py | 4 - .../get_all_creative_templates.py | 3 - .../get_creative_templates_by_statement.py | 3 - .../create_creative_wrappers.py | 3 - .../deactivate_creative_wrapper.py | 4 - .../get_active_creative_wrappers.py | 3 - .../get_all_creative_wrappers.py | 3 - .../update_creative_wrappers.py | 4 - .../create_custom_field_options.py | 3 - .../create_custom_fields.py | 3 - .../deactivate_all_line_item_custom_fields.py | 4 - .../get_all_custom_fields.py | 3 - .../get_all_line_item_custom_fields.py | 3 - .../set_line_item_custom_field_value.py | 4 - .../update_custom_fields.py | 4 - ...create_custom_targeting_keys_and_values.py | 4 - .../delete_custom_targeting_keys.py | 3 - .../delete_custom_targeting_values.py | 3 - ...et_all_custom_targeting_keys_and_values.py | 2 - .../get_custom_targeting_keys_by_statement.py | 2 - ...et_custom_targeting_values_by_statement.py | 2 - .../update_custom_targeting_keys.py | 2 - .../update_custom_targeting_values.py | 2 - .../create_exchange_rates.py | 2 - .../get_all_exchange_rates.py | 2 - .../get_exchange_rates_by_currency_code.py | 2 - .../update_exchange_rates.py | 2 - .../v201411/forecast_service/get_forecast.py | 2 - .../forecast_service/get_forecast_by_id.py | 2 - .../inventory_service/archive_ad_units.py | 3 - .../inventory_service/create_ad_units.py | 3 - .../get_ad_unit_hierarchy.py | 3 - .../get_all_ad_unit_sizes.py | 3 - .../inventory_service/get_all_ad_units.py | 3 - .../get_top_level_ad_units.py | 3 - .../inventory_service/update_ad_units.py | 4 - .../v201411/label_service/create_labels.py | 2 - .../label_service/deactivate_labels.py | 2 - .../v201411/label_service/get_all_labels.py | 2 - .../label_service/get_labels_by_statement.py | 2 - .../v201411/label_service/update_labels.py | 2 - .../create_licas.py | 2 - .../deactivate_licas.py | 2 - .../get_all_licas.py | 2 - .../get_licas_by_statement.py | 2 - .../update_licas.py | 2 - .../line_item_service/activate_line_items.py | 2 - .../line_item_service/create_line_items.py | 2 - .../create_video_line_item.py | 2 - .../line_item_service/get_all_line_items.py | 2 - .../get_line_items_by_statement.py | 12 +- .../get_recently_updated_line_items.py | 2 - .../target_custom_criteria.py | 2 - .../line_item_service/update_line_items.py | 2 - .../network_service/get_all_networks.py | 2 - .../network_service/get_current_network.py | 2 - .../network_service/make_test_network.py | 2 - .../v201411/order_service/approve_orders.py | 2 - .../v201411/order_service/create_orders.py | 2 - .../v201411/order_service/get_all_orders.py | 2 - .../order_service/get_orders_by_statement.py | 2 - .../v201411/order_service/update_orders.py | 2 - .../placement_service/create_placements.py | 2 - .../deactivate_placements.py | 2 - .../placement_service/get_all_placements.py | 2 - .../get_placements_by_statement.py | 2 - .../placement_service/update_placements.py | 2 - .../create_premium_rates.py | 3 - .../get_all_premium_rates.py | 2 - .../get_premium_rates_for_a_rate_card.py | 2 - .../update_premium_rates.py | 3 - .../product_service/get_all_products.py | 2 - .../get_products_for_product_template.py | 2 - .../product_service/update_products.py | 3 - .../activate_product_templates.py | 3 - .../create_product_templates.py | 3 - .../get_all_product_templates.py | 2 - .../get_sponsorship_product_templates.py | 2 - .../update_product_templates.py | 3 - .../archive_proposal_line_items.py | 1 - .../create_proposal_line_items.py | 1 - .../get_all_proposal_line_items.py | 1 - .../get_proposal_line_items_for_proposal.py | 15 +- .../update_proposal_line_items.py | 1 - .../proposal_service/create_proposals.py | 1 - .../proposal_service/get_all_proposals.py | 1 - .../get_proposals_by_statement.py | 1 - .../submit_proposals_for_approval.py | 1 - .../proposal_service/update_proposals.py | 1 - .../fetch_match_tables.py | 2 - .../get_geo_targets.py | 2 - .../get_line_items_named_like.py | 2 - .../rate_card_service/get_all_rate_cards.py | 2 - .../get_rate_cards_priced_with_currency.py | 2 - .../report_service/run_delivery_report.py | 2 - .../report_service/run_inventory_report.py | 2 - .../report_service/run_reach_report.py | 2 - .../run_report_with_custom_fields.py | 2 - .../report_service/run_sales_report.py | 2 - .../approve_all_suggested_ad_units.py | 2 - .../get_all_suggested_ad_units.py | 2 - .../get_suggested_ad_units_by_statement.py | 2 - .../dfp/v201411/team_service/create_teams.py | 3 - .../dfp/v201411/team_service/get_all_teams.py | 3 - .../team_service/get_teams_by_statement.py | 3 - .../dfp/v201411/team_service/update_teams.py | 3 - .../dfp/v201411/user_service/create_users.py | 2 - .../v201411/user_service/deactivate_users.py | 2 - .../dfp/v201411/user_service/get_all_roles.py | 2 - .../dfp/v201411/user_service/get_all_users.py | 2 - .../v201411/user_service/get_current_user.py | 2 - .../user_service/get_users_by_statement.py | 2 - .../dfp/v201411/user_service/update_users.py | 2 - .../create_user_team_associations.py | 3 - .../delete_user_team_associations.py | 3 - .../get_all_user_team_associations.py | 3 - .../get_user_team_associations_for_user.py | 3 - .../update_user_team_associations.py | 4 - .../approve_workflow_approval_requests.py | 3 - ...workflow_approval_requests_by_statement.py | 2 - ...xternal_condition_requests_by_statement.py | 2 - ...er_workflow_external_condition_requests.py | 3 - .../create_activity_groups.py | 3 - .../get_active_activity_groups.py | 3 - .../get_all_activity_groups.py | 3 - .../update_activity_groups.py | 4 - .../activity_service/create_activities.py | 3 - .../activity_service/get_active_activities.py | 3 - .../activity_service/get_all_activities.py | 3 - .../activity_service/update_activities.py | 4 - .../create_audience_segments.py | 6 +- .../get_all_audience_segments.py | 2 - .../get_first_party_audience_segments.py | 2 - .../populate_first_party_audience_segments.py | 2 - .../update_audience_segments.py | 2 - .../create_product_base_rates.py | 2 - .../create_product_template_base_rates.py | 2 - .../base_rate_service/get_all_base_rates.py | 2 - .../get_base_rates_for_a_rate_card.py | 2 - .../base_rate_service/update_base_rates.py | 3 - .../company_service/create_companies.py | 3 - .../company_service/get_advertisers.py | 3 - .../company_service/get_all_companies.py | 3 - .../company_service/update_companies.py | 3 - .../contact_service/create_contacts.py | 3 - .../contact_service/get_all_contacts.py | 3 - .../contact_service/get_uninvited_contacts.py | 3 - .../contact_service/update_contacts.py | 4 - ...create_content_metadata_key_hierarchies.py | 3 - ...delete_content_metadata_key_hierarchies.py | 4 - ...et_all_content_metadata_key_hierarchies.py | 3 - ...update_content_metadata_key_hierarchies.py | 4 - .../content_service/get_all_content.py | 3 - .../get_content_by_category.py | 3 - .../create_creative_from_template.py | 5 +- .../creative_service/create_creatives.py | 3 - .../create_custom_creative.py | 3 - .../creative_service/get_all_creatives.py | 3 - .../get_creatives_by_statement.py | 3 - .../creative_service/update_creatives.py | 4 - .../associate_creative_set_to_line_item.py | 3 - .../create_creative_set.py | 3 - .../get_all_creative_sets.py | 3 - .../get_creative_sets_by_statement.py | 3 - .../update_creative_set.py | 4 - .../get_all_creative_templates.py | 3 - .../get_creative_templates_by_statement.py | 3 - .../create_creative_wrappers.py | 3 - .../deactivate_creative_wrapper.py | 4 - .../get_active_creative_wrappers.py | 3 - .../get_all_creative_wrappers.py | 3 - .../update_creative_wrappers.py | 4 - .../create_custom_field_options.py | 3 - .../create_custom_fields.py | 3 - .../deactivate_all_line_item_custom_fields.py | 4 - .../get_all_custom_fields.py | 3 - .../get_all_line_item_custom_fields.py | 3 - .../set_line_item_custom_field_value.py | 4 - .../update_custom_fields.py | 4 - ...create_custom_targeting_keys_and_values.py | 4 - .../delete_custom_targeting_keys.py | 3 - .../delete_custom_targeting_values.py | 3 - ...et_all_custom_targeting_keys_and_values.py | 2 - .../get_custom_targeting_keys_by_statement.py | 2 - ...et_custom_targeting_values_by_statement.py | 2 - .../update_custom_targeting_keys.py | 2 - .../update_custom_targeting_values.py | 2 - .../create_exchange_rates.py | 2 - .../get_all_exchange_rates.py | 2 - .../get_exchange_rates_by_currency_code.py | 2 - .../update_exchange_rates.py | 2 - .../get_availability_forecast.py | 3 - ...get_availability_forecast_for_line_item.py | 2 - .../get_delivery_forecast_for_line_items.py | 2 - .../inventory_service/archive_ad_units.py | 3 - .../inventory_service/create_ad_units.py | 3 - .../get_ad_unit_hierarchy.py | 3 - .../get_all_ad_unit_sizes.py | 3 - .../inventory_service/get_all_ad_units.py | 3 - .../get_top_level_ad_units.py | 3 - .../inventory_service/update_ad_units.py | 4 - .../v201502/label_service/create_labels.py | 2 - .../label_service/deactivate_labels.py | 2 - .../v201502/label_service/get_all_labels.py | 2 - .../label_service/get_labels_by_statement.py | 2 - .../v201502/label_service/update_labels.py | 2 - .../create_licas.py | 2 - .../deactivate_licas.py | 2 - .../get_all_licas.py | 2 - .../get_licas_by_statement.py | 2 - .../update_licas.py | 2 - .../line_item_service/activate_line_items.py | 2 - .../line_item_service/create_line_items.py | 2 - .../create_video_line_item.py | 2 - .../line_item_service/get_all_line_items.py | 2 - .../get_line_items_by_statement.py | 12 +- .../get_recently_updated_line_items.py | 2 - .../target_custom_criteria.py | 2 - .../line_item_service/update_line_items.py | 2 - .../network_service/get_all_networks.py | 2 - .../network_service/get_current_network.py | 2 - .../network_service/make_test_network.py | 2 - .../v201502/order_service/approve_orders.py | 2 - .../v201502/order_service/create_orders.py | 2 - .../v201502/order_service/get_all_orders.py | 2 - .../order_service/get_orders_by_statement.py | 2 - .../v201502/order_service/update_orders.py | 2 - .../placement_service/create_placements.py | 2 - .../deactivate_placements.py | 2 - .../placement_service/get_all_placements.py | 2 - .../get_placements_by_statement.py | 2 - .../placement_service/update_placements.py | 2 - .../create_premium_rates.py | 3 - .../get_all_premium_rates.py | 2 - .../get_premium_rates_for_a_rate_card.py | 2 - .../update_premium_rates.py | 3 - .../product_service/get_all_products.py | 2 - .../get_products_for_product_template.py | 2 - .../product_service/update_products.py | 3 - .../activate_product_templates.py | 3 - .../create_product_templates.py | 3 - .../get_all_product_templates.py | 2 - .../get_sponsorship_product_templates.py | 2 - .../update_product_templates.py | 3 - .../archive_proposal_line_items.py | 1 - .../create_proposal_line_items.py | 1 - .../get_all_proposal_line_items.py | 1 - .../get_proposal_line_items_for_proposal.py | 15 +- .../update_proposal_line_items.py | 1 - .../proposal_service/create_proposals.py | 1 - .../proposal_service/get_all_proposals.py | 1 - .../get_proposals_by_statement.py | 1 - .../submit_proposals_for_approval.py | 1 - .../proposal_service/update_proposals.py | 1 - .../fetch_match_tables.py | 2 - .../get_geo_targets.py | 2 - .../get_line_items_named_like.py | 2 - .../rate_card_service/get_all_rate_cards.py | 2 - .../get_rate_cards_priced_with_currency.py | 2 - .../report_service/run_delivery_report.py | 2 - .../report_service/run_inventory_report.py | 2 - .../report_service/run_reach_report.py | 2 - .../run_report_with_custom_fields.py | 2 - .../report_service/run_sales_report.py | 2 - .../approve_all_suggested_ad_units.py | 2 - .../get_all_suggested_ad_units.py | 2 - .../get_suggested_ad_units_by_statement.py | 2 - .../dfp/v201502/team_service/create_teams.py | 3 - .../dfp/v201502/team_service/get_all_teams.py | 3 - .../team_service/get_teams_by_statement.py | 3 - .../dfp/v201502/team_service/update_teams.py | 3 - .../dfp/v201502/user_service/create_users.py | 2 - .../v201502/user_service/deactivate_users.py | 2 - .../dfp/v201502/user_service/get_all_roles.py | 2 - .../dfp/v201502/user_service/get_all_users.py | 2 - .../v201502/user_service/get_current_user.py | 2 - .../user_service/get_users_by_statement.py | 2 - .../dfp/v201502/user_service/update_users.py | 2 - .../create_user_team_associations.py | 3 - .../delete_user_team_associations.py | 3 - .../get_all_user_team_associations.py | 3 - .../get_user_team_associations_for_user.py | 3 - .../update_user_team_associations.py | 4 - .../approve_workflow_approval_requests.py | 3 - ...workflow_approval_requests_by_statement.py | 2 - ...xternal_condition_requests_by_statement.py | 2 - ...er_workflow_external_condition_requests.py | 3 - .../create_activity_groups.py | 3 - .../get_active_activity_groups.py | 3 - .../get_all_activity_groups.py | 3 - .../update_activity_groups.py | 4 - .../activity_service/create_activities.py | 3 - .../activity_service/get_active_activities.py | 3 - .../activity_service/get_all_activities.py | 3 - .../activity_service/update_activities.py | 4 - .../create_audience_segments.py | 6 +- .../get_all_audience_segments.py | 2 - .../get_first_party_audience_segments.py | 2 - .../populate_first_party_audience_segments.py | 2 - .../update_audience_segments.py | 2 - .../create_product_base_rates.py | 2 - .../create_product_template_base_rates.py | 2 - .../base_rate_service/get_all_base_rates.py | 2 - .../get_base_rates_for_a_rate_card.py | 2 - .../base_rate_service/update_base_rates.py | 3 - .../company_service/create_companies.py | 3 - .../company_service/get_advertisers.py | 3 - .../company_service/get_all_companies.py | 3 - .../company_service/update_companies.py | 3 - .../contact_service/create_contacts.py | 3 - .../contact_service/get_all_contacts.py | 3 - .../contact_service/get_uninvited_contacts.py | 3 - .../contact_service/update_contacts.py | 4 - ...create_content_metadata_key_hierarchies.py | 3 - ...delete_content_metadata_key_hierarchies.py | 4 - ...et_all_content_metadata_key_hierarchies.py | 3 - ...update_content_metadata_key_hierarchies.py | 4 - .../content_service/get_all_content.py | 3 - .../get_content_by_category.py | 3 - .../create_creative_from_template.py | 5 +- .../creative_service/create_creatives.py | 3 - .../create_custom_creative.py | 3 - .../creative_service/get_all_creatives.py | 3 - .../get_creatives_by_statement.py | 3 - .../creative_service/update_creatives.py | 4 - .../associate_creative_set_to_line_item.py | 3 - .../create_creative_set.py | 3 - .../get_all_creative_sets.py | 3 - .../get_creative_sets_by_statement.py | 3 - .../update_creative_set.py | 4 - .../get_all_creative_templates.py | 3 - .../get_creative_templates_by_statement.py | 3 - .../create_creative_wrappers.py | 3 - .../deactivate_creative_wrapper.py | 4 - .../get_active_creative_wrappers.py | 3 - .../get_all_creative_wrappers.py | 3 - .../update_creative_wrappers.py | 4 - .../create_custom_field_options.py | 3 - .../create_custom_fields.py | 3 - .../deactivate_all_line_item_custom_fields.py | 4 - .../get_all_custom_fields.py | 3 - .../get_all_line_item_custom_fields.py | 3 - .../set_line_item_custom_field_value.py | 4 - .../update_custom_fields.py | 4 - ...create_custom_targeting_keys_and_values.py | 4 - .../delete_custom_targeting_keys.py | 3 - .../delete_custom_targeting_values.py | 3 - ...et_all_custom_targeting_keys_and_values.py | 2 - .../get_custom_targeting_keys_by_statement.py | 2 - ...et_custom_targeting_values_by_statement.py | 2 - .../update_custom_targeting_keys.py | 2 - .../update_custom_targeting_values.py | 2 - .../create_exchange_rates.py | 2 - .../get_all_exchange_rates.py | 2 - .../get_exchange_rates_by_currency_code.py | 2 - .../update_exchange_rates.py | 2 - .../get_availability_forecast.py | 3 - ...get_availability_forecast_for_line_item.py | 2 - .../get_delivery_forecast_for_line_items.py | 2 - .../inventory_service/archive_ad_units.py | 3 - .../inventory_service/create_ad_units.py | 3 - .../get_ad_unit_hierarchy.py | 3 - .../get_all_ad_unit_sizes.py | 3 - .../inventory_service/get_all_ad_units.py | 3 - .../get_top_level_ad_units.py | 3 - .../inventory_service/update_ad_units.py | 4 - .../v201505/label_service/create_labels.py | 2 - .../label_service/deactivate_labels.py | 2 - .../v201505/label_service/get_all_labels.py | 2 - .../label_service/get_labels_by_statement.py | 2 - .../v201505/label_service/update_labels.py | 2 - .../create_licas.py | 2 - .../deactivate_licas.py | 2 - .../get_all_licas.py | 2 - .../get_licas_by_statement.py | 2 - .../update_licas.py | 2 - .../line_item_service/activate_line_items.py | 2 - .../line_item_service/create_line_items.py | 2 - .../create_video_line_item.py | 2 - .../line_item_service/get_all_line_items.py | 2 - .../get_line_items_by_statement.py | 12 +- .../get_recently_updated_line_items.py | 2 - .../target_custom_criteria.py | 2 - .../line_item_service/update_line_items.py | 2 - .../network_service/get_all_networks.py | 2 - .../network_service/get_current_network.py | 2 - .../network_service/make_test_network.py | 2 - .../v201505/order_service/approve_orders.py | 2 - .../v201505/order_service/create_orders.py | 2 - .../v201505/order_service/get_all_orders.py | 2 - .../order_service/get_orders_by_statement.py | 2 - .../v201505/order_service/update_orders.py | 2 - .../placement_service/create_placements.py | 2 - .../deactivate_placements.py | 2 - .../placement_service/get_all_placements.py | 2 - .../get_placements_by_statement.py | 2 - .../placement_service/update_placements.py | 2 - .../create_premium_rates.py | 3 - .../get_all_premium_rates.py | 2 - .../get_premium_rates_for_a_rate_card.py | 2 - .../update_premium_rates.py | 3 - .../product_service/get_all_products.py | 2 - .../get_products_for_product_template.py | 2 - .../product_service/update_products.py | 3 - .../activate_product_templates.py | 3 - .../create_product_templates.py | 3 - .../get_all_product_templates.py | 2 - .../get_sponsorship_product_templates.py | 2 - .../update_product_templates.py | 3 - .../archive_proposal_line_items.py | 1 - .../create_proposal_line_items.py | 1 - .../get_all_proposal_line_items.py | 1 - .../get_proposal_line_items_for_proposal.py | 15 +- .../update_proposal_line_items.py | 1 - .../proposal_service/create_proposals.py | 1 - .../proposal_service/get_all_proposals.py | 1 - .../get_proposals_by_statement.py | 1 - .../submit_proposals_for_approval.py | 1 - .../proposal_service/update_proposals.py | 1 - .../fetch_match_tables.py | 2 - .../get_geo_targets.py | 2 - .../get_line_items_named_like.py | 2 - .../rate_card_service/get_all_rate_cards.py | 2 - .../get_rate_cards_priced_with_currency.py | 2 - .../report_service/run_delivery_report.py | 2 - .../report_service/run_inventory_report.py | 2 - .../report_service/run_reach_report.py | 2 - .../run_report_with_custom_fields.py | 2 - .../report_service/run_sales_report.py | 2 - .../approve_all_suggested_ad_units.py | 2 - .../get_all_suggested_ad_units.py | 2 - .../get_suggested_ad_units_by_statement.py | 2 - .../dfp/v201505/team_service/create_teams.py | 3 - .../dfp/v201505/team_service/get_all_teams.py | 3 - .../team_service/get_teams_by_statement.py | 3 - .../dfp/v201505/team_service/update_teams.py | 3 - .../dfp/v201505/user_service/create_users.py | 2 - .../v201505/user_service/deactivate_users.py | 2 - .../dfp/v201505/user_service/get_all_roles.py | 2 - .../dfp/v201505/user_service/get_all_users.py | 2 - .../v201505/user_service/get_current_user.py | 2 - .../user_service/get_users_by_statement.py | 2 - .../dfp/v201505/user_service/update_users.py | 2 - .../create_user_team_associations.py | 3 - .../delete_user_team_associations.py | 3 - .../get_all_user_team_associations.py | 3 - .../get_user_team_associations_for_user.py | 3 - .../update_user_team_associations.py | 4 - .../approve_workflow_approval_requests.py | 3 - ...workflow_approval_requests_by_statement.py | 2 - ...xternal_condition_requests_by_statement.py | 2 - ...er_workflow_external_condition_requests.py | 3 - .../activity_group_service/__init__.py | 2 +- .../create_activity_groups.py | 7 +- .../get_active_activity_groups.py | 7 +- .../get_all_activity_groups.py | 7 +- .../update_activity_groups.py | 8 +- .../activity_service/__init__.py | 2 +- .../activity_service/create_activities.py | 7 +- .../activity_service/get_active_activities.py | 7 +- .../activity_service/get_all_activities.py | 7 +- .../activity_service/update_activities.py | 8 +- .../audience_segment_service/__init__.py | 2 +- .../create_audience_segments.py | 12 +- .../get_all_audience_segments.py | 6 +- .../get_first_party_audience_segments.py | 6 +- .../populate_first_party_audience_segments.py | 6 +- .../update_audience_segments.py | 6 +- .../base_rate_service}/__init__.py | 2 +- .../create_product_base_rates.py | 63 ++++++++ .../create_product_template_base_rates.py | 63 ++++++++ .../base_rate_service/get_all_base_rates.py | 59 ++++++++ .../get_base_rates_for_a_rate_card.py | 69 +++++++++ .../base_rate_service/update_base_rates.py | 81 ++++++++++ .../dfp/v201508/company_service/__init__.py | 15 ++ .../company_service/create_companies.py | 7 +- .../company_service/get_advertisers.py | 7 +- .../company_service/get_all_companies.py | 7 +- .../company_service/update_companies.py | 7 +- .../dfp/v201508/contact_service/__init__.py | 15 ++ .../contact_service/create_contacts.py | 7 +- .../contact_service/get_all_contacts.py | 7 +- .../contact_service/get_uninvited_contacts.py | 7 +- .../contact_service/update_contacts.py | 8 +- .../__init__.py | 15 ++ ...create_content_metadata_key_hierarchies.py | 7 +- ...delete_content_metadata_key_hierarchies.py | 8 +- ...et_all_content_metadata_key_hierarchies.py | 7 +- ...update_content_metadata_key_hierarchies.py | 8 +- .../dfp/v201508/content_service/__init__.py | 15 ++ .../content_service/get_all_content.py | 7 +- .../get_content_by_category.py | 11 +- .../dfp/v201508/creative_service/__init__.py | 15 ++ .../create_creative_from_template.py | 11 +- .../creative_service/create_creatives.py | 9 +- .../create_custom_creative.py | 9 +- .../create_native_creative.py | 138 ++++++++++++++++++ .../creative_service/get_all_creatives.py | 9 +- .../get_creatives_by_statement.py | 9 +- .../creative_service/update_creatives.py | 8 +- .../v201508/creative_set_service/__init__.py | 15 ++ .../associate_creative_set_to_line_item.py | 7 +- .../create_creative_set.py | 7 +- .../get_all_creative_sets.py | 7 +- .../get_creative_sets_by_statement.py | 7 +- .../update_creative_set.py | 8 +- .../creative_template_service/__init__.py | 15 ++ .../get_all_creative_templates.py | 7 +- .../get_creative_templates_by_statement.py | 7 +- .../create_creative_wrappers.py | 7 +- .../deactivate_creative_wrapper.py | 8 +- .../get_active_creative_wrappers.py | 7 +- .../get_all_creative_wrappers.py | 7 +- .../update_creative_wrappers.py | 8 +- .../v201508/custom_field_service/__init__.py | 15 ++ .../create_custom_field_options.py | 7 +- .../create_custom_fields.py | 7 +- .../deactivate_all_line_item_custom_fields.py | 8 +- .../get_all_custom_fields.py | 7 +- .../get_all_line_item_custom_fields.py | 7 +- .../set_line_item_custom_field_value.py | 14 +- .../update_custom_fields.py | 8 +- .../custom_targeting_service/__init__.py | 15 ++ ...create_custom_targeting_keys_and_values.py | 8 +- .../delete_custom_targeting_keys.py | 7 +- .../delete_custom_targeting_values.py | 7 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- .../get_custom_targeting_keys_by_statement.py | 6 +- ...et_custom_targeting_values_by_statement.py | 6 +- .../update_custom_targeting_keys.py | 6 +- .../update_custom_targeting_values.py | 6 +- .../v201508/exchange_rate_service/__init__.py | 15 ++ .../create_exchange_rates.py | 58 ++++++++ .../get_all_exchange_rates.py | 60 ++++++++ .../get_exchange_rates_by_currency_code.py | 71 +++++++++ .../update_exchange_rates.py | 77 ++++++++++ .../get_availability_forecast.py} | 54 +++++-- ...et_availability_forecast_for_line_item.py} | 25 ++-- .../get_delivery_forecast_for_line_items.py | 52 +++++++ .../dfp/v201508/inventory_service/__init__.py | 15 ++ .../inventory_service/archive_ad_units.py | 7 +- .../inventory_service/create_ad_units.py | 7 +- .../get_ad_unit_hierarchy.py | 7 +- .../get_all_ad_unit_sizes.py | 7 +- .../inventory_service/get_all_ad_units.py | 7 +- .../get_top_level_ad_units.py | 9 +- .../inventory_service/update_ad_units.py | 8 +- .../dfp/v201508/label_service/__init__.py | 15 ++ .../label_service/create_labels.py | 6 +- .../label_service/deactivate_labels.py | 6 +- .../label_service/get_all_labels.py | 6 +- .../label_service/get_labels_by_statement.py | 6 +- .../label_service/update_labels.py | 6 +- .../__init__.py | 15 ++ .../create_licas.py | 6 +- .../deactivate_licas.py | 6 +- .../get_all_licas.py | 6 +- .../get_licas_by_statement.py | 6 +- .../update_licas.py | 6 +- .../dfp/v201508/line_item_service/__init__.py | 15 ++ .../line_item_service/activate_line_items.py | 6 +- .../line_item_service/create_line_items.py | 9 +- .../create_video_line_item.py | 43 ++---- .../line_item_service/get_all_line_items.py | 6 +- .../get_line_items_by_statement.py | 21 ++- .../get_recently_updated_line_items.py | 6 +- .../target_custom_criteria.py | 6 +- .../line_item_service/update_line_items.py | 6 +- .../dfp/v201508/network_service/__init__.py | 15 ++ .../network_service/get_all_networks.py | 6 +- .../network_service/get_current_network.py | 6 +- .../network_service/make_test_network.py | 6 +- .../dfp/v201508/order_service/__init__.py | 15 ++ .../order_service/approve_orders.py | 6 +- .../order_service/create_orders.py | 6 +- .../order_service/get_all_orders.py | 6 +- .../order_service/get_orders_by_statement.py | 6 +- .../order_service/update_orders.py | 6 +- .../placement_service/create_placements.py | 8 +- .../deactivate_placements.py | 6 +- .../placement_service/get_all_placements.py | 6 +- .../get_placements_by_statement.py | 6 +- .../placement_service/update_placements.py | 6 +- .../v201508/premium_rate_service/__init__.py | 15 ++ .../create_premium_rates.py | 81 ++++++++++ .../get_all_premium_rates.py | 58 ++++++++ .../get_premium_rates_for_a_rate_card.py | 68 +++++++++ .../update_premium_rates.py | 91 ++++++++++++ .../dfp/v201508/product_service/__init__.py | 15 ++ .../product_service/get_all_products.py | 53 +++++++ .../get_products_for_product_template.py | 62 ++++++++ .../product_service/update_products.py | 72 +++++++++ .../product_template_service/__init__.py | 15 ++ .../activate_product_templates.py | 79 ++++++++++ .../create_product_templates.py | 105 +++++++++++++ .../get_all_product_templates.py | 55 +++++++ .../get_sponsorship_product_templates.py | 61 ++++++++ .../update_product_templates.py | 98 +++++++++++++ .../proposal_line_item_service/__init__.py | 15 ++ .../archive_proposal_line_items.py | 81 ++++++++++ .../create_proposal_line_items.py | 120 +++++++++++++++ .../get_all_proposal_line_items.py | 57 ++++++++ .../get_proposal_line_items_for_proposal.py | 70 +++++++++ .../update_proposal_line_items.py | 77 ++++++++++ .../dfp/v201508/proposal_service/__init__.py | 15 ++ .../proposal_service/create_proposals.py | 76 ++++++++++ .../proposal_service/get_all_proposals.py | 52 +++++++ .../get_proposals_by_statement.py | 60 ++++++++ .../submit_proposals_for_approval.py | 72 +++++++++ .../proposal_service/update_proposals.py | 71 +++++++++ .../__init__.py | 15 ++ .../fetch_match_tables.py | 6 +- .../get_geo_targets.py | 8 +- .../get_line_items_named_like.py | 6 +- .../dfp/v201508/rate_card_service/__init__.py | 15 ++ .../rate_card_service/get_all_rate_cards.py | 53 +++++++ .../get_rate_cards_priced_with_currency.py | 62 ++++++++ .../dfp/v201508/report_service/__init__.py | 15 ++ .../report_service/run_delivery_report.py | 20 ++- .../report_service/run_inventory_report.py | 8 +- .../report_service/run_reach_report.py | 6 +- .../run_report_with_custom_fields.py | 8 +- .../report_service/run_sales_report.py | 6 +- .../suggested_ad_unit_service/__init__.py | 15 ++ .../approve_all_suggested_ad_units.py | 6 +- .../get_all_suggested_ad_units.py | 6 +- .../get_suggested_ad_units_by_statement.py | 6 +- examples/dfp/v201508/team_service/__init__.py | 15 ++ .../team_service/create_teams.py | 7 +- .../team_service/get_all_teams.py | 7 +- .../team_service/get_teams_by_statement.py | 7 +- .../team_service/update_teams.py | 7 +- examples/dfp/v201508/user_service/__init__.py | 15 ++ .../user_service/create_users.py | 6 +- .../user_service/deactivate_users.py | 6 +- .../user_service/get_all_roles.py | 6 +- .../user_service/get_all_users.py | 6 +- .../user_service/get_current_user.py | 6 +- .../user_service/get_users_by_statement.py | 6 +- .../user_service/update_users.py | 6 +- .../user_team_association_service/__init__.py | 15 ++ .../create_user_team_associations.py | 7 +- .../delete_user_team_associations.py | 7 +- .../get_all_user_team_associations.py | 7 +- .../get_user_team_associations_for_user.py | 7 +- .../update_user_team_associations.py | 8 +- .../workflow_request_service/__init__.py | 15 ++ .../approve_workflow_approval_requests.py | 97 ++++++++++++ ...workflow_approval_requests_by_statement.py | 67 +++++++++ ...xternal_condition_requests_by_statement.py | 67 +++++++++ ...er_workflow_external_condition_requests.py | 100 +++++++++++++ googleads/adwords.py | 1 - googleads/common.py | 3 +- googleads/dfa.py | 1 - googleads/dfp.py | 37 ++--- googleads/errors.py | 2 - googleads/oauth2.py | 3 +- setup.py | 1 - tests/adwords_test.py | 1 - tests/common_test.py | 1 - tests/dfa_test.py | 1 - tests/dfp_test.py | 1 - tests/errors_test.py | 1 - tests/oauth2_test.py | 1 - 972 files changed, 3746 insertions(+), 2869 deletions(-) delete mode 100755 examples/dfp/v201408/contact_service/__init__.py delete mode 100755 examples/dfp/v201408/content_metadata_key_hierarchy_service/__init__.py delete mode 100755 examples/dfp/v201408/content_service/__init__.py delete mode 100755 examples/dfp/v201408/creative_service/__init__.py delete mode 100755 examples/dfp/v201408/creative_set_service/__init__.py delete mode 100755 examples/dfp/v201408/creative_template_service/__init__.py delete mode 100755 examples/dfp/v201408/custom_field_service/__init__.py delete mode 100755 examples/dfp/v201408/custom_targeting_service/__init__.py delete mode 100755 examples/dfp/v201408/inventory_service/__init__.py delete mode 100755 examples/dfp/v201408/label_service/__init__.py delete mode 100755 examples/dfp/v201408/line_item_creative_association_service/__init__.py delete mode 100755 examples/dfp/v201408/line_item_service/__init__.py delete mode 100755 examples/dfp/v201408/network_service/__init__.py delete mode 100755 examples/dfp/v201408/order_service/__init__.py delete mode 100755 examples/dfp/v201408/publisher_query_language_service/__init__.py delete mode 100755 examples/dfp/v201408/report_service/__init__.py delete mode 100755 examples/dfp/v201408/suggested_ad_unit_service/__init__.py delete mode 100755 examples/dfp/v201408/team_service/__init__.py delete mode 100755 examples/dfp/v201408/user_service/__init__.py delete mode 100755 examples/dfp/v201408/user_team_association_service/__init__.py rename examples/dfp/{v201408 => v201508}/activity_group_service/__init__.py (91%) rename examples/dfp/{v201408 => v201508}/activity_group_service/create_activity_groups.py (91%) rename examples/dfp/{v201408 => v201508}/activity_group_service/get_active_activity_groups.py (90%) rename examples/dfp/{v201408 => v201508}/activity_group_service/get_all_activity_groups.py (88%) rename examples/dfp/{v201408 => v201508}/activity_group_service/update_activity_groups.py (90%) rename examples/dfp/{v201408 => v201508}/activity_service/__init__.py (91%) rename examples/dfp/{v201408 => v201508}/activity_service/create_activities.py (92%) rename examples/dfp/{v201408 => v201508}/activity_service/get_active_activities.py (92%) rename examples/dfp/{v201408 => v201508}/activity_service/get_all_activities.py (91%) rename examples/dfp/{v201408 => v201508}/activity_service/update_activities.py (91%) rename examples/dfp/{v201408 => v201508}/audience_segment_service/__init__.py (91%) rename examples/dfp/{v201408 => v201508}/audience_segment_service/create_audience_segments.py (91%) rename examples/dfp/{v201408 => v201508}/audience_segment_service/get_all_audience_segments.py (91%) rename examples/dfp/{v201408 => v201508}/audience_segment_service/get_first_party_audience_segments.py (92%) rename examples/dfp/{v201408 => v201508}/audience_segment_service/populate_first_party_audience_segments.py (93%) rename examples/dfp/{v201408 => v201508}/audience_segment_service/update_audience_segments.py (94%) rename examples/dfp/{v201408/company_service => v201508/base_rate_service}/__init__.py (91%) create mode 100755 examples/dfp/v201508/base_rate_service/create_product_base_rates.py create mode 100755 examples/dfp/v201508/base_rate_service/create_product_template_base_rates.py create mode 100755 examples/dfp/v201508/base_rate_service/get_all_base_rates.py create mode 100755 examples/dfp/v201508/base_rate_service/get_base_rates_for_a_rate_card.py create mode 100755 examples/dfp/v201508/base_rate_service/update_base_rates.py create mode 100755 examples/dfp/v201508/company_service/__init__.py rename examples/dfp/{v201408 => v201508}/company_service/create_companies.py (91%) rename examples/dfp/{v201408 => v201508}/company_service/get_advertisers.py (92%) rename examples/dfp/{v201408 => v201508}/company_service/get_all_companies.py (91%) rename examples/dfp/{v201408 => v201508}/company_service/update_companies.py (93%) create mode 100755 examples/dfp/v201508/contact_service/__init__.py rename examples/dfp/{v201408 => v201508}/contact_service/create_contacts.py (93%) rename examples/dfp/{v201408 => v201508}/contact_service/get_all_contacts.py (91%) rename examples/dfp/{v201408 => v201508}/contact_service/get_uninvited_contacts.py (92%) rename examples/dfp/{v201408 => v201508}/contact_service/update_contacts.py (91%) create mode 100755 examples/dfp/v201508/content_metadata_key_hierarchy_service/__init__.py rename examples/dfp/{v201408 => v201508}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (91%) rename examples/dfp/{v201408 => v201508}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (89%) rename examples/dfp/{v201408 => v201508}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (89%) rename examples/dfp/{v201408 => v201508}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (91%) create mode 100755 examples/dfp/v201508/content_service/__init__.py rename examples/dfp/{v201408 => v201508}/content_service/get_all_content.py (91%) rename examples/dfp/{v201408 => v201508}/content_service/get_content_by_category.py (94%) create mode 100755 examples/dfp/v201508/creative_service/__init__.py rename examples/dfp/{v201408 => v201508}/creative_service/create_creative_from_template.py (91%) rename examples/dfp/{v201408 => v201508}/creative_service/create_creatives.py (91%) rename examples/dfp/{v201408 => v201508}/creative_service/create_custom_creative.py (92%) create mode 100755 examples/dfp/v201508/creative_service/create_native_creative.py rename examples/dfp/{v201408 => v201508}/creative_service/get_all_creatives.py (89%) rename examples/dfp/{v201408 => v201508}/creative_service/get_creatives_by_statement.py (90%) rename examples/dfp/{v201408 => v201508}/creative_service/update_creatives.py (92%) create mode 100755 examples/dfp/v201508/creative_set_service/__init__.py rename examples/dfp/{v201408 => v201508}/creative_set_service/associate_creative_set_to_line_item.py (88%) rename examples/dfp/{v201408 => v201508}/creative_set_service/create_creative_set.py (90%) rename examples/dfp/{v201408 => v201508}/creative_set_service/get_all_creative_sets.py (89%) rename examples/dfp/{v201408 => v201508}/creative_set_service/get_creative_sets_by_statement.py (91%) rename examples/dfp/{v201408 => v201508}/creative_set_service/update_creative_set.py (90%) create mode 100755 examples/dfp/v201508/creative_template_service/__init__.py rename examples/dfp/{v201408 => v201508}/creative_template_service/get_all_creative_templates.py (89%) rename examples/dfp/{v201408 => v201508}/creative_template_service/get_creative_templates_by_statement.py (90%) rename examples/dfp/{v201408 => v201508}/creative_wrapper_service/create_creative_wrappers.py (90%) rename examples/dfp/{v201408 => v201508}/creative_wrapper_service/deactivate_creative_wrapper.py (90%) rename examples/dfp/{v201408 => v201508}/creative_wrapper_service/get_active_creative_wrappers.py (89%) rename examples/dfp/{v201408 => v201508}/creative_wrapper_service/get_all_creative_wrappers.py (88%) rename examples/dfp/{v201408 => v201508}/creative_wrapper_service/update_creative_wrappers.py (89%) create mode 100755 examples/dfp/v201508/custom_field_service/__init__.py rename examples/dfp/{v201408 => v201508}/custom_field_service/create_custom_field_options.py (91%) rename examples/dfp/{v201408 => v201508}/custom_field_service/create_custom_fields.py (90%) rename examples/dfp/{v201408 => v201508}/custom_field_service/deactivate_all_line_item_custom_fields.py (91%) rename examples/dfp/{v201408 => v201508}/custom_field_service/get_all_custom_fields.py (89%) rename examples/dfp/{v201408 => v201508}/custom_field_service/get_all_line_item_custom_fields.py (90%) rename examples/dfp/{v201408 => v201508}/custom_field_service/set_line_item_custom_field_value.py (92%) rename examples/dfp/{v201408 => v201508}/custom_field_service/update_custom_fields.py (90%) create mode 100755 examples/dfp/v201508/custom_targeting_service/__init__.py rename examples/dfp/{v201408 => v201508}/custom_targeting_service/create_custom_targeting_keys_and_values.py (93%) rename examples/dfp/{v201408 => v201508}/custom_targeting_service/delete_custom_targeting_keys.py (91%) rename examples/dfp/{v201408 => v201508}/custom_targeting_service/delete_custom_targeting_values.py (92%) rename examples/dfp/{v201408 => v201508}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (94%) rename examples/dfp/{v201408 => v201508}/custom_targeting_service/get_custom_targeting_keys_by_statement.py (91%) rename examples/dfp/{v201408 => v201508}/custom_targeting_service/get_custom_targeting_values_by_statement.py (92%) rename examples/dfp/{v201408 => v201508}/custom_targeting_service/update_custom_targeting_keys.py (93%) rename examples/dfp/{v201408 => v201508}/custom_targeting_service/update_custom_targeting_values.py (93%) create mode 100755 examples/dfp/v201508/exchange_rate_service/__init__.py create mode 100755 examples/dfp/v201508/exchange_rate_service/create_exchange_rates.py create mode 100755 examples/dfp/v201508/exchange_rate_service/get_all_exchange_rates.py create mode 100755 examples/dfp/v201508/exchange_rate_service/get_exchange_rates_by_currency_code.py create mode 100755 examples/dfp/v201508/exchange_rate_service/update_exchange_rates.py rename examples/dfp/{v201408/forecast_service/get_forecast.py => v201508/forecast_service/get_availability_forecast.py} (63%) rename examples/dfp/{v201408/forecast_service/get_forecast_by_id.py => v201508/forecast_service/get_availability_forecast_for_line_item.py} (76%) create mode 100755 examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py create mode 100755 examples/dfp/v201508/inventory_service/__init__.py rename examples/dfp/{v201408 => v201508}/inventory_service/archive_ad_units.py (93%) rename examples/dfp/{v201408 => v201508}/inventory_service/create_ad_units.py (92%) rename examples/dfp/{v201408 => v201508}/inventory_service/get_ad_unit_hierarchy.py (95%) rename examples/dfp/{v201408 => v201508}/inventory_service/get_all_ad_unit_sizes.py (90%) rename examples/dfp/{v201408 => v201508}/inventory_service/get_all_ad_units.py (91%) rename examples/dfp/{v201408 => v201508}/inventory_service/get_top_level_ad_units.py (92%) rename examples/dfp/{v201408 => v201508}/inventory_service/update_ad_units.py (93%) create mode 100755 examples/dfp/v201508/label_service/__init__.py rename examples/dfp/{v201408 => v201508}/label_service/create_labels.py (92%) rename examples/dfp/{v201408 => v201508}/label_service/deactivate_labels.py (94%) rename examples/dfp/{v201408 => v201508}/label_service/get_all_labels.py (92%) rename examples/dfp/{v201408 => v201508}/label_service/get_labels_by_statement.py (93%) rename examples/dfp/{v201408 => v201508}/label_service/update_labels.py (94%) create mode 100755 examples/dfp/v201508/line_item_creative_association_service/__init__.py rename examples/dfp/{v201408 => v201508}/line_item_creative_association_service/create_licas.py (90%) rename examples/dfp/{v201408 => v201508}/line_item_creative_association_service/deactivate_licas.py (93%) rename examples/dfp/{v201408 => v201508}/line_item_creative_association_service/get_all_licas.py (91%) rename examples/dfp/{v201408 => v201508}/line_item_creative_association_service/get_licas_by_statement.py (92%) rename examples/dfp/{v201408 => v201508}/line_item_creative_association_service/update_licas.py (92%) create mode 100755 examples/dfp/v201508/line_item_service/__init__.py rename examples/dfp/{v201408 => v201508}/line_item_service/activate_line_items.py (95%) rename examples/dfp/{v201408 => v201508}/line_item_service/create_line_items.py (97%) rename examples/dfp/{v201408 => v201508}/line_item_service/create_video_line_item.py (79%) rename examples/dfp/{v201408 => v201508}/line_item_service/get_all_line_items.py (92%) rename examples/dfp/{v201408 => v201508}/line_item_service/get_line_items_by_statement.py (85%) rename examples/dfp/{v201408 => v201508}/line_item_service/get_recently_updated_line_items.py (94%) rename examples/dfp/{v201408 => v201508}/line_item_service/target_custom_criteria.py (96%) rename examples/dfp/{v201408 => v201508}/line_item_service/update_line_items.py (95%) create mode 100755 examples/dfp/v201508/network_service/__init__.py rename examples/dfp/{v201408 => v201508}/network_service/get_all_networks.py (91%) rename examples/dfp/{v201408 => v201508}/network_service/get_current_network.py (90%) rename examples/dfp/{v201408 => v201508}/network_service/make_test_network.py (93%) create mode 100755 examples/dfp/v201508/order_service/__init__.py rename examples/dfp/{v201408 => v201508}/order_service/approve_orders.py (95%) rename examples/dfp/{v201408 => v201508}/order_service/create_orders.py (93%) rename examples/dfp/{v201408 => v201508}/order_service/get_all_orders.py (92%) rename examples/dfp/{v201408 => v201508}/order_service/get_orders_by_statement.py (93%) rename examples/dfp/{v201408 => v201508}/order_service/update_orders.py (94%) rename examples/dfp/{v201408 => v201508}/placement_service/create_placements.py (96%) rename examples/dfp/{v201408 => v201508}/placement_service/deactivate_placements.py (94%) rename examples/dfp/{v201408 => v201508}/placement_service/get_all_placements.py (92%) rename examples/dfp/{v201408 => v201508}/placement_service/get_placements_by_statement.py (93%) rename examples/dfp/{v201408 => v201508}/placement_service/update_placements.py (94%) create mode 100755 examples/dfp/v201508/premium_rate_service/__init__.py create mode 100755 examples/dfp/v201508/premium_rate_service/create_premium_rates.py create mode 100755 examples/dfp/v201508/premium_rate_service/get_all_premium_rates.py create mode 100755 examples/dfp/v201508/premium_rate_service/get_premium_rates_for_a_rate_card.py create mode 100755 examples/dfp/v201508/premium_rate_service/update_premium_rates.py create mode 100755 examples/dfp/v201508/product_service/__init__.py create mode 100755 examples/dfp/v201508/product_service/get_all_products.py create mode 100755 examples/dfp/v201508/product_service/get_products_for_product_template.py create mode 100755 examples/dfp/v201508/product_service/update_products.py create mode 100755 examples/dfp/v201508/product_template_service/__init__.py create mode 100755 examples/dfp/v201508/product_template_service/activate_product_templates.py create mode 100755 examples/dfp/v201508/product_template_service/create_product_templates.py create mode 100755 examples/dfp/v201508/product_template_service/get_all_product_templates.py create mode 100755 examples/dfp/v201508/product_template_service/get_sponsorship_product_templates.py create mode 100755 examples/dfp/v201508/product_template_service/update_product_templates.py create mode 100755 examples/dfp/v201508/proposal_line_item_service/__init__.py create mode 100755 examples/dfp/v201508/proposal_line_item_service/archive_proposal_line_items.py create mode 100755 examples/dfp/v201508/proposal_line_item_service/create_proposal_line_items.py create mode 100755 examples/dfp/v201508/proposal_line_item_service/get_all_proposal_line_items.py create mode 100755 examples/dfp/v201508/proposal_line_item_service/get_proposal_line_items_for_proposal.py create mode 100755 examples/dfp/v201508/proposal_line_item_service/update_proposal_line_items.py create mode 100755 examples/dfp/v201508/proposal_service/__init__.py create mode 100755 examples/dfp/v201508/proposal_service/create_proposals.py create mode 100755 examples/dfp/v201508/proposal_service/get_all_proposals.py create mode 100755 examples/dfp/v201508/proposal_service/get_proposals_by_statement.py create mode 100755 examples/dfp/v201508/proposal_service/submit_proposals_for_approval.py create mode 100755 examples/dfp/v201508/proposal_service/update_proposals.py create mode 100755 examples/dfp/v201508/publisher_query_language_service/__init__.py rename examples/dfp/{v201408 => v201508}/publisher_query_language_service/fetch_match_tables.py (90%) rename examples/dfp/{v201408 => v201508}/publisher_query_language_service/get_geo_targets.py (89%) rename examples/dfp/{v201408 => v201508}/publisher_query_language_service/get_line_items_named_like.py (90%) create mode 100755 examples/dfp/v201508/rate_card_service/__init__.py create mode 100755 examples/dfp/v201508/rate_card_service/get_all_rate_cards.py create mode 100755 examples/dfp/v201508/rate_card_service/get_rate_cards_priced_with_currency.py create mode 100755 examples/dfp/v201508/report_service/__init__.py rename examples/dfp/{v201408 => v201508}/report_service/run_delivery_report.py (79%) rename examples/dfp/{v201408 => v201508}/report_service/run_inventory_report.py (93%) rename examples/dfp/{v201408 => v201508}/report_service/run_reach_report.py (91%) rename examples/dfp/{v201408 => v201508}/report_service/run_report_with_custom_fields.py (94%) rename examples/dfp/{v201408 => v201508}/report_service/run_sales_report.py (91%) create mode 100755 examples/dfp/v201508/suggested_ad_unit_service/__init__.py rename examples/dfp/{v201408 => v201508}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (93%) rename examples/dfp/{v201408 => v201508}/suggested_ad_unit_service/get_all_suggested_ad_units.py (91%) rename examples/dfp/{v201408 => v201508}/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py (91%) create mode 100755 examples/dfp/v201508/team_service/__init__.py rename examples/dfp/{v201408 => v201508}/team_service/create_teams.py (88%) rename examples/dfp/{v201408 => v201508}/team_service/get_all_teams.py (88%) rename examples/dfp/{v201408 => v201508}/team_service/get_teams_by_statement.py (90%) rename examples/dfp/{v201408 => v201508}/team_service/update_teams.py (91%) create mode 100755 examples/dfp/v201508/user_service/__init__.py rename examples/dfp/{v201408 => v201508}/user_service/create_users.py (90%) rename examples/dfp/{v201408 => v201508}/user_service/deactivate_users.py (92%) rename examples/dfp/{v201408 => v201508}/user_service/get_all_roles.py (87%) rename examples/dfp/{v201408 => v201508}/user_service/get_all_users.py (89%) rename examples/dfp/{v201408 => v201508}/user_service/get_current_user.py (86%) rename examples/dfp/{v201408 => v201508}/user_service/get_users_by_statement.py (89%) rename examples/dfp/{v201408 => v201508}/user_service/update_users.py (90%) create mode 100755 examples/dfp/v201508/user_team_association_service/__init__.py rename examples/dfp/{v201408 => v201508}/user_team_association_service/create_user_team_associations.py (90%) rename examples/dfp/{v201408 => v201508}/user_team_association_service/delete_user_team_associations.py (91%) rename examples/dfp/{v201408 => v201508}/user_team_association_service/get_all_user_team_associations.py (89%) rename examples/dfp/{v201408 => v201508}/user_team_association_service/get_user_team_associations_for_user.py (90%) rename examples/dfp/{v201408 => v201508}/user_team_association_service/update_user_team_associations.py (90%) create mode 100755 examples/dfp/v201508/workflow_request_service/__init__.py create mode 100755 examples/dfp/v201508/workflow_request_service/approve_workflow_approval_requests.py create mode 100755 examples/dfp/v201508/workflow_request_service/get_workflow_approval_requests_by_statement.py create mode 100755 examples/dfp/v201508/workflow_request_service/get_workflow_external_condition_requests_by_statement.py create mode 100755 examples/dfp/v201508/workflow_request_service/trigger_workflow_external_condition_requests.py diff --git a/ChangeLog b/ChangeLog index bec5d4a8..e229a4d3 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +3.7.0 - 8/20/2015 +* Update ServiceAccount constructor to open p12 file in binary mode. +* Added support for v201508 for the Doubleclick for Publishers Client Library. +* Removed support for v201403 for the Doubleclick for Publishers Client Library. + 3.6.0 - 7/31/2015 * Removed support for AdWords v201409. * Removed examples for AdWords v201409. diff --git a/README.md b/README.md index 14fb84ce..20d04d0d 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,14 @@ Publishers. The library provides easy ways to store your authentication and create SOAP web service clients. It also contains example code to help you get started integrating with our APIs. +####Important Note Regarding DFP +If you are using v201502 and newer in the DFP API, then performing actions on +objects will fail with an 'args NULL' error due to a bug in the underlying SOAP +client, more details here: https://github.com/googleads/googleads-python-lib/issues/58. + +While the fix has been accepted and merged into the source, you will need to download +the source files yourself and install them directly. The source can be located here: +https://bitbucket.org/jurko/suds/downloads ##How do I get started? ####Installing the library @@ -56,13 +64,19 @@ adwords_client.SetClientCustomerId('my_client_customer_id') ##Where do I submit bug reports and/or feature requests? -Use the issue tracker at: - https://github.com/googleads/googleads-python-lib/issues +If you have issues directly related to the client library, use the [issue +tracker](https://github.com/googleads/googleads-python-lib/issues). + + +If you have issues pertaining to a specific product, use the product support forums: -Make sure to subscribe to our Google Plus page for API change announcements and -other news: +* [AdWords](https://groups.google.com/forum/#!forum/adwords-api) +* [DoubleClick Ad Exchange](https://groups.google.com/forum/#!forum/google-doubleclick-ad-exchange-buyer-api) +* [DoubleClick for Advertisers](https://groups.google.com/forum/#!forum/google-doubleclick-for-advertisers-api) +* [DoubleClick for Publishers](https://groups.google.com/forum/#!forum/google-doubleclick-for-publishers-api) - https://plus.google.com/+GoogleAdsDevelopers +Make sure to subscribe to our [Google Plus page](https://plus.google.com/+GoogleAdsDevelopers) +for API change announcements and other news. ##How do I log SOAP interactions? @@ -127,4 +141,4 @@ suds_client.service.mutate([operation]) ##Authors: - msaniscalchi@google.com (Mark Saniscalchi) + Mark Saniscalchi diff --git a/examples/adwords/adwords_appengine_demo/demo/__init__.py b/examples/adwords/adwords_appengine_demo/demo/__init__.py index 71de3769..59e8ef3a 100755 --- a/examples/adwords/adwords_appengine_demo/demo/__init__.py +++ b/examples/adwords/adwords_appengine_demo/demo/__init__.py @@ -15,8 +15,5 @@ # limitations under the License. """AdWords App Engine demo web application.""" -__author__ = 'Mark Saniscalchi' - - DEBUG = False # Enable to see debug logs in the App Engine console. VERSION = '1.0.0' diff --git a/examples/adwords/adwords_appengine_demo/demo/main.py b/examples/adwords/adwords_appengine_demo/demo/main.py index b0890637..5d364db6 100755 --- a/examples/adwords/adwords_appengine_demo/demo/main.py +++ b/examples/adwords/adwords_appengine_demo/demo/main.py @@ -18,7 +18,6 @@ Configures the web application that will display the AdWords UI. """ -__author__ = 'Mark Saniscalchi' from demo import DEBUG from views import AddAdGroup diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index f69cb0d0..28436736 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -15,7 +15,6 @@ # limitations under the License. """Handler to make calls against the AdWords API.""" -__author__ = 'Mark Saniscalchi' import time diff --git a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py index 1524c61e..9c73510a 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py @@ -16,7 +16,6 @@ """Handler for ndb transactions.""" -__author__ = 'Mark Saniscalchi' from models.app_user import AppUser diff --git a/examples/adwords/adwords_appengine_demo/models/app_user.py b/examples/adwords/adwords_appengine_demo/models/app_user.py index ef710c3a..649c4190 100755 --- a/examples/adwords/adwords_appengine_demo/models/app_user.py +++ b/examples/adwords/adwords_appengine_demo/models/app_user.py @@ -16,7 +16,6 @@ """Model representing a user of the application.""" -__author__ = 'Mark Saniscalchi' from google.appengine.ext import ndb diff --git a/examples/adwords/adwords_appengine_demo/views/__init__.py b/examples/adwords/adwords_appengine_demo/views/__init__.py index 42f315ed..f6f56e9a 100755 --- a/examples/adwords/adwords_appengine_demo/views/__init__.py +++ b/examples/adwords/adwords_appengine_demo/views/__init__.py @@ -16,7 +16,6 @@ """Views for the web application.""" -__author__ = 'Mark Saniscalchi' from add_adgroup_view import AddAdGroup from add_campaign_view import AddCampaign diff --git a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py index 011f5553..15d5ea37 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py @@ -16,7 +16,6 @@ """Handles request to add an AdGroup to a Campaign.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py index 5b01c7f7..9e62984f 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py @@ -16,7 +16,6 @@ """Handles request to add a Campaign to a client account.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/adwords_appengine_demo/views/init_view.py b/examples/adwords/adwords_appengine_demo/views/init_view.py index d051fb4b..5a73b0e0 100755 --- a/examples/adwords/adwords_appengine_demo/views/init_view.py +++ b/examples/adwords/adwords_appengine_demo/views/init_view.py @@ -16,7 +16,6 @@ """View at the root directory of the application.""" -__author__ = 'Mark Saniscalchi' import logging diff --git a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py index 43cce8dd..5201230f 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py @@ -16,7 +16,6 @@ """Handles request to view accounts associated with MCC Cluent Customer Id.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py index cb7abf55..e2b84c26 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py @@ -16,7 +16,6 @@ """Handles request to view the AdGroups associated with a given Campaign.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py index c4cb2a8a..4b8e2d03 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py @@ -16,7 +16,6 @@ """Handles request to view a Campaign's budget.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py index da09fa47..25c1c7ca 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py @@ -16,7 +16,6 @@ """Handles request to view Campaigns associated with a given client account.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py index 38588dcd..b23d3137 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py @@ -15,7 +15,6 @@ # limitations under the License. """Handles requests to view the user's credentials.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py index 11e54864..71dfc092 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py @@ -16,7 +16,6 @@ """Handles requests to update a given Budget.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py index 9c732019..52d93e9d 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py @@ -16,7 +16,6 @@ """Handles requests to update the current user's credentials.""" -__author__ = 'Mark Saniscalchi' import os diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index 24e46578..1d9f0b86 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -16,7 +16,6 @@ """Initializes an AdWordsClient via impersonation using a Service Account.""" -__author__ = 'Mark Saniscalchi' from googleads import adwords from googleads import oauth2 diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_without_yaml.py index 4877407a..30e50723 100755 --- a/examples/adwords/authentication/create_adwords_client_without_yaml.py +++ b/examples/adwords/authentication/create_adwords_client_without_yaml.py @@ -22,7 +22,6 @@ client and an AdWordsClient without relying on a yaml file. """ -__author__ = 'Joseph DiLallo' from googleads import adwords from googleads import oauth2 diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 2ededff7..21698c51 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -16,7 +16,6 @@ """Generates refresh token for AdWords using the Installed Application flow.""" -__author__ = 'Mark Saniscalchi' import sys diff --git a/examples/adwords/v201502/account_management/create_account.py b/examples/adwords/v201502/account_management/create_account.py index 1427677c..94eddd14 100755 --- a/examples/adwords/v201502/account_management/create_account.py +++ b/examples/adwords/v201502/account_management/create_account.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreateAccountService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from datetime import datetime diff --git a/examples/adwords/v201502/account_management/get_account_changes.py b/examples/adwords/v201502/account_management/get_account_changes.py index 7fa5ff80..b23a5ca1 100755 --- a/examples/adwords/v201502/account_management/get_account_changes.py +++ b/examples/adwords/v201502/account_management/get_account_changes.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomerSyncService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import datetime diff --git a/examples/adwords/v201502/account_management/get_account_hierarchy.py b/examples/adwords/v201502/account_management/get_account_hierarchy.py index 78606269..855ee159 100755 --- a/examples/adwords/v201502/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201502/account_management/get_account_hierarchy.py @@ -24,12 +24,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ServicedAccountService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/advanced_operations/add_ad_customizer.py b/examples/adwords/v201502/advanced_operations/add_ad_customizer.py index 1c85f1fd..055a04ec 100755 --- a/examples/adwords/v201502/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201502/advanced_operations/add_ad_customizer.py @@ -19,11 +19,8 @@ Associates the feed with customer and adds an ad that uses the feed to populate dynamic data. -Tags: AdCustomizerFeedService.mutate, AdGroupAdService.mutate -Tags: FeedItemService.mutate """ -__author__ = 'api.msaniscalchi@gmail.com (Mark Saniscalchi)' from datetime import datetime from uuid import uuid4 diff --git a/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py index c1de6f8c..0db78808 100755 --- a/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupBidModifierService.mutate """ -__author__ = 'Joseph DiLallo' from googleads import adwords diff --git a/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py index a9aaeffe..e81d0498 100755 --- a/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py @@ -24,13 +24,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate Api: AdWordsOnly """ -__author__ = 'Joseph DiLallo' - - from googleads import adwords diff --git a/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py index a3032cb2..d0bb5eef 100755 --- a/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = 'Mark Saniscalchi' from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py index 7dd535da..2919e0d3 100755 --- a/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignSharedSetService.mutate, SharedCriterionService.mutate, - SharedSetService.mutate """ -__author__ = 'Mark Saniscalchi' import uuid diff --git a/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py index e366d28a..c0fd53fd 100755 --- a/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignSharedSetService.get, SharedCriterionService.get, - SharedCriterionService.mutate """ -__author__ = 'Mark Saniscalchi' from googleads import adwords diff --git a/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py index 88b39a7a..54b3ffe6 100755 --- a/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupBidModifierService.get """ -__author__ = 'Joseph DiLallo' from googleads import adwords diff --git a/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py index fafbcca2..b944429c 100755 --- a/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py +++ b/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ConversionTrackerService.mutate, OfflineConversionFeedService.mutate """ -__author__ = 'Joseph DiLallo' from googleads import adwords diff --git a/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py index 8e0fd39b..d93873b8 100755 --- a/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: BiddingStrategyService.mutate -Tags: BudgetService.mutate, CampaignService.mutate """ -__author__ = 'Joseph DiLallo' import uuid diff --git a/examples/adwords/v201502/basic_operations/add_ad_groups.py b/examples/adwords/v201502/basic_operations/add_ad_groups.py index b8eadc57..131f952d 100755 --- a/examples/adwords/v201502/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201502/basic_operations/add_ad_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README.. -Tags: AdGroupService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import uuid diff --git a/examples/adwords/v201502/basic_operations/add_campaigns.py b/examples/adwords/v201502/basic_operations/add_campaigns.py index c2c05c27..2719dc97 100755 --- a/examples/adwords/v201502/basic_operations/add_campaigns.py +++ b/examples/adwords/v201502/basic_operations/add_campaigns.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate -Tags: BudgetService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import datetime import uuid diff --git a/examples/adwords/v201502/basic_operations/add_keywords.py b/examples/adwords/v201502/basic_operations/add_keywords.py index f87b2b52..f9ef9002 100755 --- a/examples/adwords/v201502/basic_operations/add_keywords.py +++ b/examples/adwords/v201502/basic_operations/add_keywords.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/add_text_ads.py b/examples/adwords/v201502/basic_operations/add_text_ads.py index 2f32332d..1f043345 100755 --- a/examples/adwords/v201502/basic_operations/add_text_ads.py +++ b/examples/adwords/v201502/basic_operations/add_text_ads.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/get_ad_groups.py b/examples/adwords/v201502/basic_operations/get_ad_groups.py index 4cfc1add..c295768f 100755 --- a/examples/adwords/v201502/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201502/basic_operations/get_ad_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/get_campaigns.py b/examples/adwords/v201502/basic_operations/get_campaigns.py index 8631c5fe..be56c978 100755 --- a/examples/adwords/v201502/basic_operations/get_campaigns.py +++ b/examples/adwords/v201502/basic_operations/get_campaigns.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.get """ -__author__ = 'Joseph DiLallo' import logging import time diff --git a/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py index 3d1f3c99..75c41593 100755 --- a/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.query """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import time diff --git a/examples/adwords/v201502/basic_operations/get_keywords.py b/examples/adwords/v201502/basic_operations/get_keywords.py index 1d5214bb..0ef3b1a0 100755 --- a/examples/adwords/v201502/basic_operations/get_keywords.py +++ b/examples/adwords/v201502/basic_operations/get_keywords.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/get_text_ads.py b/examples/adwords/v201502/basic_operations/get_text_ads.py index a27ab6f8..03f6f464 100755 --- a/examples/adwords/v201502/basic_operations/get_text_ads.py +++ b/examples/adwords/v201502/basic_operations/get_text_ads.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/pause_ad.py b/examples/adwords/v201502/basic_operations/pause_ad.py index ae4dbcdc..ca87c702 100755 --- a/examples/adwords/v201502/basic_operations/pause_ad.py +++ b/examples/adwords/v201502/basic_operations/pause_ad.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/remove_ad.py b/examples/adwords/v201502/basic_operations/remove_ad.py index d12c147a..273241cd 100755 --- a/examples/adwords/v201502/basic_operations/remove_ad.py +++ b/examples/adwords/v201502/basic_operations/remove_ad.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/remove_ad_group.py b/examples/adwords/v201502/basic_operations/remove_ad_group.py index dacd3d1f..818e7f98 100755 --- a/examples/adwords/v201502/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201502/basic_operations/remove_ad_group.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/remove_campaign.py b/examples/adwords/v201502/basic_operations/remove_campaign.py index 4705f99e..dcfdde97 100755 --- a/examples/adwords/v201502/basic_operations/remove_campaign.py +++ b/examples/adwords/v201502/basic_operations/remove_campaign.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/remove_keyword.py b/examples/adwords/v201502/basic_operations/remove_keyword.py index 9b8d85b5..8f6d2b7f 100755 --- a/examples/adwords/v201502/basic_operations/remove_keyword.py +++ b/examples/adwords/v201502/basic_operations/remove_keyword.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/update_ad_group.py b/examples/adwords/v201502/basic_operations/update_ad_group.py index 25a8c8fd..d13c9a51 100755 --- a/examples/adwords/v201502/basic_operations/update_ad_group.py +++ b/examples/adwords/v201502/basic_operations/update_ad_group.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/update_campaign.py b/examples/adwords/v201502/basic_operations/update_campaign.py index f9625702..15012ba9 100755 --- a/examples/adwords/v201502/basic_operations/update_campaign.py +++ b/examples/adwords/v201502/basic_operations/update_campaign.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/basic_operations/update_keyword.py b/examples/adwords/v201502/basic_operations/update_keyword.py index 9e8c7291..70f61b8f 100755 --- a/examples/adwords/v201502/basic_operations/update_keyword.py +++ b/examples/adwords/v201502/basic_operations/update_keyword.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/campaign_management/add_campaign_labels.py b/examples/adwords/v201502/campaign_management/add_campaign_labels.py index 0817e8d4..648b2ac6 100755 --- a/examples/adwords/v201502/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201502/campaign_management/add_campaign_labels.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutateLabel """ -__author__ = 'Mark Saniscalchi' from googleads import adwords diff --git a/examples/adwords/v201502/campaign_management/add_experiment.py b/examples/adwords/v201502/campaign_management/add_experiment.py index d7dadc35..156a0195 100755 --- a/examples/adwords/v201502/campaign_management/add_experiment.py +++ b/examples/adwords/v201502/campaign_management/add_experiment.py @@ -27,12 +27,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ExperimentService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import datetime import uuid diff --git a/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py index e346eb7a..21abdc01 100755 --- a/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py +++ b/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py @@ -21,14 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MutateJobService.mutate -Tags: MutateJobService.get -Tags: MutateJobService.getResult Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import random import re diff --git a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py index ca22bf7d..b664fb86 100755 --- a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py index 3a820077..6e7c5781 100755 --- a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py index c18d8714..dfebfdec 100755 --- a/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.get """ -__author__ = 'Mark Saniscalchi' import time diff --git a/examples/adwords/v201502/campaign_management/promote_experiment.py b/examples/adwords/v201502/campaign_management/promote_experiment.py index 09e370a3..b63a01d6 100755 --- a/examples/adwords/v201502/campaign_management/promote_experiment.py +++ b/examples/adwords/v201502/campaign_management/promote_experiment.py @@ -25,12 +25,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ExperimentService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/campaign_management/set_ad_parameters.py b/examples/adwords/v201502/campaign_management/set_ad_parameters.py index e7f22a68..a815200e 100755 --- a/examples/adwords/v201502/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201502/campaign_management/set_ad_parameters.py @@ -24,12 +24,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate, AdParamService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py index 0b2e4a03..e8be422f 100755 --- a/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignCriterionService.mutate """ -__author__ = ('api.dklimkin@gmail.com (Danial Klimkin)', - 'Joseph DiLallo') - from googleads import adwords diff --git a/examples/adwords/v201502/campaign_management/validate_text_ad.py b/examples/adwords/v201502/campaign_management/validate_text_ad.py index 46cd4c3a..03c6abad 100755 --- a/examples/adwords/v201502/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201502/campaign_management/validate_text_ad.py @@ -21,12 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import suds diff --git a/examples/adwords/v201502/error_handling/handle_partial_failures.py b/examples/adwords/v201502/error_handling/handle_partial_failures.py index 644f22fe..614dd036 100755 --- a/examples/adwords/v201502/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201502/error_handling/handle_partial_failures.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import re diff --git a/examples/adwords/v201502/error_handling/handle_policy_violation_error.py b/examples/adwords/v201502/error_handling/handle_policy_violation_error.py index 2a5a390d..33b69907 100755 --- a/examples/adwords/v201502/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201502/error_handling/handle_policy_violation_error.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = 'Joseph DiLallo' import re diff --git a/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py index b723ca95..97112f68 100755 --- a/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomerFeedService.mutate, FeedService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') import time import uuid diff --git a/examples/adwords/v201502/extensions/add_site_links.py b/examples/adwords/v201502/extensions/add_site_links.py index d7cf2989..cc6297dd 100755 --- a/examples/adwords/v201502/extensions/add_site_links.py +++ b/examples/adwords/v201502/extensions/add_site_links.py @@ -21,11 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignExtensionSettingService.mutate, CustomerService.get Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' from datetime import datetime diff --git a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py b/examples/adwords/v201502/extensions/add_site_links_using_feeds.py index 8bf899b0..6ff72e0b 100755 --- a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201502/extensions/add_site_links_using_feeds.py @@ -24,12 +24,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignFeedService.mutate, FeedItemService.mutate -Tags: FeedMappingService.mutate, FeedService.mutate Api: AdWordsOnly """ -__author__ = 'Joseph DiLallo' import re import uuid diff --git a/examples/adwords/v201502/migration/migrate_to_extension_settings.py b/examples/adwords/v201502/migration/migrate_to_extension_settings.py index 0b134549..56c777bd 100755 --- a/examples/adwords/v201502/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201502/migration/migrate_to_extension_settings.py @@ -27,13 +27,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: FeedService.get, FeedMappingService.get, FeedItemService.get -Tags: CampaignExtensionSettingService.mutate, CampaignFeedService.get, -Tags: CampaignFeedService.mutate Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' from googleads import adwords diff --git a/examples/adwords/v201502/migration/upgrade_ad_url.py b/examples/adwords/v201502/migration/upgrade_ad_url.py index 3ccd8c63..0e805bee 100755 --- a/examples/adwords/v201502/migration/upgrade_ad_url.py +++ b/examples/adwords/v201502/migration/upgrade_ad_url.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get, AdGroupAdService.upgradeUrl """ -__author__ = 'Mark Saniscalchi' from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201502/misc/get_all_images_and_videos.py b/examples/adwords/v201502/misc/get_all_images_and_videos.py index 77bffc39..b64c898f 100755 --- a/examples/adwords/v201502/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201502/misc/get_all_images_and_videos.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MediaService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/misc/upload_image.py b/examples/adwords/v201502/misc/upload_image.py index 3d8d7478..9aea238e 100755 --- a/examples/adwords/v201502/misc/upload_image.py +++ b/examples/adwords/v201502/misc/upload_image.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MediaService.upload """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import base64 diff --git a/examples/adwords/v201502/optimization/estimate_keyword_traffic.py b/examples/adwords/v201502/optimization/estimate_keyword_traffic.py index 83387853..ee1f3ae3 100755 --- a/examples/adwords/v201502/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201502/optimization/estimate_keyword_traffic.py @@ -21,12 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TrafficEstimatorService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py index cfee2131..eb42cc50 100755 --- a/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: BidLandscapeService.getBidLandscape Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/optimization/get_keyword_ideas.py b/examples/adwords/v201502/optimization/get_keyword_ideas.py index abbe0e3b..29eaf0e5 100755 --- a/examples/adwords/v201502/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201502/optimization/get_keyword_ideas.py @@ -21,12 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TargetingIdeaService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/remarketing/add_audience.py b/examples/adwords/v201502/remarketing/add_audience.py index a8cff444..8bbcde0c 100755 --- a/examples/adwords/v201502/remarketing/add_audience.py +++ b/examples/adwords/v201502/remarketing/add_audience.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserListService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import uuid diff --git a/examples/adwords/v201502/remarketing/add_conversion_tracker.py b/examples/adwords/v201502/remarketing/add_conversion_tracker.py index 4b65b9ba..39c7ff6a 100755 --- a/examples/adwords/v201502/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201502/remarketing/add_conversion_tracker.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ConversionTrackerService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import uuid diff --git a/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py index bfa1ef50..46fae2b5 100755 --- a/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py @@ -25,10 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdwordsUserListService.mutate """ -__author__ = 'Mark Saniscalchi' import calendar from datetime import date diff --git a/examples/adwords/v201502/reporting/download_criteria_report.py b/examples/adwords/v201502/reporting/download_criteria_report.py index cd2dd747..4cd49ea0 100755 --- a/examples/adwords/v201502/reporting/download_criteria_report.py +++ b/examples/adwords/v201502/reporting/download_criteria_report.py @@ -23,11 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' import logging import sys diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py index a32af291..a47e32be 100755 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py @@ -23,11 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' import logging import StringIO diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py index 8846265d..0c41a692 100755 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import logging import StringIO diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_string.py b/examples/adwords/v201502/reporting/download_criteria_report_as_string.py index c667b24c..5328a735 100755 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201502/reporting/download_criteria_report_as_string.py @@ -23,11 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' import logging diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py index cc5c90e8..1cb21479 100755 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py index 75cb3451..83125deb 100755 --- a/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/reporting/get_report_fields.py b/examples/adwords/v201502/reporting/get_report_fields.py index 408d4926..3fab2daa 100755 --- a/examples/adwords/v201502/reporting/get_report_fields.py +++ b/examples/adwords/v201502/reporting/get_report_fields.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.getReportFields """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/shopping/add_product_partition_tree.py b/examples/adwords/v201502/shopping/add_product_partition_tree.py index 56d7a02c..065fb3b5 100755 --- a/examples/adwords/v201502/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201502/shopping/add_product_partition_tree.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import adwords diff --git a/examples/adwords/v201502/shopping/add_product_scope.py b/examples/adwords/v201502/shopping/add_product_scope.py index 9ac3d667..51393c42 100755 --- a/examples/adwords/v201502/shopping/add_product_scope.py +++ b/examples/adwords/v201502/shopping/add_product_scope.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignCriterionService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import adwords diff --git a/examples/adwords/v201502/shopping/add_shopping_campaign.py b/examples/adwords/v201502/shopping/add_shopping_campaign.py index 3cbe4da8..f10fe740 100755 --- a/examples/adwords/v201502/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201502/shopping/add_shopping_campaign.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate, AdGroupService.mutate, AdGroupAdService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') import uuid diff --git a/examples/adwords/v201502/shopping/get_product_category_taxonomy.py b/examples/adwords/v201502/shopping/get_product_category_taxonomy.py index ac82093d..b198ed8e 100755 --- a/examples/adwords/v201502/shopping/get_product_category_taxonomy.py +++ b/examples/adwords/v201502/shopping/get_product_category_taxonomy.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ConstantDataService.getProductBiddingCategoryData """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import adwords diff --git a/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py index cdbddd74..8be19b82 100755 --- a/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignCriterionService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py index 8e0a8c63..880b542c 100755 --- a/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'Joseph Dilallo' from googleads import adwords diff --git a/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py index c1868d72..84ebe093 100755 --- a/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignCriterionService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py index 61a6f2a2..80580e76 100755 --- a/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ConstantDataService.getLanguageCriterion -Tags: ConstantDataService.getCarrierCriterion """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201502/targeting/lookup_location.py b/examples/adwords/v201502/targeting/lookup_location.py index 761ddb1e..19732cfd 100755 --- a/examples/adwords/v201502/targeting/lookup_location.py +++ b/examples/adwords/v201502/targeting/lookup_location.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: LocationCriterionService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/account_management/create_account.py b/examples/adwords/v201506/account_management/create_account.py index 273f311b..406c7d60 100755 --- a/examples/adwords/v201506/account_management/create_account.py +++ b/examples/adwords/v201506/account_management/create_account.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreateAccountService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from datetime import datetime diff --git a/examples/adwords/v201506/account_management/get_account_changes.py b/examples/adwords/v201506/account_management/get_account_changes.py index 2515b979..279fa0b4 100755 --- a/examples/adwords/v201506/account_management/get_account_changes.py +++ b/examples/adwords/v201506/account_management/get_account_changes.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomerSyncService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import datetime diff --git a/examples/adwords/v201506/account_management/get_account_hierarchy.py b/examples/adwords/v201506/account_management/get_account_hierarchy.py index e901c6a9..dacffac0 100755 --- a/examples/adwords/v201506/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201506/account_management/get_account_hierarchy.py @@ -24,12 +24,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ServicedAccountService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/add_ad_customizer.py b/examples/adwords/v201506/advanced_operations/add_ad_customizer.py index 1c85f1fd..055a04ec 100755 --- a/examples/adwords/v201506/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201506/advanced_operations/add_ad_customizer.py @@ -19,11 +19,8 @@ Associates the feed with customer and adds an ad that uses the feed to populate dynamic data. -Tags: AdCustomizerFeedService.mutate, AdGroupAdService.mutate -Tags: FeedItemService.mutate """ -__author__ = 'api.msaniscalchi@gmail.com (Mark Saniscalchi)' from datetime import datetime from uuid import uuid4 diff --git a/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py index b5be64fe..0b044c45 100755 --- a/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupBidModifierService.mutate """ -__author__ = 'Joseph DiLallo' from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py index fb6a9c2b..6b735876 100755 --- a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py @@ -24,13 +24,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate Api: AdWordsOnly """ -__author__ = 'Joseph DiLallo' - - from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py index cca69d0c..504c4968 100755 --- a/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = 'Mark Saniscalchi' from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py index a0b0dce9..00f9629f 100755 --- a/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignSharedSetService.mutate, SharedCriterionService.mutate, - SharedSetService.mutate """ -__author__ = 'Mark Saniscalchi' import uuid diff --git a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py index e72ccd64..56f39737 100755 --- a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignSharedSetService.get, SharedCriterionService.get, - SharedCriterionService.mutate """ -__author__ = 'Mark Saniscalchi' from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py index 57397379..57bc6388 100755 --- a/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupBidModifierService.get """ -__author__ = 'Joseph DiLallo' from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py index c4782d27..01d725cb 100755 --- a/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py +++ b/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ConversionTrackerService.mutate, OfflineConversionFeedService.mutate """ -__author__ = 'Joseph DiLallo' from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py index ad044d12..e1826938 100755 --- a/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: BiddingStrategyService.mutate -Tags: BudgetService.mutate, CampaignService.mutate """ -__author__ = 'Joseph DiLallo' import uuid diff --git a/examples/adwords/v201506/basic_operations/add_ad_groups.py b/examples/adwords/v201506/basic_operations/add_ad_groups.py index 12abf5a1..242dde17 100755 --- a/examples/adwords/v201506/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201506/basic_operations/add_ad_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README.. -Tags: AdGroupService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import uuid diff --git a/examples/adwords/v201506/basic_operations/add_campaigns.py b/examples/adwords/v201506/basic_operations/add_campaigns.py index a7671bba..a73e904c 100755 --- a/examples/adwords/v201506/basic_operations/add_campaigns.py +++ b/examples/adwords/v201506/basic_operations/add_campaigns.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate -Tags: BudgetService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import datetime import uuid diff --git a/examples/adwords/v201506/basic_operations/add_keywords.py b/examples/adwords/v201506/basic_operations/add_keywords.py index 874d507a..e7298bad 100755 --- a/examples/adwords/v201506/basic_operations/add_keywords.py +++ b/examples/adwords/v201506/basic_operations/add_keywords.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/add_text_ads.py b/examples/adwords/v201506/basic_operations/add_text_ads.py index 462fd680..0284b76b 100755 --- a/examples/adwords/v201506/basic_operations/add_text_ads.py +++ b/examples/adwords/v201506/basic_operations/add_text_ads.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/get_ad_groups.py b/examples/adwords/v201506/basic_operations/get_ad_groups.py index 00532ccf..e7ca7fac 100755 --- a/examples/adwords/v201506/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201506/basic_operations/get_ad_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/get_campaigns.py b/examples/adwords/v201506/basic_operations/get_campaigns.py index 79926ab8..ff161fde 100755 --- a/examples/adwords/v201506/basic_operations/get_campaigns.py +++ b/examples/adwords/v201506/basic_operations/get_campaigns.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.get """ -__author__ = 'Joseph DiLallo' import logging import time diff --git a/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py index a7fc93dc..d4b0f4f6 100755 --- a/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.query """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import time diff --git a/examples/adwords/v201506/basic_operations/get_keywords.py b/examples/adwords/v201506/basic_operations/get_keywords.py index 6d99c0a0..e4c75faa 100755 --- a/examples/adwords/v201506/basic_operations/get_keywords.py +++ b/examples/adwords/v201506/basic_operations/get_keywords.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/get_text_ads.py b/examples/adwords/v201506/basic_operations/get_text_ads.py index e2376f6e..c2b7593c 100755 --- a/examples/adwords/v201506/basic_operations/get_text_ads.py +++ b/examples/adwords/v201506/basic_operations/get_text_ads.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/pause_ad.py b/examples/adwords/v201506/basic_operations/pause_ad.py index ebf11f50..938f0548 100755 --- a/examples/adwords/v201506/basic_operations/pause_ad.py +++ b/examples/adwords/v201506/basic_operations/pause_ad.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/remove_ad.py b/examples/adwords/v201506/basic_operations/remove_ad.py index 554e902a..0becfa0a 100755 --- a/examples/adwords/v201506/basic_operations/remove_ad.py +++ b/examples/adwords/v201506/basic_operations/remove_ad.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/remove_ad_group.py b/examples/adwords/v201506/basic_operations/remove_ad_group.py index fa2e8437..d4dd2c62 100755 --- a/examples/adwords/v201506/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201506/basic_operations/remove_ad_group.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/remove_campaign.py b/examples/adwords/v201506/basic_operations/remove_campaign.py index cccae255..017f2425 100755 --- a/examples/adwords/v201506/basic_operations/remove_campaign.py +++ b/examples/adwords/v201506/basic_operations/remove_campaign.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/remove_keyword.py b/examples/adwords/v201506/basic_operations/remove_keyword.py index 266a8020..eb882642 100755 --- a/examples/adwords/v201506/basic_operations/remove_keyword.py +++ b/examples/adwords/v201506/basic_operations/remove_keyword.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/update_ad_group.py b/examples/adwords/v201506/basic_operations/update_ad_group.py index c7a01151..38f52a22 100755 --- a/examples/adwords/v201506/basic_operations/update_ad_group.py +++ b/examples/adwords/v201506/basic_operations/update_ad_group.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/update_campaign.py b/examples/adwords/v201506/basic_operations/update_campaign.py index 2162e056..e97986bd 100755 --- a/examples/adwords/v201506/basic_operations/update_campaign.py +++ b/examples/adwords/v201506/basic_operations/update_campaign.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/update_keyword.py b/examples/adwords/v201506/basic_operations/update_keyword.py index 51eaa44a..37e3644e 100755 --- a/examples/adwords/v201506/basic_operations/update_keyword.py +++ b/examples/adwords/v201506/basic_operations/update_keyword.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/add_campaign_labels.py b/examples/adwords/v201506/campaign_management/add_campaign_labels.py index 8fee3a55..3044e313 100755 --- a/examples/adwords/v201506/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201506/campaign_management/add_campaign_labels.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutateLabel """ -__author__ = 'Mark Saniscalchi' from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/add_experiment.py b/examples/adwords/v201506/campaign_management/add_experiment.py index 534a6c9d..d04117a5 100755 --- a/examples/adwords/v201506/campaign_management/add_experiment.py +++ b/examples/adwords/v201506/campaign_management/add_experiment.py @@ -27,12 +27,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ExperimentService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import datetime import uuid diff --git a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py index d1e25e14..27561489 100755 --- a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py +++ b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py @@ -21,14 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MutateJobService.mutate -Tags: MutateJobService.get -Tags: MutateJobService.getResult Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import random import re diff --git a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py index d507a02f..feb1106f 100755 --- a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py index ad9b73fc..be536c39 100755 --- a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py index 85d371d9..51728528 100755 --- a/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.get """ -__author__ = 'Mark Saniscalchi' import time diff --git a/examples/adwords/v201506/campaign_management/promote_experiment.py b/examples/adwords/v201506/campaign_management/promote_experiment.py index c2b48c6c..56cbe3bc 100755 --- a/examples/adwords/v201506/campaign_management/promote_experiment.py +++ b/examples/adwords/v201506/campaign_management/promote_experiment.py @@ -25,12 +25,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ExperimentService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/set_ad_parameters.py b/examples/adwords/v201506/campaign_management/set_ad_parameters.py index a88f204b..2e2a51c5 100755 --- a/examples/adwords/v201506/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201506/campaign_management/set_ad_parameters.py @@ -24,12 +24,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate, AdParamService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py index a6673363..f0b65df9 100755 --- a/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignCriterionService.mutate """ -__author__ = ('api.dklimkin@gmail.com (Danial Klimkin)', - 'Joseph DiLallo') - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/validate_text_ad.py b/examples/adwords/v201506/campaign_management/validate_text_ad.py index 534772d5..8bc022f6 100755 --- a/examples/adwords/v201506/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201506/campaign_management/validate_text_ad.py @@ -21,12 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import suds diff --git a/examples/adwords/v201506/error_handling/handle_partial_failures.py b/examples/adwords/v201506/error_handling/handle_partial_failures.py index a22f64ed..39c8b4e3 100755 --- a/examples/adwords/v201506/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201506/error_handling/handle_partial_failures.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import re diff --git a/examples/adwords/v201506/error_handling/handle_policy_violation_error.py b/examples/adwords/v201506/error_handling/handle_policy_violation_error.py index 53640a42..ccf35075 100755 --- a/examples/adwords/v201506/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201506/error_handling/handle_policy_violation_error.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = 'Joseph DiLallo' import re diff --git a/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py index 00741ce9..5777903f 100755 --- a/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomerFeedService.mutate, FeedService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') import time import uuid diff --git a/examples/adwords/v201506/extensions/add_site_links.py b/examples/adwords/v201506/extensions/add_site_links.py index 4dd8520b..3e54c326 100755 --- a/examples/adwords/v201506/extensions/add_site_links.py +++ b/examples/adwords/v201506/extensions/add_site_links.py @@ -21,11 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignExtensionSettingService.mutate, CustomerService.get Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' from datetime import datetime diff --git a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py index cce0de02..562ce67c 100755 --- a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py @@ -24,12 +24,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignFeedService.mutate, FeedItemService.mutate -Tags: FeedMappingService.mutate, FeedService.mutate Api: AdWordsOnly """ -__author__ = 'Joseph DiLallo' import re import uuid diff --git a/examples/adwords/v201506/migration/migrate_to_extension_settings.py b/examples/adwords/v201506/migration/migrate_to_extension_settings.py index c54fc6e0..8798818b 100755 --- a/examples/adwords/v201506/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201506/migration/migrate_to_extension_settings.py @@ -27,13 +27,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: FeedService.get, FeedMappingService.get, FeedItemService.get -Tags: CampaignExtensionSettingService.mutate, CampaignFeedService.get, -Tags: CampaignFeedService.mutate Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' from googleads import adwords diff --git a/examples/adwords/v201506/migration/upgrade_ad_url.py b/examples/adwords/v201506/migration/upgrade_ad_url.py index 1a9c1b4f..c4158ff0 100755 --- a/examples/adwords/v201506/migration/upgrade_ad_url.py +++ b/examples/adwords/v201506/migration/upgrade_ad_url.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get, AdGroupAdService.upgradeUrl """ -__author__ = 'Mark Saniscalchi' from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201506/misc/get_all_images_and_videos.py b/examples/adwords/v201506/misc/get_all_images_and_videos.py index 428017d8..cfc01af6 100755 --- a/examples/adwords/v201506/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201506/misc/get_all_images_and_videos.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MediaService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/misc/upload_image.py b/examples/adwords/v201506/misc/upload_image.py index 267d14fe..a017eb69 100755 --- a/examples/adwords/v201506/misc/upload_image.py +++ b/examples/adwords/v201506/misc/upload_image.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MediaService.upload """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import base64 diff --git a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py index b35e68b8..58836606 100755 --- a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py @@ -21,12 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TrafficEstimatorService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py index 34a18888..f8961aef 100755 --- a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: BidLandscapeService.getBidLandscape Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/optimization/get_keyword_ideas.py b/examples/adwords/v201506/optimization/get_keyword_ideas.py index 5b9d7757..1ac5f573 100755 --- a/examples/adwords/v201506/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201506/optimization/get_keyword_ideas.py @@ -21,12 +21,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TargetingIdeaService.get Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/remarketing/add_audience.py b/examples/adwords/v201506/remarketing/add_audience.py index 2939dd56..437bd427 100755 --- a/examples/adwords/v201506/remarketing/add_audience.py +++ b/examples/adwords/v201506/remarketing/add_audience.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserListService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import uuid diff --git a/examples/adwords/v201506/remarketing/add_conversion_tracker.py b/examples/adwords/v201506/remarketing/add_conversion_tracker.py index 7801ab0e..cda8ff0c 100755 --- a/examples/adwords/v201506/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201506/remarketing/add_conversion_tracker.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ConversionTrackerService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import uuid diff --git a/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py index b54feeaf..2b411d81 100755 --- a/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py @@ -25,10 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdwordsUserListService.mutate """ -__author__ = 'Mark Saniscalchi' import calendar from datetime import date diff --git a/examples/adwords/v201506/reporting/download_criteria_report.py b/examples/adwords/v201506/reporting/download_criteria_report.py index 21420b9e..4dae0371 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report.py +++ b/examples/adwords/v201506/reporting/download_criteria_report.py @@ -23,11 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' import logging import sys diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py index 3543c6f5..9723455f 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py @@ -23,11 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' import logging import StringIO diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py index a0c5aaa7..d8be18c5 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') import logging import StringIO diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py index cbc6e56c..af4f366a 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py @@ -23,11 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = 'Mark Saniscalchi' import logging diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py index 800a8076..469b5653 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py index a2f69a59..864ee661 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py @@ -23,12 +23,9 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.mutate Api: AdWordsOnly """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/reporting/get_report_fields.py b/examples/adwords/v201506/reporting/get_report_fields.py index eeb64ccb..289f9df7 100755 --- a/examples/adwords/v201506/reporting/get_report_fields.py +++ b/examples/adwords/v201506/reporting/get_report_fields.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ReportDefinitionService.getReportFields """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/shopping/add_product_partition_tree.py b/examples/adwords/v201506/shopping/add_product_partition_tree.py index f36770fb..b2aa3a80 100755 --- a/examples/adwords/v201506/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201506/shopping/add_product_partition_tree.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import adwords diff --git a/examples/adwords/v201506/shopping/add_product_scope.py b/examples/adwords/v201506/shopping/add_product_scope.py index d8376d45..28c18b4b 100755 --- a/examples/adwords/v201506/shopping/add_product_scope.py +++ b/examples/adwords/v201506/shopping/add_product_scope.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignCriterionService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import adwords diff --git a/examples/adwords/v201506/shopping/add_shopping_campaign.py b/examples/adwords/v201506/shopping/add_shopping_campaign.py index 21663a93..4dc3e54c 100755 --- a/examples/adwords/v201506/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201506/shopping/add_shopping_campaign.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate, AdGroupService.mutate, AdGroupAdService.mutate """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') import uuid diff --git a/examples/adwords/v201506/shopping/get_product_category_taxonomy.py b/examples/adwords/v201506/shopping/get_product_category_taxonomy.py index da3a7d23..98bc359d 100755 --- a/examples/adwords/v201506/shopping/get_product_category_taxonomy.py +++ b/examples/adwords/v201506/shopping/get_product_category_taxonomy.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ConstantDataService.getProductBiddingCategoryData """ -__author__ = ('api.msaniscalchi@gmail.com (Mark Saniscalchi)', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import adwords diff --git a/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py index 3476019e..16db54a2 100755 --- a/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignCriterionService.mutate """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py index 0ff8e703..e3d72430 100755 --- a/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'Joseph Dilallo' from googleads import adwords diff --git a/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py index 3e2e65d5..147c1140 100755 --- a/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignCriterionService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py index 88532997..189b3597 100755 --- a/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ConstantDataService.getLanguageCriterion -Tags: ConstantDataService.getCarrierCriterion """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adwords/v201506/targeting/lookup_location.py b/examples/adwords/v201506/targeting/lookup_location.py index 4de1b3eb..b65efa30 100755 --- a/examples/adwords/v201506/targeting/lookup_location.py +++ b/examples/adwords/v201506/targeting/lookup_location.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: LocationCriterionService.get """ -__author__ = ('api.kwinter@gmail.com (Kevin Winter)' - 'Joseph DiLallo') from googleads import adwords diff --git a/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py index 187d2596..01d4442b 100755 --- a/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py +++ b/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import uuid diff --git a/examples/adxbuyer/v201409/basic_operations/add_campaigns.py b/examples/adxbuyer/v201409/basic_operations/add_campaigns.py index d2ddd0dd..8385b980 100755 --- a/examples/adxbuyer/v201409/basic_operations/add_campaigns.py +++ b/examples/adxbuyer/v201409/basic_operations/add_campaigns.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate -Tags: BudgetService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import datetime import uuid diff --git a/examples/adxbuyer/v201409/basic_operations/add_placements.py b/examples/adxbuyer/v201409/basic_operations/add_placements.py index a815d47c..0eab3807 100755 --- a/examples/adxbuyer/v201409/basic_operations/add_placements.py +++ b/examples/adxbuyer/v201409/basic_operations/add_placements.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py index ce94ab77..7af580b7 100755 --- a/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py +++ b/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import uuid diff --git a/examples/adxbuyer/v201409/basic_operations/get_placements.py b/examples/adxbuyer/v201409/basic_operations/get_placements.py index 5f109eee..38316425 100755 --- a/examples/adxbuyer/v201409/basic_operations/get_placements.py +++ b/examples/adxbuyer/v201409/basic_operations/get_placements.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.get """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py index 7e6401cd..d9958aa9 100755 --- a/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py +++ b/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201409/basic_operations/remove_placement.py b/examples/adxbuyer/v201409/basic_operations/remove_placement.py index 1f1655ad..c1e77ff0 100755 --- a/examples/adxbuyer/v201409/basic_operations/remove_placement.py +++ b/examples/adxbuyer/v201409/basic_operations/remove_placement.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201409/basic_operations/update_placement.py b/examples/adxbuyer/v201409/basic_operations/update_placement.py index bae10ac5..9ba0cccb 100755 --- a/examples/adxbuyer/v201409/basic_operations/update_placement.py +++ b/examples/adxbuyer/v201409/basic_operations/update_placement.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py index df803b9e..e54a32d9 100755 --- a/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py +++ b/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MutateJobService.mutate -Tags: MutateJobService.get -Tags: MutateJobService.getResult """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import random import re diff --git a/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py index 28d4b451..b59977df 100755 --- a/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py +++ b/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import re diff --git a/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py index 04027a3c..ec1dd7b2 100755 --- a/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py +++ b/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import uuid diff --git a/examples/adxbuyer/v201502/basic_operations/add_campaigns.py b/examples/adxbuyer/v201502/basic_operations/add_campaigns.py index 1e11d1c4..1b2f4416 100755 --- a/examples/adxbuyer/v201502/basic_operations/add_campaigns.py +++ b/examples/adxbuyer/v201502/basic_operations/add_campaigns.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate -Tags: BudgetService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import datetime import uuid diff --git a/examples/adxbuyer/v201502/basic_operations/add_placements.py b/examples/adxbuyer/v201502/basic_operations/add_placements.py index 7cb0bfe1..88a853c6 100755 --- a/examples/adxbuyer/v201502/basic_operations/add_placements.py +++ b/examples/adxbuyer/v201502/basic_operations/add_placements.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py index 8ccd8581..8097343f 100755 --- a/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py +++ b/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import uuid diff --git a/examples/adxbuyer/v201502/basic_operations/get_placements.py b/examples/adxbuyer/v201502/basic_operations/get_placements.py index e2355618..88f52bec 100755 --- a/examples/adxbuyer/v201502/basic_operations/get_placements.py +++ b/examples/adxbuyer/v201502/basic_operations/get_placements.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.get """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py index 9b54a0ca..593d9660 100755 --- a/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py +++ b/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201502/basic_operations/remove_placement.py b/examples/adxbuyer/v201502/basic_operations/remove_placement.py index 0c9ddcb8..d2fd0d30 100755 --- a/examples/adxbuyer/v201502/basic_operations/remove_placement.py +++ b/examples/adxbuyer/v201502/basic_operations/remove_placement.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201502/basic_operations/update_placement.py b/examples/adxbuyer/v201502/basic_operations/update_placement.py index 6f08598d..faea2ccc 100755 --- a/examples/adxbuyer/v201502/basic_operations/update_placement.py +++ b/examples/adxbuyer/v201502/basic_operations/update_placement.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py index 6eb3da56..e6d43230 100755 --- a/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py +++ b/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MutateJobService.mutate -Tags: MutateJobService.get -Tags: MutateJobService.getResult """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import random import re diff --git a/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py index 8b57f953..94e360e1 100755 --- a/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py +++ b/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import re diff --git a/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py index 36643b17..ba3920e5 100755 --- a/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py +++ b/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import uuid diff --git a/examples/adxbuyer/v201506/basic_operations/add_campaigns.py b/examples/adxbuyer/v201506/basic_operations/add_campaigns.py index f869d252..a7958911 100755 --- a/examples/adxbuyer/v201506/basic_operations/add_campaigns.py +++ b/examples/adxbuyer/v201506/basic_operations/add_campaigns.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CampaignService.mutate -Tags: BudgetService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import datetime import uuid diff --git a/examples/adxbuyer/v201506/basic_operations/add_placements.py b/examples/adxbuyer/v201506/basic_operations/add_placements.py index 73a1eb83..344a7a16 100755 --- a/examples/adxbuyer/v201506/basic_operations/add_placements.py +++ b/examples/adxbuyer/v201506/basic_operations/add_placements.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py index 0e7d3432..687fba1e 100755 --- a/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py +++ b/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import uuid diff --git a/examples/adxbuyer/v201506/basic_operations/get_placements.py b/examples/adxbuyer/v201506/basic_operations/get_placements.py index 1ff485e3..33f4969f 100755 --- a/examples/adxbuyer/v201506/basic_operations/get_placements.py +++ b/examples/adxbuyer/v201506/basic_operations/get_placements.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.get """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py index 5da3b45f..0b4d794d 100755 --- a/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py +++ b/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupAdService.get """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201506/basic_operations/remove_placement.py b/examples/adxbuyer/v201506/basic_operations/remove_placement.py index f056f2b3..cf0e59aa 100755 --- a/examples/adxbuyer/v201506/basic_operations/remove_placement.py +++ b/examples/adxbuyer/v201506/basic_operations/remove_placement.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201506/basic_operations/update_placement.py b/examples/adxbuyer/v201506/basic_operations/update_placement.py index 0821a436..fad84fcf 100755 --- a/examples/adxbuyer/v201506/basic_operations/update_placement.py +++ b/examples/adxbuyer/v201506/basic_operations/update_placement.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' from googleads import adwords diff --git a/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py index 031c83e5..cabccf97 100755 --- a/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py +++ b/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: MutateJobService.mutate -Tags: MutateJobService.get -Tags: MutateJobService.getResult """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import random import re diff --git a/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py index 88057e6b..25f09598 100755 --- a/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py +++ b/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: AdGroupCriterionService.mutate """ -__author__ = 'api.kwinter@gmail.com (Kevin Winter)' import re diff --git a/examples/dfa/authentication/create_dfa_client_with_service_account.py b/examples/dfa/authentication/create_dfa_client_with_service_account.py index 77b2f8ec..e496b485 100755 --- a/examples/dfa/authentication/create_dfa_client_with_service_account.py +++ b/examples/dfa/authentication/create_dfa_client_with_service_account.py @@ -16,7 +16,6 @@ """Initializes a DfaClient via impersonation using a Service Account.""" -__author__ = 'Mark Saniscalchi' from googleads import dfa from googleads import oauth2 diff --git a/examples/dfa/authentication/create_dfa_client_without_yaml.py b/examples/dfa/authentication/create_dfa_client_without_yaml.py index 47677634..dfa5f80a 100755 --- a/examples/dfa/authentication/create_dfa_client_without_yaml.py +++ b/examples/dfa/authentication/create_dfa_client_without_yaml.py @@ -22,7 +22,6 @@ client and a DfaClient without relying on a yaml file. """ -__author__ = 'Joseph DiLallo' from googleads import dfa from googleads import oauth2 diff --git a/examples/dfa/authentication/generate_refresh_token.py b/examples/dfa/authentication/generate_refresh_token.py index aaed2437..62665840 100755 --- a/examples/dfa/authentication/generate_refresh_token.py +++ b/examples/dfa/authentication/generate_refresh_token.py @@ -16,7 +16,6 @@ """Generates a refresh token for use with DFA.""" -__author__ = 'Mark Saniscalchi' import sys diff --git a/examples/dfa/v1_20/add_advertiser_user_filter.py b/examples/dfa/v1_20/add_advertiser_user_filter.py index 582d7cda..b7d9c0f4 100755 --- a/examples/dfa/v1_20/add_advertiser_user_filter.py +++ b/examples/dfa/v1_20/add_advertiser_user_filter.py @@ -28,10 +28,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: user.getUser, user.saveUser """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py b/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py index 9944e6c3..2e5505b9 100755 --- a/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py +++ b/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: advertisergroup.assignAdvertisersToAdvertiserGroup """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/assign_creatives_to_placements.py b/examples/dfa/v1_20/assign_creatives_to_placements.py index 51703c1a..be4e3377 100755 --- a/examples/dfa/v1_20/assign_creatives_to_placements.py +++ b/examples/dfa/v1_20/assign_creatives_to_placements.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creative.assignCreativesToPlacements """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_advertiser.py b/examples/dfa/v1_20/create_advertiser.py index 96ba7e38..962bc0ec 100755 --- a/examples/dfa/v1_20/create_advertiser.py +++ b/examples/dfa/v1_20/create_advertiser.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: advertiser.saveAdvertiser """ -__author__ = 'Joseph DiLallo' import uuid diff --git a/examples/dfa/v1_20/create_advertiser_group.py b/examples/dfa/v1_20/create_advertiser_group.py index e0e2e490..f8e3eaa2 100755 --- a/examples/dfa/v1_20/create_advertiser_group.py +++ b/examples/dfa/v1_20/create_advertiser_group.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: advertisergroup.saveAdvertiserGroup """ -__author__ = 'Joseph DiLallo' import uuid diff --git a/examples/dfa/v1_20/create_campaign.py b/examples/dfa/v1_20/create_campaign.py index 53969e95..48d92902 100755 --- a/examples/dfa/v1_20/create_campaign.py +++ b/examples/dfa/v1_20/create_campaign.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: campaign.saveCampaign """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_content_category.py b/examples/dfa/v1_20/create_content_category.py index d9a19808..fafc24f1 100755 --- a/examples/dfa/v1_20/create_content_category.py +++ b/examples/dfa/v1_20/create_content_category.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: contentcategory.saveContentCategory """ -__author__ = 'Joseph DiLallo' import uuid diff --git a/examples/dfa/v1_20/create_creative_field.py b/examples/dfa/v1_20/create_creative_field.py index 5b58666c..213fec2c 100755 --- a/examples/dfa/v1_20/create_creative_field.py +++ b/examples/dfa/v1_20/create_creative_field.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creativefield.saveCreativeField """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_creative_field_value.py b/examples/dfa/v1_20/create_creative_field_value.py index e2cbf7a7..690b7cc8 100755 --- a/examples/dfa/v1_20/create_creative_field_value.py +++ b/examples/dfa/v1_20/create_creative_field_value.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creativefield.saveCreativeFieldValue """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_creative_group.py b/examples/dfa/v1_20/create_creative_group.py index 5eb25fa3..1ffafc6c 100755 --- a/examples/dfa/v1_20/create_creative_group.py +++ b/examples/dfa/v1_20/create_creative_group.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creativegroup.saveCreativeGroup """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_flash_inpage_creative.py b/examples/dfa/v1_20/create_flash_inpage_creative.py index 06d7026e..348090a4 100755 --- a/examples/dfa/v1_20/create_flash_inpage_creative.py +++ b/examples/dfa/v1_20/create_flash_inpage_creative.py @@ -26,10 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creative.saveCreative """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_html_asset.py b/examples/dfa/v1_20/create_html_asset.py index 6e24dd83..50a7faef 100755 --- a/examples/dfa/v1_20/create_html_asset.py +++ b/examples/dfa/v1_20/create_html_asset.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creative.saveCreativeAsset """ -__author__ = 'Joseph DiLallo' import base64 # Import appropriate modules from the client library. diff --git a/examples/dfa/v1_20/create_image_asset.py b/examples/dfa/v1_20/create_image_asset.py index 52960c0b..b57a5f61 100755 --- a/examples/dfa/v1_20/create_image_asset.py +++ b/examples/dfa/v1_20/create_image_asset.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creative.saveCreativeAsset """ -__author__ = 'Joseph DiLallo' import base64 diff --git a/examples/dfa/v1_20/create_in_stream_video_creative.py b/examples/dfa/v1_20/create_in_stream_video_creative.py index 2d368726..7a8bf9f0 100755 --- a/examples/dfa/v1_20/create_in_stream_video_creative.py +++ b/examples/dfa/v1_20/create_in_stream_video_creative.py @@ -26,10 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creative.saveCreative """ -__author__ = 'Joseph DiLallo' import uuid diff --git a/examples/dfa/v1_20/create_placement.py b/examples/dfa/v1_20/create_placement.py index f7d5ee70..13462db1 100755 --- a/examples/dfa/v1_20/create_placement.py +++ b/examples/dfa/v1_20/create_placement.py @@ -26,10 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: placement.savePlacement """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_placement_strategy.py b/examples/dfa/v1_20/create_placement_strategy.py index e47abf04..122ed269 100755 --- a/examples/dfa/v1_20/create_placement_strategy.py +++ b/examples/dfa/v1_20/create_placement_strategy.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: strategy.savePlacementStrategy """ -__author__ = 'Joseph DiLallo' import uuid diff --git a/examples/dfa/v1_20/create_rotation_group.py b/examples/dfa/v1_20/create_rotation_group.py index afd14665..a54fea8a 100755 --- a/examples/dfa/v1_20/create_rotation_group.py +++ b/examples/dfa/v1_20/create_rotation_group.py @@ -26,10 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ad.saveAd """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_spotlight_activity.py b/examples/dfa/v1_20/create_spotlight_activity.py index 5c8387a1..10f88032 100755 --- a/examples/dfa/v1_20/create_spotlight_activity.py +++ b/examples/dfa/v1_20/create_spotlight_activity.py @@ -25,10 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: spotlight.saveSpotlightActivity """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_spotlight_activity_group.py b/examples/dfa/v1_20/create_spotlight_activity_group.py index 7b40dc31..2eeee577 100755 --- a/examples/dfa/v1_20/create_spotlight_activity_group.py +++ b/examples/dfa/v1_20/create_spotlight_activity_group.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: spotlight.saveSpotlightActivityGroup """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_subnetwork.py b/examples/dfa/v1_20/create_subnetwork.py index ba11a5e8..4850967a 100755 --- a/examples/dfa/v1_20/create_subnetwork.py +++ b/examples/dfa/v1_20/create_subnetwork.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: subnetwork.saveSubnetwork """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/create_user_role.py b/examples/dfa/v1_20/create_user_role.py index 4d2407aa..d713c09d 100755 --- a/examples/dfa/v1_20/create_user_role.py +++ b/examples/dfa/v1_20/create_user_role.py @@ -25,10 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: userrole.saveUserRole """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/download_tags.py b/examples/dfa/v1_20/download_tags.py index bd74c3a4..32721eab 100755 --- a/examples/dfa/v1_20/download_tags.py +++ b/examples/dfa/v1_20/download_tags.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: placement.getPlacementTagData """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_activity_groups.py b/examples/dfa/v1_20/get_activity_groups.py index 848f617b..b92a9e7e 100755 --- a/examples/dfa/v1_20/get_activity_groups.py +++ b/examples/dfa/v1_20/get_activity_groups.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: spotlight.getSpotlightActivityGroups """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_activity_types.py b/examples/dfa/v1_20/get_activity_types.py index e7b064c1..f479a388 100755 --- a/examples/dfa/v1_20/get_activity_types.py +++ b/examples/dfa/v1_20/get_activity_types.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: spotlight.getSpotlightActivityTypes """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_ad_types.py b/examples/dfa/v1_20/get_ad_types.py index 4692ebf1..73c76bc3 100755 --- a/examples/dfa/v1_20/get_ad_types.py +++ b/examples/dfa/v1_20/get_ad_types.py @@ -22,10 +22,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ad.getAdTypes """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_advertiser_groups.py b/examples/dfa/v1_20/get_advertiser_groups.py index 003ff214..c7b16ab0 100755 --- a/examples/dfa/v1_20/get_advertiser_groups.py +++ b/examples/dfa/v1_20/get_advertiser_groups.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: advertisergroup.getAdvertiserGroups """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_advertisers.py b/examples/dfa/v1_20/get_advertisers.py index d759a0b9..98407cbf 100755 --- a/examples/dfa/v1_20/get_advertisers.py +++ b/examples/dfa/v1_20/get_advertisers.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: advertiser.getAdvertisers """ -__author__ = 'Joseph DiLallo' import googleads.dfa diff --git a/examples/dfa/v1_20/get_available_permissions.py b/examples/dfa/v1_20/get_available_permissions.py index 2ed69e68..800cd02f 100755 --- a/examples/dfa/v1_20/get_available_permissions.py +++ b/examples/dfa/v1_20/get_available_permissions.py @@ -28,10 +28,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: userrole.getAvailablePermissions """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_campaigns.py b/examples/dfa/v1_20/get_campaigns.py index ad8bf39f..35de6775 100755 --- a/examples/dfa/v1_20/get_campaigns.py +++ b/examples/dfa/v1_20/get_campaigns.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: campaign.getCampaignsByCriteria """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_change_log_for_advertiser.py b/examples/dfa/v1_20/get_change_log_for_advertiser.py index 8af6c0f9..5a7f0891 100755 --- a/examples/dfa/v1_20/get_change_log_for_advertiser.py +++ b/examples/dfa/v1_20/get_change_log_for_advertiser.py @@ -27,10 +27,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: changelog.getChangeLogRecords """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_change_log_object_types.py b/examples/dfa/v1_20/get_change_log_object_types.py index 9952c95c..26b04dae 100755 --- a/examples/dfa/v1_20/get_change_log_object_types.py +++ b/examples/dfa/v1_20/get_change_log_object_types.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: changelog.getChangeLogObjectTypes """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_content_categories.py b/examples/dfa/v1_20/get_content_categories.py index 7c0b1cc3..735657d9 100755 --- a/examples/dfa/v1_20/get_content_categories.py +++ b/examples/dfa/v1_20/get_content_categories.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: contentcategory.getContentCategories """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_countries.py b/examples/dfa/v1_20/get_countries.py index 358a2b85..4f79e613 100755 --- a/examples/dfa/v1_20/get_countries.py +++ b/examples/dfa/v1_20/get_countries.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: spotlight.getCountriesByCriteria """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_creative_field.py b/examples/dfa/v1_20/get_creative_field.py index 6be814e4..f376bdf0 100755 --- a/examples/dfa/v1_20/get_creative_field.py +++ b/examples/dfa/v1_20/get_creative_field.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creativefield.getCreativeFields """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_creative_field_values.py b/examples/dfa/v1_20/get_creative_field_values.py index c97e1ac2..ce2caff6 100755 --- a/examples/dfa/v1_20/get_creative_field_values.py +++ b/examples/dfa/v1_20/get_creative_field_values.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creativefield.getCreativeFieldValues """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_creative_groups.py b/examples/dfa/v1_20/get_creative_groups.py index 9f942270..51fdaa99 100755 --- a/examples/dfa/v1_20/get_creative_groups.py +++ b/examples/dfa/v1_20/get_creative_groups.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creativegroup.getCreativeGroups """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_creative_types.py b/examples/dfa/v1_20/get_creative_types.py index 09d7c7d8..03f5236d 100755 --- a/examples/dfa/v1_20/get_creative_types.py +++ b/examples/dfa/v1_20/get_creative_types.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creative.getCreativeTypes """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_creatives.py b/examples/dfa/v1_20/get_creatives.py index cc891cd5..15187683 100755 --- a/examples/dfa/v1_20/get_creatives.py +++ b/examples/dfa/v1_20/get_creatives.py @@ -24,10 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: creative.getCreatives """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_dfa_site.py b/examples/dfa/v1_20/get_dfa_site.py index 38a15a56..c10205b6 100755 --- a/examples/dfa/v1_20/get_dfa_site.py +++ b/examples/dfa/v1_20/get_dfa_site.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: site.getDfaSites """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_placement_strategies.py b/examples/dfa/v1_20/get_placement_strategies.py index e3852bd5..99f6a2de 100755 --- a/examples/dfa/v1_20/get_placement_strategies.py +++ b/examples/dfa/v1_20/get_placement_strategies.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: strategy.getPlacementStrategiesByCriteria """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_placement_types.py b/examples/dfa/v1_20/get_placement_types.py index b1e6004f..a024644a 100755 --- a/examples/dfa/v1_20/get_placement_types.py +++ b/examples/dfa/v1_20/get_placement_types.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: placement.getPlacementTypes """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_placements.py b/examples/dfa/v1_20/get_placements.py index 3d9c9b2e..edcd6b5a 100755 --- a/examples/dfa/v1_20/get_placements.py +++ b/examples/dfa/v1_20/get_placements.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: placement.getPlacementsByCriteria """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_pricing_types.py b/examples/dfa/v1_20/get_pricing_types.py index 48d1c5a5..117212a0 100755 --- a/examples/dfa/v1_20/get_pricing_types.py +++ b/examples/dfa/v1_20/get_pricing_types.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: placement.getPricingTypes """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_size.py b/examples/dfa/v1_20/get_size.py index a60e7657..53930a2b 100755 --- a/examples/dfa/v1_20/get_size.py +++ b/examples/dfa/v1_20/get_size.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: size.getSize """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_subnetworks.py b/examples/dfa/v1_20/get_subnetworks.py index eb578443..8351ee5c 100755 --- a/examples/dfa/v1_20/get_subnetworks.py +++ b/examples/dfa/v1_20/get_subnetworks.py @@ -27,10 +27,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: subnetwork.getSubnetworks """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_tag_method_types.py b/examples/dfa/v1_20/get_tag_method_types.py index 044373fc..86d00192 100755 --- a/examples/dfa/v1_20/get_tag_method_types.py +++ b/examples/dfa/v1_20/get_tag_method_types.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: spotlight.getSpotlightTagMethodTypes """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_user_filter_types.py b/examples/dfa/v1_20/get_user_filter_types.py index e7b9c28c..984b5e24 100755 --- a/examples/dfa/v1_20/get_user_filter_types.py +++ b/examples/dfa/v1_20/get_user_filter_types.py @@ -21,10 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: user.getAvailableUserFilterCriteriaTypes """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_user_roles.py b/examples/dfa/v1_20/get_user_roles.py index fe41f565..8afd61f5 100755 --- a/examples/dfa/v1_20/get_user_roles.py +++ b/examples/dfa/v1_20/get_user_roles.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: userrole.getUserRoles """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfa/v1_20/get_users.py b/examples/dfa/v1_20/get_users.py index f7a57109..b67c63be 100755 --- a/examples/dfa/v1_20/get_users.py +++ b/examples/dfa/v1_20/get_users.py @@ -23,10 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: user.getUsersByCriteria """ -__author__ = 'Joseph DiLallo' # Import appropriate modules from the client library. from googleads import dfa diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/dfp/authentication/create_dfp_client_with_service_account.py index 59b92fd3..264c4edc 100755 --- a/examples/dfp/authentication/create_dfp_client_with_service_account.py +++ b/examples/dfp/authentication/create_dfp_client_with_service_account.py @@ -16,7 +16,6 @@ """Initializes a DfpClient using a Service Account.""" -__author__ = 'Mark Saniscalchi' from googleads import dfp from googleads import oauth2 diff --git a/examples/dfp/authentication/create_dfp_client_without_yaml.py b/examples/dfp/authentication/create_dfp_client_without_yaml.py index 357d0622..8d57e16d 100755 --- a/examples/dfp/authentication/create_dfp_client_without_yaml.py +++ b/examples/dfp/authentication/create_dfp_client_without_yaml.py @@ -22,7 +22,6 @@ client and a DfpClient without relying on a yaml file. """ -__author__ = 'Joseph DiLallo' from googleads import dfp from googleads import oauth2 diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py index de6aa6da..d41ac526 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/dfp/authentication/generate_refresh_token.py @@ -16,7 +16,6 @@ """Generates a refresh token for use with DFP.""" -__author__ = 'Mark Saniscalchi' import sys diff --git a/examples/dfp/v201408/contact_service/__init__.py b/examples/dfp/v201408/contact_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/contact_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201408/content_metadata_key_hierarchy_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/content_service/__init__.py b/examples/dfp/v201408/content_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/content_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/creative_service/__init__.py b/examples/dfp/v201408/creative_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/creative_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/creative_set_service/__init__.py b/examples/dfp/v201408/creative_set_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/creative_set_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/creative_template_service/__init__.py b/examples/dfp/v201408/creative_template_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/creative_template_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/custom_field_service/__init__.py b/examples/dfp/v201408/custom_field_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/custom_field_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/custom_targeting_service/__init__.py b/examples/dfp/v201408/custom_targeting_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/custom_targeting_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/inventory_service/__init__.py b/examples/dfp/v201408/inventory_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/inventory_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/label_service/__init__.py b/examples/dfp/v201408/label_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/label_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/line_item_creative_association_service/__init__.py b/examples/dfp/v201408/line_item_creative_association_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/line_item_creative_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/line_item_service/__init__.py b/examples/dfp/v201408/line_item_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/line_item_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/network_service/__init__.py b/examples/dfp/v201408/network_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/network_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/order_service/__init__.py b/examples/dfp/v201408/order_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/order_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/publisher_query_language_service/__init__.py b/examples/dfp/v201408/publisher_query_language_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/publisher_query_language_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/report_service/__init__.py b/examples/dfp/v201408/report_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/report_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/suggested_ad_unit_service/__init__.py b/examples/dfp/v201408/suggested_ad_unit_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/suggested_ad_unit_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/team_service/__init__.py b/examples/dfp/v201408/team_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/team_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/user_service/__init__.py b/examples/dfp/v201408/user_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/user_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201408/user_team_association_service/__init__.py b/examples/dfp/v201408/user_team_association_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201408/user_team_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/activity_group_service/create_activity_groups.py b/examples/dfp/v201411/activity_group_service/create_activity_groups.py index 4a57d7a5..f8be58bd 100755 --- a/examples/dfp/v201411/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201411/activity_group_service/create_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.createActivityGroups """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py index 99dea94d..10040d10 100755 --- a/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroupsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py index 38571d30..306eb56c 100755 --- a/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroupsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/activity_group_service/update_activity_groups.py b/examples/dfp/v201411/activity_group_service/update_activity_groups.py index a1ca687c..98b3fca2 100755 --- a/examples/dfp/v201411/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201411/activity_group_service/update_activity_groups.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroup -Tags: ActivityGroupService.updateActivityGroups """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/activity_service/create_activities.py b/examples/dfp/v201411/activity_service/create_activities.py index d9220dcc..2429d4aa 100755 --- a/examples/dfp/v201411/activity_service/create_activities.py +++ b/examples/dfp/v201411/activity_service/create_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.createActivities """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/activity_service/get_active_activities.py b/examples/dfp/v201411/activity_service/get_active_activities.py index e3376d8b..89086383 100755 --- a/examples/dfp/v201411/activity_service/get_active_activities.py +++ b/examples/dfp/v201411/activity_service/get_active_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/activity_service/get_all_activities.py b/examples/dfp/v201411/activity_service/get_all_activities.py index cc1897c0..070b9618 100755 --- a/examples/dfp/v201411/activity_service/get_all_activities.py +++ b/examples/dfp/v201411/activity_service/get_all_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/activity_service/update_activities.py b/examples/dfp/v201411/activity_service/update_activities.py index 9c215666..2fd6f715 100755 --- a/examples/dfp/v201411/activity_service/update_activities.py +++ b/examples/dfp/v201411/activity_service/update_activities.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.updateActivities - ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/audience_segment_service/create_audience_segments.py b/examples/dfp/v201411/audience_segment_service/create_audience_segments.py index d3c0bfe1..3ef66447 100755 --- a/examples/dfp/v201411/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201411/audience_segment_service/create_audience_segments.py @@ -16,8 +16,6 @@ """This example creates a new rule based first party audience segment.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py index d32b2ea2..69b63f9b 100755 --- a/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py @@ -19,8 +19,6 @@ To create audience segments, run create_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py index cb4f5c53..4593817e 100755 --- a/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py @@ -19,8 +19,6 @@ To create first party audience segments, run create_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py index 0088b991..658f0044 100755 --- a/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py @@ -20,8 +20,6 @@ get_first_party_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/audience_segment_service/update_audience_segments.py b/examples/dfp/v201411/audience_segment_service/update_audience_segments.py index 0d2dfa3e..338d54b7 100755 --- a/examples/dfp/v201411/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201411/audience_segment_service/update_audience_segments.py @@ -19,8 +19,6 @@ To determine which audience segments exist, run get_all_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/base_rate_service/create_product_base_rates.py b/examples/dfp/v201411/base_rate_service/create_product_base_rates.py index dcccdbba..4cde291b 100755 --- a/examples/dfp/v201411/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201411/base_rate_service/create_product_base_rates.py @@ -18,10 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.createBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py index 1d135c71..6884a1bd 100755 --- a/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py @@ -18,10 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.createBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/base_rate_service/get_all_base_rates.py b/examples/dfp/v201411/base_rate_service/get_all_base_rates.py index a5ebeaa2..450638ac 100755 --- a/examples/dfp/v201411/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201411/base_rate_service/get_all_base_rates.py @@ -20,10 +20,8 @@ To create product template base rates, run create_product_template_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py index f15d79d9..32ac9941 100755 --- a/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py @@ -20,10 +20,8 @@ To create product template base rates, run create_product_template_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/base_rate_service/update_base_rates.py b/examples/dfp/v201411/base_rate_service/update_base_rates.py index 0beebbd4..f5323598 100755 --- a/examples/dfp/v201411/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201411/base_rate_service/update_base_rates.py @@ -18,11 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement -Tags: BaseRateService.updateBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/company_service/create_companies.py b/examples/dfp/v201411/company_service/create_companies.py index 33fdedeb..219fe6d9 100755 --- a/examples/dfp/v201411/company_service/create_companies.py +++ b/examples/dfp/v201411/company_service/create_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.createCompanies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/company_service/get_advertisers.py b/examples/dfp/v201411/company_service/get_advertisers.py index 4923ecb4..759313ef 100755 --- a/examples/dfp/v201411/company_service/get_advertisers.py +++ b/examples/dfp/v201411/company_service/get_advertisers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.getCompaniesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/company_service/get_all_companies.py b/examples/dfp/v201411/company_service/get_all_companies.py index b7917243..0ca241aa 100755 --- a/examples/dfp/v201411/company_service/get_all_companies.py +++ b/examples/dfp/v201411/company_service/get_all_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.getCompaniesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/company_service/update_companies.py b/examples/dfp/v201411/company_service/update_companies.py index 2940d98f..49936e3e 100755 --- a/examples/dfp/v201411/company_service/update_companies.py +++ b/examples/dfp/v201411/company_service/update_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.updateCompanies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/contact_service/create_contacts.py b/examples/dfp/v201411/contact_service/create_contacts.py index 8fcd07ab..33473868 100755 --- a/examples/dfp/v201411/contact_service/create_contacts.py +++ b/examples/dfp/v201411/contact_service/create_contacts.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.createContacts """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/contact_service/get_all_contacts.py b/examples/dfp/v201411/contact_service/get_all_contacts.py index ddd7108f..88f319f9 100755 --- a/examples/dfp/v201411/contact_service/get_all_contacts.py +++ b/examples/dfp/v201411/contact_service/get_all_contacts.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/contact_service/get_uninvited_contacts.py b/examples/dfp/v201411/contact_service/get_uninvited_contacts.py index b911f4f8..893c9a59 100755 --- a/examples/dfp/v201411/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201411/contact_service/get_uninvited_contacts.py @@ -23,10 +23,7 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/contact_service/update_contacts.py b/examples/dfp/v201411/contact_service/update_contacts.py index 61bb8508..c1db8705 100755 --- a/examples/dfp/v201411/contact_service/update_contacts.py +++ b/examples/dfp/v201411/contact_service/update_contacts.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.updateContacts - ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index b77e1222..7b5aea36 100755 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -26,11 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 063cccca..3d20e444 100755 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -26,12 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement - ContentMetadataKeyHierarchyService.perfomContentMetadataKeyHierarchyAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index c0ae709c..d200593f 100755 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 74401822..cd8ad106 100755 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -26,12 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement - ContentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/content_service/get_all_content.py b/examples/dfp/v201411/content_service/get_all_content.py index 0ff9e1e3..919c4683 100755 --- a/examples/dfp/v201411/content_service/get_all_content.py +++ b/examples/dfp/v201411/content_service/get_all_content.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentService.getContentByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/content_service/get_content_by_category.py b/examples/dfp/v201411/content_service/get_content_by_category.py index 6273ebc0..f37eb1a8 100755 --- a/examples/dfp/v201411/content_service/get_content_by_category.py +++ b/examples/dfp/v201411/content_service/get_content_by_category.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentService.getContentByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_service/create_creative_from_template.py b/examples/dfp/v201411/creative_service/create_creative_from_template.py index 3db1c257..34c20d8e 100755 --- a/examples/dfp/v201411/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201411/creative_service/create_creative_from_template.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreative """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os @@ -90,7 +87,7 @@ def main(client, advertiser_id): } # Call service to create the creative. - creative = creative_service.createCreative(creative) + creative = creative_service.createCreatives([creative])[0] # Display results. print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' diff --git a/examples/dfp/v201411/creative_service/create_creatives.py b/examples/dfp/v201411/creative_service/create_creatives.py index 184aefc3..9d169cbc 100755 --- a/examples/dfp/v201411/creative_service/create_creatives.py +++ b/examples/dfp/v201411/creative_service/create_creatives.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreatives """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os diff --git a/examples/dfp/v201411/creative_service/create_custom_creative.py b/examples/dfp/v201411/creative_service/create_custom_creative.py index 443c98f0..e2948ee3 100755 --- a/examples/dfp/v201411/creative_service/create_custom_creative.py +++ b/examples/dfp/v201411/creative_service/create_custom_creative.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreative """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os diff --git a/examples/dfp/v201411/creative_service/get_all_creatives.py b/examples/dfp/v201411/creative_service/get_all_creatives.py index 999cf422..2dacbd55 100755 --- a/examples/dfp/v201411/creative_service/get_all_creatives.py +++ b/examples/dfp/v201411/creative_service/get_all_creatives.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_service/get_creatives_by_statement.py b/examples/dfp/v201411/creative_service/get_creatives_by_statement.py index 1c391510..f49a4222 100755 --- a/examples/dfp/v201411/creative_service/get_creatives_by_statement.py +++ b/examples/dfp/v201411/creative_service/get_creatives_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_service/update_creatives.py b/examples/dfp/v201411/creative_service/update_creatives.py index 8222690e..de7f3125 100755 --- a/examples/dfp/v201411/creative_service/update_creatives.py +++ b/examples/dfp/v201411/creative_service/update_creatives.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.updateCreatives - CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py index 134b1e6d..b70d1160 100755 --- a/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: LineItemCreativeAssociationService.createLineItemCreativeAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_set_service/create_creative_set.py b/examples/dfp/v201411/creative_set_service/create_creative_set.py index 70b26d62..d359335d 100755 --- a/examples/dfp/v201411/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201411/creative_set_service/create_creative_set.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.createCreativeSet """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py index 7b53ea25..09467cc5 100755 --- a/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py index bee62a09..22ef638b 100755 --- a/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_set_service/update_creative_set.py b/examples/dfp/v201411/creative_set_service/update_creative_set.py index 49bedcef..3738c0f1 100755 --- a/examples/dfp/v201411/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201411/creative_set_service/update_creative_set.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.updateCreativeSet - CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py index 7896b6f6..b7acc37b 100755 --- a/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeTemplateService.getCreativeTemplatesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py index dee9b434..d6cdf6a0 100755 --- a/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py +++ b/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeTemplateService.getCreativeTemplatesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py index ebc814e0..0e2b524a 100755 --- a/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.createCreativeWrappers """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py index 2090cf13..cbc924f5 100755 --- a/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrapperByStatement -Tags: CreativeWrapperService.performCreativeWrapperAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py index 0c9dc2b2..2848e4b6 100755 --- a/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py index d55662b6..3ce406a8 100755 --- a/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py index 681e06b6..eb2b4b01 100755 --- a/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement -Tags: CreativeWrapperService.updateCreativeWrappers """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_field_service/create_custom_field_options.py b/examples/dfp/v201411/custom_field_service/create_custom_field_options.py index 428865a7..d34fc59e 100755 --- a/examples/dfp/v201411/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201411/custom_field_service/create_custom_field_options.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.createCustomFieldOptions """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_field_service/create_custom_fields.py b/examples/dfp/v201411/custom_field_service/create_custom_fields.py index ec674836..1b90f115 100755 --- a/examples/dfp/v201411/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201411/custom_field_service/create_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.createCustomFields """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py index d80b74d5..4d99acc4 100755 --- a/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement -Tags: CustomFieldService.performCustomFieldAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py index d14472ca..2affc664 100755 --- a/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py index 50b1c2fd..b6c9f9a8 100755 --- a/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py index 19d4a6f2..08e778c1 100755 --- a/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement - LineItemService.getLineItemsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_field_service/update_custom_fields.py b/examples/dfp/v201411/custom_field_service/update_custom_fields.py index ef78d4c6..28ea7422 100755 --- a/examples/dfp/v201411/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201411/custom_field_service/update_custom_fields.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.updateCustomFields - CustomFieldService.getCustomFieldByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py index 2306e2c8..6820dd86 100755 --- a/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.createCustomTargetingKeys - CustomTargetingService.createCustomTargetingValues """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py index 8191349f..44bc55b9 100755 --- a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.getCustomTargetingKeysByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py index bd39b35d..d0781855 100755 --- a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.getCustomTargetingValuesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index afa13419..53877569 100755 --- a/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -19,8 +19,6 @@ To create custom targeting keys and values, run create_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py index de51b5ec..49464fda 100755 --- a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py @@ -19,8 +19,6 @@ To create custom targeting keys, run create_custom_targeting_keys_and_values.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py index fada5280..9c64b6d0 100755 --- a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ b/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py @@ -21,8 +21,6 @@ create_custom_targeting_keys_and_values.py. To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py index e8075cb0..f99aeafb 100755 --- a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py @@ -19,8 +19,6 @@ To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py index 0df55b71..d011feee 100755 --- a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py @@ -20,8 +20,6 @@ To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py index e2a4145f..a53d3ba7 100755 --- a/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py @@ -19,10 +19,8 @@ To determine which exchange rates exist, run get_all_exchange_rates.py. -Tags: ExchangeRateService.createExchangeRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py index cab6efb3..150e849a 100755 --- a/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py index 9b7591dd..b57dbcf1 100755 --- a/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py index 34cdb3f3..5acf07f4 100755 --- a/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/forecast_service/get_forecast.py b/examples/dfp/v201411/forecast_service/get_forecast.py index e45d5c39..d6eb4c73 100755 --- a/examples/dfp/v201411/forecast_service/get_forecast.py +++ b/examples/dfp/v201411/forecast_service/get_forecast.py @@ -18,8 +18,6 @@ To determine which placements exist, run get_all_placements.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date diff --git a/examples/dfp/v201411/forecast_service/get_forecast_by_id.py b/examples/dfp/v201411/forecast_service/get_forecast_by_id.py index cb2b8129..d4b40161 100755 --- a/examples/dfp/v201411/forecast_service/get_forecast_by_id.py +++ b/examples/dfp/v201411/forecast_service/get_forecast_by_id.py @@ -18,8 +18,6 @@ To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/inventory_service/archive_ad_units.py b/examples/dfp/v201411/inventory_service/archive_ad_units.py index be4d96c1..4f75a4c7 100755 --- a/examples/dfp/v201411/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201411/inventory_service/archive_ad_units.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/inventory_service/create_ad_units.py b/examples/dfp/v201411/inventory_service/create_ad_units.py index b29ef484..6e003e09 100755 --- a/examples/dfp/v201411/inventory_service/create_ad_units.py +++ b/examples/dfp/v201411/inventory_service/create_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.createAdUnits """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py index 4fef1844..cc63a207 100755 --- a/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py index face2a14..34388920 100755 --- a/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitSizesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/inventory_service/get_all_ad_units.py b/examples/dfp/v201411/inventory_service/get_all_ad_units.py index 45ebe07d..688eb008 100755 --- a/examples/dfp/v201411/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201411/inventory_service/get_all_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py index a1988c0d..1291b78d 100755 --- a/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/inventory_service/update_ad_units.py b/examples/dfp/v201411/inventory_service/update_ad_units.py index 4869b99e..96258bb0 100755 --- a/examples/dfp/v201411/inventory_service/update_ad_units.py +++ b/examples/dfp/v201411/inventory_service/update_ad_units.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnit -Tags: InventoryService.updateAdUnits """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/label_service/create_labels.py b/examples/dfp/v201411/label_service/create_labels.py index 3e26c13b..77876fb6 100755 --- a/examples/dfp/v201411/label_service/create_labels.py +++ b/examples/dfp/v201411/label_service/create_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/label_service/deactivate_labels.py b/examples/dfp/v201411/label_service/deactivate_labels.py index 4e172e2e..5ffd6659 100755 --- a/examples/dfp/v201411/label_service/deactivate_labels.py +++ b/examples/dfp/v201411/label_service/deactivate_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/label_service/get_all_labels.py b/examples/dfp/v201411/label_service/get_all_labels.py index 340f340d..7ad49239 100755 --- a/examples/dfp/v201411/label_service/get_all_labels.py +++ b/examples/dfp/v201411/label_service/get_all_labels.py @@ -19,8 +19,6 @@ To create labels, run create_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/label_service/get_labels_by_statement.py b/examples/dfp/v201411/label_service/get_labels_by_statement.py index 35368752..6f7fcc39 100755 --- a/examples/dfp/v201411/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201411/label_service/get_labels_by_statement.py @@ -20,8 +20,6 @@ premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/label_service/update_labels.py b/examples/dfp/v201411/label_service/update_labels.py index 3876ae7a..e62887ae 100755 --- a/examples/dfp/v201411/label_service/update_labels.py +++ b/examples/dfp/v201411/label_service/update_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/line_item_creative_association_service/create_licas.py b/examples/dfp/v201411/line_item_creative_association_service/create_licas.py index bbaca276..b63ca262 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201411/line_item_creative_association_service/create_licas.py @@ -19,8 +19,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py index 5c2af158..c3b0f645 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py @@ -18,8 +18,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py index f932e842..617cd409 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py @@ -19,8 +19,6 @@ To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py index 130e8c3b..fbc7b723 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py @@ -19,8 +19,6 @@ To create LICAs, run create_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/line_item_creative_association_service/update_licas.py b/examples/dfp/v201411/line_item_creative_association_service/update_licas.py index 21dbe952..69280916 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201411/line_item_creative_association_service/update_licas.py @@ -19,8 +19,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/line_item_service/activate_line_items.py b/examples/dfp/v201411/line_item_service/activate_line_items.py index e76f4764..a820d61a 100755 --- a/examples/dfp/v201411/line_item_service/activate_line_items.py +++ b/examples/dfp/v201411/line_item_service/activate_line_items.py @@ -22,8 +22,6 @@ create_licas.py. To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/line_item_service/create_line_items.py b/examples/dfp/v201411/line_item_service/create_line_items.py index 9f0a50c8..81dd730d 100755 --- a/examples/dfp/v201411/line_item_service/create_line_items.py +++ b/examples/dfp/v201411/line_item_service/create_line_items.py @@ -20,8 +20,6 @@ which orders exist, run get_all_orders.py. To determine which placements exist, run get_all_placements.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date import uuid diff --git a/examples/dfp/v201411/line_item_service/create_video_line_item.py b/examples/dfp/v201411/line_item_service/create_video_line_item.py index 2eb42fa6..20ceea82 100755 --- a/examples/dfp/v201411/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201411/line_item_service/create_video_line_item.py @@ -22,8 +22,6 @@ create_video_ad_unit.py. To create criteria for categories, run create_custom_targeting_keys_and_values.py""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date import uuid diff --git a/examples/dfp/v201411/line_item_service/get_all_line_items.py b/examples/dfp/v201411/line_item_service/get_all_line_items.py index f6549c6e..ea35b3cf 100755 --- a/examples/dfp/v201411/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201411/line_item_service/get_all_line_items.py @@ -18,8 +18,6 @@ To create line items, run create_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py index f04d3929..9cedbbbd 100755 --- a/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py +++ b/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py @@ -14,13 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets all line items that need creatives for the given -order. +"""This code example gets all line items that need creatives for an order. -To create line items, run create_line_items.py.""" +To create line items, run create_line_items.py. +""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -48,8 +46,8 @@ def main(client, order_id): 'value': 'true' } }] - query = 'WHERE orderId = :orderId AND ' - 'isMissingCreatives = :isMissingCreatives' + query = ('WHERE orderId = :orderId AND ' + 'isMissingCreatives = :isMissingCreatives') statement = dfp.FilterStatement(query, values) while True: diff --git a/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py index 2d7d4040..3abce181 100755 --- a/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py @@ -18,8 +18,6 @@ To create line items, run create_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import datetime diff --git a/examples/dfp/v201411/line_item_service/target_custom_criteria.py b/examples/dfp/v201411/line_item_service/target_custom_criteria.py index b2805e59..d3dd59cb 100755 --- a/examples/dfp/v201411/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201411/line_item_service/target_custom_criteria.py @@ -20,8 +20,6 @@ which custom targeting keys and values exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import pprint diff --git a/examples/dfp/v201411/line_item_service/update_line_items.py b/examples/dfp/v201411/line_item_service/update_line_items.py index 77cb41cb..8bd2a780 100755 --- a/examples/dfp/v201411/line_item_service/update_line_items.py +++ b/examples/dfp/v201411/line_item_service/update_line_items.py @@ -18,8 +18,6 @@ To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/network_service/get_all_networks.py b/examples/dfp/v201411/network_service/get_all_networks.py index 4c82ffbd..cb631a5c 100755 --- a/examples/dfp/v201411/network_service/get_all_networks.py +++ b/examples/dfp/v201411/network_service/get_all_networks.py @@ -19,8 +19,6 @@ A networkCode should be left out for this request.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/network_service/get_current_network.py b/examples/dfp/v201411/network_service/get_current_network.py index a5742ccb..56f7395d 100755 --- a/examples/dfp/v201411/network_service/get_current_network.py +++ b/examples/dfp/v201411/network_service/get_current_network.py @@ -16,8 +16,6 @@ """This example gets the current network that you can make requests against.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/network_service/make_test_network.py b/examples/dfp/v201411/network_service/make_test_network.py index 7e347447..11419e85 100755 --- a/examples/dfp/v201411/network_service/make_test_network.py +++ b/examples/dfp/v201411/network_service/make_test_network.py @@ -27,8 +27,6 @@ https://dfp-playground.appspot.com """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/order_service/approve_orders.py b/examples/dfp/v201411/order_service/approve_orders.py index 51a792e4..8ef188df 100755 --- a/examples/dfp/v201411/order_service/approve_orders.py +++ b/examples/dfp/v201411/order_service/approve_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import datetime diff --git a/examples/dfp/v201411/order_service/create_orders.py b/examples/dfp/v201411/order_service/create_orders.py index fd3f3301..bad34098 100755 --- a/examples/dfp/v201411/order_service/create_orders.py +++ b/examples/dfp/v201411/order_service/create_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/order_service/get_all_orders.py b/examples/dfp/v201411/order_service/get_all_orders.py index addcd5e8..be89dad4 100755 --- a/examples/dfp/v201411/order_service/get_all_orders.py +++ b/examples/dfp/v201411/order_service/get_all_orders.py @@ -19,8 +19,6 @@ To create orders, run create_orders.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/order_service/get_orders_by_statement.py b/examples/dfp/v201411/order_service/get_orders_by_statement.py index 65ce24ad..5f4cd895 100755 --- a/examples/dfp/v201411/order_service/get_orders_by_statement.py +++ b/examples/dfp/v201411/order_service/get_orders_by_statement.py @@ -18,8 +18,6 @@ To create orders, run create_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/order_service/update_orders.py b/examples/dfp/v201411/order_service/update_orders.py index 263ca6ce..cb943ac7 100755 --- a/examples/dfp/v201411/order_service/update_orders.py +++ b/examples/dfp/v201411/order_service/update_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/placement_service/create_placements.py b/examples/dfp/v201411/placement_service/create_placements.py index 4a160c5e..5bdb6f78 100755 --- a/examples/dfp/v201411/placement_service/create_placements.py +++ b/examples/dfp/v201411/placement_service/create_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/placement_service/deactivate_placements.py b/examples/dfp/v201411/placement_service/deactivate_placements.py index e83c7930..6ba63597 100755 --- a/examples/dfp/v201411/placement_service/deactivate_placements.py +++ b/examples/dfp/v201411/placement_service/deactivate_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/placement_service/get_all_placements.py b/examples/dfp/v201411/placement_service/get_all_placements.py index 5bf5be02..41d50b10 100755 --- a/examples/dfp/v201411/placement_service/get_all_placements.py +++ b/examples/dfp/v201411/placement_service/get_all_placements.py @@ -19,8 +19,6 @@ To create placements, run create_placement.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/placement_service/get_placements_by_statement.py b/examples/dfp/v201411/placement_service/get_placements_by_statement.py index 89768f20..99a3031c 100755 --- a/examples/dfp/v201411/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201411/placement_service/get_placements_by_statement.py @@ -19,8 +19,6 @@ To create a placement, run create_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/placement_service/update_placements.py b/examples/dfp/v201411/placement_service/update_placements.py index ef0be169..c6b0b100 100755 --- a/examples/dfp/v201411/placement_service/update_placements.py +++ b/examples/dfp/v201411/placement_service/update_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/premium_rate_service/create_premium_rates.py b/examples/dfp/v201411/premium_rate_service/create_premium_rates.py index 199a469a..1945e22c 100755 --- a/examples/dfp/v201411/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201411/premium_rate_service/create_premium_rates.py @@ -19,9 +19,6 @@ To determine which premium_rates exist, run get_all_premium_rates.py. """ -__author__ = 'Nicholas Chen' - - # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py index f1cf5d7c..6a695b2e 100755 --- a/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py @@ -18,10 +18,8 @@ To create premium rates, run create_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py index 6db40fed..2b02c375 100755 --- a/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py @@ -18,10 +18,8 @@ To create premium rates, run create_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/premium_rate_service/update_premium_rates.py b/examples/dfp/v201411/premium_rate_service/update_premium_rates.py index bb40da22..6d6e630b 100755 --- a/examples/dfp/v201411/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201411/premium_rate_service/update_premium_rates.py @@ -18,11 +18,8 @@ To determine which premium rates exist, run get_all_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement -Tags: PremiumRateService.updatePremiumRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/product_service/get_all_products.py b/examples/dfp/v201411/product_service/get_all_products.py index ee23f09d..629592ae 100755 --- a/examples/dfp/v201411/product_service/get_all_products.py +++ b/examples/dfp/v201411/product_service/get_all_products.py @@ -18,10 +18,8 @@ Products are created automatically from product templates. -Tags: ProductService.getProductsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/product_service/get_products_for_product_template.py b/examples/dfp/v201411/product_service/get_products_for_product_template.py index 0d3b1fd1..dca44c56 100755 --- a/examples/dfp/v201411/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201411/product_service/get_products_for_product_template.py @@ -16,10 +16,8 @@ """This example gets all products created from a product template. -Tags: ProductService.getProductsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/product_service/update_products.py b/examples/dfp/v201411/product_service/update_products.py index 40c9e246..4d043a7f 100755 --- a/examples/dfp/v201411/product_service/update_products.py +++ b/examples/dfp/v201411/product_service/update_products.py @@ -18,11 +18,8 @@ To determine which products exist, run get_all_products.py. -Tags: ProductService.getProductsByStatement -Tags: ProductService.updateProducts """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/product_template_service/activate_product_templates.py b/examples/dfp/v201411/product_template_service/activate_product_templates.py index 3541655c..f3ec5ecd 100755 --- a/examples/dfp/v201411/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201411/product_template_service/activate_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement -Tags: ProductTemplateService.performProductTemplateAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/product_template_service/create_product_templates.py b/examples/dfp/v201411/product_template_service/create_product_templates.py index 7d1d281b..e88d6360 100755 --- a/examples/dfp/v201411/product_template_service/create_product_templates.py +++ b/examples/dfp/v201411/product_template_service/create_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.createProductTemplates -Tags: NetworkService.getCurrentNetwork """ -__author__ = 'Nicholas Chen' import uuid diff --git a/examples/dfp/v201411/product_template_service/get_all_product_templates.py b/examples/dfp/v201411/product_template_service/get_all_product_templates.py index ab7f7dbf..21c3eb78 100755 --- a/examples/dfp/v201411/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201411/product_template_service/get_all_product_templates.py @@ -18,10 +18,8 @@ To create product templates, run create_product_template_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py index b6fb40d5..ca082787 100755 --- a/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py @@ -16,10 +16,8 @@ """This code example gets all sponsorship product templates. -Tags: ProductTemplateService.getProductTemplatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/product_template_service/update_product_templates.py b/examples/dfp/v201411/product_template_service/update_product_templates.py index 3e5d562a..63e416ed 100755 --- a/examples/dfp/v201411/product_template_service/update_product_templates.py +++ b/examples/dfp/v201411/product_template_service/update_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement -Tags: ProductTemplateService.updateProductTemplates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py index f1d5e071..7dec1361 100755 --- a/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py @@ -20,7 +20,6 @@ get_all_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py index 8933c4f8..9551bc74 100755 --- a/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py @@ -21,7 +21,6 @@ get_all_proposals.py. """ -__author__ = 'Nicholas Chen' from datetime import date import uuid diff --git a/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py index f2ec70d4..dbfe9db9 100755 --- a/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py @@ -19,7 +19,6 @@ To create proposal line items, run create_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 71c05562..9cdaca1f 100755 --- a/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -13,12 +13,10 @@ # 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 code example gets all proposal line items that belong to a proposal. To create proposal line items, run create_proposal_line_items.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,8 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201411') + 'ProposalLineItemService', + version='v201411') # Create statement object to only select proposal line items belonging to a # given proposal. @@ -53,11 +52,11 @@ def main(client, proposal_id): # Display results. for idx, proposal_line_item in enumerate(response['results'], start=statement.offset): - print ('%s) Line item with id \'%s\', belonging to proposal id \'%s\', ' - 'and named \'%s\' was found.' % ( - idx, proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) + print( + '%s) Proposal line item with id \'%s\', belonging to proposal id ' + '\'%s\', and named \'%s\' was found.' % ( + idx, proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py index 3aceda7c..fa16acf3 100755 --- a/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py @@ -20,7 +20,6 @@ run get_all_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/proposal_service/create_proposals.py b/examples/dfp/v201411/proposal_service/create_proposals.py index 8a296fbc..13683f61 100755 --- a/examples/dfp/v201411/proposal_service/create_proposals.py +++ b/examples/dfp/v201411/proposal_service/create_proposals.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' import uuid diff --git a/examples/dfp/v201411/proposal_service/get_all_proposals.py b/examples/dfp/v201411/proposal_service/get_all_proposals.py index 8f99c808..e95ca255 100755 --- a/examples/dfp/v201411/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201411/proposal_service/get_all_proposals.py @@ -19,7 +19,6 @@ To create proposals, run create_proposals.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py index b2882dcb..c8fba63c 100755 --- a/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py @@ -18,7 +18,6 @@ To create proposals, run create_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py index 7b34c17b..0d0e7689 100755 --- a/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/proposal_service/update_proposals.py b/examples/dfp/v201411/proposal_service/update_proposals.py index 28ec32f9..e24ea866 100755 --- a/examples/dfp/v201411/proposal_service/update_proposals.py +++ b/examples/dfp/v201411/proposal_service/update_proposals.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py index bf661f14..d5cfd085 100755 --- a/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py @@ -16,8 +16,6 @@ """This example fetches data from PQL tables and creates match table files.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py index 71c0e7a6..194dd0d3 100755 --- a/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py @@ -23,8 +23,6 @@ https://developers.google.com/doubleclick-publishers/docs/reference/v201411/PublisherQueryLanguageService """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py index 3dc35259..7eabb7f1 100755 --- a/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py @@ -16,8 +16,6 @@ """This example gets all line items with names starting with 'line item'.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py index 1cf2b027..4544c625 100755 --- a/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py @@ -16,10 +16,8 @@ """This code example gets all rate cards. -Tags: RateCardService.getRateCardsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py index 27497359..47a804df 100755 --- a/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py @@ -16,10 +16,8 @@ """This example gets all rate cards that have a currency in US dollars. -Tags: RateCardService.getRateCardsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/report_service/run_delivery_report.py b/examples/dfp/v201411/report_service/run_delivery_report.py index 274741b8..10352d58 100755 --- a/examples/dfp/v201411/report_service/run_delivery_report.py +++ b/examples/dfp/v201411/report_service/run_delivery_report.py @@ -18,8 +18,6 @@ website with additional attributes and can filter to include just one order. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201411/report_service/run_inventory_report.py b/examples/dfp/v201411/report_service/run_inventory_report.py index 508cc250..ad2c6c1f 100755 --- a/examples/dfp/v201411/report_service/run_inventory_report.py +++ b/examples/dfp/v201411/report_service/run_inventory_report.py @@ -18,8 +18,6 @@ DFP website. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201411/report_service/run_reach_report.py b/examples/dfp/v201411/report_service/run_reach_report.py index 747c6893..b3b86285 100755 --- a/examples/dfp/v201411/report_service/run_reach_report.py +++ b/examples/dfp/v201411/report_service/run_reach_report.py @@ -16,8 +16,6 @@ """This code example runs a reach report.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201411/report_service/run_report_with_custom_fields.py b/examples/dfp/v201411/report_service/run_report_with_custom_fields.py index 2abb3f69..1e4c17f5 100755 --- a/examples/dfp/v201411/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201411/report_service/run_report_with_custom_fields.py @@ -18,8 +18,6 @@ items of an order. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201411/report_service/run_sales_report.py b/examples/dfp/v201411/report_service/run_sales_report.py index f77c2ea0..d4265342 100755 --- a/examples/dfp/v201411/report_service/run_sales_report.py +++ b/examples/dfp/v201411/report_service/run_sales_report.py @@ -17,8 +17,6 @@ """This code example runs a report equal to the "Sales by salespersons report." """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py index adc975fb..b785813a 100755 --- a/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -19,8 +19,6 @@ This feature is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py index e57a1aba..6b37b047 100755 --- a/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -20,8 +20,6 @@ is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py index 949c5678..faa6c3ca 100755 --- a/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py @@ -19,8 +19,6 @@ This feature is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/team_service/create_teams.py b/examples/dfp/v201411/team_service/create_teams.py index 36d32532..c6e22117 100755 --- a/examples/dfp/v201411/team_service/create_teams.py +++ b/examples/dfp/v201411/team_service/create_teams.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.createTeams """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201411/team_service/get_all_teams.py b/examples/dfp/v201411/team_service/get_all_teams.py index cd91f0a4..e174ec6b 100755 --- a/examples/dfp/v201411/team_service/get_all_teams.py +++ b/examples/dfp/v201411/team_service/get_all_teams.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/team_service/get_teams_by_statement.py b/examples/dfp/v201411/team_service/get_teams_by_statement.py index 4954a652..2d3a8fd2 100755 --- a/examples/dfp/v201411/team_service/get_teams_by_statement.py +++ b/examples/dfp/v201411/team_service/get_teams_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/team_service/update_teams.py b/examples/dfp/v201411/team_service/update_teams.py index 74d28901..33d2b2eb 100755 --- a/examples/dfp/v201411/team_service/update_teams.py +++ b/examples/dfp/v201411/team_service/update_teams.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement, TeamService.updateTeams """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_service/create_users.py b/examples/dfp/v201411/user_service/create_users.py index e898770f..2ee6dce5 100755 --- a/examples/dfp/v201411/user_service/create_users.py +++ b/examples/dfp/v201411/user_service/create_users.py @@ -18,8 +18,6 @@ To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_service/deactivate_users.py b/examples/dfp/v201411/user_service/deactivate_users.py index 69d3c83c..c45cea0f 100755 --- a/examples/dfp/v201411/user_service/deactivate_users.py +++ b/examples/dfp/v201411/user_service/deactivate_users.py @@ -20,8 +20,6 @@ request cannot deactivate itself. To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_service/get_all_roles.py b/examples/dfp/v201411/user_service/get_all_roles.py index 9584e3b3..55a9e2e0 100755 --- a/examples/dfp/v201411/user_service/get_all_roles.py +++ b/examples/dfp/v201411/user_service/get_all_roles.py @@ -19,8 +19,6 @@ This sample can be used to determine which role id is needed when getting and creating users.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_service/get_all_users.py b/examples/dfp/v201411/user_service/get_all_users.py index 0b57ca40..b79ce84d 100755 --- a/examples/dfp/v201411/user_service/get_all_users.py +++ b/examples/dfp/v201411/user_service/get_all_users.py @@ -16,8 +16,6 @@ """This code example gets all users. To create users, run create_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_service/get_current_user.py b/examples/dfp/v201411/user_service/get_current_user.py index 1ed7fe5e..92262660 100755 --- a/examples/dfp/v201411/user_service/get_current_user.py +++ b/examples/dfp/v201411/user_service/get_current_user.py @@ -16,8 +16,6 @@ """This code example gets the current user.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_service/get_users_by_statement.py b/examples/dfp/v201411/user_service/get_users_by_statement.py index f5342b9b..55f159a2 100755 --- a/examples/dfp/v201411/user_service/get_users_by_statement.py +++ b/examples/dfp/v201411/user_service/get_users_by_statement.py @@ -18,8 +18,6 @@ To create users, run create_user.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_service/update_users.py b/examples/dfp/v201411/user_service/update_users.py index 22b9c434..8347e77f 100755 --- a/examples/dfp/v201411/user_service/update_users.py +++ b/examples/dfp/v201411/user_service/update_users.py @@ -18,8 +18,6 @@ To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py index 67a6aedc..70b463e9 100755 --- a/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.createUserTeamAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py index b5d053db..13252a1d 100755 --- a/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.performUserTeamAssociationAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py index ecab0241..ea62a4c0 100755 --- a/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py index 11fd535a..0c125679 100755 --- a/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociation """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py index 6350425e..90397738 100755 --- a/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement -Tags: UserTeamAssociationService.updateUserTeamAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py index 24cc3520..7e9849ad 100755 --- a/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py @@ -19,11 +19,8 @@ To determine which workflow approval requests exist, run get_all_workflow_approval_requests.py. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement -Tags: WorkflowRequestService.performWorkflowRequestAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py index 6a36618a..41574fd4 100755 --- a/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py @@ -19,10 +19,8 @@ Workflow approval requests must be approved or rejected for a workflow to finish. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py index 4378f35f..84a58ef8 100755 --- a/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py @@ -19,10 +19,8 @@ Workflow external condition requests must be triggered or skipped for a workflow to finish. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py index 3a61978f..74966b98 100755 --- a/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -19,11 +19,8 @@ Workflow external condition requests must be triggered or skipped for a workflow to finish. To determine which proposals exist, run get_all_proposals.py. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement -Tags: WorkflowRequestService.performWorkflowRequestAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/activity_group_service/create_activity_groups.py b/examples/dfp/v201502/activity_group_service/create_activity_groups.py index fb039e32..f49ea294 100755 --- a/examples/dfp/v201502/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201502/activity_group_service/create_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.createActivityGroups """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py index eb8d380e..ae22d2e1 100755 --- a/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroupsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py index 1f68ec6f..b24019a9 100755 --- a/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroupsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/activity_group_service/update_activity_groups.py b/examples/dfp/v201502/activity_group_service/update_activity_groups.py index 1bfd692c..9853c93a 100755 --- a/examples/dfp/v201502/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201502/activity_group_service/update_activity_groups.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroup -Tags: ActivityGroupService.updateActivityGroups """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/activity_service/create_activities.py b/examples/dfp/v201502/activity_service/create_activities.py index 53504cc3..74dcfcb3 100755 --- a/examples/dfp/v201502/activity_service/create_activities.py +++ b/examples/dfp/v201502/activity_service/create_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.createActivities """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/activity_service/get_active_activities.py b/examples/dfp/v201502/activity_service/get_active_activities.py index 79dd965b..16b2b0a8 100755 --- a/examples/dfp/v201502/activity_service/get_active_activities.py +++ b/examples/dfp/v201502/activity_service/get_active_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/activity_service/get_all_activities.py b/examples/dfp/v201502/activity_service/get_all_activities.py index 288826a5..2e1e37a7 100755 --- a/examples/dfp/v201502/activity_service/get_all_activities.py +++ b/examples/dfp/v201502/activity_service/get_all_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/activity_service/update_activities.py b/examples/dfp/v201502/activity_service/update_activities.py index bcfe6a08..71afa07f 100755 --- a/examples/dfp/v201502/activity_service/update_activities.py +++ b/examples/dfp/v201502/activity_service/update_activities.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.updateActivities - ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/audience_segment_service/create_audience_segments.py b/examples/dfp/v201502/audience_segment_service/create_audience_segments.py index 1713f998..17c97a4f 100755 --- a/examples/dfp/v201502/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201502/audience_segment_service/create_audience_segments.py @@ -16,8 +16,6 @@ """This example creates a new rule based first party audience segment.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -52,8 +50,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): custom_criteria = [ { 'xsi_type': 'CustomCriteria', - 'keyId': CUSTOM_TARGETING_KEY_ID, - 'valueIds': [CUSTOM_TARGETING_VALUE_ID], + 'keyId': custom_targeting_key_id, + 'valueIds': [custom_targeting_value_id], 'operator': 'IS' } ] diff --git a/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py index 63a910b0..758479ed 100755 --- a/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py @@ -19,8 +19,6 @@ To create audience segments, run create_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py index 97b0ae67..f2450b93 100755 --- a/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py @@ -19,8 +19,6 @@ To create first party audience segments, run create_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py index 8f8bfe6c..4357cb3c 100755 --- a/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py @@ -20,8 +20,6 @@ get_first_party_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/audience_segment_service/update_audience_segments.py b/examples/dfp/v201502/audience_segment_service/update_audience_segments.py index 39a5e03e..e1381a79 100755 --- a/examples/dfp/v201502/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201502/audience_segment_service/update_audience_segments.py @@ -19,8 +19,6 @@ To determine which audience segments exist, run get_all_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/base_rate_service/create_product_base_rates.py b/examples/dfp/v201502/base_rate_service/create_product_base_rates.py index f6e45ecf..63bb3180 100755 --- a/examples/dfp/v201502/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201502/base_rate_service/create_product_base_rates.py @@ -18,10 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.createBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py index aca22d0b..9ad21ef1 100755 --- a/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py @@ -18,10 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.createBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/base_rate_service/get_all_base_rates.py b/examples/dfp/v201502/base_rate_service/get_all_base_rates.py index 5ef40bbe..48d4aab9 100755 --- a/examples/dfp/v201502/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201502/base_rate_service/get_all_base_rates.py @@ -20,10 +20,8 @@ To create product template base rates, run create_product_template_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py index 59792818..db42f70e 100755 --- a/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py @@ -20,10 +20,8 @@ To create product template base rates, run create_product_template_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/base_rate_service/update_base_rates.py b/examples/dfp/v201502/base_rate_service/update_base_rates.py index d93d18ca..5444f278 100755 --- a/examples/dfp/v201502/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201502/base_rate_service/update_base_rates.py @@ -18,11 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement -Tags: BaseRateService.updateBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/company_service/create_companies.py b/examples/dfp/v201502/company_service/create_companies.py index a59a1b69..4bfd25c3 100755 --- a/examples/dfp/v201502/company_service/create_companies.py +++ b/examples/dfp/v201502/company_service/create_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.createCompanies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/company_service/get_advertisers.py b/examples/dfp/v201502/company_service/get_advertisers.py index 8b2568dd..ead587fc 100755 --- a/examples/dfp/v201502/company_service/get_advertisers.py +++ b/examples/dfp/v201502/company_service/get_advertisers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.getCompaniesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/company_service/get_all_companies.py b/examples/dfp/v201502/company_service/get_all_companies.py index b9405658..fcf47ac6 100755 --- a/examples/dfp/v201502/company_service/get_all_companies.py +++ b/examples/dfp/v201502/company_service/get_all_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.getCompaniesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/company_service/update_companies.py b/examples/dfp/v201502/company_service/update_companies.py index cd45fa69..1799b0f8 100755 --- a/examples/dfp/v201502/company_service/update_companies.py +++ b/examples/dfp/v201502/company_service/update_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.updateCompanies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/contact_service/create_contacts.py b/examples/dfp/v201502/contact_service/create_contacts.py index 081bf44e..892ae9e5 100755 --- a/examples/dfp/v201502/contact_service/create_contacts.py +++ b/examples/dfp/v201502/contact_service/create_contacts.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.createContacts """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/contact_service/get_all_contacts.py b/examples/dfp/v201502/contact_service/get_all_contacts.py index a00eb9e9..352849db 100755 --- a/examples/dfp/v201502/contact_service/get_all_contacts.py +++ b/examples/dfp/v201502/contact_service/get_all_contacts.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/contact_service/get_uninvited_contacts.py b/examples/dfp/v201502/contact_service/get_uninvited_contacts.py index 91ffd159..887c1ef0 100755 --- a/examples/dfp/v201502/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201502/contact_service/get_uninvited_contacts.py @@ -23,10 +23,7 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/contact_service/update_contacts.py b/examples/dfp/v201502/contact_service/update_contacts.py index c8d7241e..de3054bf 100755 --- a/examples/dfp/v201502/contact_service/update_contacts.py +++ b/examples/dfp/v201502/contact_service/update_contacts.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.updateContacts - ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 9debd246..d14fb793 100755 --- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -26,11 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 25d014cb..b929bac6 100755 --- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -26,12 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement - ContentMetadataKeyHierarchyService.perfomContentMetadataKeyHierarchyAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 002eeb89..aba4c9cd 100755 --- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index d2b37dfa..ed70ad9e 100755 --- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -26,12 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement - ContentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/content_service/get_all_content.py b/examples/dfp/v201502/content_service/get_all_content.py index 5b17ca8e..c22cf0bb 100755 --- a/examples/dfp/v201502/content_service/get_all_content.py +++ b/examples/dfp/v201502/content_service/get_all_content.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentService.getContentByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/content_service/get_content_by_category.py b/examples/dfp/v201502/content_service/get_content_by_category.py index 34d6a713..d3792e1b 100755 --- a/examples/dfp/v201502/content_service/get_content_by_category.py +++ b/examples/dfp/v201502/content_service/get_content_by_category.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentService.getContentByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_service/create_creative_from_template.py b/examples/dfp/v201502/creative_service/create_creative_from_template.py index 6cf77f5c..f44b5b4c 100755 --- a/examples/dfp/v201502/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201502/creative_service/create_creative_from_template.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreative """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os @@ -90,7 +87,7 @@ def main(client, advertiser_id): } # Call service to create the creative. - creative = creative_service.createCreative(creative) + creative = creative_service.createCreatives([creative])[0] # Display results. print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' diff --git a/examples/dfp/v201502/creative_service/create_creatives.py b/examples/dfp/v201502/creative_service/create_creatives.py index 1e7183fb..119301e7 100755 --- a/examples/dfp/v201502/creative_service/create_creatives.py +++ b/examples/dfp/v201502/creative_service/create_creatives.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreatives """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os diff --git a/examples/dfp/v201502/creative_service/create_custom_creative.py b/examples/dfp/v201502/creative_service/create_custom_creative.py index dcae98c8..03ae4550 100755 --- a/examples/dfp/v201502/creative_service/create_custom_creative.py +++ b/examples/dfp/v201502/creative_service/create_custom_creative.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreative """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os diff --git a/examples/dfp/v201502/creative_service/get_all_creatives.py b/examples/dfp/v201502/creative_service/get_all_creatives.py index 436e48d7..a6c3c252 100755 --- a/examples/dfp/v201502/creative_service/get_all_creatives.py +++ b/examples/dfp/v201502/creative_service/get_all_creatives.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_service/get_creatives_by_statement.py b/examples/dfp/v201502/creative_service/get_creatives_by_statement.py index db2bd3b2..6cc1fc23 100755 --- a/examples/dfp/v201502/creative_service/get_creatives_by_statement.py +++ b/examples/dfp/v201502/creative_service/get_creatives_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_service/update_creatives.py b/examples/dfp/v201502/creative_service/update_creatives.py index 1dab62ad..7429fd38 100755 --- a/examples/dfp/v201502/creative_service/update_creatives.py +++ b/examples/dfp/v201502/creative_service/update_creatives.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.updateCreatives - CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py index dc423cc7..3b3d3bcb 100755 --- a/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: LineItemCreativeAssociationService.createLineItemCreativeAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_set_service/create_creative_set.py b/examples/dfp/v201502/creative_set_service/create_creative_set.py index 9fcb5afb..106005d7 100755 --- a/examples/dfp/v201502/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201502/creative_set_service/create_creative_set.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.createCreativeSet """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py index 930506af..e6b6e42b 100755 --- a/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py index 010243e1..285307b3 100755 --- a/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_set_service/update_creative_set.py b/examples/dfp/v201502/creative_set_service/update_creative_set.py index 0c34cb80..f9da7295 100755 --- a/examples/dfp/v201502/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201502/creative_set_service/update_creative_set.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.updateCreativeSet - CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py index 7c3a5275..7fd2e471 100755 --- a/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeTemplateService.getCreativeTemplatesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py index f799e7c4..05cc10be 100755 --- a/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py +++ b/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeTemplateService.getCreativeTemplatesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py index 36cba79c..61bc793f 100755 --- a/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.createCreativeWrappers """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py index 8c59c06d..ff051cca 100755 --- a/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrapperByStatement -Tags: CreativeWrapperService.performCreativeWrapperAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py index 453504d1..72c98063 100755 --- a/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py index 7defc209..cdd86677 100755 --- a/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py index 04235d0a..177ef746 100755 --- a/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement -Tags: CreativeWrapperService.updateCreativeWrappers """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_field_service/create_custom_field_options.py b/examples/dfp/v201502/custom_field_service/create_custom_field_options.py index a73c9a8a..b084ff2e 100755 --- a/examples/dfp/v201502/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201502/custom_field_service/create_custom_field_options.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.createCustomFieldOptions """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_field_service/create_custom_fields.py b/examples/dfp/v201502/custom_field_service/create_custom_fields.py index f4f6dcb2..d3aa0251 100755 --- a/examples/dfp/v201502/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201502/custom_field_service/create_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.createCustomFields """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py index a3eeeb65..46ee7896 100755 --- a/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement -Tags: CustomFieldService.performCustomFieldAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py index 8a23dfd7..0d305f70 100755 --- a/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py index 4413453a..51e26215 100755 --- a/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py index 6ad309d0..e6dae9d0 100755 --- a/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement - LineItemService.getLineItemsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_field_service/update_custom_fields.py b/examples/dfp/v201502/custom_field_service/update_custom_fields.py index 4259b204..db401b1f 100755 --- a/examples/dfp/v201502/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201502/custom_field_service/update_custom_fields.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.updateCustomFields - CustomFieldService.getCustomFieldByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py index 11c583c6..8a7c5c1c 100755 --- a/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.createCustomTargetingKeys - CustomTargetingService.createCustomTargetingValues """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py index 6523e417..c5196526 100755 --- a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.getCustomTargetingKeysByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py index cece48a7..f3aee029 100755 --- a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.getCustomTargetingValuesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index f1751cb1..94cfa891 100755 --- a/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -19,8 +19,6 @@ To create custom targeting keys and values, run create_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py index 07b44b4f..0812eb42 100755 --- a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py @@ -19,8 +19,6 @@ To create custom targeting keys, run create_custom_targeting_keys_and_values.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py index 112a48b3..af3bce4e 100755 --- a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ b/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py @@ -21,8 +21,6 @@ create_custom_targeting_keys_and_values.py. To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py index f23fae91..365f935d 100755 --- a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py @@ -19,8 +19,6 @@ To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py index 2d705319..e4e37a72 100755 --- a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py @@ -20,8 +20,6 @@ To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py index 996b5628..f8928d03 100755 --- a/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py @@ -19,10 +19,8 @@ To determine which exchange rates exist, run get_all_exchange_rates.py. -Tags: ExchangeRateService.createExchangeRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py index 6002f471..6b311fdd 100755 --- a/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py index c2ff187c..3eb23cc6 100755 --- a/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py index b390da34..a4ef9b74 100755 --- a/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/forecast_service/get_availability_forecast.py b/examples/dfp/v201502/forecast_service/get_availability_forecast.py index 3186d647..a79d18a4 100755 --- a/examples/dfp/v201502/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201502/forecast_service/get_availability_forecast.py @@ -21,11 +21,8 @@ targeting (in addition to targeting the whole network). See create_line_items.py for an example of how to create more complex targeting. -Tags: ForecastService.getAvailabilityForecast -Tags: NetworkService.getCurrentNetwork """ -__author__ = 'Nicholas Chen' from datetime import date diff --git a/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py index 16ccd4cd..98c0c8db 100755 --- a/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py @@ -18,10 +18,8 @@ To determine which line items exist, run get_all_line_items.py. -Tags: ForecastService.getAvailabilityForecastById """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py index 877be0ec..c2c51d26 100755 --- a/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py @@ -18,10 +18,8 @@ To determine which line items exist, run get_all_line_items.py. -Tags: ForecastService.getDeliveryForecastByIds """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/inventory_service/archive_ad_units.py b/examples/dfp/v201502/inventory_service/archive_ad_units.py index eac46431..6a333d8c 100755 --- a/examples/dfp/v201502/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201502/inventory_service/archive_ad_units.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/inventory_service/create_ad_units.py b/examples/dfp/v201502/inventory_service/create_ad_units.py index 6aaab080..f29dbd2a 100755 --- a/examples/dfp/v201502/inventory_service/create_ad_units.py +++ b/examples/dfp/v201502/inventory_service/create_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.createAdUnits """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py index 4863f219..f797196e 100755 --- a/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py index a6a0e0c0..84283c22 100755 --- a/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitSizesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/inventory_service/get_all_ad_units.py b/examples/dfp/v201502/inventory_service/get_all_ad_units.py index a18169f7..d1063d32 100755 --- a/examples/dfp/v201502/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201502/inventory_service/get_all_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py index 086380a7..def1bf83 100755 --- a/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/inventory_service/update_ad_units.py b/examples/dfp/v201502/inventory_service/update_ad_units.py index f37e90d7..c0ee45ea 100755 --- a/examples/dfp/v201502/inventory_service/update_ad_units.py +++ b/examples/dfp/v201502/inventory_service/update_ad_units.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnit -Tags: InventoryService.updateAdUnits """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/label_service/create_labels.py b/examples/dfp/v201502/label_service/create_labels.py index 8d8d80d6..44a5a5c5 100755 --- a/examples/dfp/v201502/label_service/create_labels.py +++ b/examples/dfp/v201502/label_service/create_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/label_service/deactivate_labels.py b/examples/dfp/v201502/label_service/deactivate_labels.py index 91529f52..0676f221 100755 --- a/examples/dfp/v201502/label_service/deactivate_labels.py +++ b/examples/dfp/v201502/label_service/deactivate_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/label_service/get_all_labels.py b/examples/dfp/v201502/label_service/get_all_labels.py index 97290f58..88f5af86 100755 --- a/examples/dfp/v201502/label_service/get_all_labels.py +++ b/examples/dfp/v201502/label_service/get_all_labels.py @@ -19,8 +19,6 @@ To create labels, run create_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/label_service/get_labels_by_statement.py b/examples/dfp/v201502/label_service/get_labels_by_statement.py index ffba7047..d088c5c0 100755 --- a/examples/dfp/v201502/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201502/label_service/get_labels_by_statement.py @@ -20,8 +20,6 @@ premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/label_service/update_labels.py b/examples/dfp/v201502/label_service/update_labels.py index b4a205ed..43e64226 100755 --- a/examples/dfp/v201502/label_service/update_labels.py +++ b/examples/dfp/v201502/label_service/update_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/line_item_creative_association_service/create_licas.py b/examples/dfp/v201502/line_item_creative_association_service/create_licas.py index 3229a437..b195e2a2 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201502/line_item_creative_association_service/create_licas.py @@ -19,8 +19,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py index f57ce3cd..bb53aa1e 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py @@ -18,8 +18,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py index 06e972a6..190533cb 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py @@ -19,8 +19,6 @@ To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py index 980424be..615129f0 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py @@ -19,8 +19,6 @@ To create LICAs, run create_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/line_item_creative_association_service/update_licas.py b/examples/dfp/v201502/line_item_creative_association_service/update_licas.py index 404006a7..87437391 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201502/line_item_creative_association_service/update_licas.py @@ -19,8 +19,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/line_item_service/activate_line_items.py b/examples/dfp/v201502/line_item_service/activate_line_items.py index da82d8e9..1ddc961b 100755 --- a/examples/dfp/v201502/line_item_service/activate_line_items.py +++ b/examples/dfp/v201502/line_item_service/activate_line_items.py @@ -22,8 +22,6 @@ create_licas.py. To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/line_item_service/create_line_items.py b/examples/dfp/v201502/line_item_service/create_line_items.py index 9ee57e26..56e84548 100755 --- a/examples/dfp/v201502/line_item_service/create_line_items.py +++ b/examples/dfp/v201502/line_item_service/create_line_items.py @@ -20,8 +20,6 @@ which orders exist, run get_all_orders.py. To determine which placements exist, run get_all_placements.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date import uuid diff --git a/examples/dfp/v201502/line_item_service/create_video_line_item.py b/examples/dfp/v201502/line_item_service/create_video_line_item.py index 827ff738..0af61849 100755 --- a/examples/dfp/v201502/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201502/line_item_service/create_video_line_item.py @@ -22,8 +22,6 @@ create_video_ad_unit.py. To create criteria for categories, run create_custom_targeting_keys_and_values.py""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date import uuid diff --git a/examples/dfp/v201502/line_item_service/get_all_line_items.py b/examples/dfp/v201502/line_item_service/get_all_line_items.py index 18cf1895..4607acc9 100755 --- a/examples/dfp/v201502/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201502/line_item_service/get_all_line_items.py @@ -18,8 +18,6 @@ To create line items, run create_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py index c46929fd..ce964e36 100755 --- a/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py +++ b/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py @@ -14,13 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets all line items that need creatives for the given -order. +"""This code example gets all line items that need creatives for an order. -To create line items, run create_line_items.py.""" +To create line items, run create_line_items.py. +""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -48,8 +46,8 @@ def main(client, order_id): 'value': 'true' } }] - query = 'WHERE orderId = :orderId AND ' - 'isMissingCreatives = :isMissingCreatives' + query = ('WHERE orderId = :orderId AND ' + 'isMissingCreatives = :isMissingCreatives') statement = dfp.FilterStatement(query, values) while True: diff --git a/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py index 9301c8f5..59a2d9a2 100755 --- a/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py @@ -18,8 +18,6 @@ To create line items, run create_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import datetime diff --git a/examples/dfp/v201502/line_item_service/target_custom_criteria.py b/examples/dfp/v201502/line_item_service/target_custom_criteria.py index 46ad56d6..d835bcac 100755 --- a/examples/dfp/v201502/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201502/line_item_service/target_custom_criteria.py @@ -20,8 +20,6 @@ which custom targeting keys and values exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import pprint diff --git a/examples/dfp/v201502/line_item_service/update_line_items.py b/examples/dfp/v201502/line_item_service/update_line_items.py index fd7af4da..fd864fd8 100755 --- a/examples/dfp/v201502/line_item_service/update_line_items.py +++ b/examples/dfp/v201502/line_item_service/update_line_items.py @@ -18,8 +18,6 @@ To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/network_service/get_all_networks.py b/examples/dfp/v201502/network_service/get_all_networks.py index cc8c6236..4a8e9ad8 100755 --- a/examples/dfp/v201502/network_service/get_all_networks.py +++ b/examples/dfp/v201502/network_service/get_all_networks.py @@ -19,8 +19,6 @@ A networkCode should be left out for this request.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/network_service/get_current_network.py b/examples/dfp/v201502/network_service/get_current_network.py index ad37d3f8..98eb0d2c 100755 --- a/examples/dfp/v201502/network_service/get_current_network.py +++ b/examples/dfp/v201502/network_service/get_current_network.py @@ -16,8 +16,6 @@ """This example gets the current network that you can make requests against.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/network_service/make_test_network.py b/examples/dfp/v201502/network_service/make_test_network.py index 54560848..c5b32df2 100755 --- a/examples/dfp/v201502/network_service/make_test_network.py +++ b/examples/dfp/v201502/network_service/make_test_network.py @@ -27,8 +27,6 @@ https://dfp-playground.appspot.com """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/order_service/approve_orders.py b/examples/dfp/v201502/order_service/approve_orders.py index 25461c20..a63631b8 100755 --- a/examples/dfp/v201502/order_service/approve_orders.py +++ b/examples/dfp/v201502/order_service/approve_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import datetime diff --git a/examples/dfp/v201502/order_service/create_orders.py b/examples/dfp/v201502/order_service/create_orders.py index 2bd42259..d20ba034 100755 --- a/examples/dfp/v201502/order_service/create_orders.py +++ b/examples/dfp/v201502/order_service/create_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/order_service/get_all_orders.py b/examples/dfp/v201502/order_service/get_all_orders.py index b38eaf6c..ee396ed7 100755 --- a/examples/dfp/v201502/order_service/get_all_orders.py +++ b/examples/dfp/v201502/order_service/get_all_orders.py @@ -19,8 +19,6 @@ To create orders, run create_orders.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/order_service/get_orders_by_statement.py b/examples/dfp/v201502/order_service/get_orders_by_statement.py index ee3c96f8..3952fcf1 100755 --- a/examples/dfp/v201502/order_service/get_orders_by_statement.py +++ b/examples/dfp/v201502/order_service/get_orders_by_statement.py @@ -18,8 +18,6 @@ To create orders, run create_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/order_service/update_orders.py b/examples/dfp/v201502/order_service/update_orders.py index 7512049c..03b19a96 100755 --- a/examples/dfp/v201502/order_service/update_orders.py +++ b/examples/dfp/v201502/order_service/update_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/placement_service/create_placements.py b/examples/dfp/v201502/placement_service/create_placements.py index e09a5c76..3729afc7 100755 --- a/examples/dfp/v201502/placement_service/create_placements.py +++ b/examples/dfp/v201502/placement_service/create_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/placement_service/deactivate_placements.py b/examples/dfp/v201502/placement_service/deactivate_placements.py index 9f888b11..a14c09a4 100755 --- a/examples/dfp/v201502/placement_service/deactivate_placements.py +++ b/examples/dfp/v201502/placement_service/deactivate_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/placement_service/get_all_placements.py b/examples/dfp/v201502/placement_service/get_all_placements.py index adfbde6c..a14e2959 100755 --- a/examples/dfp/v201502/placement_service/get_all_placements.py +++ b/examples/dfp/v201502/placement_service/get_all_placements.py @@ -19,8 +19,6 @@ To create placements, run create_placement.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/placement_service/get_placements_by_statement.py b/examples/dfp/v201502/placement_service/get_placements_by_statement.py index 8f501a17..44ce4967 100755 --- a/examples/dfp/v201502/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201502/placement_service/get_placements_by_statement.py @@ -19,8 +19,6 @@ To create a placement, run create_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/placement_service/update_placements.py b/examples/dfp/v201502/placement_service/update_placements.py index ada64131..ea5b13f4 100755 --- a/examples/dfp/v201502/placement_service/update_placements.py +++ b/examples/dfp/v201502/placement_service/update_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/premium_rate_service/create_premium_rates.py b/examples/dfp/v201502/premium_rate_service/create_premium_rates.py index b4f59725..22654560 100755 --- a/examples/dfp/v201502/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201502/premium_rate_service/create_premium_rates.py @@ -19,9 +19,6 @@ To determine which premium_rates exist, run get_all_premium_rates.py. """ -__author__ = 'Nicholas Chen' - - # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py index 54443214..1c530821 100755 --- a/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py @@ -18,10 +18,8 @@ To create premium rates, run create_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py index e21f2572..2caa45ed 100755 --- a/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py @@ -18,10 +18,8 @@ To create premium rates, run create_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/premium_rate_service/update_premium_rates.py b/examples/dfp/v201502/premium_rate_service/update_premium_rates.py index e2cc88d3..c2c259a7 100755 --- a/examples/dfp/v201502/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201502/premium_rate_service/update_premium_rates.py @@ -18,11 +18,8 @@ To determine which premium rates exist, run get_all_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement -Tags: PremiumRateService.updatePremiumRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/product_service/get_all_products.py b/examples/dfp/v201502/product_service/get_all_products.py index 37c64506..20e976c8 100755 --- a/examples/dfp/v201502/product_service/get_all_products.py +++ b/examples/dfp/v201502/product_service/get_all_products.py @@ -18,10 +18,8 @@ Products are created automatically from product templates. -Tags: ProductService.getProductsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/product_service/get_products_for_product_template.py b/examples/dfp/v201502/product_service/get_products_for_product_template.py index e21bb3f8..87eb4e43 100755 --- a/examples/dfp/v201502/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201502/product_service/get_products_for_product_template.py @@ -16,10 +16,8 @@ """This example gets all products created from a product template. -Tags: ProductService.getProductsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/product_service/update_products.py b/examples/dfp/v201502/product_service/update_products.py index a4f38527..fd099403 100755 --- a/examples/dfp/v201502/product_service/update_products.py +++ b/examples/dfp/v201502/product_service/update_products.py @@ -18,11 +18,8 @@ To determine which products exist, run get_all_products.py. -Tags: ProductService.getProductsByStatement -Tags: ProductService.updateProducts """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/product_template_service/activate_product_templates.py b/examples/dfp/v201502/product_template_service/activate_product_templates.py index a79cc2a9..647ddb63 100755 --- a/examples/dfp/v201502/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201502/product_template_service/activate_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement -Tags: ProductTemplateService.performProductTemplateAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/product_template_service/create_product_templates.py b/examples/dfp/v201502/product_template_service/create_product_templates.py index 5d761752..163adf63 100755 --- a/examples/dfp/v201502/product_template_service/create_product_templates.py +++ b/examples/dfp/v201502/product_template_service/create_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.createProductTemplates -Tags: NetworkService.getCurrentNetwork """ -__author__ = 'Nicholas Chen' import uuid diff --git a/examples/dfp/v201502/product_template_service/get_all_product_templates.py b/examples/dfp/v201502/product_template_service/get_all_product_templates.py index 4e7f1e99..cc71f5b6 100755 --- a/examples/dfp/v201502/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201502/product_template_service/get_all_product_templates.py @@ -18,10 +18,8 @@ To create product templates, run create_product_template_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py index 25011c46..7fb30b78 100755 --- a/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py @@ -16,10 +16,8 @@ """This code example gets all sponsorship product templates. -Tags: ProductTemplateService.getProductTemplatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/product_template_service/update_product_templates.py b/examples/dfp/v201502/product_template_service/update_product_templates.py index 00f10b12..eb3e42ec 100755 --- a/examples/dfp/v201502/product_template_service/update_product_templates.py +++ b/examples/dfp/v201502/product_template_service/update_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement -Tags: ProductTemplateService.updateProductTemplates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py index 1b586c2d..62ea64c5 100755 --- a/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py @@ -20,7 +20,6 @@ get_all_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py index 1449ce52..34bed36e 100755 --- a/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py @@ -21,7 +21,6 @@ get_all_proposals.py. """ -__author__ = 'Nicholas Chen' from datetime import date import uuid diff --git a/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py index a1e8ae70..79d6a8a8 100755 --- a/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py @@ -19,7 +19,6 @@ To create proposal line items, run create_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 5206b61c..df8d3aa4 100755 --- a/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -13,12 +13,10 @@ # 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 code example gets all proposal line items that belong to a proposal. To create proposal line items, run create_proposal_line_items.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,8 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201502') + 'ProposalLineItemService', + version='v201502') # Create statement object to only select proposal line items belonging to a # given proposal. @@ -53,11 +52,11 @@ def main(client, proposal_id): # Display results. for idx, proposal_line_item in enumerate(response['results'], start=statement.offset): - print ('%s) Line item with id \'%s\', belonging to proposal id \'%s\', ' - 'and named \'%s\' was found.' % ( - idx, proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) + print( + '%s) Proposal line item with id \'%s\', belonging to proposal id ' + '\'%s\', and named \'%s\' was found.' % ( + idx, proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py index 7bfbab25..48111594 100755 --- a/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py @@ -20,7 +20,6 @@ run get_all_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/proposal_service/create_proposals.py b/examples/dfp/v201502/proposal_service/create_proposals.py index dab9f002..a2bcfd9c 100755 --- a/examples/dfp/v201502/proposal_service/create_proposals.py +++ b/examples/dfp/v201502/proposal_service/create_proposals.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' import uuid diff --git a/examples/dfp/v201502/proposal_service/get_all_proposals.py b/examples/dfp/v201502/proposal_service/get_all_proposals.py index 6bbf66ef..fb45be8c 100755 --- a/examples/dfp/v201502/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201502/proposal_service/get_all_proposals.py @@ -19,7 +19,6 @@ To create proposals, run create_proposals.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py index c203af87..27fc2466 100755 --- a/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py @@ -18,7 +18,6 @@ To create proposals, run create_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py index d24f8938..977101bb 100755 --- a/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/proposal_service/update_proposals.py b/examples/dfp/v201502/proposal_service/update_proposals.py index 2394038c..dc82ac2c 100755 --- a/examples/dfp/v201502/proposal_service/update_proposals.py +++ b/examples/dfp/v201502/proposal_service/update_proposals.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py index fd848da3..e3d5c279 100755 --- a/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py @@ -16,8 +16,6 @@ """This example fetches data from PQL tables and creates match table files.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py index e4679714..2501536c 100755 --- a/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py @@ -23,8 +23,6 @@ https://developers.google.com/doubleclick-publishers/docs/reference/v201502/PublisherQueryLanguageService """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py index 37980e87..86e5c23d 100755 --- a/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py @@ -16,8 +16,6 @@ """This example gets all line items with names starting with 'line item'.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py index a541c1db..d0b16453 100755 --- a/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py @@ -16,10 +16,8 @@ """This code example gets all rate cards. -Tags: RateCardService.getRateCardsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py index 4f69f5e7..26a680cb 100755 --- a/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py @@ -16,10 +16,8 @@ """This example gets all rate cards that have a currency in US dollars. -Tags: RateCardService.getRateCardsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/report_service/run_delivery_report.py b/examples/dfp/v201502/report_service/run_delivery_report.py index 205d5dc0..3bb28979 100755 --- a/examples/dfp/v201502/report_service/run_delivery_report.py +++ b/examples/dfp/v201502/report_service/run_delivery_report.py @@ -18,8 +18,6 @@ website with additional attributes and can filter to include just one order. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201502/report_service/run_inventory_report.py b/examples/dfp/v201502/report_service/run_inventory_report.py index ed743e81..89e0dfbc 100755 --- a/examples/dfp/v201502/report_service/run_inventory_report.py +++ b/examples/dfp/v201502/report_service/run_inventory_report.py @@ -18,8 +18,6 @@ DFP website. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201502/report_service/run_reach_report.py b/examples/dfp/v201502/report_service/run_reach_report.py index 1d26baa3..4673960b 100755 --- a/examples/dfp/v201502/report_service/run_reach_report.py +++ b/examples/dfp/v201502/report_service/run_reach_report.py @@ -16,8 +16,6 @@ """This code example runs a reach report.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201502/report_service/run_report_with_custom_fields.py b/examples/dfp/v201502/report_service/run_report_with_custom_fields.py index 21da37d1..d1a3519b 100755 --- a/examples/dfp/v201502/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201502/report_service/run_report_with_custom_fields.py @@ -18,8 +18,6 @@ items of an order. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201502/report_service/run_sales_report.py b/examples/dfp/v201502/report_service/run_sales_report.py index 4146cb51..7e3c7a60 100755 --- a/examples/dfp/v201502/report_service/run_sales_report.py +++ b/examples/dfp/v201502/report_service/run_sales_report.py @@ -17,8 +17,6 @@ """This code example runs a report equal to the "Sales by salespersons report." """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py index b73964cc..527b6a57 100755 --- a/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -19,8 +19,6 @@ This feature is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py index 46ae8e49..5c6c6630 100755 --- a/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -20,8 +20,6 @@ is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py index b6bf16df..09a77274 100755 --- a/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py @@ -19,8 +19,6 @@ This feature is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/team_service/create_teams.py b/examples/dfp/v201502/team_service/create_teams.py index 53f6e12a..e8f4be8e 100755 --- a/examples/dfp/v201502/team_service/create_teams.py +++ b/examples/dfp/v201502/team_service/create_teams.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.createTeams """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201502/team_service/get_all_teams.py b/examples/dfp/v201502/team_service/get_all_teams.py index 2ca82f3f..89694fb9 100755 --- a/examples/dfp/v201502/team_service/get_all_teams.py +++ b/examples/dfp/v201502/team_service/get_all_teams.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/team_service/get_teams_by_statement.py b/examples/dfp/v201502/team_service/get_teams_by_statement.py index db9c9e60..495151bf 100755 --- a/examples/dfp/v201502/team_service/get_teams_by_statement.py +++ b/examples/dfp/v201502/team_service/get_teams_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/team_service/update_teams.py b/examples/dfp/v201502/team_service/update_teams.py index a38c104a..15377e5b 100755 --- a/examples/dfp/v201502/team_service/update_teams.py +++ b/examples/dfp/v201502/team_service/update_teams.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement, TeamService.updateTeams """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_service/create_users.py b/examples/dfp/v201502/user_service/create_users.py index 055270a9..7a51a267 100755 --- a/examples/dfp/v201502/user_service/create_users.py +++ b/examples/dfp/v201502/user_service/create_users.py @@ -18,8 +18,6 @@ To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_service/deactivate_users.py b/examples/dfp/v201502/user_service/deactivate_users.py index a0bbbd96..6d009181 100755 --- a/examples/dfp/v201502/user_service/deactivate_users.py +++ b/examples/dfp/v201502/user_service/deactivate_users.py @@ -20,8 +20,6 @@ request cannot deactivate itself. To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_service/get_all_roles.py b/examples/dfp/v201502/user_service/get_all_roles.py index d9bced06..baed0111 100755 --- a/examples/dfp/v201502/user_service/get_all_roles.py +++ b/examples/dfp/v201502/user_service/get_all_roles.py @@ -19,8 +19,6 @@ This sample can be used to determine which role id is needed when getting and creating users.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_service/get_all_users.py b/examples/dfp/v201502/user_service/get_all_users.py index 012601e8..107efd22 100755 --- a/examples/dfp/v201502/user_service/get_all_users.py +++ b/examples/dfp/v201502/user_service/get_all_users.py @@ -16,8 +16,6 @@ """This code example gets all users. To create users, run create_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_service/get_current_user.py b/examples/dfp/v201502/user_service/get_current_user.py index a5739c0e..bec07a58 100755 --- a/examples/dfp/v201502/user_service/get_current_user.py +++ b/examples/dfp/v201502/user_service/get_current_user.py @@ -16,8 +16,6 @@ """This code example gets the current user.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_service/get_users_by_statement.py b/examples/dfp/v201502/user_service/get_users_by_statement.py index 48461c51..176166f2 100755 --- a/examples/dfp/v201502/user_service/get_users_by_statement.py +++ b/examples/dfp/v201502/user_service/get_users_by_statement.py @@ -18,8 +18,6 @@ To create users, run create_user.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_service/update_users.py b/examples/dfp/v201502/user_service/update_users.py index 08317efc..5fba527c 100755 --- a/examples/dfp/v201502/user_service/update_users.py +++ b/examples/dfp/v201502/user_service/update_users.py @@ -18,8 +18,6 @@ To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py index 724e2345..95169a34 100755 --- a/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.createUserTeamAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py index ee27770b..76ebfdd0 100755 --- a/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.performUserTeamAssociationAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py index e2b9c816..2f07e7e3 100755 --- a/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py index ed2c7015..a9a6e397 100755 --- a/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociation """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py index d2b3f380..3101c2ee 100755 --- a/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement -Tags: UserTeamAssociationService.updateUserTeamAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py index 99d68931..37b58706 100755 --- a/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py @@ -19,11 +19,8 @@ To determine which workflow approval requests exist, run get_all_workflow_approval_requests.py. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement -Tags: WorkflowRequestService.performWorkflowRequestAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py index 09da9783..50ba5376 100755 --- a/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py @@ -19,10 +19,8 @@ Workflow approval requests must be approved or rejected for a workflow to finish. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py index 3c839d83..d63103bf 100755 --- a/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py @@ -19,10 +19,8 @@ Workflow external condition requests must be triggered or skipped for a workflow to finish. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py index 0f4881af..4f2807c9 100755 --- a/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -19,11 +19,8 @@ Workflow external condition requests must be triggered or skipped for a workflow to finish. To determine which proposals exist, run get_all_proposals.py. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement -Tags: WorkflowRequestService.performWorkflowRequestAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/activity_group_service/create_activity_groups.py b/examples/dfp/v201505/activity_group_service/create_activity_groups.py index 2421c463..65358edd 100755 --- a/examples/dfp/v201505/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201505/activity_group_service/create_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.createActivityGroups """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201505/activity_group_service/get_active_activity_groups.py index 3bf1d009..61b317da 100755 --- a/examples/dfp/v201505/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201505/activity_group_service/get_active_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroupsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201505/activity_group_service/get_all_activity_groups.py index 43778b20..0a709e07 100755 --- a/examples/dfp/v201505/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201505/activity_group_service/get_all_activity_groups.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroupsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/activity_group_service/update_activity_groups.py b/examples/dfp/v201505/activity_group_service/update_activity_groups.py index 2b228e41..ceb9e994 100755 --- a/examples/dfp/v201505/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201505/activity_group_service/update_activity_groups.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroup -Tags: ActivityGroupService.updateActivityGroups """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/activity_service/create_activities.py b/examples/dfp/v201505/activity_service/create_activities.py index 9dc5e957..10d59362 100755 --- a/examples/dfp/v201505/activity_service/create_activities.py +++ b/examples/dfp/v201505/activity_service/create_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.createActivities """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/activity_service/get_active_activities.py b/examples/dfp/v201505/activity_service/get_active_activities.py index 0fa25b1d..bf94bedf 100755 --- a/examples/dfp/v201505/activity_service/get_active_activities.py +++ b/examples/dfp/v201505/activity_service/get_active_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/activity_service/get_all_activities.py b/examples/dfp/v201505/activity_service/get_all_activities.py index ce6a9904..db0241ea 100755 --- a/examples/dfp/v201505/activity_service/get_all_activities.py +++ b/examples/dfp/v201505/activity_service/get_all_activities.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/activity_service/update_activities.py b/examples/dfp/v201505/activity_service/update_activities.py index f859ec21..6f0a722a 100755 --- a/examples/dfp/v201505/activity_service/update_activities.py +++ b/examples/dfp/v201505/activity_service/update_activities.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.updateActivities - ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/audience_segment_service/create_audience_segments.py b/examples/dfp/v201505/audience_segment_service/create_audience_segments.py index 53ccdccc..29fb5f80 100755 --- a/examples/dfp/v201505/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/create_audience_segments.py @@ -16,8 +16,6 @@ """This example creates a new rule based first party audience segment.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -52,8 +50,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): custom_criteria = [ { 'xsi_type': 'CustomCriteria', - 'keyId': CUSTOM_TARGETING_KEY_ID, - 'valueIds': [CUSTOM_TARGETING_VALUE_ID], + 'keyId': custom_targeting_key_id, + 'valueIds': [custom_targeting_value_id], 'operator': 'IS' } ] diff --git a/examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py index 1bd90120..da60d96f 100755 --- a/examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py @@ -19,8 +19,6 @@ To create audience segments, run create_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py index 0a96536f..b7d55dc8 100755 --- a/examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py @@ -19,8 +19,6 @@ To create first party audience segments, run create_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py index 83ddcd42..a8cb293e 100755 --- a/examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py @@ -20,8 +20,6 @@ get_first_party_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/audience_segment_service/update_audience_segments.py b/examples/dfp/v201505/audience_segment_service/update_audience_segments.py index 59d70194..1fefe15b 100755 --- a/examples/dfp/v201505/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201505/audience_segment_service/update_audience_segments.py @@ -19,8 +19,6 @@ To determine which audience segments exist, run get_all_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/base_rate_service/create_product_base_rates.py b/examples/dfp/v201505/base_rate_service/create_product_base_rates.py index fdf4fbbf..18f25cf3 100755 --- a/examples/dfp/v201505/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201505/base_rate_service/create_product_base_rates.py @@ -18,10 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.createBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py index 715d2db5..fa37f438 100755 --- a/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py @@ -18,10 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.createBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/base_rate_service/get_all_base_rates.py b/examples/dfp/v201505/base_rate_service/get_all_base_rates.py index 0763d4b9..0831f26b 100755 --- a/examples/dfp/v201505/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201505/base_rate_service/get_all_base_rates.py @@ -20,10 +20,8 @@ To create product template base rates, run create_product_template_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py index c2b7b29d..ebdcec39 100755 --- a/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py @@ -20,10 +20,8 @@ To create product template base rates, run create_product_template_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/base_rate_service/update_base_rates.py b/examples/dfp/v201505/base_rate_service/update_base_rates.py index a7b8da8d..77674d35 100755 --- a/examples/dfp/v201505/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201505/base_rate_service/update_base_rates.py @@ -18,11 +18,8 @@ To determine which base rates exist, run get_all_base_rates.py. -Tags: BaseRateService.getBaseRatesByStatement -Tags: BaseRateService.updateBaseRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/company_service/create_companies.py b/examples/dfp/v201505/company_service/create_companies.py index 4b9fc756..9041634b 100755 --- a/examples/dfp/v201505/company_service/create_companies.py +++ b/examples/dfp/v201505/company_service/create_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.createCompanies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/company_service/get_advertisers.py b/examples/dfp/v201505/company_service/get_advertisers.py index 1c4db812..6b3f9dc9 100755 --- a/examples/dfp/v201505/company_service/get_advertisers.py +++ b/examples/dfp/v201505/company_service/get_advertisers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.getCompaniesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/company_service/get_all_companies.py b/examples/dfp/v201505/company_service/get_all_companies.py index 5082af52..46a1b9dc 100755 --- a/examples/dfp/v201505/company_service/get_all_companies.py +++ b/examples/dfp/v201505/company_service/get_all_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.getCompaniesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/company_service/update_companies.py b/examples/dfp/v201505/company_service/update_companies.py index 425fddfc..15e20da1 100755 --- a/examples/dfp/v201505/company_service/update_companies.py +++ b/examples/dfp/v201505/company_service/update_companies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.updateCompanies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/contact_service/create_contacts.py b/examples/dfp/v201505/contact_service/create_contacts.py index 9cfd31ae..11daf677 100755 --- a/examples/dfp/v201505/contact_service/create_contacts.py +++ b/examples/dfp/v201505/contact_service/create_contacts.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.createContacts """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/contact_service/get_all_contacts.py b/examples/dfp/v201505/contact_service/get_all_contacts.py index 39ff20dc..5ca9356c 100755 --- a/examples/dfp/v201505/contact_service/get_all_contacts.py +++ b/examples/dfp/v201505/contact_service/get_all_contacts.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/contact_service/get_uninvited_contacts.py b/examples/dfp/v201505/contact_service/get_uninvited_contacts.py index eccb4170..d3c16423 100755 --- a/examples/dfp/v201505/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201505/contact_service/get_uninvited_contacts.py @@ -23,10 +23,7 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/contact_service/update_contacts.py b/examples/dfp/v201505/contact_service/update_contacts.py index 2ca3e06c..99eca358 100755 --- a/examples/dfp/v201505/contact_service/update_contacts.py +++ b/examples/dfp/v201505/contact_service/update_contacts.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.updateContacts - ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 65d02493..7b10dea0 100755 --- a/examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -26,11 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 4d430b0b..0d86e096 100755 --- a/examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -26,12 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement - ContentMetadataKeyHierarchyService.perfomContentMetadataKeyHierarchyAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index e504fbff..5fdd83f1 100755 --- a/examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index e8746427..eab54bf5 100755 --- a/examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -26,12 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement - ContentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/content_service/get_all_content.py b/examples/dfp/v201505/content_service/get_all_content.py index 0bd6c25b..0541cdec 100755 --- a/examples/dfp/v201505/content_service/get_all_content.py +++ b/examples/dfp/v201505/content_service/get_all_content.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentService.getContentByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/content_service/get_content_by_category.py b/examples/dfp/v201505/content_service/get_content_by_category.py index b5fca4a3..574069ef 100755 --- a/examples/dfp/v201505/content_service/get_content_by_category.py +++ b/examples/dfp/v201505/content_service/get_content_by_category.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentService.getContentByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_service/create_creative_from_template.py b/examples/dfp/v201505/creative_service/create_creative_from_template.py index 60e35029..64c4f434 100755 --- a/examples/dfp/v201505/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201505/creative_service/create_creative_from_template.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreative """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os @@ -90,7 +87,7 @@ def main(client, advertiser_id): } # Call service to create the creative. - creative = creative_service.createCreative(creative) + creative = creative_service.createCreatives([creative])[0] # Display results. print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' diff --git a/examples/dfp/v201505/creative_service/create_creatives.py b/examples/dfp/v201505/creative_service/create_creatives.py index 56d3240f..639374bd 100755 --- a/examples/dfp/v201505/creative_service/create_creatives.py +++ b/examples/dfp/v201505/creative_service/create_creatives.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreatives """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os diff --git a/examples/dfp/v201505/creative_service/create_custom_creative.py b/examples/dfp/v201505/creative_service/create_custom_creative.py index 7bf92ad5..5343bfb4 100755 --- a/examples/dfp/v201505/creative_service/create_custom_creative.py +++ b/examples/dfp/v201505/creative_service/create_custom_creative.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreative """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os diff --git a/examples/dfp/v201505/creative_service/get_all_creatives.py b/examples/dfp/v201505/creative_service/get_all_creatives.py index 37f6e0fc..5fb20564 100755 --- a/examples/dfp/v201505/creative_service/get_all_creatives.py +++ b/examples/dfp/v201505/creative_service/get_all_creatives.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_service/get_creatives_by_statement.py b/examples/dfp/v201505/creative_service/get_creatives_by_statement.py index 466dcfd3..429bd019 100755 --- a/examples/dfp/v201505/creative_service/get_creatives_by_statement.py +++ b/examples/dfp/v201505/creative_service/get_creatives_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_service/update_creatives.py b/examples/dfp/v201505/creative_service/update_creatives.py index 855169e9..2bdeb944 100755 --- a/examples/dfp/v201505/creative_service/update_creatives.py +++ b/examples/dfp/v201505/creative_service/update_creatives.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.updateCreatives - CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py index 3981bd81..7d40a82b 100755 --- a/examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: LineItemCreativeAssociationService.createLineItemCreativeAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_set_service/create_creative_set.py b/examples/dfp/v201505/creative_set_service/create_creative_set.py index 3326489d..fcfd132a 100755 --- a/examples/dfp/v201505/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201505/creative_set_service/create_creative_set.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.createCreativeSet """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201505/creative_set_service/get_all_creative_sets.py index ad200999..b9c26ae5 100755 --- a/examples/dfp/v201505/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201505/creative_set_service/get_all_creative_sets.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py index dea7f147..f47d345a 100755 --- a/examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_set_service/update_creative_set.py b/examples/dfp/v201505/creative_set_service/update_creative_set.py index 623444c5..e371ad27 100755 --- a/examples/dfp/v201505/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201505/creative_set_service/update_creative_set.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.updateCreativeSet - CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201505/creative_template_service/get_all_creative_templates.py index 9ffd0131..2adffb47 100755 --- a/examples/dfp/v201505/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201505/creative_template_service/get_all_creative_templates.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeTemplateService.getCreativeTemplatesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py index 348a6d5e..59b14511 100755 --- a/examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py +++ b/examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeTemplateService.getCreativeTemplatesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py index 288c8af2..fad612ad 100755 --- a/examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.createCreativeWrappers """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py index 2e1a8004..021e51ae 100755 --- a/examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrapperByStatement -Tags: CreativeWrapperService.performCreativeWrapperAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py index 09453ff8..e84684c9 100755 --- a/examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py index 9ec01abb..f417b64d 100755 --- a/examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py index 0974cc5f..b8d1e004 100755 --- a/examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement -Tags: CreativeWrapperService.updateCreativeWrappers """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_field_service/create_custom_field_options.py b/examples/dfp/v201505/custom_field_service/create_custom_field_options.py index 8e0e6e98..254c0cc0 100755 --- a/examples/dfp/v201505/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201505/custom_field_service/create_custom_field_options.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.createCustomFieldOptions """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_field_service/create_custom_fields.py b/examples/dfp/v201505/custom_field_service/create_custom_fields.py index e006939b..0cd9bba1 100755 --- a/examples/dfp/v201505/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/create_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.createCustomFields """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py index 6a0cfdfc..75d69423 100755 --- a/examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement -Tags: CustomFieldService.performCustomFieldAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201505/custom_field_service/get_all_custom_fields.py index 695121cb..f75a7bec 100755 --- a/examples/dfp/v201505/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/get_all_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py index 9a334105..1c8930a7 100755 --- a/examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py index 917d405a..603c168b 100755 --- a/examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement - LineItemService.getLineItemsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_field_service/update_custom_fields.py b/examples/dfp/v201505/custom_field_service/update_custom_fields.py index 2fa529c3..bfa30c5c 100755 --- a/examples/dfp/v201505/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201505/custom_field_service/update_custom_fields.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.updateCustomFields - CustomFieldService.getCustomFieldByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py index e3ccf0a6..6c433dbf 100755 --- a/examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.createCustomTargetingKeys - CustomTargetingService.createCustomTargetingValues """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py index 8096ed5c..5820bdd3 100755 --- a/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.getCustomTargetingKeysByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py index 615e1d3b..150c6258 100755 --- a/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.getCustomTargetingValuesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 2252e51d..0b974d0f 100755 --- a/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -19,8 +19,6 @@ To create custom targeting keys and values, run create_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py index 9632a185..9cb5a762 100755 --- a/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py @@ -19,8 +19,6 @@ To create custom targeting keys, run create_custom_targeting_keys_and_values.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py index 5fb874ce..1e7544ed 100755 --- a/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ b/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py @@ -21,8 +21,6 @@ create_custom_targeting_keys_and_values.py. To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py index e8cf1b3e..74a4a86d 100755 --- a/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py @@ -19,8 +19,6 @@ To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py index ebdd5bc8..30ea91e1 100755 --- a/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py @@ -20,8 +20,6 @@ To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py index beac31c7..f9057cd3 100755 --- a/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py @@ -19,10 +19,8 @@ To determine which exchange rates exist, run get_all_exchange_rates.py. -Tags: ExchangeRateService.createExchangeRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py index 2ede79a8..fc1f00ce 100755 --- a/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py index d67a475b..be5445fd 100755 --- a/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py index acee7f9b..70c06c1e 100755 --- a/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py @@ -18,10 +18,8 @@ To create exchange rates, run create_exchange_rates.py. -Tags: ExchangeRateService.getExchangeRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/forecast_service/get_availability_forecast.py b/examples/dfp/v201505/forecast_service/get_availability_forecast.py index 77e12afb..5ca1708c 100755 --- a/examples/dfp/v201505/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201505/forecast_service/get_availability_forecast.py @@ -21,11 +21,8 @@ targeting (in addition to targeting the whole network). See create_line_items.py for an example of how to create more complex targeting. -Tags: ForecastService.getAvailabilityForecast -Tags: NetworkService.getCurrentNetwork """ -__author__ = 'Nicholas Chen' from datetime import date diff --git a/examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py index 6085cc02..058e9a05 100755 --- a/examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py @@ -18,10 +18,8 @@ To determine which line items exist, run get_all_line_items.py. -Tags: ForecastService.getAvailabilityForecastById """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py index 6585a95b..ee829e85 100755 --- a/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py @@ -18,10 +18,8 @@ To determine which line items exist, run get_all_line_items.py. -Tags: ForecastService.getDeliveryForecastByIds """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/inventory_service/archive_ad_units.py b/examples/dfp/v201505/inventory_service/archive_ad_units.py index 2d5c01b8..2e45006b 100755 --- a/examples/dfp/v201505/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201505/inventory_service/archive_ad_units.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/inventory_service/create_ad_units.py b/examples/dfp/v201505/inventory_service/create_ad_units.py index ac1edaec..40a74b35 100755 --- a/examples/dfp/v201505/inventory_service/create_ad_units.py +++ b/examples/dfp/v201505/inventory_service/create_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.createAdUnits """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py index 65c6b793..8706c8b7 100755 --- a/examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py index 7a719155..64dc0ab8 100755 --- a/examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitSizesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/inventory_service/get_all_ad_units.py b/examples/dfp/v201505/inventory_service/get_all_ad_units.py index f6d78437..49484df8 100755 --- a/examples/dfp/v201505/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201505/inventory_service/get_all_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201505/inventory_service/get_top_level_ad_units.py index d6b85c74..4381ebde 100755 --- a/examples/dfp/v201505/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201505/inventory_service/get_top_level_ad_units.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/inventory_service/update_ad_units.py b/examples/dfp/v201505/inventory_service/update_ad_units.py index db8a1633..a893785d 100755 --- a/examples/dfp/v201505/inventory_service/update_ad_units.py +++ b/examples/dfp/v201505/inventory_service/update_ad_units.py @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnit -Tags: InventoryService.updateAdUnits """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/label_service/create_labels.py b/examples/dfp/v201505/label_service/create_labels.py index 2347eeb5..d23995b8 100755 --- a/examples/dfp/v201505/label_service/create_labels.py +++ b/examples/dfp/v201505/label_service/create_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/label_service/deactivate_labels.py b/examples/dfp/v201505/label_service/deactivate_labels.py index f278e5fc..7f0019da 100755 --- a/examples/dfp/v201505/label_service/deactivate_labels.py +++ b/examples/dfp/v201505/label_service/deactivate_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/label_service/get_all_labels.py b/examples/dfp/v201505/label_service/get_all_labels.py index 0d704227..bb0574db 100755 --- a/examples/dfp/v201505/label_service/get_all_labels.py +++ b/examples/dfp/v201505/label_service/get_all_labels.py @@ -19,8 +19,6 @@ To create labels, run create_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/label_service/get_labels_by_statement.py b/examples/dfp/v201505/label_service/get_labels_by_statement.py index a4364ee0..fae47ceb 100755 --- a/examples/dfp/v201505/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201505/label_service/get_labels_by_statement.py @@ -20,8 +20,6 @@ premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/label_service/update_labels.py b/examples/dfp/v201505/label_service/update_labels.py index 70c125c8..508529f7 100755 --- a/examples/dfp/v201505/label_service/update_labels.py +++ b/examples/dfp/v201505/label_service/update_labels.py @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/line_item_creative_association_service/create_licas.py b/examples/dfp/v201505/line_item_creative_association_service/create_licas.py index b5d2c0cf..43934944 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201505/line_item_creative_association_service/create_licas.py @@ -19,8 +19,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py index b51fc2a1..8b0d2a35 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py @@ -18,8 +18,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py index 5eb41be5..634b9b12 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py @@ -19,8 +19,6 @@ To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py index 390ddded..10836292 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py @@ -19,8 +19,6 @@ To create LICAs, run create_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/line_item_creative_association_service/update_licas.py b/examples/dfp/v201505/line_item_creative_association_service/update_licas.py index 1464a1e4..7a53d342 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201505/line_item_creative_association_service/update_licas.py @@ -19,8 +19,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/line_item_service/activate_line_items.py b/examples/dfp/v201505/line_item_service/activate_line_items.py index 2a6b604b..76a5a8ea 100755 --- a/examples/dfp/v201505/line_item_service/activate_line_items.py +++ b/examples/dfp/v201505/line_item_service/activate_line_items.py @@ -22,8 +22,6 @@ create_licas.py. To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/line_item_service/create_line_items.py b/examples/dfp/v201505/line_item_service/create_line_items.py index 8f587e1d..61c08ffb 100755 --- a/examples/dfp/v201505/line_item_service/create_line_items.py +++ b/examples/dfp/v201505/line_item_service/create_line_items.py @@ -20,8 +20,6 @@ which orders exist, run get_all_orders.py. To determine which placements exist, run get_all_placements.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date import uuid diff --git a/examples/dfp/v201505/line_item_service/create_video_line_item.py b/examples/dfp/v201505/line_item_service/create_video_line_item.py index c64c1d3c..06835263 100755 --- a/examples/dfp/v201505/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201505/line_item_service/create_video_line_item.py @@ -22,8 +22,6 @@ create_video_ad_unit.py. To create criteria for categories, run create_custom_targeting_keys_and_values.py""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date import uuid diff --git a/examples/dfp/v201505/line_item_service/get_all_line_items.py b/examples/dfp/v201505/line_item_service/get_all_line_items.py index 3b325864..e2d6431a 100755 --- a/examples/dfp/v201505/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201505/line_item_service/get_all_line_items.py @@ -18,8 +18,6 @@ To create line items, run create_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201505/line_item_service/get_line_items_by_statement.py index d17bc71b..c3e9acbc 100755 --- a/examples/dfp/v201505/line_item_service/get_line_items_by_statement.py +++ b/examples/dfp/v201505/line_item_service/get_line_items_by_statement.py @@ -14,13 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets all line items that need creatives for the given -order. +"""This code example gets all line items that need creatives for an order. -To create line items, run create_line_items.py.""" +To create line items, run create_line_items.py. +""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -48,8 +46,8 @@ def main(client, order_id): 'value': 'true' } }] - query = 'WHERE orderId = :orderId AND ' - 'isMissingCreatives = :isMissingCreatives' + query = ('WHERE orderId = :orderId AND ' + 'isMissingCreatives = :isMissingCreatives') statement = dfp.FilterStatement(query, values) while True: diff --git a/examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py index b7b78e5b..dca16f6a 100755 --- a/examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py @@ -18,8 +18,6 @@ To create line items, run create_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import datetime diff --git a/examples/dfp/v201505/line_item_service/target_custom_criteria.py b/examples/dfp/v201505/line_item_service/target_custom_criteria.py index 91717ef3..6eff449d 100755 --- a/examples/dfp/v201505/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201505/line_item_service/target_custom_criteria.py @@ -20,8 +20,6 @@ which custom targeting keys and values exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import pprint diff --git a/examples/dfp/v201505/line_item_service/update_line_items.py b/examples/dfp/v201505/line_item_service/update_line_items.py index c67bf761..d3695143 100755 --- a/examples/dfp/v201505/line_item_service/update_line_items.py +++ b/examples/dfp/v201505/line_item_service/update_line_items.py @@ -18,8 +18,6 @@ To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/network_service/get_all_networks.py b/examples/dfp/v201505/network_service/get_all_networks.py index d70a65ae..d9bcda9d 100755 --- a/examples/dfp/v201505/network_service/get_all_networks.py +++ b/examples/dfp/v201505/network_service/get_all_networks.py @@ -19,8 +19,6 @@ A networkCode should be left out for this request.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/network_service/get_current_network.py b/examples/dfp/v201505/network_service/get_current_network.py index 52138ce9..54068e24 100755 --- a/examples/dfp/v201505/network_service/get_current_network.py +++ b/examples/dfp/v201505/network_service/get_current_network.py @@ -16,8 +16,6 @@ """This example gets the current network that you can make requests against.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/network_service/make_test_network.py b/examples/dfp/v201505/network_service/make_test_network.py index a5649823..93e21a7c 100755 --- a/examples/dfp/v201505/network_service/make_test_network.py +++ b/examples/dfp/v201505/network_service/make_test_network.py @@ -27,8 +27,6 @@ https://dfp-playground.appspot.com """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/order_service/approve_orders.py b/examples/dfp/v201505/order_service/approve_orders.py index 1c5888bc..43ee7d93 100755 --- a/examples/dfp/v201505/order_service/approve_orders.py +++ b/examples/dfp/v201505/order_service/approve_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import datetime diff --git a/examples/dfp/v201505/order_service/create_orders.py b/examples/dfp/v201505/order_service/create_orders.py index 24d967e3..44daffe3 100755 --- a/examples/dfp/v201505/order_service/create_orders.py +++ b/examples/dfp/v201505/order_service/create_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/order_service/get_all_orders.py b/examples/dfp/v201505/order_service/get_all_orders.py index 41bfa575..161c54c1 100755 --- a/examples/dfp/v201505/order_service/get_all_orders.py +++ b/examples/dfp/v201505/order_service/get_all_orders.py @@ -19,8 +19,6 @@ To create orders, run create_orders.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/order_service/get_orders_by_statement.py b/examples/dfp/v201505/order_service/get_orders_by_statement.py index 95d8e174..138fd268 100755 --- a/examples/dfp/v201505/order_service/get_orders_by_statement.py +++ b/examples/dfp/v201505/order_service/get_orders_by_statement.py @@ -18,8 +18,6 @@ To create orders, run create_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/order_service/update_orders.py b/examples/dfp/v201505/order_service/update_orders.py index d9192f19..e216dded 100755 --- a/examples/dfp/v201505/order_service/update_orders.py +++ b/examples/dfp/v201505/order_service/update_orders.py @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/placement_service/create_placements.py b/examples/dfp/v201505/placement_service/create_placements.py index 0688c620..edcb7136 100755 --- a/examples/dfp/v201505/placement_service/create_placements.py +++ b/examples/dfp/v201505/placement_service/create_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/placement_service/deactivate_placements.py b/examples/dfp/v201505/placement_service/deactivate_placements.py index c4726bad..78cc8ee9 100755 --- a/examples/dfp/v201505/placement_service/deactivate_placements.py +++ b/examples/dfp/v201505/placement_service/deactivate_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/placement_service/get_all_placements.py b/examples/dfp/v201505/placement_service/get_all_placements.py index bfdb34ae..f35524fc 100755 --- a/examples/dfp/v201505/placement_service/get_all_placements.py +++ b/examples/dfp/v201505/placement_service/get_all_placements.py @@ -19,8 +19,6 @@ To create placements, run create_placement.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/placement_service/get_placements_by_statement.py b/examples/dfp/v201505/placement_service/get_placements_by_statement.py index 9281f234..94aeb621 100755 --- a/examples/dfp/v201505/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201505/placement_service/get_placements_by_statement.py @@ -19,8 +19,6 @@ To create a placement, run create_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/placement_service/update_placements.py b/examples/dfp/v201505/placement_service/update_placements.py index dc2877b9..469e0663 100755 --- a/examples/dfp/v201505/placement_service/update_placements.py +++ b/examples/dfp/v201505/placement_service/update_placements.py @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/premium_rate_service/create_premium_rates.py b/examples/dfp/v201505/premium_rate_service/create_premium_rates.py index 445b86bd..c7d6f0b8 100755 --- a/examples/dfp/v201505/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201505/premium_rate_service/create_premium_rates.py @@ -19,9 +19,6 @@ To determine which premium_rates exist, run get_all_premium_rates.py. """ -__author__ = 'Nicholas Chen' - - # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py index cbee9eb5..2da3b647 100755 --- a/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py @@ -18,10 +18,8 @@ To create premium rates, run create_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py index 5fc8fcdf..b22faa40 100755 --- a/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py @@ -18,10 +18,8 @@ To create premium rates, run create_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/premium_rate_service/update_premium_rates.py b/examples/dfp/v201505/premium_rate_service/update_premium_rates.py index ec936060..6fdd9a74 100755 --- a/examples/dfp/v201505/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201505/premium_rate_service/update_premium_rates.py @@ -18,11 +18,8 @@ To determine which premium rates exist, run get_all_premium_rates.py. -Tags: PremiumRateService.getPremiumRatesByStatement -Tags: PremiumRateService.updatePremiumRates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/product_service/get_all_products.py b/examples/dfp/v201505/product_service/get_all_products.py index 34bc3e24..d66f7ba8 100755 --- a/examples/dfp/v201505/product_service/get_all_products.py +++ b/examples/dfp/v201505/product_service/get_all_products.py @@ -18,10 +18,8 @@ Products are created automatically from product templates. -Tags: ProductService.getProductsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/product_service/get_products_for_product_template.py b/examples/dfp/v201505/product_service/get_products_for_product_template.py index 2c07c8a4..886d84ed 100755 --- a/examples/dfp/v201505/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201505/product_service/get_products_for_product_template.py @@ -16,10 +16,8 @@ """This example gets all products created from a product template. -Tags: ProductService.getProductsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/product_service/update_products.py b/examples/dfp/v201505/product_service/update_products.py index 900dbbd9..af816775 100755 --- a/examples/dfp/v201505/product_service/update_products.py +++ b/examples/dfp/v201505/product_service/update_products.py @@ -18,11 +18,8 @@ To determine which products exist, run get_all_products.py. -Tags: ProductService.getProductsByStatement -Tags: ProductService.updateProducts """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/product_template_service/activate_product_templates.py b/examples/dfp/v201505/product_template_service/activate_product_templates.py index 7d2a919f..4e2f9126 100755 --- a/examples/dfp/v201505/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201505/product_template_service/activate_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement -Tags: ProductTemplateService.performProductTemplateAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/product_template_service/create_product_templates.py b/examples/dfp/v201505/product_template_service/create_product_templates.py index 7ccaad2b..8b960910 100755 --- a/examples/dfp/v201505/product_template_service/create_product_templates.py +++ b/examples/dfp/v201505/product_template_service/create_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.createProductTemplates -Tags: NetworkService.getCurrentNetwork """ -__author__ = 'Nicholas Chen' import uuid diff --git a/examples/dfp/v201505/product_template_service/get_all_product_templates.py b/examples/dfp/v201505/product_template_service/get_all_product_templates.py index b0391890..e3ac0d46 100755 --- a/examples/dfp/v201505/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201505/product_template_service/get_all_product_templates.py @@ -18,10 +18,8 @@ To create product templates, run create_product_template_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py index 4366e842..a0e4345a 100755 --- a/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py @@ -16,10 +16,8 @@ """This code example gets all sponsorship product templates. -Tags: ProductTemplateService.getProductTemplatesByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/product_template_service/update_product_templates.py b/examples/dfp/v201505/product_template_service/update_product_templates.py index 4144c7e7..54250aff 100755 --- a/examples/dfp/v201505/product_template_service/update_product_templates.py +++ b/examples/dfp/v201505/product_template_service/update_product_templates.py @@ -18,11 +18,8 @@ To determine which product templates exist, run get_all_product_templates.py. -Tags: ProductTemplateService.getProductTemplatesByStatement -Tags: ProductTemplateService.updateProductTemplates """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py index 5213530b..e3b498e4 100755 --- a/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py @@ -20,7 +20,6 @@ get_all_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py index f12a681e..779b1502 100755 --- a/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py @@ -21,7 +21,6 @@ get_all_proposals.py. """ -__author__ = 'Nicholas Chen' from datetime import date import uuid diff --git a/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py index b0b02594..5d0e2898 100755 --- a/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py @@ -19,7 +19,6 @@ To create proposal line items, run create_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py index cafb9e41..5fc1fe41 100755 --- a/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -13,12 +13,10 @@ # 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 code example gets all proposal line items that belong to a proposal. To create proposal line items, run create_proposal_line_items.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,8 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201505') + 'ProposalLineItemService', + version='v201505') # Create statement object to only select proposal line items belonging to a # given proposal. @@ -53,11 +52,11 @@ def main(client, proposal_id): # Display results. for idx, proposal_line_item in enumerate(response['results'], start=statement.offset): - print ('%s) Line item with id \'%s\', belonging to proposal id \'%s\', ' - 'and named \'%s\' was found.' % ( - idx, proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) + print( + '%s) Proposal line item with id \'%s\', belonging to proposal id ' + '\'%s\', and named \'%s\' was found.' % ( + idx, proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py index 3b152be0..f9cb063b 100755 --- a/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py @@ -20,7 +20,6 @@ run get_all_proposal_line_items.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/proposal_service/create_proposals.py b/examples/dfp/v201505/proposal_service/create_proposals.py index bb8047d8..daf8cd32 100755 --- a/examples/dfp/v201505/proposal_service/create_proposals.py +++ b/examples/dfp/v201505/proposal_service/create_proposals.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' import uuid diff --git a/examples/dfp/v201505/proposal_service/get_all_proposals.py b/examples/dfp/v201505/proposal_service/get_all_proposals.py index a5f79d79..6875bbca 100755 --- a/examples/dfp/v201505/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201505/proposal_service/get_all_proposals.py @@ -19,7 +19,6 @@ To create proposals, run create_proposals.py. """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py index 7aae86c2..6550dd58 100755 --- a/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py @@ -18,7 +18,6 @@ To create proposals, run create_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py index 87f3e0f4..17a5f7b0 100755 --- a/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/proposal_service/update_proposals.py b/examples/dfp/v201505/proposal_service/update_proposals.py index d166abbc..5de8dac5 100755 --- a/examples/dfp/v201505/proposal_service/update_proposals.py +++ b/examples/dfp/v201505/proposal_service/update_proposals.py @@ -18,7 +18,6 @@ To determine which proposals exist, run get_all_proposals.py.""" -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py index b7c3d3b9..764f7812 100755 --- a/examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py @@ -16,8 +16,6 @@ """This example fetches data from PQL tables and creates match table files.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py index 24cdbff9..6013be2f 100755 --- a/examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py @@ -23,8 +23,6 @@ https://developers.google.com/doubleclick-publishers/docs/reference/v201505/PublisherQueryLanguageService """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py index 66812bdd..6a8496b2 100755 --- a/examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py @@ -16,8 +16,6 @@ """This example gets all line items with names starting with 'line item'.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile diff --git a/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py index 7ee584da..f85dec4f 100755 --- a/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py @@ -16,10 +16,8 @@ """This code example gets all rate cards. -Tags: RateCardService.getRateCardsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py index c81bbd5b..f0954058 100755 --- a/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py @@ -16,10 +16,8 @@ """This example gets all rate cards that have a currency in US dollars. -Tags: RateCardService.getRateCardsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/report_service/run_delivery_report.py b/examples/dfp/v201505/report_service/run_delivery_report.py index 8038b0bd..15b1a2cc 100755 --- a/examples/dfp/v201505/report_service/run_delivery_report.py +++ b/examples/dfp/v201505/report_service/run_delivery_report.py @@ -18,8 +18,6 @@ website with additional attributes and can filter to include just one order. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201505/report_service/run_inventory_report.py b/examples/dfp/v201505/report_service/run_inventory_report.py index b04b0968..99af3ea1 100755 --- a/examples/dfp/v201505/report_service/run_inventory_report.py +++ b/examples/dfp/v201505/report_service/run_inventory_report.py @@ -18,8 +18,6 @@ DFP website. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201505/report_service/run_reach_report.py b/examples/dfp/v201505/report_service/run_reach_report.py index d84c43ef..b02737cd 100755 --- a/examples/dfp/v201505/report_service/run_reach_report.py +++ b/examples/dfp/v201505/report_service/run_reach_report.py @@ -16,8 +16,6 @@ """This code example runs a reach report.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201505/report_service/run_report_with_custom_fields.py b/examples/dfp/v201505/report_service/run_report_with_custom_fields.py index c3c46e91..0441aa9e 100755 --- a/examples/dfp/v201505/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201505/report_service/run_report_with_custom_fields.py @@ -18,8 +18,6 @@ items of an order. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201505/report_service/run_sales_report.py b/examples/dfp/v201505/report_service/run_sales_report.py index 2539aaad..fdfcf618 100755 --- a/examples/dfp/v201505/report_service/run_sales_report.py +++ b/examples/dfp/v201505/report_service/run_sales_report.py @@ -17,8 +17,6 @@ """This code example runs a report equal to the "Sales by salespersons report." """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. diff --git a/examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py index ce54ff15..d3a81368 100755 --- a/examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -19,8 +19,6 @@ This feature is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py index 775e4239..c2f1dc00 100755 --- a/examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -20,8 +20,6 @@ is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py index 180fc082..9a59cd9f 100755 --- a/examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py @@ -19,8 +19,6 @@ This feature is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/team_service/create_teams.py b/examples/dfp/v201505/team_service/create_teams.py index 51119ecc..2f3f37cf 100755 --- a/examples/dfp/v201505/team_service/create_teams.py +++ b/examples/dfp/v201505/team_service/create_teams.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.createTeams """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid diff --git a/examples/dfp/v201505/team_service/get_all_teams.py b/examples/dfp/v201505/team_service/get_all_teams.py index 463d9ca0..91b7e130 100755 --- a/examples/dfp/v201505/team_service/get_all_teams.py +++ b/examples/dfp/v201505/team_service/get_all_teams.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/team_service/get_teams_by_statement.py b/examples/dfp/v201505/team_service/get_teams_by_statement.py index d877329f..4f820dbc 100755 --- a/examples/dfp/v201505/team_service/get_teams_by_statement.py +++ b/examples/dfp/v201505/team_service/get_teams_by_statement.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/team_service/update_teams.py b/examples/dfp/v201505/team_service/update_teams.py index d4dafdf3..f23df5e0 100755 --- a/examples/dfp/v201505/team_service/update_teams.py +++ b/examples/dfp/v201505/team_service/update_teams.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement, TeamService.updateTeams """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_service/create_users.py b/examples/dfp/v201505/user_service/create_users.py index f7da0e8c..aaaa7738 100755 --- a/examples/dfp/v201505/user_service/create_users.py +++ b/examples/dfp/v201505/user_service/create_users.py @@ -18,8 +18,6 @@ To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_service/deactivate_users.py b/examples/dfp/v201505/user_service/deactivate_users.py index 350950d8..e1db318e 100755 --- a/examples/dfp/v201505/user_service/deactivate_users.py +++ b/examples/dfp/v201505/user_service/deactivate_users.py @@ -20,8 +20,6 @@ request cannot deactivate itself. To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_service/get_all_roles.py b/examples/dfp/v201505/user_service/get_all_roles.py index e82db9ce..6ba977be 100755 --- a/examples/dfp/v201505/user_service/get_all_roles.py +++ b/examples/dfp/v201505/user_service/get_all_roles.py @@ -19,8 +19,6 @@ This sample can be used to determine which role id is needed when getting and creating users.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_service/get_all_users.py b/examples/dfp/v201505/user_service/get_all_users.py index 9249baf5..24e4aeb0 100755 --- a/examples/dfp/v201505/user_service/get_all_users.py +++ b/examples/dfp/v201505/user_service/get_all_users.py @@ -16,8 +16,6 @@ """This code example gets all users. To create users, run create_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_service/get_current_user.py b/examples/dfp/v201505/user_service/get_current_user.py index 6ec54e10..c676f5da 100755 --- a/examples/dfp/v201505/user_service/get_current_user.py +++ b/examples/dfp/v201505/user_service/get_current_user.py @@ -16,8 +16,6 @@ """This code example gets the current user.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_service/get_users_by_statement.py b/examples/dfp/v201505/user_service/get_users_by_statement.py index 8496c62a..4e1d3bcb 100755 --- a/examples/dfp/v201505/user_service/get_users_by_statement.py +++ b/examples/dfp/v201505/user_service/get_users_by_statement.py @@ -18,8 +18,6 @@ To create users, run create_user.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_service/update_users.py b/examples/dfp/v201505/user_service/update_users.py index 7786c469..1feab89c 100755 --- a/examples/dfp/v201505/user_service/update_users.py +++ b/examples/dfp/v201505/user_service/update_users.py @@ -18,8 +18,6 @@ To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201505/user_team_association_service/create_user_team_associations.py index 8710c07f..bdca5233 100755 --- a/examples/dfp/v201505/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201505/user_team_association_service/create_user_team_associations.py @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.createUserTeamAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py index 47e23734..89d08795 100755 --- a/examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.performUserTeamAssociationAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py index 4ea6956b..592881b7 100755 --- a/examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py index fb2f99b5..f7210bd4 100755 --- a/examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociation """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201505/user_team_association_service/update_user_team_associations.py index 0ad6b314..42b69bae 100755 --- a/examples/dfp/v201505/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201505/user_team_association_service/update_user_team_associations.py @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement -Tags: UserTeamAssociationService.updateUserTeamAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py index 64ec3783..d20e0f96 100755 --- a/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py @@ -19,11 +19,8 @@ To determine which workflow approval requests exist, run get_all_workflow_approval_requests.py. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement -Tags: WorkflowRequestService.performWorkflowRequestAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py index cfae6c8c..92b98fcf 100755 --- a/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py @@ -19,10 +19,8 @@ Workflow approval requests must be approved or rejected for a workflow to finish. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py index 1f1a9b8c..f03696ae 100755 --- a/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py @@ -19,10 +19,8 @@ Workflow external condition requests must be triggered or skipped for a workflow to finish. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py index 01f03c8d..eb08a09c 100755 --- a/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -19,11 +19,8 @@ Workflow external condition requests must be triggered or skipped for a workflow to finish. To determine which proposals exist, run get_all_proposals.py. -Tags: WorkflowRequestService.getWorkflowRequestsByStatement -Tags: WorkflowRequestService.performWorkflowRequestAction """ -__author__ = 'Nicholas Chen' # Import appropriate modules from the client library. from googleads import dfp diff --git a/examples/dfp/v201408/activity_group_service/__init__.py b/examples/dfp/v201508/activity_group_service/__init__.py similarity index 91% rename from examples/dfp/v201408/activity_group_service/__init__.py rename to examples/dfp/v201508/activity_group_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201408/activity_group_service/__init__.py +++ b/examples/dfp/v201508/activity_group_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201408/activity_group_service/create_activity_groups.py b/examples/dfp/v201508/activity_group_service/create_activity_groups.py similarity index 91% rename from examples/dfp/v201408/activity_group_service/create_activity_groups.py rename to examples/dfp/v201508/activity_group_service/create_activity_groups.py index 6021486d..4ab78498 100755 --- a/examples/dfp/v201408/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201508/activity_group_service/create_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.createActivityGroups """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid @@ -41,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201408') + version='v201508') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201408/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201508/activity_group_service/get_active_activity_groups.py similarity index 90% rename from examples/dfp/v201408/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201508/activity_group_service/get_active_activity_groups.py index 81fcb5bf..c6cd26ed 100755 --- a/examples/dfp/v201408/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201508/activity_group_service/get_active_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroupsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201408') + version='v201508') # Create statement object to only select active activity groups. values = [{ diff --git a/examples/dfp/v201408/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201508/activity_group_service/get_all_activity_groups.py similarity index 88% rename from examples/dfp/v201408/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201508/activity_group_service/get_all_activity_groups.py index a4d34c55..c610a3c5 100755 --- a/examples/dfp/v201408/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201508/activity_group_service/get_all_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroupsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201408') + version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/activity_group_service/update_activity_groups.py b/examples/dfp/v201508/activity_group_service/update_activity_groups.py similarity index 90% rename from examples/dfp/v201408/activity_group_service/update_activity_groups.py rename to examples/dfp/v201508/activity_group_service/update_activity_groups.py index d1a065c8..1220eaeb 100755 --- a/examples/dfp/v201408/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201508/activity_group_service/update_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityGroupService.getActivityGroup -Tags: ActivityGroupService.updateActivityGroups """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -41,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201408') + version='v201508') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201408/activity_service/__init__.py b/examples/dfp/v201508/activity_service/__init__.py similarity index 91% rename from examples/dfp/v201408/activity_service/__init__.py rename to examples/dfp/v201508/activity_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201408/activity_service/__init__.py +++ b/examples/dfp/v201508/activity_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201408/activity_service/create_activities.py b/examples/dfp/v201508/activity_service/create_activities.py similarity index 92% rename from examples/dfp/v201408/activity_service/create_activities.py rename to examples/dfp/v201508/activity_service/create_activities.py index 36783f82..b1bb4812 100755 --- a/examples/dfp/v201408/activity_service/create_activities.py +++ b/examples/dfp/v201508/activity_service/create_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.createActivities """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid @@ -40,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201408') + activity_service = client.GetService('ActivityService', version='v201508') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201408/activity_service/get_active_activities.py b/examples/dfp/v201508/activity_service/get_active_activities.py similarity index 92% rename from examples/dfp/v201408/activity_service/get_active_activities.py rename to examples/dfp/v201508/activity_service/get_active_activities.py index 19dc569c..e2d1d647 100755 --- a/examples/dfp/v201408/activity_service/get_active_activities.py +++ b/examples/dfp/v201508/activity_service/get_active_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201408') + activity_service = client.GetService('ActivityService', version='v201508') # Create statement object to only select active activities. values = [{ diff --git a/examples/dfp/v201408/activity_service/get_all_activities.py b/examples/dfp/v201508/activity_service/get_all_activities.py similarity index 91% rename from examples/dfp/v201408/activity_service/get_all_activities.py rename to examples/dfp/v201508/activity_service/get_all_activities.py index 9622e5a3..c953b823 100755 --- a/examples/dfp/v201408/activity_service/get_all_activities.py +++ b/examples/dfp/v201508/activity_service/get_all_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201408') + activity_service = client.GetService('ActivityService', version='v201508') # Create statement object to select only all activities. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/activity_service/update_activities.py b/examples/dfp/v201508/activity_service/update_activities.py similarity index 91% rename from examples/dfp/v201408/activity_service/update_activities.py rename to examples/dfp/v201508/activity_service/update_activities.py index 4db4254a..c2021187 100755 --- a/examples/dfp/v201408/activity_service/update_activities.py +++ b/examples/dfp/v201508/activity_service/update_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ActivityService.updateActivities - ActivityService.getActivitiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -39,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201408') + activity_service = client.GetService('ActivityService', version='v201508') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201408/audience_segment_service/__init__.py b/examples/dfp/v201508/audience_segment_service/__init__.py similarity index 91% rename from examples/dfp/v201408/audience_segment_service/__init__.py rename to examples/dfp/v201508/audience_segment_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201408/audience_segment_service/__init__.py +++ b/examples/dfp/v201508/audience_segment_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201408/audience_segment_service/create_audience_segments.py b/examples/dfp/v201508/audience_segment_service/create_audience_segments.py similarity index 91% rename from examples/dfp/v201408/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201508/audience_segment_service/create_audience_segments.py index 547b6ff5..fe1cff5c 100755 --- a/examples/dfp/v201408/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201508/audience_segment_service/create_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -16,8 +16,6 @@ """This example creates a new rule based first party audience segment.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -34,8 +32,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201408') - network_service = client.GetService('NetworkService', version='v201408') + 'AudienceSegmentService', version='v201508') + network_service = client.GetService('NetworkService', version='v201508') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( @@ -52,8 +50,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): custom_criteria = [ { 'xsi_type': 'CustomCriteria', - 'keyId': CUSTOM_TARGETING_KEY_ID, - 'valueIds': [CUSTOM_TARGETING_VALUE_ID], + 'keyId': custom_targeting_key_id, + 'valueIds': [custom_targeting_value_id], 'operator': 'IS' } ] diff --git a/examples/dfp/v201408/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201508/audience_segment_service/get_all_audience_segments.py similarity index 91% rename from examples/dfp/v201408/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201508/audience_segment_service/get_all_audience_segments.py index 81f37df6..a44b2596 100755 --- a/examples/dfp/v201408/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201508/audience_segment_service/get_all_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create audience segments, run create_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -32,7 +30,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201408') + 'AudienceSegmentService', version='v201508') # Create statement object to select all audience segments. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201508/audience_segment_service/get_first_party_audience_segments.py similarity index 92% rename from examples/dfp/v201408/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201508/audience_segment_service/get_first_party_audience_segments.py index d3fd3952..bee6f37a 100755 --- a/examples/dfp/v201408/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201508/audience_segment_service/get_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create first party audience segments, run create_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -32,7 +30,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201408') + 'AudienceSegmentService', version='v201508') # Create statement object to only select first party audience segments. values = [{ diff --git a/examples/dfp/v201408/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201508/audience_segment_service/populate_first_party_audience_segments.py similarity index 93% rename from examples/dfp/v201408/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201508/audience_segment_service/populate_first_party_audience_segments.py index f9115285..43402066 100755 --- a/examples/dfp/v201408/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201508/audience_segment_service/populate_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,8 +20,6 @@ get_first_party_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +33,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201408') + 'AudienceSegmentService', version='v201508') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201408/audience_segment_service/update_audience_segments.py b/examples/dfp/v201508/audience_segment_service/update_audience_segments.py similarity index 94% rename from examples/dfp/v201408/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201508/audience_segment_service/update_audience_segments.py index 0cbd7bc4..230c3a5c 100755 --- a/examples/dfp/v201408/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201508/audience_segment_service/update_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which audience segments exist, run get_all_audience_segments.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -34,7 +32,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201408') + 'AudienceSegmentService', version='v201508') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201408/company_service/__init__.py b/examples/dfp/v201508/base_rate_service/__init__.py similarity index 91% rename from examples/dfp/v201408/company_service/__init__.py rename to examples/dfp/v201508/base_rate_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201408/company_service/__init__.py +++ b/examples/dfp/v201508/base_rate_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201508/base_rate_service/create_product_base_rates.py b/examples/dfp/v201508/base_rate_service/create_product_base_rates.py new file mode 100755 index 00000000..013056b3 --- /dev/null +++ b/examples/dfp/v201508/base_rate_service/create_product_base_rates.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates a product base rate. + +To determine which base rates exist, run get_all_base_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, product_id, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService( + 'BaseRateService', version='v201508') + + # Create a product base rate. + product_base_rate = { + 'xsi_type': 'ProductBaseRate', + 'rateCardId': rate_card_id, + 'productId': product_id, + # Set the rate to be $2. + 'rate': { + 'currencyCode': 'USD', + 'microAmount': 2000000 + } + } + + # Create base rates on the server. + base_rates = base_rate_service.createBaseRates( + [product_base_rate]) + + if base_rates: + for base_rate in base_rates: + print ('A product base rate with ID \'%s\' and rate \'%.2f\' %s was ' + 'created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201508/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201508/base_rate_service/create_product_template_base_rates.py new file mode 100755 index 00000000..c2687f58 --- /dev/null +++ b/examples/dfp/v201508/base_rate_service/create_product_template_base_rates.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates a product template base rate. + +To determine which base rates exist, run get_all_base_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, product_template_id, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService( + 'BaseRateService', version='v201508') + + # Create a product template base rate. + product_template_base_rate = { + 'xsi_type': 'ProductTemplateBaseRate', + 'rateCardId': rate_card_id, + 'productTemplateId': product_template_id, + # Set the rate to be $2. + 'rate': { + 'currencyCode': 'USD', + 'microAmount': 2000000 + } + } + + # Create base rates on the server. + base_rates = base_rate_service.createBaseRates( + [product_template_base_rate]) + + if base_rates: + for base_rate in base_rates: + print ('A product template base rate with ID \'%s\' and rate \'%.2f\' %s' + ' was created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201508/base_rate_service/get_all_base_rates.py b/examples/dfp/v201508/base_rate_service/get_all_base_rates.py new file mode 100755 index 00000000..f9b0d176 --- /dev/null +++ b/examples/dfp/v201508/base_rate_service/get_all_base_rates.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2015 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 base rates. + +To create product base rates, run create_product_base_rates.py +To create product template base rates, run +create_product_template_base_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201508') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get base rates by statement. + while True: + response = base_rate_service.getBaseRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for base_rate in response['results']: + print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' + 'rate card ID \'%s\' was found.' % ( + base_rate['id'], + dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201508/base_rate_service/get_base_rates_for_a_rate_card.py new file mode 100755 index 00000000..b3ed2345 --- /dev/null +++ b/examples/dfp/v201508/base_rate_service/get_base_rates_for_a_rate_card.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# +# Copyright 2015 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 base rates. + +To create product base rates, run create_product_base_rates.py +To create product template base rates, run +create_product_template_base_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201508') + + # Create a filter statement for base rates for a single rate card. + values = [{ + 'key': 'rateCardId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': rate_card_id + } + }] + query = 'where rateCardId = :rateCardId ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + # Get base rates by statement. + while True: + response = base_rate_service.getBaseRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for base_rate in response['results']: + print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' + 'rate card ID \'%s\' was found.' % ( + base_rate['id'], + dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201508/base_rate_service/update_base_rates.py b/examples/dfp/v201508/base_rate_service/update_base_rates.py new file mode 100755 index 00000000..7ae1882f --- /dev/null +++ b/examples/dfp/v201508/base_rate_service/update_base_rates.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a base rate's value. + +To determine which base rates exist, run get_all_base_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' + + +def main(client, base_rate_id): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201508') + + # Create a filter statement for base rates for a single rate card. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': base_rate_id + } + }] + query = 'where id = :id ORDER BY id ASC' + statement = dfp.FilterStatement(query, values, 1) + + # Get single base rate by statement. + response = base_rate_service.getBaseRatesByStatement( + statement.ToStatement()) + + if 'results' in response: + # Update each local base rate object by changing its value to $3 USD. + new_rate = { + 'currencyCode': 'USD', + 'microAmount': 3000000 + } + + updated_base_rates = [] + for base_rate in response['results']: + base_rate['rate'] = new_rate + updated_base_rates.append(base_rate) + + # Update base rates remotely. + base_rates = base_rate_service.updateBaseRates(updated_base_rates) + + # Display results. + if base_rates: + for base_rate in base_rates: + print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' + 'rate card ID \'%s\' was updated.' % ( + base_rate['id'], + dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) + else: + print 'No base rates were updated.' + else: + print 'No base rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, BASE_RATE_ID) diff --git a/examples/dfp/v201508/company_service/__init__.py b/examples/dfp/v201508/company_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/company_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/company_service/create_companies.py b/examples/dfp/v201508/company_service/create_companies.py similarity index 91% rename from examples/dfp/v201408/company_service/create_companies.py rename to examples/dfp/v201508/company_service/create_companies.py index ff233ef8..43a43c2a 100755 --- a/examples/dfp/v201408/company_service/create_companies.py +++ b/examples/dfp/v201508/company_service/create_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.createCompanies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -37,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201408') + company_service = client.GetService('CompanyService', version='v201508') # Create company objects. companies = [ diff --git a/examples/dfp/v201408/company_service/get_advertisers.py b/examples/dfp/v201508/company_service/get_advertisers.py similarity index 92% rename from examples/dfp/v201408/company_service/get_advertisers.py rename to examples/dfp/v201508/company_service/get_advertisers.py index 7d359119..487f099f 100755 --- a/examples/dfp/v201408/company_service/get_advertisers.py +++ b/examples/dfp/v201508/company_service/get_advertisers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.getCompaniesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201408') + company_service = client.GetService('CompanyService', version='v201508') # Create statement object to only select companies that are advertisers. values = [{ diff --git a/examples/dfp/v201408/company_service/get_all_companies.py b/examples/dfp/v201508/company_service/get_all_companies.py similarity index 91% rename from examples/dfp/v201408/company_service/get_all_companies.py rename to examples/dfp/v201508/company_service/get_all_companies.py index e5b4f560..3500c1e1 100755 --- a/examples/dfp/v201408/company_service/get_all_companies.py +++ b/examples/dfp/v201508/company_service/get_all_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.getCompaniesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201408') + company_service = client.GetService('CompanyService', version='v201508') # Create statement object to select all companies. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/company_service/update_companies.py b/examples/dfp/v201508/company_service/update_companies.py similarity index 93% rename from examples/dfp/v201408/company_service/update_companies.py rename to examples/dfp/v201508/company_service/update_companies.py index fb986270..59ee492d 100755 --- a/examples/dfp/v201408/company_service/update_companies.py +++ b/examples/dfp/v201508/company_service/update_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CompanyService.updateCompanies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -38,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201408') + company_service = client.GetService('CompanyService', version='v201508') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201508/contact_service/__init__.py b/examples/dfp/v201508/contact_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/contact_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/contact_service/create_contacts.py b/examples/dfp/v201508/contact_service/create_contacts.py similarity index 93% rename from examples/dfp/v201408/contact_service/create_contacts.py rename to examples/dfp/v201508/contact_service/create_contacts.py index b453eae9..4ddd1abf 100755 --- a/examples/dfp/v201408/contact_service/create_contacts.py +++ b/examples/dfp/v201508/contact_service/create_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.createContacts """ -__author__ = ('Vincent Tsao', - 'Joseph DiLallo') import uuid @@ -43,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201408') + contact_service = client.GetService('ContactService', version='v201508') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201408/contact_service/get_all_contacts.py b/examples/dfp/v201508/contact_service/get_all_contacts.py similarity index 91% rename from examples/dfp/v201408/contact_service/get_all_contacts.py rename to examples/dfp/v201508/contact_service/get_all_contacts.py index d258a5f0..fc089821 100755 --- a/examples/dfp/v201408/contact_service/get_all_contacts.py +++ b/examples/dfp/v201508/contact_service/get_all_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201408') + contact_service = client.GetService('ContactService', version='v201508') # Create statement object to get all contacts. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/contact_service/get_uninvited_contacts.py b/examples/dfp/v201508/contact_service/get_uninvited_contacts.py similarity index 92% rename from examples/dfp/v201408/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201508/contact_service/get_uninvited_contacts.py index 42765bff..5ac7d861 100755 --- a/examples/dfp/v201408/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201508/contact_service/get_uninvited_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,10 +23,7 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -34,7 +31,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201408') + contact_service = client.GetService('ContactService', version='v201508') # Create statement object to only select contacts that are uninvited. values = [{ diff --git a/examples/dfp/v201408/contact_service/update_contacts.py b/examples/dfp/v201508/contact_service/update_contacts.py similarity index 91% rename from examples/dfp/v201408/contact_service/update_contacts.py rename to examples/dfp/v201508/contact_service/update_contacts.py index 9d6adea4..a0c17015 100755 --- a/examples/dfp/v201408/contact_service/update_contacts.py +++ b/examples/dfp/v201508/contact_service/update_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContactService.updateContacts - ContactService.getContactsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -39,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201408') + contact_service = client.GetService('ContactService', version='v201508') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201508/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201508/content_metadata_key_hierarchy_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/content_metadata_key_hierarchy_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201508/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201408/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201508/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 31864b23..cf3a5319 100755 --- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201508/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,11 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.createContentMetadataKeyHierarchies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -45,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201408') + 'ContentMetadataKeyHierarchyService', version='v201508') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201508/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 89% rename from examples/dfp/v201408/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201508/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 171915fb..1076efbb 100755 --- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201508/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,12 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement - ContentMetadataKeyHierarchyService.perfomContentMetadataKeyHierarchyAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -44,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201408') + 'ContentMetadataKeyHierarchyService', version='v201508') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201508/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 89% rename from examples/dfp/v201408/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201508/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 09dbd412..7797e571 100755 --- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201508/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201408') + 'ContentMetadataKeyHierarchyService', version='v201508') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201508/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201408/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201508/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 17bdab6f..ff23e47c 100755 --- a/examples/dfp/v201408/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201508/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,12 +26,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement - ContentMetadataKeyHierarchyService.updateContentMetadataKeyHierarchies """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -46,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201408') + 'ContentMetadataKeyHierarchyService', version='v201508') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201508/content_service/__init__.py b/examples/dfp/v201508/content_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/content_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/content_service/get_all_content.py b/examples/dfp/v201508/content_service/get_all_content.py similarity index 91% rename from examples/dfp/v201408/content_service/get_all_content.py rename to examples/dfp/v201508/content_service/get_all_content.py index 589a8c78..6c4e5499 100755 --- a/examples/dfp/v201408/content_service/get_all_content.py +++ b/examples/dfp/v201508/content_service/get_all_content.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentService.getContentByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201408') + content_service = client.GetService('ContentService', version='v201508') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/content_service/get_content_by_category.py b/examples/dfp/v201508/content_service/get_content_by_category.py similarity index 94% rename from examples/dfp/v201408/content_service/get_content_by_category.py rename to examples/dfp/v201508/content_service/get_content_by_category.py index fb8beb68..ba20d5a9 100755 --- a/examples/dfp/v201408/content_service/get_content_by_category.py +++ b/examples/dfp/v201508/content_service/get_content_by_category.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: ContentService.getContentByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,10 +33,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201408') - network_service = client.GetService('NetworkService', version='v201408') + content_service = client.GetService('ContentService', version='v201508') + network_service = client.GetService('NetworkService', version='v201508') custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') # Get the network's content browse custom targeting key. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201508/creative_service/__init__.py b/examples/dfp/v201508/creative_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/creative_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/creative_service/create_creative_from_template.py b/examples/dfp/v201508/creative_service/create_creative_from_template.py similarity index 91% rename from examples/dfp/v201408/creative_service/create_creative_from_template.py rename to examples/dfp/v201508/creative_service/create_creative_from_template.py index b340d78a..3107d975 100755 --- a/examples/dfp/v201408/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201508/creative_service/create_creative_from_template.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreative """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os @@ -44,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201408') + creative_service = client.GetService('CreativeService', version='v201508') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' @@ -90,12 +87,12 @@ def main(client, advertiser_id): } # Call service to create the creative. - creative = creative_service.createCreative(creative) + creative = creative_service.createCreatives([creative])[0] # Display results. print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201408/creative_service/create_creatives.py b/examples/dfp/v201508/creative_service/create_creatives.py similarity index 91% rename from examples/dfp/v201408/creative_service/create_creatives.py rename to examples/dfp/v201508/creative_service/create_creatives.py index e0cbc5ee..008ac0e2 100755 --- a/examples/dfp/v201408/creative_service/create_creatives.py +++ b/examples/dfp/v201508/creative_service/create_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreatives """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os @@ -43,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201408') + creative_service = client.GetService('CreativeService', version='v201508') # Create creative objects. creatives = [] @@ -85,7 +82,7 @@ def main(client, advertiser_id): for creative in creatives: print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201408/creative_service/create_custom_creative.py b/examples/dfp/v201508/creative_service/create_custom_creative.py similarity index 92% rename from examples/dfp/v201408/creative_service/create_custom_creative.py rename to examples/dfp/v201508/creative_service/create_custom_creative.py index 2ac6f38f..0e2dd500 100755 --- a/examples/dfp/v201408/creative_service/create_custom_creative.py +++ b/examples/dfp/v201508/creative_service/create_custom_creative.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.createCreative """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import base64 import os @@ -44,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201408') + creative_service = client.GetService('CreativeService', version='v201508') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', @@ -81,7 +78,7 @@ def main(client, advertiser_id): if creative: print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201508/creative_service/create_native_creative.py b/examples/dfp/v201508/creative_service/create_native_creative.py new file mode 100755 index 00000000..6dedd04c --- /dev/null +++ b/examples/dfp/v201508/creative_service/create_native_creative.py @@ -0,0 +1,138 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates a new native creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. + +The code in this example will use app data from the Google sample app +'Pie Noon': + +https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import urllib2 +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' +ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO' + 'PYnTdOQGaSpGSEZflIFs0iw=h300') +APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp' + 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300') + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201508') + + # Use the system defined native app install creative template. + creative_template_id = '10004400' + + image_data = urllib2.urlopen(ICON_URL).read() + image_data = base64.b64encode(image_data) + + app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() + app_icon_data = base64.b64encode(app_icon_data) + + # Create creative from templates. + creative = { + 'xsi_type': 'TemplateCreative', + 'name': 'Native Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '1', 'height': '1', 'isAspectRatio': False}, + 'creativeTemplateId': creative_template_id, + 'destinationUrl': ('https://play.google.com/store/apps/details?id=' + 'com.google.fpl.pie_noon'), + 'isNativeEligible': True, + 'creativeTemplateVariableValues': [ + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Image', + 'assetByteArray': image_data, + 'fileName': 'file%s.png' % uuid.uuid4() + }, + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Appicon', + 'assetByteArray': app_icon_data, + 'fileName': 'appicon%s.png' % uuid.uuid4() + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Price', + 'value': 'Free' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Calltoaction', + 'value': 'Install' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Starrating', + 'value': '4' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Store', + 'value': 'Google Play' + }, + { + 'xsi_type': 'UrlCreativeTemplateVariableValue', + 'uniqueName': 'DeeplinkclickactionURL', + 'value': 'market://details?id=com.google.fpl.pie_noon' + }, + { + 'xsi_type': 'UrlCreativeTemplateVariableValue', + 'uniqueName': 'FallbackclickactionURL', + 'value': ('https://play.google.com/store/apps/details?id=' + 'com.google.fpl.pie_noon'), + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Body', + 'value': 'Try multi-screen mode!' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Headline', + 'value': 'Pie Noon' + } + ] + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print ('Native creative with id \'%s\' and name \'%s\' was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], creative['previewUrl'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201408/creative_service/get_all_creatives.py b/examples/dfp/v201508/creative_service/get_all_creatives.py similarity index 89% rename from examples/dfp/v201408/creative_service/get_all_creatives.py rename to examples/dfp/v201508/creative_service/get_all_creatives.py index 40c2eecf..d0a3d68c 100755 --- a/examples/dfp/v201408/creative_service/get_all_creatives.py +++ b/examples/dfp/v201508/creative_service/get_all_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201408') + creative_service = client.GetService('CreativeService', version='v201508') # Create statement object to select all creatives. statement = dfp.FilterStatement() @@ -49,7 +46,7 @@ def main(client): for creative in response['results']: print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'found.' % (creative['id'], creative['name'], - creative['Creative.Type'])) + dfp.DfpClassType(creative))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201408/creative_service/get_creatives_by_statement.py b/examples/dfp/v201508/creative_service/get_creatives_by_statement.py similarity index 90% rename from examples/dfp/v201408/creative_service/get_creatives_by_statement.py rename to examples/dfp/v201508/creative_service/get_creatives_by_statement.py index 8f7eeb90..83093abd 100755 --- a/examples/dfp/v201408/creative_service/get_creatives_by_statement.py +++ b/examples/dfp/v201508/creative_service/get_creatives_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201408') + creative_service = client.GetService('CreativeService', version='v201508') # Create statement object to only select image creatives. values = [{ @@ -59,7 +56,7 @@ def main(client): for creative in creatives: print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'found.' % (creative['id'], creative['name'], - creative['Creative.Type'])) + dfp.DfpClassType(creative))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201408/creative_service/update_creatives.py b/examples/dfp/v201508/creative_service/update_creatives.py similarity index 92% rename from examples/dfp/v201408/creative_service/update_creatives.py rename to examples/dfp/v201508/creative_service/update_creatives.py index 66d44519..9a10daf2 100755 --- a/examples/dfp/v201408/creative_service/update_creatives.py +++ b/examples/dfp/v201508/creative_service/update_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeService.updateCreatives - CreativeService.getCreativesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -38,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201408') + creative_service = client.GetService('CreativeService', version='v201508') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201508/creative_set_service/__init__.py b/examples/dfp/v201508/creative_set_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/creative_set_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201508/creative_set_service/associate_creative_set_to_line_item.py similarity index 88% rename from examples/dfp/v201408/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201508/creative_set_service/associate_creative_set_to_line_item.py index 1a518581..d2b997f3 100755 --- a/examples/dfp/v201408/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201508/creative_set_service/associate_creative_set_to_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: LineItemCreativeAssociationService.createLineItemCreativeAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -41,7 +38,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201408') + 'LineItemCreativeAssociationService', version='v201508') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201408/creative_set_service/create_creative_set.py b/examples/dfp/v201508/creative_set_service/create_creative_set.py similarity index 90% rename from examples/dfp/v201408/creative_set_service/create_creative_set.py rename to examples/dfp/v201508/creative_set_service/create_creative_set.py index 9ece07f8..16789024 100755 --- a/examples/dfp/v201408/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201508/creative_set_service/create_creative_set.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.createCreativeSet """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -41,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201408') + version='v201508') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201408/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201508/creative_set_service/get_all_creative_sets.py similarity index 89% rename from examples/dfp/v201408/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201508/creative_set_service/get_all_creative_sets.py index 701e9c98..a03667c9 100755 --- a/examples/dfp/v201408/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201508/creative_set_service/get_all_creative_sets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201408') + version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201508/creative_set_service/get_creative_sets_by_statement.py similarity index 91% rename from examples/dfp/v201408/creative_set_service/get_creative_sets_by_statement.py rename to examples/dfp/v201508/creative_set_service/get_creative_sets_by_statement.py index 5c668485..0d89cba7 100755 --- a/examples/dfp/v201408/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201508/creative_set_service/get_creative_sets_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -38,7 +35,7 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201408') + version='v201508') # Create statement object to only select creative sets that have the given # master creative. diff --git a/examples/dfp/v201408/creative_set_service/update_creative_set.py b/examples/dfp/v201508/creative_set_service/update_creative_set.py similarity index 90% rename from examples/dfp/v201408/creative_set_service/update_creative_set.py rename to examples/dfp/v201508/creative_set_service/update_creative_set.py index 963213d2..3975a354 100755 --- a/examples/dfp/v201408/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201508/creative_set_service/update_creative_set.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeSetService.updateCreativeSet - CreativeSetService.getCreativeSetsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -41,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201408') + version='v201508') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201508/creative_template_service/__init__.py b/examples/dfp/v201508/creative_template_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/creative_template_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201508/creative_template_service/get_all_creative_templates.py similarity index 89% rename from examples/dfp/v201408/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201508/creative_template_service/get_all_creative_templates.py index dc055d22..7d7a40fb 100755 --- a/examples/dfp/v201408/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201508/creative_template_service/get_all_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeTemplateService.getCreativeTemplatesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -34,7 +31,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201408') + 'CreativeTemplateService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201508/creative_template_service/get_creative_templates_by_statement.py similarity index 90% rename from examples/dfp/v201408/creative_template_service/get_creative_templates_by_statement.py rename to examples/dfp/v201508/creative_template_service/get_creative_templates_by_statement.py index 49095751..7c825ac7 100755 --- a/examples/dfp/v201408/creative_template_service/get_creative_templates_by_statement.py +++ b/examples/dfp/v201508/creative_template_service/get_creative_templates_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -21,11 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeTemplateService.getCreativeTemplatesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -34,7 +31,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201408') + 'CreativeTemplateService', version='v201508') # Create statement object to only select system defined creative templates. values = [{ diff --git a/examples/dfp/v201408/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201508/creative_wrapper_service/create_creative_wrappers.py similarity index 90% rename from examples/dfp/v201408/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201508/creative_wrapper_service/create_creative_wrappers.py index a214487a..e68bc21a 100755 --- a/examples/dfp/v201408/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201508/creative_wrapper_service/create_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.createCreativeWrappers """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -40,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201408') + version='v201508') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201408/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201508/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 90% rename from examples/dfp/v201408/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201508/creative_wrapper_service/deactivate_creative_wrapper.py index e17cd42c..3575b2d0 100755 --- a/examples/dfp/v201408/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201508/creative_wrapper_service/deactivate_creative_wrapper.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -21,12 +21,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrapperByStatement -Tags: CreativeWrapperService.performCreativeWrapperAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -37,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201408') + version='v201508') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201408/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201508/creative_wrapper_service/get_active_creative_wrappers.py similarity index 89% rename from examples/dfp/v201408/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201508/creative_wrapper_service/get_active_creative_wrappers.py index 08e1271e..399f3b5b 100755 --- a/examples/dfp/v201408/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201508/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201408') + version='v201508') # Create statement object to only select active creative wrappers. values = [{ diff --git a/examples/dfp/v201408/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201508/creative_wrapper_service/get_all_creative_wrappers.py similarity index 88% rename from examples/dfp/v201408/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201508/creative_wrapper_service/get_all_creative_wrappers.py index 04db6e88..aabc2352 100755 --- a/examples/dfp/v201408/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201508/creative_wrapper_service/get_all_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201408') + version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201508/creative_wrapper_service/update_creative_wrappers.py similarity index 89% rename from examples/dfp/v201408/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201508/creative_wrapper_service/update_creative_wrappers.py index 230fc1e3..ad59b9fd 100755 --- a/examples/dfp/v201408/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201508/creative_wrapper_service/update_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CreativeWrapperService.getCreativeWrappersByStatement -Tags: CreativeWrapperService.updateCreativeWrappers """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -40,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201408') + version='v201508') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201508/custom_field_service/__init__.py b/examples/dfp/v201508/custom_field_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/custom_field_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/custom_field_service/create_custom_field_options.py b/examples/dfp/v201508/custom_field_service/create_custom_field_options.py similarity index 91% rename from examples/dfp/v201408/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201508/custom_field_service/create_custom_field_options.py index c26ab0e6..b0a564e9 100755 --- a/examples/dfp/v201408/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201508/custom_field_service/create_custom_field_options.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.createCustomFieldOptions """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -41,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201408') + 'CustomFieldService', version='v201508') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201408/custom_field_service/create_custom_fields.py b/examples/dfp/v201508/custom_field_service/create_custom_fields.py similarity index 90% rename from examples/dfp/v201408/custom_field_service/create_custom_fields.py rename to examples/dfp/v201508/custom_field_service/create_custom_fields.py index 3c3c0dee..6ed440fe 100755 --- a/examples/dfp/v201408/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201508/custom_field_service/create_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.createCustomFields """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -38,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201408') + 'CustomFieldService', version='v201508') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201408/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201508/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 91% rename from examples/dfp/v201408/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201508/custom_field_service/deactivate_all_line_item_custom_fields.py index 556949d3..8b95be8a 100755 --- a/examples/dfp/v201408/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201508/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement -Tags: CustomFieldService.performCustomFieldAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -37,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201408') + 'CustomFieldService', version='v201508') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201408/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201508/custom_field_service/get_all_custom_fields.py similarity index 89% rename from examples/dfp/v201408/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201508/custom_field_service/get_all_custom_fields.py index 0a239cf8..74fc1e6f 100755 --- a/examples/dfp/v201408/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201508/custom_field_service/get_all_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201408') + 'CustomFieldService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201508/custom_field_service/get_all_line_item_custom_fields.py similarity index 90% rename from examples/dfp/v201408/custom_field_service/get_all_line_item_custom_fields.py rename to examples/dfp/v201508/custom_field_service/get_all_line_item_custom_fields.py index 303e0dc3..c0a4b4f6 100755 --- a/examples/dfp/v201408/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201508/custom_field_service/get_all_line_item_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201408') + 'CustomFieldService', version='v201508') # Create statement to select only custom fields that apply to line items. values = [{ diff --git a/examples/dfp/v201408/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201508/custom_field_service/set_line_item_custom_field_value.py similarity index 92% rename from examples/dfp/v201408/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201508/custom_field_service/set_line_item_custom_field_value.py index 205d147b..8fb51fe1 100755 --- a/examples/dfp/v201408/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201508/custom_field_service/set_line_item_custom_field_value.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.getCustomFieldsByStatement - LineItemService.getLineItemsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -46,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201408') + 'CustomFieldService', version='v201508') - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # Create statement to get a custom field. custom_field_values = [{ @@ -139,11 +135,11 @@ def main(client, custom_field_id, drop_down_custom_field_id, for line_item in line_items: custom_field_value_strings = [] for value in line_item['customFieldValues']: - if value['BaseCustomFieldValue.Type'] == 'CustomFieldValue': + if dfp.DfpClassType(value) == 'CustomFieldValue': custom_field_value_string = ( '{ID: \'%s\', value: \'%s\'}' % (value['customFieldId'], value['value']['value'])) - elif value['BaseCustomFieldValue.Type'] == 'DropDownCustomFieldValue': + elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( '{ID: \'%s\', custom field option ID: \'%s\'}' % (value['customFieldId'], value['customFieldOptionId'])) diff --git a/examples/dfp/v201408/custom_field_service/update_custom_fields.py b/examples/dfp/v201508/custom_field_service/update_custom_fields.py similarity index 90% rename from examples/dfp/v201408/custom_field_service/update_custom_fields.py rename to examples/dfp/v201508/custom_field_service/update_custom_fields.py index 01620256..80e6d5df 100755 --- a/examples/dfp/v201408/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201508/custom_field_service/update_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomFieldService.updateCustomFields - CustomFieldService.getCustomFieldByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -40,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201408') + 'CustomFieldService', version='v201508') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201508/custom_targeting_service/__init__.py b/examples/dfp/v201508/custom_targeting_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/custom_targeting_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201508/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 93% rename from examples/dfp/v201408/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201508/custom_targeting_service/create_custom_targeting_keys_and_values.py index 5e5468b3..c2c81306 100755 --- a/examples/dfp/v201408/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201508/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.createCustomTargetingKeys - CustomTargetingService.createCustomTargetingValues """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -39,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_keys.py similarity index 91% rename from examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_keys.py index 3e53a959..38214918 100755 --- a/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_keys.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.getCustomTargetingKeysByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -39,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') values = [{ 'key': 'name', diff --git a/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_values.py similarity index 92% rename from examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_values.py index c7b3ba97..5044d18d 100755 --- a/examples/dfp/v201408/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,11 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: CustomTargetingService.getCustomTargetingValuesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -40,7 +37,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201508/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 94% rename from examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201508/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 0440a514..32cc075e 100755 --- a/examples/dfp/v201408/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201508/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create custom targeting keys and values, run create_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') # Create statement to get all targeting keys. targeting_key_statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_keys_by_statement.py similarity index 91% rename from examples/dfp/v201408/custom_targeting_service/get_custom_targeting_keys_by_statement.py rename to examples/dfp/v201508/custom_targeting_service/get_custom_targeting_keys_by_statement.py index f108e71f..b8b6b58a 100755 --- a/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_keys_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create custom targeting keys, run create_custom_targeting_keys_and_values.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') values = [{ 'key': 'type', diff --git a/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_values_by_statement.py similarity index 92% rename from examples/dfp/v201408/custom_targeting_service/get_custom_targeting_values_by_statement.py rename to examples/dfp/v201508/custom_targeting_service/get_custom_targeting_values_by_statement.py index 04eed247..441b501c 100755 --- a/examples/dfp/v201408/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ b/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_values_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -21,8 +21,6 @@ create_custom_targeting_keys_and_values.py. To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -33,7 +31,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201508/custom_targeting_service/update_custom_targeting_keys.py similarity index 93% rename from examples/dfp/v201408/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201508/custom_targeting_service/update_custom_targeting_keys.py index 6adfc325..a7d52b61 100755 --- a/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201508/custom_targeting_service/update_custom_targeting_keys.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -31,7 +29,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201508/custom_targeting_service/update_custom_targeting_values.py similarity index 93% rename from examples/dfp/v201408/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201508/custom_targeting_service/update_custom_targeting_values.py index a0e444bc..bc874204 100755 --- a/examples/dfp/v201408/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201508/custom_targeting_service/update_custom_targeting_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,8 +20,6 @@ To determine which custom targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -32,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201408') + 'CustomTargetingService', version='v201508') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201508/exchange_rate_service/__init__.py b/examples/dfp/v201508/exchange_rate_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/exchange_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201508/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201508/exchange_rate_service/create_exchange_rates.py new file mode 100755 index 00000000..6e2d1491 --- /dev/null +++ b/examples/dfp/v201508/exchange_rate_service/create_exchange_rates.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates an exchange rate. + +To determine which exchange rates exist, run get_all_exchange_rates.py. + + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201508') + + # Create a new fixed exchange rate with currency code 'AUD', with direction + # FROM_NETWORK with a value of 1.5. + exchange_rate = { + 'currencyCode': 'AUD', + 'direction': 'FROM_NETWORK', + 'exchangeRate': long(15000000000), + 'refreshRate': 'FIXED' + } + + created_exchange_rate = exchange_rate_service.createExchangeRates( + [exchange_rate])[0] + + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was created.' % (created_exchange_rate['id'], + created_exchange_rate['currencyCode'], + created_exchange_rate['direction'], + (float(created_exchange_rate['exchangeRate']) / + 10000000000))) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201508/exchange_rate_service/get_all_exchange_rates.py new file mode 100755 index 00000000..9049d7a9 --- /dev/null +++ b/examples/dfp/v201508/exchange_rate_service/get_all_exchange_rates.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all exchange rates. + +To create exchange rates, run create_exchange_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201508') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get all exchange rates by statement. + while True: + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for exchange_rate in response['results']: + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was found.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201508/exchange_rate_service/get_exchange_rates_by_currency_code.py new file mode 100755 index 00000000..2a354485 --- /dev/null +++ b/examples/dfp/v201508/exchange_rate_service/get_exchange_rates_by_currency_code.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the exchange rate for a specific currency code. + +To create exchange rates, run create_exchange_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' + + +def main(client, currency_code): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201508') + + # Create a statement to get exchange rates for the specified currency code. + values = [{ + 'key': 'currencyCode', + 'value': { + 'xsi_type': 'TextValue', + 'value': currency_code + } + }] + query = 'WHERE currencyCode = :currencyCode' + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + + # Get rate cards by statement. + while True: + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for exchange_rate in response['results']: + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was found.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, CURRENCY_CODE) diff --git a/examples/dfp/v201508/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201508/exchange_rate_service/update_exchange_rates.py new file mode 100755 index 00000000..395fa493 --- /dev/null +++ b/examples/dfp/v201508/exchange_rate_service/update_exchange_rates.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates the value of an exchange rate. + +To create exchange rates, run create_exchange_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' + + +def main(client, exchange_rate_id): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201508') + + # Create a statement to get an exchange rate by its ID. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': exchange_rate_id + } + }] + query = 'WHERE id = :id' + # Create a filter statement. + statement = dfp.FilterStatement(query, values, 1) + + # Get rate cards by statement. + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + + if 'results' in response: + exchange_rate = response['results'][0] + + # Update the exchange rate value to 1.5. + exchange_rate['exchangeRate'] = long(15000000000) + + exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) + + if exchange_rates: + for exchange_rate in exchange_rates: + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was updated.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) + else: + print 'No exchange rates were updated.' + else: + print 'No exchange rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, EXCHANGE_RATE_ID) diff --git a/examples/dfp/v201408/forecast_service/get_forecast.py b/examples/dfp/v201508/forecast_service/get_availability_forecast.py similarity index 63% rename from examples/dfp/v201408/forecast_service/get_forecast.py rename to examples/dfp/v201508/forecast_service/get_availability_forecast.py index c5909472..f4b10c02 100755 --- a/examples/dfp/v201408/forecast_service/get_forecast.py +++ b/examples/dfp/v201508/forecast_service/get_availability_forecast.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -14,31 +14,44 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets a forecast for a prospective line item. +"""This example gets a forecast for a prospective line item. -To determine which placements exist, run get_all_placements.py.""" +The prospective line item targets the entire network. The targeting can be +modified to determine forecasts for other criteria such as custom criteria +targeting (in addition to targeting the whole network). See +create_line_items.py for an example of how to create more complex targeting. + +""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date # Import appropriate modules from the client library. from googleads import dfp -# Set the placement that the prospective line item will target. -TARGET_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE'] +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -def main(client, target_placement_ids): +def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201408') + forecast_service = client.GetService('ForecastService', version='v201508') + network_service = client.GetService('NetworkService', version='v201508') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] # Create prospective line item. line_item = { 'targeting': { 'inventoryTargeting': { - 'targetedPlacementIds': target_placement_ids + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] } }, 'creativePlaceholders': [ @@ -65,7 +78,8 @@ def main(client, target_placement_ids): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/New_York' }, 'costType': 'CPM', 'costPerUnit': { @@ -82,8 +96,20 @@ def main(client, target_placement_ids): 'discountType': 'PERCENTAGE', } + prospective_line_item = { + 'lineItem': line_item, + 'advertiserId': advertiser_id + } + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } + # Get forecast. - forecast = forecast_service.getForecast(line_item) + forecast = forecast_service.getAvailabilityForecast( + prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) available_percent = (((long(forecast['availableUnits'])/ (matched * 1.0)) * 100) @@ -96,11 +122,11 @@ def main(client, target_placement_ids): print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) print '%d contending line items.' % len(contending_line_items) - if 'possibleUnits' in forecast: + if 'possibleUnits' in forecast and matched: possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TARGET_PLACEMENT_IDS) + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201408/forecast_service/get_forecast_by_id.py b/examples/dfp/v201508/forecast_service/get_availability_forecast_for_line_item.py similarity index 76% rename from examples/dfp/v201408/forecast_service/get_forecast_by_id.py rename to examples/dfp/v201508/forecast_service/get_availability_forecast_for_line_item.py index c8d4263c..9d3300d3 100755 --- a/examples/dfp/v201408/forecast_service/get_forecast_by_id.py +++ b/examples/dfp/v201508/forecast_service/get_availability_forecast_for_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -14,26 +14,33 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets a forecast for an existing line item. +"""This code example gets an availability forecast for an existing line item. -To determine which line items exist, run get_all_line_items.py.""" +To determine which line items exist, run get_all_line_items.py. + +""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp # Set the line item to get a forecast for. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID' +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201408') + forecast_service = client.GetService('ForecastService', version='v201508') + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } # Get forecast for line item. - forecast = forecast_service.getForecastById(line_item_id) + forecast = forecast_service.getAvailabilityForecastById( + line_item_id, forecast_options) matched = long(forecast['matchedUnits']) available_percent = (((long(forecast['availableUnits'])/ (matched * 1.0)) * 100) @@ -46,7 +53,7 @@ def main(client, line_item_id): print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) print '%d contending line items.' % len(contending_line_items) - if 'possibleUnits' in forecast: + if 'possibleUnits' in forecast and matched: possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) diff --git a/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py new file mode 100755 index 00000000..46742580 --- /dev/null +++ b/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets a delivery forecast for two existing line items. + +To determine which line items exist, run get_all_line_items.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the line items to get forecasts for. +LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_ID_1_HERE' +LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_ID_2_HERE' + + +def main(client, line_item_id1, line_item_id2): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201508') + + # Get forecast for line item. + forecast = forecast_service.getDeliveryForecastByIds( + [line_item_id1, line_item_id2], None) + + for single_forecast in forecast['lineItemDeliveryForecasts']: + unit_type = single_forecast['unitType'] + print ('Forecast for line item %d:%n%t%d %s matched%n%t%d %s delivered%n%t' + '%d %s predicted%n' % ( + single_forecast['lineItemId'], single_forecast['matchedUnits'], + unit_type, single_forecast['deliveredUnits'], unit_type, + single_forecast['predictedDeliveryUnits'], unit_type)) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201508/inventory_service/__init__.py b/examples/dfp/v201508/inventory_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/inventory_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/inventory_service/archive_ad_units.py b/examples/dfp/v201508/inventory_service/archive_ad_units.py similarity index 93% rename from examples/dfp/v201408/inventory_service/archive_ad_units.py rename to examples/dfp/v201508/inventory_service/archive_ad_units.py index 86518875..f4783b96 100755 --- a/examples/dfp/v201408/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201508/inventory_service/archive_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -38,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201408') + inventory_service = client.GetService('InventoryService', version='v201508') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201408/inventory_service/create_ad_units.py b/examples/dfp/v201508/inventory_service/create_ad_units.py similarity index 92% rename from examples/dfp/v201408/inventory_service/create_ad_units.py rename to examples/dfp/v201508/inventory_service/create_ad_units.py index 1061837d..79711a46 100755 --- a/examples/dfp/v201408/inventory_service/create_ad_units.py +++ b/examples/dfp/v201508/inventory_service/create_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.createAdUnits """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -39,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201408') + inventory_service = client.GetService('InventoryService', version='v201508') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201408/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201508/inventory_service/get_ad_unit_hierarchy.py similarity index 95% rename from examples/dfp/v201408/inventory_service/get_ad_unit_hierarchy.py rename to examples/dfp/v201508/inventory_service/get_ad_unit_hierarchy.py index b3469245..ea5072fe 100755 --- a/examples/dfp/v201408/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201508/inventory_service/get_ad_unit_hierarchy.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201408') + inventory_service = client.GetService('InventoryService', version='v201508') statement = dfp.FilterStatement() all_ad_units = [] diff --git a/examples/dfp/v201408/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201508/inventory_service/get_all_ad_unit_sizes.py similarity index 90% rename from examples/dfp/v201408/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201508/inventory_service/get_all_ad_unit_sizes.py index 180c781f..0f18d439 100755 --- a/examples/dfp/v201408/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201508/inventory_service/get_all_ad_unit_sizes.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitSizesByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201408') + inventory_service = client.GetService('InventoryService', version='v201508') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201408/inventory_service/get_all_ad_units.py b/examples/dfp/v201508/inventory_service/get_all_ad_units.py similarity index 91% rename from examples/dfp/v201408/inventory_service/get_all_ad_units.py rename to examples/dfp/v201508/inventory_service/get_all_ad_units.py index 6b8cfb52..5a8877ad 100755 --- a/examples/dfp/v201408/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201508/inventory_service/get_all_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201408') + inventory_service = client.GetService('InventoryService', version='v201508') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201408/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201508/inventory_service/get_top_level_ad_units.py similarity index 92% rename from examples/dfp/v201408/inventory_service/get_top_level_ad_units.py rename to examples/dfp/v201508/inventory_service/get_top_level_ad_units.py index a32e7e12..3c1fead9 100755 --- a/examples/dfp/v201408/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201508/inventory_service/get_top_level_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnitsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,8 +32,8 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201408') - network_service = client.GetService('NetworkService', version='v201408') + inventory_service = client.GetService('InventoryService', version='v201508') + network_service = client.GetService('NetworkService', version='v201508') root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201408/inventory_service/update_ad_units.py b/examples/dfp/v201508/inventory_service/update_ad_units.py similarity index 93% rename from examples/dfp/v201408/inventory_service/update_ad_units.py rename to examples/dfp/v201508/inventory_service/update_ad_units.py index 3a19b6ed..2b7dda3e 100755 --- a/examples/dfp/v201408/inventory_service/update_ad_units.py +++ b/examples/dfp/v201508/inventory_service/update_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,12 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: InventoryService.getAdUnit -Tags: InventoryService.updateAdUnits """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -40,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201408') + inventory_service = client.GetService('InventoryService', version='v201508') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201508/label_service/__init__.py b/examples/dfp/v201508/label_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/label_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/label_service/create_labels.py b/examples/dfp/v201508/label_service/create_labels.py similarity index 92% rename from examples/dfp/v201408/label_service/create_labels.py rename to examples/dfp/v201508/label_service/create_labels.py index 96ef8d62..c9f2d4a3 100755 --- a/examples/dfp/v201408/label_service/create_labels.py +++ b/examples/dfp/v201508/label_service/create_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -30,7 +28,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201408') + label_service = client.GetService('LabelService', version='v201508') # Create label objects. labels = [] diff --git a/examples/dfp/v201408/label_service/deactivate_labels.py b/examples/dfp/v201508/label_service/deactivate_labels.py similarity index 94% rename from examples/dfp/v201408/label_service/deactivate_labels.py rename to examples/dfp/v201508/label_service/deactivate_labels.py index 7a2ebc2e..0b71733b 100755 --- a/examples/dfp/v201408/label_service/deactivate_labels.py +++ b/examples/dfp/v201508/label_service/deactivate_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -28,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201408') + label_service = client.GetService('LabelService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201408/label_service/get_all_labels.py b/examples/dfp/v201508/label_service/get_all_labels.py similarity index 92% rename from examples/dfp/v201408/label_service/get_all_labels.py rename to examples/dfp/v201508/label_service/get_all_labels.py index 9faf62ba..85bbecec 100755 --- a/examples/dfp/v201408/label_service/get_all_labels.py +++ b/examples/dfp/v201508/label_service/get_all_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create labels, run create_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -28,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201408') + label_service = client.GetService('LabelService', version='v201508') # Create statement to get all labels statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/label_service/get_labels_by_statement.py b/examples/dfp/v201508/label_service/get_labels_by_statement.py similarity index 93% rename from examples/dfp/v201408/label_service/get_labels_by_statement.py rename to examples/dfp/v201508/label_service/get_labels_by_statement.py index 5d084442..ba3e3be7 100755 --- a/examples/dfp/v201408/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201508/label_service/get_labels_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,8 +20,6 @@ premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201408') + label_service = client.GetService('LabelService', version='v201508') # Create statement to get all labels statement = dfp.FilterStatement('ORDER BY name') diff --git a/examples/dfp/v201408/label_service/update_labels.py b/examples/dfp/v201508/label_service/update_labels.py similarity index 94% rename from examples/dfp/v201408/label_service/update_labels.py rename to examples/dfp/v201508/label_service/update_labels.py index 1873c083..85da0b5d 100755 --- a/examples/dfp/v201408/label_service/update_labels.py +++ b/examples/dfp/v201508/label_service/update_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which labels exist, run get_all_labels.py. This feature is only available to DFP premium solution networks.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201408') + label_service = client.GetService('LabelService', version='v201508') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201508/line_item_creative_association_service/__init__.py b/examples/dfp/v201508/line_item_creative_association_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/line_item_creative_association_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/line_item_creative_association_service/create_licas.py b/examples/dfp/v201508/line_item_creative_association_service/create_licas.py similarity index 90% rename from examples/dfp/v201408/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201508/line_item_creative_association_service/create_licas.py index 283012e1..3380fbac 100755 --- a/examples/dfp/v201408/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201508/line_item_creative_association_service/create_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -33,7 +31,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201408') + 'LineItemCreativeAssociationService', version='v201508') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201408/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201508/line_item_creative_association_service/deactivate_licas.py similarity index 93% rename from examples/dfp/v201408/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201508/line_item_creative_association_service/deactivate_licas.py index 8f968236..7c34795f 100755 --- a/examples/dfp/v201408/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201508/line_item_creative_association_service/deactivate_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -31,7 +29,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201408') + 'LineItemCreativeAssociationService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201408/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201508/line_item_creative_association_service/get_all_licas.py similarity index 91% rename from examples/dfp/v201408/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201508/line_item_creative_association_service/get_all_licas.py index daadf781..f402a933 100755 --- a/examples/dfp/v201408/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201508/line_item_creative_association_service/get_all_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201408') + 'LineItemCreativeAssociationService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201508/line_item_creative_association_service/get_licas_by_statement.py similarity index 92% rename from examples/dfp/v201408/line_item_creative_association_service/get_licas_by_statement.py rename to examples/dfp/v201508/line_item_creative_association_service/get_licas_by_statement.py index 0d7d5814..605df830 100755 --- a/examples/dfp/v201408/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201508/line_item_creative_association_service/get_licas_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create LICAs, run create_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -32,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201408') + 'LineItemCreativeAssociationService', version='v201508') # Create statement object to only select LICAs for the given line item id. values = [{ diff --git a/examples/dfp/v201408/line_item_creative_association_service/update_licas.py b/examples/dfp/v201508/line_item_creative_association_service/update_licas.py similarity index 92% rename from examples/dfp/v201408/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201508/line_item_creative_association_service/update_licas.py index 152d8753..1bc27b6c 100755 --- a/examples/dfp/v201408/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201508/line_item_creative_association_service/update_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which LICAs exist, run get_all_licas.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201408') + 'LineItemCreativeAssociationService', version='v201508') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201508/line_item_service/__init__.py b/examples/dfp/v201508/line_item_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/line_item_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/line_item_service/activate_line_items.py b/examples/dfp/v201508/line_item_service/activate_line_items.py similarity index 95% rename from examples/dfp/v201408/line_item_service/activate_line_items.py rename to examples/dfp/v201508/line_item_service/activate_line_items.py index 291dedd5..e6fa74cc 100755 --- a/examples/dfp/v201408/line_item_service/activate_line_items.py +++ b/examples/dfp/v201508/line_item_service/activate_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -22,8 +22,6 @@ create_licas.py. To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -34,7 +32,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201408/line_item_service/create_line_items.py b/examples/dfp/v201508/line_item_service/create_line_items.py similarity index 97% rename from examples/dfp/v201408/line_item_service/create_line_items.py rename to examples/dfp/v201508/line_item_service/create_line_items.py index 6488b335..e4b656f7 100755 --- a/examples/dfp/v201408/line_item_service/create_line_items.py +++ b/examples/dfp/v201508/line_item_service/create_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,8 +20,6 @@ which orders exist, run get_all_orders.py. To determine which placements exist, run get_all_placements.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date import uuid @@ -37,7 +35,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # Create line item objects. line_items = [] @@ -137,7 +135,8 @@ def main(client, order_id, targeted_placement_ids): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'costType': 'CPM', 'costPerUnit': { diff --git a/examples/dfp/v201408/line_item_service/create_video_line_item.py b/examples/dfp/v201508/line_item_service/create_video_line_item.py similarity index 79% rename from examples/dfp/v201408/line_item_service/create_video_line_item.py rename to examples/dfp/v201508/line_item_service/create_video_line_item.py index da01d296..5e95752e 100755 --- a/examples/dfp/v201408/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201508/line_item_service/create_video_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -22,8 +22,6 @@ create_video_ad_unit.py. To create criteria for categories, run create_custom_targeting_keys_and_values.py""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') from datetime import date import uuid @@ -36,40 +34,30 @@ ORDER_ID = 'INSERT_ORDER_ID_HERE' TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE' -# Set the custom targeting key ID and value ID representing the metadata on the -# content to target. This would typically be a key representing a 'genre' and -# a value representing something like 'comedy'. -CONTENT_CUSTOM_TARGETING_KEY_ID = 'INSERT_CONTENT_CUSTOM_TARGETING_KEY_ID_HERE' +# Set the custom targeting value ID representing the metadata +# on the content to target. This would typically be from a key representing +# a "genre" and the value representing something like "comedy". The value +# must be from a key in a content metadata key hierarchy. CONTENT_CUSTOM_TARGETING_VALUE_ID = \ 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE' def main(client, order_id, targeted_video_ad_unit_id, - content_custom_targeting_key_id, content_custom_targeting_value_id): + content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') - - # create custom criteria for the content metadata targeting. - custom_criteria = { - 'xsi_type': 'CustomCriteria', - 'keyId': content_custom_targeting_key_id, - 'valueIds': [content_custom_targeting_value_id], - 'operator': 'IS' - } - - # Create the custom criteria set. - top_set = { - 'xsi_type': 'CustomCriteriaSet', - 'logicalOperator': 'OR', - 'children': [custom_criteria] - } + line_item_service = client.GetService('LineItemService', version='v201508') # Create line item object. line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, 'targeting': { - 'customTargeting': top_set, + 'contentTargeting': { + 'targetedContentMetadata': [ + {'customTargetingValueIds': [ + content_custom_targeting_value_id]} + ] + }, 'inventoryTargeting': { 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id, 'includeDescendants': 'true'}] @@ -118,7 +106,8 @@ def main(client, order_id, targeted_video_ad_unit_id, }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'costType': 'CPM', 'costPerUnit': { @@ -148,4 +137,4 @@ def main(client, order_id, targeted_video_ad_unit_id, # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, - CONTENT_CUSTOM_TARGETING_KEY_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID) + CONTENT_CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201408/line_item_service/get_all_line_items.py b/examples/dfp/v201508/line_item_service/get_all_line_items.py similarity index 92% rename from examples/dfp/v201408/line_item_service/get_all_line_items.py rename to examples/dfp/v201508/line_item_service/get_all_line_items.py index c1827973..d40f5f49 100755 --- a/examples/dfp/v201408/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201508/line_item_service/get_all_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To create line items, run create_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -27,7 +25,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201508/line_item_service/get_line_items_by_statement.py similarity index 85% rename from examples/dfp/v201408/line_item_service/get_line_items_by_statement.py rename to examples/dfp/v201508/line_item_service/get_line_items_by_statement.py index 805ff404..bd7428bd 100755 --- a/examples/dfp/v201408/line_item_service/get_line_items_by_statement.py +++ b/examples/dfp/v201508/line_item_service/get_line_items_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -14,13 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets all line items that need creatives for the given -order. +"""This code example gets all line items that need creatives for an order. -To create line items, run create_line_items.py.""" +To create line items, run create_line_items.py. +""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -31,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # Create statement object to only select line items that need creatives from a # given order. @@ -42,13 +40,14 @@ def main(client, order_id): 'value': order_id } }, { - 'key': 'status', + 'key': 'isMissingCreatives', 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' + 'xsi_type': 'BooleanValue', + 'value': 'true' } }] - query = 'WHERE orderId = :orderId AND status = :status' + query = ('WHERE orderId = :orderId AND ' + 'isMissingCreatives = :isMissingCreatives') statement = dfp.FilterStatement(query, values) while True: diff --git a/examples/dfp/v201408/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201508/line_item_service/get_recently_updated_line_items.py similarity index 94% rename from examples/dfp/v201408/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201508/line_item_service/get_recently_updated_line_items.py index 712ecb74..fcdffcd7 100755 --- a/examples/dfp/v201408/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201508/line_item_service/get_recently_updated_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To create line items, run create_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import datetime @@ -31,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # Create statement object to only select line items belonging to the order and # have been modified in the last 3 days. diff --git a/examples/dfp/v201408/line_item_service/target_custom_criteria.py b/examples/dfp/v201508/line_item_service/target_custom_criteria.py similarity index 96% rename from examples/dfp/v201408/line_item_service/target_custom_criteria.py rename to examples/dfp/v201508/line_item_service/target_custom_criteria.py index 3e09c5b5..a5b1ae92 100755 --- a/examples/dfp/v201408/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201508/line_item_service/target_custom_criteria.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,8 +20,6 @@ which custom targeting keys and values exist, run get_all_custom_targeting_keys_and_values.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import pprint @@ -41,7 +39,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201408/line_item_service/update_line_items.py b/examples/dfp/v201508/line_item_service/update_line_items.py similarity index 95% rename from examples/dfp/v201408/line_item_service/update_line_items.py rename to examples/dfp/v201508/line_item_service/update_line_items.py index 18243fb3..f5464c86 100755 --- a/examples/dfp/v201408/line_item_service/update_line_items.py +++ b/examples/dfp/v201508/line_item_service/update_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To determine which line items exist, run get_all_line_items.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201508/network_service/__init__.py b/examples/dfp/v201508/network_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/network_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/network_service/get_all_networks.py b/examples/dfp/v201508/network_service/get_all_networks.py similarity index 91% rename from examples/dfp/v201408/network_service/get_all_networks.py rename to examples/dfp/v201508/network_service/get_all_networks.py index df4beace..fe0b99af 100755 --- a/examples/dfp/v201408/network_service/get_all_networks.py +++ b/examples/dfp/v201508/network_service/get_all_networks.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ A networkCode should be left out for this request.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -28,7 +26,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201408') + network_service = client.GetService('NetworkService', version='v201508') # Get all networks that you have access to with the current login credentials. networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201408/network_service/get_current_network.py b/examples/dfp/v201508/network_service/get_current_network.py similarity index 90% rename from examples/dfp/v201408/network_service/get_current_network.py rename to examples/dfp/v201508/network_service/get_current_network.py index e5be7cc4..c2f62c7e 100755 --- a/examples/dfp/v201408/network_service/get_current_network.py +++ b/examples/dfp/v201508/network_service/get_current_network.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -16,8 +16,6 @@ """This example gets the current network that you can make requests against.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -25,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201408') + network_service = client.GetService('NetworkService', version='v201508') # Get the current network. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201408/network_service/make_test_network.py b/examples/dfp/v201508/network_service/make_test_network.py similarity index 93% rename from examples/dfp/v201408/network_service/make_test_network.py rename to examples/dfp/v201508/network_service/make_test_network.py index e33f56a4..1284f124 100755 --- a/examples/dfp/v201408/network_service/make_test_network.py +++ b/examples/dfp/v201508/network_service/make_test_network.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,8 +27,6 @@ https://dfp-playground.appspot.com """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201408') + network_service = client.GetService('NetworkService', version='v201508') # Create a test network. network = network_service.MakeTestNetwork() diff --git a/examples/dfp/v201508/order_service/__init__.py b/examples/dfp/v201508/order_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/order_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/order_service/approve_orders.py b/examples/dfp/v201508/order_service/approve_orders.py similarity index 95% rename from examples/dfp/v201408/order_service/approve_orders.py rename to examples/dfp/v201508/order_service/approve_orders.py index fa02cd9d..6f49b0b9 100755 --- a/examples/dfp/v201408/order_service/approve_orders.py +++ b/examples/dfp/v201508/order_service/approve_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import datetime @@ -29,7 +27,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201408') + order_service = client.GetService('OrderService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201408/order_service/create_orders.py b/examples/dfp/v201508/order_service/create_orders.py similarity index 93% rename from examples/dfp/v201408/order_service/create_orders.py rename to examples/dfp/v201508/order_service/create_orders.py index 9d37f3d4..f847ab30 100755 --- a/examples/dfp/v201408/order_service/create_orders.py +++ b/examples/dfp/v201508/order_service/create_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -33,7 +31,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201408') + order_service = client.GetService('OrderService', version='v201508') # Create order objects. orders = [] diff --git a/examples/dfp/v201408/order_service/get_all_orders.py b/examples/dfp/v201508/order_service/get_all_orders.py similarity index 92% rename from examples/dfp/v201408/order_service/get_all_orders.py rename to examples/dfp/v201508/order_service/get_all_orders.py index a3de741d..e9bca038 100755 --- a/examples/dfp/v201408/order_service/get_all_orders.py +++ b/examples/dfp/v201508/order_service/get_all_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create orders, run create_orders.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -28,7 +26,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201408') + order_service = client.GetService('OrderService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/order_service/get_orders_by_statement.py b/examples/dfp/v201508/order_service/get_orders_by_statement.py similarity index 93% rename from examples/dfp/v201408/order_service/get_orders_by_statement.py rename to examples/dfp/v201508/order_service/get_orders_by_statement.py index b156a8c8..762f5596 100755 --- a/examples/dfp/v201408/order_service/get_orders_by_statement.py +++ b/examples/dfp/v201508/order_service/get_orders_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To create orders, run create_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201408') + order_service = client.GetService('OrderService', version='v201508') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201408/order_service/update_orders.py b/examples/dfp/v201508/order_service/update_orders.py similarity index 94% rename from examples/dfp/v201408/order_service/update_orders.py rename to examples/dfp/v201508/order_service/update_orders.py index 5e8d346a..4ffa2de3 100755 --- a/examples/dfp/v201408/order_service/update_orders.py +++ b/examples/dfp/v201508/order_service/update_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To determine which orders exist, run get_all_orders.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201408') + order_service = client.GetService('OrderService', version='v201508') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201408/placement_service/create_placements.py b/examples/dfp/v201508/placement_service/create_placements.py similarity index 96% rename from examples/dfp/v201408/placement_service/create_placements.py rename to examples/dfp/v201508/placement_service/create_placements.py index d9346747..3eda6d90 100755 --- a/examples/dfp/v201408/placement_service/create_placements.py +++ b/examples/dfp/v201508/placement_service/create_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -30,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201408') - inventory_service = client.GetService('InventoryService', version='v201408') + placement_service = client.GetService('PlacementService', version='v201508') + inventory_service = client.GetService('InventoryService', version='v201508') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201408/placement_service/deactivate_placements.py b/examples/dfp/v201508/placement_service/deactivate_placements.py similarity index 94% rename from examples/dfp/v201408/placement_service/deactivate_placements.py rename to examples/dfp/v201508/placement_service/deactivate_placements.py index d173b2a2..6ab8e988 100755 --- a/examples/dfp/v201408/placement_service/deactivate_placements.py +++ b/examples/dfp/v201508/placement_service/deactivate_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201408') + placement_service = client.GetService('PlacementService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201408/placement_service/get_all_placements.py b/examples/dfp/v201508/placement_service/get_all_placements.py similarity index 92% rename from examples/dfp/v201408/placement_service/get_all_placements.py rename to examples/dfp/v201508/placement_service/get_all_placements.py index 833a5c66..dc581a3d 100755 --- a/examples/dfp/v201408/placement_service/get_all_placements.py +++ b/examples/dfp/v201508/placement_service/get_all_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create placements, run create_placement.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -28,7 +26,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201408') + placement_service = client.GetService('PlacementService', version='v201508') # Create statement to fetch all placements. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/placement_service/get_placements_by_statement.py b/examples/dfp/v201508/placement_service/get_placements_by_statement.py similarity index 93% rename from examples/dfp/v201408/placement_service/get_placements_by_statement.py rename to examples/dfp/v201508/placement_service/get_placements_by_statement.py index 0189c544..21283c4a 100755 --- a/examples/dfp/v201408/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201508/placement_service/get_placements_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To create a placement, run create_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -28,7 +26,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201408') + placement_service = client.GetService('PlacementService', version='v201508') # Create a statement to only select active placements. values = [{ diff --git a/examples/dfp/v201408/placement_service/update_placements.py b/examples/dfp/v201508/placement_service/update_placements.py similarity index 94% rename from examples/dfp/v201408/placement_service/update_placements.py rename to examples/dfp/v201508/placement_service/update_placements.py index 7f196084..45f3fcca 100755 --- a/examples/dfp/v201408/placement_service/update_placements.py +++ b/examples/dfp/v201508/placement_service/update_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ To determine which placements exist, run get_all_placements.py. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201408') + placement_service = client.GetService('PlacementService', version='v201508') # Create query. values = [{ 'key': 'placementId', diff --git a/examples/dfp/v201508/premium_rate_service/__init__.py b/examples/dfp/v201508/premium_rate_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/premium_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201508/premium_rate_service/create_premium_rates.py b/examples/dfp/v201508/premium_rate_service/create_premium_rates.py new file mode 100755 index 00000000..4cbc87db --- /dev/null +++ b/examples/dfp/v201508/premium_rate_service/create_premium_rates.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates new premium_rates. + +To determine which premium_rates exist, run get_all_premium_rates.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate services. + premium_rate_service = client.GetService('PremiumRateService', + version='v201508') + + # Create an ad unit premium to apply to the rate card. + ad_unit_premium_feature = { + 'xsi_type': 'AdUnitPremiumFeature' + } + + # Create a CPC based premium rate value with adjustments in milli amounts. + # This will adjust a CPC priced proposal line item that has + # inventory targeting specified by 10% of the cost associated with the rate + # card (this comes from a percentage adjustment). + cpc_premium_rate_value = { + 'premiumFeature': ad_unit_premium_feature, + 'rateType': 'CPC', + 'adjustmentSize': 10000, + 'adjustmentType': 'PERCENTAGE' + } + + # Create a CPM based premium rate value with adjustments in micro amounts. + # This will adjust a CPM priced proposal line item that has + # inventory targeting specified by 2 units of the currency associated with + # the rate card (this comes from absolute value adjustment). + cpm_premium_rate_value = { + 'premiumFeature': ad_unit_premium_feature, + 'rateType': 'CPM', + 'adjustmentSize': 2000000, + 'adjustmentType': 'ABSOLUTE_VALUE' + } + + # Create premium_rate objects. + premium_rate = { + 'rateCardId': rate_card_id, + 'pricingMethod': 'ANY_VALUE', + 'premiumFeature': ad_unit_premium_feature, + 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value] + } + + # Add premium_rates. + premium_rates = premium_rate_service.createPremiumRates([premium_rate]) + + # Display results. + for premium_rate in premium_rates: + print ('A premium rate for \'%s\' was added to the rate card with ID' + ' of \'%s\'.\n' + % (dfp.DfpClassType(premium_rate['premiumFeature']), + premium_rate['id'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201508/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201508/premium_rate_service/get_all_premium_rates.py new file mode 100755 index 00000000..155500d2 --- /dev/null +++ b/examples/dfp/v201508/premium_rate_service/get_all_premium_rates.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all premium rates. + +To create premium rates, run create_premium_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + premium_rate_service = client.GetService('PremiumRateService', + version='v201508') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get premium rates by statement. + while True: + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for premium_rate in response['results']: + print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' + ' rate card with ID \'%s\' was found.\n' % ( + premium_rate['id'], + dfp.DfpClassType(premium_rate['premiumFeature']), + premium_rate['rateCardId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201508/premium_rate_service/get_premium_rates_for_a_rate_card.py new file mode 100755 index 00000000..94521798 --- /dev/null +++ b/examples/dfp/v201508/premium_rate_service/get_premium_rates_for_a_rate_card.py @@ -0,0 +1,68 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all premium rates belonging to a specific rate card. + +To create premium rates, run create_premium_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate service. + premium_rate_service = client.GetService('PremiumRateService', + version='v201508') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'rateCardId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': rate_card_id + } + }] + query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + # Get premium rates by statement. + while True: + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for premium_rate in response['results']: + print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' + ' rate card with ID \'%s\' was found.\n' % ( + premium_rate['id'], + dfp.DfpClassType(premium_rate['premiumFeature']), + premium_rate['rateCardId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201508/premium_rate_service/update_premium_rates.py b/examples/dfp/v201508/premium_rate_service/update_premium_rates.py new file mode 100755 index 00000000..5fe463b2 --- /dev/null +++ b/examples/dfp/v201508/premium_rate_service/update_premium_rates.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a premium rate to add a flat fee to an existing feature. + +To determine which premium rates exist, run get_all_premium_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' + + +def main(client, premium_rate_id): + # Initialize appropriate service. + premium_rate_service = client.GetService('PremiumRateService', + version='v201508') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': premium_rate_id + } + }] + query = 'WHERE id = :id ORDER BY id ASC' + statement = dfp.FilterStatement(query, values, 1) + + # Get the premium rate. + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + + if 'results' in response: + updated_premium_rates = [] + for premium_rate in response['results']: + # Create a flat fee based premium rate value with a 10% increase. + new_flat_fee_rate = { + 'premiumFeature': premium_rate['premiumFeature'], + 'rateType': 'CPM', + 'adjustmentSize': 10000, + 'adjustmentType': 'PERCENTAGE' + } + + # Update the premium rate's premiumRateValues to include a flat fee + # premium rate. + + existing_premium_rate_value = ( + [] if 'premiumRateValues' not in premium_rate else + premium_rate['premiumRateValues']) + existing_premium_rate_value.append(new_flat_fee_rate) + premium_rate['premiumRateValues'] = existing_premium_rate_value + + updated_premium_rates.append(premium_rate) + + # Update products remotely. + premium_rates = premium_rate_service.updatePremiumRates( + updated_premium_rates) + + # Display results. + if premium_rates: + for premium_rate in premium_rates: + print ('Premium rate with ID \'%s\', associated with rate card id' + ' \'%s\' was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) + else: + print 'No premium rates were updated.' + else: + print 'No premium rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PREMIUM_RATE_ID) diff --git a/examples/dfp/v201508/product_service/__init__.py b/examples/dfp/v201508/product_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/product_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201508/product_service/get_all_products.py b/examples/dfp/v201508/product_service/get_all_products.py new file mode 100755 index 00000000..ffd5c938 --- /dev/null +++ b/examples/dfp/v201508/product_service/get_all_products.py @@ -0,0 +1,53 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all products. + +Products are created automatically from product templates. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201508') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get products by statement. + while True: + response = product_service.getProductsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for product in response['results']: + print ('Product with id \'%s\' and name \'%s\' was found.' % ( + product['id'], product['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/product_service/get_products_for_product_template.py b/examples/dfp/v201508/product_service/get_products_for_product_template.py new file mode 100755 index 00000000..ae7acbca --- /dev/null +++ b/examples/dfp/v201508/product_service/get_products_for_product_template.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 products created from a product template. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201508') + + # Create a filter statement to select only products created from a single + # a product template. + values = [{ + 'key': 'productTemplateId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_template_id + } + }] + query = 'WHERE productTemplateId = :productTemplateId ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + # Get products by statement. + while True: + response = product_service.getProductsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for product in response['results']: + print ('Product with id \'%s\' and name \'%s\' was found.' % ( + product['id'], product['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201508/product_service/update_products.py b/examples/dfp/v201508/product_service/update_products.py new file mode 100755 index 00000000..c82aa09d --- /dev/null +++ b/examples/dfp/v201508/product_service/update_products.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a product's notes. + +To determine which products exist, run get_all_products.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, product_id): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201508') + + # Create statement object to select a single product by an ID. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + # Get products by statement. + response = product_service.getProductsByStatement(statement.ToStatement()) + + if 'results' in response: + # Update each local product object by changing its notes. + updated_products = [] + for product in response['results']: + product['notes'] = 'Product needs further review before activation.' + updated_products.append(product) + + # Update products remotely. + products = product_service.updateProducts(updated_products) + + # Display results. + if products: + for product in products: + print ('Product with id \'%s\', name \'%s\', and ' + 'notes \'%s\' was updated.' + % (product['id'], product['name'], product['notes'])) + else: + print 'No products were updated.' + else: + print 'No products found to update.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201508/product_template_service/__init__.py b/examples/dfp/v201508/product_template_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/product_template_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201508/product_template_service/activate_product_templates.py b/examples/dfp/v201508/product_template_service/activate_product_templates.py new file mode 100755 index 00000000..52c72f08 --- /dev/null +++ b/examples/dfp/v201508/product_template_service/activate_product_templates.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example activates a product template. + +To determine which product templates exist, run get_all_product_templates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the product template to activate. +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201508') + + # Create query. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_template_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + product_templates_activated = 0 + + # Get product_templates by statement. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response: + for product_template in response['results']: + print ('Product template with id \'%s\' and name \'%s\' will be ' + 'activated.' % (product_template['id'], + product_template['name'])) + + # Perform action. + result = product_template_service.performProductTemplateAction( + {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + product_templates_activated += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if product_templates_activated > 0: + print ('Number of product templates ' + 'activated: %s' % product_templates_activated) + else: + print 'No product templates were activated.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201508/product_template_service/create_product_templates.py b/examples/dfp/v201508/product_template_service/create_product_templates.py new file mode 100755 index 00000000..018958e2 --- /dev/null +++ b/examples/dfp/v201508/product_template_service/create_product_templates.py @@ -0,0 +1,105 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates a product template. + +To determine which product templates exist, run get_all_product_templates.py. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201508') + network_service = client.GetService( + 'NetworkService', version='v201508') + + # Create a product template. + product_template = { + 'name': ('Product template #%d' % uuid.uuid4()), + 'description': ('This product template creates standard proposal line ' + 'items targeting Chrome browsers with product ' + 'segmentation on ad units and geo targeting.'), + 'nameMacro': (' - - ' + ' - '), + 'productType': 'DFP', + 'rateType': 'CPM', + 'roadblockingType': 'ONE_OR_MORE', + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'lineItemType': 'STANDARD', + 'builtInTargeting': { + 'technologyTargeting': { + # Set browser targeting to Chrome. + 'browserTargeting': { + { + 'browsers': [ + { + 'id': '500072' + } + ] + } + } + } + }, + 'productSegmentation': { + 'geoSegment': { + 'targetedLocations': [ + {'id': '2840', + 'displayName': 'US'}, + {'id': '2344', + 'displayName': 'Hong Kong'} + ] + }, + 'adUnitSegments': [{ + 'adUnitId': (network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId']), + 'includeDescendants': 'true' + }] + } + } + + # Create product templates on the server. + product_templates = product_template_service.createProductTemplates( + [product_template]) + + if product_templates: + for product_template in product_templates: + print ('A product template with ID \'%s\' and name \'%s\' was ' + 'created.' % (product_template['id'], product_template['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/product_template_service/get_all_product_templates.py b/examples/dfp/v201508/product_template_service/get_all_product_templates.py new file mode 100755 index 00000000..8e82c5e6 --- /dev/null +++ b/examples/dfp/v201508/product_template_service/get_all_product_templates.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all product templates. + +To create product templates, run create_product_template_templates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201508') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get product templates by statement. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for product_template in response['results']: + print ('Product template with id \'%s\' and name \'%s\' was found.' % ( + product_template['id'], product_template['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201508/product_template_service/get_sponsorship_product_templates.py new file mode 100755 index 00000000..6da4290d --- /dev/null +++ b/examples/dfp/v201508/product_template_service/get_sponsorship_product_templates.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all sponsorship product templates. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201508') + + # Create a statement to select all sponsorship product templates. + values = [{ + 'key': 'lineItemType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'SPONSORSHIP' + } + }] + query = 'WHERE lineItemType = :lineItemType ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + # Get product templates by statement. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for product_template in response['results']: + print ('Product template with id \'%s\' and name \'%s\' was found.' % ( + product_template['id'], product_template['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/product_template_service/update_product_templates.py b/examples/dfp/v201508/product_template_service/update_product_templates.py new file mode 100755 index 00000000..1fcbba51 --- /dev/null +++ b/examples/dfp/v201508/product_template_service/update_product_templates.py @@ -0,0 +1,98 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a product template's GeoTargeting. + +To determine which product templates exist, run get_all_product_templates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201508') + + # Create a statement to select a single product template by ID. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_template_id + } + }] + query = 'WHERE id = :id ORDER BY id ASC' + statement = dfp.FilterStatement(query, values, 1) + + # Get product templates by statement. + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + + if 'results' in response: + # Update each local product template object by appending a new geo-target. + for product_template in response['results']: + # Create geo-targeting for Canada to append. + location = { + 'id': '2124', + 'displayName': 'Canada' + } + + try: + targeting = product_template['builtInTargeting'] + + if 'geoTargeting' in targeting: + geo_targeting = targeting['geoTargeting'] + + if 'targetedLocations' in geo_targeting: + geo_targeting['targetedLocations'].append(location) + else: + geo_targeting['targetedLocations'] = [location] + else: + targeting['geoTargeting'] = { + 'targetedLocations': [location] + } + except KeyError: + product_template['builtInTargeting'] = { + 'geoTargeting': { + 'targetedLocations': [location] + } + } + + # Update products remotely. + product_templates = product_template_service.updateProductTemplates( + [product_template]) + + # Display results. + if product_templates: + for product_template in product_templates: + print ('Product template with id \'%s\' and name \'%s\' was ' + 'updated.' % (product_template['id'], product_template['name'])) + else: + print 'No product templates were updated.' + else: + print 'No product templates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201508/proposal_line_item_service/__init__.py b/examples/dfp/v201508/proposal_line_item_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/proposal_line_item_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201508/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201508/proposal_line_item_service/archive_proposal_line_items.py new file mode 100755 index 00000000..1e656b70 --- /dev/null +++ b/examples/dfp/v201508/proposal_line_item_service/archive_proposal_line_items.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example archives a proposal line item. + +To determine which proposal line items exist, run +get_all_proposal_line_items.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the proposal line item to archive. +PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' + + +def main(client, proposal_line_item_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201508') + + # Create query. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': proposal_line_item_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + proposal_line_items_archived = 0 + + # Get proposal line items by statement. + while True: + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + if 'results' in response: + for proposal_line_item in response['results']: + print ('Proposal line item with id \'%s\', ' + 'belonging to proposal id \'%s\', and ' + 'name \'%s\' will be archived.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + # Perform action. + result = proposal_line_item_service.performProposalLineItemAction( + {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposal_line_items_archived += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if proposal_line_items_archived > 0: + print ('Number of proposal line items ' + 'archived: %s' % proposal_line_items_archived) + else: + print 'No proposal line items were archived.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201508/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201508/proposal_line_item_service/create_proposal_line_items.py new file mode 100755 index 00000000..71239483 --- /dev/null +++ b/examples/dfp/v201508/proposal_line_item_service/create_proposal_line_items.py @@ -0,0 +1,120 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates a new run-of-network proposal line item. + +To determine which proposal line items exist, run +get_all_proposal_line_items.py. To determine which proposals exist, run +get_all_proposals.py. +""" + + +from datetime import date +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set proposal that the created proposal line item will belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + +# Set the ID of the rate card the proposal line items should be priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, proposal_id, product_id, rate_card_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201508') + network_service = client.GetService('NetworkService', version='v201508') + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single proposal line item. + proposal_line_item = { + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'rateCardId': rate_card_id, + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': { + 'date': { + 'year': str(date.today().year), + 'month': str(date.today().month), + 'day': str(date.today().day) + }, + 'hour': '23', + 'minute': '59', + 'second': '59' + }, + 'endDateTime': { + 'date': { + 'year': str(date.today().year + 1), + 'month': '9', + 'day': '30' + }, + 'hour': '0', + 'minute': '0', + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' + }, + 'deliveryRateType': 'EVENLY', + 'creativeRotationType': 'OPTIMIZED', + 'billingCap': 'CAPPED_CUMULATIVE', + 'billingSource': 'THIRD_PARTY_VOLUME', + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'cost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Proposal line item with id \'%s\', belonging to proposal id \'%s\'' + ', and named \'%s\' was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + diff --git a/examples/dfp/v201508/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201508/proposal_line_item_service/get_all_proposal_line_items.py new file mode 100755 index 00000000..85881a87 --- /dev/null +++ b/examples/dfp/v201508/proposal_line_item_service/get_all_proposal_line_items.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all proposal line items. + +To create proposal line items, run create_proposal_line_items.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201508') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get proposal line items by statement. + while True: + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for idx, proposal_line_item in enumerate(response['results'], + start=statement.offset): + print ('%s) Proposal line item with id \'%s\', belonging to proposal id' + ' \'%s\', and named \'%s\' was found.' % + (idx, proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201508/proposal_line_item_service/get_proposal_line_items_for_proposal.py new file mode 100755 index 00000000..f1a20f12 --- /dev/null +++ b/examples/dfp/v201508/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all proposal line items that belong to a proposal. + +To create proposal line items, run create_proposal_line_items.py.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the proposal to get proposal line items from. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', + version='v201508') + + # Create statement object to only select proposal line items belonging to a + # given proposal. + values = [{ + 'key': 'proposalId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': proposal_id + } + }] + query = 'WHERE proposalId = :proposalId ORDER BY id ASC' + statement = dfp.FilterStatement(query, values) + + while True: + # Get proposal line items by statement. + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + + if 'results' in response: + # Display results. + for idx, proposal_line_item in enumerate(response['results'], + start=statement.offset): + print( + '%s) Proposal line item with id \'%s\', belonging to proposal id ' + '\'%s\', and named \'%s\' was found.' % ( + idx, proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201508/proposal_line_item_service/update_proposal_line_items.py new file mode 100755 index 00000000..691ffbd6 --- /dev/null +++ b/examples/dfp/v201508/proposal_line_item_service/update_proposal_line_items.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example updates a proposal line item's notes. + +To determine which proposal line items exist, +run get_all_proposal_line_items.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set id of the proposal line item to update. +PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' + + +def main(client, proposal_line_item_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201508') + + # Create statement to select a proposal line item. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': proposal_line_item_id + } + }] + + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + # Get proposal line items by statement. + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + + if 'results' in response: + # Update each the proposal line item's notes field. + proposal_line_item = response['results'][0] + proposal_line_item['notes'] = 'Proposal line item ready for submission.' + + # Update proposal line items remotely. + proposal_line_items = proposal_line_item_service.updateProposalLineItems( + [proposal_line_item]) + + # Display results. + if proposal_line_items: + for proposal_line_item in proposal_line_items: + print ('Line item with id \'%s\', belonging to proposal id \'%s\' and,' + ' named \'%s\' was updated.' % ( + proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + else: + print 'No proposal line items were updated.' + else: + print 'No proposal line items found to update.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201508/proposal_service/__init__.py b/examples/dfp/v201508/proposal_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/proposal_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201508/proposal_service/create_proposals.py b/examples/dfp/v201508/proposal_service/create_proposals.py new file mode 100755 index 00000000..ef94b94f --- /dev/null +++ b/examples/dfp/v201508/proposal_service/create_proposals.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates new proposals. + +To determine which proposals exist, run get_all_proposals.py.""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' + + +def main(client, advertiser_id, primary_salesperson_id, + secondary_salesperson_id, primary_trafficker_id): + # Initialize appropriate services. + proposal_service = client.GetService('ProposalService', version='v201508') + network_service = client.GetService('NetworkService', version='v201508') + + # Create proposal objects. + proposal = { + 'name': 'Proposal #%s' % uuid.uuid4(), + 'advertiser': { + 'companyId': advertiser_id, + 'type': 'ADVERTISER' + }, + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '75000' + }, + 'secondarySalespeople': [{ + 'userId': secondary_salesperson_id, + 'split': '25000' + }], + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + 'budget': { + 'microAmount': '100000000', + 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] + }, + 'billingCap': 'CAPPED_CUMULATIVE', + 'billingSource': 'DFP_VOLUME' + } + + # Add proposals. + proposals = proposal_service.createProposals([proposals]) + + # Display results. + for proposal in proposals: + print ('Proposal with id \'%s\' and name \'%s\' was created.' + % (proposal['id'], proposal['name'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201508/proposal_service/get_all_proposals.py b/examples/dfp/v201508/proposal_service/get_all_proposals.py new file mode 100755 index 00000000..28768d10 --- /dev/null +++ b/examples/dfp/v201508/proposal_service/get_all_proposals.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all proposals. + +To create proposals, run create_proposals.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201508') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for proposal in response['results']: + print ('Proposal with id \'%s\' and name \'%s\' was found.' % ( + proposal['id'], proposal['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201508/proposal_service/get_proposals_by_statement.py new file mode 100755 index 00000000..1dda0155 --- /dev/null +++ b/examples/dfp/v201508/proposal_service/get_proposals_by_statement.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all proposals that are currently 'PENDING_APPROVAL.' + +To create proposals, run create_proposals.py.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201508') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PENDING_APPROVAL' + } + }] + query = 'WHERE status = :status ORDER BY id ASC' + + statement = dfp.FilterStatement(query, values) + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for proposal in response['results']: + print ('Proposal with id \'%s\' name \'%s\' was found.' + % (proposal['id'], proposal['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201508/proposal_service/submit_proposals_for_approval.py new file mode 100755 index 00000000..74d27fb8 --- /dev/null +++ b/examples/dfp/v201508/proposal_service/submit_proposals_for_approval.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example approves a single proposal. + +To determine which proposals exist, run get_all_proposals.py.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201508') + + # Create query. + values = [{ + 'key': 'proposalId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + } + }] + query = 'WHERE id = :proposalId' + + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + proposals_approved = 0 + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for proposal in response['results']: + print ('Proposal with id \'%s\', name \'%s\', and status \'%s\' will be' + ' approved.' % (proposal['id'], proposal['name'], + proposal['status'])) + # Perform action. + result = proposal_service.performProposalAction( + {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposals_approved += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if proposals_approved > 0: + print '\nNumber of proposals approved: %s' % proposals_approved + else: + print '\nNo proposals were approved.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/proposal_service/update_proposals.py b/examples/dfp/v201508/proposal_service/update_proposals.py new file mode 100755 index 00000000..40c0eb28 --- /dev/null +++ b/examples/dfp/v201508/proposal_service/update_proposals.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example updates the notes of a single proposal specified by ID. + +To determine which proposals exist, run get_all_proposals.py.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201508') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'proposalId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': proposal_id + } + }] + query = 'WHERE id = :proposalId' + + statement = dfp.FilterStatement(query, values, 1) + + # Get proposals by statement. + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + + if 'results' in response: + # Update each local proposal object by changing its notes. + updated_proposals = [] + for proposal in response['results']: + proposal['notes'] = 'Proposal needs further review before approval.' + updated_proposals.append(proposal) + + # Update proposals remotely. + proposals = proposal_service.updateProposals(updated_proposals) + + # Display results. + if proposals: + for proposal in proposals: + print ('Proposal with id \'%s\', name \'%s\', and ' + 'notes \'%s\' was updated.' + % (proposal['id'], proposal['name'], proposal['notes'])) + else: + print 'No proposals were updated.' + else: + print 'No proposals found to update.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/publisher_query_language_service/__init__.py b/examples/dfp/v201508/publisher_query_language_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/publisher_query_language_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201508/publisher_query_language_service/fetch_match_tables.py similarity index 90% rename from examples/dfp/v201408/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201508/publisher_query_language_service/fetch_match_tables.py index 18f20806..7c24da58 100755 --- a/examples/dfp/v201408/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201508/publisher_query_language_service/fetch_match_tables.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -16,8 +16,6 @@ """This example fetches data from PQL tables and creates match table files.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile @@ -27,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201408') + report_downloader = client.GetDataDownloader(version='v201508') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201408/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201508/publisher_query_language_service/get_geo_targets.py similarity index 89% rename from examples/dfp/v201408/publisher_query_language_service/get_geo_targets.py rename to examples/dfp/v201508/publisher_query_language_service/get_geo_targets.py index bab9d479..235cdeea 100755 --- a/examples/dfp/v201408/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201508/publisher_query_language_service/get_geo_targets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,11 +20,9 @@ 'Postal_Code', and 'DMA_Region' (i.e. Metro). A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201408/PublisherQueryLanguageService +https://developers.google.com/doubleclick-publishers/docs/reference/v201508/PublisherQueryLanguageService """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile @@ -34,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201408') + report_downloader = client.GetDataDownloader(version='v201508') output_file = tempfile.NamedTemporaryFile( prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201408/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201508/publisher_query_language_service/get_line_items_named_like.py similarity index 90% rename from examples/dfp/v201408/publisher_query_language_service/get_line_items_named_like.py rename to examples/dfp/v201508/publisher_query_language_service/get_line_items_named_like.py index ec7dc34b..3e698313 100755 --- a/examples/dfp/v201408/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201508/publisher_query_language_service/get_line_items_named_like.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -16,8 +16,6 @@ """This example gets all line items with names starting with 'line item'.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile @@ -27,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201408') + report_downloader = client.GetDataDownloader(version='v201508') output_file = tempfile.NamedTemporaryFile( prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201508/rate_card_service/__init__.py b/examples/dfp/v201508/rate_card_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/rate_card_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201508/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201508/rate_card_service/get_all_rate_cards.py new file mode 100755 index 00000000..4d7bf1f2 --- /dev/null +++ b/examples/dfp/v201508/rate_card_service/get_all_rate_cards.py @@ -0,0 +1,53 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets all rate cards. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201508') + + # Create a filter statement. + statement = dfp.FilterStatement('ORDER BY id ASC') + + # Get rate cards by statement. + while True: + response = rate_card_service.getRateCardsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for rate_card in response['results']: + print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' + 'was found.' % (rate_card['id'], rate_card['name'], + rate_card['currencyCode'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201508/rate_card_service/get_rate_cards_priced_with_currency.py new file mode 100755 index 00000000..c2314783 --- /dev/null +++ b/examples/dfp/v201508/rate_card_service/get_rate_cards_priced_with_currency.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 rate cards that have a currency in US dollars. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201508') + + # Create a statement to get all rate cards using USD as currency. + values = [{ + 'key': 'currencyCode', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'USD' + } + }] + query = 'WHERE currencyCode = :currencyCode' + + statement = dfp.FilterStatement(query, values) + + # Get rate cards by statement. + while True: + response = rate_card_service.getRateCardsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for rate_card in response['results']: + print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' + 'was found.' % (rate_card['id'], rate_card['name'], + rate_card['currencyCode'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/report_service/__init__.py b/examples/dfp/v201508/report_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/report_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/report_service/run_delivery_report.py b/examples/dfp/v201508/report_service/run_delivery_report.py similarity index 79% rename from examples/dfp/v201408/report_service/run_delivery_report.py rename to examples/dfp/v201508/report_service/run_delivery_report.py index 123d0472..48e05a3b 100755 --- a/examples/dfp/v201408/report_service/run_delivery_report.py +++ b/examples/dfp/v201508/report_service/run_delivery_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,8 @@ website with additional attributes and can filter to include just one order. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') +from datetime import datetime +from datetime import timedelta import tempfile # Import appropriate modules from the client library. @@ -41,6 +41,10 @@ def main(client, order_id): filter_statement = {'query': 'WHERE ORDER_ID = :id', 'values': values} + # Set the start and end dates of the report to run (past 8 days). + end_date = datetime.now() + start_date = end_date - timedelta(days=8) + # Create report job. report_job = { 'reportQuery': { @@ -51,12 +55,18 @@ def main(client, order_id): 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'LAST_MONTH' + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': {'year': start_date.year, + 'month': start_date.month, + 'day': start_date.day}, + 'endDate': {'year': end_date.year, + 'month': end_date.month, + 'day': end_date.day} } } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201408') + report_downloader = client.GetDataDownloader(version='v201508') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201408/report_service/run_inventory_report.py b/examples/dfp/v201508/report_service/run_inventory_report.py similarity index 93% rename from examples/dfp/v201408/report_service/run_inventory_report.py rename to examples/dfp/v201508/report_service/run_inventory_report.py index 18592405..918fc0b0 100755 --- a/examples/dfp/v201408/report_service/run_inventory_report.py +++ b/examples/dfp/v201508/report_service/run_inventory_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ DFP website. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. @@ -29,9 +27,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201408') + network_service = client.GetService('NetworkService', version='v201508') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201408') + report_downloader = client.GetDataDownloader(version='v201508') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201408/report_service/run_reach_report.py b/examples/dfp/v201508/report_service/run_reach_report.py similarity index 91% rename from examples/dfp/v201408/report_service/run_reach_report.py rename to examples/dfp/v201508/report_service/run_reach_report.py index d3d017ee..e7801abf 100755 --- a/examples/dfp/v201408/report_service/run_reach_report.py +++ b/examples/dfp/v201508/report_service/run_reach_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -16,8 +16,6 @@ """This code example runs a reach report.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. @@ -27,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201408') + report_downloader = client.GetDataDownloader(version='v201508') # Create report job. report_job = { diff --git a/examples/dfp/v201408/report_service/run_report_with_custom_fields.py b/examples/dfp/v201508/report_service/run_report_with_custom_fields.py similarity index 94% rename from examples/dfp/v201408/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201508/report_service/run_report_with_custom_fields.py index 2fcac888..b955623a 100755 --- a/examples/dfp/v201408/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201508/report_service/run_report_with_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ items of an order. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. @@ -32,9 +30,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201408') + line_item_service = client.GetService('LineItemService', version='v201508') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201408') + report_downloader = client.GetDataDownloader(version='v201508') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201408/report_service/run_sales_report.py b/examples/dfp/v201508/report_service/run_sales_report.py similarity index 91% rename from examples/dfp/v201408/report_service/run_sales_report.py rename to examples/dfp/v201508/report_service/run_sales_report.py index 1e330d64..304291e8 100755 --- a/examples/dfp/v201408/report_service/run_sales_report.py +++ b/examples/dfp/v201508/report_service/run_sales_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -17,8 +17,6 @@ """This code example runs a report equal to the "Sales by salespersons report." """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. @@ -28,7 +26,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201408') + report_downloader = client.GetDataDownloader(version='v201508') # Create report job. report_job = { diff --git a/examples/dfp/v201508/suggested_ad_unit_service/__init__.py b/examples/dfp/v201508/suggested_ad_unit_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/suggested_ad_unit_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201508/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 93% rename from examples/dfp/v201408/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201508/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 9d70e3ed..6e4b10c4 100755 --- a/examples/dfp/v201408/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201508/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ This feature is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -31,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201408') + 'SuggestedAdUnitService', version='v201508') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201408/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201508/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 91% rename from examples/dfp/v201408/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201508/suggested_ad_unit_service/get_all_suggested_ad_units.py index 94ed9e4c..26c76bef 100755 --- a/examples/dfp/v201408/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201508/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,8 +20,6 @@ is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201408') + 'SuggestedAdUnitService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201508/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py similarity index 91% rename from examples/dfp/v201408/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py rename to examples/dfp/v201508/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py index 1be5bc2d..ed40b482 100755 --- a/examples/dfp/v201408/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201508/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ This feature is only available to DFP premium solution networks. """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201408') + 'SuggestedAdUnitService', version='v201508') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201508/team_service/__init__.py b/examples/dfp/v201508/team_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/team_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/team_service/create_teams.py b/examples/dfp/v201508/team_service/create_teams.py similarity index 88% rename from examples/dfp/v201408/team_service/create_teams.py rename to examples/dfp/v201508/team_service/create_teams.py index 213bcbfa..21ff0eaa 100755 --- a/examples/dfp/v201408/team_service/create_teams.py +++ b/examples/dfp/v201508/team_service/create_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.createTeams """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') import uuid @@ -37,7 +34,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201408') + team_service = client.GetService('TeamService', version='v201508') # Create team objects. teams = [] diff --git a/examples/dfp/v201408/team_service/get_all_teams.py b/examples/dfp/v201508/team_service/get_all_teams.py similarity index 88% rename from examples/dfp/v201408/team_service/get_all_teams.py rename to examples/dfp/v201508/team_service/get_all_teams.py index 21e99e5f..0e9d2ac3 100755 --- a/examples/dfp/v201408/team_service/get_all_teams.py +++ b/examples/dfp/v201508/team_service/get_all_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -35,7 +32,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201408') + team_service = client.GetService('TeamService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/team_service/get_teams_by_statement.py b/examples/dfp/v201508/team_service/get_teams_by_statement.py similarity index 90% rename from examples/dfp/v201408/team_service/get_teams_by_statement.py rename to examples/dfp/v201508/team_service/get_teams_by_statement.py index 8efa32d3..ab734b7d 100755 --- a/examples/dfp/v201408/team_service/get_teams_by_statement.py +++ b/examples/dfp/v201508/team_service/get_teams_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -37,7 +34,7 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201408') + team_service = client.GetService('TeamService', version='v201508') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201408/team_service/update_teams.py b/examples/dfp/v201508/team_service/update_teams.py similarity index 91% rename from examples/dfp/v201408/team_service/update_teams.py rename to examples/dfp/v201508/team_service/update_teams.py index 28e09c69..08c3a134 100755 --- a/examples/dfp/v201408/team_service/update_teams.py +++ b/examples/dfp/v201508/team_service/update_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: TeamService.getTeamsByStatement, TeamService.updateTeams """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -39,7 +36,7 @@ def main(client, ad_unit_id, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201408') + team_service = client.GetService('TeamService', version='v201508') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201508/user_service/__init__.py b/examples/dfp/v201508/user_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/user_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/user_service/create_users.py b/examples/dfp/v201508/user_service/create_users.py similarity index 90% rename from examples/dfp/v201408/user_service/create_users.py rename to examples/dfp/v201508/user_service/create_users.py index 457c9218..36259c12 100755 --- a/examples/dfp/v201408/user_service/create_users.py +++ b/examples/dfp/v201508/user_service/create_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -30,7 +28,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201408') + user_service = client.GetService('UserService', version='v201508') # Create user objects. users = [ diff --git a/examples/dfp/v201408/user_service/deactivate_users.py b/examples/dfp/v201508/user_service/deactivate_users.py similarity index 92% rename from examples/dfp/v201408/user_service/deactivate_users.py rename to examples/dfp/v201508/user_service/deactivate_users.py index bdb55bc4..8bf631d6 100755 --- a/examples/dfp/v201408/user_service/deactivate_users.py +++ b/examples/dfp/v201508/user_service/deactivate_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,8 +20,6 @@ request cannot deactivate itself. To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -31,7 +29,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201408') + user_service = client.GetService('UserService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201408/user_service/get_all_roles.py b/examples/dfp/v201508/user_service/get_all_roles.py similarity index 87% rename from examples/dfp/v201408/user_service/get_all_roles.py rename to examples/dfp/v201508/user_service/get_all_roles.py index b9053254..dd597127 100755 --- a/examples/dfp/v201408/user_service/get_all_roles.py +++ b/examples/dfp/v201508/user_service/get_all_roles.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -19,8 +19,6 @@ This sample can be used to determine which role id is needed when getting and creating users.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -28,7 +26,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201408') + user_service = client.GetService('UserService', version='v201508') # Get all roles. roles = user_service.getAllRoles() diff --git a/examples/dfp/v201408/user_service/get_all_users.py b/examples/dfp/v201508/user_service/get_all_users.py similarity index 89% rename from examples/dfp/v201408/user_service/get_all_users.py rename to examples/dfp/v201508/user_service/get_all_users.py index 8466edd4..d00b47c3 100755 --- a/examples/dfp/v201408/user_service/get_all_users.py +++ b/examples/dfp/v201508/user_service/get_all_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -16,8 +16,6 @@ """This code example gets all users. To create users, run create_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -25,7 +23,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201408') + user_service = client.GetService('UserService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/user_service/get_current_user.py b/examples/dfp/v201508/user_service/get_current_user.py similarity index 86% rename from examples/dfp/v201408/user_service/get_current_user.py rename to examples/dfp/v201508/user_service/get_current_user.py index 386bff30..e6c9df97 100755 --- a/examples/dfp/v201408/user_service/get_current_user.py +++ b/examples/dfp/v201508/user_service/get_current_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -16,8 +16,6 @@ """This code example gets the current user.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -25,7 +23,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201408') + user_service = client.GetService('UserService', version='v201508') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201408/user_service/get_users_by_statement.py b/examples/dfp/v201508/user_service/get_users_by_statement.py similarity index 89% rename from examples/dfp/v201408/user_service/get_users_by_statement.py rename to examples/dfp/v201508/user_service/get_users_by_statement.py index cc1ca2fb..9f2758ef 100755 --- a/examples/dfp/v201408/user_service/get_users_by_statement.py +++ b/examples/dfp/v201508/user_service/get_users_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To create users, run create_user.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201408') + user_service = client.GetService('UserService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201408/user_service/update_users.py b/examples/dfp/v201508/user_service/update_users.py similarity index 90% rename from examples/dfp/v201408/user_service/update_users.py rename to examples/dfp/v201508/user_service/update_users.py index 8476420c..edd8abdf 100755 --- a/examples/dfp/v201408/user_service/update_users.py +++ b/examples/dfp/v201508/user_service/update_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,8 +18,6 @@ To determine which users exist, run get_all_users.py.""" -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -29,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201408') + user_service = client.GetService('UserService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201508/user_team_association_service/__init__.py b/examples/dfp/v201508/user_team_association_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/user_team_association_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201408/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201508/user_team_association_service/create_user_team_associations.py similarity index 90% rename from examples/dfp/v201408/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201508/user_team_association_service/create_user_team_associations.py index f298bcdc..b19ee3e9 100755 --- a/examples/dfp/v201408/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201508/user_team_association_service/create_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -24,11 +24,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.createUserTeamAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -40,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201408') + 'UserTeamAssociationService', version='v201508') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201408/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201508/user_team_association_service/delete_user_team_associations.py similarity index 91% rename from examples/dfp/v201408/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201508/user_team_association_service/delete_user_team_associations.py index 2d6967e6..f1aada8f 100755 --- a/examples/dfp/v201408/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201508/user_team_association_service/delete_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.performUserTeamAssociationAction """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -38,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201408') + 'UserTeamAssociationService', version='v201508') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201408/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201508/user_team_association_service/get_all_user_team_associations.py similarity index 89% rename from examples/dfp/v201408/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201508/user_team_association_service/get_all_user_team_associations.py index f536ef0e..3af4c74b 100755 --- a/examples/dfp/v201408/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201508/user_team_association_service/get_all_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -36,7 +33,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201408') + 'UserTeamAssociationService', version='v201508') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201408/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201508/user_team_association_service/get_user_team_associations_for_user.py similarity index 90% rename from examples/dfp/v201408/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201508/user_team_association_service/get_user_team_associations_for_user.py index e60af35d..f2706cc4 100755 --- a/examples/dfp/v201408/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201508/user_team_association_service/get_user_team_associations_for_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,11 +23,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociation """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -38,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201408') + 'UserTeamAssociationService', version='v201508') # Create query. values = [{ diff --git a/examples/dfp/v201408/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201508/user_team_association_service/update_user_team_associations.py similarity index 90% rename from examples/dfp/v201408/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201508/user_team_association_service/update_user_team_associations.py index 9d730096..50e8b862 100755 --- a/examples/dfp/v201408/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201508/user_team_association_service/update_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,12 +25,8 @@ directory. For more information, see the "Caching authentication information" section of our README. -Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement -Tags: UserTeamAssociationService.updateUserTeamAssociations """ -__author__ = ('Nicholas Chen', - 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp @@ -41,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201408') + 'UserTeamAssociationService', version='v201508') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201508/workflow_request_service/__init__.py b/examples/dfp/v201508/workflow_request_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201508/workflow_request_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201508/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201508/workflow_request_service/approve_workflow_approval_requests.py new file mode 100755 index 00000000..ceafa9f2 --- /dev/null +++ b/examples/dfp/v201508/workflow_request_service/approve_workflow_approval_requests.py @@ -0,0 +1,97 @@ +#!/usr/bin/python +# +# Copyright 2015 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 approves all workflow approval requests belonging to a proposal. + +To determine which workflow approval requests exist, run +get_all_workflow_approval_requests.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201508') + + # Create query. + values = [ + { + 'key': 'entityId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + } + }, + { + 'key': 'entityType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PROPOSAL' + } + }, + { + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_APPROVAL_REQUEST' + } + } + ] + query = ('WHERE entityId = :entityId and entityType = :entityType ' + 'and type = :type') + + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + workflow_approval_requests_approved = 0 + + # Get workflow approval requests by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for workflow_approval_request in response['results']: + print ('Workflow approval request with id \'%s\' will be' + ' approved.' % workflow_approval_request['id']) + # Perform action. + result = workflow_request_service.performWorkflowRequestAction( + {'xsi_type': 'ApproveWorkflowApprovalRequests', + 'comment': 'This workflow has now been approved for submission.'}, + statement.ToStatement()) + if result and int(result['numChanges']) > 0: + workflow_approval_requests_approved += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if workflow_approval_requests_approved > 0: + print ('\nNumber of workflow approval requests approved: %s' % + workflow_approval_requests_approved) + else: + print '\nNo workflow approval requests were approved.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201508/workflow_request_service/get_workflow_approval_requests_by_statement.py new file mode 100755 index 00000000..68466589 --- /dev/null +++ b/examples/dfp/v201508/workflow_request_service/get_workflow_approval_requests_by_statement.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2015 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 workflow approval requests. + +Workflow approval requests must be approved or rejected for a workflow to +finish. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201508') + + # Create statement object to select all workflow approval requests. + values = [{ + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_APPROVAL_REQUEST' + } + }] + query = 'WHERE type = :type' + + statement = dfp.FilterStatement(query, values) + + # Get proposals by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for workflow_request in response['results']: + print ('Workflow approval request with id \'%s\' for %s with id \'%s\' ' + 'was found.' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201508/workflow_request_service/get_workflow_external_condition_requests_by_statement.py new file mode 100755 index 00000000..bacb285f --- /dev/null +++ b/examples/dfp/v201508/workflow_request_service/get_workflow_external_condition_requests_by_statement.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2015 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 workflow external condition requests. + +Workflow external condition requests must be triggered or skipped for a workflow +to finish. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201508') + + # Create statement object to select a single proposal by an ID. + values = [{ + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' + } + }] + query = 'WHERE type = :type' + + statement = dfp.FilterStatement(query, values) + + # Get proposals by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for workflow_request in response['results']: + print ('Workflow external condition request with id \'%s\' for %s ' + 'with id \'%s\' was found.' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201508/workflow_request_service/trigger_workflow_external_condition_requests.py new file mode 100755 index 00000000..77cadbb7 --- /dev/null +++ b/examples/dfp/v201508/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# +# Copyright 2015 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 triggers all workflow external condition requests for a proposal. + +Workflow external condition requests must be triggered or skipped for a workflow +to finish. To determine which proposals exist, run get_all_proposals.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201508') + + # Create query. + values = [ + { + 'key': 'entityId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + } + }, + { + 'key': 'entityType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PROPOSAL' + } + }, + { + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' + } + } + ] + query = ('WHERE entityId = :entityId and entityType = :entityType ' + 'and type = :type') + + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + workflow_external_condition_requests_triggered = 0 + + # Get workflow external condition requests by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response: + # Display results. + for workflow_request in response['results']: + print ('Workflow external condition request with id \'%s\' for %s ' + 'with id \'%s\' will be triggered.' % + (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + # Perform action. + result = workflow_request_service.performWorkflowRequestAction( + {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, + statement.ToStatement()) + if result and int(result['numChanges']) > 0: + workflow_external_condition_requests_triggered += int( + result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if workflow_external_condition_requests_triggered > 0: + print ('\nNumber of workflow external condition requests triggered: %s' % + workflow_external_condition_requests_triggered) + else: + print '\nNo workflow external condition requests were triggered.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/googleads/adwords.py b/googleads/adwords.py index 93749ada..7c3c44ae 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -14,7 +14,6 @@ """Client library for the AdWords API.""" -__author__ = 'Joseph DiLallo' import io import os diff --git a/googleads/common.py b/googleads/common.py index fd0e3ba7..2a3f62ed 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -14,7 +14,6 @@ """Common client library functions and classes used by all products.""" -__author__ = 'Joseph DiLallo' import os import sys @@ -28,7 +27,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.6.0' +VERSION = '3.7.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], diff --git a/googleads/dfa.py b/googleads/dfa.py index afccf285..c3cbfba1 100644 --- a/googleads/dfa.py +++ b/googleads/dfa.py @@ -14,7 +14,6 @@ """Client library for the DoubleClick for Advertisers API.""" -__author__ = 'Joseph DiLallo' import os diff --git a/googleads/dfp.py b/googleads/dfp.py index e7c30d87..72881ca6 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -14,7 +14,6 @@ """Client library for the DoubleClick for Publishers API.""" -__author__ = 'Joseph DiLallo' import csv import datetime @@ -40,7 +39,7 @@ _CHUNK_SIZE = 16 * 1024 # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201403': + 'v201405': ('ActivityGroupService', 'ActivityService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -59,7 +58,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201405': + 'v201408': ('ActivityGroupService', 'ActivityService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -70,18 +69,17 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProductService', - 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardCustomizationService', - 'RateCardCustomizationGroupService', 'RateCardService', + 'OrderService', 'PlacementService', 'PremiumRateService', + 'ProductService', 'ProductTemplateService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201408': - ('ActivityGroupService', 'ActivityService', 'AdRuleService', - 'AudienceSegmentService', 'BaseRateService', 'CompanyService', - 'ContactService', 'ContentBundleService', + 'v201411': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', + 'CompanyService', 'ContactService', 'ContentBundleService', 'ContentMetadataKeyHierarchyService', 'ContentService', 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', 'CreativeWrapperService', 'CustomFieldService', @@ -93,10 +91,10 @@ 'ProductService', 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationReportService', 'ReportService', + 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201411': + 'v201502': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -107,14 +105,16 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PlacementService', 'PremiumRateService', - 'ProductService', 'ProductTemplateService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201502': + 'v201505': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -134,7 +134,7 @@ 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201505': + 'v201508': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -151,6 +151,7 @@ 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', + 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), diff --git a/googleads/errors.py b/googleads/errors.py index 4243cb83..618bc64e 100644 --- a/googleads/errors.py +++ b/googleads/errors.py @@ -14,8 +14,6 @@ """Errors used by the Google Ads Client Library.""" -__author__ = 'Joseph DiLallo' - class GoogleAdsError(Exception): """Parent class of all errors raised by this library.""" diff --git a/googleads/oauth2.py b/googleads/oauth2.py index b5f6b0f3..7caaaee4 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -22,7 +22,6 @@ from independently refreshing the credentials. """ -__author__ = 'Mark Saniscalchi' import datetime @@ -205,7 +204,7 @@ def __init__(self, scope, client_email, key_file, GoogleAdsValueError: If the given key file does not exist. """ try: - with open(key_file) as f: + with open(key_file, 'rb') as f: private_key = f.read() except IOError: raise googleads.errors.GoogleAdsValueError('The specified key file (%s)' diff --git a/setup.py b/setup.py index cd0785d6..d24039c3 100755 --- a/setup.py +++ b/setup.py @@ -16,7 +16,6 @@ """Setup script for the Google Ads Python Client Library.""" -__author__ = 'Mark Saniscalchi' import os import re diff --git a/tests/adwords_test.py b/tests/adwords_test.py index bffad2f8..780a8ef4 100755 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -17,7 +17,6 @@ """Unit tests to cover the adwords module.""" -__author__ = 'Joseph DiLallo' import io import sys diff --git a/tests/common_test.py b/tests/common_test.py index 4c2c8c75..06cc0393 100755 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -16,7 +16,6 @@ """Unit tests to cover the common module.""" -__author__ = 'Joseph DiLallo' import unittest import warnings diff --git a/tests/dfa_test.py b/tests/dfa_test.py index 744bb925..a481957c 100755 --- a/tests/dfa_test.py +++ b/tests/dfa_test.py @@ -16,7 +16,6 @@ """Unit tests to cover the dfa module.""" -__author__ = 'Joseph DiLallo' import unittest diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 7995c450..87f4e3ff 100755 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -16,7 +16,6 @@ """Unit tests to cover the dfp module.""" -__author__ = 'Joseph DiLallo' import StringIO import sys diff --git a/tests/errors_test.py b/tests/errors_test.py index dd3fe094..5bf87320 100755 --- a/tests/errors_test.py +++ b/tests/errors_test.py @@ -16,7 +16,6 @@ """Unit tests to cover the errors module.""" -__author__ = 'Joseph DiLallo' import unittest diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index 5f73d9cb..c2e96b19 100755 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -16,7 +16,6 @@ """Unit tests to cover the oauth2 module.""" -__author__ = 'Mark Saniscalchi' import datetime import unittest From 97743df32eff92cf00cb8beaddcda42dfa0a37f4 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 25 Aug 2015 14:35:49 -0400 Subject: [PATCH 014/180] Commiting latest changes. From 89d826c62218603c446aa5a0754bdeae637313b3 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 8 Oct 2015 00:02:46 -0400 Subject: [PATCH 015/180] Adding support for AdWords v201509. --- ChangeLog | 12 + .../adwords/adwords_appengine_demo/README | 2 +- .../handlers/api_handler.py | 10 +- .../handlers/ndb_handler.py | 8 +- .../adwords_appengine_demo/models/app_user.py | 2 +- .../templates/show_credentials.html | 6 +- .../views/add_adgroup_view.py | 2 +- .../views/add_campaign_view.py | 2 +- .../adwords_appengine_demo/views/init_view.py | 2 +- .../views/show_accounts_view.py | 6 +- .../views/show_adgroups_view.py | 2 +- .../views/show_budget_view.py | 2 +- .../views/show_campaigns_view.py | 2 +- .../views/show_credentials_view.py | 5 +- .../views/update_budget_view.py | 2 +- .../views/update_credentials_view.py | 2 +- .../account_management/create_account.py | 3 +- .../account_management/create_account.py | 3 +- .../v201506/basic_operations/get_keywords.py | 41 +- .../v201506/extensions/add_site_links.py | 8 +- examples/adwords/v201509/__init__.py | 15 + .../v201509/account_management/__init__.py | 15 + .../account_management/create_account.py | 65 +++ .../account_management/get_account_changes.py | 97 ++++ .../get_account_hierarchy.py | 94 ++++ .../v201509/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 222 ++++++++ .../add_ad_group_bid_modifier.py | 76 +++ .../add_click_to_download_ad.py | 110 ++++ .../advanced_operations/add_html5_ad.py | 113 ++++ .../add_text_ad_with_upgraded_urls.py | 112 ++++ .../create_and_attach_shared_keyword_set.py | 129 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 +++++ .../get_ad_group_bid_modifier.py | 74 +++ .../upload_offline_conversions.py | 99 ++++ .../use_shared_bidding_strategy.py | 173 ++++++ .../v201509/basic_operations/__init__.py | 15 + .../v201509/basic_operations/add_ad_groups.py | 113 ++++ .../v201509/basic_operations/add_campaigns.py | 127 +++++ .../v201509/basic_operations/add_keywords.py | 94 ++++ .../v201509/basic_operations/add_text_ads.py | 95 ++++ .../v201509/basic_operations/get_ad_groups.py | 77 +++ .../v201509/basic_operations/get_campaigns.py | 75 +++ .../get_campaigns_with_awql.py | 65 +++ .../v201509/basic_operations/get_keywords.py | 89 +++ .../v201509/basic_operations/get_text_ads.py | 82 +++ .../v201509/basic_operations/pause_ad.py | 62 ++ .../v201509/basic_operations/remove_ad.py | 63 +++ .../basic_operations/remove_ad_group.py | 59 ++ .../basic_operations/remove_campaign.py | 59 ++ .../basic_operations/remove_keyword.py | 69 +++ .../basic_operations/update_ad_group.py | 59 ++ .../basic_operations/update_campaign.py | 59 ++ .../basic_operations/update_keyword.py | 84 +++ .../v201509/campaign_management/__init__.py | 15 + .../add_campaign_labels.py | 68 +++ .../campaign_management/add_experiment.py | 129 +++++ .../add_keywords_in_bulk.py | 136 +++++ .../get_all_disapproved_ads.py | 75 +++ .../get_all_disapproved_ads_with_awql.py | 64 +++ .../get_campaigns_by_label.py | 86 +++ .../campaign_management/promote_experiment.py | 62 ++ .../campaign_management/set_ad_parameters.py | 104 ++++ .../set_criterion_bid_modifier.py | 78 +++ .../campaign_management/validate_text_ad.py | 88 +++ .../v201509/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 121 ++++ .../handle_policy_violation_error.py | 115 ++++ .../adwords/v201509/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../v201509/extensions/add_site_links.py | 126 +++++ .../extensions/add_site_links_using_feeds.py | 235 ++++++++ .../adwords/v201509/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 529 ++++++++++++++++++ .../v201509/migration/upgrade_ad_url.py | 80 +++ examples/adwords/v201509/misc/__init__.py | 15 + .../v201509/misc/get_all_images_and_videos.py | 86 +++ examples/adwords/v201509/misc/upload_image.py | 67 +++ .../v201509/misc/upload_media_bundle.py | 61 ++ .../adwords/v201509/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 134 +++++ .../get_keyword_bid_simulations.py | 83 +++ .../v201509/optimization/get_keyword_ideas.py | 92 +++ .../adwords/v201509/remarketing/__init__.py | 15 + .../v201509/remarketing/add_audience.py | 104 ++++ .../remarketing/add_conversion_tracker.py | 72 +++ .../remarketing/add_crm_based_user_list.py | 99 ++++ .../remarketing/add_rule_based_user_lists.py | 184 ++++++ .../adwords/v201509/reporting/__init__.py | 15 + .../reporting/download_criteria_report.py | 63 +++ .../download_criteria_report_as_stream.py | 79 +++ ...oad_criteria_report_as_stream_with_awql.py | 83 +++ .../download_criteria_report_as_string.py | 61 ++ ...oad_criteria_report_as_string_with_awql.py | 57 ++ .../download_criteria_report_with_awql.py | 61 ++ .../v201509/reporting/get_report_fields.py | 53 ++ examples/adwords/v201509/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 282 ++++++++++ .../v201509/shopping/add_product_scope.py | 104 ++++ .../v201509/shopping/add_shopping_campaign.py | 121 ++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201509/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 162 ++++++ .../add_demographic_targeting_criteria.py | 97 ++++ .../get_campaign_targeting_criteria.py | 86 +++ .../get_targetable_languages_and_carriers.py | 56 ++ .../v201509/targeting/lookup_location.py | 83 +++ examples/adxbuyer/v201409/__init__.py | 0 .../v201409/basic_operations/__init__.py | 0 .../v201409/campaign_management/__init__.py | 0 .../v201409/error_handling/__init__.py | 0 examples/adxbuyer/v201509/__init__.py | 15 + .../v201509/basic_operations/__init__.py | 15 + .../basic_operations/add_ad_groups.py | 2 +- .../basic_operations/add_campaigns.py | 4 +- .../basic_operations/add_placements.py | 2 +- .../add_third_party_redirect_ad.py | 2 +- .../basic_operations/get_placements.py | 2 +- .../get_third_party_redirect_ads.py | 2 +- .../basic_operations/remove_placement.py | 2 +- .../basic_operations/update_placement.py | 2 +- .../v201509/campaign_management/__init__.py | 15 + .../add_placements_in_bulk.py | 2 +- .../v201509/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 2 +- .../create_native_creative.py | 7 - googleads/adwords.py | 48 +- googleads/common.py | 2 +- tests/adwords_test.py | 2 +- tests/common_test.py | 3 +- tests/dfa_test.py | 4 +- tests/dfp_test.py | 7 +- tests/errors_test.py | 2 - tests/oauth2_test.py | 3 +- 134 files changed, 8040 insertions(+), 83 deletions(-) create mode 100644 examples/adwords/v201509/__init__.py create mode 100644 examples/adwords/v201509/account_management/__init__.py create mode 100755 examples/adwords/v201509/account_management/create_account.py create mode 100755 examples/adwords/v201509/account_management/get_account_changes.py create mode 100755 examples/adwords/v201509/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201509/advanced_operations/__init__.py create mode 100755 examples/adwords/v201509/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201509/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201509/advanced_operations/upload_offline_conversions.py create mode 100755 examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201509/basic_operations/__init__.py create mode 100755 examples/adwords/v201509/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201509/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201509/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201509/basic_operations/add_text_ads.py create mode 100755 examples/adwords/v201509/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201509/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201509/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201509/basic_operations/get_text_ads.py create mode 100755 examples/adwords/v201509/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201509/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201509/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201509/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201509/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201509/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201509/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201509/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201509/campaign_management/__init__.py create mode 100755 examples/adwords/v201509/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201509/campaign_management/add_experiment.py create mode 100755 examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py create mode 100755 examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201509/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201509/campaign_management/promote_experiment.py create mode 100755 examples/adwords/v201509/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201509/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201509/error_handling/__init__.py create mode 100755 examples/adwords/v201509/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201509/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201509/extensions/__init__.py create mode 100755 examples/adwords/v201509/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201509/extensions/add_site_links.py create mode 100755 examples/adwords/v201509/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201509/migration/__init__.py create mode 100755 examples/adwords/v201509/migration/migrate_to_extension_settings.py create mode 100755 examples/adwords/v201509/migration/upgrade_ad_url.py create mode 100644 examples/adwords/v201509/misc/__init__.py create mode 100755 examples/adwords/v201509/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201509/misc/upload_image.py create mode 100755 examples/adwords/v201509/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201509/optimization/__init__.py create mode 100755 examples/adwords/v201509/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201509/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201509/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201509/remarketing/__init__.py create mode 100755 examples/adwords/v201509/remarketing/add_audience.py create mode 100755 examples/adwords/v201509/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201509/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201509/remarketing/add_rule_based_user_lists.py create mode 100644 examples/adwords/v201509/reporting/__init__.py create mode 100755 examples/adwords/v201509/reporting/download_criteria_report.py create mode 100755 examples/adwords/v201509/reporting/download_criteria_report_as_stream.py create mode 100755 examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201509/reporting/download_criteria_report_as_string.py create mode 100755 examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201509/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201509/reporting/get_report_fields.py create mode 100644 examples/adwords/v201509/shopping/__init__.py create mode 100755 examples/adwords/v201509/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201509/shopping/add_product_scope.py create mode 100755 examples/adwords/v201509/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201509/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201509/targeting/__init__.py create mode 100755 examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201509/targeting/lookup_location.py delete mode 100644 examples/adxbuyer/v201409/__init__.py delete mode 100644 examples/adxbuyer/v201409/basic_operations/__init__.py delete mode 100644 examples/adxbuyer/v201409/campaign_management/__init__.py delete mode 100644 examples/adxbuyer/v201409/error_handling/__init__.py create mode 100644 examples/adxbuyer/v201509/__init__.py create mode 100644 examples/adxbuyer/v201509/basic_operations/__init__.py rename examples/adxbuyer/{v201409 => v201509}/basic_operations/add_ad_groups.py (99%) rename examples/adxbuyer/{v201409 => v201509}/basic_operations/add_campaigns.py (99%) rename examples/adxbuyer/{v201409 => v201509}/basic_operations/add_placements.py (97%) rename examples/adxbuyer/{v201409 => v201509}/basic_operations/add_third_party_redirect_ad.py (99%) rename examples/adxbuyer/{v201409 => v201509}/basic_operations/get_placements.py (97%) rename examples/adxbuyer/{v201409 => v201509}/basic_operations/get_third_party_redirect_ads.py (99%) rename examples/adxbuyer/{v201409 => v201509}/basic_operations/remove_placement.py (97%) rename examples/adxbuyer/{v201409 => v201509}/basic_operations/update_placement.py (98%) create mode 100644 examples/adxbuyer/v201509/campaign_management/__init__.py rename examples/adxbuyer/{v201409 => v201509}/campaign_management/add_placements_in_bulk.py (99%) create mode 100644 examples/adxbuyer/v201509/error_handling/__init__.py rename examples/adxbuyer/{v201409 => v201509}/error_handling/handle_partial_failures.py (98%) mode change 100755 => 100644 tests/adwords_test.py mode change 100755 => 100644 tests/common_test.py mode change 100755 => 100644 tests/dfa_test.py mode change 100755 => 100644 tests/dfp_test.py mode change 100755 => 100644 tests/errors_test.py mode change 100755 => 100644 tests/oauth2_test.py diff --git a/ChangeLog b/ChangeLog index e229a4d3..3d5c0b5d 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,15 @@ +3.8.0 - 10/7/2015 +* Added support for AdWords v201509. +* Replaced references to MCC accounts with AdWords manager accounts. +* Added upload_media_bundle as a new misc example for AdWords v201509. +* Added add_html5_ad as a new advanced_operations example for AdWords v201509. +* Added add_crm_based_user_list as a new remarketing example for AdWords + v201509. + +3.7.1 - 9/4/2015 +* Fixed issue #68. +* Updated the get_keywords AdWords sample. + 3.7.0 - 8/20/2015 * Update ServiceAccount constructor to open p12 file in binary mode. * Added support for v201508 for the Doubleclick for Publishers Client Library. diff --git a/examples/adwords/adwords_appengine_demo/README b/examples/adwords/adwords_appengine_demo/README index 6885f0e6..189de5ed 100644 --- a/examples/adwords/adwords_appengine_demo/README +++ b/examples/adwords/adwords_appengine_demo/README @@ -11,7 +11,7 @@ to build and host web applications. In order for the web application to communicate with AdWords API, we will use the [Google Ads Python Client Library](https://github.com/googleads/googleads-python-lib). -In this demo, a user signs in and provides their MCC Client Customer Id and +In this demo, a user signs in and provides their AdWords manager account id and other credentials that are used to access the AdWords API and provide the following functionality: diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index 28436736..f68e6d17 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -31,21 +31,21 @@ class APIHandler(object): # The user-agent sent in requests from this demo. _USER_AGENT = 'AppEngine Googleads Demo v%s' % VERSION - def __init__(self, client_id, client_secret, refresh_token, mcc_cid, - dev_token): + def __init__(self, client_id, client_secret, refresh_token, + manager_account_id, dev_token): """Initializes an APIHandler. Args: client_id: The client customer id retrieved from the Developers Console. client_secret: The client secret retrieved from the Developers Console. refresh_token: The refresh token retrieved with generate_refresh_token.py. - mcc_cid: The AdWords MCC Account Client Customer Id. + manager_account_id: The AdWords manager account Id. dev_token: The AdWords Developer Token. """ credentials = GoogleRefreshTokenClient(client_id, client_secret, refresh_token) self.client = AdWordsClient(dev_token, credentials, self._USER_AGENT, - mcc_cid) + manager_account_id) def AddAdGroup(self, client_customer_id, campaign_id, name, status): """Create a new ad group. @@ -133,7 +133,7 @@ def AddCampaign(self, client_customer_id, campaign_name, ad_channel_type, campaign_service.mutate(operations) def GetAccounts(self): - """Return the client accounts associated with the user's MCC account. + """Return the client accounts associated with the user's manager account. Returns: list List of ManagedCustomer data objects. diff --git a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py index 9c73510a..97d6a3e4 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py @@ -42,15 +42,15 @@ def InitUser(): return app_user -def UpdateUserCredentials(client_id, client_secret, refresh_token, mcc_cid, - developer_token): +def UpdateUserCredentials(client_id, client_secret, refresh_token, + manager_account_id, developer_token): """Update the credentials associated with application user. Args: client_id: str Client Id retrieved from the developer's console. client_secret: str Client Secret retrieved from the developer's console. refresh_token: str Refresh token generated with the above client id/secret. - mcc_cid: str Customer Id for the AdWords MCC account. + manager_account_id: str Customer Id for the AdWords manager account. developer_token: str Developer Token for the AdWords account. """ app_user = AppUser.query(AppUser.user == users.get_current_user()).fetch()[0] @@ -58,7 +58,7 @@ def UpdateUserCredentials(client_id, client_secret, refresh_token, mcc_cid, app_user.client_id = client_id app_user.client_secret = client_secret app_user.refresh_token = refresh_token - app_user.mcc_cid = mcc_cid + app_user.manager_account_id = manager_account_id app_user.developer_token = developer_token app_user.put() diff --git a/examples/adwords/adwords_appengine_demo/models/app_user.py b/examples/adwords/adwords_appengine_demo/models/app_user.py index 649c4190..5272ee87 100755 --- a/examples/adwords/adwords_appengine_demo/models/app_user.py +++ b/examples/adwords/adwords_appengine_demo/models/app_user.py @@ -32,5 +32,5 @@ class AppUser(ndb.Model): client_id = ndb.StringProperty(required=False) client_secret = ndb.StringProperty(required=False) refresh_token = ndb.StringProperty(required=False) - mcc_cid = ndb.StringProperty(required=False) + adwords_manager_cid = ndb.StringProperty(required=False) developer_token = ndb.StringProperty(required=False) diff --git a/examples/adwords/adwords_appengine_demo/templates/show_credentials.html b/examples/adwords/adwords_appengine_demo/templates/show_credentials.html index 3acafc8f..417cb6df 100644 --- a/examples/adwords/adwords_appengine_demo/templates/show_credentials.html +++ b/examples/adwords/adwords_appengine_demo/templates/show_credentials.html @@ -23,9 +23,9 @@ value="{{ refresh_token }}"/> - - + + diff --git a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py index 15d5ea37..ce4d8943 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py @@ -49,7 +49,7 @@ def post(self): handler = APIHandler(app_user.client_id, app_user.client_secret, app_user.refresh_token, - app_user.mcc_cid, + app_user.adwords_manager_cid, app_user.developer_token) # Create new ad group. diff --git a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py index 9e62984f..d86b3181 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py @@ -49,7 +49,7 @@ def post(self): handler = APIHandler(app_user.client_id, app_user.client_secret, app_user.refresh_token, - app_user.mcc_cid, + app_user.adwords_manager_cid, app_user.developer_token) # Create new campaign. diff --git a/examples/adwords/adwords_appengine_demo/views/init_view.py b/examples/adwords/adwords_appengine_demo/views/init_view.py index 5a73b0e0..edb5d935 100755 --- a/examples/adwords/adwords_appengine_demo/views/init_view.py +++ b/examples/adwords/adwords_appengine_demo/views/init_view.py @@ -32,7 +32,7 @@ def get(self): app_user = InitUser() if (app_user.client_id and app_user.client_secret and - app_user.mcc_cid and app_user.developer_token and + app_user.adwords_manager_cid and app_user.developer_token and app_user.refresh_token): self.redirect('/showAccounts') else: diff --git a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py index 5201230f..2813a14a 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Handles request to view accounts associated with MCC Cluent Customer Id.""" +"""Handles request to view accounts associated with manager account Id.""" import os @@ -28,7 +28,7 @@ class ShowAccounts(webapp2.RequestHandler): - """View showing the client accounts for a given MCC Client Customer Id.""" + """View showing the client accounts for a given manager account Id.""" def get(self): """Handle get request.""" @@ -46,7 +46,7 @@ def get(self): handler = APIHandler(app_user.client_id, app_user.client_secret, app_user.refresh_token, - app_user.mcc_cid, + app_user.adwords_manager_cid, app_user.developer_token) # Fetch account info for each client account and place in template. diff --git a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py index e2b84c26..74e00a59 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py @@ -50,7 +50,7 @@ def get(self): handler = APIHandler(app_user.client_id, app_user.client_secret, app_user.refresh_token, - app_user.mcc_cid, + app_user.adwords_manager_cid, app_user.developer_token) adgroups = handler.GetAdGroups(client_customer_id, campaign_id) diff --git a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py index 4b8e2d03..a0f1448c 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py @@ -52,7 +52,7 @@ def get(self): handler = APIHandler(app_user.client_id, app_user.client_secret, app_user.refresh_token, - app_user.mcc_cid, + app_user.adwords_manager_cid, app_user.developer_token) budget = handler.GetBudget(client_customer_id, budget_id) diff --git a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py index 25c1c7ca..05f071f5 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py @@ -50,7 +50,7 @@ def get(self): handler = APIHandler(app_user.client_id, app_user.client_secret, app_user.refresh_token, - app_user.mcc_cid, + app_user.adwords_manager_cid, app_user.developer_token) campaigns = handler.GetCampaigns(client_customer_id) diff --git a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py index b23d3137..af08fa55 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py @@ -47,8 +47,9 @@ def get(self): app_user.client_secret else '') template_values['refresh_token'] = (app_user.refresh_token if app_user.refresh_token else '') - template_values['mcc_cid'] = (app_user.mcc_cid if app_user.mcc_cid - else '') + template_values['adwords_manager_cid'] = ( + app_user.adwords_manager_cid if app_user.adwords_manager_cid else '' + ) template_values['dev_token'] = (app_user.developer_token if app_user.developer_token else '') except Exception, e: diff --git a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py index 71dfc092..53903584 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py @@ -50,7 +50,7 @@ def post(self): handler = APIHandler(app_user.client_id, app_user.client_secret, app_user.refresh_token, - app_user.mcc_cid, + app_user.adwords_manager_cid, app_user.developer_token) # Update the Budget. diff --git a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py index 52d93e9d..3be794b6 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py @@ -41,7 +41,7 @@ def post(self): UpdateUserCredentials(self.request.get('client_id'), self.request.get('client_secret'), self.request.get('refresh_token'), - self.request.get('mcc_cid'), + self.request.get('manager_account_id'), self.request.get('dev_token')) self.redirect('/showCredentials') except Exception, e: diff --git a/examples/adwords/v201502/account_management/create_account.py b/examples/adwords/v201502/account_management/create_account.py index 94eddd14..12536f72 100755 --- a/examples/adwords/v201502/account_management/create_account.py +++ b/examples/adwords/v201502/account_management/create_account.py @@ -16,7 +16,8 @@ """This example illustrates how to create an account. -Note by default this account will only be accessible via parent MCC. +Note by default this account will only be accessible via its parent AdWords +manager account. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home diff --git a/examples/adwords/v201506/account_management/create_account.py b/examples/adwords/v201506/account_management/create_account.py index 406c7d60..6038fcfb 100755 --- a/examples/adwords/v201506/account_management/create_account.py +++ b/examples/adwords/v201506/account_management/create_account.py @@ -16,7 +16,8 @@ """This example illustrates how to create an account. -Note by default this account will only be accessible via parent MCC. +Note by default this account will only be accessible via parent AdWords manager +account. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home diff --git a/examples/adwords/v201506/basic_operations/get_keywords.py b/examples/adwords/v201506/basic_operations/get_keywords.py index e4c75faa..6f618405 100755 --- a/examples/adwords/v201506/basic_operations/get_keywords.py +++ b/examples/adwords/v201506/basic_operations/get_keywords.py @@ -32,8 +32,10 @@ PAGE_SIZE = 500 +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -def main(client): + +def main(client, adgroup_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( 'AdGroupCriterionService', version='v201506') @@ -41,16 +43,24 @@ def main(client): # Construct selector and get all ad group criteria. offset = 0 selector = { - 'fields': ['AdGroupId', 'Id', 'Text', 'KeywordMatchType', 'PlacementUrl'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - }], + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], 'paging': { 'startIndex': str(offset), 'numberResults': str(PAGE_SIZE) - } + }, + 'ordering': [{'field': 'Id', 'sortOrder': 'ASCENDING'}] } more_pages = True while more_pages: @@ -58,12 +68,13 @@ def main(client): # Display results. if 'entries' in page: - for criterion in page['entries']: - print ('Keyword ad group criterion with ad group id \'%s\', criterion ' - 'id \'%s\', text \'%s\', and match type \'%s\' was found.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\'' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) else: print 'No keywords were found.' offset += PAGE_SIZE @@ -75,4 +86,4 @@ def main(client): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201506/extensions/add_site_links.py b/examples/adwords/v201506/extensions/add_site_links.py index 3e54c326..0a43a9e3 100755 --- a/examples/adwords/v201506/extensions/add_site_links.py +++ b/examples/adwords/v201506/extensions/add_site_links.py @@ -48,14 +48,14 @@ def main(client, campaign_id): sitelink1 = { 'xsi_type': 'SitelinkFeedItem', 'sitelinkText': 'Store Hours', - 'sitelinkUrl': 'http://www.example.com/storehours' + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} } # Show the Thanksgiving specials link only from 20 - 27 Nov. sitelink2 = { 'xsi_type': 'SitelinkFeedItem', 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkUrl': 'http://www.example.com/thanksgiving', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, # The time zone of the start and end date/times must match the time zone # of the customer. 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, @@ -68,7 +68,7 @@ def main(client, campaign_id): sitelink3 = { 'xsi_type': 'SitelinkFeedItem', 'sitelinkText': 'Wifi Available', - 'sitelinkUrl': 'http://www.example.com/mobile/wifi', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, # See https://developers.google.com/adwords/api/docs/appendix/platforms # for device criteria IDs. 'devicePreference': {'devicePreference': '30001'} @@ -78,7 +78,7 @@ def main(client, campaign_id): sitelink4 = { 'xsi_type': 'SitelinkFeedItem', 'sitelinkText': 'Happy hours', - 'sitelinkUrl': 'http://www.example.com/happyhours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, 'scheduling': { 'feedItemSchedules': [ { diff --git a/examples/adwords/v201509/__init__.py b/examples/adwords/v201509/__init__.py new file mode 100644 index 00000000..41f5a52e --- /dev/null +++ b/examples/adwords/v201509/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201509/account_management/__init__.py b/examples/adwords/v201509/account_management/__init__.py new file mode 100644 index 00000000..fb8c03ea --- /dev/null +++ b/examples/adwords/v201509/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201509/account_management/create_account.py b/examples/adwords/v201509/account_management/create_account.py new file mode 100755 index 00000000..bf103a7b --- /dev/null +++ b/examples/adwords/v201509/account_management/create_account.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Copyright 2015 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from datetime import datetime + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201509') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/account_management/get_account_changes.py b/examples/adwords/v201509/account_management/get_account_changes.py new file mode 100755 index 00000000..8b0b3107 --- /dev/null +++ b/examples/adwords/v201509/account_management/get_account_changes.py @@ -0,0 +1,97 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201509') + campaign_service = client.GetService('CampaignService', version='v201509') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + print ' Added ad extensions: %s' % data.get('addedAdExtensions') + print ' Removed ad extensions: %s' % data.get('deletedAdExtensions') + print (' Added campaign criteria: %s' + % data.get('addedCampaignCriteria')) + print (' Removed campaign criteria: %s' + % data.get('deletedCampaignCriteria')) + if data.get('changedAdGroups'): + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + print ' Changed ads: %s' % ad_group_data['changedAds'] + print (' Changed criteria: %s' + % ad_group_data['changedCriteria']) + print (' Removed criteria: %s' + % ad_group_data['deletedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/account_management/get_account_hierarchy.py b/examples/adwords/v201509/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..7b0a30c9 --- /dev/null +++ b/examples/adwords/v201509/account_management/get_account_hierarchy.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the account hierarchy under the current account. + +Note: this code example won't work with test accounts. See +https://developers.google.com/adwords/api/docs/test-accounts + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201509') + + # Construct selector to get all accounts. + selector = { + 'fields': ['CustomerId', 'Name'] + } + # Get serviced account graph. + graph = managed_customer_service.get(selector) + if 'entries' in graph and graph['entries']: + # Create map from customerId to parent and child links. + child_links = {} + parent_links = {} + if 'links' in graph: + for link in graph['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Create map from customerID to account and find root account. + accounts = {} + root_account = None + for account in graph['entries']: + accounts[account['customerId']] = account + if account['customerId'] not in parent_links: + root_account = account + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + else: + print 'No serviced accounts were found' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/advanced_operations/__init__.py b/examples/adwords/v201509/advanced_operations/__init__.py new file mode 100644 index 00000000..7e57b8b3 --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201509/advanced_operations/add_ad_customizer.py b/examples/adwords/v201509/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..055a04ec --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/add_ad_customizer.py @@ -0,0 +1,222 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates TextAds that use ad customizations for the specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add TextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no TextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService') + + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'description1': 'Only {=%s.Price}' % feed_name, + 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com' + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..64f14421 --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201509') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..0067ad1c --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,110 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad to ad group ID \'%s\' ' + 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/advanced_operations/add_html5_ad.py b/examples/adwords/v201509/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..c7e5d29f --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/add_html5_ad.py @@ -0,0 +1,113 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..93909358 --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -0,0 +1,112 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a text add that uses advanced features of upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Create the text ad + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print ('AdGroupAd with ID %s and display URL \'%s\'was added.' + % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..b4a66c1a --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,129 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201509') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201509') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201509') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..285c9881 --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201509') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201509') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if page['entries']: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..292958ac --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201509') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py new file mode 100755 index 00000000..50cfc409 --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + conversion_tracker_service = client.GetService('ConversionTrackerService', + version='v201509') + + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201509') + + # Once created, this entry will be visible under + # Tools and Analysis->Conversion and will have "Source = Import". + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'category': 'PAGE_VIEW', + 'name': conversion_name, + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90' + } + + upload_conversion_operation = { + 'operator': 'ADD', + 'operand': upload_conversion + } + + response = conversion_tracker_service.mutate( + [upload_conversion_operation]) + new_upload_conversion = response['value'] + + print ('New upload conversion type with name \'%s\' and ID \'%s\' was ' + 'created.' % (new_upload_conversion['name'], + new_upload_conversion['id'])) + + # Associate offline conversions with the upload conversion we created. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..a02607f7 --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,173 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201509') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201509') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'period': 'DAILY', + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201509') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201509/basic_operations/__init__.py b/examples/adwords/v201509/basic_operations/__init__.py new file mode 100644 index 00000000..80acbea9 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201509/basic_operations/add_ad_groups.py b/examples/adwords/v201509/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..5bc97212 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/add_ad_groups.py @@ -0,0 +1,113 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README.. + +""" + + +import uuid + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201509') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings - these settings only affect + # serving for the Display Network. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/basic_operations/add_campaigns.py b/examples/adwords/v201509/basic_operations/add_campaigns.py new file mode 100755 index 00000000..8bd8a561 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/add_campaigns.py @@ -0,0 +1,127 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201509') + budget_service = client.GetService('BudgetService', version='v201509') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'period': 'DAILY' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/basic_operations/add_keywords.py b/examples/adwords/v201509/basic_operations/add_keywords.py new file mode 100755 index 00000000..6b2bdd75 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/add_keywords.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201509') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/add_text_ads.py b/examples/adwords/v201509/basic_operations/add_text_ads.py new file mode 100755 index 00000000..605a1064 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/add_text_ads.py @@ -0,0 +1,95 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds several text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Construct operations and add ads. + # If needed, you could specify an exemption request here, e.g.: + # 'exemptionRequests': [{ + # # This comes back in a PolicyViolationError. + # 'key' { + # 'policyName': '...', + # 'violatingText': '...' + # } + # }] + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + }, + # Optional fields. + 'status': 'PAUSED' + } + }, + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Enjoy your stay at Red Planet.', + 'description2': 'Buy your tickets now!', + 'headline': 'Luxury Cruise to Mars' + } + } + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad with id \'%s\' and of type \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/get_ad_groups.py b/examples/adwords/v201509/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..914813bf --- /dev/null +++ b/examples/adwords/v201509/basic_operations/get_ad_groups.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2015 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201509') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/basic_operations/get_campaigns.py b/examples/adwords/v201509/basic_operations/get_campaigns.py new file mode 100755 index 00000000..b3233682 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/get_campaigns.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2015 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time + +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201509') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..61cb711e --- /dev/null +++ b/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Copyright 2015 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201509') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/basic_operations/get_keywords.py b/examples/adwords/v201509/basic_operations/get_keywords.py new file mode 100755 index 00000000..332fc6be --- /dev/null +++ b/examples/adwords/v201509/basic_operations/get_keywords.py @@ -0,0 +1,89 @@ +#!/usr/bin/python +# +# Copyright 2015 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201509') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'Id', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\'' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/get_text_ads.py b/examples/adwords/v201509/basic_operations/get_text_ads.py new file mode 100755 index 00000000..00e219b6 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/get_text_ads.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2015 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 text ads for a given ad group. + +To add an ad, run add_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/pause_ad.py b/examples/adwords/v201509/basic_operations/pause_ad.py new file mode 100755 index 00000000..adf64e13 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/pause_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201509/basic_operations/remove_ad.py b/examples/adwords/v201509/basic_operations/remove_ad.py new file mode 100755 index 00000000..9728af22 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/remove_ad.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2015 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201509/basic_operations/remove_ad_group.py b/examples/adwords/v201509/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..077f344b --- /dev/null +++ b/examples/adwords/v201509/basic_operations/remove_ad_group.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2015 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201509') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/remove_campaign.py b/examples/adwords/v201509/basic_operations/remove_campaign.py new file mode 100755 index 00000000..ded3830b --- /dev/null +++ b/examples/adwords/v201509/basic_operations/remove_campaign.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2015 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201509') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/basic_operations/remove_keyword.py b/examples/adwords/v201509/basic_operations/remove_keyword.py new file mode 100755 index 00000000..b9ca0308 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/remove_keyword.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# +# Copyright 2015 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201509') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201509/basic_operations/update_ad_group.py b/examples/adwords/v201509/basic_operations/update_ad_group.py new file mode 100755 index 00000000..d0f8f176 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/update_ad_group.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201509') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/update_campaign.py b/examples/adwords/v201509/basic_operations/update_campaign.py new file mode 100755 index 00000000..cab1e337 --- /dev/null +++ b/examples/adwords/v201509/basic_operations/update_campaign.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201509') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/basic_operations/update_keyword.py b/examples/adwords/v201509/basic_operations/update_keyword.py new file mode 100755 index 00000000..72aac27f --- /dev/null +++ b/examples/adwords/v201509/basic_operations/update_keyword.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2015 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201509') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201509/campaign_management/__init__.py b/examples/adwords/v201509/campaign_management/__init__.py new file mode 100644 index 00000000..db098bda --- /dev/null +++ b/examples/adwords/v201509/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201509/campaign_management/add_campaign_labels.py b/examples/adwords/v201509/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..286a4337 --- /dev/null +++ b/examples/adwords/v201509/campaign_management/add_campaign_labels.py @@ -0,0 +1,68 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201509') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201509/campaign_management/add_experiment.py b/examples/adwords/v201509/campaign_management/add_experiment.py new file mode 100755 index 00000000..2ebfe263 --- /dev/null +++ b/examples/adwords/v201509/campaign_management/add_experiment.py @@ -0,0 +1,129 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates an experiment. + +The created experiment is using a query percentage of 10, which defines what +fraction of auctions should go to the control split (90%) vs. the experiment +split (10%), then adds experimental bid changes for an ad group, and adds an +experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad +groups, run get_ad_groups.py. To get keywords, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import datetime +import uuid + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, campaign_id, ad_group_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201509') + ad_group_service = client.GetService('AdGroupService', version='v201509') + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201509') + + # Construct operations and add experiment. + tomorrow = datetime.datetime.now() + datetime.timedelta(1) + thirty_days = datetime.datetime.now() + datetime.timedelta(30) + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), + 'queryPercentage': '10', + 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), + # Optional fields. + 'status': 'ENABLED', + 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was added.' + % (experiment['name'], experiment['id'])) + + # Construct operations and update ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'experimentData': { + 'xsi_type': 'AdGroupExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'MODIFIED', + 'experimentBidMultipliers': { + 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', + 'maxCpcMultiplier': { + 'multiplier': '0.5' + } + } + } + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' + 'experiment.' % (ad_group['name'], ad_group['id'])) + + # Construct operations and add ad group crierion. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + }, + 'experimentData': { + 'xsi_type': 'BiddableAdGroupCriterionExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'EXPERIMENT_ONLY' + } + } + }] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\' and criterion ' + 'id \'%s\' was added to the experiment.' + % (criterion['adGroupId'], criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py new file mode 100755 index 00000000..861dcfbf --- /dev/null +++ b/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py @@ -0,0 +1,136 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code sample illustrates how to perform asynchronous requests. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import random +import re +import time + +from googleads import adwords +from googleads import errors + + +RETRY_INTERVAL = 10 +RETRIES_COUNT = 30 +KEYWORD_NUMBER = 100 +INDEX_REGEX = r'operations\[(\d+)\].operand' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + mutate_job_service = client.GetService('MutateJobService', version='v201509') + + # Create list of all operations for the job. + operations = [] + + # Create AdGroupCriterionOperations to add keywords. + for i in range(KEYWORD_NUMBER): + keyword = 'mars%d' % i + if random.randint(1, 10) == 1: + keyword += '!!!' + operations.append({ + 'xsi_type': 'AdGroupCriterionOperation', + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': keyword + } + } + }) + + # You can specify up to 3 job IDs that must successfully complete before + # this job can be processed. + policy = { + 'prerequisiteJobIds': [] + } + + # Call mutate to create a new job. + response = mutate_job_service.mutate(operations, policy) + + if not response: + raise errors.GoogleAdsError('Failed to submit a job; aborting.') + + job_id = response['id'] + print 'Job with ID %s was successfully created.' % job_id + + # Create selector to retrieve job status and wait for it to complete. + selector = { + 'xsi_type': 'BulkMutateJobSelector', + 'jobIds': [job_id] + } + + time.sleep(RETRY_INTERVAL) + # Poll for job status until it's finished. + print 'Retrieving job status...' + for i in range(RETRIES_COUNT): + job_status_response = mutate_job_service.get(selector) + status = job_status_response[0]['status'] + if status in ('COMPLETED', 'FAILED'): + break + print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % + (i, status, RETRY_INTERVAL)) + time.sleep(RETRY_INTERVAL) + + if status == 'FAILED': + raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % + job_status_response[0]['failure_reason']) + if status in ('PROCESSING', 'PENDING'): + raise errors.GoogleAdsError('Job did not complete within %d seconds' % + (RETRY_INTERVAL * (RETRIES_COUNT - 1))) + + # Status must be COMPLETED. + # Get the job result. Here we re-use the same selector. + result_response = mutate_job_service.getResult(selector) + + # Output results. + index = 0 + for result in result_response['SimpleMutateResult']['results']: + if 'PlaceHolder' in result: + print 'Operation [%d] - FAILED' % index + else: + print 'Operation [%d] - SUCCEEDED' % index + index += 1 + + # Output errors + for error in result_response['SimpleMutateResult']['errors']: + index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) + reason = error['reason'] + keyword = operations[index]['operand']['criterion']['text'] + print ('ERROR - keyword \'%s\' failed due to \'%s\'' % + (keyword, reason)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..6ac34e1c --- /dev/null +++ b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2015 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Construct selector and get all ads for a given ad group. + selector = { + 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'AdGroupCreativeApprovalStatus', + 'operator': 'IN', + 'values': ['DISAPPROVED'] + } + ] + } + ads = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..ca660dbc --- /dev/null +++ b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2015 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, AdGroupAdDisapprovalReasons ' + 'WHERE CampaignId = %s AND ' + 'AdGroupCreativeApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % campaign_id) + ads = ad_group_ad_service.query(query) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..7d71764d --- /dev/null +++ b/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2015 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time + +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201509') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201509/campaign_management/promote_experiment.py b/examples/adwords/v201509/campaign_management/promote_experiment.py new file mode 100755 index 00000000..e5900edd --- /dev/null +++ b/examples/adwords/v201509/campaign_management/promote_experiment.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2015 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 promotes an experiment. + +Promoting an experiment permanently applies all the experimental changes made to +its related ad groups, criteria and ads. To add an experiment, run +add_experiment.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' + + +def main(client, experiment_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201509') + + # Construct operations and promote experiment. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': experiment_id, + 'status': 'PROMOTED' + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was promoted.' + % (experiment['name'], experiment['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201509/campaign_management/set_ad_parameters.py b/examples/adwords/v201509/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..865e420c --- /dev/null +++ b/examples/adwords/v201509/campaign_management/set_ad_parameters.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2015 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + ad_param_service = client.GetService('AdParamService', version='v201509') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': { + 'urls': ['http://www.example.com'] + }, + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..37ed3795 --- /dev/null +++ b/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2015 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201509') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201509/campaign_management/validate_text_ad.py b/examples/adwords/v201509/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..05a4ee54 --- /dev/null +++ b/examples/adwords/v201509/campaign_management/validate_text_ad.py @@ -0,0 +1,88 @@ +#!/usr/bin/python +# +# Copyright 2015 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 shows how to use validateOnly SOAP header. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Construct operations to add a text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': { + 'urls': ['http://www.example.com'] + }, + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'url': 'http://www.example.com', + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for all astronauts in orbit', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/error_handling/__init__.py b/examples/adwords/v201509/error_handling/__init__.py new file mode 100644 index 00000000..b5203c57 --- /dev/null +++ b/examples/adwords/v201509/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201509/error_handling/handle_partial_failures.py b/examples/adwords/v201509/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..adcdf369 --- /dev/null +++ b/examples/adwords/v201509/error_handling/handle_partial_failures.py @@ -0,0 +1,121 @@ +#!/usr/bin/python +# +# Copyright 2015 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201509') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) + if index: + print ('Keyword ad group criterion with ad group id \'%s\' and text ' + '\'%s\' triggered a failure for the following reason: \'%s\'.' + % (keywords[int(index[0])]['adGroupId'], + keywords[int(index[0])]['criterion']['text'], + error['errorString'])) + else: + print 'The following failure has occurred: \'%s\'.' % error['errorString'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/error_handling/handle_policy_violation_error.py b/examples/adwords/v201509/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..9e114b1c --- /dev/null +++ b/examples/adwords/v201509/error_handling/handle_policy_violation_error.py @@ -0,0 +1,115 @@ +#!/usr/bin/python +# +# Copyright 2015 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201509') + + # Create text ad. + text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'TextAd', + 'headline': 'Mars Cruise!!!', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com', + } + } + } + + operations = [text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + if error['ApiError.Type'] == 'PolicyViolationError': + operation_index = re.findall(r'operations\[(.*)\]\.', + error['fieldPath']) + if operation_index: + operation = operations[int(operation_index[0])] + print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % + (operation['operand']['ad']['headline'], + 'exemptable' if error['isExemptable'] else 'non-exemptable', + error['externalPolicyName'])) + if error['isExemptable'].lower() == 'true': + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text ' + '\'%s\'.' % + (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({ + 'key': error['key'] + }) + else: + # Remove non-exemptable operation + print 'Removing the operation from the request.' + operations.delete(operation) + else: + # Non-policy error returned, re-throw exception. + raise e + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/extensions/__init__.py b/examples/adwords/v201509/extensions/__init__.py new file mode 100644 index 00000000..b4d63e00 --- /dev/null +++ b/examples/adwords/v201509/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201509/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201509/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..2b0e1fdf --- /dev/null +++ b/examples/adwords/v201509/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201509').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201509') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201509/extensions/add_site_links.py b/examples/adwords/v201509/extensions/add_site_links.py new file mode 100755 index 00000000..0102e725 --- /dev/null +++ b/examples/adwords/v201509/extensions/add_site_links.py @@ -0,0 +1,126 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from datetime import datetime + + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201509') + customer_service = client.GetService('CustomerService', version='v201509') + + customer_tz = timezone(customer_service.get()['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt) + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'} + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/extensions/add_site_links_using_feeds.py b/examples/adwords/v201509/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..93b8f2e5 --- /dev/null +++ b/examples/adwords/v201509/extensions/add_site_links_using_feeds.py @@ -0,0 +1,235 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import re +import uuid + +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_1_TEXT = '3' +PLACEHOLDER_FIELD_LINE_2_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201509') + feed_item_service = client.GetService('FeedItemService', version='v201509') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201509') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201509') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 1 Description'}, + {'type': 'STRING', 'name': 'Line 2 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_1_feed_attribute_id = feed['attributes'][2]['id'] + line_2_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % + (line_1_feed_attribute_id, line_2_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line1FeedId'] = line_1_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line1': 'Home line 1', 'line2': 'Home line 2'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line1': 'Support line 1', 'line2': 'Support line 2'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line1': 'Products line 1', 'line2': 'Products line 2'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'stringValue': item['line1'] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/migration/__init__.py b/examples/adwords/v201509/migration/__init__.py new file mode 100644 index 00000000..5de8ecca --- /dev/null +++ b/examples/adwords/v201509/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201509/migration/migrate_to_extension_settings.py b/examples/adwords/v201509/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..ce7f7b11 --- /dev/null +++ b/examples/adwords/v201509/migration/migrate_to_extension_settings.py @@ -0,0 +1,529 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201509') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201509') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201509') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201509') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201509') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201509') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201509') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/migration/upgrade_ad_url.py b/examples/adwords/v201509/migration/upgrade_ad_url.py new file mode 100755 index 00000000..48c6a827 --- /dev/null +++ b/examples/adwords/v201509/migration/upgrade_ad_url.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2015 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 upgrades an ad to use upgraded URLs. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, adgroup_id, ad_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201509') + + selector = { + 'fields': ['Id', 'Url'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [ad_id] + } + ] + } + + page = adgroup_ad_service.get(selector) + + adgroup_ad = page['entries'][0] if page['entries'] else None + + if not adgroup_ad: + raise errors.GoogleAdsError('Ad not found.') + + ad_url_upgrade = { + 'adId': adgroup_ad['ad']['id'], + 'finalUrl': adgroup_ad['ad']['url'] + } + + adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] + + if adgroup_ad: + print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' + % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201509/misc/__init__.py b/examples/adwords/v201509/misc/__init__.py new file mode 100644 index 00000000..30d42e87 --- /dev/null +++ b/examples/adwords/v201509/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201509/misc/get_all_images_and_videos.py b/examples/adwords/v201509/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..ed378a23 --- /dev/null +++ b/examples/adwords/v201509/misc/get_all_images_and_videos.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2015 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201509') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/misc/upload_image.py b/examples/adwords/v201509/misc/upload_image.py new file mode 100755 index 00000000..4ae9eafc --- /dev/null +++ b/examples/adwords/v201509/misc/upload_image.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2015 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 + +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201509') + + with open(image_filename, 'r') as image_handle: + image_data = base64.encodestring(image_handle.read()) + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201509/misc/upload_media_bundle.py b/examples/adwords/v201509/misc/upload_media_bundle.py new file mode 100755 index 00000000..f6cd7dce --- /dev/null +++ b/examples/adwords/v201509/misc/upload_media_bundle.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2015 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 uploads an HTML5 zip file. + +Api: AdWordsOnly +""" + +import base64 +import urllib2 + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201509') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/optimization/__init__.py b/examples/adwords/v201509/optimization/__init__.py new file mode 100644 index 00000000..2e0ca689 --- /dev/null +++ b/examples/adwords/v201509/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..493760ca --- /dev/null +++ b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py @@ -0,0 +1,134 @@ +#!/usr/bin/python +# +# Copyright 2015 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201509') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + selector = { + 'campaignEstimateRequests': [{ + 'adGroupEstimateRequests': [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }], + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ] + }] + } + estimates = traffic_estimator_service.get(selector) + + # Display results. + ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] + keyword_estimates = ad_group_estimate['keywordEstimates'] + for index in xrange(len(keyword_estimates)): + keyword = keyword_estimate_requests[index]['keyword'] + estimate = keyword_estimates[index] + if keyword_estimate_requests[index].get('isNegative', False): + continue + + # Find the mean of the min and max values. + mean_avg_cpc = (calc_mean(estimate['min']['averageCpc']['microAmount'], + estimate['max']['averageCpc']['microAmount']) + if 'averageCpc' in estimate['min'] else 'N/A') + mean_avg_pos = calc_mean(estimate['min']['averagePosition'], + estimate['max']['averagePosition']) + mean_clicks = calc_mean(estimate['min']['clicksPerDay'], + estimate['max']['clicksPerDay']) + mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], + estimate['max']['totalCost']['microAmount']) + + print ('Results for the keyword with text \'%s\' and match type \'%s\':' + % (keyword['text'], keyword['matchType'])) + print ' Estimated average CPC: %s' % mean_avg_cpc + print ' Estimated ad position: %s' % mean_avg_pos + print ' Estimated daily clicks: %s' % mean_clicks + print ' Estimated daily cost: %s' % mean_total_cost + + +def fmt_mean(mean): + if mean: + return '%.2f' % mean + else: + return None + + +def calc_mean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..3c5565df --- /dev/null +++ b/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,83 @@ +#!/usr/bin/python +# +# Copyright 2015 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201509') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201509/optimization/get_keyword_ideas.py b/examples/adwords/v201509/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..ebd1b74b --- /dev/null +++ b/examples/adwords/v201509/optimization/get_keyword_ideas.py @@ -0,0 +1,92 @@ +#!/usr/bin/python +# +# Copyright 2015 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201509') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/remarketing/__init__.py b/examples/adwords/v201509/remarketing/__init__.py new file mode 100644 index 00000000..b39776a8 --- /dev/null +++ b/examples/adwords/v201509/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201509/remarketing/add_audience.py b/examples/adwords/v201509/remarketing/add_audience.py new file mode 100755 index 00000000..945d4694 --- /dev/null +++ b/examples/adwords/v201509/remarketing/add_audience.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201509') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201509') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/remarketing/add_conversion_tracker.py b/examples/adwords/v201509/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..2654ff11 --- /dev/null +++ b/examples/adwords/v201509/remarketing/add_conversion_tracker.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201509') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'markupLanguage': 'HTML', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/remarketing/add_crm_based_user_list.py b/examples/adwords/v201509/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..3f02d154 --- /dev/null +++ b/examples/adwords/v201509/remarketing/add_crm_based_user_list.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + + +"""Adds a remarketing user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client, emails): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201509') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180, + # This field is required. It links to a service you created that allows + # members of this list to remove themselves. It will be shown in the + # "Why this Ad?" of an ad and so it needs to be verified. Read more about + # "Why this Ad?" here: https://support.google.com/ads/answer/2662850. + 'optOutLink': 'http://endpoint1.example.com/optout' + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + hashed_emails = HashEmails(emails) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'dataType': 'EMAIL_SHA256', + 'members': hashed_emails + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def HashEmails(emails): + """Hashes the given emails using SHA-256. + + Note: Emails are stripped of any whitespace and set to lowercase before + hashing. + + Args: + emails: list of str emails to be hashed. + + Returns: + A list of SHA-256 hashed emails. + """ + return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + + +if __name__ == '__main__': + EMAILS = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, EMAILS) diff --git a/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..6544d4f3 --- /dev/null +++ b/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,184 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201509') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords will logically OR the + # groups together. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/reporting/__init__.py b/examples/adwords/v201509/reporting/__init__.py new file mode 100644 index 00000000..85eee62f --- /dev/null +++ b/examples/adwords/v201509/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201509/reporting/download_criteria_report.py b/examples/adwords/v201509/reporting/download_criteria_report.py new file mode 100755 index 00000000..40878412 --- /dev/null +++ b/examples/adwords/v201509/reporting/download_criteria_report.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import logging +import sys + +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201509') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py new file mode 100755 index 00000000..420cb47e --- /dev/null +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2015 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201509') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..8ec1930c --- /dev/null +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,83 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import logging +import StringIO +import sys + + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201509') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_string.py b/examples/adwords/v201509/reporting/download_criteria_report_as_string.py new file mode 100755 index 00000000..32a9fbd2 --- /dev/null +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_string.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +import logging + +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201509') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..1a9df79f --- /dev/null +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201509') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..b1a272ae --- /dev/null +++ b/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2015 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +Api: AdWordsOnly +""" + + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client, path): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201509') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + with open(path, 'w') as output_file: + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', output_file, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=False) + + print 'Report was downloaded to \'%s\'.' % path + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, PATH) diff --git a/examples/adwords/v201509/reporting/get_report_fields.py b/examples/adwords/v201509/reporting/get_report_fields.py new file mode 100755 index 00000000..eec9ec5a --- /dev/null +++ b/examples/adwords/v201509/reporting/get_report_fields.py @@ -0,0 +1,53 @@ +#!/usr/bin/python +# +# Copyright 2015 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201509') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201509/shopping/__init__.py b/examples/adwords/v201509/shopping/__init__.py new file mode 100644 index 00000000..96422728 --- /dev/null +++ b/examples/adwords/v201509/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201509/shopping/add_product_partition_tree.py b/examples/adwords/v201509/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..3c245206 --- /dev/null +++ b/examples/adwords/v201509/shopping/add_product_partition_tree.py @@ -0,0 +1,282 @@ +#!/usr/bin/python +# +# Copyright 2015 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201509') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) + diff --git a/examples/adwords/v201509/shopping/add_product_scope.py b/examples/adwords/v201509/shopping/add_product_scope.py new file mode 100755 index 00000000..c5d86ec6 --- /dev/null +++ b/examples/adwords/v201509/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2015 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201509') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/shopping/add_shopping_campaign.py b/examples/adwords/v201509/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..f8500d2b --- /dev/null +++ b/examples/adwords/v201509/shopping/add_shopping_campaign.py @@ -0,0 +1,121 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id): + campaign_service = client.GetService('CampaignService', version='v201509') + ad_group_service = client.GetService('AdGroupService', version='v201509') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Set shared budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + adgroup = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group_result = ad_group_service.mutate(adgroup_operations) + + for adgroup in ad_group_result['value']: + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (adgroup['name'], adgroup['id'])) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': adgroup['id'], + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201509/shopping/get_product_category_taxonomy.py b/examples/adwords/v201509/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..6a3c112f --- /dev/null +++ b/examples/adwords/v201509/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2015 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201509') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/targeting/__init__.py b/examples/adwords/v201509/targeting/__init__.py new file mode 100644 index 00000000..2c027ccc --- /dev/null +++ b/examples/adwords/v201509/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..9323d659 --- /dev/null +++ b/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,162 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201509') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create location groups. The IDs can be found in the documentation or + # retrieved with the LocationCriterionService. + florida_tier3 = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'IncomeOperand', + # Tiers are numbered 1-10, and represent 10% segments of earners. + # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. + # Tiers 6 through 10 are grouped into TIER_6_TO_10. + 'tier': 'TIER_3' + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + }, + } + florida_downtown = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'PlacesOfInterestOperand', + # Other valid options: AIRPORT, UNIVERSITY. + 'category': 'DOWNTOWN', + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + } + } + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish, florida_tier3, + florida_downtown] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..10bb9d96 --- /dev/null +++ b/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,97 @@ +#!/usr/bin/python +# +# Copyright 2015 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201509') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..c68df858 --- /dev/null +++ b/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2015 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201509') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..5692ced2 --- /dev/null +++ b/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# +# Copyright 2015 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201509') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201509/targeting/lookup_location.py b/examples/adwords/v201509/targeting/lookup_location.py new file mode 100755 index 00000000..c49fe69f --- /dev/null +++ b/examples/adwords/v201509/targeting/lookup_location.py @@ -0,0 +1,83 @@ +#!/usr/bin/python +# +# Copyright 2015 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201509') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adxbuyer/v201409/__init__.py b/examples/adxbuyer/v201409/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201409/basic_operations/__init__.py b/examples/adxbuyer/v201409/basic_operations/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201409/campaign_management/__init__.py b/examples/adxbuyer/v201409/campaign_management/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201409/error_handling/__init__.py b/examples/adxbuyer/v201409/error_handling/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/adxbuyer/v201509/__init__.py b/examples/adxbuyer/v201509/__init__.py new file mode 100644 index 00000000..55fdaeac --- /dev/null +++ b/examples/adxbuyer/v201509/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Examples for DoubleClick Ad Exchange Buyer SOAP API.""" diff --git a/examples/adxbuyer/v201509/basic_operations/__init__.py b/examples/adxbuyer/v201509/basic_operations/__init__.py new file mode 100644 index 00000000..80acbea9 --- /dev/null +++ b/examples/adxbuyer/v201509/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Basic operations examples.""" diff --git a/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201509/basic_operations/add_ad_groups.py similarity index 99% rename from examples/adxbuyer/v201409/basic_operations/add_ad_groups.py rename to examples/adxbuyer/v201509/basic_operations/add_ad_groups.py index 01d4442b..b9f3b561 100755 --- a/examples/adxbuyer/v201409/basic_operations/add_ad_groups.py +++ b/examples/adxbuyer/v201509/basic_operations/add_ad_groups.py @@ -36,7 +36,7 @@ def main(client, campaign_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201409') + ad_group_service = client.GetService('AdGroupService', version='v201509') # Construct operations and add ad groups. operations = [{ diff --git a/examples/adxbuyer/v201409/basic_operations/add_campaigns.py b/examples/adxbuyer/v201509/basic_operations/add_campaigns.py similarity index 99% rename from examples/adxbuyer/v201409/basic_operations/add_campaigns.py rename to examples/adxbuyer/v201509/basic_operations/add_campaigns.py index 8385b980..6524ce73 100755 --- a/examples/adxbuyer/v201409/basic_operations/add_campaigns.py +++ b/examples/adxbuyer/v201509/basic_operations/add_campaigns.py @@ -32,8 +32,8 @@ def main(client): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201409') - budget_service = client.GetService('BudgetService', version='v201409') + campaign_service = client.GetService('CampaignService', version='v201509') + budget_service = client.GetService('BudgetService', version='v201509') # Create a budget, which can be shared by multiple campaigns. budget = { diff --git a/examples/adxbuyer/v201409/basic_operations/add_placements.py b/examples/adxbuyer/v201509/basic_operations/add_placements.py similarity index 97% rename from examples/adxbuyer/v201409/basic_operations/add_placements.py rename to examples/adxbuyer/v201509/basic_operations/add_placements.py index 0eab3807..0aa78015 100755 --- a/examples/adxbuyer/v201409/basic_operations/add_placements.py +++ b/examples/adxbuyer/v201509/basic_operations/add_placements.py @@ -35,7 +35,7 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') + 'AdGroupCriterionService', version='v201509') # Construct keyword ad group criterion object. placement1 = { diff --git a/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201509/basic_operations/add_third_party_redirect_ad.py similarity index 99% rename from examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py rename to examples/adxbuyer/v201509/basic_operations/add_third_party_redirect_ad.py index 7af580b7..409fcfb5 100755 --- a/examples/adxbuyer/v201409/basic_operations/add_third_party_redirect_ad.py +++ b/examples/adxbuyer/v201509/basic_operations/add_third_party_redirect_ad.py @@ -36,7 +36,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') # Construct operations and add ads. operations = [ diff --git a/examples/adxbuyer/v201409/basic_operations/get_placements.py b/examples/adxbuyer/v201509/basic_operations/get_placements.py similarity index 97% rename from examples/adxbuyer/v201409/basic_operations/get_placements.py rename to examples/adxbuyer/v201509/basic_operations/get_placements.py index 38316425..1a4338b6 100755 --- a/examples/adxbuyer/v201409/basic_operations/get_placements.py +++ b/examples/adxbuyer/v201509/basic_operations/get_placements.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') + 'AdGroupCriterionService', version='v201509') # Construct selector and get all ad group criteria. offset = 0 diff --git a/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201509/basic_operations/get_third_party_redirect_ads.py similarity index 99% rename from examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py rename to examples/adxbuyer/v201509/basic_operations/get_third_party_redirect_ads.py index d9958aa9..32032edc 100755 --- a/examples/adxbuyer/v201409/basic_operations/get_third_party_redirect_ads.py +++ b/examples/adxbuyer/v201509/basic_operations/get_third_party_redirect_ads.py @@ -35,7 +35,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201409') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') # Construct selector and get all ads for a given ad group. offset = 0 diff --git a/examples/adxbuyer/v201409/basic_operations/remove_placement.py b/examples/adxbuyer/v201509/basic_operations/remove_placement.py similarity index 97% rename from examples/adxbuyer/v201409/basic_operations/remove_placement.py rename to examples/adxbuyer/v201509/basic_operations/remove_placement.py index c1e77ff0..e22a904c 100755 --- a/examples/adxbuyer/v201409/basic_operations/remove_placement.py +++ b/examples/adxbuyer/v201509/basic_operations/remove_placement.py @@ -36,7 +36,7 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') + 'AdGroupCriterionService', version='v201509') # Construct operations and delete ad group criteria. operations = [ diff --git a/examples/adxbuyer/v201409/basic_operations/update_placement.py b/examples/adxbuyer/v201509/basic_operations/update_placement.py similarity index 98% rename from examples/adxbuyer/v201409/basic_operations/update_placement.py rename to examples/adxbuyer/v201509/basic_operations/update_placement.py index 9ba0cccb..cfaec8b4 100755 --- a/examples/adxbuyer/v201409/basic_operations/update_placement.py +++ b/examples/adxbuyer/v201509/basic_operations/update_placement.py @@ -36,7 +36,7 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') + 'AdGroupCriterionService', version='v201509') # Construct operations and update bids. operations = [{ diff --git a/examples/adxbuyer/v201509/campaign_management/__init__.py b/examples/adxbuyer/v201509/campaign_management/__init__.py new file mode 100644 index 00000000..db098bda --- /dev/null +++ b/examples/adxbuyer/v201509/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Campaign management examples.""" diff --git a/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201509/campaign_management/add_placements_in_bulk.py similarity index 99% rename from examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py rename to examples/adxbuyer/v201509/campaign_management/add_placements_in_bulk.py index e54a32d9..878b9c47 100755 --- a/examples/adxbuyer/v201409/campaign_management/add_placements_in_bulk.py +++ b/examples/adxbuyer/v201509/campaign_management/add_placements_in_bulk.py @@ -42,7 +42,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201409') + mutate_job_service = client.GetService('MutateJobService', version='v201509') # Create list of all operations for the job. operations = [] diff --git a/examples/adxbuyer/v201509/error_handling/__init__.py b/examples/adxbuyer/v201509/error_handling/__init__.py new file mode 100644 index 00000000..b5203c57 --- /dev/null +++ b/examples/adxbuyer/v201509/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2015 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. + +"""Error handling examples.""" diff --git a/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201509/error_handling/handle_partial_failures.py similarity index 98% rename from examples/adxbuyer/v201409/error_handling/handle_partial_failures.py rename to examples/adxbuyer/v201509/error_handling/handle_partial_failures.py index b59977df..4e8d1ac9 100755 --- a/examples/adxbuyer/v201409/error_handling/handle_partial_failures.py +++ b/examples/adxbuyer/v201509/error_handling/handle_partial_failures.py @@ -40,7 +40,7 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201409') + 'AdGroupCriterionService', version='v201509') # Construct placement ad group criteria objects. placements = [ diff --git a/examples/dfp/v201508/creative_service/create_native_creative.py b/examples/dfp/v201508/creative_service/create_native_creative.py index 6dedd04c..d5939e91 100755 --- a/examples/dfp/v201508/creative_service/create_native_creative.py +++ b/examples/dfp/v201508/creative_service/create_native_creative.py @@ -66,7 +66,6 @@ def main(client, advertiser_id): 'creativeTemplateId': creative_template_id, 'destinationUrl': ('https://play.google.com/store/apps/details?id=' 'com.google.fpl.pie_noon'), - 'isNativeEligible': True, 'creativeTemplateVariableValues': [ { 'xsi_type': 'AssetCreativeTemplateVariableValue', @@ -105,12 +104,6 @@ def main(client, advertiser_id): 'uniqueName': 'DeeplinkclickactionURL', 'value': 'market://details?id=com.google.fpl.pie_noon' }, - { - 'xsi_type': 'UrlCreativeTemplateVariableValue', - 'uniqueName': 'FallbackclickactionURL', - 'value': ('https://play.google.com/store/apps/details?id=' - 'com.google.fpl.pie_noon'), - }, { 'xsi_type': 'StringCreativeTemplateVariableValue', 'uniqueName': 'Body', diff --git a/googleads/adwords.py b/googleads/adwords.py index 7c3c44ae..3ffbfa7f 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -117,6 +117,50 @@ 'SharedSetService': 'cm', 'TargetingIdeaService': 'o', 'TrafficEstimatorService': 'o', + }, + 'v201509': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'BatchJobService': 'cm', + 'BudgetOrderService': 'billing', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'ExperimentService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'GeoLocationService': 'cm', + 'LocationCriterionService': 'cm', + 'MediaService': 'cm', + 'MutateJobService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'ManagedCustomerService': 'mcm', + 'CustomerService': 'mcm', + 'CustomerFeedService': 'cm', + 'BudgetService': 'cm', + 'BiddingStrategyService': 'cm', + 'AdwordsUserListService': 'rm', + 'LabelService': 'cm', } } @@ -205,8 +249,8 @@ def __init__( [optional] client_customer_id: A string identifying which AdWords customer you want to act as. You do not have to provide this if you are using a client - account. You probably want to provide this if you're using an MCC - account. + account. You probably want to provide this if you're using an AdWords + manager account. validate_only: A boolean indicating if you want your request to be validated but not actually executed. partial_failure: A boolean indicating if you want your mutate calls diff --git a/googleads/common.py b/googleads/common.py index 2a3f62ed..13655f04 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -27,7 +27,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.7.0' +VERSION = '3.8.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], diff --git a/tests/adwords_test.py b/tests/adwords_test.py old mode 100755 new mode 100644 index 780a8ef4..4761e52c --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -1,4 +1,3 @@ -#!/usr/bin/python # -*- coding: UTF-8 -*- # # Copyright 2013 Google Inc. All Rights Reserved. @@ -25,6 +24,7 @@ import urllib import urllib2 + import mock import googleads.adwords diff --git a/tests/common_test.py b/tests/common_test.py old mode 100755 new mode 100644 index 06cc0393..e3d9482f --- a/tests/common_test.py +++ b/tests/common_test.py @@ -1,5 +1,3 @@ -#!/usr/bin/python -# # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -20,6 +18,7 @@ import unittest import warnings + import fake_filesystem import fake_tempfile import mock diff --git a/tests/dfa_test.py b/tests/dfa_test.py old mode 100755 new mode 100644 index a481957c..3a191253 --- a/tests/dfa_test.py +++ b/tests/dfa_test.py @@ -1,5 +1,3 @@ -#!/usr/bin/python -# # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,6 +17,7 @@ import unittest + import mock import suds.transport @@ -147,3 +146,4 @@ def testGetService_transportError(self): if __name__ == '__main__': unittest.main() + diff --git a/tests/dfp_test.py b/tests/dfp_test.py old mode 100755 new mode 100644 index 87f4e3ff..2dda75b7 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -1,5 +1,3 @@ -#!/usr/bin/python -# # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,6 +19,7 @@ import sys import unittest + import mock import suds.transport @@ -166,9 +165,7 @@ def testInitializeWithDefaultApplicationName(self): self.assertRaises( googleads.errors.GoogleAdsValueError, googleads.dfp.DfpClient, self.oauth2_client, self.application_name, self.network_code, - self.https_proxy, self.cache, - 'Application name must be set and not be the default [%s]' % - googleads.dfp.DEFAULT_APPLICATION_NAME) + self.https_proxy, self.cache) def testGetService_success(self): service = googleads.dfp._SERVICE_MAP[self.version][0] diff --git a/tests/errors_test.py b/tests/errors_test.py old mode 100755 new mode 100644 index 5bf87320..5f3c5c9f --- a/tests/errors_test.py +++ b/tests/errors_test.py @@ -1,5 +1,3 @@ -#!/usr/bin/python -# # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py old mode 100755 new mode 100644 index c2e96b19..80194aa4 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -1,5 +1,3 @@ -#!/usr/bin/python -# # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -20,6 +18,7 @@ import datetime import unittest + import httplib2 import mock import socks From 38c46c0edc5957353bfdfbb4a89a789b41e96140 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 8 Oct 2015 00:04:09 -0400 Subject: [PATCH 016/180] Commiting latest changes. From 9aa0d96219c4959bcccfbc2cbfcde041f9646259 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 21 Oct 2015 06:43:36 -0700 Subject: [PATCH 017/180] Adding BatchJobService example and utility. --- ChangeLog | 6 + .../add_complete_campaigns_using_batch_job.py | 467 ++++++++++++++++++ .../campaign_management/batch_job_util.py | 185 +++++++ .../campaign_management/set_ad_parameters.py | 4 +- .../campaign_management/validate_text_ad.py | 4 +- .../create_dfa_client_with_service_account.py | 53 -- .../create_dfa_client_without_yaml.py | 58 --- .../authentication/generate_refresh_token.py | 61 --- .../dfa/v1_20/add_advertiser_user_filter.py | 85 ---- .../assign_advertisers_to_advertiser_group.py | 53 -- .../v1_20/assign_creatives_to_placements.py | 76 --- examples/dfa/v1_20/create_advertiser.py | 53 -- examples/dfa/v1_20/create_advertiser_group.py | 52 -- examples/dfa/v1_20/create_campaign.py | 81 --- examples/dfa/v1_20/create_content_category.py | 52 -- examples/dfa/v1_20/create_creative_field.py | 57 --- .../dfa/v1_20/create_creative_field_value.py | 58 --- examples/dfa/v1_20/create_creative_group.py | 60 --- .../dfa/v1_20/create_flash_inpage_creative.py | 82 --- examples/dfa/v1_20/create_html_asset.py | 66 --- examples/dfa/v1_20/create_image_asset.py | 66 --- .../v1_20/create_in_stream_video_creative.py | 85 ---- examples/dfa/v1_20/create_placement.py | 90 ---- .../dfa/v1_20/create_placement_strategy.py | 52 -- examples/dfa/v1_20/create_rotation_group.py | 102 ---- .../dfa/v1_20/create_spotlight_activity.py | 66 --- .../v1_20/create_spotlight_activity_group.py | 60 --- examples/dfa/v1_20/create_subnetwork.py | 66 --- examples/dfa/v1_20/create_user_role.py | 77 --- examples/dfa/v1_20/download_tags.py | 82 --- examples/dfa/v1_20/get_activity_groups.py | 63 --- examples/dfa/v1_20/get_activity_types.py | 51 -- examples/dfa/v1_20/get_ad_types.py | 52 -- examples/dfa/v1_20/get_advertiser_groups.py | 62 --- examples/dfa/v1_20/get_advertisers.py | 66 --- .../dfa/v1_20/get_available_permissions.py | 61 --- examples/dfa/v1_20/get_campaigns.py | 66 --- .../v1_20/get_change_log_for_advertiser.py | 75 --- .../dfa/v1_20/get_change_log_object_types.py | 51 -- examples/dfa/v1_20/get_content_categories.py | 59 --- examples/dfa/v1_20/get_countries.py | 58 --- examples/dfa/v1_20/get_creative_field.py | 66 --- .../dfa/v1_20/get_creative_field_values.py | 61 --- examples/dfa/v1_20/get_creative_groups.py | 66 --- examples/dfa/v1_20/get_creative_types.py | 51 -- examples/dfa/v1_20/get_creatives.py | 70 --- examples/dfa/v1_20/get_dfa_site.py | 58 --- .../dfa/v1_20/get_placement_strategies.py | 59 --- examples/dfa/v1_20/get_placement_types.py | 51 -- examples/dfa/v1_20/get_placements.py | 59 --- examples/dfa/v1_20/get_pricing_types.py | 51 -- examples/dfa/v1_20/get_size.py | 60 --- examples/dfa/v1_20/get_subnetworks.py | 64 --- examples/dfa/v1_20/get_tag_method_types.py | 51 -- examples/dfa/v1_20/get_user_filter_types.py | 51 -- examples/dfa/v1_20/get_user_roles.py | 68 --- examples/dfa/v1_20/get_users.py | 60 --- googleads.yaml | 6 - googleads/__init__.py | 1 - googleads/adwords.py | 1 - googleads/dfa.py | 189 ------- googleads/oauth2.py | 3 +- setup.py | 2 +- tests/dfa_test.py | 149 ------ tests/oauth2_test.py | 6 - 65 files changed, 662 insertions(+), 3664 deletions(-) create mode 100755 examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201509/campaign_management/batch_job_util.py delete mode 100755 examples/dfa/authentication/create_dfa_client_with_service_account.py delete mode 100755 examples/dfa/authentication/create_dfa_client_without_yaml.py delete mode 100755 examples/dfa/authentication/generate_refresh_token.py delete mode 100755 examples/dfa/v1_20/add_advertiser_user_filter.py delete mode 100755 examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py delete mode 100755 examples/dfa/v1_20/assign_creatives_to_placements.py delete mode 100755 examples/dfa/v1_20/create_advertiser.py delete mode 100755 examples/dfa/v1_20/create_advertiser_group.py delete mode 100755 examples/dfa/v1_20/create_campaign.py delete mode 100755 examples/dfa/v1_20/create_content_category.py delete mode 100755 examples/dfa/v1_20/create_creative_field.py delete mode 100755 examples/dfa/v1_20/create_creative_field_value.py delete mode 100755 examples/dfa/v1_20/create_creative_group.py delete mode 100755 examples/dfa/v1_20/create_flash_inpage_creative.py delete mode 100755 examples/dfa/v1_20/create_html_asset.py delete mode 100755 examples/dfa/v1_20/create_image_asset.py delete mode 100755 examples/dfa/v1_20/create_in_stream_video_creative.py delete mode 100755 examples/dfa/v1_20/create_placement.py delete mode 100755 examples/dfa/v1_20/create_placement_strategy.py delete mode 100755 examples/dfa/v1_20/create_rotation_group.py delete mode 100755 examples/dfa/v1_20/create_spotlight_activity.py delete mode 100755 examples/dfa/v1_20/create_spotlight_activity_group.py delete mode 100755 examples/dfa/v1_20/create_subnetwork.py delete mode 100755 examples/dfa/v1_20/create_user_role.py delete mode 100755 examples/dfa/v1_20/download_tags.py delete mode 100755 examples/dfa/v1_20/get_activity_groups.py delete mode 100755 examples/dfa/v1_20/get_activity_types.py delete mode 100755 examples/dfa/v1_20/get_ad_types.py delete mode 100755 examples/dfa/v1_20/get_advertiser_groups.py delete mode 100755 examples/dfa/v1_20/get_advertisers.py delete mode 100755 examples/dfa/v1_20/get_available_permissions.py delete mode 100755 examples/dfa/v1_20/get_campaigns.py delete mode 100755 examples/dfa/v1_20/get_change_log_for_advertiser.py delete mode 100755 examples/dfa/v1_20/get_change_log_object_types.py delete mode 100755 examples/dfa/v1_20/get_content_categories.py delete mode 100755 examples/dfa/v1_20/get_countries.py delete mode 100755 examples/dfa/v1_20/get_creative_field.py delete mode 100755 examples/dfa/v1_20/get_creative_field_values.py delete mode 100755 examples/dfa/v1_20/get_creative_groups.py delete mode 100755 examples/dfa/v1_20/get_creative_types.py delete mode 100755 examples/dfa/v1_20/get_creatives.py delete mode 100755 examples/dfa/v1_20/get_dfa_site.py delete mode 100755 examples/dfa/v1_20/get_placement_strategies.py delete mode 100755 examples/dfa/v1_20/get_placement_types.py delete mode 100755 examples/dfa/v1_20/get_placements.py delete mode 100755 examples/dfa/v1_20/get_pricing_types.py delete mode 100755 examples/dfa/v1_20/get_size.py delete mode 100755 examples/dfa/v1_20/get_subnetworks.py delete mode 100755 examples/dfa/v1_20/get_tag_method_types.py delete mode 100755 examples/dfa/v1_20/get_user_filter_types.py delete mode 100755 examples/dfa/v1_20/get_user_roles.py delete mode 100755 examples/dfa/v1_20/get_users.py delete mode 100644 googleads/dfa.py delete mode 100644 tests/dfa_test.py diff --git a/ChangeLog b/ChangeLog index 3d5c0b5d..50dce949 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,4 +1,10 @@ +3.8.1 - 10/19/13 +* Added BatchJobService example for AdWords v201509. +* Removed GeoLocationService from AdWords v201509 because it isn't available + in this version. + 3.8.0 - 10/7/2015 +* Removed DFA from GoogleAds SOAP Client Library. * Added support for AdWords v201509. * Replaced references to MCC accounts with AdWords manager accounts. * Added upload_media_bundle as a new misc example for AdWords v201509. diff --git a/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..915c777e --- /dev/null +++ b/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,467 @@ +#!/usr/bin/python +# +# Copyright 2015 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +Api: AdWordsOnly +""" + +import logging +import random +import time +import urllib2 +import uuid + + +from batch_job_util import BatchJobHelper +from batch_job_util import BatchJobServiceIdGenerator +from googleads import adwords + + +# Set logging configuration +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper + batch_job_helper = BatchJobHelper(client) + + batch_job = AddBatchJob(client) + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + + logging.info('Created BatchJob with ID "%d", status "%s", and upload URL ' + '"%s"', batch_job['id'], batch_job['status'], upload_url) + + operations = BuildUploadUrlOperations(batch_job_helper, number_of_campaigns, + number_of_adgroups, number_of_keywords) + + batch_job_helper.UploadBatchJobOperations( + upload_url, *operations) + + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url) + logging.info('Downloaded following response:\n%s', response.read()) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201509') + # Create a BatchJob + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding a TextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new TextAd for each of + the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_id_generator, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_id_generator: a BatchJobServiceIdGenerator instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_id_generator.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_id_generator): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_id_generator: a BatchJobServiceIdGenerator instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_id_generator.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'period': 'DAILY' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_id_generator, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_id_generator: a BatchJobServiceIdGenerator instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_id_generator.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def BuildUploadUrlOperations(batch_job_helper, number_of_campaigns, + number_of_adgroups, number_of_keywords): + """Builds a list of operations that will be uploaded to the BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance used to construct operations. + number_of_campaigns: an int defining the number of Campaigns to be created. + number_of_adgroups: an int defining the number of AdGroups to be created. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + A tuple of str, where each is a set of operations for distinct services. + """ + # Initialize BatchJobServiceIdGenerator. + batch_id_generator = BatchJobServiceIdGenerator() + + # Build BudgetOperations and retrieve in XML form. + budget_operations = BuildBudgetOperations(batch_id_generator) + budget_request_xml = batch_job_helper.GenerateRawRequestXML( + budget_operations, 'BudgetService') + budget_operations_xml = batch_job_helper.ExtractOperations( + budget_request_xml) + # Build CampaignOperations and retrieve in XML form. + campaign_operations = BuildCampaignOperations( + batch_id_generator, budget_operations, number_of_campaigns) + campaign_request_xml = batch_job_helper.GenerateRawRequestXML( + campaign_operations, 'CampaignService') + campaign_operations_xml = batch_job_helper.ExtractOperations( + campaign_request_xml) + # Build CampaignCriterionOperations and retrieve in XML form. + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + campaign_criterion_request_xml = batch_job_helper.GenerateRawRequestXML( + campaign_criterion_operations, 'CampaignCriterionService') + campaign_criterion_operations_xml = ( + batch_job_helper.ExtractOperations( + campaign_criterion_request_xml)) + # Build AdGroupOperations and retrieve in XML form. + adgroup_operations = BuildAdGroupOperations( + batch_id_generator, campaign_operations, number_of_adgroups) + adgroup_request_xml = batch_job_helper.GenerateRawRequestXML( + adgroup_operations, 'AdGroupService') + adgroup_operations_xml = batch_job_helper.ExtractOperations( + adgroup_request_xml) + # Build AdGroupCriterionOperations and retrieve in XML form. + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_criterion_request_xml = batch_job_helper.GenerateRawRequestXML( + adgroup_criterion_operations, 'AdGroupCriterionService') + adgroup_criterion_operations_xml = ( + batch_job_helper.ExtractOperations( + adgroup_criterion_request_xml)) + # Build AdGroupAdOperations and retrieve in XML form. + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + adgroup_ad_request_xml = batch_job_helper.GenerateRawRequestXML( + adgroup_ad_operations, 'AdGroupAdService') + adgroup_ad_operations_xml = batch_job_helper.ExtractOperations( + adgroup_ad_request_xml) + + return (budget_operations_xml, campaign_operations_xml, + campaign_criterion_operations_xml, adgroup_operations_xml, + adgroup_criterion_operations_xml, adgroup_ad_operations_xml) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + logging.info('Batch Job not ready, sleeping for %s seconds.', + sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + logging.info( + 'Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.', + batch_job['id'], batch_job['status'], url) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201509/campaign_management/batch_job_util.py b/examples/adwords/v201509/campaign_management/batch_job_util.py new file mode 100755 index 00000000..f075d725 --- /dev/null +++ b/examples/adwords/v201509/campaign_management/batch_job_util.py @@ -0,0 +1,185 @@ +#!/usr/bin/python +# +# Copyright 2015 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 for use with BatchJobService. + +Api: AdWordsOnly +""" + + +import re +import urllib2 +from xml.etree import ElementTree + + +class BatchJobHelper(object): + """A utility that simplifies working with the BatchJobService.""" + + _VERSION = 'v201509' + _ADWORDS_ENDPOINT = ('https://adwords.google.com/api/adwords/cm/%s' % + _VERSION) + _ADWORDS_NAMESPACE = ('{%s}' % _ADWORDS_ENDPOINT) + # Used to remove namespace from xsi:type Element attributes. + _ATTRIB_NAMESPACE_SUB = re.compile('ns[0-1]:') + # Used to remove the AdWords namespace from Element tags. + _TAG_NAMESPACE_SUB = re.compile(_ADWORDS_NAMESPACE) + + def __init__(self, client): + """Initializes the BatchJobHelper. + + Args: + client: an initialized AdWordsClient. + """ + self.client = client + + def UploadBatchJobOperations(self, upload_url, *operations): + """Uploads operations to the given uploadUrl. + + Args: + upload_url: The url the given operations will be uploaded to. + *operations: The operations being uploaded, provided as strings containing + only the operations tags and their contents. + """ + request_body = ( + '%s' + % (self._ADWORDS_ENDPOINT, ''.join([operation + for operation in operations]))) + + req = urllib2.Request(upload_url) + req.add_header('Content-Type', 'application/xml') + urllib2.urlopen(req, data=request_body) + + def GenerateRawRequestXML(self, operations, service): + """Generates the raw XML for the operations sent to the given service. + + Args: + operations: a list containing operations that could be run by the given + service. + service: a str identifying the name of the service that the operations + would ordinarily be run against. + + Returns: + A str containing the raw XML of the request to the given service that + would execute the given operations. + """ + service = self.client.GetService(service, 'v201509') + service.suds_client.set_options(nosend=True) + service_request = service.mutate(operations).envelope + service.suds_client.set_options(nosend=False) + return service_request + + def ExtractOperations(self, full_soap_xml): + """Extracts operations from API Request XML for use with BatchJobService. + + Args: + full_soap_xml: The full XML for the desired operation, as generated by + suds. + + Returns: + A string containing only the operations portion of the full XML request, + formatted for use with the BatchJobService. If no operations are found, + returns an empty string. + + Raises: + ValueError: If no Operation.Type element is found in the operations. This + ordinarily happens if no xsi_type is specified for the operations. + """ + # Extract mutate element from XML + mutate = BatchJobHelper._GetRawOperationsFromXML(self, full_soap_xml) + + if mutate is not None: + # Ensure operations are formatted correctly for BatchJobService. + for operations in mutate: + self._FormatForBatchJobService(operations) + # Extract the operation type, ensure xsi:type is set for + # BatchJobService. + operation_type = operations.find('Operation.Type') + + if operation_type is None: + raise ValueError('No xsi_type specified for the operations.') + + operations.attrib['xsi:type'] = operation_type.text + operations_xml = ''.join([ElementTree.tostring(operations) + for operations in mutate]) + return operations_xml + else: + return '' + + def _FormatForBatchJobService(self, element): + """Formats contents of all operations for use with the BatchJobService. + + This will recursively remove unnecessary namespaces generated by suds that + would prevent the operations from executing via the BatchJobService. It will + also remove namespaces appended to the xsi:type in some cases that also + cause issues for the BatchJobService. + + Args: + element: a starting Element to be modified to the correct format. + """ + # Remove any unnecessary AdWords namespace from the tag. + element.tag = self._TAG_NAMESPACE_SUB.sub('', element.tag) + xsi_type = element.attrib.get( + '{http://www.w3.org/2001/XMLSchema-instance}type') + # If an xsi_type attribute exists, ensure that the namespace is removed from + # the type. + if xsi_type: + element.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'] = ( + self._ATTRIB_NAMESPACE_SUB.sub('', xsi_type)) + for child in element: + self._FormatForBatchJobService(child) + + def _GetRawOperationsFromXML(self, raw_request_xml): + """Retrieve the raw set of operations from the request XML. + + Args: + raw_request_xml: The full XML for the desired operation, as generated by + suds. + + Returns: + An unmodified mutate Element containing the operations from the raw + request xml. + + Raises: + AttributeError: if the provided XML isn't from AdWords. + """ + root = ElementTree.fromstring(raw_request_xml) + return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( + '%smutate' % self._ADWORDS_NAMESPACE) + + +class BatchJobServiceIdGenerator(object): + """Utility for generating IDs used by the BatchJobService. + + This produces sequential negative IDs used by the BatchJobService as temporary + IDs for resources created while the jobs execute. These can be used across + operations for cases where the ID of one resource a is a dependency of + another resource. + """ + + def __init__(self): + """Initializes the BatchJobServiceIdGenerator.""" + self.i = 0 + + def GetId(self): + """Produces a distinct sequential Id for the BatchJobService. + + Returns: + A negative number that will be the temporary Id for an API resource. + """ + self.i -= 1 + return self.i diff --git a/examples/adwords/v201509/campaign_management/set_ad_parameters.py b/examples/adwords/v201509/campaign_management/set_ad_parameters.py index 865e420c..ad24efbd 100755 --- a/examples/adwords/v201509/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201509/campaign_management/set_ad_parameters.py @@ -48,9 +48,7 @@ def main(client, ad_group_id, criterion_id): 'adGroupId': ad_group_id, 'ad': { 'xsi_type': 'TextAd', - 'finalUrls': { - 'urls': ['http://www.example.com'] - }, + 'finalUrls': ['http://www.example.com'], 'displayUrl': 'example.com', 'description1': 'Low-gravity fun for {param1:cheap}.', 'description2': 'Only {param2:a few} seats left!', diff --git a/examples/adwords/v201509/campaign_management/validate_text_ad.py b/examples/adwords/v201509/campaign_management/validate_text_ad.py index 05a4ee54..683b6937 100755 --- a/examples/adwords/v201509/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201509/campaign_management/validate_text_ad.py @@ -46,9 +46,7 @@ def main(client, ad_group_id): 'adGroupId': ad_group_id, 'ad': { 'xsi_type': 'TextAd', - 'finalUrls': { - 'urls': ['http://www.example.com'] - }, + 'finalUrls': ['http://www.example.com'], 'displayUrl': 'example.com', 'description1': 'Visit the Red Planet in style.', 'description2': 'Low-gravity fun for everyone!', diff --git a/examples/dfa/authentication/create_dfa_client_with_service_account.py b/examples/dfa/authentication/create_dfa_client_with_service_account.py deleted file mode 100755 index e496b485..00000000 --- a/examples/dfa/authentication/create_dfa_client_with_service_account.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/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. - -"""Initializes a DfaClient via impersonation using a Service Account.""" - - -from googleads import dfa -from googleads import oauth2 - -# OAuth 2.0 credential information. In a real application, you'd probably be -# pulling these values from a credential storage. -SERVICE_ACCOUNT_EMAIL = 'INSERT_SERVICE_ACCOUNT_EMAIL_HERE' -KEY_FILE = 'INSERT_PATH_TO_KEY_FILE' -SERVICE_ACCOUNT_USER = 'INSERT_IMPERSONATED_EMAIL_HERE' - -# DFA API information. -USER_PROFILE_NAME = 'INSERT_USER_PROFILE_NAME_HERE' -APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE' - - -def main(service_account_email, key_file, service_account_user, - user_profile_name, application_name): - oauth2_client = oauth2.GoogleServiceAccountClient( - oauth2.GetAPIScope('dfa'), service_account_email, key_file, - sub=service_account_user) - - dfa_client = dfa.DfaClient(user_profile_name, oauth2_client, application_name) - - campaign_service = dfa_client.GetService( - 'campaign', server='https://advertisersapitest.doubleclick.net') - results = campaign_service.getCampaignsByCriteria({}) - if results['records']: - for campaign in results['records']: - print ('Campaign with name \'%s\' and ID \'%s\' was found.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - main(SERVICE_ACCOUNT_EMAIL, KEY_FILE, SERVICE_ACCOUNT_USER, USER_PROFILE_NAME, - APPLICATION_NAME) diff --git a/examples/dfa/authentication/create_dfa_client_without_yaml.py b/examples/dfa/authentication/create_dfa_client_without_yaml.py deleted file mode 100755 index dfa5f80a..00000000 --- a/examples/dfa/authentication/create_dfa_client_without_yaml.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/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. - -"""Initializes a DfaClient without using yaml-cached credentials. - -While our LoadFromStorage method provides a useful shortcut to instantiate a -client if you regularly use just one set of credentials, production applications -may need to swap out users. This example shows you how to create an OAuth 2.0 -client and a DfaClient without relying on a yaml file. -""" - - -from googleads import dfa -from googleads import oauth2 - -# OAuth 2.0 credential information. In a real application, you'd probably be -# pulling these values from a credential storage. -CLIENT_ID = 'INSERT_CLIENT_ID_HERE' -CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' -REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE' - -# DFA API information. -USER_PROFILE_NAME = 'INSERT_USER_PROFILE_NAME_HERE' -APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE' - - -def main(client_id, client_secret, refresh_token, user_profile_name, - application_name): - oauth2_client = oauth2.GoogleRefreshTokenClient( - client_id, client_secret, refresh_token) - - dfa_client = dfa.DfaClient(user_profile_name, oauth2_client, application_name) - - campaign_service = dfa_client.GetService( - 'campaign', server='https://advertisersapitest.doubleclick.net') - results = campaign_service.getCampaignsByCriteria({}) - if results['records']: - for campaign in results['records']: - print ('Campaign with name \'%s\' and ID \'%s\' was found.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - main(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, USER_PROFILE_NAME, - APPLICATION_NAME) diff --git a/examples/dfa/authentication/generate_refresh_token.py b/examples/dfa/authentication/generate_refresh_token.py deleted file mode 100755 index 62665840..00000000 --- a/examples/dfa/authentication/generate_refresh_token.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/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. - -"""Generates a refresh token for use with DFA.""" - - -import sys - -from oauth2client import client - -# Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet, -# please go to https://console.developers.google.com and create a set. -CLIENT_ID = 'INSERT_CLIENT_ID_HERE' -CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' - -# The DFA API OAuth 2.0 scope. -SCOPE = u'https://www.googleapis.com/auth/dfatrafficking' - - -def main(): - """Retrieve and display the access and refresh token.""" - flow = client.OAuth2WebServerFlow( - client_id=CLIENT_ID, - client_secret=CLIENT_SECRET, - scope=[SCOPE], - user_agent='Ads Python Client Library', - redirect_uri='urn:ietf:wg:oauth:2.0:oob') - - authorize_url = flow.step1_get_authorize_url() - - print ('Log into the Google Account you use to access your DFA account' - 'and go to the following URL: \n%s\n' % (authorize_url)) - print 'After approving the token enter the verification code (if specified).' - code = raw_input('Code: ').strip() - - try: - credential = flow.step2_exchange(code) - except client.FlowExchangeError, e: - print 'Authentication has failed: %s' % e - sys.exit(1) - else: - print ('OAuth 2.0 authorization successful!\n\n' - 'Your access token is:\n %s\n\nYour refresh token is:\n %s' - % (credential.access_token, credential.refresh_token)) - - -if __name__ == '__main__': - main() diff --git a/examples/dfa/v1_20/add_advertiser_user_filter.py b/examples/dfa/v1_20/add_advertiser_user_filter.py deleted file mode 100755 index b7d9c0f4..00000000 --- a/examples/dfa/v1_20/add_advertiser_user_filter.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/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. - -"""Adds a filter to a user profile, limiting its access to certain advertisers. - -To get user IDs, run get_users.py. To get advertiser IDs, run -get_advertisers.py. - -A similar pattern can be applied to set filters limiting site, user role, -and/or campaign access for any user. To get the Filter Criteria Type ID, run -get_user_filter_types.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -USER_ID = 'INSERT_USER_ID_HERE' -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, user_id, advertiser_id): - # Initialize appropriate service. - user_service = client.GetService( - 'user', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Retrieve the user who is to be modified. - user = user_service.getUser(user_id) - - # Create and configure a user filter. - advertiser_filter = { - # The following field has been filled in to make a filter that allows a - # user to access only the assigned objects. - # This value was determined using get_user_filter_types.py. - 'userFilterCriteriaId': '2', - # Because this filter used the criteria type "Assigned" it is necessary - # to specify what advertisers this user has access to. This next step - # would be skipped for the criteria types "All" and "None". - - # Create a list of object filters to represent each object the user has - # access to. Since this is an advertiser filter, the list elements - # represent an advertiser each. The size of the list will need to match - # the total number of advertisers the user is assigned. - 'objectFilters': [{ - 'id': advertiser_id - }] - } - - # Add the filter to the user. - user['advertiserUserFilter'] = advertiser_filter - - # Save the changes made and display a success message. - result = user_service.saveUser(user) - - if result: - print 'User with ID \'%s\' was modified.' % result['id'] - else: - print 'No user was modified.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, USER_ID, ADVERTISER_ID) - diff --git a/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py b/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py deleted file mode 100755 index 2e5505b9..00000000 --- a/examples/dfa/v1_20/assign_advertisers_to_advertiser_group.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/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. - -"""This example assigns a list of advertisers to an advertiser group. - -CAUTION: An advertiser that has campaigns associated with it cannot be -removed from an advertiser group once assigned. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_IDS = ['INSERT_FIRST_ADVERTISER_ID_HERE', - 'INSERT_SECOND_ADVERTISER_ID_HERE'] -ADVERTISER_GROUP_IDS = 'INSERT_ADVERTISER_GROUP_ID_HERE' - - -def main(client, advertiser_ids, advertiser_group_id): - # Initialize appropriate service. - advertiser_group_service = client.GetService( - 'advertisergroup', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Assign the advertisers to the advertiser group. - advertiser_group_service.assignAdvertisersToAdvertiserGroup( - advertiser_group_id, advertiser_ids) - print 'Advertisers have been updated.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_IDS, ADVERTISER_GROUP_IDS) diff --git a/examples/dfa/v1_20/assign_creatives_to_placements.py b/examples/dfa/v1_20/assign_creatives_to_placements.py deleted file mode 100755 index be4e3377..00000000 --- a/examples/dfa/v1_20/assign_creatives_to_placements.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/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. - -"""Assigns creatives to placements and creates a unique ad for each assignment. - -To get creatives, run get_creatives.py example. To get placements, -run get_placement.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -CREATIVE_IDS = ['INSERT_FIRST_CREATIVE_ID', 'INSERT_SECOND_CREATIVE_ID'] -PLACEMENT_IDS = ['INSERT_FIRST_PLACEMENT_ID', 'INSERT_SECOND_PLACEMENT_ID'] - - -def main(client, creative_ids, placement_ids): - # Initialize appropriate service. - creative_service = client.GetService( - 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create creative placement assignment structure. - creative_placement_assignments = [] - for index in range(len(creative_ids)): - creative_placement_assignments.append({ - 'xsi_type': 'CreativePlacementAssignment', - 'creativeId': creative_ids[index], - 'placementId': placement_ids[index], - 'placementIds': placement_ids - }) - - # Submit the request. - results = creative_service.assignCreativesToPlacements( - creative_placement_assignments) - - # Display results. - if results: - for assignment_result in results: - if assignment_result['errorMessage'] is None: - print ('Ad with name \'%s\' and ID \'%s\' was created.' % - (assignment_result['adName'], assignment_result['adId'])) - else: - print ('Assignment unsuccessful for creative ID \'%s\' and placementID' - ' \'%s\'. Error message says \'%s\'.' - % (assignment_result['creativeId'], - assignment_result['placementId'], - assignment_result['errorMessage'])) - else: - print 'No ads were created.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, CREATIVE_IDS, PLACEMENT_IDS) diff --git a/examples/dfa/v1_20/create_advertiser.py b/examples/dfa/v1_20/create_advertiser.py deleted file mode 100755 index 962bc0ec..00000000 --- a/examples/dfa/v1_20/create_advertiser.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/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. - -"""This example creates an advertiser in a given DFA network. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - advertiser_service = client.GetService( - 'advertiser', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save advertiser. - advertiser = { - 'name': 'Advertiser %s' % uuid.uuid4(), - 'approved': 'true' - } - - result = advertiser_service.saveAdvertiser(advertiser) - - # Display results. - print 'Advertiser with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/create_advertiser_group.py b/examples/dfa/v1_20/create_advertiser_group.py deleted file mode 100755 index f8e3eaa2..00000000 --- a/examples/dfa/v1_20/create_advertiser_group.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/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. - -"""This example creates an advertiser group. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - advertiser_group_service = client.GetService( - 'advertisergroup', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save advertiser. - advertiser_group = { - 'name': 'AdvertiserGroup %s' % uuid.uuid4() - } - result = advertiser_group_service.saveAdvertiserGroup( - advertiser_group) - - # Display results. - print 'Advertiser group with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/create_campaign.py b/examples/dfa/v1_20/create_campaign.py deleted file mode 100755 index 48d92902..00000000 --- a/examples/dfa/v1_20/create_campaign.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/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. - -"""This example creates a campaign in a given advertiser. - -To create an advertiser, run create_advertiser.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -CAMPAIGN_NAME = 'INSERT_CAMPAIGN_NAME_HERE' -URL = 'INSERT_LANDING_PAGE_URL_HERE' -LANDING_PAGE_NAME = 'INSERT_LANDING_PAGE_NAME_HERE' -START_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % { - 'year': 'INSERT_START_YEAR_HERE', - 'month': int('INSERT_START_MONTH_HERE'), - 'day': int('INSERT_START_DAY_HERE')} -END_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % { - 'year': 'INSERT_END_YEAR_HERE', - 'month': int('INSERT_END_MONTH_HERE'), - 'day': int('INSERT_END_DAY_HERE')} - - -def main(client, advertiser_id, campaign_name, url, landing_page_name, - start_date, end_date): - # Initialize appropriate service. - campaign_service = client.GetService( - 'campaign', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create a default landing page for the campaign and save it. - default_landing_page = { - 'url': url, - 'name': landing_page_name - } - - default_landing_page_id = campaign_service.saveLandingPage( - default_landing_page)['id'] - - # Construct and save the campaign. - campaign = { - 'name': campaign_name, - 'advertiserId': advertiser_id, - 'defaultLandingPageId': default_landing_page_id, - 'archived': 'false', - 'startDate': start_date, - 'endDate': end_date - } - result = campaign_service.saveCampaign(campaign) - - # Display results. - print 'Campaign with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID, CAMPAIGN_NAME, URL, LANDING_PAGE_NAME, - START_DATE, END_DATE) diff --git a/examples/dfa/v1_20/create_content_category.py b/examples/dfa/v1_20/create_content_category.py deleted file mode 100755 index fafc24f1..00000000 --- a/examples/dfa/v1_20/create_content_category.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/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. - -"""This example creates a content category with the given name and description. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - content_category_service = client.GetService( - 'contentcategory', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save content category. - content_category = { - 'name': 'Category %s' % uuid.uuid4() - } - result = content_category_service.saveContentCategory( - content_category) - - # Display results. - print 'Content category with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/create_creative_field.py b/examples/dfa/v1_20/create_creative_field.py deleted file mode 100755 index 213fec2c..00000000 --- a/examples/dfa/v1_20/create_creative_field.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/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. - -"""This example creates a creative field associated with a given advertiser. - -To get an advertiser ID, run get_advertisers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -CREATIVE_FIELD_NAME = 'INSERT_CREATIVE_FIELD_NAME_HERE' - - -def main(client, advertiser_id, creative_field_name): - # Initialize appropriate service. - creative_field_service = client.GetService( - 'creativefield', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save creative field. - creative_field = { - 'name': creative_field_name, - 'advertiserId': advertiser_id, - 'id': '-1' - } - result = creative_field_service.saveCreativeField(creative_field) - - # Display results. - print 'Creative field with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID, CREATIVE_FIELD_NAME) diff --git a/examples/dfa/v1_20/create_creative_field_value.py b/examples/dfa/v1_20/create_creative_field_value.py deleted file mode 100755 index 690b7cc8..00000000 --- a/examples/dfa/v1_20/create_creative_field_value.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/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. - -"""Creates a creative field value associated with a given creative field. - -To get the creative field ID, run get_creative_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -CREATIVE_FIELD_ID = 'INSERT_CREATIVE_FIELD_ID_HERE' -CREATIVE_FIELD_VALUE_NAME = 'INSERT_CREATIVE_FIELD_VALUE_NAME_HERE' - - -def main(client, creative_field_id, creative_field_value_name): - # Initialize appropriate service. - creative_field_service = client.GetService( - 'creativefield', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save creative field value. - creative_field_value = { - 'name': creative_field_value_name, - 'creativeFieldId': creative_field_id, - 'id': '-1' - } - result = creative_field_service.saveCreativeFieldValue( - creative_field_value) - - # Display results. - print 'Creative field value with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, CREATIVE_FIELD_ID, CREATIVE_FIELD_VALUE_NAME) diff --git a/examples/dfa/v1_20/create_creative_group.py b/examples/dfa/v1_20/create_creative_group.py deleted file mode 100755 index 1ffafc6c..00000000 --- a/examples/dfa/v1_20/create_creative_group.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/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. - -"""This example creates a creative group associated with a given advertiser. - -To get an advertiser ID, run get_advertisers.py. Valid group numbers are limited -to 1 or 2. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -GROUP_NUMBER = 'INSERT_GROUP_NUMBER_HERE' -CREATIVE_GROUP_NAME = 'INSERT_CREATIVE_GROUP_NAME_HERE' - - -def main(client, advertiser_id, group_number, creative_group_name): - # Initialize appropriate service. - creative_group_service = client.GetService( - 'creativegroup', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save creative group. - creative_group = { - 'name': creative_group_name, - 'id': '-1', - 'advertiserId': advertiser_id, - 'groupNumber': group_number - } - result = creative_group_service.saveCreativeGroup(creative_group) - - # Display results. - print 'Creative group with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID, GROUP_NUMBER, CREATIVE_GROUP_NAME) diff --git a/examples/dfa/v1_20/create_flash_inpage_creative.py b/examples/dfa/v1_20/create_flash_inpage_creative.py deleted file mode 100755 index 348090a4..00000000 --- a/examples/dfa/v1_20/create_flash_inpage_creative.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/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. - -"""Creates a "Flash InPage" creative in a given advertiser or campaign. - -If no campaign is specified then the creative is created in the advertiser -provided. To get assets file names, run create_html_asset.py and -create_image_asset.py. To get a size ID, run get_size.py. To get a creative -type ID, run get_creative_type.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -CREATIVE_NAME = 'INSERT_CREATIVE_NAME_HERE' -SWF_ASSET_FILE_NAME = 'INSERT_SWF_ASSET_FILE_NAME_HERE' -IMG_ASSET_FILE_NAME = 'INSERT_IMG_ASSET_FILE_NAME_HERE' -SIZE_ID = 'INSERT_SIZE_ID_HERE' - - -def main(client, campaign_id, advertiser_id, creative_name, swf_asset_file_name, - img_asset_file_name, size_id): - # Initialize appropriate service. - creative_service = client.GetService( - 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save flash inpage creative structure. - flash_inpage_creative = { - 'name': creative_name, - 'id': '0', - 'advertiserId': advertiser_id, - 'typeId': '24', - 'sizeId': size_id, - 'codeLocked': 'true', - 'active': 'true', - 'parentFlashAsset': { - 'assetFilename': swf_asset_file_name - }, - 'wmode': 'opaque', - 'backupImageAsset': { - 'assetFilename': img_asset_file_name - }, - 'backupImageTargetWindow': { - 'option': '_blank' - } - } - - result = creative_service.saveCreative( - flash_inpage_creative, campaign_id) - - # Display results. - print 'Flash inpage creative with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, CAMPAIGN_ID, ADVERTISER_ID, CREATIVE_NAME, - SWF_ASSET_FILE_NAME, IMG_ASSET_FILE_NAME, SIZE_ID) diff --git a/examples/dfa/v1_20/create_html_asset.py b/examples/dfa/v1_20/create_html_asset.py deleted file mode 100755 index 50a7faef..00000000 --- a/examples/dfa/v1_20/create_html_asset.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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. - -"""This example creates a HTML creative asset in a given advertiser. - -To create an advertiser, run create_advertiser.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -ASSET_NAME = 'INSERT_SWF_ASSET_NAME_HERE' -PATH_TO_FILE = 'INSERT_PATH_TO_SWF_FILE_HERE' - - -def main(client, advertiser_id, asset_name, path_to_file): - # Initialize appropriate service. - creative_service = client.GetService( - 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Convert file into format that can be sent in SOAP messages. - with open(path_to_file, 'r') as file_handle: - content = base64.encodestring(file_handle.read()) - - # Construct and save HTML asset. - html_asset = { - 'name': asset_name, - 'advertiserId': advertiser_id, - 'content': content, - # Set he following to true if this asset is being used for HTML creative. - 'forHTMLCreatives': 'true' - } - result = creative_service.saveCreativeAsset(html_asset) - - # Display results. - print ('Creative asset with file name of \'%s\' was created.' - % result['savedFilename']) - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID, ASSET_NAME, PATH_TO_FILE) diff --git a/examples/dfa/v1_20/create_image_asset.py b/examples/dfa/v1_20/create_image_asset.py deleted file mode 100755 index b57a5f61..00000000 --- a/examples/dfa/v1_20/create_image_asset.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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. - -"""This example creates an image creative asset in a given advertiser. - -To create an advertiser, run create_advertiser.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -ASSET_NAME = 'INSERT_IMAGE_ASSET_NAME_HERE' -PATH_TO_FILE = 'INSERT_PATH_TO_IMAGE_FILE_HERE' - - -def main(client, advertiser_id, asset_name, path_to_file): - # Initialize appropriate service. - creative_service = client.GetService( - 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Convert file into format that can be sent in SOAP messages. - with open(path_to_file, 'r') as file_handle: - content = base64.encodestring(file_handle.read()) - - # Construct and save image asset. - image_asset = { - 'name': asset_name, - 'advertiserId': advertiser_id, - 'content': content, - 'forHTMLCreatives': 'false' - } - result = creative_service.saveCreativeAsset(image_asset) - - # Display results. - print ('Creative asset with file name of \'%s\' was created.' - % result['savedFilename']) - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID, ASSET_NAME, PATH_TO_FILE) diff --git a/examples/dfa/v1_20/create_in_stream_video_creative.py b/examples/dfa/v1_20/create_in_stream_video_creative.py deleted file mode 100755 index 7a8bf9f0..00000000 --- a/examples/dfa/v1_20/create_in_stream_video_creative.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/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. - -"""Creates an In-Stream video creative associated with a given advertiser. - -If a campaign is specified, the creative is also associated with that campaign. - -To associate In-Stream assets with an In-Stream video creative, first create -the creative and then run upload_in_stream_asset.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfa - - -# Set the parameters for the new In-Stream video creative. -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -VIDEO_DURATION = 'INSERT_VIDEO_DURATION_HERE' -AD_ID = 'INSERT_VAST_AD_ID_HERE' -SURVEY_URL = 'INSERT_VAST_SURVEY_URL_HERE' -CLICK_THROUGH_URL = 'INSERT_VAST_CLICK_THROUGH_URL_HERE' -# You may optionally set a campaign ID. If the campaign ID is set to 0, then the -# creative will be associated only with the advertiser. -CAMPAIGN_ID = '0' - - -def main(client, advertiser_id, video_duration, ad_id, survey_url, - click_through_url, campaign_id): - # Initialize appropriate service. - creative_service = client.GetService( - 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create the In-Stream video creative. - in_stream_video_creative = { - 'advertiserId': advertiser_id, - 'name': 'In-Stream Video Creative #%s' % uuid.uuid4(), - 'videoDuration': video_duration, - # In-Stream video creatives have to be created inactive. One can only be - # set active after at least one media file has been added to it or the API - # will return an error message. - 'active': 'false', - - # Set the video details based on the Video Ad Serving Template (VAST) - # specification. - 'adId': ad_id, - 'description': 'You are viewing an In-Stream Video Creative', - 'surveyUrl': survey_url, - 'clickThroughUrl': click_through_url - } - - # Save the In-Stream video creative. - result = creative_service.saveCreative( - in_stream_video_creative, campaign_id) - - # Display the new creative ID. - print 'In-Stream video creative with ID \'%s\' was created.' % result['Id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID, VIDEO_DURATION, AD_ID, SURVEY_URL, - CLICK_THROUGH_URL, CAMPAIGN_ID) diff --git a/examples/dfa/v1_20/create_placement.py b/examples/dfa/v1_20/create_placement.py deleted file mode 100755 index 13462db1..00000000 --- a/examples/dfa/v1_20/create_placement.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/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. - -"""This example creates a placement in a given campaign. - -Requires the DFA site ID and campaign ID in which the placement will be created -into. To create a campaign, run create_campaign.py. To get DFA site ID, run -get_dfa_site.py. To get a size ID, run get_size.py. To get placement types, run -get_placement_types.py. To get pricing types, run get_pricing_types.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -PLACEMENT_NAME = 'INSERT_PLACEMENT_NAME_HERE' -DFA_SITE_ID = 'INSERT_DFA_SITE_ID_HERE' -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PRICING_TYPE = 'INSERT_PRICING_TYPE_HERE' -PLACEMENT_TYPE = 'INSERT_PLACEMENT_TYPE_HERE' -SIZE_ID = 'INSERT_SIZE_ID_HERE' -START_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % { - 'year': 'INSERT_START_YEAR_HERE', - 'month': int('INSERT_START_MONTH_HERE'), - 'day': int('INSERT_START_DAY_HERE')} -END_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % { - 'year': 'INSERT_END_YEAR_HERE', - 'month': int('INSERT_END_MONTH_HERE'), - 'day': int('INSERT_END_DAY_HERE')} - - -def main(client, placement_name, dfa_site_id, campaign_id, pricing_type, - placement_type, size_id, start_date, end_date): - # Initialize appropriate service. - placement_service = client.GetService( - 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save placement. - placement = { - 'name': placement_name, - 'campaignId': campaign_id, - 'dfaSiteId': dfa_site_id, - 'sizeId': size_id, - 'placementType': placement_type, - 'pricingSchedule': { - 'startDate': start_date, - 'endDate': end_date, - 'pricingType': pricing_type - } - } - - # Set placement tag settings. - tag_options = placement_service.getRegularPlacementTagOptions() - tag_types = [] - for tag_listing in tag_options: - tag_types.append(tag_listing['id']) - - placement['tagSettings'] = {'tagTypes': tag_types} - - result = placement_service.savePlacement(placement) - - # Display results. - print 'Placement with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, PLACEMENT_NAME, DFA_SITE_ID, CAMPAIGN_ID, PRICING_TYPE, - PLACEMENT_TYPE, SIZE_ID, START_DATE, END_DATE) diff --git a/examples/dfa/v1_20/create_placement_strategy.py b/examples/dfa/v1_20/create_placement_strategy.py deleted file mode 100755 index 122ed269..00000000 --- a/examples/dfa/v1_20/create_placement_strategy.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/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. - -"""This example creates a placement strategy with the given name. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - placement_strategy_service = client.GetService( - 'strategy', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save placement strategy. - placement_strategy = { - 'name': 'Strategy %s' % uuid.uuid4() - } - result = placement_strategy_service.savePlacementStrategy( - placement_strategy) - - # Display results. - print 'Placement strategy with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/create_rotation_group.py b/examples/dfa/v1_20/create_rotation_group.py deleted file mode 100755 index a54fea8a..00000000 --- a/examples/dfa/v1_20/create_rotation_group.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/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. - -"""This example creates a rotation group ad in a given campaign. - -To get ad types run get_ad_types.py. Start and end date for the ad must be -within campaign start and end dates. To create creatives, run -create_[type]_creative.py. To get available placements, run get_placements.py. -To get a size ID, run get_size.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -SIZE_ID = 'INSERT_SIZE_ID_HERE' -CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' -PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' -AD_NAME = 'INSERT_AD_NAME_HERE' -START_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % { - 'year': 'INSERT_START_YEAR_HERE', - 'month': int('INSERT_START_MONTH_HERE'), - 'day': int('INSERT_START_DAY_HERE')} -END_DATE = '%(year)s-%(month)02d-%(day)02dT12:00:00' % { - 'year': 'INSERT_END_YEAR_HERE', - 'month': int('INSERT_END_MONTH_HERE'), - 'day': int('INSERT_END_DAY_HERE')} - - -def main(client, campaign_id, size_id, creative_id, placement_id, ad_name, - start_date, end_date): - # Initialize appropriate service. - ad_service = client.GetService( - 'ad', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct basic rotation group structure. - rotation_group = { - 'xsi_type': 'RotationGroup', - 'name': ad_name, - 'active': 'true', - 'archived': 'false', - 'campaignId': campaign_id, - 'sizeId': size_id, - 'typeId': '1', - 'priority': '12', - 'ratio': '1', - 'rotationType': '1', - 'startTime': start_date, - 'endTime': end_date, - } - - # Construct creative assignments and add them to the rotation group. - creative_assignment = { - 'active': 'true', - 'creativeId': creative_id, - 'clickThroughUrl': { - 'defaultLandingPageUsed': 'true', - 'landingPageId': '0' - } - } - rotation_group['creativeAssignments'] = [creative_assignment] - - # Construct placement assignments and add them to the rotation group. - placement_assignment = { - 'active': 'true', - 'placementId': placement_id - } - rotation_group['placementAssignments'] = [placement_assignment] - - # Save the rotation group. - result = ad_service.saveAd(rotation_group) - - # Display results. - print 'Ad with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, CAMPAIGN_ID, SIZE_ID, CREATIVE_ID, PLACEMENT_ID, AD_NAME, - START_DATE, END_DATE) diff --git a/examples/dfa/v1_20/create_spotlight_activity.py b/examples/dfa/v1_20/create_spotlight_activity.py deleted file mode 100755 index 10f88032..00000000 --- a/examples/dfa/v1_20/create_spotlight_activity.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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. - -"""This example creates a spotlight activity in a given activity group. - -To create an activity group, run create_spotlight_activity_group.py. To get tag -methods types, run get_tag_methods.py. To get activity type IDs, run -get_activity_types.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' -ACTIVITY_TYPE_ID = 'INSERT_ACTIVITY_TYPE_ID_HERE' -TAG_METHOD_TYPE_ID = 'INSERT_TAG_METHOD_TYPE_ID_HERE' -URL = 'INSERT_EXPECTED_URL_HERE' -ACTIVITY_NAME = 'INSERT_ACTIVITY_NAME_HERE' - - -def main(client, activity_group_id, activity_type_id, tag_method_type_id, url, - activity_name): - # Initialize appropriate service. - spotlight_service = client.GetService( - 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save spotlight activity. - spotlight_activity = { - 'name': activity_name, - 'activityGroupId': activity_group_id, - 'activityTypeId': activity_type_id, - 'tagMethodTypeId': tag_method_type_id, - 'expectedUrl': url - } - result = spotlight_service.saveSpotlightActivity(spotlight_activity) - - # Display results. - print 'Spotlight activity with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ACTIVITY_GROUP_ID, ACTIVITY_TYPE_ID, TAG_METHOD_TYPE_ID, URL, - ACTIVITY_NAME) diff --git a/examples/dfa/v1_20/create_spotlight_activity_group.py b/examples/dfa/v1_20/create_spotlight_activity_group.py deleted file mode 100755 index 2eeee577..00000000 --- a/examples/dfa/v1_20/create_spotlight_activity_group.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/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. - -"""Creates a new activity group for a given spotlight configuration. - -To get spotlight tag configuration, run get_advertisers.py. To get activity -types, run get_activity_types.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -SPOTLIGHT_CONFIGURATION_ID = 'INSERT_SPOTLIGHT_CONFIGURATION_ID_HERE' -ACTIVITY_TYPE = 'INSERT_ACTIVITY_TYPE_HERE' -GROUP_NAME = 'INSERT_GROUP_NAME_HERE' - - -def main(client, spotlight_configuration_id, activity_type, group_name): - # Initialize appropriate service. - spotlight_service = client.GetService( - 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and save spotlight activity group. - spotlight_activity_group = { - 'name': group_name, - 'spotlightConfigurationId': spotlight_configuration_id, - 'groupType': activity_type - } - result = spotlight_service.saveSpotlightActivityGroup( - spotlight_activity_group) - - # Display results. - print 'Spotlight activity group with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, SPOTLIGHT_CONFIGURATION_ID, ACTIVITY_TYPE, GROUP_NAME) diff --git a/examples/dfa/v1_20/create_subnetwork.py b/examples/dfa/v1_20/create_subnetwork.py deleted file mode 100755 index 4850967a..00000000 --- a/examples/dfa/v1_20/create_subnetwork.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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. - -"""This example creates a subnetwork in a given DFA network. - -To get the network ID, run get_users.py. To get the available permissions, run -get_available_permissions.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -NETWORK_ID = 'INSERT_NETWORK_ID_HERE' -SUBNETWORK_NAME = 'INSERT_SUBNETWORK_NAME_HERE' -PERMISSION1 = 'INSERT_FIRST_PERMISSION_ID_HERE' -PERMISSION2 = 'INSERT_SECOND_PERMISSION_ID_HERE' - - -def main(client, network_id, subnetwork_name, permission1, permission2): - # Initialize appropriate service. - subnetwork_service = client.GetService( - 'subnetwork', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and the basic subnetwork structure. - subnetwork = { - 'name': subnetwork_name, - 'networkId': network_id - } - - # Create an array of all permissions assigned to this subnetwork and add it to - # the subnetwork structure. To get a list of available permissions, run - # get_available_permissions.py. - subnetwork['availablePermissions'] = [permission1, permission2] - - # Save the subnetwork. - result = subnetwork_service.saveSubnetwork(subnetwork) - - # Display results. - print 'Subnetwork with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, NETWORK_ID, SUBNETWORK_NAME, PERMISSION1, PERMISSION2) diff --git a/examples/dfa/v1_20/create_user_role.py b/examples/dfa/v1_20/create_user_role.py deleted file mode 100755 index d713c09d..00000000 --- a/examples/dfa/v1_20/create_user_role.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/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. - -"""This example creates a user role in a given DFA subnetwork. - -To get the subnetwork ID, run get_subnetworks.py. To get the available -permissions, run get_available_permissions.py. To get the parent user role ID, -run get_user_roles.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -USER_ROLE_NAME = 'INSERT_USER_ROLE_NAME_HERE' -SUBNETWORK_ID = 'INSERT_SUBNETWORK_ID_HERE' -PARENT_USER_ROLE_ID = 'INSERT_PARENT_USER_ROLE_ID_HERE' -PERMISSION1_ID = 'INSERT_FIRST_PERMISSION_ID_HERE' -PERMISSION2_ID = 'INSERT_SECOND_PERMISSION_ID_HERE' - - -def main(client, user_role_name, subnetwork_id, parent_user_role_id, - permission1_id, permission2_id): - # Initialize appropriate service. - user_role_service = client.GetService( - 'userrole', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Construct and the basic user role structure. - user_role = { - 'name': user_role_name, - 'subnetworkId': subnetwork_id, - 'parentUserRoleId': parent_user_role_id - } - - # Create an array of all permissions assigned to this user role and add it to - # the user role structure. To get a list of available permissions, run - # get_available_permissions.py. - permission1 = { - 'id': permission1_id - } - permission2 = { - 'id': permission2_id - } - user_role['permissions'] = [permission1, permission2] - - # Save the user role. - result = user_role_service.saveUserRole(user_role) - - # Display results. - print 'User role with ID \'%s\' was created.' % result['id'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, USER_ROLE_NAME, SUBNETWORK_ID, PARENT_USER_ROLE_ID, - PERMISSION1_ID, PERMISSION2_ID) diff --git a/examples/dfa/v1_20/download_tags.py b/examples/dfa/v1_20/download_tags.py deleted file mode 100755 index 32721eab..00000000 --- a/examples/dfa/v1_20/download_tags.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/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. - -"""This example downloads HTML Tags for a given campaign and placement ID. - -To create campaigns, run create_campaign.py. To create placements, run -create_placement.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' - - -def main(client, campaign_id, placement_id): - # Initialize appropriate service. - placement_service = client.GetService( - 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set placement tag search criteria. - placement_tag_criteria = { - 'id': placement_id - } - - # Get placement tag options. - tag_options = placement_service.getRegularPlacementTagOptions() - tag_types = [tag_listing['id'] for tag_listing in tag_options] - - # Add all types of tag options to the search criteria. - placement_tag_criteria['tagOptionIds'] = tag_types - - # Create a list of placement tag search criterias. - placement_tag_criterias = [placement_tag_criteria] - - # Get HTML tags for the placements. - results = placement_service.getPlacementTagData( - campaign_id, placement_tag_criterias) - - # Display tags for the placement ID used as criteria. - for result in results: - for placement_tag_info in result['placementTagInfos']: - print 'Iframe/JavaScript tag for placement \'%s\' is \n%s\n' % ( - placement_tag_info['placement']['name'], - placement_tag_info['iframeJavaScriptTag']) - print 'JavaScript tag for placement \'%s\' is \n%s\n' % ( - placement_tag_info['placement']['name'], - placement_tag_info['javaScriptTag']) - print 'Standard tag for placement \'%s\' is \n%s\n' % ( - placement_tag_info['placement']['name'], - placement_tag_info['standardTag']) - print 'Internal Redirect tag for placement \'%s\' is \n%s\n' % ( - placement_tag_info['placement']['name'], - placement_tag_info['internalRedirectTag']) - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, CAMPAIGN_ID, PLACEMENT_ID) diff --git a/examples/dfa/v1_20/get_activity_groups.py b/examples/dfa/v1_20/get_activity_groups.py deleted file mode 100755 index b92a9e7e..00000000 --- a/examples/dfa/v1_20/get_activity_groups.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/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. - -"""This example displays activity groups names and IDs for a given advertiser. - -To create an advertiser, run create_advertiser.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - spotlight_service = client.GetService( - 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set activity group search criteria structure and use advertiser ID as search - # criteria. - spotlight_activity_group_search_criteria = { - 'advertiserId': advertiser_id - } - - # Get activity groups. - results = spotlight_service.getSpotlightActivityGroups( - spotlight_activity_group_search_criteria) - - # Display activity group names and IDs. - if results['records']: - for activity_group in results['records']: - print ('Activity group with name \'%s\' and ID \'%s\' was found.' - % (activity_group['name'], activity_group['id'])) - else: - print 'No activity groups found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID) diff --git a/examples/dfa/v1_20/get_activity_types.py b/examples/dfa/v1_20/get_activity_types.py deleted file mode 100755 index f479a388..00000000 --- a/examples/dfa/v1_20/get_activity_types.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/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. - -"""This example displays activity type names and IDs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - spotlight_service = client.GetService( - 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get activity types. - results = spotlight_service.getSpotlightActivityTypes() - - # Display activity type names and IDs. - if results: - for activity_type in results: - print ('Activity type with name \'%s\' and ID \'%s\' was found.' - % (activity_type['name'], activity_type['id'])) - else: - print 'No activity types found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_ad_types.py b/examples/dfa/v1_20/get_ad_types.py deleted file mode 100755 index 73c76bc3..00000000 --- a/examples/dfa/v1_20/get_ad_types.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/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 available ad types and displays the name and ID for each type. - - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - ad_service = client.GetService( - 'ad', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get ad types. - results = ad_service.getAdTypes() - - # Display ad type names and IDs. - if results: - for ad_type in results: - print ('Ad type with name \'%s\' and ID \'%s\' was found.' - % (ad_type['name'], ad_type['id'])) - else: - print 'No activity types found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_advertiser_groups.py b/examples/dfa/v1_20/get_advertiser_groups.py deleted file mode 100755 index c7b16ab0..00000000 --- a/examples/dfa/v1_20/get_advertiser_groups.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/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. - -"""Displays advertiser groups for the given search criteria. - -Results are limited to the first 10 records. - - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - advertiser_group_service = client.GetService( - 'advertisergroup', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create advertiser group search criteria structure. - advertiser_group_search_criteria = { - 'pageSize': '10' - } - - # Get advertiser group record set. - results = advertiser_group_service.getAdvertiserGroups( - advertiser_group_search_criteria) - - # Display advertiser group names, IDs and advertiser count. - if results['records']: - for advertiser_group in results['records']: - print ('Advertiser group with name \'%s\', ID \'%s\', containing %s' - ' advertisers was found.' % (advertiser_group['name'], - advertiser_group['id'], - advertiser_group['advertiserCount'])) - else: - print 'No advertiser groups found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_advertisers.py b/examples/dfa/v1_20/get_advertisers.py deleted file mode 100755 index 98407cbf..00000000 --- a/examples/dfa/v1_20/get_advertisers.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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. - -"""Fetches all advertisers in a DFA account. - -This example displays advertiser name, ID and spotlight configuration ID for -the given search criteria. Results are limited to first 10 records. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import googleads.dfa - - -def main(client): - # Initialize appropriate service. - advertiser_service = client.GetService( - 'advertiser', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create advertiser search criteria structure. - page_number = 1 - advertiser_search_criteria = { - 'pageSize': '100', - 'pageNumber': str(page_number) - } - - while True: - # Get advertiser record set. - results = advertiser_service.getAdvertisers(advertiser_search_criteria) - - # Display advertiser names, IDs and spotlight configuration IDs. - if results['records']: - for advertiser in results['records']: - print ('Advertiser with name \'%s\', ID \'%s\', and spotlight ' - 'configuration id \'%s\' was found.' - % (advertiser['name'], advertiser['id'], advertiser['spotId'])) - page_number += 1 - advertiser_search_criteria['pageNumber'] = str(page_number) - if page_number > int(results['totalNumberOfPages']): - break - - print 'Number of results found: %s' % results['totalNumberOfRecords'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = googleads.dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_available_permissions.py b/examples/dfa/v1_20/get_available_permissions.py deleted file mode 100755 index 800cd02f..00000000 --- a/examples/dfa/v1_20/get_available_permissions.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/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. - -"""Displays the permissions that a user role or subnetwork may be granted. - -To get a subnetwork ID, run get_subnetworks.py. - -A user role may not be set with more permissions than the subnetwork it -belongs to. You may enter a subnetwork ID to see the maximum permissions a -user role belonging to it can have, or enter '0' as the subnetwork ID to see -all possible permissions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -SUBNETWORK_ID = 'INSERT_SUBNETWORK_ID_HERE' - - -def main(client, subnetwork_id): - # Initialize appropriate service. - user_role_service = client.GetService( - 'userrole', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get available permissions. - results = user_role_service.getAvailablePermissions(subnetwork_id) - - # Display permission name and its ID. - if results: - for permission in results: - print ('Permission with name \'%s\' and ID \'%s\' was found.' - % (permission['name'], permission['id'])) - else: - print 'No permissions found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, SUBNETWORK_ID) diff --git a/examples/dfa/v1_20/get_campaigns.py b/examples/dfa/v1_20/get_campaigns.py deleted file mode 100755 index 35de6775..00000000 --- a/examples/dfa/v1_20/get_campaigns.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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. - -"""This example gets existing campaigns based on a given search criteria. - -Results are limited to the first 10. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService( - 'campaign', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create campaign search criteria structure. - page_number = 1 - campaign_search_criteria = { - 'pageSize': '100', - 'pageNumber': str(page_number) - } - - while True: - # Get campaign record set. - results = campaign_service.getCampaignsByCriteria( - campaign_search_criteria) - - # Display campaign names and IDs. - if results['records']: - for campaign in results['records']: - print ('Campaign with name \'%s\' and ID \'%s\' was found.' - % (campaign['name'], campaign['id'])) - page_number += 1 - campaign_search_criteria['pageNumber'] = str(page_number) - if page_number > int(results['totalNumberOfPages']): - break - - print 'Number of results found: %s' % results['totalNumberOfRecords'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_change_log_for_advertiser.py b/examples/dfa/v1_20/get_change_log_for_advertiser.py deleted file mode 100755 index 5a7f0891..00000000 --- a/examples/dfa/v1_20/get_change_log_for_advertiser.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/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. - -"""This example displays the change logs of a specified advertiser object. - -Results are limited to the first 10 records. - -A similar pattern can be applied to get change logs for many other object -types. Run get_change_log_object_types.py for a list of other supported object -types and their ID numbers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - change_log_service = client.GetService( - 'changelog', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create change log search criteria structure. - change_log_search_criteria = { - 'pageSize': '10', - 'objectId': advertiser_id, - # The following field has been filled in to choose advertiser change - # logs. This values was determined using get_change_log_object_types.py. - 'objectTypeId': '1' - } - - # Get change log record set. - results = change_log_service.getChangeLogRecords( - change_log_search_criteria) - - # Display the contents of each change log record. - if results['records']: - for change_log in results['records']: - print ('Action \'%s\', Context \'%s\', Change Date \'%s\',' - ' New Value \'%s\', Old Value \'%s\', Profile Name \'%s\'' - ' was found.' - % (change_log['action'], - change_log['context'], change_log['changeDate'], - change_log['newValue'], change_log['oldValue'], - change_log['username'])) - else: - print 'No change log entries found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID) diff --git a/examples/dfa/v1_20/get_change_log_object_types.py b/examples/dfa/v1_20/get_change_log_object_types.py deleted file mode 100755 index 26b04dae..00000000 --- a/examples/dfa/v1_20/get_change_log_object_types.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/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. - -"""This example displays change log object type names and IDs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - change_log_service = client.GetService( - 'changelog', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get change log object types. - results = change_log_service.getChangeLogObjectTypes() - - # Display change log object type names and IDs. - if results: - for object_type in results: - print ('Change log object type with name \'%s\' and ID \'%s\' was found.' - % (object_type['name'], object_type['id'])) - else: - print 'No change log object types found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_content_categories.py b/examples/dfa/v1_20/get_content_categories.py deleted file mode 100755 index 735657d9..00000000 --- a/examples/dfa/v1_20/get_content_categories.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/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. - -"""This example displays available content categories for a given search string. - -Results are limited to 10. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - content_category_service = client.GetService( - 'contentcategory', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create content category search criteria structure. - content_category_search_criteria = { - 'pageSize': '10' - } - - # Get content category record set. - results = content_category_service.getContentCategories( - content_category_search_criteria) - - # Display content category names, IDs and descriptions. - if results['records']: - for content_category in results['records']: - print ('Content category with name \'%s\' and ID \'%s\' was found.' - % (content_category['name'], content_category['id'])) - else: - print 'No content categories found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_countries.py b/examples/dfa/v1_20/get_countries.py deleted file mode 100755 index 4f79e613..00000000 --- a/examples/dfa/v1_20/get_countries.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/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. - -"""Displays all countries matching a search criteria. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - spotlight_service = client.GetService( - 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set search criteria. - country_search_criteria = { - 'secure': 'false' - } - - # Get countries. - results = spotlight_service.getCountriesByCriteria( - country_search_criteria) - - # Display country names, codes and secure server support information. - if results: - for country in results: - print ('Country with name \'%s\', country code \'%s\', and supports a' - ' secure server? \'%s\'.' - % (country['name'], country['countryCode'], country['secure'])) - else: - print 'No countries found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_creative_field.py b/examples/dfa/v1_20/get_creative_field.py deleted file mode 100755 index f376bdf0..00000000 --- a/examples/dfa/v1_20/get_creative_field.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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 and displays available creative fields for a given string. - -Results are limited to the first 10. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_field_service = client.GetService( - 'creativefield', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set up creative field search criteria structure. - creative_field_search_criteria = { - 'advertiserIds': [advertiser_id], - 'pageSize': '10' - } - - # Get creative fields for the selected criteria. - results = creative_field_service.getCreativeFields( - creative_field_search_criteria) - - # Display creative field names, IDs, advertiser IDs, and number of values. - if results['records']: - for creative_field in results['records']: - print ('Creative field with name \'%s\', ID \'%s\', advertiser ID \'%s\',' - ' and containing \'%s\' values was found.' - % (creative_field['name'], creative_field['id'], - creative_field['advertiserId'], - creative_field['totalNumberOfValues'])) - else: - print 'No creative fields found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID) diff --git a/examples/dfa/v1_20/get_creative_field_values.py b/examples/dfa/v1_20/get_creative_field_values.py deleted file mode 100755 index ce2caff6..00000000 --- a/examples/dfa/v1_20/get_creative_field_values.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/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 and displays available creative field values for a given string. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -CREATIVE_FIELD_ID = 'INSERT_CREATIVE_FIELD_ID_HERE' - - -def main(client, creative_field_id): - # Initialize appropriate service. - creative_field_service = client.GetService( - 'creativefield', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set up creative field value search criteria structure. - creative_field_value_search_criteria = { - 'creativeFieldIds': [creative_field_id], - 'pageSize': '10' - } - - # Get creative field values for the selected criteria. - results = creative_field_service.getCreativeFieldValues( - creative_field_value_search_criteria) - - # Display creative field value names and IDs. - if results['records']: - for creative_field_value in results['records']: - print ('Creative field value with name \'%s\' and ID \'%s\' was found.' - % (creative_field_value['name'], creative_field_value['id'])) - else: - print 'No creative field values found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, CREATIVE_FIELD_ID) diff --git a/examples/dfa/v1_20/get_creative_groups.py b/examples/dfa/v1_20/get_creative_groups.py deleted file mode 100755 index 51fdaa99..00000000 --- a/examples/dfa/v1_20/get_creative_groups.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/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 and displays available creative groups for a given advertiser. - -To get an advertiser ID, run get_advertisers.py. Results are limited to the -first 10. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_group_service = client.GetService( - 'creativegroup', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set up creative group search criteria structure. - creative_group_search_criteria = { - 'advertiserIds': [advertiser_id], - } - - # Get creatives groups for the selected criteria. - results = creative_group_service.getCreativeGroups( - creative_group_search_criteria) - - # Display creative group names, IDs, advertiser IDs, and group numbers. - if results['records']: - for creative_field_value in results['records']: - print ('Creative group with name \'%s\', ID \'%s\', advertiser ID \'%s\',' - ' and group number \'%s\' was found.' - % (creative_field_value['name'], creative_field_value['id'], - creative_field_value['advertiserId'], - creative_field_value['groupNumber'])) - else: - print 'No creative groups found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID) diff --git a/examples/dfa/v1_20/get_creative_types.py b/examples/dfa/v1_20/get_creative_types.py deleted file mode 100755 index 03f5236d..00000000 --- a/examples/dfa/v1_20/get_creative_types.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/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. - -"""Gets available creative types and displays the name and ID for each type. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService( - 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get creative types. - results = creative_service.getCreativeTypes() - - # Display creative types and IDs. - if results: - for creative_type in results: - print ('Creative type with name \'%s\' and ID \'%s\' was found.' - % (creative_type['name'], creative_type['id'])) - else: - print 'No creative types found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_creatives.py b/examples/dfa/v1_20/get_creatives.py deleted file mode 100755 index 15187683..00000000 --- a/examples/dfa/v1_20/get_creatives.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/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 and displays available creatives for a given advertiser. - -To create an advertiser, run create_advertiser.py. Results are limited to the -first 10. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService( - 'creative', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set up creative search criteria structure. - page_number = 1 - creative_search_criteria = { - 'advertiserId': advertiser_id, - 'pageSize': '100', - 'pageNumber': str(page_number) - } - - while True: - # Get creatives for the selected criteria. - results = creative_service.getCreatives(creative_search_criteria) - - # Display creative name and its ID. - if results['records']: - for creative in results['records']: - print ('Creative with name \'%s\' and ID \'%s\' was found.' - % (creative['name'], creative['id'])) - page_number += 1 - creative_search_criteria['pageNumber'] = str(page_number) - if page_number > int(results['totalNumberOfPages']): - break - - print 'Number of results found: %s' % results['totalNumberOfRecords'] - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, ADVERTISER_ID) diff --git a/examples/dfa/v1_20/get_dfa_site.py b/examples/dfa/v1_20/get_dfa_site.py deleted file mode 100755 index c10205b6..00000000 --- a/examples/dfa/v1_20/get_dfa_site.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/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. - -"""This example gets existing DFA sites based on a given search criteria. - -Results are limited to the first 10. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - site_service = client.GetService( - 'site', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create DFA site search criteria structure. - dfa_site_search_criteria = { - 'pageSize': '10' - } - - # Get the sites. - results = site_service.getDfaSites(dfa_site_search_criteria) - - # Display DFA site names and IDs. - if results['records']: - for dfa_site in results['records']: - print ('DFA site with name \'%s\' and ID \'%s\' was found.' - % (dfa_site['name'], dfa_site['id'])) - else: - print 'No DFA sites found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_placement_strategies.py b/examples/dfa/v1_20/get_placement_strategies.py deleted file mode 100755 index 99f6a2de..00000000 --- a/examples/dfa/v1_20/get_placement_strategies.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/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. - -"""Displays available placement strategies for a given search string. - -Results are limited to 10. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - placement_strategy_service = client.GetService( - 'strategy', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create placement strategy search criteria structure. - placement_strategy_search_criteria = { - 'pageSize': '10' - } - - # Get placement strategy record set. - results = placement_strategy_service.getPlacementStrategiesByCriteria( - placement_strategy_search_criteria) - - # Display placement strategy names, IDs and descriptions. - if results['records']: - for placement in results['records']: - print ('Placement strategy with name \'%s\' and ID \'%s\' was found.' - % (placement['name'], placement['id'])) - else: - print 'No placement strategies found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_placement_types.py b/examples/dfa/v1_20/get_placement_types.py deleted file mode 100755 index a024644a..00000000 --- a/examples/dfa/v1_20/get_placement_types.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/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. - -"""This example displays placement type names and IDs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - placement_service = client.GetService( - 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get placement types. - results = placement_service.getPlacementTypes() - - # Display placement type names and IDs. - if results: - for placement_type in results: - print ('Placement type with name \'%s\' and ID \'%s\' was found.' - % (placement_type['name'], placement_type['id'])) - else: - print 'No placement types found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_placements.py b/examples/dfa/v1_20/get_placements.py deleted file mode 100755 index edcd6b5a..00000000 --- a/examples/dfa/v1_20/get_placements.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/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. - -"""This example displays available placements for a given search string. - -Results are limited to 10. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - placement_service = client.GetService( - 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set placement search criteria. - placement_search_criteria = { - 'pageSize': '10' - } - - # Get placement types. - results = placement_service.getPlacementsByCriteria( - placement_search_criteria) - - # Display placement names and IDs. - if results['records']: - for placement in results['records']: - print ('Placement with name \'%s\' and ID \'%s\' was found.' - % (placement['name'], placement['id'])) - else: - print 'No placements found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_pricing_types.py b/examples/dfa/v1_20/get_pricing_types.py deleted file mode 100755 index 117212a0..00000000 --- a/examples/dfa/v1_20/get_pricing_types.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/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. - -"""This example displays placement pricing type names and IDs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - placement_service = client.GetService( - 'placement', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get placement pricing types. - results = placement_service.getPricingTypes() - - # Display placement pricing type names and IDs. - if results: - for creative_type in results: - print ('Pricing type with name \'%s\' and ID \'%s\' was found.' - % (creative_type['name'], creative_type['id'])) - else: - print 'No pricing types found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_size.py b/examples/dfa/v1_20/get_size.py deleted file mode 100755 index 53930a2b..00000000 --- a/examples/dfa/v1_20/get_size.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/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. - -"""This example gets the size ID for a given width and height. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -WIDTH = 'INSERT_WIDTH_HERE' -HEIGHT = 'INSERT_HEIGHT_HERE' - - -def main(client, width, height): - # Initialize appropriate service. - size_service = client.GetService( - 'size', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Create size search criteria. - size_search_criteria = { - 'width': width, - 'height': height - } - - # Get size. - size_record_set = size_service.getSizes(size_search_criteria) - - # Display size ID. - if size_record_set['records']: - for size in size_record_set['records']: - print 'Size id for \'%sx%s\' is \'%s\'.' % (width, height, size['id']) - else: - print 'No sizes found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client, WIDTH, HEIGHT) diff --git a/examples/dfa/v1_20/get_subnetworks.py b/examples/dfa/v1_20/get_subnetworks.py deleted file mode 100755 index 8351ee5c..00000000 --- a/examples/dfa/v1_20/get_subnetworks.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/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. - -"""Displays subnetwork names, IDs, and subnetwork IDs for a given search string. - -Results are limited to 10. - -Note that the permissions assigned to a subnetwork are not returned in a -human-readable format with this example. Run get_available_permissions.py to -see what permissions are available on a subnetwork. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - subnetwork_service = client.GetService( - 'subnetwork', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set subnetwork search criteria. - subnetwork_search_criteria = { - 'pageSize': '10' - } - - # Get subnetworks. - results = subnetwork_service.getSubnetworks( - subnetwork_search_criteria) - - # Display subnetwork names, IDs, and subnetwork IDs. - if results['records']: - for subnetwork in results['records']: - print ('Subnetwork with name \'%s\', ID \'%s\', part of network ID \'%s\'' - ' was found.' % (subnetwork['name'], subnetwork['id'], - subnetwork['networkId'])) - else: - print 'No subnetworks found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_tag_method_types.py b/examples/dfa/v1_20/get_tag_method_types.py deleted file mode 100755 index 86d00192..00000000 --- a/examples/dfa/v1_20/get_tag_method_types.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/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. - -"""This example displays activity method type names and IDs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - spotlight_service = client.GetService( - 'spotlight', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get method types. - results = spotlight_service.getSpotlightTagMethodTypes() - - # Display method type names and IDs. - if results: - for method_type in results: - print ('Method type with name \'%s\' and ID \'%s\' was found.' - % (method_type['name'], method_type['id'])) - else: - print 'No method types found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_user_filter_types.py b/examples/dfa/v1_20/get_user_filter_types.py deleted file mode 100755 index 984b5e24..00000000 --- a/examples/dfa/v1_20/get_user_filter_types.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/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. - -"""This example displays user filter criteria type names and IDs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService( - 'user', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Get user filter criteria types. - results = user_service.getAvailableUserFilterCriteriaTypes() - - # Display user filter criteria types. - if results: - for filter_type in results: - print ('User filter criteria type with name \'%s\' and ID \'%s\' was ' - 'found.' % (filter_type['name'], filter_type['id'])) - else: - print 'No user filter criteria types found.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_user_roles.py b/examples/dfa/v1_20/get_user_roles.py deleted file mode 100755 index 8afd61f5..00000000 --- a/examples/dfa/v1_20/get_user_roles.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/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. - -"""Displays user roles for the given search criteria. - -Results are limited to the first 10 records. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - user_role_service = client.GetService( - 'userrole', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set user role search criteria. - user_role_search_criteria = { - 'pageSize': '10' - } - - # Get user roles that match the search criteria. - results = user_role_service.getUserRoles(user_role_search_criteria) - - # Display user role names, IDs, subnetwork IDs, number of assigned users, and - # assigned permissions. - if results['userRoles']: - for user_role in results['userRoles']: - print ('User role with name \'%s\', ID \'%s\', subnetwork ID \'%s\', and ' - 'assigned to \'%s\' users was found.' - % (user_role['name'], user_role['id'], user_role['subnetworkId'], - user_role['totalAssignedUsers'])) - if user_role['permissions']: - print ' The above user role has the following permissions:' - for permission in user_role['permissions']: - print (' Permission with name \'%s\' and ID \'%s\'.' - % (permission['name'], permission['id'])) - else: - print ' The above user role has no permissions assigned.' - else: - print 'No user roles found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/examples/dfa/v1_20/get_users.py b/examples/dfa/v1_20/get_users.py deleted file mode 100755 index b67c63be..00000000 --- a/examples/dfa/v1_20/get_users.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/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. - -"""This example displays users for the given search criteria. - -Results are limited to the first 10 records. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfa - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService( - 'user', 'v1.20', 'https://advertisersapitest.doubleclick.net') - - # Set user search criteria. - user_search_criteria = { - 'pageSize': '10' - } - - # Get users that match the search criteria. - results = user_service.getUsersByCriteria(user_search_criteria) - - # Display user names, IDs, network IDs, subnetwork IDs, and group IDs. - if results['records']: - for user in results['records']: - print ('User with name \'%s\', ID \'%s\', network ID \'%s\', ' - 'subnetwork ID \'%s\', and user role id \'%s\' was found.' - % (user['name'], user['id'], user['networkId'], - user['subnetworkId'], user['userGroupId'])) - else: - print 'No users found for your criteria.' - - -if __name__ == '__main__': - # Initialize client object. - dfa_client = dfa.DfaClient.LoadFromStorage() - main(dfa_client) diff --git a/googleads.yaml b/googleads.yaml index b4c0abfb..7b9a34c9 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -18,12 +18,6 @@ dfp: # unless the network code is set directly on the DfpClient object: # network_code: INSERT_NETWORK_CODE_HERE -dfa: - username: INSERT_DFA_USERNAME_HERE - application_name: INSERT_APPLICATION_NAME_HERE - client_id: INSERT_OAUTH_2_CLIENT_ID_HERE - client_secret: INSERT_CLIENT_SECRET_HERE - refresh_token: INSERT_REFRESH_TOKEN_HERE # The following values are optional: # The following are optional settings for using a proxy. diff --git a/googleads/__init__.py b/googleads/__init__.py index e0beb1d9..1f5e6526 100644 --- a/googleads/__init__.py +++ b/googleads/__init__.py @@ -15,5 +15,4 @@ """A client library for Google's SOAP Ads APIs.""" from adwords import AdWordsClient -from dfa import DfaClient from dfp import DfpClient diff --git a/googleads/adwords.py b/googleads/adwords.py index 3ffbfa7f..aba34710 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -144,7 +144,6 @@ 'FeedItemService': 'cm', 'FeedMappingService': 'cm', 'FeedService': 'cm', - 'GeoLocationService': 'cm', 'LocationCriterionService': 'cm', 'MediaService': 'cm', 'MutateJobService': 'cm', diff --git a/googleads/dfa.py b/googleads/dfa.py deleted file mode 100644 index c3cbfba1..00000000 --- a/googleads/dfa.py +++ /dev/null @@ -1,189 +0,0 @@ -# Copyright 2013 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. - -"""Client library for the DoubleClick for Advertisers API.""" - - -import os - -import suds.client -import suds.sax.element -import suds.transport -import suds.wsse - -import googleads.common -import googleads.errors - - -class DfaClient(object): - """A central location to set headers and create web service clients. - - Attributes: - username: A string representation of your DFA username. - oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize your - requests. - application_name: An arbitrary string which will be used to identify your - application - https_proxy: A string identifying the URL of a proxy that all HTTPS requests - should be routed through. Modifying this value will not affect any SOAP - service clients you've already created. - """ - - # The key in the storage yaml which contains DFA data. - _YAML_KEY = 'dfa' - # A list of values which must be provided to use DFA. - _REQUIRED_INIT_VALUES = ('application_name', 'username') - # A list of values which may optionally be provided when using DFA. - _OPTIONAL_INIT_VALUES = () - # The format of SOAP service WSDLs. A server, version, and service name need - # to be formatted in. - _SOAP_SERVICE_FORMAT = '%s/%s/api/dfa-api/%s?wsdl' - # A giant dictionary of DFA versions and the services they support. - _SERVICE_MAP = { - 'v1.19': ('ad', 'advertiser', 'advertisergroup', 'campaign', 'changelog', - 'contentcategory', 'creative', 'creativefield', 'creativegroup', - 'login', 'network', 'placement', 'site', 'size', 'spotlight', - 'strategy', 'subnetwork', 'user', 'userrole', 'report'), - 'v1.20': ('ad', 'advertiser', 'advertisergroup', 'campaign', 'changelog', - 'contentcategory', 'creative', 'creativefield', 'creativegroup', - 'login', 'network', 'placement', 'site', 'size', 'spotlight', - 'strategy', 'subnetwork', 'user', 'userrole', 'report'), - } - - @classmethod - def LoadFromStorage(cls, path=None): - """Creates an DfaClient with information stored in a yaml file. - - Args: - [optional] - path: The path string to the file containing cached DFA data. - - Returns: - A DfaClient initialized with the values cached in the file. - - Raises: - A GoogleAdsValueError if the given yaml file does not contain the - information necessary to instantiate a client object - either a - required key was missing or an OAuth 2.0 key was missing. - """ - if path is None: - path = os.path.join(os.path.expanduser('~'), 'googleads.yaml') - - return cls(**googleads.common.LoadFromStorage( - path, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES, - cls._OPTIONAL_INIT_VALUES)) - - def __init__(self, username, oauth2_client, application_name, - https_proxy=None, cache=None): - """Initializes a DfaClient. - - For more information on these arguments, see our SOAP headers guide: - https://developers.google.com/doubleclick-advertisers/docs/SOAP_headers - - Args: - username: A string representation of your DFA username. This is likely not - the same as your Google Account name. - oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize - your requests. - application_name: An arbitrary string which will be used to identify your - application - [optional] - https_proxy: A string identifying the proxy that all HTTPS requests - should be routed through. - cache: A subclass of suds.cache.Cache; defaults to None. - """ - self.username = username - self.oauth2_client = oauth2_client - self.application_name = application_name - self.https_proxy = https_proxy - self.cache = cache - self._header_handler = _DfaHeaderHandler(self) - - def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], - server='https://advertisersapi.doubleclick.com'): - """Creates a service client for the given service. - - Args: - service_name: A string identifying which DFA service to create a service - client for. - [optional] - version: A string identifying the DFA version to connect to. This defaults - to what is currently the latest version. This will be updated in - future releases to point to what is then the latest version. - server: A string identifying the webserver hosting the DFA API. - - Returns: - A suds.client.ServiceSelector which has the headers and proxy configured - for use. - - Raises: - A GoogleAdsValueError if the service or version provided do not exist. - """ - server = server[:-1] if server[-1] == '/' else server - try: - proxy_option = None - if self.https_proxy: - proxy_option = { - 'https': self.https_proxy - } - - client = suds.client.Client( - self._SOAP_SERVICE_FORMAT % (server, version, service_name), - proxy=proxy_option, cache=self.cache, timeout=3600) - except suds.transport.TransportError: - if version in self._SERVICE_MAP: - if service_name in self._SERVICE_MAP[version]: - raise - else: - raise googleads.errors.GoogleAdsValueError( - 'Unrecognized service for the DFA API. Service given: %s ' - 'Supported services: %s' - % (service_name, self._SERVICE_MAP[version])) - else: - raise googleads.errors.GoogleAdsValueError( - 'Unrecognized version of the DFA API. Version given: %s Supported ' - 'versions: %s' % (version, self._SERVICE_MAP.keys())) - - return googleads.common.SudsServiceProxy(client, self._header_handler) - - -class _DfaHeaderHandler(googleads.common.HeaderHandler): - """Handler which sets the headers for a DFA SOAP call.""" - - # The library signature for DFA, to be appended to all application_names. - _LIB_SIG = googleads.common.GenerateLibSig('DfaApi-Python') - - def __init__(self, dfa_client): - """Initializes a DfaHeaderHandler. - - Args: - dfa_client: The DfaClient whose data will be used to fill in the headers. - We retain a reference to this object so that the header handler picks - up changes to the client. - """ - self._dfa_client = dfa_client - - def SetHeaders(self, suds_client): - """Sets the SOAP and HTTP headers on the given suds client.""" - wsse_header = suds.wsse.Security() - wsse_header.tokens.append( - suds.wsse.UsernameToken(self._dfa_client.username)) - request_header = suds.sax.element.Element('RequestHeader') - request_header.append( - suds.sax.element.Element('applicationName').setText( - ''.join([self._dfa_client.application_name, self._LIB_SIG]))) - - suds_client.set_options( - wsse=wsse_header, soapheaders=request_header, - headers=self._dfa_client.oauth2_client.CreateHttpHeader()) diff --git a/googleads/oauth2.py b/googleads/oauth2.py index 7caaaee4..6bd6b11d 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -32,7 +32,6 @@ # The scopes used for authorizing with the APIs supported by this library. SCOPES = {'adwords': 'https://www.googleapis.com/auth/adwords', - 'dfa': 'https://www.googleapis.com/auth/dfatrafficking', 'dfp': 'https://www.googleapis.com/auth/dfp'} @@ -48,7 +47,7 @@ def GetAPIScope(api_name): Raises: GoogleAdsValueError: If the given api_name is invalid; accepted valus are - "adwords", "dfa", and "dfp". + "adwords" and "dfp". """ try: return SCOPES[api_name] diff --git a/setup.py b/setup.py index d24039c3..a8627d4f 100755 --- a/setup.py +++ b/setup.py @@ -113,7 +113,7 @@ def GetVersion(): long_description=long_description, packages=PACKAGES, platforms='any', - keywords='adwords adxbuyer dfp dfa google', + keywords='adwords adxbuyer dfp google', classifiers=CLASSIFIERS, install_requires=DEPENDENCIES, **extra_params) diff --git a/tests/dfa_test.py b/tests/dfa_test.py deleted file mode 100644 index 3a191253..00000000 --- a/tests/dfa_test.py +++ /dev/null @@ -1,149 +0,0 @@ -# Copyright 2013 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. - -"""Unit tests to cover the dfa module.""" - - -import unittest - - -import mock -import suds.transport - -import googleads.dfa -import googleads.common -import googleads.errors - - -class DfaHeaderHandlerTest(unittest.TestCase): - """Tests for the googleads.dfa._DfaHeaderHandler class.""" - - def setUp(self): - self.dfa_client = mock.Mock() - self.header_handler = googleads.dfa._DfaHeaderHandler(self.dfa_client) - - def testSetHeaders(self): - suds_client = mock.Mock() - request_header_element = mock.Mock() - app_name_element = mock.Mock() - app_name_element.setText.return_value = app_name_element - username = 'my username is name' - app_name = 'application name' - oauth_header = {'oauth', 'header'} - self.dfa_client.username = username - self.dfa_client.application_name = app_name - self.dfa_client.oauth2_client.CreateHttpHeader.return_value = ( - oauth_header) - element_mocks = {'RequestHeader': request_header_element, - 'applicationName': app_name_element} - - with mock.patch('suds.wsse') as mock_wsse: - with mock.patch('suds.sax') as mock_sax: - mock_sax.element.Element.side_effect = lambda x: element_mocks[x] - - self.header_handler.SetHeaders(suds_client) - - mock_wsse.Security.assert_called_once_with() - mock_wsse.UsernameToken.assert_called_once_with(username) - mock_wsse.Security.return_value.tokens.append.assert_called_once_with( - mock_wsse.UsernameToken.return_value) - - app_name_element.setText.assert_called_once_with( - ''.join([app_name, googleads.dfa._DfaHeaderHandler._LIB_SIG])) - request_header_element.append.assert_called_once_with(app_name_element) - - suds_client.set_options.assert_any_call( - wsse=mock_wsse.Security.return_value, - soapheaders=request_header_element, - headers=oauth_header) - - -class DfaClientTest(unittest.TestCase): - """Tests for the googleads.dfa.DfaClient class.""" - - def setUp(self): - self.username = 'dfa_user_1' - self.application_name = 'application name' - self.oauth2_client = 'unused' - self.https_proxy = 'myproxy.com:443' - self.cache = None - self.dfa_client = googleads.dfa.DfaClient( - self.username, self.oauth2_client, self.application_name, - self.https_proxy, self.cache) - - def testLoadFromStorage(self): - with mock.patch('googleads.common.LoadFromStorage') as mock_load: - mock_load.return_value = { - 'username': 'abcdEFghIjkLMOpqRs', - 'oauth2_client': True, - 'application_name': 'unit testing' - } - self.assertIsInstance(googleads.dfa.DfaClient.LoadFromStorage(), - googleads.dfa.DfaClient) - - def testGetService_success(self): - version = googleads.dfa.DfaClient._SERVICE_MAP.keys()[0] - service = googleads.dfa.DfaClient._SERVICE_MAP[version][0] - - # Use a custom server. Also test what happens if the server ends with a - # trailing slash - server = 'https://testing.test.com/' - https_proxy = {'https': self.https_proxy} - with mock.patch('suds.client.Client') as mock_client: - suds_service = self.dfa_client.GetService(service, version, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/%s/api/dfa-api/%s?wsdl' - % (version, service), proxy=https_proxy, cache=self.cache, - timeout=3600) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) - - # Use the default server and https_proxy. - self.dfa_client.https_proxy = None - with mock.patch('suds.client.Client') as mock_client: - suds_service = self.dfa_client.GetService(service, version) - - mock_client.assert_called_once_with( - 'https://advertisersapi.doubleclick.com/%s/api/dfa-api/%s?wsdl' - % (version, service), proxy=None, cache=self.cache, timeout=3600) - self.assertFalse(mock_client.return_value.set_options.called) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) - - def testGetService_badService(self): - version = googleads.dfa.DfaClient._SERVICE_MAP.keys()[0] - with mock.patch('suds.client.Client') as mock_client: - mock_client.side_effect = suds.transport.TransportError('', '') - self.assertRaises( - googleads.errors.GoogleAdsValueError, self.dfa_client.GetService, - 'GYIVyievfyiovslf', version) - - def testGetService_badVersion(self): - with mock.patch('suds.client.Client') as mock_client: - mock_client.side_effect = suds.transport.TransportError('', '') - self.assertRaises( - googleads.errors.GoogleAdsValueError, self.dfa_client.GetService, - 'campaign', '11111') - - def testGetService_transportError(self): - version = googleads.dfa.DfaClient._SERVICE_MAP.keys()[0] - service = googleads.dfa.DfaClient._SERVICE_MAP[version][0] - with mock.patch('suds.client.Client') as mock_client: - mock_client.side_effect = suds.transport.TransportError('', '') - self.assertRaises(suds.transport.TransportError, - self.dfa_client.GetService, service, version) - - -if __name__ == '__main__': - unittest.main() - diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index 80194aa4..cbb8bc79 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -38,10 +38,8 @@ class GetAPIScopeTest(unittest.TestCase): def setUp(self): self.api_name_adwords = 'adwords' - self.api_name_dfa = 'dfa' self.api_name_dfp = 'dfp' self.scope_adwords = 'https://www.googleapis.com/auth/adwords' - self.scope_dfa = 'https://www.googleapis.com/auth/dfatrafficking' self.scope_dfp = 'https://www.googleapis.com/auth/dfp' def testGetAPIScope_adwords(self): @@ -52,10 +50,6 @@ def testGetAPIScope_badKey(self): self.assertRaises(googleads.errors.GoogleAdsValueError, googleads.oauth2.GetAPIScope, 'fake_api_name') - def testGetAPIScope_dfa(self): - self.assertEquals(googleads.oauth2.GetAPIScope(self.api_name_dfa), - self.scope_dfa) - def testGetAPIScope_dfp(self): self.assertEquals(googleads.oauth2.GetAPIScope(self.api_name_dfp), self.scope_dfp) From 7ebec097569d2b179f322c6a93096a6659948d01 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 21 Oct 2015 10:17:16 -0400 Subject: [PATCH 018/180] Commiting latest changes. From 65223fc34a416b5c49b009ec3c6c8d21eedcd436 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Thu, 19 Nov 2015 14:05:30 -0500 Subject: [PATCH 019/180] add v201511 for DFP --- ChangeLog | 12 +- .../account_management/get_account_changes.py | 31 +- .../account_management/get_account_changes.py | 31 +- .../account_management/get_account_changes.py | 31 +- .../add_complete_campaigns_using_batch_job.py | 114 ++--- .../campaign_management/batch_job_util.py | 185 -------- .../dfp/v201411/contact_service/__init__.py | 15 - .../__init__.py | 15 - .../dfp/v201411/content_service/__init__.py | 15 - .../dfp/v201411/creative_service/__init__.py | 15 - .../v201411/creative_set_service/__init__.py | 15 - .../creative_template_service/__init__.py | 15 - .../v201411/custom_field_service/__init__.py | 15 - .../custom_targeting_service/__init__.py | 15 - .../v201411/exchange_rate_service/__init__.py | 15 - .../dfp/v201411/inventory_service/__init__.py | 15 - .../dfp/v201411/label_service/__init__.py | 15 - .../__init__.py | 15 - .../dfp/v201411/line_item_service/__init__.py | 15 - .../dfp/v201411/network_service/__init__.py | 15 - .../dfp/v201411/order_service/__init__.py | 15 - .../dfp/v201411/product_service/__init__.py | 15 - .../proposal_line_item_service/__init__.py | 15 - .../dfp/v201411/proposal_service/__init__.py | 15 - .../__init__.py | 15 - .../dfp/v201411/rate_card_service/__init__.py | 15 - .../dfp/v201411/report_service/__init__.py | 15 - .../suggested_ad_unit_service/__init__.py | 15 - examples/dfp/v201411/team_service/__init__.py | 15 - examples/dfp/v201411/user_service/__init__.py | 15 - .../user_team_association_service/__init__.py | 15 - .../workflow_request_service/__init__.py | 15 - .../get_delivery_forecast_for_line_items.py | 6 +- .../get_delivery_forecast_for_line_items.py | 6 +- .../get_delivery_forecast_for_line_items.py | 6 +- .../activity_group_service}/__init__.py | 0 .../create_activity_groups.py | 4 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service}/__init__.py | 0 .../activity_service/create_activities.py | 4 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../audience_segment_service}/__init__.py | 0 .../create_audience_segments.py | 10 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../base_rate_service}/__init__.py | 2 +- .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 5 +- .../get_base_rates_for_a_rate_card.py | 5 +- .../base_rate_service/update_base_rates.py | 5 +- .../company_service}/__init__.py | 2 +- .../company_service/create_companies.py | 4 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service}/__init__.py | 2 +- .../contact_service/create_contacts.py | 4 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../__init__.py | 2 +- ...create_content_metadata_key_hierarchies.py | 4 +- ...delete_content_metadata_key_hierarchies.py | 4 +- ...et_all_content_metadata_key_hierarchies.py | 4 +- ...update_content_metadata_key_hierarchies.py | 4 +- .../dfp/v201511/content_service/__init__.py | 15 + .../content_service/get_all_content.py | 4 +- .../get_content_by_category.py | 8 +- .../dfp/v201511/creative_service/__init__.py | 15 + .../create_creative_from_template.py | 6 +- .../creative_service/create_creatives.py | 6 +- .../create_custom_creative.py | 12 +- .../create_native_creative.py | 135 ++++++ .../creative_service/get_all_creatives.py | 6 +- .../get_creatives_by_statement.py | 6 +- .../creative_service/update_creatives.py | 4 +- .../v201511/creative_set_service/__init__.py | 15 + .../associate_creative_set_to_line_item.py | 4 +- .../create_creative_set.py | 4 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_by_statement.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 15 + .../get_all_creative_templates.py | 4 +- .../get_creative_templates_by_statement.py | 4 +- .../create_creative_wrappers.py | 4 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../v201511/custom_field_service/__init__.py | 15 + .../create_custom_field_options.py | 4 +- .../create_custom_fields.py | 4 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_all_line_item_custom_fields.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 15 + ...create_custom_targeting_keys_and_values.py | 4 +- .../delete_custom_targeting_keys.py | 4 +- .../delete_custom_targeting_values.py | 4 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- .../get_custom_targeting_keys_by_statement.py | 4 +- ...et_custom_targeting_values_by_statement.py | 4 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../v201511/exchange_rate_service/__init__.py | 15 + .../create_exchange_rates.py | 4 +- .../get_all_exchange_rates.py | 4 +- .../get_exchange_rates_by_currency_code.py | 4 +- .../update_exchange_rates.py | 4 +- .../get_availability_forecast.py} | 52 ++- ...et_availability_forecast_for_line_item.py} | 23 +- .../get_delivery_forecast_for_line_items.py | 52 +++ .../dfp/v201511/inventory_service/__init__.py | 15 + .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 4 +- .../get_ad_unit_hierarchy.py | 4 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../dfp/v201511/label_service/__init__.py | 15 + .../label_service/create_labels.py | 4 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/get_labels_by_statement.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 15 + .../create_licas.py | 4 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_by_statement.py | 4 +- .../update_licas.py | 4 +- .../dfp/v201511/line_item_service/__init__.py | 15 + .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 7 +- .../create_video_line_item.py | 41 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_by_statement.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../dfp/v201511/network_service/__init__.py | 15 + .../network_service/get_all_networks.py | 4 +- .../network_service/get_current_network.py | 4 +- .../network_service/make_test_network.py | 4 +- .../dfp/v201511/order_service/__init__.py | 15 + .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 4 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_by_statement.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../get_placements_by_statement.py | 4 +- .../placement_service/update_placements.py | 4 +- .../v201511/premium_rate_service/__init__.py | 15 + .../create_premium_rates.py | 4 +- .../get_all_premium_rates.py | 4 +- .../get_premium_rates_for_a_rate_card.py | 4 +- .../update_premium_rates.py | 2 +- .../dfp/v201511/product_service/__init__.py | 15 + .../product_service/get_all_products.py | 4 +- .../get_products_for_product_template.py | 4 +- .../product_service/update_products.py | 4 +- .../product_template_service/__init__.py | 15 + .../activate_product_templates.py | 2 +- .../create_product_templates.py | 32 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 6 +- .../proposal_line_item_service/__init__.py | 15 + .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 9 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../dfp/v201511/proposal_service/__init__.py | 15 + .../proposal_service/create_proposals.py | 6 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_proposals_by_statement.py | 4 +- .../submit_proposals_for_approval.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 15 + .../fetch_match_tables.py | 4 +- .../get_geo_targets.py | 6 +- .../get_line_items_named_like.py | 4 +- .../dfp/v201511/rate_card_service/__init__.py | 15 + .../rate_card_service/get_all_rate_cards.py | 4 +- .../get_rate_cards_priced_with_currency.py | 4 +- .../dfp/v201511/report_service/__init__.py | 15 + .../report_service/run_delivery_report.py | 18 +- .../report_service/run_inventory_report.py | 6 +- .../report_service/run_reach_report.py | 4 +- .../run_report_with_custom_fields.py | 6 +- .../report_service/run_sales_report.py | 4 +- .../suggested_ad_unit_service/__init__.py | 15 + .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- .../get_suggested_ad_units_by_statement.py | 4 +- examples/dfp/v201511/team_service/__init__.py | 15 + .../team_service/create_teams.py | 4 +- .../team_service/get_all_teams.py | 4 +- .../team_service/get_teams_by_statement.py | 4 +- .../team_service/update_teams.py | 4 +- examples/dfp/v201511/user_service/__init__.py | 15 + .../user_service/create_users.py | 4 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 4 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 4 +- .../user_service/get_users_by_statement.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 15 + .../create_user_team_associations.py | 4 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- .../workflow_request_service/__init__.py | 15 + .../approve_workflow_approval_requests.py | 7 +- ...workflow_approval_requests_by_statement.py | 4 +- ...xternal_condition_requests_by_statement.py | 4 +- ...er_workflow_external_condition_requests.py | 4 +- googleads/adwords.py | 186 +++++++- googleads/common.py | 6 +- googleads/dfp.py | 46 +- tests/adwords_test.py | 411 +++++++++++++++++- 238 files changed, 1751 insertions(+), 1145 deletions(-) delete mode 100755 examples/adwords/v201509/campaign_management/batch_job_util.py delete mode 100755 examples/dfp/v201411/contact_service/__init__.py delete mode 100755 examples/dfp/v201411/content_metadata_key_hierarchy_service/__init__.py delete mode 100755 examples/dfp/v201411/content_service/__init__.py delete mode 100755 examples/dfp/v201411/creative_service/__init__.py delete mode 100755 examples/dfp/v201411/creative_set_service/__init__.py delete mode 100755 examples/dfp/v201411/creative_template_service/__init__.py delete mode 100755 examples/dfp/v201411/custom_field_service/__init__.py delete mode 100755 examples/dfp/v201411/custom_targeting_service/__init__.py delete mode 100755 examples/dfp/v201411/exchange_rate_service/__init__.py delete mode 100755 examples/dfp/v201411/inventory_service/__init__.py delete mode 100755 examples/dfp/v201411/label_service/__init__.py delete mode 100755 examples/dfp/v201411/line_item_creative_association_service/__init__.py delete mode 100755 examples/dfp/v201411/line_item_service/__init__.py delete mode 100755 examples/dfp/v201411/network_service/__init__.py delete mode 100755 examples/dfp/v201411/order_service/__init__.py delete mode 100755 examples/dfp/v201411/product_service/__init__.py delete mode 100755 examples/dfp/v201411/proposal_line_item_service/__init__.py delete mode 100755 examples/dfp/v201411/proposal_service/__init__.py delete mode 100755 examples/dfp/v201411/publisher_query_language_service/__init__.py delete mode 100755 examples/dfp/v201411/rate_card_service/__init__.py delete mode 100755 examples/dfp/v201411/report_service/__init__.py delete mode 100755 examples/dfp/v201411/suggested_ad_unit_service/__init__.py delete mode 100755 examples/dfp/v201411/team_service/__init__.py delete mode 100755 examples/dfp/v201411/user_service/__init__.py delete mode 100755 examples/dfp/v201411/user_team_association_service/__init__.py delete mode 100755 examples/dfp/v201411/workflow_request_service/__init__.py rename examples/dfp/{v201411/base_rate_service => v201511/activity_group_service}/__init__.py (100%) rename examples/dfp/{v201411 => v201511}/activity_group_service/create_activity_groups.py (95%) rename examples/dfp/{v201411 => v201511}/activity_group_service/get_active_activity_groups.py (94%) rename examples/dfp/{v201411 => v201511}/activity_group_service/get_all_activity_groups.py (94%) rename examples/dfp/{v201411 => v201511}/activity_group_service/update_activity_groups.py (95%) rename examples/dfp/{v201411/premium_rate_service => v201511/activity_service}/__init__.py (100%) rename examples/dfp/{v201411 => v201511}/activity_service/create_activities.py (97%) rename examples/dfp/{v201411 => v201511}/activity_service/get_active_activities.py (97%) rename examples/dfp/{v201411 => v201511}/activity_service/get_all_activities.py (96%) rename examples/dfp/{v201411 => v201511}/activity_service/update_activities.py (97%) rename examples/dfp/{v201411/product_template_service => v201511/audience_segment_service}/__init__.py (100%) rename examples/dfp/{v201411 => v201511}/audience_segment_service/create_audience_segments.py (93%) rename examples/dfp/{v201411 => v201511}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/dfp/{v201411 => v201511}/audience_segment_service/get_first_party_audience_segments.py (95%) rename examples/dfp/{v201411 => v201511}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/dfp/{v201411 => v201511}/audience_segment_service/update_audience_segments.py (96%) rename examples/dfp/{v201411/company_service => v201511/base_rate_service}/__init__.py (91%) rename examples/dfp/{v201411 => v201511}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201411 => v201511}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201411 => v201511}/base_rate_service/get_all_base_rates.py (94%) rename examples/dfp/{v201411 => v201511}/base_rate_service/get_base_rates_for_a_rate_card.py (95%) rename examples/dfp/{v201411 => v201511}/base_rate_service/update_base_rates.py (95%) rename examples/dfp/{v201411/activity_group_service => v201511/company_service}/__init__.py (91%) rename examples/dfp/{v201411 => v201511}/company_service/create_companies.py (96%) rename examples/dfp/{v201411 => v201511}/company_service/get_advertisers.py (97%) rename examples/dfp/{v201411 => v201511}/company_service/get_all_companies.py (96%) rename examples/dfp/{v201411 => v201511}/company_service/update_companies.py (97%) rename examples/dfp/{v201411/activity_service => v201511/contact_service}/__init__.py (91%) rename examples/dfp/{v201411 => v201511}/contact_service/create_contacts.py (97%) rename examples/dfp/{v201411 => v201511}/contact_service/get_all_contacts.py (96%) rename examples/dfp/{v201411 => v201511}/contact_service/get_uninvited_contacts.py (97%) rename examples/dfp/{v201411 => v201511}/contact_service/update_contacts.py (97%) rename examples/dfp/{v201411/audience_segment_service => v201511/content_metadata_key_hierarchy_service}/__init__.py (91%) rename examples/dfp/{v201411 => v201511}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (95%) rename examples/dfp/{v201411 => v201511}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201411 => v201511}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (95%) rename examples/dfp/{v201411 => v201511}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (96%) create mode 100755 examples/dfp/v201511/content_service/__init__.py rename examples/dfp/{v201411 => v201511}/content_service/get_all_content.py (96%) rename examples/dfp/{v201411 => v201511}/content_service/get_content_by_category.py (96%) create mode 100755 examples/dfp/v201511/creative_service/__init__.py rename examples/dfp/{v201411 => v201511}/creative_service/create_creative_from_template.py (96%) rename examples/dfp/{v201411 => v201511}/creative_service/create_creatives.py (95%) rename examples/dfp/{v201411 => v201511}/creative_service/create_custom_creative.py (90%) create mode 100755 examples/dfp/v201511/creative_service/create_native_creative.py rename examples/dfp/{v201411 => v201511}/creative_service/get_all_creatives.py (93%) rename examples/dfp/{v201411 => v201511}/creative_service/get_creatives_by_statement.py (94%) rename examples/dfp/{v201411 => v201511}/creative_service/update_creatives.py (97%) create mode 100755 examples/dfp/v201511/creative_set_service/__init__.py rename examples/dfp/{v201411 => v201511}/creative_set_service/associate_creative_set_to_line_item.py (94%) rename examples/dfp/{v201411 => v201511}/creative_set_service/create_creative_set.py (94%) rename examples/dfp/{v201411 => v201511}/creative_set_service/get_all_creative_sets.py (94%) rename examples/dfp/{v201411 => v201511}/creative_set_service/get_creative_sets_by_statement.py (95%) rename examples/dfp/{v201411 => v201511}/creative_set_service/update_creative_set.py (95%) create mode 100755 examples/dfp/v201511/creative_template_service/__init__.py rename examples/dfp/{v201411 => v201511}/creative_template_service/get_all_creative_templates.py (94%) rename examples/dfp/{v201411 => v201511}/creative_template_service/get_creative_templates_by_statement.py (95%) rename examples/dfp/{v201411 => v201511}/creative_wrapper_service/create_creative_wrappers.py (94%) rename examples/dfp/{v201411 => v201511}/creative_wrapper_service/deactivate_creative_wrapper.py (96%) rename examples/dfp/{v201411 => v201511}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/dfp/{v201411 => v201511}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/dfp/{v201411 => v201511}/creative_wrapper_service/update_creative_wrappers.py (95%) create mode 100755 examples/dfp/v201511/custom_field_service/__init__.py rename examples/dfp/{v201411 => v201511}/custom_field_service/create_custom_field_options.py (95%) rename examples/dfp/{v201411 => v201511}/custom_field_service/create_custom_fields.py (95%) rename examples/dfp/{v201411 => v201511}/custom_field_service/deactivate_all_line_item_custom_fields.py (96%) rename examples/dfp/{v201411 => v201511}/custom_field_service/get_all_custom_fields.py (94%) rename examples/dfp/{v201411 => v201511}/custom_field_service/get_all_line_item_custom_fields.py (95%) rename examples/dfp/{v201411 => v201511}/custom_field_service/set_line_item_custom_field_value.py (95%) rename examples/dfp/{v201411 => v201511}/custom_field_service/update_custom_fields.py (96%) create mode 100755 examples/dfp/v201511/custom_targeting_service/__init__.py rename examples/dfp/{v201411 => v201511}/custom_targeting_service/create_custom_targeting_keys_and_values.py (97%) rename examples/dfp/{v201411 => v201511}/custom_targeting_service/delete_custom_targeting_keys.py (96%) rename examples/dfp/{v201411 => v201511}/custom_targeting_service/delete_custom_targeting_values.py (96%) rename examples/dfp/{v201411 => v201511}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (96%) rename examples/dfp/{v201411 => v201511}/custom_targeting_service/get_custom_targeting_keys_by_statement.py (94%) rename examples/dfp/{v201411 => v201511}/custom_targeting_service/get_custom_targeting_values_by_statement.py (95%) rename examples/dfp/{v201411 => v201511}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/dfp/{v201411 => v201511}/custom_targeting_service/update_custom_targeting_values.py (96%) create mode 100755 examples/dfp/v201511/exchange_rate_service/__init__.py rename examples/dfp/{v201411 => v201511}/exchange_rate_service/create_exchange_rates.py (94%) rename examples/dfp/{v201411 => v201511}/exchange_rate_service/get_all_exchange_rates.py (94%) rename examples/dfp/{v201411 => v201511}/exchange_rate_service/get_exchange_rates_by_currency_code.py (95%) rename examples/dfp/{v201411 => v201511}/exchange_rate_service/update_exchange_rates.py (95%) rename examples/dfp/{v201411/forecast_service/get_forecast.py => v201511/forecast_service/get_availability_forecast.py} (63%) rename examples/dfp/{v201411/forecast_service/get_forecast_by_id.py => v201511/forecast_service/get_availability_forecast_for_line_item.py} (76%) create mode 100755 examples/dfp/v201511/forecast_service/get_delivery_forecast_for_line_items.py create mode 100755 examples/dfp/v201511/inventory_service/__init__.py rename examples/dfp/{v201411 => v201511}/inventory_service/archive_ad_units.py (97%) rename examples/dfp/{v201411 => v201511}/inventory_service/create_ad_units.py (96%) rename examples/dfp/{v201411 => v201511}/inventory_service/get_ad_unit_hierarchy.py (98%) rename examples/dfp/{v201411 => v201511}/inventory_service/get_all_ad_unit_sizes.py (96%) rename examples/dfp/{v201411 => v201511}/inventory_service/get_all_ad_units.py (96%) rename examples/dfp/{v201411 => v201511}/inventory_service/get_top_level_ad_units.py (96%) rename examples/dfp/{v201411 => v201511}/inventory_service/update_ad_units.py (97%) create mode 100755 examples/dfp/v201511/label_service/__init__.py rename examples/dfp/{v201411 => v201511}/label_service/create_labels.py (96%) rename examples/dfp/{v201411 => v201511}/label_service/deactivate_labels.py (97%) rename examples/dfp/{v201411 => v201511}/label_service/get_all_labels.py (96%) rename examples/dfp/{v201411 => v201511}/label_service/get_labels_by_statement.py (96%) rename examples/dfp/{v201411 => v201511}/label_service/update_labels.py (97%) create mode 100755 examples/dfp/v201511/line_item_creative_association_service/__init__.py rename examples/dfp/{v201411 => v201511}/line_item_creative_association_service/create_licas.py (93%) rename examples/dfp/{v201411 => v201511}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/dfp/{v201411 => v201511}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/dfp/{v201411 => v201511}/line_item_creative_association_service/get_licas_by_statement.py (94%) rename examples/dfp/{v201411 => v201511}/line_item_creative_association_service/update_licas.py (94%) create mode 100755 examples/dfp/v201511/line_item_service/__init__.py rename examples/dfp/{v201411 => v201511}/line_item_service/activate_line_items.py (97%) rename examples/dfp/{v201411 => v201511}/line_item_service/create_line_items.py (97%) rename examples/dfp/{v201411 => v201511}/line_item_service/create_video_line_item.py (80%) rename examples/dfp/{v201411 => v201511}/line_item_service/get_all_line_items.py (96%) rename examples/dfp/{v201411 => v201511}/line_item_service/get_line_items_by_statement.py (97%) rename examples/dfp/{v201411 => v201511}/line_item_service/get_recently_updated_line_items.py (97%) rename examples/dfp/{v201411 => v201511}/line_item_service/target_custom_criteria.py (98%) rename examples/dfp/{v201411 => v201511}/line_item_service/update_line_items.py (97%) create mode 100755 examples/dfp/v201511/network_service/__init__.py rename examples/dfp/{v201411 => v201511}/network_service/get_all_networks.py (95%) rename examples/dfp/{v201411 => v201511}/network_service/get_current_network.py (95%) rename examples/dfp/{v201411 => v201511}/network_service/make_test_network.py (96%) create mode 100755 examples/dfp/v201511/order_service/__init__.py rename examples/dfp/{v201411 => v201511}/order_service/approve_orders.py (97%) rename examples/dfp/{v201411 => v201511}/order_service/create_orders.py (96%) rename examples/dfp/{v201411 => v201511}/order_service/get_all_orders.py (96%) rename examples/dfp/{v201411 => v201511}/order_service/get_orders_by_statement.py (96%) rename examples/dfp/{v201411 => v201511}/order_service/update_orders.py (97%) rename examples/dfp/{v201411 => v201511}/placement_service/create_placements.py (97%) rename examples/dfp/{v201411 => v201511}/placement_service/deactivate_placements.py (96%) rename examples/dfp/{v201411 => v201511}/placement_service/get_all_placements.py (96%) rename examples/dfp/{v201411 => v201511}/placement_service/get_placements_by_statement.py (96%) rename examples/dfp/{v201411 => v201511}/placement_service/update_placements.py (97%) create mode 100755 examples/dfp/v201511/premium_rate_service/__init__.py rename examples/dfp/{v201411 => v201511}/premium_rate_service/create_premium_rates.py (95%) rename examples/dfp/{v201411 => v201511}/premium_rate_service/get_all_premium_rates.py (92%) rename examples/dfp/{v201411 => v201511}/premium_rate_service/get_premium_rates_for_a_rate_card.py (93%) rename examples/dfp/{v201411 => v201511}/premium_rate_service/update_premium_rates.py (97%) create mode 100755 examples/dfp/v201511/product_service/__init__.py rename examples/dfp/{v201411 => v201511}/product_service/get_all_products.py (96%) rename examples/dfp/{v201411 => v201511}/product_service/get_products_for_product_template.py (96%) rename examples/dfp/{v201411 => v201511}/product_service/update_products.py (97%) create mode 100755 examples/dfp/v201511/product_template_service/__init__.py rename examples/dfp/{v201411 => v201511}/product_template_service/activate_product_templates.py (97%) rename examples/dfp/{v201411 => v201511}/product_template_service/create_product_templates.py (82%) rename examples/dfp/{v201411 => v201511}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201411 => v201511}/product_template_service/get_sponsorship_product_templates.py (97%) rename examples/dfp/{v201411 => v201511}/product_template_service/update_product_templates.py (94%) create mode 100755 examples/dfp/v201511/proposal_line_item_service/__init__.py rename examples/dfp/{v201411 => v201511}/proposal_line_item_service/archive_proposal_line_items.py (96%) rename examples/dfp/{v201411 => v201511}/proposal_line_item_service/create_proposal_line_items.py (95%) rename examples/dfp/{v201411 => v201511}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/dfp/{v201411 => v201511}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (96%) rename examples/dfp/{v201411 => v201511}/proposal_line_item_service/update_proposal_line_items.py (95%) create mode 100755 examples/dfp/v201511/proposal_service/__init__.py rename examples/dfp/{v201411 => v201511}/proposal_service/create_proposals.py (97%) rename examples/dfp/{v201411 => v201511}/proposal_service/get_all_proposals.py (96%) rename examples/dfp/{v201411 => v201511}/proposal_service/get_proposals_by_statement.py (96%) rename examples/dfp/{v201411 => v201511}/proposal_service/submit_proposals_for_approval.py (97%) rename examples/dfp/{v201411 => v201511}/proposal_service/update_proposals.py (97%) create mode 100755 examples/dfp/v201511/publisher_query_language_service/__init__.py rename examples/dfp/{v201411 => v201511}/publisher_query_language_service/fetch_match_tables.py (93%) rename examples/dfp/{v201411 => v201511}/publisher_query_language_service/get_geo_targets.py (92%) rename examples/dfp/{v201411 => v201511}/publisher_query_language_service/get_line_items_named_like.py (93%) create mode 100755 examples/dfp/v201511/rate_card_service/__init__.py rename examples/dfp/{v201411 => v201511}/rate_card_service/get_all_rate_cards.py (96%) rename examples/dfp/{v201411 => v201511}/rate_card_service/get_rate_cards_priced_with_currency.py (96%) create mode 100755 examples/dfp/v201511/report_service/__init__.py rename examples/dfp/{v201411 => v201511}/report_service/run_delivery_report.py (79%) rename examples/dfp/{v201411 => v201511}/report_service/run_inventory_report.py (95%) rename examples/dfp/{v201411 => v201511}/report_service/run_reach_report.py (94%) rename examples/dfp/{v201411 => v201511}/report_service/run_report_with_custom_fields.py (96%) rename examples/dfp/{v201411 => v201511}/report_service/run_sales_report.py (94%) create mode 100755 examples/dfp/v201511/suggested_ad_unit_service/__init__.py rename examples/dfp/{v201411 => v201511}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (96%) rename examples/dfp/{v201411 => v201511}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/dfp/{v201411 => v201511}/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py (94%) create mode 100755 examples/dfp/v201511/team_service/__init__.py rename examples/dfp/{v201411 => v201511}/team_service/create_teams.py (93%) rename examples/dfp/{v201411 => v201511}/team_service/get_all_teams.py (93%) rename examples/dfp/{v201411 => v201511}/team_service/get_teams_by_statement.py (94%) rename examples/dfp/{v201411 => v201511}/team_service/update_teams.py (95%) create mode 100755 examples/dfp/v201511/user_service/__init__.py rename examples/dfp/{v201411 => v201511}/user_service/create_users.py (93%) rename examples/dfp/{v201411 => v201511}/user_service/deactivate_users.py (95%) rename examples/dfp/{v201411 => v201511}/user_service/get_all_roles.py (91%) rename examples/dfp/{v201411 => v201511}/user_service/get_all_users.py (92%) rename examples/dfp/{v201411 => v201511}/user_service/get_current_user.py (90%) rename examples/dfp/{v201411 => v201511}/user_service/get_users_by_statement.py (93%) rename examples/dfp/{v201411 => v201511}/user_service/update_users.py (93%) create mode 100755 examples/dfp/v201511/user_team_association_service/__init__.py rename examples/dfp/{v201411 => v201511}/user_team_association_service/create_user_team_associations.py (95%) rename examples/dfp/{v201411 => v201511}/user_team_association_service/delete_user_team_associations.py (96%) rename examples/dfp/{v201411 => v201511}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/dfp/{v201411 => v201511}/user_team_association_service/get_user_team_associations_for_user.py (95%) rename examples/dfp/{v201411 => v201511}/user_team_association_service/update_user_team_associations.py (96%) create mode 100755 examples/dfp/v201511/workflow_request_service/__init__.py rename examples/dfp/{v201411 => v201511}/workflow_request_service/approve_workflow_approval_requests.py (92%) rename examples/dfp/{v201411 => v201511}/workflow_request_service/get_workflow_approval_requests_by_statement.py (94%) rename examples/dfp/{v201411 => v201511}/workflow_request_service/get_workflow_external_condition_requests_by_statement.py (94%) rename examples/dfp/{v201411 => v201511}/workflow_request_service/trigger_workflow_external_condition_requests.py (96%) diff --git a/ChangeLog b/ChangeLog index 50dce949..61f12d9b 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,4 +1,14 @@ -3.8.1 - 10/19/13 +3.10.0 - 11/17/2015 +* Removed support for DFP v201405 and v201408. +* Removed examples for v201411. +* Added support for DFP v201511. + +3.9.0 - 10/23/2015 +* The AdWords BatchJobHelper has been updated and added to the core library. +* Updates to add_complete_campaigns_using_batch_job.py example. +* Fixed issue #85. + +3.8.1 - 10/19/2015 * Added BatchJobService example for AdWords v201509. * Removed GeoLocationService from AdWords v201509 because it isn't available in this version. diff --git a/examples/adwords/v201502/account_management/get_account_changes.py b/examples/adwords/v201502/account_management/get_account_changes.py index b23a5ca1..3709b0bb 100755 --- a/examples/adwords/v201502/account_management/get_account_changes.py +++ b/examples/adwords/v201502/account_management/get_account_changes.py @@ -70,23 +70,30 @@ def main(client): % (data['campaignId'], data['campaignChangeStatus'])) if (data['campaignChangeStatus'] != 'NEW' and data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - print ' Added ad extensions: %s' % data.get('addedAdExtensions') - print ' Removed ad extensions: %s' % data.get('deletedAdExtensions') - print (' Added campaign criteria: %s' - % data.get('addedCampaignCriteria')) - print (' Removed campaign criteria: %s' - % data.get('deletedCampaignCriteria')) - if data.get('changedAdGroups'): + if 'addedAdExtensions' in data: + print ' Added ad extensions: %s' % data['addedAdExtensions'] + if 'removedAdExtensions' in data: + print ' Removed ad extensions: %s' % data['removedAdExtensions'] + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: for ad_group_data in data['changedAdGroups']: print (' Ad group with id \'%s\' has change status \'%s\'.' % (ad_group_data['adGroupId'], ad_group_data['adGroupChangeStatus'])) if ad_group_data['adGroupChangeStatus'] != 'NEW': - print ' Changed ads: %s' % ad_group_data['changedAds'] - print (' Changed criteria: %s' - % ad_group_data['changedCriteria']) - print (' Removed criteria: %s' - % ad_group_data['deletedCriteria']) + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) else: print 'No changes were found.' diff --git a/examples/adwords/v201506/account_management/get_account_changes.py b/examples/adwords/v201506/account_management/get_account_changes.py index 279fa0b4..a1e4cb4b 100755 --- a/examples/adwords/v201506/account_management/get_account_changes.py +++ b/examples/adwords/v201506/account_management/get_account_changes.py @@ -70,23 +70,30 @@ def main(client): % (data['campaignId'], data['campaignChangeStatus'])) if (data['campaignChangeStatus'] != 'NEW' and data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - print ' Added ad extensions: %s' % data.get('addedAdExtensions') - print ' Removed ad extensions: %s' % data.get('deletedAdExtensions') - print (' Added campaign criteria: %s' - % data.get('addedCampaignCriteria')) - print (' Removed campaign criteria: %s' - % data.get('deletedCampaignCriteria')) - if data.get('changedAdGroups'): + if 'addedAdExtensions' in data: + print ' Added ad extensions: %s' % data['addedAdExtensions'] + if 'removedAdExtensions' in data: + print ' Removed ad extensions: %s' % data['removedAdExtensions'] + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: for ad_group_data in data['changedAdGroups']: print (' Ad group with id \'%s\' has change status \'%s\'.' % (ad_group_data['adGroupId'], ad_group_data['adGroupChangeStatus'])) if ad_group_data['adGroupChangeStatus'] != 'NEW': - print ' Changed ads: %s' % ad_group_data['changedAds'] - print (' Changed criteria: %s' - % ad_group_data['changedCriteria']) - print (' Removed criteria: %s' - % ad_group_data['deletedCriteria']) + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) else: print 'No changes were found.' diff --git a/examples/adwords/v201509/account_management/get_account_changes.py b/examples/adwords/v201509/account_management/get_account_changes.py index 8b0b3107..dd0f1005 100755 --- a/examples/adwords/v201509/account_management/get_account_changes.py +++ b/examples/adwords/v201509/account_management/get_account_changes.py @@ -70,23 +70,30 @@ def main(client): % (data['campaignId'], data['campaignChangeStatus'])) if (data['campaignChangeStatus'] != 'NEW' and data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - print ' Added ad extensions: %s' % data.get('addedAdExtensions') - print ' Removed ad extensions: %s' % data.get('deletedAdExtensions') - print (' Added campaign criteria: %s' - % data.get('addedCampaignCriteria')) - print (' Removed campaign criteria: %s' - % data.get('deletedCampaignCriteria')) - if data.get('changedAdGroups'): + if 'addedAdExtensions' in data: + print ' Added ad extensions: %s' % data['addedAdExtensions'] + if 'removedAdExtensions' in data: + print ' Removed ad extensions: %s' % data['removedAdExtensions'] + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: for ad_group_data in data['changedAdGroups']: print (' Ad group with id \'%s\' has change status \'%s\'.' % (ad_group_data['adGroupId'], ad_group_data['adGroupChangeStatus'])) if ad_group_data['adGroupChangeStatus'] != 'NEW': - print ' Changed ads: %s' % ad_group_data['changedAds'] - print (' Changed criteria: %s' - % ad_group_data['changedCriteria']) - print (' Removed criteria: %s' - % ad_group_data['deletedCriteria']) + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) else: print 'No changes were found.' diff --git a/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py index 915c777e..9af6977b 100755 --- a/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py @@ -29,12 +29,10 @@ import uuid -from batch_job_util import BatchJobHelper -from batch_job_util import BatchJobServiceIdGenerator from googleads import adwords -# Set logging configuration +# Set logging configuration. logging.basicConfig(level=logging.INFO) logging.getLogger('suds.transport').setLevel(logging.DEBUG) @@ -47,22 +45,36 @@ def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper - batch_job_helper = BatchJobHelper(client) + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper() + # Create a BatchJob. batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. upload_url = batch_job['uploadUrl']['url'] batch_job_id = batch_job['id'] - logging.info('Created BatchJob with ID "%d", status "%s", and upload URL ' '"%s"', batch_job['id'], batch_job['status'], upload_url) - operations = BuildUploadUrlOperations(batch_job_helper, number_of_campaigns, - number_of_adgroups, number_of_keywords) + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + # Upload operations. batch_job_helper.UploadBatchJobOperations( - upload_url, *operations) + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + # Download and display results. download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) response = urllib2.urlopen(download_url) logging.info('Downloaded following response:\n%s', response.read()) @@ -79,7 +91,7 @@ def AddBatchJob(client): """ # Initialize appropriate service. batch_job_service = client.GetService('BatchJobService', version='v201509') - # Create a BatchJob + # Create a BatchJob. batch_job_operations = [{ 'operand': {}, 'operator': 'ADD' @@ -160,7 +172,7 @@ def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): return criterion_operations -def BuildAdGroupOperations(batch_id_generator, +def BuildAdGroupOperations(batch_job_helper, campaign_operations, number_of_adgroups=1): """Builds the operations adding desired number of AdGroups to given Campaigns. @@ -169,7 +181,7 @@ def BuildAdGroupOperations(batch_id_generator, BatchJobService. Args: - batch_id_generator: a BatchJobServiceIdGenerator instance. + batch_job_helper: a BatchJobHelper instance. campaign_operations: a list containing the operations that will add Campaigns. number_of_adgroups: an int defining the number of AdGroups to be created per @@ -189,7 +201,7 @@ def BuildAdGroupOperations(batch_id_generator, 'xsi_type': 'AdGroupOperation', 'operand': { 'campaignId': campaign_operation['operand']['id'], - 'id': batch_id_generator.GetId(), + 'id': batch_job_helper.GetId(), 'name': 'Batch Ad Group #%s' % uuid.uuid4(), 'biddingStrategyConfiguration': { 'bids': [ @@ -210,7 +222,7 @@ def BuildAdGroupOperations(batch_id_generator, return adgroup_operations -def BuildBudgetOperations(batch_id_generator): +def BuildBudgetOperations(batch_job_helper): """Builds the operations needed to create a new Budget. Note: When the Budget is created, it will have a different Id than the one @@ -218,7 +230,7 @@ def BuildBudgetOperations(batch_id_generator): BatchJobService. Args: - batch_id_generator: a BatchJobServiceIdGenerator instance. + batch_job_helper: a BatchJobHelper instance. Returns: a list containing the operation that will create a new Budget. @@ -234,7 +246,7 @@ def BuildBudgetOperations(batch_id_generator): 'name': 'Batch budget #%s' % uuid.uuid4(), # This is a temporary Id used by the BatchJobService to identify the # Budget for operations that require a budgetId. - 'budgetId': batch_id_generator.GetId(), + 'budgetId': batch_job_helper.GetId(), 'amount': { 'microAmount': '50000000' }, @@ -282,7 +294,7 @@ def BuildCampaignCriterionOperations(campaign_operations): return criterion_operations -def BuildCampaignOperations(batch_id_generator, +def BuildCampaignOperations(batch_job_helper, budget_operations, number_of_campaigns=1): """Builds the operations needed to create a new Campaign. @@ -291,7 +303,7 @@ def BuildCampaignOperations(batch_id_generator, BatchJobService. Args: - batch_id_generator: a BatchJobServiceIdGenerator instance. + batch_job_helper: a BatchJobHelper instance. budget_operations: a list containing the operation that will add the budget used by these Campaigns. number_of_campaigns: an int number defining the number of campaigns to be @@ -316,7 +328,7 @@ def BuildCampaignOperations(batch_id_generator, 'status': 'PAUSED', # This is a temporary Id used by the BatchJobService to identify # the Campaigns for operations that require a campaignId. - 'id': batch_id_generator.GetId(), + 'id': batch_job_helper.GetId(), 'advertisingChannelType': 'SEARCH', # Note that only the budgetId is required 'budget': { @@ -333,70 +345,6 @@ def BuildCampaignOperations(batch_id_generator, return campaign_operations -def BuildUploadUrlOperations(batch_job_helper, number_of_campaigns, - number_of_adgroups, number_of_keywords): - """Builds a list of operations that will be uploaded to the BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance used to construct operations. - number_of_campaigns: an int defining the number of Campaigns to be created. - number_of_adgroups: an int defining the number of AdGroups to be created. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - A tuple of str, where each is a set of operations for distinct services. - """ - # Initialize BatchJobServiceIdGenerator. - batch_id_generator = BatchJobServiceIdGenerator() - - # Build BudgetOperations and retrieve in XML form. - budget_operations = BuildBudgetOperations(batch_id_generator) - budget_request_xml = batch_job_helper.GenerateRawRequestXML( - budget_operations, 'BudgetService') - budget_operations_xml = batch_job_helper.ExtractOperations( - budget_request_xml) - # Build CampaignOperations and retrieve in XML form. - campaign_operations = BuildCampaignOperations( - batch_id_generator, budget_operations, number_of_campaigns) - campaign_request_xml = batch_job_helper.GenerateRawRequestXML( - campaign_operations, 'CampaignService') - campaign_operations_xml = batch_job_helper.ExtractOperations( - campaign_request_xml) - # Build CampaignCriterionOperations and retrieve in XML form. - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - campaign_criterion_request_xml = batch_job_helper.GenerateRawRequestXML( - campaign_criterion_operations, 'CampaignCriterionService') - campaign_criterion_operations_xml = ( - batch_job_helper.ExtractOperations( - campaign_criterion_request_xml)) - # Build AdGroupOperations and retrieve in XML form. - adgroup_operations = BuildAdGroupOperations( - batch_id_generator, campaign_operations, number_of_adgroups) - adgroup_request_xml = batch_job_helper.GenerateRawRequestXML( - adgroup_operations, 'AdGroupService') - adgroup_operations_xml = batch_job_helper.ExtractOperations( - adgroup_request_xml) - # Build AdGroupCriterionOperations and retrieve in XML form. - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_criterion_request_xml = batch_job_helper.GenerateRawRequestXML( - adgroup_criterion_operations, 'AdGroupCriterionService') - adgroup_criterion_operations_xml = ( - batch_job_helper.ExtractOperations( - adgroup_criterion_request_xml)) - # Build AdGroupAdOperations and retrieve in XML form. - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - adgroup_ad_request_xml = batch_job_helper.GenerateRawRequestXML( - adgroup_ad_operations, 'AdGroupAdService') - adgroup_ad_operations_xml = batch_job_helper.ExtractOperations( - adgroup_ad_request_xml) - - return (budget_operations_xml, campaign_operations_xml, - campaign_criterion_operations_xml, adgroup_operations_xml, - adgroup_criterion_operations_xml, adgroup_ad_operations_xml) - - def GetBatchJob(client, batch_job_id): """Retrieves the BatchJob with the given id. diff --git a/examples/adwords/v201509/campaign_management/batch_job_util.py b/examples/adwords/v201509/campaign_management/batch_job_util.py deleted file mode 100755 index f075d725..00000000 --- a/examples/adwords/v201509/campaign_management/batch_job_util.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 for use with BatchJobService. - -Api: AdWordsOnly -""" - - -import re -import urllib2 -from xml.etree import ElementTree - - -class BatchJobHelper(object): - """A utility that simplifies working with the BatchJobService.""" - - _VERSION = 'v201509' - _ADWORDS_ENDPOINT = ('https://adwords.google.com/api/adwords/cm/%s' % - _VERSION) - _ADWORDS_NAMESPACE = ('{%s}' % _ADWORDS_ENDPOINT) - # Used to remove namespace from xsi:type Element attributes. - _ATTRIB_NAMESPACE_SUB = re.compile('ns[0-1]:') - # Used to remove the AdWords namespace from Element tags. - _TAG_NAMESPACE_SUB = re.compile(_ADWORDS_NAMESPACE) - - def __init__(self, client): - """Initializes the BatchJobHelper. - - Args: - client: an initialized AdWordsClient. - """ - self.client = client - - def UploadBatchJobOperations(self, upload_url, *operations): - """Uploads operations to the given uploadUrl. - - Args: - upload_url: The url the given operations will be uploaded to. - *operations: The operations being uploaded, provided as strings containing - only the operations tags and their contents. - """ - request_body = ( - '%s' - % (self._ADWORDS_ENDPOINT, ''.join([operation - for operation in operations]))) - - req = urllib2.Request(upload_url) - req.add_header('Content-Type', 'application/xml') - urllib2.urlopen(req, data=request_body) - - def GenerateRawRequestXML(self, operations, service): - """Generates the raw XML for the operations sent to the given service. - - Args: - operations: a list containing operations that could be run by the given - service. - service: a str identifying the name of the service that the operations - would ordinarily be run against. - - Returns: - A str containing the raw XML of the request to the given service that - would execute the given operations. - """ - service = self.client.GetService(service, 'v201509') - service.suds_client.set_options(nosend=True) - service_request = service.mutate(operations).envelope - service.suds_client.set_options(nosend=False) - return service_request - - def ExtractOperations(self, full_soap_xml): - """Extracts operations from API Request XML for use with BatchJobService. - - Args: - full_soap_xml: The full XML for the desired operation, as generated by - suds. - - Returns: - A string containing only the operations portion of the full XML request, - formatted for use with the BatchJobService. If no operations are found, - returns an empty string. - - Raises: - ValueError: If no Operation.Type element is found in the operations. This - ordinarily happens if no xsi_type is specified for the operations. - """ - # Extract mutate element from XML - mutate = BatchJobHelper._GetRawOperationsFromXML(self, full_soap_xml) - - if mutate is not None: - # Ensure operations are formatted correctly for BatchJobService. - for operations in mutate: - self._FormatForBatchJobService(operations) - # Extract the operation type, ensure xsi:type is set for - # BatchJobService. - operation_type = operations.find('Operation.Type') - - if operation_type is None: - raise ValueError('No xsi_type specified for the operations.') - - operations.attrib['xsi:type'] = operation_type.text - operations_xml = ''.join([ElementTree.tostring(operations) - for operations in mutate]) - return operations_xml - else: - return '' - - def _FormatForBatchJobService(self, element): - """Formats contents of all operations for use with the BatchJobService. - - This will recursively remove unnecessary namespaces generated by suds that - would prevent the operations from executing via the BatchJobService. It will - also remove namespaces appended to the xsi:type in some cases that also - cause issues for the BatchJobService. - - Args: - element: a starting Element to be modified to the correct format. - """ - # Remove any unnecessary AdWords namespace from the tag. - element.tag = self._TAG_NAMESPACE_SUB.sub('', element.tag) - xsi_type = element.attrib.get( - '{http://www.w3.org/2001/XMLSchema-instance}type') - # If an xsi_type attribute exists, ensure that the namespace is removed from - # the type. - if xsi_type: - element.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'] = ( - self._ATTRIB_NAMESPACE_SUB.sub('', xsi_type)) - for child in element: - self._FormatForBatchJobService(child) - - def _GetRawOperationsFromXML(self, raw_request_xml): - """Retrieve the raw set of operations from the request XML. - - Args: - raw_request_xml: The full XML for the desired operation, as generated by - suds. - - Returns: - An unmodified mutate Element containing the operations from the raw - request xml. - - Raises: - AttributeError: if the provided XML isn't from AdWords. - """ - root = ElementTree.fromstring(raw_request_xml) - return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( - '%smutate' % self._ADWORDS_NAMESPACE) - - -class BatchJobServiceIdGenerator(object): - """Utility for generating IDs used by the BatchJobService. - - This produces sequential negative IDs used by the BatchJobService as temporary - IDs for resources created while the jobs execute. These can be used across - operations for cases where the ID of one resource a is a dependency of - another resource. - """ - - def __init__(self): - """Initializes the BatchJobServiceIdGenerator.""" - self.i = 0 - - def GetId(self): - """Produces a distinct sequential Id for the BatchJobService. - - Returns: - A negative number that will be the temporary Id for an API resource. - """ - self.i -= 1 - return self.i diff --git a/examples/dfp/v201411/contact_service/__init__.py b/examples/dfp/v201411/contact_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/contact_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201411/content_metadata_key_hierarchy_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/content_service/__init__.py b/examples/dfp/v201411/content_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/content_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/creative_service/__init__.py b/examples/dfp/v201411/creative_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/creative_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/creative_set_service/__init__.py b/examples/dfp/v201411/creative_set_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/creative_set_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/creative_template_service/__init__.py b/examples/dfp/v201411/creative_template_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/creative_template_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/custom_field_service/__init__.py b/examples/dfp/v201411/custom_field_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/custom_field_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/custom_targeting_service/__init__.py b/examples/dfp/v201411/custom_targeting_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/custom_targeting_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/exchange_rate_service/__init__.py b/examples/dfp/v201411/exchange_rate_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/exchange_rate_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/inventory_service/__init__.py b/examples/dfp/v201411/inventory_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/inventory_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/label_service/__init__.py b/examples/dfp/v201411/label_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/label_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/line_item_creative_association_service/__init__.py b/examples/dfp/v201411/line_item_creative_association_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/line_item_creative_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/line_item_service/__init__.py b/examples/dfp/v201411/line_item_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/line_item_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/network_service/__init__.py b/examples/dfp/v201411/network_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/network_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/order_service/__init__.py b/examples/dfp/v201411/order_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/order_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/product_service/__init__.py b/examples/dfp/v201411/product_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/product_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/proposal_line_item_service/__init__.py b/examples/dfp/v201411/proposal_line_item_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/proposal_line_item_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/proposal_service/__init__.py b/examples/dfp/v201411/proposal_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/proposal_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/publisher_query_language_service/__init__.py b/examples/dfp/v201411/publisher_query_language_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/publisher_query_language_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/rate_card_service/__init__.py b/examples/dfp/v201411/rate_card_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/rate_card_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/report_service/__init__.py b/examples/dfp/v201411/report_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/report_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/suggested_ad_unit_service/__init__.py b/examples/dfp/v201411/suggested_ad_unit_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/suggested_ad_unit_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/team_service/__init__.py b/examples/dfp/v201411/team_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/team_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/user_service/__init__.py b/examples/dfp/v201411/user_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/user_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/user_team_association_service/__init__.py b/examples/dfp/v201411/user_team_association_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/user_team_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201411/workflow_request_service/__init__.py b/examples/dfp/v201411/workflow_request_service/__init__.py deleted file mode 100755 index 02adb9a5..00000000 --- a/examples/dfp/v201411/workflow_request_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/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. diff --git a/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py index c2c51d26..9ddade58 100755 --- a/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py @@ -36,11 +36,11 @@ def main(client, line_item_id1, line_item_id2): # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( [line_item_id1, line_item_id2], None) - + for single_forecast in forecast['lineItemDeliveryForecasts']: unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:%n%t%d %s matched%n%t%d %s delivered%n%t' - '%d %s predicted%n' % ( + print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( single_forecast['lineItemId'], single_forecast['matchedUnits'], unit_type, single_forecast['deliveredUnits'], unit_type, single_forecast['predictedDeliveryUnits'], unit_type)) diff --git a/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py index ee829e85..9f47d86a 100755 --- a/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py @@ -36,11 +36,11 @@ def main(client, line_item_id1, line_item_id2): # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( [line_item_id1, line_item_id2], None) - + for single_forecast in forecast['lineItemDeliveryForecasts']: unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:%n%t%d %s matched%n%t%d %s delivered%n%t' - '%d %s predicted%n' % ( + print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( single_forecast['lineItemId'], single_forecast['matchedUnits'], unit_type, single_forecast['deliveredUnits'], unit_type, single_forecast['predictedDeliveryUnits'], unit_type)) diff --git a/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py index 46742580..6db68bff 100755 --- a/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py @@ -36,11 +36,11 @@ def main(client, line_item_id1, line_item_id2): # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( [line_item_id1, line_item_id2], None) - + for single_forecast in forecast['lineItemDeliveryForecasts']: unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:%n%t%d %s matched%n%t%d %s delivered%n%t' - '%d %s predicted%n' % ( + print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( single_forecast['lineItemId'], single_forecast['matchedUnits'], unit_type, single_forecast['deliveredUnits'], unit_type, single_forecast['predictedDeliveryUnits'], unit_type)) diff --git a/examples/dfp/v201411/base_rate_service/__init__.py b/examples/dfp/v201511/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201411/base_rate_service/__init__.py rename to examples/dfp/v201511/activity_group_service/__init__.py diff --git a/examples/dfp/v201411/activity_group_service/create_activity_groups.py b/examples/dfp/v201511/activity_group_service/create_activity_groups.py similarity index 95% rename from examples/dfp/v201411/activity_group_service/create_activity_groups.py rename to examples/dfp/v201511/activity_group_service/create_activity_groups.py index f8be58bd..95ad201a 100755 --- a/examples/dfp/v201411/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201511/activity_group_service/create_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201411') + version='v201511') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201511/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/dfp/v201411/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201511/activity_group_service/get_active_activity_groups.py index 10040d10..32a7cc0d 100755 --- a/examples/dfp/v201411/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201511/activity_group_service/get_active_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201411') + version='v201511') # Create statement object to only select active activity groups. values = [{ diff --git a/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201511/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/dfp/v201411/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201511/activity_group_service/get_all_activity_groups.py index 306eb56c..d6b02cae 100755 --- a/examples/dfp/v201411/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201511/activity_group_service/get_all_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201411') + version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/activity_group_service/update_activity_groups.py b/examples/dfp/v201511/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/dfp/v201411/activity_group_service/update_activity_groups.py rename to examples/dfp/v201511/activity_group_service/update_activity_groups.py index 98b3fca2..448eadd6 100755 --- a/examples/dfp/v201411/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201511/activity_group_service/update_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201411') + version='v201511') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201411/premium_rate_service/__init__.py b/examples/dfp/v201511/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201411/premium_rate_service/__init__.py rename to examples/dfp/v201511/activity_service/__init__.py diff --git a/examples/dfp/v201411/activity_service/create_activities.py b/examples/dfp/v201511/activity_service/create_activities.py similarity index 97% rename from examples/dfp/v201411/activity_service/create_activities.py rename to examples/dfp/v201511/activity_service/create_activities.py index 2429d4aa..eaa35ca6 100755 --- a/examples/dfp/v201411/activity_service/create_activities.py +++ b/examples/dfp/v201511/activity_service/create_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201411') + activity_service = client.GetService('ActivityService', version='v201511') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201411/activity_service/get_active_activities.py b/examples/dfp/v201511/activity_service/get_active_activities.py similarity index 97% rename from examples/dfp/v201411/activity_service/get_active_activities.py rename to examples/dfp/v201511/activity_service/get_active_activities.py index 89086383..70c745e5 100755 --- a/examples/dfp/v201411/activity_service/get_active_activities.py +++ b/examples/dfp/v201511/activity_service/get_active_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201411') + activity_service = client.GetService('ActivityService', version='v201511') # Create statement object to only select active activities. values = [{ diff --git a/examples/dfp/v201411/activity_service/get_all_activities.py b/examples/dfp/v201511/activity_service/get_all_activities.py similarity index 96% rename from examples/dfp/v201411/activity_service/get_all_activities.py rename to examples/dfp/v201511/activity_service/get_all_activities.py index 070b9618..02f8c2d0 100755 --- a/examples/dfp/v201411/activity_service/get_all_activities.py +++ b/examples/dfp/v201511/activity_service/get_all_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201411') + activity_service = client.GetService('ActivityService', version='v201511') # Create statement object to select only all activities. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/activity_service/update_activities.py b/examples/dfp/v201511/activity_service/update_activities.py similarity index 97% rename from examples/dfp/v201411/activity_service/update_activities.py rename to examples/dfp/v201511/activity_service/update_activities.py index 2fd6f715..0b9d622c 100755 --- a/examples/dfp/v201411/activity_service/update_activities.py +++ b/examples/dfp/v201511/activity_service/update_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201411') + activity_service = client.GetService('ActivityService', version='v201511') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201411/product_template_service/__init__.py b/examples/dfp/v201511/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201411/product_template_service/__init__.py rename to examples/dfp/v201511/audience_segment_service/__init__.py diff --git a/examples/dfp/v201411/audience_segment_service/create_audience_segments.py b/examples/dfp/v201511/audience_segment_service/create_audience_segments.py similarity index 93% rename from examples/dfp/v201411/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201511/audience_segment_service/create_audience_segments.py index 3ef66447..e73a26eb 100755 --- a/examples/dfp/v201411/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201511/audience_segment_service/create_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,8 +32,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201411') - network_service = client.GetService('NetworkService', version='v201411') + 'AudienceSegmentService', version='v201511') + network_service = client.GetService('NetworkService', version='v201511') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( @@ -50,8 +50,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): custom_criteria = [ { 'xsi_type': 'CustomCriteria', - 'keyId': CUSTOM_TARGETING_KEY_ID, - 'valueIds': [CUSTOM_TARGETING_VALUE_ID], + 'keyId': custom_targeting_key_id, + 'valueIds': [custom_targeting_value_id], 'operator': 'IS' } ] diff --git a/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201511/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201511/audience_segment_service/get_all_audience_segments.py index 69b63f9b..443d135a 100755 --- a/examples/dfp/v201411/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201511/audience_segment_service/get_all_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201411') + 'AudienceSegmentService', version='v201511') # Create statement object to select all audience segments. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201511/audience_segment_service/get_first_party_audience_segments.py similarity index 95% rename from examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201511/audience_segment_service/get_first_party_audience_segments.py index 4593817e..f68e0dc8 100755 --- a/examples/dfp/v201411/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201511/audience_segment_service/get_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201411') + 'AudienceSegmentService', version='v201511') # Create statement object to only select first party audience segments. values = [{ diff --git a/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201511/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201511/audience_segment_service/populate_first_party_audience_segments.py index 658f0044..254a6d0c 100755 --- a/examples/dfp/v201411/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201511/audience_segment_service/populate_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201411') + 'AudienceSegmentService', version='v201511') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201411/audience_segment_service/update_audience_segments.py b/examples/dfp/v201511/audience_segment_service/update_audience_segments.py similarity index 96% rename from examples/dfp/v201411/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201511/audience_segment_service/update_audience_segments.py index 338d54b7..7aec80d3 100755 --- a/examples/dfp/v201411/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201511/audience_segment_service/update_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201411') + 'AudienceSegmentService', version='v201511') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201411/company_service/__init__.py b/examples/dfp/v201511/base_rate_service/__init__.py similarity index 91% rename from examples/dfp/v201411/company_service/__init__.py rename to examples/dfp/v201511/base_rate_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201411/company_service/__init__.py +++ b/examples/dfp/v201511/base_rate_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201411/base_rate_service/create_product_base_rates.py b/examples/dfp/v201511/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201411/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201511/base_rate_service/create_product_base_rates.py index 4cde291b..debb93d0 100755 --- a/examples/dfp/v201411/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201511/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201411') + 'BaseRateService', version='v201511') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201511/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201511/base_rate_service/create_product_template_base_rates.py index 6884a1bd..9f4d7f91 100755 --- a/examples/dfp/v201411/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201511/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201411') + 'BaseRateService', version='v201511') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201411/base_rate_service/get_all_base_rates.py b/examples/dfp/v201511/base_rate_service/get_all_base_rates.py similarity index 94% rename from examples/dfp/v201411/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201511/base_rate_service/get_all_base_rates.py index 450638ac..7c0dd891 100755 --- a/examples/dfp/v201411/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201511/base_rate_service/get_all_base_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201411') + base_rate_service = client.GetService('BaseRateService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') @@ -43,7 +43,8 @@ def main(client): for base_rate in response['results']: print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' 'rate card ID \'%s\' was found.' % ( - base_rate['id'], base_rate['BaseRate.Type'], + base_rate['id'], + dfp.DfpClassType(base_rate), base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: diff --git a/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201511/base_rate_service/get_base_rates_for_a_rate_card.py similarity index 95% rename from examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py rename to examples/dfp/v201511/base_rate_service/get_base_rates_for_a_rate_card.py index 32ac9941..90527f3f 100755 --- a/examples/dfp/v201411/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201511/base_rate_service/get_base_rates_for_a_rate_card.py @@ -31,7 +31,7 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201411') + base_rate_service = client.GetService('BaseRateService', version='v201511') # Create a filter statement for base rates for a single rate card. values = [{ @@ -53,7 +53,8 @@ def main(client, rate_card_id): for base_rate in response['results']: print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' 'rate card ID \'%s\' was found.' % ( - base_rate['id'], base_rate['BaseRate.Type'], + base_rate['id'], + dfp.DfpClassType(base_rate), base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: diff --git a/examples/dfp/v201411/base_rate_service/update_base_rates.py b/examples/dfp/v201511/base_rate_service/update_base_rates.py similarity index 95% rename from examples/dfp/v201411/base_rate_service/update_base_rates.py rename to examples/dfp/v201511/base_rate_service/update_base_rates.py index f5323598..09bcd071 100755 --- a/examples/dfp/v201411/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201511/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201411') + base_rate_service = client.GetService('BaseRateService', version='v201511') # Create a filter statement for base rates for a single rate card. values = [{ @@ -66,7 +66,8 @@ def main(client, base_rate_id): for base_rate in base_rates: print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' 'rate card ID \'%s\' was updated.' % ( - base_rate['id'], base_rate['BaseRate.Type'], + base_rate['id'], + dfp.DfpClassType(base_rate), base_rate['rateCardId'])) else: print 'No base rates were updated.' diff --git a/examples/dfp/v201411/activity_group_service/__init__.py b/examples/dfp/v201511/company_service/__init__.py similarity index 91% rename from examples/dfp/v201411/activity_group_service/__init__.py rename to examples/dfp/v201511/company_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201411/activity_group_service/__init__.py +++ b/examples/dfp/v201511/company_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201411/company_service/create_companies.py b/examples/dfp/v201511/company_service/create_companies.py similarity index 96% rename from examples/dfp/v201411/company_service/create_companies.py rename to examples/dfp/v201511/company_service/create_companies.py index 219fe6d9..74658606 100755 --- a/examples/dfp/v201411/company_service/create_companies.py +++ b/examples/dfp/v201511/company_service/create_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201411') + company_service = client.GetService('CompanyService', version='v201511') # Create company objects. companies = [ diff --git a/examples/dfp/v201411/company_service/get_advertisers.py b/examples/dfp/v201511/company_service/get_advertisers.py similarity index 97% rename from examples/dfp/v201411/company_service/get_advertisers.py rename to examples/dfp/v201511/company_service/get_advertisers.py index 759313ef..96d54060 100755 --- a/examples/dfp/v201411/company_service/get_advertisers.py +++ b/examples/dfp/v201511/company_service/get_advertisers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201411') + company_service = client.GetService('CompanyService', version='v201511') # Create statement object to only select companies that are advertisers. values = [{ diff --git a/examples/dfp/v201411/company_service/get_all_companies.py b/examples/dfp/v201511/company_service/get_all_companies.py similarity index 96% rename from examples/dfp/v201411/company_service/get_all_companies.py rename to examples/dfp/v201511/company_service/get_all_companies.py index 0ca241aa..bf712894 100755 --- a/examples/dfp/v201411/company_service/get_all_companies.py +++ b/examples/dfp/v201511/company_service/get_all_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201411') + company_service = client.GetService('CompanyService', version='v201511') # Create statement object to select all companies. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/company_service/update_companies.py b/examples/dfp/v201511/company_service/update_companies.py similarity index 97% rename from examples/dfp/v201411/company_service/update_companies.py rename to examples/dfp/v201511/company_service/update_companies.py index 49936e3e..eadd677d 100755 --- a/examples/dfp/v201411/company_service/update_companies.py +++ b/examples/dfp/v201511/company_service/update_companies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201411') + company_service = client.GetService('CompanyService', version='v201511') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201411/activity_service/__init__.py b/examples/dfp/v201511/contact_service/__init__.py similarity index 91% rename from examples/dfp/v201411/activity_service/__init__.py rename to examples/dfp/v201511/contact_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201411/activity_service/__init__.py +++ b/examples/dfp/v201511/contact_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201411/contact_service/create_contacts.py b/examples/dfp/v201511/contact_service/create_contacts.py similarity index 97% rename from examples/dfp/v201411/contact_service/create_contacts.py rename to examples/dfp/v201511/contact_service/create_contacts.py index 33473868..f5538caf 100755 --- a/examples/dfp/v201411/contact_service/create_contacts.py +++ b/examples/dfp/v201511/contact_service/create_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201411') + contact_service = client.GetService('ContactService', version='v201511') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201411/contact_service/get_all_contacts.py b/examples/dfp/v201511/contact_service/get_all_contacts.py similarity index 96% rename from examples/dfp/v201411/contact_service/get_all_contacts.py rename to examples/dfp/v201511/contact_service/get_all_contacts.py index 88f319f9..5d96fa18 100755 --- a/examples/dfp/v201411/contact_service/get_all_contacts.py +++ b/examples/dfp/v201511/contact_service/get_all_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201411') + contact_service = client.GetService('ContactService', version='v201511') # Create statement object to get all contacts. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/contact_service/get_uninvited_contacts.py b/examples/dfp/v201511/contact_service/get_uninvited_contacts.py similarity index 97% rename from examples/dfp/v201411/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201511/contact_service/get_uninvited_contacts.py index 893c9a59..4ca72a5d 100755 --- a/examples/dfp/v201411/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201511/contact_service/get_uninvited_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201411') + contact_service = client.GetService('ContactService', version='v201511') # Create statement object to only select contacts that are uninvited. values = [{ diff --git a/examples/dfp/v201411/contact_service/update_contacts.py b/examples/dfp/v201511/contact_service/update_contacts.py similarity index 97% rename from examples/dfp/v201411/contact_service/update_contacts.py rename to examples/dfp/v201511/contact_service/update_contacts.py index c1db8705..1656f6fa 100755 --- a/examples/dfp/v201411/contact_service/update_contacts.py +++ b/examples/dfp/v201511/contact_service/update_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201411') + contact_service = client.GetService('ContactService', version='v201511') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201411/audience_segment_service/__init__.py b/examples/dfp/v201511/content_metadata_key_hierarchy_service/__init__.py similarity index 91% rename from examples/dfp/v201411/audience_segment_service/__init__.py rename to examples/dfp/v201511/content_metadata_key_hierarchy_service/__init__.py index 02adb9a5..a426ca48 100755 --- a/examples/dfp/v201411/audience_segment_service/__init__.py +++ b/examples/dfp/v201511/content_metadata_key_hierarchy_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201511/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 95% rename from examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201511/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 7b5aea36..52f2db84 100755 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201511/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201411') + 'ContentMetadataKeyHierarchyService', version='v201511') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201511/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201511/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 3d20e444..400f5e4e 100755 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201511/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201411') + 'ContentMetadataKeyHierarchyService', version='v201511') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201511/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 95% rename from examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201511/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index d200593f..54017130 100755 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201511/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201411') + 'ContentMetadataKeyHierarchyService', version='v201511') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201511/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201511/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index cd8ad106..dee65348 100755 --- a/examples/dfp/v201411/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201511/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201411') + 'ContentMetadataKeyHierarchyService', version='v201511') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201511/content_service/__init__.py b/examples/dfp/v201511/content_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/content_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/content_service/get_all_content.py b/examples/dfp/v201511/content_service/get_all_content.py similarity index 96% rename from examples/dfp/v201411/content_service/get_all_content.py rename to examples/dfp/v201511/content_service/get_all_content.py index 919c4683..e7747145 100755 --- a/examples/dfp/v201411/content_service/get_all_content.py +++ b/examples/dfp/v201511/content_service/get_all_content.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201411') + content_service = client.GetService('ContentService', version='v201511') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/content_service/get_content_by_category.py b/examples/dfp/v201511/content_service/get_content_by_category.py similarity index 96% rename from examples/dfp/v201411/content_service/get_content_by_category.py rename to examples/dfp/v201511/content_service/get_content_by_category.py index f37eb1a8..19c55e77 100755 --- a/examples/dfp/v201411/content_service/get_content_by_category.py +++ b/examples/dfp/v201511/content_service/get_content_by_category.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,10 +33,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201411') - network_service = client.GetService('NetworkService', version='v201411') + content_service = client.GetService('ContentService', version='v201511') + network_service = client.GetService('NetworkService', version='v201511') custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') # Get the network's content browse custom targeting key. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201511/creative_service/__init__.py b/examples/dfp/v201511/creative_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/creative_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/creative_service/create_creative_from_template.py b/examples/dfp/v201511/creative_service/create_creative_from_template.py similarity index 96% rename from examples/dfp/v201411/creative_service/create_creative_from_template.py rename to examples/dfp/v201511/creative_service/create_creative_from_template.py index 34c20d8e..b8e0081c 100755 --- a/examples/dfp/v201411/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201511/creative_service/create_creative_from_template.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201411') + creative_service = client.GetService('CreativeService', version='v201511') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' @@ -92,7 +92,7 @@ def main(client, advertiser_id): # Display results. print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201411/creative_service/create_creatives.py b/examples/dfp/v201511/creative_service/create_creatives.py similarity index 95% rename from examples/dfp/v201411/creative_service/create_creatives.py rename to examples/dfp/v201511/creative_service/create_creatives.py index 9d169cbc..e14284d8 100755 --- a/examples/dfp/v201411/creative_service/create_creatives.py +++ b/examples/dfp/v201511/creative_service/create_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201411') + creative_service = client.GetService('CreativeService', version='v201511') # Create creative objects. creatives = [] @@ -82,7 +82,7 @@ def main(client, advertiser_id): for creative in creatives: print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201411/creative_service/create_custom_creative.py b/examples/dfp/v201511/creative_service/create_custom_creative.py similarity index 90% rename from examples/dfp/v201411/creative_service/create_custom_creative.py rename to examples/dfp/v201511/creative_service/create_custom_creative.py index e2948ee3..393e82ae 100755 --- a/examples/dfp/v201411/creative_service/create_custom_creative.py +++ b/examples/dfp/v201511/creative_service/create_custom_creative.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201411') + creative_service = client.GetService('CreativeService', version='v201511') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', @@ -64,8 +64,10 @@ def main(client, advertiser_id): { 'xsi_type': 'CustomCreativeAsset', 'macroName': 'IMAGE_ASSET', - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() + 'asset': { + 'assetByteArray': image_data, + 'fileName': 'image%s.jpg' % uuid.uuid4() + } } ], 'htmlSnippet': html_snippet @@ -78,7 +80,7 @@ def main(client, advertiser_id): if creative: print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['Creative.Type'], + % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/dfp/v201511/creative_service/create_native_creative.py b/examples/dfp/v201511/creative_service/create_native_creative.py new file mode 100755 index 00000000..53128ac2 --- /dev/null +++ b/examples/dfp/v201511/creative_service/create_native_creative.py @@ -0,0 +1,135 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates a new native creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. + +The code in this example will use app data from the Google sample app +'Pie Noon': + +https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import urllib2 +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO' + 'PYnTdOQGaSpGSEZflIFs0iw=h300') +APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp' + 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300') + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201511') + + # Use the system defined native app install creative template. + creative_template_id = '10004400' + + image_data = urllib2.urlopen(ICON_URL).read() + image_data = base64.b64encode(image_data) + + app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() + app_icon_data = base64.b64encode(app_icon_data) + + # Create creative from templates. + creative = { + 'xsi_type': 'TemplateCreative', + 'name': 'Native Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '1', 'height': '1', 'isAspectRatio': False}, + 'creativeTemplateId': creative_template_id, + 'destinationUrl': ('https://play.google.com/store/apps/details?id=' + 'com.google.fpl.pie_noon'), + 'creativeTemplateVariableValues': [ + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Image', + 'asset': { + 'assetByteArray': image_data, + 'fileName': 'file%s.png' % uuid.uuid4() + } + }, + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Appicon', + 'asset': { + 'assetByteArray': app_icon_data, + 'fileName': 'appicon%s.png' % uuid.uuid4() + } + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Price', + 'value': 'Free' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Calltoaction', + 'value': 'Install' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Starrating', + 'value': '4' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Store', + 'value': 'Google Play' + }, + { + 'xsi_type': 'UrlCreativeTemplateVariableValue', + 'uniqueName': 'DeeplinkclickactionURL', + 'value': 'market://details?id=com.google.fpl.pie_noon' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Body', + 'value': 'Try multi-screen mode!' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Headline', + 'value': 'Pie Noon' + } + ] + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print ('Native creative with id \'%s\' and name \'%s\' was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], creative['previewUrl'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201411/creative_service/get_all_creatives.py b/examples/dfp/v201511/creative_service/get_all_creatives.py similarity index 93% rename from examples/dfp/v201411/creative_service/get_all_creatives.py rename to examples/dfp/v201511/creative_service/get_all_creatives.py index 2dacbd55..2d3de109 100755 --- a/examples/dfp/v201411/creative_service/get_all_creatives.py +++ b/examples/dfp/v201511/creative_service/get_all_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201411') + creative_service = client.GetService('CreativeService', version='v201511') # Create statement object to select all creatives. statement = dfp.FilterStatement() @@ -46,7 +46,7 @@ def main(client): for creative in response['results']: print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'found.' % (creative['id'], creative['name'], - creative['Creative.Type'])) + dfp.DfpClassType(creative))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201411/creative_service/get_creatives_by_statement.py b/examples/dfp/v201511/creative_service/get_creatives_by_statement.py similarity index 94% rename from examples/dfp/v201411/creative_service/get_creatives_by_statement.py rename to examples/dfp/v201511/creative_service/get_creatives_by_statement.py index f49a4222..a57f641c 100755 --- a/examples/dfp/v201411/creative_service/get_creatives_by_statement.py +++ b/examples/dfp/v201511/creative_service/get_creatives_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201411') + creative_service = client.GetService('CreativeService', version='v201511') # Create statement object to only select image creatives. values = [{ @@ -56,7 +56,7 @@ def main(client): for creative in creatives: print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'found.' % (creative['id'], creative['name'], - creative['Creative.Type'])) + dfp.DfpClassType(creative))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201411/creative_service/update_creatives.py b/examples/dfp/v201511/creative_service/update_creatives.py similarity index 97% rename from examples/dfp/v201411/creative_service/update_creatives.py rename to examples/dfp/v201511/creative_service/update_creatives.py index de7f3125..025e18e2 100755 --- a/examples/dfp/v201411/creative_service/update_creatives.py +++ b/examples/dfp/v201511/creative_service/update_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201411') + creative_service = client.GetService('CreativeService', version='v201511') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201511/creative_set_service/__init__.py b/examples/dfp/v201511/creative_set_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/creative_set_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201511/creative_set_service/associate_creative_set_to_line_item.py similarity index 94% rename from examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201511/creative_set_service/associate_creative_set_to_line_item.py index b70d1160..f7a74261 100755 --- a/examples/dfp/v201411/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201511/creative_set_service/associate_creative_set_to_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201411') + 'LineItemCreativeAssociationService', version='v201511') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201411/creative_set_service/create_creative_set.py b/examples/dfp/v201511/creative_set_service/create_creative_set.py similarity index 94% rename from examples/dfp/v201411/creative_set_service/create_creative_set.py rename to examples/dfp/v201511/creative_set_service/create_creative_set.py index d359335d..5a3cdaa0 100755 --- a/examples/dfp/v201411/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201511/creative_set_service/create_creative_set.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201411') + version='v201511') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201511/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/dfp/v201411/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201511/creative_set_service/get_all_creative_sets.py index 09467cc5..8bbcd04b 100755 --- a/examples/dfp/v201411/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201511/creative_set_service/get_all_creative_sets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201411') + version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201511/creative_set_service/get_creative_sets_by_statement.py similarity index 95% rename from examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py rename to examples/dfp/v201511/creative_set_service/get_creative_sets_by_statement.py index 22ef638b..9afe63a5 100755 --- a/examples/dfp/v201411/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201511/creative_set_service/get_creative_sets_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201411') + version='v201511') # Create statement object to only select creative sets that have the given # master creative. diff --git a/examples/dfp/v201411/creative_set_service/update_creative_set.py b/examples/dfp/v201511/creative_set_service/update_creative_set.py similarity index 95% rename from examples/dfp/v201411/creative_set_service/update_creative_set.py rename to examples/dfp/v201511/creative_set_service/update_creative_set.py index 3738c0f1..3c041d91 100755 --- a/examples/dfp/v201411/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201511/creative_set_service/update_creative_set.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201411') + version='v201511') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201511/creative_template_service/__init__.py b/examples/dfp/v201511/creative_template_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/creative_template_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201511/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/dfp/v201411/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201511/creative_template_service/get_all_creative_templates.py index b7acc37b..80a769af 100755 --- a/examples/dfp/v201411/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201511/creative_template_service/get_all_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201411') + 'CreativeTemplateService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201511/creative_template_service/get_creative_templates_by_statement.py similarity index 95% rename from examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py rename to examples/dfp/v201511/creative_template_service/get_creative_templates_by_statement.py index d6cdf6a0..b0be9179 100755 --- a/examples/dfp/v201411/creative_template_service/get_creative_templates_by_statement.py +++ b/examples/dfp/v201511/creative_template_service/get_creative_templates_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201411') + 'CreativeTemplateService', version='v201511') # Create statement object to only select system defined creative templates. values = [{ diff --git a/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201511/creative_wrapper_service/create_creative_wrappers.py similarity index 94% rename from examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201511/creative_wrapper_service/create_creative_wrappers.py index 0e2b524a..19c05e39 100755 --- a/examples/dfp/v201411/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201511/creative_wrapper_service/create_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201411') + version='v201511') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201511/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 96% rename from examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201511/creative_wrapper_service/deactivate_creative_wrapper.py index cbc924f5..265b4fa1 100755 --- a/examples/dfp/v201411/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201511/creative_wrapper_service/deactivate_creative_wrapper.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201411') + version='v201511') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201511/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201511/creative_wrapper_service/get_active_creative_wrappers.py index 2848e4b6..e7e06ac9 100755 --- a/examples/dfp/v201411/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201511/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201411') + version='v201511') # Create statement object to only select active creative wrappers. values = [{ diff --git a/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201511/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201511/creative_wrapper_service/get_all_creative_wrappers.py index 3ce406a8..feaf9556 100755 --- a/examples/dfp/v201411/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201511/creative_wrapper_service/get_all_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201411') + version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201511/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201511/creative_wrapper_service/update_creative_wrappers.py index eb2b4b01..85db9fc9 100755 --- a/examples/dfp/v201411/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201511/creative_wrapper_service/update_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201411') + version='v201511') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201511/custom_field_service/__init__.py b/examples/dfp/v201511/custom_field_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/custom_field_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/custom_field_service/create_custom_field_options.py b/examples/dfp/v201511/custom_field_service/create_custom_field_options.py similarity index 95% rename from examples/dfp/v201411/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201511/custom_field_service/create_custom_field_options.py index d34fc59e..d40575cb 100755 --- a/examples/dfp/v201411/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201511/custom_field_service/create_custom_field_options.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201411') + 'CustomFieldService', version='v201511') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201411/custom_field_service/create_custom_fields.py b/examples/dfp/v201511/custom_field_service/create_custom_fields.py similarity index 95% rename from examples/dfp/v201411/custom_field_service/create_custom_fields.py rename to examples/dfp/v201511/custom_field_service/create_custom_fields.py index 1b90f115..6d28d55f 100755 --- a/examples/dfp/v201411/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201511/custom_field_service/create_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201411') + 'CustomFieldService', version='v201511') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201511/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 96% rename from examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201511/custom_field_service/deactivate_all_line_item_custom_fields.py index 4d99acc4..20e17ebc 100755 --- a/examples/dfp/v201411/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201511/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201411') + 'CustomFieldService', version='v201511') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201511/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/dfp/v201411/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201511/custom_field_service/get_all_custom_fields.py index 2affc664..7c17aa5d 100755 --- a/examples/dfp/v201411/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201511/custom_field_service/get_all_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201411') + 'CustomFieldService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201511/custom_field_service/get_all_line_item_custom_fields.py similarity index 95% rename from examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py rename to examples/dfp/v201511/custom_field_service/get_all_line_item_custom_fields.py index b6c9f9a8..c2932572 100755 --- a/examples/dfp/v201411/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201511/custom_field_service/get_all_line_item_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201411') + 'CustomFieldService', version='v201511') # Create statement to select only custom fields that apply to line items. values = [{ diff --git a/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201511/custom_field_service/set_line_item_custom_field_value.py similarity index 95% rename from examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201511/custom_field_service/set_line_item_custom_field_value.py index 08e778c1..7cf63b0c 100755 --- a/examples/dfp/v201411/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201511/custom_field_service/set_line_item_custom_field_value.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201411') + 'CustomFieldService', version='v201511') - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # Create statement to get a custom field. custom_field_values = [{ @@ -135,11 +135,11 @@ def main(client, custom_field_id, drop_down_custom_field_id, for line_item in line_items: custom_field_value_strings = [] for value in line_item['customFieldValues']: - if value['BaseCustomFieldValue.Type'] == 'CustomFieldValue': + if dfp.DfpClassType(value) == 'CustomFieldValue': custom_field_value_string = ( '{ID: \'%s\', value: \'%s\'}' % (value['customFieldId'], value['value']['value'])) - elif value['BaseCustomFieldValue.Type'] == 'DropDownCustomFieldValue': + elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( '{ID: \'%s\', custom field option ID: \'%s\'}' % (value['customFieldId'], value['customFieldOptionId'])) diff --git a/examples/dfp/v201411/custom_field_service/update_custom_fields.py b/examples/dfp/v201511/custom_field_service/update_custom_fields.py similarity index 96% rename from examples/dfp/v201411/custom_field_service/update_custom_fields.py rename to examples/dfp/v201511/custom_field_service/update_custom_fields.py index 28ea7422..774b6507 100755 --- a/examples/dfp/v201411/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201511/custom_field_service/update_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201411') + 'CustomFieldService', version='v201511') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201511/custom_targeting_service/__init__.py b/examples/dfp/v201511/custom_targeting_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/custom_targeting_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201511/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 97% rename from examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201511/custom_targeting_service/create_custom_targeting_keys_and_values.py index 6820dd86..d8107011 100755 --- a/examples/dfp/v201411/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201511/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_keys.py similarity index 96% rename from examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_keys.py index 44bc55b9..76c76226 100755 --- a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_keys.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') values = [{ 'key': 'name', diff --git a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_values.py similarity index 96% rename from examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_values.py index d0781855..1f81302d 100755 --- a/examples/dfp/v201411/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201511/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 96% rename from examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201511/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 53877569..7f44e6cc 100755 --- a/examples/dfp/v201411/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201511/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') # Create statement to get all targeting keys. targeting_key_statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_keys_by_statement.py similarity index 94% rename from examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py rename to examples/dfp/v201511/custom_targeting_service/get_custom_targeting_keys_by_statement.py index 49464fda..7018ca2d 100755 --- a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_keys_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') values = [{ 'key': 'type', diff --git a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_values_by_statement.py similarity index 95% rename from examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py rename to examples/dfp/v201511/custom_targeting_service/get_custom_targeting_values_by_statement.py index 9c64b6d0..f0cbf056 100755 --- a/examples/dfp/v201411/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ b/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_values_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201511/custom_targeting_service/update_custom_targeting_keys.py index f99aeafb..1c15b143 100755 --- a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_keys.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_values.py similarity index 96% rename from examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201511/custom_targeting_service/update_custom_targeting_values.py index d011feee..07eee074 100755 --- a/examples/dfp/v201411/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_values.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201411') + 'CustomTargetingService', version='v201511') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201511/exchange_rate_service/__init__.py b/examples/dfp/v201511/exchange_rate_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/exchange_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201511/exchange_rate_service/create_exchange_rates.py similarity index 94% rename from examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201511/exchange_rate_service/create_exchange_rates.py index a53d3ba7..10bc9b2d 100755 --- a/examples/dfp/v201411/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201511/exchange_rate_service/create_exchange_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201411') + version='v201511') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201511/exchange_rate_service/get_all_exchange_rates.py similarity index 94% rename from examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201511/exchange_rate_service/get_all_exchange_rates.py index 150e849a..ba9a0c5d 100755 --- a/examples/dfp/v201411/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201511/exchange_rate_service/get_all_exchange_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201411') + version='v201511') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201511/exchange_rate_service/get_exchange_rates_by_currency_code.py similarity index 95% rename from examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py rename to examples/dfp/v201511/exchange_rate_service/get_exchange_rates_by_currency_code.py index b57dbcf1..8e4b1bc9 100755 --- a/examples/dfp/v201411/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201511/exchange_rate_service/get_exchange_rates_by_currency_code.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201411') + version='v201511') # Create a statement to get exchange rates for the specified currency code. values = [{ diff --git a/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201511/exchange_rate_service/update_exchange_rates.py similarity index 95% rename from examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201511/exchange_rate_service/update_exchange_rates.py index 5acf07f4..15cb0e3d 100755 --- a/examples/dfp/v201411/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201511/exchange_rate_service/update_exchange_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201411') + version='v201511') # Create a statement to get an exchange rate by its ID. values = [{ diff --git a/examples/dfp/v201411/forecast_service/get_forecast.py b/examples/dfp/v201511/forecast_service/get_availability_forecast.py similarity index 63% rename from examples/dfp/v201411/forecast_service/get_forecast.py rename to examples/dfp/v201511/forecast_service/get_availability_forecast.py index d6eb4c73..152bbb88 100755 --- a/examples/dfp/v201411/forecast_service/get_forecast.py +++ b/examples/dfp/v201511/forecast_service/get_availability_forecast.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -14,9 +14,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets a forecast for a prospective line item. +"""This example gets a forecast for a prospective line item. -To determine which placements exist, run get_all_placements.py.""" +The prospective line item targets the entire network. The targeting can be +modified to determine forecasts for other criteria such as custom criteria +targeting (in addition to targeting the whole network). See +create_line_items.py for an example of how to create more complex targeting. + +""" from datetime import date @@ -24,19 +29,29 @@ # Import appropriate modules from the client library. from googleads import dfp -# Set the placement that the prospective line item will target. -TARGET_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE'] +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -def main(client, target_placement_ids): +def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201411') + forecast_service = client.GetService('ForecastService', version='v201511') + network_service = client.GetService('NetworkService', version='v201511') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] # Create prospective line item. line_item = { 'targeting': { 'inventoryTargeting': { - 'targetedPlacementIds': target_placement_ids + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] } }, 'creativePlaceholders': [ @@ -63,7 +78,8 @@ def main(client, target_placement_ids): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/New_York' }, 'costType': 'CPM', 'costPerUnit': { @@ -80,8 +96,20 @@ def main(client, target_placement_ids): 'discountType': 'PERCENTAGE', } + prospective_line_item = { + 'lineItem': line_item, + 'advertiserId': advertiser_id + } + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } + # Get forecast. - forecast = forecast_service.getForecast(line_item) + forecast = forecast_service.getAvailabilityForecast( + prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) available_percent = (((long(forecast['availableUnits'])/ (matched * 1.0)) * 100) @@ -94,11 +122,11 @@ def main(client, target_placement_ids): print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) print '%d contending line items.' % len(contending_line_items) - if 'possibleUnits' in forecast: + if 'possibleUnits' in forecast and matched: possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TARGET_PLACEMENT_IDS) + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201411/forecast_service/get_forecast_by_id.py b/examples/dfp/v201511/forecast_service/get_availability_forecast_for_line_item.py similarity index 76% rename from examples/dfp/v201411/forecast_service/get_forecast_by_id.py rename to examples/dfp/v201511/forecast_service/get_availability_forecast_for_line_item.py index d4b40161..6a869a44 100755 --- a/examples/dfp/v201411/forecast_service/get_forecast_by_id.py +++ b/examples/dfp/v201511/forecast_service/get_availability_forecast_for_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -14,24 +14,33 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example gets a forecast for an existing line item. +"""This code example gets an availability forecast for an existing line item. -To determine which line items exist, run get_all_line_items.py.""" +To determine which line items exist, run get_all_line_items.py. + +""" # Import appropriate modules from the client library. from googleads import dfp # Set the line item to get a forecast for. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID' +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201411') + forecast_service = client.GetService('ForecastService', version='v201511') + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } # Get forecast for line item. - forecast = forecast_service.getForecastById(line_item_id) + forecast = forecast_service.getAvailabilityForecastById( + line_item_id, forecast_options) matched = long(forecast['matchedUnits']) available_percent = (((long(forecast['availableUnits'])/ (matched * 1.0)) * 100) @@ -44,7 +53,7 @@ def main(client, line_item_id): print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) print '%d contending line items.' % len(contending_line_items) - if 'possibleUnits' in forecast: + if 'possibleUnits' in forecast and matched: possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) diff --git a/examples/dfp/v201511/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201511/forecast_service/get_delivery_forecast_for_line_items.py new file mode 100755 index 00000000..01d0b6c7 --- /dev/null +++ b/examples/dfp/v201511/forecast_service/get_delivery_forecast_for_line_items.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets a delivery forecast for two existing line items. + +To determine which line items exist, run get_all_line_items.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the line items to get forecasts for. +LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' +LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE' + + +def main(client, line_item_id1, line_item_id2): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201511') + + # Get forecast for line item. + forecast = forecast_service.getDeliveryForecastByIds( + [line_item_id1, line_item_id2], None) + + for single_forecast in forecast['lineItemDeliveryForecasts']: + unit_type = single_forecast['unitType'] + print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( + single_forecast['lineItemId'], single_forecast['matchedUnits'], + unit_type, single_forecast['deliveredUnits'], unit_type, + single_forecast['predictedDeliveryUnits'], unit_type)) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201511/inventory_service/__init__.py b/examples/dfp/v201511/inventory_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/inventory_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/inventory_service/archive_ad_units.py b/examples/dfp/v201511/inventory_service/archive_ad_units.py similarity index 97% rename from examples/dfp/v201411/inventory_service/archive_ad_units.py rename to examples/dfp/v201511/inventory_service/archive_ad_units.py index 4f75a4c7..abacd508 100755 --- a/examples/dfp/v201411/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201511/inventory_service/archive_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201411') + inventory_service = client.GetService('InventoryService', version='v201511') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201411/inventory_service/create_ad_units.py b/examples/dfp/v201511/inventory_service/create_ad_units.py similarity index 96% rename from examples/dfp/v201411/inventory_service/create_ad_units.py rename to examples/dfp/v201511/inventory_service/create_ad_units.py index 6e003e09..a170447f 100755 --- a/examples/dfp/v201411/inventory_service/create_ad_units.py +++ b/examples/dfp/v201511/inventory_service/create_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201411') + inventory_service = client.GetService('InventoryService', version='v201511') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201511/inventory_service/get_ad_unit_hierarchy.py similarity index 98% rename from examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py rename to examples/dfp/v201511/inventory_service/get_ad_unit_hierarchy.py index cc63a207..48edc04a 100755 --- a/examples/dfp/v201411/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201511/inventory_service/get_ad_unit_hierarchy.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201411') + inventory_service = client.GetService('InventoryService', version='v201511') statement = dfp.FilterStatement() all_ad_units = [] diff --git a/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201511/inventory_service/get_all_ad_unit_sizes.py similarity index 96% rename from examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201511/inventory_service/get_all_ad_unit_sizes.py index 34388920..60427703 100755 --- a/examples/dfp/v201411/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201511/inventory_service/get_all_ad_unit_sizes.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201411') + inventory_service = client.GetService('InventoryService', version='v201511') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201411/inventory_service/get_all_ad_units.py b/examples/dfp/v201511/inventory_service/get_all_ad_units.py similarity index 96% rename from examples/dfp/v201411/inventory_service/get_all_ad_units.py rename to examples/dfp/v201511/inventory_service/get_all_ad_units.py index 688eb008..45fe7a33 100755 --- a/examples/dfp/v201411/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201511/inventory_service/get_all_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201411') + inventory_service = client.GetService('InventoryService', version='v201511') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201511/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/dfp/v201411/inventory_service/get_top_level_ad_units.py rename to examples/dfp/v201511/inventory_service/get_top_level_ad_units.py index 1291b78d..00994c63 100755 --- a/examples/dfp/v201411/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201511/inventory_service/get_top_level_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,8 +32,8 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201411') - network_service = client.GetService('NetworkService', version='v201411') + inventory_service = client.GetService('InventoryService', version='v201511') + network_service = client.GetService('NetworkService', version='v201511') root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201411/inventory_service/update_ad_units.py b/examples/dfp/v201511/inventory_service/update_ad_units.py similarity index 97% rename from examples/dfp/v201411/inventory_service/update_ad_units.py rename to examples/dfp/v201511/inventory_service/update_ad_units.py index 96258bb0..3c8bdf43 100755 --- a/examples/dfp/v201411/inventory_service/update_ad_units.py +++ b/examples/dfp/v201511/inventory_service/update_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201411') + inventory_service = client.GetService('InventoryService', version='v201511') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201511/label_service/__init__.py b/examples/dfp/v201511/label_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/label_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/label_service/create_labels.py b/examples/dfp/v201511/label_service/create_labels.py similarity index 96% rename from examples/dfp/v201411/label_service/create_labels.py rename to examples/dfp/v201511/label_service/create_labels.py index 77876fb6..62bc0c81 100755 --- a/examples/dfp/v201411/label_service/create_labels.py +++ b/examples/dfp/v201511/label_service/create_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201411') + label_service = client.GetService('LabelService', version='v201511') # Create label objects. labels = [] diff --git a/examples/dfp/v201411/label_service/deactivate_labels.py b/examples/dfp/v201511/label_service/deactivate_labels.py similarity index 97% rename from examples/dfp/v201411/label_service/deactivate_labels.py rename to examples/dfp/v201511/label_service/deactivate_labels.py index 5ffd6659..0ef77133 100755 --- a/examples/dfp/v201411/label_service/deactivate_labels.py +++ b/examples/dfp/v201511/label_service/deactivate_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201411') + label_service = client.GetService('LabelService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/label_service/get_all_labels.py b/examples/dfp/v201511/label_service/get_all_labels.py similarity index 96% rename from examples/dfp/v201411/label_service/get_all_labels.py rename to examples/dfp/v201511/label_service/get_all_labels.py index 7ad49239..7d662ee5 100755 --- a/examples/dfp/v201411/label_service/get_all_labels.py +++ b/examples/dfp/v201511/label_service/get_all_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201411') + label_service = client.GetService('LabelService', version='v201511') # Create statement to get all labels statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/label_service/get_labels_by_statement.py b/examples/dfp/v201511/label_service/get_labels_by_statement.py similarity index 96% rename from examples/dfp/v201411/label_service/get_labels_by_statement.py rename to examples/dfp/v201511/label_service/get_labels_by_statement.py index 6f7fcc39..b0696743 100755 --- a/examples/dfp/v201411/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201511/label_service/get_labels_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201411') + label_service = client.GetService('LabelService', version='v201511') # Create statement to get all labels statement = dfp.FilterStatement('ORDER BY name') diff --git a/examples/dfp/v201411/label_service/update_labels.py b/examples/dfp/v201511/label_service/update_labels.py similarity index 97% rename from examples/dfp/v201411/label_service/update_labels.py rename to examples/dfp/v201511/label_service/update_labels.py index e62887ae..ad428db9 100755 --- a/examples/dfp/v201411/label_service/update_labels.py +++ b/examples/dfp/v201511/label_service/update_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201411') + label_service = client.GetService('LabelService', version='v201511') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201511/line_item_creative_association_service/__init__.py b/examples/dfp/v201511/line_item_creative_association_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/line_item_creative_association_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/line_item_creative_association_service/create_licas.py b/examples/dfp/v201511/line_item_creative_association_service/create_licas.py similarity index 93% rename from examples/dfp/v201411/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201511/line_item_creative_association_service/create_licas.py index b63ca262..b76ef132 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201511/line_item_creative_association_service/create_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201411') + 'LineItemCreativeAssociationService', version='v201511') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201511/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201511/line_item_creative_association_service/deactivate_licas.py index c3b0f645..ab7d3532 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201511/line_item_creative_association_service/deactivate_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201411') + 'LineItemCreativeAssociationService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201511/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201511/line_item_creative_association_service/get_all_licas.py index 617cd409..a9beaf0b 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201511/line_item_creative_association_service/get_all_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201411') + 'LineItemCreativeAssociationService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201511/line_item_creative_association_service/get_licas_by_statement.py similarity index 94% rename from examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py rename to examples/dfp/v201511/line_item_creative_association_service/get_licas_by_statement.py index fbc7b723..28f3f3e6 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201511/line_item_creative_association_service/get_licas_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201411') + 'LineItemCreativeAssociationService', version='v201511') # Create statement object to only select LICAs for the given line item id. values = [{ diff --git a/examples/dfp/v201411/line_item_creative_association_service/update_licas.py b/examples/dfp/v201511/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/dfp/v201411/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201511/line_item_creative_association_service/update_licas.py index 69280916..7ae15ce2 100755 --- a/examples/dfp/v201411/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201511/line_item_creative_association_service/update_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201411') + 'LineItemCreativeAssociationService', version='v201511') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201511/line_item_service/__init__.py b/examples/dfp/v201511/line_item_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/line_item_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/line_item_service/activate_line_items.py b/examples/dfp/v201511/line_item_service/activate_line_items.py similarity index 97% rename from examples/dfp/v201411/line_item_service/activate_line_items.py rename to examples/dfp/v201511/line_item_service/activate_line_items.py index a820d61a..279b317a 100755 --- a/examples/dfp/v201411/line_item_service/activate_line_items.py +++ b/examples/dfp/v201511/line_item_service/activate_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/line_item_service/create_line_items.py b/examples/dfp/v201511/line_item_service/create_line_items.py similarity index 97% rename from examples/dfp/v201411/line_item_service/create_line_items.py rename to examples/dfp/v201511/line_item_service/create_line_items.py index 81dd730d..8b3e90c2 100755 --- a/examples/dfp/v201411/line_item_service/create_line_items.py +++ b/examples/dfp/v201511/line_item_service/create_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # Create line item objects. line_items = [] @@ -135,7 +135,8 @@ def main(client, order_id, targeted_placement_ids): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'costType': 'CPM', 'costPerUnit': { diff --git a/examples/dfp/v201411/line_item_service/create_video_line_item.py b/examples/dfp/v201511/line_item_service/create_video_line_item.py similarity index 80% rename from examples/dfp/v201411/line_item_service/create_video_line_item.py rename to examples/dfp/v201511/line_item_service/create_video_line_item.py index 20ceea82..0c5cf526 100755 --- a/examples/dfp/v201411/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201511/line_item_service/create_video_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,40 +34,30 @@ ORDER_ID = 'INSERT_ORDER_ID_HERE' TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE' -# Set the custom targeting key ID and value ID representing the metadata on the -# content to target. This would typically be a key representing a 'genre' and -# a value representing something like 'comedy'. -CONTENT_CUSTOM_TARGETING_KEY_ID = 'INSERT_CONTENT_CUSTOM_TARGETING_KEY_ID_HERE' +# Set the custom targeting value ID representing the metadata +# on the content to target. This would typically be from a key representing +# a "genre" and the value representing something like "comedy". The value +# must be from a key in a content metadata key hierarchy. CONTENT_CUSTOM_TARGETING_VALUE_ID = \ 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE' def main(client, order_id, targeted_video_ad_unit_id, - content_custom_targeting_key_id, content_custom_targeting_value_id): + content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') - - # create custom criteria for the content metadata targeting. - custom_criteria = { - 'xsi_type': 'CustomCriteria', - 'keyId': content_custom_targeting_key_id, - 'valueIds': [content_custom_targeting_value_id], - 'operator': 'IS' - } - - # Create the custom criteria set. - top_set = { - 'xsi_type': 'CustomCriteriaSet', - 'logicalOperator': 'OR', - 'children': [custom_criteria] - } + line_item_service = client.GetService('LineItemService', version='v201511') # Create line item object. line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, 'targeting': { - 'customTargeting': top_set, + 'contentTargeting': { + 'targetedContentMetadata': [ + {'customTargetingValueIds': [ + content_custom_targeting_value_id]} + ] + }, 'inventoryTargeting': { 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id, 'includeDescendants': 'true'}] @@ -116,7 +106,8 @@ def main(client, order_id, targeted_video_ad_unit_id, }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'costType': 'CPM', 'costPerUnit': { @@ -146,4 +137,4 @@ def main(client, order_id, targeted_video_ad_unit_id, # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, - CONTENT_CUSTOM_TARGETING_KEY_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID) + CONTENT_CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201411/line_item_service/get_all_line_items.py b/examples/dfp/v201511/line_item_service/get_all_line_items.py similarity index 96% rename from examples/dfp/v201411/line_item_service/get_all_line_items.py rename to examples/dfp/v201511/line_item_service/get_all_line_items.py index ea35b3cf..4d446ab6 100755 --- a/examples/dfp/v201411/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201511/line_item_service/get_all_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201511/line_item_service/get_line_items_by_statement.py similarity index 97% rename from examples/dfp/v201411/line_item_service/get_line_items_by_statement.py rename to examples/dfp/v201511/line_item_service/get_line_items_by_statement.py index 9cedbbbd..587e626e 100755 --- a/examples/dfp/v201411/line_item_service/get_line_items_by_statement.py +++ b/examples/dfp/v201511/line_item_service/get_line_items_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # Create statement object to only select line items that need creatives from a # given order. diff --git a/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201511/line_item_service/get_recently_updated_line_items.py similarity index 97% rename from examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201511/line_item_service/get_recently_updated_line_items.py index 3abce181..193cdcbd 100755 --- a/examples/dfp/v201411/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201511/line_item_service/get_recently_updated_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # Create statement object to only select line items belonging to the order and # have been modified in the last 3 days. diff --git a/examples/dfp/v201411/line_item_service/target_custom_criteria.py b/examples/dfp/v201511/line_item_service/target_custom_criteria.py similarity index 98% rename from examples/dfp/v201411/line_item_service/target_custom_criteria.py rename to examples/dfp/v201511/line_item_service/target_custom_criteria.py index d3dd59cb..bc6d2cad 100755 --- a/examples/dfp/v201411/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201511/line_item_service/target_custom_criteria.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -39,7 +39,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201411/line_item_service/update_line_items.py b/examples/dfp/v201511/line_item_service/update_line_items.py similarity index 97% rename from examples/dfp/v201411/line_item_service/update_line_items.py rename to examples/dfp/v201511/line_item_service/update_line_items.py index 8bd2a780..695145d3 100755 --- a/examples/dfp/v201411/line_item_service/update_line_items.py +++ b/examples/dfp/v201511/line_item_service/update_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201511/network_service/__init__.py b/examples/dfp/v201511/network_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/network_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/network_service/get_all_networks.py b/examples/dfp/v201511/network_service/get_all_networks.py similarity index 95% rename from examples/dfp/v201411/network_service/get_all_networks.py rename to examples/dfp/v201511/network_service/get_all_networks.py index cb631a5c..867c9319 100755 --- a/examples/dfp/v201411/network_service/get_all_networks.py +++ b/examples/dfp/v201511/network_service/get_all_networks.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201411') + network_service = client.GetService('NetworkService', version='v201511') # Get all networks that you have access to with the current login credentials. networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201411/network_service/get_current_network.py b/examples/dfp/v201511/network_service/get_current_network.py similarity index 95% rename from examples/dfp/v201411/network_service/get_current_network.py rename to examples/dfp/v201511/network_service/get_current_network.py index 56f7395d..fd821e73 100755 --- a/examples/dfp/v201411/network_service/get_current_network.py +++ b/examples/dfp/v201511/network_service/get_current_network.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201411') + network_service = client.GetService('NetworkService', version='v201511') # Get the current network. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201411/network_service/make_test_network.py b/examples/dfp/v201511/network_service/make_test_network.py similarity index 96% rename from examples/dfp/v201411/network_service/make_test_network.py rename to examples/dfp/v201511/network_service/make_test_network.py index 11419e85..ff937e8d 100755 --- a/examples/dfp/v201411/network_service/make_test_network.py +++ b/examples/dfp/v201511/network_service/make_test_network.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201411') + network_service = client.GetService('NetworkService', version='v201511') # Create a test network. network = network_service.MakeTestNetwork() diff --git a/examples/dfp/v201511/order_service/__init__.py b/examples/dfp/v201511/order_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/order_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/order_service/approve_orders.py b/examples/dfp/v201511/order_service/approve_orders.py similarity index 97% rename from examples/dfp/v201411/order_service/approve_orders.py rename to examples/dfp/v201511/order_service/approve_orders.py index 8ef188df..aee7a64b 100755 --- a/examples/dfp/v201411/order_service/approve_orders.py +++ b/examples/dfp/v201511/order_service/approve_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201411') + order_service = client.GetService('OrderService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/order_service/create_orders.py b/examples/dfp/v201511/order_service/create_orders.py similarity index 96% rename from examples/dfp/v201411/order_service/create_orders.py rename to examples/dfp/v201511/order_service/create_orders.py index bad34098..4d968a15 100755 --- a/examples/dfp/v201411/order_service/create_orders.py +++ b/examples/dfp/v201511/order_service/create_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201411') + order_service = client.GetService('OrderService', version='v201511') # Create order objects. orders = [] diff --git a/examples/dfp/v201411/order_service/get_all_orders.py b/examples/dfp/v201511/order_service/get_all_orders.py similarity index 96% rename from examples/dfp/v201411/order_service/get_all_orders.py rename to examples/dfp/v201511/order_service/get_all_orders.py index be89dad4..278de5d3 100755 --- a/examples/dfp/v201411/order_service/get_all_orders.py +++ b/examples/dfp/v201511/order_service/get_all_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201411') + order_service = client.GetService('OrderService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/order_service/get_orders_by_statement.py b/examples/dfp/v201511/order_service/get_orders_by_statement.py similarity index 96% rename from examples/dfp/v201411/order_service/get_orders_by_statement.py rename to examples/dfp/v201511/order_service/get_orders_by_statement.py index 5f4cd895..8f3daad7 100755 --- a/examples/dfp/v201411/order_service/get_orders_by_statement.py +++ b/examples/dfp/v201511/order_service/get_orders_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201411') + order_service = client.GetService('OrderService', version='v201511') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201411/order_service/update_orders.py b/examples/dfp/v201511/order_service/update_orders.py similarity index 97% rename from examples/dfp/v201411/order_service/update_orders.py rename to examples/dfp/v201511/order_service/update_orders.py index cb943ac7..7fab14ac 100755 --- a/examples/dfp/v201411/order_service/update_orders.py +++ b/examples/dfp/v201511/order_service/update_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201411') + order_service = client.GetService('OrderService', version='v201511') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201411/placement_service/create_placements.py b/examples/dfp/v201511/placement_service/create_placements.py similarity index 97% rename from examples/dfp/v201411/placement_service/create_placements.py rename to examples/dfp/v201511/placement_service/create_placements.py index 5bdb6f78..0ab286c5 100755 --- a/examples/dfp/v201411/placement_service/create_placements.py +++ b/examples/dfp/v201511/placement_service/create_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201411') - inventory_service = client.GetService('InventoryService', version='v201411') + placement_service = client.GetService('PlacementService', version='v201511') + inventory_service = client.GetService('InventoryService', version='v201511') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201411/placement_service/deactivate_placements.py b/examples/dfp/v201511/placement_service/deactivate_placements.py similarity index 96% rename from examples/dfp/v201411/placement_service/deactivate_placements.py rename to examples/dfp/v201511/placement_service/deactivate_placements.py index 6ba63597..4bd94f4c 100755 --- a/examples/dfp/v201411/placement_service/deactivate_placements.py +++ b/examples/dfp/v201511/placement_service/deactivate_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201411') + placement_service = client.GetService('PlacementService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/placement_service/get_all_placements.py b/examples/dfp/v201511/placement_service/get_all_placements.py similarity index 96% rename from examples/dfp/v201411/placement_service/get_all_placements.py rename to examples/dfp/v201511/placement_service/get_all_placements.py index 41d50b10..8a9273c1 100755 --- a/examples/dfp/v201411/placement_service/get_all_placements.py +++ b/examples/dfp/v201511/placement_service/get_all_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201411') + placement_service = client.GetService('PlacementService', version='v201511') # Create statement to fetch all placements. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/placement_service/get_placements_by_statement.py b/examples/dfp/v201511/placement_service/get_placements_by_statement.py similarity index 96% rename from examples/dfp/v201411/placement_service/get_placements_by_statement.py rename to examples/dfp/v201511/placement_service/get_placements_by_statement.py index 99a3031c..69e649bf 100755 --- a/examples/dfp/v201411/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201511/placement_service/get_placements_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201411') + placement_service = client.GetService('PlacementService', version='v201511') # Create a statement to only select active placements. values = [{ diff --git a/examples/dfp/v201411/placement_service/update_placements.py b/examples/dfp/v201511/placement_service/update_placements.py similarity index 97% rename from examples/dfp/v201411/placement_service/update_placements.py rename to examples/dfp/v201511/placement_service/update_placements.py index c6b0b100..074c4187 100755 --- a/examples/dfp/v201411/placement_service/update_placements.py +++ b/examples/dfp/v201511/placement_service/update_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201411') + placement_service = client.GetService('PlacementService', version='v201511') # Create query. values = [{ 'key': 'placementId', diff --git a/examples/dfp/v201511/premium_rate_service/__init__.py b/examples/dfp/v201511/premium_rate_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/premium_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/premium_rate_service/create_premium_rates.py b/examples/dfp/v201511/premium_rate_service/create_premium_rates.py similarity index 95% rename from examples/dfp/v201411/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201511/premium_rate_service/create_premium_rates.py index 1945e22c..74ca9a90 100755 --- a/examples/dfp/v201411/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201511/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201411') + version='v201511') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { @@ -72,7 +72,7 @@ def main(client, rate_card_id): for premium_rate in premium_rates: print ('A premium rate for \'%s\' was added to the rate card with ID' ' of \'%s\'.\n' - % (premium_rate['premiumFeature']['PremiumFeature.Type'], + % (dfp.DfpClassType(premium_rate['premiumFeature']), premium_rate['id'])) if __name__ == '__main__': diff --git a/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201511/premium_rate_service/get_all_premium_rates.py similarity index 92% rename from examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201511/premium_rate_service/get_all_premium_rates.py index 6a695b2e..c26788fc 100755 --- a/examples/dfp/v201411/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201511/premium_rate_service/get_all_premium_rates.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201411') + version='v201511') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') @@ -43,7 +43,7 @@ def main(client): print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' ' rate card with ID \'%s\' was found.\n' % ( premium_rate['id'], - premium_rate['premiumFeature']['PremiumFeature.Type'], + dfp.DfpClassType(premium_rate['premiumFeature']), premium_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: diff --git a/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201511/premium_rate_service/get_premium_rates_for_a_rate_card.py similarity index 93% rename from examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py rename to examples/dfp/v201511/premium_rate_service/get_premium_rates_for_a_rate_card.py index 2b02c375..4ecbc43a 100755 --- a/examples/dfp/v201411/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201511/premium_rate_service/get_premium_rates_for_a_rate_card.py @@ -30,7 +30,7 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201411') + version='v201511') # Create statement object to select a single proposal by an ID. values = [{ @@ -53,7 +53,7 @@ def main(client, rate_card_id): print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' ' rate card with ID \'%s\' was found.\n' % ( premium_rate['id'], - premium_rate['premiumFeature']['PremiumFeature.Type'], + dfp.DfpClassType(premium_rate['premiumFeature']), premium_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: diff --git a/examples/dfp/v201411/premium_rate_service/update_premium_rates.py b/examples/dfp/v201511/premium_rate_service/update_premium_rates.py similarity index 97% rename from examples/dfp/v201411/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201511/premium_rate_service/update_premium_rates.py index 6d6e630b..4321181c 100755 --- a/examples/dfp/v201411/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201511/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201411') + version='v201511') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201511/product_service/__init__.py b/examples/dfp/v201511/product_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/product_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/product_service/get_all_products.py b/examples/dfp/v201511/product_service/get_all_products.py similarity index 96% rename from examples/dfp/v201411/product_service/get_all_products.py rename to examples/dfp/v201511/product_service/get_all_products.py index 629592ae..2df37979 100755 --- a/examples/dfp/v201411/product_service/get_all_products.py +++ b/examples/dfp/v201511/product_service/get_all_products.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201411') + product_service = client.GetService('ProductService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201411/product_service/get_products_for_product_template.py b/examples/dfp/v201511/product_service/get_products_for_product_template.py similarity index 96% rename from examples/dfp/v201411/product_service/get_products_for_product_template.py rename to examples/dfp/v201511/product_service/get_products_for_product_template.py index dca44c56..bdc173b3 100755 --- a/examples/dfp/v201411/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201511/product_service/get_products_for_product_template.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201411') + product_service = client.GetService('ProductService', version='v201511') # Create a filter statement to select only products created from a single # a product template. diff --git a/examples/dfp/v201411/product_service/update_products.py b/examples/dfp/v201511/product_service/update_products.py similarity index 97% rename from examples/dfp/v201411/product_service/update_products.py rename to examples/dfp/v201511/product_service/update_products.py index 4d043a7f..5275cfe2 100755 --- a/examples/dfp/v201411/product_service/update_products.py +++ b/examples/dfp/v201511/product_service/update_products.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201411') + product_service = client.GetService('ProductService', version='v201511') # Create statement object to select a single product by an ID. values = [{ diff --git a/examples/dfp/v201511/product_template_service/__init__.py b/examples/dfp/v201511/product_template_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/product_template_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/product_template_service/activate_product_templates.py b/examples/dfp/v201511/product_template_service/activate_product_templates.py similarity index 97% rename from examples/dfp/v201411/product_template_service/activate_product_templates.py rename to examples/dfp/v201511/product_template_service/activate_product_templates.py index f3ec5ecd..54a96bb9 100755 --- a/examples/dfp/v201411/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201511/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201411') + 'ProductTemplateService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/product_template_service/create_product_templates.py b/examples/dfp/v201511/product_template_service/create_product_templates.py similarity index 82% rename from examples/dfp/v201411/product_template_service/create_product_templates.py rename to examples/dfp/v201511/product_template_service/create_product_templates.py index e88d6360..dfbe45e7 100755 --- a/examples/dfp/v201411/product_template_service/create_product_templates.py +++ b/examples/dfp/v201511/product_template_service/create_product_templates.py @@ -17,10 +17,8 @@ """This example creates a product template. To determine which product templates exist, run get_all_product_templates.py. - """ - import uuid # Import appropriate modules from the client library. @@ -30,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201411') + 'ProductTemplateService', version='v201511') network_service = client.GetService( - 'NetworkService', version='v201411') + 'NetworkService', version='v201511') # Create a product template. product_template = { @@ -45,6 +43,7 @@ def main(client): 'productType': 'DFP', 'rateType': 'CPM', 'roadblockingType': 'ONE_OR_MORE', + 'deliveryRateType': 'AS_FAST_AS_POSSIBLE', 'creativePlaceholders': [ { 'size': { @@ -60,17 +59,22 @@ def main(client): } ], 'lineItemType': 'STANDARD', - 'targeting': { - # Set browser targeting to Chrome. - 'browserTargeting': [ - { - 'browsers': [ - { - 'id': '500072' - } - ] + 'customizableAttributes': { + 'allowPlacementTargetingCustomization': True, + }, + 'builtInTargeting': { + 'technologyTargeting': { + # Set browser targeting to Chrome. + 'browserTargeting': { + { + 'browsers': [ + { + 'id': '500072' + } + ] + } } - ] + } }, 'productSegmentation': { 'geoSegment': { diff --git a/examples/dfp/v201411/product_template_service/get_all_product_templates.py b/examples/dfp/v201511/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201411/product_template_service/get_all_product_templates.py rename to examples/dfp/v201511/product_template_service/get_all_product_templates.py index 21c3eb78..338d2ccf 100755 --- a/examples/dfp/v201411/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201511/product_template_service/get_all_product_templates.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201411') + 'ProductTemplateService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201511/product_template_service/get_sponsorship_product_templates.py similarity index 97% rename from examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201511/product_template_service/get_sponsorship_product_templates.py index ca082787..7a015232 100755 --- a/examples/dfp/v201411/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201511/product_template_service/get_sponsorship_product_templates.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201411') + 'ProductTemplateService', version='v201511') # Create a statement to select all sponsorship product templates. values = [{ diff --git a/examples/dfp/v201411/product_template_service/update_product_templates.py b/examples/dfp/v201511/product_template_service/update_product_templates.py similarity index 94% rename from examples/dfp/v201411/product_template_service/update_product_templates.py rename to examples/dfp/v201511/product_template_service/update_product_templates.py index 63e416ed..e1d855b8 100755 --- a/examples/dfp/v201411/product_template_service/update_product_templates.py +++ b/examples/dfp/v201511/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201411') + 'ProductTemplateService', version='v201511') # Create a statement to select a single product template by ID. values = [{ @@ -57,7 +57,7 @@ def main(client, product_template_id): } try: - targeting = product_template['targeting'] + targeting = product_template['builtInTargeting'] if 'geoTargeting' in targeting: geo_targeting = targeting['geoTargeting'] @@ -71,7 +71,7 @@ def main(client, product_template_id): 'targetedLocations': [location] } except KeyError: - product_template['targeting'] = { + product_template['builtInTargeting'] = { 'geoTargeting': { 'targetedLocations': [location] } diff --git a/examples/dfp/v201511/proposal_line_item_service/__init__.py b/examples/dfp/v201511/proposal_line_item_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/proposal_line_item_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201511/proposal_line_item_service/archive_proposal_line_items.py similarity index 96% rename from examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201511/proposal_line_item_service/archive_proposal_line_items.py index 7dec1361..3ff003ca 100755 --- a/examples/dfp/v201411/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201511/proposal_line_item_service/archive_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201411') + 'ProposalLineItemService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201511/proposal_line_item_service/create_proposal_line_items.py similarity index 95% rename from examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201511/proposal_line_item_service/create_proposal_line_items.py index 9551bc74..c8d78a2e 100755 --- a/examples/dfp/v201411/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201511/proposal_line_item_service/create_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -41,8 +41,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201411') - network_service = client.GetService('NetworkService', version='v201411') + 'ProposalLineItemService', version='v201511') + network_service = client.GetService('NetworkService', version='v201511') # Get the root ad unit to target. root_ad_unit_id = ( @@ -79,7 +79,8 @@ def main(client, proposal_id, product_id, rate_card_id): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'deliveryRateType': 'EVENLY', 'creativeRotationType': 'OPTIMIZED', diff --git a/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201511/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201511/proposal_line_item_service/get_all_proposal_line_items.py index dbfe9db9..699cd596 100755 --- a/examples/dfp/v201411/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201511/proposal_line_item_service/get_all_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201411') + 'ProposalLineItemService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201511/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 96% rename from examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201511/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 9cdaca1f..f725625a 100755 --- a/examples/dfp/v201411/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201511/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( 'ProposalLineItemService', - version='v201411') + version='v201511') # Create statement object to only select proposal line items belonging to a # given proposal. diff --git a/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201511/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201511/proposal_line_item_service/update_proposal_line_items.py index fa16acf3..5d268a03 100755 --- a/examples/dfp/v201411/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201511/proposal_line_item_service/update_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201411') + 'ProposalLineItemService', version='v201511') # Create statement to select a proposal line item. values = [{ diff --git a/examples/dfp/v201511/proposal_service/__init__.py b/examples/dfp/v201511/proposal_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/proposal_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/proposal_service/create_proposals.py b/examples/dfp/v201511/proposal_service/create_proposals.py similarity index 97% rename from examples/dfp/v201411/proposal_service/create_proposals.py rename to examples/dfp/v201511/proposal_service/create_proposals.py index 13683f61..b4dfa293 100755 --- a/examples/dfp/v201411/proposal_service/create_proposals.py +++ b/examples/dfp/v201511/proposal_service/create_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,8 +33,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201411') - network_service = client.GetService('NetworkService', version='v201411') + proposal_service = client.GetService('ProposalService', version='v201511') + network_service = client.GetService('NetworkService', version='v201511') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201411/proposal_service/get_all_proposals.py b/examples/dfp/v201511/proposal_service/get_all_proposals.py similarity index 96% rename from examples/dfp/v201411/proposal_service/get_all_proposals.py rename to examples/dfp/v201511/proposal_service/get_all_proposals.py index e95ca255..7763de74 100755 --- a/examples/dfp/v201411/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201511/proposal_service/get_all_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201411') + proposal_service = client.GetService('ProposalService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201511/proposal_service/get_proposals_by_statement.py similarity index 96% rename from examples/dfp/v201411/proposal_service/get_proposals_by_statement.py rename to examples/dfp/v201511/proposal_service/get_proposals_by_statement.py index c8fba63c..8a5fb08c 100755 --- a/examples/dfp/v201411/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201511/proposal_service/get_proposals_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201411') + proposal_service = client.GetService('ProposalService', version='v201511') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201511/proposal_service/submit_proposals_for_approval.py similarity index 97% rename from examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201511/proposal_service/submit_proposals_for_approval.py index 0d0e7689..9ac06a60 100755 --- a/examples/dfp/v201411/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201511/proposal_service/submit_proposals_for_approval.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201411') + proposal_service = client.GetService('ProposalService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/proposal_service/update_proposals.py b/examples/dfp/v201511/proposal_service/update_proposals.py similarity index 97% rename from examples/dfp/v201411/proposal_service/update_proposals.py rename to examples/dfp/v201511/proposal_service/update_proposals.py index e24ea866..3ca6466d 100755 --- a/examples/dfp/v201411/proposal_service/update_proposals.py +++ b/examples/dfp/v201511/proposal_service/update_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201411') + proposal_service = client.GetService('ProposalService', version='v201511') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201511/publisher_query_language_service/__init__.py b/examples/dfp/v201511/publisher_query_language_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/publisher_query_language_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201511/publisher_query_language_service/fetch_match_tables.py similarity index 93% rename from examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201511/publisher_query_language_service/fetch_match_tables.py index d5cfd085..d8431b90 100755 --- a/examples/dfp/v201411/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201511/publisher_query_language_service/fetch_match_tables.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201411') + report_downloader = client.GetDataDownloader(version='v201511') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201511/publisher_query_language_service/get_geo_targets.py similarity index 92% rename from examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py rename to examples/dfp/v201511/publisher_query_language_service/get_geo_targets.py index 194dd0d3..5403cab4 100755 --- a/examples/dfp/v201411/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201511/publisher_query_language_service/get_geo_targets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -20,7 +20,7 @@ 'Postal_Code', and 'DMA_Region' (i.e. Metro). A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201411/PublisherQueryLanguageService +https://developers.google.com/doubleclick-publishers/docs/reference/v201511/PublisherQueryLanguageService """ @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201411') + report_downloader = client.GetDataDownloader(version='v201511') output_file = tempfile.NamedTemporaryFile( prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201511/publisher_query_language_service/get_line_items_named_like.py similarity index 93% rename from examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py rename to examples/dfp/v201511/publisher_query_language_service/get_line_items_named_like.py index 7eabb7f1..736d3f1d 100755 --- a/examples/dfp/v201411/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201511/publisher_query_language_service/get_line_items_named_like.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201411') + report_downloader = client.GetDataDownloader(version='v201511') output_file = tempfile.NamedTemporaryFile( prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201511/rate_card_service/__init__.py b/examples/dfp/v201511/rate_card_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/rate_card_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201511/rate_card_service/get_all_rate_cards.py similarity index 96% rename from examples/dfp/v201411/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201511/rate_card_service/get_all_rate_cards.py index 4544c625..72252033 100755 --- a/examples/dfp/v201411/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201511/rate_card_service/get_all_rate_cards.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201411') + rate_card_service = client.GetService('RateCardService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201511/rate_card_service/get_rate_cards_priced_with_currency.py similarity index 96% rename from examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py rename to examples/dfp/v201511/rate_card_service/get_rate_cards_priced_with_currency.py index 47a804df..6aa39088 100755 --- a/examples/dfp/v201411/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201511/rate_card_service/get_rate_cards_priced_with_currency.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201411') + rate_card_service = client.GetService('RateCardService', version='v201511') # Create a statement to get all rate cards using USD as currency. values = [{ diff --git a/examples/dfp/v201511/report_service/__init__.py b/examples/dfp/v201511/report_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/report_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/report_service/run_delivery_report.py b/examples/dfp/v201511/report_service/run_delivery_report.py similarity index 79% rename from examples/dfp/v201411/report_service/run_delivery_report.py rename to examples/dfp/v201511/report_service/run_delivery_report.py index 10352d58..f8bf5fc5 100755 --- a/examples/dfp/v201411/report_service/run_delivery_report.py +++ b/examples/dfp/v201511/report_service/run_delivery_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -18,6 +18,8 @@ website with additional attributes and can filter to include just one order. """ +from datetime import datetime +from datetime import timedelta import tempfile # Import appropriate modules from the client library. @@ -39,6 +41,10 @@ def main(client, order_id): filter_statement = {'query': 'WHERE ORDER_ID = :id', 'values': values} + # Set the start and end dates of the report to run (past 8 days). + end_date = datetime.now() + start_date = end_date - timedelta(days=8) + # Create report job. report_job = { 'reportQuery': { @@ -49,12 +55,18 @@ def main(client, order_id): 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'LAST_MONTH' + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': {'year': start_date.year, + 'month': start_date.month, + 'day': start_date.day}, + 'endDate': {'year': end_date.year, + 'month': end_date.month, + 'day': end_date.day} } } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201411') + report_downloader = client.GetDataDownloader(version='v201511') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201411/report_service/run_inventory_report.py b/examples/dfp/v201511/report_service/run_inventory_report.py similarity index 95% rename from examples/dfp/v201411/report_service/run_inventory_report.py rename to examples/dfp/v201511/report_service/run_inventory_report.py index ad2c6c1f..d6f304a2 100755 --- a/examples/dfp/v201411/report_service/run_inventory_report.py +++ b/examples/dfp/v201511/report_service/run_inventory_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,9 +27,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201411') + network_service = client.GetService('NetworkService', version='v201511') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201411') + report_downloader = client.GetDataDownloader(version='v201511') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201411/report_service/run_reach_report.py b/examples/dfp/v201511/report_service/run_reach_report.py similarity index 94% rename from examples/dfp/v201411/report_service/run_reach_report.py rename to examples/dfp/v201511/report_service/run_reach_report.py index b3b86285..dfeef10a 100755 --- a/examples/dfp/v201411/report_service/run_reach_report.py +++ b/examples/dfp/v201511/report_service/run_reach_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201411') + report_downloader = client.GetDataDownloader(version='v201511') # Create report job. report_job = { diff --git a/examples/dfp/v201411/report_service/run_report_with_custom_fields.py b/examples/dfp/v201511/report_service/run_report_with_custom_fields.py similarity index 96% rename from examples/dfp/v201411/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201511/report_service/run_report_with_custom_fields.py index 1e4c17f5..b97a7a40 100755 --- a/examples/dfp/v201411/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201511/report_service/run_report_with_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -30,9 +30,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201411') + line_item_service = client.GetService('LineItemService', version='v201511') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201411') + report_downloader = client.GetDataDownloader(version='v201511') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201411/report_service/run_sales_report.py b/examples/dfp/v201511/report_service/run_sales_report.py similarity index 94% rename from examples/dfp/v201411/report_service/run_sales_report.py rename to examples/dfp/v201511/report_service/run_sales_report.py index d4265342..b3ab5722 100755 --- a/examples/dfp/v201411/report_service/run_sales_report.py +++ b/examples/dfp/v201511/report_service/run_sales_report.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201411') + report_downloader = client.GetDataDownloader(version='v201511') # Create report job. report_job = { diff --git a/examples/dfp/v201511/suggested_ad_unit_service/__init__.py b/examples/dfp/v201511/suggested_ad_unit_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/suggested_ad_unit_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201511/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 96% rename from examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201511/suggested_ad_unit_service/approve_all_suggested_ad_units.py index b785813a..ae8c83ff 100755 --- a/examples/dfp/v201411/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201511/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201411') + 'SuggestedAdUnitService', version='v201511') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201511/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201511/suggested_ad_unit_service/get_all_suggested_ad_units.py index 6b37b047..8a1709a7 100755 --- a/examples/dfp/v201411/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201511/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201411') + 'SuggestedAdUnitService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201511/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py similarity index 94% rename from examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py rename to examples/dfp/v201511/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py index faa6c3ca..c7f27618 100755 --- a/examples/dfp/v201411/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201511/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201411') + 'SuggestedAdUnitService', version='v201511') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201511/team_service/__init__.py b/examples/dfp/v201511/team_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/team_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/team_service/create_teams.py b/examples/dfp/v201511/team_service/create_teams.py similarity index 93% rename from examples/dfp/v201411/team_service/create_teams.py rename to examples/dfp/v201511/team_service/create_teams.py index c6e22117..ac17b297 100755 --- a/examples/dfp/v201411/team_service/create_teams.py +++ b/examples/dfp/v201511/team_service/create_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201411') + team_service = client.GetService('TeamService', version='v201511') # Create team objects. teams = [] diff --git a/examples/dfp/v201411/team_service/get_all_teams.py b/examples/dfp/v201511/team_service/get_all_teams.py similarity index 93% rename from examples/dfp/v201411/team_service/get_all_teams.py rename to examples/dfp/v201511/team_service/get_all_teams.py index e174ec6b..25811c84 100755 --- a/examples/dfp/v201411/team_service/get_all_teams.py +++ b/examples/dfp/v201511/team_service/get_all_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201411') + team_service = client.GetService('TeamService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/team_service/get_teams_by_statement.py b/examples/dfp/v201511/team_service/get_teams_by_statement.py similarity index 94% rename from examples/dfp/v201411/team_service/get_teams_by_statement.py rename to examples/dfp/v201511/team_service/get_teams_by_statement.py index 2d3a8fd2..558fc62d 100755 --- a/examples/dfp/v201411/team_service/get_teams_by_statement.py +++ b/examples/dfp/v201511/team_service/get_teams_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -34,7 +34,7 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201411') + team_service = client.GetService('TeamService', version='v201511') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201411/team_service/update_teams.py b/examples/dfp/v201511/team_service/update_teams.py similarity index 95% rename from examples/dfp/v201411/team_service/update_teams.py rename to examples/dfp/v201511/team_service/update_teams.py index 33d2b2eb..91391277 100755 --- a/examples/dfp/v201411/team_service/update_teams.py +++ b/examples/dfp/v201511/team_service/update_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -36,7 +36,7 @@ def main(client, ad_unit_id, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201411') + team_service = client.GetService('TeamService', version='v201511') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201511/user_service/__init__.py b/examples/dfp/v201511/user_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/user_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/user_service/create_users.py b/examples/dfp/v201511/user_service/create_users.py similarity index 93% rename from examples/dfp/v201411/user_service/create_users.py rename to examples/dfp/v201511/user_service/create_users.py index 2ee6dce5..3c46eeea 100755 --- a/examples/dfp/v201411/user_service/create_users.py +++ b/examples/dfp/v201511/user_service/create_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -28,7 +28,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201411') + user_service = client.GetService('UserService', version='v201511') # Create user objects. users = [ diff --git a/examples/dfp/v201411/user_service/deactivate_users.py b/examples/dfp/v201511/user_service/deactivate_users.py similarity index 95% rename from examples/dfp/v201411/user_service/deactivate_users.py rename to examples/dfp/v201511/user_service/deactivate_users.py index c45cea0f..da72e67b 100755 --- a/examples/dfp/v201411/user_service/deactivate_users.py +++ b/examples/dfp/v201511/user_service/deactivate_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201411') + user_service = client.GetService('UserService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/user_service/get_all_roles.py b/examples/dfp/v201511/user_service/get_all_roles.py similarity index 91% rename from examples/dfp/v201411/user_service/get_all_roles.py rename to examples/dfp/v201511/user_service/get_all_roles.py index 55a9e2e0..6b391d7c 100755 --- a/examples/dfp/v201411/user_service/get_all_roles.py +++ b/examples/dfp/v201511/user_service/get_all_roles.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201411') + user_service = client.GetService('UserService', version='v201511') # Get all roles. roles = user_service.getAllRoles() diff --git a/examples/dfp/v201411/user_service/get_all_users.py b/examples/dfp/v201511/user_service/get_all_users.py similarity index 92% rename from examples/dfp/v201411/user_service/get_all_users.py rename to examples/dfp/v201511/user_service/get_all_users.py index b79ce84d..abdca1a0 100755 --- a/examples/dfp/v201411/user_service/get_all_users.py +++ b/examples/dfp/v201511/user_service/get_all_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201411') + user_service = client.GetService('UserService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/user_service/get_current_user.py b/examples/dfp/v201511/user_service/get_current_user.py similarity index 90% rename from examples/dfp/v201411/user_service/get_current_user.py rename to examples/dfp/v201511/user_service/get_current_user.py index 92262660..475400de 100755 --- a/examples/dfp/v201411/user_service/get_current_user.py +++ b/examples/dfp/v201511/user_service/get_current_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201411') + user_service = client.GetService('UserService', version='v201511') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201411/user_service/get_users_by_statement.py b/examples/dfp/v201511/user_service/get_users_by_statement.py similarity index 93% rename from examples/dfp/v201411/user_service/get_users_by_statement.py rename to examples/dfp/v201511/user_service/get_users_by_statement.py index 55f159a2..6c65a97b 100755 --- a/examples/dfp/v201411/user_service/get_users_by_statement.py +++ b/examples/dfp/v201511/user_service/get_users_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201411') + user_service = client.GetService('UserService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/user_service/update_users.py b/examples/dfp/v201511/user_service/update_users.py similarity index 93% rename from examples/dfp/v201411/user_service/update_users.py rename to examples/dfp/v201511/user_service/update_users.py index 8347e77f..293bbb2c 100755 --- a/examples/dfp/v201411/user_service/update_users.py +++ b/examples/dfp/v201511/user_service/update_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -27,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201411') + user_service = client.GetService('UserService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201511/user_team_association_service/__init__.py b/examples/dfp/v201511/user_team_association_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/user_team_association_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201511/user_team_association_service/create_user_team_associations.py similarity index 95% rename from examples/dfp/v201411/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201511/user_team_association_service/create_user_team_associations.py index 70b463e9..e98d6a77 100755 --- a/examples/dfp/v201411/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201511/user_team_association_service/create_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201411') + 'UserTeamAssociationService', version='v201511') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201511/user_team_association_service/delete_user_team_associations.py similarity index 96% rename from examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201511/user_team_association_service/delete_user_team_associations.py index 13252a1d..7cca9b99 100755 --- a/examples/dfp/v201411/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201511/user_team_association_service/delete_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201411') + 'UserTeamAssociationService', version='v201511') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201511/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201511/user_team_association_service/get_all_user_team_associations.py index ea62a4c0..c0a92262 100755 --- a/examples/dfp/v201411/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201511/user_team_association_service/get_all_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201411') + 'UserTeamAssociationService', version='v201511') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201511/user_team_association_service/get_user_team_associations_for_user.py similarity index 95% rename from examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201511/user_team_association_service/get_user_team_associations_for_user.py index 0c125679..860f2c01 100755 --- a/examples/dfp/v201411/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201511/user_team_association_service/get_user_team_associations_for_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201411') + 'UserTeamAssociationService', version='v201511') # Create query. values = [{ diff --git a/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201511/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/dfp/v201411/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201511/user_team_association_service/update_user_team_associations.py index 90397738..d9863023 100755 --- a/examples/dfp/v201411/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201511/user_team_association_service/update_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201411') + 'UserTeamAssociationService', version='v201511') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201511/workflow_request_service/__init__.py b/examples/dfp/v201511/workflow_request_service/__init__.py new file mode 100755 index 00000000..a426ca48 --- /dev/null +++ b/examples/dfp/v201511/workflow_request_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2015 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. diff --git a/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201511/workflow_request_service/approve_workflow_approval_requests.py similarity index 92% rename from examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201511/workflow_request_service/approve_workflow_approval_requests.py index 7e9849ad..99b8c2bb 100755 --- a/examples/dfp/v201411/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201511/workflow_request_service/approve_workflow_approval_requests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201411') + version='v201511') # Create query. values = [ @@ -75,7 +75,8 @@ def main(client, proposal_id): ' approved.' % workflow_approval_request['id']) # Perform action. result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'ApproveWorkflowApprovalRequests'}, + {'xsi_type': 'ApproveWorkflowApprovalRequests', + 'comment': 'This workflow has now been approved for submission.'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: workflow_approval_requests_approved += int(result['numChanges']) diff --git a/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201511/workflow_request_service/get_workflow_approval_requests_by_statement.py similarity index 94% rename from examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py rename to examples/dfp/v201511/workflow_request_service/get_workflow_approval_requests_by_statement.py index 41574fd4..415fdd06 100755 --- a/examples/dfp/v201411/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201511/workflow_request_service/get_workflow_approval_requests_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201411') + version='v201511') # Create statement object to select all workflow approval requests. values = [{ diff --git a/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201511/workflow_request_service/get_workflow_external_condition_requests_by_statement.py similarity index 94% rename from examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py rename to examples/dfp/v201511/workflow_request_service/get_workflow_external_condition_requests_by_statement.py index 84a58ef8..dd697d6d 100755 --- a/examples/dfp/v201411/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201511/workflow_request_service/get_workflow_external_condition_requests_by_statement.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201411') + version='v201511') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201511/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 96% rename from examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201511/workflow_request_service/trigger_workflow_external_condition_requests.py index 74966b98..6fab09fb 100755 --- a/examples/dfp/v201411/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201511/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2014 Google Inc. All Rights Reserved. +# Copyright 2015 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. @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201411') + version='v201511') # Create query. values = [ diff --git a/googleads/adwords.py b/googleads/adwords.py index aba34710..81ad7187 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -14,9 +14,9 @@ """Client library for the AdWords API.""" - import io import os +import re import sys import urllib import urllib2 @@ -317,12 +317,23 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], return googleads.common.SudsServiceProxy( client, _AdWordsHeaderHandler(self, version)) + def GetBatchJobHelper(self): + """Returns a BatchJobHelper to work with the BatchJobService. + + This is a convenience method. It is functionally identical to calling + BatchJobHelper(adwords_client, version). + + Returns: + An initialized BatchJobHelper tied to this client. + """ + return BatchJobHelper(self) + def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=_DEFAULT_ENDPOINT): """Creates a downloader for AdWords reports. This is a convenience method. It is functionally identical to calling - ReportDownloader(adwords_client, version, server) + ReportDownloader(adwords_client, version, server). Args: [optional] @@ -340,7 +351,7 @@ def SetClientCustomerId(self, client_customer_id): """Change the client customer id used by the AdWordsClient instance. Args: - client_customer_id: str New Client Customer Id to use. + client_customer_id: str New Client Customer ID to use. """ self.client_customer_id = client_customer_id @@ -425,6 +436,175 @@ def GetReportDownloadHeaders(self, kwargs): return headers +class BatchJobHelper(object): + """A utility that simplifies working with the BatchJobService.""" + # Used to remove namespace from xsi:type Element attributes. + _ATTRIB_NAMESPACE_SUB = re.compile('ns[0-1]:') + _UPLOAD_REQUEST_BODY_TEMPLATE = """ +%s +""" + + def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1]): + """Initializes the BatchJobHelper. + + Args: + adwords_client: an initialized AdWordsClient. + version: a str indicating version of the AdWords API you intend to use. + This will be set to the latest version of AdWords by default. + """ + self.client = adwords_client + self._temporary_id = 0 # Used for temporary IDs in BatchJobService. + self._version = version + self._adwords_endpoint = ('https://adwords.google.com/api/adwords/cm/%s' % + self._version) + self._adwords_namespace = ('{%s}' % self._adwords_endpoint) + # Used to remove the AdWords namespace from Element tags. + self._tag_namespace_sub = re.compile(self._adwords_namespace) + + def GetId(self): + """Produces a distinct sequential ID for the BatchJobService. + + Returns: + A negative number that will be the temporary ID for an API resource. + """ + self._temporary_id -= 1 + return self._temporary_id + + def UploadBatchJobOperations(self, upload_url, *operations): + """Uploads operations to the given uploadUrl. + + Note: Each list of operations is expected to contain operations of the same + type, similar to how one would normally send operations in an AdWords API + Service request. + + Args: + upload_url: a string url that the given operations will be uploaded to. + *operations: one or more lists of operations as would be sent to the + AdWords API for the associated service. + """ + operations_xml = ''.join([ + self._GenerateOperationsXML(operations_list) + for operations_list in operations]) + + request_body = (self._UPLOAD_REQUEST_BODY_TEMPLATE % + (self._adwords_endpoint, operations_xml)) + + req = urllib2.Request(upload_url) + req.add_header('Content-Type', 'application/xml') + urllib2.urlopen(req, data=request_body) + + def _GenerateOperationsXML(self, operations): + """Generates XML for the given list of operations. + + Args: + operations: a list of operations for single AdWords Service. + Returns: + A str containing the XML for only the operations, formatted to work + with the BatchJobService. + Raises: + ValueError: if no xsi_type is specified for the operations. + """ + if operations: + # Verify that all operations included specify an xsi_type. + for operation in operations: + if 'xsi_type' not in operation: + raise ValueError('Operations have no xsi_type specified.') + return self._ExtractOperations(self._GenerateRawRequestXML(operations)) + else: + return '' + + def _GenerateRawRequestXML(self, operations): + """Generates the raw XML for the operations sent to the given service. + + Args: + operations: a list containing operations that could be run by the given + service. + + Returns: + A str containing the raw XML of the request to the given service that + would execute the given operations. + """ + service_name = operations[0]['xsi_type'].replace('Operation', 'Service') + service = self.client.GetService(service_name, self._version) + service.suds_client.set_options(nosend=True) + service_request = service.mutate(operations).envelope + service.suds_client.set_options(nosend=False) + return service_request + + def _ExtractOperations(self, full_soap_xml): + """Extracts operations from API Request XML for use with BatchJobService. + + Args: + full_soap_xml: The full XML for the desired operation, as generated by + suds. + + Returns: + A string containing only the operations portion of the full XML request, + formatted for use with the BatchJobService. If no operations are found, + returns an empty string. + + Raises: + ValueError: If no Operation.Type element is found in the operations. This + ordinarily happens if no xsi_type is specified for the operations. + """ + # Extract mutate element from XML, this contains the operations. + mutate = BatchJobHelper._GetRawOperationsFromXML(self, full_soap_xml) + # Ensure operations are formatted correctly for BatchJobService. + for operations in mutate: + self._FormatForBatchJobService(operations) + # Extract the operation type, ensure xsi:type is set for + # BatchJobService. Even if xsi_type is set earlier, suds will end up + # removing it when it sets Operation.Type. + operation_type = operations.find('Operation.Type') + if operation_type is None: + raise ValueError('No xsi_type specified for the operations.') + operations.attrib['xsi:type'] = operation_type.text + operations_xml = ''.join([ElementTree.tostring(operations) + for operations in mutate]) + return operations_xml + + def _FormatForBatchJobService(self, element): + """Formats contents of all operations for use with the BatchJobService. + + This will recursively remove unnecessary namespaces generated by suds that + would prevent the operations from executing via the BatchJobService. It will + also remove namespaces appended to the xsi:type in some cases that also + cause issues for the BatchJobService. + + Args: + element: a starting Element to be modified to the correct format. + """ + # Remove any unnecessary AdWords namespace from the tag. + element.tag = self._tag_namespace_sub.sub('', element.tag) + xsi_type = element.attrib.get( + '{http://www.w3.org/2001/XMLSchema-instance}type') + # If an xsi_type attribute exists, ensure that the namespace is removed from + # the type. + if xsi_type: + element.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'] = ( + self._ATTRIB_NAMESPACE_SUB.sub('', xsi_type)) + for child in element: + self._FormatForBatchJobService(child) + + def _GetRawOperationsFromXML(self, raw_request_xml): + """Retrieve the raw set of operations from the request XML. + + Args: + raw_request_xml: The full XML for the desired operation, as generated by + suds. + + Returns: + An unmodified mutate Element containing the operations from the raw + request xml. + + Raises: + AttributeError: if the provided XML isn't from AdWords. + """ + root = ElementTree.fromstring(raw_request_xml) + return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( + '%smutate' % self._adwords_namespace) + + class ReportDownloader(object): """A utility that can be used to download reports from AdWords.""" diff --git a/googleads/common.py b/googleads/common.py index 13655f04..ddd2ba9b 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -27,7 +27,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.8.0' +VERSION = '3.10.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], @@ -261,8 +261,8 @@ def __init__(self, suds_client, header_handler): Args: suds_client: The suds.client.Client whose service will be wrapped. Note - that this is the client itself, not the client's embedded service - object. + that this is the client itself, not the client's embedded service + object. header_handler: A HeaderHandler responsible for setting the SOAP and HTTP headers on the service client. """ diff --git a/googleads/dfp.py b/googleads/dfp.py index 72881ca6..2553d153 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -39,29 +39,10 @@ _CHUNK_SIZE = 16 * 1024 # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201405': - ('ActivityGroupService', 'ActivityService', 'AdRuleService', - 'AudienceSegmentService', 'BaseRateService', 'CompanyService', - 'ContactService', 'ContentBundleService', - 'ContentMetadataKeyHierarchyService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', - 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProductService', - 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardCustomizationService', - 'RateCardCustomizationGroupService', 'RateCardService', - 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationReportService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'UserService', - 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201408': - ('ActivityGroupService', 'ActivityService', 'AdRuleService', - 'AudienceSegmentService', 'BaseRateService', 'CompanyService', - 'ContactService', 'ContentBundleService', + 'v201411': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', + 'CompanyService', 'ContactService', 'ContentBundleService', 'ContentMetadataKeyHierarchyService', 'ContentService', 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', 'CreativeWrapperService', 'CustomFieldService', @@ -73,10 +54,10 @@ 'ProductService', 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationReportService', 'ReportService', + 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201411': + 'v201502': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -87,14 +68,16 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PlacementService', 'PremiumRateService', - 'ProductService', 'ProductTemplateService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201502': + 'v201505': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -114,7 +97,7 @@ 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201505': + 'v201508': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -131,10 +114,11 @@ 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', + 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201508': + 'v201511': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 4761e52c..5f4b4be8 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -16,13 +16,14 @@ """Unit tests to cover the adwords module.""" - import io +import os import sys import tempfile import unittest import urllib import urllib2 +from xml.etree import ElementTree import mock @@ -227,6 +228,12 @@ def testGetService_badVersion(self): googleads.errors.GoogleAdsValueError, self.adwords_client.GetService, 'CampaignService', '11111') + def testGetBatchJobHelper(self): + with mock.patch('googleads.adwords.BatchJobHelper') as mock_helper: + self.assertEqual( + mock_helper.return_value, + self.adwords_client.GetBatchJobHelper()) + def testGetReportDownloader(self): with mock.patch('googleads.adwords.ReportDownloader') as mock_downloader: self.assertEqual( @@ -245,6 +252,408 @@ def testSetClientCustomerId(self): self.assertEqual(ccid, soap_header.clientCustomerId) +class BatchJobHelperTest(unittest.TestCase): + + """Test suite for BatchJobHelper utility.""" + + ENVELOPE_NS = 'http://schemas.xmlsoap.org/soap/envelope/' + + def GenerateBudgetOperations(self, operations): + """Generates request containing given number of BudgetOperations. + + Args: + operations: a positive int defining the number of BudgetOperations to be + generated. + Returns: + A list of dictionaries containing distinct BudgetOperations. + """ + return [{ + 'operator': 'ADD', + 'xsi_type': 'BudgetOperation', + 'operand': { + 'budgetId': str(i), + 'name': 'Batch budget #%s' % i, + 'period': 'DAILY', + 'amount': {'microAmount': str(3333333 * i)}, + 'deliveryMethod': 'STANDARD'} + } for i in range(1, operations + 1)] + + def GenerateCampaignCriterionOperations(self, operations): + """Generates request containing given number of CampaignCriterionOperations. + + Args: + operations: a positive int defining the number of + CampaignCriterionOperations to be generated. + Returns: + A list of dictionaries containing distinct CampaignCriterionOperations. + """ + return [{ + 'operator': 'ADD', + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': str(100 * i), + 'criterion': { + 'xsi_type': 'Keyword', + 'text': 'venus %s' % i, + 'matchType': 'BROAD' + } + } + } for i in range(1, operations + 1)] + + def GenerateValidRequest(self, operations): + """Generates a valid API request containing the given number of operations. + + Args: + operations: a positive int defining the number of BudgetOperations to be + generated. + + Returns: + A tuple containing the operations used to construct str containing a valid + API request. + """ + ops = self.GenerateBudgetOperations(operations) + ops_xml = ''.join([self.RAW_OPERATION_TEMPLATE % ( + op['operator'], op['xsi_type'], op['operand']['budgetId'], + op['operand']['name'], op['operand']['period'], + op['operand']['amount']['microAmount'], + op['operand']['deliveryMethod'] + ) for op in ops]) + request = self.RAW_API_REQUEST_TEMPLATE % (ops_xml) + return (ops, request) + + def setUp(self): + """Prepare tests.""" + oauth_header = {'Authorization': 'header'} + client_customer_id = 'client customer id' + dev_token = '4W1NN3R15Y0U' + user_agent = 'users gonna use' + oauth2_client = mock.Mock() + oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) + self.client = googleads.adwords.AdWordsClient( + dev_token, oauth2_client, user_agent, + client_customer_id=client_customer_id) + self.batch_job_helper = self.client.GetBatchJobHelper() + + @classmethod + def setUpClass(cls): + test_dir = os.path.dirname(__file__) + with open(os.path.join( + test_dir, 'data/batch_job_util_invalid_request.txt')) as handler: + cls.INVALID_API_REQUEST = handler.read() + with open(os.path.join( + test_dir, 'data/batch_job_util_not_request.txt')) as handler: + cls.NOT_API_REQUEST = handler.read() + with open(os.path.join( + test_dir, 'data/batch_job_util_raw_request_template.txt')) as handler: + cls.RAW_API_REQUEST_TEMPLATE = handler.read() + with open(os.path.join( + test_dir, 'data/batch_job_util_raw_operation_template.txt')) as handler: + cls.RAW_OPERATION_TEMPLATE = handler.read() + with open(os.path.join( + test_dir, 'data/batch_job_util_upload_template.txt')) as handler: + cls.UPLOAD_OPERATIONS_TEMPLATE = handler.read() + + def testExtractOperations(self): + """Tests whether operations XML was extracted and formatted correctly. + + Verifies that the xsi_type has been properly assigned. + """ + operations = self.GenerateCampaignCriterionOperations(1) + raw_xml = self.batch_job_helper._GenerateRawRequestXML(operations) + operations_xml = self.batch_job_helper._ExtractOperations(raw_xml) + # Put operations in a format that allows us to easily verify the behavior. + ops_element = ElementTree.fromstring(operations_xml) + self.assertTrue(ops_element.tag == 'operations') + # Check that the xsi_type has been set correctly. + self.assertTrue(ops_element.attrib[ + '{http://www.w3.org/2001/XMLSchema-instance}type'] == + 'CampaignCriterionOperation') + operand = ops_element.find('operand') + self.assertTrue(operand.attrib[ + '{http://www.w3.org/2001/XMLSchema-instance}type'] == + 'NegativeCampaignCriterion') + criterion = operand.find('criterion') + self.assertTrue(criterion.attrib[ + '{http://www.w3.org/2001/XMLSchema-instance}type'] == + 'Keyword') + + def testFormatForBatchJobService(self): + """Tests whether namespaces have been removed.""" + operations_amount = 5 + ops = self.GenerateCampaignCriterionOperations(operations_amount) + root = ElementTree.fromstring(self.batch_job_helper._GenerateRawRequestXML( + ops)) + body = root.find('{%s}Body' % self.ENVELOPE_NS) + mutate = body.find('{%s}mutate' % self.batch_job_helper._adwords_endpoint) + self.batch_job_helper._FormatForBatchJobService(mutate) + self.assertTrue(self.batch_job_helper._adwords_endpoint not in mutate.tag) + self.assertTrue(len(mutate) == operations_amount) + + for ops in mutate: + self.assertTrue(self.batch_job_helper._adwords_endpoint not in ops.tag) + for child in ops: + self.assertTrue(self.batch_job_helper._adwords_endpoint not in + child.tag) + operand = ops.find('operand') + self.assertTrue(len(operand.attrib) == 1) + self.assertTrue( + 'ns' not in + operand.attrib['{http://www.w3.org/2001/XMLSchema-instance}type']) + for child in operand: + self.assertTrue(self.batch_job_helper._adwords_endpoint not in + child.tag) + criterion = operand.find('criterion') + self.assertTrue( + 'ns' not in + criterion.attrib['{http://www.w3.org/2001/XMLSchema-instance}type']) + for child in criterion: + self.assertTrue(self.batch_job_helper._adwords_endpoint not in + child.tag) + + def testGenerateOperationsXMLNoXsiType(self): + """Tests whether _GenerateOperationsXML raises ValueError if no xsi_type. + """ + operations = self.GenerateCampaignCriterionOperations(1) + del operations[0]['xsi_type'] + self.assertRaises(ValueError, self.batch_job_helper._GenerateOperationsXML, + operations) + + def testGenerateOperationsXMLWithNoOperations(self): + """Tests whether _GenerateOperationsXML produces empty str if no operations. + """ + operations = self.GenerateCampaignCriterionOperations(0) + raw_xml = self.batch_job_helper._GenerateOperationsXML( + operations) + self.assertTrue(raw_xml is '') + + def testGenerateRawRequestXMLFromSingleOperation(self): + """Tests whether raw request xml can be produced from a single operation.""" + operations_amount = 1 + ops = self.GenerateBudgetOperations(operations_amount) + + root = ElementTree.fromstring( + self.batch_job_helper._GenerateRawRequestXML(ops)) + self.assertTrue(len(root) == 2) + body = root.find('{%s}Body' % self.ENVELOPE_NS) + self.assertTrue(len(body) == 1) + mutate = body.find('{%s}mutate' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(mutate) == operations_amount) + + for i in range(0, operations_amount): + operations = mutate[i] + self.assertEqual(operations.tag, '{%s}operations' % + self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertEqual(operations.find( + '{%s}operator' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operator']) + self.assertEqual( + operations.find( + '{%s}Operation.Type' % + self.batch_job_helper._adwords_endpoint).text, + ops[i]['xsi_type']) + operand = operations.find( + '{%s}operand' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertEqual(operand.find( + '{%s}budgetId' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['budgetId']) + self.assertEqual(operand.find( + '{%s}name' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['name']) + self.assertEqual( + operand.find( + '{%s}period' % + self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['period']) + amount = operand.find('{%s}amount' % + self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(amount._children) == + len(ops[i]['operand']['amount'].keys())) + self.assertEqual(amount.find( + '{%s}microAmount' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['amount']['microAmount']) + self.assertEqual(operand.find( + '{%s}deliveryMethod' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['deliveryMethod']) + + def testGenerateRawRequestXMLFromMultipleOperations(self): + """Tests whether raw request xml can be produced for multiple operations.""" + operations_amount = 5 + ops = self.GenerateBudgetOperations(operations_amount) + + root = ElementTree.fromstring( + self.batch_job_helper._GenerateRawRequestXML(ops)) + self.assertTrue(len(root) == 2) + body = root.find('{%s}Body' % self.ENVELOPE_NS) + self.assertTrue(len(body) == 1) + mutate = body.find('{%s}mutate' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(mutate) == operations_amount) + + for i in range(0, operations_amount): + operations = mutate[i] + self.assertEqual( + operations.tag, + '{%s}operations' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertEqual(operations.find( + '{%s}operator' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operator']) + self.assertEqual(operations.find( + '{%s}Operation.Type' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['xsi_type']) + operand = operations.find( + '{%s}operand' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertEqual(operand.find( + '{%s}budgetId' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['budgetId']) + self.assertEqual(operand.find( + '{%s}name' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['name']) + self.assertEqual(operand.find( + '{%s}period' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['period']) + amount = operand.find( + '{%s}amount' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(amount._children) == + len(ops[i]['operand']['amount'].keys())) + self.assertEqual(amount.find( + '{%s}microAmount' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['amount']['microAmount']) + self.assertEqual(operand.find( + '{%s}deliveryMethod' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['deliveryMethod']) + + def testGetId(self): + """Test whether the Ids generated are decreasing sequentially.""" + expected = [-x for x in range(1, 101)] + + for value in expected: + self.assertEqual(value, self.batch_job_helper.GetId()) + + def testGetRawOperationsFromValidSingleOperationRequest(self): + """Test whether operations XML can be retrieved for a single-op request. + + Also verifies that the contents of generated XML are correct. + """ + operations_amount = 1 + ops, request = self.GenerateValidRequest(operations_amount) + + mutate = self.batch_job_helper._GetRawOperationsFromXML(request) + self.assertEqual(mutate.tag, + '{%s}mutate' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(mutate._children) == operations_amount) + + for i in range(0, operations_amount): + operations = mutate[i] + self.assertEqual( + operations.tag, + '{%s}operations' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertEqual(operations.find( + '{%s}operator' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operator']) + self.assertEqual(operations.find( + '{%s}Operation.Type' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['xsi_type']) + operand = operations.find( + '{%s}operand' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertEqual(operand.find( + '{%s}budgetId' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['budgetId']) + self.assertEqual(operand.find( + '{%s}name' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['name']) + self.assertEqual(operand.find( + '{%s}period' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['period']) + amount = operand.find( + '{%s}amount' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(amount._children) == + len(ops[i]['operand']['amount'].keys())) + self.assertEqual(amount.find( + '{%s}microAmount' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['amount']['microAmount']) + self.assertEqual(operand.find( + '{%s}deliveryMethod' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['deliveryMethod']) + + def testGetRawOperationsFromValidMultipleOperationRequest(self): + """Test whether operations XML can be retrieved for a multi-op request. + + Also verifies that the contents of generated XML are correct. + """ + operations_amount = 5 + ops, request = self.GenerateValidRequest(operations_amount) + + mutate = self.batch_job_helper._GetRawOperationsFromXML(request) + self.assertEqual( + mutate.tag, + '{%s}mutate' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(mutate._children) == operations_amount) + + for i in range(0, operations_amount): + operations = mutate[i] + self.assertEqual( + operations.tag, + '{%s}operations' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertEqual(operations.find( + '{%s}operator' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operator']) + self.assertEqual(operations.find( + '{%s}Operation.Type' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['xsi_type']) + operand = (operations.find( + '{%s}operand' % self.batch_job_helper._adwords_endpoint)) + self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertEqual(operand.find( + '{%s}budgetId' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['budgetId']) + self.assertEqual(operand.find( + '{%s}name' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['name']) + self.assertEqual(operand.find( + '{%s}period' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['period']) + amount = (operand.find( + '{%s}amount' % self.batch_job_helper._adwords_endpoint)) + self.assertTrue(len(amount._children) == + len(ops[i]['operand']['amount'].keys())) + self.assertEqual(amount.find( + '{%s}microAmount' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['amount']['microAmount']) + self.assertEqual(operand.find( + '{%s}deliveryMethod' % self.batch_job_helper._adwords_endpoint).text, + ops[i]['operand']['deliveryMethod']) + + def testGetRawOperationsFromValidZeroOperationRequest(self): + """Test verifying empty request generated if no operations provided.""" + operations_amount = 0 + _, request = self.GenerateValidRequest(operations_amount) + + mutate = self.batch_job_helper._GetRawOperationsFromXML(request) + self.assertEqual( + mutate.tag, + '{%s}mutate' % self.batch_job_helper._adwords_endpoint) + self.assertTrue(len(mutate._children) == operations_amount) + + def testGetRawOperationsFromInvalidRequest(self): + """Test whether an invalid API request raises an Exception.""" + self.assertRaises(AttributeError, + self.batch_job_helper._GetRawOperationsFromXML, + self.INVALID_API_REQUEST) + + def testGetRawOperationsFromNotXMLRequest(self): + """Test whether non-XML input raises an Exception.""" + self.assertRaises(ElementTree.ParseError, + self.batch_job_helper._GetRawOperationsFromXML, + self.NOT_API_REQUEST) + + class ReportDownloaderTest(unittest.TestCase): """Tests for the googleads.adwords.ReportDownloader class.""" From ecb39e9c422bcb9fc53d832924b5cf435e269dc0 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Thu, 19 Nov 2015 14:07:42 -0500 Subject: [PATCH 020/180] Commiting latest changes. From e8dea473c7944ed54fc9b1277744a032fce73019 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 24 Nov 2015 11:28:19 -0500 Subject: [PATCH 021/180] Removing AdWords v201502 and adding Batch Job Incremental Upload Support. --- ChangeLog | 12 + .../authentication/generate_refresh_token.py | 28 +- examples/adwords/v201502/__init__.py | 15 - .../v201502/account_management/__init__.py | 15 - .../account_management/create_account.py | 65 -- .../account_management/get_account_changes.py | 104 --- .../get_account_hierarchy.py | 94 --- .../v201502/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 222 ------ .../add_ad_group_bid_modifier.py | 76 --- .../add_click_to_download_ad.py | 110 --- .../add_text_ad_with_upgraded_urls.py | 112 ---- .../create_and_attach_shared_keyword_set.py | 129 ---- ...ind_and_remove_criteria_from_shared_set.py | 155 ----- .../get_ad_group_bid_modifier.py | 74 -- .../upload_offline_conversions.py | 99 --- .../use_shared_bidding_strategy.py | 173 ----- .../v201502/basic_operations/__init__.py | 15 - .../v201502/basic_operations/add_ad_groups.py | 113 ---- .../v201502/basic_operations/add_campaigns.py | 127 ---- .../v201502/basic_operations/add_keywords.py | 94 --- .../v201502/basic_operations/add_text_ads.py | 95 --- .../v201502/basic_operations/get_ad_groups.py | 77 --- .../v201502/basic_operations/get_campaigns.py | 75 --- .../get_campaigns_with_awql.py | 65 -- .../v201502/basic_operations/get_keywords.py | 78 --- .../v201502/basic_operations/get_text_ads.py | 82 --- .../v201502/basic_operations/pause_ad.py | 62 -- .../v201502/basic_operations/remove_ad.py | 63 -- .../basic_operations/remove_ad_group.py | 59 -- .../basic_operations/remove_campaign.py | 59 -- .../basic_operations/remove_keyword.py | 69 -- .../basic_operations/update_ad_group.py | 59 -- .../basic_operations/update_campaign.py | 59 -- .../basic_operations/update_keyword.py | 84 --- .../v201502/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 68 -- .../campaign_management/add_experiment.py | 129 ---- .../add_keywords_in_bulk.py | 136 ---- .../get_all_disapproved_ads.py | 75 --- .../get_all_disapproved_ads_with_awql.py | 64 -- .../get_campaigns_by_label.py | 86 --- .../campaign_management/promote_experiment.py | 62 -- .../campaign_management/set_ad_parameters.py | 104 --- .../set_criterion_bid_modifier.py | 78 --- .../campaign_management/validate_text_ad.py | 88 --- .../v201502/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 121 ---- .../handle_policy_violation_error.py | 115 ---- .../adwords/v201502/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 155 ----- .../v201502/extensions/add_site_links.py | 126 ---- .../extensions/add_site_links_using_feeds.py | 228 ------- .../adwords/v201502/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 525 --------------- .../v201502/migration/upgrade_ad_url.py | 80 --- examples/adwords/v201502/misc/__init__.py | 15 - .../v201502/misc/get_all_images_and_videos.py | 77 --- examples/adwords/v201502/misc/upload_image.py | 67 -- .../adwords/v201502/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 133 ---- .../get_keyword_bid_simulations.py | 83 --- .../v201502/optimization/get_keyword_ideas.py | 92 --- .../adwords/v201502/remarketing/__init__.py | 15 - .../v201502/remarketing/add_audience.py | 104 --- .../remarketing/add_conversion_tracker.py | 74 -- .../remarketing/add_rule_based_user_lists.py | 184 ----- .../adwords/v201502/reporting/__init__.py | 15 - .../reporting/download_criteria_report.py | 63 -- .../download_criteria_report_as_stream.py | 79 --- ...oad_criteria_report_as_stream_with_awql.py | 81 --- .../download_criteria_report_as_string.py | 61 -- ...oad_criteria_report_as_string_with_awql.py | 55 -- .../download_criteria_report_with_awql.py | 58 -- .../v201502/reporting/get_report_fields.py | 53 -- examples/adwords/v201502/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 282 -------- .../v201502/shopping/add_product_scope.py | 104 --- .../v201502/shopping/add_shopping_campaign.py | 121 ---- .../shopping/get_product_category_taxonomy.py | 96 --- .../adwords/v201502/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 156 ----- .../add_demographic_targeting_criteria.py | 97 --- .../get_campaign_targeting_criteria.py | 86 --- .../get_targetable_languages_and_carriers.py | 56 -- .../v201502/targeting/lookup_location.py | 83 --- .../v201506/basic_operations/get_keywords.py | 4 +- .../add_complete_campaigns_using_batch_job.py | 46 +- ...dd_keywords_using_incremental_batch_job.py | 215 ++++++ .../v201509/basic_operations/get_keywords.py | 4 +- examples/adxbuyer/v201502/__init__.py | 15 - .../v201502/basic_operations/__init__.py | 15 - .../v201502/basic_operations/add_ad_groups.py | 89 --- .../v201502/basic_operations/add_campaigns.py | 120 ---- .../basic_operations/add_placements.py | 88 --- .../add_third_party_redirect_ad.py | 100 --- .../basic_operations/get_placements.py | 76 --- .../get_third_party_redirect_ads.py | 81 --- .../basic_operations/remove_placement.py | 69 -- .../basic_operations/update_placement.py | 81 --- .../v201502/campaign_management/__init__.py | 15 - .../add_placements_in_bulk.py | 134 ---- .../v201502/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 115 ---- .../authentication/generate_refresh_token.py | 28 +- googleads/adwords.py | 562 +++++++++++----- googleads/common.py | 2 +- googleads/errors.py | 5 + setup.py | 2 +- tests/adwords_test.py | 634 ++++++++++++++---- 110 files changed, 1224 insertions(+), 8859 deletions(-) delete mode 100644 examples/adwords/v201502/__init__.py delete mode 100644 examples/adwords/v201502/account_management/__init__.py delete mode 100755 examples/adwords/v201502/account_management/create_account.py delete mode 100755 examples/adwords/v201502/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201502/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201502/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201502/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201502/advanced_operations/upload_offline_conversions.py delete mode 100755 examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201502/basic_operations/__init__.py delete mode 100755 examples/adwords/v201502/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201502/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201502/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201502/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201502/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201502/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201502/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201502/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201502/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201502/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201502/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201502/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201502/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201502/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201502/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201502/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201502/campaign_management/__init__.py delete mode 100755 examples/adwords/v201502/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201502/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py delete mode 100755 examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201502/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201502/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201502/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201502/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201502/error_handling/__init__.py delete mode 100755 examples/adwords/v201502/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201502/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201502/extensions/__init__.py delete mode 100755 examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201502/extensions/add_site_links.py delete mode 100755 examples/adwords/v201502/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201502/migration/__init__.py delete mode 100755 examples/adwords/v201502/migration/migrate_to_extension_settings.py delete mode 100755 examples/adwords/v201502/migration/upgrade_ad_url.py delete mode 100644 examples/adwords/v201502/misc/__init__.py delete mode 100755 examples/adwords/v201502/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201502/misc/upload_image.py delete mode 100644 examples/adwords/v201502/optimization/__init__.py delete mode 100755 examples/adwords/v201502/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201502/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201502/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201502/remarketing/__init__.py delete mode 100755 examples/adwords/v201502/remarketing/add_audience.py delete mode 100755 examples/adwords/v201502/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201502/remarketing/add_rule_based_user_lists.py delete mode 100644 examples/adwords/v201502/reporting/__init__.py delete mode 100755 examples/adwords/v201502/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201502/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201502/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201502/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201502/reporting/get_report_fields.py delete mode 100644 examples/adwords/v201502/shopping/__init__.py delete mode 100755 examples/adwords/v201502/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201502/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201502/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201502/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201502/targeting/__init__.py delete mode 100755 examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201502/targeting/lookup_location.py rename examples/adwords/v201509/{campaign_management => advanced_operations}/add_complete_campaigns_using_batch_job.py (90%) create mode 100755 examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py delete mode 100644 examples/adxbuyer/v201502/__init__.py delete mode 100644 examples/adxbuyer/v201502/basic_operations/__init__.py delete mode 100755 examples/adxbuyer/v201502/basic_operations/add_ad_groups.py delete mode 100755 examples/adxbuyer/v201502/basic_operations/add_campaigns.py delete mode 100755 examples/adxbuyer/v201502/basic_operations/add_placements.py delete mode 100755 examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py delete mode 100755 examples/adxbuyer/v201502/basic_operations/get_placements.py delete mode 100755 examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py delete mode 100755 examples/adxbuyer/v201502/basic_operations/remove_placement.py delete mode 100755 examples/adxbuyer/v201502/basic_operations/update_placement.py delete mode 100644 examples/adxbuyer/v201502/campaign_management/__init__.py delete mode 100755 examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py delete mode 100644 examples/adxbuyer/v201502/error_handling/__init__.py delete mode 100755 examples/adxbuyer/v201502/error_handling/handle_partial_failures.py diff --git a/ChangeLog b/ChangeLog index 61f12d9b..880989c1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,15 @@ +3.11.0 -- 11/24/2015 +* Removed support for AdWords v201502. +* Added incremental upload support to BatchJobHelper. +* Added the add_keywords_using_incremental_batch_job.py to advanced_operations + examples. +* Moved add_complete_campaigns_using_batch_job.py to advanced_operations. +* The BatchJobHelper can now be used to parse the BatchJob response. Examples + have been updated to demonstrate this. +* The xmltodict library has been added as a new dependency. +* Added option to set additional scopes in generate_refresh_token.py for + AdWords and DFP. + 3.10.0 - 11/17/2015 * Removed support for DFP v201405 and v201408. * Removed examples for v201411. diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 21698c51..34ff383a 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -17,6 +17,7 @@ """Generates refresh token for AdWords using the Installed Application flow.""" +import argparse import sys from oauth2client import client @@ -29,13 +30,24 @@ # The AdWords API OAuth 2.0 scope. SCOPE = u'https://www.googleapis.com/auth/adwords' +parser = argparse.ArgumentParser(description='Generates a refresh token with ' + 'the provided credentials.') +parser.add_argument('--client_id', default=CLIENT_ID, + help='Client Id retrieved from the Developer\'s Console.') +parser.add_argument('--client_secret', default=CLIENT_SECRET, + help='Client Secret retrieved from the Developer\'s ' + 'Console.') +parser.add_argument('--additional_scopes', default=None, + help='Additional scopes to apply when generating the ' + 'refresh token. Each scope should be separated by a comma.') -def main(): + +def main(client_id, client_secret, scopes): """Retrieve and display the access and refresh token.""" flow = client.OAuth2WebServerFlow( - client_id=CLIENT_ID, - client_secret=CLIENT_SECRET, - scope=[SCOPE], + client_id=client_id, + client_secret=client_secret, + scope=scopes, user_agent='Ads Python Client Library', redirect_uri='urn:ietf:wg:oauth:2.0:oob') @@ -58,4 +70,10 @@ def main(): if __name__ == '__main__': - main() + args = parser.parse_args() + configured_scopes = [SCOPE] + if args.client_id == CLIENT_ID or args.client_secret == CLIENT_SECRET: + raise AttributeError('No client_id or client_secret specified.') + if args.additional_scopes: + configured_scopes.extend(args.additional_scopes.replace(' ', '').split(',')) + main(args.client_id, args.client_secret, configured_scopes) diff --git a/examples/adwords/v201502/__init__.py b/examples/adwords/v201502/__init__.py deleted file mode 100644 index 41f5a52e..00000000 --- a/examples/adwords/v201502/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201502/account_management/__init__.py b/examples/adwords/v201502/account_management/__init__.py deleted file mode 100644 index fb8c03ea..00000000 --- a/examples/adwords/v201502/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201502/account_management/create_account.py b/examples/adwords/v201502/account_management/create_account.py deleted file mode 100755 index 12536f72..00000000 --- a/examples/adwords/v201502/account_management/create_account.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from datetime import datetime - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201502') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201502/account_management/get_account_changes.py b/examples/adwords/v201502/account_management/get_account_changes.py deleted file mode 100755 index 3709b0bb..00000000 --- a/examples/adwords/v201502/account_management/get_account_changes.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201502') - campaign_service = client.GetService('CampaignService', version='v201502') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedAdExtensions' in data: - print ' Added ad extensions: %s' % data['addedAdExtensions'] - if 'removedAdExtensions' in data: - print ' Removed ad extensions: %s' % data['removedAdExtensions'] - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201502/account_management/get_account_hierarchy.py b/examples/adwords/v201502/account_management/get_account_hierarchy.py deleted file mode 100755 index 855ee159..00000000 --- a/examples/adwords/v201502/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the account hierarchy under the current account. - -Note: this code example won't work with test accounts. See -https://developers.google.com/adwords/api/docs/test-accounts - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201502') - - # Construct selector to get all accounts. - selector = { - 'fields': ['CustomerId', 'Name'] - } - # Get serviced account graph. - graph = managed_customer_service.get(selector) - if 'entries' in graph and graph['entries']: - # Create map from customerId to parent and child links. - child_links = {} - parent_links = {} - if 'links' in graph: - for link in graph['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Create map from customerID to account and find root account. - accounts = {} - root_account = None - for account in graph['entries']: - accounts[account['customerId']] = account - if account['customerId'] not in parent_links: - root_account = account - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - else: - print 'No serviced accounts were found' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201502/advanced_operations/__init__.py b/examples/adwords/v201502/advanced_operations/__init__.py deleted file mode 100644 index 7e57b8b3..00000000 --- a/examples/adwords/v201502/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201502/advanced_operations/add_ad_customizer.py b/examples/adwords/v201502/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 055a04ec..00000000 --- a/examples/adwords/v201502/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates TextAds that use ad customizations for the specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add TextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no TextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService') - - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'description1': 'Only {=%s.Price}' % feed_name, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 0db78808..00000000 --- a/examples/adwords/v201502/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201502') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index e81d0498..00000000 --- a/examples/adwords/v201502/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad to ad group ID \'%s\' ' - 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index d0bb5eef..00000000 --- a/examples/adwords/v201502/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a text add that uses advanced features of upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 2919e0d3..00000000 --- a/examples/adwords/v201502/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201502') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201502') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201502') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index c0fd53fd..00000000 --- a/examples/adwords/v201502/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201502') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201502') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if page['entries']: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 54b3ffe6..00000000 --- a/examples/adwords/v201502/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201502') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py deleted file mode 100755 index b944429c..00000000 --- a/examples/adwords/v201502/advanced_operations/upload_offline_conversions.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - conversion_tracker_service = client.GetService('ConversionTrackerService', - version='v201502') - - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201502') - - # Once created, this entry will be visible under - # Tools and Analysis->Conversion and will have "Source = Import". - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'category': 'PAGE_VIEW', - 'name': conversion_name, - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90' - } - - upload_conversion_operation = { - 'operator': 'ADD', - 'operand': upload_conversion - } - - response = conversion_tracker_service.mutate( - [upload_conversion_operation]) - new_upload_conversion = response['value'] - - print ('New upload conversion type with name \'%s\' and ID \'%s\' was ' - 'created.' % (new_upload_conversion['name'], - new_upload_conversion['id'])) - - # Associate offline conversions with the upload conversion we created. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index d93873b8..00000000 --- a/examples/adwords/v201502/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,173 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201502') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201502') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'period': 'DAILY', - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201502') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201502/basic_operations/__init__.py b/examples/adwords/v201502/basic_operations/__init__.py deleted file mode 100644 index 80acbea9..00000000 --- a/examples/adwords/v201502/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201502/basic_operations/add_ad_groups.py b/examples/adwords/v201502/basic_operations/add_ad_groups.py deleted file mode 100755 index 131f952d..00000000 --- a/examples/adwords/v201502/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README.. - -""" - - -import uuid - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201502') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings - these settings only affect - # serving for the Display Network. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/basic_operations/add_campaigns.py b/examples/adwords/v201502/basic_operations/add_campaigns.py deleted file mode 100755 index 2719dc97..00000000 --- a/examples/adwords/v201502/basic_operations/add_campaigns.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201502') - budget_service = client.GetService('BudgetService', version='v201502') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/basic_operations/add_keywords.py b/examples/adwords/v201502/basic_operations/add_keywords.py deleted file mode 100755 index f9ef9002..00000000 --- a/examples/adwords/v201502/basic_operations/add_keywords.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/basic_operations/add_text_ads.py b/examples/adwords/v201502/basic_operations/add_text_ads.py deleted file mode 100755 index 1f043345..00000000 --- a/examples/adwords/v201502/basic_operations/add_text_ads.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/basic_operations/get_ad_groups.py b/examples/adwords/v201502/basic_operations/get_ad_groups.py deleted file mode 100755 index c295768f..00000000 --- a/examples/adwords/v201502/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201502') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/basic_operations/get_campaigns.py b/examples/adwords/v201502/basic_operations/get_campaigns.py deleted file mode 100755 index be56c978..00000000 --- a/examples/adwords/v201502/basic_operations/get_campaigns.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201502') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 75c41593..00000000 --- a/examples/adwords/v201502/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201502') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201502/basic_operations/get_keywords.py b/examples/adwords/v201502/basic_operations/get_keywords.py deleted file mode 100755 index 0ef3b1a0..00000000 --- a/examples/adwords/v201502/basic_operations/get_keywords.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['AdGroupId', 'Id', 'Text', 'KeywordMatchType', 'PlacementUrl'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for criterion in page['entries']: - print ('Keyword ad group criterion with ad group id \'%s\', criterion ' - 'id \'%s\', text \'%s\', and match type \'%s\' was found.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/basic_operations/get_text_ads.py b/examples/adwords/v201502/basic_operations/get_text_ads.py deleted file mode 100755 index 03f6f464..00000000 --- a/examples/adwords/v201502/basic_operations/get_text_ads.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/basic_operations/pause_ad.py b/examples/adwords/v201502/basic_operations/pause_ad.py deleted file mode 100755 index ca87c702..00000000 --- a/examples/adwords/v201502/basic_operations/pause_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201502/basic_operations/remove_ad.py b/examples/adwords/v201502/basic_operations/remove_ad.py deleted file mode 100755 index 273241cd..00000000 --- a/examples/adwords/v201502/basic_operations/remove_ad.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201502/basic_operations/remove_ad_group.py b/examples/adwords/v201502/basic_operations/remove_ad_group.py deleted file mode 100755 index 818e7f98..00000000 --- a/examples/adwords/v201502/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201502') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/basic_operations/remove_campaign.py b/examples/adwords/v201502/basic_operations/remove_campaign.py deleted file mode 100755 index dcfdde97..00000000 --- a/examples/adwords/v201502/basic_operations/remove_campaign.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201502') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/basic_operations/remove_keyword.py b/examples/adwords/v201502/basic_operations/remove_keyword.py deleted file mode 100755 index 8f6d2b7f..00000000 --- a/examples/adwords/v201502/basic_operations/remove_keyword.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201502/basic_operations/update_ad_group.py b/examples/adwords/v201502/basic_operations/update_ad_group.py deleted file mode 100755 index d13c9a51..00000000 --- a/examples/adwords/v201502/basic_operations/update_ad_group.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201502') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/basic_operations/update_campaign.py b/examples/adwords/v201502/basic_operations/update_campaign.py deleted file mode 100755 index 15012ba9..00000000 --- a/examples/adwords/v201502/basic_operations/update_campaign.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201502') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/basic_operations/update_keyword.py b/examples/adwords/v201502/basic_operations/update_keyword.py deleted file mode 100755 index 70f61b8f..00000000 --- a/examples/adwords/v201502/basic_operations/update_keyword.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201502/campaign_management/__init__.py b/examples/adwords/v201502/campaign_management/__init__.py deleted file mode 100644 index db098bda..00000000 --- a/examples/adwords/v201502/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201502/campaign_management/add_campaign_labels.py b/examples/adwords/v201502/campaign_management/add_campaign_labels.py deleted file mode 100755 index 648b2ac6..00000000 --- a/examples/adwords/v201502/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201502') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201502/campaign_management/add_experiment.py b/examples/adwords/v201502/campaign_management/add_experiment.py deleted file mode 100755 index 156a0195..00000000 --- a/examples/adwords/v201502/campaign_management/add_experiment.py +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -import datetime -import uuid - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201502') - ad_group_service = client.GetService('AdGroupService', version='v201502') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py deleted file mode 100755 index 21abdc01..00000000 --- a/examples/adwords/v201502/campaign_management/add_keywords_in_bulk.py +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code sample illustrates how to perform asynchronous requests. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -import random -import re -import time - -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -KEYWORD_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201502') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add keywords. - for i in range(KEYWORD_NUMBER): - keyword = 'mars%d' % i - if random.randint(1, 10) == 1: - keyword += '!!!' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': keyword - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - keyword = operations[index]['operand']['criterion']['text'] - print ('ERROR - keyword \'%s\' failed due to \'%s\'' % - (keyword, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index b664fb86..00000000 --- a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 6e7c5781..00000000 --- a/examples/adwords/v201502/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index dfebfdec..00000000 --- a/examples/adwords/v201502/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time - -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201502') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201502/campaign_management/promote_experiment.py b/examples/adwords/v201502/campaign_management/promote_experiment.py deleted file mode 100755 index b63a01d6..00000000 --- a/examples/adwords/v201502/campaign_management/promote_experiment.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201502') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201502/campaign_management/set_ad_parameters.py b/examples/adwords/v201502/campaign_management/set_ad_parameters.py deleted file mode 100755 index a815200e..00000000 --- a/examples/adwords/v201502/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright 2015 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - ad_param_service = client.GetService('AdParamService', version='v201502') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': { - 'urls': ['http://www.example.com'] - }, - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index e8be422f..00000000 --- a/examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201502') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201502/campaign_management/validate_text_ad.py b/examples/adwords/v201502/campaign_management/validate_text_ad.py deleted file mode 100755 index 03c6abad..00000000 --- a/examples/adwords/v201502/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': { - 'urls': ['http://www.example.com'] - }, - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/error_handling/__init__.py b/examples/adwords/v201502/error_handling/__init__.py deleted file mode 100644 index b5203c57..00000000 --- a/examples/adwords/v201502/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201502/error_handling/handle_partial_failures.py b/examples/adwords/v201502/error_handling/handle_partial_failures.py deleted file mode 100755 index 614dd036..00000000 --- a/examples/adwords/v201502/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/error_handling/handle_policy_violation_error.py b/examples/adwords/v201502/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 33b69907..00000000 --- a/examples/adwords/v201502/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re - -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201502') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - operation = operations[int(operation_index[0])] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) - else: - # Non-policy error returned, re-throw exception. - raise e - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/extensions/__init__.py b/examples/adwords/v201502/extensions/__init__.py deleted file mode 100644 index b4d63e00..00000000 --- a/examples/adwords/v201502/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 97112f68..00000000 --- a/examples/adwords/v201502/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' -# To obtain an access token for your Places account, you can run the -# generate_refresh_token.py example and manually replace the scope with -# "https://www.google.com/local/add". -GMB_ACCESS_TOKEN = 'INSERT_GMB_OAUTH_ACCESS_TOKEN_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201502').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201502') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201502/extensions/add_site_links.py b/examples/adwords/v201502/extensions/add_site_links.py deleted file mode 100755 index cc6297dd..00000000 --- a/examples/adwords/v201502/extensions/add_site_links.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from datetime import datetime - - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201502') - customer_service = client.GetService('CustomerService', version='v201502') - - customer_tz = timezone(customer_service.get()['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkUrl': 'http://www.example.com/storehours' - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkUrl': 'http://www.example.com/thanksgiving', - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt) - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkUrl': 'http://www.example.com/mobile/wifi', - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'} - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkUrl': 'http://www.example.com/happyhours', - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py b/examples/adwords/v201502/extensions/add_site_links_using_feeds.py deleted file mode 100755 index 6ff72e0b..00000000 --- a/examples/adwords/v201502/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,228 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -import re -import uuid - -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201502') - feed_item_service = client.GetService('FeedItemService', version='v201502') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201502') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201502') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2'} - ] - - feed_items = [] - for item in items_data: - feed_items.append({ - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - - # Optional: use the 'scheduling' key to specify time and days of the - # week for feed to deliver. This is a Beta feature. - }) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/migration/__init__.py b/examples/adwords/v201502/migration/__init__.py deleted file mode 100644 index 5de8ecca..00000000 --- a/examples/adwords/v201502/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201502/migration/migrate_to_extension_settings.py b/examples/adwords/v201502/migration/migrate_to_extension_settings.py deleted file mode 100755 index 56c777bd..00000000 --- a/examples/adwords/v201502/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,525 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201502') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201502') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201502') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201502') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201502') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201502') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - if ('lhsOperand' in campaign_feed['matchingFunction'] and - campaign_feed['matchingFunction']['lhsOperand'][0]['xsi_type'] == - 'RequestContextOperand'): - request_context_operand = campaign_feed['matchingFunction']['lhsOperand'][0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201502') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings['attributeValue']['feedAttributeId']: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/migration/upgrade_ad_url.py b/examples/adwords/v201502/migration/upgrade_ad_url.py deleted file mode 100755 index 0e805bee..00000000 --- a/examples/adwords/v201502/migration/upgrade_ad_url.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 upgrades an ad to use upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, adgroup_id, ad_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201502') - - selector = { - 'fields': ['Id', 'Url'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [ad_id] - } - ] - } - - page = adgroup_ad_service.get(selector) - - adgroup_ad = page['entries'][0] if page['entries'] else None - - if not adgroup_ad: - raise errors.GoogleAdsError('Ad not found.') - - ad_url_upgrade = { - 'adId': adgroup_ad['ad']['id'], - 'finalUrl': adgroup_ad['ad']['url'] - } - - adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] - - if adgroup_ad: - print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' - % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201502/misc/__init__.py b/examples/adwords/v201502/misc/__init__.py deleted file mode 100644 index 30d42e87..00000000 --- a/examples/adwords/v201502/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201502/misc/get_all_images_and_videos.py b/examples/adwords/v201502/misc/get_all_images_and_videos.py deleted file mode 100755 index b64c898f..00000000 --- a/examples/adwords/v201502/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201502') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - print ('Media with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], image['mimeType'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/misc/upload_image.py b/examples/adwords/v201502/misc/upload_image.py deleted file mode 100755 index 9aea238e..00000000 --- a/examples/adwords/v201502/misc/upload_image.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 - -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201502') - - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201502/optimization/__init__.py b/examples/adwords/v201502/optimization/__init__.py deleted file mode 100644 index 2e0ca689..00000000 --- a/examples/adwords/v201502/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201502/optimization/estimate_keyword_traffic.py b/examples/adwords/v201502/optimization/estimate_keyword_traffic.py deleted file mode 100755 index ee1f3ae3..00000000 --- a/examples/adwords/v201502/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201502') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - selector = { - 'campaignEstimateRequests': [{ - 'adGroupEstimateRequests': [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }], - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ] - }] - } - estimates = traffic_estimator_service.get(selector) - - # Display results. - ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] - keyword_estimates = ad_group_estimate['keywordEstimates'] - for index in xrange(len(keyword_estimates)): - keyword = keyword_estimate_requests[index]['keyword'] - estimate = keyword_estimates[index] - if keyword_estimate_requests[index].get('isNegative', False): - continue - - # Find the mean of the min and max values. - mean_avg_cpc = calc_mean(estimate['min']['averageCpc']['microAmount'], - estimate['max']['averageCpc']['microAmount']) - mean_avg_pos = calc_mean(estimate['min']['averagePosition'], - estimate['max']['averagePosition']) - mean_clicks = calc_mean(estimate['min']['clicksPerDay'], - estimate['max']['clicksPerDay']) - mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], - estimate['max']['totalCost']['microAmount']) - - print ('Results for the keyword with text \'%s\' and match type \'%s\':' - % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % mean_avg_cpc - print ' Estimated ad position: %s' % mean_avg_pos - print ' Estimated daily clicks: %s' % mean_clicks - print ' Estimated daily cost: %s' % mean_total_cost - - -def fmt_mean(mean): - if mean: - return '%.2f' % mean - else: - return None - - -def calc_mean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index eb42cc50..00000000 --- a/examples/adwords/v201502/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201502') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201502/optimization/get_keyword_ideas.py b/examples/adwords/v201502/optimization/get_keyword_ideas.py deleted file mode 100755 index 29eaf0e5..00000000 --- a/examples/adwords/v201502/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201502') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/remarketing/__init__.py b/examples/adwords/v201502/remarketing/__init__.py deleted file mode 100644 index b39776a8..00000000 --- a/examples/adwords/v201502/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201502/remarketing/add_audience.py b/examples/adwords/v201502/remarketing/add_audience.py deleted file mode 100755 index 8bbcde0c..00000000 --- a/examples/adwords/v201502/remarketing/add_audience.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201502') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201502') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/remarketing/add_conversion_tracker.py b/examples/adwords/v201502/remarketing/add_conversion_tracker.py deleted file mode 100755 index 39c7ff6a..00000000 --- a/examples/adwords/v201502/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201502') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'markupLanguage': 'HTML', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'isProductAdsChargeable': 'true', - 'productAdsChargeableConversionWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 46fae2b5..00000000 --- a/examples/adwords/v201502/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,184 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201502') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/reporting/__init__.py b/examples/adwords/v201502/reporting/__init__.py deleted file mode 100644 index 85eee62f..00000000 --- a/examples/adwords/v201502/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201502/reporting/download_criteria_report.py b/examples/adwords/v201502/reporting/download_criteria_report.py deleted file mode 100755 index 4cd49ea0..00000000 --- a/examples/adwords/v201502/reporting/download_criteria_report.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -import logging -import sys - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201502') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport(report, sys.stdout) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index a47e32be..00000000 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201502') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream(report) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 0c41a692..00000000 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -import logging -import StringIO -import sys - - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201502') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV') - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_string.py b/examples/adwords/v201502/reporting/download_criteria_report_as_string.py deleted file mode 100755 index 5328a735..00000000 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -import logging - -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201502') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - }, - # Enable to get rows with zero impressions. - 'includeZeroImpressions': 'false' - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString(report) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 1cb21479..00000000 --- a/examples/adwords/v201502/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201502') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 83125deb..00000000 --- a/examples/adwords/v201502/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -Api: AdWordsOnly -""" - - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201502') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql(report_query, 'CSV', output_file) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201502/reporting/get_report_fields.py b/examples/adwords/v201502/reporting/get_report_fields.py deleted file mode 100755 index 3fab2daa..00000000 --- a/examples/adwords/v201502/reporting/get_report_fields.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201502') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201502/shopping/__init__.py b/examples/adwords/v201502/shopping/__init__.py deleted file mode 100644 index 96422728..00000000 --- a/examples/adwords/v201502/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201502/shopping/add_product_partition_tree.py b/examples/adwords/v201502/shopping/add_product_partition_tree.py deleted file mode 100755 index 065fb3b5..00000000 --- a/examples/adwords/v201502/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,282 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) - diff --git a/examples/adwords/v201502/shopping/add_product_scope.py b/examples/adwords/v201502/shopping/add_product_scope.py deleted file mode 100755 index 51393c42..00000000 --- a/examples/adwords/v201502/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201502') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/shopping/add_shopping_campaign.py b/examples/adwords/v201502/shopping/add_shopping_campaign.py deleted file mode 100755 index f10fe740..00000000 --- a/examples/adwords/v201502/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201502') - ad_group_service = client.GetService('AdGroupService', version='v201502') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set shared budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201502/shopping/get_product_category_taxonomy.py b/examples/adwords/v201502/shopping/get_product_category_taxonomy.py deleted file mode 100755 index b198ed8e..00000000 --- a/examples/adwords/v201502/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201502') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/targeting/__init__.py b/examples/adwords/v201502/targeting/__init__.py deleted file mode 100644 index 2c027ccc..00000000 --- a/examples/adwords/v201502/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 8be19b82..00000000 --- a/examples/adwords/v201502/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201502') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - florida_downtown = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'PlacesOfInterestOperand', - # Other valid options: AIRPORT, UNIVERSITY. - 'category': 'DOWNTOWN', - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - } - } - # Distance targeting. Area of 10 miles around targets above. - distance_10_miles = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - - }] - } - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - - # Create operations - operations = [] - for criterion in [california, mexico, english, spanish, florida_tier3, - florida_downtown, distance_10_miles]: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 880b542c..00000000 --- a/examples/adwords/v201502/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 84ebe093..00000000 --- a/examples/adwords/v201502/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201502') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index 80580e76..00000000 --- a/examples/adwords/v201502/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201502') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201502/targeting/lookup_location.py b/examples/adwords/v201502/targeting/lookup_location.py deleted file mode 100755 index 19732cfd..00000000 --- a/examples/adwords/v201502/targeting/lookup_location.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201502') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/basic_operations/get_keywords.py b/examples/adwords/v201506/basic_operations/get_keywords.py index 6f618405..4cb24c58 100755 --- a/examples/adwords/v201506/basic_operations/get_keywords.py +++ b/examples/adwords/v201506/basic_operations/get_keywords.py @@ -60,7 +60,7 @@ def main(client, adgroup_id): 'startIndex': str(offset), 'numberResults': str(PAGE_SIZE) }, - 'ordering': [{'field': 'Id', 'sortOrder': 'ASCENDING'}] + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] } more_pages = True while more_pages: @@ -70,7 +70,7 @@ def main(client, adgroup_id): if 'entries' in page: for keyword in page['entries']: print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\'' % ( + '\'%s\' was found.' % ( keyword['criterion']['id'], keyword['criterion']['type'], keyword['criterion']['text'], diff --git a/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py similarity index 90% rename from examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py rename to examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py index 9af6977b..ccd3e2cd 100755 --- a/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py @@ -22,7 +22,6 @@ Api: AdWordsOnly """ -import logging import random import time import urllib2 @@ -32,11 +31,6 @@ from googleads import adwords -# Set logging configuration. -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - NUMBER_OF_CAMPAIGNS_TO_ADD = 2 NUMBER_OF_ADGROUPS_TO_ADD = 2 NUMBER_OF_KEYWORDS_TO_ADD = 5 @@ -53,8 +47,8 @@ def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): # Retrieve the URL used to upload the BatchJob operations. upload_url = batch_job['uploadUrl']['url'] batch_job_id = batch_job['id'] - logging.info('Created BatchJob with ID "%d", status "%s", and upload URL ' - '"%s"', batch_job['id'], batch_job['status'], upload_url) + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) # Generate operations to upload. budget_operations = BuildBudgetOperations(batch_job_helper) @@ -69,15 +63,15 @@ def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) # Upload operations. - batch_job_helper.UploadBatchJobOperations( + batch_job_helper.UploadOperations( upload_url, budget_operations, campaign_operations, campaign_criterion_operations, adgroup_operations, adgroup_criterion_operations, adgroup_ad_operations) # Download and display results. download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url) - logging.info('Downloaded following response:\n%s', response.read()) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) def AddBatchJob(client): @@ -393,21 +387,41 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, batch_job['status'] in PENDING_STATUSES): sleep_interval = (30 * (2 ** poll_attempt) + (random.randint(0, 10000) / 1000)) - logging.info('Batch Job not ready, sleeping for %s seconds.', - sleep_interval) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval time.sleep(sleep_interval) batch_job = GetBatchJob(client, batch_job_id) poll_attempt += 1 if 'downloadUrl' in batch_job: url = batch_job['downloadUrl']['url'] - logging.info( - 'Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.', - batch_job['id'], batch_job['status'], url) + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) return url raise Exception('Batch Job not finished downloading. Try checking later.') +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() diff --git a/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..931e3923 --- /dev/null +++ b/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,215 @@ +#!/usr/bin/python +# +# Copyright 2015 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +Api: AdWordsOnly +""" + +import random +import time +import urllib2 +import uuid + + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper() + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201509') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job with ID "%s" not finished downloading. Try ' + 'checking later.' % batch_job_id) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/get_keywords.py b/examples/adwords/v201509/basic_operations/get_keywords.py index 332fc6be..3359dd5a 100755 --- a/examples/adwords/v201509/basic_operations/get_keywords.py +++ b/examples/adwords/v201509/basic_operations/get_keywords.py @@ -60,7 +60,7 @@ def main(client, adgroup_id): 'startIndex': str(offset), 'numberResults': str(PAGE_SIZE) }, - 'ordering': [{'field': 'Id', 'sortOrder': 'ASCENDING'}] + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] } more_pages = True while more_pages: @@ -70,7 +70,7 @@ def main(client, adgroup_id): if 'entries' in page: for keyword in page['entries']: print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\'' % ( + '\'%s\' was found.' % ( keyword['criterion']['id'], keyword['criterion']['type'], keyword['criterion']['text'], diff --git a/examples/adxbuyer/v201502/__init__.py b/examples/adxbuyer/v201502/__init__.py deleted file mode 100644 index 55fdaeac..00000000 --- a/examples/adxbuyer/v201502/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Examples for DoubleClick Ad Exchange Buyer SOAP API.""" diff --git a/examples/adxbuyer/v201502/basic_operations/__init__.py b/examples/adxbuyer/v201502/basic_operations/__init__.py deleted file mode 100644 index 80acbea9..00000000 --- a/examples/adxbuyer/v201502/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Basic operations examples.""" diff --git a/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py b/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py deleted file mode 100755 index ec1dd7b2..00000000 --- a/examples/adxbuyer/v201502/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201502') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adxbuyer/v201502/basic_operations/add_campaigns.py b/examples/adxbuyer/v201502/basic_operations/add_campaigns.py deleted file mode 100755 index 1b2f4416..00000000 --- a/examples/adxbuyer/v201502/basic_operations/add_campaigns.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds campaigns. To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201502') - budget_service = client.GetService('BudgetService', version='v201502') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'DISPLAY', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPM', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'settings': [{ - 'xsi_type': 'RealTimeBiddingSetting', - 'optIn': 'true' - }], - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - } - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise Banners #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'DISPLAY', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPM', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'settings': [{ - 'xsi_type': 'RealTimeBiddingSetting', - 'optIn': 'true' - }], - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adxbuyer/v201502/basic_operations/add_placements.py b/examples/adxbuyer/v201502/basic_operations/add_placements.py deleted file mode 100755 index 88a853c6..00000000 --- a/examples/adxbuyer/v201502/basic_operations/add_placements.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct keyword ad group criterion object. - placement1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'http://mars.google.com' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'destinationUrl': 'http://example.com/mars' - } - - placement2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'http://example.com/pluto' - }, - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': placement1 - }, - { - 'operator': 'ADD', - 'operand': placement2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Placement ad group criterion with ad group id \'%s\', criterion ' - 'id \'%s\', and url \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py deleted file mode 100755 index 8097343f..00000000 --- a/examples/adxbuyer/v201502/basic_operations/add_third_party_redirect_ad.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds several third party ads to a given ad group. - -To get an ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct operations and add ads. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ThirdPartyRedirectAd', - 'name': 'Example third party ad #%s' % uuid.uuid4(), - 'url': 'http://www.example.com', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - # This field normally contains the javascript ad tag. - 'snippet': (''), - 'certifiedVendorFormatId': '232', - 'isCookieTargeted': 'false', - 'isUserInterestTargeted': 'false', - 'isTagged': 'false', - 'richMediaAdType': 'STANDARD', - 'expandingDirections': ['EXPANDING_UP', 'EXPANDING_DOWN'], - 'adAttributes': ['ROLL_OVER_TO_EXPAND'] - } - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ThirdPartyRedirectAd', - 'name': 'Example third party ad #%s' % uuid.uuid4(), - 'url': 'http://www.example.com', - 'adDuration': '15000', - 'sourceUrl': ('http://ad.doubleclick.net/pfadx/N270.126913.' - '6102203221521/B3876671.21;dcadv=2215309;' - 'sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml'), - 'certifiedVendorFormatId': '303', - 'richMediaAdType': 'IN_STREAM_VIDEO' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with ID \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201502/basic_operations/get_placements.py b/examples/adxbuyer/v201502/basic_operations/get_placements.py deleted file mode 100755 index 88f52bec..00000000 --- a/examples/adxbuyer/v201502/basic_operations/get_placements.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 group criteria in an account. - -To add placements, run add_placements.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['AdGroupId', 'Id', 'PlacementUrl'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['PLACEMENT'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for criterion in page['entries']: - print ('Placement ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\' and url \'%s\'.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) - else: - print 'No placements were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py b/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py deleted file mode 100755 index 593d9660..00000000 --- a/examples/adxbuyer/v201502/basic_operations/get_third_party_redirect_ads.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 third party ads for a given ad group. - -To add a third party ad, add_third_party_redirect_ad.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201502') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['THIRD_PARTY_REDIRECT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201502/basic_operations/remove_placement.py b/examples/adxbuyer/v201502/basic_operations/remove_placement.py deleted file mode 100755 index d2fd0d30..00000000 --- a/examples/adxbuyer/v201502/basic_operations/remove_placement.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_placements.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adxbuyer/v201502/basic_operations/update_placement.py b/examples/adxbuyer/v201502/basic_operations/update_placement.py deleted file mode 100755 index faea2ccc..00000000 --- a/examples/adxbuyer/v201502/basic_operations/update_placement.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 updates the bid of a placement. - -To add a placement, run add_placements.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_PLACEMENT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct operations and update bids. - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' had its bid set to \'%s\'.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['bids']['maxCpc']['amount']['microAmount'])) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adxbuyer/v201502/campaign_management/__init__.py b/examples/adxbuyer/v201502/campaign_management/__init__.py deleted file mode 100644 index db098bda..00000000 --- a/examples/adxbuyer/v201502/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Campaign management examples.""" diff --git a/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py deleted file mode 100755 index e6d43230..00000000 --- a/examples/adxbuyer/v201502/campaign_management/add_placements_in_bulk.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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. - -"""Illustrates how to perform asynchronous requests using the MutateJobService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import random -import re -import time - -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -PLACEMENT_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201502') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add placements. - for i in range(PLACEMENT_NUMBER): - url = 'www.example.com/mars%d' % i - if random.randint(1, 10) == 1: - url = 'NOT_@_URL' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': url - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - url = operations[index]['operand']['criterion']['url'] - print ('ERROR - placement \'%s\' failed due to \'%s\'' % - (url, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201502/error_handling/__init__.py b/examples/adxbuyer/v201502/error_handling/__init__.py deleted file mode 100644 index b5203c57..00000000 --- a/examples/adxbuyer/v201502/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Error handling examples.""" diff --git a/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py deleted file mode 100755 index 94e360e1..00000000 --- a/examples/adxbuyer/v201502/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201502') - - # Construct placement ad group criteria objects. - placements = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'www.example.com/something' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'INVALID!!_URL' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'www.example.com/somethingelse' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'BAD!!_URL' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for placement in placements: - operations.append( - { - 'operator': 'ADD', - 'operand': placement - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added placement ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\' and url \'%s\'' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Placement ad group criterion with ad group id \'%s\' and url ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (placements[int(index[0])]['adGroupId'], - placements[int(index[0])]['criterion']['url'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py index d41ac526..c6ba0516 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/dfp/authentication/generate_refresh_token.py @@ -17,6 +17,7 @@ """Generates a refresh token for use with DFP.""" +import argparse import sys from oauth2client import client @@ -29,13 +30,24 @@ # The DFP API OAuth 2.0 scope. SCOPE = u'https://www.googleapis.com/auth/dfp' +parser = argparse.ArgumentParser(description='Generates a refresh token with ' + 'the provided credentials.') +parser.add_argument('--client_id', default=CLIENT_ID, + help='Client Id retrieved from the Developer\'s Console.') +parser.add_argument('--client_secret', default=CLIENT_SECRET, + help='Client Secret retrieved from the Developer\'s ' + 'Console.') +parser.add_argument('--additional_scopes', default=None, + help='Additional scopes to apply when generating the ' + 'refresh token. Each scope should be separated by a comma.') -def main(): + +def main(client_id, client_secret, scopes): """Retrieve and display the access and refresh token.""" flow = client.OAuth2WebServerFlow( - client_id=CLIENT_ID, - client_secret=CLIENT_SECRET, - scope=[SCOPE], + client_id=client_id, + client_secret=client_secret, + scope=scopes, user_agent='Ads Python Client Library', redirect_uri='urn:ietf:wg:oauth:2.0:oob') @@ -58,4 +70,10 @@ def main(): if __name__ == '__main__': - main() + args = parser.parse_args() + configured_scopes = [SCOPE] + if args.client_id == CLIENT_ID or args.client_secret == CLIENT_SECRET: + raise AttributeError('No client_id or client_secret specified.') + if args.additional_scopes: + configured_scopes.extend(args.additional_scopes.replace(' ', '').split(',')) + main(args.client_id, args.client_secret, configured_scopes) diff --git a/googleads/adwords.py b/googleads/adwords.py index 81ad7187..c0a2509a 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -22,9 +22,11 @@ import urllib2 from xml.etree import ElementTree + import suds.client import suds.mx.literal import suds.xsd.doctor +import xmltodict import googleads.common import googleads.errors @@ -32,49 +34,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201502': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'GeoLocationService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'MutateJobService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - }, 'v201506': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', @@ -317,16 +276,28 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], return googleads.common.SudsServiceProxy( client, _AdWordsHeaderHandler(self, version)) - def GetBatchJobHelper(self): + def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], + server=_DEFAULT_ENDPOINT): """Returns a BatchJobHelper to work with the BatchJobService. This is a convenience method. It is functionally identical to calling BatchJobHelper(adwords_client, version). + Args: + [optional] + version: A string identifying the AdWords version to connect to. This + defaults to what is currently the latest version. This will be updated + in future releases to point to what is then the latest version. + server: A string identifying the webserver hosting the AdWords API. + Returns: An initialized BatchJobHelper tied to this client. """ - return BatchJobHelper(self) + request_builder = BatchJobHelper.GetRequestBuilder( + client=self, version=version, server=server) + response_parser = BatchJobHelper.GetResponseParser() + + return BatchJobHelper(request_builder, response_parser) def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=_DEFAULT_ENDPOINT): @@ -438,28 +409,310 @@ def GetReportDownloadHeaders(self, kwargs): class BatchJobHelper(object): """A utility that simplifies working with the BatchJobService.""" - # Used to remove namespace from xsi:type Element attributes. - _ATTRIB_NAMESPACE_SUB = re.compile('ns[0-1]:') - _UPLOAD_REQUEST_BODY_TEMPLATE = """ -%s -""" - def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1]): + class AbstractResponseParser(object): + """Interface for parsing responses from the BatchJobService.""" + + def ParseResponse(self, batch_job_response): + """Parses a Batch Job Service response.. + + Args: + batch_job_response: a str containing the response from the + BatchJobService. + """ + raise NotImplementedError('You must subclass' + 'AbstractResponseParser.') + + class _XMLToDictResponseParser(AbstractResponseParser): + """Parses responses from the BatchJobService, returning as a dictionary.""" + + def ParseResponse(self, batch_job_response): + """Parses a Batch Job Service response. + + Args: + batch_job_response: a str containing the response from the + BatchJobService. + + Returns: + An OrderedDict containing the Batch Job Service response. + """ + return xmltodict.parse(batch_job_response) + + class AbstractUploadRequestBuilder(object): + """Interface for building requests used to upload batch job operations.""" + + def BuildUploadRequest(self, upload_url, operations, **kwargs): + """Builds the BatchJob upload request. + + Args: + upload_url: a string url that the given operations will be uploaded to. + operations: a list where each element is a list containing operations + for a single AdWords Service. + **kwargs: optional keyword arguments. + + Returns: + A urllib2.Request instance with the correct method, headers, and + padding (if required) for the batch job upload. + """ + raise NotImplementedError('You must subclass' + 'AbstractUploadRequestBuilder.') + + class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): + """Builds requests used to upload operations for Batch Jobs.""" + # Used to remove namespace from xsi:type Element attributes. + _ATTRIB_NAMESPACE_SUB = re.compile('ns[0-1]:') + # Components of the upload request. + _UPLOAD_PREFIX_TEMPLATE = """ +""" + _UPLOAD_SUFFIX = '' + # Incremental uploads must have a content-length that is a multiple of this. + _BATCH_JOB_INCREMENT = 262144 + + def __init__(self, **kwargs): + """Initializes a _SudsUploadRequestBuilder. + + Arguments: + **kwargs: Keyword arguments. + + Keyword Arguments: + client: an AdWordsClient instance. + version: a string identifying the AdWords version to connect to. + server: a string identifying the webserver hosting the AdWords API. + + Raises: + AttributeError: if no client is specified in the Keyword Arguments. + """ + if 'client' not in kwargs: + raise AttributeError('No client specified for Request Builder.') + + self._client = kwargs['client'] + self._version = kwargs.get('version', sorted(_SERVICE_MAP.keys())[-1]) + server = kwargs.get('server', _DEFAULT_ENDPOINT) + self._adwords_endpoint = ('%s/api/adwords/cm/%s' % + (server, self._version)) + self._adwords_namespace = ('{%s}' % self._adwords_endpoint) + # Used to remove the AdWords namespace from Element tags. + self._tag_namespace_sub = re.compile(self._adwords_namespace) + + def BuildUploadRequest(self, upload_url, operations, **kwargs): + """Builds the BatchJob upload request. + + Args: + upload_url: a string url that the given operations will be uploaded to. + operations: a list where each element is a list containing operations + for a single AdWords Service. + **kwargs: optional keyword arguments. + + Keyword Arguments: + current_content_length: an integer indicating the current total content + length of an incremental upload request. If this keyword argument is + provided, this request will be handled as an incremental upload. + is_last: a boolean indicating whether this is the final request in an + incremental upload. + + Returns: + A urllib2.Request instance with the correct method, headers, and + padding (if required) for the batch job upload. + """ + is_incremental = 'current_content_length' in kwargs + current_content_length = kwargs.get('current_content_length', 0) + is_last = kwargs.get('is_last') if is_incremental else True + # Generate an unpadded request body + request_body = self._BuildUploadRequestBody( + operations, + has_prefix=current_content_length == 0, + has_suffix=is_last) + req = urllib2.Request(upload_url) + req.add_header('Content-Type', 'application/xml') + # Add padding, headers, and modify request method for incremental upload. + if is_incremental: + # Determine length of this message and the required padding. + new_content_length = current_content_length + request_length = len(request_body.encode('utf-8')) + padding_length = self._GetPaddingLength(request_length) + padded_request_length = request_length + padding_length + new_content_length += padded_request_length + request_body += ' ' * padding_length + req.get_method = lambda: 'PUT' # Modify this into a PUT request. + req.add_header('Content-Length', padded_request_length) + req.add_header('Content-Range', 'bytes %s-%s/%s' % ( + current_content_length, + new_content_length - 1, + new_content_length if is_last else '*' + )) + req.data = request_body + return req + + def _BuildUploadRequestBody(self, operations, has_prefix=True, + has_suffix=True): + """Builds an unpadded body containing operations for a BatchJob upload. + + Args: + operations: a list where each element is a list containing operations + for a single AdWords Service. + has_prefix: a boolean indicating whether the prefix should be included + in the request body. + has_suffix: a boolean indicating whether the suffic should be included + in the request body. + + Returns: + A string containing the unpadded batch job upload request body. + """ + operations_xml = ''.join([ + self._GenerateOperationsXML(operations_list) + for operations_list in operations]) + request_body = '%s%s%s' % ((self._UPLOAD_PREFIX_TEMPLATE % + self._adwords_endpoint) if has_prefix else '', + operations_xml, + self._UPLOAD_SUFFIX if has_suffix else '') + return request_body + + def _ExtractOperations(self, full_soap_xml): + """Extracts operations from API Request XML for use with BatchJobService. + + Args: + full_soap_xml: The full XML for the desired operation, as generated by + suds. + + Returns: + A string containing only the operations portion of the full XML request, + formatted for use with the BatchJobService. If no operations are found, + returns an empty string. + + Raises: + GoogleAdsValueErrorr: If no Operation.Type element is found in the + operations. This ordinarily happens if no xsi_type is specified for the + operations. + """ + # Extract mutate element from XML, this contains the operations. + mutate = self._GetRawOperationsFromXML(full_soap_xml) + # Ensure operations are formatted correctly for BatchJobService. + for operations in mutate: + self._FormatForBatchJobService(operations) + # Extract the operation type, ensure xsi:type is set for + # BatchJobService. Even if xsi_type is set earlier, suds will end up + # removing it when it sets Operation.Type. + operation_type = operations.find('Operation.Type') + if operation_type is None: + raise googleads.errors.GoogleAdsValueError('No xsi_type specified ' + 'for the operations.') + operations.attrib['xsi:type'] = operation_type.text + operations_xml = ''.join([ElementTree.tostring(operations) + for operations in mutate]) + # Force removal of this line, which suds produces. + operations_xml = operations_xml.replace( + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"', '') + return operations_xml + + def _FormatForBatchJobService(self, element): + """Formats contents of all operations for use with the BatchJobService. + + This will recursively remove unnecessary namespaces generated by suds that + would prevent the operations from executing via the BatchJobService. It + will also remove namespaces appended to the xsi:type in some cases that + also cause issues for the BatchJobService. + + Args: + element: a starting Element to be modified to the correct format. + """ + # Remove any unnecessary AdWords namespace from the tag. + element.tag = self._tag_namespace_sub.sub('', element.tag) + xsi_type = element.attrib.get( + '{http://www.w3.org/2001/XMLSchema-instance}type') + # If an xsi_type attribute exists, ensure that the namespace is removed + # from the type. + if xsi_type: + element.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'] = ( + self._ATTRIB_NAMESPACE_SUB.sub('', xsi_type)) + for child in element: + self._FormatForBatchJobService(child) + + def _GenerateOperationsXML(self, operations): + """Generates XML for the given list of operations. + + Args: + operations: a list of operations for single AdWords Service. + + Returns: + A str containing the XML for only the operations, formatted to work with + the BatchJobService. + + Raises: + GoogleAdsValueError: if no xsi_type is specified for the operations. + """ + if operations: + # Verify that all operations included specify an xsi_type. + for operation in operations: + if 'xsi_type' not in operation: + raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( + 'Operations have no xsi_type specified.') + return self._ExtractOperations(self._GenerateRawRequestXML(operations)) + else: + return '' + + def _GenerateRawRequestXML(self, operations): + """Generates the raw XML for the operations sent to the given service. + + Args: + operations: a list containing operations that could be run by the given + service. + + Returns: + A str containing the raw XML of the request to the given service that + would execute the given operations. + """ + service_name = operations[0]['xsi_type'].replace('Operation', 'Service') + service = self._client.GetService(service_name, self._version) + service.suds_client.set_options(nosend=True) + service_request = service.mutate(operations).envelope + service.suds_client.set_options(nosend=False) + return service_request + + def _GetPaddingLength(self, length): + """Retrieve the padding to be used in an incremental upload. + + Args: + length: an integer containing the length of the operations XML to be + uploaded as part of a batch job. + Returns: + An integer indicating the required padding to be applied in an + incremental batch job upload request. + """ + padding = self._BATCH_JOB_INCREMENT - (length % self._BATCH_JOB_INCREMENT) + return 0 if padding == self._BATCH_JOB_INCREMENT else padding + + def _GetRawOperationsFromXML(self, raw_request_xml): + """Retrieve the raw set of operations from the request XML. + + Args: + raw_request_xml: The full XML for the desired operation, as generated by + suds. + + Returns: + An unmodified mutate Element containing the operations from the raw + request xml. + + Raises: + AttributeError: if the provided XML isn't from AdWords. + """ + root = ElementTree.fromstring(raw_request_xml.encode('utf-8')) + return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( + '%smutate' % self._adwords_namespace) + + def __init__(self, request_builder, response_parser): """Initializes the BatchJobHelper. + For general use, consider using AdWordsClient's GetBatchJobHelper method to + receive an initialized BatchJobHelper using the default request builder and + response parser. + Args: - adwords_client: an initialized AdWordsClient. - version: a str indicating version of the AdWords API you intend to use. - This will be set to the latest version of AdWords by default. + request_builder: an AbstractUploadRequestBuilder instance. + response_parser: an AbstractResponseParser instance. """ - self.client = adwords_client self._temporary_id = 0 # Used for temporary IDs in BatchJobService. - self._version = version - self._adwords_endpoint = ('https://adwords.google.com/api/adwords/cm/%s' % - self._version) - self._adwords_namespace = ('{%s}' % self._adwords_endpoint) - # Used to remove the AdWords namespace from Element tags. - self._tag_namespace_sub = re.compile(self._adwords_namespace) + self._request_builder = request_builder + self._response_parser = response_parser def GetId(self): """Produces a distinct sequential ID for the BatchJobService. @@ -470,139 +723,108 @@ def GetId(self): self._temporary_id -= 1 return self._temporary_id - def UploadBatchJobOperations(self, upload_url, *operations): - """Uploads operations to the given uploadUrl. + def GetIncrementalUploadHelper(self, upload_url): + return IncrementalUploadHelper(self._request_builder, upload_url) - Note: Each list of operations is expected to contain operations of the same - type, similar to how one would normally send operations in an AdWords API - Service request. - - Args: - upload_url: a string url that the given operations will be uploaded to. - *operations: one or more lists of operations as would be sent to the - AdWords API for the associated service. - """ - operations_xml = ''.join([ - self._GenerateOperationsXML(operations_list) - for operations_list in operations]) + @classmethod + def GetRequestBuilder(cls, **kwargs): + """Get a new AbstractUploadRequestBuilder instance.""" + return cls._SudsUploadRequestBuilder(**kwargs) - request_body = (self._UPLOAD_REQUEST_BODY_TEMPLATE % - (self._adwords_endpoint, operations_xml)) + @classmethod + def GetResponseParser(cls, **kwargs): + """Get a new AbstractResponseParser instance.""" + return cls._XMLToDictResponseParser(**kwargs) - req = urllib2.Request(upload_url) - req.add_header('Content-Type', 'application/xml') - urllib2.urlopen(req, data=request_body) + def ParseResponse(self, batch_job_response): + """Parses a Batch Job Service response and returns it as a suds object. - def _GenerateOperationsXML(self, operations): - """Generates XML for the given list of operations. + Note: Unlike suds objects generated via an API call with suds, type + information will be lost. All values are strings. Args: - operations: a list of operations for single AdWords Service. + batch_job_response: a str containing the response from the + BatchJobService. + Returns: - A str containing the XML for only the operations, formatted to work - with the BatchJobService. - Raises: - ValueError: if no xsi_type is specified for the operations. + A suds object response generated from the provided batch_job_response. """ - if operations: - # Verify that all operations included specify an xsi_type. - for operation in operations: - if 'xsi_type' not in operation: - raise ValueError('Operations have no xsi_type specified.') - return self._ExtractOperations(self._GenerateRawRequestXML(operations)) - else: - return '' + return self._response_parser.ParseResponse(batch_job_response) - def _GenerateRawRequestXML(self, operations): - """Generates the raw XML for the operations sent to the given service. + def UploadOperations(self, upload_url, *operations): + """Uploads all operations to the given uploadUrl in a single request. - Args: - operations: a list containing operations that could be run by the given - service. + Note: Each list of operations is expected to contain operations of the same + type, similar to how one would normally send operations in an AdWords API + Service request. - Returns: - A str containing the raw XML of the request to the given service that - would execute the given operations. + Args: + upload_url: a string url that the given operations will be uploaded to. + *operations: one or more lists of operations as would be sent to the + AdWords API for the associated service. """ - service_name = operations[0]['xsi_type'].replace('Operation', 'Service') - service = self.client.GetService(service_name, self._version) - service.suds_client.set_options(nosend=True) - service_request = service.mutate(operations).envelope - service.suds_client.set_options(nosend=False) - return service_request + req = self._request_builder.BuildUploadRequest(upload_url, operations) + urllib2.urlopen(req) - def _ExtractOperations(self, full_soap_xml): - """Extracts operations from API Request XML for use with BatchJobService. - Args: - full_soap_xml: The full XML for the desired operation, as generated by - suds. +class IncrementalUploadHelper(object): + """A utility for uploading operations for a BatchJob incrementally.""" - Returns: - A string containing only the operations portion of the full XML request, - formatted for use with the BatchJobService. If no operations are found, - returns an empty string. + def __init__(self, request_builder, upload_url, current_content_length=0, + is_last=False): + """Initializes the IncrementalUpload. + Args: + request_builder: an AbstractUploadRequestBuilder instance. + upload_url: a string url that the given operations will be uploaded to. + current_content_length: an integer identifying the current content length + of data uploaded to the Batch Job. + is_last: a boolean indicating whether this is the final increment. Raises: - ValueError: If no Operation.Type element is found in the operations. This - ordinarily happens if no xsi_type is specified for the operations. + GoogleAdsValueError: if the content length is lower than 0. """ - # Extract mutate element from XML, this contains the operations. - mutate = BatchJobHelper._GetRawOperationsFromXML(self, full_soap_xml) - # Ensure operations are formatted correctly for BatchJobService. - for operations in mutate: - self._FormatForBatchJobService(operations) - # Extract the operation type, ensure xsi:type is set for - # BatchJobService. Even if xsi_type is set earlier, suds will end up - # removing it when it sets Operation.Type. - operation_type = operations.find('Operation.Type') - if operation_type is None: - raise ValueError('No xsi_type specified for the operations.') - operations.attrib['xsi:type'] = operation_type.text - operations_xml = ''.join([ElementTree.tostring(operations) - for operations in mutate]) - return operations_xml - - def _FormatForBatchJobService(self, element): - """Formats contents of all operations for use with the BatchJobService. - - This will recursively remove unnecessary namespaces generated by suds that - would prevent the operations from executing via the BatchJobService. It will - also remove namespaces appended to the xsi:type in some cases that also - cause issues for the BatchJobService. + self._request_builder = request_builder + self._upload_url = upload_url + if current_content_length < 0: + raise googleads.errors.GoogleAdsValueError( + 'Current content length %s is < 0.' % current_content_length) + self._current_content_length = current_content_length + self._is_last = is_last - Args: - element: a starting Element to be modified to the correct format. - """ - # Remove any unnecessary AdWords namespace from the tag. - element.tag = self._tag_namespace_sub.sub('', element.tag) - xsi_type = element.attrib.get( - '{http://www.w3.org/2001/XMLSchema-instance}type') - # If an xsi_type attribute exists, ensure that the namespace is removed from - # the type. - if xsi_type: - element.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'] = ( - self._ATTRIB_NAMESPACE_SUB.sub('', xsi_type)) - for child in element: - self._FormatForBatchJobService(child) - - def _GetRawOperationsFromXML(self, raw_request_xml): - """Retrieve the raw set of operations from the request XML. + def UploadOperations(self, operations, is_last=False): + """Uploads operations to the given uploadUrl in incremental steps. + + Note: Each list of operations is expected to contain operations of the + same type, similar to how one would normally send operations in an + AdWords API Service request. Args: - raw_request_xml: The full XML for the desired operation, as generated by - suds. + operations: one or more lists of operations as would be sent to the + AdWords API for the associated service. + is_last: a boolean indicating whether this is the final increment to be + added to the batch job. Returns: - An unmodified mutate Element containing the operations from the raw - request xml. - - Raises: - AttributeError: if the provided XML isn't from AdWords. + A BatchJobHelper.BatchJobUploadStatus instance that should be provided in + requests to upload additional increments. """ - root = ElementTree.fromstring(raw_request_xml) - return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( - '%smutate' % self._adwords_namespace) + if self._is_last is True: + raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( + 'Can\'t add new operations to a completed incremental upload.') + # Build the request + req = self._request_builder.BuildUploadRequest( + self._upload_url, operations, + current_content_length=self._current_content_length, is_last=is_last) + # Make the request, ignoring the urllib2.HTTPError raised due to HTTP status + # code 308 (for resumable uploads). + try: + urllib2.urlopen(req) + except urllib2.HTTPError, e: + if e.code != 308: + raise urllib2.HTTPError(e) + # Update upload status. + self._current_content_length += len(req.data) + self._is_last = is_last class ReportDownloader(object): diff --git a/googleads/common.py b/googleads/common.py index ddd2ba9b..e051f9ff 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -27,7 +27,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.10.0' +VERSION = '3.11.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], diff --git a/googleads/errors.py b/googleads/errors.py index 618bc64e..89252f40 100644 --- a/googleads/errors.py +++ b/googleads/errors.py @@ -89,6 +89,11 @@ def __init__(self, type_, trigger, field_path, code, error, content): self.field_path = field_path +class AdWordsBatchJobServiceInvalidOperationError(GoogleAdsError): + """Error indicating that an upload operation is malformed.""" + pass + + class DfpReportError(GoogleAdsError): """Error indicating that a DFP report download request failed. diff --git a/setup.py b/setup.py index a8627d4f..9798d97a 100755 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ PACKAGES = ['googleads'] DEPENDENCIES = ['httplib2', 'oauth2client', 'suds-jurko', 'pysocks', 'pytz', - 'PyYAML'] + 'PyYAML', 'xmltodict'] CLASSIFIERS = [ 'Intended Audience :: Developers', diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 5f4b4be8..1cde8469 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -26,17 +26,31 @@ from xml.etree import ElementTree -import mock - import googleads.adwords import googleads.common import googleads.errors +import mock + PYTHON2 = sys.version_info[0] == 2 URL_REQUEST_PATH = ('urllib2' if PYTHON2 else 'urllib.request') CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] +def GetAdWordsClient(): + """Returns an initialized AdwordsClient for use in testing.""" + oauth_header = {'Authorization': 'header'} + client_customer_id = 'client customer id' + dev_token = 'N3v3rG0nN4Giv3Y0uUp' + user_agent = 'N3v3rG0nN4l37y0uDoWN' + oauth2_client = mock.Mock() + oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) + client = googleads.adwords.AdWordsClient( + dev_token, oauth2_client, user_agent, + client_customer_id=client_customer_id) + return client + + class AdWordsHeaderHandlerTest(unittest.TestCase): """Tests for the googleads.adwords._AdWordsHeaderHandler class.""" @@ -162,18 +176,10 @@ class AdWordsClientTest(unittest.TestCase): """Tests for the googleads.adwords.AdWordsClient class.""" def setUp(self): - oauth_header = {'Authorization': 'header'} - self.cache = None - self.client_customer_id = 'client customer id' - self.dev_token = 'developers developers developers' - self.user_agent = 'users users user' - self.oauth2_client = mock.Mock() - self.oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) self.https_proxy = 'myproxy:443' - self.adwords_client = googleads.adwords.AdWordsClient( - self.dev_token, self.oauth2_client, self.user_agent, - client_customer_id=self.client_customer_id, - https_proxy=self.https_proxy, cache=self.cache) + self.cache = None + self.adwords_client = GetAdWordsClient() + self.adwords_client.https_proxy = self.https_proxy self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.adwords_client, CURRENT_VERSION) @@ -181,7 +187,7 @@ def testLoadFromStorage(self): with mock.patch('googleads.common.LoadFromStorage') as mock_load: mock_load.return_value = { 'developer_token': 'abcdEFghIjkLMOpqRs', - 'oauth2_client': self.oauth2_client, + 'oauth2_client': mock.Mock(), 'user_agent': 'unit testing' } self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage(), @@ -256,8 +262,85 @@ class BatchJobHelperTest(unittest.TestCase): """Test suite for BatchJobHelper utility.""" + def setUp(self): + """Prepare tests.""" + self.client = GetAdWordsClient() + self.batch_job_helper = self.client.GetBatchJobHelper() + + def testGetId(self): + expected = [-x for x in range(1, 101)] + for value in expected: + self.assertEqual(value, self.batch_job_helper.GetId()) + + def testUploadOperations(self): + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + 'BuildUploadRequest') as mock_build_request: + mock_request = mock.MagicMock() + mock_build_request.return_value = mock_request + with mock.patch('urllib2.urlopen') as mock_urlopen: + self.batch_job_helper.UploadOperations([[]]) + mock_urlopen.assert_called_with(mock_request) + + +class BatchJobUploadRequestBuilderTest(unittest.TestCase): + + """Test suite for the BatchJobUploadRequestBuilder.""" + ENVELOPE_NS = 'http://schemas.xmlsoap.org/soap/envelope/' + def setUp(self): + """Prepare tests.""" + self.client = GetAdWordsClient() + self.request_builder = self.client.GetBatchJobHelper()._request_builder + self.upload_url = 'https://goo.gl/IaQQsJ' + self.sample_xml = ('!n3vERg0Nn4Run4r0und4NDd35Er7Y0u!~' + '') + self.complete_request_body = '%s%s%s' % ( + self.request_builder._UPLOAD_PREFIX_TEMPLATE % ( + self.request_builder._adwords_endpoint), + self.sample_xml, + self.request_builder._UPLOAD_SUFFIX) + self.request_body_complete = '%s%s%s' % ( + self.request_builder._UPLOAD_PREFIX_TEMPLATE % ( + self.request_builder._adwords_endpoint), + self.sample_xml, + self.request_builder._UPLOAD_SUFFIX) + self.request_body_start = '%s%s' % ( + self.request_builder._UPLOAD_PREFIX_TEMPLATE % + self.request_builder._adwords_endpoint, self.sample_xml) + self.request_body_end = '%s%s' % ( + self.sample_xml, + self.request_builder._UPLOAD_SUFFIX) + self.single_upload_headers = {'Content-type': 'application/xml'} + self.incremental_upload_headers = { + 'Content-type': 'application/xml', + 'Content-range': 'bytes %s-%s/*' % ( + self.request_builder._BATCH_JOB_INCREMENT, + (self.request_builder._BATCH_JOB_INCREMENT * 2) - 1 + ), + 'Content-length': self.request_builder._BATCH_JOB_INCREMENT + } + + @classmethod + def setUpClass(cls): + test_dir = os.path.dirname(__file__) + with open(os.path.join( + test_dir, 'data/batch_job_util_invalid_request.txt')) as handler: + cls.INVALID_API_REQUEST = handler.read() + with open(os.path.join( + test_dir, 'data/batch_job_util_not_request.txt')) as handler: + cls.NOT_API_REQUEST = handler.read() + with open(os.path.join( + test_dir, 'data/batch_job_util_raw_request_template.txt')) as handler: + cls.RAW_API_REQUEST_TEMPLATE = handler.read() + with open(os.path.join( + test_dir, 'data/batch_job_util_raw_operation_template.txt')) as handler: + cls.RAW_OPERATION_TEMPLATE = handler.read() + with open(os.path.join( + test_dir, 'data/batch_job_util_upload_template.txt')) as handler: + cls.UPLOAD_OPERATIONS_TEMPLATE = handler.read() + def GenerateBudgetOperations(self, operations): """Generates request containing given number of BudgetOperations. @@ -322,37 +405,52 @@ def GenerateValidRequest(self, operations): request = self.RAW_API_REQUEST_TEMPLATE % (ops_xml) return (ops, request) - def setUp(self): - """Prepare tests.""" - oauth_header = {'Authorization': 'header'} - client_customer_id = 'client customer id' - dev_token = '4W1NN3R15Y0U' - user_agent = 'users gonna use' - oauth2_client = mock.Mock() - oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) - self.client = googleads.adwords.AdWordsClient( - dev_token, oauth2_client, user_agent, - client_customer_id=client_customer_id) - self.batch_job_helper = self.client.GetBatchJobHelper() + def GenerateValidUnicodeRequest(self, operations): + """Generates a valid API request containing the given number of operations. - @classmethod - def setUpClass(cls): - test_dir = os.path.dirname(__file__) - with open(os.path.join( - test_dir, 'data/batch_job_util_invalid_request.txt')) as handler: - cls.INVALID_API_REQUEST = handler.read() - with open(os.path.join( - test_dir, 'data/batch_job_util_not_request.txt')) as handler: - cls.NOT_API_REQUEST = handler.read() - with open(os.path.join( - test_dir, 'data/batch_job_util_raw_request_template.txt')) as handler: - cls.RAW_API_REQUEST_TEMPLATE = handler.read() - with open(os.path.join( - test_dir, 'data/batch_job_util_raw_operation_template.txt')) as handler: - cls.RAW_OPERATION_TEMPLATE = handler.read() - with open(os.path.join( - test_dir, 'data/batch_job_util_upload_template.txt')) as handler: - cls.UPLOAD_OPERATIONS_TEMPLATE = handler.read() + Args: + operations: a positive int defining the number of BudgetOperations to be + generated. + + Returns: + A tuple containing the operations used to construct unicode containing a + valid API request. + """ + ops = self.GenerateUnicodeBudgetOperations(operations) + ops_xml = ''.join([self.RAW_OPERATION_TEMPLATE.decode('utf-8') % ( + op[u'operator'], op[u'xsi_type'], op[u'operand'][u'budgetId'], + op[u'operand'][u'name'], op[u'operand'][u'period'], + op[u'operand'][u'amount'][u'microAmount'], + op[u'operand'][u'deliveryMethod'] + ) for op in ops]) + request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % (ops_xml) + return (ops, request) + + def GenerateUnicodeBudgetOperations(self, operations): + """Generates request containing given number of BudgetOperations. + + Args: + operations: a positive int defining the number of BudgetOperations to be + generated. + Returns: + A list of dictionaries containing distinct BudgetOperations. + """ + return [{ + u'operator': u'ADD', + u'xsi_type': u'BudgetOperation', + u'operand': { + u'budgetId': str(i).decode('utf-8'), + u'name': u'アングリーバード Batch budget #%s' % i, + u'period': u'DAILY', + u'amount': {u'microAmount': str(3333333 * i).decode('utf-8')}, + u'deliveryMethod': u'STANDARD'} + } for i in range(1, operations + 1)] + + def testGetPaddingLength(self): + length = len(self.sample_xml) + padding = self.request_builder._GetPaddingLength(length) + self.assertTrue( + padding == self.request_builder._BATCH_JOB_INCREMENT - length) def testExtractOperations(self): """Tests whether operations XML was extracted and formatted correctly. @@ -360,11 +458,17 @@ def testExtractOperations(self): Verifies that the xsi_type has been properly assigned. """ operations = self.GenerateCampaignCriterionOperations(1) - raw_xml = self.batch_job_helper._GenerateRawRequestXML(operations) - operations_xml = self.batch_job_helper._ExtractOperations(raw_xml) + raw_xml = self.request_builder._GenerateRawRequestXML(operations) + operations_xml = self.request_builder._ExtractOperations(raw_xml) # Put operations in a format that allows us to easily verify the behavior. - ops_element = ElementTree.fromstring(operations_xml) - self.assertTrue(ops_element.tag == 'operations') + ElementTree.register_namespace( + 'xsi', 'http://www.w3.org/2001/XMLSchema-instance') + # Need to declare xsi for ElementTree to parse operations properly. + body = ElementTree.fromstring( + '%s' + '' % operations_xml) + self.assertTrue(body.tag == 'body') + ops_element = body.find('operations') # Check that the xsi_type has been set correctly. self.assertTrue(ops_element.attrib[ '{http://www.w3.org/2001/XMLSchema-instance}type'] == @@ -382,18 +486,18 @@ def testFormatForBatchJobService(self): """Tests whether namespaces have been removed.""" operations_amount = 5 ops = self.GenerateCampaignCriterionOperations(operations_amount) - root = ElementTree.fromstring(self.batch_job_helper._GenerateRawRequestXML( + root = ElementTree.fromstring(self.request_builder._GenerateRawRequestXML( ops)) body = root.find('{%s}Body' % self.ENVELOPE_NS) - mutate = body.find('{%s}mutate' % self.batch_job_helper._adwords_endpoint) - self.batch_job_helper._FormatForBatchJobService(mutate) - self.assertTrue(self.batch_job_helper._adwords_endpoint not in mutate.tag) + mutate = body.find('{%s}mutate' % self.request_builder._adwords_endpoint) + self.request_builder._FormatForBatchJobService(mutate) + self.assertTrue(self.request_builder._adwords_endpoint not in mutate.tag) self.assertTrue(len(mutate) == operations_amount) for ops in mutate: - self.assertTrue(self.batch_job_helper._adwords_endpoint not in ops.tag) + self.assertTrue(self.request_builder._adwords_endpoint not in ops.tag) for child in ops: - self.assertTrue(self.batch_job_helper._adwords_endpoint not in + self.assertTrue(self.request_builder._adwords_endpoint not in child.tag) operand = ops.find('operand') self.assertTrue(len(operand.attrib) == 1) @@ -401,14 +505,14 @@ def testFormatForBatchJobService(self): 'ns' not in operand.attrib['{http://www.w3.org/2001/XMLSchema-instance}type']) for child in operand: - self.assertTrue(self.batch_job_helper._adwords_endpoint not in + self.assertTrue(self.request_builder._adwords_endpoint not in child.tag) criterion = operand.find('criterion') self.assertTrue( 'ns' not in criterion.attrib['{http://www.w3.org/2001/XMLSchema-instance}type']) for child in criterion: - self.assertTrue(self.batch_job_helper._adwords_endpoint not in + self.assertTrue(self.request_builder._adwords_endpoint not in child.tag) def testGenerateOperationsXMLNoXsiType(self): @@ -416,14 +520,15 @@ def testGenerateOperationsXMLNoXsiType(self): """ operations = self.GenerateCampaignCriterionOperations(1) del operations[0]['xsi_type'] - self.assertRaises(ValueError, self.batch_job_helper._GenerateOperationsXML, - operations) + self.assertRaises( + googleads.errors.AdWordsBatchJobServiceInvalidOperationError, + self.request_builder._GenerateOperationsXML, operations) def testGenerateOperationsXMLWithNoOperations(self): """Tests whether _GenerateOperationsXML produces empty str if no operations. """ operations = self.GenerateCampaignCriterionOperations(0) - raw_xml = self.batch_job_helper._GenerateOperationsXML( + raw_xml = self.request_builder._GenerateOperationsXML( operations) self.assertTrue(raw_xml is '') @@ -433,49 +538,49 @@ def testGenerateRawRequestXMLFromSingleOperation(self): ops = self.GenerateBudgetOperations(operations_amount) root = ElementTree.fromstring( - self.batch_job_helper._GenerateRawRequestXML(ops)) + self.request_builder._GenerateRawRequestXML(ops)) self.assertTrue(len(root) == 2) body = root.find('{%s}Body' % self.ENVELOPE_NS) self.assertTrue(len(body) == 1) - mutate = body.find('{%s}mutate' % self.batch_job_helper._adwords_endpoint) + mutate = body.find('{%s}mutate' % self.request_builder._adwords_endpoint) self.assertTrue(len(mutate) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual(operations.tag, '{%s}operations' % - self.batch_job_helper._adwords_endpoint) + self.request_builder._adwords_endpoint) self.assertTrue(len(operations._children) == len(ops[i].keys())) self.assertEqual(operations.find( - '{%s}operator' % self.batch_job_helper._adwords_endpoint).text, + '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) self.assertEqual( operations.find( '{%s}Operation.Type' % - self.batch_job_helper._adwords_endpoint).text, + self.request_builder._adwords_endpoint).text, ops[i]['xsi_type']) operand = operations.find( - '{%s}operand' % self.batch_job_helper._adwords_endpoint) + '{%s}operand' % self.request_builder._adwords_endpoint) self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) self.assertEqual(operand.find( - '{%s}budgetId' % self.batch_job_helper._adwords_endpoint).text, + '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) self.assertEqual(operand.find( - '{%s}name' % self.batch_job_helper._adwords_endpoint).text, + '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) self.assertEqual( operand.find( '{%s}period' % - self.batch_job_helper._adwords_endpoint).text, + self.request_builder._adwords_endpoint).text, ops[i]['operand']['period']) amount = operand.find('{%s}amount' % - self.batch_job_helper._adwords_endpoint) + self.request_builder._adwords_endpoint) self.assertTrue(len(amount._children) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( - '{%s}microAmount' % self.batch_job_helper._adwords_endpoint).text, + '{%s}microAmount' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['amount']['microAmount']) self.assertEqual(operand.find( - '{%s}deliveryMethod' % self.batch_job_helper._adwords_endpoint).text, + '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['deliveryMethod']) def testGenerateRawRequestXMLFromMultipleOperations(self): @@ -484,54 +589,98 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): ops = self.GenerateBudgetOperations(operations_amount) root = ElementTree.fromstring( - self.batch_job_helper._GenerateRawRequestXML(ops)) + self.request_builder._GenerateRawRequestXML(ops)) self.assertTrue(len(root) == 2) body = root.find('{%s}Body' % self.ENVELOPE_NS) self.assertTrue(len(body) == 1) - mutate = body.find('{%s}mutate' % self.batch_job_helper._adwords_endpoint) + mutate = body.find('{%s}mutate' % self.request_builder._adwords_endpoint) self.assertTrue(len(mutate) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, - '{%s}operations' % self.batch_job_helper._adwords_endpoint) + '{%s}operations' % self.request_builder._adwords_endpoint) self.assertTrue(len(operations._children) == len(ops[i].keys())) self.assertEqual(operations.find( - '{%s}operator' % self.batch_job_helper._adwords_endpoint).text, + '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) self.assertEqual(operations.find( - '{%s}Operation.Type' % self.batch_job_helper._adwords_endpoint).text, + '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text, ops[i]['xsi_type']) operand = operations.find( - '{%s}operand' % self.batch_job_helper._adwords_endpoint) + '{%s}operand' % self.request_builder._adwords_endpoint) self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) self.assertEqual(operand.find( - '{%s}budgetId' % self.batch_job_helper._adwords_endpoint).text, + '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) self.assertEqual(operand.find( - '{%s}name' % self.batch_job_helper._adwords_endpoint).text, + '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) self.assertEqual(operand.find( - '{%s}period' % self.batch_job_helper._adwords_endpoint).text, + '{%s}period' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['period']) amount = operand.find( - '{%s}amount' % self.batch_job_helper._adwords_endpoint) + '{%s}amount' % self.request_builder._adwords_endpoint) self.assertTrue(len(amount._children) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( - '{%s}microAmount' % self.batch_job_helper._adwords_endpoint).text, + '{%s}microAmount' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['amount']['microAmount']) self.assertEqual(operand.find( - '{%s}deliveryMethod' % self.batch_job_helper._adwords_endpoint).text, + '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['deliveryMethod']) - def testGetId(self): - """Test whether the Ids generated are decreasing sequentially.""" - expected = [-x for x in range(1, 101)] + def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): + """Tests whether raw request xml can be produced from a single operation.""" + operations_amount = 1 + ops = self.GenerateUnicodeBudgetOperations(operations_amount) - for value in expected: - self.assertEqual(value, self.batch_job_helper.GetId()) + root = ElementTree.fromstring( + self.request_builder._GenerateRawRequestXML(ops)) + self.assertTrue(len(root) == 2) + body = root.find(u'{%s}Body' % self.ENVELOPE_NS) + self.assertTrue(len(body) == 1) + mutate = body.find(u'{%s}mutate' % self.request_builder._adwords_endpoint) + self.assertTrue(len(mutate) == operations_amount) + + for i in range(0, operations_amount): + operations = mutate[i] + self.assertEqual(operations.tag, '{%s}operations' % + self.request_builder._adwords_endpoint) + self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertEqual(operations.find( + '{%s}operator' % self.request_builder._adwords_endpoint).text, + ops[i]['operator']) + self.assertEqual( + operations.find( + '{%s}Operation.Type' % + self.request_builder._adwords_endpoint).text, + ops[i]['xsi_type']) + operand = operations.find( + '{%s}operand' % self.request_builder._adwords_endpoint) + self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertEqual(operand.find( + '{%s}budgetId' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['budgetId']) + self.assertEqual(operand.find( + '{%s}name' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['name']) + self.assertEqual( + operand.find( + '{%s}period' % + self.request_builder._adwords_endpoint).text, + ops[i]['operand']['period']) + amount = operand.find('{%s}amount' % + self.request_builder._adwords_endpoint) + self.assertTrue(len(amount._children) == + len(ops[i]['operand']['amount'].keys())) + self.assertEqual(amount.find( + '{%s}microAmount' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['amount']['microAmount']) + self.assertEqual(operand.find( + '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['deliveryMethod']) def testGetRawOperationsFromValidSingleOperationRequest(self): """Test whether operations XML can be retrieved for a single-op request. @@ -541,44 +690,44 @@ def testGetRawOperationsFromValidSingleOperationRequest(self): operations_amount = 1 ops, request = self.GenerateValidRequest(operations_amount) - mutate = self.batch_job_helper._GetRawOperationsFromXML(request) + mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual(mutate.tag, - '{%s}mutate' % self.batch_job_helper._adwords_endpoint) + '{%s}mutate' % self.request_builder._adwords_endpoint) self.assertTrue(len(mutate._children) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, - '{%s}operations' % self.batch_job_helper._adwords_endpoint) + '{%s}operations' % self.request_builder._adwords_endpoint) self.assertTrue(len(operations._children) == len(ops[i].keys())) self.assertEqual(operations.find( - '{%s}operator' % self.batch_job_helper._adwords_endpoint).text, + '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) self.assertEqual(operations.find( - '{%s}Operation.Type' % self.batch_job_helper._adwords_endpoint).text, + '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text, ops[i]['xsi_type']) operand = operations.find( - '{%s}operand' % self.batch_job_helper._adwords_endpoint) + '{%s}operand' % self.request_builder._adwords_endpoint) self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) self.assertEqual(operand.find( - '{%s}budgetId' % self.batch_job_helper._adwords_endpoint).text, + '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) self.assertEqual(operand.find( - '{%s}name' % self.batch_job_helper._adwords_endpoint).text, + '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) self.assertEqual(operand.find( - '{%s}period' % self.batch_job_helper._adwords_endpoint).text, + '{%s}period' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['period']) amount = operand.find( - '{%s}amount' % self.batch_job_helper._adwords_endpoint) + '{%s}amount' % self.request_builder._adwords_endpoint) self.assertTrue(len(amount._children) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( - '{%s}microAmount' % self.batch_job_helper._adwords_endpoint).text, + '{%s}microAmount' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['amount']['microAmount']) self.assertEqual(operand.find( - '{%s}deliveryMethod' % self.batch_job_helper._adwords_endpoint).text, + '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['deliveryMethod']) def testGetRawOperationsFromValidMultipleOperationRequest(self): @@ -589,45 +738,94 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): operations_amount = 5 ops, request = self.GenerateValidRequest(operations_amount) - mutate = self.batch_job_helper._GetRawOperationsFromXML(request) + mutate = self.request_builder._GetRawOperationsFromXML(request) + self.assertEqual( + mutate.tag, + '{%s}mutate' % self.request_builder._adwords_endpoint) + self.assertTrue(len(mutate._children) == operations_amount) + + for i in range(0, operations_amount): + operations = mutate[i] + self.assertEqual( + operations.tag, + '{%s}operations' % self.request_builder._adwords_endpoint) + self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertEqual(operations.find( + '{%s}operator' % self.request_builder._adwords_endpoint).text, + ops[i]['operator']) + self.assertEqual(operations.find( + '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text, + ops[i]['xsi_type']) + operand = (operations.find( + '{%s}operand' % self.request_builder._adwords_endpoint)) + self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertEqual(operand.find( + '{%s}budgetId' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['budgetId']) + self.assertEqual(operand.find( + '{%s}name' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['name']) + self.assertEqual(operand.find( + '{%s}period' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['period']) + amount = (operand.find( + '{%s}amount' % self.request_builder._adwords_endpoint)) + self.assertTrue(len(amount._children) == + len(ops[i]['operand']['amount'].keys())) + self.assertEqual(amount.find( + '{%s}microAmount' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['amount']['microAmount']) + self.assertEqual(operand.find( + '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text, + ops[i]['operand']['deliveryMethod']) + + def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): + """Test whether operations XML can be retrieved for a multi-op request. + + Also verifies that the contents of generated XML are correct. + """ + operations_amount = 5 + ops, request = self.GenerateValidUnicodeRequest(operations_amount) + + mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual( mutate.tag, - '{%s}mutate' % self.batch_job_helper._adwords_endpoint) + u'{%s}mutate' % self.request_builder._adwords_endpoint) self.assertTrue(len(mutate._children) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, - '{%s}operations' % self.batch_job_helper._adwords_endpoint) + '{%s}operations' % self.request_builder._adwords_endpoint) self.assertTrue(len(operations._children) == len(ops[i].keys())) self.assertEqual(operations.find( - '{%s}operator' % self.batch_job_helper._adwords_endpoint).text, + '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) self.assertEqual(operations.find( - '{%s}Operation.Type' % self.batch_job_helper._adwords_endpoint).text, + '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text, ops[i]['xsi_type']) operand = (operations.find( - '{%s}operand' % self.batch_job_helper._adwords_endpoint)) + '{%s}operand' % self.request_builder._adwords_endpoint)) self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) self.assertEqual(operand.find( - '{%s}budgetId' % self.batch_job_helper._adwords_endpoint).text, + '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) self.assertEqual(operand.find( - '{%s}name' % self.batch_job_helper._adwords_endpoint).text, + '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) self.assertEqual(operand.find( - '{%s}period' % self.batch_job_helper._adwords_endpoint).text, + '{%s}period' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['period']) amount = (operand.find( - '{%s}amount' % self.batch_job_helper._adwords_endpoint)) + '{%s}amount' % self.request_builder._adwords_endpoint)) self.assertTrue(len(amount._children) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( - '{%s}microAmount' % self.batch_job_helper._adwords_endpoint).text, + '{%s}microAmount' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['amount']['microAmount']) self.assertEqual(operand.find( - '{%s}deliveryMethod' % self.batch_job_helper._adwords_endpoint).text, + '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['deliveryMethod']) def testGetRawOperationsFromValidZeroOperationRequest(self): @@ -635,24 +833,228 @@ def testGetRawOperationsFromValidZeroOperationRequest(self): operations_amount = 0 _, request = self.GenerateValidRequest(operations_amount) - mutate = self.batch_job_helper._GetRawOperationsFromXML(request) + mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual( mutate.tag, - '{%s}mutate' % self.batch_job_helper._adwords_endpoint) + '{%s}mutate' % self.request_builder._adwords_endpoint) self.assertTrue(len(mutate._children) == operations_amount) def testGetRawOperationsFromInvalidRequest(self): """Test whether an invalid API request raises an Exception.""" self.assertRaises(AttributeError, - self.batch_job_helper._GetRawOperationsFromXML, + self.request_builder._GetRawOperationsFromXML, self.INVALID_API_REQUEST) def testGetRawOperationsFromNotXMLRequest(self): """Test whether non-XML input raises an Exception.""" self.assertRaises(ElementTree.ParseError, - self.batch_job_helper._GetRawOperationsFromXML, + self.request_builder._GetRawOperationsFromXML, self.NOT_API_REQUEST) + def testBuildRequestForSingleUpload(self): + """Test whether a single upload request is build correctly.""" + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_BuildUploadRequestBody') as mock_request_body_builder: + mock_request_body_builder.return_value = self.sample_xml + req = self.request_builder.BuildUploadRequest(self.upload_url, [[]]) + self.assertEqual(req.headers, self.single_upload_headers) + self.assertEqual(req.get_method(), 'POST') + + def testBuildRequestForIncrementalUpload(self): + """Test whether an incremental upload request is built correctly.""" + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_BuildUploadRequestBody') as mock_request_body_builder: + mock_request_body_builder.return_value = self.sample_xml + req = self.request_builder.BuildUploadRequest( + self.upload_url, [[]], + current_content_length=self.request_builder._BATCH_JOB_INCREMENT) + self.assertEqual(req.headers, self.incremental_upload_headers) + self.assertEqual(req.get_method(), 'PUT') + + def testBuildUploadRequestBody(self): + """Test whether a a complete request body is built correctly.""" + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_GenerateOperationsXML') as mock_generate_xml: + mock_generate_xml.return_value = self.sample_xml + with mock.patch('googleads.adwords.BatchJobHelper._' + 'SudsUploadRequestBuilder.' + '_GetPaddingLength') as mock_get_padding_length: + mock_get_padding_length.return_value = 0 + increment = self.request_builder._BuildUploadRequestBody([[]]) + self.assertTrue(increment == self.request_body_complete) + + def testBuildUploadRequestBodyWithSuffix(self): + """Test whether a request body is built correctly with only the suffix.""" + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_GenerateOperationsXML') as mock_generate_xml: + mock_generate_xml.return_value = self.sample_xml + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_GetPaddingLength') as mock_get_padding_length: + mock_get_padding_length.return_value = 0 + increment = self.request_builder._BuildUploadRequestBody( + [[]], has_prefix=False) + self.assertTrue(increment == self.request_body_end) + + def testBuildUploadRequestBodyWithoutPrefixOrSuffix(self): + """Test whether a request body is built correctly without prefix/suffix.""" + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_GenerateOperationsXML') as mock_generate_xml: + mock_generate_xml.return_value = self.sample_xml + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_GetPaddingLength') as mock_get_padding_length: + mock_get_padding_length.return_value = 0 + increment = self.request_builder._BuildUploadRequestBody( + [[]], has_prefix=False, has_suffix=False) + self.assertTrue(increment == self.sample_xml) + + def testBuildUploadRequestBodyWithOnlyPrefix(self): + """Test whether a request body is built correctly with only the prefix.""" + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_GenerateOperationsXML') as mock_generate_xml: + mock_generate_xml.return_value = self.sample_xml + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + '_GetPaddingLength') as mock_get_padding_length: + mock_get_padding_length.return_value = 0 + increment = self.request_builder._BuildUploadRequestBody( + [[]], has_suffix=False) + self.assertTrue(increment == self.request_body_start) + + +class IncrementalUploadHelperTest(unittest.TestCase): + + """Test suite for the IncrementalUploadHelper.""" + + def setUp(self): + """Prepare tests.""" + self.client = GetAdWordsClient() + self.batch_job_helper = self.client.GetBatchJobHelper() + self.incremental_uploader = ( + self.batch_job_helper.GetIncrementalUploadHelper( + 'https://goo.gl/Xtaq83')) + + def testUploadOperations(self): + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + 'BuildUploadRequest') as mock_build_request: + mock_request = mock.MagicMock() + mock_build_request.return_value = mock_request + with mock.patch('urllib2.urlopen') as mock_urlopen: + self.incremental_uploader.UploadOperations([[]], True) + mock_urlopen.assert_called_with(mock_request) + + def testUploadOperationsAfterFinished(self): + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + 'BuildUploadRequest') as mock_build_request: + mock_request = mock.MagicMock() + mock_build_request.return_value = mock_request + with mock.patch('urllib2.urlopen'): + self.incremental_uploader.UploadOperations([[]], True) + self.assertRaises( + googleads.errors.AdWordsBatchJobServiceInvalidOperationError, + self.incremental_uploader.UploadOperations, {}) + + +class ResponseParserTest(unittest.TestCase): + """Test suite for the ResponseParser.""" + + def setUp(self): + """Prepare tests.""" + self.client = GetAdWordsClient() + self.response_parser = googleads.adwords.BatchJobHelper.GetResponseParser() + + @classmethod + def setUpClass(cls): + test_dir = os.path.dirname(__file__) + with open(os.path.join( + test_dir, 'data/batch_job_util_response_template.txt')) as handler: + cls.API_RESPONSE_XML_TEMPLATE = handler.read() + + def testParseResponse(self): + campaign_id = '1' + name = 'Test Campaign' + status = 'PAUSED' + serving_status = 'SUSPENDED' + start_date = '20151116' + end_date = '20371230' + budget_id = '2' + budget_name = 'Test Budget' + period = 'DAILY' + micro_amount = '50000000' + delivery_method = 'STANDARD' + is_explicitly_shared = 'true' + bidding_strategy_type = 'MANUAL_CPC' + + response = ( + self.response_parser.ParseResponse( + self.API_RESPONSE_XML_TEMPLATE % + (campaign_id, name, status, + serving_status, start_date, + end_date, budget_id, + budget_name, period, + micro_amount, delivery_method, + is_explicitly_shared, + bidding_strategy_type)) + ['mutateResponse']['rval']) + + # Assert that we correct parsed the response (2 results: Budget & Campaign) + self.assertTrue(len(response) == 2) + + campaign = response[1]['result']['Campaign'] + self.assertTrue(campaign['id'] == campaign_id) + self.assertTrue(campaign['name'] == name) + self.assertTrue(campaign['status'] == status) + self.assertTrue(campaign['servingStatus'] == serving_status) + self.assertTrue(campaign['startDate'] == start_date) + self.assertTrue(campaign['endDate'] == end_date) + self.assertTrue(campaign['budget']['name'] == budget_name) + self.assertTrue(campaign['budget']['amount']['microAmount'] == micro_amount) + self.assertTrue(campaign['budget']['isExplicitlyShared'] == + is_explicitly_shared) + self.assertTrue( + campaign['biddingStrategyConfiguration']['biddingStrategyType'] == + bidding_strategy_type) + + def testParseUnicodeResponse(self): + campaign_id = u'1' + name = u'アングリーバード' + status = u'PAUSED' + serving_status = u'SUSPENDED' + start_date = u'20151116' + end_date = u'20371230' + budget_id = u'2' + budget_name = u'Test Budget' + period = u'DAILY' + micro_amount = u'50000000' + delivery_method = u'STANDARD' + is_explicitly_shared = u'true' + bidding_strategy_type = u'MANUAL_CPC' + + response = ( + self.response_parser.ParseResponse( + self.API_RESPONSE_XML_TEMPLATE % + (campaign_id, name, status, + serving_status, start_date, + end_date, budget_id, + budget_name, period, + micro_amount, delivery_method, + is_explicitly_shared, + bidding_strategy_type)) + ['mutateResponse']['rval']) + + self.assertTrue(len(response) == 2) + campaign = response[1]['result']['Campaign'] + self.assertTrue(campaign['name'] == name) + class ReportDownloaderTest(unittest.TestCase): """Tests for the googleads.adwords.ReportDownloader class.""" From fac5452dbe4a83c9303b26c29e3d753835c999d6 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 24 Nov 2015 11:29:31 -0500 Subject: [PATCH 022/180] Commiting latest changes. From 57fe3710c6ff95554415640a82f645d894eb1f96 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 4 Feb 2016 14:57:24 -0800 Subject: [PATCH 023/180] AdWords v201601 release. --- ChangeLog | 14 + README.md | 9 +- .../authentication/generate_refresh_token.py | 11 +- .../account_management/create_account.py | 1 - .../get_account_hierarchy.py | 1 - .../add_click_to_download_ad.py | 1 - .../v201506/basic_operations/add_keywords.py | 1 - .../v201506/basic_operations/add_text_ads.py | 1 - .../v201506/basic_operations/get_keywords.py | 1 - .../v201506/basic_operations/get_text_ads.py | 1 - .../basic_operations/remove_keyword.py | 1 - .../basic_operations/update_keyword.py | 1 - .../campaign_management/add_experiment.py | 1 - .../add_keywords_in_bulk.py | 1 - .../campaign_management/promote_experiment.py | 1 - .../campaign_management/set_ad_parameters.py | 1 - .../campaign_management/validate_text_ad.py | 1 - .../v201506/extensions/add_site_links.py | 1 - .../extensions/add_site_links_using_feeds.py | 1 - .../migrate_to_extension_settings.py | 1 - .../optimization/estimate_keyword_traffic.py | 1 - .../get_keyword_bid_simulations.py | 1 - .../v201506/optimization/get_keyword_ideas.py | 1 - .../reporting/download_criteria_report.py | 1 - .../download_criteria_report_as_stream.py | 1 - ...oad_criteria_report_as_stream_with_awql.py | 1 - .../download_criteria_report_as_string.py | 1 - ...oad_criteria_report_as_string_with_awql.py | 1 - .../download_criteria_report_with_awql.py | 1 - .../account_management/create_account.py | 1 - .../get_account_hierarchy.py | 81 +-- .../add_click_to_download_ad.py | 1 - .../add_complete_campaigns_using_batch_job.py | 1 - .../advanced_operations/add_html5_ad.py | 1 - ...dd_keywords_using_incremental_batch_job.py | 1 - .../v201509/basic_operations/add_ad_groups.py | 7 +- .../v201509/basic_operations/add_keywords.py | 1 - .../v201509/basic_operations/add_text_ads.py | 1 - .../v201509/basic_operations/get_keywords.py | 1 - .../v201509/basic_operations/get_text_ads.py | 1 - .../basic_operations/remove_keyword.py | 1 - .../basic_operations/update_keyword.py | 1 - .../campaign_management/add_experiment.py | 1 - .../add_keywords_in_bulk.py | 1 - .../campaign_management/promote_experiment.py | 1 - .../campaign_management/set_ad_parameters.py | 1 - .../campaign_management/validate_text_ad.py | 1 - .../v201509/extensions/add_site_links.py | 1 - .../extensions/add_site_links_using_feeds.py | 1 - .../migrate_to_extension_settings.py | 1 - .../v201509/misc/upload_media_bundle.py | 1 - .../optimization/estimate_keyword_traffic.py | 1 - .../get_keyword_bid_simulations.py | 1 - .../v201509/optimization/get_keyword_ideas.py | 1 - .../remarketing/add_crm_based_user_list.py | 6 +- .../reporting/download_criteria_report.py | 1 - .../download_criteria_report_as_stream.py | 1 - ...oad_criteria_report_as_stream_with_awql.py | 1 - .../download_criteria_report_as_string.py | 1 - ...oad_criteria_report_as_string_with_awql.py | 1 - .../download_criteria_report_with_awql.py | 1 - .../v201601}/__init__.py | 4 +- .../v201601/account_management/__init__.py | 15 + .../account_management/create_account.py | 64 +++ .../account_management/get_account_changes.py | 104 ++++ .../get_account_hierarchy.py | 105 ++++ .../v201601/advanced_operations}/__init__.py | 4 +- .../advanced_operations/add_ad_customizer.py | 222 ++++++++ .../add_ad_group_bid_modifier.py | 76 +++ .../add_click_to_download_ad.py | 109 ++++ .../advanced_operations/add_html5_ad.py | 112 ++++ ...dd_keywords_using_incremental_batch_job.py | 214 +++++++ .../add_text_ad_with_upgraded_urls.py | 112 ++++ .../create_and_attach_shared_keyword_set.py | 129 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 +++++ .../get_ad_group_bid_modifier.py | 74 +++ .../use_shared_bidding_strategy.py | 173 ++++++ .../v201601}/basic_operations/__init__.py | 2 +- .../basic_operations/add_ad_groups.py | 39 +- .../basic_operations/add_campaigns.py | 45 +- .../v201601/basic_operations/add_keywords.py} | 35 +- .../v201601/basic_operations/add_text_ads.py} | 62 +- .../basic_operations/get_ad_groups.py} | 38 +- .../basic_operations/get_campaigns.py} | 43 +- .../get_campaigns_with_awql.py | 65 +++ .../v201601/basic_operations/get_keywords.py} | 48 +- .../v201601/basic_operations/get_text_ads.py} | 10 +- .../v201601/basic_operations/pause_ad.py | 62 ++ .../v201601/basic_operations/remove_ad.py | 63 +++ .../basic_operations/remove_ad_group.py | 59 ++ .../basic_operations/remove_campaign.py | 59 ++ .../basic_operations/remove_keyword.py} | 7 +- .../basic_operations/update_ad_group.py} | 52 +- .../basic_operations/update_campaign.py | 59 ++ .../basic_operations/update_keyword.py} | 24 +- .../v201601}/campaign_management/__init__.py | 2 +- .../add_campaign_labels.py} | 47 +- .../add_complete_campaigns_using_batch_job.py | 428 ++++++++++++++ .../campaign_management/add_experiment.py | 128 +++++ .../add_keywords_in_bulk.py} | 27 +- .../get_all_disapproved_ads.py | 75 +++ .../get_all_disapproved_ads_with_awql.py | 64 +++ .../get_campaigns_by_label.py | 86 +++ .../campaign_management/promote_experiment.py | 61 ++ .../campaign_management/set_ad_parameters.py | 101 ++++ .../set_criterion_bid_modifier.py | 78 +++ .../campaign_management/validate_text_ad.py | 85 +++ .../v201601}/error_handling/__init__.py | 2 +- .../error_handling/handle_partial_failures.py | 46 +- .../handle_policy_violation_error.py | 115 ++++ .../v201601/extensions}/__init__.py | 4 +- ..._google_my_business_location_extensions.py | 159 ++++++ .../v201601/extensions/add_site_links.py | 125 +++++ .../extensions/add_site_links_using_feeds.py | 234 ++++++++ .../adwords/v201601/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 528 ++++++++++++++++++ .../v201601/migration/upgrade_ad_url.py | 80 +++ examples/adwords/v201601/misc/__init__.py | 15 + .../v201601/misc/get_all_images_and_videos.py | 86 +++ examples/adwords/v201601/misc/upload_image.py | 67 +++ .../v201601/misc/upload_media_bundle.py | 60 ++ .../adwords/v201601/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 133 +++++ .../get_keyword_bid_simulations.py | 82 +++ .../v201601/optimization/get_keyword_ideas.py | 91 +++ .../adwords/v201601/remarketing/__init__.py | 15 + .../v201601/remarketing/add_audience.py | 104 ++++ .../remarketing/add_conversion_tracker.py | 71 +++ .../remarketing/add_crm_based_user_list.py | 97 ++++ .../remarketing/add_rule_based_user_lists.py | 184 ++++++ .../remarketing/upload_offline_conversions.py | 76 +++ .../adwords/v201601/reporting/__init__.py | 15 + .../reporting/download_criteria_report.py | 62 ++ .../download_criteria_report_as_stream.py | 78 +++ ...oad_criteria_report_as_stream_with_awql.py | 82 +++ .../download_criteria_report_as_string.py | 60 ++ ...oad_criteria_report_as_string_with_awql.py | 56 ++ .../download_criteria_report_with_awql.py | 60 ++ .../v201601/reporting/get_report_fields.py | 53 ++ examples/adwords/v201601/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 282 ++++++++++ .../v201601/shopping/add_product_scope.py | 104 ++++ .../v201601/shopping/add_shopping_campaign.py | 121 ++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201601/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 162 ++++++ .../add_demographic_targeting_criteria.py | 97 ++++ .../get_campaign_targeting_criteria.py | 86 +++ .../get_targetable_languages_and_carriers.py | 56 ++ .../v201601/targeting/lookup_location.py | 83 +++ examples/adxbuyer/v201506/__init__.py | 15 - .../v201506/basic_operations/add_campaigns.py | 120 ---- .../add_placements_in_bulk.py | 134 ----- examples/adxbuyer/v201509/__init__.py | 15 - .../basic_operations/add_placements.py | 88 --- .../add_third_party_redirect_ad.py | 100 ---- .../basic_operations/update_placement.py | 81 --- .../error_handling/handle_partial_failures.py | 115 ---- .../authentication/generate_refresh_token.py | 11 +- googleads/adwords.py | 208 +++++-- googleads/common.py | 2 +- setup.py | 3 +- tests/adwords_test.py | 78 ++- 163 files changed, 7680 insertions(+), 1086 deletions(-) rename examples/{adxbuyer/v201506/error_handling => adwords/v201601}/__init__.py (87%) create mode 100644 examples/adwords/v201601/account_management/__init__.py create mode 100755 examples/adwords/v201601/account_management/create_account.py create mode 100755 examples/adwords/v201601/account_management/get_account_changes.py create mode 100755 examples/adwords/v201601/account_management/get_account_hierarchy.py rename examples/{adxbuyer/v201506/campaign_management => adwords/v201601/advanced_operations}/__init__.py (86%) create mode 100755 examples/adwords/v201601/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201601/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201601/advanced_operations/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py rename examples/{adxbuyer/v201509 => adwords/v201601}/basic_operations/__init__.py (92%) rename examples/{adxbuyer/v201509 => adwords/v201601}/basic_operations/add_ad_groups.py (62%) rename examples/{adxbuyer/v201509 => adwords/v201601}/basic_operations/add_campaigns.py (76%) rename examples/{adxbuyer/v201506/basic_operations/add_placements.py => adwords/v201601/basic_operations/add_keywords.py} (73%) rename examples/{adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py => adwords/v201601/basic_operations/add_text_ads.py} (50%) rename examples/{adxbuyer/v201509/basic_operations/get_third_party_redirect_ads.py => adwords/v201601/basic_operations/get_ad_groups.py} (61%) rename examples/{adxbuyer/v201506/basic_operations/get_placements.py => adwords/v201601/basic_operations/get_campaigns.py} (60%) create mode 100755 examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py rename examples/{adxbuyer/v201509/basic_operations/get_placements.py => adwords/v201601/basic_operations/get_keywords.py} (59%) rename examples/{adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py => adwords/v201601/basic_operations/get_text_ads.py} (90%) create mode 100755 examples/adwords/v201601/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201601/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201601/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201601/basic_operations/remove_campaign.py rename examples/{adxbuyer/v201509/basic_operations/remove_placement.py => adwords/v201601/basic_operations/remove_keyword.py} (91%) rename examples/{adxbuyer/v201506/basic_operations/add_ad_groups.py => adwords/v201601/basic_operations/update_ad_group.py} (51%) create mode 100755 examples/adwords/v201601/basic_operations/update_campaign.py rename examples/{adxbuyer/v201506/basic_operations/update_placement.py => adwords/v201601/basic_operations/update_keyword.py} (78%) rename examples/{adxbuyer/v201509 => adwords/v201601}/campaign_management/__init__.py (92%) rename examples/{adxbuyer/v201506/basic_operations/remove_placement.py => adwords/v201601/campaign_management/add_campaign_labels.py} (50%) create mode 100755 examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201601/campaign_management/add_experiment.py rename examples/{adxbuyer/v201509/campaign_management/add_placements_in_bulk.py => adwords/v201601/campaign_management/add_keywords_in_bulk.py} (86%) create mode 100755 examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201601/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201601/campaign_management/promote_experiment.py create mode 100755 examples/adwords/v201601/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201601/campaign_management/validate_text_ad.py rename examples/{adxbuyer/v201509 => adwords/v201601}/error_handling/__init__.py (92%) rename examples/{adxbuyer/v201506 => adwords/v201601}/error_handling/handle_partial_failures.py (69%) create mode 100755 examples/adwords/v201601/error_handling/handle_policy_violation_error.py rename examples/{adxbuyer/v201506/basic_operations => adwords/v201601/extensions}/__init__.py (86%) create mode 100755 examples/adwords/v201601/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201601/extensions/add_site_links.py create mode 100755 examples/adwords/v201601/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201601/migration/__init__.py create mode 100755 examples/adwords/v201601/migration/migrate_to_extension_settings.py create mode 100755 examples/adwords/v201601/migration/upgrade_ad_url.py create mode 100644 examples/adwords/v201601/misc/__init__.py create mode 100755 examples/adwords/v201601/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201601/misc/upload_image.py create mode 100755 examples/adwords/v201601/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201601/optimization/__init__.py create mode 100755 examples/adwords/v201601/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201601/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201601/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201601/remarketing/__init__.py create mode 100755 examples/adwords/v201601/remarketing/add_audience.py create mode 100755 examples/adwords/v201601/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201601/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201601/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201601/remarketing/upload_offline_conversions.py create mode 100644 examples/adwords/v201601/reporting/__init__.py create mode 100755 examples/adwords/v201601/reporting/download_criteria_report.py create mode 100755 examples/adwords/v201601/reporting/download_criteria_report_as_stream.py create mode 100755 examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201601/reporting/download_criteria_report_as_string.py create mode 100755 examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201601/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201601/reporting/get_report_fields.py create mode 100644 examples/adwords/v201601/shopping/__init__.py create mode 100755 examples/adwords/v201601/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201601/shopping/add_product_scope.py create mode 100755 examples/adwords/v201601/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201601/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201601/targeting/__init__.py create mode 100755 examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201601/targeting/lookup_location.py delete mode 100644 examples/adxbuyer/v201506/__init__.py delete mode 100755 examples/adxbuyer/v201506/basic_operations/add_campaigns.py delete mode 100755 examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py delete mode 100644 examples/adxbuyer/v201509/__init__.py delete mode 100755 examples/adxbuyer/v201509/basic_operations/add_placements.py delete mode 100755 examples/adxbuyer/v201509/basic_operations/add_third_party_redirect_ad.py delete mode 100755 examples/adxbuyer/v201509/basic_operations/update_placement.py delete mode 100755 examples/adxbuyer/v201509/error_handling/handle_partial_failures.py diff --git a/ChangeLog b/ChangeLog index 880989c1..93ccc008 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,17 @@ +3.12.0 -- 02/01/2016 +* Removed DoubleClick Ad Exchange content. This API has been sunset. +* Added support for AdWords v201601. +* Updated the AdWords account_management get_account_hierarchy.py example to + properly handle the case where ManagedCustomerService.get returns multiple + pages of results. +* Refactored AdWords upload_offline_conversions.py example, moved to + remarketing. +* Refactored AdWords add_complete_campaigns_using_batch_job.py example, moved to + campaign_management. +* The AdWords BatchJobHelper and IncrementalUploadHelper utilities now + initialize URLs for v201601 and up. +* The AdWords IncrementalUploadHelper is now serializable. + 3.11.0 -- 11/24/2015 * Removed support for AdWords v201502. * Added incremental upload support to BatchJobHelper. diff --git a/README.md b/README.md index 20d04d0d..61c3a501 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,9 @@ This client library simplifies accessing Google's SOAP Ads APIs - AdWords, -DoubleClick Ad Exchange SOAP, DoubleClick for Advertisers, and DoubleClick for -Publishers. The library provides easy ways to store your authentication and -create SOAP web service clients. It also contains example code to help you get -started integrating with our APIs. +and DoubleClick for Publishers. The library provides easy ways to store your +authentication and create SOAP web service clients. It also contains example +code to help you get started integrating with our APIs. ####Important Note Regarding DFP If you are using v201502 and newer in the DFP API, then performing actions on @@ -71,8 +70,6 @@ tracker](https://github.com/googleads/googleads-python-lib/issues). If you have issues pertaining to a specific product, use the product support forums: * [AdWords](https://groups.google.com/forum/#!forum/adwords-api) -* [DoubleClick Ad Exchange](https://groups.google.com/forum/#!forum/google-doubleclick-ad-exchange-buyer-api) -* [DoubleClick for Advertisers](https://groups.google.com/forum/#!forum/google-doubleclick-for-advertisers-api) * [DoubleClick for Publishers](https://groups.google.com/forum/#!forum/google-doubleclick-for-publishers-api) Make sure to subscribe to our [Google Plus page](https://plus.google.com/+GoogleAdsDevelopers) diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 34ff383a..20c28c0c 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -24,17 +24,17 @@ # Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet, # please go to https://console.developers.google.com and create a set. -CLIENT_ID = 'INSERT_CLIENT_ID_HERE' -CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' +DEFAULT_CLIENT_ID = None +DEFAULT_CLIENT_SECRET = None # The AdWords API OAuth 2.0 scope. SCOPE = u'https://www.googleapis.com/auth/adwords' parser = argparse.ArgumentParser(description='Generates a refresh token with ' 'the provided credentials.') -parser.add_argument('--client_id', default=CLIENT_ID, +parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID, help='Client Id retrieved from the Developer\'s Console.') -parser.add_argument('--client_secret', default=CLIENT_SECRET, +parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET, help='Client Secret retrieved from the Developer\'s ' 'Console.') parser.add_argument('--additional_scopes', default=None, @@ -72,7 +72,8 @@ def main(client_id, client_secret, scopes): if __name__ == '__main__': args = parser.parse_args() configured_scopes = [SCOPE] - if args.client_id == CLIENT_ID or args.client_secret == CLIENT_SECRET: + if not (any([args.client_id, DEFAULT_CLIENT_ID]) and + any([args.client_secret, DEFAULT_CLIENT_SECRET])): raise AttributeError('No client_id or client_secret specified.') if args.additional_scopes: configured_scopes.extend(args.additional_scopes.replace(' ', '').split(',')) diff --git a/examples/adwords/v201506/account_management/create_account.py b/examples/adwords/v201506/account_management/create_account.py index 6038fcfb..75f5fc1b 100755 --- a/examples/adwords/v201506/account_management/create_account.py +++ b/examples/adwords/v201506/account_management/create_account.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/account_management/get_account_hierarchy.py b/examples/adwords/v201506/account_management/get_account_hierarchy.py index dacffac0..f575868f 100755 --- a/examples/adwords/v201506/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201506/account_management/get_account_hierarchy.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py index 6b735876..f8367749 100755 --- a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/add_keywords.py b/examples/adwords/v201506/basic_operations/add_keywords.py index e7298bad..d5cddc28 100755 --- a/examples/adwords/v201506/basic_operations/add_keywords.py +++ b/examples/adwords/v201506/basic_operations/add_keywords.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/basic_operations/add_text_ads.py b/examples/adwords/v201506/basic_operations/add_text_ads.py index 0284b76b..0b56f8fa 100755 --- a/examples/adwords/v201506/basic_operations/add_text_ads.py +++ b/examples/adwords/v201506/basic_operations/add_text_ads.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/basic_operations/get_keywords.py b/examples/adwords/v201506/basic_operations/get_keywords.py index 4cb24c58..1c1e78ca 100755 --- a/examples/adwords/v201506/basic_operations/get_keywords.py +++ b/examples/adwords/v201506/basic_operations/get_keywords.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/basic_operations/get_text_ads.py b/examples/adwords/v201506/basic_operations/get_text_ads.py index c2b7593c..b06b2d44 100755 --- a/examples/adwords/v201506/basic_operations/get_text_ads.py +++ b/examples/adwords/v201506/basic_operations/get_text_ads.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/basic_operations/remove_keyword.py b/examples/adwords/v201506/basic_operations/remove_keyword.py index eb882642..69ac8cba 100755 --- a/examples/adwords/v201506/basic_operations/remove_keyword.py +++ b/examples/adwords/v201506/basic_operations/remove_keyword.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/basic_operations/update_keyword.py b/examples/adwords/v201506/basic_operations/update_keyword.py index 37e3644e..d4fa50cf 100755 --- a/examples/adwords/v201506/basic_operations/update_keyword.py +++ b/examples/adwords/v201506/basic_operations/update_keyword.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/campaign_management/add_experiment.py b/examples/adwords/v201506/campaign_management/add_experiment.py index d04117a5..a5a0c421 100755 --- a/examples/adwords/v201506/campaign_management/add_experiment.py +++ b/examples/adwords/v201506/campaign_management/add_experiment.py @@ -27,7 +27,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py index 27561489..8db03a3f 100755 --- a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py +++ b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/campaign_management/promote_experiment.py b/examples/adwords/v201506/campaign_management/promote_experiment.py index 56cbe3bc..39ff5c4a 100755 --- a/examples/adwords/v201506/campaign_management/promote_experiment.py +++ b/examples/adwords/v201506/campaign_management/promote_experiment.py @@ -25,7 +25,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/campaign_management/set_ad_parameters.py b/examples/adwords/v201506/campaign_management/set_ad_parameters.py index 2e2a51c5..b0925086 100755 --- a/examples/adwords/v201506/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201506/campaign_management/set_ad_parameters.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/campaign_management/validate_text_ad.py b/examples/adwords/v201506/campaign_management/validate_text_ad.py index 8bc022f6..c11b7443 100755 --- a/examples/adwords/v201506/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201506/campaign_management/validate_text_ad.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/extensions/add_site_links.py b/examples/adwords/v201506/extensions/add_site_links.py index 0a43a9e3..ad1f63bf 100755 --- a/examples/adwords/v201506/extensions/add_site_links.py +++ b/examples/adwords/v201506/extensions/add_site_links.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py index 562ce67c..da321c9e 100755 --- a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/migration/migrate_to_extension_settings.py b/examples/adwords/v201506/migration/migrate_to_extension_settings.py index 8798818b..1d8c1972 100755 --- a/examples/adwords/v201506/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201506/migration/migrate_to_extension_settings.py @@ -27,7 +27,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py index 58836606..278736c1 100755 --- a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py index f8961aef..2a770b00 100755 --- a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/optimization/get_keyword_ideas.py b/examples/adwords/v201506/optimization/get_keyword_ideas.py index 1ac5f573..920fbf40 100755 --- a/examples/adwords/v201506/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201506/optimization/get_keyword_ideas.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/reporting/download_criteria_report.py b/examples/adwords/v201506/reporting/download_criteria_report.py index 4dae0371..5cddd34a 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report.py +++ b/examples/adwords/v201506/reporting/download_criteria_report.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py index 9723455f..8daa5411 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py index d8be18c5..10223304 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py index af4f366a..b376d930 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py index 469b5653..42d8516e 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py index 864ee661..4b261a46 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/account_management/create_account.py b/examples/adwords/v201509/account_management/create_account.py index bf103a7b..ea1dd60f 100755 --- a/examples/adwords/v201509/account_management/create_account.py +++ b/examples/adwords/v201509/account_management/create_account.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/account_management/get_account_hierarchy.py b/examples/adwords/v201509/account_management/get_account_hierarchy.py index 7b0a30c9..951fa6dc 100755 --- a/examples/adwords/v201509/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201509/account_management/get_account_hierarchy.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -16,21 +16,19 @@ """This example gets the account hierarchy under the current account. -Note: this code example won't work with test accounts. See -https://developers.google.com/adwords/api/docs/test-accounts - The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ - from googleads import adwords +PAGE_SIZE = 500 + + def DisplayAccountTree(account, accounts, links, depth=0): """Displays an account tree. @@ -54,38 +52,51 @@ def main(client): 'ManagedCustomerService', version='v201509') # Construct selector to get all accounts. + offset = 0 selector = { - 'fields': ['CustomerId', 'Name'] + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } } - # Get serviced account graph. - graph = managed_customer_service.get(selector) - if 'entries' in graph and graph['entries']: - # Create map from customerId to parent and child links. - child_links = {} - parent_links = {} - if 'links' in graph: - for link in graph['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Create map from customerID to account and find root account. - accounts = {} - root_account = None - for account in graph['entries']: - accounts[account['customerId']] = account - if account['customerId'] not in parent_links: - root_account = account - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) else: - print 'No serviced accounts were found' + print 'Unable to determine a root account' if __name__ == '__main__': diff --git a/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py index 0067ad1c..4563c4ad 100755 --- a/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py index ccd3e2cd..57dc3222 100755 --- a/examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py @@ -19,7 +19,6 @@ The complete Campaign created by this example also includes AdGroups and KeyWords. -Api: AdWordsOnly """ import random diff --git a/examples/adwords/v201509/advanced_operations/add_html5_ad.py b/examples/adwords/v201509/advanced_operations/add_html5_ad.py index c7e5d29f..fc6e19d3 100755 --- a/examples/adwords/v201509/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201509/advanced_operations/add_html5_ad.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py index 931e3923..8c409409 100755 --- a/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py @@ -19,7 +19,6 @@ The complete Campaign created by this example also includes AdGroups and KeyWords. -Api: AdWordsOnly """ import random diff --git a/examples/adwords/v201509/basic_operations/add_ad_groups.py b/examples/adwords/v201509/basic_operations/add_ad_groups.py index 5bc97212..5059bffd 100755 --- a/examples/adwords/v201509/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201509/basic_operations/add_ad_groups.py @@ -57,8 +57,11 @@ def main(client, campaign_id): }, 'settings': [ { - # Targeting restriction settings - these settings only affect - # serving for the Display Network. + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. 'xsi_type': 'TargetingSetting', 'details': [ # Restricting to serve ads that match your ad group diff --git a/examples/adwords/v201509/basic_operations/add_keywords.py b/examples/adwords/v201509/basic_operations/add_keywords.py index 6b2bdd75..fb946b2e 100755 --- a/examples/adwords/v201509/basic_operations/add_keywords.py +++ b/examples/adwords/v201509/basic_operations/add_keywords.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/basic_operations/add_text_ads.py b/examples/adwords/v201509/basic_operations/add_text_ads.py index 605a1064..56f44f18 100755 --- a/examples/adwords/v201509/basic_operations/add_text_ads.py +++ b/examples/adwords/v201509/basic_operations/add_text_ads.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/basic_operations/get_keywords.py b/examples/adwords/v201509/basic_operations/get_keywords.py index 3359dd5a..82fb7f03 100755 --- a/examples/adwords/v201509/basic_operations/get_keywords.py +++ b/examples/adwords/v201509/basic_operations/get_keywords.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/basic_operations/get_text_ads.py b/examples/adwords/v201509/basic_operations/get_text_ads.py index 00e219b6..f6c553ad 100755 --- a/examples/adwords/v201509/basic_operations/get_text_ads.py +++ b/examples/adwords/v201509/basic_operations/get_text_ads.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/basic_operations/remove_keyword.py b/examples/adwords/v201509/basic_operations/remove_keyword.py index b9ca0308..a733c77d 100755 --- a/examples/adwords/v201509/basic_operations/remove_keyword.py +++ b/examples/adwords/v201509/basic_operations/remove_keyword.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/basic_operations/update_keyword.py b/examples/adwords/v201509/basic_operations/update_keyword.py index 72aac27f..aeb9dfe8 100755 --- a/examples/adwords/v201509/basic_operations/update_keyword.py +++ b/examples/adwords/v201509/basic_operations/update_keyword.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/campaign_management/add_experiment.py b/examples/adwords/v201509/campaign_management/add_experiment.py index 2ebfe263..38cba15b 100755 --- a/examples/adwords/v201509/campaign_management/add_experiment.py +++ b/examples/adwords/v201509/campaign_management/add_experiment.py @@ -27,7 +27,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py index 861dcfbf..622449d2 100755 --- a/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py +++ b/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/campaign_management/promote_experiment.py b/examples/adwords/v201509/campaign_management/promote_experiment.py index e5900edd..a7fe43e1 100755 --- a/examples/adwords/v201509/campaign_management/promote_experiment.py +++ b/examples/adwords/v201509/campaign_management/promote_experiment.py @@ -25,7 +25,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/campaign_management/set_ad_parameters.py b/examples/adwords/v201509/campaign_management/set_ad_parameters.py index ad24efbd..98fbc66b 100755 --- a/examples/adwords/v201509/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201509/campaign_management/set_ad_parameters.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/campaign_management/validate_text_ad.py b/examples/adwords/v201509/campaign_management/validate_text_ad.py index 683b6937..dd0d79f4 100755 --- a/examples/adwords/v201509/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201509/campaign_management/validate_text_ad.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/extensions/add_site_links.py b/examples/adwords/v201509/extensions/add_site_links.py index 0102e725..72463ace 100755 --- a/examples/adwords/v201509/extensions/add_site_links.py +++ b/examples/adwords/v201509/extensions/add_site_links.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/extensions/add_site_links_using_feeds.py b/examples/adwords/v201509/extensions/add_site_links_using_feeds.py index 93b8f2e5..505a81c4 100755 --- a/examples/adwords/v201509/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201509/extensions/add_site_links_using_feeds.py @@ -24,7 +24,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/migration/migrate_to_extension_settings.py b/examples/adwords/v201509/migration/migrate_to_extension_settings.py index ce7f7b11..66a14ce8 100755 --- a/examples/adwords/v201509/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201509/migration/migrate_to_extension_settings.py @@ -27,7 +27,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/misc/upload_media_bundle.py b/examples/adwords/v201509/misc/upload_media_bundle.py index f6cd7dce..a5dd7752 100755 --- a/examples/adwords/v201509/misc/upload_media_bundle.py +++ b/examples/adwords/v201509/misc/upload_media_bundle.py @@ -16,7 +16,6 @@ """This example uploads an HTML5 zip file. -Api: AdWordsOnly """ import base64 diff --git a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py index 493760ca..7e452bb3 100755 --- a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py index 3c5565df..920c307e 100755 --- a/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/optimization/get_keyword_ideas.py b/examples/adwords/v201509/optimization/get_keyword_ideas.py index ebd1b74b..b82a9dc3 100755 --- a/examples/adwords/v201509/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201509/optimization/get_keyword_ideas.py @@ -21,7 +21,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/remarketing/add_crm_based_user_list.py b/examples/adwords/v201509/remarketing/add_crm_based_user_list.py index 3f02d154..49a56586 100755 --- a/examples/adwords/v201509/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201509/remarketing/add_crm_based_user_list.py @@ -41,10 +41,8 @@ def main(client, emails): 'description': 'A list of customers that originated from email addresses', # Maximum lifespan is 180 days. 'membershipLifeSpan': 180, - # This field is required. It links to a service you created that allows - # members of this list to remove themselves. It will be shown in the - # "Why this Ad?" of an ad and so it needs to be verified. Read more about - # "Why this Ad?" here: https://support.google.com/ads/answer/2662850. + # This field is optional. It links to a service you created that allows + # members of this list to remove themselves. 'optOutLink': 'http://endpoint1.example.com/optout' } diff --git a/examples/adwords/v201509/reporting/download_criteria_report.py b/examples/adwords/v201509/reporting/download_criteria_report.py index 40878412..dff28760 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report.py +++ b/examples/adwords/v201509/reporting/download_criteria_report.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py index 420cb47e..04a9d480 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py index 8ec1930c..6a26daca 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_string.py b/examples/adwords/v201509/reporting/download_criteria_report_as_string.py index 32a9fbd2..7bed6696 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_string.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py index 1a9df79f..b647021c 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py index b1a272ae..47d536b1 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py @@ -23,7 +23,6 @@ directory. For more information, see the "Caching authentication information" section of our README. -Api: AdWordsOnly """ diff --git a/examples/adxbuyer/v201506/error_handling/__init__.py b/examples/adwords/v201601/__init__.py similarity index 87% rename from examples/adxbuyer/v201506/error_handling/__init__.py rename to examples/adwords/v201601/__init__.py index b5203c57..16ff256a 100644 --- a/examples/adxbuyer/v201506/error_handling/__init__.py +++ b/examples/adwords/v201601/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Error handling examples.""" +"""Examples for AdWords.""" diff --git a/examples/adwords/v201601/account_management/__init__.py b/examples/adwords/v201601/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201601/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201601/account_management/create_account.py b/examples/adwords/v201601/account_management/create_account.py new file mode 100755 index 00000000..74255ed4 --- /dev/null +++ b/examples/adwords/v201601/account_management/create_account.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201601') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201601/account_management/get_account_changes.py b/examples/adwords/v201601/account_management/get_account_changes.py new file mode 100755 index 00000000..0c1e1f28 --- /dev/null +++ b/examples/adwords/v201601/account_management/get_account_changes.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201601') + campaign_service = client.GetService('CampaignService', version='v201601') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedAdExtensions' in data: + print ' Added ad extensions: %s' % data['addedAdExtensions'] + if 'removedAdExtensions' in data: + print ' Removed ad extensions: %s' % data['removedAdExtensions'] + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201601/account_management/get_account_hierarchy.py b/examples/adwords/v201601/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..af319888 --- /dev/null +++ b/examples/adwords/v201601/account_management/get_account_hierarchy.py @@ -0,0 +1,105 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201601') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adxbuyer/v201506/campaign_management/__init__.py b/examples/adwords/v201601/advanced_operations/__init__.py similarity index 86% rename from examples/adxbuyer/v201506/campaign_management/__init__.py rename to examples/adwords/v201601/advanced_operations/__init__.py index db098bda..dc91ba79 100644 --- a/examples/adxbuyer/v201506/campaign_management/__init__.py +++ b/examples/adwords/v201601/advanced_operations/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Campaign management examples.""" +"""Advanced operations examples.""" diff --git a/examples/adwords/v201601/advanced_operations/add_ad_customizer.py b/examples/adwords/v201601/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..4f5a84f9 --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/add_ad_customizer.py @@ -0,0 +1,222 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates TextAds that use ad customizations for the specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add TextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no TextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService') + + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'description1': 'Only {=%s.Price}' % feed_name, + 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com' + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..e5c9ca14 --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201601') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..7e66f33f --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,109 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad to ad group ID \'%s\' ' + 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/advanced_operations/add_html5_ad.py b/examples/adwords/v201601/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..6c8dbdd2 --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/add_html5_ad.py @@ -0,0 +1,112 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/advanced_operations/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201601/advanced_operations/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..70c7fc3b --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,214 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper() + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201601') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job with ID "%s" not finished downloading. Try ' + 'checking later.' % batch_job_id) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..ddfbc339 --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -0,0 +1,112 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a text add that uses advanced features of upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Create the text ad + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print ('AdGroupAd with ID %s and display URL \'%s\'was added.' + % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..e408b17f --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,129 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201601') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201601') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201601') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..8961be5b --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201601') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201601') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if page['entries']: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..12d6c7eb --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201601') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..5d4024cd --- /dev/null +++ b/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,173 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201601') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201601') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'period': 'DAILY', + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201601') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adxbuyer/v201509/basic_operations/__init__.py b/examples/adwords/v201601/basic_operations/__init__.py similarity index 92% rename from examples/adxbuyer/v201509/basic_operations/__init__.py rename to examples/adwords/v201601/basic_operations/__init__.py index 80acbea9..1a2bc84a 100644 --- a/examples/adxbuyer/v201509/basic_operations/__init__.py +++ b/examples/adwords/v201601/basic_operations/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. diff --git a/examples/adxbuyer/v201509/basic_operations/add_ad_groups.py b/examples/adwords/v201601/basic_operations/add_ad_groups.py similarity index 62% rename from examples/adxbuyer/v201509/basic_operations/add_ad_groups.py rename to examples/adwords/v201601/basic_operations/add_ad_groups.py index b9f3b561..ce712ed8 100755 --- a/examples/adxbuyer/v201509/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201601/basic_operations/add_ad_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -36,7 +36,7 @@ def main(client, campaign_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201509') + ad_group_service = client.GetService('AdGroupService', version='v201601') # Construct operations and add ad groups. operations = [{ @@ -48,13 +48,40 @@ def main(client, campaign_id): 'biddingStrategyConfiguration': { 'bids': [ { - 'xsi_type': 'CpmBid', + 'xsi_type': 'CpcBid', 'bid': { 'microAmount': '1000000' }, } ] - } + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] } }, { 'operator': 'ADD', @@ -65,10 +92,10 @@ def main(client, campaign_id): 'biddingStrategyConfiguration': { 'bids': [ { - 'xsi_type': 'CpmBid', + 'xsi_type': 'CpcBid', 'bid': { 'microAmount': '1000000' - }, + } } ] } diff --git a/examples/adxbuyer/v201509/basic_operations/add_campaigns.py b/examples/adwords/v201601/basic_operations/add_campaigns.py similarity index 76% rename from examples/adxbuyer/v201509/basic_operations/add_campaigns.py rename to examples/adwords/v201601/basic_operations/add_campaigns.py index 6524ce73..2c398c0b 100755 --- a/examples/adxbuyer/v201509/basic_operations/add_campaigns.py +++ b/examples/adwords/v201601/basic_operations/add_campaigns.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,7 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example adds campaigns. To get campaigns, run get_campaigns.py. +"""This example adds campaigns. + +To get campaigns, run get_campaigns.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -31,9 +33,9 @@ def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201509') - budget_service = client.GetService('BudgetService', version='v201509') + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201601') + budget_service = client.GetService('BudgetService', version='v201601') # Create a budget, which can be shared by multiple campaigns. budget = { @@ -60,9 +62,9 @@ def main(client): 'operand': { 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), 'status': 'PAUSED', - 'advertisingChannelType': 'DISPLAY', + 'advertisingChannelType': 'SEARCH', 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPM', + 'biddingStrategyType': 'MANUAL_CPC', }, 'endDate': (datetime.datetime.now() + datetime.timedelta(365)).strftime('%Y%m%d'), @@ -70,10 +72,12 @@ def main(client): 'budget': { 'budgetId': budget_id }, - 'settings': [{ - 'xsi_type': 'RealTimeBiddingSetting', - 'optIn': 'true' - }], + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, # Optional fields 'startDate': (datetime.datetime.now() + datetime.timedelta(1)).strftime('%Y%m%d'), @@ -82,16 +86,22 @@ def main(client): 'impressions': '5', 'timeUnit': 'DAY', 'level': 'ADGROUP' - } + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] } }, { 'operator': 'ADD', 'operand': { - 'name': 'Interplanetary Cruise Banners #%s' % uuid.uuid4(), + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), 'status': 'PAUSED', - 'advertisingChannelType': 'DISPLAY', 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPM', + 'biddingStrategyType': 'MANUAL_CPC' }, 'endDate': (datetime.datetime.now() + datetime.timedelta(365)).strftime('%Y%m%d'), @@ -99,10 +109,7 @@ def main(client): 'budget': { 'budgetId': budget_id }, - 'settings': [{ - 'xsi_type': 'RealTimeBiddingSetting', - 'optIn': 'true' - }], + 'advertisingChannelType': 'DISPLAY' } }] campaigns = campaign_service.mutate(operations) diff --git a/examples/adxbuyer/v201506/basic_operations/add_placements.py b/examples/adwords/v201601/basic_operations/add_keywords.py similarity index 73% rename from examples/adxbuyer/v201506/basic_operations/add_placements.py rename to examples/adwords/v201601/basic_operations/add_keywords.py index 344a7a16..44d5f321 100755 --- a/examples/adxbuyer/v201506/basic_operations/add_placements.py +++ b/examples/adwords/v201601/basic_operations/add_keywords.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -35,39 +35,43 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') + 'AdGroupCriterionService', version='v201601') # Construct keyword ad group criterion object. - placement1 = { + keyword1 = { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', - 'url': 'http://mars.google.com' + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' }, # These fields are optional. 'userStatus': 'PAUSED', - 'destinationUrl': 'http://example.com/mars' + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } } - placement2 = { + keyword2 = { 'xsi_type': 'NegativeAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', - 'url': 'http://example.com/pluto' - }, + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } } # Construct operations and add ad group criteria. operations = [ { 'operator': 'ADD', - 'operand': placement1 + 'operand': keyword1 }, { 'operator': 'ADD', - 'operand': placement2 + 'operand': keyword2 } ] ad_group_criteria = ad_group_criterion_service.mutate( @@ -75,10 +79,11 @@ def main(client, ad_group_id): # Display results. for criterion in ad_group_criteria: - print ('Placement ad group criterion with ad group id \'%s\', criterion ' - 'id \'%s\', and url \'%s\' was added.' + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) + criterion['criterion']['text'], + criterion['criterion']['matchType'])) if __name__ == '__main__': diff --git a/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py b/examples/adwords/v201601/basic_operations/add_text_ads.py similarity index 50% rename from examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py rename to examples/adwords/v201601/basic_operations/add_text_ads.py index 687fba1e..7a29859f 100755 --- a/examples/adxbuyer/v201506/basic_operations/add_third_party_redirect_ad.py +++ b/examples/adwords/v201601/basic_operations/add_text_ads.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example adds several third party ads to a given ad group. +"""This example adds several text ads to a given ad group. -To get an ad_group_id, run get_ad_groups.py. +To get ad_group_id, run get_ad_groups.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -26,8 +26,6 @@ """ -import uuid - from googleads import adwords @@ -36,9 +34,17 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') # Construct operations and add ads. + # If needed, you could specify an exemption request here, e.g.: + # 'exemptionRequests': [{ + # # This comes back in a PolicyViolationError. + # 'key' { + # 'policyName': '...', + # 'violatingText': '...' + # } + # }] operations = [ { 'operator': 'ADD', @@ -46,24 +52,15 @@ def main(client, ad_group_id): 'xsi_type': 'AdGroupAd', 'adGroupId': ad_group_id, 'ad': { - 'xsi_type': 'ThirdPartyRedirectAd', - 'name': 'Example third party ad #%s' % uuid.uuid4(), - 'url': 'http://www.example.com', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - # This field normally contains the javascript ad tag. - 'snippet': (''), - 'certifiedVendorFormatId': '232', - 'isCookieTargeted': 'false', - 'isUserInterestTargeted': 'false', - 'isTagged': 'false', - 'richMediaAdType': 'STANDARD', - 'expandingDirections': ['EXPANDING_UP', 'EXPANDING_DOWN'], - 'adAttributes': ['ROLL_OVER_TO_EXPAND'] - } + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + }, + # Optional fields. + 'status': 'PAUSED' } }, { @@ -72,15 +69,12 @@ def main(client, ad_group_id): 'xsi_type': 'AdGroupAd', 'adGroupId': ad_group_id, 'ad': { - 'xsi_type': 'ThirdPartyRedirectAd', - 'name': 'Example third party ad #%s' % uuid.uuid4(), - 'url': 'http://www.example.com', - 'adDuration': '15000', - 'sourceUrl': ('http://ad.doubleclick.net/pfadx/N270.126913.' - '6102203221521/B3876671.21;dcadv=2215309;' - 'sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml'), - 'certifiedVendorFormatId': '303', - 'richMediaAdType': 'IN_STREAM_VIDEO' + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Enjoy your stay at Red Planet.', + 'description2': 'Buy your tickets now!', + 'headline': 'Luxury Cruise to Mars' } } } @@ -89,7 +83,7 @@ def main(client, ad_group_id): # Display results. for ad in ads['value']: - print ('Ad with ID \'%s\' and of type \'%s\' was added.' + print ('Ad with id \'%s\' and of type \'%s\' was added.' % (ad['ad']['id'], ad['ad']['Ad.Type'])) diff --git a/examples/adxbuyer/v201509/basic_operations/get_third_party_redirect_ads.py b/examples/adwords/v201601/basic_operations/get_ad_groups.py similarity index 61% rename from examples/adxbuyer/v201509/basic_operations/get_third_party_redirect_ads.py rename to examples/adwords/v201601/basic_operations/get_ad_groups.py index 32032edc..d43eb30e 100755 --- a/examples/adxbuyer/v201509/basic_operations/get_third_party_redirect_ads.py +++ b/examples/adwords/v201601/basic_operations/get_ad_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all third party ads for a given ad group. +"""This example gets all ad groups for a given campaign. -To add a third party ad, add_third_party_redirect_ad.py. +To add an ad group, run add_ad_group.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,27 +30,22 @@ PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -def main(client, ad_group_id): +def main(client, campaign_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') + ad_group_service = client.GetService('AdGroupService', version='v201601') - # Construct selector and get all ads for a given ad group. + # Construct selector and get all ad groups. offset = 0 selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], + 'fields': ['Id', 'Name', 'Status'], 'predicates': [ { - 'field': 'AdGroupId', + 'field': 'CampaignId', 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['THIRD_PARTY_REDIRECT_AD'] + 'values': [campaign_id] } ], 'paging': { @@ -60,15 +55,16 @@ def main(client, ad_group_id): } more_pages = True while more_pages: - page = ad_group_ad_service.get(selector) + page = ad_group_service.get(selector) # Display results. if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) else: - print 'No ads were found.' + print 'No ad groups were found.' offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) @@ -78,4 +74,4 @@ def main(client, ad_group_id): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/get_placements.py b/examples/adwords/v201601/basic_operations/get_campaigns.py similarity index 60% rename from examples/adxbuyer/v201506/basic_operations/get_placements.py rename to examples/adwords/v201601/basic_operations/get_campaigns.py index 33f4969f..a455f19d 100755 --- a/examples/adxbuyer/v201506/basic_operations/get_placements.py +++ b/examples/adwords/v201601/basic_operations/get_campaigns.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all ad group criteria in an account. +"""This example gets all campaigns. -To add placements, run add_placements.py. +To add a campaign, run add_campaign.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -26,51 +26,50 @@ """ +import logging +import time + from googleads import adwords +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + -PAGE_SIZE = 500 +PAGE_SIZE = 100 def main(client): # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') + campaign_service = client.GetService('CampaignService', version='v201601') - # Construct selector and get all ad group criteria. + # Construct selector and get all campaigns. offset = 0 selector = { - 'fields': ['AdGroupId', 'Id', 'PlacementUrl'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['PLACEMENT'] - }], + 'fields': ['Id', 'Name', 'Status'], 'paging': { 'startIndex': str(offset), 'numberResults': str(PAGE_SIZE) } } + more_pages = True while more_pages: - page = ad_group_criterion_service.get(selector) + page = campaign_service.get(selector) # Display results. if 'entries' in page: - for criterion in page['entries']: - print ('Placement ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\' and url \'%s\'.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) else: - print 'No placements were found.' + print 'No campaigns were found.' offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) if __name__ == '__main__': - # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..68bb3be3 --- /dev/null +++ b/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,65 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201601') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adxbuyer/v201509/basic_operations/get_placements.py b/examples/adwords/v201601/basic_operations/get_keywords.py similarity index 59% rename from examples/adxbuyer/v201509/basic_operations/get_placements.py rename to examples/adwords/v201601/basic_operations/get_keywords.py index 1a4338b6..1f9ae5d5 100755 --- a/examples/adxbuyer/v201509/basic_operations/get_placements.py +++ b/examples/adwords/v201601/basic_operations/get_keywords.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -16,7 +16,7 @@ """This example gets all ad group criteria in an account. -To add placements, run add_placements.py. +To add keywords, run add_keywords.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -31,25 +31,35 @@ PAGE_SIZE = 500 +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -def main(client): + +def main(client, adgroup_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') + 'AdGroupCriterionService', version='v201601') # Construct selector and get all ad group criteria. offset = 0 selector = { - 'fields': ['AdGroupId', 'Id', 'PlacementUrl'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['PLACEMENT'] - }], + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], 'paging': { 'startIndex': str(offset), 'numberResults': str(PAGE_SIZE) - } + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] } more_pages = True while more_pages: @@ -57,13 +67,15 @@ def main(client): # Display results. if 'entries' in page: - for criterion in page['entries']: - print ('Placement ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\' and url \'%s\'.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\' was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) else: - print 'No placements were found.' + print 'No keywords were found.' offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) @@ -73,4 +85,4 @@ def main(client): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) + main(adwords_client, ADGROUP_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py b/examples/adwords/v201601/basic_operations/get_text_ads.py similarity index 90% rename from examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py rename to examples/adwords/v201601/basic_operations/get_text_ads.py index 0b4d794d..4e9e4b2b 100755 --- a/examples/adxbuyer/v201506/basic_operations/get_third_party_redirect_ads.py +++ b/examples/adwords/v201601/basic_operations/get_text_ads.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all third party ads for a given ad group. +"""This example gets all text ads for a given ad group. -To add a third party ad, add_third_party_redirect_ad.py. +To add an ad, run add_text_ads.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -35,7 +35,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') # Construct selector and get all ads for a given ad group. offset = 0 @@ -50,7 +50,7 @@ def main(client, ad_group_id): { 'field': 'AdType', 'operator': 'EQUALS', - 'values': ['THIRD_PARTY_REDIRECT_AD'] + 'values': ['TEXT_AD'] } ], 'paging': { diff --git a/examples/adwords/v201601/basic_operations/pause_ad.py b/examples/adwords/v201601/basic_operations/pause_ad.py new file mode 100755 index 00000000..1f3e4c63 --- /dev/null +++ b/examples/adwords/v201601/basic_operations/pause_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201601/basic_operations/remove_ad.py b/examples/adwords/v201601/basic_operations/remove_ad.py new file mode 100755 index 00000000..0e8cd7e2 --- /dev/null +++ b/examples/adwords/v201601/basic_operations/remove_ad.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201601/basic_operations/remove_ad_group.py b/examples/adwords/v201601/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..dc8b8961 --- /dev/null +++ b/examples/adwords/v201601/basic_operations/remove_ad_group.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201601') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/basic_operations/remove_campaign.py b/examples/adwords/v201601/basic_operations/remove_campaign.py new file mode 100755 index 00000000..bbd99e10 --- /dev/null +++ b/examples/adwords/v201601/basic_operations/remove_campaign.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201601') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adxbuyer/v201509/basic_operations/remove_placement.py b/examples/adwords/v201601/basic_operations/remove_keyword.py similarity index 91% rename from examples/adxbuyer/v201509/basic_operations/remove_placement.py rename to examples/adwords/v201601/basic_operations/remove_keyword.py index e22a904c..2d627a80 100755 --- a/examples/adxbuyer/v201509/basic_operations/remove_placement.py +++ b/examples/adwords/v201601/basic_operations/remove_keyword.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -16,7 +16,7 @@ """This example deletes an ad group criterion using the 'REMOVE' operator. -To get ad group criteria, run get_placements.py. +To get ad group criteria, run get_keywords.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -36,7 +36,7 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') + 'AdGroupCriterionService', version='v201601') # Construct operations and delete ad group criteria. operations = [ @@ -46,7 +46,6 @@ def main(client, ad_group_id, criterion_id): 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', 'id': criterion_id } } diff --git a/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py b/examples/adwords/v201601/basic_operations/update_ad_group.py similarity index 51% rename from examples/adxbuyer/v201506/basic_operations/add_ad_groups.py rename to examples/adwords/v201601/basic_operations/update_ad_group.py index ba3920e5..a894d396 100755 --- a/examples/adxbuyer/v201506/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201601/basic_operations/update_ad_group.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example adds ad groups to a given campaign. +"""This example updates status for a given ad group. To get ad groups, run get_ad_groups.py. @@ -26,59 +26,29 @@ """ -import uuid - from googleads import adwords -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -def main(client, campaign_id): +def main(client, ad_group_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201506') + ad_group_service = client.GetService('AdGroupService', version='v201601') - # Construct operations and add ad groups. + # Construct operations and update an ad group. operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } - } - }, { - 'operator': 'ADD', + 'operator': 'SET', 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } + 'id': ad_group_id, + 'status': 'PAUSED' } }] ad_groups = ad_group_service.mutate(operations) # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' + print ('Ad group with name \'%s\' and id \'%s\' was updated.' % (ad_group['name'], ad_group['id'])) @@ -86,4 +56,4 @@ def main(client, campaign_id): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/basic_operations/update_campaign.py b/examples/adwords/v201601/basic_operations/update_campaign.py new file mode 100755 index 00000000..c34b2b04 --- /dev/null +++ b/examples/adwords/v201601/basic_operations/update_campaign.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201601') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/update_placement.py b/examples/adwords/v201601/basic_operations/update_keyword.py similarity index 78% rename from examples/adxbuyer/v201506/basic_operations/update_placement.py rename to examples/adwords/v201601/basic_operations/update_keyword.py index fad84fcf..cad55b8e 100755 --- a/examples/adxbuyer/v201506/basic_operations/update_placement.py +++ b/examples/adwords/v201601/basic_operations/update_keyword.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates the bid of a placement. +"""This example updates the bid of a keyword. -To add a placement, run add_placements.py. +To add a keyword, run add_keywords.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,31 +30,31 @@ AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_PLACEMENT_CRITERION_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' def main(client, ad_group_id, criterion_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') + 'AdGroupCriterionService', version='v201601') # Construct operations and update bids. + operations = [{ 'operator': 'SET', 'operand': { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', 'id': criterion_id, }, 'biddingStrategyConfiguration': { 'bids': [ { - 'xsi_type': 'CpmBid', + 'xsi_type': 'CpcBid', 'bid': { 'microAmount': '1000000' - }, + } } ] } @@ -67,9 +67,11 @@ def main(client, ad_group_id, criterion_id): for criterion in ad_group_criteria['value']: if criterion['criterion']['Criterion.Type'] == 'Keyword': print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' had its bid set to \'%s\'.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['bids']['maxCpc']['amount']['microAmount'])) + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) else: print 'No ad group criteria were updated.' diff --git a/examples/adxbuyer/v201509/campaign_management/__init__.py b/examples/adwords/v201601/campaign_management/__init__.py similarity index 92% rename from examples/adxbuyer/v201509/campaign_management/__init__.py rename to examples/adwords/v201601/campaign_management/__init__.py index db098bda..afa503f3 100644 --- a/examples/adxbuyer/v201509/campaign_management/__init__.py +++ b/examples/adwords/v201601/campaign_management/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. diff --git a/examples/adxbuyer/v201506/basic_operations/remove_placement.py b/examples/adwords/v201601/campaign_management/add_campaign_labels.py similarity index 50% rename from examples/adxbuyer/v201506/basic_operations/remove_placement.py rename to examples/adwords/v201601/campaign_management/add_campaign_labels.py index cf0e59aa..78d075ac 100755 --- a/examples/adxbuyer/v201506/basic_operations/remove_placement.py +++ b/examples/adwords/v201601/campaign_management/add_campaign_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_placements.py. +"""This example adds a label to multiple campaigns. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -29,41 +27,42 @@ from googleads import adwords -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' -def main(client, ad_group_id, criterion_id): +def main(client, campaign_id1, campaign_id2, label_id): # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') + campaign_service = client.GetService('CampaignService', version='v201601') - # Construct operations and delete ad group criteria. operations = [ { - 'operator': 'REMOVE', + 'operator': 'ADD', 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'id': criterion_id - } + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, } } ] - result = ad_group_criterion_service.mutate(operations) + + result = campaign_service.mutateLabel(operations) # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID, CRITERION_ID) + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..60a149c8 --- /dev/null +++ b/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,428 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper() + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201601') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding a TextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new TextAd for each of + the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'period': 'DAILY' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201601/campaign_management/add_experiment.py b/examples/adwords/v201601/campaign_management/add_experiment.py new file mode 100755 index 00000000..04ea5775 --- /dev/null +++ b/examples/adwords/v201601/campaign_management/add_experiment.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates an experiment. + +The created experiment is using a query percentage of 10, which defines what +fraction of auctions should go to the control split (90%) vs. the experiment +split (10%), then adds experimental bid changes for an ad group, and adds an +experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad +groups, run get_ad_groups.py. To get keywords, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, campaign_id, ad_group_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201601') + ad_group_service = client.GetService('AdGroupService', version='v201601') + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201601') + + # Construct operations and add experiment. + tomorrow = datetime.datetime.now() + datetime.timedelta(1) + thirty_days = datetime.datetime.now() + datetime.timedelta(30) + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), + 'queryPercentage': '10', + 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), + # Optional fields. + 'status': 'ENABLED', + 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was added.' + % (experiment['name'], experiment['id'])) + + # Construct operations and update ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'experimentData': { + 'xsi_type': 'AdGroupExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'MODIFIED', + 'experimentBidMultipliers': { + 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', + 'maxCpcMultiplier': { + 'multiplier': '0.5' + } + } + } + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' + 'experiment.' % (ad_group['name'], ad_group['id'])) + + # Construct operations and add ad group crierion. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + }, + 'experimentData': { + 'xsi_type': 'BiddableAdGroupCriterionExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'EXPERIMENT_ONLY' + } + } + }] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\' and criterion ' + 'id \'%s\' was added to the experiment.' + % (criterion['adGroupId'], criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201509/campaign_management/add_placements_in_bulk.py b/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py similarity index 86% rename from examples/adxbuyer/v201509/campaign_management/add_placements_in_bulk.py rename to examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py index 878b9c47..131369c0 100755 --- a/examples/adxbuyer/v201509/campaign_management/add_placements_in_bulk.py +++ b/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Illustrates how to perform asynchronous requests using the MutateJobService. +"""This code sample illustrates how to perform asynchronous requests. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -34,7 +34,7 @@ RETRY_INTERVAL = 10 RETRIES_COUNT = 30 -PLACEMENT_NUMBER = 100 +KEYWORD_NUMBER = 100 INDEX_REGEX = r'operations\[(\d+)\].operand' AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' @@ -42,16 +42,16 @@ def main(client, ad_group_id): # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201509') + mutate_job_service = client.GetService('MutateJobService', version='v201601') # Create list of all operations for the job. operations = [] - # Create AdGroupCriterionOperations to add placements. - for i in range(PLACEMENT_NUMBER): - url = 'www.example.com/mars%d' % i + # Create AdGroupCriterionOperations to add keywords. + for i in range(KEYWORD_NUMBER): + keyword = 'mars%d' % i if random.randint(1, 10) == 1: - url = 'NOT_@_URL' + keyword += '!!!' operations.append({ 'xsi_type': 'AdGroupCriterionOperation', 'operator': 'ADD', @@ -59,8 +59,9 @@ def main(client, ad_group_id): 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', - 'url': url + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': keyword } } }) @@ -122,9 +123,9 @@ def main(client, ad_group_id): for error in result_response['SimpleMutateResult']['errors']: index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) reason = error['reason'] - url = operations[index]['operand']['criterion']['url'] - print ('ERROR - placement \'%s\' failed due to \'%s\'' % - (url, reason)) + keyword = operations[index]['operand']['criterion']['text'] + print ('ERROR - keyword \'%s\' failed due to \'%s\'' % + (keyword, reason)) if __name__ == '__main__': diff --git a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..1bd033f0 --- /dev/null +++ b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Construct selector and get all ads for a given ad group. + selector = { + 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'AdGroupCreativeApprovalStatus', + 'operator': 'IN', + 'values': ['DISAPPROVED'] + } + ] + } + ads = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..113e47cf --- /dev/null +++ b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, AdGroupAdDisapprovalReasons ' + 'WHERE CampaignId = %s AND ' + 'AdGroupCreativeApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % campaign_id) + ads = ad_group_ad_service.query(query) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..8a133533 --- /dev/null +++ b/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time + +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201601') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201601/campaign_management/promote_experiment.py b/examples/adwords/v201601/campaign_management/promote_experiment.py new file mode 100755 index 00000000..19f404ac --- /dev/null +++ b/examples/adwords/v201601/campaign_management/promote_experiment.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 promotes an experiment. + +Promoting an experiment permanently applies all the experimental changes made to +its related ad groups, criteria and ads. To add an experiment, run +add_experiment.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' + + +def main(client, experiment_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201601') + + # Construct operations and promote experiment. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': experiment_id, + 'status': 'PROMOTED' + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was promoted.' + % (experiment['name'], experiment['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201601/campaign_management/set_ad_parameters.py b/examples/adwords/v201601/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..ca7a1b2b --- /dev/null +++ b/examples/adwords/v201601/campaign_management/set_ad_parameters.py @@ -0,0 +1,101 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + ad_param_service = client.GetService('AdParamService', version='v201601') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..142d0367 --- /dev/null +++ b/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201601') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201601/campaign_management/validate_text_ad.py b/examples/adwords/v201601/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..74bd9e37 --- /dev/null +++ b/examples/adwords/v201601/campaign_management/validate_text_ad.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Construct operations to add a text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'url': 'http://www.example.com', + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for all astronauts in orbit', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201509/error_handling/__init__.py b/examples/adwords/v201601/error_handling/__init__.py similarity index 92% rename from examples/adxbuyer/v201509/error_handling/__init__.py rename to examples/adwords/v201601/error_handling/__init__.py index b5203c57..7b767e05 100644 --- a/examples/adxbuyer/v201509/error_handling/__init__.py +++ b/examples/adwords/v201601/error_handling/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. diff --git a/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py b/examples/adwords/v201601/error_handling/handle_partial_failures.py similarity index 69% rename from examples/adxbuyer/v201506/error_handling/handle_partial_failures.py rename to examples/adwords/v201601/error_handling/handle_partial_failures.py index 25f09598..60e96913 100755 --- a/examples/adxbuyer/v201506/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201601/error_handling/handle_partial_failures.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2013 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -40,69 +40,75 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') + 'AdGroupCriterionService', version='v201601') - # Construct placement ad group criteria objects. - placements = [ + # Construct keyword ad group criteria objects. + keywords = [ { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', - 'url': 'www.example.com/something' + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' } }, { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', - 'url': 'INVALID!!_URL' + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' } }, { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', - 'url': 'www.example.com/somethingelse' + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' } }, { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id, 'criterion': { - 'xsi_type': 'Placement', - 'url': 'BAD!!_URL' + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' } } ] # Construct operations and add ad group criteria. operations = [] - for placement in placements: + for keyword in keywords: operations.append( { 'operator': 'ADD', - 'operand': placement + 'operand': keyword }) result = ad_group_criterion_service.mutate(operations) # Display results. for criterion in result['value']: if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added placement ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\' and url \'%s\'' + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) + criterion['criterion']['text'], + criterion['criterion']['matchType'])) for error in result['partialFailureErrors']: index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) if index: - print ('Placement ad group criterion with ad group id \'%s\' and url ' + print ('Keyword ad group criterion with ad group id \'%s\' and text ' '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (placements[int(index[0])]['adGroupId'], - placements[int(index[0])]['criterion']['url'], + % (keywords[int(index[0])]['adGroupId'], + keywords[int(index[0])]['criterion']['text'], error['errorString'])) else: print 'The following failure has occurred: \'%s\'.' % error['errorString'] diff --git a/examples/adwords/v201601/error_handling/handle_policy_violation_error.py b/examples/adwords/v201601/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..7dcaf20a --- /dev/null +++ b/examples/adwords/v201601/error_handling/handle_policy_violation_error.py @@ -0,0 +1,115 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201601') + + # Create text ad. + text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'TextAd', + 'headline': 'Mars Cruise!!!', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com', + } + } + } + + operations = [text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + if error['ApiError.Type'] == 'PolicyViolationError': + operation_index = re.findall(r'operations\[(.*)\]\.', + error['fieldPath']) + if operation_index: + operation = operations[int(operation_index[0])] + print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % + (operation['operand']['ad']['headline'], + 'exemptable' if error['isExemptable'] else 'non-exemptable', + error['externalPolicyName'])) + if error['isExemptable'].lower() == 'true': + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text ' + '\'%s\'.' % + (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({ + 'key': error['key'] + }) + else: + # Remove non-exemptable operation + print 'Removing the operation from the request.' + operations.delete(operation) + else: + # Non-policy error returned, re-throw exception. + raise e + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201506/basic_operations/__init__.py b/examples/adwords/v201601/extensions/__init__.py similarity index 86% rename from examples/adxbuyer/v201506/basic_operations/__init__.py rename to examples/adwords/v201601/extensions/__init__.py index 80acbea9..594717b1 100644 --- a/examples/adxbuyer/v201506/basic_operations/__init__.py +++ b/examples/adwords/v201601/extensions/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Basic operations examples.""" +"""Extension examples.""" diff --git a/examples/adwords/v201601/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201601/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..5fc14a00 --- /dev/null +++ b/examples/adwords/v201601/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201601').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201601') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201601/extensions/add_site_links.py b/examples/adwords/v201601/extensions/add_site_links.py new file mode 100755 index 00000000..ffd6d5ee --- /dev/null +++ b/examples/adwords/v201601/extensions/add_site_links.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201601') + customer_service = client.GetService('CustomerService', version='v201601') + + customer_tz = timezone(customer_service.get()['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt) + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'} + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/extensions/add_site_links_using_feeds.py b/examples/adwords/v201601/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..67adb6ec --- /dev/null +++ b/examples/adwords/v201601/extensions/add_site_links_using_feeds.py @@ -0,0 +1,234 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid + +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_1_TEXT = '3' +PLACEHOLDER_FIELD_LINE_2_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201601') + feed_item_service = client.GetService('FeedItemService', version='v201601') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201601') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201601') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 1 Description'}, + {'type': 'STRING', 'name': 'Line 2 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_1_feed_attribute_id = feed['attributes'][2]['id'] + line_2_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % + (line_1_feed_attribute_id, line_2_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line1FeedId'] = line_1_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line1': 'Home line 1', 'line2': 'Home line 2'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line1': 'Support line 1', 'line2': 'Support line 2'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line1': 'Products line 1', 'line2': 'Products line 2'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'stringValue': item['line1'] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/migration/__init__.py b/examples/adwords/v201601/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201601/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201601/migration/migrate_to_extension_settings.py b/examples/adwords/v201601/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..94aa1614 --- /dev/null +++ b/examples/adwords/v201601/migration/migrate_to_extension_settings.py @@ -0,0 +1,528 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201601') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201601') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201601') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201601') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201601') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201601') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201601') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/migration/upgrade_ad_url.py b/examples/adwords/v201601/migration/upgrade_ad_url.py new file mode 100755 index 00000000..46c465cb --- /dev/null +++ b/examples/adwords/v201601/migration/upgrade_ad_url.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2016 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 upgrades an ad to use upgraded URLs. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, adgroup_id, ad_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201601') + + selector = { + 'fields': ['Id', 'Url'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [ad_id] + } + ] + } + + page = adgroup_ad_service.get(selector) + + adgroup_ad = page['entries'][0] if page['entries'] else None + + if not adgroup_ad: + raise errors.GoogleAdsError('Ad not found.') + + ad_url_upgrade = { + 'adId': adgroup_ad['ad']['id'], + 'finalUrl': adgroup_ad['ad']['url'] + } + + adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] + + if adgroup_ad: + print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' + % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201601/misc/__init__.py b/examples/adwords/v201601/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201601/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201601/misc/get_all_images_and_videos.py b/examples/adwords/v201601/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..76c47961 --- /dev/null +++ b/examples/adwords/v201601/misc/get_all_images_and_videos.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201601') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/misc/upload_image.py b/examples/adwords/v201601/misc/upload_image.py new file mode 100755 index 00000000..d0ef6e5c --- /dev/null +++ b/examples/adwords/v201601/misc/upload_image.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 + +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201601') + + with open(image_filename, 'r') as image_handle: + image_data = base64.encodestring(image_handle.read()) + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201601/misc/upload_media_bundle.py b/examples/adwords/v201601/misc/upload_media_bundle.py new file mode 100755 index 00000000..3a180119 --- /dev/null +++ b/examples/adwords/v201601/misc/upload_media_bundle.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201601') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201601/optimization/__init__.py b/examples/adwords/v201601/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201601/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201601/optimization/estimate_keyword_traffic.py b/examples/adwords/v201601/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..bb71c08d --- /dev/null +++ b/examples/adwords/v201601/optimization/estimate_keyword_traffic.py @@ -0,0 +1,133 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201601') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + selector = { + 'campaignEstimateRequests': [{ + 'adGroupEstimateRequests': [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }], + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ] + }] + } + estimates = traffic_estimator_service.get(selector) + + # Display results. + ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] + keyword_estimates = ad_group_estimate['keywordEstimates'] + for index in xrange(len(keyword_estimates)): + keyword = keyword_estimate_requests[index]['keyword'] + estimate = keyword_estimates[index] + if keyword_estimate_requests[index].get('isNegative', False): + continue + + # Find the mean of the min and max values. + mean_avg_cpc = (calc_mean(estimate['min']['averageCpc']['microAmount'], + estimate['max']['averageCpc']['microAmount']) + if 'averageCpc' in estimate['min'] else 'N/A') + mean_avg_pos = calc_mean(estimate['min']['averagePosition'], + estimate['max']['averagePosition']) + mean_clicks = calc_mean(estimate['min']['clicksPerDay'], + estimate['max']['clicksPerDay']) + mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], + estimate['max']['totalCost']['microAmount']) + + print ('Results for the keyword with text \'%s\' and match type \'%s\':' + % (keyword['text'], keyword['matchType'])) + print ' Estimated average CPC: %s' % mean_avg_cpc + print ' Estimated ad position: %s' % mean_avg_pos + print ' Estimated daily clicks: %s' % mean_clicks + print ' Estimated daily cost: %s' % mean_total_cost + + +def fmt_mean(mean): + if mean: + return '%.2f' % mean + else: + return None + + +def calc_mean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..ee8fb345 --- /dev/null +++ b/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201601') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201601/optimization/get_keyword_ideas.py b/examples/adwords/v201601/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..ef51b4b9 --- /dev/null +++ b/examples/adwords/v201601/optimization/get_keyword_ideas.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201601') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/remarketing/__init__.py b/examples/adwords/v201601/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201601/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201601/remarketing/add_audience.py b/examples/adwords/v201601/remarketing/add_audience.py new file mode 100755 index 00000000..5428cab0 --- /dev/null +++ b/examples/adwords/v201601/remarketing/add_audience.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201601') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201601') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/remarketing/add_conversion_tracker.py b/examples/adwords/v201601/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..6b0322a4 --- /dev/null +++ b/examples/adwords/v201601/remarketing/add_conversion_tracker.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201601') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/remarketing/add_crm_based_user_list.py b/examples/adwords/v201601/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..5b4f9df2 --- /dev/null +++ b/examples/adwords/v201601/remarketing/add_crm_based_user_list.py @@ -0,0 +1,97 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a remarketing user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client, emails): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201601') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180, + # This field is optional. It links to a service you created that allows + # members of this list to remove themselves. + 'optOutLink': 'http://endpoint1.example.com/optout' + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + hashed_emails = HashEmails(emails) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'dataType': 'EMAIL_SHA256', + 'members': hashed_emails + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def HashEmails(emails): + """Hashes the given emails using SHA-256. + + Note: Emails are stripped of any whitespace and set to lowercase before + hashing. + + Args: + emails: list of str emails to be hashed. + + Returns: + A list of SHA-256 hashed emails. + """ + return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + + +if __name__ == '__main__': + EMAILS = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, EMAILS) diff --git a/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..75c6423c --- /dev/null +++ b/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,184 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201601') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords will logically OR the + # groups together. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/remarketing/upload_offline_conversions.py b/examples/adwords/v201601/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..dc51ce2b --- /dev/null +++ b/examples/adwords/v201601/remarketing/upload_offline_conversions.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201601') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201601/reporting/__init__.py b/examples/adwords/v201601/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201601/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201601/reporting/download_criteria_report.py b/examples/adwords/v201601/reporting/download_criteria_report.py new file mode 100755 index 00000000..280899ac --- /dev/null +++ b/examples/adwords/v201601/reporting/download_criteria_report.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys + +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201601') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py new file mode 100755 index 00000000..fc6f98b6 --- /dev/null +++ b/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201601') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..740793bb --- /dev/null +++ b/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201601') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_string.py b/examples/adwords/v201601/reporting/download_criteria_report_as_string.py new file mode 100755 index 00000000..eaee4236 --- /dev/null +++ b/examples/adwords/v201601/reporting/download_criteria_report_as_string.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging + +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201601') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..f2454324 --- /dev/null +++ b/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201601') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=False) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..5b551e19 --- /dev/null +++ b/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client, path): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201601') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + with open(path, 'w') as output_file: + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', output_file, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=False) + + print 'Report was downloaded to \'%s\'.' % path + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, PATH) diff --git a/examples/adwords/v201601/reporting/get_report_fields.py b/examples/adwords/v201601/reporting/get_report_fields.py new file mode 100755 index 00000000..b89dc8e1 --- /dev/null +++ b/examples/adwords/v201601/reporting/get_report_fields.py @@ -0,0 +1,53 @@ +#!/usr/bin/python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201601') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201601/shopping/__init__.py b/examples/adwords/v201601/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201601/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201601/shopping/add_product_partition_tree.py b/examples/adwords/v201601/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..beb5b452 --- /dev/null +++ b/examples/adwords/v201601/shopping/add_product_partition_tree.py @@ -0,0 +1,282 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201601') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) + diff --git a/examples/adwords/v201601/shopping/add_product_scope.py b/examples/adwords/v201601/shopping/add_product_scope.py new file mode 100755 index 00000000..f0973f61 --- /dev/null +++ b/examples/adwords/v201601/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201601') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/shopping/add_shopping_campaign.py b/examples/adwords/v201601/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..24088044 --- /dev/null +++ b/examples/adwords/v201601/shopping/add_shopping_campaign.py @@ -0,0 +1,121 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id): + campaign_service = client.GetService('CampaignService', version='v201601') + ad_group_service = client.GetService('AdGroupService', version='v201601') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Set shared budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + adgroup = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group_result = ad_group_service.mutate(adgroup_operations) + + for adgroup in ad_group_result['value']: + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (adgroup['name'], adgroup['id'])) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': adgroup['id'], + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201601/shopping/get_product_category_taxonomy.py b/examples/adwords/v201601/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..f4f8a2c5 --- /dev/null +++ b/examples/adwords/v201601/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201601') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/targeting/__init__.py b/examples/adwords/v201601/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201601/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..805bc7b4 --- /dev/null +++ b/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,162 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201601') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create location groups. The IDs can be found in the documentation or + # retrieved with the LocationCriterionService. + florida_tier3 = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'IncomeOperand', + # Tiers are numbered 1-10, and represent 10% segments of earners. + # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. + # Tiers 6 through 10 are grouped into TIER_6_TO_10. + 'tier': 'TIER_3' + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + }, + } + florida_downtown = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'PlacesOfInterestOperand', + # Other valid options: AIRPORT, UNIVERSITY. + 'category': 'DOWNTOWN', + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + } + } + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish, florida_tier3, + florida_downtown] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..54b0f435 --- /dev/null +++ b/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,97 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201601') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..fec63a1a --- /dev/null +++ b/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,86 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201601') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..903b9360 --- /dev/null +++ b/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201601') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201601/targeting/lookup_location.py b/examples/adwords/v201601/targeting/lookup_location.py new file mode 100755 index 00000000..049fffd9 --- /dev/null +++ b/examples/adwords/v201601/targeting/lookup_location.py @@ -0,0 +1,83 @@ +#!/usr/bin/python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201601') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adxbuyer/v201506/__init__.py b/examples/adxbuyer/v201506/__init__.py deleted file mode 100644 index 55fdaeac..00000000 --- a/examples/adxbuyer/v201506/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Examples for DoubleClick Ad Exchange Buyer SOAP API.""" diff --git a/examples/adxbuyer/v201506/basic_operations/add_campaigns.py b/examples/adxbuyer/v201506/basic_operations/add_campaigns.py deleted file mode 100755 index a7958911..00000000 --- a/examples/adxbuyer/v201506/basic_operations/add_campaigns.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds campaigns. To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201506') - budget_service = client.GetService('BudgetService', version='v201506') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'DISPLAY', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPM', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'settings': [{ - 'xsi_type': 'RealTimeBiddingSetting', - 'optIn': 'true' - }], - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - } - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise Banners #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'DISPLAY', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPM', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'settings': [{ - 'xsi_type': 'RealTimeBiddingSetting', - 'optIn': 'true' - }], - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py b/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py deleted file mode 100755 index cabccf97..00000000 --- a/examples/adxbuyer/v201506/campaign_management/add_placements_in_bulk.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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. - -"""Illustrates how to perform asynchronous requests using the MutateJobService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import random -import re -import time - -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -PLACEMENT_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201506') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add placements. - for i in range(PLACEMENT_NUMBER): - url = 'www.example.com/mars%d' % i - if random.randint(1, 10) == 1: - url = 'NOT_@_URL' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': url - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - url = operations[index]['operand']['criterion']['url'] - print ('ERROR - placement \'%s\' failed due to \'%s\'' % - (url, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201509/__init__.py b/examples/adxbuyer/v201509/__init__.py deleted file mode 100644 index 55fdaeac..00000000 --- a/examples/adxbuyer/v201509/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Examples for DoubleClick Ad Exchange Buyer SOAP API.""" diff --git a/examples/adxbuyer/v201509/basic_operations/add_placements.py b/examples/adxbuyer/v201509/basic_operations/add_placements.py deleted file mode 100755 index 0aa78015..00000000 --- a/examples/adxbuyer/v201509/basic_operations/add_placements.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct keyword ad group criterion object. - placement1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'http://mars.google.com' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'destinationUrl': 'http://example.com/mars' - } - - placement2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'http://example.com/pluto' - }, - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': placement1 - }, - { - 'operator': 'ADD', - 'operand': placement2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Placement ad group criterion with ad group id \'%s\', criterion ' - 'id \'%s\', and url \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201509/basic_operations/add_third_party_redirect_ad.py b/examples/adxbuyer/v201509/basic_operations/add_third_party_redirect_ad.py deleted file mode 100755 index 409fcfb5..00000000 --- a/examples/adxbuyer/v201509/basic_operations/add_third_party_redirect_ad.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 adds several third party ads to a given ad group. - -To get an ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Construct operations and add ads. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ThirdPartyRedirectAd', - 'name': 'Example third party ad #%s' % uuid.uuid4(), - 'url': 'http://www.example.com', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - # This field normally contains the javascript ad tag. - 'snippet': (''), - 'certifiedVendorFormatId': '232', - 'isCookieTargeted': 'false', - 'isUserInterestTargeted': 'false', - 'isTagged': 'false', - 'richMediaAdType': 'STANDARD', - 'expandingDirections': ['EXPANDING_UP', 'EXPANDING_DOWN'], - 'adAttributes': ['ROLL_OVER_TO_EXPAND'] - } - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ThirdPartyRedirectAd', - 'name': 'Example third party ad #%s' % uuid.uuid4(), - 'url': 'http://www.example.com', - 'adDuration': '15000', - 'sourceUrl': ('http://ad.doubleclick.net/pfadx/N270.126913.' - '6102203221521/B3876671.21;dcadv=2215309;' - 'sz=0x0;ord=%5btimestamp%5d;dcmt=text/xml'), - 'certifiedVendorFormatId': '303', - 'richMediaAdType': 'IN_STREAM_VIDEO' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with ID \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adxbuyer/v201509/basic_operations/update_placement.py b/examples/adxbuyer/v201509/basic_operations/update_placement.py deleted file mode 100755 index cfaec8b4..00000000 --- a/examples/adxbuyer/v201509/basic_operations/update_placement.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 updates the bid of a placement. - -To add a placement, run add_placements.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_PLACEMENT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct operations and update bids. - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpmBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' had its bid set to \'%s\'.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['bids']['maxCpc']['amount']['microAmount'])) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adxbuyer/v201509/error_handling/handle_partial_failures.py b/examples/adxbuyer/v201509/error_handling/handle_partial_failures.py deleted file mode 100755 index 4e8d1ac9..00000000 --- a/examples/adxbuyer/v201509/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2013 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct placement ad group criteria objects. - placements = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'www.example.com/something' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'INVALID!!_URL' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'www.example.com/somethingelse' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Placement', - 'url': 'BAD!!_URL' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for placement in placements: - operations.append( - { - 'operator': 'ADD', - 'operand': placement - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added placement ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\' and url \'%s\'' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['url'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Placement ad group criterion with ad group id \'%s\' and url ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (placements[int(index[0])]['adGroupId'], - placements[int(index[0])]['criterion']['url'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py index c6ba0516..5d927606 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/dfp/authentication/generate_refresh_token.py @@ -24,17 +24,17 @@ # Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet, # please go to https://console.developers.google.com and create a set. -CLIENT_ID = 'INSERT_CLIENT_ID_HERE' -CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' +DEFAULT_CLIENT_ID = None +DEFAULT_CLIENT_SECRET = None # The DFP API OAuth 2.0 scope. SCOPE = u'https://www.googleapis.com/auth/dfp' parser = argparse.ArgumentParser(description='Generates a refresh token with ' 'the provided credentials.') -parser.add_argument('--client_id', default=CLIENT_ID, +parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID, help='Client Id retrieved from the Developer\'s Console.') -parser.add_argument('--client_secret', default=CLIENT_SECRET, +parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET, help='Client Secret retrieved from the Developer\'s ' 'Console.') parser.add_argument('--additional_scopes', default=None, @@ -72,7 +72,8 @@ def main(client_id, client_secret, scopes): if __name__ == '__main__': args = parser.parse_args() configured_scopes = [SCOPE] - if args.client_id == CLIENT_ID or args.client_secret == CLIENT_SECRET: + if not (any([args.client_id, DEFAULT_CLIENT_ID]) and + any([args.client_secret, DEFAULT_CLIENT_SECRET])): raise AttributeError('No client_id or client_secret specified.') if args.additional_scopes: configured_scopes.extend(args.additional_scopes.replace(' ', '').split(',')) diff --git a/googleads/adwords.py b/googleads/adwords.py index c0a2509a..a61cf2a2 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -27,6 +27,7 @@ import suds.mx.literal import suds.xsd.doctor import xmltodict +import yaml import googleads.common import googleads.errors @@ -119,6 +120,49 @@ 'BiddingStrategyService': 'cm', 'AdwordsUserListService': 'rm', 'LabelService': 'cm', + }, + 'v201601': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'BatchJobService': 'cm', + 'BudgetOrderService': 'billing', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'ExperimentService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LocationCriterionService': 'cm', + 'MediaService': 'cm', + 'MutateJobService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'ManagedCustomerService': 'mcm', + 'CustomerService': 'mcm', + 'CustomerFeedService': 'cm', + 'BudgetService': 'cm', + 'BiddingStrategyService': 'cm', + 'AdwordsUserListService': 'rm', + 'LabelService': 'cm', } } @@ -297,7 +341,7 @@ def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], client=self, version=version, server=server) response_parser = BatchJobHelper.GetResponseParser() - return BatchJobHelper(request_builder, response_parser) + return BatchJobHelper(request_builder, response_parser, version=version) def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=_DEFAULT_ENDPOINT): @@ -485,8 +529,8 @@ def __init__(self, **kwargs): if 'client' not in kwargs: raise AttributeError('No client specified for Request Builder.') - self._client = kwargs['client'] self._version = kwargs.get('version', sorted(_SERVICE_MAP.keys())[-1]) + self._client = kwargs['client'] server = kwargs.get('server', _DEFAULT_ENDPOINT) self._adwords_endpoint = ('%s/api/adwords/cm/%s' % (server, self._version)) @@ -514,9 +558,8 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): A urllib2.Request instance with the correct method, headers, and padding (if required) for the batch job upload. """ - is_incremental = 'current_content_length' in kwargs current_content_length = kwargs.get('current_content_length', 0) - is_last = kwargs.get('is_last') if is_incremental else True + is_last = kwargs.get('is_last') # Generate an unpadded request body request_body = self._BuildUploadRequestBody( operations, @@ -524,22 +567,20 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): has_suffix=is_last) req = urllib2.Request(upload_url) req.add_header('Content-Type', 'application/xml') - # Add padding, headers, and modify request method for incremental upload. - if is_incremental: - # Determine length of this message and the required padding. - new_content_length = current_content_length - request_length = len(request_body.encode('utf-8')) - padding_length = self._GetPaddingLength(request_length) - padded_request_length = request_length + padding_length - new_content_length += padded_request_length - request_body += ' ' * padding_length - req.get_method = lambda: 'PUT' # Modify this into a PUT request. - req.add_header('Content-Length', padded_request_length) - req.add_header('Content-Range', 'bytes %s-%s/%s' % ( - current_content_length, - new_content_length - 1, - new_content_length if is_last else '*' - )) + # Determine length of this message and the required padding. + new_content_length = current_content_length + request_length = len(request_body.encode('utf-8')) + padding_length = self._GetPaddingLength(request_length) + padded_request_length = request_length + padding_length + new_content_length += padded_request_length + request_body += ' ' * padding_length + req.get_method = lambda: 'PUT' # Modify this into a PUT request. + req.add_header('Content-Length', padded_request_length) + req.add_header('Content-Range', 'bytes %s-%s/%s' % ( + current_content_length, + new_content_length - 1, + new_content_length if is_last else '*' + )) req.data = request_body return req @@ -699,7 +740,8 @@ def _GetRawOperationsFromXML(self, raw_request_xml): return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( '%smutate' % self._adwords_namespace) - def __init__(self, request_builder, response_parser): + def __init__(self, request_builder, response_parser, + version=sorted(_SERVICE_MAP.keys())[-1]): """Initializes the BatchJobHelper. For general use, consider using AdWordsClient's GetBatchJobHelper method to @@ -709,10 +751,14 @@ def __init__(self, request_builder, response_parser): Args: request_builder: an AbstractUploadRequestBuilder instance. response_parser: an AbstractResponseParser instance. + version: A string identifying the AdWords version to connect to. This + defaults to what is currently the latest version. This will be updated + in future releases to point to what is then the latest version. """ self._temporary_id = 0 # Used for temporary IDs in BatchJobService. self._request_builder = request_builder self._response_parser = response_parser + self._version = version def GetId(self): """Produces a distinct sequential ID for the BatchJobService. @@ -723,8 +769,10 @@ def GetId(self): self._temporary_id -= 1 return self._temporary_id - def GetIncrementalUploadHelper(self, upload_url): - return IncrementalUploadHelper(self._request_builder, upload_url) + def GetIncrementalUploadHelper(self, upload_url, current_content_length=0): + return IncrementalUploadHelper(self._request_builder, upload_url, + current_content_length, + version=self._version) @classmethod def GetRequestBuilder(cls, **kwargs): @@ -763,34 +811,134 @@ def UploadOperations(self, upload_url, *operations): *operations: one or more lists of operations as would be sent to the AdWords API for the associated service. """ - req = self._request_builder.BuildUploadRequest(upload_url, operations) - urllib2.urlopen(req) + uploader = IncrementalUploadHelper(self._request_builder, upload_url, + version=self._version) + uploader.UploadOperations(operations, is_last=True) class IncrementalUploadHelper(object): """A utility for uploading operations for a BatchJob incrementally.""" + @classmethod + def Load(cls, file_input, client=None): + """Loads an IncrementalUploadHelper from the given file-like object. + + Args: + file_input: a file-like object containing a serialized + IncrementalUploadHelper. + client: an AdWordsClient instance. + + Returns: + An IncrementalUploadHelper instance initialized using the contents of the + serialized input file. + + Raises: + GoogleAdsError: If there is an error reading the input file containing the + serialized IncrementalUploadHelper. + GoogleAdsValueError: If the contents of the input file can't be parsed to + produce an IncrementalUploadHelper. + """ + if client is None: + client = AdWordsClient.LoadFromStorage() + + try: + data = yaml.safe_load(file_input) + except yaml.YAMLError: + raise googleads.errors.GoogleAdsError( + 'Error loading IncrementalUploadHelper from file.') + + batch_job_helper = client.GetBatchJobHelper(version=data['version']) + request_builder = batch_job_helper.GetRequestBuilder( + client=client, version=data['version']) + + try: + return cls(request_builder, data['upload_url'], + current_content_length=data['current_content_length'], + is_last=data['is_last'], version=data['version']) + except KeyError: + raise googleads.errors.GoogleAdsValueError( + 'Can\'t parse IncrementalUploadHelper from file.') + def __init__(self, request_builder, upload_url, current_content_length=0, - is_last=False): + is_last=False, version=sorted(_SERVICE_MAP.keys())[-1]): """Initializes the IncrementalUpload. Args: request_builder: an AbstractUploadRequestBuilder instance. - upload_url: a string url that the given operations will be uploaded to. + upload_url: a string url provided by the BatchJobService. current_content_length: an integer identifying the current content length of data uploaded to the Batch Job. is_last: a boolean indicating whether this is the final increment. + version: A string identifying the AdWords version to connect to. This + defaults to what is currently the latest version. This will be updated + in future releases to point to what is then the latest version. Raises: GoogleAdsValueError: if the content length is lower than 0. """ + self._version = version self._request_builder = request_builder - self._upload_url = upload_url if current_content_length < 0: raise googleads.errors.GoogleAdsValueError( 'Current content length %s is < 0.' % current_content_length) self._current_content_length = current_content_length + self._upload_url = self._InitializeURL(upload_url, current_content_length) self._is_last = is_last + def _InitializeURL(self, upload_url, current_content_length): + """Ensures that the URL used to upload operations is properly initialized. + + Initialization is only necessary in v201601 or higher when the + current_content_length is 0. + + Args: + upload_url: a string url. + current_content_length: an integer identifying the current content length + of data uploaded to the Batch Job. + + Returns: + An initialized string URL, or the provided string URL if the URL has + already been initialized or the version is below v201601. + """ + # If initialization is not necessary, return the provided upload_url. + if (self._version < 'v201601' + or current_content_length != 0): + return upload_url + + headers = { + 'Content-Type': 'application/xml', + 'Content-Length': 0, + 'x-goog-resumable': 'start' + } + + # Send an HTTP POST request to the given upload_url + req = urllib2.Request(upload_url, data={}, headers=headers) + resp = urllib2.urlopen(req) + + return resp.headers['location'] + + def Dump(self, output): + """Serialize the IncrementalUploadHelper and store in file-like object. + + Args: + output: a file-like object where the status of the IncrementalUploadHelper + will be written. + + Raises: + GoogleAdsError: If a YAMLError occurs while writing to the file. + """ + data = { + 'current_content_length': self._current_content_length, + 'is_last': self._is_last, + 'upload_url': self._upload_url, + 'version': self._version + } + + try: + yaml.dump(data, output) + except yaml.YAMLError: + raise googleads.errors.GoogleAdsError( + 'Error dumping IncrementalUploadHelper to file.') + def UploadOperations(self, operations, is_last=False): """Uploads operations to the given uploadUrl in incremental steps. @@ -803,10 +951,6 @@ def UploadOperations(self, operations, is_last=False): AdWords API for the associated service. is_last: a boolean indicating whether this is the final increment to be added to the batch job. - - Returns: - A BatchJobHelper.BatchJobUploadStatus instance that should be provided in - requests to upload additional increments. """ if self._is_last is True: raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( diff --git a/googleads/common.py b/googleads/common.py index e051f9ff..dae836af 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -27,7 +27,7 @@ import googleads.errors import googleads.oauth2 -VERSION = '3.11.0' +VERSION = '3.12.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], diff --git a/setup.py b/setup.py index 9798d97a..c738ecc8 100755 --- a/setup.py +++ b/setup.py @@ -57,7 +57,6 @@ def GetVersion(): The googleads Python Client Libraries support the following products: * AdWords API -* DoubleClick for Advertisers API * DoubleClick for Publishers API You can find more information about the Google Ads Python Client Libraries @@ -113,7 +112,7 @@ def GetVersion(): long_description=long_description, packages=PACKAGES, platforms='any', - keywords='adwords adxbuyer dfp google', + keywords='adwords dfp google', classifiers=CLASSIFIERS, install_requires=DEPENDENCIES, **extra_params) diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 1cde8469..f1a9fb01 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -18,6 +18,7 @@ import io import os +import StringIO import sys import tempfile import unittest @@ -279,7 +280,10 @@ def testUploadOperations(self): mock_request = mock.MagicMock() mock_build_request.return_value = mock_request with mock.patch('urllib2.urlopen') as mock_urlopen: - self.batch_job_helper.UploadOperations([[]]) + with mock.patch('googleads.adwords.IncrementalUploadHelper' + '._InitializeURL') as mock_init: + mock_init.return_value = 'https://www.google.com' + self.batch_job_helper.UploadOperations([[]]) mock_urlopen.assert_called_with(mock_request) @@ -293,9 +297,11 @@ def setUp(self): """Prepare tests.""" self.client = GetAdWordsClient() self.request_builder = self.client.GetBatchJobHelper()._request_builder + self.version = self.request_builder._version self.upload_url = 'https://goo.gl/IaQQsJ' self.sample_xml = ('!n3vERg0Nn4Run4r0und4NDd35Er7Y0u!~' '') + sample_xml_length = len(self.sample_xml) self.complete_request_body = '%s%s%s' % ( self.request_builder._UPLOAD_PREFIX_TEMPLATE % ( self.request_builder._adwords_endpoint), @@ -312,7 +318,14 @@ def setUp(self): self.request_body_end = '%s%s' % ( self.sample_xml, self.request_builder._UPLOAD_SUFFIX) - self.single_upload_headers = {'Content-type': 'application/xml'} + self.single_upload_headers = { + 'Content-type': 'application/xml', + 'Content-range': 'bytes %s-%s/%s' % ( + 0, + self.request_builder._BATCH_JOB_INCREMENT - 1, + self.request_builder._BATCH_JOB_INCREMENT), + 'Content-length': self.request_builder._BATCH_JOB_INCREMENT + } self.incremental_upload_headers = { 'Content-type': 'application/xml', 'Content-range': 'bytes %s-%s/*' % ( @@ -402,7 +415,8 @@ def GenerateValidRequest(self, operations): op['operand']['amount']['microAmount'], op['operand']['deliveryMethod'] ) for op in ops]) - request = self.RAW_API_REQUEST_TEMPLATE % (ops_xml) + request = self.RAW_API_REQUEST_TEMPLATE % (self.version, self.version, + ops_xml) return (ops, request) def GenerateValidUnicodeRequest(self, operations): @@ -423,7 +437,9 @@ def GenerateValidUnicodeRequest(self, operations): op[u'operand'][u'amount'][u'microAmount'], op[u'operand'][u'deliveryMethod'] ) for op in ops]) - request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % (ops_xml) + request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % (self.version, + self.version, + ops_xml) return (ops, request) def GenerateUnicodeBudgetOperations(self, operations): @@ -834,6 +850,7 @@ def testGetRawOperationsFromValidZeroOperationRequest(self): _, request = self.GenerateValidRequest(operations_amount) mutate = self.request_builder._GetRawOperationsFromXML(request) + self.assertEqual( mutate.tag, '{%s}mutate' % self.request_builder._adwords_endpoint) @@ -857,9 +874,10 @@ def testBuildRequestForSingleUpload(self): '_SudsUploadRequestBuilder.' '_BuildUploadRequestBody') as mock_request_body_builder: mock_request_body_builder.return_value = self.sample_xml - req = self.request_builder.BuildUploadRequest(self.upload_url, [[]]) + req = self.request_builder.BuildUploadRequest(self.upload_url, [[]], + is_last=True) self.assertEqual(req.headers, self.single_upload_headers) - self.assertEqual(req.get_method(), 'POST') + self.assertEqual(req.get_method(), 'PUT') def testBuildRequestForIncrementalUpload(self): """Test whether an incremental upload request is built correctly.""" @@ -937,9 +955,51 @@ def setUp(self): """Prepare tests.""" self.client = GetAdWordsClient() self.batch_job_helper = self.client.GetBatchJobHelper() - self.incremental_uploader = ( - self.batch_job_helper.GetIncrementalUploadHelper( - 'https://goo.gl/Xtaq83')) + self.original_url = 'https://goo.gl/w8tkpK' + self.initialized_url = 'https://goo.gl/Xtaq83' + + with mock.patch('urllib2.urlopen') as mock_open: + mock_open.return_value.headers = { + 'location': self.initialized_url + } + self.incremental_uploader = ( + self.batch_job_helper.GetIncrementalUploadHelper( + self.original_url)) + + self.incremental_uploader_dump = ( + '{current_content_length: 0, is_last: false, ' + 'upload_url: \'https://goo.gl/Xtaq83\', version: v201601}\n') + + def testDump(self): + expected = self.incremental_uploader_dump + + with tempfile.NamedTemporaryFile(delete=False, mode='w') as t: + name = t.name + self.incremental_uploader.Dump(t) + + with open(name, mode='r') as handler: + dump_data = handler.read() + + self.assertEqual(expected, dump_data) + + def testLoad(self): + s = StringIO.StringIO(self.incremental_uploader_dump) + + with mock.patch('urllib2.urlopen') as mock_open: + mock_open.return_value.headers = { + 'location': self.initialized_url + } + restored_uploader = googleads.adwords.IncrementalUploadHelper.Load( + s, client=self.client) + + self.assertEquals(restored_uploader._current_content_length, + self.incremental_uploader._current_content_length) + self.assertEquals(restored_uploader._is_last, + self.incremental_uploader._is_last) + self.assertEquals(restored_uploader._request_builder._version, + self.incremental_uploader._request_builder._version) + self.assertEquals(restored_uploader._upload_url, + self.incremental_uploader._upload_url) def testUploadOperations(self): with mock.patch('googleads.adwords.BatchJobHelper.' From 6bbc6f9c80dfa68b791b5bd65de5f75018e8b51c Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 5 Feb 2016 14:51:31 -0500 Subject: [PATCH 024/180] Commiting latest changes. From 65fe857f3f3ae33a8cb379c8ae3a48b2fd20d284 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 5 Feb 2016 16:03:15 -0500 Subject: [PATCH 025/180] Commiting latest changes. From 09c766b7cb8f273a12b533e7fb988c6b0d02f8e9 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 5 Feb 2016 16:26:20 -0500 Subject: [PATCH 026/180] Commiting latest changes. From 1eb173282d9c3f3957ebd680bb8d6fc72dcb4471 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 5 Feb 2016 16:33:05 -0500 Subject: [PATCH 027/180] Commiting latest changes. From c5d3f7cdbc1f9b61cc765047f14cac17431a15ae Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 5 Feb 2016 17:00:14 -0500 Subject: [PATCH 028/180] Commiting latest changes. From 7465430aaee72bc30341f095c109ff125d5131fa Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 23 Feb 2016 15:05:32 -0500 Subject: [PATCH 029/180] v201602 support for DFP --- ChangeLog | 20 +++ README.md | 9 -- ...ind_and_remove_criteria_from_shared_set.py | 33 +++-- ...ind_and_remove_criteria_from_shared_set.py | 33 +++-- ...ind_and_remove_criteria_from_shared_set.py | 33 +++-- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 2 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_a_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 2 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../get_content_by_category.py | 6 +- .../creative_service/__init__.py | 0 .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 8 +- .../create_native_creative.py | 135 +++++++++++++++++ .../creative_service/get_all_creatives.py | 2 +- .../get_creatives_by_statement.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_by_statement.py | 2 +- .../update_creative_set.py | 2 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_creative_templates_by_statement.py | 2 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 2 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 2 +- .../get_all_line_item_custom_fields.py | 2 +- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 2 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- .../get_custom_targeting_keys_by_statement.py | 2 +- ...et_custom_targeting_values_by_statement.py | 2 +- .../update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_by_currency_code.py | 2 +- .../update_exchange_rates.py | 2 +- .../get_availability_forecast.py | 15 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 6 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 3 +- .../get_ad_unit_hierarchy.py | 2 +- .../get_all_ad_unit_sizes.py | 2 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 4 +- .../inventory_service/update_ad_units.py | 2 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../label_service/get_all_labels.py | 2 +- .../label_service/get_labels_by_statement.py | 2 +- .../label_service/update_labels.py | 2 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 2 +- .../get_all_licas.py | 2 +- .../get_licas_by_statement.py | 2 +- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 2 +- .../line_item_service/create_line_items.py | 5 +- .../create_video_line_item.py | 5 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_by_statement.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 2 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 2 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_by_statement.py | 2 +- .../order_service/update_orders.py | 2 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../get_placements_by_statement.py | 2 +- .../placement_service/update_placements.py | 2 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_a_rate_card.py | 2 +- .../update_premium_rates.py | 2 +- .../product_service/__init__.py | 0 .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- .../product_service/update_products.py | 2 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 2 +- .../create_product_templates.py | 32 ++-- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 6 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 2 +- .../create_proposal_line_items.py | 7 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 2 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_proposals_by_statement.py | 2 +- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 2 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_geo_targets.py | 4 +- .../get_line_items_named_like.py | 2 +- .../rate_card_service/__init__.py | 0 .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_rate_cards_priced_with_currency.py | 2 +- .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 16 +- .../report_service/run_inventory_report.py | 4 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 4 +- .../report_service/run_sales_report.py | 2 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 2 +- .../get_suggested_ad_units_by_statement.py | 2 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 2 +- .../team_service/get_teams_by_statement.py | 2 +- .../team_service/update_teams.py | 2 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 2 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 2 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_users_by_statement.py | 2 +- .../user_service/update_users.py | 2 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 5 +- ...workflow_approval_requests_by_statement.py | 2 +- ...xternal_condition_requests_by_statement.py | 2 +- ...er_workflow_external_condition_requests.py | 2 +- googleads.yaml | 50 +++++-- googleads/adwords.py | 35 ++++- googleads/common.py | 53 +++++-- googleads/dfp.py | 21 +-- googleads/oauth2.py | 5 +- googleads/patches.py | 40 +++++ setup.py | 5 +- tests/adwords_test.py | 30 ++++ tests/common_test.py | 124 ++++++++++++---- tests/dfp_test.py | 3 +- tests/patches_test.py | 138 ++++++++++++++++++ 215 files changed, 876 insertions(+), 329 deletions(-) rename examples/dfp/{v201502 => v201602}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201502 => v201602}/activity_group_service/get_active_activity_groups.py (97%) rename examples/dfp/{v201502 => v201602}/activity_group_service/get_all_activity_groups.py (96%) rename examples/dfp/{v201502 => v201602}/activity_group_service/update_activity_groups.py (97%) rename examples/dfp/{v201502 => v201602}/activity_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/activity_service/create_activities.py (99%) rename examples/dfp/{v201502 => v201602}/activity_service/get_active_activities.py (99%) rename examples/dfp/{v201502 => v201602}/activity_service/get_all_activities.py (99%) rename examples/dfp/{v201502 => v201602}/activity_service/update_activities.py (99%) rename examples/dfp/{v201502 => v201602}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/audience_segment_service/create_audience_segments.py (98%) rename examples/dfp/{v201502 => v201602}/audience_segment_service/get_all_audience_segments.py (97%) rename examples/dfp/{v201502 => v201602}/audience_segment_service/get_first_party_audience_segments.py (97%) rename examples/dfp/{v201502 => v201602}/audience_segment_service/populate_first_party_audience_segments.py (97%) rename examples/dfp/{v201502 => v201602}/audience_segment_service/update_audience_segments.py (98%) rename examples/dfp/{v201502 => v201602}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201502 => v201602}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201502 => v201602}/base_rate_service/get_all_base_rates.py (99%) rename examples/dfp/{v201502 => v201602}/base_rate_service/get_base_rates_for_a_rate_card.py (99%) rename examples/dfp/{v201502 => v201602}/base_rate_service/update_base_rates.py (99%) rename examples/dfp/{v201502 => v201602}/company_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/company_service/create_companies.py (99%) rename examples/dfp/{v201502 => v201602}/company_service/get_advertisers.py (99%) rename examples/dfp/{v201502 => v201602}/company_service/get_all_companies.py (99%) rename examples/dfp/{v201502 => v201602}/company_service/update_companies.py (99%) rename examples/dfp/{v201502 => v201602}/contact_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201502 => v201602}/contact_service/get_all_contacts.py (99%) rename examples/dfp/{v201502 => v201602}/contact_service/get_uninvited_contacts.py (99%) rename examples/dfp/{v201502 => v201602}/contact_service/update_contacts.py (99%) rename examples/dfp/{v201502 => v201602}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201502 => v201602}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201502 => v201602}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201502 => v201602}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (98%) rename examples/dfp/{v201502 => v201602}/content_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/content_service/get_all_content.py (99%) rename examples/dfp/{v201502 => v201602}/content_service/get_content_by_category.py (98%) rename examples/dfp/{v201502 => v201602}/creative_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201502 => v201602}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201502 => v201602}/creative_service/create_custom_creative.py (94%) create mode 100755 examples/dfp/v201602/creative_service/create_native_creative.py rename examples/dfp/{v201502 => v201602}/creative_service/get_all_creatives.py (99%) rename examples/dfp/{v201502 => v201602}/creative_service/get_creatives_by_statement.py (99%) rename examples/dfp/{v201502 => v201602}/creative_service/update_creatives.py (99%) rename examples/dfp/{v201502 => v201602}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201502 => v201602}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201502 => v201602}/creative_set_service/get_all_creative_sets.py (96%) rename examples/dfp/{v201502 => v201602}/creative_set_service/get_creative_sets_by_statement.py (97%) rename examples/dfp/{v201502 => v201602}/creative_set_service/update_creative_set.py (97%) rename examples/dfp/{v201502 => v201602}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/creative_template_service/get_all_creative_templates.py (97%) rename examples/dfp/{v201502 => v201602}/creative_template_service/get_creative_templates_by_statement.py (97%) rename examples/dfp/{v201502 => v201602}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/dfp/{v201502 => v201602}/creative_wrapper_service/deactivate_creative_wrapper.py (97%) rename examples/dfp/{v201502 => v201602}/creative_wrapper_service/get_active_creative_wrappers.py (97%) rename examples/dfp/{v201502 => v201602}/creative_wrapper_service/get_all_creative_wrappers.py (96%) rename examples/dfp/{v201502 => v201602}/creative_wrapper_service/update_creative_wrappers.py (97%) rename examples/dfp/{v201502 => v201602}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201502 => v201602}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201502 => v201602}/custom_field_service/deactivate_all_line_item_custom_fields.py (98%) rename examples/dfp/{v201502 => v201602}/custom_field_service/get_all_custom_fields.py (97%) rename examples/dfp/{v201502 => v201602}/custom_field_service/get_all_line_item_custom_fields.py (97%) rename examples/dfp/{v201502 => v201602}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201502 => v201602}/custom_field_service/update_custom_fields.py (98%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/delete_custom_targeting_keys.py (98%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/delete_custom_targeting_values.py (98%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/get_custom_targeting_keys_by_statement.py (97%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/get_custom_targeting_values_by_statement.py (97%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/update_custom_targeting_keys.py (97%) rename examples/dfp/{v201502 => v201602}/custom_targeting_service/update_custom_targeting_values.py (97%) rename examples/dfp/{v201502 => v201602}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201502 => v201602}/exchange_rate_service/get_all_exchange_rates.py (96%) rename examples/dfp/{v201502 => v201602}/exchange_rate_service/get_exchange_rates_by_currency_code.py (97%) rename examples/dfp/{v201502 => v201602}/exchange_rate_service/update_exchange_rates.py (97%) rename examples/dfp/{v201502 => v201602}/forecast_service/get_availability_forecast.py (91%) rename examples/dfp/{v201502 => v201602}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/dfp/{v201502 => v201602}/forecast_service/get_delivery_forecast_for_line_items.py (94%) rename examples/dfp/{v201502 => v201602}/inventory_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/inventory_service/archive_ad_units.py (99%) rename examples/dfp/{v201502 => v201602}/inventory_service/create_ad_units.py (97%) rename examples/dfp/{v201502 => v201602}/inventory_service/get_ad_unit_hierarchy.py (99%) rename examples/dfp/{v201502 => v201602}/inventory_service/get_all_ad_unit_sizes.py (99%) rename examples/dfp/{v201502 => v201602}/inventory_service/get_all_ad_units.py (99%) rename examples/dfp/{v201502 => v201602}/inventory_service/get_top_level_ad_units.py (98%) rename examples/dfp/{v201502 => v201602}/inventory_service/update_ad_units.py (99%) rename examples/dfp/{v201502 => v201602}/label_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/label_service/create_labels.py (99%) rename examples/dfp/{v201502 => v201602}/label_service/deactivate_labels.py (99%) rename examples/dfp/{v201502 => v201602}/label_service/get_all_labels.py (99%) rename examples/dfp/{v201502 => v201602}/label_service/get_labels_by_statement.py (99%) rename examples/dfp/{v201502 => v201602}/label_service/update_labels.py (99%) rename examples/dfp/{v201502 => v201602}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201502 => v201602}/line_item_creative_association_service/deactivate_licas.py (97%) rename examples/dfp/{v201502 => v201602}/line_item_creative_association_service/get_all_licas.py (96%) rename examples/dfp/{v201502 => v201602}/line_item_creative_association_service/get_licas_by_statement.py (97%) rename examples/dfp/{v201502 => v201602}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201502 => v201602}/line_item_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/line_item_service/activate_line_items.py (99%) rename examples/dfp/{v201502 => v201602}/line_item_service/create_line_items.py (98%) rename examples/dfp/{v201502 => v201602}/line_item_service/create_video_line_item.py (98%) rename examples/dfp/{v201502 => v201602}/line_item_service/get_all_line_items.py (99%) rename examples/dfp/{v201502 => v201602}/line_item_service/get_line_items_by_statement.py (99%) rename examples/dfp/{v201502 => v201602}/line_item_service/get_recently_updated_line_items.py (99%) rename examples/dfp/{v201502 => v201602}/line_item_service/target_custom_criteria.py (99%) rename examples/dfp/{v201502 => v201602}/line_item_service/update_line_items.py (99%) rename examples/dfp/{v201502 => v201602}/network_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/network_service/get_all_networks.py (99%) rename examples/dfp/{v201502 => v201602}/network_service/get_current_network.py (99%) rename examples/dfp/{v201502 => v201602}/network_service/make_test_network.py (99%) rename examples/dfp/{v201502 => v201602}/order_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/order_service/approve_orders.py (99%) rename examples/dfp/{v201502 => v201602}/order_service/create_orders.py (99%) rename examples/dfp/{v201502 => v201602}/order_service/get_all_orders.py (99%) rename examples/dfp/{v201502 => v201602}/order_service/get_orders_by_statement.py (99%) rename examples/dfp/{v201502 => v201602}/order_service/update_orders.py (99%) rename examples/dfp/{v201502 => v201602}/placement_service/create_placements.py (99%) rename examples/dfp/{v201502 => v201602}/placement_service/deactivate_placements.py (99%) rename examples/dfp/{v201502 => v201602}/placement_service/get_all_placements.py (99%) rename examples/dfp/{v201502 => v201602}/placement_service/get_placements_by_statement.py (99%) rename examples/dfp/{v201502 => v201602}/placement_service/update_placements.py (99%) rename examples/dfp/{v201502 => v201602}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/premium_rate_service/create_premium_rates.py (97%) rename examples/dfp/{v201502 => v201602}/premium_rate_service/get_all_premium_rates.py (96%) rename examples/dfp/{v201502 => v201602}/premium_rate_service/get_premium_rates_for_a_rate_card.py (97%) rename examples/dfp/{v201502 => v201602}/premium_rate_service/update_premium_rates.py (97%) rename examples/dfp/{v201502 => v201602}/product_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/product_service/get_all_products.py (99%) rename examples/dfp/{v201502 => v201602}/product_service/get_products_for_product_template.py (99%) rename examples/dfp/{v201502 => v201602}/product_service/update_products.py (99%) rename examples/dfp/{v201502 => v201602}/product_template_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/product_template_service/activate_product_templates.py (97%) rename examples/dfp/{v201502 => v201602}/product_template_service/create_product_templates.py (82%) rename examples/dfp/{v201502 => v201602}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201502 => v201602}/product_template_service/get_sponsorship_product_templates.py (97%) rename examples/dfp/{v201502 => v201602}/product_template_service/update_product_templates.py (94%) rename examples/dfp/{v201502 => v201602}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/proposal_line_item_service/archive_proposal_line_items.py (98%) rename examples/dfp/{v201502 => v201602}/proposal_line_item_service/create_proposal_line_items.py (96%) rename examples/dfp/{v201502 => v201602}/proposal_line_item_service/get_all_proposal_line_items.py (97%) rename examples/dfp/{v201502 => v201602}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (98%) rename examples/dfp/{v201502 => v201602}/proposal_line_item_service/update_proposal_line_items.py (97%) rename examples/dfp/{v201502 => v201602}/proposal_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/proposal_service/create_proposals.py (99%) rename examples/dfp/{v201502 => v201602}/proposal_service/get_all_proposals.py (99%) rename examples/dfp/{v201502 => v201602}/proposal_service/get_proposals_by_statement.py (99%) rename examples/dfp/{v201502 => v201602}/proposal_service/submit_proposals_for_approval.py (99%) rename examples/dfp/{v201502 => v201602}/proposal_service/update_proposals.py (99%) rename examples/dfp/{v201502 => v201602}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/dfp/{v201502 => v201602}/publisher_query_language_service/get_geo_targets.py (94%) rename examples/dfp/{v201502 => v201602}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/dfp/{v201502 => v201602}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/rate_card_service/get_all_rate_cards.py (99%) rename examples/dfp/{v201502 => v201602}/rate_card_service/get_rate_cards_priced_with_currency.py (99%) rename examples/dfp/{v201502 => v201602}/report_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/report_service/run_delivery_report.py (81%) rename examples/dfp/{v201502 => v201602}/report_service/run_inventory_report.py (97%) rename examples/dfp/{v201502 => v201602}/report_service/run_reach_report.py (96%) rename examples/dfp/{v201502 => v201602}/report_service/run_report_with_custom_fields.py (97%) rename examples/dfp/{v201502 => v201602}/report_service/run_sales_report.py (96%) rename examples/dfp/{v201502 => v201602}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/dfp/{v201502 => v201602}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) rename examples/dfp/{v201502 => v201602}/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py (97%) rename examples/dfp/{v201502 => v201602}/team_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/team_service/create_teams.py (96%) rename examples/dfp/{v201502 => v201602}/team_service/get_all_teams.py (96%) rename examples/dfp/{v201502 => v201602}/team_service/get_teams_by_statement.py (96%) rename examples/dfp/{v201502 => v201602}/team_service/update_teams.py (97%) rename examples/dfp/{v201502 => v201602}/user_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/user_service/create_users.py (96%) rename examples/dfp/{v201502 => v201602}/user_service/deactivate_users.py (97%) rename examples/dfp/{v201502 => v201602}/user_service/get_all_roles.py (95%) rename examples/dfp/{v201502 => v201602}/user_service/get_all_users.py (95%) rename examples/dfp/{v201502 => v201602}/user_service/get_current_user.py (94%) rename examples/dfp/{v201502 => v201602}/user_service/get_users_by_statement.py (96%) rename examples/dfp/{v201502 => v201602}/user_service/update_users.py (96%) rename examples/dfp/{v201502 => v201602}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201502 => v201602}/user_team_association_service/delete_user_team_associations.py (98%) rename examples/dfp/{v201502 => v201602}/user_team_association_service/get_all_user_team_associations.py (97%) rename examples/dfp/{v201502 => v201602}/user_team_association_service/get_user_team_associations_for_user.py (97%) rename examples/dfp/{v201502 => v201602}/user_team_association_service/update_user_team_associations.py (98%) rename examples/dfp/{v201502 => v201602}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201502 => v201602}/workflow_request_service/approve_workflow_approval_requests.py (93%) rename examples/dfp/{v201502 => v201602}/workflow_request_service/get_workflow_approval_requests_by_statement.py (96%) rename examples/dfp/{v201502 => v201602}/workflow_request_service/get_workflow_external_condition_requests_by_statement.py (97%) rename examples/dfp/{v201502 => v201602}/workflow_request_service/trigger_workflow_external_condition_requests.py (98%) create mode 100644 googleads/patches.py create mode 100644 tests/patches_test.py diff --git a/ChangeLog b/ChangeLog index 93ccc008..29bed34a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,22 @@ +3.13.0 -- 2/23/2016 +* Added support for DFP v201602. +* Removed support for DFP v201411. +* Removed examples for DFP v201502. +* The library now applies a temporary patch to the suds-jurko dependency that + resolves multiple issues. This patch will be removed when the suds-jurko + library publicly exposes its 0.7 release. Thanks to GitHub user adiharush for + suggesting the patch! +* The LoadFromStorage function can now load credentials for either the + installed application or service account (.p12 files only) OAuth 2.0 flows. +* The googleads.yaml configuration file has been updated to reflect the changes + to the LoadFromStorage function. +* Resolved Issues: + Issue #58: https://github.com/googleads/googleads-python-lib/issues/58 + Issue #62: https://github.com/googleads/googleads-python-lib/issues/62 + Issue #63: https://github.com/googleads/googleads-python-lib/issues/63 + Issue #68: https://github.com/googleads/googleads-python-lib/issues/68 + Issue #78: https://github.com/googleads/googleads-python-lib/issues/78 + 3.12.0 -- 02/01/2016 * Removed DoubleClick Ad Exchange content. This API has been sunset. * Added support for AdWords v201601. @@ -11,6 +30,7 @@ * The AdWords BatchJobHelper and IncrementalUploadHelper utilities now initialize URLs for v201601 and up. * The AdWords IncrementalUploadHelper is now serializable. +>>>>>>> a4bf1f889e4cecee17f2e27a10d593452904cb8b 3.11.0 -- 11/24/2015 * Removed support for AdWords v201502. diff --git a/README.md b/README.md index 61c3a501..f52e919e 100644 --- a/README.md +++ b/README.md @@ -6,15 +6,6 @@ and DoubleClick for Publishers. The library provides easy ways to store your authentication and create SOAP web service clients. It also contains example code to help you get started integrating with our APIs. -####Important Note Regarding DFP -If you are using v201502 and newer in the DFP API, then performing actions on -objects will fail with an 'args NULL' error due to a bug in the underlying SOAP -client, more details here: https://github.com/googleads/googleads-python-lib/issues/58. - -While the fix has been accepted and merged into the source, you will need to download -the source files yourself and install them directly. The source can be located here: -https://bitbucket.org/jurko/suds/downloads - ##How do I get started? ####Installing the library Install or update the library from PyPI. If you're using pip, this is as easy diff --git a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py index 56f39737..b81812e4 100755 --- a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -106,7 +106,7 @@ def main(client, campaign_id): while page['totalNumEntries'] > offset: page = shared_criterion_service.get(selector) - if page['entries']: + if 'entries' in page: for shared_criterion in page['entries']: if shared_criterion['criterion']['type'] == 'KEYWORD': print ('Shared negative keyword with ID %d and text "%s" was' @@ -129,21 +129,22 @@ def main(client, campaign_id): selector['paging']['startIndex'] = offset # Finally, remove the criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) else: print 'No shared criteria were removed.' diff --git a/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py index 285c9881..d5f6179c 100755 --- a/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -106,7 +106,7 @@ def main(client, campaign_id): while page['totalNumEntries'] > offset: page = shared_criterion_service.get(selector) - if page['entries']: + if 'entries' in page: for shared_criterion in page['entries']: if shared_criterion['criterion']['type'] == 'KEYWORD': print ('Shared negative keyword with ID %d and text "%s" was' @@ -129,21 +129,22 @@ def main(client, campaign_id): selector['paging']['startIndex'] = offset # Finally, remove the criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) else: print 'No shared criteria were removed.' diff --git a/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py index 8961be5b..8e9373b8 100755 --- a/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -106,7 +106,7 @@ def main(client, campaign_id): while page['totalNumEntries'] > offset: page = shared_criterion_service.get(selector) - if page['entries']: + if 'entries' in page: for shared_criterion in page['entries']: if shared_criterion['criterion']['type'] == 'KEYWORD': print ('Shared negative keyword with ID %d and text "%s" was' @@ -129,21 +129,22 @@ def main(client, campaign_id): selector['paging']['startIndex'] = offset # Finally, remove the criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) else: print 'No shared criteria were removed.' diff --git a/examples/dfp/v201502/activity_group_service/__init__.py b/examples/dfp/v201602/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201502/activity_group_service/__init__.py rename to examples/dfp/v201602/activity_group_service/__init__.py diff --git a/examples/dfp/v201502/activity_group_service/create_activity_groups.py b/examples/dfp/v201602/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201502/activity_group_service/create_activity_groups.py rename to examples/dfp/v201602/activity_group_service/create_activity_groups.py index f49ea294..01b05c17 100755 --- a/examples/dfp/v201502/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201602/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201502') + version='v201602') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201602/activity_group_service/get_active_activity_groups.py similarity index 97% rename from examples/dfp/v201502/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201602/activity_group_service/get_active_activity_groups.py index ae22d2e1..dd3abcb4 100755 --- a/examples/dfp/v201502/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201602/activity_group_service/get_active_activity_groups.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201502') + version='v201602') # Create statement object to only select active activity groups. values = [{ diff --git a/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201602/activity_group_service/get_all_activity_groups.py similarity index 96% rename from examples/dfp/v201502/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201602/activity_group_service/get_all_activity_groups.py index b24019a9..9020c1ff 100755 --- a/examples/dfp/v201502/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201602/activity_group_service/get_all_activity_groups.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201502') + version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/activity_group_service/update_activity_groups.py b/examples/dfp/v201602/activity_group_service/update_activity_groups.py similarity index 97% rename from examples/dfp/v201502/activity_group_service/update_activity_groups.py rename to examples/dfp/v201602/activity_group_service/update_activity_groups.py index 9853c93a..b984cc00 100755 --- a/examples/dfp/v201502/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201602/activity_group_service/update_activity_groups.py @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201502') + version='v201602') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201502/activity_service/__init__.py b/examples/dfp/v201602/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201502/activity_service/__init__.py rename to examples/dfp/v201602/activity_service/__init__.py diff --git a/examples/dfp/v201502/activity_service/create_activities.py b/examples/dfp/v201602/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201502/activity_service/create_activities.py rename to examples/dfp/v201602/activity_service/create_activities.py index 74dcfcb3..1624f8b8 100755 --- a/examples/dfp/v201502/activity_service/create_activities.py +++ b/examples/dfp/v201602/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201502') + activity_service = client.GetService('ActivityService', version='v201602') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201502/activity_service/get_active_activities.py b/examples/dfp/v201602/activity_service/get_active_activities.py similarity index 99% rename from examples/dfp/v201502/activity_service/get_active_activities.py rename to examples/dfp/v201602/activity_service/get_active_activities.py index 16b2b0a8..c2ec75bf 100755 --- a/examples/dfp/v201502/activity_service/get_active_activities.py +++ b/examples/dfp/v201602/activity_service/get_active_activities.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201502') + activity_service = client.GetService('ActivityService', version='v201602') # Create statement object to only select active activities. values = [{ diff --git a/examples/dfp/v201502/activity_service/get_all_activities.py b/examples/dfp/v201602/activity_service/get_all_activities.py similarity index 99% rename from examples/dfp/v201502/activity_service/get_all_activities.py rename to examples/dfp/v201602/activity_service/get_all_activities.py index 2e1e37a7..7bf0281a 100755 --- a/examples/dfp/v201502/activity_service/get_all_activities.py +++ b/examples/dfp/v201602/activity_service/get_all_activities.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201502') + activity_service = client.GetService('ActivityService', version='v201602') # Create statement object to select only all activities. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/activity_service/update_activities.py b/examples/dfp/v201602/activity_service/update_activities.py similarity index 99% rename from examples/dfp/v201502/activity_service/update_activities.py rename to examples/dfp/v201602/activity_service/update_activities.py index 71afa07f..c7285189 100755 --- a/examples/dfp/v201502/activity_service/update_activities.py +++ b/examples/dfp/v201602/activity_service/update_activities.py @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201502') + activity_service = client.GetService('ActivityService', version='v201602') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201502/audience_segment_service/__init__.py b/examples/dfp/v201602/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201502/audience_segment_service/__init__.py rename to examples/dfp/v201602/audience_segment_service/__init__.py diff --git a/examples/dfp/v201502/audience_segment_service/create_audience_segments.py b/examples/dfp/v201602/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/dfp/v201502/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201602/audience_segment_service/create_audience_segments.py index 17c97a4f..235c6c67 100755 --- a/examples/dfp/v201502/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/create_audience_segments.py @@ -32,8 +32,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201502') - network_service = client.GetService('NetworkService', version='v201502') + 'AudienceSegmentService', version='v201602') + network_service = client.GetService('NetworkService', version='v201602') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py similarity index 97% rename from examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py index 758479ed..6ead437b 100755 --- a/examples/dfp/v201502/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201502') + 'AudienceSegmentService', version='v201602') # Create statement object to select all audience segments. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py similarity index 97% rename from examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py index f2450b93..42111d74 100755 --- a/examples/dfp/v201502/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201502') + 'AudienceSegmentService', version='v201602') # Create statement object to only select first party audience segments. values = [{ diff --git a/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py similarity index 97% rename from examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py index 4357cb3c..18a53e9e 100755 --- a/examples/dfp/v201502/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py @@ -33,7 +33,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201502') + 'AudienceSegmentService', version='v201602') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201502/audience_segment_service/update_audience_segments.py b/examples/dfp/v201602/audience_segment_service/update_audience_segments.py similarity index 98% rename from examples/dfp/v201502/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201602/audience_segment_service/update_audience_segments.py index e1381a79..84a74aa4 100755 --- a/examples/dfp/v201502/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/update_audience_segments.py @@ -32,7 +32,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201502') + 'AudienceSegmentService', version='v201602') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201502/base_rate_service/__init__.py b/examples/dfp/v201602/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201502/base_rate_service/__init__.py rename to examples/dfp/v201602/base_rate_service/__init__.py diff --git a/examples/dfp/v201502/base_rate_service/create_product_base_rates.py b/examples/dfp/v201602/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201502/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201602/base_rate_service/create_product_base_rates.py index 63bb3180..0c622718 100755 --- a/examples/dfp/v201502/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201602/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201502') + 'BaseRateService', version='v201602') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201602/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201602/base_rate_service/create_product_template_base_rates.py index 9ad21ef1..2dc3bfb3 100755 --- a/examples/dfp/v201502/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201602/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201502') + 'BaseRateService', version='v201602') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201502/base_rate_service/get_all_base_rates.py b/examples/dfp/v201602/base_rate_service/get_all_base_rates.py similarity index 99% rename from examples/dfp/v201502/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201602/base_rate_service/get_all_base_rates.py index 48d4aab9..1d0772d5 100755 --- a/examples/dfp/v201502/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201602/base_rate_service/get_all_base_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201502') + base_rate_service = client.GetService('BaseRateService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201602/base_rate_service/get_base_rates_for_a_rate_card.py similarity index 99% rename from examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py rename to examples/dfp/v201602/base_rate_service/get_base_rates_for_a_rate_card.py index db42f70e..6f73b7f0 100755 --- a/examples/dfp/v201502/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201602/base_rate_service/get_base_rates_for_a_rate_card.py @@ -31,7 +31,7 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201502') + base_rate_service = client.GetService('BaseRateService', version='v201602') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201502/base_rate_service/update_base_rates.py b/examples/dfp/v201602/base_rate_service/update_base_rates.py similarity index 99% rename from examples/dfp/v201502/base_rate_service/update_base_rates.py rename to examples/dfp/v201602/base_rate_service/update_base_rates.py index 5444f278..bdb18701 100755 --- a/examples/dfp/v201502/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201602/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201502') + base_rate_service = client.GetService('BaseRateService', version='v201602') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201502/company_service/__init__.py b/examples/dfp/v201602/company_service/__init__.py similarity index 100% rename from examples/dfp/v201502/company_service/__init__.py rename to examples/dfp/v201602/company_service/__init__.py diff --git a/examples/dfp/v201502/company_service/create_companies.py b/examples/dfp/v201602/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201502/company_service/create_companies.py rename to examples/dfp/v201602/company_service/create_companies.py index 4bfd25c3..3b7d1080 100755 --- a/examples/dfp/v201502/company_service/create_companies.py +++ b/examples/dfp/v201602/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201502') + company_service = client.GetService('CompanyService', version='v201602') # Create company objects. companies = [ diff --git a/examples/dfp/v201502/company_service/get_advertisers.py b/examples/dfp/v201602/company_service/get_advertisers.py similarity index 99% rename from examples/dfp/v201502/company_service/get_advertisers.py rename to examples/dfp/v201602/company_service/get_advertisers.py index ead587fc..cff77570 100755 --- a/examples/dfp/v201502/company_service/get_advertisers.py +++ b/examples/dfp/v201602/company_service/get_advertisers.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201502') + company_service = client.GetService('CompanyService', version='v201602') # Create statement object to only select companies that are advertisers. values = [{ diff --git a/examples/dfp/v201502/company_service/get_all_companies.py b/examples/dfp/v201602/company_service/get_all_companies.py similarity index 99% rename from examples/dfp/v201502/company_service/get_all_companies.py rename to examples/dfp/v201602/company_service/get_all_companies.py index fcf47ac6..ea3de273 100755 --- a/examples/dfp/v201502/company_service/get_all_companies.py +++ b/examples/dfp/v201602/company_service/get_all_companies.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201502') + company_service = client.GetService('CompanyService', version='v201602') # Create statement object to select all companies. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/company_service/update_companies.py b/examples/dfp/v201602/company_service/update_companies.py similarity index 99% rename from examples/dfp/v201502/company_service/update_companies.py rename to examples/dfp/v201602/company_service/update_companies.py index 1799b0f8..ed860582 100755 --- a/examples/dfp/v201502/company_service/update_companies.py +++ b/examples/dfp/v201602/company_service/update_companies.py @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201502') + company_service = client.GetService('CompanyService', version='v201602') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201502/contact_service/__init__.py b/examples/dfp/v201602/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201502/contact_service/__init__.py rename to examples/dfp/v201602/contact_service/__init__.py diff --git a/examples/dfp/v201502/contact_service/create_contacts.py b/examples/dfp/v201602/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201502/contact_service/create_contacts.py rename to examples/dfp/v201602/contact_service/create_contacts.py index 892ae9e5..11700297 100755 --- a/examples/dfp/v201502/contact_service/create_contacts.py +++ b/examples/dfp/v201602/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201502') + contact_service = client.GetService('ContactService', version='v201602') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201502/contact_service/get_all_contacts.py b/examples/dfp/v201602/contact_service/get_all_contacts.py similarity index 99% rename from examples/dfp/v201502/contact_service/get_all_contacts.py rename to examples/dfp/v201602/contact_service/get_all_contacts.py index 352849db..483a0cfc 100755 --- a/examples/dfp/v201502/contact_service/get_all_contacts.py +++ b/examples/dfp/v201602/contact_service/get_all_contacts.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201502') + contact_service = client.GetService('ContactService', version='v201602') # Create statement object to get all contacts. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/contact_service/get_uninvited_contacts.py b/examples/dfp/v201602/contact_service/get_uninvited_contacts.py similarity index 99% rename from examples/dfp/v201502/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201602/contact_service/get_uninvited_contacts.py index 887c1ef0..a2bcc4aa 100755 --- a/examples/dfp/v201502/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201602/contact_service/get_uninvited_contacts.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201502') + contact_service = client.GetService('ContactService', version='v201602') # Create statement object to only select contacts that are uninvited. values = [{ diff --git a/examples/dfp/v201502/contact_service/update_contacts.py b/examples/dfp/v201602/contact_service/update_contacts.py similarity index 99% rename from examples/dfp/v201502/contact_service/update_contacts.py rename to examples/dfp/v201602/contact_service/update_contacts.py index de3054bf..e4e543d6 100755 --- a/examples/dfp/v201502/contact_service/update_contacts.py +++ b/examples/dfp/v201602/contact_service/update_contacts.py @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201502') + contact_service = client.GetService('ContactService', version='v201602') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201602/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201502/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201602/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201602/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201602/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index d14fb793..482885f1 100755 --- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201602/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201502') + 'ContentMetadataKeyHierarchyService', version='v201602') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201602/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201602/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index b929bac6..f040e967 100755 --- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201602/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201502') + 'ContentMetadataKeyHierarchyService', version='v201602') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201602/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201602/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index aba4c9cd..3a782798 100755 --- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201602/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201502') + 'ContentMetadataKeyHierarchyService', version='v201602') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201602/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 98% rename from examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201602/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index ed70ad9e..399e7e6d 100755 --- a/examples/dfp/v201502/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201602/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201502') + 'ContentMetadataKeyHierarchyService', version='v201602') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201502/content_service/__init__.py b/examples/dfp/v201602/content_service/__init__.py similarity index 100% rename from examples/dfp/v201502/content_service/__init__.py rename to examples/dfp/v201602/content_service/__init__.py diff --git a/examples/dfp/v201502/content_service/get_all_content.py b/examples/dfp/v201602/content_service/get_all_content.py similarity index 99% rename from examples/dfp/v201502/content_service/get_all_content.py rename to examples/dfp/v201602/content_service/get_all_content.py index c22cf0bb..5fa483cd 100755 --- a/examples/dfp/v201502/content_service/get_all_content.py +++ b/examples/dfp/v201602/content_service/get_all_content.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201502') + content_service = client.GetService('ContentService', version='v201602') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/content_service/get_content_by_category.py b/examples/dfp/v201602/content_service/get_content_by_category.py similarity index 98% rename from examples/dfp/v201502/content_service/get_content_by_category.py rename to examples/dfp/v201602/content_service/get_content_by_category.py index d3792e1b..b563f85d 100755 --- a/examples/dfp/v201502/content_service/get_content_by_category.py +++ b/examples/dfp/v201602/content_service/get_content_by_category.py @@ -33,10 +33,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201502') - network_service = client.GetService('NetworkService', version='v201502') + content_service = client.GetService('ContentService', version='v201602') + network_service = client.GetService('NetworkService', version='v201602') custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') # Get the network's content browse custom targeting key. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201502/creative_service/__init__.py b/examples/dfp/v201602/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201502/creative_service/__init__.py rename to examples/dfp/v201602/creative_service/__init__.py diff --git a/examples/dfp/v201502/creative_service/create_creative_from_template.py b/examples/dfp/v201602/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201502/creative_service/create_creative_from_template.py rename to examples/dfp/v201602/creative_service/create_creative_from_template.py index f44b5b4c..8d53214c 100755 --- a/examples/dfp/v201502/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201602/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201502') + creative_service = client.GetService('CreativeService', version='v201602') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201502/creative_service/create_creatives.py b/examples/dfp/v201602/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201502/creative_service/create_creatives.py rename to examples/dfp/v201602/creative_service/create_creatives.py index 119301e7..fcef2d5a 100755 --- a/examples/dfp/v201502/creative_service/create_creatives.py +++ b/examples/dfp/v201602/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201502') + creative_service = client.GetService('CreativeService', version='v201602') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201502/creative_service/create_custom_creative.py b/examples/dfp/v201602/creative_service/create_custom_creative.py similarity index 94% rename from examples/dfp/v201502/creative_service/create_custom_creative.py rename to examples/dfp/v201602/creative_service/create_custom_creative.py index 03ae4550..f60bc215 100755 --- a/examples/dfp/v201502/creative_service/create_custom_creative.py +++ b/examples/dfp/v201602/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201502') + creative_service = client.GetService('CreativeService', version='v201602') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', @@ -64,8 +64,10 @@ def main(client, advertiser_id): { 'xsi_type': 'CustomCreativeAsset', 'macroName': 'IMAGE_ASSET', - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() + 'asset': { + 'assetByteArray': image_data, + 'fileName': 'image%s.jpg' % uuid.uuid4() + } } ], 'htmlSnippet': html_snippet diff --git a/examples/dfp/v201602/creative_service/create_native_creative.py b/examples/dfp/v201602/creative_service/create_native_creative.py new file mode 100755 index 00000000..6765e3d6 --- /dev/null +++ b/examples/dfp/v201602/creative_service/create_native_creative.py @@ -0,0 +1,135 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates a new native creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. + +The code in this example will use app data from the Google sample app +'Pie Noon': + +https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import urllib2 +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO' + 'PYnTdOQGaSpGSEZflIFs0iw=h300') +APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp' + 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300') + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201602') + + # Use the system defined native app install creative template. + creative_template_id = '10004400' + + image_data = urllib2.urlopen(ICON_URL).read() + image_data = base64.b64encode(image_data) + + app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() + app_icon_data = base64.b64encode(app_icon_data) + + # Create creative from templates. + creative = { + 'xsi_type': 'TemplateCreative', + 'name': 'Native Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '1', 'height': '1', 'isAspectRatio': False}, + 'creativeTemplateId': creative_template_id, + 'destinationUrl': ('https://play.google.com/store/apps/details?id=' + 'com.google.fpl.pie_noon'), + 'creativeTemplateVariableValues': [ + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Image', + 'asset': { + 'assetByteArray': image_data, + 'fileName': 'file%s.png' % uuid.uuid4() + } + }, + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Appicon', + 'asset': { + 'assetByteArray': app_icon_data, + 'fileName': 'appicon%s.png' % uuid.uuid4() + } + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Price', + 'value': 'Free' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Calltoaction', + 'value': 'Install' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Starrating', + 'value': '4' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Store', + 'value': 'Google Play' + }, + { + 'xsi_type': 'UrlCreativeTemplateVariableValue', + 'uniqueName': 'DeeplinkclickactionURL', + 'value': 'market://details?id=com.google.fpl.pie_noon' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Body', + 'value': 'Try multi-screen mode!' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Headline', + 'value': 'Pie Noon' + } + ] + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print ('Native creative with id \'%s\' and name \'%s\' was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], creative['previewUrl'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201502/creative_service/get_all_creatives.py b/examples/dfp/v201602/creative_service/get_all_creatives.py similarity index 99% rename from examples/dfp/v201502/creative_service/get_all_creatives.py rename to examples/dfp/v201602/creative_service/get_all_creatives.py index a6c3c252..b0cb054d 100755 --- a/examples/dfp/v201502/creative_service/get_all_creatives.py +++ b/examples/dfp/v201602/creative_service/get_all_creatives.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201502') + creative_service = client.GetService('CreativeService', version='v201602') # Create statement object to select all creatives. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/creative_service/get_creatives_by_statement.py b/examples/dfp/v201602/creative_service/get_creatives_by_statement.py similarity index 99% rename from examples/dfp/v201502/creative_service/get_creatives_by_statement.py rename to examples/dfp/v201602/creative_service/get_creatives_by_statement.py index 6cc1fc23..e0280e99 100755 --- a/examples/dfp/v201502/creative_service/get_creatives_by_statement.py +++ b/examples/dfp/v201602/creative_service/get_creatives_by_statement.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201502') + creative_service = client.GetService('CreativeService', version='v201602') # Create statement object to only select image creatives. values = [{ diff --git a/examples/dfp/v201502/creative_service/update_creatives.py b/examples/dfp/v201602/creative_service/update_creatives.py similarity index 99% rename from examples/dfp/v201502/creative_service/update_creatives.py rename to examples/dfp/v201602/creative_service/update_creatives.py index 7429fd38..7ef3da5a 100755 --- a/examples/dfp/v201502/creative_service/update_creatives.py +++ b/examples/dfp/v201602/creative_service/update_creatives.py @@ -34,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201502') + creative_service = client.GetService('CreativeService', version='v201602') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201502/creative_set_service/__init__.py b/examples/dfp/v201602/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201502/creative_set_service/__init__.py rename to examples/dfp/v201602/creative_set_service/__init__.py diff --git a/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201602/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201602/creative_set_service/associate_creative_set_to_line_item.py index 3b3d3bcb..e09dab08 100755 --- a/examples/dfp/v201502/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201602/creative_set_service/associate_creative_set_to_line_item.py @@ -38,7 +38,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201502') + 'LineItemCreativeAssociationService', version='v201602') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201502/creative_set_service/create_creative_set.py b/examples/dfp/v201602/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201502/creative_set_service/create_creative_set.py rename to examples/dfp/v201602/creative_set_service/create_creative_set.py index 106005d7..34df634f 100755 --- a/examples/dfp/v201502/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201602/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201502') + version='v201602') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201602/creative_set_service/get_all_creative_sets.py similarity index 96% rename from examples/dfp/v201502/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201602/creative_set_service/get_all_creative_sets.py index e6b6e42b..7cbb375e 100755 --- a/examples/dfp/v201502/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201602/creative_set_service/get_all_creative_sets.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201502') + version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201602/creative_set_service/get_creative_sets_by_statement.py similarity index 97% rename from examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py rename to examples/dfp/v201602/creative_set_service/get_creative_sets_by_statement.py index 285307b3..191d8039 100755 --- a/examples/dfp/v201502/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201602/creative_set_service/get_creative_sets_by_statement.py @@ -35,7 +35,7 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201502') + version='v201602') # Create statement object to only select creative sets that have the given # master creative. diff --git a/examples/dfp/v201502/creative_set_service/update_creative_set.py b/examples/dfp/v201602/creative_set_service/update_creative_set.py similarity index 97% rename from examples/dfp/v201502/creative_set_service/update_creative_set.py rename to examples/dfp/v201602/creative_set_service/update_creative_set.py index f9da7295..3997e534 100755 --- a/examples/dfp/v201502/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201602/creative_set_service/update_creative_set.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201502') + version='v201602') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201502/creative_template_service/__init__.py b/examples/dfp/v201602/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201502/creative_template_service/__init__.py rename to examples/dfp/v201602/creative_template_service/__init__.py diff --git a/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201602/creative_template_service/get_all_creative_templates.py similarity index 97% rename from examples/dfp/v201502/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201602/creative_template_service/get_all_creative_templates.py index 7fd2e471..30d4046b 100755 --- a/examples/dfp/v201502/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201602/creative_template_service/get_all_creative_templates.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201502') + 'CreativeTemplateService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201602/creative_template_service/get_creative_templates_by_statement.py similarity index 97% rename from examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py rename to examples/dfp/v201602/creative_template_service/get_creative_templates_by_statement.py index 05cc10be..b1a74adc 100755 --- a/examples/dfp/v201502/creative_template_service/get_creative_templates_by_statement.py +++ b/examples/dfp/v201602/creative_template_service/get_creative_templates_by_statement.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201502') + 'CreativeTemplateService', version='v201602') # Create statement object to only select system defined creative templates. values = [{ diff --git a/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201602/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201602/creative_wrapper_service/create_creative_wrappers.py index 61bc793f..1161dd79 100755 --- a/examples/dfp/v201502/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201602/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201502') + version='v201602') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201602/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 97% rename from examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201602/creative_wrapper_service/deactivate_creative_wrapper.py index ff051cca..f0c53925 100755 --- a/examples/dfp/v201502/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201602/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201502') + version='v201602') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201602/creative_wrapper_service/get_active_creative_wrappers.py similarity index 97% rename from examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201602/creative_wrapper_service/get_active_creative_wrappers.py index 72c98063..3dc66413 100755 --- a/examples/dfp/v201502/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201602/creative_wrapper_service/get_active_creative_wrappers.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201502') + version='v201602') # Create statement object to only select active creative wrappers. values = [{ diff --git a/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201602/creative_wrapper_service/get_all_creative_wrappers.py similarity index 96% rename from examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201602/creative_wrapper_service/get_all_creative_wrappers.py index cdd86677..e7126c80 100755 --- a/examples/dfp/v201502/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201602/creative_wrapper_service/get_all_creative_wrappers.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201502') + version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201602/creative_wrapper_service/update_creative_wrappers.py similarity index 97% rename from examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201602/creative_wrapper_service/update_creative_wrappers.py index 177ef746..c13b6b5b 100755 --- a/examples/dfp/v201502/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201602/creative_wrapper_service/update_creative_wrappers.py @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201502') + version='v201602') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201502/custom_field_service/__init__.py b/examples/dfp/v201602/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201502/custom_field_service/__init__.py rename to examples/dfp/v201602/custom_field_service/__init__.py diff --git a/examples/dfp/v201502/custom_field_service/create_custom_field_options.py b/examples/dfp/v201602/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201502/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201602/custom_field_service/create_custom_field_options.py index b084ff2e..2d8f7ec6 100755 --- a/examples/dfp/v201502/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201602/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201502') + 'CustomFieldService', version='v201602') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201502/custom_field_service/create_custom_fields.py b/examples/dfp/v201602/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201502/custom_field_service/create_custom_fields.py rename to examples/dfp/v201602/custom_field_service/create_custom_fields.py index d3aa0251..2f1bfa6b 100755 --- a/examples/dfp/v201502/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201602/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201502') + 'CustomFieldService', version='v201602') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201602/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 98% rename from examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201602/custom_field_service/deactivate_all_line_item_custom_fields.py index 46ee7896..d18d0828 100755 --- a/examples/dfp/v201502/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201602/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201502') + 'CustomFieldService', version='v201602') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201602/custom_field_service/get_all_custom_fields.py similarity index 97% rename from examples/dfp/v201502/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201602/custom_field_service/get_all_custom_fields.py index 0d305f70..6b8085e0 100755 --- a/examples/dfp/v201502/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201602/custom_field_service/get_all_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201502') + 'CustomFieldService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201602/custom_field_service/get_all_line_item_custom_fields.py similarity index 97% rename from examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py rename to examples/dfp/v201602/custom_field_service/get_all_line_item_custom_fields.py index 51e26215..436aaf0e 100755 --- a/examples/dfp/v201502/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201602/custom_field_service/get_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201502') + 'CustomFieldService', version='v201602') # Create statement to select only custom fields that apply to line items. values = [{ diff --git a/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201602/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201602/custom_field_service/set_line_item_custom_field_value.py index e6dae9d0..4f224371 100755 --- a/examples/dfp/v201502/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201602/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201502') + 'CustomFieldService', version='v201602') - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201502/custom_field_service/update_custom_fields.py b/examples/dfp/v201602/custom_field_service/update_custom_fields.py similarity index 98% rename from examples/dfp/v201502/custom_field_service/update_custom_fields.py rename to examples/dfp/v201602/custom_field_service/update_custom_fields.py index db401b1f..f2b52384 100755 --- a/examples/dfp/v201502/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201602/custom_field_service/update_custom_fields.py @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201502') + 'CustomFieldService', version='v201602') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201502/custom_targeting_service/__init__.py b/examples/dfp/v201602/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201502/custom_targeting_service/__init__.py rename to examples/dfp/v201602/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201602/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201602/custom_targeting_service/create_custom_targeting_keys_and_values.py index 8a7c5c1c..20e024dd 100755 --- a/examples/dfp/v201502/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201602/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_keys.py similarity index 98% rename from examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_keys.py index c5196526..356658af 100755 --- a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') values = [{ 'key': 'name', diff --git a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_values.py similarity index 98% rename from examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_values.py index f3aee029..8dc1099c 100755 --- a/examples/dfp/v201502/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_values.py @@ -37,7 +37,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201602/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201602/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 94cfa891..2700ddf9 100755 --- a/examples/dfp/v201502/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201602/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') # Create statement to get all targeting keys. targeting_key_statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_keys_by_statement.py similarity index 97% rename from examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py rename to examples/dfp/v201602/custom_targeting_service/get_custom_targeting_keys_by_statement.py index 0812eb42..28ff1cc7 100755 --- a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_keys_by_statement.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') values = [{ 'key': 'type', diff --git a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_values_by_statement.py similarity index 97% rename from examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py rename to examples/dfp/v201602/custom_targeting_service/get_custom_targeting_values_by_statement.py index af3bce4e..8c7e6ac3 100755 --- a/examples/dfp/v201502/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ b/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_values_by_statement.py @@ -31,7 +31,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201602/custom_targeting_service/update_custom_targeting_keys.py similarity index 97% rename from examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201602/custom_targeting_service/update_custom_targeting_keys.py index 365f935d..24fff377 100755 --- a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201602/custom_targeting_service/update_custom_targeting_keys.py @@ -29,7 +29,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201602/custom_targeting_service/update_custom_targeting_values.py similarity index 97% rename from examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201602/custom_targeting_service/update_custom_targeting_values.py index e4e37a72..88b1da87 100755 --- a/examples/dfp/v201502/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201602/custom_targeting_service/update_custom_targeting_values.py @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201502') + 'CustomTargetingService', version='v201602') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201502/exchange_rate_service/__init__.py b/examples/dfp/v201602/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201502/exchange_rate_service/__init__.py rename to examples/dfp/v201602/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201602/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201602/exchange_rate_service/create_exchange_rates.py index f8928d03..1edc93a2 100755 --- a/examples/dfp/v201502/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201602/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201502') + version='v201602') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201602/exchange_rate_service/get_all_exchange_rates.py similarity index 96% rename from examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201602/exchange_rate_service/get_all_exchange_rates.py index 6b311fdd..f3f50bec 100755 --- a/examples/dfp/v201502/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201602/exchange_rate_service/get_all_exchange_rates.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201502') + version='v201602') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201602/exchange_rate_service/get_exchange_rates_by_currency_code.py similarity index 97% rename from examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py rename to examples/dfp/v201602/exchange_rate_service/get_exchange_rates_by_currency_code.py index 3eb23cc6..475c3a9c 100755 --- a/examples/dfp/v201502/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201602/exchange_rate_service/get_exchange_rates_by_currency_code.py @@ -30,7 +30,7 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201502') + version='v201602') # Create a statement to get exchange rates for the specified currency code. values = [{ diff --git a/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201602/exchange_rate_service/update_exchange_rates.py similarity index 97% rename from examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201602/exchange_rate_service/update_exchange_rates.py index a4ef9b74..84d7d335 100755 --- a/examples/dfp/v201502/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201602/exchange_rate_service/update_exchange_rates.py @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201502') + version='v201602') # Create a statement to get an exchange rate by its ID. values = [{ diff --git a/examples/dfp/v201502/forecast_service/get_availability_forecast.py b/examples/dfp/v201602/forecast_service/get_availability_forecast.py similarity index 91% rename from examples/dfp/v201502/forecast_service/get_availability_forecast.py rename to examples/dfp/v201602/forecast_service/get_availability_forecast.py index a79d18a4..2f267c8d 100755 --- a/examples/dfp/v201502/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201602/forecast_service/get_availability_forecast.py @@ -29,11 +29,15 @@ # Import appropriate modules from the client library. from googleads import dfp +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -def main(client): + +def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201502') - network_service = client.GetService('NetworkService', version='v201502') + forecast_service = client.GetService('ForecastService', version='v201602') + network_service = client.GetService('NetworkService', version='v201602') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] @@ -93,7 +97,8 @@ def main(client): } prospective_line_item = { - 'lineItem': line_item + 'lineItem': line_item, + 'advertiserId': advertiser_id } # Set forecasting options. @@ -124,4 +129,4 @@ def main(client): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201602/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201602/forecast_service/get_availability_forecast_for_line_item.py index 98c0c8db..d167ee2c 100755 --- a/examples/dfp/v201502/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201602/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201502') + forecast_service = client.GetService('ForecastService', version='v201602') # Set forecasting options. forecast_options = { diff --git a/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201602/forecast_service/get_delivery_forecast_for_line_items.py similarity index 94% rename from examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201602/forecast_service/get_delivery_forecast_for_line_items.py index 9ddade58..955c6e74 100755 --- a/examples/dfp/v201502/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201602/forecast_service/get_delivery_forecast_for_line_items.py @@ -25,13 +25,13 @@ from googleads import dfp # Set the line items to get forecasts for. -LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_ID_1_HERE' -LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_ID_2_HERE' +LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' +LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE' def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201502') + forecast_service = client.GetService('ForecastService', version='v201602') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201502/inventory_service/__init__.py b/examples/dfp/v201602/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201502/inventory_service/__init__.py rename to examples/dfp/v201602/inventory_service/__init__.py diff --git a/examples/dfp/v201502/inventory_service/archive_ad_units.py b/examples/dfp/v201602/inventory_service/archive_ad_units.py similarity index 99% rename from examples/dfp/v201502/inventory_service/archive_ad_units.py rename to examples/dfp/v201602/inventory_service/archive_ad_units.py index 6a333d8c..c40b3052 100755 --- a/examples/dfp/v201502/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201602/inventory_service/archive_ad_units.py @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201502') + inventory_service = client.GetService('InventoryService', version='v201602') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201502/inventory_service/create_ad_units.py b/examples/dfp/v201602/inventory_service/create_ad_units.py similarity index 97% rename from examples/dfp/v201502/inventory_service/create_ad_units.py rename to examples/dfp/v201602/inventory_service/create_ad_units.py index f29dbd2a..ca2fc59b 100755 --- a/examples/dfp/v201502/inventory_service/create_ad_units.py +++ b/examples/dfp/v201602/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201502') + inventory_service = client.GetService('InventoryService', version='v201602') # Create ad unit size. ad_unit_size = { @@ -53,7 +53,6 @@ def main(client, parent_id): 'parentId': parent_id, 'description': 'Ad unit description.', 'targetWindow': 'BLANK', - 'targetPlatform': 'WEB', 'adUnitSizes': [ad_unit_size] } diff --git a/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201602/inventory_service/get_ad_unit_hierarchy.py similarity index 99% rename from examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py rename to examples/dfp/v201602/inventory_service/get_ad_unit_hierarchy.py index f797196e..1c617a58 100755 --- a/examples/dfp/v201502/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201602/inventory_service/get_ad_unit_hierarchy.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201502') + inventory_service = client.GetService('InventoryService', version='v201602') statement = dfp.FilterStatement() all_ad_units = [] diff --git a/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201602/inventory_service/get_all_ad_unit_sizes.py similarity index 99% rename from examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201602/inventory_service/get_all_ad_unit_sizes.py index 84283c22..324b52b5 100755 --- a/examples/dfp/v201502/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201602/inventory_service/get_all_ad_unit_sizes.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201502') + inventory_service = client.GetService('InventoryService', version='v201602') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201502/inventory_service/get_all_ad_units.py b/examples/dfp/v201602/inventory_service/get_all_ad_units.py similarity index 99% rename from examples/dfp/v201502/inventory_service/get_all_ad_units.py rename to examples/dfp/v201602/inventory_service/get_all_ad_units.py index d1063d32..1bd0f91f 100755 --- a/examples/dfp/v201502/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201602/inventory_service/get_all_ad_units.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201502') + inventory_service = client.GetService('InventoryService', version='v201602') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201602/inventory_service/get_top_level_ad_units.py similarity index 98% rename from examples/dfp/v201502/inventory_service/get_top_level_ad_units.py rename to examples/dfp/v201602/inventory_service/get_top_level_ad_units.py index def1bf83..e47de3ec 100755 --- a/examples/dfp/v201502/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201602/inventory_service/get_top_level_ad_units.py @@ -32,8 +32,8 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201502') - network_service = client.GetService('NetworkService', version='v201502') + inventory_service = client.GetService('InventoryService', version='v201602') + network_service = client.GetService('NetworkService', version='v201602') root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201502/inventory_service/update_ad_units.py b/examples/dfp/v201602/inventory_service/update_ad_units.py similarity index 99% rename from examples/dfp/v201502/inventory_service/update_ad_units.py rename to examples/dfp/v201602/inventory_service/update_ad_units.py index c0ee45ea..3d174a61 100755 --- a/examples/dfp/v201502/inventory_service/update_ad_units.py +++ b/examples/dfp/v201602/inventory_service/update_ad_units.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201502') + inventory_service = client.GetService('InventoryService', version='v201602') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201502/label_service/__init__.py b/examples/dfp/v201602/label_service/__init__.py similarity index 100% rename from examples/dfp/v201502/label_service/__init__.py rename to examples/dfp/v201602/label_service/__init__.py diff --git a/examples/dfp/v201502/label_service/create_labels.py b/examples/dfp/v201602/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201502/label_service/create_labels.py rename to examples/dfp/v201602/label_service/create_labels.py index 44a5a5c5..409d8f7d 100755 --- a/examples/dfp/v201502/label_service/create_labels.py +++ b/examples/dfp/v201602/label_service/create_labels.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201502') + label_service = client.GetService('LabelService', version='v201602') # Create label objects. labels = [] diff --git a/examples/dfp/v201502/label_service/deactivate_labels.py b/examples/dfp/v201602/label_service/deactivate_labels.py similarity index 99% rename from examples/dfp/v201502/label_service/deactivate_labels.py rename to examples/dfp/v201602/label_service/deactivate_labels.py index 0676f221..a31a2c8a 100755 --- a/examples/dfp/v201502/label_service/deactivate_labels.py +++ b/examples/dfp/v201602/label_service/deactivate_labels.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201502') + label_service = client.GetService('LabelService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/label_service/get_all_labels.py b/examples/dfp/v201602/label_service/get_all_labels.py similarity index 99% rename from examples/dfp/v201502/label_service/get_all_labels.py rename to examples/dfp/v201602/label_service/get_all_labels.py index 88f5af86..0d85b0e7 100755 --- a/examples/dfp/v201502/label_service/get_all_labels.py +++ b/examples/dfp/v201602/label_service/get_all_labels.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201502') + label_service = client.GetService('LabelService', version='v201602') # Create statement to get all labels statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/label_service/get_labels_by_statement.py b/examples/dfp/v201602/label_service/get_labels_by_statement.py similarity index 99% rename from examples/dfp/v201502/label_service/get_labels_by_statement.py rename to examples/dfp/v201602/label_service/get_labels_by_statement.py index d088c5c0..e9ab41c9 100755 --- a/examples/dfp/v201502/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201602/label_service/get_labels_by_statement.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201502') + label_service = client.GetService('LabelService', version='v201602') # Create statement to get all labels statement = dfp.FilterStatement('ORDER BY name') diff --git a/examples/dfp/v201502/label_service/update_labels.py b/examples/dfp/v201602/label_service/update_labels.py similarity index 99% rename from examples/dfp/v201502/label_service/update_labels.py rename to examples/dfp/v201602/label_service/update_labels.py index 43e64226..94ac6aa6 100755 --- a/examples/dfp/v201502/label_service/update_labels.py +++ b/examples/dfp/v201602/label_service/update_labels.py @@ -28,7 +28,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201502') + label_service = client.GetService('LabelService', version='v201602') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201502/line_item_creative_association_service/__init__.py b/examples/dfp/v201602/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201502/line_item_creative_association_service/__init__.py rename to examples/dfp/v201602/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201502/line_item_creative_association_service/create_licas.py b/examples/dfp/v201602/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201502/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201602/line_item_creative_association_service/create_licas.py index b195e2a2..c77ad32e 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201602/line_item_creative_association_service/create_licas.py @@ -31,7 +31,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201502') + 'LineItemCreativeAssociationService', version='v201602') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201602/line_item_creative_association_service/deactivate_licas.py similarity index 97% rename from examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201602/line_item_creative_association_service/deactivate_licas.py index bb53aa1e..bc7aacfc 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201602/line_item_creative_association_service/deactivate_licas.py @@ -29,7 +29,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201502') + 'LineItemCreativeAssociationService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201602/line_item_creative_association_service/get_all_licas.py similarity index 96% rename from examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201602/line_item_creative_association_service/get_all_licas.py index 190533cb..a00879f2 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201602/line_item_creative_association_service/get_all_licas.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201502') + 'LineItemCreativeAssociationService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201602/line_item_creative_association_service/get_licas_by_statement.py similarity index 97% rename from examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py rename to examples/dfp/v201602/line_item_creative_association_service/get_licas_by_statement.py index 615129f0..5ed9a3a3 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201602/line_item_creative_association_service/get_licas_by_statement.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201502') + 'LineItemCreativeAssociationService', version='v201602') # Create statement object to only select LICAs for the given line item id. values = [{ diff --git a/examples/dfp/v201502/line_item_creative_association_service/update_licas.py b/examples/dfp/v201602/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201502/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201602/line_item_creative_association_service/update_licas.py index 87437391..36996d82 100755 --- a/examples/dfp/v201502/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201602/line_item_creative_association_service/update_licas.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201502') + 'LineItemCreativeAssociationService', version='v201602') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/line_item_service/__init__.py b/examples/dfp/v201602/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201502/line_item_service/__init__.py rename to examples/dfp/v201602/line_item_service/__init__.py diff --git a/examples/dfp/v201502/line_item_service/activate_line_items.py b/examples/dfp/v201602/line_item_service/activate_line_items.py similarity index 99% rename from examples/dfp/v201502/line_item_service/activate_line_items.py rename to examples/dfp/v201602/line_item_service/activate_line_items.py index 1ddc961b..a5701efe 100755 --- a/examples/dfp/v201502/line_item_service/activate_line_items.py +++ b/examples/dfp/v201602/line_item_service/activate_line_items.py @@ -32,7 +32,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/line_item_service/create_line_items.py b/examples/dfp/v201602/line_item_service/create_line_items.py similarity index 98% rename from examples/dfp/v201502/line_item_service/create_line_items.py rename to examples/dfp/v201602/line_item_service/create_line_items.py index 56e84548..7737842a 100755 --- a/examples/dfp/v201502/line_item_service/create_line_items.py +++ b/examples/dfp/v201602/line_item_service/create_line_items.py @@ -35,7 +35,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Create line item objects. line_items = [] @@ -135,7 +135,8 @@ def main(client, order_id, targeted_placement_ids): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'costType': 'CPM', 'costPerUnit': { diff --git a/examples/dfp/v201502/line_item_service/create_video_line_item.py b/examples/dfp/v201602/line_item_service/create_video_line_item.py similarity index 98% rename from examples/dfp/v201502/line_item_service/create_video_line_item.py rename to examples/dfp/v201602/line_item_service/create_video_line_item.py index 0af61849..a58c808e 100755 --- a/examples/dfp/v201502/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201602/line_item_service/create_video_line_item.py @@ -45,7 +45,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Create line item object. line_item = { @@ -106,7 +106,8 @@ def main(client, order_id, targeted_video_ad_unit_id, }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'costType': 'CPM', 'costPerUnit': { diff --git a/examples/dfp/v201502/line_item_service/get_all_line_items.py b/examples/dfp/v201602/line_item_service/get_all_line_items.py similarity index 99% rename from examples/dfp/v201502/line_item_service/get_all_line_items.py rename to examples/dfp/v201602/line_item_service/get_all_line_items.py index 4607acc9..af079042 100755 --- a/examples/dfp/v201502/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201602/line_item_service/get_all_line_items.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201602/line_item_service/get_line_items_by_statement.py similarity index 99% rename from examples/dfp/v201502/line_item_service/get_line_items_by_statement.py rename to examples/dfp/v201602/line_item_service/get_line_items_by_statement.py index ce964e36..699480a9 100755 --- a/examples/dfp/v201502/line_item_service/get_line_items_by_statement.py +++ b/examples/dfp/v201602/line_item_service/get_line_items_by_statement.py @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Create statement object to only select line items that need creatives from a # given order. diff --git a/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201602/line_item_service/get_recently_updated_line_items.py similarity index 99% rename from examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201602/line_item_service/get_recently_updated_line_items.py index 59a2d9a2..2f8eb46d 100755 --- a/examples/dfp/v201502/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201602/line_item_service/get_recently_updated_line_items.py @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Create statement object to only select line items belonging to the order and # have been modified in the last 3 days. diff --git a/examples/dfp/v201502/line_item_service/target_custom_criteria.py b/examples/dfp/v201602/line_item_service/target_custom_criteria.py similarity index 99% rename from examples/dfp/v201502/line_item_service/target_custom_criteria.py rename to examples/dfp/v201602/line_item_service/target_custom_criteria.py index d835bcac..12ada4c1 100755 --- a/examples/dfp/v201502/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201602/line_item_service/target_custom_criteria.py @@ -39,7 +39,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201502/line_item_service/update_line_items.py b/examples/dfp/v201602/line_item_service/update_line_items.py similarity index 99% rename from examples/dfp/v201502/line_item_service/update_line_items.py rename to examples/dfp/v201602/line_item_service/update_line_items.py index fd864fd8..048db06c 100755 --- a/examples/dfp/v201502/line_item_service/update_line_items.py +++ b/examples/dfp/v201602/line_item_service/update_line_items.py @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201502/network_service/__init__.py b/examples/dfp/v201602/network_service/__init__.py similarity index 100% rename from examples/dfp/v201502/network_service/__init__.py rename to examples/dfp/v201602/network_service/__init__.py diff --git a/examples/dfp/v201502/network_service/get_all_networks.py b/examples/dfp/v201602/network_service/get_all_networks.py similarity index 99% rename from examples/dfp/v201502/network_service/get_all_networks.py rename to examples/dfp/v201602/network_service/get_all_networks.py index 4a8e9ad8..fe308836 100755 --- a/examples/dfp/v201502/network_service/get_all_networks.py +++ b/examples/dfp/v201602/network_service/get_all_networks.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201502') + network_service = client.GetService('NetworkService', version='v201602') # Get all networks that you have access to with the current login credentials. networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201502/network_service/get_current_network.py b/examples/dfp/v201602/network_service/get_current_network.py similarity index 99% rename from examples/dfp/v201502/network_service/get_current_network.py rename to examples/dfp/v201602/network_service/get_current_network.py index 98eb0d2c..6b589bc3 100755 --- a/examples/dfp/v201502/network_service/get_current_network.py +++ b/examples/dfp/v201602/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201502') + network_service = client.GetService('NetworkService', version='v201602') # Get the current network. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201502/network_service/make_test_network.py b/examples/dfp/v201602/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201502/network_service/make_test_network.py rename to examples/dfp/v201602/network_service/make_test_network.py index c5b32df2..64f5d706 100755 --- a/examples/dfp/v201502/network_service/make_test_network.py +++ b/examples/dfp/v201602/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201502') + network_service = client.GetService('NetworkService', version='v201602') # Create a test network. network = network_service.MakeTestNetwork() diff --git a/examples/dfp/v201502/order_service/__init__.py b/examples/dfp/v201602/order_service/__init__.py similarity index 100% rename from examples/dfp/v201502/order_service/__init__.py rename to examples/dfp/v201602/order_service/__init__.py diff --git a/examples/dfp/v201502/order_service/approve_orders.py b/examples/dfp/v201602/order_service/approve_orders.py similarity index 99% rename from examples/dfp/v201502/order_service/approve_orders.py rename to examples/dfp/v201602/order_service/approve_orders.py index a63631b8..aab76562 100755 --- a/examples/dfp/v201502/order_service/approve_orders.py +++ b/examples/dfp/v201602/order_service/approve_orders.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201502') + order_service = client.GetService('OrderService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/order_service/create_orders.py b/examples/dfp/v201602/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201502/order_service/create_orders.py rename to examples/dfp/v201602/order_service/create_orders.py index d20ba034..1edef159 100755 --- a/examples/dfp/v201502/order_service/create_orders.py +++ b/examples/dfp/v201602/order_service/create_orders.py @@ -31,7 +31,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201502') + order_service = client.GetService('OrderService', version='v201602') # Create order objects. orders = [] diff --git a/examples/dfp/v201502/order_service/get_all_orders.py b/examples/dfp/v201602/order_service/get_all_orders.py similarity index 99% rename from examples/dfp/v201502/order_service/get_all_orders.py rename to examples/dfp/v201602/order_service/get_all_orders.py index ee396ed7..8e74fd66 100755 --- a/examples/dfp/v201502/order_service/get_all_orders.py +++ b/examples/dfp/v201602/order_service/get_all_orders.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201502') + order_service = client.GetService('OrderService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/order_service/get_orders_by_statement.py b/examples/dfp/v201602/order_service/get_orders_by_statement.py similarity index 99% rename from examples/dfp/v201502/order_service/get_orders_by_statement.py rename to examples/dfp/v201602/order_service/get_orders_by_statement.py index 3952fcf1..0ae4e06c 100755 --- a/examples/dfp/v201502/order_service/get_orders_by_statement.py +++ b/examples/dfp/v201602/order_service/get_orders_by_statement.py @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201502') + order_service = client.GetService('OrderService', version='v201602') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201502/order_service/update_orders.py b/examples/dfp/v201602/order_service/update_orders.py similarity index 99% rename from examples/dfp/v201502/order_service/update_orders.py rename to examples/dfp/v201602/order_service/update_orders.py index 03b19a96..704d12ae 100755 --- a/examples/dfp/v201502/order_service/update_orders.py +++ b/examples/dfp/v201602/order_service/update_orders.py @@ -27,7 +27,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201502') + order_service = client.GetService('OrderService', version='v201602') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201502/placement_service/create_placements.py b/examples/dfp/v201602/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201502/placement_service/create_placements.py rename to examples/dfp/v201602/placement_service/create_placements.py index 3729afc7..fcadce84 100755 --- a/examples/dfp/v201502/placement_service/create_placements.py +++ b/examples/dfp/v201602/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201502') - inventory_service = client.GetService('InventoryService', version='v201502') + placement_service = client.GetService('PlacementService', version='v201602') + inventory_service = client.GetService('InventoryService', version='v201602') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201502/placement_service/deactivate_placements.py b/examples/dfp/v201602/placement_service/deactivate_placements.py similarity index 99% rename from examples/dfp/v201502/placement_service/deactivate_placements.py rename to examples/dfp/v201602/placement_service/deactivate_placements.py index a14c09a4..5a0724e8 100755 --- a/examples/dfp/v201502/placement_service/deactivate_placements.py +++ b/examples/dfp/v201602/placement_service/deactivate_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201502') + placement_service = client.GetService('PlacementService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/placement_service/get_all_placements.py b/examples/dfp/v201602/placement_service/get_all_placements.py similarity index 99% rename from examples/dfp/v201502/placement_service/get_all_placements.py rename to examples/dfp/v201602/placement_service/get_all_placements.py index a14e2959..c73d7557 100755 --- a/examples/dfp/v201502/placement_service/get_all_placements.py +++ b/examples/dfp/v201602/placement_service/get_all_placements.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201502') + placement_service = client.GetService('PlacementService', version='v201602') # Create statement to fetch all placements. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/placement_service/get_placements_by_statement.py b/examples/dfp/v201602/placement_service/get_placements_by_statement.py similarity index 99% rename from examples/dfp/v201502/placement_service/get_placements_by_statement.py rename to examples/dfp/v201602/placement_service/get_placements_by_statement.py index 44ce4967..c75be817 100755 --- a/examples/dfp/v201502/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201602/placement_service/get_placements_by_statement.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201502') + placement_service = client.GetService('PlacementService', version='v201602') # Create a statement to only select active placements. values = [{ diff --git a/examples/dfp/v201502/placement_service/update_placements.py b/examples/dfp/v201602/placement_service/update_placements.py similarity index 99% rename from examples/dfp/v201502/placement_service/update_placements.py rename to examples/dfp/v201602/placement_service/update_placements.py index ea5b13f4..1a9137c0 100755 --- a/examples/dfp/v201502/placement_service/update_placements.py +++ b/examples/dfp/v201602/placement_service/update_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201502') + placement_service = client.GetService('PlacementService', version='v201602') # Create query. values = [{ 'key': 'placementId', diff --git a/examples/dfp/v201502/premium_rate_service/__init__.py b/examples/dfp/v201602/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201502/premium_rate_service/__init__.py rename to examples/dfp/v201602/premium_rate_service/__init__.py diff --git a/examples/dfp/v201502/premium_rate_service/create_premium_rates.py b/examples/dfp/v201602/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/dfp/v201502/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201602/premium_rate_service/create_premium_rates.py index 22654560..14546531 100755 --- a/examples/dfp/v201502/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201602/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201502') + version='v201602') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201602/premium_rate_service/get_all_premium_rates.py similarity index 96% rename from examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201602/premium_rate_service/get_all_premium_rates.py index 1c530821..4d9c47e4 100755 --- a/examples/dfp/v201502/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201602/premium_rate_service/get_all_premium_rates.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201502') + version='v201602') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201602/premium_rate_service/get_premium_rates_for_a_rate_card.py similarity index 97% rename from examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py rename to examples/dfp/v201602/premium_rate_service/get_premium_rates_for_a_rate_card.py index 2caa45ed..4aa87593 100755 --- a/examples/dfp/v201502/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201602/premium_rate_service/get_premium_rates_for_a_rate_card.py @@ -30,7 +30,7 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201502') + version='v201602') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201502/premium_rate_service/update_premium_rates.py b/examples/dfp/v201602/premium_rate_service/update_premium_rates.py similarity index 97% rename from examples/dfp/v201502/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201602/premium_rate_service/update_premium_rates.py index c2c259a7..23201b03 100755 --- a/examples/dfp/v201502/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201602/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201502') + version='v201602') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201502/product_service/__init__.py b/examples/dfp/v201602/product_service/__init__.py similarity index 100% rename from examples/dfp/v201502/product_service/__init__.py rename to examples/dfp/v201602/product_service/__init__.py diff --git a/examples/dfp/v201502/product_service/get_all_products.py b/examples/dfp/v201602/product_service/get_all_products.py similarity index 99% rename from examples/dfp/v201502/product_service/get_all_products.py rename to examples/dfp/v201602/product_service/get_all_products.py index 20e976c8..ace3c916 100755 --- a/examples/dfp/v201502/product_service/get_all_products.py +++ b/examples/dfp/v201602/product_service/get_all_products.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201502') + product_service = client.GetService('ProductService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201502/product_service/get_products_for_product_template.py b/examples/dfp/v201602/product_service/get_products_for_product_template.py similarity index 99% rename from examples/dfp/v201502/product_service/get_products_for_product_template.py rename to examples/dfp/v201602/product_service/get_products_for_product_template.py index 87eb4e43..afe8f948 100755 --- a/examples/dfp/v201502/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201602/product_service/get_products_for_product_template.py @@ -27,7 +27,7 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201502') + product_service = client.GetService('ProductService', version='v201602') # Create a filter statement to select only products created from a single # a product template. diff --git a/examples/dfp/v201502/product_service/update_products.py b/examples/dfp/v201602/product_service/update_products.py similarity index 99% rename from examples/dfp/v201502/product_service/update_products.py rename to examples/dfp/v201602/product_service/update_products.py index fd099403..cb33200a 100755 --- a/examples/dfp/v201502/product_service/update_products.py +++ b/examples/dfp/v201602/product_service/update_products.py @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201502') + product_service = client.GetService('ProductService', version='v201602') # Create statement object to select a single product by an ID. values = [{ diff --git a/examples/dfp/v201502/product_template_service/__init__.py b/examples/dfp/v201602/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201502/product_template_service/__init__.py rename to examples/dfp/v201602/product_template_service/__init__.py diff --git a/examples/dfp/v201502/product_template_service/activate_product_templates.py b/examples/dfp/v201602/product_template_service/activate_product_templates.py similarity index 97% rename from examples/dfp/v201502/product_template_service/activate_product_templates.py rename to examples/dfp/v201602/product_template_service/activate_product_templates.py index 647ddb63..7b4e8a81 100755 --- a/examples/dfp/v201502/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201602/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201502') + 'ProductTemplateService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/product_template_service/create_product_templates.py b/examples/dfp/v201602/product_template_service/create_product_templates.py similarity index 82% rename from examples/dfp/v201502/product_template_service/create_product_templates.py rename to examples/dfp/v201602/product_template_service/create_product_templates.py index 163adf63..822b9d17 100755 --- a/examples/dfp/v201502/product_template_service/create_product_templates.py +++ b/examples/dfp/v201602/product_template_service/create_product_templates.py @@ -17,10 +17,8 @@ """This example creates a product template. To determine which product templates exist, run get_all_product_templates.py. - """ - import uuid # Import appropriate modules from the client library. @@ -30,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201502') + 'ProductTemplateService', version='v201602') network_service = client.GetService( - 'NetworkService', version='v201502') + 'NetworkService', version='v201602') # Create a product template. product_template = { @@ -45,6 +43,7 @@ def main(client): 'productType': 'DFP', 'rateType': 'CPM', 'roadblockingType': 'ONE_OR_MORE', + 'deliveryRateType': 'AS_FAST_AS_POSSIBLE', 'creativePlaceholders': [ { 'size': { @@ -60,17 +59,22 @@ def main(client): } ], 'lineItemType': 'STANDARD', - 'targeting': { - # Set browser targeting to Chrome. - 'browserTargeting': [ - { - 'browsers': [ - { - 'id': '500072' - } - ] + 'customizableAttributes': { + 'allowPlacementTargetingCustomization': True, + }, + 'builtInTargeting': { + 'technologyTargeting': { + # Set browser targeting to Chrome. + 'browserTargeting': { + { + 'browsers': [ + { + 'id': '500072' + } + ] + } } - ] + } }, 'productSegmentation': { 'geoSegment': { diff --git a/examples/dfp/v201502/product_template_service/get_all_product_templates.py b/examples/dfp/v201602/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201502/product_template_service/get_all_product_templates.py rename to examples/dfp/v201602/product_template_service/get_all_product_templates.py index cc71f5b6..1e27c0bc 100755 --- a/examples/dfp/v201502/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201602/product_template_service/get_all_product_templates.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201502') + 'ProductTemplateService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201602/product_template_service/get_sponsorship_product_templates.py similarity index 97% rename from examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201602/product_template_service/get_sponsorship_product_templates.py index 7fb30b78..9df978aa 100755 --- a/examples/dfp/v201502/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201602/product_template_service/get_sponsorship_product_templates.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201502') + 'ProductTemplateService', version='v201602') # Create a statement to select all sponsorship product templates. values = [{ diff --git a/examples/dfp/v201502/product_template_service/update_product_templates.py b/examples/dfp/v201602/product_template_service/update_product_templates.py similarity index 94% rename from examples/dfp/v201502/product_template_service/update_product_templates.py rename to examples/dfp/v201602/product_template_service/update_product_templates.py index eb3e42ec..32d4798a 100755 --- a/examples/dfp/v201502/product_template_service/update_product_templates.py +++ b/examples/dfp/v201602/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201502') + 'ProductTemplateService', version='v201602') # Create a statement to select a single product template by ID. values = [{ @@ -57,7 +57,7 @@ def main(client, product_template_id): } try: - targeting = product_template['targeting'] + targeting = product_template['builtInTargeting'] if 'geoTargeting' in targeting: geo_targeting = targeting['geoTargeting'] @@ -71,7 +71,7 @@ def main(client, product_template_id): 'targetedLocations': [location] } except KeyError: - product_template['targeting'] = { + product_template['builtInTargeting'] = { 'geoTargeting': { 'targetedLocations': [location] } diff --git a/examples/dfp/v201502/proposal_line_item_service/__init__.py b/examples/dfp/v201602/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201502/proposal_line_item_service/__init__.py rename to examples/dfp/v201602/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201602/proposal_line_item_service/archive_proposal_line_items.py similarity index 98% rename from examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201602/proposal_line_item_service/archive_proposal_line_items.py index 62ea64c5..d6d2a234 100755 --- a/examples/dfp/v201502/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201602/proposal_line_item_service/archive_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201502') + 'ProposalLineItemService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201602/proposal_line_item_service/create_proposal_line_items.py similarity index 96% rename from examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201602/proposal_line_item_service/create_proposal_line_items.py index 34bed36e..e07bea88 100755 --- a/examples/dfp/v201502/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201602/proposal_line_item_service/create_proposal_line_items.py @@ -41,8 +41,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201502') - network_service = client.GetService('NetworkService', version='v201502') + 'ProposalLineItemService', version='v201602') + network_service = client.GetService('NetworkService', version='v201602') # Get the root ad unit to target. root_ad_unit_id = ( @@ -79,7 +79,8 @@ def main(client, proposal_id, product_id, rate_card_id): }, 'hour': '0', 'minute': '0', - 'second': '0' + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' }, 'deliveryRateType': 'EVENLY', 'creativeRotationType': 'OPTIMIZED', diff --git a/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201602/proposal_line_item_service/get_all_proposal_line_items.py similarity index 97% rename from examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201602/proposal_line_item_service/get_all_proposal_line_items.py index 79d6a8a8..8280ee29 100755 --- a/examples/dfp/v201502/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201602/proposal_line_item_service/get_all_proposal_line_items.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201502') + 'ProposalLineItemService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201602/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 98% rename from examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201602/proposal_line_item_service/get_proposal_line_items_for_proposal.py index df8d3aa4..7ad00d5e 100755 --- a/examples/dfp/v201502/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201602/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -29,7 +29,7 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( 'ProposalLineItemService', - version='v201502') + version='v201602') # Create statement object to only select proposal line items belonging to a # given proposal. diff --git a/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201602/proposal_line_item_service/update_proposal_line_items.py similarity index 97% rename from examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201602/proposal_line_item_service/update_proposal_line_items.py index 48111594..0132dcb7 100755 --- a/examples/dfp/v201502/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201602/proposal_line_item_service/update_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201502') + 'ProposalLineItemService', version='v201602') # Create statement to select a proposal line item. values = [{ diff --git a/examples/dfp/v201502/proposal_service/__init__.py b/examples/dfp/v201602/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201502/proposal_service/__init__.py rename to examples/dfp/v201602/proposal_service/__init__.py diff --git a/examples/dfp/v201502/proposal_service/create_proposals.py b/examples/dfp/v201602/proposal_service/create_proposals.py similarity index 99% rename from examples/dfp/v201502/proposal_service/create_proposals.py rename to examples/dfp/v201602/proposal_service/create_proposals.py index a2bcfd9c..1ca82b97 100755 --- a/examples/dfp/v201502/proposal_service/create_proposals.py +++ b/examples/dfp/v201602/proposal_service/create_proposals.py @@ -33,8 +33,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201502') - network_service = client.GetService('NetworkService', version='v201502') + proposal_service = client.GetService('ProposalService', version='v201602') + network_service = client.GetService('NetworkService', version='v201602') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201502/proposal_service/get_all_proposals.py b/examples/dfp/v201602/proposal_service/get_all_proposals.py similarity index 99% rename from examples/dfp/v201502/proposal_service/get_all_proposals.py rename to examples/dfp/v201602/proposal_service/get_all_proposals.py index fb45be8c..d2f42f99 100755 --- a/examples/dfp/v201502/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201602/proposal_service/get_all_proposals.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201502') + proposal_service = client.GetService('ProposalService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201602/proposal_service/get_proposals_by_statement.py similarity index 99% rename from examples/dfp/v201502/proposal_service/get_proposals_by_statement.py rename to examples/dfp/v201602/proposal_service/get_proposals_by_statement.py index 27fc2466..54d3b437 100755 --- a/examples/dfp/v201502/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201602/proposal_service/get_proposals_by_statement.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201502') + proposal_service = client.GetService('ProposalService', version='v201602') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201602/proposal_service/submit_proposals_for_approval.py similarity index 99% rename from examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201602/proposal_service/submit_proposals_for_approval.py index 977101bb..93def5e8 100755 --- a/examples/dfp/v201502/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201602/proposal_service/submit_proposals_for_approval.py @@ -26,7 +26,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201502') + proposal_service = client.GetService('ProposalService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/proposal_service/update_proposals.py b/examples/dfp/v201602/proposal_service/update_proposals.py similarity index 99% rename from examples/dfp/v201502/proposal_service/update_proposals.py rename to examples/dfp/v201602/proposal_service/update_proposals.py index dc82ac2c..6ab3eb5f 100755 --- a/examples/dfp/v201502/proposal_service/update_proposals.py +++ b/examples/dfp/v201602/proposal_service/update_proposals.py @@ -27,7 +27,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201502') + proposal_service = client.GetService('ProposalService', version='v201602') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201502/publisher_query_language_service/__init__.py b/examples/dfp/v201602/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201502/publisher_query_language_service/__init__.py rename to examples/dfp/v201602/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201602/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201602/publisher_query_language_service/fetch_match_tables.py index e3d5c279..2406460b 100755 --- a/examples/dfp/v201502/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201602/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201502') + report_downloader = client.GetDataDownloader(version='v201602') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201602/publisher_query_language_service/get_geo_targets.py similarity index 94% rename from examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py rename to examples/dfp/v201602/publisher_query_language_service/get_geo_targets.py index 2501536c..f4b2131d 100755 --- a/examples/dfp/v201502/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201602/publisher_query_language_service/get_geo_targets.py @@ -20,7 +20,7 @@ 'Postal_Code', and 'DMA_Region' (i.e. Metro). A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201502/PublisherQueryLanguageService +https://developers.google.com/doubleclick-publishers/docs/reference/v201602/PublisherQueryLanguageService """ @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201502') + report_downloader = client.GetDataDownloader(version='v201602') output_file = tempfile.NamedTemporaryFile( prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201602/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py rename to examples/dfp/v201602/publisher_query_language_service/get_line_items_named_like.py index 86e5c23d..97e045a5 100755 --- a/examples/dfp/v201502/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201602/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201502') + report_downloader = client.GetDataDownloader(version='v201602') output_file = tempfile.NamedTemporaryFile( prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201502/rate_card_service/__init__.py b/examples/dfp/v201602/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201502/rate_card_service/__init__.py rename to examples/dfp/v201602/rate_card_service/__init__.py diff --git a/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201602/rate_card_service/get_all_rate_cards.py similarity index 99% rename from examples/dfp/v201502/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201602/rate_card_service/get_all_rate_cards.py index d0b16453..07c5df84 100755 --- a/examples/dfp/v201502/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201602/rate_card_service/get_all_rate_cards.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201502') + rate_card_service = client.GetService('RateCardService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201602/rate_card_service/get_rate_cards_priced_with_currency.py similarity index 99% rename from examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py rename to examples/dfp/v201602/rate_card_service/get_rate_cards_priced_with_currency.py index 26a680cb..860ebb5b 100755 --- a/examples/dfp/v201502/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201602/rate_card_service/get_rate_cards_priced_with_currency.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201502') + rate_card_service = client.GetService('RateCardService', version='v201602') # Create a statement to get all rate cards using USD as currency. values = [{ diff --git a/examples/dfp/v201502/report_service/__init__.py b/examples/dfp/v201602/report_service/__init__.py similarity index 100% rename from examples/dfp/v201502/report_service/__init__.py rename to examples/dfp/v201602/report_service/__init__.py diff --git a/examples/dfp/v201502/report_service/run_delivery_report.py b/examples/dfp/v201602/report_service/run_delivery_report.py similarity index 81% rename from examples/dfp/v201502/report_service/run_delivery_report.py rename to examples/dfp/v201602/report_service/run_delivery_report.py index 3bb28979..65f9e547 100755 --- a/examples/dfp/v201502/report_service/run_delivery_report.py +++ b/examples/dfp/v201602/report_service/run_delivery_report.py @@ -18,6 +18,8 @@ website with additional attributes and can filter to include just one order. """ +from datetime import datetime +from datetime import timedelta import tempfile # Import appropriate modules from the client library. @@ -39,6 +41,10 @@ def main(client, order_id): filter_statement = {'query': 'WHERE ORDER_ID = :id', 'values': values} + # Set the start and end dates of the report to run (past 8 days). + end_date = datetime.now() + start_date = end_date - timedelta(days=8) + # Create report job. report_job = { 'reportQuery': { @@ -49,12 +55,18 @@ def main(client, order_id): 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'LAST_MONTH' + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': {'year': start_date.year, + 'month': start_date.month, + 'day': start_date.day}, + 'endDate': {'year': end_date.year, + 'month': end_date.month, + 'day': end_date.day} } } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201502') + report_downloader = client.GetDataDownloader(version='v201602') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201502/report_service/run_inventory_report.py b/examples/dfp/v201602/report_service/run_inventory_report.py similarity index 97% rename from examples/dfp/v201502/report_service/run_inventory_report.py rename to examples/dfp/v201602/report_service/run_inventory_report.py index 89e0dfbc..f9c3b755 100755 --- a/examples/dfp/v201502/report_service/run_inventory_report.py +++ b/examples/dfp/v201602/report_service/run_inventory_report.py @@ -27,9 +27,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201502') + network_service = client.GetService('NetworkService', version='v201602') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201502') + report_downloader = client.GetDataDownloader(version='v201602') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201502/report_service/run_reach_report.py b/examples/dfp/v201602/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201502/report_service/run_reach_report.py rename to examples/dfp/v201602/report_service/run_reach_report.py index 4673960b..8a856d5e 100755 --- a/examples/dfp/v201502/report_service/run_reach_report.py +++ b/examples/dfp/v201602/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201502') + report_downloader = client.GetDataDownloader(version='v201602') # Create report job. report_job = { diff --git a/examples/dfp/v201502/report_service/run_report_with_custom_fields.py b/examples/dfp/v201602/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/dfp/v201502/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201602/report_service/run_report_with_custom_fields.py index d1a3519b..571963a6 100755 --- a/examples/dfp/v201502/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201602/report_service/run_report_with_custom_fields.py @@ -30,9 +30,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201502') + line_item_service = client.GetService('LineItemService', version='v201602') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201502') + report_downloader = client.GetDataDownloader(version='v201602') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201502/report_service/run_sales_report.py b/examples/dfp/v201602/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201502/report_service/run_sales_report.py rename to examples/dfp/v201602/report_service/run_sales_report.py index 7e3c7a60..733f2bd0 100755 --- a/examples/dfp/v201502/report_service/run_sales_report.py +++ b/examples/dfp/v201602/report_service/run_sales_report.py @@ -26,7 +26,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201502') + report_downloader = client.GetDataDownloader(version='v201602') # Create report job. report_job = { diff --git a/examples/dfp/v201502/suggested_ad_unit_service/__init__.py b/examples/dfp/v201602/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201502/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201602/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201602/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201602/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 527b6a57..422a62a1 100755 --- a/examples/dfp/v201502/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201602/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201502') + 'SuggestedAdUnitService', version='v201602') values = [{ 'key': 'numRequests', @@ -58,7 +58,7 @@ def main(client): # Approve suggested ad units. result = suggested_ad_unit_service.performSuggestedAdUnitAction( - {'xsi_type': 'ApproveSuggestedAdUnit'}, + {'xsi_type': 'ApproveSuggestedAdUnits'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: num_approved_suggested_ad_units += int(result['numChanges']) diff --git a/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201602/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201602/suggested_ad_unit_service/get_all_suggested_ad_units.py index 5c6c6630..31034d29 100755 --- a/examples/dfp/v201502/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201602/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201502') + 'SuggestedAdUnitService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201602/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py similarity index 97% rename from examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py rename to examples/dfp/v201602/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py index 09a77274..d4e0f631 100755 --- a/examples/dfp/v201502/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201602/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201502') + 'SuggestedAdUnitService', version='v201602') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201502/team_service/__init__.py b/examples/dfp/v201602/team_service/__init__.py similarity index 100% rename from examples/dfp/v201502/team_service/__init__.py rename to examples/dfp/v201602/team_service/__init__.py diff --git a/examples/dfp/v201502/team_service/create_teams.py b/examples/dfp/v201602/team_service/create_teams.py similarity index 96% rename from examples/dfp/v201502/team_service/create_teams.py rename to examples/dfp/v201602/team_service/create_teams.py index e8f4be8e..3d8caad1 100755 --- a/examples/dfp/v201502/team_service/create_teams.py +++ b/examples/dfp/v201602/team_service/create_teams.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201502') + team_service = client.GetService('TeamService', version='v201602') # Create team objects. teams = [] diff --git a/examples/dfp/v201502/team_service/get_all_teams.py b/examples/dfp/v201602/team_service/get_all_teams.py similarity index 96% rename from examples/dfp/v201502/team_service/get_all_teams.py rename to examples/dfp/v201602/team_service/get_all_teams.py index 89694fb9..e13035e4 100755 --- a/examples/dfp/v201502/team_service/get_all_teams.py +++ b/examples/dfp/v201602/team_service/get_all_teams.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201502') + team_service = client.GetService('TeamService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/team_service/get_teams_by_statement.py b/examples/dfp/v201602/team_service/get_teams_by_statement.py similarity index 96% rename from examples/dfp/v201502/team_service/get_teams_by_statement.py rename to examples/dfp/v201602/team_service/get_teams_by_statement.py index 495151bf..4b9c00fc 100755 --- a/examples/dfp/v201502/team_service/get_teams_by_statement.py +++ b/examples/dfp/v201602/team_service/get_teams_by_statement.py @@ -34,7 +34,7 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201502') + team_service = client.GetService('TeamService', version='v201602') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201502/team_service/update_teams.py b/examples/dfp/v201602/team_service/update_teams.py similarity index 97% rename from examples/dfp/v201502/team_service/update_teams.py rename to examples/dfp/v201602/team_service/update_teams.py index 15377e5b..f3e50b4f 100755 --- a/examples/dfp/v201502/team_service/update_teams.py +++ b/examples/dfp/v201602/team_service/update_teams.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201502') + team_service = client.GetService('TeamService', version='v201602') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201502/user_service/__init__.py b/examples/dfp/v201602/user_service/__init__.py similarity index 100% rename from examples/dfp/v201502/user_service/__init__.py rename to examples/dfp/v201602/user_service/__init__.py diff --git a/examples/dfp/v201502/user_service/create_users.py b/examples/dfp/v201602/user_service/create_users.py similarity index 96% rename from examples/dfp/v201502/user_service/create_users.py rename to examples/dfp/v201602/user_service/create_users.py index 7a51a267..5e37432f 100755 --- a/examples/dfp/v201502/user_service/create_users.py +++ b/examples/dfp/v201602/user_service/create_users.py @@ -28,7 +28,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201502') + user_service = client.GetService('UserService', version='v201602') # Create user objects. users = [ diff --git a/examples/dfp/v201502/user_service/deactivate_users.py b/examples/dfp/v201602/user_service/deactivate_users.py similarity index 97% rename from examples/dfp/v201502/user_service/deactivate_users.py rename to examples/dfp/v201602/user_service/deactivate_users.py index 6d009181..a3c0b94e 100755 --- a/examples/dfp/v201502/user_service/deactivate_users.py +++ b/examples/dfp/v201602/user_service/deactivate_users.py @@ -29,7 +29,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201502') + user_service = client.GetService('UserService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/user_service/get_all_roles.py b/examples/dfp/v201602/user_service/get_all_roles.py similarity index 95% rename from examples/dfp/v201502/user_service/get_all_roles.py rename to examples/dfp/v201602/user_service/get_all_roles.py index baed0111..54606aa5 100755 --- a/examples/dfp/v201502/user_service/get_all_roles.py +++ b/examples/dfp/v201602/user_service/get_all_roles.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201502') + user_service = client.GetService('UserService', version='v201602') # Get all roles. roles = user_service.getAllRoles() diff --git a/examples/dfp/v201502/user_service/get_all_users.py b/examples/dfp/v201602/user_service/get_all_users.py similarity index 95% rename from examples/dfp/v201502/user_service/get_all_users.py rename to examples/dfp/v201602/user_service/get_all_users.py index 107efd22..29f8f1d4 100755 --- a/examples/dfp/v201502/user_service/get_all_users.py +++ b/examples/dfp/v201602/user_service/get_all_users.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201502') + user_service = client.GetService('UserService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/user_service/get_current_user.py b/examples/dfp/v201602/user_service/get_current_user.py similarity index 94% rename from examples/dfp/v201502/user_service/get_current_user.py rename to examples/dfp/v201602/user_service/get_current_user.py index bec07a58..27426f56 100755 --- a/examples/dfp/v201502/user_service/get_current_user.py +++ b/examples/dfp/v201602/user_service/get_current_user.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201502') + user_service = client.GetService('UserService', version='v201602') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201502/user_service/get_users_by_statement.py b/examples/dfp/v201602/user_service/get_users_by_statement.py similarity index 96% rename from examples/dfp/v201502/user_service/get_users_by_statement.py rename to examples/dfp/v201602/user_service/get_users_by_statement.py index 176166f2..4b729bae 100755 --- a/examples/dfp/v201502/user_service/get_users_by_statement.py +++ b/examples/dfp/v201602/user_service/get_users_by_statement.py @@ -27,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201502') + user_service = client.GetService('UserService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/user_service/update_users.py b/examples/dfp/v201602/user_service/update_users.py similarity index 96% rename from examples/dfp/v201502/user_service/update_users.py rename to examples/dfp/v201602/user_service/update_users.py index 5fba527c..1a3f575f 100755 --- a/examples/dfp/v201502/user_service/update_users.py +++ b/examples/dfp/v201602/user_service/update_users.py @@ -27,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201502') + user_service = client.GetService('UserService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/user_team_association_service/__init__.py b/examples/dfp/v201602/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201502/user_team_association_service/__init__.py rename to examples/dfp/v201602/user_team_association_service/__init__.py diff --git a/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201602/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201502/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201602/user_team_association_service/create_user_team_associations.py index 95169a34..c9ee9903 100755 --- a/examples/dfp/v201502/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201602/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201502') + 'UserTeamAssociationService', version='v201602') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201602/user_team_association_service/delete_user_team_associations.py similarity index 98% rename from examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201602/user_team_association_service/delete_user_team_associations.py index 76ebfdd0..a2aed829 100755 --- a/examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201602/user_team_association_service/delete_user_team_associations.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201502') + 'UserTeamAssociationService', version='v201602') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201602/user_team_association_service/get_all_user_team_associations.py similarity index 97% rename from examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201602/user_team_association_service/get_all_user_team_associations.py index 2f07e7e3..cb7243fd 100755 --- a/examples/dfp/v201502/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201602/user_team_association_service/get_all_user_team_associations.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201502') + 'UserTeamAssociationService', version='v201602') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201602/user_team_association_service/get_user_team_associations_for_user.py similarity index 97% rename from examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201602/user_team_association_service/get_user_team_associations_for_user.py index a9a6e397..edc3ec0e 100755 --- a/examples/dfp/v201502/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201602/user_team_association_service/get_user_team_associations_for_user.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201502') + 'UserTeamAssociationService', version='v201602') # Create query. values = [{ diff --git a/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201602/user_team_association_service/update_user_team_associations.py similarity index 98% rename from examples/dfp/v201502/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201602/user_team_association_service/update_user_team_associations.py index 3101c2ee..73176735 100755 --- a/examples/dfp/v201502/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201602/user_team_association_service/update_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201502') + 'UserTeamAssociationService', version='v201602') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201502/workflow_request_service/__init__.py b/examples/dfp/v201602/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201502/workflow_request_service/__init__.py rename to examples/dfp/v201602/workflow_request_service/__init__.py diff --git a/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201602/workflow_request_service/approve_workflow_approval_requests.py similarity index 93% rename from examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201602/workflow_request_service/approve_workflow_approval_requests.py index 37b58706..89dbd1f2 100755 --- a/examples/dfp/v201502/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201602/workflow_request_service/approve_workflow_approval_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201502') + version='v201602') # Create query. values = [ @@ -75,7 +75,8 @@ def main(client, proposal_id): ' approved.' % workflow_approval_request['id']) # Perform action. result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'ApproveWorkflowApprovalRequests'}, + {'xsi_type': 'ApproveWorkflowApprovalRequests', + 'comment': 'This workflow has now been approved for submission.'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: workflow_approval_requests_approved += int(result['numChanges']) diff --git a/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201602/workflow_request_service/get_workflow_approval_requests_by_statement.py similarity index 96% rename from examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py rename to examples/dfp/v201602/workflow_request_service/get_workflow_approval_requests_by_statement.py index 50ba5376..fe8e7d13 100755 --- a/examples/dfp/v201502/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201602/workflow_request_service/get_workflow_approval_requests_by_statement.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201502') + version='v201602') # Create statement object to select all workflow approval requests. values = [{ diff --git a/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201602/workflow_request_service/get_workflow_external_condition_requests_by_statement.py similarity index 97% rename from examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py rename to examples/dfp/v201602/workflow_request_service/get_workflow_external_condition_requests_by_statement.py index d63103bf..24d85042 100755 --- a/examples/dfp/v201502/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201602/workflow_request_service/get_workflow_external_condition_requests_by_statement.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201502') + version='v201602') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201602/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 98% rename from examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201602/workflow_request_service/trigger_workflow_external_condition_requests.py index 4f2807c9..913335b6 100755 --- a/examples/dfp/v201502/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201602/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201502') + version='v201602') # Create query. values = [ diff --git a/googleads.yaml b/googleads.yaml index 7b9a34c9..9ff40109 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -1,26 +1,58 @@ +# AdWordsClient configurations adwords: + ############################################################################# + # Required Fields # + ############################################################################# developer_token: INSERT_DEVELOPER_TOKEN_HERE user_agent: INSERT_USER_AGENT_HERE + ############################################################################# + # Optional Fields # + ############################################################################# + # client_customer_id: INSERT_CLIENT_CUSTOMER_ID_HERE + # partial_failure: True + # validate_only: True + ############################################################################# + # OAuth 2.0 Configuration # + # Below you may provide credentials for either the installed application or # + # service account flows. Remove or comment the lines for the flow you're # + # not using. # + ############################################################################# + # The following values configure the client for the installed application + # flow. client_id: INSERT_OAUTH_2_CLIENT_ID_HERE client_secret: INSERT_CLIENT_SECRET_HERE refresh_token: INSERT_REFRESH_TOKEN_HERE -# The following values are optional: -# client_customer_id: INSERT_CLIENT_CUSTOMER_ID_HERE -# partial_failure: True -# validate_only: True + # The following values configure the client for the service account flow. + # service_account_email: INSERT_SERVICE_ACCOUNT_EMAIL_HERE + # path_to_private_key_file: INSERT_PATH_TO_FILE_HERE + +# DfpClient configurations dfp: + ############################################################################# + # Required Fields # + ############################################################################# application_name: INSERT_APPLICATION_NAME_HERE + # The following values are required for all services except NetworkService, + # unless the network code is set directly on the DfpClient object: + # network_code: INSERT_NETWORK_CODE_HERE + ############################################################################# + # OAuth 2.0 Configuration # + # Below you may provide credentials for either the installed application or # + # service account flows. Remove or comment the lines for the flow you're # + # not using. # + ############################################################################# + # The following values configure the client for the installed application + # flow. client_id: INSERT_OAUTH_2_CLIENT_ID_HERE client_secret: INSERT_CLIENT_SECRET_HERE refresh_token: INSERT_REFRESH_TOKEN_HERE -# The following values are required for all services except NetworkService, -# unless the network code is set directly on the DfpClient object: -# network_code: INSERT_NETWORK_CODE_HERE + # The following values configure the client for the service account flow. + # service_account_email: INSERT_SERVICE_ACCOUNT_EMAIL_HERE + # path_to_private_key_file: INSERT_PATH_TO_FILE_HERE -# The following values are optional: -# The following are optional settings for using a proxy. +# Proxy configurations (optional) # proxy_info: # host: INSERT_HOST_HERE # port: INSERT_PROXY_PORT_HERE diff --git a/googleads/adwords.py b/googleads/adwords.py index a61cf2a2..d6b25532 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -14,6 +14,7 @@ """Client library for the AdWords API.""" +from collections import namedtuple import io import os import re @@ -511,6 +512,29 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): _UPLOAD_SUFFIX = '' # Incremental uploads must have a content-length that is a multiple of this. _BATCH_JOB_INCREMENT = 262144 + # Generate a mapping of Operations to their service and methods. + _OPERATION_MAP = { + op[0]: namedtuple('Operation', ['operation_type', 'service', 'method']) + (op[0], op[1], op[2]) + for op in ( + ('AdGroupAdOperation', 'AdGroupAdService', 'mutate'), + ('AdGroupAdLabelOperation', 'AdGroupAdService', 'mutateLabel'), + ('AdGroupBidModifierOperation', 'AdGroupBidModifierService', + 'mutate'), + ('AdGroupCriterionOperation', 'AdGroupCriterionService', + 'mutate'), + ('AdGroupCriterionLabelOperation', 'AdGroupCriterionServce', + 'mutateLabel'), + ('AdGroupOperation', 'AdGroupService', 'mutate'), + ('AdGroupLabelOperation', 'AdGroupService', 'mutateLabel'), + ('BudgetOperation', 'BudgetService', 'mutate'), + ('CampaignCriterionOperation', 'CampaignCriterionService', + 'mutate'), + ('CampaignOperation', 'CampaignService', 'mutate'), + ('CampaignLabelOperation', 'CampaignService', 'mutateLabel'), + ('FeedItemOperation', 'FeedItemService', 'mutate') + ) + } def __init__(self, **kwargs): """Initializes a _SudsUploadRequestBuilder. @@ -702,10 +726,15 @@ def _GenerateRawRequestXML(self, operations): A str containing the raw XML of the request to the given service that would execute the given operations. """ - service_name = operations[0]['xsi_type'].replace('Operation', 'Service') - service = self._client.GetService(service_name, self._version) + try: + operation = self._OPERATION_MAP[operations[0]['xsi_type']] + except KeyError, e: + raise googleads.errors.GoogleAdsValueError('"%s" is an unsupported ' + 'operation.' % e.message) + service = self._client.GetService(operation.service, self._version) service.suds_client.set_options(nosend=True) - service_request = service.mutate(operations).envelope + service_request = (getattr(service, operation.method) + (operations).envelope) service.suds_client.set_options(nosend=False) return service_request diff --git a/googleads/common.py b/googleads/common.py index dae836af..faa929d7 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -26,8 +26,9 @@ import googleads.errors import googleads.oauth2 +import googleads.patches -VERSION = '3.12.0' +VERSION = '3.13.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], @@ -35,12 +36,17 @@ # The keys in the authentication dictionary that are used to construct OAuth 2.0 # credentials. -_OAUTH_2_AUTH_KEYS = ('client_id', 'client_secret', 'refresh_token') +_OAUTH2_INSTALLED_APP_KEYS = ('client_id', 'client_secret', 'refresh_token') +_OAUTH2_SERVICE_ACCT_KEYS = ('service_account_email', + 'path_to_private_key_file') # The keys in the proxy dictionary that are used to construct a ProxyInfo # instance. _PROXY_KEYS = ('host', 'port') +# Apply any necessary patches to dependency libraries. +googleads.patches.Apply() + def GenerateLibSig(short_name): """Generates a library signature suitable for a user agent field. @@ -83,13 +89,17 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, if not os.path.isabs(path): path = os.path.expanduser(path) try: - with open(path, 'r') as handle: + with open(path, 'rb') as handle: data = yaml.safe_load(handle.read()) - product_data = data.get(product_yaml_key) or {} + product_data = data[product_yaml_key] proxy_data = data.get(_PROXY_YAML_KEY) or {} except IOError: raise googleads.errors.GoogleAdsValueError( 'Given yaml file, %s, could not be opened.' % path) + except KeyError: + raise googleads.errors.GoogleAdsValueError( + 'Given yaml file, %s, does not contain a "%s" configuration.' + % (path, product_yaml_key)) original_keys = list(product_data.keys()) original_proxy_keys = list(proxy_data.keys()) @@ -121,19 +131,36 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, disable_ssl_certificate_validation = proxy_data.get( 'disable_ssl_certificate_validation', True) - try: + if all(config in product_data for config in _OAUTH2_INSTALLED_APP_KEYS): + # Use provided configurations for the installed application flow. client_kwargs['oauth2_client'] = ( googleads.oauth2.GoogleRefreshTokenClient( product_data['client_id'], product_data['client_secret'], - product_data['refresh_token'], proxy_info, - disable_ssl_certificate_validation, ca_certs)) - for auth_key in _OAUTH_2_AUTH_KEYS: - del product_data[auth_key] - except KeyError: + product_data['refresh_token'], proxy_info=proxy_info, + disable_ssl_certificate_validation=( + disable_ssl_certificate_validation), + ca_certs=ca_certs)) + for key in _OAUTH2_INSTALLED_APP_KEYS: + del product_data[key] + elif all(config in product_data for config in _OAUTH2_SERVICE_ACCT_KEYS): + # Use provided configurations for the service account flow. + client_kwargs['oauth2_client'] = ( + googleads.oauth2.GoogleServiceAccountClient( + googleads.oauth2.GetAPIScope(product_yaml_key), + product_data['service_account_email'], + product_data['path_to_private_key_file'], proxy_info=proxy_info, + disable_ssl_certificate_validation=( + disable_ssl_certificate_validation), + ca_certs=ca_certs)) + for key in _OAUTH2_SERVICE_ACCT_KEYS: + del product_data[key] + else: raise googleads.errors.GoogleAdsValueError( - 'Your yaml file, %s, is missing some of the required OAuth 2.0 ' - 'values. Required values are: %s, actual values are %s' - % (path, _OAUTH_2_AUTH_KEYS, original_keys)) + 'Your yaml file, %s, is incorrectly configured for OAuth 2.0. You ' + 'need to specify credentials for either the installed application ' + 'flow (%s) or service account flow (%s). Actual values provided are: ' + '%s' % (path, _OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS, + original_keys)) for value in optional_product_values: if value in product_data: diff --git a/googleads/dfp.py b/googleads/dfp.py index 2553d153..17256a13 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -39,7 +39,7 @@ _CHUNK_SIZE = 16 * 1024 # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201411': + 'v201502': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -50,14 +50,16 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PlacementService', 'PremiumRateService', - 'ProductService', 'ProductTemplateService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201502': + 'v201505': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -77,7 +79,7 @@ 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201505': + 'v201508': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -94,10 +96,11 @@ 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', + 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201508': + 'v201511': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -118,7 +121,7 @@ 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201511': + 'v201602': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -136,7 +139,7 @@ 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', + 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), } diff --git a/googleads/oauth2.py b/googleads/oauth2.py index 6bd6b11d..7f1aa85f 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -210,8 +210,9 @@ def __init__(self, scope, client_email, key_file, ' does not exist.' % key_file) self.oauth2credentials = oauth2client.client.SignedJwtAssertionCredentials( - client_email, private_key, scope, private_key_password, - self._USER_AGENT, sub=sub) + client_email, private_key, scope, + private_key_password=private_key_password, + user_agent=self._USER_AGENT, sub=sub) self.proxy_info = proxy_info self.disable_ssl_certificate_validation = disable_ssl_certificate_validation self.ca_certs = ca_certs diff --git a/googleads/patches.py b/googleads/patches.py new file mode 100644 index 00000000..eb512f18 --- /dev/null +++ b/googleads/patches.py @@ -0,0 +1,40 @@ +# Copyright 2016 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. + +"""Patches applied by the Google Ads Client Library.""" + +import suds + + +def Apply(): + """Apply patches used by the Google Ads Client Library.""" + _ApplySudsJurkoAppenderPatch() + + +def _ApplySudsJurkoAppenderPatch(): + """Appends a Monkey Patch to the suds.mx.appender module. + + This resolves an issue where empty objects are ignored and stripped from the + request output. More details can be found on the suds-jurko issue tracker: + https://bitbucket.org/jurko/suds/issues/81/suds-should-support-an-empty-object + """ + def PatchedAppend(self, parent, content): + obj = content.value + child = self.node(content) + parent.append(child) + for item in obj: + cont = suds.mx.Content(tag=item[0], value=item[1]) + suds.mx.appender.Appender.append(self, child, cont) + + suds.mx.appender.ObjectAppender.append = PatchedAppend diff --git a/setup.py b/setup.py index c738ecc8..bf7ebca7 100755 --- a/setup.py +++ b/setup.py @@ -24,8 +24,9 @@ PACKAGES = ['googleads'] -DEPENDENCIES = ['httplib2', 'oauth2client', 'suds-jurko', 'pysocks', 'pytz', - 'PyYAML', 'xmltodict'] +DEPENDENCIES = ['httplib2>=0.9.2', 'oauth2client>=1.5.2,<2.0.0', + 'suds-jurko>=0.6', 'pysocks>=1.5.6', 'pytz>=2015.7', + 'PyYAML>=3.11', 'xmltodict>=0.9.2'] CLASSIFIERS = [ 'Intended Audience :: Developers', diff --git a/tests/adwords_test.py b/tests/adwords_test.py index f1a9fb01..4d353604 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -548,6 +548,36 @@ def testGenerateOperationsXMLWithNoOperations(self): operations) self.assertTrue(raw_xml is '') + def testGenerateRawRequestXMLFromBogusOperation(self): + """Tests whether an invalid operation raises an Exception.""" + bogus_operations = [{ + 'operator': 'ADD', + 'xsi_type': 'BogusOperation', + 'operand': { + 'bogusProperty': 'bogusValue'} + }] + + self.assertRaises(googleads.errors.GoogleAdsValueError, + self.request_builder._GenerateRawRequestXML, + bogus_operations) + + def testGenerateRawRequestXMLFromCampaignLabelOperation(self): + """Tests whether raw request xml can be produced from a label operation.""" + ops = [{ + 'operator': 'ADD', + 'xsi_type': 'CampaignLabelOperation', + 'operand': {'campaignId': 0, 'labelId': 0} + }] + + root = ElementTree.fromstring( + self.request_builder._GenerateRawRequestXML(ops)) + self.assertTrue(len(root) == 2) + body = root.find('{%s}Body' % self.ENVELOPE_NS) + self.assertTrue(len(body) == 1) + mutate_label = body.find('{%s}mutateLabel' + % self.request_builder._adwords_endpoint) + self.assertTrue(len(mutate_label) == len(ops)) + def testGenerateRawRequestXMLFromSingleOperation(self): """Tests whether raw request xml can be produced from a single operation.""" operations_amount = 1 diff --git a/tests/common_test.py b/tests/common_test.py index e3d9482f..5f4d470d 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -27,13 +27,17 @@ import googleads.common import googleads.errors +import googleads.oauth2 class CommonTest(unittest.TestCase): """Tests for the googleads.common module.""" - # A dictionary with all the required OAuth 2.0 keys - _OAUTH_DICT = {'client_id': 'a', 'client_secret': 'b', 'refresh_token': 'c'} + # Dictionaries with all the required OAuth 2.0 keys + _OAUTH_INSTALLED_APP_DICT = {'client_id': 'a', 'client_secret': 'b', + 'refresh_token': 'c'} + _OAUTH_SERVICE_ACCT_DICT = {'service_account_email': 'test@test.com', + 'path_to_private_key_file': '/test/test.p12'} def setUp(self): self.filesystem = fake_filesystem.FakeFilesystem() @@ -44,14 +48,14 @@ def setUp(self): self.fake_proxy.return_value.proxy_host = 'ahost' self.fake_proxy.return_value.proxy_port = 'aport' - def _CreateYamlFile(self, data, insert_oauth2_key=None): + def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): """Return the filename of a yaml file created for testing.""" yaml_file = self.tempfile.NamedTemporaryFile(delete=False) with self.fake_open(yaml_file.name, 'w') as yaml_handle: for key in data: if key is insert_oauth2_key: - data[key].update(self._OAUTH_DICT) + data[key].update(oauth_dict) yaml_handle.write(yaml.dump({key: data[key]})) return yaml_file.name @@ -71,12 +75,32 @@ def testLoadFromStorage_missingOAuthKey(self): googleads.common.LoadFromStorage, yaml_fname, 'woo', [], []) + def testLoadFromStorage_missingPartialInstalledAppOAuthCredential(self): + yaml_fname = self._CreateYamlFile({'woo': {}}, 'woo', {'client_id': 'abc'}) + with mock.patch('googleads.common.open', self.fake_open, create=True): + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromStorage, + yaml_fname, 'woo', [], []) + + def testLoadFromStorage_missingPartialServiceAcctOAuthCredential(self): + yaml_fname = self._CreateYamlFile({'woo': {}}, 'woo', { + 'service_account_email': 'abc@xyz.com'}) + with mock.patch('googleads.common.open', self.fake_open, create=True): + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromStorage, + yaml_fname, 'woo', [], []) + def testLoadFromStorage_passesWithNoRequiredKeys(self): - yaml_fname = self._CreateYamlFile({'woo': {}}, 'woo') + yaml_fname = self._CreateYamlFile({'woo': {}}, 'woo', + self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): rval = googleads.common.LoadFromStorage(yaml_fname, 'woo', [], []) - mock_client.assert_called_once_with('a', 'b', 'c', None, True, None) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_info=None, ca_certs=None, + disable_ssl_certificate_validation=True) self.assertEqual({'oauth2_client': mock_client.return_value, 'https_proxy': None}, rval) @@ -85,21 +109,22 @@ def testLoadFromStorage_passesWithProxy(self): 'proxy_info': { 'host': 'ahost', 'port': 'aport' - }}, 'adwords') + }}, 'adwords', + self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('httplib2.ProxyInfo', self.fake_proxy): rval = googleads.common.LoadFromStorage(yaml_fname, 'adwords', [], []) - mock_client.assert_called_once_with('a', 'b', 'c', - self.fake_proxy.return_value, - True, None) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_info=self.fake_proxy.return_value, + ca_certs=None, disable_ssl_certificate_validation=True) self.assertEqual({'oauth2_client': mock_client.return_value, 'https_proxy': 'ahost:aport'}, rval) def testLoadFromStorage_failsWithMisconfiguredProxy(self): yaml_fname = self._CreateYamlFile({'adwords': {}, 'proxy_info': {'host': 'ahost'}}, - 'adwords') + 'adwords', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient'): with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('httplib2.ProxyInfo', self.fake_proxy): @@ -110,14 +135,16 @@ def testLoadFromStorage_failsWithMisconfiguredProxy(self): def testLoadFromStorage_missingRequiredKey(self): with mock.patch('googleads.common.open', self.fake_open, create=True): # Both keys are missing. - yaml_fname = self._CreateYamlFile({'two': {}}, 'two') + yaml_fname = self._CreateYamlFile({'two': {}}, 'two', + self._OAUTH_INSTALLED_APP_DICT) self.assertRaises( googleads.errors.GoogleAdsValueError, googleads.common.LoadFromStorage, yaml_fname, 'two', ['needed', 'keys'], []) # One key is missing. - yaml_fname = self._CreateYamlFile({'three': {'needed': 'd'}}, 'three') + yaml_fname = self._CreateYamlFile({'three': {'needed': 'd'}}, 'three', + self._OAUTH_INSTALLED_APP_DICT) self.assertRaises( googleads.errors.GoogleAdsValueError, googleads.common.LoadFromStorage, @@ -126,24 +153,29 @@ def testLoadFromStorage_missingRequiredKey(self): def testLoadFromStorage(self): # No optional keys present. yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e'}}, - 'one') + 'one', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): rval = googleads.common.LoadFromStorage( yaml_fname, 'one', ['needed', 'keys'], ['other']) - mock_client.assert_called_once_with('a', 'b', 'c', None, True, None) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_info=None, ca_certs=None, + disable_ssl_certificate_validation=True) self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'https_proxy': None}, rval) # The optional key is present. yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e', - 'other': 'f'}}, 'one') + 'other': 'f'}}, 'one', + self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): rval = googleads.common.LoadFromStorage( yaml_fname, 'one', ['needed', 'keys'], ['other']) - mock_client.assert_called_once_with('a', 'b', 'c', None, True, None) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_info=None, ca_certs=None, + disable_ssl_certificate_validation=True) self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'other': 'f', 'https_proxy': None}, rval) @@ -151,7 +183,7 @@ def testLoadFromStorage(self): def testLoadFromStorage_relativePath(self): fake_os = fake_filesystem.FakeOsModule(self.filesystem) yaml_contents = {'one': {'needed': 'd', 'keys': 'e'}} - yaml_contents['one'].update(self._OAUTH_DICT) + yaml_contents['one'].update(self._OAUTH_INSTALLED_APP_DICT) self.filesystem.CreateFile('/home/test/yaml/googleads.yaml', contents=yaml.dump(yaml_contents)) fake_os.chdir('/home/test') @@ -161,23 +193,61 @@ def testLoadFromStorage_relativePath(self): with mock.patch('googleads.common.open', self.fake_open, create=True): rval = googleads.common.LoadFromStorage( 'yaml/googleads.yaml', 'one', ['needed', 'keys'], ['other']) - mock_client.assert_called_once_with('a', 'b', 'c', None, True, None) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'needed': 'd', 'keys': 'e', - 'https_proxy': None}, rval) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_info=None, ca_certs=None, + disable_ssl_certificate_validation=True) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', + 'https_proxy': None}, rval) + + def testLoadFromStorage_serviceAccount(self): + dfp_scope = googleads.oauth2.GetAPIScope('dfp') + # No optional keys present. + yaml_fname = self._CreateYamlFile({'dfp': {'needed': 'd', 'keys': 'e'}}, + 'dfp', self._OAUTH_SERVICE_ACCT_DICT) + with mock.patch( + 'googleads.oauth2.GoogleServiceAccountClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + rval = googleads.common.LoadFromStorage( + yaml_fname, 'dfp', ['needed', 'keys'], ['other']) + mock_client.assert_called_once_with( + dfp_scope, 'test@test.com', '/test/test.p12', proxy_info=None, + ca_certs=None, disable_ssl_certificate_validation=True) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', + 'https_proxy': None}, rval) + + # The optional key is present. + yaml_fname = self._CreateYamlFile({'dfp': {'needed': 'd', 'keys': 'e', + 'other': 'f'}}, 'dfp', + self._OAUTH_SERVICE_ACCT_DICT) + with mock.patch( + 'googleads.oauth2.GoogleServiceAccountClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + rval = googleads.common.LoadFromStorage( + yaml_fname, 'dfp', ['needed', 'keys'], ['other']) + mock_client.assert_called_once_with( + dfp_scope, 'test@test.com', '/test/test.p12', proxy_info=None, + ca_certs=None, disable_ssl_certificate_validation=True) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', 'other': 'f', + 'https_proxy': None}, rval) def testLoadFromStorage_warningWithUnrecognizedKey(self): yaml_fname = self._CreateYamlFile( - {'kval': {'Im': 'here', 'whats': 'this?'}}, 'kval') + {'kval': {'Im': 'here', 'whats': 'this?'}}, 'kval', + self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with warnings.catch_warnings(record=True) as captured_warnings: with mock.patch('googleads.common.open', self.fake_open, create=True): rval = googleads.common.LoadFromStorage( yaml_fname, 'kval', ['Im'], ['other']) - mock_client.assert_called_once_with('a', 'b', 'c', None, True, None) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'Im': 'here', 'https_proxy': None}, rval) - self.assertEqual(len(captured_warnings), 1) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_info=None, ca_certs=None, + disable_ssl_certificate_validation=True) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'Im': 'here', 'https_proxy': None}, rval) + self.assertEqual(len(captured_warnings), 1) def testGenerateLibSig(self): my_name = 'Joseph' diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 2dda75b7..f936ffb9 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -142,7 +142,8 @@ class DfpClientTest(unittest.TestCase): def setUp(self): self.network_code = '12345' self.application_name = 'application name' - self.oauth2_client = 'unused' + self.oauth2_client = mock.Mock() + self.oauth2_client.CreateHttpHeader.return_value = {} self.https_proxy = 'myproxy:443' self.cache = None self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1] diff --git a/tests/patches_test.py b/tests/patches_test.py new file mode 100644 index 00000000..35bed860 --- /dev/null +++ b/tests/patches_test.py @@ -0,0 +1,138 @@ +# Copyright 2016 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. + +"""Unit tests to cover the errors module.""" + +import re +import unittest +from xml.etree import ElementTree + + + +import googleads.adwords +import googleads.dfp +import mock + + +class PatchesTest(unittest.TestCase): + """Tests for the googleads.patches module.""" + + def setUp(self): + oauth_header = {'Authorization': 'header'} + oauth2_client = mock.Mock() + oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) + + # AdWordsClient setup + client_customer_id = 'client customer id' + dev_token = '?wH47154M4n' + user_agent = '4M153rAb13p1l30F53CR37s' + self.adwords_client = googleads.adwords.AdWordsClient( + dev_token, oauth2_client, user_agent, + client_customer_id=client_customer_id) + + # DfpClient setup + network_code = '12345' + application_name = 'application name' + self.dfp_client = googleads.dfp.DfpClient( + oauth2_client, application_name, network_code) + + def testPatchedSudsJurkoAppender(self): + """Tests to confirm that the appender no longer removes empty objects.""" + # Create a fake query & statement + order_id = 1 + values = [{ + 'key': 'orderId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': order_id + } + }, { + 'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'NEEDS_CREATIVES' + } + }] + query = 'WHERE orderId = :orderId AND status = :status' + statement = googleads.dfp.FilterStatement(query, values) + + line_item_service = self.dfp_client.GetService('LineItemService') + line_item_service.suds_client.set_options(nosend=True) + line_item_action = {'xsi_type': 'ActivateLineItems'} + # Perform the ActivateLineItems action. + request = line_item_service.performLineItemAction( + line_item_action, statement.ToStatement()).envelope + line_item_service.suds_client.set_options(nosend=False) + # Strip namespace prefixes and parse. + parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) + line_item_action = parsed_request.find('Body').find('performLineItemAction') + # Assert that the request includes the action. + self.assertTrue(line_item_action is not None) + + def testPatchedSudsJurkoAppenderIssue63(self): + """Verifies that issue 63 has been resolved with the patch.""" + # Create a fake operation to set a Keyword's finalMobileUrls and finalUrls + # to a blank value. In the bug, these fields would be excluded from the + # output. + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': 1, + 'criterion': { + 'id': 123456, + 'xsi_type': 'Keyword', + 'type': 'KEYWORD', + 'matchType': 'BROAD', + 'text': 'I AM ERROR', + }, + # These two fields should appear in the request. + 'finalMobileUrls': {'urls': []}, + 'finalUrls': {'urls': []} + } + }] + adgroup_criterion_service = self.adwords_client.GetService( + 'AdGroupCriterionService') + adgroup_criterion_service.suds_client.set_options(nosend=True) + request = adgroup_criterion_service.mutate(operations).envelope + adgroup_criterion_service.suds_client.set_options(nosend=False) + # Strip namespace prefixes and parse. + parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) + operand = parsed_request.find('Body').find('mutate').find( + 'operations').find('operand') + final_mobile_urls = operand.find('finalMobileUrls') + final_urls = operand.find('finalUrls') + # Assert that the request includes the empty urls. + self.assertTrue(final_mobile_urls is not None) + self.assertTrue(final_urls is not None) + + def testPatchedSudsJurkoAppenderIssue78(self): + """Verifies that issue 78 has been resolved with the patch.""" + # Create a fake customer that contains only an empty value for the + # trackingUrl template. In the bug, this would be excluded from the output. + customer = {'trackingUrlTemplate': '', 'xsi_type': 'Customer'} + customer_service = self.adwords_client.GetService('CustomerService') + customer_service.suds_client.set_options(nosend=True) + request = customer_service.mutate(customer).envelope + customer_service.suds_client.set_options(nosend=False) + # Strip namespace prefixes and parse. + parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) + tracking_url_template = parsed_request.find('Body').find('mutate').find( + 'customer').find('trackingUrlTemplate') + # Assert that the request includes the empty trackingUrlTemplate. + self.assertTrue(tracking_url_template is not None) + + +if __name__ == '__main__': + unittest.main() From c0f8ce6c4acfe88ce8f913a4f0e0e92b548e1022 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 23 Feb 2016 15:07:02 -0500 Subject: [PATCH 030/180] Commiting latest changes. From 69369aedffae9be1a3059b62acd7900ddb43df1e Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 25 Mar 2016 12:06:26 -0700 Subject: [PATCH 031/180] AdWords v201603 release --- ChangeLog | 11 +- README.md | 76 ++- ...ate_adwords_client_with_service_account.py | 2 +- .../create_adwords_client_without_yaml.py | 4 +- .../authentication/generate_refresh_token.py | 6 +- .../account_management/create_account.py | 1 - .../account_management/get_account_changes.py | 1 - .../get_account_hierarchy.py | 1 - .../add_ad_group_bid_modifier.py | 1 - .../add_click_to_download_ad.py | 1 - .../add_text_ad_with_upgraded_urls.py | 1 - .../create_and_attach_shared_keyword_set.py | 1 - ...ind_and_remove_criteria_from_shared_set.py | 1 - .../get_ad_group_bid_modifier.py | 1 - .../upload_offline_conversions.py | 1 - .../use_shared_bidding_strategy.py | 1 - .../v201506/basic_operations/add_ad_groups.py | 1 - .../v201506/basic_operations/add_campaigns.py | 1 - .../v201506/basic_operations/add_keywords.py | 1 - .../v201506/basic_operations/add_text_ads.py | 1 - .../v201506/basic_operations/get_ad_groups.py | 1 - .../v201506/basic_operations/get_campaigns.py | 1 - .../get_campaigns_with_awql.py | 1 - .../v201506/basic_operations/get_keywords.py | 1 - .../v201506/basic_operations/get_text_ads.py | 1 - .../v201506/basic_operations/pause_ad.py | 1 - .../v201506/basic_operations/remove_ad.py | 1 - .../basic_operations/remove_ad_group.py | 1 - .../basic_operations/remove_campaign.py | 1 - .../basic_operations/remove_keyword.py | 1 - .../basic_operations/update_ad_group.py | 1 - .../basic_operations/update_campaign.py | 1 - .../basic_operations/update_keyword.py | 1 - .../add_campaign_labels.py | 1 - .../campaign_management/add_experiment.py | 1 - .../add_keywords_in_bulk.py | 1 - .../get_all_disapproved_ads.py | 1 - .../get_all_disapproved_ads_with_awql.py | 1 - .../get_campaigns_by_label.py | 1 - .../campaign_management/promote_experiment.py | 1 - .../campaign_management/set_ad_parameters.py | 1 - .../set_criterion_bid_modifier.py | 1 - .../campaign_management/validate_text_ad.py | 1 - .../error_handling/handle_partial_failures.py | 1 - .../handle_policy_violation_error.py | 1 - .../v201506/extensions/add_site_links.py | 1 - .../extensions/add_site_links_using_feeds.py | 1 - .../migrate_to_extension_settings.py | 1 - .../v201506/migration/upgrade_ad_url.py | 1 - .../v201506/misc/get_all_images_and_videos.py | 1 - examples/adwords/v201506/misc/upload_image.py | 1 - .../optimization/estimate_keyword_traffic.py | 1 - .../get_keyword_bid_simulations.py | 1 - .../v201506/optimization/get_keyword_ideas.py | 1 - .../v201506/remarketing/add_audience.py | 1 - .../remarketing/add_conversion_tracker.py | 1 - .../remarketing/add_rule_based_user_lists.py | 1 - .../reporting/download_criteria_report.py | 1 - .../download_criteria_report_as_stream.py | 1 - ...oad_criteria_report_as_stream_with_awql.py | 1 - .../download_criteria_report_as_string.py | 1 - ...oad_criteria_report_as_string_with_awql.py | 1 - .../download_criteria_report_with_awql.py | 1 - .../v201506/reporting/get_report_fields.py | 1 - .../shopping/add_product_partition_tree.py | 1 - .../add_campaign_targeting_criteria.py | 1 - .../add_demographic_targeting_criteria.py | 1 - .../get_campaign_targeting_criteria.py | 1 - .../get_targetable_languages_and_carriers.py | 1 - .../v201506/targeting/lookup_location.py | 1 - .../account_management/create_account.py | 1 - .../account_management/get_account_changes.py | 1 - .../get_account_hierarchy.py | 1 - .../add_ad_group_bid_modifier.py | 1 - .../add_click_to_download_ad.py | 1 - .../advanced_operations/add_html5_ad.py | 1 - .../add_text_ad_with_upgraded_urls.py | 1 - .../create_and_attach_shared_keyword_set.py | 1 - ...ind_and_remove_criteria_from_shared_set.py | 1 - .../get_ad_group_bid_modifier.py | 1 - .../upload_offline_conversions.py | 1 - .../use_shared_bidding_strategy.py | 1 - .../v201509/basic_operations/add_ad_groups.py | 1 - .../v201509/basic_operations/add_campaigns.py | 1 - .../v201509/basic_operations/add_keywords.py | 1 - .../v201509/basic_operations/add_text_ads.py | 1 - .../v201509/basic_operations/get_ad_groups.py | 1 - .../v201509/basic_operations/get_campaigns.py | 1 - .../get_campaigns_with_awql.py | 1 - .../v201509/basic_operations/get_keywords.py | 1 - .../v201509/basic_operations/get_text_ads.py | 1 - .../v201509/basic_operations/pause_ad.py | 1 - .../v201509/basic_operations/remove_ad.py | 1 - .../basic_operations/remove_ad_group.py | 1 - .../basic_operations/remove_campaign.py | 1 - .../basic_operations/remove_keyword.py | 1 - .../basic_operations/update_ad_group.py | 1 - .../basic_operations/update_campaign.py | 1 - .../basic_operations/update_keyword.py | 1 - .../add_campaign_labels.py | 1 - .../add_complete_campaigns_using_batch_job.py | 7 +- .../campaign_management/add_experiment.py | 1 - .../add_keywords_in_bulk.py | 1 - ...dd_keywords_using_incremental_batch_job.py | 57 +- .../get_all_disapproved_ads.py | 1 - .../get_all_disapproved_ads_with_awql.py | 1 - .../get_campaigns_by_label.py | 1 - .../campaign_management/promote_experiment.py | 1 - .../campaign_management/set_ad_parameters.py | 1 - .../set_criterion_bid_modifier.py | 1 - .../campaign_management/validate_text_ad.py | 1 - .../error_handling/handle_partial_failures.py | 1 - .../handle_policy_violation_error.py | 1 - .../v201509/extensions/add_site_links.py | 1 - .../extensions/add_site_links_using_feeds.py | 1 - .../migrate_to_extension_settings.py | 1 - .../v201509/migration/upgrade_ad_url.py | 1 - .../v201509/misc/get_all_images_and_videos.py | 1 - examples/adwords/v201509/misc/upload_image.py | 1 - .../v201509/misc/upload_media_bundle.py | 1 - .../optimization/estimate_keyword_traffic.py | 1 - .../get_keyword_bid_simulations.py | 1 - .../v201509/optimization/get_keyword_ideas.py | 1 - .../v201509/remarketing/add_audience.py | 1 - .../remarketing/add_conversion_tracker.py | 1 - .../remarketing/add_rule_based_user_lists.py | 1 - .../reporting/download_criteria_report.py | 1 - .../download_criteria_report_as_stream.py | 1 - ...oad_criteria_report_as_stream_with_awql.py | 1 - .../download_criteria_report_as_string.py | 1 - ...oad_criteria_report_as_string_with_awql.py | 1 - .../download_criteria_report_with_awql.py | 1 - .../v201509/reporting/get_report_fields.py | 1 - .../shopping/add_product_partition_tree.py | 1 - .../add_campaign_targeting_criteria.py | 1 - .../add_demographic_targeting_criteria.py | 1 - .../get_campaign_targeting_criteria.py | 1 - .../get_targetable_languages_and_carriers.py | 5 +- .../v201509/targeting/lookup_location.py | 1 - .../account_management/create_account.py | 1 - .../account_management/get_account_changes.py | 1 - .../get_account_hierarchy.py | 1 - .../add_ad_group_bid_modifier.py | 1 - .../add_click_to_download_ad.py | 1 - .../advanced_operations/add_html5_ad.py | 1 - .../add_text_ad_with_upgraded_urls.py | 1 - .../create_and_attach_shared_keyword_set.py | 1 - ...ind_and_remove_criteria_from_shared_set.py | 1 - .../get_ad_group_bid_modifier.py | 1 - .../use_shared_bidding_strategy.py | 1 - .../v201601/basic_operations/add_ad_groups.py | 1 - .../v201601/basic_operations/add_campaigns.py | 1 - .../v201601/basic_operations/add_keywords.py | 1 - .../v201601/basic_operations/add_text_ads.py | 1 - .../v201601/basic_operations/get_ad_groups.py | 1 - .../v201601/basic_operations/get_campaigns.py | 1 - .../get_campaigns_with_awql.py | 1 - .../v201601/basic_operations/get_keywords.py | 1 - .../v201601/basic_operations/get_text_ads.py | 1 - .../v201601/basic_operations/pause_ad.py | 1 - .../v201601/basic_operations/remove_ad.py | 1 - .../basic_operations/remove_ad_group.py | 1 - .../basic_operations/remove_campaign.py | 1 - .../basic_operations/remove_keyword.py | 1 - .../basic_operations/update_ad_group.py | 1 - .../basic_operations/update_campaign.py | 1 - .../basic_operations/update_keyword.py | 1 - .../add_campaign_labels.py | 1 - .../add_complete_campaigns_using_batch_job.py | 7 +- .../campaign_management/add_experiment.py | 1 - .../add_keywords_in_bulk.py | 1 - ...dd_keywords_using_incremental_batch_job.py | 57 +- .../get_all_disapproved_ads.py | 1 - .../get_all_disapproved_ads_with_awql.py | 1 - .../get_campaigns_by_label.py | 1 - .../campaign_management/promote_experiment.py | 1 - .../campaign_management/set_ad_parameters.py | 1 - .../set_criterion_bid_modifier.py | 1 - .../campaign_management/validate_text_ad.py | 1 - .../error_handling/handle_partial_failures.py | 1 - .../handle_policy_violation_error.py | 1 - .../v201601/extensions/add_site_links.py | 1 - .../extensions/add_site_links_using_feeds.py | 1 - .../migrate_to_extension_settings.py | 1 - .../v201601/migration/upgrade_ad_url.py | 1 - .../v201601/misc/get_all_images_and_videos.py | 1 - examples/adwords/v201601/misc/upload_image.py | 1 - .../v201601/misc/upload_media_bundle.py | 1 - .../optimization/estimate_keyword_traffic.py | 1 - .../get_keyword_bid_simulations.py | 1 - .../v201601/optimization/get_keyword_ideas.py | 1 - .../v201601/remarketing/add_audience.py | 1 - .../remarketing/add_conversion_tracker.py | 1 - .../remarketing/add_rule_based_user_lists.py | 1 - .../remarketing/upload_offline_conversions.py | 1 - .../reporting/download_criteria_report.py | 1 - .../download_criteria_report_as_stream.py | 1 - ...oad_criteria_report_as_stream_with_awql.py | 1 - .../download_criteria_report_as_string.py | 1 - ...oad_criteria_report_as_string_with_awql.py | 1 - .../download_criteria_report_with_awql.py | 1 - .../v201601/reporting/get_report_fields.py | 1 - .../shopping/add_product_partition_tree.py | 1 - .../v201601/shopping/add_shopping_campaign.py | 2 +- .../add_campaign_targeting_criteria.py | 1 - .../add_demographic_targeting_criteria.py | 1 - .../get_campaign_targeting_criteria.py | 1 - .../get_targetable_languages_and_carriers.py | 5 +- .../v201601/targeting/lookup_location.py | 1 - examples/adwords/v201603/__init__.py | 15 + .../v201603/account_management/__init__.py | 15 + .../account_management/create_account.py | 63 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201603/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 222 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 108 ++++ .../advanced_operations/add_html5_ad.py | 111 ++++ .../add_text_ad_with_upgraded_urls.py | 111 ++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201603/basic_operations/__init__.py | 15 + .../v201603/basic_operations/add_ad_groups.py | 115 ++++ .../v201603/basic_operations/add_campaigns.py | 125 +++++ .../v201603/basic_operations/add_keywords.py | 92 +++ .../v201603/basic_operations/add_text_ads.py | 93 ++++ .../v201603/basic_operations/get_ad_groups.py | 76 +++ .../v201603/basic_operations/get_campaigns.py | 74 +++ .../get_campaigns_with_awql.py | 64 +++ .../v201603/basic_operations/get_keywords.py | 87 +++ .../v201603/basic_operations/get_text_ads.py | 80 +++ .../v201603/basic_operations/pause_ad.py | 61 ++ .../v201603/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 58 ++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201603/campaign_management/__init__.py | 15 + .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 426 ++++++++++++++ .../v201603/campaign_management/add_draft.py | 81 +++ .../campaign_management/add_experiment.py | 127 +++++ ...dd_keywords_using_incremental_batch_job.py | 259 +++++++++ .../v201603/campaign_management/add_trial.py | 117 ++++ .../get_all_disapproved_ads.py | 74 +++ .../get_all_disapproved_ads_with_awql.py | 63 +++ .../get_campaigns_by_label.py | 85 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/promote_experiment.py | 60 ++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201603/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 120 ++++ .../handle_policy_violation_error.py | 114 ++++ .../adwords/v201603/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../v201603/extensions/add_site_links.py | 134 +++++ .../extensions/add_site_links_using_feeds.py | 233 ++++++++ .../adwords/v201603/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 527 ++++++++++++++++++ .../v201603/migration/upgrade_ad_url.py | 79 +++ examples/adwords/v201603/misc/__init__.py | 15 + .../v201603/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201603/misc/upload_image.py | 66 +++ .../v201603/misc/upload_media_bundle.py | 59 ++ .../adwords/v201603/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 132 +++++ ...aign_criterion_bid_modifier_simulations.py | 96 ++++ .../get_keyword_bid_simulations.py | 81 +++ .../v201603/optimization/get_keyword_ideas.py | 100 ++++ .../adwords/v201603/remarketing/__init__.py | 15 + .../v201603/remarketing/add_audience.py | 103 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_crm_based_user_list.py | 94 ++++ .../remarketing/add_rule_based_user_lists.py | 183 ++++++ .../remarketing/upload_offline_conversions.py | 75 +++ .../adwords/v201603/reporting/__init__.py | 15 + .../reporting/download_criteria_report.py | 61 ++ .../download_criteria_report_as_stream.py | 77 +++ ...oad_criteria_report_as_stream_with_awql.py | 81 +++ .../download_criteria_report_as_string.py | 59 ++ ...oad_criteria_report_as_string_with_awql.py | 55 ++ .../download_criteria_report_with_awql.py | 58 ++ .../v201603/reporting/get_report_fields.py | 52 ++ examples/adwords/v201603/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 281 ++++++++++ .../v201603/shopping/add_product_scope.py | 104 ++++ .../v201603/shopping/add_shopping_campaign.py | 121 ++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201603/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 161 ++++++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201603/targeting/lookup_location.py | 82 +++ .../create_dfp_client_with_service_account.py | 2 +- .../create_dfp_client_without_yaml.py | 4 +- .../authentication/generate_refresh_token.py | 6 +- googleads.yaml | 4 +- googleads/adwords.py | 67 ++- googleads/common.py | 12 +- googleads/dfp.py | 2 +- googleads/oauth2.py | 36 +- tests/adwords_test.py | 256 ++++++--- tests/common_test.py | 2 +- 311 files changed, 9115 insertions(+), 387 deletions(-) rename examples/adwords/v201509/{advanced_operations => campaign_management}/add_complete_campaigns_using_batch_job.py (98%) rename examples/adwords/v201509/{advanced_operations => campaign_management}/add_keywords_using_incremental_batch_job.py (78%) rename examples/adwords/v201601/{advanced_operations => campaign_management}/add_keywords_using_incremental_batch_job.py (78%) create mode 100644 examples/adwords/v201603/__init__.py create mode 100644 examples/adwords/v201603/account_management/__init__.py create mode 100755 examples/adwords/v201603/account_management/create_account.py create mode 100755 examples/adwords/v201603/account_management/get_account_changes.py create mode 100755 examples/adwords/v201603/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201603/advanced_operations/__init__.py create mode 100755 examples/adwords/v201603/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201603/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201603/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201603/advanced_operations/add_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201603/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201603/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201603/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201603/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201603/basic_operations/__init__.py create mode 100755 examples/adwords/v201603/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201603/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201603/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201603/basic_operations/add_text_ads.py create mode 100755 examples/adwords/v201603/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201603/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201603/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201603/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201603/basic_operations/get_text_ads.py create mode 100755 examples/adwords/v201603/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201603/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201603/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201603/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201603/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201603/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201603/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201603/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201603/campaign_management/__init__.py create mode 100755 examples/adwords/v201603/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201603/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201603/campaign_management/add_draft.py create mode 100755 examples/adwords/v201603/campaign_management/add_experiment.py create mode 100755 examples/adwords/v201603/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201603/campaign_management/add_trial.py create mode 100755 examples/adwords/v201603/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201603/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201603/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201603/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201603/campaign_management/promote_experiment.py create mode 100755 examples/adwords/v201603/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201603/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201603/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201603/error_handling/__init__.py create mode 100755 examples/adwords/v201603/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201603/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201603/extensions/__init__.py create mode 100755 examples/adwords/v201603/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201603/extensions/add_site_links.py create mode 100755 examples/adwords/v201603/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201603/migration/__init__.py create mode 100755 examples/adwords/v201603/migration/migrate_to_extension_settings.py create mode 100755 examples/adwords/v201603/migration/upgrade_ad_url.py create mode 100644 examples/adwords/v201603/misc/__init__.py create mode 100755 examples/adwords/v201603/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201603/misc/upload_image.py create mode 100755 examples/adwords/v201603/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201603/optimization/__init__.py create mode 100755 examples/adwords/v201603/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201603/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201603/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201603/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201603/remarketing/__init__.py create mode 100755 examples/adwords/v201603/remarketing/add_audience.py create mode 100755 examples/adwords/v201603/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201603/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201603/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201603/remarketing/upload_offline_conversions.py create mode 100644 examples/adwords/v201603/reporting/__init__.py create mode 100755 examples/adwords/v201603/reporting/download_criteria_report.py create mode 100755 examples/adwords/v201603/reporting/download_criteria_report_as_stream.py create mode 100755 examples/adwords/v201603/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201603/reporting/download_criteria_report_as_string.py create mode 100755 examples/adwords/v201603/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201603/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201603/reporting/get_report_fields.py create mode 100644 examples/adwords/v201603/shopping/__init__.py create mode 100755 examples/adwords/v201603/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201603/shopping/add_product_scope.py create mode 100755 examples/adwords/v201603/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201603/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201603/targeting/__init__.py create mode 100755 examples/adwords/v201603/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201603/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201603/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201603/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201603/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 29bed34a..a3b5f546 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +3.14.0 -- 3/25/2016 +* Added support for AdWords v201603. +* Resolved Issues: + Issue #105: https://github.com/googleads/googleads-python-lib/issues/105 + Issue #106: https://github.com/googleads/googleads-python-lib/issues/106 + 3.13.0 -- 2/23/2016 * Added support for DFP v201602. * Removed support for DFP v201411. @@ -7,7 +13,7 @@ library publicly exposes its 0.7 release. Thanks to GitHub user adiharush for suggesting the patch! * The LoadFromStorage function can now load credentials for either the - installed application or service account (.p12 files only) OAuth 2.0 flows. + installed application or service account (.p12 files only) OAuth2 flows. * The googleads.yaml configuration file has been updated to reflect the changes to the LoadFromStorage function. * Resolved Issues: @@ -30,7 +36,6 @@ * The AdWords BatchJobHelper and IncrementalUploadHelper utilities now initialize URLs for v201601 and up. * The AdWords IncrementalUploadHelper is now serializable. ->>>>>>> a4bf1f889e4cecee17f2e27a10d593452904cb8b 3.11.0 -- 11/24/2015 * Removed support for AdWords v201502. @@ -196,7 +201,7 @@ Library. * Added CampaignSharedSetService, LabelService, SharedCriterionService, and SharedSetService for AdWords. -* Updated AdWords OAuth 2.0 scope. +* Updated AdWords OAuth2 scope. See: https://developers.google.com/adwords/api/docs/guides/authentication. 1.0.6 - 05/29/2014 diff --git a/README.md b/README.md index f52e919e..5679da8e 100644 --- a/README.md +++ b/README.md @@ -6,34 +6,64 @@ and DoubleClick for Publishers. The library provides easy ways to store your authentication and create SOAP web service clients. It also contains example code to help you get started integrating with our APIs. -##How do I get started? -####Installing the library -Install or update the library from PyPI. If you're using pip, this is as easy -as: +##Getting started +1. Download and install the library -`$ pip install [--upgrade] googleads` + It is recommended that you install the library and its dependencies from + PyPI using [pip](https://pip.pypa.io/en/stable/installing/). This can be + accomplished with a single command: -If you don't want to install directly from PyPI, you can download the library -as a tarball and then install it manually. The download can be found here: -https://pypi.python.org/pypi/googleads -Navigate to the directory that contains your downloaded unzipped client -library and run the "setup.py" script to install the "googleads" -module. + `$ pip install googleads` -`$ python setup.py build install` + As an alternative, you can + [download the library as a tarball](https://pypi.python.org/pypi/googleads). + To start the installation, navigate to the directory that contains your + downloaded unzipped client library and run the "setup.py" script as follows: -You can find code examples in the git repo and in the library's releases within -the examples folder. + `$ python setup.py build install` + +1. Copy the [googleads.yaml](https://github.com/googleads/googleads-python-lib/blob/master/googleads.yaml) + file to your home directory. + + This will be used to store credentials and other settings that can be loaded + to initialize a client. + +1. Set up your OAuth2 credentials + + The AdWords and DoubleClick for Publishers APIs use + [OAuth2](http://oauth.net/2/) as the authentication mechanism. Follow the + appropriate guide below based on your use case. + + **If you're accessing an API using your own credentials...** + + * [Using AdWords](https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-(installed-application-flow)) + * [Using DFP](https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-(server-to-server-flow)) + + **If you're accessing an API on behalf of clients...** + + * [Developing a web application (AdWords or DFP)](https://github.com/googleads/googleads-python-lib/wiki/API-access-on-behalf-of-your-clients-(web-flow)) + +####Where can I find samples? + +You can find code examples for the latest versions of AdWords or DFP on the +[releases](https://github.com/googleads/googleads-python-lib/releases) page. + +Alternatively, you can find [AdWords](https://github.com/googleads/googleads-python-lib/tree/master/examples/adwords) +or [DFP](https://github.com/googleads/googleads-python-lib/tree/master/examples/dfp) +samples in the examples directory of this repository. ####Where can I find the pydocs? -Our pydocs are hosted at: http://googleads.github.io/googleads-python-lib + +Our Pydoc can be found [here](http://googleads.github.io/googleads-python-lib). ####Caching authentication information + It is possible to cache your API authentication information. The library includes a sample file showing how to do this named `googleads.yaml`. Fill -in the fields for the API you plan to use. The library's `LoadFromStorage` -methods default to looking for a file with this name in your home directory, -but you can pass in a path to any file with the correct yaml contents. +in the fields for the API and features you plan to use. The library's +`LoadFromStorage` methods default to looking for a file with this name in your +home directory, but you can pass in a path to any file with the correct yaml +contents. ```python # Use the default location - your home directory: @@ -118,11 +148,13 @@ suds_client.service.mutate([operation]) ##External Dependencies: - - oauthlib -- http://pypi.python.org/pypi/oauthlib/ - - suds-jurko -- http://pypi.python.org/pypi/suds-jurko/ + - oauth2client -- https://pypi.python.org/pypi/oauth2client/ + - suds-jurko -- https://pypi.python.org/pypi/suds-jurko/ + - pysocks -- https://pypi.python.org/pypi/PySocks/ - pytz -- https://pypi.python.org/pypi/pytz - - pyYAML -- http://pypi.python.org/pypi/pyYAML/ - - mock -- http://pypi.python.org/pypi/mock + - pyYAML -- https://pypi.python.org/pypi/pyYAML/ + - xmltodict -- https://pypi.python.org/pypi/xmltodict/ + - mock -- https://pypi.python.org/pypi/mock (only needed to run unit tests) - pyfakefs -- https://pypi.python.org/pypi/pyfakefs (only needed to run unit tests) diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index 1d9f0b86..71469a2e 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -20,7 +20,7 @@ from googleads import adwords from googleads import oauth2 -# OAuth 2.0 credential information. In a real application, you'd probably be +# OAuth2 credential information. In a real application, you'd probably be # pulling these values from a credential storage. SERVICE_ACCOUNT_EMAIL = 'INSERT_SERVICE_ACCOUNT_EMAIL_HERE' KEY_FILE = 'INSERT_PATH_TO_KEY_FILE' diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_without_yaml.py index 30e50723..3726b195 100755 --- a/examples/adwords/authentication/create_adwords_client_without_yaml.py +++ b/examples/adwords/authentication/create_adwords_client_without_yaml.py @@ -18,7 +18,7 @@ While our LoadFromStorage method provides a useful shortcut to instantiate a client if you regularly use just one set of credentials, production applications -may need to swap out users. This example shows you how to create an OAuth 2.0 +may need to swap out users. This example shows you how to create an OAuth2 client and an AdWordsClient without relying on a yaml file. """ @@ -26,7 +26,7 @@ from googleads import adwords from googleads import oauth2 -# OAuth 2.0 credential information. In a real application, you'd probably be +# OAuth2 credential information. In a real application, you'd probably be # pulling these values from a credential storage. CLIENT_ID = 'INSERT_CLIENT_ID_HERE' CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 20c28c0c..37696d7e 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -22,12 +22,12 @@ from oauth2client import client -# Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet, +# Your OAuth2 Client ID and Secret. If you do not have an ID and Secret yet, # please go to https://console.developers.google.com and create a set. DEFAULT_CLIENT_ID = None DEFAULT_CLIENT_SECRET = None -# The AdWords API OAuth 2.0 scope. +# The AdWords API OAuth2 scope. SCOPE = u'https://www.googleapis.com/auth/adwords' parser = argparse.ArgumentParser(description='Generates a refresh token with ' @@ -64,7 +64,7 @@ def main(client_id, client_secret, scopes): print 'Authentication has failed: %s' % e sys.exit(1) else: - print ('OAuth 2.0 authorization successful!\n\n' + print ('OAuth2 authorization successful!\n\n' 'Your access token is:\n %s\n\nYour refresh token is:\n %s' % (credential.access_token, credential.refresh_token)) diff --git a/examples/adwords/v201506/account_management/create_account.py b/examples/adwords/v201506/account_management/create_account.py index 75f5fc1b..e85b211a 100755 --- a/examples/adwords/v201506/account_management/create_account.py +++ b/examples/adwords/v201506/account_management/create_account.py @@ -28,7 +28,6 @@ from datetime import datetime - from googleads import adwords diff --git a/examples/adwords/v201506/account_management/get_account_changes.py b/examples/adwords/v201506/account_management/get_account_changes.py index a1e4cb4b..dec446fe 100755 --- a/examples/adwords/v201506/account_management/get_account_changes.py +++ b/examples/adwords/v201506/account_management/get_account_changes.py @@ -25,7 +25,6 @@ import datetime - from googleads import adwords diff --git a/examples/adwords/v201506/account_management/get_account_hierarchy.py b/examples/adwords/v201506/account_management/get_account_hierarchy.py index f575868f..5b875a11 100755 --- a/examples/adwords/v201506/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201506/account_management/get_account_hierarchy.py @@ -26,7 +26,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py index 0b044c45..4a4d501f 100755 --- a/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py index f8367749..814f7ee5 100755 --- a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py @@ -25,7 +25,6 @@ section of our README. """ - from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py index 504c4968..51f67f00 100755 --- a/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -23,7 +23,6 @@ """ - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py index 00f9629f..9eec131f 100755 --- a/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py index b81812e4..5d6e1356 100755 --- a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py index 57bc6388..65ff5ab5 100755 --- a/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py index 01d725cb..94ad5d2a 100755 --- a/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py +++ b/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py index e1826938..b77cdda9 100755 --- a/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/add_ad_groups.py b/examples/adwords/v201506/basic_operations/add_ad_groups.py index 242dde17..98c385bd 100755 --- a/examples/adwords/v201506/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201506/basic_operations/add_ad_groups.py @@ -27,7 +27,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/add_campaigns.py b/examples/adwords/v201506/basic_operations/add_campaigns.py index a73e904c..0afc9310 100755 --- a/examples/adwords/v201506/basic_operations/add_campaigns.py +++ b/examples/adwords/v201506/basic_operations/add_campaigns.py @@ -28,7 +28,6 @@ import datetime import uuid - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/add_keywords.py b/examples/adwords/v201506/basic_operations/add_keywords.py index d5cddc28..9495ca1e 100755 --- a/examples/adwords/v201506/basic_operations/add_keywords.py +++ b/examples/adwords/v201506/basic_operations/add_keywords.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/add_text_ads.py b/examples/adwords/v201506/basic_operations/add_text_ads.py index 0b56f8fa..0968e2ac 100755 --- a/examples/adwords/v201506/basic_operations/add_text_ads.py +++ b/examples/adwords/v201506/basic_operations/add_text_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/get_ad_groups.py b/examples/adwords/v201506/basic_operations/get_ad_groups.py index e7ca7fac..68f5860e 100755 --- a/examples/adwords/v201506/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201506/basic_operations/get_ad_groups.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/get_campaigns.py b/examples/adwords/v201506/basic_operations/get_campaigns.py index ff161fde..377cfd81 100755 --- a/examples/adwords/v201506/basic_operations/get_campaigns.py +++ b/examples/adwords/v201506/basic_operations/get_campaigns.py @@ -28,7 +28,6 @@ import logging import time - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py index d4b0f4f6..ea9c31a1 100755 --- a/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py @@ -27,7 +27,6 @@ import time - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/get_keywords.py b/examples/adwords/v201506/basic_operations/get_keywords.py index 1c1e78ca..e70dd2dd 100755 --- a/examples/adwords/v201506/basic_operations/get_keywords.py +++ b/examples/adwords/v201506/basic_operations/get_keywords.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/get_text_ads.py b/examples/adwords/v201506/basic_operations/get_text_ads.py index b06b2d44..4d189e28 100755 --- a/examples/adwords/v201506/basic_operations/get_text_ads.py +++ b/examples/adwords/v201506/basic_operations/get_text_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/pause_ad.py b/examples/adwords/v201506/basic_operations/pause_ad.py index 938f0548..e293acf1 100755 --- a/examples/adwords/v201506/basic_operations/pause_ad.py +++ b/examples/adwords/v201506/basic_operations/pause_ad.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/remove_ad.py b/examples/adwords/v201506/basic_operations/remove_ad.py index 0becfa0a..a2fd34a7 100755 --- a/examples/adwords/v201506/basic_operations/remove_ad.py +++ b/examples/adwords/v201506/basic_operations/remove_ad.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/remove_ad_group.py b/examples/adwords/v201506/basic_operations/remove_ad_group.py index d4dd2c62..e852b3ba 100755 --- a/examples/adwords/v201506/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201506/basic_operations/remove_ad_group.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/remove_campaign.py b/examples/adwords/v201506/basic_operations/remove_campaign.py index 017f2425..d6212974 100755 --- a/examples/adwords/v201506/basic_operations/remove_campaign.py +++ b/examples/adwords/v201506/basic_operations/remove_campaign.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/remove_keyword.py b/examples/adwords/v201506/basic_operations/remove_keyword.py index 69ac8cba..d1fe3c2c 100755 --- a/examples/adwords/v201506/basic_operations/remove_keyword.py +++ b/examples/adwords/v201506/basic_operations/remove_keyword.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/update_ad_group.py b/examples/adwords/v201506/basic_operations/update_ad_group.py index 38f52a22..32cdd184 100755 --- a/examples/adwords/v201506/basic_operations/update_ad_group.py +++ b/examples/adwords/v201506/basic_operations/update_ad_group.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/update_campaign.py b/examples/adwords/v201506/basic_operations/update_campaign.py index e97986bd..5e7b0c03 100755 --- a/examples/adwords/v201506/basic_operations/update_campaign.py +++ b/examples/adwords/v201506/basic_operations/update_campaign.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/basic_operations/update_keyword.py b/examples/adwords/v201506/basic_operations/update_keyword.py index d4fa50cf..0c083bdf 100755 --- a/examples/adwords/v201506/basic_operations/update_keyword.py +++ b/examples/adwords/v201506/basic_operations/update_keyword.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/add_campaign_labels.py b/examples/adwords/v201506/campaign_management/add_campaign_labels.py index 3044e313..2747e00f 100755 --- a/examples/adwords/v201506/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201506/campaign_management/add_campaign_labels.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/add_experiment.py b/examples/adwords/v201506/campaign_management/add_experiment.py index a5a0c421..ce68a39c 100755 --- a/examples/adwords/v201506/campaign_management/add_experiment.py +++ b/examples/adwords/v201506/campaign_management/add_experiment.py @@ -32,7 +32,6 @@ import datetime import uuid - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py index 8db03a3f..2922b32b 100755 --- a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py +++ b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py @@ -27,7 +27,6 @@ import random import re import time - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py index feb1106f..12f4cc97 100755 --- a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py index be536c39..1f1580b8 100755 --- a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py index 51728528..acc574b8 100755 --- a/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py @@ -27,7 +27,6 @@ import time - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/promote_experiment.py b/examples/adwords/v201506/campaign_management/promote_experiment.py index 39ff5c4a..a197a120 100755 --- a/examples/adwords/v201506/campaign_management/promote_experiment.py +++ b/examples/adwords/v201506/campaign_management/promote_experiment.py @@ -27,7 +27,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/set_ad_parameters.py b/examples/adwords/v201506/campaign_management/set_ad_parameters.py index b0925086..c7a9727d 100755 --- a/examples/adwords/v201506/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201506/campaign_management/set_ad_parameters.py @@ -26,7 +26,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py index f0b65df9..aef6b487 100755 --- a/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py @@ -24,7 +24,6 @@ section of our README. """ - from googleads import adwords diff --git a/examples/adwords/v201506/campaign_management/validate_text_ad.py b/examples/adwords/v201506/campaign_management/validate_text_ad.py index c11b7443..001ae7cf 100755 --- a/examples/adwords/v201506/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201506/campaign_management/validate_text_ad.py @@ -23,7 +23,6 @@ """ - import suds from googleads import adwords diff --git a/examples/adwords/v201506/error_handling/handle_partial_failures.py b/examples/adwords/v201506/error_handling/handle_partial_failures.py index 39c8b4e3..c6729d1e 100755 --- a/examples/adwords/v201506/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201506/error_handling/handle_partial_failures.py @@ -27,7 +27,6 @@ import re - from googleads import adwords diff --git a/examples/adwords/v201506/error_handling/handle_policy_violation_error.py b/examples/adwords/v201506/error_handling/handle_policy_violation_error.py index ccf35075..1c9ee84c 100755 --- a/examples/adwords/v201506/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201506/error_handling/handle_policy_violation_error.py @@ -27,7 +27,6 @@ import re - import suds from googleads import adwords diff --git a/examples/adwords/v201506/extensions/add_site_links.py b/examples/adwords/v201506/extensions/add_site_links.py index ad1f63bf..38f8e087 100755 --- a/examples/adwords/v201506/extensions/add_site_links.py +++ b/examples/adwords/v201506/extensions/add_site_links.py @@ -26,7 +26,6 @@ from datetime import datetime - from googleads import adwords from googleads import errors from pytz import timezone diff --git a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py index da321c9e..0c126473 100755 --- a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py @@ -29,7 +29,6 @@ import re import uuid - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201506/migration/migrate_to_extension_settings.py b/examples/adwords/v201506/migration/migrate_to_extension_settings.py index 1d8c1972..a4ea2eff 100755 --- a/examples/adwords/v201506/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201506/migration/migrate_to_extension_settings.py @@ -30,7 +30,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/migration/upgrade_ad_url.py b/examples/adwords/v201506/migration/upgrade_ad_url.py index c4158ff0..edca6b1b 100755 --- a/examples/adwords/v201506/migration/upgrade_ad_url.py +++ b/examples/adwords/v201506/migration/upgrade_ad_url.py @@ -23,7 +23,6 @@ """ - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201506/misc/get_all_images_and_videos.py b/examples/adwords/v201506/misc/get_all_images_and_videos.py index cfc01af6..96c5c518 100755 --- a/examples/adwords/v201506/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201506/misc/get_all_images_and_videos.py @@ -26,7 +26,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/misc/upload_image.py b/examples/adwords/v201506/misc/upload_image.py index a017eb69..fae31b83 100755 --- a/examples/adwords/v201506/misc/upload_image.py +++ b/examples/adwords/v201506/misc/upload_image.py @@ -27,7 +27,6 @@ import base64 - from googleads import adwords diff --git a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py index 278736c1..b87b3623 100755 --- a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py index 2a770b00..dec4acd9 100755 --- a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/optimization/get_keyword_ideas.py b/examples/adwords/v201506/optimization/get_keyword_ideas.py index 920fbf40..28ce973d 100755 --- a/examples/adwords/v201506/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201506/optimization/get_keyword_ideas.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/remarketing/add_audience.py b/examples/adwords/v201506/remarketing/add_audience.py index 437bd427..102f8249 100755 --- a/examples/adwords/v201506/remarketing/add_audience.py +++ b/examples/adwords/v201506/remarketing/add_audience.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201506/remarketing/add_conversion_tracker.py b/examples/adwords/v201506/remarketing/add_conversion_tracker.py index cda8ff0c..367e305f 100755 --- a/examples/adwords/v201506/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201506/remarketing/add_conversion_tracker.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py index 2b411d81..76de9a66 100755 --- a/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py @@ -32,7 +32,6 @@ from datetime import date from datetime import datetime from datetime import timedelta - from googleads import adwords diff --git a/examples/adwords/v201506/reporting/download_criteria_report.py b/examples/adwords/v201506/reporting/download_criteria_report.py index 5cddd34a..f0b72e18 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report.py +++ b/examples/adwords/v201506/reporting/download_criteria_report.py @@ -28,7 +28,6 @@ import logging import sys - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py index 8daa5411..8b36a0f4 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py @@ -29,7 +29,6 @@ import logging import StringIO import sys - from googleads import adwords diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py index 10223304..98567d95 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py @@ -30,7 +30,6 @@ import StringIO import sys - from googleads import adwords diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py index b376d930..51cc7415 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py @@ -27,7 +27,6 @@ import logging - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py index 42d8516e..2da6d4ad 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py index 4b261a46..714e900c 100755 --- a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/reporting/get_report_fields.py b/examples/adwords/v201506/reporting/get_report_fields.py index 289f9df7..73a250ea 100755 --- a/examples/adwords/v201506/reporting/get_report_fields.py +++ b/examples/adwords/v201506/reporting/get_report_fields.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/shopping/add_product_partition_tree.py b/examples/adwords/v201506/shopping/add_product_partition_tree.py index b2aa3a80..c151b050 100755 --- a/examples/adwords/v201506/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201506/shopping/add_product_partition_tree.py @@ -279,4 +279,3 @@ def DisplayTree(node, children, level=0): adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, ADGROUP_ID) - diff --git a/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py index 16db54a2..ecb1346f 100755 --- a/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py index e3d72430..2910530d 100755 --- a/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py index 147c1140..2188f179 100755 --- a/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py index 189b3597..70104d28 100755 --- a/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201506/targeting/lookup_location.py b/examples/adwords/v201506/targeting/lookup_location.py index b65efa30..3b6abe9f 100755 --- a/examples/adwords/v201506/targeting/lookup_location.py +++ b/examples/adwords/v201506/targeting/lookup_location.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/account_management/create_account.py b/examples/adwords/v201509/account_management/create_account.py index ea1dd60f..a0470ff2 100755 --- a/examples/adwords/v201509/account_management/create_account.py +++ b/examples/adwords/v201509/account_management/create_account.py @@ -28,7 +28,6 @@ from datetime import datetime - from googleads import adwords diff --git a/examples/adwords/v201509/account_management/get_account_changes.py b/examples/adwords/v201509/account_management/get_account_changes.py index dd0f1005..635445c5 100755 --- a/examples/adwords/v201509/account_management/get_account_changes.py +++ b/examples/adwords/v201509/account_management/get_account_changes.py @@ -25,7 +25,6 @@ import datetime - from googleads import adwords diff --git a/examples/adwords/v201509/account_management/get_account_hierarchy.py b/examples/adwords/v201509/account_management/get_account_hierarchy.py index 951fa6dc..c788e1cc 100755 --- a/examples/adwords/v201509/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201509/account_management/get_account_hierarchy.py @@ -22,7 +22,6 @@ section of our README. """ - from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py index 64f14421..cde0ba14 100755 --- a/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py index 4563c4ad..955ded76 100755 --- a/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py @@ -25,7 +25,6 @@ section of our README. """ - from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/add_html5_ad.py b/examples/adwords/v201509/advanced_operations/add_html5_ad.py index fc6e19d3..b171ca8a 100755 --- a/examples/adwords/v201509/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201509/advanced_operations/add_html5_ad.py @@ -28,7 +28,6 @@ import base64 import urllib2 - from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py index 93909358..b75702e1 100755 --- a/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -23,7 +23,6 @@ """ - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py index b4a66c1a..c6b91733 100755 --- a/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py index d5f6179c..da0361e2 100755 --- a/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py index 292958ac..1ff38b87 100755 --- a/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py index 50cfc409..123d0027 100755 --- a/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py +++ b/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py index a02607f7..28b90a07 100755 --- a/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/add_ad_groups.py b/examples/adwords/v201509/basic_operations/add_ad_groups.py index 5059bffd..eef60c1f 100755 --- a/examples/adwords/v201509/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201509/basic_operations/add_ad_groups.py @@ -27,7 +27,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/add_campaigns.py b/examples/adwords/v201509/basic_operations/add_campaigns.py index 8bd8a561..ef01b692 100755 --- a/examples/adwords/v201509/basic_operations/add_campaigns.py +++ b/examples/adwords/v201509/basic_operations/add_campaigns.py @@ -28,7 +28,6 @@ import datetime import uuid - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/add_keywords.py b/examples/adwords/v201509/basic_operations/add_keywords.py index fb946b2e..bd2a6f4b 100755 --- a/examples/adwords/v201509/basic_operations/add_keywords.py +++ b/examples/adwords/v201509/basic_operations/add_keywords.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/add_text_ads.py b/examples/adwords/v201509/basic_operations/add_text_ads.py index 56f44f18..168720f7 100755 --- a/examples/adwords/v201509/basic_operations/add_text_ads.py +++ b/examples/adwords/v201509/basic_operations/add_text_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/get_ad_groups.py b/examples/adwords/v201509/basic_operations/get_ad_groups.py index 914813bf..d2009ece 100755 --- a/examples/adwords/v201509/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201509/basic_operations/get_ad_groups.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/get_campaigns.py b/examples/adwords/v201509/basic_operations/get_campaigns.py index b3233682..0c400aea 100755 --- a/examples/adwords/v201509/basic_operations/get_campaigns.py +++ b/examples/adwords/v201509/basic_operations/get_campaigns.py @@ -28,7 +28,6 @@ import logging import time - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py index 61cb711e..c2cbf6e4 100755 --- a/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py @@ -27,7 +27,6 @@ import time - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/get_keywords.py b/examples/adwords/v201509/basic_operations/get_keywords.py index 82fb7f03..dc452bdf 100755 --- a/examples/adwords/v201509/basic_operations/get_keywords.py +++ b/examples/adwords/v201509/basic_operations/get_keywords.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/get_text_ads.py b/examples/adwords/v201509/basic_operations/get_text_ads.py index f6c553ad..caabbb42 100755 --- a/examples/adwords/v201509/basic_operations/get_text_ads.py +++ b/examples/adwords/v201509/basic_operations/get_text_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/pause_ad.py b/examples/adwords/v201509/basic_operations/pause_ad.py index adf64e13..a698508d 100755 --- a/examples/adwords/v201509/basic_operations/pause_ad.py +++ b/examples/adwords/v201509/basic_operations/pause_ad.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/remove_ad.py b/examples/adwords/v201509/basic_operations/remove_ad.py index 9728af22..d8a1a2bc 100755 --- a/examples/adwords/v201509/basic_operations/remove_ad.py +++ b/examples/adwords/v201509/basic_operations/remove_ad.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/remove_ad_group.py b/examples/adwords/v201509/basic_operations/remove_ad_group.py index 077f344b..d9a6901c 100755 --- a/examples/adwords/v201509/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201509/basic_operations/remove_ad_group.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/remove_campaign.py b/examples/adwords/v201509/basic_operations/remove_campaign.py index ded3830b..d7dd29f7 100755 --- a/examples/adwords/v201509/basic_operations/remove_campaign.py +++ b/examples/adwords/v201509/basic_operations/remove_campaign.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/remove_keyword.py b/examples/adwords/v201509/basic_operations/remove_keyword.py index a733c77d..a9eb585d 100755 --- a/examples/adwords/v201509/basic_operations/remove_keyword.py +++ b/examples/adwords/v201509/basic_operations/remove_keyword.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/update_ad_group.py b/examples/adwords/v201509/basic_operations/update_ad_group.py index d0f8f176..e29956a6 100755 --- a/examples/adwords/v201509/basic_operations/update_ad_group.py +++ b/examples/adwords/v201509/basic_operations/update_ad_group.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/update_campaign.py b/examples/adwords/v201509/basic_operations/update_campaign.py index cab1e337..8349d529 100755 --- a/examples/adwords/v201509/basic_operations/update_campaign.py +++ b/examples/adwords/v201509/basic_operations/update_campaign.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/basic_operations/update_keyword.py b/examples/adwords/v201509/basic_operations/update_keyword.py index aeb9dfe8..da51cc46 100755 --- a/examples/adwords/v201509/basic_operations/update_keyword.py +++ b/examples/adwords/v201509/basic_operations/update_keyword.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/campaign_management/add_campaign_labels.py b/examples/adwords/v201509/campaign_management/add_campaign_labels.py index 286a4337..d40b5e38 100755 --- a/examples/adwords/v201509/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201509/campaign_management/add_campaign_labels.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py similarity index 98% rename from examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py rename to examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py index 57dc3222..c4fb105f 100755 --- a/examples/adwords/v201509/advanced_operations/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py @@ -26,7 +26,6 @@ import urllib2 import uuid - from googleads import adwords @@ -34,12 +33,12 @@ NUMBER_OF_ADGROUPS_TO_ADD = 2 NUMBER_OF_KEYWORDS_TO_ADD = 5 MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE') +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper() + batch_job_helper = client.GetBatchJobHelper(version='v201509') # Create a BatchJob. batch_job = AddBatchJob(client) @@ -347,7 +346,7 @@ def GetBatchJob(client, batch_job_id): Returns: The BatchJob associated with the given id. """ - batch_job_service = client.GetService('BatchJobService') + batch_job_service = client.GetService('BatchJobService', version='v201509') selector = { 'fields': ['Id', 'Status', 'DownloadUrl'], diff --git a/examples/adwords/v201509/campaign_management/add_experiment.py b/examples/adwords/v201509/campaign_management/add_experiment.py index 38cba15b..1309216c 100755 --- a/examples/adwords/v201509/campaign_management/add_experiment.py +++ b/examples/adwords/v201509/campaign_management/add_experiment.py @@ -32,7 +32,6 @@ import datetime import uuid - from googleads import adwords diff --git a/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py index 622449d2..c3f1058a 100755 --- a/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py +++ b/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py @@ -27,7 +27,6 @@ import random import re import time - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201509/campaign_management/add_keywords_using_incremental_batch_job.py similarity index 78% rename from examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py rename to examples/adwords/v201509/campaign_management/add_keywords_using_incremental_batch_job.py index 8c409409..f068e055 100755 --- a/examples/adwords/v201509/advanced_operations/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201509/campaign_management/add_keywords_using_incremental_batch_job.py @@ -26,19 +26,18 @@ import urllib2 import uuid - from googleads import adwords ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' KEYWORD_COUNT = 100 MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE') +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') def main(client, adgroup_id): # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper() + batch_job_helper = client.GetBatchJobHelper(version='v201509') # Create a BatchJob. batch_job = AddBatchJob(client) @@ -123,6 +122,46 @@ def BuildAdGroupCriterionOperations(adgroup_id): return criterion_operations +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201509') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + def GetBatchJob(client, batch_job_id): """Retrieves the BatchJob with the given id. @@ -132,7 +171,7 @@ def GetBatchJob(client, batch_job_id): Returns: The BatchJob associated with the given id. """ - batch_job_service = client.GetService('BatchJobService') + batch_job_service = client.GetService('BatchJobService', 'v201509') selector = { 'fields': ['Id', 'Status', 'DownloadUrl'], @@ -166,6 +205,10 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, have been made. """ batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + poll_attempt = 0 while (poll_attempt in range(max_poll_attempts) and @@ -182,8 +225,10 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' % (batch_job['id'], batch_job['status'], url)) return url - raise Exception('Batch Job with ID "%s" not finished downloading. Try ' - 'checking later.' % batch_job_id) + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) def PrintResponse(batch_job_helper, response_xml): diff --git a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py index 6ac34e1c..0c2aa610 100755 --- a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py index ca660dbc..b71b1763 100755 --- a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py index 7d71764d..7f7293b7 100755 --- a/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py @@ -27,7 +27,6 @@ import time - from googleads import adwords diff --git a/examples/adwords/v201509/campaign_management/promote_experiment.py b/examples/adwords/v201509/campaign_management/promote_experiment.py index a7fe43e1..7791f05a 100755 --- a/examples/adwords/v201509/campaign_management/promote_experiment.py +++ b/examples/adwords/v201509/campaign_management/promote_experiment.py @@ -27,7 +27,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/campaign_management/set_ad_parameters.py b/examples/adwords/v201509/campaign_management/set_ad_parameters.py index 98fbc66b..0bb56840 100755 --- a/examples/adwords/v201509/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201509/campaign_management/set_ad_parameters.py @@ -26,7 +26,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py index 37ed3795..a7ceb5d5 100755 --- a/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py @@ -24,7 +24,6 @@ section of our README. """ - from googleads import adwords diff --git a/examples/adwords/v201509/campaign_management/validate_text_ad.py b/examples/adwords/v201509/campaign_management/validate_text_ad.py index dd0d79f4..6def1840 100755 --- a/examples/adwords/v201509/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201509/campaign_management/validate_text_ad.py @@ -23,7 +23,6 @@ """ - import suds from googleads import adwords diff --git a/examples/adwords/v201509/error_handling/handle_partial_failures.py b/examples/adwords/v201509/error_handling/handle_partial_failures.py index adcdf369..4f5a3ba9 100755 --- a/examples/adwords/v201509/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201509/error_handling/handle_partial_failures.py @@ -27,7 +27,6 @@ import re - from googleads import adwords diff --git a/examples/adwords/v201509/error_handling/handle_policy_violation_error.py b/examples/adwords/v201509/error_handling/handle_policy_violation_error.py index 9e114b1c..2a467150 100755 --- a/examples/adwords/v201509/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201509/error_handling/handle_policy_violation_error.py @@ -27,7 +27,6 @@ import re - import suds from googleads import adwords diff --git a/examples/adwords/v201509/extensions/add_site_links.py b/examples/adwords/v201509/extensions/add_site_links.py index 72463ace..65bfeff0 100755 --- a/examples/adwords/v201509/extensions/add_site_links.py +++ b/examples/adwords/v201509/extensions/add_site_links.py @@ -26,7 +26,6 @@ from datetime import datetime - from googleads import adwords from googleads import errors from pytz import timezone diff --git a/examples/adwords/v201509/extensions/add_site_links_using_feeds.py b/examples/adwords/v201509/extensions/add_site_links_using_feeds.py index 505a81c4..b89254ef 100755 --- a/examples/adwords/v201509/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201509/extensions/add_site_links_using_feeds.py @@ -29,7 +29,6 @@ import re import uuid - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201509/migration/migrate_to_extension_settings.py b/examples/adwords/v201509/migration/migrate_to_extension_settings.py index 66a14ce8..89a849e8 100755 --- a/examples/adwords/v201509/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201509/migration/migrate_to_extension_settings.py @@ -30,7 +30,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/migration/upgrade_ad_url.py b/examples/adwords/v201509/migration/upgrade_ad_url.py index 48c6a827..ba94f2b6 100755 --- a/examples/adwords/v201509/migration/upgrade_ad_url.py +++ b/examples/adwords/v201509/migration/upgrade_ad_url.py @@ -23,7 +23,6 @@ """ - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201509/misc/get_all_images_and_videos.py b/examples/adwords/v201509/misc/get_all_images_and_videos.py index ed378a23..ff93a94c 100755 --- a/examples/adwords/v201509/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201509/misc/get_all_images_and_videos.py @@ -26,7 +26,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/misc/upload_image.py b/examples/adwords/v201509/misc/upload_image.py index 4ae9eafc..fd9cd12a 100755 --- a/examples/adwords/v201509/misc/upload_image.py +++ b/examples/adwords/v201509/misc/upload_image.py @@ -27,7 +27,6 @@ import base64 - from googleads import adwords diff --git a/examples/adwords/v201509/misc/upload_media_bundle.py b/examples/adwords/v201509/misc/upload_media_bundle.py index a5dd7752..9c7754f9 100755 --- a/examples/adwords/v201509/misc/upload_media_bundle.py +++ b/examples/adwords/v201509/misc/upload_media_bundle.py @@ -20,7 +20,6 @@ import base64 import urllib2 - from googleads import adwords diff --git a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py index 7e452bb3..ab9bc3fb 100755 --- a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py index 920c307e..4ad9cb18 100755 --- a/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/optimization/get_keyword_ideas.py b/examples/adwords/v201509/optimization/get_keyword_ideas.py index b82a9dc3..fb2f5492 100755 --- a/examples/adwords/v201509/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201509/optimization/get_keyword_ideas.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/remarketing/add_audience.py b/examples/adwords/v201509/remarketing/add_audience.py index 945d4694..0780d450 100755 --- a/examples/adwords/v201509/remarketing/add_audience.py +++ b/examples/adwords/v201509/remarketing/add_audience.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201509/remarketing/add_conversion_tracker.py b/examples/adwords/v201509/remarketing/add_conversion_tracker.py index 2654ff11..adb733af 100755 --- a/examples/adwords/v201509/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201509/remarketing/add_conversion_tracker.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py index 6544d4f3..4e338fd0 100755 --- a/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py @@ -32,7 +32,6 @@ from datetime import date from datetime import datetime from datetime import timedelta - from googleads import adwords diff --git a/examples/adwords/v201509/reporting/download_criteria_report.py b/examples/adwords/v201509/reporting/download_criteria_report.py index dff28760..5702ba94 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report.py +++ b/examples/adwords/v201509/reporting/download_criteria_report.py @@ -28,7 +28,6 @@ import logging import sys - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py index 04a9d480..b43319f8 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py @@ -29,7 +29,6 @@ import logging import StringIO import sys - from googleads import adwords diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py index 6a26daca..1092d2d5 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py @@ -30,7 +30,6 @@ import StringIO import sys - from googleads import adwords diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_string.py b/examples/adwords/v201509/reporting/download_criteria_report_as_string.py index 7bed6696..2bdb2cc9 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_string.py @@ -27,7 +27,6 @@ import logging - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py index b647021c..e2f4e476 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py index 47d536b1..ae40ab08 100755 --- a/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/reporting/get_report_fields.py b/examples/adwords/v201509/reporting/get_report_fields.py index eec9ec5a..d59f4c65 100755 --- a/examples/adwords/v201509/reporting/get_report_fields.py +++ b/examples/adwords/v201509/reporting/get_report_fields.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/shopping/add_product_partition_tree.py b/examples/adwords/v201509/shopping/add_product_partition_tree.py index 3c245206..32b74a0d 100755 --- a/examples/adwords/v201509/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201509/shopping/add_product_partition_tree.py @@ -279,4 +279,3 @@ def DisplayTree(node, children, level=0): adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, ADGROUP_ID) - diff --git a/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py index 9323d659..a51eb83d 100755 --- a/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py index 10bb9d96..723ccd84 100755 --- a/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py index c68df858..277d1e55 100755 --- a/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py index 5692ced2..6878f09f 100755 --- a/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py @@ -23,7 +23,6 @@ """ - from googleads import adwords @@ -46,7 +45,9 @@ def main(client): # Display results. for carrier in carriers: print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) if __name__ == '__main__': diff --git a/examples/adwords/v201509/targeting/lookup_location.py b/examples/adwords/v201509/targeting/lookup_location.py index c49fe69f..d4df2d7c 100755 --- a/examples/adwords/v201509/targeting/lookup_location.py +++ b/examples/adwords/v201509/targeting/lookup_location.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/account_management/create_account.py b/examples/adwords/v201601/account_management/create_account.py index 74255ed4..54aee6ce 100755 --- a/examples/adwords/v201601/account_management/create_account.py +++ b/examples/adwords/v201601/account_management/create_account.py @@ -28,7 +28,6 @@ from datetime import datetime - from googleads import adwords diff --git a/examples/adwords/v201601/account_management/get_account_changes.py b/examples/adwords/v201601/account_management/get_account_changes.py index 0c1e1f28..61f9ef6b 100755 --- a/examples/adwords/v201601/account_management/get_account_changes.py +++ b/examples/adwords/v201601/account_management/get_account_changes.py @@ -25,7 +25,6 @@ import datetime - from googleads import adwords diff --git a/examples/adwords/v201601/account_management/get_account_hierarchy.py b/examples/adwords/v201601/account_management/get_account_hierarchy.py index af319888..8ab21f78 100755 --- a/examples/adwords/v201601/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201601/account_management/get_account_hierarchy.py @@ -22,7 +22,6 @@ section of our README. """ - from googleads import adwords diff --git a/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py index e5c9ca14..73beb48b 100755 --- a/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py index 7e66f33f..733fa7d4 100755 --- a/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py @@ -25,7 +25,6 @@ section of our README. """ - from googleads import adwords diff --git a/examples/adwords/v201601/advanced_operations/add_html5_ad.py b/examples/adwords/v201601/advanced_operations/add_html5_ad.py index 6c8dbdd2..4113a759 100755 --- a/examples/adwords/v201601/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201601/advanced_operations/add_html5_ad.py @@ -28,7 +28,6 @@ import base64 import urllib2 - from googleads import adwords diff --git a/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py index ddfbc339..5d3c4192 100755 --- a/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -23,7 +23,6 @@ """ - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py index e408b17f..51ab7e67 100755 --- a/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py index 8e9373b8..9b916b91 100755 --- a/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py index 12d6c7eb..4302c53f 100755 --- a/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py index 5d4024cd..e7de9fed 100755 --- a/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/add_ad_groups.py b/examples/adwords/v201601/basic_operations/add_ad_groups.py index ce712ed8..9d4848f7 100755 --- a/examples/adwords/v201601/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201601/basic_operations/add_ad_groups.py @@ -27,7 +27,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/add_campaigns.py b/examples/adwords/v201601/basic_operations/add_campaigns.py index 2c398c0b..406d91fb 100755 --- a/examples/adwords/v201601/basic_operations/add_campaigns.py +++ b/examples/adwords/v201601/basic_operations/add_campaigns.py @@ -28,7 +28,6 @@ import datetime import uuid - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/add_keywords.py b/examples/adwords/v201601/basic_operations/add_keywords.py index 44d5f321..ef2d222c 100755 --- a/examples/adwords/v201601/basic_operations/add_keywords.py +++ b/examples/adwords/v201601/basic_operations/add_keywords.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/add_text_ads.py b/examples/adwords/v201601/basic_operations/add_text_ads.py index 7a29859f..198063bc 100755 --- a/examples/adwords/v201601/basic_operations/add_text_ads.py +++ b/examples/adwords/v201601/basic_operations/add_text_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/get_ad_groups.py b/examples/adwords/v201601/basic_operations/get_ad_groups.py index d43eb30e..516d889e 100755 --- a/examples/adwords/v201601/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201601/basic_operations/get_ad_groups.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/get_campaigns.py b/examples/adwords/v201601/basic_operations/get_campaigns.py index a455f19d..0212b784 100755 --- a/examples/adwords/v201601/basic_operations/get_campaigns.py +++ b/examples/adwords/v201601/basic_operations/get_campaigns.py @@ -28,7 +28,6 @@ import logging import time - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py index 68bb3be3..322c9c2e 100755 --- a/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py @@ -27,7 +27,6 @@ import time - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/get_keywords.py b/examples/adwords/v201601/basic_operations/get_keywords.py index 1f9ae5d5..0d13da3b 100755 --- a/examples/adwords/v201601/basic_operations/get_keywords.py +++ b/examples/adwords/v201601/basic_operations/get_keywords.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/get_text_ads.py b/examples/adwords/v201601/basic_operations/get_text_ads.py index 4e9e4b2b..c7001b81 100755 --- a/examples/adwords/v201601/basic_operations/get_text_ads.py +++ b/examples/adwords/v201601/basic_operations/get_text_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/pause_ad.py b/examples/adwords/v201601/basic_operations/pause_ad.py index 1f3e4c63..32b6bd4b 100755 --- a/examples/adwords/v201601/basic_operations/pause_ad.py +++ b/examples/adwords/v201601/basic_operations/pause_ad.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/remove_ad.py b/examples/adwords/v201601/basic_operations/remove_ad.py index 0e8cd7e2..36623500 100755 --- a/examples/adwords/v201601/basic_operations/remove_ad.py +++ b/examples/adwords/v201601/basic_operations/remove_ad.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/remove_ad_group.py b/examples/adwords/v201601/basic_operations/remove_ad_group.py index dc8b8961..47de93fa 100755 --- a/examples/adwords/v201601/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201601/basic_operations/remove_ad_group.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/remove_campaign.py b/examples/adwords/v201601/basic_operations/remove_campaign.py index bbd99e10..75679ed0 100755 --- a/examples/adwords/v201601/basic_operations/remove_campaign.py +++ b/examples/adwords/v201601/basic_operations/remove_campaign.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/remove_keyword.py b/examples/adwords/v201601/basic_operations/remove_keyword.py index 2d627a80..1d8d8c99 100755 --- a/examples/adwords/v201601/basic_operations/remove_keyword.py +++ b/examples/adwords/v201601/basic_operations/remove_keyword.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/update_ad_group.py b/examples/adwords/v201601/basic_operations/update_ad_group.py index a894d396..6a22c2b0 100755 --- a/examples/adwords/v201601/basic_operations/update_ad_group.py +++ b/examples/adwords/v201601/basic_operations/update_ad_group.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/update_campaign.py b/examples/adwords/v201601/basic_operations/update_campaign.py index c34b2b04..ebfc0490 100755 --- a/examples/adwords/v201601/basic_operations/update_campaign.py +++ b/examples/adwords/v201601/basic_operations/update_campaign.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/basic_operations/update_keyword.py b/examples/adwords/v201601/basic_operations/update_keyword.py index cad55b8e..8e473b48 100755 --- a/examples/adwords/v201601/basic_operations/update_keyword.py +++ b/examples/adwords/v201601/basic_operations/update_keyword.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/add_campaign_labels.py b/examples/adwords/v201601/campaign_management/add_campaign_labels.py index 78d075ac..cbcb8251 100755 --- a/examples/adwords/v201601/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201601/campaign_management/add_campaign_labels.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py index 60a149c8..5dae21d8 100755 --- a/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py @@ -26,7 +26,6 @@ import urllib2 import uuid - from googleads import adwords @@ -34,12 +33,12 @@ NUMBER_OF_ADGROUPS_TO_ADD = 2 NUMBER_OF_KEYWORDS_TO_ADD = 5 MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE') +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper() + batch_job_helper = client.GetBatchJobHelper(version='v201601') # Create a BatchJob. batch_job = AddBatchJob(client) @@ -347,7 +346,7 @@ def GetBatchJob(client, batch_job_id): Returns: The BatchJob associated with the given id. """ - batch_job_service = client.GetService('BatchJobService') + batch_job_service = client.GetService('BatchJobService', 'v201601') selector = { 'fields': ['Id', 'Status', 'DownloadUrl'], diff --git a/examples/adwords/v201601/campaign_management/add_experiment.py b/examples/adwords/v201601/campaign_management/add_experiment.py index 04ea5775..13132b6c 100755 --- a/examples/adwords/v201601/campaign_management/add_experiment.py +++ b/examples/adwords/v201601/campaign_management/add_experiment.py @@ -32,7 +32,6 @@ import datetime import uuid - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py index 131369c0..ace90f21 100755 --- a/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py +++ b/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py @@ -27,7 +27,6 @@ import random import re import time - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201601/advanced_operations/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201601/campaign_management/add_keywords_using_incremental_batch_job.py similarity index 78% rename from examples/adwords/v201601/advanced_operations/add_keywords_using_incremental_batch_job.py rename to examples/adwords/v201601/campaign_management/add_keywords_using_incremental_batch_job.py index 70c7fc3b..5a41aea6 100755 --- a/examples/adwords/v201601/advanced_operations/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201601/campaign_management/add_keywords_using_incremental_batch_job.py @@ -26,19 +26,18 @@ import urllib2 import uuid - from googleads import adwords ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' KEYWORD_COUNT = 100 MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE') +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') def main(client, adgroup_id): # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper() + batch_job_helper = client.GetBatchJobHelper(version='v201601') # Create a BatchJob. batch_job = AddBatchJob(client) @@ -123,6 +122,46 @@ def BuildAdGroupCriterionOperations(adgroup_id): return criterion_operations +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201601') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + def GetBatchJob(client, batch_job_id): """Retrieves the BatchJob with the given id. @@ -132,7 +171,7 @@ def GetBatchJob(client, batch_job_id): Returns: The BatchJob associated with the given id. """ - batch_job_service = client.GetService('BatchJobService') + batch_job_service = client.GetService('BatchJobService', 'v201601') selector = { 'fields': ['Id', 'Status', 'DownloadUrl'], @@ -166,6 +205,10 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, have been made. """ batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + poll_attempt = 0 while (poll_attempt in range(max_poll_attempts) and @@ -182,8 +225,10 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' % (batch_job['id'], batch_job['status'], url)) return url - raise Exception('Batch Job with ID "%s" not finished downloading. Try ' - 'checking later.' % batch_job_id) + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) def PrintResponse(batch_job_helper, response_xml): diff --git a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py index 1bd033f0..3d563de4 100755 --- a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py index 113e47cf..b63ad3cb 100755 --- a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py index 8a133533..51ae8e5d 100755 --- a/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py @@ -27,7 +27,6 @@ import time - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/promote_experiment.py b/examples/adwords/v201601/campaign_management/promote_experiment.py index 19f404ac..04e9d7c6 100755 --- a/examples/adwords/v201601/campaign_management/promote_experiment.py +++ b/examples/adwords/v201601/campaign_management/promote_experiment.py @@ -27,7 +27,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/set_ad_parameters.py b/examples/adwords/v201601/campaign_management/set_ad_parameters.py index ca7a1b2b..1a54db8f 100755 --- a/examples/adwords/v201601/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201601/campaign_management/set_ad_parameters.py @@ -26,7 +26,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py index 142d0367..1aca6398 100755 --- a/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py @@ -24,7 +24,6 @@ section of our README. """ - from googleads import adwords diff --git a/examples/adwords/v201601/campaign_management/validate_text_ad.py b/examples/adwords/v201601/campaign_management/validate_text_ad.py index 74bd9e37..25acd193 100755 --- a/examples/adwords/v201601/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201601/campaign_management/validate_text_ad.py @@ -23,7 +23,6 @@ """ - import suds from googleads import adwords diff --git a/examples/adwords/v201601/error_handling/handle_partial_failures.py b/examples/adwords/v201601/error_handling/handle_partial_failures.py index 60e96913..de348a93 100755 --- a/examples/adwords/v201601/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201601/error_handling/handle_partial_failures.py @@ -27,7 +27,6 @@ import re - from googleads import adwords diff --git a/examples/adwords/v201601/error_handling/handle_policy_violation_error.py b/examples/adwords/v201601/error_handling/handle_policy_violation_error.py index 7dcaf20a..b4d1f7a6 100755 --- a/examples/adwords/v201601/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201601/error_handling/handle_policy_violation_error.py @@ -27,7 +27,6 @@ import re - import suds from googleads import adwords diff --git a/examples/adwords/v201601/extensions/add_site_links.py b/examples/adwords/v201601/extensions/add_site_links.py index ffd6d5ee..2f8d7f89 100755 --- a/examples/adwords/v201601/extensions/add_site_links.py +++ b/examples/adwords/v201601/extensions/add_site_links.py @@ -26,7 +26,6 @@ from datetime import datetime - from googleads import adwords from googleads import errors from pytz import timezone diff --git a/examples/adwords/v201601/extensions/add_site_links_using_feeds.py b/examples/adwords/v201601/extensions/add_site_links_using_feeds.py index 67adb6ec..a27c550f 100755 --- a/examples/adwords/v201601/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201601/extensions/add_site_links_using_feeds.py @@ -29,7 +29,6 @@ import re import uuid - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201601/migration/migrate_to_extension_settings.py b/examples/adwords/v201601/migration/migrate_to_extension_settings.py index 94aa1614..0e46c6f1 100755 --- a/examples/adwords/v201601/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201601/migration/migrate_to_extension_settings.py @@ -30,7 +30,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/migration/upgrade_ad_url.py b/examples/adwords/v201601/migration/upgrade_ad_url.py index 46c465cb..22fd74e7 100755 --- a/examples/adwords/v201601/migration/upgrade_ad_url.py +++ b/examples/adwords/v201601/migration/upgrade_ad_url.py @@ -23,7 +23,6 @@ """ - from googleads import adwords from googleads import errors diff --git a/examples/adwords/v201601/misc/get_all_images_and_videos.py b/examples/adwords/v201601/misc/get_all_images_and_videos.py index 76c47961..404c1822 100755 --- a/examples/adwords/v201601/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201601/misc/get_all_images_and_videos.py @@ -26,7 +26,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/misc/upload_image.py b/examples/adwords/v201601/misc/upload_image.py index d0ef6e5c..ad0d2684 100755 --- a/examples/adwords/v201601/misc/upload_image.py +++ b/examples/adwords/v201601/misc/upload_image.py @@ -27,7 +27,6 @@ import base64 - from googleads import adwords diff --git a/examples/adwords/v201601/misc/upload_media_bundle.py b/examples/adwords/v201601/misc/upload_media_bundle.py index 3a180119..8816b544 100755 --- a/examples/adwords/v201601/misc/upload_media_bundle.py +++ b/examples/adwords/v201601/misc/upload_media_bundle.py @@ -20,7 +20,6 @@ import base64 import urllib2 - from googleads import adwords diff --git a/examples/adwords/v201601/optimization/estimate_keyword_traffic.py b/examples/adwords/v201601/optimization/estimate_keyword_traffic.py index bb71c08d..cbb5e01f 100755 --- a/examples/adwords/v201601/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201601/optimization/estimate_keyword_traffic.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py index ee8fb345..c7690c23 100755 --- a/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/optimization/get_keyword_ideas.py b/examples/adwords/v201601/optimization/get_keyword_ideas.py index ef51b4b9..a6b590d2 100755 --- a/examples/adwords/v201601/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201601/optimization/get_keyword_ideas.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/remarketing/add_audience.py b/examples/adwords/v201601/remarketing/add_audience.py index 5428cab0..11b032f1 100755 --- a/examples/adwords/v201601/remarketing/add_audience.py +++ b/examples/adwords/v201601/remarketing/add_audience.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201601/remarketing/add_conversion_tracker.py b/examples/adwords/v201601/remarketing/add_conversion_tracker.py index 6b0322a4..a5db7153 100755 --- a/examples/adwords/v201601/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201601/remarketing/add_conversion_tracker.py @@ -25,7 +25,6 @@ import uuid - from googleads import adwords diff --git a/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py index 75c6423c..8783417b 100755 --- a/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py @@ -32,7 +32,6 @@ from datetime import date from datetime import datetime from datetime import timedelta - from googleads import adwords diff --git a/examples/adwords/v201601/remarketing/upload_offline_conversions.py b/examples/adwords/v201601/remarketing/upload_offline_conversions.py index dc51ce2b..190295b1 100755 --- a/examples/adwords/v201601/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201601/remarketing/upload_offline_conversions.py @@ -26,7 +26,6 @@ """ - from googleads import adwords # Name of the conversion tracker to upload to. diff --git a/examples/adwords/v201601/reporting/download_criteria_report.py b/examples/adwords/v201601/reporting/download_criteria_report.py index 280899ac..61d018e8 100755 --- a/examples/adwords/v201601/reporting/download_criteria_report.py +++ b/examples/adwords/v201601/reporting/download_criteria_report.py @@ -28,7 +28,6 @@ import logging import sys - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py index fc6f98b6..d2a6ab14 100755 --- a/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py @@ -29,7 +29,6 @@ import logging import StringIO import sys - from googleads import adwords diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py index 740793bb..8545b4cc 100755 --- a/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py @@ -30,7 +30,6 @@ import StringIO import sys - from googleads import adwords diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_string.py b/examples/adwords/v201601/reporting/download_criteria_report_as_string.py index eaee4236..2889911b 100755 --- a/examples/adwords/v201601/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201601/reporting/download_criteria_report_as_string.py @@ -27,7 +27,6 @@ import logging - from googleads import adwords logging.basicConfig(level=logging.INFO) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py index f2454324..33881398 100755 --- a/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py index 5b551e19..7985bff7 100755 --- a/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/reporting/get_report_fields.py b/examples/adwords/v201601/reporting/get_report_fields.py index b89dc8e1..50edd0e1 100755 --- a/examples/adwords/v201601/reporting/get_report_fields.py +++ b/examples/adwords/v201601/reporting/get_report_fields.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/shopping/add_product_partition_tree.py b/examples/adwords/v201601/shopping/add_product_partition_tree.py index beb5b452..7247ba12 100755 --- a/examples/adwords/v201601/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201601/shopping/add_product_partition_tree.py @@ -279,4 +279,3 @@ def DisplayTree(node, children, level=0): adwords_client = adwords.AdWordsClient.LoadFromStorage() main(adwords_client, ADGROUP_ID) - diff --git a/examples/adwords/v201601/shopping/add_shopping_campaign.py b/examples/adwords/v201601/shopping/add_shopping_campaign.py index 24088044..7b93a2fb 100755 --- a/examples/adwords/v201601/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201601/shopping/add_shopping_campaign.py @@ -43,7 +43,7 @@ def main(client, budget_id, merchant_id): 'name': 'Shopping campaign #%s' % uuid.uuid4(), # The advertisingChannelType is what makes this a shopping campaign 'advertisingChannelType': 'SHOPPING', - # Set shared budget (required) + # Set portfolio budget (required) 'budget': { 'budgetId': budget_id }, diff --git a/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py index 805bc7b4..9ff418f9 100755 --- a/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py index 54b0f435..dcb27348 100755 --- a/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py index fec63a1a..e2cccbcf 100755 --- a/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py @@ -25,7 +25,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py index 903b9360..a81d7d77 100755 --- a/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py @@ -23,7 +23,6 @@ """ - from googleads import adwords @@ -46,7 +45,9 @@ def main(client): # Display results. for carrier in carriers: print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) if __name__ == '__main__': diff --git a/examples/adwords/v201601/targeting/lookup_location.py b/examples/adwords/v201601/targeting/lookup_location.py index 049fffd9..ae34e59b 100755 --- a/examples/adwords/v201601/targeting/lookup_location.py +++ b/examples/adwords/v201601/targeting/lookup_location.py @@ -23,7 +23,6 @@ """ - from googleads import adwords diff --git a/examples/adwords/v201603/__init__.py b/examples/adwords/v201603/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201603/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201603/account_management/__init__.py b/examples/adwords/v201603/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201603/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201603/account_management/create_account.py b/examples/adwords/v201603/account_management/create_account.py new file mode 100755 index 00000000..251bf45c --- /dev/null +++ b/examples/adwords/v201603/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201603') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/account_management/get_account_changes.py b/examples/adwords/v201603/account_management/get_account_changes.py new file mode 100755 index 00000000..ec9c4676 --- /dev/null +++ b/examples/adwords/v201603/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201603') + campaign_service = client.GetService('CampaignService', version='v201603') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/account_management/get_account_hierarchy.py b/examples/adwords/v201603/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..6155aec0 --- /dev/null +++ b/examples/adwords/v201603/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201603') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/advanced_operations/__init__.py b/examples/adwords/v201603/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201603/advanced_operations/add_ad_customizer.py b/examples/adwords/v201603/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..4f5a84f9 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/add_ad_customizer.py @@ -0,0 +1,222 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates TextAds that use ad customizations for the specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add TextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no TextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService') + + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'description1': 'Only {=%s.Price}' % feed_name, + 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com' + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201603/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201603/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..7988ab5f --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201603') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..97605a74 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,108 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad to ad group ID \'%s\' ' + 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/advanced_operations/add_html5_ad.py b/examples/adwords/v201603/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..5bd82d84 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/add_html5_ad.py @@ -0,0 +1,111 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201603/advanced_operations/add_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..4f3dce96 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -0,0 +1,111 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a text add that uses advanced features of upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Create the text ad + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print ('AdGroupAd with ID %s and display URL \'%s\'was added.' + % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201603/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201603/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..06343667 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201603') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201603') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201603') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201603/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..a51297f1 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201603') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201603') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201603/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..74081091 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201603') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201603/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..5a939e60 --- /dev/null +++ b/examples/adwords/v201603/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201603') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201603') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201603') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201603/basic_operations/__init__.py b/examples/adwords/v201603/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201603/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201603/basic_operations/add_ad_groups.py b/examples/adwords/v201603/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..53e56f42 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201603') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/basic_operations/add_campaigns.py b/examples/adwords/v201603/basic_operations/add_campaigns.py new file mode 100755 index 00000000..57d23cf7 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/add_campaigns.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201603') + budget_service = client.GetService('BudgetService', version='v201603') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/basic_operations/add_keywords.py b/examples/adwords/v201603/basic_operations/add_keywords.py new file mode 100755 index 00000000..cebf5506 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201603') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/add_text_ads.py b/examples/adwords/v201603/basic_operations/add_text_ads.py new file mode 100755 index 00000000..76e0e093 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/add_text_ads.py @@ -0,0 +1,93 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds several text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Construct operations and add ads. + # If needed, you could specify an exemption request here, e.g.: + # 'exemptionRequests': [{ + # # This comes back in a PolicyViolationError. + # 'key' { + # 'policyName': '...', + # 'violatingText': '...' + # } + # }] + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + }, + # Optional fields. + 'status': 'PAUSED' + } + }, + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Enjoy your stay at Red Planet.', + 'description2': 'Buy your tickets now!', + 'headline': 'Luxury Cruise to Mars' + } + } + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad with id \'%s\' and of type \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/get_ad_groups.py b/examples/adwords/v201603/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..a675c9fa --- /dev/null +++ b/examples/adwords/v201603/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201603') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/basic_operations/get_campaigns.py b/examples/adwords/v201603/basic_operations/get_campaigns.py new file mode 100755 index 00000000..e6509124 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/get_campaigns.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201603') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201603/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..51be081e --- /dev/null +++ b/examples/adwords/v201603/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201603') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/basic_operations/get_keywords.py b/examples/adwords/v201603/basic_operations/get_keywords.py new file mode 100755 index 00000000..6548e2c5 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201603') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\' was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/get_text_ads.py b/examples/adwords/v201603/basic_operations/get_text_ads.py new file mode 100755 index 00000000..628888d2 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/get_text_ads.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2016 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 text ads for a given ad group. + +To add an ad, run add_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/pause_ad.py b/examples/adwords/v201603/basic_operations/pause_ad.py new file mode 100755 index 00000000..ee7e9ca1 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201603/basic_operations/remove_ad.py b/examples/adwords/v201603/basic_operations/remove_ad.py new file mode 100755 index 00000000..3f7e6c6c --- /dev/null +++ b/examples/adwords/v201603/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201603/basic_operations/remove_ad_group.py b/examples/adwords/v201603/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..3f3c788d --- /dev/null +++ b/examples/adwords/v201603/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201603') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/remove_campaign.py b/examples/adwords/v201603/basic_operations/remove_campaign.py new file mode 100755 index 00000000..fecfc26e --- /dev/null +++ b/examples/adwords/v201603/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201603') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/basic_operations/remove_keyword.py b/examples/adwords/v201603/basic_operations/remove_keyword.py new file mode 100755 index 00000000..bf0cce96 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201603') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201603/basic_operations/update_ad_group.py b/examples/adwords/v201603/basic_operations/update_ad_group.py new file mode 100755 index 00000000..f01d759b --- /dev/null +++ b/examples/adwords/v201603/basic_operations/update_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201603') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/update_campaign.py b/examples/adwords/v201603/basic_operations/update_campaign.py new file mode 100755 index 00000000..fe266424 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201603') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/basic_operations/update_keyword.py b/examples/adwords/v201603/basic_operations/update_keyword.py new file mode 100755 index 00000000..83908c54 --- /dev/null +++ b/examples/adwords/v201603/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201603') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201603/campaign_management/__init__.py b/examples/adwords/v201603/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201603/campaign_management/add_campaign_labels.py b/examples/adwords/v201603/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..0d1b37b0 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201603') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201603/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201603/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..cff2a8a1 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,426 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201603') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201603') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding a TextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new TextAd for each of + the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201603') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201603/campaign_management/add_draft.py b/examples/adwords/v201603/campaign_management/add_draft.py new file mode 100755 index 00000000..db08175f --- /dev/null +++ b/examples/adwords/v201603/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + # Initialize appropriate services. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201603') + draft_service = client.GetService('DraftService', version='v201603') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201603/campaign_management/add_experiment.py b/examples/adwords/v201603/campaign_management/add_experiment.py new file mode 100755 index 00000000..4f90ae9c --- /dev/null +++ b/examples/adwords/v201603/campaign_management/add_experiment.py @@ -0,0 +1,127 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates an experiment. + +The created experiment is using a query percentage of 10, which defines what +fraction of auctions should go to the control split (90%) vs. the experiment +split (10%), then adds experimental bid changes for an ad group, and adds an +experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad +groups, run get_ad_groups.py. To get keywords, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, campaign_id, ad_group_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201603') + ad_group_service = client.GetService('AdGroupService', version='v201603') + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201603') + + # Construct operations and add experiment. + tomorrow = datetime.datetime.now() + datetime.timedelta(1) + thirty_days = datetime.datetime.now() + datetime.timedelta(30) + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), + 'queryPercentage': '10', + 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), + # Optional fields. + 'status': 'ENABLED', + 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was added.' + % (experiment['name'], experiment['id'])) + + # Construct operations and update ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'experimentData': { + 'xsi_type': 'AdGroupExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'MODIFIED', + 'experimentBidMultipliers': { + 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', + 'maxCpcMultiplier': { + 'multiplier': '0.5' + } + } + } + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' + 'experiment.' % (ad_group['name'], ad_group['id'])) + + # Construct operations and add ad group crierion. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + }, + 'experimentData': { + 'xsi_type': 'BiddableAdGroupCriterionExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'EXPERIMENT_ONLY' + } + } + }] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\' and criterion ' + 'id \'%s\' was added to the experiment.' + % (criterion['adGroupId'], criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201603/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201603/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..f1e093d4 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,259 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201603') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201603') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201603') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201603') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201603/campaign_management/add_trial.py b/examples/adwords/v201603/campaign_management/add_trial.py new file mode 100755 index 00000000..2666dbaa --- /dev/null +++ b/examples/adwords/v201603/campaign_management/add_trial.py @@ -0,0 +1,117 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201603') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201603') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201603/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201603/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..0f9597be --- /dev/null +++ b/examples/adwords/v201603/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Construct selector and get all ads for a given ad group. + selector = { + 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'AdGroupCreativeApprovalStatus', + 'operator': 'IN', + 'values': ['DISAPPROVED'] + } + ] + } + ads = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201603/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..720fac6f --- /dev/null +++ b/examples/adwords/v201603/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, AdGroupAdDisapprovalReasons ' + 'WHERE CampaignId = %s AND ' + 'AdGroupCreativeApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % campaign_id) + ads = ad_group_ad_service.query(query) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201603/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..e6d997e4 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201603') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201603/campaign_management/graduate_trial.py b/examples/adwords/v201603/campaign_management/graduate_trial.py new file mode 100755 index 00000000..3a0824f8 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201603') + budget_service = client.GetService('BudgetService', version='v201603') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201603/campaign_management/promote_experiment.py b/examples/adwords/v201603/campaign_management/promote_experiment.py new file mode 100755 index 00000000..cc5a6db5 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/promote_experiment.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2016 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 promotes an experiment. + +Promoting an experiment permanently applies all the experimental changes made to +its related ad groups, criteria and ads. To add an experiment, run +add_experiment.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' + + +def main(client, experiment_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201603') + + # Construct operations and promote experiment. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': experiment_id, + 'status': 'PROMOTED' + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was promoted.' + % (experiment['name'], experiment['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201603/campaign_management/set_ad_parameters.py b/examples/adwords/v201603/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..133d9b81 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + ad_param_service = client.GetService('AdParamService', version='v201603') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201603/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201603/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..63ce1d23 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201603') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201603/campaign_management/validate_text_ad.py b/examples/adwords/v201603/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..ef271911 --- /dev/null +++ b/examples/adwords/v201603/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Construct operations to add a text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'url': 'http://www.example.com', + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for all astronauts in orbit', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/error_handling/__init__.py b/examples/adwords/v201603/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201603/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201603/error_handling/handle_partial_failures.py b/examples/adwords/v201603/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..01a7a462 --- /dev/null +++ b/examples/adwords/v201603/error_handling/handle_partial_failures.py @@ -0,0 +1,120 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201603') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) + if index: + print ('Keyword ad group criterion with ad group id \'%s\' and text ' + '\'%s\' triggered a failure for the following reason: \'%s\'.' + % (keywords[int(index[0])]['adGroupId'], + keywords[int(index[0])]['criterion']['text'], + error['errorString'])) + else: + print 'The following failure has occurred: \'%s\'.' % error['errorString'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/error_handling/handle_policy_violation_error.py b/examples/adwords/v201603/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..9d3ecdaa --- /dev/null +++ b/examples/adwords/v201603/error_handling/handle_policy_violation_error.py @@ -0,0 +1,114 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201603') + + # Create text ad. + text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'TextAd', + 'headline': 'Mars Cruise!!!', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com', + } + } + } + + operations = [text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + if error['ApiError.Type'] == 'PolicyViolationError': + operation_index = re.findall(r'operations\[(.*)\]\.', + error['fieldPath']) + if operation_index: + operation = operations[int(operation_index[0])] + print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % + (operation['operand']['ad']['headline'], + 'exemptable' if error['isExemptable'] else 'non-exemptable', + error['externalPolicyName'])) + if error['isExemptable'].lower() == 'true': + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text ' + '\'%s\'.' % + (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({ + 'key': error['key'] + }) + else: + # Remove non-exemptable operation + print 'Removing the operation from the request.' + operations.delete(operation) + else: + # Non-policy error returned, re-throw exception. + raise e + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/extensions/__init__.py b/examples/adwords/v201603/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201603/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201603/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201603/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..3414e5b8 --- /dev/null +++ b/examples/adwords/v201603/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201603').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201603') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201603/extensions/add_site_links.py b/examples/adwords/v201603/extensions/add_site_links.py new file mode 100755 index 00000000..5f9fb083 --- /dev/null +++ b/examples/adwords/v201603/extensions/add_site_links.py @@ -0,0 +1,134 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201603') + customer_service = client.GetService('CustomerService', version='v201603') + + customer_tz = timezone(customer_service.get()['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840} + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/extensions/add_site_links_using_feeds.py b/examples/adwords/v201603/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..05135612 --- /dev/null +++ b/examples/adwords/v201603/extensions/add_site_links_using_feeds.py @@ -0,0 +1,233 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_1_TEXT = '3' +PLACEHOLDER_FIELD_LINE_2_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201603') + feed_item_service = client.GetService('FeedItemService', version='v201603') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201603') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201603') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 1 Description'}, + {'type': 'STRING', 'name': 'Line 2 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_1_feed_attribute_id = feed['attributes'][2]['id'] + line_2_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % + (line_1_feed_attribute_id, line_2_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line1FeedId'] = line_1_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line1': 'Home line 1', 'line2': 'Home line 2'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line1': 'Support line 1', 'line2': 'Support line 2'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line1': 'Products line 1', 'line2': 'Products line 2'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'stringValue': item['line1'] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/migration/__init__.py b/examples/adwords/v201603/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201603/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201603/migration/migrate_to_extension_settings.py b/examples/adwords/v201603/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..534fde73 --- /dev/null +++ b/examples/adwords/v201603/migration/migrate_to_extension_settings.py @@ -0,0 +1,527 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201603') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201603') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201603') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201603') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201603') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201603') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201603') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/migration/upgrade_ad_url.py b/examples/adwords/v201603/migration/upgrade_ad_url.py new file mode 100755 index 00000000..642b3e1b --- /dev/null +++ b/examples/adwords/v201603/migration/upgrade_ad_url.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2016 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 upgrades an ad to use upgraded URLs. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, adgroup_id, ad_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201603') + + selector = { + 'fields': ['Id', 'Url'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [ad_id] + } + ] + } + + page = adgroup_ad_service.get(selector) + + adgroup_ad = page['entries'][0] if page['entries'] else None + + if not adgroup_ad: + raise errors.GoogleAdsError('Ad not found.') + + ad_url_upgrade = { + 'adId': adgroup_ad['ad']['id'], + 'finalUrl': adgroup_ad['ad']['url'] + } + + adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] + + if adgroup_ad: + print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' + % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201603/misc/__init__.py b/examples/adwords/v201603/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201603/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201603/misc/get_all_images_and_videos.py b/examples/adwords/v201603/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..39248f5c --- /dev/null +++ b/examples/adwords/v201603/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201603') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/misc/upload_image.py b/examples/adwords/v201603/misc/upload_image.py new file mode 100755 index 00000000..09adbae1 --- /dev/null +++ b/examples/adwords/v201603/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201603') + + with open(image_filename, 'r') as image_handle: + image_data = base64.encodestring(image_handle.read()) + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201603/misc/upload_media_bundle.py b/examples/adwords/v201603/misc/upload_media_bundle.py new file mode 100755 index 00000000..0712e63a --- /dev/null +++ b/examples/adwords/v201603/misc/upload_media_bundle.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201603') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/optimization/__init__.py b/examples/adwords/v201603/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201603/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201603/optimization/estimate_keyword_traffic.py b/examples/adwords/v201603/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..4516e6f4 --- /dev/null +++ b/examples/adwords/v201603/optimization/estimate_keyword_traffic.py @@ -0,0 +1,132 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201603') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + selector = { + 'campaignEstimateRequests': [{ + 'adGroupEstimateRequests': [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }], + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ] + }] + } + estimates = traffic_estimator_service.get(selector) + + # Display results. + ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] + keyword_estimates = ad_group_estimate['keywordEstimates'] + for index in xrange(len(keyword_estimates)): + keyword = keyword_estimate_requests[index]['keyword'] + estimate = keyword_estimates[index] + if keyword_estimate_requests[index].get('isNegative', False): + continue + + # Find the mean of the min and max values. + mean_avg_cpc = (calc_mean(estimate['min']['averageCpc']['microAmount'], + estimate['max']['averageCpc']['microAmount']) + if 'averageCpc' in estimate['min'] else 'N/A') + mean_avg_pos = calc_mean(estimate['min']['averagePosition'], + estimate['max']['averagePosition']) + mean_clicks = calc_mean(estimate['min']['clicksPerDay'], + estimate['max']['clicksPerDay']) + mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], + estimate['max']['totalCost']['microAmount']) + + print ('Results for the keyword with text \'%s\' and match type \'%s\':' + % (keyword['text'], keyword['matchType'])) + print ' Estimated average CPC: %s' % mean_avg_cpc + print ' Estimated ad position: %s' % mean_avg_pos + print ' Estimated daily clicks: %s' % mean_clicks + print ' Estimated daily cost: %s' % mean_total_cost + + +def fmt_mean(mean): + if mean: + return '%.2f' % mean + else: + return None + + +def calc_mean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201603/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..e44d730b --- /dev/null +++ b/examples/adwords/v201603/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201603') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201603/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..bd12884f --- /dev/null +++ b/examples/adwords/v201603/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201603') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201603/optimization/get_keyword_ideas.py b/examples/adwords/v201603/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..e1404548 --- /dev/null +++ b/examples/adwords/v201603/optimization/get_keyword_ideas.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201603') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }, + { + # Network search parameter (optional) + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/remarketing/__init__.py b/examples/adwords/v201603/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201603/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201603/remarketing/add_audience.py b/examples/adwords/v201603/remarketing/add_audience.py new file mode 100755 index 00000000..f49746ec --- /dev/null +++ b/examples/adwords/v201603/remarketing/add_audience.py @@ -0,0 +1,103 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201603') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201603') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/remarketing/add_conversion_tracker.py b/examples/adwords/v201603/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..f273c0b7 --- /dev/null +++ b/examples/adwords/v201603/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201603') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/remarketing/add_crm_based_user_list.py b/examples/adwords/v201603/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..181ee4e2 --- /dev/null +++ b/examples/adwords/v201603/remarketing/add_crm_based_user_list.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a remarketing user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client, emails): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201603') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180 + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + hashed_emails = HashEmails(emails) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'dataType': 'EMAIL_SHA256', + 'members': hashed_emails + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def HashEmails(emails): + """Hashes the given emails using SHA-256. + + Note: Emails are stripped of any whitespace and set to lowercase before + hashing. + + Args: + emails: list of str emails to be hashed. + + Returns: + A list of SHA-256 hashed emails. + """ + return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + + +if __name__ == '__main__': + EMAILS = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, EMAILS) diff --git a/examples/adwords/v201603/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201603/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..78185eb9 --- /dev/null +++ b/examples/adwords/v201603/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,183 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201603') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords will logically OR the + # groups together. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/remarketing/upload_offline_conversions.py b/examples/adwords/v201603/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..2b9d1e9e --- /dev/null +++ b/examples/adwords/v201603/remarketing/upload_offline_conversions.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201603') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201603/reporting/__init__.py b/examples/adwords/v201603/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201603/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201603/reporting/download_criteria_report.py b/examples/adwords/v201603/reporting/download_criteria_report.py new file mode 100755 index 00000000..9ec69a35 --- /dev/null +++ b/examples/adwords/v201603/reporting/download_criteria_report.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201603') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201603/reporting/download_criteria_report_as_stream.py new file mode 100755 index 00000000..64b6bf0e --- /dev/null +++ b/examples/adwords/v201603/reporting/download_criteria_report_as_stream.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201603') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201603/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..6ba9579d --- /dev/null +++ b/examples/adwords/v201603/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201603') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_as_string.py b/examples/adwords/v201603/reporting/download_criteria_report_as_string.py new file mode 100755 index 00000000..87d8da98 --- /dev/null +++ b/examples/adwords/v201603/reporting/download_criteria_report_as_string.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201603') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201603/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..605d5523 --- /dev/null +++ b/examples/adwords/v201603/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201603') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201603/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..eeb6ff62 --- /dev/null +++ b/examples/adwords/v201603/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client, path): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201603') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + with open(path, 'w') as output_file: + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', output_file, skip_report_header=False, + skip_column_header=False, skip_report_summary=False) + + print 'Report was downloaded to \'%s\'.' % path + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, PATH) diff --git a/examples/adwords/v201603/reporting/get_report_fields.py b/examples/adwords/v201603/reporting/get_report_fields.py new file mode 100755 index 00000000..55e96959 --- /dev/null +++ b/examples/adwords/v201603/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201603') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201603/shopping/__init__.py b/examples/adwords/v201603/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201603/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201603/shopping/add_product_partition_tree.py b/examples/adwords/v201603/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..e3954d94 --- /dev/null +++ b/examples/adwords/v201603/shopping/add_product_partition_tree.py @@ -0,0 +1,281 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201603') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201603/shopping/add_product_scope.py b/examples/adwords/v201603/shopping/add_product_scope.py new file mode 100755 index 00000000..822e6e57 --- /dev/null +++ b/examples/adwords/v201603/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201603') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/shopping/add_shopping_campaign.py b/examples/adwords/v201603/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..fe99b26c --- /dev/null +++ b/examples/adwords/v201603/shopping/add_shopping_campaign.py @@ -0,0 +1,121 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id): + campaign_service = client.GetService('CampaignService', version='v201603') + ad_group_service = client.GetService('AdGroupService', version='v201603') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + adgroup = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group_result = ad_group_service.mutate(adgroup_operations) + + for adgroup in ad_group_result['value']: + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (adgroup['name'], adgroup['id'])) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': adgroup['id'], + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201603/shopping/get_product_category_taxonomy.py b/examples/adwords/v201603/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..241eea4e --- /dev/null +++ b/examples/adwords/v201603/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201603') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/targeting/__init__.py b/examples/adwords/v201603/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201603/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201603/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201603/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..48c62a68 --- /dev/null +++ b/examples/adwords/v201603/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,161 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201603') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create location groups. The IDs can be found in the documentation or + # retrieved with the LocationCriterionService. + florida_tier3 = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'IncomeOperand', + # Tiers are numbered 1-10, and represent 10% segments of earners. + # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. + # Tiers 6 through 10 are grouped into TIER_6_TO_10. + 'tier': 'TIER_3' + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + }, + } + florida_downtown = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'PlacesOfInterestOperand', + # Other valid options: AIRPORT, UNIVERSITY. + 'category': 'DOWNTOWN', + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + } + } + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish, florida_tier3, + florida_downtown] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201603/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201603/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..0aa66873 --- /dev/null +++ b/examples/adwords/v201603/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201603') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201603/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..58f5c627 --- /dev/null +++ b/examples/adwords/v201603/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201603') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201603/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..1244517e --- /dev/null +++ b/examples/adwords/v201603/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201603') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201603/targeting/lookup_location.py b/examples/adwords/v201603/targeting/lookup_location.py new file mode 100755 index 00000000..40216270 --- /dev/null +++ b/examples/adwords/v201603/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201603') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/dfp/authentication/create_dfp_client_with_service_account.py index 264c4edc..3f7dcc2f 100755 --- a/examples/dfp/authentication/create_dfp_client_with_service_account.py +++ b/examples/dfp/authentication/create_dfp_client_with_service_account.py @@ -20,7 +20,7 @@ from googleads import dfp from googleads import oauth2 -# OAuth 2.0 credential information. In a real application, you'd probably be +# OAuth2 credential information. In a real application, you'd probably be # pulling these values from a credential storage. SERVICE_ACCOUNT_EMAIL = 'INSERT_SERVICE_ACCOUNT_EMAIL' KEY_FILE = 'INSERT_KEY_FILE_PATH' diff --git a/examples/dfp/authentication/create_dfp_client_without_yaml.py b/examples/dfp/authentication/create_dfp_client_without_yaml.py index 8d57e16d..9b15b3ca 100755 --- a/examples/dfp/authentication/create_dfp_client_without_yaml.py +++ b/examples/dfp/authentication/create_dfp_client_without_yaml.py @@ -18,7 +18,7 @@ While our LoadFromStorage method provides a useful shortcut to instantiate a client if you regularly use just one set of credentials, production applications -may need to swap out users. This example shows you how to create an OAuth 2.0 +may need to swap out users. This example shows you how to create an OAuth2 client and a DfpClient without relying on a yaml file. """ @@ -26,7 +26,7 @@ from googleads import dfp from googleads import oauth2 -# OAuth 2.0 credential information. In a real application, you'd probably be +# OAuth2 credential information. In a real application, you'd probably be # pulling these values from a credential storage. CLIENT_ID = 'INSERT_CLIENT_ID_HERE' CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py index 5d927606..d725022e 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/dfp/authentication/generate_refresh_token.py @@ -22,12 +22,12 @@ from oauth2client import client -# Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet, +# Your OAuth2 Client ID and Secret. If you do not have an ID and Secret yet, # please go to https://console.developers.google.com and create a set. DEFAULT_CLIENT_ID = None DEFAULT_CLIENT_SECRET = None -# The DFP API OAuth 2.0 scope. +# The DFP API OAuth2 scope. SCOPE = u'https://www.googleapis.com/auth/dfp' parser = argparse.ArgumentParser(description='Generates a refresh token with ' @@ -64,7 +64,7 @@ def main(client_id, client_secret, scopes): print 'Authentication has failed: %s' % e sys.exit(1) else: - print ('OAuth 2.0 authorization successful!\n\n' + print ('OAuth2 authorization successful!\n\n' 'Your access token is:\n %s\n\nYour refresh token is:\n %s' % (credential.access_token, credential.refresh_token)) diff --git a/googleads.yaml b/googleads.yaml index 9ff40109..3358bb82 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -12,7 +12,7 @@ adwords: # partial_failure: True # validate_only: True ############################################################################# - # OAuth 2.0 Configuration # + # OAuth2 Configuration # # Below you may provide credentials for either the installed application or # # service account flows. Remove or comment the lines for the flow you're # # not using. # @@ -37,7 +37,7 @@ dfp: # unless the network code is set directly on the DfpClient object: # network_code: INSERT_NETWORK_CODE_HERE ############################################################################# - # OAuth 2.0 Configuration # + # OAuth2 Configuration # # Below you may provide credentials for either the installed application or # # service account flows. Remove or comment the lines for the flow you're # # not using. # diff --git a/googleads/adwords.py b/googleads/adwords.py index d6b25532..84acf159 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -164,6 +164,52 @@ 'BiddingStrategyService': 'cm', 'AdwordsUserListService': 'rm', 'LabelService': 'cm', + }, + 'v201603': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'CustomerFeedService': 'cm', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'ExperimentService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } @@ -225,7 +271,7 @@ def LoadFromStorage(cls, path=None): Raises: A GoogleAdsValueError if the given yaml file does not contain the information necessary to instantiate a client object - either a - required key was missing or an OAuth 2.0 key was missing. + required key was missing or an OAuth2 key was missing. """ if path is None: path = os.path.join(os.path.expanduser('~'), 'googleads.yaml') @@ -523,7 +569,7 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): 'mutate'), ('AdGroupCriterionOperation', 'AdGroupCriterionService', 'mutate'), - ('AdGroupCriterionLabelOperation', 'AdGroupCriterionServce', + ('AdGroupCriterionLabelOperation', 'AdGroupCriterionService', 'mutateLabel'), ('AdGroupOperation', 'AdGroupService', 'mutate'), ('AdGroupLabelOperation', 'AdGroupService', 'mutateLabel'), @@ -649,10 +695,11 @@ def _ExtractOperations(self, full_soap_xml): operations. This ordinarily happens if no xsi_type is specified for the operations. """ - # Extract mutate element from XML, this contains the operations. - mutate = self._GetRawOperationsFromXML(full_soap_xml) + # Extract method element (e.g. mutate, mutateLabel, etc...) from XML, this + # contains the operations. + method = self._GetRawOperationsFromXML(full_soap_xml) # Ensure operations are formatted correctly for BatchJobService. - for operations in mutate: + for operations in method: self._FormatForBatchJobService(operations) # Extract the operation type, ensure xsi:type is set for # BatchJobService. Even if xsi_type is set earlier, suds will end up @@ -662,8 +709,8 @@ def _ExtractOperations(self, full_soap_xml): raise googleads.errors.GoogleAdsValueError('No xsi_type specified ' 'for the operations.') operations.attrib['xsi:type'] = operation_type.text - operations_xml = ''.join([ElementTree.tostring(operations) - for operations in mutate]) + operations_xml = ''.join([ElementTree.tostring(operation) + for operation in method]) # Force removal of this line, which suds produces. operations_xml = operations_xml.replace( 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"', '') @@ -759,15 +806,15 @@ def _GetRawOperationsFromXML(self, raw_request_xml): suds. Returns: - An unmodified mutate Element containing the operations from the raw - request xml. + An unmodified Element containing the operations from the raw request + xml. Raises: AttributeError: if the provided XML isn't from AdWords. """ root = ElementTree.fromstring(raw_request_xml.encode('utf-8')) return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( - '%smutate' % self._adwords_namespace) + './/') def __init__(self, request_builder, response_parser, version=sorted(_SERVICE_MAP.keys())[-1]): diff --git a/googleads/common.py b/googleads/common.py index faa929d7..78ff9ecd 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -28,13 +28,13 @@ import googleads.oauth2 import googleads.patches -VERSION = '3.13.0' +VERSION = '3.14.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) -# The keys in the authentication dictionary that are used to construct OAuth 2.0 +# The keys in the authentication dictionary that are used to construct OAuth2 # credentials. _OAUTH2_INSTALLED_APP_KEYS = ('client_id', 'client_secret', 'refresh_token') _OAUTH2_SERVICE_ACCT_KEYS = ('service_account_email', @@ -64,7 +64,7 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, """Loads the data necessary for instantiating a client from file storage. In addition to the required_client_values argument, the yaml file must supply - the keys used to create OAuth 2.0 credentials. It may also optionally provide + the keys used to create OAuth2 credentials. It may also optionally provide proxy_info in order to configure a proxy. Args: @@ -78,13 +78,13 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, Returns: A dictionary map of the keys in the yaml file to their values. This will not - contain the keys used for OAuth 2.0 client creation and instead will have a + contain the keys used for OAuth2 client creation and instead will have a GoogleOAuth2Client object stored in the 'oauth2_client' field. Raises: A GoogleAdsValueError if the given yaml file does not contain the information necessary to instantiate a client object - either a - required_client_values key was missing or an OAuth 2.0 key was missing. + required_client_values key was missing or an OAuth2 key was missing. """ if not os.path.isabs(path): path = os.path.expanduser(path) @@ -156,7 +156,7 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, del product_data[key] else: raise googleads.errors.GoogleAdsValueError( - 'Your yaml file, %s, is incorrectly configured for OAuth 2.0. You ' + 'Your yaml file, %s, is incorrectly configured for OAuth2. You ' 'need to specify credentials for either the installed application ' 'flow (%s) or service account flow (%s). Actual values provided are: ' '%s' % (path, _OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS, diff --git a/googleads/dfp.py b/googleads/dfp.py index 17256a13..80be77b0 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -186,7 +186,7 @@ def LoadFromStorage(cls, path=None): Raises: A GoogleAdsValueError if the given yaml file does not contain the information necessary to instantiate a client object - either a - required key was missing or an OAuth 2.0 key was missing. + required key was missing or an OAuth2 key was missing. """ if path is None: path = os.path.join(os.path.expanduser('~'), 'googleads.yaml') diff --git a/googleads/oauth2.py b/googleads/oauth2.py index 7f1aa85f..e0affb53 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -12,11 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""OAuth 2.0 integration for the googleads library. +"""OAuth2 integration for the googleads library. This module provides a basic interface which the googleads library uses to authorize API requests and some simple implementations built on oauth2client. If -our OAuth 2.0 workflows doesn't meet your requirements, you can implement this +our OAuth2 workflows doesn't meet your requirements, you can implement this interface in your own way. For example, you could pull credentials from a shared server and/or centralize refreshing credentials to prevent every Python process from independently refreshing the credentials. @@ -58,19 +58,19 @@ def GetAPIScope(api_name): class GoogleOAuth2Client(object): - """An OAuth 2.0 client for use with Google APIs. + """An OAuth2 client for use with Google APIs. This interface assumes all responsibilty for refreshing credentials when necessary. """ def CreateHttpHeader(self): - """Creates an OAuth 2.0 HTTP header. + """Creates an OAuth2 HTTP header. - The OAuth 2.0 credentials will be refreshed as necessary. + The OAuth2 credentials will be refreshed as necessary. Returns: - A dictionary containing one entry: the OAuth 2.0 Bearer header under the + A dictionary containing one entry: the OAuth2 Bearer header under the 'Authorization' key. """ raise NotImplementedError('You must subclass GoogleOAuth2Client.') @@ -81,19 +81,19 @@ def Refresh(self): class GoogleRefreshTokenClient(GoogleOAuth2Client): - """A simple client for using OAuth 2.0 for Google APIs with a refresh token. + """A simple client for using OAuth2 for Google APIs with a refresh token. This class is not capable of supporting any flows other than taking an existing, active refresh token and generating credentials from it. It does not - matter which of Google's OAuth 2.0 flows you used to generate the refresh + matter which of Google's OAuth2 flows you used to generate the refresh token (installed application, web flow, etc.). Attributes: proxy_info: A ProxyInfo instance used for refresh requests. """ - # The web address for generating OAuth 2.0 credentials at Google. + # The web address for generating OAuth2 credentials at Google. _GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token' - # We will refresh an OAuth 2.0 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE + # We will refresh an OAuth2 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE # minutes in advance of its expiration. _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5 # The placeholder URL is used when adding the access token to our request. A @@ -127,14 +127,14 @@ def __init__(self, client_id, client_secret, refresh_token, proxy_info=None, self.ca_certs = ca_certs def CreateHttpHeader(self): - """Creates an OAuth 2.0 HTTP header. + """Creates an OAuth2 HTTP header. - The OAuth 2.0 credentials will be refreshed as necessary. In the event that + The OAuth2 credentials will be refreshed as necessary. In the event that the credentials fail to refresh, a message is logged but no exception is raised. Returns: - A dictionary containing one entry: the OAuth 2.0 Bearer header under the + A dictionary containing one entry: the OAuth2 Bearer header under the 'Authorization' key. Raises: @@ -165,7 +165,7 @@ def Refresh(self): class GoogleServiceAccountClient(GoogleOAuth2Client): - """A simple client for using OAuth 2.0 for Google APIs with a service account. + """A simple client for using OAuth2 for Google APIs with a service account. This class is not capable of supporting any flows other than generating credentials from a service account email and key file. This is incompatible @@ -174,7 +174,7 @@ class GoogleServiceAccountClient(GoogleOAuth2Client): Attributes: proxy_info: A ProxyInfo instance used for refresh requests. """ - # We will refresh an OAuth 2.0 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE + # We will refresh an OAuth2 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE # minutes in advance of its expiration. _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5 _USER_AGENT = 'Google Ads Python Client Library' @@ -219,14 +219,14 @@ def __init__(self, scope, client_email, key_file, self.Refresh() def CreateHttpHeader(self): - """Creates an OAuth 2.0 HTTP header. + """Creates an OAuth2 HTTP header. - The OAuth 2.0 credentials will be refreshed as necessary. In the event that + The OAuth2 credentials will be refreshed as necessary. In the event that the credentials fail to refresh, a message is logged but no exception is raised. Returns: - A dictionary containing one entry: the OAuth 2.0 Bearer header under the + A dictionary containing one entry: the OAuth2 Bearer header under the 'Authorization' key. Raises: diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 4d353604..9153bae5 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -338,6 +338,17 @@ def setUp(self): @classmethod def setUpClass(cls): test_dir = os.path.dirname(__file__) + with open(os.path.join( + test_dir, 'data/batch_job_util_budget_template.txt')) as handler: + cls.BUDGET_TEMPLATE = handler.read() + with open(os.path.join( + test_dir, + 'data/batch_job_util_campaign_criterion_template.txt')) as handler: + cls.CAMPAIGN_CRITERION_TEMPLATE = handler.read() + with open(os.path.join( + test_dir, + 'data/batch_job_util_campaign_label_template.txt')) as handler: + cls.CAMPAIGN_LABEL_TEMPLATE = handler.read() with open(os.path.join( test_dir, 'data/batch_job_util_invalid_request.txt')) as handler: cls.INVALID_API_REQUEST = handler.read() @@ -348,75 +359,127 @@ def setUpClass(cls): test_dir, 'data/batch_job_util_raw_request_template.txt')) as handler: cls.RAW_API_REQUEST_TEMPLATE = handler.read() with open(os.path.join( - test_dir, 'data/batch_job_util_raw_operation_template.txt')) as handler: - cls.RAW_OPERATION_TEMPLATE = handler.read() + test_dir, 'data/batch_job_util_operations_template.txt')) as handler: + cls.OPERATIONS_TEMPLATE = handler.read() with open(os.path.join( test_dir, 'data/batch_job_util_upload_template.txt')) as handler: cls.UPLOAD_OPERATIONS_TEMPLATE = handler.read() - def GenerateBudgetOperations(self, operations): - """Generates request containing given number of BudgetOperations. + def ExpandOperandTemplate(self, operation_type, operand): + """Expands the appropriate operand for the given operation_type. Args: - operations: a positive int defining the number of BudgetOperations to be - generated. + operation_type: str indicating the type of operation the operand is being + expanded for. Accepted types include: "BudgetOperation", + "CampaignCriterionOperation", and "CampaignLabelOperation". + operand: dict containing fields for the operation_type's operand. + Returns: - A list of dictionaries containing distinct BudgetOperations. - """ - return [{ - 'operator': 'ADD', - 'xsi_type': 'BudgetOperation', - 'operand': { - 'budgetId': str(i), - 'name': 'Batch budget #%s' % i, - 'period': 'DAILY', - 'amount': {'microAmount': str(3333333 * i)}, - 'deliveryMethod': 'STANDARD'} - } for i in range(1, operations + 1)] + A str containing the expanded operand. - def GenerateCampaignCriterionOperations(self, operations): - """Generates request containing given number of CampaignCriterionOperations. + Raises: + ValueError: if an unsupported operation_type is specified. + """ + if operation_type == 'BudgetOperation': + return self.BUDGET_TEMPLATE % ( + operand['budgetId'], operand['name'], + operand['amount']['microAmount'], operand['deliveryMethod']) + elif operation_type == 'CampaignCriterionOperation': + return self.CAMPAIGN_CRITERION_TEMPLATE % ( + operand['CampaignCriterion.Type'], operand['campaignId'], + operand['criterion']['Criterion.Type'], + operand['criterion']['text'], + operand['criterion']['matchType']) + elif operation_type == 'CampaignLabelOperation': + return self.CAMPAIGN_LABEL_TEMPLATE % ( + operand['campaignId'], operand['labelId']) + else: + raise ValueError('Invalid operation_type "%s" specified.' + % operation_type) + + def GenerateOperations(self, operation_type, num_operations): + """Generates a set of operations of the given type. Args: - operations: a positive int defining the number of - CampaignCriterionOperations to be generated. + operation_type: str indicating the type of operation to be generated. + Accepted types include: "BudgetOperation", "CampaignCriterionOperation", + and "CampaignLabelOperation". + num_operations: a positive int defining the number of operations to be + generated. + Returns: - A list of dictionaries containing distinct CampaignCriterionOperations. - """ - return [{ - 'operator': 'ADD', - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': str(100 * i), - 'criterion': { - 'xsi_type': 'Keyword', - 'text': 'venus %s' % i, - 'matchType': 'BROAD' - } - } - } for i in range(1, operations + 1)] + A tuple where the first item indicates the method to be used in the + request and the second is a list of dictionaries containing distinct + operations of the given operation_type. - def GenerateValidRequest(self, operations): + Raises: + ValueError: if an unsupported operation_type is specified. + """ + operation_range = range(1, num_operations + 1) + + if operation_type == 'BudgetOperation': + return ('mutate', [{ + 'operator': 'ADD', + 'xsi_type': 'BudgetOperation', + 'operand': { + 'budgetId': str(i), + 'name': 'Batch budget #%s' % i, + 'amount': {'microAmount': str(3333333 * i)}, + 'deliveryMethod': 'STANDARD'} + } for i in operation_range]) + elif operation_type == 'CampaignCriterionOperation': + return ('mutate', [{ + 'operator': 'ADD', + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': str(100 * i), + 'criterion': { + 'xsi_type': 'Keyword', + 'text': 'venus %s' % i, + 'matchType': 'BROAD' + } + } + } for i in operation_range]) + elif operation_type == 'CampaignLabelOperation': + return ('mutateLabel', [{ + 'operator': 'ADD', + 'xsi_type': 'CampaignLabelOperation', + 'operand': { + 'campaignId': 123 * i, + 'labelId': 321 * i} + } for i in operation_range]) + else: + raise ValueError('Invalid operation_type "%s" specified.' + % operation_type) + + def GenerateValidRequest(self, operation_type, num_operations=1): """Generates a valid API request containing the given number of operations. Args: - operations: a positive int defining the number of BudgetOperations to be + operation_type: str indicating the type of operation to be generated. + Accepted types include: "BudgetOperation", "CampaignCriterionOperation", + and "CampaignLabelOperation". + num_operations: a positive int defining the number of operations to be generated. Returns: A tuple containing the operations used to construct str containing a valid API request. + + Raises: + ValueError: if an unsupported operation_type is specified. """ - ops = self.GenerateBudgetOperations(operations) - ops_xml = ''.join([self.RAW_OPERATION_TEMPLATE % ( - op['operator'], op['xsi_type'], op['operand']['budgetId'], - op['operand']['name'], op['operand']['period'], - op['operand']['amount']['microAmount'], - op['operand']['deliveryMethod'] + method, ops = self.GenerateOperations(operation_type, num_operations) + + ops_xml = ''.join([self.OPERATIONS_TEMPLATE % ( + op['operator'], op['xsi_type'], + self.ExpandOperandTemplate(operation_type, op['operand']) ) for op in ops]) - request = self.RAW_API_REQUEST_TEMPLATE % (self.version, self.version, - ops_xml) + + request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % ( + self.version, self.version, method, ops_xml, method) + return (ops, request) def GenerateValidUnicodeRequest(self, operations): @@ -431,15 +494,13 @@ def GenerateValidUnicodeRequest(self, operations): valid API request. """ ops = self.GenerateUnicodeBudgetOperations(operations) - ops_xml = ''.join([self.RAW_OPERATION_TEMPLATE.decode('utf-8') % ( - op[u'operator'], op[u'xsi_type'], op[u'operand'][u'budgetId'], - op[u'operand'][u'name'], op[u'operand'][u'period'], - op[u'operand'][u'amount'][u'microAmount'], - op[u'operand'][u'deliveryMethod'] + method = 'mutate' + ops_xml = ''.join([self.OPERATIONS_TEMPLATE.decode('utf-8') % ( + op[u'operator'], op[u'xsi_type'], + self.ExpandOperandTemplate('BudgetOperation', op['operand']) ) for op in ops]) - request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % (self.version, - self.version, - ops_xml) + request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % ( + self.version, self.version, method, ops_xml, method) return (ops, request) def GenerateUnicodeBudgetOperations(self, operations): @@ -457,7 +518,6 @@ def GenerateUnicodeBudgetOperations(self, operations): u'operand': { u'budgetId': str(i).decode('utf-8'), u'name': u'アングリーバード Batch budget #%s' % i, - u'period': u'DAILY', u'amount': {u'microAmount': str(3333333 * i).decode('utf-8')}, u'deliveryMethod': u'STANDARD'} } for i in range(1, operations + 1)] @@ -473,7 +533,7 @@ def testExtractOperations(self): Verifies that the xsi_type has been properly assigned. """ - operations = self.GenerateCampaignCriterionOperations(1) + _, operations = self.GenerateOperations('CampaignCriterionOperation', 1) raw_xml = self.request_builder._GenerateRawRequestXML(operations) operations_xml = self.request_builder._ExtractOperations(raw_xml) # Put operations in a format that allows us to easily verify the behavior. @@ -501,7 +561,8 @@ def testExtractOperations(self): def testFormatForBatchJobService(self): """Tests whether namespaces have been removed.""" operations_amount = 5 - ops = self.GenerateCampaignCriterionOperations(operations_amount) + _, ops = self.GenerateOperations('CampaignCriterionOperation', + operations_amount) root = ElementTree.fromstring(self.request_builder._GenerateRawRequestXML( ops)) body = root.find('{%s}Body' % self.ENVELOPE_NS) @@ -534,7 +595,7 @@ def testFormatForBatchJobService(self): def testGenerateOperationsXMLNoXsiType(self): """Tests whether _GenerateOperationsXML raises ValueError if no xsi_type. """ - operations = self.GenerateCampaignCriterionOperations(1) + _, operations = self.GenerateOperations('CampaignCriterionOperation', 1) del operations[0]['xsi_type'] self.assertRaises( googleads.errors.AdWordsBatchJobServiceInvalidOperationError, @@ -543,7 +604,7 @@ def testGenerateOperationsXMLNoXsiType(self): def testGenerateOperationsXMLWithNoOperations(self): """Tests whether _GenerateOperationsXML produces empty str if no operations. """ - operations = self.GenerateCampaignCriterionOperations(0) + _, operations = self.GenerateOperations('CampaignCriterionOperation', 0) raw_xml = self.request_builder._GenerateOperationsXML( operations) self.assertTrue(raw_xml is '') @@ -581,7 +642,7 @@ def testGenerateRawRequestXMLFromCampaignLabelOperation(self): def testGenerateRawRequestXMLFromSingleOperation(self): """Tests whether raw request xml can be produced from a single operation.""" operations_amount = 1 - ops = self.GenerateBudgetOperations(operations_amount) + _, ops = self.GenerateOperations('BudgetOperation', operations_amount) root = ElementTree.fromstring( self.request_builder._GenerateRawRequestXML(ops)) @@ -613,11 +674,6 @@ def testGenerateRawRequestXMLFromSingleOperation(self): self.assertEqual(operand.find( '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) - self.assertEqual( - operand.find( - '{%s}period' % - self.request_builder._adwords_endpoint).text, - ops[i]['operand']['period']) amount = operand.find('{%s}amount' % self.request_builder._adwords_endpoint) self.assertTrue(len(amount._children) == @@ -632,7 +688,7 @@ def testGenerateRawRequestXMLFromSingleOperation(self): def testGenerateRawRequestXMLFromMultipleOperations(self): """Tests whether raw request xml can be produced for multiple operations.""" operations_amount = 5 - ops = self.GenerateBudgetOperations(operations_amount) + _, ops = self.GenerateOperations('BudgetOperation', operations_amount) root = ElementTree.fromstring( self.request_builder._GenerateRawRequestXML(ops)) @@ -663,9 +719,6 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): self.assertEqual(operand.find( '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) - self.assertEqual(operand.find( - '{%s}period' % self.request_builder._adwords_endpoint).text, - ops[i]['operand']['period']) amount = operand.find( '{%s}amount' % self.request_builder._adwords_endpoint) self.assertTrue(len(amount._children) == @@ -712,11 +765,6 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): self.assertEqual(operand.find( '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) - self.assertEqual( - operand.find( - '{%s}period' % - self.request_builder._adwords_endpoint).text, - ops[i]['operand']['period']) amount = operand.find('{%s}amount' % self.request_builder._adwords_endpoint) self.assertTrue(len(amount._children) == @@ -728,13 +776,47 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): '{%s}deliveryMethod' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['deliveryMethod']) + def testGetRawOperationsFromValidSingleOperationMutateLabelRequest(self): + """Test if operations XML can be retrieved for a single-op label request.""" + operations_amount = 1 + ops, request = self.GenerateValidRequest('CampaignLabelOperation', + operations_amount) + + mutate = self.request_builder._GetRawOperationsFromXML(request) + self.assertEqual(mutate.tag, + '{%s}mutateLabel' % self.request_builder._adwords_endpoint) + self.assertTrue(len(mutate._children) == operations_amount) + + for i in range(0, operations_amount): + operations = mutate[i] + self.assertEqual( + operations.tag, + '{%s}operations' % self.request_builder._adwords_endpoint) + self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertEqual(operations.find( + '{%s}operator' % self.request_builder._adwords_endpoint).text, + ops[i]['operator']) + self.assertEqual(operations.find( + '{%s}Operation.Type' % self.request_builder._adwords_endpoint).text, + ops[i]['xsi_type']) + operand = operations.find( + '{%s}operand' % self.request_builder._adwords_endpoint) + self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertEqual(int(operand.find( + '{%s}campaignId' % self.request_builder._adwords_endpoint).text), + ops[i]['operand']['campaignId']) + self.assertEqual(int(operand.find( + '{%s}labelId' % self.request_builder._adwords_endpoint).text), + ops[i]['operand']['labelId']) + def testGetRawOperationsFromValidSingleOperationRequest(self): - """Test whether operations XML can be retrieved for a single-op request. + """Test if operations XML can be retrieved for a single-op request. Also verifies that the contents of generated XML are correct. """ operations_amount = 1 - ops, request = self.GenerateValidRequest(operations_amount) + ops, request = self.GenerateValidRequest('BudgetOperation', + operations_amount) mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual(mutate.tag, @@ -762,9 +844,6 @@ def testGetRawOperationsFromValidSingleOperationRequest(self): self.assertEqual(operand.find( '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) - self.assertEqual(operand.find( - '{%s}period' % self.request_builder._adwords_endpoint).text, - ops[i]['operand']['period']) amount = operand.find( '{%s}amount' % self.request_builder._adwords_endpoint) self.assertTrue(len(amount._children) == @@ -782,7 +861,8 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): Also verifies that the contents of generated XML are correct. """ operations_amount = 5 - ops, request = self.GenerateValidRequest(operations_amount) + ops, request = self.GenerateValidRequest('BudgetOperation', + operations_amount) mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual( @@ -811,9 +891,6 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): self.assertEqual(operand.find( '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) - self.assertEqual(operand.find( - '{%s}period' % self.request_builder._adwords_endpoint).text, - ops[i]['operand']['period']) amount = (operand.find( '{%s}amount' % self.request_builder._adwords_endpoint)) self.assertTrue(len(amount._children) == @@ -860,9 +937,6 @@ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): self.assertEqual(operand.find( '{%s}name' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['name']) - self.assertEqual(operand.find( - '{%s}period' % self.request_builder._adwords_endpoint).text, - ops[i]['operand']['period']) amount = (operand.find( '{%s}amount' % self.request_builder._adwords_endpoint)) self.assertTrue(len(amount._children) == @@ -877,7 +951,8 @@ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): def testGetRawOperationsFromValidZeroOperationRequest(self): """Test verifying empty request generated if no operations provided.""" operations_amount = 0 - _, request = self.GenerateValidRequest(operations_amount) + _, request = self.GenerateValidRequest('BudgetOperation', + operations_amount) mutate = self.request_builder._GetRawOperationsFromXML(request) @@ -985,6 +1060,7 @@ def setUp(self): """Prepare tests.""" self.client = GetAdWordsClient() self.batch_job_helper = self.client.GetBatchJobHelper() + self.version = self.batch_job_helper._version self.original_url = 'https://goo.gl/w8tkpK' self.initialized_url = 'https://goo.gl/Xtaq83' @@ -998,7 +1074,7 @@ def setUp(self): self.incremental_uploader_dump = ( '{current_content_length: 0, is_last: false, ' - 'upload_url: \'https://goo.gl/Xtaq83\', version: v201601}\n') + 'upload_url: \'https://goo.gl/Xtaq83\', version: %s}\n' % self.version) def testDump(self): expected = self.incremental_uploader_dump @@ -1027,7 +1103,7 @@ def testLoad(self): self.assertEquals(restored_uploader._is_last, self.incremental_uploader._is_last) self.assertEquals(restored_uploader._request_builder._version, - self.incremental_uploader._request_builder._version) + self.version) self.assertEquals(restored_uploader._upload_url, self.incremental_uploader._upload_url) diff --git a/tests/common_test.py b/tests/common_test.py index 5f4d470d..b50b5402 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -33,7 +33,7 @@ class CommonTest(unittest.TestCase): """Tests for the googleads.common module.""" - # Dictionaries with all the required OAuth 2.0 keys + # Dictionaries with all the required OAuth2 keys _OAUTH_INSTALLED_APP_DICT = {'client_id': 'a', 'client_secret': 'b', 'refresh_token': 'c'} _OAUTH_SERVICE_ACCT_DICT = {'service_account_email': 'test@test.com', From b80b8b3741a55f1d00c5974bc58f92540663c6f6 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 25 Mar 2016 15:08:29 -0400 Subject: [PATCH 032/180] Commiting latest changes. From 72a85c906ff7f1bfa17d2ff6854bdbe44e551e60 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 11 Apr 2016 09:08:00 -0700 Subject: [PATCH 033/180] AdWords v201506 Sunset --- ChangeLog | 6 + examples/adwords/v201506/__init__.py | 15 - .../v201506/account_management/__init__.py | 15 - .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 103 ---- .../get_account_hierarchy.py | 92 --- .../v201506/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 222 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 108 ---- .../add_text_ad_with_upgraded_urls.py | 111 ---- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../upload_offline_conversions.py | 98 ---- .../use_shared_bidding_strategy.py | 172 ------ .../v201506/basic_operations/__init__.py | 15 - .../v201506/basic_operations/add_ad_groups.py | 112 ---- .../v201506/basic_operations/add_campaigns.py | 126 ----- .../v201506/basic_operations/add_keywords.py | 92 --- .../v201506/basic_operations/add_text_ads.py | 93 ---- .../v201506/basic_operations/get_ad_groups.py | 76 --- .../v201506/basic_operations/get_campaigns.py | 74 --- .../get_campaigns_with_awql.py | 64 --- .../v201506/basic_operations/get_keywords.py | 87 --- .../v201506/basic_operations/get_text_ads.py | 80 --- .../v201506/basic_operations/pause_ad.py | 61 -- .../v201506/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 58 -- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201506/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 67 --- .../campaign_management/add_experiment.py | 127 ----- .../add_keywords_in_bulk.py | 134 ----- .../get_all_disapproved_ads.py | 74 --- .../get_all_disapproved_ads_with_awql.py | 63 --- .../get_campaigns_by_label.py | 85 --- .../campaign_management/promote_experiment.py | 60 -- .../campaign_management/set_ad_parameters.py | 102 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 86 --- .../v201506/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 120 ---- .../handle_policy_violation_error.py | 114 ---- .../adwords/v201506/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 ------ .../v201506/extensions/add_site_links.py | 124 ----- .../extensions/add_site_links_using_feeds.py | 226 -------- .../adwords/v201506/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 ------------------ .../v201506/migration/upgrade_ad_url.py | 79 --- examples/adwords/v201506/misc/__init__.py | 15 - .../v201506/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201506/misc/upload_image.py | 66 --- .../adwords/v201506/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 132 ----- .../get_keyword_bid_simulations.py | 81 --- .../v201506/optimization/get_keyword_ideas.py | 90 --- .../adwords/v201506/remarketing/__init__.py | 15 - .../v201506/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 73 --- .../remarketing/add_rule_based_user_lists.py | 183 ------ .../adwords/v201506/reporting/__init__.py | 15 - .../reporting/download_criteria_report.py | 61 -- .../download_criteria_report_as_stream.py | 77 --- ...oad_criteria_report_as_stream_with_awql.py | 81 --- .../download_criteria_report_as_string.py | 59 -- ...oad_criteria_report_as_string_with_awql.py | 55 -- .../download_criteria_report_with_awql.py | 59 -- .../v201506/reporting/get_report_fields.py | 52 -- examples/adwords/v201506/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 281 ---------- .../v201506/shopping/add_product_scope.py | 104 ---- .../v201506/shopping/add_shopping_campaign.py | 121 ---- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201506/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 161 ------ .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 55 -- .../v201506/targeting/lookup_location.py | 82 --- .../create_custom_creative.py | 5 +- .../create_custom_creative.py | 5 +- .../create_custom_creative.py | 5 +- .../create_custom_creative.py | 5 +- googleads/adwords.py | 49 +- googleads/common.py | 2 +- tests/adwords_test.py | 46 +- 92 files changed, 41 insertions(+), 7562 deletions(-) delete mode 100644 examples/adwords/v201506/__init__.py delete mode 100644 examples/adwords/v201506/account_management/__init__.py delete mode 100755 examples/adwords/v201506/account_management/create_account.py delete mode 100755 examples/adwords/v201506/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201506/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201506/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201506/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201506/advanced_operations/upload_offline_conversions.py delete mode 100755 examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201506/basic_operations/__init__.py delete mode 100755 examples/adwords/v201506/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201506/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201506/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201506/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201506/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201506/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201506/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201506/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201506/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201506/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201506/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201506/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201506/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201506/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201506/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201506/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201506/campaign_management/__init__.py delete mode 100755 examples/adwords/v201506/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201506/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py delete mode 100755 examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201506/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201506/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201506/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201506/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201506/error_handling/__init__.py delete mode 100755 examples/adwords/v201506/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201506/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201506/extensions/__init__.py delete mode 100755 examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201506/extensions/add_site_links.py delete mode 100755 examples/adwords/v201506/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201506/migration/__init__.py delete mode 100755 examples/adwords/v201506/migration/migrate_to_extension_settings.py delete mode 100755 examples/adwords/v201506/migration/upgrade_ad_url.py delete mode 100644 examples/adwords/v201506/misc/__init__.py delete mode 100755 examples/adwords/v201506/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201506/misc/upload_image.py delete mode 100644 examples/adwords/v201506/optimization/__init__.py delete mode 100755 examples/adwords/v201506/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201506/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201506/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201506/remarketing/__init__.py delete mode 100755 examples/adwords/v201506/remarketing/add_audience.py delete mode 100755 examples/adwords/v201506/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201506/remarketing/add_rule_based_user_lists.py delete mode 100644 examples/adwords/v201506/reporting/__init__.py delete mode 100755 examples/adwords/v201506/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201506/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201506/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201506/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201506/reporting/get_report_fields.py delete mode 100644 examples/adwords/v201506/shopping/__init__.py delete mode 100755 examples/adwords/v201506/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201506/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201506/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201506/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201506/targeting/__init__.py delete mode 100755 examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201506/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index a3b5f546..0285850a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +3.15.0 -- 4/11/2016 +* Removed support for AdWords v201506. +* Resolved issues: + Issue #108: https://github.com/googleads/googleads-python-lib/issues/108 + Issue #111: https://github.com/googleads/googleads-python-lib/issues/111 + 3.14.0 -- 3/25/2016 * Added support for AdWords v201603. * Resolved Issues: diff --git a/examples/adwords/v201506/__init__.py b/examples/adwords/v201506/__init__.py deleted file mode 100644 index 41f5a52e..00000000 --- a/examples/adwords/v201506/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201506/account_management/__init__.py b/examples/adwords/v201506/account_management/__init__.py deleted file mode 100644 index fb8c03ea..00000000 --- a/examples/adwords/v201506/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201506/account_management/create_account.py b/examples/adwords/v201506/account_management/create_account.py deleted file mode 100755 index e85b211a..00000000 --- a/examples/adwords/v201506/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 illustrates how to create an account. - -Note by default this account will only be accessible via parent AdWords manager -account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201506') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201506/account_management/get_account_changes.py b/examples/adwords/v201506/account_management/get_account_changes.py deleted file mode 100755 index dec446fe..00000000 --- a/examples/adwords/v201506/account_management/get_account_changes.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201506') - campaign_service = client.GetService('CampaignService', version='v201506') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedAdExtensions' in data: - print ' Added ad extensions: %s' % data['addedAdExtensions'] - if 'removedAdExtensions' in data: - print ' Removed ad extensions: %s' % data['removedAdExtensions'] - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201506/account_management/get_account_hierarchy.py b/examples/adwords/v201506/account_management/get_account_hierarchy.py deleted file mode 100755 index 5b875a11..00000000 --- a/examples/adwords/v201506/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the account hierarchy under the current account. - -Note: this code example won't work with test accounts. See -https://developers.google.com/adwords/api/docs/test-accounts - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201506') - - # Construct selector to get all accounts. - selector = { - 'fields': ['CustomerId', 'Name'] - } - # Get serviced account graph. - graph = managed_customer_service.get(selector) - if 'entries' in graph and graph['entries']: - # Create map from customerId to parent and child links. - child_links = {} - parent_links = {} - if 'links' in graph: - for link in graph['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Create map from customerID to account and find root account. - accounts = {} - root_account = None - for account in graph['entries']: - accounts[account['customerId']] = account - if account['customerId'] not in parent_links: - root_account = account - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - else: - print 'No serviced accounts were found' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201506/advanced_operations/__init__.py b/examples/adwords/v201506/advanced_operations/__init__.py deleted file mode 100644 index 7e57b8b3..00000000 --- a/examples/adwords/v201506/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201506/advanced_operations/add_ad_customizer.py b/examples/adwords/v201506/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 055a04ec..00000000 --- a/examples/adwords/v201506/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates TextAds that use ad customizations for the specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add TextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no TextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService') - - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'description1': 'Only {=%s.Price}' % feed_name, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 4a4d501f..00000000 --- a/examples/adwords/v201506/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201506') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 814f7ee5..00000000 --- a/examples/adwords/v201506/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad to ad group ID \'%s\' ' - 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index 51f67f00..00000000 --- a/examples/adwords/v201506/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a text add that uses advanced features of upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 9eec131f..00000000 --- a/examples/adwords/v201506/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201506') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201506') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201506') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index 5d6e1356..00000000 --- a/examples/adwords/v201506/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201506') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201506') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 65ff5ab5..00000000 --- a/examples/adwords/v201506/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201506') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py deleted file mode 100755 index 94ad5d2a..00000000 --- a/examples/adwords/v201506/advanced_operations/upload_offline_conversions.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - conversion_tracker_service = client.GetService('ConversionTrackerService', - version='v201506') - - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201506') - - # Once created, this entry will be visible under - # Tools and Analysis->Conversion and will have "Source = Import". - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'category': 'PAGE_VIEW', - 'name': conversion_name, - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90' - } - - upload_conversion_operation = { - 'operator': 'ADD', - 'operand': upload_conversion - } - - response = conversion_tracker_service.mutate( - [upload_conversion_operation]) - new_upload_conversion = response['value'] - - print ('New upload conversion type with name \'%s\' and ID \'%s\' was ' - 'created.' % (new_upload_conversion['name'], - new_upload_conversion['id'])) - - # Associate offline conversions with the upload conversion we created. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index b77cdda9..00000000 --- a/examples/adwords/v201506/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201506') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201506') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'period': 'DAILY', - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201506') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201506/basic_operations/__init__.py b/examples/adwords/v201506/basic_operations/__init__.py deleted file mode 100644 index 80acbea9..00000000 --- a/examples/adwords/v201506/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201506/basic_operations/add_ad_groups.py b/examples/adwords/v201506/basic_operations/add_ad_groups.py deleted file mode 100755 index 98c385bd..00000000 --- a/examples/adwords/v201506/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README.. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201506') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings - these settings only affect - # serving for the Display Network. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/basic_operations/add_campaigns.py b/examples/adwords/v201506/basic_operations/add_campaigns.py deleted file mode 100755 index 0afc9310..00000000 --- a/examples/adwords/v201506/basic_operations/add_campaigns.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201506') - budget_service = client.GetService('BudgetService', version='v201506') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/basic_operations/add_keywords.py b/examples/adwords/v201506/basic_operations/add_keywords.py deleted file mode 100755 index 9495ca1e..00000000 --- a/examples/adwords/v201506/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/add_text_ads.py b/examples/adwords/v201506/basic_operations/add_text_ads.py deleted file mode 100755 index 0968e2ac..00000000 --- a/examples/adwords/v201506/basic_operations/add_text_ads.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/get_ad_groups.py b/examples/adwords/v201506/basic_operations/get_ad_groups.py deleted file mode 100755 index 68f5860e..00000000 --- a/examples/adwords/v201506/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201506') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/basic_operations/get_campaigns.py b/examples/adwords/v201506/basic_operations/get_campaigns.py deleted file mode 100755 index 377cfd81..00000000 --- a/examples/adwords/v201506/basic_operations/get_campaigns.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201506') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index ea9c31a1..00000000 --- a/examples/adwords/v201506/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201506') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201506/basic_operations/get_keywords.py b/examples/adwords/v201506/basic_operations/get_keywords.py deleted file mode 100755 index e70dd2dd..00000000 --- a/examples/adwords/v201506/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/get_text_ads.py b/examples/adwords/v201506/basic_operations/get_text_ads.py deleted file mode 100755 index 4d189e28..00000000 --- a/examples/adwords/v201506/basic_operations/get_text_ads.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/pause_ad.py b/examples/adwords/v201506/basic_operations/pause_ad.py deleted file mode 100755 index e293acf1..00000000 --- a/examples/adwords/v201506/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201506/basic_operations/remove_ad.py b/examples/adwords/v201506/basic_operations/remove_ad.py deleted file mode 100755 index a2fd34a7..00000000 --- a/examples/adwords/v201506/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201506/basic_operations/remove_ad_group.py b/examples/adwords/v201506/basic_operations/remove_ad_group.py deleted file mode 100755 index e852b3ba..00000000 --- a/examples/adwords/v201506/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201506') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/remove_campaign.py b/examples/adwords/v201506/basic_operations/remove_campaign.py deleted file mode 100755 index d6212974..00000000 --- a/examples/adwords/v201506/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201506') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/basic_operations/remove_keyword.py b/examples/adwords/v201506/basic_operations/remove_keyword.py deleted file mode 100755 index d1fe3c2c..00000000 --- a/examples/adwords/v201506/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201506/basic_operations/update_ad_group.py b/examples/adwords/v201506/basic_operations/update_ad_group.py deleted file mode 100755 index 32cdd184..00000000 --- a/examples/adwords/v201506/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201506') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/basic_operations/update_campaign.py b/examples/adwords/v201506/basic_operations/update_campaign.py deleted file mode 100755 index 5e7b0c03..00000000 --- a/examples/adwords/v201506/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201506') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/basic_operations/update_keyword.py b/examples/adwords/v201506/basic_operations/update_keyword.py deleted file mode 100755 index 0c083bdf..00000000 --- a/examples/adwords/v201506/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201506/campaign_management/__init__.py b/examples/adwords/v201506/campaign_management/__init__.py deleted file mode 100644 index db098bda..00000000 --- a/examples/adwords/v201506/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201506/campaign_management/add_campaign_labels.py b/examples/adwords/v201506/campaign_management/add_campaign_labels.py deleted file mode 100755 index 2747e00f..00000000 --- a/examples/adwords/v201506/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201506') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201506/campaign_management/add_experiment.py b/examples/adwords/v201506/campaign_management/add_experiment.py deleted file mode 100755 index ce68a39c..00000000 --- a/examples/adwords/v201506/campaign_management/add_experiment.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201506') - ad_group_service = client.GetService('AdGroupService', version='v201506') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py deleted file mode 100755 index 2922b32b..00000000 --- a/examples/adwords/v201506/campaign_management/add_keywords_in_bulk.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code sample illustrates how to perform asynchronous requests. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import random -import re -import time -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -KEYWORD_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201506') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add keywords. - for i in range(KEYWORD_NUMBER): - keyword = 'mars%d' % i - if random.randint(1, 10) == 1: - keyword += '!!!' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': keyword - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - keyword = operations[index]['operand']['criterion']['text'] - print ('ERROR - keyword \'%s\' failed due to \'%s\'' % - (keyword, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 12f4cc97..00000000 --- a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 1f1580b8..00000000 --- a/examples/adwords/v201506/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index acc574b8..00000000 --- a/examples/adwords/v201506/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201506') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201506/campaign_management/promote_experiment.py b/examples/adwords/v201506/campaign_management/promote_experiment.py deleted file mode 100755 index a197a120..00000000 --- a/examples/adwords/v201506/campaign_management/promote_experiment.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201506') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201506/campaign_management/set_ad_parameters.py b/examples/adwords/v201506/campaign_management/set_ad_parameters.py deleted file mode 100755 index c7a9727d..00000000 --- a/examples/adwords/v201506/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright 2015 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - ad_param_service = client.GetService('AdParamService', version='v201506') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': { - 'urls': ['http://www.example.com'] - }, - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index aef6b487..00000000 --- a/examples/adwords/v201506/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201506') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201506/campaign_management/validate_text_ad.py b/examples/adwords/v201506/campaign_management/validate_text_ad.py deleted file mode 100755 index 001ae7cf..00000000 --- a/examples/adwords/v201506/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': { - 'urls': ['http://www.example.com'] - }, - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/error_handling/__init__.py b/examples/adwords/v201506/error_handling/__init__.py deleted file mode 100644 index b5203c57..00000000 --- a/examples/adwords/v201506/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201506/error_handling/handle_partial_failures.py b/examples/adwords/v201506/error_handling/handle_partial_failures.py deleted file mode 100755 index c6729d1e..00000000 --- a/examples/adwords/v201506/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/error_handling/handle_policy_violation_error.py b/examples/adwords/v201506/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 1c9ee84c..00000000 --- a/examples/adwords/v201506/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201506') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - operation = operations[int(operation_index[0])] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) - else: - # Non-policy error returned, re-throw exception. - raise e - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/extensions/__init__.py b/examples/adwords/v201506/extensions/__init__.py deleted file mode 100644 index b4d63e00..00000000 --- a/examples/adwords/v201506/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 5777903f..00000000 --- a/examples/adwords/v201506/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201506').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201506') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201506/extensions/add_site_links.py b/examples/adwords/v201506/extensions/add_site_links.py deleted file mode 100755 index 38f8e087..00000000 --- a/examples/adwords/v201506/extensions/add_site_links.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201506') - customer_service = client.GetService('CustomerService', version='v201506') - - customer_tz = timezone(customer_service.get()['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt) - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'} - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py b/examples/adwords/v201506/extensions/add_site_links_using_feeds.py deleted file mode 100755 index 0c126473..00000000 --- a/examples/adwords/v201506/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201506') - feed_item_service = client.GetService('FeedItemService', version='v201506') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201506') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201506') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2'} - ] - - feed_items = [] - for item in items_data: - feed_items.append({ - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - - # Optional: use the 'scheduling' key to specify time and days of the - # week for feed to deliver. This is a Beta feature. - }) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/migration/__init__.py b/examples/adwords/v201506/migration/__init__.py deleted file mode 100644 index 5de8ecca..00000000 --- a/examples/adwords/v201506/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201506/migration/migrate_to_extension_settings.py b/examples/adwords/v201506/migration/migrate_to_extension_settings.py deleted file mode 100755 index a4ea2eff..00000000 --- a/examples/adwords/v201506/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201506') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201506') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201506') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201506') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201506') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201506') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201506') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/migration/upgrade_ad_url.py b/examples/adwords/v201506/migration/upgrade_ad_url.py deleted file mode 100755 index edca6b1b..00000000 --- a/examples/adwords/v201506/migration/upgrade_ad_url.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 upgrades an ad to use upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, adgroup_id, ad_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201506') - - selector = { - 'fields': ['Id', 'Url'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [ad_id] - } - ] - } - - page = adgroup_ad_service.get(selector) - - adgroup_ad = page['entries'][0] if page['entries'] else None - - if not adgroup_ad: - raise errors.GoogleAdsError('Ad not found.') - - ad_url_upgrade = { - 'adId': adgroup_ad['ad']['id'], - 'finalUrl': adgroup_ad['ad']['url'] - } - - adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] - - if adgroup_ad: - print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' - % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201506/misc/__init__.py b/examples/adwords/v201506/misc/__init__.py deleted file mode 100644 index 30d42e87..00000000 --- a/examples/adwords/v201506/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201506/misc/get_all_images_and_videos.py b/examples/adwords/v201506/misc/get_all_images_and_videos.py deleted file mode 100755 index 96c5c518..00000000 --- a/examples/adwords/v201506/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201506') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/misc/upload_image.py b/examples/adwords/v201506/misc/upload_image.py deleted file mode 100755 index fae31b83..00000000 --- a/examples/adwords/v201506/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201506') - - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201506/optimization/__init__.py b/examples/adwords/v201506/optimization/__init__.py deleted file mode 100644 index 2e0ca689..00000000 --- a/examples/adwords/v201506/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py b/examples/adwords/v201506/optimization/estimate_keyword_traffic.py deleted file mode 100755 index b87b3623..00000000 --- a/examples/adwords/v201506/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201506') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - selector = { - 'campaignEstimateRequests': [{ - 'adGroupEstimateRequests': [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }], - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ] - }] - } - estimates = traffic_estimator_service.get(selector) - - # Display results. - ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] - keyword_estimates = ad_group_estimate['keywordEstimates'] - for index in xrange(len(keyword_estimates)): - keyword = keyword_estimate_requests[index]['keyword'] - estimate = keyword_estimates[index] - if keyword_estimate_requests[index].get('isNegative', False): - continue - - # Find the mean of the min and max values. - mean_avg_cpc = (calc_mean(estimate['min']['averageCpc']['microAmount'], - estimate['max']['averageCpc']['microAmount']) - if 'averageCpc' in estimate['min'] else 'N/A') - mean_avg_pos = calc_mean(estimate['min']['averagePosition'], - estimate['max']['averagePosition']) - mean_clicks = calc_mean(estimate['min']['clicksPerDay'], - estimate['max']['clicksPerDay']) - mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], - estimate['max']['totalCost']['microAmount']) - - print ('Results for the keyword with text \'%s\' and match type \'%s\':' - % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % mean_avg_cpc - print ' Estimated ad position: %s' % mean_avg_pos - print ' Estimated daily clicks: %s' % mean_clicks - print ' Estimated daily cost: %s' % mean_total_cost - - -def fmt_mean(mean): - if mean: - return '%.2f' % mean - else: - return None - - -def calc_mean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index dec4acd9..00000000 --- a/examples/adwords/v201506/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201506') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201506/optimization/get_keyword_ideas.py b/examples/adwords/v201506/optimization/get_keyword_ideas.py deleted file mode 100755 index 28ce973d..00000000 --- a/examples/adwords/v201506/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201506') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/remarketing/__init__.py b/examples/adwords/v201506/remarketing/__init__.py deleted file mode 100644 index b39776a8..00000000 --- a/examples/adwords/v201506/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201506/remarketing/add_audience.py b/examples/adwords/v201506/remarketing/add_audience.py deleted file mode 100755 index 102f8249..00000000 --- a/examples/adwords/v201506/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201506') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201506') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/remarketing/add_conversion_tracker.py b/examples/adwords/v201506/remarketing/add_conversion_tracker.py deleted file mode 100755 index 367e305f..00000000 --- a/examples/adwords/v201506/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201506') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'markupLanguage': 'HTML', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'isProductAdsChargeable': 'true', - 'productAdsChargeableConversionWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 76de9a66..00000000 --- a/examples/adwords/v201506/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201506') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/reporting/__init__.py b/examples/adwords/v201506/reporting/__init__.py deleted file mode 100644 index 85eee62f..00000000 --- a/examples/adwords/v201506/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201506/reporting/download_criteria_report.py b/examples/adwords/v201506/reporting/download_criteria_report.py deleted file mode 100755 index f0b72e18..00000000 --- a/examples/adwords/v201506/reporting/download_criteria_report.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201506') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index 8b36a0f4..00000000 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201506') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 98567d95..00000000 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201506') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string.py deleted file mode 100755 index 51cc7415..00000000 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201506') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 2da6d4ad..00000000 --- a/examples/adwords/v201506/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201506') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 714e900c..00000000 --- a/examples/adwords/v201506/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201506') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=False) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201506/reporting/get_report_fields.py b/examples/adwords/v201506/reporting/get_report_fields.py deleted file mode 100755 index 73a250ea..00000000 --- a/examples/adwords/v201506/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201506') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201506/shopping/__init__.py b/examples/adwords/v201506/shopping/__init__.py deleted file mode 100644 index 96422728..00000000 --- a/examples/adwords/v201506/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201506/shopping/add_product_partition_tree.py b/examples/adwords/v201506/shopping/add_product_partition_tree.py deleted file mode 100755 index c151b050..00000000 --- a/examples/adwords/v201506/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201506/shopping/add_product_scope.py b/examples/adwords/v201506/shopping/add_product_scope.py deleted file mode 100755 index 28c18b4b..00000000 --- a/examples/adwords/v201506/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201506') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201506/shopping/add_shopping_campaign.py b/examples/adwords/v201506/shopping/add_shopping_campaign.py deleted file mode 100755 index 4dc3e54c..00000000 --- a/examples/adwords/v201506/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201506') - ad_group_service = client.GetService('AdGroupService', version='v201506') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201506') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set shared budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201506/shopping/get_product_category_taxonomy.py b/examples/adwords/v201506/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 98bc359d..00000000 --- a/examples/adwords/v201506/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201506') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/targeting/__init__.py b/examples/adwords/v201506/targeting/__init__.py deleted file mode 100644 index 2c027ccc..00000000 --- a/examples/adwords/v201506/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index ecb1346f..00000000 --- a/examples/adwords/v201506/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201506') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - florida_downtown = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'PlacesOfInterestOperand', - # Other valid options: AIRPORT, UNIVERSITY. - 'category': 'DOWNTOWN', - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - } - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish, florida_tier3, - florida_downtown] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 2910530d..00000000 --- a/examples/adwords/v201506/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201506') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 2188f179..00000000 --- a/examples/adwords/v201506/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201506') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index 70104d28..00000000 --- a/examples/adwords/v201506/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201506') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % (carrier['name'], carrier['id'], carrier['countryCode'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201506/targeting/lookup_location.py b/examples/adwords/v201506/targeting/lookup_location.py deleted file mode 100755 index 3b6abe9f..00000000 --- a/examples/adwords/v201506/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201506') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/dfp/v201505/creative_service/create_custom_creative.py b/examples/dfp/v201505/creative_service/create_custom_creative.py index 5343bfb4..d5fdfdb0 100755 --- a/examples/dfp/v201505/creative_service/create_custom_creative.py +++ b/examples/dfp/v201505/creative_service/create_custom_creative.py @@ -72,10 +72,11 @@ def main(client, advertiser_id): } # Call service to create the creative. - creative = creative_service.createCreative(creative) + creatives = creative_service.createCreatives([creative]) # Display results. - if creative: + if creatives: + creative = creatives[0] print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), diff --git a/examples/dfp/v201508/creative_service/create_custom_creative.py b/examples/dfp/v201508/creative_service/create_custom_creative.py index 0e2dd500..8e2eb1ae 100755 --- a/examples/dfp/v201508/creative_service/create_custom_creative.py +++ b/examples/dfp/v201508/creative_service/create_custom_creative.py @@ -72,10 +72,11 @@ def main(client, advertiser_id): } # Call service to create the creative. - creative = creative_service.createCreative(creative) + creatives = creative_service.createCreatives([creative]) # Display results. - if creative: + if creatives: + creative = creatives[0] print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), diff --git a/examples/dfp/v201511/creative_service/create_custom_creative.py b/examples/dfp/v201511/creative_service/create_custom_creative.py index 393e82ae..f8591c15 100755 --- a/examples/dfp/v201511/creative_service/create_custom_creative.py +++ b/examples/dfp/v201511/creative_service/create_custom_creative.py @@ -74,10 +74,11 @@ def main(client, advertiser_id): } # Call service to create the creative. - creative = creative_service.createCreative(creative) + creatives = creative_service.createCreatives([creative]) # Display results. - if creative: + if creatives: + creative = creatives[0] print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), diff --git a/examples/dfp/v201602/creative_service/create_custom_creative.py b/examples/dfp/v201602/creative_service/create_custom_creative.py index f60bc215..1c642806 100755 --- a/examples/dfp/v201602/creative_service/create_custom_creative.py +++ b/examples/dfp/v201602/creative_service/create_custom_creative.py @@ -74,10 +74,11 @@ def main(client, advertiser_id): } # Call service to create the creative. - creative = creative_service.createCreative(creative) + creatives = creative_service.createCreatives([creative]) # Display results. - if creative: + if creatives: + creative = creatives[0] print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), diff --git a/googleads/adwords.py b/googleads/adwords.py index 84acf159..b1fcaca9 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -36,49 +36,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201506': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'GeoLocationService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'MutateJobService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - }, 'v201509': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', @@ -651,7 +608,7 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): new_content_length - 1, new_content_length if is_last else '*' )) - req.data = request_body + req.data = request_body.encode('utf-8') return req def _BuildUploadRequestBody(self, operations, has_prefix=True, @@ -709,7 +666,7 @@ def _ExtractOperations(self, full_soap_xml): raise googleads.errors.GoogleAdsValueError('No xsi_type specified ' 'for the operations.') operations.attrib['xsi:type'] = operation_type.text - operations_xml = ''.join([ElementTree.tostring(operation) + operations_xml = ''.join([ElementTree.tostring(operation).decode('utf-8') for operation in method]) # Force removal of this line, which suds produces. operations_xml = operations_xml.replace( @@ -812,7 +769,7 @@ def _GetRawOperationsFromXML(self, raw_request_xml): Raises: AttributeError: if the provided XML isn't from AdWords. """ - root = ElementTree.fromstring(raw_request_xml.encode('utf-8')) + root = ElementTree.fromstring(raw_request_xml) return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( './/') diff --git a/googleads/common.py b/googleads/common.py index 78ff9ecd..10626cec 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -28,7 +28,7 @@ import googleads.oauth2 import googleads.patches -VERSION = '3.14.0' +VERSION = '3.15.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _PROXY_YAML_KEY = 'proxy_info' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 9153bae5..af7691a9 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -495,12 +495,14 @@ def GenerateValidUnicodeRequest(self, operations): """ ops = self.GenerateUnicodeBudgetOperations(operations) method = 'mutate' - ops_xml = ''.join([self.OPERATIONS_TEMPLATE.decode('utf-8') % ( - op[u'operator'], op[u'xsi_type'], + ops_xml = ''.join([self.OPERATIONS_TEMPLATE % ( + op['operator'], op['xsi_type'], self.ExpandOperandTemplate('BudgetOperation', op['operand']) ) for op in ops]) - request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % ( - self.version, self.version, method, ops_xml, method) + + request = (self.RAW_API_REQUEST_TEMPLATE % ( + self.version, self.version, method, ops_xml, method)).encode('utf-8') + return (ops, request) def GenerateUnicodeBudgetOperations(self, operations): @@ -513,13 +515,13 @@ def GenerateUnicodeBudgetOperations(self, operations): A list of dictionaries containing distinct BudgetOperations. """ return [{ - u'operator': u'ADD', - u'xsi_type': u'BudgetOperation', - u'operand': { - u'budgetId': str(i).decode('utf-8'), - u'name': u'アングリーバード Batch budget #%s' % i, - u'amount': {u'microAmount': str(3333333 * i).decode('utf-8')}, - u'deliveryMethod': u'STANDARD'} + 'operator': 'ADD', + 'xsi_type': 'BudgetOperation', + 'operand': { + 'budgetId': str(i), + 'name': u'アングリーバード Batch budget #%d' % i, + 'amount': {'microAmount': str(3333333 * i)}, + 'deliveryMethod': 'STANDARD'} } for i in range(1, operations + 1)] def testGetPaddingLength(self): @@ -1154,7 +1156,6 @@ def testParseResponse(self): end_date = '20371230' budget_id = '2' budget_name = 'Test Budget' - period = 'DAILY' micro_amount = '50000000' delivery_method = 'STANDARD' is_explicitly_shared = 'true' @@ -1163,13 +1164,9 @@ def testParseResponse(self): response = ( self.response_parser.ParseResponse( self.API_RESPONSE_XML_TEMPLATE % - (campaign_id, name, status, - serving_status, start_date, - end_date, budget_id, - budget_name, period, - micro_amount, delivery_method, - is_explicitly_shared, - bidding_strategy_type)) + (campaign_id, name, status, serving_status, start_date, end_date, + budget_id, budget_name, micro_amount, delivery_method, + is_explicitly_shared, bidding_strategy_type)) ['mutateResponse']['rval']) # Assert that we correct parsed the response (2 results: Budget & Campaign) @@ -1199,7 +1196,6 @@ def testParseUnicodeResponse(self): end_date = u'20371230' budget_id = u'2' budget_name = u'Test Budget' - period = u'DAILY' micro_amount = u'50000000' delivery_method = u'STANDARD' is_explicitly_shared = u'true' @@ -1208,13 +1204,9 @@ def testParseUnicodeResponse(self): response = ( self.response_parser.ParseResponse( self.API_RESPONSE_XML_TEMPLATE % - (campaign_id, name, status, - serving_status, start_date, - end_date, budget_id, - budget_name, period, - micro_amount, delivery_method, - is_explicitly_shared, - bidding_strategy_type)) + (campaign_id, name, status, serving_status, start_date, end_date, + budget_id, budget_name, micro_amount, delivery_method, + is_explicitly_shared, bidding_strategy_type)) ['mutateResponse']['rval']) self.assertTrue(len(response) == 2) From 23a38a3b839ebfda04ef192ff723d982f475a4f8 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 11 Apr 2016 12:09:53 -0400 Subject: [PATCH 034/180] Commiting latest changes. From 5820c980f4733606c93149e62e7a6737785eda6d Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 17 May 2016 12:42:49 -0400 Subject: [PATCH 035/180] adding support for v201605 of the DFP API --- ChangeLog | 10 + .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 2 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_a_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 2 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../get_content_by_category.py | 6 +- .../creative_service/__init__.py | 0 .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 8 +- .../create_native_creative.py | 135 +++++ .../creative_service/get_all_creatives.py | 2 +- .../get_creatives_by_statement.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_by_statement.py | 2 +- .../update_creative_set.py | 2 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_creative_templates_by_statement.py | 2 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 2 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 2 +- .../get_all_line_item_custom_fields.py | 2 +- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 2 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- .../get_custom_targeting_keys_by_statement.py | 2 +- ...et_custom_targeting_values_by_statement.py | 2 +- .../update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_by_currency_code.py | 2 +- .../update_exchange_rates.py | 2 +- .../get_availability_forecast.py | 15 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 6 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 3 +- .../get_ad_unit_hierarchy.py | 2 +- .../get_all_ad_unit_sizes.py | 2 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 4 +- .../inventory_service/update_ad_units.py | 2 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../label_service/get_all_labels.py | 2 +- .../label_service/get_labels_by_statement.py | 2 +- .../label_service/update_labels.py | 2 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 2 +- .../get_all_licas.py | 2 +- .../get_licas_by_statement.py | 2 +- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 2 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_by_statement.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 2 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 2 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_by_statement.py | 2 +- .../order_service/update_orders.py | 2 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../get_placements_by_statement.py | 2 +- .../placement_service/update_placements.py | 2 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_a_rate_card.py | 2 +- .../update_premium_rates.py | 2 +- .../product_service/__init__.py | 0 .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- .../product_service/update_products.py | 2 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 2 +- .../create_product_templates.py | 32 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 6 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 2 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 2 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_proposals_by_statement.py | 2 +- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 2 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_geo_targets.py | 4 +- .../get_line_items_named_like.py | 2 +- .../rate_card_service/__init__.py | 0 .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_rate_cards_priced_with_currency.py | 2 +- .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 16 +- .../report_service/run_inventory_report.py | 4 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 4 +- .../report_service/run_sales_report.py | 2 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 2 +- .../get_suggested_ad_units_by_statement.py | 2 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 2 +- .../team_service/get_teams_by_statement.py | 2 +- .../team_service/update_teams.py | 2 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 3 +- .../user_service/deactivate_users.py | 2 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 2 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_users_by_statement.py | 2 +- .../user_service/update_users.py | 2 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 2 +- ...workflow_approval_requests_by_statement.py | 2 +- ...xternal_condition_requests_by_statement.py | 2 +- ...er_workflow_external_condition_requests.py | 2 +- googleads.yaml | 23 +- googleads/adwords.py | 45 +- googleads/common.py | 231 +++++++- googleads/dfp.py | 35 +- googleads/oauth2.py | 43 +- tests/adwords_test.py | 173 ++++-- tests/common_test.py | 507 +++++++++++++++--- tests/dfp_test.py | 60 ++- tests/oauth2_test.py | 50 +- 209 files changed, 1245 insertions(+), 494 deletions(-) rename examples/dfp/{v201505 => v201605}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201505 => v201605}/activity_group_service/get_active_activity_groups.py (97%) rename examples/dfp/{v201505 => v201605}/activity_group_service/get_all_activity_groups.py (96%) rename examples/dfp/{v201505 => v201605}/activity_group_service/update_activity_groups.py (97%) rename examples/dfp/{v201505 => v201605}/activity_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/activity_service/create_activities.py (99%) rename examples/dfp/{v201505 => v201605}/activity_service/get_active_activities.py (99%) rename examples/dfp/{v201505 => v201605}/activity_service/get_all_activities.py (99%) rename examples/dfp/{v201505 => v201605}/activity_service/update_activities.py (99%) rename examples/dfp/{v201505 => v201605}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/audience_segment_service/create_audience_segments.py (98%) rename examples/dfp/{v201505 => v201605}/audience_segment_service/get_all_audience_segments.py (97%) rename examples/dfp/{v201505 => v201605}/audience_segment_service/get_first_party_audience_segments.py (97%) rename examples/dfp/{v201505 => v201605}/audience_segment_service/populate_first_party_audience_segments.py (97%) rename examples/dfp/{v201505 => v201605}/audience_segment_service/update_audience_segments.py (98%) rename examples/dfp/{v201505 => v201605}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201505 => v201605}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201505 => v201605}/base_rate_service/get_all_base_rates.py (99%) rename examples/dfp/{v201505 => v201605}/base_rate_service/get_base_rates_for_a_rate_card.py (99%) rename examples/dfp/{v201505 => v201605}/base_rate_service/update_base_rates.py (99%) rename examples/dfp/{v201505 => v201605}/company_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/company_service/create_companies.py (99%) rename examples/dfp/{v201505 => v201605}/company_service/get_advertisers.py (99%) rename examples/dfp/{v201505 => v201605}/company_service/get_all_companies.py (99%) rename examples/dfp/{v201505 => v201605}/company_service/update_companies.py (99%) rename examples/dfp/{v201505 => v201605}/contact_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201505 => v201605}/contact_service/get_all_contacts.py (99%) rename examples/dfp/{v201505 => v201605}/contact_service/get_uninvited_contacts.py (99%) rename examples/dfp/{v201505 => v201605}/contact_service/update_contacts.py (99%) rename examples/dfp/{v201505 => v201605}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201505 => v201605}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201505 => v201605}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201505 => v201605}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (98%) rename examples/dfp/{v201505 => v201605}/content_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/content_service/get_all_content.py (99%) rename examples/dfp/{v201505 => v201605}/content_service/get_content_by_category.py (98%) rename examples/dfp/{v201505 => v201605}/creative_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201505 => v201605}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201505 => v201605}/creative_service/create_custom_creative.py (94%) create mode 100755 examples/dfp/v201605/creative_service/create_native_creative.py rename examples/dfp/{v201505 => v201605}/creative_service/get_all_creatives.py (99%) rename examples/dfp/{v201505 => v201605}/creative_service/get_creatives_by_statement.py (99%) rename examples/dfp/{v201505 => v201605}/creative_service/update_creatives.py (99%) rename examples/dfp/{v201505 => v201605}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201505 => v201605}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201505 => v201605}/creative_set_service/get_all_creative_sets.py (96%) rename examples/dfp/{v201505 => v201605}/creative_set_service/get_creative_sets_by_statement.py (97%) rename examples/dfp/{v201505 => v201605}/creative_set_service/update_creative_set.py (97%) rename examples/dfp/{v201505 => v201605}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/creative_template_service/get_all_creative_templates.py (97%) rename examples/dfp/{v201505 => v201605}/creative_template_service/get_creative_templates_by_statement.py (97%) rename examples/dfp/{v201505 => v201605}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/dfp/{v201505 => v201605}/creative_wrapper_service/deactivate_creative_wrapper.py (97%) rename examples/dfp/{v201505 => v201605}/creative_wrapper_service/get_active_creative_wrappers.py (97%) rename examples/dfp/{v201505 => v201605}/creative_wrapper_service/get_all_creative_wrappers.py (96%) rename examples/dfp/{v201505 => v201605}/creative_wrapper_service/update_creative_wrappers.py (97%) rename examples/dfp/{v201505 => v201605}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201505 => v201605}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201505 => v201605}/custom_field_service/deactivate_all_line_item_custom_fields.py (98%) rename examples/dfp/{v201505 => v201605}/custom_field_service/get_all_custom_fields.py (97%) rename examples/dfp/{v201505 => v201605}/custom_field_service/get_all_line_item_custom_fields.py (97%) rename examples/dfp/{v201505 => v201605}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201505 => v201605}/custom_field_service/update_custom_fields.py (98%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/delete_custom_targeting_keys.py (98%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/delete_custom_targeting_values.py (98%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/get_custom_targeting_keys_by_statement.py (97%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/get_custom_targeting_values_by_statement.py (97%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/update_custom_targeting_keys.py (97%) rename examples/dfp/{v201505 => v201605}/custom_targeting_service/update_custom_targeting_values.py (97%) rename examples/dfp/{v201505 => v201605}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201505 => v201605}/exchange_rate_service/get_all_exchange_rates.py (96%) rename examples/dfp/{v201505 => v201605}/exchange_rate_service/get_exchange_rates_by_currency_code.py (97%) rename examples/dfp/{v201505 => v201605}/exchange_rate_service/update_exchange_rates.py (97%) rename examples/dfp/{v201505 => v201605}/forecast_service/get_availability_forecast.py (91%) rename examples/dfp/{v201505 => v201605}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/dfp/{v201505 => v201605}/forecast_service/get_delivery_forecast_for_line_items.py (94%) rename examples/dfp/{v201505 => v201605}/inventory_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/inventory_service/archive_ad_units.py (99%) rename examples/dfp/{v201505 => v201605}/inventory_service/create_ad_units.py (97%) rename examples/dfp/{v201505 => v201605}/inventory_service/get_ad_unit_hierarchy.py (99%) rename examples/dfp/{v201505 => v201605}/inventory_service/get_all_ad_unit_sizes.py (99%) rename examples/dfp/{v201505 => v201605}/inventory_service/get_all_ad_units.py (99%) rename examples/dfp/{v201505 => v201605}/inventory_service/get_top_level_ad_units.py (98%) rename examples/dfp/{v201505 => v201605}/inventory_service/update_ad_units.py (99%) rename examples/dfp/{v201505 => v201605}/label_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/label_service/create_labels.py (99%) rename examples/dfp/{v201505 => v201605}/label_service/deactivate_labels.py (99%) rename examples/dfp/{v201505 => v201605}/label_service/get_all_labels.py (99%) rename examples/dfp/{v201505 => v201605}/label_service/get_labels_by_statement.py (99%) rename examples/dfp/{v201505 => v201605}/label_service/update_labels.py (99%) rename examples/dfp/{v201505 => v201605}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201505 => v201605}/line_item_creative_association_service/deactivate_licas.py (97%) rename examples/dfp/{v201505 => v201605}/line_item_creative_association_service/get_all_licas.py (96%) rename examples/dfp/{v201505 => v201605}/line_item_creative_association_service/get_licas_by_statement.py (97%) rename examples/dfp/{v201505 => v201605}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201505 => v201605}/line_item_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/line_item_service/activate_line_items.py (99%) rename examples/dfp/{v201505 => v201605}/line_item_service/create_line_items.py (99%) rename examples/dfp/{v201505 => v201605}/line_item_service/create_video_line_item.py (99%) rename examples/dfp/{v201505 => v201605}/line_item_service/get_all_line_items.py (99%) rename examples/dfp/{v201505 => v201605}/line_item_service/get_line_items_by_statement.py (99%) rename examples/dfp/{v201505 => v201605}/line_item_service/get_recently_updated_line_items.py (99%) rename examples/dfp/{v201505 => v201605}/line_item_service/target_custom_criteria.py (99%) rename examples/dfp/{v201505 => v201605}/line_item_service/update_line_items.py (99%) rename examples/dfp/{v201505 => v201605}/network_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/network_service/get_all_networks.py (99%) rename examples/dfp/{v201505 => v201605}/network_service/get_current_network.py (99%) rename examples/dfp/{v201505 => v201605}/network_service/make_test_network.py (99%) rename examples/dfp/{v201505 => v201605}/order_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/order_service/approve_orders.py (99%) rename examples/dfp/{v201505 => v201605}/order_service/create_orders.py (99%) rename examples/dfp/{v201505 => v201605}/order_service/get_all_orders.py (99%) rename examples/dfp/{v201505 => v201605}/order_service/get_orders_by_statement.py (99%) rename examples/dfp/{v201505 => v201605}/order_service/update_orders.py (99%) rename examples/dfp/{v201505 => v201605}/placement_service/create_placements.py (99%) rename examples/dfp/{v201505 => v201605}/placement_service/deactivate_placements.py (99%) rename examples/dfp/{v201505 => v201605}/placement_service/get_all_placements.py (99%) rename examples/dfp/{v201505 => v201605}/placement_service/get_placements_by_statement.py (99%) rename examples/dfp/{v201505 => v201605}/placement_service/update_placements.py (99%) rename examples/dfp/{v201505 => v201605}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/premium_rate_service/create_premium_rates.py (97%) rename examples/dfp/{v201505 => v201605}/premium_rate_service/get_all_premium_rates.py (96%) rename examples/dfp/{v201505 => v201605}/premium_rate_service/get_premium_rates_for_a_rate_card.py (97%) rename examples/dfp/{v201505 => v201605}/premium_rate_service/update_premium_rates.py (97%) rename examples/dfp/{v201505 => v201605}/product_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/product_service/get_all_products.py (99%) rename examples/dfp/{v201505 => v201605}/product_service/get_products_for_product_template.py (99%) rename examples/dfp/{v201505 => v201605}/product_service/update_products.py (99%) rename examples/dfp/{v201505 => v201605}/product_template_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/product_template_service/activate_product_templates.py (97%) rename examples/dfp/{v201505 => v201605}/product_template_service/create_product_templates.py (82%) rename examples/dfp/{v201505 => v201605}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201505 => v201605}/product_template_service/get_sponsorship_product_templates.py (97%) rename examples/dfp/{v201505 => v201605}/product_template_service/update_product_templates.py (94%) rename examples/dfp/{v201505 => v201605}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/proposal_line_item_service/archive_proposal_line_items.py (98%) rename examples/dfp/{v201505 => v201605}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/dfp/{v201505 => v201605}/proposal_line_item_service/get_all_proposal_line_items.py (97%) rename examples/dfp/{v201505 => v201605}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (98%) rename examples/dfp/{v201505 => v201605}/proposal_line_item_service/update_proposal_line_items.py (97%) rename examples/dfp/{v201505 => v201605}/proposal_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/proposal_service/create_proposals.py (99%) rename examples/dfp/{v201505 => v201605}/proposal_service/get_all_proposals.py (99%) rename examples/dfp/{v201505 => v201605}/proposal_service/get_proposals_by_statement.py (99%) rename examples/dfp/{v201505 => v201605}/proposal_service/submit_proposals_for_approval.py (99%) rename examples/dfp/{v201505 => v201605}/proposal_service/update_proposals.py (99%) rename examples/dfp/{v201505 => v201605}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/dfp/{v201505 => v201605}/publisher_query_language_service/get_geo_targets.py (94%) rename examples/dfp/{v201505 => v201605}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/dfp/{v201505 => v201605}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/rate_card_service/get_all_rate_cards.py (99%) rename examples/dfp/{v201505 => v201605}/rate_card_service/get_rate_cards_priced_with_currency.py (99%) rename examples/dfp/{v201505 => v201605}/report_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/report_service/run_delivery_report.py (81%) rename examples/dfp/{v201505 => v201605}/report_service/run_inventory_report.py (97%) rename examples/dfp/{v201505 => v201605}/report_service/run_reach_report.py (96%) rename examples/dfp/{v201505 => v201605}/report_service/run_report_with_custom_fields.py (97%) rename examples/dfp/{v201505 => v201605}/report_service/run_sales_report.py (96%) rename examples/dfp/{v201505 => v201605}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/dfp/{v201505 => v201605}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) rename examples/dfp/{v201505 => v201605}/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py (97%) rename examples/dfp/{v201505 => v201605}/team_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/team_service/create_teams.py (96%) rename examples/dfp/{v201505 => v201605}/team_service/get_all_teams.py (96%) rename examples/dfp/{v201505 => v201605}/team_service/get_teams_by_statement.py (96%) rename examples/dfp/{v201505 => v201605}/team_service/update_teams.py (97%) rename examples/dfp/{v201505 => v201605}/user_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/user_service/create_users.py (94%) rename examples/dfp/{v201505 => v201605}/user_service/deactivate_users.py (97%) rename examples/dfp/{v201505 => v201605}/user_service/get_all_roles.py (95%) rename examples/dfp/{v201505 => v201605}/user_service/get_all_users.py (95%) rename examples/dfp/{v201505 => v201605}/user_service/get_current_user.py (94%) rename examples/dfp/{v201505 => v201605}/user_service/get_users_by_statement.py (96%) rename examples/dfp/{v201505 => v201605}/user_service/update_users.py (96%) rename examples/dfp/{v201505 => v201605}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201505 => v201605}/user_team_association_service/delete_user_team_associations.py (98%) rename examples/dfp/{v201505 => v201605}/user_team_association_service/get_all_user_team_associations.py (97%) rename examples/dfp/{v201505 => v201605}/user_team_association_service/get_user_team_associations_for_user.py (97%) rename examples/dfp/{v201505 => v201605}/user_team_association_service/update_user_team_associations.py (98%) rename examples/dfp/{v201505 => v201605}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201505 => v201605}/workflow_request_service/approve_workflow_approval_requests.py (97%) rename examples/dfp/{v201505 => v201605}/workflow_request_service/get_workflow_approval_requests_by_statement.py (96%) rename examples/dfp/{v201505 => v201605}/workflow_request_service/get_workflow_external_condition_requests_by_statement.py (97%) rename examples/dfp/{v201505 => v201605}/workflow_request_service/trigger_workflow_external_condition_requests.py (98%) diff --git a/ChangeLog b/ChangeLog index 0285850a..d187b16c 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,13 @@ +4.0.0 -- 5/17/2016 +* Add support for DFP v201605. +* Removed examples for DFP v201505. +* Removed support for DFP v201502. +* Improved proxy support. +* BREAKING CHANGE: The googleads.common.LoadFromStorage function has been + updated to accommodate the current proxy support. This will break users with + a proxy configured. Check out the changes in our sample googleads.yaml file + to see the new format. + 3.15.0 -- 4/11/2016 * Removed support for AdWords v201506. * Resolved issues: diff --git a/examples/dfp/v201505/activity_group_service/__init__.py b/examples/dfp/v201605/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201505/activity_group_service/__init__.py rename to examples/dfp/v201605/activity_group_service/__init__.py diff --git a/examples/dfp/v201505/activity_group_service/create_activity_groups.py b/examples/dfp/v201605/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201505/activity_group_service/create_activity_groups.py rename to examples/dfp/v201605/activity_group_service/create_activity_groups.py index 65358edd..79c5bdc9 100755 --- a/examples/dfp/v201505/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201605/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201505') + version='v201605') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201505/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201605/activity_group_service/get_active_activity_groups.py similarity index 97% rename from examples/dfp/v201505/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201605/activity_group_service/get_active_activity_groups.py index 61b317da..e47f391c 100755 --- a/examples/dfp/v201505/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201605/activity_group_service/get_active_activity_groups.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201505') + version='v201605') # Create statement object to only select active activity groups. values = [{ diff --git a/examples/dfp/v201505/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201605/activity_group_service/get_all_activity_groups.py similarity index 96% rename from examples/dfp/v201505/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201605/activity_group_service/get_all_activity_groups.py index 0a709e07..0b1592b2 100755 --- a/examples/dfp/v201505/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201605/activity_group_service/get_all_activity_groups.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201505') + version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/activity_group_service/update_activity_groups.py b/examples/dfp/v201605/activity_group_service/update_activity_groups.py similarity index 97% rename from examples/dfp/v201505/activity_group_service/update_activity_groups.py rename to examples/dfp/v201605/activity_group_service/update_activity_groups.py index ceb9e994..d7a21f29 100755 --- a/examples/dfp/v201505/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201605/activity_group_service/update_activity_groups.py @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201505') + version='v201605') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201505/activity_service/__init__.py b/examples/dfp/v201605/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201505/activity_service/__init__.py rename to examples/dfp/v201605/activity_service/__init__.py diff --git a/examples/dfp/v201505/activity_service/create_activities.py b/examples/dfp/v201605/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201505/activity_service/create_activities.py rename to examples/dfp/v201605/activity_service/create_activities.py index 10d59362..d5f30f3d 100755 --- a/examples/dfp/v201505/activity_service/create_activities.py +++ b/examples/dfp/v201605/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201505') + activity_service = client.GetService('ActivityService', version='v201605') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201505/activity_service/get_active_activities.py b/examples/dfp/v201605/activity_service/get_active_activities.py similarity index 99% rename from examples/dfp/v201505/activity_service/get_active_activities.py rename to examples/dfp/v201605/activity_service/get_active_activities.py index bf94bedf..dc7bcaeb 100755 --- a/examples/dfp/v201505/activity_service/get_active_activities.py +++ b/examples/dfp/v201605/activity_service/get_active_activities.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201505') + activity_service = client.GetService('ActivityService', version='v201605') # Create statement object to only select active activities. values = [{ diff --git a/examples/dfp/v201505/activity_service/get_all_activities.py b/examples/dfp/v201605/activity_service/get_all_activities.py similarity index 99% rename from examples/dfp/v201505/activity_service/get_all_activities.py rename to examples/dfp/v201605/activity_service/get_all_activities.py index db0241ea..80642b6e 100755 --- a/examples/dfp/v201505/activity_service/get_all_activities.py +++ b/examples/dfp/v201605/activity_service/get_all_activities.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201505') + activity_service = client.GetService('ActivityService', version='v201605') # Create statement object to select only all activities. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/activity_service/update_activities.py b/examples/dfp/v201605/activity_service/update_activities.py similarity index 99% rename from examples/dfp/v201505/activity_service/update_activities.py rename to examples/dfp/v201605/activity_service/update_activities.py index 6f0a722a..8abefc6d 100755 --- a/examples/dfp/v201505/activity_service/update_activities.py +++ b/examples/dfp/v201605/activity_service/update_activities.py @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201505') + activity_service = client.GetService('ActivityService', version='v201605') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201505/audience_segment_service/__init__.py b/examples/dfp/v201605/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201505/audience_segment_service/__init__.py rename to examples/dfp/v201605/audience_segment_service/__init__.py diff --git a/examples/dfp/v201505/audience_segment_service/create_audience_segments.py b/examples/dfp/v201605/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/dfp/v201505/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201605/audience_segment_service/create_audience_segments.py index 29fb5f80..864507fa 100755 --- a/examples/dfp/v201505/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/create_audience_segments.py @@ -32,8 +32,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201505') - network_service = client.GetService('NetworkService', version='v201505') + 'AudienceSegmentService', version='v201605') + network_service = client.GetService('NetworkService', version='v201605') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py similarity index 97% rename from examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py index da60d96f..173be58d 100755 --- a/examples/dfp/v201505/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201505') + 'AudienceSegmentService', version='v201605') # Create statement object to select all audience segments. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py similarity index 97% rename from examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py index b7d55dc8..51a07904 100755 --- a/examples/dfp/v201505/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201505') + 'AudienceSegmentService', version='v201605') # Create statement object to only select first party audience segments. values = [{ diff --git a/examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py similarity index 97% rename from examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py index a8cb293e..467681b5 100755 --- a/examples/dfp/v201505/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py @@ -33,7 +33,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201505') + 'AudienceSegmentService', version='v201605') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201505/audience_segment_service/update_audience_segments.py b/examples/dfp/v201605/audience_segment_service/update_audience_segments.py similarity index 98% rename from examples/dfp/v201505/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201605/audience_segment_service/update_audience_segments.py index 1fefe15b..7f09df0d 100755 --- a/examples/dfp/v201505/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/update_audience_segments.py @@ -32,7 +32,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201505') + 'AudienceSegmentService', version='v201605') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201505/base_rate_service/__init__.py b/examples/dfp/v201605/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201505/base_rate_service/__init__.py rename to examples/dfp/v201605/base_rate_service/__init__.py diff --git a/examples/dfp/v201505/base_rate_service/create_product_base_rates.py b/examples/dfp/v201605/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201505/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201605/base_rate_service/create_product_base_rates.py index 18f25cf3..e4005425 100755 --- a/examples/dfp/v201505/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201605/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201505') + 'BaseRateService', version='v201605') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201605/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201605/base_rate_service/create_product_template_base_rates.py index fa37f438..efd4dd08 100755 --- a/examples/dfp/v201505/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201605/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201505') + 'BaseRateService', version='v201605') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201505/base_rate_service/get_all_base_rates.py b/examples/dfp/v201605/base_rate_service/get_all_base_rates.py similarity index 99% rename from examples/dfp/v201505/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201605/base_rate_service/get_all_base_rates.py index 0831f26b..6918d1a2 100755 --- a/examples/dfp/v201505/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201605/base_rate_service/get_all_base_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201505') + base_rate_service = client.GetService('BaseRateService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201605/base_rate_service/get_base_rates_for_a_rate_card.py similarity index 99% rename from examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py rename to examples/dfp/v201605/base_rate_service/get_base_rates_for_a_rate_card.py index ebdcec39..5b9e610e 100755 --- a/examples/dfp/v201505/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201605/base_rate_service/get_base_rates_for_a_rate_card.py @@ -31,7 +31,7 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201505') + base_rate_service = client.GetService('BaseRateService', version='v201605') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201505/base_rate_service/update_base_rates.py b/examples/dfp/v201605/base_rate_service/update_base_rates.py similarity index 99% rename from examples/dfp/v201505/base_rate_service/update_base_rates.py rename to examples/dfp/v201605/base_rate_service/update_base_rates.py index 77674d35..34147f30 100755 --- a/examples/dfp/v201505/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201605/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201505') + base_rate_service = client.GetService('BaseRateService', version='v201605') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201505/company_service/__init__.py b/examples/dfp/v201605/company_service/__init__.py similarity index 100% rename from examples/dfp/v201505/company_service/__init__.py rename to examples/dfp/v201605/company_service/__init__.py diff --git a/examples/dfp/v201505/company_service/create_companies.py b/examples/dfp/v201605/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201505/company_service/create_companies.py rename to examples/dfp/v201605/company_service/create_companies.py index 9041634b..e1ea337a 100755 --- a/examples/dfp/v201505/company_service/create_companies.py +++ b/examples/dfp/v201605/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201505') + company_service = client.GetService('CompanyService', version='v201605') # Create company objects. companies = [ diff --git a/examples/dfp/v201505/company_service/get_advertisers.py b/examples/dfp/v201605/company_service/get_advertisers.py similarity index 99% rename from examples/dfp/v201505/company_service/get_advertisers.py rename to examples/dfp/v201605/company_service/get_advertisers.py index 6b3f9dc9..4c66ebad 100755 --- a/examples/dfp/v201505/company_service/get_advertisers.py +++ b/examples/dfp/v201605/company_service/get_advertisers.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201505') + company_service = client.GetService('CompanyService', version='v201605') # Create statement object to only select companies that are advertisers. values = [{ diff --git a/examples/dfp/v201505/company_service/get_all_companies.py b/examples/dfp/v201605/company_service/get_all_companies.py similarity index 99% rename from examples/dfp/v201505/company_service/get_all_companies.py rename to examples/dfp/v201605/company_service/get_all_companies.py index 46a1b9dc..e3f361f9 100755 --- a/examples/dfp/v201505/company_service/get_all_companies.py +++ b/examples/dfp/v201605/company_service/get_all_companies.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201505') + company_service = client.GetService('CompanyService', version='v201605') # Create statement object to select all companies. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/company_service/update_companies.py b/examples/dfp/v201605/company_service/update_companies.py similarity index 99% rename from examples/dfp/v201505/company_service/update_companies.py rename to examples/dfp/v201605/company_service/update_companies.py index 15e20da1..3ec15248 100755 --- a/examples/dfp/v201505/company_service/update_companies.py +++ b/examples/dfp/v201605/company_service/update_companies.py @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201505') + company_service = client.GetService('CompanyService', version='v201605') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201505/contact_service/__init__.py b/examples/dfp/v201605/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201505/contact_service/__init__.py rename to examples/dfp/v201605/contact_service/__init__.py diff --git a/examples/dfp/v201505/contact_service/create_contacts.py b/examples/dfp/v201605/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201505/contact_service/create_contacts.py rename to examples/dfp/v201605/contact_service/create_contacts.py index 11daf677..8a36cb8e 100755 --- a/examples/dfp/v201505/contact_service/create_contacts.py +++ b/examples/dfp/v201605/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201505') + contact_service = client.GetService('ContactService', version='v201605') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201505/contact_service/get_all_contacts.py b/examples/dfp/v201605/contact_service/get_all_contacts.py similarity index 99% rename from examples/dfp/v201505/contact_service/get_all_contacts.py rename to examples/dfp/v201605/contact_service/get_all_contacts.py index 5ca9356c..96b1da55 100755 --- a/examples/dfp/v201505/contact_service/get_all_contacts.py +++ b/examples/dfp/v201605/contact_service/get_all_contacts.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201505') + contact_service = client.GetService('ContactService', version='v201605') # Create statement object to get all contacts. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/contact_service/get_uninvited_contacts.py b/examples/dfp/v201605/contact_service/get_uninvited_contacts.py similarity index 99% rename from examples/dfp/v201505/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201605/contact_service/get_uninvited_contacts.py index d3c16423..dd3929c4 100755 --- a/examples/dfp/v201505/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201605/contact_service/get_uninvited_contacts.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201505') + contact_service = client.GetService('ContactService', version='v201605') # Create statement object to only select contacts that are uninvited. values = [{ diff --git a/examples/dfp/v201505/contact_service/update_contacts.py b/examples/dfp/v201605/contact_service/update_contacts.py similarity index 99% rename from examples/dfp/v201505/contact_service/update_contacts.py rename to examples/dfp/v201605/contact_service/update_contacts.py index 99eca358..afc37eb9 100755 --- a/examples/dfp/v201505/contact_service/update_contacts.py +++ b/examples/dfp/v201605/contact_service/update_contacts.py @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201505') + contact_service = client.GetService('ContactService', version='v201605') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201605/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201505/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201605/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201605/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201605/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 7b10dea0..5e08ef12 100755 --- a/examples/dfp/v201505/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201605/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201505') + 'ContentMetadataKeyHierarchyService', version='v201605') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201605/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201605/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 0d86e096..cbacd5d0 100755 --- a/examples/dfp/v201505/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201605/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201505') + 'ContentMetadataKeyHierarchyService', version='v201605') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201605/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201605/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 5fdd83f1..1636e052 100755 --- a/examples/dfp/v201505/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201605/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201505') + 'ContentMetadataKeyHierarchyService', version='v201605') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201605/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 98% rename from examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201605/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index eab54bf5..9608dc9e 100755 --- a/examples/dfp/v201505/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201605/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201505') + 'ContentMetadataKeyHierarchyService', version='v201605') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201505/content_service/__init__.py b/examples/dfp/v201605/content_service/__init__.py similarity index 100% rename from examples/dfp/v201505/content_service/__init__.py rename to examples/dfp/v201605/content_service/__init__.py diff --git a/examples/dfp/v201505/content_service/get_all_content.py b/examples/dfp/v201605/content_service/get_all_content.py similarity index 99% rename from examples/dfp/v201505/content_service/get_all_content.py rename to examples/dfp/v201605/content_service/get_all_content.py index 0541cdec..7347e940 100755 --- a/examples/dfp/v201505/content_service/get_all_content.py +++ b/examples/dfp/v201605/content_service/get_all_content.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201505') + content_service = client.GetService('ContentService', version='v201605') # Create statement object to select all content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/content_service/get_content_by_category.py b/examples/dfp/v201605/content_service/get_content_by_category.py similarity index 98% rename from examples/dfp/v201505/content_service/get_content_by_category.py rename to examples/dfp/v201605/content_service/get_content_by_category.py index 574069ef..b8f3c805 100755 --- a/examples/dfp/v201505/content_service/get_content_by_category.py +++ b/examples/dfp/v201605/content_service/get_content_by_category.py @@ -33,10 +33,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201505') - network_service = client.GetService('NetworkService', version='v201505') + content_service = client.GetService('ContentService', version='v201605') + network_service = client.GetService('NetworkService', version='v201605') custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') # Get the network's content browse custom targeting key. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201505/creative_service/__init__.py b/examples/dfp/v201605/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201505/creative_service/__init__.py rename to examples/dfp/v201605/creative_service/__init__.py diff --git a/examples/dfp/v201505/creative_service/create_creative_from_template.py b/examples/dfp/v201605/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201505/creative_service/create_creative_from_template.py rename to examples/dfp/v201605/creative_service/create_creative_from_template.py index 64c4f434..9134d94e 100755 --- a/examples/dfp/v201505/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201605/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201505') + creative_service = client.GetService('CreativeService', version='v201605') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201505/creative_service/create_creatives.py b/examples/dfp/v201605/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201505/creative_service/create_creatives.py rename to examples/dfp/v201605/creative_service/create_creatives.py index 639374bd..48fee463 100755 --- a/examples/dfp/v201505/creative_service/create_creatives.py +++ b/examples/dfp/v201605/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201505') + creative_service = client.GetService('CreativeService', version='v201605') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201505/creative_service/create_custom_creative.py b/examples/dfp/v201605/creative_service/create_custom_creative.py similarity index 94% rename from examples/dfp/v201505/creative_service/create_custom_creative.py rename to examples/dfp/v201605/creative_service/create_custom_creative.py index d5fdfdb0..e465eae8 100755 --- a/examples/dfp/v201505/creative_service/create_custom_creative.py +++ b/examples/dfp/v201605/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201505') + creative_service = client.GetService('CreativeService', version='v201605') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', @@ -64,8 +64,10 @@ def main(client, advertiser_id): { 'xsi_type': 'CustomCreativeAsset', 'macroName': 'IMAGE_ASSET', - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() + 'asset': { + 'assetByteArray': image_data, + 'fileName': 'image%s.jpg' % uuid.uuid4() + } } ], 'htmlSnippet': html_snippet diff --git a/examples/dfp/v201605/creative_service/create_native_creative.py b/examples/dfp/v201605/creative_service/create_native_creative.py new file mode 100755 index 00000000..30dc8fec --- /dev/null +++ b/examples/dfp/v201605/creative_service/create_native_creative.py @@ -0,0 +1,135 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example creates a new native creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. + +The code in this example will use app data from the Google sample app +'Pie Noon': + +https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import urllib2 +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO' + 'PYnTdOQGaSpGSEZflIFs0iw=h300') +APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp' + 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300') + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201605') + + # Use the system defined native app install creative template. + creative_template_id = '10004400' + + image_data = urllib2.urlopen(ICON_URL).read() + image_data = base64.b64encode(image_data) + + app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() + app_icon_data = base64.b64encode(app_icon_data) + + # Create creative from templates. + creative = { + 'xsi_type': 'TemplateCreative', + 'name': 'Native Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '1', 'height': '1', 'isAspectRatio': False}, + 'creativeTemplateId': creative_template_id, + 'destinationUrl': ('https://play.google.com/store/apps/details?id=' + 'com.google.fpl.pie_noon'), + 'creativeTemplateVariableValues': [ + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Image', + 'asset': { + 'assetByteArray': image_data, + 'fileName': 'file%s.png' % uuid.uuid4() + } + }, + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Appicon', + 'asset': { + 'assetByteArray': app_icon_data, + 'fileName': 'appicon%s.png' % uuid.uuid4() + } + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Price', + 'value': 'Free' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Calltoaction', + 'value': 'Install' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Starrating', + 'value': '4' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Store', + 'value': 'Google Play' + }, + { + 'xsi_type': 'UrlCreativeTemplateVariableValue', + 'uniqueName': 'DeeplinkclickactionURL', + 'value': 'market://details?id=com.google.fpl.pie_noon' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Body', + 'value': 'Try multi-screen mode!' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Headline', + 'value': 'Pie Noon' + } + ] + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print ('Native creative with id \'%s\' and name \'%s\' was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], creative['previewUrl'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201505/creative_service/get_all_creatives.py b/examples/dfp/v201605/creative_service/get_all_creatives.py similarity index 99% rename from examples/dfp/v201505/creative_service/get_all_creatives.py rename to examples/dfp/v201605/creative_service/get_all_creatives.py index 5fb20564..d771703b 100755 --- a/examples/dfp/v201505/creative_service/get_all_creatives.py +++ b/examples/dfp/v201605/creative_service/get_all_creatives.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201505') + creative_service = client.GetService('CreativeService', version='v201605') # Create statement object to select all creatives. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/creative_service/get_creatives_by_statement.py b/examples/dfp/v201605/creative_service/get_creatives_by_statement.py similarity index 99% rename from examples/dfp/v201505/creative_service/get_creatives_by_statement.py rename to examples/dfp/v201605/creative_service/get_creatives_by_statement.py index 429bd019..8757a292 100755 --- a/examples/dfp/v201505/creative_service/get_creatives_by_statement.py +++ b/examples/dfp/v201605/creative_service/get_creatives_by_statement.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201505') + creative_service = client.GetService('CreativeService', version='v201605') # Create statement object to only select image creatives. values = [{ diff --git a/examples/dfp/v201505/creative_service/update_creatives.py b/examples/dfp/v201605/creative_service/update_creatives.py similarity index 99% rename from examples/dfp/v201505/creative_service/update_creatives.py rename to examples/dfp/v201605/creative_service/update_creatives.py index 2bdeb944..62da60f3 100755 --- a/examples/dfp/v201505/creative_service/update_creatives.py +++ b/examples/dfp/v201605/creative_service/update_creatives.py @@ -34,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201505') + creative_service = client.GetService('CreativeService', version='v201605') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201505/creative_set_service/__init__.py b/examples/dfp/v201605/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201505/creative_set_service/__init__.py rename to examples/dfp/v201605/creative_set_service/__init__.py diff --git a/examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201605/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201605/creative_set_service/associate_creative_set_to_line_item.py index 7d40a82b..2eeb0c80 100755 --- a/examples/dfp/v201505/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201605/creative_set_service/associate_creative_set_to_line_item.py @@ -38,7 +38,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201505') + 'LineItemCreativeAssociationService', version='v201605') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201505/creative_set_service/create_creative_set.py b/examples/dfp/v201605/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201505/creative_set_service/create_creative_set.py rename to examples/dfp/v201605/creative_set_service/create_creative_set.py index fcfd132a..fb833495 100755 --- a/examples/dfp/v201505/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201605/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201505') + version='v201605') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201505/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201605/creative_set_service/get_all_creative_sets.py similarity index 96% rename from examples/dfp/v201505/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201605/creative_set_service/get_all_creative_sets.py index b9c26ae5..acaf3dca 100755 --- a/examples/dfp/v201505/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201605/creative_set_service/get_all_creative_sets.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201505') + version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201605/creative_set_service/get_creative_sets_by_statement.py similarity index 97% rename from examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py rename to examples/dfp/v201605/creative_set_service/get_creative_sets_by_statement.py index f47d345a..06fb4141 100755 --- a/examples/dfp/v201505/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201605/creative_set_service/get_creative_sets_by_statement.py @@ -35,7 +35,7 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201505') + version='v201605') # Create statement object to only select creative sets that have the given # master creative. diff --git a/examples/dfp/v201505/creative_set_service/update_creative_set.py b/examples/dfp/v201605/creative_set_service/update_creative_set.py similarity index 97% rename from examples/dfp/v201505/creative_set_service/update_creative_set.py rename to examples/dfp/v201605/creative_set_service/update_creative_set.py index e371ad27..d5a40595 100755 --- a/examples/dfp/v201505/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201605/creative_set_service/update_creative_set.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201505') + version='v201605') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201505/creative_template_service/__init__.py b/examples/dfp/v201605/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201505/creative_template_service/__init__.py rename to examples/dfp/v201605/creative_template_service/__init__.py diff --git a/examples/dfp/v201505/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201605/creative_template_service/get_all_creative_templates.py similarity index 97% rename from examples/dfp/v201505/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201605/creative_template_service/get_all_creative_templates.py index 2adffb47..052325ff 100755 --- a/examples/dfp/v201505/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201605/creative_template_service/get_all_creative_templates.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201505') + 'CreativeTemplateService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201605/creative_template_service/get_creative_templates_by_statement.py similarity index 97% rename from examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py rename to examples/dfp/v201605/creative_template_service/get_creative_templates_by_statement.py index 59b14511..93d4befe 100755 --- a/examples/dfp/v201505/creative_template_service/get_creative_templates_by_statement.py +++ b/examples/dfp/v201605/creative_template_service/get_creative_templates_by_statement.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201505') + 'CreativeTemplateService', version='v201605') # Create statement object to only select system defined creative templates. values = [{ diff --git a/examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201605/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201605/creative_wrapper_service/create_creative_wrappers.py index fad612ad..bfbfbac4 100755 --- a/examples/dfp/v201505/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201605/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201505') + version='v201605') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201605/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 97% rename from examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201605/creative_wrapper_service/deactivate_creative_wrapper.py index 021e51ae..32c67123 100755 --- a/examples/dfp/v201505/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201605/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201505') + version='v201605') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201605/creative_wrapper_service/get_active_creative_wrappers.py similarity index 97% rename from examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201605/creative_wrapper_service/get_active_creative_wrappers.py index e84684c9..1a92e1c1 100755 --- a/examples/dfp/v201505/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201605/creative_wrapper_service/get_active_creative_wrappers.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201505') + version='v201605') # Create statement object to only select active creative wrappers. values = [{ diff --git a/examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201605/creative_wrapper_service/get_all_creative_wrappers.py similarity index 96% rename from examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201605/creative_wrapper_service/get_all_creative_wrappers.py index f417b64d..ba9bd354 100755 --- a/examples/dfp/v201505/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201605/creative_wrapper_service/get_all_creative_wrappers.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201505') + version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201605/creative_wrapper_service/update_creative_wrappers.py similarity index 97% rename from examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201605/creative_wrapper_service/update_creative_wrappers.py index b8d1e004..1eb8ae0e 100755 --- a/examples/dfp/v201505/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201605/creative_wrapper_service/update_creative_wrappers.py @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201505') + version='v201605') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201505/custom_field_service/__init__.py b/examples/dfp/v201605/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201505/custom_field_service/__init__.py rename to examples/dfp/v201605/custom_field_service/__init__.py diff --git a/examples/dfp/v201505/custom_field_service/create_custom_field_options.py b/examples/dfp/v201605/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201505/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201605/custom_field_service/create_custom_field_options.py index 254c0cc0..4835ec5c 100755 --- a/examples/dfp/v201505/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201605/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201505') + 'CustomFieldService', version='v201605') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201505/custom_field_service/create_custom_fields.py b/examples/dfp/v201605/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201505/custom_field_service/create_custom_fields.py rename to examples/dfp/v201605/custom_field_service/create_custom_fields.py index 0cd9bba1..2cff40e9 100755 --- a/examples/dfp/v201505/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201605/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201505') + 'CustomFieldService', version='v201605') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201605/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 98% rename from examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201605/custom_field_service/deactivate_all_line_item_custom_fields.py index 75d69423..34e8e152 100755 --- a/examples/dfp/v201505/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201605/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201505') + 'CustomFieldService', version='v201605') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201505/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201605/custom_field_service/get_all_custom_fields.py similarity index 97% rename from examples/dfp/v201505/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201605/custom_field_service/get_all_custom_fields.py index f75a7bec..140bd2fe 100755 --- a/examples/dfp/v201505/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201605/custom_field_service/get_all_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201505') + 'CustomFieldService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201605/custom_field_service/get_all_line_item_custom_fields.py similarity index 97% rename from examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py rename to examples/dfp/v201605/custom_field_service/get_all_line_item_custom_fields.py index 1c8930a7..0cca03b8 100755 --- a/examples/dfp/v201505/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201605/custom_field_service/get_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201505') + 'CustomFieldService', version='v201605') # Create statement to select only custom fields that apply to line items. values = [{ diff --git a/examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201605/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201605/custom_field_service/set_line_item_custom_field_value.py index 603c168b..45b651df 100755 --- a/examples/dfp/v201505/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201605/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201505') + 'CustomFieldService', version='v201605') - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201505/custom_field_service/update_custom_fields.py b/examples/dfp/v201605/custom_field_service/update_custom_fields.py similarity index 98% rename from examples/dfp/v201505/custom_field_service/update_custom_fields.py rename to examples/dfp/v201605/custom_field_service/update_custom_fields.py index bfa30c5c..9ef155f1 100755 --- a/examples/dfp/v201505/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201605/custom_field_service/update_custom_fields.py @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201505') + 'CustomFieldService', version='v201605') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201505/custom_targeting_service/__init__.py b/examples/dfp/v201605/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201505/custom_targeting_service/__init__.py rename to examples/dfp/v201605/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py index 6c433dbf..abd058ec 100755 --- a/examples/dfp/v201505/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py similarity index 98% rename from examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py index 5820bdd3..2750bda5 100755 --- a/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') values = [{ 'key': 'name', diff --git a/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_values.py similarity index 98% rename from examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_values.py index 150c6258..694c4aef 100755 --- a/examples/dfp/v201505/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_values.py @@ -37,7 +37,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201605/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201605/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 0b974d0f..3cb317ca 100755 --- a/examples/dfp/v201505/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201605/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') # Create statement to get all targeting keys. targeting_key_statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_keys_by_statement.py similarity index 97% rename from examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py rename to examples/dfp/v201605/custom_targeting_service/get_custom_targeting_keys_by_statement.py index 9cb5a762..086d003f 100755 --- a/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_keys_by_statement.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') values = [{ 'key': 'type', diff --git a/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_values_by_statement.py similarity index 97% rename from examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py rename to examples/dfp/v201605/custom_targeting_service/get_custom_targeting_values_by_statement.py index 1e7544ed..d0e507b0 100755 --- a/examples/dfp/v201505/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ b/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_values_by_statement.py @@ -31,7 +31,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201605/custom_targeting_service/update_custom_targeting_keys.py similarity index 97% rename from examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201605/custom_targeting_service/update_custom_targeting_keys.py index 74a4a86d..2b47509b 100755 --- a/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201605/custom_targeting_service/update_custom_targeting_keys.py @@ -29,7 +29,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201605/custom_targeting_service/update_custom_targeting_values.py similarity index 97% rename from examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201605/custom_targeting_service/update_custom_targeting_values.py index 30ea91e1..10ba2325 100755 --- a/examples/dfp/v201505/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201605/custom_targeting_service/update_custom_targeting_values.py @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201505') + 'CustomTargetingService', version='v201605') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201505/exchange_rate_service/__init__.py b/examples/dfp/v201605/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201505/exchange_rate_service/__init__.py rename to examples/dfp/v201605/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201605/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201605/exchange_rate_service/create_exchange_rates.py index f9057cd3..40df526f 100755 --- a/examples/dfp/v201505/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201605/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201505') + version='v201605') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201605/exchange_rate_service/get_all_exchange_rates.py similarity index 96% rename from examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201605/exchange_rate_service/get_all_exchange_rates.py index fc1f00ce..37389725 100755 --- a/examples/dfp/v201505/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201605/exchange_rate_service/get_all_exchange_rates.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201505') + version='v201605') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201605/exchange_rate_service/get_exchange_rates_by_currency_code.py similarity index 97% rename from examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py rename to examples/dfp/v201605/exchange_rate_service/get_exchange_rates_by_currency_code.py index be5445fd..0f0b8f31 100755 --- a/examples/dfp/v201505/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201605/exchange_rate_service/get_exchange_rates_by_currency_code.py @@ -30,7 +30,7 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201505') + version='v201605') # Create a statement to get exchange rates for the specified currency code. values = [{ diff --git a/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201605/exchange_rate_service/update_exchange_rates.py similarity index 97% rename from examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201605/exchange_rate_service/update_exchange_rates.py index 70c06c1e..3cd457f2 100755 --- a/examples/dfp/v201505/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201605/exchange_rate_service/update_exchange_rates.py @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201505') + version='v201605') # Create a statement to get an exchange rate by its ID. values = [{ diff --git a/examples/dfp/v201505/forecast_service/get_availability_forecast.py b/examples/dfp/v201605/forecast_service/get_availability_forecast.py similarity index 91% rename from examples/dfp/v201505/forecast_service/get_availability_forecast.py rename to examples/dfp/v201605/forecast_service/get_availability_forecast.py index 5ca1708c..9f7290e2 100755 --- a/examples/dfp/v201505/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201605/forecast_service/get_availability_forecast.py @@ -29,11 +29,15 @@ # Import appropriate modules from the client library. from googleads import dfp +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -def main(client): + +def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201505') - network_service = client.GetService('NetworkService', version='v201505') + forecast_service = client.GetService('ForecastService', version='v201605') + network_service = client.GetService('NetworkService', version='v201605') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] @@ -93,7 +97,8 @@ def main(client): } prospective_line_item = { - 'lineItem': line_item + 'lineItem': line_item, + 'advertiserId': advertiser_id } # Set forecasting options. @@ -124,4 +129,4 @@ def main(client): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201605/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201605/forecast_service/get_availability_forecast_for_line_item.py index 058e9a05..a380f171 100755 --- a/examples/dfp/v201505/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201605/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201505') + forecast_service = client.GetService('ForecastService', version='v201605') # Set forecasting options. forecast_options = { diff --git a/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201605/forecast_service/get_delivery_forecast_for_line_items.py similarity index 94% rename from examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201605/forecast_service/get_delivery_forecast_for_line_items.py index 9f47d86a..979f55f6 100755 --- a/examples/dfp/v201505/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201605/forecast_service/get_delivery_forecast_for_line_items.py @@ -25,13 +25,13 @@ from googleads import dfp # Set the line items to get forecasts for. -LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_ID_1_HERE' -LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_ID_2_HERE' +LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' +LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE' def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201505') + forecast_service = client.GetService('ForecastService', version='v201605') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201505/inventory_service/__init__.py b/examples/dfp/v201605/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201505/inventory_service/__init__.py rename to examples/dfp/v201605/inventory_service/__init__.py diff --git a/examples/dfp/v201505/inventory_service/archive_ad_units.py b/examples/dfp/v201605/inventory_service/archive_ad_units.py similarity index 99% rename from examples/dfp/v201505/inventory_service/archive_ad_units.py rename to examples/dfp/v201605/inventory_service/archive_ad_units.py index 2e45006b..4e0b3f02 100755 --- a/examples/dfp/v201505/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201605/inventory_service/archive_ad_units.py @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201505') + inventory_service = client.GetService('InventoryService', version='v201605') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201505/inventory_service/create_ad_units.py b/examples/dfp/v201605/inventory_service/create_ad_units.py similarity index 97% rename from examples/dfp/v201505/inventory_service/create_ad_units.py rename to examples/dfp/v201605/inventory_service/create_ad_units.py index 40a74b35..fc55f9b6 100755 --- a/examples/dfp/v201505/inventory_service/create_ad_units.py +++ b/examples/dfp/v201605/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201505') + inventory_service = client.GetService('InventoryService', version='v201605') # Create ad unit size. ad_unit_size = { @@ -53,7 +53,6 @@ def main(client, parent_id): 'parentId': parent_id, 'description': 'Ad unit description.', 'targetWindow': 'BLANK', - 'targetPlatform': 'WEB', 'adUnitSizes': [ad_unit_size] } diff --git a/examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py similarity index 99% rename from examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py rename to examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py index 8706c8b7..8126467a 100755 --- a/examples/dfp/v201505/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201505') + inventory_service = client.GetService('InventoryService', version='v201605') statement = dfp.FilterStatement() all_ad_units = [] diff --git a/examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201605/inventory_service/get_all_ad_unit_sizes.py similarity index 99% rename from examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201605/inventory_service/get_all_ad_unit_sizes.py index 64dc0ab8..68534b9a 100755 --- a/examples/dfp/v201505/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201605/inventory_service/get_all_ad_unit_sizes.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201505') + inventory_service = client.GetService('InventoryService', version='v201605') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201505/inventory_service/get_all_ad_units.py b/examples/dfp/v201605/inventory_service/get_all_ad_units.py similarity index 99% rename from examples/dfp/v201505/inventory_service/get_all_ad_units.py rename to examples/dfp/v201605/inventory_service/get_all_ad_units.py index 49484df8..119359c8 100755 --- a/examples/dfp/v201505/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201605/inventory_service/get_all_ad_units.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201505') + inventory_service = client.GetService('InventoryService', version='v201605') statement = dfp.FilterStatement() # Get ad units by statement. diff --git a/examples/dfp/v201505/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201605/inventory_service/get_top_level_ad_units.py similarity index 98% rename from examples/dfp/v201505/inventory_service/get_top_level_ad_units.py rename to examples/dfp/v201605/inventory_service/get_top_level_ad_units.py index 4381ebde..1274a9dc 100755 --- a/examples/dfp/v201505/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201605/inventory_service/get_top_level_ad_units.py @@ -32,8 +32,8 @@ def main(client): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201505') - network_service = client.GetService('NetworkService', version='v201505') + inventory_service = client.GetService('InventoryService', version='v201605') + network_service = client.GetService('NetworkService', version='v201605') root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201505/inventory_service/update_ad_units.py b/examples/dfp/v201605/inventory_service/update_ad_units.py similarity index 99% rename from examples/dfp/v201505/inventory_service/update_ad_units.py rename to examples/dfp/v201605/inventory_service/update_ad_units.py index a893785d..b1b2e26b 100755 --- a/examples/dfp/v201505/inventory_service/update_ad_units.py +++ b/examples/dfp/v201605/inventory_service/update_ad_units.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201505') + inventory_service = client.GetService('InventoryService', version='v201605') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201505/label_service/__init__.py b/examples/dfp/v201605/label_service/__init__.py similarity index 100% rename from examples/dfp/v201505/label_service/__init__.py rename to examples/dfp/v201605/label_service/__init__.py diff --git a/examples/dfp/v201505/label_service/create_labels.py b/examples/dfp/v201605/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201505/label_service/create_labels.py rename to examples/dfp/v201605/label_service/create_labels.py index d23995b8..9cbfc220 100755 --- a/examples/dfp/v201505/label_service/create_labels.py +++ b/examples/dfp/v201605/label_service/create_labels.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201505') + label_service = client.GetService('LabelService', version='v201605') # Create label objects. labels = [] diff --git a/examples/dfp/v201505/label_service/deactivate_labels.py b/examples/dfp/v201605/label_service/deactivate_labels.py similarity index 99% rename from examples/dfp/v201505/label_service/deactivate_labels.py rename to examples/dfp/v201605/label_service/deactivate_labels.py index 7f0019da..99a72617 100755 --- a/examples/dfp/v201505/label_service/deactivate_labels.py +++ b/examples/dfp/v201605/label_service/deactivate_labels.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201505') + label_service = client.GetService('LabelService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/label_service/get_all_labels.py b/examples/dfp/v201605/label_service/get_all_labels.py similarity index 99% rename from examples/dfp/v201505/label_service/get_all_labels.py rename to examples/dfp/v201605/label_service/get_all_labels.py index bb0574db..77265cfe 100755 --- a/examples/dfp/v201505/label_service/get_all_labels.py +++ b/examples/dfp/v201605/label_service/get_all_labels.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201505') + label_service = client.GetService('LabelService', version='v201605') # Create statement to get all labels statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/label_service/get_labels_by_statement.py b/examples/dfp/v201605/label_service/get_labels_by_statement.py similarity index 99% rename from examples/dfp/v201505/label_service/get_labels_by_statement.py rename to examples/dfp/v201605/label_service/get_labels_by_statement.py index fae47ceb..a71b5363 100755 --- a/examples/dfp/v201505/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201605/label_service/get_labels_by_statement.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201505') + label_service = client.GetService('LabelService', version='v201605') # Create statement to get all labels statement = dfp.FilterStatement('ORDER BY name') diff --git a/examples/dfp/v201505/label_service/update_labels.py b/examples/dfp/v201605/label_service/update_labels.py similarity index 99% rename from examples/dfp/v201505/label_service/update_labels.py rename to examples/dfp/v201605/label_service/update_labels.py index 508529f7..f5088514 100755 --- a/examples/dfp/v201505/label_service/update_labels.py +++ b/examples/dfp/v201605/label_service/update_labels.py @@ -28,7 +28,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201505') + label_service = client.GetService('LabelService', version='v201605') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201505/line_item_creative_association_service/__init__.py b/examples/dfp/v201605/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201505/line_item_creative_association_service/__init__.py rename to examples/dfp/v201605/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201505/line_item_creative_association_service/create_licas.py b/examples/dfp/v201605/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201505/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201605/line_item_creative_association_service/create_licas.py index 43934944..4cab1cb6 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201605/line_item_creative_association_service/create_licas.py @@ -31,7 +31,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201505') + 'LineItemCreativeAssociationService', version='v201605') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201605/line_item_creative_association_service/deactivate_licas.py similarity index 97% rename from examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201605/line_item_creative_association_service/deactivate_licas.py index 8b0d2a35..c40d5888 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201605/line_item_creative_association_service/deactivate_licas.py @@ -29,7 +29,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201505') + 'LineItemCreativeAssociationService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201605/line_item_creative_association_service/get_all_licas.py similarity index 96% rename from examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201605/line_item_creative_association_service/get_all_licas.py index 634b9b12..d183e4bf 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201605/line_item_creative_association_service/get_all_licas.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201505') + 'LineItemCreativeAssociationService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201605/line_item_creative_association_service/get_licas_by_statement.py similarity index 97% rename from examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py rename to examples/dfp/v201605/line_item_creative_association_service/get_licas_by_statement.py index 10836292..f3f11653 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201605/line_item_creative_association_service/get_licas_by_statement.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201505') + 'LineItemCreativeAssociationService', version='v201605') # Create statement object to only select LICAs for the given line item id. values = [{ diff --git a/examples/dfp/v201505/line_item_creative_association_service/update_licas.py b/examples/dfp/v201605/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201505/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201605/line_item_creative_association_service/update_licas.py index 7a53d342..2a493b63 100755 --- a/examples/dfp/v201505/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201605/line_item_creative_association_service/update_licas.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201505') + 'LineItemCreativeAssociationService', version='v201605') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/line_item_service/__init__.py b/examples/dfp/v201605/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201505/line_item_service/__init__.py rename to examples/dfp/v201605/line_item_service/__init__.py diff --git a/examples/dfp/v201505/line_item_service/activate_line_items.py b/examples/dfp/v201605/line_item_service/activate_line_items.py similarity index 99% rename from examples/dfp/v201505/line_item_service/activate_line_items.py rename to examples/dfp/v201605/line_item_service/activate_line_items.py index 76a5a8ea..3cbe6db2 100755 --- a/examples/dfp/v201505/line_item_service/activate_line_items.py +++ b/examples/dfp/v201605/line_item_service/activate_line_items.py @@ -32,7 +32,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/line_item_service/create_line_items.py b/examples/dfp/v201605/line_item_service/create_line_items.py similarity index 99% rename from examples/dfp/v201505/line_item_service/create_line_items.py rename to examples/dfp/v201605/line_item_service/create_line_items.py index 61c08ffb..4ff47d3b 100755 --- a/examples/dfp/v201505/line_item_service/create_line_items.py +++ b/examples/dfp/v201605/line_item_service/create_line_items.py @@ -35,7 +35,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Create line item objects. line_items = [] diff --git a/examples/dfp/v201505/line_item_service/create_video_line_item.py b/examples/dfp/v201605/line_item_service/create_video_line_item.py similarity index 99% rename from examples/dfp/v201505/line_item_service/create_video_line_item.py rename to examples/dfp/v201605/line_item_service/create_video_line_item.py index 06835263..c90ef243 100755 --- a/examples/dfp/v201505/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201605/line_item_service/create_video_line_item.py @@ -45,7 +45,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Create line item object. line_item = { diff --git a/examples/dfp/v201505/line_item_service/get_all_line_items.py b/examples/dfp/v201605/line_item_service/get_all_line_items.py similarity index 99% rename from examples/dfp/v201505/line_item_service/get_all_line_items.py rename to examples/dfp/v201605/line_item_service/get_all_line_items.py index e2d6431a..4deaf7e0 100755 --- a/examples/dfp/v201505/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201605/line_item_service/get_all_line_items.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201605/line_item_service/get_line_items_by_statement.py similarity index 99% rename from examples/dfp/v201505/line_item_service/get_line_items_by_statement.py rename to examples/dfp/v201605/line_item_service/get_line_items_by_statement.py index c3e9acbc..7d7db8e9 100755 --- a/examples/dfp/v201505/line_item_service/get_line_items_by_statement.py +++ b/examples/dfp/v201605/line_item_service/get_line_items_by_statement.py @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Create statement object to only select line items that need creatives from a # given order. diff --git a/examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201605/line_item_service/get_recently_updated_line_items.py similarity index 99% rename from examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201605/line_item_service/get_recently_updated_line_items.py index dca16f6a..4d254e07 100755 --- a/examples/dfp/v201505/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201605/line_item_service/get_recently_updated_line_items.py @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Create statement object to only select line items belonging to the order and # have been modified in the last 3 days. diff --git a/examples/dfp/v201505/line_item_service/target_custom_criteria.py b/examples/dfp/v201605/line_item_service/target_custom_criteria.py similarity index 99% rename from examples/dfp/v201505/line_item_service/target_custom_criteria.py rename to examples/dfp/v201605/line_item_service/target_custom_criteria.py index 6eff449d..f2ff5c1b 100755 --- a/examples/dfp/v201505/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201605/line_item_service/target_custom_criteria.py @@ -39,7 +39,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201505/line_item_service/update_line_items.py b/examples/dfp/v201605/line_item_service/update_line_items.py similarity index 99% rename from examples/dfp/v201505/line_item_service/update_line_items.py rename to examples/dfp/v201605/line_item_service/update_line_items.py index d3695143..c663c795 100755 --- a/examples/dfp/v201505/line_item_service/update_line_items.py +++ b/examples/dfp/v201605/line_item_service/update_line_items.py @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201505/network_service/__init__.py b/examples/dfp/v201605/network_service/__init__.py similarity index 100% rename from examples/dfp/v201505/network_service/__init__.py rename to examples/dfp/v201605/network_service/__init__.py diff --git a/examples/dfp/v201505/network_service/get_all_networks.py b/examples/dfp/v201605/network_service/get_all_networks.py similarity index 99% rename from examples/dfp/v201505/network_service/get_all_networks.py rename to examples/dfp/v201605/network_service/get_all_networks.py index d9bcda9d..2177f2c6 100755 --- a/examples/dfp/v201505/network_service/get_all_networks.py +++ b/examples/dfp/v201605/network_service/get_all_networks.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201505') + network_service = client.GetService('NetworkService', version='v201605') # Get all networks that you have access to with the current login credentials. networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201505/network_service/get_current_network.py b/examples/dfp/v201605/network_service/get_current_network.py similarity index 99% rename from examples/dfp/v201505/network_service/get_current_network.py rename to examples/dfp/v201605/network_service/get_current_network.py index 54068e24..ade4c633 100755 --- a/examples/dfp/v201505/network_service/get_current_network.py +++ b/examples/dfp/v201605/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201505') + network_service = client.GetService('NetworkService', version='v201605') # Get the current network. network = network_service.getCurrentNetwork() diff --git a/examples/dfp/v201505/network_service/make_test_network.py b/examples/dfp/v201605/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201505/network_service/make_test_network.py rename to examples/dfp/v201605/network_service/make_test_network.py index 93e21a7c..45b995ab 100755 --- a/examples/dfp/v201505/network_service/make_test_network.py +++ b/examples/dfp/v201605/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201505') + network_service = client.GetService('NetworkService', version='v201605') # Create a test network. network = network_service.MakeTestNetwork() diff --git a/examples/dfp/v201505/order_service/__init__.py b/examples/dfp/v201605/order_service/__init__.py similarity index 100% rename from examples/dfp/v201505/order_service/__init__.py rename to examples/dfp/v201605/order_service/__init__.py diff --git a/examples/dfp/v201505/order_service/approve_orders.py b/examples/dfp/v201605/order_service/approve_orders.py similarity index 99% rename from examples/dfp/v201505/order_service/approve_orders.py rename to examples/dfp/v201605/order_service/approve_orders.py index 43ee7d93..edf02931 100755 --- a/examples/dfp/v201505/order_service/approve_orders.py +++ b/examples/dfp/v201605/order_service/approve_orders.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201505') + order_service = client.GetService('OrderService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/order_service/create_orders.py b/examples/dfp/v201605/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201505/order_service/create_orders.py rename to examples/dfp/v201605/order_service/create_orders.py index 44daffe3..75cab0fc 100755 --- a/examples/dfp/v201505/order_service/create_orders.py +++ b/examples/dfp/v201605/order_service/create_orders.py @@ -31,7 +31,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201505') + order_service = client.GetService('OrderService', version='v201605') # Create order objects. orders = [] diff --git a/examples/dfp/v201505/order_service/get_all_orders.py b/examples/dfp/v201605/order_service/get_all_orders.py similarity index 99% rename from examples/dfp/v201505/order_service/get_all_orders.py rename to examples/dfp/v201605/order_service/get_all_orders.py index 161c54c1..14ede832 100755 --- a/examples/dfp/v201505/order_service/get_all_orders.py +++ b/examples/dfp/v201605/order_service/get_all_orders.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201505') + order_service = client.GetService('OrderService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/order_service/get_orders_by_statement.py b/examples/dfp/v201605/order_service/get_orders_by_statement.py similarity index 99% rename from examples/dfp/v201505/order_service/get_orders_by_statement.py rename to examples/dfp/v201605/order_service/get_orders_by_statement.py index 138fd268..0106f3ae 100755 --- a/examples/dfp/v201505/order_service/get_orders_by_statement.py +++ b/examples/dfp/v201605/order_service/get_orders_by_statement.py @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201505') + order_service = client.GetService('OrderService', version='v201605') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201505/order_service/update_orders.py b/examples/dfp/v201605/order_service/update_orders.py similarity index 99% rename from examples/dfp/v201505/order_service/update_orders.py rename to examples/dfp/v201605/order_service/update_orders.py index e216dded..77632245 100755 --- a/examples/dfp/v201505/order_service/update_orders.py +++ b/examples/dfp/v201605/order_service/update_orders.py @@ -27,7 +27,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201505') + order_service = client.GetService('OrderService', version='v201605') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201505/placement_service/create_placements.py b/examples/dfp/v201605/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201505/placement_service/create_placements.py rename to examples/dfp/v201605/placement_service/create_placements.py index edcb7136..e6bc429c 100755 --- a/examples/dfp/v201505/placement_service/create_placements.py +++ b/examples/dfp/v201605/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201505') - inventory_service = client.GetService('InventoryService', version='v201505') + placement_service = client.GetService('PlacementService', version='v201605') + inventory_service = client.GetService('InventoryService', version='v201605') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201505/placement_service/deactivate_placements.py b/examples/dfp/v201605/placement_service/deactivate_placements.py similarity index 99% rename from examples/dfp/v201505/placement_service/deactivate_placements.py rename to examples/dfp/v201605/placement_service/deactivate_placements.py index 78cc8ee9..eac7f3d7 100755 --- a/examples/dfp/v201505/placement_service/deactivate_placements.py +++ b/examples/dfp/v201605/placement_service/deactivate_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201505') + placement_service = client.GetService('PlacementService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/placement_service/get_all_placements.py b/examples/dfp/v201605/placement_service/get_all_placements.py similarity index 99% rename from examples/dfp/v201505/placement_service/get_all_placements.py rename to examples/dfp/v201605/placement_service/get_all_placements.py index f35524fc..2d60fe64 100755 --- a/examples/dfp/v201505/placement_service/get_all_placements.py +++ b/examples/dfp/v201605/placement_service/get_all_placements.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201505') + placement_service = client.GetService('PlacementService', version='v201605') # Create statement to fetch all placements. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/placement_service/get_placements_by_statement.py b/examples/dfp/v201605/placement_service/get_placements_by_statement.py similarity index 99% rename from examples/dfp/v201505/placement_service/get_placements_by_statement.py rename to examples/dfp/v201605/placement_service/get_placements_by_statement.py index 94aeb621..db9e389d 100755 --- a/examples/dfp/v201505/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201605/placement_service/get_placements_by_statement.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201505') + placement_service = client.GetService('PlacementService', version='v201605') # Create a statement to only select active placements. values = [{ diff --git a/examples/dfp/v201505/placement_service/update_placements.py b/examples/dfp/v201605/placement_service/update_placements.py similarity index 99% rename from examples/dfp/v201505/placement_service/update_placements.py rename to examples/dfp/v201605/placement_service/update_placements.py index 469e0663..a864766c 100755 --- a/examples/dfp/v201505/placement_service/update_placements.py +++ b/examples/dfp/v201605/placement_service/update_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201505') + placement_service = client.GetService('PlacementService', version='v201605') # Create query. values = [{ 'key': 'placementId', diff --git a/examples/dfp/v201505/premium_rate_service/__init__.py b/examples/dfp/v201605/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201505/premium_rate_service/__init__.py rename to examples/dfp/v201605/premium_rate_service/__init__.py diff --git a/examples/dfp/v201505/premium_rate_service/create_premium_rates.py b/examples/dfp/v201605/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/dfp/v201505/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201605/premium_rate_service/create_premium_rates.py index c7d6f0b8..f560f0a1 100755 --- a/examples/dfp/v201505/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201605/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201505') + version='v201605') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201605/premium_rate_service/get_all_premium_rates.py similarity index 96% rename from examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201605/premium_rate_service/get_all_premium_rates.py index 2da3b647..f9d95576 100755 --- a/examples/dfp/v201505/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201605/premium_rate_service/get_all_premium_rates.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201505') + version='v201605') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201605/premium_rate_service/get_premium_rates_for_a_rate_card.py similarity index 97% rename from examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py rename to examples/dfp/v201605/premium_rate_service/get_premium_rates_for_a_rate_card.py index b22faa40..6b5aa2d1 100755 --- a/examples/dfp/v201505/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201605/premium_rate_service/get_premium_rates_for_a_rate_card.py @@ -30,7 +30,7 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201505') + version='v201605') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201505/premium_rate_service/update_premium_rates.py b/examples/dfp/v201605/premium_rate_service/update_premium_rates.py similarity index 97% rename from examples/dfp/v201505/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201605/premium_rate_service/update_premium_rates.py index 6fdd9a74..6e35fbf2 100755 --- a/examples/dfp/v201505/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201605/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201505') + version='v201605') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201505/product_service/__init__.py b/examples/dfp/v201605/product_service/__init__.py similarity index 100% rename from examples/dfp/v201505/product_service/__init__.py rename to examples/dfp/v201605/product_service/__init__.py diff --git a/examples/dfp/v201505/product_service/get_all_products.py b/examples/dfp/v201605/product_service/get_all_products.py similarity index 99% rename from examples/dfp/v201505/product_service/get_all_products.py rename to examples/dfp/v201605/product_service/get_all_products.py index d66f7ba8..9e8aa190 100755 --- a/examples/dfp/v201505/product_service/get_all_products.py +++ b/examples/dfp/v201605/product_service/get_all_products.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201505') + product_service = client.GetService('ProductService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201505/product_service/get_products_for_product_template.py b/examples/dfp/v201605/product_service/get_products_for_product_template.py similarity index 99% rename from examples/dfp/v201505/product_service/get_products_for_product_template.py rename to examples/dfp/v201605/product_service/get_products_for_product_template.py index 886d84ed..8b569ddc 100755 --- a/examples/dfp/v201505/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201605/product_service/get_products_for_product_template.py @@ -27,7 +27,7 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201505') + product_service = client.GetService('ProductService', version='v201605') # Create a filter statement to select only products created from a single # a product template. diff --git a/examples/dfp/v201505/product_service/update_products.py b/examples/dfp/v201605/product_service/update_products.py similarity index 99% rename from examples/dfp/v201505/product_service/update_products.py rename to examples/dfp/v201605/product_service/update_products.py index af816775..a77c83d9 100755 --- a/examples/dfp/v201505/product_service/update_products.py +++ b/examples/dfp/v201605/product_service/update_products.py @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201505') + product_service = client.GetService('ProductService', version='v201605') # Create statement object to select a single product by an ID. values = [{ diff --git a/examples/dfp/v201505/product_template_service/__init__.py b/examples/dfp/v201605/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201505/product_template_service/__init__.py rename to examples/dfp/v201605/product_template_service/__init__.py diff --git a/examples/dfp/v201505/product_template_service/activate_product_templates.py b/examples/dfp/v201605/product_template_service/activate_product_templates.py similarity index 97% rename from examples/dfp/v201505/product_template_service/activate_product_templates.py rename to examples/dfp/v201605/product_template_service/activate_product_templates.py index 4e2f9126..795472ed 100755 --- a/examples/dfp/v201505/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201605/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201505') + 'ProductTemplateService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/product_template_service/create_product_templates.py b/examples/dfp/v201605/product_template_service/create_product_templates.py similarity index 82% rename from examples/dfp/v201505/product_template_service/create_product_templates.py rename to examples/dfp/v201605/product_template_service/create_product_templates.py index 8b960910..ab716be7 100755 --- a/examples/dfp/v201505/product_template_service/create_product_templates.py +++ b/examples/dfp/v201605/product_template_service/create_product_templates.py @@ -17,10 +17,8 @@ """This example creates a product template. To determine which product templates exist, run get_all_product_templates.py. - """ - import uuid # Import appropriate modules from the client library. @@ -30,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201505') + 'ProductTemplateService', version='v201605') network_service = client.GetService( - 'NetworkService', version='v201505') + 'NetworkService', version='v201605') # Create a product template. product_template = { @@ -45,6 +43,7 @@ def main(client): 'productType': 'DFP', 'rateType': 'CPM', 'roadblockingType': 'ONE_OR_MORE', + 'deliveryRateType': 'AS_FAST_AS_POSSIBLE', 'creativePlaceholders': [ { 'size': { @@ -60,17 +59,22 @@ def main(client): } ], 'lineItemType': 'STANDARD', - 'targeting': { - # Set browser targeting to Chrome. - 'browserTargeting': [ - { - 'browsers': [ - { - 'id': '500072' - } - ] + 'customizableAttributes': { + 'allowPlacementTargetingCustomization': True, + }, + 'builtInTargeting': { + 'technologyTargeting': { + # Set browser targeting to Chrome. + 'browserTargeting': { + { + 'browsers': [ + { + 'id': '500072' + } + ] + } } - ] + } }, 'productSegmentation': { 'geoSegment': { diff --git a/examples/dfp/v201505/product_template_service/get_all_product_templates.py b/examples/dfp/v201605/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201505/product_template_service/get_all_product_templates.py rename to examples/dfp/v201605/product_template_service/get_all_product_templates.py index e3ac0d46..cbc81489 100755 --- a/examples/dfp/v201505/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201605/product_template_service/get_all_product_templates.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201505') + 'ProductTemplateService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201605/product_template_service/get_sponsorship_product_templates.py similarity index 97% rename from examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201605/product_template_service/get_sponsorship_product_templates.py index a0e4345a..33f799c6 100755 --- a/examples/dfp/v201505/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201605/product_template_service/get_sponsorship_product_templates.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201505') + 'ProductTemplateService', version='v201605') # Create a statement to select all sponsorship product templates. values = [{ diff --git a/examples/dfp/v201505/product_template_service/update_product_templates.py b/examples/dfp/v201605/product_template_service/update_product_templates.py similarity index 94% rename from examples/dfp/v201505/product_template_service/update_product_templates.py rename to examples/dfp/v201605/product_template_service/update_product_templates.py index 54250aff..c1356465 100755 --- a/examples/dfp/v201505/product_template_service/update_product_templates.py +++ b/examples/dfp/v201605/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201505') + 'ProductTemplateService', version='v201605') # Create a statement to select a single product template by ID. values = [{ @@ -57,7 +57,7 @@ def main(client, product_template_id): } try: - targeting = product_template['targeting'] + targeting = product_template['builtInTargeting'] if 'geoTargeting' in targeting: geo_targeting = targeting['geoTargeting'] @@ -71,7 +71,7 @@ def main(client, product_template_id): 'targetedLocations': [location] } except KeyError: - product_template['targeting'] = { + product_template['builtInTargeting'] = { 'geoTargeting': { 'targetedLocations': [location] } diff --git a/examples/dfp/v201505/proposal_line_item_service/__init__.py b/examples/dfp/v201605/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201505/proposal_line_item_service/__init__.py rename to examples/dfp/v201605/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201605/proposal_line_item_service/archive_proposal_line_items.py similarity index 98% rename from examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201605/proposal_line_item_service/archive_proposal_line_items.py index e3b498e4..342032f6 100755 --- a/examples/dfp/v201505/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201605/proposal_line_item_service/archive_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201505') + 'ProposalLineItemService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201605/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201605/proposal_line_item_service/create_proposal_line_items.py index 779b1502..ca9270d2 100755 --- a/examples/dfp/v201505/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201605/proposal_line_item_service/create_proposal_line_items.py @@ -41,8 +41,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201505') - network_service = client.GetService('NetworkService', version='v201505') + 'ProposalLineItemService', version='v201605') + network_service = client.GetService('NetworkService', version='v201605') # Get the root ad unit to target. root_ad_unit_id = ( diff --git a/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201605/proposal_line_item_service/get_all_proposal_line_items.py similarity index 97% rename from examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201605/proposal_line_item_service/get_all_proposal_line_items.py index 5d0e2898..1302dc0f 100755 --- a/examples/dfp/v201505/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201605/proposal_line_item_service/get_all_proposal_line_items.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201505') + 'ProposalLineItemService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201605/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 98% rename from examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201605/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 5fc1fe41..f93ae1c3 100755 --- a/examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201605/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -29,7 +29,7 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( 'ProposalLineItemService', - version='v201505') + version='v201605') # Create statement object to only select proposal line items belonging to a # given proposal. diff --git a/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201605/proposal_line_item_service/update_proposal_line_items.py similarity index 97% rename from examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201605/proposal_line_item_service/update_proposal_line_items.py index f9cb063b..ee40006f 100755 --- a/examples/dfp/v201505/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201605/proposal_line_item_service/update_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201505') + 'ProposalLineItemService', version='v201605') # Create statement to select a proposal line item. values = [{ diff --git a/examples/dfp/v201505/proposal_service/__init__.py b/examples/dfp/v201605/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201505/proposal_service/__init__.py rename to examples/dfp/v201605/proposal_service/__init__.py diff --git a/examples/dfp/v201505/proposal_service/create_proposals.py b/examples/dfp/v201605/proposal_service/create_proposals.py similarity index 99% rename from examples/dfp/v201505/proposal_service/create_proposals.py rename to examples/dfp/v201605/proposal_service/create_proposals.py index daf8cd32..b725d22b 100755 --- a/examples/dfp/v201505/proposal_service/create_proposals.py +++ b/examples/dfp/v201605/proposal_service/create_proposals.py @@ -33,8 +33,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201505') - network_service = client.GetService('NetworkService', version='v201505') + proposal_service = client.GetService('ProposalService', version='v201605') + network_service = client.GetService('NetworkService', version='v201605') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201505/proposal_service/get_all_proposals.py b/examples/dfp/v201605/proposal_service/get_all_proposals.py similarity index 99% rename from examples/dfp/v201505/proposal_service/get_all_proposals.py rename to examples/dfp/v201605/proposal_service/get_all_proposals.py index 6875bbca..cd1797bf 100755 --- a/examples/dfp/v201505/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201605/proposal_service/get_all_proposals.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201505') + proposal_service = client.GetService('ProposalService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201605/proposal_service/get_proposals_by_statement.py similarity index 99% rename from examples/dfp/v201505/proposal_service/get_proposals_by_statement.py rename to examples/dfp/v201605/proposal_service/get_proposals_by_statement.py index 6550dd58..343eba97 100755 --- a/examples/dfp/v201505/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201605/proposal_service/get_proposals_by_statement.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201505') + proposal_service = client.GetService('ProposalService', version='v201605') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201605/proposal_service/submit_proposals_for_approval.py similarity index 99% rename from examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201605/proposal_service/submit_proposals_for_approval.py index 17a5f7b0..0810c29b 100755 --- a/examples/dfp/v201505/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201605/proposal_service/submit_proposals_for_approval.py @@ -26,7 +26,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201505') + proposal_service = client.GetService('ProposalService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/proposal_service/update_proposals.py b/examples/dfp/v201605/proposal_service/update_proposals.py similarity index 99% rename from examples/dfp/v201505/proposal_service/update_proposals.py rename to examples/dfp/v201605/proposal_service/update_proposals.py index 5de8dac5..02e14e7b 100755 --- a/examples/dfp/v201505/proposal_service/update_proposals.py +++ b/examples/dfp/v201605/proposal_service/update_proposals.py @@ -27,7 +27,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201505') + proposal_service = client.GetService('ProposalService', version='v201605') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201505/publisher_query_language_service/__init__.py b/examples/dfp/v201605/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201505/publisher_query_language_service/__init__.py rename to examples/dfp/v201605/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201605/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201605/publisher_query_language_service/fetch_match_tables.py index 764f7812..99fa8da6 100755 --- a/examples/dfp/v201505/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201605/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201505') + report_downloader = client.GetDataDownloader(version='v201605') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201605/publisher_query_language_service/get_geo_targets.py similarity index 94% rename from examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py rename to examples/dfp/v201605/publisher_query_language_service/get_geo_targets.py index 6013be2f..9d5fe7f3 100755 --- a/examples/dfp/v201505/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201605/publisher_query_language_service/get_geo_targets.py @@ -20,7 +20,7 @@ 'Postal_Code', and 'DMA_Region' (i.e. Metro). A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201505/PublisherQueryLanguageService +https://developers.google.com/doubleclick-publishers/docs/reference/v201605/PublisherQueryLanguageService """ @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201505') + report_downloader = client.GetDataDownloader(version='v201605') output_file = tempfile.NamedTemporaryFile( prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201605/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py rename to examples/dfp/v201605/publisher_query_language_service/get_line_items_named_like.py index 6a8496b2..a1fb4351 100755 --- a/examples/dfp/v201505/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201605/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201505') + report_downloader = client.GetDataDownloader(version='v201605') output_file = tempfile.NamedTemporaryFile( prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201505/rate_card_service/__init__.py b/examples/dfp/v201605/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201505/rate_card_service/__init__.py rename to examples/dfp/v201605/rate_card_service/__init__.py diff --git a/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201605/rate_card_service/get_all_rate_cards.py similarity index 99% rename from examples/dfp/v201505/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201605/rate_card_service/get_all_rate_cards.py index f85dec4f..a6a16ad5 100755 --- a/examples/dfp/v201505/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201605/rate_card_service/get_all_rate_cards.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201505') + rate_card_service = client.GetService('RateCardService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement('ORDER BY id ASC') diff --git a/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201605/rate_card_service/get_rate_cards_priced_with_currency.py similarity index 99% rename from examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py rename to examples/dfp/v201605/rate_card_service/get_rate_cards_priced_with_currency.py index f0954058..9b9a67a2 100755 --- a/examples/dfp/v201505/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201605/rate_card_service/get_rate_cards_priced_with_currency.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201505') + rate_card_service = client.GetService('RateCardService', version='v201605') # Create a statement to get all rate cards using USD as currency. values = [{ diff --git a/examples/dfp/v201505/report_service/__init__.py b/examples/dfp/v201605/report_service/__init__.py similarity index 100% rename from examples/dfp/v201505/report_service/__init__.py rename to examples/dfp/v201605/report_service/__init__.py diff --git a/examples/dfp/v201505/report_service/run_delivery_report.py b/examples/dfp/v201605/report_service/run_delivery_report.py similarity index 81% rename from examples/dfp/v201505/report_service/run_delivery_report.py rename to examples/dfp/v201605/report_service/run_delivery_report.py index 15b1a2cc..4fa2a96a 100755 --- a/examples/dfp/v201505/report_service/run_delivery_report.py +++ b/examples/dfp/v201605/report_service/run_delivery_report.py @@ -18,6 +18,8 @@ website with additional attributes and can filter to include just one order. """ +from datetime import datetime +from datetime import timedelta import tempfile # Import appropriate modules from the client library. @@ -39,6 +41,10 @@ def main(client, order_id): filter_statement = {'query': 'WHERE ORDER_ID = :id', 'values': values} + # Set the start and end dates of the report to run (past 8 days). + end_date = datetime.now() + start_date = end_date - timedelta(days=8) + # Create report job. report_job = { 'reportQuery': { @@ -49,12 +55,18 @@ def main(client, order_id): 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'LAST_MONTH' + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': {'year': start_date.year, + 'month': start_date.month, + 'day': start_date.day}, + 'endDate': {'year': end_date.year, + 'month': end_date.month, + 'day': end_date.day} } } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201505') + report_downloader = client.GetDataDownloader(version='v201605') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201505/report_service/run_inventory_report.py b/examples/dfp/v201605/report_service/run_inventory_report.py similarity index 97% rename from examples/dfp/v201505/report_service/run_inventory_report.py rename to examples/dfp/v201605/report_service/run_inventory_report.py index 99af3ea1..8c5befa4 100755 --- a/examples/dfp/v201505/report_service/run_inventory_report.py +++ b/examples/dfp/v201605/report_service/run_inventory_report.py @@ -27,9 +27,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201505') + network_service = client.GetService('NetworkService', version='v201605') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201505') + report_downloader = client.GetDataDownloader(version='v201605') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201505/report_service/run_reach_report.py b/examples/dfp/v201605/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201505/report_service/run_reach_report.py rename to examples/dfp/v201605/report_service/run_reach_report.py index b02737cd..58364ff9 100755 --- a/examples/dfp/v201505/report_service/run_reach_report.py +++ b/examples/dfp/v201605/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201505') + report_downloader = client.GetDataDownloader(version='v201605') # Create report job. report_job = { diff --git a/examples/dfp/v201505/report_service/run_report_with_custom_fields.py b/examples/dfp/v201605/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/dfp/v201505/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201605/report_service/run_report_with_custom_fields.py index 0441aa9e..169a8496 100755 --- a/examples/dfp/v201505/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201605/report_service/run_report_with_custom_fields.py @@ -30,9 +30,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201505') + line_item_service = client.GetService('LineItemService', version='v201605') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201505') + report_downloader = client.GetDataDownloader(version='v201605') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201505/report_service/run_sales_report.py b/examples/dfp/v201605/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201505/report_service/run_sales_report.py rename to examples/dfp/v201605/report_service/run_sales_report.py index fdfcf618..db25f236 100755 --- a/examples/dfp/v201505/report_service/run_sales_report.py +++ b/examples/dfp/v201605/report_service/run_sales_report.py @@ -26,7 +26,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201505') + report_downloader = client.GetDataDownloader(version='v201605') # Create report job. report_job = { diff --git a/examples/dfp/v201505/suggested_ad_unit_service/__init__.py b/examples/dfp/v201605/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201505/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201605/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201605/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201605/suggested_ad_unit_service/approve_all_suggested_ad_units.py index d3a81368..d5417ce8 100755 --- a/examples/dfp/v201505/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201605/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201505') + 'SuggestedAdUnitService', version='v201605') values = [{ 'key': 'numRequests', @@ -58,7 +58,7 @@ def main(client): # Approve suggested ad units. result = suggested_ad_unit_service.performSuggestedAdUnitAction( - {'xsi_type': 'ApproveSuggestedAdUnit'}, + {'xsi_type': 'ApproveSuggestedAdUnits'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: num_approved_suggested_ad_units += int(result['numChanges']) diff --git a/examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201605/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201605/suggested_ad_unit_service/get_all_suggested_ad_units.py index c2f1dc00..7ab1a1b8 100755 --- a/examples/dfp/v201505/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201605/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201505') + 'SuggestedAdUnitService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201605/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py similarity index 97% rename from examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py rename to examples/dfp/v201605/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py index 9a59cd9f..3cc6a7cf 100755 --- a/examples/dfp/v201505/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201605/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201505') + 'SuggestedAdUnitService', version='v201605') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201505/team_service/__init__.py b/examples/dfp/v201605/team_service/__init__.py similarity index 100% rename from examples/dfp/v201505/team_service/__init__.py rename to examples/dfp/v201605/team_service/__init__.py diff --git a/examples/dfp/v201505/team_service/create_teams.py b/examples/dfp/v201605/team_service/create_teams.py similarity index 96% rename from examples/dfp/v201505/team_service/create_teams.py rename to examples/dfp/v201605/team_service/create_teams.py index 2f3f37cf..70e65266 100755 --- a/examples/dfp/v201505/team_service/create_teams.py +++ b/examples/dfp/v201605/team_service/create_teams.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201505') + team_service = client.GetService('TeamService', version='v201605') # Create team objects. teams = [] diff --git a/examples/dfp/v201505/team_service/get_all_teams.py b/examples/dfp/v201605/team_service/get_all_teams.py similarity index 96% rename from examples/dfp/v201505/team_service/get_all_teams.py rename to examples/dfp/v201605/team_service/get_all_teams.py index 91b7e130..bb847b45 100755 --- a/examples/dfp/v201505/team_service/get_all_teams.py +++ b/examples/dfp/v201605/team_service/get_all_teams.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201505') + team_service = client.GetService('TeamService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/team_service/get_teams_by_statement.py b/examples/dfp/v201605/team_service/get_teams_by_statement.py similarity index 96% rename from examples/dfp/v201505/team_service/get_teams_by_statement.py rename to examples/dfp/v201605/team_service/get_teams_by_statement.py index 4f820dbc..a7058f0e 100755 --- a/examples/dfp/v201505/team_service/get_teams_by_statement.py +++ b/examples/dfp/v201605/team_service/get_teams_by_statement.py @@ -34,7 +34,7 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201505') + team_service = client.GetService('TeamService', version='v201605') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201505/team_service/update_teams.py b/examples/dfp/v201605/team_service/update_teams.py similarity index 97% rename from examples/dfp/v201505/team_service/update_teams.py rename to examples/dfp/v201605/team_service/update_teams.py index f23df5e0..f511fbc2 100755 --- a/examples/dfp/v201505/team_service/update_teams.py +++ b/examples/dfp/v201605/team_service/update_teams.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201505') + team_service = client.GetService('TeamService', version='v201605') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201505/user_service/__init__.py b/examples/dfp/v201605/user_service/__init__.py similarity index 100% rename from examples/dfp/v201505/user_service/__init__.py rename to examples/dfp/v201605/user_service/__init__.py diff --git a/examples/dfp/v201505/user_service/create_users.py b/examples/dfp/v201605/user_service/create_users.py similarity index 94% rename from examples/dfp/v201505/user_service/create_users.py rename to examples/dfp/v201605/user_service/create_users.py index aaaa7738..f41a7655 100755 --- a/examples/dfp/v201505/user_service/create_users.py +++ b/examples/dfp/v201605/user_service/create_users.py @@ -28,14 +28,13 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201505') + user_service = client.GetService('UserService', version='v201605') # Create user objects. users = [ { 'email': email, 'name': name, - 'preferredLocale': 'en_US' } ] for user in users: diff --git a/examples/dfp/v201505/user_service/deactivate_users.py b/examples/dfp/v201605/user_service/deactivate_users.py similarity index 97% rename from examples/dfp/v201505/user_service/deactivate_users.py rename to examples/dfp/v201605/user_service/deactivate_users.py index e1db318e..12b0872f 100755 --- a/examples/dfp/v201505/user_service/deactivate_users.py +++ b/examples/dfp/v201605/user_service/deactivate_users.py @@ -29,7 +29,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201505') + user_service = client.GetService('UserService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/user_service/get_all_roles.py b/examples/dfp/v201605/user_service/get_all_roles.py similarity index 95% rename from examples/dfp/v201505/user_service/get_all_roles.py rename to examples/dfp/v201605/user_service/get_all_roles.py index 6ba977be..ba3a4607 100755 --- a/examples/dfp/v201505/user_service/get_all_roles.py +++ b/examples/dfp/v201605/user_service/get_all_roles.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201505') + user_service = client.GetService('UserService', version='v201605') # Get all roles. roles = user_service.getAllRoles() diff --git a/examples/dfp/v201505/user_service/get_all_users.py b/examples/dfp/v201605/user_service/get_all_users.py similarity index 95% rename from examples/dfp/v201505/user_service/get_all_users.py rename to examples/dfp/v201605/user_service/get_all_users.py index 24e4aeb0..a50c9be6 100755 --- a/examples/dfp/v201505/user_service/get_all_users.py +++ b/examples/dfp/v201605/user_service/get_all_users.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201505') + user_service = client.GetService('UserService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/user_service/get_current_user.py b/examples/dfp/v201605/user_service/get_current_user.py similarity index 94% rename from examples/dfp/v201505/user_service/get_current_user.py rename to examples/dfp/v201605/user_service/get_current_user.py index c676f5da..020ee7be 100755 --- a/examples/dfp/v201505/user_service/get_current_user.py +++ b/examples/dfp/v201605/user_service/get_current_user.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201505') + user_service = client.GetService('UserService', version='v201605') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201505/user_service/get_users_by_statement.py b/examples/dfp/v201605/user_service/get_users_by_statement.py similarity index 96% rename from examples/dfp/v201505/user_service/get_users_by_statement.py rename to examples/dfp/v201605/user_service/get_users_by_statement.py index 4e1d3bcb..b6f039e0 100755 --- a/examples/dfp/v201505/user_service/get_users_by_statement.py +++ b/examples/dfp/v201605/user_service/get_users_by_statement.py @@ -27,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201505') + user_service = client.GetService('UserService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/user_service/update_users.py b/examples/dfp/v201605/user_service/update_users.py similarity index 96% rename from examples/dfp/v201505/user_service/update_users.py rename to examples/dfp/v201605/user_service/update_users.py index 1feab89c..8d462f65 100755 --- a/examples/dfp/v201505/user_service/update_users.py +++ b/examples/dfp/v201605/user_service/update_users.py @@ -27,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201505') + user_service = client.GetService('UserService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/user_team_association_service/__init__.py b/examples/dfp/v201605/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201505/user_team_association_service/__init__.py rename to examples/dfp/v201605/user_team_association_service/__init__.py diff --git a/examples/dfp/v201505/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201605/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201505/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201605/user_team_association_service/create_user_team_associations.py index bdca5233..50c29f6b 100755 --- a/examples/dfp/v201505/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201605/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201505') + 'UserTeamAssociationService', version='v201605') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201605/user_team_association_service/delete_user_team_associations.py similarity index 98% rename from examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201605/user_team_association_service/delete_user_team_associations.py index 89d08795..0afcf796 100755 --- a/examples/dfp/v201505/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201605/user_team_association_service/delete_user_team_associations.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201505') + 'UserTeamAssociationService', version='v201605') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201605/user_team_association_service/get_all_user_team_associations.py similarity index 97% rename from examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201605/user_team_association_service/get_all_user_team_associations.py index 592881b7..66bd27f3 100755 --- a/examples/dfp/v201505/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201605/user_team_association_service/get_all_user_team_associations.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201505') + 'UserTeamAssociationService', version='v201605') # Create a filter statement. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201605/user_team_association_service/get_user_team_associations_for_user.py similarity index 97% rename from examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201605/user_team_association_service/get_user_team_associations_for_user.py index f7210bd4..e63e5a32 100755 --- a/examples/dfp/v201505/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201605/user_team_association_service/get_user_team_associations_for_user.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201505') + 'UserTeamAssociationService', version='v201605') # Create query. values = [{ diff --git a/examples/dfp/v201505/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201605/user_team_association_service/update_user_team_associations.py similarity index 98% rename from examples/dfp/v201505/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201605/user_team_association_service/update_user_team_associations.py index 42b69bae..9f2fa3f0 100755 --- a/examples/dfp/v201505/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201605/user_team_association_service/update_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201505') + 'UserTeamAssociationService', version='v201605') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201505/workflow_request_service/__init__.py b/examples/dfp/v201605/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201505/workflow_request_service/__init__.py rename to examples/dfp/v201605/workflow_request_service/__init__.py diff --git a/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201605/workflow_request_service/approve_workflow_approval_requests.py similarity index 97% rename from examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201605/workflow_request_service/approve_workflow_approval_requests.py index d20e0f96..e208569c 100755 --- a/examples/dfp/v201505/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201605/workflow_request_service/approve_workflow_approval_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201505') + version='v201605') # Create query. values = [ diff --git a/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201605/workflow_request_service/get_workflow_approval_requests_by_statement.py similarity index 96% rename from examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py rename to examples/dfp/v201605/workflow_request_service/get_workflow_approval_requests_by_statement.py index 92b98fcf..3a1c617b 100755 --- a/examples/dfp/v201505/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201605/workflow_request_service/get_workflow_approval_requests_by_statement.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201505') + version='v201605') # Create statement object to select all workflow approval requests. values = [{ diff --git a/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201605/workflow_request_service/get_workflow_external_condition_requests_by_statement.py similarity index 97% rename from examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py rename to examples/dfp/v201605/workflow_request_service/get_workflow_external_condition_requests_by_statement.py index f03696ae..6c71774d 100755 --- a/examples/dfp/v201505/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201605/workflow_request_service/get_workflow_external_condition_requests_by_statement.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201505') + version='v201605') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201605/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 98% rename from examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201605/workflow_request_service/trigger_workflow_external_condition_requests.py index eb08a09c..3564703d 100755 --- a/examples/dfp/v201505/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201605/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201505') + version='v201605') # Create query. values = [ diff --git a/googleads.yaml b/googleads.yaml index 3358bb82..f4c02277 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -53,9 +53,20 @@ dfp: # Proxy configurations (optional) -# proxy_info: -# host: INSERT_HOST_HERE -# port: INSERT_PROXY_PORT_HERE -# The following values are optional: -# disable_ssl_certificate_validation: False -# ca_certs: INSERT_PATH_HERE +# proxy_config: + # If specified, the given cafile will only be used if certificate validation + # is not disabled. + # cafile: INSERT_PATH_HERE + # disable_certificate_validation: False + # http_proxy: + # host: INSERT_HOST_HERE + # port: INSERT_PROXY_PORT_HERE + # The following values are optional: + # username: INSERT_USERNAME_HERE + # password: INSERT_PASSWORD_HERE + # https_proxy: + # host: INSERT_HOST_HERE + # port: INSERT_PROXY_PORT_HERE + # The following values are optional: + # username: INSERT_USERNAME_HERE + # password: INSERT_PASSWORD_HERE diff --git a/googleads/adwords.py b/googleads/adwords.py index b1fcaca9..51e1a3cb 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -240,7 +240,7 @@ def LoadFromStorage(cls, path=None): def __init__( self, developer_token, oauth2_client, user_agent, client_customer_id=None, validate_only=False, partial_failure=False, - https_proxy=None, cache=None): + cache=None, proxy_config=None): """Initializes an AdWordsClient. For more information on these arguments, see our SOAP headers guide: @@ -264,9 +264,9 @@ def __init__( succeed, to result in a complete failure with no changes made or a partial failure with some changes made. Only certain services respect this header. - https_proxy: A string identifying the proxy that all HTTPS requests - should be routed through. cache: A subclass of suds.cache.Cache; defaults to None. + proxy_config: A googleads.common.ProxyConfig instance or None if a proxy + isn't being used. """ self.developer_token = developer_token self.oauth2_client = oauth2_client @@ -275,8 +275,9 @@ def __init__( self.client_customer_id = client_customer_id self.validate_only = validate_only self.partial_failure = partial_failure - self.https_proxy = https_proxy self.cache = cache + self.proxy_config = (proxy_config if proxy_config + else googleads.common.ProxyConfig()) def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server=_DEFAULT_ENDPOINT): @@ -300,16 +301,11 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], """ if server[-1] == '/': server = server[:-1] try: - proxy_option = None - if self.https_proxy: - proxy_option = { - 'https': self.https_proxy - } - client = suds.client.Client( self._SOAP_SERVICE_FORMAT % (server, _SERVICE_MAP[version][service_name], version, service_name), - proxy=proxy_option, cache=self.cache, timeout=3600) + cache=self.cache, timeout=3600, + transport=self.proxy_config.GetSudsProxyTransport()) except KeyError: if version in _SERVICE_MAP: raise googleads.errors.GoogleAdsValueError( @@ -557,7 +553,7 @@ def __init__(self, **kwargs): raise AttributeError('No client specified for Request Builder.') self._version = kwargs.get('version', sorted(_SERVICE_MAP.keys())[-1]) - self._client = kwargs['client'] + self.client = kwargs['client'] server = kwargs.get('server', _DEFAULT_ENDPOINT) self._adwords_endpoint = ('%s/api/adwords/cm/%s' % (server, self._version)) @@ -735,7 +731,7 @@ def _GenerateRawRequestXML(self, operations): except KeyError, e: raise googleads.errors.GoogleAdsValueError('"%s" is an unsupported ' 'operation.' % e.message) - service = self._client.GetService(operation.service, self._version) + service = self.client.GetService(operation.service, self._version) service.suds_client.set_options(nosend=True) service_request = (getattr(service, operation.method) (operations).envelope) @@ -914,9 +910,12 @@ def __init__(self, request_builder, upload_url, current_content_length=0, raise googleads.errors.GoogleAdsValueError( 'Current content length %s is < 0.' % current_content_length) self._current_content_length = current_content_length - self._upload_url = self._InitializeURL(upload_url, current_content_length) self._is_last = is_last + self._url_opener = urllib2.build_opener( + *self._request_builder.client.proxy_config.GetHandlers()) + self._upload_url = self._InitializeURL(upload_url, current_content_length) + def _InitializeURL(self, upload_url, current_content_length): """Ensures that the URL used to upload operations is properly initialized. @@ -945,7 +944,7 @@ def _InitializeURL(self, upload_url, current_content_length): # Send an HTTP POST request to the given upload_url req = urllib2.Request(upload_url, data={}, headers=headers) - resp = urllib2.urlopen(req) + resp = self._url_opener.open(req) return resp.headers['location'] @@ -995,7 +994,7 @@ def UploadOperations(self, operations, is_last=False): # Make the request, ignoring the urllib2.HTTPError raised due to HTTP status # code 308 (for resumable uploads). try: - urllib2.urlopen(req) + self._url_opener.open(req) except urllib2.HTTPError, e: if e.code != 308: raise urllib2.HTTPError(e) @@ -1037,22 +1036,16 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], self._namespace = self._NAMESPACE_FORMAT % version self._end_point = self._END_POINT_FORMAT % (server, version) self._header_handler = _AdWordsHeaderHandler(adwords_client, version) - - proxy_option = None - if self._adwords_client.https_proxy: - proxy_option = {'https': self._adwords_client.https_proxy} - # Create an Opener to handle requests when downloading reports. - self.url_opener = urllib2.build_opener( - urllib2.ProxyHandler({'https': self._adwords_client.https_proxy})) - else: - self.url_opener = urllib2.build_opener() + self.proxy_config = self._adwords_client.proxy_config + self.url_opener = urllib2.build_opener(*self.proxy_config.GetHandlers()) schema_url = self._SCHEMA_FORMAT % (server, version) schema = suds.client.Client( schema_url, doctor=suds.xsd.doctor.ImportDoctor(suds.xsd.doctor.Import( self._namespace, schema_url)), - proxy=proxy_option, cache=self._adwords_client.cache).wsdl.schema + transport=self.proxy_config.GetSudsProxyTransport(), + cache=self._adwords_client.cache).wsdl.schema self._report_definition_type = schema.elements[ (self._REPORT_DEFINITION_NAME, self._namespace)] self._marshaller = suds.mx.literal.Literal(schema) diff --git a/googleads/common.py b/googleads/common.py index 10626cec..fa8dc942 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -16,21 +16,34 @@ import os +import ssl import sys +import urllib2 import warnings import httplib2 import socks import suds +import suds.transport.http import yaml import googleads.errors import googleads.oauth2 import googleads.patches -VERSION = '3.15.0' +try: + import urllib2.HTTPSHandler +except ImportError: + # Python versions below 2.7.9 / 3.4 won't have this. In order to offer legacy + # support (for now) we will work around this gracefully, but users will + # not have certificate validation performed until they update. + pass + +VERSION = '4.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION -_PROXY_YAML_KEY = 'proxy_info' +_HTTP_PROXY_YAML_KEY = 'http_proxy' +_HTTPS_PROXY_YAML_KEY = 'https_proxy' +_PROXY_CONFIG_KEY = 'proxy_config' _PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) @@ -40,7 +53,8 @@ _OAUTH2_SERVICE_ACCT_KEYS = ('service_account_email', 'path_to_private_key_file') -# The keys in the proxy dictionary that are used to construct a ProxyInfo +# The keys in the http_proxy and https_proxy dictionaries that are used to +# construct a Proxy, HTTPSProxy, and ProxyConfig instances. # instance. _PROXY_KEYS = ('host', 'port') @@ -64,8 +78,8 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, """Loads the data necessary for instantiating a client from file storage. In addition to the required_client_values argument, the yaml file must supply - the keys used to create OAuth2 credentials. It may also optionally provide - proxy_info in order to configure a proxy. + the keys used to create OAuth2 credentials. It may also optionally set proxy + configurations. Args: path: A path string to the yaml document whose keys should be used. @@ -92,7 +106,7 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, with open(path, 'rb') as handle: data = yaml.safe_load(handle.read()) product_data = data[product_yaml_key] - proxy_data = data.get(_PROXY_YAML_KEY) or {} + proxy_config_data = data.get(_PROXY_CONFIG_KEY) or {} except IOError: raise googleads.errors.GoogleAdsValueError( 'Given yaml file, %s, could not be opened.' % path) @@ -102,7 +116,6 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, % (path, product_yaml_key)) original_keys = list(product_data.keys()) - original_proxy_keys = list(proxy_data.keys()) client_kwargs = {} try: for key in required_client_values: @@ -114,32 +127,54 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, 'values are: %s, actual values are %s' % (path, required_client_values, original_keys)) + http_proxy = None + https_proxy = None + + # HTTP Proxy Config try: - proxy_info = (httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, proxy_data['host'], - proxy_data['port']) - if proxy_data else None) - client_kwargs['https_proxy'] = ('%s:%s' % (proxy_info.proxy_host, - proxy_info.proxy_port) - if proxy_info else None) + if 'http_proxy' in proxy_config_data: + http_proxy_data = proxy_config_data.get('http_proxy') + original_http_proxy_keys = list(http_proxy_data.keys()) + http_proxy = ProxyConfig.Proxy( + http_proxy_data['host'], http_proxy_data['port'], + username=http_proxy_data.get('username'), + password=http_proxy_data.get('password')) except KeyError: raise googleads.errors.GoogleAdsValueError( - 'Your yaml file, %s, is missing some of the required proxy values.' - 'Required values are: %s, actual values are %s' - % (path, _PROXY_KEYS, original_proxy_keys)) - - ca_certs = proxy_data.get('ca_certs', None) - disable_ssl_certificate_validation = proxy_data.get( - 'disable_ssl_certificate_validation', True) + 'Your yaml file, %s, is missing some of the required http proxy ' + 'values. Required values are: %s, actual values are %s' + % (path, _PROXY_KEYS, original_http_proxy_keys)) + # HTTPS Proxy Config + # Note: If both HTTP and HTTPS proxies are specified, the ProxyInfo used + # by oauth2.py will always be the HTTPS proxy. + try: + if 'https_proxy' in proxy_config_data: + https_proxy_data = proxy_config_data.get('https_proxy') + original_https_proxy_keys = list(https_proxy_data.keys()) + https_proxy = ProxyConfig.Proxy( + https_proxy_data['host'], https_proxy_data['port'], + username=https_proxy_data.get('username'), + password=https_proxy_data.get('password')) + except KeyError: + raise googleads.errors.GoogleAdsValueError( + 'Your yaml file, %s, is missing some of the required https proxy ' + 'values. Required values are: %s, actual values are %s' + % (path, _PROXY_KEYS, original_https_proxy_keys)) + + cafile = proxy_config_data.get('cafile', None) + disable_certificate_validation = proxy_config_data.get( + 'disable_certificate_validation', False) + proxy_config = ProxyConfig( + http_proxy=http_proxy, https_proxy=https_proxy, cafile=cafile, + disable_certificate_validation=disable_certificate_validation) + client_kwargs['proxy_config'] = proxy_config if all(config in product_data for config in _OAUTH2_INSTALLED_APP_KEYS): # Use provided configurations for the installed application flow. client_kwargs['oauth2_client'] = ( googleads.oauth2.GoogleRefreshTokenClient( product_data['client_id'], product_data['client_secret'], - product_data['refresh_token'], proxy_info=proxy_info, - disable_ssl_certificate_validation=( - disable_ssl_certificate_validation), - ca_certs=ca_certs)) + product_data['refresh_token'], proxy_config=proxy_config)) for key in _OAUTH2_INSTALLED_APP_KEYS: del product_data[key] elif all(config in product_data for config in _OAUTH2_SERVICE_ACCT_KEYS): @@ -148,10 +183,8 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, googleads.oauth2.GoogleServiceAccountClient( googleads.oauth2.GetAPIScope(product_yaml_key), product_data['service_account_email'], - product_data['path_to_private_key_file'], proxy_info=proxy_info, - disable_ssl_certificate_validation=( - disable_ssl_certificate_validation), - ca_certs=ca_certs)) + product_data['path_to_private_key_file'], + proxy_config=proxy_config)) for key in _OAUTH2_SERVICE_ACCT_KEYS: del product_data[key] else: @@ -269,6 +302,148 @@ def _IsSudsIterable(obj): return (obj and not isinstance(obj, basestring) and hasattr(obj, '__iter__')) +class ProxyConfig(object): + """A utility for configuring the usage of a proxy.""" + + def __init__(self, http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False): + self._http_proxy = http_proxy + self._https_proxy = https_proxy + # Initialize httplib2.ProxyInfo used by oauth2client and a proxy option + # dictionary used to generate the urllib2.ProxyHandler used by suds and + # urllib2. For the ProxyInfo object, the HTTPS proxy will always be used + # over the HTTP proxy if it is available. + self.proxy_info = None + self._proxy_option = {} + if self._https_proxy: + self.proxy_info = httplib2.ProxyInfo( + socks.PROXY_TYPE_HTTP, self._https_proxy.host, self._https_proxy.port, + proxy_user=self._https_proxy.username, + proxy_pass=self._https_proxy.password) + self._proxy_option['https'] = str(self._https_proxy) + if self._http_proxy: + if not self.proxy_info: + self.proxy_info = httplib2.ProxyInfo( + socks.PROXY_TYPE_HTTP, self._http_proxy.host, self._http_proxy.port, + proxy_user=self._http_proxy.username, + proxy_pass=self._http_proxy.password) + self._proxy_option['http'] = str(self._http_proxy) + + self.disable_certificate_validation = disable_certificate_validation + self.cafile = None if disable_certificate_validation else cafile + # Initialize the context used to generate the urllib2.HTTPSHandler (in + # Python 2.7.9+ and 3.4+) used by suds and urllib2. + self._ssl_context = self._InitSSLContext( + self.cafile, self.disable_certificate_validation) + + def _InitSSLContext(self, cafile=None, + disable_ssl_certificate_validation=False): + """Creates a ssl.SSLContext with the given settings. + + Args: + cafile: A str identifying the resolved path to the cafile. If not set, + this will use the system default cafile. + disable_ssl_certificate_validation: A boolean indicating whether + certificate verification is disabled. For security purposes, it is + highly recommended that certificate verification remain enabled. + + Returns: + An ssl.SSLContext instance, or None if the version of Python being used + doesn't support it. + """ + # Attempt to create a context; this should succeed in Python 2 versions + # 2.7.9+ and Python 3 versions 3.4+. + try: + ssl_context = ssl.create_default_context(cafile=cafile) + except AttributeError: + # Earlier versions lack ssl.create_default_context() + # Rather than raising the exception, no context will be provided for + # legacy support. Of course, this means no certificate validation is + # taking place! + return None + + if disable_ssl_certificate_validation: + ssl_context.verify_mode = ssl.CERT_NONE + + return ssl_context + + def GetHandlers(self): + """Retrieve the appropriate urllib2 handlers for the given configuration. + + Returns: + A list of urllib2.BaseHandler subclasses to be used when making calls + with proxy. + """ + handlers = [] + + if self._ssl_context: + handlers.append(urllib2.HTTPSHandler(self._ssl_context)) + + if self._proxy_option: + handlers.append(urllib2.ProxyHandler(self._proxy_option)) + + return handlers + + def GetSudsProxyTransport(self): + """Retrieve a suds.transport.http.HttpTransport to be used with suds. + + This will apply all handlers relevant to the usage of the proxy + configuration automatically. + + Returns: + A _SudsProxyTransport instance used to make requests with suds using the + configured proxy. + """ + return self._SudsProxyTransport(self.GetHandlers()) + + class Proxy(object): + """Defines settings for a proxy connection.""" + + STR_TEMPLATE = '%s:%s' + CRED_TEMPLATE = '%s@%s' + + def __init__(self, host, port, username=None, password=''): + self.host = host + self.port = port + self.username = username + self.password = password + + def __str__(self): + if self.username: + s = self.CRED_TEMPLATE % ( + self.STR_TEMPLATE % ( + self.username, self.password), + self.STR_TEMPLATE % (self.host, self.port)) + else: + s = self.STR_TEMPLATE % (self.host, self.port) + return s + + class _SudsProxyTransport(suds.transport.http.HttpTransport): + """A transport that applies the given handlers for usage with a proxy.""" + + def __init__(self, handlers, **kwargs): + """Initializes SudsHTTPSTransport. + + Args: + handlers: an iterable of urllib2.BaseHandler subclasses. + **kwargs: Keyword arguments. + """ + suds.transport.http.HttpTransport.__init__(self, **kwargs) + self.handlers = handlers + + def u2handlers(self): + """Get a collection of urllib2 handlers to be installed in the opener. + + Returns: + A list of handlers to be installed to the OpenerDirector used by suds. + """ + # Start with the default set of handlers. + return_handlers = suds.transport.http.HttpTransport.u2handlers(self) + return_handlers.extend(self.handlers) + + return return_handlers + + class SudsServiceProxy(object): """Wraps a suds service object, allowing custom logic to be injected. diff --git a/googleads/dfp.py b/googleads/dfp.py index 80be77b0..15ba30d8 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -39,7 +39,7 @@ _CHUNK_SIZE = 16 * 1024 # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201502': + 'v201505': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -59,7 +59,7 @@ 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201505': + 'v201508': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -76,10 +76,11 @@ 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', + 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201508': + 'v201511': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -100,7 +101,7 @@ 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201511': + 'v201602': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -118,10 +119,10 @@ 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', + 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201602': + 'v201605': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -196,7 +197,7 @@ def LoadFromStorage(cls, path=None): cls._OPTIONAL_INIT_VALUES)) def __init__(self, oauth2_client, application_name, network_code=None, - https_proxy=None, cache=None): + cache=None, proxy_config=None): """Initializes a DfpClient. For more information on these arguments, see our SOAP headers guide: @@ -211,9 +212,9 @@ def __init__(self, oauth2_client, application_name, network_code=None, network_code: A string identifying the network code of the network you are accessing. All requests other than getAllNetworks and getCurrentUser calls require this header to be set. - https_proxy: A string identifying the proxy that all HTTPS requests - should be routed through. cache: A subclass of suds.cache.Cache; defaults to None. + proxy_config: A googleads.common.ProxyConfig instance or None if a proxy + isn't being used. """ if application_name is DEFAULT_APPLICATION_NAME: raise googleads.errors.GoogleAdsValueError( @@ -223,9 +224,10 @@ def __init__(self, oauth2_client, application_name, network_code=None, self.oauth2_client = oauth2_client self.application_name = application_name self.network_code = network_code - self.https_proxy = https_proxy self.cache = cache self._header_handler = _DfpHeaderHandler(self) + self.proxy_config = (proxy_config if proxy_config + else googleads.common.ProxyConfig()) def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server=DEFAULT_ENDPOINT): @@ -249,15 +251,10 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], """ server = server[:-1] if server[-1] == '/' else server try: - proxy_option = None - if self.https_proxy: - proxy_option = { - 'https': self.https_proxy - } - client = suds.client.Client( self._SOAP_SERVICE_FORMAT % (server, version, service_name), - proxy=proxy_option, cache=self.cache, timeout=3600) + cache=self.cache, timeout=3600, + transport=self.proxy_config.GetSudsProxyTransport()) except suds.transport.TransportError: if version in _SERVICE_MAP: if service_name in _SERVICE_MAP[version]: @@ -368,6 +365,8 @@ def __init__(self, dfp_client, version=sorted(_SERVICE_MAP.keys())[-1], self._server = server self._report_service = None self._pql_service = None + self.proxy_config = self._dfp_client.proxy_config + self.url_opener = urllib2.build_opener(*self.proxy_config.GetHandlers()) def _GetReportService(self): """Lazily initializes a report service client.""" @@ -430,7 +429,7 @@ def DownloadReportToFile(self, report_job_id, export_format, outfile): """ service = self._GetReportService() report_url = service.getReportDownloadURL(report_job_id, export_format) - response = urllib2.urlopen(report_url) + response = self.url_opener.open(report_url) while True: chunk = response.read(_CHUNK_SIZE) if not chunk: break diff --git a/googleads/oauth2.py b/googleads/oauth2.py index e0affb53..fdea66e7 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -102,8 +102,8 @@ class GoogleRefreshTokenClient(GoogleOAuth2Client): _TOKEN_URL = 'https://www.google.com' _USER_AGENT = 'Google Ads Python Client Library' - def __init__(self, client_id, client_secret, refresh_token, proxy_info=None, - disable_ssl_certificate_validation=False, ca_certs=None): + def __init__(self, client_id, client_secret, refresh_token, + proxy_config=None): """Initializes a GoogleRefreshTokenClient. Args: @@ -111,20 +111,15 @@ def __init__(self, client_id, client_secret, refresh_token, proxy_info=None, client_secret: A string containing your client secret. refresh_token: A string containing your refresh token. [optional] - proxy_info: A ProxyInfo instance identifying the proxy used for all - requests. - disable_ssl_certificate_validation: A boolean indicating whether ssl - certificate validation should be disabled while using a proxy. - ca_certs: A string identifying the path to a file containing root CA - certificates for SSL server certificate validation. + proxy_config: A googleads.common.ProxyConfig instance or None if a proxy + isn't being used. """ self.oauth2credentials = oauth2client.client.OAuth2Credentials( None, client_id, client_secret, refresh_token, datetime.datetime(1980, 1, 1, 12), self._GOOGLE_OAUTH2_ENDPOINT, self._USER_AGENT) - self.proxy_info = proxy_info - self.disable_ssl_certificate_validation = disable_ssl_certificate_validation - self.ca_certs = ca_certs + self.proxy_config = (proxy_config if proxy_config + else googleads.common.ProxyConfig()) def CreateHttpHeader(self): """Creates an OAuth2 HTTP header. @@ -158,10 +153,10 @@ def Refresh(self): """ self.oauth2credentials.refresh( httplib2.Http( - proxy_info=self.proxy_info, - ca_certs=self.ca_certs, + proxy_info=self.proxy_config.proxy_info, + ca_certs=self.proxy_config.cafile, disable_ssl_certificate_validation=( - self.disable_ssl_certificate_validation))) + self.proxy_config.disable_certificate_validation))) class GoogleServiceAccountClient(GoogleOAuth2Client): @@ -180,8 +175,7 @@ class GoogleServiceAccountClient(GoogleOAuth2Client): _USER_AGENT = 'Google Ads Python Client Library' def __init__(self, scope, client_email, key_file, - private_key_password='notasecret', sub=None, proxy_info=None, - disable_ssl_certificate_validation=False, ca_certs=None): + private_key_password='notasecret', sub=None, proxy_config=None): """Initializes a GoogleServiceAccountClient. Args: @@ -192,12 +186,7 @@ def __init__(self, scope, client_email, key_file, private_key_password: A string containing the password for your key file. sub: A string containing the email address of a user account you want to impersonate. - proxy_info: A ProxyInfo instance identifying the proxy used for all - requests. - disable_ssl_certificate_validation: A boolean indicating whether ssl - certificate validation should be disabled while using a proxy. - ca_certs: A string identifying the path to a file containing root CA - certificates for SSL server certificate validation. + proxy_config: A googleads.common.ProxyConfig instance. Raises: GoogleAdsValueError: If the given key file does not exist. @@ -213,9 +202,7 @@ def __init__(self, scope, client_email, key_file, client_email, private_key, scope, private_key_password=private_key_password, user_agent=self._USER_AGENT, sub=sub) - self.proxy_info = proxy_info - self.disable_ssl_certificate_validation = disable_ssl_certificate_validation - self.ca_certs = ca_certs + self.proxy_config = proxy_config self.Refresh() def CreateHttpHeader(self): @@ -250,7 +237,7 @@ def Refresh(self): """ self.oauth2credentials.refresh( httplib2.Http( - proxy_info=self.proxy_info, - ca_certs=self.ca_certs, + proxy_info=self.proxy_config.proxy_info, + ca_certs=self.proxy_config.cafile, disable_ssl_certificate_validation=( - self.disable_ssl_certificate_validation))) + self.proxy_config.disable_certificate_validation))) diff --git a/tests/adwords_test.py b/tests/adwords_test.py index af7691a9..4f298913 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -38,27 +38,69 @@ CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] -def GetAdWordsClient(): - """Returns an initialized AdwordsClient for use in testing.""" +def GetAdWordsClient(proxy_config=None): + """Returns an initialized AdwordsClient for use in testing. + + Args: + proxy_config: A googleads.common.ProxyConfig or None if no proxy is being + used. + + Returns: + An AdWordsClient instance with or without a proxy configured depending on + whether a ProxyConfig instance was provided. + """ oauth_header = {'Authorization': 'header'} client_customer_id = 'client customer id' dev_token = 'N3v3rG0nN4Giv3Y0uUp' user_agent = 'N3v3rG0nN4l37y0uDoWN' oauth2_client = mock.Mock() oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) + client = googleads.adwords.AdWordsClient( dev_token, oauth2_client, user_agent, - client_customer_id=client_customer_id) + client_customer_id=client_customer_id, proxy_config=proxy_config) + return client +def GetProxyConfig(http_host=None, http_port=None, https_host=None, + https_port=None, cafile=None, + disable_certificate_validation=None): + """Returns an initialized ProxyConfig for use in testing. + + Args: + http_host: A str containing the url or IP of an http proxy host. + http_port: An int port number for the HTTP proxy host. + https_host: A str containing the url or IP of an https proxy host. + https_port: An int port number for the HTTPS proxy host. + cafile: A str containing the path to a custom ca file. + disable_certificate_validation: A boolean indicating whether or not to + disable certificate validation. + + Returns: + An initialized ProxyConfig using the given configurations. + """ + http_proxy = None + https_proxy = None + + if http_host: + http_proxy = googleads.common.ProxyConfig.Proxy(http_host, http_port) + + if https_host: + https_proxy = googleads.common.ProxyConfig.Proxy(https_host, https_port) + + return googleads.common.ProxyConfig( + http_proxy, https_proxy, cafile=cafile, + disable_certificate_validation=disable_certificate_validation) + + class AdWordsHeaderHandlerTest(unittest.TestCase): """Tests for the googleads.adwords._AdWordsHeaderHandler class.""" def setUp(self): - self.adwords_client = mock.Mock() + self.aw_client = mock.Mock() self.header_handler = googleads.adwords._AdWordsHeaderHandler( - self.adwords_client, CURRENT_VERSION) + self.aw_client, CURRENT_VERSION) def testSetHeaders(self): suds_client = mock.Mock() @@ -68,13 +110,12 @@ def testSetHeaders(self): validate_only = True partial_failure = False oauth_header = {'oauth': 'header'} - self.adwords_client.client_customer_id = ccid - self.adwords_client.developer_token = dev_token - self.adwords_client.user_agent = user_agent - self.adwords_client.validate_only = validate_only - self.adwords_client.partial_failure = partial_failure - self.adwords_client.oauth2_client.CreateHttpHeader.return_value = ( - oauth_header) + self.aw_client.client_customer_id = ccid + self.aw_client.developer_token = dev_token + self.aw_client.user_agent = user_agent + self.aw_client.validate_only = validate_only + self.aw_client.partial_failure = partial_failure + self.aw_client.oauth2_client.CreateHttpHeader.return_value = (oauth_header) self.header_handler.SetHeaders(suds_client) @@ -100,10 +141,10 @@ def testGetReportDownloadHeaders(self): dev_token = 'developer token' user_agent = 'user agent!' oauth_header = {'Authorization': 'header'} - self.adwords_client.client_customer_id = ccid - self.adwords_client.developer_token = dev_token - self.adwords_client.user_agent = user_agent - self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( + self.aw_client.client_customer_id = ccid + self.aw_client.developer_token = dev_token + self.aw_client.user_agent = user_agent + self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', @@ -118,7 +159,7 @@ def testGetReportDownloadHeaders(self): 'skipReportSummary': 'False' } - self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( + self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( @@ -130,9 +171,9 @@ def testGetReportDownloadHeadersWithInvalidKeyword(self): ccid = 'client customer id' dev_token = 'developer token' user_agent = 'user agent!' - self.adwords_client.client_customer_id = ccid - self.adwords_client.developer_token = dev_token - self.adwords_client.user_agent = user_agent + self.aw_client.client_customer_id = ccid + self.aw_client.developer_token = dev_token + self.aw_client.user_agent = user_agent self.assertRaises( googleads.errors.GoogleAdsValueError, @@ -144,10 +185,10 @@ def testGetReportDownloadHeadersWithOptionalHeaders(self): dev_token = 'developer token' user_agent = 'user agent!' oauth_header = {'Authorization': 'header'} - self.adwords_client.client_customer_id = ccid - self.adwords_client.developer_token = dev_token - self.adwords_client.user_agent = user_agent - self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( + self.aw_client.client_customer_id = ccid + self.aw_client.developer_token = dev_token + self.aw_client.user_agent = user_agent + self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', @@ -163,7 +204,7 @@ def testGetReportDownloadHeadersWithOptionalHeaders(self): 'includeZeroImpressions': 'True' } - self.adwords_client.oauth2_client.CreateHttpHeader.return_value = dict( + self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( @@ -177,10 +218,14 @@ class AdWordsClientTest(unittest.TestCase): """Tests for the googleads.adwords.AdWordsClient class.""" def setUp(self): - self.https_proxy = 'myproxy:443' + self.https_proxy_host = 'myproxy' + self.https_proxy_port = 443 + self.proxy_config = GetProxyConfig(https_host=self.https_proxy_host, + https_port=self.https_proxy_port) self.cache = None self.adwords_client = GetAdWordsClient() - self.adwords_client.https_proxy = self.https_proxy + self.aw_client = GetAdWordsClient( + proxy_config=self.proxy_config) self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.adwords_client, CURRENT_VERSION) @@ -198,36 +243,43 @@ def testGetService_success(self): version = CURRENT_VERSION service = googleads.adwords._SERVICE_MAP[version].keys()[0] namespace = googleads.adwords._SERVICE_MAP[version][service] + mock_transport_instance = mock.Mock() # Use a custom server. Also test what happens if the server ends with a # trailing slash server = 'https://testing.test.com/' - https_proxy = {'https': self.https_proxy} with mock.patch('suds.client.Client') as mock_client: - suds_service = self.adwords_client.GetService(service, version, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, version, service), proxy=https_proxy, cache=self.cache, - timeout=3600) + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' + ) as mock_transport: + mock_transport.return_value = mock_transport_instance + suds_service = self.aw_client.GetService( + service, version, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' + % (namespace, version, service), cache=self.cache, + transport=mock_transport_instance, timeout=3600) self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) - # Use the default server and https_proxy. - self.adwords_client.https_proxy = None + # Use the default server without a proxy. with mock.patch('suds.client.Client') as mock_client: - suds_service = self.adwords_client.GetService(service, version) - - mock_client.assert_called_once_with( - 'https://adwords.google.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, version, service), proxy=None, cache=self.cache, - timeout=3600) - self.assertFalse(mock_client.return_value.set_options.called) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' + ) as mock_transport: + mock_transport.return_value = mock_transport_instance + suds_service = self.adwords_client.GetService(service, version) + + mock_client.assert_called_once_with( + 'https://adwords.google.com/api/adwords/%s/%s/%s?wsdl' + % (namespace, version, service), cache=self.cache, + transport=mock_transport_instance, timeout=3600) + self.assertFalse(mock_client.return_value.set_options.called) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_badService(self): version = CURRENT_VERSION self.assertRaises( - googleads.errors.GoogleAdsValueError, self.adwords_client.GetService, + googleads.errors.GoogleAdsValueError, + self.adwords_client.GetService, 'GYIVyievfyiovslf', version) def testGetService_badVersion(self): @@ -277,14 +329,15 @@ def testUploadOperations(self): with mock.patch('googleads.adwords.BatchJobHelper.' '_SudsUploadRequestBuilder.' 'BuildUploadRequest') as mock_build_request: - mock_request = mock.MagicMock() + mock_request = mock.Mock() + mock_request.data = 'in disguise.' mock_build_request.return_value = mock_request - with mock.patch('urllib2.urlopen') as mock_urlopen: - with mock.patch('googleads.adwords.IncrementalUploadHelper' - '._InitializeURL') as mock_init: - mock_init.return_value = 'https://www.google.com' + with mock.patch('googleads.adwords.IncrementalUploadHelper' + '._InitializeURL') as mock_init: + mock_init.return_value = 'https://www.google.com' + with mock.patch('urllib2.OpenerDirector.open') as mock_open: self.batch_job_helper.UploadOperations([[]]) - mock_urlopen.assert_called_with(mock_request) + mock_open.assert_called_with(mock_request) class BatchJobUploadRequestBuilderTest(unittest.TestCase): @@ -1066,7 +1119,7 @@ def setUp(self): self.original_url = 'https://goo.gl/w8tkpK' self.initialized_url = 'https://goo.gl/Xtaq83' - with mock.patch('urllib2.urlopen') as mock_open: + with mock.patch('urllib2.OpenerDirector.open') as mock_open: mock_open.return_value.headers = { 'location': self.initialized_url } @@ -1097,8 +1150,11 @@ def testLoad(self): mock_open.return_value.headers = { 'location': self.initialized_url } - restored_uploader = googleads.adwords.IncrementalUploadHelper.Load( - s, client=self.client) + with mock.patch('googleads.adwords.IncrementalUploadHelper' + '._InitializeURL') as mock_init: + mock_init.return_value = self.initialized_url + restored_uploader = googleads.adwords.IncrementalUploadHelper.Load( + s, client=self.client) self.assertEquals(restored_uploader._current_content_length, self.incremental_uploader._current_content_length) @@ -1115,9 +1171,9 @@ def testUploadOperations(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('urllib2.urlopen') as mock_urlopen: + with mock.patch('urllib2.OpenerDirector.open') as mock_open: self.incremental_uploader.UploadOperations([[]], True) - mock_urlopen.assert_called_with(mock_request) + mock_open.assert_called_with(mock_request) def testUploadOperationsAfterFinished(self): with mock.patch('googleads.adwords.BatchJobHelper.' @@ -1125,7 +1181,7 @@ def testUploadOperationsAfterFinished(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('urllib2.urlopen'): + with mock.patch('urllib2.OpenerDirector.open'): self.incremental_uploader.UploadOperations([[]], True) self.assertRaises( googleads.errors.AdWordsBatchJobServiceInvalidOperationError, @@ -1222,8 +1278,9 @@ def setUp(self): self.marshaller = mock.Mock() self.header_handler = mock.Mock() self.adwords_client = mock.Mock() + self.adwords_client.proxy_config = GetProxyConfig() self.opener = mock.Mock() - self.adwords_client.https_proxy = 'my.proxy.gov:443' + with mock.patch('suds.client.Client'): with mock.patch('suds.xsd.doctor'): with mock.patch('suds.mx.literal.Literal') as mock_literal: diff --git a/tests/common_test.py b/tests/common_test.py index b50b5402..fa8872f1 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -16,6 +16,7 @@ import unittest +import urllib2 import warnings @@ -43,10 +44,12 @@ def setUp(self): self.filesystem = fake_filesystem.FakeFilesystem() self.tempfile = fake_tempfile.FakeTempfileModule(self.filesystem) self.fake_open = fake_filesystem.FakeFileOpen(self.filesystem) - self.fake_proxy = mock.Mock() - self.fake_proxy.return_value = mock.Mock() - self.fake_proxy.return_value.proxy_host = 'ahost' - self.fake_proxy.return_value.proxy_port = 'aport' + self.host1 = 'h1' + self.port1 = 'p1' + self.host2 = 'h2' + self.port2 = 'p2' + self.username = 'username' + self.password = 'password' def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): """Return the filename of a yaml file created for testing.""" @@ -97,40 +100,170 @@ def testLoadFromStorage_passesWithNoRequiredKeys(self): self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): - rval = googleads.common.LoadFromStorage(yaml_fname, 'woo', [], []) - mock_client.assert_called_once_with( - 'a', 'b', 'c', proxy_info=None, ca_certs=None, - disable_ssl_certificate_validation=True) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'https_proxy': None}, rval) - - def testLoadFromStorage_passesWithProxy(self): - yaml_fname = self._CreateYamlFile({'adwords': {}, - 'proxy_info': { - 'host': 'ahost', - 'port': 'aport' - }}, 'adwords', - self._OAUTH_INSTALLED_APP_DICT) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage(yaml_fname, 'woo', [], []) + + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value}, rval) + + def testLoadFromStorage_passesWithHTTPAndHTTPSProxy(self): + yaml_fname = self._CreateYamlFile( + {'adwords': {}, + 'proxy_config': { + 'http_proxy': {'host': self.host1, 'port': self.port1}, + 'https_proxy': {'host': self.host2, 'port': self.port2}}}, + insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): - with mock.patch('httplib2.ProxyInfo', self.fake_proxy): - rval = googleads.common.LoadFromStorage(yaml_fname, 'adwords', [], []) - mock_client.assert_called_once_with( - 'a', 'b', 'c', proxy_info=self.fake_proxy.return_value, - ca_certs=None, disable_ssl_certificate_validation=True) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'https_proxy': 'ahost:aport'}, rval) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: + proxy.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'adwords', [], []) + proxy.assert_has_calls([mock.call(self.host1, self.port1, + username=None, password=None), + mock.call(self.host2, self.port2, + username=None, password=None)]) + proxy_config.assert_called_once_with( + http_proxy=proxy.return_value, + https_proxy=proxy.return_value, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value}, rval) + + def testLoadFromStorage_passesWithHTTPProxy(self): + yaml_fname = self._CreateYamlFile( + {'adwords': {}, + 'proxy_config': { + 'http_proxy': {'host': self.host1, 'port': self.port1}}}, + insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: + proxy.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'adwords', [], []) + + proxy.assert_called_once_with(self.host1, self.port1, + username=None, password=None) + proxy_config.assert_called_once_with(http_proxy=proxy.return_value, + https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value}, rval) + + def testLoadFromStorage_passesWithHTTPProxyLogin(self): + yaml_fname = self._CreateYamlFile( + {'adwords': {}, + 'proxy_config': { + 'http_proxy': {'host': self.host1, 'port': self.port1, + 'username': self.username, + 'password': self.password}}}, + insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: + proxy.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'adwords', [], []) + + proxy.assert_called_once_with(self.host1, self.port1, + username=self.username, + password=self.password) + proxy_config.assert_called_once_with(http_proxy=proxy.return_value, + https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value}, rval) + + def testLoadFromStorage_passesWithHTTPSProxy(self): + yaml_fname = self._CreateYamlFile( + {'adwords': {}, + 'proxy_config': { + 'https_proxy': {'host': self.host1, 'port': self.port1}}}, + insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: + proxy.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'adwords', [], []) + + proxy.assert_called_once_with(self.host1, self.port1, + username=None, password=None) + proxy_config.assert_called_once_with(http_proxy=None, + https_proxy=proxy.return_value, + cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value}, rval) + + def testLoadFromStorage_passesWithHTTPSProxyLogin(self): + yaml_fname = self._CreateYamlFile( + {'adwords': {}, + 'proxy_config': { + 'https_proxy': {'host': self.host1, 'port': self.port1, + 'username': self.username, + 'password': self.password}}}, + insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: + proxy.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'adwords', [], []) + + proxy.assert_called_once_with(self.host1, self.port1, + username=self.username, + password=self.password) + proxy_config.assert_called_once_with(http_proxy=None, + https_proxy=proxy.return_value, + cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value}, rval) def testLoadFromStorage_failsWithMisconfiguredProxy(self): - yaml_fname = self._CreateYamlFile({'adwords': {}, - 'proxy_info': {'host': 'ahost'}}, - 'adwords', self._OAUTH_INSTALLED_APP_DICT) + yaml_fname = self._CreateYamlFile( + {'adwords': {}, + 'proxy_config': { + 'http_proxy': {'host': self.host1}}}, + insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient'): with mock.patch('googleads.common.open', self.fake_open, create=True): - with mock.patch('httplib2.ProxyInfo', self.fake_proxy): - self.assertRaises(googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromStorage, - yaml_fname, 'adwords', [], []) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: + proxy.return_value = mock.Mock() + self.assertRaises(googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromStorage, + yaml_fname, 'adwords', [], []) def testLoadFromStorage_missingRequiredKey(self): with mock.patch('googleads.common.open', self.fake_open, create=True): @@ -156,14 +289,18 @@ def testLoadFromStorage(self): 'one', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): - rval = googleads.common.LoadFromStorage( - yaml_fname, 'one', ['needed', 'keys'], ['other']) - mock_client.assert_called_once_with( - 'a', 'b', 'c', proxy_info=None, ca_certs=None, - disable_ssl_certificate_validation=True) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'needed': 'd', 'keys': 'e', - 'https_proxy': None}, rval) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'one', ['needed', 'keys'], ['other']) + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', + 'proxy_config': proxy_config.return_value}, rval) # The optional key is present. yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e', @@ -171,14 +308,18 @@ def testLoadFromStorage(self): self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): - rval = googleads.common.LoadFromStorage( - yaml_fname, 'one', ['needed', 'keys'], ['other']) - mock_client.assert_called_once_with( - 'a', 'b', 'c', proxy_info=None, ca_certs=None, - disable_ssl_certificate_validation=True) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'needed': 'd', 'keys': 'e', 'other': 'f', - 'https_proxy': None}, rval) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'one', ['needed', 'keys'], ['other']) + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', 'other': 'f', + 'proxy_config': proxy_config.return_value}, rval) def testLoadFromStorage_relativePath(self): fake_os = fake_filesystem.FakeOsModule(self.filesystem) @@ -191,47 +332,65 @@ def testLoadFromStorage_relativePath(self): with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.os', fake_os): with mock.patch('googleads.common.open', self.fake_open, create=True): - rval = googleads.common.LoadFromStorage( - 'yaml/googleads.yaml', 'one', ['needed', 'keys'], ['other']) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + 'yaml/googleads.yaml', 'one', ['needed', 'keys'], ['other']) + + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) mock_client.assert_called_once_with( - 'a', 'b', 'c', proxy_info=None, ca_certs=None, - disable_ssl_certificate_validation=True) + 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, - 'needed': 'd', 'keys': 'e', - 'https_proxy': None}, rval) + 'proxy_config': proxy_config.return_value, + 'needed': 'd', 'keys': 'e'}, rval) def testLoadFromStorage_serviceAccount(self): dfp_scope = googleads.oauth2.GetAPIScope('dfp') # No optional keys present. - yaml_fname = self._CreateYamlFile({'dfp': {'needed': 'd', 'keys': 'e'}}, - 'dfp', self._OAUTH_SERVICE_ACCT_DICT) + yaml_fname = self._CreateYamlFile( + {'dfp': {'needed': 'd', 'keys': 'e'}}, + insert_oauth2_key='dfp', oauth_dict=self._OAUTH_SERVICE_ACCT_DICT) with mock.patch( 'googleads.oauth2.GoogleServiceAccountClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): - rval = googleads.common.LoadFromStorage( - yaml_fname, 'dfp', ['needed', 'keys'], ['other']) - mock_client.assert_called_once_with( - dfp_scope, 'test@test.com', '/test/test.p12', proxy_info=None, - ca_certs=None, disable_ssl_certificate_validation=True) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'needed': 'd', 'keys': 'e', - 'https_proxy': None}, rval) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'dfp', ['needed', 'keys'], ['other']) + + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + dfp_scope, 'test@test.com', '/test/test.p12', + proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value, + 'needed': 'd', 'keys': 'e'}, rval) # The optional key is present. - yaml_fname = self._CreateYamlFile({'dfp': {'needed': 'd', 'keys': 'e', - 'other': 'f'}}, 'dfp', - self._OAUTH_SERVICE_ACCT_DICT) + yaml_fname = self._CreateYamlFile( + {'dfp': {'needed': 'd', 'keys': 'e', 'other': 'f'}}, 'dfp', + self._OAUTH_SERVICE_ACCT_DICT) with mock.patch( 'googleads.oauth2.GoogleServiceAccountClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): - rval = googleads.common.LoadFromStorage( - yaml_fname, 'dfp', ['needed', 'keys'], ['other']) - mock_client.assert_called_once_with( - dfp_scope, 'test@test.com', '/test/test.p12', proxy_info=None, - ca_certs=None, disable_ssl_certificate_validation=True) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'needed': 'd', 'keys': 'e', 'other': 'f', - 'https_proxy': None}, rval) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'dfp', ['needed', 'keys'], ['other']) + + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + dfp_scope, 'test@test.com', '/test/test.p12', + proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value, + 'needed': 'd', 'keys': 'e', 'other': 'f'}, rval) def testLoadFromStorage_warningWithUnrecognizedKey(self): yaml_fname = self._CreateYamlFile( @@ -240,13 +399,18 @@ def testLoadFromStorage_warningWithUnrecognizedKey(self): with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with warnings.catch_warnings(record=True) as captured_warnings: with mock.patch('googleads.common.open', self.fake_open, create=True): - rval = googleads.common.LoadFromStorage( - yaml_fname, 'kval', ['Im'], ['other']) + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'kval', ['Im'], ['other']) mock_client.assert_called_once_with( - 'a', 'b', 'c', proxy_info=None, ca_certs=None, - disable_ssl_certificate_validation=True) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'Im': 'here', 'https_proxy': None}, rval) + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual( + { + 'oauth2_client': mock_client.return_value, + 'Im': 'here', + 'proxy_config': proxy_config.return_value + }, rval) self.assertEqual(len(captured_warnings), 1) def testGenerateLibSig(self): @@ -365,5 +529,186 @@ def testSetHeaders(self): mock.Mock()) +class ProxyConfigTest(unittest.TestCase): + """Tests fpr the googleads.common.ProxyConfig class.""" + + def setUp(self): + self.proxy_host1 = 'host1' + self.proxy_port1 = 'port1' + self.proxy_host2 = 'host2' + self.proxy_port2 = 'port2' + self.username = 'username' + self.password = 'password' + self.cafile = '/tmp/file.ca' + + self.proxy_no_credentials = googleads.common.ProxyConfig.Proxy( + self.proxy_host1, self.proxy_port1) + + self.proxy_with_credentials = googleads.common.ProxyConfig.Proxy( + self.proxy_host2, self.proxy_port2, username=self.username, + password=self.password) + + def testProxyToStringWithCredentials(self): + proxy = googleads.common.ProxyConfig.Proxy( + self.proxy_host1, self.proxy_port1, username=self.username, + password=self.password) + self.assertEqual(str(proxy), + '%s:%s@%s:%s' % (self.username, self.password, + self.proxy_host1, + self.proxy_port1)) + + def testProxyToStringWithoutCredentials(self): + proxy = googleads.common.ProxyConfig.Proxy( + self.proxy_host2, self.proxy_port2) + self.assertEqual(str(proxy), + '%s:%s' % (self.proxy_host2, self.proxy_port2)) + + def testProxyToStringWithOnlyUsername(self): + proxy = googleads.common.ProxyConfig.Proxy( + self.proxy_host1, self.proxy_port1, username=self.username) + self.assertEqual(str(proxy), + '%s:@%s:%s' % (self.username, self.proxy_host1, + self.proxy_port1)) + + def testProxyConfigGetHandlersWithNoProxyOrSSLContext(self): + proxy_config = googleads.common.ProxyConfig() + self.assertEqual(proxy_config.GetHandlers(), []) + + def testProxyConfigGetHandlersWithProxy(self): + http_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, + self.proxy_port1) + with mock.patch('urllib2.ProxyHandler') as proxy_handler: + proxy_handler.return_value = mock.Mock() + proxy_config = googleads.common.ProxyConfig(http_proxy=http_proxy) + self.assertEqual(proxy_config.GetHandlers(), [proxy_handler.return_value]) + proxy_handler.assert_called_once_with( + {'http': '%s' % str(http_proxy)}) + + def testProxyConfigGetHandlersWithProxyAndSLLContext(self): + https_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, + self.proxy_port1) + # We normally couldn't access HTTPSHandler below Python 2.7.9, but we'll at + # least verify that the logic is right. + urllib2.HTTPSHandler = mock.Mock() + urllib2.HTTPSHandler.return_value = mock.Mock() + with mock.patch('googleads.common.ProxyConfig._InitSSLContext') as ssl_ctxt: + ssl_ctxt.return_value = 'CONTEXT' + with mock.patch('urllib2.ProxyHandler') as proxy_handler: + proxy_handler.return_value = mock.Mock() + proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) + self.assertEqual(proxy_config.GetHandlers(), + [urllib2.HTTPSHandler.return_value, + proxy_handler.return_value]) + proxy_handler.assert_called_once_with( + {'https': '%s' % str(https_proxy)}) + urllib2.HTTPSHandler.assert_called_once_with(ssl_ctxt.return_value) + + def testProxyConfigWithNoProxy(self): + proxy_config = googleads.common.ProxyConfig() + self.assertEqual(proxy_config.proxy_info, None) + self.assertEqual(proxy_config.GetHandlers(), []) + # Note: The ssl_context will always be None on incompatible versions of + # Python. The version used internally doesn't support this feature. Another + # impact is that HTTPSHandler will never be invoked in these tests. + self.assertEqual(proxy_config._ssl_context, None) + + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: + t.return_value = mock.Mock() + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with([]) + self.assertEqual(t.return_value, transport) + + def testProxyConfigWithHTTPProxy(self): + with mock.patch('httplib2.ProxyInfo') as proxy_info: + proxy_info.return_value = mock.Mock() + with mock.patch('socks.PROXY_TYPE_HTTP') as proxy_type: + proxy_config = googleads.common.ProxyConfig( + http_proxy=self.proxy_no_credentials) + proxy_info.assert_called_once_with( + proxy_type, self.proxy_host1, self.proxy_port1, + proxy_user=None, proxy_pass='') + self.assertEqual(proxy_config.proxy_info, proxy_info.return_value) + self.assertEqual(proxy_config._proxy_option, {'http': '%s:%s' % ( + self.proxy_host1, self.proxy_port1)}) + # Note: The ssl_context will always be None on incompatible versions of + # Python. The version used internally doesn't support this feature. Another + # impact is that HTTPSHandler will never be invoked in these tests. + self.assertEqual(proxy_config._ssl_context, None) + + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: + t.return_value = mock.Mock() + with mock.patch('urllib2.ProxyHandler') as proxy_handler: + proxy_handler.return_value = mock.Mock() + self.assertEqual(proxy_config.GetHandlers(), + [proxy_handler.return_value]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with([proxy_handler.return_value]) + self.assertEqual(t.return_value, transport) + + def testProxyConfigWithHTTPSProxy(self): + with mock.patch('httplib2.ProxyInfo') as proxy_info: + proxy_info.return_value = mock.Mock() + with mock.patch('socks.PROXY_TYPE_HTTP') as proxy_type: + proxy_config = googleads.common.ProxyConfig( + https_proxy=self.proxy_with_credentials, + cafile=self.cafile) + proxy_info.assert_called_once_with( + proxy_type, self.proxy_host2, self.proxy_port2, + proxy_user=self.username, proxy_pass=self.password) + self.assertEqual(proxy_config.proxy_info, proxy_info.return_value) + self.assertEqual(proxy_config._proxy_option, {'https': '%s:%s@%s:%s' % ( + self.username, self.password, self.proxy_host2, + self.proxy_port2)}) + # Note: The ssl_context will always be None on incompatible versions of + # Python. The version used internally doesn't support this feature. Another + # impact is that HTTPSHandler will never be invoked in these tests. + self.assertEqual(proxy_config._ssl_context, None) + self.assertEqual(proxy_config.cafile, self.cafile) + self.assertEqual(proxy_config.disable_certificate_validation, False) + + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: + t.return_value = mock.Mock() + with mock.patch('urllib2.ProxyHandler') as proxy_handler: + proxy_handler.return_value = mock.Mock() + self.assertEqual(proxy_config.GetHandlers(), + [proxy_handler.return_value]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with([proxy_handler.return_value]) + self.assertEqual(t.return_value, transport) + + def testProxyConfigWithHTTPAndHTTPSProxy(self): + with mock.patch('httplib2.ProxyInfo') as proxy_info: + proxy_info.return_value = mock.Mock() + with mock.patch('socks.PROXY_TYPE_HTTP') as proxy_type: + proxy_config = googleads.common.ProxyConfig( + http_proxy=self.proxy_with_credentials, + https_proxy=self.proxy_no_credentials, + disable_certificate_validation=True) + proxy_info.assert_called_once_with( + proxy_type, self.proxy_host1, self.proxy_port1, + proxy_user=None, proxy_pass='') + self.assertEqual(proxy_config.proxy_info, proxy_info.return_value) + self.assertEqual(proxy_config._proxy_option, { + 'http': '%s:%s@%s:%s' % (self.username, self.password, + self.proxy_host2, self.proxy_port2), + 'https': '%s:%s' % (self.proxy_host1, self.proxy_port1)}) + # Note: The ssl_context will always be None on incompatible versions of + # Python. The version used internally doesn't support this feature. Another + # impact is that HTTPSHandler will never be invoked in these tests. + self.assertEqual(proxy_config._ssl_context, None) + self.assertEqual(proxy_config.cafile, None) + self.assertEqual(proxy_config.disable_certificate_validation, True) + + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: + t.return_value = mock.Mock() + with mock.patch('urllib2.ProxyHandler') as proxy_handler: + proxy_handler.return_value = mock.Mock() + self.assertEqual(proxy_config.GetHandlers(), + [proxy_handler.return_value]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with([proxy_handler.return_value]) + self.assertEqual(t.return_value, transport) + + if __name__ == '__main__': unittest.main() diff --git a/tests/dfp_test.py b/tests/dfp_test.py index f936ffb9..91271fd5 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -144,12 +144,17 @@ def setUp(self): self.application_name = 'application name' self.oauth2_client = mock.Mock() self.oauth2_client.CreateHttpHeader.return_value = {} - self.https_proxy = 'myproxy:443' + self.proxy_host = 'myproxy' + self.proxy_port = 443 + self.https_proxy = googleads.common.ProxyConfig.Proxy(host=self.proxy_host, + port=self.proxy_port) + self.proxy_config = googleads.common.ProxyConfig( + https_proxy=self.https_proxy) self.cache = None self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1] self.dfp_client = googleads.dfp.DfpClient( self.oauth2_client, self.application_name, self.network_code, - self.https_proxy, self.cache) + proxy_config=self.proxy_config, cache=self.cache) def testLoadFromStorage(self): with mock.patch('googleads.common.LoadFromStorage') as mock_load: @@ -174,27 +179,32 @@ def testGetService_success(self): # Use a custom server. Also test what happens if the server ends with a # trailing slash server = 'https://testing.test.com/' - https_proxy = {'https': self.https_proxy} with mock.patch('suds.client.Client') as mock_client: - suds_service = self.dfp_client.GetService(service, self.version, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), proxy=https_proxy, cache=self.cache, - timeout=3600) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) - - # Use the default server and https proxy. - self.dfp_client.https_proxy = None + with mock.patch('googleads.common.' + 'ProxyConfig._SudsProxyTransport') as mock_transport: + mock_transport.return_value = mock.Mock() + suds_service = self.dfp_client.GetService(service, self.version, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service), cache=self.cache, timeout=3600, + transport=mock_transport.return_value) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + + # Use the default server without a proxy. + self.dfp_client.proxy_option = None with mock.patch('suds.client.Client') as mock_client: - suds_service = self.dfp_client.GetService(service, self.version) - - mock_client.assert_called_once_with( - 'https://ads.google.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), proxy=None, cache=self.cache, - timeout=3600) - self.assertFalse(mock_client.return_value.set_options.called) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + with mock.patch('googleads.common.' + 'ProxyConfig._SudsProxyTransport') as mock_transport: + mock_transport.return_value = mock.Mock() + suds_service = self.dfp_client.GetService(service, self.version) + + mock_client.assert_called_once_with( + 'https://ads.google.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service), cache=self.cache, timeout=3600, + transport=mock_transport.return_value) + self.assertFalse(mock_client.return_value.set_options.called) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_badService(self): with mock.patch('suds.client.Client') as mock_client: @@ -444,12 +454,12 @@ def testDownloadReportToFile(self): self.report_service.getReportDownloadURL.return_value = report_download_url - with mock.patch('urllib2.urlopen' if sys.version_info[0] == 2 - else 'urllib.request.urlopen') as mock_urlopen: - mock_urlopen.return_value = fake_request + with mock.patch('urllib2.OpenerDirector.open' if sys.version_info[0] == 2 + else 'urllib.request.OpenerDirector.open') as mock_open: + mock_open.return_value = fake_request self.report_downloader.DownloadReportToFile( report_job_id, report_format, outfile) - mock_urlopen.assert_called_once_with(report_download_url) + mock_open.assert_called_once_with(report_download_url) self.assertEqual(report_contents, outfile.getvalue()) def testGetReportService(self): diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index cbb8bc79..c3ca02a2 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -21,8 +21,8 @@ import httplib2 import mock -import socks +import googleads.common import googleads.errors import googleads.oauth2 @@ -78,19 +78,22 @@ def setUp(self): self.client_id = 'client_id' self.client_secret = 'itsasecret' self.refresh_token = 'refreshing' - self.proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, 'myproxy.com', - 443) - self.https_proxy = '%s:%s' % (self.proxy_info.proxy_host, - self.proxy_info.proxy_port) + https_proxy_host = 'myproxy.com' + https_proxy_port = 443 + self.https_proxy = googleads.common.ProxyConfig.Proxy(https_proxy_host, + https_proxy_port) + self.proxy_config = googleads.common.ProxyConfig( + https_proxy=self.https_proxy) self.access_token_unrefreshed = 'a' self.access_token_refreshed = 'b' # Mock out httplib2.Http for testing. self.http = mock.Mock(spec=httplib2.Http) self.opener = self.http.return_value = mock.Mock() - self.opener.proxy_info = self.proxy_info - self.opener.ca_certs = None - self.opener.disable_ssl_certificate_valiation = True + self.opener.proxy_info = self.proxy_config.proxy_info + self.opener.ca_certs = self.proxy_config.cafile + self.opener.disable_ssl_certificate_valiation = ( + self.proxy_config.disable_certificate_validation) # Mock out oauth2client.client.OAuth2Credentials for testing self.oauth2_credentials = mock.Mock(spec=OAuth2Credentials) @@ -114,7 +117,7 @@ def refresh(mock_http): self.oauth2_credentials): self.googleads_client = googleads.oauth2.GoogleRefreshTokenClient( self.client_id, self.client_secret, self.refresh_token, - self.proxy_info) + self.proxy_config) def testCreateHttpHeader_noRefresh(self): header = {'Authorization': 'Bearer %s' % self.access_token_unrefreshed} @@ -127,8 +130,9 @@ def testCreateHttpHeader_refresh(self): with mock.patch('httplib2.Http', self.http): self.assertEqual(header, self.googleads_client.CreateHttpHeader()) self.http.assert_called_once_with( - ca_certs=None, proxy_info=self.proxy_info, - disable_ssl_certificate_validation=False) + ca_certs=None, proxy_info=self.proxy_config.proxy_info, + disable_ssl_certificate_validation=( + self.proxy_config.disable_certificate_validation)) self.mock_oauth2_credentials.refresh.assert_called_once_with( self.opener) @@ -149,10 +153,12 @@ def setUp(self): self.scope = 'scope' self.service_account_email = 'email@email.com' self.private_key_password = 'notasecret' - self.proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, 'myproxy.com', - 443) - self.https_proxy = '%s:%s' % (self.proxy_info.proxy_host, - self.proxy_info.proxy_port) + https_proxy_host = 'myproxy.com' + https_proxy_port = 443 + https_proxy = googleads.common.ProxyConfig.Proxy(https_proxy_host, + https_proxy_port) + self.proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) + self.https_proxy = '%s:%s' % (https_proxy_host, https_proxy_port) self.access_token_unrefreshed = 'a' self.access_token_refreshed = 'b' @@ -168,9 +174,10 @@ def setUp(self): # Mock out httplib2.Http for testing. self.http = mock.Mock(spec=httplib2.Http) self.opener = self.http.return_value = mock.Mock() - self.opener.proxy_info = self.proxy_info - self.opener.ca_certs = None - self.opener.disable_ssl_certificate_valiation = True + self.opener.proxy_info = self.proxy_config.proxy_info + self.opener.ca_certs = self.proxy_config.cafile + self.opener.disable_ssl_certificate_valiation = ( + self.proxy_config.disable_certificate_validation) # Mock out oauth2client.client.OAuth2Credentials for testing self.oauth2_credentials = mock.Mock(spec=SignedJwtAssertionCredentials) @@ -198,7 +205,7 @@ def refresh(mock_http): self.oauth2_credentials): self.googleads_client = googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, key_file_path, - self.private_key_password, proxy_info=self.proxy_info) + self.private_key_password, proxy_config=self.proxy_config) # Undo the call count for the auto-refresh self.mock_oauth2_credentials.refresh.reset_mock() @@ -213,8 +220,9 @@ def testCreateHttpHeader_refresh(self): with mock.patch('httplib2.Http', self.http): self.assertEqual(header, self.googleads_client.CreateHttpHeader()) self.http.assert_called_once_with( - ca_certs=None, proxy_info=self.proxy_info, - disable_ssl_certificate_validation=False) + ca_certs=None, proxy_info=self.proxy_config.proxy_info, + disable_ssl_certificate_validation=( + self.proxy_config.disable_certificate_validation)) self.mock_oauth2_credentials.refresh.assert_called_once_with( self.opener) From 75c27f715fad190eb381f4a44a3a2a1fb472df9b Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 17 May 2016 12:44:23 -0400 Subject: [PATCH 036/180] Commiting latest changes. From df744af0ca2e6a9006d50a03f249b5e13b84a635 Mon Sep 17 00:00:00 2001 From: nicholaschen Date: Thu, 26 May 2016 14:39:12 -0400 Subject: [PATCH 037/180] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5679da8e..6111549c 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ samples in the examples directory of this repository. ####Where can I find the pydocs? -Our Pydoc can be found [here](http://googleads.github.io/googleads-python-lib). +Our pydocs can be found [here](http://googleads.github.io/googleads-python-lib). ####Caching authentication information From 73bb96881e0401f692ea47e23f62ab5ca59820eb Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Fri, 27 May 2016 13:21:25 -0400 Subject: [PATCH 038/180] releasing v201605 of AdWords --- ChangeLog | 5 + .../handlers/api_handler.py | 1 - .../optimization/estimate_keyword_traffic.py | 37 +- .../optimization/estimate_keyword_traffic.py | 37 +- .../optimization/estimate_keyword_traffic.py | 37 +- examples/adwords/v201605/__init__.py | 15 + .../v201605/account_management/__init__.py | 15 + .../account_management/create_account.py | 63 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201605/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 222 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 108 ++++ .../advanced_operations/add_html5_ad.py | 111 ++++ .../add_responsive_display_ad.py | 91 +++ .../add_text_ad_with_upgraded_urls.py | 111 ++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201605/basic_operations/__init__.py | 15 + .../v201605/basic_operations/add_ad_groups.py | 115 ++++ .../v201605/basic_operations/add_campaigns.py | 125 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201605/basic_operations/add_keywords.py | 92 +++ .../v201605/basic_operations/add_text_ads.py | 93 ++++ .../v201605/basic_operations/get_ad_groups.py | 76 +++ .../v201605/basic_operations/get_campaigns.py | 74 +++ .../get_campaigns_with_awql.py | 64 +++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201605/basic_operations/get_keywords.py | 87 +++ .../v201605/basic_operations/get_text_ads.py | 80 +++ .../v201605/basic_operations/pause_ad.py | 61 ++ .../v201605/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 58 ++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201605/campaign_management/__init__.py | 15 + .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 426 ++++++++++++++ .../v201605/campaign_management/add_draft.py | 81 +++ .../campaign_management/add_experiment.py | 127 +++++ ...dd_keywords_using_incremental_batch_job.py | 259 +++++++++ .../v201605/campaign_management/add_trial.py | 117 ++++ .../get_all_disapproved_ads.py | 74 +++ .../get_all_disapproved_ads_with_awql.py | 63 +++ .../get_campaigns_by_label.py | 85 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/promote_experiment.py | 60 ++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201605/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 120 ++++ .../handle_policy_violation_error.py | 114 ++++ .../adwords/v201605/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../v201605/extensions/add_site_links.py | 134 +++++ .../extensions/add_site_links_using_feeds.py | 233 ++++++++ .../adwords/v201605/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 527 ++++++++++++++++++ .../v201605/migration/upgrade_ad_url.py | 79 +++ examples/adwords/v201605/misc/__init__.py | 15 + .../v201605/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201605/misc/upload_image.py | 66 +++ .../v201605/misc/upload_media_bundle.py | 59 ++ .../adwords/v201605/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 180 ++++++ ...aign_criterion_bid_modifier_simulations.py | 96 ++++ .../get_keyword_bid_simulations.py | 81 +++ .../v201605/optimization/get_keyword_ideas.py | 100 ++++ .../adwords/v201605/remarketing/__init__.py | 15 + .../v201605/remarketing/add_audience.py | 103 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_crm_based_user_list.py | 94 ++++ .../remarketing/add_rule_based_user_lists.py | 183 ++++++ .../remarketing/upload_offline_conversions.py | 75 +++ .../adwords/v201605/reporting/__init__.py | 15 + .../reporting/download_criteria_report.py | 61 ++ .../download_criteria_report_as_stream.py | 77 +++ ...oad_criteria_report_as_stream_with_awql.py | 81 +++ .../download_criteria_report_as_string.py | 59 ++ ...oad_criteria_report_as_string_with_awql.py | 55 ++ .../download_criteria_report_with_awql.py | 58 ++ .../v201605/reporting/get_report_fields.py | 52 ++ examples/adwords/v201605/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 281 ++++++++++ .../v201605/shopping/add_product_scope.py | 104 ++++ .../v201605/shopping/add_shopping_campaign.py | 121 ++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201605/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 161 ++++++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201605/targeting/lookup_location.py | 82 +++ googleads.yaml | 10 + googleads/adwords.py | 153 +++-- googleads/common.py | 186 ++++--- googleads/dfp.py | 15 +- googleads/oauth2.py | 68 ++- tests/adwords_test.py | 115 +++- tests/common_test.py | 11 +- 107 files changed, 9428 insertions(+), 225 deletions(-) create mode 100644 examples/adwords/v201605/__init__.py create mode 100644 examples/adwords/v201605/account_management/__init__.py create mode 100755 examples/adwords/v201605/account_management/create_account.py create mode 100755 examples/adwords/v201605/account_management/get_account_changes.py create mode 100755 examples/adwords/v201605/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201605/advanced_operations/__init__.py create mode 100755 examples/adwords/v201605/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201605/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201605/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201605/advanced_operations/add_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201605/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201605/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201605/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201605/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201605/basic_operations/__init__.py create mode 100755 examples/adwords/v201605/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201605/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201605/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201605/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201605/basic_operations/add_text_ads.py create mode 100755 examples/adwords/v201605/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201605/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201605/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201605/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201605/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201605/basic_operations/get_text_ads.py create mode 100755 examples/adwords/v201605/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201605/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201605/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201605/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201605/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201605/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201605/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201605/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201605/campaign_management/__init__.py create mode 100755 examples/adwords/v201605/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201605/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201605/campaign_management/add_draft.py create mode 100755 examples/adwords/v201605/campaign_management/add_experiment.py create mode 100755 examples/adwords/v201605/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201605/campaign_management/add_trial.py create mode 100755 examples/adwords/v201605/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201605/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201605/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201605/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201605/campaign_management/promote_experiment.py create mode 100755 examples/adwords/v201605/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201605/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201605/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201605/error_handling/__init__.py create mode 100755 examples/adwords/v201605/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201605/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201605/extensions/__init__.py create mode 100755 examples/adwords/v201605/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201605/extensions/add_site_links.py create mode 100755 examples/adwords/v201605/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201605/migration/__init__.py create mode 100755 examples/adwords/v201605/migration/migrate_to_extension_settings.py create mode 100755 examples/adwords/v201605/migration/upgrade_ad_url.py create mode 100644 examples/adwords/v201605/misc/__init__.py create mode 100755 examples/adwords/v201605/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201605/misc/upload_image.py create mode 100755 examples/adwords/v201605/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201605/optimization/__init__.py create mode 100755 examples/adwords/v201605/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201605/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201605/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201605/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201605/remarketing/__init__.py create mode 100755 examples/adwords/v201605/remarketing/add_audience.py create mode 100755 examples/adwords/v201605/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201605/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201605/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201605/remarketing/upload_offline_conversions.py create mode 100644 examples/adwords/v201605/reporting/__init__.py create mode 100755 examples/adwords/v201605/reporting/download_criteria_report.py create mode 100755 examples/adwords/v201605/reporting/download_criteria_report_as_stream.py create mode 100755 examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201605/reporting/download_criteria_report_as_string.py create mode 100755 examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201605/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201605/reporting/get_report_fields.py create mode 100644 examples/adwords/v201605/shopping/__init__.py create mode 100755 examples/adwords/v201605/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201605/shopping/add_product_scope.py create mode 100755 examples/adwords/v201605/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201605/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201605/targeting/__init__.py create mode 100755 examples/adwords/v201605/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201605/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201605/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201605/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201605/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index d187b16c..461f8209 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +4.1.0 -- 5/26/2016 +* Added support for AdWords v201605. +* Added new use_raw_enum_values keyword argument to the AdWords ReportDownloader + utility. + 4.0.0 -- 5/17/2016 * Add support for DFP v201605. * Removed examples for DFP v201505. diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index f68e6d17..68cafb70 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -87,7 +87,6 @@ def AddBudget(self, client_customer_id, micro_amount): 'operator': 'ADD', 'operand': { 'name': 'Budget #%s' % time.time(), - 'period': 'DAILY', 'amount': { 'microAmount': micro_amount }, diff --git a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py index ab9bc3fb..12fdd5f8 100755 --- a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py @@ -93,34 +93,35 @@ def main(client): continue # Find the mean of the min and max values. - mean_avg_cpc = (calc_mean(estimate['min']['averageCpc']['microAmount'], - estimate['max']['averageCpc']['microAmount']) + mean_avg_cpc = (_CalculateMean(estimate['min']['averageCpc']['microAmount'], + estimate['max']['averageCpc']['microAmount']) if 'averageCpc' in estimate['min'] else 'N/A') - mean_avg_pos = calc_mean(estimate['min']['averagePosition'], - estimate['max']['averagePosition']) - mean_clicks = calc_mean(estimate['min']['clicksPerDay'], - estimate['max']['clicksPerDay']) - mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], - estimate['max']['totalCost']['microAmount']) + mean_avg_pos = _CalculateMean(estimate['min']['averagePosition'], + estimate['max']['averagePosition']) + mean_clicks = _CalculateMean(estimate['min']['clicksPerDay'], + estimate['max']['clicksPerDay']) + mean_total_cost = _CalculateMean( + estimate['min']['totalCost']['microAmount'], + estimate['max']['totalCost']['microAmount']) print ('Results for the keyword with text \'%s\' and match type \'%s\':' % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % mean_avg_cpc - print ' Estimated ad position: %s' % mean_avg_pos - print ' Estimated daily clicks: %s' % mean_clicks - print ' Estimated daily cost: %s' % mean_total_cost + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) -def fmt_mean(mean): - if mean: - return '%.2f' % mean +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 else: return None -def calc_mean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 +def _FormatMean(mean): + if mean: + return '%.2f' % mean else: return None diff --git a/examples/adwords/v201601/optimization/estimate_keyword_traffic.py b/examples/adwords/v201601/optimization/estimate_keyword_traffic.py index cbb5e01f..c18dd310 100755 --- a/examples/adwords/v201601/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201601/optimization/estimate_keyword_traffic.py @@ -93,34 +93,35 @@ def main(client): continue # Find the mean of the min and max values. - mean_avg_cpc = (calc_mean(estimate['min']['averageCpc']['microAmount'], - estimate['max']['averageCpc']['microAmount']) + mean_avg_cpc = (_CalculateMean(estimate['min']['averageCpc']['microAmount'], + estimate['max']['averageCpc']['microAmount']) if 'averageCpc' in estimate['min'] else 'N/A') - mean_avg_pos = calc_mean(estimate['min']['averagePosition'], - estimate['max']['averagePosition']) - mean_clicks = calc_mean(estimate['min']['clicksPerDay'], - estimate['max']['clicksPerDay']) - mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], - estimate['max']['totalCost']['microAmount']) + mean_avg_pos = _CalculateMean(estimate['min']['averagePosition'], + estimate['max']['averagePosition']) + mean_clicks = _CalculateMean(estimate['min']['clicksPerDay'], + estimate['max']['clicksPerDay']) + mean_total_cost = _CalculateMean( + estimate['min']['totalCost']['microAmount'], + estimate['max']['totalCost']['microAmount']) print ('Results for the keyword with text \'%s\' and match type \'%s\':' % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % mean_avg_cpc - print ' Estimated ad position: %s' % mean_avg_pos - print ' Estimated daily clicks: %s' % mean_clicks - print ' Estimated daily cost: %s' % mean_total_cost + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) -def fmt_mean(mean): - if mean: - return '%.2f' % mean +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 else: return None -def calc_mean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 +def _FormatMean(mean): + if mean: + return '%.2f' % mean else: return None diff --git a/examples/adwords/v201603/optimization/estimate_keyword_traffic.py b/examples/adwords/v201603/optimization/estimate_keyword_traffic.py index 4516e6f4..885ae713 100755 --- a/examples/adwords/v201603/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201603/optimization/estimate_keyword_traffic.py @@ -93,34 +93,35 @@ def main(client): continue # Find the mean of the min and max values. - mean_avg_cpc = (calc_mean(estimate['min']['averageCpc']['microAmount'], - estimate['max']['averageCpc']['microAmount']) + mean_avg_cpc = (_CalculateMean(estimate['min']['averageCpc']['microAmount'], + estimate['max']['averageCpc']['microAmount']) if 'averageCpc' in estimate['min'] else 'N/A') - mean_avg_pos = calc_mean(estimate['min']['averagePosition'], - estimate['max']['averagePosition']) - mean_clicks = calc_mean(estimate['min']['clicksPerDay'], - estimate['max']['clicksPerDay']) - mean_total_cost = calc_mean(estimate['min']['totalCost']['microAmount'], - estimate['max']['totalCost']['microAmount']) + mean_avg_pos = _CalculateMean(estimate['min']['averagePosition'], + estimate['max']['averagePosition']) + mean_clicks = _CalculateMean(estimate['min']['clicksPerDay'], + estimate['max']['clicksPerDay']) + mean_total_cost = _CalculateMean( + estimate['min']['totalCost']['microAmount'], + estimate['max']['totalCost']['microAmount']) print ('Results for the keyword with text \'%s\' and match type \'%s\':' % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % mean_avg_cpc - print ' Estimated ad position: %s' % mean_avg_pos - print ' Estimated daily clicks: %s' % mean_clicks - print ' Estimated daily cost: %s' % mean_total_cost + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) -def fmt_mean(mean): - if mean: - return '%.2f' % mean +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 else: return None -def calc_mean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 +def _FormatMean(mean): + if mean: + return '%.2f' % mean else: return None diff --git a/examples/adwords/v201605/__init__.py b/examples/adwords/v201605/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201605/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201605/account_management/__init__.py b/examples/adwords/v201605/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201605/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201605/account_management/create_account.py b/examples/adwords/v201605/account_management/create_account.py new file mode 100755 index 00000000..72f0028b --- /dev/null +++ b/examples/adwords/v201605/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201605') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/account_management/get_account_changes.py b/examples/adwords/v201605/account_management/get_account_changes.py new file mode 100755 index 00000000..d2b94067 --- /dev/null +++ b/examples/adwords/v201605/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201605') + campaign_service = client.GetService('CampaignService', version='v201605') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/account_management/get_account_hierarchy.py b/examples/adwords/v201605/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..08128681 --- /dev/null +++ b/examples/adwords/v201605/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201605') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/advanced_operations/__init__.py b/examples/adwords/v201605/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201605/advanced_operations/add_ad_customizer.py b/examples/adwords/v201605/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..4f5a84f9 --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/add_ad_customizer.py @@ -0,0 +1,222 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates TextAds that use ad customizations for the specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add TextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no TextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService') + + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'description1': 'Only {=%s.Price}' % feed_name, + 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com' + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201605/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201605/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..40cdd07a --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201605') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..d23b1f83 --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,108 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad to ad group ID \'%s\' ' + 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/advanced_operations/add_html5_ad.py b/examples/adwords/v201605/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..9cc2e229 --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/add_html5_ad.py @@ -0,0 +1,111 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..c72d4e3c --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + media_service = client.GetService('MediaService', version='v201605') + + try: + # Create image. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + # Make the upload request + image = media_service.upload(image)[0] + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': image, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'] + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201605/advanced_operations/add_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..7ce22271 --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -0,0 +1,111 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a text add that uses advanced features of upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Create the text ad + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print ('AdGroupAd with ID %s and display URL \'%s\'was added.' + % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201605/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201605/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..d7dccbc9 --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201605') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201605') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201605') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201605/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..fba405b3 --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201605') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201605') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201605/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..deaa6b0f --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201605') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201605/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..d6c80a81 --- /dev/null +++ b/examples/adwords/v201605/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201605') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201605') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201605') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201605/basic_operations/__init__.py b/examples/adwords/v201605/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201605/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201605/basic_operations/add_ad_groups.py b/examples/adwords/v201605/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..7b1a46d4 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201605') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/basic_operations/add_campaigns.py b/examples/adwords/v201605/basic_operations/add_campaigns.py new file mode 100755 index 00000000..d6f447c3 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/add_campaigns.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201605') + budget_service = client.GetService('BudgetService', version='v201605') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201605/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..c5f0f9bc --- /dev/null +++ b/examples/adwords/v201605/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/add_keywords.py b/examples/adwords/v201605/basic_operations/add_keywords.py new file mode 100755 index 00000000..171b5f4a --- /dev/null +++ b/examples/adwords/v201605/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201605') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/add_text_ads.py b/examples/adwords/v201605/basic_operations/add_text_ads.py new file mode 100755 index 00000000..011ea55c --- /dev/null +++ b/examples/adwords/v201605/basic_operations/add_text_ads.py @@ -0,0 +1,93 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds several text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Construct operations and add ads. + # If needed, you could specify an exemption request here, e.g.: + # 'exemptionRequests': [{ + # # This comes back in a PolicyViolationError. + # 'key' { + # 'policyName': '...', + # 'violatingText': '...' + # } + # }] + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + }, + # Optional fields. + 'status': 'PAUSED' + } + }, + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Enjoy your stay at Red Planet.', + 'description2': 'Buy your tickets now!', + 'headline': 'Luxury Cruise to Mars' + } + } + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad with id \'%s\' and of type \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/get_ad_groups.py b/examples/adwords/v201605/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..3f4315cf --- /dev/null +++ b/examples/adwords/v201605/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201605') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/basic_operations/get_campaigns.py b/examples/adwords/v201605/basic_operations/get_campaigns.py new file mode 100755 index 00000000..0ef90350 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/get_campaigns.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201605') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201605/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..6ba4bcd0 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201605') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..b5c726f0 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an ad, run add_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/get_keywords.py b/examples/adwords/v201605/basic_operations/get_keywords.py new file mode 100755 index 00000000..8ffb8181 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201605') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\' was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/get_text_ads.py b/examples/adwords/v201605/basic_operations/get_text_ads.py new file mode 100755 index 00000000..97306ccb --- /dev/null +++ b/examples/adwords/v201605/basic_operations/get_text_ads.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2016 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 text ads for a given ad group. + +To add an ad, run add_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/pause_ad.py b/examples/adwords/v201605/basic_operations/pause_ad.py new file mode 100755 index 00000000..a0afeec8 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201605/basic_operations/remove_ad.py b/examples/adwords/v201605/basic_operations/remove_ad.py new file mode 100755 index 00000000..bfb6fee8 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201605/basic_operations/remove_ad_group.py b/examples/adwords/v201605/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..be66dc20 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201605') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/remove_campaign.py b/examples/adwords/v201605/basic_operations/remove_campaign.py new file mode 100755 index 00000000..adb7f0ef --- /dev/null +++ b/examples/adwords/v201605/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201605') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/basic_operations/remove_keyword.py b/examples/adwords/v201605/basic_operations/remove_keyword.py new file mode 100755 index 00000000..93c2c53b --- /dev/null +++ b/examples/adwords/v201605/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201605') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201605/basic_operations/update_ad_group.py b/examples/adwords/v201605/basic_operations/update_ad_group.py new file mode 100755 index 00000000..0b8debe4 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/update_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201605') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/update_campaign.py b/examples/adwords/v201605/basic_operations/update_campaign.py new file mode 100755 index 00000000..c5070940 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201605') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/basic_operations/update_keyword.py b/examples/adwords/v201605/basic_operations/update_keyword.py new file mode 100755 index 00000000..fb009448 --- /dev/null +++ b/examples/adwords/v201605/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201605') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201605/campaign_management/__init__.py b/examples/adwords/v201605/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201605/campaign_management/add_campaign_labels.py b/examples/adwords/v201605/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..4b2b0cc0 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201605') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201605/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201605/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..89ef25a1 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,426 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201605') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201605') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding a TextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new TextAd for each of + the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201605') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201605/campaign_management/add_draft.py b/examples/adwords/v201605/campaign_management/add_draft.py new file mode 100755 index 00000000..f69d81db --- /dev/null +++ b/examples/adwords/v201605/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + # Initialize appropriate services. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201605') + draft_service = client.GetService('DraftService', version='v201605') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201605/campaign_management/add_experiment.py b/examples/adwords/v201605/campaign_management/add_experiment.py new file mode 100755 index 00000000..baf9c14d --- /dev/null +++ b/examples/adwords/v201605/campaign_management/add_experiment.py @@ -0,0 +1,127 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates an experiment. + +The created experiment is using a query percentage of 10, which defines what +fraction of auctions should go to the control split (90%) vs. the experiment +split (10%), then adds experimental bid changes for an ad group, and adds an +experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad +groups, run get_ad_groups.py. To get keywords, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, campaign_id, ad_group_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201605') + ad_group_service = client.GetService('AdGroupService', version='v201605') + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201605') + + # Construct operations and add experiment. + tomorrow = datetime.datetime.now() + datetime.timedelta(1) + thirty_days = datetime.datetime.now() + datetime.timedelta(30) + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), + 'queryPercentage': '10', + 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), + # Optional fields. + 'status': 'ENABLED', + 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was added.' + % (experiment['name'], experiment['id'])) + + # Construct operations and update ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'experimentData': { + 'xsi_type': 'AdGroupExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'MODIFIED', + 'experimentBidMultipliers': { + 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', + 'maxCpcMultiplier': { + 'multiplier': '0.5' + } + } + } + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' + 'experiment.' % (ad_group['name'], ad_group['id'])) + + # Construct operations and add ad group crierion. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + }, + 'experimentData': { + 'xsi_type': 'BiddableAdGroupCriterionExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'EXPERIMENT_ONLY' + } + } + }] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\' and criterion ' + 'id \'%s\' was added to the experiment.' + % (criterion['adGroupId'], criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201605/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201605/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..2fdd9939 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,259 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201605') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201605') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201605') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201605') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201605/campaign_management/add_trial.py b/examples/adwords/v201605/campaign_management/add_trial.py new file mode 100755 index 00000000..a1412cb7 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/add_trial.py @@ -0,0 +1,117 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201605') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201605') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201605/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201605/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..63aabca5 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Construct selector and get all ads for a given ad group. + selector = { + 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'AdGroupCreativeApprovalStatus', + 'operator': 'IN', + 'values': ['DISAPPROVED'] + } + ] + } + ads = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201605/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..97b3c1ec --- /dev/null +++ b/examples/adwords/v201605/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, AdGroupAdDisapprovalReasons ' + 'WHERE CampaignId = %s AND ' + 'AdGroupCreativeApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % campaign_id) + ads = ad_group_ad_service.query(query) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201605/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..99a69be3 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201605') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201605/campaign_management/graduate_trial.py b/examples/adwords/v201605/campaign_management/graduate_trial.py new file mode 100755 index 00000000..290284e0 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201605') + budget_service = client.GetService('BudgetService', version='v201605') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201605/campaign_management/promote_experiment.py b/examples/adwords/v201605/campaign_management/promote_experiment.py new file mode 100755 index 00000000..0f181e10 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/promote_experiment.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2016 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 promotes an experiment. + +Promoting an experiment permanently applies all the experimental changes made to +its related ad groups, criteria and ads. To add an experiment, run +add_experiment.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' + + +def main(client, experiment_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201605') + + # Construct operations and promote experiment. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': experiment_id, + 'status': 'PROMOTED' + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was promoted.' + % (experiment['name'], experiment['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201605/campaign_management/set_ad_parameters.py b/examples/adwords/v201605/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..987a8fc3 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + ad_param_service = client.GetService('AdParamService', version='v201605') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201605/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201605/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..5d48f143 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201605') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201605/campaign_management/validate_text_ad.py b/examples/adwords/v201605/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..b3dbb560 --- /dev/null +++ b/examples/adwords/v201605/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Construct operations to add a text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'url': 'http://www.example.com', + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for all astronauts in orbit', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/error_handling/__init__.py b/examples/adwords/v201605/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201605/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201605/error_handling/handle_partial_failures.py b/examples/adwords/v201605/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..a67c5191 --- /dev/null +++ b/examples/adwords/v201605/error_handling/handle_partial_failures.py @@ -0,0 +1,120 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201605') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) + if index: + print ('Keyword ad group criterion with ad group id \'%s\' and text ' + '\'%s\' triggered a failure for the following reason: \'%s\'.' + % (keywords[int(index[0])]['adGroupId'], + keywords[int(index[0])]['criterion']['text'], + error['errorString'])) + else: + print 'The following failure has occurred: \'%s\'.' % error['errorString'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/error_handling/handle_policy_violation_error.py b/examples/adwords/v201605/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..89a81b53 --- /dev/null +++ b/examples/adwords/v201605/error_handling/handle_policy_violation_error.py @@ -0,0 +1,114 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201605') + + # Create text ad. + text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'TextAd', + 'headline': 'Mars Cruise!!!', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com', + } + } + } + + operations = [text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + if error['ApiError.Type'] == 'PolicyViolationError': + operation_index = re.findall(r'operations\[(.*)\]\.', + error['fieldPath']) + if operation_index: + operation = operations[int(operation_index[0])] + print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % + (operation['operand']['ad']['headline'], + 'exemptable' if error['isExemptable'] else 'non-exemptable', + error['externalPolicyName'])) + if error['isExemptable'].lower() == 'true': + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text ' + '\'%s\'.' % + (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({ + 'key': error['key'] + }) + else: + # Remove non-exemptable operation + print 'Removing the operation from the request.' + operations.delete(operation) + else: + # Non-policy error returned, re-throw exception. + raise e + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/extensions/__init__.py b/examples/adwords/v201605/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201605/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201605/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201605/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..49a2d81b --- /dev/null +++ b/examples/adwords/v201605/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201605').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201605') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201605/extensions/add_site_links.py b/examples/adwords/v201605/extensions/add_site_links.py new file mode 100755 index 00000000..8a654c43 --- /dev/null +++ b/examples/adwords/v201605/extensions/add_site_links.py @@ -0,0 +1,134 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201605') + customer_service = client.GetService('CustomerService', version='v201605') + + customer_tz = timezone(customer_service.get()['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840} + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/extensions/add_site_links_using_feeds.py b/examples/adwords/v201605/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..a6e5ddb9 --- /dev/null +++ b/examples/adwords/v201605/extensions/add_site_links_using_feeds.py @@ -0,0 +1,233 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_1_TEXT = '3' +PLACEHOLDER_FIELD_LINE_2_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201605') + feed_item_service = client.GetService('FeedItemService', version='v201605') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201605') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201605') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 1 Description'}, + {'type': 'STRING', 'name': 'Line 2 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_1_feed_attribute_id = feed['attributes'][2]['id'] + line_2_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % + (line_1_feed_attribute_id, line_2_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line1FeedId'] = line_1_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line1': 'Home line 1', 'line2': 'Home line 2'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line1': 'Support line 1', 'line2': 'Support line 2'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line1': 'Products line 1', 'line2': 'Products line 2'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'stringValue': item['line1'] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/migration/__init__.py b/examples/adwords/v201605/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201605/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201605/migration/migrate_to_extension_settings.py b/examples/adwords/v201605/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..7552842f --- /dev/null +++ b/examples/adwords/v201605/migration/migrate_to_extension_settings.py @@ -0,0 +1,527 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201605') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201605') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201605') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201605') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201605') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201605') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201605') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/migration/upgrade_ad_url.py b/examples/adwords/v201605/migration/upgrade_ad_url.py new file mode 100755 index 00000000..e111692a --- /dev/null +++ b/examples/adwords/v201605/migration/upgrade_ad_url.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2016 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 upgrades an ad to use upgraded URLs. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, adgroup_id, ad_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201605') + + selector = { + 'fields': ['Id', 'Url'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [ad_id] + } + ] + } + + page = adgroup_ad_service.get(selector) + + adgroup_ad = page['entries'][0] if page['entries'] else None + + if not adgroup_ad: + raise errors.GoogleAdsError('Ad not found.') + + ad_url_upgrade = { + 'adId': adgroup_ad['ad']['id'], + 'finalUrl': adgroup_ad['ad']['url'] + } + + adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] + + if adgroup_ad: + print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' + % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201605/misc/__init__.py b/examples/adwords/v201605/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201605/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201605/misc/get_all_images_and_videos.py b/examples/adwords/v201605/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..40a0e6fb --- /dev/null +++ b/examples/adwords/v201605/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201605') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/misc/upload_image.py b/examples/adwords/v201605/misc/upload_image.py new file mode 100755 index 00000000..564603df --- /dev/null +++ b/examples/adwords/v201605/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201605') + + with open(image_filename, 'r') as image_handle: + image_data = base64.encodestring(image_handle.read()) + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201605/misc/upload_media_bundle.py b/examples/adwords/v201605/misc/upload_media_bundle.py new file mode 100755 index 00000000..033d2010 --- /dev/null +++ b/examples/adwords/v201605/misc/upload_media_bundle.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201605') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/optimization/__init__.py b/examples/adwords/v201605/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201605/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201605/optimization/estimate_keyword_traffic.py b/examples/adwords/v201605/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..21920429 --- /dev/null +++ b/examples/adwords/v201605/optimization/estimate_keyword_traffic.py @@ -0,0 +1,180 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201605') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201605/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..9892b9f5 --- /dev/null +++ b/examples/adwords/v201605/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201605') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201605/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..c4575852 --- /dev/null +++ b/examples/adwords/v201605/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201605') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201605/optimization/get_keyword_ideas.py b/examples/adwords/v201605/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..cedc3511 --- /dev/null +++ b/examples/adwords/v201605/optimization/get_keyword_ideas.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201605') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }, + { + # Network search parameter (optional) + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/remarketing/__init__.py b/examples/adwords/v201605/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201605/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201605/remarketing/add_audience.py b/examples/adwords/v201605/remarketing/add_audience.py new file mode 100755 index 00000000..92a02035 --- /dev/null +++ b/examples/adwords/v201605/remarketing/add_audience.py @@ -0,0 +1,103 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201605') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201605') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/remarketing/add_conversion_tracker.py b/examples/adwords/v201605/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..2fffb372 --- /dev/null +++ b/examples/adwords/v201605/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201605') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/remarketing/add_crm_based_user_list.py b/examples/adwords/v201605/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..30935a69 --- /dev/null +++ b/examples/adwords/v201605/remarketing/add_crm_based_user_list.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a remarketing user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client, emails): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201605') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180 + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + hashed_emails = HashEmails(emails) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'dataType': 'EMAIL_SHA256', + 'members': hashed_emails + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def HashEmails(emails): + """Hashes the given emails using SHA-256. + + Note: Emails are stripped of any whitespace and set to lowercase before + hashing. + + Args: + emails: list of str emails to be hashed. + + Returns: + A list of SHA-256 hashed emails. + """ + return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + + +if __name__ == '__main__': + EMAILS = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, EMAILS) diff --git a/examples/adwords/v201605/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201605/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..bd682ca7 --- /dev/null +++ b/examples/adwords/v201605/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,183 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201605') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords will logically OR the + # groups together. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/remarketing/upload_offline_conversions.py b/examples/adwords/v201605/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..4ff0d95d --- /dev/null +++ b/examples/adwords/v201605/remarketing/upload_offline_conversions.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201605') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201605/reporting/__init__.py b/examples/adwords/v201605/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201605/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201605/reporting/download_criteria_report.py b/examples/adwords/v201605/reporting/download_criteria_report.py new file mode 100755 index 00000000..9a3b12f8 --- /dev/null +++ b/examples/adwords/v201605/reporting/download_criteria_report.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201605') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py new file mode 100755 index 00000000..b4e018d7 --- /dev/null +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201605') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..f51f53df --- /dev/null +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201605') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_string.py b/examples/adwords/v201605/reporting/download_criteria_report_as_string.py new file mode 100755 index 00000000..165a15ab --- /dev/null +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_string.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201605') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..c9d24ab8 --- /dev/null +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201605') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..866810f5 --- /dev/null +++ b/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client, path): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201605') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + with open(path, 'w') as output_file: + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', output_file, skip_report_header=False, + skip_column_header=False, skip_report_summary=False) + + print 'Report was downloaded to \'%s\'.' % path + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, PATH) diff --git a/examples/adwords/v201605/reporting/get_report_fields.py b/examples/adwords/v201605/reporting/get_report_fields.py new file mode 100755 index 00000000..cc630f7e --- /dev/null +++ b/examples/adwords/v201605/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201605') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201605/shopping/__init__.py b/examples/adwords/v201605/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201605/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201605/shopping/add_product_partition_tree.py b/examples/adwords/v201605/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..b3751eda --- /dev/null +++ b/examples/adwords/v201605/shopping/add_product_partition_tree.py @@ -0,0 +1,281 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201605') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201605/shopping/add_product_scope.py b/examples/adwords/v201605/shopping/add_product_scope.py new file mode 100755 index 00000000..01adb7ec --- /dev/null +++ b/examples/adwords/v201605/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201605') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/shopping/add_shopping_campaign.py b/examples/adwords/v201605/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..c1b798dd --- /dev/null +++ b/examples/adwords/v201605/shopping/add_shopping_campaign.py @@ -0,0 +1,121 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id): + campaign_service = client.GetService('CampaignService', version='v201605') + ad_group_service = client.GetService('AdGroupService', version='v201605') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + adgroup = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group_result = ad_group_service.mutate(adgroup_operations) + + for adgroup in ad_group_result['value']: + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (adgroup['name'], adgroup['id'])) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': adgroup['id'], + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201605/shopping/get_product_category_taxonomy.py b/examples/adwords/v201605/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..e7a91f78 --- /dev/null +++ b/examples/adwords/v201605/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201605') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/targeting/__init__.py b/examples/adwords/v201605/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201605/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201605/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201605/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..237c26d5 --- /dev/null +++ b/examples/adwords/v201605/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,161 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201605') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create location groups. The IDs can be found in the documentation or + # retrieved with the LocationCriterionService. + florida_tier3 = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'IncomeOperand', + # Tiers are numbered 1-10, and represent 10% segments of earners. + # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. + # Tiers 6 through 10 are grouped into TIER_6_TO_10. + 'tier': 'TIER_3' + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + }, + } + florida_downtown = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'PlacesOfInterestOperand', + # Other valid options: AIRPORT, UNIVERSITY. + 'category': 'DOWNTOWN', + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + } + } + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish, florida_tier3, + florida_downtown] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201605/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201605/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..ffd844e9 --- /dev/null +++ b/examples/adwords/v201605/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201605') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201605/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..040af85d --- /dev/null +++ b/examples/adwords/v201605/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201605') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201605/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..b6066f51 --- /dev/null +++ b/examples/adwords/v201605/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201605') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201605/targeting/lookup_location.py b/examples/adwords/v201605/targeting/lookup_location.py new file mode 100755 index 00000000..76561912 --- /dev/null +++ b/examples/adwords/v201605/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201605') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/googleads.yaml b/googleads.yaml index f4c02277..64d7985a 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -25,6 +25,16 @@ adwords: # The following values configure the client for the service account flow. # service_account_email: INSERT_SERVICE_ACCOUNT_EMAIL_HERE # path_to_private_key_file: INSERT_PATH_TO_FILE_HERE + ############################################################################# + # ReportDownloader Headers # + # Below you may specify boolean values for optional headers that will be # + # applied to all requests made by the ReportDownloader utility by default. # + ############################################################################# + # report_downloader_headers: + # skip_report_header: False + # skip_column_header: False + # skip_report_summary: False + # use_raw_enum_values: False # DfpClient configurations diff --git a/googleads/adwords.py b/googleads/adwords.py index 51e1a3cb..64606c3e 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -167,6 +167,52 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201605': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'ExperimentService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } @@ -174,7 +220,8 @@ _REPORT_HEADER_KWARGS = {'include_zero_impressions': 'includeZeroImpressions', 'skip_report_header': 'skipReportHeader', 'skip_column_header': 'skipColumnHeader', - 'skip_report_summary': 'skipReportSummary'} + 'skip_report_summary': 'skipReportSummary', + 'use_raw_enum_values': 'useRawEnumValues'} # The endpoint used by default when making AdWords API requests. _DEFAULT_ENDPOINT = 'https://adwords.google.com' @@ -209,7 +256,7 @@ class AdWordsClient(object): _REQUIRED_INIT_VALUES = ('user_agent', 'developer_token') # A list of values which may optionally be provided when using AdWords. _OPTIONAL_INIT_VALUES = ('validate_only', 'partial_failure', - 'client_customer_id') + 'client_customer_id', 'report_downloader_headers') # The format of SOAP service WSDLs. A server, namespace, version, and service # name need to be formatted in. _SOAP_SERVICE_FORMAT = '%s/api/adwords/%s/%s/%s?wsdl' @@ -238,9 +285,7 @@ def LoadFromStorage(cls, path=None): cls._OPTIONAL_INIT_VALUES)) def __init__( - self, developer_token, oauth2_client, user_agent, - client_customer_id=None, validate_only=False, partial_failure=False, - cache=None, proxy_config=None): + self, developer_token, oauth2_client, user_agent, **kwargs): """Initializes an AdWordsClient. For more information on these arguments, see our SOAP headers guide: @@ -252,7 +297,9 @@ def __init__( your requests. user_agent: An arbitrary string which will be used to identify your application - [optional] + **kwargs: Optional keyword arguments. + + Keyword Arguments: client_customer_id: A string identifying which AdWords customer you want to act as. You do not have to provide this if you are using a client account. You probably want to provide this if you're using an AdWords @@ -267,20 +314,24 @@ def __init__( cache: A subclass of suds.cache.Cache; defaults to None. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. + report_downloader_headers: A dict containing optional headers to be used + by default when making requests with the ReportDownloader. """ self.developer_token = developer_token self.oauth2_client = oauth2_client self.oauth2_client.Refresh() self.user_agent = user_agent - self.client_customer_id = client_customer_id - self.validate_only = validate_only - self.partial_failure = partial_failure - self.cache = cache - self.proxy_config = (proxy_config if proxy_config - else googleads.common.ProxyConfig()) + self.client_customer_id = kwargs.get('client_customer_id') + self.validate_only = kwargs.get('validate_only', False) + self.partial_failure = kwargs.get('partial_failure', False) + self.cache = kwargs.get('cache') + proxy_config = kwargs.get('proxy_config') + self.proxy_config = (proxy_config if proxy_config else + googleads.common.ProxyConfig()) + self.report_download_headers = kwargs.get('report_download_headers', {}) def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], - server=_DEFAULT_ENDPOINT): + server=None): """Creates a service client for the given service. Args: @@ -299,6 +350,9 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], Raises: A GoogleAdsValueError if the service or version provided do not exist. """ + if not server: + server = _DEFAULT_ENDPOINT + if server[-1] == '/': server = server[:-1] try: client = suds.client.Client( @@ -321,7 +375,7 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], client, _AdWordsHeaderHandler(self, version)) def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], - server=_DEFAULT_ENDPOINT): + server=None): """Returns a BatchJobHelper to work with the BatchJobService. This is a convenience method. It is functionally identical to calling @@ -337,6 +391,9 @@ def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], Returns: An initialized BatchJobHelper tied to this client. """ + if not server: + server = _DEFAULT_ENDPOINT + request_builder = BatchJobHelper.GetRequestBuilder( client=self, version=version, server=server) response_parser = BatchJobHelper.GetResponseParser() @@ -344,7 +401,7 @@ def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], return BatchJobHelper(request_builder, response_parser, version=version) def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], - server=_DEFAULT_ENDPOINT): + server=None): """Creates a downloader for AdWords reports. This is a convenience method. It is functionally identical to calling @@ -360,6 +417,9 @@ def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], Returns: A ReportDownloader tied to this AdWordsClient, ready to download reports. """ + if not server: + server = _DEFAULT_ENDPOINT + return ReportDownloader(self, version, server) def SetClientCustomerId(self, client_customer_id): @@ -409,11 +469,14 @@ def SetHeaders(self, suds_client): soapheaders=header, headers=self._adwords_client.oauth2_client.CreateHttpHeader()) - def GetReportDownloadHeaders(self, kwargs): + def GetReportDownloadHeaders(self, **kwargs): """Returns a dictionary of headers for a report download request. + Note that the given keyword arguments will override any settings configured + from the googleads.yaml file. + Args: - kwargs: A dictionary containing optional keyword arguments. + **kwargs: Optional keyword arguments. Keyword Arguments: include_zero_impressions: A boolean indicating whether the report should @@ -427,6 +490,8 @@ def GetReportDownloadHeaders(self, kwargs): skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Returns: A dictionary containing the headers configured for downloading a report. @@ -440,9 +505,12 @@ def GetReportDownloadHeaders(self, kwargs): ',gzip']) }) - for kw in kwargs: + updated_kwargs = dict(self._adwords_client.report_download_headers) + updated_kwargs.update(kwargs) + + for kw in updated_kwargs: try: - headers.update({_REPORT_HEADER_KWARGS[kw]: str(kwargs[kw])}) + headers.update({_REPORT_HEADER_KWARGS[kw]: str(updated_kwargs[kw])}) except KeyError: raise googleads.errors.GoogleAdsValueError( 'The provided keyword "%s" is invalid. Accepted keywords are: %s' @@ -706,7 +774,7 @@ def _GenerateOperationsXML(self, operations): GoogleAdsValueError: if no xsi_type is specified for the operations. """ if operations: - # Verify that all operations included specify an xsi_type. + # Verify that all operations included specify an xsi_type. for operation in operations: if 'xsi_type' not in operation: raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( @@ -1019,7 +1087,7 @@ class ReportDownloader(object): _REPORT_DEFINITION_NAME = 'reportDefinition' def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], - server=_DEFAULT_ENDPOINT): + server=None): """Initializes a ReportDownloader. Args: @@ -1031,6 +1099,9 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], in future releases to point to what is then the latest version. server: A string identifying the webserver hosting the AdWords API. """ + if not server: + server = _DEFAULT_ENDPOINT + if server[-1] == '/': server = server[:-1] self._adwords_client = adwords_client self._namespace = self._NAMESPACE_FORMAT % version @@ -1084,6 +1155,8 @@ def DownloadReport(self, report_definition, output=sys.stdout, **kwargs): skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Raises: AdWordsReportBadRequestError: if the report download fails due to @@ -1095,7 +1168,7 @@ def DownloadReport(self, report_definition, output=sys.stdout, **kwargs): """ self._DownloadReportCheckFormat(report_definition['downloadFormat'], output) self._DownloadReport(self._SerializeReportDefinition(report_definition), - output, kwargs) + output, **kwargs) def DownloadReportAsStream(self, report_definition, **kwargs): """Downloads an AdWords report using a report definition. @@ -1120,6 +1193,8 @@ def DownloadReportAsStream(self, report_definition, **kwargs): skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Returns: A stream to be used in retrieving the report contents. @@ -1133,7 +1208,7 @@ def DownloadReportAsStream(self, report_definition, **kwargs): network error. """ return self._DownloadReportAsStream( - self._SerializeReportDefinition(report_definition), kwargs) + self._SerializeReportDefinition(report_definition), **kwargs) def DownloadReportAsStreamWithAwql(self, query, file_format, **kwargs): """Downloads an AdWords report using an AWQL query. @@ -1160,6 +1235,8 @@ def DownloadReportAsStreamWithAwql(self, query, file_format, **kwargs): skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Returns: A stream to be used in retrieving the report contents. @@ -1173,7 +1250,7 @@ def DownloadReportAsStreamWithAwql(self, query, file_format, **kwargs): network error. """ return self._DownloadReportAsStream(self._SerializeAwql(query, file_format), - kwargs) + **kwargs) def DownloadReportAsString(self, report_definition, **kwargs): """Downloads an AdWords report using a report definition. @@ -1198,6 +1275,8 @@ def DownloadReportAsString(self, report_definition, **kwargs): skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Returns: A string containing the report contents. @@ -1213,7 +1292,7 @@ def DownloadReportAsString(self, report_definition, **kwargs): response = None try: response = self._DownloadReportAsStream( - self._SerializeReportDefinition(report_definition), kwargs) + self._SerializeReportDefinition(report_definition), **kwargs) return response.read().decode('utf-8') finally: if response: @@ -1244,6 +1323,8 @@ def DownloadReportAsStringWithAwql(self, query, file_format, **kwargs): skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Returns: A string containing the report contents. @@ -1259,7 +1340,7 @@ def DownloadReportAsStringWithAwql(self, query, file_format, **kwargs): response = None try: response = self._DownloadReportAsStream( - self._SerializeAwql(query, file_format), kwargs) + self._SerializeAwql(query, file_format), **kwargs) return response.read().decode('utf-8') finally: if response: @@ -1295,6 +1376,8 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Raises: AdWordsReportBadRequestError: if the report download fails due to @@ -1306,9 +1389,9 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, """ self._DownloadReportCheckFormat(file_format, output) self._DownloadReport(self._SerializeAwql(query, file_format), output, - kwargs) + **kwargs) - def _DownloadReport(self, post_body, output, kwargs): + def _DownloadReport(self, post_body, output, **kwargs): """Downloads an AdWords report, writing the contents to the given file. Args: @@ -1316,7 +1399,7 @@ def _DownloadReport(self, post_body, output, kwargs): string. output: A writable object where the contents of the report will be written to. - kwargs: A dictionary containing optional keyword arguments. + **kwargs: A dictionary containing optional keyword arguments. Keyword Arguments: include_zero_impressions: A boolean indicating whether the report should @@ -1330,6 +1413,8 @@ def _DownloadReport(self, post_body, output, kwargs): skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Raises: AdWordsReportBadRequestError: if the report download fails due to @@ -1341,7 +1426,7 @@ def _DownloadReport(self, post_body, output, kwargs): """ response = None try: - response = self._DownloadReportAsStream(post_body, kwargs) + response = self._DownloadReportAsStream(post_body, **kwargs) output.write(response.read().decode() if sys.version_info[0] == 3 and (getattr(output, 'mode', 'w') == 'w' and type(output) is not io.BytesIO) @@ -1350,13 +1435,13 @@ def _DownloadReport(self, post_body, output, kwargs): if response: response.close() - def _DownloadReportAsStream(self, post_body, kwargs): + def _DownloadReportAsStream(self, post_body, **kwargs): """Downloads an AdWords report, returning a stream. Args: post_body: The contents of the POST request's body as a URL encoded string. - kwargs: A dictionary containing optional keyword arguments. + **kwargs: Optional keyword arguments. Keyword Arguments: include_zero_impressions: A boolean indicating whether the report should @@ -1370,6 +1455,8 @@ def _DownloadReportAsStream(self, post_body, kwargs): skip_report_summary: A boolean indicating whether to include a summary row containing the report totals. If false or not specified, report output will include the summary row. + use_raw_enum_values: A boolean indicating whether to return enum field + values as enums instead of display values. Returns: A stream to be used in retrieving the report contents. @@ -1386,7 +1473,7 @@ def _DownloadReportAsStream(self, post_body, kwargs): post_body = bytes(post_body, 'utf8') request = urllib2.Request( self._end_point, post_body, - self._header_handler.GetReportDownloadHeaders(kwargs)) + self._header_handler.GetReportDownloadHeaders(**kwargs)) try: return self.url_opener.open(request) except urllib2.HTTPError, e: diff --git a/googleads/common.py b/googleads/common.py index fa8dc942..c2ad9970 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -39,7 +39,7 @@ # not have certificate validation performed until they update. pass -VERSION = '4.0.0' +VERSION = '4.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' @@ -127,85 +127,130 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, 'values are: %s, actual values are %s' % (path, required_client_values, original_keys)) - http_proxy = None - https_proxy = None + proxy_config = _ExtractProxyConfig(product_yaml_key, proxy_config_data) + client_kwargs['proxy_config'] = proxy_config + client_kwargs['oauth2_client'] = _ExtractOAuth2Client( + product_yaml_key, product_data, proxy_config) - # HTTP Proxy Config - try: - if 'http_proxy' in proxy_config_data: - http_proxy_data = proxy_config_data.get('http_proxy') - original_http_proxy_keys = list(http_proxy_data.keys()) - http_proxy = ProxyConfig.Proxy( - http_proxy_data['host'], http_proxy_data['port'], - username=http_proxy_data.get('username'), - password=http_proxy_data.get('password')) - except KeyError: - raise googleads.errors.GoogleAdsValueError( - 'Your yaml file, %s, is missing some of the required http proxy ' - 'values. Required values are: %s, actual values are %s' - % (path, _PROXY_KEYS, original_http_proxy_keys)) - # HTTPS Proxy Config - # Note: If both HTTP and HTTPS proxies are specified, the ProxyInfo used - # by oauth2.py will always be the HTTPS proxy. - try: - if 'https_proxy' in proxy_config_data: - https_proxy_data = proxy_config_data.get('https_proxy') - original_https_proxy_keys = list(https_proxy_data.keys()) - https_proxy = ProxyConfig.Proxy( - https_proxy_data['host'], https_proxy_data['port'], - username=https_proxy_data.get('username'), - password=https_proxy_data.get('password')) - except KeyError: - raise googleads.errors.GoogleAdsValueError( - 'Your yaml file, %s, is missing some of the required https proxy ' - 'values. Required values are: %s, actual values are %s' - % (path, _PROXY_KEYS, original_https_proxy_keys)) + for value in optional_product_values: + if value in product_data: + client_kwargs[value] = product_data[value] + del product_data[value] - cafile = proxy_config_data.get('cafile', None) - disable_certificate_validation = proxy_config_data.get( - 'disable_certificate_validation', False) - proxy_config = ProxyConfig( - http_proxy=http_proxy, https_proxy=https_proxy, cafile=cafile, - disable_certificate_validation=disable_certificate_validation) - client_kwargs['proxy_config'] = proxy_config + if product_data: + warnings.warn('Your yaml file, %s, contains the following unrecognized ' + 'keys: %s. They were ignored.' % (path, product_data), + stacklevel=3) + + return client_kwargs + + +def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config): + """Generates an GoogleOAuth2Client subclass using the given product_data. + + Args: + product_yaml_key: a string key identifying the product being configured. + product_data: a dict containing the configurations for a given product. + proxy_config: a ProxyConfig instance. + Returns: + An instantiated GoogleOAuth2Client subclass. + + Raises: + A GoogleAdsValueError if the OAuth2 configuration for the given product is + misconfigured. + """ if all(config in product_data for config in _OAUTH2_INSTALLED_APP_KEYS): - # Use provided configurations for the installed application flow. - client_kwargs['oauth2_client'] = ( - googleads.oauth2.GoogleRefreshTokenClient( - product_data['client_id'], product_data['client_secret'], - product_data['refresh_token'], proxy_config=proxy_config)) + oauth2_args = [ + product_data['client_id'], product_data['client_secret'], + product_data['refresh_token'] + ] + oauth2_client = googleads.oauth2.GoogleRefreshTokenClient for key in _OAUTH2_INSTALLED_APP_KEYS: del product_data[key] elif all(config in product_data for config in _OAUTH2_SERVICE_ACCT_KEYS): - # Use provided configurations for the service account flow. - client_kwargs['oauth2_client'] = ( - googleads.oauth2.GoogleServiceAccountClient( - googleads.oauth2.GetAPIScope(product_yaml_key), - product_data['service_account_email'], - product_data['path_to_private_key_file'], - proxy_config=proxy_config)) + oauth2_args = [ + googleads.oauth2.GetAPIScope(product_yaml_key), + product_data['service_account_email'], + product_data['path_to_private_key_file'] + ] + oauth2_client = googleads.oauth2.GoogleServiceAccountClient for key in _OAUTH2_SERVICE_ACCT_KEYS: del product_data[key] else: raise googleads.errors.GoogleAdsValueError( - 'Your yaml file, %s, is incorrectly configured for OAuth2. You ' - 'need to specify credentials for either the installed application ' - 'flow (%s) or service account flow (%s). Actual values provided are: ' - '%s' % (path, _OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS, - original_keys)) + 'Your yaml file is incorrectly configured for OAuth2. You need to ' + 'specify credentials for either the installed application flow (%s) ' + 'or service account flow (%s).' % + (_OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS)) - for value in optional_product_values: - if value in product_data: - client_kwargs[value] = product_data[value] - del product_data[value] + return oauth2_client(*oauth2_args, proxy_config=proxy_config) - if product_data: - warnings.warn( - 'Your yaml file, %s, contains the following unrecognized ' - 'keys: %s. They were ignored.' % (path, product_data), stacklevel=3) - return client_kwargs +def _ExtractProxyConfig(product_yaml_key, proxy_config_data): + """Returns an initialized ProxyConfig using the given proxy_config_data. + + Args: + product_yaml_key: a string indicating the client being loaded. + proxy_config_data: a dict containing the contents of proxy_config from the + YAML file. + + Returns: + If there is a proxy to configure in proxy_config, this will return a + ProxyConfig instance with those settings. Otherwise, it will return None. + + Raises: + A GoogleAdsValueError if one of the required keys specified by _PROXY_KEYS + is missing. + """ + cafile = proxy_config_data.get('cafile', None) + disable_certificate_validation = proxy_config_data.get( + 'disable_certificate_validation', False) + http_proxy = _ExtractProxy(_HTTP_PROXY_YAML_KEY, proxy_config_data) + https_proxy = _ExtractProxy(_HTTPS_PROXY_YAML_KEY, proxy_config_data) + proxy_config = ProxyConfig( + http_proxy=http_proxy, + https_proxy=https_proxy, + cafile=cafile, + disable_certificate_validation=disable_certificate_validation) + + return proxy_config + + +def _ExtractProxy(proxy_yaml_key, proxy_config_data): + """Extracts a ProxyConfig.Proxy from the proxy_config for a given key. + + Args: + proxy_yaml_key: a key specifying the type of proxy for which data is being + loaded. + proxy_config_data: a dict containing the proxy configurations loaded from + the YAML file. + + Returns: + If the proxy_yaml_key exists in the proxy_config_data, this will return a + ProxyConfig.Proxy instance initialized with the data associated with it. + Otherwise, this will return None. + + Raises: + A GoogleAdsValueError if one of the required keys specified by _PROXY_KEYS + is missing. + """ + proxy = None + try: + if proxy_yaml_key in proxy_config_data: + proxy_data = proxy_config_data.get(proxy_yaml_key) + original_proxy_keys = list(proxy_data.keys()) + proxy = ProxyConfig.Proxy(proxy_data['host'], + proxy_data['port'], + username=proxy_data.get('username'), + password=proxy_data.get('password')) + except KeyError: + raise googleads.errors.GoogleAdsValueError( + 'Your yaml file is missing some of the required proxy values. Required ' + 'values are: %s, actual values are %s' % + (_PROXY_KEYS, original_proxy_keys)) + + return proxy def _PackForSuds(obj, factory): @@ -354,7 +399,11 @@ def _InitSSLContext(self, cafile=None, # Attempt to create a context; this should succeed in Python 2 versions # 2.7.9+ and Python 3 versions 3.4+. try: - ssl_context = ssl.create_default_context(cafile=cafile) + if disable_ssl_certificate_validation: + ssl._create_default_https_context = ssl._create_unverified_context + ssl_context = ssl.create_default_context() + else: + ssl_context = ssl.create_default_context(cafile=cafile) except AttributeError: # Earlier versions lack ssl.create_default_context() # Rather than raising the exception, no context will be provided for @@ -362,9 +411,6 @@ def _InitSSLContext(self, cafile=None, # taking place! return None - if disable_ssl_certificate_validation: - ssl_context.verify_mode = ssl.CERT_NONE - return ssl_context def GetHandlers(self): diff --git a/googleads/dfp.py b/googleads/dfp.py index 15ba30d8..284257d2 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -230,7 +230,7 @@ def __init__(self, oauth2_client, application_name, network_code=None, else googleads.common.ProxyConfig()) def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], - server=DEFAULT_ENDPOINT): + server=None): """Creates a service client for the given service. Args: @@ -249,6 +249,9 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], Raises: A GoogleAdsValueError if the service or version provided do not exist. """ + if not server: + server = DEFAULT_ENDPOINT + server = server[:-1] if server[-1] == '/' else server try: client = suds.client.Client( @@ -272,7 +275,7 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], return googleads.common.SudsServiceProxy(client, self._header_handler) def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], - server=DEFAULT_ENDPOINT): + server=None): """Creates a downloader for DFP reports and PQL result sets. This is a convenience method. It is functionally identical to calling @@ -288,6 +291,9 @@ def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], Returns: A DataDownloader tied to this DfpClient, ready to download reports. """ + if not server: + server = DEFAULT_ENDPOINT + return DataDownloader(self, version, server) @@ -347,7 +353,7 @@ class DataDownloader(object): """A utility that can be used to download reports and PQL result sets.""" def __init__(self, dfp_client, version=sorted(_SERVICE_MAP.keys())[-1], - server=DEFAULT_ENDPOINT): + server=None): """Initializes a DataDownloader. Args: @@ -359,6 +365,9 @@ def __init__(self, dfp_client, version=sorted(_SERVICE_MAP.keys())[-1], future releases to point to what is then the latest version. server: A string identifying the webserver hosting the DFP API. """ + if not server: + server = DEFAULT_ENDPOINT + if server[-1] == '/': server = server[:-1] self._dfp_client = dfp_client self._version = version diff --git a/googleads/oauth2.py b/googleads/oauth2.py index fdea66e7..a425fcba 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -11,7 +11,6 @@ # 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. - """OAuth2 integration for the googleads library. This module provides a basic interface which the googleads library uses to @@ -22,7 +21,6 @@ from independently refreshing the credentials. """ - import datetime @@ -53,8 +51,8 @@ def GetAPIScope(api_name): return SCOPES[api_name] except KeyError: raise googleads.errors.GoogleAdsValueError( - 'Invalid API name "%s" provided. Acceptable values are: %s' - % (api_name, SCOPES.keys())) + 'Invalid API name "%s" provided. Acceptable values are: %s' % + (api_name, SCOPES.keys())) class GoogleOAuth2Client(object): @@ -63,6 +61,16 @@ class GoogleOAuth2Client(object): This interface assumes all responsibilty for refreshing credentials when necessary. """ + # The web address for generating OAuth2 credentials at Google. + _GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token' + # We will refresh an OAuth2 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE + # minutes in advance of its expiration. + _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5 + # The placeholder URL is used when adding the access token to our request. A + # well-formed URL is required, but since we're using HTTP header placement for + # the token, this URL is completely unused. + _TOKEN_URL = 'https://www.google.com' + _USER_AGENT = 'Google Ads Python Client Library' def CreateHttpHeader(self): """Creates an OAuth2 HTTP header. @@ -91,16 +99,6 @@ class GoogleRefreshTokenClient(GoogleOAuth2Client): Attributes: proxy_info: A ProxyInfo instance used for refresh requests. """ - # The web address for generating OAuth2 credentials at Google. - _GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token' - # We will refresh an OAuth2 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE - # minutes in advance of its expiration. - _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5 - # The placeholder URL is used when adding the access token to our request. A - # well-formed URL is required, but since we're using HTTP header placement for - # the token, this URL is completely unused. - _TOKEN_URL = 'https://www.google.com' - _USER_AGENT = 'Google Ads Python Client Library' def __init__(self, client_id, client_secret, refresh_token, proxy_config=None): @@ -118,8 +116,8 @@ def __init__(self, client_id, client_secret, refresh_token, None, client_id, client_secret, refresh_token, datetime.datetime(1980, 1, 1, 12), self._GOOGLE_OAUTH2_ENDPOINT, self._USER_AGENT) - self.proxy_config = (proxy_config if proxy_config - else googleads.common.ProxyConfig()) + self.proxy_config = (proxy_config if proxy_config else + googleads.common.ProxyConfig()) def CreateHttpHeader(self): """Creates an OAuth2 HTTP header. @@ -137,9 +135,9 @@ def CreateHttpHeader(self): """ oauth2_header = {} - if(self.oauth2credentials.token_expiry is not None and - (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() < - datetime.timedelta(minutes=self._OAUTH2_REFRESH_MINUTES_IN_ADVANCE))): + if (self.oauth2credentials.token_expiry is not None and + (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() < + datetime.timedelta(minutes=self._OAUTH2_REFRESH_MINUTES_IN_ADVANCE))): self.Refresh() self.oauth2credentials.apply(oauth2_header) @@ -151,12 +149,11 @@ def Refresh(self): Raises: AccessTokenRefreshError: If the refresh fails. """ - self.oauth2credentials.refresh( - httplib2.Http( - proxy_info=self.proxy_config.proxy_info, - ca_certs=self.proxy_config.cafile, - disable_ssl_certificate_validation=( - self.proxy_config.disable_certificate_validation))) + self.oauth2credentials.refresh(httplib2.Http( + proxy_info=self.proxy_config.proxy_info, + ca_certs=self.proxy_config.cafile, + disable_ssl_certificate_validation=( + self.proxy_config.disable_certificate_validation))) class GoogleServiceAccountClient(GoogleOAuth2Client): @@ -200,8 +197,8 @@ def __init__(self, scope, client_email, key_file, self.oauth2credentials = oauth2client.client.SignedJwtAssertionCredentials( client_email, private_key, scope, - private_key_password=private_key_password, - user_agent=self._USER_AGENT, sub=sub) + private_key_password=private_key_password, user_agent=self._USER_AGENT, + token_uri=self._GOOGLE_OAUTH2_ENDPOINT, sub=sub) self.proxy_config = proxy_config self.Refresh() @@ -221,9 +218,9 @@ def CreateHttpHeader(self): """ oauth2_header = {} - if(self.oauth2credentials.token_expiry is not None and - (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() < - datetime.timedelta(minutes=self._OAUTH2_REFRESH_MINUTES_IN_ADVANCE))): + if (self.oauth2credentials.token_expiry is not None and + (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() < + datetime.timedelta(minutes=self._OAUTH2_REFRESH_MINUTES_IN_ADVANCE))): self.Refresh() self.oauth2credentials.apply(oauth2_header) @@ -235,9 +232,8 @@ def Refresh(self): Raises: AccessTokenRefreshError: If the refresh fails. """ - self.oauth2credentials.refresh( - httplib2.Http( - proxy_info=self.proxy_config.proxy_info, - ca_certs=self.proxy_config.cafile, - disable_ssl_certificate_validation=( - self.proxy_config.disable_certificate_validation))) + self.oauth2credentials.refresh(httplib2.Http( + proxy_info=self.proxy_config.proxy_info, + ca_certs=self.proxy_config.cafile, + disable_ssl_certificate_validation=( + self.proxy_config.disable_certificate_validation))) diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 4f298913..8330b077 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -99,6 +99,7 @@ class AdWordsHeaderHandlerTest(unittest.TestCase): def setUp(self): self.aw_client = mock.Mock() + self.aw_client.report_download_headers = {} self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.aw_client, CURRENT_VERSION) @@ -136,7 +137,7 @@ def testSetHeaders(self): suds_client.set_options.assert_any_call( soapheaders=soap_header, headers=oauth_header) - def testGetReportDownloadHeaders(self): + def testGetReportDownloadHeadersOverrideDefaults(self): ccid = 'client customer id' dev_token = 'developer token' user_agent = 'user agent!' @@ -146,6 +147,9 @@ def testGetReportDownloadHeaders(self): self.aw_client.user_agent = user_agent self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) + self.aw_client.report_downloader_headers = { + 'skip_report_header': True, 'skip_column_header': False, + 'skip_report_summary': False, 'use_raw_enum_values': True} expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', 'developerToken': dev_token, @@ -155,17 +159,51 @@ def testGetReportDownloadHeaders(self): user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, ',gzip']), 'skipReportHeader': 'False', - 'skipColumnHeader': 'False', - 'skipReportSummary': 'False' + 'skipColumnHeader': 'True', + 'skipReportSummary': 'False', + 'useRawEnumValues': 'True' } self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( - {'skip_report_header': False, - 'skip_column_header': False, - 'skip_report_summary': False})) + skip_report_header=False, + skip_column_header=True, + skip_report_summary=False, + use_raw_enum_values=True)) + + def testGetReportDownloadHeadersWithDefaultsFromConfig(self): + ccid = 'client customer id' + dev_token = 'developer token' + user_agent = 'user agent!' + oauth_header = {'Authorization': 'header'} + self.aw_client.client_customer_id = ccid + self.aw_client.developer_token = dev_token + self.aw_client.user_agent = user_agent + self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( + oauth_header) + self.aw_client.report_download_headers = { + 'skip_report_header': True, 'skip_column_header': False, + 'skip_report_summary': False, 'use_raw_enum_values': True} + expected_return_value = { + 'Content-type': 'application/x-www-form-urlencoded', + 'developerToken': dev_token, + 'clientCustomerId': ccid, + 'Authorization': 'header', + 'User-Agent': ''.join([ + user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + ',gzip']), + 'skipReportHeader': 'True', + 'skipColumnHeader': 'False', + 'skipReportSummary': 'False', + 'useRawEnumValues': 'True' + } + + self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( + oauth_header) + self.assertEqual(expected_return_value, + self.header_handler.GetReportDownloadHeaders()) def testGetReportDownloadHeadersWithInvalidKeyword(self): ccid = 'client customer id' @@ -177,10 +215,9 @@ def testGetReportDownloadHeadersWithInvalidKeyword(self): self.assertRaises( googleads.errors.GoogleAdsValueError, - self.header_handler.GetReportDownloadHeaders, - {'invalid_key_word': True}) + self.header_handler.GetReportDownloadHeaders, invalid_key_word=True) - def testGetReportDownloadHeadersWithOptionalHeaders(self): + def testGetReportDownloadHeadersWithKeywordArguments(self): ccid = 'client customer id' dev_token = 'developer token' user_agent = 'user agent!' @@ -201,17 +238,44 @@ def testGetReportDownloadHeadersWithOptionalHeaders(self): 'skipReportHeader': 'True', 'skipColumnHeader': 'True', 'skipReportSummary': 'True', - 'includeZeroImpressions': 'True' + 'includeZeroImpressions': 'True', + 'useRawEnumValues': 'True' } self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( - {'skip_report_header': True, - 'skip_column_header': True, - 'skip_report_summary': True, - 'include_zero_impressions': True})) + skip_report_header=True, + skip_column_header=True, + skip_report_summary=True, + include_zero_impressions=True, + use_raw_enum_values=True)) + + def testGetReportDownloadHeadersWithNoOptionalHeaders(self): + ccid = 'client customer id' + dev_token = 'developer token' + user_agent = 'user agent!' + oauth_header = {'Authorization': 'header'} + self.aw_client.client_customer_id = ccid + self.aw_client.developer_token = dev_token + self.aw_client.user_agent = user_agent + self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( + oauth_header) + expected_return_value = { + 'Content-type': 'application/x-www-form-urlencoded', + 'developerToken': dev_token, + 'clientCustomerId': ccid, + 'Authorization': 'header', + 'User-Agent': ''.join([ + user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + ',gzip']) + } + + self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( + oauth_header) + self.assertEqual(expected_return_value, + self.header_handler.GetReportDownloadHeaders()) class AdWordsClientTest(unittest.TestCase): @@ -1313,7 +1377,9 @@ def testDownloadReport(self): with mock.patch('suds.mx.Content') as mock_content: with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: self.opener.open.return_value = fake_request - self.report_downloader.DownloadReport(report_definition, output_file) + self.report_downloader.DownloadReport(report_definition, output_file, + skip_report_header=True, + use_raw_enum_values=False) mock_request.assert_called_once_with( ('https://adwords.google.com/api/adwords/reportdownload/%s' % self.version), post_body, headers) @@ -1321,7 +1387,8 @@ def testDownloadReport(self): self.marshaller.process.assert_called_once_with( mock_content.return_value) self.assertEqual(content, output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with( + skip_report_header=True, use_raw_enum_values=False) def testDownloadReportAsString(self): report_definition = {'table': 'campaigns', @@ -1350,7 +1417,7 @@ def testDownloadReportAsString(self): self.marshaller.process.assert_called_once_with( mock_content.return_value) self.assertEqual(content, s) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with() def testDownloadReportAsStringWithAwql(self): query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' @@ -1367,14 +1434,16 @@ def testDownloadReportAsStringWithAwql(self): fake_request.seek(0) with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: self.opener.open.return_value = fake_request - s = self.report_downloader.DownloadReportAsStringWithAwql(query, - file_format) + s = self.report_downloader.DownloadReportAsStringWithAwql( + query, file_format, include_zero_impressions=True, + use_raw_enum_values=False) mock_request.assert_called_once_with( ('https://adwords.google.com/api/adwords/reportdownload/%s' % self.version), post_body, headers) self.opener.open.assert_called_once_with(mock_request.return_value) self.assertEqual(content, s) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with( + include_zero_impressions=True, use_raw_enum_values=False) def testDownloadReportCheckFormat_CSVStringSuccess(self): output_file = io.StringIO() @@ -1444,7 +1513,7 @@ def testDownloadReport_failure(self): self.marshaller.process.assert_called_once_with( mock_content.return_value) self.assertEqual('', output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with() def testDownloadReportWithAwql(self): output_file = io.StringIO() @@ -1471,7 +1540,7 @@ def testDownloadReportWithAwql(self): self.opener.open.assert_called_once_with(mock_request.return_value) self.assertEqual(content, output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with() def testDownloadReportWithBytesIO(self): output_file = io.BytesIO() @@ -1501,7 +1570,7 @@ def testDownloadReportWithBytesIO(self): self.marshaller.process.assert_called_once_with( mock_content.return_value) self.assertEqual(content, output_file.getvalue().decode('utf-8')) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with({}) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with() def testExtractError_badRequest(self): response = mock.Mock() diff --git a/tests/common_test.py b/tests/common_test.py index fa8872f1..57169b4e 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -11,7 +11,6 @@ # 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. - """Unit tests to cover the common module.""" @@ -20,8 +19,8 @@ import warnings -import fake_filesystem -import fake_tempfile +from pyfakefs import fake_filesystem +from pyfakefs import fake_tempfile import mock import suds import yaml @@ -45,9 +44,11 @@ def setUp(self): self.tempfile = fake_tempfile.FakeTempfileModule(self.filesystem) self.fake_open = fake_filesystem.FakeFileOpen(self.filesystem) self.host1 = 'h1' - self.port1 = 'p1' + self.port1 = 1 self.host2 = 'h2' - self.port2 = 'p2' + self.port2 = 2 + self.uplink_host = '127.0.0.1' + self.uplink_port = 999 self.username = 'username' self.password = 'password' From 33d96923c4a1aae0a7689b50c0787b64414edc32 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Fri, 27 May 2016 13:22:56 -0400 Subject: [PATCH 039/180] Commiting latest changes. From fa93533552abea81e324ed9087086e288cbe2549 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 17 Jun 2016 17:39:43 -0400 Subject: [PATCH 040/180] Removing support for AdWords v201509 --- ChangeLog | 13 + README.md | 14 + examples/adwords/v201509/__init__.py | 15 - .../v201509/account_management/__init__.py | 15 - .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 103 ---- .../get_account_hierarchy.py | 104 ---- .../v201509/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 222 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 108 ---- .../advanced_operations/add_html5_ad.py | 111 ---- .../add_text_ad_with_upgraded_urls.py | 111 ---- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../upload_offline_conversions.py | 98 ---- .../use_shared_bidding_strategy.py | 172 ------ .../v201509/basic_operations/__init__.py | 15 - .../v201509/basic_operations/add_ad_groups.py | 115 ---- .../v201509/basic_operations/add_campaigns.py | 126 ----- .../v201509/basic_operations/add_keywords.py | 92 --- .../v201509/basic_operations/add_text_ads.py | 93 ---- .../v201509/basic_operations/get_ad_groups.py | 76 --- .../v201509/basic_operations/get_campaigns.py | 74 --- .../get_campaigns_with_awql.py | 64 --- .../v201509/basic_operations/get_keywords.py | 87 --- .../v201509/basic_operations/get_text_ads.py | 80 --- .../v201509/basic_operations/pause_ad.py | 61 -- .../v201509/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 58 -- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201509/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 427 -------------- .../campaign_management/add_experiment.py | 127 ----- .../add_keywords_in_bulk.py | 134 ----- ...dd_keywords_using_incremental_batch_job.py | 259 --------- .../get_all_disapproved_ads.py | 74 --- .../get_all_disapproved_ads_with_awql.py | 63 --- .../get_campaigns_by_label.py | 85 --- .../campaign_management/promote_experiment.py | 60 -- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201509/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 120 ---- .../handle_policy_violation_error.py | 114 ---- .../adwords/v201509/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 ------ .../v201509/extensions/add_site_links.py | 124 ----- .../extensions/add_site_links_using_feeds.py | 233 -------- .../adwords/v201509/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 ------------------ .../v201509/migration/upgrade_ad_url.py | 79 --- examples/adwords/v201509/misc/__init__.py | 15 - .../v201509/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201509/misc/upload_image.py | 66 --- .../v201509/misc/upload_media_bundle.py | 59 -- .../adwords/v201509/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 133 ----- .../get_keyword_bid_simulations.py | 81 --- .../v201509/optimization/get_keyword_ideas.py | 90 --- .../adwords/v201509/remarketing/__init__.py | 15 - .../v201509/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 71 --- .../remarketing/add_crm_based_user_list.py | 97 ---- .../remarketing/add_rule_based_user_lists.py | 183 ------ .../adwords/v201509/reporting/__init__.py | 15 - .../reporting/download_criteria_report.py | 61 -- .../download_criteria_report_as_stream.py | 77 --- ...oad_criteria_report_as_stream_with_awql.py | 81 --- .../download_criteria_report_as_string.py | 59 -- ...oad_criteria_report_as_string_with_awql.py | 55 -- .../download_criteria_report_with_awql.py | 59 -- .../v201509/reporting/get_report_fields.py | 52 -- examples/adwords/v201509/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 281 ---------- .../v201509/shopping/add_product_scope.py | 104 ---- .../v201509/shopping/add_shopping_campaign.py | 121 ---- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201509/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 161 ------ .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201509/targeting/lookup_location.py | 82 --- .../reporting/parallel_report_download.py | 230 ++++++++ .../reporting/parallel_report_download.py | 230 ++++++++ .../add_responsive_display_ad.py | 2 +- .../reporting/parallel_report_download.py | 230 ++++++++ .../get_content_by_category.py | 109 ---- googleads.yaml | 5 + googleads/adwords.py | 75 +-- googleads/common.py | 96 +++- googleads/oauth2.py | 3 +- googleads/patches.py | 40 -- googleads/util.py | 78 +++ tests/adwords_test.py | 10 +- tests/common_test.py | 104 +++- tests/oauth2_test.py | 12 + tests/{patches_test.py => util_test.py} | 3 +- 106 files changed, 1039 insertions(+), 8667 deletions(-) delete mode 100644 examples/adwords/v201509/__init__.py delete mode 100644 examples/adwords/v201509/account_management/__init__.py delete mode 100755 examples/adwords/v201509/account_management/create_account.py delete mode 100755 examples/adwords/v201509/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201509/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201509/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201509/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201509/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201509/advanced_operations/upload_offline_conversions.py delete mode 100755 examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201509/basic_operations/__init__.py delete mode 100755 examples/adwords/v201509/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201509/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201509/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201509/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201509/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201509/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201509/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201509/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201509/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201509/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201509/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201509/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201509/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201509/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201509/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201509/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201509/campaign_management/__init__.py delete mode 100755 examples/adwords/v201509/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201509/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py delete mode 100755 examples/adwords/v201509/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201509/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201509/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201509/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201509/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201509/error_handling/__init__.py delete mode 100755 examples/adwords/v201509/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201509/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201509/extensions/__init__.py delete mode 100755 examples/adwords/v201509/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201509/extensions/add_site_links.py delete mode 100755 examples/adwords/v201509/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201509/migration/__init__.py delete mode 100755 examples/adwords/v201509/migration/migrate_to_extension_settings.py delete mode 100755 examples/adwords/v201509/migration/upgrade_ad_url.py delete mode 100644 examples/adwords/v201509/misc/__init__.py delete mode 100755 examples/adwords/v201509/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201509/misc/upload_image.py delete mode 100755 examples/adwords/v201509/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201509/optimization/__init__.py delete mode 100755 examples/adwords/v201509/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201509/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201509/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201509/remarketing/__init__.py delete mode 100755 examples/adwords/v201509/remarketing/add_audience.py delete mode 100755 examples/adwords/v201509/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201509/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201509/remarketing/add_rule_based_user_lists.py delete mode 100644 examples/adwords/v201509/reporting/__init__.py delete mode 100755 examples/adwords/v201509/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201509/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201509/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201509/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201509/reporting/get_report_fields.py delete mode 100644 examples/adwords/v201509/shopping/__init__.py delete mode 100755 examples/adwords/v201509/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201509/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201509/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201509/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201509/targeting/__init__.py delete mode 100755 examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201509/targeting/lookup_location.py create mode 100755 examples/adwords/v201601/reporting/parallel_report_download.py create mode 100755 examples/adwords/v201603/reporting/parallel_report_download.py create mode 100755 examples/adwords/v201605/reporting/parallel_report_download.py delete mode 100755 examples/dfp/v201605/content_service/get_content_by_category.py delete mode 100644 googleads/patches.py create mode 100644 googleads/util.py rename tests/{patches_test.py => util_test.py} (98%) diff --git a/ChangeLog b/ChangeLog index 461f8209..5dfe9af0 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,16 @@ +4.2.0 -- 6/13/2016 +* Removed support and examples for AdWords v201509. +* The AdWords ReportDownloader now accepts a "client_customer_id" keyword + argument that overrides the default client customer ID. +* For utilities such as the ReportDownloader or BatchJobHelper, data points + about usage are now sent in the user-agent of API requests by default. This + can be disabled with the new include_utilities_in_user_agent configuration in + the googleads.yaml file. +* Added a new parallel_report_download.py example. +* Resolved issues: + Issue #122: https://github.com/googleads/googleads-python-lib/issues/122 + Issue #123: https://github.com/googleads/googleads-python-lib/issues/123 + 4.1.0 -- 5/26/2016 * Added support for AdWords v201605. * Added new use_raw_enum_values keyword argument to the AdWords ReportDownloader diff --git a/README.md b/README.md index 6111549c..ab5c4505 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,9 @@ code to help you get started integrating with our APIs. ##Getting started 1. Download and install the library + *[setuptools](https://pypi.python.org/pypi/setuptools) is a pre-requisite + for installing the googleads library* + It is recommended that you install the library and its dependencies from PyPI using [pip](https://pip.pypa.io/en/stable/installing/). This can be accomplished with a single command: @@ -144,6 +147,17 @@ suds_client.set_options( suds_client.service.mutate([operation]) ``` +##Timeout Tips +The requests sent by this library are sent via urllib, which is consequently +where the timeout is set. If you set a system timeout elsewhere, the googleads +library will respect it. + +You can do the following if you wish to override the timeout: + +```python +import socket +socket.setdefaulttimeout(15 * 60) +``` ##External Dependencies: diff --git a/examples/adwords/v201509/__init__.py b/examples/adwords/v201509/__init__.py deleted file mode 100644 index 41f5a52e..00000000 --- a/examples/adwords/v201509/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201509/account_management/__init__.py b/examples/adwords/v201509/account_management/__init__.py deleted file mode 100644 index fb8c03ea..00000000 --- a/examples/adwords/v201509/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201509/account_management/create_account.py b/examples/adwords/v201509/account_management/create_account.py deleted file mode 100755 index a0470ff2..00000000 --- a/examples/adwords/v201509/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201509') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/account_management/get_account_changes.py b/examples/adwords/v201509/account_management/get_account_changes.py deleted file mode 100755 index 635445c5..00000000 --- a/examples/adwords/v201509/account_management/get_account_changes.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201509') - campaign_service = client.GetService('CampaignService', version='v201509') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedAdExtensions' in data: - print ' Added ad extensions: %s' % data['addedAdExtensions'] - if 'removedAdExtensions' in data: - print ' Removed ad extensions: %s' % data['removedAdExtensions'] - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/account_management/get_account_hierarchy.py b/examples/adwords/v201509/account_management/get_account_hierarchy.py deleted file mode 100755 index c788e1cc..00000000 --- a/examples/adwords/v201509/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201509') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/advanced_operations/__init__.py b/examples/adwords/v201509/advanced_operations/__init__.py deleted file mode 100644 index 7e57b8b3..00000000 --- a/examples/adwords/v201509/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201509/advanced_operations/add_ad_customizer.py b/examples/adwords/v201509/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 055a04ec..00000000 --- a/examples/adwords/v201509/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates TextAds that use ad customizations for the specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add TextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no TextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService') - - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'description1': 'Only {=%s.Price}' % feed_name, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index cde0ba14..00000000 --- a/examples/adwords/v201509/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201509') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 955ded76..00000000 --- a/examples/adwords/v201509/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad to ad group ID \'%s\' ' - 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/advanced_operations/add_html5_ad.py b/examples/adwords/v201509/advanced_operations/add_html5_ad.py deleted file mode 100755 index b171ca8a..00000000 --- a/examples/adwords/v201509/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index b75702e1..00000000 --- a/examples/adwords/v201509/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a text add that uses advanced features of upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index c6b91733..00000000 --- a/examples/adwords/v201509/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201509') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201509') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201509') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index da0361e2..00000000 --- a/examples/adwords/v201509/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201509') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201509') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 1ff38b87..00000000 --- a/examples/adwords/v201509/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201509') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py b/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py deleted file mode 100755 index 123d0027..00000000 --- a/examples/adwords/v201509/advanced_operations/upload_offline_conversions.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - conversion_tracker_service = client.GetService('ConversionTrackerService', - version='v201509') - - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201509') - - # Once created, this entry will be visible under - # Tools and Analysis->Conversion and will have "Source = Import". - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'category': 'PAGE_VIEW', - 'name': conversion_name, - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90' - } - - upload_conversion_operation = { - 'operator': 'ADD', - 'operand': upload_conversion - } - - response = conversion_tracker_service.mutate( - [upload_conversion_operation]) - new_upload_conversion = response['value'] - - print ('New upload conversion type with name \'%s\' and ID \'%s\' was ' - 'created.' % (new_upload_conversion['name'], - new_upload_conversion['id'])) - - # Associate offline conversions with the upload conversion we created. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 28b90a07..00000000 --- a/examples/adwords/v201509/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201509') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201509') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'period': 'DAILY', - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201509') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201509/basic_operations/__init__.py b/examples/adwords/v201509/basic_operations/__init__.py deleted file mode 100644 index 80acbea9..00000000 --- a/examples/adwords/v201509/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201509/basic_operations/add_ad_groups.py b/examples/adwords/v201509/basic_operations/add_ad_groups.py deleted file mode 100755 index eef60c1f..00000000 --- a/examples/adwords/v201509/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README.. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201509') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/basic_operations/add_campaigns.py b/examples/adwords/v201509/basic_operations/add_campaigns.py deleted file mode 100755 index ef01b692..00000000 --- a/examples/adwords/v201509/basic_operations/add_campaigns.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201509') - budget_service = client.GetService('BudgetService', version='v201509') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/basic_operations/add_keywords.py b/examples/adwords/v201509/basic_operations/add_keywords.py deleted file mode 100755 index bd2a6f4b..00000000 --- a/examples/adwords/v201509/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/add_text_ads.py b/examples/adwords/v201509/basic_operations/add_text_ads.py deleted file mode 100755 index 168720f7..00000000 --- a/examples/adwords/v201509/basic_operations/add_text_ads.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/get_ad_groups.py b/examples/adwords/v201509/basic_operations/get_ad_groups.py deleted file mode 100755 index d2009ece..00000000 --- a/examples/adwords/v201509/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201509') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/basic_operations/get_campaigns.py b/examples/adwords/v201509/basic_operations/get_campaigns.py deleted file mode 100755 index 0c400aea..00000000 --- a/examples/adwords/v201509/basic_operations/get_campaigns.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201509') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index c2cbf6e4..00000000 --- a/examples/adwords/v201509/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201509') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/basic_operations/get_keywords.py b/examples/adwords/v201509/basic_operations/get_keywords.py deleted file mode 100755 index dc452bdf..00000000 --- a/examples/adwords/v201509/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/get_text_ads.py b/examples/adwords/v201509/basic_operations/get_text_ads.py deleted file mode 100755 index caabbb42..00000000 --- a/examples/adwords/v201509/basic_operations/get_text_ads.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/pause_ad.py b/examples/adwords/v201509/basic_operations/pause_ad.py deleted file mode 100755 index a698508d..00000000 --- a/examples/adwords/v201509/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201509/basic_operations/remove_ad.py b/examples/adwords/v201509/basic_operations/remove_ad.py deleted file mode 100755 index d8a1a2bc..00000000 --- a/examples/adwords/v201509/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201509/basic_operations/remove_ad_group.py b/examples/adwords/v201509/basic_operations/remove_ad_group.py deleted file mode 100755 index d9a6901c..00000000 --- a/examples/adwords/v201509/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201509') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/remove_campaign.py b/examples/adwords/v201509/basic_operations/remove_campaign.py deleted file mode 100755 index d7dd29f7..00000000 --- a/examples/adwords/v201509/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201509') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/basic_operations/remove_keyword.py b/examples/adwords/v201509/basic_operations/remove_keyword.py deleted file mode 100755 index a9eb585d..00000000 --- a/examples/adwords/v201509/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201509/basic_operations/update_ad_group.py b/examples/adwords/v201509/basic_operations/update_ad_group.py deleted file mode 100755 index e29956a6..00000000 --- a/examples/adwords/v201509/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201509') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/basic_operations/update_campaign.py b/examples/adwords/v201509/basic_operations/update_campaign.py deleted file mode 100755 index 8349d529..00000000 --- a/examples/adwords/v201509/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201509') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/basic_operations/update_keyword.py b/examples/adwords/v201509/basic_operations/update_keyword.py deleted file mode 100755 index da51cc46..00000000 --- a/examples/adwords/v201509/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201509/campaign_management/__init__.py b/examples/adwords/v201509/campaign_management/__init__.py deleted file mode 100644 index db098bda..00000000 --- a/examples/adwords/v201509/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201509/campaign_management/add_campaign_labels.py b/examples/adwords/v201509/campaign_management/add_campaign_labels.py deleted file mode 100755 index d40b5e38..00000000 --- a/examples/adwords/v201509/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201509') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index c4fb105f..00000000 --- a/examples/adwords/v201509/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,427 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201509') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201509') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding a TextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new TextAd for each of - the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', version='v201509') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201509/campaign_management/add_experiment.py b/examples/adwords/v201509/campaign_management/add_experiment.py deleted file mode 100755 index 1309216c..00000000 --- a/examples/adwords/v201509/campaign_management/add_experiment.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201509') - ad_group_service = client.GetService('AdGroupService', version='v201509') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py deleted file mode 100755 index c3f1058a..00000000 --- a/examples/adwords/v201509/campaign_management/add_keywords_in_bulk.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code sample illustrates how to perform asynchronous requests. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import random -import re -import time -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -KEYWORD_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201509') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add keywords. - for i in range(KEYWORD_NUMBER): - keyword = 'mars%d' % i - if random.randint(1, 10) == 1: - keyword += '!!!' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': keyword - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - keyword = operations[index]['operand']['criterion']['text'] - print ('ERROR - keyword \'%s\' failed due to \'%s\'' % - (keyword, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201509/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index f068e055..00000000 --- a/examples/adwords/v201509/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201509') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201509') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201509') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201509') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 0c2aa610..00000000 --- a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index b71b1763..00000000 --- a/examples/adwords/v201509/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 7f7293b7..00000000 --- a/examples/adwords/v201509/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201509') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201509/campaign_management/promote_experiment.py b/examples/adwords/v201509/campaign_management/promote_experiment.py deleted file mode 100755 index 7791f05a..00000000 --- a/examples/adwords/v201509/campaign_management/promote_experiment.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201509') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201509/campaign_management/set_ad_parameters.py b/examples/adwords/v201509/campaign_management/set_ad_parameters.py deleted file mode 100755 index 0bb56840..00000000 --- a/examples/adwords/v201509/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright 2015 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - ad_param_service = client.GetService('AdParamService', version='v201509') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index a7ceb5d5..00000000 --- a/examples/adwords/v201509/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201509') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201509/campaign_management/validate_text_ad.py b/examples/adwords/v201509/campaign_management/validate_text_ad.py deleted file mode 100755 index 6def1840..00000000 --- a/examples/adwords/v201509/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/error_handling/__init__.py b/examples/adwords/v201509/error_handling/__init__.py deleted file mode 100644 index b5203c57..00000000 --- a/examples/adwords/v201509/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201509/error_handling/handle_partial_failures.py b/examples/adwords/v201509/error_handling/handle_partial_failures.py deleted file mode 100755 index 4f5a3ba9..00000000 --- a/examples/adwords/v201509/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/error_handling/handle_policy_violation_error.py b/examples/adwords/v201509/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 2a467150..00000000 --- a/examples/adwords/v201509/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201509') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - operation = operations[int(operation_index[0])] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) - else: - # Non-policy error returned, re-throw exception. - raise e - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/extensions/__init__.py b/examples/adwords/v201509/extensions/__init__.py deleted file mode 100644 index b4d63e00..00000000 --- a/examples/adwords/v201509/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201509/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201509/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 2b0e1fdf..00000000 --- a/examples/adwords/v201509/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201509').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201509') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201509/extensions/add_site_links.py b/examples/adwords/v201509/extensions/add_site_links.py deleted file mode 100755 index 65bfeff0..00000000 --- a/examples/adwords/v201509/extensions/add_site_links.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201509') - customer_service = client.GetService('CustomerService', version='v201509') - - customer_tz = timezone(customer_service.get()['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt) - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'} - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/extensions/add_site_links_using_feeds.py b/examples/adwords/v201509/extensions/add_site_links_using_feeds.py deleted file mode 100755 index b89254ef..00000000 --- a/examples/adwords/v201509/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,233 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201509') - feed_item_service = client.GetService('FeedItemService', version='v201509') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201509') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201509') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/migration/__init__.py b/examples/adwords/v201509/migration/__init__.py deleted file mode 100644 index 5de8ecca..00000000 --- a/examples/adwords/v201509/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201509/migration/migrate_to_extension_settings.py b/examples/adwords/v201509/migration/migrate_to_extension_settings.py deleted file mode 100755 index 89a849e8..00000000 --- a/examples/adwords/v201509/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201509') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201509') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201509') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201509') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201509') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201509') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201509') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/migration/upgrade_ad_url.py b/examples/adwords/v201509/migration/upgrade_ad_url.py deleted file mode 100755 index ba94f2b6..00000000 --- a/examples/adwords/v201509/migration/upgrade_ad_url.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 upgrades an ad to use upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, adgroup_id, ad_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201509') - - selector = { - 'fields': ['Id', 'Url'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [ad_id] - } - ] - } - - page = adgroup_ad_service.get(selector) - - adgroup_ad = page['entries'][0] if page['entries'] else None - - if not adgroup_ad: - raise errors.GoogleAdsError('Ad not found.') - - ad_url_upgrade = { - 'adId': adgroup_ad['ad']['id'], - 'finalUrl': adgroup_ad['ad']['url'] - } - - adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] - - if adgroup_ad: - print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' - % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201509/misc/__init__.py b/examples/adwords/v201509/misc/__init__.py deleted file mode 100644 index 30d42e87..00000000 --- a/examples/adwords/v201509/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201509/misc/get_all_images_and_videos.py b/examples/adwords/v201509/misc/get_all_images_and_videos.py deleted file mode 100755 index ff93a94c..00000000 --- a/examples/adwords/v201509/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201509') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/misc/upload_image.py b/examples/adwords/v201509/misc/upload_image.py deleted file mode 100755 index fd9cd12a..00000000 --- a/examples/adwords/v201509/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201509') - - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201509/misc/upload_media_bundle.py b/examples/adwords/v201509/misc/upload_media_bundle.py deleted file mode 100755 index 9c7754f9..00000000 --- a/examples/adwords/v201509/misc/upload_media_bundle.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201509') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/optimization/__init__.py b/examples/adwords/v201509/optimization/__init__.py deleted file mode 100644 index 2e0ca689..00000000 --- a/examples/adwords/v201509/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py b/examples/adwords/v201509/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 12fdd5f8..00000000 --- a/examples/adwords/v201509/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201509') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - selector = { - 'campaignEstimateRequests': [{ - 'adGroupEstimateRequests': [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }], - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ] - }] - } - estimates = traffic_estimator_service.get(selector) - - # Display results. - ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] - keyword_estimates = ad_group_estimate['keywordEstimates'] - for index in xrange(len(keyword_estimates)): - keyword = keyword_estimate_requests[index]['keyword'] - estimate = keyword_estimates[index] - if keyword_estimate_requests[index].get('isNegative', False): - continue - - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(estimate['min']['averageCpc']['microAmount'], - estimate['max']['averageCpc']['microAmount']) - if 'averageCpc' in estimate['min'] else 'N/A') - mean_avg_pos = _CalculateMean(estimate['min']['averagePosition'], - estimate['max']['averagePosition']) - mean_clicks = _CalculateMean(estimate['min']['clicksPerDay'], - estimate['max']['clicksPerDay']) - mean_total_cost = _CalculateMean( - estimate['min']['totalCost']['microAmount'], - estimate['max']['totalCost']['microAmount']) - - print ('Results for the keyword with text \'%s\' and match type \'%s\':' - % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return None - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index 4ad9cb18..00000000 --- a/examples/adwords/v201509/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201509') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201509/optimization/get_keyword_ideas.py b/examples/adwords/v201509/optimization/get_keyword_ideas.py deleted file mode 100755 index fb2f5492..00000000 --- a/examples/adwords/v201509/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201509') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/remarketing/__init__.py b/examples/adwords/v201509/remarketing/__init__.py deleted file mode 100644 index b39776a8..00000000 --- a/examples/adwords/v201509/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201509/remarketing/add_audience.py b/examples/adwords/v201509/remarketing/add_audience.py deleted file mode 100755 index 0780d450..00000000 --- a/examples/adwords/v201509/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201509') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201509') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/remarketing/add_conversion_tracker.py b/examples/adwords/v201509/remarketing/add_conversion_tracker.py deleted file mode 100755 index adb733af..00000000 --- a/examples/adwords/v201509/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201509') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'markupLanguage': 'HTML', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/remarketing/add_crm_based_user_list.py b/examples/adwords/v201509/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 49a56586..00000000 --- a/examples/adwords/v201509/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - - -"""Adds a remarketing user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client, emails): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201509') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180, - # This field is optional. It links to a service you created that allows - # members of this list to remove themselves. - 'optOutLink': 'http://endpoint1.example.com/optout' - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. - - Args: - emails: list of str emails to be hashed. - - Returns: - A list of SHA-256 hashed emails. - """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] - - -if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) diff --git a/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 4e338fd0..00000000 --- a/examples/adwords/v201509/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201509') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/reporting/__init__.py b/examples/adwords/v201509/reporting/__init__.py deleted file mode 100644 index 85eee62f..00000000 --- a/examples/adwords/v201509/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201509/reporting/download_criteria_report.py b/examples/adwords/v201509/reporting/download_criteria_report.py deleted file mode 100755 index 5702ba94..00000000 --- a/examples/adwords/v201509/reporting/download_criteria_report.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201509') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index b43319f8..00000000 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201509') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 1092d2d5..00000000 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201509') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_string.py b/examples/adwords/v201509/reporting/download_criteria_report_as_string.py deleted file mode 100755 index 2bdb2cc9..00000000 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201509') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index e2f4e476..00000000 --- a/examples/adwords/v201509/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201509') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index ae40ab08..00000000 --- a/examples/adwords/v201509/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201509') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=False) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201509/reporting/get_report_fields.py b/examples/adwords/v201509/reporting/get_report_fields.py deleted file mode 100755 index d59f4c65..00000000 --- a/examples/adwords/v201509/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201509') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201509/shopping/__init__.py b/examples/adwords/v201509/shopping/__init__.py deleted file mode 100644 index 96422728..00000000 --- a/examples/adwords/v201509/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201509/shopping/add_product_partition_tree.py b/examples/adwords/v201509/shopping/add_product_partition_tree.py deleted file mode 100755 index 32b74a0d..00000000 --- a/examples/adwords/v201509/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201509/shopping/add_product_scope.py b/examples/adwords/v201509/shopping/add_product_scope.py deleted file mode 100755 index c5d86ec6..00000000 --- a/examples/adwords/v201509/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201509') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201509/shopping/add_shopping_campaign.py b/examples/adwords/v201509/shopping/add_shopping_campaign.py deleted file mode 100755 index f8500d2b..00000000 --- a/examples/adwords/v201509/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201509') - ad_group_service = client.GetService('AdGroupService', version='v201509') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201509') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set shared budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201509/shopping/get_product_category_taxonomy.py b/examples/adwords/v201509/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 6a3c112f..00000000 --- a/examples/adwords/v201509/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201509') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/targeting/__init__.py b/examples/adwords/v201509/targeting/__init__.py deleted file mode 100644 index 2c027ccc..00000000 --- a/examples/adwords/v201509/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2015 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index a51eb83d..00000000 --- a/examples/adwords/v201509/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201509') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - florida_downtown = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'PlacesOfInterestOperand', - # Other valid options: AIRPORT, UNIVERSITY. - 'category': 'DOWNTOWN', - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - } - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish, florida_tier3, - florida_downtown] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 723ccd84..00000000 --- a/examples/adwords/v201509/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201509') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 277d1e55..00000000 --- a/examples/adwords/v201509/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201509') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index 6878f09f..00000000 --- a/examples/adwords/v201509/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201509') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201509/targeting/lookup_location.py b/examples/adwords/v201509/targeting/lookup_location.py deleted file mode 100755 index d4df2d7c..00000000 --- a/examples/adwords/v201509/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201509') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/reporting/parallel_report_download.py b/examples/adwords/v201601/reporting/parallel_report_download.py new file mode 100755 index 00000000..65ea88fe --- /dev/null +++ b/examples/adwords/v201601/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201601') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201601') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201603/reporting/parallel_report_download.py b/examples/adwords/v201603/reporting/parallel_report_download.py new file mode 100755 index 00000000..431c81bd --- /dev/null +++ b/examples/adwords/v201603/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201603') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201603') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py index c72d4e3c..a81be943 100755 --- a/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py @@ -60,7 +60,7 @@ def main(client, ad_group_id): 'adGroupId': ad_group_id, 'ad': { 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': image, + 'marketingImage': {'mediaId': image['mediaId']}, 'shortHeadline': 'Travel', 'longHeadline': 'Travel the World', 'description': 'Take to the air!', diff --git a/examples/adwords/v201605/reporting/parallel_report_download.py b/examples/adwords/v201605/reporting/parallel_report_download.py new file mode 100755 index 00000000..a7ec117a --- /dev/null +++ b/examples/adwords/v201605/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201605') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201605') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/dfp/v201605/content_service/get_content_by_category.py b/examples/dfp/v201605/content_service/get_content_by_category.py deleted file mode 100755 index b8f3c805..00000000 --- a/examples/dfp/v201605/content_service/get_content_by_category.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active content categorized as a "comedy" using the -network's content browse custom targeting key. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201605') - network_service = client.GetService('NetworkService', version='v201605') - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') - - # Get the network's content browse custom targeting key. - network = network_service.getCurrentNetwork() - key_id = network['contentBrowseCustomTargetingKeyId'] - - # Create a statement to select the categories matching the name comedy. - values = [ - { - 'key': 'contentBrowseCustomTargetingKeyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }, - { - 'key': 'category', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'comedy' - } - } - ] - category_filter_query = ('WHERE customTargetingKeyId = ' - ':contentBrowseCustomTargetingKeyId and name = ' - ':category') - category_filter_statement = dfp.FilterStatement( - category_filter_query, values, 1) - - # Get categories matching the filter statement. - response = custom_targeting_service.getCustomTargetingValuesByStatement( - category_filter_statement.ToStatement()) - - # Get the custom targeting value ID for the comedy category. - if 'results' in response: - category_custom_targeting_value_id = (response['results']['id']) - - # Create a statement to select the active content. - content_values = [ - { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - } - ] - content_query = 'WHERE status = :status' - content_statement = dfp.FilterStatement(content_query, content_values) - - while True: - # Get the content by statement and custom targeting value. - response = content_service.getContentByStatementAndCustomTargetingValue( - content_statement.ToStatement(), - category_custom_targeting_value_id) - if 'results' in response: - # Display results. - for content_item in response['results']: - print ('Content with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (content_item['id'], content_item['name'], - content_item['status'])) - content_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/googleads.yaml b/googleads.yaml index 64d7985a..3ea0285d 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -80,3 +80,8 @@ dfp: # The following values are optional: # username: INSERT_USERNAME_HERE # password: INSERT_PASSWORD_HERE + + +# Optional: By default, the library will include utilities used in the user +# agent. +# include_utilities_in_user_agent: True diff --git a/googleads/adwords.py b/googleads/adwords.py index 64606c3e..35fed0ad 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -36,49 +36,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201509': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'BatchJobService': 'cm', - 'BudgetOrderService': 'billing', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LocationCriterionService': 'cm', - 'MediaService': 'cm', - 'MutateJobService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'ManagedCustomerService': 'mcm', - 'CustomerService': 'mcm', - 'CustomerFeedService': 'cm', - 'BudgetService': 'cm', - 'BiddingStrategyService': 'cm', - 'AdwordsUserListService': 'rm', - 'LabelService': 'cm', - }, 'v201601': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', @@ -217,7 +174,8 @@ } # Supported kwargs for params sent in the report header. -_REPORT_HEADER_KWARGS = {'include_zero_impressions': 'includeZeroImpressions', +_REPORT_HEADER_KWARGS = {'client_customer_id': 'clientCustomerId', + 'include_zero_impressions': 'includeZeroImpressions', 'skip_report_header': 'skipReportHeader', 'skip_column_header': 'skipColumnHeader', 'skip_report_summary': 'skipReportSummary', @@ -479,6 +437,8 @@ def GetReportDownloadHeaders(self, **kwargs): **kwargs: Optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set by the AdWordsClient. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row @@ -500,7 +460,8 @@ def GetReportDownloadHeaders(self, **kwargs): headers.update({ 'Content-type': self._CONTENT_TYPE, 'developerToken': str(self._adwords_client.developer_token), - 'clientCustomerId': str(self._adwords_client.client_customer_id), + 'clientCustomerId': str(kwargs.get( + 'client_customer_id', self._adwords_client.client_customer_id)), 'User-Agent': ''.join([self._adwords_client.user_agent, self._LIB_SIG, ',gzip']) }) @@ -519,6 +480,7 @@ def GetReportDownloadHeaders(self, **kwargs): return headers +@googleads.common.RegisterUtility('BatchJobHelper') class BatchJobHelper(object): """A utility that simplifies working with the BatchJobService.""" @@ -1071,6 +1033,13 @@ def UploadOperations(self, operations, is_last=False): self._is_last = is_last +@googleads.common.RegisterUtility( + 'ReportDownloader', {'DownloadReport': 'File', + 'DownloadReportWithAwql': 'File', + 'DownloadReportAsStream': 'Stream', + 'DownloadReportAsStreamWithAwql': 'Stream', + 'DownloadReportAsString': 'String', + 'DownloadReportAsStringWithAwql': 'String'}) class ReportDownloader(object): """A utility that can be used to download reports from AdWords.""" @@ -1144,6 +1113,8 @@ def DownloadReport(self, report_definition, output=sys.stdout, **kwargs): **kwargs: Optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set for the client. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row @@ -1182,6 +1153,8 @@ def DownloadReportAsStream(self, report_definition, **kwargs): **kwargs: Optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set for the client. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row @@ -1224,6 +1197,8 @@ def DownloadReportAsStreamWithAwql(self, query, file_format, **kwargs): **kwargs: Optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set for the client. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row @@ -1264,6 +1239,8 @@ def DownloadReportAsString(self, report_definition, **kwargs): **kwargs: Optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set for the client. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row @@ -1312,6 +1289,8 @@ def DownloadReportAsStringWithAwql(self, query, file_format, **kwargs): **kwargs: Optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set for the client. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row @@ -1365,6 +1344,8 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, **kwargs: Optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set for the client. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row @@ -1402,6 +1383,8 @@ def _DownloadReport(self, post_body, output, **kwargs): **kwargs: A dictionary containing optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set for the client. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row @@ -1444,6 +1427,8 @@ def _DownloadReportAsStream(self, post_body, **kwargs): **kwargs: Optional keyword arguments. Keyword Arguments: + client_customer_id: A string containing a client_customer_id intended to + override the default value set for the client. include_zero_impressions: A boolean indicating whether the report should show rows with zero impressions. skip_report_header: A boolean indicating whether to include a header row diff --git a/googleads/common.py b/googleads/common.py index c2ad9970..e611e512 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -15,9 +15,12 @@ """Common client library functions and classes used by all products.""" +from functools import wraps +import inspect import os import ssl import sys +import threading import urllib2 import warnings @@ -29,7 +32,7 @@ import googleads.errors import googleads.oauth2 -import googleads.patches +import googleads.util try: import urllib2.HTTPSHandler @@ -39,7 +42,7 @@ # not have certificate validation performed until they update. pass -VERSION = '4.1.0' +VERSION = '4.2.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' @@ -58,8 +61,13 @@ # instance. _PROXY_KEYS = ('host', 'port') +# Global variables used to enable and store utility usage stats. +_utility_registry = googleads.util.UtilityRegistry() +_UTILITY_REGISTER_YAML_KEY = 'include_utilities_in_user_agent' +_UTILITY_LOCK = threading.Lock() + # Apply any necessary patches to dependency libraries. -googleads.patches.Apply() +googleads.util.PatchHelper().Apply() def GenerateLibSig(short_name): @@ -70,7 +78,15 @@ def GenerateLibSig(short_name): Returns: A library signature string to append to user-supplied user-agent value. """ - return ' (%s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION) + with _UTILITY_LOCK: + utilities_used = ', '.join([utility for utility in _utility_registry]) + _utility_registry.Clear() + + if utilities_used: + return ' (%s, %s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION, + utilities_used) + else: + return ' (%s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION) def LoadFromStorage(path, product_yaml_key, required_client_values, @@ -115,6 +131,8 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, 'Given yaml file, %s, does not contain a "%s" configuration.' % (path, product_yaml_key)) + IncludeUtilitiesInUserAgent(data.get(_UTILITY_REGISTER_YAML_KEY, True)) + original_keys = list(product_data.keys()) client_kwargs = {} try: @@ -319,13 +337,13 @@ def _PackForSuds(obj, factory): def _RecurseOverObject(obj, factory, parent=None): """Recurses over a nested structure to look for changes in Suds objects. - Args: - obj: A parameter for a SOAP request field which is to be inspected and - will be packed for Suds if an xsi_type is specified, otherwise will be - left unaltered. - factory: The suds.client.Factory object which can create instances of the - classes generated from the WSDL. - parent: The parent object that contains the obj parameter to be inspected. + Args: + obj: A parameter for a SOAP request field which is to be inspected and + will be packed for Suds if an xsi_type is specified, otherwise will be + left unaltered. + factory: The suds.client.Factory object which can create instances of the + classes generated from the WSDL. + parent: The parent object that contains the obj parameter to be inspected. """ if _IsSudsIterable(obj): # Since in-place modification of the Suds object is taking place, the @@ -347,6 +365,60 @@ def _IsSudsIterable(obj): return (obj and not isinstance(obj, basestring) and hasattr(obj, '__iter__')) +def IncludeUtilitiesInUserAgent(value): + """Configures the logging of utilities in the User-Agent. + + Args: + value: a bool indicating that you want to include utility names in the + User-Agent if set True, otherwise, these will not be added. + """ + with _UTILITY_LOCK: + _utility_registry.SetEnabled(value) + + +def RegisterUtility(utility_name, version_mapping=None): + """Decorator that registers a class with the given utility name. + + This will only register the utilities being used if the UtilityRegistry is + enabled. Note that only the utility class's public methods will cause the + utility name to be added to the registry. + + Args: + utility_name: A str specifying the utility name associated with the class. + version_mapping: A dict containing optional version strings to append to the + utility string for individual methods; where the key is the method name and + the value is the text to be appended as the version. + + Returns: + The decorated class. + """ + def MethodDecorator(utility_method, version): + """Decorates a method in the utility class.""" + registry_name = ('%s/%s' % (utility_name, version) if version + else utility_name) + @wraps(utility_method) + def Wrapper(*args, **kwargs): + with _UTILITY_LOCK: + _utility_registry.Add(registry_name) + return utility_method(*args, **kwargs) + return Wrapper + + def ClassDecorator(cls): + """Decorates a utility class.""" + for name, method in inspect.getmembers(cls, inspect.ismethod): + # Public methods of the class will have the decorator applied. + if not name.startswith('_'): + # The decorator will only be applied to unbound methods; this prevents + # it from clobbering class methods. If the attribute doesn't exist, set + # None for PY3 compatibility. + if not getattr(method, '__self__', None): + setattr(cls, name, MethodDecorator( + method, version_mapping.get(name) if version_mapping else None)) + return cls + + return ClassDecorator + + class ProxyConfig(object): """A utility for configuring the usage of a proxy.""" @@ -423,7 +495,7 @@ def GetHandlers(self): handlers = [] if self._ssl_context: - handlers.append(urllib2.HTTPSHandler(self._ssl_context)) + handlers.append(urllib2.HTTPSHandler(context=self._ssl_context)) if self._proxy_option: handlers.append(urllib2.ProxyHandler(self._proxy_option)) diff --git a/googleads/oauth2.py b/googleads/oauth2.py index a425fcba..b98a0773 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -199,7 +199,8 @@ def __init__(self, scope, client_email, key_file, client_email, private_key, scope, private_key_password=private_key_password, user_agent=self._USER_AGENT, token_uri=self._GOOGLE_OAUTH2_ENDPOINT, sub=sub) - self.proxy_config = proxy_config + self.proxy_config = (proxy_config if proxy_config else + googleads.common.ProxyConfig()) self.Refresh() def CreateHttpHeader(self): diff --git a/googleads/patches.py b/googleads/patches.py deleted file mode 100644 index eb512f18..00000000 --- a/googleads/patches.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright 2016 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. - -"""Patches applied by the Google Ads Client Library.""" - -import suds - - -def Apply(): - """Apply patches used by the Google Ads Client Library.""" - _ApplySudsJurkoAppenderPatch() - - -def _ApplySudsJurkoAppenderPatch(): - """Appends a Monkey Patch to the suds.mx.appender module. - - This resolves an issue where empty objects are ignored and stripped from the - request output. More details can be found on the suds-jurko issue tracker: - https://bitbucket.org/jurko/suds/issues/81/suds-should-support-an-empty-object - """ - def PatchedAppend(self, parent, content): - obj = content.value - child = self.node(content) - parent.append(child) - for item in obj: - cont = suds.mx.Content(tag=item[0], value=item[1]) - suds.mx.appender.Appender.append(self, child, cont) - - suds.mx.appender.ObjectAppender.append = PatchedAppend diff --git a/googleads/util.py b/googleads/util.py new file mode 100644 index 00000000..3324a06c --- /dev/null +++ b/googleads/util.py @@ -0,0 +1,78 @@ +# Copyright 2016 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. + +"""Utilities used by the client library.""" + +import threading + +import suds + + +class PatchHelper(object): + """Utility that applies patches on behalf of the Google Ads Client Library.""" + + def Apply(self): + """Apply patches used by the Google Ads Client Library.""" + self._ApplySudsJurkoAppenderPatch() + + def _ApplySudsJurkoAppenderPatch(self): + """Appends a Monkey Patch to the suds.mx.appender module. + + This resolves an issue where empty objects are ignored and stripped from the + request output. More details can be found on the suds-jurko issue tracker: + https://goo.gl/uyYw0C + """ + def PatchedAppend(self, parent, content): + obj = content.value + child = self.node(content) + parent.append(child) + for item in obj: + cont = suds.mx.Content(tag=item[0], value=item[1]) + suds.mx.appender.Appender.append(self, child, cont) + + suds.mx.appender.ObjectAppender.append = PatchedAppend + + +class UtilityRegistry(object): + """Utility that registers product utilities used in generating a request.""" + + def __contains__(self, utility): + with self._lock: + return utility in self._registry + + def __init__(self): + self._enabled = True + self._registry = set() + self._lock = threading.Lock() + + def __iter__(self): + with self._lock: + return iter(self._registry.copy()) + + def __len__(self): + with self._lock: + return len(self._registry) + + def Add(self, obj): + with self._lock: + if self._enabled: + self._registry.add(obj) + + def Clear(self): + with self._lock: + self._registry.clear() + + def SetEnabled(self, value): + with self._lock: + self._enabled = value diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 8330b077..eb34b2fe 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -218,11 +218,12 @@ def testGetReportDownloadHeadersWithInvalidKeyword(self): self.header_handler.GetReportDownloadHeaders, invalid_key_word=True) def testGetReportDownloadHeadersWithKeywordArguments(self): - ccid = 'client customer id' + original_ccid = 'client customer id' + updated_ccid = 'updated client customer id' dev_token = 'developer token' user_agent = 'user agent!' oauth_header = {'Authorization': 'header'} - self.aw_client.client_customer_id = ccid + self.aw_client.client_customer_id = original_ccid self.aw_client.developer_token = dev_token self.aw_client.user_agent = user_agent self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( @@ -230,7 +231,7 @@ def testGetReportDownloadHeadersWithKeywordArguments(self): expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', 'developerToken': dev_token, - 'clientCustomerId': ccid, + 'clientCustomerId': updated_ccid, 'Authorization': 'header', 'User-Agent': ''.join([ user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, @@ -250,7 +251,8 @@ def testGetReportDownloadHeadersWithKeywordArguments(self): skip_column_header=True, skip_report_summary=True, include_zero_impressions=True, - use_raw_enum_values=True)) + use_raw_enum_values=True, + client_customer_id=updated_ccid)) def testGetReportDownloadHeadersWithNoOptionalHeaders(self): ccid = 'client customer id' diff --git a/tests/common_test.py b/tests/common_test.py index 57169b4e..dc797a9e 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -11,6 +11,7 @@ # 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. + """Unit tests to cover the common module.""" @@ -51,6 +52,25 @@ def setUp(self): self.uplink_port = 999 self.username = 'username' self.password = 'password' + self.test1_name = 'Test1' + self.test2_name = 'Test2' + self.test2_version = 'testing' + + @googleads.common.RegisterUtility(self.test1_name) + class Test1(object): + + def test(self): + pass + + @googleads.common.RegisterUtility(self.test2_name, + {'test': self.test2_version}) + class Test2(object): + + def test(self): + pass + + self.test1 = Test1 + self.test2 = Test2 def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): """Return the filename of a yaml file created for testing.""" @@ -60,7 +80,7 @@ def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): for key in data: if key is insert_oauth2_key: data[key].update(oauth_dict) - yaml_handle.write(yaml.dump({key: data[key]})) + yaml_handle.write(yaml.dump(data)) return yaml_file.name @@ -302,6 +322,7 @@ def testLoadFromStorage(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'proxy_config': proxy_config.return_value}, rval) + self.assertTrue(googleads.common._utility_registry._enabled) # The optional key is present. yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e', @@ -321,6 +342,7 @@ def testLoadFromStorage(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'other': 'f', 'proxy_config': proxy_config.return_value}, rval) + self.assertTrue(googleads.common._utility_registry._enabled) def testLoadFromStorage_relativePath(self): fake_os = fake_filesystem.FakeOsModule(self.filesystem) @@ -346,6 +368,7 @@ def testLoadFromStorage_relativePath(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, 'needed': 'd', 'keys': 'e'}, rval) + self.assertTrue(googleads.common._utility_registry._enabled) def testLoadFromStorage_serviceAccount(self): dfp_scope = googleads.oauth2.GetAPIScope('dfp') @@ -370,6 +393,7 @@ def testLoadFromStorage_serviceAccount(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, 'needed': 'd', 'keys': 'e'}, rval) + self.assertTrue(googleads.common._utility_registry._enabled) # The optional key is present. yaml_fname = self._CreateYamlFile( @@ -392,6 +416,31 @@ def testLoadFromStorage_serviceAccount(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, 'needed': 'd', 'keys': 'e', 'other': 'f'}, rval) + self.assertTrue(googleads.common._utility_registry._enabled) + + + def testLoadFromStorage_utilityRegistryDisabled(self): + yaml_fname = self._CreateYamlFile( + {'one': {'needed': 'd', 'keys': 'e'}, + 'include_utilities_in_user_agent': False}, + 'one', self._OAUTH_INSTALLED_APP_DICT) + + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'one', ['needed', 'keys'], ['other']) + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', + 'proxy_config': proxy_config.return_value}, rval) + self.assertFalse(googleads.common._utility_registry._enabled) + def testLoadFromStorage_warningWithUnrecognizedKey(self): yaml_fname = self._CreateYamlFile( @@ -412,6 +461,7 @@ def testLoadFromStorage_warningWithUnrecognizedKey(self): 'Im': 'here', 'proxy_config': proxy_config.return_value }, rval) + self.assertTrue(googleads.common._utility_registry._enabled) self.assertEqual(len(captured_warnings), 1) def testGenerateLibSig(self): @@ -421,6 +471,55 @@ def testGenerateLibSig(self): googleads.common._PYTHON_VERSION), googleads.common.GenerateLibSig(my_name)) + def testGenerateLibSigWithUtilities(self): + my_name = 'Mark' + + t1 = self.test1() + t2 = self.test2() + + # The order of utilities in the generated library signature is not + # guaranteed, so verify that the string contains the same values instead. + # Make the first request using both utilities. + t1.test() + t2.test() + expected = set((my_name, googleads.common._COMMON_LIB_SIG, + googleads.common._PYTHON_VERSION, self.test1_name, + '%s/%s' % (self.test2_name, self.test2_version))) + generated = set(googleads.common.GenerateLibSig(my_name)[2:-1].split(', ')) + + self.assertEqual(expected, generated) + + # Make another request, this time no utilities. + expected = set((my_name, googleads.common._COMMON_LIB_SIG, + googleads.common._PYTHON_VERSION)) + generated = set(googleads.common.GenerateLibSig(my_name)[2:-1].split(', ')) + + self.assertEqual(expected, generated) + + # Make another request, this time one utility. + t1.test() + expected = set((my_name, googleads.common._COMMON_LIB_SIG, + googleads.common._PYTHON_VERSION, self.test1_name)) + generated = set(googleads.common.GenerateLibSig(my_name)[2:-1].split(', ')) + + self.assertEqual(expected, generated) + + + def testGenerateLibSigWithUtilitiesDisabled(self): + my_name = 'Mark' + + googleads.common.IncludeUtilitiesInUserAgent(False) + + t1 = self.test1() + t1.test() + t2 = self.test2() + t2.test() + + self.assertEqual( + ' (%s, %s, %s)' % (my_name, googleads.common._COMMON_LIB_SIG, + googleads.common._PYTHON_VERSION), + googleads.common.GenerateLibSig(my_name)) + def testPackForSuds(self): factory = mock.Mock() @@ -602,7 +701,8 @@ def testProxyConfigGetHandlersWithProxyAndSLLContext(self): proxy_handler.return_value]) proxy_handler.assert_called_once_with( {'https': '%s' % str(https_proxy)}) - urllib2.HTTPSHandler.assert_called_once_with(ssl_ctxt.return_value) + urllib2.HTTPSHandler.assert_called_once_with( + context=ssl_ctxt.return_value) def testProxyConfigWithNoProxy(self): proxy_config = googleads.common.ProxyConfig() diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index c3ca02a2..3bfe14c5 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -235,6 +235,18 @@ def testCreateHttpHeader_refreshFails(self): self.googleads_client.CreateHttpHeader) self.assertFalse(self.mock_oauth2_credentials.apply.called) + def testIssue123(self): + """Test that verifies the fix for Issue #123 on the GitHub Issue Tracker. + + See: https://github.com/googleads/googleads-python-lib/issues/123 + """ + with mock.patch('__builtin__.open'): + with mock.patch('oauth2client.client.SignedJwtAssertionCredentials', + self.oauth2_credentials): + googleads.oauth2.GoogleServiceAccountClient( + self.scope, self.service_account_email, '/dev/null', + self.private_key_password) + if __name__ == '__main__': unittest.main() diff --git a/tests/patches_test.py b/tests/util_test.py similarity index 98% rename from tests/patches_test.py rename to tests/util_test.py index 35bed860..375adc20 100644 --- a/tests/patches_test.py +++ b/tests/util_test.py @@ -22,11 +22,12 @@ import googleads.adwords import googleads.dfp +import googleads.util import mock class PatchesTest(unittest.TestCase): - """Tests for the googleads.patches module.""" + """Tests for the PatchHelper utility.""" def setUp(self): oauth_header = {'Authorization': 'header'} From 194d7ec0076679867a5d6d7660ae1a3e9ecf2712 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 17 Jun 2016 17:40:43 -0400 Subject: [PATCH 041/180] Commiting latest changes. From eea0abd58eb1dba79d9bdf04a5a07dd77ce32a6d Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 29 Jul 2016 17:05:34 -0400 Subject: [PATCH 042/180] AdWords v201607 Release --- ChangeLog | 3 + .../add_click_to_download_ad.py | 4 +- .../remarketing/add_crm_based_user_list.py | 2 +- .../add_click_to_download_ad.py | 4 +- .../remarketing/add_crm_based_user_list.py | 2 +- .../add_click_to_download_ad.py | 4 +- .../remarketing/add_crm_based_user_list.py | 2 +- examples/adwords/v201607/__init__.py | 15 + .../v201607/account_management/__init__.py | 15 + .../account_management/create_account.py | 63 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201607/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 222 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 126 +++++ .../advanced_operations/add_html5_ad.py | 111 ++++ .../add_responsive_display_ad.py | 91 +++ .../add_text_ad_with_upgraded_urls.py | 111 ++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201607/basic_operations/__init__.py | 15 + .../v201607/basic_operations/add_ad_groups.py | 115 ++++ .../v201607/basic_operations/add_campaigns.py | 125 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201607/basic_operations/add_keywords.py | 92 +++ .../v201607/basic_operations/add_text_ads.py | 93 ++++ .../v201607/basic_operations/get_ad_groups.py | 76 +++ .../v201607/basic_operations/get_campaigns.py | 74 +++ .../get_campaigns_with_awql.py | 64 +++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201607/basic_operations/get_keywords.py | 87 +++ .../v201607/basic_operations/get_text_ads.py | 80 +++ .../v201607/basic_operations/pause_ad.py | 61 ++ .../v201607/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 58 ++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201607/campaign_management/__init__.py | 15 + .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 426 ++++++++++++++ .../v201607/campaign_management/add_draft.py | 81 +++ .../campaign_management/add_experiment.py | 127 +++++ ...dd_keywords_using_incremental_batch_job.py | 259 +++++++++ .../v201607/campaign_management/add_trial.py | 117 ++++ .../get_all_disapproved_ads.py | 74 +++ .../get_all_disapproved_ads_with_awql.py | 63 +++ .../get_campaigns_by_label.py | 85 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/promote_experiment.py | 60 ++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201607/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 120 ++++ .../handle_policy_violation_error.py | 114 ++++ .../adwords/v201607/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../adwords/v201607/extensions/add_prices.py | 144 +++++ .../v201607/extensions/add_site_links.py | 146 +++++ .../extensions/add_site_links_using_feeds.py | 236 ++++++++ .../adwords/v201607/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 527 ++++++++++++++++++ .../v201607/migration/upgrade_ad_url.py | 79 +++ examples/adwords/v201607/misc/__init__.py | 15 + .../v201607/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201607/misc/upload_image.py | 66 +++ .../v201607/misc/upload_media_bundle.py | 59 ++ .../adwords/v201607/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 180 ++++++ ...aign_criterion_bid_modifier_simulations.py | 96 ++++ .../get_keyword_bid_simulations.py | 81 +++ .../v201607/optimization/get_keyword_ideas.py | 100 ++++ .../adwords/v201607/remarketing/__init__.py | 15 + .../v201607/remarketing/add_audience.py | 103 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_crm_based_user_list.py | 94 ++++ .../remarketing/add_rule_based_user_lists.py | 183 ++++++ .../remarketing/upload_offline_conversions.py | 75 +++ .../adwords/v201607/reporting/__init__.py | 15 + .../reporting/download_criteria_report.py | 61 ++ .../download_criteria_report_as_stream.py | 77 +++ ...oad_criteria_report_as_stream_with_awql.py | 81 +++ .../download_criteria_report_as_string.py | 59 ++ ...oad_criteria_report_as_string_with_awql.py | 55 ++ .../download_criteria_report_with_awql.py | 58 ++ .../v201607/reporting/get_report_fields.py | 52 ++ .../reporting/parallel_report_download.py | 230 ++++++++ examples/adwords/v201607/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 281 ++++++++++ .../v201607/shopping/add_product_scope.py | 104 ++++ .../v201607/shopping/add_shopping_campaign.py | 121 ++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201607/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 145 +++++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201607/targeting/lookup_location.py | 82 +++ googleads/adwords.py | 52 +- googleads/common.py | 3 +- 106 files changed, 9433 insertions(+), 12 deletions(-) create mode 100644 examples/adwords/v201607/__init__.py create mode 100644 examples/adwords/v201607/account_management/__init__.py create mode 100755 examples/adwords/v201607/account_management/create_account.py create mode 100755 examples/adwords/v201607/account_management/get_account_changes.py create mode 100755 examples/adwords/v201607/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201607/advanced_operations/__init__.py create mode 100755 examples/adwords/v201607/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201607/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201607/basic_operations/__init__.py create mode 100755 examples/adwords/v201607/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201607/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201607/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201607/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201607/basic_operations/add_text_ads.py create mode 100755 examples/adwords/v201607/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201607/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201607/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201607/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201607/basic_operations/get_text_ads.py create mode 100755 examples/adwords/v201607/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201607/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201607/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201607/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201607/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201607/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201607/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201607/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201607/campaign_management/__init__.py create mode 100755 examples/adwords/v201607/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201607/campaign_management/add_draft.py create mode 100755 examples/adwords/v201607/campaign_management/add_experiment.py create mode 100755 examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201607/campaign_management/add_trial.py create mode 100755 examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201607/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201607/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201607/campaign_management/promote_experiment.py create mode 100755 examples/adwords/v201607/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201607/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201607/error_handling/__init__.py create mode 100755 examples/adwords/v201607/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201607/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201607/extensions/__init__.py create mode 100755 examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201607/extensions/add_prices.py create mode 100755 examples/adwords/v201607/extensions/add_site_links.py create mode 100755 examples/adwords/v201607/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201607/migration/__init__.py create mode 100755 examples/adwords/v201607/migration/migrate_to_extension_settings.py create mode 100755 examples/adwords/v201607/migration/upgrade_ad_url.py create mode 100644 examples/adwords/v201607/misc/__init__.py create mode 100755 examples/adwords/v201607/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201607/misc/upload_image.py create mode 100755 examples/adwords/v201607/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201607/optimization/__init__.py create mode 100755 examples/adwords/v201607/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201607/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201607/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201607/remarketing/__init__.py create mode 100755 examples/adwords/v201607/remarketing/add_audience.py create mode 100755 examples/adwords/v201607/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201607/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201607/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201607/remarketing/upload_offline_conversions.py create mode 100644 examples/adwords/v201607/reporting/__init__.py create mode 100755 examples/adwords/v201607/reporting/download_criteria_report.py create mode 100755 examples/adwords/v201607/reporting/download_criteria_report_as_stream.py create mode 100755 examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201607/reporting/download_criteria_report_as_string.py create mode 100755 examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201607/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201607/reporting/get_report_fields.py create mode 100755 examples/adwords/v201607/reporting/parallel_report_download.py create mode 100644 examples/adwords/v201607/shopping/__init__.py create mode 100755 examples/adwords/v201607/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201607/shopping/add_product_scope.py create mode 100755 examples/adwords/v201607/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201607/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201607/targeting/__init__.py create mode 100755 examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201607/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 5dfe9af0..fe1d1e76 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +4.3.0 -- 7/29/2016 +* Added support for AdWords v201607. + 4.2.0 -- 6/13/2016 * Removed support and examples for AdWords v201509. * The AdWords ReportDownloader now accepts a "client_customer_id" keyword diff --git a/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py index 733fa7d4..61c91b3e 100755 --- a/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py @@ -96,8 +96,8 @@ def main(client, ad_group_id): # Display results. if 'value' in ads: for ad in ads['value']: - print ('Added new click-to-download ad to ad group ID \'%s\' ' - 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) else: print 'No ads were added.' diff --git a/examples/adwords/v201601/remarketing/add_crm_based_user_list.py b/examples/adwords/v201601/remarketing/add_crm_based_user_list.py index 5b4f9df2..98c226aa 100755 --- a/examples/adwords/v201601/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201601/remarketing/add_crm_based_user_list.py @@ -15,7 +15,7 @@ # limitations under the License. -"""Adds a remarketing user list and populates it with hashed email addresses. +"""Adds a user list and populates it with hashed email addresses. Note: It may take several hours for the list to be populated with members. Email addresses must be associated with a Google account. For privacy purposes, the diff --git a/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py index 97605a74..face8aaf 100755 --- a/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py @@ -96,8 +96,8 @@ def main(client, ad_group_id): # Display results. if 'value' in ads: for ad in ads['value']: - print ('Added new click-to-download ad to ad group ID \'%s\' ' - 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) else: print 'No ads were added.' diff --git a/examples/adwords/v201603/remarketing/add_crm_based_user_list.py b/examples/adwords/v201603/remarketing/add_crm_based_user_list.py index 181ee4e2..de51346c 100755 --- a/examples/adwords/v201603/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201603/remarketing/add_crm_based_user_list.py @@ -15,7 +15,7 @@ # limitations under the License. -"""Adds a remarketing user list and populates it with hashed email addresses. +"""Adds a user list and populates it with hashed email addresses. Note: It may take several hours for the list to be populated with members. Email addresses must be associated with a Google account. For privacy purposes, the diff --git a/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py index d23b1f83..3c4be5be 100755 --- a/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py @@ -96,8 +96,8 @@ def main(client, ad_group_id): # Display results. if 'value' in ads: for ad in ads['value']: - print ('Added new click-to-download ad to ad group ID \'%s\' ' - 'with URL \'%s\'.' % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) else: print 'No ads were added.' diff --git a/examples/adwords/v201605/remarketing/add_crm_based_user_list.py b/examples/adwords/v201605/remarketing/add_crm_based_user_list.py index 30935a69..107969eb 100755 --- a/examples/adwords/v201605/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201605/remarketing/add_crm_based_user_list.py @@ -15,7 +15,7 @@ # limitations under the License. -"""Adds a remarketing user list and populates it with hashed email addresses. +"""Adds a user list and populates it with hashed email addresses. Note: It may take several hours for the list to be populated with members. Email addresses must be associated with a Google account. For privacy purposes, the diff --git a/examples/adwords/v201607/__init__.py b/examples/adwords/v201607/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201607/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201607/account_management/__init__.py b/examples/adwords/v201607/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201607/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201607/account_management/create_account.py b/examples/adwords/v201607/account_management/create_account.py new file mode 100755 index 00000000..25faa91d --- /dev/null +++ b/examples/adwords/v201607/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201607') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/account_management/get_account_changes.py b/examples/adwords/v201607/account_management/get_account_changes.py new file mode 100755 index 00000000..6ba4174e --- /dev/null +++ b/examples/adwords/v201607/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201607') + campaign_service = client.GetService('CampaignService', version='v201607') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/account_management/get_account_hierarchy.py b/examples/adwords/v201607/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..3b6b2e33 --- /dev/null +++ b/examples/adwords/v201607/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201607') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/advanced_operations/__init__.py b/examples/adwords/v201607/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..4f5a84f9 --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py @@ -0,0 +1,222 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates TextAds that use ad customizations for the specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add TextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no TextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService') + + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'description1': 'Only {=%s.Price}' % feed_name, + 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com' + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..25f0877e --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201607') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..7ad07397 --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,126 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Optionally, you may specify a landscape image. The image needs to be in a + # BASE64 encoded form. Here we download a demo image and encode it for this + # ad. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + }, + { + 'name': 'landscapeImage', + 'field_media': { + 'xsi_type': 'Image', + 'data': image_data + }, + 'type': 'IMAGE' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/advanced_operations/add_html5_ad.py b/examples/adwords/v201607/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..4af60d30 --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/add_html5_ad.py @@ -0,0 +1,111 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..ee4eea91 --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + media_service = client.GetService('MediaService', version='v201607') + + try: + # Create image. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + # Make the upload request + image = media_service.upload(image)[0] + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'] + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..c87bb167 --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -0,0 +1,111 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a text add that uses advanced features of upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Create the text ad + text_ad = { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print ('AdGroupAd with ID %s and display URL \'%s\'was added.' + % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..8d46d8ce --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201607') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201607') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201607') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..cf24c855 --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201607') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201607') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..d5f847f4 --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201607') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..00e5f08f --- /dev/null +++ b/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201607') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201607') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201607') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201607/basic_operations/__init__.py b/examples/adwords/v201607/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201607/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201607/basic_operations/add_ad_groups.py b/examples/adwords/v201607/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..2839ac7f --- /dev/null +++ b/examples/adwords/v201607/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201607') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/basic_operations/add_campaigns.py b/examples/adwords/v201607/basic_operations/add_campaigns.py new file mode 100755 index 00000000..3df426bb --- /dev/null +++ b/examples/adwords/v201607/basic_operations/add_campaigns.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201607') + budget_service = client.GetService('BudgetService', version='v201607') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..02c127de --- /dev/null +++ b/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/add_keywords.py b/examples/adwords/v201607/basic_operations/add_keywords.py new file mode 100755 index 00000000..37f8e7f0 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201607') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/add_text_ads.py b/examples/adwords/v201607/basic_operations/add_text_ads.py new file mode 100755 index 00000000..55e39292 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/add_text_ads.py @@ -0,0 +1,93 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds several text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Construct operations and add ads. + # If needed, you could specify an exemption request here, e.g.: + # 'exemptionRequests': [{ + # # This comes back in a PolicyViolationError. + # 'key' { + # 'policyName': '...', + # 'violatingText': '...' + # } + # }] + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + }, + # Optional fields. + 'status': 'PAUSED' + } + }, + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Enjoy your stay at Red Planet.', + 'description2': 'Buy your tickets now!', + 'headline': 'Luxury Cruise to Mars' + } + } + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad with id \'%s\' and of type \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/get_ad_groups.py b/examples/adwords/v201607/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..aeda14ef --- /dev/null +++ b/examples/adwords/v201607/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201607') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/basic_operations/get_campaigns.py b/examples/adwords/v201607/basic_operations/get_campaigns.py new file mode 100755 index 00000000..894e5b18 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/get_campaigns.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201607') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..94efbdcf --- /dev/null +++ b/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201607') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..2ae1d940 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an ad, run add_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/get_keywords.py b/examples/adwords/v201607/basic_operations/get_keywords.py new file mode 100755 index 00000000..4c38359c --- /dev/null +++ b/examples/adwords/v201607/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201607') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\' was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/get_text_ads.py b/examples/adwords/v201607/basic_operations/get_text_ads.py new file mode 100755 index 00000000..8a007d64 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/get_text_ads.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2016 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 text ads for a given ad group. + +To add an ad, run add_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/pause_ad.py b/examples/adwords/v201607/basic_operations/pause_ad.py new file mode 100755 index 00000000..3b08cbb4 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201607/basic_operations/remove_ad.py b/examples/adwords/v201607/basic_operations/remove_ad.py new file mode 100755 index 00000000..a0fbf984 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201607/basic_operations/remove_ad_group.py b/examples/adwords/v201607/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..1fa20584 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201607') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/remove_campaign.py b/examples/adwords/v201607/basic_operations/remove_campaign.py new file mode 100755 index 00000000..651d50ad --- /dev/null +++ b/examples/adwords/v201607/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201607') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/basic_operations/remove_keyword.py b/examples/adwords/v201607/basic_operations/remove_keyword.py new file mode 100755 index 00000000..144674f2 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201607') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201607/basic_operations/update_ad_group.py b/examples/adwords/v201607/basic_operations/update_ad_group.py new file mode 100755 index 00000000..b80c1058 --- /dev/null +++ b/examples/adwords/v201607/basic_operations/update_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201607') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/update_campaign.py b/examples/adwords/v201607/basic_operations/update_campaign.py new file mode 100755 index 00000000..0b6cb3ad --- /dev/null +++ b/examples/adwords/v201607/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201607') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/basic_operations/update_keyword.py b/examples/adwords/v201607/basic_operations/update_keyword.py new file mode 100755 index 00000000..006601ff --- /dev/null +++ b/examples/adwords/v201607/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201607') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201607/campaign_management/__init__.py b/examples/adwords/v201607/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201607/campaign_management/add_campaign_labels.py b/examples/adwords/v201607/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..c778800a --- /dev/null +++ b/examples/adwords/v201607/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201607') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..7889ceac --- /dev/null +++ b/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,426 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201607') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201607') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding a TextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new TextAd for each of + the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'TextAd', + 'headline': 'Luxury Cruise to Mars', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'displayUrl': 'www.example.com', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201607') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201607/campaign_management/add_draft.py b/examples/adwords/v201607/campaign_management/add_draft.py new file mode 100755 index 00000000..5308c4fb --- /dev/null +++ b/examples/adwords/v201607/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + # Initialize appropriate services. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201607') + draft_service = client.GetService('DraftService', version='v201607') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201607/campaign_management/add_experiment.py b/examples/adwords/v201607/campaign_management/add_experiment.py new file mode 100755 index 00000000..26cb9852 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/add_experiment.py @@ -0,0 +1,127 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates an experiment. + +The created experiment is using a query percentage of 10, which defines what +fraction of auctions should go to the control split (90%) vs. the experiment +split (10%), then adds experimental bid changes for an ad group, and adds an +experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad +groups, run get_ad_groups.py. To get keywords, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, campaign_id, ad_group_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201607') + ad_group_service = client.GetService('AdGroupService', version='v201607') + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201607') + + # Construct operations and add experiment. + tomorrow = datetime.datetime.now() + datetime.timedelta(1) + thirty_days = datetime.datetime.now() + datetime.timedelta(30) + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), + 'queryPercentage': '10', + 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), + # Optional fields. + 'status': 'ENABLED', + 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was added.' + % (experiment['name'], experiment['id'])) + + # Construct operations and update ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'experimentData': { + 'xsi_type': 'AdGroupExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'MODIFIED', + 'experimentBidMultipliers': { + 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', + 'maxCpcMultiplier': { + 'multiplier': '0.5' + } + } + } + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' + 'experiment.' % (ad_group['name'], ad_group['id'])) + + # Construct operations and add ad group crierion. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + }, + 'experimentData': { + 'xsi_type': 'BiddableAdGroupCriterionExperimentData', + 'experimentId': experiment['id'], + 'experimentDeltaStatus': 'EXPERIMENT_ONLY' + } + } + }] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\' and criterion ' + 'id \'%s\' was added to the experiment.' + % (criterion['adGroupId'], criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..99b7d74b --- /dev/null +++ b/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,259 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201607') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201607') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201607') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201607') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201607/campaign_management/add_trial.py b/examples/adwords/v201607/campaign_management/add_trial.py new file mode 100755 index 00000000..40e5a3f6 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/add_trial.py @@ -0,0 +1,117 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201607') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201607') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..9d716450 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Construct selector and get all ads for a given ad group. + selector = { + 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'AdGroupCreativeApprovalStatus', + 'operator': 'IN', + 'values': ['DISAPPROVED'] + } + ] + } + ads = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..c89cb6b0 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, AdGroupAdDisapprovalReasons ' + 'WHERE CampaignId = %s AND ' + 'AdGroupCreativeApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % campaign_id) + ads = ad_group_ad_service.query(query) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..c0979099 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201607') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201607/campaign_management/graduate_trial.py b/examples/adwords/v201607/campaign_management/graduate_trial.py new file mode 100755 index 00000000..899c9182 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201607') + budget_service = client.GetService('BudgetService', version='v201607') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201607/campaign_management/promote_experiment.py b/examples/adwords/v201607/campaign_management/promote_experiment.py new file mode 100755 index 00000000..757ace46 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/promote_experiment.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2016 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 promotes an experiment. + +Promoting an experiment permanently applies all the experimental changes made to +its related ad groups, criteria and ads. To add an experiment, run +add_experiment.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' + + +def main(client, experiment_id): + # Initialize appropriate service. + experiment_service = client.GetService('ExperimentService', version='v201607') + + # Construct operations and promote experiment. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': experiment_id, + 'status': 'PROMOTED' + } + }] + result = experiment_service.mutate(operations) + + # Display results. + for experiment in result['value']: + print ('Experiment with name \'%s\' and id \'%s\' was promoted.' + % (experiment['name'], experiment['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201607/campaign_management/set_ad_parameters.py b/examples/adwords/v201607/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..4a8a3146 --- /dev/null +++ b/examples/adwords/v201607/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + ad_param_service = client.GetService('AdParamService', version='v201607') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..1ab4374a --- /dev/null +++ b/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201607') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201607/campaign_management/validate_text_ad.py b/examples/adwords/v201607/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..3b7d6a7f --- /dev/null +++ b/examples/adwords/v201607/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Construct operations to add a text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'url': 'http://www.example.com', + 'displayUrl': 'example.com', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for all astronauts in orbit', + 'headline': 'Luxury Cruise to Mars' + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/error_handling/__init__.py b/examples/adwords/v201607/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201607/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201607/error_handling/handle_partial_failures.py b/examples/adwords/v201607/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..a6fa6a91 --- /dev/null +++ b/examples/adwords/v201607/error_handling/handle_partial_failures.py @@ -0,0 +1,120 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201607') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) + if index: + print ('Keyword ad group criterion with ad group id \'%s\' and text ' + '\'%s\' triggered a failure for the following reason: \'%s\'.' + % (keywords[int(index[0])]['adGroupId'], + keywords[int(index[0])]['criterion']['text'], + error['errorString'])) + else: + print 'The following failure has occurred: \'%s\'.' % error['errorString'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..1119662c --- /dev/null +++ b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py @@ -0,0 +1,114 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201607') + + # Create text ad. + text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'TextAd', + 'headline': 'Mars Cruise!!!', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com', + } + } + } + + operations = [text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + if error['ApiError.Type'] == 'PolicyViolationError': + operation_index = re.findall(r'operations\[(.*)\]\.', + error['fieldPath']) + if operation_index: + operation = operations[int(operation_index[0])] + print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % + (operation['operand']['ad']['headline'], + 'exemptable' if error['isExemptable'] else 'non-exemptable', + error['externalPolicyName'])) + if error['isExemptable'].lower() == 'true': + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text ' + '\'%s\'.' % + (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({ + 'key': error['key'] + }) + else: + # Remove non-exemptable operation + print 'Removing the operation from the request.' + operations.delete(operation) + else: + # Non-policy error returned, re-throw exception. + raise e + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/extensions/__init__.py b/examples/adwords/v201607/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201607/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..5d743c1e --- /dev/null +++ b/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201607').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201607') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201607/extensions/add_prices.py b/examples/adwords/v201607/extensions/add_prices.py new file mode 100755 index 00000000..9f4026cd --- /dev/null +++ b/examples/adwords/v201607/extensions/add_prices.py @@ -0,0 +1,144 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201607') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH') + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + return { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/extensions/add_site_links.py b/examples/adwords/v201607/extensions/add_site_links.py new file mode 100755 index 00000000..315101c0 --- /dev/null +++ b/examples/adwords/v201607/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201607') + customer_service = client.GetService('CustomerService', version='v201607') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..5fce9b94 --- /dev/null +++ b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py @@ -0,0 +1,236 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_1_TEXT = '3' +PLACEHOLDER_FIELD_LINE_2_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201607') + feed_item_service = client.GetService('FeedItemService', version='v201607') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201607') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201607') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 1 Description'}, + {'type': 'STRING', 'name': 'Line 2 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_1_feed_attribute_id = feed['attributes'][2]['id'] + line_2_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % + (line_1_feed_attribute_id, line_2_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line1FeedId'] = line_1_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line1': 'Home line 1', 'line2': 'Home line 2'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line1': 'Support line 1', 'line2': 'Support line 2'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line1': 'Products line 1', 'line2': 'Products line 2'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'stringValue': item['line1'] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + feed_item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/migration/__init__.py b/examples/adwords/v201607/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201607/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201607/migration/migrate_to_extension_settings.py b/examples/adwords/v201607/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..2e513597 --- /dev/null +++ b/examples/adwords/v201607/migration/migrate_to_extension_settings.py @@ -0,0 +1,527 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201607') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201607') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201607') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201607') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201607') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201607') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201607') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/migration/upgrade_ad_url.py b/examples/adwords/v201607/migration/upgrade_ad_url.py new file mode 100755 index 00000000..1020f0ea --- /dev/null +++ b/examples/adwords/v201607/migration/upgrade_ad_url.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2016 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 upgrades an ad to use upgraded URLs. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, adgroup_id, ad_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201607') + + selector = { + 'fields': ['Id', 'Url'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [ad_id] + } + ] + } + + page = adgroup_ad_service.get(selector) + + adgroup_ad = page['entries'][0] if page['entries'] else None + + if not adgroup_ad: + raise errors.GoogleAdsError('Ad not found.') + + ad_url_upgrade = { + 'adId': adgroup_ad['ad']['id'], + 'finalUrl': adgroup_ad['ad']['url'] + } + + adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] + + if adgroup_ad: + print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' + % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201607/misc/__init__.py b/examples/adwords/v201607/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201607/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201607/misc/get_all_images_and_videos.py b/examples/adwords/v201607/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..713a9529 --- /dev/null +++ b/examples/adwords/v201607/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201607') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/misc/upload_image.py b/examples/adwords/v201607/misc/upload_image.py new file mode 100755 index 00000000..abb26584 --- /dev/null +++ b/examples/adwords/v201607/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201607') + + with open(image_filename, 'r') as image_handle: + image_data = base64.encodestring(image_handle.read()) + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201607/misc/upload_media_bundle.py b/examples/adwords/v201607/misc/upload_media_bundle.py new file mode 100755 index 00000000..3b543eeb --- /dev/null +++ b/examples/adwords/v201607/misc/upload_media_bundle.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201607') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/optimization/__init__.py b/examples/adwords/v201607/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201607/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201607/optimization/estimate_keyword_traffic.py b/examples/adwords/v201607/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..81570092 --- /dev/null +++ b/examples/adwords/v201607/optimization/estimate_keyword_traffic.py @@ -0,0 +1,180 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201607') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..4957cebf --- /dev/null +++ b/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201607') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..4bf2c5e8 --- /dev/null +++ b/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201607') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201607/optimization/get_keyword_ideas.py b/examples/adwords/v201607/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..c47cf6e9 --- /dev/null +++ b/examples/adwords/v201607/optimization/get_keyword_ideas.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201607') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }, + { + # Network search parameter (optional) + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/remarketing/__init__.py b/examples/adwords/v201607/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201607/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201607/remarketing/add_audience.py b/examples/adwords/v201607/remarketing/add_audience.py new file mode 100755 index 00000000..c13e4f6b --- /dev/null +++ b/examples/adwords/v201607/remarketing/add_audience.py @@ -0,0 +1,103 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201607') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201607') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/remarketing/add_conversion_tracker.py b/examples/adwords/v201607/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..7abe5a99 --- /dev/null +++ b/examples/adwords/v201607/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201607') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/remarketing/add_crm_based_user_list.py b/examples/adwords/v201607/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..7c8d51a5 --- /dev/null +++ b/examples/adwords/v201607/remarketing/add_crm_based_user_list.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client, emails): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201607') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180 + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + hashed_emails = HashEmails(emails) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'dataType': 'EMAIL_SHA256', + 'members': hashed_emails + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def HashEmails(emails): + """Hashes the given emails using SHA-256. + + Note: Emails are stripped of any whitespace and set to lowercase before + hashing. + + Args: + emails: list of str emails to be hashed. + + Returns: + A list of SHA-256 hashed emails. + """ + return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + + +if __name__ == '__main__': + EMAILS = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, EMAILS) diff --git a/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..28cf1ffc --- /dev/null +++ b/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,183 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201607') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords will logically OR the + # groups together. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/remarketing/upload_offline_conversions.py b/examples/adwords/v201607/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..8a32a9d6 --- /dev/null +++ b/examples/adwords/v201607/remarketing/upload_offline_conversions.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201607') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201607/reporting/__init__.py b/examples/adwords/v201607/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201607/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201607/reporting/download_criteria_report.py b/examples/adwords/v201607/reporting/download_criteria_report.py new file mode 100755 index 00000000..0e96e562 --- /dev/null +++ b/examples/adwords/v201607/reporting/download_criteria_report.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201607') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py new file mode 100755 index 00000000..5a7040f6 --- /dev/null +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201607') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..7e305ab8 --- /dev/null +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201607') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py new file mode 100755 index 00000000..1933b7be --- /dev/null +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201607') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..13c16109 --- /dev/null +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201607') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..f7d20d60 --- /dev/null +++ b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client, path): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201607') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + with open(path, 'w') as output_file: + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', output_file, skip_report_header=False, + skip_column_header=False, skip_report_summary=False) + + print 'Report was downloaded to \'%s\'.' % path + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, PATH) diff --git a/examples/adwords/v201607/reporting/get_report_fields.py b/examples/adwords/v201607/reporting/get_report_fields.py new file mode 100755 index 00000000..97bf5e01 --- /dev/null +++ b/examples/adwords/v201607/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201607') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201607/reporting/parallel_report_download.py b/examples/adwords/v201607/reporting/parallel_report_download.py new file mode 100755 index 00000000..b3e16bda --- /dev/null +++ b/examples/adwords/v201607/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201607') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201607') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201607/shopping/__init__.py b/examples/adwords/v201607/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201607/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201607/shopping/add_product_partition_tree.py b/examples/adwords/v201607/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..302b63ab --- /dev/null +++ b/examples/adwords/v201607/shopping/add_product_partition_tree.py @@ -0,0 +1,281 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201607') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201607/shopping/add_product_scope.py b/examples/adwords/v201607/shopping/add_product_scope.py new file mode 100755 index 00000000..c2f57ef2 --- /dev/null +++ b/examples/adwords/v201607/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201607') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/shopping/add_shopping_campaign.py b/examples/adwords/v201607/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..fec5419f --- /dev/null +++ b/examples/adwords/v201607/shopping/add_shopping_campaign.py @@ -0,0 +1,121 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id): + campaign_service = client.GetService('CampaignService', version='v201607') + ad_group_service = client.GetService('AdGroupService', version='v201607') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + adgroup = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group_result = ad_group_service.mutate(adgroup_operations) + + for adgroup in ad_group_result['value']: + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (adgroup['name'], adgroup['id'])) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': adgroup['id'], + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201607/shopping/get_product_category_taxonomy.py b/examples/adwords/v201607/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..029d7299 --- /dev/null +++ b/examples/adwords/v201607/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201607') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/targeting/__init__.py b/examples/adwords/v201607/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201607/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..59b636c8 --- /dev/null +++ b/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,145 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201607') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create location groups. The IDs can be found in the documentation or + # retrieved with the LocationCriterionService. + florida_tier3 = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'IncomeOperand', + # Tiers are numbered 1-10, and represent 10% segments of earners. + # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. + # Tiers 6 through 10 are grouped into TIER_6_TO_10. + 'tier': 'TIER_3' + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + }, + } + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish, florida_tier3] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..24ae1373 --- /dev/null +++ b/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201607') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..bd904689 --- /dev/null +++ b/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201607') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..ecf76a5c --- /dev/null +++ b/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201607') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201607/targeting/lookup_location.py b/examples/adwords/v201607/targeting/lookup_location.py new file mode 100755 index 00000000..37a7756b --- /dev/null +++ b/examples/adwords/v201607/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201607') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/googleads/adwords.py b/googleads/adwords.py index 35fed0ad..1e96ba9b 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -170,6 +170,52 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201607': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'ExperimentService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } @@ -213,8 +259,10 @@ class AdWordsClient(object): # A list of values which must be provided to use AdWords. _REQUIRED_INIT_VALUES = ('user_agent', 'developer_token') # A list of values which may optionally be provided when using AdWords. - _OPTIONAL_INIT_VALUES = ('validate_only', 'partial_failure', - 'client_customer_id', 'report_downloader_headers') + _OPTIONAL_INIT_VALUES = ( + 'validate_only', 'partial_failure', 'client_customer_id', + 'report_downloader_headers') + # The format of SOAP service WSDLs. A server, namespace, version, and service # name need to be formatted in. _SOAP_SERVICE_FORMAT = '%s/api/adwords/%s/%s/%s?wsdl' diff --git a/googleads/common.py b/googleads/common.py index e611e512..9467cb24 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -42,7 +42,8 @@ # not have certificate validation performed until they update. pass -VERSION = '4.2.0' + +VERSION = '4.3.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' From 7b411c5870d615da579fe33975e5bfd064f14db2 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 29 Jul 2016 17:06:35 -0400 Subject: [PATCH 043/180] Commiting latest changes. From a93f712196d2a041737d996fb46f94463944e0b2 Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 23 Aug 2016 14:26:59 -0400 Subject: [PATCH 044/180] adding v201608 support for DFP --- ChangeLog | 5 + .../get_active_activity_groups.py | 69 ------- .../update_activity_groups.py | 76 -------- .../activity_service/create_activities.py | 68 ------- .../activity_service/get_active_activities.py | 66 ------- .../activity_service/get_all_activities.py | 58 ------ .../create_audience_segments.py | 98 ---------- .../get_first_party_audience_segments.py | 67 ------- .../populate_first_party_audience_segments.py | 82 -------- .../update_audience_segments.py | 80 -------- .../get_base_rates_for_a_rate_card.py | 69 ------- .../company_service/create_companies.py | 62 ------ .../company_service/get_advertisers.py | 66 ------- .../company_service/update_companies.py | 74 -------- .../contact_service/get_all_contacts.py | 58 ------ .../contact_service/get_uninvited_contacts.py | 65 ------- .../contact_service/update_contacts.py | 75 -------- ...create_content_metadata_key_hierarchies.py | 78 -------- ...delete_content_metadata_key_hierarchies.py | 84 --------- ...et_all_content_metadata_key_hierarchies.py | 63 ------- .../content_service/get_all_content.py | 59 ------ .../get_content_by_category.py | 109 ----------- .../creative_service/create_creatives.py | 91 --------- .../create_custom_creative.py | 88 --------- .../create_native_creative.py | 131 ------------- .../get_creatives_by_statement.py | 69 ------- .../get_all_creative_sets.py | 59 ------ .../get_creative_templates_by_statement.py | 67 ------- .../deactivate_creative_wrapper.py | 88 --------- .../get_active_creative_wrappers.py | 67 ------- .../create_custom_field_options.py | 67 ------- .../create_custom_fields.py | 66 ------- .../get_all_line_item_custom_fields.py | 69 ------- .../set_line_item_custom_field_value.py | 156 ---------------- .../update_custom_fields.py | 75 -------- .../delete_custom_targeting_keys.py | 82 -------- ...et_all_custom_targeting_keys_and_values.py | 88 --------- ...et_custom_targeting_values_by_statement.py | 65 ------- .../get_all_exchange_rates.py | 60 ------ .../get_availability_forecast.py | 132 ------------- ...get_availability_forecast_for_line_item.py | 63 ------- .../get_delivery_forecast_for_line_items.py | 52 ------ .../inventory_service/create_ad_units.py | 71 ------- .../get_ad_unit_hierarchy.py | 115 ------------ .../get_all_ad_unit_sizes.py | 54 ------ .../inventory_service/get_all_ad_units.py | 56 ------ .../get_top_level_ad_units.py | 69 ------- .../v201508/label_service/create_labels.py | 54 ------ .../label_service/get_labels_by_statement.py | 53 ------ .../create_licas.py | 56 ------ .../deactivate_licas.py | 82 -------- .../get_all_licas.py | 56 ------ .../line_item_service/create_line_items.py | 171 ----------------- .../create_video_line_item.py | 140 -------------- .../get_line_items_by_statement.py | 75 -------- .../get_recently_updated_line_items.py | 74 -------- .../network_service/get_all_networks.py | 44 ----- .../network_service/get_current_network.py | 38 ---- .../order_service/get_orders_by_statement.py | 61 ------ .../v201508/order_service/update_orders.py | 75 -------- .../placement_service/create_placements.py | 108 ----------- .../deactivate_placements.py | 66 ------- .../placement_service/update_placements.py | 66 ------- .../create_premium_rates.py | 81 -------- .../get_premium_rates_for_a_rate_card.py | 68 ------- .../update_premium_rates.py | 91 --------- .../product_service/get_all_products.py | 53 ------ .../archive_proposal_line_items.py | 81 -------- .../get_proposal_line_items_for_proposal.py | 70 ------- .../proposal_service/get_all_proposals.py | 52 ------ .../get_geo_targets.py | 63 ------- .../rate_card_service/get_all_rate_cards.py | 53 ------ .../report_service/run_delivery_report.py | 95 ---------- .../report_service/run_inventory_report.py | 88 --------- .../report_service/run_reach_report.py | 64 ------- .../approve_all_suggested_ad_units.py | 78 -------- .../team_service/get_teams_by_statement.py | 67 ------- .../v201508/user_service/get_current_user.py | 38 ---- .../user_service/get_users_by_statement.py | 57 ------ .../create_user_team_associations.py | 67 ------- .../delete_user_team_associations.py | 80 -------- .../update_user_team_associations.py | 85 --------- .../approve_workflow_approval_requests.py | 97 ---------- ...workflow_approval_requests_by_statement.py | 67 ------- ...xternal_condition_requests_by_statement.py | 67 ------- .../activity_group_service/__init__.py | 15 -- .../create_activity_groups.py | 71 ------- .../get_active_activity_groups.py | 69 ------- .../dfp/v201511/activity_service/__init__.py | 15 -- .../activity_service/get_active_activities.py | 66 ------- .../activity_service/update_activities.py | 72 ------- .../audience_segment_service/__init__.py | 15 -- .../dfp/v201511/base_rate_service/__init__.py | 15 -- .../create_product_base_rates.py | 63 ------- .../create_product_template_base_rates.py | 63 ------- .../base_rate_service/get_all_base_rates.py | 59 ------ .../base_rate_service/update_base_rates.py | 81 -------- .../dfp/v201511/company_service/__init__.py | 15 -- .../company_service/get_advertisers.py | 66 ------- .../dfp/v201511/contact_service/__init__.py | 15 -- .../contact_service/create_contacts.py | 71 ------- .../contact_service/get_uninvited_contacts.py | 65 ------- .../__init__.py | 15 -- ...et_all_content_metadata_key_hierarchies.py | 63 ------- ...update_content_metadata_key_hierarchies.py | 96 ---------- .../dfp/v201511/content_service/__init__.py | 15 -- .../content_service/get_all_content.py | 59 ------ .../get_content_by_category.py | 109 ----------- .../dfp/v201511/creative_service/__init__.py | 15 -- .../create_creative_from_template.py | 101 ---------- .../creative_service/get_all_creatives.py | 59 ------ .../get_creatives_by_statement.py | 69 ------- .../creative_service/update_creatives.py | 80 -------- .../v201511/creative_set_service/__init__.py | 15 -- .../associate_creative_set_to_line_item.py | 56 ------ .../create_creative_set.py | 61 ------ .../get_all_creative_sets.py | 59 ------ .../get_creative_sets_by_statement.py | 72 ------- .../update_creative_set.py | 78 -------- .../creative_template_service/__init__.py | 15 -- .../get_creative_templates_by_statement.py | 67 ------- .../create_creative_wrappers.py | 63 ------- .../get_active_creative_wrappers.py | 67 ------- .../get_all_creative_wrappers.py | 59 ------ .../update_creative_wrappers.py | 77 -------- .../v201511/custom_field_service/__init__.py | 15 -- .../deactivate_all_line_item_custom_fields.py | 85 --------- .../get_all_line_item_custom_fields.py | 69 ------- .../custom_targeting_service/__init__.py | 15 -- ...create_custom_targeting_keys_and_values.py | 132 ------------- .../delete_custom_targeting_values.py | 83 --------- ...et_all_custom_targeting_keys_and_values.py | 88 --------- .../get_custom_targeting_keys_by_statement.py | 61 ------ ...et_custom_targeting_values_by_statement.py | 65 ------- .../update_custom_targeting_keys.py | 70 ------- .../update_custom_targeting_values.py | 76 -------- .../v201511/exchange_rate_service/__init__.py | 15 -- .../create_exchange_rates.py | 58 ------ .../get_exchange_rates_by_currency_code.py | 71 ------- .../update_exchange_rates.py | 77 -------- .../get_availability_forecast.py | 132 ------------- ...get_availability_forecast_for_line_item.py | 63 ------- .../get_delivery_forecast_for_line_items.py | 52 ------ .../dfp/v201511/inventory_service/__init__.py | 15 -- .../inventory_service/archive_ad_units.py | 80 -------- .../get_ad_unit_hierarchy.py | 115 ------------ .../get_all_ad_unit_sizes.py | 54 ------ .../inventory_service/get_all_ad_units.py | 56 ------ .../get_top_level_ad_units.py | 69 ------- .../inventory_service/update_ad_units.py | 87 --------- .../dfp/v201511/label_service/__init__.py | 15 -- .../label_service/deactivate_labels.py | 69 ------- .../v201511/label_service/update_labels.py | 69 ------- .../__init__.py | 15 -- .../get_licas_by_statement.py | 66 ------- .../update_licas.py | 65 ------- .../dfp/v201511/line_item_service/__init__.py | 15 -- .../line_item_service/activate_line_items.py | 84 --------- .../get_line_items_by_statement.py | 75 -------- .../get_recently_updated_line_items.py | 74 -------- .../target_custom_criteria.py | 113 ----------- .../line_item_service/update_line_items.py | 81 -------- .../dfp/v201511/network_service/__init__.py | 15 -- .../network_service/get_current_network.py | 38 ---- .../network_service/make_test_network.py | 51 ----- .../dfp/v201511/order_service/__init__.py | 15 -- .../v201511/order_service/approve_orders.py | 73 -------- .../v201511/order_service/create_orders.py | 58 ------ .../order_service/get_orders_by_statement.py | 61 ------ .../v201511/premium_rate_service/__init__.py | 15 -- .../get_all_premium_rates.py | 58 ------ .../dfp/v201511/product_service/__init__.py | 15 -- .../get_products_for_product_template.py | 62 ------ .../product_template_service/__init__.py | 15 -- .../activate_product_templates.py | 79 -------- .../get_all_product_templates.py | 55 ------ .../get_sponsorship_product_templates.py | 61 ------ .../update_product_templates.py | 98 ---------- .../proposal_line_item_service/__init__.py | 15 -- .../get_proposal_line_items_for_proposal.py | 70 ------- .../update_proposal_line_items.py | 77 -------- .../dfp/v201511/proposal_service/__init__.py | 15 -- .../get_proposals_by_statement.py | 60 ------ .../proposal_service/update_proposals.py | 71 ------- .../__init__.py | 15 -- .../fetch_match_tables.py | 55 ------ .../get_geo_targets.py | 63 ------- .../get_line_items_named_like.py | 56 ------ .../dfp/v201511/rate_card_service/__init__.py | 15 -- .../get_rate_cards_priced_with_currency.py | 62 ------ .../dfp/v201511/report_service/__init__.py | 15 -- .../run_report_with_custom_fields.py | 105 ----------- .../report_service/run_sales_report.py | 65 ------- .../suggested_ad_unit_service/__init__.py | 15 -- .../get_suggested_ad_units_by_statement.py | 63 ------- examples/dfp/v201511/team_service/__init__.py | 15 -- .../dfp/v201511/team_service/create_teams.py | 61 ------ .../dfp/v201511/team_service/get_all_teams.py | 57 ------ .../team_service/get_teams_by_statement.py | 67 ------- .../dfp/v201511/team_service/update_teams.py | 81 -------- examples/dfp/v201511/user_service/__init__.py | 15 -- .../dfp/v201511/user_service/create_users.py | 57 ------ .../v201511/user_service/deactivate_users.py | 71 ------- .../dfp/v201511/user_service/get_all_roles.py | 44 ----- .../v201511/user_service/get_current_user.py | 38 ---- .../user_service/get_users_by_statement.py | 57 ------ .../dfp/v201511/user_service/update_users.py | 64 ------- .../user_team_association_service/__init__.py | 15 -- .../get_all_user_team_associations.py | 61 ------ .../get_user_team_associations_for_user.py | 72 ------- .../workflow_request_service/__init__.py | 15 -- ...er_workflow_external_condition_requests.py | 100 ---------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py} | 42 ++--- .../get_all_activity_groups.py | 51 +++++ .../update_activity_groups.py | 2 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../get_active_activities.py} | 45 +++-- .../activity_service/get_all_activities.py | 50 +++++ .../activity_service/update_activities.py | 2 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 6 +- .../get_all_audience_segments.py | 28 ++- .../get_first_party_audience_segments.py | 46 ++--- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 2 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 32 ++-- .../get_base_rates_for_rate_card.py} | 49 ++--- .../base_rate_service/update_base_rates.py | 2 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py} | 44 +++-- .../company_service/get_all_companies.py | 49 +++++ .../company_service/update_companies.py | 2 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py} | 25 ++- .../get_uninvited_contacts.py} | 44 +++-- .../contact_service/update_contacts.py | 2 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...t_all_content_metadata_key_hierarchies.py} | 35 ++-- ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py} | 27 ++- .../creative_service/__init__.py | 0 .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 49 +++++ .../creative_service/get_image_creatives.py} | 45 +++-- .../creative_service/update_creatives.py | 2 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py} | 29 ++- .../get_creative_sets_for_master_creative.py} | 48 ++--- .../update_creative_set.py | 2 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 30 ++- .../get_system_defined_creative_templates.py} | 43 +++-- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py} | 43 +++-- .../get_all_creative_wrappers.py} | 29 ++- .../update_creative_wrappers.py | 2 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 26 +-- .../get_custom_fields_for_line_items.py} | 41 ++-- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 2 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 72 +++++++ ...efined_custom_targeting_keys_and_values.py | 80 ++++++++ .../update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 34 ++-- .../get_exchange_rates_for_currency_code.py} | 45 ++--- .../update_exchange_rates.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 3 +- .../get_all_ad_unit_sizes.py | 49 +++++ .../inventory_service/get_all_ad_units.py | 49 +++++ .../inventory_service/update_ad_units.py | 2 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../label_service/get_active_labels.py} | 35 ++-- .../label_service/get_all_labels.py | 23 +-- .../label_service/update_labels.py | 2 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 2 +- .../get_all_licas.py | 33 ++-- .../get_licas_for_line_item.py} | 50 ++--- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 2 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 28 ++- .../get_line_items_that_need_creatives.py | 57 ++++++ .../get_recently_updated_line_items.py | 61 ++++++ .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 2 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 20 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 2 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 21 +-- .../order_service/get_orders_starting_soon.py | 71 +++++++ .../order_service/update_orders.py | 2 +- .../package_service/get_all_packages.py} | 28 ++- .../get_in_progress_packages.py} | 43 ++--- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 2 +- .../get_active_placements.py} | 41 ++-- .../placement_service/get_all_placements.py | 26 ++- .../placement_service/update_placements.py | 2 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 31 ++- .../get_premium_rates_for_rate_card.py} | 46 ++--- .../update_premium_rates.py | 2 +- .../get_all_product_package_items.py} | 35 ++-- ...oduct_package_items_for_product_package.py | 62 ++++++ .../get_active_product_packages.py} | 45 +++-- .../get_all_product_packages.py | 51 +++++ .../product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 84 +++++++++ .../product_service/get_all_products.py | 24 +-- .../get_products_for_product_template.py | 37 ++-- ...h_programmatic_products_to_marketplace.py} | 52 +++--- .../product_service/update_products.py | 2 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 2 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py} | 44 ++--- .../get_all_product_templates.py | 24 +-- .../get_sponsorship_product_templates.py | 37 ++-- .../update_product_templates.py | 2 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 2 +- ...reate_programmatic_proposal_line_items.py} | 39 ++-- ...sal_line_items_for_non_sales_management.py | 125 +++++++++++++ .../create_proposal_line_items.py | 8 +- .../get_all_proposal_line_items.py | 28 ++- .../get_proposal_line_items_for_proposal.py} | 45 ++--- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py} | 47 +++-- ...atic_proposals_for_non_sales_management.py | 62 ++++++ .../proposal_service/create_proposals.py | 6 +- .../proposal_service/get_all_proposals.py | 23 +-- .../get_marketplace_comments.py | 72 +++++++ .../get_proposals_pending_approval.py} | 40 ++-- .../request_buyers_acceptance.py} | 30 +-- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 6 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_programmatic_buyers.py} | 31 ++- .../rate_card_service/__init__.py | 0 .../rate_card_service/get_all_rate_cards.py | 28 ++- .../get_marketplace_rate_cards.py} | 44 +++-- ..._item_reports_for_reconciliation_report.py | 73 ++++++++ ...order_reports_for_reconciliation_report.py | 61 ++++++ ...n_report_rows_for_reconciliation_report.py | 69 +++++++ .../get_all_reconciliation_reports.py} | 34 ++-- ...iliation_report_for_last_billing_period.py | 66 +++++++ .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 2 +- .../report_service/run_inventory_report.py | 4 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 4 +- .../report_service/run_sales_report.py | 2 +- .../v201608/report_service/run_saved_query.py | 85 +++++++++ .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 24 ++- ...et_highly_requested_suggested_ad_units.py} | 48 +++-- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 26 +-- .../team_service/update_teams.py | 22 +-- .../user_service/__init__.py | 0 .../user_service/create_users.py | 3 +- .../user_service/deactivate_users.py | 2 +- .../user_service/get_all_roles.py | 20 +- .../user_service/get_all_users.py | 21 ++- .../get_user_by_email_address.py} | 40 ++-- .../user_service/update_users.py | 2 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 27 +-- .../get_user_team_associations_for_user.py | 47 ++--- .../update_user_team_associations.py | 2 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py} | 40 ++-- ...t_workflow_external_condition_requests.py} | 44 ++--- ...er_workflow_external_condition_requests.py | 2 +- googleads/adwords.py | 175 ++++++++--------- googleads/common.py | 2 +- googleads/dfp.py | 17 +- tests/adwords_test.py | 176 +++++++----------- tests/dfp_test.py | 7 + 426 files changed, 2771 insertions(+), 15025 deletions(-) delete mode 100755 examples/dfp/v201508/activity_group_service/get_active_activity_groups.py delete mode 100755 examples/dfp/v201508/activity_group_service/update_activity_groups.py delete mode 100755 examples/dfp/v201508/activity_service/create_activities.py delete mode 100755 examples/dfp/v201508/activity_service/get_active_activities.py delete mode 100755 examples/dfp/v201508/activity_service/get_all_activities.py delete mode 100755 examples/dfp/v201508/audience_segment_service/create_audience_segments.py delete mode 100755 examples/dfp/v201508/audience_segment_service/get_first_party_audience_segments.py delete mode 100755 examples/dfp/v201508/audience_segment_service/populate_first_party_audience_segments.py delete mode 100755 examples/dfp/v201508/audience_segment_service/update_audience_segments.py delete mode 100755 examples/dfp/v201508/base_rate_service/get_base_rates_for_a_rate_card.py delete mode 100755 examples/dfp/v201508/company_service/create_companies.py delete mode 100755 examples/dfp/v201508/company_service/get_advertisers.py delete mode 100755 examples/dfp/v201508/company_service/update_companies.py delete mode 100755 examples/dfp/v201508/contact_service/get_all_contacts.py delete mode 100755 examples/dfp/v201508/contact_service/get_uninvited_contacts.py delete mode 100755 examples/dfp/v201508/contact_service/update_contacts.py delete mode 100755 examples/dfp/v201508/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py delete mode 100755 examples/dfp/v201508/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py delete mode 100755 examples/dfp/v201508/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py delete mode 100755 examples/dfp/v201508/content_service/get_all_content.py delete mode 100755 examples/dfp/v201508/content_service/get_content_by_category.py delete mode 100755 examples/dfp/v201508/creative_service/create_creatives.py delete mode 100755 examples/dfp/v201508/creative_service/create_custom_creative.py delete mode 100755 examples/dfp/v201508/creative_service/create_native_creative.py delete mode 100755 examples/dfp/v201508/creative_service/get_creatives_by_statement.py delete mode 100755 examples/dfp/v201508/creative_set_service/get_all_creative_sets.py delete mode 100755 examples/dfp/v201508/creative_template_service/get_creative_templates_by_statement.py delete mode 100755 examples/dfp/v201508/creative_wrapper_service/deactivate_creative_wrapper.py delete mode 100755 examples/dfp/v201508/creative_wrapper_service/get_active_creative_wrappers.py delete mode 100755 examples/dfp/v201508/custom_field_service/create_custom_field_options.py delete mode 100755 examples/dfp/v201508/custom_field_service/create_custom_fields.py delete mode 100755 examples/dfp/v201508/custom_field_service/get_all_line_item_custom_fields.py delete mode 100755 examples/dfp/v201508/custom_field_service/set_line_item_custom_field_value.py delete mode 100755 examples/dfp/v201508/custom_field_service/update_custom_fields.py delete mode 100755 examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_keys.py delete mode 100755 examples/dfp/v201508/custom_targeting_service/get_all_custom_targeting_keys_and_values.py delete mode 100755 examples/dfp/v201508/custom_targeting_service/get_custom_targeting_values_by_statement.py delete mode 100755 examples/dfp/v201508/exchange_rate_service/get_all_exchange_rates.py delete mode 100755 examples/dfp/v201508/forecast_service/get_availability_forecast.py delete mode 100755 examples/dfp/v201508/forecast_service/get_availability_forecast_for_line_item.py delete mode 100755 examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py delete mode 100755 examples/dfp/v201508/inventory_service/create_ad_units.py delete mode 100755 examples/dfp/v201508/inventory_service/get_ad_unit_hierarchy.py delete mode 100755 examples/dfp/v201508/inventory_service/get_all_ad_unit_sizes.py delete mode 100755 examples/dfp/v201508/inventory_service/get_all_ad_units.py delete mode 100755 examples/dfp/v201508/inventory_service/get_top_level_ad_units.py delete mode 100755 examples/dfp/v201508/label_service/create_labels.py delete mode 100755 examples/dfp/v201508/label_service/get_labels_by_statement.py delete mode 100755 examples/dfp/v201508/line_item_creative_association_service/create_licas.py delete mode 100755 examples/dfp/v201508/line_item_creative_association_service/deactivate_licas.py delete mode 100755 examples/dfp/v201508/line_item_creative_association_service/get_all_licas.py delete mode 100755 examples/dfp/v201508/line_item_service/create_line_items.py delete mode 100755 examples/dfp/v201508/line_item_service/create_video_line_item.py delete mode 100755 examples/dfp/v201508/line_item_service/get_line_items_by_statement.py delete mode 100755 examples/dfp/v201508/line_item_service/get_recently_updated_line_items.py delete mode 100755 examples/dfp/v201508/network_service/get_all_networks.py delete mode 100755 examples/dfp/v201508/network_service/get_current_network.py delete mode 100755 examples/dfp/v201508/order_service/get_orders_by_statement.py delete mode 100755 examples/dfp/v201508/order_service/update_orders.py delete mode 100755 examples/dfp/v201508/placement_service/create_placements.py delete mode 100755 examples/dfp/v201508/placement_service/deactivate_placements.py delete mode 100755 examples/dfp/v201508/placement_service/update_placements.py delete mode 100755 examples/dfp/v201508/premium_rate_service/create_premium_rates.py delete mode 100755 examples/dfp/v201508/premium_rate_service/get_premium_rates_for_a_rate_card.py delete mode 100755 examples/dfp/v201508/premium_rate_service/update_premium_rates.py delete mode 100755 examples/dfp/v201508/product_service/get_all_products.py delete mode 100755 examples/dfp/v201508/proposal_line_item_service/archive_proposal_line_items.py delete mode 100755 examples/dfp/v201508/proposal_line_item_service/get_proposal_line_items_for_proposal.py delete mode 100755 examples/dfp/v201508/proposal_service/get_all_proposals.py delete mode 100755 examples/dfp/v201508/publisher_query_language_service/get_geo_targets.py delete mode 100755 examples/dfp/v201508/rate_card_service/get_all_rate_cards.py delete mode 100755 examples/dfp/v201508/report_service/run_delivery_report.py delete mode 100755 examples/dfp/v201508/report_service/run_inventory_report.py delete mode 100755 examples/dfp/v201508/report_service/run_reach_report.py delete mode 100755 examples/dfp/v201508/suggested_ad_unit_service/approve_all_suggested_ad_units.py delete mode 100755 examples/dfp/v201508/team_service/get_teams_by_statement.py delete mode 100755 examples/dfp/v201508/user_service/get_current_user.py delete mode 100755 examples/dfp/v201508/user_service/get_users_by_statement.py delete mode 100755 examples/dfp/v201508/user_team_association_service/create_user_team_associations.py delete mode 100755 examples/dfp/v201508/user_team_association_service/delete_user_team_associations.py delete mode 100755 examples/dfp/v201508/user_team_association_service/update_user_team_associations.py delete mode 100755 examples/dfp/v201508/workflow_request_service/approve_workflow_approval_requests.py delete mode 100755 examples/dfp/v201508/workflow_request_service/get_workflow_approval_requests_by_statement.py delete mode 100755 examples/dfp/v201508/workflow_request_service/get_workflow_external_condition_requests_by_statement.py delete mode 100755 examples/dfp/v201511/activity_group_service/__init__.py delete mode 100755 examples/dfp/v201511/activity_group_service/create_activity_groups.py delete mode 100755 examples/dfp/v201511/activity_group_service/get_active_activity_groups.py delete mode 100755 examples/dfp/v201511/activity_service/__init__.py delete mode 100755 examples/dfp/v201511/activity_service/get_active_activities.py delete mode 100755 examples/dfp/v201511/activity_service/update_activities.py delete mode 100755 examples/dfp/v201511/audience_segment_service/__init__.py delete mode 100755 examples/dfp/v201511/base_rate_service/__init__.py delete mode 100755 examples/dfp/v201511/base_rate_service/create_product_base_rates.py delete mode 100755 examples/dfp/v201511/base_rate_service/create_product_template_base_rates.py delete mode 100755 examples/dfp/v201511/base_rate_service/get_all_base_rates.py delete mode 100755 examples/dfp/v201511/base_rate_service/update_base_rates.py delete mode 100755 examples/dfp/v201511/company_service/__init__.py delete mode 100755 examples/dfp/v201511/company_service/get_advertisers.py delete mode 100755 examples/dfp/v201511/contact_service/__init__.py delete mode 100755 examples/dfp/v201511/contact_service/create_contacts.py delete mode 100755 examples/dfp/v201511/contact_service/get_uninvited_contacts.py delete mode 100755 examples/dfp/v201511/content_metadata_key_hierarchy_service/__init__.py delete mode 100755 examples/dfp/v201511/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py delete mode 100755 examples/dfp/v201511/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py delete mode 100755 examples/dfp/v201511/content_service/__init__.py delete mode 100755 examples/dfp/v201511/content_service/get_all_content.py delete mode 100755 examples/dfp/v201511/content_service/get_content_by_category.py delete mode 100755 examples/dfp/v201511/creative_service/__init__.py delete mode 100755 examples/dfp/v201511/creative_service/create_creative_from_template.py delete mode 100755 examples/dfp/v201511/creative_service/get_all_creatives.py delete mode 100755 examples/dfp/v201511/creative_service/get_creatives_by_statement.py delete mode 100755 examples/dfp/v201511/creative_service/update_creatives.py delete mode 100755 examples/dfp/v201511/creative_set_service/__init__.py delete mode 100755 examples/dfp/v201511/creative_set_service/associate_creative_set_to_line_item.py delete mode 100755 examples/dfp/v201511/creative_set_service/create_creative_set.py delete mode 100755 examples/dfp/v201511/creative_set_service/get_all_creative_sets.py delete mode 100755 examples/dfp/v201511/creative_set_service/get_creative_sets_by_statement.py delete mode 100755 examples/dfp/v201511/creative_set_service/update_creative_set.py delete mode 100755 examples/dfp/v201511/creative_template_service/__init__.py delete mode 100755 examples/dfp/v201511/creative_template_service/get_creative_templates_by_statement.py delete mode 100755 examples/dfp/v201511/creative_wrapper_service/create_creative_wrappers.py delete mode 100755 examples/dfp/v201511/creative_wrapper_service/get_active_creative_wrappers.py delete mode 100755 examples/dfp/v201511/creative_wrapper_service/get_all_creative_wrappers.py delete mode 100755 examples/dfp/v201511/creative_wrapper_service/update_creative_wrappers.py delete mode 100755 examples/dfp/v201511/custom_field_service/__init__.py delete mode 100755 examples/dfp/v201511/custom_field_service/deactivate_all_line_item_custom_fields.py delete mode 100755 examples/dfp/v201511/custom_field_service/get_all_line_item_custom_fields.py delete mode 100755 examples/dfp/v201511/custom_targeting_service/__init__.py delete mode 100755 examples/dfp/v201511/custom_targeting_service/create_custom_targeting_keys_and_values.py delete mode 100755 examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_values.py delete mode 100755 examples/dfp/v201511/custom_targeting_service/get_all_custom_targeting_keys_and_values.py delete mode 100755 examples/dfp/v201511/custom_targeting_service/get_custom_targeting_keys_by_statement.py delete mode 100755 examples/dfp/v201511/custom_targeting_service/get_custom_targeting_values_by_statement.py delete mode 100755 examples/dfp/v201511/custom_targeting_service/update_custom_targeting_keys.py delete mode 100755 examples/dfp/v201511/custom_targeting_service/update_custom_targeting_values.py delete mode 100755 examples/dfp/v201511/exchange_rate_service/__init__.py delete mode 100755 examples/dfp/v201511/exchange_rate_service/create_exchange_rates.py delete mode 100755 examples/dfp/v201511/exchange_rate_service/get_exchange_rates_by_currency_code.py delete mode 100755 examples/dfp/v201511/exchange_rate_service/update_exchange_rates.py delete mode 100755 examples/dfp/v201511/forecast_service/get_availability_forecast.py delete mode 100755 examples/dfp/v201511/forecast_service/get_availability_forecast_for_line_item.py delete mode 100755 examples/dfp/v201511/forecast_service/get_delivery_forecast_for_line_items.py delete mode 100755 examples/dfp/v201511/inventory_service/__init__.py delete mode 100755 examples/dfp/v201511/inventory_service/archive_ad_units.py delete mode 100755 examples/dfp/v201511/inventory_service/get_ad_unit_hierarchy.py delete mode 100755 examples/dfp/v201511/inventory_service/get_all_ad_unit_sizes.py delete mode 100755 examples/dfp/v201511/inventory_service/get_all_ad_units.py delete mode 100755 examples/dfp/v201511/inventory_service/get_top_level_ad_units.py delete mode 100755 examples/dfp/v201511/inventory_service/update_ad_units.py delete mode 100755 examples/dfp/v201511/label_service/__init__.py delete mode 100755 examples/dfp/v201511/label_service/deactivate_labels.py delete mode 100755 examples/dfp/v201511/label_service/update_labels.py delete mode 100755 examples/dfp/v201511/line_item_creative_association_service/__init__.py delete mode 100755 examples/dfp/v201511/line_item_creative_association_service/get_licas_by_statement.py delete mode 100755 examples/dfp/v201511/line_item_creative_association_service/update_licas.py delete mode 100755 examples/dfp/v201511/line_item_service/__init__.py delete mode 100755 examples/dfp/v201511/line_item_service/activate_line_items.py delete mode 100755 examples/dfp/v201511/line_item_service/get_line_items_by_statement.py delete mode 100755 examples/dfp/v201511/line_item_service/get_recently_updated_line_items.py delete mode 100755 examples/dfp/v201511/line_item_service/target_custom_criteria.py delete mode 100755 examples/dfp/v201511/line_item_service/update_line_items.py delete mode 100755 examples/dfp/v201511/network_service/__init__.py delete mode 100755 examples/dfp/v201511/network_service/get_current_network.py delete mode 100755 examples/dfp/v201511/network_service/make_test_network.py delete mode 100755 examples/dfp/v201511/order_service/__init__.py delete mode 100755 examples/dfp/v201511/order_service/approve_orders.py delete mode 100755 examples/dfp/v201511/order_service/create_orders.py delete mode 100755 examples/dfp/v201511/order_service/get_orders_by_statement.py delete mode 100755 examples/dfp/v201511/premium_rate_service/__init__.py delete mode 100755 examples/dfp/v201511/premium_rate_service/get_all_premium_rates.py delete mode 100755 examples/dfp/v201511/product_service/__init__.py delete mode 100755 examples/dfp/v201511/product_service/get_products_for_product_template.py delete mode 100755 examples/dfp/v201511/product_template_service/__init__.py delete mode 100755 examples/dfp/v201511/product_template_service/activate_product_templates.py delete mode 100755 examples/dfp/v201511/product_template_service/get_all_product_templates.py delete mode 100755 examples/dfp/v201511/product_template_service/get_sponsorship_product_templates.py delete mode 100755 examples/dfp/v201511/product_template_service/update_product_templates.py delete mode 100755 examples/dfp/v201511/proposal_line_item_service/__init__.py delete mode 100755 examples/dfp/v201511/proposal_line_item_service/get_proposal_line_items_for_proposal.py delete mode 100755 examples/dfp/v201511/proposal_line_item_service/update_proposal_line_items.py delete mode 100755 examples/dfp/v201511/proposal_service/__init__.py delete mode 100755 examples/dfp/v201511/proposal_service/get_proposals_by_statement.py delete mode 100755 examples/dfp/v201511/proposal_service/update_proposals.py delete mode 100755 examples/dfp/v201511/publisher_query_language_service/__init__.py delete mode 100755 examples/dfp/v201511/publisher_query_language_service/fetch_match_tables.py delete mode 100755 examples/dfp/v201511/publisher_query_language_service/get_geo_targets.py delete mode 100755 examples/dfp/v201511/publisher_query_language_service/get_line_items_named_like.py delete mode 100755 examples/dfp/v201511/rate_card_service/__init__.py delete mode 100755 examples/dfp/v201511/rate_card_service/get_rate_cards_priced_with_currency.py delete mode 100755 examples/dfp/v201511/report_service/__init__.py delete mode 100755 examples/dfp/v201511/report_service/run_report_with_custom_fields.py delete mode 100755 examples/dfp/v201511/report_service/run_sales_report.py delete mode 100755 examples/dfp/v201511/suggested_ad_unit_service/__init__.py delete mode 100755 examples/dfp/v201511/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py delete mode 100755 examples/dfp/v201511/team_service/__init__.py delete mode 100755 examples/dfp/v201511/team_service/create_teams.py delete mode 100755 examples/dfp/v201511/team_service/get_all_teams.py delete mode 100755 examples/dfp/v201511/team_service/get_teams_by_statement.py delete mode 100755 examples/dfp/v201511/team_service/update_teams.py delete mode 100755 examples/dfp/v201511/user_service/__init__.py delete mode 100755 examples/dfp/v201511/user_service/create_users.py delete mode 100755 examples/dfp/v201511/user_service/deactivate_users.py delete mode 100755 examples/dfp/v201511/user_service/get_all_roles.py delete mode 100755 examples/dfp/v201511/user_service/get_current_user.py delete mode 100755 examples/dfp/v201511/user_service/get_users_by_statement.py delete mode 100755 examples/dfp/v201511/user_service/update_users.py delete mode 100755 examples/dfp/v201511/user_team_association_service/__init__.py delete mode 100755 examples/dfp/v201511/user_team_association_service/get_all_user_team_associations.py delete mode 100755 examples/dfp/v201511/user_team_association_service/get_user_team_associations_for_user.py delete mode 100755 examples/dfp/v201511/workflow_request_service/__init__.py delete mode 100755 examples/dfp/v201511/workflow_request_service/trigger_workflow_external_condition_requests.py rename examples/dfp/{v201508 => v201608}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201511/activity_group_service/get_all_activity_groups.py => v201608/activity_group_service/get_active_activity_groups.py} (59%) create mode 100755 examples/dfp/v201608/activity_group_service/get_all_activity_groups.py rename examples/dfp/{v201511 => v201608}/activity_group_service/update_activity_groups.py (97%) rename examples/dfp/{v201508 => v201608}/activity_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/activity_service/create_activities.py (99%) rename examples/dfp/{v201511/activity_service/get_all_activities.py => v201608/activity_service/get_active_activities.py} (58%) create mode 100755 examples/dfp/v201608/activity_service/get_all_activities.py rename examples/dfp/{v201508 => v201608}/activity_service/update_activities.py (99%) rename examples/dfp/{v201508 => v201608}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/audience_segment_service/create_audience_segments.py (95%) rename examples/dfp/{v201511 => v201608}/audience_segment_service/get_all_audience_segments.py (65%) rename examples/dfp/{v201511 => v201608}/audience_segment_service/get_first_party_audience_segments.py (59%) rename examples/dfp/{v201511 => v201608}/audience_segment_service/populate_first_party_audience_segments.py (97%) rename examples/dfp/{v201511 => v201608}/audience_segment_service/update_audience_segments.py (98%) rename examples/dfp/{v201508 => v201608}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201508 => v201608}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201508 => v201608}/base_rate_service/get_all_base_rates.py (62%) rename examples/dfp/{v201511/base_rate_service/get_base_rates_for_a_rate_card.py => v201608/base_rate_service/get_base_rates_for_rate_card.py} (57%) rename examples/dfp/{v201508 => v201608}/base_rate_service/update_base_rates.py (99%) rename examples/dfp/{v201508 => v201608}/company_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/company_service/create_companies.py (99%) rename examples/dfp/{v201511/company_service/get_all_companies.py => v201608/company_service/get_advertisers.py} (59%) create mode 100755 examples/dfp/v201608/company_service/get_all_companies.py rename examples/dfp/{v201511 => v201608}/company_service/update_companies.py (99%) rename examples/dfp/{v201508 => v201608}/contact_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201508/order_service/get_all_orders.py => v201608/contact_service/get_all_contacts.py} (63%) rename examples/dfp/{v201511/contact_service/get_all_contacts.py => v201608/contact_service/get_uninvited_contacts.py} (60%) rename examples/dfp/{v201511 => v201608}/contact_service/update_contacts.py (99%) rename examples/dfp/{v201508 => v201608}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201511 => v201608}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201508/activity_group_service/get_all_activity_groups.py => v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py} (54%) rename examples/dfp/{v201508 => v201608}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (98%) rename examples/dfp/{v201508 => v201608}/content_service/__init__.py (100%) rename examples/dfp/{v201511/placement_service/get_all_placements.py => v201608/content_service/get_all_content.py} (63%) rename examples/dfp/{v201508 => v201608}/creative_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201511 => v201608}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201511 => v201608}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201511 => v201608}/creative_service/create_native_creative.py (99%) create mode 100755 examples/dfp/v201608/creative_service/get_all_creatives.py rename examples/dfp/{v201508/creative_service/get_all_creatives.py => v201608/creative_service/get_image_creatives.py} (57%) rename examples/dfp/{v201508 => v201608}/creative_service/update_creatives.py (99%) rename examples/dfp/{v201508 => v201608}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201508 => v201608}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201511/line_item_service/get_all_line_items.py => v201608/creative_set_service/get_all_creative_sets.py} (62%) rename examples/dfp/{v201508/creative_set_service/get_creative_sets_by_statement.py => v201608/creative_set_service/get_creative_sets_for_master_creative.py} (54%) rename examples/dfp/{v201508 => v201608}/creative_set_service/update_creative_set.py (97%) rename examples/dfp/{v201508 => v201608}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/creative_template_service/get_all_creative_templates.py (61%) rename examples/dfp/{v201511/creative_template_service/get_all_creative_templates.py => v201608/creative_template_service/get_system_defined_creative_templates.py} (58%) rename examples/dfp/{v201508 => v201608}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/dfp/{v201511 => v201608}/creative_wrapper_service/deactivate_creative_wrapper.py (97%) rename examples/dfp/{v201508/creative_wrapper_service/get_all_creative_wrappers.py => v201608/creative_wrapper_service/get_active_creative_wrappers.py} (58%) rename examples/dfp/{v201511/suggested_ad_unit_service/get_all_suggested_ad_units.py => v201608/creative_wrapper_service/get_all_creative_wrappers.py} (60%) rename examples/dfp/{v201508 => v201608}/creative_wrapper_service/update_creative_wrappers.py (97%) rename examples/dfp/{v201508 => v201608}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201511 => v201608}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201508 => v201608}/custom_field_service/deactivate_all_line_item_custom_fields.py (98%) rename examples/dfp/{v201508 => v201608}/custom_field_service/get_all_custom_fields.py (67%) rename examples/dfp/{v201511/custom_field_service/get_all_custom_fields.py => v201608/custom_field_service/get_custom_fields_for_line_items.py} (61%) rename examples/dfp/{v201511 => v201608}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201511 => v201608}/custom_field_service/update_custom_fields.py (98%) rename examples/dfp/{v201508 => v201608}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201511 => v201608}/custom_targeting_service/delete_custom_targeting_keys.py (98%) rename examples/dfp/{v201508 => v201608}/custom_targeting_service/delete_custom_targeting_values.py (98%) create mode 100755 examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py create mode 100755 examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename examples/dfp/{v201508 => v201608}/custom_targeting_service/update_custom_targeting_keys.py (97%) rename examples/dfp/{v201508 => v201608}/custom_targeting_service/update_custom_targeting_values.py (97%) rename examples/dfp/{v201508 => v201608}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201511 => v201608}/exchange_rate_service/get_all_exchange_rates.py (57%) rename examples/dfp/{v201508/exchange_rate_service/get_exchange_rates_by_currency_code.py => v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py} (59%) rename examples/dfp/{v201508 => v201608}/exchange_rate_service/update_exchange_rates.py (97%) rename examples/dfp/{v201508 => v201608}/inventory_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/inventory_service/archive_ad_units.py (99%) rename examples/dfp/{v201511 => v201608}/inventory_service/create_ad_units.py (97%) create mode 100755 examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py create mode 100755 examples/dfp/v201608/inventory_service/get_all_ad_units.py rename examples/dfp/{v201508 => v201608}/inventory_service/update_ad_units.py (99%) rename examples/dfp/{v201508 => v201608}/label_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/label_service/create_labels.py (99%) rename examples/dfp/{v201508 => v201608}/label_service/deactivate_labels.py (99%) rename examples/dfp/{v201511/label_service/get_labels_by_statement.py => v201608/label_service/get_active_labels.py} (63%) rename examples/dfp/{v201511 => v201608}/label_service/get_all_labels.py (73%) rename examples/dfp/{v201508 => v201608}/label_service/update_labels.py (99%) rename examples/dfp/{v201508 => v201608}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201511 => v201608}/line_item_creative_association_service/deactivate_licas.py (97%) rename examples/dfp/{v201511 => v201608}/line_item_creative_association_service/get_all_licas.py (56%) rename examples/dfp/{v201508/line_item_creative_association_service/get_licas_by_statement.py => v201608/line_item_creative_association_service/get_licas_for_line_item.py} (52%) rename examples/dfp/{v201508 => v201608}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201508 => v201608}/line_item_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/line_item_service/activate_line_items.py (99%) rename examples/dfp/{v201511 => v201608}/line_item_service/create_line_items.py (99%) rename examples/dfp/{v201511 => v201608}/line_item_service/create_video_line_item.py (99%) rename examples/dfp/{v201508 => v201608}/line_item_service/get_all_line_items.py (68%) create mode 100755 examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py create mode 100755 examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py rename examples/dfp/{v201508 => v201608}/line_item_service/target_custom_criteria.py (99%) rename examples/dfp/{v201508 => v201608}/line_item_service/update_line_items.py (99%) rename examples/dfp/{v201508 => v201608}/network_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/network_service/get_all_networks.py (69%) rename examples/dfp/{v201508 => v201608}/network_service/make_test_network.py (99%) rename examples/dfp/{v201508 => v201608}/order_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/order_service/approve_orders.py (99%) rename examples/dfp/{v201508 => v201608}/order_service/create_orders.py (99%) rename examples/dfp/{v201511 => v201608}/order_service/get_all_orders.py (73%) create mode 100755 examples/dfp/v201608/order_service/get_orders_starting_soon.py rename examples/dfp/{v201511 => v201608}/order_service/update_orders.py (99%) rename examples/dfp/{v201508/label_service/get_all_labels.py => v201608/package_service/get_all_packages.py} (63%) rename examples/dfp/{v201508/placement_service/get_placements_by_statement.py => v201608/package_service/get_in_progress_packages.py} (58%) rename examples/dfp/{v201511 => v201608}/placement_service/create_placements.py (99%) rename examples/dfp/{v201511 => v201608}/placement_service/deactivate_placements.py (99%) rename examples/dfp/{v201511/placement_service/get_placements_by_statement.py => v201608/placement_service/get_active_placements.py} (64%) rename examples/dfp/{v201508 => v201608}/placement_service/get_all_placements.py (68%) rename examples/dfp/{v201511 => v201608}/placement_service/update_placements.py (99%) rename examples/dfp/{v201508 => v201608}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/premium_rate_service/create_premium_rates.py (97%) rename examples/dfp/{v201508 => v201608}/premium_rate_service/get_all_premium_rates.py (61%) rename examples/dfp/{v201511/premium_rate_service/get_premium_rates_for_a_rate_card.py => v201608/premium_rate_service/get_premium_rates_for_rate_card.py} (58%) rename examples/dfp/{v201511 => v201608}/premium_rate_service/update_premium_rates.py (97%) rename examples/dfp/{v201508/company_service/get_all_companies.py => v201608/product_package_item_service/get_all_product_package_items.py} (56%) create mode 100755 examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py rename examples/dfp/{v201508/custom_targeting_service/get_custom_targeting_keys_by_statement.py => v201608/product_package_service/get_active_product_packages.py} (56%) create mode 100755 examples/dfp/v201608/product_package_service/get_all_product_packages.py rename examples/dfp/{v201508 => v201608}/product_service/__init__.py (100%) create mode 100755 examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py rename examples/dfp/{v201511 => v201608}/product_service/get_all_products.py (72%) rename examples/dfp/{v201508 => v201608}/product_service/get_products_for_product_template.py (70%) rename examples/dfp/{v201508/product_service/update_products.py => v201608/product_service/publish_programmatic_products_to_marketplace.py} (56%) rename examples/dfp/{v201511 => v201608}/product_service/update_products.py (99%) rename examples/dfp/{v201508 => v201608}/product_template_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/product_template_service/activate_product_templates.py (97%) rename examples/dfp/{v201511 => v201608}/product_template_service/create_product_templates.py (97%) rename examples/dfp/{v201508/product_template_service/create_product_templates.py => v201608/product_template_service/create_programmatic_product_templates.py} (66%) rename examples/dfp/{v201508 => v201608}/product_template_service/get_all_product_templates.py (68%) rename examples/dfp/{v201508 => v201608}/product_template_service/get_sponsorship_product_templates.py (63%) rename examples/dfp/{v201508 => v201608}/product_template_service/update_product_templates.py (98%) rename examples/dfp/{v201508 => v201608}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/proposal_line_item_service/archive_proposal_line_items.py (98%) rename examples/dfp/{v201508/proposal_line_item_service/create_proposal_line_items.py => v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py} (76%) create mode 100755 examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename examples/dfp/{v201511 => v201608}/proposal_line_item_service/create_proposal_line_items.py (97%) rename examples/dfp/{v201511 => v201608}/proposal_line_item_service/get_all_proposal_line_items.py (60%) rename examples/dfp/{v201508/proposal_line_item_service/get_all_proposal_line_items.py => v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py} (54%) rename examples/dfp/{v201508 => v201608}/proposal_line_item_service/update_proposal_line_items.py (94%) rename examples/dfp/{v201508 => v201608}/proposal_service/__init__.py (100%) rename examples/dfp/{v201511/proposal_service/create_proposals.py => v201608/proposal_service/create_programmatic_proposals.py} (62%) create mode 100755 examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename examples/dfp/{v201508 => v201608}/proposal_service/create_proposals.py (96%) rename examples/dfp/{v201511 => v201608}/proposal_service/get_all_proposals.py (72%) create mode 100755 examples/dfp/v201608/proposal_service/get_marketplace_comments.py rename examples/dfp/{v201508/proposal_service/get_proposals_by_statement.py => v201608/proposal_service/get_proposals_pending_approval.py} (66%) rename examples/dfp/{v201511/proposal_service/submit_proposals_for_approval.py => v201608/proposal_service/request_buyers_acceptance.py} (66%) rename examples/dfp/{v201508 => v201608}/proposal_service/submit_proposals_for_approval.py (99%) rename examples/dfp/{v201508 => v201608}/proposal_service/update_proposals.py (93%) rename examples/dfp/{v201508 => v201608}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/dfp/{v201508/publisher_query_language_service/get_line_items_named_like.py => v201608/publisher_query_language_service/get_all_programmatic_buyers.py} (57%) rename examples/dfp/{v201508 => v201608}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/rate_card_service/get_all_rate_cards.py (64%) rename examples/dfp/{v201508/rate_card_service/get_rate_cards_priced_with_currency.py => v201608/rate_card_service/get_marketplace_rate_cards.py} (58%) create mode 100755 examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py create mode 100755 examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py create mode 100755 examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename examples/dfp/{v201508/audience_segment_service/get_all_audience_segments.py => v201608/reconciliation_report_service/get_all_reconciliation_reports.py} (54%) create mode 100755 examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename examples/dfp/{v201508 => v201608}/report_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/report_service/run_delivery_report.py (97%) rename examples/dfp/{v201511 => v201608}/report_service/run_inventory_report.py (97%) rename examples/dfp/{v201511 => v201608}/report_service/run_reach_report.py (96%) rename examples/dfp/{v201508 => v201608}/report_service/run_report_with_custom_fields.py (97%) rename examples/dfp/{v201508 => v201608}/report_service/run_sales_report.py (96%) create mode 100755 examples/dfp/v201608/report_service/run_saved_query.py rename examples/dfp/{v201508 => v201608}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/dfp/{v201508 => v201608}/suggested_ad_unit_service/get_all_suggested_ad_units.py (69%) rename examples/dfp/{v201508/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py => v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py} (58%) rename examples/dfp/{v201508 => v201608}/team_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/team_service/create_teams.py (96%) rename examples/dfp/{v201508 => v201608}/team_service/get_all_teams.py (67%) rename examples/dfp/{v201508 => v201608}/team_service/update_teams.py (73%) rename examples/dfp/{v201508 => v201608}/user_service/__init__.py (100%) rename examples/dfp/{v201508 => v201608}/user_service/create_users.py (94%) rename examples/dfp/{v201508 => v201608}/user_service/deactivate_users.py (97%) rename examples/dfp/{v201508 => v201608}/user_service/get_all_roles.py (70%) rename examples/dfp/{v201508 => v201608}/user_service/get_all_users.py (70%) rename examples/dfp/{v201511/user_service/get_all_users.py => v201608/user_service/get_user_by_email_address.py} (56%) rename examples/dfp/{v201508 => v201608}/user_service/update_users.py (96%) rename examples/dfp/{v201508 => v201608}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201511 => v201608}/user_team_association_service/delete_user_team_associations.py (98%) rename examples/dfp/{v201508 => v201608}/user_team_association_service/get_all_user_team_associations.py (63%) rename examples/dfp/{v201508 => v201608}/user_team_association_service/get_user_team_associations_for_user.py (59%) rename examples/dfp/{v201511 => v201608}/user_team_association_service/update_user_team_associations.py (98%) rename examples/dfp/{v201508 => v201608}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201511 => v201608}/workflow_request_service/approve_workflow_approval_requests.py (97%) rename examples/dfp/{v201511/workflow_request_service/get_workflow_approval_requests_by_statement.py => v201608/workflow_request_service/get_workflow_approval_requests.py} (62%) rename examples/dfp/{v201511/workflow_request_service/get_workflow_external_condition_requests_by_statement.py => v201608/workflow_request_service/get_workflow_external_condition_requests.py} (61%) rename examples/dfp/{v201508 => v201608}/workflow_request_service/trigger_workflow_external_condition_requests.py (98%) diff --git a/ChangeLog b/ChangeLog index fe1d1e76..9ac308f8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +4.4.0 -- 8/23/2016 +* Removed support for DFP v201505. +* Added support for DFP v201608. +* Removed examples for DFP v201508 and v201511. + 4.3.0 -- 7/29/2016 * Added support for AdWords v201607. diff --git a/examples/dfp/v201508/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201508/activity_group_service/get_active_activity_groups.py deleted file mode 100755 index c6cd26ed..00000000 --- a/examples/dfp/v201508/activity_group_service/get_active_activity_groups.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active activity groups. - -To create activity groups, run create_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201508') - - # Create statement object to only select active activity groups. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get activity groups by statement. - while True: - response = activity_group_service.getActivityGroupsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity_group in response['results']: - print ('Activity group with ID \'%s\' and name \'%s\' was found.' - % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/activity_group_service/update_activity_groups.py b/examples/dfp/v201508/activity_group_service/update_activity_groups.py deleted file mode 100755 index 1220eaeb..00000000 --- a/examples/dfp/v201508/activity_group_service/update_activity_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates activity groups. - -To determine which activity groups exist, run get_all_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the activity group and the company to update it with. -ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' -ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, activity_group_id, advertiser_company_id): - # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201508') - - # Create statement object to select a single activity groups by ID. - values = [{ - 'key': 'activityGroupId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_group_id - } - }] - query = 'WHERE id = :activityGroupId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) - - # Get activity groups by statement. - response = activity_group_service.getActivityGroupsByStatement( - statement.ToStatement()) - if 'results' in response: - updated_activity_groups = [] - for activity_group in response['results']: - activity_group['companyIds'].append(advertiser_company_id) - updated_activity_groups.append(activity_group) - # Update the activity groups on the server. - activity_groups = activity_group_service.updateActivityGroups( - updated_activity_groups) - - for activity_group in activity_groups: - print (('Activity group with ID \'%s\' and name \'%s\' was updated.') - % (activity_group['id'], activity_group['name'])) - else: - print 'No activity groups found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) diff --git a/examples/dfp/v201508/activity_service/create_activities.py b/examples/dfp/v201508/activity_service/create_activities.py deleted file mode 100755 index b1bb4812..00000000 --- a/examples/dfp/v201508/activity_service/create_activities.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new activities. - -To determine which activities groups exist, run get_all_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the activity group this activity is associated with. -ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' - - -def main(client, activity_group_id): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201508') - - # Create a daily visits activity. - daily_visits_activity = { - 'name': 'Activity #%s' % uuid.uuid4(), - 'activityGroupId': activity_group_id, - 'type': 'DAILY_VISITS' - } - - # Create a custom activity. - custom_activity = { - 'name': 'Activity #%s' % uuid.uuid4(), - 'activityGroupId': activity_group_id, - 'type': 'CUSTOM' - } - - # Create the activities on the server. - activities = activity_service.createActivities([ - daily_visits_activity, custom_activity]) - - # Display results. - for activity in activities: - print ('An activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'created.' % (activity['id'], activity['name'], activity['type'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_GROUP_ID) diff --git a/examples/dfp/v201508/activity_service/get_active_activities.py b/examples/dfp/v201508/activity_service/get_active_activities.py deleted file mode 100755 index e2d1d647..00000000 --- a/examples/dfp/v201508/activity_service/get_active_activities.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active activities. - -To create activities, run create_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201508') - - # Create statement object to only select active activities. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get activities by statement. - while True: - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity in response['results']: - print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (activity['id'], activity['name'], activity['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/activity_service/get_all_activities.py b/examples/dfp/v201508/activity_service/get_all_activities.py deleted file mode 100755 index c953b823..00000000 --- a/examples/dfp/v201508/activity_service/get_all_activities.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all activities. - -To create activities, run create_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201508') - - # Create statement object to select only all activities. - statement = dfp.FilterStatement() - - # Get activities by statement. - while True: - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity in response['results']: - print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (activity['id'], activity['name'], activity['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/audience_segment_service/create_audience_segments.py b/examples/dfp/v201508/audience_segment_service/create_audience_segments.py deleted file mode 100755 index fe1cff5c..00000000 --- a/examples/dfp/v201508/audience_segment_service/create_audience_segments.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates a new rule based first party audience segment.""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the IDs of the custom criteria to be used in the segment rule. -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' -CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' - -def main(client, custom_targeting_key_id, custom_targeting_value_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - - # Initialize appropriate services. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201508') - network_service = client.GetService('NetworkService', version='v201508') - - # Get the root ad unit ID used to target the entire network. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Create inventory targeting (pointed at root ad unit i.e. the whole network) - inventory_targeting = { - 'targetedAdUnits': [ - {'adUnitId': root_ad_unit_id} - ] - } - - # Create custom criteria. - custom_criteria = [ - { - 'xsi_type': 'CustomCriteria', - 'keyId': custom_targeting_key_id, - 'valueIds': [custom_targeting_value_id], - 'operator': 'IS' - } - ] - - # Create the custom criteria set. - top_custom_criteria_set = { - 'logicalOperator': 'AND', - 'children': custom_criteria - } - - # Create the audience segment rule. - rule = { - 'inventoryRule': inventory_targeting, - 'customCriteriaRule': top_custom_criteria_set - } - - # Create an audience segment. - audience_segment = [ - { - 'xsi_type': 'RuleBasedFirstPartyAudienceSegment', - 'name': ('Sports enthusiasts audience segment %s' % - uuid.uuid4()), - 'description': 'Sports enthusiasts between the ages of 20 and 30', - 'pageViews': '6', - 'recencyDays': '6', - 'membershipExpirationDays': '88', - 'rule': rule - } - ] - - audience_segments = ( - audience_segment_service.createAudienceSegments(audience_segment)) - - for created_audience_segment in audience_segments: - print ('An audience segment with ID \'%s\', name \'%s\', and type \'%s\' ' - 'was created.' % (created_audience_segment['id'], - created_audience_segment['name'], - created_audience_segment['type'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201508/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201508/audience_segment_service/get_first_party_audience_segments.py deleted file mode 100755 index bee6f37a..00000000 --- a/examples/dfp/v201508/audience_segment_service/get_first_party_audience_segments.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all first party audience segments. - -To create first party audience segments, run create_audience_segments.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - - # Initialize appropriate service. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201508') - - # Create statement object to only select first party audience segments. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }] - query = 'WHERE Type = :type' - statement = dfp.FilterStatement(query, values) - - # Get audience segments by statement. - while True: - response = audience_segment_service.getAudienceSegmentsByStatement( - statement.ToStatement()) - - if 'results' in response: - segments = response['results'] - for segment in segments: - print ('Audience segment with id \'%s\' and name \'%s\' of size ' - '%s was found. ' % - (segment['id'], segment['name'], segment['size'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201508/audience_segment_service/populate_first_party_audience_segments.py deleted file mode 100755 index 43402066..00000000 --- a/examples/dfp/v201508/audience_segment_service/populate_first_party_audience_segments.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 populates a specific first party audience segment. - -To determine which first party audience segments exist, run -get_first_party_audience_segments.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' - - -def main(client, audience_segment_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - - # Initialize appropriate service. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201508') - - # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': AUDIENCE_SEGMENT_ID - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) - - response = audience_segment_service.getAudienceSegmentsByStatement( - statement.ToStatement()) - - if 'results' in response: - segments = response['results'] - - for segment in segments: - print ('Audience segment with id \'%s\' and name \'%s\' will be populated.' - % (segment['id'], segment['name'])) - - action = { - 'xsi_type': 'PopulateAudienceSegments' - } - - populated_audience_segments = ( - audience_segment_service.performAudienceSegmentAction( - action, statement.ToStatement())) - - print ('%s audience segment populated' % - populated_audience_segments['numChanges']) - else: - print 'No Results Found' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/dfp/v201508/audience_segment_service/update_audience_segments.py b/examples/dfp/v201508/audience_segment_service/update_audience_segments.py deleted file mode 100755 index 230c3a5c..00000000 --- a/examples/dfp/v201508/audience_segment_service/update_audience_segments.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates rule based first party audience segments. - -To determine which audience segments exist, run get_all_audience_segments.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' - - -def main(client, audience_segment_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - - # Initialize appropriate service. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201508') - - # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': AUDIENCE_SEGMENT_ID - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) - - # Get audience segments by statement. - response = audience_segment_service.getAudienceSegmentsByStatement( - statement.ToStatement()) - - if 'results' in response: - updated_audience_segments = [] - for audience_segment in response['results']: - print ('Audience segment with id \'%s\' and name \'%s\' will be updated.' - % (audience_segment['id'], audience_segment['name'])) - - audience_segment['membershipExpirationDays'] = '180' - updated_audience_segments.append(audience_segment) - - audience_segments = audience_segment_service.updateAudienceSegments( - updated_audience_segments) - - for audience_segment in audience_segments: - print ('Audience segment with id \'%s\' and name \'%s\' was updated' % - (audience_segment['id'], audience_segment['name'])) - else: - print 'No audience segment found to update.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/dfp/v201508/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201508/base_rate_service/get_base_rates_for_a_rate_card.py deleted file mode 100755 index b3ed2345..00000000 --- a/examples/dfp/v201508/base_rate_service/get_base_rates_for_a_rate_card.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 base rates. - -To create product base rates, run create_product_base_rates.py -To create product template base rates, run -create_product_template_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201508') - - # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'rateCardId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': rate_card_id - } - }] - query = 'where rateCardId = :rateCardId ORDER BY id ASC' - statement = dfp.FilterStatement(query, values) - - # Get base rates by statement. - while True: - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for base_rate in response['results']: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was found.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201508/company_service/create_companies.py b/examples/dfp/v201508/company_service/create_companies.py deleted file mode 100755 index 43a43c2a..00000000 --- a/examples/dfp/v201508/company_service/create_companies.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new companies. - -To determine which companies exist, run get_all_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201508') - - # Create company objects. - companies = [ - { - 'name': 'Advertiser #%s' % uuid.uuid4(), - 'type': 'ADVERTISER' - }, - { - 'name': 'Agency #%s' % uuid.uuid4(), - 'type': 'AGENCY' - } - ] - - # Add companies. - companies = company_service.createCompanies(companies) - - # Display results. - for company in companies: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.' - % (company['id'], company['name'], company['type'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/company_service/get_advertisers.py b/examples/dfp/v201508/company_service/get_advertisers.py deleted file mode 100755 index 487f099f..00000000 --- a/examples/dfp/v201508/company_service/get_advertisers.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all companies that are advertisers. - -To create companies, run create_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201508') - - # Create statement object to only select companies that are advertisers. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - } - }] - query = 'WHERE type = :type' - statement = dfp.FilterStatement(query, values) - - # Get companies by statement. - while True: - response = company_service.getCompaniesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for company in response['results']: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.' - % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/company_service/update_companies.py b/examples/dfp/v201508/company_service/update_companies.py deleted file mode 100755 index 59ee492d..00000000 --- a/examples/dfp/v201508/company_service/update_companies.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates company comments. - -To determine which companies exist, run get_all_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the company to update. -COMPANY_ID = 'INSERT_COMPANY_ID_HERE' - - -def main(client, company_id): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201508') - - # Create statement object to only select a single company by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': company_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - # Get companies by statement. - response = company_service.getCompaniesByStatement( - statement.ToStatement()) - if 'results' in response: - updated_companies = [] - for company in response['results']: - company['comment'] += ' Updated.' - updated_companies.append(company) - - # Update the companies on the server. - companies = company_service.updateCompanies(updated_companies) - - # Display results. - for company in companies: - print (('Company with ID \'%s\', name \'%s\', and comment \'%s\'' - 'was updated.') - % (company['id'], company['name'], company['comment'])) - else: - print 'No companies found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, COMPANY_ID) diff --git a/examples/dfp/v201508/contact_service/get_all_contacts.py b/examples/dfp/v201508/contact_service/get_all_contacts.py deleted file mode 100755 index fc089821..00000000 --- a/examples/dfp/v201508/contact_service/get_all_contacts.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all contacts. - -To create contacts, run create_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201508') - - # Create statement object to get all contacts. - statement = dfp.FilterStatement() - - # Get contacts by statement. - while True: - response = contact_service.getContactsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for contact in response['results']: - print ('Contact with ID \'%s\' and name \'%s\' was found.' - % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/contact_service/get_uninvited_contacts.py b/examples/dfp/v201508/contact_service/get_uninvited_contacts.py deleted file mode 100755 index 5ac7d861..00000000 --- a/examples/dfp/v201508/contact_service/get_uninvited_contacts.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all contacts that aren't invited yet. - -To create contacts, run create_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201508') - - # Create statement object to only select contacts that are uninvited. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get contacts by statement. - while True: - response = contact_service.getContactsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for contact in response['results']: - print ('Contact with ID \'%s\' and name \'%s\' was found.' - % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/contact_service/update_contacts.py b/examples/dfp/v201508/contact_service/update_contacts.py deleted file mode 100755 index a0c17015..00000000 --- a/examples/dfp/v201508/contact_service/update_contacts.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates contact addresses. - -To determine which contacts exist, run get_all_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the contact to update. -CONTACT_ID = 'INSERT_CONTACT_ID_HERE' - - -def main(client, contact_id): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201508') - - # Create statement object to select the single contact by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': contact_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - # Get contacts by statement. - response = contact_service.getContactsByStatement( - statement.ToStatement()) - - if 'results' in response: - updated_contacts = [] - for contact in response['results']: - contact['address'] = '123 New Street, New York, NY, 10011' - updated_contacts.append(contact) - - # Update the contact on the server. - contacts = contact_service.updateContacts(updated_contacts) - - # Display results. - for contact in contacts: - print (('Contact with ID \'%s\', name \'%s\', and address \'%s\' ' - 'was updated.') - % (contact['id'], contact['name'], contact['address'])) - else: - print 'No contacts found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTACT_ID) diff --git a/examples/dfp/v201508/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201508/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py deleted file mode 100755 index cf3a5319..00000000 --- a/examples/dfp/v201508/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the IDs of the custom targeting keys for the hierarchy. -HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' -HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201508') - - hierarchy_level_1 = { - 'customTargetingKeyId': hierarchy_level_one_key_id, - 'hierarchyLevel': '1' - } - - hierarchy_level_2 = { - 'customTargetingKeyId': hierarchy_level_two_key_id, - 'hierarchyLevel': '2' - } - - hierarchy_levels = [hierarchy_level_1, hierarchy_level_2] - - # Create content metadata key hierarchy object. - content_metadata_key_hierarchy = { - 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(), - 'hierarchyLevels': hierarchy_levels - } - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy])) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id \'%s\' and name \'%s\'' - ' was created.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, HIERARCHY_LEVEL_ONE_KEY_ID, HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/dfp/v201508/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201508/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py deleted file mode 100755 index 1076efbb..00000000 --- a/examples/dfp/v201508/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example deletes content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the content metadata key hierarchy to delete. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') - - -def main(client, content_metadata_key_hierarchy_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201508') - - # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())[0]) - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - # Display results. - if content_metadata_key_hierarchies: - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with ID \'%s\' and name \'%s\' ' - 'will be deleted.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - # Perform action. - result = (content_metadata_key_hierarchy_service - .performContentMetadataKeyHierarchyAction( - {'type': 'DeleteContentMetadataKeyHierarchies'}, - statement.ToStatement()))[0] - - # Display results. - print ('Number of content metadata key hierarchies deleted: %s' % - result['numChanges']) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID) diff --git a/examples/dfp/v201508/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201508/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py deleted file mode 100755 index 7797e571..00000000 --- a/examples/dfp/v201508/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all content metadata key hierarchies. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201508') - - # Create statement object to select all content. - statement = dfp.FilterStatement() - - # Get content by statement. - while True: - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())[0]) - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - if content_metadata_key_hierarchies: - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchyy with id \'%s\' and name \'%s\'' - ' was found.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/content_service/get_all_content.py b/examples/dfp/v201508/content_service/get_all_content.py deleted file mode 100755 index 6c4e5499..00000000 --- a/examples/dfp/v201508/content_service/get_all_content.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all content. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201508') - - # Create statement object to select all content. - statement = dfp.FilterStatement() - - # Get content by statement. - while True: - response = content_service.getContentByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for content_item in response['results']: - print ('Content with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (content_item['id'], content_item['name'], - content_item['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/content_service/get_content_by_category.py b/examples/dfp/v201508/content_service/get_content_by_category.py deleted file mode 100755 index ba20d5a9..00000000 --- a/examples/dfp/v201508/content_service/get_content_by_category.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active content categorized as a "comedy" using the -network's content browse custom targeting key. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201508') - network_service = client.GetService('NetworkService', version='v201508') - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') - - # Get the network's content browse custom targeting key. - network = network_service.getCurrentNetwork() - key_id = network['contentBrowseCustomTargetingKeyId'] - - # Create a statement to select the categories matching the name comedy. - values = [ - { - 'key': 'contentBrowseCustomTargetingKeyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }, - { - 'key': 'category', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'comedy' - } - } - ] - category_filter_query = ('WHERE customTargetingKeyId = ' - ':contentBrowseCustomTargetingKeyId and name = ' - ':category') - category_filter_statement = dfp.FilterStatement( - category_filter_query, values, 1) - - # Get categories matching the filter statement. - response = custom_targeting_service.getCustomTargetingValuesByStatement( - category_filter_statement.ToStatement()) - - # Get the custom targeting value ID for the comedy category. - if 'results' in response: - category_custom_targeting_value_id = (response['results']['id']) - - # Create a statement to select the active content. - content_values = [ - { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - } - ] - content_query = 'WHERE status = :status' - content_statement = dfp.FilterStatement(content_query, content_values) - - while True: - # Get the content by statement and custom targeting value. - response = content_service.getContentByStatementAndCustomTargetingValue( - content_statement.ToStatement(), - category_custom_targeting_value_id) - if 'results' in response: - # Display results. - for content_item in response['results']: - print ('Content with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (content_item['id'], content_item['name'], - content_item['status'])) - content_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/creative_service/create_creatives.py b/examples/dfp/v201508/creative_service/create_creatives.py deleted file mode 100755 index 008ac0e2..00000000 --- a/examples/dfp/v201508/creative_service/create_creatives.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new image creatives for a given advertiser. - -To determine which companies are advertisers, run get_advertisers.py. -To determine which creatives already exist, run get_all_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import os -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the advertiser (company) that all creatives will be assigned to. -ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201508') - - # Create creative objects. - creatives = [] - with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r') as image: - image_data = base64.encodestring(image.read()) - - for i in xrange(5): - # Create creative size. - size = { - 'width': '300', - 'height': '250' - } - - # Create image asset. - creative_asset = { - 'xsi_type': 'CreativeAsset', - 'fileName': 'image.jpg', - 'assetByteArray': image_data, - 'size': size - } - - # Create an image creative. - creative = { - 'xsi_type': 'ImageCreative', - 'name': 'Image Creative #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'destinationUrl': 'http://google.com', - 'size': size, - 'primaryImageAsset': creative_asset - } - - creatives.append(creative) - - # Add creatives. - creatives = creative_service.createCreatives(creatives) - - # Display results. - for creative in creatives: - print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201508/creative_service/create_custom_creative.py b/examples/dfp/v201508/creative_service/create_custom_creative.py deleted file mode 100755 index 8e2eb1ae..00000000 --- a/examples/dfp/v201508/creative_service/create_custom_creative.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates a custom creative for a given advertiser. - -This feature is only available to DFP premium solution networks. To determine -which companies are advertisers, run get_advertisers.py. To determine -which creative templates exist, run get_all_creative_templates.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import os -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the advertiser (company) that the creative will be assigned to. -ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201508') - - # Get the image data for the creative. - image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r').read() - image_data = base64.encodestring(image_data) - - # Create the HTML snippet used in the custom creative. - html_snippet = ('
Click above for ' - 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%', - '%%FILE:IMAGE_ASSET%%') - - # Create custom creative. - creative = { - 'xsi_type': 'CustomCreative', - 'name': 'Custom Creative #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'size': {'width': '300', 'height': '250'}, - 'destinationUrl': 'http://google.com', - 'customCreativeAssets': [ - { - 'xsi_type': 'CustomCreativeAsset', - 'macroName': 'IMAGE_ASSET', - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() - } - ], - 'htmlSnippet': html_snippet - } - - # Call service to create the creative. - creatives = creative_service.createCreatives([creative]) - - # Display results. - if creatives: - creative = creatives[0] - print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201508/creative_service/create_native_creative.py b/examples/dfp/v201508/creative_service/create_native_creative.py deleted file mode 100755 index d5939e91..00000000 --- a/examples/dfp/v201508/creative_service/create_native_creative.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates a new native creative for a given advertiser. - -To determine which companies are advertisers, run get_advertisers.py. - -The code in this example will use app data from the Google sample app -'Pie Noon': - -https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import base64 -import urllib2 -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the advertiser (company) that the creative will be assigned to. -ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' -ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO' - 'PYnTdOQGaSpGSEZflIFs0iw=h300') -APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp' - 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300') - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201508') - - # Use the system defined native app install creative template. - creative_template_id = '10004400' - - image_data = urllib2.urlopen(ICON_URL).read() - image_data = base64.b64encode(image_data) - - app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - app_icon_data = base64.b64encode(app_icon_data) - - # Create creative from templates. - creative = { - 'xsi_type': 'TemplateCreative', - 'name': 'Native Creative #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'size': {'width': '1', 'height': '1', 'isAspectRatio': False}, - 'creativeTemplateId': creative_template_id, - 'destinationUrl': ('https://play.google.com/store/apps/details?id=' - 'com.google.fpl.pie_noon'), - 'creativeTemplateVariableValues': [ - { - 'xsi_type': 'AssetCreativeTemplateVariableValue', - 'uniqueName': 'Image', - 'assetByteArray': image_data, - 'fileName': 'file%s.png' % uuid.uuid4() - }, - { - 'xsi_type': 'AssetCreativeTemplateVariableValue', - 'uniqueName': 'Appicon', - 'assetByteArray': app_icon_data, - 'fileName': 'appicon%s.png' % uuid.uuid4() - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Price', - 'value': 'Free' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Calltoaction', - 'value': 'Install' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Starrating', - 'value': '4' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Store', - 'value': 'Google Play' - }, - { - 'xsi_type': 'UrlCreativeTemplateVariableValue', - 'uniqueName': 'DeeplinkclickactionURL', - 'value': 'market://details?id=com.google.fpl.pie_noon' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Body', - 'value': 'Try multi-screen mode!' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Headline', - 'value': 'Pie Noon' - } - ] - } - - # Call service to create the creative. - creative = creative_service.createCreatives([creative])[0] - - # Display results. - print ('Native creative with id \'%s\' and name \'%s\' was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['previewUrl'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201508/creative_service/get_creatives_by_statement.py b/examples/dfp/v201508/creative_service/get_creatives_by_statement.py deleted file mode 100755 index 83093abd..00000000 --- a/examples/dfp/v201508/creative_service/get_creatives_by_statement.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all image creatives. - -To create an image creative, run create_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201508') - - # Create statement object to only select image creatives. - values = [{ - 'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }] - query = 'WHERE creativeType = :creativeType' - statement = dfp.FilterStatement(query, values) - - # Get creatives by statement. - while True: - response = creative_service.getCreativesByStatement( - statement.ToStatement()) - creatives = response['results'] - - if creatives: - # Display results. - for creative in creatives: - print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (creative['id'], creative['name'], - dfp.DfpClassType(creative))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201508/creative_set_service/get_all_creative_sets.py deleted file mode 100755 index a03667c9..00000000 --- a/examples/dfp/v201508/creative_set_service/get_all_creative_sets.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all creative sets. - -To create creative sets, run create_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201508') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get creative sets by statement. - while True: - response = creative_set_service.getCreativeSetsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_set in response['results']: - print ('Creative set with ID \'%s\' and name \'%s\' was found.' - % (creative_set['id'], creative_set['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201508/creative_template_service/get_creative_templates_by_statement.py deleted file mode 100755 index 7c825ac7..00000000 --- a/examples/dfp/v201508/creative_template_service/get_creative_templates_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all system defined creative templates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201508') - - # Create statement object to only select system defined creative templates. - values = [{ - 'key': 'creativeTemplateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - } - }] - query = 'WHERE type = :creativeTemplateType' - statement = dfp.FilterStatement(query, values) - - # Get creative templates by statement. - while True: - response = creative_template_service.getCreativeTemplatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for template in response['results']: - print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' ' - 'was found.' % (template['id'], - template['name'], - template['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201508/creative_wrapper_service/deactivate_creative_wrapper.py deleted file mode 100755 index 3575b2d0..00000000 --- a/examples/dfp/v201508/creative_wrapper_service/deactivate_creative_wrapper.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example deactivates a creative wrapper belonging to a label. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, label_id): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201508') - - # Create a query to select the active creative wrappers for the given label. - values = [{ - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status AND labelId = :labelId' - statement = dfp.FilterStatement(query, values) - - creative_wrappers_deactivated = 0 - - # Get creative wrappers by statement. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' with ' - 'status \'%s\' will be deactivated.' % - (creative_wrapper['id'], - creative_wrapper['labelId'], - creative_wrapper['status'])) - # Perform action. - result = creative_wrapper_service.performCreativeWrapperAction( - {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - creative_wrappers_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if creative_wrappers_deactivated > 0: - print ('Number of creative wrappers deactivated: %s' % - creative_wrappers_deactivated) - else: - print 'No creative wrappers were deactivated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) diff --git a/examples/dfp/v201508/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201508/creative_wrapper_service/get_active_creative_wrappers.py deleted file mode 100755 index 399f3b5b..00000000 --- a/examples/dfp/v201508/creative_wrapper_service/get_active_creative_wrappers.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active creative wrappers. - -To create creative wrappers, run create_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201508') - - # Create statement object to only select active creative wrappers. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get creative wrappers by statement. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'found.' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/custom_field_service/create_custom_field_options.py b/examples/dfp/v201508/custom_field_service/create_custom_field_options.py deleted file mode 100755 index b0a564e9..00000000 --- a/examples/dfp/v201508/custom_field_service/create_custom_field_options.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates custom field options for a drop-down custom field. - -Once created, custom field options can be found under the options fields of the -drop-down custom field and they cannot be deleted. To determine which custom -fields exist, run get_all_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the drop-down custom field to create options for. -CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' - - -def main(client, custom_field_id): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201508') - - # Create custom field options. - custom_field_options = [ - { - 'displayName': 'Approved', - 'customFieldId': custom_field_id - }, - { - 'displayName': 'Unapproved', - 'customFieldId': custom_field_id - } - ] - - # Add custom field options. - custom_field_options = custom_field_service.createCustomFieldOptions( - custom_field_options) - - # Display results. - for custom_field_option in custom_field_options: - print ('Custom field option with ID \'%s\' and name \'%s\' was created.' - % (custom_field_option['id'], custom_field_option['displayName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID) diff --git a/examples/dfp/v201508/custom_field_service/create_custom_fields.py b/examples/dfp/v201508/custom_field_service/create_custom_fields.py deleted file mode 100755 index 6ed440fe..00000000 --- a/examples/dfp/v201508/custom_field_service/create_custom_fields.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates custom fields. - -To determine which custom fields exist, run get_all_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201508') - - # Create custom field objects. - custom_fields = [ - { - 'name': 'Customer comments #%s' % uuid.uuid4(), - 'entityType': 'LINE_ITEM', - 'dataType': 'STRING', - 'visibility': 'FULL' - }, { - 'name': 'Internal approval status #%s' % uuid.uuid4(), - 'entityType': 'LINE_ITEM', - 'dataType': 'DROP_DOWN', - 'visibility': 'FULL' - } - ] - - # Add custom fields. - custom_fields = custom_field_service.createCustomFields(custom_fields) - - # Display results. - for custom_field in custom_fields: - print ('Custom field with ID \'%s\' and name \'%s\' was created.' - % (custom_field['id'], custom_field['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201508/custom_field_service/get_all_line_item_custom_fields.py deleted file mode 100755 index c0a4b4f6..00000000 --- a/examples/dfp/v201508/custom_field_service/get_all_line_item_custom_fields.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 fields that apply to line items. - -To create custom fields, run create_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201508') - - # Create statement to select only custom fields that apply to line items. - values = [{ - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }] - query = 'WHERE entityType = :entityType' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get custom fields by statement. - while True: - response = custom_field_service.getCustomFieldsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' was found.' - % (custom_field['id'], custom_field['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201508/custom_field_service/set_line_item_custom_field_value.py deleted file mode 100755 index 8fb51fe1..00000000 --- a/examples/dfp/v201508/custom_field_service/set_line_item_custom_field_value.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 sets custom field values on a line item. - -To determine which custom fields exist, run get_all_custom_fields.py. -To determine which line item exist, run get_all_line_items.py. -To create custom field options, run create_custom_field_options.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the custom fields, custom field option, and line item. -CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' -DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' -CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE' -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, custom_field_id, drop_down_custom_field_id, - custom_field_option_id, line_item_id): - # Initialize appropriate services. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201508') - - line_item_service = client.GetService('LineItemService', version='v201508') - - # Create statement to get a custom field. - custom_field_values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - custom_field_query = 'WHERE id = :customFieldId' - custom_field_statement = dfp.FilterStatement( - custom_field_query, custom_field_values, 1) - - # Get custom field. - custom_field = custom_field_service.getCustomFieldsByStatement( - custom_field_statement.ToStatement())['results'][0] - - # Create statement to get a drop down custom field. - drop_down_custom_field_values = [{ - 'key': 'dropDownCustomFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': drop_down_custom_field_id - } - }] - drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId' - drop_down_custom_field_statement = dfp.FilterStatement( - drop_down_custom_field_query, drop_down_custom_field_values, 1) - - # Get drop-down custom field. - drop_down_custom_field = custom_field_service.getCustomFieldsByStatement( - drop_down_custom_field_statement.ToStatement())['results'][0] - - # Create statement to get a line item. - line_item_values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - line_item_query = 'WHERE id = :lineItemId' - line_item_statement = dfp.FilterStatement( - line_item_query, line_item_values, 1) - - # Get line item. - line_item = line_item_service.getLineItemsByStatement( - line_item_statement.ToStatement())['results'][0] - - if custom_field and line_item: - # Create custom field values. - custom_field_value = { - 'customFieldId': custom_field['id'], - 'xsi_type': 'CustomFieldValue', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'Custom field value' - } - } - - drop_down_custom_field_value = { - 'customFieldId': drop_down_custom_field['id'], - 'xsi_type': 'DropDownCustomFieldValue', - 'customFieldOptionId': custom_field_option_id, - } - - custom_field_values = [custom_field_value, drop_down_custom_field_value] - - old_custom_field_values = [] - if 'customFieldValues' in line_item: - old_custom_field_values = line_item['customFieldValues'] - - # Only add existing custom field values for different custom fields than the - # ones you are setting. - for old_custom_field_value in old_custom_field_values: - if (old_custom_field_value['customFieldId'] != - custom_field_value['customFieldId'] - and old_custom_field_value['customFieldId'] != - drop_down_custom_field_value['customFieldId']): - custom_field_values.append(old_custom_field_value) - - line_item['customFieldValues'] = custom_field_values - - # Update the line item on the server. - line_items = line_item_service.updateLineItems([line_item]) - - # Display results. - for line_item in line_items: - custom_field_value_strings = [] - for value in line_item['customFieldValues']: - if dfp.DfpClassType(value) == 'CustomFieldValue': - custom_field_value_string = ( - '{ID: \'%s\', value: \'%s\'}' - % (value['customFieldId'], value['value']['value'])) - elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': - custom_field_value_string = ( - '{ID: \'%s\', custom field option ID: \'%s\'}' - % (value['customFieldId'], value['customFieldOptionId'])) - custom_field_value_strings.append(custom_field_value_string) - print ('Line item with ID \'%s\' set with custom field values %s.' - % (line_item['id'], ','.join(custom_field_value_strings))) - else: - print 'Line item or custom field not found.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, - CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID) diff --git a/examples/dfp/v201508/custom_field_service/update_custom_fields.py b/examples/dfp/v201508/custom_field_service/update_custom_fields.py deleted file mode 100755 index 80e6d5df..00000000 --- a/examples/dfp/v201508/custom_field_service/update_custom_fields.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates custom field descriptions. - -To determine which custom fields exist, run get_all_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the custom field to update. -CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' - - -def main(client, custom_field_id): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201508') - - # Create statement to get a custom field. - values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - query = 'WHERE id = :customFieldId' - statement = dfp.FilterStatement(query, values) - - # Get custom field. - custom_fields = custom_field_service.getCustomsFieldByStatement( - statement.ToStatement()) - - if custom_fields: - for custom_field in custom_fields: - custom_field['description'] += ' Updated.' - - # Update the custom field on the server. - custom_fields = custom_field_service.updateCustomFields(custom_fields) - - # Display results. - for custom_field in custom_fields: - print (('Custom field with ID \'%s\', name \'%s\', and ' - 'description \'%s\' was updated.') - % (custom_field['id'], custom_field['name'], - custom_field['description'])) - else: - print 'No custom fields found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID) diff --git a/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_keys.py deleted file mode 100755 index 38214918..00000000 --- a/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_keys.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes a custom targeting key by its name. - -To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE' - - -def main(client, key_name): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') - - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': key_name - } - }] - query = 'WHERE name = :name' - statement = dfp.FilterStatement(query, values) - - deleted_custom_targeting_keys = 0 - - # Get custom targeting keys. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - statement.ToStatement()) - if 'results' in response: - key_ids = [key['id'] for key in response['results']] - action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) - key_statement = dfp.FilterStatement(key_query) - - # Delete custom targeting keys. - result = custom_targeting_service.performCustomTargetingKeyAction( - action, key_statement.ToStatement()) - - if result and int(result['numChanges']) > 0: - deleted_custom_targeting_keys += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if deleted_custom_targeting_keys > 0: - print ('Number of custom targeting keys deleted: %s' - % deleted_custom_targeting_keys) - else: - print 'No custom targeting keys were deleted.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, KEY_NAME) diff --git a/examples/dfp/v201508/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201508/custom_targeting_service/get_all_custom_targeting_keys_and_values.py deleted file mode 100755 index 32cc075e..00000000 --- a/examples/dfp/v201508/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 targeting keys and the values. - -To create custom targeting keys and values, run -create_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') - - # Create statement to get all targeting keys. - targeting_key_statement = dfp.FilterStatement() - - all_keys = [] - - # Get custom targeting keys by statement. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - targeting_key_statement.ToStatement()) - if 'results' in response: - all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if all_keys: - # Create map of custom targeting key id to custom targeting values. - key_value_map = {} - - # Create statement to get all targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' - % ', '.join([str(key['id']) for key in all_keys])) - targeting_value_statement = dfp.FilterStatement(query) - - # Get custom targeting values by statement. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - targeting_value_statement.ToStatement()) - if 'results' in response: - for key in all_keys: - for value in response['results']: - if key['id'] == value['customTargetingKeyId']: - if key['id'] not in key_value_map.keys(): - key_value_map[key['id']] = [] - key_value_map[key['id']].append(value) - targeting_value_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - for key in all_keys: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was found.' - %(key['id'], key['name'], key['displayName'], key['type'])) - if key['id'] in key_value_map.keys(): - for value in key_value_map[key['id']]: - print ('\tCustom targeting value with id \'%s\', name \'%s\', and ' - 'display name \'%s\' was found.' - % (value['id'], value['name'], value['displayName'])) - else: - print 'No keys were found.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) - diff --git a/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_values_by_statement.py deleted file mode 100755 index 441b501c..00000000 --- a/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 custom targeting values for the given predefined custom -targeting key. - -To create custom targeting values, run -create_custom_targeting_keys_and_values.py. To determine which custom -targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') - - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) - - # Get custom targeting values by statement. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for value in response['results']: - print ('Custom targeting value with id \'%s\', name \'%s\', and display' - ' name \'%s\' was found.' - % (value['id'], value['name'], value['displayName'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201508/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201508/exchange_rate_service/get_all_exchange_rates.py deleted file mode 100755 index 9049d7a9..00000000 --- a/examples/dfp/v201508/exchange_rate_service/get_all_exchange_rates.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all exchange rates. - -To create exchange rates, run create_exchange_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201508') - - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') - - # Get all exchange rates by statement. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for exchange_rate in response['results']: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was found.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/forecast_service/get_availability_forecast.py b/examples/dfp/v201508/forecast_service/get_availability_forecast.py deleted file mode 100755 index f4b10c02..00000000 --- a/examples/dfp/v201508/forecast_service/get_availability_forecast.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a forecast for a prospective line item. - -The prospective line item targets the entire network. The targeting can be -modified to determine forecasts for other criteria such as custom criteria -targeting (in addition to targeting the whole network). See -create_line_items.py for an example of how to create more complex targeting. - -""" - - -from datetime import date - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the advertiser (company) to forecast for. Setting an advertiser -# will cause the forecast to apply the appropriate unified blocking rules. -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201508') - network_service = client.GetService('NetworkService', version='v201508') - - # get the root ad unit ID to target the entire network. - root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - # Create prospective line item. - line_item = { - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': [ - { - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id, - } - ] - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '300', - 'height': '250' - } - }, - { - 'size': { - 'width': '120', - 'height': '600' - } - } - ], - 'lineItemType': 'SPONSORSHIP', - 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/New_York' - }, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'DAILY' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'EVEN', - 'discountType': 'PERCENTAGE', - } - - prospective_line_item = { - 'lineItem': line_item, - 'advertiserId': advertiser_id - } - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - 'includeTargetingCriteriaBreakdown': True, - } - - # Get forecast. - forecast = forecast_service.getAvailabilityForecast( - prospective_line_item, forecast_options) - matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) - - # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) - - if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201508/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201508/forecast_service/get_availability_forecast_for_line_item.py deleted file mode 100755 index 9d3300d3..00000000 --- a/examples/dfp/v201508/forecast_service/get_availability_forecast_for_line_item.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets an availability forecast for an existing line item. - -To determine which line items exist, run get_all_line_items.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the line item to get a forecast for. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, line_item_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201508') - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - 'includeTargetingCriteriaBreakdown': True, - } - - # Get forecast for line item. - forecast = forecast_service.getAvailabilityForecastById( - line_item_id, forecast_options) - matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) - - # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) - - if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py deleted file mode 100755 index 6db68bff..00000000 --- a/examples/dfp/v201508/forecast_service/get_delivery_forecast_for_line_items.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets a delivery forecast for two existing line items. - -To determine which line items exist, run get_all_line_items.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the line items to get forecasts for. -LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_ID_1_HERE' -LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_ID_2_HERE' - - -def main(client, line_item_id1, line_item_id2): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201508') - - # Get forecast for line item. - forecast = forecast_service.getDeliveryForecastByIds( - [line_item_id1, line_item_id2], None) - - for single_forecast in forecast['lineItemDeliveryForecasts']: - unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' - '%d %s predicted\n' % ( - single_forecast['lineItemId'], single_forecast['matchedUnits'], - unit_type, single_forecast['deliveredUnits'], unit_type, - single_forecast['predictedDeliveryUnits'], unit_type)) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201508/inventory_service/create_ad_units.py b/examples/dfp/v201508/inventory_service/create_ad_units.py deleted file mode 100755 index 79711a46..00000000 --- a/examples/dfp/v201508/inventory_service/create_ad_units.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new ad units. - -To determine which ad units exist, run get_all_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' - - -def main(client, parent_id): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201508') - - # Create ad unit size. - ad_unit_size = { - 'size': { - 'width': '300', - 'height': '250' - }, - 'environmentType': 'BROWSER' - } - - # Create ad unit objects. - ad_unit = { - 'name': 'Ad_unit_%s' % uuid.uuid4(), - 'parentId': parent_id, - 'description': 'Ad unit description.', - 'targetWindow': 'BLANK', - 'targetPlatform': 'WEB', - 'adUnitSizes': [ad_unit_size] - } - - # Add ad units. - ad_units = inventory_service.createAdUnits([ad_unit]) - - # Display results. - for ad_unit in ad_units: - print ('Ad unit with ID \'%s\' and name \'%s\' was created.' - % (ad_unit['id'], ad_unit['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PARENT_AD_UNIT_ID) diff --git a/examples/dfp/v201508/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201508/inventory_service/get_ad_unit_hierarchy.py deleted file mode 100755 index ea5072fe..00000000 --- a/examples/dfp/v201508/inventory_service/get_ad_unit_hierarchy.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code gets the ad unit hierarchy and displays it as a tree. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201508') - statement = dfp.FilterStatement() - - all_ad_units = [] - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - all_ad_units.extend(response['results']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Find the root ad unit. root_ad_unit can also be set to child unit to only - # build and display a portion of the tree. - query = 'WHERE parentId IS NULL' - root_statement = dfp.FilterStatement(query) - response = inventory_service.getAdUnitsByStatement( - root_statement.ToStatement()) - root_ad_unit = response['results'] - - if root_ad_unit: - BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units) - else: - print 'Could not build tree. No root ad unit found.' - - -def DisplayAdUnitTree(root_ad_unit, ad_unit_tree, depth=0): - """Helper for displaying ad unit tree. - - Args: - root_ad_unit: dict the root ad unit. - ad_unit_tree: dict the tree of ad units. - [optional] - depth: int the depth the tree has reached. - """ - print '%s%s (%s)' % (GenerateTab(depth), root_ad_unit['name'], - root_ad_unit['id']) - if root_ad_unit['id'] in ad_unit_tree: - for child in ad_unit_tree[root_ad_unit['id']]: - DisplayAdUnitTree(child, ad_unit_tree, depth+1) - - -def GenerateTab(depth): - """Generate tabs to represent branching to children. - - Args: - depth: int the depth the tree has reached. - - Returns: - string inserted in front of the root unit. - """ - tab_list = [] - if depth > 0: - tab_list.append(' ') - tab_list.append('| ' * depth) - tab_list.append('+--') - return ''.join(tab_list) - - -def BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units): - """Create an ad unit tree and display it. - - Args: - root_ad_unit: dict the root ad unit to build the tree under. - all_ad_units: list the list of all ad units to build the tree with. - """ - tree = {} - for ad_unit in all_ad_units: - if 'parentId' in ad_unit: - if ad_unit['parentId'] not in tree: - tree[ad_unit['parentId']] = [] - tree[ad_unit['parentId']].append(ad_unit) - - DisplayAdUnitTree(root_ad_unit, tree) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201508/inventory_service/get_all_ad_unit_sizes.py deleted file mode 100755 index 0f18d439..00000000 --- a/examples/dfp/v201508/inventory_service/get_all_ad_unit_sizes.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all ad unit sizes defined in a network. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201508') - statement = dfp.FilterStatement() - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitSizesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit_size in response['results']: - print ('Ad unit size of dimensions %s was found.' % - (ad_unit_size['fullDisplayString'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/inventory_service/get_all_ad_units.py b/examples/dfp/v201508/inventory_service/get_all_ad_units.py deleted file mode 100755 index 5a8877ad..00000000 --- a/examples/dfp/v201508/inventory_service/get_all_ad_units.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all ad units within a network. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201508') - statement = dfp.FilterStatement() - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' was found.' - % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201508/inventory_service/get_top_level_ad_units.py deleted file mode 100755 index 3c1fead9..00000000 --- a/examples/dfp/v201508/inventory_service/get_top_level_ad_units.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all child ad units of the effective root ad unit. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201508') - network_service = client.GetService('NetworkService', version='v201508') - - root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - # Create a statement to select the children of the effective root ad unit. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': root_id - } - }] - query = 'WHERE parentId = :id' - statement = dfp.FilterStatement(query, values) - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' was found.' - % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/label_service/create_labels.py b/examples/dfp/v201508/label_service/create_labels.py deleted file mode 100755 index c9f2d4a3..00000000 --- a/examples/dfp/v201508/label_service/create_labels.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new labels. - -To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201508') - - # Create label objects. - labels = [] - for _ in xrange(5): - label = { - 'name': 'Label #%s' % uuid.uuid4(), - 'isActive': 'true', - 'types': ['COMPETITIVE_EXCLUSION'] - } - labels.append(label) - - # Add Labels. - labels = label_service.createLabels(labels) - - # Display results. - for label in labels: - print ('Label with id \'%s\', name \'%s\', and types {%s} was found.' - % (label['id'], label['name'], ','.join(label['types']))) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/label_service/get_labels_by_statement.py b/examples/dfp/v201508/label_service/get_labels_by_statement.py deleted file mode 100755 index ba3e3be7..00000000 --- a/examples/dfp/v201508/label_service/get_labels_by_statement.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all labels ordered by name. - -To create a label, run create_label.py. This feature is only available to DFP -premium solution networks. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201508') - - # Create statement to get all labels - statement = dfp.FilterStatement('ORDER BY name') - - # Get labels by statement. - while True: - response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' was found.' - % (label['id'], label['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/line_item_creative_association_service/create_licas.py b/examples/dfp/v201508/line_item_creative_association_service/create_licas.py deleted file mode 100755 index 3380fbac..00000000 --- a/examples/dfp/v201508/line_item_creative_association_service/create_licas.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new line item creative associations (LICAs) for an -existing line item and a set of creative ids. - -To determine which LICAs exist, run get_all_licas.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the line item ID and creative IDs to associate. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' -CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE'] - - -def main(client, line_item_id, creative_ids): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201508') - - licas = [] - for creative_id in creative_ids: - licas.append({'creativeId': creative_id, - 'lineItemId': line_item_id}) - - # Create the LICAs remotely. - licas = lica_service.createLineItemCreativeAssociations(licas) - - # Display results. - if licas: - for lica in licas: - print ('LICA with line item id \'%s\', creative id \'%s\', and ' - 'status \'%s\' was created.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) - else: - print 'No LICAs created.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID, CREATIVE_IDS) diff --git a/examples/dfp/v201508/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201508/line_item_creative_association_service/deactivate_licas.py deleted file mode 100755 index 7c34795f..00000000 --- a/examples/dfp/v201508/line_item_creative_association_service/deactivate_licas.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example deactivates all LICAs for the line item. - -To determine which LICAs exist, run get_all_licas.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the line item in which to deactivate LICAs. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, line_item_id): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201508') - - # Create query. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE lineItemId = :lineItemId AND status = :status' - statement = dfp.FilterStatement(query, values) - - num_deactivated_licas = 0 - - # Get LICAs by statement. - while True: - response = lica_service.getLineItemCreativeAssociationsByStatement( - statement.ToStatement()) - if 'results' in response: - for lica in response['results']: - print ('LICA with line item id \'%s\', creative id \'%s\', and status' - ' \'%s\' will be deactivated.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) - - # Perform action. - result = lica_service.performLineItemCreativeAssociationAction( - {'xsi_type': 'DeactivateLineItemCreativeAssociations'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - num_deactivated_licas += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if num_deactivated_licas > 0: - print 'Number of LICAs deactivated: %s' % num_deactivated_licas - else: - print 'No LICAs were deactivated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201508/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201508/line_item_creative_association_service/get_all_licas.py deleted file mode 100755 index f402a933..00000000 --- a/examples/dfp/v201508/line_item_creative_association_service/get_all_licas.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all line item creative associations (LICA). - -To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201508') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get line items by statement. - while True: - response = lica_service.getLineItemCreativeAssociationsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for lica in response['results']: - if 'creativeSetId' in lica: - print ('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % - (lica['lineItemId'], lica['creativeSetId'], lica['status'])) - else: - print ('LICA with line item ID \'%s\', creative ID \'%s\', and status' - ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/line_item_service/create_line_items.py b/examples/dfp/v201508/line_item_service/create_line_items.py deleted file mode 100755 index e4b656f7..00000000 --- a/examples/dfp/v201508/line_item_service/create_line_items.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new line items. - -To determine which line items exist, run get_all_line_items.py. To determine -which orders exist, run get_all_orders.py. To determine which placements exist, -run get_all_placements.py.""" - - -from datetime import date -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set order that the created line item will belong to and add the id of a -# placement containing ad units to target. -ORDER_ID = 'INSERT_ORDER_ID_HERE' -TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE'] - - -def main(client, order_id, targeted_placement_ids): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') - - # Create line item objects. - line_items = [] - for i in xrange(5): - line_item = { - 'name': 'Line item #%s' % uuid.uuid4(), - 'orderId': order_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedPlacementIds': targeted_placement_ids - }, - 'geoTargeting': { - 'targetedLocations': [ - { - 'id': '2840', - 'displayName': 'US' - }, - { - 'id': '20133', - 'displayName': 'Geneva' - }, - { - 'id': '9000093', - 'displayName': 'B3P', - } - ], - 'excludedLocations': [ - { - 'id': '1016367', - 'displayName': 'Chicago', - }, - { - 'id': '200501', - 'displayName': 'New York NY' - } - ] - }, - 'dayPartTargeting': { - 'dayParts': [ - { - 'dayOfWeek': 'SATURDAY', - 'startTime': { - 'hour': '0', - 'minute': 'ZERO' - }, - 'endTime': { - 'hour': '24', - 'minute': 'ZERO' - } - }, - { - 'dayOfWeek': 'SUNDAY', - 'startTime': { - 'hour': '0', - 'minute': 'ZERO' - }, - 'endTime': { - 'hour': '24', - 'minute': 'ZERO' - } - } - ], - 'timeZone': 'BROWSER' - }, - 'userDomainTargeting': { - 'domains': ['usa.gov'], - 'targeted': 'false' - }, - 'technologyTargeting': { - 'browserTargeting': { - 'browsers': [{'id': '500072'}], - 'isTargeted': 'true' - } - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '300', - 'height': '250' - } - }, - { - 'size': { - 'width': '120', - 'height': '600' - } - } - ], - 'startDateTimeType': 'IMMEDIATELY', - 'lineItemType': 'STANDARD', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'LIFETIME' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'EVEN', - 'discountType': 'PERCENTAGE', - 'allowOverbook': 'true' - } - line_items.append(line_item) - - # Add line items. - line_items = line_item_service.createLineItems(line_items) - - # Display results. - for line_item in line_items: - print ('Line item with id \'%s\', belonging to order id \'%s\', and named ' - '\'%s\' was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID, TARGETED_PLACEMENT_IDS) - diff --git a/examples/dfp/v201508/line_item_service/create_video_line_item.py b/examples/dfp/v201508/line_item_service/create_video_line_item.py deleted file mode 100755 index 5e95752e..00000000 --- a/examples/dfp/v201508/line_item_service/create_video_line_item.py +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates a new line item to serve to video content. - -This feature is only available to DFP premium solution networks. To determine -which line items exist, run get_all_line_items.py. To determine which orders -exist, run get_all_orders.py. To create a video ad unit, run -create_video_ad_unit.py. To create criteria for categories, run -create_custom_targeting_keys_and_values.py""" - - -from datetime import date -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set order that all created line item will belong to and the video ad unit id -# to target. -ORDER_ID = 'INSERT_ORDER_ID_HERE' -TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE' - -# Set the custom targeting value ID representing the metadata -# on the content to target. This would typically be from a key representing -# a "genre" and the value representing something like "comedy". The value -# must be from a key in a content metadata key hierarchy. -CONTENT_CUSTOM_TARGETING_VALUE_ID = \ - 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE' - - -def main(client, order_id, targeted_video_ad_unit_id, - content_custom_targeting_value_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') - - # Create line item object. - line_item = { - 'name': 'Line item #%s' % uuid.uuid4(), - 'orderId': order_id, - 'targeting': { - 'contentTargeting': { - 'targetedContentMetadata': [ - {'customTargetingValueIds': [ - content_custom_targeting_value_id]} - ] - }, - 'inventoryTargeting': { - 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id, - 'includeDescendants': 'true'}] - }, - 'videoPositionTargeting': { - 'targetedPositions': [ - { - 'videoPosition': { - 'positionType': 'PREROLL' - } - } - ] - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '400', - 'height': '300' - }, - 'companions': [ - { - 'size': { - 'width': '300', - 'height': '250' - }, - }, - { - 'size': { - 'width': '728', - 'height': '90' - }, - } - ] - } - ], - 'environmentType': 'VIDEO_PLAYER', - 'companionDeliveryOption': 'OPTIONAL', - 'startDateTimeType': 'IMMEDIATELY', - 'lineItemType': 'SPONSORSHIP', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'DAILY' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'OPTIMIZED', - 'discountType': 'PERCENTAGE', - 'allowOverbook': 'true' - } - - # Add line item. - line_item = line_item_service.createLineItem(line_item) - - # Display results. - print ('Video line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, - CONTENT_CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201508/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201508/line_item_service/get_line_items_by_statement.py deleted file mode 100755 index bd7428bd..00000000 --- a/examples/dfp/v201508/line_item_service/get_line_items_by_statement.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all line items that need creatives for an order. - -To create line items, run create_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') - - # Create statement object to only select line items that need creatives from a - # given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - }] - query = ('WHERE orderId = :orderId AND ' - 'isMissingCreatives = :isMissingCreatives') - statement = dfp.FilterStatement(query, values) - - while True: - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % (line_item['id'], - line_item['orderId'], - line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201508/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201508/line_item_service/get_recently_updated_line_items.py deleted file mode 100755 index fcdffcd7..00000000 --- a/examples/dfp/v201508/line_item_service/get_recently_updated_line_items.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example shows how to get recently updated line items. - -To create line items, run create_line_items.py.""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import dfp - -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') - - # Create statement object to only select line items belonging to the order and - # have been modified in the last 3 days. - three_days_ago = datetime.date.today() - datetime.timedelta(days=3) - values = [{ - 'key': 'dateTimeString', - 'value': { - 'xsi_type': 'TextValue', - 'value': three_days_ago.strftime('%Y-%m-%dT%H:%M:%S') - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE lastModifiedDateTime >= :dateTimeString AND orderId = :orderId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % (line_item['id'], - line_item['orderId'], - line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201508/network_service/get_all_networks.py b/examples/dfp/v201508/network_service/get_all_networks.py deleted file mode 100755 index fe0b99af..00000000 --- a/examples/dfp/v201508/network_service/get_all_networks.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 networks that you have access to with the current login -credentials. - -A networkCode should be left out for this request.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201508') - - # Get all networks that you have access to with the current login credentials. - networks = network_service.getAllNetworks() - - # Display results. - for network in networks: - print ('Network with network code \'%s\' and display name \'%s\' was found.' - % (network['networkCode'], network['displayName'])) - - print '\nNumber of results found: %s' % len(networks) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/network_service/get_current_network.py b/examples/dfp/v201508/network_service/get_current_network.py deleted file mode 100755 index c2f62c7e..00000000 --- a/examples/dfp/v201508/network_service/get_current_network.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the current network that you can make requests against.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201508') - - # Get the current network. - network = network_service.getCurrentNetwork() - - # Display results. - print ('Current network has network code \'%s\' and display name \'%s\'.' - % (network['networkCode'], network['displayName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/order_service/get_orders_by_statement.py b/examples/dfp/v201508/order_service/get_orders_by_statement.py deleted file mode 100755 index 762f5596..00000000 --- a/examples/dfp/v201508/order_service/get_orders_by_statement.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets an order by an ID. - -To create orders, run create_orders.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the order to get. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201508') - - # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - - statement = dfp.FilterStatement(query, values) - - # Get orders by statement. - response = order_service.getOrdersByStatement(statement.ToStatement()) - orders = [] - if 'results' in response: - orders = response['results'] - - # Display results. - for order in orders: - print ('Order with id \'%s\' name \'%s\' was found.' - % (order['id'], order['name'])) - - print '\nNumber of results found: %s' % len(orders) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201508/order_service/update_orders.py b/examples/dfp/v201508/order_service/update_orders.py deleted file mode 100755 index 4ffa2de3..00000000 --- a/examples/dfp/v201508/order_service/update_orders.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates the notes of a single order specified by ID. - -To determine which orders exist, run get_all_orders.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201508') - - # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - - statement = dfp.FilterStatement(query, values) - - # Get orders by statement. - response = order_service.getOrdersByStatement(statement.ToStatement()) - - if 'results' in response: - # Update each local order object by changing its notes. - updated_orders = [] - for order in response['results']: - # Archived orders cannot be updated. - if not order['isArchived']: - order['notes'] = 'Spoke to advertiser. All is well.' - updated_orders.append(order) - - # Update orders remotely. - orders = order_service.updateOrders(updated_orders) - - # Display results. - if orders: - for order in orders: - print ('Order with id \'%s\', name \'%s\', advertiser id \'%s\', and ' - 'notes \'%s\' was updated.' - % (order['id'], order['name'], order['advertiserId'], - order['notes'])) - else: - print 'No orders were updated.' - else: - print 'No orders found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) - diff --git a/examples/dfp/v201508/placement_service/create_placements.py b/examples/dfp/v201508/placement_service/create_placements.py deleted file mode 100755 index 3eda6d90..00000000 --- a/examples/dfp/v201508/placement_service/create_placements.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new placements for various ad unit sizes. - -To determine which placements exist, run get_all_placements.py. -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201508') - inventory_service = client.GetService('InventoryService', version='v201508') - - # Create placement object to store medium rectangle ad units. - medium_rectangle_ad_unit_placement = { - 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(), - 'description': 'Contains ad units that hold creatives of size 300x250', - 'targetedAdUnitIds': [] - } - - # Create placement object to store skyscraper ad units. - skyscraper_ad_unit_placement = { - 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(), - 'description': 'Contains ad units that hold creatives of size 120x600', - 'targetedAdUnitIds': [] - } - - # Create placement object to store banner ad units. - banner_ad_unit_placement = { - 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(), - 'description': 'Contains ad units that hold creatives of size 468x60', - 'targetedAdUnitIds': [] - } - - placement_list = [] - - # Create statement to get all the ad units. - statement = dfp.FilterStatement() - - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Separate the ad units by size. - for ad_unit in response['results']: - if 'adUnitSizes' in ad_unit: - for ad_unit_size in ad_unit['adUnitSizes']: - size = ad_unit_size['size'] - if size['width'] == '300' and size['height'] == '250': - medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append( - ad_unit['id']) - elif size['width'] == '120' and size['height'] == '600': - skyscraper_ad_unit_placement['targetedAdUnitIds'].append( - ad_unit['id']) - elif size['width'] == '468' and size['height'] == '60': - banner_ad_unit_placement['targetedAdUnitIds'].append( - ad_unit['id']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Only create placements with one or more ad unit. - if medium_rectangle_ad_unit_placement['targetedAdUnitIds']: - placement_list.append(medium_rectangle_ad_unit_placement) - - if skyscraper_ad_unit_placement['targetedAdUnitIds']: - placement_list.append(skyscraper_ad_unit_placement) - - if banner_ad_unit_placement['targetedAdUnitIds']: - placement_list.append(banner_ad_unit_placement) - - # Add placements. - placements = placement_service.createPlacements(placement_list) - - # Display results. - for placement in placements: - ad_unit_ids = '' - if 'targetedAdUnitIds' in placement: - ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) - print ('A Placement with ID \'%s\', name \'%s\', and containing ad units ' - '{%s} was created.' % (placement['id'], placement['name'], - ad_unit_ids)) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/placement_service/deactivate_placements.py b/examples/dfp/v201508/placement_service/deactivate_placements.py deleted file mode 100755 index 6ab8e988..00000000 --- a/examples/dfp/v201508/placement_service/deactivate_placements.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example deactivates all active placements. - -To determine which placements exist, run get_all_placements.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' - - -def main(client, placement_id): - # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201508') - - # Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) - - # Get placements by statement. - placements = placement_service.getPlacementsByStatement( - statement.ToStatement()) - - for placement in placements: - print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be ' - 'deactivated.' % (placement['id'], placement['name'], - placement['status'])) - - # Perform action. - result = placement_service.performPlacementAction( - {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement()) - - # Display results. - if result and int(result['numChanges']) > 0: - print 'Number of placements deactivated: %s' % result['numChanges'] - else: - print 'No placements were deactivated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PLACEMENT_ID) diff --git a/examples/dfp/v201508/placement_service/update_placements.py b/examples/dfp/v201508/placement_service/update_placements.py deleted file mode 100755 index 45f3fcca..00000000 --- a/examples/dfp/v201508/placement_service/update_placements.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates a single placement to allow for AdSense targeting. - -To determine which placements exist, run get_all_placements.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' - - -def main(client, placement_id): - # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201508') -# Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) - - # Get placements by statement. - placements = placement_service.getPlacementsByStatement( - statement.ToStatement()) - - for placement in placements: - if not placement['targetingDescription']: - placement['targetingDescription'] = 'Generic description' - placement['targetingAdLocation'] = 'All images on sports pages.' - placement['targetingSiteName'] = 'http://code.google.com' - placement['isAdSenseTargetingEnabled'] = 'true' - - # Update placements remotely. - placements = placement_service.updatePlacements(placements) - - for placement in placements: - print ('Placement with id \'%s\', name \'%s\', and AdSense targeting ' - 'enabled \'%s\' was updated.' - % (placement['id'], placement['name'], - placement['isAdSenseTargetingEnabled'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PLACEMENT_ID) diff --git a/examples/dfp/v201508/premium_rate_service/create_premium_rates.py b/examples/dfp/v201508/premium_rate_service/create_premium_rates.py deleted file mode 100755 index 4cbc87db..00000000 --- a/examples/dfp/v201508/premium_rate_service/create_premium_rates.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new premium_rates. - -To determine which premium_rates exist, run get_all_premium_rates.py. -""" - -# Import appropriate modules from the client library. -from googleads import dfp - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate services. - premium_rate_service = client.GetService('PremiumRateService', - version='v201508') - - # Create an ad unit premium to apply to the rate card. - ad_unit_premium_feature = { - 'xsi_type': 'AdUnitPremiumFeature' - } - - # Create a CPC based premium rate value with adjustments in milli amounts. - # This will adjust a CPC priced proposal line item that has - # inventory targeting specified by 10% of the cost associated with the rate - # card (this comes from a percentage adjustment). - cpc_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPC', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Create a CPM based premium rate value with adjustments in micro amounts. - # This will adjust a CPM priced proposal line item that has - # inventory targeting specified by 2 units of the currency associated with - # the rate card (this comes from absolute value adjustment). - cpm_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPM', - 'adjustmentSize': 2000000, - 'adjustmentType': 'ABSOLUTE_VALUE' - } - - # Create premium_rate objects. - premium_rate = { - 'rateCardId': rate_card_id, - 'pricingMethod': 'ANY_VALUE', - 'premiumFeature': ad_unit_premium_feature, - 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value] - } - - # Add premium_rates. - premium_rates = premium_rate_service.createPremiumRates([premium_rate]) - - # Display results. - for premium_rate in premium_rates: - print ('A premium rate for \'%s\' was added to the rate card with ID' - ' of \'%s\'.\n' - % (dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['id'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201508/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201508/premium_rate_service/get_premium_rates_for_a_rate_card.py deleted file mode 100755 index 94521798..00000000 --- a/examples/dfp/v201508/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all premium rates belonging to a specific rate card. - -To create premium rates, run create_premium_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201508') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'rateCardId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': rate_card_id - } - }] - query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC' - statement = dfp.FilterStatement(query, values) - - # Get premium rates by statement. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for premium_rate in response['results']: - print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' - ' rate card with ID \'%s\' was found.\n' % ( - premium_rate['id'], - dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) diff --git a/examples/dfp/v201508/premium_rate_service/update_premium_rates.py b/examples/dfp/v201508/premium_rate_service/update_premium_rates.py deleted file mode 100755 index 5fe463b2..00000000 --- a/examples/dfp/v201508/premium_rate_service/update_premium_rates.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates a premium rate to add a flat fee to an existing feature. - -To determine which premium rates exist, run get_all_premium_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' - - -def main(client, premium_rate_id): - # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201508') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': premium_rate_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) - - # Get the premium rate. - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - - if 'results' in response: - updated_premium_rates = [] - for premium_rate in response['results']: - # Create a flat fee based premium rate value with a 10% increase. - new_flat_fee_rate = { - 'premiumFeature': premium_rate['premiumFeature'], - 'rateType': 'CPM', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Update the premium rate's premiumRateValues to include a flat fee - # premium rate. - - existing_premium_rate_value = ( - [] if 'premiumRateValues' not in premium_rate else - premium_rate['premiumRateValues']) - existing_premium_rate_value.append(new_flat_fee_rate) - premium_rate['premiumRateValues'] = existing_premium_rate_value - - updated_premium_rates.append(premium_rate) - - # Update products remotely. - premium_rates = premium_rate_service.updatePremiumRates( - updated_premium_rates) - - # Display results. - if premium_rates: - for premium_rate in premium_rates: - print ('Premium rate with ID \'%s\', associated with rate card id' - ' \'%s\' was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) - else: - print 'No premium rates were updated.' - else: - print 'No premium rates found to update.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PREMIUM_RATE_ID) diff --git a/examples/dfp/v201508/product_service/get_all_products.py b/examples/dfp/v201508/product_service/get_all_products.py deleted file mode 100755 index ffd5c938..00000000 --- a/examples/dfp/v201508/product_service/get_all_products.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all products. - -Products are created automatically from product templates. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201508') - - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') - - # Get products by statement. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' was found.' % ( - product['id'], product['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201508/proposal_line_item_service/archive_proposal_line_items.py deleted file mode 100755 index 1e656b70..00000000 --- a/examples/dfp/v201508/proposal_line_item_service/archive_proposal_line_items.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example archives a proposal line item. - -To determine which proposal line items exist, run -get_all_proposal_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the proposal line item to archive. -PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' - - -def main(client, proposal_line_item_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201508') - - # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - proposal_line_items_archived = 0 - - # Get proposal line items by statement. - while True: - response = proposal_line_item_service.getProposalLineItemsByStatement( - statement.ToStatement()) - if 'results' in response: - for proposal_line_item in response['results']: - print ('Proposal line item with id \'%s\', ' - 'belonging to proposal id \'%s\', and ' - 'name \'%s\' will be archived.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - - # Perform action. - result = proposal_line_item_service.performProposalLineItemAction( - {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - proposal_line_items_archived += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if proposal_line_items_archived > 0: - print ('Number of proposal line items ' - 'archived: %s' % proposal_line_items_archived) - else: - print 'No proposal line items were archived.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201508/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201508/proposal_line_item_service/get_proposal_line_items_for_proposal.py deleted file mode 100755 index f1a20f12..00000000 --- a/examples/dfp/v201508/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all proposal line items that belong to a proposal. - -To create proposal line items, run create_proposal_line_items.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the proposal to get proposal line items from. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', - version='v201508') - - # Create statement object to only select proposal line items belonging to a - # given proposal. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE proposalId = :proposalId ORDER BY id ASC' - statement = dfp.FilterStatement(query, values) - - while True: - # Get proposal line items by statement. - response = proposal_line_item_service.getProposalLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for idx, proposal_line_item in enumerate(response['results'], - start=statement.offset): - print( - '%s) Proposal line item with id \'%s\', belonging to proposal id ' - '\'%s\', and named \'%s\' was found.' % ( - idx, proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/proposal_service/get_all_proposals.py b/examples/dfp/v201508/proposal_service/get_all_proposals.py deleted file mode 100755 index 28768d10..00000000 --- a/examples/dfp/v201508/proposal_service/get_all_proposals.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all proposals. - -To create proposals, run create_proposals.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201508') - - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') - - # Get proposals by statement. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for proposal in response['results']: - print ('Proposal with id \'%s\' and name \'%s\' was found.' % ( - proposal['id'], proposal['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201508/publisher_query_language_service/get_geo_targets.py deleted file mode 100755 index 235cdeea..00000000 --- a/examples/dfp/v201508/publisher_query_language_service/get_geo_targets.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 geographic criteria from the Geo_Target table. - -The types available to filter on include 'City', 'Country', 'Region', 'State', -'Postal_Code', and 'DMA_Region' (i.e. Metro). - -A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201508/PublisherQueryLanguageService -""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201508') - - output_file = tempfile.NamedTemporaryFile( - prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) - - # Create bind value to select geo-targets of type 'City'. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'City' - } - }] - - pql_query = ('SELECT Name, Id FROM Geo_Target ' - 'WHERE targetable = true AND Type = :type') - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - pql_query, output_file, values) - output_file.close() - - print ('Saved geo targets to... %s' % output_file.name) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201508/rate_card_service/get_all_rate_cards.py deleted file mode 100755 index 4d7bf1f2..00000000 --- a/examples/dfp/v201508/rate_card_service/get_all_rate_cards.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all rate cards. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201508') - - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') - - # Get rate cards by statement. - while True: - response = rate_card_service.getRateCardsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for rate_card in response['results']: - print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' - 'was found.' % (rate_card['id'], rate_card['name'], - rate_card['currencyCode'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/report_service/run_delivery_report.py b/examples/dfp/v201508/report_service/run_delivery_report.py deleted file mode 100755 index 48e05a3b..00000000 --- a/examples/dfp/v201508/report_service/run_delivery_report.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example runs a report similar to the "Orders report" on the DFP -website with additional attributes and can filter to include just one order. -""" - -from datetime import datetime -from datetime import timedelta -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp -from googleads import errors - -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - filter_statement = {'query': 'WHERE ORDER_ID = :id', - 'values': values} - - # Set the start and end dates of the report to run (past 8 days). - end_date = datetime.now() - start_date = end_date - timedelta(days=8) - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['ORDER_ID', 'ORDER_NAME'], - 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', - 'ORDER_END_DATE_TIME'], - 'statement': filter_statement, - 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', - 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'CUSTOM_DATE', - 'startDate': {'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day}, - 'endDate': {'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day} - } - } - - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201508') - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201508/report_service/run_inventory_report.py b/examples/dfp/v201508/report_service/run_inventory_report.py deleted file mode 100755 index 918fc0b0..00000000 --- a/examples/dfp/v201508/report_service/run_inventory_report.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example runs a report equal to the "Whole network report" on the -DFP website. -""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp -from googleads import errors - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201508') - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201508') - - # Get root ad unit id for network. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Set filter statement and bind value for reportQuery. - values = [{ - 'key': 'parent_ad_unit_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': root_ad_unit_id - } - }] - filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id', - 'values': values} - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['DATE', 'AD_UNIT_NAME'], - 'adUnitView': 'HIERARCHICAL', - 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS', - 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS', - 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', - 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], - 'dateRangeType': 'LAST_WEEK', - 'statement': filter_statement - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/report_service/run_reach_report.py b/examples/dfp/v201508/report_service/run_reach_report.py deleted file mode 100755 index e7801abf..00000000 --- a/examples/dfp/v201508/report_service/run_reach_report.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example runs a reach report.""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp -from googleads import errors - - -def main(client): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201508') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'], - 'dateRangeType': 'REACH_LIFETIME' - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( - report_job_id, report_file.name) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201508/suggested_ad_unit_service/approve_all_suggested_ad_units.py deleted file mode 100755 index 6e4b10c4..00000000 --- a/examples/dfp/v201508/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example approves all suggested ad units with 50 or more requests. - -This feature is only available to DFP premium solution networks. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -THRESHOLD_NUMBER_OF_REQUESTS = '50' - - -def main(client): - # Initialize appropriate service. - suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201508') - - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': THRESHOLD_NUMBER_OF_REQUESTS - } - }] - - query = 'WHERE numRequests > :numRequests' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - num_approved_suggested_ad_units = 0 - - # Get suggested ad units by statement. - while True: - response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Print suggested ad units that will be approved. - for suggested_ad_unit in response['results']: - print ('Suggested ad unit with id \'%s\', and number of requests \'%s\'' - ' will be approved.' % (suggested_ad_unit['id'], - suggested_ad_unit['numRequests'])) - - # Approve suggested ad units. - result = suggested_ad_unit_service.performSuggestedAdUnitAction( - {'xsi_type': 'ApproveSuggestedAdUnit'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - num_approved_suggested_ad_units += int(result['numChanges']) - else: - break - - if num_approved_suggested_ad_units > 0: - print ('Number of suggested ad units approved: %s' % - num_approved_suggested_ad_units) - else: - print 'No suggested ad units were approved.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) - diff --git a/examples/dfp/v201508/team_service/get_teams_by_statement.py b/examples/dfp/v201508/team_service/get_teams_by_statement.py deleted file mode 100755 index ab734b7d..00000000 --- a/examples/dfp/v201508/team_service/get_teams_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a single team by ID. - -To create teams, run create_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -TEAM_ID = 'INSERT_TEAM_ID_HERE' - - -def main(client, team_id): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201508') - - # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get teams by statement. - response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for team in response['results']: - print ('Team with id \'%s\' and name \'%s\' was found.' - % (team['id'], team['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID) diff --git a/examples/dfp/v201508/user_service/get_current_user.py b/examples/dfp/v201508/user_service/get_current_user.py deleted file mode 100755 index e6c9df97..00000000 --- a/examples/dfp/v201508/user_service/get_current_user.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets the current user.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201508') - - # Get current user. - user = user_service.getCurrentUser() - - # Display results. - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/user_service/get_users_by_statement.py b/examples/dfp/v201508/user_service/get_users_by_statement.py deleted file mode 100755 index 9f2758ef..00000000 --- a/examples/dfp/v201508/user_service/get_users_by_statement.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets a user by its id. - -To create users, run create_user.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_TO_FIND_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201508') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get users by statement. - response = user_service.getUsersByStatement(statement.ToStatement()) - users = response['results'] if 'results' in response else [] - - for user in users: - # Display results. - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201508/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201508/user_team_association_service/create_user_team_associations.py deleted file mode 100755 index b19ee3e9..00000000 --- a/examples/dfp/v201508/user_team_association_service/create_user_team_associations.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 adds a user to a team by creating an association between them. - -To determine which teams exists, run get_all_teams.py. To determine which -users exist, run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -TEAM_ID = 'INSERT_TEAM_ID_HERE' -USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE'] - - -def main(client, team_id, user_ids): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201508') - - user_team_associations = [] - for user_id in user_ids: - user_team_associations.append( - { - 'teamId': team_id, - 'userId': user_id - }) - - # Create the user team association on the server. - user_team_associations = ( - user_team_association_service.createUserTeamAssociations( - user_team_associations)) - - # Display results. - if user_team_associations: - for user_team_association in user_team_associations: - print ('A user team association between user with ID \'%s\' and team with' - ' ID \'%s\'was created.' % (user_team_association['userId'], - user_team_association['teamId'])) - else: - print 'No user team associations created.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID, USER_IDS) diff --git a/examples/dfp/v201508/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201508/user_team_association_service/delete_user_team_associations.py deleted file mode 100755 index f1aada8f..00000000 --- a/examples/dfp/v201508/user_team_association_service/delete_user_team_associations.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 removes the user from all its teams. - -To determine which users exist, run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201508') - - # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get user team associations by statement. - response = user_team_association_service.getUserTeamAssociationsByStatement( - statement.ToStatement()) - user_team_associations = response['results'] if 'results' in response else [] - - for user_team_association in user_team_associations: - print ('User team association between user with ID \'%s\' and team with ' - 'ID \'%s\' will be deleted.' % (user_team_association['userId'], - user_team_association['teamId'])) - print ('Number of teams that the user will be removed from: %s' % - len(user_team_associations)) - - # Perform action. - result = user_team_association_service.performUserTeamAssociationAction( - {'xsi_type': 'DeleteUserTeamAssociations'}, - {'query': query, 'values': values}) - - # Display results. - if result and int(result['numChanges']) > 0: - print ('Number of teams that the user was removed from: %s' - % result['numChanges']) - else: - print 'No user team associations were deleted.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201508/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201508/user_team_association_service/update_user_team_associations.py deleted file mode 100755 index 50e8b862..00000000 --- a/examples/dfp/v201508/user_team_association_service/update_user_team_associations.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates user team associations. - -It updates a user team association by setting the overridden access type to read -only for all teams that the user belongs to. To determine which users exists, -run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201508') - - # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get user team associations by statement. - response = user_team_association_service.getUserTeamAssociationsByStatement( - statement.ToStatement()) - - if 'results' in response: - updated_user_team_associations = [] - # Update each local user team association to read only access. - for user_team_association in response['results']: - user_team_association['overriddenTeamAccessType'] = 'READ_ONLY' - updated_user_team_associations.append(user_team_association) - - # Update user team associations on the server. - user_team_associations = ( - user_team_association_service.updateUserTeamAssociations( - updated_user_team_associations)) - - # Display results. - if user_team_associations: - for user_team_association in user_team_associations: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was updated.' % (user_team_association['userId'], - user_team_association['teamId'])) - else: - print 'No user team associations were updated.' - else: - print 'No user team associations found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201508/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201508/workflow_request_service/approve_workflow_approval_requests.py deleted file mode 100755 index ceafa9f2..00000000 --- a/examples/dfp/v201508/workflow_request_service/approve_workflow_approval_requests.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 approves all workflow approval requests belonging to a proposal. - -To determine which workflow approval requests exist, run -get_all_workflow_approval_requests.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201508') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - workflow_approval_requests_approved = 0 - - # Get workflow approval requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for workflow_approval_request in response['results']: - print ('Workflow approval request with id \'%s\' will be' - ' approved.' % workflow_approval_request['id']) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'ApproveWorkflowApprovalRequests', - 'comment': 'This workflow has now been approved for submission.'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_approval_requests_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if workflow_approval_requests_approved > 0: - print ('\nNumber of workflow approval requests approved: %s' % - workflow_approval_requests_approved) - else: - print '\nNo workflow approval requests were approved.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201508/workflow_request_service/get_workflow_approval_requests_by_statement.py deleted file mode 100755 index 68466589..00000000 --- a/examples/dfp/v201508/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 workflow approval requests. - -Workflow approval requests must be approved or rejected for a workflow to -finish. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201508') - - # Create statement object to select all workflow approval requests. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - }] - query = 'WHERE type = :type' - - statement = dfp.FilterStatement(query, values) - - # Get proposals by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for workflow_request in response['results']: - print ('Workflow approval request with id \'%s\' for %s with id \'%s\' ' - 'was found.' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201508/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201508/workflow_request_service/get_workflow_external_condition_requests_by_statement.py deleted file mode 100755 index bacb285f..00000000 --- a/examples/dfp/v201508/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 workflow external condition requests. - -Workflow external condition requests must be triggered or skipped for a workflow -to finish. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201508') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - }] - query = 'WHERE type = :type' - - statement = dfp.FilterStatement(query, values) - - # Get proposals by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for workflow_request in response['results']: - print ('Workflow external condition request with id \'%s\' for %s ' - 'with id \'%s\' was found.' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/activity_group_service/__init__.py b/examples/dfp/v201511/activity_group_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/activity_group_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/activity_group_service/create_activity_groups.py b/examples/dfp/v201511/activity_group_service/create_activity_groups.py deleted file mode 100755 index 95ad201a..00000000 --- a/examples/dfp/v201511/activity_group_service/create_activity_groups.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new activity groups. - -To determine which activity groups exist, run get_all_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the advertiser company this activity group is associated with. -ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, advertiser_company_id): - # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201511') - - # Create a short-term activity group. - short_term_activity_group = { - 'name': 'Short-term activity group #%s' % uuid.uuid4(), - 'companyIds': [advertiser_company_id], - 'clicksLookback': '1', - 'impressionsLookback': '1' - } - - # Create a long-term activity group. - long_term_activity_group = { - 'name': 'Long-term activity group #%s' % uuid.uuid4(), - 'companyIds': [advertiser_company_id], - 'clicksLookback': '30', - 'impressionsLookback': '30' - } - - # Create the activity groups on the server. - activity_groups = activity_group_service.createActivityGroups([ - short_term_activity_group, long_term_activity_group]) - - # Display results. - for activity_group in activity_groups: - print ('Activity group with ID \'%s\' and name \'%s\' was created.' - % (activity_group['id'], activity_group['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_COMPANY_ID) diff --git a/examples/dfp/v201511/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201511/activity_group_service/get_active_activity_groups.py deleted file mode 100755 index 32a7cc0d..00000000 --- a/examples/dfp/v201511/activity_group_service/get_active_activity_groups.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active activity groups. - -To create activity groups, run create_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201511') - - # Create statement object to only select active activity groups. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get activity groups by statement. - while True: - response = activity_group_service.getActivityGroupsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity_group in response['results']: - print ('Activity group with ID \'%s\' and name \'%s\' was found.' - % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/activity_service/__init__.py b/examples/dfp/v201511/activity_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/activity_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/activity_service/get_active_activities.py b/examples/dfp/v201511/activity_service/get_active_activities.py deleted file mode 100755 index 70c745e5..00000000 --- a/examples/dfp/v201511/activity_service/get_active_activities.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active activities. - -To create activities, run create_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201511') - - # Create statement object to only select active activities. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get activities by statement. - while True: - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity in response['results']: - print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (activity['id'], activity['name'], activity['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/activity_service/update_activities.py b/examples/dfp/v201511/activity_service/update_activities.py deleted file mode 100755 index 0b9d622c..00000000 --- a/examples/dfp/v201511/activity_service/update_activities.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates activities. - -To determine which activities exist, run get_all_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the activity to update. -ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE' - - -def main(client, activity_id): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201511') - - # Create statement object to select one activity by ID to update. - values = [{ - 'key': 'activityId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_id - } - }] - query = 'WHERE id = :activityId' - statement = dfp.FilterStatement(query, values, 1) - - # Get activities by statement. - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) - if 'results' in response: - updated_activities = [] - for activity in response['results']: - # Update the expected URL. - activity['expectedURL'] = 'https://google.com' - updated_activities.append(activity) - # Update the activity on the server. - activities = activity_service.updateActivities(updated_activities) - - for updated_activity in activities: - print (('Activity with ID \'%s\' and name \'%s\' was updated.') - % (updated_activity['id'], updated_activity['name'])) - else: - print 'No activities found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_ID) diff --git a/examples/dfp/v201511/audience_segment_service/__init__.py b/examples/dfp/v201511/audience_segment_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/audience_segment_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/base_rate_service/__init__.py b/examples/dfp/v201511/base_rate_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/base_rate_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/base_rate_service/create_product_base_rates.py b/examples/dfp/v201511/base_rate_service/create_product_base_rates.py deleted file mode 100755 index debb93d0..00000000 --- a/examples/dfp/v201511/base_rate_service/create_product_base_rates.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates a product base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201511') - - # Create a product base rate. - product_base_rate = { - 'xsi_type': 'ProductBaseRate', - 'rateCardId': rate_card_id, - 'productId': product_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create base rates on the server. - base_rates = base_rate_service.createBaseRates( - [product_base_rate]) - - if base_rates: - for base_rate in base_rates: - print ('A product base rate with ID \'%s\' and rate \'%.2f\' %s was ' - 'created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201511/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201511/base_rate_service/create_product_template_base_rates.py deleted file mode 100755 index 9f4d7f91..00000000 --- a/examples/dfp/v201511/base_rate_service/create_product_template_base_rates.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates a product template base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_template_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201511') - - # Create a product template base rate. - product_template_base_rate = { - 'xsi_type': 'ProductTemplateBaseRate', - 'rateCardId': rate_card_id, - 'productTemplateId': product_template_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create base rates on the server. - base_rates = base_rate_service.createBaseRates( - [product_template_base_rate]) - - if base_rates: - for base_rate in base_rates: - print ('A product template base rate with ID \'%s\' and rate \'%.2f\' %s' - ' was created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201511/base_rate_service/get_all_base_rates.py b/examples/dfp/v201511/base_rate_service/get_all_base_rates.py deleted file mode 100755 index 7c0dd891..00000000 --- a/examples/dfp/v201511/base_rate_service/get_all_base_rates.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 base rates. - -To create product base rates, run create_product_base_rates.py -To create product template base rates, run -create_product_template_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') - - # Get base rates by statement. - while True: - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for base_rate in response['results']: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was found.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/base_rate_service/update_base_rates.py b/examples/dfp/v201511/base_rate_service/update_base_rates.py deleted file mode 100755 index 09bcd071..00000000 --- a/examples/dfp/v201511/base_rate_service/update_base_rates.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates a base rate's value. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' - - -def main(client, base_rate_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201511') - - # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': base_rate_id - } - }] - query = 'where id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) - - # Get single base rate by statement. - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) - - if 'results' in response: - # Update each local base rate object by changing its value to $3 USD. - new_rate = { - 'currencyCode': 'USD', - 'microAmount': 3000000 - } - - updated_base_rates = [] - for base_rate in response['results']: - base_rate['rate'] = new_rate - updated_base_rates.append(base_rate) - - # Update base rates remotely. - base_rates = base_rate_service.updateBaseRates(updated_base_rates) - - # Display results. - if base_rates: - for base_rate in base_rates: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was updated.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) - else: - print 'No base rates were updated.' - else: - print 'No base rates found to update.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, BASE_RATE_ID) diff --git a/examples/dfp/v201511/company_service/__init__.py b/examples/dfp/v201511/company_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/company_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/company_service/get_advertisers.py b/examples/dfp/v201511/company_service/get_advertisers.py deleted file mode 100755 index 96d54060..00000000 --- a/examples/dfp/v201511/company_service/get_advertisers.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all companies that are advertisers. - -To create companies, run create_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201511') - - # Create statement object to only select companies that are advertisers. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - } - }] - query = 'WHERE type = :type' - statement = dfp.FilterStatement(query, values) - - # Get companies by statement. - while True: - response = company_service.getCompaniesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for company in response['results']: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.' - % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/contact_service/__init__.py b/examples/dfp/v201511/contact_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/contact_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/contact_service/create_contacts.py b/examples/dfp/v201511/contact_service/create_contacts.py deleted file mode 100755 index f5538caf..00000000 --- a/examples/dfp/v201511/contact_service/create_contacts.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new contacts. - -To determine which contacts exist, run get_all_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the advertiser company this contact is associated with. -ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - -# Set the ID of the agency company this contact is associated with. -AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE' - - -def main(client, advertiser_company_id, agency_company_id): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201511') - - # Create an advertiser contact. - advertiser_contact = { - 'name': 'Mr. Advertiser #%s' % uuid.uuid4(), - 'email': 'advertiser@advertising.com', - 'companyId': advertiser_company_id - } - - # Create an agency contact. - agency_contact = { - 'name': 'Ms. Agency #%s' % uuid.uuid4(), - 'email': 'agency@agencies.com', - 'companyId': agency_company_id - } - - # Create the contacts on the server. - contacts = contact_service.createContacts([advertiser_contact, - agency_contact]) - - # Display results. - for contact in contacts: - print ('Contact with ID \'%s\' name \'%s\' was created.' - % (contact['id'], contact['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) diff --git a/examples/dfp/v201511/contact_service/get_uninvited_contacts.py b/examples/dfp/v201511/contact_service/get_uninvited_contacts.py deleted file mode 100755 index 4ca72a5d..00000000 --- a/examples/dfp/v201511/contact_service/get_uninvited_contacts.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all contacts that aren't invited yet. - -To create contacts, run create_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201511') - - # Create statement object to only select contacts that are uninvited. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get contacts by statement. - while True: - response = contact_service.getContactsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for contact in response['results']: - print ('Contact with ID \'%s\' and name \'%s\' was found.' - % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201511/content_metadata_key_hierarchy_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/content_metadata_key_hierarchy_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201511/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py deleted file mode 100755 index 54017130..00000000 --- a/examples/dfp/v201511/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all content metadata key hierarchies. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201511') - - # Create statement object to select all content. - statement = dfp.FilterStatement() - - # Get content by statement. - while True: - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())[0]) - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - if content_metadata_key_hierarchies: - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchyy with id \'%s\' and name \'%s\'' - ' was found.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201511/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py deleted file mode 100755 index dee65348..00000000 --- a/examples/dfp/v201511/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the content metadata key hierarchy to update. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') -# Set the ID of the custom targeting key to be added as a hierarchy level. -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201511') - - # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement()))[0] - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - if content_metadata_key_hierarchies: - content_metadata_key_hierarchy = content_metadata_key_hierarchies[0] - - # Update the content metadata key hierarchy by adding a hierarchy level. - hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels'] - - hierarchy_level = { - 'customTargetingKeyId': custom_targeting_key_id, - 'hierarchyLevel': str(len(hierarchy_levels) + 1) - } - - content_metadata_key_hierarchy['hierarchyLevels'] = ( - hierarchy_levels.append(hierarchy_level)) - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies)) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id \'%s\' and name \'%s\'' - ' was updated.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - else: - print 'No content metadata key hierarchies were found' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201511/content_service/__init__.py b/examples/dfp/v201511/content_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/content_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/content_service/get_all_content.py b/examples/dfp/v201511/content_service/get_all_content.py deleted file mode 100755 index e7747145..00000000 --- a/examples/dfp/v201511/content_service/get_all_content.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all content. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201511') - - # Create statement object to select all content. - statement = dfp.FilterStatement() - - # Get content by statement. - while True: - response = content_service.getContentByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for content_item in response['results']: - print ('Content with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (content_item['id'], content_item['name'], - content_item['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/content_service/get_content_by_category.py b/examples/dfp/v201511/content_service/get_content_by_category.py deleted file mode 100755 index 19c55e77..00000000 --- a/examples/dfp/v201511/content_service/get_content_by_category.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active content categorized as a "comedy" using the -network's content browse custom targeting key. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201511') - network_service = client.GetService('NetworkService', version='v201511') - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') - - # Get the network's content browse custom targeting key. - network = network_service.getCurrentNetwork() - key_id = network['contentBrowseCustomTargetingKeyId'] - - # Create a statement to select the categories matching the name comedy. - values = [ - { - 'key': 'contentBrowseCustomTargetingKeyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }, - { - 'key': 'category', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'comedy' - } - } - ] - category_filter_query = ('WHERE customTargetingKeyId = ' - ':contentBrowseCustomTargetingKeyId and name = ' - ':category') - category_filter_statement = dfp.FilterStatement( - category_filter_query, values, 1) - - # Get categories matching the filter statement. - response = custom_targeting_service.getCustomTargetingValuesByStatement( - category_filter_statement.ToStatement()) - - # Get the custom targeting value ID for the comedy category. - if 'results' in response: - category_custom_targeting_value_id = (response['results']['id']) - - # Create a statement to select the active content. - content_values = [ - { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - } - ] - content_query = 'WHERE status = :status' - content_statement = dfp.FilterStatement(content_query, content_values) - - while True: - # Get the content by statement and custom targeting value. - response = content_service.getContentByStatementAndCustomTargetingValue( - content_statement.ToStatement(), - category_custom_targeting_value_id) - if 'results' in response: - # Display results. - for content_item in response['results']: - print ('Content with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (content_item['id'], content_item['name'], - content_item['status'])) - content_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/creative_service/__init__.py b/examples/dfp/v201511/creative_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/creative_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/creative_service/create_creative_from_template.py b/examples/dfp/v201511/creative_service/create_creative_from_template.py deleted file mode 100755 index b8e0081c..00000000 --- a/examples/dfp/v201511/creative_service/create_creative_from_template.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates a new template creative for a given advertiser. - -To determine which companies are advertisers, run get_advertisers.py. -To determine which creative templates exist, run -get_all_creative_templates.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import os -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the advertiser (company) that the creative will be assigned to. -ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201511') - - # Use the image banner with optional third party tracking template. - creative_template_id = '10000680' - - image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r').read() - image_data = base64.encodestring(image_data) - # Create creative from templates. - creative = { - 'xsi_type': 'TemplateCreative', - 'name': 'Template Creative #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'size': {'width': '300', 'height': '250'}, - 'creativeTemplateId': creative_template_id, - 'creativeTemplateVariableValues': [ - { - 'xsi_type': 'AssetCreativeTemplateVariableValue', - 'uniqueName': 'Imagefile', - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() - }, - { - 'xsi_type': 'LongCreativeTemplateVariableValue', - 'uniqueName': 'Imagewidth', - 'value': '300' - }, - { - 'xsi_type': 'LongCreativeTemplateVariableValue', - 'uniqueName': 'Imageheight', - 'value': '250' - }, - { - 'xsi_type': 'UrlCreativeTemplateVariableValue', - 'uniqueName': 'ClickthroughURL', - 'value': 'www.google.com' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Targetwindow', - 'value': '_blank' - } - ] - } - - # Call service to create the creative. - creative = creative_service.createCreatives([creative])[0] - - # Display results. - print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201511/creative_service/get_all_creatives.py b/examples/dfp/v201511/creative_service/get_all_creatives.py deleted file mode 100755 index 2d3de109..00000000 --- a/examples/dfp/v201511/creative_service/get_all_creatives.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all creatives. - -To create creatives, run create_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201511') - - # Create statement object to select all creatives. - statement = dfp.FilterStatement() - - # Get creatives by statement. - while True: - response = creative_service.getCreativesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative in response['results']: - print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (creative['id'], creative['name'], - dfp.DfpClassType(creative))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/creative_service/get_creatives_by_statement.py b/examples/dfp/v201511/creative_service/get_creatives_by_statement.py deleted file mode 100755 index a57f641c..00000000 --- a/examples/dfp/v201511/creative_service/get_creatives_by_statement.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all image creatives. - -To create an image creative, run create_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201511') - - # Create statement object to only select image creatives. - values = [{ - 'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }] - query = 'WHERE creativeType = :creativeType' - statement = dfp.FilterStatement(query, values) - - # Get creatives by statement. - while True: - response = creative_service.getCreativesByStatement( - statement.ToStatement()) - creatives = response['results'] - - if creatives: - # Display results. - for creative in creatives: - print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (creative['id'], creative['name'], - dfp.DfpClassType(creative))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/creative_service/update_creatives.py b/examples/dfp/v201511/creative_service/update_creatives.py deleted file mode 100755 index 025e18e2..00000000 --- a/examples/dfp/v201511/creative_service/update_creatives.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates the destination URL of a single image creative. - -To determine which image creatives exist, run get_all_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE' - - -def main(client, image_creative_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201511') - - # Create statement object to get all image creatives. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }, { - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': image_creative_id - } - }] - query = 'WHERE creativeType = :type AND id = :id' - statement = dfp.FilterStatement(query, values, 1) - - # Get creatives by statement. - response = creative_service.getCreativesByStatement( - statement.ToStatement()) - - if 'results' in response: - # Update each local creative object by changing its destination URL. - updated_creatives = [] - for creative in response['results']: - creative['destinationUrl'] = 'http://news.google.com' - updated_creatives.append(creative) - - # Update creatives remotely. - creatives = creative_service.updateCreatives(updated_creatives) - - # Display results. - for creative in creatives: - print ('Image creative with id \'%s\' and destination URL \'%s\' was ' - 'updated.' % (creative['id'], creative['destinationUrl'])) - else: - print 'No creatives found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, IMAGE_CREATIVE_ID) diff --git a/examples/dfp/v201511/creative_set_service/__init__.py b/examples/dfp/v201511/creative_set_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/creative_set_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201511/creative_set_service/associate_creative_set_to_line_item.py deleted file mode 100755 index f7a74261..00000000 --- a/examples/dfp/v201511/creative_set_service/associate_creative_set_to_line_item.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates a line item creative association for a creative -set. - -To create creative sets, run create_creative_set.py. To create creatives, run -create_creatives.py. To determine which LICAs exist, run get_all_licas.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, creative_set_id, line_item_id): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201511') - - # Create LICA for a creative set. - lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} - - # Add LICA. - lica = lica_service.createLineItemCreativeAssociations([lica]) - - # Display results. - print (('LICA with line item ID \'%s\' and creative set ID \'%s\' was ' - 'created.') % (lica['lineItemId'], lica['creativeSetId'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_SET_ID, LINE_ITEM_ID) diff --git a/examples/dfp/v201511/creative_set_service/create_creative_set.py b/examples/dfp/v201511/creative_set_service/create_creative_set.py deleted file mode 100755 index 5a3cdaa0..00000000 --- a/examples/dfp/v201511/creative_set_service/create_creative_set.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new creative sets. - -To determine which creative sets exist, run get_all_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' -COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' - - -def main(client, master_creative_id, companion_creative_id): - # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201511') - - # Create creative set objects. - creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), - 'masterCreativeId': master_creative_id, - 'companionCreativeIds': [companion_creative_id]} - - # Add creative sets. - creative_set = creative_set_service.createCreativeSet(creative_set) - - # Display results. - if creative_set: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' - 'companion creative IDs {%s} was created.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) diff --git a/examples/dfp/v201511/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201511/creative_set_service/get_all_creative_sets.py deleted file mode 100755 index 8bbcd04b..00000000 --- a/examples/dfp/v201511/creative_set_service/get_all_creative_sets.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all creative sets. - -To create creative sets, run create_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get creative sets by statement. - while True: - response = creative_set_service.getCreativeSetsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_set in response['results']: - print ('Creative set with ID \'%s\' and name \'%s\' was found.' - % (creative_set['id'], creative_set['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201511/creative_set_service/get_creative_sets_by_statement.py deleted file mode 100755 index 9afe63a5..00000000 --- a/examples/dfp/v201511/creative_set_service/get_creative_sets_by_statement.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all creative sets for a master creative. - -To create creative sets, run create_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' - - -def main(client, master_creative_id): - # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201511') - - # Create statement object to only select creative sets that have the given - # master creative. - values = [{ - 'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': master_creative_id - } - }] - query = 'WHERE masterCreativeId = :masterCreativeId' - statement = dfp.FilterStatement(query, values) - - # Get creative sets by statement. - while True: - response = creative_set_service.getCreativeSetsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_set in response['results']: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' - 'companion creative IDs {%s} was found.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, MASTER_CREATIVE_ID) diff --git a/examples/dfp/v201511/creative_set_service/update_creative_set.py b/examples/dfp/v201511/creative_set_service/update_creative_set.py deleted file mode 100755 index 3c041d91..00000000 --- a/examples/dfp/v201511/creative_set_service/update_creative_set.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates a creative set by adding a companion creative. - -To determine which creative sets exist, run get_all_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the creative set to update. -CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' -COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' - - -def main(client, creative_set_id, companion_creative_id): - # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201511') - - # Create statement to select a single creative set by ID. - values = [{ - 'key': 'creativeSetId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_set_id - } - }] - query = 'WHERE id = :creativeSetId' - statement = dfp.FilterStatement(query, values) - - # Get creative set. - response = creative_set_service.getCreativeSetsByStatement( - statement.ToStatement()) - - if 'results' in response: - updated_created_sets = [] - for creative_set in response['results']: - creative_set['companionCreativeIds'].append(companion_creative_id) - updated_created_sets.append(creative_set) - - # Update the creative sets on the server. - creative_sets = creative_set_service.updateCreativeSet(updated_created_sets) - - # Display results. - for creative_set in creative_sets: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' - 'companion creative IDs {%s} was updated.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) - else: - print 'No creative sets found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) diff --git a/examples/dfp/v201511/creative_template_service/__init__.py b/examples/dfp/v201511/creative_template_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/creative_template_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201511/creative_template_service/get_creative_templates_by_statement.py deleted file mode 100755 index b0be9179..00000000 --- a/examples/dfp/v201511/creative_template_service/get_creative_templates_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all system defined creative templates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201511') - - # Create statement object to only select system defined creative templates. - values = [{ - 'key': 'creativeTemplateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - } - }] - query = 'WHERE type = :creativeTemplateType' - statement = dfp.FilterStatement(query, values) - - # Get creative templates by statement. - while True: - response = creative_template_service.getCreativeTemplatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for template in response['results']: - print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' ' - 'was found.' % (template['id'], - template['name'], - template['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201511/creative_wrapper_service/create_creative_wrappers.py deleted file mode 100755 index 19c05e39..00000000 --- a/examples/dfp/v201511/creative_wrapper_service/create_creative_wrappers.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates a new creative wrapper. - -Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and -applied to ad units by AdUnit.appliedLabels. To determine which creative -wrappers exist, run get_all_creative_wrappers.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE' - - -def main(client, label_id): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201511') - - # Create creative wrapper objects. - creative_wrapper = { - # A label can only be associated with one creative wrapper. - 'labelId': label_id, - 'ordering': 'INNER', - 'header': {'htmlSnippet': 'My creative wrapper header'}, - 'footer': {'htmlSnippet': 'My creative wrapper footer'} - } - - # Add creative wrapper. - creative_wrappers = creative_wrapper_service.createCreativeWrappers( - [creative_wrapper]) - - # Display results. - for creative_wrapper in creative_wrappers: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) diff --git a/examples/dfp/v201511/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201511/creative_wrapper_service/get_active_creative_wrappers.py deleted file mode 100755 index e7e06ac9..00000000 --- a/examples/dfp/v201511/creative_wrapper_service/get_active_creative_wrappers.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active creative wrappers. - -To create creative wrappers, run create_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201511') - - # Create statement object to only select active creative wrappers. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get creative wrappers by statement. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'found.' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201511/creative_wrapper_service/get_all_creative_wrappers.py deleted file mode 100755 index feaf9556..00000000 --- a/examples/dfp/v201511/creative_wrapper_service/get_all_creative_wrappers.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all creative wrappers. - -To create creative wrappers, run create_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get creative wrappers by statement. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'found.' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201511/creative_wrapper_service/update_creative_wrappers.py deleted file mode 100755 index 85db9fc9..00000000 --- a/examples/dfp/v201511/creative_wrapper_service/update_creative_wrappers.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates a creative wrapper to the 'OUTER' wrapping order. - -To determine which creative wrappers exist, run get_all_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the creative wrapper to update. -CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE' - - -def main(client, creative_wrapper_id): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201511') - - # Create statement to get a creative wrapper by ID. - values = [{ - 'key': 'creativeWrapperId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_wrapper_id - } - }] - query = 'WHERE id = :creativeWrapperId' - statement = dfp.FilterStatement(query, values) - - # Get creative wrappers. - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - - if 'results' in response: - updated_creative_wrappers = [] - for creative_wrapper in response['results']: - creative_wrapper['ordering'] = 'OUTER' - updated_creative_wrappers.append(creative_wrapper) - - # Update the creative wrappers on the server. - creative_wrappers = creative_wrapper_service.updateCreativeWrappers( - updated_creative_wrappers) - - # Display results. - for creative_wrapper in creative_wrappers: - print (('Creative wrapper with ID \'%s\' and wrapping order \'%s\' ' - 'was updated.') % (creative_wrapper['id'], - creative_wrapper['ordering'])) - else: - print 'No creative wrappers found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_WRAPPER_ID) diff --git a/examples/dfp/v201511/custom_field_service/__init__.py b/examples/dfp/v201511/custom_field_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/custom_field_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201511/custom_field_service/deactivate_all_line_item_custom_fields.py deleted file mode 100755 index 20e17ebc..00000000 --- a/examples/dfp/v201511/custom_field_service/deactivate_all_line_item_custom_fields.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deactivates all active line items custom fields. - -To determine which custom fields exist, run get_all_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201511') - - # Create statement to select only active custom fields that apply to - # line items. - values = [ - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }, { - 'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - } - ] - query = 'WHERE entityType = :entityType and isActive = :isActive' - statement = dfp.FilterStatement(query, values) - - custom_fields_deactivated = 0 - - # Get custom fields by statement. - while True: - response = custom_field_service.getCustomFieldsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' will' - ' be deactivated.' % (custom_field['id'], custom_field['name'])) - result = custom_field_service.performCustomFieldAction( - {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - custom_fields_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if custom_fields_deactivated > 0: - print 'Number of custom fields deactivated: %s' % custom_fields_deactivated - else: - print 'No custom fields were deactivated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201511/custom_field_service/get_all_line_item_custom_fields.py deleted file mode 100755 index c2932572..00000000 --- a/examples/dfp/v201511/custom_field_service/get_all_line_item_custom_fields.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 fields that apply to line items. - -To create custom fields, run create_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201511') - - # Create statement to select only custom fields that apply to line items. - values = [{ - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }] - query = 'WHERE entityType = :entityType' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get custom fields by statement. - while True: - response = custom_field_service.getCustomFieldsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' was found.' - % (custom_field['id'], custom_field['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/custom_targeting_service/__init__.py b/examples/dfp/v201511/custom_targeting_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/custom_targeting_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201511/custom_targeting_service/create_custom_targeting_keys_and_values.py deleted file mode 100755 index d8107011..00000000 --- a/examples/dfp/v201511/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates new custom targeting keys and values. - -To determine which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py. To target these custom targeting -keys and values, run target_custom_criteria_example.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') - - # Create custom targeting key objects. - keys = [ - { - 'displayName': 'gender', - 'name': 'g', - 'type': 'PREDEFINED' - }, - { - 'displayName': 'car model', - 'name': 'c', - 'type': 'FREEFORM' - }, - # Add predefined key that may be use for content targeting. - { - 'displayName': 'genre', - 'name': 'genre', - 'type': 'PREDEFINED' - } - ] - - # Add custom targeting keys. - keys = custom_targeting_service.createCustomTargetingKeys(keys) - - # Display results. - if keys: - for key in keys: - print ('A custom targeting key with id \'%s\', name \'%s\', and display ' - 'name \'%s\' was created.' % (key['id'], key['name'], - key['displayName'])) - else: - print 'No keys were created.' - - # Create custom targeting value objects. - values = [ - { - 'customTargetingKeyId': keys['id'], - 'displayName': 'male', - # Name is set to 1 so that the actual name can be hidden from website - # users. - 'name': '1', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys['id'], - 'displayName': 'female', - # Name is set to 2 so that the actual name can be hidden from website - # users. - 'name': '2', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[1]['id'], - 'displayName': 'honda civic', - 'name': 'honda civic', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[1]['id'], - 'displayName': 'toyota', - 'name': 'toyota', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[2]['id'], - 'displayName': 'comedy', - 'name': 'comedy', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[2]['id'], - 'displayName': 'drama', - 'name': 'drama', - 'matchType': 'EXACT' - } - ] - - # Add custom targeting values. - values = custom_targeting_service.createCustomTargetingValues(values) - - # Display results. - if values: - for value in values: - print ('A custom targeting value with id \'%s\', belonging to key with id' - ' \'%s\', name \'%s\', and display name \'%s\' was created.' - % (value['id'], value['customTargetingKeyId'], value['name'], - value['displayName'])) - else: - print 'No values were created.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_values.py deleted file mode 100755 index 1f81302d..00000000 --- a/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_values.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 deletes custom targeting values for a given custom targeting -key. - -To determine which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') - - filter_values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, filter_values) - - deleted_custom_targeting_values = 0 - - # Get custom targeting values. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - if 'results' in response: - value_ids = [value['id'] for value in response['results']] - action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_query = ('WHERE customTargetingKeyId = :keyId ' - 'AND id IN (%s)' % ', '.join(value_ids)) - value_statement = dfp.FilterStatement(value_query, filter_values) - - # Delete custom targeting values. - result = custom_targeting_service.performCustomTargetingValueAction( - action, value_statement.ToStatement()) - if result and int(result['numChanges']) > 0: - deleted_custom_targeting_values += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if deleted_custom_targeting_values > 0: - print ('Number of custom targeting values deleted: %s' - % deleted_custom_targeting_values) - else: - print 'No custom targeting values were deleted.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, KEY_ID) diff --git a/examples/dfp/v201511/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201511/custom_targeting_service/get_all_custom_targeting_keys_and_values.py deleted file mode 100755 index 7f44e6cc..00000000 --- a/examples/dfp/v201511/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 targeting keys and the values. - -To create custom targeting keys and values, run -create_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') - - # Create statement to get all targeting keys. - targeting_key_statement = dfp.FilterStatement() - - all_keys = [] - - # Get custom targeting keys by statement. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - targeting_key_statement.ToStatement()) - if 'results' in response: - all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if all_keys: - # Create map of custom targeting key id to custom targeting values. - key_value_map = {} - - # Create statement to get all targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' - % ', '.join([str(key['id']) for key in all_keys])) - targeting_value_statement = dfp.FilterStatement(query) - - # Get custom targeting values by statement. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - targeting_value_statement.ToStatement()) - if 'results' in response: - for key in all_keys: - for value in response['results']: - if key['id'] == value['customTargetingKeyId']: - if key['id'] not in key_value_map.keys(): - key_value_map[key['id']] = [] - key_value_map[key['id']].append(value) - targeting_value_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - for key in all_keys: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was found.' - %(key['id'], key['name'], key['displayName'], key['type'])) - if key['id'] in key_value_map.keys(): - for value in key_value_map[key['id']]: - print ('\tCustom targeting value with id \'%s\', name \'%s\', and ' - 'display name \'%s\' was found.' - % (value['id'], value['name'], value['displayName'])) - else: - print 'No keys were found.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) - diff --git a/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_keys_by_statement.py deleted file mode 100755 index 7018ca2d..00000000 --- a/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 predefined custom targeting keys. - -To create custom targeting keys, run create_custom_targeting_keys_and_values.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') - - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] - query = 'WHERE type = :type' - statement = dfp.FilterStatement(query, values) - - # Get custom targeting keys by statement. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for key in response['results']: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was found.' - % (key['id'], key['name'], key['displayName'], key['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_values_by_statement.py deleted file mode 100755 index f0cbf056..00000000 --- a/examples/dfp/v201511/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 custom targeting values for the given predefined custom -targeting key. - -To create custom targeting values, run -create_custom_targeting_keys_and_values.py. To determine which custom -targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') - - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) - - # Get custom targeting values by statement. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for value in response['results']: - print ('Custom targeting value with id \'%s\', name \'%s\', and display' - ' name \'%s\' was found.' - % (value['id'], value['name'], value['displayName'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_keys.py deleted file mode 100755 index 1c15b143..00000000 --- a/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_keys.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates the display name of a single custom targeting key. - -To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') - - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE id = :keyId' - statement = dfp.FilterStatement(query, values, 1) - - # Get custom targeting keys by statement. - response = custom_targeting_service.getCustomTargetingKeysByStatement( - statement.ToStatement()) - - # Update each local custom targeting key object by changing its display name. - if 'results' in response: - updated_keys = [] - for key in response['results']: - if not key['displayName']: - key['displayName'] = key['name'] - key['displayName'] += ' (Deprecated)' - updated_keys.append(key) - keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys) - - # Display results. - if keys: - for key in keys: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was updated.' - % (key['id'], key['name'], key['displayName'], key['type'])) - else: - print 'No custom targeting keys were found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_values.py deleted file mode 100755 index 07eee074..00000000 --- a/examples/dfp/v201511/custom_targeting_service/update_custom_targeting_values.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates the display name of the custom targeting values -belonging to a custom targeting key. - -To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') - - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get custom targeting values by statement. - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - - # Update each local custom targeting value object by changing its name. - if 'results' in response: - updated_values = [] - for value in response['results']: - if not value['displayName']: - value['displayName'] = value['name'] - value['displayName'] += ' (Deprecated)' - updated_values.append(value) - values = custom_targeting_service.updateCustomTargetingValues( - updated_values) - - # Display results. - for value in values: - print ('Custom targeting value with id \'%s\', name \'%s\', and display' - ' name \'%s\' was updated.' - % (value['id'], value['name'], value['displayName'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if response['totalResultSetSize'] == 0: - print 'No custom targeting values were updated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201511/exchange_rate_service/__init__.py b/examples/dfp/v201511/exchange_rate_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/exchange_rate_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201511/exchange_rate_service/create_exchange_rates.py deleted file mode 100755 index 10bc9b2d..00000000 --- a/examples/dfp/v201511/exchange_rate_service/create_exchange_rates.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates an exchange rate. - -To determine which exchange rates exist, run get_all_exchange_rates.py. - - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201511') - - # Create a new fixed exchange rate with currency code 'AUD', with direction - # FROM_NETWORK with a value of 1.5. - exchange_rate = { - 'currencyCode': 'AUD', - 'direction': 'FROM_NETWORK', - 'exchangeRate': long(15000000000), - 'refreshRate': 'FIXED' - } - - created_exchange_rate = exchange_rate_service.createExchangeRates( - [exchange_rate])[0] - - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was created.' % (created_exchange_rate['id'], - created_exchange_rate['currencyCode'], - created_exchange_rate['direction'], - (float(created_exchange_rate['exchangeRate']) / - 10000000000))) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201511/exchange_rate_service/get_exchange_rates_by_currency_code.py deleted file mode 100755 index 8e4b1bc9..00000000 --- a/examples/dfp/v201511/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the exchange rate for a specific currency code. - -To create exchange rates, run create_exchange_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client, currency_code): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201511') - - # Create a statement to get exchange rates for the specified currency code. - values = [{ - 'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - } - }] - query = 'WHERE currencyCode = :currencyCode' - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get rate cards by statement. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for exchange_rate in response['results']: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was found.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CURRENCY_CODE) diff --git a/examples/dfp/v201511/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201511/exchange_rate_service/update_exchange_rates.py deleted file mode 100755 index 15cb0e3d..00000000 --- a/examples/dfp/v201511/exchange_rate_service/update_exchange_rates.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates the value of an exchange rate. - -To create exchange rates, run create_exchange_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' - - -def main(client, exchange_rate_id): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201511') - - # Create a statement to get an exchange rate by its ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': exchange_rate_id - } - }] - query = 'WHERE id = :id' - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) - - # Get rate cards by statement. - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - - if 'results' in response: - exchange_rate = response['results'][0] - - # Update the exchange rate value to 1.5. - exchange_rate['exchangeRate'] = long(15000000000) - - exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) - - if exchange_rates: - for exchange_rate in exchange_rates: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was updated.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) - else: - print 'No exchange rates were updated.' - else: - print 'No exchange rates found to update.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, EXCHANGE_RATE_ID) diff --git a/examples/dfp/v201511/forecast_service/get_availability_forecast.py b/examples/dfp/v201511/forecast_service/get_availability_forecast.py deleted file mode 100755 index 152bbb88..00000000 --- a/examples/dfp/v201511/forecast_service/get_availability_forecast.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a forecast for a prospective line item. - -The prospective line item targets the entire network. The targeting can be -modified to determine forecasts for other criteria such as custom criteria -targeting (in addition to targeting the whole network). See -create_line_items.py for an example of how to create more complex targeting. - -""" - - -from datetime import date - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the advertiser (company) to forecast for. Setting an advertiser -# will cause the forecast to apply the appropriate unified blocking rules. -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201511') - network_service = client.GetService('NetworkService', version='v201511') - - # get the root ad unit ID to target the entire network. - root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - # Create prospective line item. - line_item = { - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': [ - { - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id, - } - ] - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '300', - 'height': '250' - } - }, - { - 'size': { - 'width': '120', - 'height': '600' - } - } - ], - 'lineItemType': 'SPONSORSHIP', - 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/New_York' - }, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'DAILY' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'EVEN', - 'discountType': 'PERCENTAGE', - } - - prospective_line_item = { - 'lineItem': line_item, - 'advertiserId': advertiser_id - } - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - 'includeTargetingCriteriaBreakdown': True, - } - - # Get forecast. - forecast = forecast_service.getAvailabilityForecast( - prospective_line_item, forecast_options) - matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) - - # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) - - if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201511/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201511/forecast_service/get_availability_forecast_for_line_item.py deleted file mode 100755 index 6a869a44..00000000 --- a/examples/dfp/v201511/forecast_service/get_availability_forecast_for_line_item.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets an availability forecast for an existing line item. - -To determine which line items exist, run get_all_line_items.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the line item to get a forecast for. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, line_item_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201511') - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - 'includeTargetingCriteriaBreakdown': True, - } - - # Get forecast for line item. - forecast = forecast_service.getAvailabilityForecastById( - line_item_id, forecast_options) - matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) - - # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) - - if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201511/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201511/forecast_service/get_delivery_forecast_for_line_items.py deleted file mode 100755 index 01d0b6c7..00000000 --- a/examples/dfp/v201511/forecast_service/get_delivery_forecast_for_line_items.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets a delivery forecast for two existing line items. - -To determine which line items exist, run get_all_line_items.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the line items to get forecasts for. -LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' -LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE' - - -def main(client, line_item_id1, line_item_id2): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201511') - - # Get forecast for line item. - forecast = forecast_service.getDeliveryForecastByIds( - [line_item_id1, line_item_id2], None) - - for single_forecast in forecast['lineItemDeliveryForecasts']: - unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' - '%d %s predicted\n' % ( - single_forecast['lineItemId'], single_forecast['matchedUnits'], - unit_type, single_forecast['deliveredUnits'], unit_type, - single_forecast['predictedDeliveryUnits'], unit_type)) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201511/inventory_service/__init__.py b/examples/dfp/v201511/inventory_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/inventory_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/inventory_service/archive_ad_units.py b/examples/dfp/v201511/inventory_service/archive_ad_units.py deleted file mode 100755 index abacd508..00000000 --- a/examples/dfp/v201511/inventory_service/archive_ad_units.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example archives ad units. - -The parent ad unit and all ad units underneath it will be archived. To create ad -units, run create_ad_units.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' - - -def main(client, parent_id): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201511') - - # Create a query to select ad units under the parent ad unit and the parent ad - # unit. - values = [{ - 'key': 'parentId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': parent_id - } - }] - query = 'WHERE parentId = :parentId or id = :parentId' - statement = dfp.FilterStatement(query, values) - - ad_units_archived = 0 - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' will be archived.' - % (ad_unit['id'], ad_unit['name'])) - # Perform action. - result = inventory_service.performAdUnitAction( - {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - ad_units_archived += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if ad_units_archived > 0: - print 'Number of ad units archived: %s' % ad_units_archived - else: - print 'No ad units were archived.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PARENT_AD_UNIT_ID) diff --git a/examples/dfp/v201511/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201511/inventory_service/get_ad_unit_hierarchy.py deleted file mode 100755 index 48edc04a..00000000 --- a/examples/dfp/v201511/inventory_service/get_ad_unit_hierarchy.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code gets the ad unit hierarchy and displays it as a tree. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201511') - statement = dfp.FilterStatement() - - all_ad_units = [] - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - all_ad_units.extend(response['results']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Find the root ad unit. root_ad_unit can also be set to child unit to only - # build and display a portion of the tree. - query = 'WHERE parentId IS NULL' - root_statement = dfp.FilterStatement(query) - response = inventory_service.getAdUnitsByStatement( - root_statement.ToStatement()) - root_ad_unit = response['results'] - - if root_ad_unit: - BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units) - else: - print 'Could not build tree. No root ad unit found.' - - -def DisplayAdUnitTree(root_ad_unit, ad_unit_tree, depth=0): - """Helper for displaying ad unit tree. - - Args: - root_ad_unit: dict the root ad unit. - ad_unit_tree: dict the tree of ad units. - [optional] - depth: int the depth the tree has reached. - """ - print '%s%s (%s)' % (GenerateTab(depth), root_ad_unit['name'], - root_ad_unit['id']) - if root_ad_unit['id'] in ad_unit_tree: - for child in ad_unit_tree[root_ad_unit['id']]: - DisplayAdUnitTree(child, ad_unit_tree, depth+1) - - -def GenerateTab(depth): - """Generate tabs to represent branching to children. - - Args: - depth: int the depth the tree has reached. - - Returns: - string inserted in front of the root unit. - """ - tab_list = [] - if depth > 0: - tab_list.append(' ') - tab_list.append('| ' * depth) - tab_list.append('+--') - return ''.join(tab_list) - - -def BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units): - """Create an ad unit tree and display it. - - Args: - root_ad_unit: dict the root ad unit to build the tree under. - all_ad_units: list the list of all ad units to build the tree with. - """ - tree = {} - for ad_unit in all_ad_units: - if 'parentId' in ad_unit: - if ad_unit['parentId'] not in tree: - tree[ad_unit['parentId']] = [] - tree[ad_unit['parentId']].append(ad_unit) - - DisplayAdUnitTree(root_ad_unit, tree) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201511/inventory_service/get_all_ad_unit_sizes.py deleted file mode 100755 index 60427703..00000000 --- a/examples/dfp/v201511/inventory_service/get_all_ad_unit_sizes.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all ad unit sizes defined in a network. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201511') - statement = dfp.FilterStatement() - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitSizesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit_size in response['results']: - print ('Ad unit size of dimensions %s was found.' % - (ad_unit_size['fullDisplayString'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/inventory_service/get_all_ad_units.py b/examples/dfp/v201511/inventory_service/get_all_ad_units.py deleted file mode 100755 index 45fe7a33..00000000 --- a/examples/dfp/v201511/inventory_service/get_all_ad_units.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all ad units within a network. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201511') - statement = dfp.FilterStatement() - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' was found.' - % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201511/inventory_service/get_top_level_ad_units.py deleted file mode 100755 index 00994c63..00000000 --- a/examples/dfp/v201511/inventory_service/get_top_level_ad_units.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all child ad units of the effective root ad unit. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201511') - network_service = client.GetService('NetworkService', version='v201511') - - root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - # Create a statement to select the children of the effective root ad unit. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': root_id - } - }] - query = 'WHERE parentId = :id' - statement = dfp.FilterStatement(query, values) - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' was found.' - % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/inventory_service/update_ad_units.py b/examples/dfp/v201511/inventory_service/update_ad_units.py deleted file mode 100755 index 3c8bdf43..00000000 --- a/examples/dfp/v201511/inventory_service/update_ad_units.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates ad unit sizes by adding a banner ad size. - -To determine which ad units exist, run get_all_ad_units.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -# Set the ID of the ad unit to get. -AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' - - -def main(client, ad_unit_id): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201511') - - # Create a statement to select a single ad unit by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': ad_unit_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values) - - # Get ad units by statement. - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - - # Add the size 468x60 to the ad unit. - ad_unit_size = { - 'size': { - 'width': '468', - 'height': '60' - }, - 'environmentType': 'BROWSER' - } - - if 'results' in response: - updated_ad_units = [] - for ad_unit in response['results']: - if 'adUnitSizes' not in ad_unit: - ad_unit['adUnitSizes'] = [] - ad_unit['adUnitSizes'].append(ad_unit_size) - updated_ad_units.append(ad_unit) - - # Update ad unit on the server. - ad_units = inventory_service.updateAdUnits(updated_ad_units) - - # Display results. - for ad_unit in ad_units: - ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], - size['size']['height']) - for size in ad_unit['adUnitSizes']] - print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated' - % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AD_UNIT_ID) diff --git a/examples/dfp/v201511/label_service/__init__.py b/examples/dfp/v201511/label_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/label_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/label_service/deactivate_labels.py b/examples/dfp/v201511/label_service/deactivate_labels.py deleted file mode 100755 index 0ef77133..00000000 --- a/examples/dfp/v201511/label_service/deactivate_labels.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example deactivates all active Labels. - -To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201511') - - # Create query. - values = [{ - 'key': 'isActive', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'true' - } - }] - query = 'WHERE isActive = :isActive' - statement = dfp.FilterStatement(query, values) - - labels_deactivated = 0 - - # Get labels by statement. - while True: - response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: - for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' will be ' - 'deactivated.' % (label['id'], label['name'])) - # Perform action. - result = label_service.performLabelAction( - {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - labels_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if labels_deactivated > 0: - print 'Number of labels deactivated: %s' % labels_deactivated - else: - print 'No labels were deactivated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/label_service/update_labels.py b/examples/dfp/v201511/label_service/update_labels.py deleted file mode 100755 index ad428db9..00000000 --- a/examples/dfp/v201511/label_service/update_labels.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates the description of a single label. - -To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, label_id): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201511') - - # Create a statement to select only active labels. - values = [ - { - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - } - ] - query = 'WHERE id = :labelId' - statement = dfp.FilterStatement(query, values) - - # Get labels by filter. - response = label_service.getLabelsByStatement(statement.ToStatement()) - - if 'results' in response: - # Update each local label object by changing the description. - updated_labels = [] - for label in response['results']: - label['description'] = 'These labels are updated.' - updated_labels.append(label) - - # Update labels remotely. - labels = label_service.updateLabels(updated_labels) - - for label in labels: - print ('Label with id \'%s\' and name \'%s\' was updated.' - % (label['id'], label['name'])) - else: - print 'No labels found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) - diff --git a/examples/dfp/v201511/line_item_creative_association_service/__init__.py b/examples/dfp/v201511/line_item_creative_association_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/line_item_creative_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201511/line_item_creative_association_service/get_licas_by_statement.py deleted file mode 100755 index 28f3f3e6..00000000 --- a/examples/dfp/v201511/line_item_creative_association_service/get_licas_by_statement.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all line item creative associations (LICA) for a given -line item id. - -To create LICAs, run create_licas.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the line item to get LICAs by. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, line_item_id): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201511') - -# Create statement object to only select LICAs for the given line item id. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - query = 'WHERE lineItemId = :lineItemId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get LICAs by statement. - response = lica_service.getLineItemCreativeAssociationsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for lica in response['results']: - print ('LICA with line item id \'%s\', creative id \'%s\', and status ' - '\'%s\' was found.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201511/line_item_creative_association_service/update_licas.py b/examples/dfp/v201511/line_item_creative_association_service/update_licas.py deleted file mode 100755 index 7ae15ce2..00000000 --- a/examples/dfp/v201511/line_item_creative_association_service/update_licas.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates the destination URL of all line item creative -associations (LICA). - -To determine which LICAs exist, run get_all_licas.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201511') - - # Create statement object to get all LICAs. - statement = dfp.FilterStatement() - - while True: - # Get LICAs by statement. - response = lica_service.getLineItemCreativeAssociationsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Update each local LICA object by changing its destination URL. - updated_licas = [] - for lica in response['results']: - lica['destinationUrl'] = 'http://news.google.com' - updated_licas.append(lica) - - # Update LICAs remotely. - licas = lica_service.updateLineItemCreativeAssociations(updated_licas) - - # Display results. - for lica in licas: - print ('LICA with line item id \'%s\', creative id \'%s\', and status ' - '\'%s\' was updated.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if response['totalResultSetSize'] == 0: - print 'No LICAs found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/line_item_service/__init__.py b/examples/dfp/v201511/line_item_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/line_item_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/line_item_service/activate_line_items.py b/examples/dfp/v201511/line_item_service/activate_line_items.py deleted file mode 100755 index 279b317a..00000000 --- a/examples/dfp/v201511/line_item_service/activate_line_items.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example activates all line items for the given order. - -To be activated, line items need to be in the approved state and have at least -one creative associated with them. To approve line items, approve the order to -which they belong by running approve_orders.py. To create LICAs, run -create_licas.py. To determine which line items exist, run -get_all_line_items.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') - - # Create query. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' - } - }] - query = 'WHERE orderId = :orderId AND status = :status' - statement = dfp.FilterStatement(query, values) - - line_items_activated = 0 - - # Get line items by statement. - while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - if 'results' in response: - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'name \'%s\' will be activated.' % - (line_item['id'], line_item['orderId'], line_item['name'])) - - # Perform action. - result = line_item_service.performLineItemAction( - {'xsi_type': 'ActivateLineItems'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - line_items_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if line_items_activated > 0: - print 'Number of line items activated: %s' % line_items_activated - else: - print 'No line items were activated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201511/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201511/line_item_service/get_line_items_by_statement.py deleted file mode 100755 index 587e626e..00000000 --- a/examples/dfp/v201511/line_item_service/get_line_items_by_statement.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all line items that need creatives for an order. - -To create line items, run create_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') - - # Create statement object to only select line items that need creatives from a - # given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - }] - query = ('WHERE orderId = :orderId AND ' - 'isMissingCreatives = :isMissingCreatives') - statement = dfp.FilterStatement(query, values) - - while True: - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % (line_item['id'], - line_item['orderId'], - line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201511/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201511/line_item_service/get_recently_updated_line_items.py deleted file mode 100755 index 193cdcbd..00000000 --- a/examples/dfp/v201511/line_item_service/get_recently_updated_line_items.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example shows how to get recently updated line items. - -To create line items, run create_line_items.py.""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import dfp - -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') - - # Create statement object to only select line items belonging to the order and - # have been modified in the last 3 days. - three_days_ago = datetime.date.today() - datetime.timedelta(days=3) - values = [{ - 'key': 'dateTimeString', - 'value': { - 'xsi_type': 'TextValue', - 'value': three_days_ago.strftime('%Y-%m-%dT%H:%M:%S') - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE lastModifiedDateTime >= :dateTimeString AND orderId = :orderId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % (line_item['id'], - line_item['orderId'], - line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201511/line_item_service/target_custom_criteria.py b/examples/dfp/v201511/line_item_service/target_custom_criteria.py deleted file mode 100755 index bc6d2cad..00000000 --- a/examples/dfp/v201511/line_item_service/target_custom_criteria.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates a line item to add custom criteria targeting. - -To determine which line items exist, run get_all_line_items.py. To determine -which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py.""" - - -import pprint - -# Import appropriate modules from the client library. -from googleads import dfp - -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' -KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE' -KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE' -KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE' - -VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE' -VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE' -VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE' - - -def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, - value_id3): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') - - # create custom criterias - custom_criteria1 = { - 'xsi_type': 'CustomCriteria', - 'keyId': key_id1, - 'valueIds': [value_id1], - 'operator': 'IS' - } - - custom_criteria2 = { - 'xsi_type': 'CustomCriteria', - 'keyId': key_id2, - 'valueIds': [value_id2], - 'operator': 'IS_NOT' - } - - custom_criteria3 = { - 'xsi_type': 'CustomCriteria', - 'keyId': key_id3, - 'valueIds': [value_id3], - 'operator': 'IS' - } - - # Create the custom criteria set that will resemble: - # (custom_criteria1.key == custom_criteria1.value OR - # (custom_criteria2.key != custom_criteria2.value AND - # custom_criteria13.key == custom_criteria3.value)) - sub_set = { - 'xsi_type': 'CustomCriteriaSet', - 'logicalOperator': 'AND', - 'children': [custom_criteria2, custom_criteria3] - } - - top_set = { - 'xsi_type': 'CustomCriteriaSet', - 'logicalOperator': 'OR', - 'children': [custom_criteria1, sub_set] - } - - # Create statement to get the line item - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - query = 'WHERE id = :lineItemId' - statement = dfp.FilterStatement(query, values, 1) - - # Set custom criteria targeting on the line item. - line_item = line_item_service.getLineItemsByStatement( - statement.ToStatement())['results'][0] - line_item['targeting']['customTargeting'] = top_set - - # Update line item. - line_item = line_item_service.updateLineItems([line_item])[0] - - # Display results. - if line_item: - print ('Line item with id \'%s\' updated with custom criteria targeting:' - % line_item['id']) - pprint.pprint(line_item['targeting']['customTargeting']) - else: - print 'No line items were updated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, - VALUE_ID2, VALUE_ID3) diff --git a/examples/dfp/v201511/line_item_service/update_line_items.py b/examples/dfp/v201511/line_item_service/update_line_items.py deleted file mode 100755 index 695145d3..00000000 --- a/examples/dfp/v201511/line_item_service/update_line_items.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates the delivery rate of all line items in an order. - -To determine which line items exist, run get_all_line_items.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') - - # Create statement object to only select line items with even delivery rates. - values = [{ - 'key': 'deliveryRateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'EVENLY' - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - - query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId' - statement = dfp.FilterStatement(query, values, 500) - - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Update each local line item by changing its delivery rate type. - updated_line_items = [] - for line_item in response['results']: - if not line_item['isArchived']: - line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE' - updated_line_items.append(line_item) - - # Update line items remotely. - line_items = line_item_service.updateLineItems(updated_line_items) - - # Display results. - if line_items: - for line_item in line_items: - print ('Line item with id \'%s\', belonging to order id \'%s\', named ' - '\'%s\', and delivery rate \'%s\' was updated.' - % (line_item['id'], line_item['orderId'], line_item['name'], - line_item['deliveryRateType'])) - else: - print 'No line items were updated.' - else: - print 'No line items found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201511/network_service/__init__.py b/examples/dfp/v201511/network_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/network_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/network_service/get_current_network.py b/examples/dfp/v201511/network_service/get_current_network.py deleted file mode 100755 index fd821e73..00000000 --- a/examples/dfp/v201511/network_service/get_current_network.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 the current network that you can make requests against.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201511') - - # Get the current network. - network = network_service.getCurrentNetwork() - - # Display results. - print ('Current network has network code \'%s\' and display name \'%s\'.' - % (network['networkCode'], network['displayName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/network_service/make_test_network.py b/examples/dfp/v201511/network_service/make_test_network.py deleted file mode 100755 index ff937e8d..00000000 --- a/examples/dfp/v201511/network_service/make_test_network.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates a test network. - -You do not need to have a DFP account to run this example, but you do need to -have a Google account (created at http://www.google.com/accounts/newaccount -if you currently don't have one) that is not associated with any other DFP test -networks. Once this network is created, you can supply the network code in your -settings to make calls to other services. - -Alternatively, if you do not wish to run this example, you can create a test -network at: -https://dfp-playground.appspot.com -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201511') - - # Create a test network. - network = network_service.MakeTestNetwork() - - # Display results. - print ('Test network with network code \'%s\' and display name \'%s\' ' - 'created.' % (network['networkCode'], network['displayName'])) - print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s' - % network['networkCode']) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/order_service/__init__.py b/examples/dfp/v201511/order_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/order_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/order_service/approve_orders.py b/examples/dfp/v201511/order_service/approve_orders.py deleted file mode 100755 index aee7a64b..00000000 --- a/examples/dfp/v201511/order_service/approve_orders.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example approves all eligible draft and pending orders. - -To determine which orders exist, run get_all_orders.py.""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201511') - - # Create query. - values = [{ - 'key': 'today', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S') - } - }] - query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')' - ' AND endDateTime >= :today AND isArchived = FALSE') - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - orders_approved = 0 - - # Get orders by statement. - while True: - response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for order in response['results']: - print ('Order with id \'%s\', name \'%s\', and status \'%s\' will be ' - 'approved.' % (order['id'], order['name'], order['status'])) - # Perform action. - result = order_service.performOrderAction( - {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - orders_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if orders_approved > 0: - print 'Number of orders approved: %s' % orders_approved - else: - print 'No orders were approved.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/order_service/create_orders.py b/examples/dfp/v201511/order_service/create_orders.py deleted file mode 100755 index 4d968a15..00000000 --- a/examples/dfp/v201511/order_service/create_orders.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new orders. - -To determine which orders exist, run get_all_orders.py.""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - -COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' -SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE' -TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE' - - -def main(client, company_id, salesperson_id, trafficker_id): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201511') - - # Create order objects. - orders = [] - for i in xrange(5): - order = { - 'name': 'Order #%s' % uuid.uuid4(), - 'advertiserId': company_id, - 'salespersonId': salesperson_id, - 'traffickerId': trafficker_id - } - orders.append(order) - - # Add orders. - orders = order_service.createOrders(orders) - - # Display results. - for order in orders: - print ('Order with id \'%s\' and name \'%s\' was created.' - % (order['id'], order['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) diff --git a/examples/dfp/v201511/order_service/get_orders_by_statement.py b/examples/dfp/v201511/order_service/get_orders_by_statement.py deleted file mode 100755 index 8f3daad7..00000000 --- a/examples/dfp/v201511/order_service/get_orders_by_statement.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets an order by an ID. - -To create orders, run create_orders.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the order to get. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201511') - - # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - - statement = dfp.FilterStatement(query, values) - - # Get orders by statement. - response = order_service.getOrdersByStatement(statement.ToStatement()) - orders = [] - if 'results' in response: - orders = response['results'] - - # Display results. - for order in orders: - print ('Order with id \'%s\' name \'%s\' was found.' - % (order['id'], order['name'])) - - print '\nNumber of results found: %s' % len(orders) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201511/premium_rate_service/__init__.py b/examples/dfp/v201511/premium_rate_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/premium_rate_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201511/premium_rate_service/get_all_premium_rates.py deleted file mode 100755 index c26788fc..00000000 --- a/examples/dfp/v201511/premium_rate_service/get_all_premium_rates.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all premium rates. - -To create premium rates, run create_premium_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') - - # Get premium rates by statement. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for premium_rate in response['results']: - print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' - ' rate card with ID \'%s\' was found.\n' % ( - premium_rate['id'], - dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/product_service/__init__.py b/examples/dfp/v201511/product_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/product_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/product_service/get_products_for_product_template.py b/examples/dfp/v201511/product_service/get_products_for_product_template.py deleted file mode 100755 index bdc173b3..00000000 --- a/examples/dfp/v201511/product_service/get_products_for_product_template.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 products created from a product template. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201511') - - # Create a filter statement to select only products created from a single - # a product template. - values = [{ - 'key': 'productTemplateId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE productTemplateId = :productTemplateId ORDER BY id ASC' - statement = dfp.FilterStatement(query, values) - - # Get products by statement. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' was found.' % ( - product['id'], product['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201511/product_template_service/__init__.py b/examples/dfp/v201511/product_template_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/product_template_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/product_template_service/activate_product_templates.py b/examples/dfp/v201511/product_template_service/activate_product_templates.py deleted file mode 100755 index 54a96bb9..00000000 --- a/examples/dfp/v201511/product_template_service/activate_product_templates.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example activates a product template. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the product template to activate. -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201511') - - # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - product_templates_activated = 0 - - # Get product_templates by statement. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response: - for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' will be ' - 'activated.' % (product_template['id'], - product_template['name'])) - - # Perform action. - result = product_template_service.performProductTemplateAction( - {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - product_templates_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if product_templates_activated > 0: - print ('Number of product templates ' - 'activated: %s' % product_templates_activated) - else: - print 'No product templates were activated.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201511/product_template_service/get_all_product_templates.py b/examples/dfp/v201511/product_template_service/get_all_product_templates.py deleted file mode 100755 index 338d2ccf..00000000 --- a/examples/dfp/v201511/product_template_service/get_all_product_templates.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all product templates. - -To create product templates, run create_product_template_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') - - # Get product templates by statement. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' was found.' % ( - product_template['id'], product_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201511/product_template_service/get_sponsorship_product_templates.py deleted file mode 100755 index 7a015232..00000000 --- a/examples/dfp/v201511/product_template_service/get_sponsorship_product_templates.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all sponsorship product templates. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201511') - - # Create a statement to select all sponsorship product templates. - values = [{ - 'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - } - }] - query = 'WHERE lineItemType = :lineItemType ORDER BY id ASC' - statement = dfp.FilterStatement(query, values) - - # Get product templates by statement. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' was found.' % ( - product_template['id'], product_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/product_template_service/update_product_templates.py b/examples/dfp/v201511/product_template_service/update_product_templates.py deleted file mode 100755 index e1d855b8..00000000 --- a/examples/dfp/v201511/product_template_service/update_product_templates.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates a product template's GeoTargeting. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201511') - - # Create a statement to select a single product template by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) - - # Get product templates by statement. - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - - if 'results' in response: - # Update each local product template object by appending a new geo-target. - for product_template in response['results']: - # Create geo-targeting for Canada to append. - location = { - 'id': '2124', - 'displayName': 'Canada' - } - - try: - targeting = product_template['builtInTargeting'] - - if 'geoTargeting' in targeting: - geo_targeting = targeting['geoTargeting'] - - if 'targetedLocations' in geo_targeting: - geo_targeting['targetedLocations'].append(location) - else: - geo_targeting['targetedLocations'] = [location] - else: - targeting['geoTargeting'] = { - 'targetedLocations': [location] - } - except KeyError: - product_template['builtInTargeting'] = { - 'geoTargeting': { - 'targetedLocations': [location] - } - } - - # Update products remotely. - product_templates = product_template_service.updateProductTemplates( - [product_template]) - - # Display results. - if product_templates: - for product_template in product_templates: - print ('Product template with id \'%s\' and name \'%s\' was ' - 'updated.' % (product_template['id'], product_template['name'])) - else: - print 'No product templates were updated.' - else: - print 'No product templates found to update.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201511/proposal_line_item_service/__init__.py b/examples/dfp/v201511/proposal_line_item_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/proposal_line_item_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201511/proposal_line_item_service/get_proposal_line_items_for_proposal.py deleted file mode 100755 index f725625a..00000000 --- a/examples/dfp/v201511/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all proposal line items that belong to a proposal. - -To create proposal line items, run create_proposal_line_items.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the proposal to get proposal line items from. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', - version='v201511') - - # Create statement object to only select proposal line items belonging to a - # given proposal. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE proposalId = :proposalId ORDER BY id ASC' - statement = dfp.FilterStatement(query, values) - - while True: - # Get proposal line items by statement. - response = proposal_line_item_service.getProposalLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for idx, proposal_line_item in enumerate(response['results'], - start=statement.offset): - print( - '%s) Proposal line item with id \'%s\', belonging to proposal id ' - '\'%s\', and named \'%s\' was found.' % ( - idx, proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201511/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201511/proposal_line_item_service/update_proposal_line_items.py deleted file mode 100755 index 5d268a03..00000000 --- a/examples/dfp/v201511/proposal_line_item_service/update_proposal_line_items.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates a proposal line item's notes. - -To determine which proposal line items exist, -run get_all_proposal_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the proposal line item to update. -PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' - - -def main(client, proposal_line_item_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201511') - - # Create statement to select a proposal line item. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - # Get proposal line items by statement. - response = proposal_line_item_service.getProposalLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Update each the proposal line item's notes field. - proposal_line_item = response['results'][0] - proposal_line_item['notes'] = 'Proposal line item ready for submission.' - - # Update proposal line items remotely. - proposal_line_items = proposal_line_item_service.updateProposalLineItems( - [proposal_line_item]) - - # Display results. - if proposal_line_items: - for proposal_line_item in proposal_line_items: - print ('Line item with id \'%s\', belonging to proposal id \'%s\' and,' - ' named \'%s\' was updated.' % ( - proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - else: - print 'No proposal line items were updated.' - else: - print 'No proposal line items found to update.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201511/proposal_service/__init__.py b/examples/dfp/v201511/proposal_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/proposal_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201511/proposal_service/get_proposals_by_statement.py deleted file mode 100755 index 8a5fb08c..00000000 --- a/examples/dfp/v201511/proposal_service/get_proposals_by_statement.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all proposals that are currently 'PENDING_APPROVAL.' - -To create proposals, run create_proposals.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201511') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - } - }] - query = 'WHERE status = :status ORDER BY id ASC' - - statement = dfp.FilterStatement(query, values) - - # Get proposals by statement. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for proposal in response['results']: - print ('Proposal with id \'%s\' name \'%s\' was found.' - % (proposal['id'], proposal['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/proposal_service/update_proposals.py b/examples/dfp/v201511/proposal_service/update_proposals.py deleted file mode 100755 index 3ca6466d..00000000 --- a/examples/dfp/v201511/proposal_service/update_proposals.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates the notes of a single proposal specified by ID. - -To determine which proposals exist, run get_all_proposals.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201511') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - statement = dfp.FilterStatement(query, values, 1) - - # Get proposals by statement. - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - - if 'results' in response: - # Update each local proposal object by changing its notes. - updated_proposals = [] - for proposal in response['results']: - proposal['notes'] = 'Proposal needs further review before approval.' - updated_proposals.append(proposal) - - # Update proposals remotely. - proposals = proposal_service.updateProposals(updated_proposals) - - # Display results. - if proposals: - for proposal in proposals: - print ('Proposal with id \'%s\', name \'%s\', and ' - 'notes \'%s\' was updated.' - % (proposal['id'], proposal['name'], proposal['notes'])) - else: - print 'No proposals were updated.' - else: - print 'No proposals found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201511/publisher_query_language_service/__init__.py b/examples/dfp/v201511/publisher_query_language_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/publisher_query_language_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201511/publisher_query_language_service/fetch_match_tables.py deleted file mode 100755 index d8431b90..00000000 --- a/examples/dfp/v201511/publisher_query_language_service/fetch_match_tables.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 fetches data from PQL tables and creates match table files.""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201511') - - line_items_file = tempfile.NamedTemporaryFile( - prefix='line_items_', suffix='.csv', mode='w', delete=False) - ad_units_file = tempfile.NamedTemporaryFile( - prefix='ad_units_', suffix='.csv', mode='w', delete=False) - - line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id ' - 'ASC') - ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC' - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - line_items_pql_query, line_items_file) - report_downloader.DownloadPqlResultToCsv( - ad_units_pql_query, ad_units_file) - - line_items_file.close() - ad_units_file.close() - - print ('Saved line items to... %s' % line_items_file.name) - print ('Saved ad units to... %s' % ad_units_file.name) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201511/publisher_query_language_service/get_geo_targets.py deleted file mode 100755 index 5403cab4..00000000 --- a/examples/dfp/v201511/publisher_query_language_service/get_geo_targets.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 geographic criteria from the Geo_Target table. - -The types available to filter on include 'City', 'Country', 'Region', 'State', -'Postal_Code', and 'DMA_Region' (i.e. Metro). - -A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201511/PublisherQueryLanguageService -""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201511') - - output_file = tempfile.NamedTemporaryFile( - prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) - - # Create bind value to select geo-targets of type 'City'. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'City' - } - }] - - pql_query = ('SELECT Name, Id FROM Geo_Target ' - 'WHERE targetable = true AND Type = :type') - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - pql_query, output_file, values) - output_file.close() - - print ('Saved geo targets to... %s' % output_file.name) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201511/publisher_query_language_service/get_line_items_named_like.py deleted file mode 100755 index 736d3f1d..00000000 --- a/examples/dfp/v201511/publisher_query_language_service/get_line_items_named_like.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 line items with names starting with 'line item'.""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201511') - - output_file = tempfile.NamedTemporaryFile( - prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) - - # Create bind value to select line items with names starting with 'line item'. - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'line item%' - } - }] - - pql_query = ('SELECT Name, Id, Status FROM Line_Item ' - 'WHERE Name LIKE :name') - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - pql_query, output_file, values) - output_file.close() - - print ('Saved line items to... %s' % output_file.name) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/rate_card_service/__init__.py b/examples/dfp/v201511/rate_card_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/rate_card_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201511/rate_card_service/get_rate_cards_priced_with_currency.py deleted file mode 100755 index 6aa39088..00000000 --- a/examples/dfp/v201511/rate_card_service/get_rate_cards_priced_with_currency.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 rate cards that have a currency in US dollars. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201511') - - # Create a statement to get all rate cards using USD as currency. - values = [{ - 'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'USD' - } - }] - query = 'WHERE currencyCode = :currencyCode' - - statement = dfp.FilterStatement(query, values) - - # Get rate cards by statement. - while True: - response = rate_card_service.getRateCardsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for rate_card in response['results']: - print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' - 'was found.' % (rate_card['id'], rate_card['name'], - rate_card['currencyCode'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/report_service/__init__.py b/examples/dfp/v201511/report_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/report_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/report_service/run_report_with_custom_fields.py b/examples/dfp/v201511/report_service/run_report_with_custom_fields.py deleted file mode 100755 index b97a7a40..00000000 --- a/examples/dfp/v201511/report_service/run_report_with_custom_fields.py +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example runs a report that with custom fields found in the line -items of an order. -""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp -from googleads import errors - -# Set the ID of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201511') - - # Filter for line items of a given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE orderId = :orderId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Collect all line item custom field IDs for an order. - custom_field_ids = set() - - # Get users by statement. - while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - if 'results' in response: - # Get custom field IDs from the line items of an order. - for line_item in response['results']: - if 'customFieldValues' in line_item: - for custom_field_value in line_item['customFieldValues']: - custom_field_ids.add(custom_field_value['customFieldId']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Create statement object to filter for an order. - filter_statement = {'query': query, 'values': values} - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': filter_statement, - 'columns': ['AD_SERVER_IMPRESSIONS'], - 'dateRangeType': 'LAST_MONTH', - 'customFieldIds': list(custom_field_ids) - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201511/report_service/run_sales_report.py b/examples/dfp/v201511/report_service/run_sales_report.py deleted file mode 100755 index b3ab5722..00000000 --- a/examples/dfp/v201511/report_service/run_sales_report.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example runs a report equal to the "Sales by salespersons report." -""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp -from googleads import errors - - -def main(client): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201511') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'], - 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE', - 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'LAST_MONTH' - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/suggested_ad_unit_service/__init__.py b/examples/dfp/v201511/suggested_ad_unit_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/suggested_ad_unit_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201511/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py deleted file mode 100755 index c7f27618..00000000 --- a/examples/dfp/v201511/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets suggested ad units that have more than 50 requests. - -This feature is only available to DFP premium solution networks. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201511') - - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '50' - } - }] - - query = 'WHERE numRequests > :numRequests' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get suggested ad units by statement. - while True: - response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for suggested_ad_unit in response['results']: - print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/team_service/__init__.py b/examples/dfp/v201511/team_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/team_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/team_service/create_teams.py b/examples/dfp/v201511/team_service/create_teams.py deleted file mode 100755 index ac17b297..00000000 --- a/examples/dfp/v201511/team_service/create_teams.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 creates new teams. - -To determine which teams exist, run get_all_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201511') - - # Create team objects. - teams = [] - for i in xrange(5): - team = { - 'name': 'Team %s' % uuid.uuid4(), - 'hasAllCompanies': 'false', - 'hasAllInventory': 'false', - 'teamAccessType': 'READ_WRITE' - } - teams.append(team) - - # Add Teams. - teams = team_service.createTeams(teams) - - # Display results. - for team in teams: - print ('Team with ID \'%s\' and name \'%s\' was created.' - % (team['id'], team['name'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/team_service/get_all_teams.py b/examples/dfp/v201511/team_service/get_all_teams.py deleted file mode 100755 index 25811c84..00000000 --- a/examples/dfp/v201511/team_service/get_all_teams.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 teams. - -To create teams, run create_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get users by statement. - while True: - response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for team in response['results']: - print ('Team with ID \'%s\' and name \'%s\' was found.' - % (team['id'], team['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/team_service/get_teams_by_statement.py b/examples/dfp/v201511/team_service/get_teams_by_statement.py deleted file mode 100755 index 558fc62d..00000000 --- a/examples/dfp/v201511/team_service/get_teams_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a single team by ID. - -To create teams, run create_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -TEAM_ID = 'INSERT_TEAM_ID_HERE' - - -def main(client, team_id): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201511') - - # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get teams by statement. - response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for team in response['results']: - print ('Team with id \'%s\' and name \'%s\' was found.' - % (team['id'], team['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID) diff --git a/examples/dfp/v201511/team_service/update_teams.py b/examples/dfp/v201511/team_service/update_teams.py deleted file mode 100755 index 91391277..00000000 --- a/examples/dfp/v201511/team_service/update_teams.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 updates teams by adding an ad unit to a team. - -To determine which teams exist, run get_all_teams.py. To determine which ad -units exist, run get_all_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' -TEAM_ID = 'INSERT_TEAM_ID_HERE' - - -def main(client, ad_unit_id, team_id): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201511') - - # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) - - # Get teams by statement. - response = team_service.getTeamsByStatement(statement.ToStatement()) - - if 'results' in response: - updated_teams = [] - # Update each local team object by adding the ad unit to it. - for team in response['results']: - ad_unit_ids = [] - if 'adUnitIds' in team: - ad_unit_ids = team['adUnitIds'] - # Don't add the ad unit if the team has all inventory already. - if not team['hasAllInventory']: - ad_unit_ids.append(ad_unit_id) - team['adUnitIds'] = ad_unit_ids - updated_teams.append(team) - - # Update teams on the server. - teams = team_service.updateTeams(updated_teams) - - # Display results. - for team in teams: - print ('Team with id \'%s\' and name \'%s\' was updated.' - % (team['id'], team['name'])) - else: - print 'No teams found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AD_UNIT_ID, TEAM_ID) diff --git a/examples/dfp/v201511/user_service/__init__.py b/examples/dfp/v201511/user_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/user_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/user_service/create_users.py b/examples/dfp/v201511/user_service/create_users.py deleted file mode 100755 index 3c46eeea..00000000 --- a/examples/dfp/v201511/user_service/create_users.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example creates new users. - -To determine which users exist, run get_all_users.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' -NEW_USER_NAME = 'INSERT_NAME_HERE' - - -def main(client, email, name): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201511') - - # Create user objects. - users = [ - { - 'email': email, - 'name': name, - 'preferredLocale': 'en_US' - } - ] - for user in users: - # Set the system defined ID of the trafficker role. - # To determine what other roles exist, run get_all_roles.py. - user['roleId'] = '-7' - - # Add users. - users = user_service.createUsers(users) - - # Display results. - for user in users: - print ('User with id \'%s\', email \'%s\', and role \'%s\' was created.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) diff --git a/examples/dfp/v201511/user_service/deactivate_users.py b/examples/dfp/v201511/user_service/deactivate_users.py deleted file mode 100755 index da72e67b..00000000 --- a/examples/dfp/v201511/user_service/deactivate_users.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example deactivates a user. - -Deactivated users can no longer make requests to the API. The user making the -request cannot deactivate itself. To determine which users exist, run -get_all_users.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201511') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get users by statement. - response = user_service.getUsersByStatement(statement.ToStatement()) - users = response['results'] if 'results' in response else [] - - for user in users: - print ('User with id \'%s\', email \'%s\', and status \'%s\' will be ' - 'deactivated.' - % (user['id'], user['email'], - {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) - print 'Number of users to be deactivated: %s' % len(users) - - # Perform action. - result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'}, - statement.ToStatement()) - - # Display results. - if result and int(result['numChanges']) > 0: - print 'Number of users deactivated: %s' % result['numChanges'] - else: - print 'No users were deactivated.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201511/user_service/get_all_roles.py b/examples/dfp/v201511/user_service/get_all_roles.py deleted file mode 100755 index 6b391d7c..00000000 --- a/examples/dfp/v201511/user_service/get_all_roles.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all roles. - -This sample can be used to determine which role id is needed when getting and -creating users.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201511') - - # Get all roles. - roles = user_service.getAllRoles() - - # Display results. - for role in roles: - print ('Role with id \'%s\' and name \'%s\' was found.' - % (role['id'], role['name'])) - - print '\nNumber of results found: %s' % len(roles) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/user_service/get_current_user.py b/examples/dfp/v201511/user_service/get_current_user.py deleted file mode 100755 index 475400de..00000000 --- a/examples/dfp/v201511/user_service/get_current_user.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets the current user.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201511') - - # Get current user. - user = user_service.getCurrentUser() - - # Display results. - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/user_service/get_users_by_statement.py b/examples/dfp/v201511/user_service/get_users_by_statement.py deleted file mode 100755 index 6c65a97b..00000000 --- a/examples/dfp/v201511/user_service/get_users_by_statement.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets a user by its id. - -To create users, run create_user.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_TO_FIND_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201511') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get users by statement. - response = user_service.getUsersByStatement(statement.ToStatement()) - users = response['results'] if 'results' in response else [] - - for user in users: - # Display results. - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201511/user_service/update_users.py b/examples/dfp/v201511/user_service/update_users.py deleted file mode 100755 index 293bbb2c..00000000 --- a/examples/dfp/v201511/user_service/update_users.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example updates a user by adding " Sr." to the end of their name. - -To determine which users exist, run get_all_users.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201511') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get users by statement. - response = user_service.getUsersByStatement(statement.ToStatement()) - - if 'results' in response: - users = response['results'] - for user in users: - user['name'] += ' Sr.' - - # Update users on server. - users = user_service.updateUsers(users) - for user in users: - print ('User with id \'%s\' and name \'%s\' was updated.' - % (user['id'], user['name'])) - else: - print 'No users found to update.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201511/user_team_association_service/__init__.py b/examples/dfp/v201511/user_team_association_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/user_team_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201511/user_team_association_service/get_all_user_team_associations.py deleted file mode 100755 index c0a92262..00000000 --- a/examples/dfp/v201511/user_team_association_service/get_all_user_team_associations.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 user team associations. - -To create user team associations, run create_user_team_assocations.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get user team associations by statement. - while True: - response = user_team_association_service.getUserTeamAssociationsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for user_team_association in response['results']: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was found.' % (user_team_association['userId'], - user_team_association['teamId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201511/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201511/user_team_association_service/get_user_team_associations_for_user.py deleted file mode 100755 index 860f2c01..00000000 --- a/examples/dfp/v201511/user_team_association_service/get_user_team_associations_for_user.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 user team associations for a single user. - -To determine which users exist, run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201511') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get user team associations by statement. - while True: - response = user_team_association_service.getUserTeamAssociationsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for user_team_association in response['results']: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was found.' % (user_team_association['userId'], - user_team_association['teamId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201511/workflow_request_service/__init__.py b/examples/dfp/v201511/workflow_request_service/__init__.py deleted file mode 100755 index a426ca48..00000000 --- a/examples/dfp/v201511/workflow_request_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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. diff --git a/examples/dfp/v201511/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201511/workflow_request_service/trigger_workflow_external_condition_requests.py deleted file mode 100755 index 6fab09fb..00000000 --- a/examples/dfp/v201511/workflow_request_service/trigger_workflow_external_condition_requests.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 triggers all workflow external condition requests for a proposal. - -Workflow external condition requests must be triggered or skipped for a workflow -to finish. To determine which proposals exist, run get_all_proposals.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201511') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - workflow_external_condition_requests_triggered = 0 - - # Get workflow external condition requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for workflow_request in response['results']: - print ('Workflow external condition request with id \'%s\' for %s ' - 'with id \'%s\' will be triggered.' % - (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_external_condition_requests_triggered += int( - result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if workflow_external_condition_requests_triggered > 0: - print ('\nNumber of workflow external condition requests triggered: %s' % - workflow_external_condition_requests_triggered) - else: - print '\nNo workflow external condition requests were triggered.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/activity_group_service/__init__.py b/examples/dfp/v201608/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201508/activity_group_service/__init__.py rename to examples/dfp/v201608/activity_group_service/__init__.py diff --git a/examples/dfp/v201508/activity_group_service/create_activity_groups.py b/examples/dfp/v201608/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201508/activity_group_service/create_activity_groups.py rename to examples/dfp/v201608/activity_group_service/create_activity_groups.py index 4ab78498..5550817f 100755 --- a/examples/dfp/v201508/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201608/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201508') + version='v201608') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201511/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201608/activity_group_service/get_active_activity_groups.py similarity index 59% rename from examples/dfp/v201511/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201608/activity_group_service/get_active_activity_groups.py index d6b02cae..3f8cd974 100755 --- a/examples/dfp/v201511/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201608/activity_group_service/get_active_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,40 +13,38 @@ # 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 code example gets all activity groups. - -To create activity groups, run create_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all active activity groups. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get activity groups by statement. + activity_group_service = client.GetService( + 'ActivityGroupService', version='v201608') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select activity groups. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of activity groups at a time, paging + # through until all activity groups have been retrieved. while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for activity_group in response['results']: - print ('Activity group with ID \'%s\' and name \'%s\' was found.' - % (activity_group['id'], activity_group['name'])) + # Print out some information for each activity group. + print('Activity group with ID "%d" and name "%s" was found.\n' % + (activity_group['id'], activity_group['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py new file mode 100755 index 00000000..14a582d3 --- /dev/null +++ b/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2016 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 activity groups. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + activity_group_service = client.GetService( + 'ActivityGroupService', version='v201608') + + # Create a statement to select activity groups. + statement = dfp.FilterStatement() + + # Retrieve a small amount of activity groups at a time, paging + # through until all activity groups have been retrieved. + while True: + response = activity_group_service.getActivityGroupsByStatement( + statement.ToStatement()) + if 'results' in response: + for activity_group in response['results']: + # Print out some information for each activity group. + print('Activity group with ID "%d" and name "%s" was found.\n' % + (activity_group['id'], activity_group['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201511/activity_group_service/update_activity_groups.py b/examples/dfp/v201608/activity_group_service/update_activity_groups.py similarity index 97% rename from examples/dfp/v201511/activity_group_service/update_activity_groups.py rename to examples/dfp/v201608/activity_group_service/update_activity_groups.py index 448eadd6..4d2fadd6 100755 --- a/examples/dfp/v201511/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201608/activity_group_service/update_activity_groups.py @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201511') + version='v201608') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201508/activity_service/__init__.py b/examples/dfp/v201608/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201508/activity_service/__init__.py rename to examples/dfp/v201608/activity_service/__init__.py diff --git a/examples/dfp/v201511/activity_service/create_activities.py b/examples/dfp/v201608/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201511/activity_service/create_activities.py rename to examples/dfp/v201608/activity_service/create_activities.py index eaa35ca6..1ab9262d 100755 --- a/examples/dfp/v201511/activity_service/create_activities.py +++ b/examples/dfp/v201608/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201511') + activity_service = client.GetService('ActivityService', version='v201608') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201511/activity_service/get_all_activities.py b/examples/dfp/v201608/activity_service/get_active_activities.py similarity index 58% rename from examples/dfp/v201511/activity_service/get_all_activities.py rename to examples/dfp/v201608/activity_service/get_active_activities.py index 02f8c2d0..3ea352d4 100755 --- a/examples/dfp/v201511/activity_service/get_all_activities.py +++ b/examples/dfp/v201608/activity_service/get_active_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,44 @@ # 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 code example gets all activities. - -To create activities, run create_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all active activities. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201511') - - # Create statement object to select only all activities. - statement = dfp.FilterStatement() - - # Get activities by statement. + activity_service = client.GetService('ActivityService', version='v201608') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select activities. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of activities at a time, paging + # through until all activities have been retrieved. while True: - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) + response = activity_service.getActivitiesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for activity in response['results']: - print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (activity['id'], activity['name'], activity['type'])) + # Print out some information for each activity. + print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % + (activity['id'], activity['name'], activity['type'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201608/activity_service/get_all_activities.py b/examples/dfp/v201608/activity_service/get_all_activities.py new file mode 100755 index 00000000..5147c4d8 --- /dev/null +++ b/examples/dfp/v201608/activity_service/get_all_activities.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# +# Copyright 2016 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 activities. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + activity_service = client.GetService('ActivityService', version='v201608') + + # Create a statement to select activities. + statement = dfp.FilterStatement() + + # Retrieve a small amount of activities at a time, paging + # through until all activities have been retrieved. + while True: + response = activity_service.getActivitiesByStatement(statement.ToStatement( + )) + if 'results' in response: + for activity in response['results']: + # Print out some information for each activity. + print('Activity with ID "%d" and name "%s" was found.\n' % + (activity['id'], activity['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/activity_service/update_activities.py b/examples/dfp/v201608/activity_service/update_activities.py similarity index 99% rename from examples/dfp/v201508/activity_service/update_activities.py rename to examples/dfp/v201608/activity_service/update_activities.py index c2021187..8640050c 100755 --- a/examples/dfp/v201508/activity_service/update_activities.py +++ b/examples/dfp/v201608/activity_service/update_activities.py @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201508') + activity_service = client.GetService('ActivityService', version='v201608') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201508/audience_segment_service/__init__.py b/examples/dfp/v201608/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201508/audience_segment_service/__init__.py rename to examples/dfp/v201608/audience_segment_service/__init__.py diff --git a/examples/dfp/v201511/audience_segment_service/create_audience_segments.py b/examples/dfp/v201608/audience_segment_service/create_audience_segments.py similarity index 95% rename from examples/dfp/v201511/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201608/audience_segment_service/create_audience_segments.py index e73a26eb..13ec4be7 100755 --- a/examples/dfp/v201511/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/create_audience_segments.py @@ -32,8 +32,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201511') - network_service = client.GetService('NetworkService', version='v201511') + 'AudienceSegmentService', version='v201608') + network_service = client.GetService('NetworkService', version='v201608') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( @@ -95,4 +95,4 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) + main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201511/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py similarity index 65% rename from examples/dfp/v201511/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py index 443d135a..c77a17b1 100755 --- a/examples/dfp/v201511/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,38 +13,32 @@ # 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 code example gets all audience segments. - -To create audience segments, run create_audience_segments.py. +"""This example gets all audience segments. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201511') + 'AudienceSegmentService', version='v201608') - # Create statement object to select all audience segments. + # Create a statement to select audience segments. statement = dfp.FilterStatement() - # Get audience segments by statement. + # Retrieve a small amount of audience segments at a time, paging + # through until all audience segments have been retrieved. while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for segment in response['results']: - print ('Audience segment with id \'%s\' and name ' - '\'%s\' of size %s was found.' % - (segment['id'], segment['name'], segment['size'])) + for audience_segment in response['results']: + # Print out some information for each audience segment. + print('Audience segment with ID "%d", name "%s", and size "%d" was ' + 'found.\n' % (audience_segment['id'], audience_segment['name'], + audience_segment['size'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py similarity index 59% rename from examples/dfp/v201511/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py index f68e0dc8..237bc5c2 100755 --- a/examples/dfp/v201511/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,39 @@ # 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 code example gets all first party audience segments. - -To create first party audience segments, run create_audience_segments.py. +"""This example gets all first party audience segments. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201511') - - # Create statement object to only select first party audience segments. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }] - query = 'WHERE Type = :type' + 'AudienceSegmentService', version='v201608') + query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'FIRST_PARTY' + }}, + ] + # Create a statement to select audience segments. statement = dfp.FilterStatement(query, values) - # Get audience segments by statement. + # Retrieve a small amount of audience segments at a time, paging + # through until all audience segments have been retrieved. while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: - segments = response['results'] - for segment in segments: - print ('Audience segment with id \'%s\' and name \'%s\' of size ' - '%s was found. ' % - (segment['id'], segment['name'], segment['size'])) + for audience_segment in response['results']: + # Print out some information for each audience segment. + print('Audience segment with ID "%d", name "%s", and size "%d" was ' + 'found.\n' % (audience_segment['id'], audience_segment['name'], + audience_segment['size'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py similarity index 97% rename from examples/dfp/v201511/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py index 254a6d0c..e753b4d1 100755 --- a/examples/dfp/v201511/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py @@ -33,7 +33,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201511') + 'AudienceSegmentService', version='v201608') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201511/audience_segment_service/update_audience_segments.py b/examples/dfp/v201608/audience_segment_service/update_audience_segments.py similarity index 98% rename from examples/dfp/v201511/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201608/audience_segment_service/update_audience_segments.py index 7aec80d3..52a59e4c 100755 --- a/examples/dfp/v201511/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/update_audience_segments.py @@ -32,7 +32,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201511') + 'AudienceSegmentService', version='v201608') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201508/base_rate_service/__init__.py b/examples/dfp/v201608/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201508/base_rate_service/__init__.py rename to examples/dfp/v201608/base_rate_service/__init__.py diff --git a/examples/dfp/v201508/base_rate_service/create_product_base_rates.py b/examples/dfp/v201608/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201508/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201608/base_rate_service/create_product_base_rates.py index 013056b3..139998a8 100755 --- a/examples/dfp/v201508/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201608/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201508') + 'BaseRateService', version='v201608') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201508/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201508/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py index c2687f58..2c0f5693 100755 --- a/examples/dfp/v201508/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201508') + 'BaseRateService', version='v201608') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201508/base_rate_service/get_all_base_rates.py b/examples/dfp/v201608/base_rate_service/get_all_base_rates.py similarity index 62% rename from examples/dfp/v201508/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201608/base_rate_service/get_all_base_rates.py index f9b0d176..e74ab065 100755 --- a/examples/dfp/v201508/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201608/base_rate_service/get_all_base_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,39 +13,31 @@ # 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 base rates. - -To create product base rates, run create_product_base_rates.py -To create product template base rates, run -create_product_template_base_rates.py. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201508') + base_rate_service = client.GetService('BaseRateService', version='v201608') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select base rates. + statement = dfp.FilterStatement() - # Get base rates by statement. + # Retrieve a small amount of base rates at a time, paging + # through until all base rates have been retrieved. while True: - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) + response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for base_rate in response['results']: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was found.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) + # Print out some information for each base rate. + print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' + 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py similarity index 57% rename from examples/dfp/v201511/base_rate_service/get_base_rates_for_a_rate_card.py rename to examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py index 90527f3f..74d72e63 100755 --- a/examples/dfp/v201511/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,16 +13,9 @@ # 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 base rates. - -To create product base rates, run create_product_base_rates.py -To create product template base rates, run -create_product_template_base_rates.py. - +"""This example gets all base rates belonging to a rate card. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -31,31 +24,29 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201511') - - # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'rateCardId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': rate_card_id - } - }] - query = 'where rateCardId = :rateCardId ORDER BY id ASC' + base_rate_service = client.GetService('BaseRateService', version='v201608') + query = 'WHERE rateCardId = :rateCardId' + values = [ + {'key': 'rateCardId', + 'value': { + 'xsi_type': 'TextValue', + 'value': rate_card_id + }}, + ] + # Create a statement to select base rates. statement = dfp.FilterStatement(query, values) - # Get base rates by statement. + # Retrieve a small amount of base rates at a time, paging + # through until all base rates have been retrieved. while True: - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) + response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for base_rate in response['results']: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was found.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) + # Print out some information for each base rate. + print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' + 'found.\n' % + (base_rate['id'], base_rate['type'], base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/base_rate_service/update_base_rates.py b/examples/dfp/v201608/base_rate_service/update_base_rates.py similarity index 99% rename from examples/dfp/v201508/base_rate_service/update_base_rates.py rename to examples/dfp/v201608/base_rate_service/update_base_rates.py index 7ae1882f..6c7573fe 100755 --- a/examples/dfp/v201508/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201608/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201508') + base_rate_service = client.GetService('BaseRateService', version='v201608') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201508/company_service/__init__.py b/examples/dfp/v201608/company_service/__init__.py similarity index 100% rename from examples/dfp/v201508/company_service/__init__.py rename to examples/dfp/v201608/company_service/__init__.py diff --git a/examples/dfp/v201511/company_service/create_companies.py b/examples/dfp/v201608/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201511/company_service/create_companies.py rename to examples/dfp/v201608/company_service/create_companies.py index 74658606..5c1974a7 100755 --- a/examples/dfp/v201511/company_service/create_companies.py +++ b/examples/dfp/v201608/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201511') + company_service = client.GetService('CompanyService', version='v201608') # Create company objects. companies = [ diff --git a/examples/dfp/v201511/company_service/get_all_companies.py b/examples/dfp/v201608/company_service/get_advertisers.py similarity index 59% rename from examples/dfp/v201511/company_service/get_all_companies.py rename to examples/dfp/v201608/company_service/get_advertisers.py index bf712894..eb4e9a2c 100755 --- a/examples/dfp/v201511/company_service/get_all_companies.py +++ b/examples/dfp/v201608/company_service/get_advertisers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,43 @@ # 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 code example gets all companies. - -To create companies, run create_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all companies that are advertisers. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201511') - - # Create statement object to select all companies. - statement = dfp.FilterStatement() - - # Get companies by statement. + company_service = client.GetService('CompanyService', version='v201608') + query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ADVERTISER' + }}, + ] + # Create a statement to select companies. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of companies at a time, paging + # through until all companies have been retrieved. while True: - response = company_service.getCompaniesByStatement( - statement.ToStatement()) + response = company_service.getCompaniesByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for company in response['results']: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.' - % (company['id'], company['name'], company['type'])) + # Print out some information for each company. + print('Company with ID "%d", name "%s", and type "%s" was found.\n' % + (company['id'], company['name'], company['type'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201608/company_service/get_all_companies.py b/examples/dfp/v201608/company_service/get_all_companies.py new file mode 100755 index 00000000..f1a5a6a9 --- /dev/null +++ b/examples/dfp/v201608/company_service/get_all_companies.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 companies. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + company_service = client.GetService('CompanyService', version='v201608') + + # Create a statement to select companies. + statement = dfp.FilterStatement() + + # Retrieve a small amount of companies at a time, paging + # through until all companies have been retrieved. + while True: + response = company_service.getCompaniesByStatement(statement.ToStatement()) + if 'results' in response: + for company in response['results']: + # Print out some information for each company. + print('Company with ID "%d", name "%s", and type "%s" was found.\n' % + (company['id'], company['name'], company['type'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201511/company_service/update_companies.py b/examples/dfp/v201608/company_service/update_companies.py similarity index 99% rename from examples/dfp/v201511/company_service/update_companies.py rename to examples/dfp/v201608/company_service/update_companies.py index eadd677d..fd8cdc5c 100755 --- a/examples/dfp/v201511/company_service/update_companies.py +++ b/examples/dfp/v201608/company_service/update_companies.py @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201511') + company_service = client.GetService('CompanyService', version='v201608') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201508/contact_service/__init__.py b/examples/dfp/v201608/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201508/contact_service/__init__.py rename to examples/dfp/v201608/contact_service/__init__.py diff --git a/examples/dfp/v201508/contact_service/create_contacts.py b/examples/dfp/v201608/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201508/contact_service/create_contacts.py rename to examples/dfp/v201608/contact_service/create_contacts.py index 4ddd1abf..381a6787 100755 --- a/examples/dfp/v201508/contact_service/create_contacts.py +++ b/examples/dfp/v201608/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201508') + contact_service = client.GetService('ContactService', version='v201608') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201508/order_service/get_all_orders.py b/examples/dfp/v201608/contact_service/get_all_contacts.py similarity index 63% rename from examples/dfp/v201508/order_service/get_all_orders.py rename to examples/dfp/v201608/contact_service/get_all_contacts.py index e9bca038..fc327c70 100755 --- a/examples/dfp/v201508/order_service/get_all_orders.py +++ b/examples/dfp/v201608/contact_service/get_all_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,32 +13,29 @@ # 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 code example gets all orders. - -To create orders, run create_orders.py. +"""This example gets all contacts. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201508') + contact_service = client.GetService('ContactService', version='v201608') - # Create a filter statement. + # Create a statement to select contacts. statement = dfp.FilterStatement() - # Get orders by statement. + # Retrieve a small amount of contacts at a time, paging + # through until all contacts have been retrieved. while True: - response = order_service.getOrdersByStatement(statement.ToStatement()) + response = contact_service.getContactsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. - for order in response['results']: - print ('Order with id \'%s\', name \'%s\', and advertiser id \'%s\' was' - ' found.' % (order['id'], order['name'], order['advertiserId'])) + for contact in response['results']: + # Print out some information for each contact. + print('Contact with ID "%d" and name "%s" was found.\n' % + (contact['id'], contact['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/contact_service/get_all_contacts.py b/examples/dfp/v201608/contact_service/get_uninvited_contacts.py similarity index 60% rename from examples/dfp/v201511/contact_service/get_all_contacts.py rename to examples/dfp/v201608/contact_service/get_uninvited_contacts.py index 5d96fa18..c635b8b6 100755 --- a/examples/dfp/v201511/contact_service/get_all_contacts.py +++ b/examples/dfp/v201608/contact_service/get_uninvited_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,43 @@ # 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 code example gets all contacts. - -To create contacts, run create_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all contacts that aren't invited yet. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201511') - - # Create statement object to get all contacts. - statement = dfp.FilterStatement() - - # Get contacts by statement. + contact_service = client.GetService('ContactService', version='v201608') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'UNINVITED' + }}, + ] + # Create a statement to select contacts. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of contacts at a time, paging + # through until all contacts have been retrieved. while True: - response = contact_service.getContactsByStatement( - statement.ToStatement()) + response = contact_service.getContactsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for contact in response['results']: - print ('Contact with ID \'%s\' and name \'%s\' was found.' - % (contact['id'], contact['name'])) + # Print out some information for each contact. + print('Contact with ID "%d" and name "%s" was found.\n' % + (contact['id'], contact['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/contact_service/update_contacts.py b/examples/dfp/v201608/contact_service/update_contacts.py similarity index 99% rename from examples/dfp/v201511/contact_service/update_contacts.py rename to examples/dfp/v201608/contact_service/update_contacts.py index 1656f6fa..8a8921b8 100755 --- a/examples/dfp/v201511/contact_service/update_contacts.py +++ b/examples/dfp/v201608/contact_service/update_contacts.py @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201511') + contact_service = client.GetService('ContactService', version='v201608') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201508/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201508/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201608/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201511/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201511/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 52f2db84..ee3a9c4e 100755 --- a/examples/dfp/v201511/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201511') + 'ContentMetadataKeyHierarchyService', version='v201608') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201511/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201511/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 400f5e4e..3044c2aa 100755 --- a/examples/dfp/v201511/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201511') + 'ContentMetadataKeyHierarchyService', version='v201608') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201508/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 54% rename from examples/dfp/v201508/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index c610a3c5..04259e95 100755 --- a/examples/dfp/v201508/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,40 +13,33 @@ # 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 code example gets all activity groups. - -To create activity groups, run create_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all content metadata key hierarchies. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201508') + content_metadata_key_hierarchy_service = client.GetService( + 'ContentMetadataKeyHierarchyService', version='v201608') - # Create a filter statement. + # Create a statement to select content metadata key hierarchies. statement = dfp.FilterStatement() - # Get activity groups by statement. + # Retrieve a small amount of content metadata key hierarchies at a time, + # paging through until all content metadata key hierarchies have been + # retrieved. while True: - response = activity_group_service.getActivityGroupsByStatement( + response = content_metadata_key_hierarchy_service.getContentMetadataKeyHierarchiesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for activity_group in response['results']: - print ('Activity group with ID \'%s\' and name \'%s\' was found.' - % (activity_group['id'], activity_group['name'])) + for content_metadata_key_hierarchy in response['results']: + # Print out some information for each content metadata key hierarchy. + print('Content metadata key hierarchy with ID "%d" and name "%s" was ' + 'found.\n' % (content_metadata_key_hierarchy['id'], + content_metadata_key_hierarchy['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 98% rename from examples/dfp/v201508/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index ff23e47c..3b692a82 100755 --- a/examples/dfp/v201508/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201508') + 'ContentMetadataKeyHierarchyService', version='v201608') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201508/content_service/__init__.py b/examples/dfp/v201608/content_service/__init__.py similarity index 100% rename from examples/dfp/v201508/content_service/__init__.py rename to examples/dfp/v201608/content_service/__init__.py diff --git a/examples/dfp/v201511/placement_service/get_all_placements.py b/examples/dfp/v201608/content_service/get_all_content.py similarity index 63% rename from examples/dfp/v201511/placement_service/get_all_placements.py rename to examples/dfp/v201608/content_service/get_all_content.py index 8a9273c1..d7a5be55 100755 --- a/examples/dfp/v201511/placement_service/get_all_placements.py +++ b/examples/dfp/v201608/content_service/get_all_content.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,39 +13,36 @@ # 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 code example gets all placements. - -To create placements, run create_placement.py. +"""This example gets all content. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201511') + content_service = client.GetService('ContentService', version='v201608') - # Create statement to fetch all placements. + # Create a statement to select content. statement = dfp.FilterStatement() - # Get placements by statement. + # Retrieve a small amount of content at a time, paging + # through until all content have been retrieved. while True: - response = placement_service.getPlacementsByStatement( - statement.ToStatement()) + response = content_service.getContentByStatement(statement.ToStatement()) if 'results' in response: - # Display results. - for placement in response['results']: - print ('Placement with id \'%s\' and name \'%s\' was found.' - % (placement['id'], placement['name'])) + for content in response['results']: + # Print out some information for each content. + print('Content with ID "%d" and name "%s" was found.\n' % + (content['id'], content['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/creative_service/__init__.py b/examples/dfp/v201608/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201508/creative_service/__init__.py rename to examples/dfp/v201608/creative_service/__init__.py diff --git a/examples/dfp/v201508/creative_service/create_creative_from_template.py b/examples/dfp/v201608/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201508/creative_service/create_creative_from_template.py rename to examples/dfp/v201608/creative_service/create_creative_from_template.py index 3107d975..dd76310b 100755 --- a/examples/dfp/v201508/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201608/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201508') + creative_service = client.GetService('CreativeService', version='v201608') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201511/creative_service/create_creatives.py b/examples/dfp/v201608/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201511/creative_service/create_creatives.py rename to examples/dfp/v201608/creative_service/create_creatives.py index e14284d8..0e84a7e2 100755 --- a/examples/dfp/v201511/creative_service/create_creatives.py +++ b/examples/dfp/v201608/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201511') + creative_service = client.GetService('CreativeService', version='v201608') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201511/creative_service/create_custom_creative.py b/examples/dfp/v201608/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201511/creative_service/create_custom_creative.py rename to examples/dfp/v201608/creative_service/create_custom_creative.py index f8591c15..be617aa8 100755 --- a/examples/dfp/v201511/creative_service/create_custom_creative.py +++ b/examples/dfp/v201608/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201511') + creative_service = client.GetService('CreativeService', version='v201608') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201511/creative_service/create_native_creative.py b/examples/dfp/v201608/creative_service/create_native_creative.py similarity index 99% rename from examples/dfp/v201511/creative_service/create_native_creative.py rename to examples/dfp/v201608/creative_service/create_native_creative.py index 53128ac2..3536bae8 100755 --- a/examples/dfp/v201511/creative_service/create_native_creative.py +++ b/examples/dfp/v201608/creative_service/create_native_creative.py @@ -46,7 +46,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201511') + creative_service = client.GetService('CreativeService', version='v201608') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/dfp/v201608/creative_service/get_all_creatives.py b/examples/dfp/v201608/creative_service/get_all_creatives.py new file mode 100755 index 00000000..b0eb7c25 --- /dev/null +++ b/examples/dfp/v201608/creative_service/get_all_creatives.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creatives. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201608') + + # Create a statement to select creatives. + statement = dfp.FilterStatement() + + # Retrieve a small amount of creatives at a time, paging + # through until all creatives have been retrieved. + while True: + response = creative_service.getCreativesByStatement(statement.ToStatement()) + if 'results' in response: + for creative in response['results']: + # Print out some information for each creative. + print('Creative with ID "%d" and name "%s" was found.\n' % + (creative['id'], creative['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/creative_service/get_all_creatives.py b/examples/dfp/v201608/creative_service/get_image_creatives.py similarity index 57% rename from examples/dfp/v201508/creative_service/get_all_creatives.py rename to examples/dfp/v201608/creative_service/get_image_creatives.py index d0a3d68c..90d5be9f 100755 --- a/examples/dfp/v201508/creative_service/get_all_creatives.py +++ b/examples/dfp/v201608/creative_service/get_image_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,46 +13,43 @@ # 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 code example gets all creatives. - -To create creatives, run create_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all image creatives. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201508') - - # Create statement object to select all creatives. - statement = dfp.FilterStatement() - - # Get creatives by statement. + creative_service = client.GetService('CreativeService', version='v201608') + query = 'WHERE creativeType = :creativeType' + values = [ + {'key': 'creativeType', + 'value': { + 'xsi_type': 'TextValue', + 'value': '_image_creative' + }}, + ] + # Create a statement to select creatives. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of creatives at a time, paging + # through until all creatives have been retrieved. while True: - response = creative_service.getCreativesByStatement( - statement.ToStatement()) + response = creative_service.getCreativesByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for creative in response['results']: - print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (creative['id'], creative['name'], - dfp.DfpClassType(creative))) + # Print out some information for each creative. + print('Creative with ID "%d" and name "%s" was found.\n' % + (creative['id'], creative['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/creative_service/update_creatives.py b/examples/dfp/v201608/creative_service/update_creatives.py similarity index 99% rename from examples/dfp/v201508/creative_service/update_creatives.py rename to examples/dfp/v201608/creative_service/update_creatives.py index 9a10daf2..60a6fb7a 100755 --- a/examples/dfp/v201508/creative_service/update_creatives.py +++ b/examples/dfp/v201608/creative_service/update_creatives.py @@ -34,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201508') + creative_service = client.GetService('CreativeService', version='v201608') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201508/creative_set_service/__init__.py b/examples/dfp/v201608/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201508/creative_set_service/__init__.py rename to examples/dfp/v201608/creative_set_service/__init__.py diff --git a/examples/dfp/v201508/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201508/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py index d2b997f3..62b68f37 100755 --- a/examples/dfp/v201508/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py @@ -38,7 +38,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201508') + 'LineItemCreativeAssociationService', version='v201608') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201508/creative_set_service/create_creative_set.py b/examples/dfp/v201608/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201508/creative_set_service/create_creative_set.py rename to examples/dfp/v201608/creative_set_service/create_creative_set.py index 16789024..06fef367 100755 --- a/examples/dfp/v201508/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201608/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201508') + version='v201608') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201511/line_item_service/get_all_line_items.py b/examples/dfp/v201608/creative_set_service/get_all_creative_sets.py similarity index 62% rename from examples/dfp/v201511/line_item_service/get_all_line_items.py rename to examples/dfp/v201608/creative_set_service/get_all_creative_sets.py index 4d446ab6..b92491d6 100755 --- a/examples/dfp/v201511/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201608/creative_set_service/get_all_creative_sets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,11 +13,8 @@ # 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 code example gets all line items. - -To create line items, run create_line_items.py.""" - +"""This example gets all creative sets. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -25,27 +22,29 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') + creative_set_service = client.GetService( + 'CreativeSetService', version='v201608') - # Create a filter statement. + # Create a statement to select creative sets. statement = dfp.FilterStatement() - # Get line items by statement. + # Retrieve a small amount of creative sets at a time, paging + # through until all creative sets have been retrieved. while True: - response = line_item_service.getLineItemsByStatement( + response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % - (line_item['id'], line_item['orderId'], line_item['name'])) + for creative_set in response['results']: + # Print out some information for each creative set. + print('Creative set with ID "%d" and name "%s" was found.\n' % + (creative_set['id'], creative_set['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py similarity index 54% rename from examples/dfp/v201508/creative_set_service/get_creative_sets_by_statement.py rename to examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py index 0d89cba7..34986922 100755 --- a/examples/dfp/v201508/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 code example gets all creative sets for a master creative. - -To create creative sets, run create_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all creative sets for a master creative. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -34,38 +24,36 @@ def main(client, master_creative_id): # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201508') - - # Create statement object to only select creative sets that have the given - # master creative. - values = [{ - 'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': master_creative_id - } - }] + creative_set_service = client.GetService( + 'CreativeSetService', version='v201608') query = 'WHERE masterCreativeId = :masterCreativeId' + values = [ + {'key': 'masterCreativeId', + 'value': { + 'xsi_type': 'TextValue', + 'value': master_creative_id + }}, + ] + # Create a statement to select creative sets. statement = dfp.FilterStatement(query, values) - # Get creative sets by statement. + # Retrieve a small amount of creative sets at a time, paging + # through until all creative sets have been retrieved. while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for creative_set in response['results']: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' - 'companion creative IDs {%s} was found.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) + # Print out some information for each creative set. + print('Creative set with ID "%d" and name "%s" was found.\n' % + (creative_set['id'], creative_set['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/creative_set_service/update_creative_set.py b/examples/dfp/v201608/creative_set_service/update_creative_set.py similarity index 97% rename from examples/dfp/v201508/creative_set_service/update_creative_set.py rename to examples/dfp/v201608/creative_set_service/update_creative_set.py index 3975a354..4f46f517 100755 --- a/examples/dfp/v201508/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201608/creative_set_service/update_creative_set.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201508') + version='v201608') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201508/creative_template_service/__init__.py b/examples/dfp/v201608/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201508/creative_template_service/__init__.py rename to examples/dfp/v201608/creative_template_service/__init__.py diff --git a/examples/dfp/v201508/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201608/creative_template_service/get_all_creative_templates.py similarity index 61% rename from examples/dfp/v201508/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201608/creative_template_service/get_all_creative_templates.py index 7d7a40fb..416883a6 100755 --- a/examples/dfp/v201508/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201608/creative_template_service/get_all_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,17 +13,9 @@ # 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 code example gets all creative templates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all creative templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -31,28 +23,28 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201508') + 'CreativeTemplateService', version='v201608') - # Create a filter statement. + # Create a statement to select creative templates. statement = dfp.FilterStatement() - # Get creative templates by statement. + # Retrieve a small amount of creative templates at a time, paging + # through until all creative templates have been retrieved. while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for template in response['results']: - print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' ' - 'was found.' % (template['id'], - template['name'], - template['type'])) + for creative_template in response['results']: + # Print out some information for each creative template. + print('Creative template with ID "%d" and name "%s" was found.\n' % + (creative_template['id'], creative_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py similarity index 58% rename from examples/dfp/v201511/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py index 80a769af..38d60806 100755 --- a/examples/dfp/v201511/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,17 +13,9 @@ # 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 code example gets all creative templates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all system defined creative templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -31,28 +23,35 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get creative templates by statement. + 'CreativeTemplateService', version='v201608') + query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'SYSTEM_DEFINED' + }}, + ] + # Create a statement to select creative templates. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of creative templates at a time, paging + # through until all creative templates have been retrieved. while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for template in response['results']: - print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' ' - 'was found.' % (template['id'], - template['name'], - template['type'])) + for creative_template in response['results']: + # Print out some information for each creative template. + print('Creative template with ID "%d" and name "%s" was found.\n' % + (creative_template['id'], creative_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/dfp/v201508/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py index e68bc21a..4ffe322b 100755 --- a/examples/dfp/v201508/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201508') + version='v201608') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201511/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 97% rename from examples/dfp/v201511/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py index 265b4fa1..81032bd7 100755 --- a/examples/dfp/v201511/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201511') + version='v201608') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201508/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py similarity index 58% rename from examples/dfp/v201508/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py index aabc2352..e1c7e997 100755 --- a/examples/dfp/v201508/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,46 +13,45 @@ # 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 code example gets all creative wrappers. - -To create creative wrappers, run create_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all active creative wrappers. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201508') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get creative wrappers by statement. + creative_wrapper_service = client.GetService( + 'CreativeWrapperService', version='v201608') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select creative wrappers. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of creative wrappers at a time, paging + # through until all creative wrappers have been retrieved. while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'found.' % (creative_wrapper['id'], creative_wrapper['labelId'])) + # Print out some information for each creative wrapper. + print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % + (creative_wrapper['id'], creative_wrapper['labelId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py similarity index 60% rename from examples/dfp/v201511/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py index 8a1709a7..ea6daf38 100755 --- a/examples/dfp/v201511/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,41 +13,38 @@ # 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 code example gets all suggested ad units. - -To approve suggested ad units, run approve_suggested_ad_units.py. This feature -is only available to DFP premium solution networks. +"""This example gets all creative wrappers. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201511') + creative_wrapper_service = client.GetService( + 'CreativeWrapperService', version='v201608') - # Create a filter statement. + # Create a statement to select creative wrappers. statement = dfp.FilterStatement() - # Get suggested ad units by statement. + # Retrieve a small amount of creative wrappers at a time, paging + # through until all creative wrappers have been retrieved. while True: - response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( + response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for suggested_ad_unit in response['results']: - print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + for creative_wrapper in response['results']: + # Print out some information for each creative wrapper. + print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % + (creative_wrapper['id'], creative_wrapper['labelId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py similarity index 97% rename from examples/dfp/v201508/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py index ad59b9fd..e1e5cdfe 100755 --- a/examples/dfp/v201508/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201508') + version='v201608') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201508/custom_field_service/__init__.py b/examples/dfp/v201608/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201508/custom_field_service/__init__.py rename to examples/dfp/v201608/custom_field_service/__init__.py diff --git a/examples/dfp/v201511/custom_field_service/create_custom_field_options.py b/examples/dfp/v201608/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201511/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201608/custom_field_service/create_custom_field_options.py index d40575cb..bed95fe0 100755 --- a/examples/dfp/v201511/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201608/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201511') + 'CustomFieldService', version='v201608') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201511/custom_field_service/create_custom_fields.py b/examples/dfp/v201608/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201511/custom_field_service/create_custom_fields.py rename to examples/dfp/v201608/custom_field_service/create_custom_fields.py index 6d28d55f..8cec412d 100755 --- a/examples/dfp/v201511/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201511') + 'CustomFieldService', version='v201608') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201508/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 98% rename from examples/dfp/v201508/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py index 8b95be8a..90cebf21 100755 --- a/examples/dfp/v201508/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201508') + 'CustomFieldService', version='v201608') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201508/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201608/custom_field_service/get_all_custom_fields.py similarity index 67% rename from examples/dfp/v201508/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201608/custom_field_service/get_all_custom_fields.py index 74fc1e6f..e64fa4e7 100755 --- a/examples/dfp/v201508/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/get_all_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 fields. - -To create custom fields, run create_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,26 +23,28 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201508') + 'CustomFieldService', version='v201608') - # Create a filter statement. + # Create a statement to select custom fields. statement = dfp.FilterStatement() - # Get custom fields by statement. + # Retrieve a small amount of custom fields at a time, paging + # through until all custom fields have been retrieved. while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' was found.' - % (custom_field['id'], custom_field['name'])) + # Print out some information for each custom field. + print('Custom field with ID "%d" and name "%s" was found.\n' % + (custom_field['id'], custom_field['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py similarity index 61% rename from examples/dfp/v201511/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py index 7c17aa5d..af37b100 100755 --- a/examples/dfp/v201511/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 fields. - -To create custom fields, run create_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all custom fields that can be applied to line items. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,26 +23,35 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get custom fields by statement. + 'CustomFieldService', version='v201608') + query = 'WHERE entityType = :entityType' + values = [ + {'key': 'entityType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'LINE_ITEM' + }}, + ] + # Create a statement to select custom fields. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of custom fields at a time, paging + # through until all custom fields have been retrieved. while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' was found.' - % (custom_field['id'], custom_field['name'])) + # Print out some information for each custom field. + print('Custom field with ID "%d" and name "%s" was found.\n' % + (custom_field['id'], custom_field['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201511/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py index 7cf63b0c..fe5d3103 100755 --- a/examples/dfp/v201511/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201511') + 'CustomFieldService', version='v201608') - line_item_service = client.GetService('LineItemService', version='v201511') + line_item_service = client.GetService('LineItemService', version='v201608') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201511/custom_field_service/update_custom_fields.py b/examples/dfp/v201608/custom_field_service/update_custom_fields.py similarity index 98% rename from examples/dfp/v201511/custom_field_service/update_custom_fields.py rename to examples/dfp/v201608/custom_field_service/update_custom_fields.py index 774b6507..d468d268 100755 --- a/examples/dfp/v201511/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/update_custom_fields.py @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201511') + 'CustomFieldService', version='v201608') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201508/custom_targeting_service/__init__.py b/examples/dfp/v201608/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201508/custom_targeting_service/__init__.py rename to examples/dfp/v201608/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201508/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201508/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py index c2c81306..912771f8 100755 --- a/examples/dfp/v201508/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') + 'CustomTargetingService', version='v201608') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py similarity index 98% rename from examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py index 76c76226..4882cf8a 100755 --- a/examples/dfp/v201511/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201511') + 'CustomTargetingService', version='v201608') values = [{ 'key': 'name', diff --git a/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py similarity index 98% rename from examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py index 5044d18d..60b21ab2 100755 --- a/examples/dfp/v201508/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py @@ -37,7 +37,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') + 'CustomTargetingService', version='v201608') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..0c1f1ceb --- /dev/null +++ b/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2016 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 targeting keys and values. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201608') + + # Create statement to get all targeting keys. + targeting_key_statement = dfp.FilterStatement() + + all_keys = [] + + # Get custom targeting keys by statement. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + targeting_key_statement.ToStatement()) + if 'results' in response: + all_keys.extend(response['results']) + targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + if all_keys: + # Create a statement to select custom targeting values. + query = ('WHERE customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys])) + statement = dfp.FilterStatement(query) + + # Retreive a small amount of custom targeting values at a time, paging + # through until all custom targeting values have been retrieved. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response: + for custom_targeting_value in response['results']: + # Print out some information for each custom targeting value. + print('Custom targeting value with ID "%d", name "%s", display name ' + '"%s", and custom targeting key ID "%d" was found.\n' % + (custom_targeting_value['id'], custom_targeting_value['name'], + custom_targeting_value['displayName'], + custom_targeting_value['customTargetingKeyId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..b2eb5870 --- /dev/null +++ b/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2016 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 targeting keys and values. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201608') + + # Create statement to get targeting keys for predefined values. + query = ('WHERE type = :type') + values = [{ + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PREDEFINED' + } + }] + targeting_key_statement = dfp.FilterStatement(query, values) + + all_keys = [] + + # Get custom targeting keys by statement. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + targeting_key_statement.ToStatement()) + if 'results' in response: + all_keys.extend(response['results']) + targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + if all_keys: + # Create a statement to select custom targeting values. + query = ('WHERE customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys])) + statement = dfp.FilterStatement(query) + + # Retreive a small amount of custom targeting values at a time, paging + # through until all custom targeting values have been retrieved. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response: + for custom_targeting_value in response['results']: + # Print out some information for each custom targeting value. + print('Custom targeting value with ID "%d", name "%s", display name ' + '"%s", and custom targeting key ID "%d" was found.\n' % + (custom_targeting_value['id'], custom_targeting_value['name'], + custom_targeting_value['displayName'], + custom_targeting_value['customTargetingKeyId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py similarity index 97% rename from examples/dfp/v201508/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py index a7d52b61..8da5581e 100755 --- a/examples/dfp/v201508/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py @@ -29,7 +29,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') + 'CustomTargetingService', version='v201608') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201508/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py similarity index 97% rename from examples/dfp/v201508/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py index bc874204..0154e6cb 100755 --- a/examples/dfp/v201508/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') + 'CustomTargetingService', version='v201608') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201508/exchange_rate_service/__init__.py b/examples/dfp/v201608/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201508/exchange_rate_service/__init__.py rename to examples/dfp/v201608/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201508/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201508/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py index 6e2d1491..64dbfed7 100755 --- a/examples/dfp/v201508/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201508') + version='v201608') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201511/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py similarity index 57% rename from examples/dfp/v201511/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py index ba9a0c5d..312c5213 100755 --- a/examples/dfp/v201511/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,40 +13,34 @@ # 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 code example gets all exchange rates. - -To create exchange rates, run create_exchange_rates.py. - +"""This example gets all exchange rates. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201511') + exchange_rate_service = client.GetService( + 'ExchangeRateService', version='v201608') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select exchange rates. + statement = dfp.FilterStatement() - # Get all exchange rates by statement. + # Retrieve a small amount of exchange rates at a time, paging + # through until all exchange rates have been retrieved. while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for exchange_rate in response['results']: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was found.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + # Print out some information for each exchange rate. + print( + 'Exchange rate with ID "%d", currency code "%s", direction "%s", ' + 'and exchange rate "%d" was found.\n' % + (exchange_rate['id'], exchange_rate['currencyCode'], + exchange_rate['direction'], exchange_rate['exchangeRate'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 59% rename from examples/dfp/v201508/exchange_rate_service/get_exchange_rates_by_currency_code.py rename to examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py index 2a354485..dd6e2b49 100755 --- a/examples/dfp/v201508/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 the exchange rate for a specific currency code. - -To create exchange rates, run create_exchange_rates.py. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -29,35 +24,31 @@ def main(client, currency_code): # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201508') - - # Create a statement to get exchange rates for the specified currency code. - values = [{ - 'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - } - }] + exchange_rate_service = client.GetService( + 'ExchangeRateService', version='v201608') query = 'WHERE currencyCode = :currencyCode' - # Create a filter statement. + values = [ + {'key': 'currencyCode', + 'value': { + 'xsi_type': 'TextValue', + 'value': currency_code + }}, + ] + # Create a statement to select exchange rates. statement = dfp.FilterStatement(query, values) - # Get rate cards by statement. + # Retrieve a small amount of exchange rates at a time, paging + # through until all exchange rates have been retrieved. while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for exchange_rate in response['results']: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was found.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + # Print out some information for each exchange rate. + print('Exchange rate with ID "%d", currency code "%s", and exchange ' + 'rate "%.2f" was found.\n' % + (exchange_rate['id'], exchange_rate['currencyCode'], + float(exchange_rate['exchangeRate'] / 1000000))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py similarity index 97% rename from examples/dfp/v201508/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py index 395fa493..9ce75995 100755 --- a/examples/dfp/v201508/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201508') + version='v201608') # Create a statement to get an exchange rate by its ID. values = [{ diff --git a/examples/dfp/v201508/inventory_service/__init__.py b/examples/dfp/v201608/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201508/inventory_service/__init__.py rename to examples/dfp/v201608/inventory_service/__init__.py diff --git a/examples/dfp/v201508/inventory_service/archive_ad_units.py b/examples/dfp/v201608/inventory_service/archive_ad_units.py similarity index 99% rename from examples/dfp/v201508/inventory_service/archive_ad_units.py rename to examples/dfp/v201608/inventory_service/archive_ad_units.py index f4783b96..a0f83f84 100755 --- a/examples/dfp/v201508/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201608/inventory_service/archive_ad_units.py @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201508') + inventory_service = client.GetService('InventoryService', version='v201608') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201511/inventory_service/create_ad_units.py b/examples/dfp/v201608/inventory_service/create_ad_units.py similarity index 97% rename from examples/dfp/v201511/inventory_service/create_ad_units.py rename to examples/dfp/v201608/inventory_service/create_ad_units.py index a170447f..8b83f144 100755 --- a/examples/dfp/v201511/inventory_service/create_ad_units.py +++ b/examples/dfp/v201608/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201511') + inventory_service = client.GetService('InventoryService', version='v201608') # Create ad unit size. ad_unit_size = { @@ -53,7 +53,6 @@ def main(client, parent_id): 'parentId': parent_id, 'description': 'Ad unit description.', 'targetWindow': 'BLANK', - 'targetPlatform': 'WEB', 'adUnitSizes': [ad_unit_size] } diff --git a/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py new file mode 100755 index 00000000..1f1fe0fd --- /dev/null +++ b/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 unit sizes. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + ad_unit_size_service = client.GetService( + 'InventoryService', version='v201608') + + # Create a statement to select ad unit sizes. + statement = dfp.FilterStatement() + + # Retreive a small amount of ad unit sizes at a time, paging + # through until all ad unit sizes have been retrieved. + while True: + response = ad_unit_size_service.getAdUnitSizesByStatement( + statement.ToStatement()) + if response: + for ad_unit_size in response: + # Print out some information for each ad unit size. + print('Ad unit size with dimensions "%s" was found.\n' % + (ad_unit_size['fullDisplayString'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/inventory_service/get_all_ad_units.py b/examples/dfp/v201608/inventory_service/get_all_ad_units.py new file mode 100755 index 00000000..bd058720 --- /dev/null +++ b/examples/dfp/v201608/inventory_service/get_all_ad_units.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + ad_unit_service = client.GetService('InventoryService', version='v201608') + + # Create a statement to select ad units. + statement = dfp.FilterStatement() + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response: + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/inventory_service/update_ad_units.py b/examples/dfp/v201608/inventory_service/update_ad_units.py similarity index 99% rename from examples/dfp/v201508/inventory_service/update_ad_units.py rename to examples/dfp/v201608/inventory_service/update_ad_units.py index 2b7dda3e..f2366d35 100755 --- a/examples/dfp/v201508/inventory_service/update_ad_units.py +++ b/examples/dfp/v201608/inventory_service/update_ad_units.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201508') + inventory_service = client.GetService('InventoryService', version='v201608') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201508/label_service/__init__.py b/examples/dfp/v201608/label_service/__init__.py similarity index 100% rename from examples/dfp/v201508/label_service/__init__.py rename to examples/dfp/v201608/label_service/__init__.py diff --git a/examples/dfp/v201511/label_service/create_labels.py b/examples/dfp/v201608/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201511/label_service/create_labels.py rename to examples/dfp/v201608/label_service/create_labels.py index 62bc0c81..71c92934 100755 --- a/examples/dfp/v201511/label_service/create_labels.py +++ b/examples/dfp/v201608/label_service/create_labels.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201511') + label_service = client.GetService('LabelService', version='v201608') # Create label objects. labels = [] diff --git a/examples/dfp/v201508/label_service/deactivate_labels.py b/examples/dfp/v201608/label_service/deactivate_labels.py similarity index 99% rename from examples/dfp/v201508/label_service/deactivate_labels.py rename to examples/dfp/v201608/label_service/deactivate_labels.py index 0b71733b..a77bca6f 100755 --- a/examples/dfp/v201508/label_service/deactivate_labels.py +++ b/examples/dfp/v201608/label_service/deactivate_labels.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201508') + label_service = client.GetService('LabelService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201511/label_service/get_labels_by_statement.py b/examples/dfp/v201608/label_service/get_active_labels.py similarity index 63% rename from examples/dfp/v201511/label_service/get_labels_by_statement.py rename to examples/dfp/v201608/label_service/get_active_labels.py index b0696743..549f79bc 100755 --- a/examples/dfp/v201511/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201608/label_service/get_active_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,36 @@ # 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 code example gets all labels ordered by name. - -To create a label, run create_label.py. This feature is only available to DFP -premium solution networks. +"""This example gets all active labels. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201511') - - # Create statement to get all labels - statement = dfp.FilterStatement('ORDER BY name') - - # Get labels by statement. + label_service = client.GetService('LabelService', version='v201608') + query = 'WHERE isActive = :isActive' + values = [ + {'key': 'isActive', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select labels. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of labels at a time, paging + # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' was found.' - % (label['id'], label['name'])) + # Print out some information for each label. + print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], + label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/label_service/get_all_labels.py b/examples/dfp/v201608/label_service/get_all_labels.py similarity index 73% rename from examples/dfp/v201511/label_service/get_all_labels.py rename to examples/dfp/v201608/label_service/get_all_labels.py index 7d662ee5..e8c29f8f 100755 --- a/examples/dfp/v201511/label_service/get_all_labels.py +++ b/examples/dfp/v201608/label_service/get_all_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 code example gets all labels. - -To create labels, run create_labels.py. This feature is only available to DFP -premium solution networks.""" - +"""This example gets all labels. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,19 +22,20 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201511') + label_service = client.GetService('LabelService', version='v201608') - # Create statement to get all labels + # Create a statement to select labels. statement = dfp.FilterStatement() - # Get labels by statement. + # Retrieve a small amount of labels at a time, paging + # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' was found.' - % (label['id'], label['name'])) + # Print out some information for each label. + print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], + label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/label_service/update_labels.py b/examples/dfp/v201608/label_service/update_labels.py similarity index 99% rename from examples/dfp/v201508/label_service/update_labels.py rename to examples/dfp/v201608/label_service/update_labels.py index 85da0b5d..5b3f1596 100755 --- a/examples/dfp/v201508/label_service/update_labels.py +++ b/examples/dfp/v201608/label_service/update_labels.py @@ -28,7 +28,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201508') + label_service = client.GetService('LabelService', version='v201608') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201508/line_item_creative_association_service/__init__.py b/examples/dfp/v201608/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201508/line_item_creative_association_service/__init__.py rename to examples/dfp/v201608/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201511/line_item_creative_association_service/create_licas.py b/examples/dfp/v201608/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201511/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201608/line_item_creative_association_service/create_licas.py index b76ef132..47e9e67e 100755 --- a/examples/dfp/v201511/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201608/line_item_creative_association_service/create_licas.py @@ -31,7 +31,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201511') + 'LineItemCreativeAssociationService', version='v201608') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201511/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py similarity index 97% rename from examples/dfp/v201511/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py index ab7d3532..92f350f7 100755 --- a/examples/dfp/v201511/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py @@ -29,7 +29,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201511') + 'LineItemCreativeAssociationService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201511/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py similarity index 56% rename from examples/dfp/v201511/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py index a9beaf0b..c4a41691 100755 --- a/examples/dfp/v201511/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all line item creative associations (LICA). - -To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py. +"""This example gets all line item creative associations. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,29 +23,34 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201511') + 'LineItemCreativeAssociationService', version='v201608') - # Create a filter statement. + # Create a statement to select line item creative associations. statement = dfp.FilterStatement() - # Get line items by statement. + # Retrieve a small amount of line item creative associations at a time, paging + # through until all line item creative associations have been retrieved. while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for lica in response['results']: + # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print ('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % - (lica['lineItemId'], lica['creativeSetId'], lica['status'])) + print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' + 'status \'%s\' was found.' % + (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: - print ('LICA with line item ID \'%s\', creative ID \'%s\', and status' - ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print('Line item creative association with line item ID "%d" and ' + 'creative ID "%d" was found.\n' % + (lica['lineItemId'], lica['creativeId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py similarity index 52% rename from examples/dfp/v201508/line_item_creative_association_service/get_licas_by_statement.py rename to examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py index 605df830..13265dee 100755 --- a/examples/dfp/v201508/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,52 +13,52 @@ # 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 code example gets all line item creative associations (LICA) for a given -line item id. - -To create LICAs, run create_licas.py.""" - +"""This example gets all line item creative associations for a given line item. +""" # Import appropriate modules from the client library. from googleads import dfp -# Set the id of the line item to get LICAs by. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201508') - -# Create statement object to only select LICAs for the given line item id. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] + 'LineItemCreativeAssociationService', version='v201608') query = 'WHERE lineItemId = :lineItemId' + values = [ + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'TextValue', + 'value': line_item_id + }}, + ] + # Create a statement to select line item creative associations. statement = dfp.FilterStatement(query, values) + # Retrieve a small amount of line item creative associations at a time, paging + # through until all line item creative associations have been retrieved. while True: - # Get LICAs by statement. response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: - # Display results. for lica in response['results']: - print ('LICA with line item id \'%s\', creative id \'%s\', and status ' - '\'%s\' was found.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + # Print out some information for each line item creative association. + if 'creativeSetId' in lica: + print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' + 'status \'%s\' was found.' % + (lica['lineItemId'], lica['creativeSetId'], lica['status'])) + else: + print('Line item creative association with line item ID "%d" and ' + 'creative ID "%d" was found.\n' % + (lica['lineItemId'], lica['creativeId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201508/line_item_creative_association_service/update_licas.py b/examples/dfp/v201608/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201508/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201608/line_item_creative_association_service/update_licas.py index 1bc27b6c..cf9b1f35 100755 --- a/examples/dfp/v201508/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201608/line_item_creative_association_service/update_licas.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201508') + 'LineItemCreativeAssociationService', version='v201608') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201508/line_item_service/__init__.py b/examples/dfp/v201608/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201508/line_item_service/__init__.py rename to examples/dfp/v201608/line_item_service/__init__.py diff --git a/examples/dfp/v201508/line_item_service/activate_line_items.py b/examples/dfp/v201608/line_item_service/activate_line_items.py similarity index 99% rename from examples/dfp/v201508/line_item_service/activate_line_items.py rename to examples/dfp/v201608/line_item_service/activate_line_items.py index e6fa74cc..66e0bb41 100755 --- a/examples/dfp/v201508/line_item_service/activate_line_items.py +++ b/examples/dfp/v201608/line_item_service/activate_line_items.py @@ -32,7 +32,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') + line_item_service = client.GetService('LineItemService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201511/line_item_service/create_line_items.py b/examples/dfp/v201608/line_item_service/create_line_items.py similarity index 99% rename from examples/dfp/v201511/line_item_service/create_line_items.py rename to examples/dfp/v201608/line_item_service/create_line_items.py index 8b3e90c2..922e170b 100755 --- a/examples/dfp/v201511/line_item_service/create_line_items.py +++ b/examples/dfp/v201608/line_item_service/create_line_items.py @@ -35,7 +35,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') + line_item_service = client.GetService('LineItemService', version='v201608') # Create line item objects. line_items = [] diff --git a/examples/dfp/v201511/line_item_service/create_video_line_item.py b/examples/dfp/v201608/line_item_service/create_video_line_item.py similarity index 99% rename from examples/dfp/v201511/line_item_service/create_video_line_item.py rename to examples/dfp/v201608/line_item_service/create_video_line_item.py index 0c5cf526..06a34de7 100755 --- a/examples/dfp/v201511/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201608/line_item_service/create_video_line_item.py @@ -45,7 +45,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201511') + line_item_service = client.GetService('LineItemService', version='v201608') # Create line item object. line_item = { diff --git a/examples/dfp/v201508/line_item_service/get_all_line_items.py b/examples/dfp/v201608/line_item_service/get_all_line_items.py similarity index 68% rename from examples/dfp/v201508/line_item_service/get_all_line_items.py rename to examples/dfp/v201608/line_item_service/get_all_line_items.py index d40f5f49..99a8c84f 100755 --- a/examples/dfp/v201508/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201608/line_item_service/get_all_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,11 +13,8 @@ # 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 code example gets all line items. - -To create line items, run create_line_items.py.""" - +"""This example gets all line items. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -25,27 +22,28 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') + line_item_service = client.GetService('LineItemService', version='v201608') - # Create a filter statement. + # Create a statement to select line items. statement = dfp.FilterStatement() - # Get line items by statement. + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % - (line_item['id'], line_item['orderId'], line_item['name'])) + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py new file mode 100755 index 00000000..c67e7bef --- /dev/null +++ b/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 line items that are missing creatives. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201608') + query = 'WHERE isMissingCreatives = :isMissingCreatives' + values = [ + {'key': 'isMissingCreatives', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select line items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response: + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py new file mode 100755 index 00000000..dd3edd39 --- /dev/null +++ b/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 only recently updated line items. +""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201608') + query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' + values = [ + {'key': 'lastModifiedDateTime', + 'value': { + 'xsi_type': 'TextValue', + 'value': (datetime.now() - timedelta(days=1)) + .strftime('%Y-%m-%dT%H:%M:%S') + }}, + ] + # Create a statement to select line items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response: + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/line_item_service/target_custom_criteria.py b/examples/dfp/v201608/line_item_service/target_custom_criteria.py similarity index 99% rename from examples/dfp/v201508/line_item_service/target_custom_criteria.py rename to examples/dfp/v201608/line_item_service/target_custom_criteria.py index a5b1ae92..5ff0a04f 100755 --- a/examples/dfp/v201508/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201608/line_item_service/target_custom_criteria.py @@ -39,7 +39,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') + line_item_service = client.GetService('LineItemService', version='v201608') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201508/line_item_service/update_line_items.py b/examples/dfp/v201608/line_item_service/update_line_items.py similarity index 99% rename from examples/dfp/v201508/line_item_service/update_line_items.py rename to examples/dfp/v201608/line_item_service/update_line_items.py index f5464c86..845a2864 100755 --- a/examples/dfp/v201508/line_item_service/update_line_items.py +++ b/examples/dfp/v201608/line_item_service/update_line_items.py @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') + line_item_service = client.GetService('LineItemService', version='v201608') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201508/network_service/__init__.py b/examples/dfp/v201608/network_service/__init__.py similarity index 100% rename from examples/dfp/v201508/network_service/__init__.py rename to examples/dfp/v201608/network_service/__init__.py diff --git a/examples/dfp/v201511/network_service/get_all_networks.py b/examples/dfp/v201608/network_service/get_all_networks.py similarity index 69% rename from examples/dfp/v201511/network_service/get_all_networks.py rename to examples/dfp/v201608/network_service/get_all_networks.py index 867c9319..a3683152 100755 --- a/examples/dfp/v201511/network_service/get_all_networks.py +++ b/examples/dfp/v201608/network_service/get_all_networks.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 networks that you have access to with the current login -credentials. - -A networkCode should be left out for this request.""" - +"""This example gets all networks. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,18 +22,18 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201511') + network_service = client.GetService('NetworkService', version='v201608') - # Get all networks that you have access to with the current login credentials. networks = network_service.getAllNetworks() - # Display results. + # Print out some information for each network. for network in networks: - print ('Network with network code \'%s\' and display name \'%s\' was found.' - % (network['networkCode'], network['displayName'])) + print('Network with network code \'%s\' and display name \'%s\' was found.' + % (network['networkCode'], network['displayName'])) print '\nNumber of results found: %s' % len(networks) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/network_service/make_test_network.py b/examples/dfp/v201608/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201508/network_service/make_test_network.py rename to examples/dfp/v201608/network_service/make_test_network.py index 1284f124..35e0577c 100755 --- a/examples/dfp/v201508/network_service/make_test_network.py +++ b/examples/dfp/v201608/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201508') + network_service = client.GetService('NetworkService', version='v201608') # Create a test network. network = network_service.MakeTestNetwork() diff --git a/examples/dfp/v201508/order_service/__init__.py b/examples/dfp/v201608/order_service/__init__.py similarity index 100% rename from examples/dfp/v201508/order_service/__init__.py rename to examples/dfp/v201608/order_service/__init__.py diff --git a/examples/dfp/v201508/order_service/approve_orders.py b/examples/dfp/v201608/order_service/approve_orders.py similarity index 99% rename from examples/dfp/v201508/order_service/approve_orders.py rename to examples/dfp/v201608/order_service/approve_orders.py index 6f49b0b9..fce28cbd 100755 --- a/examples/dfp/v201508/order_service/approve_orders.py +++ b/examples/dfp/v201608/order_service/approve_orders.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201508') + order_service = client.GetService('OrderService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201508/order_service/create_orders.py b/examples/dfp/v201608/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201508/order_service/create_orders.py rename to examples/dfp/v201608/order_service/create_orders.py index f847ab30..26babf04 100755 --- a/examples/dfp/v201508/order_service/create_orders.py +++ b/examples/dfp/v201608/order_service/create_orders.py @@ -31,7 +31,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201508') + order_service = client.GetService('OrderService', version='v201608') # Create order objects. orders = [] diff --git a/examples/dfp/v201511/order_service/get_all_orders.py b/examples/dfp/v201608/order_service/get_all_orders.py similarity index 73% rename from examples/dfp/v201511/order_service/get_all_orders.py rename to examples/dfp/v201608/order_service/get_all_orders.py index 278de5d3..aebbacd3 100755 --- a/examples/dfp/v201511/order_service/get_all_orders.py +++ b/examples/dfp/v201608/order_service/get_all_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,32 +13,29 @@ # 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 code example gets all orders. - -To create orders, run create_orders.py. +"""This example gets all orders. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201511') + order_service = client.GetService('OrderService', version='v201608') - # Create a filter statement. + # Create a statement to select orders. statement = dfp.FilterStatement() - # Get orders by statement. + # Retrieve a small amount of orders at a time, paging + # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for order in response['results']: - print ('Order with id \'%s\', name \'%s\', and advertiser id \'%s\' was' - ' found.' % (order['id'], order['name'], order['advertiserId'])) + # Print out some information for each order. + print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], + order['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201608/order_service/get_orders_starting_soon.py b/examples/dfp/v201608/order_service/get_orders_starting_soon.py new file mode 100755 index 00000000..cd3cd2b5 --- /dev/null +++ b/examples/dfp/v201608/order_service/get_orders_starting_soon.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2016 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 orders that are starting soon. +""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + order_service = client.GetService('OrderService', version='v201608') + query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' + '<= :soon') + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'APPROVED' + }}, + {'key': 'now', + 'value': { + 'xsi_type': 'TextValue', + 'value': datetime.now().strftime('%y-%m-%d_t%h:%m:%s') + }}, + {'key': 'soon', + 'value': { + 'xsi_type': 'TextValue', + 'value': (datetime.now() + timedelta(days=5)) + .strftime('%Y-%m-%dT%H:%M:%S') + }}, + ] + # Create a statement to select orders. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of orders at a time, paging + # through until all orders have been retrieved. + while True: + response = order_service.getOrdersByStatement(statement.ToStatement()) + if 'results' in response: + for order in response['results']: + # Print out some information for each order. + print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], + order['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201511/order_service/update_orders.py b/examples/dfp/v201608/order_service/update_orders.py similarity index 99% rename from examples/dfp/v201511/order_service/update_orders.py rename to examples/dfp/v201608/order_service/update_orders.py index 7fab14ac..fa0496a6 100755 --- a/examples/dfp/v201511/order_service/update_orders.py +++ b/examples/dfp/v201608/order_service/update_orders.py @@ -27,7 +27,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201511') + order_service = client.GetService('OrderService', version='v201608') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201508/label_service/get_all_labels.py b/examples/dfp/v201608/package_service/get_all_packages.py similarity index 63% rename from examples/dfp/v201508/label_service/get_all_labels.py rename to examples/dfp/v201608/package_service/get_all_packages.py index 85bbecec..8987bd1e 100755 --- a/examples/dfp/v201508/label_service/get_all_labels.py +++ b/examples/dfp/v201608/package_service/get_all_packages.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 code example gets all labels. - -To create labels, run create_labels.py. This feature is only available to DFP -premium solution networks.""" - +"""This example gets all packages. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,19 +22,21 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201508') + pkg_service = client.GetService('PackageService', version='v201608') - # Create statement to get all labels + # Create a statement to select packages. statement = dfp.FilterStatement() - # Get labels by statement. + # Retrieve a small amount of packages at a time, paging + # through until all packages have been retrieved. while True: - response = label_service.getLabelsByStatement(statement.ToStatement()) + response = pkg_service.getPackagesByStatement(statement.ToStatement()) if 'results' in response: - # Display results. - for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' was found.' - % (label['id'], label['name'])) + for pkg in response['results']: + # Print out some information for each package. + print( + 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' + % (pkg['id'], pkg['name'], pkg['proposalId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/placement_service/get_placements_by_statement.py b/examples/dfp/v201608/package_service/get_in_progress_packages.py similarity index 58% rename from examples/dfp/v201508/placement_service/get_placements_by_statement.py rename to examples/dfp/v201608/package_service/get_in_progress_packages.py index 21283c4a..e3c9eabb 100755 --- a/examples/dfp/v201508/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201608/package_service/get_in_progress_packages.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,44 @@ # 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 code example gets all active placements by using a statement. - -To create a placement, run create_placements.py. +"""This example gets all packages in progress. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201508') - - # Create a statement to only select active placements. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] + pkg_service = client.GetService('PackageService', version='v201608') query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'IN_PROGRESS' + }}, + ] + # Create a statement to select packages. statement = dfp.FilterStatement(query, values) - # Get placements by statement. + # Retrieve a small amount of packages at a time, paging + # through until all packages have been retrieved. while True: - response = placement_service.getPlacementsByStatement( - statement.ToStatement()) + response = pkg_service.getPackagesByStatement(statement.ToStatement()) if 'results' in response: - # Display results. - for placement in response['results']: - print ('Placement with id \'%s\' and name \'%s\' was found.' - % (placement['id'], placement['name'])) + for pkg in response['results']: + # Print out some information for each package. + print( + 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' + % (pkg['id'], pkg['name'], pkg['proposalId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/placement_service/create_placements.py b/examples/dfp/v201608/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201511/placement_service/create_placements.py rename to examples/dfp/v201608/placement_service/create_placements.py index 0ab286c5..f7cc56d6 100755 --- a/examples/dfp/v201511/placement_service/create_placements.py +++ b/examples/dfp/v201608/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201511') - inventory_service = client.GetService('InventoryService', version='v201511') + placement_service = client.GetService('PlacementService', version='v201608') + inventory_service = client.GetService('InventoryService', version='v201608') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201511/placement_service/deactivate_placements.py b/examples/dfp/v201608/placement_service/deactivate_placements.py similarity index 99% rename from examples/dfp/v201511/placement_service/deactivate_placements.py rename to examples/dfp/v201608/placement_service/deactivate_placements.py index 4bd94f4c..fbc79d28 100755 --- a/examples/dfp/v201511/placement_service/deactivate_placements.py +++ b/examples/dfp/v201608/placement_service/deactivate_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201511') + placement_service = client.GetService('PlacementService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201511/placement_service/get_placements_by_statement.py b/examples/dfp/v201608/placement_service/get_active_placements.py similarity index 64% rename from examples/dfp/v201511/placement_service/get_placements_by_statement.py rename to examples/dfp/v201608/placement_service/get_active_placements.py index 69e649bf..30eb771a 100755 --- a/examples/dfp/v201511/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201608/placement_service/get_active_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,44 @@ # 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 code example gets all active placements by using a statement. - -To create a placement, run create_placements.py. +"""This example gets all active placements. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201511') - - # Create a statement to only select active placements. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] + placement_service = client.GetService('PlacementService', version='v201608') query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select placements. statement = dfp.FilterStatement(query, values) - # Get placements by statement. + # Retrieve a small amount of placements at a time, paging + # through until all placements have been retrieved. while True: - response = placement_service.getPlacementsByStatement( - statement.ToStatement()) + response = placement_service.getPlacementsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for placement in response['results']: - print ('Placement with id \'%s\' and name \'%s\' was found.' - % (placement['id'], placement['name'])) + # Print out some information for each placement. + print('Placement with ID "%d" and name "%s" was found.\n' % + (placement['id'], placement['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/placement_service/get_all_placements.py b/examples/dfp/v201608/placement_service/get_all_placements.py similarity index 68% rename from examples/dfp/v201508/placement_service/get_all_placements.py rename to examples/dfp/v201608/placement_service/get_all_placements.py index dc581a3d..4c710f06 100755 --- a/examples/dfp/v201508/placement_service/get_all_placements.py +++ b/examples/dfp/v201608/placement_service/get_all_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,39 +13,37 @@ # 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 code example gets all placements. - -To create placements, run create_placement.py. +"""This example gets all placements. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201508') + placement_service = client.GetService('PlacementService', version='v201608') - # Create statement to fetch all placements. + # Create a statement to select placements. statement = dfp.FilterStatement() - # Get placements by statement. + # Retrieve a small amount of placements at a time, paging + # through until all placements have been retrieved. while True: - response = placement_service.getPlacementsByStatement( - statement.ToStatement()) + response = placement_service.getPlacementsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for placement in response['results']: - print ('Placement with id \'%s\' and name \'%s\' was found.' - % (placement['id'], placement['name'])) + # Print out some information for each placement. + print('Placement with ID "%d" and name "%s" was found.\n' % + (placement['id'], placement['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/placement_service/update_placements.py b/examples/dfp/v201608/placement_service/update_placements.py similarity index 99% rename from examples/dfp/v201511/placement_service/update_placements.py rename to examples/dfp/v201608/placement_service/update_placements.py index 074c4187..8d50585b 100755 --- a/examples/dfp/v201511/placement_service/update_placements.py +++ b/examples/dfp/v201608/placement_service/update_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201511') + placement_service = client.GetService('PlacementService', version='v201608') # Create query. values = [{ 'key': 'placementId', diff --git a/examples/dfp/v201508/premium_rate_service/__init__.py b/examples/dfp/v201608/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201508/premium_rate_service/__init__.py rename to examples/dfp/v201608/premium_rate_service/__init__.py diff --git a/examples/dfp/v201511/premium_rate_service/create_premium_rates.py b/examples/dfp/v201608/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/dfp/v201511/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201608/premium_rate_service/create_premium_rates.py index 74ca9a90..e051d77b 100755 --- a/examples/dfp/v201511/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201608/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201511') + version='v201608') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201508/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py similarity index 61% rename from examples/dfp/v201508/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py index 155500d2..6f6dc23a 100755 --- a/examples/dfp/v201508/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,38 +13,33 @@ # 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 code example gets all premium rates. - -To create premium rates, run create_premium_rates.py. - +"""This example gets all premium rates. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201508') + premium_rate_service = client.GetService( + 'PremiumRateService', version='v201608') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select premium rates. + statement = dfp.FilterStatement() - # Get premium rates by statement. + # Retrieve a small amount of premium rates at a time, paging + # through until all premium rates have been retrieved. while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for premium_rate in response['results']: - print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' - ' rate card with ID \'%s\' was found.\n' % ( - premium_rate['id'], - dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['rateCardId'])) + # Print out some information for each premium rate. + print('Premium rate with ID "%d", premium feature "%s", and rate card ' + 'id "%d" was found.\n' % (premium_rate['id'], + dfp.DfpClassType(premium_rate), + premium_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 58% rename from examples/dfp/v201511/premium_rate_service/get_premium_rates_for_a_rate_card.py rename to examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py index 4ecbc43a..41ff2610 100755 --- a/examples/dfp/v201511/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all premium rates belonging to a specific rate card. - -To create premium rates, run create_premium_rates.py. - +"""This example gets all premium rates on a specific rate card. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -29,32 +24,31 @@ def main(client, rate_card_id): # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201511') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'rateCardId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': rate_card_id - } - }] - query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC' + premium_rate_service = client.GetService( + 'PremiumRateService', version='v201608') + query = 'WHERE rateCardId = :rateCardId' + values = [ + {'key': 'rateCardId', + 'value': { + 'xsi_type': 'TextValue', + 'value': rate_card_id + }}, + ] + # Create a statement to select premium rates. statement = dfp.FilterStatement(query, values) - # Get premium rates by statement. + # Retrieve a small amount of premium rates at a time, paging + # through until all premium rates have been retrieved. while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for premium_rate in response['results']: - print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' - ' rate card with ID \'%s\' was found.\n' % ( - premium_rate['id'], - dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['rateCardId'])) + # Print out some information for each premium rate. + print('Premium rate with ID "%d", premium feature "%s", and rate card ' + 'ID "%d" was found.\n' % (premium_rate['id'], + premium_rate['premium feature'], + premium_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/premium_rate_service/update_premium_rates.py b/examples/dfp/v201608/premium_rate_service/update_premium_rates.py similarity index 97% rename from examples/dfp/v201511/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201608/premium_rate_service/update_premium_rates.py index 4321181c..81a10c0e 100755 --- a/examples/dfp/v201511/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201608/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201511') + version='v201608') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201508/company_service/get_all_companies.py b/examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py similarity index 56% rename from examples/dfp/v201508/company_service/get_all_companies.py rename to examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py index 3500c1e1..41e1d638 100755 --- a/examples/dfp/v201508/company_service/get_all_companies.py +++ b/examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,40 @@ # 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 code example gets all companies. - -To create companies, run create_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all product package items. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201508') + product_package_item_service = client.GetService( + 'ProductPackageItemService', version='v201608') - # Create statement object to select all companies. + # Create a statement to select product package items. statement = dfp.FilterStatement() - # Get companies by statement. + # Retrieve a small amount of product package items at a time, paging + # through until all product package items have been retrieved. while True: - response = company_service.getCompaniesByStatement( + response = product_package_item_service.getProductPackageItemsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for company in response['results']: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.' - % (company['id'], company['name'], company['type'])) + for product_package_item in response['results']: + # Print out some information for each product package item. + print('Product package item with ID "%d", product id "%d", and product ' + 'package id "%d" was found.\n' % + (product_package_item['id'], product_package_item['productId'], + product_package_item['productPackageId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py new file mode 100755 index 00000000..075dd635 --- /dev/null +++ b/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 product package items belonging to a product package. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + + +def main(client, product_package_id): + # Initialize appropriate service. + product_package_item_service = client.GetService( + 'ProductPackageItemService', version='v201608') + query = 'WHERE productPackageId = :productPackageId' + values = [ + {'key': 'productPackageId', + 'value': { + 'xsi_type': 'TextValue', + 'value': product_package_id + }}, + ] + # Create a statement to select product package items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of product package items at a time, paging + # through until all product package items have been retrieved. + while True: + response = product_package_item_service.getProductPackageItemsByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package_item in response['results']: + # Print out some information for each product package item. + print('Product package item with ID "%d", product ID "%d", and product ' + 'package ID "%d" was found.\n' % + (product_package_item['id'], product_package_item['productId'], + product_package_item['productPackageId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_PACKAGE_ID) diff --git a/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201608/product_package_service/get_active_product_packages.py similarity index 56% rename from examples/dfp/v201508/custom_targeting_service/get_custom_targeting_keys_by_statement.py rename to examples/dfp/v201608/product_package_service/get_active_product_packages.py index b8b6b58a..dc73e915 100755 --- a/examples/dfp/v201508/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201608/product_package_service/get_active_product_packages.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,48 +13,45 @@ # 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 predefined custom targeting keys. - -To create custom targeting keys, run create_custom_targeting_keys_and_values.py. +"""This example gets all active product packages. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201508') - - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] - query = 'WHERE type = :type' + product_package_service = client.GetService( + 'ProductPackageService', version='v201608') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select product packages. statement = dfp.FilterStatement(query, values) - # Get custom targeting keys by statement. + # Retrieve a small amount of product packages at a time, paging + # through until all product packages have been retrieved. while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( + response = product_package_service.getProductPackagesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for key in response['results']: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was found.' - % (key['id'], key['name'], key['displayName'], key['type'])) + for product_package in response['results']: + # Print out some information for each product package. + print('Product package with ID "%d" and name "%s" was found.\n' % + (product_package['id'], product_package['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201608/product_package_service/get_all_product_packages.py b/examples/dfp/v201608/product_package_service/get_all_product_packages.py new file mode 100755 index 00000000..16b03d95 --- /dev/null +++ b/examples/dfp/v201608/product_package_service/get_all_product_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2016 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 product packages. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_package_service = client.GetService( + 'ProductPackageService', version='v201608') + + # Create a statement to select product packages. + statement = dfp.FilterStatement() + + # Retrieve a small amount of product packages at a time, paging + # through until all product packages have been retrieved. + while True: + response = product_package_service.getProductPackagesByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package in response['results']: + # Print out some information for each product package. + print('Product package with ID "%d" and name "%s" was found.\n' % + (product_package['id'], product_package['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/product_service/__init__.py b/examples/dfp/v201608/product_service/__init__.py similarity index 100% rename from examples/dfp/v201508/product_service/__init__.py rename to examples/dfp/v201608/product_service/__init__.py diff --git a/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py new file mode 100755 index 00000000..87bb3363 --- /dev/null +++ b/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a programmatic product for non-sales management. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + product_service = client.GetService('ProductService', version='v201608') + network_service = client.GetService('NetworkService', version='v201608') + + product = { + # Setting required Marketplace Information. + 'productMarketplaceInfo': { + 'additionalTerms': 'Remember to also discuss that thing.', + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for products. + 'name': ('Product #%d' % uuid.uuid4()), + 'productType': 'DFP', + 'rateType': 'CPM', + 'lineItemType': 'STANDARD', + 'priority': 8, + 'environment': 'BROWSER', + 'rate': { + 'currencyCode': 'USD', + 'microAmount': '6000000' + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'builtInTargeting': { + 'inventoryTargeting': { + 'adUnitTargeting': { + 'adUnitId': network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId'], + 'includeDescendents': 'true' + } + } + }, + } + + products = product_service.createProducts([product]) + + if products: + for product in products: + print ('A programmatic product for non-sales management with ID "%s"' + ' and name "%s" was created.' % (product['id'], product['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201511/product_service/get_all_products.py b/examples/dfp/v201608/product_service/get_all_products.py similarity index 72% rename from examples/dfp/v201511/product_service/get_all_products.py rename to examples/dfp/v201608/product_service/get_all_products.py index 2df37979..468bd05a 100755 --- a/examples/dfp/v201511/product_service/get_all_products.py +++ b/examples/dfp/v201608/product_service/get_all_products.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,29 @@ # 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 code example gets all products. - -Products are created automatically from product templates. - +"""This example gets all products. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201511') + product_service = client.GetService('ProductService', version='v201608') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select products. + statement = dfp.FilterStatement() - # Get products by statement. + # Retrieve a small amount of products at a time, paging + # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' was found.' % ( - product['id'], product['name'])) + # Print out some information for each product. + print('Product with ID "%d" and name "%s" was found.\n' % + (product['id'], product['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/product_service/get_products_for_product_template.py b/examples/dfp/v201608/product_service/get_products_for_product_template.py similarity index 70% rename from examples/dfp/v201508/product_service/get_products_for_product_template.py rename to examples/dfp/v201608/product_service/get_products_for_product_template.py index ae7acbca..2072df12 100755 --- a/examples/dfp/v201508/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201608/product_service/get_products_for_product_template.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,9 @@ # 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 products created from a product template. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,28 +24,28 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201508') - - # Create a filter statement to select only products created from a single - # a product template. - values = [{ - 'key': 'productTemplateId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE productTemplateId = :productTemplateId ORDER BY id ASC' + product_service = client.GetService('ProductService', version='v201608') + + query = 'WHERE productTemplateId = :productTemplateId' + values = [ + {'key': 'productTemplateId', + 'value': { + 'xsi_type': 'TextValue', + 'value': product_template_id + }}, + ] + # Create a statement to select products. statement = dfp.FilterStatement(query, values) - # Get products by statement. + # Retrieve a small amount of products at a time, paging + # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' was found.' % ( - product['id'], product['name'])) + # Print out some information for each product. + print('Product with ID "%d" and name "%s" was found.\n' % + (product['id'], product['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/product_service/update_products.py b/examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py similarity index 56% rename from examples/dfp/v201508/product_service/update_products.py rename to examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py index c82aa09d..63173a32 100755 --- a/examples/dfp/v201508/product_service/update_products.py +++ b/examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py @@ -14,24 +14,22 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates a product's notes. - -To determine which products exist, run get_all_products.py. - +"""This code example publishes a product to Marketplace. """ # Import appropriate modules from the client library. from googleads import dfp +# Set the id of the product to publish. PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201508') + product_service = client.GetService('ProductService', version='v201608') - # Create statement object to select a single product by an ID. + # Create query. values = [{ 'key': 'id', 'value': { @@ -42,29 +40,33 @@ def main(client, product_id): query = 'WHERE id = :id' statement = dfp.FilterStatement(query, values, 1) - # Get products by statement. - response = product_service.getProductsByStatement(statement.ToStatement()) - - if 'results' in response: - # Update each local product object by changing its notes. - updated_products = [] - for product in response['results']: - product['notes'] = 'Product needs further review before activation.' - updated_products.append(product) + products_published = 0 - # Update products remotely. - products = product_service.updateProducts(updated_products) + # Get products by statement. + while True: + response = product_service.getProductsByStatement( + statement.ToStatement()) + if 'results' in response: + for product in response['results']: + print ('Product with id \'%s\' and name \'%s\' will be ' + 'published.' % (product['id'], + product['name'])) - # Display results. - if products: - for product in products: - print ('Product with id \'%s\', name \'%s\', and ' - 'notes \'%s\' was updated.' - % (product['id'], product['name'], product['notes'])) + # Perform action. + result = product_service.performProductAction( + {'xsi_type': 'PublishProducts'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + products_published += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: - print 'No products were updated.' + break + + # Display results. + if products_published > 0: + print 'Number of programmatic products published: %s' % products_published else: - print 'No products found to update.' + print 'No products were published.' + if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201511/product_service/update_products.py b/examples/dfp/v201608/product_service/update_products.py similarity index 99% rename from examples/dfp/v201511/product_service/update_products.py rename to examples/dfp/v201608/product_service/update_products.py index 5275cfe2..ac4e1e3f 100755 --- a/examples/dfp/v201511/product_service/update_products.py +++ b/examples/dfp/v201608/product_service/update_products.py @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201511') + product_service = client.GetService('ProductService', version='v201608') # Create statement object to select a single product by an ID. values = [{ diff --git a/examples/dfp/v201508/product_template_service/__init__.py b/examples/dfp/v201608/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201508/product_template_service/__init__.py rename to examples/dfp/v201608/product_template_service/__init__.py diff --git a/examples/dfp/v201508/product_template_service/activate_product_templates.py b/examples/dfp/v201608/product_template_service/activate_product_templates.py similarity index 97% rename from examples/dfp/v201508/product_template_service/activate_product_templates.py rename to examples/dfp/v201608/product_template_service/activate_product_templates.py index 52c72f08..d67f931c 100755 --- a/examples/dfp/v201508/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201608/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201508') + 'ProductTemplateService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201511/product_template_service/create_product_templates.py b/examples/dfp/v201608/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201511/product_template_service/create_product_templates.py rename to examples/dfp/v201608/product_template_service/create_product_templates.py index dfbe45e7..e8d244ec 100755 --- a/examples/dfp/v201511/product_template_service/create_product_templates.py +++ b/examples/dfp/v201608/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201511') + 'ProductTemplateService', version='v201608') network_service = client.GetService( - 'NetworkService', version='v201511') + 'NetworkService', version='v201608') # Create a product template. product_template = { diff --git a/examples/dfp/v201508/product_template_service/create_product_templates.py b/examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py similarity index 66% rename from examples/dfp/v201508/product_template_service/create_product_templates.py rename to examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py index 018958e2..bd38db83 100755 --- a/examples/dfp/v201508/product_template_service/create_product_templates.py +++ b/examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example creates a product template. - -To determine which product templates exist, run get_all_product_templates.py. +"""This example creates a programmatic product template. """ import uuid @@ -26,23 +24,25 @@ def main(client): - # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201508') + 'ProductTemplateService', version='v201608') network_service = client.GetService( - 'NetworkService', version='v201508') + 'NetworkService', version='v201608') - # Create a product template. product_template = { + # Setting required Marketplace information. + 'productTemplateMarketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + # Setting common required fields for product templates. 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard proposal line ' - 'items targeting Chrome browsers with product ' - 'segmentation on ad units and geo targeting.'), + 'description': ('This product template creates standard programmatic' + 'proposal line items targeting all ad units with' + 'product segmentation on geo targeting.'), 'nameMacro': (' - - ' ' - '), 'productType': 'DFP', 'rateType': 'CPM', - 'roadblockingType': 'ONE_OR_MORE', 'creativePlaceholders': [ { 'size': { @@ -58,20 +58,6 @@ def main(client): } ], 'lineItemType': 'STANDARD', - 'builtInTargeting': { - 'technologyTargeting': { - # Set browser targeting to Chrome. - 'browserTargeting': { - { - 'browsers': [ - { - 'id': '500072' - } - ] - } - } - } - }, 'productSegmentation': { 'geoSegment': { 'targetedLocations': [ @@ -89,14 +75,14 @@ def main(client): } } - # Create product templates on the server. product_templates = product_template_service.createProductTemplates( [product_template]) if product_templates: for product_template in product_templates: - print ('A product template with ID \'%s\' and name \'%s\' was ' - 'created.' % (product_template['id'], product_template['name'])) + print ('A programmatic product template with ID \'%s\' and name \'%s\' ' + 'was created.' % (product_template['id'], + product_template['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201508/product_template_service/get_all_product_templates.py b/examples/dfp/v201608/product_template_service/get_all_product_templates.py similarity index 68% rename from examples/dfp/v201508/product_template_service/get_all_product_templates.py rename to examples/dfp/v201608/product_template_service/get_all_product_templates.py index 8e82c5e6..5fe8887e 100755 --- a/examples/dfp/v201508/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201608/product_template_service/get_all_product_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all product templates. - -To create product templates, run create_product_template_templates.py. - +"""This example gets all product templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -28,20 +23,21 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201508') + 'ProductTemplateService', version='v201608') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select product templates. + statement = dfp.FilterStatement() - # Get product templates by statement. + # Retrieve a small amount of product templates at a time, paging + # through until all product templates have been retrieved. while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' was found.' % ( - product_template['id'], product_template['name'])) + # Print out some information for each product template. + print('Product template with ID "%d" and name "%s" was found.\n' % + (product_template['id'], product_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py similarity index 63% rename from examples/dfp/v201508/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py index 6da4290d..cf412570 100755 --- a/examples/dfp/v201508/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,9 @@ # 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 code example gets all sponsorship product templates. - +"""This example gets all sponsorship product templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -26,28 +23,28 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201508') - - # Create a statement to select all sponsorship product templates. - values = [{ - 'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - } - }] - query = 'WHERE lineItemType = :lineItemType ORDER BY id ASC' + 'ProductTemplateService', version='v201608') + query = 'WHERE lineItemType = :lineItemType' + values = [ + {'key': 'lineItemType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'SPONSORSHIP' + }}, + ] + # Create a statement to select product templates. statement = dfp.FilterStatement(query, values) - # Get product templates by statement. + # Retrieve a small amount of product templates at a time, paging + # through until all product templates have been retrieved. while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' was found.' % ( - product_template['id'], product_template['name'])) + # Print out some information for each product template. + print('Product template with ID "%d" and name "%s" was found.\n' % + (product_template['id'], product_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/product_template_service/update_product_templates.py b/examples/dfp/v201608/product_template_service/update_product_templates.py similarity index 98% rename from examples/dfp/v201508/product_template_service/update_product_templates.py rename to examples/dfp/v201608/product_template_service/update_product_templates.py index 1fcbba51..7201cc3c 100755 --- a/examples/dfp/v201508/product_template_service/update_product_templates.py +++ b/examples/dfp/v201608/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201508') + 'ProductTemplateService', version='v201608') # Create a statement to select a single product template by ID. values = [{ diff --git a/examples/dfp/v201508/proposal_line_item_service/__init__.py b/examples/dfp/v201608/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201508/proposal_line_item_service/__init__.py rename to examples/dfp/v201608/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201511/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py similarity index 98% rename from examples/dfp/v201511/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py index 3ff003ca..88401b33 100755 --- a/examples/dfp/v201511/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201511') + 'ProposalLineItemService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201508/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 76% rename from examples/dfp/v201508/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py index 71239483..7642027b 100755 --- a/examples/dfp/v201508/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,11 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates a new run-of-network proposal line item. - -To determine which proposal line items exist, run -get_all_proposal_line_items.py. To determine which proposals exist, run -get_all_proposals.py. +"""This code example creates a new programmatic proposal line item. """ @@ -28,28 +24,35 @@ # Import appropriate modules from the client library. from googleads import dfp -# Set proposal that the created proposal line item will belong to. +# Set the ID of the programmatic proposal that the proposal line item will +# belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' # Set the ID of the product that the proposal line items should be created from. PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' -# Set the ID of the rate card the proposal line items should be priced from. +# Set the ID of the Marketplace rate card the proposal line items should be +# priced from. RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201508') - network_service = client.GetService('NetworkService', version='v201508') + 'ProposalLineItemService', version='v201608') + network_service = client.GetService('NetworkService', version='v201608') # Get the root ad unit to target. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - # Create a single proposal line item. + # Create a single programmatic proposal line item. proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + # Setting common required fields for proposal line items. 'name': 'Proposal line item #%s' % uuid.uuid4(), 'rateCardId': rate_card_id, 'productId': product_id, @@ -82,33 +85,29 @@ def main(client, proposal_id, product_id, rate_card_id): 'second': '0', 'timeZoneID': 'America/Los_Angeles' }, - 'deliveryRateType': 'EVENLY', - 'creativeRotationType': 'OPTIMIZED', - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'THIRD_PARTY_VOLUME', 'goal': { 'units': '1000', 'unitType': 'IMPRESSIONS', }, - 'cost': { + 'netCost': { 'currencyCode': 'USD', 'microAmount': '2000000' }, - 'costPerUnit': { + 'netRate': { 'currencyCode': 'USD', 'microAmount': '2000000' }, 'rateType': 'CPM', } - # Add proposal line items. + # Add programmatic proposal line items. proposal_line_items = proposal_line_item_service.createProposalLineItems( [proposal_line_item]) # Display results. for proposal_line_item in proposal_line_items: - print ('Proposal line item with id \'%s\', belonging to proposal id \'%s\'' - ', and named \'%s\' was created.' % + print ('Programmatic proposal line item with id \'%s\', belonging to ' + 'proposal id \'%s\', and named \'%s\' was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py new file mode 100755 index 00000000..012ab4c5 --- /dev/null +++ b/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a programmatic proposal line item for non-sales management. +""" + + +from datetime import date +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set proposal that the created proposal line item will belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, proposal_id, product_id): + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201608') + network_service = client.GetService('NetworkService', version='v201608') + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single programmatic proposal line item. + proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for proposal line items. + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': { + 'date': { + 'year': str(date.today().year), + 'month': str(date.today().month), + 'day': str(date.today().day) + }, + 'hour': '23', + 'minute': '59', + 'second': '59' + }, + 'endDateTime': { + 'date': { + 'year': str(date.today().year + 1), + 'month': '9', + 'day': '30' + }, + 'hour': '0', + 'minute': '0', + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' + }, + 'creativePlaceholders': [{ + 'size': { + 'width': '300', + 'height': '250' + } + }, { + 'size': { + 'width': '120', + 'height': '600' + } + }], + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'netCost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'netRate': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Programmatic proposal line item for non-sales management with id ' + '\'%s\', belonging to proposal id \'%s\', and named \'%s\' ' + 'was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID, PRODUCT_ID) + diff --git a/examples/dfp/v201511/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py similarity index 97% rename from examples/dfp/v201511/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py index c8d78a2e..33f236d6 100755 --- a/examples/dfp/v201511/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py @@ -41,8 +41,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201511') - network_service = client.GetService('NetworkService', version='v201511') + 'ProposalLineItemService', version='v201608') + network_service = client.GetService('NetworkService', version='v201608') # Get the root ad unit to target. root_ad_unit_id = ( @@ -90,11 +90,11 @@ def main(client, proposal_id, product_id, rate_card_id): 'units': '1000', 'unitType': 'IMPRESSIONS', }, - 'cost': { + 'netCost': { 'currencyCode': 'USD', 'microAmount': '2000000' }, - 'costPerUnit': { + 'netRate': { 'currencyCode': 'USD', 'microAmount': '2000000' }, diff --git a/examples/dfp/v201511/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py similarity index 60% rename from examples/dfp/v201511/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py index 699cd596..439551e6 100755 --- a/examples/dfp/v201511/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all proposal line items. - -To create proposal line items, run create_proposal_line_items.py. +"""This example gets all proposal line items. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,23 +23,21 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201511') + 'ProposalLineItemService', version='v201608') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select proposal line items. + statement = dfp.FilterStatement() - # Get proposal line items by statement. + # Retrieve a small amount of proposal line items at a time, paging + # through until all proposal line items have been retrieved. while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for idx, proposal_line_item in enumerate(response['results'], - start=statement.offset): - print ('%s) Proposal line item with id \'%s\', belonging to proposal id' - ' \'%s\', and named \'%s\' was found.' % - (idx, proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + for proposal_line_item in response['results']: + # Print out some information for each proposal line item. + print('Proposal line item with ID "%d" and name "%s" was found.\n' % + (proposal_line_item['id'], proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 54% rename from examples/dfp/v201508/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 85881a87..c0c6d1bb 100755 --- a/examples/dfp/v201508/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,37 +13,40 @@ # 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 code example gets all proposal line items. - -To create proposal line items, run create_proposal_line_items.py. +"""This example gets all proposal line items belonging to a specific proposal. """ - # Import appropriate modules from the client library. from googleads import dfp +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' -def main(client): + +def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201508') - - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') - - # Get proposal line items by statement. + 'ProposalLineItemService', version='v201608') + query = 'WHERE proposalId = :proposalId' + values = [ + {'key': 'proposalId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + }}, + ] + # Create a statement to select proposal line items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of proposal line items at a time, paging + # through until all proposal line items have been retrieved. while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for idx, proposal_line_item in enumerate(response['results'], - start=statement.offset): - print ('%s) Proposal line item with id \'%s\', belonging to proposal id' - ' \'%s\', and named \'%s\' was found.' % - (idx, proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + for proposal_line_item in response['results']: + # Print out some information for each proposal line item. + print('Proposal line item with ID "%d" and name "%s" was found.\n' % + (proposal_line_item['id'], proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break @@ -54,4 +57,4 @@ def main(client): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py similarity index 94% rename from examples/dfp/v201508/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py index 691ffbd6..e4ad0ba7 100755 --- a/examples/dfp/v201508/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201508') + 'ProposalLineItemService', version='v201608') # Create statement to select a proposal line item. values = [{ @@ -52,7 +52,7 @@ def main(client, proposal_line_item_id): if 'results' in response: # Update each the proposal line item's notes field. proposal_line_item = response['results'][0] - proposal_line_item['notes'] = 'Proposal line item ready for submission.' + proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.' # Update proposal line items remotely. proposal_line_items = proposal_line_item_service.updateProposalLineItems( diff --git a/examples/dfp/v201508/proposal_service/__init__.py b/examples/dfp/v201608/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201508/proposal_service/__init__.py rename to examples/dfp/v201608/proposal_service/__init__.py diff --git a/examples/dfp/v201511/proposal_service/create_proposals.py b/examples/dfp/v201608/proposal_service/create_programmatic_proposals.py similarity index 62% rename from examples/dfp/v201511/proposal_service/create_proposals.py rename to examples/dfp/v201608/proposal_service/create_programmatic_proposals.py index b4dfa293..bb98fe3a 100755 --- a/examples/dfp/v201511/proposal_service/create_proposals.py +++ b/examples/dfp/v201608/proposal_service/create_programmatic_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,10 +14,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates new proposals. - -To determine which proposals exist, run get_all_proposals.py.""" - +"""This code example creates new programmatic proposals. +""" import uuid @@ -26,18 +24,22 @@ ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' +BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' -def main(client, advertiser_id, primary_salesperson_id, - secondary_salesperson_id, primary_trafficker_id): - # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201511') - network_service = client.GetService('NetworkService', version='v201511') +def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, + buyer_id): + proposal_service = client.GetService('ProposalService', version='v201608') + network_service = client.GetService('NetworkService', version='v201608') - # Create proposal objects. proposal = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'buyerAccountId': buyer_id + }, + 'isProgrammatic': True, + # Setting required common fields for Proposals. 'name': 'Proposal #%s' % uuid.uuid4(), 'advertiser': { 'companyId': advertiser_id, @@ -45,32 +47,25 @@ def main(client, advertiser_id, primary_salesperson_id, }, 'primarySalesperson': { 'userId': primary_salesperson_id, - 'split': '75000' + 'split': '100000' }, - 'secondarySalespeople': [{ - 'userId': secondary_salesperson_id, - 'split': '25000' - }], 'primaryTraffickerId': primary_trafficker_id, 'probabilityOfClose': '100000', 'budget': { 'microAmount': '100000000', 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] }, - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'DFP_VOLUME' } - - # Add proposals. - proposals = proposal_service.createProposals([proposals]) + proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: - print ('Proposal with id \'%s\' and name \'%s\' was created.' - % (proposal['id'], proposal['name'])) + print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + (proposal['id'], proposal['name'])) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) + main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID, + BUYER_ID) diff --git a/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py new file mode 100755 index 00000000..59b9d20e --- /dev/null +++ b/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a programmatic proposal for networks not using sales management. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' + + +def main(client, programmatic_buyer_id, primary_salesperson_id, + primary_trafficker_id): + proposal_service = client.GetService('ProposalService', version='v201608') + + proposal = { + # Setting required Marketplace information. + 'isProgrammatic': 'true', + 'marketplaceInfo': { + 'buyerAccountId': programmatic_buyer_id, + }, + # Set common required fields for proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '100000' + }, + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + } + + proposals = proposal_service.createProposals([proposals]) + + # Display results. + for proposal in proposals: + print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + (proposal['id'], proposal['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201508/proposal_service/create_proposals.py b/examples/dfp/v201608/proposal_service/create_proposals.py similarity index 96% rename from examples/dfp/v201508/proposal_service/create_proposals.py rename to examples/dfp/v201608/proposal_service/create_proposals.py index ef94b94f..56ec41bc 100755 --- a/examples/dfp/v201508/proposal_service/create_proposals.py +++ b/examples/dfp/v201608/proposal_service/create_proposals.py @@ -33,8 +33,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201508') - network_service = client.GetService('NetworkService', version='v201508') + proposal_service = client.GetService('ProposalService', version='v201608') + network_service = client.GetService('NetworkService', version='v201608') # Create proposal objects. proposal = { @@ -62,7 +62,7 @@ def main(client, advertiser_id, primary_salesperson_id, } # Add proposals. - proposals = proposal_service.createProposals([proposals]) + proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: diff --git a/examples/dfp/v201511/proposal_service/get_all_proposals.py b/examples/dfp/v201608/proposal_service/get_all_proposals.py similarity index 72% rename from examples/dfp/v201511/proposal_service/get_all_proposals.py rename to examples/dfp/v201608/proposal_service/get_all_proposals.py index 7763de74..fefa06a8 100755 --- a/examples/dfp/v201511/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201608/proposal_service/get_all_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,32 +13,29 @@ # 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 code example gets all proposals. - -To create proposals, run create_proposals.py. +"""This example gets all proposals. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201511') + proposal_service = client.GetService('ProposalService', version='v201608') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select proposals. + statement = dfp.FilterStatement() - # Get proposals by statement. + # Retrieve a small amount of proposals at a time, paging + # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\' and name \'%s\' was found.' % ( - proposal['id'], proposal['name'])) + # Print out some information for each proposal. + print('Proposal with ID "%d" and name "%s" was found.\n' % + (proposal['id'], proposal['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201608/proposal_service/get_marketplace_comments.py b/examples/dfp/v201608/proposal_service/get_marketplace_comments.py new file mode 100755 index 00000000..431f4409 --- /dev/null +++ b/examples/dfp/v201608/proposal_service/get_marketplace_comments.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the Marketplace comments for a programmatic proposal. +""" + +# Import appropriate modules from the client library. +from datetime import datetime + +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + marketplace_comment_service = client.GetService( + 'ProposalService', version='v201608') + query = 'WHERE proposal_id = :proposal_id' + values = [ + {'key': 'proposal_id', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + }} + ] + # Create a statement to select marketplace comments. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of marketplace comments at a time, paging + # through until all marketplace comments have been retrieved. + while True: + response = marketplace_comment_service.getMarketplaceCommentsByStatement( + statement.ToStatement()) + if 'results' in response: + for marketplace_comment in response['results']: + # Print out some information for each marketplace comment. + date_time = marketplace_comment['creationTime'] + date_time_string = datetime(date_time['date']['year'], + date_time['date']['month'], + date_time['date']['day'], date_time['hour'], + date_time['minute'], + date_time['second']).isoformat() + + print( + 'Marketplace comment with creation time "%s"and comment "%s" was ' + 'found.\n' + % (date_time_string, marketplace_comment['comment'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201508/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py similarity index 66% rename from examples/dfp/v201508/proposal_service/get_proposals_by_statement.py rename to examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py index 1dda0155..d798ca99 100755 --- a/examples/dfp/v201508/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,11 +13,8 @@ # 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 code example gets all proposals that are currently 'PENDING_APPROVAL.' - -To create proposals, run create_proposals.py.""" - +"""This example gets all proposals pending approval. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -25,28 +22,27 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201508') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - } - }] - query = 'WHERE status = :status ORDER BY id ASC' - + proposal_service = client.GetService('ProposalService', version='v201608') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PENDING_APPROVAL' + }}, + ] + # Create a statement to select proposals. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of proposals at a time, paging + # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\' name \'%s\' was found.' - % (proposal['id'], proposal['name'])) + # Print out some information for each proposal. + print('Proposal with ID "%d" and name "%s" was found.\n' % + (proposal['id'], proposal['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201608/proposal_service/request_buyers_acceptance.py similarity index 66% rename from examples/dfp/v201511/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201608/proposal_service/request_buyers_acceptance.py index 9ac06a60..d1600595 100755 --- a/examples/dfp/v201511/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201608/proposal_service/request_buyers_acceptance.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,9 +14,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example approves a single proposal. - -To determine which proposals exist, run get_all_proposals.py.""" +"""This code example requests buyer acceptance for a single proposal. +""" # Import appropriate modules from the client library. @@ -24,9 +23,10 @@ PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201511') + proposal_service = client.GetService('ProposalService', version='v201608') # Create query. values = [{ @@ -40,7 +40,7 @@ def main(client, proposal_id): # Create a filter statement. statement = dfp.FilterStatement(query, values) - proposals_approved = 0 + proposals_pushed_to_marketplace = 0 # Get proposals by statement. while True: @@ -48,23 +48,25 @@ def main(client, proposal_id): if 'results' in response: # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\', name \'%s\', and status \'%s\' will be' - ' approved.' % (proposal['id'], proposal['name'], - proposal['status'])) + print ('Programmatic proposal with id \'%s\', name \'%s\', and status ' + '\'%s\' will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( - {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) + {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: - proposals_approved += int(result['numChanges']) + proposals_pushed_to_marketplace += int(result['numChanges']) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break # Display results. - if proposals_approved > 0: - print '\nNumber of proposals approved: %s' % proposals_approved + if proposals_pushed_to_marketplace > 0: + print ('\nNumber of programmatic proposals pushed to Marketplace: %s' + % proposals_pushed_to_marketplace) else: - print '\nNo proposals were approved.' + print '\nNo programmatic proposals were pushed to Marketplace.' if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201508/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py similarity index 99% rename from examples/dfp/v201508/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py index 74d27fb8..8fae1df9 100755 --- a/examples/dfp/v201508/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py @@ -26,7 +26,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201508') + proposal_service = client.GetService('ProposalService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201508/proposal_service/update_proposals.py b/examples/dfp/v201608/proposal_service/update_proposals.py similarity index 93% rename from examples/dfp/v201508/proposal_service/update_proposals.py rename to examples/dfp/v201608/proposal_service/update_proposals.py index 40c0eb28..5bf73026 100755 --- a/examples/dfp/v201508/proposal_service/update_proposals.py +++ b/examples/dfp/v201608/proposal_service/update_proposals.py @@ -27,7 +27,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201508') + proposal_service = client.GetService('ProposalService', version='v201608') # Create statement object to select a single proposal by an ID. values = [{ @@ -48,7 +48,7 @@ def main(client, proposal_id): # Update each local proposal object by changing its notes. updated_proposals = [] for proposal in response['results']: - proposal['notes'] = 'Proposal needs further review before approval.' + proposal['internalNotes'] = 'Proposal needs review before approval.' updated_proposals.append(proposal) # Update proposals remotely. @@ -59,7 +59,7 @@ def main(client, proposal_id): for proposal in proposals: print ('Proposal with id \'%s\', name \'%s\', and ' 'notes \'%s\' was updated.' - % (proposal['id'], proposal['name'], proposal['notes'])) + % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: print 'No proposals were updated.' else: diff --git a/examples/dfp/v201508/publisher_query_language_service/__init__.py b/examples/dfp/v201608/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201508/publisher_query_language_service/__init__.py rename to examples/dfp/v201608/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201508/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201508/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py index 7c24da58..599ee25e 100755 --- a/examples/dfp/v201508/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201508') + report_downloader = client.GetDataDownloader(version='v201608') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201508/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 57% rename from examples/dfp/v201508/publisher_query_language_service/get_line_items_named_like.py rename to examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py index 3e698313..71299e31 100755 --- a/examples/dfp/v201508/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all line items with names starting with 'line item'.""" +"""This example fetches programmatic buyer information from the PQL table.""" import tempfile @@ -25,29 +25,22 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201508') + data_downloader = client.GetDataDownloader(version='v201608') - output_file = tempfile.NamedTemporaryFile( - prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) + programmatic_buyers_file = tempfile.NamedTemporaryFile( + prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) - # Create bind value to select line items with names starting with 'line item'. - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'line item%' - } - }] - - pql_query = ('SELECT Name, Id, Status FROM Line_Item ' - 'WHERE Name LIKE :name') + programmatic_buyers_query = ('SELECT BuyerAccountId, Name ' + 'FROM Programmatic_Buyer ' + 'ORDER BY BuyerAccountId ASC') # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - pql_query, output_file, values) - output_file.close() + data_downloader.DownloadPqlResultToCsv( + programmatic_buyers_query, programmatic_buyers_file) + + programmatic_buyers_file.close() - print ('Saved line items to... %s' % output_file.name) + print ('Saved programmatic buyers to... %s' % programmatic_buyers_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201508/rate_card_service/__init__.py b/examples/dfp/v201608/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201508/rate_card_service/__init__.py rename to examples/dfp/v201608/rate_card_service/__init__.py diff --git a/examples/dfp/v201511/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201608/rate_card_service/get_all_rate_cards.py similarity index 64% rename from examples/dfp/v201511/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201608/rate_card_service/get_all_rate_cards.py index 72252033..e9d4f15b 100755 --- a/examples/dfp/v201511/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201608/rate_card_service/get_all_rate_cards.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,31 @@ # 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 code example gets all rate cards. - +"""This example gets all rate cards. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201511') + rate_card_service = client.GetService('RateCardService', version='v201608') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select rate cards. + statement = dfp.FilterStatement() - # Get rate cards by statement. + # Retrieve a small amount of rate cards at a time, paging + # through until all rate cards have been retrieved. while True: - response = rate_card_service.getRateCardsByStatement( - statement.ToStatement()) + response = rate_card_service.getRateCardsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for rate_card in response['results']: - print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' - 'was found.' % (rate_card['id'], rate_card['name'], - rate_card['currencyCode'])) + # Print out some information for each rate card. + print('Rate card with ID "%d", name "%s", and currency code "%s" was ' + 'found.\n' % + (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py similarity index 58% rename from examples/dfp/v201508/rate_card_service/get_rate_cards_priced_with_currency.py rename to examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py index c2314783..9c0c9624 100755 --- a/examples/dfp/v201508/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,41 +14,39 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all rate cards that have a currency in US dollars. - +"""This example gets all rate cards that can be used for Marketplace products. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201508') - - # Create a statement to get all rate cards using USD as currency. - values = [{ - 'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'USD' - } - }] - query = 'WHERE currencyCode = :currencyCode' - + rate_card_service = client.GetService('RateCardService', version='v201608') + query = 'WHERE forMarketplace = :forMarketplace' + values = [ + {'key': 'forMarketplace', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select rate cards. statement = dfp.FilterStatement(query, values) - # Get rate cards by statement. + # Retrieve a small amount of rate cards at a time, paging + # through until all rate cards have been retrieved. while True: - response = rate_card_service.getRateCardsByStatement( - statement.ToStatement()) + response = rate_card_service.getRateCardsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for rate_card in response['results']: - print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' - 'was found.' % (rate_card['id'], rate_card['name'], - rate_card['currencyCode'])) + # Print out some information for each rate card. + print( + 'Rate card with ID "%d", name "%s", and currency code "%s" was ' + 'found.\n' + % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py new file mode 100755 index 00000000..aa1c8254 --- /dev/null +++ b/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -0,0 +1,73 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets a reconciliation report's data for line items that served through DFP. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_line_item_report_service = client.GetService( + 'ReconciliationLineItemReportService', version='v201608') + query = ('WHERE reconciliationReportId = :reconciliationReportId AND ' + 'lineItemId != :lineItemId') + values = [ + {'key': 'reconciliationReportId', + 'value': { + 'xsi_type': 'TextValue', + 'value': reconciliation_report_id + }}, + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + }}, + ] + # Create a statement to select reconciliation line item reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation line item reports at a time, + # paging through until all reconciliation line item reports have been + # retrieved. + while True: + response = reconciliation_line_item_report_service.getReconciliationLineItemReportsByStatement( + statement.ToStatement()) + if 'results' in response: + for reconciliation_line_item_report in response['results']: + # Print out some information for each reconciliation line item report. + print( + 'Reconciliation line item report with ID "%d", line item ID "%d", ' + 'reconciliation source "%s", and reconciled volume "%d" was ' + 'found.\n' % + (reconciliation_line_item_report['id'], + reconciliation_line_item_report['lineItemId'], + reconciliation_line_item_report['reconciliationSource'], + reconciliation_line_item_report['reconciledVolume'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py new file mode 100755 index 00000000..e350d000 --- /dev/null +++ b/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets all reconciliation order reports for a given reconciliation report. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_order_report_service = client.GetService( + 'ReconciliationOrderReportService', version='v201608') + query = 'WHERE reconciliationReportId = :reconciliationReportId' + values = [ + {'key': 'reconciliationReportId', + 'value': { + 'xsi_type': 'TextValue', + 'value': reconciliation_report_id + }}, + ] + # Create a statement to select reconciliation order reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation order reports at a time, paging + # through until all reconciliation order reports have been retrieved. + while True: + response = reconciliation_order_report_service.getReconciliationOrderReportsByStatement( + statement.ToStatement()) + if 'results' in response: + for reconciliation_order_report in response['results']: + # Print out some information for each reconciliation order report. + print('Reconciliation order report with ID "%d" and status "%s" was ' + 'found.\n' % (reconciliation_order_report['id'], + reconciliation_order_report['status'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py new file mode 100755 index 00000000..5cb21ae3 --- /dev/null +++ b/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets a reconciliation report's rows for line items that served through DFP. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_report_row_service = client.GetService( + 'ReconciliationReportRowService', version='v201608') + query = ('WHERE reconciliationReportId = :reconciliationReportId AND ' + 'lineItemId != :lineItemId') + values = [ + {'key': 'reconciliationReportId', + 'value': { + 'xsi_type': 'TextValue', + 'value': reconciliation_report_id + }}, + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + }}, + ] + # Create a statement to select reconciliation report rows. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation report rows at a time, paging + # through until all reconciliation report rows have been retrieved. + while True: + response = reconciliation_report_row_service.getReconciliationReportRowsByStatement( + statement.ToStatement()) + if 'results' in response: + for reconciliation_report_row in response['results']: + # Print out some information for each reconciliation report row. + print('Reconciliation report row with ID "%d", reconciliation source ' + '"%s", and reconciled volume "%d" was found.\n' % + (reconciliation_report_row['id'], + reconciliation_report_row['reconciliationSource'], + reconciliation_report_row['reconciledVolume'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201508/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 54% rename from examples/dfp/v201508/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py index a44b2596..7e33afe2 100755 --- a/examples/dfp/v201508/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,38 +13,34 @@ # 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 code example gets all audience segments. - -To create audience segments, run create_audience_segments.py. +"""This example gets all reconciliation reports. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201508') + reconciliation_report_service = client.GetService( + 'ReconciliationReportService', version='v201608') - # Create statement object to select all audience segments. + # Create a statement to select reconciliation reports. statement = dfp.FilterStatement() - # Get audience segments by statement. + # Retrieve a small amount of reconciliation reports at a time, paging + # through until all reconciliation reports have been retrieved. while True: - response = audience_segment_service.getAudienceSegmentsByStatement( + response = reconciliation_report_service.getReconciliationReportsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for segment in response['results']: - print ('Audience segment with id \'%s\' and name ' - '\'%s\' of size %s was found.' % - (segment['id'], segment['name'], segment['size'])) + for reconciliation_report in response['results']: + # Print out some information for each reconciliation report. + print( + 'Reconciliation report with ID "%d", month "%d", and year "%d" was' + ' found.\n' % (reconciliation_report['id'], + reconciliation_report['startDate']['month'], + reconciliation_report['startDate']['year'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py new file mode 100755 index 00000000..578c17b1 --- /dev/null +++ b/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the previous billing period's reconciliation report. +""" + +# Import appropriate modules from the client library. +from datetime import date +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + reconciliation_report_service = client.GetService( + 'ReconciliationReportService', version='v201608') + + first_of_the_month = date.today().replace(day=1) + last_month = first_of_the_month - timedelta(days=1) + + query = 'WHERE startDate = :startDate' + values = [ + {'key': 'startDate', + 'value': { + 'xsi_type': 'TextValue', + 'value': last_month.strftime('%Y-%m-01') + }}, + ] + # Create a statement to select reconciliation reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation reports at a time, paging + # through until all reconciliation reports have been retrieved. + while True: + response = reconciliation_report_service.getReconciliationReportsByStatement( + statement.ToStatement()) + if 'results' in response: + for reconciliation_report in response['results']: + # Print out some information for each reconciliation report. + print( + 'Reconciliation report with ID "%d" and start date "%d" was found.\n' + % (reconciliation_report['id'], last_month.strftime('%Y-%m-01'))) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201508/report_service/__init__.py b/examples/dfp/v201608/report_service/__init__.py similarity index 100% rename from examples/dfp/v201508/report_service/__init__.py rename to examples/dfp/v201608/report_service/__init__.py diff --git a/examples/dfp/v201511/report_service/run_delivery_report.py b/examples/dfp/v201608/report_service/run_delivery_report.py similarity index 97% rename from examples/dfp/v201511/report_service/run_delivery_report.py rename to examples/dfp/v201608/report_service/run_delivery_report.py index f8bf5fc5..f341a0bb 100755 --- a/examples/dfp/v201511/report_service/run_delivery_report.py +++ b/examples/dfp/v201608/report_service/run_delivery_report.py @@ -66,7 +66,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201511') + report_downloader = client.GetDataDownloader(version='v201608') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201511/report_service/run_inventory_report.py b/examples/dfp/v201608/report_service/run_inventory_report.py similarity index 97% rename from examples/dfp/v201511/report_service/run_inventory_report.py rename to examples/dfp/v201608/report_service/run_inventory_report.py index d6f304a2..7decb0e8 100755 --- a/examples/dfp/v201511/report_service/run_inventory_report.py +++ b/examples/dfp/v201608/report_service/run_inventory_report.py @@ -27,9 +27,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201511') + network_service = client.GetService('NetworkService', version='v201608') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201511') + report_downloader = client.GetDataDownloader(version='v201608') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201511/report_service/run_reach_report.py b/examples/dfp/v201608/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201511/report_service/run_reach_report.py rename to examples/dfp/v201608/report_service/run_reach_report.py index dfeef10a..0211681c 100755 --- a/examples/dfp/v201511/report_service/run_reach_report.py +++ b/examples/dfp/v201608/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201511') + report_downloader = client.GetDataDownloader(version='v201608') # Create report job. report_job = { diff --git a/examples/dfp/v201508/report_service/run_report_with_custom_fields.py b/examples/dfp/v201608/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/dfp/v201508/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201608/report_service/run_report_with_custom_fields.py index b955623a..56d735e3 100755 --- a/examples/dfp/v201508/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201608/report_service/run_report_with_custom_fields.py @@ -30,9 +30,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201508') + line_item_service = client.GetService('LineItemService', version='v201608') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201508') + report_downloader = client.GetDataDownloader(version='v201608') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201508/report_service/run_sales_report.py b/examples/dfp/v201608/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201508/report_service/run_sales_report.py rename to examples/dfp/v201608/report_service/run_sales_report.py index 304291e8..800aeb8c 100755 --- a/examples/dfp/v201508/report_service/run_sales_report.py +++ b/examples/dfp/v201608/report_service/run_sales_report.py @@ -26,7 +26,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201508') + report_downloader = client.GetDataDownloader(version='v201608') # Create report job. report_job = { diff --git a/examples/dfp/v201608/report_service/run_saved_query.py b/examples/dfp/v201608/report_service/run_saved_query.py new file mode 100755 index 00000000..3b8000d6 --- /dev/null +++ b/examples/dfp/v201608/report_service/run_saved_query.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 runs a report from a saved query. +""" + +# Import appropriate modules from the client library. +import tempfile + +from googleads import dfp +from googleads import errors + +SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' + + +def main(client, saved_query_id): + # Initialize appropriate service. + report_service = client.GetService('ReportService', version='v201608') + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201608') + + # Create statement object to filter for an order. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': saved_query_id + } + }] + filter_statement = {'query': 'WHERE id = :id', + 'values': values} + + response = report_service.getSavedQueriesByStatement( + filter_statement.ToStatement()) + + if 'results' in response: + saved_query = response['results'][0] + + if saved_query['isCompatibleWithApiVersion']: + report_job = {} + + # Set report query and optionally modify it. + report_job['reportQuery'] = saved_query['reportQuery'] + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id \'%s\' downloaded to:\n%s' % ( + report_job_id, report_file.name) + else: + print 'The query specified is not compatible with the API version.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, SAVED_QUERY_ID) diff --git a/examples/dfp/v201508/suggested_ad_unit_service/__init__.py b/examples/dfp/v201608/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201508/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201608/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201511/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/dfp/v201511/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py index ae8c83ff..4d1eac0c 100755 --- a/examples/dfp/v201511/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201511') + 'SuggestedAdUnitService', version='v201608') values = [{ 'key': 'numRequests', @@ -58,7 +58,7 @@ def main(client): # Approve suggested ad units. result = suggested_ad_unit_service.performSuggestedAdUnitAction( - {'xsi_type': 'ApproveSuggestedAdUnit'}, + {'xsi_type': 'ApproveSuggestedAdUnits'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: num_approved_suggested_ad_units += int(result['numChanges']) diff --git a/examples/dfp/v201508/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 69% rename from examples/dfp/v201508/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py index 26c76bef..17d32080 100755 --- a/examples/dfp/v201508/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all suggested ad units. - -To approve suggested ad units, run approve_suggested_ad_units.py. This feature -is only available to DFP premium solution networks. +"""This example gets all suggested ad units. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -28,26 +23,29 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201508') + 'SuggestedAdUnitService', version='v201608') - # Create a filter statement. + # Create a statement to select suggested ad units. statement = dfp.FilterStatement() - # Get suggested ad units by statement. + # Retrieve a small amount of suggested ad units at a time, paging + # through until all suggested ad units have been retrieved. while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for suggested_ad_unit in response['results']: - print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + # Print out some information for each suggested ad unit. + print( + 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' + % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 58% rename from examples/dfp/v201508/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py rename to examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index ed40b482..2f833695 100755 --- a/examples/dfp/v201508/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,51 +13,49 @@ # 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 code example gets suggested ad units that have more than 50 requests. - -This feature is only available to DFP premium solution networks. +"""This example gets all highly requested suggested ad units. """ - # Import appropriate modules from the client library. from googleads import dfp +NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE' + -def main(client): +def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201508') - - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '50' - } - }] - - query = 'WHERE numRequests > :numRequests' - - # Create a filter statement. + 'SuggestedAdUnitService', version='v201608') + query = 'WHERE numRequests >= :numRequests' + values = [ + {'key': 'numRequests', + 'value': { + 'xsi_type': 'TextValue', + 'value': num_requests + }}, + ] + # Create a statement to select suggested ad units. statement = dfp.FilterStatement(query, values) - # Get suggested ad units by statement. + # Retrieve a small amount of suggested ad units at a time, paging + # through until all suggested ad units have been retrieved. while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for suggested_ad_unit in response['results']: - print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + # Print out some information for each suggested ad unit. + print( + 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' + % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + main(dfp_client, NUM_REQUESTS) diff --git a/examples/dfp/v201508/team_service/__init__.py b/examples/dfp/v201608/team_service/__init__.py similarity index 100% rename from examples/dfp/v201508/team_service/__init__.py rename to examples/dfp/v201608/team_service/__init__.py diff --git a/examples/dfp/v201508/team_service/create_teams.py b/examples/dfp/v201608/team_service/create_teams.py similarity index 96% rename from examples/dfp/v201508/team_service/create_teams.py rename to examples/dfp/v201608/team_service/create_teams.py index 21ff0eaa..b15bdde4 100755 --- a/examples/dfp/v201508/team_service/create_teams.py +++ b/examples/dfp/v201608/team_service/create_teams.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201508') + team_service = client.GetService('TeamService', version='v201608') # Create team objects. teams = [] diff --git a/examples/dfp/v201508/team_service/get_all_teams.py b/examples/dfp/v201608/team_service/get_all_teams.py similarity index 67% rename from examples/dfp/v201508/team_service/get_all_teams.py rename to examples/dfp/v201608/team_service/get_all_teams.py index 0e9d2ac3..7f690498 100755 --- a/examples/dfp/v201508/team_service/get_all_teams.py +++ b/examples/dfp/v201608/team_service/get_all_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,44 +13,36 @@ # 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 teams. - -To create teams, run create_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201508') + team_service = client.GetService('TeamService', version='v201608') - # Create a filter statement. + # Create a statement to select teams. statement = dfp.FilterStatement() - # Get users by statement. + # Retrieve a small amount of teams at a time, paging + # through until all teams have been retrieved. while True: response = team_service.getTeamsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for team in response['results']: - print ('Team with ID \'%s\' and name \'%s\' was found.' - % (team['id'], team['name'])) + # Print out some information for each team. + print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], + team['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/team_service/update_teams.py b/examples/dfp/v201608/team_service/update_teams.py similarity index 73% rename from examples/dfp/v201508/team_service/update_teams.py rename to examples/dfp/v201608/team_service/update_teams.py index 08c3a134..8808b777 100755 --- a/examples/dfp/v201508/team_service/update_teams.py +++ b/examples/dfp/v201608/team_service/update_teams.py @@ -14,10 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates teams by adding an ad unit to a team. +"""This example updates teams by changing its description. -To determine which teams exist, run get_all_teams.py. To determine which ad -units exist, run get_all_ad_units.py +To determine which teams exist, run get_all_teams.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,13 +29,12 @@ # Import appropriate modules from the client library. from googleads import dfp -AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' TEAM_ID = 'INSERT_TEAM_ID_HERE' -def main(client, ad_unit_id, team_id): +def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201508') + team_service = client.GetService('TeamService', version='v201608') # Create a filter statement to select a single team by ID. values = [{ @@ -54,15 +52,9 @@ def main(client, ad_unit_id, team_id): if 'results' in response: updated_teams = [] - # Update each local team object by adding the ad unit to it. + # Update each local team object by changing its description. for team in response['results']: - ad_unit_ids = [] - if 'adUnitIds' in team: - ad_unit_ids = team['adUnitIds'] - # Don't add the ad unit if the team has all inventory already. - if not team['hasAllInventory']: - ad_unit_ids.append(ad_unit_id) - team['adUnitIds'] = ad_unit_ids + team['description'] = 'this team is great!' updated_teams.append(team) # Update teams on the server. @@ -78,4 +70,4 @@ def main(client, ad_unit_id, team_id): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AD_UNIT_ID, TEAM_ID) + main(dfp_client, TEAM_ID) diff --git a/examples/dfp/v201508/user_service/__init__.py b/examples/dfp/v201608/user_service/__init__.py similarity index 100% rename from examples/dfp/v201508/user_service/__init__.py rename to examples/dfp/v201608/user_service/__init__.py diff --git a/examples/dfp/v201508/user_service/create_users.py b/examples/dfp/v201608/user_service/create_users.py similarity index 94% rename from examples/dfp/v201508/user_service/create_users.py rename to examples/dfp/v201608/user_service/create_users.py index 36259c12..5bf833cf 100755 --- a/examples/dfp/v201508/user_service/create_users.py +++ b/examples/dfp/v201608/user_service/create_users.py @@ -28,14 +28,13 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201508') + user_service = client.GetService('UserService', version='v201608') # Create user objects. users = [ { 'email': email, 'name': name, - 'preferredLocale': 'en_US' } ] for user in users: diff --git a/examples/dfp/v201508/user_service/deactivate_users.py b/examples/dfp/v201608/user_service/deactivate_users.py similarity index 97% rename from examples/dfp/v201508/user_service/deactivate_users.py rename to examples/dfp/v201608/user_service/deactivate_users.py index 8bf631d6..8bb427dc 100755 --- a/examples/dfp/v201508/user_service/deactivate_users.py +++ b/examples/dfp/v201608/user_service/deactivate_users.py @@ -29,7 +29,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201508') + user_service = client.GetService('UserService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201508/user_service/get_all_roles.py b/examples/dfp/v201608/user_service/get_all_roles.py similarity index 70% rename from examples/dfp/v201508/user_service/get_all_roles.py rename to examples/dfp/v201608/user_service/get_all_roles.py index dd597127..03f79651 100755 --- a/examples/dfp/v201508/user_service/get_all_roles.py +++ b/examples/dfp/v201608/user_service/get_all_roles.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 code example gets all roles. - -This sample can be used to determine which role id is needed when getting and -creating users.""" - +"""This example gets all roles. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,18 +22,18 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201508') + user_service = client.GetService('UserService', version='v201605') - # Get all roles. roles = user_service.getAllRoles() - # Display results. + # Print out some information for each role. for role in roles: - print ('Role with id \'%s\' and name \'%s\' was found.' - % (role['id'], role['name'])) + print('Role with id \'%s\' and name \'%s\' was found.' % + (role['id'], role['name'])) print '\nNumber of results found: %s' % len(roles) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201508/user_service/get_all_users.py b/examples/dfp/v201608/user_service/get_all_users.py similarity index 70% rename from examples/dfp/v201508/user_service/get_all_users.py rename to examples/dfp/v201608/user_service/get_all_users.py index d00b47c3..5b915268 100755 --- a/examples/dfp/v201508/user_service/get_all_users.py +++ b/examples/dfp/v201608/user_service/get_all_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,9 +13,8 @@ # 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 code example gets all users. To create users, run create_users.py.""" - +"""This example gets all users. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -23,25 +22,27 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201508') + user_service = client.GetService('UserService', version='v201608') - # Create a filter statement. + # Create a statement to select users. statement = dfp.FilterStatement() - # Get users by statement. + # Retrieve a small amount of users at a time, paging + # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for user in response['results']: - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) + # Print out some information for each user. + print('User with ID "%d" and name "%s" was found.\n' % (user['id'], + user['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/user_service/get_all_users.py b/examples/dfp/v201608/user_service/get_user_by_email_address.py similarity index 56% rename from examples/dfp/v201511/user_service/get_all_users.py rename to examples/dfp/v201608/user_service/get_user_by_email_address.py index abdca1a0..d26e58c4 100755 --- a/examples/dfp/v201511/user_service/get_all_users.py +++ b/examples/dfp/v201608/user_service/get_user_by_email_address.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,36 +13,46 @@ # 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 code example gets all users. To create users, run create_users.py.""" - +"""This example gets users by email. +""" # Import appropriate modules from the client library. from googleads import dfp +EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201511') - - # Create a filter statement. - statement = dfp.FilterStatement() - # Get users by statement. +def main(client, email_address): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201608') + query = 'WHERE email = :email' + values = [ + {'key': 'email', + 'value': { + 'xsi_type': 'TextValue', + 'value': email_address + }}, + ] + # Create a statement to select users. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of users at a time, paging + # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for user in response['results']: - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) + # Print out some information for each user. + print('User with ID "%d" and name "%s" was found.\n' % (user['id'], + user['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + main(dfp_client, EMAIL_ADDRESS) diff --git a/examples/dfp/v201508/user_service/update_users.py b/examples/dfp/v201608/user_service/update_users.py similarity index 96% rename from examples/dfp/v201508/user_service/update_users.py rename to examples/dfp/v201608/user_service/update_users.py index edd8abdf..debc4b75 100755 --- a/examples/dfp/v201508/user_service/update_users.py +++ b/examples/dfp/v201608/user_service/update_users.py @@ -27,7 +27,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201508') + user_service = client.GetService('UserService', version='v201608') # Create query. values = [{ diff --git a/examples/dfp/v201508/user_team_association_service/__init__.py b/examples/dfp/v201608/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201508/user_team_association_service/__init__.py rename to examples/dfp/v201608/user_team_association_service/__init__.py diff --git a/examples/dfp/v201511/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201608/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201511/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201608/user_team_association_service/create_user_team_associations.py index e98d6a77..f917e63c 100755 --- a/examples/dfp/v201511/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201608/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201511') + 'UserTeamAssociationService', version='v201608') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201511/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py similarity index 98% rename from examples/dfp/v201511/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py index 7cca9b99..d29636e3 100755 --- a/examples/dfp/v201511/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201511') + 'UserTeamAssociationService', version='v201608') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201508/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py similarity index 63% rename from examples/dfp/v201508/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py index 3af4c74b..9b4ea627 100755 --- a/examples/dfp/v201508/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 user team associations. - -To create user team associations, run create_user_team_assocations.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,21 +23,22 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201508') + 'UserTeamAssociationService', version='v201608') - # Create a filter statement. + # Create a statement to select user team associations. statement = dfp.FilterStatement() - # Get user team associations by statement. + # Retrieve a small amount of user team associations at a time, paging + # through until all user team associations have been retrieved. while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for user_team_association in response['results']: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was found.' % (user_team_association['userId'], - user_team_association['teamId'])) + # Print out some information for each user team association. + print('User team association with team id "%d" and user id "%d" was ' + 'found.\n' % (user_team_association['teamId'], + user_team_association['userId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py similarity index 59% rename from examples/dfp/v201508/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py index f2706cc4..9df23eaa 100755 --- a/examples/dfp/v201508/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 user team associations for a single user. - -To determine which users exist, run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all user team associations (i.e. teams) for a given user. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -35,37 +25,36 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201508') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] + 'UserTeamAssociationService', version='v201608') query = 'WHERE userId = :userId' - - # Create a filter statement. + values = [ + {'key': 'userId', + 'value': { + 'xsi_type': 'TextValue', + 'value': user_id + }}, + ] + # Create a statement to select user team associations. statement = dfp.FilterStatement(query, values) - # Get user team associations by statement. + # Retrieve a small amount of user team associations at a time, paging + # through until all user team associations have been retrieved. while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for user_team_association in response['results']: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was found.' % (user_team_association['userId'], - user_team_association['teamId'])) + # Print out some information for each user team association. + print('User team association with user ID "%d" and team ID "%d" was ' + 'found.\n' % (user_team_association['userId'], + user_team_association['teamId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201511/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201608/user_team_association_service/update_user_team_associations.py similarity index 98% rename from examples/dfp/v201511/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201608/user_team_association_service/update_user_team_associations.py index d9863023..638782e1 100755 --- a/examples/dfp/v201511/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201608/user_team_association_service/update_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201511') + 'UserTeamAssociationService', version='v201608') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201508/workflow_request_service/__init__.py b/examples/dfp/v201608/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201508/workflow_request_service/__init__.py rename to examples/dfp/v201608/workflow_request_service/__init__.py diff --git a/examples/dfp/v201511/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py similarity index 97% rename from examples/dfp/v201511/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py index 99b8c2bb..958c0c09 100755 --- a/examples/dfp/v201511/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201511') + version='v201608') # Create query. values = [ diff --git a/examples/dfp/v201511/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py similarity index 62% rename from examples/dfp/v201511/workflow_request_service/get_workflow_approval_requests_by_statement.py rename to examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py index 415fdd06..5fc2332b 100755 --- a/examples/dfp/v201511/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,43 @@ # 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 workflow approval requests. Workflow approval requests must be approved or rejected for a workflow to finish. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201511') - - # Create statement object to select all workflow approval requests. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - }] + workflow_request_service = client.GetService( + 'WorkflowRequestService', version='v201608') query = 'WHERE type = :type' - + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_APPROVAL_REQUEST' + }}, + ] + # Create a statement to select workflow requests. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of workflow requests at a time, paging + # through until all workflow requests have been retrieved. while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for workflow_request in response['results']: - print ('Workflow approval request with id \'%s\' for %s with id \'%s\' ' - 'was found.' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + # Print out some information for each workflow request. + print('Workflow request with ID "%d", entity type "%s", and entity ID ' + '"%d" was found.\n' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201511/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py similarity index 61% rename from examples/dfp/v201511/workflow_request_service/get_workflow_external_condition_requests_by_statement.py rename to examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py index dd697d6d..aa7bbf25 100755 --- a/examples/dfp/v201511/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,43 @@ # 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 workflow external condition requests. -Workflow external condition requests must be triggered or skipped for a workflow -to finish. - +Workflow external condition requests must be triggered or skipped for a +workflow to finish. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201511') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - }] + workflow_request_service = client.GetService( + 'WorkflowRequestService', version='v201608') query = 'WHERE type = :type' - + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' + }}, + ] + # Create a statement to select workflow requests. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of workflow requests at a time, paging + # through until all workflow requests have been retrieved. while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id \'%s\' for %s ' - 'with id \'%s\' was found.' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + # Print out some information for each workflow request. + print('Workflow request with ID "%d", entity type "%s", and entity ID ' + '"%d" was found.\n' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201508/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 98% rename from examples/dfp/v201508/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py index 77cadbb7..bac97e0b 100755 --- a/examples/dfp/v201508/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201508') + version='v201608') # Create query. values = [ diff --git a/googleads/adwords.py b/googleads/adwords.py index 1e96ba9b..a383c7b1 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -336,8 +336,7 @@ def __init__( googleads.common.ProxyConfig()) self.report_download_headers = kwargs.get('report_download_headers', {}) - def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], - server=None): + def GetService(self, service_name, version=None, server=None): """Creates a service client for the given service. Args: @@ -358,24 +357,28 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], """ if not server: server = _DEFAULT_ENDPOINT + server = server.rstrip('/') + + if not version: + version = sorted(_SERVICE_MAP.keys())[-1] - if server[-1] == '/': server = server[:-1] try: - client = suds.client.Client( - self._SOAP_SERVICE_FORMAT % - (server, _SERVICE_MAP[version][service_name], version, service_name), - cache=self.cache, timeout=3600, - transport=self.proxy_config.GetSudsProxyTransport()) + version_service_mapping = _SERVICE_MAP[version][service_name] except KeyError: + msg_fmt = 'Unrecognized %s for the AdWords API. Given: %s Supported: %s' + if version in _SERVICE_MAP: raise googleads.errors.GoogleAdsValueError( - 'Unrecognized service for the AdWords API. Service given: %s ' - 'Supported services: %s' - % (service_name, _SERVICE_MAP[version].keys())) + msg_fmt % ('service', service_name, _SERVICE_MAP[version].keys())) else: raise googleads.errors.GoogleAdsValueError( - 'Unrecognized version of the AdWords API. Version given: %s ' - 'Supported versions: %s' % (version, _SERVICE_MAP.keys())) + msg_fmt % ('version', version, _SERVICE_MAP.keys())) + + client = suds.client.Client( + self._SOAP_SERVICE_FORMAT % + (server, version_service_mapping, version, service_name), + cache=self.cache, timeout=3600, + transport=self.proxy_config.GetSudsProxyTransport()) return googleads.common.SudsServiceProxy( client, _AdWordsHeaderHandler(self, version)) @@ -401,7 +404,7 @@ def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], server = _DEFAULT_ENDPOINT request_builder = BatchJobHelper.GetRequestBuilder( - client=self, version=version, server=server) + self, version=version, server=server) response_parser = BatchJobHelper.GetResponseParser() return BatchJobHelper(request_builder, response_parser, version=version) @@ -444,8 +447,8 @@ class _AdWordsHeaderHandler(googleads.common.HeaderHandler): _LIB_SIG = googleads.common.GenerateLibSig('AwApi-Python') # The name of the WSDL-defined SOAP Header class used in all SOAP requests. # The namespace needs the version of AdWords being used to be templated in. - _SOAP_HEADER_CLASS = ('{https://adwords.google.com/api/adwords/cm/%s}' - 'SoapHeader') + _SOAP_HEADER_CLASS = ( + '{https://adwords.google.com/api/adwords/cm/%s}SoapHeader') # The content type of report download requests _CONTENT_TYPE = 'application/x-www-form-urlencoded' @@ -463,7 +466,11 @@ def __init__(self, adwords_client, version): self._version = version def SetHeaders(self, suds_client): - """Sets the SOAP and HTTP headers on the given suds client.""" + """Sets the SOAP and HTTP headers on the given suds client. + + Args: + suds_client: An initialized suds.client.Client. + """ header = suds_client.factory.create(self._SOAP_HEADER_CLASS % self._version) header.clientCustomerId = self._adwords_client.client_customer_id header.developerToken = self._adwords_client.developer_token @@ -503,6 +510,10 @@ def GetReportDownloadHeaders(self, **kwargs): Returns: A dictionary containing the headers configured for downloading a report. + + Raises: + GoogleAdsValueError: If one or more of the report header keyword arguments + is invalid. """ headers = self._adwords_client.oauth2_client.CreateHttpHeader() headers.update({ @@ -519,7 +530,7 @@ def GetReportDownloadHeaders(self, **kwargs): for kw in updated_kwargs: try: - headers.update({_REPORT_HEADER_KWARGS[kw]: str(updated_kwargs[kw])}) + headers[_REPORT_HEADER_KWARGS[kw]] = str(updated_kwargs[kw]) except KeyError: raise googleads.errors.GoogleAdsValueError( 'The provided keyword "%s" is invalid. Accepted keywords are: %s' @@ -542,8 +553,7 @@ def ParseResponse(self, batch_job_response): batch_job_response: a str containing the response from the BatchJobService. """ - raise NotImplementedError('You must subclass' - 'AbstractResponseParser.') + raise NotImplementedError('You must implement ParseResponse().') class _XMLToDictResponseParser(AbstractResponseParser): """Parses responses from the BatchJobService, returning as a dictionary.""" @@ -576,8 +586,7 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): A urllib2.Request instance with the correct method, headers, and padding (if required) for the batch job upload. """ - raise NotImplementedError('You must subclass' - 'AbstractUploadRequestBuilder.') + raise NotImplementedError('You must implement BuildUploadRequest().') class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): """Builds requests used to upload operations for Batch Jobs.""" @@ -589,49 +598,50 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): _UPLOAD_SUFFIX = '' # Incremental uploads must have a content-length that is a multiple of this. _BATCH_JOB_INCREMENT = 262144 - # Generate a mapping of Operations to their service and methods. + _OPERATION = namedtuple('Operation', + ['operation_type', 'service', 'method']) _OPERATION_MAP = { - op[0]: namedtuple('Operation', ['operation_type', 'service', 'method']) - (op[0], op[1], op[2]) - for op in ( - ('AdGroupAdOperation', 'AdGroupAdService', 'mutate'), - ('AdGroupAdLabelOperation', 'AdGroupAdService', 'mutateLabel'), - ('AdGroupBidModifierOperation', 'AdGroupBidModifierService', - 'mutate'), - ('AdGroupCriterionOperation', 'AdGroupCriterionService', - 'mutate'), - ('AdGroupCriterionLabelOperation', 'AdGroupCriterionService', - 'mutateLabel'), - ('AdGroupOperation', 'AdGroupService', 'mutate'), - ('AdGroupLabelOperation', 'AdGroupService', 'mutateLabel'), - ('BudgetOperation', 'BudgetService', 'mutate'), - ('CampaignCriterionOperation', 'CampaignCriterionService', - 'mutate'), - ('CampaignOperation', 'CampaignService', 'mutate'), - ('CampaignLabelOperation', 'CampaignService', 'mutateLabel'), - ('FeedItemOperation', 'FeedItemService', 'mutate') - ) + 'AdGroupAdOperation': _OPERATION('AdGroupAdOperation', + 'AdGroupAdService', 'mutate'), + 'AdGroupAdLabelOperation': _OPERATION( + 'AdGroupAdLabelOperation', 'AdGroupAdService', 'mutateLabel'), + 'AdGroupBidModifierOperation': _OPERATION( + 'AdGroupBidModifierOperation', 'AdGroupBidModifierService', + 'mutate'), + 'AdGroupCriterionOperation': _OPERATION( + 'AdGroupCriterionOperation', 'AdGroupCriterionService', 'mutate'), + 'AdGroupCriterionLabelOperation': _OPERATION( + 'AdGroupCriterionLabelOperation', 'AdGroupCriterionService', + 'mutateLabel'), + 'AdGroupOperation': _OPERATION('AdGroupOperation', 'AdGroupService', + 'mutate'), + 'AdGroupLabelOperation': _OPERATION('AdGroupLabelOperation', + 'AdGroupService', 'mutateLabel'), + 'BudgetOperation': _OPERATION('BudgetOperation', 'BudgetService', + 'mutate'), + 'CampaignCriterionOperation': _OPERATION( + 'CampaignCriterionOperation', 'CampaignCriterionService', 'mutate'), + 'CampaignOperation': _OPERATION('CampaignOperation', + 'CampaignService', 'mutate'), + 'CampaignLabelOperation': _OPERATION('CampaignLabelOperation', + 'CampaignService', 'mutateLabel'), + 'FeedItemOperation': _OPERATION('FeedItemOperation', 'FeedItemService', + 'mutate') } - def __init__(self, **kwargs): + def __init__(self, client, **kwargs): """Initializes a _SudsUploadRequestBuilder. Arguments: + client: an AdWordsClient instance. **kwargs: Keyword arguments. Keyword Arguments: - client: an AdWordsClient instance. version: a string identifying the AdWords version to connect to. server: a string identifying the webserver hosting the AdWords API. - - Raises: - AttributeError: if no client is specified in the Keyword Arguments. """ - if 'client' not in kwargs: - raise AttributeError('No client specified for Request Builder.') - + self.client = client self._version = kwargs.get('version', sorted(_SERVICE_MAP.keys())[-1]) - self.client = kwargs['client'] server = kwargs.get('server', _DEFAULT_ENDPOINT) self._adwords_endpoint = ('%s/api/adwords/cm/%s' % (server, self._version)) @@ -783,12 +793,11 @@ def _GenerateOperationsXML(self, operations): Raises: GoogleAdsValueError: if no xsi_type is specified for the operations. """ - if operations: # Verify that all operations included specify an xsi_type. - for operation in operations: - if 'xsi_type' not in operation: - raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( - 'Operations have no xsi_type specified.') + if operations: + if any('xsi_type' not in operation for operation in operations): + raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( + 'Operations have no xsi_type specified.') return self._ExtractOperations(self._GenerateRawRequestXML(operations)) else: return '' @@ -803,12 +812,11 @@ def _GenerateRawRequestXML(self, operations): Returns: A str containing the raw XML of the request to the given service that would execute the given operations. + + Raises: + KeyError: If the given operation type is not supported. """ - try: - operation = self._OPERATION_MAP[operations[0]['xsi_type']] - except KeyError, e: - raise googleads.errors.GoogleAdsValueError('"%s" is an unsupported ' - 'operation.' % e.message) + operation = self._OPERATION_MAP[operations[0]['xsi_type']] service = self.client.GetService(operation.service, self._version) service.suds_client.set_options(nosend=True) service_request = (getattr(service, operation.method) @@ -882,14 +890,14 @@ def GetIncrementalUploadHelper(self, upload_url, current_content_length=0): version=self._version) @classmethod - def GetRequestBuilder(cls, **kwargs): + def GetRequestBuilder(cls, *args, **kwargs): """Get a new AbstractUploadRequestBuilder instance.""" - return cls._SudsUploadRequestBuilder(**kwargs) + return cls._SudsUploadRequestBuilder(*args, **kwargs) @classmethod - def GetResponseParser(cls, **kwargs): + def GetResponseParser(cls, *args, **kwargs): """Get a new AbstractResponseParser instance.""" - return cls._XMLToDictResponseParser(**kwargs) + return cls._XMLToDictResponseParser(*args, **kwargs) def ParseResponse(self, batch_job_response): """Parses a Batch Job Service response and returns it as a suds object. @@ -933,7 +941,8 @@ def Load(cls, file_input, client=None): Args: file_input: a file-like object containing a serialized IncrementalUploadHelper. - client: an AdWordsClient instance. + client: an AdWordsClient instance. If not specified, an AdWordsClient will + be instantiated using the default configuration file. Returns: An IncrementalUploadHelper instance initialized using the contents of the @@ -950,21 +959,22 @@ def Load(cls, file_input, client=None): try: data = yaml.safe_load(file_input) - except yaml.YAMLError: + except yaml.YAMLError as e: raise googleads.errors.GoogleAdsError( - 'Error loading IncrementalUploadHelper from file.') + 'Error loading IncrementalUploadHelper from file: %s' % str(e)) batch_job_helper = client.GetBatchJobHelper(version=data['version']) request_builder = batch_job_helper.GetRequestBuilder( - client=client, version=data['version']) + client, version=data['version']) try: return cls(request_builder, data['upload_url'], current_content_length=data['current_content_length'], is_last=data['is_last'], version=data['version']) - except KeyError: + except KeyError as e: raise googleads.errors.GoogleAdsValueError( - 'Can\'t parse IncrementalUploadHelper from file.') + 'Can\'t parse IncrementalUploadHelper from file. Required field ' + '"%s" is missing.' % e.message) def __init__(self, request_builder, upload_url, current_content_length=0, is_last=False, version=sorted(_SERVICE_MAP.keys())[-1]): @@ -1010,8 +1020,7 @@ def _InitializeURL(self, upload_url, current_content_length): already been initialized or the version is below v201601. """ # If initialization is not necessary, return the provided upload_url. - if (self._version < 'v201601' - or current_content_length != 0): + if self._version < 'v201601' or current_content_length != 0: return upload_url headers = { @@ -1045,9 +1054,9 @@ def Dump(self, output): try: yaml.dump(data, output) - except yaml.YAMLError: + except yaml.YAMLError as e: raise googleads.errors.GoogleAdsError( - 'Error dumping IncrementalUploadHelper to file.') + 'Error dumping IncrementalUploadHelper to file: %s' % str(e)) def UploadOperations(self, operations, is_last=False): """Uploads operations to the given uploadUrl in incremental steps. @@ -1062,7 +1071,7 @@ def UploadOperations(self, operations, is_last=False): is_last: a boolean indicating whether this is the final increment to be added to the batch job. """ - if self._is_last is True: + if self._is_last: raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( 'Can\'t add new operations to a completed incremental upload.') # Build the request @@ -1073,7 +1082,7 @@ def UploadOperations(self, operations, is_last=False): # code 308 (for resumable uploads). try: self._url_opener.open(req) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if e.code != 308: raise urllib2.HTTPError(e) # Update upload status. @@ -1119,7 +1128,7 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], if not server: server = _DEFAULT_ENDPOINT - if server[-1] == '/': server = server[:-1] + server = server.rstrip('/') self._adwords_client = adwords_client self._namespace = self._NAMESPACE_FORMAT % version self._end_point = self._END_POINT_FORMAT % (server, version) @@ -1139,9 +1148,9 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], self._marshaller = suds.mx.literal.Literal(schema) def _DownloadReportCheckFormat(self, file_format, output): - if(file_format.startswith('GZIPPED_') - and not (('b' in getattr(output, 'mode', 'w')) or - type(output) is io.BytesIO)): + is_binary_mode = getattr(output, 'mode', 'w') == 'wb' + if (file_format.startswith('GZIPPED_') + and not (is_binary_mode or type(output) is io.BytesIO)): raise googleads.errors.GoogleAdsValueError('Need to specify a binary' ' output for GZIPPED formats.') @@ -1509,7 +1518,7 @@ def _DownloadReportAsStream(self, post_body, **kwargs): self._header_handler.GetReportDownloadHeaders(**kwargs)) try: return self.url_opener.open(request) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: raise self._ExtractError(e) def _SerializeAwql(self, query, file_format): diff --git a/googleads/common.py b/googleads/common.py index 9467cb24..262887be 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -43,7 +43,7 @@ pass -VERSION = '4.3.0' +VERSION = '4.4.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' diff --git a/googleads/dfp.py b/googleads/dfp.py index 284257d2..caa85889 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -39,7 +39,7 @@ _CHUNK_SIZE = 16 * 1024 # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201505': + 'v201508': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -56,10 +56,11 @@ 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', + 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201508': + 'v201511': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -80,7 +81,7 @@ 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201511': + 'v201602': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -98,10 +99,10 @@ 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', + 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201602': + 'v201605': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -122,7 +123,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201605': + 'v201608': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -216,9 +217,9 @@ def __init__(self, oauth2_client, application_name, network_code=None, proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. """ - if application_name is DEFAULT_APPLICATION_NAME: + if not application_name or (DEFAULT_APPLICATION_NAME in application_name): raise googleads.errors.GoogleAdsValueError( - 'Application name must be set and not be the default [%s]' % + 'Application name must be set and not contain the default [%s]' % DEFAULT_APPLICATION_NAME) self.oauth2_client = oauth2_client diff --git a/tests/adwords_test.py b/tests/adwords_test.py index eb34b2fe..cf49c44e 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -38,27 +38,48 @@ CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] -def GetAdWordsClient(proxy_config=None): +def GetAdWordsClient(**kwargs): """Returns an initialized AdwordsClient for use in testing. + If not specified, the keyword arguments will be set to default test values. + Args: - proxy_config: A googleads.common.ProxyConfig or None if no proxy is being - used. + **kwargs: Optional keyword arguments that can be provided to customize the + generated AdWordsClient. + Keyword Arguments: + ccid: A str value for the AdWordsClient's client_customer_id. + dev_token: A str value for the AdWordsClient's developer_token. + oauth2_client: A GoogleOAuth2Client instance or mock implementing its + interface. + proxy_config: A googleads.common.ProxyConfig instance. If not specified, + this will default to None to specify that no Proxy is being used. + report_downloader_headers: A dict containing optional report downloader + headers. + user_agent: A str value for the AdWordsClient's user_agent. Returns: - An AdWordsClient instance with or without a proxy configured depending on - whether a ProxyConfig instance was provided. + An AdWordsClient instance intended for testing. """ - oauth_header = {'Authorization': 'header'} - client_customer_id = 'client customer id' - dev_token = 'N3v3rG0nN4Giv3Y0uUp' - user_agent = 'N3v3rG0nN4l37y0uDoWN' - oauth2_client = mock.Mock() - oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) + client_customer_id = kwargs.get('ccid', 'client customer id') + dev_token = kwargs.get('dev_token', 'dev_token') + user_agent = kwargs.get('user_agent', 'user_agent') + validate_only = kwargs.get('validate_only', False) + partial_failure = kwargs.get('partial_failure', False) + report_downloader_headers = kwargs.get('report_downloader_headers', {}) + + if 'oauth2_client' in kwargs: + oauth2_client = kwargs['oauth2_client'] + else: + oauth_header = {'Authorization': 'header'} + oauth2_client = mock.Mock() + oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) client = googleads.adwords.AdWordsClient( dev_token, oauth2_client, user_agent, - client_customer_id=client_customer_id, proxy_config=proxy_config) + client_customer_id=client_customer_id, + proxy_config=kwargs.get('proxy_config'), + validate_only=validate_only, partial_failure=partial_failure, + report_downloader_headers=report_downloader_headers) return client @@ -69,9 +90,13 @@ def GetProxyConfig(http_host=None, http_port=None, https_host=None, """Returns an initialized ProxyConfig for use in testing. Args: - http_host: A str containing the url or IP of an http proxy host. + http_host: A str containing the url or IP of an http proxy host. If this is + not specified, the ProxyConfig will be initialized without an HTTP proxy + configured. http_port: An int port number for the HTTP proxy host. - https_host: A str containing the url or IP of an https proxy host. + https_host: A str containing the url or IP of an https proxy host. If this + is not specified, the ProxyConfig will be initialized without an HTTPS + proxy configured. https_port: An int port number for the HTTPS proxy host. cafile: A str containing the path to a custom ca file. disable_certificate_validation: A boolean indicating whether or not to @@ -98,74 +123,60 @@ class AdWordsHeaderHandlerTest(unittest.TestCase): """Tests for the googleads.adwords._AdWordsHeaderHandler class.""" def setUp(self): - self.aw_client = mock.Mock() - self.aw_client.report_download_headers = {} + self.report_downloader_headers = {} + self.oauth2_client = mock.Mock() + self.oauth_header = {'Authorization': 'header'} + self.oauth2_client.CreateHttpHeader.return_value = self.oauth_header + self.ccid = 'client customer id' + self.dev_token = 'developer token' + self.user_agent = 'user agent!' + self.validate_only = True + self.partial_failure = False + self.aw_client = GetAdWordsClient( + ccid=self.ccid, dev_token=self.dev_token, user_agent=self.user_agent, + oauth2_client=self.oauth2_client, validate_only=self.validate_only, + partial_failure=self.partial_failure, + report_downloader_headers=self.report_downloader_headers) self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.aw_client, CURRENT_VERSION) def testSetHeaders(self): suds_client = mock.Mock() - ccid = 'client customer id' - dev_token = 'developer token' - user_agent = 'user agent!' - validate_only = True - partial_failure = False - oauth_header = {'oauth': 'header'} - self.aw_client.client_customer_id = ccid - self.aw_client.developer_token = dev_token - self.aw_client.user_agent = user_agent - self.aw_client.validate_only = validate_only - self.aw_client.partial_failure = partial_failure - self.aw_client.oauth2_client.CreateHttpHeader.return_value = (oauth_header) - self.header_handler.SetHeaders(suds_client) - # Check that the SOAP header has the correct values. suds_client.factory.create.assert_called_once_with( '{https://adwords.google.com/api/adwords/cm/%s}SoapHeader' % CURRENT_VERSION) soap_header = suds_client.factory.create.return_value - self.assertEqual(ccid, soap_header.clientCustomerId) - self.assertEqual(dev_token, soap_header.developerToken) + self.assertEqual(self.ccid, soap_header.clientCustomerId) + self.assertEqual(self.dev_token, soap_header.developerToken) self.assertEqual( - ''.join([user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG]), + ''.join([self.user_agent, + googleads.adwords._AdWordsHeaderHandler._LIB_SIG]), soap_header.userAgent) - self.assertEqual(validate_only, soap_header.validateOnly) - self.assertEqual(partial_failure, soap_header.partialFailure) - + self.assertEqual(self.validate_only, soap_header.validateOnly) + self.assertEqual(self.partial_failure, soap_header.partialFailure) # Check that the suds client has the correct values. suds_client.set_options.assert_any_call( - soapheaders=soap_header, headers=oauth_header) + soapheaders=soap_header, headers=self.oauth_header) def testGetReportDownloadHeadersOverrideDefaults(self): - ccid = 'client customer id' - dev_token = 'developer token' - user_agent = 'user agent!' - oauth_header = {'Authorization': 'header'} - self.aw_client.client_customer_id = ccid - self.aw_client.developer_token = dev_token - self.aw_client.user_agent = user_agent - self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( - oauth_header) self.aw_client.report_downloader_headers = { 'skip_report_header': True, 'skip_column_header': False, 'skip_report_summary': False, 'use_raw_enum_values': True} expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', - 'developerToken': dev_token, - 'clientCustomerId': ccid, + 'developerToken': self.dev_token, + 'clientCustomerId': self.ccid, 'Authorization': 'header', 'User-Agent': ''.join([ - user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + self.user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, ',gzip']), 'skipReportHeader': 'False', 'skipColumnHeader': 'True', 'skipReportSummary': 'False', 'useRawEnumValues': 'True' } - - self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( - oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( skip_report_header=False, @@ -174,67 +185,39 @@ def testGetReportDownloadHeadersOverrideDefaults(self): use_raw_enum_values=True)) def testGetReportDownloadHeadersWithDefaultsFromConfig(self): - ccid = 'client customer id' - dev_token = 'developer token' - user_agent = 'user agent!' - oauth_header = {'Authorization': 'header'} - self.aw_client.client_customer_id = ccid - self.aw_client.developer_token = dev_token - self.aw_client.user_agent = user_agent - self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( - oauth_header) self.aw_client.report_download_headers = { 'skip_report_header': True, 'skip_column_header': False, 'skip_report_summary': False, 'use_raw_enum_values': True} expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', - 'developerToken': dev_token, - 'clientCustomerId': ccid, + 'developerToken': self.dev_token, + 'clientCustomerId': self.ccid, 'Authorization': 'header', 'User-Agent': ''.join([ - user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + self.user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, ',gzip']), 'skipReportHeader': 'True', 'skipColumnHeader': 'False', 'skipReportSummary': 'False', 'useRawEnumValues': 'True' } - - self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( - oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders()) def testGetReportDownloadHeadersWithInvalidKeyword(self): - ccid = 'client customer id' - dev_token = 'developer token' - user_agent = 'user agent!' - self.aw_client.client_customer_id = ccid - self.aw_client.developer_token = dev_token - self.aw_client.user_agent = user_agent - self.assertRaises( googleads.errors.GoogleAdsValueError, self.header_handler.GetReportDownloadHeaders, invalid_key_word=True) def testGetReportDownloadHeadersWithKeywordArguments(self): - original_ccid = 'client customer id' updated_ccid = 'updated client customer id' - dev_token = 'developer token' - user_agent = 'user agent!' - oauth_header = {'Authorization': 'header'} - self.aw_client.client_customer_id = original_ccid - self.aw_client.developer_token = dev_token - self.aw_client.user_agent = user_agent - self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( - oauth_header) expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', - 'developerToken': dev_token, + 'developerToken': self.dev_token, 'clientCustomerId': updated_ccid, 'Authorization': 'header', 'User-Agent': ''.join([ - user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + self.user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, ',gzip']), 'skipReportHeader': 'True', 'skipColumnHeader': 'True', @@ -242,9 +225,6 @@ def testGetReportDownloadHeadersWithKeywordArguments(self): 'includeZeroImpressions': 'True', 'useRawEnumValues': 'True' } - - self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( - oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders( skip_report_header=True, @@ -255,27 +235,15 @@ def testGetReportDownloadHeadersWithKeywordArguments(self): client_customer_id=updated_ccid)) def testGetReportDownloadHeadersWithNoOptionalHeaders(self): - ccid = 'client customer id' - dev_token = 'developer token' - user_agent = 'user agent!' - oauth_header = {'Authorization': 'header'} - self.aw_client.client_customer_id = ccid - self.aw_client.developer_token = dev_token - self.aw_client.user_agent = user_agent - self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( - oauth_header) expected_return_value = { 'Content-type': 'application/x-www-form-urlencoded', - 'developerToken': dev_token, - 'clientCustomerId': ccid, + 'developerToken': self.dev_token, + 'clientCustomerId': self.ccid, 'Authorization': 'header', 'User-Agent': ''.join([ - user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + self.user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, ',gzip']) } - - self.aw_client.oauth2_client.CreateHttpHeader.return_value = dict( - oauth_header) self.assertEqual(expected_return_value, self.header_handler.GetReportDownloadHeaders()) @@ -739,7 +707,7 @@ def testGenerateRawRequestXMLFromBogusOperation(self): 'bogusProperty': 'bogusValue'} }] - self.assertRaises(googleads.errors.GoogleAdsValueError, + self.assertRaises(KeyError, self.request_builder._GenerateRawRequestXML, bogus_operations) diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 91271fd5..9f3791b2 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -173,6 +173,13 @@ def testInitializeWithDefaultApplicationName(self): self.oauth2_client, self.application_name, self.network_code, self.https_proxy, self.cache) + def testInitializeWithUselessApplicationName(self): + self.application_name = 'try_to_trick_me_INSERT_APPLICATION_NAME_HERE' + self.assertRaises( + googleads.errors.GoogleAdsValueError, googleads.dfp.DfpClient, + self.oauth2_client, self.application_name, self.network_code, + self.https_proxy, self.cache) + def testGetService_success(self): service = googleads.dfp._SERVICE_MAP[self.version][0] From 25a2ce24aaa862d99d9596f344cc1a75f3b0911a Mon Sep 17 00:00:00 2001 From: Nicholas Chen Date: Tue, 23 Aug 2016 14:29:50 -0400 Subject: [PATCH 045/180] Commiting latest changes. From 2004599b89772761f15a7424be3c299bc0698b9b Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 26 Aug 2016 18:27:06 -0400 Subject: [PATCH 046/180] Removing support for AdWords v201601. --- ChangeLog | 6 + ...ate_adwords_client_with_service_account.py | 3 +- .../create_adwords_client_without_yaml.py | 3 +- examples/adwords/v201601/__init__.py | 15 - .../v201601/account_management/__init__.py | 15 - .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 103 ---- .../get_account_hierarchy.py | 104 ---- .../v201601/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 222 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 108 ---- .../advanced_operations/add_html5_ad.py | 111 ---- .../add_text_ad_with_upgraded_urls.py | 111 ---- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 172 ------ .../v201601/basic_operations/__init__.py | 15 - .../v201601/basic_operations/add_ad_groups.py | 115 ---- .../v201601/basic_operations/add_campaigns.py | 126 ----- .../v201601/basic_operations/add_keywords.py | 92 --- .../v201601/basic_operations/add_text_ads.py | 93 ---- .../v201601/basic_operations/get_ad_groups.py | 76 --- .../v201601/basic_operations/get_campaigns.py | 74 --- .../get_campaigns_with_awql.py | 64 --- .../v201601/basic_operations/get_keywords.py | 87 --- .../v201601/basic_operations/get_text_ads.py | 80 --- .../v201601/basic_operations/pause_ad.py | 61 -- .../v201601/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 58 -- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201601/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 427 -------------- .../campaign_management/add_experiment.py | 127 ----- .../add_keywords_in_bulk.py | 134 ----- ...dd_keywords_using_incremental_batch_job.py | 259 --------- .../get_all_disapproved_ads.py | 74 --- .../get_all_disapproved_ads_with_awql.py | 63 --- .../get_campaigns_by_label.py | 85 --- .../campaign_management/promote_experiment.py | 60 -- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201601/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 120 ---- .../handle_policy_violation_error.py | 114 ---- .../adwords/v201601/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 ------ .../v201601/extensions/add_site_links.py | 124 ----- .../extensions/add_site_links_using_feeds.py | 233 -------- .../adwords/v201601/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 ------------------ .../v201601/migration/upgrade_ad_url.py | 79 --- examples/adwords/v201601/misc/__init__.py | 15 - .../v201601/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201601/misc/upload_image.py | 66 --- .../v201601/misc/upload_media_bundle.py | 59 -- .../adwords/v201601/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 133 ----- .../get_keyword_bid_simulations.py | 81 --- .../v201601/optimization/get_keyword_ideas.py | 90 --- .../adwords/v201601/remarketing/__init__.py | 15 - .../v201601/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 70 --- .../remarketing/add_crm_based_user_list.py | 97 ---- .../remarketing/add_rule_based_user_lists.py | 183 ------ .../remarketing/upload_offline_conversions.py | 75 --- .../adwords/v201601/reporting/__init__.py | 15 - .../reporting/download_criteria_report.py | 61 -- .../download_criteria_report_as_stream.py | 77 --- ...oad_criteria_report_as_stream_with_awql.py | 81 --- .../download_criteria_report_as_string.py | 59 -- ...oad_criteria_report_as_string_with_awql.py | 55 -- .../download_criteria_report_with_awql.py | 59 -- .../v201601/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 230 -------- examples/adwords/v201601/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 281 ---------- .../v201601/shopping/add_product_scope.py | 104 ---- .../v201601/shopping/add_shopping_campaign.py | 121 ---- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201601/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 161 ------ .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201601/targeting/lookup_location.py | 82 --- .../v201605/migration/upgrade_ad_url.py | 79 --- .../v201607/campaign_management/add_draft.py | 6 +- .../v201607/campaign_management/add_trial.py | 1 - .../v201607/migration/upgrade_ad_url.py | 79 --- .../create_audience_segments.py | 3 - .../get_all_audience_segments.py | 3 - .../get_first_party_audience_segments.py | 3 - .../populate_first_party_audience_segments.py | 3 - .../update_audience_segments.py | 3 - .../create_audience_segments.py | 3 - .../get_all_audience_segments.py | 3 - .../get_first_party_audience_segments.py | 3 - .../populate_first_party_audience_segments.py | 3 - .../update_audience_segments.py | 3 - .../create_audience_segments.py | 3 - .../populate_first_party_audience_segments.py | 3 - .../update_audience_segments.py | 3 - .../get_base_rates_for_rate_card.py | 3 +- .../get_all_ad_unit_sizes.py | 15 +- .../order_service/get_orders_starting_soon.py | 2 +- .../get_marketplace_comments.py | 14 +- ...n_report_rows_for_reconciliation_report.py | 9 +- ...iliation_report_for_last_billing_period.py | 5 +- googleads.yaml | 2 +- googleads/adwords.py | 79 +-- googleads/common.py | 2 +- tests/adwords_test.py | 20 + tests/common_test.py | 22 +- 121 files changed, 86 insertions(+), 8961 deletions(-) delete mode 100644 examples/adwords/v201601/__init__.py delete mode 100644 examples/adwords/v201601/account_management/__init__.py delete mode 100755 examples/adwords/v201601/account_management/create_account.py delete mode 100755 examples/adwords/v201601/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201601/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201601/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201601/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201601/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201601/basic_operations/__init__.py delete mode 100755 examples/adwords/v201601/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201601/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201601/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201601/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201601/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201601/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201601/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201601/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201601/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201601/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201601/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201601/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201601/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201601/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201601/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201601/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201601/campaign_management/__init__.py delete mode 100755 examples/adwords/v201601/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201601/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py delete mode 100755 examples/adwords/v201601/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201601/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201601/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201601/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201601/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201601/error_handling/__init__.py delete mode 100755 examples/adwords/v201601/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201601/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201601/extensions/__init__.py delete mode 100755 examples/adwords/v201601/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201601/extensions/add_site_links.py delete mode 100755 examples/adwords/v201601/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201601/migration/__init__.py delete mode 100755 examples/adwords/v201601/migration/migrate_to_extension_settings.py delete mode 100755 examples/adwords/v201601/migration/upgrade_ad_url.py delete mode 100644 examples/adwords/v201601/misc/__init__.py delete mode 100755 examples/adwords/v201601/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201601/misc/upload_image.py delete mode 100755 examples/adwords/v201601/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201601/optimization/__init__.py delete mode 100755 examples/adwords/v201601/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201601/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201601/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201601/remarketing/__init__.py delete mode 100755 examples/adwords/v201601/remarketing/add_audience.py delete mode 100755 examples/adwords/v201601/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201601/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201601/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201601/remarketing/upload_offline_conversions.py delete mode 100644 examples/adwords/v201601/reporting/__init__.py delete mode 100755 examples/adwords/v201601/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201601/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201601/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201601/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201601/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201601/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201601/shopping/__init__.py delete mode 100755 examples/adwords/v201601/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201601/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201601/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201601/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201601/targeting/__init__.py delete mode 100755 examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201601/targeting/lookup_location.py delete mode 100755 examples/adwords/v201605/migration/upgrade_ad_url.py delete mode 100755 examples/adwords/v201607/migration/upgrade_ad_url.py diff --git a/ChangeLog b/ChangeLog index 9ac308f8..a8ba1216 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +4.5.0 -- 8/26/2016 +* AdWordsClient's initializer no longer requires the user_agent field. This + field is also now validated to ensure that it only contains ASCII characters. +* Removed support and examples for AdWords v201601. +* Removed upgrade_ad_url example for AdWords v201605 and v201607. + 4.4.0 -- 8/23/2016 * Removed support for DFP v201505. * Added support for DFP v201608. diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index 71469a2e..e91aaee4 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -39,7 +39,8 @@ def main(service_account_email, key_file, service_account_user, sub=service_account_user) adwords_client = adwords.AdWordsClient( - developer_token, oauth2_client, user_agent, client_customer_id) + developer_token, oauth2_client, user_agent, + client_customer_id=client_customer_id) customer = adwords_client.GetService('CustomerService').get() print 'You are logged in as customer: %s' % customer['customerId'] diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_without_yaml.py index 3726b195..daad6080 100755 --- a/examples/adwords/authentication/create_adwords_client_without_yaml.py +++ b/examples/adwords/authentication/create_adwords_client_without_yaml.py @@ -44,7 +44,8 @@ def main(client_id, client_secret, refresh_token, developer_token, user_agent, client_id, client_secret, refresh_token) adwords_client = adwords.AdWordsClient( - developer_token, oauth2_client, user_agent, client_customer_id) + developer_token, oauth2_client, user_agent, + client_customer_id=client_customer_id) customer = adwords_client.GetService('CustomerService').get() print 'You are logged in as customer: %s' % customer['customerId'] diff --git a/examples/adwords/v201601/__init__.py b/examples/adwords/v201601/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201601/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201601/account_management/__init__.py b/examples/adwords/v201601/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201601/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201601/account_management/create_account.py b/examples/adwords/v201601/account_management/create_account.py deleted file mode 100755 index 54aee6ce..00000000 --- a/examples/adwords/v201601/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201601') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/account_management/get_account_changes.py b/examples/adwords/v201601/account_management/get_account_changes.py deleted file mode 100755 index 61f9ef6b..00000000 --- a/examples/adwords/v201601/account_management/get_account_changes.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201601') - campaign_service = client.GetService('CampaignService', version='v201601') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedAdExtensions' in data: - print ' Added ad extensions: %s' % data['addedAdExtensions'] - if 'removedAdExtensions' in data: - print ' Removed ad extensions: %s' % data['removedAdExtensions'] - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/account_management/get_account_hierarchy.py b/examples/adwords/v201601/account_management/get_account_hierarchy.py deleted file mode 100755 index 8ab21f78..00000000 --- a/examples/adwords/v201601/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201601') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/advanced_operations/__init__.py b/examples/adwords/v201601/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201601/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201601/advanced_operations/add_ad_customizer.py b/examples/adwords/v201601/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 4f5a84f9..00000000 --- a/examples/adwords/v201601/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates TextAds that use ad customizations for the specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add TextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no TextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService') - - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'description1': 'Only {=%s.Price}' % feed_name, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 73beb48b..00000000 --- a/examples/adwords/v201601/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201601') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 61c91b3e..00000000 --- a/examples/adwords/v201601/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/advanced_operations/add_html5_ad.py b/examples/adwords/v201601/advanced_operations/add_html5_ad.py deleted file mode 100755 index 4113a759..00000000 --- a/examples/adwords/v201601/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index 5d3c4192..00000000 --- a/examples/adwords/v201601/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a text add that uses advanced features of upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 51ab7e67..00000000 --- a/examples/adwords/v201601/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201601') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201601') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201601') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index 9b916b91..00000000 --- a/examples/adwords/v201601/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201601') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201601') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 4302c53f..00000000 --- a/examples/adwords/v201601/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201601') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index e7de9fed..00000000 --- a/examples/adwords/v201601/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201601') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201601') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'period': 'DAILY', - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201601') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201601/basic_operations/__init__.py b/examples/adwords/v201601/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201601/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201601/basic_operations/add_ad_groups.py b/examples/adwords/v201601/basic_operations/add_ad_groups.py deleted file mode 100755 index 9d4848f7..00000000 --- a/examples/adwords/v201601/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201601') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/basic_operations/add_campaigns.py b/examples/adwords/v201601/basic_operations/add_campaigns.py deleted file mode 100755 index 406d91fb..00000000 --- a/examples/adwords/v201601/basic_operations/add_campaigns.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201601') - budget_service = client.GetService('BudgetService', version='v201601') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/basic_operations/add_keywords.py b/examples/adwords/v201601/basic_operations/add_keywords.py deleted file mode 100755 index ef2d222c..00000000 --- a/examples/adwords/v201601/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201601') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/basic_operations/add_text_ads.py b/examples/adwords/v201601/basic_operations/add_text_ads.py deleted file mode 100755 index 198063bc..00000000 --- a/examples/adwords/v201601/basic_operations/add_text_ads.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/basic_operations/get_ad_groups.py b/examples/adwords/v201601/basic_operations/get_ad_groups.py deleted file mode 100755 index 516d889e..00000000 --- a/examples/adwords/v201601/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201601') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/basic_operations/get_campaigns.py b/examples/adwords/v201601/basic_operations/get_campaigns.py deleted file mode 100755 index 0212b784..00000000 --- a/examples/adwords/v201601/basic_operations/get_campaigns.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201601') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 322c9c2e..00000000 --- a/examples/adwords/v201601/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201601') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/basic_operations/get_keywords.py b/examples/adwords/v201601/basic_operations/get_keywords.py deleted file mode 100755 index 0d13da3b..00000000 --- a/examples/adwords/v201601/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201601') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201601/basic_operations/get_text_ads.py b/examples/adwords/v201601/basic_operations/get_text_ads.py deleted file mode 100755 index c7001b81..00000000 --- a/examples/adwords/v201601/basic_operations/get_text_ads.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/basic_operations/pause_ad.py b/examples/adwords/v201601/basic_operations/pause_ad.py deleted file mode 100755 index 32b6bd4b..00000000 --- a/examples/adwords/v201601/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201601/basic_operations/remove_ad.py b/examples/adwords/v201601/basic_operations/remove_ad.py deleted file mode 100755 index 36623500..00000000 --- a/examples/adwords/v201601/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201601/basic_operations/remove_ad_group.py b/examples/adwords/v201601/basic_operations/remove_ad_group.py deleted file mode 100755 index 47de93fa..00000000 --- a/examples/adwords/v201601/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201601') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/basic_operations/remove_campaign.py b/examples/adwords/v201601/basic_operations/remove_campaign.py deleted file mode 100755 index 75679ed0..00000000 --- a/examples/adwords/v201601/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201601') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/basic_operations/remove_keyword.py b/examples/adwords/v201601/basic_operations/remove_keyword.py deleted file mode 100755 index 1d8d8c99..00000000 --- a/examples/adwords/v201601/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201601') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201601/basic_operations/update_ad_group.py b/examples/adwords/v201601/basic_operations/update_ad_group.py deleted file mode 100755 index 6a22c2b0..00000000 --- a/examples/adwords/v201601/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201601') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/basic_operations/update_campaign.py b/examples/adwords/v201601/basic_operations/update_campaign.py deleted file mode 100755 index ebfc0490..00000000 --- a/examples/adwords/v201601/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201601') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/basic_operations/update_keyword.py b/examples/adwords/v201601/basic_operations/update_keyword.py deleted file mode 100755 index 8e473b48..00000000 --- a/examples/adwords/v201601/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201601') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201601/campaign_management/__init__.py b/examples/adwords/v201601/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201601/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201601/campaign_management/add_campaign_labels.py b/examples/adwords/v201601/campaign_management/add_campaign_labels.py deleted file mode 100755 index cbcb8251..00000000 --- a/examples/adwords/v201601/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201601') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index 5dae21d8..00000000 --- a/examples/adwords/v201601/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,427 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201601') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201601') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding a TextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new TextAd for each of - the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'period': 'DAILY' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201601') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201601/campaign_management/add_experiment.py b/examples/adwords/v201601/campaign_management/add_experiment.py deleted file mode 100755 index 13132b6c..00000000 --- a/examples/adwords/v201601/campaign_management/add_experiment.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201601') - ad_group_service = client.GetService('AdGroupService', version='v201601') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201601') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py b/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py deleted file mode 100755 index ace90f21..00000000 --- a/examples/adwords/v201601/campaign_management/add_keywords_in_bulk.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 code sample illustrates how to perform asynchronous requests. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import random -import re -import time -from googleads import adwords -from googleads import errors - - -RETRY_INTERVAL = 10 -RETRIES_COUNT = 30 -KEYWORD_NUMBER = 100 -INDEX_REGEX = r'operations\[(\d+)\].operand' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - mutate_job_service = client.GetService('MutateJobService', version='v201601') - - # Create list of all operations for the job. - operations = [] - - # Create AdGroupCriterionOperations to add keywords. - for i in range(KEYWORD_NUMBER): - keyword = 'mars%d' % i - if random.randint(1, 10) == 1: - keyword += '!!!' - operations.append({ - 'xsi_type': 'AdGroupCriterionOperation', - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': keyword - } - } - }) - - # You can specify up to 3 job IDs that must successfully complete before - # this job can be processed. - policy = { - 'prerequisiteJobIds': [] - } - - # Call mutate to create a new job. - response = mutate_job_service.mutate(operations, policy) - - if not response: - raise errors.GoogleAdsError('Failed to submit a job; aborting.') - - job_id = response['id'] - print 'Job with ID %s was successfully created.' % job_id - - # Create selector to retrieve job status and wait for it to complete. - selector = { - 'xsi_type': 'BulkMutateJobSelector', - 'jobIds': [job_id] - } - - time.sleep(RETRY_INTERVAL) - # Poll for job status until it's finished. - print 'Retrieving job status...' - for i in range(RETRIES_COUNT): - job_status_response = mutate_job_service.get(selector) - status = job_status_response[0]['status'] - if status in ('COMPLETED', 'FAILED'): - break - print ('[%d] Current status is \'%s\', waiting %d seconds to retry...' % - (i, status, RETRY_INTERVAL)) - time.sleep(RETRY_INTERVAL) - - if status == 'FAILED': - raise errors.GoogleAdsError('Job failed with reason: \'%s\'' % - job_status_response[0]['failure_reason']) - if status in ('PROCESSING', 'PENDING'): - raise errors.GoogleAdsError('Job did not complete within %d seconds' % - (RETRY_INTERVAL * (RETRIES_COUNT - 1))) - - # Status must be COMPLETED. - # Get the job result. Here we re-use the same selector. - result_response = mutate_job_service.getResult(selector) - - # Output results. - index = 0 - for result in result_response['SimpleMutateResult']['results']: - if 'PlaceHolder' in result: - print 'Operation [%d] - FAILED' % index - else: - print 'Operation [%d] - SUCCEEDED' % index - index += 1 - - # Output errors - for error in result_response['SimpleMutateResult']['errors']: - index = int(re.search(INDEX_REGEX, error['fieldPath']).group(1)) - reason = error['reason'] - keyword = operations[index]['operand']['criterion']['text'] - print ('ERROR - keyword \'%s\' failed due to \'%s\'' % - (keyword, reason)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201601/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index 5a41aea6..00000000 --- a/examples/adwords/v201601/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201601') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201601') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201601') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201601') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 3d563de4..00000000 --- a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index b63ad3cb..00000000 --- a/examples/adwords/v201601/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 51ae8e5d..00000000 --- a/examples/adwords/v201601/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201601') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201601/campaign_management/promote_experiment.py b/examples/adwords/v201601/campaign_management/promote_experiment.py deleted file mode 100755 index 04e9d7c6..00000000 --- a/examples/adwords/v201601/campaign_management/promote_experiment.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201601') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201601/campaign_management/set_ad_parameters.py b/examples/adwords/v201601/campaign_management/set_ad_parameters.py deleted file mode 100755 index 1a54db8f..00000000 --- a/examples/adwords/v201601/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - ad_param_service = client.GetService('AdParamService', version='v201601') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index 1aca6398..00000000 --- a/examples/adwords/v201601/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201601') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201601/campaign_management/validate_text_ad.py b/examples/adwords/v201601/campaign_management/validate_text_ad.py deleted file mode 100755 index 25acd193..00000000 --- a/examples/adwords/v201601/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/error_handling/__init__.py b/examples/adwords/v201601/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201601/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201601/error_handling/handle_partial_failures.py b/examples/adwords/v201601/error_handling/handle_partial_failures.py deleted file mode 100755 index de348a93..00000000 --- a/examples/adwords/v201601/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201601') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/error_handling/handle_policy_violation_error.py b/examples/adwords/v201601/error_handling/handle_policy_violation_error.py deleted file mode 100755 index b4d1f7a6..00000000 --- a/examples/adwords/v201601/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201601') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - operation = operations[int(operation_index[0])] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) - else: - # Non-policy error returned, re-throw exception. - raise e - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/extensions/__init__.py b/examples/adwords/v201601/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201601/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201601/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201601/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 5fc14a00..00000000 --- a/examples/adwords/v201601/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201601').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201601') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201601/extensions/add_site_links.py b/examples/adwords/v201601/extensions/add_site_links.py deleted file mode 100755 index 2f8d7f89..00000000 --- a/examples/adwords/v201601/extensions/add_site_links.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201601') - customer_service = client.GetService('CustomerService', version='v201601') - - customer_tz = timezone(customer_service.get()['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt) - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'} - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/extensions/add_site_links_using_feeds.py b/examples/adwords/v201601/extensions/add_site_links_using_feeds.py deleted file mode 100755 index a27c550f..00000000 --- a/examples/adwords/v201601/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,233 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201601') - feed_item_service = client.GetService('FeedItemService', version='v201601') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201601') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201601') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/migration/__init__.py b/examples/adwords/v201601/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201601/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201601/migration/migrate_to_extension_settings.py b/examples/adwords/v201601/migration/migrate_to_extension_settings.py deleted file mode 100755 index 0e46c6f1..00000000 --- a/examples/adwords/v201601/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201601') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201601') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201601') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201601') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201601') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201601') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201601') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/migration/upgrade_ad_url.py b/examples/adwords/v201601/migration/upgrade_ad_url.py deleted file mode 100755 index 22fd74e7..00000000 --- a/examples/adwords/v201601/migration/upgrade_ad_url.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 upgrades an ad to use upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, adgroup_id, ad_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201601') - - selector = { - 'fields': ['Id', 'Url'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [ad_id] - } - ] - } - - page = adgroup_ad_service.get(selector) - - adgroup_ad = page['entries'][0] if page['entries'] else None - - if not adgroup_ad: - raise errors.GoogleAdsError('Ad not found.') - - ad_url_upgrade = { - 'adId': adgroup_ad['ad']['id'], - 'finalUrl': adgroup_ad['ad']['url'] - } - - adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] - - if adgroup_ad: - print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' - % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201601/misc/__init__.py b/examples/adwords/v201601/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201601/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201601/misc/get_all_images_and_videos.py b/examples/adwords/v201601/misc/get_all_images_and_videos.py deleted file mode 100755 index 404c1822..00000000 --- a/examples/adwords/v201601/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201601') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/misc/upload_image.py b/examples/adwords/v201601/misc/upload_image.py deleted file mode 100755 index ad0d2684..00000000 --- a/examples/adwords/v201601/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201601') - - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201601/misc/upload_media_bundle.py b/examples/adwords/v201601/misc/upload_media_bundle.py deleted file mode 100755 index 8816b544..00000000 --- a/examples/adwords/v201601/misc/upload_media_bundle.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201601') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/optimization/__init__.py b/examples/adwords/v201601/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201601/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201601/optimization/estimate_keyword_traffic.py b/examples/adwords/v201601/optimization/estimate_keyword_traffic.py deleted file mode 100755 index c18dd310..00000000 --- a/examples/adwords/v201601/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201601') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - selector = { - 'campaignEstimateRequests': [{ - 'adGroupEstimateRequests': [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }], - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ] - }] - } - estimates = traffic_estimator_service.get(selector) - - # Display results. - ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] - keyword_estimates = ad_group_estimate['keywordEstimates'] - for index in xrange(len(keyword_estimates)): - keyword = keyword_estimate_requests[index]['keyword'] - estimate = keyword_estimates[index] - if keyword_estimate_requests[index].get('isNegative', False): - continue - - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(estimate['min']['averageCpc']['microAmount'], - estimate['max']['averageCpc']['microAmount']) - if 'averageCpc' in estimate['min'] else 'N/A') - mean_avg_pos = _CalculateMean(estimate['min']['averagePosition'], - estimate['max']['averagePosition']) - mean_clicks = _CalculateMean(estimate['min']['clicksPerDay'], - estimate['max']['clicksPerDay']) - mean_total_cost = _CalculateMean( - estimate['min']['totalCost']['microAmount'], - estimate['max']['totalCost']['microAmount']) - - print ('Results for the keyword with text \'%s\' and match type \'%s\':' - % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return None - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index c7690c23..00000000 --- a/examples/adwords/v201601/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201601') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201601/optimization/get_keyword_ideas.py b/examples/adwords/v201601/optimization/get_keyword_ideas.py deleted file mode 100755 index a6b590d2..00000000 --- a/examples/adwords/v201601/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201601') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/remarketing/__init__.py b/examples/adwords/v201601/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201601/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201601/remarketing/add_audience.py b/examples/adwords/v201601/remarketing/add_audience.py deleted file mode 100755 index 11b032f1..00000000 --- a/examples/adwords/v201601/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201601') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201601') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/remarketing/add_conversion_tracker.py b/examples/adwords/v201601/remarketing/add_conversion_tracker.py deleted file mode 100755 index a5db7153..00000000 --- a/examples/adwords/v201601/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201601') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/remarketing/add_crm_based_user_list.py b/examples/adwords/v201601/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 98c226aa..00000000 --- a/examples/adwords/v201601/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client, emails): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201601') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180, - # This field is optional. It links to a service you created that allows - # members of this list to remove themselves. - 'optOutLink': 'http://endpoint1.example.com/optout' - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. - - Args: - emails: list of str emails to be hashed. - - Returns: - A list of SHA-256 hashed emails. - """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] - - -if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) diff --git a/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 8783417b..00000000 --- a/examples/adwords/v201601/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201601') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/remarketing/upload_offline_conversions.py b/examples/adwords/v201601/remarketing/upload_offline_conversions.py deleted file mode 100755 index 190295b1..00000000 --- a/examples/adwords/v201601/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201601') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201601/reporting/__init__.py b/examples/adwords/v201601/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201601/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201601/reporting/download_criteria_report.py b/examples/adwords/v201601/reporting/download_criteria_report.py deleted file mode 100755 index 61d018e8..00000000 --- a/examples/adwords/v201601/reporting/download_criteria_report.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201601') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index d2a6ab14..00000000 --- a/examples/adwords/v201601/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201601') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 8545b4cc..00000000 --- a/examples/adwords/v201601/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201601') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_string.py b/examples/adwords/v201601/reporting/download_criteria_report_as_string.py deleted file mode 100755 index 2889911b..00000000 --- a/examples/adwords/v201601/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201601') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 33881398..00000000 --- a/examples/adwords/v201601/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201601') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=False) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 7985bff7..00000000 --- a/examples/adwords/v201601/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201601') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=False) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201601/reporting/get_report_fields.py b/examples/adwords/v201601/reporting/get_report_fields.py deleted file mode 100755 index 50edd0e1..00000000 --- a/examples/adwords/v201601/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201601') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201601/reporting/parallel_report_download.py b/examples/adwords/v201601/reporting/parallel_report_download.py deleted file mode 100755 index 65ea88fe..00000000 --- a/examples/adwords/v201601/reporting/parallel_report_download.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import logging -import multiprocessing -from Queue import Empty -import time -import googleads - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - client: An AdWordsClient instance. - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201601') - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = self._DownloadReport(customer_id) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - - Raises: - Exception: if no CustomerIds could be found. - - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201601') - - offset = 0 - - # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201601/shopping/__init__.py b/examples/adwords/v201601/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201601/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201601/shopping/add_product_partition_tree.py b/examples/adwords/v201601/shopping/add_product_partition_tree.py deleted file mode 100755 index 7247ba12..00000000 --- a/examples/adwords/v201601/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201601') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201601/shopping/add_product_scope.py b/examples/adwords/v201601/shopping/add_product_scope.py deleted file mode 100755 index f0973f61..00000000 --- a/examples/adwords/v201601/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201601') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201601/shopping/add_shopping_campaign.py b/examples/adwords/v201601/shopping/add_shopping_campaign.py deleted file mode 100755 index 7b93a2fb..00000000 --- a/examples/adwords/v201601/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201601') - ad_group_service = client.GetService('AdGroupService', version='v201601') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201601') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201601/shopping/get_product_category_taxonomy.py b/examples/adwords/v201601/shopping/get_product_category_taxonomy.py deleted file mode 100755 index f4f8a2c5..00000000 --- a/examples/adwords/v201601/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201601') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/targeting/__init__.py b/examples/adwords/v201601/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201601/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 9ff418f9..00000000 --- a/examples/adwords/v201601/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201601') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - florida_downtown = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'PlacesOfInterestOperand', - # Other valid options: AIRPORT, UNIVERSITY. - 'category': 'DOWNTOWN', - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - } - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish, florida_tier3, - florida_downtown] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index dcb27348..00000000 --- a/examples/adwords/v201601/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201601') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index e2cccbcf..00000000 --- a/examples/adwords/v201601/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201601') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index a81d7d77..00000000 --- a/examples/adwords/v201601/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201601') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201601/targeting/lookup_location.py b/examples/adwords/v201601/targeting/lookup_location.py deleted file mode 100755 index ae34e59b..00000000 --- a/examples/adwords/v201601/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201601') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/migration/upgrade_ad_url.py b/examples/adwords/v201605/migration/upgrade_ad_url.py deleted file mode 100755 index e111692a..00000000 --- a/examples/adwords/v201605/migration/upgrade_ad_url.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 upgrades an ad to use upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, adgroup_id, ad_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201605') - - selector = { - 'fields': ['Id', 'Url'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [ad_id] - } - ] - } - - page = adgroup_ad_service.get(selector) - - adgroup_ad = page['entries'][0] if page['entries'] else None - - if not adgroup_ad: - raise errors.GoogleAdsError('Ad not found.') - - ad_url_upgrade = { - 'adId': adgroup_ad['ad']['id'], - 'finalUrl': adgroup_ad['ad']['url'] - } - - adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] - - if adgroup_ad: - print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' - % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201607/campaign_management/add_draft.py b/examples/adwords/v201607/campaign_management/add_draft.py index 5308c4fb..6936265c 100755 --- a/examples/adwords/v201607/campaign_management/add_draft.py +++ b/examples/adwords/v201607/campaign_management/add_draft.py @@ -35,9 +35,6 @@ def main(client, base_campaign_id): - # Initialize appropriate services. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201607') draft_service = client.GetService('DraftService', version='v201607') draft = { @@ -52,6 +49,9 @@ def main(client, base_campaign_id): # Once the draft is created, you can modify the draft campaign as if it were a # real campaign. For example, you may add criteria, adjust bids, or even # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201607') + criterion = { 'xsi_type': 'Language', 'id': 1003 # Spanish diff --git a/examples/adwords/v201607/campaign_management/add_trial.py b/examples/adwords/v201607/campaign_management/add_trial.py index 40e5a3f6..960a0e02 100755 --- a/examples/adwords/v201607/campaign_management/add_trial.py +++ b/examples/adwords/v201607/campaign_management/add_trial.py @@ -52,7 +52,6 @@ def main(client, base_campaign_id, draft_id): trial_operation = {'operator': 'ADD', 'operand': trial} trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], 'predicates': [{ diff --git a/examples/adwords/v201607/migration/upgrade_ad_url.py b/examples/adwords/v201607/migration/upgrade_ad_url.py deleted file mode 100755 index 1020f0ea..00000000 --- a/examples/adwords/v201607/migration/upgrade_ad_url.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 upgrades an ad to use upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, adgroup_id, ad_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201607') - - selector = { - 'fields': ['Id', 'Url'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [ad_id] - } - ] - } - - page = adgroup_ad_service.get(selector) - - adgroup_ad = page['entries'][0] if page['entries'] else None - - if not adgroup_ad: - raise errors.GoogleAdsError('Ad not found.') - - ad_url_upgrade = { - 'adId': adgroup_ad['ad']['id'], - 'finalUrl': adgroup_ad['ad']['url'] - } - - adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] - - if adgroup_ad: - print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' - % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/dfp/v201602/audience_segment_service/create_audience_segments.py b/examples/dfp/v201602/audience_segment_service/create_audience_segments.py index 235c6c67..cf698887 100755 --- a/examples/dfp/v201602/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/create_audience_segments.py @@ -27,9 +27,6 @@ CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' def main(client, custom_targeting_key_id, custom_targeting_value_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate services. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201602') diff --git a/examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py index 6ead437b..88d6f495 100755 --- a/examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py @@ -25,9 +25,6 @@ def main(client): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201602') diff --git a/examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py index 42111d74..4bdc0feb 100755 --- a/examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py @@ -25,9 +25,6 @@ def main(client): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201602') diff --git a/examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py index 18a53e9e..eaec6f08 100755 --- a/examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py @@ -28,9 +28,6 @@ def main(client, audience_segment_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201602') diff --git a/examples/dfp/v201602/audience_segment_service/update_audience_segments.py b/examples/dfp/v201602/audience_segment_service/update_audience_segments.py index 84a74aa4..ce81cd01 100755 --- a/examples/dfp/v201602/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201602/audience_segment_service/update_audience_segments.py @@ -27,9 +27,6 @@ def main(client, audience_segment_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201602') diff --git a/examples/dfp/v201605/audience_segment_service/create_audience_segments.py b/examples/dfp/v201605/audience_segment_service/create_audience_segments.py index 864507fa..f82eaf83 100755 --- a/examples/dfp/v201605/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/create_audience_segments.py @@ -27,9 +27,6 @@ CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' def main(client, custom_targeting_key_id, custom_targeting_value_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate services. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201605') diff --git a/examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py index 173be58d..ad13bd5f 100755 --- a/examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py @@ -25,9 +25,6 @@ def main(client): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201605') diff --git a/examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py index 51a07904..45a2c437 100755 --- a/examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py @@ -25,9 +25,6 @@ def main(client): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201605') diff --git a/examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py index 467681b5..61bd1e32 100755 --- a/examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py @@ -28,9 +28,6 @@ def main(client, audience_segment_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201605') diff --git a/examples/dfp/v201605/audience_segment_service/update_audience_segments.py b/examples/dfp/v201605/audience_segment_service/update_audience_segments.py index 7f09df0d..b03c84a7 100755 --- a/examples/dfp/v201605/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201605/audience_segment_service/update_audience_segments.py @@ -27,9 +27,6 @@ def main(client, audience_segment_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201605') diff --git a/examples/dfp/v201608/audience_segment_service/create_audience_segments.py b/examples/dfp/v201608/audience_segment_service/create_audience_segments.py index 13ec4be7..f0845326 100755 --- a/examples/dfp/v201608/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/create_audience_segments.py @@ -27,9 +27,6 @@ CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' def main(client, custom_targeting_key_id, custom_targeting_value_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate services. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201608') diff --git a/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py index e753b4d1..6d4f94cc 100755 --- a/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py @@ -28,9 +28,6 @@ def main(client, audience_segment_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201608') diff --git a/examples/dfp/v201608/audience_segment_service/update_audience_segments.py b/examples/dfp/v201608/audience_segment_service/update_audience_segments.py index 52a59e4c..957b8e2e 100755 --- a/examples/dfp/v201608/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/update_audience_segments.py @@ -27,9 +27,6 @@ def main(client, audience_segment_id): - # Initialize client object. - client = dfp.DfpClient.LoadFromStorage() - # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201608') diff --git a/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py index 74d72e63..b230db2c 100755 --- a/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py @@ -46,7 +46,8 @@ def main(client, rate_card_id): # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' 'found.\n' % - (base_rate['id'], base_rate['type'], base_rate['rateCardId'])) + (base_rate['id'], dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py index 1f1fe0fd..953f1269 100755 --- a/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py @@ -30,17 +30,14 @@ def main(client): # Retreive a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. - while True: - response = ad_unit_size_service.getAdUnitSizesByStatement( - statement.ToStatement()) - if response: - for ad_unit_size in response: - # Print out some information for each ad unit size. + response = ad_unit_size_service.getAdUnitSizesByStatement( + statement.ToStatement()) + if response: + for ad_unit_size in response: + # Print out some information for each ad unit size. + if 'fullDisplayString' in ad_unit_size: print('Ad unit size with dimensions "%s" was found.\n' % (ad_unit_size['fullDisplayString'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break if __name__ == '__main__': diff --git a/examples/dfp/v201608/order_service/get_orders_starting_soon.py b/examples/dfp/v201608/order_service/get_orders_starting_soon.py index cd3cd2b5..1c3bcbd4 100755 --- a/examples/dfp/v201608/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201608/order_service/get_orders_starting_soon.py @@ -37,7 +37,7 @@ def main(client): {'key': 'now', 'value': { 'xsi_type': 'TextValue', - 'value': datetime.now().strftime('%y-%m-%d_t%h:%m:%s') + 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') }}, {'key': 'soon', 'value': { diff --git a/examples/dfp/v201608/proposal_service/get_marketplace_comments.py b/examples/dfp/v201608/proposal_service/get_marketplace_comments.py index 431f4409..87f64a58 100755 --- a/examples/dfp/v201608/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201608/proposal_service/get_marketplace_comments.py @@ -29,22 +29,15 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( 'ProposalService', version='v201608') - query = 'WHERE proposal_id = :proposal_id' - values = [ - {'key': 'proposal_id', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - }} - ] + query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. - statement = dfp.FilterStatement(query, values) + statement = {'query': query} # Retrieve a small amount of marketplace comments at a time, paging # through until all marketplace comments have been retrieved. while True: response = marketplace_comment_service.getMarketplaceCommentsByStatement( - statement.ToStatement()) + statement) if 'results' in response: for marketplace_comment in response['results']: # Print out some information for each marketplace comment. @@ -59,7 +52,6 @@ def main(client, proposal_id): 'Marketplace comment with creation time "%s"and comment "%s" was ' 'found.\n' % (date_time_string, marketplace_comment['comment'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 5cb21ae3..622b9a6d 100755 --- a/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -26,14 +26,9 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( 'ReconciliationReportRowService', version='v201608') - query = ('WHERE reconciliationReportId = :reconciliationReportId AND ' - 'lineItemId != :lineItemId') + query = ('WHERE reconciliationReportId = %s AND ' + 'lineItemId != :lineItemId') % reconciliation_report_id values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, {'key': 'lineItemId', 'value': { 'xsi_type': 'NumberValue', diff --git a/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 578c17b1..f67a4e85 100755 --- a/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -51,8 +51,9 @@ def main(client): for reconciliation_report in response['results']: # Print out some information for each reconciliation report. print( - 'Reconciliation report with ID "%d" and start date "%d" was found.\n' - % (reconciliation_report['id'], last_month.strftime('%Y-%m-01'))) + 'Reconciliation report with ID "%d" and start date "%s" was found.' + '\n' % (reconciliation_report['id'], + last_month.strftime('%Y-%m-01'))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/googleads.yaml b/googleads.yaml index 3ea0285d..7d4bdbb6 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -4,11 +4,11 @@ adwords: # Required Fields # ############################################################################# developer_token: INSERT_DEVELOPER_TOKEN_HERE - user_agent: INSERT_USER_AGENT_HERE ############################################################################# # Optional Fields # ############################################################################# # client_customer_id: INSERT_CLIENT_CUSTOMER_ID_HERE + # user_agent: INSERT_USER_AGENT_HERE # partial_failure: True # validate_only: True ############################################################################# diff --git a/googleads/adwords.py b/googleads/adwords.py index a383c7b1..326fd1c2 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -36,49 +36,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201601': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'BatchJobService': 'cm', - 'BudgetOrderService': 'billing', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LocationCriterionService': 'cm', - 'MediaService': 'cm', - 'MutateJobService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'ManagedCustomerService': 'mcm', - 'CustomerService': 'mcm', - 'CustomerFeedService': 'cm', - 'BudgetService': 'cm', - 'BiddingStrategyService': 'cm', - 'AdwordsUserListService': 'rm', - 'LabelService': 'cm', - }, 'v201603': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', @@ -229,6 +186,8 @@ # The endpoint used by default when making AdWords API requests. _DEFAULT_ENDPOINT = 'https://adwords.google.com' +# The user-agent used by default when making AdWords API requests. +_DEFAULT_USER_AGENT = 'unknown' class AdWordsClient(object): @@ -257,10 +216,10 @@ class AdWordsClient(object): # The key in the storage yaml which contains AdWords data. _YAML_KEY = 'adwords' # A list of values which must be provided to use AdWords. - _REQUIRED_INIT_VALUES = ('user_agent', 'developer_token') + _REQUIRED_INIT_VALUES = ('developer_token') # A list of values which may optionally be provided when using AdWords. _OPTIONAL_INIT_VALUES = ( - 'validate_only', 'partial_failure', 'client_customer_id', + 'validate_only', 'partial_failure', 'client_customer_id', 'user_agent', 'report_downloader_headers') # The format of SOAP service WSDLs. A server, namespace, version, and service @@ -290,8 +249,8 @@ def LoadFromStorage(cls, path=None): path, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES, cls._OPTIONAL_INIT_VALUES)) - def __init__( - self, developer_token, oauth2_client, user_agent, **kwargs): + def __init__(self, developer_token, oauth2_client, + user_agent=_DEFAULT_USER_AGENT, **kwargs): """Initializes an AdWordsClient. For more information on these arguments, see our SOAP headers guide: @@ -301,8 +260,9 @@ def __init__( developer_token: A string containing your AdWords API developer token. oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize your requests. - user_agent: An arbitrary string which will be used to identify your - application + user_agent: An arbitrary string containing only ASCII characters that will + be used to identify your application. If not set, this will default to + the string value "unknown". **kwargs: Optional keyword arguments. Keyword Arguments: @@ -322,12 +282,24 @@ def __init__( isn't being used. report_downloader_headers: A dict containing optional headers to be used by default when making requests with the ReportDownloader. + + Raises: + GoogleAdsValueError: If the provided user_agent contains non-ASCII + characters. """ self.developer_token = developer_token self.oauth2_client = oauth2_client self.oauth2_client.Refresh() - self.user_agent = user_agent self.client_customer_id = kwargs.get('client_customer_id') + self.user_agent = user_agent + # Verify that the provided user_agent contains only ASCII characters. In + # both Python 2 and Python 3, a UnicodeEncodeError will be raised if it + # contains a non-ASCII character. + try: + self.user_agent.encode('ascii') + except UnicodeEncodeError: + raise googleads.errors.GoogleAdsValueError( + 'Invalid user_agent value, must contain only ASCII characters.') self.validate_only = kwargs.get('validate_only', False) self.partial_failure = kwargs.get('partial_failure', False) self.cache = kwargs.get('cache') @@ -1007,9 +979,6 @@ def __init__(self, request_builder, upload_url, current_content_length=0, def _InitializeURL(self, upload_url, current_content_length): """Ensures that the URL used to upload operations is properly initialized. - Initialization is only necessary in v201601 or higher when the - current_content_length is 0. - Args: upload_url: a string url. current_content_length: an integer identifying the current content length @@ -1017,10 +986,10 @@ def _InitializeURL(self, upload_url, current_content_length): Returns: An initialized string URL, or the provided string URL if the URL has - already been initialized or the version is below v201601. + already been initialized. """ # If initialization is not necessary, return the provided upload_url. - if self._version < 'v201601' or current_content_length != 0: + if current_content_length != 0: return upload_url headers = { diff --git a/googleads/common.py b/googleads/common.py index 262887be..2796d4a1 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -43,7 +43,7 @@ pass -VERSION = '4.4.0' +VERSION = '4.5.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' diff --git a/tests/adwords_test.py b/tests/adwords_test.py index cf49c44e..1075fa10 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -273,6 +273,26 @@ def testLoadFromStorage(self): self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage(), googleads.adwords.AdWordsClient) + def testLoadFromStorageWithNonASCIIUserAgent(self): + with mock.patch('googleads.common.LoadFromStorage') as mock_load: + mock_load.return_value = { + 'developer_token': 'abcdEFghIjkLMOpqRs', + 'oauth2_client': mock.Mock(), + 'user_agent': u'ゼロ' + } + self.assertRaises(googleads.errors.GoogleAdsValueError, + googleads.adwords.AdWordsClient.LoadFromStorage) + + def testLoadFromStorageWithNoUserAgent(self): + with mock.patch('googleads.common.LoadFromStorage') as mock_load: + mock_load.return_value = { + 'developer_token': 'abcdEFghIjkLMOpqRs', + 'oauth2_client': mock.Mock() + } + + client = googleads.adwords.AdWordsClient.LoadFromStorage() + self.assertEquals(client.user_agent, 'unknown') + def testGetService_success(self): version = CURRENT_VERSION service = googleads.adwords._SERVICE_MAP[version].keys()[0] diff --git a/tests/common_test.py b/tests/common_test.py index dc797a9e..0c708345 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -687,22 +687,20 @@ def testProxyConfigGetHandlersWithProxy(self): def testProxyConfigGetHandlersWithProxyAndSLLContext(self): https_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, self.proxy_port1) - # We normally couldn't access HTTPSHandler below Python 2.7.9, but we'll at - # least verify that the logic is right. - urllib2.HTTPSHandler = mock.Mock() - urllib2.HTTPSHandler.return_value = mock.Mock() with mock.patch('googleads.common.ProxyConfig._InitSSLContext') as ssl_ctxt: ssl_ctxt.return_value = 'CONTEXT' with mock.patch('urllib2.ProxyHandler') as proxy_handler: proxy_handler.return_value = mock.Mock() - proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) - self.assertEqual(proxy_config.GetHandlers(), - [urllib2.HTTPSHandler.return_value, - proxy_handler.return_value]) - proxy_handler.assert_called_once_with( - {'https': '%s' % str(https_proxy)}) - urllib2.HTTPSHandler.assert_called_once_with( - context=ssl_ctxt.return_value) + with mock.patch('urllib2.HTTPSHandler') as https_handler: + https_handler.return_value = mock.Mock() + proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) + self.assertEqual(proxy_config.GetHandlers(), + [https_handler.return_value, + proxy_handler.return_value]) + proxy_handler.assert_called_once_with( + {'https': '%s' % str(https_proxy)}) + https_handler.assert_called_once_with( + context=ssl_ctxt.return_value) def testProxyConfigWithNoProxy(self): proxy_config = googleads.common.ProxyConfig() From f640385b4056464a69e33f5a64f6b5efdea4f4ed Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 26 Aug 2016 18:28:05 -0400 Subject: [PATCH 047/180] Commiting latest changes. From fa84240539e4d42adb4a1ced9f9266c852feb8e0 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 31 Aug 2016 11:35:26 -0400 Subject: [PATCH 048/180] `Fixing issue #148. --- ChangeLog | 4 ++++ googleads/adwords.py | 7 ++++--- googleads/common.py | 2 +- tests/adwords_test.py | 32 ++++++++++++++++---------------- 4 files changed, 25 insertions(+), 20 deletions(-) diff --git a/ChangeLog b/ChangeLog index a8ba1216..f7857cca 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +4.5.1 -- 8/30/2016: +* Resolved issue #148: + https://github.com/googleads/googleads-python-lib/issues/148 + 4.5.0 -- 8/26/2016 * AdWordsClient's initializer no longer requires the user_agent field. This field is also now validated to ensure that it only contains ASCII characters. diff --git a/googleads/adwords.py b/googleads/adwords.py index 326fd1c2..48dd1ad0 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -215,9 +215,10 @@ class AdWordsClient(object): # The key in the storage yaml which contains AdWords data. _YAML_KEY = 'adwords' - # A list of values which must be provided to use AdWords. - _REQUIRED_INIT_VALUES = ('developer_token') - # A list of values which may optionally be provided when using AdWords. + # A tuple containing values which must be provided to use AdWords. + _REQUIRED_INIT_VALUES = ('developer_token',) + # A tuple containing values which may optionally be provided when using + # AdWords. _OPTIONAL_INIT_VALUES = ( 'validate_only', 'partial_failure', 'client_customer_id', 'user_agent', 'report_downloader_headers') diff --git a/googleads/common.py b/googleads/common.py index 2796d4a1..c76c1e2f 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -43,7 +43,7 @@ pass -VERSION = '4.5.0' +VERSION = '4.5.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 1075fa10..3875e592 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -252,6 +252,8 @@ class AdWordsClientTest(unittest.TestCase): """Tests for the googleads.adwords.AdWordsClient class.""" def setUp(self): + self.load_from_storage_path = os.path.join( + os.path.dirname(__file__), 'test_data/adwords_googleads.yaml') self.https_proxy_host = 'myproxy' self.https_proxy_port = 443 self.proxy_config = GetProxyConfig(https_host=self.https_proxy_host, @@ -264,13 +266,9 @@ def setUp(self): self.adwords_client, CURRENT_VERSION) def testLoadFromStorage(self): - with mock.patch('googleads.common.LoadFromStorage') as mock_load: - mock_load.return_value = { - 'developer_token': 'abcdEFghIjkLMOpqRs', - 'oauth2_client': mock.Mock(), - 'user_agent': 'unit testing' - } - self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage(), + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient.Refresh'): + self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage( + path=self.load_from_storage_path), googleads.adwords.AdWordsClient) def testLoadFromStorageWithNonASCIIUserAgent(self): @@ -446,30 +444,32 @@ def setUp(self): def setUpClass(cls): test_dir = os.path.dirname(__file__) with open(os.path.join( - test_dir, 'data/batch_job_util_budget_template.txt')) as handler: + test_dir, 'test_data/batch_job_util_budget_template.txt')) as handler: cls.BUDGET_TEMPLATE = handler.read() with open(os.path.join( test_dir, - 'data/batch_job_util_campaign_criterion_template.txt')) as handler: + 'test_data/batch_job_util_campaign_criterion_template.txt')) as handler: cls.CAMPAIGN_CRITERION_TEMPLATE = handler.read() with open(os.path.join( test_dir, - 'data/batch_job_util_campaign_label_template.txt')) as handler: + 'test_data/batch_job_util_campaign_label_template.txt')) as handler: cls.CAMPAIGN_LABEL_TEMPLATE = handler.read() with open(os.path.join( - test_dir, 'data/batch_job_util_invalid_request.txt')) as handler: + test_dir, 'test_data/batch_job_util_invalid_request.txt')) as handler: cls.INVALID_API_REQUEST = handler.read() with open(os.path.join( - test_dir, 'data/batch_job_util_not_request.txt')) as handler: + test_dir, 'test_data/batch_job_util_not_request.txt')) as handler: cls.NOT_API_REQUEST = handler.read() with open(os.path.join( - test_dir, 'data/batch_job_util_raw_request_template.txt')) as handler: + test_dir, 'test_data/batch_job_util_raw_request_template.txt') + ) as handler: cls.RAW_API_REQUEST_TEMPLATE = handler.read() with open(os.path.join( - test_dir, 'data/batch_job_util_operations_template.txt')) as handler: + test_dir, 'test_data/batch_job_util_operations_template.txt') + ) as handler: cls.OPERATIONS_TEMPLATE = handler.read() with open(os.path.join( - test_dir, 'data/batch_job_util_upload_template.txt')) as handler: + test_dir, 'test_data/batch_job_util_upload_template.txt')) as handler: cls.UPLOAD_OPERATIONS_TEMPLATE = handler.read() def ExpandOperandTemplate(self, operation_type, operand): @@ -1254,7 +1254,7 @@ def setUp(self): def setUpClass(cls): test_dir = os.path.dirname(__file__) with open(os.path.join( - test_dir, 'data/batch_job_util_response_template.txt')) as handler: + test_dir, 'test_data/batch_job_util_response_template.txt')) as handler: cls.API_RESPONSE_XML_TEMPLATE = handler.read() def testParseResponse(self): From 54ecab350b3ad64af60ce5770dc309d511f5332c Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 31 Aug 2016 11:36:20 -0400 Subject: [PATCH 049/180] Commiting latest changes. From 3744ea3522be5d7a3fb96bf15e7f754f852f9834 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 3 Oct 2016 17:58:54 -0400 Subject: [PATCH 050/180] AdWords v201609 Release --- ChangeLog | 8 + README.md | 17 +- .../handlers/api_handler.py | 2 +- .../basic_operations/get_expanded_text_ads.py | 2 +- .../basic_operations/get_expanded_text_ads.py | 2 +- examples/adwords/v201609/__init__.py | 15 + .../v201609/account_management/__init__.py | 15 + .../account_management/create_account.py | 63 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201609/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 221 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 126 +++++ ...add_expanded_text_ad_with_upgraded_urls.py | 109 ++++ .../advanced_operations/add_html5_ad.py | 111 ++++ .../add_responsive_display_ad.py | 91 +++ .../add_universal_app_campaign.py | 214 +++++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201609/basic_operations/__init__.py | 15 + .../v201609/basic_operations/add_ad_groups.py | 115 ++++ .../v201609/basic_operations/add_campaigns.py | 125 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201609/basic_operations/add_keywords.py | 92 +++ .../v201609/basic_operations/get_ad_groups.py | 76 +++ .../v201609/basic_operations/get_campaigns.py | 74 +++ .../get_campaigns_with_awql.py | 64 +++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201609/basic_operations/get_keywords.py | 87 +++ .../v201609/basic_operations/get_text_ads.py | 78 +++ .../v201609/basic_operations/pause_ad.py | 61 ++ .../v201609/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 58 ++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201609/campaign_management/__init__.py | 15 + .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 425 ++++++++++++++ .../v201609/campaign_management/add_draft.py | 81 +++ ...dd_keywords_using_incremental_batch_job.py | 259 +++++++++ .../v201609/campaign_management/add_trial.py | 116 ++++ .../get_all_disapproved_ads.py | 74 +++ .../get_all_disapproved_ads_with_awql.py | 63 +++ .../get_campaigns_by_label.py | 85 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201609/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 120 ++++ .../handle_policy_violation_error.py | 114 ++++ .../adwords/v201609/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../adwords/v201609/extensions/add_prices.py | 144 +++++ .../v201609/extensions/add_site_links.py | 146 +++++ .../extensions/add_site_links_using_feeds.py | 236 ++++++++ .../adwords/v201609/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 527 ++++++++++++++++++ examples/adwords/v201609/misc/__init__.py | 15 + .../v201609/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201609/misc/upload_image.py | 66 +++ .../v201609/misc/upload_media_bundle.py | 59 ++ .../adwords/v201609/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 180 ++++++ ...aign_criterion_bid_modifier_simulations.py | 96 ++++ .../get_keyword_bid_simulations.py | 81 +++ .../v201609/optimization/get_keyword_ideas.py | 100 ++++ .../adwords/v201609/remarketing/__init__.py | 15 + .../v201609/remarketing/add_audience.py | 103 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_crm_based_user_list.py | 94 ++++ .../remarketing/add_rule_based_user_lists.py | 183 ++++++ .../upload_offline_call_conversions.py | 77 +++ .../remarketing/upload_offline_conversions.py | 75 +++ .../adwords/v201609/reporting/__init__.py | 15 + .../reporting/download_criteria_report.py | 61 ++ .../download_criteria_report_as_stream.py | 77 +++ ...oad_criteria_report_as_stream_with_awql.py | 81 +++ .../download_criteria_report_as_string.py | 59 ++ ...oad_criteria_report_as_string_with_awql.py | 55 ++ .../download_criteria_report_with_awql.py | 58 ++ .../v201609/reporting/get_report_fields.py | 52 ++ .../reporting/parallel_report_download.py | 230 ++++++++ examples/adwords/v201609/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 281 ++++++++++ .../v201609/shopping/add_product_scope.py | 104 ++++ .../v201609/shopping/add_shopping_campaign.py | 121 ++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201609/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 145 +++++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201609/targeting/lookup_location.py | 82 +++ .../get_availability_forecast.py | 132 +++++ ...get_availability_forecast_for_line_item.py | 63 +++ .../get_delivery_forecast_for_line_items.py | 52 ++ .../v201608/report_service/run_saved_query.py | 6 +- googleads/adwords.py | 50 +- googleads/common.py | 47 +- googleads/util.py | 91 +++ tests/adwords_test.py | 41 +- tests/common_test.py | 55 +- tests/util_test.py | 102 ++++ 110 files changed, 9914 insertions(+), 50 deletions(-) create mode 100644 examples/adwords/v201609/__init__.py create mode 100644 examples/adwords/v201609/account_management/__init__.py create mode 100755 examples/adwords/v201609/account_management/create_account.py create mode 100755 examples/adwords/v201609/account_management/get_account_changes.py create mode 100755 examples/adwords/v201609/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201609/advanced_operations/__init__.py create mode 100755 examples/adwords/v201609/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201609/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py create mode 100755 examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201609/basic_operations/__init__.py create mode 100755 examples/adwords/v201609/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201609/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201609/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201609/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201609/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201609/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201609/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201609/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201609/basic_operations/get_text_ads.py create mode 100755 examples/adwords/v201609/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201609/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201609/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201609/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201609/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201609/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201609/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201609/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201609/campaign_management/__init__.py create mode 100755 examples/adwords/v201609/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201609/campaign_management/add_draft.py create mode 100755 examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201609/campaign_management/add_trial.py create mode 100755 examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201609/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201609/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201609/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201609/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201609/error_handling/__init__.py create mode 100755 examples/adwords/v201609/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201609/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201609/extensions/__init__.py create mode 100755 examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201609/extensions/add_prices.py create mode 100755 examples/adwords/v201609/extensions/add_site_links.py create mode 100755 examples/adwords/v201609/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201609/migration/__init__.py create mode 100755 examples/adwords/v201609/migration/migrate_to_extension_settings.py create mode 100644 examples/adwords/v201609/misc/__init__.py create mode 100755 examples/adwords/v201609/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201609/misc/upload_image.py create mode 100755 examples/adwords/v201609/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201609/optimization/__init__.py create mode 100755 examples/adwords/v201609/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201609/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201609/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201609/remarketing/__init__.py create mode 100755 examples/adwords/v201609/remarketing/add_audience.py create mode 100755 examples/adwords/v201609/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201609/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201609/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201609/remarketing/upload_offline_call_conversions.py create mode 100755 examples/adwords/v201609/remarketing/upload_offline_conversions.py create mode 100644 examples/adwords/v201609/reporting/__init__.py create mode 100755 examples/adwords/v201609/reporting/download_criteria_report.py create mode 100755 examples/adwords/v201609/reporting/download_criteria_report_as_stream.py create mode 100755 examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201609/reporting/download_criteria_report_as_string.py create mode 100755 examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201609/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201609/reporting/get_report_fields.py create mode 100755 examples/adwords/v201609/reporting/parallel_report_download.py create mode 100644 examples/adwords/v201609/shopping/__init__.py create mode 100755 examples/adwords/v201609/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201609/shopping/add_product_scope.py create mode 100755 examples/adwords/v201609/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201609/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201609/targeting/__init__.py create mode 100755 examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201609/targeting/lookup_location.py create mode 100755 examples/dfp/v201608/forecast_service/get_availability_forecast.py create mode 100755 examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py create mode 100755 examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py diff --git a/ChangeLog b/ChangeLog index f7857cca..7530a5e4 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,11 @@ +4.6.1 -- 9/30/16: +* Added support for AdWords v201609. +* The library now automatically applies filters to log output to sanitize its + contents of sensitive data. For more details on how to configure logging or + disable log filtering, see the README. +* The library will now log warnings if it detects that it is being run with + Python versions below 2.7.9. + 4.5.1 -- 8/30/2016: * Resolved issue #148: https://github.com/googleads/googleads-python-lib/issues/148 diff --git a/README.md b/README.md index ab5c4505..df0fde24 100644 --- a/README.md +++ b/README.md @@ -104,13 +104,28 @@ for API change announcements and other news. The library uses Python's built in logging framework. If you wish to log your SOAP interactions to stdout, you can do the following: ```python -logging.basicConfig(level=logging.INFO) +logging.basicConfig(level=logging.INFO, format=googleads.util.LOGGER_FORMAT) logging.getLogger('suds.transport').setLevel(logging.DEBUG) ``` If you wish to log to a file, you'll need to attach a log handler to this source which is configured to write the output to a file. +##How do I disable log filters? +By default, this library will apply log filters to the `googleads.common`, +`suds.client`, and `suds.transport` loggers in order to omit sensitive data. If +you need to see this data in your logs, you can disable the filters with the +following: +```python +logging.getLogger('googleads.common').removeFilter( + googleads.util.GetGoogleAdsCommonFilter()) +logging.getLogger('suds.client').removeFilter( + googleads.util.GetSudsClientFilter()) +logging.getLogger('suds.transport').removeFilter( + googleads.util.GetSudsTransportFilter()) +``` + + ##I'm familiar with suds. Can I use suds features with this library? Yes, you can. The services returned by the `client.GetService()` functions all have a reference to the underlying suds client stored in the `suds_client` diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index 68cafb70..a45c8bbb 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -45,7 +45,7 @@ def __init__(self, client_id, client_secret, refresh_token, credentials = GoogleRefreshTokenClient(client_id, client_secret, refresh_token) self.client = AdWordsClient(dev_token, credentials, self._USER_AGENT, - manager_account_id) + client_customer_id=manager_account_id) def AddAdGroup(self, client_customer_id, campaign_id, name, status): """Create a new ad group. diff --git a/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py index b5c726f0..2fdfe030 100755 --- a/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py +++ b/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py @@ -16,7 +16,7 @@ """This example gets all expanded text ads for a given ad group. -To add an ad, run add_text_ads.py. +To add an expanded text ad, run add_expanded_text_ads.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home diff --git a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py index 2ae1d940..7cd152f9 100755 --- a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py +++ b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py @@ -16,7 +16,7 @@ """This example gets all expanded text ads for a given ad group. -To add an ad, run add_text_ads.py. +To add an expanded text ad, run add_expanded_text_ads.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home diff --git a/examples/adwords/v201609/__init__.py b/examples/adwords/v201609/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201609/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201609/account_management/__init__.py b/examples/adwords/v201609/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201609/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201609/account_management/create_account.py b/examples/adwords/v201609/account_management/create_account.py new file mode 100755 index 00000000..d1e80e07 --- /dev/null +++ b/examples/adwords/v201609/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201609') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/account_management/get_account_changes.py b/examples/adwords/v201609/account_management/get_account_changes.py new file mode 100755 index 00000000..a06d1d13 --- /dev/null +++ b/examples/adwords/v201609/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201609') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/account_management/get_account_hierarchy.py b/examples/adwords/v201609/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..ebac72e4 --- /dev/null +++ b/examples/adwords/v201609/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201609') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/advanced_operations/__init__.py b/examples/adwords/v201609/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..f3c8da4f --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py @@ -0,0 +1,221 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates ExpandedTextAds that use ad customizations for specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no ExpandedTextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService') + + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'headlinePart2': 'Only {=%s.Price}' % feed_name, + 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': expanded_text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..093acb78 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201609') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..3d406df7 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,126 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Optionally, you may specify a landscape image. The image needs to be in a + # BASE64 encoded form. Here we download a demo image and encode it for this + # ad. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + }, + { + 'name': 'landscapeImage', + 'fieldMedia': { + 'xsi_type': 'Image', + 'data': image_data + }, + 'type': 'IMAGE' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..8d039035 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -0,0 +1,109 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Create the expanded text ad + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': expanded_text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_html5_ad.py b/examples/adwords/v201609/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..e8582408 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/add_html5_ad.py @@ -0,0 +1,111 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..20fc2de5 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + media_service = client.GetService('MediaService', version='v201609') + + try: + # Create image. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + # Make the upload request + image = media_service.upload(image)[0] + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'] + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py new file mode 100755 index 00000000..47e07bd5 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py @@ -0,0 +1,214 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a Universal App campaign. + +To get campaigns, run get_campaigns.py. To upload image assets for this +campaign, run upload_image.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201609') + + budget_id = CreateBudget(client) + + # Create the Universal App campaign. + universal_app_campaign = { + 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'MULTI_CHANNEL', + 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', + # Set the campaign's bidding strategy. Universal app campaigns only + # support TARGET_CPA bidding strategy. + 'biddingStrategyConfiguration': { + # Set the target CPA to $1 / app install. + 'biddingScheme': { + 'xsi_type': 'TargetCpaBiddingScheme', + 'targetCpa': { + 'microAmount': '1000000' + } + }, + 'biddingStrategyType': 'TARGET_CPA' + }, + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + + universal_app_campaign['settings'] = [ + # Set the campaign's assets and ad text ideas. These values will + # be used to generate ads. + { + 'xsi_type': 'UniversalAppCampaignSetting', + 'appId': 'com.interplanetarycruise.booking', + 'description1': 'Best Space Cruise Line', + 'description2': 'Visit all the planets', + 'description3': 'Trips 7 days a week', + 'description4': 'Buy your tickets now!', + # Optional: You can set up to 10 image assets for your campaign. + # See upload_image.py for an example on how to upload images. + # + # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] + } + ] + + # Optimize this campaign for getting new users for your app. + universal_app_campaign_setting = universal_app_campaign['settings'][0] + universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( + 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') + + # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, + # then also specify your in-app conversion types so AdWords can focus your + # campaign on people who are most likely to complete the corresponding in-app + # actions. + # + # Conversions type IDs can be retrieved using ConversionTrackerService.get. + # universal_app_campaign['selectiveOptimization'] = { + # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] + # } + + # Optional: Set the campaign settings for Advanced location options. + universal_app_campaign['settings'].append({ + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + }) + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': universal_app_campaign + }] + + campaigns = campaign_service.mutate(operations)['value'] + + # Display results. + if campaigns: + for campaign in campaigns: + print ('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + # Optional: Set the campaign's location and language targeting. No other + # targeting criteria can be used for Universal App campaigns. + SetCampaignTargetingCriteria(client, campaign) + else: + print 'No Universal App campaigns were added.' + + +def CreateBudget(client): + """Creates a budget and returns its budgetId. + + Args: + client: An AdWordsClient instance. + + Returns: + An int budgetId for the created Budget. + """ + budget_service = client.GetService('BudgetService', version='v201609') + + # Create a budget. + budget = { + 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Create the budget and return its ID. + budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] + # [END createBudget] MOE_strip_line + + return budget_id + +def SetCampaignTargetingCriteria(client, campaign): + """Sets targeting criteria for the given campaign. + + Args: + client: An AdWordsClient instance. + campaign: A suds object representing the campaign we wish to attach + targeting criteria. + """ + campaign_criterion_service = client.GetService('CampaignCriterionService') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + criteria = [ + { + 'xsi_type': 'Location', + 'id': 21137 # California + }, + { + 'xsi_type': 'Location', + 'id': 2484 # Mexico + }, + { + 'xsi_type': 'Language', + 'id': 1000 # English + }, + { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + ] + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign['id'], + 'criterion': criterion + } + } for criterion in criteria] + + response = campaign_criterion_service.mutate(operations) + + if response and 'value' in response: + # Display the added campaign targets. + for criterion in response['value']: + print ('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], + criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..dc832cb3 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201609') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201609') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201609') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..01e0cb97 --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201609') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201609') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..eecb8c2e --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201609') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..509b097d --- /dev/null +++ b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201609') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201609') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201609') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201609/basic_operations/__init__.py b/examples/adwords/v201609/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201609/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201609/basic_operations/add_ad_groups.py b/examples/adwords/v201609/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..9f43d863 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201609') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/basic_operations/add_campaigns.py b/examples/adwords/v201609/basic_operations/add_campaigns.py new file mode 100755 index 00000000..fb8faa33 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/add_campaigns.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201609') + budget_service = client.GetService('BudgetService', version='v201609') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..233677a7 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/add_keywords.py b/examples/adwords/v201609/basic_operations/add_keywords.py new file mode 100755 index 00000000..b92fec27 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201609') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/get_ad_groups.py b/examples/adwords/v201609/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..b3273ea8 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201609') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/basic_operations/get_campaigns.py b/examples/adwords/v201609/basic_operations/get_campaigns.py new file mode 100755 index 00000000..9493c343 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/get_campaigns.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201609') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..fb210a3b --- /dev/null +++ b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201609') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..ddb84cb1 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an expanded text ad, run add_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/get_keywords.py b/examples/adwords/v201609/basic_operations/get_keywords.py new file mode 100755 index 00000000..8e8d38f0 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201609') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\' was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/get_text_ads.py b/examples/adwords/v201609/basic_operations/get_text_ads.py new file mode 100755 index 00000000..9518f0eb --- /dev/null +++ b/examples/adwords/v201609/basic_operations/get_text_ads.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2016 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 text ads for a given ad group. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/pause_ad.py b/examples/adwords/v201609/basic_operations/pause_ad.py new file mode 100755 index 00000000..5535f12b --- /dev/null +++ b/examples/adwords/v201609/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201609/basic_operations/remove_ad.py b/examples/adwords/v201609/basic_operations/remove_ad.py new file mode 100755 index 00000000..d40c1a8f --- /dev/null +++ b/examples/adwords/v201609/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201609/basic_operations/remove_ad_group.py b/examples/adwords/v201609/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..c0e2bacf --- /dev/null +++ b/examples/adwords/v201609/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201609') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/remove_campaign.py b/examples/adwords/v201609/basic_operations/remove_campaign.py new file mode 100755 index 00000000..f0912f81 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201609') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/basic_operations/remove_keyword.py b/examples/adwords/v201609/basic_operations/remove_keyword.py new file mode 100755 index 00000000..8448c248 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201609') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201609/basic_operations/update_ad_group.py b/examples/adwords/v201609/basic_operations/update_ad_group.py new file mode 100755 index 00000000..09d3bf1e --- /dev/null +++ b/examples/adwords/v201609/basic_operations/update_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201609') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/update_campaign.py b/examples/adwords/v201609/basic_operations/update_campaign.py new file mode 100755 index 00000000..167d1c42 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201609') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/basic_operations/update_keyword.py b/examples/adwords/v201609/basic_operations/update_keyword.py new file mode 100755 index 00000000..2fa0b419 --- /dev/null +++ b/examples/adwords/v201609/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201609') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201609/campaign_management/__init__.py b/examples/adwords/v201609/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201609/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201609/campaign_management/add_campaign_labels.py b/examples/adwords/v201609/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..7d1e52cd --- /dev/null +++ b/examples/adwords/v201609/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201609') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..6333790b --- /dev/null +++ b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,425 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201609') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201609') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding an ExpandedTextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new ExpandedTextAd for + each of the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201609') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201609/campaign_management/add_draft.py b/examples/adwords/v201609/campaign_management/add_draft.py new file mode 100755 index 00000000..fb64a48c --- /dev/null +++ b/examples/adwords/v201609/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + draft_service = client.GetService('DraftService', version='v201609') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201609') + + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..45fb351d --- /dev/null +++ b/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,259 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201609') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201609') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201609') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201609') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201609/campaign_management/add_trial.py b/examples/adwords/v201609/campaign_management/add_trial.py new file mode 100755 index 00000000..09058ad0 --- /dev/null +++ b/examples/adwords/v201609/campaign_management/add_trial.py @@ -0,0 +1,116 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201609') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201609') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..05860fe5 --- /dev/null +++ b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Construct selector and get all ads for a given ad group. + selector = { + 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'AdGroupCreativeApprovalStatus', + 'operator': 'IN', + 'values': ['DISAPPROVED'] + } + ] + } + ads = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..a94e3ff1 --- /dev/null +++ b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, AdGroupAdDisapprovalReasons ' + 'WHERE CampaignId = %s AND ' + 'AdGroupCreativeApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % campaign_id) + ads = ad_group_ad_service.query(query) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..6819ebca --- /dev/null +++ b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201609') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201609/campaign_management/graduate_trial.py b/examples/adwords/v201609/campaign_management/graduate_trial.py new file mode 100755 index 00000000..2ccd302b --- /dev/null +++ b/examples/adwords/v201609/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201609') + budget_service = client.GetService('BudgetService', version='v201609') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201609/campaign_management/set_ad_parameters.py b/examples/adwords/v201609/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..64c4d8ad --- /dev/null +++ b/examples/adwords/v201609/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_param_service = client.GetService('AdParamService', version='v201609') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..bba2fddd --- /dev/null +++ b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201609') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201609/campaign_management/validate_text_ad.py b/examples/adwords/v201609/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..9b277065 --- /dev/null +++ b/examples/adwords/v201609/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +No objects will be created, but exceptions will still be returned. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Construct operations to add an expanded text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'] + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for all astronauts in orbit', + 'finalUrls': ['http://www.example.com'], + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/error_handling/__init__.py b/examples/adwords/v201609/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201609/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201609/error_handling/handle_partial_failures.py b/examples/adwords/v201609/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..5f23a8a7 --- /dev/null +++ b/examples/adwords/v201609/error_handling/handle_partial_failures.py @@ -0,0 +1,120 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201609') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) + if index: + print ('Keyword ad group criterion with ad group id \'%s\' and text ' + '\'%s\' triggered a failure for the following reason: \'%s\'.' + % (keywords[int(index[0])]['adGroupId'], + keywords[int(index[0])]['criterion']['text'], + error['errorString'])) + else: + print 'The following failure has occurred: \'%s\'.' % error['errorString'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..6803cd0b --- /dev/null +++ b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py @@ -0,0 +1,114 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201609') + + # Create text ad. + text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'TextAd', + 'headline': 'Mars Cruise!!!', + 'description1': 'Visit the Red Planet in style.', + 'description2': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'www.example.com', + } + } + } + + operations = [text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + if error['ApiError.Type'] == 'PolicyViolationError': + operation_index = re.findall(r'operations\[(.*)\]\.', + error['fieldPath']) + if operation_index: + operation = operations[int(operation_index[0])] + print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % + (operation['operand']['ad']['headline'], + 'exemptable' if error['isExemptable'] else 'non-exemptable', + error['externalPolicyName'])) + if error['isExemptable'].lower() == 'true': + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text ' + '\'%s\'.' % + (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({ + 'key': error['key'] + }) + else: + # Remove non-exemptable operation + print 'Removing the operation from the request.' + operations.delete(operation) + else: + # Non-policy error returned, re-throw exception. + raise e + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/extensions/__init__.py b/examples/adwords/v201609/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201609/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..a4f2bb99 --- /dev/null +++ b/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201609').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201609') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201609/extensions/add_prices.py b/examples/adwords/v201609/extensions/add_prices.py new file mode 100755 index 00000000..a1a42caf --- /dev/null +++ b/examples/adwords/v201609/extensions/add_prices.py @@ -0,0 +1,144 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201609') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH') + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + return { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/extensions/add_site_links.py b/examples/adwords/v201609/extensions/add_site_links.py new file mode 100755 index 00000000..bf470bbd --- /dev/null +++ b/examples/adwords/v201609/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201609') + customer_service = client.GetService('CustomerService', version='v201609') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..9115c415 --- /dev/null +++ b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py @@ -0,0 +1,236 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_1_TEXT = '3' +PLACEHOLDER_FIELD_LINE_2_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201609') + feed_item_service = client.GetService('FeedItemService', version='v201609') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201609') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201609') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 1 Description'}, + {'type': 'STRING', 'name': 'Line 2 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_1_feed_attribute_id = feed['attributes'][2]['id'] + line_2_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % + (line_1_feed_attribute_id, line_2_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line1FeedId'] = line_1_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line1': 'Home line 1', 'line2': 'Home line 2'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line1': 'Support line 1', 'line2': 'Support line 2'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line1': 'Products line 1', 'line2': 'Products line 2'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'stringValue': item['line1'] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + feed_item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/migration/__init__.py b/examples/adwords/v201609/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201609/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201609/migration/migrate_to_extension_settings.py b/examples/adwords/v201609/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..cae2dc68 --- /dev/null +++ b/examples/adwords/v201609/migration/migrate_to_extension_settings.py @@ -0,0 +1,527 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201609') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201609') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201609') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201609') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201609') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201609') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201609') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/misc/__init__.py b/examples/adwords/v201609/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201609/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201609/misc/get_all_images_and_videos.py b/examples/adwords/v201609/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..9ac21269 --- /dev/null +++ b/examples/adwords/v201609/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201609') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/misc/upload_image.py b/examples/adwords/v201609/misc/upload_image.py new file mode 100755 index 00000000..ef13ff54 --- /dev/null +++ b/examples/adwords/v201609/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201609') + + with open(image_filename, 'r') as image_handle: + image_data = base64.encodestring(image_handle.read()) + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201609/misc/upload_media_bundle.py b/examples/adwords/v201609/misc/upload_media_bundle.py new file mode 100755 index 00000000..224a0095 --- /dev/null +++ b/examples/adwords/v201609/misc/upload_media_bundle.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201609') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/optimization/__init__.py b/examples/adwords/v201609/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201609/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py b/examples/adwords/v201609/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..3f937af9 --- /dev/null +++ b/examples/adwords/v201609/optimization/estimate_keyword_traffic.py @@ -0,0 +1,180 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201609') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..4258a0ac --- /dev/null +++ b/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201609') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..b1a478d1 --- /dev/null +++ b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201609') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201609/optimization/get_keyword_ideas.py b/examples/adwords/v201609/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..9cc80081 --- /dev/null +++ b/examples/adwords/v201609/optimization/get_keyword_ideas.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201609') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }, + { + # Network search parameter (optional) + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/__init__.py b/examples/adwords/v201609/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201609/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201609/remarketing/add_audience.py b/examples/adwords/v201609/remarketing/add_audience.py new file mode 100755 index 00000000..fa0c3527 --- /dev/null +++ b/examples/adwords/v201609/remarketing/add_audience.py @@ -0,0 +1,103 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201609') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201609') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/add_conversion_tracker.py b/examples/adwords/v201609/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..81df219a --- /dev/null +++ b/examples/adwords/v201609/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201609') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py b/examples/adwords/v201609/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..92967601 --- /dev/null +++ b/examples/adwords/v201609/remarketing/add_crm_based_user_list.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client, emails): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201609') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180 + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + hashed_emails = HashEmails(emails) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'dataType': 'EMAIL_SHA256', + 'members': hashed_emails + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def HashEmails(emails): + """Hashes the given emails using SHA-256. + + Note: Emails are stripped of any whitespace and set to lowercase before + hashing. + + Args: + emails: list of str emails to be hashed. + + Returns: + A list of SHA-256 hashed emails. + """ + return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + + +if __name__ == '__main__': + EMAILS = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, EMAILS) diff --git a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..6ea515dd --- /dev/null +++ b/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,183 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201609') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords will logically OR the + # groups together. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py new file mode 100755 index 00000000..970a1624 --- /dev/null +++ b/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Imports offline conversion values for calls related to ads in your account. + +To set up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CALLER_ID = 'INSERT_CALLER_ID_HERE' +# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats +# For time zones, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +CALL_START_TIME = 'INSERT_CALL_START_TIME' +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, caller_id, call_start_time, conversion_name, conversion_time, + conversion_value): + # Initialize appropriate services. + occ_feed_service = client.GetService( + 'OfflineCallConversionFeedService', version='v201609') + + # Associate offline call conversions with the existing named conversion + # tracker. If this tracker was newly created, it may be a few hours before it + # can accept conversions. + feed = { + 'callerId': caller_id, + 'callStartTime': call_start_time, + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + } + + occ_operations = [{'operator': 'ADD', 'operand': feed}] + + occ_response = occ_feed_service.mutate(occ_operations) + values = occ_response['value'] + + if values: + for occ_feed in values: + print ('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + else: + print 'No offline call conversions were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, + CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201609/remarketing/upload_offline_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..770b3316 --- /dev/null +++ b/examples/adwords/v201609/remarketing/upload_offline_conversions.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201609') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201609/reporting/__init__.py b/examples/adwords/v201609/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201609/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201609/reporting/download_criteria_report.py b/examples/adwords/v201609/reporting/download_criteria_report.py new file mode 100755 index 00000000..fc905bd8 --- /dev/null +++ b/examples/adwords/v201609/reporting/download_criteria_report.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201609') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py new file mode 100755 index 00000000..0480f69c --- /dev/null +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201609') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..c67d71d7 --- /dev/null +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201609') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py new file mode 100755 index 00000000..ceb11acb --- /dev/null +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201609') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..a589a321 --- /dev/null +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201609') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..b627e3ed --- /dev/null +++ b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client, path): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201609') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + with open(path, 'w') as output_file: + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', output_file, skip_report_header=False, + skip_column_header=False, skip_report_summary=False) + + print 'Report was downloaded to \'%s\'.' % path + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, PATH) diff --git a/examples/adwords/v201609/reporting/get_report_fields.py b/examples/adwords/v201609/reporting/get_report_fields.py new file mode 100755 index 00000000..c1b4adb5 --- /dev/null +++ b/examples/adwords/v201609/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201609') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201609/reporting/parallel_report_download.py b/examples/adwords/v201609/reporting/parallel_report_download.py new file mode 100755 index 00000000..48c01a2c --- /dev/null +++ b/examples/adwords/v201609/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201609') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201609') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201609/shopping/__init__.py b/examples/adwords/v201609/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201609/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201609/shopping/add_product_partition_tree.py b/examples/adwords/v201609/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..08c292fc --- /dev/null +++ b/examples/adwords/v201609/shopping/add_product_partition_tree.py @@ -0,0 +1,281 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201609') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201609/shopping/add_product_scope.py b/examples/adwords/v201609/shopping/add_product_scope.py new file mode 100755 index 00000000..086bb76a --- /dev/null +++ b/examples/adwords/v201609/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201609') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/shopping/add_shopping_campaign.py b/examples/adwords/v201609/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..0df5099b --- /dev/null +++ b/examples/adwords/v201609/shopping/add_shopping_campaign.py @@ -0,0 +1,121 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id): + campaign_service = client.GetService('CampaignService', version='v201609') + ad_group_service = client.GetService('AdGroupService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + adgroup = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group_result = ad_group_service.mutate(adgroup_operations) + + for adgroup in ad_group_result['value']: + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (adgroup['name'], adgroup['id'])) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': adgroup['id'], + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py b/examples/adwords/v201609/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..10762989 --- /dev/null +++ b/examples/adwords/v201609/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201609') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/targeting/__init__.py b/examples/adwords/v201609/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201609/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..6e80f55c --- /dev/null +++ b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,145 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201609') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create location groups. The IDs can be found in the documentation or + # retrieved with the LocationCriterionService. + florida_tier3 = { + 'xsi_type': 'LocationGroups', + 'matchingFunction': { + 'operator': 'AND', + 'lhsOperand': [{ + 'xsi_type': 'IncomeOperand', + # Tiers are numbered 1-10, and represent 10% segments of earners. + # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. + # Tiers 6 through 10 are grouped into TIER_6_TO_10. + 'tier': 'TIER_3' + }], + 'rhsOperand': [{ + 'xsi_type': 'GeoTargetOperand', + 'locations': [1015116] # Miami, FL + }] + }, + } + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish, florida_tier3] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..dae2b6b3 --- /dev/null +++ b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201609') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..b29d7b11 --- /dev/null +++ b/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201609') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..958862f7 --- /dev/null +++ b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201609') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/targeting/lookup_location.py b/examples/adwords/v201609/targeting/lookup_location.py new file mode 100755 index 00000000..e2986dd5 --- /dev/null +++ b/examples/adwords/v201609/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201609') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/dfp/v201608/forecast_service/get_availability_forecast.py b/examples/dfp/v201608/forecast_service/get_availability_forecast.py new file mode 100755 index 00000000..c2f74c3a --- /dev/null +++ b/examples/dfp/v201608/forecast_service/get_availability_forecast.py @@ -0,0 +1,132 @@ +#!/usr/bin/python +# +# Copyright 2015 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 a forecast for a prospective line item. + +The prospective line item targets the entire network. The targeting can be +modified to determine forecasts for other criteria such as custom criteria +targeting (in addition to targeting the whole network). See +create_line_items.py for an example of how to create more complex targeting. + +""" + + +from datetime import date + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201608') + network_service = client.GetService('NetworkService', version='v201608') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + + # Create prospective line item. + line_item = { + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + } + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + } + }, + { + 'size': { + 'width': '120', + 'height': '600' + } + } + ], + 'lineItemType': 'SPONSORSHIP', + 'startDateTimeType': 'IMMEDIATELY', + 'endDateTime': { + 'date': { + 'year': str(date.today().year + 1), + 'month': '9', + 'day': '30' + }, + 'hour': '0', + 'minute': '0', + 'second': '0', + 'timeZoneID': 'America/New_York' + }, + 'costType': 'CPM', + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'primaryGoal': { + 'units': '50', + 'unitType': 'IMPRESSIONS', + 'goalType': 'DAILY' + }, + 'contractedUnitsBought': '100', + 'creativeRotationType': 'EVEN', + 'discountType': 'PERCENTAGE', + } + + prospective_line_item = { + 'lineItem': line_item, + 'advertiserId': advertiser_id + } + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } + + # Get forecast. + forecast = forecast_service.getAvailabilityForecast( + prospective_line_item, forecast_options) + matched = long(forecast['matchedUnits']) + available_percent = (((long(forecast['availableUnits'])/ + (matched * 1.0)) * 100) + if matched != 0 else 0) + contending_line_items = ([] if 'contendingLineItems' not in forecast + else forecast['contendingLineItems']) + + # Display results. + print '%s %s matched.' % (matched, forecast['unitType'].lower()) + print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) + print '%d contending line items.' % len(contending_line_items) + + if 'possibleUnits' in forecast and matched: + possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID) diff --git a/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py new file mode 100755 index 00000000..a23ba2fb --- /dev/null +++ b/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets an availability forecast for an existing line item. + +To determine which line items exist, run get_all_line_items.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the line item to get a forecast for. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client, line_item_id): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201608') + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } + + # Get forecast for line item. + forecast = forecast_service.getAvailabilityForecastById( + line_item_id, forecast_options) + matched = long(forecast['matchedUnits']) + available_percent = (((long(forecast['availableUnits'])/ + (matched * 1.0)) * 100) + if matched != 0 else 0) + contending_line_items = ([] if 'contendingLineItems' not in forecast + else forecast['contendingLineItems']) + + # Display results. + print '%s %s matched.' % (matched, forecast['unitType'].lower()) + print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) + print '%d contending line items.' % len(contending_line_items) + + if 'possibleUnits' in forecast and matched: + possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py new file mode 100755 index 00000000..e70a7bea --- /dev/null +++ b/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example gets a delivery forecast for two existing line items. + +To determine which line items exist, run get_all_line_items.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the line items to get forecasts for. +LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' +LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE' + + +def main(client, line_item_id1, line_item_id2): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201608') + + # Get forecast for line item. + forecast = forecast_service.getDeliveryForecastByIds( + [line_item_id1, line_item_id2], None) + + for single_forecast in forecast['lineItemDeliveryForecasts']: + unit_type = single_forecast['unitType'] + print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( + single_forecast['lineItemId'], single_forecast['matchedUnits'], + unit_type, single_forecast['deliveredUnits'], unit_type, + single_forecast['predictedDeliveryUnits'], unit_type)) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201608/report_service/run_saved_query.py b/examples/dfp/v201608/report_service/run_saved_query.py index 3b8000d6..c7987626 100755 --- a/examples/dfp/v201608/report_service/run_saved_query.py +++ b/examples/dfp/v201608/report_service/run_saved_query.py @@ -41,11 +41,11 @@ def main(client, saved_query_id): 'value': saved_query_id } }] - filter_statement = {'query': 'WHERE id = :id', - 'values': values} + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) response = report_service.getSavedQueriesByStatement( - filter_statement.ToStatement()) + statement.ToStatement()) if 'results' in response: saved_query = response['results'][0] diff --git a/googleads/adwords.py b/googleads/adwords.py index 48dd1ad0..c19d05f8 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -173,6 +173,52 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201609': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineCallConversionFeedService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } @@ -308,6 +354,7 @@ def __init__(self, developer_token, oauth2_client, self.proxy_config = (proxy_config if proxy_config else googleads.common.ProxyConfig()) self.report_download_headers = kwargs.get('report_download_headers', {}) + self.message_plugin = googleads.common.LoggingMessagePlugin() def GetService(self, service_name, version=None, server=None): """Creates a service client for the given service. @@ -351,7 +398,8 @@ def GetService(self, service_name, version=None, server=None): self._SOAP_SERVICE_FORMAT % (server, version_service_mapping, version, service_name), cache=self.cache, timeout=3600, - transport=self.proxy_config.GetSudsProxyTransport()) + transport=self.proxy_config.GetSudsProxyTransport(), + plugins=[self.message_plugin]) return googleads.common.SudsServiceProxy( client, _AdWordsHeaderHandler(self, version)) diff --git a/googleads/common.py b/googleads/common.py index c76c1e2f..fa7d56a4 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -17,6 +17,7 @@ from functools import wraps import inspect +import logging import os import ssl import sys @@ -43,13 +44,28 @@ pass -VERSION = '4.5.1' +logging.getLogger('suds.client').addFilter(googleads.util.GetSudsClientFilter()) +logging.getLogger('suds.transport.http').addFilter( + googleads.util.GetSudsTransportFilter()) +_logger = logging.getLogger(__name__) +_logger.addFilter(googleads.util.GetGoogleAdsCommonFilter()) + +_PY_VERSION_MAJOR = sys.version_info.major +_PY_VERSION_MINOR = sys.version_info.minor +_PY_VERSION_MICRO = sys.version_info.micro +_DEPRECATED_VERSION_TEMPLATE = ( + 'This library is being run by an unsupported Python version (%s.%s.%s). In ' + 'order to benefit from important security improvements and ensure ' + 'compatibility with this library, upgrade to Python 2.7.9 or higher.') + + +VERSION = '4.6.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' _PROXY_CONFIG_KEY = 'proxy_config' -_PYTHON_VERSION = 'Python/%d.%d.%d' % (sys.version_info[0], sys.version_info[1], - sys.version_info[2]) +_PYTHON_VERSION = 'Python/%d.%d.%d' % ( + _PY_VERSION_MAJOR, _PY_VERSION_MINOR, _PY_VERSION_MICRO) # The keys in the authentication dictionary that are used to construct OAuth2 # credentials. @@ -117,6 +133,15 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, information necessary to instantiate a client object - either a required_client_values key was missing or an OAuth2 key was missing. """ + # Warn users on deprecated Python versions on initialization. + if _PY_VERSION_MAJOR == 2: + if _PY_VERSION_MINOR == 7 and _PY_VERSION_MICRO < 9: + _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, + _PY_VERSION_MINOR, _PY_VERSION_MICRO) + elif _PY_VERSION_MINOR < 7: + _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, + _PY_VERSION_MINOR, _PY_VERSION_MICRO) + if not os.path.isabs(path): path = os.path.expanduser(path) try: @@ -613,8 +638,13 @@ def _CreateMethod(self, method_name): def MakeSoapRequest(*args): """Perform a SOAP call.""" self._header_handler.SetHeaders(self.suds_client) - return soap_service_method(*[_PackForSuds(arg, self.suds_client.factory) - for arg in args]) + try: + return soap_service_method(*[_PackForSuds(arg, self.suds_client.factory) + for arg in args]) + except suds.WebFault as e: + _logger.error('Server raised fault in response.') + _logger.info('Failure response:\n%s', e.document) + raise e return MakeSoapRequest @@ -625,3 +655,10 @@ class HeaderHandler(object): def SetHeaders(self, client): """Sets the SOAP and HTTP headers on the given suds client.""" raise NotImplementedError('You must subclass HeaderHandler.') + + +class LoggingMessagePlugin(suds.plugin.MessagePlugin): + """A MessagePlugin used to log request summaries.""" + + def sending(self, context): + _logger.info('Request made.') diff --git a/googleads/util.py b/googleads/util.py index 3324a06c..125e942b 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -14,11 +14,40 @@ """Utilities used by the client library.""" +import logging +import re import threading import suds +_COMMON_FILTER = None +_SUDS_CLIENT_FILTER = None +_SUDS_TRANSPORT_FILTER = None +LOGGER_FORMAT = '[%(asctime)s - %(name)s - %(levelname)s] %(message)s' + + +def GetGoogleAdsCommonFilter(): + global _COMMON_FILTER + if not _COMMON_FILTER: + _COMMON_FILTER = _GoogleAdsCommonFilter() + return _COMMON_FILTER + + +def GetSudsClientFilter(): + global _SUDS_CLIENT_FILTER + if not _SUDS_CLIENT_FILTER: + _SUDS_CLIENT_FILTER = _SudsClientFilter() + return _SUDS_CLIENT_FILTER + + +def GetSudsTransportFilter(): + global _SUDS_TRANSPORT_FILTER + if not _SUDS_TRANSPORT_FILTER: + _SUDS_TRANSPORT_FILTER = _SudsTransportFilter() + return _SUDS_TRANSPORT_FILTER + + class PatchHelper(object): """Utility that applies patches on behalf of the Google Ads Client Library.""" @@ -44,6 +73,68 @@ def PatchedAppend(self, parent, content): suds.mx.appender.ObjectAppender.append = PatchedAppend +class _AbstractDevTokenSOAPFilter(logging.Filter): + """Interface for sanitizing logs containing SOAP request/response data.""" + + _AUTHORIZATION_HEADER = 'Authorization' + _DEVELOPER_TOKEN_SUB = re.compile( + r'(?<=\).*?(?=\)') + _OMITTED = 'OMITTED' + + def filter(self, record): + raise NotImplementedError('You must implement filter().') + + +class _GoogleAdsCommonFilter(_AbstractDevTokenSOAPFilter): + """Removes sensitive data from logs generated by googleads.common.""" + + def filter(self, record): + if record.levelno == logging.INFO and record.args: + content = record.args[0].str() + content = self._DEVELOPER_TOKEN_SUB.sub(self._OMITTED, content) + record.args = (content,) + return True + + +class _SudsClientFilter(_AbstractDevTokenSOAPFilter): + """Removes sensitive data from logs generated by suds.client.""" + _SUDS_CLIENT_SOAP_MSG = 'sending to (%s)\nmessage:\n%s' + _SUDS_CLIENT_HEADERS_MSG = 'headers = %s' + + def filter(self, record): + args = record.args + if record.msg == self._SUDS_CLIENT_SOAP_MSG: + # If the original suds.sax.document.Document is modified, that will also + # modify the request itself. Instead, replace it with its sanitized text. + record.args = (args[0], self._DEVELOPER_TOKEN_SUB.sub( + self._OMITTED, args[1].str())) + elif record.msg == self._SUDS_CLIENT_HEADERS_MSG: + sanitized_headers = record.args.copy() + if self._AUTHORIZATION_HEADER in sanitized_headers: + sanitized_headers[self._AUTHORIZATION_HEADER] = self._OMITTED + record.args = sanitized_headers + return True + + +class _SudsTransportFilter(_AbstractDevTokenSOAPFilter): + """Removes sensitive data from logs generated by suds.transport.""" + + def filter(self, record): + if record.args: + arg = record.args[0] + if isinstance(arg, suds.transport.Request): + new_arg = suds.transport.Request(arg.url) + sanitized_headers = arg.headers.copy() + if self._AUTHORIZATION_HEADER in sanitized_headers: + sanitized_headers[self._AUTHORIZATION_HEADER] = self._OMITTED + new_arg.headers = sanitized_headers + new_arg.message = self._DEVELOPER_TOKEN_SUB.sub( + self._OMITTED, arg.message.decode('utf-8')) + record.args = (new_arg,) + + return True + + class UtilityRegistry(object): """Utility that registers product utilities used in generating a request.""" diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 3875e592..90d428ec 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -292,38 +292,41 @@ def testLoadFromStorageWithNoUserAgent(self): self.assertEquals(client.user_agent, 'unknown') def testGetService_success(self): - version = CURRENT_VERSION - service = googleads.adwords._SERVICE_MAP[version].keys()[0] - namespace = googleads.adwords._SERVICE_MAP[version][service] - mock_transport_instance = mock.Mock() - + service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use a custom server. Also test what happens if the server ends with a # trailing slash server = 'https://testing.test.com/' - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' - ) as mock_transport: - mock_transport.return_value = mock_transport_instance - suds_service = self.aw_client.GetService( - service, version, server) - mock_client.assert_called_once_with( - 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, version, service), cache=self.cache, - transport=mock_transport_instance, timeout=3600) + with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: + with mock.patch('suds.client.Client') as mock_client: + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' + ) as mock_transport: + mock_plugin.return_value = mock.Mock() + mock_transport.return_value = mock.Mock() + client = GetAdWordsClient() + suds_service = client.GetService( + service, CURRENT_VERSION, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' + % (namespace, CURRENT_VERSION, service), cache=self.cache, + transport=mock_transport.return_value, timeout=3600, + plugins=[mock_plugin.return_value]) self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) # Use the default server without a proxy. with mock.patch('suds.client.Client') as mock_client: with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' ) as mock_transport: - mock_transport.return_value = mock_transport_instance - suds_service = self.adwords_client.GetService(service, version) + mock_transport.return_value = mock.Mock() + suds_service = client.GetService(service, CURRENT_VERSION) mock_client.assert_called_once_with( 'https://adwords.google.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, version, service), cache=self.cache, - transport=mock_transport_instance, timeout=3600) + % (namespace, CURRENT_VERSION, service), cache=self.cache, + transport=mock_transport.return_value, timeout=3600, + plugins=[mock_plugin.return_value]) self.assertFalse(mock_client.return_value.set_options.called) self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) diff --git a/tests/common_test.py b/tests/common_test.py index 0c708345..118f1278 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -84,6 +84,24 @@ def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): return yaml_file.name + def testLoadFromStorage_deprecatedWarningLogger(self): + yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e'}}, + 'one', self._OAUTH_INSTALLED_APP_DICT) + test_major_value = 2 + test_minor_value = 7 + test_micro_value = 6 + with mock.patch('googleads.common._PY_VERSION_MAJOR', test_major_value): + with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): + with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): + with mock.patch('googleads.common._logger') as mock_logger: + with mock.patch('googleads.common.open', self.fake_open, + create=True): + googleads.common.LoadFromStorage(yaml_fname, 'one', + ['needed', 'keys'], ['other']) + mock_logger.warning.assert_called_once_with( + googleads.common._DEPRECATED_VERSION_TEMPLATE, + test_major_value, test_minor_value, test_micro_value) + def testLoadFromStorage_missingFile(self): with mock.patch('googleads.common.open', self.fake_open, create=True): self.assertRaises( @@ -594,29 +612,30 @@ def testPackForSuds_secondNamespace(self): class SudsServiceProxyTest(unittest.TestCase): """Tests for the googleads.common.SudsServiceProxy class.""" + def setUp(self): + self.header_handler = mock.Mock() + self.port = mock.Mock() + self.port.methods = ('SoapMethod',) + self.services = mock.Mock() + self.services.ports = [self.port] + self.client = mock.Mock() + self.client.wsdl.services = [self.services] + self.suds_service_wrapper = googleads.common.SudsServiceProxy( + self.client, self.header_handler) + def testSudsServiceProxy(self): - header_handler = mock.Mock() - port = mock.Mock() - port.methods = ('SoapMethod',) - services = mock.Mock() - services.ports = [port] - client = mock.Mock() - client.wsdl.services = [services] - suds_service_wrapper = googleads.common.SudsServiceProxy( - client, header_handler) - - self.assertEqual(suds_service_wrapper.SoapMethod, - suds_service_wrapper._method_proxies['SoapMethod']) - self.assertEqual(suds_service_wrapper.NotSoapMethod, - client.service.NotSoapMethod) + self.assertEqual(self.suds_service_wrapper.SoapMethod, + self.suds_service_wrapper._method_proxies['SoapMethod']) + self.assertEqual(self.suds_service_wrapper.NotSoapMethod, + self.client.service.NotSoapMethod) with mock.patch('googleads.common._PackForSuds') as mock_pack_for_suds: mock_pack_for_suds.return_value = 'modified_test' - suds_service_wrapper.SoapMethod('test') - mock_pack_for_suds.assert_called_once_with('test', client.factory) + self.suds_service_wrapper.SoapMethod('test') + mock_pack_for_suds.assert_called_once_with('test', self.client.factory) - client.service.SoapMethod.assert_called_once_with('modified_test') - header_handler.SetHeaders.assert_called_once_with(client) + self.client.service.SoapMethod.assert_called_once_with('modified_test') + self.header_handler.SetHeaders.assert_called_once_with(self.client) class HeaderHandlerTest(unittest.TestCase): diff --git a/tests/util_test.py b/tests/util_test.py index 375adc20..2efd9831 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -14,6 +14,8 @@ """Unit tests to cover the errors module.""" +import logging +import os import re import unittest from xml.etree import ElementTree @@ -24,6 +26,7 @@ import googleads.dfp import googleads.util import mock +import suds.transport class PatchesTest(unittest.TestCase): @@ -135,5 +138,104 @@ def testPatchedSudsJurkoAppenderIssue78(self): self.assertTrue(tracking_url_template is not None) +class GoogleAdsCommonFilterTest(unittest.TestCase): + """Tests for the GoogleAdsCommonFilter utility.""" + + def setUp(self): + self.filter = googleads.util.GetGoogleAdsCommonFilter() + self.omitted_text = 'OMITTED' + self.dev_token_template = ('%s') + + def testGetGoogleAdsCommonFilter(self): + self.assertIs(self.filter, googleads.util.GetGoogleAdsCommonFilter()) + + def testFilterAtInfoLevel(self): + record = mock.Mock() + record.levelno = logging.INFO + record.args = [self.dev_token_template % 'test'] + self.filter.filter(record) + self.assertEqual( + record.args, (self.dev_token_template % self.omitted_text,)) + + def testFilterAtUnfilteredLevel(self): + expected_args = (1, 2, 3, 4, 5) + record = mock.Mock() + record.levelno = logging.DEBUG + record.args = expected_args + self.filter.filter(record) + self.assertEqual(record.args, expected_args) + + +class SudsClientFilterTest(unittest.TestCase): + """Tests for the SudsClientFilter utility.""" + + def setUp(self): + self.filter = googleads.util.GetSudsClientFilter() + self.omitted_text = 'OMITTED' + self.dev_token_template = 'DevToken' + self.location = 'https://www.google.com' + test_dir = os.path.dirname(__file__) + with open(os.path.join( + test_dir, 'test_data/request_envelope_template.txt'), 'r') as handler: + self.test_request_envelope_template = handler.read() + + def testGetSudsClientFilter(self): + self.assertIs(self.filter, googleads.util.GetSudsClientFilter()) + + def testFilterWithSudsClientSOAPMessage(self): + record = mock.Mock() + soapenv = mock.Mock() + soapenv.str.return_value = (self.test_request_envelope_template + % self.dev_token_template) + record.msg = 'sending to (%s)\nmessage:\n%s' + record.args = [self.location, soapenv] + self.filter.filter(record) + self.assertEqual(record.args, (self.location, + (self.test_request_envelope_template + % self.omitted_text))) + + def testFilterWithSudsClientHeadersMessage(self): + record = mock.Mock() + record.msg = 'headers = %s' + record.args = {'Content-Type': 'text/xml; charset=utf-8', + 'Authorization': 'Bearer abc123doremi'} + expected_args = {'Content-Type': 'text/xml; charset=utf-8', + 'Authorization': self.omitted_text} + self.filter.filter(record) + self.assertEqual(record.args, expected_args) + + +class SudsTransportFilterTest(unittest.TestCase): + """Tests for the SudsTransportFilter utility.""" + + def setUp(self): + self.filter = googleads.util.GetSudsTransportFilter() + self.omitted_text = 'OMITTED' + self.dev_token_template = 'DevToken' + self.location = 'https://www.google.com' + test_dir = os.path.dirname(__file__) + with open(os.path.join( + test_dir, 'test_data/request_envelope_template.txt'), 'r') as handler: + self.test_request_envelope_template = handler.read() + + def testGetSudsTransportFilter(self): + self.assertIs(self.filter, googleads.util.GetSudsTransportFilter()) + + def testFilterSudsTransportRequest(self): + request_instance = suds.transport.Request('https://www.google.com') + request_instance.headers = {'User-Agent': 'user-agent', + 'Authorization': 'abc123doremi'} + request_instance.message = (self.test_request_envelope_template % + self.dev_token_template) + expected_headers = {'User-Agent': 'user-agent', + 'Authorization': self.omitted_text} + record = mock.Mock() + record.args = (request_instance,) + self.filter.filter(record) + self.assertEqual(record.args[0].headers, expected_headers) + self.assertEqual(record.args[0].message, + self.test_request_envelope_template % self.omitted_text) + + if __name__ == '__main__': unittest.main() From be8414b243065c77aa39de38776c0039ef4d42b2 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 3 Oct 2016 17:59:50 -0400 Subject: [PATCH 051/180] Commiting latest changes. From 58478eebc5627eb455adb5156edbc77b12585f46 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 25 Oct 2016 17:48:42 -0400 Subject: [PATCH 052/180] AdWords v201603 sunset. --- ChangeLog | 3 + examples/adwords/v201603/__init__.py | 15 - .../v201603/account_management/__init__.py | 15 - .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 99 ---- .../get_account_hierarchy.py | 104 ---- .../v201603/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 222 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 108 ---- .../advanced_operations/add_html5_ad.py | 111 ---- .../add_text_ad_with_upgraded_urls.py | 111 ---- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 171 ------ .../v201603/basic_operations/__init__.py | 15 - .../v201603/basic_operations/add_ad_groups.py | 115 ---- .../v201603/basic_operations/add_campaigns.py | 125 ----- .../v201603/basic_operations/add_keywords.py | 92 --- .../v201603/basic_operations/add_text_ads.py | 93 ---- .../v201603/basic_operations/get_ad_groups.py | 76 --- .../v201603/basic_operations/get_campaigns.py | 74 --- .../get_campaigns_with_awql.py | 64 --- .../v201603/basic_operations/get_keywords.py | 87 --- .../v201603/basic_operations/get_text_ads.py | 80 --- .../v201603/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 58 -- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201603/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 426 -------------- .../v201603/campaign_management/add_draft.py | 81 --- .../campaign_management/add_experiment.py | 127 ----- ...dd_keywords_using_incremental_batch_job.py | 259 --------- .../v201603/campaign_management/add_trial.py | 117 ---- .../get_all_disapproved_ads.py | 74 --- .../get_all_disapproved_ads_with_awql.py | 63 --- .../get_campaigns_by_label.py | 85 --- .../campaign_management/graduate_trial.py | 79 --- .../campaign_management/promote_experiment.py | 60 -- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201603/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 120 ---- .../handle_policy_violation_error.py | 114 ---- .../adwords/v201603/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 ------ .../v201603/extensions/add_site_links.py | 134 ----- .../extensions/add_site_links_using_feeds.py | 233 -------- .../adwords/v201603/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 ------------------ .../v201603/migration/upgrade_ad_url.py | 79 --- examples/adwords/v201603/misc/__init__.py | 15 - .../v201603/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201603/misc/upload_image.py | 66 --- .../v201603/misc/upload_media_bundle.py | 59 -- .../adwords/v201603/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 133 ----- ...aign_criterion_bid_modifier_simulations.py | 96 ---- .../get_keyword_bid_simulations.py | 81 --- .../v201603/optimization/get_keyword_ideas.py | 100 ---- .../adwords/v201603/remarketing/__init__.py | 15 - .../v201603/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 70 --- .../remarketing/add_crm_based_user_list.py | 94 ---- .../remarketing/add_rule_based_user_lists.py | 183 ------ .../remarketing/upload_offline_conversions.py | 75 --- .../adwords/v201603/reporting/__init__.py | 15 - .../reporting/download_criteria_report.py | 61 -- .../download_criteria_report_as_stream.py | 77 --- ...oad_criteria_report_as_stream_with_awql.py | 81 --- .../download_criteria_report_as_string.py | 59 -- ...oad_criteria_report_as_string_with_awql.py | 55 -- .../download_criteria_report_with_awql.py | 58 -- .../v201603/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 230 -------- examples/adwords/v201603/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 281 ---------- .../v201603/shopping/add_product_scope.py | 104 ---- .../v201603/shopping/add_shopping_campaign.py | 121 ---- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201603/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 161 ------ .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201603/targeting/lookup_location.py | 82 --- .../accept_service_link.py} | 37 +- .../add_universal_app_campaign.py | 3 + .../v201609/basic_operations/add_campaigns.py | 3 + .../add_complete_campaigns_using_batch_job.py | 3 + .../v201609/shopping/add_shopping_campaign.py | 4 + googleads/adwords.py | 46 -- googleads/common.py | 2 +- googleads/oauth2.py | 16 +- tests/oauth2_test.py | 6 +- 102 files changed, 50 insertions(+), 8918 deletions(-) delete mode 100644 examples/adwords/v201603/__init__.py delete mode 100644 examples/adwords/v201603/account_management/__init__.py delete mode 100755 examples/adwords/v201603/account_management/create_account.py delete mode 100755 examples/adwords/v201603/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201603/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201603/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201603/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201603/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201603/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201603/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201603/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201603/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201603/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201603/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201603/basic_operations/__init__.py delete mode 100755 examples/adwords/v201603/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201603/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201603/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201603/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201603/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201603/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201603/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201603/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201603/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201603/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201603/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201603/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201603/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201603/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201603/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201603/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201603/campaign_management/__init__.py delete mode 100755 examples/adwords/v201603/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201603/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201603/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201603/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201603/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201603/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201603/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201603/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201603/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201603/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201603/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201603/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201603/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201603/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201603/error_handling/__init__.py delete mode 100755 examples/adwords/v201603/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201603/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201603/extensions/__init__.py delete mode 100755 examples/adwords/v201603/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201603/extensions/add_site_links.py delete mode 100755 examples/adwords/v201603/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201603/migration/__init__.py delete mode 100755 examples/adwords/v201603/migration/migrate_to_extension_settings.py delete mode 100755 examples/adwords/v201603/migration/upgrade_ad_url.py delete mode 100644 examples/adwords/v201603/misc/__init__.py delete mode 100755 examples/adwords/v201603/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201603/misc/upload_image.py delete mode 100755 examples/adwords/v201603/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201603/optimization/__init__.py delete mode 100755 examples/adwords/v201603/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201603/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201603/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201603/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201603/remarketing/__init__.py delete mode 100755 examples/adwords/v201603/remarketing/add_audience.py delete mode 100755 examples/adwords/v201603/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201603/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201603/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201603/remarketing/upload_offline_conversions.py delete mode 100644 examples/adwords/v201603/reporting/__init__.py delete mode 100755 examples/adwords/v201603/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201603/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201603/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201603/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201603/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201603/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201603/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201603/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201603/shopping/__init__.py delete mode 100755 examples/adwords/v201603/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201603/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201603/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201603/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201603/targeting/__init__.py delete mode 100755 examples/adwords/v201603/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201603/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201603/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201603/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201603/targeting/lookup_location.py rename examples/adwords/{v201603/basic_operations/pause_ad.py => v201609/account_management/accept_service_link.py} (55%) diff --git a/ChangeLog b/ChangeLog index 7530a5e4..bf18d2df 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +4.7.0 -- 10/25/16: +* Removed support for AdWords v201603. + 4.6.1 -- 9/30/16: * Added support for AdWords v201609. * The library now automatically applies filters to log output to sanitize its diff --git a/examples/adwords/v201603/__init__.py b/examples/adwords/v201603/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201603/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201603/account_management/__init__.py b/examples/adwords/v201603/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201603/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201603/account_management/create_account.py b/examples/adwords/v201603/account_management/create_account.py deleted file mode 100755 index 251bf45c..00000000 --- a/examples/adwords/v201603/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201603') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/account_management/get_account_changes.py b/examples/adwords/v201603/account_management/get_account_changes.py deleted file mode 100755 index ec9c4676..00000000 --- a/examples/adwords/v201603/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201603') - campaign_service = client.GetService('CampaignService', version='v201603') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/account_management/get_account_hierarchy.py b/examples/adwords/v201603/account_management/get_account_hierarchy.py deleted file mode 100755 index 6155aec0..00000000 --- a/examples/adwords/v201603/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201603') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/advanced_operations/__init__.py b/examples/adwords/v201603/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201603/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201603/advanced_operations/add_ad_customizer.py b/examples/adwords/v201603/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 4f5a84f9..00000000 --- a/examples/adwords/v201603/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates TextAds that use ad customizations for the specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add TextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no TextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService') - - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'description1': 'Only {=%s.Price}' % feed_name, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201603/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201603/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 7988ab5f..00000000 --- a/examples/adwords/v201603/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201603') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index face8aaf..00000000 --- a/examples/adwords/v201603/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/advanced_operations/add_html5_ad.py b/examples/adwords/v201603/advanced_operations/add_html5_ad.py deleted file mode 100755 index 5bd82d84..00000000 --- a/examples/adwords/v201603/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201603/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index 4f3dce96..00000000 --- a/examples/adwords/v201603/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a text add that uses advanced features of upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201603/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201603/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 06343667..00000000 --- a/examples/adwords/v201603/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201603') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201603') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201603') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201603/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index a51297f1..00000000 --- a/examples/adwords/v201603/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201603') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201603') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201603/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 74081091..00000000 --- a/examples/adwords/v201603/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201603') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201603/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 5a939e60..00000000 --- a/examples/adwords/v201603/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201603') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201603') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201603') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201603/basic_operations/__init__.py b/examples/adwords/v201603/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201603/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201603/basic_operations/add_ad_groups.py b/examples/adwords/v201603/basic_operations/add_ad_groups.py deleted file mode 100755 index 53e56f42..00000000 --- a/examples/adwords/v201603/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201603') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/basic_operations/add_campaigns.py b/examples/adwords/v201603/basic_operations/add_campaigns.py deleted file mode 100755 index 57d23cf7..00000000 --- a/examples/adwords/v201603/basic_operations/add_campaigns.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201603') - budget_service = client.GetService('BudgetService', version='v201603') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/basic_operations/add_keywords.py b/examples/adwords/v201603/basic_operations/add_keywords.py deleted file mode 100755 index cebf5506..00000000 --- a/examples/adwords/v201603/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201603') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/add_text_ads.py b/examples/adwords/v201603/basic_operations/add_text_ads.py deleted file mode 100755 index 76e0e093..00000000 --- a/examples/adwords/v201603/basic_operations/add_text_ads.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/get_ad_groups.py b/examples/adwords/v201603/basic_operations/get_ad_groups.py deleted file mode 100755 index a675c9fa..00000000 --- a/examples/adwords/v201603/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201603') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/basic_operations/get_campaigns.py b/examples/adwords/v201603/basic_operations/get_campaigns.py deleted file mode 100755 index e6509124..00000000 --- a/examples/adwords/v201603/basic_operations/get_campaigns.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201603') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201603/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 51be081e..00000000 --- a/examples/adwords/v201603/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201603') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/basic_operations/get_keywords.py b/examples/adwords/v201603/basic_operations/get_keywords.py deleted file mode 100755 index 6548e2c5..00000000 --- a/examples/adwords/v201603/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201603') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/get_text_ads.py b/examples/adwords/v201603/basic_operations/get_text_ads.py deleted file mode 100755 index 628888d2..00000000 --- a/examples/adwords/v201603/basic_operations/get_text_ads.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/remove_ad.py b/examples/adwords/v201603/basic_operations/remove_ad.py deleted file mode 100755 index 3f7e6c6c..00000000 --- a/examples/adwords/v201603/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201603/basic_operations/remove_ad_group.py b/examples/adwords/v201603/basic_operations/remove_ad_group.py deleted file mode 100755 index 3f3c788d..00000000 --- a/examples/adwords/v201603/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201603') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/remove_campaign.py b/examples/adwords/v201603/basic_operations/remove_campaign.py deleted file mode 100755 index fecfc26e..00000000 --- a/examples/adwords/v201603/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201603') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/basic_operations/remove_keyword.py b/examples/adwords/v201603/basic_operations/remove_keyword.py deleted file mode 100755 index bf0cce96..00000000 --- a/examples/adwords/v201603/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201603') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201603/basic_operations/update_ad_group.py b/examples/adwords/v201603/basic_operations/update_ad_group.py deleted file mode 100755 index f01d759b..00000000 --- a/examples/adwords/v201603/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201603') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/basic_operations/update_campaign.py b/examples/adwords/v201603/basic_operations/update_campaign.py deleted file mode 100755 index fe266424..00000000 --- a/examples/adwords/v201603/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201603') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/basic_operations/update_keyword.py b/examples/adwords/v201603/basic_operations/update_keyword.py deleted file mode 100755 index 83908c54..00000000 --- a/examples/adwords/v201603/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201603') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201603/campaign_management/__init__.py b/examples/adwords/v201603/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201603/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201603/campaign_management/add_campaign_labels.py b/examples/adwords/v201603/campaign_management/add_campaign_labels.py deleted file mode 100755 index 0d1b37b0..00000000 --- a/examples/adwords/v201603/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201603') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201603/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201603/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index cff2a8a1..00000000 --- a/examples/adwords/v201603/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,426 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201603') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201603') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding a TextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new TextAd for each of - the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201603') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201603/campaign_management/add_draft.py b/examples/adwords/v201603/campaign_management/add_draft.py deleted file mode 100755 index db08175f..00000000 --- a/examples/adwords/v201603/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - # Initialize appropriate services. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201603') - draft_service = client.GetService('DraftService', version='v201603') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201603/campaign_management/add_experiment.py b/examples/adwords/v201603/campaign_management/add_experiment.py deleted file mode 100755 index 4f90ae9c..00000000 --- a/examples/adwords/v201603/campaign_management/add_experiment.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201603') - ad_group_service = client.GetService('AdGroupService', version='v201603') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201603') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201603/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201603/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index f1e093d4..00000000 --- a/examples/adwords/v201603/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201603') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201603') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201603') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201603') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201603/campaign_management/add_trial.py b/examples/adwords/v201603/campaign_management/add_trial.py deleted file mode 100755 index 2666dbaa..00000000 --- a/examples/adwords/v201603/campaign_management/add_trial.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201603') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201603') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201603/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201603/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 0f9597be..00000000 --- a/examples/adwords/v201603/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201603/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 720fac6f..00000000 --- a/examples/adwords/v201603/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201603/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index e6d997e4..00000000 --- a/examples/adwords/v201603/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201603') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201603/campaign_management/graduate_trial.py b/examples/adwords/v201603/campaign_management/graduate_trial.py deleted file mode 100755 index 3a0824f8..00000000 --- a/examples/adwords/v201603/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201603') - budget_service = client.GetService('BudgetService', version='v201603') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201603/campaign_management/promote_experiment.py b/examples/adwords/v201603/campaign_management/promote_experiment.py deleted file mode 100755 index cc5a6db5..00000000 --- a/examples/adwords/v201603/campaign_management/promote_experiment.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201603') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201603/campaign_management/set_ad_parameters.py b/examples/adwords/v201603/campaign_management/set_ad_parameters.py deleted file mode 100755 index 133d9b81..00000000 --- a/examples/adwords/v201603/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - ad_param_service = client.GetService('AdParamService', version='v201603') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201603/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201603/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index 63ce1d23..00000000 --- a/examples/adwords/v201603/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201603') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201603/campaign_management/validate_text_ad.py b/examples/adwords/v201603/campaign_management/validate_text_ad.py deleted file mode 100755 index ef271911..00000000 --- a/examples/adwords/v201603/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/error_handling/__init__.py b/examples/adwords/v201603/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201603/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201603/error_handling/handle_partial_failures.py b/examples/adwords/v201603/error_handling/handle_partial_failures.py deleted file mode 100755 index 01a7a462..00000000 --- a/examples/adwords/v201603/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201603') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/error_handling/handle_policy_violation_error.py b/examples/adwords/v201603/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 9d3ecdaa..00000000 --- a/examples/adwords/v201603/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201603') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - operation = operations[int(operation_index[0])] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) - else: - # Non-policy error returned, re-throw exception. - raise e - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/extensions/__init__.py b/examples/adwords/v201603/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201603/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201603/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201603/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 3414e5b8..00000000 --- a/examples/adwords/v201603/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201603').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201603') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201603/extensions/add_site_links.py b/examples/adwords/v201603/extensions/add_site_links.py deleted file mode 100755 index 5f9fb083..00000000 --- a/examples/adwords/v201603/extensions/add_site_links.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201603') - customer_service = client.GetService('CustomerService', version='v201603') - - customer_tz = timezone(customer_service.get()['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840} - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/extensions/add_site_links_using_feeds.py b/examples/adwords/v201603/extensions/add_site_links_using_feeds.py deleted file mode 100755 index 05135612..00000000 --- a/examples/adwords/v201603/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,233 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201603') - feed_item_service = client.GetService('FeedItemService', version='v201603') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201603') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201603') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/migration/__init__.py b/examples/adwords/v201603/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201603/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201603/migration/migrate_to_extension_settings.py b/examples/adwords/v201603/migration/migrate_to_extension_settings.py deleted file mode 100755 index 534fde73..00000000 --- a/examples/adwords/v201603/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201603') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201603') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201603') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201603') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201603') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201603') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201603') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/migration/upgrade_ad_url.py b/examples/adwords/v201603/migration/upgrade_ad_url.py deleted file mode 100755 index 642b3e1b..00000000 --- a/examples/adwords/v201603/migration/upgrade_ad_url.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 upgrades an ad to use upgraded URLs. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, adgroup_id, ad_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201603') - - selector = { - 'fields': ['Id', 'Url'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [ad_id] - } - ] - } - - page = adgroup_ad_service.get(selector) - - adgroup_ad = page['entries'][0] if page['entries'] else None - - if not adgroup_ad: - raise errors.GoogleAdsError('Ad not found.') - - ad_url_upgrade = { - 'adId': adgroup_ad['ad']['id'], - 'finalUrl': adgroup_ad['ad']['url'] - } - - adgroup_ad = adgroup_ad_service.upgradeUrl([ad_url_upgrade])[0] - - if adgroup_ad: - print ('AdGroupAd with ID %s and destination URL \'%s\' was upgraded.' - % (adgroup_ad['id'], adgroup_ad['finalUrls'][0])) - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID, AD_ID) diff --git a/examples/adwords/v201603/misc/__init__.py b/examples/adwords/v201603/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201603/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201603/misc/get_all_images_and_videos.py b/examples/adwords/v201603/misc/get_all_images_and_videos.py deleted file mode 100755 index 39248f5c..00000000 --- a/examples/adwords/v201603/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201603') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/misc/upload_image.py b/examples/adwords/v201603/misc/upload_image.py deleted file mode 100755 index 09adbae1..00000000 --- a/examples/adwords/v201603/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201603') - - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201603/misc/upload_media_bundle.py b/examples/adwords/v201603/misc/upload_media_bundle.py deleted file mode 100755 index 0712e63a..00000000 --- a/examples/adwords/v201603/misc/upload_media_bundle.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201603') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/optimization/__init__.py b/examples/adwords/v201603/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201603/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201603/optimization/estimate_keyword_traffic.py b/examples/adwords/v201603/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 885ae713..00000000 --- a/examples/adwords/v201603/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201603') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - selector = { - 'campaignEstimateRequests': [{ - 'adGroupEstimateRequests': [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }], - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ] - }] - } - estimates = traffic_estimator_service.get(selector) - - # Display results. - ad_group_estimate = estimates['campaignEstimates'][0]['adGroupEstimates'][0] - keyword_estimates = ad_group_estimate['keywordEstimates'] - for index in xrange(len(keyword_estimates)): - keyword = keyword_estimate_requests[index]['keyword'] - estimate = keyword_estimates[index] - if keyword_estimate_requests[index].get('isNegative', False): - continue - - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(estimate['min']['averageCpc']['microAmount'], - estimate['max']['averageCpc']['microAmount']) - if 'averageCpc' in estimate['min'] else 'N/A') - mean_avg_pos = _CalculateMean(estimate['min']['averagePosition'], - estimate['max']['averagePosition']) - mean_clicks = _CalculateMean(estimate['min']['clicksPerDay'], - estimate['max']['clicksPerDay']) - mean_total_cost = _CalculateMean( - estimate['min']['totalCost']['microAmount'], - estimate['max']['totalCost']['microAmount']) - - print ('Results for the keyword with text \'%s\' and match type \'%s\':' - % (keyword['text'], keyword['matchType'])) - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return None - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201603/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index e44d730b..00000000 --- a/examples/adwords/v201603/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201603') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201603/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index bd12884f..00000000 --- a/examples/adwords/v201603/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201603') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201603/optimization/get_keyword_ideas.py b/examples/adwords/v201603/optimization/get_keyword_ideas.py deleted file mode 100755 index e1404548..00000000 --- a/examples/adwords/v201603/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201603') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/remarketing/__init__.py b/examples/adwords/v201603/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201603/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201603/remarketing/add_audience.py b/examples/adwords/v201603/remarketing/add_audience.py deleted file mode 100755 index f49746ec..00000000 --- a/examples/adwords/v201603/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201603') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201603') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/remarketing/add_conversion_tracker.py b/examples/adwords/v201603/remarketing/add_conversion_tracker.py deleted file mode 100755 index f273c0b7..00000000 --- a/examples/adwords/v201603/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201603') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/remarketing/add_crm_based_user_list.py b/examples/adwords/v201603/remarketing/add_crm_based_user_list.py deleted file mode 100755 index de51346c..00000000 --- a/examples/adwords/v201603/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client, emails): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201603') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. - - Args: - emails: list of str emails to be hashed. - - Returns: - A list of SHA-256 hashed emails. - """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] - - -if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) diff --git a/examples/adwords/v201603/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201603/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 78185eb9..00000000 --- a/examples/adwords/v201603/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201603') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/remarketing/upload_offline_conversions.py b/examples/adwords/v201603/remarketing/upload_offline_conversions.py deleted file mode 100755 index 2b9d1e9e..00000000 --- a/examples/adwords/v201603/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201603') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201603/reporting/__init__.py b/examples/adwords/v201603/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201603/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201603/reporting/download_criteria_report.py b/examples/adwords/v201603/reporting/download_criteria_report.py deleted file mode 100755 index 9ec69a35..00000000 --- a/examples/adwords/v201603/reporting/download_criteria_report.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201603') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201603/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index 64b6bf0e..00000000 --- a/examples/adwords/v201603/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201603') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201603/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 6ba9579d..00000000 --- a/examples/adwords/v201603/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201603') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_as_string.py b/examples/adwords/v201603/reporting/download_criteria_report_as_string.py deleted file mode 100755 index 87d8da98..00000000 --- a/examples/adwords/v201603/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201603') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201603/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 605d5523..00000000 --- a/examples/adwords/v201603/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201603') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201603/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index eeb6ff62..00000000 --- a/examples/adwords/v201603/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201603') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201603/reporting/get_report_fields.py b/examples/adwords/v201603/reporting/get_report_fields.py deleted file mode 100755 index 55e96959..00000000 --- a/examples/adwords/v201603/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201603') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201603/reporting/parallel_report_download.py b/examples/adwords/v201603/reporting/parallel_report_download.py deleted file mode 100755 index 431c81bd..00000000 --- a/examples/adwords/v201603/reporting/parallel_report_download.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import logging -import multiprocessing -from Queue import Empty -import time -import googleads - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - client: An AdWordsClient instance. - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201603') - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = self._DownloadReport(customer_id) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - - Raises: - Exception: if no CustomerIds could be found. - - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201603') - - offset = 0 - - # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201603/shopping/__init__.py b/examples/adwords/v201603/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201603/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201603/shopping/add_product_partition_tree.py b/examples/adwords/v201603/shopping/add_product_partition_tree.py deleted file mode 100755 index e3954d94..00000000 --- a/examples/adwords/v201603/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201603') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201603/shopping/add_product_scope.py b/examples/adwords/v201603/shopping/add_product_scope.py deleted file mode 100755 index 822e6e57..00000000 --- a/examples/adwords/v201603/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201603') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201603/shopping/add_shopping_campaign.py b/examples/adwords/v201603/shopping/add_shopping_campaign.py deleted file mode 100755 index fe99b26c..00000000 --- a/examples/adwords/v201603/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201603') - ad_group_service = client.GetService('AdGroupService', version='v201603') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201603/shopping/get_product_category_taxonomy.py b/examples/adwords/v201603/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 241eea4e..00000000 --- a/examples/adwords/v201603/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201603') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/targeting/__init__.py b/examples/adwords/v201603/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201603/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201603/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201603/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 48c62a68..00000000 --- a/examples/adwords/v201603/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201603') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - florida_downtown = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'PlacesOfInterestOperand', - # Other valid options: AIRPORT, UNIVERSITY. - 'category': 'DOWNTOWN', - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - } - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish, florida_tier3, - florida_downtown] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201603/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201603/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 0aa66873..00000000 --- a/examples/adwords/v201603/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201603') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201603/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201603/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 58f5c627..00000000 --- a/examples/adwords/v201603/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201603') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201603/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index 1244517e..00000000 --- a/examples/adwords/v201603/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201603') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/targeting/lookup_location.py b/examples/adwords/v201603/targeting/lookup_location.py deleted file mode 100755 index 40216270..00000000 --- a/examples/adwords/v201603/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201603') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201603/basic_operations/pause_ad.py b/examples/adwords/v201609/account_management/accept_service_link.py similarity index 55% rename from examples/adwords/v201603/basic_operations/pause_ad.py rename to examples/adwords/v201609/account_management/accept_service_link.py index ee7e9ca1..930fe0b7 100755 --- a/examples/adwords/v201603/basic_operations/pause_ad.py +++ b/examples/adwords/v201609/account_management/accept_service_link.py @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates status for a given ad. - -To get ads, run get_text_ads.py. +"""This example accepts a pending Google Merchant Center invitation link. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -25,37 +23,40 @@ """ + from googleads import adwords -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' +SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' -def main(client, ad_group_id, ad_id): +def main(client, service_link_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201603') + customer_service = client.GetService( + 'CustomerService', version='v201609') - # Construct operations and update an ad. + # Create the operation to set the status to ACTIVE. operations = [{ 'operator': 'SET', 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' + 'serviceLinkId': service_link_id, + 'serviceType': 'MERCHANT_CENTER', + 'linkStatus': 'ACTIVE', } }] - ads = ad_group_ad_service.mutate(operations) + + # Update the service link. + mutated_service_links = customer_service.mutateServiceLinks(operations) # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + for mutated_service_link in mutated_service_links: + print ('Service link with service link ID \'%s\', type \'%s\' was updated ' + 'to status: \'%s\'.' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) + main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py index 47e07bd5..8ee87822 100755 --- a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py @@ -41,6 +41,9 @@ def main(client): # Create the Universal App campaign. universal_app_campaign = { 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. 'status': 'PAUSED', 'advertisingChannelType': 'MULTI_CHANNEL', 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', diff --git a/examples/adwords/v201609/basic_operations/add_campaigns.py b/examples/adwords/v201609/basic_operations/add_campaigns.py index fb8faa33..b78331c3 100755 --- a/examples/adwords/v201609/basic_operations/add_campaigns.py +++ b/examples/adwords/v201609/basic_operations/add_campaigns.py @@ -59,6 +59,9 @@ def main(client): 'operator': 'ADD', 'operand': { 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. 'status': 'PAUSED', 'advertisingChannelType': 'SEARCH', 'biddingStrategyConfiguration': { diff --git a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py index 6333790b..4ea79492 100755 --- a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py @@ -315,6 +315,9 @@ def BuildCampaignOperations(batch_job_helper, 'xsi_type': 'CampaignOperation', 'operand': { 'name': 'Batch Campaign #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once + # you've added targeting and the ads are ready to serve. 'status': 'PAUSED', # This is a temporary Id used by the BatchJobService to identify # the Campaigns for operations that require a campaignId. diff --git a/examples/adwords/v201609/shopping/add_shopping_campaign.py b/examples/adwords/v201609/shopping/add_shopping_campaign.py index 0df5099b..166c272e 100755 --- a/examples/adwords/v201609/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201609/shopping/add_shopping_campaign.py @@ -43,6 +43,10 @@ def main(client, budget_id, merchant_id): 'name': 'Shopping campaign #%s' % uuid.uuid4(), # The advertisingChannelType is what makes this a shopping campaign 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', # Set portfolio budget (required) 'budget': { 'budgetId': budget_id diff --git a/googleads/adwords.py b/googleads/adwords.py index c19d05f8..3036c4c5 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -36,52 +36,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201603': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'CustomerFeedService': 'cm', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201605': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', diff --git a/googleads/common.py b/googleads/common.py index fa7d56a4..dcdbb09f 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -59,7 +59,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '4.6.1' +VERSION = '4.7.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' diff --git a/googleads/oauth2.py b/googleads/oauth2.py index b98a0773..2600ccdb 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -14,8 +14,10 @@ """OAuth2 integration for the googleads library. This module provides a basic interface which the googleads library uses to -authorize API requests and some simple implementations built on oauth2client. If -our OAuth2 workflows doesn't meet your requirements, you can implement this +authorize API requests and some simple implementations built on +oauth2client. + +If our OAuth2 workflows doesn't meet your requirements, you can implement this interface in your own way. For example, you could pull credentials from a shared server and/or centralize refreshing credentials to prevent every Python process from independently refreshing the credentials. @@ -195,10 +197,12 @@ def __init__(self, scope, client_email, key_file, raise googleads.errors.GoogleAdsValueError('The specified key file (%s)' ' does not exist.' % key_file) - self.oauth2credentials = oauth2client.client.SignedJwtAssertionCredentials( - client_email, private_key, scope, - private_key_password=private_key_password, user_agent=self._USER_AGENT, - token_uri=self._GOOGLE_OAUTH2_ENDPOINT, sub=sub) + self.oauth2credentials = ( + oauth2client.client.SignedJwtAssertionCredentials( + client_email, private_key, scope, + private_key_password=private_key_password, + user_agent=self._USER_AGENT, token_uri=self._GOOGLE_OAUTH2_ENDPOINT, + sub=sub)) self.proxy_config = (proxy_config if proxy_config else googleads.common.ProxyConfig()) self.Refresh() diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index 3bfe14c5..343ffbf3 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -201,7 +201,8 @@ def refresh(mock_http): self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply) self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh) with mock.patch('__builtin__.open', fake_open): - with mock.patch('oauth2client.client.SignedJwtAssertionCredentials', + with mock.patch('oauth2client.client' + '.SignedJwtAssertionCredentials', self.oauth2_credentials): self.googleads_client = googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, key_file_path, @@ -241,7 +242,8 @@ def testIssue123(self): See: https://github.com/googleads/googleads-python-lib/issues/123 """ with mock.patch('__builtin__.open'): - with mock.patch('oauth2client.client.SignedJwtAssertionCredentials', + with mock.patch('oauth2client.client' + '.SignedJwtAssertionCredentials', self.oauth2_credentials): googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, '/dev/null', From 58219ecbad92ba8cbe5442a3f31fa5d017755301 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 25 Oct 2016 17:49:21 -0400 Subject: [PATCH 053/180] Commiting latest changes. From 6ad7ac568cabe11433a84513d127987427d80288 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 7 Dec 2016 17:33:22 -0500 Subject: [PATCH 054/180] DFP v201611 Release --- ChangeLog | 13 + examples/adwords/v201605/misc/upload_image.py | 4 +- examples/adwords/v201607/misc/upload_image.py | 4 +- examples/adwords/v201609/misc/upload_image.py | 4 +- .../get_active_activity_groups.py | 69 ---- .../activity_service/get_active_activities.py | 66 ---- .../company_service/get_advertisers.py | 66 ---- .../contact_service/get_uninvited_contacts.py | 65 ---- ...et_all_content_metadata_key_hierarchies.py | 63 --- .../content_service/get_all_content.py | 59 --- .../get_content_by_category.py | 109 ------ .../get_creatives_by_statement.py | 69 ---- .../get_creative_templates_by_statement.py | 67 ---- .../get_active_creative_wrappers.py | 67 ---- ...et_all_custom_targeting_keys_and_values.py | 88 ----- ...et_custom_targeting_values_by_statement.py | 65 ---- .../get_ad_unit_hierarchy.py | 115 ------ .../get_all_ad_unit_sizes.py | 54 --- .../inventory_service/get_all_ad_units.py | 56 --- .../get_top_level_ad_units.py | 69 ---- .../get_line_items_by_statement.py | 75 ---- .../get_recently_updated_line_items.py | 74 ---- .../order_service/get_orders_by_statement.py | 61 --- .../get_geo_targets.py | 63 --- .../team_service/get_teams_by_statement.py | 67 ---- .../v201602/user_service/get_current_user.py | 38 -- .../user_service/get_users_by_statement.py | 57 --- ...create_custom_targeting_keys_and_values.py | 4 +- .../delete_custom_targeting_keys.py | 2 +- ...create_custom_targeting_keys_and_values.py | 4 +- .../delete_custom_targeting_keys.py | 2 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 58 +++ .../get_all_activity_groups.py | 29 +- .../update_activity_groups.py | 2 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../get_active_activities.py} | 45 ++- .../activity_service/get_all_activities.py | 50 +++ .../activity_service/update_activities.py | 2 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 7 +- .../get_all_audience_segments.py | 25 +- .../get_first_party_audience_segments.py | 43 +-- .../populate_first_party_audience_segments.py | 9 +- .../update_audience_segments.py | 4 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 32 +- .../get_base_rates_for_rate_card.py} | 50 +-- .../base_rate_service/update_base_rates.py | 2 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py} | 44 +-- .../company_service/get_all_companies.py | 49 +++ .../company_service/update_companies.py | 2 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 49 +++ .../get_uninvited_contacts.py} | 44 +-- .../contact_service/update_contacts.py | 2 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 55 +++ ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 49 +++ .../creative_service/__init__.py | 0 .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 4 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 49 +++ .../creative_service/get_image_creatives.py} | 45 +-- .../creative_service/update_creatives.py | 2 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 5 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 30 +- .../get_creative_sets_for_master_creative.py} | 48 +-- .../update_creative_set.py | 2 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 30 +- .../get_system_defined_creative_templates.py} | 43 +-- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py} | 43 +-- .../get_all_creative_wrappers.py | 51 +++ .../update_creative_wrappers.py | 2 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 26 +- .../get_custom_fields_for_line_items.py} | 45 +-- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 2 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 6 +- .../delete_custom_targeting_keys.py | 4 +- .../delete_custom_targeting_values.py | 5 +- ...et_all_custom_targeting_keys_and_values.py | 72 ++++ ...efined_custom_targeting_keys_and_values.py | 80 ++++ .../update_custom_targeting_keys.py | 5 +- .../update_custom_targeting_values.py | 8 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 34 +- .../get_exchange_rates_for_currency_code.py} | 45 +-- .../update_exchange_rates.py | 2 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 2 +- .../get_all_ad_unit_sizes.py} | 30 +- .../inventory_service/get_all_ad_units.py | 49 +++ .../inventory_service/update_ad_units.py | 2 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 5 +- .../label_service/deactivate_labels.py | 5 +- .../label_service/get_active_labels.py} | 35 +- .../label_service/get_all_labels.py | 23 +- .../label_service/update_labels.py | 5 +- .../__init__.py | 0 .../create_licas.py | 5 +- .../deactivate_licas.py | 5 +- .../get_all_licas.py | 33 +- .../get_licas_for_line_item.py} | 50 +-- .../update_licas.py | 5 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 5 +- .../line_item_service/create_line_items.py | 7 +- .../create_video_line_item.py | 9 +- .../line_item_service/get_all_line_items.py | 28 +- .../get_line_items_that_need_creatives.py | 57 +++ .../get_recently_updated_line_items.py | 61 +++ .../target_custom_criteria.py | 5 +- .../line_item_service/update_line_items.py | 5 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 20 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 5 +- .../order_service/create_orders.py | 7 +- .../order_service/get_all_orders.py | 21 +- .../order_service/get_orders_starting_soon.py | 71 ++++ .../order_service/update_orders.py | 5 +- .../package_service/get_all_packages.py | 50 +++ .../get_in_progress_packages.py | 57 +++ .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 2 +- .../get_active_placements.py} | 41 +- .../placement_service/get_all_placements.py | 26 +- .../placement_service/update_placements.py | 2 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 31 +- .../get_premium_rates_for_rate_card.py} | 46 +-- .../update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 53 +++ ...oduct_package_items_for_product_package.py | 62 +++ .../get_active_product_packages.py | 58 +++ .../get_all_product_packages.py | 51 +++ .../product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 84 ++++ .../product_service/get_all_products.py | 24 +- .../get_products_for_product_template.py | 37 +- ...sh_programmatic_products_to_marketplace.py | 74 ++++ .../product_service/update_products.py | 2 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 2 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 91 +++++ .../get_all_product_templates.py | 24 +- .../get_sponsorship_product_templates.py | 37 +- .../update_product_templates.py | 2 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 2 +- ...create_programmatic_proposal_line_items.py | 119 ++++++ ...sal_line_items_for_non_sales_management.py | 125 ++++++ .../create_proposal_line_items.py | 8 +- .../get_all_proposal_line_items.py | 28 +- .../get_proposal_line_items_for_proposal.py | 48 +-- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 71 ++++ ...atic_proposals_for_non_sales_management.py | 62 +++ .../proposal_service/create_proposals.py | 9 +- .../proposal_service/get_all_proposals.py | 23 +- .../get_marketplace_comments.py | 64 ++++ .../get_proposals_pending_approval.py} | 40 +- .../request_buyers_acceptance.py | 74 ++++ .../submit_proposals_for_approval.py | 6 +- .../proposal_service/update_proposals.py | 9 +- .../__init__.py | 0 .../fetch_match_tables.py | 6 +- .../get_all_programmatic_buyers.py} | 31 +- .../rate_card_service/__init__.py | 0 .../rate_card_service/get_all_rate_cards.py | 28 +- .../get_marketplace_rate_cards.py} | 44 +-- ..._item_reports_for_reconciliation_report.py | 75 ++++ ...order_reports_for_reconciliation_report.py | 63 +++ ...n_report_rows_for_reconciliation_report.py | 66 ++++ .../get_all_reconciliation_reports.py | 56 +++ ...iliation_report_for_last_billing_period.py | 69 ++++ .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 7 +- .../report_service/run_inventory_report.py | 8 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 8 +- .../report_service/run_sales_report.py | 5 +- .../v201611/report_service/run_saved_query.py | 85 +++++ .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 24 +- ...et_highly_requested_suggested_ad_units.py} | 48 ++- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 5 +- .../team_service/get_all_teams.py | 26 +- .../team_service/update_teams.py | 22 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 6 +- .../user_service/deactivate_users.py | 5 +- .../user_service/get_all_roles.py | 20 +- .../user_service/get_all_users.py | 21 +- .../user_service/get_user_by_email_address.py | 58 +++ .../user_service/update_users.py | 5 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 27 +- .../get_user_team_associations_for_user.py | 47 +-- .../update_user_team_associations.py | 2 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py} | 40 +- ...t_workflow_external_condition_requests.py} | 44 +-- ...er_workflow_external_condition_requests.py | 2 +- googleads/adwords.py | 36 +- googleads/common.py | 89 ++++- googleads/dfp.py | 60 ++- tests/adwords_test.py | 21 + tests/common_test.py | 359 ++++++++++++------ tests/dfp_test.py | 12 + 249 files changed, 3754 insertions(+), 2919 deletions(-) delete mode 100755 examples/dfp/v201602/activity_group_service/get_active_activity_groups.py delete mode 100755 examples/dfp/v201602/activity_service/get_active_activities.py delete mode 100755 examples/dfp/v201602/company_service/get_advertisers.py delete mode 100755 examples/dfp/v201602/contact_service/get_uninvited_contacts.py delete mode 100755 examples/dfp/v201602/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py delete mode 100755 examples/dfp/v201602/content_service/get_all_content.py delete mode 100755 examples/dfp/v201602/content_service/get_content_by_category.py delete mode 100755 examples/dfp/v201602/creative_service/get_creatives_by_statement.py delete mode 100755 examples/dfp/v201602/creative_template_service/get_creative_templates_by_statement.py delete mode 100755 examples/dfp/v201602/creative_wrapper_service/get_active_creative_wrappers.py delete mode 100755 examples/dfp/v201602/custom_targeting_service/get_all_custom_targeting_keys_and_values.py delete mode 100755 examples/dfp/v201602/custom_targeting_service/get_custom_targeting_values_by_statement.py delete mode 100755 examples/dfp/v201602/inventory_service/get_ad_unit_hierarchy.py delete mode 100755 examples/dfp/v201602/inventory_service/get_all_ad_unit_sizes.py delete mode 100755 examples/dfp/v201602/inventory_service/get_all_ad_units.py delete mode 100755 examples/dfp/v201602/inventory_service/get_top_level_ad_units.py delete mode 100755 examples/dfp/v201602/line_item_service/get_line_items_by_statement.py delete mode 100755 examples/dfp/v201602/line_item_service/get_recently_updated_line_items.py delete mode 100755 examples/dfp/v201602/order_service/get_orders_by_statement.py delete mode 100755 examples/dfp/v201602/publisher_query_language_service/get_geo_targets.py delete mode 100755 examples/dfp/v201602/team_service/get_teams_by_statement.py delete mode 100755 examples/dfp/v201602/user_service/get_current_user.py delete mode 100755 examples/dfp/v201602/user_service/get_users_by_statement.py rename examples/dfp/{v201602 => v201611}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/activity_group_service/create_activity_groups.py (97%) create mode 100755 examples/dfp/v201611/activity_group_service/get_active_activity_groups.py rename examples/dfp/{v201602 => v201611}/activity_group_service/get_all_activity_groups.py (61%) rename examples/dfp/{v201602 => v201611}/activity_group_service/update_activity_groups.py (97%) rename examples/dfp/{v201602 => v201611}/activity_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/activity_service/create_activities.py (99%) rename examples/dfp/{v201602/activity_service/get_all_activities.py => v201611/activity_service/get_active_activities.py} (58%) create mode 100755 examples/dfp/v201611/activity_service/get_all_activities.py rename examples/dfp/{v201602 => v201611}/activity_service/update_activities.py (99%) rename examples/dfp/{v201602 => v201611}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/audience_segment_service/create_audience_segments.py (95%) rename examples/dfp/{v201602 => v201611}/audience_segment_service/get_all_audience_segments.py (65%) rename examples/dfp/{v201602 => v201611}/audience_segment_service/get_first_party_audience_segments.py (59%) rename examples/dfp/{v201602 => v201611}/audience_segment_service/populate_first_party_audience_segments.py (90%) rename examples/dfp/{v201602 => v201611}/audience_segment_service/update_audience_segments.py (96%) rename examples/dfp/{v201602 => v201611}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201602 => v201611}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201602 => v201611}/base_rate_service/get_all_base_rates.py (62%) rename examples/dfp/{v201602/base_rate_service/get_base_rates_for_a_rate_card.py => v201611/base_rate_service/get_base_rates_for_rate_card.py} (57%) rename examples/dfp/{v201602 => v201611}/base_rate_service/update_base_rates.py (99%) rename examples/dfp/{v201602 => v201611}/company_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/company_service/create_companies.py (99%) rename examples/dfp/{v201602/company_service/get_all_companies.py => v201611/company_service/get_advertisers.py} (59%) create mode 100755 examples/dfp/v201611/company_service/get_all_companies.py rename examples/dfp/{v201602 => v201611}/company_service/update_companies.py (99%) rename examples/dfp/{v201602 => v201611}/contact_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/contact_service/create_contacts.py (99%) create mode 100755 examples/dfp/v201611/contact_service/get_all_contacts.py rename examples/dfp/{v201602/contact_service/get_all_contacts.py => v201611/contact_service/get_uninvited_contacts.py} (60%) rename examples/dfp/{v201602 => v201611}/contact_service/update_contacts.py (99%) rename examples/dfp/{v201602 => v201611}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201602 => v201611}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (97%) create mode 100755 examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename examples/dfp/{v201602 => v201611}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (98%) rename examples/dfp/{v201602 => v201611}/content_service/__init__.py (100%) create mode 100755 examples/dfp/v201611/content_service/get_all_content.py rename examples/dfp/{v201602 => v201611}/creative_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201602 => v201611}/creative_service/create_creatives.py (98%) rename examples/dfp/{v201602 => v201611}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201602 => v201611}/creative_service/create_native_creative.py (99%) create mode 100755 examples/dfp/v201611/creative_service/get_all_creatives.py rename examples/dfp/{v201602/creative_service/get_all_creatives.py => v201611/creative_service/get_image_creatives.py} (57%) rename examples/dfp/{v201602 => v201611}/creative_service/update_creatives.py (99%) rename examples/dfp/{v201602 => v201611}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/creative_set_service/associate_creative_set_to_line_item.py (92%) rename examples/dfp/{v201602 => v201611}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201602 => v201611}/creative_set_service/get_all_creative_sets.py (61%) rename examples/dfp/{v201602/creative_set_service/get_creative_sets_by_statement.py => v201611/creative_set_service/get_creative_sets_for_master_creative.py} (54%) rename examples/dfp/{v201602 => v201611}/creative_set_service/update_creative_set.py (97%) rename examples/dfp/{v201602 => v201611}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/creative_template_service/get_all_creative_templates.py (61%) rename examples/dfp/{v201602/custom_targeting_service/get_custom_targeting_keys_by_statement.py => v201611/creative_template_service/get_system_defined_creative_templates.py} (56%) rename examples/dfp/{v201602 => v201611}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/dfp/{v201602 => v201611}/creative_wrapper_service/deactivate_creative_wrapper.py (97%) rename examples/dfp/{v201602/creative_wrapper_service/get_all_creative_wrappers.py => v201611/creative_wrapper_service/get_active_creative_wrappers.py} (58%) create mode 100755 examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py rename examples/dfp/{v201602 => v201611}/creative_wrapper_service/update_creative_wrappers.py (97%) rename examples/dfp/{v201602 => v201611}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201602 => v201611}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201602 => v201611}/custom_field_service/deactivate_all_line_item_custom_fields.py (98%) rename examples/dfp/{v201602 => v201611}/custom_field_service/get_all_custom_fields.py (67%) rename examples/dfp/{v201602/custom_field_service/get_all_line_item_custom_fields.py => v201611/custom_field_service/get_custom_fields_for_line_items.py} (59%) rename examples/dfp/{v201602 => v201611}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201602 => v201611}/custom_field_service/update_custom_fields.py (98%) rename examples/dfp/{v201602 => v201611}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/custom_targeting_service/create_custom_targeting_keys_and_values.py (96%) rename examples/dfp/{v201602 => v201611}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/dfp/{v201602 => v201611}/custom_targeting_service/delete_custom_targeting_values.py (95%) create mode 100755 examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py create mode 100755 examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename examples/dfp/{v201602 => v201611}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/dfp/{v201602 => v201611}/custom_targeting_service/update_custom_targeting_values.py (91%) rename examples/dfp/{v201602 => v201611}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201602 => v201611}/exchange_rate_service/get_all_exchange_rates.py (57%) rename examples/dfp/{v201602/exchange_rate_service/get_exchange_rates_by_currency_code.py => v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py} (59%) rename examples/dfp/{v201602 => v201611}/exchange_rate_service/update_exchange_rates.py (97%) rename examples/dfp/{v201602 => v201611}/forecast_service/get_availability_forecast.py (99%) rename examples/dfp/{v201602 => v201611}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/dfp/{v201602 => v201611}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/dfp/{v201602 => v201611}/inventory_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/inventory_service/archive_ad_units.py (99%) rename examples/dfp/{v201602 => v201611}/inventory_service/create_ad_units.py (99%) rename examples/dfp/{v201602/network_service/get_current_network.py => v201611/inventory_service/get_all_ad_unit_sizes.py} (52%) create mode 100755 examples/dfp/v201611/inventory_service/get_all_ad_units.py rename examples/dfp/{v201602 => v201611}/inventory_service/update_ad_units.py (99%) rename examples/dfp/{v201602 => v201611}/label_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/label_service/create_labels.py (96%) rename examples/dfp/{v201602 => v201611}/label_service/deactivate_labels.py (97%) rename examples/dfp/{v201602/label_service/get_labels_by_statement.py => v201611/label_service/get_active_labels.py} (63%) rename examples/dfp/{v201602 => v201611}/label_service/get_all_labels.py (73%) rename examples/dfp/{v201602 => v201611}/label_service/update_labels.py (97%) rename examples/dfp/{v201602 => v201611}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/line_item_creative_association_service/create_licas.py (93%) rename examples/dfp/{v201602 => v201611}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/dfp/{v201602 => v201611}/line_item_creative_association_service/get_all_licas.py (56%) rename examples/dfp/{v201602/line_item_creative_association_service/get_licas_by_statement.py => v201611/line_item_creative_association_service/get_licas_for_line_item.py} (52%) rename examples/dfp/{v201602 => v201611}/line_item_creative_association_service/update_licas.py (94%) rename examples/dfp/{v201602 => v201611}/line_item_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/line_item_service/activate_line_items.py (98%) rename examples/dfp/{v201602 => v201611}/line_item_service/create_line_items.py (98%) rename examples/dfp/{v201602 => v201611}/line_item_service/create_video_line_item.py (96%) rename examples/dfp/{v201602 => v201611}/line_item_service/get_all_line_items.py (68%) create mode 100755 examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py create mode 100755 examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py rename examples/dfp/{v201602 => v201611}/line_item_service/target_custom_criteria.py (98%) rename examples/dfp/{v201602 => v201611}/line_item_service/update_line_items.py (96%) rename examples/dfp/{v201602 => v201611}/network_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/network_service/get_all_networks.py (69%) rename examples/dfp/{v201602 => v201611}/network_service/make_test_network.py (99%) rename examples/dfp/{v201602 => v201611}/order_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/order_service/approve_orders.py (97%) rename examples/dfp/{v201602 => v201611}/order_service/create_orders.py (94%) rename examples/dfp/{v201602 => v201611}/order_service/get_all_orders.py (73%) create mode 100755 examples/dfp/v201611/order_service/get_orders_starting_soon.py rename examples/dfp/{v201602 => v201611}/order_service/update_orders.py (97%) create mode 100755 examples/dfp/v201611/package_service/get_all_packages.py create mode 100755 examples/dfp/v201611/package_service/get_in_progress_packages.py rename examples/dfp/{v201602 => v201611}/placement_service/create_placements.py (99%) rename examples/dfp/{v201602 => v201611}/placement_service/deactivate_placements.py (99%) rename examples/dfp/{v201602/placement_service/get_placements_by_statement.py => v201611/placement_service/get_active_placements.py} (64%) rename examples/dfp/{v201602 => v201611}/placement_service/get_all_placements.py (68%) rename examples/dfp/{v201602 => v201611}/placement_service/update_placements.py (99%) rename examples/dfp/{v201602 => v201611}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/premium_rate_service/create_premium_rates.py (97%) rename examples/dfp/{v201602 => v201611}/premium_rate_service/get_all_premium_rates.py (61%) rename examples/dfp/{v201602/premium_rate_service/get_premium_rates_for_a_rate_card.py => v201611/premium_rate_service/get_premium_rates_for_rate_card.py} (58%) rename examples/dfp/{v201602 => v201611}/premium_rate_service/update_premium_rates.py (97%) create mode 100755 examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py create mode 100755 examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py create mode 100755 examples/dfp/v201611/product_package_service/get_active_product_packages.py create mode 100755 examples/dfp/v201611/product_package_service/get_all_product_packages.py rename examples/dfp/{v201602 => v201611}/product_service/__init__.py (100%) create mode 100755 examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py rename examples/dfp/{v201602 => v201611}/product_service/get_all_products.py (72%) rename examples/dfp/{v201602 => v201611}/product_service/get_products_for_product_template.py (70%) create mode 100755 examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py rename examples/dfp/{v201602 => v201611}/product_service/update_products.py (99%) rename examples/dfp/{v201602 => v201611}/product_template_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/product_template_service/activate_product_templates.py (97%) rename examples/dfp/{v201602 => v201611}/product_template_service/create_product_templates.py (97%) create mode 100755 examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py rename examples/dfp/{v201602 => v201611}/product_template_service/get_all_product_templates.py (68%) rename examples/dfp/{v201602 => v201611}/product_template_service/get_sponsorship_product_templates.py (63%) rename examples/dfp/{v201602 => v201611}/product_template_service/update_product_templates.py (98%) rename examples/dfp/{v201602 => v201611}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/proposal_line_item_service/archive_proposal_line_items.py (98%) create mode 100755 examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py create mode 100755 examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename examples/dfp/{v201602 => v201611}/proposal_line_item_service/create_proposal_line_items.py (97%) rename examples/dfp/{v201602 => v201611}/proposal_line_item_service/get_all_proposal_line_items.py (60%) rename examples/dfp/{v201602 => v201611}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (54%) rename examples/dfp/{v201602 => v201611}/proposal_line_item_service/update_proposal_line_items.py (94%) rename examples/dfp/{v201602 => v201611}/proposal_service/__init__.py (100%) create mode 100755 examples/dfp/v201611/proposal_service/create_programmatic_proposals.py create mode 100755 examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename examples/dfp/{v201602 => v201611}/proposal_service/create_proposals.py (94%) rename examples/dfp/{v201602 => v201611}/proposal_service/get_all_proposals.py (72%) create mode 100755 examples/dfp/v201611/proposal_service/get_marketplace_comments.py rename examples/dfp/{v201602/proposal_service/get_proposals_by_statement.py => v201611/proposal_service/get_proposals_pending_approval.py} (66%) create mode 100755 examples/dfp/v201611/proposal_service/request_buyers_acceptance.py rename examples/dfp/{v201602 => v201611}/proposal_service/submit_proposals_for_approval.py (96%) rename examples/dfp/{v201602 => v201611}/proposal_service/update_proposals.py (90%) rename examples/dfp/{v201602 => v201611}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/publisher_query_language_service/fetch_match_tables.py (90%) rename examples/dfp/{v201602/publisher_query_language_service/get_line_items_named_like.py => v201611/publisher_query_language_service/get_all_programmatic_buyers.py} (57%) rename examples/dfp/{v201602 => v201611}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/rate_card_service/get_all_rate_cards.py (64%) rename examples/dfp/{v201602/rate_card_service/get_rate_cards_priced_with_currency.py => v201611/rate_card_service/get_marketplace_rate_cards.py} (58%) create mode 100755 examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py create mode 100755 examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py create mode 100755 examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py create mode 100755 examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py create mode 100755 examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename examples/dfp/{v201602 => v201611}/report_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/report_service/run_delivery_report.py (93%) rename examples/dfp/{v201602 => v201611}/report_service/run_inventory_report.py (94%) rename examples/dfp/{v201602 => v201611}/report_service/run_reach_report.py (96%) rename examples/dfp/{v201602 => v201611}/report_service/run_report_with_custom_fields.py (94%) rename examples/dfp/{v201602 => v201611}/report_service/run_sales_report.py (92%) create mode 100755 examples/dfp/v201611/report_service/run_saved_query.py rename examples/dfp/{v201602 => v201611}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (97%) rename examples/dfp/{v201602 => v201611}/suggested_ad_unit_service/get_all_suggested_ad_units.py (69%) rename examples/dfp/{v201602/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py => v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py} (58%) rename examples/dfp/{v201602 => v201611}/team_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/team_service/create_teams.py (98%) rename examples/dfp/{v201602 => v201611}/team_service/get_all_teams.py (70%) rename examples/dfp/{v201602 => v201611}/team_service/update_teams.py (75%) rename examples/dfp/{v201602 => v201611}/user_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/user_service/create_users.py (94%) rename examples/dfp/{v201602 => v201611}/user_service/deactivate_users.py (98%) rename examples/dfp/{v201602 => v201611}/user_service/get_all_roles.py (75%) rename examples/dfp/{v201602 => v201611}/user_service/get_all_users.py (73%) create mode 100755 examples/dfp/v201611/user_service/get_user_by_email_address.py rename examples/dfp/{v201602 => v201611}/user_service/update_users.py (96%) rename examples/dfp/{v201602 => v201611}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201602 => v201611}/user_team_association_service/delete_user_team_associations.py (98%) rename examples/dfp/{v201602 => v201611}/user_team_association_service/get_all_user_team_associations.py (63%) rename examples/dfp/{v201602 => v201611}/user_team_association_service/get_user_team_associations_for_user.py (59%) rename examples/dfp/{v201602 => v201611}/user_team_association_service/update_user_team_associations.py (98%) rename examples/dfp/{v201602 => v201611}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201602 => v201611}/workflow_request_service/approve_workflow_approval_requests.py (97%) rename examples/dfp/{v201602/workflow_request_service/get_workflow_approval_requests_by_statement.py => v201611/workflow_request_service/get_workflow_approval_requests.py} (62%) rename examples/dfp/{v201602/workflow_request_service/get_workflow_external_condition_requests_by_statement.py => v201611/workflow_request_service/get_workflow_external_condition_requests.py} (61%) rename examples/dfp/{v201602 => v201611}/workflow_request_service/trigger_workflow_external_condition_requests.py (98%) diff --git a/ChangeLog b/ChangeLog index bf18d2df..00f93722 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,16 @@ +4.8.0 -- 11/29/16: +* Added support for DFP v201611. +* Removed support for DFP v201508 and v201511. +* Removed examples for DFP v201602. +* Resolved issues: + Issue 138: https://github.com/googleads/googleads-python-lib/issues/138 + Issue 147: https://github.com/googleads/googleads-python-lib/issues/147 + Issue 152: https://github.com/googleads/googleads-python-lib/issues/152 + Issue 158: https://github.com/googleads/googleads-python-lib/issues/158 + Issue 162: https://github.com/googleads/googleads-python-lib/issues/162 +* Resolved Pull Requests: + PR 163: https://github.com/googleads/googleads-python-lib/pull/163 + 4.7.0 -- 10/25/16: * Removed support for AdWords v201603. diff --git a/examples/adwords/v201605/misc/upload_image.py b/examples/adwords/v201605/misc/upload_image.py index 564603df..d762e10c 100755 --- a/examples/adwords/v201605/misc/upload_image.py +++ b/examples/adwords/v201605/misc/upload_image.py @@ -37,8 +37,8 @@ def main(client, image_filename): # Initialize appropriate service. media_service = client.GetService('MediaService', version='v201605') - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) + with open(image_filename, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') # Construct media and upload image. media = [{ diff --git a/examples/adwords/v201607/misc/upload_image.py b/examples/adwords/v201607/misc/upload_image.py index abb26584..f7924112 100755 --- a/examples/adwords/v201607/misc/upload_image.py +++ b/examples/adwords/v201607/misc/upload_image.py @@ -37,8 +37,8 @@ def main(client, image_filename): # Initialize appropriate service. media_service = client.GetService('MediaService', version='v201607') - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) + with open(image_filename, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') # Construct media and upload image. media = [{ diff --git a/examples/adwords/v201609/misc/upload_image.py b/examples/adwords/v201609/misc/upload_image.py index ef13ff54..e0bde8f9 100755 --- a/examples/adwords/v201609/misc/upload_image.py +++ b/examples/adwords/v201609/misc/upload_image.py @@ -37,8 +37,8 @@ def main(client, image_filename): # Initialize appropriate service. media_service = client.GetService('MediaService', version='v201609') - with open(image_filename, 'r') as image_handle: - image_data = base64.encodestring(image_handle.read()) + with open(image_filename, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') # Construct media and upload image. media = [{ diff --git a/examples/dfp/v201602/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201602/activity_group_service/get_active_activity_groups.py deleted file mode 100755 index dd3abcb4..00000000 --- a/examples/dfp/v201602/activity_group_service/get_active_activity_groups.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active activity groups. - -To create activity groups, run create_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201602') - - # Create statement object to only select active activity groups. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get activity groups by statement. - while True: - response = activity_group_service.getActivityGroupsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity_group in response['results']: - print ('Activity group with ID \'%s\' and name \'%s\' was found.' - % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/activity_service/get_active_activities.py b/examples/dfp/v201602/activity_service/get_active_activities.py deleted file mode 100755 index c2ec75bf..00000000 --- a/examples/dfp/v201602/activity_service/get_active_activities.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active activities. - -To create activities, run create_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201602') - - # Create statement object to only select active activities. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get activities by statement. - while True: - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity in response['results']: - print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (activity['id'], activity['name'], activity['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/company_service/get_advertisers.py b/examples/dfp/v201602/company_service/get_advertisers.py deleted file mode 100755 index cff77570..00000000 --- a/examples/dfp/v201602/company_service/get_advertisers.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all companies that are advertisers. - -To create companies, run create_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201602') - - # Create statement object to only select companies that are advertisers. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - } - }] - query = 'WHERE type = :type' - statement = dfp.FilterStatement(query, values) - - # Get companies by statement. - while True: - response = company_service.getCompaniesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for company in response['results']: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.' - % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/contact_service/get_uninvited_contacts.py b/examples/dfp/v201602/contact_service/get_uninvited_contacts.py deleted file mode 100755 index a2bcc4aa..00000000 --- a/examples/dfp/v201602/contact_service/get_uninvited_contacts.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all contacts that aren't invited yet. - -To create contacts, run create_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201602') - - # Create statement object to only select contacts that are uninvited. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get contacts by statement. - while True: - response = contact_service.getContactsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for contact in response['results']: - print ('Contact with ID \'%s\' and name \'%s\' was found.' - % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201602/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py deleted file mode 100755 index 3a782798..00000000 --- a/examples/dfp/v201602/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all content metadata key hierarchies. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201602') - - # Create statement object to select all content. - statement = dfp.FilterStatement() - - # Get content by statement. - while True: - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())[0]) - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - if content_metadata_key_hierarchies: - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchyy with id \'%s\' and name \'%s\'' - ' was found.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/content_service/get_all_content.py b/examples/dfp/v201602/content_service/get_all_content.py deleted file mode 100755 index 5fa483cd..00000000 --- a/examples/dfp/v201602/content_service/get_all_content.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all content. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201602') - - # Create statement object to select all content. - statement = dfp.FilterStatement() - - # Get content by statement. - while True: - response = content_service.getContentByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for content_item in response['results']: - print ('Content with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (content_item['id'], content_item['name'], - content_item['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/content_service/get_content_by_category.py b/examples/dfp/v201602/content_service/get_content_by_category.py deleted file mode 100755 index b563f85d..00000000 --- a/examples/dfp/v201602/content_service/get_content_by_category.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active content categorized as a "comedy" using the -network's content browse custom targeting key. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201602') - network_service = client.GetService('NetworkService', version='v201602') - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') - - # Get the network's content browse custom targeting key. - network = network_service.getCurrentNetwork() - key_id = network['contentBrowseCustomTargetingKeyId'] - - # Create a statement to select the categories matching the name comedy. - values = [ - { - 'key': 'contentBrowseCustomTargetingKeyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }, - { - 'key': 'category', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'comedy' - } - } - ] - category_filter_query = ('WHERE customTargetingKeyId = ' - ':contentBrowseCustomTargetingKeyId and name = ' - ':category') - category_filter_statement = dfp.FilterStatement( - category_filter_query, values, 1) - - # Get categories matching the filter statement. - response = custom_targeting_service.getCustomTargetingValuesByStatement( - category_filter_statement.ToStatement()) - - # Get the custom targeting value ID for the comedy category. - if 'results' in response: - category_custom_targeting_value_id = (response['results']['id']) - - # Create a statement to select the active content. - content_values = [ - { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - } - ] - content_query = 'WHERE status = :status' - content_statement = dfp.FilterStatement(content_query, content_values) - - while True: - # Get the content by statement and custom targeting value. - response = content_service.getContentByStatementAndCustomTargetingValue( - content_statement.ToStatement(), - category_custom_targeting_value_id) - if 'results' in response: - # Display results. - for content_item in response['results']: - print ('Content with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (content_item['id'], content_item['name'], - content_item['status'])) - content_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/creative_service/get_creatives_by_statement.py b/examples/dfp/v201602/creative_service/get_creatives_by_statement.py deleted file mode 100755 index e0280e99..00000000 --- a/examples/dfp/v201602/creative_service/get_creatives_by_statement.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all image creatives. - -To create an image creative, run create_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201602') - - # Create statement object to only select image creatives. - values = [{ - 'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }] - query = 'WHERE creativeType = :creativeType' - statement = dfp.FilterStatement(query, values) - - # Get creatives by statement. - while True: - response = creative_service.getCreativesByStatement( - statement.ToStatement()) - creatives = response['results'] - - if creatives: - # Display results. - for creative in creatives: - print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (creative['id'], creative['name'], - dfp.DfpClassType(creative))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201602/creative_template_service/get_creative_templates_by_statement.py deleted file mode 100755 index b1a74adc..00000000 --- a/examples/dfp/v201602/creative_template_service/get_creative_templates_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all system defined creative templates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201602') - - # Create statement object to only select system defined creative templates. - values = [{ - 'key': 'creativeTemplateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - } - }] - query = 'WHERE type = :creativeTemplateType' - statement = dfp.FilterStatement(query, values) - - # Get creative templates by statement. - while True: - response = creative_template_service.getCreativeTemplatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for template in response['results']: - print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' ' - 'was found.' % (template['id'], - template['name'], - template['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201602/creative_wrapper_service/get_active_creative_wrappers.py deleted file mode 100755 index 3dc66413..00000000 --- a/examples/dfp/v201602/creative_wrapper_service/get_active_creative_wrappers.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active creative wrappers. - -To create creative wrappers, run create_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201602') - - # Create statement object to only select active creative wrappers. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get creative wrappers by statement. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'found.' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201602/custom_targeting_service/get_all_custom_targeting_keys_and_values.py deleted file mode 100755 index 2700ddf9..00000000 --- a/examples/dfp/v201602/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 targeting keys and the values. - -To create custom targeting keys and values, run -create_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') - - # Create statement to get all targeting keys. - targeting_key_statement = dfp.FilterStatement() - - all_keys = [] - - # Get custom targeting keys by statement. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - targeting_key_statement.ToStatement()) - if 'results' in response: - all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if all_keys: - # Create map of custom targeting key id to custom targeting values. - key_value_map = {} - - # Create statement to get all targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' - % ', '.join([str(key['id']) for key in all_keys])) - targeting_value_statement = dfp.FilterStatement(query) - - # Get custom targeting values by statement. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - targeting_value_statement.ToStatement()) - if 'results' in response: - for key in all_keys: - for value in response['results']: - if key['id'] == value['customTargetingKeyId']: - if key['id'] not in key_value_map.keys(): - key_value_map[key['id']] = [] - key_value_map[key['id']].append(value) - targeting_value_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - for key in all_keys: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was found.' - %(key['id'], key['name'], key['displayName'], key['type'])) - if key['id'] in key_value_map.keys(): - for value in key_value_map[key['id']]: - print ('\tCustom targeting value with id \'%s\', name \'%s\', and ' - 'display name \'%s\' was found.' - % (value['id'], value['name'], value['displayName'])) - else: - print 'No keys were found.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) - diff --git a/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_values_by_statement.py deleted file mode 100755 index 8c7e6ac3..00000000 --- a/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 custom targeting values for the given predefined custom -targeting key. - -To create custom targeting values, run -create_custom_targeting_keys_and_values.py. To determine which custom -targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') - - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) - - # Get custom targeting values by statement. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for value in response['results']: - print ('Custom targeting value with id \'%s\', name \'%s\', and display' - ' name \'%s\' was found.' - % (value['id'], value['name'], value['displayName'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201602/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201602/inventory_service/get_ad_unit_hierarchy.py deleted file mode 100755 index 1c617a58..00000000 --- a/examples/dfp/v201602/inventory_service/get_ad_unit_hierarchy.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code gets the ad unit hierarchy and displays it as a tree. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201602') - statement = dfp.FilterStatement() - - all_ad_units = [] - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - all_ad_units.extend(response['results']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Find the root ad unit. root_ad_unit can also be set to child unit to only - # build and display a portion of the tree. - query = 'WHERE parentId IS NULL' - root_statement = dfp.FilterStatement(query) - response = inventory_service.getAdUnitsByStatement( - root_statement.ToStatement()) - root_ad_unit = response['results'] - - if root_ad_unit: - BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units) - else: - print 'Could not build tree. No root ad unit found.' - - -def DisplayAdUnitTree(root_ad_unit, ad_unit_tree, depth=0): - """Helper for displaying ad unit tree. - - Args: - root_ad_unit: dict the root ad unit. - ad_unit_tree: dict the tree of ad units. - [optional] - depth: int the depth the tree has reached. - """ - print '%s%s (%s)' % (GenerateTab(depth), root_ad_unit['name'], - root_ad_unit['id']) - if root_ad_unit['id'] in ad_unit_tree: - for child in ad_unit_tree[root_ad_unit['id']]: - DisplayAdUnitTree(child, ad_unit_tree, depth+1) - - -def GenerateTab(depth): - """Generate tabs to represent branching to children. - - Args: - depth: int the depth the tree has reached. - - Returns: - string inserted in front of the root unit. - """ - tab_list = [] - if depth > 0: - tab_list.append(' ') - tab_list.append('| ' * depth) - tab_list.append('+--') - return ''.join(tab_list) - - -def BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units): - """Create an ad unit tree and display it. - - Args: - root_ad_unit: dict the root ad unit to build the tree under. - all_ad_units: list the list of all ad units to build the tree with. - """ - tree = {} - for ad_unit in all_ad_units: - if 'parentId' in ad_unit: - if ad_unit['parentId'] not in tree: - tree[ad_unit['parentId']] = [] - tree[ad_unit['parentId']].append(ad_unit) - - DisplayAdUnitTree(root_ad_unit, tree) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201602/inventory_service/get_all_ad_unit_sizes.py deleted file mode 100755 index 324b52b5..00000000 --- a/examples/dfp/v201602/inventory_service/get_all_ad_unit_sizes.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all ad unit sizes defined in a network. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201602') - statement = dfp.FilterStatement() - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitSizesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit_size in response['results']: - print ('Ad unit size of dimensions %s was found.' % - (ad_unit_size['fullDisplayString'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/inventory_service/get_all_ad_units.py b/examples/dfp/v201602/inventory_service/get_all_ad_units.py deleted file mode 100755 index 1bd0f91f..00000000 --- a/examples/dfp/v201602/inventory_service/get_all_ad_units.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all ad units within a network. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201602') - statement = dfp.FilterStatement() - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' was found.' - % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201602/inventory_service/get_top_level_ad_units.py deleted file mode 100755 index e47de3ec..00000000 --- a/examples/dfp/v201602/inventory_service/get_top_level_ad_units.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all child ad units of the effective root ad unit. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201602') - network_service = client.GetService('NetworkService', version='v201602') - - root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - # Create a statement to select the children of the effective root ad unit. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': root_id - } - }] - query = 'WHERE parentId = :id' - statement = dfp.FilterStatement(query, values) - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' was found.' - % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201602/line_item_service/get_line_items_by_statement.py deleted file mode 100755 index 699480a9..00000000 --- a/examples/dfp/v201602/line_item_service/get_line_items_by_statement.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all line items that need creatives for an order. - -To create line items, run create_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') - - # Create statement object to only select line items that need creatives from a - # given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - }] - query = ('WHERE orderId = :orderId AND ' - 'isMissingCreatives = :isMissingCreatives') - statement = dfp.FilterStatement(query, values) - - while True: - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % (line_item['id'], - line_item['orderId'], - line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201602/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201602/line_item_service/get_recently_updated_line_items.py deleted file mode 100755 index 2f8eb46d..00000000 --- a/examples/dfp/v201602/line_item_service/get_recently_updated_line_items.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example shows how to get recently updated line items. - -To create line items, run create_line_items.py.""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import dfp - -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') - - # Create statement object to only select line items belonging to the order and - # have been modified in the last 3 days. - three_days_ago = datetime.date.today() - datetime.timedelta(days=3) - values = [{ - 'key': 'dateTimeString', - 'value': { - 'xsi_type': 'TextValue', - 'value': three_days_ago.strftime('%Y-%m-%dT%H:%M:%S') - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE lastModifiedDateTime >= :dateTimeString AND orderId = :orderId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % (line_item['id'], - line_item['orderId'], - line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201602/order_service/get_orders_by_statement.py b/examples/dfp/v201602/order_service/get_orders_by_statement.py deleted file mode 100755 index 0ae4e06c..00000000 --- a/examples/dfp/v201602/order_service/get_orders_by_statement.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets an order by an ID. - -To create orders, run create_orders.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the order to get. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201602') - - # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - - statement = dfp.FilterStatement(query, values) - - # Get orders by statement. - response = order_service.getOrdersByStatement(statement.ToStatement()) - orders = [] - if 'results' in response: - orders = response['results'] - - # Display results. - for order in orders: - print ('Order with id \'%s\' name \'%s\' was found.' - % (order['id'], order['name'])) - - print '\nNumber of results found: %s' % len(orders) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201602/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201602/publisher_query_language_service/get_geo_targets.py deleted file mode 100755 index f4b2131d..00000000 --- a/examples/dfp/v201602/publisher_query_language_service/get_geo_targets.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 geographic criteria from the Geo_Target table. - -The types available to filter on include 'City', 'Country', 'Region', 'State', -'Postal_Code', and 'DMA_Region' (i.e. Metro). - -A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201602/PublisherQueryLanguageService -""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201602') - - output_file = tempfile.NamedTemporaryFile( - prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) - - # Create bind value to select geo-targets of type 'City'. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'City' - } - }] - - pql_query = ('SELECT Name, Id FROM Geo_Target ' - 'WHERE targetable = true AND Type = :type') - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - pql_query, output_file, values) - output_file.close() - - print ('Saved geo targets to... %s' % output_file.name) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/team_service/get_teams_by_statement.py b/examples/dfp/v201602/team_service/get_teams_by_statement.py deleted file mode 100755 index 4b9c00fc..00000000 --- a/examples/dfp/v201602/team_service/get_teams_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a single team by ID. - -To create teams, run create_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -TEAM_ID = 'INSERT_TEAM_ID_HERE' - - -def main(client, team_id): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201602') - - # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get teams by statement. - response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for team in response['results']: - print ('Team with id \'%s\' and name \'%s\' was found.' - % (team['id'], team['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID) diff --git a/examples/dfp/v201602/user_service/get_current_user.py b/examples/dfp/v201602/user_service/get_current_user.py deleted file mode 100755 index 27426f56..00000000 --- a/examples/dfp/v201602/user_service/get_current_user.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets the current user.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201602') - - # Get current user. - user = user_service.getCurrentUser() - - # Display results. - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201602/user_service/get_users_by_statement.py b/examples/dfp/v201602/user_service/get_users_by_statement.py deleted file mode 100755 index 4b729bae..00000000 --- a/examples/dfp/v201602/user_service/get_users_by_statement.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets a user by its id. - -To create users, run create_user.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_TO_FIND_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201602') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get users by statement. - response = user_service.getUsersByStatement(statement.ToStatement()) - users = response['results'] if 'results' in response else [] - - for user in users: - # Display results. - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py index abd058ec..9da61c0f 100755 --- a/examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -72,7 +72,7 @@ def main(client): # Create custom targeting value objects. values = [ { - 'customTargetingKeyId': keys['id'], + 'customTargetingKeyId': keys[0]['id'], 'displayName': 'male', # Name is set to 1 so that the actual name can be hidden from website # users. @@ -80,7 +80,7 @@ def main(client): 'matchType': 'EXACT' }, { - 'customTargetingKeyId': keys['id'], + 'customTargetingKeyId': keys[0]['id'], 'displayName': 'female', # Name is set to 2 so that the actual name can be hidden from website # users. diff --git a/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py index 2750bda5..547145f0 100755 --- a/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py @@ -55,7 +55,7 @@ def main(client, key_name): response = custom_targeting_service.getCustomTargetingKeysByStatement( statement.ToStatement()) if 'results' in response: - key_ids = [key['id'] for key in response['results']] + key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) key_statement = dfp.FilterStatement(key_query) diff --git a/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py index 912771f8..a55f48d0 100755 --- a/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -72,7 +72,7 @@ def main(client): # Create custom targeting value objects. values = [ { - 'customTargetingKeyId': keys['id'], + 'customTargetingKeyId': keys[0]['id'], 'displayName': 'male', # Name is set to 1 so that the actual name can be hidden from website # users. @@ -80,7 +80,7 @@ def main(client): 'matchType': 'EXACT' }, { - 'customTargetingKeyId': keys['id'], + 'customTargetingKeyId': keys[0]['id'], 'displayName': 'female', # Name is set to 2 so that the actual name can be hidden from website # users. diff --git a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py index 4882cf8a..38c327f2 100755 --- a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py @@ -55,7 +55,7 @@ def main(client, key_name): response = custom_targeting_service.getCustomTargetingKeysByStatement( statement.ToStatement()) if 'results' in response: - key_ids = [key['id'] for key in response['results']] + key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) key_statement = dfp.FilterStatement(key_query) diff --git a/examples/dfp/v201602/activity_group_service/__init__.py b/examples/dfp/v201611/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201602/activity_group_service/__init__.py rename to examples/dfp/v201611/activity_group_service/__init__.py diff --git a/examples/dfp/v201602/activity_group_service/create_activity_groups.py b/examples/dfp/v201611/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201602/activity_group_service/create_activity_groups.py rename to examples/dfp/v201611/activity_group_service/create_activity_groups.py index 01b05c17..45f1487b 100755 --- a/examples/dfp/v201602/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201602') + version='v201611') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py new file mode 100755 index 00000000..55284d6c --- /dev/null +++ b/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 active activity groups. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + activity_group_service = client.GetService( + 'ActivityGroupService', version='v201611') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select activity groups. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of activity groups at a time, paging + # through until all activity groups have been retrieved. + while True: + response = activity_group_service.getActivityGroupsByStatement( + statement.ToStatement()) + if 'results' in response: + for activity_group in response['results']: + # Print out some information for each activity group. + print('Activity group with ID "%d" and name "%s" was found.\n' % + (activity_group['id'], activity_group['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py similarity index 61% rename from examples/dfp/v201602/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201611/activity_group_service/get_all_activity_groups.py index 9020c1ff..a2b2290c 100755 --- a/examples/dfp/v201602/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,40 +13,31 @@ # 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 code example gets all activity groups. - -To create activity groups, run create_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all activity groups. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201602') + activity_group_service = client.GetService( + 'ActivityGroupService', version='v201611') - # Create a filter statement. + # Create a statement to select activity groups. statement = dfp.FilterStatement() - # Get activity groups by statement. + # Retrieve a small amount of activity groups at a time, paging + # through until all activity groups have been retrieved. while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for activity_group in response['results']: - print ('Activity group with ID \'%s\' and name \'%s\' was found.' - % (activity_group['id'], activity_group['name'])) + # Print out some information for each activity group. + print('Activity group with ID "%d" and name "%s" was found.\n' % + (activity_group['id'], activity_group['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/activity_group_service/update_activity_groups.py b/examples/dfp/v201611/activity_group_service/update_activity_groups.py similarity index 97% rename from examples/dfp/v201602/activity_group_service/update_activity_groups.py rename to examples/dfp/v201611/activity_group_service/update_activity_groups.py index b984cc00..b2cb9bf1 100755 --- a/examples/dfp/v201602/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/update_activity_groups.py @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201602') + version='v201611') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201602/activity_service/__init__.py b/examples/dfp/v201611/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201602/activity_service/__init__.py rename to examples/dfp/v201611/activity_service/__init__.py diff --git a/examples/dfp/v201602/activity_service/create_activities.py b/examples/dfp/v201611/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201602/activity_service/create_activities.py rename to examples/dfp/v201611/activity_service/create_activities.py index 1624f8b8..c8ff8e9e 100755 --- a/examples/dfp/v201602/activity_service/create_activities.py +++ b/examples/dfp/v201611/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201602') + activity_service = client.GetService('ActivityService', version='v201611') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201602/activity_service/get_all_activities.py b/examples/dfp/v201611/activity_service/get_active_activities.py similarity index 58% rename from examples/dfp/v201602/activity_service/get_all_activities.py rename to examples/dfp/v201611/activity_service/get_active_activities.py index 7bf0281a..b04b9566 100755 --- a/examples/dfp/v201602/activity_service/get_all_activities.py +++ b/examples/dfp/v201611/activity_service/get_active_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,44 @@ # 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 code example gets all activities. - -To create activities, run create_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all active activities. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201602') - - # Create statement object to select only all activities. - statement = dfp.FilterStatement() - - # Get activities by statement. + activity_service = client.GetService('ActivityService', version='v201611') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select activities. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of activities at a time, paging + # through until all activities have been retrieved. while True: - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) + response = activity_service.getActivitiesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for activity in response['results']: - print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (activity['id'], activity['name'], activity['type'])) + # Print out some information for each activity. + print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % + (activity['id'], activity['name'], activity['type'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201611/activity_service/get_all_activities.py b/examples/dfp/v201611/activity_service/get_all_activities.py new file mode 100755 index 00000000..d7eca262 --- /dev/null +++ b/examples/dfp/v201611/activity_service/get_all_activities.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# +# Copyright 2016 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 activities. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + activity_service = client.GetService('ActivityService', version='v201611') + + # Create a statement to select activities. + statement = dfp.FilterStatement() + + # Retrieve a small amount of activities at a time, paging + # through until all activities have been retrieved. + while True: + response = activity_service.getActivitiesByStatement(statement.ToStatement( + )) + if 'results' in response: + for activity in response['results']: + # Print out some information for each activity. + print('Activity with ID "%d" and name "%s" was found.\n' % + (activity['id'], activity['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/activity_service/update_activities.py b/examples/dfp/v201611/activity_service/update_activities.py similarity index 99% rename from examples/dfp/v201602/activity_service/update_activities.py rename to examples/dfp/v201611/activity_service/update_activities.py index c7285189..d29a2d36 100755 --- a/examples/dfp/v201602/activity_service/update_activities.py +++ b/examples/dfp/v201611/activity_service/update_activities.py @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201602') + activity_service = client.GetService('ActivityService', version='v201611') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201602/audience_segment_service/__init__.py b/examples/dfp/v201611/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201602/audience_segment_service/__init__.py rename to examples/dfp/v201611/audience_segment_service/__init__.py diff --git a/examples/dfp/v201602/audience_segment_service/create_audience_segments.py b/examples/dfp/v201611/audience_segment_service/create_audience_segments.py similarity index 95% rename from examples/dfp/v201602/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201611/audience_segment_service/create_audience_segments.py index cf698887..b463e4c3 100755 --- a/examples/dfp/v201602/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/create_audience_segments.py @@ -26,11 +26,12 @@ CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' + def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201602') - network_service = client.GetService('NetworkService', version='v201602') + 'AudienceSegmentService', version='v201611') + network_service = client.GetService('NetworkService', version='v201611') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( @@ -92,4 +93,4 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) + main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py similarity index 65% rename from examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py index 88d6f495..815e5495 100755 --- a/examples/dfp/v201602/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all audience segments. - -To create audience segments, run create_audience_segments.py. +"""This example gets all audience segments. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,21 +23,22 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201602') + 'AudienceSegmentService', version='v201611') - # Create statement object to select all audience segments. + # Create a statement to select audience segments. statement = dfp.FilterStatement() - # Get audience segments by statement. + # Retrieve a small amount of audience segments at a time, paging + # through until all audience segments have been retrieved. while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for segment in response['results']: - print ('Audience segment with id \'%s\' and name ' - '\'%s\' of size %s was found.' % - (segment['id'], segment['name'], segment['size'])) + for audience_segment in response['results']: + # Print out some information for each audience segment. + print('Audience segment with ID "%d", name "%s", and size "%d" was ' + 'found.\n' % (audience_segment['id'], audience_segment['name'], + audience_segment['size'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py similarity index 59% rename from examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py index 4bdc0feb..d220c92e 100755 --- a/examples/dfp/v201602/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all first party audience segments. - -To create first party audience segments, run create_audience_segments.py. +"""This example gets all first party audience segments. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,30 +23,29 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201602') - - # Create statement object to only select first party audience segments. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }] - query = 'WHERE Type = :type' + 'AudienceSegmentService', version='v201611') + query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'FIRST_PARTY' + }}, + ] + # Create a statement to select audience segments. statement = dfp.FilterStatement(query, values) - # Get audience segments by statement. + # Retrieve a small amount of audience segments at a time, paging + # through until all audience segments have been retrieved. while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: - segments = response['results'] - for segment in segments: - print ('Audience segment with id \'%s\' and name \'%s\' of size ' - '%s was found. ' % - (segment['id'], segment['name'], segment['size'])) + for audience_segment in response['results']: + # Print out some information for each audience segment. + print('Audience segment with ID "%d", name "%s", and size "%d" was ' + 'found.\n' % (audience_segment['id'], audience_segment['name'], + audience_segment['size'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py similarity index 90% rename from examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py index eaec6f08..78f63c91 100755 --- a/examples/dfp/v201602/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py @@ -30,7 +30,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201602') + 'AudienceSegmentService', version='v201611') # Create statement object to get the specified first party audience segment. values = ( @@ -43,7 +43,7 @@ def main(client, audience_segment_id): {'key': 'audience_segment_id', 'value': { 'xsi_type': 'NumberValue', - 'value': AUDIENCE_SEGMENT_ID + 'value': audience_segment_id } }]) query = 'WHERE Type = :type AND Id = :audience_segment_id' @@ -56,8 +56,9 @@ def main(client, audience_segment_id): segments = response['results'] for segment in segments: - print ('Audience segment with id \'%s\' and name \'%s\' will be populated.' - % (segment['id'], segment['name'])) + print ( + 'Audience segment with id \'%s\' and name \'%s\' will be populated.' + % (segment['id'], segment['name'])) action = { 'xsi_type': 'PopulateAudienceSegments' diff --git a/examples/dfp/v201602/audience_segment_service/update_audience_segments.py b/examples/dfp/v201611/audience_segment_service/update_audience_segments.py similarity index 96% rename from examples/dfp/v201602/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201611/audience_segment_service/update_audience_segments.py index ce81cd01..b6ceea81 100755 --- a/examples/dfp/v201602/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/update_audience_segments.py @@ -29,7 +29,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201602') + 'AudienceSegmentService', version='v201611') # Create statement object to get the specified first party audience segment. values = ( @@ -42,7 +42,7 @@ def main(client, audience_segment_id): {'key': 'audience_segment_id', 'value': { 'xsi_type': 'NumberValue', - 'value': AUDIENCE_SEGMENT_ID + 'value': audience_segment_id } }]) query = 'WHERE Type = :type AND Id = :audience_segment_id' diff --git a/examples/dfp/v201602/base_rate_service/__init__.py b/examples/dfp/v201611/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201602/base_rate_service/__init__.py rename to examples/dfp/v201611/base_rate_service/__init__.py diff --git a/examples/dfp/v201602/base_rate_service/create_product_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201602/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201611/base_rate_service/create_product_base_rates.py index 0c622718..96e50bc7 100755 --- a/examples/dfp/v201602/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201602') + 'BaseRateService', version='v201611') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201602/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201602/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py index 2dc3bfb3..d96eb469 100755 --- a/examples/dfp/v201602/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201602') + 'BaseRateService', version='v201611') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201602/base_rate_service/get_all_base_rates.py b/examples/dfp/v201611/base_rate_service/get_all_base_rates.py similarity index 62% rename from examples/dfp/v201602/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201611/base_rate_service/get_all_base_rates.py index 1d0772d5..a49c3838 100755 --- a/examples/dfp/v201602/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/get_all_base_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,39 +13,31 @@ # 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 base rates. - -To create product base rates, run create_product_base_rates.py -To create product template base rates, run -create_product_template_base_rates.py. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201602') + base_rate_service = client.GetService('BaseRateService', version='v201611') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select base rates. + statement = dfp.FilterStatement() - # Get base rates by statement. + # Retrieve a small amount of base rates at a time, paging + # through until all base rates have been retrieved. while True: - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) + response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for base_rate in response['results']: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was found.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) + # Print out some information for each base rate. + print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' + 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py similarity index 57% rename from examples/dfp/v201602/base_rate_service/get_base_rates_for_a_rate_card.py rename to examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py index 6f73b7f0..02728d9f 100755 --- a/examples/dfp/v201602/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,16 +13,9 @@ # 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 base rates. - -To create product base rates, run create_product_base_rates.py -To create product template base rates, run -create_product_template_base_rates.py. - +"""This example gets all base rates belonging to a rate card. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -31,31 +24,30 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201602') - - # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'rateCardId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': rate_card_id - } - }] - query = 'where rateCardId = :rateCardId ORDER BY id ASC' + base_rate_service = client.GetService('BaseRateService', version='v201611') + query = 'WHERE rateCardId = :rateCardId' + values = [ + {'key': 'rateCardId', + 'value': { + 'xsi_type': 'TextValue', + 'value': rate_card_id + }}, + ] + # Create a statement to select base rates. statement = dfp.FilterStatement(query, values) - # Get base rates by statement. + # Retrieve a small amount of base rates at a time, paging + # through until all base rates have been retrieved. while True: - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) + response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for base_rate in response['results']: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was found.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) + # Print out some information for each base rate. + print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' + 'found.\n' % + (base_rate['id'], dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/base_rate_service/update_base_rates.py b/examples/dfp/v201611/base_rate_service/update_base_rates.py similarity index 99% rename from examples/dfp/v201602/base_rate_service/update_base_rates.py rename to examples/dfp/v201611/base_rate_service/update_base_rates.py index bdb18701..ab15fe5e 100755 --- a/examples/dfp/v201602/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201602') + base_rate_service = client.GetService('BaseRateService', version='v201611') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201602/company_service/__init__.py b/examples/dfp/v201611/company_service/__init__.py similarity index 100% rename from examples/dfp/v201602/company_service/__init__.py rename to examples/dfp/v201611/company_service/__init__.py diff --git a/examples/dfp/v201602/company_service/create_companies.py b/examples/dfp/v201611/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201602/company_service/create_companies.py rename to examples/dfp/v201611/company_service/create_companies.py index 3b7d1080..b9e7d07c 100755 --- a/examples/dfp/v201602/company_service/create_companies.py +++ b/examples/dfp/v201611/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201602') + company_service = client.GetService('CompanyService', version='v201611') # Create company objects. companies = [ diff --git a/examples/dfp/v201602/company_service/get_all_companies.py b/examples/dfp/v201611/company_service/get_advertisers.py similarity index 59% rename from examples/dfp/v201602/company_service/get_all_companies.py rename to examples/dfp/v201611/company_service/get_advertisers.py index ea3de273..2b0ba1b5 100755 --- a/examples/dfp/v201602/company_service/get_all_companies.py +++ b/examples/dfp/v201611/company_service/get_advertisers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,43 @@ # 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 code example gets all companies. - -To create companies, run create_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all companies that are advertisers. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201602') - - # Create statement object to select all companies. - statement = dfp.FilterStatement() - - # Get companies by statement. + company_service = client.GetService('CompanyService', version='v201611') + query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ADVERTISER' + }}, + ] + # Create a statement to select companies. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of companies at a time, paging + # through until all companies have been retrieved. while True: - response = company_service.getCompaniesByStatement( - statement.ToStatement()) + response = company_service.getCompaniesByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for company in response['results']: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.' - % (company['id'], company['name'], company['type'])) + # Print out some information for each company. + print('Company with ID "%d", name "%s", and type "%s" was found.\n' % + (company['id'], company['name'], company['type'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201611/company_service/get_all_companies.py b/examples/dfp/v201611/company_service/get_all_companies.py new file mode 100755 index 00000000..8a4a6937 --- /dev/null +++ b/examples/dfp/v201611/company_service/get_all_companies.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 companies. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + company_service = client.GetService('CompanyService', version='v201611') + + # Create a statement to select companies. + statement = dfp.FilterStatement() + + # Retrieve a small amount of companies at a time, paging + # through until all companies have been retrieved. + while True: + response = company_service.getCompaniesByStatement(statement.ToStatement()) + if 'results' in response: + for company in response['results']: + # Print out some information for each company. + print('Company with ID "%d", name "%s", and type "%s" was found.\n' % + (company['id'], company['name'], company['type'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/company_service/update_companies.py b/examples/dfp/v201611/company_service/update_companies.py similarity index 99% rename from examples/dfp/v201602/company_service/update_companies.py rename to examples/dfp/v201611/company_service/update_companies.py index ed860582..3bf0e14b 100755 --- a/examples/dfp/v201602/company_service/update_companies.py +++ b/examples/dfp/v201611/company_service/update_companies.py @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201602') + company_service = client.GetService('CompanyService', version='v201611') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201602/contact_service/__init__.py b/examples/dfp/v201611/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201602/contact_service/__init__.py rename to examples/dfp/v201611/contact_service/__init__.py diff --git a/examples/dfp/v201602/contact_service/create_contacts.py b/examples/dfp/v201611/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201602/contact_service/create_contacts.py rename to examples/dfp/v201611/contact_service/create_contacts.py index 11700297..9854ab64 100755 --- a/examples/dfp/v201602/contact_service/create_contacts.py +++ b/examples/dfp/v201611/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201602') + contact_service = client.GetService('ContactService', version='v201611') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201611/contact_service/get_all_contacts.py b/examples/dfp/v201611/contact_service/get_all_contacts.py new file mode 100755 index 00000000..594f9422 --- /dev/null +++ b/examples/dfp/v201611/contact_service/get_all_contacts.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 contacts. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + contact_service = client.GetService('ContactService', version='v201611') + + # Create a statement to select contacts. + statement = dfp.FilterStatement() + + # Retrieve a small amount of contacts at a time, paging + # through until all contacts have been retrieved. + while True: + response = contact_service.getContactsByStatement(statement.ToStatement()) + if 'results' in response: + for contact in response['results']: + # Print out some information for each contact. + print('Contact with ID "%d" and name "%s" was found.\n' % + (contact['id'], contact['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/contact_service/get_all_contacts.py b/examples/dfp/v201611/contact_service/get_uninvited_contacts.py similarity index 60% rename from examples/dfp/v201602/contact_service/get_all_contacts.py rename to examples/dfp/v201611/contact_service/get_uninvited_contacts.py index 483a0cfc..7e98ec79 100755 --- a/examples/dfp/v201602/contact_service/get_all_contacts.py +++ b/examples/dfp/v201611/contact_service/get_uninvited_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,43 @@ # 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 code example gets all contacts. - -To create contacts, run create_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all contacts that aren't invited yet. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201602') - - # Create statement object to get all contacts. - statement = dfp.FilterStatement() - - # Get contacts by statement. + contact_service = client.GetService('ContactService', version='v201611') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'UNINVITED' + }}, + ] + # Create a statement to select contacts. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of contacts at a time, paging + # through until all contacts have been retrieved. while True: - response = contact_service.getContactsByStatement( - statement.ToStatement()) + response = contact_service.getContactsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for contact in response['results']: - print ('Contact with ID \'%s\' and name \'%s\' was found.' - % (contact['id'], contact['name'])) + # Print out some information for each contact. + print('Contact with ID "%d" and name "%s" was found.\n' % + (contact['id'], contact['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/contact_service/update_contacts.py b/examples/dfp/v201611/contact_service/update_contacts.py similarity index 99% rename from examples/dfp/v201602/contact_service/update_contacts.py rename to examples/dfp/v201611/contact_service/update_contacts.py index e4e543d6..a4fbac28 100755 --- a/examples/dfp/v201602/contact_service/update_contacts.py +++ b/examples/dfp/v201611/contact_service/update_contacts.py @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201602') + contact_service = client.GetService('ContactService', version='v201611') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201602/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201602/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201602/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201602/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 482885f1..ab288f07 100755 --- a/examples/dfp/v201602/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201602') + 'ContentMetadataKeyHierarchyService', version='v201611') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201602/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201602/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index f040e967..e815b89a 100755 --- a/examples/dfp/v201602/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201602') + 'ContentMetadataKeyHierarchyService', version='v201611') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py new file mode 100755 index 00000000..795c7f0c --- /dev/null +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2016 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 content metadata key hierarchies. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + content_metadata_key_hierarchy_service = client.GetService( + 'ContentMetadataKeyHierarchyService', version='v201611') + + # Create a statement to select content metadata key hierarchies. + statement = dfp.FilterStatement() + + # Retrieve a small amount of content metadata key hierarchies at a time, + # paging through until all content metadata key hierarchies have been + # retrieved. + while True: + response = ( + content_metadata_key_hierarchy_service + .getContentMetadataKeyHierarchiesByStatement( + statement.ToStatement())) + if 'results' in response: + for content_metadata_key_hierarchy in response['results']: + # Print out some information for each content metadata key hierarchy. + print('Content metadata key hierarchy with ID "%d" and name "%s" was ' + 'found.\n' % (content_metadata_key_hierarchy['id'], + content_metadata_key_hierarchy['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 98% rename from examples/dfp/v201602/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 399e7e6d..c463f7ea 100755 --- a/examples/dfp/v201602/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201602') + 'ContentMetadataKeyHierarchyService', version='v201611') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201602/content_service/__init__.py b/examples/dfp/v201611/content_service/__init__.py similarity index 100% rename from examples/dfp/v201602/content_service/__init__.py rename to examples/dfp/v201611/content_service/__init__.py diff --git a/examples/dfp/v201611/content_service/get_all_content.py b/examples/dfp/v201611/content_service/get_all_content.py new file mode 100755 index 00000000..8e4ab458 --- /dev/null +++ b/examples/dfp/v201611/content_service/get_all_content.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 content. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + content_service = client.GetService('ContentService', version='v201611') + + # Create a statement to select content. + statement = dfp.FilterStatement() + + # Retrieve a small amount of content at a time, paging + # through until all content have been retrieved. + while True: + response = content_service.getContentByStatement(statement.ToStatement()) + if 'results' in response: + for content in response['results']: + # Print out some information for each content. + print('Content with ID "%d" and name "%s" was found.\n' % + (content['id'], content['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/creative_service/__init__.py b/examples/dfp/v201611/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201602/creative_service/__init__.py rename to examples/dfp/v201611/creative_service/__init__.py diff --git a/examples/dfp/v201602/creative_service/create_creative_from_template.py b/examples/dfp/v201611/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201602/creative_service/create_creative_from_template.py rename to examples/dfp/v201611/creative_service/create_creative_from_template.py index 8d53214c..a612e533 100755 --- a/examples/dfp/v201602/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201611/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201602') + creative_service = client.GetService('CreativeService', version='v201611') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201602/creative_service/create_creatives.py b/examples/dfp/v201611/creative_service/create_creatives.py similarity index 98% rename from examples/dfp/v201602/creative_service/create_creatives.py rename to examples/dfp/v201611/creative_service/create_creatives.py index fcef2d5a..4ee153b9 100755 --- a/examples/dfp/v201602/creative_service/create_creatives.py +++ b/examples/dfp/v201611/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201602') + creative_service = client.GetService('CreativeService', version='v201611') # Create creative objects. creatives = [] @@ -48,7 +48,7 @@ def main(client, advertiser_id): 'medium_rectangle.jpg'), 'r') as image: image_data = base64.encodestring(image.read()) - for i in xrange(5): + for _ in xrange(5): # Create creative size. size = { 'width': '300', diff --git a/examples/dfp/v201602/creative_service/create_custom_creative.py b/examples/dfp/v201611/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201602/creative_service/create_custom_creative.py rename to examples/dfp/v201611/creative_service/create_custom_creative.py index 1c642806..2a1fe137 100755 --- a/examples/dfp/v201602/creative_service/create_custom_creative.py +++ b/examples/dfp/v201611/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201602') + creative_service = client.GetService('CreativeService', version='v201611') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201602/creative_service/create_native_creative.py b/examples/dfp/v201611/creative_service/create_native_creative.py similarity index 99% rename from examples/dfp/v201602/creative_service/create_native_creative.py rename to examples/dfp/v201611/creative_service/create_native_creative.py index 6765e3d6..0e3a86cc 100755 --- a/examples/dfp/v201602/creative_service/create_native_creative.py +++ b/examples/dfp/v201611/creative_service/create_native_creative.py @@ -46,7 +46,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201602') + creative_service = client.GetService('CreativeService', version='v201611') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/dfp/v201611/creative_service/get_all_creatives.py b/examples/dfp/v201611/creative_service/get_all_creatives.py new file mode 100755 index 00000000..265d9a7b --- /dev/null +++ b/examples/dfp/v201611/creative_service/get_all_creatives.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creatives. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201611') + + # Create a statement to select creatives. + statement = dfp.FilterStatement() + + # Retrieve a small amount of creatives at a time, paging + # through until all creatives have been retrieved. + while True: + response = creative_service.getCreativesByStatement(statement.ToStatement()) + if 'results' in response: + for creative in response['results']: + # Print out some information for each creative. + print('Creative with ID "%d" and name "%s" was found.\n' % + (creative['id'], creative['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/creative_service/get_all_creatives.py b/examples/dfp/v201611/creative_service/get_image_creatives.py similarity index 57% rename from examples/dfp/v201602/creative_service/get_all_creatives.py rename to examples/dfp/v201611/creative_service/get_image_creatives.py index b0cb054d..6e85199d 100755 --- a/examples/dfp/v201602/creative_service/get_all_creatives.py +++ b/examples/dfp/v201611/creative_service/get_image_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,46 +13,43 @@ # 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 code example gets all creatives. - -To create creatives, run create_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all image creatives. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201602') - - # Create statement object to select all creatives. - statement = dfp.FilterStatement() - - # Get creatives by statement. + creative_service = client.GetService('CreativeService', version='v201611') + query = 'WHERE creativeType = :creativeType' + values = [ + {'key': 'creativeType', + 'value': { + 'xsi_type': 'TextValue', + 'value': '_image_creative' + }}, + ] + # Create a statement to select creatives. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of creatives at a time, paging + # through until all creatives have been retrieved. while True: - response = creative_service.getCreativesByStatement( - statement.ToStatement()) + response = creative_service.getCreativesByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for creative in response['results']: - print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (creative['id'], creative['name'], - dfp.DfpClassType(creative))) + # Print out some information for each creative. + print('Creative with ID "%d" and name "%s" was found.\n' % + (creative['id'], creative['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/creative_service/update_creatives.py b/examples/dfp/v201611/creative_service/update_creatives.py similarity index 99% rename from examples/dfp/v201602/creative_service/update_creatives.py rename to examples/dfp/v201611/creative_service/update_creatives.py index 7ef3da5a..582247af 100755 --- a/examples/dfp/v201602/creative_service/update_creatives.py +++ b/examples/dfp/v201611/creative_service/update_creatives.py @@ -34,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201602') + creative_service = client.GetService('CreativeService', version='v201611') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201602/creative_set_service/__init__.py b/examples/dfp/v201611/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201602/creative_set_service/__init__.py rename to examples/dfp/v201611/creative_set_service/__init__.py diff --git a/examples/dfp/v201602/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py similarity index 92% rename from examples/dfp/v201602/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py index e09dab08..cc4e5038 100755 --- a/examples/dfp/v201602/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates a line item creative association for a creative -set. +"""Creates a line item creative association for a creative set. To create creative sets, run create_creative_set.py. To create creatives, run create_creatives.py. To determine which LICAs exist, run get_all_licas.py. @@ -38,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201602') + 'LineItemCreativeAssociationService', version='v201611') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201602/creative_set_service/create_creative_set.py b/examples/dfp/v201611/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201602/creative_set_service/create_creative_set.py rename to examples/dfp/v201611/creative_set_service/create_creative_set.py index 34df634f..a245b268 100755 --- a/examples/dfp/v201602/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201611/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201602') + version='v201611') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201602/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py similarity index 61% rename from examples/dfp/v201602/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201611/creative_set_service/get_all_creative_sets.py index 7cbb375e..967241a8 100755 --- a/examples/dfp/v201602/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,46 +13,38 @@ # 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 code example gets all creative sets. - -To create creative sets, run create_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all creative sets. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201602') + creative_set_service = client.GetService( + 'CreativeSetService', version='v201611') - # Create a filter statement. + # Create a statement to select creative sets. statement = dfp.FilterStatement() - # Get creative sets by statement. + # Retrieve a small amount of creative sets at a time, paging + # through until all creative sets have been retrieved. while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for creative_set in response['results']: - print ('Creative set with ID \'%s\' and name \'%s\' was found.' - % (creative_set['id'], creative_set['name'])) + # Print out some information for each creative set. + print('Creative set with ID "%d" and name "%s" was found.\n' % + (creative_set['id'], creative_set['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py similarity index 54% rename from examples/dfp/v201602/creative_set_service/get_creative_sets_by_statement.py rename to examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py index 191d8039..cd17ab52 100755 --- a/examples/dfp/v201602/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 code example gets all creative sets for a master creative. - -To create creative sets, run create_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all creative sets for a master creative. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -34,38 +24,36 @@ def main(client, master_creative_id): # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201602') - - # Create statement object to only select creative sets that have the given - # master creative. - values = [{ - 'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': master_creative_id - } - }] + creative_set_service = client.GetService( + 'CreativeSetService', version='v201611') query = 'WHERE masterCreativeId = :masterCreativeId' + values = [ + {'key': 'masterCreativeId', + 'value': { + 'xsi_type': 'TextValue', + 'value': master_creative_id + }}, + ] + # Create a statement to select creative sets. statement = dfp.FilterStatement(query, values) - # Get creative sets by statement. + # Retrieve a small amount of creative sets at a time, paging + # through until all creative sets have been retrieved. while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for creative_set in response['results']: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' - 'companion creative IDs {%s} was found.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) + # Print out some information for each creative set. + print('Creative set with ID "%d" and name "%s" was found.\n' % + (creative_set['id'], creative_set['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/creative_set_service/update_creative_set.py b/examples/dfp/v201611/creative_set_service/update_creative_set.py similarity index 97% rename from examples/dfp/v201602/creative_set_service/update_creative_set.py rename to examples/dfp/v201611/creative_set_service/update_creative_set.py index 3997e534..cc23b187 100755 --- a/examples/dfp/v201602/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201611/creative_set_service/update_creative_set.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201602') + version='v201611') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201602/creative_template_service/__init__.py b/examples/dfp/v201611/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201602/creative_template_service/__init__.py rename to examples/dfp/v201611/creative_template_service/__init__.py diff --git a/examples/dfp/v201602/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py similarity index 61% rename from examples/dfp/v201602/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201611/creative_template_service/get_all_creative_templates.py index 30d4046b..b13ab25d 100755 --- a/examples/dfp/v201602/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,17 +13,9 @@ # 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 code example gets all creative templates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all creative templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -31,28 +23,28 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201602') + 'CreativeTemplateService', version='v201611') - # Create a filter statement. + # Create a statement to select creative templates. statement = dfp.FilterStatement() - # Get creative templates by statement. + # Retrieve a small amount of creative templates at a time, paging + # through until all creative templates have been retrieved. while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for template in response['results']: - print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' ' - 'was found.' % (template['id'], - template['name'], - template['type'])) + for creative_template in response['results']: + # Print out some information for each creative template. + print('Creative template with ID "%d" and name "%s" was found.\n' % + (creative_template['id'], creative_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py similarity index 56% rename from examples/dfp/v201602/custom_targeting_service/get_custom_targeting_keys_by_statement.py rename to examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py index 28ff1cc7..dec095f0 100755 --- a/examples/dfp/v201602/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,48 +13,45 @@ # 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 predefined custom targeting keys. - -To create custom targeting keys, run create_custom_targeting_keys_and_values.py. +"""This example gets all system defined creative templates. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') - - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] + creative_template_service = client.GetService( + 'CreativeTemplateService', version='v201611') query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'SYSTEM_DEFINED' + }}, + ] + # Create a statement to select creative templates. statement = dfp.FilterStatement(query, values) - # Get custom targeting keys by statement. + # Retrieve a small amount of creative templates at a time, paging + # through until all creative templates have been retrieved. while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( + response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for key in response['results']: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was found.' - % (key['id'], key['name'], key['displayName'], key['type'])) + for creative_template in response['results']: + # Print out some information for each creative template. + print('Creative template with ID "%d" and name "%s" was found.\n' % + (creative_template['id'], creative_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/dfp/v201602/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py index 1161dd79..e648addf 100755 --- a/examples/dfp/v201602/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201602') + version='v201611') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201602/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 97% rename from examples/dfp/v201602/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py index f0c53925..df05fd69 100755 --- a/examples/dfp/v201602/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201602') + version='v201611') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201602/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py similarity index 58% rename from examples/dfp/v201602/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py index e7126c80..5f0c04c5 100755 --- a/examples/dfp/v201602/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,46 +13,45 @@ # 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 code example gets all creative wrappers. - -To create creative wrappers, run create_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all active creative wrappers. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201602') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get creative wrappers by statement. + creative_wrapper_service = client.GetService( + 'CreativeWrapperService', version='v201611') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select creative wrappers. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of creative wrappers at a time, paging + # through until all creative wrappers have been retrieved. while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'found.' % (creative_wrapper['id'], creative_wrapper['labelId'])) + # Print out some information for each creative wrapper. + print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % + (creative_wrapper['id'], creative_wrapper['labelId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py new file mode 100755 index 00000000..ce3f2887 --- /dev/null +++ b/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creative wrappers. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + creative_wrapper_service = client.GetService( + 'CreativeWrapperService', version='v201611') + + # Create a statement to select creative wrappers. + statement = dfp.FilterStatement() + + # Retrieve a small amount of creative wrappers at a time, paging + # through until all creative wrappers have been retrieved. + while True: + response = creative_wrapper_service.getCreativeWrappersByStatement( + statement.ToStatement()) + if 'results' in response: + for creative_wrapper in response['results']: + # Print out some information for each creative wrapper. + print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % + (creative_wrapper['id'], creative_wrapper['labelId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py similarity index 97% rename from examples/dfp/v201602/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py index c13b6b5b..e5cc273b 100755 --- a/examples/dfp/v201602/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201602') + version='v201611') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201602/custom_field_service/__init__.py b/examples/dfp/v201611/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201602/custom_field_service/__init__.py rename to examples/dfp/v201611/custom_field_service/__init__.py diff --git a/examples/dfp/v201602/custom_field_service/create_custom_field_options.py b/examples/dfp/v201611/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201602/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201611/custom_field_service/create_custom_field_options.py index 2d8f7ec6..d23e1ad0 100755 --- a/examples/dfp/v201602/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201611/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201602') + 'CustomFieldService', version='v201611') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201602/custom_field_service/create_custom_fields.py b/examples/dfp/v201611/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201602/custom_field_service/create_custom_fields.py rename to examples/dfp/v201611/custom_field_service/create_custom_fields.py index 2f1bfa6b..7f092cd6 100755 --- a/examples/dfp/v201602/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201602') + 'CustomFieldService', version='v201611') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201602/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 98% rename from examples/dfp/v201602/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py index d18d0828..7122d3bf 100755 --- a/examples/dfp/v201602/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201602') + 'CustomFieldService', version='v201611') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201602/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py similarity index 67% rename from examples/dfp/v201602/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201611/custom_field_service/get_all_custom_fields.py index 6b8085e0..f2b116f4 100755 --- a/examples/dfp/v201602/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 fields. - -To create custom fields, run create_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,26 +23,28 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201602') + 'CustomFieldService', version='v201611') - # Create a filter statement. + # Create a statement to select custom fields. statement = dfp.FilterStatement() - # Get custom fields by statement. + # Retrieve a small amount of custom fields at a time, paging + # through until all custom fields have been retrieved. while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' was found.' - % (custom_field['id'], custom_field['name'])) + # Print out some information for each custom field. + print('Custom field with ID "%d" and name "%s" was found.\n' % + (custom_field['id'], custom_field['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py similarity index 59% rename from examples/dfp/v201602/custom_field_service/get_all_line_item_custom_fields.py rename to examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py index 436aaf0e..c1f374bb 100755 --- a/examples/dfp/v201602/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 fields that apply to line items. - -To create custom fields, run create_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all custom fields that can be applied to line items. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,36 +23,35 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201602') - - # Create statement to select only custom fields that apply to line items. - values = [{ - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }] + 'CustomFieldService', version='v201611') query = 'WHERE entityType = :entityType' - - # Create a filter statement. + values = [ + {'key': 'entityType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'LINE_ITEM' + }}, + ] + # Create a statement to select custom fields. statement = dfp.FilterStatement(query, values) - # Get custom fields by statement. + # Retrieve a small amount of custom fields at a time, paging + # through until all custom fields have been retrieved. while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' was found.' - % (custom_field['id'], custom_field['name'])) + # Print out some information for each custom field. + print('Custom field with ID "%d" and name "%s" was found.\n' % + (custom_field['id'], custom_field['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201602/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py index 4f224371..34551829 100755 --- a/examples/dfp/v201602/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201602') + 'CustomFieldService', version='v201611') - line_item_service = client.GetService('LineItemService', version='v201602') + line_item_service = client.GetService('LineItemService', version='v201611') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201602/custom_field_service/update_custom_fields.py b/examples/dfp/v201611/custom_field_service/update_custom_fields.py similarity index 98% rename from examples/dfp/v201602/custom_field_service/update_custom_fields.py rename to examples/dfp/v201611/custom_field_service/update_custom_fields.py index f2b52384..5e38cb3e 100755 --- a/examples/dfp/v201602/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/update_custom_fields.py @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201602') + 'CustomFieldService', version='v201611') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201602/custom_targeting_service/__init__.py b/examples/dfp/v201611/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201602/custom_targeting_service/__init__.py rename to examples/dfp/v201611/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201602/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 96% rename from examples/dfp/v201602/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py index 20e024dd..1c5ffc2b 100755 --- a/examples/dfp/v201602/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') + 'CustomTargetingService', version='v201611') # Create custom targeting key objects. keys = [ @@ -72,7 +72,7 @@ def main(client): # Create custom targeting value objects. values = [ { - 'customTargetingKeyId': keys['id'], + 'customTargetingKeyId': keys[0]['id'], 'displayName': 'male', # Name is set to 1 so that the actual name can be hidden from website # users. @@ -80,7 +80,7 @@ def main(client): 'matchType': 'EXACT' }, { - 'customTargetingKeyId': keys['id'], + 'customTargetingKeyId': keys[0]['id'], 'displayName': 'female', # Name is set to 2 so that the actual name can be hidden from website # users. diff --git a/examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py index 356658af..9e902a0e 100755 --- a/examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') + 'CustomTargetingService', version='v201611') values = [{ 'key': 'name', @@ -55,7 +55,7 @@ def main(client, key_name): response = custom_targeting_service.getCustomTargetingKeysByStatement( statement.ToStatement()) if 'results' in response: - key_ids = [key['id'] for key in response['results']] + key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) key_statement = dfp.FilterStatement(key_query) diff --git a/examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py index 8dc1099c..4c7969bd 100755 --- a/examples/dfp/v201602/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example deletes custom targeting values for a given custom targeting -key. +"""Deletes custom targeting values for a given custom targeting key. To determine which custom targeting keys and values exist, run get_all_custom_targeting_keys_and_values.py. @@ -37,7 +36,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') + 'CustomTargetingService', version='v201611') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..33f31780 --- /dev/null +++ b/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2016 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 targeting keys and values. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201611') + + # Create statement to get all targeting keys. + targeting_key_statement = dfp.FilterStatement() + + all_keys = [] + + # Get custom targeting keys by statement. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + targeting_key_statement.ToStatement()) + if 'results' in response: + all_keys.extend(response['results']) + targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + if all_keys: + # Create a statement to select custom targeting values. + query = ('WHERE customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys])) + statement = dfp.FilterStatement(query) + + # Retreive a small amount of custom targeting values at a time, paging + # through until all custom targeting values have been retrieved. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response: + for custom_targeting_value in response['results']: + # Print out some information for each custom targeting value. + print('Custom targeting value with ID "%d", name "%s", display name ' + '"%s", and custom targeting key ID "%d" was found.\n' % + (custom_targeting_value['id'], custom_targeting_value['name'], + custom_targeting_value['displayName'], + custom_targeting_value['customTargetingKeyId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..67680326 --- /dev/null +++ b/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2016 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 targeting keys and values. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201611') + + # Create statement to get targeting keys for predefined values. + query = ('WHERE type = :type') + values = [{ + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PREDEFINED' + } + }] + targeting_key_statement = dfp.FilterStatement(query, values) + + all_keys = [] + + # Get custom targeting keys by statement. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + targeting_key_statement.ToStatement()) + if 'results' in response: + all_keys.extend(response['results']) + targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + if all_keys: + # Create a statement to select custom targeting values. + query = ('WHERE customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys])) + statement = dfp.FilterStatement(query) + + # Retreive a small amount of custom targeting values at a time, paging + # through until all custom targeting values have been retrieved. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response: + for custom_targeting_value in response['results']: + # Print out some information for each custom targeting value. + print('Custom targeting value with ID "%d", name "%s", display name ' + '"%s", and custom targeting key ID "%d" was found.\n' % + (custom_targeting_value['id'], custom_targeting_value['name'], + custom_targeting_value['displayName'], + custom_targeting_value['customTargetingKeyId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/dfp/v201602/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py index 24fff377..0d2b665e 100755 --- a/examples/dfp/v201602/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py @@ -17,7 +17,8 @@ """This example updates the display name of a single custom targeting key. To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') + 'CustomTargetingService', version='v201611') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201602/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py similarity index 91% rename from examples/dfp/v201602/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py index 88b1da87..dc16b89a 100755 --- a/examples/dfp/v201602/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates the display name of the custom targeting values -belonging to a custom targeting key. +"""Updates name of custom targeting values belonging to a custom targeting key. To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" # Import appropriate modules from the client library. @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201602') + 'CustomTargetingService', version='v201611') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201602/exchange_rate_service/__init__.py b/examples/dfp/v201611/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201602/exchange_rate_service/__init__.py rename to examples/dfp/v201611/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201602/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201602/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py index 1edc93a2..bed9b04c 100755 --- a/examples/dfp/v201602/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201602') + version='v201611') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201602/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py similarity index 57% rename from examples/dfp/v201602/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py index f3f50bec..0782d282 100755 --- a/examples/dfp/v201602/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,40 +13,34 @@ # 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 code example gets all exchange rates. - -To create exchange rates, run create_exchange_rates.py. - +"""This example gets all exchange rates. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201602') + exchange_rate_service = client.GetService( + 'ExchangeRateService', version='v201611') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select exchange rates. + statement = dfp.FilterStatement() - # Get all exchange rates by statement. + # Retrieve a small amount of exchange rates at a time, paging + # through until all exchange rates have been retrieved. while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for exchange_rate in response['results']: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was found.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + # Print out some information for each exchange rate. + print( + 'Exchange rate with ID "%d", currency code "%s", direction "%s", ' + 'and exchange rate "%d" was found.\n' % + (exchange_rate['id'], exchange_rate['currencyCode'], + exchange_rate['direction'], exchange_rate['exchangeRate'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 59% rename from examples/dfp/v201602/exchange_rate_service/get_exchange_rates_by_currency_code.py rename to examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py index 475c3a9c..ad5b8c5b 100755 --- a/examples/dfp/v201602/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 the exchange rate for a specific currency code. - -To create exchange rates, run create_exchange_rates.py. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -29,35 +24,31 @@ def main(client, currency_code): # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201602') - - # Create a statement to get exchange rates for the specified currency code. - values = [{ - 'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - } - }] + exchange_rate_service = client.GetService( + 'ExchangeRateService', version='v201611') query = 'WHERE currencyCode = :currencyCode' - # Create a filter statement. + values = [ + {'key': 'currencyCode', + 'value': { + 'xsi_type': 'TextValue', + 'value': currency_code + }}, + ] + # Create a statement to select exchange rates. statement = dfp.FilterStatement(query, values) - # Get rate cards by statement. + # Retrieve a small amount of exchange rates at a time, paging + # through until all exchange rates have been retrieved. while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for exchange_rate in response['results']: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was found.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + # Print out some information for each exchange rate. + print('Exchange rate with ID "%d", currency code "%s", and exchange ' + 'rate "%.2f" was found.\n' % + (exchange_rate['id'], exchange_rate['currencyCode'], + float(exchange_rate['exchangeRate'] / 1000000))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py similarity index 97% rename from examples/dfp/v201602/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py index 84d7d335..40a14446 100755 --- a/examples/dfp/v201602/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201602') + version='v201611') # Create a statement to get an exchange rate by its ID. values = [{ diff --git a/examples/dfp/v201602/forecast_service/get_availability_forecast.py b/examples/dfp/v201611/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/dfp/v201602/forecast_service/get_availability_forecast.py rename to examples/dfp/v201611/forecast_service/get_availability_forecast.py index 2f267c8d..f2175a8d 100755 --- a/examples/dfp/v201602/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201611/forecast_service/get_availability_forecast.py @@ -36,8 +36,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201602') - network_service = client.GetService('NetworkService', version='v201602') + forecast_service = client.GetService('ForecastService', version='v201611') + network_service = client.GetService('NetworkService', version='v201611') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201602/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/dfp/v201602/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py index d167ee2c..f7bd982f 100755 --- a/examples/dfp/v201602/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201602') + forecast_service = client.GetService('ForecastService', version='v201611') # Set forecasting options. forecast_options = { diff --git a/examples/dfp/v201602/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/dfp/v201602/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py index 955c6e74..9ad38bcc 100755 --- a/examples/dfp/v201602/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201602') + forecast_service = client.GetService('ForecastService', version='v201611') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201602/inventory_service/__init__.py b/examples/dfp/v201611/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201602/inventory_service/__init__.py rename to examples/dfp/v201611/inventory_service/__init__.py diff --git a/examples/dfp/v201602/inventory_service/archive_ad_units.py b/examples/dfp/v201611/inventory_service/archive_ad_units.py similarity index 99% rename from examples/dfp/v201602/inventory_service/archive_ad_units.py rename to examples/dfp/v201611/inventory_service/archive_ad_units.py index c40b3052..530e0b23 100755 --- a/examples/dfp/v201602/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201611/inventory_service/archive_ad_units.py @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201602') + inventory_service = client.GetService('InventoryService', version='v201611') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201602/inventory_service/create_ad_units.py b/examples/dfp/v201611/inventory_service/create_ad_units.py similarity index 99% rename from examples/dfp/v201602/inventory_service/create_ad_units.py rename to examples/dfp/v201611/inventory_service/create_ad_units.py index ca2fc59b..0c8ab6a3 100755 --- a/examples/dfp/v201602/inventory_service/create_ad_units.py +++ b/examples/dfp/v201611/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201602') + inventory_service = client.GetService('InventoryService', version='v201611') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201602/network_service/get_current_network.py b/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py similarity index 52% rename from examples/dfp/v201602/network_service/get_current_network.py rename to examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py index 6b589bc3..e0600a46 100755 --- a/examples/dfp/v201602/network_service/get_current_network.py +++ b/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,9 +13,8 @@ # 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 the current network that you can make requests against.""" - +"""This example gets all ad unit sizes. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -23,14 +22,23 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201602') - - # Get the current network. - network = network_service.getCurrentNetwork() + ad_unit_size_service = client.GetService( + 'InventoryService', version='v201611') + + # Create a statement to select ad unit sizes. + statement = dfp.FilterStatement() + + # Retreive a small amount of ad unit sizes at a time, paging + # through until all ad unit sizes have been retrieved. + response = ad_unit_size_service.getAdUnitSizesByStatement( + statement.ToStatement()) + if response: + for ad_unit_size in response: + # Print out some information for each ad unit size. + if 'fullDisplayString' in ad_unit_size: + print('Ad unit size with dimensions "%s" was found.\n' % + (ad_unit_size['fullDisplayString'])) - # Display results. - print ('Current network has network code \'%s\' and display name \'%s\'.' - % (network['networkCode'], network['displayName'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_units.py b/examples/dfp/v201611/inventory_service/get_all_ad_units.py new file mode 100755 index 00000000..ddcc06e2 --- /dev/null +++ b/examples/dfp/v201611/inventory_service/get_all_ad_units.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + ad_unit_service = client.GetService('InventoryService', version='v201611') + + # Create a statement to select ad units. + statement = dfp.FilterStatement() + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response: + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/inventory_service/update_ad_units.py b/examples/dfp/v201611/inventory_service/update_ad_units.py similarity index 99% rename from examples/dfp/v201602/inventory_service/update_ad_units.py rename to examples/dfp/v201611/inventory_service/update_ad_units.py index 3d174a61..28ed83e6 100755 --- a/examples/dfp/v201602/inventory_service/update_ad_units.py +++ b/examples/dfp/v201611/inventory_service/update_ad_units.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201602') + inventory_service = client.GetService('InventoryService', version='v201611') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201602/label_service/__init__.py b/examples/dfp/v201611/label_service/__init__.py similarity index 100% rename from examples/dfp/v201602/label_service/__init__.py rename to examples/dfp/v201611/label_service/__init__.py diff --git a/examples/dfp/v201602/label_service/create_labels.py b/examples/dfp/v201611/label_service/create_labels.py similarity index 96% rename from examples/dfp/v201602/label_service/create_labels.py rename to examples/dfp/v201611/label_service/create_labels.py index 409d8f7d..5e9cfe19 100755 --- a/examples/dfp/v201602/label_service/create_labels.py +++ b/examples/dfp/v201611/label_service/create_labels.py @@ -17,7 +17,8 @@ """This code example creates new labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" import uuid @@ -28,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201602') + label_service = client.GetService('LabelService', version='v201611') # Create label objects. labels = [] diff --git a/examples/dfp/v201602/label_service/deactivate_labels.py b/examples/dfp/v201611/label_service/deactivate_labels.py similarity index 97% rename from examples/dfp/v201602/label_service/deactivate_labels.py rename to examples/dfp/v201611/label_service/deactivate_labels.py index a31a2c8a..c65fadef 100755 --- a/examples/dfp/v201602/label_service/deactivate_labels.py +++ b/examples/dfp/v201611/label_service/deactivate_labels.py @@ -17,7 +17,8 @@ """This code example deactivates all active Labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" # Import appropriate modules from the client library. @@ -26,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201602') + label_service = client.GetService('LabelService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/label_service/get_labels_by_statement.py b/examples/dfp/v201611/label_service/get_active_labels.py similarity index 63% rename from examples/dfp/v201602/label_service/get_labels_by_statement.py rename to examples/dfp/v201611/label_service/get_active_labels.py index e9ab41c9..2fecfce8 100755 --- a/examples/dfp/v201602/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201611/label_service/get_active_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,36 @@ # 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 code example gets all labels ordered by name. - -To create a label, run create_label.py. This feature is only available to DFP -premium solution networks. +"""This example gets all active labels. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201602') - - # Create statement to get all labels - statement = dfp.FilterStatement('ORDER BY name') - - # Get labels by statement. + label_service = client.GetService('LabelService', version='v201611') + query = 'WHERE isActive = :isActive' + values = [ + {'key': 'isActive', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select labels. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of labels at a time, paging + # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' was found.' - % (label['id'], label['name'])) + # Print out some information for each label. + print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], + label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/label_service/get_all_labels.py b/examples/dfp/v201611/label_service/get_all_labels.py similarity index 73% rename from examples/dfp/v201602/label_service/get_all_labels.py rename to examples/dfp/v201611/label_service/get_all_labels.py index 0d85b0e7..b06bd23c 100755 --- a/examples/dfp/v201602/label_service/get_all_labels.py +++ b/examples/dfp/v201611/label_service/get_all_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 code example gets all labels. - -To create labels, run create_labels.py. This feature is only available to DFP -premium solution networks.""" - +"""This example gets all labels. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,19 +22,20 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201602') + label_service = client.GetService('LabelService', version='v201611') - # Create statement to get all labels + # Create a statement to select labels. statement = dfp.FilterStatement() - # Get labels by statement. + # Retrieve a small amount of labels at a time, paging + # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' was found.' - % (label['id'], label['name'])) + # Print out some information for each label. + print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], + label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/label_service/update_labels.py b/examples/dfp/v201611/label_service/update_labels.py similarity index 97% rename from examples/dfp/v201602/label_service/update_labels.py rename to examples/dfp/v201611/label_service/update_labels.py index 94ac6aa6..71ea8045 100755 --- a/examples/dfp/v201602/label_service/update_labels.py +++ b/examples/dfp/v201611/label_service/update_labels.py @@ -17,7 +17,8 @@ """This code example updates the description of a single label. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" # Import appropriate modules from the client library. @@ -28,7 +29,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201602') + label_service = client.GetService('LabelService', version='v201611') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201602/line_item_creative_association_service/__init__.py b/examples/dfp/v201611/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201602/line_item_creative_association_service/__init__.py rename to examples/dfp/v201611/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201602/line_item_creative_association_service/create_licas.py b/examples/dfp/v201611/line_item_creative_association_service/create_licas.py similarity index 93% rename from examples/dfp/v201602/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201611/line_item_creative_association_service/create_licas.py index c77ad32e..fee354cd 100755 --- a/examples/dfp/v201602/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/create_licas.py @@ -17,7 +17,8 @@ """This code example creates new line item creative associations (LICAs) for an existing line item and a set of creative ids. -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -31,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201602') + 'LineItemCreativeAssociationService', version='v201611') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201602/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/dfp/v201602/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py index bc7aacfc..81efb3b4 100755 --- a/examples/dfp/v201602/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py @@ -16,7 +16,8 @@ """This code example deactivates all LICAs for the line item. -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201602') + 'LineItemCreativeAssociationService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py similarity index 56% rename from examples/dfp/v201602/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py index a00879f2..233a83c6 100755 --- a/examples/dfp/v201602/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all line item creative associations (LICA). - -To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py. +"""This example gets all line item creative associations. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,29 +23,34 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201602') + 'LineItemCreativeAssociationService', version='v201611') - # Create a filter statement. + # Create a statement to select line item creative associations. statement = dfp.FilterStatement() - # Get line items by statement. + # Retrieve a small amount of line item creative associations at a time, paging + # through until all line item creative associations have been retrieved. while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for lica in response['results']: + # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print ('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % - (lica['lineItemId'], lica['creativeSetId'], lica['status'])) + print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' + 'status \'%s\' was found.' % + (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: - print ('LICA with line item ID \'%s\', creative ID \'%s\', and status' - ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print('Line item creative association with line item ID "%d" and ' + 'creative ID "%d" was found.\n' % + (lica['lineItemId'], lica['creativeId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py similarity index 52% rename from examples/dfp/v201602/line_item_creative_association_service/get_licas_by_statement.py rename to examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py index 5ed9a3a3..ab1304d2 100755 --- a/examples/dfp/v201602/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,52 +13,52 @@ # 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 code example gets all line item creative associations (LICA) for a given -line item id. - -To create LICAs, run create_licas.py.""" - +"""This example gets all line item creative associations for a given line item. +""" # Import appropriate modules from the client library. from googleads import dfp -# Set the id of the line item to get LICAs by. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201602') - -# Create statement object to only select LICAs for the given line item id. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] + 'LineItemCreativeAssociationService', version='v201611') query = 'WHERE lineItemId = :lineItemId' + values = [ + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'TextValue', + 'value': line_item_id + }}, + ] + # Create a statement to select line item creative associations. statement = dfp.FilterStatement(query, values) + # Retrieve a small amount of line item creative associations at a time, paging + # through until all line item creative associations have been retrieved. while True: - # Get LICAs by statement. response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: - # Display results. for lica in response['results']: - print ('LICA with line item id \'%s\', creative id \'%s\', and status ' - '\'%s\' was found.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + # Print out some information for each line item creative association. + if 'creativeSetId' in lica: + print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' + 'status \'%s\' was found.' % + (lica['lineItemId'], lica['creativeSetId'], lica['status'])) + else: + print('Line item creative association with line item ID "%d" and ' + 'creative ID "%d" was found.\n' % + (lica['lineItemId'], lica['creativeId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201602/line_item_creative_association_service/update_licas.py b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/dfp/v201602/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201611/line_item_creative_association_service/update_licas.py index 36996d82..0593e472 100755 --- a/examples/dfp/v201602/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py @@ -17,7 +17,8 @@ """This code example updates the destination URL of all line item creative associations (LICA). -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201602') + 'LineItemCreativeAssociationService', version='v201611') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201602/line_item_service/__init__.py b/examples/dfp/v201611/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201602/line_item_service/__init__.py rename to examples/dfp/v201611/line_item_service/__init__.py diff --git a/examples/dfp/v201602/line_item_service/activate_line_items.py b/examples/dfp/v201611/line_item_service/activate_line_items.py similarity index 98% rename from examples/dfp/v201602/line_item_service/activate_line_items.py rename to examples/dfp/v201611/line_item_service/activate_line_items.py index a5701efe..af758328 100755 --- a/examples/dfp/v201602/line_item_service/activate_line_items.py +++ b/examples/dfp/v201611/line_item_service/activate_line_items.py @@ -20,7 +20,8 @@ one creative associated with them. To approve line items, approve the order to which they belong by running approve_orders.py. To create LICAs, run create_licas.py. To determine which line items exist, run -get_all_line_items.py.""" +get_all_line_items.py. +""" # Import appropriate modules from the client library. @@ -32,7 +33,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') + line_item_service = client.GetService('LineItemService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/line_item_service/create_line_items.py b/examples/dfp/v201611/line_item_service/create_line_items.py similarity index 98% rename from examples/dfp/v201602/line_item_service/create_line_items.py rename to examples/dfp/v201611/line_item_service/create_line_items.py index 7737842a..b8ab25c9 100755 --- a/examples/dfp/v201602/line_item_service/create_line_items.py +++ b/examples/dfp/v201611/line_item_service/create_line_items.py @@ -18,7 +18,8 @@ To determine which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To determine which placements exist, -run get_all_placements.py.""" +run get_all_placements.py. +""" from datetime import date @@ -35,11 +36,11 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') + line_item_service = client.GetService('LineItemService', version='v201611') # Create line item objects. line_items = [] - for i in xrange(5): + for _ in xrange(5): line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, diff --git a/examples/dfp/v201602/line_item_service/create_video_line_item.py b/examples/dfp/v201611/line_item_service/create_video_line_item.py similarity index 96% rename from examples/dfp/v201602/line_item_service/create_video_line_item.py rename to examples/dfp/v201611/line_item_service/create_video_line_item.py index a58c808e..622747a0 100755 --- a/examples/dfp/v201602/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201611/line_item_service/create_video_line_item.py @@ -20,7 +20,8 @@ which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To create a video ad unit, run create_video_ad_unit.py. To create criteria for categories, run -create_custom_targeting_keys_and_values.py""" +create_custom_targeting_keys_and_values.py. +""" from datetime import date @@ -38,14 +39,14 @@ # on the content to target. This would typically be from a key representing # a "genre" and the value representing something like "comedy". The value # must be from a key in a content metadata key hierarchy. -CONTENT_CUSTOM_TARGETING_VALUE_ID = \ - 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE' +CONTENT_CUSTOM_TARGETING_VALUE_ID = ( + 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE') def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') + line_item_service = client.GetService('LineItemService', version='v201611') # Create line item object. line_item = { diff --git a/examples/dfp/v201602/line_item_service/get_all_line_items.py b/examples/dfp/v201611/line_item_service/get_all_line_items.py similarity index 68% rename from examples/dfp/v201602/line_item_service/get_all_line_items.py rename to examples/dfp/v201611/line_item_service/get_all_line_items.py index af079042..3ba749b4 100755 --- a/examples/dfp/v201602/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201611/line_item_service/get_all_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,11 +13,8 @@ # 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 code example gets all line items. - -To create line items, run create_line_items.py.""" - +"""This example gets all line items. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -25,27 +22,28 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') + line_item_service = client.GetService('LineItemService', version='v201611') - # Create a filter statement. + # Create a statement to select line items. statement = dfp.FilterStatement() - # Get line items by statement. + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % - (line_item['id'], line_item['orderId'], line_item['name'])) + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py new file mode 100755 index 00000000..c53fa9e6 --- /dev/null +++ b/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 line items that are missing creatives. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201611') + query = 'WHERE isMissingCreatives = :isMissingCreatives' + values = [ + {'key': 'isMissingCreatives', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select line items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response: + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py new file mode 100755 index 00000000..233611c8 --- /dev/null +++ b/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 only recently updated line items. +""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201611') + query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' + values = [ + {'key': 'lastModifiedDateTime', + 'value': { + 'xsi_type': 'TextValue', + 'value': (datetime.now() - timedelta(days=1)) + .strftime('%Y-%m-%dT%H:%M:%S') + }}, + ] + # Create a statement to select line items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response: + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/line_item_service/target_custom_criteria.py b/examples/dfp/v201611/line_item_service/target_custom_criteria.py similarity index 98% rename from examples/dfp/v201602/line_item_service/target_custom_criteria.py rename to examples/dfp/v201611/line_item_service/target_custom_criteria.py index 12ada4c1..fe5f71e6 100755 --- a/examples/dfp/v201602/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201611/line_item_service/target_custom_criteria.py @@ -18,7 +18,8 @@ To determine which line items exist, run get_all_line_items.py. To determine which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" import pprint @@ -39,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') + line_item_service = client.GetService('LineItemService', version='v201611') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201602/line_item_service/update_line_items.py b/examples/dfp/v201611/line_item_service/update_line_items.py similarity index 96% rename from examples/dfp/v201602/line_item_service/update_line_items.py rename to examples/dfp/v201611/line_item_service/update_line_items.py index 048db06c..61b56f07 100755 --- a/examples/dfp/v201602/line_item_service/update_line_items.py +++ b/examples/dfp/v201611/line_item_service/update_line_items.py @@ -16,7 +16,8 @@ """This code example updates the delivery rate of all line items in an order. -To determine which line items exist, run get_all_line_items.py.""" +To determine which line items exist, run get_all_line_items.py. +""" # Import appropriate modules from the client library. @@ -28,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') + line_item_service = client.GetService('LineItemService', version='v201611') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201602/network_service/__init__.py b/examples/dfp/v201611/network_service/__init__.py similarity index 100% rename from examples/dfp/v201602/network_service/__init__.py rename to examples/dfp/v201611/network_service/__init__.py diff --git a/examples/dfp/v201602/network_service/get_all_networks.py b/examples/dfp/v201611/network_service/get_all_networks.py similarity index 69% rename from examples/dfp/v201602/network_service/get_all_networks.py rename to examples/dfp/v201611/network_service/get_all_networks.py index fe308836..e6113c7e 100755 --- a/examples/dfp/v201602/network_service/get_all_networks.py +++ b/examples/dfp/v201611/network_service/get_all_networks.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 networks that you have access to with the current login -credentials. - -A networkCode should be left out for this request.""" - +"""This example gets all networks. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,18 +22,18 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201602') + network_service = client.GetService('NetworkService', version='v201611') - # Get all networks that you have access to with the current login credentials. networks = network_service.getAllNetworks() - # Display results. + # Print out some information for each network. for network in networks: - print ('Network with network code \'%s\' and display name \'%s\' was found.' - % (network['networkCode'], network['displayName'])) + print('Network with network code \'%s\' and display name \'%s\' was found.' + % (network['networkCode'], network['displayName'])) print '\nNumber of results found: %s' % len(networks) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/network_service/make_test_network.py b/examples/dfp/v201611/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201602/network_service/make_test_network.py rename to examples/dfp/v201611/network_service/make_test_network.py index 64f5d706..01325e37 100755 --- a/examples/dfp/v201602/network_service/make_test_network.py +++ b/examples/dfp/v201611/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201602') + network_service = client.GetService('NetworkService', version='v201611') # Create a test network. network = network_service.MakeTestNetwork() diff --git a/examples/dfp/v201602/order_service/__init__.py b/examples/dfp/v201611/order_service/__init__.py similarity index 100% rename from examples/dfp/v201602/order_service/__init__.py rename to examples/dfp/v201611/order_service/__init__.py diff --git a/examples/dfp/v201602/order_service/approve_orders.py b/examples/dfp/v201611/order_service/approve_orders.py similarity index 97% rename from examples/dfp/v201602/order_service/approve_orders.py rename to examples/dfp/v201611/order_service/approve_orders.py index aab76562..cd38ac74 100755 --- a/examples/dfp/v201602/order_service/approve_orders.py +++ b/examples/dfp/v201611/order_service/approve_orders.py @@ -16,7 +16,8 @@ """This code example approves all eligible draft and pending orders. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" import datetime @@ -27,7 +28,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201602') + order_service = client.GetService('OrderService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/order_service/create_orders.py b/examples/dfp/v201611/order_service/create_orders.py similarity index 94% rename from examples/dfp/v201602/order_service/create_orders.py rename to examples/dfp/v201611/order_service/create_orders.py index 1edef159..6380d29a 100755 --- a/examples/dfp/v201602/order_service/create_orders.py +++ b/examples/dfp/v201611/order_service/create_orders.py @@ -16,7 +16,8 @@ """This code example creates new orders. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" import uuid @@ -31,11 +32,11 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201602') + order_service = client.GetService('OrderService', version='v201611') # Create order objects. orders = [] - for i in xrange(5): + for _ in xrange(5): order = { 'name': 'Order #%s' % uuid.uuid4(), 'advertiserId': company_id, diff --git a/examples/dfp/v201602/order_service/get_all_orders.py b/examples/dfp/v201611/order_service/get_all_orders.py similarity index 73% rename from examples/dfp/v201602/order_service/get_all_orders.py rename to examples/dfp/v201611/order_service/get_all_orders.py index 8e74fd66..c13a352a 100755 --- a/examples/dfp/v201602/order_service/get_all_orders.py +++ b/examples/dfp/v201611/order_service/get_all_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,32 +13,29 @@ # 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 code example gets all orders. - -To create orders, run create_orders.py. +"""This example gets all orders. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201602') + order_service = client.GetService('OrderService', version='v201611') - # Create a filter statement. + # Create a statement to select orders. statement = dfp.FilterStatement() - # Get orders by statement. + # Retrieve a small amount of orders at a time, paging + # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for order in response['results']: - print ('Order with id \'%s\', name \'%s\', and advertiser id \'%s\' was' - ' found.' % (order['id'], order['name'], order['advertiserId'])) + # Print out some information for each order. + print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], + order['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201611/order_service/get_orders_starting_soon.py b/examples/dfp/v201611/order_service/get_orders_starting_soon.py new file mode 100755 index 00000000..f1e0078b --- /dev/null +++ b/examples/dfp/v201611/order_service/get_orders_starting_soon.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2016 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 orders that are starting soon. +""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + order_service = client.GetService('OrderService', version='v201611') + query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' + '<= :soon') + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'APPROVED' + }}, + {'key': 'now', + 'value': { + 'xsi_type': 'TextValue', + 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') + }}, + {'key': 'soon', + 'value': { + 'xsi_type': 'TextValue', + 'value': (datetime.now() + timedelta(days=5)) + .strftime('%Y-%m-%dT%H:%M:%S') + }}, + ] + # Create a statement to select orders. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of orders at a time, paging + # through until all orders have been retrieved. + while True: + response = order_service.getOrdersByStatement(statement.ToStatement()) + if 'results' in response: + for order in response['results']: + # Print out some information for each order. + print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], + order['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/order_service/update_orders.py b/examples/dfp/v201611/order_service/update_orders.py similarity index 97% rename from examples/dfp/v201602/order_service/update_orders.py rename to examples/dfp/v201611/order_service/update_orders.py index 704d12ae..cd5fa27a 100755 --- a/examples/dfp/v201602/order_service/update_orders.py +++ b/examples/dfp/v201611/order_service/update_orders.py @@ -16,7 +16,8 @@ """This code example updates the notes of a single order specified by ID. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201602') + order_service = client.GetService('OrderService', version='v201611') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201611/package_service/get_all_packages.py b/examples/dfp/v201611/package_service/get_all_packages.py new file mode 100755 index 00000000..f2c0cc11 --- /dev/null +++ b/examples/dfp/v201611/package_service/get_all_packages.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# +# Copyright 2016 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 packages. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + pkg_service = client.GetService('PackageService', version='v201611') + + # Create a statement to select packages. + statement = dfp.FilterStatement() + + # Retrieve a small amount of packages at a time, paging + # through until all packages have been retrieved. + while True: + response = pkg_service.getPackagesByStatement(statement.ToStatement()) + if 'results' in response: + for pkg in response['results']: + # Print out some information for each package. + print( + 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' + % (pkg['id'], pkg['name'], pkg['proposalId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/package_service/get_in_progress_packages.py b/examples/dfp/v201611/package_service/get_in_progress_packages.py new file mode 100755 index 00000000..ea5205d1 --- /dev/null +++ b/examples/dfp/v201611/package_service/get_in_progress_packages.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 packages in progress. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + pkg_service = client.GetService('PackageService', version='v201611') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'IN_PROGRESS' + }}, + ] + # Create a statement to select packages. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of packages at a time, paging + # through until all packages have been retrieved. + while True: + response = pkg_service.getPackagesByStatement(statement.ToStatement()) + if 'results' in response: + for pkg in response['results']: + # Print out some information for each package. + print( + 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' + % (pkg['id'], pkg['name'], pkg['proposalId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/placement_service/create_placements.py b/examples/dfp/v201611/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201602/placement_service/create_placements.py rename to examples/dfp/v201611/placement_service/create_placements.py index fcadce84..caf2bba1 100755 --- a/examples/dfp/v201602/placement_service/create_placements.py +++ b/examples/dfp/v201611/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201602') - inventory_service = client.GetService('InventoryService', version='v201602') + placement_service = client.GetService('PlacementService', version='v201611') + inventory_service = client.GetService('InventoryService', version='v201611') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201602/placement_service/deactivate_placements.py b/examples/dfp/v201611/placement_service/deactivate_placements.py similarity index 99% rename from examples/dfp/v201602/placement_service/deactivate_placements.py rename to examples/dfp/v201611/placement_service/deactivate_placements.py index 5a0724e8..89397713 100755 --- a/examples/dfp/v201602/placement_service/deactivate_placements.py +++ b/examples/dfp/v201611/placement_service/deactivate_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201602') + placement_service = client.GetService('PlacementService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/placement_service/get_placements_by_statement.py b/examples/dfp/v201611/placement_service/get_active_placements.py similarity index 64% rename from examples/dfp/v201602/placement_service/get_placements_by_statement.py rename to examples/dfp/v201611/placement_service/get_active_placements.py index c75be817..37b3f34a 100755 --- a/examples/dfp/v201602/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201611/placement_service/get_active_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,44 @@ # 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 code example gets all active placements by using a statement. - -To create a placement, run create_placements.py. +"""This example gets all active placements. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201602') - - # Create a statement to only select active placements. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] + placement_service = client.GetService('PlacementService', version='v201611') query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select placements. statement = dfp.FilterStatement(query, values) - # Get placements by statement. + # Retrieve a small amount of placements at a time, paging + # through until all placements have been retrieved. while True: - response = placement_service.getPlacementsByStatement( - statement.ToStatement()) + response = placement_service.getPlacementsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for placement in response['results']: - print ('Placement with id \'%s\' and name \'%s\' was found.' - % (placement['id'], placement['name'])) + # Print out some information for each placement. + print('Placement with ID "%d" and name "%s" was found.\n' % + (placement['id'], placement['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/placement_service/get_all_placements.py b/examples/dfp/v201611/placement_service/get_all_placements.py similarity index 68% rename from examples/dfp/v201602/placement_service/get_all_placements.py rename to examples/dfp/v201611/placement_service/get_all_placements.py index c73d7557..7cea4522 100755 --- a/examples/dfp/v201602/placement_service/get_all_placements.py +++ b/examples/dfp/v201611/placement_service/get_all_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,39 +13,37 @@ # 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 code example gets all placements. - -To create placements, run create_placement.py. +"""This example gets all placements. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201602') + placement_service = client.GetService('PlacementService', version='v201611') - # Create statement to fetch all placements. + # Create a statement to select placements. statement = dfp.FilterStatement() - # Get placements by statement. + # Retrieve a small amount of placements at a time, paging + # through until all placements have been retrieved. while True: - response = placement_service.getPlacementsByStatement( - statement.ToStatement()) + response = placement_service.getPlacementsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for placement in response['results']: - print ('Placement with id \'%s\' and name \'%s\' was found.' - % (placement['id'], placement['name'])) + # Print out some information for each placement. + print('Placement with ID "%d" and name "%s" was found.\n' % + (placement['id'], placement['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/placement_service/update_placements.py b/examples/dfp/v201611/placement_service/update_placements.py similarity index 99% rename from examples/dfp/v201602/placement_service/update_placements.py rename to examples/dfp/v201611/placement_service/update_placements.py index 1a9137c0..dd7a9653 100755 --- a/examples/dfp/v201602/placement_service/update_placements.py +++ b/examples/dfp/v201611/placement_service/update_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201602') + placement_service = client.GetService('PlacementService', version='v201611') # Create query. values = [{ 'key': 'placementId', diff --git a/examples/dfp/v201602/premium_rate_service/__init__.py b/examples/dfp/v201611/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201602/premium_rate_service/__init__.py rename to examples/dfp/v201611/premium_rate_service/__init__.py diff --git a/examples/dfp/v201602/premium_rate_service/create_premium_rates.py b/examples/dfp/v201611/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/dfp/v201602/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201611/premium_rate_service/create_premium_rates.py index 14546531..e47d9439 100755 --- a/examples/dfp/v201602/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201602') + version='v201611') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201602/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py similarity index 61% rename from examples/dfp/v201602/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py index 4d9c47e4..33ad7633 100755 --- a/examples/dfp/v201602/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,38 +13,33 @@ # 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 code example gets all premium rates. - -To create premium rates, run create_premium_rates.py. - +"""This example gets all premium rates. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201602') + premium_rate_service = client.GetService( + 'PremiumRateService', version='v201611') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select premium rates. + statement = dfp.FilterStatement() - # Get premium rates by statement. + # Retrieve a small amount of premium rates at a time, paging + # through until all premium rates have been retrieved. while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for premium_rate in response['results']: - print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' - ' rate card with ID \'%s\' was found.\n' % ( - premium_rate['id'], - dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['rateCardId'])) + # Print out some information for each premium rate. + print('Premium rate with ID "%d", premium feature "%s", and rate card ' + 'id "%d" was found.\n' % (premium_rate['id'], + dfp.DfpClassType(premium_rate), + premium_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 58% rename from examples/dfp/v201602/premium_rate_service/get_premium_rates_for_a_rate_card.py rename to examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py index 4aa87593..f37dce8b 100755 --- a/examples/dfp/v201602/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all premium rates belonging to a specific rate card. - -To create premium rates, run create_premium_rates.py. - +"""This example gets all premium rates on a specific rate card. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -29,32 +24,31 @@ def main(client, rate_card_id): # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201602') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'rateCardId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': rate_card_id - } - }] - query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC' + premium_rate_service = client.GetService( + 'PremiumRateService', version='v201611') + query = 'WHERE rateCardId = :rateCardId' + values = [ + {'key': 'rateCardId', + 'value': { + 'xsi_type': 'TextValue', + 'value': rate_card_id + }}, + ] + # Create a statement to select premium rates. statement = dfp.FilterStatement(query, values) - # Get premium rates by statement. + # Retrieve a small amount of premium rates at a time, paging + # through until all premium rates have been retrieved. while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for premium_rate in response['results']: - print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' - ' rate card with ID \'%s\' was found.\n' % ( - premium_rate['id'], - dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['rateCardId'])) + # Print out some information for each premium rate. + print('Premium rate with ID "%d", premium feature "%s", and rate card ' + 'ID "%d" was found.\n' % (premium_rate['id'], + premium_rate['premium feature'], + premium_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/premium_rate_service/update_premium_rates.py b/examples/dfp/v201611/premium_rate_service/update_premium_rates.py similarity index 97% rename from examples/dfp/v201602/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201611/premium_rate_service/update_premium_rates.py index 23201b03..14b9bb2e 100755 --- a/examples/dfp/v201602/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201602') + version='v201611') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py new file mode 100755 index 00000000..8e3efa13 --- /dev/null +++ b/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py @@ -0,0 +1,53 @@ +#!/usr/bin/python +# +# Copyright 2016 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 product package items. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_package_item_service = client.GetService( + 'ProductPackageItemService', version='v201611') + + # Create a statement to select product package items. + statement = dfp.FilterStatement() + + # Retrieve a small amount of product package items at a time, paging + # through until all product package items have been retrieved. + while True: + response = product_package_item_service.getProductPackageItemsByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package_item in response['results']: + # Print out some information for each product package item. + print('Product package item with ID "%d", product id "%d", and product ' + 'package id "%d" was found.\n' % + (product_package_item['id'], product_package_item['productId'], + product_package_item['productPackageId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py new file mode 100755 index 00000000..6841a0b2 --- /dev/null +++ b/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 product package items belonging to a product package. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + + +def main(client, product_package_id): + # Initialize appropriate service. + product_package_item_service = client.GetService( + 'ProductPackageItemService', version='v201611') + query = 'WHERE productPackageId = :productPackageId' + values = [ + {'key': 'productPackageId', + 'value': { + 'xsi_type': 'TextValue', + 'value': product_package_id + }}, + ] + # Create a statement to select product package items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of product package items at a time, paging + # through until all product package items have been retrieved. + while True: + response = product_package_item_service.getProductPackageItemsByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package_item in response['results']: + # Print out some information for each product package item. + print('Product package item with ID "%d", product ID "%d", and product ' + 'package ID "%d" was found.\n' % + (product_package_item['id'], product_package_item['productId'], + product_package_item['productPackageId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_PACKAGE_ID) diff --git a/examples/dfp/v201611/product_package_service/get_active_product_packages.py b/examples/dfp/v201611/product_package_service/get_active_product_packages.py new file mode 100755 index 00000000..bfd7d55c --- /dev/null +++ b/examples/dfp/v201611/product_package_service/get_active_product_packages.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 active product packages. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_package_service = client.GetService( + 'ProductPackageService', version='v201611') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select product packages. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of product packages at a time, paging + # through until all product packages have been retrieved. + while True: + response = product_package_service.getProductPackagesByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package in response['results']: + # Print out some information for each product package. + print('Product package with ID "%d" and name "%s" was found.\n' % + (product_package['id'], product_package['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/product_package_service/get_all_product_packages.py b/examples/dfp/v201611/product_package_service/get_all_product_packages.py new file mode 100755 index 00000000..894ddcfe --- /dev/null +++ b/examples/dfp/v201611/product_package_service/get_all_product_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2016 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 product packages. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_package_service = client.GetService( + 'ProductPackageService', version='v201611') + + # Create a statement to select product packages. + statement = dfp.FilterStatement() + + # Retrieve a small amount of product packages at a time, paging + # through until all product packages have been retrieved. + while True: + response = product_package_service.getProductPackagesByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package in response['results']: + # Print out some information for each product package. + print('Product package with ID "%d" and name "%s" was found.\n' % + (product_package['id'], product_package['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/product_service/__init__.py b/examples/dfp/v201611/product_service/__init__.py similarity index 100% rename from examples/dfp/v201602/product_service/__init__.py rename to examples/dfp/v201611/product_service/__init__.py diff --git a/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py new file mode 100755 index 00000000..d558134f --- /dev/null +++ b/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a programmatic product for non-sales management. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + product_service = client.GetService('ProductService', version='v201611') + network_service = client.GetService('NetworkService', version='v201611') + + product = { + # Setting required Marketplace Information. + 'productMarketplaceInfo': { + 'additionalTerms': 'Remember to also discuss that thing.', + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for products. + 'name': ('Product #%d' % uuid.uuid4()), + 'productType': 'DFP', + 'rateType': 'CPM', + 'lineItemType': 'STANDARD', + 'priority': 8, + 'environment': 'BROWSER', + 'rate': { + 'currencyCode': 'USD', + 'microAmount': '6000000' + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'builtInTargeting': { + 'inventoryTargeting': { + 'adUnitTargeting': { + 'adUnitId': network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId'], + 'includeDescendents': 'true' + } + } + }, + } + + products = product_service.createProducts([product]) + + if products: + for product in products: + print ('A programmatic product for non-sales management with ID "%s"' + ' and name "%s" was created.' % (product['id'], product['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/product_service/get_all_products.py b/examples/dfp/v201611/product_service/get_all_products.py similarity index 72% rename from examples/dfp/v201602/product_service/get_all_products.py rename to examples/dfp/v201611/product_service/get_all_products.py index ace3c916..0767c318 100755 --- a/examples/dfp/v201602/product_service/get_all_products.py +++ b/examples/dfp/v201611/product_service/get_all_products.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,29 @@ # 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 code example gets all products. - -Products are created automatically from product templates. - +"""This example gets all products. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201602') + product_service = client.GetService('ProductService', version='v201611') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select products. + statement = dfp.FilterStatement() - # Get products by statement. + # Retrieve a small amount of products at a time, paging + # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' was found.' % ( - product['id'], product['name'])) + # Print out some information for each product. + print('Product with ID "%d" and name "%s" was found.\n' % + (product['id'], product['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/product_service/get_products_for_product_template.py b/examples/dfp/v201611/product_service/get_products_for_product_template.py similarity index 70% rename from examples/dfp/v201602/product_service/get_products_for_product_template.py rename to examples/dfp/v201611/product_service/get_products_for_product_template.py index afe8f948..365c06d0 100755 --- a/examples/dfp/v201602/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201611/product_service/get_products_for_product_template.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,9 @@ # 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 products created from a product template. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,28 +24,28 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201602') - - # Create a filter statement to select only products created from a single - # a product template. - values = [{ - 'key': 'productTemplateId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE productTemplateId = :productTemplateId ORDER BY id ASC' + product_service = client.GetService('ProductService', version='v201611') + + query = 'WHERE productTemplateId = :productTemplateId' + values = [ + {'key': 'productTemplateId', + 'value': { + 'xsi_type': 'TextValue', + 'value': product_template_id + }}, + ] + # Create a statement to select products. statement = dfp.FilterStatement(query, values) - # Get products by statement. + # Retrieve a small amount of products at a time, paging + # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' was found.' % ( - product['id'], product['name'])) + # Print out some information for each product. + print('Product with ID "%d" and name "%s" was found.\n' % + (product['id'], product['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py new file mode 100755 index 00000000..9cf947d7 --- /dev/null +++ b/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example publishes a product to Marketplace. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the product to publish. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, product_id): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201611') + + # Create query. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + products_published = 0 + + # Get products by statement. + while True: + response = product_service.getProductsByStatement( + statement.ToStatement()) + if 'results' in response: + for product in response['results']: + print ('Product with id \'%s\' and name \'%s\' will be ' + 'published.' % (product['id'], + product['name'])) + + # Perform action. + result = product_service.performProductAction( + {'xsi_type': 'PublishProducts'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + products_published += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if products_published > 0: + print 'Number of programmatic products published: %s' % products_published + else: + print 'No products were published.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201602/product_service/update_products.py b/examples/dfp/v201611/product_service/update_products.py similarity index 99% rename from examples/dfp/v201602/product_service/update_products.py rename to examples/dfp/v201611/product_service/update_products.py index cb33200a..451887d8 100755 --- a/examples/dfp/v201602/product_service/update_products.py +++ b/examples/dfp/v201611/product_service/update_products.py @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201602') + product_service = client.GetService('ProductService', version='v201611') # Create statement object to select a single product by an ID. values = [{ diff --git a/examples/dfp/v201602/product_template_service/__init__.py b/examples/dfp/v201611/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201602/product_template_service/__init__.py rename to examples/dfp/v201611/product_template_service/__init__.py diff --git a/examples/dfp/v201602/product_template_service/activate_product_templates.py b/examples/dfp/v201611/product_template_service/activate_product_templates.py similarity index 97% rename from examples/dfp/v201602/product_template_service/activate_product_templates.py rename to examples/dfp/v201611/product_template_service/activate_product_templates.py index 7b4e8a81..8542de37 100755 --- a/examples/dfp/v201602/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201611/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201602') + 'ProductTemplateService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/product_template_service/create_product_templates.py b/examples/dfp/v201611/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201602/product_template_service/create_product_templates.py rename to examples/dfp/v201611/product_template_service/create_product_templates.py index 822b9d17..b03e76e3 100755 --- a/examples/dfp/v201602/product_template_service/create_product_templates.py +++ b/examples/dfp/v201611/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201602') + 'ProductTemplateService', version='v201611') network_service = client.GetService( - 'NetworkService', version='v201602') + 'NetworkService', version='v201611') # Create a product template. product_template = { diff --git a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py new file mode 100755 index 00000000..5d512740 --- /dev/null +++ b/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a programmatic product template. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + product_template_service = client.GetService( + 'ProductTemplateService', version='v201611') + network_service = client.GetService( + 'NetworkService', version='v201611') + + product_template = { + # Setting required Marketplace information. + 'productTemplateMarketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + # Setting common required fields for product templates. + 'name': ('Product template #%d' % uuid.uuid4()), + 'description': ('This product template creates standard programmatic' + 'proposal line items targeting all ad units with' + 'product segmentation on geo targeting.'), + 'nameMacro': (' - - ' + ' - '), + 'productType': 'DFP', + 'rateType': 'CPM', + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'lineItemType': 'STANDARD', + 'productSegmentation': { + 'geoSegment': { + 'targetedLocations': [ + {'id': '2840', + 'displayName': 'US'}, + {'id': '2344', + 'displayName': 'Hong Kong'} + ] + }, + 'adUnitSegments': [{ + 'adUnitId': (network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId']), + 'includeDescendants': 'true' + }] + } + } + + product_templates = product_template_service.createProductTemplates( + [product_template]) + + if product_templates: + for product_template in product_templates: + print ('A programmatic product template with ID \'%s\' and name \'%s\' ' + 'was created.' % (product_template['id'], + product_template['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/product_template_service/get_all_product_templates.py b/examples/dfp/v201611/product_template_service/get_all_product_templates.py similarity index 68% rename from examples/dfp/v201602/product_template_service/get_all_product_templates.py rename to examples/dfp/v201611/product_template_service/get_all_product_templates.py index 1e27c0bc..b16537ec 100755 --- a/examples/dfp/v201602/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201611/product_template_service/get_all_product_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all product templates. - -To create product templates, run create_product_template_templates.py. - +"""This example gets all product templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -28,20 +23,21 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201602') + 'ProductTemplateService', version='v201611') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select product templates. + statement = dfp.FilterStatement() - # Get product templates by statement. + # Retrieve a small amount of product templates at a time, paging + # through until all product templates have been retrieved. while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' was found.' % ( - product_template['id'], product_template['name'])) + # Print out some information for each product template. + print('Product template with ID "%d" and name "%s" was found.\n' % + (product_template['id'], product_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py similarity index 63% rename from examples/dfp/v201602/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py index 9df978aa..90bdce21 100755 --- a/examples/dfp/v201602/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,9 @@ # 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 code example gets all sponsorship product templates. - +"""This example gets all sponsorship product templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -26,28 +23,28 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201602') - - # Create a statement to select all sponsorship product templates. - values = [{ - 'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - } - }] - query = 'WHERE lineItemType = :lineItemType ORDER BY id ASC' + 'ProductTemplateService', version='v201611') + query = 'WHERE lineItemType = :lineItemType' + values = [ + {'key': 'lineItemType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'SPONSORSHIP' + }}, + ] + # Create a statement to select product templates. statement = dfp.FilterStatement(query, values) - # Get product templates by statement. + # Retrieve a small amount of product templates at a time, paging + # through until all product templates have been retrieved. while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' was found.' % ( - product_template['id'], product_template['name'])) + # Print out some information for each product template. + print('Product template with ID "%d" and name "%s" was found.\n' % + (product_template['id'], product_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/product_template_service/update_product_templates.py b/examples/dfp/v201611/product_template_service/update_product_templates.py similarity index 98% rename from examples/dfp/v201602/product_template_service/update_product_templates.py rename to examples/dfp/v201611/product_template_service/update_product_templates.py index 32d4798a..dc957b2e 100755 --- a/examples/dfp/v201602/product_template_service/update_product_templates.py +++ b/examples/dfp/v201611/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201602') + 'ProductTemplateService', version='v201611') # Create a statement to select a single product template by ID. values = [{ diff --git a/examples/dfp/v201602/proposal_line_item_service/__init__.py b/examples/dfp/v201611/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201602/proposal_line_item_service/__init__.py rename to examples/dfp/v201611/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201602/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py similarity index 98% rename from examples/dfp/v201602/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py index d6d2a234..41f0e740 100755 --- a/examples/dfp/v201602/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201602') + 'ProposalLineItemService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py new file mode 100755 index 00000000..c83ca7d5 --- /dev/null +++ b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -0,0 +1,119 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates a new programmatic proposal line item. +""" + + +from datetime import date +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the programmatic proposal that the proposal line item will +# belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + +# Set the ID of the Marketplace rate card the proposal line items should be +# priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, proposal_id, product_id, rate_card_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201611') + network_service = client.GetService('NetworkService', version='v201611') + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single programmatic proposal line item. + proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + # Setting common required fields for proposal line items. + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'rateCardId': rate_card_id, + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': { + 'date': { + 'year': str(date.today().year), + 'month': str(date.today().month), + 'day': str(date.today().day) + }, + 'hour': '23', + 'minute': '59', + 'second': '59' + }, + 'endDateTime': { + 'date': { + 'year': str(date.today().year + 1), + 'month': '9', + 'day': '30' + }, + 'hour': '0', + 'minute': '0', + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' + }, + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'netCost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'netRate': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add programmatic proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Programmatic proposal line item with id \'%s\', belonging to ' + 'proposal id \'%s\', and named \'%s\' was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py new file mode 100755 index 00000000..5191dca8 --- /dev/null +++ b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a programmatic proposal line item for non-sales management. +""" + + +from datetime import date +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set proposal that the created proposal line item will belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, proposal_id, product_id): + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201611') + network_service = client.GetService('NetworkService', version='v201611') + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single programmatic proposal line item. + proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for proposal line items. + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': { + 'date': { + 'year': str(date.today().year), + 'month': str(date.today().month), + 'day': str(date.today().day) + }, + 'hour': '23', + 'minute': '59', + 'second': '59' + }, + 'endDateTime': { + 'date': { + 'year': str(date.today().year + 1), + 'month': '9', + 'day': '30' + }, + 'hour': '0', + 'minute': '0', + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' + }, + 'creativePlaceholders': [{ + 'size': { + 'width': '300', + 'height': '250' + } + }, { + 'size': { + 'width': '120', + 'height': '600' + } + }], + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'netCost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'netRate': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Programmatic proposal line item for non-sales management with id ' + '\'%s\', belonging to proposal id \'%s\', and named \'%s\' ' + 'was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID, PRODUCT_ID) + diff --git a/examples/dfp/v201602/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py similarity index 97% rename from examples/dfp/v201602/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py index e07bea88..247a7dbb 100755 --- a/examples/dfp/v201602/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py @@ -41,8 +41,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201602') - network_service = client.GetService('NetworkService', version='v201602') + 'ProposalLineItemService', version='v201611') + network_service = client.GetService('NetworkService', version='v201611') # Get the root ad unit to target. root_ad_unit_id = ( @@ -90,11 +90,11 @@ def main(client, proposal_id, product_id, rate_card_id): 'units': '1000', 'unitType': 'IMPRESSIONS', }, - 'cost': { + 'netCost': { 'currencyCode': 'USD', 'microAmount': '2000000' }, - 'costPerUnit': { + 'netRate': { 'currencyCode': 'USD', 'microAmount': '2000000' }, diff --git a/examples/dfp/v201602/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py similarity index 60% rename from examples/dfp/v201602/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py index 8280ee29..bbe0ec7a 100755 --- a/examples/dfp/v201602/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all proposal line items. - -To create proposal line items, run create_proposal_line_items.py. +"""This example gets all proposal line items. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,23 +23,21 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201602') + 'ProposalLineItemService', version='v201611') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select proposal line items. + statement = dfp.FilterStatement() - # Get proposal line items by statement. + # Retrieve a small amount of proposal line items at a time, paging + # through until all proposal line items have been retrieved. while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for idx, proposal_line_item in enumerate(response['results'], - start=statement.offset): - print ('%s) Proposal line item with id \'%s\', belonging to proposal id' - ' \'%s\', and named \'%s\' was found.' % - (idx, proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + for proposal_line_item in response['results']: + # Print out some information for each proposal line item. + print('Proposal line item with ID "%d" and name "%s" was found.\n' % + (proposal_line_item['id'], proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 54% rename from examples/dfp/v201602/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 7ad00d5e..302427eb 100755 --- a/examples/dfp/v201602/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,50 +13,40 @@ # 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 code example gets all proposal line items that belong to a proposal. - -To create proposal line items, run create_proposal_line_items.py.""" - +"""This example gets all proposal line items belonging to a specific proposal. +""" # Import appropriate modules from the client library. from googleads import dfp -# Set the id of the proposal to get proposal line items from. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', - version='v201602') - - # Create statement object to only select proposal line items belonging to a - # given proposal. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE proposalId = :proposalId ORDER BY id ASC' + 'ProposalLineItemService', version='v201611') + query = 'WHERE proposalId = :proposalId' + values = [ + {'key': 'proposalId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + }}, + ] + # Create a statement to select proposal line items. statement = dfp.FilterStatement(query, values) + # Retrieve a small amount of proposal line items at a time, paging + # through until all proposal line items have been retrieved. while True: - # Get proposal line items by statement. response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: - # Display results. - for idx, proposal_line_item in enumerate(response['results'], - start=statement.offset): - print( - '%s) Proposal line item with id \'%s\', belonging to proposal id ' - '\'%s\', and named \'%s\' was found.' % ( - idx, proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + for proposal_line_item in response['results']: + # Print out some information for each proposal line item. + print('Proposal line item with ID "%d" and name "%s" was found.\n' % + (proposal_line_item['id'], proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py similarity index 94% rename from examples/dfp/v201602/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py index 0132dcb7..f0bedf4a 100755 --- a/examples/dfp/v201602/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201602') + 'ProposalLineItemService', version='v201611') # Create statement to select a proposal line item. values = [{ @@ -52,7 +52,7 @@ def main(client, proposal_line_item_id): if 'results' in response: # Update each the proposal line item's notes field. proposal_line_item = response['results'][0] - proposal_line_item['notes'] = 'Proposal line item ready for submission.' + proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.' # Update proposal line items remotely. proposal_line_items = proposal_line_item_service.updateProposalLineItems( diff --git a/examples/dfp/v201602/proposal_service/__init__.py b/examples/dfp/v201611/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201602/proposal_service/__init__.py rename to examples/dfp/v201611/proposal_service/__init__.py diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py new file mode 100755 index 00000000..7c55fd86 --- /dev/null +++ b/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates new programmatic proposals. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' +BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' + + +def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, + buyer_id): + proposal_service = client.GetService('ProposalService', version='v201611') + network_service = client.GetService('NetworkService', version='v201611') + + proposal = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'buyerAccountId': buyer_id + }, + 'isProgrammatic': True, + # Setting required common fields for Proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), + 'advertiser': { + 'companyId': advertiser_id, + 'type': 'ADVERTISER' + }, + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '100000' + }, + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + 'budget': { + 'microAmount': '100000000', + 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] + }, + } + proposals = proposal_service.createProposals([proposal]) + + # Display results. + for proposal in proposals: + print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + (proposal['id'], proposal['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID, + BUYER_ID) diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py new file mode 100755 index 00000000..7168c561 --- /dev/null +++ b/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a programmatic proposal for networks not using sales management. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' + + +def main(client, programmatic_buyer_id, primary_salesperson_id, + primary_trafficker_id): + proposal_service = client.GetService('ProposalService', version='v201611') + + proposal = { + # Setting required Marketplace information. + 'isProgrammatic': 'true', + 'marketplaceInfo': { + 'buyerAccountId': programmatic_buyer_id, + }, + # Set common required fields for proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '100000' + }, + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + } + + proposals = proposal_service.createProposals([proposal]) + + # Display results. + for proposal in proposals: + print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + (proposal['id'], proposal['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201602/proposal_service/create_proposals.py b/examples/dfp/v201611/proposal_service/create_proposals.py similarity index 94% rename from examples/dfp/v201602/proposal_service/create_proposals.py rename to examples/dfp/v201611/proposal_service/create_proposals.py index 1ca82b97..0fe9be27 100755 --- a/examples/dfp/v201602/proposal_service/create_proposals.py +++ b/examples/dfp/v201611/proposal_service/create_proposals.py @@ -16,7 +16,8 @@ """This code example creates new proposals. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" import uuid @@ -33,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201602') - network_service = client.GetService('NetworkService', version='v201602') + proposal_service = client.GetService('ProposalService', version='v201611') + network_service = client.GetService('NetworkService', version='v201611') # Create proposal objects. proposal = { @@ -62,7 +63,7 @@ def main(client, advertiser_id, primary_salesperson_id, } # Add proposals. - proposals = proposal_service.createProposals([proposals]) + proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: diff --git a/examples/dfp/v201602/proposal_service/get_all_proposals.py b/examples/dfp/v201611/proposal_service/get_all_proposals.py similarity index 72% rename from examples/dfp/v201602/proposal_service/get_all_proposals.py rename to examples/dfp/v201611/proposal_service/get_all_proposals.py index d2f42f99..9134abc5 100755 --- a/examples/dfp/v201602/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201611/proposal_service/get_all_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,32 +13,29 @@ # 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 code example gets all proposals. - -To create proposals, run create_proposals.py. +"""This example gets all proposals. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201602') + proposal_service = client.GetService('ProposalService', version='v201611') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select proposals. + statement = dfp.FilterStatement() - # Get proposals by statement. + # Retrieve a small amount of proposals at a time, paging + # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\' and name \'%s\' was found.' % ( - proposal['id'], proposal['name'])) + # Print out some information for each proposal. + print('Proposal with ID "%d" and name "%s" was found.\n' % + (proposal['id'], proposal['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201611/proposal_service/get_marketplace_comments.py b/examples/dfp/v201611/proposal_service/get_marketplace_comments.py new file mode 100755 index 00000000..663e87b8 --- /dev/null +++ b/examples/dfp/v201611/proposal_service/get_marketplace_comments.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the Marketplace comments for a programmatic proposal. +""" + +# Import appropriate modules from the client library. +from datetime import datetime + +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + marketplace_comment_service = client.GetService( + 'ProposalService', version='v201611') + query = 'WHERE proposalId = %s' % proposal_id + # Create a statement to select marketplace comments. + statement = {'query': query} + + # Retrieve a small amount of marketplace comments at a time, paging + # through until all marketplace comments have been retrieved. + while True: + response = marketplace_comment_service.getMarketplaceCommentsByStatement( + statement) + if 'results' in response: + for marketplace_comment in response['results']: + # Print out some information for each marketplace comment. + date_time = marketplace_comment['creationTime'] + date_time_string = datetime(date_time['date']['year'], + date_time['date']['month'], + date_time['date']['day'], date_time['hour'], + date_time['minute'], + date_time['second']).isoformat() + + print( + 'Marketplace comment with creation time "%s"and comment "%s" was ' + 'found.\n' + % (date_time_string, marketplace_comment['comment'])) + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201602/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py similarity index 66% rename from examples/dfp/v201602/proposal_service/get_proposals_by_statement.py rename to examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py index 54d3b437..b961e67a 100755 --- a/examples/dfp/v201602/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,11 +13,8 @@ # 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 code example gets all proposals that are currently 'PENDING_APPROVAL.' - -To create proposals, run create_proposals.py.""" - +"""This example gets all proposals pending approval. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -25,28 +22,27 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201602') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - } - }] - query = 'WHERE status = :status ORDER BY id ASC' - + proposal_service = client.GetService('ProposalService', version='v201611') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PENDING_APPROVAL' + }}, + ] + # Create a statement to select proposals. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of proposals at a time, paging + # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\' name \'%s\' was found.' - % (proposal['id'], proposal['name'])) + # Print out some information for each proposal. + print('Proposal with ID "%d" and name "%s" was found.\n' % + (proposal['id'], proposal['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py new file mode 100755 index 00000000..3d95d901 --- /dev/null +++ b/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example requests buyer acceptance for a single proposal. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201611') + + # Create query. + values = [{ + 'key': 'proposalId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + } + }] + query = 'WHERE id = :proposalId' + + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + proposals_pushed_to_marketplace = 0 + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for proposal in response['results']: + print ('Programmatic proposal with id \'%s\', name \'%s\', and status ' + '\'%s\' will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) + # Perform action. + result = proposal_service.performProposalAction( + {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposals_pushed_to_marketplace += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if proposals_pushed_to_marketplace > 0: + print ('\nNumber of programmatic proposals pushed to Marketplace: %s' + % proposals_pushed_to_marketplace) + else: + print '\nNo programmatic proposals were pushed to Marketplace.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201602/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py similarity index 96% rename from examples/dfp/v201602/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py index 93def5e8..c2ae4325 100755 --- a/examples/dfp/v201602/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py @@ -16,7 +16,8 @@ """This code example approves a single proposal. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" # Import appropriate modules from the client library. @@ -24,9 +25,10 @@ PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201602') + proposal_service = client.GetService('ProposalService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/proposal_service/update_proposals.py b/examples/dfp/v201611/proposal_service/update_proposals.py similarity index 90% rename from examples/dfp/v201602/proposal_service/update_proposals.py rename to examples/dfp/v201611/proposal_service/update_proposals.py index 6ab3eb5f..195087fa 100755 --- a/examples/dfp/v201602/proposal_service/update_proposals.py +++ b/examples/dfp/v201611/proposal_service/update_proposals.py @@ -16,7 +16,8 @@ """This code example updates the notes of a single proposal specified by ID. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201602') + proposal_service = client.GetService('ProposalService', version='v201611') # Create statement object to select a single proposal by an ID. values = [{ @@ -48,7 +49,7 @@ def main(client, proposal_id): # Update each local proposal object by changing its notes. updated_proposals = [] for proposal in response['results']: - proposal['notes'] = 'Proposal needs further review before approval.' + proposal['internalNotes'] = 'Proposal needs review before approval.' updated_proposals.append(proposal) # Update proposals remotely. @@ -59,7 +60,7 @@ def main(client, proposal_id): for proposal in proposals: print ('Proposal with id \'%s\', name \'%s\', and ' 'notes \'%s\' was updated.' - % (proposal['id'], proposal['name'], proposal['notes'])) + % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: print 'No proposals were updated.' else: diff --git a/examples/dfp/v201602/publisher_query_language_service/__init__.py b/examples/dfp/v201611/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201602/publisher_query_language_service/__init__.py rename to examples/dfp/v201611/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201602/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py similarity index 90% rename from examples/dfp/v201602/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py index 2406460b..48a6df9f 100755 --- a/examples/dfp/v201602/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201602') + report_downloader = client.GetDataDownloader(version='v201611') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) @@ -45,8 +45,8 @@ def main(client): line_items_file.close() ad_units_file.close() - print ('Saved line items to... %s' % line_items_file.name) - print ('Saved ad units to... %s' % ad_units_file.name) + print 'Saved line items to... %s' % line_items_file.name + print 'Saved ad units to... %s' % ad_units_file.name if __name__ == '__main__': diff --git a/examples/dfp/v201602/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 57% rename from examples/dfp/v201602/publisher_query_language_service/get_line_items_named_like.py rename to examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py index 97e045a5..2c7e1596 100755 --- a/examples/dfp/v201602/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all line items with names starting with 'line item'.""" +"""This example fetches programmatic buyer information from the PQL table.""" import tempfile @@ -25,29 +25,22 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201602') + data_downloader = client.GetDataDownloader(version='v201611') - output_file = tempfile.NamedTemporaryFile( - prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) + programmatic_buyers_file = tempfile.NamedTemporaryFile( + prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) - # Create bind value to select line items with names starting with 'line item'. - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'line item%' - } - }] - - pql_query = ('SELECT Name, Id, Status FROM Line_Item ' - 'WHERE Name LIKE :name') + programmatic_buyers_query = ('SELECT BuyerAccountId, Name ' + 'FROM Programmatic_Buyer ' + 'ORDER BY BuyerAccountId ASC') # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - pql_query, output_file, values) - output_file.close() + data_downloader.DownloadPqlResultToCsv( + programmatic_buyers_query, programmatic_buyers_file) + + programmatic_buyers_file.close() - print ('Saved line items to... %s' % output_file.name) + print 'Saved programmatic buyers to... %s' % programmatic_buyers_file.name if __name__ == '__main__': diff --git a/examples/dfp/v201602/rate_card_service/__init__.py b/examples/dfp/v201611/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201602/rate_card_service/__init__.py rename to examples/dfp/v201611/rate_card_service/__init__.py diff --git a/examples/dfp/v201602/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py similarity index 64% rename from examples/dfp/v201602/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201611/rate_card_service/get_all_rate_cards.py index 07c5df84..dd95a292 100755 --- a/examples/dfp/v201602/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,31 @@ # 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 code example gets all rate cards. - +"""This example gets all rate cards. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201602') + rate_card_service = client.GetService('RateCardService', version='v201611') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select rate cards. + statement = dfp.FilterStatement() - # Get rate cards by statement. + # Retrieve a small amount of rate cards at a time, paging + # through until all rate cards have been retrieved. while True: - response = rate_card_service.getRateCardsByStatement( - statement.ToStatement()) + response = rate_card_service.getRateCardsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for rate_card in response['results']: - print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' - 'was found.' % (rate_card['id'], rate_card['name'], - rate_card['currencyCode'])) + # Print out some information for each rate card. + print('Rate card with ID "%d", name "%s", and currency code "%s" was ' + 'found.\n' % + (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py similarity index 58% rename from examples/dfp/v201602/rate_card_service/get_rate_cards_priced_with_currency.py rename to examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py index 860ebb5b..f41a7090 100755 --- a/examples/dfp/v201602/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,41 +14,39 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all rate cards that have a currency in US dollars. - +"""This example gets all rate cards that can be used for Marketplace products. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201602') - - # Create a statement to get all rate cards using USD as currency. - values = [{ - 'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'USD' - } - }] - query = 'WHERE currencyCode = :currencyCode' - + rate_card_service = client.GetService('RateCardService', version='v201611') + query = 'WHERE forMarketplace = :forMarketplace' + values = [ + {'key': 'forMarketplace', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select rate cards. statement = dfp.FilterStatement(query, values) - # Get rate cards by statement. + # Retrieve a small amount of rate cards at a time, paging + # through until all rate cards have been retrieved. while True: - response = rate_card_service.getRateCardsByStatement( - statement.ToStatement()) + response = rate_card_service.getRateCardsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for rate_card in response['results']: - print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' - 'was found.' % (rate_card['id'], rate_card['name'], - rate_card['currencyCode'])) + # Print out some information for each rate card. + print( + 'Rate card with ID "%d", name "%s", and currency code "%s" was ' + 'found.\n' + % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py new file mode 100755 index 00000000..7e626152 --- /dev/null +++ b/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets a reconciliation report's data for line items that served through DFP. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_line_item_report_service = client.GetService( + 'ReconciliationLineItemReportService', version='v201611') + query = ('WHERE reconciliationReportId = :reconciliationReportId AND ' + 'lineItemId != :lineItemId') + values = [ + {'key': 'reconciliationReportId', + 'value': { + 'xsi_type': 'TextValue', + 'value': reconciliation_report_id + }}, + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + }}, + ] + # Create a statement to select reconciliation line item reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation line item reports at a time, + # paging through until all reconciliation line item reports have been + # retrieved. + while True: + response = ( + reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_line_item_report in response['results']: + # Print out some information for each reconciliation line item report. + print( + 'Reconciliation line item report with ID "%d", line item ID "%d", ' + 'reconciliation source "%s", and reconciled volume "%d" was ' + 'found.\n' % + (reconciliation_line_item_report['id'], + reconciliation_line_item_report['lineItemId'], + reconciliation_line_item_report['reconciliationSource'], + reconciliation_line_item_report['reconciledVolume'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py new file mode 100755 index 00000000..a0a0ad7e --- /dev/null +++ b/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets all reconciliation order reports for a given reconciliation report. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_order_report_service = client.GetService( + 'ReconciliationOrderReportService', version='v201611') + query = 'WHERE reconciliationReportId = :reconciliationReportId' + values = [ + {'key': 'reconciliationReportId', + 'value': { + 'xsi_type': 'TextValue', + 'value': reconciliation_report_id + }}, + ] + # Create a statement to select reconciliation order reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation order reports at a time, paging + # through until all reconciliation order reports have been retrieved. + while True: + response = ( + reconciliation_order_report_service + .getReconciliationOrderReportsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_order_report in response['results']: + # Print out some information for each reconciliation order report. + print('Reconciliation order report with ID "%d" and status "%s" was ' + 'found.\n' % (reconciliation_order_report['id'], + reconciliation_order_report['status'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py new file mode 100755 index 00000000..becbc4bf --- /dev/null +++ b/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets a reconciliation report's rows for line items that served through DFP. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_report_row_service = client.GetService( + 'ReconciliationReportRowService', version='v201611') + query = ('WHERE reconciliationReportId = %s AND ' + 'lineItemId != :lineItemId') % reconciliation_report_id + values = [ + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + }}, + ] + # Create a statement to select reconciliation report rows. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation report rows at a time, paging + # through until all reconciliation report rows have been retrieved. + while True: + response = ( + reconciliation_report_row_service + .getReconciliationReportRowsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_report_row in response['results']: + # Print out some information for each reconciliation report row. + print('Reconciliation report row with ID "%d", reconciliation source ' + '"%s", and reconciled volume "%d" was found.\n' % + (reconciliation_report_row['id'], + reconciliation_report_row['reconciliationSource'], + reconciliation_report_row['reconciledVolume'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py new file mode 100755 index 00000000..9658cbe0 --- /dev/null +++ b/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# +# Copyright 2016 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 reconciliation reports. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + reconciliation_report_service = client.GetService( + 'ReconciliationReportService', version='v201611') + + # Create a statement to select reconciliation reports. + statement = dfp.FilterStatement() + + # Retrieve a small amount of reconciliation reports at a time, paging + # through until all reconciliation reports have been retrieved. + while True: + response = ( + reconciliation_report_service + .getReconciliationReportsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_report in response['results']: + # Print out some information for each reconciliation report. + print( + 'Reconciliation report with ID "%d", month "%d", and year "%d" was' + ' found.\n' % (reconciliation_report['id'], + reconciliation_report['startDate']['month'], + reconciliation_report['startDate']['year'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py new file mode 100755 index 00000000..2edadb90 --- /dev/null +++ b/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the previous billing period's reconciliation report. +""" + +# Import appropriate modules from the client library. +from datetime import date +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + reconciliation_report_service = client.GetService( + 'ReconciliationReportService', version='v201611') + + first_of_the_month = date.today().replace(day=1) + last_month = first_of_the_month - timedelta(days=1) + + query = 'WHERE startDate = :startDate' + values = [ + {'key': 'startDate', + 'value': { + 'xsi_type': 'TextValue', + 'value': last_month.strftime('%Y-%m-01') + }}, + ] + # Create a statement to select reconciliation reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation reports at a time, paging + # through until all reconciliation reports have been retrieved. + while True: + response = ( + reconciliation_report_service + .getReconciliationReportsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_report in response['results']: + # Print out some information for each reconciliation report. + print( + 'Reconciliation report with ID "%d" and start date "%s" was found.' + '\n' % (reconciliation_report['id'], + last_month.strftime('%Y-%m-01'))) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201602/report_service/__init__.py b/examples/dfp/v201611/report_service/__init__.py similarity index 100% rename from examples/dfp/v201602/report_service/__init__.py rename to examples/dfp/v201611/report_service/__init__.py diff --git a/examples/dfp/v201602/report_service/run_delivery_report.py b/examples/dfp/v201611/report_service/run_delivery_report.py similarity index 93% rename from examples/dfp/v201602/report_service/run_delivery_report.py rename to examples/dfp/v201611/report_service/run_delivery_report.py index 65f9e547..47fc5e46 100755 --- a/examples/dfp/v201602/report_service/run_delivery_report.py +++ b/examples/dfp/v201611/report_service/run_delivery_report.py @@ -14,8 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report similar to the "Orders report" on the DFP -website with additional attributes and can filter to include just one order. +"""Runs a report similar to the "Orders report" on the DFP website. + +Includes additional attributes and can filter to include just one order. """ from datetime import datetime @@ -66,7 +67,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201602') + report_downloader = client.GetDataDownloader(version='v201611') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201602/report_service/run_inventory_report.py b/examples/dfp/v201611/report_service/run_inventory_report.py similarity index 94% rename from examples/dfp/v201602/report_service/run_inventory_report.py rename to examples/dfp/v201611/report_service/run_inventory_report.py index f9c3b755..35fa1ef9 100755 --- a/examples/dfp/v201602/report_service/run_inventory_report.py +++ b/examples/dfp/v201611/report_service/run_inventory_report.py @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report equal to the "Whole network report" on the -DFP website. -""" +"""Runs a report equal to the "Whole network report" on the DFP website.""" import tempfile @@ -27,9 +25,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201602') + network_service = client.GetService('NetworkService', version='v201611') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201602') + report_downloader = client.GetDataDownloader(version='v201611') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201602/report_service/run_reach_report.py b/examples/dfp/v201611/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201602/report_service/run_reach_report.py rename to examples/dfp/v201611/report_service/run_reach_report.py index 8a856d5e..99908ebe 100755 --- a/examples/dfp/v201602/report_service/run_reach_report.py +++ b/examples/dfp/v201611/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201602') + report_downloader = client.GetDataDownloader(version='v201611') # Create report job. report_job = { diff --git a/examples/dfp/v201602/report_service/run_report_with_custom_fields.py b/examples/dfp/v201611/report_service/run_report_with_custom_fields.py similarity index 94% rename from examples/dfp/v201602/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201611/report_service/run_report_with_custom_fields.py index 571963a6..9d77e614 100755 --- a/examples/dfp/v201602/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201611/report_service/run_report_with_custom_fields.py @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report that with custom fields found in the line -items of an order. -""" +"""Runs a report with custom fields found in the line items of an order.""" import tempfile @@ -30,9 +28,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201602') + line_item_service = client.GetService('LineItemService', version='v201611') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201602') + report_downloader = client.GetDataDownloader(version='v201611') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201602/report_service/run_sales_report.py b/examples/dfp/v201611/report_service/run_sales_report.py similarity index 92% rename from examples/dfp/v201602/report_service/run_sales_report.py rename to examples/dfp/v201611/report_service/run_sales_report.py index 733f2bd0..58e0362d 100755 --- a/examples/dfp/v201602/report_service/run_sales_report.py +++ b/examples/dfp/v201611/report_service/run_sales_report.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report equal to the "Sales by salespersons report." -""" +"""Runs a report equal to the 'Sales by salespersons report'.""" import tempfile @@ -26,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201602') + report_downloader = client.GetDataDownloader(version='v201611') # Create report job. report_job = { diff --git a/examples/dfp/v201611/report_service/run_saved_query.py b/examples/dfp/v201611/report_service/run_saved_query.py new file mode 100755 index 00000000..97e01a14 --- /dev/null +++ b/examples/dfp/v201611/report_service/run_saved_query.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 runs a report from a saved query. +""" + +# Import appropriate modules from the client library. +import tempfile + +from googleads import dfp +from googleads import errors + +SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' + + +def main(client, saved_query_id): + # Initialize appropriate service. + report_service = client.GetService('ReportService', version='v201611') + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201611') + + # Create statement object to filter for an order. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': saved_query_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + response = report_service.getSavedQueriesByStatement( + statement.ToStatement()) + + if 'results' in response: + saved_query = response['results'][0] + + if saved_query['isCompatibleWithApiVersion']: + report_job = {} + + # Set report query and optionally modify it. + report_job['reportQuery'] = saved_query['reportQuery'] + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id \'%s\' downloaded to:\n%s' % ( + report_job_id, report_file.name) + else: + print 'The query specified is not compatible with the API version.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, SAVED_QUERY_ID) diff --git a/examples/dfp/v201602/suggested_ad_unit_service/__init__.py b/examples/dfp/v201611/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201602/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201611/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201602/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201602/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 422a62a1..425fef3f 100755 --- a/examples/dfp/v201602/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201602') + 'SuggestedAdUnitService', version='v201611') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201602/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 69% rename from examples/dfp/v201602/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py index 31034d29..af992a6f 100755 --- a/examples/dfp/v201602/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all suggested ad units. - -To approve suggested ad units, run approve_suggested_ad_units.py. This feature -is only available to DFP premium solution networks. +"""This example gets all suggested ad units. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -28,26 +23,29 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201602') + 'SuggestedAdUnitService', version='v201611') - # Create a filter statement. + # Create a statement to select suggested ad units. statement = dfp.FilterStatement() - # Get suggested ad units by statement. + # Retrieve a small amount of suggested ad units at a time, paging + # through until all suggested ad units have been retrieved. while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for suggested_ad_unit in response['results']: - print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + # Print out some information for each suggested ad unit. + print( + 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' + % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 58% rename from examples/dfp/v201602/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py rename to examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index d4e0f631..78a35e1d 100755 --- a/examples/dfp/v201602/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,51 +13,49 @@ # 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 code example gets suggested ad units that have more than 50 requests. - -This feature is only available to DFP premium solution networks. +"""This example gets all highly requested suggested ad units. """ - # Import appropriate modules from the client library. from googleads import dfp +NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE' + -def main(client): +def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201602') - - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '50' - } - }] - - query = 'WHERE numRequests > :numRequests' - - # Create a filter statement. + 'SuggestedAdUnitService', version='v201611') + query = 'WHERE numRequests >= :numRequests' + values = [ + {'key': 'numRequests', + 'value': { + 'xsi_type': 'TextValue', + 'value': num_requests + }}, + ] + # Create a statement to select suggested ad units. statement = dfp.FilterStatement(query, values) - # Get suggested ad units by statement. + # Retrieve a small amount of suggested ad units at a time, paging + # through until all suggested ad units have been retrieved. while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for suggested_ad_unit in response['results']: - print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + # Print out some information for each suggested ad unit. + print( + 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' + % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + main(dfp_client, NUM_REQUESTS) diff --git a/examples/dfp/v201602/team_service/__init__.py b/examples/dfp/v201611/team_service/__init__.py similarity index 100% rename from examples/dfp/v201602/team_service/__init__.py rename to examples/dfp/v201611/team_service/__init__.py diff --git a/examples/dfp/v201602/team_service/create_teams.py b/examples/dfp/v201611/team_service/create_teams.py similarity index 98% rename from examples/dfp/v201602/team_service/create_teams.py rename to examples/dfp/v201611/team_service/create_teams.py index 3d8caad1..5825fb3a 100755 --- a/examples/dfp/v201602/team_service/create_teams.py +++ b/examples/dfp/v201611/team_service/create_teams.py @@ -22,7 +22,6 @@ "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. - """ @@ -34,11 +33,11 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201602') + team_service = client.GetService('TeamService', version='v201611') # Create team objects. teams = [] - for i in xrange(5): + for _ in xrange(5): team = { 'name': 'Team %s' % uuid.uuid4(), 'hasAllCompanies': 'false', diff --git a/examples/dfp/v201602/team_service/get_all_teams.py b/examples/dfp/v201611/team_service/get_all_teams.py similarity index 70% rename from examples/dfp/v201602/team_service/get_all_teams.py rename to examples/dfp/v201611/team_service/get_all_teams.py index e13035e4..aff0dae6 100755 --- a/examples/dfp/v201602/team_service/get_all_teams.py +++ b/examples/dfp/v201611/team_service/get_all_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,44 +13,36 @@ # 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 teams. - -To create teams, run create_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201602') + team_service = client.GetService('TeamService', version='v201611') - # Create a filter statement. + # Create a statement to select teams. statement = dfp.FilterStatement() - # Get users by statement. + # Retrieve a small amount of teams at a time, paging + # through until all teams have been retrieved. while True: response = team_service.getTeamsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for team in response['results']: - print ('Team with ID \'%s\' and name \'%s\' was found.' - % (team['id'], team['name'])) + # Print out some information for each team. + print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], + team['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/team_service/update_teams.py b/examples/dfp/v201611/team_service/update_teams.py similarity index 75% rename from examples/dfp/v201602/team_service/update_teams.py rename to examples/dfp/v201611/team_service/update_teams.py index f3e50b4f..f8605ccd 100755 --- a/examples/dfp/v201602/team_service/update_teams.py +++ b/examples/dfp/v201611/team_service/update_teams.py @@ -14,10 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates teams by adding an ad unit to a team. +"""This example updates teams by changing its description. -To determine which teams exist, run get_all_teams.py. To determine which ad -units exist, run get_all_ad_units.py +To determine which teams exist, run get_all_teams.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,13 +29,12 @@ # Import appropriate modules from the client library. from googleads import dfp -AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' TEAM_ID = 'INSERT_TEAM_ID_HERE' -def main(client, ad_unit_id, team_id): +def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201602') + team_service = client.GetService('TeamService', version='v201611') # Create a filter statement to select a single team by ID. values = [{ @@ -54,15 +52,9 @@ def main(client, ad_unit_id, team_id): if 'results' in response: updated_teams = [] - # Update each local team object by adding the ad unit to it. + # Update each local team object by changing its description. for team in response['results']: - ad_unit_ids = [] - if 'adUnitIds' in team: - ad_unit_ids = team['adUnitIds'] - # Don't add the ad unit if the team has all inventory already. - if not team['hasAllInventory']: - ad_unit_ids.append(ad_unit_id) - team['adUnitIds'] = ad_unit_ids + team['description'] = 'this team is great!' updated_teams.append(team) # Update teams on the server. @@ -78,4 +70,4 @@ def main(client, ad_unit_id, team_id): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AD_UNIT_ID, TEAM_ID) + main(dfp_client, TEAM_ID) diff --git a/examples/dfp/v201602/user_service/__init__.py b/examples/dfp/v201611/user_service/__init__.py similarity index 100% rename from examples/dfp/v201602/user_service/__init__.py rename to examples/dfp/v201611/user_service/__init__.py diff --git a/examples/dfp/v201602/user_service/create_users.py b/examples/dfp/v201611/user_service/create_users.py similarity index 94% rename from examples/dfp/v201602/user_service/create_users.py rename to examples/dfp/v201611/user_service/create_users.py index 5e37432f..e33d0849 100755 --- a/examples/dfp/v201602/user_service/create_users.py +++ b/examples/dfp/v201611/user_service/create_users.py @@ -16,7 +16,8 @@ """This code example creates new users. -To determine which users exist, run get_all_users.py.""" +To determine which users exist, run get_all_users.py. +""" # Import appropriate modules from the client library. @@ -28,14 +29,13 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201602') + user_service = client.GetService('UserService', version='v201611') # Create user objects. users = [ { 'email': email, 'name': name, - 'preferredLocale': 'en_US' } ] for user in users: diff --git a/examples/dfp/v201602/user_service/deactivate_users.py b/examples/dfp/v201611/user_service/deactivate_users.py similarity index 98% rename from examples/dfp/v201602/user_service/deactivate_users.py rename to examples/dfp/v201611/user_service/deactivate_users.py index a3c0b94e..09463ebf 100755 --- a/examples/dfp/v201602/user_service/deactivate_users.py +++ b/examples/dfp/v201611/user_service/deactivate_users.py @@ -18,7 +18,8 @@ Deactivated users can no longer make requests to the API. The user making the request cannot deactivate itself. To determine which users exist, run -get_all_users.py.""" +get_all_users.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201602') + user_service = client.GetService('UserService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/user_service/get_all_roles.py b/examples/dfp/v201611/user_service/get_all_roles.py similarity index 75% rename from examples/dfp/v201602/user_service/get_all_roles.py rename to examples/dfp/v201611/user_service/get_all_roles.py index 54606aa5..03f79651 100755 --- a/examples/dfp/v201602/user_service/get_all_roles.py +++ b/examples/dfp/v201611/user_service/get_all_roles.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 code example gets all roles. - -This sample can be used to determine which role id is needed when getting and -creating users.""" - +"""This example gets all roles. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,18 +22,18 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201602') + user_service = client.GetService('UserService', version='v201605') - # Get all roles. roles = user_service.getAllRoles() - # Display results. + # Print out some information for each role. for role in roles: - print ('Role with id \'%s\' and name \'%s\' was found.' - % (role['id'], role['name'])) + print('Role with id \'%s\' and name \'%s\' was found.' % + (role['id'], role['name'])) print '\nNumber of results found: %s' % len(roles) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/user_service/get_all_users.py b/examples/dfp/v201611/user_service/get_all_users.py similarity index 73% rename from examples/dfp/v201602/user_service/get_all_users.py rename to examples/dfp/v201611/user_service/get_all_users.py index 29f8f1d4..7c853784 100755 --- a/examples/dfp/v201602/user_service/get_all_users.py +++ b/examples/dfp/v201611/user_service/get_all_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,9 +13,8 @@ # 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 code example gets all users. To create users, run create_users.py.""" - +"""This example gets all users. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -23,25 +22,27 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201602') + user_service = client.GetService('UserService', version='v201611') - # Create a filter statement. + # Create a statement to select users. statement = dfp.FilterStatement() - # Get users by statement. + # Retrieve a small amount of users at a time, paging + # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for user in response['results']: - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) + # Print out some information for each user. + print('User with ID "%d" and name "%s" was found.\n' % (user['id'], + user['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201611/user_service/get_user_by_email_address.py b/examples/dfp/v201611/user_service/get_user_by_email_address.py new file mode 100755 index 00000000..8fb8320d --- /dev/null +++ b/examples/dfp/v201611/user_service/get_user_by_email_address.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 users by email. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' + + +def main(client, email_address): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201611') + query = 'WHERE email = :email' + values = [ + {'key': 'email', + 'value': { + 'xsi_type': 'TextValue', + 'value': email_address + }}, + ] + # Create a statement to select users. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of users at a time, paging + # through until all users have been retrieved. + while True: + response = user_service.getUsersByStatement(statement.ToStatement()) + if 'results' in response: + for user in response['results']: + # Print out some information for each user. + print('User with ID "%d" and name "%s" was found.\n' % (user['id'], + user['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, EMAIL_ADDRESS) diff --git a/examples/dfp/v201602/user_service/update_users.py b/examples/dfp/v201611/user_service/update_users.py similarity index 96% rename from examples/dfp/v201602/user_service/update_users.py rename to examples/dfp/v201611/user_service/update_users.py index 1a3f575f..e58b3097 100755 --- a/examples/dfp/v201602/user_service/update_users.py +++ b/examples/dfp/v201611/user_service/update_users.py @@ -16,7 +16,8 @@ """This code example updates a user by adding " Sr." to the end of their name. -To determine which users exist, run get_all_users.py.""" +To determine which users exist, run get_all_users.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201602') + user_service = client.GetService('UserService', version='v201611') # Create query. values = [{ diff --git a/examples/dfp/v201602/user_team_association_service/__init__.py b/examples/dfp/v201611/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201602/user_team_association_service/__init__.py rename to examples/dfp/v201611/user_team_association_service/__init__.py diff --git a/examples/dfp/v201602/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201602/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201611/user_team_association_service/create_user_team_associations.py index c9ee9903..099610ec 100755 --- a/examples/dfp/v201602/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201602') + 'UserTeamAssociationService', version='v201611') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201602/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py similarity index 98% rename from examples/dfp/v201602/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py index a2aed829..17936e8b 100755 --- a/examples/dfp/v201602/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201602') + 'UserTeamAssociationService', version='v201611') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201602/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py similarity index 63% rename from examples/dfp/v201602/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py index cb7243fd..c1f3854c 100755 --- a/examples/dfp/v201602/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 user team associations. - -To create user team associations, run create_user_team_assocations.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,21 +23,22 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201602') + 'UserTeamAssociationService', version='v201611') - # Create a filter statement. + # Create a statement to select user team associations. statement = dfp.FilterStatement() - # Get user team associations by statement. + # Retrieve a small amount of user team associations at a time, paging + # through until all user team associations have been retrieved. while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for user_team_association in response['results']: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was found.' % (user_team_association['userId'], - user_team_association['teamId'])) + # Print out some information for each user team association. + print('User team association with team id "%d" and user id "%d" was ' + 'found.\n' % (user_team_association['teamId'], + user_team_association['userId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py similarity index 59% rename from examples/dfp/v201602/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py index edc3ec0e..8b96abd9 100755 --- a/examples/dfp/v201602/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 user team associations for a single user. - -To determine which users exist, run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all user team associations (i.e. teams) for a given user. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -35,37 +25,36 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201602') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] + 'UserTeamAssociationService', version='v201611') query = 'WHERE userId = :userId' - - # Create a filter statement. + values = [ + {'key': 'userId', + 'value': { + 'xsi_type': 'TextValue', + 'value': user_id + }}, + ] + # Create a statement to select user team associations. statement = dfp.FilterStatement(query, values) - # Get user team associations by statement. + # Retrieve a small amount of user team associations at a time, paging + # through until all user team associations have been retrieved. while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for user_team_association in response['results']: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was found.' % (user_team_association['userId'], - user_team_association['teamId'])) + # Print out some information for each user team association. + print('User team association with user ID "%d" and team ID "%d" was ' + 'found.\n' % (user_team_association['userId'], + user_team_association['teamId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201602/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py similarity index 98% rename from examples/dfp/v201602/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201611/user_team_association_service/update_user_team_associations.py index 73176735..2ec85897 100755 --- a/examples/dfp/v201602/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201602') + 'UserTeamAssociationService', version='v201611') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201602/workflow_request_service/__init__.py b/examples/dfp/v201611/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201602/workflow_request_service/__init__.py rename to examples/dfp/v201611/workflow_request_service/__init__.py diff --git a/examples/dfp/v201602/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py similarity index 97% rename from examples/dfp/v201602/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py index 89dbd1f2..d749e76d 100755 --- a/examples/dfp/v201602/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201602') + version='v201611') # Create query. values = [ diff --git a/examples/dfp/v201602/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py similarity index 62% rename from examples/dfp/v201602/workflow_request_service/get_workflow_approval_requests_by_statement.py rename to examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py index fe8e7d13..53fdc773 100755 --- a/examples/dfp/v201602/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,43 @@ # 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 workflow approval requests. Workflow approval requests must be approved or rejected for a workflow to finish. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201602') - - # Create statement object to select all workflow approval requests. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - }] + workflow_request_service = client.GetService( + 'WorkflowRequestService', version='v201611') query = 'WHERE type = :type' - + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_APPROVAL_REQUEST' + }}, + ] + # Create a statement to select workflow requests. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of workflow requests at a time, paging + # through until all workflow requests have been retrieved. while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for workflow_request in response['results']: - print ('Workflow approval request with id \'%s\' for %s with id \'%s\' ' - 'was found.' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + # Print out some information for each workflow request. + print('Workflow request with ID "%d", entity type "%s", and entity ID ' + '"%d" was found.\n' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py similarity index 61% rename from examples/dfp/v201602/workflow_request_service/get_workflow_external_condition_requests_by_statement.py rename to examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py index 24d85042..b5c00cee 100755 --- a/examples/dfp/v201602/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,43 @@ # 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 workflow external condition requests. -Workflow external condition requests must be triggered or skipped for a workflow -to finish. - +Workflow external condition requests must be triggered or skipped for a +workflow to finish. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201602') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - }] + workflow_request_service = client.GetService( + 'WorkflowRequestService', version='v201611') query = 'WHERE type = :type' - + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' + }}, + ] + # Create a statement to select workflow requests. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of workflow requests at a time, paging + # through until all workflow requests have been retrieved. while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id \'%s\' for %s ' - 'with id \'%s\' was found.' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + # Print out some information for each workflow request. + print('Workflow request with ID "%d", entity type "%s", and entity ID ' + '"%d" was found.\n' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201602/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 98% rename from examples/dfp/v201602/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py index 913335b6..a7127cad 100755 --- a/examples/dfp/v201602/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201602') + version='v201611') # Create query. values = [ diff --git a/googleads/adwords.py b/googleads/adwords.py index 3036c4c5..b2d4fbbc 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -227,6 +227,25 @@ class AdWordsClient(object): # name need to be formatted in. _SOAP_SERVICE_FORMAT = '%s/api/adwords/%s/%s/%s?wsdl' + @classmethod + def LoadFromString(cls, yaml_doc): + """Creates an AdWordsClient with information stored in a yaml string. + + Args: + yaml_doc: The yaml string containing the cached AdWords data. + + Returns: + An AdWordsClient initialized with the values cached in the string. + + Raises: + A GoogleAdsValueError if the given yaml string does not contain the + information necessary to instantiate a client object - either a + required key was missing or an OAuth2 key was missing. + """ + return cls(**googleads.common.LoadFromString( + yaml_doc, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES, + cls._OPTIONAL_INIT_VALUES)) + @classmethod def LoadFromStorage(cls, path=None): """Creates an AdWordsClient with information stored in a yaml file. @@ -588,6 +607,9 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): 'AdGroupCriterionLabelOperation': _OPERATION( 'AdGroupCriterionLabelOperation', 'AdGroupCriterionService', 'mutateLabel'), + 'AdGroupExtensionSettingOperation': _OPERATION( + 'AdGroupExtensionSettingOperation', + 'AdGroupExtensionSettingService', 'mutate'), 'AdGroupOperation': _OPERATION('AdGroupOperation', 'AdGroupService', 'mutate'), 'AdGroupLabelOperation': _OPERATION('AdGroupLabelOperation', @@ -596,10 +618,16 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): 'mutate'), 'CampaignCriterionOperation': _OPERATION( 'CampaignCriterionOperation', 'CampaignCriterionService', 'mutate'), + 'CampaignExtensionSettingOperation': _OPERATION( + 'CampaignExtensionSettingOperation', + 'CampaignExtensionSettingService', 'mutate'), 'CampaignOperation': _OPERATION('CampaignOperation', 'CampaignService', 'mutate'), 'CampaignLabelOperation': _OPERATION('CampaignLabelOperation', 'CampaignService', 'mutateLabel'), + 'CustomerExtensionSettingOperation': _OPERATION( + 'CustomerExtensionSettingOperation', + 'CustomerExtensionSettingService', 'mutate'), 'FeedItemOperation': _OPERATION('FeedItemOperation', 'FeedItemService', 'mutate') } @@ -1056,7 +1084,7 @@ def UploadOperations(self, operations, is_last=False): self._url_opener.open(req) except urllib2.HTTPError as e: if e.code != 308: - raise urllib2.HTTPError(e) + raise # Update upload status. self._current_content_length += len(req.data) self._is_last = is_last @@ -1120,9 +1148,11 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], self._marshaller = suds.mx.literal.Literal(schema) def _DownloadReportCheckFormat(self, file_format, output): - is_binary_mode = getattr(output, 'mode', 'w') == 'wb' + mode = getattr(output, 'mode', 'w') + is_valid_gzip_mode = 'b' in mode and ('+' in mode or 'w' in mode) + if (file_format.startswith('GZIPPED_') - and not (is_binary_mode or type(output) is io.BytesIO)): + and not (is_valid_gzip_mode or type(output) is io.BytesIO)): raise googleads.errors.GoogleAdsValueError('Need to specify a binary' ' output for GZIPPED formats.') diff --git a/googleads/common.py b/googleads/common.py index dcdbb09f..210f6c69 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -59,7 +59,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '4.7.0' +VERSION = '4.8.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' @@ -106,8 +106,8 @@ def GenerateLibSig(short_name): return ' (%s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION) -def LoadFromStorage(path, product_yaml_key, required_client_values, - optional_product_values): +def LoadFromString(yaml_doc, product_yaml_key, required_client_values, + optional_product_values): """Loads the data necessary for instantiating a client from file storage. In addition to the required_client_values argument, the yaml file must supply @@ -115,7 +115,7 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, configurations. Args: - path: A path string to the yaml document whose keys should be used. + yaml_doc: the yaml document whose keys should be used. product_yaml_key: The key to read in the yaml as a string. required_client_values: A tuple of strings representing values which must be in the yaml file for a supported API. If one of these keys is not in @@ -142,20 +142,19 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, _PY_VERSION_MINOR, _PY_VERSION_MICRO) - if not os.path.isabs(path): - path = os.path.expanduser(path) + data = yaml.safe_load(yaml_doc) or {} + try: - with open(path, 'rb') as handle: - data = yaml.safe_load(handle.read()) - product_data = data[product_yaml_key] - proxy_config_data = data.get(_PROXY_CONFIG_KEY) or {} - except IOError: - raise googleads.errors.GoogleAdsValueError( - 'Given yaml file, %s, could not be opened.' % path) + product_data = data[product_yaml_key] except KeyError: raise googleads.errors.GoogleAdsValueError( - 'Given yaml file, %s, does not contain a "%s" configuration.' - % (path, product_yaml_key)) + 'The "%s" configuration is missing' + % (product_yaml_key,)) + + if not isinstance(product_data, dict): + raise googleads.errors.GoogleAdsValueError( + 'The "%s" configuration is empty or invalid' + % (product_yaml_key,)) IncludeUtilitiesInUserAgent(data.get(_UTILITY_REGISTER_YAML_KEY, True)) @@ -167,10 +166,11 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, del product_data[key] except KeyError: raise googleads.errors.GoogleAdsValueError( - 'Your yaml file, %s, is missing some of the required values. Required ' + 'Some of the required values are missing. Required ' 'values are: %s, actual values are %s' - % (path, required_client_values, original_keys)) + % (required_client_values, original_keys)) + proxy_config_data = data.get(_PROXY_CONFIG_KEY, {}) proxy_config = _ExtractProxyConfig(product_yaml_key, proxy_config_data) client_kwargs['proxy_config'] = proxy_config client_kwargs['oauth2_client'] = _ExtractOAuth2Client( @@ -182,9 +182,58 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, del product_data[value] if product_data: - warnings.warn('Your yaml file, %s, contains the following unrecognized ' - 'keys: %s. They were ignored.' % (path, product_data), - stacklevel=3) + warnings.warn('Could not recognize the following keys: %s. ' + 'They were ignored.' % (product_data,), stacklevel=3) + + return client_kwargs + + +def LoadFromStorage(path, product_yaml_key, required_client_values, + optional_product_values): + """Loads the data necessary for instantiating a client from file storage. + + In addition to the required_client_values argument, the yaml file must supply + the keys used to create OAuth2 credentials. It may also optionally set proxy + configurations. + + Args: + path: A path string to the yaml document whose keys should be used. + product_yaml_key: The key to read in the yaml as a string. + required_client_values: A tuple of strings representing values which must + be in the yaml file for a supported API. If one of these keys is not in + the yaml file, an error will be raised. + optional_product_values: A tuple of strings representing optional values + which may be in the yaml file. + + Returns: + A dictionary map of the keys in the yaml file to their values. This will not + contain the keys used for OAuth2 client creation and instead will have a + GoogleOAuth2Client object stored in the 'oauth2_client' field. + + Raises: + A GoogleAdsValueError if the given yaml file does not contain the + information necessary to instantiate a client object - either a + required_client_values key was missing or an OAuth2 key was missing. + """ + + if not os.path.isabs(path): + path = os.path.expanduser(path) + + try: + with open(path, 'rb') as handle: + yaml_doc = handle.read() + except IOError: + raise googleads.errors.GoogleAdsValueError( + 'Given yaml file, %s, could not be opened.' % path) + + try: + client_kwargs = LoadFromString(yaml_doc, product_yaml_key, + required_client_values, + optional_product_values) + except googleads.errors.GoogleAdsValueError as e: + e.message = ('Given yaml file, %s, ' + 'could not find some keys. %s' % (path, e.message)) + raise return client_kwargs diff --git a/googleads/dfp.py b/googleads/dfp.py index caa85889..b4c70653 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -39,28 +39,7 @@ _CHUNK_SIZE = 16 * 1024 # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201508': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentMetadataKeyHierarchyService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', - 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardService', - 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', - 'SuggestedAdUnitService', 'TeamService', 'UserService', - 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201511': + 'v201602': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -78,10 +57,10 @@ 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', 'SharedAdUnitService', + 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201602': + 'v201605': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -102,7 +81,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201605': + 'v201608': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -123,7 +102,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201608': + 'v201611': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -133,11 +112,11 @@ 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NetworkService', 'OrderService', + 'PackageService', 'PlacementService', 'PremiumRateService', + 'ProductService', 'ProductPackageService', 'ProductPackageItemService', + 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', @@ -174,6 +153,25 @@ class DfpClient(object): # to be formatted in. _SOAP_SERVICE_FORMAT = '%s/apis/ads/publisher/%s/%s?wsdl' + @classmethod + def LoadFromString(cls, yaml_doc): + """Creates a DfpClient with information stored in a yaml string. + + Args: + yaml_doc: The yaml string containing the cached DFP data. + + Returns: + A DfpClient initialized with the values cached in the yaml string. + + Raises: + A GoogleAdsValueError if the given yaml string does not contain the + information necessary to instantiate a client object - either a + required key was missing or an OAuth2 key was missing. + """ + return cls(**googleads.common.LoadFromString( + yaml_doc, cls._YAML_KEY, cls._REQUIRED_INIT_VALUES, + cls._OPTIONAL_INIT_VALUES)) + @classmethod def LoadFromStorage(cls, path=None): """Creates a DfpClient with information stored in a yaml file. diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 90d428ec..7226d343 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -265,6 +265,7 @@ def setUp(self): self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.adwords_client, CURRENT_VERSION) + def testLoadFromStorage(self): with mock.patch('googleads.oauth2.GoogleRefreshTokenClient.Refresh'): self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage( @@ -1473,6 +1474,26 @@ def testDownloadReportCheckFormat_GZIPPEDStringFailure(self): self.report_downloader._DownloadReportCheckFormat, 'GZIPPED_CSV', output_file) + def testDownloadReportCheckFormat_Issue152(self): + output_file = io.StringIO() + output_file.mode = 'w+b' # Verify writing and reading works. + + try: + self.report_downloader._DownloadReportCheckFormat( + 'GZIPPED_CSV', output_file) + except googleads.errors.GoogleAdsValueError: + self.fail('_DownloadReportCheckFormat raised GoogleAdsValueError' + 'unexpectedly!') + + output_file.mode = 'r+b' # Verify reading and writing works. + + try: + self.report_downloader._DownloadReportCheckFormat( + 'GZIPPED_CSV', output_file) + except googleads.errors.GoogleAdsValueError: + self.fail('_DownloadReportCheckFormat raised GoogleAdsValueError' + 'unexpectedly!') + def testDownloadReport_failure(self): output_file = io.StringIO() report_definition = {'table': 'campaigns', diff --git a/tests/common_test.py b/tests/common_test.py index 118f1278..2b89f54e 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -84,9 +84,111 @@ def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): return yaml_file.name - def testLoadFromStorage_deprecatedWarningLogger(self): + def testLoadFromStorage_missingFile(self): + with mock.patch('googleads.common.open', self.fake_open, create=True): + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromStorage, + 'yaml_filename', 'woo', [], []) + + def testLoadFromStorage_missingRequiredKey(self): + with mock.patch('googleads.common.open', self.fake_open, create=True): + # Both keys are missing. + yaml_fname = self._CreateYamlFile({'two': {}}, 'two', + self._OAUTH_INSTALLED_APP_DICT) + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromStorage, + yaml_fname, 'two', ['needed', 'keys'], []) + + # One key is missing. + yaml_fname = self._CreateYamlFile({'three': {'needed': 'd'}}, 'three', + self._OAUTH_INSTALLED_APP_DICT) + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromStorage, + yaml_fname, 'three', ['needed', 'keys'], []) + + def testLoadFromStorage(self): + # No optional keys present. yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e'}}, 'one', self._OAUTH_INSTALLED_APP_DICT) + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'one', ['needed', 'keys'], ['other']) + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', + 'proxy_config': proxy_config.return_value}, rval) + self.assertTrue(googleads.common._utility_registry._enabled) + + # The optional key is present. + yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e', + 'other': 'f'}}, 'one', + self._OAUTH_INSTALLED_APP_DICT) + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'one', ['needed', 'keys'], ['other']) + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', 'other': 'f', + 'proxy_config': proxy_config.return_value}, rval) + self.assertTrue(googleads.common._utility_registry._enabled) + + def testLoadFromStorage_relativePath(self): + fake_os = fake_filesystem.FakeOsModule(self.filesystem) + yaml_contents = {'one': {'needed': 'd', 'keys': 'e'}} + yaml_contents['one'].update(self._OAUTH_INSTALLED_APP_DICT) + self.filesystem.CreateFile('/home/test/yaml/googleads.yaml', + contents=yaml.dump(yaml_contents)) + fake_os.chdir('/home/test') + + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: + with mock.patch('googleads.common.os', fake_os): + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('googleads.common.ProxyConfig') as proxy_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + 'yaml/googleads.yaml', 'one', ['needed', 'keys'], ['other']) + + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'proxy_config': proxy_config.return_value, + 'needed': 'd', 'keys': 'e'}, rval) + self.assertTrue(googleads.common._utility_registry._enabled) + + def _CreateYamlDoc(self, data, insert_oauth2_key=None, oauth_dict=None): + """Return the yaml doc created for testing.""" + for key in data: + if key is insert_oauth2_key: + data[key].update(oauth_dict) + return yaml.dump(data) + + def testLoadFromString_deprecatedWarningLoggerByMicroValue(self): + yaml_doc = self._CreateYamlDoc({ + 'one': { + 'needed': 'd', + 'keys': 'e' + } + }, 'one', self._OAUTH_INSTALLED_APP_DICT) test_major_value = 2 test_minor_value = 7 test_micro_value = 6 @@ -94,54 +196,103 @@ def testLoadFromStorage_deprecatedWarningLogger(self): with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): with mock.patch('googleads.common._logger') as mock_logger: - with mock.patch('googleads.common.open', self.fake_open, - create=True): - googleads.common.LoadFromStorage(yaml_fname, 'one', - ['needed', 'keys'], ['other']) + with mock.patch( + 'googleads.common.open', self.fake_open, create=True): + googleads.common.LoadFromString(yaml_doc, 'one', + ['needed', 'keys'], ['other']) mock_logger.warning.assert_called_once_with( googleads.common._DEPRECATED_VERSION_TEMPLATE, test_major_value, test_minor_value, test_micro_value) - def testLoadFromStorage_missingFile(self): + def testLoadFromString_deprecatedWarningLoggerByMinorValue(self): + yaml_doc = self._CreateYamlDoc({'one': {'needed': 'd', 'keys': 'e'}}, + 'one', self._OAUTH_INSTALLED_APP_DICT) + test_major_value = 2 + test_minor_value = 6 + test_micro_value = 9 + with mock.patch('googleads.common._PY_VERSION_MAJOR', test_major_value): + with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): + with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): + with mock.patch('googleads.common._logger') as mock_logger: + with mock.patch( + 'googleads.common.open', self.fake_open, create=True): + googleads.common.LoadFromString(yaml_doc, 'one', + ['needed', 'keys'], ['other']) + mock_logger.warning.assert_called_once_with( + googleads.common._DEPRECATED_VERSION_TEMPLATE, + test_major_value, test_minor_value, test_micro_value) + + def testLoadFromString_emptyYamlString(self): + yaml_doc = '' with mock.patch('googleads.common.open', self.fake_open, create=True): self.assertRaises( googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromStorage, - 'yaml_filename', 'woo', [], []) + googleads.common.LoadFromString, + yaml_doc, 'woo', [], []) - def testLoadFromStorage_missingOAuthKey(self): - yaml_fname = self._CreateYamlFile({'woo': {}}) + def testLoadFromString_malformedYamlString(self): + yaml_doc = 'woo:::' + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromString, + yaml_doc, 'woo', [], []) + + def testLoadFromString_emptyProductData(self): + yaml_doc = self._CreateYamlDoc({'woo': None}) + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromString, + yaml_doc, 'woo', [], []) + + def testLoadFromString_missingOAuthKey(self): + yaml_doc = self._CreateYamlDoc({'woo': {}}) with mock.patch('googleads.common.open', self.fake_open, create=True): self.assertRaises( googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromStorage, - yaml_fname, 'woo', [], []) + googleads.common.LoadFromString, + yaml_doc, 'woo', [], []) - def testLoadFromStorage_missingPartialInstalledAppOAuthCredential(self): - yaml_fname = self._CreateYamlFile({'woo': {}}, 'woo', {'client_id': 'abc'}) + def testLoadFromString_missingProductYamlKey(self): + yaml_doc = self._CreateYamlDoc({'woo': {}}) with mock.patch('googleads.common.open', self.fake_open, create=True): self.assertRaises( googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromStorage, - yaml_fname, 'woo', [], []) + googleads.common.LoadFromString, + yaml_doc, 'bar', [], []) - def testLoadFromStorage_missingPartialServiceAcctOAuthCredential(self): - yaml_fname = self._CreateYamlFile({'woo': {}}, 'woo', { + def testLoadFromString_missingRequiredKey(self): + yaml_doc = self._CreateYamlDoc({'woo': {}}) + with mock.patch('googleads.common.open', self.fake_open, create=True): + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromString, + yaml_doc, 'woo', ['bar'], []) + + def testLoadFromString_missingPartialInstalledAppOAuthCredential(self): + yaml_doc = self._CreateYamlDoc({'woo': {}}, 'woo', {'client_id': 'abc'}) + with mock.patch('googleads.common.open', self.fake_open, create=True): + self.assertRaises( + googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromString, + yaml_doc, 'woo', [], []) + + def testLoadFromString_missingPartialServiceAcctOAuthCredential(self): + yaml_doc = self._CreateYamlDoc({'woo': {}}, 'woo', { 'service_account_email': 'abc@xyz.com'}) with mock.patch('googleads.common.open', self.fake_open, create=True): self.assertRaises( googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromStorage, - yaml_fname, 'woo', [], []) + googleads.common.LoadFromString, + yaml_doc, 'woo', [], []) - def testLoadFromStorage_passesWithNoRequiredKeys(self): - yaml_fname = self._CreateYamlFile({'woo': {}}, 'woo', - self._OAUTH_INSTALLED_APP_DICT) + def testLoadFromString_passesWithNoRequiredKeys(self): + yaml_doc = self._CreateYamlDoc({'woo': {}}, 'woo', + self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage(yaml_fname, 'woo', [], []) + rval = googleads.common.LoadFromString(yaml_doc, 'woo', [], []) proxy_config.assert_called_once_with( http_proxy=None, https_proxy=None, cafile=None, @@ -151,8 +302,8 @@ def testLoadFromStorage_passesWithNoRequiredKeys(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value}, rval) - def testLoadFromStorage_passesWithHTTPAndHTTPSProxy(self): - yaml_fname = self._CreateYamlFile( + def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): + yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { 'http_proxy': {'host': self.host1, 'port': self.port1}, @@ -164,8 +315,8 @@ def testLoadFromStorage_passesWithHTTPAndHTTPSProxy(self): proxy_config.return_value = mock.Mock() with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'adwords', [], []) + rval = googleads.common.LoadFromString( + yaml_doc, 'adwords', [], []) proxy.assert_has_calls([mock.call(self.host1, self.port1, username=None, password=None), mock.call(self.host2, self.port2, @@ -179,8 +330,8 @@ def testLoadFromStorage_passesWithHTTPAndHTTPSProxy(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value}, rval) - def testLoadFromStorage_passesWithHTTPProxy(self): - yaml_fname = self._CreateYamlFile( + def testLoadFromString_passesWithHTTPProxy(self): + yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { 'http_proxy': {'host': self.host1, 'port': self.port1}}}, @@ -191,8 +342,8 @@ def testLoadFromStorage_passesWithHTTPProxy(self): proxy_config.return_value = mock.Mock() with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'adwords', [], []) + rval = googleads.common.LoadFromString( + yaml_doc, 'adwords', [], []) proxy.assert_called_once_with(self.host1, self.port1, username=None, password=None) @@ -204,8 +355,8 @@ def testLoadFromStorage_passesWithHTTPProxy(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value}, rval) - def testLoadFromStorage_passesWithHTTPProxyLogin(self): - yaml_fname = self._CreateYamlFile( + def testLoadFromString_passesWithHTTPProxyLogin(self): + yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { 'http_proxy': {'host': self.host1, 'port': self.port1, @@ -218,8 +369,8 @@ def testLoadFromStorage_passesWithHTTPProxyLogin(self): proxy_config.return_value = mock.Mock() with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'adwords', [], []) + rval = googleads.common.LoadFromString( + yaml_doc, 'adwords', [], []) proxy.assert_called_once_with(self.host1, self.port1, username=self.username, @@ -232,8 +383,8 @@ def testLoadFromStorage_passesWithHTTPProxyLogin(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value}, rval) - def testLoadFromStorage_passesWithHTTPSProxy(self): - yaml_fname = self._CreateYamlFile( + def testLoadFromString_passesWithHTTPSProxy(self): + yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { 'https_proxy': {'host': self.host1, 'port': self.port1}}}, @@ -244,8 +395,8 @@ def testLoadFromStorage_passesWithHTTPSProxy(self): proxy_config.return_value = mock.Mock() with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'adwords', [], []) + rval = googleads.common.LoadFromString( + yaml_doc, 'adwords', [], []) proxy.assert_called_once_with(self.host1, self.port1, username=None, password=None) @@ -258,8 +409,8 @@ def testLoadFromStorage_passesWithHTTPSProxy(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value}, rval) - def testLoadFromStorage_passesWithHTTPSProxyLogin(self): - yaml_fname = self._CreateYamlFile( + def testLoadFromString_passesWithHTTPSProxyLogin(self): + yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { 'https_proxy': {'host': self.host1, 'port': self.port1, @@ -272,8 +423,8 @@ def testLoadFromStorage_passesWithHTTPSProxyLogin(self): proxy_config.return_value = mock.Mock() with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'adwords', [], []) + rval = googleads.common.LoadFromString( + yaml_doc, 'adwords', [], []) proxy.assert_called_once_with(self.host1, self.port1, username=self.username, @@ -287,8 +438,8 @@ def testLoadFromStorage_passesWithHTTPSProxyLogin(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value}, rval) - def testLoadFromStorage_failsWithMisconfiguredProxy(self): - yaml_fname = self._CreateYamlFile( + def testLoadFromString_failsWithMisconfiguredProxy(self): + yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { 'http_proxy': {'host': self.host1}}}, @@ -301,37 +452,43 @@ def testLoadFromStorage_failsWithMisconfiguredProxy(self): with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: proxy.return_value = mock.Mock() self.assertRaises(googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromStorage, - yaml_fname, 'adwords', [], []) + googleads.common.LoadFromString, + yaml_doc, 'adwords', [], []) - def testLoadFromStorage_missingRequiredKey(self): + def testLoadFromString_missingRequiredKeys(self): with mock.patch('googleads.common.open', self.fake_open, create=True): # Both keys are missing. - yaml_fname = self._CreateYamlFile({'two': {}}, 'two', - self._OAUTH_INSTALLED_APP_DICT) - self.assertRaises( - googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromStorage, - yaml_fname, 'two', ['needed', 'keys'], []) + yaml_doc = self._CreateYamlDoc({ + 'two': {} + }, 'two', self._OAUTH_INSTALLED_APP_DICT) + self.assertRaises(googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromString, yaml_doc, 'two', + ['needed', 'keys'], []) # One key is missing. - yaml_fname = self._CreateYamlFile({'three': {'needed': 'd'}}, 'three', - self._OAUTH_INSTALLED_APP_DICT) - self.assertRaises( - googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromStorage, - yaml_fname, 'three', ['needed', 'keys'], []) - - def testLoadFromStorage(self): + yaml_doc = self._CreateYamlDoc({ + 'three': { + 'needed': 'd' + } + }, 'three', self._OAUTH_INSTALLED_APP_DICT) + self.assertRaises(googleads.errors.GoogleAdsValueError, + googleads.common.LoadFromString, yaml_doc, 'three', + ['needed', 'keys'], []) + + def testLoadFromString(self): # No optional keys present. - yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e'}}, - 'one', self._OAUTH_INSTALLED_APP_DICT) + yaml_doc = self._CreateYamlDoc({ + 'one': { + 'needed': 'd', + 'keys': 'e' + } + }, 'one', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'one', ['needed', 'keys'], ['other']) + rval = googleads.common.LoadFromString( + yaml_doc, 'one', ['needed', 'keys'], ['other']) proxy_config.assert_called_once_with( http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) @@ -343,15 +500,15 @@ def testLoadFromStorage(self): self.assertTrue(googleads.common._utility_registry._enabled) # The optional key is present. - yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e', - 'other': 'f'}}, 'one', - self._OAUTH_INSTALLED_APP_DICT) + yaml_doc = self._CreateYamlDoc({'one': {'needed': 'd', 'keys': 'e', + 'other': 'f'}}, 'one', + self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'one', ['needed', 'keys'], ['other']) + rval = googleads.common.LoadFromString( + yaml_doc, 'one', ['needed', 'keys'], ['other']) proxy_config.assert_called_once_with( http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) @@ -362,36 +519,10 @@ def testLoadFromStorage(self): 'proxy_config': proxy_config.return_value}, rval) self.assertTrue(googleads.common._utility_registry._enabled) - def testLoadFromStorage_relativePath(self): - fake_os = fake_filesystem.FakeOsModule(self.filesystem) - yaml_contents = {'one': {'needed': 'd', 'keys': 'e'}} - yaml_contents['one'].update(self._OAUTH_INSTALLED_APP_DICT) - self.filesystem.CreateFile('/home/test/yaml/googleads.yaml', - contents=yaml.dump(yaml_contents)) - fake_os.chdir('/home/test') - - with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: - with mock.patch('googleads.common.os', fake_os): - with mock.patch('googleads.common.open', self.fake_open, create=True): - with mock.patch('googleads.common.ProxyConfig') as proxy_config: - proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - 'yaml/googleads.yaml', 'one', ['needed', 'keys'], ['other']) - - proxy_config.assert_called_once_with( - http_proxy=None, https_proxy=None, cafile=None, - disable_certificate_validation=False) - mock_client.assert_called_once_with( - 'a', 'b', 'c', proxy_config=proxy_config.return_value) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'proxy_config': proxy_config.return_value, - 'needed': 'd', 'keys': 'e'}, rval) - self.assertTrue(googleads.common._utility_registry._enabled) - - def testLoadFromStorage_serviceAccount(self): + def testLoadFromString_serviceAccount(self): dfp_scope = googleads.oauth2.GetAPIScope('dfp') # No optional keys present. - yaml_fname = self._CreateYamlFile( + yaml_doc = self._CreateYamlDoc( {'dfp': {'needed': 'd', 'keys': 'e'}}, insert_oauth2_key='dfp', oauth_dict=self._OAUTH_SERVICE_ACCT_DICT) with mock.patch( @@ -399,8 +530,8 @@ def testLoadFromStorage_serviceAccount(self): with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'dfp', ['needed', 'keys'], ['other']) + rval = googleads.common.LoadFromString( + yaml_doc, 'dfp', ['needed', 'keys'], ['other']) proxy_config.assert_called_once_with( http_proxy=None, https_proxy=None, cafile=None, @@ -414,7 +545,7 @@ def testLoadFromStorage_serviceAccount(self): self.assertTrue(googleads.common._utility_registry._enabled) # The optional key is present. - yaml_fname = self._CreateYamlFile( + yaml_doc = self._CreateYamlDoc( {'dfp': {'needed': 'd', 'keys': 'e', 'other': 'f'}}, 'dfp', self._OAUTH_SERVICE_ACCT_DICT) with mock.patch( @@ -422,8 +553,8 @@ def testLoadFromStorage_serviceAccount(self): with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'dfp', ['needed', 'keys'], ['other']) + rval = googleads.common.LoadFromString( + yaml_doc, 'dfp', ['needed', 'keys'], ['other']) proxy_config.assert_called_once_with( http_proxy=None, https_proxy=None, cafile=None, @@ -437,8 +568,8 @@ def testLoadFromStorage_serviceAccount(self): self.assertTrue(googleads.common._utility_registry._enabled) - def testLoadFromStorage_utilityRegistryDisabled(self): - yaml_fname = self._CreateYamlFile( + def testLoadFromString_utilityRegistryDisabled(self): + yaml_doc = self._CreateYamlDoc( {'one': {'needed': 'd', 'keys': 'e'}, 'include_utilities_in_user_agent': False}, 'one', self._OAUTH_INSTALLED_APP_DICT) @@ -447,8 +578,8 @@ def testLoadFromStorage_utilityRegistryDisabled(self): with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'one', ['needed', 'keys'], ['other']) + rval = googleads.common.LoadFromString( + yaml_doc, 'one', ['needed', 'keys'], ['other']) proxy_config.assert_called_once_with( http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) @@ -460,8 +591,8 @@ def testLoadFromStorage_utilityRegistryDisabled(self): self.assertFalse(googleads.common._utility_registry._enabled) - def testLoadFromStorage_warningWithUnrecognizedKey(self): - yaml_fname = self._CreateYamlFile( + def testLoadFromString_warningWithUnrecognizedKey(self): + yaml_doc = self._CreateYamlDoc( {'kval': {'Im': 'here', 'whats': 'this?'}}, 'kval', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: @@ -469,8 +600,8 @@ def testLoadFromStorage_warningWithUnrecognizedKey(self): with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'kval', ['Im'], ['other']) + rval = googleads.common.LoadFromString( + yaml_doc, 'kval', ['Im'], ['other']) mock_client.assert_called_once_with( 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual( @@ -482,6 +613,7 @@ def testLoadFromStorage_warningWithUnrecognizedKey(self): self.assertTrue(googleads.common._utility_registry._enabled) self.assertEqual(len(captured_warnings), 1) + def testGenerateLibSig(self): my_name = 'Joseph' self.assertEqual( @@ -489,6 +621,7 @@ def testGenerateLibSig(self): googleads.common._PYTHON_VERSION), googleads.common.GenerateLibSig(my_name)) + def testGenerateLibSigWithUtilities(self): my_name = 'Mark' diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 9f3791b2..94f40793 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -156,6 +156,16 @@ def setUp(self): self.oauth2_client, self.application_name, self.network_code, proxy_config=self.proxy_config, cache=self.cache) + def testLoadFromString(self): + with mock.patch('googleads.common.LoadFromString') as mock_load: + mock_load.return_value = { + 'network_code': 'abcdEFghIjkLMOpqRs', + 'oauth2_client': True, + 'application_name': 'unit testing' + } + self.assertIsInstance(googleads.dfp.DfpClient.LoadFromString(''), + googleads.dfp.DfpClient) + def testLoadFromStorage(self): with mock.patch('googleads.common.LoadFromStorage') as mock_load: mock_load.return_value = { @@ -166,6 +176,8 @@ def testLoadFromStorage(self): self.assertIsInstance(googleads.dfp.DfpClient.LoadFromStorage(), googleads.dfp.DfpClient) + + def testInitializeWithDefaultApplicationName(self): self.application_name = 'INSERT_APPLICATION_NAME_HERE' self.assertRaises( From 6138ea796b54d83d8aa4853eab26aa428de86487 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 7 Dec 2016 17:34:24 -0500 Subject: [PATCH 055/180] Commiting latest changes. From 7f5753403e2d299824a07f917389ce1905b09d61 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 13 Jan 2017 14:20:09 -0500 Subject: [PATCH 056/180] 5.0.0 release, fixing various bugs and enable SOAP gzip compression. --- ChangeLog | 23 ++++ README.md | 25 ++++ .../{README => README.md} | 0 .../handlers/api_handler.py | 5 +- .../handle_policy_violation_error.py | 13 +- ...oad_criteria_report_as_stream_with_awql.py | 2 +- .../handle_policy_violation_error.py | 13 +- ...oad_criteria_report_as_stream_with_awql.py | 2 +- .../handle_policy_violation_error.py | 13 +- ...oad_criteria_report_as_stream_with_awql.py | 2 +- .../get_ad_unit_hierarchy.py | 2 +- .../network_service/make_test_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../network_service/make_test_network.py | 2 +- googleads.yaml | 33 +++-- googleads/adwords.py | 44 +++++-- googleads/common.py | 28 +++- googleads/dfp.py | 41 ++++-- googleads/util.py | 48 +++++++ tests/adwords_test.py | 120 +++++++++++++++--- tests/common_test.py | 50 +++++--- tests/dfp_test.py | 97 ++++++++++++-- tests/util_test.py | 106 +++++++++++++++- 23 files changed, 575 insertions(+), 98 deletions(-) rename examples/adwords/adwords_appengine_demo/{README => README.md} (100%) diff --git a/ChangeLog b/ChangeLog index 00f93722..879ec2cd 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,26 @@ +5.0.0 -- 1/13/17: +* BREAKING CHANGE: The underlying suds client now has cache enabled. By default, + suds uses FileCache which requires access to local file system and will break + users using Google App Engine. For more details on how to configure or disable + caching, see the README. +* The library will now automatically apply a monkey patch to the suds-jurko + dependency on initialization that will modify the suds.transport.http module. + The patch modifies HttpTransport's send method such that it can detect and + decompress a gzip encoded SOAP body. +* Added new "enable_compression" optional keyword argument for AdWordsClient and + DfpClient. If set True, the client will request gzip compression and + automatically decompress the SOAP body for you. For more details on this + feature, see: + https://developers.google.com/adwords/api/docs/guides/bestpractices?hl=en#use_compression +* Resolved issues: + Issue 77: https://github.com/googleads/googleads-python-lib/issues/77 + Issue 97: https://github.com/googleads/googleads-python-lib/issues/97 +* Resolved pull requests: + PR 79: https://github.com/googleads/googleads-python-lib/pull/79 + PR 81: https://github.com/googleads/googleads-python-lib/pull/81 + PR 91: https://github.com/googleads/googleads-python-lib/pull/91 + PR 99: https://github.com/googleads/googleads-python-lib/pull/99 + 4.8.0 -- 11/29/16: * Added support for DFP v201611. * Removed support for DFP v201508 and v201511. diff --git a/README.md b/README.md index df0fde24..1e36c492 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,31 @@ suds_client.set_options( suds_client.service.mutate([operation]) ``` +##How can I configure or disable caching for the suds client? + +By default, the suds clients are cached because reading and digesting the WSDL +can be expensive. However, the default caching method requires permission to +access a local file system that may not be available in certain hosting +environments such as App Engine. + +You can pass an implementation of `suds.cache.Cache` to the `AdWordsClient` or +`DfpClient` initializer to modify the default caching behavior. + +For example, configuring a different location and duration of the cache file: +```python +file_cache = suds.cache.FileCache(location=cache_path, days=2) +adwords_client = adwords.AdWordsClient( + developer_token, oauth2_client, user_agent, + client_customer_id=client_customer_id, cache=file_cache) +``` + +You can also disable caching in similar fashion: +```python +adwords_client = adwords.AdWordsClient( + developer_token, oauth2_client, user_agent, + client_customer_id=client_customer_id, cache=suds.cache.NoCache) +``` + ##Timeout Tips The requests sent by this library are sent via urllib, which is consequently where the timeout is set. If you set a system timeout elsewhere, the googleads diff --git a/examples/adwords/adwords_appengine_demo/README b/examples/adwords/adwords_appengine_demo/README.md similarity index 100% rename from examples/adwords/adwords_appengine_demo/README rename to examples/adwords/adwords_appengine_demo/README.md diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index a45c8bbb..c2e70b54 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -19,6 +19,8 @@ import time +from suds.cache import NoCache + from demo import VERSION from googleads.adwords import AdWordsClient from googleads.errors import GoogleAdsError @@ -45,7 +47,8 @@ def __init__(self, client_id, client_secret, refresh_token, credentials = GoogleRefreshTokenClient(client_id, client_secret, refresh_token) self.client = AdWordsClient(dev_token, credentials, self._USER_AGENT, - client_customer_id=manager_account_id) + client_customer_id=manager_account_id, + cache=NoCache) def AddAdGroup(self, client_customer_id, campaign_id, name, status): """Create a new ad group. diff --git a/examples/adwords/v201605/error_handling/handle_policy_violation_error.py b/examples/adwords/v201605/error_handling/handle_policy_violation_error.py index 89a81b53..c5658859 100755 --- a/examples/adwords/v201605/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201605/error_handling/handle_policy_violation_error.py @@ -70,7 +70,8 @@ def main(client, ad_group_id): operation_index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) if operation_index: - operation = operations[int(operation_index[0])] + index = int(operation_index[0]) + operation = operations[index] print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % (operation['operand']['ad']['headline'], 'exemptable' if error['isExemptable'] else 'non-exemptable', @@ -85,13 +86,15 @@ def main(client, ad_group_id): operation['exemptionRequests'].append({ 'key': error['key'] }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) + else: + # Set non-exemptable operation to None to mark for deletion + print 'Removing the operation from the request.' + operations[index] = None else: # Non-policy error returned, re-throw exception. raise e + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] # Add these ads. Disable "validate only" so the ads will get created. client.validate_only = False diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py index f51f53df..5f82c8c9 100755 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example downloads a criteria performance report as a string with AWQL. +"""This example downloads a criteria performance report as a stream with AWQL. To get report fields, run get_report_fields.py. diff --git a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py index 1119662c..45cf9ad7 100755 --- a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py @@ -70,7 +70,8 @@ def main(client, ad_group_id): operation_index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) if operation_index: - operation = operations[int(operation_index[0])] + index = int(operation_index[0]) + operation = operations[index] print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % (operation['operand']['ad']['headline'], 'exemptable' if error['isExemptable'] else 'non-exemptable', @@ -85,13 +86,15 @@ def main(client, ad_group_id): operation['exemptionRequests'].append({ 'key': error['key'] }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) + else: + # Set non-exemptable operation to None to mark for deletion + print 'Removing the operation from the request.' + operations[index] = None else: # Non-policy error returned, re-throw exception. raise e + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] # Add these ads. Disable "validate only" so the ads will get created. client.validate_only = False diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py index 7e305ab8..1de6ad8d 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example downloads a criteria performance report as a string with AWQL. +"""This example downloads a criteria performance report as a stream with AWQL. To get report fields, run get_report_fields.py. diff --git a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py index 6803cd0b..cf6cb5f1 100755 --- a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py @@ -70,7 +70,8 @@ def main(client, ad_group_id): operation_index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) if operation_index: - operation = operations[int(operation_index[0])] + index = int(operation_index[0]) + operation = operations[index] print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % (operation['operand']['ad']['headline'], 'exemptable' if error['isExemptable'] else 'non-exemptable', @@ -85,13 +86,15 @@ def main(client, ad_group_id): operation['exemptionRequests'].append({ 'key': error['key'] }) - else: - # Remove non-exemptable operation - print 'Removing the operation from the request.' - operations.delete(operation) + else: + # Set non-exemptable operation to None to mark for deletion + print 'Removing the operation from the request.' + operations[index] = None else: # Non-policy error returned, re-throw exception. raise e + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] # Add these ads. Disable "validate only" so the ads will get created. client.validate_only = False diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py index c67d71d7..135e6f31 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example downloads a criteria performance report as a string with AWQL. +"""This example downloads a criteria performance report as a stream with AWQL. To get report fields, run get_report_fields.py. diff --git a/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py index 8126467a..23c939ca 100755 --- a/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py @@ -52,7 +52,7 @@ def main(client): root_statement = dfp.FilterStatement(query) response = inventory_service.getAdUnitsByStatement( root_statement.ToStatement()) - root_ad_unit = response['results'] + root_ad_unit = response['results'][0] if root_ad_unit: BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units) diff --git a/examples/dfp/v201605/network_service/make_test_network.py b/examples/dfp/v201605/network_service/make_test_network.py index 45b995ab..c686f7c3 100755 --- a/examples/dfp/v201605/network_service/make_test_network.py +++ b/examples/dfp/v201605/network_service/make_test_network.py @@ -37,7 +37,7 @@ def main(client): network_service = client.GetService('NetworkService', version='v201605') # Create a test network. - network = network_service.MakeTestNetwork() + network = network_service.makeTestNetwork() # Display results. print ('Test network with network code \'%s\' and display name \'%s\' ' diff --git a/examples/dfp/v201608/network_service/make_test_network.py b/examples/dfp/v201608/network_service/make_test_network.py index 35e0577c..d1f4cebc 100755 --- a/examples/dfp/v201608/network_service/make_test_network.py +++ b/examples/dfp/v201608/network_service/make_test_network.py @@ -37,7 +37,7 @@ def main(client): network_service = client.GetService('NetworkService', version='v201608') # Create a test network. - network = network_service.MakeTestNetwork() + network = network_service.makeTestNetwork() # Display results. print ('Test network with network code \'%s\' and display name \'%s\' ' diff --git a/examples/dfp/v201611/network_service/make_test_network.py b/examples/dfp/v201611/network_service/make_test_network.py index 01325e37..94475a3d 100755 --- a/examples/dfp/v201611/network_service/make_test_network.py +++ b/examples/dfp/v201611/network_service/make_test_network.py @@ -37,7 +37,7 @@ def main(client): network_service = client.GetService('NetworkService', version='v201611') # Create a test network. - network = network_service.MakeTestNetwork() + network = network_service.makeTestNetwork() # Display results. print ('Test network with network code \'%s\' and display name \'%s\' ' diff --git a/googleads.yaml b/googleads.yaml index 7d4bdbb6..9e6294c7 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -12,7 +12,7 @@ adwords: # partial_failure: True # validate_only: True ############################################################################# - # OAuth2 Configuration # + # OAuth2 Configuration # # Below you may provide credentials for either the installed application or # # service account flows. Remove or comment the lines for the flow you're # # not using. # @@ -43,11 +43,13 @@ dfp: # Required Fields # ############################################################################# application_name: INSERT_APPLICATION_NAME_HERE - # The following values are required for all services except NetworkService, - # unless the network code is set directly on the DfpClient object: + ############################################################################# + # Optional Fields # + ############################################################################# + # The network_code is required for all services except NetworkService: # network_code: INSERT_NETWORK_CODE_HERE ############################################################################# - # OAuth2 Configuration # + # OAuth2 Configuration # # Below you may provide credentials for either the installed application or # # service account flows. Remove or comment the lines for the flow you're # # not using. # @@ -62,7 +64,18 @@ dfp: # path_to_private_key_file: INSERT_PATH_TO_FILE_HERE -# Proxy configurations (optional) +# Common configurations: +############################################################################### +# Compression (optional) # +# Below you may specify whether to accept and automatically decompress gzip # +# encoded SOAP requests. By default, gzip compression is not enabled. # +############################################################################### +# enable_compression: False +############################################################################### +# Proxy configurations (optional) # +# Below you may specify an HTTP or HTTPS Proxy to be used when making API # +# requests. # +############################################################################### # proxy_config: # If specified, the given cafile will only be used if certificate validation # is not disabled. @@ -80,8 +93,10 @@ dfp: # The following values are optional: # username: INSERT_USERNAME_HERE # password: INSERT_PASSWORD_HERE - - -# Optional: By default, the library will include utilities used in the user -# agent. +################################################################################ +# Utilities Included (optional) # +# Below you may specify whether the library will include utilities used in the # +# user agent. By default, the library will include utilities used in the user # +# agent. # +################################################################################ # include_utilities_in_user_agent: True diff --git a/googleads/adwords.py b/googleads/adwords.py index b2d4fbbc..44ae847b 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -23,7 +23,6 @@ import urllib2 from xml.etree import ElementTree - import suds.client import suds.mx.literal import suds.xsd.doctor @@ -221,7 +220,8 @@ class AdWordsClient(object): # AdWords. _OPTIONAL_INIT_VALUES = ( 'validate_only', 'partial_failure', 'client_customer_id', 'user_agent', - 'report_downloader_headers') + 'report_downloader_headers', + googleads.common.ENABLE_COMPRESSION_KEY) # The format of SOAP service WSDLs. A server, namespace, version, and service # name need to be formatted in. @@ -297,11 +297,15 @@ def __init__(self, developer_token, oauth2_client, succeed, to result in a complete failure with no changes made or a partial failure with some changes made. Only certain services respect this header. - cache: A subclass of suds.cache.Cache; defaults to None. + cache: A subclass of suds.cache.Cache. If not set, this will default to an + instance of suds.cache.FileCache. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. report_downloader_headers: A dict containing optional headers to be used by default when making requests with the ReportDownloader. + enable_compression: A boolean indicating if you want to enable compression + of the SOAP response. If True, the SOAP response will use gzip + compression, and will be decompressed for you automatically. Raises: GoogleAdsValueError: If the provided user_agent contains non-ASCII @@ -327,6 +331,12 @@ def __init__(self, developer_token, oauth2_client, self.proxy_config = (proxy_config if proxy_config else googleads.common.ProxyConfig()) self.report_download_headers = kwargs.get('report_download_headers', {}) + self.enable_compression = kwargs.get( + googleads.common.ENABLE_COMPRESSION_KEY, False) + + if self.enable_compression: + self.user_agent = '%s (gzip)' % self.user_agent + self.message_plugin = googleads.common.LoggingMessagePlugin() def GetService(self, service_name, version=None, server=None): @@ -367,15 +377,20 @@ def GetService(self, service_name, version=None, server=None): raise googleads.errors.GoogleAdsValueError( msg_fmt % ('version', version, _SERVICE_MAP.keys())) + kwargs = {'timeout': 3600, + 'transport': self.proxy_config.GetSudsProxyTransport(), + 'plugins': [self.message_plugin]} + + if self.cache: + kwargs['cache'] = self.cache + client = suds.client.Client( self._SOAP_SERVICE_FORMAT % (server, version_service_mapping, version, service_name), - cache=self.cache, timeout=3600, - transport=self.proxy_config.GetSudsProxyTransport(), - plugins=[self.message_plugin]) + **kwargs) return googleads.common.SudsServiceProxy( - client, _AdWordsHeaderHandler(self, version)) + client, _AdWordsHeaderHandler(self, version, self.enable_compression)) def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -446,7 +461,7 @@ class _AdWordsHeaderHandler(googleads.common.HeaderHandler): # The content type of report download requests _CONTENT_TYPE = 'application/x-www-form-urlencoded' - def __init__(self, adwords_client, version): + def __init__(self, adwords_client, version, enable_compression): """Initializes an AdWordsHeaderHandler. Args: @@ -455,9 +470,13 @@ def __init__(self, adwords_client, version): handler picks up changes to the client. version: A string identifying which version of AdWords this header handler will be used for. + enable_compression: A boolean indicating if you want to enable compression + of the SOAP response. If True, the SOAP response will use gzip + compression, and will be decompressed for you automatically. """ self._adwords_client = adwords_client self._version = version + self.enable_compression = enable_compression def SetHeaders(self, suds_client): """Sets the SOAP and HTTP headers on the given suds client. @@ -472,9 +491,13 @@ def SetHeaders(self, suds_client): header.validateOnly = self._adwords_client.validate_only header.partialFailure = self._adwords_client.partial_failure + http_headers = self._adwords_client.oauth2_client.CreateHttpHeader() + if self.enable_compression: + http_headers['accept-encoding'] = 'gzip' + suds_client.set_options( soapheaders=header, - headers=self._adwords_client.oauth2_client.CreateHttpHeader()) + headers=http_headers) def GetReportDownloadHeaders(self, **kwargs): """Returns a dictionary of headers for a report download request. @@ -1132,7 +1155,8 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], self._adwords_client = adwords_client self._namespace = self._NAMESPACE_FORMAT % version self._end_point = self._END_POINT_FORMAT % (server, version) - self._header_handler = _AdWordsHeaderHandler(adwords_client, version) + self._header_handler = _AdWordsHeaderHandler( + adwords_client, version, self._adwords_client.enable_compression) self.proxy_config = self._adwords_client.proxy_config self.url_opener = urllib2.build_opener(*self.proxy_config.GetHandlers()) diff --git a/googleads/common.py b/googleads/common.py index 210f6c69..af0bbf62 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -25,6 +25,7 @@ import urllib2 import warnings + import httplib2 import socks import suds @@ -59,7 +60,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '4.8.0' +VERSION = '5.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' @@ -78,6 +79,10 @@ # instance. _PROXY_KEYS = ('host', 'port') +# A key used to configure the client to accept and automatically decompress +# gzip encoded SOAP responses. +ENABLE_COMPRESSION_KEY = 'enable_compression' + # Global variables used to enable and store utility usage stats. _utility_registry = googleads.util.UtilityRegistry() _UTILITY_REGISTER_YAML_KEY = 'include_utilities_in_user_agent' @@ -176,6 +181,9 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, client_kwargs['oauth2_client'] = _ExtractOAuth2Client( product_yaml_key, product_data, proxy_config) + client_kwargs[ENABLE_COMPRESSION_KEY] = data.get( + ENABLE_COMPRESSION_KEY, False) + for value in optional_product_values: if value in product_data: client_kwargs[value] = product_data[value] @@ -688,12 +696,24 @@ def MakeSoapRequest(*args): """Perform a SOAP call.""" self._header_handler.SetHeaders(self.suds_client) try: - return soap_service_method(*[_PackForSuds(arg, self.suds_client.factory) - for arg in args]) + return soap_service_method( + *[_PackForSuds(arg, self.suds_client.factory) for arg in args]) except suds.WebFault as e: _logger.error('Server raised fault in response.') _logger.info('Failure response:\n%s', e.document) - raise e + + # Before re-throwing the WebFault exception, an error object needs to be + # wrapped in a list for safe iteration. + fault = e.fault.detail.ApiExceptionFault + if not hasattr(fault, 'errors') or fault.errors is None: + e.fault.detail.ApiExceptionFault.errors = [] + raise + + obj = fault.errors + if not isinstance(obj, list): + fault.errors = [obj] + + raise return MakeSoapRequest diff --git a/googleads/dfp.py b/googleads/dfp.py index b4c70653..9a08d8ad 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -148,7 +148,8 @@ class DfpClient(object): _REQUIRED_INIT_VALUES = ('application_name',) # A list of values which may optionally be provided when using DFP. _OPTIONAL_INIT_VALUES = ( - 'network_code', 'https_proxy') + 'network_code', 'https_proxy', + googleads.common.ENABLE_COMPRESSION_KEY) # The format of SOAP service WSDLs. A server, version, and service name need # to be formatted in. _SOAP_SERVICE_FORMAT = '%s/apis/ads/publisher/%s/%s?wsdl' @@ -196,7 +197,8 @@ def LoadFromStorage(cls, path=None): cls._OPTIONAL_INIT_VALUES)) def __init__(self, oauth2_client, application_name, network_code=None, - cache=None, proxy_config=None): + cache=None, proxy_config=None, + enable_compression=False): """Initializes a DfpClient. For more information on these arguments, see our SOAP headers guide: @@ -211,9 +213,13 @@ def __init__(self, oauth2_client, application_name, network_code=None, network_code: A string identifying the network code of the network you are accessing. All requests other than getAllNetworks and getCurrentUser calls require this header to be set. - cache: A subclass of suds.cache.Cache; defaults to None. + cache: A subclass of suds.cache.Cache. If not set, this will default to an + instance of suds.cache.FileCache. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. + enable_compression: A boolean indicating if you want to enable compression + of the SOAP response. If True, the SOAP response will use gzip + compression, and will be decompressed for you automatically. """ if not application_name or (DEFAULT_APPLICATION_NAME in application_name): raise googleads.errors.GoogleAdsValueError( @@ -224,10 +230,14 @@ def __init__(self, oauth2_client, application_name, network_code=None, self.application_name = application_name self.network_code = network_code self.cache = cache - self._header_handler = _DfpHeaderHandler(self) + self._header_handler = _DfpHeaderHandler(self, enable_compression) self.proxy_config = (proxy_config if proxy_config else googleads.common.ProxyConfig()) + if enable_compression: + self.application_name = '%s (gzip)' % self.application_name + + def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server=None): """Creates a service client for the given service. @@ -252,11 +262,18 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server = DEFAULT_ENDPOINT server = server[:-1] if server[-1] == '/' else server + + kwargs = {'timeout': 3600, + 'transport': self.proxy_config.GetSudsProxyTransport()} + + if self.cache: + kwargs['cache'] = self.cache + try: client = suds.client.Client( self._SOAP_SERVICE_FORMAT % (server, version, service_name), - cache=self.cache, timeout=3600, - transport=self.proxy_config.GetSudsProxyTransport()) + **kwargs) + except suds.transport.TransportError: if version in _SERVICE_MAP: if service_name in _SERVICE_MAP[version]: @@ -304,15 +321,19 @@ class _DfpHeaderHandler(googleads.common.HeaderHandler): # The name of the WSDL-defined SOAP Header class used in all requests. _SOAP_HEADER_CLASS = 'SoapRequestHeader' - def __init__(self, dfp_client): + def __init__(self, dfp_client, enable_compression): """Initializes a DfpHeaderHandler. Args: dfp_client: The DfpClient whose data will be used to fill in the headers. We retain a reference to this object so that the header handler picks up changes to the client. + enable_compression: A boolean indicating if you want to enable compression + of the SOAP response. If True, the SOAP response will use gzip + compression, and will be decompressed for you automatically. """ self._dfp_client = dfp_client + self.enable_compression = enable_compression def SetHeaders(self, suds_client): """Sets the SOAP and HTTP headers on the given suds client.""" @@ -321,9 +342,13 @@ def SetHeaders(self, suds_client): header.applicationName = ''.join([self._dfp_client.application_name, self._LIB_SIG]) + http_headers = self._dfp_client.oauth2_client.CreateHttpHeader() + if self.enable_compression: + http_headers['accept-encoding'] = 'gzip' + suds_client.set_options( soapheaders=header, - headers=self._dfp_client.oauth2_client.CreateHttpHeader()) + headers=http_headers) class FilterStatement(object): diff --git a/googleads/util.py b/googleads/util.py index 125e942b..b6e97d2f 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -14,9 +14,14 @@ """Utilities used by the client library.""" +import gzip +import io import logging import re +import sys import threading +import urllib2 + import suds @@ -54,6 +59,7 @@ class PatchHelper(object): def Apply(self): """Apply patches used by the Google Ads Client Library.""" self._ApplySudsJurkoAppenderPatch() + self._ApplySudsJurkoSendPatch() def _ApplySudsJurkoAppenderPatch(self): """Appends a Monkey Patch to the suds.mx.appender module. @@ -72,6 +78,48 @@ def PatchedAppend(self, parent, content): suds.mx.appender.ObjectAppender.append = PatchedAppend + def _ApplySudsJurkoSendPatch(self): + """Appends a Monkey Patch to the suds.transport.http module. + + This allows the suds library to decompress the SOAP body when compression is + enabled. For more details on SOAP Compression, see: + https://developers.google.com/adwords/api/docs/guides/bestpractices?hl=en#use_compression + """ + def PatchedHttpTransportSend(self, request): + """Patch for HttpTransport.send to enable gzip compression.""" + msg = request.message + url = request.url + headers = request.headers + u2request = urllib2.Request(url, msg, headers) + self.addcookies(u2request) + self.proxy = self.options.proxy + request.headers.update(u2request.headers) + suds.transport.http.log.debug('sending:\n%s', request) + fp = self.u2open(u2request) + self.getcookies(fp, u2request) + headers = (fp.headers.dict if sys.version_info < (3, 0) else fp.headers) + + try: + result = suds.transport.Reply(200, headers, fp.read()) + except urllib2.HTTPError, e: + if e.code in (202, 204): + result = None + else: + raise suds.transport.TransportError(e.msg, e.code, e.fp) + + if result.headers.get('content-encoding') == 'gzip': + # If gzip encoding is used, decompress here. + stream = io.BytesIO() + stream.write(result.message) + stream.flush() + stream.seek(0) + result.message = gzip.GzipFile(fileobj=stream, mode='rb').read() + + suds.transport.http.log.debug('received:\n%s', result) + return result + + suds.transport.http.HttpTransport.send = PatchedHttpTransportSend + class _AbstractDevTokenSOAPFilter(logging.Filter): """Interface for sanitizing logs containing SOAP request/response data.""" diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 7226d343..6ab042b5 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -31,6 +31,7 @@ import googleads.common import googleads.errors import mock +import suds PYTHON2 = sys.version_info[0] == 2 @@ -77,6 +78,7 @@ def GetAdWordsClient(**kwargs): client = googleads.adwords.AdWordsClient( dev_token, oauth2_client, user_agent, client_customer_id=client_customer_id, + cache=kwargs.get('cache'), proxy_config=kwargs.get('proxy_config'), validate_only=validate_only, partial_failure=partial_failure, report_downloader_headers=report_downloader_headers) @@ -132,13 +134,14 @@ def setUp(self): self.user_agent = 'user agent!' self.validate_only = True self.partial_failure = False + self.enable_compression = False self.aw_client = GetAdWordsClient( ccid=self.ccid, dev_token=self.dev_token, user_agent=self.user_agent, oauth2_client=self.oauth2_client, validate_only=self.validate_only, partial_failure=self.partial_failure, report_downloader_headers=self.report_downloader_headers) self.header_handler = googleads.adwords._AdWordsHeaderHandler( - self.aw_client, CURRENT_VERSION) + self.aw_client, CURRENT_VERSION, self.enable_compression) def testSetHeaders(self): suds_client = mock.Mock() @@ -258,12 +261,13 @@ def setUp(self): self.https_proxy_port = 443 self.proxy_config = GetProxyConfig(https_host=self.https_proxy_host, https_port=self.https_proxy_port) - self.cache = None + self.file_cache = suds.cache.FileCache + self.no_cache = suds.cache.NoCache self.adwords_client = GetAdWordsClient() self.aw_client = GetAdWordsClient( proxy_config=self.proxy_config) self.header_handler = googleads.adwords._AdWordsHeaderHandler( - self.adwords_client, CURRENT_VERSION) + self.adwords_client, CURRENT_VERSION, False) def testLoadFromStorage(self): @@ -272,6 +276,23 @@ def testLoadFromStorage(self): path=self.load_from_storage_path), googleads.adwords.AdWordsClient) + def testLoadFromStorageWithCompressionEnabled(self): + enable_compression = True + user_agent_gzip_template = '%s (gzip)' + default_user_agent = 'unit testing' + + with mock.patch('googleads.common.LoadFromStorage') as mock_load: + mock_load.return_value = { + 'developer_token': 'abcdEFghIjkLMOpqRs', + 'oauth2_client': mock.Mock(), + 'user_agent': default_user_agent, + 'enable_compression': enable_compression + } + client = googleads.adwords.AdWordsClient.LoadFromStorage() + self.assertEqual(enable_compression, client.enable_compression) + self.assertEqual(user_agent_gzip_template % default_user_agent, + client.user_agent) + def testLoadFromStorageWithNonASCIIUserAgent(self): with mock.patch('googleads.common.LoadFromStorage') as mock_load: mock_load.return_value = { @@ -311,25 +332,79 @@ def testGetService_success(self): mock_client.assert_called_once_with( 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, CURRENT_VERSION, service), cache=self.cache, + % (namespace, CURRENT_VERSION, service), transport=mock_transport.return_value, timeout=3600, plugins=[mock_plugin.return_value]) self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + def testGetService_successWithFileCache(self): + service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] + # Use a custom server. Also test what happens if the server ends with a + # trailing slash + server = 'https://testing.test.com/' + + with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: + with mock.patch('suds.client.Client') as mock_client: + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' + ) as mock_transport: + mock_plugin.return_value = mock.Mock() + mock_transport.return_value = mock.Mock() + client = GetAdWordsClient(cache=self.file_cache) + suds_service = client.GetService( + service, CURRENT_VERSION, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' + % (namespace, CURRENT_VERSION, service), + transport=mock_transport.return_value, timeout=3600, + cache=self.file_cache, plugins=[mock_plugin.return_value]) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + + def testGetService_successWithNoCache(self): + service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] + # Use a custom server. Also test what happens if the server ends with a + # trailing slash + server = 'https://testing.test.com/' + + with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: + with mock.patch('suds.client.Client') as mock_client: + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' + ) as mock_transport: + mock_plugin.return_value = mock.Mock() + mock_transport.return_value = mock.Mock() + client = GetAdWordsClient(cache=self.no_cache) + suds_service = client.GetService( + service, CURRENT_VERSION, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' + % (namespace, CURRENT_VERSION, service), + transport=mock_transport.return_value, timeout=3600, + cache=self.no_cache, plugins=[mock_plugin.return_value]) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + + def testGetService_successWithoutProxy(self): + service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] + # Use the default server without a proxy. - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' - ) as mock_transport: - mock_transport.return_value = mock.Mock() - suds_service = client.GetService(service, CURRENT_VERSION) - - mock_client.assert_called_once_with( - 'https://adwords.google.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, CURRENT_VERSION, service), cache=self.cache, - transport=mock_transport.return_value, timeout=3600, - plugins=[mock_plugin.return_value]) - self.assertFalse(mock_client.return_value.set_options.called) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: + with mock.patch('suds.client.Client') as mock_client: + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' + ) as mock_transport: + mock_transport.return_value = mock.Mock() + client = GetAdWordsClient() + suds_service = client.GetService(service, CURRENT_VERSION) + + mock_client.assert_called_once_with( + 'https://adwords.google.com/api/adwords/%s/%s/%s?wsdl' + % (namespace, CURRENT_VERSION, service), + transport=mock_transport.return_value, timeout=3600, + plugins=[mock_plugin.return_value]) + self.assertFalse(mock_client.return_value.set_options.called) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_badService(self): version = CURRENT_VERSION @@ -343,6 +418,17 @@ def testGetService_badVersion(self): googleads.errors.GoogleAdsValueError, self.adwords_client.GetService, 'CampaignService', '11111') + def testGetService_compressionEnabled(self): + service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + client = GetAdWordsClient() + client.enable_compression = True + + with mock.patch('suds.client.Client'): + with mock.patch('googleads.adwords._AdWordsHeaderHandler') as mock_h: + client.GetService(service, CURRENT_VERSION) + mock_h.assert_called_once_with(client, CURRENT_VERSION, + client.enable_compression) + def testGetBatchJobHelper(self): with mock.patch('googleads.adwords.BatchJobHelper') as mock_helper: self.assertEqual( diff --git a/tests/common_test.py b/tests/common_test.py index 2b89f54e..2ccd66d3 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -126,7 +126,9 @@ def testLoadFromStorage(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, + rval) self.assertTrue(googleads.common._utility_registry._enabled) # The optional key is present. @@ -146,7 +148,9 @@ def testLoadFromStorage(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'other': 'f', - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, + rval) self.assertTrue(googleads.common._utility_registry._enabled) def testLoadFromStorage_relativePath(self): @@ -172,7 +176,8 @@ def testLoadFromStorage_relativePath(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - 'needed': 'd', 'keys': 'e'}, rval) + 'needed': 'd', 'keys': 'e', + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) self.assertTrue(googleads.common._utility_registry._enabled) def _CreateYamlDoc(self, data, insert_oauth2_key=None, oauth_dict=None): @@ -300,7 +305,8 @@ def testLoadFromString_passesWithNoRequiredKeys(self): mock_client.assert_called_once_with( 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): yaml_doc = self._CreateYamlDoc( @@ -328,7 +334,8 @@ def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): mock_client.assert_called_once_with( 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) def testLoadFromString_passesWithHTTPProxy(self): yaml_doc = self._CreateYamlDoc( @@ -353,7 +360,8 @@ def testLoadFromString_passesWithHTTPProxy(self): mock_client.assert_called_once_with( 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) def testLoadFromString_passesWithHTTPProxyLogin(self): yaml_doc = self._CreateYamlDoc( @@ -381,7 +389,8 @@ def testLoadFromString_passesWithHTTPProxyLogin(self): mock_client.assert_called_once_with( 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) def testLoadFromString_passesWithHTTPSProxy(self): yaml_doc = self._CreateYamlDoc( @@ -407,7 +416,8 @@ def testLoadFromString_passesWithHTTPSProxy(self): mock_client.assert_called_once_with( 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) def testLoadFromString_passesWithHTTPSProxyLogin(self): yaml_doc = self._CreateYamlDoc( @@ -436,7 +446,8 @@ def testLoadFromString_passesWithHTTPSProxyLogin(self): mock_client.assert_called_once_with( 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) def testLoadFromString_failsWithMisconfiguredProxy(self): yaml_doc = self._CreateYamlDoc( @@ -496,7 +507,9 @@ def testLoadFromString(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, + rval) self.assertTrue(googleads.common._utility_registry._enabled) # The optional key is present. @@ -516,7 +529,9 @@ def testLoadFromString(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'other': 'f', - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, + rval) self.assertTrue(googleads.common._utility_registry._enabled) def testLoadFromString_serviceAccount(self): @@ -541,7 +556,8 @@ def testLoadFromString_serviceAccount(self): proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - 'needed': 'd', 'keys': 'e'}, rval) + 'needed': 'd', 'keys': 'e', + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) self.assertTrue(googleads.common._utility_registry._enabled) # The optional key is present. @@ -564,7 +580,8 @@ def testLoadFromString_serviceAccount(self): proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - 'needed': 'd', 'keys': 'e', 'other': 'f'}, rval) + 'needed': 'd', 'keys': 'e', 'other': 'f', + googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) self.assertTrue(googleads.common._utility_registry._enabled) @@ -587,7 +604,9 @@ def testLoadFromString_utilityRegistryDisabled(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', - 'proxy_config': proxy_config.return_value}, rval) + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, + rval) self.assertFalse(googleads.common._utility_registry._enabled) @@ -608,7 +627,8 @@ def testLoadFromString_warningWithUnrecognizedKey(self): { 'oauth2_client': mock_client.return_value, 'Im': 'here', - 'proxy_config': proxy_config.return_value + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False }, rval) self.assertTrue(googleads.common._utility_registry._enabled) self.assertEqual(len(captured_warnings), 1) diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 94f40793..9cd49d68 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -109,7 +109,9 @@ class DfpHeaderHandlerTest(unittest.TestCase): def setUp(self): self.dfp_client = mock.Mock() - self.header_handler = googleads.dfp._DfpHeaderHandler(self.dfp_client) + self.enable_compression = False + self.header_handler = googleads.dfp._DfpHeaderHandler( + self.dfp_client, self.enable_compression) def testSetHeaders(self): suds_client = mock.Mock() @@ -152,9 +154,17 @@ def setUp(self): https_proxy=self.https_proxy) self.cache = None self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1] - self.dfp_client = googleads.dfp.DfpClient( + + def CreateDfpClient(self, **kwargs): + if 'proxy_config' not in kwargs: + kwargs['proxy_config'] = self.proxy_config + + if 'cache' not in kwargs: + kwargs['cache'] = self.cache + + return googleads.dfp.DfpClient( self.oauth2_client, self.application_name, self.network_code, - proxy_config=self.proxy_config, cache=self.cache) + **kwargs) def testLoadFromString(self): with mock.patch('googleads.common.LoadFromString') as mock_load: @@ -176,6 +186,25 @@ def testLoadFromStorage(self): self.assertIsInstance(googleads.dfp.DfpClient.LoadFromStorage(), googleads.dfp.DfpClient) + def testLoadFromStorageWithCompressionEnabled(self): + enable_compression = True + application_name_gzip_template = '%s (gzip)' + default_app_name = 'unit testing' + + with mock.patch('googleads.common.LoadFromStorage') as mock_load: + with mock.patch('googleads.dfp._DfpHeaderHandler') as mock_h: + mock_load.return_value = { + 'network_code': 'abcdEFghIjkLMOpqRs', + 'oauth2_client': True, + 'application_name': default_app_name, + 'enable_compression': enable_compression + } + dfp_client = googleads.dfp.DfpClient.LoadFromStorage() + self.assertEqual( + application_name_gzip_template % default_app_name, + dfp_client.application_name) + mock_h.assert_called_once_with(dfp_client, enable_compression) + def testInitializeWithDefaultApplicationName(self): @@ -194,6 +223,7 @@ def testInitializeWithUselessApplicationName(self): def testGetService_success(self): service = googleads.dfp._SERVICE_MAP[self.version][0] + dfp_client = self.CreateDfpClient() # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -202,49 +232,94 @@ def testGetService_success(self): with mock.patch('googleads.common.' 'ProxyConfig._SudsProxyTransport') as mock_transport: mock_transport.return_value = mock.Mock() - suds_service = self.dfp_client.GetService(service, self.version, server) + suds_service = dfp_client.GetService(service, self.version, server) mock_client.assert_called_once_with( 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), cache=self.cache, timeout=3600, + % (self.version, service), timeout=3600, transport=mock_transport.return_value) self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + def testGetService_successWithFileCache(self): + service = googleads.dfp._SERVICE_MAP[self.version][0] + dfp_client = self.CreateDfpClient(cache=suds.cache.FileCache) + + # Use a custom server. Also test what happens if the server ends with a + # trailing slash + server = 'https://testing.test.com/' + with mock.patch('suds.client.Client') as mock_client: + with mock.patch('googleads.common.' + 'ProxyConfig._SudsProxyTransport') as mock_transport: + mock_transport.return_value = mock.Mock() + suds_service = dfp_client.GetService(service, self.version, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service), timeout=3600, + cache=suds.cache.FileCache, transport=mock_transport.return_value) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + + def testGetService_successWithNoCache(self): + service = googleads.dfp._SERVICE_MAP[self.version][0] + dfp_client = self.CreateDfpClient(cache=suds.cache.NoCache) + + # Use a custom server. Also test what happens if the server ends with a + # trailing slash + server = 'https://testing.test.com/' + with mock.patch('suds.client.Client') as mock_client: + with mock.patch('googleads.common.' + 'ProxyConfig._SudsProxyTransport') as mock_transport: + mock_transport.return_value = mock.Mock() + suds_service = dfp_client.GetService(service, self.version, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service), timeout=3600, + cache=suds.cache.NoCache, transport=mock_transport.return_value) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + + def testGetService_successWithoutProxy(self): + service = googleads.dfp._SERVICE_MAP[self.version][0] + dfp_client = self.CreateDfpClient() + # Use the default server without a proxy. - self.dfp_client.proxy_option = None + dfp_client.proxy_option = None with mock.patch('suds.client.Client') as mock_client: with mock.patch('googleads.common.' 'ProxyConfig._SudsProxyTransport') as mock_transport: mock_transport.return_value = mock.Mock() - suds_service = self.dfp_client.GetService(service, self.version) + suds_service = dfp_client.GetService(service, self.version) mock_client.assert_called_once_with( 'https://ads.google.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), cache=self.cache, timeout=3600, + % (self.version, service), timeout=3600, transport=mock_transport.return_value) self.assertFalse(mock_client.return_value.set_options.called) self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_badService(self): + dfp_client = self.CreateDfpClient() with mock.patch('suds.client.Client') as mock_client: mock_client.side_effect = suds.transport.TransportError('', '') self.assertRaises( - googleads.errors.GoogleAdsValueError, self.dfp_client.GetService, + googleads.errors.GoogleAdsValueError, dfp_client.GetService, 'GYIVyievfyiovslf', self.version) def testGetService_badVersion(self): + dfp_client = self.CreateDfpClient() with mock.patch('suds.client.Client') as mock_client: mock_client.side_effect = suds.transport.TransportError('', '') self.assertRaises( - googleads.errors.GoogleAdsValueError, self.dfp_client.GetService, + googleads.errors.GoogleAdsValueError, dfp_client.GetService, 'CampaignService', '11111') def testGetService_transportError(self): service = googleads.dfp._SERVICE_MAP[self.version][0] + dfp_client = self.CreateDfpClient() with mock.patch('suds.client.Client') as mock_client: mock_client.side_effect = suds.transport.TransportError('', '') self.assertRaises(suds.transport.TransportError, - self.dfp_client.GetService, service, self.version) + dfp_client.GetService, service, self.version) class DataDownloaderTest(unittest.TestCase): diff --git a/tests/util_test.py b/tests/util_test.py index 2efd9831..e08fafa8 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -21,7 +21,6 @@ from xml.etree import ElementTree - import googleads.adwords import googleads.dfp import googleads.util @@ -44,6 +43,11 @@ def setUp(self): self.adwords_client = googleads.adwords.AdWordsClient( dev_token, oauth2_client, user_agent, client_customer_id=client_customer_id) + # AdWordsClient setup (compression enabled) + self.adwords_client_with_compression = googleads.adwords.AdWordsClient( + dev_token, oauth2_client, user_agent, + client_customer_id=client_customer_id, + enable_compression=True) # DfpClient setup network_code = '12345' @@ -137,6 +141,106 @@ def testPatchedSudsJurkoAppenderIssue78(self): # Assert that the request includes the empty trackingUrlTemplate. self.assertTrue(tracking_url_template is not None) + def testSudsJurkoSendWithCompression(self): + """Verifies that the patched HttpTransport.send can decode gzip response.""" + test_dir = os.path.dirname(__file__) + cs = self.adwords_client_with_compression.GetService('CampaignService') + + with mock.patch('suds.transport.http.HttpTransport.u2open'): + with mock.patch('suds.transport.Reply') as mock_reply: + with open(os.path.join( + test_dir, 'test_data/gzip_response.bin'), 'rb') as handler: + # Use a fake reply containing a gzipped SOAP response. + reply_instance = mock.Mock() + reply_instance.code = 200 + reply_instance.headers = {'content-encoding': 'gzip'} + reply_instance.message = handler.read() + mock_reply.return_value = reply_instance + # The send method would ordinarily fail to decompress the gzip SOAP + # message without the patch, resulting in an exception being raised. + cs.get() + + def testSingleErrorListIssue90(self): + """Verifies that issue 90 has been resolved with the patch.""" + query = 'WHERE 1 = 0' + statement = googleads.dfp.FilterStatement(query) + line_item_service = self.dfp_client.GetService('LineItemService') + line_item_action = {'xsi_type': 'ActivateLineItems'} + st = statement.ToStatement() + + test_dir = os.path.dirname(__file__) + + with mock.patch('suds.transport.http.HttpTransport.send') as mock_send: + with open(os.path.join( + test_dir, 'test_data/fault_response_envelope.txt'), 'rb' + ) as handler: + # Use a fake reply containing a fault SOAP response. + reply_instance = mock.Mock() + reply_instance.code = 500 + reply_instance.headers = {} + reply_instance.message = handler.read() + mock_send.return_value = reply_instance + try: + line_item_service.performLineItemAction(line_item_action, st) + except suds.WebFault, e: + errors = e.fault.detail.ApiExceptionFault.errors + self.assertIsInstance(errors, list) + self.assertEqual(1, len(errors)) + + def testSingleErrorListIssue90_emptyErrors(self): + """Verifies that issue 90 has been resolved with the patch.""" + query = 'WHERE 1 = 0' + statement = googleads.dfp.FilterStatement(query) + line_item_service = self.dfp_client.GetService('LineItemService') + line_item_action = {'xsi_type': 'ActivateLineItems'} + st = statement.ToStatement() + + test_dir = os.path.dirname(__file__) + + with mock.patch('suds.transport.http.HttpTransport.send') as mock_send: + with open(os.path.join( + test_dir, 'test_data/empty_fault_response_envelope.txt'), 'rb' + ) as handler: + # Use a fake reply containing a fault SOAP response. + reply_instance = mock.Mock() + reply_instance.code = 500 + reply_instance.headers = {} + reply_instance.message = handler.read() + mock_send.return_value = reply_instance + try: + line_item_service.performLineItemAction(line_item_action, st) + except suds.WebFault, e: + errors = e.fault.detail.ApiExceptionFault.errors + self.assertIsInstance(errors, list) + self.assertEqual(0, len(errors)) + + def testSingleErrorListIssue90_multipleErrors(self): + """Verifies that issue 90 has been resolved with the patch.""" + query = 'WHERE 1 = 0' + statement = googleads.dfp.FilterStatement(query) + line_item_service = self.dfp_client.GetService('LineItemService') + line_item_action = {'xsi_type': 'ActivateLineItems'} + st = statement.ToStatement() + + test_dir = os.path.dirname(__file__) + + with mock.patch('suds.transport.http.HttpTransport.send') as mock_send: + with open(os.path.join( + test_dir, 'test_data/multi_errors_fault_response_envelope.txt'), 'rb' + ) as handler: + # Use a fake reply containing a fault SOAP response. + reply_instance = mock.Mock() + reply_instance.code = 500 + reply_instance.headers = {} + reply_instance.message = handler.read() + mock_send.return_value = reply_instance + try: + line_item_service.performLineItemAction(line_item_action, st) + except suds.WebFault, e: + errors = e.fault.detail.ApiExceptionFault.errors + self.assertIsInstance(errors, list) + self.assertEqual(2, len(errors)) + class GoogleAdsCommonFilterTest(unittest.TestCase): """Tests for the GoogleAdsCommonFilter utility.""" From 02a80dec72e78886f5eb0bc6db9278d9b5ab85c3 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 13 Jan 2017 14:23:58 -0500 Subject: [PATCH 057/180] Commiting latest changes. From 99b99eede64c2f5a04677579f2626bb3462f7f71 Mon Sep 17 00:00:00 2001 From: Thang Duong Date: Tue, 14 Feb 2017 14:54:25 -0500 Subject: [PATCH 058/180] 5.1.0 release, v201702 support for DFP --- ChangeLog | 10 + README.md | 2 +- .../get_active_activity_groups.py | 69 ------ .../activity_service/get_active_activities.py | 66 ------ .../company_service/get_advertisers.py | 66 ------ .../contact_service/get_uninvited_contacts.py | 65 ------ ...et_all_content_metadata_key_hierarchies.py | 63 ------ .../content_service/get_all_content.py | 59 ----- .../get_creatives_by_statement.py | 69 ------ .../get_creative_templates_by_statement.py | 67 ------ .../get_active_creative_wrappers.py | 67 ------ ...et_all_custom_targeting_keys_and_values.py | 88 -------- ...et_custom_targeting_values_by_statement.py | 65 ------ .../get_ad_unit_hierarchy.py | 115 ---------- .../get_all_ad_unit_sizes.py | 54 ----- .../inventory_service/get_all_ad_units.py | 56 ----- .../get_top_level_ad_units.py | 69 ------ .../get_line_items_by_statement.py | 75 ------- .../get_recently_updated_line_items.py | 74 ------ .../order_service/get_orders_by_statement.py | 61 ----- .../get_geo_targets.py | 63 ------ .../team_service/get_teams_by_statement.py | 67 ------ .../v201605/user_service/get_current_user.py | 38 ---- .../user_service/get_users_by_statement.py | 57 ----- .../create_creative_from_template.py | 18 +- .../create_creative_from_template.py | 18 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 58 +++++ .../get_all_activity_groups.py | 29 +-- .../update_activity_groups.py | 2 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../get_active_activities.py} | 45 ++-- .../activity_service/get_all_activities.py | 50 +++++ .../activity_service/update_activities.py | 2 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 7 +- .../get_all_audience_segments.py | 25 +-- .../get_first_party_audience_segments.py | 43 ++-- .../populate_first_party_audience_segments.py | 9 +- .../update_audience_segments.py | 4 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 32 +-- .../get_base_rates_for_rate_card.py} | 50 ++--- .../base_rate_service/update_base_rates.py | 2 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py} | 44 ++-- .../company_service/get_all_companies.py | 49 ++++ .../company_service/update_companies.py | 2 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 49 ++++ .../get_uninvited_contacts.py} | 44 ++-- .../contact_service/update_contacts.py | 2 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 55 +++++ ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 49 ++++ .../creative_service/__init__.py | 0 .../create_creative_from_template.py | 20 +- .../creative_service/create_creatives.py | 4 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 49 ++++ .../creative_service/get_image_creatives.py} | 45 ++-- .../creative_service/update_creatives.py | 2 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 5 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 30 +-- .../get_creative_sets_for_master_creative.py} | 48 ++-- .../update_creative_set.py | 2 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 30 +-- .../get_system_defined_creative_templates.py} | 43 ++-- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py} | 43 ++-- .../get_all_creative_wrappers.py | 51 +++++ .../update_creative_wrappers.py | 2 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 26 +-- .../get_custom_fields_for_line_items.py} | 45 ++-- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 2 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 5 +- ...et_all_custom_targeting_keys_and_values.py | 72 ++++++ ...efined_custom_targeting_keys_and_values.py | 80 +++++++ .../update_custom_targeting_keys.py | 5 +- .../update_custom_targeting_values.py | 8 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 34 ++- .../get_exchange_rates_for_currency_code.py} | 45 ++-- .../update_exchange_rates.py | 2 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 2 +- .../get_all_ad_unit_sizes.py} | 30 ++- .../inventory_service/get_all_ad_units.py | 49 ++++ .../inventory_service/update_ad_units.py | 2 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 5 +- .../label_service/deactivate_labels.py | 5 +- .../label_service/get_active_labels.py} | 35 +-- .../label_service/get_all_labels.py | 23 +- .../label_service/update_labels.py | 5 +- .../__init__.py | 0 .../create_licas.py | 5 +- .../deactivate_licas.py | 5 +- .../get_all_licas.py | 33 +-- .../get_licas_for_line_item.py} | 50 ++--- .../update_licas.py | 5 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 5 +- .../line_item_service/create_line_items.py | 7 +- .../create_video_line_item.py | 9 +- .../line_item_service/get_all_line_items.py | 28 ++- .../get_line_items_that_need_creatives.py | 57 +++++ .../get_recently_updated_line_items.py | 61 +++++ .../target_custom_criteria.py | 5 +- .../line_item_service/update_line_items.py | 5 +- .../v201702/native_style_service/__init__.py | 15 ++ .../create_native_styles.py | 180 +++++++++++++++ .../get_all_native_styles.py | 51 +++++ .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 20 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 5 +- .../order_service/create_orders.py | 7 +- .../order_service/get_all_orders.py | 21 +- .../order_service/get_orders_starting_soon.py | 71 ++++++ .../order_service/update_orders.py | 5 +- .../package_service/get_all_packages.py | 50 +++++ .../get_in_progress_packages.py | 57 +++++ .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 2 +- .../get_active_placements.py} | 41 ++-- .../placement_service/get_all_placements.py | 26 +-- .../placement_service/update_placements.py | 2 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 31 ++- .../get_premium_rates_for_rate_card.py} | 46 ++-- .../update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 53 +++++ ...oduct_package_items_for_product_package.py | 62 ++++++ .../get_active_product_packages.py | 58 +++++ .../get_all_product_packages.py | 51 +++++ .../product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 84 +++++++ .../product_service/get_all_products.py | 24 +- .../get_products_for_product_template.py | 37 ++- ...sh_programmatic_products_to_marketplace.py | 74 ++++++ .../product_service/update_products.py | 2 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 2 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 91 ++++++++ .../get_all_product_templates.py | 24 +- .../get_sponsorship_product_templates.py | 37 ++- .../update_product_templates.py | 2 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 2 +- ...create_programmatic_proposal_line_items.py | 119 ++++++++++ ...sal_line_items_for_non_sales_management.py | 125 +++++++++++ .../create_proposal_line_items.py | 8 +- .../get_all_proposal_line_items.py | 28 +-- .../get_proposal_line_items_for_proposal.py | 48 ++-- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 71 ++++++ ...atic_proposals_for_non_sales_management.py | 62 ++++++ .../proposal_service/create_proposals.py | 9 +- .../proposal_service/get_all_proposals.py | 23 +- .../get_marketplace_comments.py | 56 +++++ .../get_proposals_pending_approval.py} | 40 ++-- .../request_buyers_acceptance.py | 74 ++++++ .../submit_proposals_for_approval.py | 6 +- .../proposal_service/update_proposals.py | 9 +- .../__init__.py | 0 .../fetch_match_tables.py | 6 +- .../get_all_programmatic_buyers.py} | 31 +-- .../get_recent_changes.py | 210 ++++++++++++++++++ .../rate_card_service/__init__.py | 0 .../rate_card_service/get_all_rate_cards.py | 28 ++- .../get_marketplace_rate_cards.py} | 44 ++-- ..._item_reports_for_reconciliation_report.py | 75 +++++++ ...order_reports_for_reconciliation_report.py | 63 ++++++ ...n_report_rows_for_reconciliation_report.py | 66 ++++++ .../get_all_reconciliation_reports.py | 56 +++++ ...iliation_report_for_last_billing_period.py | 69 ++++++ .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 7 +- .../report_service/run_inventory_report.py | 8 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 8 +- .../report_service/run_sales_report.py | 5 +- .../v201702/report_service/run_saved_query.py | 85 +++++++ .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 24 +- ...et_highly_requested_suggested_ad_units.py} | 48 ++-- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 5 +- .../team_service/get_all_teams.py | 26 +-- .../team_service/update_teams.py | 22 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 5 +- .../user_service/deactivate_users.py | 5 +- .../user_service/get_all_roles.py | 18 +- .../user_service/get_all_users.py | 21 +- .../user_service/get_user_by_email_address.py | 58 +++++ .../user_service/update_users.py | 5 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 27 +-- .../get_user_team_associations_for_user.py | 47 ++-- .../update_user_team_associations.py | 2 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py} | 40 ++-- ...t_workflow_external_condition_requests.py} | 44 ++-- ...er_workflow_external_condition_requests.py | 2 +- googleads/common.py | 5 +- googleads/dfp.py | 27 +-- googleads/util.py | 12 +- tests/adwords_test.py | 2 +- tests/dfp_test.py | 5 +- tests/util_test.py | 25 +++ 248 files changed, 3872 insertions(+), 2659 deletions(-) delete mode 100755 examples/dfp/v201605/activity_group_service/get_active_activity_groups.py delete mode 100755 examples/dfp/v201605/activity_service/get_active_activities.py delete mode 100755 examples/dfp/v201605/company_service/get_advertisers.py delete mode 100755 examples/dfp/v201605/contact_service/get_uninvited_contacts.py delete mode 100755 examples/dfp/v201605/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py delete mode 100755 examples/dfp/v201605/content_service/get_all_content.py delete mode 100755 examples/dfp/v201605/creative_service/get_creatives_by_statement.py delete mode 100755 examples/dfp/v201605/creative_template_service/get_creative_templates_by_statement.py delete mode 100755 examples/dfp/v201605/creative_wrapper_service/get_active_creative_wrappers.py delete mode 100755 examples/dfp/v201605/custom_targeting_service/get_all_custom_targeting_keys_and_values.py delete mode 100755 examples/dfp/v201605/custom_targeting_service/get_custom_targeting_values_by_statement.py delete mode 100755 examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py delete mode 100755 examples/dfp/v201605/inventory_service/get_all_ad_unit_sizes.py delete mode 100755 examples/dfp/v201605/inventory_service/get_all_ad_units.py delete mode 100755 examples/dfp/v201605/inventory_service/get_top_level_ad_units.py delete mode 100755 examples/dfp/v201605/line_item_service/get_line_items_by_statement.py delete mode 100755 examples/dfp/v201605/line_item_service/get_recently_updated_line_items.py delete mode 100755 examples/dfp/v201605/order_service/get_orders_by_statement.py delete mode 100755 examples/dfp/v201605/publisher_query_language_service/get_geo_targets.py delete mode 100755 examples/dfp/v201605/team_service/get_teams_by_statement.py delete mode 100755 examples/dfp/v201605/user_service/get_current_user.py delete mode 100755 examples/dfp/v201605/user_service/get_users_by_statement.py rename examples/dfp/{v201605 => v201702}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/activity_group_service/create_activity_groups.py (97%) create mode 100755 examples/dfp/v201702/activity_group_service/get_active_activity_groups.py rename examples/dfp/{v201605 => v201702}/activity_group_service/get_all_activity_groups.py (61%) rename examples/dfp/{v201605 => v201702}/activity_group_service/update_activity_groups.py (97%) rename examples/dfp/{v201605 => v201702}/activity_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/activity_service/create_activities.py (99%) rename examples/dfp/{v201605/activity_service/get_all_activities.py => v201702/activity_service/get_active_activities.py} (58%) create mode 100755 examples/dfp/v201702/activity_service/get_all_activities.py rename examples/dfp/{v201605 => v201702}/activity_service/update_activities.py (99%) rename examples/dfp/{v201605 => v201702}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/audience_segment_service/create_audience_segments.py (95%) rename examples/dfp/{v201605 => v201702}/audience_segment_service/get_all_audience_segments.py (65%) rename examples/dfp/{v201605 => v201702}/audience_segment_service/get_first_party_audience_segments.py (59%) rename examples/dfp/{v201605 => v201702}/audience_segment_service/populate_first_party_audience_segments.py (90%) rename examples/dfp/{v201605 => v201702}/audience_segment_service/update_audience_segments.py (96%) rename examples/dfp/{v201605 => v201702}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201605 => v201702}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201605 => v201702}/base_rate_service/get_all_base_rates.py (62%) rename examples/dfp/{v201605/base_rate_service/get_base_rates_for_a_rate_card.py => v201702/base_rate_service/get_base_rates_for_rate_card.py} (57%) rename examples/dfp/{v201605 => v201702}/base_rate_service/update_base_rates.py (99%) rename examples/dfp/{v201605 => v201702}/company_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/company_service/create_companies.py (99%) rename examples/dfp/{v201605/company_service/get_all_companies.py => v201702/company_service/get_advertisers.py} (59%) create mode 100755 examples/dfp/v201702/company_service/get_all_companies.py rename examples/dfp/{v201605 => v201702}/company_service/update_companies.py (99%) rename examples/dfp/{v201605 => v201702}/contact_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/contact_service/create_contacts.py (99%) create mode 100755 examples/dfp/v201702/contact_service/get_all_contacts.py rename examples/dfp/{v201605/contact_service/get_all_contacts.py => v201702/contact_service/get_uninvited_contacts.py} (60%) rename examples/dfp/{v201605 => v201702}/contact_service/update_contacts.py (99%) rename examples/dfp/{v201605 => v201702}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201605 => v201702}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (97%) create mode 100755 examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename examples/dfp/{v201605 => v201702}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (98%) rename examples/dfp/{v201605 => v201702}/content_service/__init__.py (100%) create mode 100755 examples/dfp/v201702/content_service/get_all_content.py rename examples/dfp/{v201605 => v201702}/creative_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/creative_service/create_creative_from_template.py (91%) rename examples/dfp/{v201605 => v201702}/creative_service/create_creatives.py (98%) rename examples/dfp/{v201605 => v201702}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201605 => v201702}/creative_service/create_native_creative.py (99%) create mode 100755 examples/dfp/v201702/creative_service/get_all_creatives.py rename examples/dfp/{v201605/creative_service/get_all_creatives.py => v201702/creative_service/get_image_creatives.py} (57%) rename examples/dfp/{v201605 => v201702}/creative_service/update_creatives.py (99%) rename examples/dfp/{v201605 => v201702}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/creative_set_service/associate_creative_set_to_line_item.py (92%) rename examples/dfp/{v201605 => v201702}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201605 => v201702}/creative_set_service/get_all_creative_sets.py (61%) rename examples/dfp/{v201605/creative_set_service/get_creative_sets_by_statement.py => v201702/creative_set_service/get_creative_sets_for_master_creative.py} (54%) rename examples/dfp/{v201605 => v201702}/creative_set_service/update_creative_set.py (97%) rename examples/dfp/{v201605 => v201702}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/creative_template_service/get_all_creative_templates.py (61%) rename examples/dfp/{v201605/custom_targeting_service/get_custom_targeting_keys_by_statement.py => v201702/creative_template_service/get_system_defined_creative_templates.py} (56%) rename examples/dfp/{v201605 => v201702}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/dfp/{v201605 => v201702}/creative_wrapper_service/deactivate_creative_wrapper.py (97%) rename examples/dfp/{v201605/creative_wrapper_service/get_all_creative_wrappers.py => v201702/creative_wrapper_service/get_active_creative_wrappers.py} (58%) create mode 100755 examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py rename examples/dfp/{v201605 => v201702}/creative_wrapper_service/update_creative_wrappers.py (97%) rename examples/dfp/{v201605 => v201702}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201605 => v201702}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201605 => v201702}/custom_field_service/deactivate_all_line_item_custom_fields.py (98%) rename examples/dfp/{v201605 => v201702}/custom_field_service/get_all_custom_fields.py (67%) rename examples/dfp/{v201605/custom_field_service/get_all_line_item_custom_fields.py => v201702/custom_field_service/get_custom_fields_for_line_items.py} (59%) rename examples/dfp/{v201605 => v201702}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201605 => v201702}/custom_field_service/update_custom_fields.py (98%) rename examples/dfp/{v201605 => v201702}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201605 => v201702}/custom_targeting_service/delete_custom_targeting_keys.py (98%) rename examples/dfp/{v201605 => v201702}/custom_targeting_service/delete_custom_targeting_values.py (95%) create mode 100755 examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py create mode 100755 examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename examples/dfp/{v201605 => v201702}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/dfp/{v201605 => v201702}/custom_targeting_service/update_custom_targeting_values.py (91%) rename examples/dfp/{v201605 => v201702}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201605 => v201702}/exchange_rate_service/get_all_exchange_rates.py (57%) rename examples/dfp/{v201605/exchange_rate_service/get_exchange_rates_by_currency_code.py => v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py} (59%) rename examples/dfp/{v201605 => v201702}/exchange_rate_service/update_exchange_rates.py (97%) rename examples/dfp/{v201605 => v201702}/forecast_service/get_availability_forecast.py (99%) rename examples/dfp/{v201605 => v201702}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/dfp/{v201605 => v201702}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/dfp/{v201605 => v201702}/inventory_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/inventory_service/archive_ad_units.py (99%) rename examples/dfp/{v201605 => v201702}/inventory_service/create_ad_units.py (99%) rename examples/dfp/{v201605/network_service/get_current_network.py => v201702/inventory_service/get_all_ad_unit_sizes.py} (52%) create mode 100755 examples/dfp/v201702/inventory_service/get_all_ad_units.py rename examples/dfp/{v201605 => v201702}/inventory_service/update_ad_units.py (99%) rename examples/dfp/{v201605 => v201702}/label_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/label_service/create_labels.py (96%) rename examples/dfp/{v201605 => v201702}/label_service/deactivate_labels.py (97%) rename examples/dfp/{v201605/label_service/get_labels_by_statement.py => v201702/label_service/get_active_labels.py} (63%) rename examples/dfp/{v201605 => v201702}/label_service/get_all_labels.py (73%) rename examples/dfp/{v201605 => v201702}/label_service/update_labels.py (97%) rename examples/dfp/{v201605 => v201702}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/line_item_creative_association_service/create_licas.py (93%) rename examples/dfp/{v201605 => v201702}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/dfp/{v201605 => v201702}/line_item_creative_association_service/get_all_licas.py (56%) rename examples/dfp/{v201605/line_item_creative_association_service/get_licas_by_statement.py => v201702/line_item_creative_association_service/get_licas_for_line_item.py} (52%) rename examples/dfp/{v201605 => v201702}/line_item_creative_association_service/update_licas.py (94%) rename examples/dfp/{v201605 => v201702}/line_item_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/line_item_service/activate_line_items.py (98%) rename examples/dfp/{v201605 => v201702}/line_item_service/create_line_items.py (98%) rename examples/dfp/{v201605 => v201702}/line_item_service/create_video_line_item.py (96%) rename examples/dfp/{v201605 => v201702}/line_item_service/get_all_line_items.py (68%) create mode 100755 examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py create mode 100755 examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py rename examples/dfp/{v201605 => v201702}/line_item_service/target_custom_criteria.py (98%) rename examples/dfp/{v201605 => v201702}/line_item_service/update_line_items.py (96%) create mode 100755 examples/dfp/v201702/native_style_service/__init__.py create mode 100755 examples/dfp/v201702/native_style_service/create_native_styles.py create mode 100755 examples/dfp/v201702/native_style_service/get_all_native_styles.py rename examples/dfp/{v201605 => v201702}/network_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/network_service/get_all_networks.py (69%) rename examples/dfp/{v201605 => v201702}/network_service/make_test_network.py (99%) rename examples/dfp/{v201605 => v201702}/order_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/order_service/approve_orders.py (97%) rename examples/dfp/{v201605 => v201702}/order_service/create_orders.py (94%) rename examples/dfp/{v201605 => v201702}/order_service/get_all_orders.py (73%) create mode 100755 examples/dfp/v201702/order_service/get_orders_starting_soon.py rename examples/dfp/{v201605 => v201702}/order_service/update_orders.py (97%) create mode 100755 examples/dfp/v201702/package_service/get_all_packages.py create mode 100755 examples/dfp/v201702/package_service/get_in_progress_packages.py rename examples/dfp/{v201605 => v201702}/placement_service/create_placements.py (99%) rename examples/dfp/{v201605 => v201702}/placement_service/deactivate_placements.py (99%) rename examples/dfp/{v201605/placement_service/get_placements_by_statement.py => v201702/placement_service/get_active_placements.py} (64%) rename examples/dfp/{v201605 => v201702}/placement_service/get_all_placements.py (68%) rename examples/dfp/{v201605 => v201702}/placement_service/update_placements.py (99%) rename examples/dfp/{v201605 => v201702}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/premium_rate_service/create_premium_rates.py (97%) rename examples/dfp/{v201605 => v201702}/premium_rate_service/get_all_premium_rates.py (61%) rename examples/dfp/{v201605/premium_rate_service/get_premium_rates_for_a_rate_card.py => v201702/premium_rate_service/get_premium_rates_for_rate_card.py} (58%) rename examples/dfp/{v201605 => v201702}/premium_rate_service/update_premium_rates.py (97%) create mode 100755 examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py create mode 100755 examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py create mode 100755 examples/dfp/v201702/product_package_service/get_active_product_packages.py create mode 100755 examples/dfp/v201702/product_package_service/get_all_product_packages.py rename examples/dfp/{v201605 => v201702}/product_service/__init__.py (100%) create mode 100755 examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py rename examples/dfp/{v201605 => v201702}/product_service/get_all_products.py (72%) rename examples/dfp/{v201605 => v201702}/product_service/get_products_for_product_template.py (70%) create mode 100755 examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py rename examples/dfp/{v201605 => v201702}/product_service/update_products.py (99%) rename examples/dfp/{v201605 => v201702}/product_template_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/product_template_service/activate_product_templates.py (97%) rename examples/dfp/{v201605 => v201702}/product_template_service/create_product_templates.py (97%) create mode 100755 examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py rename examples/dfp/{v201605 => v201702}/product_template_service/get_all_product_templates.py (68%) rename examples/dfp/{v201605 => v201702}/product_template_service/get_sponsorship_product_templates.py (63%) rename examples/dfp/{v201605 => v201702}/product_template_service/update_product_templates.py (98%) rename examples/dfp/{v201605 => v201702}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/proposal_line_item_service/archive_proposal_line_items.py (98%) create mode 100755 examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py create mode 100755 examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename examples/dfp/{v201605 => v201702}/proposal_line_item_service/create_proposal_line_items.py (97%) rename examples/dfp/{v201605 => v201702}/proposal_line_item_service/get_all_proposal_line_items.py (60%) rename examples/dfp/{v201605 => v201702}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (54%) rename examples/dfp/{v201605 => v201702}/proposal_line_item_service/update_proposal_line_items.py (94%) rename examples/dfp/{v201605 => v201702}/proposal_service/__init__.py (100%) create mode 100755 examples/dfp/v201702/proposal_service/create_programmatic_proposals.py create mode 100755 examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename examples/dfp/{v201605 => v201702}/proposal_service/create_proposals.py (94%) rename examples/dfp/{v201605 => v201702}/proposal_service/get_all_proposals.py (72%) create mode 100755 examples/dfp/v201702/proposal_service/get_marketplace_comments.py rename examples/dfp/{v201605/proposal_service/get_proposals_by_statement.py => v201702/proposal_service/get_proposals_pending_approval.py} (66%) create mode 100755 examples/dfp/v201702/proposal_service/request_buyers_acceptance.py rename examples/dfp/{v201605 => v201702}/proposal_service/submit_proposals_for_approval.py (96%) rename examples/dfp/{v201605 => v201702}/proposal_service/update_proposals.py (90%) rename examples/dfp/{v201605 => v201702}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/publisher_query_language_service/fetch_match_tables.py (90%) rename examples/dfp/{v201605/publisher_query_language_service/get_line_items_named_like.py => v201702/publisher_query_language_service/get_all_programmatic_buyers.py} (57%) create mode 100755 examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py rename examples/dfp/{v201605 => v201702}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/rate_card_service/get_all_rate_cards.py (64%) rename examples/dfp/{v201605/rate_card_service/get_rate_cards_priced_with_currency.py => v201702/rate_card_service/get_marketplace_rate_cards.py} (58%) create mode 100755 examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py create mode 100755 examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py create mode 100755 examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py create mode 100755 examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py create mode 100755 examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename examples/dfp/{v201605 => v201702}/report_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/report_service/run_delivery_report.py (93%) rename examples/dfp/{v201605 => v201702}/report_service/run_inventory_report.py (94%) rename examples/dfp/{v201605 => v201702}/report_service/run_reach_report.py (96%) rename examples/dfp/{v201605 => v201702}/report_service/run_report_with_custom_fields.py (94%) rename examples/dfp/{v201605 => v201702}/report_service/run_sales_report.py (92%) create mode 100755 examples/dfp/v201702/report_service/run_saved_query.py rename examples/dfp/{v201605 => v201702}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (97%) rename examples/dfp/{v201605 => v201702}/suggested_ad_unit_service/get_all_suggested_ad_units.py (69%) rename examples/dfp/{v201605/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py => v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py} (58%) rename examples/dfp/{v201605 => v201702}/team_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/team_service/create_teams.py (94%) rename examples/dfp/{v201605 => v201702}/team_service/get_all_teams.py (66%) rename examples/dfp/{v201605 => v201702}/team_service/update_teams.py (73%) rename examples/dfp/{v201605 => v201702}/user_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/user_service/create_users.py (92%) rename examples/dfp/{v201605 => v201702}/user_service/deactivate_users.py (96%) rename examples/dfp/{v201605 => v201702}/user_service/get_all_roles.py (75%) rename examples/dfp/{v201605 => v201702}/user_service/get_all_users.py (69%) create mode 100755 examples/dfp/v201702/user_service/get_user_by_email_address.py rename examples/dfp/{v201605 => v201702}/user_service/update_users.py (93%) rename examples/dfp/{v201605 => v201702}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201605 => v201702}/user_team_association_service/delete_user_team_associations.py (98%) rename examples/dfp/{v201605 => v201702}/user_team_association_service/get_all_user_team_associations.py (63%) rename examples/dfp/{v201605 => v201702}/user_team_association_service/get_user_team_associations_for_user.py (59%) rename examples/dfp/{v201605 => v201702}/user_team_association_service/update_user_team_associations.py (98%) rename examples/dfp/{v201605 => v201702}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201605 => v201702}/workflow_request_service/approve_workflow_approval_requests.py (97%) rename examples/dfp/{v201605/workflow_request_service/get_workflow_approval_requests_by_statement.py => v201702/workflow_request_service/get_workflow_approval_requests.py} (62%) rename examples/dfp/{v201605/workflow_request_service/get_workflow_external_condition_requests_by_statement.py => v201702/workflow_request_service/get_workflow_external_condition_requests.py} (61%) rename examples/dfp/{v201605 => v201702}/workflow_request_service/trigger_workflow_external_condition_requests.py (98%) diff --git a/ChangeLog b/ChangeLog index 879ec2cd..2f10094a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,13 @@ +5.1.0 -- 2/13/17: +* Added support for DFP v201702. +* Removed examples for DFP v201605. +* Removed support for DFP v201602. +* Resolved issues: +- Issue 166: https://github.com/googleads/googleads-python-lib/issues/166 +- Issue 176: https://github.com/googleads/googleads-python-lib/issues/176 + Issue 177: https://github.com/googleads/googleads-python-lib/issues/177 + + 5.0.0 -- 1/13/17: * BREAKING CHANGE: The underlying suds client now has cache enabled. By default, suds uses FileCache which requires access to local file system and will break diff --git a/README.md b/README.md index 1e36c492..377a65cb 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ You can also disable caching in similar fashion: ```python adwords_client = adwords.AdWordsClient( developer_token, oauth2_client, user_agent, - client_customer_id=client_customer_id, cache=suds.cache.NoCache) + client_customer_id=client_customer_id, cache=suds.cache.NoCache()) ``` ##Timeout Tips diff --git a/examples/dfp/v201605/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201605/activity_group_service/get_active_activity_groups.py deleted file mode 100755 index e47f391c..00000000 --- a/examples/dfp/v201605/activity_group_service/get_active_activity_groups.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active activity groups. - -To create activity groups, run create_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201605') - - # Create statement object to only select active activity groups. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get activity groups by statement. - while True: - response = activity_group_service.getActivityGroupsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity_group in response['results']: - print ('Activity group with ID \'%s\' and name \'%s\' was found.' - % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/activity_service/get_active_activities.py b/examples/dfp/v201605/activity_service/get_active_activities.py deleted file mode 100755 index dc7bcaeb..00000000 --- a/examples/dfp/v201605/activity_service/get_active_activities.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active activities. - -To create activities, run create_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201605') - - # Create statement object to only select active activities. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get activities by statement. - while True: - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for activity in response['results']: - print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (activity['id'], activity['name'], activity['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/company_service/get_advertisers.py b/examples/dfp/v201605/company_service/get_advertisers.py deleted file mode 100755 index 4c66ebad..00000000 --- a/examples/dfp/v201605/company_service/get_advertisers.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all companies that are advertisers. - -To create companies, run create_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201605') - - # Create statement object to only select companies that are advertisers. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - } - }] - query = 'WHERE type = :type' - statement = dfp.FilterStatement(query, values) - - # Get companies by statement. - while True: - response = company_service.getCompaniesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for company in response['results']: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.' - % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/contact_service/get_uninvited_contacts.py b/examples/dfp/v201605/contact_service/get_uninvited_contacts.py deleted file mode 100755 index dd3929c4..00000000 --- a/examples/dfp/v201605/contact_service/get_uninvited_contacts.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all contacts that aren't invited yet. - -To create contacts, run create_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201605') - - # Create statement object to only select contacts that are uninvited. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get contacts by statement. - while True: - response = contact_service.getContactsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for contact in response['results']: - print ('Contact with ID \'%s\' and name \'%s\' was found.' - % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201605/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py deleted file mode 100755 index 1636e052..00000000 --- a/examples/dfp/v201605/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all content metadata key hierarchies. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201605') - - # Create statement object to select all content. - statement = dfp.FilterStatement() - - # Get content by statement. - while True: - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())[0]) - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - if content_metadata_key_hierarchies: - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchyy with id \'%s\' and name \'%s\'' - ' was found.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/content_service/get_all_content.py b/examples/dfp/v201605/content_service/get_all_content.py deleted file mode 100755 index 7347e940..00000000 --- a/examples/dfp/v201605/content_service/get_all_content.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all content. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201605') - - # Create statement object to select all content. - statement = dfp.FilterStatement() - - # Get content by statement. - while True: - response = content_service.getContentByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for content_item in response['results']: - print ('Content with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (content_item['id'], content_item['name'], - content_item['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/creative_service/get_creatives_by_statement.py b/examples/dfp/v201605/creative_service/get_creatives_by_statement.py deleted file mode 100755 index 8757a292..00000000 --- a/examples/dfp/v201605/creative_service/get_creatives_by_statement.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all image creatives. - -To create an image creative, run create_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201605') - - # Create statement object to only select image creatives. - values = [{ - 'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }] - query = 'WHERE creativeType = :creativeType' - statement = dfp.FilterStatement(query, values) - - # Get creatives by statement. - while True: - response = creative_service.getCreativesByStatement( - statement.ToStatement()) - creatives = response['results'] - - if creatives: - # Display results. - for creative in creatives: - print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (creative['id'], creative['name'], - dfp.DfpClassType(creative))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/creative_template_service/get_creative_templates_by_statement.py b/examples/dfp/v201605/creative_template_service/get_creative_templates_by_statement.py deleted file mode 100755 index 93d4befe..00000000 --- a/examples/dfp/v201605/creative_template_service/get_creative_templates_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all system defined creative templates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201605') - - # Create statement object to only select system defined creative templates. - values = [{ - 'key': 'creativeTemplateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - } - }] - query = 'WHERE type = :creativeTemplateType' - statement = dfp.FilterStatement(query, values) - - # Get creative templates by statement. - while True: - response = creative_template_service.getCreativeTemplatesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for template in response['results']: - print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' ' - 'was found.' % (template['id'], - template['name'], - template['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201605/creative_wrapper_service/get_active_creative_wrappers.py deleted file mode 100755 index 1a92e1c1..00000000 --- a/examples/dfp/v201605/creative_wrapper_service/get_active_creative_wrappers.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all active creative wrappers. - -To create creative wrappers, run create_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201605') - - # Create statement object to only select active creative wrappers. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status' - statement = dfp.FilterStatement(query, values) - - # Get creative wrappers by statement. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'found.' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201605/custom_targeting_service/get_all_custom_targeting_keys_and_values.py deleted file mode 100755 index 3cb317ca..00000000 --- a/examples/dfp/v201605/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 targeting keys and the values. - -To create custom targeting keys and values, run -create_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') - - # Create statement to get all targeting keys. - targeting_key_statement = dfp.FilterStatement() - - all_keys = [] - - # Get custom targeting keys by statement. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - targeting_key_statement.ToStatement()) - if 'results' in response: - all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - if all_keys: - # Create map of custom targeting key id to custom targeting values. - key_value_map = {} - - # Create statement to get all targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' - % ', '.join([str(key['id']) for key in all_keys])) - targeting_value_statement = dfp.FilterStatement(query) - - # Get custom targeting values by statement. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - targeting_value_statement.ToStatement()) - if 'results' in response: - for key in all_keys: - for value in response['results']: - if key['id'] == value['customTargetingKeyId']: - if key['id'] not in key_value_map.keys(): - key_value_map[key['id']] = [] - key_value_map[key['id']].append(value) - targeting_value_statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - for key in all_keys: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was found.' - %(key['id'], key['name'], key['displayName'], key['type'])) - if key['id'] in key_value_map.keys(): - for value in key_value_map[key['id']]: - print ('\tCustom targeting value with id \'%s\', name \'%s\', and ' - 'display name \'%s\' was found.' - % (value['id'], value['name'], value['displayName'])) - else: - print 'No keys were found.' - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) - diff --git a/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_values_by_statement.py b/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_values_by_statement.py deleted file mode 100755 index d0e507b0..00000000 --- a/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_values_by_statement.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 custom targeting values for the given predefined custom -targeting key. - -To create custom targeting values, run -create_custom_targeting_keys_and_values.py. To determine which custom -targeting keys exist, run get_all_custom_targeting_keys_and_values.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') - - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) - - # Get custom targeting values by statement. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for value in response['results']: - print ('Custom targeting value with id \'%s\', name \'%s\', and display' - ' name \'%s\' was found.' - % (value['id'], value['name'], value['displayName'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py deleted file mode 100755 index 23c939ca..00000000 --- a/examples/dfp/v201605/inventory_service/get_ad_unit_hierarchy.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code gets the ad unit hierarchy and displays it as a tree. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201605') - statement = dfp.FilterStatement() - - all_ad_units = [] - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - all_ad_units.extend(response['results']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Find the root ad unit. root_ad_unit can also be set to child unit to only - # build and display a portion of the tree. - query = 'WHERE parentId IS NULL' - root_statement = dfp.FilterStatement(query) - response = inventory_service.getAdUnitsByStatement( - root_statement.ToStatement()) - root_ad_unit = response['results'][0] - - if root_ad_unit: - BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units) - else: - print 'Could not build tree. No root ad unit found.' - - -def DisplayAdUnitTree(root_ad_unit, ad_unit_tree, depth=0): - """Helper for displaying ad unit tree. - - Args: - root_ad_unit: dict the root ad unit. - ad_unit_tree: dict the tree of ad units. - [optional] - depth: int the depth the tree has reached. - """ - print '%s%s (%s)' % (GenerateTab(depth), root_ad_unit['name'], - root_ad_unit['id']) - if root_ad_unit['id'] in ad_unit_tree: - for child in ad_unit_tree[root_ad_unit['id']]: - DisplayAdUnitTree(child, ad_unit_tree, depth+1) - - -def GenerateTab(depth): - """Generate tabs to represent branching to children. - - Args: - depth: int the depth the tree has reached. - - Returns: - string inserted in front of the root unit. - """ - tab_list = [] - if depth > 0: - tab_list.append(' ') - tab_list.append('| ' * depth) - tab_list.append('+--') - return ''.join(tab_list) - - -def BuildAndDisplayAdUnitTree(root_ad_unit, all_ad_units): - """Create an ad unit tree and display it. - - Args: - root_ad_unit: dict the root ad unit to build the tree under. - all_ad_units: list the list of all ad units to build the tree with. - """ - tree = {} - for ad_unit in all_ad_units: - if 'parentId' in ad_unit: - if ad_unit['parentId'] not in tree: - tree[ad_unit['parentId']] = [] - tree[ad_unit['parentId']].append(ad_unit) - - DisplayAdUnitTree(root_ad_unit, tree) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201605/inventory_service/get_all_ad_unit_sizes.py deleted file mode 100755 index 68534b9a..00000000 --- a/examples/dfp/v201605/inventory_service/get_all_ad_unit_sizes.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all ad unit sizes defined in a network. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201605') - statement = dfp.FilterStatement() - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitSizesByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit_size in response['results']: - print ('Ad unit size of dimensions %s was found.' % - (ad_unit_size['fullDisplayString'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/inventory_service/get_all_ad_units.py b/examples/dfp/v201605/inventory_service/get_all_ad_units.py deleted file mode 100755 index 119359c8..00000000 --- a/examples/dfp/v201605/inventory_service/get_all_ad_units.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all ad units within a network. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201605') - statement = dfp.FilterStatement() - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' was found.' - % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201605/inventory_service/get_top_level_ad_units.py deleted file mode 100755 index 1274a9dc..00000000 --- a/examples/dfp/v201605/inventory_service/get_top_level_ad_units.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all child ad units of the effective root ad unit. - -To create ad units, run create_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201605') - network_service = client.GetService('NetworkService', version='v201605') - - root_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - # Create a statement to select the children of the effective root ad unit. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': root_id - } - }] - query = 'WHERE parentId = :id' - statement = dfp.FilterStatement(query, values) - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response: - # Display results. - for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' was found.' - % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/line_item_service/get_line_items_by_statement.py b/examples/dfp/v201605/line_item_service/get_line_items_by_statement.py deleted file mode 100755 index 7d7db8e9..00000000 --- a/examples/dfp/v201605/line_item_service/get_line_items_by_statement.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets all line items that need creatives for an order. - -To create line items, run create_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') - - # Create statement object to only select line items that need creatives from a - # given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - }] - query = ('WHERE orderId = :orderId AND ' - 'isMissingCreatives = :isMissingCreatives') - statement = dfp.FilterStatement(query, values) - - while True: - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % (line_item['id'], - line_item['orderId'], - line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201605/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201605/line_item_service/get_recently_updated_line_items.py deleted file mode 100755 index 4d254e07..00000000 --- a/examples/dfp/v201605/line_item_service/get_recently_updated_line_items.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example shows how to get recently updated line items. - -To create line items, run create_line_items.py.""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import dfp - -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') - - # Create statement object to only select line items belonging to the order and - # have been modified in the last 3 days. - three_days_ago = datetime.date.today() - datetime.timedelta(days=3) - values = [{ - 'key': 'dateTimeString', - 'value': { - 'xsi_type': 'TextValue', - 'value': three_days_ago.strftime('%Y-%m-%dT%H:%M:%S') - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE lastModifiedDateTime >= :dateTimeString AND orderId = :orderId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response: - # Display results. - for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % (line_item['id'], - line_item['orderId'], - line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201605/order_service/get_orders_by_statement.py b/examples/dfp/v201605/order_service/get_orders_by_statement.py deleted file mode 100755 index 0106f3ae..00000000 --- a/examples/dfp/v201605/order_service/get_orders_by_statement.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets an order by an ID. - -To create orders, run create_orders.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set id of the order to get. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201605') - - # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - - statement = dfp.FilterStatement(query, values) - - # Get orders by statement. - response = order_service.getOrdersByStatement(statement.ToStatement()) - orders = [] - if 'results' in response: - orders = response['results'] - - # Display results. - for order in orders: - print ('Order with id \'%s\' name \'%s\' was found.' - % (order['id'], order['name'])) - - print '\nNumber of results found: %s' % len(orders) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) diff --git a/examples/dfp/v201605/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201605/publisher_query_language_service/get_geo_targets.py deleted file mode 100755 index 9d5fe7f3..00000000 --- a/examples/dfp/v201605/publisher_query_language_service/get_geo_targets.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 geographic criteria from the Geo_Target table. - -The types available to filter on include 'City', 'Country', 'Region', 'State', -'Postal_Code', and 'DMA_Region' (i.e. Metro). - -A full list of available geo target types can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201605/PublisherQueryLanguageService -""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201605') - - output_file = tempfile.NamedTemporaryFile( - prefix='geo_target_type_', suffix='.csv', mode='w', delete=False) - - # Create bind value to select geo-targets of type 'City'. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'City' - } - }] - - pql_query = ('SELECT Name, Id FROM Geo_Target ' - 'WHERE targetable = true AND Type = :type') - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - pql_query, output_file, values) - output_file.close() - - print ('Saved geo targets to... %s' % output_file.name) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/team_service/get_teams_by_statement.py b/examples/dfp/v201605/team_service/get_teams_by_statement.py deleted file mode 100755 index a7058f0e..00000000 --- a/examples/dfp/v201605/team_service/get_teams_by_statement.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 a single team by ID. - -To create teams, run create_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -TEAM_ID = 'INSERT_TEAM_ID_HERE' - - -def main(client, team_id): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201605') - - # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) - - while True: - # Get teams by statement. - response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: - # Display results. - for team in response['results']: - print ('Team with id \'%s\' and name \'%s\' was found.' - % (team['id'], team['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID) diff --git a/examples/dfp/v201605/user_service/get_current_user.py b/examples/dfp/v201605/user_service/get_current_user.py deleted file mode 100755 index 020ee7be..00000000 --- a/examples/dfp/v201605/user_service/get_current_user.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets the current user.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') - - # Get current user. - user = user_service.getCurrentUser() - - # Display results. - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201605/user_service/get_users_by_statement.py b/examples/dfp/v201605/user_service/get_users_by_statement.py deleted file mode 100755 index b6f039e0..00000000 --- a/examples/dfp/v201605/user_service/get_users_by_statement.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2015 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 code example gets a user by its id. - -To create users, run create_user.py.""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -USER_ID = 'INSERT_USER_ID_TO_FIND_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) - - # Get users by statement. - response = user_service.getUsersByStatement(statement.ToStatement()) - users = response['results'] if 'results' in response else [] - - for user in users: - # Display results. - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) diff --git a/examples/dfp/v201608/creative_service/create_creative_from_template.py b/examples/dfp/v201608/creative_service/create_creative_from_template.py index dd76310b..8986be11 100755 --- a/examples/dfp/v201608/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201608/creative_service/create_creative_from_template.py @@ -46,22 +46,34 @@ def main(client, advertiser_id): # Use the image banner with optional third party tracking template. creative_template_id = '10000680' + # Create image asset. + file_name = 'image%s.jpg' % uuid.uuid4() image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() image_data = base64.encodestring(image_data) + size = { + 'width': '300', + 'height': '250' + } + asset = { + 'xsi_type': 'CreativeAsset', + 'fileName': file_name, + 'assetByteArray': image_data, + 'size': size + } + # Create creative from templates. creative = { 'xsi_type': 'TemplateCreative', 'name': 'Template Creative #%s' % uuid.uuid4(), 'advertiserId': advertiser_id, - 'size': {'width': '300', 'height': '250'}, + 'size': size, 'creativeTemplateId': creative_template_id, 'creativeTemplateVariableValues': [ { 'xsi_type': 'AssetCreativeTemplateVariableValue', 'uniqueName': 'Imagefile', - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() + 'asset': asset }, { 'xsi_type': 'LongCreativeTemplateVariableValue', diff --git a/examples/dfp/v201611/creative_service/create_creative_from_template.py b/examples/dfp/v201611/creative_service/create_creative_from_template.py index a612e533..1024497e 100755 --- a/examples/dfp/v201611/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201611/creative_service/create_creative_from_template.py @@ -46,22 +46,34 @@ def main(client, advertiser_id): # Use the image banner with optional third party tracking template. creative_template_id = '10000680' + # Create image asset. + file_name = 'image%s.jpg' % uuid.uuid4() image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() image_data = base64.encodestring(image_data) + size = { + 'width': '300', + 'height': '250' + } + asset = { + 'xsi_type': 'CreativeAsset', + 'fileName': file_name, + 'assetByteArray': image_data, + 'size': size + } + # Create creative from templates. creative = { 'xsi_type': 'TemplateCreative', 'name': 'Template Creative #%s' % uuid.uuid4(), 'advertiserId': advertiser_id, - 'size': {'width': '300', 'height': '250'}, + 'size': size, 'creativeTemplateId': creative_template_id, 'creativeTemplateVariableValues': [ { 'xsi_type': 'AssetCreativeTemplateVariableValue', 'uniqueName': 'Imagefile', - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() + 'asset': asset }, { 'xsi_type': 'LongCreativeTemplateVariableValue', diff --git a/examples/dfp/v201605/activity_group_service/__init__.py b/examples/dfp/v201702/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201605/activity_group_service/__init__.py rename to examples/dfp/v201702/activity_group_service/__init__.py diff --git a/examples/dfp/v201605/activity_group_service/create_activity_groups.py b/examples/dfp/v201702/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201605/activity_group_service/create_activity_groups.py rename to examples/dfp/v201702/activity_group_service/create_activity_groups.py index 79c5bdc9..74fa25cd 100755 --- a/examples/dfp/v201605/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201605') + version='v201702') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py new file mode 100755 index 00000000..c4e7e4f7 --- /dev/null +++ b/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 active activity groups. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + activity_group_service = client.GetService( + 'ActivityGroupService', version='v201702') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select activity groups. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of activity groups at a time, paging + # through until all activity groups have been retrieved. + while True: + response = activity_group_service.getActivityGroupsByStatement( + statement.ToStatement()) + if 'results' in response: + for activity_group in response['results']: + # Print out some information for each activity group. + print('Activity group with ID "%d" and name "%s" was found.\n' % + (activity_group['id'], activity_group['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py similarity index 61% rename from examples/dfp/v201605/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201702/activity_group_service/get_all_activity_groups.py index 0b1592b2..bd1abc49 100755 --- a/examples/dfp/v201605/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,40 +13,31 @@ # 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 code example gets all activity groups. - -To create activity groups, run create_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all activity groups. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201605') + activity_group_service = client.GetService( + 'ActivityGroupService', version='v201702') - # Create a filter statement. + # Create a statement to select activity groups. statement = dfp.FilterStatement() - # Get activity groups by statement. + # Retrieve a small amount of activity groups at a time, paging + # through until all activity groups have been retrieved. while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for activity_group in response['results']: - print ('Activity group with ID \'%s\' and name \'%s\' was found.' - % (activity_group['id'], activity_group['name'])) + # Print out some information for each activity group. + print('Activity group with ID "%d" and name "%s" was found.\n' % + (activity_group['id'], activity_group['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/activity_group_service/update_activity_groups.py b/examples/dfp/v201702/activity_group_service/update_activity_groups.py similarity index 97% rename from examples/dfp/v201605/activity_group_service/update_activity_groups.py rename to examples/dfp/v201702/activity_group_service/update_activity_groups.py index d7a21f29..ac561ae5 100755 --- a/examples/dfp/v201605/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/update_activity_groups.py @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201605') + version='v201702') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201605/activity_service/__init__.py b/examples/dfp/v201702/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201605/activity_service/__init__.py rename to examples/dfp/v201702/activity_service/__init__.py diff --git a/examples/dfp/v201605/activity_service/create_activities.py b/examples/dfp/v201702/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201605/activity_service/create_activities.py rename to examples/dfp/v201702/activity_service/create_activities.py index d5f30f3d..d5922287 100755 --- a/examples/dfp/v201605/activity_service/create_activities.py +++ b/examples/dfp/v201702/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201605') + activity_service = client.GetService('ActivityService', version='v201702') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201605/activity_service/get_all_activities.py b/examples/dfp/v201702/activity_service/get_active_activities.py similarity index 58% rename from examples/dfp/v201605/activity_service/get_all_activities.py rename to examples/dfp/v201702/activity_service/get_active_activities.py index 80642b6e..ab6a7dbf 100755 --- a/examples/dfp/v201605/activity_service/get_all_activities.py +++ b/examples/dfp/v201702/activity_service/get_active_activities.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,44 @@ # 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 code example gets all activities. - -To create activities, run create_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all active activities. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201605') - - # Create statement object to select only all activities. - statement = dfp.FilterStatement() - - # Get activities by statement. + activity_service = client.GetService('ActivityService', version='v201702') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select activities. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of activities at a time, paging + # through until all activities have been retrieved. while True: - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) + response = activity_service.getActivitiesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for activity in response['results']: - print ('Activity with ID \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (activity['id'], activity['name'], activity['type'])) + # Print out some information for each activity. + print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % + (activity['id'], activity['name'], activity['type'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/activity_service/get_all_activities.py b/examples/dfp/v201702/activity_service/get_all_activities.py new file mode 100755 index 00000000..b95a3c96 --- /dev/null +++ b/examples/dfp/v201702/activity_service/get_all_activities.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# +# Copyright 2016 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 activities. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + activity_service = client.GetService('ActivityService', version='v201702') + + # Create a statement to select activities. + statement = dfp.FilterStatement() + + # Retrieve a small amount of activities at a time, paging + # through until all activities have been retrieved. + while True: + response = activity_service.getActivitiesByStatement(statement.ToStatement( + )) + if 'results' in response: + for activity in response['results']: + # Print out some information for each activity. + print('Activity with ID "%d" and name "%s" was found.\n' % + (activity['id'], activity['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/activity_service/update_activities.py b/examples/dfp/v201702/activity_service/update_activities.py similarity index 99% rename from examples/dfp/v201605/activity_service/update_activities.py rename to examples/dfp/v201702/activity_service/update_activities.py index 8abefc6d..936a704a 100755 --- a/examples/dfp/v201605/activity_service/update_activities.py +++ b/examples/dfp/v201702/activity_service/update_activities.py @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201605') + activity_service = client.GetService('ActivityService', version='v201702') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201605/audience_segment_service/__init__.py b/examples/dfp/v201702/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201605/audience_segment_service/__init__.py rename to examples/dfp/v201702/audience_segment_service/__init__.py diff --git a/examples/dfp/v201605/audience_segment_service/create_audience_segments.py b/examples/dfp/v201702/audience_segment_service/create_audience_segments.py similarity index 95% rename from examples/dfp/v201605/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201702/audience_segment_service/create_audience_segments.py index f82eaf83..49cbc19d 100755 --- a/examples/dfp/v201605/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/create_audience_segments.py @@ -26,11 +26,12 @@ CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' + def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201605') - network_service = client.GetService('NetworkService', version='v201605') + 'AudienceSegmentService', version='v201702') + network_service = client.GetService('NetworkService', version='v201702') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( @@ -92,4 +93,4 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) + main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py similarity index 65% rename from examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py index ad13bd5f..75eb78fb 100755 --- a/examples/dfp/v201605/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all audience segments. - -To create audience segments, run create_audience_segments.py. +"""This example gets all audience segments. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,21 +23,22 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201605') + 'AudienceSegmentService', version='v201702') - # Create statement object to select all audience segments. + # Create a statement to select audience segments. statement = dfp.FilterStatement() - # Get audience segments by statement. + # Retrieve a small amount of audience segments at a time, paging + # through until all audience segments have been retrieved. while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for segment in response['results']: - print ('Audience segment with id \'%s\' and name ' - '\'%s\' of size %s was found.' % - (segment['id'], segment['name'], segment['size'])) + for audience_segment in response['results']: + # Print out some information for each audience segment. + print('Audience segment with ID "%d", name "%s", and size "%d" was ' + 'found.\n' % (audience_segment['id'], audience_segment['name'], + audience_segment['size'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py similarity index 59% rename from examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py index 45a2c437..eb59f816 100755 --- a/examples/dfp/v201605/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all first party audience segments. - -To create first party audience segments, run create_audience_segments.py. +"""This example gets all first party audience segments. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,30 +23,29 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201605') - - # Create statement object to only select first party audience segments. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }] - query = 'WHERE Type = :type' + 'AudienceSegmentService', version='v201702') + query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'FIRST_PARTY' + }}, + ] + # Create a statement to select audience segments. statement = dfp.FilterStatement(query, values) - # Get audience segments by statement. + # Retrieve a small amount of audience segments at a time, paging + # through until all audience segments have been retrieved. while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: - segments = response['results'] - for segment in segments: - print ('Audience segment with id \'%s\' and name \'%s\' of size ' - '%s was found. ' % - (segment['id'], segment['name'], segment['size'])) + for audience_segment in response['results']: + # Print out some information for each audience segment. + print('Audience segment with ID "%d", name "%s", and size "%d" was ' + 'found.\n' % (audience_segment['id'], audience_segment['name'], + audience_segment['size'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py similarity index 90% rename from examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py index 61bd1e32..905ca9d7 100755 --- a/examples/dfp/v201605/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py @@ -30,7 +30,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201605') + 'AudienceSegmentService', version='v201702') # Create statement object to get the specified first party audience segment. values = ( @@ -43,7 +43,7 @@ def main(client, audience_segment_id): {'key': 'audience_segment_id', 'value': { 'xsi_type': 'NumberValue', - 'value': AUDIENCE_SEGMENT_ID + 'value': audience_segment_id } }]) query = 'WHERE Type = :type AND Id = :audience_segment_id' @@ -56,8 +56,9 @@ def main(client, audience_segment_id): segments = response['results'] for segment in segments: - print ('Audience segment with id \'%s\' and name \'%s\' will be populated.' - % (segment['id'], segment['name'])) + print ( + 'Audience segment with id \'%s\' and name \'%s\' will be populated.' + % (segment['id'], segment['name'])) action = { 'xsi_type': 'PopulateAudienceSegments' diff --git a/examples/dfp/v201605/audience_segment_service/update_audience_segments.py b/examples/dfp/v201702/audience_segment_service/update_audience_segments.py similarity index 96% rename from examples/dfp/v201605/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201702/audience_segment_service/update_audience_segments.py index b03c84a7..9decb091 100755 --- a/examples/dfp/v201605/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/update_audience_segments.py @@ -29,7 +29,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201605') + 'AudienceSegmentService', version='v201702') # Create statement object to get the specified first party audience segment. values = ( @@ -42,7 +42,7 @@ def main(client, audience_segment_id): {'key': 'audience_segment_id', 'value': { 'xsi_type': 'NumberValue', - 'value': AUDIENCE_SEGMENT_ID + 'value': audience_segment_id } }]) query = 'WHERE Type = :type AND Id = :audience_segment_id' diff --git a/examples/dfp/v201605/base_rate_service/__init__.py b/examples/dfp/v201702/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201605/base_rate_service/__init__.py rename to examples/dfp/v201702/base_rate_service/__init__.py diff --git a/examples/dfp/v201605/base_rate_service/create_product_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201605/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201702/base_rate_service/create_product_base_rates.py index e4005425..4a7d1a58 100755 --- a/examples/dfp/v201605/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201605') + 'BaseRateService', version='v201702') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201605/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201605/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py index efd4dd08..a54399b6 100755 --- a/examples/dfp/v201605/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201605') + 'BaseRateService', version='v201702') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201605/base_rate_service/get_all_base_rates.py b/examples/dfp/v201702/base_rate_service/get_all_base_rates.py similarity index 62% rename from examples/dfp/v201605/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201702/base_rate_service/get_all_base_rates.py index 6918d1a2..e6d724cd 100755 --- a/examples/dfp/v201605/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/get_all_base_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,39 +13,31 @@ # 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 base rates. - -To create product base rates, run create_product_base_rates.py -To create product template base rates, run -create_product_template_base_rates.py. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201605') + base_rate_service = client.GetService('BaseRateService', version='v201702') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select base rates. + statement = dfp.FilterStatement() - # Get base rates by statement. + # Retrieve a small amount of base rates at a time, paging + # through until all base rates have been retrieved. while True: - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) + response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for base_rate in response['results']: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was found.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) + # Print out some information for each base rate. + print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' + 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/base_rate_service/get_base_rates_for_a_rate_card.py b/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py similarity index 57% rename from examples/dfp/v201605/base_rate_service/get_base_rates_for_a_rate_card.py rename to examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py index 5b9e610e..21863358 100755 --- a/examples/dfp/v201605/base_rate_service/get_base_rates_for_a_rate_card.py +++ b/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,16 +13,9 @@ # 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 base rates. - -To create product base rates, run create_product_base_rates.py -To create product template base rates, run -create_product_template_base_rates.py. - +"""This example gets all base rates belonging to a rate card. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -31,31 +24,30 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201605') - - # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'rateCardId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': rate_card_id - } - }] - query = 'where rateCardId = :rateCardId ORDER BY id ASC' + base_rate_service = client.GetService('BaseRateService', version='v201702') + query = 'WHERE rateCardId = :rateCardId' + values = [ + {'key': 'rateCardId', + 'value': { + 'xsi_type': 'TextValue', + 'value': rate_card_id + }}, + ] + # Create a statement to select base rates. statement = dfp.FilterStatement(query, values) - # Get base rates by statement. + # Retrieve a small amount of base rates at a time, paging + # through until all base rates have been retrieved. while True: - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) + response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for base_rate in response['results']: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was found.' % ( - base_rate['id'], - dfp.DfpClassType(base_rate), - base_rate['rateCardId'])) + # Print out some information for each base rate. + print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' + 'found.\n' % + (base_rate['id'], dfp.DfpClassType(base_rate), + base_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/base_rate_service/update_base_rates.py b/examples/dfp/v201702/base_rate_service/update_base_rates.py similarity index 99% rename from examples/dfp/v201605/base_rate_service/update_base_rates.py rename to examples/dfp/v201702/base_rate_service/update_base_rates.py index 34147f30..2c5edad7 100755 --- a/examples/dfp/v201605/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201605') + base_rate_service = client.GetService('BaseRateService', version='v201702') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201605/company_service/__init__.py b/examples/dfp/v201702/company_service/__init__.py similarity index 100% rename from examples/dfp/v201605/company_service/__init__.py rename to examples/dfp/v201702/company_service/__init__.py diff --git a/examples/dfp/v201605/company_service/create_companies.py b/examples/dfp/v201702/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201605/company_service/create_companies.py rename to examples/dfp/v201702/company_service/create_companies.py index e1ea337a..1882bd4b 100755 --- a/examples/dfp/v201605/company_service/create_companies.py +++ b/examples/dfp/v201702/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201605') + company_service = client.GetService('CompanyService', version='v201702') # Create company objects. companies = [ diff --git a/examples/dfp/v201605/company_service/get_all_companies.py b/examples/dfp/v201702/company_service/get_advertisers.py similarity index 59% rename from examples/dfp/v201605/company_service/get_all_companies.py rename to examples/dfp/v201702/company_service/get_advertisers.py index e3f361f9..4e105f9c 100755 --- a/examples/dfp/v201605/company_service/get_all_companies.py +++ b/examples/dfp/v201702/company_service/get_advertisers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,43 @@ # 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 code example gets all companies. - -To create companies, run create_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all companies that are advertisers. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201605') - - # Create statement object to select all companies. - statement = dfp.FilterStatement() - - # Get companies by statement. + company_service = client.GetService('CompanyService', version='v201702') + query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ADVERTISER' + }}, + ] + # Create a statement to select companies. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of companies at a time, paging + # through until all companies have been retrieved. while True: - response = company_service.getCompaniesByStatement( - statement.ToStatement()) + response = company_service.getCompaniesByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for company in response['results']: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was found.' - % (company['id'], company['name'], company['type'])) + # Print out some information for each company. + print('Company with ID "%d", name "%s", and type "%s" was found.\n' % + (company['id'], company['name'], company['type'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/company_service/get_all_companies.py b/examples/dfp/v201702/company_service/get_all_companies.py new file mode 100755 index 00000000..ea05fe58 --- /dev/null +++ b/examples/dfp/v201702/company_service/get_all_companies.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 companies. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + company_service = client.GetService('CompanyService', version='v201702') + + # Create a statement to select companies. + statement = dfp.FilterStatement() + + # Retrieve a small amount of companies at a time, paging + # through until all companies have been retrieved. + while True: + response = company_service.getCompaniesByStatement(statement.ToStatement()) + if 'results' in response: + for company in response['results']: + # Print out some information for each company. + print('Company with ID "%d", name "%s", and type "%s" was found.\n' % + (company['id'], company['name'], company['type'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/company_service/update_companies.py b/examples/dfp/v201702/company_service/update_companies.py similarity index 99% rename from examples/dfp/v201605/company_service/update_companies.py rename to examples/dfp/v201702/company_service/update_companies.py index 3ec15248..764898e5 100755 --- a/examples/dfp/v201605/company_service/update_companies.py +++ b/examples/dfp/v201702/company_service/update_companies.py @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201605') + company_service = client.GetService('CompanyService', version='v201702') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201605/contact_service/__init__.py b/examples/dfp/v201702/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201605/contact_service/__init__.py rename to examples/dfp/v201702/contact_service/__init__.py diff --git a/examples/dfp/v201605/contact_service/create_contacts.py b/examples/dfp/v201702/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201605/contact_service/create_contacts.py rename to examples/dfp/v201702/contact_service/create_contacts.py index 8a36cb8e..a9b1a54a 100755 --- a/examples/dfp/v201605/contact_service/create_contacts.py +++ b/examples/dfp/v201702/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201605') + contact_service = client.GetService('ContactService', version='v201702') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201702/contact_service/get_all_contacts.py b/examples/dfp/v201702/contact_service/get_all_contacts.py new file mode 100755 index 00000000..82e8cd04 --- /dev/null +++ b/examples/dfp/v201702/contact_service/get_all_contacts.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 contacts. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + contact_service = client.GetService('ContactService', version='v201702') + + # Create a statement to select contacts. + statement = dfp.FilterStatement() + + # Retrieve a small amount of contacts at a time, paging + # through until all contacts have been retrieved. + while True: + response = contact_service.getContactsByStatement(statement.ToStatement()) + if 'results' in response: + for contact in response['results']: + # Print out some information for each contact. + print('Contact with ID "%d" and name "%s" was found.\n' % + (contact['id'], contact['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/contact_service/get_all_contacts.py b/examples/dfp/v201702/contact_service/get_uninvited_contacts.py similarity index 60% rename from examples/dfp/v201605/contact_service/get_all_contacts.py rename to examples/dfp/v201702/contact_service/get_uninvited_contacts.py index 96b1da55..e6a4b8fd 100755 --- a/examples/dfp/v201605/contact_service/get_all_contacts.py +++ b/examples/dfp/v201702/contact_service/get_uninvited_contacts.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,45 +13,43 @@ # 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 code example gets all contacts. - -To create contacts, run create_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all contacts that aren't invited yet. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201605') - - # Create statement object to get all contacts. - statement = dfp.FilterStatement() - - # Get contacts by statement. + contact_service = client.GetService('ContactService', version='v201702') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'UNINVITED' + }}, + ] + # Create a statement to select contacts. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of contacts at a time, paging + # through until all contacts have been retrieved. while True: - response = contact_service.getContactsByStatement( - statement.ToStatement()) + response = contact_service.getContactsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for contact in response['results']: - print ('Contact with ID \'%s\' and name \'%s\' was found.' - % (contact['id'], contact['name'])) + # Print out some information for each contact. + print('Contact with ID "%d" and name "%s" was found.\n' % + (contact['id'], contact['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/contact_service/update_contacts.py b/examples/dfp/v201702/contact_service/update_contacts.py similarity index 99% rename from examples/dfp/v201605/contact_service/update_contacts.py rename to examples/dfp/v201702/contact_service/update_contacts.py index afc37eb9..b851bda0 100755 --- a/examples/dfp/v201605/contact_service/update_contacts.py +++ b/examples/dfp/v201702/contact_service/update_contacts.py @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201605') + contact_service = client.GetService('ContactService', version='v201702') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201605/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201605/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201605/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201605/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 5e08ef12..557fc76c 100755 --- a/examples/dfp/v201605/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201605') + 'ContentMetadataKeyHierarchyService', version='v201702') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201605/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201605/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index cbacd5d0..86f8426b 100755 --- a/examples/dfp/v201605/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201605') + 'ContentMetadataKeyHierarchyService', version='v201702') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py new file mode 100755 index 00000000..05142739 --- /dev/null +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2016 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 content metadata key hierarchies. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + content_metadata_key_hierarchy_service = client.GetService( + 'ContentMetadataKeyHierarchyService', version='v201702') + + # Create a statement to select content metadata key hierarchies. + statement = dfp.FilterStatement() + + # Retrieve a small amount of content metadata key hierarchies at a time, + # paging through until all content metadata key hierarchies have been + # retrieved. + while True: + response = ( + content_metadata_key_hierarchy_service + .getContentMetadataKeyHierarchiesByStatement( + statement.ToStatement())) + if 'results' in response: + for content_metadata_key_hierarchy in response['results']: + # Print out some information for each content metadata key hierarchy. + print('Content metadata key hierarchy with ID "%d" and name "%s" was ' + 'found.\n' % (content_metadata_key_hierarchy['id'], + content_metadata_key_hierarchy['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 98% rename from examples/dfp/v201605/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 9608dc9e..8e165a40 100755 --- a/examples/dfp/v201605/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201605') + 'ContentMetadataKeyHierarchyService', version='v201702') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201605/content_service/__init__.py b/examples/dfp/v201702/content_service/__init__.py similarity index 100% rename from examples/dfp/v201605/content_service/__init__.py rename to examples/dfp/v201702/content_service/__init__.py diff --git a/examples/dfp/v201702/content_service/get_all_content.py b/examples/dfp/v201702/content_service/get_all_content.py new file mode 100755 index 00000000..8954f123 --- /dev/null +++ b/examples/dfp/v201702/content_service/get_all_content.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 content. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + content_service = client.GetService('ContentService', version='v201702') + + # Create a statement to select content. + statement = dfp.FilterStatement() + + # Retrieve a small amount of content at a time, paging + # through until all content have been retrieved. + while True: + response = content_service.getContentByStatement(statement.ToStatement()) + if 'results' in response: + for content in response['results']: + # Print out some information for each content. + print('Content with ID "%d" and name "%s" was found.\n' % + (content['id'], content['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/creative_service/__init__.py b/examples/dfp/v201702/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201605/creative_service/__init__.py rename to examples/dfp/v201702/creative_service/__init__.py diff --git a/examples/dfp/v201605/creative_service/create_creative_from_template.py b/examples/dfp/v201702/creative_service/create_creative_from_template.py similarity index 91% rename from examples/dfp/v201605/creative_service/create_creative_from_template.py rename to examples/dfp/v201702/creative_service/create_creative_from_template.py index 9134d94e..714abc9a 100755 --- a/examples/dfp/v201605/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201702/creative_service/create_creative_from_template.py @@ -41,27 +41,39 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201605') + creative_service = client.GetService('CreativeService', version='v201702') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' + # Create image asset. + file_name = 'image%s.jpg' % uuid.uuid4() image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() image_data = base64.encodestring(image_data) + size = { + 'width': '300', + 'height': '250' + } + asset = { + 'xsi_type': 'CreativeAsset', + 'fileName': file_name, + 'assetByteArray': image_data, + 'size': size + } + # Create creative from templates. creative = { 'xsi_type': 'TemplateCreative', 'name': 'Template Creative #%s' % uuid.uuid4(), 'advertiserId': advertiser_id, - 'size': {'width': '300', 'height': '250'}, + 'size': size, 'creativeTemplateId': creative_template_id, 'creativeTemplateVariableValues': [ { 'xsi_type': 'AssetCreativeTemplateVariableValue', 'uniqueName': 'Imagefile', - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() + 'asset': asset }, { 'xsi_type': 'LongCreativeTemplateVariableValue', diff --git a/examples/dfp/v201605/creative_service/create_creatives.py b/examples/dfp/v201702/creative_service/create_creatives.py similarity index 98% rename from examples/dfp/v201605/creative_service/create_creatives.py rename to examples/dfp/v201702/creative_service/create_creatives.py index 48fee463..a598af5f 100755 --- a/examples/dfp/v201605/creative_service/create_creatives.py +++ b/examples/dfp/v201702/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201605') + creative_service = client.GetService('CreativeService', version='v201702') # Create creative objects. creatives = [] @@ -48,7 +48,7 @@ def main(client, advertiser_id): 'medium_rectangle.jpg'), 'r') as image: image_data = base64.encodestring(image.read()) - for i in xrange(5): + for _ in xrange(5): # Create creative size. size = { 'width': '300', diff --git a/examples/dfp/v201605/creative_service/create_custom_creative.py b/examples/dfp/v201702/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201605/creative_service/create_custom_creative.py rename to examples/dfp/v201702/creative_service/create_custom_creative.py index e465eae8..76ef336f 100755 --- a/examples/dfp/v201605/creative_service/create_custom_creative.py +++ b/examples/dfp/v201702/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201605') + creative_service = client.GetService('CreativeService', version='v201702') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201605/creative_service/create_native_creative.py b/examples/dfp/v201702/creative_service/create_native_creative.py similarity index 99% rename from examples/dfp/v201605/creative_service/create_native_creative.py rename to examples/dfp/v201702/creative_service/create_native_creative.py index 30dc8fec..e5e97f84 100755 --- a/examples/dfp/v201605/creative_service/create_native_creative.py +++ b/examples/dfp/v201702/creative_service/create_native_creative.py @@ -46,7 +46,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201605') + creative_service = client.GetService('CreativeService', version='v201702') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/dfp/v201702/creative_service/get_all_creatives.py b/examples/dfp/v201702/creative_service/get_all_creatives.py new file mode 100755 index 00000000..ac1509ee --- /dev/null +++ b/examples/dfp/v201702/creative_service/get_all_creatives.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creatives. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201702') + + # Create a statement to select creatives. + statement = dfp.FilterStatement() + + # Retrieve a small amount of creatives at a time, paging + # through until all creatives have been retrieved. + while True: + response = creative_service.getCreativesByStatement(statement.ToStatement()) + if 'results' in response: + for creative in response['results']: + # Print out some information for each creative. + print('Creative with ID "%d" and name "%s" was found.\n' % + (creative['id'], creative['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/creative_service/get_all_creatives.py b/examples/dfp/v201702/creative_service/get_image_creatives.py similarity index 57% rename from examples/dfp/v201605/creative_service/get_all_creatives.py rename to examples/dfp/v201702/creative_service/get_image_creatives.py index d771703b..412126d9 100755 --- a/examples/dfp/v201605/creative_service/get_all_creatives.py +++ b/examples/dfp/v201702/creative_service/get_image_creatives.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,46 +13,43 @@ # 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 code example gets all creatives. - -To create creatives, run create_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all image creatives. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201605') - - # Create statement object to select all creatives. - statement = dfp.FilterStatement() - - # Get creatives by statement. + creative_service = client.GetService('CreativeService', version='v201702') + query = 'WHERE creativeType = :creativeType' + values = [ + {'key': 'creativeType', + 'value': { + 'xsi_type': 'TextValue', + 'value': '_image_creative' + }}, + ] + # Create a statement to select creatives. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of creatives at a time, paging + # through until all creatives have been retrieved. while True: - response = creative_service.getCreativesByStatement( - statement.ToStatement()) + response = creative_service.getCreativesByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for creative in response['results']: - print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was ' - 'found.' % (creative['id'], creative['name'], - dfp.DfpClassType(creative))) + # Print out some information for each creative. + print('Creative with ID "%d" and name "%s" was found.\n' % + (creative['id'], creative['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/creative_service/update_creatives.py b/examples/dfp/v201702/creative_service/update_creatives.py similarity index 99% rename from examples/dfp/v201605/creative_service/update_creatives.py rename to examples/dfp/v201702/creative_service/update_creatives.py index 62da60f3..69be89a1 100755 --- a/examples/dfp/v201605/creative_service/update_creatives.py +++ b/examples/dfp/v201702/creative_service/update_creatives.py @@ -34,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201605') + creative_service = client.GetService('CreativeService', version='v201702') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201605/creative_set_service/__init__.py b/examples/dfp/v201702/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201605/creative_set_service/__init__.py rename to examples/dfp/v201702/creative_set_service/__init__.py diff --git a/examples/dfp/v201605/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py similarity index 92% rename from examples/dfp/v201605/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py index 2eeb0c80..1aaec355 100755 --- a/examples/dfp/v201605/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates a line item creative association for a creative -set. +"""Creates a line item creative association for a creative set. To create creative sets, run create_creative_set.py. To create creatives, run create_creatives.py. To determine which LICAs exist, run get_all_licas.py. @@ -38,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201605') + 'LineItemCreativeAssociationService', version='v201702') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201605/creative_set_service/create_creative_set.py b/examples/dfp/v201702/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201605/creative_set_service/create_creative_set.py rename to examples/dfp/v201702/creative_set_service/create_creative_set.py index fb833495..c87f7837 100755 --- a/examples/dfp/v201605/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201702/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201605') + version='v201702') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201605/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py similarity index 61% rename from examples/dfp/v201605/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201702/creative_set_service/get_all_creative_sets.py index acaf3dca..267e1a64 100755 --- a/examples/dfp/v201605/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,46 +13,38 @@ # 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 code example gets all creative sets. - -To create creative sets, run create_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all creative sets. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201605') + creative_set_service = client.GetService( + 'CreativeSetService', version='v201702') - # Create a filter statement. + # Create a statement to select creative sets. statement = dfp.FilterStatement() - # Get creative sets by statement. + # Retrieve a small amount of creative sets at a time, paging + # through until all creative sets have been retrieved. while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for creative_set in response['results']: - print ('Creative set with ID \'%s\' and name \'%s\' was found.' - % (creative_set['id'], creative_set['name'])) + # Print out some information for each creative set. + print('Creative set with ID "%d" and name "%s" was found.\n' % + (creative_set['id'], creative_set['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/creative_set_service/get_creative_sets_by_statement.py b/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py similarity index 54% rename from examples/dfp/v201605/creative_set_service/get_creative_sets_by_statement.py rename to examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py index 06fb4141..5f2f3051 100755 --- a/examples/dfp/v201605/creative_set_service/get_creative_sets_by_statement.py +++ b/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 code example gets all creative sets for a master creative. - -To create creative sets, run create_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all creative sets for a master creative. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -34,38 +24,36 @@ def main(client, master_creative_id): # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201605') - - # Create statement object to only select creative sets that have the given - # master creative. - values = [{ - 'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': master_creative_id - } - }] + creative_set_service = client.GetService( + 'CreativeSetService', version='v201702') query = 'WHERE masterCreativeId = :masterCreativeId' + values = [ + {'key': 'masterCreativeId', + 'value': { + 'xsi_type': 'TextValue', + 'value': master_creative_id + }}, + ] + # Create a statement to select creative sets. statement = dfp.FilterStatement(query, values) - # Get creative sets by statement. + # Retrieve a small amount of creative sets at a time, paging + # through until all creative sets have been retrieved. while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for creative_set in response['results']: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' - 'companion creative IDs {%s} was found.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) + # Print out some information for each creative set. + print('Creative set with ID "%d" and name "%s" was found.\n' % + (creative_set['id'], creative_set['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/creative_set_service/update_creative_set.py b/examples/dfp/v201702/creative_set_service/update_creative_set.py similarity index 97% rename from examples/dfp/v201605/creative_set_service/update_creative_set.py rename to examples/dfp/v201702/creative_set_service/update_creative_set.py index d5a40595..1d58c518 100755 --- a/examples/dfp/v201605/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201702/creative_set_service/update_creative_set.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201605') + version='v201702') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201605/creative_template_service/__init__.py b/examples/dfp/v201702/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201605/creative_template_service/__init__.py rename to examples/dfp/v201702/creative_template_service/__init__.py diff --git a/examples/dfp/v201605/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py similarity index 61% rename from examples/dfp/v201605/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201702/creative_template_service/get_all_creative_templates.py index 052325ff..b3985406 100755 --- a/examples/dfp/v201605/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,17 +13,9 @@ # 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 code example gets all creative templates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all creative templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -31,28 +23,28 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201605') + 'CreativeTemplateService', version='v201702') - # Create a filter statement. + # Create a statement to select creative templates. statement = dfp.FilterStatement() - # Get creative templates by statement. + # Retrieve a small amount of creative templates at a time, paging + # through until all creative templates have been retrieved. while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for template in response['results']: - print ('Creative template with id \'%s\', name \'%s\', and type \'%s\' ' - 'was found.' % (template['id'], - template['name'], - template['type'])) + for creative_template in response['results']: + # Print out some information for each creative template. + print('Creative template with ID "%d" and name "%s" was found.\n' % + (creative_template['id'], creative_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_keys_by_statement.py b/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py similarity index 56% rename from examples/dfp/v201605/custom_targeting_service/get_custom_targeting_keys_by_statement.py rename to examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py index 086d003f..aa9fe7d5 100755 --- a/examples/dfp/v201605/custom_targeting_service/get_custom_targeting_keys_by_statement.py +++ b/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,48 +13,45 @@ # 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 predefined custom targeting keys. - -To create custom targeting keys, run create_custom_targeting_keys_and_values.py. +"""This example gets all system defined creative templates. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') - - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] + creative_template_service = client.GetService( + 'CreativeTemplateService', version='v201702') query = 'WHERE type = :type' + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'SYSTEM_DEFINED' + }}, + ] + # Create a statement to select creative templates. statement = dfp.FilterStatement(query, values) - # Get custom targeting keys by statement. + # Retrieve a small amount of creative templates at a time, paging + # through until all creative templates have been retrieved. while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( + response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for key in response['results']: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was found.' - % (key['id'], key['name'], key['displayName'], key['type'])) + for creative_template in response['results']: + # Print out some information for each creative template. + print('Creative template with ID "%d" and name "%s" was found.\n' % + (creative_template['id'], creative_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/dfp/v201605/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py index bfbfbac4..0454a5f6 100755 --- a/examples/dfp/v201605/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201605') + version='v201702') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201605/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 97% rename from examples/dfp/v201605/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py index 32c67123..49abdeab 100755 --- a/examples/dfp/v201605/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201605') + version='v201702') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201605/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py similarity index 58% rename from examples/dfp/v201605/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py index ba9bd354..306379bc 100755 --- a/examples/dfp/v201605/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,46 +13,45 @@ # 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 code example gets all creative wrappers. - -To create creative wrappers, run create_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all active creative wrappers. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201605') - - # Create a filter statement. - statement = dfp.FilterStatement() - - # Get creative wrappers by statement. + creative_wrapper_service = client.GetService( + 'CreativeWrapperService', version='v201702') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select creative wrappers. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of creative wrappers at a time, paging + # through until all creative wrappers have been retrieved. while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' - 'found.' % (creative_wrapper['id'], creative_wrapper['labelId'])) + # Print out some information for each creative wrapper. + print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % + (creative_wrapper['id'], creative_wrapper['labelId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py new file mode 100755 index 00000000..eaf5598b --- /dev/null +++ b/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creative wrappers. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + creative_wrapper_service = client.GetService( + 'CreativeWrapperService', version='v201702') + + # Create a statement to select creative wrappers. + statement = dfp.FilterStatement() + + # Retrieve a small amount of creative wrappers at a time, paging + # through until all creative wrappers have been retrieved. + while True: + response = creative_wrapper_service.getCreativeWrappersByStatement( + statement.ToStatement()) + if 'results' in response: + for creative_wrapper in response['results']: + # Print out some information for each creative wrapper. + print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % + (creative_wrapper['id'], creative_wrapper['labelId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py similarity index 97% rename from examples/dfp/v201605/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py index 1eb8ae0e..82e240a6 100755 --- a/examples/dfp/v201605/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201605') + version='v201702') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201605/custom_field_service/__init__.py b/examples/dfp/v201702/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201605/custom_field_service/__init__.py rename to examples/dfp/v201702/custom_field_service/__init__.py diff --git a/examples/dfp/v201605/custom_field_service/create_custom_field_options.py b/examples/dfp/v201702/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201605/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201702/custom_field_service/create_custom_field_options.py index 4835ec5c..7e7bde3f 100755 --- a/examples/dfp/v201605/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201702/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201605') + 'CustomFieldService', version='v201702') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201605/custom_field_service/create_custom_fields.py b/examples/dfp/v201702/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201605/custom_field_service/create_custom_fields.py rename to examples/dfp/v201702/custom_field_service/create_custom_fields.py index 2cff40e9..5f920c72 100755 --- a/examples/dfp/v201605/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201605') + 'CustomFieldService', version='v201702') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201605/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 98% rename from examples/dfp/v201605/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py index 34e8e152..9372c683 100755 --- a/examples/dfp/v201605/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201605') + 'CustomFieldService', version='v201702') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201605/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py similarity index 67% rename from examples/dfp/v201605/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201702/custom_field_service/get_all_custom_fields.py index 140bd2fe..8d5becbf 100755 --- a/examples/dfp/v201605/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 fields. - -To create custom fields, run create_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,26 +23,28 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201605') + 'CustomFieldService', version='v201702') - # Create a filter statement. + # Create a statement to select custom fields. statement = dfp.FilterStatement() - # Get custom fields by statement. + # Retrieve a small amount of custom fields at a time, paging + # through until all custom fields have been retrieved. while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' was found.' - % (custom_field['id'], custom_field['name'])) + # Print out some information for each custom field. + print('Custom field with ID "%d" and name "%s" was found.\n' % + (custom_field['id'], custom_field['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/custom_field_service/get_all_line_item_custom_fields.py b/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py similarity index 59% rename from examples/dfp/v201605/custom_field_service/get_all_line_item_custom_fields.py rename to examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py index 0cca03b8..5bdefdaf 100755 --- a/examples/dfp/v201605/custom_field_service/get_all_line_item_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 fields that apply to line items. - -To create custom fields, run create_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all custom fields that can be applied to line items. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,36 +23,35 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201605') - - # Create statement to select only custom fields that apply to line items. - values = [{ - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }] + 'CustomFieldService', version='v201702') query = 'WHERE entityType = :entityType' - - # Create a filter statement. + values = [ + {'key': 'entityType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'LINE_ITEM' + }}, + ] + # Create a statement to select custom fields. statement = dfp.FilterStatement(query, values) - # Get custom fields by statement. + # Retrieve a small amount of custom fields at a time, paging + # through until all custom fields have been retrieved. while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' was found.' - % (custom_field['id'], custom_field['name'])) + # Print out some information for each custom field. + print('Custom field with ID "%d" and name "%s" was found.\n' % + (custom_field['id'], custom_field['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201605/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py index 45b651df..5ff05a70 100755 --- a/examples/dfp/v201605/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201605') + 'CustomFieldService', version='v201702') - line_item_service = client.GetService('LineItemService', version='v201605') + line_item_service = client.GetService('LineItemService', version='v201702') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201605/custom_field_service/update_custom_fields.py b/examples/dfp/v201702/custom_field_service/update_custom_fields.py similarity index 98% rename from examples/dfp/v201605/custom_field_service/update_custom_fields.py rename to examples/dfp/v201702/custom_field_service/update_custom_fields.py index 9ef155f1..a3870535 100755 --- a/examples/dfp/v201605/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/update_custom_fields.py @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201605') + 'CustomFieldService', version='v201702') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201605/custom_targeting_service/__init__.py b/examples/dfp/v201702/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201605/custom_targeting_service/__init__.py rename to examples/dfp/v201702/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py index 9da61c0f..cb288480 100755 --- a/examples/dfp/v201605/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') + 'CustomTargetingService', version='v201702') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py similarity index 98% rename from examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py index 547145f0..74f8fc70 100755 --- a/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') + 'CustomTargetingService', version='v201702') values = [{ 'key': 'name', diff --git a/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py index 694c4aef..fadd57cb 100755 --- a/examples/dfp/v201605/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example deletes custom targeting values for a given custom targeting -key. +"""Deletes custom targeting values for a given custom targeting key. To determine which custom targeting keys and values exist, run get_all_custom_targeting_keys_and_values.py. @@ -37,7 +36,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') + 'CustomTargetingService', version='v201702') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..1912920e --- /dev/null +++ b/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# +# Copyright 2016 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 targeting keys and values. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201702') + + # Create statement to get all targeting keys. + targeting_key_statement = dfp.FilterStatement() + + all_keys = [] + + # Get custom targeting keys by statement. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + targeting_key_statement.ToStatement()) + if 'results' in response: + all_keys.extend(response['results']) + targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + if all_keys: + # Create a statement to select custom targeting values. + query = ('WHERE customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys])) + statement = dfp.FilterStatement(query) + + # Retreive a small amount of custom targeting values at a time, paging + # through until all custom targeting values have been retrieved. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response: + for custom_targeting_value in response['results']: + # Print out some information for each custom targeting value. + print('Custom targeting value with ID "%d", name "%s", display name ' + '"%s", and custom targeting key ID "%d" was found.\n' % + (custom_targeting_value['id'], custom_targeting_value['name'], + custom_targeting_value['displayName'], + custom_targeting_value['customTargetingKeyId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..c60ab7f6 --- /dev/null +++ b/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# +# Copyright 2016 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 targeting keys and values. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201702') + + # Create statement to get targeting keys for predefined values. + query = ('WHERE type = :type') + values = [{ + 'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PREDEFINED' + } + }] + targeting_key_statement = dfp.FilterStatement(query, values) + + all_keys = [] + + # Get custom targeting keys by statement. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + targeting_key_statement.ToStatement()) + if 'results' in response: + all_keys.extend(response['results']) + targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + if all_keys: + # Create a statement to select custom targeting values. + query = ('WHERE customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys])) + statement = dfp.FilterStatement(query) + + # Retreive a small amount of custom targeting values at a time, paging + # through until all custom targeting values have been retrieved. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response: + for custom_targeting_value in response['results']: + # Print out some information for each custom targeting value. + print('Custom targeting value with ID "%d", name "%s", display name ' + '"%s", and custom targeting key ID "%d" was found.\n' % + (custom_targeting_value['id'], custom_targeting_value['name'], + custom_targeting_value['displayName'], + custom_targeting_value['customTargetingKeyId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/dfp/v201605/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py index 2b47509b..3cf70d6c 100755 --- a/examples/dfp/v201605/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py @@ -17,7 +17,8 @@ """This example updates the display name of a single custom targeting key. To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') + 'CustomTargetingService', version='v201702') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201605/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py similarity index 91% rename from examples/dfp/v201605/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py index 10ba2325..2bd9b015 100755 --- a/examples/dfp/v201605/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates the display name of the custom targeting values -belonging to a custom targeting key. +"""Updates name of custom targeting values belonging to a custom targeting key. To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" # Import appropriate modules from the client library. @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201605') + 'CustomTargetingService', version='v201702') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201605/exchange_rate_service/__init__.py b/examples/dfp/v201702/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201605/exchange_rate_service/__init__.py rename to examples/dfp/v201702/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201605/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201605/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py index 40df526f..8b93ea62 100755 --- a/examples/dfp/v201605/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201605') + version='v201702') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201605/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py similarity index 57% rename from examples/dfp/v201605/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py index 37389725..333120b7 100755 --- a/examples/dfp/v201605/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,40 +13,34 @@ # 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 code example gets all exchange rates. - -To create exchange rates, run create_exchange_rates.py. - +"""This example gets all exchange rates. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201605') + exchange_rate_service = client.GetService( + 'ExchangeRateService', version='v201702') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select exchange rates. + statement = dfp.FilterStatement() - # Get all exchange rates by statement. + # Retrieve a small amount of exchange rates at a time, paging + # through until all exchange rates have been retrieved. while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for exchange_rate in response['results']: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was found.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + # Print out some information for each exchange rate. + print( + 'Exchange rate with ID "%d", currency code "%s", direction "%s", ' + 'and exchange rate "%d" was found.\n' % + (exchange_rate['id'], exchange_rate['currencyCode'], + exchange_rate['direction'], exchange_rate['exchangeRate'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/exchange_rate_service/get_exchange_rates_by_currency_code.py b/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 59% rename from examples/dfp/v201605/exchange_rate_service/get_exchange_rates_by_currency_code.py rename to examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py index 0f0b8f31..e592f678 100755 --- a/examples/dfp/v201605/exchange_rate_service/get_exchange_rates_by_currency_code.py +++ b/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 the exchange rate for a specific currency code. - -To create exchange rates, run create_exchange_rates.py. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -29,35 +24,31 @@ def main(client, currency_code): # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201605') - - # Create a statement to get exchange rates for the specified currency code. - values = [{ - 'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - } - }] + exchange_rate_service = client.GetService( + 'ExchangeRateService', version='v201702') query = 'WHERE currencyCode = :currencyCode' - # Create a filter statement. + values = [ + {'key': 'currencyCode', + 'value': { + 'xsi_type': 'TextValue', + 'value': currency_code + }}, + ] + # Create a statement to select exchange rates. statement = dfp.FilterStatement(query, values) - # Get rate cards by statement. + # Retrieve a small amount of exchange rates at a time, paging + # through until all exchange rates have been retrieved. while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for exchange_rate in response['results']: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was found.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + # Print out some information for each exchange rate. + print('Exchange rate with ID "%d", currency code "%s", and exchange ' + 'rate "%.2f" was found.\n' % + (exchange_rate['id'], exchange_rate['currencyCode'], + float(exchange_rate['exchangeRate'] / 1000000))) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py similarity index 97% rename from examples/dfp/v201605/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py index 3cd457f2..edaf956e 100755 --- a/examples/dfp/v201605/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201605') + version='v201702') # Create a statement to get an exchange rate by its ID. values = [{ diff --git a/examples/dfp/v201605/forecast_service/get_availability_forecast.py b/examples/dfp/v201702/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/dfp/v201605/forecast_service/get_availability_forecast.py rename to examples/dfp/v201702/forecast_service/get_availability_forecast.py index 9f7290e2..7fc3b7fb 100755 --- a/examples/dfp/v201605/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201702/forecast_service/get_availability_forecast.py @@ -36,8 +36,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201605') - network_service = client.GetService('NetworkService', version='v201605') + forecast_service = client.GetService('ForecastService', version='v201702') + network_service = client.GetService('NetworkService', version='v201702') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201605/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/dfp/v201605/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py index a380f171..d44f1529 100755 --- a/examples/dfp/v201605/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201605') + forecast_service = client.GetService('ForecastService', version='v201702') # Set forecasting options. forecast_options = { diff --git a/examples/dfp/v201605/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/dfp/v201605/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py index 979f55f6..c9395870 100755 --- a/examples/dfp/v201605/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201605') + forecast_service = client.GetService('ForecastService', version='v201702') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201605/inventory_service/__init__.py b/examples/dfp/v201702/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201605/inventory_service/__init__.py rename to examples/dfp/v201702/inventory_service/__init__.py diff --git a/examples/dfp/v201605/inventory_service/archive_ad_units.py b/examples/dfp/v201702/inventory_service/archive_ad_units.py similarity index 99% rename from examples/dfp/v201605/inventory_service/archive_ad_units.py rename to examples/dfp/v201702/inventory_service/archive_ad_units.py index 4e0b3f02..b166dc31 100755 --- a/examples/dfp/v201605/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201702/inventory_service/archive_ad_units.py @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201605') + inventory_service = client.GetService('InventoryService', version='v201702') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201605/inventory_service/create_ad_units.py b/examples/dfp/v201702/inventory_service/create_ad_units.py similarity index 99% rename from examples/dfp/v201605/inventory_service/create_ad_units.py rename to examples/dfp/v201702/inventory_service/create_ad_units.py index fc55f9b6..f7b8aeb1 100755 --- a/examples/dfp/v201605/inventory_service/create_ad_units.py +++ b/examples/dfp/v201702/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201605') + inventory_service = client.GetService('InventoryService', version='v201702') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201605/network_service/get_current_network.py b/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py similarity index 52% rename from examples/dfp/v201605/network_service/get_current_network.py rename to examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py index ade4c633..5cc3ffdf 100755 --- a/examples/dfp/v201605/network_service/get_current_network.py +++ b/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,9 +13,8 @@ # 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 the current network that you can make requests against.""" - +"""This example gets all ad unit sizes. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -23,14 +22,23 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201605') - - # Get the current network. - network = network_service.getCurrentNetwork() + ad_unit_size_service = client.GetService( + 'InventoryService', version='v201702') + + # Create a statement to select ad unit sizes. + statement = dfp.FilterStatement() + + # Retreive a small amount of ad unit sizes at a time, paging + # through until all ad unit sizes have been retrieved. + response = ad_unit_size_service.getAdUnitSizesByStatement( + statement.ToStatement()) + if response: + for ad_unit_size in response: + # Print out some information for each ad unit size. + if 'fullDisplayString' in ad_unit_size: + print('Ad unit size with dimensions "%s" was found.\n' % + (ad_unit_size['fullDisplayString'])) - # Display results. - print ('Current network has network code \'%s\' and display name \'%s\'.' - % (network['networkCode'], network['displayName'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_units.py b/examples/dfp/v201702/inventory_service/get_all_ad_units.py new file mode 100755 index 00000000..cab564b9 --- /dev/null +++ b/examples/dfp/v201702/inventory_service/get_all_ad_units.py @@ -0,0 +1,49 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + ad_unit_service = client.GetService('InventoryService', version='v201702') + + # Create a statement to select ad units. + statement = dfp.FilterStatement() + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response: + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/inventory_service/update_ad_units.py b/examples/dfp/v201702/inventory_service/update_ad_units.py similarity index 99% rename from examples/dfp/v201605/inventory_service/update_ad_units.py rename to examples/dfp/v201702/inventory_service/update_ad_units.py index b1b2e26b..9d891df9 100755 --- a/examples/dfp/v201605/inventory_service/update_ad_units.py +++ b/examples/dfp/v201702/inventory_service/update_ad_units.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201605') + inventory_service = client.GetService('InventoryService', version='v201702') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201605/label_service/__init__.py b/examples/dfp/v201702/label_service/__init__.py similarity index 100% rename from examples/dfp/v201605/label_service/__init__.py rename to examples/dfp/v201702/label_service/__init__.py diff --git a/examples/dfp/v201605/label_service/create_labels.py b/examples/dfp/v201702/label_service/create_labels.py similarity index 96% rename from examples/dfp/v201605/label_service/create_labels.py rename to examples/dfp/v201702/label_service/create_labels.py index 9cbfc220..261bbb4c 100755 --- a/examples/dfp/v201605/label_service/create_labels.py +++ b/examples/dfp/v201702/label_service/create_labels.py @@ -17,7 +17,8 @@ """This code example creates new labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" import uuid @@ -28,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201605') + label_service = client.GetService('LabelService', version='v201702') # Create label objects. labels = [] diff --git a/examples/dfp/v201605/label_service/deactivate_labels.py b/examples/dfp/v201702/label_service/deactivate_labels.py similarity index 97% rename from examples/dfp/v201605/label_service/deactivate_labels.py rename to examples/dfp/v201702/label_service/deactivate_labels.py index 99a72617..c08bf233 100755 --- a/examples/dfp/v201605/label_service/deactivate_labels.py +++ b/examples/dfp/v201702/label_service/deactivate_labels.py @@ -17,7 +17,8 @@ """This code example deactivates all active Labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" # Import appropriate modules from the client library. @@ -26,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201605') + label_service = client.GetService('LabelService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/label_service/get_labels_by_statement.py b/examples/dfp/v201702/label_service/get_active_labels.py similarity index 63% rename from examples/dfp/v201605/label_service/get_labels_by_statement.py rename to examples/dfp/v201702/label_service/get_active_labels.py index a71b5363..2a39c47e 100755 --- a/examples/dfp/v201605/label_service/get_labels_by_statement.py +++ b/examples/dfp/v201702/label_service/get_active_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,36 @@ # 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 code example gets all labels ordered by name. - -To create a label, run create_label.py. This feature is only available to DFP -premium solution networks. +"""This example gets all active labels. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201605') - - # Create statement to get all labels - statement = dfp.FilterStatement('ORDER BY name') - - # Get labels by statement. + label_service = client.GetService('LabelService', version='v201702') + query = 'WHERE isActive = :isActive' + values = [ + {'key': 'isActive', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select labels. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of labels at a time, paging + # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' was found.' - % (label['id'], label['name'])) + # Print out some information for each label. + print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], + label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/label_service/get_all_labels.py b/examples/dfp/v201702/label_service/get_all_labels.py similarity index 73% rename from examples/dfp/v201605/label_service/get_all_labels.py rename to examples/dfp/v201702/label_service/get_all_labels.py index 77265cfe..0b655f83 100755 --- a/examples/dfp/v201605/label_service/get_all_labels.py +++ b/examples/dfp/v201702/label_service/get_all_labels.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 code example gets all labels. - -To create labels, run create_labels.py. This feature is only available to DFP -premium solution networks.""" - +"""This example gets all labels. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,19 +22,20 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201605') + label_service = client.GetService('LabelService', version='v201702') - # Create statement to get all labels + # Create a statement to select labels. statement = dfp.FilterStatement() - # Get labels by statement. + # Retrieve a small amount of labels at a time, paging + # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' was found.' - % (label['id'], label['name'])) + # Print out some information for each label. + print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], + label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/label_service/update_labels.py b/examples/dfp/v201702/label_service/update_labels.py similarity index 97% rename from examples/dfp/v201605/label_service/update_labels.py rename to examples/dfp/v201702/label_service/update_labels.py index f5088514..a0cb86ef 100755 --- a/examples/dfp/v201605/label_service/update_labels.py +++ b/examples/dfp/v201702/label_service/update_labels.py @@ -17,7 +17,8 @@ """This code example updates the description of a single label. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" # Import appropriate modules from the client library. @@ -28,7 +29,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201605') + label_service = client.GetService('LabelService', version='v201702') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201605/line_item_creative_association_service/__init__.py b/examples/dfp/v201702/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201605/line_item_creative_association_service/__init__.py rename to examples/dfp/v201702/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201605/line_item_creative_association_service/create_licas.py b/examples/dfp/v201702/line_item_creative_association_service/create_licas.py similarity index 93% rename from examples/dfp/v201605/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201702/line_item_creative_association_service/create_licas.py index 4cab1cb6..1612322d 100755 --- a/examples/dfp/v201605/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/create_licas.py @@ -17,7 +17,8 @@ """This code example creates new line item creative associations (LICAs) for an existing line item and a set of creative ids. -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -31,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201605') + 'LineItemCreativeAssociationService', version='v201702') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201605/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/dfp/v201605/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py index c40d5888..e03b2837 100755 --- a/examples/dfp/v201605/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py @@ -16,7 +16,8 @@ """This code example deactivates all LICAs for the line item. -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201605') + 'LineItemCreativeAssociationService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py similarity index 56% rename from examples/dfp/v201605/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py index d183e4bf..c09a88a4 100755 --- a/examples/dfp/v201605/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all line item creative associations (LICA). - -To create LICAs, run create_licas.py or associate_creative_set_to_line_item.py. +"""This example gets all line item creative associations. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,29 +23,34 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201605') + 'LineItemCreativeAssociationService', version='v201702') - # Create a filter statement. + # Create a statement to select line item creative associations. statement = dfp.FilterStatement() - # Get line items by statement. + # Retrieve a small amount of line item creative associations at a time, paging + # through until all line item creative associations have been retrieved. while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for lica in response['results']: + # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print ('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % - (lica['lineItemId'], lica['creativeSetId'], lica['status'])) + print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' + 'status \'%s\' was found.' % + (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: - print ('LICA with line item ID \'%s\', creative ID \'%s\', and status' - ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print('Line item creative association with line item ID "%d" and ' + 'creative ID "%d" was found.\n' % + (lica['lineItemId'], lica['creativeId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/line_item_creative_association_service/get_licas_by_statement.py b/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py similarity index 52% rename from examples/dfp/v201605/line_item_creative_association_service/get_licas_by_statement.py rename to examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py index f3f11653..fa05b0ea 100755 --- a/examples/dfp/v201605/line_item_creative_association_service/get_licas_by_statement.py +++ b/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,52 +13,52 @@ # 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 code example gets all line item creative associations (LICA) for a given -line item id. - -To create LICAs, run create_licas.py.""" - +"""This example gets all line item creative associations for a given line item. +""" # Import appropriate modules from the client library. from googleads import dfp -# Set the id of the line item to get LICAs by. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201605') - -# Create statement object to only select LICAs for the given line item id. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] + 'LineItemCreativeAssociationService', version='v201702') query = 'WHERE lineItemId = :lineItemId' + values = [ + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'TextValue', + 'value': line_item_id + }}, + ] + # Create a statement to select line item creative associations. statement = dfp.FilterStatement(query, values) + # Retrieve a small amount of line item creative associations at a time, paging + # through until all line item creative associations have been retrieved. while True: - # Get LICAs by statement. response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: - # Display results. for lica in response['results']: - print ('LICA with line item id \'%s\', creative id \'%s\', and status ' - '\'%s\' was found.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + # Print out some information for each line item creative association. + if 'creativeSetId' in lica: + print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' + 'status \'%s\' was found.' % + (lica['lineItemId'], lica['creativeSetId'], lica['status'])) + else: + print('Line item creative association with line item ID "%d" and ' + 'creative ID "%d" was found.\n' % + (lica['lineItemId'], lica['creativeId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201605/line_item_creative_association_service/update_licas.py b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/dfp/v201605/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201702/line_item_creative_association_service/update_licas.py index 2a493b63..738a73be 100755 --- a/examples/dfp/v201605/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py @@ -17,7 +17,8 @@ """This code example updates the destination URL of all line item creative associations (LICA). -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201605') + 'LineItemCreativeAssociationService', version='v201702') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201605/line_item_service/__init__.py b/examples/dfp/v201702/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201605/line_item_service/__init__.py rename to examples/dfp/v201702/line_item_service/__init__.py diff --git a/examples/dfp/v201605/line_item_service/activate_line_items.py b/examples/dfp/v201702/line_item_service/activate_line_items.py similarity index 98% rename from examples/dfp/v201605/line_item_service/activate_line_items.py rename to examples/dfp/v201702/line_item_service/activate_line_items.py index 3cbe6db2..61459cd2 100755 --- a/examples/dfp/v201605/line_item_service/activate_line_items.py +++ b/examples/dfp/v201702/line_item_service/activate_line_items.py @@ -20,7 +20,8 @@ one creative associated with them. To approve line items, approve the order to which they belong by running approve_orders.py. To create LICAs, run create_licas.py. To determine which line items exist, run -get_all_line_items.py.""" +get_all_line_items.py. +""" # Import appropriate modules from the client library. @@ -32,7 +33,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') + line_item_service = client.GetService('LineItemService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/line_item_service/create_line_items.py b/examples/dfp/v201702/line_item_service/create_line_items.py similarity index 98% rename from examples/dfp/v201605/line_item_service/create_line_items.py rename to examples/dfp/v201702/line_item_service/create_line_items.py index 4ff47d3b..69002f77 100755 --- a/examples/dfp/v201605/line_item_service/create_line_items.py +++ b/examples/dfp/v201702/line_item_service/create_line_items.py @@ -18,7 +18,8 @@ To determine which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To determine which placements exist, -run get_all_placements.py.""" +run get_all_placements.py. +""" from datetime import date @@ -35,11 +36,11 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') + line_item_service = client.GetService('LineItemService', version='v201702') # Create line item objects. line_items = [] - for i in xrange(5): + for _ in xrange(5): line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, diff --git a/examples/dfp/v201605/line_item_service/create_video_line_item.py b/examples/dfp/v201702/line_item_service/create_video_line_item.py similarity index 96% rename from examples/dfp/v201605/line_item_service/create_video_line_item.py rename to examples/dfp/v201702/line_item_service/create_video_line_item.py index c90ef243..9b7e9b4e 100755 --- a/examples/dfp/v201605/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201702/line_item_service/create_video_line_item.py @@ -20,7 +20,8 @@ which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To create a video ad unit, run create_video_ad_unit.py. To create criteria for categories, run -create_custom_targeting_keys_and_values.py""" +create_custom_targeting_keys_and_values.py. +""" from datetime import date @@ -38,14 +39,14 @@ # on the content to target. This would typically be from a key representing # a "genre" and the value representing something like "comedy". The value # must be from a key in a content metadata key hierarchy. -CONTENT_CUSTOM_TARGETING_VALUE_ID = \ - 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE' +CONTENT_CUSTOM_TARGETING_VALUE_ID = ( + 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE') def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') + line_item_service = client.GetService('LineItemService', version='v201702') # Create line item object. line_item = { diff --git a/examples/dfp/v201605/line_item_service/get_all_line_items.py b/examples/dfp/v201702/line_item_service/get_all_line_items.py similarity index 68% rename from examples/dfp/v201605/line_item_service/get_all_line_items.py rename to examples/dfp/v201702/line_item_service/get_all_line_items.py index 4deaf7e0..ea5f0ee5 100755 --- a/examples/dfp/v201605/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201702/line_item_service/get_all_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,11 +13,8 @@ # 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 code example gets all line items. - -To create line items, run create_line_items.py.""" - +"""This example gets all line items. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -25,27 +22,28 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') + line_item_service = client.GetService('LineItemService', version='v201702') - # Create a filter statement. + # Create a statement to select line items. statement = dfp.FilterStatement() - # Get line items by statement. + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was found.' % - (line_item['id'], line_item['orderId'], line_item['name'])) + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py new file mode 100755 index 00000000..f6b7e1f8 --- /dev/null +++ b/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 line items that are missing creatives. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201702') + query = 'WHERE isMissingCreatives = :isMissingCreatives' + values = [ + {'key': 'isMissingCreatives', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select line items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response: + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py new file mode 100755 index 00000000..ea286912 --- /dev/null +++ b/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 only recently updated line items. +""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201702') + query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' + values = [ + {'key': 'lastModifiedDateTime', + 'value': { + 'xsi_type': 'TextValue', + 'value': (datetime.now() - timedelta(days=1)) + .strftime('%Y-%m-%dT%H:%M:%S') + }}, + ] + # Create a statement to select line items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response: + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/line_item_service/target_custom_criteria.py b/examples/dfp/v201702/line_item_service/target_custom_criteria.py similarity index 98% rename from examples/dfp/v201605/line_item_service/target_custom_criteria.py rename to examples/dfp/v201702/line_item_service/target_custom_criteria.py index f2ff5c1b..657a8bf0 100755 --- a/examples/dfp/v201605/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201702/line_item_service/target_custom_criteria.py @@ -18,7 +18,8 @@ To determine which line items exist, run get_all_line_items.py. To determine which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" import pprint @@ -39,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') + line_item_service = client.GetService('LineItemService', version='v201702') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201605/line_item_service/update_line_items.py b/examples/dfp/v201702/line_item_service/update_line_items.py similarity index 96% rename from examples/dfp/v201605/line_item_service/update_line_items.py rename to examples/dfp/v201702/line_item_service/update_line_items.py index c663c795..06134ddf 100755 --- a/examples/dfp/v201605/line_item_service/update_line_items.py +++ b/examples/dfp/v201702/line_item_service/update_line_items.py @@ -16,7 +16,8 @@ """This code example updates the delivery rate of all line items in an order. -To determine which line items exist, run get_all_line_items.py.""" +To determine which line items exist, run get_all_line_items.py. +""" # Import appropriate modules from the client library. @@ -28,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') + line_item_service = client.GetService('LineItemService', version='v201702') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201702/native_style_service/__init__.py b/examples/dfp/v201702/native_style_service/__init__.py new file mode 100755 index 00000000..5d960bcb --- /dev/null +++ b/examples/dfp/v201702/native_style_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/python +# +# Copyright 2017 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. diff --git a/examples/dfp/v201702/native_style_service/create_native_styles.py b/examples/dfp/v201702/native_style_service/create_native_styles.py new file mode 100755 index 00000000..4548575a --- /dev/null +++ b/examples/dfp/v201702/native_style_service/create_native_styles.py @@ -0,0 +1,180 @@ +#!/usr/bin/python +# +# Copyright 2017 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. + +"""Creates a native app install ad.""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +# This is the creative template ID for the system-defined native app install ad +# format, which we will create the native style from. Use +# CreativeTemplateService.getCreativeTemplateByStatement() and +# CreativeTemplate.isNativeEligible() to get other native ad formats available +# in your network. +CREATIVE_TEMPLATE_ID = 10004400 +WIDTH = 300 +HEIGHT = 345 + +HTML_SNIPPET = """
+ +
Ad
+
+ + + +
+
+ +
+
+ [%Body%] +
+
[%Price%]
+ +
+""" + +CSS_SNIPPET = """body { + background-color: rgba(255, 255, 255, 1); + font-family: "Roboto-Regular", sans-serif; + font-weight: normal; + font-size: 12px; + line-height: 14px; +} +.attribution { + background-color: rgba(236, 182, 0, 1); + color: rgba(255, 255, 255, 1); + font-size: 13px; + display: table; + margin: 4px 8px; + padding: 0 3px; + border-radius: 2px; +} +.image { + text-align: center; + margin: 8px; +} +.image img, +.image-link { + width: 100%; +} +.app-icon { + float: left; + margin: 0 8px 4px 8px; + height: 40px; + width: 40px; + background-color: transparent; +} +.app-icon img { + height: 100%; + width: 100%; + border-radius: 20%; +} +.title, +.promo-headline { + font-weight: bold; + font-size: 14px; + line-height: 20px; + margin: 8px 8px 4px 8px; +} +.title a, +.promo-headline { + color: rgba(112, 112, 112, 1); + text-decoration: none; +} +.reviews { + float: left; +} +.reviews svg { + fill: rgba(0, 0, 0, 0.7); +} +.body { + clear: left; + margin: 8px; +} +.body a { + color: rgba(110, 110, 110, 1); + text-decoration: none; +} +.price { + display: none; +} +.button { + font-size: 14px; + font-weight: bold; + float: right; + margin: 0px 16px 16px 0px; + white-space: nowrap; +} +.button a { + color: #2196F3; + text-decoration: none; +} +.button svg { + display: none; +} +""" + + +def main(client, html_snippet, css_snippet, creative_template_id, width, + height): + # Initialize appropriate service. + native_style_service = client.GetService('NativeStyleService', + version='v201702') + + native_style = { + 'name': 'Native style #%d' % uuid.uuid4(), + 'htmlSnippet': html_snippet, + 'cssSnippet': css_snippet, + 'creativeTemplateId': creative_template_id, + 'size': { + 'width': width, + 'height': height, + 'isAspectRatio': False + } + } + + # Create the native style on the server. + native_styles = native_style_service.createNativeStyles([native_style]) + + # Display results. + for native_style in native_styles: + print ('A Native style with ID "%s", name "%s", and creative template ID' + '"%d" was created.' % (native_style['id'], native_style['name'], + native_style['creativeTemplateId'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, WIDTH, + HEIGHT) diff --git a/examples/dfp/v201702/native_style_service/get_all_native_styles.py b/examples/dfp/v201702/native_style_service/get_all_native_styles.py new file mode 100755 index 00000000..17a8fa09 --- /dev/null +++ b/examples/dfp/v201702/native_style_service/get_all_native_styles.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2017 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 native styles.""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + native_style_service = client.GetService('NativeStyleService', + version='v201702') + + # Create a statement to select native styles. + statement = dfp.FilterStatement() + + # Retrieve a small amount of native styles at a time, paging + # through until all native styles have been retrieved. + while True: + response = native_style_service.getNativeStylesByStatement( + statement.ToStatement()) + if 'results' in response: + for native_style in response['results']: + # Print out some information for each native style. + print('Native style with ID "%d" and name "%s" was found.\n' % + (native_style['id'], native_style['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/network_service/__init__.py b/examples/dfp/v201702/network_service/__init__.py similarity index 100% rename from examples/dfp/v201605/network_service/__init__.py rename to examples/dfp/v201702/network_service/__init__.py diff --git a/examples/dfp/v201605/network_service/get_all_networks.py b/examples/dfp/v201702/network_service/get_all_networks.py similarity index 69% rename from examples/dfp/v201605/network_service/get_all_networks.py rename to examples/dfp/v201702/network_service/get_all_networks.py index 2177f2c6..bd346ad1 100755 --- a/examples/dfp/v201605/network_service/get_all_networks.py +++ b/examples/dfp/v201702/network_service/get_all_networks.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 networks that you have access to with the current login -credentials. - -A networkCode should be left out for this request.""" - +"""This example gets all networks. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -26,18 +22,18 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201605') + network_service = client.GetService('NetworkService', version='v201702') - # Get all networks that you have access to with the current login credentials. networks = network_service.getAllNetworks() - # Display results. + # Print out some information for each network. for network in networks: - print ('Network with network code \'%s\' and display name \'%s\' was found.' - % (network['networkCode'], network['displayName'])) + print('Network with network code \'%s\' and display name \'%s\' was found.' + % (network['networkCode'], network['displayName'])) print '\nNumber of results found: %s' % len(networks) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/network_service/make_test_network.py b/examples/dfp/v201702/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201605/network_service/make_test_network.py rename to examples/dfp/v201702/network_service/make_test_network.py index c686f7c3..4b333c57 100755 --- a/examples/dfp/v201605/network_service/make_test_network.py +++ b/examples/dfp/v201702/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201605') + network_service = client.GetService('NetworkService', version='v201702') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/dfp/v201605/order_service/__init__.py b/examples/dfp/v201702/order_service/__init__.py similarity index 100% rename from examples/dfp/v201605/order_service/__init__.py rename to examples/dfp/v201702/order_service/__init__.py diff --git a/examples/dfp/v201605/order_service/approve_orders.py b/examples/dfp/v201702/order_service/approve_orders.py similarity index 97% rename from examples/dfp/v201605/order_service/approve_orders.py rename to examples/dfp/v201702/order_service/approve_orders.py index edf02931..8ad9e52c 100755 --- a/examples/dfp/v201605/order_service/approve_orders.py +++ b/examples/dfp/v201702/order_service/approve_orders.py @@ -16,7 +16,8 @@ """This code example approves all eligible draft and pending orders. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" import datetime @@ -27,7 +28,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201605') + order_service = client.GetService('OrderService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/order_service/create_orders.py b/examples/dfp/v201702/order_service/create_orders.py similarity index 94% rename from examples/dfp/v201605/order_service/create_orders.py rename to examples/dfp/v201702/order_service/create_orders.py index 75cab0fc..7cc8f59e 100755 --- a/examples/dfp/v201605/order_service/create_orders.py +++ b/examples/dfp/v201702/order_service/create_orders.py @@ -16,7 +16,8 @@ """This code example creates new orders. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" import uuid @@ -31,11 +32,11 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201605') + order_service = client.GetService('OrderService', version='v201702') # Create order objects. orders = [] - for i in xrange(5): + for _ in xrange(5): order = { 'name': 'Order #%s' % uuid.uuid4(), 'advertiserId': company_id, diff --git a/examples/dfp/v201605/order_service/get_all_orders.py b/examples/dfp/v201702/order_service/get_all_orders.py similarity index 73% rename from examples/dfp/v201605/order_service/get_all_orders.py rename to examples/dfp/v201702/order_service/get_all_orders.py index 14ede832..a0f94440 100755 --- a/examples/dfp/v201605/order_service/get_all_orders.py +++ b/examples/dfp/v201702/order_service/get_all_orders.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,32 +13,29 @@ # 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 code example gets all orders. - -To create orders, run create_orders.py. +"""This example gets all orders. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201605') + order_service = client.GetService('OrderService', version='v201702') - # Create a filter statement. + # Create a statement to select orders. statement = dfp.FilterStatement() - # Get orders by statement. + # Retrieve a small amount of orders at a time, paging + # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for order in response['results']: - print ('Order with id \'%s\', name \'%s\', and advertiser id \'%s\' was' - ' found.' % (order['id'], order['name'], order['advertiserId'])) + # Print out some information for each order. + print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], + order['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201702/order_service/get_orders_starting_soon.py b/examples/dfp/v201702/order_service/get_orders_starting_soon.py new file mode 100755 index 00000000..cf53c918 --- /dev/null +++ b/examples/dfp/v201702/order_service/get_orders_starting_soon.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2016 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 orders that are starting soon. +""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + order_service = client.GetService('OrderService', version='v201702') + query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' + '<= :soon') + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'APPROVED' + }}, + {'key': 'now', + 'value': { + 'xsi_type': 'TextValue', + 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') + }}, + {'key': 'soon', + 'value': { + 'xsi_type': 'TextValue', + 'value': (datetime.now() + timedelta(days=5)) + .strftime('%Y-%m-%dT%H:%M:%S') + }}, + ] + # Create a statement to select orders. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of orders at a time, paging + # through until all orders have been retrieved. + while True: + response = order_service.getOrdersByStatement(statement.ToStatement()) + if 'results' in response: + for order in response['results']: + # Print out some information for each order. + print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], + order['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/order_service/update_orders.py b/examples/dfp/v201702/order_service/update_orders.py similarity index 97% rename from examples/dfp/v201605/order_service/update_orders.py rename to examples/dfp/v201702/order_service/update_orders.py index 77632245..15f58e78 100755 --- a/examples/dfp/v201605/order_service/update_orders.py +++ b/examples/dfp/v201702/order_service/update_orders.py @@ -16,7 +16,8 @@ """This code example updates the notes of a single order specified by ID. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201605') + order_service = client.GetService('OrderService', version='v201702') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201702/package_service/get_all_packages.py b/examples/dfp/v201702/package_service/get_all_packages.py new file mode 100755 index 00000000..d0f77ac0 --- /dev/null +++ b/examples/dfp/v201702/package_service/get_all_packages.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# +# Copyright 2016 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 packages. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + pkg_service = client.GetService('PackageService', version='v201702') + + # Create a statement to select packages. + statement = dfp.FilterStatement() + + # Retrieve a small amount of packages at a time, paging + # through until all packages have been retrieved. + while True: + response = pkg_service.getPackagesByStatement(statement.ToStatement()) + if 'results' in response: + for pkg in response['results']: + # Print out some information for each package. + print( + 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' + % (pkg['id'], pkg['name'], pkg['proposalId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/package_service/get_in_progress_packages.py b/examples/dfp/v201702/package_service/get_in_progress_packages.py new file mode 100755 index 00000000..97a24fa7 --- /dev/null +++ b/examples/dfp/v201702/package_service/get_in_progress_packages.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 packages in progress. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + pkg_service = client.GetService('PackageService', version='v201702') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'IN_PROGRESS' + }}, + ] + # Create a statement to select packages. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of packages at a time, paging + # through until all packages have been retrieved. + while True: + response = pkg_service.getPackagesByStatement(statement.ToStatement()) + if 'results' in response: + for pkg in response['results']: + # Print out some information for each package. + print( + 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' + % (pkg['id'], pkg['name'], pkg['proposalId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/placement_service/create_placements.py b/examples/dfp/v201702/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201605/placement_service/create_placements.py rename to examples/dfp/v201702/placement_service/create_placements.py index e6bc429c..c13e50b5 100755 --- a/examples/dfp/v201605/placement_service/create_placements.py +++ b/examples/dfp/v201702/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201605') - inventory_service = client.GetService('InventoryService', version='v201605') + placement_service = client.GetService('PlacementService', version='v201702') + inventory_service = client.GetService('InventoryService', version='v201702') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201605/placement_service/deactivate_placements.py b/examples/dfp/v201702/placement_service/deactivate_placements.py similarity index 99% rename from examples/dfp/v201605/placement_service/deactivate_placements.py rename to examples/dfp/v201702/placement_service/deactivate_placements.py index eac7f3d7..c7f6b961 100755 --- a/examples/dfp/v201605/placement_service/deactivate_placements.py +++ b/examples/dfp/v201702/placement_service/deactivate_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201605') + placement_service = client.GetService('PlacementService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/placement_service/get_placements_by_statement.py b/examples/dfp/v201702/placement_service/get_active_placements.py similarity index 64% rename from examples/dfp/v201605/placement_service/get_placements_by_statement.py rename to examples/dfp/v201702/placement_service/get_active_placements.py index db9e389d..83e38b82 100755 --- a/examples/dfp/v201605/placement_service/get_placements_by_statement.py +++ b/examples/dfp/v201702/placement_service/get_active_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,44 @@ # 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 code example gets all active placements by using a statement. - -To create a placement, run create_placements.py. +"""This example gets all active placements. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201605') - - # Create a statement to only select active placements. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] + placement_service = client.GetService('PlacementService', version='v201702') query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select placements. statement = dfp.FilterStatement(query, values) - # Get placements by statement. + # Retrieve a small amount of placements at a time, paging + # through until all placements have been retrieved. while True: - response = placement_service.getPlacementsByStatement( - statement.ToStatement()) + response = placement_service.getPlacementsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for placement in response['results']: - print ('Placement with id \'%s\' and name \'%s\' was found.' - % (placement['id'], placement['name'])) + # Print out some information for each placement. + print('Placement with ID "%d" and name "%s" was found.\n' % + (placement['id'], placement['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/placement_service/get_all_placements.py b/examples/dfp/v201702/placement_service/get_all_placements.py similarity index 68% rename from examples/dfp/v201605/placement_service/get_all_placements.py rename to examples/dfp/v201702/placement_service/get_all_placements.py index 2d60fe64..4801eb48 100755 --- a/examples/dfp/v201605/placement_service/get_all_placements.py +++ b/examples/dfp/v201702/placement_service/get_all_placements.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,39 +13,37 @@ # 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 code example gets all placements. - -To create placements, run create_placement.py. +"""This example gets all placements. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201605') + placement_service = client.GetService('PlacementService', version='v201702') - # Create statement to fetch all placements. + # Create a statement to select placements. statement = dfp.FilterStatement() - # Get placements by statement. + # Retrieve a small amount of placements at a time, paging + # through until all placements have been retrieved. while True: - response = placement_service.getPlacementsByStatement( - statement.ToStatement()) + response = placement_service.getPlacementsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for placement in response['results']: - print ('Placement with id \'%s\' and name \'%s\' was found.' - % (placement['id'], placement['name'])) + # Print out some information for each placement. + print('Placement with ID "%d" and name "%s" was found.\n' % + (placement['id'], placement['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/placement_service/update_placements.py b/examples/dfp/v201702/placement_service/update_placements.py similarity index 99% rename from examples/dfp/v201605/placement_service/update_placements.py rename to examples/dfp/v201702/placement_service/update_placements.py index a864766c..daa315fa 100755 --- a/examples/dfp/v201605/placement_service/update_placements.py +++ b/examples/dfp/v201702/placement_service/update_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201605') + placement_service = client.GetService('PlacementService', version='v201702') # Create query. values = [{ 'key': 'placementId', diff --git a/examples/dfp/v201605/premium_rate_service/__init__.py b/examples/dfp/v201702/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201605/premium_rate_service/__init__.py rename to examples/dfp/v201702/premium_rate_service/__init__.py diff --git a/examples/dfp/v201605/premium_rate_service/create_premium_rates.py b/examples/dfp/v201702/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/dfp/v201605/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201702/premium_rate_service/create_premium_rates.py index f560f0a1..7e907cd2 100755 --- a/examples/dfp/v201605/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201605') + version='v201702') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201605/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py similarity index 61% rename from examples/dfp/v201605/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py index f9d95576..fefac987 100755 --- a/examples/dfp/v201605/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,38 +13,33 @@ # 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 code example gets all premium rates. - -To create premium rates, run create_premium_rates.py. - +"""This example gets all premium rates. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201605') + premium_rate_service = client.GetService( + 'PremiumRateService', version='v201702') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select premium rates. + statement = dfp.FilterStatement() - # Get premium rates by statement. + # Retrieve a small amount of premium rates at a time, paging + # through until all premium rates have been retrieved. while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for premium_rate in response['results']: - print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' - ' rate card with ID \'%s\' was found.\n' % ( - premium_rate['id'], - dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['rateCardId'])) + # Print out some information for each premium rate. + print('Premium rate with ID "%d", premium feature "%s", and rate card ' + 'id "%d" was found.\n' % (premium_rate['id'], + dfp.DfpClassType(premium_rate), + premium_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/premium_rate_service/get_premium_rates_for_a_rate_card.py b/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 58% rename from examples/dfp/v201605/premium_rate_service/get_premium_rates_for_a_rate_card.py rename to examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py index 6b5aa2d1..2771fd29 100755 --- a/examples/dfp/v201605/premium_rate_service/get_premium_rates_for_a_rate_card.py +++ b/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all premium rates belonging to a specific rate card. - -To create premium rates, run create_premium_rates.py. - +"""This example gets all premium rates on a specific rate card. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -29,32 +24,31 @@ def main(client, rate_card_id): # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201605') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'rateCardId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': rate_card_id - } - }] - query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC' + premium_rate_service = client.GetService( + 'PremiumRateService', version='v201702') + query = 'WHERE rateCardId = :rateCardId' + values = [ + {'key': 'rateCardId', + 'value': { + 'xsi_type': 'TextValue', + 'value': rate_card_id + }}, + ] + # Create a statement to select premium rates. statement = dfp.FilterStatement(query, values) - # Get premium rates by statement. + # Retrieve a small amount of premium rates at a time, paging + # through until all premium rates have been retrieved. while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for premium_rate in response['results']: - print ('Premium rate with ID \'%s\' of type \'%s\' assigned to ' - ' rate card with ID \'%s\' was found.\n' % ( - premium_rate['id'], - dfp.DfpClassType(premium_rate['premiumFeature']), - premium_rate['rateCardId'])) + # Print out some information for each premium rate. + print('Premium rate with ID "%d", premium feature "%s", and rate card ' + 'ID "%d" was found.\n' % (premium_rate['id'], + premium_rate['premium feature'], + premium_rate['rateCardId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/premium_rate_service/update_premium_rates.py b/examples/dfp/v201702/premium_rate_service/update_premium_rates.py similarity index 97% rename from examples/dfp/v201605/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201702/premium_rate_service/update_premium_rates.py index 6e35fbf2..e49aa68f 100755 --- a/examples/dfp/v201605/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201605') + version='v201702') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py new file mode 100755 index 00000000..99a0edd9 --- /dev/null +++ b/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py @@ -0,0 +1,53 @@ +#!/usr/bin/python +# +# Copyright 2016 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 product package items. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_package_item_service = client.GetService( + 'ProductPackageItemService', version='v201702') + + # Create a statement to select product package items. + statement = dfp.FilterStatement() + + # Retrieve a small amount of product package items at a time, paging + # through until all product package items have been retrieved. + while True: + response = product_package_item_service.getProductPackageItemsByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package_item in response['results']: + # Print out some information for each product package item. + print('Product package item with ID "%d", product id "%d", and product ' + 'package id "%d" was found.\n' % + (product_package_item['id'], product_package_item['productId'], + product_package_item['productPackageId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py new file mode 100755 index 00000000..d1c92e00 --- /dev/null +++ b/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 product package items belonging to a product package. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + + +def main(client, product_package_id): + # Initialize appropriate service. + product_package_item_service = client.GetService( + 'ProductPackageItemService', version='v201702') + query = 'WHERE productPackageId = :productPackageId' + values = [ + {'key': 'productPackageId', + 'value': { + 'xsi_type': 'TextValue', + 'value': product_package_id + }}, + ] + # Create a statement to select product package items. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of product package items at a time, paging + # through until all product package items have been retrieved. + while True: + response = product_package_item_service.getProductPackageItemsByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package_item in response['results']: + # Print out some information for each product package item. + print('Product package item with ID "%d", product ID "%d", and product ' + 'package ID "%d" was found.\n' % + (product_package_item['id'], product_package_item['productId'], + product_package_item['productPackageId'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_PACKAGE_ID) diff --git a/examples/dfp/v201702/product_package_service/get_active_product_packages.py b/examples/dfp/v201702/product_package_service/get_active_product_packages.py new file mode 100755 index 00000000..99538e5c --- /dev/null +++ b/examples/dfp/v201702/product_package_service/get_active_product_packages.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 active product packages. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_package_service = client.GetService( + 'ProductPackageService', version='v201702') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'ACTIVE' + }}, + ] + # Create a statement to select product packages. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of product packages at a time, paging + # through until all product packages have been retrieved. + while True: + response = product_package_service.getProductPackagesByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package in response['results']: + # Print out some information for each product package. + print('Product package with ID "%d" and name "%s" was found.\n' % + (product_package['id'], product_package['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/product_package_service/get_all_product_packages.py b/examples/dfp/v201702/product_package_service/get_all_product_packages.py new file mode 100755 index 00000000..ffb42161 --- /dev/null +++ b/examples/dfp/v201702/product_package_service/get_all_product_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2016 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 product packages. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + product_package_service = client.GetService( + 'ProductPackageService', version='v201702') + + # Create a statement to select product packages. + statement = dfp.FilterStatement() + + # Retrieve a small amount of product packages at a time, paging + # through until all product packages have been retrieved. + while True: + response = product_package_service.getProductPackagesByStatement( + statement.ToStatement()) + if 'results' in response: + for product_package in response['results']: + # Print out some information for each product package. + print('Product package with ID "%d" and name "%s" was found.\n' % + (product_package['id'], product_package['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/product_service/__init__.py b/examples/dfp/v201702/product_service/__init__.py similarity index 100% rename from examples/dfp/v201605/product_service/__init__.py rename to examples/dfp/v201702/product_service/__init__.py diff --git a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py new file mode 100755 index 00000000..02d13ac9 --- /dev/null +++ b/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a programmatic product for non-sales management. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + product_service = client.GetService('ProductService', version='v201702') + network_service = client.GetService('NetworkService', version='v201702') + + product = { + # Setting required Marketplace Information. + 'productMarketplaceInfo': { + 'additionalTerms': 'Remember to also discuss that thing.', + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for products. + 'name': ('Product #%d' % uuid.uuid4()), + 'productType': 'DFP', + 'rateType': 'CPM', + 'lineItemType': 'STANDARD', + 'priority': 8, + 'environment': 'BROWSER', + 'rate': { + 'currencyCode': 'USD', + 'microAmount': '6000000' + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'builtInTargeting': { + 'inventoryTargeting': { + 'adUnitTargeting': { + 'adUnitId': network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId'], + 'includeDescendents': 'true' + } + } + }, + } + + products = product_service.createProducts([product]) + + if products: + for product in products: + print ('A programmatic product for non-sales management with ID "%s"' + ' and name "%s" was created.' % (product['id'], product['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/product_service/get_all_products.py b/examples/dfp/v201702/product_service/get_all_products.py similarity index 72% rename from examples/dfp/v201605/product_service/get_all_products.py rename to examples/dfp/v201702/product_service/get_all_products.py index 9e8aa190..8c7362ca 100755 --- a/examples/dfp/v201605/product_service/get_all_products.py +++ b/examples/dfp/v201702/product_service/get_all_products.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,29 @@ # 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 code example gets all products. - -Products are created automatically from product templates. - +"""This example gets all products. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201605') + product_service = client.GetService('ProductService', version='v201702') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select products. + statement = dfp.FilterStatement() - # Get products by statement. + # Retrieve a small amount of products at a time, paging + # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' was found.' % ( - product['id'], product['name'])) + # Print out some information for each product. + print('Product with ID "%d" and name "%s" was found.\n' % + (product['id'], product['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/product_service/get_products_for_product_template.py b/examples/dfp/v201702/product_service/get_products_for_product_template.py similarity index 70% rename from examples/dfp/v201605/product_service/get_products_for_product_template.py rename to examples/dfp/v201702/product_service/get_products_for_product_template.py index 8b569ddc..ddf1e27d 100755 --- a/examples/dfp/v201605/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201702/product_service/get_products_for_product_template.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,9 @@ # 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 products created from a product template. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,28 +24,28 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201605') - - # Create a filter statement to select only products created from a single - # a product template. - values = [{ - 'key': 'productTemplateId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE productTemplateId = :productTemplateId ORDER BY id ASC' + product_service = client.GetService('ProductService', version='v201702') + + query = 'WHERE productTemplateId = :productTemplateId' + values = [ + {'key': 'productTemplateId', + 'value': { + 'xsi_type': 'TextValue', + 'value': product_template_id + }}, + ] + # Create a statement to select products. statement = dfp.FilterStatement(query, values) - # Get products by statement. + # Retrieve a small amount of products at a time, paging + # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' was found.' % ( - product['id'], product['name'])) + # Print out some information for each product. + print('Product with ID "%d" and name "%s" was found.\n' % + (product['id'], product['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py new file mode 100755 index 00000000..e545b1b2 --- /dev/null +++ b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2015 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 code example publishes a product to Marketplace. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the product to publish. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, product_id): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201702') + + # Create query. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': product_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + products_published = 0 + + # Get products by statement. + while True: + response = product_service.getProductsByStatement( + statement.ToStatement()) + if 'results' in response: + for product in response['results']: + print ('Product with id \'%s\' and name \'%s\' will be ' + 'published.' % (product['id'], + product['name'])) + + # Perform action. + result = product_service.performProductAction( + {'xsi_type': 'PublishProducts'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + products_published += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if products_published > 0: + print 'Number of programmatic products published: %s' % products_published + else: + print 'No products were published.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201605/product_service/update_products.py b/examples/dfp/v201702/product_service/update_products.py similarity index 99% rename from examples/dfp/v201605/product_service/update_products.py rename to examples/dfp/v201702/product_service/update_products.py index a77c83d9..c4a11bfc 100755 --- a/examples/dfp/v201605/product_service/update_products.py +++ b/examples/dfp/v201702/product_service/update_products.py @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201605') + product_service = client.GetService('ProductService', version='v201702') # Create statement object to select a single product by an ID. values = [{ diff --git a/examples/dfp/v201605/product_template_service/__init__.py b/examples/dfp/v201702/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201605/product_template_service/__init__.py rename to examples/dfp/v201702/product_template_service/__init__.py diff --git a/examples/dfp/v201605/product_template_service/activate_product_templates.py b/examples/dfp/v201702/product_template_service/activate_product_templates.py similarity index 97% rename from examples/dfp/v201605/product_template_service/activate_product_templates.py rename to examples/dfp/v201702/product_template_service/activate_product_templates.py index 795472ed..8956315e 100755 --- a/examples/dfp/v201605/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201702/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201605') + 'ProductTemplateService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/product_template_service/create_product_templates.py b/examples/dfp/v201702/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201605/product_template_service/create_product_templates.py rename to examples/dfp/v201702/product_template_service/create_product_templates.py index ab716be7..352ea1c1 100755 --- a/examples/dfp/v201605/product_template_service/create_product_templates.py +++ b/examples/dfp/v201702/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201605') + 'ProductTemplateService', version='v201702') network_service = client.GetService( - 'NetworkService', version='v201605') + 'NetworkService', version='v201702') # Create a product template. product_template = { diff --git a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py new file mode 100755 index 00000000..4be1ce59 --- /dev/null +++ b/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a programmatic product template. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + product_template_service = client.GetService( + 'ProductTemplateService', version='v201702') + network_service = client.GetService( + 'NetworkService', version='v201702') + + product_template = { + # Setting required Marketplace information. + 'productTemplateMarketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + # Setting common required fields for product templates. + 'name': ('Product template #%d' % uuid.uuid4()), + 'description': ('This product template creates standard programmatic' + 'proposal line items targeting all ad units with' + 'product segmentation on geo targeting.'), + 'nameMacro': (' - - ' + ' - '), + 'productType': 'DFP', + 'rateType': 'CPM', + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'lineItemType': 'STANDARD', + 'productSegmentation': { + 'geoSegment': { + 'targetedLocations': [ + {'id': '2840', + 'displayName': 'US'}, + {'id': '2344', + 'displayName': 'Hong Kong'} + ] + }, + 'adUnitSegments': [{ + 'adUnitId': (network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId']), + 'includeDescendants': 'true' + }] + } + } + + product_templates = product_template_service.createProductTemplates( + [product_template]) + + if product_templates: + for product_template in product_templates: + print ('A programmatic product template with ID \'%s\' and name \'%s\' ' + 'was created.' % (product_template['id'], + product_template['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/product_template_service/get_all_product_templates.py b/examples/dfp/v201702/product_template_service/get_all_product_templates.py similarity index 68% rename from examples/dfp/v201605/product_template_service/get_all_product_templates.py rename to examples/dfp/v201702/product_template_service/get_all_product_templates.py index cbc81489..3bfa7f43 100755 --- a/examples/dfp/v201605/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201702/product_template_service/get_all_product_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all product templates. - -To create product templates, run create_product_template_templates.py. - +"""This example gets all product templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -28,20 +23,21 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201605') + 'ProductTemplateService', version='v201702') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select product templates. + statement = dfp.FilterStatement() - # Get product templates by statement. + # Retrieve a small amount of product templates at a time, paging + # through until all product templates have been retrieved. while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' was found.' % ( - product_template['id'], product_template['name'])) + # Print out some information for each product template. + print('Product template with ID "%d" and name "%s" was found.\n' % + (product_template['id'], product_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py similarity index 63% rename from examples/dfp/v201605/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py index 33f799c6..0c729b38 100755 --- a/examples/dfp/v201605/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,9 @@ # 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 code example gets all sponsorship product templates. - +"""This example gets all sponsorship product templates. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -26,28 +23,28 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201605') - - # Create a statement to select all sponsorship product templates. - values = [{ - 'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - } - }] - query = 'WHERE lineItemType = :lineItemType ORDER BY id ASC' + 'ProductTemplateService', version='v201702') + query = 'WHERE lineItemType = :lineItemType' + values = [ + {'key': 'lineItemType', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'SPONSORSHIP' + }}, + ] + # Create a statement to select product templates. statement = dfp.FilterStatement(query, values) - # Get product templates by statement. + # Retrieve a small amount of product templates at a time, paging + # through until all product templates have been retrieved. while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' was found.' % ( - product_template['id'], product_template['name'])) + # Print out some information for each product template. + print('Product template with ID "%d" and name "%s" was found.\n' % + (product_template['id'], product_template['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/product_template_service/update_product_templates.py b/examples/dfp/v201702/product_template_service/update_product_templates.py similarity index 98% rename from examples/dfp/v201605/product_template_service/update_product_templates.py rename to examples/dfp/v201702/product_template_service/update_product_templates.py index c1356465..ecd62653 100755 --- a/examples/dfp/v201605/product_template_service/update_product_templates.py +++ b/examples/dfp/v201702/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201605') + 'ProductTemplateService', version='v201702') # Create a statement to select a single product template by ID. values = [{ diff --git a/examples/dfp/v201605/proposal_line_item_service/__init__.py b/examples/dfp/v201702/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201605/proposal_line_item_service/__init__.py rename to examples/dfp/v201702/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201605/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py similarity index 98% rename from examples/dfp/v201605/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py index 342032f6..48f14301 100755 --- a/examples/dfp/v201605/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201605') + 'ProposalLineItemService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py new file mode 100755 index 00000000..2c8e81e2 --- /dev/null +++ b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -0,0 +1,119 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates a new programmatic proposal line item. +""" + + +from datetime import date +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the programmatic proposal that the proposal line item will +# belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + +# Set the ID of the Marketplace rate card the proposal line items should be +# priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, proposal_id, product_id, rate_card_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201702') + network_service = client.GetService('NetworkService', version='v201702') + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single programmatic proposal line item. + proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + # Setting common required fields for proposal line items. + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'rateCardId': rate_card_id, + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': { + 'date': { + 'year': str(date.today().year), + 'month': str(date.today().month), + 'day': str(date.today().day) + }, + 'hour': '23', + 'minute': '59', + 'second': '59' + }, + 'endDateTime': { + 'date': { + 'year': str(date.today().year + 1), + 'month': '9', + 'day': '30' + }, + 'hour': '0', + 'minute': '0', + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' + }, + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'netCost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'netRate': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add programmatic proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Programmatic proposal line item with id \'%s\', belonging to ' + 'proposal id \'%s\', and named \'%s\' was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py new file mode 100755 index 00000000..7ad91ed1 --- /dev/null +++ b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a programmatic proposal line item for non-sales management. +""" + + +from datetime import date +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set proposal that the created proposal line item will belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, proposal_id, product_id): + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201702') + network_service = client.GetService('NetworkService', version='v201702') + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single programmatic proposal line item. + proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for proposal line items. + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': { + 'date': { + 'year': str(date.today().year), + 'month': str(date.today().month), + 'day': str(date.today().day) + }, + 'hour': '23', + 'minute': '59', + 'second': '59' + }, + 'endDateTime': { + 'date': { + 'year': str(date.today().year + 1), + 'month': '9', + 'day': '30' + }, + 'hour': '0', + 'minute': '0', + 'second': '0', + 'timeZoneID': 'America/Los_Angeles' + }, + 'creativePlaceholders': [{ + 'size': { + 'width': '300', + 'height': '250' + } + }, { + 'size': { + 'width': '120', + 'height': '600' + } + }], + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'netCost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'netRate': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Programmatic proposal line item for non-sales management with id ' + '\'%s\', belonging to proposal id \'%s\', and named \'%s\' ' + 'was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID, PRODUCT_ID) + diff --git a/examples/dfp/v201605/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py similarity index 97% rename from examples/dfp/v201605/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py index ca9270d2..ab452732 100755 --- a/examples/dfp/v201605/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py @@ -41,8 +41,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201605') - network_service = client.GetService('NetworkService', version='v201605') + 'ProposalLineItemService', version='v201702') + network_service = client.GetService('NetworkService', version='v201702') # Get the root ad unit to target. root_ad_unit_id = ( @@ -90,11 +90,11 @@ def main(client, proposal_id, product_id, rate_card_id): 'units': '1000', 'unitType': 'IMPRESSIONS', }, - 'cost': { + 'netCost': { 'currencyCode': 'USD', 'microAmount': '2000000' }, - 'costPerUnit': { + 'netRate': { 'currencyCode': 'USD', 'microAmount': '2000000' }, diff --git a/examples/dfp/v201605/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py similarity index 60% rename from examples/dfp/v201605/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py index 1302dc0f..fb94c552 100755 --- a/examples/dfp/v201605/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,13 +13,9 @@ # 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 code example gets all proposal line items. - -To create proposal line items, run create_proposal_line_items.py. +"""This example gets all proposal line items. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -27,23 +23,21 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201605') + 'ProposalLineItemService', version='v201702') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select proposal line items. + statement = dfp.FilterStatement() - # Get proposal line items by statement. + # Retrieve a small amount of proposal line items at a time, paging + # through until all proposal line items have been retrieved. while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. - for idx, proposal_line_item in enumerate(response['results'], - start=statement.offset): - print ('%s) Proposal line item with id \'%s\', belonging to proposal id' - ' \'%s\', and named \'%s\' was found.' % - (idx, proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + for proposal_line_item in response['results']: + # Print out some information for each proposal line item. + print('Proposal line item with ID "%d" and name "%s" was found.\n' % + (proposal_line_item['id'], proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 54% rename from examples/dfp/v201605/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py index f93ae1c3..bfe0dfe2 100755 --- a/examples/dfp/v201605/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,50 +13,40 @@ # 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 code example gets all proposal line items that belong to a proposal. - -To create proposal line items, run create_proposal_line_items.py.""" - +"""This example gets all proposal line items belonging to a specific proposal. +""" # Import appropriate modules from the client library. from googleads import dfp -# Set the id of the proposal to get proposal line items from. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', - version='v201605') - - # Create statement object to only select proposal line items belonging to a - # given proposal. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE proposalId = :proposalId ORDER BY id ASC' + 'ProposalLineItemService', version='v201702') + query = 'WHERE proposalId = :proposalId' + values = [ + {'key': 'proposalId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + }}, + ] + # Create a statement to select proposal line items. statement = dfp.FilterStatement(query, values) + # Retrieve a small amount of proposal line items at a time, paging + # through until all proposal line items have been retrieved. while True: - # Get proposal line items by statement. response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: - # Display results. - for idx, proposal_line_item in enumerate(response['results'], - start=statement.offset): - print( - '%s) Proposal line item with id \'%s\', belonging to proposal id ' - '\'%s\', and named \'%s\' was found.' % ( - idx, proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + for proposal_line_item in response['results']: + # Print out some information for each proposal line item. + print('Proposal line item with ID "%d" and name "%s" was found.\n' % + (proposal_line_item['id'], proposal_line_item['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py similarity index 94% rename from examples/dfp/v201605/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py index ee40006f..b2309a40 100755 --- a/examples/dfp/v201605/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201605') + 'ProposalLineItemService', version='v201702') # Create statement to select a proposal line item. values = [{ @@ -52,7 +52,7 @@ def main(client, proposal_line_item_id): if 'results' in response: # Update each the proposal line item's notes field. proposal_line_item = response['results'][0] - proposal_line_item['notes'] = 'Proposal line item ready for submission.' + proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.' # Update proposal line items remotely. proposal_line_items = proposal_line_item_service.updateProposalLineItems( diff --git a/examples/dfp/v201605/proposal_service/__init__.py b/examples/dfp/v201702/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201605/proposal_service/__init__.py rename to examples/dfp/v201702/proposal_service/__init__.py diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py new file mode 100755 index 00000000..b650aac1 --- /dev/null +++ b/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py @@ -0,0 +1,71 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates new programmatic proposals. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' +BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' + + +def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, + buyer_id): + proposal_service = client.GetService('ProposalService', version='v201702') + network_service = client.GetService('NetworkService', version='v201702') + + proposal = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'buyerAccountId': buyer_id + }, + 'isProgrammatic': True, + # Setting required common fields for Proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), + 'advertiser': { + 'companyId': advertiser_id, + 'type': 'ADVERTISER' + }, + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '100000' + }, + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + 'budget': { + 'microAmount': '100000000', + 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] + }, + } + proposals = proposal_service.createProposals([proposal]) + + # Display results. + for proposal in proposals: + print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + (proposal['id'], proposal['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID, + BUYER_ID) diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py new file mode 100755 index 00000000..0d910fc8 --- /dev/null +++ b/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a programmatic proposal for networks not using sales management. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + +PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' + + +def main(client, programmatic_buyer_id, primary_salesperson_id, + primary_trafficker_id): + proposal_service = client.GetService('ProposalService', version='v201702') + + proposal = { + # Setting required Marketplace information. + 'isProgrammatic': 'true', + 'marketplaceInfo': { + 'buyerAccountId': programmatic_buyer_id, + }, + # Set common required fields for proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '100000' + }, + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + } + + proposals = proposal_service.createProposals([proposal]) + + # Display results. + for proposal in proposals: + print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + (proposal['id'], proposal['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201605/proposal_service/create_proposals.py b/examples/dfp/v201702/proposal_service/create_proposals.py similarity index 94% rename from examples/dfp/v201605/proposal_service/create_proposals.py rename to examples/dfp/v201702/proposal_service/create_proposals.py index b725d22b..f1043d11 100755 --- a/examples/dfp/v201605/proposal_service/create_proposals.py +++ b/examples/dfp/v201702/proposal_service/create_proposals.py @@ -16,7 +16,8 @@ """This code example creates new proposals. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" import uuid @@ -33,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201605') - network_service = client.GetService('NetworkService', version='v201605') + proposal_service = client.GetService('ProposalService', version='v201702') + network_service = client.GetService('NetworkService', version='v201702') # Create proposal objects. proposal = { @@ -62,7 +63,7 @@ def main(client, advertiser_id, primary_salesperson_id, } # Add proposals. - proposals = proposal_service.createProposals([proposals]) + proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: diff --git a/examples/dfp/v201605/proposal_service/get_all_proposals.py b/examples/dfp/v201702/proposal_service/get_all_proposals.py similarity index 72% rename from examples/dfp/v201605/proposal_service/get_all_proposals.py rename to examples/dfp/v201702/proposal_service/get_all_proposals.py index cd1797bf..a06117ac 100755 --- a/examples/dfp/v201605/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201702/proposal_service/get_all_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,32 +13,29 @@ # 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 code example gets all proposals. - -To create proposals, run create_proposals.py. +"""This example gets all proposals. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201605') + proposal_service = client.GetService('ProposalService', version='v201702') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select proposals. + statement = dfp.FilterStatement() - # Get proposals by statement. + # Retrieve a small amount of proposals at a time, paging + # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\' and name \'%s\' was found.' % ( - proposal['id'], proposal['name'])) + # Print out some information for each proposal. + print('Proposal with ID "%d" and name "%s" was found.\n' % + (proposal['id'], proposal['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py b/examples/dfp/v201702/proposal_service/get_marketplace_comments.py new file mode 100755 index 00000000..357dcbbc --- /dev/null +++ b/examples/dfp/v201702/proposal_service/get_marketplace_comments.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the Marketplace comments for a programmatic proposal.""" + +# Import appropriate modules from the client library. +from datetime import datetime + +from googleads import dfp + + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + marketplace_comment_service = client.GetService( + 'ProposalService', version='v201702') + query = 'WHERE proposalId = %s' % proposal_id + # Create a statement to select marketplace comments. + statement = {'query': query} + + response = marketplace_comment_service.getMarketplaceCommentsByStatement( + statement) + + # Print out some information for each marketplace comment. + for marketplace_comment in response['results']: + date_time = marketplace_comment['creationTime'] + date_time_string = datetime(date_time['date']['year'], + date_time['date']['month'], + date_time['date']['day'], date_time['hour'], + date_time['minute'], + date_time['second']).isoformat() + print('Marketplace comment with creation time "%s"and comment "%s" was ' + 'found.\n' % (date_time_string, marketplace_comment['comment'])) + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201605/proposal_service/get_proposals_by_statement.py b/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py similarity index 66% rename from examples/dfp/v201605/proposal_service/get_proposals_by_statement.py rename to examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py index 343eba97..62b7dd00 100755 --- a/examples/dfp/v201605/proposal_service/get_proposals_by_statement.py +++ b/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,11 +13,8 @@ # 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 code example gets all proposals that are currently 'PENDING_APPROVAL.' - -To create proposals, run create_proposals.py.""" - +"""This example gets all proposals pending approval. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -25,28 +22,27 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201605') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - } - }] - query = 'WHERE status = :status ORDER BY id ASC' - + proposal_service = client.GetService('ProposalService', version='v201702') + query = 'WHERE status = :status' + values = [ + {'key': 'status', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'PENDING_APPROVAL' + }}, + ] + # Create a statement to select proposals. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of proposals at a time, paging + # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\' name \'%s\' was found.' - % (proposal['id'], proposal['name'])) + # Print out some information for each proposal. + print('Proposal with ID "%d" and name "%s" was found.\n' % + (proposal['id'], proposal['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py new file mode 100755 index 00000000..72eb3ab9 --- /dev/null +++ b/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example requests buyer acceptance for a single proposal. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201702') + + # Create query. + values = [{ + 'key': 'proposalId', + 'value': { + 'xsi_type': 'TextValue', + 'value': proposal_id + } + }] + query = 'WHERE id = :proposalId' + + # Create a filter statement. + statement = dfp.FilterStatement(query, values) + proposals_pushed_to_marketplace = 0 + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response: + # Display results. + for proposal in response['results']: + print ('Programmatic proposal with id \'%s\', name \'%s\', and status ' + '\'%s\' will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) + # Perform action. + result = proposal_service.performProposalAction( + {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposals_pushed_to_marketplace += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if proposals_pushed_to_marketplace > 0: + print ('\nNumber of programmatic proposals pushed to Marketplace: %s' + % proposals_pushed_to_marketplace) + else: + print '\nNo programmatic proposals were pushed to Marketplace.' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, PROPOSAL_ID) diff --git a/examples/dfp/v201605/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py similarity index 96% rename from examples/dfp/v201605/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py index 0810c29b..cd4cce22 100755 --- a/examples/dfp/v201605/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py @@ -16,7 +16,8 @@ """This code example approves a single proposal. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" # Import appropriate modules from the client library. @@ -24,9 +25,10 @@ PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201605') + proposal_service = client.GetService('ProposalService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/proposal_service/update_proposals.py b/examples/dfp/v201702/proposal_service/update_proposals.py similarity index 90% rename from examples/dfp/v201605/proposal_service/update_proposals.py rename to examples/dfp/v201702/proposal_service/update_proposals.py index 02e14e7b..fa539df7 100755 --- a/examples/dfp/v201605/proposal_service/update_proposals.py +++ b/examples/dfp/v201702/proposal_service/update_proposals.py @@ -16,7 +16,8 @@ """This code example updates the notes of a single proposal specified by ID. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201605') + proposal_service = client.GetService('ProposalService', version='v201702') # Create statement object to select a single proposal by an ID. values = [{ @@ -48,7 +49,7 @@ def main(client, proposal_id): # Update each local proposal object by changing its notes. updated_proposals = [] for proposal in response['results']: - proposal['notes'] = 'Proposal needs further review before approval.' + proposal['internalNotes'] = 'Proposal needs review before approval.' updated_proposals.append(proposal) # Update proposals remotely. @@ -59,7 +60,7 @@ def main(client, proposal_id): for proposal in proposals: print ('Proposal with id \'%s\', name \'%s\', and ' 'notes \'%s\' was updated.' - % (proposal['id'], proposal['name'], proposal['notes'])) + % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: print 'No proposals were updated.' else: diff --git a/examples/dfp/v201605/publisher_query_language_service/__init__.py b/examples/dfp/v201702/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201605/publisher_query_language_service/__init__.py rename to examples/dfp/v201702/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201605/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py similarity index 90% rename from examples/dfp/v201605/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py index 99fa8da6..ec8a6a2a 100755 --- a/examples/dfp/v201605/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201605') + report_downloader = client.GetDataDownloader(version='v201702') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) @@ -45,8 +45,8 @@ def main(client): line_items_file.close() ad_units_file.close() - print ('Saved line items to... %s' % line_items_file.name) - print ('Saved ad units to... %s' % ad_units_file.name) + print 'Saved line items to... %s' % line_items_file.name + print 'Saved ad units to... %s' % ad_units_file.name if __name__ == '__main__': diff --git a/examples/dfp/v201605/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 57% rename from examples/dfp/v201605/publisher_query_language_service/get_line_items_named_like.py rename to examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py index a1fb4351..55ede95f 100755 --- a/examples/dfp/v201605/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all line items with names starting with 'line item'.""" +"""This example fetches programmatic buyer information from the PQL table.""" import tempfile @@ -25,29 +25,22 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201605') + data_downloader = client.GetDataDownloader(version='v201702') - output_file = tempfile.NamedTemporaryFile( - prefix='line_items_named_like_', suffix='.csv', mode='w', delete=False) + programmatic_buyers_file = tempfile.NamedTemporaryFile( + prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) - # Create bind value to select line items with names starting with 'line item'. - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'line item%' - } - }] - - pql_query = ('SELECT Name, Id, Status FROM Line_Item ' - 'WHERE Name LIKE :name') + programmatic_buyers_query = ('SELECT BuyerAccountId, Name ' + 'FROM Programmatic_Buyer ' + 'ORDER BY BuyerAccountId ASC') # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - pql_query, output_file, values) - output_file.close() + data_downloader.DownloadPqlResultToCsv( + programmatic_buyers_query, programmatic_buyers_file) + + programmatic_buyers_file.close() - print ('Saved line items to... %s' % output_file.name) + print 'Saved programmatic buyers to... %s' % programmatic_buyers_file.name if __name__ == '__main__': diff --git a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py new file mode 100755 index 00000000..32f43977 --- /dev/null +++ b/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py @@ -0,0 +1,210 @@ +#!/usr/bin/python +# +# Copyright 2017 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. + +"""Gets recent changes in your network using the Change_History table. + +A full list of available tables can be found at: +https://developers.google.com/doubleclick-publishers/docs/reference/latest/PublisherQueryLanguageService +""" + +from datetime import date +from datetime import datetime +from datetime import timedelta + +# Import appropriate modules from the client library. +from googleads import dfp +import pytz + + +def main(client): + # Initialize appropriate service. + pql_service = client.GetService('PublisherQueryLanguageService', 'v201702') + + end_date = date.today() + start_date = end_date - timedelta(days=1) + initial_query = ( + 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' + 'FROM Change_History ' + 'WHERE ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime ' + 'ORDER BY ChangeDateTime DESC') + pagination_query = ( + 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' + 'FROM Change_History ' + 'WHERE Id < :id ' + 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' + 'ORDER BY ChangeDateTime DESC') + values = [ + { + 'key': 'startDateTime', + 'value': { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': start_date.year, + 'month': start_date.month, + 'day': start_date.day + } + } + } + }, + { + 'key': 'endDateTime', + 'value': { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': end_date.year, + 'month': end_date.month, + 'day': end_date.day + } + } + } + } + ] + + statement = dfp.FilterStatement(initial_query, values) + keep_iterating = True + i = 0 + total_rows = [] + + while keep_iterating: + response = pql_service.select(statement.ToStatement()) + column_types = ([column_type['labelName'] + for column_type in response['columnTypes']]) + rows = response['rows'] + rows_length = len(rows) + total_rows.extend(rows) + + if rows and rows_length > 0: + # Get the earliest change ID in the result set. + last_row = rows[-1] + last_id = last_row['values'][0]['value'] + i += 1 + statement = UpdateFilterStatement( + statement, pagination_query, values, last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' + % (i, rows_length, last_id)) + + keep_iterating = rows and len(rows) == statement.limit + + # Print out columns header + print ','.join(column_types) + + # Print out every row + for row in total_rows: + print ConvertValueForCsv(row) + + +def UpdateFilterStatement(statement, query, values, last_id): + """Updates the FilterStatement in order to page through results. + + Args: + statement: an instantiated FilterStatement. + query: a str query that will be used to update the FilterStatement. + values: a list of bind variables to be updated. + last_id: a str representing the earliest change ID in a result set. + + Returns: + FilterStatement the updated statement. + """ + # Use the earliest change ID in the result set to page. + updated_values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'TextValue', + 'value': last_id + } + }] + updated_values.extend(values) + + statement.where_clause = query + statement.values = updated_values + + return statement + + +def ConvertValueForCsv(pql_value): + """Sanitizes a field value from a Value object to a CSV suitable format. + + Args: + pql_value: dict a dictionary containing the data for a single field of an + entity. + + Returns: + str a CSV writer friendly value formatted by Value.Type. + """ + if 'value' in pql_value: + field = pql_value['value'] + elif 'values' in pql_value: + field = pql_value['values'] + else: + field = None + + if field: + if isinstance(field, list): + return ','.join(['"%s"' % str(ConvertValueForCsv(single_field)) + for single_field in field]) + else: + class_type = dfp.DfpClassType(pql_value) + + if class_type == 'TextValue': + return field.replace('"', '""').encode('UTF8') + elif class_type == 'NumberValue': + return float(field) if '.' in field else int(field) + elif class_type == 'DateTimeValue': + return ConvertDateTimeToOffset(field) + elif class_type == 'DateValue': + return date(int(field['date']['year']), + int(field['date']['month']), + int(field['date']['day'])).isoformat() + else: + return field + else: + return '-' + + +def ConvertDateTimeToOffset(date_time_value): + """Converts the PQL formatted response for a dateTime object. + + Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.' + + Args: + date_time_value: dict The date time value from the PQL response. + + Returns: + str: A string representation of the date time value uniform to + ReportService. + """ + date_time_obj = datetime(int(date_time_value['date']['year']), + int(date_time_value['date']['month']), + int(date_time_value['date']['day']), + int(date_time_value['hour']), + int(date_time_value['minute']), + int(date_time_value['second'])) + date_time_str = pytz.timezone( + date_time_value['timeZoneID']).localize(date_time_obj).isoformat() + + if date_time_str[-5:] == '00:00': + return date_time_str[:-6] + 'Z' + else: + return date_time_str + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/rate_card_service/__init__.py b/examples/dfp/v201702/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201605/rate_card_service/__init__.py rename to examples/dfp/v201702/rate_card_service/__init__.py diff --git a/examples/dfp/v201605/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py similarity index 64% rename from examples/dfp/v201605/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201702/rate_card_service/get_all_rate_cards.py index a6a16ad5..264e016e 100755 --- a/examples/dfp/v201605/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,33 +13,31 @@ # 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 code example gets all rate cards. - +"""This example gets all rate cards. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201605') + rate_card_service = client.GetService('RateCardService', version='v201702') - # Create a filter statement. - statement = dfp.FilterStatement('ORDER BY id ASC') + # Create a statement to select rate cards. + statement = dfp.FilterStatement() - # Get rate cards by statement. + # Retrieve a small amount of rate cards at a time, paging + # through until all rate cards have been retrieved. while True: - response = rate_card_service.getRateCardsByStatement( - statement.ToStatement()) + response = rate_card_service.getRateCardsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for rate_card in response['results']: - print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' - 'was found.' % (rate_card['id'], rate_card['name'], - rate_card['currencyCode'])) + # Print out some information for each rate card. + print('Rate card with ID "%d", name "%s", and currency code "%s" was ' + 'found.\n' % + (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/rate_card_service/get_rate_cards_priced_with_currency.py b/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py similarity index 58% rename from examples/dfp/v201605/rate_card_service/get_rate_cards_priced_with_currency.py rename to examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py index 9b9a67a2..df36b13c 100755 --- a/examples/dfp/v201605/rate_card_service/get_rate_cards_priced_with_currency.py +++ b/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,41 +14,39 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all rate cards that have a currency in US dollars. - +"""This example gets all rate cards that can be used for Marketplace products. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201605') - - # Create a statement to get all rate cards using USD as currency. - values = [{ - 'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'USD' - } - }] - query = 'WHERE currencyCode = :currencyCode' - + rate_card_service = client.GetService('RateCardService', version='v201702') + query = 'WHERE forMarketplace = :forMarketplace' + values = [ + {'key': 'forMarketplace', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': 'true' + }}, + ] + # Create a statement to select rate cards. statement = dfp.FilterStatement(query, values) - # Get rate cards by statement. + # Retrieve a small amount of rate cards at a time, paging + # through until all rate cards have been retrieved. while True: - response = rate_card_service.getRateCardsByStatement( - statement.ToStatement()) + response = rate_card_service.getRateCardsByStatement(statement.ToStatement( + )) if 'results' in response: - # Display results. for rate_card in response['results']: - print ('Rate card with id \'%s,\' name \'%s,\' and currency \'%s\' ' - 'was found.' % (rate_card['id'], rate_card['name'], - rate_card['currencyCode'])) + # Print out some information for each rate card. + print( + 'Rate card with ID "%d", name "%s", and currency code "%s" was ' + 'found.\n' + % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py new file mode 100755 index 00000000..811a1c7c --- /dev/null +++ b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets a reconciliation report's data for line items that served through DFP. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_line_item_report_service = client.GetService( + 'ReconciliationLineItemReportService', version='v201702') + query = ('WHERE reconciliationReportId = :reconciliationReportId AND ' + 'lineItemId != :lineItemId') + values = [ + {'key': 'reconciliationReportId', + 'value': { + 'xsi_type': 'TextValue', + 'value': reconciliation_report_id + }}, + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + }}, + ] + # Create a statement to select reconciliation line item reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation line item reports at a time, + # paging through until all reconciliation line item reports have been + # retrieved. + while True: + response = ( + reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_line_item_report in response['results']: + # Print out some information for each reconciliation line item report. + print( + 'Reconciliation line item report with ID "%d", line item ID "%d", ' + 'reconciliation source "%s", and reconciled volume "%d" was ' + 'found.\n' % + (reconciliation_line_item_report['id'], + reconciliation_line_item_report['lineItemId'], + reconciliation_line_item_report['reconciliationSource'], + reconciliation_line_item_report['reconciledVolume'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py new file mode 100755 index 00000000..c3492a2d --- /dev/null +++ b/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets all reconciliation order reports for a given reconciliation report. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_order_report_service = client.GetService( + 'ReconciliationOrderReportService', version='v201702') + query = 'WHERE reconciliationReportId = :reconciliationReportId' + values = [ + {'key': 'reconciliationReportId', + 'value': { + 'xsi_type': 'TextValue', + 'value': reconciliation_report_id + }}, + ] + # Create a statement to select reconciliation order reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation order reports at a time, paging + # through until all reconciliation order reports have been retrieved. + while True: + response = ( + reconciliation_order_report_service + .getReconciliationOrderReportsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_order_report in response['results']: + # Print out some information for each reconciliation order report. + print('Reconciliation order report with ID "%d" and status "%s" was ' + 'found.\n' % (reconciliation_order_report['id'], + reconciliation_order_report['status'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py new file mode 100755 index 00000000..fc2e2570 --- /dev/null +++ b/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2016 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. +"""Gets a reconciliation report's rows for line items that served through DFP. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_report_row_service = client.GetService( + 'ReconciliationReportRowService', version='v201702') + query = ('WHERE reconciliationReportId = %s AND ' + 'lineItemId != :lineItemId') % reconciliation_report_id + values = [ + {'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + }}, + ] + # Create a statement to select reconciliation report rows. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation report rows at a time, paging + # through until all reconciliation report rows have been retrieved. + while True: + response = ( + reconciliation_report_row_service + .getReconciliationReportRowsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_report_row in response['results']: + # Print out some information for each reconciliation report row. + print('Reconciliation report row with ID "%d", reconciliation source ' + '"%s", and reconciled volume "%d" was found.\n' % + (reconciliation_report_row['id'], + reconciliation_report_row['reconciliationSource'], + reconciliation_report_row['reconciledVolume'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py new file mode 100755 index 00000000..415bdcc0 --- /dev/null +++ b/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py @@ -0,0 +1,56 @@ +#!/usr/bin/python +# +# Copyright 2016 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 reconciliation reports. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + reconciliation_report_service = client.GetService( + 'ReconciliationReportService', version='v201702') + + # Create a statement to select reconciliation reports. + statement = dfp.FilterStatement() + + # Retrieve a small amount of reconciliation reports at a time, paging + # through until all reconciliation reports have been retrieved. + while True: + response = ( + reconciliation_report_service + .getReconciliationReportsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_report in response['results']: + # Print out some information for each reconciliation report. + print( + 'Reconciliation report with ID "%d", month "%d", and year "%d" was' + ' found.\n' % (reconciliation_report['id'], + reconciliation_report['startDate']['month'], + reconciliation_report['startDate']['year'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py new file mode 100755 index 00000000..a802c9c7 --- /dev/null +++ b/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the previous billing period's reconciliation report. +""" + +# Import appropriate modules from the client library. +from datetime import date +from datetime import timedelta + +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + reconciliation_report_service = client.GetService( + 'ReconciliationReportService', version='v201702') + + first_of_the_month = date.today().replace(day=1) + last_month = first_of_the_month - timedelta(days=1) + + query = 'WHERE startDate = :startDate' + values = [ + {'key': 'startDate', + 'value': { + 'xsi_type': 'TextValue', + 'value': last_month.strftime('%Y-%m-01') + }}, + ] + # Create a statement to select reconciliation reports. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of reconciliation reports at a time, paging + # through until all reconciliation reports have been retrieved. + while True: + response = ( + reconciliation_report_service + .getReconciliationReportsByStatement( + statement.ToStatement())) + if 'results' in response: + for reconciliation_report in response['results']: + # Print out some information for each reconciliation report. + print( + 'Reconciliation report with ID "%d" and start date "%s" was found.' + '\n' % (reconciliation_report['id'], + last_month.strftime('%Y-%m-01'))) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201605/report_service/__init__.py b/examples/dfp/v201702/report_service/__init__.py similarity index 100% rename from examples/dfp/v201605/report_service/__init__.py rename to examples/dfp/v201702/report_service/__init__.py diff --git a/examples/dfp/v201605/report_service/run_delivery_report.py b/examples/dfp/v201702/report_service/run_delivery_report.py similarity index 93% rename from examples/dfp/v201605/report_service/run_delivery_report.py rename to examples/dfp/v201702/report_service/run_delivery_report.py index 4fa2a96a..c379caaf 100755 --- a/examples/dfp/v201605/report_service/run_delivery_report.py +++ b/examples/dfp/v201702/report_service/run_delivery_report.py @@ -14,8 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report similar to the "Orders report" on the DFP -website with additional attributes and can filter to include just one order. +"""Runs a report similar to the "Orders report" on the DFP website. + +Includes additional attributes and can filter to include just one order. """ from datetime import datetime @@ -66,7 +67,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201605') + report_downloader = client.GetDataDownloader(version='v201702') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201605/report_service/run_inventory_report.py b/examples/dfp/v201702/report_service/run_inventory_report.py similarity index 94% rename from examples/dfp/v201605/report_service/run_inventory_report.py rename to examples/dfp/v201702/report_service/run_inventory_report.py index 8c5befa4..3774ba19 100755 --- a/examples/dfp/v201605/report_service/run_inventory_report.py +++ b/examples/dfp/v201702/report_service/run_inventory_report.py @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report equal to the "Whole network report" on the -DFP website. -""" +"""Runs a report equal to the "Whole network report" on the DFP website.""" import tempfile @@ -27,9 +25,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201605') + network_service = client.GetService('NetworkService', version='v201702') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201605') + report_downloader = client.GetDataDownloader(version='v201702') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201605/report_service/run_reach_report.py b/examples/dfp/v201702/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201605/report_service/run_reach_report.py rename to examples/dfp/v201702/report_service/run_reach_report.py index 58364ff9..72d144f8 100755 --- a/examples/dfp/v201605/report_service/run_reach_report.py +++ b/examples/dfp/v201702/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201605') + report_downloader = client.GetDataDownloader(version='v201702') # Create report job. report_job = { diff --git a/examples/dfp/v201605/report_service/run_report_with_custom_fields.py b/examples/dfp/v201702/report_service/run_report_with_custom_fields.py similarity index 94% rename from examples/dfp/v201605/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201702/report_service/run_report_with_custom_fields.py index 169a8496..8c9f92e2 100755 --- a/examples/dfp/v201605/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201702/report_service/run_report_with_custom_fields.py @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report that with custom fields found in the line -items of an order. -""" +"""Runs a report with custom fields found in the line items of an order.""" import tempfile @@ -30,9 +28,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201605') + line_item_service = client.GetService('LineItemService', version='v201702') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201605') + report_downloader = client.GetDataDownloader(version='v201702') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201605/report_service/run_sales_report.py b/examples/dfp/v201702/report_service/run_sales_report.py similarity index 92% rename from examples/dfp/v201605/report_service/run_sales_report.py rename to examples/dfp/v201702/report_service/run_sales_report.py index db25f236..09fed67a 100755 --- a/examples/dfp/v201605/report_service/run_sales_report.py +++ b/examples/dfp/v201702/report_service/run_sales_report.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report equal to the "Sales by salespersons report." -""" +"""Runs a report equal to the 'Sales by salespersons report'.""" import tempfile @@ -26,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201605') + report_downloader = client.GetDataDownloader(version='v201702') # Create report job. report_job = { diff --git a/examples/dfp/v201702/report_service/run_saved_query.py b/examples/dfp/v201702/report_service/run_saved_query.py new file mode 100755 index 00000000..20a6be2d --- /dev/null +++ b/examples/dfp/v201702/report_service/run_saved_query.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 runs a report from a saved query. +""" + +# Import appropriate modules from the client library. +import tempfile + +from googleads import dfp +from googleads import errors + +SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' + + +def main(client, saved_query_id): + # Initialize appropriate service. + report_service = client.GetService('ReportService', version='v201702') + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201702') + + # Create statement object to filter for an order. + values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'NumberValue', + 'value': saved_query_id + } + }] + query = 'WHERE id = :id' + statement = dfp.FilterStatement(query, values, 1) + + response = report_service.getSavedQueriesByStatement( + statement.ToStatement()) + + if 'results' in response: + saved_query = response['results'][0] + + if saved_query['isCompatibleWithApiVersion']: + report_job = {} + + # Set report query and optionally modify it. + report_job['reportQuery'] = saved_query['reportQuery'] + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id \'%s\' downloaded to:\n%s' % ( + report_job_id, report_file.name) + else: + print 'The query specified is not compatible with the API version.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, SAVED_QUERY_ID) diff --git a/examples/dfp/v201605/suggested_ad_unit_service/__init__.py b/examples/dfp/v201702/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201605/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201702/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201605/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201605/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py index d5417ce8..2ac63825 100755 --- a/examples/dfp/v201605/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201605') + 'SuggestedAdUnitService', version='v201702') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201605/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 69% rename from examples/dfp/v201605/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py index 7ab1a1b8..14c4dbc3 100755 --- a/examples/dfp/v201605/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,14 +13,9 @@ # 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 code example gets all suggested ad units. - -To approve suggested ad units, run approve_suggested_ad_units.py. This feature -is only available to DFP premium solution networks. +"""This example gets all suggested ad units. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -28,26 +23,29 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201605') + 'SuggestedAdUnitService', version='v201702') - # Create a filter statement. + # Create a statement to select suggested ad units. statement = dfp.FilterStatement() - # Get suggested ad units by statement. + # Retrieve a small amount of suggested ad units at a time, paging + # through until all suggested ad units have been retrieved. while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for suggested_ad_unit in response['results']: - print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + # Print out some information for each suggested ad unit. + print( + 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' + % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py b/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 58% rename from examples/dfp/v201605/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py rename to examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 3cc6a7cf..87869c9a 100755 --- a/examples/dfp/v201605/suggested_ad_unit_service/get_suggested_ad_units_by_statement.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,51 +13,49 @@ # 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 code example gets suggested ad units that have more than 50 requests. - -This feature is only available to DFP premium solution networks. +"""This example gets all highly requested suggested ad units. """ - # Import appropriate modules from the client library. from googleads import dfp +NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE' + -def main(client): +def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201605') - - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '50' - } - }] - - query = 'WHERE numRequests > :numRequests' - - # Create a filter statement. + 'SuggestedAdUnitService', version='v201702') + query = 'WHERE numRequests >= :numRequests' + values = [ + {'key': 'numRequests', + 'value': { + 'xsi_type': 'TextValue', + 'value': num_requests + }}, + ] + # Create a statement to select suggested ad units. statement = dfp.FilterStatement(query, values) - # Get suggested ad units by statement. + # Retrieve a small amount of suggested ad units at a time, paging + # through until all suggested ad units have been retrieved. while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for suggested_ad_unit in response['results']: - print ('Ad unit with id \'%s\' and number of requests \'%s\' was found.' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + # Print out some information for each suggested ad unit. + print( + 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' + % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + main(dfp_client, NUM_REQUESTS) diff --git a/examples/dfp/v201605/team_service/__init__.py b/examples/dfp/v201702/team_service/__init__.py similarity index 100% rename from examples/dfp/v201605/team_service/__init__.py rename to examples/dfp/v201702/team_service/__init__.py diff --git a/examples/dfp/v201605/team_service/create_teams.py b/examples/dfp/v201702/team_service/create_teams.py similarity index 94% rename from examples/dfp/v201605/team_service/create_teams.py rename to examples/dfp/v201702/team_service/create_teams.py index 70e65266..116fccb3 100755 --- a/examples/dfp/v201605/team_service/create_teams.py +++ b/examples/dfp/v201702/team_service/create_teams.py @@ -22,7 +22,6 @@ "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. - """ @@ -34,11 +33,11 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201605') + team_service = client.GetService('TeamService', version='v201702') # Create team objects. teams = [] - for i in xrange(5): + for _ in xrange(5): team = { 'name': 'Team %s' % uuid.uuid4(), 'hasAllCompanies': 'false', diff --git a/examples/dfp/v201605/team_service/get_all_teams.py b/examples/dfp/v201702/team_service/get_all_teams.py similarity index 66% rename from examples/dfp/v201605/team_service/get_all_teams.py rename to examples/dfp/v201702/team_service/get_all_teams.py index bb847b45..3448e552 100755 --- a/examples/dfp/v201605/team_service/get_all_teams.py +++ b/examples/dfp/v201702/team_service/get_all_teams.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,44 +13,36 @@ # 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 teams. - -To create teams, run create_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201605') + team_service = client.GetService('TeamService', version='v201702') - # Create a filter statement. + # Create a statement to select teams. statement = dfp.FilterStatement() - # Get users by statement. + # Retrieve a small amount of teams at a time, paging + # through until all teams have been retrieved. while True: response = team_service.getTeamsByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for team in response['results']: - print ('Team with ID \'%s\' and name \'%s\' was found.' - % (team['id'], team['name'])) + # Print out some information for each team. + print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], + team['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/team_service/update_teams.py b/examples/dfp/v201702/team_service/update_teams.py similarity index 73% rename from examples/dfp/v201605/team_service/update_teams.py rename to examples/dfp/v201702/team_service/update_teams.py index f511fbc2..62e08691 100755 --- a/examples/dfp/v201605/team_service/update_teams.py +++ b/examples/dfp/v201702/team_service/update_teams.py @@ -14,10 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates teams by adding an ad unit to a team. +"""This example updates teams by changing its description. -To determine which teams exist, run get_all_teams.py. To determine which ad -units exist, run get_all_ad_units.py +To determine which teams exist, run get_all_teams.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,13 +29,12 @@ # Import appropriate modules from the client library. from googleads import dfp -AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' TEAM_ID = 'INSERT_TEAM_ID_HERE' -def main(client, ad_unit_id, team_id): +def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201605') + team_service = client.GetService('TeamService', version='v201702') # Create a filter statement to select a single team by ID. values = [{ @@ -54,15 +52,9 @@ def main(client, ad_unit_id, team_id): if 'results' in response: updated_teams = [] - # Update each local team object by adding the ad unit to it. + # Update each local team object by changing its description. for team in response['results']: - ad_unit_ids = [] - if 'adUnitIds' in team: - ad_unit_ids = team['adUnitIds'] - # Don't add the ad unit if the team has all inventory already. - if not team['hasAllInventory']: - ad_unit_ids.append(ad_unit_id) - team['adUnitIds'] = ad_unit_ids + team['description'] = 'this team is great!' updated_teams.append(team) # Update teams on the server. @@ -78,4 +70,4 @@ def main(client, ad_unit_id, team_id): if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AD_UNIT_ID, TEAM_ID) + main(dfp_client, TEAM_ID) diff --git a/examples/dfp/v201605/user_service/__init__.py b/examples/dfp/v201702/user_service/__init__.py similarity index 100% rename from examples/dfp/v201605/user_service/__init__.py rename to examples/dfp/v201702/user_service/__init__.py diff --git a/examples/dfp/v201605/user_service/create_users.py b/examples/dfp/v201702/user_service/create_users.py similarity index 92% rename from examples/dfp/v201605/user_service/create_users.py rename to examples/dfp/v201702/user_service/create_users.py index f41a7655..14e21113 100755 --- a/examples/dfp/v201605/user_service/create_users.py +++ b/examples/dfp/v201702/user_service/create_users.py @@ -16,7 +16,8 @@ """This code example creates new users. -To determine which users exist, run get_all_users.py.""" +To determine which users exist, run get_all_users.py. +""" # Import appropriate modules from the client library. @@ -28,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') + user_service = client.GetService('UserService', version='v201702') # Create user objects. users = [ diff --git a/examples/dfp/v201605/user_service/deactivate_users.py b/examples/dfp/v201702/user_service/deactivate_users.py similarity index 96% rename from examples/dfp/v201605/user_service/deactivate_users.py rename to examples/dfp/v201702/user_service/deactivate_users.py index 12b0872f..66819175 100755 --- a/examples/dfp/v201605/user_service/deactivate_users.py +++ b/examples/dfp/v201702/user_service/deactivate_users.py @@ -18,7 +18,8 @@ Deactivated users can no longer make requests to the API. The user making the request cannot deactivate itself. To determine which users exist, run -get_all_users.py.""" +get_all_users.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') + user_service = client.GetService('UserService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/user_service/get_all_roles.py b/examples/dfp/v201702/user_service/get_all_roles.py similarity index 75% rename from examples/dfp/v201605/user_service/get_all_roles.py rename to examples/dfp/v201702/user_service/get_all_roles.py index ba3a4607..03f79651 100755 --- a/examples/dfp/v201605/user_service/get_all_roles.py +++ b/examples/dfp/v201702/user_service/get_all_roles.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,12 +13,8 @@ # 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 code example gets all roles. - -This sample can be used to determine which role id is needed when getting and -creating users.""" - +"""This example gets all roles. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -28,16 +24,16 @@ def main(client): # Initialize appropriate service. user_service = client.GetService('UserService', version='v201605') - # Get all roles. roles = user_service.getAllRoles() - # Display results. + # Print out some information for each role. for role in roles: - print ('Role with id \'%s\' and name \'%s\' was found.' - % (role['id'], role['name'])) + print('Role with id \'%s\' and name \'%s\' was found.' % + (role['id'], role['name'])) print '\nNumber of results found: %s' % len(roles) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/user_service/get_all_users.py b/examples/dfp/v201702/user_service/get_all_users.py similarity index 69% rename from examples/dfp/v201605/user_service/get_all_users.py rename to examples/dfp/v201702/user_service/get_all_users.py index a50c9be6..b7ff6a1b 100755 --- a/examples/dfp/v201605/user_service/get_all_users.py +++ b/examples/dfp/v201702/user_service/get_all_users.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,9 +13,8 @@ # 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 code example gets all users. To create users, run create_users.py.""" - +"""This example gets all users. +""" # Import appropriate modules from the client library. from googleads import dfp @@ -23,25 +22,27 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') + user_service = client.GetService('UserService', version='v201702') - # Create a filter statement. + # Create a statement to select users. statement = dfp.FilterStatement() - # Get users by statement. + # Retrieve a small amount of users at a time, paging + # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) if 'results' in response: - # Display results. for user in response['results']: - print ('User with id \'%s\', email \'%s\', and role \'%s\' was found.' - % (user['id'], user['email'], user['roleName'])) + # Print out some information for each user. + print('User with ID "%d" and name "%s" was found.\n' % (user['id'], + user['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_service/get_user_by_email_address.py b/examples/dfp/v201702/user_service/get_user_by_email_address.py new file mode 100755 index 00000000..f6993643 --- /dev/null +++ b/examples/dfp/v201702/user_service/get_user_by_email_address.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 users by email. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' + + +def main(client, email_address): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201702') + query = 'WHERE email = :email' + values = [ + {'key': 'email', + 'value': { + 'xsi_type': 'TextValue', + 'value': email_address + }}, + ] + # Create a statement to select users. + statement = dfp.FilterStatement(query, values) + + # Retrieve a small amount of users at a time, paging + # through until all users have been retrieved. + while True: + response = user_service.getUsersByStatement(statement.ToStatement()) + if 'results' in response: + for user in response['results']: + # Print out some information for each user. + print('User with ID "%d" and name "%s" was found.\n' % (user['id'], + user['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, EMAIL_ADDRESS) diff --git a/examples/dfp/v201605/user_service/update_users.py b/examples/dfp/v201702/user_service/update_users.py similarity index 93% rename from examples/dfp/v201605/user_service/update_users.py rename to examples/dfp/v201702/user_service/update_users.py index 8d462f65..f8071fc8 100755 --- a/examples/dfp/v201605/user_service/update_users.py +++ b/examples/dfp/v201702/user_service/update_users.py @@ -16,7 +16,8 @@ """This code example updates a user by adding " Sr." to the end of their name. -To determine which users exist, run get_all_users.py.""" +To determine which users exist, run get_all_users.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') + user_service = client.GetService('UserService', version='v201702') # Create query. values = [{ diff --git a/examples/dfp/v201605/user_team_association_service/__init__.py b/examples/dfp/v201702/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201605/user_team_association_service/__init__.py rename to examples/dfp/v201702/user_team_association_service/__init__.py diff --git a/examples/dfp/v201605/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201605/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201702/user_team_association_service/create_user_team_associations.py index 50c29f6b..1cbb2580 100755 --- a/examples/dfp/v201605/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201605') + 'UserTeamAssociationService', version='v201702') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201605/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py similarity index 98% rename from examples/dfp/v201605/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py index 0afcf796..c903bcab 100755 --- a/examples/dfp/v201605/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201605') + 'UserTeamAssociationService', version='v201702') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201605/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py similarity index 63% rename from examples/dfp/v201605/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py index 66bd27f3..8aa96e57 100755 --- a/examples/dfp/v201605/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 user team associations. - -To create user team associations, run create_user_team_assocations.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - """ - # Import appropriate modules from the client library. from googleads import dfp @@ -33,21 +23,22 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201605') + 'UserTeamAssociationService', version='v201702') - # Create a filter statement. + # Create a statement to select user team associations. statement = dfp.FilterStatement() - # Get user team associations by statement. + # Retrieve a small amount of user team associations at a time, paging + # through until all user team associations have been retrieved. while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for user_team_association in response['results']: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was found.' % (user_team_association['userId'], - user_team_association['teamId'])) + # Print out some information for each user team association. + print('User team association with team id "%d" and user id "%d" was ' + 'found.\n' % (user_team_association['teamId'], + user_team_association['userId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py similarity index 59% rename from examples/dfp/v201605/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py index e63e5a32..1e250536 100755 --- a/examples/dfp/v201605/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,19 +13,9 @@ # 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 user team associations for a single user. - -To determine which users exist, run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - +"""This example gets all user team associations (i.e. teams) for a given user. """ - # Import appropriate modules from the client library. from googleads import dfp @@ -35,37 +25,36 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201605') - - # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] + 'UserTeamAssociationService', version='v201702') query = 'WHERE userId = :userId' - - # Create a filter statement. + values = [ + {'key': 'userId', + 'value': { + 'xsi_type': 'TextValue', + 'value': user_id + }}, + ] + # Create a statement to select user team associations. statement = dfp.FilterStatement(query, values) - # Get user team associations by statement. + # Retrieve a small amount of user team associations at a time, paging + # through until all user team associations have been retrieved. while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for user_team_association in response['results']: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was found.' % (user_team_association['userId'], - user_team_association['teamId'])) + # Print out some information for each user team association. + print('User team association with user ID "%d" and team ID "%d" was ' + 'found.\n' % (user_team_association['userId'], + user_team_association['teamId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201605/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py similarity index 98% rename from examples/dfp/v201605/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201702/user_team_association_service/update_user_team_associations.py index 9f2fa3f0..c7f3c1e1 100755 --- a/examples/dfp/v201605/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201605') + 'UserTeamAssociationService', version='v201702') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201605/workflow_request_service/__init__.py b/examples/dfp/v201702/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201605/workflow_request_service/__init__.py rename to examples/dfp/v201702/workflow_request_service/__init__.py diff --git a/examples/dfp/v201605/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py similarity index 97% rename from examples/dfp/v201605/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py index e208569c..5beaab90 100755 --- a/examples/dfp/v201605/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201605') + version='v201702') # Create query. values = [ diff --git a/examples/dfp/v201605/workflow_request_service/get_workflow_approval_requests_by_statement.py b/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py similarity index 62% rename from examples/dfp/v201605/workflow_request_service/get_workflow_approval_requests_by_statement.py rename to examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py index 3a1c617b..13f36103 100755 --- a/examples/dfp/v201605/workflow_request_service/get_workflow_approval_requests_by_statement.py +++ b/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,43 @@ # 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 workflow approval requests. Workflow approval requests must be approved or rejected for a workflow to finish. - """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201605') - - # Create statement object to select all workflow approval requests. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - }] + workflow_request_service = client.GetService( + 'WorkflowRequestService', version='v201702') query = 'WHERE type = :type' - + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_APPROVAL_REQUEST' + }}, + ] + # Create a statement to select workflow requests. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of workflow requests at a time, paging + # through until all workflow requests have been retrieved. while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for workflow_request in response['results']: - print ('Workflow approval request with id \'%s\' for %s with id \'%s\' ' - 'was found.' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + # Print out some information for each workflow request. + print('Workflow request with ID "%d", entity type "%s", and entity ID ' + '"%d" was found.\n' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/workflow_request_service/get_workflow_external_condition_requests_by_statement.py b/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py similarity index 61% rename from examples/dfp/v201605/workflow_request_service/get_workflow_external_condition_requests_by_statement.py rename to examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py index 6c71774d..8e721180 100755 --- a/examples/dfp/v201605/workflow_request_service/get_workflow_external_condition_requests_by_statement.py +++ b/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -13,47 +13,43 @@ # 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 workflow external condition requests. -Workflow external condition requests must be triggered or skipped for a workflow -to finish. - +Workflow external condition requests must be triggered or skipped for a +workflow to finish. """ - # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201605') - - # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - }] + workflow_request_service = client.GetService( + 'WorkflowRequestService', version='v201702') query = 'WHERE type = :type' - + values = [ + {'key': 'type', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' + }}, + ] + # Create a statement to select workflow requests. statement = dfp.FilterStatement(query, values) - # Get proposals by statement. + # Retrieve a small amount of workflow requests at a time, paging + # through until all workflow requests have been retrieved. while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) if 'results' in response: - # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id \'%s\' for %s ' - 'with id \'%s\' was found.' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + # Print out some information for each workflow request. + print('Workflow request with ID "%d", entity type "%s", and entity ID ' + '"%d" was found.\n' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201605/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 98% rename from examples/dfp/v201605/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py index 3564703d..e3434aac 100755 --- a/examples/dfp/v201605/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201605') + version='v201702') # Create query. values = [ diff --git a/googleads/common.py b/googleads/common.py index af0bbf62..6c1d122f 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -60,7 +60,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '5.0.0' +VERSION = '5.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' @@ -702,6 +702,9 @@ def MakeSoapRequest(*args): _logger.error('Server raised fault in response.') _logger.info('Failure response:\n%s', e.document) + if not hasattr(e.fault, 'detail'): + raise + # Before re-throwing the WebFault exception, an error object needs to be # wrapped in a list for safe iteration. fault = e.fault.detail.ApiExceptionFault diff --git a/googleads/dfp.py b/googleads/dfp.py index 9a08d8ad..e8d94280 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -39,7 +39,7 @@ _CHUNK_SIZE = 16 * 1024 # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201602': + 'v201605': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -60,7 +60,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201605': + 'v201608': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -81,7 +81,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201608': + 'v201611': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -91,18 +91,18 @@ 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NetworkService', 'OrderService', + 'PackageService', 'PlacementService', 'PremiumRateService', + 'ProductService', 'ProductPackageService', 'ProductPackageItemService', + 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201611': + 'v201702': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -113,10 +113,11 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NetworkService', 'OrderService', - 'PackageService', 'PlacementService', 'PremiumRateService', - 'ProductService', 'ProductPackageService', 'ProductPackageItemService', - 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', diff --git a/googleads/util.py b/googleads/util.py index b6e97d2f..390f6c62 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -95,18 +95,18 @@ def PatchedHttpTransportSend(self, request): self.proxy = self.options.proxy request.headers.update(u2request.headers) suds.transport.http.log.debug('sending:\n%s', request) - fp = self.u2open(u2request) - self.getcookies(fp, u2request) - headers = (fp.headers.dict if sys.version_info < (3, 0) else fp.headers) - try: - result = suds.transport.Reply(200, headers, fp.read()) + fp = self.u2open(u2request) except urllib2.HTTPError, e: if e.code in (202, 204): - result = None + return None else: raise suds.transport.TransportError(e.msg, e.code, e.fp) + self.getcookies(fp, u2request) + headers = (fp.headers.dict if sys.version_info < (3, 0) else fp.headers) + result = suds.transport.Reply(200, headers, fp.read()) + if result.headers.get('content-encoding') == 'gzip': # If gzip encoding is used, decompress here. stream = io.BytesIO() diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 6ab042b5..bf586c58 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -262,7 +262,7 @@ def setUp(self): self.proxy_config = GetProxyConfig(https_host=self.https_proxy_host, https_port=self.https_proxy_port) self.file_cache = suds.cache.FileCache - self.no_cache = suds.cache.NoCache + self.no_cache = suds.cache.NoCache() self.adwords_client = GetAdWordsClient() self.aw_client = GetAdWordsClient( proxy_config=self.proxy_config) diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 9cd49d68..27bf4e3f 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -261,7 +261,8 @@ def testGetService_successWithFileCache(self): def testGetService_successWithNoCache(self): service = googleads.dfp._SERVICE_MAP[self.version][0] - dfp_client = self.CreateDfpClient(cache=suds.cache.NoCache) + no_cache = suds.cache.NoCache() + dfp_client = self.CreateDfpClient(cache=no_cache) # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -275,7 +276,7 @@ def testGetService_successWithNoCache(self): mock_client.assert_called_once_with( 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' % (self.version, service), timeout=3600, - cache=suds.cache.NoCache, transport=mock_transport.return_value) + cache=no_cache, transport=mock_transport.return_value) self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_successWithoutProxy(self): diff --git a/tests/util_test.py b/tests/util_test.py index e08fafa8..a6ba7587 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -18,6 +18,7 @@ import os import re import unittest +import urllib2 from xml.etree import ElementTree @@ -25,6 +26,7 @@ import googleads.dfp import googleads.util import mock +import suds import suds.transport @@ -160,6 +162,29 @@ def testSudsJurkoSendWithCompression(self): # message without the patch, resulting in an exception being raised. cs.get() + def testSudsJurkoSendWithException(self): + """Verifies that the patched HttpTransport.send can escalate HTTPError.""" + test_dir = os.path.dirname(__file__) + cs = self.adwords_client_with_compression.GetService('CampaignService') + + with mock.patch('suds.transport.http.HttpTransport.u2open') as mock_u2open: + with open(os.path.join( + test_dir, 'test_data/compact_fault_response_envelope.txt'), 'rb' + ) as handler: + url = 'https://ads.google.com' + code = 500 + msg = '' + hdrs = [] + mock_u2open.side_effect = urllib2.HTTPError(url, code, msg, hdrs, + handler) + try: + cs.get() + except suds.WebFault, e: + self.assertEqual( + 'Unmarshalling Error: For input string: ' + '"INSERT_ADVERTISER_COMPANY_ID_HERE" ', + e.fault.faultstring) + def testSingleErrorListIssue90(self): """Verifies that issue 90 has been resolved with the patch.""" query = 'WHERE 1 = 0' From ec643411042770357185ce7957469aa08e2f95c0 Mon Sep 17 00:00:00 2001 From: thangduo Date: Tue, 14 Feb 2017 14:55:36 -0500 Subject: [PATCH 059/180] Commiting latest changes. From 70ab3136395052425ef83eb381f79335373eec3c Mon Sep 17 00:00:00 2001 From: Thang Duong Date: Tue, 14 Feb 2017 15:36:25 -0500 Subject: [PATCH 060/180] Commiting latest changes. From 1d1c89dc419904fba6f5b903512f4279bb940b99 Mon Sep 17 00:00:00 2001 From: Thang Duong Date: Tue, 14 Feb 2017 15:50:13 -0500 Subject: [PATCH 061/180] Commiting latest changes. From 793805fb37978c25ffc81b92199fad78268bed89 Mon Sep 17 00:00:00 2001 From: Thang Duong Date: Tue, 14 Feb 2017 16:00:56 -0500 Subject: [PATCH 062/180] Commiting latest changes. From 25bbbb9dd3f8469569751c40dda3bda9dc9a2cd0 Mon Sep 17 00:00:00 2001 From: Thang Duong Date: Tue, 14 Feb 2017 16:22:16 -0500 Subject: [PATCH 063/180] Commiting latest changes. From 39d40b9d8578b6dfa281ef7a37ba3354e0363eed Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 1 Mar 2017 18:25:41 -0500 Subject: [PATCH 064/180] AdWords v201702 Release --- ChangeLog | 7 + README.md | 9 +- .../adwords/adwords_appengine_demo/README.md | 5 - .../advanced_operations/add_ad_customizer.py | 7 +- .../reporting/download_criteria_report.py | 2 +- .../download_criteria_report_as_stream.py | 2 +- ...oad_criteria_report_as_stream_with_awql.py | 2 +- .../download_criteria_report_as_string.py | 2 +- ...oad_criteria_report_as_string_with_awql.py | 2 +- .../download_criteria_report_with_awql.py | 3 +- .../advanced_operations/add_ad_customizer.py | 7 +- .../reporting/download_criteria_report.py | 2 +- .../download_criteria_report_as_stream.py | 2 +- ...oad_criteria_report_as_stream_with_awql.py | 2 +- .../download_criteria_report_as_string.py | 2 +- ...oad_criteria_report_as_string_with_awql.py | 2 +- .../download_criteria_report_with_awql.py | 3 +- .../advanced_operations/add_ad_customizer.py | 7 +- .../reporting/download_criteria_report.py | 2 +- .../download_criteria_report_as_stream.py | 2 +- ...oad_criteria_report_as_stream_with_awql.py | 2 +- .../download_criteria_report_as_string.py | 2 +- ...oad_criteria_report_as_string_with_awql.py | 2 +- .../download_criteria_report_with_awql.py | 3 +- examples/adwords/v201702/__init__.py | 15 + .../v201702/account_management/__init__.py | 15 + .../account_management/accept_service_link.py | 62 +++ .../account_management/create_account.py | 63 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201702/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 222 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 126 +++++ ...add_expanded_text_ad_with_upgraded_urls.py | 109 ++++ .../advanced_operations/add_html5_ad.py | 111 ++++ .../add_responsive_display_ad.py | 91 +++ .../add_universal_app_campaign.py | 218 ++++++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201702/basic_operations/__init__.py | 15 + .../v201702/basic_operations/add_ad_groups.py | 115 ++++ .../v201702/basic_operations/add_campaigns.py | 128 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201702/basic_operations/add_keywords.py | 92 +++ .../v201702/basic_operations/get_ad_groups.py | 76 +++ .../v201702/basic_operations/get_campaigns.py | 74 +++ .../get_campaigns_with_awql.py | 64 +++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201702/basic_operations/get_keywords.py | 87 +++ .../v201702/basic_operations/get_text_ads.py | 78 +++ .../v201702/basic_operations/pause_ad.py | 61 ++ .../v201702/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 58 ++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201702/campaign_management/__init__.py | 15 + .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 428 ++++++++++++++ .../v201702/campaign_management/add_draft.py | 81 +++ ...dd_keywords_using_incremental_batch_job.py | 259 +++++++++ .../v201702/campaign_management/add_trial.py | 116 ++++ .../get_all_disapproved_ads.py | 74 +++ .../get_all_disapproved_ads_with_awql.py | 63 +++ .../get_campaigns_by_label.py | 85 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201702/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 131 +++++ .../handle_policy_violation_error.py | 167 ++++++ .../adwords/v201702/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../adwords/v201702/extensions/add_prices.py | 157 ++++++ .../v201702/extensions/add_site_links.py | 146 +++++ .../extensions/add_site_links_using_feeds.py | 236 ++++++++ .../adwords/v201702/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 527 ++++++++++++++++++ examples/adwords/v201702/misc/__init__.py | 15 + .../v201702/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201702/misc/upload_image.py | 66 +++ .../v201702/misc/upload_media_bundle.py | 59 ++ .../adwords/v201702/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 180 ++++++ ...aign_criterion_bid_modifier_simulations.py | 96 ++++ .../get_keyword_bid_simulations.py | 81 +++ .../v201702/optimization/get_keyword_ideas.py | 100 ++++ .../adwords/v201702/remarketing/__init__.py | 15 + .../v201702/remarketing/add_audience.py | 103 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_crm_based_user_list.py | 94 ++++ .../remarketing/add_rule_based_user_lists.py | 186 +++++++ .../upload_offline_call_conversions.py | 77 +++ .../remarketing/upload_offline_conversions.py | 75 +++ .../adwords/v201702/reporting/__init__.py | 15 + ...oad_criteria_report_as_stream_with_awql.py | 81 +++ ...criteria_report_as_stream_with_selector.py | 77 +++ ...oad_criteria_report_as_string_with_awql.py | 55 ++ ...criteria_report_as_string_with_selector.py | 59 ++ .../download_criteria_report_with_awql.py | 59 ++ .../download_criteria_report_with_selector.py | 61 ++ .../v201702/reporting/get_report_fields.py | 52 ++ .../reporting/parallel_report_download.py | 230 ++++++++ examples/adwords/v201702/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 281 ++++++++++ .../v201702/shopping/add_product_scope.py | 104 ++++ .../v201702/shopping/add_shopping_campaign.py | 125 +++++ .../add_shopping_campaign_for_showcase_ads.py | 402 +++++++++++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201702/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 126 +++++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201702/targeting/lookup_location.py | 82 +++ googleads.yaml | 2 + googleads/adwords.py | 46 ++ googleads/common.py | 36 +- googleads/oauth2.py | 74 ++- googleads/util.py | 3 +- setup.py | 4 +- tests/common_test.py | 14 +- tests/oauth2_test.py | 176 +++++- 129 files changed, 10193 insertions(+), 78 deletions(-) create mode 100644 examples/adwords/v201702/__init__.py create mode 100644 examples/adwords/v201702/account_management/__init__.py create mode 100755 examples/adwords/v201702/account_management/accept_service_link.py create mode 100755 examples/adwords/v201702/account_management/create_account.py create mode 100755 examples/adwords/v201702/account_management/get_account_changes.py create mode 100755 examples/adwords/v201702/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201702/advanced_operations/__init__.py create mode 100755 examples/adwords/v201702/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201702/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py create mode 100755 examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201702/basic_operations/__init__.py create mode 100755 examples/adwords/v201702/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201702/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201702/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201702/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201702/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201702/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201702/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201702/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201702/basic_operations/get_text_ads.py create mode 100755 examples/adwords/v201702/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201702/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201702/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201702/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201702/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201702/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201702/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201702/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201702/campaign_management/__init__.py create mode 100755 examples/adwords/v201702/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201702/campaign_management/add_draft.py create mode 100755 examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201702/campaign_management/add_trial.py create mode 100755 examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201702/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201702/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201702/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201702/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201702/error_handling/__init__.py create mode 100755 examples/adwords/v201702/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201702/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201702/extensions/__init__.py create mode 100755 examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201702/extensions/add_prices.py create mode 100755 examples/adwords/v201702/extensions/add_site_links.py create mode 100755 examples/adwords/v201702/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201702/migration/__init__.py create mode 100755 examples/adwords/v201702/migration/migrate_to_extension_settings.py create mode 100644 examples/adwords/v201702/misc/__init__.py create mode 100755 examples/adwords/v201702/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201702/misc/upload_image.py create mode 100755 examples/adwords/v201702/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201702/optimization/__init__.py create mode 100755 examples/adwords/v201702/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201702/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201702/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201702/remarketing/__init__.py create mode 100755 examples/adwords/v201702/remarketing/add_audience.py create mode 100755 examples/adwords/v201702/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201702/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201702/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201702/remarketing/upload_offline_call_conversions.py create mode 100755 examples/adwords/v201702/remarketing/upload_offline_conversions.py create mode 100644 examples/adwords/v201702/reporting/__init__.py create mode 100755 examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py create mode 100755 examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py create mode 100755 examples/adwords/v201702/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201702/reporting/download_criteria_report_with_selector.py create mode 100755 examples/adwords/v201702/reporting/get_report_fields.py create mode 100755 examples/adwords/v201702/reporting/parallel_report_download.py create mode 100644 examples/adwords/v201702/shopping/__init__.py create mode 100755 examples/adwords/v201702/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201702/shopping/add_product_scope.py create mode 100755 examples/adwords/v201702/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py create mode 100755 examples/adwords/v201702/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201702/targeting/__init__.py create mode 100755 examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201702/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 2f10094a..61ceba30 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,10 @@ +5.2.0 -- 3/1/17: +* Added support for AdWords v201702. +* Resolved issues: +- Issue 110: https://github.com/googleads/googleads-python-lib/issues/110 +- Issue 180: https://github.com/googleads/googleads-python-lib/issues/180 + + 5.1.0 -- 2/13/17: * Added support for DFP v201702. * Removed examples for DFP v201605. diff --git a/README.md b/README.md index 377a65cb..4b35052b 100644 --- a/README.md +++ b/README.md @@ -199,9 +199,16 @@ import socket socket.setdefaulttimeout(15 * 60) ``` -##External Dependencies: +##Requirements +###Python Versions +This library supports both Python 2 and 3. To use this library, you will need to +have Python 2.7.9 (or higher) or Python 3.4 (or higher) installed. + +###External Dependencies: + + - httplib2 -- https://pypi.python.org/pypi/httplib2/ - oauth2client -- https://pypi.python.org/pypi/oauth2client/ - suds-jurko -- https://pypi.python.org/pypi/suds-jurko/ - pysocks -- https://pypi.python.org/pypi/PySocks/ diff --git a/examples/adwords/adwords_appengine_demo/README.md b/examples/adwords/adwords_appengine_demo/README.md index 189de5ed..53307a82 100644 --- a/examples/adwords/adwords_appengine_demo/README.md +++ b/examples/adwords/adwords_appengine_demo/README.md @@ -107,8 +107,3 @@ Submit bug reports or feature requests to our * [App Engine SDK v1.9.11+](https://developers.google.com/appengine/downloads) * [Google Ads Python Client Library v2.1.0+](https://github.com/googleads/googleads-python-lib) * [Google Account](https://www.google.com/accounts/NewAccount) - - -### Author: - -api.msaniscalchi@gmail.com (Mark Saniscalchi) \ No newline at end of file diff --git a/examples/adwords/v201605/advanced_operations/add_ad_customizer.py b/examples/adwords/v201605/advanced_operations/add_ad_customizer.py index 4f5a84f9..19ad142d 100755 --- a/examples/adwords/v201605/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201605/advanced_operations/add_ad_customizer.py @@ -49,7 +49,7 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): GoogleAdsError: if no TextAds were added. """ # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService') + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201605') text_ad = { 'xsi_type': 'TextAd', @@ -91,7 +91,8 @@ def CreateCustomizerFeed(client, feed_name): The new AdCustomizerFeed. """ # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201605') customizer_feed = { 'feedName': feed_name, @@ -141,7 +142,7 @@ def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): GoogleAdsError: if no FeedItems were added. """ # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService') + feed_item_service = client.GetService('FeedItemService', 'v201605') now = datetime.now() mars_date = datetime(now.year, now.month, 1, 0, 0) venus_date = datetime(now.year, now.month, 15, 0, 0) diff --git a/examples/adwords/v201605/reporting/download_criteria_report.py b/examples/adwords/v201605/reporting/download_criteria_report.py index 9a3b12f8..68122cf4 100755 --- a/examples/adwords/v201605/reporting/download_criteria_report.py +++ b/examples/adwords/v201605/reporting/download_criteria_report.py @@ -53,7 +53,7 @@ def main(client): # we use sys.stdout to write the report to the screen. report_downloader.DownloadReport( report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py index b4e018d7..e86dddee 100755 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py @@ -58,7 +58,7 @@ def main(client): report_data = StringIO.StringIO() stream_data = report_downloader.DownloadReportAsStream( report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) try: while True: diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py index 5f82c8c9..9638d92e 100755 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py @@ -55,7 +55,7 @@ def main(client): print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) # Retrieve the report stream and print it out report_data = StringIO.StringIO() diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_string.py b/examples/adwords/v201605/reporting/download_criteria_report_as_string.py index 165a15ab..c061dd60 100755 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_string.py @@ -51,7 +51,7 @@ def main(client): # Print out the report as a string print report_downloader.DownloadReportAsString( report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py index c9d24ab8..700083b2 100755 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py @@ -45,7 +45,7 @@ def main(client): print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py index 866810f5..2bc34b5d 100755 --- a/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py @@ -46,7 +46,8 @@ def main(client, path): with open(path, 'w') as output_file: report_downloader.DownloadReportWithAwql( report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False) + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) print 'Report was downloaded to \'%s\'.' % path diff --git a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py index 4f5a84f9..f23b8f36 100755 --- a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py @@ -49,7 +49,7 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): GoogleAdsError: if no TextAds were added. """ # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService') + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201607') text_ad = { 'xsi_type': 'TextAd', @@ -91,7 +91,8 @@ def CreateCustomizerFeed(client, feed_name): The new AdCustomizerFeed. """ # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201607') customizer_feed = { 'feedName': feed_name, @@ -141,7 +142,7 @@ def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): GoogleAdsError: if no FeedItems were added. """ # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService') + feed_item_service = client.GetService('FeedItemService', 'v201607') now = datetime.now() mars_date = datetime(now.year, now.month, 1, 0, 0) venus_date = datetime(now.year, now.month, 15, 0, 0) diff --git a/examples/adwords/v201607/reporting/download_criteria_report.py b/examples/adwords/v201607/reporting/download_criteria_report.py index 0e96e562..dbade940 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report.py +++ b/examples/adwords/v201607/reporting/download_criteria_report.py @@ -53,7 +53,7 @@ def main(client): # we use sys.stdout to write the report to the screen. report_downloader.DownloadReport( report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py index 5a7040f6..63563e2d 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py @@ -58,7 +58,7 @@ def main(client): report_data = StringIO.StringIO() stream_data = report_downloader.DownloadReportAsStream( report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) try: while True: diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py index 1de6ad8d..ab02ab68 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py @@ -55,7 +55,7 @@ def main(client): print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) # Retrieve the report stream and print it out report_data = StringIO.StringIO() diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py index 1933b7be..1e3aa0a1 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py @@ -51,7 +51,7 @@ def main(client): # Print out the report as a string print report_downloader.DownloadReportAsString( report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py index 13c16109..c1a1ebb9 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py @@ -45,7 +45,7 @@ def main(client): print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py index f7d20d60..2dafb47e 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py @@ -46,7 +46,8 @@ def main(client, path): with open(path, 'w') as output_file: report_downloader.DownloadReportWithAwql( report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False) + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) print 'Report was downloaded to \'%s\'.' % path diff --git a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py index f3c8da4f..f4a95d53 100755 --- a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py @@ -49,7 +49,7 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): GoogleAdsError: if no ExpandedTextAds were added. """ # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService') + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201609') expanded_text_ad = { 'xsi_type': 'ExpandedTextAd', @@ -90,7 +90,8 @@ def CreateCustomizerFeed(client, feed_name): The new AdCustomizerFeed. """ # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService') + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201609') customizer_feed = { 'feedName': feed_name, @@ -140,7 +141,7 @@ def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): GoogleAdsError: if no FeedItems were added. """ # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService') + feed_item_service = client.GetService('FeedItemService', 'v201609') now = datetime.now() mars_date = datetime(now.year, now.month, 1, 0, 0) venus_date = datetime(now.year, now.month, 15, 0, 0) diff --git a/examples/adwords/v201609/reporting/download_criteria_report.py b/examples/adwords/v201609/reporting/download_criteria_report.py index fc905bd8..d23c7135 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report.py +++ b/examples/adwords/v201609/reporting/download_criteria_report.py @@ -53,7 +53,7 @@ def main(client): # we use sys.stdout to write the report to the screen. report_downloader.DownloadReport( report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py index 0480f69c..33e25e2e 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py @@ -58,7 +58,7 @@ def main(client): report_data = StringIO.StringIO() stream_data = report_downloader.DownloadReportAsStream( report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) try: while True: diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py index 135e6f31..c487a6ee 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py @@ -55,7 +55,7 @@ def main(client): print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) # Retrieve the report stream and print it out report_data = StringIO.StringIO() diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py index ceb11acb..4da148c8 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py @@ -51,7 +51,7 @@ def main(client): # Print out the report as a string print report_downloader.DownloadReportAsString( report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py index a589a321..32766925 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py @@ -45,7 +45,7 @@ def main(client): print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False) + skip_report_summary=False, include_zero_impressions=True) if __name__ == '__main__': diff --git a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py index b627e3ed..4004551e 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py @@ -46,7 +46,8 @@ def main(client, path): with open(path, 'w') as output_file: report_downloader.DownloadReportWithAwql( report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False) + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) print 'Report was downloaded to \'%s\'.' % path diff --git a/examples/adwords/v201702/__init__.py b/examples/adwords/v201702/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201702/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201702/account_management/__init__.py b/examples/adwords/v201702/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201702/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201702/account_management/accept_service_link.py b/examples/adwords/v201702/account_management/accept_service_link.py new file mode 100755 index 00000000..928b87a5 --- /dev/null +++ b/examples/adwords/v201702/account_management/accept_service_link.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' + + +def main(client, service_link_id): + # Initialize appropriate service. + customer_service = client.GetService( + 'CustomerService', version='v201702') + + # Create the operation to set the status to ACTIVE. + operations = [{ + 'operator': 'SET', + 'operand': { + 'serviceLinkId': service_link_id, + 'serviceType': 'MERCHANT_CENTER', + 'linkStatus': 'ACTIVE', + } + }] + + # Update the service link. + mutated_service_links = customer_service.mutateServiceLinks(operations) + + # Display results. + for mutated_service_link in mutated_service_links: + print ('Service link with service link ID \'%s\', type \'%s\' was updated ' + 'to status: \'%s\'.' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201702/account_management/create_account.py b/examples/adwords/v201702/account_management/create_account.py new file mode 100755 index 00000000..0ffad749 --- /dev/null +++ b/examples/adwords/v201702/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201702') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/account_management/get_account_changes.py b/examples/adwords/v201702/account_management/get_account_changes.py new file mode 100755 index 00000000..e8217e83 --- /dev/null +++ b/examples/adwords/v201702/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201702') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/account_management/get_account_hierarchy.py b/examples/adwords/v201702/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..ba9e02ec --- /dev/null +++ b/examples/adwords/v201702/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201702') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/advanced_operations/__init__.py b/examples/adwords/v201702/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..fc5b59f7 --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py @@ -0,0 +1,222 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates ExpandedTextAds that use ad customizations for specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no ExpandedTextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201702') + + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'headlinePart2': 'Only {=%s.Price}' % feed_name, + 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': expanded_text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201702') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService', 'v201702') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..e006a8a9 --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201702') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..1bac185a --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,126 @@ +#!/usr/bin/python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Optionally, you may specify a landscape image. The image needs to be in a + # BASE64 encoded form. Here we download a demo image and encode it for this + # ad. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + }, + { + 'name': 'landscapeImage', + 'fieldMedia': { + 'xsi_type': 'Image', + 'data': image_data + }, + 'type': 'IMAGE' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..f33b3d74 --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -0,0 +1,109 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Create the expanded text ad + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': expanded_text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_html5_ad.py b/examples/adwords/v201702/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..63332b92 --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/add_html5_ad.py @@ -0,0 +1,111 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..733fb470 --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + media_service = client.GetService('MediaService', version='v201702') + + try: + # Create image. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + # Make the upload request + image = media_service.upload(image)[0] + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'] + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py new file mode 100755 index 00000000..9d8c8c0c --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py @@ -0,0 +1,218 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a Universal App campaign. + +To get campaigns, run get_campaigns.py. To upload image assets for this +campaign, run upload_image.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201702') + + budget_id = CreateBudget(client) + + # Create the Universal App campaign. + universal_app_campaign = { + 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'MULTI_CHANNEL', + 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', + # Set the campaign's bidding strategy. Universal app campaigns only + # support TARGET_CPA bidding strategy. + 'biddingStrategyConfiguration': { + # Set the target CPA to $1 / app install. + 'biddingScheme': { + 'xsi_type': 'TargetCpaBiddingScheme', + 'targetCpa': { + 'microAmount': '1000000' + } + }, + 'biddingStrategyType': 'TARGET_CPA' + }, + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + + universal_app_campaign['settings'] = [ + # Set the campaign's assets and ad text ideas. These values will + # be used to generate ads. + { + 'xsi_type': 'UniversalAppCampaignSetting', + 'appId': 'com.labpixies.colordrips', + 'description1': 'A cool puzzle game', + 'description2': 'Remove connected blocks', + 'description3': '3 difficulty levels', + 'description4': '4 colorful fun skins', + # Optional: You can set up to 10 image assets for your campaign. + # See upload_image.py for an example on how to upload images. + # + # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] + } + ] + + # Optimize this campaign for getting new users for your app. + universal_app_campaign_setting = universal_app_campaign['settings'][0] + universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( + 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') + + # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, + # then also specify your in-app conversion types so AdWords can focus your + # campaign on people who are most likely to complete the corresponding in-app + # actions. + # + # Conversions type IDs can be retrieved using ConversionTrackerService.get. + # universal_app_campaign['selectiveOptimization'] = { + # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] + # } + + # Optional: Set the campaign settings for Advanced location options. + universal_app_campaign['settings'].append({ + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + }) + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': universal_app_campaign + }] + + campaigns = campaign_service.mutate(operations)['value'] + + # Display results. + if campaigns: + for campaign in campaigns: + print ('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + # Optional: Set the campaign's location and language targeting. No other + # targeting criteria can be used for Universal App campaigns. + SetCampaignTargetingCriteria(client, campaign) + else: + print 'No Universal App campaigns were added.' + + +def CreateBudget(client): + """Creates a budget and returns its budgetId. + + Args: + client: An AdWordsClient instance. + + Returns: + An int budgetId for the created Budget. + """ + budget_service = client.GetService('BudgetService', version='v201702') + + # Create a budget. + budget = { + 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Create the budget and return its ID. + budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] + # [END createBudget] MOE_strip_line + + return budget_id + + +def SetCampaignTargetingCriteria(client, campaign): + """Sets targeting criteria for the given campaign. + + Args: + client: An AdWordsClient instance. + campaign: A suds object representing the campaign we wish to attach + targeting criteria. + """ + campaign_criterion_service = client.GetService('CampaignCriterionService') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + criteria = [ + { + 'xsi_type': 'Location', + 'id': 21137 # California + }, + { + 'xsi_type': 'Location', + 'id': 2484 # Mexico + }, + { + 'xsi_type': 'Language', + 'id': 1000 # English + }, + { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + ] + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign['id'], + 'criterion': criterion + } + } for criterion in criteria] + + response = campaign_criterion_service.mutate(operations) + + if response and 'value' in response: + # Display the added campaign targets. + for criterion in response['value']: + print ('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], + criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..b86f5b5a --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201702') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201702') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201702') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..c3e6f9f0 --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201702') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201702') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..38bccd6c --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201702') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..2fc4cd19 --- /dev/null +++ b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201702') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201702') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201702') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201702/basic_operations/__init__.py b/examples/adwords/v201702/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201702/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201702/basic_operations/add_ad_groups.py b/examples/adwords/v201702/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..9d27be61 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201702') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/basic_operations/add_campaigns.py b/examples/adwords/v201702/basic_operations/add_campaigns.py new file mode 100755 index 00000000..a1bd816e --- /dev/null +++ b/examples/adwords/v201702/basic_operations/add_campaigns.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201702') + budget_service = client.GetService('BudgetService', version='v201702') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..02b21c13 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/add_keywords.py b/examples/adwords/v201702/basic_operations/add_keywords.py new file mode 100755 index 00000000..3a5406ad --- /dev/null +++ b/examples/adwords/v201702/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201702') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/get_ad_groups.py b/examples/adwords/v201702/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..8a487183 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201702') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/basic_operations/get_campaigns.py b/examples/adwords/v201702/basic_operations/get_campaigns.py new file mode 100755 index 00000000..6e8fdf79 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/get_campaigns.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201702') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..c413d222 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201702') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..b2b7dd51 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an expanded text ad, run add_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/get_keywords.py b/examples/adwords/v201702/basic_operations/get_keywords.py new file mode 100755 index 00000000..c621b2b1 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201702') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\' was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/get_text_ads.py b/examples/adwords/v201702/basic_operations/get_text_ads.py new file mode 100755 index 00000000..26eb8dde --- /dev/null +++ b/examples/adwords/v201702/basic_operations/get_text_ads.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# +# Copyright 2016 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 text ads for a given ad group. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/pause_ad.py b/examples/adwords/v201702/basic_operations/pause_ad.py new file mode 100755 index 00000000..242bf678 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201702/basic_operations/remove_ad.py b/examples/adwords/v201702/basic_operations/remove_ad.py new file mode 100755 index 00000000..7a7ecd97 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201702/basic_operations/remove_ad_group.py b/examples/adwords/v201702/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..92e4d261 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201702') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/remove_campaign.py b/examples/adwords/v201702/basic_operations/remove_campaign.py new file mode 100755 index 00000000..ad8a87e4 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201702') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/basic_operations/remove_keyword.py b/examples/adwords/v201702/basic_operations/remove_keyword.py new file mode 100755 index 00000000..a62fc6ab --- /dev/null +++ b/examples/adwords/v201702/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201702') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201702/basic_operations/update_ad_group.py b/examples/adwords/v201702/basic_operations/update_ad_group.py new file mode 100755 index 00000000..69cd5c8e --- /dev/null +++ b/examples/adwords/v201702/basic_operations/update_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201702') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/update_campaign.py b/examples/adwords/v201702/basic_operations/update_campaign.py new file mode 100755 index 00000000..413476a7 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201702') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/basic_operations/update_keyword.py b/examples/adwords/v201702/basic_operations/update_keyword.py new file mode 100755 index 00000000..02d9ac58 --- /dev/null +++ b/examples/adwords/v201702/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201702') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201702/campaign_management/__init__.py b/examples/adwords/v201702/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201702/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201702/campaign_management/add_campaign_labels.py b/examples/adwords/v201702/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..8974b139 --- /dev/null +++ b/examples/adwords/v201702/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201702') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..41f62638 --- /dev/null +++ b/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,428 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201702') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201702') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding an ExpandedTextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new ExpandedTextAd for + each of the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once + # you've added targeting and the ads are ready to serve. + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201702') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201702/campaign_management/add_draft.py b/examples/adwords/v201702/campaign_management/add_draft.py new file mode 100755 index 00000000..7feb343e --- /dev/null +++ b/examples/adwords/v201702/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + draft_service = client.GetService('DraftService', version='v201702') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201702') + + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..fd7c1408 --- /dev/null +++ b/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,259 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201702') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201702') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201702') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201702') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/campaign_management/add_trial.py b/examples/adwords/v201702/campaign_management/add_trial.py new file mode 100755 index 00000000..e293b5fc --- /dev/null +++ b/examples/adwords/v201702/campaign_management/add_trial.py @@ -0,0 +1,116 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201702') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201702') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..60022bbb --- /dev/null +++ b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Construct selector and get all ads for a given ad group. + selector = { + 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'AdGroupCreativeApprovalStatus', + 'operator': 'IN', + 'values': ['DISAPPROVED'] + } + ] + } + ads = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..1a387975 --- /dev/null +++ b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,63 @@ +#!/usr/bin/python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, AdGroupAdDisapprovalReasons ' + 'WHERE CampaignId = %s AND ' + 'AdGroupCreativeApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % campaign_id) + ads = ad_group_ad_service.query(query) + + # Display results. + if 'entries' in ads: + for ad in ads['entries']: + print ('Ad with id \'%s\' was disapproved for the following reasons: ' + % (ad['ad']['id'])) + if ad['ad'].get('disapprovalReasons'): + for reason in ad['ad']['disapprovalReasons']: + print '\t%s' % reason + else: + print '\tReason not provided.' + else: + print 'No disapproved ads were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..17e22497 --- /dev/null +++ b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201702') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201702/campaign_management/graduate_trial.py b/examples/adwords/v201702/campaign_management/graduate_trial.py new file mode 100755 index 00000000..9d535ccd --- /dev/null +++ b/examples/adwords/v201702/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201702') + budget_service = client.GetService('BudgetService', version='v201702') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201702/campaign_management/set_ad_parameters.py b/examples/adwords/v201702/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..47cbed55 --- /dev/null +++ b/examples/adwords/v201702/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_param_service = client.GetService('AdParamService', version='v201702') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..24011f89 --- /dev/null +++ b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201702') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201702/campaign_management/validate_text_ad.py b/examples/adwords/v201702/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..0908da3d --- /dev/null +++ b/examples/adwords/v201702/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +No objects will be created, but exceptions will still be returned. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Construct operations to add an expanded text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'] + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for all astronauts in orbit', + 'finalUrls': ['http://www.example.com'], + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/error_handling/__init__.py b/examples/adwords/v201702/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201702/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201702/error_handling/handle_partial_failures.py b/examples/adwords/v201702/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..e4495c35 --- /dev/null +++ b/examples/adwords/v201702/error_handling/handle_partial_failures.py @@ -0,0 +1,131 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201702') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + if (first_field_path_element and + first_field_path_element['field'] == 'operations' and + first_field_path_element['index']): + operation_index = first_field_path_element['index'] + + adgroup_criterion = operations[operation_index]['operand'] + + print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' + 'a failure for the following reason: %s.' + % (adgroup_criterion['adGroupId'], + adgroup_criterion['criterion']['text'], + error['errorString'])) + else: + print ('A failure has occured for the following reasons: %s\n' + % error['errorString']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..b4034b22 --- /dev/null +++ b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py @@ -0,0 +1,167 @@ +#!/usr/bin/python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201702') + + # Create expanded text ad that violates an exemptable policy. + exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise!!!', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + # Create text ad that violates a non-exemptable policy. + non_exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise with too long of a headline.', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + operations = [exemptable_expanded_text_ad_operation, + non_exemptable_expanded_text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + # Get the index of the failed operation from the error's field path + # elements. + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + # If the operation index is not present on the first error field path + # element, then there's no way to determine which operation to remove, + # so simply throw the exception. + if (not (first_field_path_element + and first_field_path_element['field'] == 'operations' + and first_field_path_element['index'])): + raise e + + operation_index = first_field_path_element['index'] + index = int(operation_index[0]) + operation = operations[index] + if not HandleAPIError(error, operation): + # Set non-exemptable operation to None to mark for deletion. + print ('Removing operation with non-exemptable error at index %s.' + % operation_index) + operations[index] = None + + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +def HandleAPIError(error, operation): + """Makes an exemption for exemptable PolicyViolationErrors. + + Args: + error: the error associated with the given operation. + operation: the operation associated with the given error. + + Returns: + A boolean that is True if the given error was an exemptable + PolicyViolationError; otherwise, returns False. + """ + is_exemptable = False + + # Determine if the operation can be resubmitted with an exemption request. + if error['ApiError.Type'] == 'PolicyViolationError': + expanded_text_ad = operation['operand']['ad'] + is_exemptable = (error['isExemptable'] if 'isExemptable' in error else + False) + print ('Ad with headline "%s - %s" violated %s policy "%s".' % + (expanded_text_ad['headlinePart1'], + expanded_text_ad['headlinePart2'], + 'exemptable' if is_exemptable else 'non-exemptable', + error['externalPolicyName'])) + + if is_exemptable: + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text \'%s\'.' + % (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({'key': error['key']}) + + return is_exemptable + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/extensions/__init__.py b/examples/adwords/v201702/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201702/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..23e778c8 --- /dev/null +++ b/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201702').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201702') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201702/extensions/add_prices.py b/examples/adwords/v201702/extensions/add_prices.py new file mode 100755 index 00000000..9cb8ec85 --- /dev/null +++ b/examples/adwords/v201702/extensions/add_prices.py @@ -0,0 +1,157 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201702') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', + final_mobile_url='http://m.example.com/scrubs'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url='http://m.example.com/haircuts'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url=( + 'http://m.example.com/skincarepackage')) + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit, final_mobile_url=None): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + final_mobile_url: A str containing the final mobile URL after all cross + domain redirects. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + table_row = { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + if final_mobile_url: + table_row['finalMobileUrls'] = { + 'urls': [final_mobile_url] + } + + return table_row + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/extensions/add_site_links.py b/examples/adwords/v201702/extensions/add_site_links.py new file mode 100755 index 00000000..c12cd889 --- /dev/null +++ b/examples/adwords/v201702/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201702') + customer_service = client.GetService('CustomerService', version='v201702') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..b113e21f --- /dev/null +++ b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py @@ -0,0 +1,236 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_1_TEXT = '3' +PLACEHOLDER_FIELD_LINE_2_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201702') + feed_item_service = client.GetService('FeedItemService', version='v201702') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201702') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201702') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 1 Description'}, + {'type': 'STRING', 'name': 'Line 2 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_1_feed_attribute_id = feed['attributes'][2]['id'] + line_2_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % + (line_1_feed_attribute_id, line_2_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line1FeedId'] = line_1_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line1': 'Home line 1', 'line2': 'Home line 2'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line1': 'Support line 1', 'line2': 'Support line 2'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line1': 'Products line 1', 'line2': 'Products line 2'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'stringValue': item['line1'] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + feed_item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line1FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/migration/__init__.py b/examples/adwords/v201702/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201702/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201702/migration/migrate_to_extension_settings.py b/examples/adwords/v201702/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..3d0233be --- /dev/null +++ b/examples/adwords/v201702/migration/migrate_to_extension_settings.py @@ -0,0 +1,527 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201702') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201702') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201702') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201702') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201702') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201702') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201702') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/misc/__init__.py b/examples/adwords/v201702/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201702/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201702/misc/get_all_images_and_videos.py b/examples/adwords/v201702/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..be327b75 --- /dev/null +++ b/examples/adwords/v201702/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201702') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/misc/upload_image.py b/examples/adwords/v201702/misc/upload_image.py new file mode 100755 index 00000000..2fe59541 --- /dev/null +++ b/examples/adwords/v201702/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201702') + + with open(image_filename, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201702/misc/upload_media_bundle.py b/examples/adwords/v201702/misc/upload_media_bundle.py new file mode 100755 index 00000000..087af222 --- /dev/null +++ b/examples/adwords/v201702/misc/upload_media_bundle.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201702') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/optimization/__init__.py b/examples/adwords/v201702/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201702/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py b/examples/adwords/v201702/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..f06f2096 --- /dev/null +++ b/examples/adwords/v201702/optimization/estimate_keyword_traffic.py @@ -0,0 +1,180 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201702') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..032c15db --- /dev/null +++ b/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201702') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..c1384257 --- /dev/null +++ b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201702') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201702/optimization/get_keyword_ideas.py b/examples/adwords/v201702/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..4c513de3 --- /dev/null +++ b/examples/adwords/v201702/optimization/get_keyword_ideas.py @@ -0,0 +1,100 @@ +#!/usr/bin/python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201702') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }, + { + # Network search parameter (optional) + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/__init__.py b/examples/adwords/v201702/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201702/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201702/remarketing/add_audience.py b/examples/adwords/v201702/remarketing/add_audience.py new file mode 100755 index 00000000..08514a3c --- /dev/null +++ b/examples/adwords/v201702/remarketing/add_audience.py @@ -0,0 +1,103 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201702') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201702') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/add_conversion_tracker.py b/examples/adwords/v201702/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..18693be6 --- /dev/null +++ b/examples/adwords/v201702/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201702') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py b/examples/adwords/v201702/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..ff517131 --- /dev/null +++ b/examples/adwords/v201702/remarketing/add_crm_based_user_list.py @@ -0,0 +1,94 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client, emails): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201702') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180 + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + hashed_emails = HashEmails(emails) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'dataType': 'EMAIL_SHA256', + 'members': hashed_emails + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def HashEmails(emails): + """Hashes the given emails using SHA-256. + + Note: Emails are stripped of any whitespace and set to lowercase before + hashing. + + Args: + emails: list of str emails to be hashed. + + Returns: + A list of SHA-256 hashed emails. + """ + return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + + +if __name__ == '__main__': + EMAILS = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, EMAILS) diff --git a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..6d82ffc6 --- /dev/null +++ b/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,186 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201702') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords will logically OR the + # groups together. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule, + # Optional: Set the populationStatus to REQUESTED to include past users in + # the user list. + 'populationStatus': 'REQUESTED' + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py new file mode 100755 index 00000000..8066200f --- /dev/null +++ b/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Imports offline conversion values for calls related to ads in your account. + +To set up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CALLER_ID = 'INSERT_CALLER_ID_HERE' +# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats +# For time zones, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +CALL_START_TIME = 'INSERT_CALL_START_TIME' +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, caller_id, call_start_time, conversion_name, conversion_time, + conversion_value): + # Initialize appropriate services. + occ_feed_service = client.GetService( + 'OfflineCallConversionFeedService', version='v201702') + + # Associate offline call conversions with the existing named conversion + # tracker. If this tracker was newly created, it may be a few hours before it + # can accept conversions. + feed = { + 'callerId': caller_id, + 'callStartTime': call_start_time, + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + } + + occ_operations = [{'operator': 'ADD', 'operand': feed}] + + occ_response = occ_feed_service.mutate(occ_operations) + values = occ_response['value'] + + if values: + for occ_feed in values: + print ('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + else: + print 'No offline call conversions were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, + CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201702/remarketing/upload_offline_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..787ba0da --- /dev/null +++ b/examples/adwords/v201702/remarketing/upload_offline_conversions.py @@ -0,0 +1,75 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201702') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201702/reporting/__init__.py b/examples/adwords/v201702/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201702/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..6b21463d --- /dev/null +++ b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201702') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py new file mode 100755 index 00000000..fcafe2f1 --- /dev/null +++ b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201702') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..faf057ff --- /dev/null +++ b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201702') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py new file mode 100755 index 00000000..78816c0b --- /dev/null +++ b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201702') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..b1f3e641 --- /dev/null +++ b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client, path): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201702') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + with open(path, 'w') as output_file: + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', output_file, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) + + print 'Report was downloaded to \'%s\'.' % path + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, PATH) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py new file mode 100755 index 00000000..4218fbca --- /dev/null +++ b/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201702') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201702/reporting/get_report_fields.py b/examples/adwords/v201702/reporting/get_report_fields.py new file mode 100755 index 00000000..68a72983 --- /dev/null +++ b/examples/adwords/v201702/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201702') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201702/reporting/parallel_report_download.py b/examples/adwords/v201702/reporting/parallel_report_download.py new file mode 100755 index 00000000..048a927a --- /dev/null +++ b/examples/adwords/v201702/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201702') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201702') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201702/shopping/__init__.py b/examples/adwords/v201702/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201702/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201702/shopping/add_product_partition_tree.py b/examples/adwords/v201702/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..cf28ef53 --- /dev/null +++ b/examples/adwords/v201702/shopping/add_product_partition_tree.py @@ -0,0 +1,281 @@ +#!/usr/bin/python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201702') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/shopping/add_product_scope.py b/examples/adwords/v201702/shopping/add_product_scope.py new file mode 100755 index 00000000..ba63f9bd --- /dev/null +++ b/examples/adwords/v201702/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201702') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign.py b/examples/adwords/v201702/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..87850b6b --- /dev/null +++ b/examples/adwords/v201702/shopping/add_shopping_campaign.py @@ -0,0 +1,125 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id): + campaign_service = client.GetService('CampaignService', version='v201702') + ad_group_service = client.GetService('AdGroupService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + adgroup = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group_result = ad_group_service.mutate(adgroup_operations) + + for adgroup in ad_group_result['value']: + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (adgroup['name'], adgroup['id'])) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': adgroup['id'], + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py new file mode 100755 index 00000000..a5fbbf33 --- /dev/null +++ b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py @@ -0,0 +1,402 @@ +#!/usr/bin/python +# +# Copyright 2017 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 adds a Shopping campaign for Showcase ads. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import uuid + +from googleads import adwords +from suds import WebFault + + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' +EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' +COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, budget_id, merchant_id, expanded_image_filepath, + collapsed_image_filepath): + try: + # Create the Shopping Campaign + campaign = CreateShoppingCampaign(client, budget_id, merchant_id) + + # Create the AdGroup + adgroup = CreateAdGroup(client, campaign['id']) + + # Create a Showcase Ad + CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath) + + product_partition_tree = CreateProductPartition(client, adgroup['id']) + print 'Final tree:\n%s' % product_partition_tree + except WebFault: + print 'Failed to create shopping campaign for showcase ads.' + raise + + +def CreateShoppingCampaign(client, budget_id, merchant_id): + """Creates a shopping campaign with the given budget and merchant IDs. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + shopping campaign. + + Returns: + The created Shopping Campaign as a sudsobject. + """ + campaign_service = client.GetService('CampaignService', 'v201702') + + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + campaign = campaign_service.mutate(campaign_operations)['value'][0] + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + return campaign + + +def CreateAdGroup(client, campaign_id): + """Creates an AdGroup for the given shopping campaign ID. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a shopping campaign. + + Returns: + The created AdGroup as a sudsobject. + """ + ad_group_service = client.GetService('AdGroupService', 'v201702') + + adgroup = { + # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS + 'adGroupType': 'SHOPPING_SHOWCASE_ADS', + 'campaignId': campaign_id, + 'name': 'AdGroup #%s' % uuid.uuid4(), + # REQUIRED: Set the ad group's bidding strategy configuration. + 'biddingStrategyConfiguration': { + # Showcase ads require either ManualCpc or EnhancedCpc. + 'biddingStrategyType': 'MANUAL_CPC', + # Optional: Set the bids + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 100000 + } + }] + } + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) + + return adgroup + + +def CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath): + """Creates a showcase add for the given AdGroup with the given images. + + Args: + client: an AdWordsClient instance. + adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + expanded_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's expandedImage. + collapsed_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's collapsedImage. + + Returns: + The created Showcase Ad as a sudsobject. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201702') + + showcase_ad = { + 'adGroupId': adgroup['id'], + 'ad': { + 'xsi_type': 'ShowcaseAd', + 'Ad.Type': 'ShowcaseAd', + # Required: set the ad's name, final URLs, and display URL. + 'name': 'Showcase ad #%s' % uuid.uuid4(), + 'finalUrls': 'http://example.com/showcase', + 'displayUrl': 'example.com', + # Required: Set the ad's expanded image. + 'expandedImage': { + 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] + }, + # Optional: Set the collapsed image. + 'collapsedImage': { + 'mediaId': + UploadImage(client, collapsed_image_filepath)['mediaId'] + } + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': showcase_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] + + print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + + return showcase_ad + + +def UploadImage(client, filepath): + """Uploads a .jpg image with the given filepath via the AdWords MediaService. + + Args: + client: an AdWordsClient instance. + filepath: a str filepath to the .jpg file to be uploaded. + + Returns: + The created Image as a sudsobject. + """ + media_service = client.GetService('MediaService', 'v201702') + + with open(filepath, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + image = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + + image = media_service.upload(image)[0] + + return image + + +def CreateProductPartition(client, adgroup_id): + """Creates a ProductPartition tree for the given AdGroup ID. + + Args: + client: an AdWordsClient instance. + adgroup_id: a str AdGroup ID. + + Returns: + The ProductPartition tree as a sudsobject. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + 'v201702') + helper = ProductPartitionHelper(adgroup_id) + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition) + helper.CreateUnit(root, used_product_canonical_condition) + helper.CreateUnit(root, other_product_canonical_condition) + + result = ad_group_criterion_service.mutate(helper.operations) + return result['value'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, + COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py b/examples/adwords/v201702/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..efde9e53 --- /dev/null +++ b/examples/adwords/v201702/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201702') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/targeting/__init__.py b/examples/adwords/v201702/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201702/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..7d58f94c --- /dev/null +++ b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,126 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201702') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..109cda2d --- /dev/null +++ b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201702') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..607e32d9 --- /dev/null +++ b/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201702') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..22e94047 --- /dev/null +++ b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201702') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/targeting/lookup_location.py b/examples/adwords/v201702/targeting/lookup_location.py new file mode 100755 index 00000000..065e8eaf --- /dev/null +++ b/examples/adwords/v201702/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201702') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/googleads.yaml b/googleads.yaml index 9e6294c7..dfff1a9d 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -25,6 +25,7 @@ adwords: # The following values configure the client for the service account flow. # service_account_email: INSERT_SERVICE_ACCOUNT_EMAIL_HERE # path_to_private_key_file: INSERT_PATH_TO_FILE_HERE + # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT ############################################################################# # ReportDownloader Headers # # Below you may specify boolean values for optional headers that will be # @@ -62,6 +63,7 @@ dfp: # The following values configure the client for the service account flow. # service_account_email: INSERT_SERVICE_ACCOUNT_EMAIL_HERE # path_to_private_key_file: INSERT_PATH_TO_FILE_HERE + # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT # Common configurations: diff --git a/googleads/adwords.py b/googleads/adwords.py index 44ae847b..9d3b2470 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -172,6 +172,52 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201702': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineCallConversionFeedService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } diff --git a/googleads/common.py b/googleads/common.py index 6c1d122f..a30a28eb 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -60,7 +60,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '5.1.0' +VERSION = '5.2.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' @@ -68,11 +68,21 @@ _PYTHON_VERSION = 'Python/%d.%d.%d' % ( _PY_VERSION_MAJOR, _PY_VERSION_MINOR, _PY_VERSION_MICRO) -# The keys in the authentication dictionary that are used to construct OAuth2 -# credentials. +# The required keys in the authentication dictionary that are used to construct +# installed application OAuth2 credentials. _OAUTH2_INSTALLED_APP_KEYS = ('client_id', 'client_secret', 'refresh_token') -_OAUTH2_SERVICE_ACCT_KEYS = ('service_account_email', - 'path_to_private_key_file') + +# The keys in the authentication dictionary that are used to construct service +# account OAuth2 credentials. This will differ based on the oauth2client +# installation. +if googleads.oauth2.DEPRECATED_OAUTH2CLIENT: + _OAUTH2_SERVICE_ACCT_KEYS = ('service_account_email', + 'path_to_private_key_file') + _OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL = ('delegated_account',) +else: + _OAUTH2_SERVICE_ACCT_KEYS = ('path_to_private_key_file',) + _OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL = ('delegated_account', + 'service_account_email') # The keys in the http_proxy and https_proxy dictionaries that are used to # construct a Proxy, HTTPSProxy, and ProxyConfig instances. @@ -261,6 +271,10 @@ def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config): A GoogleAdsValueError if the OAuth2 configuration for the given product is misconfigured. """ + oauth2_kwargs = { + 'proxy_config': proxy_config + } + if all(config in product_data for config in _OAUTH2_INSTALLED_APP_KEYS): oauth2_args = [ product_data['client_id'], product_data['client_secret'], @@ -272,12 +286,18 @@ def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config): elif all(config in product_data for config in _OAUTH2_SERVICE_ACCT_KEYS): oauth2_args = [ googleads.oauth2.GetAPIScope(product_yaml_key), - product_data['service_account_email'], - product_data['path_to_private_key_file'] ] + oauth2_kwargs.update({ + 'client_email': product_data.get('service_account_email'), + 'key_file': product_data['path_to_private_key_file'], + 'sub': product_data.get('delegated_account') + }) oauth2_client = googleads.oauth2.GoogleServiceAccountClient for key in _OAUTH2_SERVICE_ACCT_KEYS: del product_data[key] + for optional_key in _OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL: + if optional_key in product_data: + del product_data[optional_key] else: raise googleads.errors.GoogleAdsValueError( 'Your yaml file is incorrectly configured for OAuth2. You need to ' @@ -285,7 +305,7 @@ def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config): 'or service account flow (%s).' % (_OAUTH2_INSTALLED_APP_KEYS, _OAUTH2_SERVICE_ACCT_KEYS)) - return oauth2_client(*oauth2_args, proxy_config=proxy_config) + return oauth2_client(*oauth2_args, **oauth2_kwargs) def _ExtractProxyConfig(product_yaml_key, proxy_config_data): diff --git a/googleads/oauth2.py b/googleads/oauth2.py index 2600ccdb..806aa896 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -30,6 +30,18 @@ import httplib2 import oauth2client.client +if oauth2client.__version__ >= '4.0.0': + import oauth2client.service_account + DEPRECATED_OAUTH2CLIENT = False +elif (oauth2client.__version__ >= '1.4.12' and + oauth2client.__version__ < '2.0.0'): + DEPRECATED_OAUTH2CLIENT = True +else: + raise googleads.errors.GoogleAdsError( + 'Unsupported version of oauth2client is installed. To use this library, ' + 'upgrade to oauth2client 4.0.0.') + + # The scopes used for authorizing with the APIs supported by this library. SCOPES = {'adwords': 'https://www.googleapis.com/auth/adwords', 'dfp': 'https://www.googleapis.com/auth/dfp'} @@ -172,14 +184,18 @@ class GoogleServiceAccountClient(GoogleOAuth2Client): # minutes in advance of its expiration. _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5 _USER_AGENT = 'Google Ads Python Client Library' + _FILE_NOT_FOUND_TEMPLATE = 'The specified key file (%s) does not exist.' - def __init__(self, scope, client_email, key_file, + def __init__(self, scope, client_email=None, key_file=None, private_key_password='notasecret', sub=None, proxy_config=None): """Initializes a GoogleServiceAccountClient. Args: scope: The scope of the API you're authorizing for. - client_email: A string containing your Service Account's email. + client_email: A string containing your Service Account's email. If this is + set when using oauth2client 4.0.0, it will be assumed that you are + providing a P12 key file. A JSON key file does not require a client + email. key_file: A string containing the path to your key file. [optional] private_key_password: A string containing the password for your key file. @@ -188,21 +204,49 @@ def __init__(self, scope, client_email, key_file, proxy_config: A googleads.common.ProxyConfig instance. Raises: + GoogleAdsError: If an unsupported version of oauth2client is installed. GoogleAdsValueError: If the given key file does not exist. """ - try: - with open(key_file, 'rb') as f: - private_key = f.read() - except IOError: - raise googleads.errors.GoogleAdsValueError('The specified key file (%s)' - ' does not exist.' % key_file) - - self.oauth2credentials = ( - oauth2client.client.SignedJwtAssertionCredentials( - client_email, private_key, scope, - private_key_password=private_key_password, - user_agent=self._USER_AGENT, token_uri=self._GOOGLE_OAUTH2_ENDPOINT, - sub=sub)) + if DEPRECATED_OAUTH2CLIENT: + # Instantiate credentials using oauth2client version < 2.0.0. + try: + with open(key_file, 'rb') as f: + private_key = f.read() + except IOError: + raise googleads.errors.GoogleAdsValueError( + self._FILE_NOT_FOUND_TEMPLATE % key_file) + + self.oauth2credentials = ( + oauth2client.client.SignedJwtAssertionCredentials( + client_email, private_key, scope, + private_key_password=private_key_password, + user_agent=self._USER_AGENT, + token_uri=self._GOOGLE_OAUTH2_ENDPOINT, + sub=sub)) + else: + # Instantiate credentials using oauth2client 4.0.0. + if client_email: + # Instantiate credentials for P12 key file. + try: + self.oauth2credentials = ( + oauth2client.service_account.ServiceAccountCredentials + .from_p12_keyfile(client_email, key_file, scopes=scope)) + except IOError: + raise googleads.errors.GoogleAdsValueError( + self._FILE_NOT_FOUND_TEMPLATE % key_file) + else: + # Instantiate credentials for JSON key file. + try: + self.oauth2credentials = ( + oauth2client.service_account.ServiceAccountCredentials + .from_json_keyfile_name(key_file, scopes=scope)) + except IOError: + raise googleads.errors.GoogleAdsValueError( + self._FILE_NOT_FOUND_TEMPLATE % key_file) + # If sub is specified, apply it for domain-wide delegation of authority. + if sub: + self.oauth2credentials = self.oauth2credentials.create_delegated(sub) + self.proxy_config = (proxy_config if proxy_config else googleads.common.ProxyConfig()) self.Refresh() diff --git a/googleads/util.py b/googleads/util.py index 390f6c62..7fff45d5 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -88,7 +88,8 @@ def _ApplySudsJurkoSendPatch(self): def PatchedHttpTransportSend(self, request): """Patch for HttpTransport.send to enable gzip compression.""" msg = request.message - url = request.url + http_transport = suds.transport.http.HttpTransport + url = http_transport._HttpTransport__get_request_url(request) headers = request.headers u2request = urllib2.Request(url, msg, headers) self.addcookies(u2request) diff --git a/setup.py b/setup.py index bf7ebca7..8c735d83 100755 --- a/setup.py +++ b/setup.py @@ -24,7 +24,7 @@ PACKAGES = ['googleads'] -DEPENDENCIES = ['httplib2>=0.9.2', 'oauth2client>=1.5.2,<2.0.0', +DEPENDENCIES = ['httplib2>=0.9.2', 'oauth2client>=4.0.0,<5.0.0', 'suds-jurko>=0.6', 'pysocks>=1.5.6', 'pytz>=2015.7', 'PyYAML>=3.11', 'xmltodict>=0.9.2'] @@ -107,7 +107,7 @@ def GetVersion(): version=GetVersion(), description='Google Ads Python Client Library', author='Mark Saniscalchi', - author_email='msaniscalchi@google.com', + author_email='api.msaniscalchi@gmail.com', url='https://github.com/googleads/googleads-python-lib', license='Apache License 2.0', long_description=long_description, diff --git a/tests/common_test.py b/tests/common_test.py index 2ccd66d3..fa566415 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,8 +37,10 @@ class CommonTest(unittest.TestCase): # Dictionaries with all the required OAuth2 keys _OAUTH_INSTALLED_APP_DICT = {'client_id': 'a', 'client_secret': 'b', 'refresh_token': 'c'} - _OAUTH_SERVICE_ACCT_DICT = {'service_account_email': 'test@test.com', - 'path_to_private_key_file': '/test/test.p12'} + _OAUTH_SERVICE_ACCT_DICT = { + 'service_account_email': 'service_account@example.com', + 'path_to_private_key_file': '/test/test.p12', + 'delegated_account': 'delegated_account@example.com'} def setUp(self): self.filesystem = fake_filesystem.FakeFilesystem() @@ -534,7 +536,7 @@ def testLoadFromString(self): rval) self.assertTrue(googleads.common._utility_registry._enabled) - def testLoadFromString_serviceAccount(self): + def testLoadFromString_serviceAccountWithDeprecatedOAuth2Client(self): dfp_scope = googleads.oauth2.GetAPIScope('dfp') # No optional keys present. yaml_doc = self._CreateYamlDoc( @@ -552,7 +554,8 @@ def testLoadFromString_serviceAccount(self): http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( - dfp_scope, 'test@test.com', '/test/test.p12', + dfp_scope, client_email='service_account@example.com', + key_file='/test/test.p12', sub='delegated_account@example.com', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, @@ -576,7 +579,8 @@ def testLoadFromString_serviceAccount(self): http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( - dfp_scope, 'test@test.com', '/test/test.p12', + dfp_scope, client_email='service_account@example.com', + key_file='/test/test.p12', sub='delegated_account@example.com', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index 343ffbf3..58cc19cb 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -97,8 +97,8 @@ def setUp(self): # Mock out oauth2client.client.OAuth2Credentials for testing self.oauth2_credentials = mock.Mock(spec=OAuth2Credentials) - self.mock_oauth2_credentials = self.oauth2_credentials.return_value = ( - mock.Mock()) + self.oauth2_credentials.return_value = mock.Mock() + self.mock_oauth2_credentials = (self.oauth2_credentials.return_value) self.mock_oauth2_credentials.access_token = self.access_token_unrefreshed self.mock_oauth2_credentials.token_expiry = datetime.datetime(1980, 1, 1, 12) @@ -152,7 +152,9 @@ class GoogleServiceAccountTest(unittest.TestCase): def setUp(self): self.scope = 'scope' self.service_account_email = 'email@email.com' + self.private_key = 'IT\'S A SECRET TO EVERYBODY.' self.private_key_password = 'notasecret' + self.delegated_account = 'delegated_account@delegated.com' https_proxy_host = 'myproxy.com' https_proxy_port = 443 https_proxy = googleads.common.ProxyConfig.Proxy(https_proxy_host, @@ -165,11 +167,11 @@ def setUp(self): # Mock out filesystem and file for testing. filesystem = fake_filesystem.FakeFilesystem() tempfile = fake_tempfile.FakeTempfileModule(filesystem) - fake_open = fake_filesystem.FakeFileOpen(filesystem) - key_file_path = tempfile.NamedTemporaryFile(delete=False).name + self.fake_open = fake_filesystem.FakeFileOpen(filesystem) + self.key_file_path = tempfile.NamedTemporaryFile(delete=False).name - with fake_open(key_file_path, 'w') as file_handle: - file_handle.write('IT\'S A SECRET TO EVERYBODY.') + with self.fake_open(self.key_file_path, 'w') as file_handle: + file_handle.write(self.private_key) # Mock out httplib2.Http for testing. self.http = mock.Mock(spec=httplib2.Http) @@ -179,13 +181,15 @@ def setUp(self): self.opener.disable_ssl_certificate_valiation = ( self.proxy_config.disable_certificate_validation) - # Mock out oauth2client.client.OAuth2Credentials for testing - self.oauth2_credentials = mock.Mock(spec=SignedJwtAssertionCredentials) - self.mock_oauth2_credentials = self.oauth2_credentials.return_value = ( - mock.Mock()) + # Mock out oauth2client.client.SignedJwtAssertionCredentials for + # testing. + self.oauth2_credentials = mock.Mock( + spec=SignedJwtAssertionCredentials) + self.oauth2_credentials.return_value = mock.Mock() + self.mock_oauth2_credentials = (self.oauth2_credentials.return_value) self.mock_oauth2_credentials.access_token = 'x' - self.mock_oauth2_credentials.token_expiry = datetime.datetime(1980, 1, 1, - 12) + self.mock_oauth2_credentials.token_expiry = datetime.datetime( + 1980, 1, 1, 12) def apply(headers): headers['Authorization'] = ('Bearer %s' @@ -200,16 +204,160 @@ def refresh(mock_http): self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply) self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh) - with mock.patch('__builtin__.open', fake_open): + with mock.patch('__builtin__.open', self.fake_open): with mock.patch('oauth2client.client' '.SignedJwtAssertionCredentials', self.oauth2_credentials): self.googleads_client = googleads.oauth2.GoogleServiceAccountClient( - self.scope, self.service_account_email, key_file_path, + self.scope, self.service_account_email, self.key_file_path, self.private_key_password, proxy_config=self.proxy_config) # Undo the call count for the auto-refresh self.mock_oauth2_credentials.refresh.reset_mock() + def testCreateGoogleServiceAccountClient_DelegatedJsonOAuth2Client4(self): + # Mock out the oauth2client 4.0.0 oauth2client.service_account module to + # verify that the correct parts are called. + mock_oauth2client_4 = mock.Mock() + mock_service_account_module = mock.Mock() + mock_service_account_credentials = mock.Mock() + mock_service_account_credentials_instance = mock.Mock() + mock_from_json_keyfile_name = mock.Mock() + mock_create_delegated = mock.Mock() + mock_service_account_credentials_instance.create_delegated = ( + mock_create_delegated) + mock_from_json_keyfile_name.return_value = ( + mock_service_account_credentials_instance) + mock_service_account_credentials.from_json_keyfile_name = ( + mock_from_json_keyfile_name) + mock_service_account_module.ServiceAccountCredentials = ( + mock_service_account_credentials) + mock_oauth2client_4.service_account = mock_service_account_module + mock_oauth2client_4.__version__ = '4.0.0' + with mock.patch('googleads.oauth2.oauth2client', + mock_oauth2client_4): + with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', False): + mock_oauth2client_4.service_account = mock_service_account_module + # Create a GoogleServiceAccountClient and verify that the + # ServiceAccountCredentials were correctly instantiated. + googleads.oauth2.GoogleServiceAccountClient( + self.scope, client_email=None, key_file=self.key_file_path, + sub=self.delegated_account) + mock_from_json_keyfile_name.assert_called_once_with( + self.key_file_path, scopes=self.scope) + mock_create_delegated.assert_called_once_with(self.delegated_account) + + def testCreateGoogleServiceAccountClient_DelegatedP12OAuth2Client4(self): + # Mock out the oauth2client 4.0.0 oauth2client.service_account module to + # verify that the correct parts are called. + mock_oauth2client_4 = mock.Mock() + mock_service_account_module = mock.Mock() + mock_service_account_credentials = mock.Mock() + mock_service_account_credentials_instance = mock.Mock() + mock_from_p12_keyfile = mock.Mock() + mock_create_delegated = mock.Mock() + mock_service_account_credentials_instance.create_delegated = ( + mock_create_delegated) + mock_from_p12_keyfile.return_value = ( + mock_service_account_credentials_instance) + mock_service_account_credentials.from_p12_keyfile = ( + mock_from_p12_keyfile) + mock_service_account_module.ServiceAccountCredentials = ( + mock_service_account_credentials) + mock_oauth2client_4.service_account = mock_service_account_module + mock_oauth2client_4.__version__ = '4.0.0' + with mock.patch('googleads.oauth2.oauth2client', + mock_oauth2client_4): + with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', False): + mock_oauth2client_4.service_account = mock_service_account_module + # Create a GoogleServiceAccountClient and verify that the + # ServiceAccountCredentials were correctly instantiated. + googleads.oauth2.GoogleServiceAccountClient( + self.scope, client_email=self.service_account_email, + key_file=self.key_file_path, sub=self.delegated_account) + mock_from_p12_keyfile.assert_called_once_with( + self.service_account_email, self.key_file_path, scopes=self.scope) + mock_create_delegated.assert_called_once_with(self.delegated_account) + + def testCreateGoogleServiceAccountClient_DelegatedP12OAuth2ClientDepr(self): + # Mock out the oauth2client 1.4.12 oauth2client.service_account module to + # verify that the correct parts are called. + with mock.patch('googleads.oauth2.oauth2client.client' + '.SignedJwtAssertionCredentials') as mock_credentials: + with mock.patch('%s.open' % googleads.oauth2.__name__, self.fake_open, + create=True): + googleads.oauth2.GoogleServiceAccountClient( + self.scope, client_email=self.service_account_email, + key_file=self.key_file_path, sub=self.delegated_account) + mock_credentials.assert_called_once_with( + self.service_account_email, self.private_key, self.scope, + private_key_password=self.private_key_password, + user_agent='Google Ads Python Client Library', + token_uri='https://accounts.google.com/o/oauth2/token', + sub=self.delegated_account) + + def testCreateGoogleServiceAccountClient_JsonOAuth2Client4(self): + # Mock out the oauth2client 4.0.0 oauth2client.service_account module to + # verify that the correct parts are called. + mock_oauth2client_4 = mock.Mock() + mock_service_account_module = mock.Mock() + mock_service_account_credentials = mock.Mock() + mock_service_account_credentials_instance = mock.Mock() + mock_from_json_keyfile_name = mock.Mock() + mock_create_delegated = mock.Mock() + mock_service_account_credentials_instance.create_delegated = ( + mock_create_delegated) + mock_from_json_keyfile_name.return_value = ( + mock_service_account_credentials_instance) + mock_service_account_credentials.from_json_keyfile_name = ( + mock_from_json_keyfile_name) + mock_service_account_module.ServiceAccountCredentials = ( + mock_service_account_credentials) + mock_oauth2client_4.service_account = mock_service_account_module + mock_oauth2client_4.__version__ = '4.0.0' + with mock.patch('googleads.oauth2.oauth2client', + mock_oauth2client_4): + with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', False): + mock_oauth2client_4.service_account = mock_service_account_module + # Create a GoogleServiceAccountClient and verify that the + # ServiceAccountCredentials were correctly instantiated. + googleads.oauth2.GoogleServiceAccountClient( + self.scope, client_email=None, key_file=self.key_file_path) + mock_from_json_keyfile_name.assert_called_once_with( + self.key_file_path, scopes=self.scope) + mock_create_delegated.assert_not_called() + + def testCreateGoogleServiceAccountClient_P12OAuth2Client4(self): + # Mock out the oauth2client 4.0.0 oauth2client.service_account module to + # verify that the correct parts are called. + mock_oauth2client_4 = mock.Mock() + mock_service_account_module = mock.Mock() + mock_service_account_credentials = mock.Mock() + mock_service_account_credentials_instance = mock.Mock() + mock_from_p12_keyfile = mock.Mock() + mock_create_delegated = mock.Mock() + mock_service_account_credentials_instance.create_delegated = ( + mock_create_delegated) + mock_from_p12_keyfile.return_value = ( + mock_service_account_credentials_instance) + mock_service_account_credentials.from_p12_keyfile = ( + mock_from_p12_keyfile) + mock_service_account_module.ServiceAccountCredentials = ( + mock_service_account_credentials) + mock_oauth2client_4.service_account = mock_service_account_module + mock_oauth2client_4.__version__ = '4.0.0' + with mock.patch('googleads.oauth2.oauth2client', + mock_oauth2client_4): + with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', False): + mock_oauth2client_4.service_account = mock_service_account_module + # Create a GoogleServiceAccountClient and verify that the + # ServiceAccountCredentials were correctly instantiated. + googleads.oauth2.GoogleServiceAccountClient( + self.scope, client_email=self.service_account_email, + key_file=self.key_file_path) + mock_from_p12_keyfile.assert_called_once_with( + self.service_account_email, self.key_file_path, scopes=self.scope) + mock_create_delegated.assert_not_called() + def testCreateHttpHeader_noRefresh(self): header = {'Authorization': 'Bearer %s' % self.access_token_unrefreshed} self.mock_oauth2_credentials.token_expiry = None From bf443160ba2588d2033817920c82d2e24cbb1fff Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 1 Mar 2017 18:26:43 -0500 Subject: [PATCH 065/180] Commiting latest changes. From 7888d906eeadfeb5093b9d9035621206017933fb Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 20 Mar 2017 18:41:13 -0400 Subject: [PATCH 066/180] AdWords v201605 sunset --- ChangeLog | 9 +- ...ate_adwords_client_with_service_account.py | 10 +- .../create_adwords_client_without_yaml.py | 10 +- examples/adwords/v201605/__init__.py | 15 - .../v201605/account_management/__init__.py | 15 - .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 99 ---- .../get_account_hierarchy.py | 104 ---- .../v201605/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 223 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 108 ---- .../advanced_operations/add_html5_ad.py | 111 ---- .../add_responsive_display_ad.py | 91 --- .../add_text_ad_with_upgraded_urls.py | 111 ---- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 171 ------ .../v201605/basic_operations/__init__.py | 15 - .../v201605/basic_operations/add_ad_groups.py | 115 ---- .../v201605/basic_operations/add_campaigns.py | 125 ----- .../basic_operations/add_expanded_text_ads.py | 74 --- .../v201605/basic_operations/add_keywords.py | 92 --- .../v201605/basic_operations/add_text_ads.py | 93 ---- .../v201605/basic_operations/get_ad_groups.py | 76 --- .../v201605/basic_operations/get_campaigns.py | 74 --- .../get_campaigns_with_awql.py | 64 --- .../basic_operations/get_expanded_text_ads.py | 90 --- .../v201605/basic_operations/get_keywords.py | 87 --- .../v201605/basic_operations/get_text_ads.py | 80 --- .../v201605/basic_operations/pause_ad.py | 61 -- .../v201605/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 58 -- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201605/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 426 -------------- .../v201605/campaign_management/add_draft.py | 81 --- .../campaign_management/add_experiment.py | 127 ----- ...dd_keywords_using_incremental_batch_job.py | 259 --------- .../v201605/campaign_management/add_trial.py | 117 ---- .../get_all_disapproved_ads.py | 74 --- .../get_all_disapproved_ads_with_awql.py | 63 --- .../get_campaigns_by_label.py | 85 --- .../campaign_management/graduate_trial.py | 79 --- .../campaign_management/promote_experiment.py | 60 -- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201605/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 120 ---- .../handle_policy_violation_error.py | 117 ---- .../adwords/v201605/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 ------ .../v201605/extensions/add_site_links.py | 134 ----- .../extensions/add_site_links_using_feeds.py | 233 -------- .../adwords/v201605/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 ------------------ examples/adwords/v201605/misc/__init__.py | 15 - .../v201605/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201605/misc/upload_image.py | 66 --- .../v201605/misc/upload_media_bundle.py | 59 -- .../adwords/v201605/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 180 ------ ...aign_criterion_bid_modifier_simulations.py | 96 ---- .../get_keyword_bid_simulations.py | 81 --- .../v201605/optimization/get_keyword_ideas.py | 100 ---- .../adwords/v201605/remarketing/__init__.py | 15 - .../v201605/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 70 --- .../remarketing/add_crm_based_user_list.py | 94 ---- .../remarketing/add_rule_based_user_lists.py | 183 ------ .../remarketing/upload_offline_conversions.py | 75 --- .../adwords/v201605/reporting/__init__.py | 15 - .../reporting/download_criteria_report.py | 61 -- .../download_criteria_report_as_stream.py | 77 --- ...oad_criteria_report_as_stream_with_awql.py | 81 --- .../download_criteria_report_as_string.py | 59 -- ...oad_criteria_report_as_string_with_awql.py | 55 -- .../download_criteria_report_with_awql.py | 59 -- .../v201605/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 230 -------- examples/adwords/v201605/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 281 ---------- .../v201605/shopping/add_product_scope.py | 104 ---- .../v201605/shopping/add_shopping_campaign.py | 121 ---- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201605/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 161 ------ .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201605/targeting/lookup_location.py | 82 --- .../extensions/add_site_links_using_feeds.py | 46 +- .../extensions/add_site_links_using_feeds.py | 46 +- .../extensions/add_site_links_using_feeds.py | 46 +- .../v201702/optimization/get_keyword_ideas.py | 2 +- googleads/adwords.py | 46 -- googleads/common.py | 2 +- googleads/dfp.py | 20 +- tests/dfp_test.py | 12 +- 106 files changed, 122 insertions(+), 9261 deletions(-) delete mode 100644 examples/adwords/v201605/__init__.py delete mode 100644 examples/adwords/v201605/account_management/__init__.py delete mode 100755 examples/adwords/v201605/account_management/create_account.py delete mode 100755 examples/adwords/v201605/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201605/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201605/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201605/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201605/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201605/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201605/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201605/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201605/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201605/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201605/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201605/basic_operations/__init__.py delete mode 100755 examples/adwords/v201605/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201605/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201605/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201605/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201605/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201605/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201605/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201605/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201605/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201605/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201605/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201605/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201605/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201605/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201605/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201605/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201605/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201605/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201605/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201605/campaign_management/__init__.py delete mode 100755 examples/adwords/v201605/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201605/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201605/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201605/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201605/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201605/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201605/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201605/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201605/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201605/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201605/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201605/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201605/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201605/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201605/error_handling/__init__.py delete mode 100755 examples/adwords/v201605/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201605/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201605/extensions/__init__.py delete mode 100755 examples/adwords/v201605/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201605/extensions/add_site_links.py delete mode 100755 examples/adwords/v201605/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201605/migration/__init__.py delete mode 100755 examples/adwords/v201605/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201605/misc/__init__.py delete mode 100755 examples/adwords/v201605/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201605/misc/upload_image.py delete mode 100755 examples/adwords/v201605/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201605/optimization/__init__.py delete mode 100755 examples/adwords/v201605/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201605/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201605/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201605/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201605/remarketing/__init__.py delete mode 100755 examples/adwords/v201605/remarketing/add_audience.py delete mode 100755 examples/adwords/v201605/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201605/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201605/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201605/remarketing/upload_offline_conversions.py delete mode 100644 examples/adwords/v201605/reporting/__init__.py delete mode 100755 examples/adwords/v201605/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201605/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201605/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201605/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201605/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201605/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201605/shopping/__init__.py delete mode 100755 examples/adwords/v201605/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201605/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201605/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201605/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201605/targeting/__init__.py delete mode 100755 examples/adwords/v201605/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201605/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201605/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201605/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201605/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 61ceba30..aba55f7a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,10 +1,16 @@ +5.3.0 -- 3/20/17: +* Removed support for AdWords v201605. +* Removed examples for AdWords v201605. +* Added support for the complete set of DFP report download options. +* Resolved issues: +- Issue 169: https://github.com/googleads/googleads-python-lib/issues/169 + 5.2.0 -- 3/1/17: * Added support for AdWords v201702. * Resolved issues: - Issue 110: https://github.com/googleads/googleads-python-lib/issues/110 - Issue 180: https://github.com/googleads/googleads-python-lib/issues/180 - 5.1.0 -- 2/13/17: * Added support for DFP v201702. * Removed examples for DFP v201605. @@ -14,7 +20,6 @@ - Issue 176: https://github.com/googleads/googleads-python-lib/issues/176 Issue 177: https://github.com/googleads/googleads-python-lib/issues/177 - 5.0.0 -- 1/13/17: * BREAKING CHANGE: The underlying suds client now has cache enabled. By default, suds uses FileCache which requires access to local file system and will break diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index e91aaee4..57f978c4 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -42,8 +42,14 @@ def main(service_account_email, key_file, service_account_user, developer_token, oauth2_client, user_agent, client_customer_id=client_customer_id) - customer = adwords_client.GetService('CustomerService').get() - print 'You are logged in as customer: %s' % customer['customerId'] + customer_service = adwords_client.GetService('CustomerService', + version='v201702') + customers = customer_service.getCustomers() + + print 'You are logged in as a user with access to the following customers:' + + for customer in customers: + print '\t%s' % customer['customerId'] if __name__ == '__main__': diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_without_yaml.py index daad6080..12e9ad99 100755 --- a/examples/adwords/authentication/create_adwords_client_without_yaml.py +++ b/examples/adwords/authentication/create_adwords_client_without_yaml.py @@ -47,8 +47,14 @@ def main(client_id, client_secret, refresh_token, developer_token, user_agent, developer_token, oauth2_client, user_agent, client_customer_id=client_customer_id) - customer = adwords_client.GetService('CustomerService').get() - print 'You are logged in as customer: %s' % customer['customerId'] + customer_service = adwords_client.GetService('CustomerService', + version='v201702') + customers = customer_service.getCustomers() + + print 'You are logged in as a user with access to the following customers:' + + for customer in customers: + print '\t%s' % customer['customerId'] if __name__ == '__main__': diff --git a/examples/adwords/v201605/__init__.py b/examples/adwords/v201605/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201605/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201605/account_management/__init__.py b/examples/adwords/v201605/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201605/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201605/account_management/create_account.py b/examples/adwords/v201605/account_management/create_account.py deleted file mode 100755 index 72f0028b..00000000 --- a/examples/adwords/v201605/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201605') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/account_management/get_account_changes.py b/examples/adwords/v201605/account_management/get_account_changes.py deleted file mode 100755 index d2b94067..00000000 --- a/examples/adwords/v201605/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201605') - campaign_service = client.GetService('CampaignService', version='v201605') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/account_management/get_account_hierarchy.py b/examples/adwords/v201605/account_management/get_account_hierarchy.py deleted file mode 100755 index 08128681..00000000 --- a/examples/adwords/v201605/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201605') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/advanced_operations/__init__.py b/examples/adwords/v201605/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201605/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201605/advanced_operations/add_ad_customizer.py b/examples/adwords/v201605/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 19ad142d..00000000 --- a/examples/adwords/v201605/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,223 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates TextAds that use ad customizations for the specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add TextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no TextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201605') - - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'description1': 'Only {=%s.Price}' % feed_name, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201605') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201605') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201605/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201605/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 40cdd07a..00000000 --- a/examples/adwords/v201605/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201605') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 3c4be5be..00000000 --- a/examples/adwords/v201605/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/advanced_operations/add_html5_ad.py b/examples/adwords/v201605/advanced_operations/add_html5_ad.py deleted file mode 100755 index 9cc2e229..00000000 --- a/examples/adwords/v201605/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index a81be943..00000000 --- a/examples/adwords/v201605/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - media_service = client.GetService('MediaService', version='v201605') - - try: - # Create image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - # Make the upload request - image = media_service.upload(image)[0] - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'] - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201605/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index 7ce22271..00000000 --- a/examples/adwords/v201605/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a text add that uses advanced features of upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201605/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201605/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index d7dccbc9..00000000 --- a/examples/adwords/v201605/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201605') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201605') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201605') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201605/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index fba405b3..00000000 --- a/examples/adwords/v201605/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201605') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201605') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201605/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index deaa6b0f..00000000 --- a/examples/adwords/v201605/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201605') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201605/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index d6c80a81..00000000 --- a/examples/adwords/v201605/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201605') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201605') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201605') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201605/basic_operations/__init__.py b/examples/adwords/v201605/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201605/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201605/basic_operations/add_ad_groups.py b/examples/adwords/v201605/basic_operations/add_ad_groups.py deleted file mode 100755 index 7b1a46d4..00000000 --- a/examples/adwords/v201605/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201605') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/basic_operations/add_campaigns.py b/examples/adwords/v201605/basic_operations/add_campaigns.py deleted file mode 100755 index d6f447c3..00000000 --- a/examples/adwords/v201605/basic_operations/add_campaigns.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201605') - budget_service = client.GetService('BudgetService', version='v201605') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201605/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index c5f0f9bc..00000000 --- a/examples/adwords/v201605/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/add_keywords.py b/examples/adwords/v201605/basic_operations/add_keywords.py deleted file mode 100755 index 171b5f4a..00000000 --- a/examples/adwords/v201605/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201605') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/add_text_ads.py b/examples/adwords/v201605/basic_operations/add_text_ads.py deleted file mode 100755 index 011ea55c..00000000 --- a/examples/adwords/v201605/basic_operations/add_text_ads.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/get_ad_groups.py b/examples/adwords/v201605/basic_operations/get_ad_groups.py deleted file mode 100755 index 3f4315cf..00000000 --- a/examples/adwords/v201605/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201605') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/basic_operations/get_campaigns.py b/examples/adwords/v201605/basic_operations/get_campaigns.py deleted file mode 100755 index 0ef90350..00000000 --- a/examples/adwords/v201605/basic_operations/get_campaigns.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201605') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201605/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 6ba4bcd0..00000000 --- a/examples/adwords/v201605/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201605') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index 2fdfe030..00000000 --- a/examples/adwords/v201605/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/get_keywords.py b/examples/adwords/v201605/basic_operations/get_keywords.py deleted file mode 100755 index 8ffb8181..00000000 --- a/examples/adwords/v201605/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201605') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/get_text_ads.py b/examples/adwords/v201605/basic_operations/get_text_ads.py deleted file mode 100755 index 97306ccb..00000000 --- a/examples/adwords/v201605/basic_operations/get_text_ads.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/pause_ad.py b/examples/adwords/v201605/basic_operations/pause_ad.py deleted file mode 100755 index a0afeec8..00000000 --- a/examples/adwords/v201605/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201605/basic_operations/remove_ad.py b/examples/adwords/v201605/basic_operations/remove_ad.py deleted file mode 100755 index bfb6fee8..00000000 --- a/examples/adwords/v201605/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201605/basic_operations/remove_ad_group.py b/examples/adwords/v201605/basic_operations/remove_ad_group.py deleted file mode 100755 index be66dc20..00000000 --- a/examples/adwords/v201605/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201605') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/remove_campaign.py b/examples/adwords/v201605/basic_operations/remove_campaign.py deleted file mode 100755 index adb7f0ef..00000000 --- a/examples/adwords/v201605/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201605') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/basic_operations/remove_keyword.py b/examples/adwords/v201605/basic_operations/remove_keyword.py deleted file mode 100755 index 93c2c53b..00000000 --- a/examples/adwords/v201605/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201605') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201605/basic_operations/update_ad_group.py b/examples/adwords/v201605/basic_operations/update_ad_group.py deleted file mode 100755 index 0b8debe4..00000000 --- a/examples/adwords/v201605/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201605') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/basic_operations/update_campaign.py b/examples/adwords/v201605/basic_operations/update_campaign.py deleted file mode 100755 index c5070940..00000000 --- a/examples/adwords/v201605/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201605') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/basic_operations/update_keyword.py b/examples/adwords/v201605/basic_operations/update_keyword.py deleted file mode 100755 index fb009448..00000000 --- a/examples/adwords/v201605/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201605') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201605/campaign_management/__init__.py b/examples/adwords/v201605/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201605/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201605/campaign_management/add_campaign_labels.py b/examples/adwords/v201605/campaign_management/add_campaign_labels.py deleted file mode 100755 index 4b2b0cc0..00000000 --- a/examples/adwords/v201605/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201605') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201605/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201605/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index 89ef25a1..00000000 --- a/examples/adwords/v201605/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,426 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201605') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201605') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding a TextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new TextAd for each of - the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201605') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201605/campaign_management/add_draft.py b/examples/adwords/v201605/campaign_management/add_draft.py deleted file mode 100755 index f69d81db..00000000 --- a/examples/adwords/v201605/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - # Initialize appropriate services. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201605') - draft_service = client.GetService('DraftService', version='v201605') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201605/campaign_management/add_experiment.py b/examples/adwords/v201605/campaign_management/add_experiment.py deleted file mode 100755 index baf9c14d..00000000 --- a/examples/adwords/v201605/campaign_management/add_experiment.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201605') - ad_group_service = client.GetService('AdGroupService', version='v201605') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201605') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201605/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201605/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index 2fdd9939..00000000 --- a/examples/adwords/v201605/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201605') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201605') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201605') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201605') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201605/campaign_management/add_trial.py b/examples/adwords/v201605/campaign_management/add_trial.py deleted file mode 100755 index a1412cb7..00000000 --- a/examples/adwords/v201605/campaign_management/add_trial.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201605') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201605') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201605/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201605/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 63aabca5..00000000 --- a/examples/adwords/v201605/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201605/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 97b3c1ec..00000000 --- a/examples/adwords/v201605/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201605/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 99a69be3..00000000 --- a/examples/adwords/v201605/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201605') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201605/campaign_management/graduate_trial.py b/examples/adwords/v201605/campaign_management/graduate_trial.py deleted file mode 100755 index 290284e0..00000000 --- a/examples/adwords/v201605/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201605') - budget_service = client.GetService('BudgetService', version='v201605') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201605/campaign_management/promote_experiment.py b/examples/adwords/v201605/campaign_management/promote_experiment.py deleted file mode 100755 index 0f181e10..00000000 --- a/examples/adwords/v201605/campaign_management/promote_experiment.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201605') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201605/campaign_management/set_ad_parameters.py b/examples/adwords/v201605/campaign_management/set_ad_parameters.py deleted file mode 100755 index 987a8fc3..00000000 --- a/examples/adwords/v201605/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - ad_param_service = client.GetService('AdParamService', version='v201605') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201605/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201605/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index 5d48f143..00000000 --- a/examples/adwords/v201605/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201605') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201605/campaign_management/validate_text_ad.py b/examples/adwords/v201605/campaign_management/validate_text_ad.py deleted file mode 100755 index b3dbb560..00000000 --- a/examples/adwords/v201605/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/error_handling/__init__.py b/examples/adwords/v201605/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201605/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201605/error_handling/handle_partial_failures.py b/examples/adwords/v201605/error_handling/handle_partial_failures.py deleted file mode 100755 index a67c5191..00000000 --- a/examples/adwords/v201605/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201605') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/error_handling/handle_policy_violation_error.py b/examples/adwords/v201605/error_handling/handle_policy_violation_error.py deleted file mode 100755 index c5658859..00000000 --- a/examples/adwords/v201605/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201605') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - index = int(operation_index[0]) - operation = operations[index] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Set non-exemptable operation to None to mark for deletion - print 'Removing the operation from the request.' - operations[index] = None - else: - # Non-policy error returned, re-throw exception. - raise e - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/extensions/__init__.py b/examples/adwords/v201605/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201605/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201605/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201605/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 49a2d81b..00000000 --- a/examples/adwords/v201605/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201605').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201605') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201605/extensions/add_site_links.py b/examples/adwords/v201605/extensions/add_site_links.py deleted file mode 100755 index 8a654c43..00000000 --- a/examples/adwords/v201605/extensions/add_site_links.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201605') - customer_service = client.GetService('CustomerService', version='v201605') - - customer_tz = timezone(customer_service.get()['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840} - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/extensions/add_site_links_using_feeds.py b/examples/adwords/v201605/extensions/add_site_links_using_feeds.py deleted file mode 100755 index a6e5ddb9..00000000 --- a/examples/adwords/v201605/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,233 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201605') - feed_item_service = client.GetService('FeedItemService', version='v201605') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201605') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201605') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/migration/__init__.py b/examples/adwords/v201605/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201605/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201605/migration/migrate_to_extension_settings.py b/examples/adwords/v201605/migration/migrate_to_extension_settings.py deleted file mode 100755 index 7552842f..00000000 --- a/examples/adwords/v201605/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201605') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201605') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201605') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201605') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201605') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201605') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201605') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/misc/__init__.py b/examples/adwords/v201605/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201605/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201605/misc/get_all_images_and_videos.py b/examples/adwords/v201605/misc/get_all_images_and_videos.py deleted file mode 100755 index 40a0e6fb..00000000 --- a/examples/adwords/v201605/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201605') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/misc/upload_image.py b/examples/adwords/v201605/misc/upload_image.py deleted file mode 100755 index d762e10c..00000000 --- a/examples/adwords/v201605/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201605') - - with open(image_filename, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201605/misc/upload_media_bundle.py b/examples/adwords/v201605/misc/upload_media_bundle.py deleted file mode 100755 index 033d2010..00000000 --- a/examples/adwords/v201605/misc/upload_media_bundle.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201605') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/optimization/__init__.py b/examples/adwords/v201605/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201605/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201605/optimization/estimate_keyword_traffic.py b/examples/adwords/v201605/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 21920429..00000000 --- a/examples/adwords/v201605/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201605') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201605/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index 9892b9f5..00000000 --- a/examples/adwords/v201605/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201605') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201605/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index c4575852..00000000 --- a/examples/adwords/v201605/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201605') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201605/optimization/get_keyword_ideas.py b/examples/adwords/v201605/optimization/get_keyword_ideas.py deleted file mode 100755 index cedc3511..00000000 --- a/examples/adwords/v201605/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201605') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/remarketing/__init__.py b/examples/adwords/v201605/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201605/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201605/remarketing/add_audience.py b/examples/adwords/v201605/remarketing/add_audience.py deleted file mode 100755 index 92a02035..00000000 --- a/examples/adwords/v201605/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201605') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201605') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/remarketing/add_conversion_tracker.py b/examples/adwords/v201605/remarketing/add_conversion_tracker.py deleted file mode 100755 index 2fffb372..00000000 --- a/examples/adwords/v201605/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201605') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/remarketing/add_crm_based_user_list.py b/examples/adwords/v201605/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 107969eb..00000000 --- a/examples/adwords/v201605/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client, emails): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201605') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. - - Args: - emails: list of str emails to be hashed. - - Returns: - A list of SHA-256 hashed emails. - """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] - - -if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) diff --git a/examples/adwords/v201605/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201605/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index bd682ca7..00000000 --- a/examples/adwords/v201605/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201605') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/remarketing/upload_offline_conversions.py b/examples/adwords/v201605/remarketing/upload_offline_conversions.py deleted file mode 100755 index 4ff0d95d..00000000 --- a/examples/adwords/v201605/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201605') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201605/reporting/__init__.py b/examples/adwords/v201605/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201605/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201605/reporting/download_criteria_report.py b/examples/adwords/v201605/reporting/download_criteria_report.py deleted file mode 100755 index 68122cf4..00000000 --- a/examples/adwords/v201605/reporting/download_criteria_report.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201605') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index e86dddee..00000000 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201605') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 9638d92e..00000000 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201605') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_string.py b/examples/adwords/v201605/reporting/download_criteria_report_as_string.py deleted file mode 100755 index c061dd60..00000000 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201605') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 700083b2..00000000 --- a/examples/adwords/v201605/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201605') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 2bc34b5d..00000000 --- a/examples/adwords/v201605/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201605') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201605/reporting/get_report_fields.py b/examples/adwords/v201605/reporting/get_report_fields.py deleted file mode 100755 index cc630f7e..00000000 --- a/examples/adwords/v201605/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201605') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201605/reporting/parallel_report_download.py b/examples/adwords/v201605/reporting/parallel_report_download.py deleted file mode 100755 index a7ec117a..00000000 --- a/examples/adwords/v201605/reporting/parallel_report_download.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import logging -import multiprocessing -from Queue import Empty -import time -import googleads - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - client: An AdWordsClient instance. - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201605') - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = self._DownloadReport(customer_id) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - - Raises: - Exception: if no CustomerIds could be found. - - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201605') - - offset = 0 - - # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201605/shopping/__init__.py b/examples/adwords/v201605/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201605/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201605/shopping/add_product_partition_tree.py b/examples/adwords/v201605/shopping/add_product_partition_tree.py deleted file mode 100755 index b3751eda..00000000 --- a/examples/adwords/v201605/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201605') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201605/shopping/add_product_scope.py b/examples/adwords/v201605/shopping/add_product_scope.py deleted file mode 100755 index 01adb7ec..00000000 --- a/examples/adwords/v201605/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201605') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201605/shopping/add_shopping_campaign.py b/examples/adwords/v201605/shopping/add_shopping_campaign.py deleted file mode 100755 index c1b798dd..00000000 --- a/examples/adwords/v201605/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201605') - ad_group_service = client.GetService('AdGroupService', version='v201605') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201605') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201605/shopping/get_product_category_taxonomy.py b/examples/adwords/v201605/shopping/get_product_category_taxonomy.py deleted file mode 100755 index e7a91f78..00000000 --- a/examples/adwords/v201605/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201605') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/targeting/__init__.py b/examples/adwords/v201605/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201605/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201605/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201605/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 237c26d5..00000000 --- a/examples/adwords/v201605/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201605') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - florida_downtown = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'PlacesOfInterestOperand', - # Other valid options: AIRPORT, UNIVERSITY. - 'category': 'DOWNTOWN', - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - } - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish, florida_tier3, - florida_downtown] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201605/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201605/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index ffd844e9..00000000 --- a/examples/adwords/v201605/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201605') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201605/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201605/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 040af85d..00000000 --- a/examples/adwords/v201605/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201605') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201605/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index b6066f51..00000000 --- a/examples/adwords/v201605/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201605') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201605/targeting/lookup_location.py b/examples/adwords/v201605/targeting/lookup_location.py deleted file mode 100755 index 76561912..00000000 --- a/examples/adwords/v201605/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201605') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py index 5fce9b94..1f93a814 100755 --- a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py @@ -38,8 +38,8 @@ PLACEHOLDER_SITELINKS = '1' PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' @@ -61,8 +61,8 @@ def main(client, campaign_id): 'attributes': [ {'type': 'STRING', 'name': 'Link Text'}, {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} ] } @@ -74,36 +74,36 @@ def main(client, campaign_id): feed = response['value'][0] link_text_feed_attribute_id = feed['attributes'][0]['id'] final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] print ('Feed with name \'%s\' and ID \'%s\' was added with' % (feed['name'], feed['id'])) print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) + print ('\tLine 2 attribute ID \'%s\' and Line 3 attribute ID \'%s\'.' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) sitelinks_data['feedId'] = feed['id'] sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id else: raise errors.GoogleAdsError('No feeds were added.') # Create site links feed items. items_data = [ {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, + 'line2': 'Home line 2', 'line3': 'Home line 3'}, {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, + 'line2': 'Support line 2', 'line3': 'Support line 3'}, {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, + 'line2': 'Products line 2', 'line3': 'Products line 3'}, {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} ] feed_items = [] @@ -119,13 +119,13 @@ def main(client, campaign_id): 'feedAttributeId': sitelinks_data['finalUrlFeedId'], 'stringValues': [item['finalUrls']] }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, { 'feedAttributeId': sitelinks_data['line2FeedId'], 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] } ], # Optional: use the 'startTime' and 'endTime' keys to specify the time @@ -178,13 +178,13 @@ def main(client, campaign_id): 'feedAttributeId': sitelinks_data['finalUrlFeedId'], 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, { 'feedAttributeId': sitelinks_data['line2FeedId'], 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT } ] } diff --git a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py index 9115c415..5706cfff 100755 --- a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py @@ -38,8 +38,8 @@ PLACEHOLDER_SITELINKS = '1' PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' @@ -61,8 +61,8 @@ def main(client, campaign_id): 'attributes': [ {'type': 'STRING', 'name': 'Link Text'}, {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} ] } @@ -74,36 +74,36 @@ def main(client, campaign_id): feed = response['value'][0] link_text_feed_attribute_id = feed['attributes'][0]['id'] final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] print ('Feed with name \'%s\' and ID \'%s\' was added with' % (feed['name'], feed['id'])) print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) + print ('\tLine 2 attribute ID \'%s\' and Line 3 attribute ID \'%s\'.' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) sitelinks_data['feedId'] = feed['id'] sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id else: raise errors.GoogleAdsError('No feeds were added.') # Create site links feed items. items_data = [ {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, + 'line2': 'Home line 2', 'line3': 'Home line 3'}, {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, + 'line2': 'Support line 2', 'line3': 'Support line 3'}, {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, + 'line2': 'Products line 2', 'line3': 'Products line 3'}, {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} ] feed_items = [] @@ -119,13 +119,13 @@ def main(client, campaign_id): 'feedAttributeId': sitelinks_data['finalUrlFeedId'], 'stringValues': [item['finalUrls']] }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, { 'feedAttributeId': sitelinks_data['line2FeedId'], 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] } ], # Optional: use the 'startTime' and 'endTime' keys to specify the time @@ -178,13 +178,13 @@ def main(client, campaign_id): 'feedAttributeId': sitelinks_data['finalUrlFeedId'], 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, { 'feedAttributeId': sitelinks_data['line2FeedId'], 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT } ] } diff --git a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py index b113e21f..f727406e 100755 --- a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py @@ -38,8 +38,8 @@ PLACEHOLDER_SITELINKS = '1' PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_1_TEXT = '3' -PLACEHOLDER_FIELD_LINE_2_TEXT = '4' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' @@ -61,8 +61,8 @@ def main(client, campaign_id): 'attributes': [ {'type': 'STRING', 'name': 'Link Text'}, {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 1 Description'}, - {'type': 'STRING', 'name': 'Line 2 Description'} + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} ] } @@ -74,36 +74,36 @@ def main(client, campaign_id): feed = response['value'][0] link_text_feed_attribute_id = feed['attributes'][0]['id'] final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_1_feed_attribute_id = feed['attributes'][2]['id'] - line_2_feed_attribute_id = feed['attributes'][3]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] print ('Feed with name \'%s\' and ID \'%s\' was added with' % (feed['name'], feed['id'])) print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 1 attribute ID \'%s\' and Line 2 attribute ID \'%s\'.' % - (line_1_feed_attribute_id, line_2_feed_attribute_id)) + print ('\tLine 2 attribute ID \'%s\' and Line 3 attribute ID \'%s\'.' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) sitelinks_data['feedId'] = feed['id'] sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line1FeedId'] = line_1_feed_attribute_id sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id else: raise errors.GoogleAdsError('No feeds were added.') # Create site links feed items. items_data = [ {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line1': 'Home line 1', 'line2': 'Home line 2'}, + 'line2': 'Home line 2', 'line3': 'Home line 3'}, {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line1': 'Stores line 1', 'line2': 'Stores line 2'}, + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line1': 'On Sale line 1', 'line2': 'On Sale line 2'}, + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line1': 'Support line 1', 'line2': 'Support line 2'}, + 'line2': 'Support line 2', 'line3': 'Support line 3'}, {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line1': 'Products line 1', 'line2': 'Products line 2'}, + 'line2': 'Products line 2', 'line3': 'Products line 3'}, {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line1': 'About line 1', 'line2': 'About line 2', 'locationId': '21137'} + 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} ] feed_items = [] @@ -119,13 +119,13 @@ def main(client, campaign_id): 'feedAttributeId': sitelinks_data['finalUrlFeedId'], 'stringValues': [item['finalUrls']] }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'stringValue': item['line1'] - }, { 'feedAttributeId': sitelinks_data['line2FeedId'], 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] } ], # Optional: use the 'startTime' and 'endTime' keys to specify the time @@ -178,13 +178,13 @@ def main(client, campaign_id): 'feedAttributeId': sitelinks_data['finalUrlFeedId'], 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS }, - { - 'feedAttributeId': sitelinks_data['line1FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_1_TEXT - }, { 'feedAttributeId': sitelinks_data['line2FeedId'], 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT } ] } diff --git a/examples/adwords/v201702/optimization/get_keyword_ideas.py b/examples/adwords/v201702/optimization/get_keyword_ideas.py index 4c513de3..66ab2d5d 100755 --- a/examples/adwords/v201702/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201702/optimization/get_keyword_ideas.py @@ -45,7 +45,7 @@ def main(client): { # Language setting (optional). # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes + # https://developers.google.com/adwords/api/docs/appendix/languagecodes 'xsi_type': 'LanguageSearchParameter', 'languages': [{'id': '1000'}] }, diff --git a/googleads/adwords.py b/googleads/adwords.py index 9d3b2470..507cf02d 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -35,52 +35,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201605': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201607': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', diff --git a/googleads/common.py b/googleads/common.py index a30a28eb..2c2e6030 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -60,7 +60,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '5.2.0' +VERSION = '5.3.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' diff --git a/googleads/dfp.py b/googleads/dfp.py index e8d94280..8944b2c2 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -451,7 +451,9 @@ def WaitForReport(self, report_job): logging.debug('Report has completed successfully') return report_job_id - def DownloadReportToFile(self, report_job_id, export_format, outfile): + def DownloadReportToFile(self, report_job_id, export_format, outfile, + include_report_properties=False, + include_totals_row=None, use_gzip_compression=True): """Downloads report data and writes it to a file. The report job must be completed before calling this function. @@ -460,9 +462,23 @@ def DownloadReportToFile(self, report_job_id, export_format, outfile): report_job_id: The ID of the report job to wait for, as a string. export_format: The export format for the report file, as a string. outfile: A writeable, file-like object to write to. + include_report_properties: Whether or not to include the report + properties (e.g. network, user, date generated...) + in the generated report. + include_totals_row: Whether or not to include the totals row. + use_gzip_compression: Whether or not to use gzip compression. """ service = self._GetReportService() - report_url = service.getReportDownloadURL(report_job_id, export_format) + + if include_totals_row is None: # True unless CSV export if not specified + include_totals_row = True if export_format != 'CSV_DUMP' else False + opts = { + 'exportFormat': export_format, + 'includeReportProperties': include_report_properties, + 'includeTotalsRow': include_totals_row, + 'useGzipCompression': use_gzip_compression + } + report_url = service.getReportDownloadUrlWithOptions(report_job_id, opts) response = self.url_opener.open(report_url) while True: chunk = response.read(_CHUNK_SIZE) diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 27bf4e3f..9311c892 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -538,7 +538,7 @@ def testWaitForReport_failure(self): self.report_downloader.WaitForReport, {'id': 'obj'}) def testDownloadReportToFile(self): - report_format = 'csv' + report_format = 'CSV_DUMP' report_job_id = 't68t3278y429' report_download_url = 'http://google.com/something' report_contents = 'THIS IS YOUR REPORT!' @@ -547,13 +547,21 @@ def testDownloadReportToFile(self): fake_request.seek(0) outfile = StringIO.StringIO() - self.report_service.getReportDownloadURL.return_value = report_download_url + download_func = self.report_service.getReportDownloadUrlWithOptions + download_func.return_value = report_download_url with mock.patch('urllib2.OpenerDirector.open' if sys.version_info[0] == 2 else 'urllib.request.OpenerDirector.open') as mock_open: mock_open.return_value = fake_request self.report_downloader.DownloadReportToFile( report_job_id, report_format, outfile) + default_opts = { + 'exportFormat': report_format, + 'includeReportProperties': False, + 'includeTotalsRow': False, + 'useGzipCompression': True, + } + download_func.assert_called_once_with(report_job_id, default_opts) mock_open.assert_called_once_with(report_download_url) self.assertEqual(report_contents, outfile.getvalue()) From 1d48d00f123d21096c67adfc7a25df1387b866b0 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 20 Mar 2017 18:42:08 -0400 Subject: [PATCH 067/180] Commiting latest changes. From aad4e4cefdcdfd0c2f39820ce3dad8a10d23b71c Mon Sep 17 00:00:00 2001 From: Miguel Paolino Date: Mon, 10 Apr 2017 10:56:03 -0300 Subject: [PATCH 068/180] Replaced example shebangs so it works with virtualenvs --- examples/adwords/adwords_appengine_demo/__init__.py | 2 +- examples/adwords/adwords_appengine_demo/demo/__init__.py | 2 +- examples/adwords/adwords_appengine_demo/demo/main.py | 2 +- examples/adwords/adwords_appengine_demo/handlers/__init__.py | 2 +- examples/adwords/adwords_appengine_demo/handlers/api_handler.py | 2 +- examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py | 2 +- examples/adwords/adwords_appengine_demo/models/__init__.py | 2 +- examples/adwords/adwords_appengine_demo/models/app_user.py | 2 +- examples/adwords/adwords_appengine_demo/views/__init__.py | 2 +- .../adwords/adwords_appengine_demo/views/add_adgroup_view.py | 2 +- .../adwords/adwords_appengine_demo/views/add_campaign_view.py | 2 +- examples/adwords/adwords_appengine_demo/views/init_view.py | 2 +- .../adwords/adwords_appengine_demo/views/show_accounts_view.py | 2 +- .../adwords/adwords_appengine_demo/views/show_adgroups_view.py | 2 +- .../adwords/adwords_appengine_demo/views/show_budget_view.py | 2 +- .../adwords/adwords_appengine_demo/views/show_campaigns_view.py | 2 +- .../adwords_appengine_demo/views/show_credentials_view.py | 2 +- .../adwords/adwords_appengine_demo/views/update_budget_view.py | 2 +- .../adwords_appengine_demo/views/update_credentials_view.py | 2 +- .../create_adwords_client_with_service_account.py | 2 +- .../authentication/create_adwords_client_without_yaml.py | 2 +- examples/adwords/authentication/generate_refresh_token.py | 2 +- examples/adwords/v201607/account_management/create_account.py | 2 +- .../adwords/v201607/account_management/get_account_changes.py | 2 +- .../adwords/v201607/account_management/get_account_hierarchy.py | 2 +- .../adwords/v201607/advanced_operations/add_ad_customizer.py | 2 +- .../v201607/advanced_operations/add_ad_group_bid_modifier.py | 2 +- .../v201607/advanced_operations/add_click_to_download_ad.py | 2 +- examples/adwords/v201607/advanced_operations/add_html5_ad.py | 2 +- .../v201607/advanced_operations/add_responsive_display_ad.py | 2 +- .../advanced_operations/add_text_ad_with_upgraded_urls.py | 2 +- .../advanced_operations/create_and_attach_shared_keyword_set.py | 2 +- .../find_and_remove_criteria_from_shared_set.py | 2 +- .../v201607/advanced_operations/get_ad_group_bid_modifier.py | 2 +- .../v201607/advanced_operations/use_shared_bidding_strategy.py | 2 +- examples/adwords/v201607/basic_operations/add_ad_groups.py | 2 +- examples/adwords/v201607/basic_operations/add_campaigns.py | 2 +- .../adwords/v201607/basic_operations/add_expanded_text_ads.py | 2 +- examples/adwords/v201607/basic_operations/add_keywords.py | 2 +- examples/adwords/v201607/basic_operations/add_text_ads.py | 2 +- examples/adwords/v201607/basic_operations/get_ad_groups.py | 2 +- examples/adwords/v201607/basic_operations/get_campaigns.py | 2 +- .../adwords/v201607/basic_operations/get_campaigns_with_awql.py | 2 +- .../adwords/v201607/basic_operations/get_expanded_text_ads.py | 2 +- examples/adwords/v201607/basic_operations/get_keywords.py | 2 +- examples/adwords/v201607/basic_operations/get_text_ads.py | 2 +- examples/adwords/v201607/basic_operations/pause_ad.py | 2 +- examples/adwords/v201607/basic_operations/remove_ad.py | 2 +- examples/adwords/v201607/basic_operations/remove_ad_group.py | 2 +- examples/adwords/v201607/basic_operations/remove_campaign.py | 2 +- examples/adwords/v201607/basic_operations/remove_keyword.py | 2 +- examples/adwords/v201607/basic_operations/update_ad_group.py | 2 +- examples/adwords/v201607/basic_operations/update_campaign.py | 2 +- examples/adwords/v201607/basic_operations/update_keyword.py | 2 +- .../adwords/v201607/campaign_management/add_campaign_labels.py | 2 +- .../add_complete_campaigns_using_batch_job.py | 2 +- examples/adwords/v201607/campaign_management/add_draft.py | 2 +- examples/adwords/v201607/campaign_management/add_experiment.py | 2 +- .../add_keywords_using_incremental_batch_job.py | 2 +- examples/adwords/v201607/campaign_management/add_trial.py | 2 +- .../v201607/campaign_management/get_all_disapproved_ads.py | 2 +- .../campaign_management/get_all_disapproved_ads_with_awql.py | 2 +- .../v201607/campaign_management/get_campaigns_by_label.py | 2 +- examples/adwords/v201607/campaign_management/graduate_trial.py | 2 +- .../adwords/v201607/campaign_management/promote_experiment.py | 2 +- .../adwords/v201607/campaign_management/set_ad_parameters.py | 2 +- .../v201607/campaign_management/set_criterion_bid_modifier.py | 2 +- .../adwords/v201607/campaign_management/validate_text_ad.py | 2 +- .../adwords/v201607/error_handling/handle_partial_failures.py | 2 +- .../v201607/error_handling/handle_policy_violation_error.py | 2 +- .../extensions/add_google_my_business_location_extensions.py | 2 +- examples/adwords/v201607/extensions/add_prices.py | 2 +- examples/adwords/v201607/extensions/add_site_links.py | 2 +- .../adwords/v201607/extensions/add_site_links_using_feeds.py | 2 +- .../adwords/v201607/migration/migrate_to_extension_settings.py | 2 +- examples/adwords/v201607/misc/get_all_images_and_videos.py | 2 +- examples/adwords/v201607/misc/upload_image.py | 2 +- examples/adwords/v201607/misc/upload_media_bundle.py | 2 +- .../adwords/v201607/optimization/estimate_keyword_traffic.py | 2 +- .../get_campaign_criterion_bid_modifier_simulations.py | 2 +- .../adwords/v201607/optimization/get_keyword_bid_simulations.py | 2 +- examples/adwords/v201607/optimization/get_keyword_ideas.py | 2 +- examples/adwords/v201607/remarketing/add_audience.py | 2 +- examples/adwords/v201607/remarketing/add_conversion_tracker.py | 2 +- examples/adwords/v201607/remarketing/add_crm_based_user_list.py | 2 +- .../adwords/v201607/remarketing/add_rule_based_user_lists.py | 2 +- .../adwords/v201607/remarketing/upload_offline_conversions.py | 2 +- examples/adwords/v201607/reporting/download_criteria_report.py | 2 +- .../v201607/reporting/download_criteria_report_as_stream.py | 2 +- .../reporting/download_criteria_report_as_stream_with_awql.py | 2 +- .../v201607/reporting/download_criteria_report_as_string.py | 2 +- .../reporting/download_criteria_report_as_string_with_awql.py | 2 +- .../v201607/reporting/download_criteria_report_with_awql.py | 2 +- examples/adwords/v201607/reporting/get_report_fields.py | 2 +- examples/adwords/v201607/reporting/parallel_report_download.py | 2 +- examples/adwords/v201607/shopping/add_product_partition_tree.py | 2 +- examples/adwords/v201607/shopping/add_product_scope.py | 2 +- examples/adwords/v201607/shopping/add_shopping_campaign.py | 2 +- .../adwords/v201607/shopping/get_product_category_taxonomy.py | 2 +- .../v201607/targeting/add_campaign_targeting_criteria.py | 2 +- .../v201607/targeting/add_demographic_targeting_criteria.py | 2 +- .../v201607/targeting/get_campaign_targeting_criteria.py | 2 +- .../v201607/targeting/get_targetable_languages_and_carriers.py | 2 +- examples/adwords/v201607/targeting/lookup_location.py | 2 +- .../adwords/v201609/account_management/accept_service_link.py | 2 +- examples/adwords/v201609/account_management/create_account.py | 2 +- .../adwords/v201609/account_management/get_account_changes.py | 2 +- .../adwords/v201609/account_management/get_account_hierarchy.py | 2 +- .../adwords/v201609/advanced_operations/add_ad_customizer.py | 2 +- .../v201609/advanced_operations/add_ad_group_bid_modifier.py | 2 +- .../v201609/advanced_operations/add_click_to_download_ad.py | 2 +- .../add_expanded_text_ad_with_upgraded_urls.py | 2 +- examples/adwords/v201609/advanced_operations/add_html5_ad.py | 2 +- .../v201609/advanced_operations/add_responsive_display_ad.py | 2 +- .../v201609/advanced_operations/add_universal_app_campaign.py | 2 +- .../advanced_operations/create_and_attach_shared_keyword_set.py | 2 +- .../find_and_remove_criteria_from_shared_set.py | 2 +- .../v201609/advanced_operations/get_ad_group_bid_modifier.py | 2 +- .../v201609/advanced_operations/use_shared_bidding_strategy.py | 2 +- examples/adwords/v201609/basic_operations/add_ad_groups.py | 2 +- examples/adwords/v201609/basic_operations/add_campaigns.py | 2 +- .../adwords/v201609/basic_operations/add_expanded_text_ads.py | 2 +- examples/adwords/v201609/basic_operations/add_keywords.py | 2 +- examples/adwords/v201609/basic_operations/get_ad_groups.py | 2 +- examples/adwords/v201609/basic_operations/get_campaigns.py | 2 +- .../adwords/v201609/basic_operations/get_campaigns_with_awql.py | 2 +- .../adwords/v201609/basic_operations/get_expanded_text_ads.py | 2 +- examples/adwords/v201609/basic_operations/get_keywords.py | 2 +- examples/adwords/v201609/basic_operations/get_text_ads.py | 2 +- examples/adwords/v201609/basic_operations/pause_ad.py | 2 +- examples/adwords/v201609/basic_operations/remove_ad.py | 2 +- examples/adwords/v201609/basic_operations/remove_ad_group.py | 2 +- examples/adwords/v201609/basic_operations/remove_campaign.py | 2 +- examples/adwords/v201609/basic_operations/remove_keyword.py | 2 +- examples/adwords/v201609/basic_operations/update_ad_group.py | 2 +- examples/adwords/v201609/basic_operations/update_campaign.py | 2 +- examples/adwords/v201609/basic_operations/update_keyword.py | 2 +- .../adwords/v201609/campaign_management/add_campaign_labels.py | 2 +- .../add_complete_campaigns_using_batch_job.py | 2 +- examples/adwords/v201609/campaign_management/add_draft.py | 2 +- .../add_keywords_using_incremental_batch_job.py | 2 +- examples/adwords/v201609/campaign_management/add_trial.py | 2 +- .../v201609/campaign_management/get_all_disapproved_ads.py | 2 +- .../campaign_management/get_all_disapproved_ads_with_awql.py | 2 +- .../v201609/campaign_management/get_campaigns_by_label.py | 2 +- examples/adwords/v201609/campaign_management/graduate_trial.py | 2 +- .../adwords/v201609/campaign_management/set_ad_parameters.py | 2 +- .../v201609/campaign_management/set_criterion_bid_modifier.py | 2 +- .../adwords/v201609/campaign_management/validate_text_ad.py | 2 +- .../adwords/v201609/error_handling/handle_partial_failures.py | 2 +- .../v201609/error_handling/handle_policy_violation_error.py | 2 +- .../extensions/add_google_my_business_location_extensions.py | 2 +- examples/adwords/v201609/extensions/add_prices.py | 2 +- examples/adwords/v201609/extensions/add_site_links.py | 2 +- .../adwords/v201609/extensions/add_site_links_using_feeds.py | 2 +- .../adwords/v201609/migration/migrate_to_extension_settings.py | 2 +- examples/adwords/v201609/misc/get_all_images_and_videos.py | 2 +- examples/adwords/v201609/misc/upload_image.py | 2 +- examples/adwords/v201609/misc/upload_media_bundle.py | 2 +- .../adwords/v201609/optimization/estimate_keyword_traffic.py | 2 +- .../get_campaign_criterion_bid_modifier_simulations.py | 2 +- .../adwords/v201609/optimization/get_keyword_bid_simulations.py | 2 +- examples/adwords/v201609/optimization/get_keyword_ideas.py | 2 +- examples/adwords/v201609/remarketing/add_audience.py | 2 +- examples/adwords/v201609/remarketing/add_conversion_tracker.py | 2 +- examples/adwords/v201609/remarketing/add_crm_based_user_list.py | 2 +- .../adwords/v201609/remarketing/add_rule_based_user_lists.py | 2 +- .../v201609/remarketing/upload_offline_call_conversions.py | 2 +- .../adwords/v201609/remarketing/upload_offline_conversions.py | 2 +- examples/adwords/v201609/reporting/download_criteria_report.py | 2 +- .../v201609/reporting/download_criteria_report_as_stream.py | 2 +- .../reporting/download_criteria_report_as_stream_with_awql.py | 2 +- .../v201609/reporting/download_criteria_report_as_string.py | 2 +- .../reporting/download_criteria_report_as_string_with_awql.py | 2 +- .../v201609/reporting/download_criteria_report_with_awql.py | 2 +- examples/adwords/v201609/reporting/get_report_fields.py | 2 +- examples/adwords/v201609/reporting/parallel_report_download.py | 2 +- examples/adwords/v201609/shopping/add_product_partition_tree.py | 2 +- examples/adwords/v201609/shopping/add_product_scope.py | 2 +- examples/adwords/v201609/shopping/add_shopping_campaign.py | 2 +- .../adwords/v201609/shopping/get_product_category_taxonomy.py | 2 +- .../v201609/targeting/add_campaign_targeting_criteria.py | 2 +- .../v201609/targeting/add_demographic_targeting_criteria.py | 2 +- .../v201609/targeting/get_campaign_targeting_criteria.py | 2 +- .../v201609/targeting/get_targetable_languages_and_carriers.py | 2 +- examples/adwords/v201609/targeting/lookup_location.py | 2 +- .../adwords/v201702/account_management/accept_service_link.py | 2 +- examples/adwords/v201702/account_management/create_account.py | 2 +- .../adwords/v201702/account_management/get_account_changes.py | 2 +- .../adwords/v201702/account_management/get_account_hierarchy.py | 2 +- .../adwords/v201702/advanced_operations/add_ad_customizer.py | 2 +- .../v201702/advanced_operations/add_ad_group_bid_modifier.py | 2 +- .../v201702/advanced_operations/add_click_to_download_ad.py | 2 +- .../add_expanded_text_ad_with_upgraded_urls.py | 2 +- examples/adwords/v201702/advanced_operations/add_html5_ad.py | 2 +- .../v201702/advanced_operations/add_responsive_display_ad.py | 2 +- .../v201702/advanced_operations/add_universal_app_campaign.py | 2 +- .../advanced_operations/create_and_attach_shared_keyword_set.py | 2 +- .../find_and_remove_criteria_from_shared_set.py | 2 +- .../v201702/advanced_operations/get_ad_group_bid_modifier.py | 2 +- .../v201702/advanced_operations/use_shared_bidding_strategy.py | 2 +- examples/adwords/v201702/basic_operations/add_ad_groups.py | 2 +- examples/adwords/v201702/basic_operations/add_campaigns.py | 2 +- .../adwords/v201702/basic_operations/add_expanded_text_ads.py | 2 +- examples/adwords/v201702/basic_operations/add_keywords.py | 2 +- examples/adwords/v201702/basic_operations/get_ad_groups.py | 2 +- examples/adwords/v201702/basic_operations/get_campaigns.py | 2 +- .../adwords/v201702/basic_operations/get_campaigns_with_awql.py | 2 +- .../adwords/v201702/basic_operations/get_expanded_text_ads.py | 2 +- examples/adwords/v201702/basic_operations/get_keywords.py | 2 +- examples/adwords/v201702/basic_operations/get_text_ads.py | 2 +- examples/adwords/v201702/basic_operations/pause_ad.py | 2 +- examples/adwords/v201702/basic_operations/remove_ad.py | 2 +- examples/adwords/v201702/basic_operations/remove_ad_group.py | 2 +- examples/adwords/v201702/basic_operations/remove_campaign.py | 2 +- examples/adwords/v201702/basic_operations/remove_keyword.py | 2 +- examples/adwords/v201702/basic_operations/update_ad_group.py | 2 +- examples/adwords/v201702/basic_operations/update_campaign.py | 2 +- examples/adwords/v201702/basic_operations/update_keyword.py | 2 +- .../adwords/v201702/campaign_management/add_campaign_labels.py | 2 +- .../add_complete_campaigns_using_batch_job.py | 2 +- examples/adwords/v201702/campaign_management/add_draft.py | 2 +- .../add_keywords_using_incremental_batch_job.py | 2 +- examples/adwords/v201702/campaign_management/add_trial.py | 2 +- .../v201702/campaign_management/get_all_disapproved_ads.py | 2 +- .../campaign_management/get_all_disapproved_ads_with_awql.py | 2 +- .../v201702/campaign_management/get_campaigns_by_label.py | 2 +- examples/adwords/v201702/campaign_management/graduate_trial.py | 2 +- .../adwords/v201702/campaign_management/set_ad_parameters.py | 2 +- .../v201702/campaign_management/set_criterion_bid_modifier.py | 2 +- .../adwords/v201702/campaign_management/validate_text_ad.py | 2 +- .../adwords/v201702/error_handling/handle_partial_failures.py | 2 +- .../v201702/error_handling/handle_policy_violation_error.py | 2 +- .../extensions/add_google_my_business_location_extensions.py | 2 +- examples/adwords/v201702/extensions/add_prices.py | 2 +- examples/adwords/v201702/extensions/add_site_links.py | 2 +- .../adwords/v201702/extensions/add_site_links_using_feeds.py | 2 +- .../adwords/v201702/migration/migrate_to_extension_settings.py | 2 +- examples/adwords/v201702/misc/get_all_images_and_videos.py | 2 +- examples/adwords/v201702/misc/upload_image.py | 2 +- examples/adwords/v201702/misc/upload_media_bundle.py | 2 +- .../adwords/v201702/optimization/estimate_keyword_traffic.py | 2 +- .../get_campaign_criterion_bid_modifier_simulations.py | 2 +- .../adwords/v201702/optimization/get_keyword_bid_simulations.py | 2 +- examples/adwords/v201702/optimization/get_keyword_ideas.py | 2 +- examples/adwords/v201702/remarketing/add_audience.py | 2 +- examples/adwords/v201702/remarketing/add_conversion_tracker.py | 2 +- examples/adwords/v201702/remarketing/add_crm_based_user_list.py | 2 +- .../adwords/v201702/remarketing/add_rule_based_user_lists.py | 2 +- .../v201702/remarketing/upload_offline_call_conversions.py | 2 +- .../adwords/v201702/remarketing/upload_offline_conversions.py | 2 +- .../reporting/download_criteria_report_as_stream_with_awql.py | 2 +- .../download_criteria_report_as_stream_with_selector.py | 2 +- .../reporting/download_criteria_report_as_string_with_awql.py | 2 +- .../download_criteria_report_as_string_with_selector.py | 2 +- .../v201702/reporting/download_criteria_report_with_awql.py | 2 +- .../v201702/reporting/download_criteria_report_with_selector.py | 2 +- examples/adwords/v201702/reporting/get_report_fields.py | 2 +- examples/adwords/v201702/reporting/parallel_report_download.py | 2 +- examples/adwords/v201702/shopping/add_product_partition_tree.py | 2 +- examples/adwords/v201702/shopping/add_product_scope.py | 2 +- examples/adwords/v201702/shopping/add_shopping_campaign.py | 2 +- .../v201702/shopping/add_shopping_campaign_for_showcase_ads.py | 2 +- .../adwords/v201702/shopping/get_product_category_taxonomy.py | 2 +- .../v201702/targeting/add_campaign_targeting_criteria.py | 2 +- .../v201702/targeting/add_demographic_targeting_criteria.py | 2 +- .../v201702/targeting/get_campaign_targeting_criteria.py | 2 +- .../v201702/targeting/get_targetable_languages_and_carriers.py | 2 +- examples/adwords/v201702/targeting/lookup_location.py | 2 +- .../authentication/create_dfp_client_with_service_account.py | 2 +- examples/dfp/authentication/create_dfp_client_without_yaml.py | 2 +- examples/dfp/authentication/generate_refresh_token.py | 2 +- examples/dfp/v201608/activity_group_service/__init__.py | 2 +- .../v201608/activity_group_service/create_activity_groups.py | 2 +- .../activity_group_service/get_active_activity_groups.py | 2 +- .../v201608/activity_group_service/get_all_activity_groups.py | 2 +- .../v201608/activity_group_service/update_activity_groups.py | 2 +- examples/dfp/v201608/activity_service/__init__.py | 2 +- examples/dfp/v201608/activity_service/create_activities.py | 2 +- examples/dfp/v201608/activity_service/get_active_activities.py | 2 +- examples/dfp/v201608/activity_service/get_all_activities.py | 2 +- examples/dfp/v201608/activity_service/update_activities.py | 2 +- examples/dfp/v201608/audience_segment_service/__init__.py | 2 +- .../audience_segment_service/create_audience_segments.py | 2 +- .../audience_segment_service/get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../audience_segment_service/update_audience_segments.py | 2 +- examples/dfp/v201608/base_rate_service/__init__.py | 2 +- .../dfp/v201608/base_rate_service/create_product_base_rates.py | 2 +- .../base_rate_service/create_product_template_base_rates.py | 2 +- examples/dfp/v201608/base_rate_service/get_all_base_rates.py | 2 +- .../v201608/base_rate_service/get_base_rates_for_rate_card.py | 2 +- examples/dfp/v201608/base_rate_service/update_base_rates.py | 2 +- examples/dfp/v201608/company_service/__init__.py | 2 +- examples/dfp/v201608/company_service/create_companies.py | 2 +- examples/dfp/v201608/company_service/get_advertisers.py | 2 +- examples/dfp/v201608/company_service/get_all_companies.py | 2 +- examples/dfp/v201608/company_service/update_companies.py | 2 +- examples/dfp/v201608/contact_service/__init__.py | 2 +- examples/dfp/v201608/contact_service/create_contacts.py | 2 +- examples/dfp/v201608/contact_service/get_all_contacts.py | 2 +- examples/dfp/v201608/contact_service/get_uninvited_contacts.py | 2 +- examples/dfp/v201608/contact_service/update_contacts.py | 2 +- .../v201608/content_metadata_key_hierarchy_service/__init__.py | 2 +- .../create_content_metadata_key_hierarchies.py | 2 +- .../delete_content_metadata_key_hierarchies.py | 2 +- .../get_all_content_metadata_key_hierarchies.py | 2 +- .../update_content_metadata_key_hierarchies.py | 2 +- examples/dfp/v201608/content_service/__init__.py | 2 +- examples/dfp/v201608/content_service/get_all_content.py | 2 +- examples/dfp/v201608/creative_service/__init__.py | 2 +- .../v201608/creative_service/create_creative_from_template.py | 2 +- examples/dfp/v201608/creative_service/create_creatives.py | 2 +- examples/dfp/v201608/creative_service/create_custom_creative.py | 2 +- examples/dfp/v201608/creative_service/create_native_creative.py | 2 +- examples/dfp/v201608/creative_service/get_all_creatives.py | 2 +- examples/dfp/v201608/creative_service/get_image_creatives.py | 2 +- examples/dfp/v201608/creative_service/update_creatives.py | 2 +- examples/dfp/v201608/creative_set_service/__init__.py | 2 +- .../creative_set_service/associate_creative_set_to_line_item.py | 2 +- .../dfp/v201608/creative_set_service/create_creative_set.py | 2 +- .../dfp/v201608/creative_set_service/get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../dfp/v201608/creative_set_service/update_creative_set.py | 2 +- examples/dfp/v201608/creative_template_service/__init__.py | 2 +- .../creative_template_service/get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../creative_wrapper_service/create_creative_wrappers.py | 2 +- .../creative_wrapper_service/deactivate_creative_wrapper.py | 2 +- .../creative_wrapper_service/get_active_creative_wrappers.py | 2 +- .../creative_wrapper_service/get_all_creative_wrappers.py | 2 +- .../creative_wrapper_service/update_creative_wrappers.py | 2 +- examples/dfp/v201608/custom_field_service/__init__.py | 2 +- .../v201608/custom_field_service/create_custom_field_options.py | 2 +- .../dfp/v201608/custom_field_service/create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../dfp/v201608/custom_field_service/get_all_custom_fields.py | 2 +- .../custom_field_service/get_custom_fields_for_line_items.py | 2 +- .../custom_field_service/set_line_item_custom_field_value.py | 2 +- .../dfp/v201608/custom_field_service/update_custom_fields.py | 2 +- examples/dfp/v201608/custom_targeting_service/__init__.py | 2 +- .../create_custom_targeting_keys_and_values.py | 2 +- .../custom_targeting_service/delete_custom_targeting_keys.py | 2 +- .../custom_targeting_service/delete_custom_targeting_values.py | 2 +- .../get_all_custom_targeting_keys_and_values.py | 2 +- .../get_predefined_custom_targeting_keys_and_values.py | 2 +- .../custom_targeting_service/update_custom_targeting_keys.py | 2 +- .../custom_targeting_service/update_custom_targeting_values.py | 2 +- examples/dfp/v201608/exchange_rate_service/__init__.py | 2 +- .../dfp/v201608/exchange_rate_service/create_exchange_rates.py | 2 +- .../dfp/v201608/exchange_rate_service/get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../dfp/v201608/exchange_rate_service/update_exchange_rates.py | 2 +- .../dfp/v201608/forecast_service/get_availability_forecast.py | 2 +- .../forecast_service/get_availability_forecast_for_line_item.py | 2 +- .../forecast_service/get_delivery_forecast_for_line_items.py | 2 +- examples/dfp/v201608/inventory_service/__init__.py | 2 +- examples/dfp/v201608/inventory_service/archive_ad_units.py | 2 +- examples/dfp/v201608/inventory_service/create_ad_units.py | 2 +- examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py | 2 +- examples/dfp/v201608/inventory_service/get_all_ad_units.py | 2 +- examples/dfp/v201608/inventory_service/update_ad_units.py | 2 +- examples/dfp/v201608/label_service/__init__.py | 2 +- examples/dfp/v201608/label_service/create_labels.py | 2 +- examples/dfp/v201608/label_service/deactivate_labels.py | 2 +- examples/dfp/v201608/label_service/get_active_labels.py | 2 +- examples/dfp/v201608/label_service/get_all_labels.py | 2 +- examples/dfp/v201608/label_service/update_labels.py | 2 +- .../v201608/line_item_creative_association_service/__init__.py | 2 +- .../line_item_creative_association_service/create_licas.py | 2 +- .../line_item_creative_association_service/deactivate_licas.py | 2 +- .../line_item_creative_association_service/get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../line_item_creative_association_service/update_licas.py | 2 +- examples/dfp/v201608/line_item_service/__init__.py | 2 +- examples/dfp/v201608/line_item_service/activate_line_items.py | 2 +- examples/dfp/v201608/line_item_service/create_line_items.py | 2 +- .../dfp/v201608/line_item_service/create_video_line_item.py | 2 +- examples/dfp/v201608/line_item_service/get_all_line_items.py | 2 +- .../line_item_service/get_line_items_that_need_creatives.py | 2 +- .../line_item_service/get_recently_updated_line_items.py | 2 +- .../dfp/v201608/line_item_service/target_custom_criteria.py | 2 +- examples/dfp/v201608/line_item_service/update_line_items.py | 2 +- examples/dfp/v201608/network_service/__init__.py | 2 +- examples/dfp/v201608/network_service/get_all_networks.py | 2 +- examples/dfp/v201608/network_service/make_test_network.py | 2 +- examples/dfp/v201608/order_service/__init__.py | 2 +- examples/dfp/v201608/order_service/approve_orders.py | 2 +- examples/dfp/v201608/order_service/create_orders.py | 2 +- examples/dfp/v201608/order_service/get_all_orders.py | 2 +- examples/dfp/v201608/order_service/get_orders_starting_soon.py | 2 +- examples/dfp/v201608/order_service/update_orders.py | 2 +- examples/dfp/v201608/package_service/get_all_packages.py | 2 +- .../dfp/v201608/package_service/get_in_progress_packages.py | 2 +- examples/dfp/v201608/placement_service/create_placements.py | 2 +- examples/dfp/v201608/placement_service/deactivate_placements.py | 2 +- examples/dfp/v201608/placement_service/get_active_placements.py | 2 +- examples/dfp/v201608/placement_service/get_all_placements.py | 2 +- examples/dfp/v201608/placement_service/update_placements.py | 2 +- examples/dfp/v201608/premium_rate_service/__init__.py | 2 +- .../dfp/v201608/premium_rate_service/create_premium_rates.py | 2 +- .../dfp/v201608/premium_rate_service/get_all_premium_rates.py | 2 +- .../premium_rate_service/get_premium_rates_for_rate_card.py | 2 +- .../dfp/v201608/premium_rate_service/update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 2 +- .../get_product_package_items_for_product_package.py | 2 +- .../product_package_service/get_active_product_packages.py | 2 +- .../v201608/product_package_service/get_all_product_packages.py | 2 +- examples/dfp/v201608/product_service/__init__.py | 2 +- .../create_programmatic_products_for_non_sales_management.py | 2 +- examples/dfp/v201608/product_service/get_all_products.py | 2 +- .../product_service/get_products_for_product_template.py | 2 +- .../publish_programmatic_products_to_marketplace.py | 2 +- examples/dfp/v201608/product_service/update_products.py | 2 +- examples/dfp/v201608/product_template_service/__init__.py | 2 +- .../product_template_service/activate_product_templates.py | 2 +- .../product_template_service/create_product_templates.py | 2 +- .../create_programmatic_product_templates.py | 2 +- .../product_template_service/get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../product_template_service/update_product_templates.py | 2 +- examples/dfp/v201608/proposal_line_item_service/__init__.py | 2 +- .../proposal_line_item_service/archive_proposal_line_items.py | 2 +- .../create_programmatic_proposal_line_items.py | 2 +- ...programmatic_proposal_line_items_for_non_sales_management.py | 2 +- .../proposal_line_item_service/create_proposal_line_items.py | 2 +- .../proposal_line_item_service/get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../proposal_line_item_service/update_proposal_line_items.py | 2 +- examples/dfp/v201608/proposal_service/__init__.py | 2 +- .../v201608/proposal_service/create_programmatic_proposals.py | 2 +- .../create_programmatic_proposals_for_non_sales_management.py | 2 +- examples/dfp/v201608/proposal_service/create_proposals.py | 2 +- examples/dfp/v201608/proposal_service/get_all_proposals.py | 2 +- .../dfp/v201608/proposal_service/get_marketplace_comments.py | 2 +- .../v201608/proposal_service/get_proposals_pending_approval.py | 2 +- .../dfp/v201608/proposal_service/request_buyers_acceptance.py | 2 +- .../v201608/proposal_service/submit_proposals_for_approval.py | 2 +- examples/dfp/v201608/proposal_service/update_proposals.py | 2 +- .../dfp/v201608/publisher_query_language_service/__init__.py | 2 +- .../publisher_query_language_service/fetch_match_tables.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- examples/dfp/v201608/rate_card_service/__init__.py | 2 +- examples/dfp/v201608/rate_card_service/get_all_rate_cards.py | 2 +- .../dfp/v201608/rate_card_service/get_marketplace_rate_cards.py | 2 +- ...econciliation_line_item_reports_for_reconciliation_report.py | 2 +- ...et_reconciliation_order_reports_for_reconciliation_report.py | 2 +- .../get_reconciliation_report_rows_for_reconciliation_report.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- .../get_reconciliation_report_for_last_billing_period.py | 2 +- examples/dfp/v201608/report_service/__init__.py | 2 +- examples/dfp/v201608/report_service/run_delivery_report.py | 2 +- examples/dfp/v201608/report_service/run_inventory_report.py | 2 +- examples/dfp/v201608/report_service/run_reach_report.py | 2 +- .../dfp/v201608/report_service/run_report_with_custom_fields.py | 2 +- examples/dfp/v201608/report_service/run_sales_report.py | 2 +- examples/dfp/v201608/report_service/run_saved_query.py | 2 +- examples/dfp/v201608/suggested_ad_unit_service/__init__.py | 2 +- .../suggested_ad_unit_service/approve_all_suggested_ad_units.py | 2 +- .../suggested_ad_unit_service/get_all_suggested_ad_units.py | 2 +- .../get_highly_requested_suggested_ad_units.py | 2 +- examples/dfp/v201608/team_service/__init__.py | 2 +- examples/dfp/v201608/team_service/create_teams.py | 2 +- examples/dfp/v201608/team_service/get_all_teams.py | 2 +- examples/dfp/v201608/team_service/update_teams.py | 2 +- examples/dfp/v201608/user_service/__init__.py | 2 +- examples/dfp/v201608/user_service/create_users.py | 2 +- examples/dfp/v201608/user_service/deactivate_users.py | 2 +- examples/dfp/v201608/user_service/get_all_roles.py | 2 +- examples/dfp/v201608/user_service/get_all_users.py | 2 +- examples/dfp/v201608/user_service/get_user_by_email_address.py | 2 +- examples/dfp/v201608/user_service/update_users.py | 2 +- examples/dfp/v201608/user_team_association_service/__init__.py | 2 +- .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- examples/dfp/v201608/workflow_request_service/__init__.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../workflow_request_service/get_workflow_approval_requests.py | 2 +- .../get_workflow_external_condition_requests.py | 2 +- .../trigger_workflow_external_condition_requests.py | 2 +- examples/dfp/v201611/activity_group_service/__init__.py | 2 +- .../v201611/activity_group_service/create_activity_groups.py | 2 +- .../activity_group_service/get_active_activity_groups.py | 2 +- .../v201611/activity_group_service/get_all_activity_groups.py | 2 +- .../v201611/activity_group_service/update_activity_groups.py | 2 +- examples/dfp/v201611/activity_service/__init__.py | 2 +- examples/dfp/v201611/activity_service/create_activities.py | 2 +- examples/dfp/v201611/activity_service/get_active_activities.py | 2 +- examples/dfp/v201611/activity_service/get_all_activities.py | 2 +- examples/dfp/v201611/activity_service/update_activities.py | 2 +- examples/dfp/v201611/audience_segment_service/__init__.py | 2 +- .../audience_segment_service/create_audience_segments.py | 2 +- .../audience_segment_service/get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../audience_segment_service/update_audience_segments.py | 2 +- examples/dfp/v201611/base_rate_service/__init__.py | 2 +- .../dfp/v201611/base_rate_service/create_product_base_rates.py | 2 +- .../base_rate_service/create_product_template_base_rates.py | 2 +- examples/dfp/v201611/base_rate_service/get_all_base_rates.py | 2 +- .../v201611/base_rate_service/get_base_rates_for_rate_card.py | 2 +- examples/dfp/v201611/base_rate_service/update_base_rates.py | 2 +- examples/dfp/v201611/company_service/__init__.py | 2 +- examples/dfp/v201611/company_service/create_companies.py | 2 +- examples/dfp/v201611/company_service/get_advertisers.py | 2 +- examples/dfp/v201611/company_service/get_all_companies.py | 2 +- examples/dfp/v201611/company_service/update_companies.py | 2 +- examples/dfp/v201611/contact_service/__init__.py | 2 +- examples/dfp/v201611/contact_service/create_contacts.py | 2 +- examples/dfp/v201611/contact_service/get_all_contacts.py | 2 +- examples/dfp/v201611/contact_service/get_uninvited_contacts.py | 2 +- examples/dfp/v201611/contact_service/update_contacts.py | 2 +- .../v201611/content_metadata_key_hierarchy_service/__init__.py | 2 +- .../create_content_metadata_key_hierarchies.py | 2 +- .../delete_content_metadata_key_hierarchies.py | 2 +- .../get_all_content_metadata_key_hierarchies.py | 2 +- .../update_content_metadata_key_hierarchies.py | 2 +- examples/dfp/v201611/content_service/__init__.py | 2 +- examples/dfp/v201611/content_service/get_all_content.py | 2 +- examples/dfp/v201611/creative_service/__init__.py | 2 +- .../v201611/creative_service/create_creative_from_template.py | 2 +- examples/dfp/v201611/creative_service/create_creatives.py | 2 +- examples/dfp/v201611/creative_service/create_custom_creative.py | 2 +- examples/dfp/v201611/creative_service/create_native_creative.py | 2 +- examples/dfp/v201611/creative_service/get_all_creatives.py | 2 +- examples/dfp/v201611/creative_service/get_image_creatives.py | 2 +- examples/dfp/v201611/creative_service/update_creatives.py | 2 +- examples/dfp/v201611/creative_set_service/__init__.py | 2 +- .../creative_set_service/associate_creative_set_to_line_item.py | 2 +- .../dfp/v201611/creative_set_service/create_creative_set.py | 2 +- .../dfp/v201611/creative_set_service/get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../dfp/v201611/creative_set_service/update_creative_set.py | 2 +- examples/dfp/v201611/creative_template_service/__init__.py | 2 +- .../creative_template_service/get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../creative_wrapper_service/create_creative_wrappers.py | 2 +- .../creative_wrapper_service/deactivate_creative_wrapper.py | 2 +- .../creative_wrapper_service/get_active_creative_wrappers.py | 2 +- .../creative_wrapper_service/get_all_creative_wrappers.py | 2 +- .../creative_wrapper_service/update_creative_wrappers.py | 2 +- examples/dfp/v201611/custom_field_service/__init__.py | 2 +- .../v201611/custom_field_service/create_custom_field_options.py | 2 +- .../dfp/v201611/custom_field_service/create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../dfp/v201611/custom_field_service/get_all_custom_fields.py | 2 +- .../custom_field_service/get_custom_fields_for_line_items.py | 2 +- .../custom_field_service/set_line_item_custom_field_value.py | 2 +- .../dfp/v201611/custom_field_service/update_custom_fields.py | 2 +- examples/dfp/v201611/custom_targeting_service/__init__.py | 2 +- .../create_custom_targeting_keys_and_values.py | 2 +- .../custom_targeting_service/delete_custom_targeting_keys.py | 2 +- .../custom_targeting_service/delete_custom_targeting_values.py | 2 +- .../get_all_custom_targeting_keys_and_values.py | 2 +- .../get_predefined_custom_targeting_keys_and_values.py | 2 +- .../custom_targeting_service/update_custom_targeting_keys.py | 2 +- .../custom_targeting_service/update_custom_targeting_values.py | 2 +- examples/dfp/v201611/exchange_rate_service/__init__.py | 2 +- .../dfp/v201611/exchange_rate_service/create_exchange_rates.py | 2 +- .../dfp/v201611/exchange_rate_service/get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../dfp/v201611/exchange_rate_service/update_exchange_rates.py | 2 +- .../dfp/v201611/forecast_service/get_availability_forecast.py | 2 +- .../forecast_service/get_availability_forecast_for_line_item.py | 2 +- .../forecast_service/get_delivery_forecast_for_line_items.py | 2 +- examples/dfp/v201611/inventory_service/__init__.py | 2 +- examples/dfp/v201611/inventory_service/archive_ad_units.py | 2 +- examples/dfp/v201611/inventory_service/create_ad_units.py | 2 +- examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py | 2 +- examples/dfp/v201611/inventory_service/get_all_ad_units.py | 2 +- examples/dfp/v201611/inventory_service/update_ad_units.py | 2 +- examples/dfp/v201611/label_service/__init__.py | 2 +- examples/dfp/v201611/label_service/create_labels.py | 2 +- examples/dfp/v201611/label_service/deactivate_labels.py | 2 +- examples/dfp/v201611/label_service/get_active_labels.py | 2 +- examples/dfp/v201611/label_service/get_all_labels.py | 2 +- examples/dfp/v201611/label_service/update_labels.py | 2 +- .../v201611/line_item_creative_association_service/__init__.py | 2 +- .../line_item_creative_association_service/create_licas.py | 2 +- .../line_item_creative_association_service/deactivate_licas.py | 2 +- .../line_item_creative_association_service/get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../line_item_creative_association_service/update_licas.py | 2 +- examples/dfp/v201611/line_item_service/__init__.py | 2 +- examples/dfp/v201611/line_item_service/activate_line_items.py | 2 +- examples/dfp/v201611/line_item_service/create_line_items.py | 2 +- .../dfp/v201611/line_item_service/create_video_line_item.py | 2 +- examples/dfp/v201611/line_item_service/get_all_line_items.py | 2 +- .../line_item_service/get_line_items_that_need_creatives.py | 2 +- .../line_item_service/get_recently_updated_line_items.py | 2 +- .../dfp/v201611/line_item_service/target_custom_criteria.py | 2 +- examples/dfp/v201611/line_item_service/update_line_items.py | 2 +- examples/dfp/v201611/network_service/__init__.py | 2 +- examples/dfp/v201611/network_service/get_all_networks.py | 2 +- examples/dfp/v201611/network_service/make_test_network.py | 2 +- examples/dfp/v201611/order_service/__init__.py | 2 +- examples/dfp/v201611/order_service/approve_orders.py | 2 +- examples/dfp/v201611/order_service/create_orders.py | 2 +- examples/dfp/v201611/order_service/get_all_orders.py | 2 +- examples/dfp/v201611/order_service/get_orders_starting_soon.py | 2 +- examples/dfp/v201611/order_service/update_orders.py | 2 +- examples/dfp/v201611/package_service/get_all_packages.py | 2 +- .../dfp/v201611/package_service/get_in_progress_packages.py | 2 +- examples/dfp/v201611/placement_service/create_placements.py | 2 +- examples/dfp/v201611/placement_service/deactivate_placements.py | 2 +- examples/dfp/v201611/placement_service/get_active_placements.py | 2 +- examples/dfp/v201611/placement_service/get_all_placements.py | 2 +- examples/dfp/v201611/placement_service/update_placements.py | 2 +- examples/dfp/v201611/premium_rate_service/__init__.py | 2 +- .../dfp/v201611/premium_rate_service/create_premium_rates.py | 2 +- .../dfp/v201611/premium_rate_service/get_all_premium_rates.py | 2 +- .../premium_rate_service/get_premium_rates_for_rate_card.py | 2 +- .../dfp/v201611/premium_rate_service/update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 2 +- .../get_product_package_items_for_product_package.py | 2 +- .../product_package_service/get_active_product_packages.py | 2 +- .../v201611/product_package_service/get_all_product_packages.py | 2 +- examples/dfp/v201611/product_service/__init__.py | 2 +- .../create_programmatic_products_for_non_sales_management.py | 2 +- examples/dfp/v201611/product_service/get_all_products.py | 2 +- .../product_service/get_products_for_product_template.py | 2 +- .../publish_programmatic_products_to_marketplace.py | 2 +- examples/dfp/v201611/product_service/update_products.py | 2 +- examples/dfp/v201611/product_template_service/__init__.py | 2 +- .../product_template_service/activate_product_templates.py | 2 +- .../product_template_service/create_product_templates.py | 2 +- .../create_programmatic_product_templates.py | 2 +- .../product_template_service/get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../product_template_service/update_product_templates.py | 2 +- examples/dfp/v201611/proposal_line_item_service/__init__.py | 2 +- .../proposal_line_item_service/archive_proposal_line_items.py | 2 +- .../create_programmatic_proposal_line_items.py | 2 +- ...programmatic_proposal_line_items_for_non_sales_management.py | 2 +- .../proposal_line_item_service/create_proposal_line_items.py | 2 +- .../proposal_line_item_service/get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../proposal_line_item_service/update_proposal_line_items.py | 2 +- examples/dfp/v201611/proposal_service/__init__.py | 2 +- .../v201611/proposal_service/create_programmatic_proposals.py | 2 +- .../create_programmatic_proposals_for_non_sales_management.py | 2 +- examples/dfp/v201611/proposal_service/create_proposals.py | 2 +- examples/dfp/v201611/proposal_service/get_all_proposals.py | 2 +- .../dfp/v201611/proposal_service/get_marketplace_comments.py | 2 +- .../v201611/proposal_service/get_proposals_pending_approval.py | 2 +- .../dfp/v201611/proposal_service/request_buyers_acceptance.py | 2 +- .../v201611/proposal_service/submit_proposals_for_approval.py | 2 +- examples/dfp/v201611/proposal_service/update_proposals.py | 2 +- .../dfp/v201611/publisher_query_language_service/__init__.py | 2 +- .../publisher_query_language_service/fetch_match_tables.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- examples/dfp/v201611/rate_card_service/__init__.py | 2 +- examples/dfp/v201611/rate_card_service/get_all_rate_cards.py | 2 +- .../dfp/v201611/rate_card_service/get_marketplace_rate_cards.py | 2 +- ...econciliation_line_item_reports_for_reconciliation_report.py | 2 +- ...et_reconciliation_order_reports_for_reconciliation_report.py | 2 +- .../get_reconciliation_report_rows_for_reconciliation_report.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- .../get_reconciliation_report_for_last_billing_period.py | 2 +- examples/dfp/v201611/report_service/__init__.py | 2 +- examples/dfp/v201611/report_service/run_delivery_report.py | 2 +- examples/dfp/v201611/report_service/run_inventory_report.py | 2 +- examples/dfp/v201611/report_service/run_reach_report.py | 2 +- .../dfp/v201611/report_service/run_report_with_custom_fields.py | 2 +- examples/dfp/v201611/report_service/run_sales_report.py | 2 +- examples/dfp/v201611/report_service/run_saved_query.py | 2 +- examples/dfp/v201611/suggested_ad_unit_service/__init__.py | 2 +- .../suggested_ad_unit_service/approve_all_suggested_ad_units.py | 2 +- .../suggested_ad_unit_service/get_all_suggested_ad_units.py | 2 +- .../get_highly_requested_suggested_ad_units.py | 2 +- examples/dfp/v201611/team_service/__init__.py | 2 +- examples/dfp/v201611/team_service/create_teams.py | 2 +- examples/dfp/v201611/team_service/get_all_teams.py | 2 +- examples/dfp/v201611/team_service/update_teams.py | 2 +- examples/dfp/v201611/user_service/__init__.py | 2 +- examples/dfp/v201611/user_service/create_users.py | 2 +- examples/dfp/v201611/user_service/deactivate_users.py | 2 +- examples/dfp/v201611/user_service/get_all_roles.py | 2 +- examples/dfp/v201611/user_service/get_all_users.py | 2 +- examples/dfp/v201611/user_service/get_user_by_email_address.py | 2 +- examples/dfp/v201611/user_service/update_users.py | 2 +- examples/dfp/v201611/user_team_association_service/__init__.py | 2 +- .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- examples/dfp/v201611/workflow_request_service/__init__.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../workflow_request_service/get_workflow_approval_requests.py | 2 +- .../get_workflow_external_condition_requests.py | 2 +- .../trigger_workflow_external_condition_requests.py | 2 +- examples/dfp/v201702/activity_group_service/__init__.py | 2 +- .../v201702/activity_group_service/create_activity_groups.py | 2 +- .../activity_group_service/get_active_activity_groups.py | 2 +- .../v201702/activity_group_service/get_all_activity_groups.py | 2 +- .../v201702/activity_group_service/update_activity_groups.py | 2 +- examples/dfp/v201702/activity_service/__init__.py | 2 +- examples/dfp/v201702/activity_service/create_activities.py | 2 +- examples/dfp/v201702/activity_service/get_active_activities.py | 2 +- examples/dfp/v201702/activity_service/get_all_activities.py | 2 +- examples/dfp/v201702/activity_service/update_activities.py | 2 +- examples/dfp/v201702/audience_segment_service/__init__.py | 2 +- .../audience_segment_service/create_audience_segments.py | 2 +- .../audience_segment_service/get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../audience_segment_service/update_audience_segments.py | 2 +- examples/dfp/v201702/base_rate_service/__init__.py | 2 +- .../dfp/v201702/base_rate_service/create_product_base_rates.py | 2 +- .../base_rate_service/create_product_template_base_rates.py | 2 +- examples/dfp/v201702/base_rate_service/get_all_base_rates.py | 2 +- .../v201702/base_rate_service/get_base_rates_for_rate_card.py | 2 +- examples/dfp/v201702/base_rate_service/update_base_rates.py | 2 +- examples/dfp/v201702/company_service/__init__.py | 2 +- examples/dfp/v201702/company_service/create_companies.py | 2 +- examples/dfp/v201702/company_service/get_advertisers.py | 2 +- examples/dfp/v201702/company_service/get_all_companies.py | 2 +- examples/dfp/v201702/company_service/update_companies.py | 2 +- examples/dfp/v201702/contact_service/__init__.py | 2 +- examples/dfp/v201702/contact_service/create_contacts.py | 2 +- examples/dfp/v201702/contact_service/get_all_contacts.py | 2 +- examples/dfp/v201702/contact_service/get_uninvited_contacts.py | 2 +- examples/dfp/v201702/contact_service/update_contacts.py | 2 +- .../v201702/content_metadata_key_hierarchy_service/__init__.py | 2 +- .../create_content_metadata_key_hierarchies.py | 2 +- .../delete_content_metadata_key_hierarchies.py | 2 +- .../get_all_content_metadata_key_hierarchies.py | 2 +- .../update_content_metadata_key_hierarchies.py | 2 +- examples/dfp/v201702/content_service/__init__.py | 2 +- examples/dfp/v201702/content_service/get_all_content.py | 2 +- examples/dfp/v201702/creative_service/__init__.py | 2 +- .../v201702/creative_service/create_creative_from_template.py | 2 +- examples/dfp/v201702/creative_service/create_creatives.py | 2 +- examples/dfp/v201702/creative_service/create_custom_creative.py | 2 +- examples/dfp/v201702/creative_service/create_native_creative.py | 2 +- examples/dfp/v201702/creative_service/get_all_creatives.py | 2 +- examples/dfp/v201702/creative_service/get_image_creatives.py | 2 +- examples/dfp/v201702/creative_service/update_creatives.py | 2 +- examples/dfp/v201702/creative_set_service/__init__.py | 2 +- .../creative_set_service/associate_creative_set_to_line_item.py | 2 +- .../dfp/v201702/creative_set_service/create_creative_set.py | 2 +- .../dfp/v201702/creative_set_service/get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../dfp/v201702/creative_set_service/update_creative_set.py | 2 +- examples/dfp/v201702/creative_template_service/__init__.py | 2 +- .../creative_template_service/get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../creative_wrapper_service/create_creative_wrappers.py | 2 +- .../creative_wrapper_service/deactivate_creative_wrapper.py | 2 +- .../creative_wrapper_service/get_active_creative_wrappers.py | 2 +- .../creative_wrapper_service/get_all_creative_wrappers.py | 2 +- .../creative_wrapper_service/update_creative_wrappers.py | 2 +- examples/dfp/v201702/custom_field_service/__init__.py | 2 +- .../v201702/custom_field_service/create_custom_field_options.py | 2 +- .../dfp/v201702/custom_field_service/create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../dfp/v201702/custom_field_service/get_all_custom_fields.py | 2 +- .../custom_field_service/get_custom_fields_for_line_items.py | 2 +- .../custom_field_service/set_line_item_custom_field_value.py | 2 +- .../dfp/v201702/custom_field_service/update_custom_fields.py | 2 +- examples/dfp/v201702/custom_targeting_service/__init__.py | 2 +- .../create_custom_targeting_keys_and_values.py | 2 +- .../custom_targeting_service/delete_custom_targeting_keys.py | 2 +- .../custom_targeting_service/delete_custom_targeting_values.py | 2 +- .../get_all_custom_targeting_keys_and_values.py | 2 +- .../get_predefined_custom_targeting_keys_and_values.py | 2 +- .../custom_targeting_service/update_custom_targeting_keys.py | 2 +- .../custom_targeting_service/update_custom_targeting_values.py | 2 +- examples/dfp/v201702/exchange_rate_service/__init__.py | 2 +- .../dfp/v201702/exchange_rate_service/create_exchange_rates.py | 2 +- .../dfp/v201702/exchange_rate_service/get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../dfp/v201702/exchange_rate_service/update_exchange_rates.py | 2 +- .../dfp/v201702/forecast_service/get_availability_forecast.py | 2 +- .../forecast_service/get_availability_forecast_for_line_item.py | 2 +- .../forecast_service/get_delivery_forecast_for_line_items.py | 2 +- examples/dfp/v201702/inventory_service/__init__.py | 2 +- examples/dfp/v201702/inventory_service/archive_ad_units.py | 2 +- examples/dfp/v201702/inventory_service/create_ad_units.py | 2 +- examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py | 2 +- examples/dfp/v201702/inventory_service/get_all_ad_units.py | 2 +- examples/dfp/v201702/inventory_service/update_ad_units.py | 2 +- examples/dfp/v201702/label_service/__init__.py | 2 +- examples/dfp/v201702/label_service/create_labels.py | 2 +- examples/dfp/v201702/label_service/deactivate_labels.py | 2 +- examples/dfp/v201702/label_service/get_active_labels.py | 2 +- examples/dfp/v201702/label_service/get_all_labels.py | 2 +- examples/dfp/v201702/label_service/update_labels.py | 2 +- .../v201702/line_item_creative_association_service/__init__.py | 2 +- .../line_item_creative_association_service/create_licas.py | 2 +- .../line_item_creative_association_service/deactivate_licas.py | 2 +- .../line_item_creative_association_service/get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../line_item_creative_association_service/update_licas.py | 2 +- examples/dfp/v201702/line_item_service/__init__.py | 2 +- examples/dfp/v201702/line_item_service/activate_line_items.py | 2 +- examples/dfp/v201702/line_item_service/create_line_items.py | 2 +- .../dfp/v201702/line_item_service/create_video_line_item.py | 2 +- examples/dfp/v201702/line_item_service/get_all_line_items.py | 2 +- .../line_item_service/get_line_items_that_need_creatives.py | 2 +- .../line_item_service/get_recently_updated_line_items.py | 2 +- .../dfp/v201702/line_item_service/target_custom_criteria.py | 2 +- examples/dfp/v201702/line_item_service/update_line_items.py | 2 +- examples/dfp/v201702/native_style_service/__init__.py | 2 +- .../dfp/v201702/native_style_service/create_native_styles.py | 2 +- .../dfp/v201702/native_style_service/get_all_native_styles.py | 2 +- examples/dfp/v201702/network_service/__init__.py | 2 +- examples/dfp/v201702/network_service/get_all_networks.py | 2 +- examples/dfp/v201702/network_service/make_test_network.py | 2 +- examples/dfp/v201702/order_service/__init__.py | 2 +- examples/dfp/v201702/order_service/approve_orders.py | 2 +- examples/dfp/v201702/order_service/create_orders.py | 2 +- examples/dfp/v201702/order_service/get_all_orders.py | 2 +- examples/dfp/v201702/order_service/get_orders_starting_soon.py | 2 +- examples/dfp/v201702/order_service/update_orders.py | 2 +- examples/dfp/v201702/package_service/get_all_packages.py | 2 +- .../dfp/v201702/package_service/get_in_progress_packages.py | 2 +- examples/dfp/v201702/placement_service/create_placements.py | 2 +- examples/dfp/v201702/placement_service/deactivate_placements.py | 2 +- examples/dfp/v201702/placement_service/get_active_placements.py | 2 +- examples/dfp/v201702/placement_service/get_all_placements.py | 2 +- examples/dfp/v201702/placement_service/update_placements.py | 2 +- examples/dfp/v201702/premium_rate_service/__init__.py | 2 +- .../dfp/v201702/premium_rate_service/create_premium_rates.py | 2 +- .../dfp/v201702/premium_rate_service/get_all_premium_rates.py | 2 +- .../premium_rate_service/get_premium_rates_for_rate_card.py | 2 +- .../dfp/v201702/premium_rate_service/update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 2 +- .../get_product_package_items_for_product_package.py | 2 +- .../product_package_service/get_active_product_packages.py | 2 +- .../v201702/product_package_service/get_all_product_packages.py | 2 +- examples/dfp/v201702/product_service/__init__.py | 2 +- .../create_programmatic_products_for_non_sales_management.py | 2 +- examples/dfp/v201702/product_service/get_all_products.py | 2 +- .../product_service/get_products_for_product_template.py | 2 +- .../publish_programmatic_products_to_marketplace.py | 2 +- examples/dfp/v201702/product_service/update_products.py | 2 +- examples/dfp/v201702/product_template_service/__init__.py | 2 +- .../product_template_service/activate_product_templates.py | 2 +- .../product_template_service/create_product_templates.py | 2 +- .../create_programmatic_product_templates.py | 2 +- .../product_template_service/get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../product_template_service/update_product_templates.py | 2 +- examples/dfp/v201702/proposal_line_item_service/__init__.py | 2 +- .../proposal_line_item_service/archive_proposal_line_items.py | 2 +- .../create_programmatic_proposal_line_items.py | 2 +- ...programmatic_proposal_line_items_for_non_sales_management.py | 2 +- .../proposal_line_item_service/create_proposal_line_items.py | 2 +- .../proposal_line_item_service/get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../proposal_line_item_service/update_proposal_line_items.py | 2 +- examples/dfp/v201702/proposal_service/__init__.py | 2 +- .../v201702/proposal_service/create_programmatic_proposals.py | 2 +- .../create_programmatic_proposals_for_non_sales_management.py | 2 +- examples/dfp/v201702/proposal_service/create_proposals.py | 2 +- examples/dfp/v201702/proposal_service/get_all_proposals.py | 2 +- .../dfp/v201702/proposal_service/get_marketplace_comments.py | 2 +- .../v201702/proposal_service/get_proposals_pending_approval.py | 2 +- .../dfp/v201702/proposal_service/request_buyers_acceptance.py | 2 +- .../v201702/proposal_service/submit_proposals_for_approval.py | 2 +- examples/dfp/v201702/proposal_service/update_proposals.py | 2 +- .../dfp/v201702/publisher_query_language_service/__init__.py | 2 +- .../publisher_query_language_service/fetch_match_tables.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../publisher_query_language_service/get_recent_changes.py | 2 +- examples/dfp/v201702/rate_card_service/__init__.py | 2 +- examples/dfp/v201702/rate_card_service/get_all_rate_cards.py | 2 +- .../dfp/v201702/rate_card_service/get_marketplace_rate_cards.py | 2 +- ...econciliation_line_item_reports_for_reconciliation_report.py | 2 +- ...et_reconciliation_order_reports_for_reconciliation_report.py | 2 +- .../get_reconciliation_report_rows_for_reconciliation_report.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- .../get_reconciliation_report_for_last_billing_period.py | 2 +- examples/dfp/v201702/report_service/__init__.py | 2 +- examples/dfp/v201702/report_service/run_delivery_report.py | 2 +- examples/dfp/v201702/report_service/run_inventory_report.py | 2 +- examples/dfp/v201702/report_service/run_reach_report.py | 2 +- .../dfp/v201702/report_service/run_report_with_custom_fields.py | 2 +- examples/dfp/v201702/report_service/run_sales_report.py | 2 +- examples/dfp/v201702/report_service/run_saved_query.py | 2 +- examples/dfp/v201702/suggested_ad_unit_service/__init__.py | 2 +- .../suggested_ad_unit_service/approve_all_suggested_ad_units.py | 2 +- .../suggested_ad_unit_service/get_all_suggested_ad_units.py | 2 +- .../get_highly_requested_suggested_ad_units.py | 2 +- examples/dfp/v201702/team_service/__init__.py | 2 +- examples/dfp/v201702/team_service/create_teams.py | 2 +- examples/dfp/v201702/team_service/get_all_teams.py | 2 +- examples/dfp/v201702/team_service/update_teams.py | 2 +- examples/dfp/v201702/user_service/__init__.py | 2 +- examples/dfp/v201702/user_service/create_users.py | 2 +- examples/dfp/v201702/user_service/deactivate_users.py | 2 +- examples/dfp/v201702/user_service/get_all_roles.py | 2 +- examples/dfp/v201702/user_service/get_all_users.py | 2 +- examples/dfp/v201702/user_service/get_user_by_email_address.py | 2 +- examples/dfp/v201702/user_service/update_users.py | 2 +- examples/dfp/v201702/user_team_association_service/__init__.py | 2 +- .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- examples/dfp/v201702/workflow_request_service/__init__.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../workflow_request_service/get_workflow_approval_requests.py | 2 +- .../get_workflow_external_condition_requests.py | 2 +- .../trigger_workflow_external_condition_requests.py | 2 +- 912 files changed, 912 insertions(+), 912 deletions(-) diff --git a/examples/adwords/adwords_appengine_demo/__init__.py b/examples/adwords/adwords_appengine_demo/__init__.py index be307921..38deb3b8 100755 --- a/examples/adwords/adwords_appengine_demo/__init__.py +++ b/examples/adwords/adwords_appengine_demo/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/demo/__init__.py b/examples/adwords/adwords_appengine_demo/demo/__init__.py index 59e8ef3a..edf49e56 100755 --- a/examples/adwords/adwords_appengine_demo/demo/__init__.py +++ b/examples/adwords/adwords_appengine_demo/demo/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/demo/main.py b/examples/adwords/adwords_appengine_demo/demo/main.py index 5d364db6..1dfb904c 100755 --- a/examples/adwords/adwords_appengine_demo/demo/main.py +++ b/examples/adwords/adwords_appengine_demo/demo/main.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/__init__.py b/examples/adwords/adwords_appengine_demo/handlers/__init__.py index 0f5dabe3..a186d331 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/__init__.py +++ b/examples/adwords/adwords_appengine_demo/handlers/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index c2e70b54..0595b40a 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py index 97d6a3e4..9cd6b7ca 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/models/__init__.py b/examples/adwords/adwords_appengine_demo/models/__init__.py index af1c9f8f..2eba7921 100755 --- a/examples/adwords/adwords_appengine_demo/models/__init__.py +++ b/examples/adwords/adwords_appengine_demo/models/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/models/app_user.py b/examples/adwords/adwords_appengine_demo/models/app_user.py index 5272ee87..56004b17 100755 --- a/examples/adwords/adwords_appengine_demo/models/app_user.py +++ b/examples/adwords/adwords_appengine_demo/models/app_user.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/__init__.py b/examples/adwords/adwords_appengine_demo/views/__init__.py index f6f56e9a..eadfba45 100755 --- a/examples/adwords/adwords_appengine_demo/views/__init__.py +++ b/examples/adwords/adwords_appengine_demo/views/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py index ce4d8943..48bb14c5 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py index d86b3181..25297d20 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/init_view.py b/examples/adwords/adwords_appengine_demo/views/init_view.py index edb5d935..e6215956 100755 --- a/examples/adwords/adwords_appengine_demo/views/init_view.py +++ b/examples/adwords/adwords_appengine_demo/views/init_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py index 2813a14a..e3bdbf1d 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py index 74e00a59..9722cad9 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py index a0f1448c..758f832d 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py index 05f071f5..9c74eeaa 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py index af08fa55..bcc709c3 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py index 53903584..bbfe5d96 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py index 3be794b6..83159ca6 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index 57f978c4..b4b0b4f9 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_without_yaml.py index 12e9ad99..b79c69ab 100755 --- a/examples/adwords/authentication/create_adwords_client_without_yaml.py +++ b/examples/adwords/authentication/create_adwords_client_without_yaml.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 37696d7e..0f5d1829 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/account_management/create_account.py b/examples/adwords/v201607/account_management/create_account.py index 25faa91d..c3e65a9e 100755 --- a/examples/adwords/v201607/account_management/create_account.py +++ b/examples/adwords/v201607/account_management/create_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/account_management/get_account_changes.py b/examples/adwords/v201607/account_management/get_account_changes.py index 6ba4174e..91476eb4 100755 --- a/examples/adwords/v201607/account_management/get_account_changes.py +++ b/examples/adwords/v201607/account_management/get_account_changes.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/account_management/get_account_hierarchy.py b/examples/adwords/v201607/account_management/get_account_hierarchy.py index 3b6b2e33..33e5127f 100755 --- a/examples/adwords/v201607/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201607/account_management/get_account_hierarchy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py index f23b8f36..801af9b8 100755 --- a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py index 25f0877e..11a3ab88 100755 --- a/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py index 7ad07397..6b840e23 100755 --- a/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/add_html5_ad.py b/examples/adwords/v201607/advanced_operations/add_html5_ad.py index 4af60d30..188cdff6 100755 --- a/examples/adwords/v201607/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201607/advanced_operations/add_html5_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py index ee4eea91..1558a6e4 100755 --- a/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py index c87bb167..9f9c55f1 100755 --- a/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py index 8d46d8ce..c52da2ba 100755 --- a/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py index cf24c855..05fcdf3f 100755 --- a/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py index d5f847f4..3de92cc2 100755 --- a/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py index 00e5f08f..5521034d 100755 --- a/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/add_ad_groups.py b/examples/adwords/v201607/basic_operations/add_ad_groups.py index 2839ac7f..b0e52a8f 100755 --- a/examples/adwords/v201607/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201607/basic_operations/add_ad_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/add_campaigns.py b/examples/adwords/v201607/basic_operations/add_campaigns.py index 3df426bb..3d3c6d1f 100755 --- a/examples/adwords/v201607/basic_operations/add_campaigns.py +++ b/examples/adwords/v201607/basic_operations/add_campaigns.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py index 02c127de..19e48782 100755 --- a/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py +++ b/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/add_keywords.py b/examples/adwords/v201607/basic_operations/add_keywords.py index 37f8e7f0..ed6db735 100755 --- a/examples/adwords/v201607/basic_operations/add_keywords.py +++ b/examples/adwords/v201607/basic_operations/add_keywords.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/add_text_ads.py b/examples/adwords/v201607/basic_operations/add_text_ads.py index 55e39292..4c58562c 100755 --- a/examples/adwords/v201607/basic_operations/add_text_ads.py +++ b/examples/adwords/v201607/basic_operations/add_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/get_ad_groups.py b/examples/adwords/v201607/basic_operations/get_ad_groups.py index aeda14ef..29a50c30 100755 --- a/examples/adwords/v201607/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201607/basic_operations/get_ad_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/get_campaigns.py b/examples/adwords/v201607/basic_operations/get_campaigns.py index 894e5b18..10c362cb 100755 --- a/examples/adwords/v201607/basic_operations/get_campaigns.py +++ b/examples/adwords/v201607/basic_operations/get_campaigns.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py index 94efbdcf..8b8043d9 100755 --- a/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py index 7cd152f9..cf10d064 100755 --- a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py +++ b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/get_keywords.py b/examples/adwords/v201607/basic_operations/get_keywords.py index 4c38359c..34a78f7e 100755 --- a/examples/adwords/v201607/basic_operations/get_keywords.py +++ b/examples/adwords/v201607/basic_operations/get_keywords.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/get_text_ads.py b/examples/adwords/v201607/basic_operations/get_text_ads.py index 8a007d64..0f6663c4 100755 --- a/examples/adwords/v201607/basic_operations/get_text_ads.py +++ b/examples/adwords/v201607/basic_operations/get_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/pause_ad.py b/examples/adwords/v201607/basic_operations/pause_ad.py index 3b08cbb4..cb8fe0f6 100755 --- a/examples/adwords/v201607/basic_operations/pause_ad.py +++ b/examples/adwords/v201607/basic_operations/pause_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/remove_ad.py b/examples/adwords/v201607/basic_operations/remove_ad.py index a0fbf984..77c2bf3a 100755 --- a/examples/adwords/v201607/basic_operations/remove_ad.py +++ b/examples/adwords/v201607/basic_operations/remove_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/remove_ad_group.py b/examples/adwords/v201607/basic_operations/remove_ad_group.py index 1fa20584..0a9991f7 100755 --- a/examples/adwords/v201607/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201607/basic_operations/remove_ad_group.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/remove_campaign.py b/examples/adwords/v201607/basic_operations/remove_campaign.py index 651d50ad..b5c953bd 100755 --- a/examples/adwords/v201607/basic_operations/remove_campaign.py +++ b/examples/adwords/v201607/basic_operations/remove_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/remove_keyword.py b/examples/adwords/v201607/basic_operations/remove_keyword.py index 144674f2..7b4d815c 100755 --- a/examples/adwords/v201607/basic_operations/remove_keyword.py +++ b/examples/adwords/v201607/basic_operations/remove_keyword.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/update_ad_group.py b/examples/adwords/v201607/basic_operations/update_ad_group.py index b80c1058..91b9310d 100755 --- a/examples/adwords/v201607/basic_operations/update_ad_group.py +++ b/examples/adwords/v201607/basic_operations/update_ad_group.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/update_campaign.py b/examples/adwords/v201607/basic_operations/update_campaign.py index 0b6cb3ad..a55ac7db 100755 --- a/examples/adwords/v201607/basic_operations/update_campaign.py +++ b/examples/adwords/v201607/basic_operations/update_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/basic_operations/update_keyword.py b/examples/adwords/v201607/basic_operations/update_keyword.py index 006601ff..9f498e46 100755 --- a/examples/adwords/v201607/basic_operations/update_keyword.py +++ b/examples/adwords/v201607/basic_operations/update_keyword.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/add_campaign_labels.py b/examples/adwords/v201607/campaign_management/add_campaign_labels.py index c778800a..69a493c5 100755 --- a/examples/adwords/v201607/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201607/campaign_management/add_campaign_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py index 7889ceac..d1e3580d 100755 --- a/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/add_draft.py b/examples/adwords/v201607/campaign_management/add_draft.py index 6936265c..0f7757c2 100755 --- a/examples/adwords/v201607/campaign_management/add_draft.py +++ b/examples/adwords/v201607/campaign_management/add_draft.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/add_experiment.py b/examples/adwords/v201607/campaign_management/add_experiment.py index 26cb9852..aac50210 100755 --- a/examples/adwords/v201607/campaign_management/add_experiment.py +++ b/examples/adwords/v201607/campaign_management/add_experiment.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py index 99b7d74b..aff70d23 100755 --- a/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/add_trial.py b/examples/adwords/v201607/campaign_management/add_trial.py index 960a0e02..4fa27d82 100755 --- a/examples/adwords/v201607/campaign_management/add_trial.py +++ b/examples/adwords/v201607/campaign_management/add_trial.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py index 9d716450..3a6691cf 100755 --- a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py index c89cb6b0..2b7a3862 100755 --- a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py index c0979099..c585a3d7 100755 --- a/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/graduate_trial.py b/examples/adwords/v201607/campaign_management/graduate_trial.py index 899c9182..31423474 100755 --- a/examples/adwords/v201607/campaign_management/graduate_trial.py +++ b/examples/adwords/v201607/campaign_management/graduate_trial.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/promote_experiment.py b/examples/adwords/v201607/campaign_management/promote_experiment.py index 757ace46..c0a6e044 100755 --- a/examples/adwords/v201607/campaign_management/promote_experiment.py +++ b/examples/adwords/v201607/campaign_management/promote_experiment.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/set_ad_parameters.py b/examples/adwords/v201607/campaign_management/set_ad_parameters.py index 4a8a3146..6cda9f60 100755 --- a/examples/adwords/v201607/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201607/campaign_management/set_ad_parameters.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016 Google Inc. All Rights Reserved. diff --git a/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py index 1ab4374a..f3567567 100755 --- a/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/campaign_management/validate_text_ad.py b/examples/adwords/v201607/campaign_management/validate_text_ad.py index 3b7d6a7f..d19563b2 100755 --- a/examples/adwords/v201607/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201607/campaign_management/validate_text_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/error_handling/handle_partial_failures.py b/examples/adwords/v201607/error_handling/handle_partial_failures.py index a6fa6a91..2ab5ec73 100755 --- a/examples/adwords/v201607/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201607/error_handling/handle_partial_failures.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py index 45cf9ad7..94782901 100755 --- a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py index 5d743c1e..77c04d35 100755 --- a/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/extensions/add_prices.py b/examples/adwords/v201607/extensions/add_prices.py index 9f4026cd..56f7c658 100755 --- a/examples/adwords/v201607/extensions/add_prices.py +++ b/examples/adwords/v201607/extensions/add_prices.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/extensions/add_site_links.py b/examples/adwords/v201607/extensions/add_site_links.py index 315101c0..24cd06da 100755 --- a/examples/adwords/v201607/extensions/add_site_links.py +++ b/examples/adwords/v201607/extensions/add_site_links.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py index 1f93a814..89e37397 100755 --- a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/migration/migrate_to_extension_settings.py b/examples/adwords/v201607/migration/migrate_to_extension_settings.py index 2e513597..8ff3c77a 100755 --- a/examples/adwords/v201607/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201607/migration/migrate_to_extension_settings.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/misc/get_all_images_and_videos.py b/examples/adwords/v201607/misc/get_all_images_and_videos.py index 713a9529..ed4bd856 100755 --- a/examples/adwords/v201607/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201607/misc/get_all_images_and_videos.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/misc/upload_image.py b/examples/adwords/v201607/misc/upload_image.py index f7924112..90903866 100755 --- a/examples/adwords/v201607/misc/upload_image.py +++ b/examples/adwords/v201607/misc/upload_image.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/misc/upload_media_bundle.py b/examples/adwords/v201607/misc/upload_media_bundle.py index 3b543eeb..c8afb690 100755 --- a/examples/adwords/v201607/misc/upload_media_bundle.py +++ b/examples/adwords/v201607/misc/upload_media_bundle.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/optimization/estimate_keyword_traffic.py b/examples/adwords/v201607/optimization/estimate_keyword_traffic.py index 81570092..ed12b2ff 100755 --- a/examples/adwords/v201607/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201607/optimization/estimate_keyword_traffic.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py index 4957cebf..3bef47c3 100755 --- a/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ b/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py index 4bf2c5e8..974a6e1b 100755 --- a/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/optimization/get_keyword_ideas.py b/examples/adwords/v201607/optimization/get_keyword_ideas.py index c47cf6e9..a61cf5b8 100755 --- a/examples/adwords/v201607/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201607/optimization/get_keyword_ideas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/remarketing/add_audience.py b/examples/adwords/v201607/remarketing/add_audience.py index c13e4f6b..1c514e58 100755 --- a/examples/adwords/v201607/remarketing/add_audience.py +++ b/examples/adwords/v201607/remarketing/add_audience.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/remarketing/add_conversion_tracker.py b/examples/adwords/v201607/remarketing/add_conversion_tracker.py index 7abe5a99..83fd087b 100755 --- a/examples/adwords/v201607/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201607/remarketing/add_conversion_tracker.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/remarketing/add_crm_based_user_list.py b/examples/adwords/v201607/remarketing/add_crm_based_user_list.py index 7c8d51a5..36ea549d 100755 --- a/examples/adwords/v201607/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201607/remarketing/add_crm_based_user_list.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py index 28cf1ffc..f0bca2bb 100755 --- a/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/remarketing/upload_offline_conversions.py b/examples/adwords/v201607/remarketing/upload_offline_conversions.py index 8a32a9d6..bd020229 100755 --- a/examples/adwords/v201607/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201607/remarketing/upload_offline_conversions.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/reporting/download_criteria_report.py b/examples/adwords/v201607/reporting/download_criteria_report.py index dbade940..7912003c 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report.py +++ b/examples/adwords/v201607/reporting/download_criteria_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py index 63563e2d..1805b421 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py index ab02ab68..f645755d 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py index 1e3aa0a1..fdc0e538 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py index c1a1ebb9..63a0e779 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py index 2dafb47e..70f8a9e6 100755 --- a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/reporting/get_report_fields.py b/examples/adwords/v201607/reporting/get_report_fields.py index 97bf5e01..9d238971 100755 --- a/examples/adwords/v201607/reporting/get_report_fields.py +++ b/examples/adwords/v201607/reporting/get_report_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/reporting/parallel_report_download.py b/examples/adwords/v201607/reporting/parallel_report_download.py index b3e16bda..abccb5e3 100755 --- a/examples/adwords/v201607/reporting/parallel_report_download.py +++ b/examples/adwords/v201607/reporting/parallel_report_download.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/shopping/add_product_partition_tree.py b/examples/adwords/v201607/shopping/add_product_partition_tree.py index 302b63ab..183dd4a9 100755 --- a/examples/adwords/v201607/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201607/shopping/add_product_partition_tree.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/shopping/add_product_scope.py b/examples/adwords/v201607/shopping/add_product_scope.py index c2f57ef2..1c529afc 100755 --- a/examples/adwords/v201607/shopping/add_product_scope.py +++ b/examples/adwords/v201607/shopping/add_product_scope.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/shopping/add_shopping_campaign.py b/examples/adwords/v201607/shopping/add_shopping_campaign.py index fec5419f..0ba1c6f5 100755 --- a/examples/adwords/v201607/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201607/shopping/add_shopping_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/shopping/get_product_category_taxonomy.py b/examples/adwords/v201607/shopping/get_product_category_taxonomy.py index 029d7299..470b0546 100755 --- a/examples/adwords/v201607/shopping/get_product_category_taxonomy.py +++ b/examples/adwords/v201607/shopping/get_product_category_taxonomy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py index 59b636c8..d1f2fbe8 100755 --- a/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py index 24ae1373..951f835e 100755 --- a/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py index bd904689..4c8b73fd 100755 --- a/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py index ecf76a5c..d63e173a 100755 --- a/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/targeting/lookup_location.py b/examples/adwords/v201607/targeting/lookup_location.py index 37a7756b..5950060b 100755 --- a/examples/adwords/v201607/targeting/lookup_location.py +++ b/examples/adwords/v201607/targeting/lookup_location.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/account_management/accept_service_link.py b/examples/adwords/v201609/account_management/accept_service_link.py index 930fe0b7..738c3971 100755 --- a/examples/adwords/v201609/account_management/accept_service_link.py +++ b/examples/adwords/v201609/account_management/accept_service_link.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/account_management/create_account.py b/examples/adwords/v201609/account_management/create_account.py index d1e80e07..cf396cd7 100755 --- a/examples/adwords/v201609/account_management/create_account.py +++ b/examples/adwords/v201609/account_management/create_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/account_management/get_account_changes.py b/examples/adwords/v201609/account_management/get_account_changes.py index a06d1d13..e1ecae70 100755 --- a/examples/adwords/v201609/account_management/get_account_changes.py +++ b/examples/adwords/v201609/account_management/get_account_changes.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/account_management/get_account_hierarchy.py b/examples/adwords/v201609/account_management/get_account_hierarchy.py index ebac72e4..ef7e6ffe 100755 --- a/examples/adwords/v201609/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201609/account_management/get_account_hierarchy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py index f4a95d53..556e21bb 100755 --- a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py index 093acb78..a14d1440 100755 --- a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py index 3d406df7..cbf0f447 100755 --- a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py index 8d039035..453bca8f 100755 --- a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/add_html5_ad.py b/examples/adwords/v201609/advanced_operations/add_html5_ad.py index e8582408..66817942 100755 --- a/examples/adwords/v201609/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201609/advanced_operations/add_html5_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py index 20fc2de5..82f1def5 100755 --- a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py index 8ee87822..0b9ffc31 100755 --- a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py index dc832cb3..37033b06 100755 --- a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py index 01e0cb97..59f7da6f 100755 --- a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py index eecb8c2e..9c183775 100755 --- a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py index 509b097d..ddb17669 100755 --- a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/add_ad_groups.py b/examples/adwords/v201609/basic_operations/add_ad_groups.py index 9f43d863..c689f945 100755 --- a/examples/adwords/v201609/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201609/basic_operations/add_ad_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/add_campaigns.py b/examples/adwords/v201609/basic_operations/add_campaigns.py index b78331c3..b7eb979f 100755 --- a/examples/adwords/v201609/basic_operations/add_campaigns.py +++ b/examples/adwords/v201609/basic_operations/add_campaigns.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py index 233677a7..4d5221db 100755 --- a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py +++ b/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/add_keywords.py b/examples/adwords/v201609/basic_operations/add_keywords.py index b92fec27..5dda0f48 100755 --- a/examples/adwords/v201609/basic_operations/add_keywords.py +++ b/examples/adwords/v201609/basic_operations/add_keywords.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/get_ad_groups.py b/examples/adwords/v201609/basic_operations/get_ad_groups.py index b3273ea8..87c7d3df 100755 --- a/examples/adwords/v201609/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201609/basic_operations/get_ad_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/get_campaigns.py b/examples/adwords/v201609/basic_operations/get_campaigns.py index 9493c343..9fc2baa1 100755 --- a/examples/adwords/v201609/basic_operations/get_campaigns.py +++ b/examples/adwords/v201609/basic_operations/get_campaigns.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py index fb210a3b..2f8756e0 100755 --- a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py index ddb84cb1..c4d9a2f5 100755 --- a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py +++ b/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/get_keywords.py b/examples/adwords/v201609/basic_operations/get_keywords.py index 8e8d38f0..34871e04 100755 --- a/examples/adwords/v201609/basic_operations/get_keywords.py +++ b/examples/adwords/v201609/basic_operations/get_keywords.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/get_text_ads.py b/examples/adwords/v201609/basic_operations/get_text_ads.py index 9518f0eb..bbff33f3 100755 --- a/examples/adwords/v201609/basic_operations/get_text_ads.py +++ b/examples/adwords/v201609/basic_operations/get_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/pause_ad.py b/examples/adwords/v201609/basic_operations/pause_ad.py index 5535f12b..165af6b0 100755 --- a/examples/adwords/v201609/basic_operations/pause_ad.py +++ b/examples/adwords/v201609/basic_operations/pause_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/remove_ad.py b/examples/adwords/v201609/basic_operations/remove_ad.py index d40c1a8f..82ae7f5a 100755 --- a/examples/adwords/v201609/basic_operations/remove_ad.py +++ b/examples/adwords/v201609/basic_operations/remove_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/remove_ad_group.py b/examples/adwords/v201609/basic_operations/remove_ad_group.py index c0e2bacf..d9e20868 100755 --- a/examples/adwords/v201609/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201609/basic_operations/remove_ad_group.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/remove_campaign.py b/examples/adwords/v201609/basic_operations/remove_campaign.py index f0912f81..73005f0d 100755 --- a/examples/adwords/v201609/basic_operations/remove_campaign.py +++ b/examples/adwords/v201609/basic_operations/remove_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/remove_keyword.py b/examples/adwords/v201609/basic_operations/remove_keyword.py index 8448c248..e2bde83d 100755 --- a/examples/adwords/v201609/basic_operations/remove_keyword.py +++ b/examples/adwords/v201609/basic_operations/remove_keyword.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/update_ad_group.py b/examples/adwords/v201609/basic_operations/update_ad_group.py index 09d3bf1e..3b58a675 100755 --- a/examples/adwords/v201609/basic_operations/update_ad_group.py +++ b/examples/adwords/v201609/basic_operations/update_ad_group.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/update_campaign.py b/examples/adwords/v201609/basic_operations/update_campaign.py index 167d1c42..96639c47 100755 --- a/examples/adwords/v201609/basic_operations/update_campaign.py +++ b/examples/adwords/v201609/basic_operations/update_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/basic_operations/update_keyword.py b/examples/adwords/v201609/basic_operations/update_keyword.py index 2fa0b419..4e056bfb 100755 --- a/examples/adwords/v201609/basic_operations/update_keyword.py +++ b/examples/adwords/v201609/basic_operations/update_keyword.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/add_campaign_labels.py b/examples/adwords/v201609/campaign_management/add_campaign_labels.py index 7d1e52cd..4c601330 100755 --- a/examples/adwords/v201609/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201609/campaign_management/add_campaign_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py index 4ea79492..60e3ce09 100755 --- a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/add_draft.py b/examples/adwords/v201609/campaign_management/add_draft.py index fb64a48c..e04ddbf5 100755 --- a/examples/adwords/v201609/campaign_management/add_draft.py +++ b/examples/adwords/v201609/campaign_management/add_draft.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py index 45fb351d..d9a2bfb5 100755 --- a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/add_trial.py b/examples/adwords/v201609/campaign_management/add_trial.py index 09058ad0..f5af4a13 100755 --- a/examples/adwords/v201609/campaign_management/add_trial.py +++ b/examples/adwords/v201609/campaign_management/add_trial.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py index 05860fe5..7d4ff086 100755 --- a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py index a94e3ff1..58915dc3 100755 --- a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py index 6819ebca..bb0c5664 100755 --- a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/graduate_trial.py b/examples/adwords/v201609/campaign_management/graduate_trial.py index 2ccd302b..6888c53a 100755 --- a/examples/adwords/v201609/campaign_management/graduate_trial.py +++ b/examples/adwords/v201609/campaign_management/graduate_trial.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/set_ad_parameters.py b/examples/adwords/v201609/campaign_management/set_ad_parameters.py index 64c4d8ad..c270e2da 100755 --- a/examples/adwords/v201609/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201609/campaign_management/set_ad_parameters.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016 Google Inc. All Rights Reserved. diff --git a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py index bba2fddd..002a05d4 100755 --- a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/campaign_management/validate_text_ad.py b/examples/adwords/v201609/campaign_management/validate_text_ad.py index 9b277065..676ee8db 100755 --- a/examples/adwords/v201609/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201609/campaign_management/validate_text_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/error_handling/handle_partial_failures.py b/examples/adwords/v201609/error_handling/handle_partial_failures.py index 5f23a8a7..0d50e044 100755 --- a/examples/adwords/v201609/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201609/error_handling/handle_partial_failures.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py index cf6cb5f1..5f7199d6 100755 --- a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py index a4f2bb99..80ee4f96 100755 --- a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/extensions/add_prices.py b/examples/adwords/v201609/extensions/add_prices.py index a1a42caf..771c6615 100755 --- a/examples/adwords/v201609/extensions/add_prices.py +++ b/examples/adwords/v201609/extensions/add_prices.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/extensions/add_site_links.py b/examples/adwords/v201609/extensions/add_site_links.py index bf470bbd..65806e36 100755 --- a/examples/adwords/v201609/extensions/add_site_links.py +++ b/examples/adwords/v201609/extensions/add_site_links.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py index 5706cfff..1373c1b1 100755 --- a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/migration/migrate_to_extension_settings.py b/examples/adwords/v201609/migration/migrate_to_extension_settings.py index cae2dc68..9cbbdc17 100755 --- a/examples/adwords/v201609/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201609/migration/migrate_to_extension_settings.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/misc/get_all_images_and_videos.py b/examples/adwords/v201609/misc/get_all_images_and_videos.py index 9ac21269..9b562fab 100755 --- a/examples/adwords/v201609/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201609/misc/get_all_images_and_videos.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/misc/upload_image.py b/examples/adwords/v201609/misc/upload_image.py index e0bde8f9..d4fd4a24 100755 --- a/examples/adwords/v201609/misc/upload_image.py +++ b/examples/adwords/v201609/misc/upload_image.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/misc/upload_media_bundle.py b/examples/adwords/v201609/misc/upload_media_bundle.py index 224a0095..fee2cc1b 100755 --- a/examples/adwords/v201609/misc/upload_media_bundle.py +++ b/examples/adwords/v201609/misc/upload_media_bundle.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py b/examples/adwords/v201609/optimization/estimate_keyword_traffic.py index 3f937af9..70c3ea73 100755 --- a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201609/optimization/estimate_keyword_traffic.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py index 4258a0ac..4a6039d6 100755 --- a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ b/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py index b1a478d1..5bfbf3af 100755 --- a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/optimization/get_keyword_ideas.py b/examples/adwords/v201609/optimization/get_keyword_ideas.py index 9cc80081..9663b601 100755 --- a/examples/adwords/v201609/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201609/optimization/get_keyword_ideas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/remarketing/add_audience.py b/examples/adwords/v201609/remarketing/add_audience.py index fa0c3527..38652c29 100755 --- a/examples/adwords/v201609/remarketing/add_audience.py +++ b/examples/adwords/v201609/remarketing/add_audience.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/remarketing/add_conversion_tracker.py b/examples/adwords/v201609/remarketing/add_conversion_tracker.py index 81df219a..310586ed 100755 --- a/examples/adwords/v201609/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201609/remarketing/add_conversion_tracker.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py b/examples/adwords/v201609/remarketing/add_crm_based_user_list.py index 92967601..75b54471 100755 --- a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201609/remarketing/add_crm_based_user_list.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py index 6ea515dd..9833ba06 100755 --- a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py index 970a1624..d8efc864 100755 --- a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py +++ b/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/remarketing/upload_offline_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_conversions.py index 770b3316..57d7836d 100755 --- a/examples/adwords/v201609/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201609/remarketing/upload_offline_conversions.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/reporting/download_criteria_report.py b/examples/adwords/v201609/reporting/download_criteria_report.py index d23c7135..993e67c6 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report.py +++ b/examples/adwords/v201609/reporting/download_criteria_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py index 33e25e2e..3beaf5ed 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py index c487a6ee..0514d0ff 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py index 4da148c8..fd34b76f 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py index 32766925..c482909a 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py index 4004551e..bfe1c36c 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/reporting/get_report_fields.py b/examples/adwords/v201609/reporting/get_report_fields.py index c1b4adb5..4f816fbb 100755 --- a/examples/adwords/v201609/reporting/get_report_fields.py +++ b/examples/adwords/v201609/reporting/get_report_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/reporting/parallel_report_download.py b/examples/adwords/v201609/reporting/parallel_report_download.py index 48c01a2c..136080f4 100755 --- a/examples/adwords/v201609/reporting/parallel_report_download.py +++ b/examples/adwords/v201609/reporting/parallel_report_download.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/shopping/add_product_partition_tree.py b/examples/adwords/v201609/shopping/add_product_partition_tree.py index 08c292fc..595c9d20 100755 --- a/examples/adwords/v201609/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201609/shopping/add_product_partition_tree.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/shopping/add_product_scope.py b/examples/adwords/v201609/shopping/add_product_scope.py index 086bb76a..0e1a0db0 100755 --- a/examples/adwords/v201609/shopping/add_product_scope.py +++ b/examples/adwords/v201609/shopping/add_product_scope.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/shopping/add_shopping_campaign.py b/examples/adwords/v201609/shopping/add_shopping_campaign.py index 166c272e..8bbfcc65 100755 --- a/examples/adwords/v201609/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201609/shopping/add_shopping_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py b/examples/adwords/v201609/shopping/get_product_category_taxonomy.py index 10762989..e2143ef4 100755 --- a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py +++ b/examples/adwords/v201609/shopping/get_product_category_taxonomy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py index 6e80f55c..6ad6bf37 100755 --- a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py index dae2b6b3..91158d00 100755 --- a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py index b29d7b11..bf4bf0f0 100755 --- a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py index 958862f7..6dec0e63 100755 --- a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201609/targeting/lookup_location.py b/examples/adwords/v201609/targeting/lookup_location.py index e2986dd5..9dcd3b72 100755 --- a/examples/adwords/v201609/targeting/lookup_location.py +++ b/examples/adwords/v201609/targeting/lookup_location.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/account_management/accept_service_link.py b/examples/adwords/v201702/account_management/accept_service_link.py index 928b87a5..4cacf5b4 100755 --- a/examples/adwords/v201702/account_management/accept_service_link.py +++ b/examples/adwords/v201702/account_management/accept_service_link.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/account_management/create_account.py b/examples/adwords/v201702/account_management/create_account.py index 0ffad749..baa39e9f 100755 --- a/examples/adwords/v201702/account_management/create_account.py +++ b/examples/adwords/v201702/account_management/create_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/account_management/get_account_changes.py b/examples/adwords/v201702/account_management/get_account_changes.py index e8217e83..63c920dd 100755 --- a/examples/adwords/v201702/account_management/get_account_changes.py +++ b/examples/adwords/v201702/account_management/get_account_changes.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/account_management/get_account_hierarchy.py b/examples/adwords/v201702/account_management/get_account_hierarchy.py index ba9e02ec..e95787ee 100755 --- a/examples/adwords/v201702/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201702/account_management/get_account_hierarchy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py index fc5b59f7..60c582e4 100755 --- a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py index e006a8a9..71bfb4a3 100755 --- a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py index 1bac185a..fd3011b8 100755 --- a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py index f33b3d74..0aea3dd7 100755 --- a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/add_html5_ad.py b/examples/adwords/v201702/advanced_operations/add_html5_ad.py index 63332b92..64c94864 100755 --- a/examples/adwords/v201702/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201702/advanced_operations/add_html5_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py index 733fb470..052d9e23 100755 --- a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py index 9d8c8c0c..0048756a 100755 --- a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py index b86f5b5a..4fcf2ef8 100755 --- a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py index c3e6f9f0..edc6c1df 100755 --- a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py index 38bccd6c..21cdf0eb 100755 --- a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py index 2fc4cd19..1c535dfb 100755 --- a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/add_ad_groups.py b/examples/adwords/v201702/basic_operations/add_ad_groups.py index 9d27be61..a561c5ef 100755 --- a/examples/adwords/v201702/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201702/basic_operations/add_ad_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/add_campaigns.py b/examples/adwords/v201702/basic_operations/add_campaigns.py index a1bd816e..ababe339 100755 --- a/examples/adwords/v201702/basic_operations/add_campaigns.py +++ b/examples/adwords/v201702/basic_operations/add_campaigns.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py index 02b21c13..45a007d3 100755 --- a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py +++ b/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/add_keywords.py b/examples/adwords/v201702/basic_operations/add_keywords.py index 3a5406ad..d86e4b31 100755 --- a/examples/adwords/v201702/basic_operations/add_keywords.py +++ b/examples/adwords/v201702/basic_operations/add_keywords.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/get_ad_groups.py b/examples/adwords/v201702/basic_operations/get_ad_groups.py index 8a487183..683a3229 100755 --- a/examples/adwords/v201702/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201702/basic_operations/get_ad_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/get_campaigns.py b/examples/adwords/v201702/basic_operations/get_campaigns.py index 6e8fdf79..159e2009 100755 --- a/examples/adwords/v201702/basic_operations/get_campaigns.py +++ b/examples/adwords/v201702/basic_operations/get_campaigns.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py index c413d222..3f7f7831 100755 --- a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py index b2b7dd51..414b76e7 100755 --- a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py +++ b/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/get_keywords.py b/examples/adwords/v201702/basic_operations/get_keywords.py index c621b2b1..87cc693a 100755 --- a/examples/adwords/v201702/basic_operations/get_keywords.py +++ b/examples/adwords/v201702/basic_operations/get_keywords.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/get_text_ads.py b/examples/adwords/v201702/basic_operations/get_text_ads.py index 26eb8dde..8393d7ae 100755 --- a/examples/adwords/v201702/basic_operations/get_text_ads.py +++ b/examples/adwords/v201702/basic_operations/get_text_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/pause_ad.py b/examples/adwords/v201702/basic_operations/pause_ad.py index 242bf678..211e67de 100755 --- a/examples/adwords/v201702/basic_operations/pause_ad.py +++ b/examples/adwords/v201702/basic_operations/pause_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/remove_ad.py b/examples/adwords/v201702/basic_operations/remove_ad.py index 7a7ecd97..7ea2ce5c 100755 --- a/examples/adwords/v201702/basic_operations/remove_ad.py +++ b/examples/adwords/v201702/basic_operations/remove_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/remove_ad_group.py b/examples/adwords/v201702/basic_operations/remove_ad_group.py index 92e4d261..278c6fc6 100755 --- a/examples/adwords/v201702/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201702/basic_operations/remove_ad_group.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/remove_campaign.py b/examples/adwords/v201702/basic_operations/remove_campaign.py index ad8a87e4..621c2144 100755 --- a/examples/adwords/v201702/basic_operations/remove_campaign.py +++ b/examples/adwords/v201702/basic_operations/remove_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/remove_keyword.py b/examples/adwords/v201702/basic_operations/remove_keyword.py index a62fc6ab..33a7c051 100755 --- a/examples/adwords/v201702/basic_operations/remove_keyword.py +++ b/examples/adwords/v201702/basic_operations/remove_keyword.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/update_ad_group.py b/examples/adwords/v201702/basic_operations/update_ad_group.py index 69cd5c8e..5f037c32 100755 --- a/examples/adwords/v201702/basic_operations/update_ad_group.py +++ b/examples/adwords/v201702/basic_operations/update_ad_group.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/update_campaign.py b/examples/adwords/v201702/basic_operations/update_campaign.py index 413476a7..5eec5e13 100755 --- a/examples/adwords/v201702/basic_operations/update_campaign.py +++ b/examples/adwords/v201702/basic_operations/update_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/basic_operations/update_keyword.py b/examples/adwords/v201702/basic_operations/update_keyword.py index 02d9ac58..1e3c8935 100755 --- a/examples/adwords/v201702/basic_operations/update_keyword.py +++ b/examples/adwords/v201702/basic_operations/update_keyword.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/add_campaign_labels.py b/examples/adwords/v201702/campaign_management/add_campaign_labels.py index 8974b139..ef96f5c3 100755 --- a/examples/adwords/v201702/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201702/campaign_management/add_campaign_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py index 41f62638..9d6dfc03 100755 --- a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/add_draft.py b/examples/adwords/v201702/campaign_management/add_draft.py index 7feb343e..6cd4fcc6 100755 --- a/examples/adwords/v201702/campaign_management/add_draft.py +++ b/examples/adwords/v201702/campaign_management/add_draft.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py index fd7c1408..54aefb49 100755 --- a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/add_trial.py b/examples/adwords/v201702/campaign_management/add_trial.py index e293b5fc..a77755a9 100755 --- a/examples/adwords/v201702/campaign_management/add_trial.py +++ b/examples/adwords/v201702/campaign_management/add_trial.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py index 60022bbb..165fc894 100755 --- a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py index 1a387975..3a3e9d34 100755 --- a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py index 17e22497..a30ec34b 100755 --- a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/graduate_trial.py b/examples/adwords/v201702/campaign_management/graduate_trial.py index 9d535ccd..324d00f1 100755 --- a/examples/adwords/v201702/campaign_management/graduate_trial.py +++ b/examples/adwords/v201702/campaign_management/graduate_trial.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/set_ad_parameters.py b/examples/adwords/v201702/campaign_management/set_ad_parameters.py index 47cbed55..1c11b356 100755 --- a/examples/adwords/v201702/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201702/campaign_management/set_ad_parameters.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2016 Google Inc. All Rights Reserved. diff --git a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py index 24011f89..f9183264 100755 --- a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/campaign_management/validate_text_ad.py b/examples/adwords/v201702/campaign_management/validate_text_ad.py index 0908da3d..db2b63d6 100755 --- a/examples/adwords/v201702/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201702/campaign_management/validate_text_ad.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/error_handling/handle_partial_failures.py b/examples/adwords/v201702/error_handling/handle_partial_failures.py index e4495c35..b8ad2d65 100755 --- a/examples/adwords/v201702/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201702/error_handling/handle_partial_failures.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py index b4034b22..a2b4828c 100755 --- a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py index 23e778c8..c346ce2a 100755 --- a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/extensions/add_prices.py b/examples/adwords/v201702/extensions/add_prices.py index 9cb8ec85..f710319a 100755 --- a/examples/adwords/v201702/extensions/add_prices.py +++ b/examples/adwords/v201702/extensions/add_prices.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/extensions/add_site_links.py b/examples/adwords/v201702/extensions/add_site_links.py index c12cd889..ef29007c 100755 --- a/examples/adwords/v201702/extensions/add_site_links.py +++ b/examples/adwords/v201702/extensions/add_site_links.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py index f727406e..786754cf 100755 --- a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/migration/migrate_to_extension_settings.py b/examples/adwords/v201702/migration/migrate_to_extension_settings.py index 3d0233be..efb27656 100755 --- a/examples/adwords/v201702/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201702/migration/migrate_to_extension_settings.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/misc/get_all_images_and_videos.py b/examples/adwords/v201702/misc/get_all_images_and_videos.py index be327b75..ac28cf74 100755 --- a/examples/adwords/v201702/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201702/misc/get_all_images_and_videos.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/misc/upload_image.py b/examples/adwords/v201702/misc/upload_image.py index 2fe59541..95ab3432 100755 --- a/examples/adwords/v201702/misc/upload_image.py +++ b/examples/adwords/v201702/misc/upload_image.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/misc/upload_media_bundle.py b/examples/adwords/v201702/misc/upload_media_bundle.py index 087af222..16b63bd2 100755 --- a/examples/adwords/v201702/misc/upload_media_bundle.py +++ b/examples/adwords/v201702/misc/upload_media_bundle.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py b/examples/adwords/v201702/optimization/estimate_keyword_traffic.py index f06f2096..49b75cde 100755 --- a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201702/optimization/estimate_keyword_traffic.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py index 032c15db..0e2d96a0 100755 --- a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ b/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py index c1384257..9bad1afd 100755 --- a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/optimization/get_keyword_ideas.py b/examples/adwords/v201702/optimization/get_keyword_ideas.py index 66ab2d5d..0f45a6de 100755 --- a/examples/adwords/v201702/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201702/optimization/get_keyword_ideas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/remarketing/add_audience.py b/examples/adwords/v201702/remarketing/add_audience.py index 08514a3c..7ebdaa66 100755 --- a/examples/adwords/v201702/remarketing/add_audience.py +++ b/examples/adwords/v201702/remarketing/add_audience.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/remarketing/add_conversion_tracker.py b/examples/adwords/v201702/remarketing/add_conversion_tracker.py index 18693be6..2cb2d4e6 100755 --- a/examples/adwords/v201702/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201702/remarketing/add_conversion_tracker.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py b/examples/adwords/v201702/remarketing/add_crm_based_user_list.py index ff517131..37fefc3b 100755 --- a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201702/remarketing/add_crm_based_user_list.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py index 6d82ffc6..67b2efb9 100755 --- a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py index 8066200f..27e355c4 100755 --- a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py +++ b/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/remarketing/upload_offline_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_conversions.py index 787ba0da..e54e803b 100755 --- a/examples/adwords/v201702/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201702/remarketing/upload_offline_conversions.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py index 6b21463d..58394d18 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py index fcafe2f1..5930c757 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py +++ b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py index faf057ff..63e08165 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py index 78816c0b..dad7f93c 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py +++ b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py index b1f3e641..bfb72e98 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py index 4218fbca..97f07edf 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py +++ b/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/reporting/get_report_fields.py b/examples/adwords/v201702/reporting/get_report_fields.py index 68a72983..9ed7c53a 100755 --- a/examples/adwords/v201702/reporting/get_report_fields.py +++ b/examples/adwords/v201702/reporting/get_report_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/reporting/parallel_report_download.py b/examples/adwords/v201702/reporting/parallel_report_download.py index 048a927a..6bbc7f90 100755 --- a/examples/adwords/v201702/reporting/parallel_report_download.py +++ b/examples/adwords/v201702/reporting/parallel_report_download.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/shopping/add_product_partition_tree.py b/examples/adwords/v201702/shopping/add_product_partition_tree.py index cf28ef53..c31a4fdb 100755 --- a/examples/adwords/v201702/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201702/shopping/add_product_partition_tree.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/shopping/add_product_scope.py b/examples/adwords/v201702/shopping/add_product_scope.py index ba63f9bd..a9d24334 100755 --- a/examples/adwords/v201702/shopping/add_product_scope.py +++ b/examples/adwords/v201702/shopping/add_product_scope.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign.py b/examples/adwords/v201702/shopping/add_shopping_campaign.py index 87850b6b..2a13a0d0 100755 --- a/examples/adwords/v201702/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201702/shopping/add_shopping_campaign.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py index a5fbbf33..a9bb23d4 100755 --- a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py b/examples/adwords/v201702/shopping/get_product_category_taxonomy.py index efde9e53..af75ea9d 100755 --- a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py +++ b/examples/adwords/v201702/shopping/get_product_category_taxonomy.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py index 7d58f94c..bd04ea6a 100755 --- a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py index 109cda2d..0b171549 100755 --- a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py index 607e32d9..45aaf587 100755 --- a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py index 22e94047..804a5edb 100755 --- a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201702/targeting/lookup_location.py b/examples/adwords/v201702/targeting/lookup_location.py index 065e8eaf..dedc5b5c 100755 --- a/examples/adwords/v201702/targeting/lookup_location.py +++ b/examples/adwords/v201702/targeting/lookup_location.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/dfp/authentication/create_dfp_client_with_service_account.py index 3f7dcc2f..11f0462b 100755 --- a/examples/dfp/authentication/create_dfp_client_with_service_account.py +++ b/examples/dfp/authentication/create_dfp_client_with_service_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/authentication/create_dfp_client_without_yaml.py b/examples/dfp/authentication/create_dfp_client_without_yaml.py index 9b15b3ca..f857f9bc 100755 --- a/examples/dfp/authentication/create_dfp_client_without_yaml.py +++ b/examples/dfp/authentication/create_dfp_client_without_yaml.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py index d725022e..4e261fe2 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/dfp/authentication/generate_refresh_token.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_group_service/__init__.py b/examples/dfp/v201608/activity_group_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/activity_group_service/__init__.py +++ b/examples/dfp/v201608/activity_group_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_group_service/create_activity_groups.py b/examples/dfp/v201608/activity_group_service/create_activity_groups.py index 5550817f..adc441de 100755 --- a/examples/dfp/v201608/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201608/activity_group_service/create_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201608/activity_group_service/get_active_activity_groups.py index 3f8cd974..eba63436 100755 --- a/examples/dfp/v201608/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201608/activity_group_service/get_active_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py index 14a582d3..c3b69785 100755 --- a/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_group_service/update_activity_groups.py b/examples/dfp/v201608/activity_group_service/update_activity_groups.py index 4d2fadd6..85bb1331 100755 --- a/examples/dfp/v201608/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201608/activity_group_service/update_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_service/__init__.py b/examples/dfp/v201608/activity_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/activity_service/__init__.py +++ b/examples/dfp/v201608/activity_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_service/create_activities.py b/examples/dfp/v201608/activity_service/create_activities.py index 1ab9262d..e1e87d44 100755 --- a/examples/dfp/v201608/activity_service/create_activities.py +++ b/examples/dfp/v201608/activity_service/create_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_service/get_active_activities.py b/examples/dfp/v201608/activity_service/get_active_activities.py index 3ea352d4..e1b5899b 100755 --- a/examples/dfp/v201608/activity_service/get_active_activities.py +++ b/examples/dfp/v201608/activity_service/get_active_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_service/get_all_activities.py b/examples/dfp/v201608/activity_service/get_all_activities.py index 5147c4d8..d51808f3 100755 --- a/examples/dfp/v201608/activity_service/get_all_activities.py +++ b/examples/dfp/v201608/activity_service/get_all_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/activity_service/update_activities.py b/examples/dfp/v201608/activity_service/update_activities.py index 8640050c..02ae1506 100755 --- a/examples/dfp/v201608/activity_service/update_activities.py +++ b/examples/dfp/v201608/activity_service/update_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/audience_segment_service/__init__.py b/examples/dfp/v201608/audience_segment_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/audience_segment_service/__init__.py +++ b/examples/dfp/v201608/audience_segment_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/audience_segment_service/create_audience_segments.py b/examples/dfp/v201608/audience_segment_service/create_audience_segments.py index f0845326..f1ffa845 100755 --- a/examples/dfp/v201608/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/create_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py index c77a17b1..a8445f6a 100755 --- a/examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py index 237bc5c2..65bf29b2 100755 --- a/examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py index 6d4f94cc..995f300a 100755 --- a/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/audience_segment_service/update_audience_segments.py b/examples/dfp/v201608/audience_segment_service/update_audience_segments.py index 957b8e2e..ca8f2ded 100755 --- a/examples/dfp/v201608/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201608/audience_segment_service/update_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/base_rate_service/__init__.py b/examples/dfp/v201608/base_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/base_rate_service/__init__.py +++ b/examples/dfp/v201608/base_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/base_rate_service/create_product_base_rates.py b/examples/dfp/v201608/base_rate_service/create_product_base_rates.py index 139998a8..2de27113 100755 --- a/examples/dfp/v201608/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201608/base_rate_service/create_product_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py index 2c0f5693..a39ce9ad 100755 --- a/examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/base_rate_service/get_all_base_rates.py b/examples/dfp/v201608/base_rate_service/get_all_base_rates.py index e74ab065..9afb9f02 100755 --- a/examples/dfp/v201608/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201608/base_rate_service/get_all_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py index b230db2c..f468e2d3 100755 --- a/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/base_rate_service/update_base_rates.py b/examples/dfp/v201608/base_rate_service/update_base_rates.py index 6c7573fe..93f1b70b 100755 --- a/examples/dfp/v201608/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201608/base_rate_service/update_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/company_service/__init__.py b/examples/dfp/v201608/company_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/company_service/__init__.py +++ b/examples/dfp/v201608/company_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/company_service/create_companies.py b/examples/dfp/v201608/company_service/create_companies.py index 5c1974a7..6d3628b7 100755 --- a/examples/dfp/v201608/company_service/create_companies.py +++ b/examples/dfp/v201608/company_service/create_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/company_service/get_advertisers.py b/examples/dfp/v201608/company_service/get_advertisers.py index eb4e9a2c..25d65ade 100755 --- a/examples/dfp/v201608/company_service/get_advertisers.py +++ b/examples/dfp/v201608/company_service/get_advertisers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/company_service/get_all_companies.py b/examples/dfp/v201608/company_service/get_all_companies.py index f1a5a6a9..10177f1c 100755 --- a/examples/dfp/v201608/company_service/get_all_companies.py +++ b/examples/dfp/v201608/company_service/get_all_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/company_service/update_companies.py b/examples/dfp/v201608/company_service/update_companies.py index fd8cdc5c..0ce64144 100755 --- a/examples/dfp/v201608/company_service/update_companies.py +++ b/examples/dfp/v201608/company_service/update_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/contact_service/__init__.py b/examples/dfp/v201608/contact_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/contact_service/__init__.py +++ b/examples/dfp/v201608/contact_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/contact_service/create_contacts.py b/examples/dfp/v201608/contact_service/create_contacts.py index 381a6787..73236787 100755 --- a/examples/dfp/v201608/contact_service/create_contacts.py +++ b/examples/dfp/v201608/contact_service/create_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/contact_service/get_all_contacts.py b/examples/dfp/v201608/contact_service/get_all_contacts.py index fc327c70..0c67d0bb 100755 --- a/examples/dfp/v201608/contact_service/get_all_contacts.py +++ b/examples/dfp/v201608/contact_service/get_all_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/contact_service/get_uninvited_contacts.py b/examples/dfp/v201608/contact_service/get_uninvited_contacts.py index c635b8b6..c913599b 100755 --- a/examples/dfp/v201608/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201608/contact_service/get_uninvited_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/contact_service/update_contacts.py b/examples/dfp/v201608/contact_service/update_contacts.py index 8a8921b8..acd72fcd 100755 --- a/examples/dfp/v201608/contact_service/update_contacts.py +++ b/examples/dfp/v201608/contact_service/update_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/__init__.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index ee3a9c4e..ab24b17f 100755 --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 3044c2aa..3b6fd2a7 100755 --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 04259e95..8fd22438 100755 --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 3b692a82..a4301c8a 100755 --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/content_service/__init__.py b/examples/dfp/v201608/content_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/content_service/__init__.py +++ b/examples/dfp/v201608/content_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/content_service/get_all_content.py b/examples/dfp/v201608/content_service/get_all_content.py index d7a5be55..ec57a600 100755 --- a/examples/dfp/v201608/content_service/get_all_content.py +++ b/examples/dfp/v201608/content_service/get_all_content.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_service/__init__.py b/examples/dfp/v201608/creative_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/creative_service/__init__.py +++ b/examples/dfp/v201608/creative_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_service/create_creative_from_template.py b/examples/dfp/v201608/creative_service/create_creative_from_template.py index 8986be11..a077fe07 100755 --- a/examples/dfp/v201608/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201608/creative_service/create_creative_from_template.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_service/create_creatives.py b/examples/dfp/v201608/creative_service/create_creatives.py index 0e84a7e2..fdc643b4 100755 --- a/examples/dfp/v201608/creative_service/create_creatives.py +++ b/examples/dfp/v201608/creative_service/create_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_service/create_custom_creative.py b/examples/dfp/v201608/creative_service/create_custom_creative.py index be617aa8..7151169d 100755 --- a/examples/dfp/v201608/creative_service/create_custom_creative.py +++ b/examples/dfp/v201608/creative_service/create_custom_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_service/create_native_creative.py b/examples/dfp/v201608/creative_service/create_native_creative.py index 3536bae8..bed2f8b2 100755 --- a/examples/dfp/v201608/creative_service/create_native_creative.py +++ b/examples/dfp/v201608/creative_service/create_native_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_service/get_all_creatives.py b/examples/dfp/v201608/creative_service/get_all_creatives.py index b0eb7c25..e7e3cf3e 100755 --- a/examples/dfp/v201608/creative_service/get_all_creatives.py +++ b/examples/dfp/v201608/creative_service/get_all_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_service/get_image_creatives.py b/examples/dfp/v201608/creative_service/get_image_creatives.py index 90d5be9f..6976b6b6 100755 --- a/examples/dfp/v201608/creative_service/get_image_creatives.py +++ b/examples/dfp/v201608/creative_service/get_image_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_service/update_creatives.py b/examples/dfp/v201608/creative_service/update_creatives.py index 60a6fb7a..7c003e71 100755 --- a/examples/dfp/v201608/creative_service/update_creatives.py +++ b/examples/dfp/v201608/creative_service/update_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_set_service/__init__.py b/examples/dfp/v201608/creative_set_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/creative_set_service/__init__.py +++ b/examples/dfp/v201608/creative_set_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py index 62b68f37..1d0238b4 100755 --- a/examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_set_service/create_creative_set.py b/examples/dfp/v201608/creative_set_service/create_creative_set.py index 06fef367..0dfb7136 100755 --- a/examples/dfp/v201608/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201608/creative_set_service/create_creative_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201608/creative_set_service/get_all_creative_sets.py index b92491d6..4297a120 100755 --- a/examples/dfp/v201608/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201608/creative_set_service/get_all_creative_sets.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py index 34986922..4fcc65f7 100755 --- a/examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_set_service/update_creative_set.py b/examples/dfp/v201608/creative_set_service/update_creative_set.py index 4f46f517..9353ad93 100755 --- a/examples/dfp/v201608/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201608/creative_set_service/update_creative_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_template_service/__init__.py b/examples/dfp/v201608/creative_template_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/creative_template_service/__init__.py +++ b/examples/dfp/v201608/creative_template_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201608/creative_template_service/get_all_creative_templates.py index 416883a6..9df6b1c0 100755 --- a/examples/dfp/v201608/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201608/creative_template_service/get_all_creative_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py index 38d60806..2be82828 100755 --- a/examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py index 4ffe322b..dc5cb188 100755 --- a/examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py index 81032bd7..cd33b02f 100755 --- a/examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py index e1c7e997..eb32cecc 100755 --- a/examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py index ea6daf38..8d0a5e81 100755 --- a/examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py index e1e5cdfe..bb9d5725 100755 --- a/examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_field_service/__init__.py b/examples/dfp/v201608/custom_field_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/custom_field_service/__init__.py +++ b/examples/dfp/v201608/custom_field_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_field_service/create_custom_field_options.py b/examples/dfp/v201608/custom_field_service/create_custom_field_options.py index bed95fe0..dc1ca182 100755 --- a/examples/dfp/v201608/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201608/custom_field_service/create_custom_field_options.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_field_service/create_custom_fields.py b/examples/dfp/v201608/custom_field_service/create_custom_fields.py index 8cec412d..8e5f4f6b 100755 --- a/examples/dfp/v201608/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/create_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py index 90cebf21..c33b63db 100755 --- a/examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201608/custom_field_service/get_all_custom_fields.py index e64fa4e7..a7cb4130 100755 --- a/examples/dfp/v201608/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/get_all_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py index af37b100..9c2ec3d5 100755 --- a/examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py index fe5d3103..2e9b302e 100755 --- a/examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_field_service/update_custom_fields.py b/examples/dfp/v201608/custom_field_service/update_custom_fields.py index d468d268..c8ed4278 100755 --- a/examples/dfp/v201608/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201608/custom_field_service/update_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_targeting_service/__init__.py b/examples/dfp/v201608/custom_targeting_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/custom_targeting_service/__init__.py +++ b/examples/dfp/v201608/custom_targeting_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py index a55f48d0..d8e5fbfe 100755 --- a/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py index 38c327f2..9513e854 100755 --- a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py index 60b21ab2..4849dd14 100755 --- a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 0c1f1ceb..afdb514c 100755 --- a/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index b2eb5870..970a1e97 100755 --- a/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py index 8da5581e..201d93ed 100755 --- a/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py index 0154e6cb..24154ce6 100755 --- a/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/exchange_rate_service/__init__.py b/examples/dfp/v201608/exchange_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/exchange_rate_service/__init__.py +++ b/examples/dfp/v201608/exchange_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py index 64dbfed7..fda130a0 100755 --- a/examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py index 312c5213..0d70e0d7 100755 --- a/examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py index dd6e2b49..677769d3 100755 --- a/examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py index 9ce75995..f22fd183 100755 --- a/examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/forecast_service/get_availability_forecast.py b/examples/dfp/v201608/forecast_service/get_availability_forecast.py index c2f74c3a..634a2eaa 100755 --- a/examples/dfp/v201608/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201608/forecast_service/get_availability_forecast.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py index a23ba2fb..5231f6c3 100755 --- a/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py index e70a7bea..1741b647 100755 --- a/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/inventory_service/__init__.py b/examples/dfp/v201608/inventory_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/inventory_service/__init__.py +++ b/examples/dfp/v201608/inventory_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/inventory_service/archive_ad_units.py b/examples/dfp/v201608/inventory_service/archive_ad_units.py index a0f83f84..e700add8 100755 --- a/examples/dfp/v201608/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201608/inventory_service/archive_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/inventory_service/create_ad_units.py b/examples/dfp/v201608/inventory_service/create_ad_units.py index 8b83f144..ef0fbf7c 100755 --- a/examples/dfp/v201608/inventory_service/create_ad_units.py +++ b/examples/dfp/v201608/inventory_service/create_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py index 953f1269..23eb21dc 100755 --- a/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/inventory_service/get_all_ad_units.py b/examples/dfp/v201608/inventory_service/get_all_ad_units.py index bd058720..61c80387 100755 --- a/examples/dfp/v201608/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201608/inventory_service/get_all_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/inventory_service/update_ad_units.py b/examples/dfp/v201608/inventory_service/update_ad_units.py index f2366d35..e02d7c12 100755 --- a/examples/dfp/v201608/inventory_service/update_ad_units.py +++ b/examples/dfp/v201608/inventory_service/update_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/label_service/__init__.py b/examples/dfp/v201608/label_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/label_service/__init__.py +++ b/examples/dfp/v201608/label_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/label_service/create_labels.py b/examples/dfp/v201608/label_service/create_labels.py index 71c92934..87fa8cf5 100755 --- a/examples/dfp/v201608/label_service/create_labels.py +++ b/examples/dfp/v201608/label_service/create_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/label_service/deactivate_labels.py b/examples/dfp/v201608/label_service/deactivate_labels.py index a77bca6f..b4920666 100755 --- a/examples/dfp/v201608/label_service/deactivate_labels.py +++ b/examples/dfp/v201608/label_service/deactivate_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/label_service/get_active_labels.py b/examples/dfp/v201608/label_service/get_active_labels.py index 549f79bc..ad8592a9 100755 --- a/examples/dfp/v201608/label_service/get_active_labels.py +++ b/examples/dfp/v201608/label_service/get_active_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/label_service/get_all_labels.py b/examples/dfp/v201608/label_service/get_all_labels.py index e8c29f8f..5545fc13 100755 --- a/examples/dfp/v201608/label_service/get_all_labels.py +++ b/examples/dfp/v201608/label_service/get_all_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/label_service/update_labels.py b/examples/dfp/v201608/label_service/update_labels.py index 5b3f1596..6403ad95 100755 --- a/examples/dfp/v201608/label_service/update_labels.py +++ b/examples/dfp/v201608/label_service/update_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_creative_association_service/__init__.py b/examples/dfp/v201608/line_item_creative_association_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/line_item_creative_association_service/__init__.py +++ b/examples/dfp/v201608/line_item_creative_association_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_creative_association_service/create_licas.py b/examples/dfp/v201608/line_item_creative_association_service/create_licas.py index 47e9e67e..1700f5d9 100755 --- a/examples/dfp/v201608/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201608/line_item_creative_association_service/create_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py index 92f350f7..29ed4a79 100755 --- a/examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py index c4a41691..5ba3194c 100755 --- a/examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py index 13265dee..4909f8f8 100755 --- a/examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_creative_association_service/update_licas.py b/examples/dfp/v201608/line_item_creative_association_service/update_licas.py index cf9b1f35..2327f44d 100755 --- a/examples/dfp/v201608/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201608/line_item_creative_association_service/update_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/__init__.py b/examples/dfp/v201608/line_item_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/line_item_service/__init__.py +++ b/examples/dfp/v201608/line_item_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/activate_line_items.py b/examples/dfp/v201608/line_item_service/activate_line_items.py index 66e0bb41..ac4d87df 100755 --- a/examples/dfp/v201608/line_item_service/activate_line_items.py +++ b/examples/dfp/v201608/line_item_service/activate_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/create_line_items.py b/examples/dfp/v201608/line_item_service/create_line_items.py index 922e170b..b9ef8c80 100755 --- a/examples/dfp/v201608/line_item_service/create_line_items.py +++ b/examples/dfp/v201608/line_item_service/create_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/create_video_line_item.py b/examples/dfp/v201608/line_item_service/create_video_line_item.py index 06a34de7..644706dd 100755 --- a/examples/dfp/v201608/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201608/line_item_service/create_video_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/get_all_line_items.py b/examples/dfp/v201608/line_item_service/get_all_line_items.py index 99a8c84f..dd1c08d2 100755 --- a/examples/dfp/v201608/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201608/line_item_service/get_all_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py index c67e7bef..8f987767 100755 --- a/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py index dd3edd39..e542720f 100755 --- a/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/target_custom_criteria.py b/examples/dfp/v201608/line_item_service/target_custom_criteria.py index 5ff0a04f..f8c524d5 100755 --- a/examples/dfp/v201608/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201608/line_item_service/target_custom_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/line_item_service/update_line_items.py b/examples/dfp/v201608/line_item_service/update_line_items.py index 845a2864..56b2dbd1 100755 --- a/examples/dfp/v201608/line_item_service/update_line_items.py +++ b/examples/dfp/v201608/line_item_service/update_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/network_service/__init__.py b/examples/dfp/v201608/network_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/network_service/__init__.py +++ b/examples/dfp/v201608/network_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/network_service/get_all_networks.py b/examples/dfp/v201608/network_service/get_all_networks.py index a3683152..cdd3141d 100755 --- a/examples/dfp/v201608/network_service/get_all_networks.py +++ b/examples/dfp/v201608/network_service/get_all_networks.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/network_service/make_test_network.py b/examples/dfp/v201608/network_service/make_test_network.py index d1f4cebc..2dcf80ab 100755 --- a/examples/dfp/v201608/network_service/make_test_network.py +++ b/examples/dfp/v201608/network_service/make_test_network.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/order_service/__init__.py b/examples/dfp/v201608/order_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/order_service/__init__.py +++ b/examples/dfp/v201608/order_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/order_service/approve_orders.py b/examples/dfp/v201608/order_service/approve_orders.py index fce28cbd..717ed821 100755 --- a/examples/dfp/v201608/order_service/approve_orders.py +++ b/examples/dfp/v201608/order_service/approve_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/order_service/create_orders.py b/examples/dfp/v201608/order_service/create_orders.py index 26babf04..328dc96c 100755 --- a/examples/dfp/v201608/order_service/create_orders.py +++ b/examples/dfp/v201608/order_service/create_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/order_service/get_all_orders.py b/examples/dfp/v201608/order_service/get_all_orders.py index aebbacd3..cda0e5b5 100755 --- a/examples/dfp/v201608/order_service/get_all_orders.py +++ b/examples/dfp/v201608/order_service/get_all_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/order_service/get_orders_starting_soon.py b/examples/dfp/v201608/order_service/get_orders_starting_soon.py index 1c3bcbd4..5a7e4dce 100755 --- a/examples/dfp/v201608/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201608/order_service/get_orders_starting_soon.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/order_service/update_orders.py b/examples/dfp/v201608/order_service/update_orders.py index fa0496a6..97877b93 100755 --- a/examples/dfp/v201608/order_service/update_orders.py +++ b/examples/dfp/v201608/order_service/update_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/package_service/get_all_packages.py b/examples/dfp/v201608/package_service/get_all_packages.py index 8987bd1e..06e9028b 100755 --- a/examples/dfp/v201608/package_service/get_all_packages.py +++ b/examples/dfp/v201608/package_service/get_all_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/package_service/get_in_progress_packages.py b/examples/dfp/v201608/package_service/get_in_progress_packages.py index e3c9eabb..63eb3236 100755 --- a/examples/dfp/v201608/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201608/package_service/get_in_progress_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/placement_service/create_placements.py b/examples/dfp/v201608/placement_service/create_placements.py index f7cc56d6..5fa3b8f4 100755 --- a/examples/dfp/v201608/placement_service/create_placements.py +++ b/examples/dfp/v201608/placement_service/create_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/placement_service/deactivate_placements.py b/examples/dfp/v201608/placement_service/deactivate_placements.py index fbc79d28..2692beb4 100755 --- a/examples/dfp/v201608/placement_service/deactivate_placements.py +++ b/examples/dfp/v201608/placement_service/deactivate_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/placement_service/get_active_placements.py b/examples/dfp/v201608/placement_service/get_active_placements.py index 30eb771a..b08873e5 100755 --- a/examples/dfp/v201608/placement_service/get_active_placements.py +++ b/examples/dfp/v201608/placement_service/get_active_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/placement_service/get_all_placements.py b/examples/dfp/v201608/placement_service/get_all_placements.py index 4c710f06..71ac94b8 100755 --- a/examples/dfp/v201608/placement_service/get_all_placements.py +++ b/examples/dfp/v201608/placement_service/get_all_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/placement_service/update_placements.py b/examples/dfp/v201608/placement_service/update_placements.py index 8d50585b..08dccfab 100755 --- a/examples/dfp/v201608/placement_service/update_placements.py +++ b/examples/dfp/v201608/placement_service/update_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/premium_rate_service/__init__.py b/examples/dfp/v201608/premium_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/premium_rate_service/__init__.py +++ b/examples/dfp/v201608/premium_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/premium_rate_service/create_premium_rates.py b/examples/dfp/v201608/premium_rate_service/create_premium_rates.py index e051d77b..be1ce13b 100755 --- a/examples/dfp/v201608/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201608/premium_rate_service/create_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py index 6f6dc23a..5681a90a 100755 --- a/examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py index 41ff2610..77d438e9 100755 --- a/examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/premium_rate_service/update_premium_rates.py b/examples/dfp/v201608/premium_rate_service/update_premium_rates.py index 81a10c0e..4c622a15 100755 --- a/examples/dfp/v201608/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201608/premium_rate_service/update_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py index 41e1d638..b21d7dbb 100755 --- a/examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py index 075dd635..0cff0fa3 100755 --- a/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_package_service/get_active_product_packages.py b/examples/dfp/v201608/product_package_service/get_active_product_packages.py index dc73e915..2bcc5003 100755 --- a/examples/dfp/v201608/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201608/product_package_service/get_active_product_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_package_service/get_all_product_packages.py b/examples/dfp/v201608/product_package_service/get_all_product_packages.py index 16b03d95..f58ebd2e 100755 --- a/examples/dfp/v201608/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201608/product_package_service/get_all_product_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_service/__init__.py b/examples/dfp/v201608/product_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/product_service/__init__.py +++ b/examples/dfp/v201608/product_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py index 87bb3363..775fa153 100755 --- a/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py +++ b/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_service/get_all_products.py b/examples/dfp/v201608/product_service/get_all_products.py index 468bd05a..4895956f 100755 --- a/examples/dfp/v201608/product_service/get_all_products.py +++ b/examples/dfp/v201608/product_service/get_all_products.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_service/get_products_for_product_template.py b/examples/dfp/v201608/product_service/get_products_for_product_template.py index 2072df12..7f1d5bef 100755 --- a/examples/dfp/v201608/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201608/product_service/get_products_for_product_template.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py index 63173a32..9ca606ac 100755 --- a/examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_service/update_products.py b/examples/dfp/v201608/product_service/update_products.py index ac4e1e3f..5c217d8e 100755 --- a/examples/dfp/v201608/product_service/update_products.py +++ b/examples/dfp/v201608/product_service/update_products.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_template_service/__init__.py b/examples/dfp/v201608/product_template_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/product_template_service/__init__.py +++ b/examples/dfp/v201608/product_template_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_template_service/activate_product_templates.py b/examples/dfp/v201608/product_template_service/activate_product_templates.py index d67f931c..cf41d3d9 100755 --- a/examples/dfp/v201608/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201608/product_template_service/activate_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_template_service/create_product_templates.py b/examples/dfp/v201608/product_template_service/create_product_templates.py index e8d244ec..929a563c 100755 --- a/examples/dfp/v201608/product_template_service/create_product_templates.py +++ b/examples/dfp/v201608/product_template_service/create_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py index bd38db83..4d9d9b9a 100755 --- a/examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_template_service/get_all_product_templates.py b/examples/dfp/v201608/product_template_service/get_all_product_templates.py index 5fe8887e..df1394a7 100755 --- a/examples/dfp/v201608/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201608/product_template_service/get_all_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py index cf412570..6c318ef4 100755 --- a/examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/product_template_service/update_product_templates.py b/examples/dfp/v201608/product_template_service/update_product_templates.py index 7201cc3c..eca3fd52 100755 --- a/examples/dfp/v201608/product_template_service/update_product_templates.py +++ b/examples/dfp/v201608/product_template_service/update_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_line_item_service/__init__.py b/examples/dfp/v201608/proposal_line_item_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/proposal_line_item_service/__init__.py +++ b/examples/dfp/v201608/proposal_line_item_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py index 88401b33..0fa549ce 100755 --- a/examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py index 7642027b..c52f90a9 100755 --- a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 012ab4c5..9dfad61b 100755 --- a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py index 33f236d6..29521952 100755 --- a/examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py index 439551e6..37ae497b 100755 --- a/examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py index c0c6d1bb..a52804ca 100755 --- a/examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py index e4ad0ba7..4299d7f4 100755 --- a/examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/__init__.py b/examples/dfp/v201608/proposal_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/proposal_service/__init__.py +++ b/examples/dfp/v201608/proposal_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201608/proposal_service/create_programmatic_proposals.py index bb98fe3a..04266ff5 100755 --- a/examples/dfp/v201608/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201608/proposal_service/create_programmatic_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 59b9d20e..b9aca741 100755 --- a/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/create_proposals.py b/examples/dfp/v201608/proposal_service/create_proposals.py index 56ec41bc..14ae2c1c 100755 --- a/examples/dfp/v201608/proposal_service/create_proposals.py +++ b/examples/dfp/v201608/proposal_service/create_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/get_all_proposals.py b/examples/dfp/v201608/proposal_service/get_all_proposals.py index fefa06a8..96987d15 100755 --- a/examples/dfp/v201608/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201608/proposal_service/get_all_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/get_marketplace_comments.py b/examples/dfp/v201608/proposal_service/get_marketplace_comments.py index 87f64a58..ded14548 100755 --- a/examples/dfp/v201608/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201608/proposal_service/get_marketplace_comments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py index d798ca99..5e70b964 100755 --- a/examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201608/proposal_service/request_buyers_acceptance.py index d1600595..b8d8dc0e 100755 --- a/examples/dfp/v201608/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201608/proposal_service/request_buyers_acceptance.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py index 8fae1df9..d305bb24 100755 --- a/examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/proposal_service/update_proposals.py b/examples/dfp/v201608/proposal_service/update_proposals.py index 5bf73026..af7d29c8 100755 --- a/examples/dfp/v201608/proposal_service/update_proposals.py +++ b/examples/dfp/v201608/proposal_service/update_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/publisher_query_language_service/__init__.py b/examples/dfp/v201608/publisher_query_language_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/publisher_query_language_service/__init__.py +++ b/examples/dfp/v201608/publisher_query_language_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py index 599ee25e..fe6ca7f1 100755 --- a/examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py index 71299e31..8dfb20cb 100755 --- a/examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/rate_card_service/__init__.py b/examples/dfp/v201608/rate_card_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/rate_card_service/__init__.py +++ b/examples/dfp/v201608/rate_card_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201608/rate_card_service/get_all_rate_cards.py index e9d4f15b..0a0dd758 100755 --- a/examples/dfp/v201608/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201608/rate_card_service/get_all_rate_cards.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py index 9c0c9624..a0f6cb73 100755 --- a/examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index aa1c8254..d38cbfad 100755 --- a/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index e350d000..a99a5cfc 100755 --- a/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 622b9a6d..38bbd31e 100755 --- a/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py index 7e33afe2..afda42dc 100755 --- a/examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index f67a4e85..315a976e 100755 --- a/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/report_service/__init__.py b/examples/dfp/v201608/report_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/report_service/__init__.py +++ b/examples/dfp/v201608/report_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/report_service/run_delivery_report.py b/examples/dfp/v201608/report_service/run_delivery_report.py index f341a0bb..8ae035f8 100755 --- a/examples/dfp/v201608/report_service/run_delivery_report.py +++ b/examples/dfp/v201608/report_service/run_delivery_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/report_service/run_inventory_report.py b/examples/dfp/v201608/report_service/run_inventory_report.py index 7decb0e8..2eee56d8 100755 --- a/examples/dfp/v201608/report_service/run_inventory_report.py +++ b/examples/dfp/v201608/report_service/run_inventory_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/report_service/run_reach_report.py b/examples/dfp/v201608/report_service/run_reach_report.py index 0211681c..7b2dadf0 100755 --- a/examples/dfp/v201608/report_service/run_reach_report.py +++ b/examples/dfp/v201608/report_service/run_reach_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/report_service/run_report_with_custom_fields.py b/examples/dfp/v201608/report_service/run_report_with_custom_fields.py index 56d735e3..9cb816a2 100755 --- a/examples/dfp/v201608/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201608/report_service/run_report_with_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/report_service/run_sales_report.py b/examples/dfp/v201608/report_service/run_sales_report.py index 800aeb8c..69e52577 100755 --- a/examples/dfp/v201608/report_service/run_sales_report.py +++ b/examples/dfp/v201608/report_service/run_sales_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/report_service/run_saved_query.py b/examples/dfp/v201608/report_service/run_saved_query.py index c7987626..fcaba920 100755 --- a/examples/dfp/v201608/report_service/run_saved_query.py +++ b/examples/dfp/v201608/report_service/run_saved_query.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/suggested_ad_unit_service/__init__.py b/examples/dfp/v201608/suggested_ad_unit_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/suggested_ad_unit_service/__init__.py +++ b/examples/dfp/v201608/suggested_ad_unit_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 4d1eac0c..11d8734a 100755 --- a/examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py index 17d32080..6683d068 100755 --- a/examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 2f833695..f1c3bc1f 100755 --- a/examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/team_service/__init__.py b/examples/dfp/v201608/team_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/team_service/__init__.py +++ b/examples/dfp/v201608/team_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/team_service/create_teams.py b/examples/dfp/v201608/team_service/create_teams.py index b15bdde4..3f2f2f9e 100755 --- a/examples/dfp/v201608/team_service/create_teams.py +++ b/examples/dfp/v201608/team_service/create_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/team_service/get_all_teams.py b/examples/dfp/v201608/team_service/get_all_teams.py index 7f690498..6ac1b1df 100755 --- a/examples/dfp/v201608/team_service/get_all_teams.py +++ b/examples/dfp/v201608/team_service/get_all_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/team_service/update_teams.py b/examples/dfp/v201608/team_service/update_teams.py index 8808b777..8643aa5e 100755 --- a/examples/dfp/v201608/team_service/update_teams.py +++ b/examples/dfp/v201608/team_service/update_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_service/__init__.py b/examples/dfp/v201608/user_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/user_service/__init__.py +++ b/examples/dfp/v201608/user_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_service/create_users.py b/examples/dfp/v201608/user_service/create_users.py index 5bf833cf..08cff403 100755 --- a/examples/dfp/v201608/user_service/create_users.py +++ b/examples/dfp/v201608/user_service/create_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_service/deactivate_users.py b/examples/dfp/v201608/user_service/deactivate_users.py index 8bb427dc..ff9459db 100755 --- a/examples/dfp/v201608/user_service/deactivate_users.py +++ b/examples/dfp/v201608/user_service/deactivate_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_service/get_all_roles.py b/examples/dfp/v201608/user_service/get_all_roles.py index 03f79651..fb763029 100755 --- a/examples/dfp/v201608/user_service/get_all_roles.py +++ b/examples/dfp/v201608/user_service/get_all_roles.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_service/get_all_users.py b/examples/dfp/v201608/user_service/get_all_users.py index 5b915268..e211603a 100755 --- a/examples/dfp/v201608/user_service/get_all_users.py +++ b/examples/dfp/v201608/user_service/get_all_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_service/get_user_by_email_address.py b/examples/dfp/v201608/user_service/get_user_by_email_address.py index d26e58c4..cd80b395 100755 --- a/examples/dfp/v201608/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201608/user_service/get_user_by_email_address.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_service/update_users.py b/examples/dfp/v201608/user_service/update_users.py index debc4b75..62ca0c22 100755 --- a/examples/dfp/v201608/user_service/update_users.py +++ b/examples/dfp/v201608/user_service/update_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_team_association_service/__init__.py b/examples/dfp/v201608/user_team_association_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/user_team_association_service/__init__.py +++ b/examples/dfp/v201608/user_team_association_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201608/user_team_association_service/create_user_team_associations.py index f917e63c..d0fe60e5 100755 --- a/examples/dfp/v201608/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201608/user_team_association_service/create_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py index d29636e3..94d3c7a9 100755 --- a/examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py index 9b4ea627..29e8afc2 100755 --- a/examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py index 9df23eaa..52bc299f 100755 --- a/examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201608/user_team_association_service/update_user_team_associations.py index 638782e1..a351b14a 100755 --- a/examples/dfp/v201608/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201608/user_team_association_service/update_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/workflow_request_service/__init__.py b/examples/dfp/v201608/workflow_request_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201608/workflow_request_service/__init__.py +++ b/examples/dfp/v201608/workflow_request_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py index 958c0c09..a5610f83 100755 --- a/examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py index 5fc2332b..762f890f 100755 --- a/examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py index aa7bbf25..f1db169a 100755 --- a/examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py index bac97e0b..7d2795a2 100755 --- a/examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_group_service/__init__.py b/examples/dfp/v201611/activity_group_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/activity_group_service/__init__.py +++ b/examples/dfp/v201611/activity_group_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_group_service/create_activity_groups.py b/examples/dfp/v201611/activity_group_service/create_activity_groups.py index 45f1487b..521c3614 100755 --- a/examples/dfp/v201611/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/create_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py index 55284d6c..c6dd6db3 100755 --- a/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py index a2b2290c..ab7f822a 100755 --- a/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_group_service/update_activity_groups.py b/examples/dfp/v201611/activity_group_service/update_activity_groups.py index b2cb9bf1..16f81c5d 100755 --- a/examples/dfp/v201611/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/update_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_service/__init__.py b/examples/dfp/v201611/activity_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/activity_service/__init__.py +++ b/examples/dfp/v201611/activity_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_service/create_activities.py b/examples/dfp/v201611/activity_service/create_activities.py index c8ff8e9e..539b3284 100755 --- a/examples/dfp/v201611/activity_service/create_activities.py +++ b/examples/dfp/v201611/activity_service/create_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_service/get_active_activities.py b/examples/dfp/v201611/activity_service/get_active_activities.py index b04b9566..45cf581f 100755 --- a/examples/dfp/v201611/activity_service/get_active_activities.py +++ b/examples/dfp/v201611/activity_service/get_active_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_service/get_all_activities.py b/examples/dfp/v201611/activity_service/get_all_activities.py index d7eca262..345093be 100755 --- a/examples/dfp/v201611/activity_service/get_all_activities.py +++ b/examples/dfp/v201611/activity_service/get_all_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_service/update_activities.py b/examples/dfp/v201611/activity_service/update_activities.py index d29a2d36..e29e25da 100755 --- a/examples/dfp/v201611/activity_service/update_activities.py +++ b/examples/dfp/v201611/activity_service/update_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/audience_segment_service/__init__.py b/examples/dfp/v201611/audience_segment_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/audience_segment_service/__init__.py +++ b/examples/dfp/v201611/audience_segment_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/audience_segment_service/create_audience_segments.py b/examples/dfp/v201611/audience_segment_service/create_audience_segments.py index b463e4c3..a6e0761b 100755 --- a/examples/dfp/v201611/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/create_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py index 815e5495..363cf3e3 100755 --- a/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py index d220c92e..b7e7b758 100755 --- a/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py index 78f63c91..c4056096 100755 --- a/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/audience_segment_service/update_audience_segments.py b/examples/dfp/v201611/audience_segment_service/update_audience_segments.py index b6ceea81..af75ab18 100755 --- a/examples/dfp/v201611/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/update_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/base_rate_service/__init__.py b/examples/dfp/v201611/base_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/base_rate_service/__init__.py +++ b/examples/dfp/v201611/base_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/base_rate_service/create_product_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_base_rates.py index 96e50bc7..35207890 100755 --- a/examples/dfp/v201611/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/create_product_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py index d96eb469..61556bbb 100755 --- a/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/base_rate_service/get_all_base_rates.py b/examples/dfp/v201611/base_rate_service/get_all_base_rates.py index a49c3838..280a4a44 100755 --- a/examples/dfp/v201611/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/get_all_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py index 02728d9f..6601eb10 100755 --- a/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/base_rate_service/update_base_rates.py b/examples/dfp/v201611/base_rate_service/update_base_rates.py index ab15fe5e..e2ac2cff 100755 --- a/examples/dfp/v201611/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/update_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/company_service/__init__.py b/examples/dfp/v201611/company_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/company_service/__init__.py +++ b/examples/dfp/v201611/company_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/company_service/create_companies.py b/examples/dfp/v201611/company_service/create_companies.py index b9e7d07c..7acb193d 100755 --- a/examples/dfp/v201611/company_service/create_companies.py +++ b/examples/dfp/v201611/company_service/create_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/company_service/get_advertisers.py b/examples/dfp/v201611/company_service/get_advertisers.py index 2b0ba1b5..6d651cec 100755 --- a/examples/dfp/v201611/company_service/get_advertisers.py +++ b/examples/dfp/v201611/company_service/get_advertisers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/company_service/get_all_companies.py b/examples/dfp/v201611/company_service/get_all_companies.py index 8a4a6937..6cf9e4b2 100755 --- a/examples/dfp/v201611/company_service/get_all_companies.py +++ b/examples/dfp/v201611/company_service/get_all_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/company_service/update_companies.py b/examples/dfp/v201611/company_service/update_companies.py index 3bf0e14b..774966df 100755 --- a/examples/dfp/v201611/company_service/update_companies.py +++ b/examples/dfp/v201611/company_service/update_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/contact_service/__init__.py b/examples/dfp/v201611/contact_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/contact_service/__init__.py +++ b/examples/dfp/v201611/contact_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/contact_service/create_contacts.py b/examples/dfp/v201611/contact_service/create_contacts.py index 9854ab64..3240fdd5 100755 --- a/examples/dfp/v201611/contact_service/create_contacts.py +++ b/examples/dfp/v201611/contact_service/create_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/contact_service/get_all_contacts.py b/examples/dfp/v201611/contact_service/get_all_contacts.py index 594f9422..690cf588 100755 --- a/examples/dfp/v201611/contact_service/get_all_contacts.py +++ b/examples/dfp/v201611/contact_service/get_all_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/contact_service/get_uninvited_contacts.py b/examples/dfp/v201611/contact_service/get_uninvited_contacts.py index 7e98ec79..8d84ca0c 100755 --- a/examples/dfp/v201611/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201611/contact_service/get_uninvited_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/contact_service/update_contacts.py b/examples/dfp/v201611/contact_service/update_contacts.py index a4fbac28..c2f5f4ad 100755 --- a/examples/dfp/v201611/contact_service/update_contacts.py +++ b/examples/dfp/v201611/contact_service/update_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index ab288f07..f272dd75 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index e815b89a..8bcc1134 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 795c7f0c..1d4bb01d 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index c463f7ea..26cb8769 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/content_service/__init__.py b/examples/dfp/v201611/content_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/content_service/__init__.py +++ b/examples/dfp/v201611/content_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/content_service/get_all_content.py b/examples/dfp/v201611/content_service/get_all_content.py index 8e4ab458..6e8f8e12 100755 --- a/examples/dfp/v201611/content_service/get_all_content.py +++ b/examples/dfp/v201611/content_service/get_all_content.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_service/__init__.py b/examples/dfp/v201611/creative_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/creative_service/__init__.py +++ b/examples/dfp/v201611/creative_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_service/create_creative_from_template.py b/examples/dfp/v201611/creative_service/create_creative_from_template.py index 1024497e..6be13e5a 100755 --- a/examples/dfp/v201611/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201611/creative_service/create_creative_from_template.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_service/create_creatives.py b/examples/dfp/v201611/creative_service/create_creatives.py index 4ee153b9..f08ae12b 100755 --- a/examples/dfp/v201611/creative_service/create_creatives.py +++ b/examples/dfp/v201611/creative_service/create_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_service/create_custom_creative.py b/examples/dfp/v201611/creative_service/create_custom_creative.py index 2a1fe137..1e49b3ec 100755 --- a/examples/dfp/v201611/creative_service/create_custom_creative.py +++ b/examples/dfp/v201611/creative_service/create_custom_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_service/create_native_creative.py b/examples/dfp/v201611/creative_service/create_native_creative.py index 0e3a86cc..29f6c7c3 100755 --- a/examples/dfp/v201611/creative_service/create_native_creative.py +++ b/examples/dfp/v201611/creative_service/create_native_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_service/get_all_creatives.py b/examples/dfp/v201611/creative_service/get_all_creatives.py index 265d9a7b..d2689507 100755 --- a/examples/dfp/v201611/creative_service/get_all_creatives.py +++ b/examples/dfp/v201611/creative_service/get_all_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_service/get_image_creatives.py b/examples/dfp/v201611/creative_service/get_image_creatives.py index 6e85199d..7e628eaf 100755 --- a/examples/dfp/v201611/creative_service/get_image_creatives.py +++ b/examples/dfp/v201611/creative_service/get_image_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_service/update_creatives.py b/examples/dfp/v201611/creative_service/update_creatives.py index 582247af..aa982eaa 100755 --- a/examples/dfp/v201611/creative_service/update_creatives.py +++ b/examples/dfp/v201611/creative_service/update_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_set_service/__init__.py b/examples/dfp/v201611/creative_set_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/creative_set_service/__init__.py +++ b/examples/dfp/v201611/creative_set_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py index cc4e5038..f88a402d 100755 --- a/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_set_service/create_creative_set.py b/examples/dfp/v201611/creative_set_service/create_creative_set.py index a245b268..dcacbebb 100755 --- a/examples/dfp/v201611/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201611/creative_set_service/create_creative_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py index 967241a8..c335a39d 100755 --- a/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py index cd17ab52..c8b6e7b3 100755 --- a/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_set_service/update_creative_set.py b/examples/dfp/v201611/creative_set_service/update_creative_set.py index cc23b187..06593b9e 100755 --- a/examples/dfp/v201611/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201611/creative_set_service/update_creative_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_template_service/__init__.py b/examples/dfp/v201611/creative_template_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/creative_template_service/__init__.py +++ b/examples/dfp/v201611/creative_template_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py index b13ab25d..da163f3f 100755 --- a/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py index dec095f0..d8ec1221 100755 --- a/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py index e648addf..8ca0984b 100755 --- a/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py index df05fd69..503a8096 100755 --- a/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py index 5f0c04c5..e03ad03c 100755 --- a/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py index ce3f2887..70375e7a 100755 --- a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py index e5cc273b..267b2d80 100755 --- a/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_field_service/__init__.py b/examples/dfp/v201611/custom_field_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/custom_field_service/__init__.py +++ b/examples/dfp/v201611/custom_field_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_field_service/create_custom_field_options.py b/examples/dfp/v201611/custom_field_service/create_custom_field_options.py index d23e1ad0..f034bbcd 100755 --- a/examples/dfp/v201611/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201611/custom_field_service/create_custom_field_options.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_field_service/create_custom_fields.py b/examples/dfp/v201611/custom_field_service/create_custom_fields.py index 7f092cd6..187278cd 100755 --- a/examples/dfp/v201611/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/create_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py index 7122d3bf..c30fbaf3 100755 --- a/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py index f2b116f4..52c3644a 100755 --- a/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py index c1f374bb..3619465e 100755 --- a/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py index 34551829..b9b5733e 100755 --- a/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_field_service/update_custom_fields.py b/examples/dfp/v201611/custom_field_service/update_custom_fields.py index 5e38cb3e..07bd3139 100755 --- a/examples/dfp/v201611/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/update_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_targeting_service/__init__.py b/examples/dfp/v201611/custom_targeting_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/custom_targeting_service/__init__.py +++ b/examples/dfp/v201611/custom_targeting_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py index 1c5ffc2b..e73d10dc 100755 --- a/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py index 9e902a0e..f0a506ad 100755 --- a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py index 4c7969bd..04741b86 100755 --- a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 33f31780..0299462f 100755 --- a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 67680326..eb30a6c4 100755 --- a/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py index 0d2b665e..ab5538e3 100755 --- a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py index dc16b89a..2f5c0389 100755 --- a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/exchange_rate_service/__init__.py b/examples/dfp/v201611/exchange_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/exchange_rate_service/__init__.py +++ b/examples/dfp/v201611/exchange_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py index bed9b04c..8c01eea9 100755 --- a/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py index 0782d282..87cf9558 100755 --- a/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py index ad5b8c5b..15d04ceb 100755 --- a/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py index 40a14446..438e9245 100755 --- a/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/forecast_service/get_availability_forecast.py b/examples/dfp/v201611/forecast_service/get_availability_forecast.py index f2175a8d..c3f2d621 100755 --- a/examples/dfp/v201611/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201611/forecast_service/get_availability_forecast.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py index f7bd982f..d929dd42 100755 --- a/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py index 9ad38bcc..b0b87c5f 100755 --- a/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/inventory_service/__init__.py b/examples/dfp/v201611/inventory_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/inventory_service/__init__.py +++ b/examples/dfp/v201611/inventory_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/inventory_service/archive_ad_units.py b/examples/dfp/v201611/inventory_service/archive_ad_units.py index 530e0b23..0e2a6fd9 100755 --- a/examples/dfp/v201611/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201611/inventory_service/archive_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/inventory_service/create_ad_units.py b/examples/dfp/v201611/inventory_service/create_ad_units.py index 0c8ab6a3..b1cc6bd9 100755 --- a/examples/dfp/v201611/inventory_service/create_ad_units.py +++ b/examples/dfp/v201611/inventory_service/create_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py index e0600a46..f792276c 100755 --- a/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_units.py b/examples/dfp/v201611/inventory_service/get_all_ad_units.py index ddcc06e2..115fce79 100755 --- a/examples/dfp/v201611/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201611/inventory_service/get_all_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/inventory_service/update_ad_units.py b/examples/dfp/v201611/inventory_service/update_ad_units.py index 28ed83e6..9d4d1f67 100755 --- a/examples/dfp/v201611/inventory_service/update_ad_units.py +++ b/examples/dfp/v201611/inventory_service/update_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/label_service/__init__.py b/examples/dfp/v201611/label_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/label_service/__init__.py +++ b/examples/dfp/v201611/label_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/label_service/create_labels.py b/examples/dfp/v201611/label_service/create_labels.py index 5e9cfe19..1afd27e1 100755 --- a/examples/dfp/v201611/label_service/create_labels.py +++ b/examples/dfp/v201611/label_service/create_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/label_service/deactivate_labels.py b/examples/dfp/v201611/label_service/deactivate_labels.py index c65fadef..61fc288d 100755 --- a/examples/dfp/v201611/label_service/deactivate_labels.py +++ b/examples/dfp/v201611/label_service/deactivate_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/label_service/get_active_labels.py b/examples/dfp/v201611/label_service/get_active_labels.py index 2fecfce8..6783a30b 100755 --- a/examples/dfp/v201611/label_service/get_active_labels.py +++ b/examples/dfp/v201611/label_service/get_active_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/label_service/get_all_labels.py b/examples/dfp/v201611/label_service/get_all_labels.py index b06bd23c..f1e248ab 100755 --- a/examples/dfp/v201611/label_service/get_all_labels.py +++ b/examples/dfp/v201611/label_service/get_all_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/label_service/update_labels.py b/examples/dfp/v201611/label_service/update_labels.py index 71ea8045..008b7913 100755 --- a/examples/dfp/v201611/label_service/update_labels.py +++ b/examples/dfp/v201611/label_service/update_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_creative_association_service/__init__.py b/examples/dfp/v201611/line_item_creative_association_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/__init__.py +++ b/examples/dfp/v201611/line_item_creative_association_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_creative_association_service/create_licas.py b/examples/dfp/v201611/line_item_creative_association_service/create_licas.py index fee354cd..8f38c48b 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/create_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py index 81efb3b4..7a31fc78 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py index 233a83c6..8d836a15 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py index ab1304d2..d98789ac 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py index 0593e472..54eb403c 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/__init__.py b/examples/dfp/v201611/line_item_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/line_item_service/__init__.py +++ b/examples/dfp/v201611/line_item_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/activate_line_items.py b/examples/dfp/v201611/line_item_service/activate_line_items.py index af758328..9dc51032 100755 --- a/examples/dfp/v201611/line_item_service/activate_line_items.py +++ b/examples/dfp/v201611/line_item_service/activate_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/create_line_items.py b/examples/dfp/v201611/line_item_service/create_line_items.py index b8ab25c9..6497dff0 100755 --- a/examples/dfp/v201611/line_item_service/create_line_items.py +++ b/examples/dfp/v201611/line_item_service/create_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/create_video_line_item.py b/examples/dfp/v201611/line_item_service/create_video_line_item.py index 622747a0..2e084fed 100755 --- a/examples/dfp/v201611/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201611/line_item_service/create_video_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/get_all_line_items.py b/examples/dfp/v201611/line_item_service/get_all_line_items.py index 3ba749b4..5ecc7951 100755 --- a/examples/dfp/v201611/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201611/line_item_service/get_all_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py index c53fa9e6..511926d5 100755 --- a/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py index 233611c8..09d4cc5b 100755 --- a/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/target_custom_criteria.py b/examples/dfp/v201611/line_item_service/target_custom_criteria.py index fe5f71e6..b1a47fcd 100755 --- a/examples/dfp/v201611/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201611/line_item_service/target_custom_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/line_item_service/update_line_items.py b/examples/dfp/v201611/line_item_service/update_line_items.py index 61b56f07..e9fb7c38 100755 --- a/examples/dfp/v201611/line_item_service/update_line_items.py +++ b/examples/dfp/v201611/line_item_service/update_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/network_service/__init__.py b/examples/dfp/v201611/network_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/network_service/__init__.py +++ b/examples/dfp/v201611/network_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/network_service/get_all_networks.py b/examples/dfp/v201611/network_service/get_all_networks.py index e6113c7e..d65e9d49 100755 --- a/examples/dfp/v201611/network_service/get_all_networks.py +++ b/examples/dfp/v201611/network_service/get_all_networks.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/network_service/make_test_network.py b/examples/dfp/v201611/network_service/make_test_network.py index 94475a3d..6045a0a4 100755 --- a/examples/dfp/v201611/network_service/make_test_network.py +++ b/examples/dfp/v201611/network_service/make_test_network.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/order_service/__init__.py b/examples/dfp/v201611/order_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/order_service/__init__.py +++ b/examples/dfp/v201611/order_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/order_service/approve_orders.py b/examples/dfp/v201611/order_service/approve_orders.py index cd38ac74..5638f2db 100755 --- a/examples/dfp/v201611/order_service/approve_orders.py +++ b/examples/dfp/v201611/order_service/approve_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/order_service/create_orders.py b/examples/dfp/v201611/order_service/create_orders.py index 6380d29a..cf3fcfb8 100755 --- a/examples/dfp/v201611/order_service/create_orders.py +++ b/examples/dfp/v201611/order_service/create_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/order_service/get_all_orders.py b/examples/dfp/v201611/order_service/get_all_orders.py index c13a352a..433a8ea5 100755 --- a/examples/dfp/v201611/order_service/get_all_orders.py +++ b/examples/dfp/v201611/order_service/get_all_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/order_service/get_orders_starting_soon.py b/examples/dfp/v201611/order_service/get_orders_starting_soon.py index f1e0078b..892291b0 100755 --- a/examples/dfp/v201611/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201611/order_service/get_orders_starting_soon.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/order_service/update_orders.py b/examples/dfp/v201611/order_service/update_orders.py index cd5fa27a..58a4e1dc 100755 --- a/examples/dfp/v201611/order_service/update_orders.py +++ b/examples/dfp/v201611/order_service/update_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/package_service/get_all_packages.py b/examples/dfp/v201611/package_service/get_all_packages.py index f2c0cc11..ff146100 100755 --- a/examples/dfp/v201611/package_service/get_all_packages.py +++ b/examples/dfp/v201611/package_service/get_all_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/package_service/get_in_progress_packages.py b/examples/dfp/v201611/package_service/get_in_progress_packages.py index ea5205d1..a72be863 100755 --- a/examples/dfp/v201611/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201611/package_service/get_in_progress_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/placement_service/create_placements.py b/examples/dfp/v201611/placement_service/create_placements.py index caf2bba1..58a86237 100755 --- a/examples/dfp/v201611/placement_service/create_placements.py +++ b/examples/dfp/v201611/placement_service/create_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/placement_service/deactivate_placements.py b/examples/dfp/v201611/placement_service/deactivate_placements.py index 89397713..f181f445 100755 --- a/examples/dfp/v201611/placement_service/deactivate_placements.py +++ b/examples/dfp/v201611/placement_service/deactivate_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/placement_service/get_active_placements.py b/examples/dfp/v201611/placement_service/get_active_placements.py index 37b3f34a..ed52aced 100755 --- a/examples/dfp/v201611/placement_service/get_active_placements.py +++ b/examples/dfp/v201611/placement_service/get_active_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/placement_service/get_all_placements.py b/examples/dfp/v201611/placement_service/get_all_placements.py index 7cea4522..8b567738 100755 --- a/examples/dfp/v201611/placement_service/get_all_placements.py +++ b/examples/dfp/v201611/placement_service/get_all_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/placement_service/update_placements.py b/examples/dfp/v201611/placement_service/update_placements.py index dd7a9653..ca053db2 100755 --- a/examples/dfp/v201611/placement_service/update_placements.py +++ b/examples/dfp/v201611/placement_service/update_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/premium_rate_service/__init__.py b/examples/dfp/v201611/premium_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/premium_rate_service/__init__.py +++ b/examples/dfp/v201611/premium_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/premium_rate_service/create_premium_rates.py b/examples/dfp/v201611/premium_rate_service/create_premium_rates.py index e47d9439..f55590fc 100755 --- a/examples/dfp/v201611/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/create_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py index 33ad7633..b75ad98e 100755 --- a/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py index f37dce8b..acac01fc 100755 --- a/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/premium_rate_service/update_premium_rates.py b/examples/dfp/v201611/premium_rate_service/update_premium_rates.py index 14b9bb2e..1565b78d 100755 --- a/examples/dfp/v201611/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/update_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py index 8e3efa13..661309d2 100755 --- a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py index 6841a0b2..f0f398f0 100755 --- a/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_package_service/get_active_product_packages.py b/examples/dfp/v201611/product_package_service/get_active_product_packages.py index bfd7d55c..c6e038db 100755 --- a/examples/dfp/v201611/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201611/product_package_service/get_active_product_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_package_service/get_all_product_packages.py b/examples/dfp/v201611/product_package_service/get_all_product_packages.py index 894ddcfe..3f101e1c 100755 --- a/examples/dfp/v201611/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201611/product_package_service/get_all_product_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_service/__init__.py b/examples/dfp/v201611/product_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/product_service/__init__.py +++ b/examples/dfp/v201611/product_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py index d558134f..5e876e25 100755 --- a/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py +++ b/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_service/get_all_products.py b/examples/dfp/v201611/product_service/get_all_products.py index 0767c318..9affd0eb 100755 --- a/examples/dfp/v201611/product_service/get_all_products.py +++ b/examples/dfp/v201611/product_service/get_all_products.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_service/get_products_for_product_template.py b/examples/dfp/v201611/product_service/get_products_for_product_template.py index 365c06d0..e483c802 100755 --- a/examples/dfp/v201611/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201611/product_service/get_products_for_product_template.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py index 9cf947d7..7e18932a 100755 --- a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_service/update_products.py b/examples/dfp/v201611/product_service/update_products.py index 451887d8..1b16d420 100755 --- a/examples/dfp/v201611/product_service/update_products.py +++ b/examples/dfp/v201611/product_service/update_products.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_template_service/__init__.py b/examples/dfp/v201611/product_template_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/product_template_service/__init__.py +++ b/examples/dfp/v201611/product_template_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_template_service/activate_product_templates.py b/examples/dfp/v201611/product_template_service/activate_product_templates.py index 8542de37..bdfb9d10 100755 --- a/examples/dfp/v201611/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201611/product_template_service/activate_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_template_service/create_product_templates.py b/examples/dfp/v201611/product_template_service/create_product_templates.py index b03e76e3..a9621b57 100755 --- a/examples/dfp/v201611/product_template_service/create_product_templates.py +++ b/examples/dfp/v201611/product_template_service/create_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py index 5d512740..f4f324a8 100755 --- a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_template_service/get_all_product_templates.py b/examples/dfp/v201611/product_template_service/get_all_product_templates.py index b16537ec..5cef24bb 100755 --- a/examples/dfp/v201611/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201611/product_template_service/get_all_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py index 90bdce21..5689bc2f 100755 --- a/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/product_template_service/update_product_templates.py b/examples/dfp/v201611/product_template_service/update_product_templates.py index dc957b2e..ca1024c0 100755 --- a/examples/dfp/v201611/product_template_service/update_product_templates.py +++ b/examples/dfp/v201611/product_template_service/update_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_line_item_service/__init__.py b/examples/dfp/v201611/proposal_line_item_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/proposal_line_item_service/__init__.py +++ b/examples/dfp/v201611/proposal_line_item_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py index 41f0e740..b51de1df 100755 --- a/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py index c83ca7d5..4049f29d 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 5191dca8..e48ee12b 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py index 247a7dbb..82d4f0f5 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py index bbe0ec7a..6edebf35 100755 --- a/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 302427eb..aaf6c0bd 100755 --- a/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py index f0bedf4a..4a05acda 100755 --- a/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/__init__.py b/examples/dfp/v201611/proposal_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/proposal_service/__init__.py +++ b/examples/dfp/v201611/proposal_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py index 7c55fd86..351602fb 100755 --- a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 7168c561..d710a59d 100755 --- a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/create_proposals.py b/examples/dfp/v201611/proposal_service/create_proposals.py index 0fe9be27..7c8d676f 100755 --- a/examples/dfp/v201611/proposal_service/create_proposals.py +++ b/examples/dfp/v201611/proposal_service/create_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/get_all_proposals.py b/examples/dfp/v201611/proposal_service/get_all_proposals.py index 9134abc5..0d95fb42 100755 --- a/examples/dfp/v201611/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201611/proposal_service/get_all_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/get_marketplace_comments.py b/examples/dfp/v201611/proposal_service/get_marketplace_comments.py index 663e87b8..f27b86c3 100755 --- a/examples/dfp/v201611/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201611/proposal_service/get_marketplace_comments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py index b961e67a..51471fa2 100755 --- a/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py index 3d95d901..a324420c 100755 --- a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py index c2ae4325..743e511c 100755 --- a/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/proposal_service/update_proposals.py b/examples/dfp/v201611/proposal_service/update_proposals.py index 195087fa..a1784550 100755 --- a/examples/dfp/v201611/proposal_service/update_proposals.py +++ b/examples/dfp/v201611/proposal_service/update_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/publisher_query_language_service/__init__.py b/examples/dfp/v201611/publisher_query_language_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/publisher_query_language_service/__init__.py +++ b/examples/dfp/v201611/publisher_query_language_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py index 48a6df9f..c85d1f22 100755 --- a/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py index 2c7e1596..d49d945b 100755 --- a/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/rate_card_service/__init__.py b/examples/dfp/v201611/rate_card_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/rate_card_service/__init__.py +++ b/examples/dfp/v201611/rate_card_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py index dd95a292..44e7743b 100755 --- a/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py index f41a7090..cb79ef97 100755 --- a/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 7e626152..bd042bb6 100755 --- a/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index a0a0ad7e..8f4ecfeb 100755 --- a/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index becbc4bf..ae5681f7 100755 --- a/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py index 9658cbe0..2a6ef8ac 100755 --- a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 2edadb90..e73149f9 100755 --- a/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/report_service/__init__.py b/examples/dfp/v201611/report_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/report_service/__init__.py +++ b/examples/dfp/v201611/report_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/report_service/run_delivery_report.py b/examples/dfp/v201611/report_service/run_delivery_report.py index 47fc5e46..562ae188 100755 --- a/examples/dfp/v201611/report_service/run_delivery_report.py +++ b/examples/dfp/v201611/report_service/run_delivery_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/report_service/run_inventory_report.py b/examples/dfp/v201611/report_service/run_inventory_report.py index 35fa1ef9..f4510511 100755 --- a/examples/dfp/v201611/report_service/run_inventory_report.py +++ b/examples/dfp/v201611/report_service/run_inventory_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/report_service/run_reach_report.py b/examples/dfp/v201611/report_service/run_reach_report.py index 99908ebe..723a0a34 100755 --- a/examples/dfp/v201611/report_service/run_reach_report.py +++ b/examples/dfp/v201611/report_service/run_reach_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/report_service/run_report_with_custom_fields.py b/examples/dfp/v201611/report_service/run_report_with_custom_fields.py index 9d77e614..e430231e 100755 --- a/examples/dfp/v201611/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201611/report_service/run_report_with_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/report_service/run_sales_report.py b/examples/dfp/v201611/report_service/run_sales_report.py index 58e0362d..c922edeb 100755 --- a/examples/dfp/v201611/report_service/run_sales_report.py +++ b/examples/dfp/v201611/report_service/run_sales_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/report_service/run_saved_query.py b/examples/dfp/v201611/report_service/run_saved_query.py index 97e01a14..dc4f502b 100755 --- a/examples/dfp/v201611/report_service/run_saved_query.py +++ b/examples/dfp/v201611/report_service/run_saved_query.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/suggested_ad_unit_service/__init__.py b/examples/dfp/v201611/suggested_ad_unit_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/__init__.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 425fef3f..627acc0d 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py index af992a6f..0ee867c9 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 78a35e1d..a4981ca6 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/team_service/__init__.py b/examples/dfp/v201611/team_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/team_service/__init__.py +++ b/examples/dfp/v201611/team_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/team_service/create_teams.py b/examples/dfp/v201611/team_service/create_teams.py index 5825fb3a..647a85fc 100755 --- a/examples/dfp/v201611/team_service/create_teams.py +++ b/examples/dfp/v201611/team_service/create_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/team_service/get_all_teams.py b/examples/dfp/v201611/team_service/get_all_teams.py index aff0dae6..4ed692d0 100755 --- a/examples/dfp/v201611/team_service/get_all_teams.py +++ b/examples/dfp/v201611/team_service/get_all_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/team_service/update_teams.py b/examples/dfp/v201611/team_service/update_teams.py index f8605ccd..5c9c4863 100755 --- a/examples/dfp/v201611/team_service/update_teams.py +++ b/examples/dfp/v201611/team_service/update_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_service/__init__.py b/examples/dfp/v201611/user_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/user_service/__init__.py +++ b/examples/dfp/v201611/user_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_service/create_users.py b/examples/dfp/v201611/user_service/create_users.py index e33d0849..e0d42cc8 100755 --- a/examples/dfp/v201611/user_service/create_users.py +++ b/examples/dfp/v201611/user_service/create_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_service/deactivate_users.py b/examples/dfp/v201611/user_service/deactivate_users.py index 09463ebf..3b86bc76 100755 --- a/examples/dfp/v201611/user_service/deactivate_users.py +++ b/examples/dfp/v201611/user_service/deactivate_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_service/get_all_roles.py b/examples/dfp/v201611/user_service/get_all_roles.py index 03f79651..fb763029 100755 --- a/examples/dfp/v201611/user_service/get_all_roles.py +++ b/examples/dfp/v201611/user_service/get_all_roles.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_service/get_all_users.py b/examples/dfp/v201611/user_service/get_all_users.py index 7c853784..fb7db4fb 100755 --- a/examples/dfp/v201611/user_service/get_all_users.py +++ b/examples/dfp/v201611/user_service/get_all_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_service/get_user_by_email_address.py b/examples/dfp/v201611/user_service/get_user_by_email_address.py index 8fb8320d..ae14fc25 100755 --- a/examples/dfp/v201611/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201611/user_service/get_user_by_email_address.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_service/update_users.py b/examples/dfp/v201611/user_service/update_users.py index e58b3097..5060cfb1 100755 --- a/examples/dfp/v201611/user_service/update_users.py +++ b/examples/dfp/v201611/user_service/update_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_team_association_service/__init__.py b/examples/dfp/v201611/user_team_association_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/user_team_association_service/__init__.py +++ b/examples/dfp/v201611/user_team_association_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py index 099610ec..f5ae34cb 100755 --- a/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py index 17936e8b..f096aefd 100755 --- a/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py index c1f3854c..7436e16b 100755 --- a/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py index 8b96abd9..8a939a7d 100755 --- a/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py index 2ec85897..194c51d1 100755 --- a/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/workflow_request_service/__init__.py b/examples/dfp/v201611/workflow_request_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201611/workflow_request_service/__init__.py +++ b/examples/dfp/v201611/workflow_request_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py index d749e76d..cdf9ea61 100755 --- a/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py index 53fdc773..cab51b81 100755 --- a/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py index b5c00cee..11651506 100755 --- a/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py index a7127cad..91131414 100755 --- a/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_group_service/__init__.py b/examples/dfp/v201702/activity_group_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/activity_group_service/__init__.py +++ b/examples/dfp/v201702/activity_group_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_group_service/create_activity_groups.py b/examples/dfp/v201702/activity_group_service/create_activity_groups.py index 74fa25cd..33d38425 100755 --- a/examples/dfp/v201702/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/create_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py index c4e7e4f7..a5059f06 100755 --- a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py index bd1abc49..67036748 100755 --- a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_group_service/update_activity_groups.py b/examples/dfp/v201702/activity_group_service/update_activity_groups.py index ac561ae5..bbdf03cc 100755 --- a/examples/dfp/v201702/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/update_activity_groups.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_service/__init__.py b/examples/dfp/v201702/activity_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/activity_service/__init__.py +++ b/examples/dfp/v201702/activity_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_service/create_activities.py b/examples/dfp/v201702/activity_service/create_activities.py index d5922287..509c9e0c 100755 --- a/examples/dfp/v201702/activity_service/create_activities.py +++ b/examples/dfp/v201702/activity_service/create_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_service/get_active_activities.py b/examples/dfp/v201702/activity_service/get_active_activities.py index ab6a7dbf..6f3e5f14 100755 --- a/examples/dfp/v201702/activity_service/get_active_activities.py +++ b/examples/dfp/v201702/activity_service/get_active_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_service/get_all_activities.py b/examples/dfp/v201702/activity_service/get_all_activities.py index b95a3c96..bc4e2f5f 100755 --- a/examples/dfp/v201702/activity_service/get_all_activities.py +++ b/examples/dfp/v201702/activity_service/get_all_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/activity_service/update_activities.py b/examples/dfp/v201702/activity_service/update_activities.py index 936a704a..9421c4fd 100755 --- a/examples/dfp/v201702/activity_service/update_activities.py +++ b/examples/dfp/v201702/activity_service/update_activities.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/audience_segment_service/__init__.py b/examples/dfp/v201702/audience_segment_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/audience_segment_service/__init__.py +++ b/examples/dfp/v201702/audience_segment_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py b/examples/dfp/v201702/audience_segment_service/create_audience_segments.py index 49cbc19d..44ce90de 100755 --- a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/create_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py index 75eb78fb..5c3a084d 100755 --- a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py index eb59f816..65dbc7be 100755 --- a/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py index 905ca9d7..6606ea22 100755 --- a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py b/examples/dfp/v201702/audience_segment_service/update_audience_segments.py index 9decb091..fe3bfd6d 100755 --- a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/update_audience_segments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/base_rate_service/__init__.py b/examples/dfp/v201702/base_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/base_rate_service/__init__.py +++ b/examples/dfp/v201702/base_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_base_rates.py index 4a7d1a58..3bb66784 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/create_product_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py index a54399b6..9ce5c42d 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py b/examples/dfp/v201702/base_rate_service/get_all_base_rates.py index e6d724cd..c37b8465 100755 --- a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/get_all_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py index 21863358..d72c1f61 100755 --- a/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/base_rate_service/update_base_rates.py b/examples/dfp/v201702/base_rate_service/update_base_rates.py index 2c5edad7..d80870bf 100755 --- a/examples/dfp/v201702/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/update_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/company_service/__init__.py b/examples/dfp/v201702/company_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/company_service/__init__.py +++ b/examples/dfp/v201702/company_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/company_service/create_companies.py b/examples/dfp/v201702/company_service/create_companies.py index 1882bd4b..ce54ddf5 100755 --- a/examples/dfp/v201702/company_service/create_companies.py +++ b/examples/dfp/v201702/company_service/create_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/company_service/get_advertisers.py b/examples/dfp/v201702/company_service/get_advertisers.py index 4e105f9c..7e8085ac 100755 --- a/examples/dfp/v201702/company_service/get_advertisers.py +++ b/examples/dfp/v201702/company_service/get_advertisers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/company_service/get_all_companies.py b/examples/dfp/v201702/company_service/get_all_companies.py index ea05fe58..1a91f814 100755 --- a/examples/dfp/v201702/company_service/get_all_companies.py +++ b/examples/dfp/v201702/company_service/get_all_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/company_service/update_companies.py b/examples/dfp/v201702/company_service/update_companies.py index 764898e5..f64378e1 100755 --- a/examples/dfp/v201702/company_service/update_companies.py +++ b/examples/dfp/v201702/company_service/update_companies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/contact_service/__init__.py b/examples/dfp/v201702/contact_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/contact_service/__init__.py +++ b/examples/dfp/v201702/contact_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/contact_service/create_contacts.py b/examples/dfp/v201702/contact_service/create_contacts.py index a9b1a54a..d27881c8 100755 --- a/examples/dfp/v201702/contact_service/create_contacts.py +++ b/examples/dfp/v201702/contact_service/create_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/contact_service/get_all_contacts.py b/examples/dfp/v201702/contact_service/get_all_contacts.py index 82e8cd04..1b56cbb5 100755 --- a/examples/dfp/v201702/contact_service/get_all_contacts.py +++ b/examples/dfp/v201702/contact_service/get_all_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/contact_service/get_uninvited_contacts.py b/examples/dfp/v201702/contact_service/get_uninvited_contacts.py index e6a4b8fd..def756c1 100755 --- a/examples/dfp/v201702/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201702/contact_service/get_uninvited_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/contact_service/update_contacts.py b/examples/dfp/v201702/contact_service/update_contacts.py index b851bda0..51de259a 100755 --- a/examples/dfp/v201702/contact_service/update_contacts.py +++ b/examples/dfp/v201702/contact_service/update_contacts.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 557fc76c..e637128a 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 86f8426b..ade4e7f5 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 05142739..47ea5d16 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 8e165a40..aed2bad1 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/content_service/__init__.py b/examples/dfp/v201702/content_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/content_service/__init__.py +++ b/examples/dfp/v201702/content_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/content_service/get_all_content.py b/examples/dfp/v201702/content_service/get_all_content.py index 8954f123..d1982060 100755 --- a/examples/dfp/v201702/content_service/get_all_content.py +++ b/examples/dfp/v201702/content_service/get_all_content.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/__init__.py b/examples/dfp/v201702/creative_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/creative_service/__init__.py +++ b/examples/dfp/v201702/creative_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/create_creative_from_template.py b/examples/dfp/v201702/creative_service/create_creative_from_template.py index 714abc9a..2f94513f 100755 --- a/examples/dfp/v201702/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201702/creative_service/create_creative_from_template.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/create_creatives.py b/examples/dfp/v201702/creative_service/create_creatives.py index a598af5f..1226a043 100755 --- a/examples/dfp/v201702/creative_service/create_creatives.py +++ b/examples/dfp/v201702/creative_service/create_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/create_custom_creative.py b/examples/dfp/v201702/creative_service/create_custom_creative.py index 76ef336f..d1edd5d9 100755 --- a/examples/dfp/v201702/creative_service/create_custom_creative.py +++ b/examples/dfp/v201702/creative_service/create_custom_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/create_native_creative.py b/examples/dfp/v201702/creative_service/create_native_creative.py index e5e97f84..3518ba5d 100755 --- a/examples/dfp/v201702/creative_service/create_native_creative.py +++ b/examples/dfp/v201702/creative_service/create_native_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/get_all_creatives.py b/examples/dfp/v201702/creative_service/get_all_creatives.py index ac1509ee..ccc2d0ee 100755 --- a/examples/dfp/v201702/creative_service/get_all_creatives.py +++ b/examples/dfp/v201702/creative_service/get_all_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/get_image_creatives.py b/examples/dfp/v201702/creative_service/get_image_creatives.py index 412126d9..e63a52d4 100755 --- a/examples/dfp/v201702/creative_service/get_image_creatives.py +++ b/examples/dfp/v201702/creative_service/get_image_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/update_creatives.py b/examples/dfp/v201702/creative_service/update_creatives.py index 69be89a1..ea861269 100755 --- a/examples/dfp/v201702/creative_service/update_creatives.py +++ b/examples/dfp/v201702/creative_service/update_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_set_service/__init__.py b/examples/dfp/v201702/creative_set_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/creative_set_service/__init__.py +++ b/examples/dfp/v201702/creative_set_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py index 1aaec355..424db9b5 100755 --- a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_set_service/create_creative_set.py b/examples/dfp/v201702/creative_set_service/create_creative_set.py index c87f7837..88706f8c 100755 --- a/examples/dfp/v201702/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201702/creative_set_service/create_creative_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py index 267e1a64..742cde34 100755 --- a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py index 5f2f3051..859b9aeb 100755 --- a/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_set_service/update_creative_set.py b/examples/dfp/v201702/creative_set_service/update_creative_set.py index 1d58c518..9b9090ad 100755 --- a/examples/dfp/v201702/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201702/creative_set_service/update_creative_set.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_template_service/__init__.py b/examples/dfp/v201702/creative_template_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/creative_template_service/__init__.py +++ b/examples/dfp/v201702/creative_template_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py index b3985406..bc75624f 100755 --- a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py index aa9fe7d5..b4748eba 100755 --- a/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py index 0454a5f6..8908cf82 100755 --- a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py index 49abdeab..7af7bf90 100755 --- a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py index 306379bc..c3200282 100755 --- a/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py index eaf5598b..bb42768b 100755 --- a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py index 82e240a6..c0b957ae 100755 --- a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_field_service/__init__.py b/examples/dfp/v201702/custom_field_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/custom_field_service/__init__.py +++ b/examples/dfp/v201702/custom_field_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py b/examples/dfp/v201702/custom_field_service/create_custom_field_options.py index 7e7bde3f..ae2c379c 100755 --- a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201702/custom_field_service/create_custom_field_options.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_field_service/create_custom_fields.py b/examples/dfp/v201702/custom_field_service/create_custom_fields.py index 5f920c72..c8a9f338 100755 --- a/examples/dfp/v201702/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/create_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py index 9372c683..c173b2bd 100755 --- a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py index 8d5becbf..6b982c43 100755 --- a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py index 5bdefdaf..a350fc29 100755 --- a/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py index 5ff05a70..1b35e8a4 100755 --- a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_field_service/update_custom_fields.py b/examples/dfp/v201702/custom_field_service/update_custom_fields.py index a3870535..f60032f2 100755 --- a/examples/dfp/v201702/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/update_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_targeting_service/__init__.py b/examples/dfp/v201702/custom_targeting_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/custom_targeting_service/__init__.py +++ b/examples/dfp/v201702/custom_targeting_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py index cb288480..552dab8d 100755 --- a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py index 74f8fc70..abb78c9d 100755 --- a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py index fadd57cb..84af48bb 100755 --- a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 1912920e..79e404ea 100755 --- a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index c60ab7f6..8e297f13 100755 --- a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py index 3cf70d6c..a3b58a9a 100755 --- a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py index 2bd9b015..dac99134 100755 --- a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/exchange_rate_service/__init__.py b/examples/dfp/v201702/exchange_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/exchange_rate_service/__init__.py +++ b/examples/dfp/v201702/exchange_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py index 8b93ea62..2cdc541f 100755 --- a/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py index 333120b7..8a17ff5e 100755 --- a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py index e592f678..f2b683f1 100755 --- a/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py index edaf956e..26dc9f69 100755 --- a/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast.py b/examples/dfp/v201702/forecast_service/get_availability_forecast.py index 7fc3b7fb..a55910ad 100755 --- a/examples/dfp/v201702/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201702/forecast_service/get_availability_forecast.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py index d44f1529..ea625ff7 100755 --- a/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py index c9395870..3d6187f7 100755 --- a/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/inventory_service/__init__.py b/examples/dfp/v201702/inventory_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/inventory_service/__init__.py +++ b/examples/dfp/v201702/inventory_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/inventory_service/archive_ad_units.py b/examples/dfp/v201702/inventory_service/archive_ad_units.py index b166dc31..3be7b81a 100755 --- a/examples/dfp/v201702/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201702/inventory_service/archive_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/inventory_service/create_ad_units.py b/examples/dfp/v201702/inventory_service/create_ad_units.py index f7b8aeb1..12f157f5 100755 --- a/examples/dfp/v201702/inventory_service/create_ad_units.py +++ b/examples/dfp/v201702/inventory_service/create_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py index 5cc3ffdf..3af222b4 100755 --- a/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_units.py b/examples/dfp/v201702/inventory_service/get_all_ad_units.py index cab564b9..83f9037b 100755 --- a/examples/dfp/v201702/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201702/inventory_service/get_all_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/inventory_service/update_ad_units.py b/examples/dfp/v201702/inventory_service/update_ad_units.py index 9d891df9..080cb4a7 100755 --- a/examples/dfp/v201702/inventory_service/update_ad_units.py +++ b/examples/dfp/v201702/inventory_service/update_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/label_service/__init__.py b/examples/dfp/v201702/label_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/label_service/__init__.py +++ b/examples/dfp/v201702/label_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/label_service/create_labels.py b/examples/dfp/v201702/label_service/create_labels.py index 261bbb4c..b65df339 100755 --- a/examples/dfp/v201702/label_service/create_labels.py +++ b/examples/dfp/v201702/label_service/create_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/label_service/deactivate_labels.py b/examples/dfp/v201702/label_service/deactivate_labels.py index c08bf233..49fd43af 100755 --- a/examples/dfp/v201702/label_service/deactivate_labels.py +++ b/examples/dfp/v201702/label_service/deactivate_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/label_service/get_active_labels.py b/examples/dfp/v201702/label_service/get_active_labels.py index 2a39c47e..895be48f 100755 --- a/examples/dfp/v201702/label_service/get_active_labels.py +++ b/examples/dfp/v201702/label_service/get_active_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/label_service/get_all_labels.py b/examples/dfp/v201702/label_service/get_all_labels.py index 0b655f83..9d5bcd1d 100755 --- a/examples/dfp/v201702/label_service/get_all_labels.py +++ b/examples/dfp/v201702/label_service/get_all_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/label_service/update_labels.py b/examples/dfp/v201702/label_service/update_labels.py index a0cb86ef..5cc83410 100755 --- a/examples/dfp/v201702/label_service/update_labels.py +++ b/examples/dfp/v201702/label_service/update_labels.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_creative_association_service/__init__.py b/examples/dfp/v201702/line_item_creative_association_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/__init__.py +++ b/examples/dfp/v201702/line_item_creative_association_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py b/examples/dfp/v201702/line_item_creative_association_service/create_licas.py index 1612322d..e66ebe2d 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/create_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py index e03b2837..6e835fb8 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py index c09a88a4..459bd82c 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py index fa05b0ea..6131cdaf 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py index 738a73be..775ce179 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/__init__.py b/examples/dfp/v201702/line_item_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/line_item_service/__init__.py +++ b/examples/dfp/v201702/line_item_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/activate_line_items.py b/examples/dfp/v201702/line_item_service/activate_line_items.py index 61459cd2..83f658d4 100755 --- a/examples/dfp/v201702/line_item_service/activate_line_items.py +++ b/examples/dfp/v201702/line_item_service/activate_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/create_line_items.py b/examples/dfp/v201702/line_item_service/create_line_items.py index 69002f77..d6df276d 100755 --- a/examples/dfp/v201702/line_item_service/create_line_items.py +++ b/examples/dfp/v201702/line_item_service/create_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/create_video_line_item.py b/examples/dfp/v201702/line_item_service/create_video_line_item.py index 9b7e9b4e..1c238363 100755 --- a/examples/dfp/v201702/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201702/line_item_service/create_video_line_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/get_all_line_items.py b/examples/dfp/v201702/line_item_service/get_all_line_items.py index ea5f0ee5..95d1c439 100755 --- a/examples/dfp/v201702/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201702/line_item_service/get_all_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py index f6b7e1f8..cfba2dd4 100755 --- a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py index ea286912..f23a397b 100755 --- a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/target_custom_criteria.py b/examples/dfp/v201702/line_item_service/target_custom_criteria.py index 657a8bf0..18f6258a 100755 --- a/examples/dfp/v201702/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201702/line_item_service/target_custom_criteria.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/update_line_items.py b/examples/dfp/v201702/line_item_service/update_line_items.py index 06134ddf..f380edbc 100755 --- a/examples/dfp/v201702/line_item_service/update_line_items.py +++ b/examples/dfp/v201702/line_item_service/update_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/native_style_service/__init__.py b/examples/dfp/v201702/native_style_service/__init__.py index 5d960bcb..473ddba1 100755 --- a/examples/dfp/v201702/native_style_service/__init__.py +++ b/examples/dfp/v201702/native_style_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/native_style_service/create_native_styles.py b/examples/dfp/v201702/native_style_service/create_native_styles.py index 4548575a..f1204fa2 100755 --- a/examples/dfp/v201702/native_style_service/create_native_styles.py +++ b/examples/dfp/v201702/native_style_service/create_native_styles.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/native_style_service/get_all_native_styles.py b/examples/dfp/v201702/native_style_service/get_all_native_styles.py index 17a8fa09..dbdfdfef 100755 --- a/examples/dfp/v201702/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201702/native_style_service/get_all_native_styles.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/network_service/__init__.py b/examples/dfp/v201702/network_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/network_service/__init__.py +++ b/examples/dfp/v201702/network_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/network_service/get_all_networks.py b/examples/dfp/v201702/network_service/get_all_networks.py index bd346ad1..ed1bb3ef 100755 --- a/examples/dfp/v201702/network_service/get_all_networks.py +++ b/examples/dfp/v201702/network_service/get_all_networks.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/network_service/make_test_network.py b/examples/dfp/v201702/network_service/make_test_network.py index 4b333c57..31397585 100755 --- a/examples/dfp/v201702/network_service/make_test_network.py +++ b/examples/dfp/v201702/network_service/make_test_network.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/order_service/__init__.py b/examples/dfp/v201702/order_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/order_service/__init__.py +++ b/examples/dfp/v201702/order_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/order_service/approve_orders.py b/examples/dfp/v201702/order_service/approve_orders.py index 8ad9e52c..15fdaf71 100755 --- a/examples/dfp/v201702/order_service/approve_orders.py +++ b/examples/dfp/v201702/order_service/approve_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/order_service/create_orders.py b/examples/dfp/v201702/order_service/create_orders.py index 7cc8f59e..a7bd18a9 100755 --- a/examples/dfp/v201702/order_service/create_orders.py +++ b/examples/dfp/v201702/order_service/create_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/order_service/get_all_orders.py b/examples/dfp/v201702/order_service/get_all_orders.py index a0f94440..7da87b2e 100755 --- a/examples/dfp/v201702/order_service/get_all_orders.py +++ b/examples/dfp/v201702/order_service/get_all_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/order_service/get_orders_starting_soon.py b/examples/dfp/v201702/order_service/get_orders_starting_soon.py index cf53c918..b99060c3 100755 --- a/examples/dfp/v201702/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201702/order_service/get_orders_starting_soon.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/order_service/update_orders.py b/examples/dfp/v201702/order_service/update_orders.py index 15f58e78..c4cda3e2 100755 --- a/examples/dfp/v201702/order_service/update_orders.py +++ b/examples/dfp/v201702/order_service/update_orders.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/package_service/get_all_packages.py b/examples/dfp/v201702/package_service/get_all_packages.py index d0f77ac0..f21ee014 100755 --- a/examples/dfp/v201702/package_service/get_all_packages.py +++ b/examples/dfp/v201702/package_service/get_all_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/package_service/get_in_progress_packages.py b/examples/dfp/v201702/package_service/get_in_progress_packages.py index 97a24fa7..23994ed3 100755 --- a/examples/dfp/v201702/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201702/package_service/get_in_progress_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/placement_service/create_placements.py b/examples/dfp/v201702/placement_service/create_placements.py index c13e50b5..d524bcb9 100755 --- a/examples/dfp/v201702/placement_service/create_placements.py +++ b/examples/dfp/v201702/placement_service/create_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/placement_service/deactivate_placements.py b/examples/dfp/v201702/placement_service/deactivate_placements.py index c7f6b961..7f840ec4 100755 --- a/examples/dfp/v201702/placement_service/deactivate_placements.py +++ b/examples/dfp/v201702/placement_service/deactivate_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/placement_service/get_active_placements.py b/examples/dfp/v201702/placement_service/get_active_placements.py index 83e38b82..64e4ff18 100755 --- a/examples/dfp/v201702/placement_service/get_active_placements.py +++ b/examples/dfp/v201702/placement_service/get_active_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/placement_service/get_all_placements.py b/examples/dfp/v201702/placement_service/get_all_placements.py index 4801eb48..ed3e9c41 100755 --- a/examples/dfp/v201702/placement_service/get_all_placements.py +++ b/examples/dfp/v201702/placement_service/get_all_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/placement_service/update_placements.py b/examples/dfp/v201702/placement_service/update_placements.py index daa315fa..838c6add 100755 --- a/examples/dfp/v201702/placement_service/update_placements.py +++ b/examples/dfp/v201702/placement_service/update_placements.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/premium_rate_service/__init__.py b/examples/dfp/v201702/premium_rate_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/premium_rate_service/__init__.py +++ b/examples/dfp/v201702/premium_rate_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py b/examples/dfp/v201702/premium_rate_service/create_premium_rates.py index 7e907cd2..665e3676 100755 --- a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/create_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py index fefac987..f94d682c 100755 --- a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py index 2771fd29..24349a44 100755 --- a/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py b/examples/dfp/v201702/premium_rate_service/update_premium_rates.py index e49aa68f..92f6ef31 100755 --- a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/update_premium_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py index 99a0edd9..a497fd47 100755 --- a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py index d1c92e00..439d98c4 100755 --- a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_package_service/get_active_product_packages.py b/examples/dfp/v201702/product_package_service/get_active_product_packages.py index 99538e5c..33facad4 100755 --- a/examples/dfp/v201702/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201702/product_package_service/get_active_product_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_package_service/get_all_product_packages.py b/examples/dfp/v201702/product_package_service/get_all_product_packages.py index ffb42161..19e33a1d 100755 --- a/examples/dfp/v201702/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201702/product_package_service/get_all_product_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_service/__init__.py b/examples/dfp/v201702/product_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/product_service/__init__.py +++ b/examples/dfp/v201702/product_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py index 02d13ac9..237453a9 100755 --- a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py +++ b/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_service/get_all_products.py b/examples/dfp/v201702/product_service/get_all_products.py index 8c7362ca..11fd193f 100755 --- a/examples/dfp/v201702/product_service/get_all_products.py +++ b/examples/dfp/v201702/product_service/get_all_products.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_service/get_products_for_product_template.py b/examples/dfp/v201702/product_service/get_products_for_product_template.py index ddf1e27d..367db302 100755 --- a/examples/dfp/v201702/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201702/product_service/get_products_for_product_template.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py index e545b1b2..642c6861 100755 --- a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_service/update_products.py b/examples/dfp/v201702/product_service/update_products.py index c4a11bfc..8d6798ab 100755 --- a/examples/dfp/v201702/product_service/update_products.py +++ b/examples/dfp/v201702/product_service/update_products.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_template_service/__init__.py b/examples/dfp/v201702/product_template_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/product_template_service/__init__.py +++ b/examples/dfp/v201702/product_template_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_template_service/activate_product_templates.py b/examples/dfp/v201702/product_template_service/activate_product_templates.py index 8956315e..71fed80d 100755 --- a/examples/dfp/v201702/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201702/product_template_service/activate_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_template_service/create_product_templates.py b/examples/dfp/v201702/product_template_service/create_product_templates.py index 352ea1c1..df5e079f 100755 --- a/examples/dfp/v201702/product_template_service/create_product_templates.py +++ b/examples/dfp/v201702/product_template_service/create_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py index 4be1ce59..dc1e4361 100755 --- a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_template_service/get_all_product_templates.py b/examples/dfp/v201702/product_template_service/get_all_product_templates.py index 3bfa7f43..d2be8378 100755 --- a/examples/dfp/v201702/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201702/product_template_service/get_all_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py index 0c729b38..44b3b3a1 100755 --- a/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_template_service/update_product_templates.py b/examples/dfp/v201702/product_template_service/update_product_templates.py index ecd62653..0dfd3df0 100755 --- a/examples/dfp/v201702/product_template_service/update_product_templates.py +++ b/examples/dfp/v201702/product_template_service/update_product_templates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_line_item_service/__init__.py b/examples/dfp/v201702/proposal_line_item_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/proposal_line_item_service/__init__.py +++ b/examples/dfp/v201702/proposal_line_item_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py index 48f14301..c4c67210 100755 --- a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py index 2c8e81e2..6cabdcf7 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 7ad91ed1..9a71f9a5 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py index ab452732..30b464a2 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py index fb94c552..0f2050c5 100755 --- a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py index bfe0dfe2..f0224ecf 100755 --- a/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py index b2309a40..b70f2d2c 100755 --- a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/__init__.py b/examples/dfp/v201702/proposal_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/proposal_service/__init__.py +++ b/examples/dfp/v201702/proposal_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py index b650aac1..d1b3b011 100755 --- a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 0d910fc8..7978cb5a 100755 --- a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/create_proposals.py b/examples/dfp/v201702/proposal_service/create_proposals.py index f1043d11..679abc33 100755 --- a/examples/dfp/v201702/proposal_service/create_proposals.py +++ b/examples/dfp/v201702/proposal_service/create_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/get_all_proposals.py b/examples/dfp/v201702/proposal_service/get_all_proposals.py index a06117ac..7fffa0f3 100755 --- a/examples/dfp/v201702/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201702/proposal_service/get_all_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py b/examples/dfp/v201702/proposal_service/get_marketplace_comments.py index 357dcbbc..b5d81c05 100755 --- a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201702/proposal_service/get_marketplace_comments.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py index 62b7dd00..33041f4a 100755 --- a/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py index 72eb3ab9..52bdac0f 100755 --- a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py index cd4cce22..8b52311a 100755 --- a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/proposal_service/update_proposals.py b/examples/dfp/v201702/proposal_service/update_proposals.py index fa539df7..3202ad84 100755 --- a/examples/dfp/v201702/proposal_service/update_proposals.py +++ b/examples/dfp/v201702/proposal_service/update_proposals.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/publisher_query_language_service/__init__.py b/examples/dfp/v201702/publisher_query_language_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/publisher_query_language_service/__init__.py +++ b/examples/dfp/v201702/publisher_query_language_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py index ec8a6a2a..6983c467 100755 --- a/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py index 55ede95f..bc5ed6a9 100755 --- a/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py index 32f43977..76c9f061 100755 --- a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py +++ b/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/rate_card_service/__init__.py b/examples/dfp/v201702/rate_card_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/rate_card_service/__init__.py +++ b/examples/dfp/v201702/rate_card_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py index 264e016e..ff302fca 100755 --- a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py index df36b13c..c300b3b9 100755 --- a/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 811a1c7c..18ab2fe7 100755 --- a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index c3492a2d..60c73c91 100755 --- a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index fc2e2570..22f41176 100755 --- a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py index 415bdcc0..d3ea80f3 100755 --- a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index a802c9c7..64b14308 100755 --- a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/report_service/__init__.py b/examples/dfp/v201702/report_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/report_service/__init__.py +++ b/examples/dfp/v201702/report_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/report_service/run_delivery_report.py b/examples/dfp/v201702/report_service/run_delivery_report.py index c379caaf..d09c1f5c 100755 --- a/examples/dfp/v201702/report_service/run_delivery_report.py +++ b/examples/dfp/v201702/report_service/run_delivery_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/report_service/run_inventory_report.py b/examples/dfp/v201702/report_service/run_inventory_report.py index 3774ba19..d408fda3 100755 --- a/examples/dfp/v201702/report_service/run_inventory_report.py +++ b/examples/dfp/v201702/report_service/run_inventory_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/report_service/run_reach_report.py b/examples/dfp/v201702/report_service/run_reach_report.py index 72d144f8..eee890d2 100755 --- a/examples/dfp/v201702/report_service/run_reach_report.py +++ b/examples/dfp/v201702/report_service/run_reach_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py b/examples/dfp/v201702/report_service/run_report_with_custom_fields.py index 8c9f92e2..909652dc 100755 --- a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201702/report_service/run_report_with_custom_fields.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/report_service/run_sales_report.py b/examples/dfp/v201702/report_service/run_sales_report.py index 09fed67a..7daedf37 100755 --- a/examples/dfp/v201702/report_service/run_sales_report.py +++ b/examples/dfp/v201702/report_service/run_sales_report.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/report_service/run_saved_query.py b/examples/dfp/v201702/report_service/run_saved_query.py index 20a6be2d..c501397a 100755 --- a/examples/dfp/v201702/report_service/run_saved_query.py +++ b/examples/dfp/v201702/report_service/run_saved_query.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/suggested_ad_unit_service/__init__.py b/examples/dfp/v201702/suggested_ad_unit_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/__init__.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 2ac63825..bbeaa77f 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py index 14c4dbc3..706fb9c3 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 87869c9a..de26bdf9 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/team_service/__init__.py b/examples/dfp/v201702/team_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/team_service/__init__.py +++ b/examples/dfp/v201702/team_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/team_service/create_teams.py b/examples/dfp/v201702/team_service/create_teams.py index 116fccb3..e250eeaa 100755 --- a/examples/dfp/v201702/team_service/create_teams.py +++ b/examples/dfp/v201702/team_service/create_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/team_service/get_all_teams.py b/examples/dfp/v201702/team_service/get_all_teams.py index 3448e552..23f54d2c 100755 --- a/examples/dfp/v201702/team_service/get_all_teams.py +++ b/examples/dfp/v201702/team_service/get_all_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/team_service/update_teams.py b/examples/dfp/v201702/team_service/update_teams.py index 62e08691..b60f2930 100755 --- a/examples/dfp/v201702/team_service/update_teams.py +++ b/examples/dfp/v201702/team_service/update_teams.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_service/__init__.py b/examples/dfp/v201702/user_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/user_service/__init__.py +++ b/examples/dfp/v201702/user_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_service/create_users.py b/examples/dfp/v201702/user_service/create_users.py index 14e21113..0a90fa02 100755 --- a/examples/dfp/v201702/user_service/create_users.py +++ b/examples/dfp/v201702/user_service/create_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_service/deactivate_users.py b/examples/dfp/v201702/user_service/deactivate_users.py index 66819175..cc5f6a42 100755 --- a/examples/dfp/v201702/user_service/deactivate_users.py +++ b/examples/dfp/v201702/user_service/deactivate_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_service/get_all_roles.py b/examples/dfp/v201702/user_service/get_all_roles.py index 03f79651..fb763029 100755 --- a/examples/dfp/v201702/user_service/get_all_roles.py +++ b/examples/dfp/v201702/user_service/get_all_roles.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_service/get_all_users.py b/examples/dfp/v201702/user_service/get_all_users.py index b7ff6a1b..698024a5 100755 --- a/examples/dfp/v201702/user_service/get_all_users.py +++ b/examples/dfp/v201702/user_service/get_all_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_service/get_user_by_email_address.py b/examples/dfp/v201702/user_service/get_user_by_email_address.py index f6993643..5e661c78 100755 --- a/examples/dfp/v201702/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201702/user_service/get_user_by_email_address.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_service/update_users.py b/examples/dfp/v201702/user_service/update_users.py index f8071fc8..583594e6 100755 --- a/examples/dfp/v201702/user_service/update_users.py +++ b/examples/dfp/v201702/user_service/update_users.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_team_association_service/__init__.py b/examples/dfp/v201702/user_team_association_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/user_team_association_service/__init__.py +++ b/examples/dfp/v201702/user_team_association_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py index 1cbb2580..540c1da5 100755 --- a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py index c903bcab..f1b0aac4 100755 --- a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py index 8aa96e57..cf5ff6c9 100755 --- a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py index 1e250536..1af444b9 100755 --- a/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py index c7f3c1e1..c2608859 100755 --- a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/workflow_request_service/__init__.py b/examples/dfp/v201702/workflow_request_service/__init__.py index a426ca48..3746cd33 100755 --- a/examples/dfp/v201702/workflow_request_service/__init__.py +++ b/examples/dfp/v201702/workflow_request_service/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py index 5beaab90..da2d3536 100755 --- a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py index 13f36103..5894de86 100755 --- a/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py index 8e721180..162b64ff 100755 --- a/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2016 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py index e3434aac..4e39fd7f 100755 --- a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2015 Google Inc. All Rights Reserved. # From 1fa2f66f30e465da9ff35596a69aa6ce3c11e923 Mon Sep 17 00:00:00 2001 From: Miguel Paolino Date: Mon, 10 Apr 2017 11:26:35 -0300 Subject: [PATCH 069/180] Updated setup.py shebang --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 8c735d83..5b323e1d 100755 --- a/setup.py +++ b/setup.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2013 Google Inc. All Rights Reserved. # From e7357cfccbea1ba5c4709fdc33778a9f6d1dda42 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 25 Apr 2017 16:32:26 -0400 Subject: [PATCH 070/180] Commiting latest changes. --- ChangeLog | 5 ++++ README.md | 41 ++++++++++---------------- googleads.yaml | 19 ++++++------ googleads/common.py | 3 +- googleads/util.py | 19 ++++++++---- tests/common_test.py | 70 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 116 insertions(+), 41 deletions(-) diff --git a/ChangeLog b/ChangeLog index aba55f7a..97ad04bd 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +5.4.0 -- 4/25/17: +* Resolved issues: +- Issue 200: https://github.com/googleads/googleads-python-lib/issues/200 +- Issue 196: https://github.com/googleads/googleads-python-lib/issues/196 + 5.3.0 -- 3/20/17: * Removed support for AdWords v201605. * Removed examples for AdWords v201605. diff --git a/README.md b/README.md index 4b35052b..927a346d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -#The googleads Python client library +# The googleads Python client library This client library simplifies accessing Google's SOAP Ads APIs - AdWords, @@ -6,7 +6,7 @@ and DoubleClick for Publishers. The library provides easy ways to store your authentication and create SOAP web service clients. It also contains example code to help you get started integrating with our APIs. -##Getting started +## Getting started 1. Download and install the library *[setuptools](https://pypi.python.org/pypi/setuptools) is a pre-requisite @@ -46,7 +46,7 @@ code to help you get started integrating with our APIs. * [Developing a web application (AdWords or DFP)](https://github.com/googleads/googleads-python-lib/wiki/API-access-on-behalf-of-your-clients-(web-flow)) -####Where can I find samples? +#### Where can I find samples? You can find code examples for the latest versions of AdWords or DFP on the [releases](https://github.com/googleads/googleads-python-lib/releases) page. @@ -55,11 +55,11 @@ Alternatively, you can find [AdWords](https://github.com/googleads/googleads-pyt or [DFP](https://github.com/googleads/googleads-python-lib/tree/master/examples/dfp) samples in the examples directory of this repository. -####Where can I find the pydocs? +#### Where can I find the pydocs? Our pydocs can be found [here](http://googleads.github.io/googleads-python-lib). -####Caching authentication information +#### Caching authentication information It is possible to cache your API authentication information. The library includes a sample file showing how to do this named `googleads.yaml`. Fill @@ -76,7 +76,7 @@ adwords_client = adwords.AdWordsClient.LoadFromStorage() dfp_client = dfp.DfpClient.LoadFromStorage('C:\My\Directory\googleads.yaml') ``` -####How do I change the Client Customer Id at runtime? +#### How do I change the Client Customer Id at runtime? You can change the Client Customer Id with the following: ``` @@ -85,7 +85,7 @@ adwords_client.SetClientCustomerId('my_client_customer_id') ``` -##Where do I submit bug reports and/or feature requests? +## Where do I submit bug reports and/or feature requests? If you have issues directly related to the client library, use the [issue tracker](https://github.com/googleads/googleads-python-lib/issues). @@ -100,7 +100,7 @@ Make sure to subscribe to our [Google Plus page](https://plus.google.com/+Google for API change announcements and other news. -##How do I log SOAP interactions? +## How do I log SOAP interactions? The library uses Python's built in logging framework. If you wish to log your SOAP interactions to stdout, you can do the following: ```python @@ -111,7 +111,7 @@ If you wish to log to a file, you'll need to attach a log handler to this source which is configured to write the output to a file. -##How do I disable log filters? +## How do I disable log filters? By default, this library will apply log filters to the `googleads.common`, `suds.client`, and `suds.transport` loggers in order to omit sensitive data. If you need to see this data in your logs, you can disable the filters with the @@ -126,7 +126,7 @@ logging.getLogger('suds.transport').removeFilter( ``` -##I'm familiar with suds. Can I use suds features with this library? +## I'm familiar with suds. Can I use suds features with this library? Yes, you can. The services returned by the `client.GetService()` functions all have a reference to the underlying suds client stored in the `suds_client` attribute. You can retrieve the client and use it in familiar ways: @@ -162,7 +162,7 @@ suds_client.set_options( suds_client.service.mutate([operation]) ``` -##How can I configure or disable caching for the suds client? +## How can I configure or disable caching for the suds client? By default, the suds clients are cached because reading and digesting the WSDL can be expensive. However, the default caching method requires permission to @@ -187,26 +187,15 @@ adwords_client = adwords.AdWordsClient( client_customer_id=client_customer_id, cache=suds.cache.NoCache()) ``` -##Timeout Tips -The requests sent by this library are sent via urllib, which is consequently -where the timeout is set. If you set a system timeout elsewhere, the googleads -library will respect it. -You can do the following if you wish to override the timeout: +## Requirements -```python -import socket -socket.setdefaulttimeout(15 * 60) -``` - -##Requirements - -###Python Versions +### Python Versions This library supports both Python 2 and 3. To use this library, you will need to have Python 2.7.9 (or higher) or Python 3.4 (or higher) installed. -###External Dependencies: +### External Dependencies: - httplib2 -- https://pypi.python.org/pypi/httplib2/ - oauth2client -- https://pypi.python.org/pypi/oauth2client/ @@ -221,5 +210,5 @@ have Python 2.7.9 (or higher) or Python 3.4 (or higher) installed. (only needed to run unit tests) -##Authors: +## Authors: Mark Saniscalchi diff --git a/googleads.yaml b/googleads.yaml index dfff1a9d..830874c7 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -49,21 +49,22 @@ dfp: ############################################################################# # The network_code is required for all services except NetworkService: # network_code: INSERT_NETWORK_CODE_HERE + # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT ############################################################################# # OAuth2 Configuration # # Below you may provide credentials for either the installed application or # - # service account flows. Remove or comment the lines for the flow you're # - # not using. # + # service account (recommended) flows. Remove or comment the lines for the # + # flow you're not using. # ############################################################################# - # The following values configure the client for the installed application - # flow. - client_id: INSERT_OAUTH_2_CLIENT_ID_HERE - client_secret: INSERT_CLIENT_SECRET_HERE - refresh_token: INSERT_REFRESH_TOKEN_HERE # The following values configure the client for the service account flow. + path_to_private_key_file: INSERT_PATH_TO_FILE_HERE + # Only needed when using P12 # service_account_email: INSERT_SERVICE_ACCOUNT_EMAIL_HERE - # path_to_private_key_file: INSERT_PATH_TO_FILE_HERE - # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT + # The following values configure the client for the installed application + # flow. + # client_id: INSERT_OAUTH_2_CLIENT_ID_HERE + # client_secret: INSERT_CLIENT_SECRET_HERE + # refresh_token: INSERT_REFRESH_TOKEN_HERE # Common configurations: diff --git a/googleads/common.py b/googleads/common.py index 2c2e6030..32e08f56 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -60,7 +60,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '5.3.0' +VERSION = '5.4.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' @@ -649,6 +649,7 @@ def __init__(self, handlers, **kwargs): handlers: an iterable of urllib2.BaseHandler subclasses. **kwargs: Keyword arguments. """ + kwargs['timeout'] = 3600 suds.transport.http.HttpTransport.__init__(self, **kwargs) self.handlers = handlers diff --git a/googleads/util.py b/googleads/util.py index 7fff45d5..80ed8aa4 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -85,6 +85,13 @@ def _ApplySudsJurkoSendPatch(self): enabled. For more details on SOAP Compression, see: https://developers.google.com/adwords/api/docs/guides/bestpractices?hl=en#use_compression """ + def GetInflateStream(msg): + stream = io.BytesIO() + stream.write(msg) + stream.flush() + stream.seek(0) + return gzip.GzipFile(fileobj=stream, mode='rb') + def PatchedHttpTransportSend(self, request): """Patch for HttpTransport.send to enable gzip compression.""" msg = request.message @@ -102,6 +109,12 @@ def PatchedHttpTransportSend(self, request): if e.code in (202, 204): return None else: + if e.headers.get('content-encoding') == 'gzip': + # If gzip encoding is used, decompress here. + # Need to read and recreate a stream because urllib result objects + # don't fully implement the file-like API + e.fp = GetInflateStream(e.fp.read()) + raise suds.transport.TransportError(e.msg, e.code, e.fp) self.getcookies(fp, u2request) @@ -110,11 +123,7 @@ def PatchedHttpTransportSend(self, request): if result.headers.get('content-encoding') == 'gzip': # If gzip encoding is used, decompress here. - stream = io.BytesIO() - stream.write(result.message) - stream.flush() - stream.seek(0) - result.message = gzip.GzipFile(fileobj=stream, mode='rb').read() + result.message = GetInflateStream(result.message).read() suds.transport.http.log.debug('received:\n%s', result) return result diff --git a/tests/common_test.py b/tests/common_test.py index fa566415..e52c9139 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -15,7 +15,9 @@ """Unit tests to cover the common module.""" +import io import unittest +from urllib import addinfourl import urllib2 import warnings @@ -339,6 +341,18 @@ def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): 'proxy_config': proxy_config.return_value, googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + def testHTTPSProxyExtendsSSLSockTimeout(self): + with mock.patch('googleads.oauth2.GoogleRefreshTokenClient'): + with mock.patch('googleads.common.open', self.fake_open, create=True): + with mock.patch('suds.transport.http.' + 'HttpTransport.__init__') as mock_transport: + proxy_config = googleads.common.ProxyConfig() + proxy_config.GetSudsProxyTransport() + mock_transport.assert_called_once() + # 90 is the default, don't expect an exact value so that we can change + # the timeout in the code without returning here. + self.assertGreater(mock_transport.call_args_list[0][1]['timeout'], 90) + def testLoadFromString_passesWithHTTPProxy(self): yaml_doc = self._CreateYamlDoc( {'adwords': {}, @@ -985,5 +999,61 @@ def testProxyConfigWithHTTPAndHTTPSProxy(self): self.assertEqual(t.return_value, transport) +class TestSudsRequestPatcher(unittest.TestCase): + + class MockHeaders(object): + + def __init__(self, d): + self.dict = d + + def testInflateSuccessfulRequestIfGzipped(self): + with mock.patch('suds.transport.http.HttpTransport.getcookies'): + with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('gzip.GzipFile.read') as mock_read: + resp_fp = io.BytesIO() + resp_fp.write('abc') + resp_fp.flush() + resp_fp.seek(0) + resp = addinfourl(resp_fp, self.MockHeaders( + {'content-encoding': 'gzip'}), 'https://example.com', code=200) + mock_open.return_value = resp + + req = suds.transport.Request('https://example.com', + message='hello world') + suds.transport.http.HttpTransport().send(req) + mock_read.assert_called_once() + + def testInflateFailedRequestIfGzipped(self): + + with mock.patch('suds.transport.http.HttpTransport.getcookies'): + with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('gzip.GzipFile') as mock_gzip: + gzip_instance_mock = mock.MagicMock + mock_gzip.return_value = gzip_instance_mock + resp_fp = io.BytesIO() + resp_fp.write('abc') + resp_fp.flush() + resp_fp.seek(0) + resp = addinfourl(resp_fp, + self.MockHeaders({'content-encoding': 'gzip'}), + 'https://example.com', code=200) + + def fail_to_open(*args, **kwargs): + raise urllib2.HTTPError( + 'https://example.com', + 500, + 'oops!', + {'content-encoding': 'gzip'}, + resp + ) + mock_open.side_effect = fail_to_open + + req = suds.transport.Request('https://example.com', + message='hello world') + with self.assertRaises(suds.transport.TransportError) as exc: + suds.transport.http.HttpTransport().send(req) + self.assertEqual(exc.exception.fp, gzip_instance_mock) + + if __name__ == '__main__': unittest.main() From dfc1ac8a25300727c8078a86069ddcdbdf1be003 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 25 Apr 2017 16:50:01 -0400 Subject: [PATCH 071/180] Commiting latest changes. From 1362709a6a75619c3fecb7aaa7d200f733721451 Mon Sep 17 00:00:00 2001 From: Miguel Paolino Date: Fri, 28 Apr 2017 11:38:14 -0300 Subject: [PATCH 072/180] Fixes README.md suds cache example --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4b35052b..0c13ca1f 100644 --- a/README.md +++ b/README.md @@ -174,10 +174,10 @@ You can pass an implementation of `suds.cache.Cache` to the `AdWordsClient` or For example, configuring a different location and duration of the cache file: ```python -file_cache = suds.cache.FileCache(location=cache_path, days=2) +doc_cache = suds.cache.DocumentCache(location=cache_path, days=2) adwords_client = adwords.AdWordsClient( developer_token, oauth2_client, user_agent, - client_customer_id=client_customer_id, cache=file_cache) + client_customer_id=client_customer_id, cache=doc_cache) ``` You can also disable caching in similar fashion: From f27f7f537b3e9899c98794204a4d9eb264d42abf Mon Sep 17 00:00:00 2001 From: Miguel Paolino Date: Fri, 28 Apr 2017 11:43:44 -0300 Subject: [PATCH 073/180] Fix suds cache example in README --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4b35052b..0c13ca1f 100644 --- a/README.md +++ b/README.md @@ -174,10 +174,10 @@ You can pass an implementation of `suds.cache.Cache` to the `AdWordsClient` or For example, configuring a different location and duration of the cache file: ```python -file_cache = suds.cache.FileCache(location=cache_path, days=2) +doc_cache = suds.cache.DocumentCache(location=cache_path, days=2) adwords_client = adwords.AdWordsClient( developer_token, oauth2_client, user_agent, - client_customer_id=client_customer_id, cache=file_cache) + client_customer_id=client_customer_id, cache=doc_cache) ``` You can also disable caching in similar fashion: From 92cc80b1eaff2673dc249c3e25222de377b0a51e Mon Sep 17 00:00:00 2001 From: Miguel Paolino Date: Fri, 28 Apr 2017 13:23:52 -0300 Subject: [PATCH 074/180] Fix default values for suds cache instances types in doctring of AdWordsClient and DfpClient --- googleads/adwords.py | 2 +- googleads/dfp.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/googleads/adwords.py b/googleads/adwords.py index 507cf02d..45cfba3e 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -298,7 +298,7 @@ def __init__(self, developer_token, oauth2_client, partial failure with some changes made. Only certain services respect this header. cache: A subclass of suds.cache.Cache. If not set, this will default to an - instance of suds.cache.FileCache. + instance of suds.cache.ObjectCache. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. report_downloader_headers: A dict containing optional headers to be used diff --git a/googleads/dfp.py b/googleads/dfp.py index 8944b2c2..4d1e6dd7 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -215,7 +215,7 @@ def __init__(self, oauth2_client, application_name, network_code=None, accessing. All requests other than getAllNetworks and getCurrentUser calls require this header to be set. cache: A subclass of suds.cache.Cache. If not set, this will default to an - instance of suds.cache.FileCache. + instance of suds.cache.ObjectCache. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. enable_compression: A boolean indicating if you want to enable compression From 212003dfab4ad37d0064c4c537dc8a64d4b2e60d Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 23 May 2017 09:23:56 -0400 Subject: [PATCH 075/180] Commiting latest changes. --- ChangeLog | 6 + .../adwords_appengine_demo/__init__.py | 2 +- .../adwords_appengine_demo/demo/__init__.py | 2 +- .../adwords_appengine_demo/demo/main.py | 2 +- .../handlers/__init__.py | 2 +- .../handlers/api_handler.py | 2 +- .../handlers/ndb_handler.py | 2 +- .../adwords_appengine_demo/models/__init__.py | 2 +- .../adwords_appengine_demo/models/app_user.py | 2 +- .../adwords_appengine_demo/views/__init__.py | 2 +- .../views/add_adgroup_view.py | 2 +- .../views/add_campaign_view.py | 2 +- .../adwords_appengine_demo/views/init_view.py | 2 +- .../views/show_accounts_view.py | 2 +- .../views/show_adgroups_view.py | 2 +- .../views/show_budget_view.py | 2 +- .../views/show_campaigns_view.py | 2 +- .../views/show_credentials_view.py | 2 +- .../views/update_budget_view.py | 2 +- .../views/update_credentials_view.py | 2 +- ...ate_adwords_client_with_service_account.py | 2 +- .../create_adwords_client_without_yaml.py | 2 +- .../authentication/generate_refresh_token.py | 2 +- .../account_management/create_account.py | 0 .../account_management/get_account_changes.py | 0 .../get_account_hierarchy.py | 0 .../advanced_operations/add_ad_customizer.py | 0 .../add_ad_group_bid_modifier.py | 0 .../add_click_to_download_ad.py | 0 .../advanced_operations/add_html5_ad.py | 0 .../add_responsive_display_ad.py | 0 .../add_text_ad_with_upgraded_urls.py | 0 .../create_and_attach_shared_keyword_set.py | 0 ...ind_and_remove_criteria_from_shared_set.py | 0 .../get_ad_group_bid_modifier.py | 0 .../use_shared_bidding_strategy.py | 0 .../v201607/basic_operations/add_ad_groups.py | 0 .../v201607/basic_operations/add_campaigns.py | 0 .../basic_operations/add_expanded_text_ads.py | 0 .../v201607/basic_operations/add_keywords.py | 0 .../v201607/basic_operations/add_text_ads.py | 0 .../v201607/basic_operations/get_ad_groups.py | 0 .../v201607/basic_operations/get_campaigns.py | 0 .../get_campaigns_with_awql.py | 0 .../basic_operations/get_expanded_text_ads.py | 0 .../v201607/basic_operations/get_keywords.py | 0 .../v201607/basic_operations/get_text_ads.py | 0 .../v201607/basic_operations/pause_ad.py | 0 .../v201607/basic_operations/remove_ad.py | 0 .../basic_operations/remove_ad_group.py | 0 .../basic_operations/remove_campaign.py | 0 .../basic_operations/remove_keyword.py | 0 .../basic_operations/update_ad_group.py | 0 .../basic_operations/update_campaign.py | 0 .../basic_operations/update_keyword.py | 0 .../add_campaign_labels.py | 0 .../add_complete_campaigns_using_batch_job.py | 0 .../v201607/campaign_management/add_draft.py | 0 .../campaign_management/add_experiment.py | 0 ...dd_keywords_using_incremental_batch_job.py | 0 .../v201607/campaign_management/add_trial.py | 0 .../get_all_disapproved_ads.py | 0 .../get_all_disapproved_ads_with_awql.py | 0 .../get_campaigns_by_label.py | 0 .../campaign_management/graduate_trial.py | 0 .../campaign_management/promote_experiment.py | 0 .../campaign_management/set_ad_parameters.py | 0 .../set_criterion_bid_modifier.py | 0 .../campaign_management/validate_text_ad.py | 0 .../error_handling/handle_partial_failures.py | 0 .../handle_policy_violation_error.py | 0 ..._google_my_business_location_extensions.py | 0 .../adwords/v201607/extensions/add_prices.py | 0 .../v201607/extensions/add_site_links.py | 0 .../extensions/add_site_links_using_feeds.py | 0 .../migrate_to_extension_settings.py | 0 .../v201607/misc/get_all_images_and_videos.py | 0 examples/adwords/v201607/misc/upload_image.py | 0 .../v201607/misc/upload_media_bundle.py | 0 .../optimization/estimate_keyword_traffic.py | 0 ...aign_criterion_bid_modifier_simulations.py | 0 .../get_keyword_bid_simulations.py | 0 .../v201607/optimization/get_keyword_ideas.py | 0 .../v201607/remarketing/add_audience.py | 0 .../remarketing/add_conversion_tracker.py | 0 .../remarketing/add_crm_based_user_list.py | 0 .../remarketing/add_rule_based_user_lists.py | 0 .../remarketing/upload_offline_conversions.py | 0 .../reporting/download_criteria_report.py | 0 .../download_criteria_report_as_stream.py | 0 ...oad_criteria_report_as_stream_with_awql.py | 0 .../download_criteria_report_as_string.py | 0 ...oad_criteria_report_as_string_with_awql.py | 0 .../download_criteria_report_with_awql.py | 0 .../v201607/reporting/get_report_fields.py | 0 .../reporting/parallel_report_download.py | 0 .../shopping/add_product_partition_tree.py | 0 .../v201607/shopping/add_product_scope.py | 0 .../v201607/shopping/add_shopping_campaign.py | 0 .../shopping/get_product_category_taxonomy.py | 0 .../add_campaign_targeting_criteria.py | 0 .../add_demographic_targeting_criteria.py | 0 .../get_campaign_targeting_criteria.py | 0 .../get_targetable_languages_and_carriers.py | 0 .../v201607/targeting/lookup_location.py | 0 .../account_management/accept_service_link.py | 0 .../account_management/create_account.py | 0 .../account_management/get_account_changes.py | 0 .../get_account_hierarchy.py | 0 .../advanced_operations/add_ad_customizer.py | 0 .../add_ad_group_bid_modifier.py | 0 .../add_click_to_download_ad.py | 0 ...add_expanded_text_ad_with_upgraded_urls.py | 0 .../advanced_operations/add_html5_ad.py | 0 .../add_responsive_display_ad.py | 0 .../add_universal_app_campaign.py | 1 - .../create_and_attach_shared_keyword_set.py | 0 ...ind_and_remove_criteria_from_shared_set.py | 0 .../get_ad_group_bid_modifier.py | 0 .../use_shared_bidding_strategy.py | 0 .../v201609/basic_operations/add_ad_groups.py | 0 .../v201609/basic_operations/add_campaigns.py | 0 .../basic_operations/add_expanded_text_ads.py | 0 .../v201609/basic_operations/add_keywords.py | 0 .../v201609/basic_operations/get_ad_groups.py | 0 .../v201609/basic_operations/get_campaigns.py | 0 .../get_campaigns_with_awql.py | 0 .../basic_operations/get_expanded_text_ads.py | 0 .../v201609/basic_operations/get_keywords.py | 0 .../v201609/basic_operations/get_text_ads.py | 0 .../v201609/basic_operations/pause_ad.py | 0 .../v201609/basic_operations/remove_ad.py | 0 .../basic_operations/remove_ad_group.py | 0 .../basic_operations/remove_campaign.py | 0 .../basic_operations/remove_keyword.py | 0 .../basic_operations/update_ad_group.py | 0 .../basic_operations/update_campaign.py | 0 .../basic_operations/update_keyword.py | 0 .../add_campaign_labels.py | 0 .../add_complete_campaigns_using_batch_job.py | 0 .../v201609/campaign_management/add_draft.py | 0 ...dd_keywords_using_incremental_batch_job.py | 0 .../v201609/campaign_management/add_trial.py | 0 .../get_all_disapproved_ads.py | 0 .../get_all_disapproved_ads_with_awql.py | 0 .../get_campaigns_by_label.py | 0 .../campaign_management/graduate_trial.py | 0 .../campaign_management/set_ad_parameters.py | 0 .../set_criterion_bid_modifier.py | 0 .../campaign_management/validate_text_ad.py | 0 .../error_handling/handle_partial_failures.py | 0 .../handle_policy_violation_error.py | 0 ..._google_my_business_location_extensions.py | 0 .../adwords/v201609/extensions/add_prices.py | 0 .../v201609/extensions/add_site_links.py | 0 .../extensions/add_site_links_using_feeds.py | 0 .../migrate_to_extension_settings.py | 0 .../v201609/misc/get_all_images_and_videos.py | 0 examples/adwords/v201609/misc/upload_image.py | 0 .../v201609/misc/upload_media_bundle.py | 0 .../optimization/estimate_keyword_traffic.py | 0 ...aign_criterion_bid_modifier_simulations.py | 0 .../get_keyword_bid_simulations.py | 0 .../v201609/optimization/get_keyword_ideas.py | 0 .../v201609/remarketing/add_audience.py | 0 .../remarketing/add_conversion_tracker.py | 0 .../remarketing/add_crm_based_user_list.py | 0 .../remarketing/add_rule_based_user_lists.py | 0 .../upload_offline_call_conversions.py | 0 .../remarketing/upload_offline_conversions.py | 0 .../reporting/download_criteria_report.py | 0 .../download_criteria_report_as_stream.py | 0 ...oad_criteria_report_as_stream_with_awql.py | 0 .../download_criteria_report_as_string.py | 0 ...oad_criteria_report_as_string_with_awql.py | 0 .../download_criteria_report_with_awql.py | 0 .../v201609/reporting/get_report_fields.py | 0 .../reporting/parallel_report_download.py | 0 .../shopping/add_product_partition_tree.py | 0 .../v201609/shopping/add_product_scope.py | 0 .../v201609/shopping/add_shopping_campaign.py | 0 .../shopping/get_product_category_taxonomy.py | 0 .../add_campaign_targeting_criteria.py | 0 .../add_demographic_targeting_criteria.py | 0 .../get_campaign_targeting_criteria.py | 0 .../get_targetable_languages_and_carriers.py | 0 .../v201609/targeting/lookup_location.py | 0 .../account_management/accept_service_link.py | 0 .../account_management/create_account.py | 0 .../account_management/get_account_changes.py | 0 .../get_account_hierarchy.py | 0 .../advanced_operations/add_ad_customizer.py | 0 .../add_ad_group_bid_modifier.py | 0 .../add_click_to_download_ad.py | 0 ...add_expanded_text_ad_with_upgraded_urls.py | 0 .../advanced_operations/add_html5_ad.py | 0 .../add_responsive_display_ad.py | 0 .../add_universal_app_campaign.py | 1 - .../create_and_attach_shared_keyword_set.py | 0 ...ind_and_remove_criteria_from_shared_set.py | 0 .../get_ad_group_bid_modifier.py | 0 .../use_shared_bidding_strategy.py | 0 .../v201702/basic_operations/add_ad_groups.py | 0 .../v201702/basic_operations/add_campaigns.py | 0 .../basic_operations/add_expanded_text_ads.py | 0 .../v201702/basic_operations/add_keywords.py | 0 .../v201702/basic_operations/get_ad_groups.py | 0 .../v201702/basic_operations/get_campaigns.py | 0 .../get_campaigns_with_awql.py | 0 .../basic_operations/get_expanded_text_ads.py | 0 .../v201702/basic_operations/get_keywords.py | 0 .../v201702/basic_operations/get_text_ads.py | 0 .../v201702/basic_operations/pause_ad.py | 0 .../v201702/basic_operations/remove_ad.py | 0 .../basic_operations/remove_ad_group.py | 0 .../basic_operations/remove_campaign.py | 0 .../basic_operations/remove_keyword.py | 0 .../basic_operations/update_ad_group.py | 0 .../basic_operations/update_campaign.py | 0 .../basic_operations/update_keyword.py | 0 .../add_campaign_labels.py | 0 .../add_complete_campaigns_using_batch_job.py | 0 .../v201702/campaign_management/add_draft.py | 0 ...dd_keywords_using_incremental_batch_job.py | 0 .../v201702/campaign_management/add_trial.py | 0 .../get_all_disapproved_ads.py | 0 .../get_all_disapproved_ads_with_awql.py | 0 .../get_campaigns_by_label.py | 0 .../campaign_management/graduate_trial.py | 0 .../campaign_management/set_ad_parameters.py | 0 .../set_criterion_bid_modifier.py | 0 .../campaign_management/validate_text_ad.py | 0 .../error_handling/handle_partial_failures.py | 0 .../handle_policy_violation_error.py | 0 ..._google_my_business_location_extensions.py | 0 .../adwords/v201702/extensions/add_prices.py | 2 +- .../v201702/extensions/add_site_links.py | 0 .../extensions/add_site_links_using_feeds.py | 0 .../migrate_to_extension_settings.py | 0 .../v201702/misc/get_all_images_and_videos.py | 0 examples/adwords/v201702/misc/upload_image.py | 0 .../v201702/misc/upload_media_bundle.py | 0 .../optimization/estimate_keyword_traffic.py | 0 ...aign_criterion_bid_modifier_simulations.py | 0 .../get_keyword_bid_simulations.py | 0 .../v201702/optimization/get_keyword_ideas.py | 0 .../v201702/remarketing/add_audience.py | 0 .../remarketing/add_conversion_tracker.py | 0 .../remarketing/add_crm_based_user_list.py | 0 .../remarketing/add_rule_based_user_lists.py | 0 .../upload_offline_call_conversions.py | 0 .../remarketing/upload_offline_conversions.py | 0 ...oad_criteria_report_as_stream_with_awql.py | 0 ...criteria_report_as_stream_with_selector.py | 0 ...oad_criteria_report_as_string_with_awql.py | 0 ...criteria_report_as_string_with_selector.py | 0 .../download_criteria_report_with_awql.py | 0 .../download_criteria_report_with_selector.py | 0 .../v201702/reporting/get_report_fields.py | 0 .../reporting/parallel_report_download.py | 0 .../shopping/add_product_partition_tree.py | 0 .../v201702/shopping/add_product_scope.py | 0 .../v201702/shopping/add_shopping_campaign.py | 0 .../add_shopping_campaign_for_showcase_ads.py | 0 .../shopping/get_product_category_taxonomy.py | 0 .../add_campaign_targeting_criteria.py | 0 .../add_demographic_targeting_criteria.py | 0 .../get_campaign_targeting_criteria.py | 0 .../get_targetable_languages_and_carriers.py | 0 .../v201702/targeting/lookup_location.py | 0 .../create_dfp_client_with_service_account.py | 2 +- .../create_dfp_client_without_yaml.py | 2 +- .../authentication/generate_refresh_token.py | 2 +- ..._item_reports_for_reconciliation_report.py | 73 ---- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 0 .../get_active_activity_groups.py | 0 .../get_all_activity_groups.py | 0 .../update_activity_groups.py | 0 .../dfp/v201611/activity_service/__init__.py | 0 .../activity_service/create_activities.py | 0 .../activity_service/get_active_activities.py | 0 .../activity_service/get_all_activities.py | 0 .../activity_service/update_activities.py | 0 .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 0 .../get_all_audience_segments.py | 0 .../get_first_party_audience_segments.py | 0 .../populate_first_party_audience_segments.py | 0 .../update_audience_segments.py | 0 .../dfp/v201611/base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 0 .../create_product_template_base_rates.py | 0 .../base_rate_service/get_all_base_rates.py | 0 .../get_base_rates_for_rate_card.py | 0 .../base_rate_service/update_base_rates.py | 0 .../dfp/v201611/company_service/__init__.py | 0 .../company_service/create_companies.py | 0 .../company_service/get_advertisers.py | 0 .../company_service/get_all_companies.py | 0 .../company_service/update_companies.py | 0 .../dfp/v201611/contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 0 .../contact_service/get_all_contacts.py | 0 .../contact_service/get_uninvited_contacts.py | 0 .../contact_service/update_contacts.py | 0 .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 0 ...delete_content_metadata_key_hierarchies.py | 0 ...et_all_content_metadata_key_hierarchies.py | 0 ...update_content_metadata_key_hierarchies.py | 0 .../dfp/v201611/content_service/__init__.py | 0 .../content_service/get_all_content.py | 0 .../dfp/v201611/creative_service/__init__.py | 0 .../create_creative_from_template.py | 0 .../creative_service/create_creatives.py | 0 .../create_custom_creative.py | 0 .../create_native_creative.py | 0 .../creative_service/get_all_creatives.py | 0 .../creative_service/get_image_creatives.py | 0 .../creative_service/update_creatives.py | 0 .../v201611/creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 0 .../create_creative_set.py | 0 .../get_all_creative_sets.py | 0 .../get_creative_sets_for_master_creative.py | 0 .../update_creative_set.py | 0 .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 0 .../get_system_defined_creative_templates.py | 0 .../create_creative_wrappers.py | 0 .../deactivate_creative_wrapper.py | 0 .../get_active_creative_wrappers.py | 0 .../get_all_creative_wrappers.py | 0 .../update_creative_wrappers.py | 0 .../v201611/custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 0 .../create_custom_fields.py | 0 .../deactivate_all_line_item_custom_fields.py | 0 .../get_all_custom_fields.py | 0 .../get_custom_fields_for_line_items.py | 0 .../set_line_item_custom_field_value.py | 0 .../update_custom_fields.py | 0 .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 0 .../delete_custom_targeting_keys.py | 0 .../delete_custom_targeting_values.py | 0 ...et_all_custom_targeting_keys_and_values.py | 0 ...efined_custom_targeting_keys_and_values.py | 0 .../update_custom_targeting_keys.py | 0 .../update_custom_targeting_values.py | 0 .../v201611/exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 0 .../get_all_exchange_rates.py | 0 .../get_exchange_rates_for_currency_code.py | 0 .../update_exchange_rates.py | 0 .../get_availability_forecast.py | 0 ...get_availability_forecast_for_line_item.py | 0 .../get_delivery_forecast_for_line_items.py | 0 .../dfp/v201611/inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 0 .../inventory_service/create_ad_units.py | 0 .../get_all_ad_unit_sizes.py | 0 .../inventory_service/get_all_ad_units.py | 0 .../inventory_service/update_ad_units.py | 0 .../dfp/v201611/label_service/__init__.py | 0 .../v201611/label_service/create_labels.py | 0 .../label_service/deactivate_labels.py | 0 .../label_service/get_active_labels.py | 0 .../v201611/label_service/get_all_labels.py | 0 .../v201611/label_service/update_labels.py | 0 .../__init__.py | 0 .../create_licas.py | 0 .../deactivate_licas.py | 0 .../get_all_licas.py | 0 .../get_licas_for_line_item.py | 0 .../update_licas.py | 0 .../dfp/v201611/line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 0 .../line_item_service/create_line_items.py | 0 .../create_video_line_item.py | 0 .../line_item_service/get_all_line_items.py | 0 .../get_line_items_that_need_creatives.py | 0 .../get_recently_updated_line_items.py | 0 .../target_custom_criteria.py | 0 .../line_item_service/update_line_items.py | 0 .../dfp/v201611/network_service/__init__.py | 0 .../network_service/get_all_networks.py | 0 .../network_service/make_test_network.py | 0 .../dfp/v201611/order_service/__init__.py | 0 .../v201611/order_service/approve_orders.py | 0 .../v201611/order_service/create_orders.py | 0 .../v201611/order_service/get_all_orders.py | 0 .../order_service/get_orders_starting_soon.py | 0 .../v201611/order_service/update_orders.py | 0 .../package_service/get_all_packages.py | 0 .../get_in_progress_packages.py | 0 .../placement_service/create_placements.py | 0 .../deactivate_placements.py | 0 .../get_active_placements.py | 0 .../placement_service/get_all_placements.py | 0 .../placement_service/update_placements.py | 0 .../v201611/premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 0 .../get_all_premium_rates.py | 0 .../get_premium_rates_for_rate_card.py | 0 .../update_premium_rates.py | 0 .../get_all_product_package_items.py | 0 ...oduct_package_items_for_product_package.py | 0 .../get_active_product_packages.py | 0 .../get_all_product_packages.py | 0 .../dfp/v201611/product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 0 .../product_service/get_all_products.py | 0 .../get_products_for_product_template.py | 0 ...sh_programmatic_products_to_marketplace.py | 0 .../product_service/update_products.py | 0 .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 0 .../create_product_templates.py | 0 .../create_programmatic_product_templates.py | 0 .../get_all_product_templates.py | 0 .../get_sponsorship_product_templates.py | 0 .../update_product_templates.py | 0 .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 0 ...create_programmatic_proposal_line_items.py | 0 ...sal_line_items_for_non_sales_management.py | 0 .../create_proposal_line_items.py | 0 .../get_all_proposal_line_items.py | 0 .../get_proposal_line_items_for_proposal.py | 0 .../update_proposal_line_items.py | 0 .../dfp/v201611/proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 0 ...atic_proposals_for_non_sales_management.py | 0 .../proposal_service/create_proposals.py | 0 .../proposal_service/get_all_proposals.py | 0 .../get_marketplace_comments.py | 0 .../get_proposals_pending_approval.py | 0 .../request_buyers_acceptance.py | 0 .../submit_proposals_for_approval.py | 0 .../proposal_service/update_proposals.py | 0 .../__init__.py | 0 .../fetch_match_tables.py | 0 .../get_all_programmatic_buyers.py | 0 .../dfp/v201611/rate_card_service/__init__.py | 0 .../rate_card_service/get_all_rate_cards.py | 0 .../get_marketplace_rate_cards.py | 0 ..._item_reports_for_reconciliation_report.py | 0 ...order_reports_for_reconciliation_report.py | 0 ...n_report_rows_for_reconciliation_report.py | 0 .../get_all_reconciliation_reports.py | 0 ...iliation_report_for_last_billing_period.py | 0 .../dfp/v201611/report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 0 .../report_service/run_inventory_report.py | 0 .../report_service/run_reach_report.py | 0 .../run_report_with_custom_fields.py | 0 .../report_service/run_sales_report.py | 0 .../v201611/report_service/run_saved_query.py | 0 .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 0 .../get_all_suggested_ad_units.py | 0 ...get_highly_requested_suggested_ad_units.py | 0 examples/dfp/v201611/team_service/__init__.py | 0 .../dfp/v201611/team_service/create_teams.py | 0 .../dfp/v201611/team_service/get_all_teams.py | 0 .../dfp/v201611/team_service/update_teams.py | 0 examples/dfp/v201611/user_service/__init__.py | 0 .../dfp/v201611/user_service/create_users.py | 0 .../v201611/user_service/deactivate_users.py | 0 .../dfp/v201611/user_service/get_all_roles.py | 0 .../dfp/v201611/user_service/get_all_users.py | 0 .../user_service/get_user_by_email_address.py | 0 .../dfp/v201611/user_service/update_users.py | 0 .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 0 .../delete_user_team_associations.py | 0 .../get_all_user_team_associations.py | 0 .../get_user_team_associations_for_user.py | 0 .../update_user_team_associations.py | 0 .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 0 .../get_workflow_approval_requests.py | 0 ...et_workflow_external_condition_requests.py | 0 ...er_workflow_external_condition_requests.py | 0 .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 0 .../get_active_activity_groups.py | 0 .../get_all_activity_groups.py | 0 .../update_activity_groups.py | 0 .../dfp/v201702/activity_service/__init__.py | 0 .../activity_service/create_activities.py | 0 .../activity_service/get_active_activities.py | 0 .../activity_service/get_all_activities.py | 0 .../activity_service/update_activities.py | 0 .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 0 .../get_all_audience_segments.py | 0 .../get_first_party_audience_segments.py | 0 .../populate_first_party_audience_segments.py | 0 .../update_audience_segments.py | 0 .../dfp/v201702/base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 0 .../create_product_package_item_base_rates.py | 66 +++ .../create_product_template_base_rates.py | 0 .../base_rate_service/get_all_base_rates.py | 0 .../get_base_rates_for_rate_card.py | 0 .../base_rate_service/update_base_rates.py | 0 .../dfp/v201702/company_service/__init__.py | 0 .../company_service/create_companies.py | 0 .../company_service/get_advertisers.py | 0 .../company_service/get_all_companies.py | 0 .../company_service/update_companies.py | 0 .../dfp/v201702/contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 0 .../contact_service/get_all_contacts.py | 0 .../contact_service/get_uninvited_contacts.py | 0 .../contact_service/update_contacts.py | 0 .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 0 ...delete_content_metadata_key_hierarchies.py | 0 ...et_all_content_metadata_key_hierarchies.py | 0 ...update_content_metadata_key_hierarchies.py | 0 .../dfp/v201702/content_service/__init__.py | 0 .../content_service/get_all_content.py | 0 .../dfp/v201702/creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 60 +++ .../create_creative_from_template.py | 0 .../creative_service/create_creatives.py | 0 .../create_custom_creative.py | 0 .../create_native_creative.py | 0 .../creative_service/get_all_creatives.py | 0 .../creative_service/get_image_creatives.py | 0 .../creative_service/update_creatives.py | 0 .../v201702/creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 0 .../create_creative_set.py | 0 .../get_all_creative_sets.py | 0 .../get_creative_sets_for_master_creative.py | 0 .../update_creative_set.py | 0 .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 0 .../get_system_defined_creative_templates.py | 0 .../create_creative_wrappers.py | 0 .../deactivate_creative_wrapper.py | 0 .../get_active_creative_wrappers.py | 0 .../get_all_creative_wrappers.py | 0 .../update_creative_wrappers.py | 0 .../v201702/custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 0 .../create_custom_fields.py | 0 .../deactivate_all_line_item_custom_fields.py | 0 .../get_all_custom_fields.py | 0 .../get_custom_fields_for_line_items.py | 0 .../set_line_item_custom_field_value.py | 0 .../update_custom_fields.py | 0 .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 0 .../delete_custom_targeting_keys.py | 0 .../delete_custom_targeting_values.py | 0 ...et_all_custom_targeting_keys_and_values.py | 0 ...efined_custom_targeting_keys_and_values.py | 0 .../update_custom_targeting_keys.py | 0 .../update_custom_targeting_values.py | 0 .../v201702/exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 0 .../get_all_exchange_rates.py | 0 .../get_exchange_rates_for_currency_code.py | 0 .../update_exchange_rates.py | 0 .../get_availability_forecast.py | 18 +- ...get_availability_forecast_for_line_item.py | 0 .../get_delivery_forecast_for_line_items.py | 0 .../dfp/v201702/inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 0 .../inventory_service/create_ad_units.py | 0 .../get_all_ad_unit_sizes.py | 0 .../inventory_service/get_all_ad_units.py | 0 .../inventory_service/update_ad_units.py | 0 .../dfp/v201702/label_service/__init__.py | 0 .../v201702/label_service/create_labels.py | 0 .../label_service/deactivate_labels.py | 0 .../label_service/get_active_labels.py | 0 .../v201702/label_service/get_all_labels.py | 0 .../v201702/label_service/update_labels.py | 0 .../__init__.py | 0 .../create_licas.py | 0 .../deactivate_licas.py | 0 .../get_all_licas.py | 0 .../get_licas_for_line_item.py | 0 .../update_licas.py | 0 .../dfp/v201702/line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 0 .../line_item_service/create_line_items.py | 0 .../create_video_line_item.py | 0 .../line_item_service/get_all_line_items.py | 0 .../get_line_items_that_need_creatives.py | 0 .../get_recently_updated_line_items.py | 0 .../line_item_service/pause_line_items.py | 74 ++++ .../target_custom_criteria.py | 0 .../line_item_service/update_line_items.py | 0 .../v201702/native_style_service/__init__.py | 0 .../create_native_styles.py | 0 .../get_all_native_styles.py | 0 .../dfp/v201702/network_service/__init__.py | 0 .../network_service/get_all_networks.py | 0 .../network_service/make_test_network.py | 0 .../dfp/v201702/order_service/__init__.py | 0 .../v201702/order_service/approve_orders.py | 0 .../v201702/order_service/create_orders.py | 0 .../v201702/order_service/get_all_orders.py | 0 .../order_service/get_orders_starting_soon.py | 0 .../v201702/order_service/update_orders.py | 0 .../package_service/create_packages.py | 61 +++ ...reate_proposal_line_items_from_packages.py | 68 +++ .../package_service/get_all_packages.py | 0 .../get_in_progress_packages.py | 0 .../placement_service/create_placements.py | 0 .../deactivate_placements.py | 0 .../get_active_placements.py | 0 .../placement_service/get_all_placements.py | 0 .../placement_service/update_placements.py | 0 .../v201702/premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 0 .../get_all_premium_rates.py | 0 .../get_premium_rates_for_rate_card.py | 0 .../update_premium_rates.py | 0 .../create_product_package_item.py | 62 +++ .../get_all_product_package_items.py | 0 ...oduct_package_items_for_product_package.py | 0 .../create_product_packages.py | 51 +++ .../get_active_product_packages.py | 0 .../get_all_product_packages.py | 0 .../dfp/v201702/product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 0 .../product_service/get_all_products.py | 0 .../get_products_for_product_template.py | 0 ...sh_programmatic_products_to_marketplace.py | 0 .../product_service/update_products.py | 0 .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 0 .../create_product_templates.py | 0 .../create_programmatic_product_templates.py | 0 .../get_all_product_templates.py | 0 .../get_sponsorship_product_templates.py | 0 .../update_product_templates.py | 0 .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 0 ...create_programmatic_proposal_line_items.py | 0 ...sal_line_items_for_non_sales_management.py | 0 .../create_proposal_line_items.py | 0 .../get_all_proposal_line_items.py | 0 .../get_proposal_line_items_for_proposal.py | 0 .../update_proposal_line_items.py | 0 .../dfp/v201702/proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 0 ...atic_proposals_for_non_sales_management.py | 0 .../proposal_service/create_proposals.py | 0 .../proposal_service/get_all_proposals.py | 0 .../get_marketplace_comments.py | 0 .../get_proposals_pending_approval.py | 0 .../request_buyers_acceptance.py | 0 .../submit_proposals_for_approval.py | 0 .../proposal_service/update_proposals.py | 0 .../__init__.py | 0 .../fetch_match_tables.py | 0 .../get_all_programmatic_buyers.py | 0 .../get_recent_changes.py | 0 .../dfp/v201702/rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 60 +++ .../rate_card_service/get_all_rate_cards.py | 0 .../get_marketplace_rate_cards.py | 0 ..._item_reports_for_reconciliation_report.py | 82 ++-- ...update_reconciliation_line_item_reports.py | 67 +++ ...order_reports_for_reconciliation_report.py | 0 .../submit_reconciliation_order_reports.py | 71 +++ ...n_report_rows_for_reconciliation_report.py | 16 +- .../update_reconciliation_report_rows.py | 75 ++++ .../get_all_reconciliation_reports.py | 0 ...iliation_report_for_last_billing_period.py | 0 .../dfp/v201702/report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 10 +- .../report_service/run_inventory_report.py | 0 .../report_service/run_reach_report.py | 0 .../run_report_with_custom_fields.py | 0 .../report_service/run_sales_report.py | 0 .../v201702/report_service/run_saved_query.py | 0 .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 0 .../get_all_suggested_ad_units.py | 0 ...get_highly_requested_suggested_ad_units.py | 0 examples/dfp/v201702/team_service/__init__.py | 0 .../dfp/v201702/team_service/create_teams.py | 0 .../dfp/v201702/team_service/get_all_teams.py | 0 .../dfp/v201702/team_service/update_teams.py | 0 examples/dfp/v201702/user_service/__init__.py | 0 .../dfp/v201702/user_service/create_users.py | 0 .../v201702/user_service/deactivate_users.py | 0 .../dfp/v201702/user_service/get_all_roles.py | 0 .../dfp/v201702/user_service/get_all_users.py | 0 .../v201702/user_service/get_current_user.py | 39 ++ .../user_service/get_user_by_email_address.py | 0 .../dfp/v201702/user_service/update_users.py | 0 .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 0 .../delete_user_team_associations.py | 0 .../get_all_user_team_associations.py | 0 .../get_user_team_associations_for_user.py | 0 .../update_user_team_associations.py | 0 .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 0 .../get_workflow_approval_requests.py | 0 ...et_workflow_external_condition_requests.py | 0 ...er_workflow_external_condition_requests.py | 0 .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 5 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 9 +- .../update_audience_segments.py | 4 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_package_item_base_rates.py | 66 +++ .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 2 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 8 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 60 +++ .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 4 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 5 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../update_creative_set.py | 2 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 2 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 2 +- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 2 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 5 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- ...efined_custom_targeting_keys_and_values.py | 2 +- .../update_custom_targeting_keys.py | 5 +- .../update_custom_targeting_values.py | 8 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../update_exchange_rates.py | 2 +- .../get_availability_forecast.py | 22 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 2 +- .../get_all_ad_unit_sizes.py | 2 +- .../inventory_service/get_all_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 2 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 5 +- .../label_service/deactivate_labels.py | 5 +- .../label_service/get_active_labels.py | 2 +- .../label_service/get_all_labels.py | 2 +- .../label_service/update_labels.py | 5 +- .../__init__.py | 0 .../create_licas.py | 5 +- .../deactivate_licas.py | 5 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../update_licas.py | 5 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 5 +- .../line_item_service/create_line_items.py | 25 +- .../create_video_line_item.py | 27 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../line_item_service/pause_line_items.py | 74 ++++ .../target_custom_criteria.py | 5 +- .../line_item_service/update_line_items.py | 5 +- .../v201705/native_style_service/__init__.py | 15 + .../create_native_styles.py | 180 ++++++++ .../get_all_native_styles.py | 51 +++ .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 5 +- .../order_service/create_orders.py | 7 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 2 +- .../order_service/update_orders.py | 5 +- .../package_service/create_packages.py | 61 +++ ...reate_proposal_line_items_from_packages.py | 68 +++ .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 2 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 2 +- .../get_active_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 40 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 2 +- .../update_premium_rates.py | 2 +- .../create_product_package_item.py | 62 +++ .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 2 +- .../create_product_packages.py | 51 +++ .../get_active_product_packages.py | 2 +- .../get_all_product_packages.py | 2 +- .../product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 4 +- .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- ...sh_programmatic_products_to_marketplace.py | 2 +- .../product_service/update_products.py | 2 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 2 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 2 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 2 +- ...create_programmatic_proposal_line_items.py | 33 +- ...sal_line_items_for_non_sales_management.py | 33 +- .../create_proposal_line_items.py | 33 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 2 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 4 +- .../proposal_service/create_proposals.py | 7 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 40 +- .../get_proposals_pending_approval.py | 2 +- .../request_buyers_acceptance.py | 2 +- .../submit_proposals_for_approval.py | 6 +- .../proposal_service/update_proposals.py | 5 +- .../__init__.py | 0 .../fetch_match_tables.py | 6 +- .../get_all_programmatic_buyers.py | 4 +- .../get_recent_changes.py | 210 +++++++++ .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 60 +++ .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 75 ++++ ...update_reconciliation_line_item_reports.py | 67 +++ ...order_reports_for_reconciliation_report.py | 8 +- .../submit_reconciliation_order_reports.py | 71 +++ ...n_report_rows_for_reconciliation_report.py | 24 +- .../update_reconciliation_report_rows.py | 75 ++++ .../get_all_reconciliation_reports.py | 8 +- ...iliation_report_for_last_billing_period.py | 8 +- .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 17 +- .../report_service/run_inventory_report.py | 8 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 8 +- .../report_service/run_sales_report.py | 5 +- .../report_service/run_saved_query.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 2 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 5 +- .../team_service/get_all_teams.py | 2 +- .../team_service/update_teams.py | 2 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 5 +- .../user_service/deactivate_users.py | 5 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 2 +- .../v201705/user_service/get_current_user.py | 39 ++ .../user_service/get_user_by_email_address.py | 2 +- .../user_service/update_users.py | 5 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py | 2 +- ...et_workflow_external_condition_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 2 +- googleads/adwords.py | 12 +- googleads/common.py | 24 +- googleads/dfp.py | 341 ++++++++++++++- setup.py | 0 tests/adwords_test.py | 96 +++- tests/common_test.py | 30 +- tests/dfp_test.py | 411 +++++++++++++++++- 949 files changed, 3346 insertions(+), 646 deletions(-) mode change 100755 => 100644 examples/adwords/v201607/account_management/create_account.py mode change 100755 => 100644 examples/adwords/v201607/account_management/get_account_changes.py mode change 100755 => 100644 examples/adwords/v201607/account_management/get_account_hierarchy.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/add_ad_customizer.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/add_html5_ad.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/add_ad_groups.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/add_campaigns.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/add_expanded_text_ads.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/add_keywords.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/add_text_ads.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/get_ad_groups.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/get_campaigns.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/get_expanded_text_ads.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/get_keywords.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/get_text_ads.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/pause_ad.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/remove_ad.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/remove_ad_group.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/remove_campaign.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/remove_keyword.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/update_ad_group.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/update_campaign.py mode change 100755 => 100644 examples/adwords/v201607/basic_operations/update_keyword.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/add_campaign_labels.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/add_draft.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/add_experiment.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/add_trial.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/get_campaigns_by_label.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/graduate_trial.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/promote_experiment.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/set_ad_parameters.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201607/campaign_management/validate_text_ad.py mode change 100755 => 100644 examples/adwords/v201607/error_handling/handle_partial_failures.py mode change 100755 => 100644 examples/adwords/v201607/error_handling/handle_policy_violation_error.py mode change 100755 => 100644 examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py mode change 100755 => 100644 examples/adwords/v201607/extensions/add_prices.py mode change 100755 => 100644 examples/adwords/v201607/extensions/add_site_links.py mode change 100755 => 100644 examples/adwords/v201607/extensions/add_site_links_using_feeds.py mode change 100755 => 100644 examples/adwords/v201607/migration/migrate_to_extension_settings.py mode change 100755 => 100644 examples/adwords/v201607/misc/get_all_images_and_videos.py mode change 100755 => 100644 examples/adwords/v201607/misc/upload_image.py mode change 100755 => 100644 examples/adwords/v201607/misc/upload_media_bundle.py mode change 100755 => 100644 examples/adwords/v201607/optimization/estimate_keyword_traffic.py mode change 100755 => 100644 examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py mode change 100755 => 100644 examples/adwords/v201607/optimization/get_keyword_bid_simulations.py mode change 100755 => 100644 examples/adwords/v201607/optimization/get_keyword_ideas.py mode change 100755 => 100644 examples/adwords/v201607/remarketing/add_audience.py mode change 100755 => 100644 examples/adwords/v201607/remarketing/add_conversion_tracker.py mode change 100755 => 100644 examples/adwords/v201607/remarketing/add_crm_based_user_list.py mode change 100755 => 100644 examples/adwords/v201607/remarketing/add_rule_based_user_lists.py mode change 100755 => 100644 examples/adwords/v201607/remarketing/upload_offline_conversions.py mode change 100755 => 100644 examples/adwords/v201607/reporting/download_criteria_report.py mode change 100755 => 100644 examples/adwords/v201607/reporting/download_criteria_report_as_stream.py mode change 100755 => 100644 examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py mode change 100755 => 100644 examples/adwords/v201607/reporting/download_criteria_report_as_string.py mode change 100755 => 100644 examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py mode change 100755 => 100644 examples/adwords/v201607/reporting/download_criteria_report_with_awql.py mode change 100755 => 100644 examples/adwords/v201607/reporting/get_report_fields.py mode change 100755 => 100644 examples/adwords/v201607/reporting/parallel_report_download.py mode change 100755 => 100644 examples/adwords/v201607/shopping/add_product_partition_tree.py mode change 100755 => 100644 examples/adwords/v201607/shopping/add_product_scope.py mode change 100755 => 100644 examples/adwords/v201607/shopping/add_shopping_campaign.py mode change 100755 => 100644 examples/adwords/v201607/shopping/get_product_category_taxonomy.py mode change 100755 => 100644 examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py mode change 100755 => 100644 examples/adwords/v201607/targeting/lookup_location.py mode change 100755 => 100644 examples/adwords/v201609/account_management/accept_service_link.py mode change 100755 => 100644 examples/adwords/v201609/account_management/create_account.py mode change 100755 => 100644 examples/adwords/v201609/account_management/get_account_changes.py mode change 100755 => 100644 examples/adwords/v201609/account_management/get_account_hierarchy.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/add_ad_customizer.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/add_html5_ad.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/add_ad_groups.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/add_campaigns.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/add_expanded_text_ads.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/add_keywords.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/get_ad_groups.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/get_campaigns.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/get_expanded_text_ads.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/get_keywords.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/get_text_ads.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/pause_ad.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/remove_ad.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/remove_ad_group.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/remove_campaign.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/remove_keyword.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/update_ad_group.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/update_campaign.py mode change 100755 => 100644 examples/adwords/v201609/basic_operations/update_keyword.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/add_campaign_labels.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/add_draft.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/add_trial.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/get_campaigns_by_label.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/graduate_trial.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/set_ad_parameters.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201609/campaign_management/validate_text_ad.py mode change 100755 => 100644 examples/adwords/v201609/error_handling/handle_partial_failures.py mode change 100755 => 100644 examples/adwords/v201609/error_handling/handle_policy_violation_error.py mode change 100755 => 100644 examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py mode change 100755 => 100644 examples/adwords/v201609/extensions/add_prices.py mode change 100755 => 100644 examples/adwords/v201609/extensions/add_site_links.py mode change 100755 => 100644 examples/adwords/v201609/extensions/add_site_links_using_feeds.py mode change 100755 => 100644 examples/adwords/v201609/migration/migrate_to_extension_settings.py mode change 100755 => 100644 examples/adwords/v201609/misc/get_all_images_and_videos.py mode change 100755 => 100644 examples/adwords/v201609/misc/upload_image.py mode change 100755 => 100644 examples/adwords/v201609/misc/upload_media_bundle.py mode change 100755 => 100644 examples/adwords/v201609/optimization/estimate_keyword_traffic.py mode change 100755 => 100644 examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py mode change 100755 => 100644 examples/adwords/v201609/optimization/get_keyword_bid_simulations.py mode change 100755 => 100644 examples/adwords/v201609/optimization/get_keyword_ideas.py mode change 100755 => 100644 examples/adwords/v201609/remarketing/add_audience.py mode change 100755 => 100644 examples/adwords/v201609/remarketing/add_conversion_tracker.py mode change 100755 => 100644 examples/adwords/v201609/remarketing/add_crm_based_user_list.py mode change 100755 => 100644 examples/adwords/v201609/remarketing/add_rule_based_user_lists.py mode change 100755 => 100644 examples/adwords/v201609/remarketing/upload_offline_call_conversions.py mode change 100755 => 100644 examples/adwords/v201609/remarketing/upload_offline_conversions.py mode change 100755 => 100644 examples/adwords/v201609/reporting/download_criteria_report.py mode change 100755 => 100644 examples/adwords/v201609/reporting/download_criteria_report_as_stream.py mode change 100755 => 100644 examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py mode change 100755 => 100644 examples/adwords/v201609/reporting/download_criteria_report_as_string.py mode change 100755 => 100644 examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py mode change 100755 => 100644 examples/adwords/v201609/reporting/download_criteria_report_with_awql.py mode change 100755 => 100644 examples/adwords/v201609/reporting/get_report_fields.py mode change 100755 => 100644 examples/adwords/v201609/reporting/parallel_report_download.py mode change 100755 => 100644 examples/adwords/v201609/shopping/add_product_partition_tree.py mode change 100755 => 100644 examples/adwords/v201609/shopping/add_product_scope.py mode change 100755 => 100644 examples/adwords/v201609/shopping/add_shopping_campaign.py mode change 100755 => 100644 examples/adwords/v201609/shopping/get_product_category_taxonomy.py mode change 100755 => 100644 examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py mode change 100755 => 100644 examples/adwords/v201609/targeting/lookup_location.py mode change 100755 => 100644 examples/adwords/v201702/account_management/accept_service_link.py mode change 100755 => 100644 examples/adwords/v201702/account_management/create_account.py mode change 100755 => 100644 examples/adwords/v201702/account_management/get_account_changes.py mode change 100755 => 100644 examples/adwords/v201702/account_management/get_account_hierarchy.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/add_ad_customizer.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/add_html5_ad.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/add_ad_groups.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/add_campaigns.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/add_expanded_text_ads.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/add_keywords.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/get_ad_groups.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/get_campaigns.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/get_expanded_text_ads.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/get_keywords.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/get_text_ads.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/pause_ad.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/remove_ad.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/remove_ad_group.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/remove_campaign.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/remove_keyword.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/update_ad_group.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/update_campaign.py mode change 100755 => 100644 examples/adwords/v201702/basic_operations/update_keyword.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/add_campaign_labels.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/add_draft.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/add_trial.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/get_campaigns_by_label.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/graduate_trial.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/set_ad_parameters.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py mode change 100755 => 100644 examples/adwords/v201702/campaign_management/validate_text_ad.py mode change 100755 => 100644 examples/adwords/v201702/error_handling/handle_partial_failures.py mode change 100755 => 100644 examples/adwords/v201702/error_handling/handle_policy_violation_error.py mode change 100755 => 100644 examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py mode change 100755 => 100644 examples/adwords/v201702/extensions/add_prices.py mode change 100755 => 100644 examples/adwords/v201702/extensions/add_site_links.py mode change 100755 => 100644 examples/adwords/v201702/extensions/add_site_links_using_feeds.py mode change 100755 => 100644 examples/adwords/v201702/migration/migrate_to_extension_settings.py mode change 100755 => 100644 examples/adwords/v201702/misc/get_all_images_and_videos.py mode change 100755 => 100644 examples/adwords/v201702/misc/upload_image.py mode change 100755 => 100644 examples/adwords/v201702/misc/upload_media_bundle.py mode change 100755 => 100644 examples/adwords/v201702/optimization/estimate_keyword_traffic.py mode change 100755 => 100644 examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py mode change 100755 => 100644 examples/adwords/v201702/optimization/get_keyword_bid_simulations.py mode change 100755 => 100644 examples/adwords/v201702/optimization/get_keyword_ideas.py mode change 100755 => 100644 examples/adwords/v201702/remarketing/add_audience.py mode change 100755 => 100644 examples/adwords/v201702/remarketing/add_conversion_tracker.py mode change 100755 => 100644 examples/adwords/v201702/remarketing/add_crm_based_user_list.py mode change 100755 => 100644 examples/adwords/v201702/remarketing/add_rule_based_user_lists.py mode change 100755 => 100644 examples/adwords/v201702/remarketing/upload_offline_call_conversions.py mode change 100755 => 100644 examples/adwords/v201702/remarketing/upload_offline_conversions.py mode change 100755 => 100644 examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py mode change 100755 => 100644 examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py mode change 100755 => 100644 examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py mode change 100755 => 100644 examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py mode change 100755 => 100644 examples/adwords/v201702/reporting/download_criteria_report_with_awql.py mode change 100755 => 100644 examples/adwords/v201702/reporting/download_criteria_report_with_selector.py mode change 100755 => 100644 examples/adwords/v201702/reporting/get_report_fields.py mode change 100755 => 100644 examples/adwords/v201702/reporting/parallel_report_download.py mode change 100755 => 100644 examples/adwords/v201702/shopping/add_product_partition_tree.py mode change 100755 => 100644 examples/adwords/v201702/shopping/add_product_scope.py mode change 100755 => 100644 examples/adwords/v201702/shopping/add_shopping_campaign.py mode change 100755 => 100644 examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py mode change 100755 => 100644 examples/adwords/v201702/shopping/get_product_category_taxonomy.py mode change 100755 => 100644 examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py mode change 100755 => 100644 examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py mode change 100755 => 100644 examples/adwords/v201702/targeting/lookup_location.py delete mode 100755 examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py mode change 100755 => 100644 examples/dfp/v201611/activity_group_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/activity_group_service/create_activity_groups.py mode change 100755 => 100644 examples/dfp/v201611/activity_group_service/get_active_activity_groups.py mode change 100755 => 100644 examples/dfp/v201611/activity_group_service/get_all_activity_groups.py mode change 100755 => 100644 examples/dfp/v201611/activity_group_service/update_activity_groups.py mode change 100755 => 100644 examples/dfp/v201611/activity_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/activity_service/create_activities.py mode change 100755 => 100644 examples/dfp/v201611/activity_service/get_active_activities.py mode change 100755 => 100644 examples/dfp/v201611/activity_service/get_all_activities.py mode change 100755 => 100644 examples/dfp/v201611/activity_service/update_activities.py mode change 100755 => 100644 examples/dfp/v201611/audience_segment_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/audience_segment_service/create_audience_segments.py mode change 100755 => 100644 examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py mode change 100755 => 100644 examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py mode change 100755 => 100644 examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py mode change 100755 => 100644 examples/dfp/v201611/audience_segment_service/update_audience_segments.py mode change 100755 => 100644 examples/dfp/v201611/base_rate_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/base_rate_service/create_product_base_rates.py mode change 100755 => 100644 examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py mode change 100755 => 100644 examples/dfp/v201611/base_rate_service/get_all_base_rates.py mode change 100755 => 100644 examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py mode change 100755 => 100644 examples/dfp/v201611/base_rate_service/update_base_rates.py mode change 100755 => 100644 examples/dfp/v201611/company_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/company_service/create_companies.py mode change 100755 => 100644 examples/dfp/v201611/company_service/get_advertisers.py mode change 100755 => 100644 examples/dfp/v201611/company_service/get_all_companies.py mode change 100755 => 100644 examples/dfp/v201611/company_service/update_companies.py mode change 100755 => 100644 examples/dfp/v201611/contact_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/contact_service/create_contacts.py mode change 100755 => 100644 examples/dfp/v201611/contact_service/get_all_contacts.py mode change 100755 => 100644 examples/dfp/v201611/contact_service/get_uninvited_contacts.py mode change 100755 => 100644 examples/dfp/v201611/contact_service/update_contacts.py mode change 100755 => 100644 examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py mode change 100755 => 100644 examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py mode change 100755 => 100644 examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py mode change 100755 => 100644 examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py mode change 100755 => 100644 examples/dfp/v201611/content_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/content_service/get_all_content.py mode change 100755 => 100644 examples/dfp/v201611/creative_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/creative_service/create_creative_from_template.py mode change 100755 => 100644 examples/dfp/v201611/creative_service/create_creatives.py mode change 100755 => 100644 examples/dfp/v201611/creative_service/create_custom_creative.py mode change 100755 => 100644 examples/dfp/v201611/creative_service/create_native_creative.py mode change 100755 => 100644 examples/dfp/v201611/creative_service/get_all_creatives.py mode change 100755 => 100644 examples/dfp/v201611/creative_service/get_image_creatives.py mode change 100755 => 100644 examples/dfp/v201611/creative_service/update_creatives.py mode change 100755 => 100644 examples/dfp/v201611/creative_set_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py mode change 100755 => 100644 examples/dfp/v201611/creative_set_service/create_creative_set.py mode change 100755 => 100644 examples/dfp/v201611/creative_set_service/get_all_creative_sets.py mode change 100755 => 100644 examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py mode change 100755 => 100644 examples/dfp/v201611/creative_set_service/update_creative_set.py mode change 100755 => 100644 examples/dfp/v201611/creative_template_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/creative_template_service/get_all_creative_templates.py mode change 100755 => 100644 examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py mode change 100755 => 100644 examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py mode change 100755 => 100644 examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py mode change 100755 => 100644 examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py mode change 100755 => 100644 examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py mode change 100755 => 100644 examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py mode change 100755 => 100644 examples/dfp/v201611/custom_field_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/custom_field_service/create_custom_field_options.py mode change 100755 => 100644 examples/dfp/v201611/custom_field_service/create_custom_fields.py mode change 100755 => 100644 examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py mode change 100755 => 100644 examples/dfp/v201611/custom_field_service/get_all_custom_fields.py mode change 100755 => 100644 examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py mode change 100755 => 100644 examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py mode change 100755 => 100644 examples/dfp/v201611/custom_field_service/update_custom_fields.py mode change 100755 => 100644 examples/dfp/v201611/custom_targeting_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py mode change 100755 => 100644 examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py mode change 100755 => 100644 examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py mode change 100755 => 100644 examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py mode change 100755 => 100644 examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py mode change 100755 => 100644 examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py mode change 100755 => 100644 examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py mode change 100755 => 100644 examples/dfp/v201611/exchange_rate_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py mode change 100755 => 100644 examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py mode change 100755 => 100644 examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py mode change 100755 => 100644 examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py mode change 100755 => 100644 examples/dfp/v201611/forecast_service/get_availability_forecast.py mode change 100755 => 100644 examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py mode change 100755 => 100644 examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py mode change 100755 => 100644 examples/dfp/v201611/inventory_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/inventory_service/archive_ad_units.py mode change 100755 => 100644 examples/dfp/v201611/inventory_service/create_ad_units.py mode change 100755 => 100644 examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py mode change 100755 => 100644 examples/dfp/v201611/inventory_service/get_all_ad_units.py mode change 100755 => 100644 examples/dfp/v201611/inventory_service/update_ad_units.py mode change 100755 => 100644 examples/dfp/v201611/label_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/label_service/create_labels.py mode change 100755 => 100644 examples/dfp/v201611/label_service/deactivate_labels.py mode change 100755 => 100644 examples/dfp/v201611/label_service/get_active_labels.py mode change 100755 => 100644 examples/dfp/v201611/label_service/get_all_labels.py mode change 100755 => 100644 examples/dfp/v201611/label_service/update_labels.py mode change 100755 => 100644 examples/dfp/v201611/line_item_creative_association_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/line_item_creative_association_service/create_licas.py mode change 100755 => 100644 examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py mode change 100755 => 100644 examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py mode change 100755 => 100644 examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py mode change 100755 => 100644 examples/dfp/v201611/line_item_creative_association_service/update_licas.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/activate_line_items.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/create_line_items.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/create_video_line_item.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/get_all_line_items.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/target_custom_criteria.py mode change 100755 => 100644 examples/dfp/v201611/line_item_service/update_line_items.py mode change 100755 => 100644 examples/dfp/v201611/network_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/network_service/get_all_networks.py mode change 100755 => 100644 examples/dfp/v201611/network_service/make_test_network.py mode change 100755 => 100644 examples/dfp/v201611/order_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/order_service/approve_orders.py mode change 100755 => 100644 examples/dfp/v201611/order_service/create_orders.py mode change 100755 => 100644 examples/dfp/v201611/order_service/get_all_orders.py mode change 100755 => 100644 examples/dfp/v201611/order_service/get_orders_starting_soon.py mode change 100755 => 100644 examples/dfp/v201611/order_service/update_orders.py mode change 100755 => 100644 examples/dfp/v201611/package_service/get_all_packages.py mode change 100755 => 100644 examples/dfp/v201611/package_service/get_in_progress_packages.py mode change 100755 => 100644 examples/dfp/v201611/placement_service/create_placements.py mode change 100755 => 100644 examples/dfp/v201611/placement_service/deactivate_placements.py mode change 100755 => 100644 examples/dfp/v201611/placement_service/get_active_placements.py mode change 100755 => 100644 examples/dfp/v201611/placement_service/get_all_placements.py mode change 100755 => 100644 examples/dfp/v201611/placement_service/update_placements.py mode change 100755 => 100644 examples/dfp/v201611/premium_rate_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/premium_rate_service/create_premium_rates.py mode change 100755 => 100644 examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py mode change 100755 => 100644 examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py mode change 100755 => 100644 examples/dfp/v201611/premium_rate_service/update_premium_rates.py mode change 100755 => 100644 examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py mode change 100755 => 100644 examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py mode change 100755 => 100644 examples/dfp/v201611/product_package_service/get_active_product_packages.py mode change 100755 => 100644 examples/dfp/v201611/product_package_service/get_all_product_packages.py mode change 100755 => 100644 examples/dfp/v201611/product_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py mode change 100755 => 100644 examples/dfp/v201611/product_service/get_all_products.py mode change 100755 => 100644 examples/dfp/v201611/product_service/get_products_for_product_template.py mode change 100755 => 100644 examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py mode change 100755 => 100644 examples/dfp/v201611/product_service/update_products.py mode change 100755 => 100644 examples/dfp/v201611/product_template_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/product_template_service/activate_product_templates.py mode change 100755 => 100644 examples/dfp/v201611/product_template_service/create_product_templates.py mode change 100755 => 100644 examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py mode change 100755 => 100644 examples/dfp/v201611/product_template_service/get_all_product_templates.py mode change 100755 => 100644 examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py mode change 100755 => 100644 examples/dfp/v201611/product_template_service/update_product_templates.py mode change 100755 => 100644 examples/dfp/v201611/proposal_line_item_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py mode change 100755 => 100644 examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py mode change 100755 => 100644 examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/create_programmatic_proposals.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/create_proposals.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/get_all_proposals.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/get_marketplace_comments.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/request_buyers_acceptance.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py mode change 100755 => 100644 examples/dfp/v201611/proposal_service/update_proposals.py mode change 100755 => 100644 examples/dfp/v201611/publisher_query_language_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py mode change 100755 => 100644 examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py mode change 100755 => 100644 examples/dfp/v201611/rate_card_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/rate_card_service/get_all_rate_cards.py mode change 100755 => 100644 examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py mode change 100755 => 100644 examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py mode change 100755 => 100644 examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py mode change 100755 => 100644 examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py mode change 100755 => 100644 examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py mode change 100755 => 100644 examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py mode change 100755 => 100644 examples/dfp/v201611/report_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/report_service/run_delivery_report.py mode change 100755 => 100644 examples/dfp/v201611/report_service/run_inventory_report.py mode change 100755 => 100644 examples/dfp/v201611/report_service/run_reach_report.py mode change 100755 => 100644 examples/dfp/v201611/report_service/run_report_with_custom_fields.py mode change 100755 => 100644 examples/dfp/v201611/report_service/run_sales_report.py mode change 100755 => 100644 examples/dfp/v201611/report_service/run_saved_query.py mode change 100755 => 100644 examples/dfp/v201611/suggested_ad_unit_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py mode change 100755 => 100644 examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py mode change 100755 => 100644 examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py mode change 100755 => 100644 examples/dfp/v201611/team_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/team_service/create_teams.py mode change 100755 => 100644 examples/dfp/v201611/team_service/get_all_teams.py mode change 100755 => 100644 examples/dfp/v201611/team_service/update_teams.py mode change 100755 => 100644 examples/dfp/v201611/user_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/user_service/create_users.py mode change 100755 => 100644 examples/dfp/v201611/user_service/deactivate_users.py mode change 100755 => 100644 examples/dfp/v201611/user_service/get_all_roles.py mode change 100755 => 100644 examples/dfp/v201611/user_service/get_all_users.py mode change 100755 => 100644 examples/dfp/v201611/user_service/get_user_by_email_address.py mode change 100755 => 100644 examples/dfp/v201611/user_service/update_users.py mode change 100755 => 100644 examples/dfp/v201611/user_team_association_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/user_team_association_service/create_user_team_associations.py mode change 100755 => 100644 examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py mode change 100755 => 100644 examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py mode change 100755 => 100644 examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py mode change 100755 => 100644 examples/dfp/v201611/user_team_association_service/update_user_team_associations.py mode change 100755 => 100644 examples/dfp/v201611/workflow_request_service/__init__.py mode change 100755 => 100644 examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py mode change 100755 => 100644 examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py mode change 100755 => 100644 examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py mode change 100755 => 100644 examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py mode change 100755 => 100644 examples/dfp/v201702/activity_group_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/activity_group_service/create_activity_groups.py mode change 100755 => 100644 examples/dfp/v201702/activity_group_service/get_active_activity_groups.py mode change 100755 => 100644 examples/dfp/v201702/activity_group_service/get_all_activity_groups.py mode change 100755 => 100644 examples/dfp/v201702/activity_group_service/update_activity_groups.py mode change 100755 => 100644 examples/dfp/v201702/activity_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/activity_service/create_activities.py mode change 100755 => 100644 examples/dfp/v201702/activity_service/get_active_activities.py mode change 100755 => 100644 examples/dfp/v201702/activity_service/get_all_activities.py mode change 100755 => 100644 examples/dfp/v201702/activity_service/update_activities.py mode change 100755 => 100644 examples/dfp/v201702/audience_segment_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/audience_segment_service/create_audience_segments.py mode change 100755 => 100644 examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py mode change 100755 => 100644 examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py mode change 100755 => 100644 examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py mode change 100755 => 100644 examples/dfp/v201702/audience_segment_service/update_audience_segments.py mode change 100755 => 100644 examples/dfp/v201702/base_rate_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/base_rate_service/create_product_base_rates.py create mode 100755 examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py mode change 100755 => 100644 examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py mode change 100755 => 100644 examples/dfp/v201702/base_rate_service/get_all_base_rates.py mode change 100755 => 100644 examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py mode change 100755 => 100644 examples/dfp/v201702/base_rate_service/update_base_rates.py mode change 100755 => 100644 examples/dfp/v201702/company_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/company_service/create_companies.py mode change 100755 => 100644 examples/dfp/v201702/company_service/get_advertisers.py mode change 100755 => 100644 examples/dfp/v201702/company_service/get_all_companies.py mode change 100755 => 100644 examples/dfp/v201702/company_service/update_companies.py mode change 100755 => 100644 examples/dfp/v201702/contact_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/contact_service/create_contacts.py mode change 100755 => 100644 examples/dfp/v201702/contact_service/get_all_contacts.py mode change 100755 => 100644 examples/dfp/v201702/contact_service/get_uninvited_contacts.py mode change 100755 => 100644 examples/dfp/v201702/contact_service/update_contacts.py mode change 100755 => 100644 examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py mode change 100755 => 100644 examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py mode change 100755 => 100644 examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py mode change 100755 => 100644 examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py mode change 100755 => 100644 examples/dfp/v201702/content_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/content_service/get_all_content.py mode change 100755 => 100644 examples/dfp/v201702/creative_service/__init__.py create mode 100755 examples/dfp/v201702/creative_service/copy_image_creatives.py mode change 100755 => 100644 examples/dfp/v201702/creative_service/create_creative_from_template.py mode change 100755 => 100644 examples/dfp/v201702/creative_service/create_creatives.py mode change 100755 => 100644 examples/dfp/v201702/creative_service/create_custom_creative.py mode change 100755 => 100644 examples/dfp/v201702/creative_service/create_native_creative.py mode change 100755 => 100644 examples/dfp/v201702/creative_service/get_all_creatives.py mode change 100755 => 100644 examples/dfp/v201702/creative_service/get_image_creatives.py mode change 100755 => 100644 examples/dfp/v201702/creative_service/update_creatives.py mode change 100755 => 100644 examples/dfp/v201702/creative_set_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py mode change 100755 => 100644 examples/dfp/v201702/creative_set_service/create_creative_set.py mode change 100755 => 100644 examples/dfp/v201702/creative_set_service/get_all_creative_sets.py mode change 100755 => 100644 examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py mode change 100755 => 100644 examples/dfp/v201702/creative_set_service/update_creative_set.py mode change 100755 => 100644 examples/dfp/v201702/creative_template_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/creative_template_service/get_all_creative_templates.py mode change 100755 => 100644 examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py mode change 100755 => 100644 examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py mode change 100755 => 100644 examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py mode change 100755 => 100644 examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py mode change 100755 => 100644 examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py mode change 100755 => 100644 examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py mode change 100755 => 100644 examples/dfp/v201702/custom_field_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/custom_field_service/create_custom_field_options.py mode change 100755 => 100644 examples/dfp/v201702/custom_field_service/create_custom_fields.py mode change 100755 => 100644 examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py mode change 100755 => 100644 examples/dfp/v201702/custom_field_service/get_all_custom_fields.py mode change 100755 => 100644 examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py mode change 100755 => 100644 examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py mode change 100755 => 100644 examples/dfp/v201702/custom_field_service/update_custom_fields.py mode change 100755 => 100644 examples/dfp/v201702/custom_targeting_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py mode change 100755 => 100644 examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py mode change 100755 => 100644 examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py mode change 100755 => 100644 examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py mode change 100755 => 100644 examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py mode change 100755 => 100644 examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py mode change 100755 => 100644 examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py mode change 100755 => 100644 examples/dfp/v201702/exchange_rate_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py mode change 100755 => 100644 examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py mode change 100755 => 100644 examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py mode change 100755 => 100644 examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py mode change 100755 => 100644 examples/dfp/v201702/forecast_service/get_availability_forecast.py mode change 100755 => 100644 examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py mode change 100755 => 100644 examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py mode change 100755 => 100644 examples/dfp/v201702/inventory_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/inventory_service/archive_ad_units.py mode change 100755 => 100644 examples/dfp/v201702/inventory_service/create_ad_units.py mode change 100755 => 100644 examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py mode change 100755 => 100644 examples/dfp/v201702/inventory_service/get_all_ad_units.py mode change 100755 => 100644 examples/dfp/v201702/inventory_service/update_ad_units.py mode change 100755 => 100644 examples/dfp/v201702/label_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/label_service/create_labels.py mode change 100755 => 100644 examples/dfp/v201702/label_service/deactivate_labels.py mode change 100755 => 100644 examples/dfp/v201702/label_service/get_active_labels.py mode change 100755 => 100644 examples/dfp/v201702/label_service/get_all_labels.py mode change 100755 => 100644 examples/dfp/v201702/label_service/update_labels.py mode change 100755 => 100644 examples/dfp/v201702/line_item_creative_association_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/line_item_creative_association_service/create_licas.py mode change 100755 => 100644 examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py mode change 100755 => 100644 examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py mode change 100755 => 100644 examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py mode change 100755 => 100644 examples/dfp/v201702/line_item_creative_association_service/update_licas.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/activate_line_items.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/create_line_items.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/create_video_line_item.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/get_all_line_items.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py create mode 100755 examples/dfp/v201702/line_item_service/pause_line_items.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/target_custom_criteria.py mode change 100755 => 100644 examples/dfp/v201702/line_item_service/update_line_items.py mode change 100755 => 100644 examples/dfp/v201702/native_style_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/native_style_service/create_native_styles.py mode change 100755 => 100644 examples/dfp/v201702/native_style_service/get_all_native_styles.py mode change 100755 => 100644 examples/dfp/v201702/network_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/network_service/get_all_networks.py mode change 100755 => 100644 examples/dfp/v201702/network_service/make_test_network.py mode change 100755 => 100644 examples/dfp/v201702/order_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/order_service/approve_orders.py mode change 100755 => 100644 examples/dfp/v201702/order_service/create_orders.py mode change 100755 => 100644 examples/dfp/v201702/order_service/get_all_orders.py mode change 100755 => 100644 examples/dfp/v201702/order_service/get_orders_starting_soon.py mode change 100755 => 100644 examples/dfp/v201702/order_service/update_orders.py create mode 100755 examples/dfp/v201702/package_service/create_packages.py create mode 100755 examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py mode change 100755 => 100644 examples/dfp/v201702/package_service/get_all_packages.py mode change 100755 => 100644 examples/dfp/v201702/package_service/get_in_progress_packages.py mode change 100755 => 100644 examples/dfp/v201702/placement_service/create_placements.py mode change 100755 => 100644 examples/dfp/v201702/placement_service/deactivate_placements.py mode change 100755 => 100644 examples/dfp/v201702/placement_service/get_active_placements.py mode change 100755 => 100644 examples/dfp/v201702/placement_service/get_all_placements.py mode change 100755 => 100644 examples/dfp/v201702/placement_service/update_placements.py mode change 100755 => 100644 examples/dfp/v201702/premium_rate_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/premium_rate_service/create_premium_rates.py mode change 100755 => 100644 examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py mode change 100755 => 100644 examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py mode change 100755 => 100644 examples/dfp/v201702/premium_rate_service/update_premium_rates.py create mode 100755 examples/dfp/v201702/product_package_item_service/create_product_package_item.py mode change 100755 => 100644 examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py mode change 100755 => 100644 examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py create mode 100755 examples/dfp/v201702/product_package_service/create_product_packages.py mode change 100755 => 100644 examples/dfp/v201702/product_package_service/get_active_product_packages.py mode change 100755 => 100644 examples/dfp/v201702/product_package_service/get_all_product_packages.py mode change 100755 => 100644 examples/dfp/v201702/product_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py mode change 100755 => 100644 examples/dfp/v201702/product_service/get_all_products.py mode change 100755 => 100644 examples/dfp/v201702/product_service/get_products_for_product_template.py mode change 100755 => 100644 examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py mode change 100755 => 100644 examples/dfp/v201702/product_service/update_products.py mode change 100755 => 100644 examples/dfp/v201702/product_template_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/product_template_service/activate_product_templates.py mode change 100755 => 100644 examples/dfp/v201702/product_template_service/create_product_templates.py mode change 100755 => 100644 examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py mode change 100755 => 100644 examples/dfp/v201702/product_template_service/get_all_product_templates.py mode change 100755 => 100644 examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py mode change 100755 => 100644 examples/dfp/v201702/product_template_service/update_product_templates.py mode change 100755 => 100644 examples/dfp/v201702/proposal_line_item_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py mode change 100755 => 100644 examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py mode change 100755 => 100644 examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/create_programmatic_proposals.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/create_proposals.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/get_all_proposals.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/get_marketplace_comments.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/request_buyers_acceptance.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py mode change 100755 => 100644 examples/dfp/v201702/proposal_service/update_proposals.py mode change 100755 => 100644 examples/dfp/v201702/publisher_query_language_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py mode change 100755 => 100644 examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py mode change 100755 => 100644 examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py mode change 100755 => 100644 examples/dfp/v201702/rate_card_service/__init__.py create mode 100755 examples/dfp/v201702/rate_card_service/create_rate_cards.py mode change 100755 => 100644 examples/dfp/v201702/rate_card_service/get_all_rate_cards.py mode change 100755 => 100644 examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py mode change 100755 => 100644 examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py create mode 100644 examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py mode change 100755 => 100644 examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py create mode 100644 examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py mode change 100755 => 100644 examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py create mode 100644 examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py mode change 100755 => 100644 examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py mode change 100755 => 100644 examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py mode change 100755 => 100644 examples/dfp/v201702/report_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/report_service/run_delivery_report.py mode change 100755 => 100644 examples/dfp/v201702/report_service/run_inventory_report.py mode change 100755 => 100644 examples/dfp/v201702/report_service/run_reach_report.py mode change 100755 => 100644 examples/dfp/v201702/report_service/run_report_with_custom_fields.py mode change 100755 => 100644 examples/dfp/v201702/report_service/run_sales_report.py mode change 100755 => 100644 examples/dfp/v201702/report_service/run_saved_query.py mode change 100755 => 100644 examples/dfp/v201702/suggested_ad_unit_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py mode change 100755 => 100644 examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py mode change 100755 => 100644 examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py mode change 100755 => 100644 examples/dfp/v201702/team_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/team_service/create_teams.py mode change 100755 => 100644 examples/dfp/v201702/team_service/get_all_teams.py mode change 100755 => 100644 examples/dfp/v201702/team_service/update_teams.py mode change 100755 => 100644 examples/dfp/v201702/user_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/user_service/create_users.py mode change 100755 => 100644 examples/dfp/v201702/user_service/deactivate_users.py mode change 100755 => 100644 examples/dfp/v201702/user_service/get_all_roles.py mode change 100755 => 100644 examples/dfp/v201702/user_service/get_all_users.py create mode 100755 examples/dfp/v201702/user_service/get_current_user.py mode change 100755 => 100644 examples/dfp/v201702/user_service/get_user_by_email_address.py mode change 100755 => 100644 examples/dfp/v201702/user_service/update_users.py mode change 100755 => 100644 examples/dfp/v201702/user_team_association_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/user_team_association_service/create_user_team_associations.py mode change 100755 => 100644 examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py mode change 100755 => 100644 examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py mode change 100755 => 100644 examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py mode change 100755 => 100644 examples/dfp/v201702/user_team_association_service/update_user_team_associations.py mode change 100755 => 100644 examples/dfp/v201702/workflow_request_service/__init__.py mode change 100755 => 100644 examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py mode change 100755 => 100644 examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py mode change 100755 => 100644 examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py mode change 100755 => 100644 examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py rename examples/dfp/{v201608 => v201705}/activity_group_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_group_service/create_activity_groups.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_group_service/get_active_activity_groups.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_group_service/get_all_activity_groups.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_group_service/update_activity_groups.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_service/create_activities.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_service/get_active_activities.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_service/get_all_activities.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/activity_service/update_activities.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/audience_segment_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/audience_segment_service/create_audience_segments.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/audience_segment_service/get_all_audience_segments.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/audience_segment_service/get_first_party_audience_segments.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/audience_segment_service/populate_first_party_audience_segments.py (90%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/audience_segment_service/update_audience_segments.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/base_rate_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/base_rate_service/create_product_base_rates.py (97%) mode change 100755 => 100644 create mode 100755 examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py rename examples/dfp/{v201608 => v201705}/base_rate_service/create_product_template_base_rates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/base_rate_service/get_all_base_rates.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/base_rate_service/get_base_rates_for_rate_card.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/base_rate_service/update_base_rates.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/company_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/company_service/create_companies.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/company_service/get_advertisers.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/company_service/get_all_companies.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/company_service/update_companies.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/contact_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/contact_service/create_contacts.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/contact_service/get_all_contacts.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/contact_service/get_uninvited_contacts.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/contact_service/update_contacts.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/content_metadata_key_hierarchy_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (89%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/content_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/content_service/get_all_content.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_service/__init__.py (100%) mode change 100755 => 100644 create mode 100755 examples/dfp/v201705/creative_service/copy_image_creatives.py rename examples/dfp/{v201608 => v201705}/creative_service/create_creative_from_template.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_service/create_creatives.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_service/create_custom_creative.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_service/create_native_creative.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_service/get_all_creatives.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_service/get_image_creatives.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_service/update_creatives.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_set_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_set_service/associate_creative_set_to_line_item.py (92%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_set_service/create_creative_set.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_set_service/get_all_creative_sets.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_set_service/get_creative_sets_for_master_creative.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_set_service/update_creative_set.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_template_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_template_service/get_all_creative_templates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_template_service/get_system_defined_creative_templates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_wrapper_service/create_creative_wrappers.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_wrapper_service/deactivate_creative_wrapper.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_wrapper_service/get_active_creative_wrappers.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_wrapper_service/get_all_creative_wrappers.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/creative_wrapper_service/update_creative_wrappers.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_field_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_field_service/create_custom_field_options.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_field_service/create_custom_fields.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_field_service/deactivate_all_line_item_custom_fields.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_field_service/get_all_custom_fields.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_field_service/get_custom_fields_for_line_items.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_field_service/set_line_item_custom_field_value.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_field_service/update_custom_fields.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_targeting_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_targeting_service/delete_custom_targeting_keys.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_targeting_service/delete_custom_targeting_values.py (95%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_targeting_service/update_custom_targeting_keys.py (95%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/custom_targeting_service/update_custom_targeting_values.py (91%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/exchange_rate_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/exchange_rate_service/create_exchange_rates.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/exchange_rate_service/get_all_exchange_rates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/exchange_rate_service/get_exchange_rates_for_currency_code.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/exchange_rate_service/update_exchange_rates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/forecast_service/get_availability_forecast.py (92%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/forecast_service/get_availability_forecast_for_line_item.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/forecast_service/get_delivery_forecast_for_line_items.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/inventory_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/inventory_service/archive_ad_units.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/inventory_service/create_ad_units.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/inventory_service/get_all_ad_unit_sizes.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/inventory_service/get_all_ad_units.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/inventory_service/update_ad_units.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/label_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/label_service/create_labels.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/label_service/deactivate_labels.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/label_service/get_active_labels.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/label_service/get_all_labels.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/label_service/update_labels.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_creative_association_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_creative_association_service/create_licas.py (93%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_creative_association_service/deactivate_licas.py (95%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_creative_association_service/get_all_licas.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_creative_association_service/get_licas_for_line_item.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_creative_association_service/update_licas.py (94%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_service/activate_line_items.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_service/create_line_items.py (92%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_service/create_video_line_item.py (90%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_service/get_all_line_items.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_service/get_line_items_that_need_creatives.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_service/get_recently_updated_line_items.py (99%) mode change 100755 => 100644 create mode 100755 examples/dfp/v201705/line_item_service/pause_line_items.py rename examples/dfp/{v201608 => v201705}/line_item_service/target_custom_criteria.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/line_item_service/update_line_items.py (96%) mode change 100755 => 100644 create mode 100644 examples/dfp/v201705/native_style_service/__init__.py create mode 100644 examples/dfp/v201705/native_style_service/create_native_styles.py create mode 100644 examples/dfp/v201705/native_style_service/get_all_native_styles.py rename examples/dfp/{v201608 => v201705}/network_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/network_service/get_all_networks.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/network_service/make_test_network.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/order_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/order_service/approve_orders.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/order_service/create_orders.py (94%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/order_service/get_all_orders.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/order_service/get_orders_starting_soon.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/order_service/update_orders.py (97%) mode change 100755 => 100644 create mode 100755 examples/dfp/v201705/package_service/create_packages.py create mode 100755 examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py rename examples/dfp/{v201608 => v201705}/package_service/get_all_packages.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/package_service/get_in_progress_packages.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/placement_service/create_placements.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/placement_service/deactivate_placements.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/placement_service/get_active_placements.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/placement_service/get_all_placements.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/placement_service/update_placements.py (56%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/premium_rate_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/premium_rate_service/create_premium_rates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/premium_rate_service/get_all_premium_rates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/premium_rate_service/get_premium_rates_for_rate_card.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/premium_rate_service/update_premium_rates.py (97%) mode change 100755 => 100644 create mode 100755 examples/dfp/v201705/product_package_item_service/create_product_package_item.py rename examples/dfp/{v201608 => v201705}/product_package_item_service/get_all_product_package_items.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_package_item_service/get_product_package_items_for_product_package.py (97%) mode change 100755 => 100644 create mode 100755 examples/dfp/v201705/product_package_service/create_product_packages.py rename examples/dfp/{v201608 => v201705}/product_package_service/get_active_product_packages.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_package_service/get_all_product_packages.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_service/create_programmatic_products_for_non_sales_management.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_service/get_all_products.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_service/get_products_for_product_template.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_service/publish_programmatic_products_to_marketplace.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_service/update_products.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_template_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_template_service/activate_product_templates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_template_service/create_product_templates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_template_service/create_programmatic_product_templates.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_template_service/get_all_product_templates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_template_service/get_sponsorship_product_templates.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/product_template_service/update_product_templates.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_line_item_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_line_item_service/archive_proposal_line_items.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_line_item_service/create_programmatic_proposal_line_items.py (82%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (82%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_line_item_service/create_proposal_line_items.py (82%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_line_item_service/get_all_proposal_line_items.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_line_item_service/update_proposal_line_items.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/create_programmatic_proposals.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/create_proposals.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/get_all_proposals.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/get_marketplace_comments.py (55%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/get_proposals_pending_approval.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/request_buyers_acceptance.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/submit_proposals_for_approval.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/proposal_service/update_proposals.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/publisher_query_language_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/publisher_query_language_service/fetch_match_tables.py (90%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/publisher_query_language_service/get_all_programmatic_buyers.py (91%) mode change 100755 => 100644 create mode 100644 examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py rename examples/dfp/{v201608 => v201705}/rate_card_service/__init__.py (100%) mode change 100755 => 100644 create mode 100755 examples/dfp/v201705/rate_card_service/create_rate_cards.py rename examples/dfp/{v201608 => v201705}/rate_card_service/get_all_rate_cards.py (99%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/rate_card_service/get_marketplace_rate_cards.py (99%) mode change 100755 => 100644 create mode 100644 examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py create mode 100644 examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename examples/dfp/{v201608 => v201705}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (91%) mode change 100755 => 100644 create mode 100644 examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename examples/dfp/{v201608 => v201705}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (84%) mode change 100755 => 100644 create mode 100644 examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py rename examples/dfp/{v201608 => v201705}/reconciliation_report_service/get_all_reconciliation_reports.py (90%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (91%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/report_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/report_service/run_delivery_report.py (83%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/report_service/run_inventory_report.py (94%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/report_service/run_reach_report.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/report_service/run_report_with_custom_fields.py (94%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/report_service/run_sales_report.py (92%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/report_service/run_saved_query.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/suggested_ad_unit_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/team_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/team_service/create_teams.py (94%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/team_service/get_all_teams.py (95%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/team_service/update_teams.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_service/create_users.py (92%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_service/deactivate_users.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_service/get_all_roles.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_service/get_all_users.py (95%) mode change 100755 => 100644 create mode 100755 examples/dfp/v201705/user_service/get_current_user.py rename examples/dfp/{v201608 => v201705}/user_service/get_user_by_email_address.py (96%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_service/update_users.py (93%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_team_association_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_team_association_service/create_user_team_associations.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_team_association_service/delete_user_team_associations.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_team_association_service/get_all_user_team_associations.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_team_association_service/get_user_team_associations_for_user.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/user_team_association_service/update_user_team_associations.py (98%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/workflow_request_service/__init__.py (100%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/workflow_request_service/approve_workflow_approval_requests.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/workflow_request_service/get_workflow_approval_requests.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/workflow_request_service/get_workflow_external_condition_requests.py (97%) mode change 100755 => 100644 rename examples/dfp/{v201608 => v201705}/workflow_request_service/trigger_workflow_external_condition_requests.py (98%) mode change 100755 => 100644 mode change 100755 => 100644 setup.py diff --git a/ChangeLog b/ChangeLog index 97ad04bd..62972e6f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +5.5.0 -- 5/23/17: +* Added more expressive python utility to build DFP PQL statements. +* Support building DFP SOAP entities with native python date/datetime objects. +* Added support and examples for DFP v201705. +* Removed support and examples for DFP v201605. + 5.4.0 -- 4/25/17: * Resolved issues: - Issue 200: https://github.com/googleads/googleads-python-lib/issues/200 diff --git a/examples/adwords/adwords_appengine_demo/__init__.py b/examples/adwords/adwords_appengine_demo/__init__.py index 38deb3b8..be307921 100755 --- a/examples/adwords/adwords_appengine_demo/__init__.py +++ b/examples/adwords/adwords_appengine_demo/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/demo/__init__.py b/examples/adwords/adwords_appengine_demo/demo/__init__.py index edf49e56..59e8ef3a 100755 --- a/examples/adwords/adwords_appengine_demo/demo/__init__.py +++ b/examples/adwords/adwords_appengine_demo/demo/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/demo/main.py b/examples/adwords/adwords_appengine_demo/demo/main.py index 1dfb904c..5d364db6 100755 --- a/examples/adwords/adwords_appengine_demo/demo/main.py +++ b/examples/adwords/adwords_appengine_demo/demo/main.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/__init__.py b/examples/adwords/adwords_appengine_demo/handlers/__init__.py index a186d331..0f5dabe3 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/__init__.py +++ b/examples/adwords/adwords_appengine_demo/handlers/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index 0595b40a..c2e70b54 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py index 9cd6b7ca..97d6a3e4 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/models/__init__.py b/examples/adwords/adwords_appengine_demo/models/__init__.py index 2eba7921..af1c9f8f 100755 --- a/examples/adwords/adwords_appengine_demo/models/__init__.py +++ b/examples/adwords/adwords_appengine_demo/models/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/models/app_user.py b/examples/adwords/adwords_appengine_demo/models/app_user.py index 56004b17..5272ee87 100755 --- a/examples/adwords/adwords_appengine_demo/models/app_user.py +++ b/examples/adwords/adwords_appengine_demo/models/app_user.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/__init__.py b/examples/adwords/adwords_appengine_demo/views/__init__.py index eadfba45..f6f56e9a 100755 --- a/examples/adwords/adwords_appengine_demo/views/__init__.py +++ b/examples/adwords/adwords_appengine_demo/views/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py index 48bb14c5..ce4d8943 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py index 25297d20..d86b3181 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/init_view.py b/examples/adwords/adwords_appengine_demo/views/init_view.py index e6215956..edb5d935 100755 --- a/examples/adwords/adwords_appengine_demo/views/init_view.py +++ b/examples/adwords/adwords_appengine_demo/views/init_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py index e3bdbf1d..2813a14a 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py index 9722cad9..74e00a59 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py index 758f832d..a0f1448c 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py index 9c74eeaa..05f071f5 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py index bcc709c3..af08fa55 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py index bbfe5d96..53903584 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py index 83159ca6..3be794b6 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index b4b0b4f9..57f978c4 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_without_yaml.py index b79c69ab..12e9ad99 100755 --- a/examples/adwords/authentication/create_adwords_client_without_yaml.py +++ b/examples/adwords/authentication/create_adwords_client_without_yaml.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 0f5d1829..37696d7e 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/account_management/create_account.py b/examples/adwords/v201607/account_management/create_account.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/account_management/get_account_changes.py b/examples/adwords/v201607/account_management/get_account_changes.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/account_management/get_account_hierarchy.py b/examples/adwords/v201607/account_management/get_account_hierarchy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/add_html5_ad.py b/examples/adwords/v201607/advanced_operations/add_html5_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/add_ad_groups.py b/examples/adwords/v201607/basic_operations/add_ad_groups.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/add_campaigns.py b/examples/adwords/v201607/basic_operations/add_campaigns.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/add_keywords.py b/examples/adwords/v201607/basic_operations/add_keywords.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/add_text_ads.py b/examples/adwords/v201607/basic_operations/add_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/get_ad_groups.py b/examples/adwords/v201607/basic_operations/get_ad_groups.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/get_campaigns.py b/examples/adwords/v201607/basic_operations/get_campaigns.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/get_keywords.py b/examples/adwords/v201607/basic_operations/get_keywords.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/get_text_ads.py b/examples/adwords/v201607/basic_operations/get_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/pause_ad.py b/examples/adwords/v201607/basic_operations/pause_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/remove_ad.py b/examples/adwords/v201607/basic_operations/remove_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/remove_ad_group.py b/examples/adwords/v201607/basic_operations/remove_ad_group.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/remove_campaign.py b/examples/adwords/v201607/basic_operations/remove_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/remove_keyword.py b/examples/adwords/v201607/basic_operations/remove_keyword.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/update_ad_group.py b/examples/adwords/v201607/basic_operations/update_ad_group.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/update_campaign.py b/examples/adwords/v201607/basic_operations/update_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/basic_operations/update_keyword.py b/examples/adwords/v201607/basic_operations/update_keyword.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/add_campaign_labels.py b/examples/adwords/v201607/campaign_management/add_campaign_labels.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/add_draft.py b/examples/adwords/v201607/campaign_management/add_draft.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/add_experiment.py b/examples/adwords/v201607/campaign_management/add_experiment.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/add_trial.py b/examples/adwords/v201607/campaign_management/add_trial.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/graduate_trial.py b/examples/adwords/v201607/campaign_management/graduate_trial.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/promote_experiment.py b/examples/adwords/v201607/campaign_management/promote_experiment.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/set_ad_parameters.py b/examples/adwords/v201607/campaign_management/set_ad_parameters.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/campaign_management/validate_text_ad.py b/examples/adwords/v201607/campaign_management/validate_text_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/error_handling/handle_partial_failures.py b/examples/adwords/v201607/error_handling/handle_partial_failures.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/extensions/add_prices.py b/examples/adwords/v201607/extensions/add_prices.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/extensions/add_site_links.py b/examples/adwords/v201607/extensions/add_site_links.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/migration/migrate_to_extension_settings.py b/examples/adwords/v201607/migration/migrate_to_extension_settings.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/misc/get_all_images_and_videos.py b/examples/adwords/v201607/misc/get_all_images_and_videos.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/misc/upload_image.py b/examples/adwords/v201607/misc/upload_image.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/misc/upload_media_bundle.py b/examples/adwords/v201607/misc/upload_media_bundle.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/optimization/estimate_keyword_traffic.py b/examples/adwords/v201607/optimization/estimate_keyword_traffic.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/optimization/get_keyword_ideas.py b/examples/adwords/v201607/optimization/get_keyword_ideas.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/remarketing/add_audience.py b/examples/adwords/v201607/remarketing/add_audience.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/remarketing/add_conversion_tracker.py b/examples/adwords/v201607/remarketing/add_conversion_tracker.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/remarketing/add_crm_based_user_list.py b/examples/adwords/v201607/remarketing/add_crm_based_user_list.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/remarketing/upload_offline_conversions.py b/examples/adwords/v201607/remarketing/upload_offline_conversions.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/reporting/download_criteria_report.py b/examples/adwords/v201607/reporting/download_criteria_report.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/reporting/get_report_fields.py b/examples/adwords/v201607/reporting/get_report_fields.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/reporting/parallel_report_download.py b/examples/adwords/v201607/reporting/parallel_report_download.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/shopping/add_product_partition_tree.py b/examples/adwords/v201607/shopping/add_product_partition_tree.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/shopping/add_product_scope.py b/examples/adwords/v201607/shopping/add_product_scope.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/shopping/add_shopping_campaign.py b/examples/adwords/v201607/shopping/add_shopping_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/shopping/get_product_category_taxonomy.py b/examples/adwords/v201607/shopping/get_product_category_taxonomy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201607/targeting/lookup_location.py b/examples/adwords/v201607/targeting/lookup_location.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/account_management/accept_service_link.py b/examples/adwords/v201609/account_management/accept_service_link.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/account_management/create_account.py b/examples/adwords/v201609/account_management/create_account.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/account_management/get_account_changes.py b/examples/adwords/v201609/account_management/get_account_changes.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/account_management/get_account_hierarchy.py b/examples/adwords/v201609/account_management/get_account_hierarchy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/add_html5_ad.py b/examples/adwords/v201609/advanced_operations/add_html5_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py old mode 100755 new mode 100644 index 0b9ffc31..b10e292d --- a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py @@ -157,7 +157,6 @@ def CreateBudget(client): # Create the budget and return its ID. budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - # [END createBudget] MOE_strip_line return budget_id diff --git a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/add_ad_groups.py b/examples/adwords/v201609/basic_operations/add_ad_groups.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/add_campaigns.py b/examples/adwords/v201609/basic_operations/add_campaigns.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/add_keywords.py b/examples/adwords/v201609/basic_operations/add_keywords.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/get_ad_groups.py b/examples/adwords/v201609/basic_operations/get_ad_groups.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/get_campaigns.py b/examples/adwords/v201609/basic_operations/get_campaigns.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/get_keywords.py b/examples/adwords/v201609/basic_operations/get_keywords.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/get_text_ads.py b/examples/adwords/v201609/basic_operations/get_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/pause_ad.py b/examples/adwords/v201609/basic_operations/pause_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/remove_ad.py b/examples/adwords/v201609/basic_operations/remove_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/remove_ad_group.py b/examples/adwords/v201609/basic_operations/remove_ad_group.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/remove_campaign.py b/examples/adwords/v201609/basic_operations/remove_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/remove_keyword.py b/examples/adwords/v201609/basic_operations/remove_keyword.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/update_ad_group.py b/examples/adwords/v201609/basic_operations/update_ad_group.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/update_campaign.py b/examples/adwords/v201609/basic_operations/update_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/basic_operations/update_keyword.py b/examples/adwords/v201609/basic_operations/update_keyword.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/add_campaign_labels.py b/examples/adwords/v201609/campaign_management/add_campaign_labels.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/add_draft.py b/examples/adwords/v201609/campaign_management/add_draft.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/add_trial.py b/examples/adwords/v201609/campaign_management/add_trial.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/graduate_trial.py b/examples/adwords/v201609/campaign_management/graduate_trial.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/set_ad_parameters.py b/examples/adwords/v201609/campaign_management/set_ad_parameters.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/campaign_management/validate_text_ad.py b/examples/adwords/v201609/campaign_management/validate_text_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/error_handling/handle_partial_failures.py b/examples/adwords/v201609/error_handling/handle_partial_failures.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/extensions/add_prices.py b/examples/adwords/v201609/extensions/add_prices.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/extensions/add_site_links.py b/examples/adwords/v201609/extensions/add_site_links.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/migration/migrate_to_extension_settings.py b/examples/adwords/v201609/migration/migrate_to_extension_settings.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/misc/get_all_images_and_videos.py b/examples/adwords/v201609/misc/get_all_images_and_videos.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/misc/upload_image.py b/examples/adwords/v201609/misc/upload_image.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/misc/upload_media_bundle.py b/examples/adwords/v201609/misc/upload_media_bundle.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py b/examples/adwords/v201609/optimization/estimate_keyword_traffic.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/optimization/get_keyword_ideas.py b/examples/adwords/v201609/optimization/get_keyword_ideas.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/remarketing/add_audience.py b/examples/adwords/v201609/remarketing/add_audience.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/remarketing/add_conversion_tracker.py b/examples/adwords/v201609/remarketing/add_conversion_tracker.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py b/examples/adwords/v201609/remarketing/add_crm_based_user_list.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/remarketing/upload_offline_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_conversions.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/reporting/download_criteria_report.py b/examples/adwords/v201609/reporting/download_criteria_report.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/reporting/get_report_fields.py b/examples/adwords/v201609/reporting/get_report_fields.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/reporting/parallel_report_download.py b/examples/adwords/v201609/reporting/parallel_report_download.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/shopping/add_product_partition_tree.py b/examples/adwords/v201609/shopping/add_product_partition_tree.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/shopping/add_product_scope.py b/examples/adwords/v201609/shopping/add_product_scope.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/shopping/add_shopping_campaign.py b/examples/adwords/v201609/shopping/add_shopping_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py b/examples/adwords/v201609/shopping/get_product_category_taxonomy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201609/targeting/lookup_location.py b/examples/adwords/v201609/targeting/lookup_location.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/account_management/accept_service_link.py b/examples/adwords/v201702/account_management/accept_service_link.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/account_management/create_account.py b/examples/adwords/v201702/account_management/create_account.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/account_management/get_account_changes.py b/examples/adwords/v201702/account_management/get_account_changes.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/account_management/get_account_hierarchy.py b/examples/adwords/v201702/account_management/get_account_hierarchy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/add_html5_ad.py b/examples/adwords/v201702/advanced_operations/add_html5_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py old mode 100755 new mode 100644 index 0048756a..72e19e88 --- a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py @@ -157,7 +157,6 @@ def CreateBudget(client): # Create the budget and return its ID. budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - # [END createBudget] MOE_strip_line return budget_id diff --git a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/add_ad_groups.py b/examples/adwords/v201702/basic_operations/add_ad_groups.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/add_campaigns.py b/examples/adwords/v201702/basic_operations/add_campaigns.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/add_keywords.py b/examples/adwords/v201702/basic_operations/add_keywords.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/get_ad_groups.py b/examples/adwords/v201702/basic_operations/get_ad_groups.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/get_campaigns.py b/examples/adwords/v201702/basic_operations/get_campaigns.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/get_keywords.py b/examples/adwords/v201702/basic_operations/get_keywords.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/get_text_ads.py b/examples/adwords/v201702/basic_operations/get_text_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/pause_ad.py b/examples/adwords/v201702/basic_operations/pause_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/remove_ad.py b/examples/adwords/v201702/basic_operations/remove_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/remove_ad_group.py b/examples/adwords/v201702/basic_operations/remove_ad_group.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/remove_campaign.py b/examples/adwords/v201702/basic_operations/remove_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/remove_keyword.py b/examples/adwords/v201702/basic_operations/remove_keyword.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/update_ad_group.py b/examples/adwords/v201702/basic_operations/update_ad_group.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/update_campaign.py b/examples/adwords/v201702/basic_operations/update_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/basic_operations/update_keyword.py b/examples/adwords/v201702/basic_operations/update_keyword.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/add_campaign_labels.py b/examples/adwords/v201702/campaign_management/add_campaign_labels.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/add_draft.py b/examples/adwords/v201702/campaign_management/add_draft.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/add_trial.py b/examples/adwords/v201702/campaign_management/add_trial.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/graduate_trial.py b/examples/adwords/v201702/campaign_management/graduate_trial.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/set_ad_parameters.py b/examples/adwords/v201702/campaign_management/set_ad_parameters.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/campaign_management/validate_text_ad.py b/examples/adwords/v201702/campaign_management/validate_text_ad.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/error_handling/handle_partial_failures.py b/examples/adwords/v201702/error_handling/handle_partial_failures.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/extensions/add_prices.py b/examples/adwords/v201702/extensions/add_prices.py old mode 100755 new mode 100644 index f710319a..62d0f3a8 --- a/examples/adwords/v201702/extensions/add_prices.py +++ b/examples/adwords/v201702/extensions/add_prices.py @@ -48,7 +48,7 @@ def main(client, campaign_id): final_mobile_url='http://m.example.com/scrubs'), CreatePriceTableRow('Hair Cuts', 'Once a month', 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', final_mobile_url='http://m.example.com/haircuts'), CreatePriceTableRow('Skin Care Package', 'Four times a month', 'https://www.examples.com/skincarepackage', diff --git a/examples/adwords/v201702/extensions/add_site_links.py b/examples/adwords/v201702/extensions/add_site_links.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/migration/migrate_to_extension_settings.py b/examples/adwords/v201702/migration/migrate_to_extension_settings.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/misc/get_all_images_and_videos.py b/examples/adwords/v201702/misc/get_all_images_and_videos.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/misc/upload_image.py b/examples/adwords/v201702/misc/upload_image.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/misc/upload_media_bundle.py b/examples/adwords/v201702/misc/upload_media_bundle.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py b/examples/adwords/v201702/optimization/estimate_keyword_traffic.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/optimization/get_keyword_ideas.py b/examples/adwords/v201702/optimization/get_keyword_ideas.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/remarketing/add_audience.py b/examples/adwords/v201702/remarketing/add_audience.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/remarketing/add_conversion_tracker.py b/examples/adwords/v201702/remarketing/add_conversion_tracker.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py b/examples/adwords/v201702/remarketing/add_crm_based_user_list.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/remarketing/upload_offline_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_conversions.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/reporting/get_report_fields.py b/examples/adwords/v201702/reporting/get_report_fields.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/reporting/parallel_report_download.py b/examples/adwords/v201702/reporting/parallel_report_download.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/shopping/add_product_partition_tree.py b/examples/adwords/v201702/shopping/add_product_partition_tree.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/shopping/add_product_scope.py b/examples/adwords/v201702/shopping/add_product_scope.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign.py b/examples/adwords/v201702/shopping/add_shopping_campaign.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py b/examples/adwords/v201702/shopping/get_product_category_taxonomy.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py old mode 100755 new mode 100644 diff --git a/examples/adwords/v201702/targeting/lookup_location.py b/examples/adwords/v201702/targeting/lookup_location.py old mode 100755 new mode 100644 diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/dfp/authentication/create_dfp_client_with_service_account.py index 11f0462b..3f7dcc2f 100755 --- a/examples/dfp/authentication/create_dfp_client_with_service_account.py +++ b/examples/dfp/authentication/create_dfp_client_with_service_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/authentication/create_dfp_client_without_yaml.py b/examples/dfp/authentication/create_dfp_client_without_yaml.py index f857f9bc..9b15b3ca 100755 --- a/examples/dfp/authentication/create_dfp_client_without_yaml.py +++ b/examples/dfp/authentication/create_dfp_client_without_yaml.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py index 4e261fe2..d725022e 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/dfp/authentication/generate_refresh_token.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py deleted file mode 100755 index d38cbfad..00000000 --- a/examples/dfp/v201608/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. -"""Gets a reconciliation report's data for line items that served through DFP. -""" - -# Import appropriate modules from the client library. -from googleads import dfp - -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_line_item_report_service = client.GetService( - 'ReconciliationLineItemReportService', version='v201608') - query = ('WHERE reconciliationReportId = :reconciliationReportId AND ' - 'lineItemId != :lineItemId') - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - }}, - ] - # Create a statement to select reconciliation line item reports. - statement = dfp.FilterStatement(query, values) - - # Retrieve a small amount of reconciliation line item reports at a time, - # paging through until all reconciliation line item reports have been - # retrieved. - while True: - response = reconciliation_line_item_report_service.getReconciliationLineItemReportsByStatement( - statement.ToStatement()) - if 'results' in response: - for reconciliation_line_item_report in response['results']: - # Print out some information for each reconciliation line item report. - print( - 'Reconciliation line item report with ID "%d", line item ID "%d", ' - 'reconciliation source "%s", and reconciled volume "%d" was ' - 'found.\n' % - (reconciliation_line_item_report['id'], - reconciliation_line_item_report['lineItemId'], - reconciliation_line_item_report['reconciliationSource'], - reconciliation_line_item_report['reconciledVolume'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201611/activity_group_service/__init__.py b/examples/dfp/v201611/activity_group_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_group_service/create_activity_groups.py b/examples/dfp/v201611/activity_group_service/create_activity_groups.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_group_service/update_activity_groups.py b/examples/dfp/v201611/activity_group_service/update_activity_groups.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_service/__init__.py b/examples/dfp/v201611/activity_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_service/create_activities.py b/examples/dfp/v201611/activity_service/create_activities.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_service/get_active_activities.py b/examples/dfp/v201611/activity_service/get_active_activities.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_service/get_all_activities.py b/examples/dfp/v201611/activity_service/get_all_activities.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/activity_service/update_activities.py b/examples/dfp/v201611/activity_service/update_activities.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/audience_segment_service/__init__.py b/examples/dfp/v201611/audience_segment_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/audience_segment_service/create_audience_segments.py b/examples/dfp/v201611/audience_segment_service/create_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/audience_segment_service/update_audience_segments.py b/examples/dfp/v201611/audience_segment_service/update_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/base_rate_service/__init__.py b/examples/dfp/v201611/base_rate_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/base_rate_service/create_product_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_base_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/base_rate_service/get_all_base_rates.py b/examples/dfp/v201611/base_rate_service/get_all_base_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/base_rate_service/update_base_rates.py b/examples/dfp/v201611/base_rate_service/update_base_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/company_service/__init__.py b/examples/dfp/v201611/company_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/company_service/create_companies.py b/examples/dfp/v201611/company_service/create_companies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/company_service/get_advertisers.py b/examples/dfp/v201611/company_service/get_advertisers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/company_service/get_all_companies.py b/examples/dfp/v201611/company_service/get_all_companies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/company_service/update_companies.py b/examples/dfp/v201611/company_service/update_companies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/contact_service/__init__.py b/examples/dfp/v201611/contact_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/contact_service/create_contacts.py b/examples/dfp/v201611/contact_service/create_contacts.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/contact_service/get_all_contacts.py b/examples/dfp/v201611/contact_service/get_all_contacts.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/contact_service/get_uninvited_contacts.py b/examples/dfp/v201611/contact_service/get_uninvited_contacts.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/contact_service/update_contacts.py b/examples/dfp/v201611/contact_service/update_contacts.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/content_service/__init__.py b/examples/dfp/v201611/content_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/content_service/get_all_content.py b/examples/dfp/v201611/content_service/get_all_content.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_service/__init__.py b/examples/dfp/v201611/creative_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_service/create_creative_from_template.py b/examples/dfp/v201611/creative_service/create_creative_from_template.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_service/create_creatives.py b/examples/dfp/v201611/creative_service/create_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_service/create_custom_creative.py b/examples/dfp/v201611/creative_service/create_custom_creative.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_service/create_native_creative.py b/examples/dfp/v201611/creative_service/create_native_creative.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_service/get_all_creatives.py b/examples/dfp/v201611/creative_service/get_all_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_service/get_image_creatives.py b/examples/dfp/v201611/creative_service/get_image_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_service/update_creatives.py b/examples/dfp/v201611/creative_service/update_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_set_service/__init__.py b/examples/dfp/v201611/creative_set_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_set_service/create_creative_set.py b/examples/dfp/v201611/creative_set_service/create_creative_set.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_set_service/update_creative_set.py b/examples/dfp/v201611/creative_set_service/update_creative_set.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_template_service/__init__.py b/examples/dfp/v201611/creative_template_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_field_service/__init__.py b/examples/dfp/v201611/custom_field_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_field_service/create_custom_field_options.py b/examples/dfp/v201611/custom_field_service/create_custom_field_options.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_field_service/create_custom_fields.py b/examples/dfp/v201611/custom_field_service/create_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_field_service/update_custom_fields.py b/examples/dfp/v201611/custom_field_service/update_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_targeting_service/__init__.py b/examples/dfp/v201611/custom_targeting_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/exchange_rate_service/__init__.py b/examples/dfp/v201611/exchange_rate_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/forecast_service/get_availability_forecast.py b/examples/dfp/v201611/forecast_service/get_availability_forecast.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/inventory_service/__init__.py b/examples/dfp/v201611/inventory_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/inventory_service/archive_ad_units.py b/examples/dfp/v201611/inventory_service/archive_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/inventory_service/create_ad_units.py b/examples/dfp/v201611/inventory_service/create_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_units.py b/examples/dfp/v201611/inventory_service/get_all_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/inventory_service/update_ad_units.py b/examples/dfp/v201611/inventory_service/update_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/label_service/__init__.py b/examples/dfp/v201611/label_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/label_service/create_labels.py b/examples/dfp/v201611/label_service/create_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/label_service/deactivate_labels.py b/examples/dfp/v201611/label_service/deactivate_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/label_service/get_active_labels.py b/examples/dfp/v201611/label_service/get_active_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/label_service/get_all_labels.py b/examples/dfp/v201611/label_service/get_all_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/label_service/update_labels.py b/examples/dfp/v201611/label_service/update_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_creative_association_service/__init__.py b/examples/dfp/v201611/line_item_creative_association_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_creative_association_service/create_licas.py b/examples/dfp/v201611/line_item_creative_association_service/create_licas.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/__init__.py b/examples/dfp/v201611/line_item_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/activate_line_items.py b/examples/dfp/v201611/line_item_service/activate_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/create_line_items.py b/examples/dfp/v201611/line_item_service/create_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/create_video_line_item.py b/examples/dfp/v201611/line_item_service/create_video_line_item.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/get_all_line_items.py b/examples/dfp/v201611/line_item_service/get_all_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/target_custom_criteria.py b/examples/dfp/v201611/line_item_service/target_custom_criteria.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/line_item_service/update_line_items.py b/examples/dfp/v201611/line_item_service/update_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/network_service/__init__.py b/examples/dfp/v201611/network_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/network_service/get_all_networks.py b/examples/dfp/v201611/network_service/get_all_networks.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/network_service/make_test_network.py b/examples/dfp/v201611/network_service/make_test_network.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/order_service/__init__.py b/examples/dfp/v201611/order_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/order_service/approve_orders.py b/examples/dfp/v201611/order_service/approve_orders.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/order_service/create_orders.py b/examples/dfp/v201611/order_service/create_orders.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/order_service/get_all_orders.py b/examples/dfp/v201611/order_service/get_all_orders.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/order_service/get_orders_starting_soon.py b/examples/dfp/v201611/order_service/get_orders_starting_soon.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/order_service/update_orders.py b/examples/dfp/v201611/order_service/update_orders.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/package_service/get_all_packages.py b/examples/dfp/v201611/package_service/get_all_packages.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/package_service/get_in_progress_packages.py b/examples/dfp/v201611/package_service/get_in_progress_packages.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/placement_service/create_placements.py b/examples/dfp/v201611/placement_service/create_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/placement_service/deactivate_placements.py b/examples/dfp/v201611/placement_service/deactivate_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/placement_service/get_active_placements.py b/examples/dfp/v201611/placement_service/get_active_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/placement_service/get_all_placements.py b/examples/dfp/v201611/placement_service/get_all_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/placement_service/update_placements.py b/examples/dfp/v201611/placement_service/update_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/premium_rate_service/__init__.py b/examples/dfp/v201611/premium_rate_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/premium_rate_service/create_premium_rates.py b/examples/dfp/v201611/premium_rate_service/create_premium_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/premium_rate_service/update_premium_rates.py b/examples/dfp/v201611/premium_rate_service/update_premium_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_package_service/get_active_product_packages.py b/examples/dfp/v201611/product_package_service/get_active_product_packages.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_package_service/get_all_product_packages.py b/examples/dfp/v201611/product_package_service/get_all_product_packages.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_service/__init__.py b/examples/dfp/v201611/product_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_service/get_all_products.py b/examples/dfp/v201611/product_service/get_all_products.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_service/get_products_for_product_template.py b/examples/dfp/v201611/product_service/get_products_for_product_template.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_service/update_products.py b/examples/dfp/v201611/product_service/update_products.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_template_service/__init__.py b/examples/dfp/v201611/product_template_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_template_service/activate_product_templates.py b/examples/dfp/v201611/product_template_service/activate_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_template_service/create_product_templates.py b/examples/dfp/v201611/product_template_service/create_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_template_service/get_all_product_templates.py b/examples/dfp/v201611/product_template_service/get_all_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/product_template_service/update_product_templates.py b/examples/dfp/v201611/product_template_service/update_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_line_item_service/__init__.py b/examples/dfp/v201611/proposal_line_item_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/__init__.py b/examples/dfp/v201611/proposal_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/create_proposals.py b/examples/dfp/v201611/proposal_service/create_proposals.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/get_all_proposals.py b/examples/dfp/v201611/proposal_service/get_all_proposals.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/get_marketplace_comments.py b/examples/dfp/v201611/proposal_service/get_marketplace_comments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/proposal_service/update_proposals.py b/examples/dfp/v201611/proposal_service/update_proposals.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/publisher_query_language_service/__init__.py b/examples/dfp/v201611/publisher_query_language_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/rate_card_service/__init__.py b/examples/dfp/v201611/rate_card_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/report_service/__init__.py b/examples/dfp/v201611/report_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/report_service/run_delivery_report.py b/examples/dfp/v201611/report_service/run_delivery_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/report_service/run_inventory_report.py b/examples/dfp/v201611/report_service/run_inventory_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/report_service/run_reach_report.py b/examples/dfp/v201611/report_service/run_reach_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/report_service/run_report_with_custom_fields.py b/examples/dfp/v201611/report_service/run_report_with_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/report_service/run_sales_report.py b/examples/dfp/v201611/report_service/run_sales_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/report_service/run_saved_query.py b/examples/dfp/v201611/report_service/run_saved_query.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/suggested_ad_unit_service/__init__.py b/examples/dfp/v201611/suggested_ad_unit_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/team_service/__init__.py b/examples/dfp/v201611/team_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/team_service/create_teams.py b/examples/dfp/v201611/team_service/create_teams.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/team_service/get_all_teams.py b/examples/dfp/v201611/team_service/get_all_teams.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/team_service/update_teams.py b/examples/dfp/v201611/team_service/update_teams.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_service/__init__.py b/examples/dfp/v201611/user_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_service/create_users.py b/examples/dfp/v201611/user_service/create_users.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_service/deactivate_users.py b/examples/dfp/v201611/user_service/deactivate_users.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_service/get_all_roles.py b/examples/dfp/v201611/user_service/get_all_roles.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_service/get_all_users.py b/examples/dfp/v201611/user_service/get_all_users.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_service/get_user_by_email_address.py b/examples/dfp/v201611/user_service/get_user_by_email_address.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_service/update_users.py b/examples/dfp/v201611/user_service/update_users.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_team_association_service/__init__.py b/examples/dfp/v201611/user_team_association_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/workflow_request_service/__init__.py b/examples/dfp/v201611/workflow_request_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_group_service/__init__.py b/examples/dfp/v201702/activity_group_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_group_service/create_activity_groups.py b/examples/dfp/v201702/activity_group_service/create_activity_groups.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_group_service/update_activity_groups.py b/examples/dfp/v201702/activity_group_service/update_activity_groups.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_service/__init__.py b/examples/dfp/v201702/activity_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_service/create_activities.py b/examples/dfp/v201702/activity_service/create_activities.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_service/get_active_activities.py b/examples/dfp/v201702/activity_service/get_active_activities.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_service/get_all_activities.py b/examples/dfp/v201702/activity_service/get_all_activities.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/activity_service/update_activities.py b/examples/dfp/v201702/activity_service/update_activities.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/audience_segment_service/__init__.py b/examples/dfp/v201702/audience_segment_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py b/examples/dfp/v201702/audience_segment_service/create_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py b/examples/dfp/v201702/audience_segment_service/update_audience_segments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/base_rate_service/__init__.py b/examples/dfp/v201702/base_rate_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_base_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py new file mode 100755 index 00000000..9a992ff4 --- /dev/null +++ b/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a product package item base rate. + +To determine which base rates exist, run get_all_base_rates.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the rate card ID to add the base rate to. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + +# Set the product package item to apply this base rate to. +PRODUCT_PACKAGE_ITEM_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201702') + + # Create a base rate for a product package item. + base_rate = { + 'xsi_type': 'ProductPackageItemBaseRate', + # Set the rate card ID that the product package item base rate + # belongs to. + 'rateCardId': RATE_CARD_ID, + # Set the product package item the base rate will be applied to. + 'productPackageItemId': PRODUCT_PACKAGE_ITEM_ID, + # Create a rate worth $2 USD and set that on the product package item + # base rate. + 'rate': { + 'xsi_type': 'Money', + 'currencyCode': 'USD', + 'microAmount': 2000000, + } + } + + # Create the product package item base rate on the server. + result = base_rate_service.createBaseRates([base_rate]) + + for new_base_rate in result: + print ('A product package item base rate with ID %d and rate %f %s ' + 'was created.' % (new_base_rate['id'], + new_base_rate['microAmount'], + new_base_rate['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py b/examples/dfp/v201702/base_rate_service/get_all_base_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/base_rate_service/update_base_rates.py b/examples/dfp/v201702/base_rate_service/update_base_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/company_service/__init__.py b/examples/dfp/v201702/company_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/company_service/create_companies.py b/examples/dfp/v201702/company_service/create_companies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/company_service/get_advertisers.py b/examples/dfp/v201702/company_service/get_advertisers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/company_service/get_all_companies.py b/examples/dfp/v201702/company_service/get_all_companies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/company_service/update_companies.py b/examples/dfp/v201702/company_service/update_companies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/contact_service/__init__.py b/examples/dfp/v201702/contact_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/contact_service/create_contacts.py b/examples/dfp/v201702/contact_service/create_contacts.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/contact_service/get_all_contacts.py b/examples/dfp/v201702/contact_service/get_all_contacts.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/contact_service/get_uninvited_contacts.py b/examples/dfp/v201702/contact_service/get_uninvited_contacts.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/contact_service/update_contacts.py b/examples/dfp/v201702/contact_service/update_contacts.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/content_service/__init__.py b/examples/dfp/v201702/content_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/content_service/get_all_content.py b/examples/dfp/v201702/content_service/get_all_content.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_service/__init__.py b/examples/dfp/v201702/creative_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_service/copy_image_creatives.py b/examples/dfp/v201702/creative_service/copy_image_creatives.py new file mode 100755 index 00000000..fcb12cd2 --- /dev/null +++ b/examples/dfp/v201702/creative_service/copy_image_creatives.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a copy of an image creative. + +To determine which image creatives exist, run get_image_creatives.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201702') + + # Create a statement to get the image creative. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', CREATIVE_ID)) + + # Get the creative. + query_result = creative_service.getCreativesByStatement( + statement.ToStatement()) + + image_creative = query_result['results'][0] + + # Build the new creative, set id to None to create a copy. + image_creative['id'] = None + image_creative['name'] = 'Copy of %s' % image_creative['name'] + + result = creative_service.createCreatives([image_creative])[0] + print ('A creative with ID %d, name \'%s\', and type \'%s\' was created and ' + 'can be previewed at: %s' % (result['id'], + result['name'], + dfp.DfpClassType(result), + result['previewUrl'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/creative_service/create_creative_from_template.py b/examples/dfp/v201702/creative_service/create_creative_from_template.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_service/create_creatives.py b/examples/dfp/v201702/creative_service/create_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_service/create_custom_creative.py b/examples/dfp/v201702/creative_service/create_custom_creative.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_service/create_native_creative.py b/examples/dfp/v201702/creative_service/create_native_creative.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_service/get_all_creatives.py b/examples/dfp/v201702/creative_service/get_all_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_service/get_image_creatives.py b/examples/dfp/v201702/creative_service/get_image_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_service/update_creatives.py b/examples/dfp/v201702/creative_service/update_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_set_service/__init__.py b/examples/dfp/v201702/creative_set_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_set_service/create_creative_set.py b/examples/dfp/v201702/creative_set_service/create_creative_set.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_set_service/update_creative_set.py b/examples/dfp/v201702/creative_set_service/update_creative_set.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_template_service/__init__.py b/examples/dfp/v201702/creative_template_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_field_service/__init__.py b/examples/dfp/v201702/custom_field_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py b/examples/dfp/v201702/custom_field_service/create_custom_field_options.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_field_service/create_custom_fields.py b/examples/dfp/v201702/custom_field_service/create_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_field_service/update_custom_fields.py b/examples/dfp/v201702/custom_field_service/update_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_targeting_service/__init__.py b/examples/dfp/v201702/custom_targeting_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/exchange_rate_service/__init__.py b/examples/dfp/v201702/exchange_rate_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast.py b/examples/dfp/v201702/forecast_service/get_availability_forecast.py old mode 100755 new mode 100644 index a55910ad..7ed5d8f1 --- a/examples/dfp/v201702/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201702/forecast_service/get_availability_forecast.py @@ -24,10 +24,11 @@ """ -from datetime import date +import datetime # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set the ID of the advertiser (company) to forecast for. Setting an advertiser # will cause the forecast to apply the appropriate unified blocking rules. @@ -42,6 +43,9 @@ def main(client, advertiser_id): # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=30) + # Create prospective line item. line_item = { 'targeting': { @@ -70,17 +74,7 @@ def main(client, advertiser_id): ], 'lineItemType': 'SPONSORSHIP', 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/New_York' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/inventory_service/__init__.py b/examples/dfp/v201702/inventory_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/inventory_service/archive_ad_units.py b/examples/dfp/v201702/inventory_service/archive_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/inventory_service/create_ad_units.py b/examples/dfp/v201702/inventory_service/create_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_units.py b/examples/dfp/v201702/inventory_service/get_all_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/inventory_service/update_ad_units.py b/examples/dfp/v201702/inventory_service/update_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/label_service/__init__.py b/examples/dfp/v201702/label_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/label_service/create_labels.py b/examples/dfp/v201702/label_service/create_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/label_service/deactivate_labels.py b/examples/dfp/v201702/label_service/deactivate_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/label_service/get_active_labels.py b/examples/dfp/v201702/label_service/get_active_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/label_service/get_all_labels.py b/examples/dfp/v201702/label_service/get_all_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/label_service/update_labels.py b/examples/dfp/v201702/label_service/update_labels.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_creative_association_service/__init__.py b/examples/dfp/v201702/line_item_creative_association_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py b/examples/dfp/v201702/line_item_creative_association_service/create_licas.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/__init__.py b/examples/dfp/v201702/line_item_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/activate_line_items.py b/examples/dfp/v201702/line_item_service/activate_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/create_line_items.py b/examples/dfp/v201702/line_item_service/create_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/create_video_line_item.py b/examples/dfp/v201702/line_item_service/create_video_line_item.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/get_all_line_items.py b/examples/dfp/v201702/line_item_service/get_all_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/pause_line_items.py b/examples/dfp/v201702/line_item_service/pause_line_items.py new file mode 100755 index 00000000..babafa4b --- /dev/null +++ b/examples/dfp/v201702/line_item_service/pause_line_items.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2017 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 pauses a line item. + +Line items must be paused before they can be updated. To determine which line +items exist, run get_all_line_items.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201702') + + # Create a statement to select the line item. + # Change this to operate on more than one Line Item. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', LINE_ITEM_ID)) + + result_set_size = 0 + should_continue = True + + # Iterate over paged results from the statement. + while should_continue: + page = line_item_service.getLineItemsByStatement(statement.ToStatement()) + if 'results' in page: + result_set_size = page['totalResultSetSize'] + # Iterate over individual results in the page. + for line_item in page['results']: + print 'Pausing line item with ID %d' % line_item['id'] + # Update statement for next page. + statement.offset += statement.limit + should_continue = statement.offset < result_set_size + + print 'Pausing %d line item(s)' % result_set_size + + if result_set_size > 0: + statement.offset = None + statement.limit = None + + # Perform Pause action on all Line Items that match the statement. + update_result = line_item_service.performLineItemAction( + {'xsi_type': 'PauseLineItems'}, statement.ToStatement()) + + if update_result and update_result['numChanges'] > 0: + print 'Updated %d line item(s)' % update_result['numChanges'] + else: + print 'No line items were paused' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/line_item_service/target_custom_criteria.py b/examples/dfp/v201702/line_item_service/target_custom_criteria.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/line_item_service/update_line_items.py b/examples/dfp/v201702/line_item_service/update_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/native_style_service/__init__.py b/examples/dfp/v201702/native_style_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/native_style_service/create_native_styles.py b/examples/dfp/v201702/native_style_service/create_native_styles.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/native_style_service/get_all_native_styles.py b/examples/dfp/v201702/native_style_service/get_all_native_styles.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/network_service/__init__.py b/examples/dfp/v201702/network_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/network_service/get_all_networks.py b/examples/dfp/v201702/network_service/get_all_networks.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/network_service/make_test_network.py b/examples/dfp/v201702/network_service/make_test_network.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/order_service/__init__.py b/examples/dfp/v201702/order_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/order_service/approve_orders.py b/examples/dfp/v201702/order_service/approve_orders.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/order_service/create_orders.py b/examples/dfp/v201702/order_service/create_orders.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/order_service/get_all_orders.py b/examples/dfp/v201702/order_service/get_all_orders.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/order_service/get_orders_starting_soon.py b/examples/dfp/v201702/order_service/get_orders_starting_soon.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/order_service/update_orders.py b/examples/dfp/v201702/order_service/update_orders.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/package_service/create_packages.py b/examples/dfp/v201702/package_service/create_packages.py new file mode 100755 index 00000000..a0466f72 --- /dev/null +++ b/examples/dfp/v201702/package_service/create_packages.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a package. + +To determine which packages exist, run get_all_packages.py. +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the ID of the product package to create the package from. +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + +# Set the ID of the proposal to create proposal line items under. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the rate card the proposal line items belonging to the product +# package are priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client): + # Initialize appropriate service. + package_service = client.GetService('PackageService', version='v201702') + + # Create local package. + package = { + 'name': 'Package #%d' % random.randint(0, 1000000), + 'proposalId': PROPOSAL_ID, + 'productPackageId': PRODUCT_PACKAGE_ID, + 'rateCardId': RATE_CARD_ID, + } + + # Create the package on the server. + result = package_service.createPackages([package]) + + for new_package in result: + print ('A package with ID %d and name \'%s\' was created' % + (new_package['id'], new_package['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py new file mode 100755 index 00000000..721d4e43 --- /dev/null +++ b/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py @@ -0,0 +1,68 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a copy of an image creative. + +To determine which image creatives exist, run get_image_creatives.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + package_service = client.GetService('PackageService', version='v201702') + + # Create a statement to select the single package. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', PACKAGE_ID)) + + # Get the package. + query_result = package_service.getPackagesByStatement(statement.ToStatement()) + + package = query_result['results'][0] + + print ('Package with ID %d will create proposal line items using product ' + 'package with ID %d.' % (package['id'], + package['productPackageId'])) + + # Remove limit and offset from statement. + statement.limit = None + statement.offset = None + + # Perform update packages action. + result = package_service.performPackageAction( + {'xsi_type': 'CreateProposalLineItemsFromPackages'}, + statement.ToStatement()) + + if result and result['numChanges'] > 0: + print ('Number of packages that proposal line items were created for: %d' % + result['numChanges']) + else: + print 'No proposal line items were created.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/package_service/get_all_packages.py b/examples/dfp/v201702/package_service/get_all_packages.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/package_service/get_in_progress_packages.py b/examples/dfp/v201702/package_service/get_in_progress_packages.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/placement_service/create_placements.py b/examples/dfp/v201702/placement_service/create_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/placement_service/deactivate_placements.py b/examples/dfp/v201702/placement_service/deactivate_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/placement_service/get_active_placements.py b/examples/dfp/v201702/placement_service/get_active_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/placement_service/get_all_placements.py b/examples/dfp/v201702/placement_service/get_all_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/placement_service/update_placements.py b/examples/dfp/v201702/placement_service/update_placements.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/premium_rate_service/__init__.py b/examples/dfp/v201702/premium_rate_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py b/examples/dfp/v201702/premium_rate_service/create_premium_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py b/examples/dfp/v201702/premium_rate_service/update_premium_rates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_package_item_service/create_product_package_item.py b/examples/dfp/v201702/product_package_item_service/create_product_package_item.py new file mode 100755 index 00000000..4c31eef9 --- /dev/null +++ b/examples/dfp/v201702/product_package_item_service/create_product_package_item.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a product package item. + +To determine which product package items exist, run +get_all_product_package_items.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the product package to add product package items to. +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + +# Set the ID of the product to generate a product package item from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client): + product_package_item_service = client.GetService('ProductPackageItemService', + version='v201702') + + product_package_item = { + # Set the product from which the product package item is created. + 'productId': PRODUCT_ID, + # Set the product package that the product package item belongs to. + 'productPackageId': PRODUCT_PACKAGE_ID, + # Specify if the product package item is required for this + # product package. + 'isMandatory': True + } + + # Create the product package item on the server. + result = product_package_item_service.createProductPackageItems( + [product_package_item]) + + for new_product_package_item in result: + print ('A product package with ID %d created from product ID %d ' + 'belonging to product package with ID %d was created.' % + (new_product_package_item['id'], + new_product_package_item['productId'], + new_product_package_item['productPackageId'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_package_service/create_product_packages.py b/examples/dfp/v201702/product_package_service/create_product_packages.py new file mode 100755 index 00000000..ec3173e0 --- /dev/null +++ b/examples/dfp/v201702/product_package_service/create_product_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a product package. + +To determine which product packages exist, run get_all_product_packages.py +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the ID of the rate card to associate with the product package. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client): + product_package_service = client.GetService('ProductPackageService', + version='v201702') + + # Create a local product package. + product_package = { + 'name': 'Product Package #%d' % random.randint(0, 100000000), + 'rateCardIds': [RATE_CARD_ID] + } + + result = product_package_service.createProductPackages([product_package]) + + for new_product_package in result: + print ('A product package with ID %d and name \'%s\' was created.' % + (new_product_package['id'], new_product_package['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/product_package_service/get_active_product_packages.py b/examples/dfp/v201702/product_package_service/get_active_product_packages.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_package_service/get_all_product_packages.py b/examples/dfp/v201702/product_package_service/get_all_product_packages.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_service/__init__.py b/examples/dfp/v201702/product_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_service/get_all_products.py b/examples/dfp/v201702/product_service/get_all_products.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_service/get_products_for_product_template.py b/examples/dfp/v201702/product_service/get_products_for_product_template.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_service/update_products.py b/examples/dfp/v201702/product_service/update_products.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_template_service/__init__.py b/examples/dfp/v201702/product_template_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_template_service/activate_product_templates.py b/examples/dfp/v201702/product_template_service/activate_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_template_service/create_product_templates.py b/examples/dfp/v201702/product_template_service/create_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_template_service/get_all_product_templates.py b/examples/dfp/v201702/product_template_service/get_all_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/product_template_service/update_product_templates.py b/examples/dfp/v201702/product_template_service/update_product_templates.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_line_item_service/__init__.py b/examples/dfp/v201702/proposal_line_item_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/__init__.py b/examples/dfp/v201702/proposal_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/create_proposals.py b/examples/dfp/v201702/proposal_service/create_proposals.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/get_all_proposals.py b/examples/dfp/v201702/proposal_service/get_all_proposals.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py b/examples/dfp/v201702/proposal_service/get_marketplace_comments.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/proposal_service/update_proposals.py b/examples/dfp/v201702/proposal_service/update_proposals.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/publisher_query_language_service/__init__.py b/examples/dfp/v201702/publisher_query_language_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/rate_card_service/__init__.py b/examples/dfp/v201702/rate_card_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/rate_card_service/create_rate_cards.py b/examples/dfp/v201702/rate_card_service/create_rate_cards.py new file mode 100755 index 00000000..45f30941 --- /dev/null +++ b/examples/dfp/v201702/rate_card_service/create_rate_cards.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a new rate card. + +To determine which rate cards exist, run get_all_rate_cards.py. +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the IDs of the teams this rate card should be visible to. +TEAM_IDS = ['INSERT_TEAM_ID_HERE'] + +# Set the currency code to create the rate card with. +CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201702') + + # Create a rate card. + rate_card = { + 'name': 'RateCard #%d' % random.randint(0, 100000000), + 'currencyCode': CURRENCY_CODE, + 'pricingModel': 'NET', + } + + # This field is optional. + rate_card['appliedTeamIds'] = TEAM_IDS + + result = rate_card_service.createRateCards([rate_card]) + + for new_rate_card in result: + print ('A rate card with ID %s, name \'%s\', and currency code \'%s\' ' + 'was created.' % (new_rate_card['id'], + new_rate_card['name'], + new_rate_card['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py old mode 100755 new mode 100644 index 18ab2fe7..7825aa01 --- a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2016 Google Inc. All Rights Reserved. +# Copyright 2017 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. @@ -13,63 +13,63 @@ # 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. -"""Gets a reconciliation report's data for line items that served through DFP. + +"""This example gets all line item reports for a given reconciliation report. + +To determine how many reconciliation reports exist, +run get_all_reconciliation_reports.py. """ # Import appropriate modules from the client library. from googleads import dfp +# Set the ID of the reconciliation report to query. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' -def main(client, reconciliation_report_id): +def main(client): # Initialize appropriate service. - reconciliation_line_item_report_service = client.GetService( - 'ReconciliationLineItemReportService', version='v201702') - query = ('WHERE reconciliationReportId = :reconciliationReportId AND ' - 'lineItemId != :lineItemId') - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - }}, - ] + reconciliation_line_item_report_service = (client.GetService( + 'ReconciliationLineItemReportService', version='v201702')) + # Create a statement to select reconciliation line item reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reconciliationReportId AND ' + 'lineItemId != :lineItemId')) + .OrderBy('lineItemId', ascending=True) + .WithBindVariable('reconciliationReportId', + RECONCILIATION_REPORT_ID) + .WithBindVariable('lineItemId', 0)) # Retrieve a small amount of reconciliation line item reports at a time, # paging through until all reconciliation line item reports have been # retrieved. - while True: - response = ( - reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement( - statement.ToStatement())) - if 'results' in response: - for reconciliation_line_item_report in response['results']: - # Print out some information for each reconciliation line item report. - print( - 'Reconciliation line item report with ID "%d", line item ID "%d", ' - 'reconciliation source "%s", and reconciled volume "%d" was ' - 'found.\n' % - (reconciliation_line_item_report['id'], - reconciliation_line_item_report['lineItemId'], - reconciliation_line_item_report['reconciliationSource'], - reconciliation_line_item_report['reconciledVolume'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break + result_set_size = 0 + should_continue = True + + while should_continue: + page = (reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement( + statement.ToStatement())) + if 'results' in page: + result_set_size += page['totalResultSetSize'] + # Iterate over individual results in the page. + for line_item_report in page['results']: + print ('Reconciliation line item report with ID %d, line item ID %d, ' + 'reconciliation source \'%s\', and reconciled volume %d was ' + 'found.' % (line_item_report['id'], + line_item_report['lineItemId'], + line_item_report['reconciliationSource'], + (line_item_report['reconciledVolume'] + if 'reconciledVolume' in line_item_report else 0))) + # Update statement for next page. + statement.offset += statement.limit + should_continue = statement.offset < result_set_size - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print 'Number of results found: %d' % result_set_size if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) + main(dfp_client) diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py new file mode 100644 index 00000000..1f9b1e48 --- /dev/null +++ b/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 updates a reconciliation line item report. + +To get reconciliation line item reports for a reconciliation report, run +get_reconciliation_line_item_reports_for_reconciliation_report.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation line item report to update. +RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_line_item_report_service = (client.GetService( + 'ReconciliationLineItemReportService', version='v201702')) + + # Create a statement to select a reconciliation line item report. + statement = (dfp.StatementBuilder() + .Where('id = :lineItemReportId') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('lineItemReportId', + RECONCILIATION_LINE_ITEM_REPORT_ID)) + + # Get reconciliation line item reports by statement. + page = (reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement(statement.ToStatement())) + + line_item_report = page['results'][0] + + # Set and use a manual volume for billing. This example splits the difference + # between DFP and the third party volume. + line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + + line_item_report['thirdPartyVolume']) / 2 + line_item_report['reconciliationSource'] = 'MANUAL' + + result = (reconciliation_line_item_report_service + .updateReconciliationLineItemReports([line_item_report])) + + for updated_report in result: + print ('Reconciliation line item report with ID %d for line item ID %d was ' + 'updated, with manual volume %d' % (updated_report['id'], + updated_report['lineItemId'], + updated_report['manualVolume'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py new file mode 100644 index 00000000..35d94c91 --- /dev/null +++ b/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 submits a reconciliation order report. + +To get all reconciliation order reports for a reconciliation report, +run get get_reconciliation_order_reports_for_reconciliation_report.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation order report to submit. +RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_order_report_service = (client.GetService( + 'ReconciliationOrderReportService', version='v201702')) + + # Create a statement to select reconciliation order reports. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', RECONCILIATION_ORDER_REPORT_ID)) + + # Get reconciliation order reports by statement. + page = (reconciliation_order_report_service + .getReconciliationOrderReportsByStatement(statement.ToStatement())) + + report = page['results'][0] + + print ('Reconciliation order report with ID %d will be submitted.' % + report['id']) + + # Remove limit and offset from statement. + statement.limit = None + statement.offset = None + + # Perform action. + result = (reconciliation_order_report_service + .performReconciliationOrderReportAction( + {'xsi_type': 'SubmitReconciliationOrderReports'}, + statement.ToStatement())) + + if result and result['numChanges'] > 0: + print ('Number of reconciliation order reports submitted: %d' % + result['numChanges']) + else: + print 'No reconciliation order reports were submitted.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py old mode 100755 new mode 100644 index 22f41176..21daadd3 --- a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -13,12 +13,14 @@ # 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. + """Gets a reconciliation report's rows for line items that served through DFP. """ # Import appropriate modules from the client library. from googleads import dfp +# Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -28,13 +30,13 @@ def main(client, reconciliation_report_id): 'ReconciliationReportRowService', version='v201702') query = ('WHERE reconciliationReportId = %s AND ' 'lineItemId != :lineItemId') % reconciliation_report_id - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - }}, - ] + values = [{ + 'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + } + }] # Create a statement to select reconciliation report rows. statement = dfp.FilterStatement(query, values) diff --git a/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py new file mode 100644 index 00000000..fff5f766 --- /dev/null +++ b/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 updates a reconciliation report row. + +To determine which reconciliation report rows exist, +run get_reconciliation_report_rows_for_reconciliation_report.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation report row. +RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' + +# Set the ID of the reconciliation report. +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_report_row_service = (client.GetService( + 'ReconciliationReportRowService', version='v201702')) + + # Create a statement to select reconciliation report rows. + statement = (dfp.StatementBuilder() + .Where(('id = :reconciliationReportRowId AND ' + 'reconciliationReportId = :reconciliationReportId')) + .OrderBy('id', ascending=True) + .WithBindVariable('reconciliationReportRowId', + RECONCILIATION_REPORT_ROW_ID) + .WithBindVariable('reconciliationReportId', + RECONCILIATION_REPORT_ID)) + + # Get reconciliation report rows by statement. + page = (reconciliation_report_row_service + .getReconciliationReportRowsByStatement(statement.ToStatement())) + + row = page['results'][0] + + # Set a comment on the reconciliation report row. + row['comments'] = ('Third part volume didn\'t match DFP - we agreed to split ' + 'the difference') + + # Set and use a manual volume for billing. + row['manualVolume'] = (row['dfpVolume'] + row['thirdPartyVolume']) / 2 + row['reconciliationSource'] = 'MANUAL' + + updated_rows = (reconciliation_report_row_service + .updateReconciliationReportRows([row])) + + for updated_row in updated_rows: + print ('Reconciliation report row for line item ID %d and creative ID %d ' + 'was updated, with manual volume %d' % (updated_row['lineItemId'], + updated_row['creativeId'], + updated_row['manualVolume'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/report_service/__init__.py b/examples/dfp/v201702/report_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/report_service/run_delivery_report.py b/examples/dfp/v201702/report_service/run_delivery_report.py old mode 100755 new mode 100644 index d09c1f5c..94b3b46c --- a/examples/dfp/v201702/report_service/run_delivery_report.py +++ b/examples/dfp/v201702/report_service/run_delivery_report.py @@ -43,7 +43,7 @@ def main(client, order_id): 'values': values} # Set the start and end dates of the report to run (past 8 days). - end_date = datetime.now() + end_date = datetime.now().date() start_date = end_date - timedelta(days=8) # Create report job. @@ -57,12 +57,8 @@ def main(client, order_id): 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], 'dateRangeType': 'CUSTOM_DATE', - 'startDate': {'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day}, - 'endDate': {'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day} + 'startDate': start_date, + 'endDate': end_date } } diff --git a/examples/dfp/v201702/report_service/run_inventory_report.py b/examples/dfp/v201702/report_service/run_inventory_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/report_service/run_reach_report.py b/examples/dfp/v201702/report_service/run_reach_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py b/examples/dfp/v201702/report_service/run_report_with_custom_fields.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/report_service/run_sales_report.py b/examples/dfp/v201702/report_service/run_sales_report.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/report_service/run_saved_query.py b/examples/dfp/v201702/report_service/run_saved_query.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/suggested_ad_unit_service/__init__.py b/examples/dfp/v201702/suggested_ad_unit_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/team_service/__init__.py b/examples/dfp/v201702/team_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/team_service/create_teams.py b/examples/dfp/v201702/team_service/create_teams.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/team_service/get_all_teams.py b/examples/dfp/v201702/team_service/get_all_teams.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/team_service/update_teams.py b/examples/dfp/v201702/team_service/update_teams.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_service/__init__.py b/examples/dfp/v201702/user_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_service/create_users.py b/examples/dfp/v201702/user_service/create_users.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_service/deactivate_users.py b/examples/dfp/v201702/user_service/deactivate_users.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_service/get_all_roles.py b/examples/dfp/v201702/user_service/get_all_roles.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_service/get_all_users.py b/examples/dfp/v201702/user_service/get_all_users.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_service/get_current_user.py b/examples/dfp/v201702/user_service/get_current_user.py new file mode 100755 index 00000000..2c056f48 --- /dev/null +++ b/examples/dfp/v201702/user_service/get_current_user.py @@ -0,0 +1,39 @@ +#!/usr/bin/python +# +# Copyright 2017 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 the current user.""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201702') + + # Get current user. + user = user_service.getCurrentUser() + + print ('User with ID %d, name \'%s\', email \'%s\', and role \'%s\' ' + 'is the current user.' % ( + user.id, user.name, user.email, user.roleName + )) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/user_service/get_user_by_email_address.py b/examples/dfp/v201702/user_service/get_user_by_email_address.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_service/update_users.py b/examples/dfp/v201702/user_service/update_users.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_team_association_service/__init__.py b/examples/dfp/v201702/user_team_association_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/workflow_request_service/__init__.py b/examples/dfp/v201702/workflow_request_service/__init__.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py old mode 100755 new mode 100644 diff --git a/examples/dfp/v201608/activity_group_service/__init__.py b/examples/dfp/v201705/activity_group_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/activity_group_service/__init__.py rename to examples/dfp/v201705/activity_group_service/__init__.py diff --git a/examples/dfp/v201608/activity_group_service/create_activity_groups.py b/examples/dfp/v201705/activity_group_service/create_activity_groups.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/activity_group_service/create_activity_groups.py rename to examples/dfp/v201705/activity_group_service/create_activity_groups.py index adc441de..ab903e32 --- a/examples/dfp/v201608/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201705/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201608') + version='v201705') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201608/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201705/activity_group_service/get_active_activity_groups.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201705/activity_group_service/get_active_activity_groups.py index eba63436..945ac5dd --- a/examples/dfp/v201608/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201705/activity_group_service/get_active_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201608') + 'ActivityGroupService', version='v201705') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201705/activity_group_service/get_all_activity_groups.py index c3b69785..7d51c2cc --- a/examples/dfp/v201608/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201608') + 'ActivityGroupService', version='v201705') # Create a statement to select activity groups. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/activity_group_service/update_activity_groups.py b/examples/dfp/v201705/activity_group_service/update_activity_groups.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/activity_group_service/update_activity_groups.py rename to examples/dfp/v201705/activity_group_service/update_activity_groups.py index 85bb1331..5d55d542 --- a/examples/dfp/v201608/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201705/activity_group_service/update_activity_groups.py @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201608') + version='v201705') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201608/activity_service/__init__.py b/examples/dfp/v201705/activity_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/activity_service/__init__.py rename to examples/dfp/v201705/activity_service/__init__.py diff --git a/examples/dfp/v201608/activity_service/create_activities.py b/examples/dfp/v201705/activity_service/create_activities.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/activity_service/create_activities.py rename to examples/dfp/v201705/activity_service/create_activities.py index e1e87d44..fd9afebc --- a/examples/dfp/v201608/activity_service/create_activities.py +++ b/examples/dfp/v201705/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201608') + activity_service = client.GetService('ActivityService', version='v201705') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201608/activity_service/get_active_activities.py b/examples/dfp/v201705/activity_service/get_active_activities.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/activity_service/get_active_activities.py rename to examples/dfp/v201705/activity_service/get_active_activities.py index e1b5899b..e9e16a6e --- a/examples/dfp/v201608/activity_service/get_active_activities.py +++ b/examples/dfp/v201705/activity_service/get_active_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201608') + activity_service = client.GetService('ActivityService', version='v201705') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201608/activity_service/get_all_activities.py b/examples/dfp/v201705/activity_service/get_all_activities.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/activity_service/get_all_activities.py rename to examples/dfp/v201705/activity_service/get_all_activities.py index d51808f3..e8db21bc --- a/examples/dfp/v201608/activity_service/get_all_activities.py +++ b/examples/dfp/v201705/activity_service/get_all_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201608') + activity_service = client.GetService('ActivityService', version='v201705') # Create a statement to select activities. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/activity_service/update_activities.py b/examples/dfp/v201705/activity_service/update_activities.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/activity_service/update_activities.py rename to examples/dfp/v201705/activity_service/update_activities.py index 02ae1506..b04c5f31 --- a/examples/dfp/v201608/activity_service/update_activities.py +++ b/examples/dfp/v201705/activity_service/update_activities.py @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201608') + activity_service = client.GetService('ActivityService', version='v201705') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201608/audience_segment_service/__init__.py b/examples/dfp/v201705/audience_segment_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/audience_segment_service/__init__.py rename to examples/dfp/v201705/audience_segment_service/__init__.py diff --git a/examples/dfp/v201608/audience_segment_service/create_audience_segments.py b/examples/dfp/v201705/audience_segment_service/create_audience_segments.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201705/audience_segment_service/create_audience_segments.py index f1ffa845..f580381b --- a/examples/dfp/v201608/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/create_audience_segments.py @@ -26,11 +26,12 @@ CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' + def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201608') - network_service = client.GetService('NetworkService', version='v201608') + 'AudienceSegmentService', version='v201705') + network_service = client.GetService('NetworkService', version='v201705') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py index a8445f6a..f3ce56ba --- a/examples/dfp/v201608/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201608') + 'AudienceSegmentService', version='v201705') # Create a statement to select audience segments. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py index 65bf29b2..faec6a63 --- a/examples/dfp/v201608/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201608') + 'AudienceSegmentService', version='v201705') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py old mode 100755 new mode 100644 similarity index 90% rename from examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py index 995f300a..72cffa44 --- a/examples/dfp/v201608/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py @@ -30,7 +30,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201608') + 'AudienceSegmentService', version='v201705') # Create statement object to get the specified first party audience segment. values = ( @@ -43,7 +43,7 @@ def main(client, audience_segment_id): {'key': 'audience_segment_id', 'value': { 'xsi_type': 'NumberValue', - 'value': AUDIENCE_SEGMENT_ID + 'value': audience_segment_id } }]) query = 'WHERE Type = :type AND Id = :audience_segment_id' @@ -56,8 +56,9 @@ def main(client, audience_segment_id): segments = response['results'] for segment in segments: - print ('Audience segment with id \'%s\' and name \'%s\' will be populated.' - % (segment['id'], segment['name'])) + print ( + 'Audience segment with id \'%s\' and name \'%s\' will be populated.' + % (segment['id'], segment['name'])) action = { 'xsi_type': 'PopulateAudienceSegments' diff --git a/examples/dfp/v201608/audience_segment_service/update_audience_segments.py b/examples/dfp/v201705/audience_segment_service/update_audience_segments.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201705/audience_segment_service/update_audience_segments.py index ca8f2ded..a7723e62 --- a/examples/dfp/v201608/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/update_audience_segments.py @@ -29,7 +29,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201608') + 'AudienceSegmentService', version='v201705') # Create statement object to get the specified first party audience segment. values = ( @@ -42,7 +42,7 @@ def main(client, audience_segment_id): {'key': 'audience_segment_id', 'value': { 'xsi_type': 'NumberValue', - 'value': AUDIENCE_SEGMENT_ID + 'value': audience_segment_id } }]) query = 'WHERE Type = :type AND Id = :audience_segment_id' diff --git a/examples/dfp/v201608/base_rate_service/__init__.py b/examples/dfp/v201705/base_rate_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/base_rate_service/__init__.py rename to examples/dfp/v201705/base_rate_service/__init__.py diff --git a/examples/dfp/v201608/base_rate_service/create_product_base_rates.py b/examples/dfp/v201705/base_rate_service/create_product_base_rates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201705/base_rate_service/create_product_base_rates.py index 2de27113..453ab744 --- a/examples/dfp/v201608/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201608') + 'BaseRateService', version='v201705') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py new file mode 100755 index 00000000..67397296 --- /dev/null +++ b/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py @@ -0,0 +1,66 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a product package item base rate. + +To determine which base rates exist, run get_all_base_rates.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the rate card ID to add the base rate to. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + +# Set the product package item to apply this base rate to. +PRODUCT_PACKAGE_ITEM_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201705') + + # Create a base rate for a product package item. + base_rate = { + 'xsi_type': 'ProductPackageItemBaseRate', + # Set the rate card ID that the product package item base rate + # belongs to. + 'rateCardId': RATE_CARD_ID, + # Set the product package item the base rate will be applied to. + 'productPackageItemId': PRODUCT_PACKAGE_ITEM_ID, + # Create a rate worth $2 USD and set that on the product package item + # base rate. + 'rate': { + 'xsi_type': 'Money', + 'currencyCode': 'USD', + 'microAmount': 2000000, + } + } + + # Create the product package item base rate on the server. + result = base_rate_service.createBaseRates([base_rate]) + + for new_base_rate in result: + print ('A product package item base rate with ID %d and rate %f %s ' + 'was created.' % (new_base_rate['id'], + new_base_rate['microAmount'], + new_base_rate['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py index a39ce9ad..2d42c897 --- a/examples/dfp/v201608/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201608') + 'BaseRateService', version='v201705') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201608/base_rate_service/get_all_base_rates.py b/examples/dfp/v201705/base_rate_service/get_all_base_rates.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201705/base_rate_service/get_all_base_rates.py index 9afb9f02..cc762428 --- a/examples/dfp/v201608/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/get_all_base_rates.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201608') + base_rate_service = client.GetService('BaseRateService', version='v201705') # Create a statement to select base rates. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py rename to examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py index f468e2d3..5ebb7edf --- a/examples/dfp/v201608/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py @@ -24,7 +24,7 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201608') + base_rate_service = client.GetService('BaseRateService', version='v201705') query = 'WHERE rateCardId = :rateCardId' values = [ {'key': 'rateCardId', diff --git a/examples/dfp/v201608/base_rate_service/update_base_rates.py b/examples/dfp/v201705/base_rate_service/update_base_rates.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/base_rate_service/update_base_rates.py rename to examples/dfp/v201705/base_rate_service/update_base_rates.py index 93f1b70b..284f6e47 --- a/examples/dfp/v201608/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201608') + base_rate_service = client.GetService('BaseRateService', version='v201705') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201608/company_service/__init__.py b/examples/dfp/v201705/company_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/company_service/__init__.py rename to examples/dfp/v201705/company_service/__init__.py diff --git a/examples/dfp/v201608/company_service/create_companies.py b/examples/dfp/v201705/company_service/create_companies.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/company_service/create_companies.py rename to examples/dfp/v201705/company_service/create_companies.py index 6d3628b7..cbaa7ff1 --- a/examples/dfp/v201608/company_service/create_companies.py +++ b/examples/dfp/v201705/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201608') + company_service = client.GetService('CompanyService', version='v201705') # Create company objects. companies = [ diff --git a/examples/dfp/v201608/company_service/get_advertisers.py b/examples/dfp/v201705/company_service/get_advertisers.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/company_service/get_advertisers.py rename to examples/dfp/v201705/company_service/get_advertisers.py index 25d65ade..16e506d9 --- a/examples/dfp/v201608/company_service/get_advertisers.py +++ b/examples/dfp/v201705/company_service/get_advertisers.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201608') + company_service = client.GetService('CompanyService', version='v201705') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201608/company_service/get_all_companies.py b/examples/dfp/v201705/company_service/get_all_companies.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/company_service/get_all_companies.py rename to examples/dfp/v201705/company_service/get_all_companies.py index 10177f1c..7bb631bb --- a/examples/dfp/v201608/company_service/get_all_companies.py +++ b/examples/dfp/v201705/company_service/get_all_companies.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201608') + company_service = client.GetService('CompanyService', version='v201705') # Create a statement to select companies. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/company_service/update_companies.py b/examples/dfp/v201705/company_service/update_companies.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/company_service/update_companies.py rename to examples/dfp/v201705/company_service/update_companies.py index 0ce64144..78ecebd8 --- a/examples/dfp/v201608/company_service/update_companies.py +++ b/examples/dfp/v201705/company_service/update_companies.py @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201608') + company_service = client.GetService('CompanyService', version='v201705') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201608/contact_service/__init__.py b/examples/dfp/v201705/contact_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/contact_service/__init__.py rename to examples/dfp/v201705/contact_service/__init__.py diff --git a/examples/dfp/v201608/contact_service/create_contacts.py b/examples/dfp/v201705/contact_service/create_contacts.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/contact_service/create_contacts.py rename to examples/dfp/v201705/contact_service/create_contacts.py index 73236787..634c774c --- a/examples/dfp/v201608/contact_service/create_contacts.py +++ b/examples/dfp/v201705/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201608') + contact_service = client.GetService('ContactService', version='v201705') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201608/contact_service/get_all_contacts.py b/examples/dfp/v201705/contact_service/get_all_contacts.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/contact_service/get_all_contacts.py rename to examples/dfp/v201705/contact_service/get_all_contacts.py index 0c67d0bb..42fdd9fd --- a/examples/dfp/v201608/contact_service/get_all_contacts.py +++ b/examples/dfp/v201705/contact_service/get_all_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201608') + contact_service = client.GetService('ContactService', version='v201705') # Create a statement to select contacts. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/contact_service/get_uninvited_contacts.py b/examples/dfp/v201705/contact_service/get_uninvited_contacts.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201705/contact_service/get_uninvited_contacts.py index c913599b..911225a5 --- a/examples/dfp/v201608/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201705/contact_service/get_uninvited_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201608') + contact_service = client.GetService('ContactService', version='v201705') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201608/contact_service/update_contacts.py b/examples/dfp/v201705/contact_service/update_contacts.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/contact_service/update_contacts.py rename to examples/dfp/v201705/contact_service/update_contacts.py index acd72fcd..772869a9 --- a/examples/dfp/v201608/contact_service/update_contacts.py +++ b/examples/dfp/v201705/contact_service/update_contacts.py @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201608') + contact_service = client.GetService('ContactService', version='v201705') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index ab24b17f..38b4b3b7 --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201608') + 'ContentMetadataKeyHierarchyService', version='v201705') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 3b6fd2a7..c605a231 --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201608') + 'ContentMetadataKeyHierarchyService', version='v201705') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 similarity index 89% rename from examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 8fd22438..4284380e --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201608') + 'ContentMetadataKeyHierarchyService', version='v201705') # Create a statement to select content metadata key hierarchies. statement = dfp.FilterStatement() @@ -32,8 +32,10 @@ def main(client): # paging through until all content metadata key hierarchies have been # retrieved. while True: - response = content_metadata_key_hierarchy_service.getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement()) + response = ( + content_metadata_key_hierarchy_service + .getContentMetadataKeyHierarchiesByStatement( + statement.ToStatement())) if 'results' in response: for content_metadata_key_hierarchy in response['results']: # Print out some information for each content metadata key hierarchy. diff --git a/examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index a4301c8a..8a2995b9 --- a/examples/dfp/v201608/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201608') + 'ContentMetadataKeyHierarchyService', version='v201705') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201608/content_service/__init__.py b/examples/dfp/v201705/content_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/content_service/__init__.py rename to examples/dfp/v201705/content_service/__init__.py diff --git a/examples/dfp/v201608/content_service/get_all_content.py b/examples/dfp/v201705/content_service/get_all_content.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/content_service/get_all_content.py rename to examples/dfp/v201705/content_service/get_all_content.py index ec57a600..c2bd7aee --- a/examples/dfp/v201608/content_service/get_all_content.py +++ b/examples/dfp/v201705/content_service/get_all_content.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201608') + content_service = client.GetService('ContentService', version='v201705') # Create a statement to select content. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/creative_service/__init__.py b/examples/dfp/v201705/creative_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/creative_service/__init__.py rename to examples/dfp/v201705/creative_service/__init__.py diff --git a/examples/dfp/v201705/creative_service/copy_image_creatives.py b/examples/dfp/v201705/creative_service/copy_image_creatives.py new file mode 100755 index 00000000..1b57ed44 --- /dev/null +++ b/examples/dfp/v201705/creative_service/copy_image_creatives.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a copy of an image creative. + +To determine which image creatives exist, run get_image_creatives.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201705') + + # Create a statement to get the image creative. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', CREATIVE_ID)) + + # Get the creative. + query_result = creative_service.getCreativesByStatement( + statement.ToStatement()) + + image_creative = query_result['results'][0] + + # Build the new creative, set id to None to create a copy. + image_creative['id'] = None + image_creative['name'] = 'Copy of %s' % image_creative['name'] + + result = creative_service.createCreatives([image_creative])[0] + print ('A creative with ID %d, name \'%s\', and type \'%s\' was created and ' + 'can be previewed at: %s' % (result['id'], + result['name'], + dfp.DfpClassType(result), + result['previewUrl'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/creative_service/create_creative_from_template.py b/examples/dfp/v201705/creative_service/create_creative_from_template.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/creative_service/create_creative_from_template.py rename to examples/dfp/v201705/creative_service/create_creative_from_template.py index a077fe07..df861679 --- a/examples/dfp/v201608/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201705/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201608') + creative_service = client.GetService('CreativeService', version='v201705') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201608/creative_service/create_creatives.py b/examples/dfp/v201705/creative_service/create_creatives.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/creative_service/create_creatives.py rename to examples/dfp/v201705/creative_service/create_creatives.py index fdc643b4..419477d7 --- a/examples/dfp/v201608/creative_service/create_creatives.py +++ b/examples/dfp/v201705/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201608') + creative_service = client.GetService('CreativeService', version='v201705') # Create creative objects. creatives = [] @@ -48,7 +48,7 @@ def main(client, advertiser_id): 'medium_rectangle.jpg'), 'r') as image: image_data = base64.encodestring(image.read()) - for i in xrange(5): + for _ in xrange(5): # Create creative size. size = { 'width': '300', diff --git a/examples/dfp/v201608/creative_service/create_custom_creative.py b/examples/dfp/v201705/creative_service/create_custom_creative.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/creative_service/create_custom_creative.py rename to examples/dfp/v201705/creative_service/create_custom_creative.py index 7151169d..32dcf3fc --- a/examples/dfp/v201608/creative_service/create_custom_creative.py +++ b/examples/dfp/v201705/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201608') + creative_service = client.GetService('CreativeService', version='v201705') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201608/creative_service/create_native_creative.py b/examples/dfp/v201705/creative_service/create_native_creative.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/creative_service/create_native_creative.py rename to examples/dfp/v201705/creative_service/create_native_creative.py index bed2f8b2..d7a7c3c1 --- a/examples/dfp/v201608/creative_service/create_native_creative.py +++ b/examples/dfp/v201705/creative_service/create_native_creative.py @@ -46,7 +46,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201608') + creative_service = client.GetService('CreativeService', version='v201705') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/dfp/v201608/creative_service/get_all_creatives.py b/examples/dfp/v201705/creative_service/get_all_creatives.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/creative_service/get_all_creatives.py rename to examples/dfp/v201705/creative_service/get_all_creatives.py index e7e3cf3e..d400094b --- a/examples/dfp/v201608/creative_service/get_all_creatives.py +++ b/examples/dfp/v201705/creative_service/get_all_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201608') + creative_service = client.GetService('CreativeService', version='v201705') # Create a statement to select creatives. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/creative_service/get_image_creatives.py b/examples/dfp/v201705/creative_service/get_image_creatives.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/creative_service/get_image_creatives.py rename to examples/dfp/v201705/creative_service/get_image_creatives.py index 6976b6b6..bc977ea8 --- a/examples/dfp/v201608/creative_service/get_image_creatives.py +++ b/examples/dfp/v201705/creative_service/get_image_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201608') + creative_service = client.GetService('CreativeService', version='v201705') query = 'WHERE creativeType = :creativeType' values = [ {'key': 'creativeType', diff --git a/examples/dfp/v201608/creative_service/update_creatives.py b/examples/dfp/v201705/creative_service/update_creatives.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/creative_service/update_creatives.py rename to examples/dfp/v201705/creative_service/update_creatives.py index 7c003e71..8d10156a --- a/examples/dfp/v201608/creative_service/update_creatives.py +++ b/examples/dfp/v201705/creative_service/update_creatives.py @@ -34,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201608') + creative_service = client.GetService('CreativeService', version='v201705') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201608/creative_set_service/__init__.py b/examples/dfp/v201705/creative_set_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/creative_set_service/__init__.py rename to examples/dfp/v201705/creative_set_service/__init__.py diff --git a/examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py old mode 100755 new mode 100644 similarity index 92% rename from examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py index 1d0238b4..b5e98713 --- a/examples/dfp/v201608/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates a line item creative association for a creative -set. +"""Creates a line item creative association for a creative set. To create creative sets, run create_creative_set.py. To create creatives, run create_creatives.py. To determine which LICAs exist, run get_all_licas.py. @@ -38,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201608') + 'LineItemCreativeAssociationService', version='v201705') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201608/creative_set_service/create_creative_set.py b/examples/dfp/v201705/creative_set_service/create_creative_set.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_set_service/create_creative_set.py rename to examples/dfp/v201705/creative_set_service/create_creative_set.py index 0dfb7136..ef60d411 --- a/examples/dfp/v201608/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201705/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201608') + version='v201705') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201608/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201705/creative_set_service/get_all_creative_sets.py index 4297a120..90257068 --- a/examples/dfp/v201608/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201608') + 'CreativeSetService', version='v201705') # Create a statement to select creative sets. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py index 4fcc65f7..2d4208d4 --- a/examples/dfp/v201608/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,7 +25,7 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201608') + 'CreativeSetService', version='v201705') query = 'WHERE masterCreativeId = :masterCreativeId' values = [ {'key': 'masterCreativeId', diff --git a/examples/dfp/v201608/creative_set_service/update_creative_set.py b/examples/dfp/v201705/creative_set_service/update_creative_set.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_set_service/update_creative_set.py rename to examples/dfp/v201705/creative_set_service/update_creative_set.py index 9353ad93..b8289d3c --- a/examples/dfp/v201608/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201705/creative_set_service/update_creative_set.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201608') + version='v201705') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201608/creative_template_service/__init__.py b/examples/dfp/v201705/creative_template_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/creative_template_service/__init__.py rename to examples/dfp/v201705/creative_template_service/__init__.py diff --git a/examples/dfp/v201608/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201705/creative_template_service/get_all_creative_templates.py index 9df6b1c0..7bdec81f --- a/examples/dfp/v201608/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201608') + 'CreativeTemplateService', version='v201705') # Create a statement to select creative templates. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py rename to examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py index 2be82828..920c4974 --- a/examples/dfp/v201608/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201608') + 'CreativeTemplateService', version='v201705') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py index dc5cb188..f0ce0521 --- a/examples/dfp/v201608/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201608') + version='v201705') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py index cd33b02f..bf72c2ea --- a/examples/dfp/v201608/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201608') + version='v201705') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py index eb32cecc..2bc54fc4 --- a/examples/dfp/v201608/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201608') + 'CreativeWrapperService', version='v201705') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py index 8d0a5e81..7b783565 --- a/examples/dfp/v201608/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201608') + 'CreativeWrapperService', version='v201705') # Create a statement to select creative wrappers. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py index bb9d5725..ae0a6e83 --- a/examples/dfp/v201608/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201608') + version='v201705') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201608/custom_field_service/__init__.py b/examples/dfp/v201705/custom_field_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/custom_field_service/__init__.py rename to examples/dfp/v201705/custom_field_service/__init__.py diff --git a/examples/dfp/v201608/custom_field_service/create_custom_field_options.py b/examples/dfp/v201705/custom_field_service/create_custom_field_options.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201705/custom_field_service/create_custom_field_options.py index dc1ca182..01c75244 --- a/examples/dfp/v201608/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201705/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201608') + 'CustomFieldService', version='v201705') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201608/custom_field_service/create_custom_fields.py b/examples/dfp/v201705/custom_field_service/create_custom_fields.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/custom_field_service/create_custom_fields.py rename to examples/dfp/v201705/custom_field_service/create_custom_fields.py index 8e5f4f6b..a02265dc --- a/examples/dfp/v201608/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201705/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201608') + 'CustomFieldService', version='v201705') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py index c33b63db..3d3b2446 --- a/examples/dfp/v201608/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201608') + 'CustomFieldService', version='v201705') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201608/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201705/custom_field_service/get_all_custom_fields.py index a7cb4130..42631ca9 --- a/examples/dfp/v201608/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201608') + 'CustomFieldService', version='v201705') # Create a statement to select custom fields. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py rename to examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py index 9c2ec3d5..a5df35ad --- a/examples/dfp/v201608/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201608') + 'CustomFieldService', version='v201705') query = 'WHERE entityType = :entityType' values = [ {'key': 'entityType', diff --git a/examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py index 2e9b302e..0951a546 --- a/examples/dfp/v201608/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201608') + 'CustomFieldService', version='v201705') - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201608/custom_field_service/update_custom_fields.py b/examples/dfp/v201705/custom_field_service/update_custom_fields.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/custom_field_service/update_custom_fields.py rename to examples/dfp/v201705/custom_field_service/update_custom_fields.py index c8ed4278..73cf0845 --- a/examples/dfp/v201608/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201705/custom_field_service/update_custom_fields.py @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201608') + 'CustomFieldService', version='v201705') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201608/custom_targeting_service/__init__.py b/examples/dfp/v201705/custom_targeting_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/custom_targeting_service/__init__.py rename to examples/dfp/v201705/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py index d8e5fbfe..e337aebf --- a/examples/dfp/v201608/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201608') + 'CustomTargetingService', version='v201705') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py index 9513e854..03c46640 --- a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201608') + 'CustomTargetingService', version='v201705') values = [{ 'key': 'name', diff --git a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py old mode 100755 new mode 100644 similarity index 95% rename from examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py index 4849dd14..9a09683d --- a/examples/dfp/v201608/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example deletes custom targeting values for a given custom targeting -key. +"""Deletes custom targeting values for a given custom targeting key. To determine which custom targeting keys and values exist, run get_all_custom_targeting_keys_and_values.py. @@ -37,7 +36,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201608') + 'CustomTargetingService', version='v201705') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index afdb514c..3e937fd0 --- a/examples/dfp/v201608/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201608') + 'CustomTargetingService', version='v201705') # Create statement to get all targeting keys. targeting_key_statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 970a1e97..eda4ac5b --- a/examples/dfp/v201608/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201608') + 'CustomTargetingService', version='v201705') # Create statement to get targeting keys for predefined values. query = ('WHERE type = :type') diff --git a/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py old mode 100755 new mode 100644 similarity index 95% rename from examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py index 201d93ed..a6bbeebe --- a/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py @@ -17,7 +17,8 @@ """This example updates the display name of a single custom targeting key. To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201608') + 'CustomTargetingService', version='v201705') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py old mode 100755 new mode 100644 similarity index 91% rename from examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py index 24154ce6..1cc85c81 --- a/examples/dfp/v201608/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates the display name of the custom targeting values -belonging to a custom targeting key. +"""Updates name of custom targeting values belonging to a custom targeting key. To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" # Import appropriate modules from the client library. @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201608') + 'CustomTargetingService', version='v201705') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201608/exchange_rate_service/__init__.py b/examples/dfp/v201705/exchange_rate_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/exchange_rate_service/__init__.py rename to examples/dfp/v201705/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py index fda130a0..4fd18507 --- a/examples/dfp/v201608/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201608') + version='v201705') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py index 0d70e0d7..69f5daac --- a/examples/dfp/v201608/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201608') + 'ExchangeRateService', version='v201705') # Create a statement to select exchange rates. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py index 677769d3..acac6d8c --- a/examples/dfp/v201608/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,7 +25,7 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201608') + 'ExchangeRateService', version='v201705') query = 'WHERE currencyCode = :currencyCode' values = [ {'key': 'currencyCode', diff --git a/examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py index f22fd183..dae8aad9 --- a/examples/dfp/v201608/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201608') + version='v201705') # Create a statement to get an exchange rate by its ID. values = [{ diff --git a/examples/dfp/v201608/forecast_service/get_availability_forecast.py b/examples/dfp/v201705/forecast_service/get_availability_forecast.py old mode 100755 new mode 100644 similarity index 92% rename from examples/dfp/v201608/forecast_service/get_availability_forecast.py rename to examples/dfp/v201705/forecast_service/get_availability_forecast.py index 634a2eaa..0bb2e691 --- a/examples/dfp/v201608/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201705/forecast_service/get_availability_forecast.py @@ -24,10 +24,11 @@ """ -from datetime import date +import datetime # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set the ID of the advertiser (company) to forecast for. Setting an advertiser # will cause the forecast to apply the appropriate unified blocking rules. @@ -36,12 +37,15 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201608') - network_service = client.GetService('NetworkService', version='v201608') + forecast_service = client.GetService('ForecastService', version='v201705') + network_service = client.GetService('NetworkService', version='v201705') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=30) + # Create prospective line item. line_item = { 'targeting': { @@ -70,17 +74,7 @@ def main(client, advertiser_id): ], 'lineItemType': 'SPONSORSHIP', 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/New_York' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py index 5231f6c3..ff2263e0 --- a/examples/dfp/v201608/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201608') + forecast_service = client.GetService('ForecastService', version='v201705') # Set forecasting options. forecast_options = { diff --git a/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py index 1741b647..42f8aa03 --- a/examples/dfp/v201608/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201608') + forecast_service = client.GetService('ForecastService', version='v201705') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201608/inventory_service/__init__.py b/examples/dfp/v201705/inventory_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/inventory_service/__init__.py rename to examples/dfp/v201705/inventory_service/__init__.py diff --git a/examples/dfp/v201608/inventory_service/archive_ad_units.py b/examples/dfp/v201705/inventory_service/archive_ad_units.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/inventory_service/archive_ad_units.py rename to examples/dfp/v201705/inventory_service/archive_ad_units.py index e700add8..753304b2 --- a/examples/dfp/v201608/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201705/inventory_service/archive_ad_units.py @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201608') + inventory_service = client.GetService('InventoryService', version='v201705') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201608/inventory_service/create_ad_units.py b/examples/dfp/v201705/inventory_service/create_ad_units.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/inventory_service/create_ad_units.py rename to examples/dfp/v201705/inventory_service/create_ad_units.py index ef0fbf7c..bc8ddc7a --- a/examples/dfp/v201608/inventory_service/create_ad_units.py +++ b/examples/dfp/v201705/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201608') + inventory_service = client.GetService('InventoryService', version='v201705') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py index 23eb21dc..ac351ef1 --- a/examples/dfp/v201608/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201608') + 'InventoryService', version='v201705') # Create a statement to select ad unit sizes. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/inventory_service/get_all_ad_units.py b/examples/dfp/v201705/inventory_service/get_all_ad_units.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/inventory_service/get_all_ad_units.py rename to examples/dfp/v201705/inventory_service/get_all_ad_units.py index 61c80387..1e2b0cb2 --- a/examples/dfp/v201608/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201705/inventory_service/get_all_ad_units.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201608') + ad_unit_service = client.GetService('InventoryService', version='v201705') # Create a statement to select ad units. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/inventory_service/update_ad_units.py b/examples/dfp/v201705/inventory_service/update_ad_units.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/inventory_service/update_ad_units.py rename to examples/dfp/v201705/inventory_service/update_ad_units.py index e02d7c12..09ad3296 --- a/examples/dfp/v201608/inventory_service/update_ad_units.py +++ b/examples/dfp/v201705/inventory_service/update_ad_units.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201608') + inventory_service = client.GetService('InventoryService', version='v201705') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201608/label_service/__init__.py b/examples/dfp/v201705/label_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/label_service/__init__.py rename to examples/dfp/v201705/label_service/__init__.py diff --git a/examples/dfp/v201608/label_service/create_labels.py b/examples/dfp/v201705/label_service/create_labels.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/label_service/create_labels.py rename to examples/dfp/v201705/label_service/create_labels.py index 87fa8cf5..a9e68ec1 --- a/examples/dfp/v201608/label_service/create_labels.py +++ b/examples/dfp/v201705/label_service/create_labels.py @@ -17,7 +17,8 @@ """This code example creates new labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" import uuid @@ -28,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201608') + label_service = client.GetService('LabelService', version='v201705') # Create label objects. labels = [] diff --git a/examples/dfp/v201608/label_service/deactivate_labels.py b/examples/dfp/v201705/label_service/deactivate_labels.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/label_service/deactivate_labels.py rename to examples/dfp/v201705/label_service/deactivate_labels.py index b4920666..84882fa1 --- a/examples/dfp/v201608/label_service/deactivate_labels.py +++ b/examples/dfp/v201705/label_service/deactivate_labels.py @@ -17,7 +17,8 @@ """This code example deactivates all active Labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" # Import appropriate modules from the client library. @@ -26,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201608') + label_service = client.GetService('LabelService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/label_service/get_active_labels.py b/examples/dfp/v201705/label_service/get_active_labels.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/label_service/get_active_labels.py rename to examples/dfp/v201705/label_service/get_active_labels.py index ad8592a9..9a6ce559 --- a/examples/dfp/v201608/label_service/get_active_labels.py +++ b/examples/dfp/v201705/label_service/get_active_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201608') + label_service = client.GetService('LabelService', version='v201705') query = 'WHERE isActive = :isActive' values = [ {'key': 'isActive', diff --git a/examples/dfp/v201608/label_service/get_all_labels.py b/examples/dfp/v201705/label_service/get_all_labels.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/label_service/get_all_labels.py rename to examples/dfp/v201705/label_service/get_all_labels.py index 5545fc13..a89f62b2 --- a/examples/dfp/v201608/label_service/get_all_labels.py +++ b/examples/dfp/v201705/label_service/get_all_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201608') + label_service = client.GetService('LabelService', version='v201705') # Create a statement to select labels. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/label_service/update_labels.py b/examples/dfp/v201705/label_service/update_labels.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/label_service/update_labels.py rename to examples/dfp/v201705/label_service/update_labels.py index 6403ad95..620836ff --- a/examples/dfp/v201608/label_service/update_labels.py +++ b/examples/dfp/v201705/label_service/update_labels.py @@ -17,7 +17,8 @@ """This code example updates the description of a single label. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks.""" +available to DFP premium solution networks. +""" # Import appropriate modules from the client library. @@ -28,7 +29,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201608') + label_service = client.GetService('LabelService', version='v201705') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201608/line_item_creative_association_service/__init__.py b/examples/dfp/v201705/line_item_creative_association_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/line_item_creative_association_service/__init__.py rename to examples/dfp/v201705/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201608/line_item_creative_association_service/create_licas.py b/examples/dfp/v201705/line_item_creative_association_service/create_licas.py old mode 100755 new mode 100644 similarity index 93% rename from examples/dfp/v201608/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201705/line_item_creative_association_service/create_licas.py index 1700f5d9..606cbc37 --- a/examples/dfp/v201608/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/create_licas.py @@ -17,7 +17,8 @@ """This code example creates new line item creative associations (LICAs) for an existing line item and a set of creative ids. -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -31,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201608') + 'LineItemCreativeAssociationService', version='v201705') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py old mode 100755 new mode 100644 similarity index 95% rename from examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py index 29ed4a79..e4368471 --- a/examples/dfp/v201608/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py @@ -16,7 +16,8 @@ """This code example deactivates all LICAs for the line item. -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201608') + 'LineItemCreativeAssociationService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py index 5ba3194c..d4d05a62 --- a/examples/dfp/v201608/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201608') + 'LineItemCreativeAssociationService', version='v201705') # Create a statement to select line item creative associations. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py index 4909f8f8..4884013a --- a/examples/dfp/v201608/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,7 +25,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201608') + 'LineItemCreativeAssociationService', version='v201705') query = 'WHERE lineItemId = :lineItemId' values = [ {'key': 'lineItemId', diff --git a/examples/dfp/v201608/line_item_creative_association_service/update_licas.py b/examples/dfp/v201705/line_item_creative_association_service/update_licas.py old mode 100755 new mode 100644 similarity index 94% rename from examples/dfp/v201608/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201705/line_item_creative_association_service/update_licas.py index 2327f44d..43b3baa8 --- a/examples/dfp/v201608/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/update_licas.py @@ -17,7 +17,8 @@ """This code example updates the destination URL of all line item creative associations (LICA). -To determine which LICAs exist, run get_all_licas.py.""" +To determine which LICAs exist, run get_all_licas.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201608') + 'LineItemCreativeAssociationService', version='v201705') # Create statement object to get all LICAs. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/line_item_service/__init__.py b/examples/dfp/v201705/line_item_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/line_item_service/__init__.py rename to examples/dfp/v201705/line_item_service/__init__.py diff --git a/examples/dfp/v201608/line_item_service/activate_line_items.py b/examples/dfp/v201705/line_item_service/activate_line_items.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/line_item_service/activate_line_items.py rename to examples/dfp/v201705/line_item_service/activate_line_items.py index ac4d87df..6089b870 --- a/examples/dfp/v201608/line_item_service/activate_line_items.py +++ b/examples/dfp/v201705/line_item_service/activate_line_items.py @@ -20,7 +20,8 @@ one creative associated with them. To approve line items, approve the order to which they belong by running approve_orders.py. To create LICAs, run create_licas.py. To determine which line items exist, run -get_all_line_items.py.""" +get_all_line_items.py. +""" # Import appropriate modules from the client library. @@ -32,7 +33,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/line_item_service/create_line_items.py b/examples/dfp/v201705/line_item_service/create_line_items.py old mode 100755 new mode 100644 similarity index 92% rename from examples/dfp/v201608/line_item_service/create_line_items.py rename to examples/dfp/v201705/line_item_service/create_line_items.py index b9ef8c80..438b0480 --- a/examples/dfp/v201608/line_item_service/create_line_items.py +++ b/examples/dfp/v201705/line_item_service/create_line_items.py @@ -18,14 +18,16 @@ To determine which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To determine which placements exist, -run get_all_placements.py.""" +run get_all_placements.py. +""" -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set order that the created line item will belong to and add the id of a # placement containing ad units to target. @@ -35,11 +37,14 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) # Create line item objects. line_items = [] - for i in xrange(5): + for _ in xrange(5): line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, @@ -127,17 +132,7 @@ def main(client, order_id, targeted_placement_ids): ], 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'STANDARD', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201608/line_item_service/create_video_line_item.py b/examples/dfp/v201705/line_item_service/create_video_line_item.py old mode 100755 new mode 100644 similarity index 90% rename from examples/dfp/v201608/line_item_service/create_video_line_item.py rename to examples/dfp/v201705/line_item_service/create_video_line_item.py index 644706dd..9a9f3c8e --- a/examples/dfp/v201608/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201705/line_item_service/create_video_line_item.py @@ -20,14 +20,16 @@ which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To create a video ad unit, run create_video_ad_unit.py. To create criteria for categories, run -create_custom_targeting_keys_and_values.py""" +create_custom_targeting_keys_and_values.py. +""" -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set order that all created line item will belong to and the video ad unit id # to target. @@ -38,14 +40,17 @@ # on the content to target. This would typically be from a key representing # a "genre" and the value representing something like "comedy". The value # must be from a key in a content metadata key hierarchy. -CONTENT_CUSTOM_TARGETING_VALUE_ID = \ - 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE' +CONTENT_CUSTOM_TARGETING_VALUE_ID = ( + 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE') def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) # Create line item object. line_item = { @@ -98,17 +103,7 @@ def main(client, order_id, targeted_video_ad_unit_id, 'companionDeliveryOption': 'OPTIONAL', 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'SPONSORSHIP', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201608/line_item_service/get_all_line_items.py b/examples/dfp/v201705/line_item_service/get_all_line_items.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/line_item_service/get_all_line_items.py rename to examples/dfp/v201705/line_item_service/get_all_line_items.py index dd1c08d2..441fc5bc --- a/examples/dfp/v201608/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201705/line_item_service/get_all_line_items.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') # Create a statement to select line items. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py rename to examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py index 8f987767..27e2cca5 --- a/examples/dfp/v201608/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') query = 'WHERE isMissingCreatives = :isMissingCreatives' values = [ {'key': 'isMissingCreatives', diff --git a/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py index e542720f..bd8e23ca --- a/examples/dfp/v201608/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' values = [ {'key': 'lastModifiedDateTime', diff --git a/examples/dfp/v201705/line_item_service/pause_line_items.py b/examples/dfp/v201705/line_item_service/pause_line_items.py new file mode 100755 index 00000000..7425cd52 --- /dev/null +++ b/examples/dfp/v201705/line_item_service/pause_line_items.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# +# Copyright 2017 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 pauses a line item. + +Line items must be paused before they can be updated. To determine which line +items exist, run get_all_line_items.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201705') + + # Create a statement to select the line item. + # Change this to operate on more than one Line Item. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', LINE_ITEM_ID)) + + result_set_size = 0 + should_continue = True + + # Iterate over paged results from the statement. + while should_continue: + page = line_item_service.getLineItemsByStatement(statement.ToStatement()) + if 'results' in page: + result_set_size = page['totalResultSetSize'] + # Iterate over individual results in the page. + for line_item in page['results']: + print 'Pausing line item with ID %d' % line_item['id'] + # Update statement for next page. + statement.offset += statement.limit + should_continue = statement.offset < result_set_size + + print 'Pausing %d line item(s)' % result_set_size + + if result_set_size > 0: + statement.offset = None + statement.limit = None + + # Perform Pause action on all Line Items that match the statement. + update_result = line_item_service.performLineItemAction( + {'xsi_type': 'PauseLineItems'}, statement.ToStatement()) + + if update_result and update_result['numChanges'] > 0: + print 'Updated %d line item(s)' % update_result['numChanges'] + else: + print 'No line items were paused' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/line_item_service/target_custom_criteria.py b/examples/dfp/v201705/line_item_service/target_custom_criteria.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/line_item_service/target_custom_criteria.py rename to examples/dfp/v201705/line_item_service/target_custom_criteria.py index f8c524d5..4ba0dd29 --- a/examples/dfp/v201608/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201705/line_item_service/target_custom_criteria.py @@ -18,7 +18,8 @@ To determine which line items exist, run get_all_line_items.py. To determine which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py.""" +get_all_custom_targeting_keys_and_values.py. +""" import pprint @@ -39,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201608/line_item_service/update_line_items.py b/examples/dfp/v201705/line_item_service/update_line_items.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/line_item_service/update_line_items.py rename to examples/dfp/v201705/line_item_service/update_line_items.py index 56b2dbd1..9f819ec7 --- a/examples/dfp/v201608/line_item_service/update_line_items.py +++ b/examples/dfp/v201705/line_item_service/update_line_items.py @@ -16,7 +16,8 @@ """This code example updates the delivery rate of all line items in an order. -To determine which line items exist, run get_all_line_items.py.""" +To determine which line items exist, run get_all_line_items.py. +""" # Import appropriate modules from the client library. @@ -28,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201705/native_style_service/__init__.py b/examples/dfp/v201705/native_style_service/__init__.py new file mode 100644 index 00000000..473ddba1 --- /dev/null +++ b/examples/dfp/v201705/native_style_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. diff --git a/examples/dfp/v201705/native_style_service/create_native_styles.py b/examples/dfp/v201705/native_style_service/create_native_styles.py new file mode 100644 index 00000000..65005e99 --- /dev/null +++ b/examples/dfp/v201705/native_style_service/create_native_styles.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Creates a native app install ad.""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +# This is the creative template ID for the system-defined native app install ad +# format, which we will create the native style from. Use +# CreativeTemplateService.getCreativeTemplateByStatement() and +# CreativeTemplate.isNativeEligible() to get other native ad formats available +# in your network. +CREATIVE_TEMPLATE_ID = 10004400 +WIDTH = 300 +HEIGHT = 345 + +HTML_SNIPPET = """
+ +
Ad
+
+ + + +
+
+ +
+
+ [%Body%] +
+
[%Price%]
+ +
+""" + +CSS_SNIPPET = """body { + background-color: rgba(255, 255, 255, 1); + font-family: "Roboto-Regular", sans-serif; + font-weight: normal; + font-size: 12px; + line-height: 14px; +} +.attribution { + background-color: rgba(236, 182, 0, 1); + color: rgba(255, 255, 255, 1); + font-size: 13px; + display: table; + margin: 4px 8px; + padding: 0 3px; + border-radius: 2px; +} +.image { + text-align: center; + margin: 8px; +} +.image img, +.image-link { + width: 100%; +} +.app-icon { + float: left; + margin: 0 8px 4px 8px; + height: 40px; + width: 40px; + background-color: transparent; +} +.app-icon img { + height: 100%; + width: 100%; + border-radius: 20%; +} +.title, +.promo-headline { + font-weight: bold; + font-size: 14px; + line-height: 20px; + margin: 8px 8px 4px 8px; +} +.title a, +.promo-headline { + color: rgba(112, 112, 112, 1); + text-decoration: none; +} +.reviews { + float: left; +} +.reviews svg { + fill: rgba(0, 0, 0, 0.7); +} +.body { + clear: left; + margin: 8px; +} +.body a { + color: rgba(110, 110, 110, 1); + text-decoration: none; +} +.price { + display: none; +} +.button { + font-size: 14px; + font-weight: bold; + float: right; + margin: 0px 16px 16px 0px; + white-space: nowrap; +} +.button a { + color: #2196F3; + text-decoration: none; +} +.button svg { + display: none; +} +""" + + +def main(client, html_snippet, css_snippet, creative_template_id, width, + height): + # Initialize appropriate service. + native_style_service = client.GetService('NativeStyleService', + version='v201705') + + native_style = { + 'name': 'Native style #%d' % uuid.uuid4(), + 'htmlSnippet': html_snippet, + 'cssSnippet': css_snippet, + 'creativeTemplateId': creative_template_id, + 'size': { + 'width': width, + 'height': height, + 'isAspectRatio': False + } + } + + # Create the native style on the server. + native_styles = native_style_service.createNativeStyles([native_style]) + + # Display results. + for native_style in native_styles: + print ('A Native style with ID "%s", name "%s", and creative template ID' + '"%d" was created.' % (native_style['id'], native_style['name'], + native_style['creativeTemplateId'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, WIDTH, + HEIGHT) diff --git a/examples/dfp/v201705/native_style_service/get_all_native_styles.py b/examples/dfp/v201705/native_style_service/get_all_native_styles.py new file mode 100644 index 00000000..915d5624 --- /dev/null +++ b/examples/dfp/v201705/native_style_service/get_all_native_styles.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 native styles.""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + native_style_service = client.GetService('NativeStyleService', + version='v201705') + + # Create a statement to select native styles. + statement = dfp.FilterStatement() + + # Retrieve a small amount of native styles at a time, paging + # through until all native styles have been retrieved. + while True: + response = native_style_service.getNativeStylesByStatement( + statement.ToStatement()) + if 'results' in response: + for native_style in response['results']: + # Print out some information for each native style. + print('Native style with ID "%d" and name "%s" was found.\n' % + (native_style['id'], native_style['name'])) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/network_service/__init__.py b/examples/dfp/v201705/network_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/network_service/__init__.py rename to examples/dfp/v201705/network_service/__init__.py diff --git a/examples/dfp/v201608/network_service/get_all_networks.py b/examples/dfp/v201705/network_service/get_all_networks.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/network_service/get_all_networks.py rename to examples/dfp/v201705/network_service/get_all_networks.py index cdd3141d..31eb685d --- a/examples/dfp/v201608/network_service/get_all_networks.py +++ b/examples/dfp/v201705/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201608') + network_service = client.GetService('NetworkService', version='v201705') networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201608/network_service/make_test_network.py b/examples/dfp/v201705/network_service/make_test_network.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/network_service/make_test_network.py rename to examples/dfp/v201705/network_service/make_test_network.py index 2dcf80ab..850e411c --- a/examples/dfp/v201608/network_service/make_test_network.py +++ b/examples/dfp/v201705/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201608') + network_service = client.GetService('NetworkService', version='v201705') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/dfp/v201608/order_service/__init__.py b/examples/dfp/v201705/order_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/order_service/__init__.py rename to examples/dfp/v201705/order_service/__init__.py diff --git a/examples/dfp/v201608/order_service/approve_orders.py b/examples/dfp/v201705/order_service/approve_orders.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/order_service/approve_orders.py rename to examples/dfp/v201705/order_service/approve_orders.py index 717ed821..d1bfee2b --- a/examples/dfp/v201608/order_service/approve_orders.py +++ b/examples/dfp/v201705/order_service/approve_orders.py @@ -16,7 +16,8 @@ """This code example approves all eligible draft and pending orders. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" import datetime @@ -27,7 +28,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201608') + order_service = client.GetService('OrderService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/order_service/create_orders.py b/examples/dfp/v201705/order_service/create_orders.py old mode 100755 new mode 100644 similarity index 94% rename from examples/dfp/v201608/order_service/create_orders.py rename to examples/dfp/v201705/order_service/create_orders.py index 328dc96c..d911d238 --- a/examples/dfp/v201608/order_service/create_orders.py +++ b/examples/dfp/v201705/order_service/create_orders.py @@ -16,7 +16,8 @@ """This code example creates new orders. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" import uuid @@ -31,11 +32,11 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201608') + order_service = client.GetService('OrderService', version='v201705') # Create order objects. orders = [] - for i in xrange(5): + for _ in xrange(5): order = { 'name': 'Order #%s' % uuid.uuid4(), 'advertiserId': company_id, diff --git a/examples/dfp/v201608/order_service/get_all_orders.py b/examples/dfp/v201705/order_service/get_all_orders.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/order_service/get_all_orders.py rename to examples/dfp/v201705/order_service/get_all_orders.py index cda0e5b5..cc192e1c --- a/examples/dfp/v201608/order_service/get_all_orders.py +++ b/examples/dfp/v201705/order_service/get_all_orders.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201608') + order_service = client.GetService('OrderService', version='v201705') # Create a statement to select orders. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/order_service/get_orders_starting_soon.py b/examples/dfp/v201705/order_service/get_orders_starting_soon.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/order_service/get_orders_starting_soon.py rename to examples/dfp/v201705/order_service/get_orders_starting_soon.py index 5a7e4dce..2083de56 --- a/examples/dfp/v201608/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201705/order_service/get_orders_starting_soon.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201608') + order_service = client.GetService('OrderService', version='v201705') query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' '<= :soon') values = [ diff --git a/examples/dfp/v201608/order_service/update_orders.py b/examples/dfp/v201705/order_service/update_orders.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/order_service/update_orders.py rename to examples/dfp/v201705/order_service/update_orders.py index 97877b93..04d2f339 --- a/examples/dfp/v201608/order_service/update_orders.py +++ b/examples/dfp/v201705/order_service/update_orders.py @@ -16,7 +16,8 @@ """This code example updates the notes of a single order specified by ID. -To determine which orders exist, run get_all_orders.py.""" +To determine which orders exist, run get_all_orders.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201608') + order_service = client.GetService('OrderService', version='v201705') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201705/package_service/create_packages.py b/examples/dfp/v201705/package_service/create_packages.py new file mode 100755 index 00000000..2b786612 --- /dev/null +++ b/examples/dfp/v201705/package_service/create_packages.py @@ -0,0 +1,61 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a package. + +To determine which packages exist, run get_all_packages.py. +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the ID of the product package to create the package from. +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + +# Set the ID of the proposal to create proposal line items under. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the rate card the proposal line items belonging to the product +# package are priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client): + # Initialize appropriate service. + package_service = client.GetService('PackageService', version='v201705') + + # Create local package. + package = { + 'name': 'Package #%d' % random.randint(0, 1000000), + 'proposalId': PROPOSAL_ID, + 'productPackageId': PRODUCT_PACKAGE_ID, + 'rateCardId': RATE_CARD_ID, + } + + # Create the package on the server. + result = package_service.createPackages([package]) + + for new_package in result: + print ('A package with ID %d and name \'%s\' was created' % + (new_package['id'], new_package['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py new file mode 100755 index 00000000..c2d9c41d --- /dev/null +++ b/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py @@ -0,0 +1,68 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a copy of an image creative. + +To determine which image creatives exist, run get_image_creatives.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + package_service = client.GetService('PackageService', version='v201705') + + # Create a statement to select the single package. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', PACKAGE_ID)) + + # Get the package. + query_result = package_service.getPackagesByStatement(statement.ToStatement()) + + package = query_result['results'][0] + + print ('Package with ID %d will create proposal line items using product ' + 'package with ID %d.' % (package['id'], + package['productPackageId'])) + + # Remove limit and offset from statement. + statement.limit = None + statement.offset = None + + # Perform update packages action. + result = package_service.performPackageAction( + {'xsi_type': 'CreateProposalLineItemsFromPackages'}, + statement.ToStatement()) + + if result and result['numChanges'] > 0: + print ('Number of packages that proposal line items were created for: %d' % + result['numChanges']) + else: + print 'No proposal line items were created.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/package_service/get_all_packages.py b/examples/dfp/v201705/package_service/get_all_packages.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/package_service/get_all_packages.py rename to examples/dfp/v201705/package_service/get_all_packages.py index 06e9028b..809a8f24 --- a/examples/dfp/v201608/package_service/get_all_packages.py +++ b/examples/dfp/v201705/package_service/get_all_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201608') + pkg_service = client.GetService('PackageService', version='v201705') # Create a statement to select packages. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/package_service/get_in_progress_packages.py b/examples/dfp/v201705/package_service/get_in_progress_packages.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/package_service/get_in_progress_packages.py rename to examples/dfp/v201705/package_service/get_in_progress_packages.py index 63eb3236..a22049a9 --- a/examples/dfp/v201608/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201705/package_service/get_in_progress_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201608') + pkg_service = client.GetService('PackageService', version='v201705') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201608/placement_service/create_placements.py b/examples/dfp/v201705/placement_service/create_placements.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/placement_service/create_placements.py rename to examples/dfp/v201705/placement_service/create_placements.py index 5fa3b8f4..2f37f07e --- a/examples/dfp/v201608/placement_service/create_placements.py +++ b/examples/dfp/v201705/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201608') - inventory_service = client.GetService('InventoryService', version='v201608') + placement_service = client.GetService('PlacementService', version='v201705') + inventory_service = client.GetService('InventoryService', version='v201705') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201608/placement_service/deactivate_placements.py b/examples/dfp/v201705/placement_service/deactivate_placements.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/placement_service/deactivate_placements.py rename to examples/dfp/v201705/placement_service/deactivate_placements.py index 2692beb4..1c42338d --- a/examples/dfp/v201608/placement_service/deactivate_placements.py +++ b/examples/dfp/v201705/placement_service/deactivate_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201608') + placement_service = client.GetService('PlacementService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/placement_service/get_active_placements.py b/examples/dfp/v201705/placement_service/get_active_placements.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/placement_service/get_active_placements.py rename to examples/dfp/v201705/placement_service/get_active_placements.py index b08873e5..3d2b4511 --- a/examples/dfp/v201608/placement_service/get_active_placements.py +++ b/examples/dfp/v201705/placement_service/get_active_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201608') + placement_service = client.GetService('PlacementService', version='v201705') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201608/placement_service/get_all_placements.py b/examples/dfp/v201705/placement_service/get_all_placements.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/placement_service/get_all_placements.py rename to examples/dfp/v201705/placement_service/get_all_placements.py index 71ac94b8..5acce24b --- a/examples/dfp/v201608/placement_service/get_all_placements.py +++ b/examples/dfp/v201705/placement_service/get_all_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201608') + placement_service = client.GetService('PlacementService', version='v201705') # Create a statement to select placements. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/placement_service/update_placements.py b/examples/dfp/v201705/placement_service/update_placements.py old mode 100755 new mode 100644 similarity index 56% rename from examples/dfp/v201608/placement_service/update_placements.py rename to examples/dfp/v201705/placement_service/update_placements.py index 08dccfab..64f37c19 --- a/examples/dfp/v201608/placement_service/update_placements.py +++ b/examples/dfp/v201705/placement_service/update_placements.py @@ -28,37 +28,29 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201608') -# Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + placement_service = client.GetService('PlacementService', version='v201705') + + # Create query. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', PLACEMENT_ID)) # Get placements by statement. - placements = placement_service.getPlacementsByStatement( + page = placement_service.getPlacementsByStatement( statement.ToStatement()) - for placement in placements: - if not placement['targetingDescription']: - placement['targetingDescription'] = 'Generic description' - placement['targetingAdLocation'] = 'All images on sports pages.' - placement['targetingSiteName'] = 'http://code.google.com' - placement['isAdSenseTargetingEnabled'] = 'true' + placement = page['results'][0] + + placement['description'] = 'This placement contains all leaderboards.' # Update placements remotely. - placements = placement_service.updatePlacements(placements) + updated_placements = placement_service.updatePlacements([placement]) - for placement in placements: - print ('Placement with id \'%s\', name \'%s\', and AdSense targeting ' - 'enabled \'%s\' was updated.' - % (placement['id'], placement['name'], - placement['isAdSenseTargetingEnabled'])) + for placement in updated_placements: + print ("Placement with id \'%s\' and name '%s' was updated." + % (placement['id'], placement['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201608/premium_rate_service/__init__.py b/examples/dfp/v201705/premium_rate_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/premium_rate_service/__init__.py rename to examples/dfp/v201705/premium_rate_service/__init__.py diff --git a/examples/dfp/v201608/premium_rate_service/create_premium_rates.py b/examples/dfp/v201705/premium_rate_service/create_premium_rates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201705/premium_rate_service/create_premium_rates.py index be1ce13b..5d0dc4f7 --- a/examples/dfp/v201608/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201705/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201608') + version='v201705') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py index 5681a90a..a8803339 --- a/examples/dfp/v201608/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201608') + 'PremiumRateService', version='v201705') # Create a statement to select premium rates. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py index 77d438e9..b374c9cf --- a/examples/dfp/v201608/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,7 +25,7 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201608') + 'PremiumRateService', version='v201705') query = 'WHERE rateCardId = :rateCardId' values = [ {'key': 'rateCardId', diff --git a/examples/dfp/v201608/premium_rate_service/update_premium_rates.py b/examples/dfp/v201705/premium_rate_service/update_premium_rates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201705/premium_rate_service/update_premium_rates.py index 4c622a15..7bc56a29 --- a/examples/dfp/v201608/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201705/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201608') + version='v201705') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201705/product_package_item_service/create_product_package_item.py b/examples/dfp/v201705/product_package_item_service/create_product_package_item.py new file mode 100755 index 00000000..fdb25318 --- /dev/null +++ b/examples/dfp/v201705/product_package_item_service/create_product_package_item.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a product package item. + +To determine which product package items exist, run +get_all_product_package_items.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the product package to add product package items to. +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + +# Set the ID of the product to generate a product package item from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client): + product_package_item_service = client.GetService('ProductPackageItemService', + version='v201705') + + product_package_item = { + # Set the product from which the product package item is created. + 'productId': PRODUCT_ID, + # Set the product package that the product package item belongs to. + 'productPackageId': PRODUCT_PACKAGE_ID, + # Specify if the product package item is required for this + # product package. + 'isMandatory': True + } + + # Create the product package item on the server. + result = product_package_item_service.createProductPackageItems( + [product_package_item]) + + for new_product_package_item in result: + print ('A product package with ID %d created from product ID %d ' + 'belonging to product package with ID %d was created.' % + (new_product_package_item['id'], + new_product_package_item['productId'], + new_product_package_item['productPackageId'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py rename to examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py index b21d7dbb..274d0d56 --- a/examples/dfp/v201608/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201608') + 'ProductPackageItemService', version='v201705') # Create a statement to select product package items. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py index 0cff0fa3..dfabfe6f --- a/examples/dfp/v201608/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,7 +25,7 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201608') + 'ProductPackageItemService', version='v201705') query = 'WHERE productPackageId = :productPackageId' values = [ {'key': 'productPackageId', diff --git a/examples/dfp/v201705/product_package_service/create_product_packages.py b/examples/dfp/v201705/product_package_service/create_product_packages.py new file mode 100755 index 00000000..3d69c3b6 --- /dev/null +++ b/examples/dfp/v201705/product_package_service/create_product_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a product package. + +To determine which product packages exist, run get_all_product_packages.py +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the ID of the rate card to associate with the product package. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client): + product_package_service = client.GetService('ProductPackageService', + version='v201705') + + # Create a local product package. + product_package = { + 'name': 'Product Package #%d' % random.randint(0, 100000000), + 'rateCardIds': [RATE_CARD_ID] + } + + result = product_package_service.createProductPackages([product_package]) + + for new_product_package in result: + print ('A product package with ID %d and name \'%s\' was created.' % + (new_product_package['id'], new_product_package['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/product_package_service/get_active_product_packages.py b/examples/dfp/v201705/product_package_service/get_active_product_packages.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/product_package_service/get_active_product_packages.py rename to examples/dfp/v201705/product_package_service/get_active_product_packages.py index 2bcc5003..a08b4733 --- a/examples/dfp/v201608/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201705/product_package_service/get_active_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201608') + 'ProductPackageService', version='v201705') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201608/product_package_service/get_all_product_packages.py b/examples/dfp/v201705/product_package_service/get_all_product_packages.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/product_package_service/get_all_product_packages.py rename to examples/dfp/v201705/product_package_service/get_all_product_packages.py index f58ebd2e..b8e1910e --- a/examples/dfp/v201608/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201705/product_package_service/get_all_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201608') + 'ProductPackageService', version='v201705') # Create a statement to select product packages. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/product_service/__init__.py b/examples/dfp/v201705/product_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/product_service/__init__.py rename to examples/dfp/v201705/product_service/__init__.py diff --git a/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py rename to examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py index 775fa153..a93d2d7f --- a/examples/dfp/v201608/product_service/create_programmatic_products_for_non_sales_management.py +++ b/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py @@ -24,8 +24,8 @@ def main(client): - product_service = client.GetService('ProductService', version='v201608') - network_service = client.GetService('NetworkService', version='v201608') + product_service = client.GetService('ProductService', version='v201705') + network_service = client.GetService('NetworkService', version='v201705') product = { # Setting required Marketplace Information. diff --git a/examples/dfp/v201608/product_service/get_all_products.py b/examples/dfp/v201705/product_service/get_all_products.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/product_service/get_all_products.py rename to examples/dfp/v201705/product_service/get_all_products.py index 4895956f..51ff246e --- a/examples/dfp/v201608/product_service/get_all_products.py +++ b/examples/dfp/v201705/product_service/get_all_products.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201608') + product_service = client.GetService('ProductService', version='v201705') # Create a statement to select products. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/product_service/get_products_for_product_template.py b/examples/dfp/v201705/product_service/get_products_for_product_template.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/product_service/get_products_for_product_template.py rename to examples/dfp/v201705/product_service/get_products_for_product_template.py index 7f1d5bef..94d11ad7 --- a/examples/dfp/v201608/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201705/product_service/get_products_for_product_template.py @@ -24,7 +24,7 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201608') + product_service = client.GetService('ProductService', version='v201705') query = 'WHERE productTemplateId = :productTemplateId' values = [ diff --git a/examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py rename to examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py index 9ca606ac..843ab498 --- a/examples/dfp/v201608/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py @@ -27,7 +27,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201608') + product_service = client.GetService('ProductService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/product_service/update_products.py b/examples/dfp/v201705/product_service/update_products.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/product_service/update_products.py rename to examples/dfp/v201705/product_service/update_products.py index 5c217d8e..28ce433b --- a/examples/dfp/v201608/product_service/update_products.py +++ b/examples/dfp/v201705/product_service/update_products.py @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201608') + product_service = client.GetService('ProductService', version='v201705') # Create statement object to select a single product by an ID. values = [{ diff --git a/examples/dfp/v201608/product_template_service/__init__.py b/examples/dfp/v201705/product_template_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/product_template_service/__init__.py rename to examples/dfp/v201705/product_template_service/__init__.py diff --git a/examples/dfp/v201608/product_template_service/activate_product_templates.py b/examples/dfp/v201705/product_template_service/activate_product_templates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/product_template_service/activate_product_templates.py rename to examples/dfp/v201705/product_template_service/activate_product_templates.py index cf41d3d9..6914a56f --- a/examples/dfp/v201608/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201705/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201608') + 'ProductTemplateService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/product_template_service/create_product_templates.py b/examples/dfp/v201705/product_template_service/create_product_templates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/product_template_service/create_product_templates.py rename to examples/dfp/v201705/product_template_service/create_product_templates.py index 929a563c..a12ae992 --- a/examples/dfp/v201608/product_template_service/create_product_templates.py +++ b/examples/dfp/v201705/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201608') + 'ProductTemplateService', version='v201705') network_service = client.GetService( - 'NetworkService', version='v201608') + 'NetworkService', version='v201705') # Create a product template. product_template = { diff --git a/examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py rename to examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py index 4d9d9b9a..60ec4793 --- a/examples/dfp/v201608/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201608') + 'ProductTemplateService', version='v201705') network_service = client.GetService( - 'NetworkService', version='v201608') + 'NetworkService', version='v201705') product_template = { # Setting required Marketplace information. diff --git a/examples/dfp/v201608/product_template_service/get_all_product_templates.py b/examples/dfp/v201705/product_template_service/get_all_product_templates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/product_template_service/get_all_product_templates.py rename to examples/dfp/v201705/product_template_service/get_all_product_templates.py index df1394a7..d9469444 --- a/examples/dfp/v201608/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201705/product_template_service/get_all_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201608') + 'ProductTemplateService', version='v201705') # Create a statement to select product templates. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py index 6c318ef4..a5108bf0 --- a/examples/dfp/v201608/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201608') + 'ProductTemplateService', version='v201705') query = 'WHERE lineItemType = :lineItemType' values = [ {'key': 'lineItemType', diff --git a/examples/dfp/v201608/product_template_service/update_product_templates.py b/examples/dfp/v201705/product_template_service/update_product_templates.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/product_template_service/update_product_templates.py rename to examples/dfp/v201705/product_template_service/update_product_templates.py index eca3fd52..77b5f174 --- a/examples/dfp/v201608/product_template_service/update_product_templates.py +++ b/examples/dfp/v201705/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201608') + 'ProductTemplateService', version='v201705') # Create a statement to select a single product template by ID. values = [{ diff --git a/examples/dfp/v201608/proposal_line_item_service/__init__.py b/examples/dfp/v201705/proposal_line_item_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/proposal_line_item_service/__init__.py rename to examples/dfp/v201705/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py index 0fa549ce..b025e997 --- a/examples/dfp/v201608/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201608') + 'ProposalLineItemService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py old mode 100755 new mode 100644 similarity index 82% rename from examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py index c52f90a9..662dbb09 --- a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -18,11 +18,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set the ID of the programmatic proposal that the proposal line item will # belong to. @@ -39,13 +40,16 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201608') - network_service = client.GetService('NetworkService', version='v201608') + 'ProposalLineItemService', version='v201705') + network_service = client.GetService('NetworkService', version='v201705') # Get the root ad unit to target. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + # Create a single programmatic proposal line item. proposal_line_item = { # Setting required Marketplace information. @@ -64,27 +68,8 @@ def main(client, proposal_id, product_id, rate_card_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'goal': { 'units': '1000', 'unitType': 'IMPRESSIONS', diff --git a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py old mode 100755 new mode 100644 similarity index 82% rename from examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 9dfad61b..461f4b7a --- a/examples/dfp/v201608/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -18,11 +18,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -33,8 +34,11 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201608') - network_service = client.GetService('NetworkService', version='v201608') + 'ProposalLineItemService', version='v201705') + network_service = client.GetService('NetworkService', version='v201705') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) # Get the root ad unit to target. root_ad_unit_id = ( @@ -58,27 +62,8 @@ def main(client, proposal_id, product_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'creativePlaceholders': [{ 'size': { 'width': '300', diff --git a/examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py old mode 100755 new mode 100644 similarity index 82% rename from examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py index 29521952..3dc6440c --- a/examples/dfp/v201608/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py @@ -22,11 +22,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -41,8 +42,11 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201608') - network_service = client.GetService('NetworkService', version='v201608') + 'ProposalLineItemService', version='v201705') + network_service = client.GetService('NetworkService', version='v201705') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) # Get the root ad unit to target. root_ad_unit_id = ( @@ -61,27 +65,8 @@ def main(client, proposal_id, product_id, rate_card_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'deliveryRateType': 'EVENLY', 'creativeRotationType': 'OPTIMIZED', 'billingCap': 'CAPPED_CUMULATIVE', diff --git a/examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py index 37ae497b..4b0a2fb6 --- a/examples/dfp/v201608/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201608') + 'ProposalLineItemService', version='v201705') # Create a statement to select proposal line items. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py index a52804ca..3600e25d --- a/examples/dfp/v201608/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,7 +25,7 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201608') + 'ProposalLineItemService', version='v201705') query = 'WHERE proposalId = :proposalId' values = [ {'key': 'proposalId', diff --git a/examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py index 4299d7f4..0139cffe --- a/examples/dfp/v201608/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201608') + 'ProposalLineItemService', version='v201705') # Create statement to select a proposal line item. values = [{ diff --git a/examples/dfp/v201608/proposal_service/__init__.py b/examples/dfp/v201705/proposal_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/proposal_service/__init__.py rename to examples/dfp/v201705/proposal_service/__init__.py diff --git a/examples/dfp/v201608/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/proposal_service/create_programmatic_proposals.py rename to examples/dfp/v201705/proposal_service/create_programmatic_proposals.py index 04266ff5..dfe5a683 --- a/examples/dfp/v201608/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201608') - network_service = client.GetService('NetworkService', version='v201608') + proposal_service = client.GetService('ProposalService', version='v201705') + network_service = client.GetService('NetworkService', version='v201705') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py index b9aca741..017a24d4 --- a/examples/dfp/v201608/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201608') + proposal_service = client.GetService('ProposalService', version='v201705') proposal = { # Setting required Marketplace information. @@ -47,7 +47,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, 'probabilityOfClose': '100000', } - proposals = proposal_service.createProposals([proposals]) + proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: diff --git a/examples/dfp/v201608/proposal_service/create_proposals.py b/examples/dfp/v201705/proposal_service/create_proposals.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/proposal_service/create_proposals.py rename to examples/dfp/v201705/proposal_service/create_proposals.py index 14ae2c1c..26c261a5 --- a/examples/dfp/v201608/proposal_service/create_proposals.py +++ b/examples/dfp/v201705/proposal_service/create_proposals.py @@ -16,7 +16,8 @@ """This code example creates new proposals. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" import uuid @@ -33,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201608') - network_service = client.GetService('NetworkService', version='v201608') + proposal_service = client.GetService('ProposalService', version='v201705') + network_service = client.GetService('NetworkService', version='v201705') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201608/proposal_service/get_all_proposals.py b/examples/dfp/v201705/proposal_service/get_all_proposals.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/proposal_service/get_all_proposals.py rename to examples/dfp/v201705/proposal_service/get_all_proposals.py index 96987d15..bc68a5ef --- a/examples/dfp/v201608/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201705/proposal_service/get_all_proposals.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201608') + proposal_service = client.GetService('ProposalService', version='v201705') # Create a statement to select proposals. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/proposal_service/get_marketplace_comments.py b/examples/dfp/v201705/proposal_service/get_marketplace_comments.py old mode 100755 new mode 100644 similarity index 55% rename from examples/dfp/v201608/proposal_service/get_marketplace_comments.py rename to examples/dfp/v201705/proposal_service/get_marketplace_comments.py index ded14548..56839ca9 --- a/examples/dfp/v201608/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201705/proposal_service/get_marketplace_comments.py @@ -14,46 +14,38 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets the Marketplace comments for a programmatic proposal. -""" +"""This example gets the Marketplace comments for a programmatic proposal.""" # Import appropriate modules from the client library. from datetime import datetime from googleads import dfp + PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201608') + 'ProposalService', version='v201705') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} - # Retrieve a small amount of marketplace comments at a time, paging - # through until all marketplace comments have been retrieved. - while True: - response = marketplace_comment_service.getMarketplaceCommentsByStatement( - statement) - if 'results' in response: - for marketplace_comment in response['results']: - # Print out some information for each marketplace comment. - date_time = marketplace_comment['creationTime'] - date_time_string = datetime(date_time['date']['year'], - date_time['date']['month'], - date_time['date']['day'], date_time['hour'], - date_time['minute'], - date_time['second']).isoformat() - - print( - 'Marketplace comment with creation time "%s"and comment "%s" was ' - 'found.\n' - % (date_time_string, marketplace_comment['comment'])) - else: - break + response = marketplace_comment_service.getMarketplaceCommentsByStatement( + statement) + + # Print out some information for each marketplace comment. + for marketplace_comment in response['results']: + date_time = marketplace_comment['creationTime'] + date_time_string = datetime(date_time['date']['year'], + date_time['date']['month'], + date_time['date']['day'], date_time['hour'], + date_time['minute'], + date_time['second']).isoformat() + print('Marketplace comment with creation time "%s"and comment "%s" was ' + 'found.\n' % (date_time_string, marketplace_comment['comment'])) print '\nNumber of results found: %s' % response['totalResultSetSize'] diff --git a/examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py rename to examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py index 5e70b964..0da9e017 --- a/examples/dfp/v201608/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201608') + proposal_service = client.GetService('ProposalService', version='v201705') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201608/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/proposal_service/request_buyers_acceptance.py rename to examples/dfp/v201705/proposal_service/request_buyers_acceptance.py index b8d8dc0e..577e69d1 --- a/examples/dfp/v201608/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py @@ -26,7 +26,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201608') + proposal_service = client.GetService('ProposalService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py index d305bb24..4a8b98b4 --- a/examples/dfp/v201608/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py @@ -16,7 +16,8 @@ """This code example approves a single proposal. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" # Import appropriate modules from the client library. @@ -24,9 +25,10 @@ PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201608') + proposal_service = client.GetService('ProposalService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/proposal_service/update_proposals.py b/examples/dfp/v201705/proposal_service/update_proposals.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/proposal_service/update_proposals.py rename to examples/dfp/v201705/proposal_service/update_proposals.py index af7d29c8..b0d0dab6 --- a/examples/dfp/v201608/proposal_service/update_proposals.py +++ b/examples/dfp/v201705/proposal_service/update_proposals.py @@ -16,7 +16,8 @@ """This code example updates the notes of a single proposal specified by ID. -To determine which proposals exist, run get_all_proposals.py.""" +To determine which proposals exist, run get_all_proposals.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201608') + proposal_service = client.GetService('ProposalService', version='v201705') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201608/publisher_query_language_service/__init__.py b/examples/dfp/v201705/publisher_query_language_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/publisher_query_language_service/__init__.py rename to examples/dfp/v201705/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py old mode 100755 new mode 100644 similarity index 90% rename from examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py index fe6ca7f1..f6b3d558 --- a/examples/dfp/v201608/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201608') + report_downloader = client.GetDataDownloader(version='v201705') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) @@ -45,8 +45,8 @@ def main(client): line_items_file.close() ad_units_file.close() - print ('Saved line items to... %s' % line_items_file.name) - print ('Saved ad units to... %s' % ad_units_file.name) + print 'Saved line items to... %s' % line_items_file.name + print 'Saved ad units to... %s' % ad_units_file.name if __name__ == '__main__': diff --git a/examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py old mode 100755 new mode 100644 similarity index 91% rename from examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py index 8dfb20cb..cdda977e --- a/examples/dfp/v201608/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201608') + data_downloader = client.GetDataDownloader(version='v201705') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) @@ -40,7 +40,7 @@ def main(client): programmatic_buyers_file.close() - print ('Saved programmatic buyers to... %s' % programmatic_buyers_file.name) + print 'Saved programmatic buyers to... %s' % programmatic_buyers_file.name if __name__ == '__main__': diff --git a/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py new file mode 100644 index 00000000..70c30b66 --- /dev/null +++ b/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Gets recent changes in your network using the Change_History table. + +A full list of available tables can be found at: +https://developers.google.com/doubleclick-publishers/docs/reference/latest/PublisherQueryLanguageService +""" + +from datetime import date +from datetime import datetime +from datetime import timedelta + +# Import appropriate modules from the client library. +from googleads import dfp +import pytz + + +def main(client): + # Initialize appropriate service. + pql_service = client.GetService('PublisherQueryLanguageService', 'v201705') + + end_date = date.today() + start_date = end_date - timedelta(days=1) + initial_query = ( + 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' + 'FROM Change_History ' + 'WHERE ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime ' + 'ORDER BY ChangeDateTime DESC') + pagination_query = ( + 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' + 'FROM Change_History ' + 'WHERE Id < :id ' + 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' + 'ORDER BY ChangeDateTime DESC') + values = [ + { + 'key': 'startDateTime', + 'value': { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': start_date.year, + 'month': start_date.month, + 'day': start_date.day + } + } + } + }, + { + 'key': 'endDateTime', + 'value': { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': end_date.year, + 'month': end_date.month, + 'day': end_date.day + } + } + } + } + ] + + statement = dfp.FilterStatement(initial_query, values) + keep_iterating = True + i = 0 + total_rows = [] + + while keep_iterating: + response = pql_service.select(statement.ToStatement()) + column_types = ([column_type['labelName'] + for column_type in response['columnTypes']]) + rows = response['rows'] + rows_length = len(rows) + total_rows.extend(rows) + + if rows and rows_length > 0: + # Get the earliest change ID in the result set. + last_row = rows[-1] + last_id = last_row['values'][0]['value'] + i += 1 + statement = UpdateFilterStatement( + statement, pagination_query, values, last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' + % (i, rows_length, last_id)) + + keep_iterating = rows and len(rows) == statement.limit + + # Print out columns header + print ','.join(column_types) + + # Print out every row + for row in total_rows: + print ConvertValueForCsv(row) + + +def UpdateFilterStatement(statement, query, values, last_id): + """Updates the FilterStatement in order to page through results. + + Args: + statement: an instantiated FilterStatement. + query: a str query that will be used to update the FilterStatement. + values: a list of bind variables to be updated. + last_id: a str representing the earliest change ID in a result set. + + Returns: + FilterStatement the updated statement. + """ + # Use the earliest change ID in the result set to page. + updated_values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'TextValue', + 'value': last_id + } + }] + updated_values.extend(values) + + statement.where_clause = query + statement.values = updated_values + + return statement + + +def ConvertValueForCsv(pql_value): + """Sanitizes a field value from a Value object to a CSV suitable format. + + Args: + pql_value: dict a dictionary containing the data for a single field of an + entity. + + Returns: + str a CSV writer friendly value formatted by Value.Type. + """ + if 'value' in pql_value: + field = pql_value['value'] + elif 'values' in pql_value: + field = pql_value['values'] + else: + field = None + + if field: + if isinstance(field, list): + return ','.join(['"%s"' % str(ConvertValueForCsv(single_field)) + for single_field in field]) + else: + class_type = dfp.DfpClassType(pql_value) + + if class_type == 'TextValue': + return field.replace('"', '""').encode('UTF8') + elif class_type == 'NumberValue': + return float(field) if '.' in field else int(field) + elif class_type == 'DateTimeValue': + return ConvertDateTimeToOffset(field) + elif class_type == 'DateValue': + return date(int(field['date']['year']), + int(field['date']['month']), + int(field['date']['day'])).isoformat() + else: + return field + else: + return '-' + + +def ConvertDateTimeToOffset(date_time_value): + """Converts the PQL formatted response for a dateTime object. + + Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.' + + Args: + date_time_value: dict The date time value from the PQL response. + + Returns: + str: A string representation of the date time value uniform to + ReportService. + """ + date_time_obj = datetime(int(date_time_value['date']['year']), + int(date_time_value['date']['month']), + int(date_time_value['date']['day']), + int(date_time_value['hour']), + int(date_time_value['minute']), + int(date_time_value['second'])) + date_time_str = pytz.timezone( + date_time_value['timeZoneID']).localize(date_time_obj).isoformat() + + if date_time_str[-5:] == '00:00': + return date_time_str[:-6] + 'Z' + else: + return date_time_str + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/rate_card_service/__init__.py b/examples/dfp/v201705/rate_card_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/rate_card_service/__init__.py rename to examples/dfp/v201705/rate_card_service/__init__.py diff --git a/examples/dfp/v201705/rate_card_service/create_rate_cards.py b/examples/dfp/v201705/rate_card_service/create_rate_cards.py new file mode 100755 index 00000000..a895a013 --- /dev/null +++ b/examples/dfp/v201705/rate_card_service/create_rate_cards.py @@ -0,0 +1,60 @@ +#!/usr/bin/python +# +# Copyright 2017 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 creates a new rate card. + +To determine which rate cards exist, run get_all_rate_cards.py. +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the IDs of the teams this rate card should be visible to. +TEAM_IDS = ['INSERT_TEAM_ID_HERE'] + +# Set the currency code to create the rate card with. +CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201705') + + # Create a rate card. + rate_card = { + 'name': 'RateCard #%d' % random.randint(0, 100000000), + 'currencyCode': CURRENCY_CODE, + 'pricingModel': 'NET', + } + + # This field is optional. + rate_card['appliedTeamIds'] = TEAM_IDS + + result = rate_card_service.createRateCards([rate_card]) + + for new_rate_card in result: + print ('A rate card with ID %s, name \'%s\', and currency code \'%s\' ' + 'was created.' % (new_rate_card['id'], + new_rate_card['name'], + new_rate_card['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201705/rate_card_service/get_all_rate_cards.py index 0a0dd758..4183924e --- a/examples/dfp/v201608/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201608') + rate_card_service = client.GetService('RateCardService', version='v201705') # Create a statement to select rate cards. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py old mode 100755 new mode 100644 similarity index 99% rename from examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py rename to examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py index a0f6cb73..232f0fd7 --- a/examples/dfp/v201608/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201608') + rate_card_service = client.GetService('RateCardService', version='v201705') query = 'WHERE forMarketplace = :forMarketplace' values = [ {'key': 'forMarketplace', diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py new file mode 100644 index 00000000..31b1337e --- /dev/null +++ b/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 line item reports for a given reconciliation report. + +To determine how many reconciliation reports exist, +run get_all_reconciliation_reports.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation report to query. +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_line_item_report_service = (client.GetService( + 'ReconciliationLineItemReportService', version='v201705')) + + # Create a statement to select reconciliation line item reports. + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reconciliationReportId AND ' + 'lineItemId != :lineItemId')) + .OrderBy('lineItemId', ascending=True) + .WithBindVariable('reconciliationReportId', + RECONCILIATION_REPORT_ID) + .WithBindVariable('lineItemId', 0)) + + # Retrieve a small amount of reconciliation line item reports at a time, + # paging through until all reconciliation line item reports have been + # retrieved. + result_set_size = 0 + should_continue = True + + while should_continue: + page = (reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement( + statement.ToStatement())) + if 'results' in page: + result_set_size += page['totalResultSetSize'] + # Iterate over individual results in the page. + for line_item_report in page['results']: + print ('Reconciliation line item report with ID %d, line item ID %d, ' + 'reconciliation source \'%s\', and reconciled volume %d was ' + 'found.' % (line_item_report['id'], + line_item_report['lineItemId'], + line_item_report['reconciliationSource'], + (line_item_report['reconciledVolume'] + if 'reconciledVolume' in line_item_report else 0))) + # Update statement for next page. + statement.offset += statement.limit + should_continue = statement.offset < result_set_size + + print 'Number of results found: %d' % result_set_size + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py new file mode 100644 index 00000000..f80694cf --- /dev/null +++ b/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 updates a reconciliation line item report. + +To get reconciliation line item reports for a reconciliation report, run +get_reconciliation_line_item_reports_for_reconciliation_report.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation line item report to update. +RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_line_item_report_service = (client.GetService( + 'ReconciliationLineItemReportService', version='v201705')) + + # Create a statement to select a reconciliation line item report. + statement = (dfp.StatementBuilder() + .Where('id = :lineItemReportId') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('lineItemReportId', + RECONCILIATION_LINE_ITEM_REPORT_ID)) + + # Get reconciliation line item reports by statement. + page = (reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement(statement.ToStatement())) + + line_item_report = page['results'][0] + + # Set and use a manual volume for billing. This example splits the difference + # between DFP and the third party volume. + line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + + line_item_report['thirdPartyVolume']) / 2 + line_item_report['reconciliationSource'] = 'MANUAL' + + result = (reconciliation_line_item_report_service + .updateReconciliationLineItemReports([line_item_report])) + + for updated_report in result: + print ('Reconciliation line item report with ID %d for line item ID %d was ' + 'updated, with manual volume %d' % (updated_report['id'], + updated_report['lineItemId'], + updated_report['manualVolume'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py old mode 100755 new mode 100644 similarity index 91% rename from examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index a99a5cfc..e9ce5265 --- a/examples/dfp/v201608/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,7 +25,7 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201608') + 'ReconciliationOrderReportService', version='v201705') query = 'WHERE reconciliationReportId = :reconciliationReportId' values = [ {'key': 'reconciliationReportId', @@ -40,8 +40,10 @@ def main(client, reconciliation_report_id): # Retrieve a small amount of reconciliation order reports at a time, paging # through until all reconciliation order reports have been retrieved. while True: - response = reconciliation_order_report_service.getReconciliationOrderReportsByStatement( - statement.ToStatement()) + response = ( + reconciliation_order_report_service + .getReconciliationOrderReportsByStatement( + statement.ToStatement())) if 'results' in response: for reconciliation_order_report in response['results']: # Print out some information for each reconciliation order report. diff --git a/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py new file mode 100644 index 00000000..f282ce56 --- /dev/null +++ b/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 submits a reconciliation order report. + +To get all reconciliation order reports for a reconciliation report, +run get get_reconciliation_order_reports_for_reconciliation_report.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation order report to submit. +RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_order_report_service = (client.GetService( + 'ReconciliationOrderReportService', version='v201705')) + + # Create a statement to select reconciliation order reports. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', RECONCILIATION_ORDER_REPORT_ID)) + + # Get reconciliation order reports by statement. + page = (reconciliation_order_report_service + .getReconciliationOrderReportsByStatement(statement.ToStatement())) + + report = page['results'][0] + + print ('Reconciliation order report with ID %d will be submitted.' % + report['id']) + + # Remove limit and offset from statement. + statement.limit = None + statement.offset = None + + # Perform action. + result = (reconciliation_order_report_service + .performReconciliationOrderReportAction( + {'xsi_type': 'SubmitReconciliationOrderReports'}, + statement.ToStatement())) + + if result and result['numChanges'] > 0: + print ('Number of reconciliation order reports submitted: %d' % + result['numChanges']) + else: + print 'No reconciliation order reports were submitted.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py old mode 100755 new mode 100644 similarity index 84% rename from examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 38bbd31e..46803c99 --- a/examples/dfp/v201608/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -13,36 +13,40 @@ # 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. + """Gets a reconciliation report's rows for line items that served through DFP. """ # Import appropriate modules from the client library. from googleads import dfp +# Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201608') + 'ReconciliationReportRowService', version='v201705') query = ('WHERE reconciliationReportId = %s AND ' 'lineItemId != :lineItemId') % reconciliation_report_id - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - }}, - ] + values = [{ + 'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + } + }] # Create a statement to select reconciliation report rows. statement = dfp.FilterStatement(query, values) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. while True: - response = reconciliation_report_row_service.getReconciliationReportRowsByStatement( - statement.ToStatement()) + response = ( + reconciliation_report_row_service + .getReconciliationReportRowsByStatement( + statement.ToStatement())) if 'results' in response: for reconciliation_report_row in response['results']: # Print out some information for each reconciliation report row. diff --git a/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py new file mode 100644 index 00000000..38158171 --- /dev/null +++ b/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 updates a reconciliation report row. + +To determine which reconciliation report rows exist, +run get_reconciliation_report_rows_for_reconciliation_report.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation report row. +RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' + +# Set the ID of the reconciliation report. +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_report_row_service = (client.GetService( + 'ReconciliationReportRowService', version='v201705')) + + # Create a statement to select reconciliation report rows. + statement = (dfp.StatementBuilder() + .Where(('id = :reconciliationReportRowId AND ' + 'reconciliationReportId = :reconciliationReportId')) + .OrderBy('id', ascending=True) + .WithBindVariable('reconciliationReportRowId', + RECONCILIATION_REPORT_ROW_ID) + .WithBindVariable('reconciliationReportId', + RECONCILIATION_REPORT_ID)) + + # Get reconciliation report rows by statement. + page = (reconciliation_report_row_service + .getReconciliationReportRowsByStatement(statement.ToStatement())) + + row = page['results'][0] + + # Set a comment on the reconciliation report row. + row['comments'] = ('Third part volume didn\'t match DFP - we agreed to split ' + 'the difference') + + # Set and use a manual volume for billing. + row['manualVolume'] = (row['dfpVolume'] + row['thirdPartyVolume']) / 2 + row['reconciliationSource'] = 'MANUAL' + + updated_rows = (reconciliation_report_row_service + .updateReconciliationReportRows([row])) + + for updated_row in updated_rows: + print ('Reconciliation report row for line item ID %d and creative ID %d ' + 'was updated, with manual volume %d' % (updated_row['lineItemId'], + updated_row['creativeId'], + updated_row['manualVolume'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py old mode 100755 new mode 100644 similarity index 90% rename from examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py index afda42dc..68e6dee5 --- a/examples/dfp/v201608/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201608') + 'ReconciliationReportService', version='v201705') # Create a statement to select reconciliation reports. statement = dfp.FilterStatement() @@ -31,8 +31,10 @@ def main(client): # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. while True: - response = reconciliation_report_service.getReconciliationReportsByStatement( - statement.ToStatement()) + response = ( + reconciliation_report_service + .getReconciliationReportsByStatement( + statement.ToStatement())) if 'results' in response: for reconciliation_report in response['results']: # Print out some information for each reconciliation report. diff --git a/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py old mode 100755 new mode 100644 similarity index 91% rename from examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 315a976e..b7c931b7 --- a/examples/dfp/v201608/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201608') + 'ReconciliationReportService', version='v201705') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) @@ -45,8 +45,10 @@ def main(client): # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. while True: - response = reconciliation_report_service.getReconciliationReportsByStatement( - statement.ToStatement()) + response = ( + reconciliation_report_service + .getReconciliationReportsByStatement( + statement.ToStatement())) if 'results' in response: for reconciliation_report in response['results']: # Print out some information for each reconciliation report. diff --git a/examples/dfp/v201608/report_service/__init__.py b/examples/dfp/v201705/report_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/report_service/__init__.py rename to examples/dfp/v201705/report_service/__init__.py diff --git a/examples/dfp/v201608/report_service/run_delivery_report.py b/examples/dfp/v201705/report_service/run_delivery_report.py old mode 100755 new mode 100644 similarity index 83% rename from examples/dfp/v201608/report_service/run_delivery_report.py rename to examples/dfp/v201705/report_service/run_delivery_report.py index 8ae035f8..098ec309 --- a/examples/dfp/v201608/report_service/run_delivery_report.py +++ b/examples/dfp/v201705/report_service/run_delivery_report.py @@ -14,8 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report similar to the "Orders report" on the DFP -website with additional attributes and can filter to include just one order. +"""Runs a report similar to the "Orders report" on the DFP website. + +Includes additional attributes and can filter to include just one order. """ from datetime import datetime @@ -42,7 +43,7 @@ def main(client, order_id): 'values': values} # Set the start and end dates of the report to run (past 8 days). - end_date = datetime.now() + end_date = datetime.now().date() start_date = end_date - timedelta(days=8) # Create report job. @@ -56,17 +57,13 @@ def main(client, order_id): 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], 'dateRangeType': 'CUSTOM_DATE', - 'startDate': {'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day}, - 'endDate': {'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day} + 'startDate': start_date, + 'endDate': end_date } } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201608') + report_downloader = client.GetDataDownloader(version='v201705') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201608/report_service/run_inventory_report.py b/examples/dfp/v201705/report_service/run_inventory_report.py old mode 100755 new mode 100644 similarity index 94% rename from examples/dfp/v201608/report_service/run_inventory_report.py rename to examples/dfp/v201705/report_service/run_inventory_report.py index 2eee56d8..329978f3 --- a/examples/dfp/v201608/report_service/run_inventory_report.py +++ b/examples/dfp/v201705/report_service/run_inventory_report.py @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report equal to the "Whole network report" on the -DFP website. -""" +"""Runs a report equal to the "Whole network report" on the DFP website.""" import tempfile @@ -27,9 +25,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201608') + network_service = client.GetService('NetworkService', version='v201705') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201608') + report_downloader = client.GetDataDownloader(version='v201705') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201608/report_service/run_reach_report.py b/examples/dfp/v201705/report_service/run_reach_report.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/report_service/run_reach_report.py rename to examples/dfp/v201705/report_service/run_reach_report.py index 7b2dadf0..640e2887 --- a/examples/dfp/v201608/report_service/run_reach_report.py +++ b/examples/dfp/v201705/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201608') + report_downloader = client.GetDataDownloader(version='v201705') # Create report job. report_job = { diff --git a/examples/dfp/v201608/report_service/run_report_with_custom_fields.py b/examples/dfp/v201705/report_service/run_report_with_custom_fields.py old mode 100755 new mode 100644 similarity index 94% rename from examples/dfp/v201608/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201705/report_service/run_report_with_custom_fields.py index 9cb816a2..16656a86 --- a/examples/dfp/v201608/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201705/report_service/run_report_with_custom_fields.py @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report that with custom fields found in the line -items of an order. -""" +"""Runs a report with custom fields found in the line items of an order.""" import tempfile @@ -30,9 +28,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201608') + line_item_service = client.GetService('LineItemService', version='v201705') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201608') + report_downloader = client.GetDataDownloader(version='v201705') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201608/report_service/run_sales_report.py b/examples/dfp/v201705/report_service/run_sales_report.py old mode 100755 new mode 100644 similarity index 92% rename from examples/dfp/v201608/report_service/run_sales_report.py rename to examples/dfp/v201705/report_service/run_sales_report.py index 69e52577..3347fc79 --- a/examples/dfp/v201608/report_service/run_sales_report.py +++ b/examples/dfp/v201705/report_service/run_sales_report.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example runs a report equal to the "Sales by salespersons report." -""" +"""Runs a report equal to the 'Sales by salespersons report'.""" import tempfile @@ -26,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201608') + report_downloader = client.GetDataDownloader(version='v201705') # Create report job. report_job = { diff --git a/examples/dfp/v201608/report_service/run_saved_query.py b/examples/dfp/v201705/report_service/run_saved_query.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/report_service/run_saved_query.py rename to examples/dfp/v201705/report_service/run_saved_query.py index fcaba920..e23b1699 --- a/examples/dfp/v201608/report_service/run_saved_query.py +++ b/examples/dfp/v201705/report_service/run_saved_query.py @@ -28,10 +28,10 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201608') + report_service = client.GetService('ReportService', version='v201705') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201608') + report_downloader = client.GetDataDownloader(version='v201705') # Create statement object to filter for an order. values = [{ diff --git a/examples/dfp/v201608/suggested_ad_unit_service/__init__.py b/examples/dfp/v201705/suggested_ad_unit_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201705/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 11d8734a..c2dab5d4 --- a/examples/dfp/v201608/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201608') + 'SuggestedAdUnitService', version='v201705') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py index 6683d068..7b4842a1 --- a/examples/dfp/v201608/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201608') + 'SuggestedAdUnitService', version='v201705') # Create a statement to select suggested ad units. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index f1c3bc1f..355b47c3 --- a/examples/dfp/v201608/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,7 +25,7 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201608') + 'SuggestedAdUnitService', version='v201705') query = 'WHERE numRequests >= :numRequests' values = [ {'key': 'numRequests', diff --git a/examples/dfp/v201608/team_service/__init__.py b/examples/dfp/v201705/team_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/team_service/__init__.py rename to examples/dfp/v201705/team_service/__init__.py diff --git a/examples/dfp/v201608/team_service/create_teams.py b/examples/dfp/v201705/team_service/create_teams.py old mode 100755 new mode 100644 similarity index 94% rename from examples/dfp/v201608/team_service/create_teams.py rename to examples/dfp/v201705/team_service/create_teams.py index 3f2f2f9e..94884e71 --- a/examples/dfp/v201608/team_service/create_teams.py +++ b/examples/dfp/v201705/team_service/create_teams.py @@ -22,7 +22,6 @@ "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. - """ @@ -34,11 +33,11 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201608') + team_service = client.GetService('TeamService', version='v201705') # Create team objects. teams = [] - for i in xrange(5): + for _ in xrange(5): team = { 'name': 'Team %s' % uuid.uuid4(), 'hasAllCompanies': 'false', diff --git a/examples/dfp/v201608/team_service/get_all_teams.py b/examples/dfp/v201705/team_service/get_all_teams.py old mode 100755 new mode 100644 similarity index 95% rename from examples/dfp/v201608/team_service/get_all_teams.py rename to examples/dfp/v201705/team_service/get_all_teams.py index 6ac1b1df..2c34c9cd --- a/examples/dfp/v201608/team_service/get_all_teams.py +++ b/examples/dfp/v201705/team_service/get_all_teams.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201608') + team_service = client.GetService('TeamService', version='v201705') # Create a statement to select teams. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/team_service/update_teams.py b/examples/dfp/v201705/team_service/update_teams.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/team_service/update_teams.py rename to examples/dfp/v201705/team_service/update_teams.py index 8643aa5e..04373311 --- a/examples/dfp/v201608/team_service/update_teams.py +++ b/examples/dfp/v201705/team_service/update_teams.py @@ -34,7 +34,7 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201608') + team_service = client.GetService('TeamService', version='v201705') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201608/user_service/__init__.py b/examples/dfp/v201705/user_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/user_service/__init__.py rename to examples/dfp/v201705/user_service/__init__.py diff --git a/examples/dfp/v201608/user_service/create_users.py b/examples/dfp/v201705/user_service/create_users.py old mode 100755 new mode 100644 similarity index 92% rename from examples/dfp/v201608/user_service/create_users.py rename to examples/dfp/v201705/user_service/create_users.py index 08cff403..0098e05c --- a/examples/dfp/v201608/user_service/create_users.py +++ b/examples/dfp/v201705/user_service/create_users.py @@ -16,7 +16,8 @@ """This code example creates new users. -To determine which users exist, run get_all_users.py.""" +To determine which users exist, run get_all_users.py. +""" # Import appropriate modules from the client library. @@ -28,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201608') + user_service = client.GetService('UserService', version='v201705') # Create user objects. users = [ diff --git a/examples/dfp/v201608/user_service/deactivate_users.py b/examples/dfp/v201705/user_service/deactivate_users.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/user_service/deactivate_users.py rename to examples/dfp/v201705/user_service/deactivate_users.py index ff9459db..bf736c09 --- a/examples/dfp/v201608/user_service/deactivate_users.py +++ b/examples/dfp/v201705/user_service/deactivate_users.py @@ -18,7 +18,8 @@ Deactivated users can no longer make requests to the API. The user making the request cannot deactivate itself. To determine which users exist, run -get_all_users.py.""" +get_all_users.py. +""" # Import appropriate modules from the client library. @@ -29,7 +30,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201608') + user_service = client.GetService('UserService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/user_service/get_all_roles.py b/examples/dfp/v201705/user_service/get_all_roles.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/user_service/get_all_roles.py rename to examples/dfp/v201705/user_service/get_all_roles.py diff --git a/examples/dfp/v201608/user_service/get_all_users.py b/examples/dfp/v201705/user_service/get_all_users.py old mode 100755 new mode 100644 similarity index 95% rename from examples/dfp/v201608/user_service/get_all_users.py rename to examples/dfp/v201705/user_service/get_all_users.py index e211603a..8319149c --- a/examples/dfp/v201608/user_service/get_all_users.py +++ b/examples/dfp/v201705/user_service/get_all_users.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201608') + user_service = client.GetService('UserService', version='v201705') # Create a statement to select users. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201705/user_service/get_current_user.py b/examples/dfp/v201705/user_service/get_current_user.py new file mode 100755 index 00000000..e83ae73f --- /dev/null +++ b/examples/dfp/v201705/user_service/get_current_user.py @@ -0,0 +1,39 @@ +#!/usr/bin/python +# +# Copyright 2017 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 the current user.""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201705') + + # Get current user. + user = user_service.getCurrentUser() + + print ('User with ID %d, name \'%s\', email \'%s\', and role \'%s\' ' + 'is the current user.' % ( + user.id, user.name, user.email, user.roleName + )) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201608/user_service/get_user_by_email_address.py b/examples/dfp/v201705/user_service/get_user_by_email_address.py old mode 100755 new mode 100644 similarity index 96% rename from examples/dfp/v201608/user_service/get_user_by_email_address.py rename to examples/dfp/v201705/user_service/get_user_by_email_address.py index cd80b395..72a800b8 --- a/examples/dfp/v201608/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201705/user_service/get_user_by_email_address.py @@ -24,7 +24,7 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201608') + user_service = client.GetService('UserService', version='v201705') query = 'WHERE email = :email' values = [ {'key': 'email', diff --git a/examples/dfp/v201608/user_service/update_users.py b/examples/dfp/v201705/user_service/update_users.py old mode 100755 new mode 100644 similarity index 93% rename from examples/dfp/v201608/user_service/update_users.py rename to examples/dfp/v201705/user_service/update_users.py index 62ca0c22..c7182647 --- a/examples/dfp/v201608/user_service/update_users.py +++ b/examples/dfp/v201705/user_service/update_users.py @@ -16,7 +16,8 @@ """This code example updates a user by adding " Sr." to the end of their name. -To determine which users exist, run get_all_users.py.""" +To determine which users exist, run get_all_users.py. +""" # Import appropriate modules from the client library. @@ -27,7 +28,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201608') + user_service = client.GetService('UserService', version='v201705') # Create query. values = [{ diff --git a/examples/dfp/v201608/user_team_association_service/__init__.py b/examples/dfp/v201705/user_team_association_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/user_team_association_service/__init__.py rename to examples/dfp/v201705/user_team_association_service/__init__.py diff --git a/examples/dfp/v201608/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201705/user_team_association_service/create_user_team_associations.py index d0fe60e5..840f0a4d --- a/examples/dfp/v201608/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201608') + 'UserTeamAssociationService', version='v201705') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py index 94d3c7a9..8a7f873a --- a/examples/dfp/v201608/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201608') + 'UserTeamAssociationService', version='v201705') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py index 29e8afc2..88208c16 --- a/examples/dfp/v201608/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201608') + 'UserTeamAssociationService', version='v201705') # Create a statement to select user team associations. statement = dfp.FilterStatement() diff --git a/examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py index 52bc299f..7e492989 --- a/examples/dfp/v201608/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py @@ -25,7 +25,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201608') + 'UserTeamAssociationService', version='v201705') query = 'WHERE userId = :userId' values = [ {'key': 'userId', diff --git a/examples/dfp/v201608/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201705/user_team_association_service/update_user_team_associations.py index a351b14a..b5ab14a0 --- a/examples/dfp/v201608/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201608') + 'UserTeamAssociationService', version='v201705') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201608/workflow_request_service/__init__.py b/examples/dfp/v201705/workflow_request_service/__init__.py old mode 100755 new mode 100644 similarity index 100% rename from examples/dfp/v201608/workflow_request_service/__init__.py rename to examples/dfp/v201705/workflow_request_service/__init__.py diff --git a/examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py index a5610f83..1092d9af --- a/examples/dfp/v201608/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201608') + version='v201705') # Create query. values = [ diff --git a/examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py rename to examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py index 762f890f..c1276194 --- a/examples/dfp/v201608/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201608') + 'WorkflowRequestService', version='v201705') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py old mode 100755 new mode 100644 similarity index 97% rename from examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py index f1db169a..7e7da01f --- a/examples/dfp/v201608/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201608') + 'WorkflowRequestService', version='v201705') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py old mode 100755 new mode 100644 similarity index 98% rename from examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py index 7d2795a2..53ca3c6f --- a/examples/dfp/v201608/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201608') + version='v201705') # Create query. values = [ diff --git a/googleads/adwords.py b/googleads/adwords.py index 45cfba3e..4952ff7c 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -453,7 +453,7 @@ class _AdWordsHeaderHandler(googleads.common.HeaderHandler): """Handler which generates the headers for AdWords requests.""" # The library signature for AdWords, to be appended to all user agents. - _LIB_SIG = googleads.common.GenerateLibSig('AwApi-Python') + _PRODUCT_SIG = 'AwApi-Python' # The name of the WSDL-defined SOAP Header class used in all SOAP requests. # The namespace needs the version of AdWords being used to be templated in. _SOAP_HEADER_CLASS = ( @@ -487,7 +487,9 @@ def SetHeaders(self, suds_client): header = suds_client.factory.create(self._SOAP_HEADER_CLASS % self._version) header.clientCustomerId = self._adwords_client.client_customer_id header.developerToken = self._adwords_client.developer_token - header.userAgent = ''.join([self._adwords_client.user_agent, self._LIB_SIG]) + header.userAgent = ''.join([ + self._adwords_client.user_agent, + googleads.common.GenerateLibSig(self._PRODUCT_SIG)]) header.validateOnly = self._adwords_client.validate_only header.partialFailure = self._adwords_client.partial_failure @@ -538,8 +540,10 @@ def GetReportDownloadHeaders(self, **kwargs): 'developerToken': str(self._adwords_client.developer_token), 'clientCustomerId': str(kwargs.get( 'client_customer_id', self._adwords_client.client_customer_id)), - 'User-Agent': ''.join([self._adwords_client.user_agent, self._LIB_SIG, - ',gzip']) + 'User-Agent': ''.join([ + self._adwords_client.user_agent, + googleads.common.GenerateLibSig(self._PRODUCT_SIG), + ',gzip']) }) updated_kwargs = dict(self._adwords_client.report_download_headers) diff --git a/googleads/common.py b/googleads/common.py index 32e08f56..8c95d4b3 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -15,6 +15,7 @@ """Common client library functions and classes used by all products.""" +import datetime from functools import wraps import inspect import logging @@ -60,7 +61,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '5.4.0' +VERSION = '5.5.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' @@ -374,7 +375,7 @@ def _ExtractProxy(proxy_yaml_key, proxy_config_data): return proxy -def _PackForSuds(obj, factory): +def _PackForSuds(obj, factory, datetime_packer=None): """Packs SOAP input into the format we want for suds. The main goal here is to pack dictionaries with an 'xsi_type' key into @@ -389,12 +390,15 @@ def _PackForSuds(obj, factory): for instances of unpacked dictionaries or lists. factory: The suds.client.Factory object which can create instances of the classes generated from the WSDL. + datetime_packer: A product specific function to unwrap date/datetimes. Returns: If the given obj was a dictionary that contained the 'xsi_type' key, this will be an instance of a class generated from the WSDL. Otherwise, this will be the same data type as the input obj was. """ + if datetime_packer and isinstance(obj, (datetime.datetime, datetime.date)): + obj = datetime_packer(obj) if obj in ({}, None): # Force suds to serialize empty objects. There are legitimate use cases for # this, for example passing in an empty SearchCriteria object to a DFA @@ -424,14 +428,17 @@ def _PackForSuds(obj, factory): setattr(new_obj, param, None) for key in obj: if key == 'xsi_type': continue - setattr(new_obj, key, _PackForSuds(obj[key], factory)) + setattr(new_obj, key, _PackForSuds(obj[key], factory, + datetime_packer=datetime_packer)) else: new_obj = {} for key in obj: - new_obj[key] = _PackForSuds(obj[key], factory) + new_obj[key] = _PackForSuds(obj[key], factory, + datetime_packer=datetime_packer) return new_obj elif isinstance(obj, (list, tuple)): - return [_PackForSuds(item, factory) for item in obj] + return [_PackForSuds(item, factory, + datetime_packer=datetime_packer) for item in obj] else: _RecurseOverObject(obj, factory) return obj @@ -680,7 +687,7 @@ class SudsServiceProxy(object): the client and its factory, """ - def __init__(self, suds_client, header_handler): + def __init__(self, suds_client, header_handler, datetime_packer=None): """Initializes a suds service proxy. Args: @@ -689,10 +696,12 @@ def __init__(self, suds_client, header_handler): object. header_handler: A HeaderHandler responsible for setting the SOAP and HTTP headers on the service client. + datetime_packer: A product specific function to unwrap date/datetimes. """ self.suds_client = suds_client self._header_handler = header_handler self._method_proxies = {} + self._datetime_packer = datetime_packer def __getattr__(self, attr): if attr in self.suds_client.wsdl.services[0].ports[0].methods: @@ -718,7 +727,8 @@ def MakeSoapRequest(*args): self._header_handler.SetHeaders(self.suds_client) try: return soap_service_method( - *[_PackForSuds(arg, self.suds_client.factory) for arg in args]) + *[_PackForSuds(arg, self.suds_client.factory, + self._datetime_packer) for arg in args]) except suds.WebFault as e: _logger.error('Server raised fault in response.') _logger.info('Failure response:\n%s', e.document) diff --git a/googleads/dfp.py b/googleads/dfp.py index 4d1e6dd7..c2202de3 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -18,6 +18,7 @@ import csv import datetime import logging +import numbers import os import time import urllib2 @@ -39,7 +40,7 @@ _CHUNK_SIZE = 16 * 1024 # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201605': + 'v201608': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -60,7 +61,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201608': + 'v201611': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -70,18 +71,18 @@ 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NetworkService', 'OrderService', + 'PackageService', 'PlacementService', 'PremiumRateService', + 'ProductService', 'ProductPackageService', 'ProductPackageItemService', + 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201611': + 'v201702': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -92,17 +93,18 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NetworkService', 'OrderService', - 'PackageService', 'PlacementService', 'PremiumRateService', - 'ProductService', 'ProductPackageService', 'ProductPackageItemService', - 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201702': + 'v201705': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -289,7 +291,8 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], 'Unrecognized version of the DFP API. Version given: %s Supported ' 'versions: %s' % (version, _SERVICE_MAP.keys())) - return googleads.common.SudsServiceProxy(client, self._header_handler) + return googleads.common.SudsServiceProxy(client, self._header_handler, + _DFPDateTimePacker) def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -318,7 +321,7 @@ class _DfpHeaderHandler(googleads.common.HeaderHandler): """Handler which sets the headers for a DFP SOAP call.""" # The library signature for DFP, to be appended to all application_names. - _LIB_SIG = googleads.common.GenerateLibSig('DfpApi-Python') + _PRODUCT_SIG = 'DfpApi-Python' # The name of the WSDL-defined SOAP Header class used in all requests. _SOAP_HEADER_CLASS = 'SoapRequestHeader' @@ -340,8 +343,9 @@ def SetHeaders(self, suds_client): """Sets the SOAP and HTTP headers on the given suds client.""" header = suds_client.factory.create(self._SOAP_HEADER_CLASS) header.networkCode = self._dfp_client.network_code - header.applicationName = ''.join([self._dfp_client.application_name, - self._LIB_SIG]) + header.applicationName = ''.join([ + self._dfp_client.application_name, + googleads.common.GenerateLibSig(self._PRODUCT_SIG)]) http_headers = self._dfp_client.oauth2_client.CreateHttpHeader() if self.enable_compression: @@ -352,6 +356,292 @@ def SetHeaders(self, suds_client): headers=http_headers) +@googleads.common.RegisterUtility('StatementBuilder') +class StatementBuilder(object): + """Provides the ability to programmatically construct PQL queries.""" + + class _OrderByPair(object): + """Stores and serializes a pair of column/ascending values.""" + + def __init__(self, column, ascending): + """Initializes a pair of column/ascending values. + + Args: + column: a string specifying the column name. + ascending: a boolean specifying sort order ascending or descending. + """ + self.column = column + self.ascending = ascending + + def __repr__(self): + """The string representation of this class is valid PQL.""" + return '%s %s' % (self.column, 'ASC' if self.ascending else 'DESC') + + _SELECT_PART = 'SELECT %s FROM %s' + _WHERE_PART = 'WHERE %s' + _ORDER_BY_PART = 'ORDER BY %s' + _LIMIT_PART = 'LIMIT %s' + _OFFSET_PART = 'OFFSET %s' + + def __init__(self, select_columns=None, from_table=None, where=None, + order_by=None, order_ascending=True, + limit=SUGGESTED_PAGE_LIMIT, offset=0): + """Initializes StatementBuilder. + + Args: + select_columns: a comma separated string of column names. + from_table: a string specifying the table to select from. + where: a string with the where clause. + order_by: a string with the order by clause. + order_ascending: a boolean specifying sort order ascending or descending. + limit: an integer with the limit clause. + offset: an integer with the offset clause. + """ + self._select = select_columns + self._from_ = from_table + self._where = where + self.limit = limit + self.offset = offset + if order_by: + self._order_by = self._OrderByPair(column=order_by, + ascending=order_ascending) + else: + self._order_by = None + self._values = {} # Use a dict to prevent duplicates + + def ToStatement(self): + """Builds a PQL string from the current state. + + Returns: + A string representation of the PQL statement. + """ + + if self._select and not self._from_: + raise googleads.errors.GoogleAdsError('FROM clause required with SELECT.') + + if self._from_ and not self._select: + raise googleads.errors.GoogleAdsError('SELECT clause required with FROM.') + + query = [] + + if self._select: + query.append(self._SELECT_PART % (self._select, self._from_)) + + if self._where: + query.append(self._WHERE_PART % self._where) + + if self._order_by: + query.append(self._ORDER_BY_PART % self._order_by) + + if self.limit: + query.append(self._LIMIT_PART % self.limit) + + if self.offset is not None: + query.append(self._OFFSET_PART % self.offset) + + return {'query': ' '.join(query), + 'values': (PQLHelper.GetQueryValuesFromDict(self._values) + if self._values else None)} + + def Select(self, columns): + """Adds a SELECT clause. + + Args: + columns: A comma separated string specifying the columns. + + Returns: + A reference to the StatementBuilder. + """ + self._select = columns + return self + + def From(self, table): + """Adds a FROM clause. + + Args: + table: A string specifying the table. + + Returns: + A reference to the StatementBuilder + """ + self._from_ = table + return self + + def Where(self, clause): + """Adds a WHERE clause. + + Args: + clause: A string specifying the where clause. + + Returns: + A reference to the StatementBuilder. + """ + self._where = clause + return self + + def Limit(self, limit=SUGGESTED_PAGE_LIMIT): + """Adds a LIMIT clause. + + Args: + limit: An integer specifying the limit value. + + Returns: + A reference to the StatementBuilder. + """ + self.limit = limit + return self + + def Offset(self, value): + """Adds an OFFSET clause. + + Args: + value: An integer specifying the offset value. + + Returns: + A reference to the StatementBuilder. + """ + self.offset = value + return self + + def OrderBy(self, column, ascending=True): + """Adds an ORDER BY clause. + + Args: + column: A string specifying the column to order by. + ascending: A bool to indicate ascending vs descending. + + Returns: + A reference to the StatementBuilder + """ + self._order_by = self._OrderByPair(column=column, + ascending=ascending) + return self + + def WithBindVariable(self, key, value): + """Binds a value to a variable in the statement. + + Args: + key: A string identifying the variable. + value: A object of an acceptable type specifying the value. + + Returns: + A reference to the StatementBuilder. + """ + + # Make this call to throw the exception here if there is a problem + PQLHelper.GetValueRepresentation(value) + + self._values[key] = value + return self + + +def _DFPDateTimePacker(value): + """Returns dicts formatted for DFP SOAP based on date/datetime. + + Args: + value: A date or datetime object to be converted. + + Returns: + The value object correctly represented for DFP SOAP. + """ + + if isinstance(value, datetime.datetime): + if value.tzinfo is None: + raise googleads.errors.GoogleAdsValueError( + 'Datetime %s is not timezone aware.' % value + ) + + return { + 'date': _DFPDateTimePacker(value.date()), + 'hour': value.hour, + 'minute': value.minute, + 'second': value.second, + 'timeZoneID': value.tzinfo.zone, + } + elif isinstance(value, datetime.date): + return {'year': value.year, 'month': value.month, 'day': value.day} + + +class PQLHelper(object): + """Utility class for PQL.""" + + @classmethod + def GetQueryValuesFromDict(cls, d): + """Converts a dict of python types into a list of PQL types. + + Args: + d: A dictionary of variable names to python types. + + Returns: + A list of variables formatted for PQL statements. + """ + return [{ + 'key': key, + 'value': cls.GetValueRepresentation(value) + } for key, value in d.iteritems()] + + @classmethod + def GetValueRepresentation(cls, value): + """Converts a single python value to its PQL representation. + + Args: + value: A python value. + + Returns: + The value formatted for PQL statements. + """ + if isinstance(value, str) or isinstance(value, unicode): + return {'value': value, 'xsi_type': 'TextValue'} + elif isinstance(value, bool): + return {'value': value, 'xsi_type': 'BooleanValue'} + elif isinstance(value, numbers.Number): + return {'value': value, 'xsi_type': 'NumberValue'} + # It's important that datetime is checked for before date + # because isinstance(datetime.datetime.now(), datetime.date) is True + elif isinstance(value, datetime.datetime): + if value.tzinfo is None: + raise googleads.errors.GoogleAdsValueError( + 'Datetime %s is not timezone aware.' % value + ) + + return { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': value.year, + 'month': value.month, + 'day': value.day, + }, + 'hour': value.hour, + 'minute': value.minute, + 'second': value.second, + 'timeZoneID': value.tzinfo.zone, + } + } + elif isinstance(value, datetime.date): + return { + 'xsi_type': 'DateValue', + 'value': { + 'year': value.year, + 'month': value.month, + 'day': value.day, + } + } + elif isinstance(value, list): + if value and not all(isinstance(x, type(value[0])) for x in value): + raise googleads.errors.GoogleAdsValueError('Cannot pass more than one ' + 'type in a set.') + + return { + 'xsi_type': 'SetValue', + 'values': [cls.GetValueRepresentation(v) for v in value] + } + else: + raise googleads.errors.GoogleAdsValueError( + 'Can\'t represent unknown type: %s.' % type(value)) + + +@googleads.common.RegisterUtility('FilterStatement') class FilterStatement(object): """A statement object for PQL and get*ByStatement queries. @@ -360,8 +650,8 @@ class FilterStatement(object): set. """ - def __init__( - self, where_clause='', values=None, limit=SUGGESTED_PAGE_LIMIT, offset=0): + def __init__(self, where_clause='', values=None, limit=SUGGESTED_PAGE_LIMIT, + offset=0): self.where_clause = where_clause self.values = values self.limit = limit @@ -571,16 +861,19 @@ def _PageThroughPqlSet(self, pql_query, output_function, values): memory) values: list dict of bind values to use with the pql_query. """ - result_set_size = 0 pql_service = self._GetPqlService() - filter_statement = FilterStatement(pql_query, values, SUGGESTED_PAGE_LIMIT) + current_offset = 0 while True: - response = pql_service.select(filter_statement.ToStatement()) + query_w_limit_offset = '%s LIMIT %d OFFSET %d' % (pql_query, + SUGGESTED_PAGE_LIMIT, + current_offset) + response = pql_service.select({'query': query_w_limit_offset, + 'values': values}) if 'rows' in response: # Write the header row only on first pull - if filter_statement.offset == 0: + if current_offset == 0: header = response['columnTypes'] output_function([label['labelName'] for label in header]) @@ -591,7 +884,7 @@ def _PageThroughPqlSet(self, pql_query, output_function, values): output_function([self._ConvertValueForCsv(value) for value in entity['values']]) - filter_statement.offset += result_set_size + current_offset += result_set_size if result_set_size != SUGGESTED_PAGE_LIMIT: break else: diff --git a/setup.py b/setup.py old mode 100755 new mode 100644 diff --git a/tests/adwords_test.py b/tests/adwords_test.py index bf586c58..145a13ed 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -135,6 +135,9 @@ def setUp(self): self.validate_only = True self.partial_failure = False self.enable_compression = False + self.utility_name = 'TestUtility' + self.default_sig_template = ' (%s, %s, %s)' + self.util_sig_template = ' (%s, %s, %s, %s)' self.aw_client = GetAdWordsClient( ccid=self.ccid, dev_token=self.dev_token, user_agent=self.user_agent, oauth2_client=self.oauth2_client, validate_only=self.validate_only, @@ -143,6 +146,14 @@ def setUp(self): self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.aw_client, CURRENT_VERSION, self.enable_compression) + @googleads.common.RegisterUtility(self.utility_name) + class TestUtility(object): + + def Test(self): + pass + + self.test_utility = TestUtility() + def testSetHeaders(self): suds_client = mock.Mock() self.header_handler.SetHeaders(suds_client) @@ -155,7 +166,8 @@ def testSetHeaders(self): self.assertEqual(self.dev_token, soap_header.developerToken) self.assertEqual( ''.join([self.user_agent, - googleads.adwords._AdWordsHeaderHandler._LIB_SIG]), + googleads.common.GenerateLibSig( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG)]), soap_header.userAgent) self.assertEqual(self.validate_only, soap_header.validateOnly) self.assertEqual(self.partial_failure, soap_header.partialFailure) @@ -163,6 +175,72 @@ def testSetHeaders(self): suds_client.set_options.assert_any_call( soapheaders=soap_header, headers=self.oauth_header) + def testSetHeadersUserAgentWithUtility(self): + suds_client = mock.Mock() + + with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: + with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: + self.test_utility.Test() # This will register TestUtility. + self.header_handler.SetHeaders(suds_client) + soap_header = suds_client.factory.create.return_value + + self.assertEqual( + ''.join([self.user_agent, + self.util_sig_template % ( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name) + ]), + soap_header.userAgent) + + def testSetHeadersUserAgentWithAndWithoutUtility(self): + suds_client = mock.Mock() + + with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: + with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: + # Check headers when utility registered. + self.test_utility.Test() # This will register TestUtility. + self.header_handler.SetHeaders(suds_client) + soap_header = suds_client.factory.create.return_value + + self.assertEqual( + ''.join([self.user_agent, + self.util_sig_template % ( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name) + ]), + soap_header.userAgent) + + # Check headers when no utility should be registered. + self.header_handler.SetHeaders(suds_client) + soap_header = suds_client.factory.create.return_value + self.assertEqual( + ''.join([self.user_agent, + self.default_sig_template % ( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver) + ]), + soap_header.userAgent) + + # Verify that utility is registered in subsequent uses. + self.test_utility.Test() # This will register TestUtility. + self.header_handler.SetHeaders(suds_client) + soap_header = suds_client.factory.create.return_value + + self.assertEqual( + ''.join([self.user_agent, + self.util_sig_template % ( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name) + ]), + soap_header.userAgent) + def testGetReportDownloadHeadersOverrideDefaults(self): self.aw_client.report_downloader_headers = { 'skip_report_header': True, 'skip_column_header': False, @@ -173,7 +251,9 @@ def testGetReportDownloadHeadersOverrideDefaults(self): 'clientCustomerId': self.ccid, 'Authorization': 'header', 'User-Agent': ''.join([ - self.user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + self.user_agent, + googleads.common.GenerateLibSig( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG), ',gzip']), 'skipReportHeader': 'False', 'skipColumnHeader': 'True', @@ -197,7 +277,9 @@ def testGetReportDownloadHeadersWithDefaultsFromConfig(self): 'clientCustomerId': self.ccid, 'Authorization': 'header', 'User-Agent': ''.join([ - self.user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + self.user_agent, + googleads.common.GenerateLibSig( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG), ',gzip']), 'skipReportHeader': 'True', 'skipColumnHeader': 'False', @@ -220,7 +302,9 @@ def testGetReportDownloadHeadersWithKeywordArguments(self): 'clientCustomerId': updated_ccid, 'Authorization': 'header', 'User-Agent': ''.join([ - self.user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + self.user_agent, + googleads.common.GenerateLibSig( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG), ',gzip']), 'skipReportHeader': 'True', 'skipColumnHeader': 'True', @@ -244,7 +328,9 @@ def testGetReportDownloadHeadersWithNoOptionalHeaders(self): 'clientCustomerId': self.ccid, 'Authorization': 'header', 'User-Agent': ''.join([ - self.user_agent, googleads.adwords._AdWordsHeaderHandler._LIB_SIG, + self.user_agent, + googleads.common.GenerateLibSig( + googleads.adwords._AdWordsHeaderHandler._PRODUCT_SIG), ',gzip']) } self.assertEqual(expected_return_value, diff --git a/tests/common_test.py b/tests/common_test.py index e52c9139..b09c1ae2 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -15,6 +15,7 @@ """Unit tests to cover the common module.""" +import datetime import io import unittest from urllib import addinfourl @@ -779,6 +780,29 @@ def testPackForSuds_secondNamespace(self): factory.create.assert_any_call('ns0:EliteCampaign') self.assertEqual('Sales', rval.name) + def testPackForSuds_datetime_packer(self): + factory = mock.Mock() + factory.create.return_value = mock.MagicMock() + factory.create.return_value.__iter__.return_value = iter( + [('abc', 0)]) + + def sample_packer(dt): + return {'xsi_type': 'abc', 'test': dt.year} + + # Test that our packer function is called for datetimes + rval = googleads.common._PackForSuds( + {'param': datetime.datetime(2017, 1, 1, 0, 0, 0)}, + factory, datetime_packer=sample_packer) + + self.assertEqual(2017, rval['param'].test) + + # Test that our packer function is called for dates + rval = googleads.common._PackForSuds( + {'param': datetime.date(2017, 1, 1)}, + factory, datetime_packer=sample_packer) + + self.assertEqual(2017, rval['param'].test) + class SudsServiceProxyTest(unittest.TestCase): """Tests for the googleads.common.SudsServiceProxy class.""" @@ -791,8 +815,9 @@ def setUp(self): self.services.ports = [self.port] self.client = mock.Mock() self.client.wsdl.services = [self.services] + self.datetime_packer = mock.Mock() self.suds_service_wrapper = googleads.common.SudsServiceProxy( - self.client, self.header_handler) + self.client, self.header_handler, self.datetime_packer) def testSudsServiceProxy(self): self.assertEqual(self.suds_service_wrapper.SoapMethod, @@ -803,7 +828,8 @@ def testSudsServiceProxy(self): with mock.patch('googleads.common._PackForSuds') as mock_pack_for_suds: mock_pack_for_suds.return_value = 'modified_test' self.suds_service_wrapper.SoapMethod('test') - mock_pack_for_suds.assert_called_once_with('test', self.client.factory) + mock_pack_for_suds.assert_called_once_with('test', self.client.factory, + self.datetime_packer) self.client.service.SoapMethod.assert_called_once_with('modified_test') self.header_handler.SetHeaders.assert_called_once_with(self.client) diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 9311c892..ccee282a 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -15,12 +15,14 @@ """Unit tests to cover the dfp module.""" +import datetime import StringIO import sys import unittest import mock +import pytz import suds.transport import googleads.dfp @@ -112,29 +114,112 @@ def setUp(self): self.enable_compression = False self.header_handler = googleads.dfp._DfpHeaderHandler( self.dfp_client, self.enable_compression) + self.utility_name = 'TestUtility' + self.default_sig_template = ' (%s, %s, %s)' + self.util_sig_template = ' (%s, %s, %s, %s)' + self.network_code = 'my network code is code' + self.app_name = 'application name' + self.oauth_header = {'oauth', 'header'} + + @googleads.common.RegisterUtility(self.utility_name) + class TestUtility(object): + + def Test(self): + pass + + self.test_utility = TestUtility() def testSetHeaders(self): suds_client = mock.Mock() - network_code = 'my network code is code' - app_name = 'application name' - oauth_header = {'oauth', 'header'} - self.dfp_client.network_code = network_code - self.dfp_client.application_name = app_name - self.dfp_client.oauth2_client.CreateHttpHeader.return_value = oauth_header + self.dfp_client.network_code = self.network_code + self.dfp_client.application_name = self.app_name + self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( + self.oauth_header) self.header_handler.SetHeaders(suds_client) # Check that the SOAP header has the correct values. suds_client.factory.create.assert_called_once_with('SoapRequestHeader') soap_header = suds_client.factory.create.return_value - self.assertEqual(network_code, soap_header.networkCode) - self.assertEqual(''.join([app_name, - googleads.dfp._DfpHeaderHandler._LIB_SIG]), - soap_header.applicationName) + self.assertEqual(self.network_code, soap_header.networkCode) + self.assertEqual( + ''.join([ + self.app_name, + googleads.common.GenerateLibSig( + googleads.dfp._DfpHeaderHandler._PRODUCT_SIG)]), + soap_header.applicationName) # Check that the suds client has the correct values. suds_client.set_options.assert_any_call(soapheaders=soap_header, - headers=oauth_header) + headers=self.oauth_header) + + def testSetHeadersUserAgentWithUtility(self): + suds_client = mock.Mock() + self.dfp_client.network_code = self.network_code + self.dfp_client.application_name = self.app_name + self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( + self.oauth_header) + + with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: + with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: + self.test_utility.Test() # This will register TestUtility. + self.header_handler.SetHeaders(suds_client) + soap_header = suds_client.factory.create.return_value + self.assertEqual( + ''.join([self.app_name, + self.util_sig_template % ( + googleads.dfp._DfpHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name)]), + soap_header.applicationName) + + def testSetHeadersUserAgentWithAndWithoutUtility(self): + suds_client = mock.Mock() + + self.dfp_client.network_code = self.network_code + self.dfp_client.application_name = self.app_name + self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( + self.oauth_header) + + with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: + with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: + # Check headers when utility registered. + self.test_utility.Test() # This will register TestUtility. + self.header_handler.SetHeaders(suds_client) + soap_header = suds_client.factory.create.return_value + self.assertEqual( + ''.join([self.app_name, + self.util_sig_template % ( + googleads.dfp._DfpHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name)]), + soap_header.applicationName) + + # Check headers when no utility should be registered. + self.header_handler.SetHeaders(suds_client) + soap_header = suds_client.factory.create.return_value + self.assertEqual( + ''.join([self.app_name, + self.default_sig_template % ( + googleads.dfp._DfpHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver)]), + soap_header.applicationName) + + # Verify that utility is registered in subsequent uses. + self.test_utility.Test() # This will register TestUtility. + self.header_handler.SetHeaders(suds_client) + soap_header = suds_client.factory.create.return_value + self.assertEqual( + ''.join([self.app_name, + self.util_sig_template % ( + googleads.dfp._DfpHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name)]), + soap_header.applicationName) @@ -231,14 +316,23 @@ def testGetService_success(self): with mock.patch('suds.client.Client') as mock_client: with mock.patch('googleads.common.' 'ProxyConfig._SudsProxyTransport') as mock_transport: - mock_transport.return_value = mock.Mock() - suds_service = dfp_client.GetService(service, self.version, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), timeout=3600, - transport=mock_transport.return_value) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + with mock.patch('googleads.common.' + 'SudsServiceProxy') as mock_service_proxy: + mock_service_proxy.return_value = mock.Mock() + mock_transport.return_value = mock.Mock() + mock_client.return_value = mock.Mock() + mock_client.return_value.sd.__getitem__ = mock.Mock() + suds_service = dfp_client.GetService(service, self.version, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service), timeout=3600, + transport=mock_transport.return_value) + self.assertEqual(suds_service, mock_service_proxy.return_value) + mock_service_proxy.assert_called_once_with( + mock_client.return_value, + dfp_client._header_handler, + googleads.dfp._DFPDateTimePacker) def testGetService_successWithFileCache(self): service = googleads.dfp._SERVICE_MAP[self.version][0] @@ -323,6 +417,27 @@ def testGetService_transportError(self): dfp_client.GetService, service, self.version) +class DateTimePackerTest(unittest.TestCase): + + def testUnwrapDate(self): + input_date = datetime.date(2017, 1, 2) + result = googleads.dfp._DFPDateTimePacker(input_date) + self.assertEqual(result, {'year': 2017, 'month': 1, 'day': 2}) + + def testUnwrapDateTime(self): + input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) + input_date = pytz.timezone('America/New_York').localize(input_date) + result = googleads.dfp._DFPDateTimePacker(input_date) + self.assertEqual(result, {'date': {'year': 2017, 'month': 1, 'day': 2}, + 'hour': 3, 'minute': 4, 'second': 5, + 'timeZoneID': 'America/New_York'}) + + def testUnwrapDateTimeNeedsTimeZone(self): + input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) + self.assertRaises(googleads.errors.GoogleAdsValueError, + googleads.dfp._DFPDateTimePacker, input_date) + + class DataDownloaderTest(unittest.TestCase): """Tests for the googleads.dfp.DfpClient class.""" @@ -582,6 +697,264 @@ def testGetPqlService(self): 'PublisherQueryLanguageService', self.version, 'https://ads.google.com') +class StatementBuilderTest(unittest.TestCase): + """Tests for the StatementBuilder class.""" + + def testBuildBasicSelectFrom(self): + test_statement = googleads.dfp.StatementBuilder() + select_call_result = test_statement.Select('Id') + from_call_result = test_statement.From('Line_Item') + + self.assertEqual(select_call_result, test_statement) + self.assertEqual(from_call_result, test_statement) + self.assertEqual(test_statement.ToStatement(), + {'query': ('SELECT Id FROM Line_Item LIMIT %s OFFSET 0' % + googleads.dfp.SUGGESTED_PAGE_LIMIT), + 'values': None}) + + def testLimitClause(self): + test_statement = googleads.dfp.StatementBuilder() + limit_call_result = (test_statement + .Select('Id') + .From('Line_Item') + .Limit(5)) + + self.assertEqual(limit_call_result, test_statement) + self.assertEqual(test_statement.ToStatement(), + {'query': 'SELECT Id FROM Line_Item LIMIT 5 OFFSET 0', + 'values': None}) + + limit_call_result.Limit(None) + self.assertEqual(test_statement.ToStatement(), + {'query': 'SELECT Id FROM Line_Item OFFSET 0', + 'values': None}) + + def testOffsetClause(self): + test_statement = googleads.dfp.StatementBuilder() + offset_call_result = ( + test_statement + .Select('Id') + .From('Line_Item') + .Offset(100) + ) + + self.assertEqual(offset_call_result, test_statement) + self.assertEqual(test_statement.ToStatement(), + {'query': ('SELECT Id FROM Line_Item LIMIT %s OFFSET 100' % + googleads.dfp.SUGGESTED_PAGE_LIMIT), + 'values': None}) + + def testOrderByClause(self): + test_statement = googleads.dfp.StatementBuilder() + order_call_result = ( + test_statement + .Select('Id') + .From('Line_Item') + .OrderBy('Id') + ) + + self.assertEqual(order_call_result, test_statement) + self.assertEqual(test_statement.ToStatement(), + {'query': ('SELECT Id FROM Line_Item ' + 'ORDER BY Id ASC ' + 'LIMIT %s OFFSET 0' % + googleads.dfp.SUGGESTED_PAGE_LIMIT), + 'values': None}) + + test_statement.OrderBy('Id', ascending=False) + self.assertEqual(test_statement.ToStatement(), + {'query': ('SELECT Id FROM Line_Item ' + 'ORDER BY Id DESC ' + 'LIMIT %s OFFSET 0' % + googleads.dfp.SUGGESTED_PAGE_LIMIT), + 'values': None}) + + def testConstructorArgs(self): + test_statement = googleads.dfp.StatementBuilder(select_columns='Id', + from_table='Line_Item', + where='abc = 123', + order_by='Id', + order_ascending=False,) + + self.assertEqual(test_statement.ToStatement(), + {'query': ('SELECT Id FROM Line_Item ' + 'WHERE abc = 123 ' + 'ORDER BY Id DESC ' + 'LIMIT %s OFFSET 0' % + googleads.dfp.SUGGESTED_PAGE_LIMIT), + 'values': None}) + + def testWhereWithStringVariable(self): + test_statement = googleads.dfp.StatementBuilder() + where_call_result = ( + test_statement + .Select('Id') + .From('Line_Item') + .Where('key = :test_key') + ) + bind_call_result = test_statement.WithBindVariable('test_key', 'test_value') + + target_values = [{ + 'key': 'test_key', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'test_value' + } + }] + self.assertEqual(where_call_result, test_statement) + self.assertEqual(bind_call_result, test_statement) + self.assertEqual(test_statement.ToStatement(), + {'query': ( + 'SELECT Id FROM Line_Item ' + 'WHERE key = :test_key ' + 'LIMIT %s ' + 'OFFSET 0' % googleads.dfp.SUGGESTED_PAGE_LIMIT), + 'values': target_values}) + + def testWhereWithOtherTypes(self): + test_statement = googleads.dfp.StatementBuilder() + test_statement.Where(( + 'bool_key = :test_bool_key ' + 'AND number_key = :test_number_key ' + 'AND date_key = :test_date_key ' + 'AND datetime_key = :test_datetime_key ' + 'AND set_key = :test_set_key' + )) + + test_statement.WithBindVariable('test_bool_key', True) + test_statement.WithBindVariable('test_number_key', 5) + test_statement.WithBindVariable('test_date_key', datetime.date(2017, 1, 2)) + test_dt = datetime.datetime(2017, 1, 2, + hour=3, minute=4, second=5, + ) + test_dt = pytz.timezone('America/New_York').localize(test_dt) + test_statement.WithBindVariable('test_datetime_key', test_dt) + test_statement.WithBindVariable('test_set_key', [1, 2]) + + target_values = [{ + 'key': 'test_bool_key', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': True, + } + }, { + 'key': 'test_number_key', + 'value': { + 'xsi_type': 'NumberValue', + 'value': 5, + } + }, { + 'key': 'test_date_key', + 'value': { + 'xsi_type': 'DateValue', + 'value': { + 'year': 2017, + 'month': 1, + 'day': 2, + }, + } + }, { + 'key': 'test_datetime_key', + 'value': { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': 2017, + 'month': 1, + 'day': 2, + }, + 'hour': 3, + 'minute': 4, + 'second': 5, + 'timeZoneID': 'America/New_York' + }, + } + }, { + 'key': 'test_set_key', + 'value': { + 'xsi_type': 'SetValue', + 'values': [ + {'xsi_type': 'NumberValue', 'value': 1}, + {'xsi_type': 'NumberValue', 'value': 2}, + ], + } + }] + target_values.sort(key=lambda v: v['key']) + + statement_result = test_statement.ToStatement() + self.assertEqual(statement_result['query'], + ('WHERE bool_key = :test_bool_key ' + 'AND number_key = :test_number_key ' + 'AND date_key = :test_date_key ' + 'AND datetime_key = :test_datetime_key ' + 'AND set_key = :test_set_key ' + 'LIMIT %s ' + 'OFFSET 0' % googleads.dfp.SUGGESTED_PAGE_LIMIT + )) + + # The output order doesn't matter, and it's stored internally as a dict + # until rendered, which is fine, but we need to lock it down for this test. + self.assertEqual( + sorted(statement_result['values'], key=lambda v: v['key']), + target_values + ) + + def testBreakWithSetOfMultipleTypes(self): + test_statement = googleads.dfp.StatementBuilder() + test_statement.Where('key = :test_key') + + self.assertRaises( + googleads.errors.GoogleAdsValueError, + test_statement.WithBindVariable, + 'key', [1, 'a'] + ) + + def testMutateVar(self): + test_statement = googleads.dfp.StatementBuilder() + test_statement.Where('key = :test_key') + test_statement.WithBindVariable('key', 'abc') + test_statement.WithBindVariable('key', '123') + + statement_result = test_statement.ToStatement() + self.assertEqual(len(statement_result['values']), 1) + self.assertEqual(statement_result['values'][0]['value']['value'], '123') + + def testBreakWithNoTZ(self): + test_statement = googleads.dfp.StatementBuilder() + test_statement.Where('key = :test_key') + + self.assertRaises( + googleads.errors.GoogleAdsValueError, + test_statement.WithBindVariable, + 'key', datetime.datetime.now().replace(tzinfo=None) + ) + + def testBreakWithUnknownType(self): + test_statement = googleads.dfp.StatementBuilder() + test_statement.Where('key = :test_key') + + class RandomType(object): + pass + + self.assertRaises( + googleads.errors.GoogleAdsValueError, + test_statement.WithBindVariable, + 'key', RandomType() + ) + + def testBreakWithBadSelectFrom(self): + test_statement = googleads.dfp.StatementBuilder() + test_statement.Select('Id') + + self.assertRaises(googleads.errors.GoogleAdsError, + test_statement.ToStatement) + + test_statement.Select(None).From('Line_Item') + + self.assertRaises(googleads.errors.GoogleAdsError, + test_statement.ToStatement) + + class FilterStatementTest(unittest.TestCase): """Tests for the FilterStatement class.""" From e246f52d7ba0d215e966988b3d06a641d45f5fe5 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 23 May 2017 09:24:38 -0400 Subject: [PATCH 076/180] Commiting latest changes. From 405e439ed528813280efab03d7222b5c5ef30e80 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 1 Jun 2017 12:37:11 -0400 Subject: [PATCH 077/180] AdWords v201705 release. --- ChangeLog | 5 +- .../adwords_appengine_demo/__init__.py | 2 +- .../adwords_appengine_demo/demo/__init__.py | 2 +- .../adwords_appengine_demo/demo/main.py | 2 +- .../handlers/__init__.py | 2 +- .../handlers/api_handler.py | 2 +- .../handlers/ndb_handler.py | 2 +- .../adwords_appengine_demo/models/__init__.py | 2 +- .../adwords_appengine_demo/models/app_user.py | 2 +- .../adwords_appengine_demo/views/__init__.py | 2 +- .../views/add_adgroup_view.py | 2 +- .../views/add_campaign_view.py | 2 +- .../adwords_appengine_demo/views/init_view.py | 2 +- .../views/show_accounts_view.py | 2 +- .../views/show_adgroups_view.py | 2 +- .../views/show_budget_view.py | 2 +- .../views/show_campaigns_view.py | 2 +- .../views/show_credentials_view.py | 2 +- .../views/update_budget_view.py | 2 +- .../views/update_credentials_view.py | 2 +- ...ate_adwords_client_with_service_account.py | 2 +- .../create_adwords_client_without_yaml.py | 2 +- .../authentication/generate_refresh_token.py | 2 +- .../account_management/create_account.py | 0 .../account_management/get_account_changes.py | 0 .../get_account_hierarchy.py | 0 .../advanced_operations/add_ad_customizer.py | 0 .../add_ad_group_bid_modifier.py | 0 .../add_click_to_download_ad.py | 0 .../advanced_operations/add_html5_ad.py | 0 .../add_responsive_display_ad.py | 0 .../add_text_ad_with_upgraded_urls.py | 0 .../create_and_attach_shared_keyword_set.py | 0 ...ind_and_remove_criteria_from_shared_set.py | 0 .../get_ad_group_bid_modifier.py | 0 .../use_shared_bidding_strategy.py | 0 .../v201607/basic_operations/add_ad_groups.py | 0 .../v201607/basic_operations/add_campaigns.py | 0 .../basic_operations/add_expanded_text_ads.py | 0 .../v201607/basic_operations/add_keywords.py | 0 .../v201607/basic_operations/add_text_ads.py | 0 .../v201607/basic_operations/get_ad_groups.py | 0 .../v201607/basic_operations/get_campaigns.py | 0 .../get_campaigns_with_awql.py | 0 .../basic_operations/get_expanded_text_ads.py | 0 .../v201607/basic_operations/get_keywords.py | 0 .../v201607/basic_operations/get_text_ads.py | 0 .../v201607/basic_operations/pause_ad.py | 0 .../v201607/basic_operations/remove_ad.py | 0 .../basic_operations/remove_ad_group.py | 0 .../basic_operations/remove_campaign.py | 0 .../basic_operations/remove_keyword.py | 0 .../basic_operations/update_ad_group.py | 0 .../basic_operations/update_campaign.py | 0 .../basic_operations/update_keyword.py | 0 .../add_campaign_labels.py | 0 .../add_complete_campaigns_using_batch_job.py | 0 .../v201607/campaign_management/add_draft.py | 0 .../campaign_management/add_experiment.py | 0 ...dd_keywords_using_incremental_batch_job.py | 0 .../v201607/campaign_management/add_trial.py | 0 .../get_all_disapproved_ads.py | 0 .../get_all_disapproved_ads_with_awql.py | 0 .../get_campaigns_by_label.py | 0 .../campaign_management/graduate_trial.py | 0 .../campaign_management/promote_experiment.py | 0 .../campaign_management/set_ad_parameters.py | 0 .../set_criterion_bid_modifier.py | 0 .../campaign_management/validate_text_ad.py | 0 .../error_handling/handle_partial_failures.py | 0 .../handle_policy_violation_error.py | 0 ..._google_my_business_location_extensions.py | 0 .../adwords/v201607/extensions/add_prices.py | 0 .../v201607/extensions/add_site_links.py | 0 .../extensions/add_site_links_using_feeds.py | 0 .../migrate_to_extension_settings.py | 0 .../v201607/misc/get_all_images_and_videos.py | 0 examples/adwords/v201607/misc/upload_image.py | 0 .../v201607/misc/upload_media_bundle.py | 0 .../optimization/estimate_keyword_traffic.py | 0 ...aign_criterion_bid_modifier_simulations.py | 0 .../get_keyword_bid_simulations.py | 0 .../v201607/optimization/get_keyword_ideas.py | 0 .../v201607/remarketing/add_audience.py | 0 .../remarketing/add_conversion_tracker.py | 0 .../remarketing/add_crm_based_user_list.py | 0 .../remarketing/add_rule_based_user_lists.py | 0 .../remarketing/upload_offline_conversions.py | 0 .../reporting/download_criteria_report.py | 0 .../download_criteria_report_as_stream.py | 0 ...oad_criteria_report_as_stream_with_awql.py | 0 .../download_criteria_report_as_string.py | 0 ...oad_criteria_report_as_string_with_awql.py | 0 .../download_criteria_report_with_awql.py | 0 .../v201607/reporting/get_report_fields.py | 0 .../reporting/parallel_report_download.py | 0 .../shopping/add_product_partition_tree.py | 0 .../v201607/shopping/add_product_scope.py | 0 .../v201607/shopping/add_shopping_campaign.py | 0 .../shopping/get_product_category_taxonomy.py | 0 .../add_campaign_targeting_criteria.py | 0 .../add_demographic_targeting_criteria.py | 0 .../get_campaign_targeting_criteria.py | 0 .../get_targetable_languages_and_carriers.py | 0 .../v201607/targeting/lookup_location.py | 0 .../account_management/accept_service_link.py | 0 .../account_management/create_account.py | 0 .../account_management/get_account_changes.py | 0 .../get_account_hierarchy.py | 0 .../advanced_operations/add_ad_customizer.py | 0 .../add_ad_group_bid_modifier.py | 0 .../add_click_to_download_ad.py | 0 ...add_expanded_text_ad_with_upgraded_urls.py | 0 .../advanced_operations/add_html5_ad.py | 0 .../add_responsive_display_ad.py | 0 .../add_universal_app_campaign.py | 0 .../create_and_attach_shared_keyword_set.py | 0 ...ind_and_remove_criteria_from_shared_set.py | 0 .../get_ad_group_bid_modifier.py | 0 .../use_shared_bidding_strategy.py | 0 .../v201609/basic_operations/add_ad_groups.py | 0 .../v201609/basic_operations/add_campaigns.py | 0 .../basic_operations/add_expanded_text_ads.py | 0 .../v201609/basic_operations/add_keywords.py | 0 .../v201609/basic_operations/get_ad_groups.py | 0 .../v201609/basic_operations/get_campaigns.py | 0 .../get_campaigns_with_awql.py | 0 .../basic_operations/get_expanded_text_ads.py | 0 .../v201609/basic_operations/get_keywords.py | 0 .../v201609/basic_operations/get_text_ads.py | 0 .../v201609/basic_operations/pause_ad.py | 0 .../v201609/basic_operations/remove_ad.py | 0 .../basic_operations/remove_ad_group.py | 0 .../basic_operations/remove_campaign.py | 0 .../basic_operations/remove_keyword.py | 0 .../basic_operations/update_ad_group.py | 0 .../basic_operations/update_campaign.py | 0 .../basic_operations/update_keyword.py | 0 .../add_campaign_labels.py | 0 .../add_complete_campaigns_using_batch_job.py | 0 .../v201609/campaign_management/add_draft.py | 0 ...dd_keywords_using_incremental_batch_job.py | 0 .../v201609/campaign_management/add_trial.py | 0 .../get_all_disapproved_ads.py | 0 .../get_all_disapproved_ads_with_awql.py | 0 .../get_campaigns_by_label.py | 0 .../campaign_management/graduate_trial.py | 0 .../campaign_management/set_ad_parameters.py | 0 .../set_criterion_bid_modifier.py | 0 .../campaign_management/validate_text_ad.py | 0 .../error_handling/handle_partial_failures.py | 0 .../handle_policy_violation_error.py | 0 ..._google_my_business_location_extensions.py | 0 .../adwords/v201609/extensions/add_prices.py | 0 .../v201609/extensions/add_site_links.py | 0 .../extensions/add_site_links_using_feeds.py | 0 .../migrate_to_extension_settings.py | 0 .../v201609/misc/get_all_images_and_videos.py | 0 examples/adwords/v201609/misc/upload_image.py | 0 .../v201609/misc/upload_media_bundle.py | 0 .../optimization/estimate_keyword_traffic.py | 0 ...aign_criterion_bid_modifier_simulations.py | 0 .../get_keyword_bid_simulations.py | 0 .../v201609/optimization/get_keyword_ideas.py | 0 .../v201609/remarketing/add_audience.py | 0 .../remarketing/add_conversion_tracker.py | 0 .../remarketing/add_crm_based_user_list.py | 0 .../remarketing/add_rule_based_user_lists.py | 0 .../upload_offline_call_conversions.py | 0 .../remarketing/upload_offline_conversions.py | 0 .../reporting/download_criteria_report.py | 0 .../download_criteria_report_as_stream.py | 0 ...oad_criteria_report_as_stream_with_awql.py | 0 .../download_criteria_report_as_string.py | 0 ...oad_criteria_report_as_string_with_awql.py | 0 .../download_criteria_report_with_awql.py | 0 .../v201609/reporting/get_report_fields.py | 0 .../reporting/parallel_report_download.py | 0 .../shopping/add_product_partition_tree.py | 0 .../v201609/shopping/add_product_scope.py | 0 .../v201609/shopping/add_shopping_campaign.py | 0 .../shopping/get_product_category_taxonomy.py | 0 .../add_campaign_targeting_criteria.py | 0 .../add_demographic_targeting_criteria.py | 0 .../get_campaign_targeting_criteria.py | 0 .../get_targetable_languages_and_carriers.py | 0 .../v201609/targeting/lookup_location.py | 0 .../account_management/accept_service_link.py | 0 .../account_management/create_account.py | 0 .../account_management/get_account_changes.py | 0 .../get_account_hierarchy.py | 0 .../advanced_operations/add_ad_customizer.py | 0 .../add_ad_group_bid_modifier.py | 0 .../add_click_to_download_ad.py | 0 ...add_expanded_text_ad_with_upgraded_urls.py | 0 .../advanced_operations/add_html5_ad.py | 0 .../add_responsive_display_ad.py | 0 .../add_universal_app_campaign.py | 0 .../create_and_attach_shared_keyword_set.py | 0 ...ind_and_remove_criteria_from_shared_set.py | 0 .../get_ad_group_bid_modifier.py | 0 .../use_shared_bidding_strategy.py | 0 .../v201702/basic_operations/add_ad_groups.py | 0 .../v201702/basic_operations/add_campaigns.py | 0 .../basic_operations/add_expanded_text_ads.py | 0 .../v201702/basic_operations/add_keywords.py | 0 .../v201702/basic_operations/get_ad_groups.py | 0 .../v201702/basic_operations/get_campaigns.py | 0 .../get_campaigns_with_awql.py | 0 .../basic_operations/get_expanded_text_ads.py | 0 .../v201702/basic_operations/get_keywords.py | 0 .../v201702/basic_operations/get_text_ads.py | 0 .../v201702/basic_operations/pause_ad.py | 0 .../v201702/basic_operations/remove_ad.py | 0 .../basic_operations/remove_ad_group.py | 0 .../basic_operations/remove_campaign.py | 0 .../basic_operations/remove_keyword.py | 0 .../basic_operations/update_ad_group.py | 0 .../basic_operations/update_campaign.py | 0 .../basic_operations/update_keyword.py | 0 .../add_campaign_labels.py | 0 .../add_complete_campaigns_using_batch_job.py | 0 .../v201702/campaign_management/add_draft.py | 0 ...dd_keywords_using_incremental_batch_job.py | 0 .../v201702/campaign_management/add_trial.py | 0 .../get_all_disapproved_ads.py | 0 .../get_all_disapproved_ads_with_awql.py | 0 .../get_campaigns_by_label.py | 0 .../campaign_management/graduate_trial.py | 0 .../campaign_management/set_ad_parameters.py | 0 .../set_criterion_bid_modifier.py | 0 .../campaign_management/validate_text_ad.py | 0 .../error_handling/handle_partial_failures.py | 0 .../handle_policy_violation_error.py | 0 ..._google_my_business_location_extensions.py | 0 .../adwords/v201702/extensions/add_prices.py | 0 .../v201702/extensions/add_site_links.py | 0 .../extensions/add_site_links_using_feeds.py | 0 .../migrate_to_extension_settings.py | 0 .../v201702/misc/get_all_images_and_videos.py | 0 examples/adwords/v201702/misc/upload_image.py | 0 .../v201702/misc/upload_media_bundle.py | 0 .../optimization/estimate_keyword_traffic.py | 0 ...aign_criterion_bid_modifier_simulations.py | 0 .../get_keyword_bid_simulations.py | 0 .../v201702/optimization/get_keyword_ideas.py | 0 .../v201702/remarketing/add_audience.py | 0 .../remarketing/add_conversion_tracker.py | 0 .../remarketing/add_crm_based_user_list.py | 0 .../remarketing/add_rule_based_user_lists.py | 2 +- .../upload_offline_call_conversions.py | 0 .../remarketing/upload_offline_conversions.py | 0 ...oad_criteria_report_as_stream_with_awql.py | 0 ...criteria_report_as_stream_with_selector.py | 0 ...oad_criteria_report_as_string_with_awql.py | 0 ...criteria_report_as_string_with_selector.py | 0 .../download_criteria_report_with_awql.py | 0 .../download_criteria_report_with_selector.py | 0 .../v201702/reporting/get_report_fields.py | 0 .../reporting/parallel_report_download.py | 0 .../shopping/add_product_partition_tree.py | 0 .../v201702/shopping/add_product_scope.py | 0 .../v201702/shopping/add_shopping_campaign.py | 0 .../add_shopping_campaign_for_showcase_ads.py | 0 .../shopping/get_product_category_taxonomy.py | 0 .../add_campaign_targeting_criteria.py | 0 .../add_demographic_targeting_criteria.py | 0 .../get_campaign_targeting_criteria.py | 0 .../get_targetable_languages_and_carriers.py | 0 .../v201702/targeting/lookup_location.py | 0 examples/adwords/v201705/__init__.py | 15 + .../v201705/account_management/__init__.py | 15 + .../account_management/accept_service_link.py | 62 +++ .../account_management/create_account.py | 63 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201705/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 222 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 126 +++++ .../add_dynamic_page_feed.py | 295 ++++++++++ .../add_dynamic_search_ads_campaign.py | 257 +++++++++ ...add_expanded_text_ad_with_upgraded_urls.py | 109 ++++ .../advanced_operations/add_html5_ad.py | 111 ++++ .../add_responsive_display_ad.py | 91 +++ .../add_universal_app_campaign.py | 217 ++++++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201705/basic_operations/__init__.py | 15 + .../v201705/basic_operations/add_ad_groups.py | 115 ++++ .../v201705/basic_operations/add_campaigns.py | 128 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201705/basic_operations/add_keywords.py | 92 +++ .../v201705/basic_operations/get_ad_groups.py | 76 +++ .../v201705/basic_operations/get_campaigns.py | 74 +++ .../get_campaigns_with_awql.py | 64 +++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201705/basic_operations/get_keywords.py | 87 +++ .../v201705/basic_operations/get_text_ads.py | 78 +++ .../v201705/basic_operations/pause_ad.py | 61 ++ .../v201705/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 58 ++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201705/campaign_management/__init__.py | 15 + ...campaign_groups_and_performance_targets.py | 152 +++++ .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 428 ++++++++++++++ .../v201705/campaign_management/add_draft.py | 81 +++ ...dd_keywords_using_incremental_batch_job.py | 259 +++++++++ .../v201705/campaign_management/add_trial.py | 116 ++++ .../get_all_disapproved_ads.py | 91 +++ .../get_all_disapproved_ads_with_awql.py | 79 +++ .../get_campaigns_by_label.py | 85 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201705/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 131 +++++ .../handle_policy_violation_error.py | 167 ++++++ .../adwords/v201705/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../adwords/v201705/extensions/add_prices.py | 157 ++++++ .../v201705/extensions/add_site_links.py | 146 +++++ .../extensions/add_site_links_using_feeds.py | 236 ++++++++ .../adwords/v201705/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 527 ++++++++++++++++++ examples/adwords/v201705/misc/__init__.py | 15 + .../v201705/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201705/misc/upload_image.py | 66 +++ .../v201705/misc/upload_media_bundle.py | 59 ++ .../adwords/v201705/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 180 ++++++ ...aign_criterion_bid_modifier_simulations.py | 96 ++++ .../get_keyword_bid_simulations.py | 81 +++ .../v201705/optimization/get_keyword_ideas.py | 100 ++++ .../adwords/v201705/remarketing/__init__.py | 15 + .../v201705/remarketing/add_audience.py | 103 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_crm_based_user_list.py | 101 ++++ .../remarketing/add_rule_based_user_lists.py | 192 +++++++ .../upload_offline_call_conversions.py | 77 +++ .../remarketing/upload_offline_conversions.py | 75 +++ .../adwords/v201705/reporting/__init__.py | 15 + ...oad_criteria_report_as_stream_with_awql.py | 81 +++ ...criteria_report_as_stream_with_selector.py | 77 +++ ...oad_criteria_report_as_string_with_awql.py | 55 ++ ...criteria_report_as_string_with_selector.py | 59 ++ .../download_criteria_report_with_awql.py | 55 ++ .../download_criteria_report_with_selector.py | 60 ++ .../v201705/reporting/get_report_fields.py | 52 ++ .../reporting/parallel_report_download.py | 230 ++++++++ examples/adwords/v201705/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 281 ++++++++++ .../v201705/shopping/add_product_scope.py | 104 ++++ .../v201705/shopping/add_shopping_campaign.py | 172 ++++++ .../add_shopping_campaign_for_showcase_ads.py | 404 ++++++++++++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201705/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 126 +++++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201705/targeting/lookup_location.py | 82 +++ .../create_dfp_client_with_service_account.py | 2 +- .../create_dfp_client_without_yaml.py | 2 +- .../authentication/generate_refresh_token.py | 2 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 0 .../get_active_activity_groups.py | 0 .../get_all_activity_groups.py | 0 .../update_activity_groups.py | 0 .../dfp/v201611/activity_service/__init__.py | 0 .../activity_service/create_activities.py | 0 .../activity_service/get_active_activities.py | 0 .../activity_service/get_all_activities.py | 0 .../activity_service/update_activities.py | 0 .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 0 .../get_all_audience_segments.py | 0 .../get_first_party_audience_segments.py | 0 .../populate_first_party_audience_segments.py | 0 .../update_audience_segments.py | 0 .../dfp/v201611/base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 0 .../create_product_template_base_rates.py | 0 .../base_rate_service/get_all_base_rates.py | 0 .../get_base_rates_for_rate_card.py | 0 .../base_rate_service/update_base_rates.py | 0 .../dfp/v201611/company_service/__init__.py | 0 .../company_service/create_companies.py | 0 .../company_service/get_advertisers.py | 0 .../company_service/get_all_companies.py | 0 .../company_service/update_companies.py | 0 .../dfp/v201611/contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 0 .../contact_service/get_all_contacts.py | 0 .../contact_service/get_uninvited_contacts.py | 0 .../contact_service/update_contacts.py | 0 .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 0 ...delete_content_metadata_key_hierarchies.py | 0 ...et_all_content_metadata_key_hierarchies.py | 0 ...update_content_metadata_key_hierarchies.py | 0 .../dfp/v201611/content_service/__init__.py | 0 .../content_service/get_all_content.py | 0 .../dfp/v201611/creative_service/__init__.py | 0 .../create_creative_from_template.py | 0 .../creative_service/create_creatives.py | 0 .../create_custom_creative.py | 0 .../create_native_creative.py | 0 .../creative_service/get_all_creatives.py | 0 .../creative_service/get_image_creatives.py | 0 .../creative_service/update_creatives.py | 0 .../v201611/creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 0 .../create_creative_set.py | 0 .../get_all_creative_sets.py | 0 .../get_creative_sets_for_master_creative.py | 0 .../update_creative_set.py | 0 .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 0 .../get_system_defined_creative_templates.py | 0 .../create_creative_wrappers.py | 0 .../deactivate_creative_wrapper.py | 0 .../get_active_creative_wrappers.py | 0 .../get_all_creative_wrappers.py | 0 .../update_creative_wrappers.py | 0 .../v201611/custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 0 .../create_custom_fields.py | 0 .../deactivate_all_line_item_custom_fields.py | 0 .../get_all_custom_fields.py | 0 .../get_custom_fields_for_line_items.py | 0 .../set_line_item_custom_field_value.py | 0 .../update_custom_fields.py | 0 .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 0 .../delete_custom_targeting_keys.py | 0 .../delete_custom_targeting_values.py | 0 ...et_all_custom_targeting_keys_and_values.py | 0 ...efined_custom_targeting_keys_and_values.py | 0 .../update_custom_targeting_keys.py | 0 .../update_custom_targeting_values.py | 0 .../v201611/exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 0 .../get_all_exchange_rates.py | 0 .../get_exchange_rates_for_currency_code.py | 0 .../update_exchange_rates.py | 0 .../get_availability_forecast.py | 0 ...get_availability_forecast_for_line_item.py | 0 .../get_delivery_forecast_for_line_items.py | 0 .../dfp/v201611/inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 0 .../inventory_service/create_ad_units.py | 0 .../get_all_ad_unit_sizes.py | 0 .../inventory_service/get_all_ad_units.py | 0 .../inventory_service/update_ad_units.py | 0 .../dfp/v201611/label_service/__init__.py | 0 .../v201611/label_service/create_labels.py | 0 .../label_service/deactivate_labels.py | 0 .../label_service/get_active_labels.py | 0 .../v201611/label_service/get_all_labels.py | 0 .../v201611/label_service/update_labels.py | 0 .../__init__.py | 0 .../create_licas.py | 0 .../deactivate_licas.py | 0 .../get_all_licas.py | 0 .../get_licas_for_line_item.py | 0 .../update_licas.py | 0 .../dfp/v201611/line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 0 .../line_item_service/create_line_items.py | 0 .../create_video_line_item.py | 0 .../line_item_service/get_all_line_items.py | 0 .../get_line_items_that_need_creatives.py | 0 .../get_recently_updated_line_items.py | 0 .../target_custom_criteria.py | 0 .../line_item_service/update_line_items.py | 0 .../dfp/v201611/network_service/__init__.py | 0 .../network_service/get_all_networks.py | 0 .../network_service/make_test_network.py | 0 .../dfp/v201611/order_service/__init__.py | 0 .../v201611/order_service/approve_orders.py | 0 .../v201611/order_service/create_orders.py | 0 .../v201611/order_service/get_all_orders.py | 0 .../order_service/get_orders_starting_soon.py | 0 .../v201611/order_service/update_orders.py | 0 .../package_service/get_all_packages.py | 0 .../get_in_progress_packages.py | 0 .../placement_service/create_placements.py | 0 .../deactivate_placements.py | 0 .../get_active_placements.py | 0 .../placement_service/get_all_placements.py | 0 .../placement_service/update_placements.py | 0 .../v201611/premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 0 .../get_all_premium_rates.py | 0 .../get_premium_rates_for_rate_card.py | 0 .../update_premium_rates.py | 0 .../get_all_product_package_items.py | 0 ...oduct_package_items_for_product_package.py | 0 .../get_active_product_packages.py | 0 .../get_all_product_packages.py | 0 .../dfp/v201611/product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 0 .../product_service/get_all_products.py | 0 .../get_products_for_product_template.py | 0 ...sh_programmatic_products_to_marketplace.py | 0 .../product_service/update_products.py | 0 .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 0 .../create_product_templates.py | 0 .../create_programmatic_product_templates.py | 0 .../get_all_product_templates.py | 0 .../get_sponsorship_product_templates.py | 0 .../update_product_templates.py | 0 .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 0 ...create_programmatic_proposal_line_items.py | 0 ...sal_line_items_for_non_sales_management.py | 0 .../create_proposal_line_items.py | 0 .../get_all_proposal_line_items.py | 0 .../get_proposal_line_items_for_proposal.py | 0 .../update_proposal_line_items.py | 0 .../dfp/v201611/proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 0 ...atic_proposals_for_non_sales_management.py | 0 .../proposal_service/create_proposals.py | 0 .../proposal_service/get_all_proposals.py | 0 .../get_marketplace_comments.py | 0 .../get_proposals_pending_approval.py | 0 .../request_buyers_acceptance.py | 0 .../submit_proposals_for_approval.py | 0 .../proposal_service/update_proposals.py | 0 .../__init__.py | 0 .../fetch_match_tables.py | 0 .../get_all_programmatic_buyers.py | 0 .../dfp/v201611/rate_card_service/__init__.py | 0 .../rate_card_service/get_all_rate_cards.py | 0 .../get_marketplace_rate_cards.py | 0 ..._item_reports_for_reconciliation_report.py | 0 ...order_reports_for_reconciliation_report.py | 0 ...n_report_rows_for_reconciliation_report.py | 0 .../get_all_reconciliation_reports.py | 0 ...iliation_report_for_last_billing_period.py | 0 .../dfp/v201611/report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 0 .../report_service/run_inventory_report.py | 0 .../report_service/run_reach_report.py | 0 .../run_report_with_custom_fields.py | 0 .../report_service/run_sales_report.py | 0 .../v201611/report_service/run_saved_query.py | 0 .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 0 .../get_all_suggested_ad_units.py | 0 ...get_highly_requested_suggested_ad_units.py | 0 examples/dfp/v201611/team_service/__init__.py | 0 .../dfp/v201611/team_service/create_teams.py | 0 .../dfp/v201611/team_service/get_all_teams.py | 0 .../dfp/v201611/team_service/update_teams.py | 0 examples/dfp/v201611/user_service/__init__.py | 0 .../dfp/v201611/user_service/create_users.py | 0 .../v201611/user_service/deactivate_users.py | 0 .../dfp/v201611/user_service/get_all_roles.py | 0 .../dfp/v201611/user_service/get_all_users.py | 0 .../user_service/get_user_by_email_address.py | 0 .../dfp/v201611/user_service/update_users.py | 0 .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 0 .../delete_user_team_associations.py | 0 .../get_all_user_team_associations.py | 0 .../get_user_team_associations_for_user.py | 0 .../update_user_team_associations.py | 0 .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 0 .../get_workflow_approval_requests.py | 0 ...et_workflow_external_condition_requests.py | 0 ...er_workflow_external_condition_requests.py | 0 .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 0 .../get_active_activity_groups.py | 0 .../get_all_activity_groups.py | 0 .../update_activity_groups.py | 0 .../dfp/v201702/activity_service/__init__.py | 0 .../activity_service/create_activities.py | 0 .../activity_service/get_active_activities.py | 0 .../activity_service/get_all_activities.py | 0 .../activity_service/update_activities.py | 0 .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 0 .../get_all_audience_segments.py | 0 .../get_first_party_audience_segments.py | 0 .../populate_first_party_audience_segments.py | 0 .../update_audience_segments.py | 0 .../dfp/v201702/base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 0 .../create_product_package_item_base_rates.py | 2 +- .../create_product_template_base_rates.py | 0 .../base_rate_service/get_all_base_rates.py | 0 .../get_base_rates_for_rate_card.py | 0 .../base_rate_service/update_base_rates.py | 0 .../dfp/v201702/company_service/__init__.py | 0 .../company_service/create_companies.py | 0 .../company_service/get_advertisers.py | 0 .../company_service/get_all_companies.py | 0 .../company_service/update_companies.py | 0 .../dfp/v201702/contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 0 .../contact_service/get_all_contacts.py | 0 .../contact_service/get_uninvited_contacts.py | 0 .../contact_service/update_contacts.py | 0 .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 0 ...delete_content_metadata_key_hierarchies.py | 0 ...et_all_content_metadata_key_hierarchies.py | 0 ...update_content_metadata_key_hierarchies.py | 0 .../dfp/v201702/content_service/__init__.py | 0 .../content_service/get_all_content.py | 0 .../dfp/v201702/creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 0 .../creative_service/create_creatives.py | 0 .../create_custom_creative.py | 0 .../create_native_creative.py | 0 .../creative_service/get_all_creatives.py | 0 .../creative_service/get_image_creatives.py | 0 .../creative_service/update_creatives.py | 0 .../v201702/creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 0 .../create_creative_set.py | 0 .../get_all_creative_sets.py | 0 .../get_creative_sets_for_master_creative.py | 0 .../update_creative_set.py | 0 .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 0 .../get_system_defined_creative_templates.py | 0 .../create_creative_wrappers.py | 0 .../deactivate_creative_wrapper.py | 0 .../get_active_creative_wrappers.py | 0 .../get_all_creative_wrappers.py | 0 .../update_creative_wrappers.py | 0 .../v201702/custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 0 .../create_custom_fields.py | 0 .../deactivate_all_line_item_custom_fields.py | 0 .../get_all_custom_fields.py | 0 .../get_custom_fields_for_line_items.py | 0 .../set_line_item_custom_field_value.py | 0 .../update_custom_fields.py | 0 .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 0 .../delete_custom_targeting_keys.py | 0 .../delete_custom_targeting_values.py | 0 ...et_all_custom_targeting_keys_and_values.py | 0 ...efined_custom_targeting_keys_and_values.py | 0 .../update_custom_targeting_keys.py | 0 .../update_custom_targeting_values.py | 0 .../v201702/exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 0 .../get_all_exchange_rates.py | 0 .../get_exchange_rates_for_currency_code.py | 0 .../update_exchange_rates.py | 0 .../get_availability_forecast.py | 0 ...get_availability_forecast_for_line_item.py | 0 .../get_delivery_forecast_for_line_items.py | 0 .../dfp/v201702/inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 0 .../inventory_service/create_ad_units.py | 0 .../get_all_ad_unit_sizes.py | 0 .../inventory_service/get_all_ad_units.py | 0 .../inventory_service/update_ad_units.py | 0 .../dfp/v201702/label_service/__init__.py | 0 .../v201702/label_service/create_labels.py | 0 .../label_service/deactivate_labels.py | 0 .../label_service/get_active_labels.py | 0 .../v201702/label_service/get_all_labels.py | 0 .../v201702/label_service/update_labels.py | 0 .../__init__.py | 0 .../create_licas.py | 0 .../deactivate_licas.py | 0 .../get_all_licas.py | 0 .../get_licas_for_line_item.py | 0 .../update_licas.py | 0 .../dfp/v201702/line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 0 .../line_item_service/create_line_items.py | 0 .../create_video_line_item.py | 0 .../line_item_service/get_all_line_items.py | 0 .../get_line_items_that_need_creatives.py | 0 .../get_recently_updated_line_items.py | 0 .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 0 .../line_item_service/update_line_items.py | 0 .../v201702/native_style_service/__init__.py | 0 .../create_native_styles.py | 0 .../get_all_native_styles.py | 0 .../dfp/v201702/network_service/__init__.py | 0 .../network_service/get_all_networks.py | 0 .../network_service/make_test_network.py | 0 .../dfp/v201702/order_service/__init__.py | 0 .../v201702/order_service/approve_orders.py | 0 .../v201702/order_service/create_orders.py | 0 .../v201702/order_service/get_all_orders.py | 0 .../order_service/get_orders_starting_soon.py | 0 .../v201702/order_service/update_orders.py | 0 .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 0 .../get_in_progress_packages.py | 0 .../placement_service/create_placements.py | 0 .../deactivate_placements.py | 0 .../get_active_placements.py | 0 .../placement_service/get_all_placements.py | 0 .../placement_service/update_placements.py | 0 .../v201702/premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 0 .../get_all_premium_rates.py | 0 .../get_premium_rates_for_rate_card.py | 0 .../update_premium_rates.py | 0 .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 0 ...oduct_package_items_for_product_package.py | 0 .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 0 .../get_all_product_packages.py | 0 .../dfp/v201702/product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 0 .../product_service/get_all_products.py | 0 .../get_products_for_product_template.py | 0 ...sh_programmatic_products_to_marketplace.py | 0 .../product_service/update_products.py | 0 .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 0 .../create_product_templates.py | 0 .../create_programmatic_product_templates.py | 0 .../get_all_product_templates.py | 0 .../get_sponsorship_product_templates.py | 0 .../update_product_templates.py | 0 .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 0 ...create_programmatic_proposal_line_items.py | 0 ...sal_line_items_for_non_sales_management.py | 0 .../create_proposal_line_items.py | 0 .../get_all_proposal_line_items.py | 0 .../get_proposal_line_items_for_proposal.py | 0 .../update_proposal_line_items.py | 0 .../dfp/v201702/proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 0 ...atic_proposals_for_non_sales_management.py | 0 .../proposal_service/create_proposals.py | 0 .../proposal_service/get_all_proposals.py | 0 .../get_marketplace_comments.py | 0 .../get_proposals_pending_approval.py | 0 .../request_buyers_acceptance.py | 0 .../submit_proposals_for_approval.py | 0 .../proposal_service/update_proposals.py | 0 .../__init__.py | 0 .../fetch_match_tables.py | 0 .../get_all_programmatic_buyers.py | 0 .../get_recent_changes.py | 0 .../dfp/v201702/rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 0 .../get_marketplace_rate_cards.py | 0 ..._item_reports_for_reconciliation_report.py | 0 ...update_reconciliation_line_item_reports.py | 0 ...order_reports_for_reconciliation_report.py | 0 .../submit_reconciliation_order_reports.py | 0 ...n_report_rows_for_reconciliation_report.py | 0 .../update_reconciliation_report_rows.py | 0 .../get_all_reconciliation_reports.py | 0 ...iliation_report_for_last_billing_period.py | 0 .../dfp/v201702/report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 0 .../report_service/run_inventory_report.py | 0 .../report_service/run_reach_report.py | 0 .../run_report_with_custom_fields.py | 0 .../report_service/run_sales_report.py | 0 .../v201702/report_service/run_saved_query.py | 0 .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 0 .../get_all_suggested_ad_units.py | 0 ...get_highly_requested_suggested_ad_units.py | 0 examples/dfp/v201702/team_service/__init__.py | 0 .../dfp/v201702/team_service/create_teams.py | 0 .../dfp/v201702/team_service/get_all_teams.py | 0 .../dfp/v201702/team_service/update_teams.py | 0 examples/dfp/v201702/user_service/__init__.py | 0 .../dfp/v201702/user_service/create_users.py | 0 .../v201702/user_service/deactivate_users.py | 0 .../dfp/v201702/user_service/get_all_roles.py | 0 .../dfp/v201702/user_service/get_all_users.py | 0 .../v201702/user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 0 .../dfp/v201702/user_service/update_users.py | 0 .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 0 .../delete_user_team_associations.py | 0 .../get_all_user_team_associations.py | 0 .../get_user_team_associations_for_user.py | 0 .../update_user_team_associations.py | 0 .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 0 .../get_workflow_approval_requests.py | 0 ...et_workflow_external_condition_requests.py | 0 ...er_workflow_external_condition_requests.py | 0 .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 0 .../get_active_activity_groups.py | 0 .../get_all_activity_groups.py | 0 .../update_activity_groups.py | 0 .../dfp/v201705/activity_service/__init__.py | 0 .../activity_service/create_activities.py | 0 .../activity_service/get_active_activities.py | 0 .../activity_service/get_all_activities.py | 0 .../activity_service/update_activities.py | 0 .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 0 .../get_all_audience_segments.py | 0 .../get_first_party_audience_segments.py | 0 .../populate_first_party_audience_segments.py | 0 .../update_audience_segments.py | 0 .../dfp/v201705/base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 4 +- .../create_product_package_item_base_rates.py | 6 +- .../create_product_template_base_rates.py | 4 +- .../base_rate_service/get_all_base_rates.py | 0 .../get_base_rates_for_rate_card.py | 0 .../base_rate_service/update_base_rates.py | 0 .../dfp/v201705/company_service/__init__.py | 0 .../company_service/create_companies.py | 0 .../company_service/get_advertisers.py | 0 .../company_service/get_all_companies.py | 0 .../company_service/update_companies.py | 0 .../dfp/v201705/contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 0 .../contact_service/get_all_contacts.py | 0 .../contact_service/get_uninvited_contacts.py | 0 .../contact_service/update_contacts.py | 0 .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 0 ...delete_content_metadata_key_hierarchies.py | 0 ...et_all_content_metadata_key_hierarchies.py | 0 ...update_content_metadata_key_hierarchies.py | 0 .../dfp/v201705/content_service/__init__.py | 0 .../content_service/get_all_content.py | 0 .../dfp/v201705/creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 0 .../creative_service/create_creatives.py | 0 .../create_custom_creative.py | 0 .../create_native_creative.py | 0 .../creative_service/get_all_creatives.py | 0 .../creative_service/get_image_creatives.py | 0 .../creative_service/update_creatives.py | 0 .../v201705/creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 0 .../create_creative_set.py | 0 .../get_all_creative_sets.py | 0 .../get_creative_sets_for_master_creative.py | 0 .../update_creative_set.py | 0 .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 0 .../get_system_defined_creative_templates.py | 0 .../create_creative_wrappers.py | 0 .../deactivate_creative_wrapper.py | 0 .../get_active_creative_wrappers.py | 0 .../get_all_creative_wrappers.py | 0 .../update_creative_wrappers.py | 0 .../v201705/custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 0 .../create_custom_fields.py | 0 .../deactivate_all_line_item_custom_fields.py | 0 .../get_all_custom_fields.py | 0 .../get_custom_fields_for_line_items.py | 0 .../set_line_item_custom_field_value.py | 0 .../update_custom_fields.py | 0 .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 0 .../delete_custom_targeting_keys.py | 0 .../delete_custom_targeting_values.py | 0 ...et_all_custom_targeting_keys_and_values.py | 0 ...efined_custom_targeting_keys_and_values.py | 0 .../update_custom_targeting_keys.py | 0 .../update_custom_targeting_values.py | 0 .../v201705/exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 0 .../get_all_exchange_rates.py | 0 .../get_exchange_rates_for_currency_code.py | 0 .../update_exchange_rates.py | 0 .../get_availability_forecast.py | 0 ...get_availability_forecast_for_line_item.py | 0 .../get_delivery_forecast_for_line_items.py | 0 .../dfp/v201705/inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 0 .../inventory_service/create_ad_units.py | 0 .../get_all_ad_unit_sizes.py | 0 .../inventory_service/get_all_ad_units.py | 0 .../inventory_service/update_ad_units.py | 0 .../dfp/v201705/label_service/__init__.py | 0 .../v201705/label_service/create_labels.py | 0 .../label_service/deactivate_labels.py | 0 .../label_service/get_active_labels.py | 0 .../v201705/label_service/get_all_labels.py | 0 .../v201705/label_service/update_labels.py | 0 .../__init__.py | 0 .../create_licas.py | 0 .../deactivate_licas.py | 0 .../get_all_licas.py | 0 .../get_licas_for_line_item.py | 0 .../update_licas.py | 0 .../dfp/v201705/line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 0 .../line_item_service/create_line_items.py | 0 .../create_video_line_item.py | 0 .../line_item_service/get_all_line_items.py | 0 .../get_line_items_that_need_creatives.py | 0 .../get_recently_updated_line_items.py | 0 .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 0 .../line_item_service/update_line_items.py | 0 .../v201705/native_style_service/__init__.py | 0 .../create_native_styles.py | 0 .../get_all_native_styles.py | 0 .../dfp/v201705/network_service/__init__.py | 0 .../network_service/get_all_networks.py | 0 .../network_service/make_test_network.py | 0 .../dfp/v201705/order_service/__init__.py | 0 .../v201705/order_service/approve_orders.py | 0 .../v201705/order_service/create_orders.py | 0 .../v201705/order_service/get_all_orders.py | 0 .../order_service/get_orders_starting_soon.py | 0 .../v201705/order_service/update_orders.py | 0 .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 0 .../get_in_progress_packages.py | 0 .../placement_service/create_placements.py | 0 .../deactivate_placements.py | 0 .../get_active_placements.py | 0 .../placement_service/get_all_placements.py | 0 .../placement_service/update_placements.py | 0 .../v201705/premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 5 +- .../get_all_premium_rates.py | 0 .../get_premium_rates_for_rate_card.py | 0 .../update_premium_rates.py | 0 .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 0 ...oduct_package_items_for_product_package.py | 0 .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 0 .../get_all_product_packages.py | 0 .../dfp/v201705/product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 0 .../product_service/get_all_products.py | 0 .../get_products_for_product_template.py | 0 ...sh_programmatic_products_to_marketplace.py | 0 .../product_service/update_products.py | 0 .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 0 .../create_product_templates.py | 0 .../create_programmatic_product_templates.py | 0 .../get_all_product_templates.py | 0 .../get_sponsorship_product_templates.py | 0 .../update_product_templates.py | 0 .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 0 ...create_programmatic_proposal_line_items.py | 0 ...sal_line_items_for_non_sales_management.py | 0 .../create_proposal_line_items.py | 0 .../get_all_proposal_line_items.py | 0 .../get_proposal_line_items_for_proposal.py | 0 .../update_proposal_line_items.py | 0 .../dfp/v201705/proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 0 ...atic_proposals_for_non_sales_management.py | 0 .../proposal_service/create_proposals.py | 0 .../proposal_service/get_all_proposals.py | 0 .../get_marketplace_comments.py | 0 .../get_proposals_pending_approval.py | 0 .../request_buyers_acceptance.py | 0 .../submit_proposals_for_approval.py | 0 .../proposal_service/update_proposals.py | 0 .../__init__.py | 0 .../fetch_match_tables.py | 0 .../get_all_programmatic_buyers.py | 0 .../get_recent_changes.py | 0 .../dfp/v201705/rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 0 .../get_marketplace_rate_cards.py | 0 ..._item_reports_for_reconciliation_report.py | 0 ...update_reconciliation_line_item_reports.py | 0 ...order_reports_for_reconciliation_report.py | 0 .../submit_reconciliation_order_reports.py | 0 ...n_report_rows_for_reconciliation_report.py | 0 .../update_reconciliation_report_rows.py | 0 .../get_all_reconciliation_reports.py | 0 ...iliation_report_for_last_billing_period.py | 12 +- .../dfp/v201705/report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 0 .../report_service/run_inventory_report.py | 0 .../report_service/run_reach_report.py | 0 .../run_report_with_custom_fields.py | 0 .../report_service/run_sales_report.py | 0 .../v201705/report_service/run_saved_query.py | 0 .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 0 .../get_all_suggested_ad_units.py | 0 ...get_highly_requested_suggested_ad_units.py | 0 examples/dfp/v201705/team_service/__init__.py | 0 .../dfp/v201705/team_service/create_teams.py | 0 .../dfp/v201705/team_service/get_all_teams.py | 0 .../dfp/v201705/team_service/update_teams.py | 0 examples/dfp/v201705/user_service/__init__.py | 0 .../dfp/v201705/user_service/create_users.py | 0 .../v201705/user_service/deactivate_users.py | 0 .../dfp/v201705/user_service/get_all_roles.py | 0 .../dfp/v201705/user_service/get_all_users.py | 0 .../v201705/user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 0 .../dfp/v201705/user_service/update_users.py | 0 .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 0 .../delete_user_team_associations.py | 0 .../get_all_user_team_associations.py | 0 .../get_user_team_associations_for_user.py | 0 .../update_user_team_associations.py | 0 .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 0 .../get_workflow_approval_requests.py | 0 ...et_workflow_external_condition_requests.py | 0 ...er_workflow_external_condition_requests.py | 0 googleads/adwords.py | 49 ++ googleads/common.py | 2 +- setup.py | 0 1044 files changed, 10741 insertions(+), 60 deletions(-) mode change 100644 => 100755 examples/adwords/v201607/account_management/create_account.py mode change 100644 => 100755 examples/adwords/v201607/account_management/get_account_changes.py mode change 100644 => 100755 examples/adwords/v201607/account_management/get_account_hierarchy.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/add_ad_customizer.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/add_html5_ad.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/add_ad_groups.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/add_campaigns.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/add_expanded_text_ads.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/add_keywords.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/add_text_ads.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/get_ad_groups.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/get_campaigns.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/get_expanded_text_ads.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/get_keywords.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/get_text_ads.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/pause_ad.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/remove_ad.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/remove_ad_group.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/remove_campaign.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/remove_keyword.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/update_ad_group.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/update_campaign.py mode change 100644 => 100755 examples/adwords/v201607/basic_operations/update_keyword.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/add_campaign_labels.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/add_draft.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/add_experiment.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/add_trial.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/get_campaigns_by_label.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/graduate_trial.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/promote_experiment.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/set_ad_parameters.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201607/campaign_management/validate_text_ad.py mode change 100644 => 100755 examples/adwords/v201607/error_handling/handle_partial_failures.py mode change 100644 => 100755 examples/adwords/v201607/error_handling/handle_policy_violation_error.py mode change 100644 => 100755 examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py mode change 100644 => 100755 examples/adwords/v201607/extensions/add_prices.py mode change 100644 => 100755 examples/adwords/v201607/extensions/add_site_links.py mode change 100644 => 100755 examples/adwords/v201607/extensions/add_site_links_using_feeds.py mode change 100644 => 100755 examples/adwords/v201607/migration/migrate_to_extension_settings.py mode change 100644 => 100755 examples/adwords/v201607/misc/get_all_images_and_videos.py mode change 100644 => 100755 examples/adwords/v201607/misc/upload_image.py mode change 100644 => 100755 examples/adwords/v201607/misc/upload_media_bundle.py mode change 100644 => 100755 examples/adwords/v201607/optimization/estimate_keyword_traffic.py mode change 100644 => 100755 examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py mode change 100644 => 100755 examples/adwords/v201607/optimization/get_keyword_bid_simulations.py mode change 100644 => 100755 examples/adwords/v201607/optimization/get_keyword_ideas.py mode change 100644 => 100755 examples/adwords/v201607/remarketing/add_audience.py mode change 100644 => 100755 examples/adwords/v201607/remarketing/add_conversion_tracker.py mode change 100644 => 100755 examples/adwords/v201607/remarketing/add_crm_based_user_list.py mode change 100644 => 100755 examples/adwords/v201607/remarketing/add_rule_based_user_lists.py mode change 100644 => 100755 examples/adwords/v201607/remarketing/upload_offline_conversions.py mode change 100644 => 100755 examples/adwords/v201607/reporting/download_criteria_report.py mode change 100644 => 100755 examples/adwords/v201607/reporting/download_criteria_report_as_stream.py mode change 100644 => 100755 examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py mode change 100644 => 100755 examples/adwords/v201607/reporting/download_criteria_report_as_string.py mode change 100644 => 100755 examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py mode change 100644 => 100755 examples/adwords/v201607/reporting/download_criteria_report_with_awql.py mode change 100644 => 100755 examples/adwords/v201607/reporting/get_report_fields.py mode change 100644 => 100755 examples/adwords/v201607/reporting/parallel_report_download.py mode change 100644 => 100755 examples/adwords/v201607/shopping/add_product_partition_tree.py mode change 100644 => 100755 examples/adwords/v201607/shopping/add_product_scope.py mode change 100644 => 100755 examples/adwords/v201607/shopping/add_shopping_campaign.py mode change 100644 => 100755 examples/adwords/v201607/shopping/get_product_category_taxonomy.py mode change 100644 => 100755 examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py mode change 100644 => 100755 examples/adwords/v201607/targeting/lookup_location.py mode change 100644 => 100755 examples/adwords/v201609/account_management/accept_service_link.py mode change 100644 => 100755 examples/adwords/v201609/account_management/create_account.py mode change 100644 => 100755 examples/adwords/v201609/account_management/get_account_changes.py mode change 100644 => 100755 examples/adwords/v201609/account_management/get_account_hierarchy.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/add_ad_customizer.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/add_html5_ad.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/add_ad_groups.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/add_campaigns.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/add_expanded_text_ads.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/add_keywords.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/get_ad_groups.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/get_campaigns.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/get_expanded_text_ads.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/get_keywords.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/get_text_ads.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/pause_ad.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/remove_ad.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/remove_ad_group.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/remove_campaign.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/remove_keyword.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/update_ad_group.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/update_campaign.py mode change 100644 => 100755 examples/adwords/v201609/basic_operations/update_keyword.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/add_campaign_labels.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/add_draft.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/add_trial.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/get_campaigns_by_label.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/graduate_trial.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/set_ad_parameters.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201609/campaign_management/validate_text_ad.py mode change 100644 => 100755 examples/adwords/v201609/error_handling/handle_partial_failures.py mode change 100644 => 100755 examples/adwords/v201609/error_handling/handle_policy_violation_error.py mode change 100644 => 100755 examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py mode change 100644 => 100755 examples/adwords/v201609/extensions/add_prices.py mode change 100644 => 100755 examples/adwords/v201609/extensions/add_site_links.py mode change 100644 => 100755 examples/adwords/v201609/extensions/add_site_links_using_feeds.py mode change 100644 => 100755 examples/adwords/v201609/migration/migrate_to_extension_settings.py mode change 100644 => 100755 examples/adwords/v201609/misc/get_all_images_and_videos.py mode change 100644 => 100755 examples/adwords/v201609/misc/upload_image.py mode change 100644 => 100755 examples/adwords/v201609/misc/upload_media_bundle.py mode change 100644 => 100755 examples/adwords/v201609/optimization/estimate_keyword_traffic.py mode change 100644 => 100755 examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py mode change 100644 => 100755 examples/adwords/v201609/optimization/get_keyword_bid_simulations.py mode change 100644 => 100755 examples/adwords/v201609/optimization/get_keyword_ideas.py mode change 100644 => 100755 examples/adwords/v201609/remarketing/add_audience.py mode change 100644 => 100755 examples/adwords/v201609/remarketing/add_conversion_tracker.py mode change 100644 => 100755 examples/adwords/v201609/remarketing/add_crm_based_user_list.py mode change 100644 => 100755 examples/adwords/v201609/remarketing/add_rule_based_user_lists.py mode change 100644 => 100755 examples/adwords/v201609/remarketing/upload_offline_call_conversions.py mode change 100644 => 100755 examples/adwords/v201609/remarketing/upload_offline_conversions.py mode change 100644 => 100755 examples/adwords/v201609/reporting/download_criteria_report.py mode change 100644 => 100755 examples/adwords/v201609/reporting/download_criteria_report_as_stream.py mode change 100644 => 100755 examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py mode change 100644 => 100755 examples/adwords/v201609/reporting/download_criteria_report_as_string.py mode change 100644 => 100755 examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py mode change 100644 => 100755 examples/adwords/v201609/reporting/download_criteria_report_with_awql.py mode change 100644 => 100755 examples/adwords/v201609/reporting/get_report_fields.py mode change 100644 => 100755 examples/adwords/v201609/reporting/parallel_report_download.py mode change 100644 => 100755 examples/adwords/v201609/shopping/add_product_partition_tree.py mode change 100644 => 100755 examples/adwords/v201609/shopping/add_product_scope.py mode change 100644 => 100755 examples/adwords/v201609/shopping/add_shopping_campaign.py mode change 100644 => 100755 examples/adwords/v201609/shopping/get_product_category_taxonomy.py mode change 100644 => 100755 examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py mode change 100644 => 100755 examples/adwords/v201609/targeting/lookup_location.py mode change 100644 => 100755 examples/adwords/v201702/account_management/accept_service_link.py mode change 100644 => 100755 examples/adwords/v201702/account_management/create_account.py mode change 100644 => 100755 examples/adwords/v201702/account_management/get_account_changes.py mode change 100644 => 100755 examples/adwords/v201702/account_management/get_account_hierarchy.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/add_ad_customizer.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/add_html5_ad.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/add_ad_groups.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/add_campaigns.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/add_expanded_text_ads.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/add_keywords.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/get_ad_groups.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/get_campaigns.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/get_expanded_text_ads.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/get_keywords.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/get_text_ads.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/pause_ad.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/remove_ad.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/remove_ad_group.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/remove_campaign.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/remove_keyword.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/update_ad_group.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/update_campaign.py mode change 100644 => 100755 examples/adwords/v201702/basic_operations/update_keyword.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/add_campaign_labels.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/add_draft.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/add_trial.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/get_campaigns_by_label.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/graduate_trial.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/set_ad_parameters.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py mode change 100644 => 100755 examples/adwords/v201702/campaign_management/validate_text_ad.py mode change 100644 => 100755 examples/adwords/v201702/error_handling/handle_partial_failures.py mode change 100644 => 100755 examples/adwords/v201702/error_handling/handle_policy_violation_error.py mode change 100644 => 100755 examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py mode change 100644 => 100755 examples/adwords/v201702/extensions/add_prices.py mode change 100644 => 100755 examples/adwords/v201702/extensions/add_site_links.py mode change 100644 => 100755 examples/adwords/v201702/extensions/add_site_links_using_feeds.py mode change 100644 => 100755 examples/adwords/v201702/migration/migrate_to_extension_settings.py mode change 100644 => 100755 examples/adwords/v201702/misc/get_all_images_and_videos.py mode change 100644 => 100755 examples/adwords/v201702/misc/upload_image.py mode change 100644 => 100755 examples/adwords/v201702/misc/upload_media_bundle.py mode change 100644 => 100755 examples/adwords/v201702/optimization/estimate_keyword_traffic.py mode change 100644 => 100755 examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py mode change 100644 => 100755 examples/adwords/v201702/optimization/get_keyword_bid_simulations.py mode change 100644 => 100755 examples/adwords/v201702/optimization/get_keyword_ideas.py mode change 100644 => 100755 examples/adwords/v201702/remarketing/add_audience.py mode change 100644 => 100755 examples/adwords/v201702/remarketing/add_conversion_tracker.py mode change 100644 => 100755 examples/adwords/v201702/remarketing/add_crm_based_user_list.py mode change 100644 => 100755 examples/adwords/v201702/remarketing/add_rule_based_user_lists.py mode change 100644 => 100755 examples/adwords/v201702/remarketing/upload_offline_call_conversions.py mode change 100644 => 100755 examples/adwords/v201702/remarketing/upload_offline_conversions.py mode change 100644 => 100755 examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py mode change 100644 => 100755 examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py mode change 100644 => 100755 examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py mode change 100644 => 100755 examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py mode change 100644 => 100755 examples/adwords/v201702/reporting/download_criteria_report_with_awql.py mode change 100644 => 100755 examples/adwords/v201702/reporting/download_criteria_report_with_selector.py mode change 100644 => 100755 examples/adwords/v201702/reporting/get_report_fields.py mode change 100644 => 100755 examples/adwords/v201702/reporting/parallel_report_download.py mode change 100644 => 100755 examples/adwords/v201702/shopping/add_product_partition_tree.py mode change 100644 => 100755 examples/adwords/v201702/shopping/add_product_scope.py mode change 100644 => 100755 examples/adwords/v201702/shopping/add_shopping_campaign.py mode change 100644 => 100755 examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py mode change 100644 => 100755 examples/adwords/v201702/shopping/get_product_category_taxonomy.py mode change 100644 => 100755 examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py mode change 100644 => 100755 examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py mode change 100644 => 100755 examples/adwords/v201702/targeting/lookup_location.py create mode 100644 examples/adwords/v201705/__init__.py create mode 100644 examples/adwords/v201705/account_management/__init__.py create mode 100755 examples/adwords/v201705/account_management/accept_service_link.py create mode 100755 examples/adwords/v201705/account_management/create_account.py create mode 100755 examples/adwords/v201705/account_management/get_account_changes.py create mode 100755 examples/adwords/v201705/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201705/advanced_operations/__init__.py create mode 100755 examples/adwords/v201705/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201705/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201705/advanced_operations/add_dynamic_page_feed.py create mode 100755 examples/adwords/v201705/advanced_operations/add_dynamic_search_ads_campaign.py create mode 100755 examples/adwords/v201705/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201705/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201705/advanced_operations/add_universal_app_campaign.py create mode 100755 examples/adwords/v201705/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201705/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201705/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201705/basic_operations/__init__.py create mode 100755 examples/adwords/v201705/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201705/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201705/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201705/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201705/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201705/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201705/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201705/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201705/basic_operations/get_text_ads.py create mode 100755 examples/adwords/v201705/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201705/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201705/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201705/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201705/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201705/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201705/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201705/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201705/campaign_management/__init__.py create mode 100755 examples/adwords/v201705/campaign_management/add_campaign_groups_and_performance_targets.py create mode 100755 examples/adwords/v201705/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201705/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201705/campaign_management/add_draft.py create mode 100755 examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201705/campaign_management/add_trial.py create mode 100755 examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201705/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201705/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201705/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201705/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201705/error_handling/__init__.py create mode 100755 examples/adwords/v201705/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201705/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201705/extensions/__init__.py create mode 100755 examples/adwords/v201705/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201705/extensions/add_prices.py create mode 100755 examples/adwords/v201705/extensions/add_site_links.py create mode 100755 examples/adwords/v201705/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201705/migration/__init__.py create mode 100755 examples/adwords/v201705/migration/migrate_to_extension_settings.py create mode 100644 examples/adwords/v201705/misc/__init__.py create mode 100755 examples/adwords/v201705/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201705/misc/upload_image.py create mode 100755 examples/adwords/v201705/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201705/optimization/__init__.py create mode 100755 examples/adwords/v201705/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201705/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201705/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201705/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201705/remarketing/__init__.py create mode 100755 examples/adwords/v201705/remarketing/add_audience.py create mode 100755 examples/adwords/v201705/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201705/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201705/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201705/remarketing/upload_offline_call_conversions.py create mode 100755 examples/adwords/v201705/remarketing/upload_offline_conversions.py create mode 100644 examples/adwords/v201705/reporting/__init__.py create mode 100755 examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_selector.py create mode 100755 examples/adwords/v201705/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201705/reporting/download_criteria_report_as_string_with_selector.py create mode 100755 examples/adwords/v201705/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201705/reporting/download_criteria_report_with_selector.py create mode 100755 examples/adwords/v201705/reporting/get_report_fields.py create mode 100755 examples/adwords/v201705/reporting/parallel_report_download.py create mode 100644 examples/adwords/v201705/shopping/__init__.py create mode 100755 examples/adwords/v201705/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201705/shopping/add_product_scope.py create mode 100755 examples/adwords/v201705/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py create mode 100755 examples/adwords/v201705/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201705/targeting/__init__.py create mode 100755 examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201705/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201705/targeting/lookup_location.py mode change 100644 => 100755 examples/dfp/v201611/activity_group_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/activity_group_service/create_activity_groups.py mode change 100644 => 100755 examples/dfp/v201611/activity_group_service/get_active_activity_groups.py mode change 100644 => 100755 examples/dfp/v201611/activity_group_service/get_all_activity_groups.py mode change 100644 => 100755 examples/dfp/v201611/activity_group_service/update_activity_groups.py mode change 100644 => 100755 examples/dfp/v201611/activity_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/activity_service/create_activities.py mode change 100644 => 100755 examples/dfp/v201611/activity_service/get_active_activities.py mode change 100644 => 100755 examples/dfp/v201611/activity_service/get_all_activities.py mode change 100644 => 100755 examples/dfp/v201611/activity_service/update_activities.py mode change 100644 => 100755 examples/dfp/v201611/audience_segment_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/audience_segment_service/create_audience_segments.py mode change 100644 => 100755 examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py mode change 100644 => 100755 examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py mode change 100644 => 100755 examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py mode change 100644 => 100755 examples/dfp/v201611/audience_segment_service/update_audience_segments.py mode change 100644 => 100755 examples/dfp/v201611/base_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/base_rate_service/create_product_base_rates.py mode change 100644 => 100755 examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py mode change 100644 => 100755 examples/dfp/v201611/base_rate_service/get_all_base_rates.py mode change 100644 => 100755 examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py mode change 100644 => 100755 examples/dfp/v201611/base_rate_service/update_base_rates.py mode change 100644 => 100755 examples/dfp/v201611/company_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/company_service/create_companies.py mode change 100644 => 100755 examples/dfp/v201611/company_service/get_advertisers.py mode change 100644 => 100755 examples/dfp/v201611/company_service/get_all_companies.py mode change 100644 => 100755 examples/dfp/v201611/company_service/update_companies.py mode change 100644 => 100755 examples/dfp/v201611/contact_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/contact_service/create_contacts.py mode change 100644 => 100755 examples/dfp/v201611/contact_service/get_all_contacts.py mode change 100644 => 100755 examples/dfp/v201611/contact_service/get_uninvited_contacts.py mode change 100644 => 100755 examples/dfp/v201611/contact_service/update_contacts.py mode change 100644 => 100755 examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201611/content_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/content_service/get_all_content.py mode change 100644 => 100755 examples/dfp/v201611/creative_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/creative_service/create_creative_from_template.py mode change 100644 => 100755 examples/dfp/v201611/creative_service/create_creatives.py mode change 100644 => 100755 examples/dfp/v201611/creative_service/create_custom_creative.py mode change 100644 => 100755 examples/dfp/v201611/creative_service/create_native_creative.py mode change 100644 => 100755 examples/dfp/v201611/creative_service/get_all_creatives.py mode change 100644 => 100755 examples/dfp/v201611/creative_service/get_image_creatives.py mode change 100644 => 100755 examples/dfp/v201611/creative_service/update_creatives.py mode change 100644 => 100755 examples/dfp/v201611/creative_set_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py mode change 100644 => 100755 examples/dfp/v201611/creative_set_service/create_creative_set.py mode change 100644 => 100755 examples/dfp/v201611/creative_set_service/get_all_creative_sets.py mode change 100644 => 100755 examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py mode change 100644 => 100755 examples/dfp/v201611/creative_set_service/update_creative_set.py mode change 100644 => 100755 examples/dfp/v201611/creative_template_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/creative_template_service/get_all_creative_templates.py mode change 100644 => 100755 examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py mode change 100644 => 100755 examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py mode change 100644 => 100755 examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201611/custom_field_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/custom_field_service/create_custom_field_options.py mode change 100644 => 100755 examples/dfp/v201611/custom_field_service/create_custom_fields.py mode change 100644 => 100755 examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py mode change 100644 => 100755 examples/dfp/v201611/custom_field_service/get_all_custom_fields.py mode change 100644 => 100755 examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py mode change 100644 => 100755 examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py mode change 100644 => 100755 examples/dfp/v201611/custom_field_service/update_custom_fields.py mode change 100644 => 100755 examples/dfp/v201611/custom_targeting_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py mode change 100644 => 100755 examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py mode change 100644 => 100755 examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py mode change 100644 => 100755 examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py mode change 100644 => 100755 examples/dfp/v201611/exchange_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py mode change 100644 => 100755 examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201611/forecast_service/get_availability_forecast.py mode change 100644 => 100755 examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py mode change 100644 => 100755 examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py mode change 100644 => 100755 examples/dfp/v201611/inventory_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/inventory_service/archive_ad_units.py mode change 100644 => 100755 examples/dfp/v201611/inventory_service/create_ad_units.py mode change 100644 => 100755 examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py mode change 100644 => 100755 examples/dfp/v201611/inventory_service/get_all_ad_units.py mode change 100644 => 100755 examples/dfp/v201611/inventory_service/update_ad_units.py mode change 100644 => 100755 examples/dfp/v201611/label_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/label_service/create_labels.py mode change 100644 => 100755 examples/dfp/v201611/label_service/deactivate_labels.py mode change 100644 => 100755 examples/dfp/v201611/label_service/get_active_labels.py mode change 100644 => 100755 examples/dfp/v201611/label_service/get_all_labels.py mode change 100644 => 100755 examples/dfp/v201611/label_service/update_labels.py mode change 100644 => 100755 examples/dfp/v201611/line_item_creative_association_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/line_item_creative_association_service/create_licas.py mode change 100644 => 100755 examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py mode change 100644 => 100755 examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py mode change 100644 => 100755 examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py mode change 100644 => 100755 examples/dfp/v201611/line_item_creative_association_service/update_licas.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/activate_line_items.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/create_line_items.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/create_video_line_item.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/get_all_line_items.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/target_custom_criteria.py mode change 100644 => 100755 examples/dfp/v201611/line_item_service/update_line_items.py mode change 100644 => 100755 examples/dfp/v201611/network_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/network_service/get_all_networks.py mode change 100644 => 100755 examples/dfp/v201611/network_service/make_test_network.py mode change 100644 => 100755 examples/dfp/v201611/order_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/order_service/approve_orders.py mode change 100644 => 100755 examples/dfp/v201611/order_service/create_orders.py mode change 100644 => 100755 examples/dfp/v201611/order_service/get_all_orders.py mode change 100644 => 100755 examples/dfp/v201611/order_service/get_orders_starting_soon.py mode change 100644 => 100755 examples/dfp/v201611/order_service/update_orders.py mode change 100644 => 100755 examples/dfp/v201611/package_service/get_all_packages.py mode change 100644 => 100755 examples/dfp/v201611/package_service/get_in_progress_packages.py mode change 100644 => 100755 examples/dfp/v201611/placement_service/create_placements.py mode change 100644 => 100755 examples/dfp/v201611/placement_service/deactivate_placements.py mode change 100644 => 100755 examples/dfp/v201611/placement_service/get_active_placements.py mode change 100644 => 100755 examples/dfp/v201611/placement_service/get_all_placements.py mode change 100644 => 100755 examples/dfp/v201611/placement_service/update_placements.py mode change 100644 => 100755 examples/dfp/v201611/premium_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/premium_rate_service/create_premium_rates.py mode change 100644 => 100755 examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py mode change 100644 => 100755 examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py mode change 100644 => 100755 examples/dfp/v201611/premium_rate_service/update_premium_rates.py mode change 100644 => 100755 examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py mode change 100644 => 100755 examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py mode change 100644 => 100755 examples/dfp/v201611/product_package_service/get_active_product_packages.py mode change 100644 => 100755 examples/dfp/v201611/product_package_service/get_all_product_packages.py mode change 100644 => 100755 examples/dfp/v201611/product_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201611/product_service/get_all_products.py mode change 100644 => 100755 examples/dfp/v201611/product_service/get_products_for_product_template.py mode change 100644 => 100755 examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py mode change 100644 => 100755 examples/dfp/v201611/product_service/update_products.py mode change 100644 => 100755 examples/dfp/v201611/product_template_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/product_template_service/activate_product_templates.py mode change 100644 => 100755 examples/dfp/v201611/product_template_service/create_product_templates.py mode change 100644 => 100755 examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py mode change 100644 => 100755 examples/dfp/v201611/product_template_service/get_all_product_templates.py mode change 100644 => 100755 examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py mode change 100644 => 100755 examples/dfp/v201611/product_template_service/update_product_templates.py mode change 100644 => 100755 examples/dfp/v201611/proposal_line_item_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py mode change 100644 => 100755 examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/create_programmatic_proposals.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/create_proposals.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/get_all_proposals.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/get_marketplace_comments.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/request_buyers_acceptance.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py mode change 100644 => 100755 examples/dfp/v201611/proposal_service/update_proposals.py mode change 100644 => 100755 examples/dfp/v201611/publisher_query_language_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py mode change 100644 => 100755 examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py mode change 100644 => 100755 examples/dfp/v201611/rate_card_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/rate_card_service/get_all_rate_cards.py mode change 100644 => 100755 examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py mode change 100644 => 100755 examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py mode change 100644 => 100755 examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py mode change 100644 => 100755 examples/dfp/v201611/report_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/report_service/run_delivery_report.py mode change 100644 => 100755 examples/dfp/v201611/report_service/run_inventory_report.py mode change 100644 => 100755 examples/dfp/v201611/report_service/run_reach_report.py mode change 100644 => 100755 examples/dfp/v201611/report_service/run_report_with_custom_fields.py mode change 100644 => 100755 examples/dfp/v201611/report_service/run_sales_report.py mode change 100644 => 100755 examples/dfp/v201611/report_service/run_saved_query.py mode change 100644 => 100755 examples/dfp/v201611/suggested_ad_unit_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201611/team_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/team_service/create_teams.py mode change 100644 => 100755 examples/dfp/v201611/team_service/get_all_teams.py mode change 100644 => 100755 examples/dfp/v201611/team_service/update_teams.py mode change 100644 => 100755 examples/dfp/v201611/user_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/user_service/create_users.py mode change 100644 => 100755 examples/dfp/v201611/user_service/deactivate_users.py mode change 100644 => 100755 examples/dfp/v201611/user_service/get_all_roles.py mode change 100644 => 100755 examples/dfp/v201611/user_service/get_all_users.py mode change 100644 => 100755 examples/dfp/v201611/user_service/get_user_by_email_address.py mode change 100644 => 100755 examples/dfp/v201611/user_service/update_users.py mode change 100644 => 100755 examples/dfp/v201611/user_team_association_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/user_team_association_service/create_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py mode change 100644 => 100755 examples/dfp/v201611/user_team_association_service/update_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201611/workflow_request_service/__init__.py mode change 100644 => 100755 examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py mode change 100644 => 100755 examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py mode change 100644 => 100755 examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py mode change 100644 => 100755 examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py mode change 100644 => 100755 examples/dfp/v201702/activity_group_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/activity_group_service/create_activity_groups.py mode change 100644 => 100755 examples/dfp/v201702/activity_group_service/get_active_activity_groups.py mode change 100644 => 100755 examples/dfp/v201702/activity_group_service/get_all_activity_groups.py mode change 100644 => 100755 examples/dfp/v201702/activity_group_service/update_activity_groups.py mode change 100644 => 100755 examples/dfp/v201702/activity_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/activity_service/create_activities.py mode change 100644 => 100755 examples/dfp/v201702/activity_service/get_active_activities.py mode change 100644 => 100755 examples/dfp/v201702/activity_service/get_all_activities.py mode change 100644 => 100755 examples/dfp/v201702/activity_service/update_activities.py mode change 100644 => 100755 examples/dfp/v201702/audience_segment_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/audience_segment_service/create_audience_segments.py mode change 100644 => 100755 examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py mode change 100644 => 100755 examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py mode change 100644 => 100755 examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py mode change 100644 => 100755 examples/dfp/v201702/audience_segment_service/update_audience_segments.py mode change 100644 => 100755 examples/dfp/v201702/base_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/base_rate_service/create_product_base_rates.py mode change 100644 => 100755 examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py mode change 100644 => 100755 examples/dfp/v201702/base_rate_service/get_all_base_rates.py mode change 100644 => 100755 examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py mode change 100644 => 100755 examples/dfp/v201702/base_rate_service/update_base_rates.py mode change 100644 => 100755 examples/dfp/v201702/company_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/company_service/create_companies.py mode change 100644 => 100755 examples/dfp/v201702/company_service/get_advertisers.py mode change 100644 => 100755 examples/dfp/v201702/company_service/get_all_companies.py mode change 100644 => 100755 examples/dfp/v201702/company_service/update_companies.py mode change 100644 => 100755 examples/dfp/v201702/contact_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/contact_service/create_contacts.py mode change 100644 => 100755 examples/dfp/v201702/contact_service/get_all_contacts.py mode change 100644 => 100755 examples/dfp/v201702/contact_service/get_uninvited_contacts.py mode change 100644 => 100755 examples/dfp/v201702/contact_service/update_contacts.py mode change 100644 => 100755 examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201702/content_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/content_service/get_all_content.py mode change 100644 => 100755 examples/dfp/v201702/creative_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/creative_service/create_creative_from_template.py mode change 100644 => 100755 examples/dfp/v201702/creative_service/create_creatives.py mode change 100644 => 100755 examples/dfp/v201702/creative_service/create_custom_creative.py mode change 100644 => 100755 examples/dfp/v201702/creative_service/create_native_creative.py mode change 100644 => 100755 examples/dfp/v201702/creative_service/get_all_creatives.py mode change 100644 => 100755 examples/dfp/v201702/creative_service/get_image_creatives.py mode change 100644 => 100755 examples/dfp/v201702/creative_service/update_creatives.py mode change 100644 => 100755 examples/dfp/v201702/creative_set_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py mode change 100644 => 100755 examples/dfp/v201702/creative_set_service/create_creative_set.py mode change 100644 => 100755 examples/dfp/v201702/creative_set_service/get_all_creative_sets.py mode change 100644 => 100755 examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py mode change 100644 => 100755 examples/dfp/v201702/creative_set_service/update_creative_set.py mode change 100644 => 100755 examples/dfp/v201702/creative_template_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/creative_template_service/get_all_creative_templates.py mode change 100644 => 100755 examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py mode change 100644 => 100755 examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py mode change 100644 => 100755 examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201702/custom_field_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/custom_field_service/create_custom_field_options.py mode change 100644 => 100755 examples/dfp/v201702/custom_field_service/create_custom_fields.py mode change 100644 => 100755 examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py mode change 100644 => 100755 examples/dfp/v201702/custom_field_service/get_all_custom_fields.py mode change 100644 => 100755 examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py mode change 100644 => 100755 examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py mode change 100644 => 100755 examples/dfp/v201702/custom_field_service/update_custom_fields.py mode change 100644 => 100755 examples/dfp/v201702/custom_targeting_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py mode change 100644 => 100755 examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py mode change 100644 => 100755 examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py mode change 100644 => 100755 examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py mode change 100644 => 100755 examples/dfp/v201702/exchange_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py mode change 100644 => 100755 examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201702/forecast_service/get_availability_forecast.py mode change 100644 => 100755 examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py mode change 100644 => 100755 examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py mode change 100644 => 100755 examples/dfp/v201702/inventory_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/inventory_service/archive_ad_units.py mode change 100644 => 100755 examples/dfp/v201702/inventory_service/create_ad_units.py mode change 100644 => 100755 examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py mode change 100644 => 100755 examples/dfp/v201702/inventory_service/get_all_ad_units.py mode change 100644 => 100755 examples/dfp/v201702/inventory_service/update_ad_units.py mode change 100644 => 100755 examples/dfp/v201702/label_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/label_service/create_labels.py mode change 100644 => 100755 examples/dfp/v201702/label_service/deactivate_labels.py mode change 100644 => 100755 examples/dfp/v201702/label_service/get_active_labels.py mode change 100644 => 100755 examples/dfp/v201702/label_service/get_all_labels.py mode change 100644 => 100755 examples/dfp/v201702/label_service/update_labels.py mode change 100644 => 100755 examples/dfp/v201702/line_item_creative_association_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/line_item_creative_association_service/create_licas.py mode change 100644 => 100755 examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py mode change 100644 => 100755 examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py mode change 100644 => 100755 examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py mode change 100644 => 100755 examples/dfp/v201702/line_item_creative_association_service/update_licas.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/activate_line_items.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/create_line_items.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/create_video_line_item.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/get_all_line_items.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/target_custom_criteria.py mode change 100644 => 100755 examples/dfp/v201702/line_item_service/update_line_items.py mode change 100644 => 100755 examples/dfp/v201702/native_style_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/native_style_service/create_native_styles.py mode change 100644 => 100755 examples/dfp/v201702/native_style_service/get_all_native_styles.py mode change 100644 => 100755 examples/dfp/v201702/network_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/network_service/get_all_networks.py mode change 100644 => 100755 examples/dfp/v201702/network_service/make_test_network.py mode change 100644 => 100755 examples/dfp/v201702/order_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/order_service/approve_orders.py mode change 100644 => 100755 examples/dfp/v201702/order_service/create_orders.py mode change 100644 => 100755 examples/dfp/v201702/order_service/get_all_orders.py mode change 100644 => 100755 examples/dfp/v201702/order_service/get_orders_starting_soon.py mode change 100644 => 100755 examples/dfp/v201702/order_service/update_orders.py mode change 100644 => 100755 examples/dfp/v201702/package_service/get_all_packages.py mode change 100644 => 100755 examples/dfp/v201702/package_service/get_in_progress_packages.py mode change 100644 => 100755 examples/dfp/v201702/placement_service/create_placements.py mode change 100644 => 100755 examples/dfp/v201702/placement_service/deactivate_placements.py mode change 100644 => 100755 examples/dfp/v201702/placement_service/get_active_placements.py mode change 100644 => 100755 examples/dfp/v201702/placement_service/get_all_placements.py mode change 100644 => 100755 examples/dfp/v201702/placement_service/update_placements.py mode change 100644 => 100755 examples/dfp/v201702/premium_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/premium_rate_service/create_premium_rates.py mode change 100644 => 100755 examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py mode change 100644 => 100755 examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py mode change 100644 => 100755 examples/dfp/v201702/premium_rate_service/update_premium_rates.py mode change 100644 => 100755 examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py mode change 100644 => 100755 examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py mode change 100644 => 100755 examples/dfp/v201702/product_package_service/get_active_product_packages.py mode change 100644 => 100755 examples/dfp/v201702/product_package_service/get_all_product_packages.py mode change 100644 => 100755 examples/dfp/v201702/product_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201702/product_service/get_all_products.py mode change 100644 => 100755 examples/dfp/v201702/product_service/get_products_for_product_template.py mode change 100644 => 100755 examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py mode change 100644 => 100755 examples/dfp/v201702/product_service/update_products.py mode change 100644 => 100755 examples/dfp/v201702/product_template_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/product_template_service/activate_product_templates.py mode change 100644 => 100755 examples/dfp/v201702/product_template_service/create_product_templates.py mode change 100644 => 100755 examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py mode change 100644 => 100755 examples/dfp/v201702/product_template_service/get_all_product_templates.py mode change 100644 => 100755 examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py mode change 100644 => 100755 examples/dfp/v201702/product_template_service/update_product_templates.py mode change 100644 => 100755 examples/dfp/v201702/proposal_line_item_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py mode change 100644 => 100755 examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/create_programmatic_proposals.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/create_proposals.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/get_all_proposals.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/get_marketplace_comments.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/request_buyers_acceptance.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py mode change 100644 => 100755 examples/dfp/v201702/proposal_service/update_proposals.py mode change 100644 => 100755 examples/dfp/v201702/publisher_query_language_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py mode change 100644 => 100755 examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py mode change 100644 => 100755 examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py mode change 100644 => 100755 examples/dfp/v201702/rate_card_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/rate_card_service/get_all_rate_cards.py mode change 100644 => 100755 examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py mode change 100644 => 100755 examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py mode change 100644 => 100755 examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py mode change 100644 => 100755 examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py mode change 100644 => 100755 examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py mode change 100644 => 100755 examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py mode change 100644 => 100755 examples/dfp/v201702/report_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/report_service/run_delivery_report.py mode change 100644 => 100755 examples/dfp/v201702/report_service/run_inventory_report.py mode change 100644 => 100755 examples/dfp/v201702/report_service/run_reach_report.py mode change 100644 => 100755 examples/dfp/v201702/report_service/run_report_with_custom_fields.py mode change 100644 => 100755 examples/dfp/v201702/report_service/run_sales_report.py mode change 100644 => 100755 examples/dfp/v201702/report_service/run_saved_query.py mode change 100644 => 100755 examples/dfp/v201702/suggested_ad_unit_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201702/team_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/team_service/create_teams.py mode change 100644 => 100755 examples/dfp/v201702/team_service/get_all_teams.py mode change 100644 => 100755 examples/dfp/v201702/team_service/update_teams.py mode change 100644 => 100755 examples/dfp/v201702/user_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/user_service/create_users.py mode change 100644 => 100755 examples/dfp/v201702/user_service/deactivate_users.py mode change 100644 => 100755 examples/dfp/v201702/user_service/get_all_roles.py mode change 100644 => 100755 examples/dfp/v201702/user_service/get_all_users.py mode change 100644 => 100755 examples/dfp/v201702/user_service/get_user_by_email_address.py mode change 100644 => 100755 examples/dfp/v201702/user_service/update_users.py mode change 100644 => 100755 examples/dfp/v201702/user_team_association_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/user_team_association_service/create_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py mode change 100644 => 100755 examples/dfp/v201702/user_team_association_service/update_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201702/workflow_request_service/__init__.py mode change 100644 => 100755 examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py mode change 100644 => 100755 examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py mode change 100644 => 100755 examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py mode change 100644 => 100755 examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py mode change 100644 => 100755 examples/dfp/v201705/activity_group_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/activity_group_service/create_activity_groups.py mode change 100644 => 100755 examples/dfp/v201705/activity_group_service/get_active_activity_groups.py mode change 100644 => 100755 examples/dfp/v201705/activity_group_service/get_all_activity_groups.py mode change 100644 => 100755 examples/dfp/v201705/activity_group_service/update_activity_groups.py mode change 100644 => 100755 examples/dfp/v201705/activity_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/activity_service/create_activities.py mode change 100644 => 100755 examples/dfp/v201705/activity_service/get_active_activities.py mode change 100644 => 100755 examples/dfp/v201705/activity_service/get_all_activities.py mode change 100644 => 100755 examples/dfp/v201705/activity_service/update_activities.py mode change 100644 => 100755 examples/dfp/v201705/audience_segment_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/audience_segment_service/create_audience_segments.py mode change 100644 => 100755 examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py mode change 100644 => 100755 examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py mode change 100644 => 100755 examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py mode change 100644 => 100755 examples/dfp/v201705/audience_segment_service/update_audience_segments.py mode change 100644 => 100755 examples/dfp/v201705/base_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/base_rate_service/create_product_base_rates.py mode change 100644 => 100755 examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py mode change 100644 => 100755 examples/dfp/v201705/base_rate_service/get_all_base_rates.py mode change 100644 => 100755 examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py mode change 100644 => 100755 examples/dfp/v201705/base_rate_service/update_base_rates.py mode change 100644 => 100755 examples/dfp/v201705/company_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/company_service/create_companies.py mode change 100644 => 100755 examples/dfp/v201705/company_service/get_advertisers.py mode change 100644 => 100755 examples/dfp/v201705/company_service/get_all_companies.py mode change 100644 => 100755 examples/dfp/v201705/company_service/update_companies.py mode change 100644 => 100755 examples/dfp/v201705/contact_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/contact_service/create_contacts.py mode change 100644 => 100755 examples/dfp/v201705/contact_service/get_all_contacts.py mode change 100644 => 100755 examples/dfp/v201705/contact_service/get_uninvited_contacts.py mode change 100644 => 100755 examples/dfp/v201705/contact_service/update_contacts.py mode change 100644 => 100755 examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py mode change 100644 => 100755 examples/dfp/v201705/content_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/content_service/get_all_content.py mode change 100644 => 100755 examples/dfp/v201705/creative_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/creative_service/create_creative_from_template.py mode change 100644 => 100755 examples/dfp/v201705/creative_service/create_creatives.py mode change 100644 => 100755 examples/dfp/v201705/creative_service/create_custom_creative.py mode change 100644 => 100755 examples/dfp/v201705/creative_service/create_native_creative.py mode change 100644 => 100755 examples/dfp/v201705/creative_service/get_all_creatives.py mode change 100644 => 100755 examples/dfp/v201705/creative_service/get_image_creatives.py mode change 100644 => 100755 examples/dfp/v201705/creative_service/update_creatives.py mode change 100644 => 100755 examples/dfp/v201705/creative_set_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py mode change 100644 => 100755 examples/dfp/v201705/creative_set_service/create_creative_set.py mode change 100644 => 100755 examples/dfp/v201705/creative_set_service/get_all_creative_sets.py mode change 100644 => 100755 examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py mode change 100644 => 100755 examples/dfp/v201705/creative_set_service/update_creative_set.py mode change 100644 => 100755 examples/dfp/v201705/creative_template_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/creative_template_service/get_all_creative_templates.py mode change 100644 => 100755 examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py mode change 100644 => 100755 examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py mode change 100644 => 100755 examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py mode change 100644 => 100755 examples/dfp/v201705/custom_field_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/custom_field_service/create_custom_field_options.py mode change 100644 => 100755 examples/dfp/v201705/custom_field_service/create_custom_fields.py mode change 100644 => 100755 examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py mode change 100644 => 100755 examples/dfp/v201705/custom_field_service/get_all_custom_fields.py mode change 100644 => 100755 examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py mode change 100644 => 100755 examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py mode change 100644 => 100755 examples/dfp/v201705/custom_field_service/update_custom_fields.py mode change 100644 => 100755 examples/dfp/v201705/custom_targeting_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py mode change 100644 => 100755 examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py mode change 100644 => 100755 examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py mode change 100644 => 100755 examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py mode change 100644 => 100755 examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py mode change 100644 => 100755 examples/dfp/v201705/exchange_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py mode change 100644 => 100755 examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py mode change 100644 => 100755 examples/dfp/v201705/forecast_service/get_availability_forecast.py mode change 100644 => 100755 examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py mode change 100644 => 100755 examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py mode change 100644 => 100755 examples/dfp/v201705/inventory_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/inventory_service/archive_ad_units.py mode change 100644 => 100755 examples/dfp/v201705/inventory_service/create_ad_units.py mode change 100644 => 100755 examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py mode change 100644 => 100755 examples/dfp/v201705/inventory_service/get_all_ad_units.py mode change 100644 => 100755 examples/dfp/v201705/inventory_service/update_ad_units.py mode change 100644 => 100755 examples/dfp/v201705/label_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/label_service/create_labels.py mode change 100644 => 100755 examples/dfp/v201705/label_service/deactivate_labels.py mode change 100644 => 100755 examples/dfp/v201705/label_service/get_active_labels.py mode change 100644 => 100755 examples/dfp/v201705/label_service/get_all_labels.py mode change 100644 => 100755 examples/dfp/v201705/label_service/update_labels.py mode change 100644 => 100755 examples/dfp/v201705/line_item_creative_association_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/line_item_creative_association_service/create_licas.py mode change 100644 => 100755 examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py mode change 100644 => 100755 examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py mode change 100644 => 100755 examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py mode change 100644 => 100755 examples/dfp/v201705/line_item_creative_association_service/update_licas.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/activate_line_items.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/create_line_items.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/create_video_line_item.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/get_all_line_items.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/target_custom_criteria.py mode change 100644 => 100755 examples/dfp/v201705/line_item_service/update_line_items.py mode change 100644 => 100755 examples/dfp/v201705/native_style_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/native_style_service/create_native_styles.py mode change 100644 => 100755 examples/dfp/v201705/native_style_service/get_all_native_styles.py mode change 100644 => 100755 examples/dfp/v201705/network_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/network_service/get_all_networks.py mode change 100644 => 100755 examples/dfp/v201705/network_service/make_test_network.py mode change 100644 => 100755 examples/dfp/v201705/order_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/order_service/approve_orders.py mode change 100644 => 100755 examples/dfp/v201705/order_service/create_orders.py mode change 100644 => 100755 examples/dfp/v201705/order_service/get_all_orders.py mode change 100644 => 100755 examples/dfp/v201705/order_service/get_orders_starting_soon.py mode change 100644 => 100755 examples/dfp/v201705/order_service/update_orders.py mode change 100644 => 100755 examples/dfp/v201705/package_service/get_all_packages.py mode change 100644 => 100755 examples/dfp/v201705/package_service/get_in_progress_packages.py mode change 100644 => 100755 examples/dfp/v201705/placement_service/create_placements.py mode change 100644 => 100755 examples/dfp/v201705/placement_service/deactivate_placements.py mode change 100644 => 100755 examples/dfp/v201705/placement_service/get_active_placements.py mode change 100644 => 100755 examples/dfp/v201705/placement_service/get_all_placements.py mode change 100644 => 100755 examples/dfp/v201705/placement_service/update_placements.py mode change 100644 => 100755 examples/dfp/v201705/premium_rate_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/premium_rate_service/create_premium_rates.py mode change 100644 => 100755 examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py mode change 100644 => 100755 examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py mode change 100644 => 100755 examples/dfp/v201705/premium_rate_service/update_premium_rates.py mode change 100644 => 100755 examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py mode change 100644 => 100755 examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py mode change 100644 => 100755 examples/dfp/v201705/product_package_service/get_active_product_packages.py mode change 100644 => 100755 examples/dfp/v201705/product_package_service/get_all_product_packages.py mode change 100644 => 100755 examples/dfp/v201705/product_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201705/product_service/get_all_products.py mode change 100644 => 100755 examples/dfp/v201705/product_service/get_products_for_product_template.py mode change 100644 => 100755 examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py mode change 100644 => 100755 examples/dfp/v201705/product_service/update_products.py mode change 100644 => 100755 examples/dfp/v201705/product_template_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/product_template_service/activate_product_templates.py mode change 100644 => 100755 examples/dfp/v201705/product_template_service/create_product_templates.py mode change 100644 => 100755 examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py mode change 100644 => 100755 examples/dfp/v201705/product_template_service/get_all_product_templates.py mode change 100644 => 100755 examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py mode change 100644 => 100755 examples/dfp/v201705/product_template_service/update_product_templates.py mode change 100644 => 100755 examples/dfp/v201705/proposal_line_item_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py mode change 100644 => 100755 examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/create_programmatic_proposals.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/create_proposals.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/get_all_proposals.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/get_marketplace_comments.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/request_buyers_acceptance.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py mode change 100644 => 100755 examples/dfp/v201705/proposal_service/update_proposals.py mode change 100644 => 100755 examples/dfp/v201705/publisher_query_language_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py mode change 100644 => 100755 examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py mode change 100644 => 100755 examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py mode change 100644 => 100755 examples/dfp/v201705/rate_card_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/rate_card_service/get_all_rate_cards.py mode change 100644 => 100755 examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py mode change 100644 => 100755 examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py mode change 100644 => 100755 examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py mode change 100644 => 100755 examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py mode change 100644 => 100755 examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py mode change 100644 => 100755 examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py mode change 100644 => 100755 examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py mode change 100644 => 100755 examples/dfp/v201705/report_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/report_service/run_delivery_report.py mode change 100644 => 100755 examples/dfp/v201705/report_service/run_inventory_report.py mode change 100644 => 100755 examples/dfp/v201705/report_service/run_reach_report.py mode change 100644 => 100755 examples/dfp/v201705/report_service/run_report_with_custom_fields.py mode change 100644 => 100755 examples/dfp/v201705/report_service/run_sales_report.py mode change 100644 => 100755 examples/dfp/v201705/report_service/run_saved_query.py mode change 100644 => 100755 examples/dfp/v201705/suggested_ad_unit_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py mode change 100644 => 100755 examples/dfp/v201705/team_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/team_service/create_teams.py mode change 100644 => 100755 examples/dfp/v201705/team_service/get_all_teams.py mode change 100644 => 100755 examples/dfp/v201705/team_service/update_teams.py mode change 100644 => 100755 examples/dfp/v201705/user_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/user_service/create_users.py mode change 100644 => 100755 examples/dfp/v201705/user_service/deactivate_users.py mode change 100644 => 100755 examples/dfp/v201705/user_service/get_all_roles.py mode change 100644 => 100755 examples/dfp/v201705/user_service/get_all_users.py mode change 100644 => 100755 examples/dfp/v201705/user_service/get_user_by_email_address.py mode change 100644 => 100755 examples/dfp/v201705/user_service/update_users.py mode change 100644 => 100755 examples/dfp/v201705/user_team_association_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/user_team_association_service/create_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py mode change 100644 => 100755 examples/dfp/v201705/user_team_association_service/update_user_team_associations.py mode change 100644 => 100755 examples/dfp/v201705/workflow_request_service/__init__.py mode change 100644 => 100755 examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py mode change 100644 => 100755 examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py mode change 100644 => 100755 examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py mode change 100644 => 100755 examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py mode change 100644 => 100755 setup.py diff --git a/ChangeLog b/ChangeLog index 62972e6f..03470056 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,4 +1,7 @@ -5.5.0 -- 5/23/17: +5.6.0 -- 06/01/17: +* Added support for AdWords v201705. + +5.5.0 -- 05/23/17: * Added more expressive python utility to build DFP PQL statements. * Support building DFP SOAP entities with native python date/datetime objects. * Added support and examples for DFP v201705. diff --git a/examples/adwords/adwords_appengine_demo/__init__.py b/examples/adwords/adwords_appengine_demo/__init__.py index be307921..38deb3b8 100755 --- a/examples/adwords/adwords_appengine_demo/__init__.py +++ b/examples/adwords/adwords_appengine_demo/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/demo/__init__.py b/examples/adwords/adwords_appengine_demo/demo/__init__.py index 59e8ef3a..edf49e56 100755 --- a/examples/adwords/adwords_appengine_demo/demo/__init__.py +++ b/examples/adwords/adwords_appengine_demo/demo/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/demo/main.py b/examples/adwords/adwords_appengine_demo/demo/main.py index 5d364db6..1dfb904c 100755 --- a/examples/adwords/adwords_appengine_demo/demo/main.py +++ b/examples/adwords/adwords_appengine_demo/demo/main.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/__init__.py b/examples/adwords/adwords_appengine_demo/handlers/__init__.py index 0f5dabe3..a186d331 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/__init__.py +++ b/examples/adwords/adwords_appengine_demo/handlers/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index c2e70b54..0595b40a 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py index 97d6a3e4..9cd6b7ca 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/models/__init__.py b/examples/adwords/adwords_appengine_demo/models/__init__.py index af1c9f8f..2eba7921 100755 --- a/examples/adwords/adwords_appengine_demo/models/__init__.py +++ b/examples/adwords/adwords_appengine_demo/models/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/models/app_user.py b/examples/adwords/adwords_appengine_demo/models/app_user.py index 5272ee87..56004b17 100755 --- a/examples/adwords/adwords_appengine_demo/models/app_user.py +++ b/examples/adwords/adwords_appengine_demo/models/app_user.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/__init__.py b/examples/adwords/adwords_appengine_demo/views/__init__.py index f6f56e9a..eadfba45 100755 --- a/examples/adwords/adwords_appengine_demo/views/__init__.py +++ b/examples/adwords/adwords_appengine_demo/views/__init__.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py index ce4d8943..48bb14c5 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py index d86b3181..25297d20 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/init_view.py b/examples/adwords/adwords_appengine_demo/views/init_view.py index edb5d935..e6215956 100755 --- a/examples/adwords/adwords_appengine_demo/views/init_view.py +++ b/examples/adwords/adwords_appengine_demo/views/init_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py index 2813a14a..e3bdbf1d 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py index 74e00a59..9722cad9 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py index a0f1448c..758f832d 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py index 05f071f5..9c74eeaa 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py index af08fa55..bcc709c3 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py index 53903584..bbfe5d96 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py index 3be794b6..83159ca6 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index 57f978c4..b4b0b4f9 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_without_yaml.py index 12e9ad99..b79c69ab 100755 --- a/examples/adwords/authentication/create_adwords_client_without_yaml.py +++ b/examples/adwords/authentication/create_adwords_client_without_yaml.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 37696d7e..0f5d1829 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/adwords/v201607/account_management/create_account.py b/examples/adwords/v201607/account_management/create_account.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/account_management/get_account_changes.py b/examples/adwords/v201607/account_management/get_account_changes.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/account_management/get_account_hierarchy.py b/examples/adwords/v201607/account_management/get_account_hierarchy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/add_html5_ad.py b/examples/adwords/v201607/advanced_operations/add_html5_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/add_ad_groups.py b/examples/adwords/v201607/basic_operations/add_ad_groups.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/add_campaigns.py b/examples/adwords/v201607/basic_operations/add_campaigns.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/add_keywords.py b/examples/adwords/v201607/basic_operations/add_keywords.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/add_text_ads.py b/examples/adwords/v201607/basic_operations/add_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/get_ad_groups.py b/examples/adwords/v201607/basic_operations/get_ad_groups.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/get_campaigns.py b/examples/adwords/v201607/basic_operations/get_campaigns.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/get_keywords.py b/examples/adwords/v201607/basic_operations/get_keywords.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/get_text_ads.py b/examples/adwords/v201607/basic_operations/get_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/pause_ad.py b/examples/adwords/v201607/basic_operations/pause_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/remove_ad.py b/examples/adwords/v201607/basic_operations/remove_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/remove_ad_group.py b/examples/adwords/v201607/basic_operations/remove_ad_group.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/remove_campaign.py b/examples/adwords/v201607/basic_operations/remove_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/remove_keyword.py b/examples/adwords/v201607/basic_operations/remove_keyword.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/update_ad_group.py b/examples/adwords/v201607/basic_operations/update_ad_group.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/update_campaign.py b/examples/adwords/v201607/basic_operations/update_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/basic_operations/update_keyword.py b/examples/adwords/v201607/basic_operations/update_keyword.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/add_campaign_labels.py b/examples/adwords/v201607/campaign_management/add_campaign_labels.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/add_draft.py b/examples/adwords/v201607/campaign_management/add_draft.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/add_experiment.py b/examples/adwords/v201607/campaign_management/add_experiment.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/add_trial.py b/examples/adwords/v201607/campaign_management/add_trial.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/graduate_trial.py b/examples/adwords/v201607/campaign_management/graduate_trial.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/promote_experiment.py b/examples/adwords/v201607/campaign_management/promote_experiment.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/set_ad_parameters.py b/examples/adwords/v201607/campaign_management/set_ad_parameters.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/campaign_management/validate_text_ad.py b/examples/adwords/v201607/campaign_management/validate_text_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/error_handling/handle_partial_failures.py b/examples/adwords/v201607/error_handling/handle_partial_failures.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/extensions/add_prices.py b/examples/adwords/v201607/extensions/add_prices.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/extensions/add_site_links.py b/examples/adwords/v201607/extensions/add_site_links.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/migration/migrate_to_extension_settings.py b/examples/adwords/v201607/migration/migrate_to_extension_settings.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/misc/get_all_images_and_videos.py b/examples/adwords/v201607/misc/get_all_images_and_videos.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/misc/upload_image.py b/examples/adwords/v201607/misc/upload_image.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/misc/upload_media_bundle.py b/examples/adwords/v201607/misc/upload_media_bundle.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/optimization/estimate_keyword_traffic.py b/examples/adwords/v201607/optimization/estimate_keyword_traffic.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/optimization/get_keyword_ideas.py b/examples/adwords/v201607/optimization/get_keyword_ideas.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/remarketing/add_audience.py b/examples/adwords/v201607/remarketing/add_audience.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/remarketing/add_conversion_tracker.py b/examples/adwords/v201607/remarketing/add_conversion_tracker.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/remarketing/add_crm_based_user_list.py b/examples/adwords/v201607/remarketing/add_crm_based_user_list.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/remarketing/upload_offline_conversions.py b/examples/adwords/v201607/remarketing/upload_offline_conversions.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/reporting/download_criteria_report.py b/examples/adwords/v201607/reporting/download_criteria_report.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/reporting/get_report_fields.py b/examples/adwords/v201607/reporting/get_report_fields.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/reporting/parallel_report_download.py b/examples/adwords/v201607/reporting/parallel_report_download.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/shopping/add_product_partition_tree.py b/examples/adwords/v201607/shopping/add_product_partition_tree.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/shopping/add_product_scope.py b/examples/adwords/v201607/shopping/add_product_scope.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/shopping/add_shopping_campaign.py b/examples/adwords/v201607/shopping/add_shopping_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/shopping/get_product_category_taxonomy.py b/examples/adwords/v201607/shopping/get_product_category_taxonomy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201607/targeting/lookup_location.py b/examples/adwords/v201607/targeting/lookup_location.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/account_management/accept_service_link.py b/examples/adwords/v201609/account_management/accept_service_link.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/account_management/create_account.py b/examples/adwords/v201609/account_management/create_account.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/account_management/get_account_changes.py b/examples/adwords/v201609/account_management/get_account_changes.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/account_management/get_account_hierarchy.py b/examples/adwords/v201609/account_management/get_account_hierarchy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/add_html5_ad.py b/examples/adwords/v201609/advanced_operations/add_html5_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/add_ad_groups.py b/examples/adwords/v201609/basic_operations/add_ad_groups.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/add_campaigns.py b/examples/adwords/v201609/basic_operations/add_campaigns.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/add_keywords.py b/examples/adwords/v201609/basic_operations/add_keywords.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/get_ad_groups.py b/examples/adwords/v201609/basic_operations/get_ad_groups.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/get_campaigns.py b/examples/adwords/v201609/basic_operations/get_campaigns.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/get_keywords.py b/examples/adwords/v201609/basic_operations/get_keywords.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/get_text_ads.py b/examples/adwords/v201609/basic_operations/get_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/pause_ad.py b/examples/adwords/v201609/basic_operations/pause_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/remove_ad.py b/examples/adwords/v201609/basic_operations/remove_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/remove_ad_group.py b/examples/adwords/v201609/basic_operations/remove_ad_group.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/remove_campaign.py b/examples/adwords/v201609/basic_operations/remove_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/remove_keyword.py b/examples/adwords/v201609/basic_operations/remove_keyword.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/update_ad_group.py b/examples/adwords/v201609/basic_operations/update_ad_group.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/update_campaign.py b/examples/adwords/v201609/basic_operations/update_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/basic_operations/update_keyword.py b/examples/adwords/v201609/basic_operations/update_keyword.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/add_campaign_labels.py b/examples/adwords/v201609/campaign_management/add_campaign_labels.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/add_draft.py b/examples/adwords/v201609/campaign_management/add_draft.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/add_trial.py b/examples/adwords/v201609/campaign_management/add_trial.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/graduate_trial.py b/examples/adwords/v201609/campaign_management/graduate_trial.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/set_ad_parameters.py b/examples/adwords/v201609/campaign_management/set_ad_parameters.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/campaign_management/validate_text_ad.py b/examples/adwords/v201609/campaign_management/validate_text_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/error_handling/handle_partial_failures.py b/examples/adwords/v201609/error_handling/handle_partial_failures.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/extensions/add_prices.py b/examples/adwords/v201609/extensions/add_prices.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/extensions/add_site_links.py b/examples/adwords/v201609/extensions/add_site_links.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/migration/migrate_to_extension_settings.py b/examples/adwords/v201609/migration/migrate_to_extension_settings.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/misc/get_all_images_and_videos.py b/examples/adwords/v201609/misc/get_all_images_and_videos.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/misc/upload_image.py b/examples/adwords/v201609/misc/upload_image.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/misc/upload_media_bundle.py b/examples/adwords/v201609/misc/upload_media_bundle.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py b/examples/adwords/v201609/optimization/estimate_keyword_traffic.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/optimization/get_keyword_ideas.py b/examples/adwords/v201609/optimization/get_keyword_ideas.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/remarketing/add_audience.py b/examples/adwords/v201609/remarketing/add_audience.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/remarketing/add_conversion_tracker.py b/examples/adwords/v201609/remarketing/add_conversion_tracker.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py b/examples/adwords/v201609/remarketing/add_crm_based_user_list.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/remarketing/upload_offline_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_conversions.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/reporting/download_criteria_report.py b/examples/adwords/v201609/reporting/download_criteria_report.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/reporting/get_report_fields.py b/examples/adwords/v201609/reporting/get_report_fields.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/reporting/parallel_report_download.py b/examples/adwords/v201609/reporting/parallel_report_download.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/shopping/add_product_partition_tree.py b/examples/adwords/v201609/shopping/add_product_partition_tree.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/shopping/add_product_scope.py b/examples/adwords/v201609/shopping/add_product_scope.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/shopping/add_shopping_campaign.py b/examples/adwords/v201609/shopping/add_shopping_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py b/examples/adwords/v201609/shopping/get_product_category_taxonomy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201609/targeting/lookup_location.py b/examples/adwords/v201609/targeting/lookup_location.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/account_management/accept_service_link.py b/examples/adwords/v201702/account_management/accept_service_link.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/account_management/create_account.py b/examples/adwords/v201702/account_management/create_account.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/account_management/get_account_changes.py b/examples/adwords/v201702/account_management/get_account_changes.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/account_management/get_account_hierarchy.py b/examples/adwords/v201702/account_management/get_account_hierarchy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/add_html5_ad.py b/examples/adwords/v201702/advanced_operations/add_html5_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/add_ad_groups.py b/examples/adwords/v201702/basic_operations/add_ad_groups.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/add_campaigns.py b/examples/adwords/v201702/basic_operations/add_campaigns.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/add_keywords.py b/examples/adwords/v201702/basic_operations/add_keywords.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/get_ad_groups.py b/examples/adwords/v201702/basic_operations/get_ad_groups.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/get_campaigns.py b/examples/adwords/v201702/basic_operations/get_campaigns.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/get_keywords.py b/examples/adwords/v201702/basic_operations/get_keywords.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/get_text_ads.py b/examples/adwords/v201702/basic_operations/get_text_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/pause_ad.py b/examples/adwords/v201702/basic_operations/pause_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/remove_ad.py b/examples/adwords/v201702/basic_operations/remove_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/remove_ad_group.py b/examples/adwords/v201702/basic_operations/remove_ad_group.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/remove_campaign.py b/examples/adwords/v201702/basic_operations/remove_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/remove_keyword.py b/examples/adwords/v201702/basic_operations/remove_keyword.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/update_ad_group.py b/examples/adwords/v201702/basic_operations/update_ad_group.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/update_campaign.py b/examples/adwords/v201702/basic_operations/update_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/basic_operations/update_keyword.py b/examples/adwords/v201702/basic_operations/update_keyword.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/add_campaign_labels.py b/examples/adwords/v201702/campaign_management/add_campaign_labels.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/add_draft.py b/examples/adwords/v201702/campaign_management/add_draft.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/add_trial.py b/examples/adwords/v201702/campaign_management/add_trial.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/graduate_trial.py b/examples/adwords/v201702/campaign_management/graduate_trial.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/set_ad_parameters.py b/examples/adwords/v201702/campaign_management/set_ad_parameters.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/campaign_management/validate_text_ad.py b/examples/adwords/v201702/campaign_management/validate_text_ad.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/error_handling/handle_partial_failures.py b/examples/adwords/v201702/error_handling/handle_partial_failures.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/extensions/add_prices.py b/examples/adwords/v201702/extensions/add_prices.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/extensions/add_site_links.py b/examples/adwords/v201702/extensions/add_site_links.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/migration/migrate_to_extension_settings.py b/examples/adwords/v201702/migration/migrate_to_extension_settings.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/misc/get_all_images_and_videos.py b/examples/adwords/v201702/misc/get_all_images_and_videos.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/misc/upload_image.py b/examples/adwords/v201702/misc/upload_image.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/misc/upload_media_bundle.py b/examples/adwords/v201702/misc/upload_media_bundle.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py b/examples/adwords/v201702/optimization/estimate_keyword_traffic.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/optimization/get_keyword_ideas.py b/examples/adwords/v201702/optimization/get_keyword_ideas.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/remarketing/add_audience.py b/examples/adwords/v201702/remarketing/add_audience.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/remarketing/add_conversion_tracker.py b/examples/adwords/v201702/remarketing/add_conversion_tracker.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py b/examples/adwords/v201702/remarketing/add_crm_based_user_list.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py old mode 100644 new mode 100755 index 67b2efb9..907e2fa2 --- a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py @@ -117,7 +117,7 @@ def main(client): 'rule': rule, # Optional: Set the populationStatus to REQUESTED to include past users in # the user list. - 'populationStatus': 'REQUESTED' + 'prepopulationStatus': 'REQUESTED' } # Create the user list restricted to users who visit your site within the next diff --git a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/remarketing/upload_offline_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_conversions.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/reporting/get_report_fields.py b/examples/adwords/v201702/reporting/get_report_fields.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/reporting/parallel_report_download.py b/examples/adwords/v201702/reporting/parallel_report_download.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/shopping/add_product_partition_tree.py b/examples/adwords/v201702/shopping/add_product_partition_tree.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/shopping/add_product_scope.py b/examples/adwords/v201702/shopping/add_product_scope.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign.py b/examples/adwords/v201702/shopping/add_shopping_campaign.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py b/examples/adwords/v201702/shopping/get_product_category_taxonomy.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201702/targeting/lookup_location.py b/examples/adwords/v201702/targeting/lookup_location.py old mode 100644 new mode 100755 diff --git a/examples/adwords/v201705/__init__.py b/examples/adwords/v201705/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201705/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201705/account_management/__init__.py b/examples/adwords/v201705/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201705/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201705/account_management/accept_service_link.py b/examples/adwords/v201705/account_management/accept_service_link.py new file mode 100755 index 00000000..5d2b8de4 --- /dev/null +++ b/examples/adwords/v201705/account_management/accept_service_link.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' + + +def main(client, service_link_id): + # Initialize appropriate service. + customer_service = client.GetService( + 'CustomerService', version='v201705') + + # Create the operation to set the status to ACTIVE. + operations = [{ + 'operator': 'SET', + 'operand': { + 'serviceLinkId': service_link_id, + 'serviceType': 'MERCHANT_CENTER', + 'linkStatus': 'ACTIVE', + } + }] + + # Update the service link. + mutated_service_links = customer_service.mutateServiceLinks(operations) + + # Display results. + for mutated_service_link in mutated_service_links: + print ('Service link with service link ID \'%s\', type \'%s\' was updated ' + 'to status: \'%s\'.' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201705/account_management/create_account.py b/examples/adwords/v201705/account_management/create_account.py new file mode 100755 index 00000000..2c7560e2 --- /dev/null +++ b/examples/adwords/v201705/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201705') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID \'%s\' was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/account_management/get_account_changes.py b/examples/adwords/v201705/account_management/get_account_changes.py new file mode 100755 index 00000000..fe1dfa94 --- /dev/null +++ b/examples/adwords/v201705/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201705') + campaign_service = client.GetService('CampaignService', version='v201705') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id \'%s\' has change status \'%s\'.' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id \'%s\' has change status \'%s\'.' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/account_management/get_account_hierarchy.py b/examples/adwords/v201705/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..8644b35b --- /dev/null +++ b/examples/adwords/v201705/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201705') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/advanced_operations/__init__.py b/examples/adwords/v201705/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201705/advanced_operations/add_ad_customizer.py b/examples/adwords/v201705/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..9d7fec28 --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_ad_customizer.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates ExpandedTextAds that use ad customizations for specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no ExpandedTextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201705') + + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'headlinePart2': 'Only {=%s.Price}' % feed_name, + 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': expanded_text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201705') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name \'%s\' and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService', 'v201705') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201705/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201705/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..993bd6f5 --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201705') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..93de192f --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Optionally, you may specify a landscape image. The image needs to be in a + # BASE64 encoded form. Here we download a demo image and encode it for this + # ad. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + }, + { + 'name': 'landscapeImage', + 'fieldMedia': { + 'xsi_type': 'Image', + 'data': image_data + }, + 'type': 'IMAGE' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201705/advanced_operations/add_dynamic_page_feed.py new file mode 100755 index 00000000..bd16bc9a --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_dynamic_page_feed.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. + +To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +from collections import namedtuple +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + +# Used to keep track of DSA page feed details. +_DSAFeedDetails = namedtuple( + '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) +# ID that corresponds to the labels. +DSA_LABEL_FIELD_ID = 2 +# The criterion type to be used for DSA page feeds. +DSA_PAGE_FEED_CRITERION_TYPE = 61 +DSA_PAGE_URL_LABEL = 'discounts' +# ID that corresponds to the page URLs. +DSA_PAGE_URLS_FIELD_ID = 1 + + +def main(client, campaign_id, ad_group_id): + # Get the page feed details. This code example creates a new feed, but you can + # fetch and re-use an existing feed. + feed_details = _CreateFeed(client) + _CreateFeedMapping(client, feed_details) + _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) + + # Associate the page feed with the campaign. + _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) + + # Optional: Target web pages matching the feed's label in the ad group. + _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) + + print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + + +def _CreateFeed(client): + """Creates the feed for DSA page URLs. + + Args: + client: an AdWordsClient instance. + + Returns: + A _DSAFeedDetails instance containing details about the created feed. + """ + # Get the FeedService. + feed_service = client.GetService('FeedService', version='v201705') + + # Create operation. + operation = { + # Create the feed. + 'operand': { + 'name': 'DSA Feed %s' % uuid.uuid4(), + # Create attributes. + 'attributes': [ + {'type': 'URL_LIST', 'name': 'Page URL'}, + {'type': 'STRING_LIST', 'name': 'Label'} + ], + 'origin': 'USER' + }, + 'operator': 'ADD' + } + + # Add the feed. + feed = feed_service.mutate([operation])['value'][0] + return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], + feed['attributes'][1]['id']) + + +def _CreateFeedMapping(client, feed_details): + """Creates the feed mapping for DSA page feeds. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + """ + # Get the FeedMappingService. + feed_mapping_service = client.GetService('FeedMappingService', + version='v201705') + + # Create the operation. + operation = { + # Create the feed mapping. + 'operand': { + 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, + 'feedId': feed_details.feed_id, + # Map the feedAttributeIds to the fieldId constants. + 'attributeFieldMappings': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'fieldId': DSA_PAGE_URLS_FIELD_ID + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'fieldId': DSA_LABEL_FIELD_ID + } + ] + }, + 'operator': 'ADD' + } + + # Add the feed mapping. + feed_mapping_service.mutate([operation]) + + +def _CreateFeedItems(client, feed_details, label_name): + """Creates the page URLs in the DSA page feed. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + label_name: a str containing the page feed URL label. + """ + # Get the FeedItemService. + feed_item_service = client.GetService('FeedItemService', version='v201705') + + # Optional: You can include the {feeditem} valuetrack parameter to track which + # page feed items lead to each click. + urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', + 'http://www.example.com/discounts/hotel-deals?id={feeditem}', + 'http://www.example.com/discounts/flight-deals?id={feeditem}') + + # Create the operation. + operations = [{ + # Create the feed item. + 'operand': { + 'feedId': feed_details.feed_id, + 'attributeValues': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'stringValues': [url] + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'stringValues': [label_name] + } + ] + }, + 'operator': 'ADD' + } for url in urls] + + # Add the feed item. + feed_item_service.mutate(operations) + + +def _UpdateCampaignDSASetting(client, campaign_id, feed_id): + """Updates the campaign DSA setting to DSA pagefeeds. + + Args: + client: an AdWordsClient instance. + campaign_id: a str Campaign ID. + feed_id: a str page Feed ID. + + Raises: + ValueError: If the given campaign is found not to be a dynamic search ad + campaign. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201705') + + selector = { + 'fields': ['Id', 'Settings'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [campaign_id] + }] + } + + response = campaign_service.get(selector) + + if response['totalNumEntries']: + campaign = response['entries'][0] + else: + raise ValueError('No campaign with ID "%d" exists.' % campaign_id) + + if not campaign['settings']: + raise ValueError('This is not a DSA campaign.') + + dsa_setting = None + + campaign_settings = campaign['settings'] + + for setting in campaign_settings: + if setting['Setting.Type'] == 'DynamicSearchAdsSetting': + dsa_setting = setting + break + + if dsa_setting is None: + raise ValueError('This is not a DSA campaign.') + + dsa_setting['pageFeed'] = { + 'feedIds': [feed_id] + } + + # Optional: Specify whether only the supplied URLs should be used with your + # Dynamic Search Ads. + dsa_setting['useSuppliedUrlsOnly'] = True + + operation = { + 'operand': { + 'id': campaign_id, + 'settings': campaign_settings + }, + 'operator': 'SET' + } + + campaign_service.mutate([operation]) + print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id) + + +def _AddDSATargeting(client, ad_group_id, label_name): + """Set custom targeting for the page feed URLs based on a list of labels. + + Args: + client: an AdWordsClient instance. + ad_group_id: a str AdGroup ID. + label_name: a str label name. + + Returns: + A suds.sudsobject.Object representing the newly created webpage criterion. + """ + # Get the AdGroupCriterionService. + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201705') + + # Create the operation. + operation = { + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Test criterion', + # Add a condition for label=specified_label_name. + 'conditions': [{ + 'operand': 'CUSTOM_LABEL', + 'argument': label_name + }], + } + }, + # Set a custom bid for this criterion + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 1500000 + } + }] + } + }, + 'operator': 'ADD' + } + + criterion = ad_group_criterion_service.mutate([operation])['value'][0] + print 'Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus']) + return criterion + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201705/advanced_operations/add_dynamic_search_ads_campaign.py new file mode 100755 index 00000000..4eb2f319 --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_dynamic_search_ads_campaign.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Dynamic Search Ads campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + budget = _CreateBudget(client) + campaign_id = _CreateCampaign(client, budget) + ad_group_id = _CreateAdGroup(client, campaign_id) + _CreateExpandedDSA(client, ad_group_id) + _AddWebPageCriteria(client, ad_group_id) + + print 'Dynamic Search Ads campaign setup is complete.' + + +def _CreateBudget(client): + """Creates the budget. + + Args: + client: an AdWordsClient instance. + + Returns: + a suds.sudsobject.Object representation of the created budget. + """ + budget_service = client.GetService('BudgetService', version='v201705') + + # Create the campaign budget + operation = { + 'operand': { + 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), + 'deliveryMethod': 'STANDARD', + 'amount': { + 'microAmount': 500000 + } + }, + 'operator': 'ADD' + } + + budget = budget_service.mutate([operation])['value'][0] + + print 'Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name']) + + return budget + + +def _CreateCampaign(client, budget): + """Creates the campaign. + + Args: + client: an AdWordsClient instance. + budget: a suds.sudsobject.Object representation of a created budget. + + Returns: + An integer campaign ID. + """ + campaign_service = client.GetService('CampaignService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # prevent the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'budget': budget, + # Required: Set the campaign's Dynamic Search Ad settings. + 'settings': [{ + 'xsi_type': 'DynamicSearchAdsSetting', + # Required: Set the domain name and language. + 'domainName': 'example.com', + 'languageCode': 'en' + }], + # Optional: Set the start date. + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + # Optional: Set the end date. + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + }] + + campaign = campaign_service.mutate(operations)['value'][0] + campaign_id = campaign['id'] + + print 'Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name']) + + return campaign_id + + +def _CreateAdGroup(client, campaign_id): + """Creates an ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: an integer campaign ID. + + Returns: + An integer ad group ID. + """ + ad_group_service = client.GetService('AdGroupService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'adGroupType': 'SEARCH_DYNAMIC_ADS', + 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '3000000' + }, + }] + } + } + }] + + ad_group = ad_group_service.mutate(operations)['value'][0] + ad_group_id = ad_group['id'] + + print 'Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name']) + + return ad_group_id + + +def _CreateExpandedDSA(client, ad_group_id): + """Creates the expanded Dynamic Search Ad. + + Args: + client: an AdwordsClient instance. + ad_group_id: an integer ID of the ad group in which the DSA is added. + """ + # Get the AdGroupAdService. + ad_group_ad_service = client.GetService('AdGroupAdService') + + # Create the operation + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + # Create the expanded dynamic search ad. This ad will have its + # headline and final URL auto-generated at serving time according to + # domain name specific information provided by DynamicSearchAdsSetting + # at the campaign level. + 'ad': { + 'xsi_type': 'ExpandedDynamicSearchAd', + # Set the ad description. + 'description': 'Buy your tickets now!' + }, + # Optional: Set the status. + 'status': 'PAUSED', + } + }] + + # Create the ad. + ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] + + # Display the results. + print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' + 'added' % (ad['id'], ad['description'])) + + +def _AddWebPageCriteria(client, ad_group_id): + """Adds a web page criterion to target Dynamic Search Ads. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID of the ad group the criteria is being added to. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201705') + + operations = [{ + 'operator': 'ADD', + # Create biddable ad group criterion. + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion for special offers for children. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Special offers for children.', + 'conditions': [ + { + 'operand': 'URL', + 'argument': '/marscruise/children' + }, + { + 'operand': 'PAGE_TITLE', + 'argument': 'Special Offer' + } + ] + } + }, + 'userStatus': 'PAUSED', + # Optional: set a custom bid. + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000L + } + }] + } + } + }] + + criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201705/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..067f0d8c --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Create the expanded text ad + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': expanded_text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_html5_ad.py b/examples/adwords/v201705/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..011dfc9b --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_html5_ad.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..996b976b --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + media_service = client.GetService('MediaService', version='v201705') + + try: + # Create image. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + # Make the upload request + image = media_service.upload(image)[0] + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'] + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201705/advanced_operations/add_universal_app_campaign.py new file mode 100755 index 00000000..93ce0930 --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/add_universal_app_campaign.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Universal App campaign. + +To get campaigns, run get_campaigns.py. To upload image assets for this +campaign, run upload_image.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201705') + + budget_id = CreateBudget(client) + + # Create the Universal App campaign. + universal_app_campaign = { + 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'MULTI_CHANNEL', + 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', + # Set the campaign's bidding strategy. Universal app campaigns only + # support TARGET_CPA bidding strategy. + 'biddingStrategyConfiguration': { + # Set the target CPA to $1 / app install. + 'biddingScheme': { + 'xsi_type': 'TargetCpaBiddingScheme', + 'targetCpa': { + 'microAmount': '1000000' + } + }, + 'biddingStrategyType': 'TARGET_CPA' + }, + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + + universal_app_campaign['settings'] = [ + # Set the campaign's assets and ad text ideas. These values will + # be used to generate ads. + { + 'xsi_type': 'UniversalAppCampaignSetting', + 'appId': 'com.labpixies.colordrips', + 'description1': 'A cool puzzle game', + 'description2': 'Remove connected blocks', + 'description3': '3 difficulty levels', + 'description4': '4 colorful fun skins', + # Optional: You can set up to 10 image assets for your campaign. + # See upload_image.py for an example on how to upload images. + # + # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] + } + ] + + # Optimize this campaign for getting new users for your app. + universal_app_campaign_setting = universal_app_campaign['settings'][0] + universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( + 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') + + # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, + # then also specify your in-app conversion types so AdWords can focus your + # campaign on people who are most likely to complete the corresponding in-app + # actions. + # + # Conversions type IDs can be retrieved using ConversionTrackerService.get. + # universal_app_campaign['selectiveOptimization'] = { + # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] + # } + + # Optional: Set the campaign settings for Advanced location options. + universal_app_campaign['settings'].append({ + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + }) + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': universal_app_campaign + }] + + campaigns = campaign_service.mutate(operations)['value'] + + # Display results. + if campaigns: + for campaign in campaigns: + print ('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + # Optional: Set the campaign's location and language targeting. No other + # targeting criteria can be used for Universal App campaigns. + SetCampaignTargetingCriteria(client, campaign) + else: + print 'No Universal App campaigns were added.' + + +def CreateBudget(client): + """Creates a budget and returns its budgetId. + + Args: + client: An AdWordsClient instance. + + Returns: + An int budgetId for the created Budget. + """ + budget_service = client.GetService('BudgetService', version='v201705') + + # Create a budget. + budget = { + 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Create the budget and return its ID. + budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] + + return budget_id + + +def SetCampaignTargetingCriteria(client, campaign): + """Sets targeting criteria for the given campaign. + + Args: + client: An AdWordsClient instance. + campaign: A suds object representing the campaign we wish to attach + targeting criteria. + """ + campaign_criterion_service = client.GetService('CampaignCriterionService') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + criteria = [ + { + 'xsi_type': 'Location', + 'id': 21137 # California + }, + { + 'xsi_type': 'Location', + 'id': 2484 # Mexico + }, + { + 'xsi_type': 'Language', + 'id': 1000 # English + }, + { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + ] + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign['id'], + 'criterion': criterion + } + } for criterion in criteria] + + response = campaign_criterion_service.mutate(operations) + + if response and 'value' in response: + # Display the added campaign targets. + for criterion in response['value']: + print ('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], + criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201705/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..95cf7815 --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201705') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201705') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201705') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201705/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..03e3fa1b --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201705') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201705') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201705/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..7e6c0840 --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201705') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..1a9b9677 --- /dev/null +++ b/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201705') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201705') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201705') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201705/basic_operations/__init__.py b/examples/adwords/v201705/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201705/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201705/basic_operations/add_ad_groups.py b/examples/adwords/v201705/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..af65ca0d --- /dev/null +++ b/examples/adwords/v201705/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201705') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/basic_operations/add_campaigns.py b/examples/adwords/v201705/basic_operations/add_campaigns.py new file mode 100755 index 00000000..b7b3fe8e --- /dev/null +++ b/examples/adwords/v201705/basic_operations/add_campaigns.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201705') + budget_service = client.GetService('BudgetService', version='v201705') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201705/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..ea8a38f9 --- /dev/null +++ b/examples/adwords/v201705/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/add_keywords.py b/examples/adwords/v201705/basic_operations/add_keywords.py new file mode 100755 index 00000000..c0cf498b --- /dev/null +++ b/examples/adwords/v201705/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201705') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' + '\'%s\', text \'%s\', and match type \'%s\' was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/get_ad_groups.py b/examples/adwords/v201705/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..c9a96fd8 --- /dev/null +++ b/examples/adwords/v201705/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201705') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/basic_operations/get_campaigns.py b/examples/adwords/v201705/basic_operations/get_campaigns.py new file mode 100755 index 00000000..d22c960b --- /dev/null +++ b/examples/adwords/v201705/basic_operations/get_campaigns.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201705') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..32eca304 --- /dev/null +++ b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201705') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201705/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..ffaeedaa --- /dev/null +++ b/examples/adwords/v201705/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an expanded text ad, run add_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/get_keywords.py b/examples/adwords/v201705/basic_operations/get_keywords.py new file mode 100755 index 00000000..c986061e --- /dev/null +++ b/examples/adwords/v201705/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201705') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' + '\'%s\' was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/get_text_ads.py b/examples/adwords/v201705/basic_operations/get_text_ads.py new file mode 100755 index 00000000..0cb5a31f --- /dev/null +++ b/examples/adwords/v201705/basic_operations/get_text_ads.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 text ads for a given ad group. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/pause_ad.py b/examples/adwords/v201705/basic_operations/pause_ad.py new file mode 100755 index 00000000..979be365 --- /dev/null +++ b/examples/adwords/v201705/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201705/basic_operations/remove_ad.py b/examples/adwords/v201705/basic_operations/remove_ad.py new file mode 100755 index 00000000..49db1522 --- /dev/null +++ b/examples/adwords/v201705/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id \'%s\' and type \'%s\' was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201705/basic_operations/remove_ad_group.py b/examples/adwords/v201705/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..2426cddf --- /dev/null +++ b/examples/adwords/v201705/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201705') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/remove_campaign.py b/examples/adwords/v201705/basic_operations/remove_campaign.py new file mode 100755 index 00000000..672e6611 --- /dev/null +++ b/examples/adwords/v201705/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201705') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/basic_operations/remove_keyword.py b/examples/adwords/v201705/basic_operations/remove_keyword.py new file mode 100755 index 00000000..5229e03b --- /dev/null +++ b/examples/adwords/v201705/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201705') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201705/basic_operations/update_ad_group.py b/examples/adwords/v201705/basic_operations/update_ad_group.py new file mode 100755 index 00000000..8548597e --- /dev/null +++ b/examples/adwords/v201705/basic_operations/update_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201705') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name \'%s\' and id \'%s\' was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/update_campaign.py b/examples/adwords/v201705/basic_operations/update_campaign.py new file mode 100755 index 00000000..cee1f881 --- /dev/null +++ b/examples/adwords/v201705/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201705') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name \'%s\' and id \'%s\' was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/basic_operations/update_keyword.py b/examples/adwords/v201705/basic_operations/update_keyword.py new file mode 100755 index 00000000..965c7190 --- /dev/null +++ b/examples/adwords/v201705/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201705') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id \'%s\' and criterion id ' + '\'%s\' currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201705/campaign_management/__init__.py b/examples/adwords/v201705/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201705/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201705/campaign_management/add_campaign_groups_and_performance_targets.py new file mode 100755 index 00000000..9fda448f --- /dev/null +++ b/examples/adwords/v201705/campaign_management/add_campaign_groups_and_performance_targets.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a campaign group and sets a performance target for it. + +To get campaigns, run get_campaigns.py. To download reports, run +download_criteria_report_with_awql.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id1, campaign_id2): + campaign_group_id = _CreateCampaignGroup(client) + _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) + _CreatePerformanceTarget(client, campaign_group_id) + print 'Campaign group and its performance target were setup successfully.' + + +def _CreateCampaignGroup(client): + """Create a campaign group. + + Args: + client: an AdWordsClient instance. + + Returns: + The integer ID of the created campaign group. + """ + # Get the CampaignGroupService. + campaign_group_service = client.GetService('CampaignGroupService', + version='v201705') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the campaign group. + 'operand': { + 'name': 'Mars campaign group #%d' % uuid.uuid4() + } + }] + + campaign_group = campaign_group_service.mutate(operations)['value'][0] + campaign_group_id = campaign_group['id'] + + # Display the results. + print 'Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name']) + + return campaign_group_id + + +def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): + """Adds multiple campaigns to a campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + campaign_ids: a list of integer IDs for campaigns. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201705') + + # Create the operations. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'campaignGroupId': campaign_group_id + } + } for campaign_id in campaign_ids] + + campaign_service.mutate(operations) + + # Display the results. + print ('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + + +def _CreatePerformanceTarget(client, campaign_group_id): + """Creates a performance target for the campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + """ + # Get the CampaignGroupPerformanceTargetService. + cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', + version='v201705') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the performance target. + 'operand': { + 'campaignGroupId': campaign_group_id, + 'performanceTarget': { + # Keep the CPC for the campaigns < $3. + 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', + 'efficiencyTargetValue': 3000000, + # Keep the maximum spend under $50. + 'spendTargetType': 'MAXIMUM', + 'spendTarget': { + 'microAmount': 500000000 + }, + # Aim for at least 3000 clicks. + 'volumeGoalType': 'MAXIMIZE_CLICKS', + 'volumeTargetValue': 3000, + # Start the performance target today, and run it for the next 90 + # days. + 'startDate': datetime.datetime.now().strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(90)).strftime('%Y%m%d') + } + } + }] + + cgpt = cgpt_service.mutate(operations)['value'][0] + + # Display the results. + print ('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201705/campaign_management/add_campaign_labels.py b/examples/adwords/v201705/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..f27724d5 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201705') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201705/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201705/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..30076238 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201705') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201705') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding an ExpandedTextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new ExpandedTextAd for + each of the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once + # you've added targeting and the ads are ready to serve. + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201705') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201705/campaign_management/add_draft.py b/examples/adwords/v201705/campaign_management/add_draft.py new file mode 100755 index 00000000..3fd211dc --- /dev/null +++ b/examples/adwords/v201705/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + draft_service = client.GetService('DraftService', version='v201705') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201705') + + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..4ca7c4ad --- /dev/null +++ b/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201705') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201705') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201705') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201705') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the the BatchJob will + be checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201705/campaign_management/add_trial.py b/examples/adwords/v201705/campaign_management/add_trial.py new file mode 100755 index 00000000..580f0c91 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/add_trial.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201705') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201705') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..49283b24 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'PolicySummary'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + disapproved_count = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.get(selector) + + if 'entries' in page: + for ad in page['entries']: + policy_summary = ad['policySummary'] + + if policy_summary['combinedApprovalStatus'] != 'DISAPPROVED': + continue # Skip ads that are not disapproved. + + disapproved_count += 1 + + print ('Ad with id \'%s\' was disapproved with the following policy ' + 'topic entries:' % (ad['ad']['id'])) + + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..a1875525 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, PolicySummary ' + 'WHERE AdGroupId = %s ' + 'ORDER BY Id' % ad_group_id) + more_pages = True + disapproved_count = 0 + offset = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.query(query + ' LIMIT %s, %s' % ( + offset, PAGE_SIZE)) + + if 'entries' in page: + for ad in page['entries']: + policy_summary = ad['policySummary'] + + if policy_summary['combinedApprovalStatus'] != 'DISAPPROVED': + continue # Skip ads that are not disapproved. + + disapproved_count += 1 + + print ('Ad with id \'%s\' was disapproved with the following policy ' + 'topic entries:' % (ad['ad']['id'])) + + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..512e24fc --- /dev/null +++ b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201705') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201705/campaign_management/graduate_trial.py b/examples/adwords/v201705/campaign_management/graduate_trial.py new file mode 100755 index 00000000..da3fb1e0 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201705') + budget_service = client.GetService('BudgetService', version='v201705') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201705/campaign_management/set_ad_parameters.py b/examples/adwords/v201705/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..59bcda45 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + ad_param_service = client.GetService('AdParamService', version='v201705') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id \'%s\' was successfully added to an ad group with ' + 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text \'%s\' was successfully set for criterion ' + 'with id \'%s\' and ad group id \'%s\'.' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..bfdbe8b8 --- /dev/null +++ b/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201705') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' + 'was updated with bid modifier \'%s\'.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201705/campaign_management/validate_text_ad.py b/examples/adwords/v201705/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..f10b200d --- /dev/null +++ b/examples/adwords/v201705/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +No objects will be created, but exceptions will still be returned. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Construct operations to add an expanded text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'] + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for all astronauts in orbit', + 'finalUrls': ['http://www.example.com'], + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with \'%s\'.' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/error_handling/__init__.py b/examples/adwords/v201705/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201705/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201705/error_handling/handle_partial_failures.py b/examples/adwords/v201705/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..df78f623 --- /dev/null +++ b/examples/adwords/v201705/error_handling/handle_partial_failures.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201705') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id \'%s\', ' + 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + if (first_field_path_element and + first_field_path_element['field'] == 'operations' and + first_field_path_element['index']): + operation_index = first_field_path_element['index'] + + adgroup_criterion = operations[operation_index]['operand'] + + print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' + 'a failure for the following reason: %s.' + % (adgroup_criterion['adGroupId'], + adgroup_criterion['criterion']['text'], + error['errorString'])) + else: + print ('A failure has occured for the following reasons: %s\n' + % error['errorString']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/error_handling/handle_policy_violation_error.py b/examples/adwords/v201705/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..257ea52c --- /dev/null +++ b/examples/adwords/v201705/error_handling/handle_policy_violation_error.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201705') + + # Create expanded text ad that violates an exemptable policy. + exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise!!!', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + # Create text ad that violates a non-exemptable policy. + non_exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise with too long of a headline.', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + operations = [exemptable_expanded_text_ad_operation, + non_exemptable_expanded_text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + # Get the index of the failed operation from the error's field path + # elements. + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + # If the operation index is not present on the first error field path + # element, then there's no way to determine which operation to remove, + # so simply throw the exception. + if (not (first_field_path_element + and first_field_path_element['field'] == 'operations' + and first_field_path_element['index'])): + raise e + + operation_index = first_field_path_element['index'] + index = int(operation_index[0]) + operation = operations[index] + if not HandleAPIError(error, operation): + # Set non-exemptable operation to None to mark for deletion. + print ('Removing operation with non-exemptable error at index %s.' + % operation_index) + operations[index] = None + + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is \'%s\'.' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +def HandleAPIError(error, operation): + """Makes an exemption for exemptable PolicyViolationErrors. + + Args: + error: the error associated with the given operation. + operation: the operation associated with the given error. + + Returns: + A boolean that is True if the given error was an exemptable + PolicyViolationError; otherwise, returns False. + """ + is_exemptable = False + + # Determine if the operation can be resubmitted with an exemption request. + if error['ApiError.Type'] == 'PolicyViolationError': + expanded_text_ad = operation['operand']['ad'] + is_exemptable = (error['isExemptable'] if 'isExemptable' in error else + False) + print ('Ad with headline "%s - %s" violated %s policy "%s".' % + (expanded_text_ad['headlinePart1'], + expanded_text_ad['headlinePart2'], + 'exemptable' if is_exemptable else 'non-exemptable', + error['externalPolicyName'])) + + if is_exemptable: + # Add exemption request to the operation. + print ('Adding exemption request for policy name \'%s\' on text \'%s\'.' + % (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({'key': error['key']}) + + return is_exemptable + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/extensions/__init__.py b/examples/adwords/v201705/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201705/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201705/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201705/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..8f7db504 --- /dev/null +++ b/examples/adwords/v201705/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201705').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201705') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201705/extensions/add_prices.py b/examples/adwords/v201705/extensions/add_prices.py new file mode 100755 index 00000000..77106251 --- /dev/null +++ b/examples/adwords/v201705/extensions/add_prices.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201705') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', + final_mobile_url='http://m.example.com/scrubs'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url='http://m.example.com/haircuts'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url=( + 'http://m.example.com/skincarepackage')) + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit, final_mobile_url=None): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + final_mobile_url: A str containing the final mobile URL after all cross + domain redirects. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + table_row = { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + if final_mobile_url: + table_row['finalMobileUrls'] = { + 'urls': [final_mobile_url] + } + + return table_row + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/extensions/add_site_links.py b/examples/adwords/v201705/extensions/add_site_links.py new file mode 100755 index 00000000..44842a60 --- /dev/null +++ b/examples/adwords/v201705/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201705') + customer_service = client.GetService('CustomerService', version='v201705') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/extensions/add_site_links_using_feeds.py b/examples/adwords/v201705/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..ecbf0bd2 --- /dev/null +++ b/examples/adwords/v201705/extensions/add_site_links_using_feeds.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201705') + feed_item_service = client.GetService('FeedItemService', version='v201705') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201705') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201705') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name \'%s\' and ID \'%s\' was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 2 attribute ID \'%s\' and Line 3 attribute ID \'%s\'.' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line2': 'Home line 2', 'line3': 'Home line 3'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line2': 'Support line 2', 'line3': 'Support line 3'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line2': 'Products line 2', 'line3': 'Products line 3'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + feed_item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/migration/__init__.py b/examples/adwords/v201705/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201705/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201705/migration/migrate_to_extension_settings.py b/examples/adwords/v201705/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..1aa8b180 --- /dev/null +++ b/examples/adwords/v201705/migration/migrate_to_extension_settings.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201705') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201705') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201705') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201705') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201705') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201705') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201705') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/misc/__init__.py b/examples/adwords/v201705/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201705/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201705/misc/get_all_images_and_videos.py b/examples/adwords/v201705/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..df28bf8a --- /dev/null +++ b/examples/adwords/v201705/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201705') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id \'%s\' was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/misc/upload_image.py b/examples/adwords/v201705/misc/upload_image.py new file mode 100755 index 00000000..ff41c3f4 --- /dev/null +++ b/examples/adwords/v201705/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201705') + + with open(image_filename, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201705/misc/upload_media_bundle.py b/examples/adwords/v201705/misc/upload_media_bundle.py new file mode 100755 index 00000000..0329dcd6 --- /dev/null +++ b/examples/adwords/v201705/misc/upload_media_bundle.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201705') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/optimization/__init__.py b/examples/adwords/v201705/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201705/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201705/optimization/estimate_keyword_traffic.py b/examples/adwords/v201705/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..69cc319f --- /dev/null +++ b/examples/adwords/v201705/optimization/estimate_keyword_traffic.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201705') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201705/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..6d9f7c8d --- /dev/null +++ b/examples/adwords/v201705/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201705') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..008ed46b --- /dev/null +++ b/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201705') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id \'%s\', criterion id ' + '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201705/optimization/get_keyword_ideas.py b/examples/adwords/v201705/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..f79fab9d --- /dev/null +++ b/examples/adwords/v201705/optimization/get_keyword_ideas.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201705') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }, + { + # Network search parameter (optional) + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with \'%s\' text and average monthly search volume ' + '\'%s\' was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/__init__.py b/examples/adwords/v201705/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201705/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201705/remarketing/add_audience.py b/examples/adwords/v201705/remarketing/add_audience.py new file mode 100755 index 00000000..3874b42c --- /dev/null +++ b/examples/adwords/v201705/remarketing/add_audience.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201705') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201705') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name \'%s\' and ID \'%s\' was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/add_conversion_tracker.py b/examples/adwords/v201705/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..039b3932 --- /dev/null +++ b/examples/adwords/v201705/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201705') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' + 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/add_crm_based_user_list.py b/examples/adwords/v201705/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..ab80f224 --- /dev/null +++ b/examples/adwords/v201705/remarketing/add_crm_based_user_list.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201705') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180 + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + + emails = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] + + # Optional: AddressInfo is only accessible to whitelisted customers. + # If you are not on the whitelist, you should leave this code commented out. + # members.append({ + # 'addressInfo': { + # 'hashedFirstName': NormalizeAndSHA256('John'), + # 'hashedLastName': NormalizeAndSHA256('Doe'), + # 'countryCode': 'US', + # 'zipCode': '10001' + # } + # }) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'membersList': members + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def NormalizeAndSHA256(s): + """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. + + Args: + s: The string to perform this operation on. + + Returns: + A normalized and SHA-256 hashed string. + """ + return hashlib.sha256(s.strip().lower()).hexdigest() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201705/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..dce0078b --- /dev/null +++ b/examples/adwords/v201705/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201705') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords knows how to apply the + # rules. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ], + # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF + # means 'at least one item in each rule item group must match', and DNF + # means 'at least one entire rule item group must match'. + # DateSpecificRuleUserList only supports DNF. You can also omit the rule + # type altogether to default to DNF. + 'ruleType': 'DNF' + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule, + # Optional: Set the populationStatus to REQUESTED to include past users in + # the user list. + 'prepopulationStatus': 'REQUESTED' + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201705/remarketing/upload_offline_call_conversions.py new file mode 100755 index 00000000..3c234236 --- /dev/null +++ b/examples/adwords/v201705/remarketing/upload_offline_call_conversions.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for calls related to ads in your account. + +To set up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CALLER_ID = 'INSERT_CALLER_ID_HERE' +# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats +# For time zones, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +CALL_START_TIME = 'INSERT_CALL_START_TIME' +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, caller_id, call_start_time, conversion_name, conversion_time, + conversion_value): + # Initialize appropriate services. + occ_feed_service = client.GetService( + 'OfflineCallConversionFeedService', version='v201705') + + # Associate offline call conversions with the existing named conversion + # tracker. If this tracker was newly created, it may be a few hours before it + # can accept conversions. + feed = { + 'callerId': caller_id, + 'callStartTime': call_start_time, + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + } + + occ_operations = [{'operator': 'ADD', 'operand': feed}] + + occ_response = occ_feed_service.mutate(occ_operations) + values = occ_response['value'] + + if values: + for occ_feed in values: + print ('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + else: + print 'No offline call conversions were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, + CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201705/remarketing/upload_offline_conversions.py b/examples/adwords/v201705/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..3e67a371 --- /dev/null +++ b/examples/adwords/v201705/remarketing/upload_offline_conversions.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_tracker.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201705') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' + '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201705/reporting/__init__.py b/examples/adwords/v201705/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201705/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..a879538c --- /dev/null +++ b/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201705') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_selector.py new file mode 100755 index 00000000..b3d789cf --- /dev/null +++ b/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_selector.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201705') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..4de147f4 --- /dev/null +++ b/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201705') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_selector.py new file mode 100755 index 00000000..42c70e5b --- /dev/null +++ b/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_selector.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201705') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201705/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..a9ddc13f --- /dev/null +++ b/examples/adwords/v201705/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import sys +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201705') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + # You can provide a file object to write the output to. For this + # demonstration we use sys.stdout to write the report to the screen. + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', sys.stdout, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201705/reporting/download_criteria_report_with_selector.py new file mode 100755 index 00000000..e1fda28d --- /dev/null +++ b/examples/adwords/v201705/reporting/download_criteria_report_with_selector.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201705') + + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201705/reporting/get_report_fields.py b/examples/adwords/v201705/reporting/get_report_fields.py new file mode 100755 index 00000000..ce5839ac --- /dev/null +++ b/examples/adwords/v201705/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201705') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type \'%s\' contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201705/reporting/parallel_report_download.py b/examples/adwords/v201705/reporting/parallel_report_download.py new file mode 100755 index 00000000..0a4578fd --- /dev/null +++ b/examples/adwords/v201705/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201705') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201705') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201705/shopping/__init__.py b/examples/adwords/v201705/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201705/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201705/shopping/add_product_partition_tree.py b/examples/adwords/v201705/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..5098996d --- /dev/null +++ b/examples/adwords/v201705/shopping/add_product_partition_tree.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201705') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201705/shopping/add_product_scope.py b/examples/adwords/v201705/shopping/add_product_scope.py new file mode 100755 index 00000000..47642112 --- /dev/null +++ b/examples/adwords/v201705/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201705') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/shopping/add_shopping_campaign.py b/examples/adwords/v201705/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..cbebb1ae --- /dev/null +++ b/examples/adwords/v201705/shopping/add_shopping_campaign.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +# If set to true, a default partition will be created. If running the +# add_product_partition_tree.py example right after this example, make +# sure this stays set to false. +CREATE_DEFAULT_PARTITION = False +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id, create_default_partition): + campaign_service = client.GetService('CampaignService', version='v201705') + ad_group_service = client.GetService('AdGroupService', version='v201705') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + ad_group = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': ad_group + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] + + print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + % (ad_group['name'], ad_group_id)) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': ad_group_id, + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201705') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + }, + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 500000 + } + }] + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py new file mode 100755 index 00000000..9e1f8790 --- /dev/null +++ b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py @@ -0,0 +1,404 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds a Shopping campaign for Showcase ads. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import uuid + +from googleads import adwords +from suds import WebFault + + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' +EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' +COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + # Note: Showcase ads require either ManualCpc or EnhancedCpc in the + # campaign's BiddingStrategyConfiguration. + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, budget_id, merchant_id, expanded_image_filepath, + collapsed_image_filepath): + try: + # Create the Shopping Campaign + campaign = CreateShoppingCampaign(client, budget_id, merchant_id) + + # Create the AdGroup + adgroup = CreateAdGroup(client, campaign['id']) + + # Create a Showcase Ad + CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath) + + product_partition_tree = CreateProductPartition(client, adgroup['id']) + print 'Final tree:\n%s' % product_partition_tree + except WebFault: + print 'Failed to create shopping campaign for showcase ads.' + raise + + +def CreateShoppingCampaign(client, budget_id, merchant_id): + """Creates a shopping campaign with the given budget and merchant IDs. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + shopping campaign. + + Returns: + The created Shopping Campaign as a sudsobject. + """ + campaign_service = client.GetService('CampaignService', 'v201705') + + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + campaign = campaign_service.mutate(campaign_operations)['value'][0] + print ('Campaign with name \'%s\' and ID \'%s\' was added.' + % (campaign['name'], campaign['id'])) + + return campaign + + +def CreateAdGroup(client, campaign_id): + """Creates an AdGroup for the given shopping campaign ID. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a shopping campaign. + + Returns: + The created AdGroup as a sudsobject. + """ + ad_group_service = client.GetService('AdGroupService', 'v201705') + + adgroup = { + # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS + 'adGroupType': 'SHOPPING_SHOWCASE_ADS', + 'campaignId': campaign_id, + 'name': 'AdGroup #%s' % uuid.uuid4(), + # REQUIRED: Set the ad group's bidding strategy configuration. + 'biddingStrategyConfiguration': { + # Showcase ads require either ManualCpc or EnhancedCpc. + 'biddingStrategyType': 'MANUAL_CPC', + # Optional: Set the bids + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 100000 + } + }] + } + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) + + return adgroup + + +def CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath): + """Creates a showcase add for the given AdGroup with the given images. + + Args: + client: an AdWordsClient instance. + adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + expanded_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's expandedImage. + collapsed_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's collapsedImage. + + Returns: + The created Showcase Ad as a sudsobject. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201705') + + showcase_ad = { + 'adGroupId': adgroup['id'], + 'ad': { + 'xsi_type': 'ShowcaseAd', + 'Ad.Type': 'ShowcaseAd', + # Required: set the ad's name, final URLs, and display URL. + 'name': 'Showcase ad #%s' % uuid.uuid4(), + 'finalUrls': 'http://example.com/showcase', + 'displayUrl': 'example.com', + # Required: Set the ad's expanded image. + 'expandedImage': { + 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] + }, + # Optional: Set the collapsed image. + 'collapsedImage': { + 'mediaId': + UploadImage(client, collapsed_image_filepath)['mediaId'] + } + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': showcase_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] + + print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + + return showcase_ad + + +def UploadImage(client, filepath): + """Uploads a .jpg image with the given filepath via the AdWords MediaService. + + Args: + client: an AdWordsClient instance. + filepath: a str filepath to the .jpg file to be uploaded. + + Returns: + The created Image as a sudsobject. + """ + media_service = client.GetService('MediaService', 'v201705') + + with open(filepath, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + image = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + + image = media_service.upload(image)[0] + + return image + + +def CreateProductPartition(client, adgroup_id): + """Creates a ProductPartition tree for the given AdGroup ID. + + Args: + client: an AdWordsClient instance. + adgroup_id: a str AdGroup ID. + + Returns: + The ProductPartition tree as a sudsobject. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + 'v201705') + helper = ProductPartitionHelper(adgroup_id) + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition) + helper.CreateUnit(root, used_product_canonical_condition) + helper.CreateUnit(root, other_product_canonical_condition) + + result = ad_group_criterion_service.mutate(helper.operations) + return result['value'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, + COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201705/shopping/get_product_category_taxonomy.py b/examples/adwords/v201705/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..23495f92 --- /dev/null +++ b/examples/adwords/v201705/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201705') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/targeting/__init__.py b/examples/adwords/v201705/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201705/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..15dd21c1 --- /dev/null +++ b/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201705') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' + 'and type \'%s\' was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..c175a2f1 --- /dev/null +++ b/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201705') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type \'%s\' was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201705/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..14ad4409 --- /dev/null +++ b/examples/adwords/v201705/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201705') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..221e8f63 --- /dev/null +++ b/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201705') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name \'%s\' and ID \'%s\' was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201705/targeting/lookup_location.py b/examples/adwords/v201705/targeting/lookup_location.py new file mode 100755 index 00000000..75bbf1c2 --- /dev/null +++ b/examples/adwords/v201705/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201705') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' + ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/dfp/authentication/create_dfp_client_with_service_account.py index 3f7dcc2f..11f0462b 100755 --- a/examples/dfp/authentication/create_dfp_client_with_service_account.py +++ b/examples/dfp/authentication/create_dfp_client_with_service_account.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/authentication/create_dfp_client_without_yaml.py b/examples/dfp/authentication/create_dfp_client_without_yaml.py index 9b15b3ca..f857f9bc 100755 --- a/examples/dfp/authentication/create_dfp_client_without_yaml.py +++ b/examples/dfp/authentication/create_dfp_client_without_yaml.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py index d725022e..4e261fe2 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/dfp/authentication/generate_refresh_token.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2014 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201611/activity_group_service/__init__.py b/examples/dfp/v201611/activity_group_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_group_service/create_activity_groups.py b/examples/dfp/v201611/activity_group_service/create_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_group_service/update_activity_groups.py b/examples/dfp/v201611/activity_group_service/update_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_service/__init__.py b/examples/dfp/v201611/activity_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_service/create_activities.py b/examples/dfp/v201611/activity_service/create_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_service/get_active_activities.py b/examples/dfp/v201611/activity_service/get_active_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_service/get_all_activities.py b/examples/dfp/v201611/activity_service/get_all_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/activity_service/update_activities.py b/examples/dfp/v201611/activity_service/update_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/audience_segment_service/__init__.py b/examples/dfp/v201611/audience_segment_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/audience_segment_service/create_audience_segments.py b/examples/dfp/v201611/audience_segment_service/create_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/audience_segment_service/update_audience_segments.py b/examples/dfp/v201611/audience_segment_service/update_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/base_rate_service/__init__.py b/examples/dfp/v201611/base_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/base_rate_service/create_product_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/base_rate_service/get_all_base_rates.py b/examples/dfp/v201611/base_rate_service/get_all_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/base_rate_service/update_base_rates.py b/examples/dfp/v201611/base_rate_service/update_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/company_service/__init__.py b/examples/dfp/v201611/company_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/company_service/create_companies.py b/examples/dfp/v201611/company_service/create_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/company_service/get_advertisers.py b/examples/dfp/v201611/company_service/get_advertisers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/company_service/get_all_companies.py b/examples/dfp/v201611/company_service/get_all_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/company_service/update_companies.py b/examples/dfp/v201611/company_service/update_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/contact_service/__init__.py b/examples/dfp/v201611/contact_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/contact_service/create_contacts.py b/examples/dfp/v201611/contact_service/create_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/contact_service/get_all_contacts.py b/examples/dfp/v201611/contact_service/get_all_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/contact_service/get_uninvited_contacts.py b/examples/dfp/v201611/contact_service/get_uninvited_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/contact_service/update_contacts.py b/examples/dfp/v201611/contact_service/update_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/content_service/__init__.py b/examples/dfp/v201611/content_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/content_service/get_all_content.py b/examples/dfp/v201611/content_service/get_all_content.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_service/__init__.py b/examples/dfp/v201611/creative_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_service/create_creative_from_template.py b/examples/dfp/v201611/creative_service/create_creative_from_template.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_service/create_creatives.py b/examples/dfp/v201611/creative_service/create_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_service/create_custom_creative.py b/examples/dfp/v201611/creative_service/create_custom_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_service/create_native_creative.py b/examples/dfp/v201611/creative_service/create_native_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_service/get_all_creatives.py b/examples/dfp/v201611/creative_service/get_all_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_service/get_image_creatives.py b/examples/dfp/v201611/creative_service/get_image_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_service/update_creatives.py b/examples/dfp/v201611/creative_service/update_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_set_service/__init__.py b/examples/dfp/v201611/creative_set_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_set_service/create_creative_set.py b/examples/dfp/v201611/creative_set_service/create_creative_set.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_set_service/update_creative_set.py b/examples/dfp/v201611/creative_set_service/update_creative_set.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_template_service/__init__.py b/examples/dfp/v201611/creative_template_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_field_service/__init__.py b/examples/dfp/v201611/custom_field_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_field_service/create_custom_field_options.py b/examples/dfp/v201611/custom_field_service/create_custom_field_options.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_field_service/create_custom_fields.py b/examples/dfp/v201611/custom_field_service/create_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_field_service/update_custom_fields.py b/examples/dfp/v201611/custom_field_service/update_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_targeting_service/__init__.py b/examples/dfp/v201611/custom_targeting_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/exchange_rate_service/__init__.py b/examples/dfp/v201611/exchange_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/forecast_service/get_availability_forecast.py b/examples/dfp/v201611/forecast_service/get_availability_forecast.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/inventory_service/__init__.py b/examples/dfp/v201611/inventory_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/inventory_service/archive_ad_units.py b/examples/dfp/v201611/inventory_service/archive_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/inventory_service/create_ad_units.py b/examples/dfp/v201611/inventory_service/create_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_units.py b/examples/dfp/v201611/inventory_service/get_all_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/inventory_service/update_ad_units.py b/examples/dfp/v201611/inventory_service/update_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/label_service/__init__.py b/examples/dfp/v201611/label_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/label_service/create_labels.py b/examples/dfp/v201611/label_service/create_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/label_service/deactivate_labels.py b/examples/dfp/v201611/label_service/deactivate_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/label_service/get_active_labels.py b/examples/dfp/v201611/label_service/get_active_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/label_service/get_all_labels.py b/examples/dfp/v201611/label_service/get_all_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/label_service/update_labels.py b/examples/dfp/v201611/label_service/update_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_creative_association_service/__init__.py b/examples/dfp/v201611/line_item_creative_association_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_creative_association_service/create_licas.py b/examples/dfp/v201611/line_item_creative_association_service/create_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/__init__.py b/examples/dfp/v201611/line_item_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/activate_line_items.py b/examples/dfp/v201611/line_item_service/activate_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/create_line_items.py b/examples/dfp/v201611/line_item_service/create_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/create_video_line_item.py b/examples/dfp/v201611/line_item_service/create_video_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/get_all_line_items.py b/examples/dfp/v201611/line_item_service/get_all_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/target_custom_criteria.py b/examples/dfp/v201611/line_item_service/target_custom_criteria.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/line_item_service/update_line_items.py b/examples/dfp/v201611/line_item_service/update_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/network_service/__init__.py b/examples/dfp/v201611/network_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/network_service/get_all_networks.py b/examples/dfp/v201611/network_service/get_all_networks.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/network_service/make_test_network.py b/examples/dfp/v201611/network_service/make_test_network.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/order_service/__init__.py b/examples/dfp/v201611/order_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/order_service/approve_orders.py b/examples/dfp/v201611/order_service/approve_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/order_service/create_orders.py b/examples/dfp/v201611/order_service/create_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/order_service/get_all_orders.py b/examples/dfp/v201611/order_service/get_all_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/order_service/get_orders_starting_soon.py b/examples/dfp/v201611/order_service/get_orders_starting_soon.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/order_service/update_orders.py b/examples/dfp/v201611/order_service/update_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/package_service/get_all_packages.py b/examples/dfp/v201611/package_service/get_all_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/package_service/get_in_progress_packages.py b/examples/dfp/v201611/package_service/get_in_progress_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/placement_service/create_placements.py b/examples/dfp/v201611/placement_service/create_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/placement_service/deactivate_placements.py b/examples/dfp/v201611/placement_service/deactivate_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/placement_service/get_active_placements.py b/examples/dfp/v201611/placement_service/get_active_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/placement_service/get_all_placements.py b/examples/dfp/v201611/placement_service/get_all_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/placement_service/update_placements.py b/examples/dfp/v201611/placement_service/update_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/premium_rate_service/__init__.py b/examples/dfp/v201611/premium_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/premium_rate_service/create_premium_rates.py b/examples/dfp/v201611/premium_rate_service/create_premium_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/premium_rate_service/update_premium_rates.py b/examples/dfp/v201611/premium_rate_service/update_premium_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_package_service/get_active_product_packages.py b/examples/dfp/v201611/product_package_service/get_active_product_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_package_service/get_all_product_packages.py b/examples/dfp/v201611/product_package_service/get_all_product_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_service/__init__.py b/examples/dfp/v201611/product_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_service/get_all_products.py b/examples/dfp/v201611/product_service/get_all_products.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_service/get_products_for_product_template.py b/examples/dfp/v201611/product_service/get_products_for_product_template.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_service/update_products.py b/examples/dfp/v201611/product_service/update_products.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_template_service/__init__.py b/examples/dfp/v201611/product_template_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_template_service/activate_product_templates.py b/examples/dfp/v201611/product_template_service/activate_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_template_service/create_product_templates.py b/examples/dfp/v201611/product_template_service/create_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_template_service/get_all_product_templates.py b/examples/dfp/v201611/product_template_service/get_all_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/product_template_service/update_product_templates.py b/examples/dfp/v201611/product_template_service/update_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_line_item_service/__init__.py b/examples/dfp/v201611/proposal_line_item_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/__init__.py b/examples/dfp/v201611/proposal_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/create_proposals.py b/examples/dfp/v201611/proposal_service/create_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/get_all_proposals.py b/examples/dfp/v201611/proposal_service/get_all_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/get_marketplace_comments.py b/examples/dfp/v201611/proposal_service/get_marketplace_comments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/proposal_service/update_proposals.py b/examples/dfp/v201611/proposal_service/update_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/publisher_query_language_service/__init__.py b/examples/dfp/v201611/publisher_query_language_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/rate_card_service/__init__.py b/examples/dfp/v201611/rate_card_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/report_service/__init__.py b/examples/dfp/v201611/report_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/report_service/run_delivery_report.py b/examples/dfp/v201611/report_service/run_delivery_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/report_service/run_inventory_report.py b/examples/dfp/v201611/report_service/run_inventory_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/report_service/run_reach_report.py b/examples/dfp/v201611/report_service/run_reach_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/report_service/run_report_with_custom_fields.py b/examples/dfp/v201611/report_service/run_report_with_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/report_service/run_sales_report.py b/examples/dfp/v201611/report_service/run_sales_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/report_service/run_saved_query.py b/examples/dfp/v201611/report_service/run_saved_query.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/suggested_ad_unit_service/__init__.py b/examples/dfp/v201611/suggested_ad_unit_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/team_service/__init__.py b/examples/dfp/v201611/team_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/team_service/create_teams.py b/examples/dfp/v201611/team_service/create_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/team_service/get_all_teams.py b/examples/dfp/v201611/team_service/get_all_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/team_service/update_teams.py b/examples/dfp/v201611/team_service/update_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_service/__init__.py b/examples/dfp/v201611/user_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_service/create_users.py b/examples/dfp/v201611/user_service/create_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_service/deactivate_users.py b/examples/dfp/v201611/user_service/deactivate_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_service/get_all_roles.py b/examples/dfp/v201611/user_service/get_all_roles.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_service/get_all_users.py b/examples/dfp/v201611/user_service/get_all_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_service/get_user_by_email_address.py b/examples/dfp/v201611/user_service/get_user_by_email_address.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_service/update_users.py b/examples/dfp/v201611/user_service/update_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_team_association_service/__init__.py b/examples/dfp/v201611/user_team_association_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/workflow_request_service/__init__.py b/examples/dfp/v201611/workflow_request_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_group_service/__init__.py b/examples/dfp/v201702/activity_group_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_group_service/create_activity_groups.py b/examples/dfp/v201702/activity_group_service/create_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_group_service/update_activity_groups.py b/examples/dfp/v201702/activity_group_service/update_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_service/__init__.py b/examples/dfp/v201702/activity_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_service/create_activities.py b/examples/dfp/v201702/activity_service/create_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_service/get_active_activities.py b/examples/dfp/v201702/activity_service/get_active_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_service/get_all_activities.py b/examples/dfp/v201702/activity_service/get_all_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/activity_service/update_activities.py b/examples/dfp/v201702/activity_service/update_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/audience_segment_service/__init__.py b/examples/dfp/v201702/audience_segment_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py b/examples/dfp/v201702/audience_segment_service/create_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py b/examples/dfp/v201702/audience_segment_service/update_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/base_rate_service/__init__.py b/examples/dfp/v201702/base_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py index 9a992ff4..63ffec25 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py b/examples/dfp/v201702/base_rate_service/get_all_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/base_rate_service/update_base_rates.py b/examples/dfp/v201702/base_rate_service/update_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/company_service/__init__.py b/examples/dfp/v201702/company_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/company_service/create_companies.py b/examples/dfp/v201702/company_service/create_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/company_service/get_advertisers.py b/examples/dfp/v201702/company_service/get_advertisers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/company_service/get_all_companies.py b/examples/dfp/v201702/company_service/get_all_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/company_service/update_companies.py b/examples/dfp/v201702/company_service/update_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/contact_service/__init__.py b/examples/dfp/v201702/contact_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/contact_service/create_contacts.py b/examples/dfp/v201702/contact_service/create_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/contact_service/get_all_contacts.py b/examples/dfp/v201702/contact_service/get_all_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/contact_service/get_uninvited_contacts.py b/examples/dfp/v201702/contact_service/get_uninvited_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/contact_service/update_contacts.py b/examples/dfp/v201702/contact_service/update_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/content_service/__init__.py b/examples/dfp/v201702/content_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/content_service/get_all_content.py b/examples/dfp/v201702/content_service/get_all_content.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_service/__init__.py b/examples/dfp/v201702/creative_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_service/copy_image_creatives.py b/examples/dfp/v201702/creative_service/copy_image_creatives.py index fcb12cd2..34854b79 100755 --- a/examples/dfp/v201702/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201702/creative_service/copy_image_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/creative_service/create_creative_from_template.py b/examples/dfp/v201702/creative_service/create_creative_from_template.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_service/create_creatives.py b/examples/dfp/v201702/creative_service/create_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_service/create_custom_creative.py b/examples/dfp/v201702/creative_service/create_custom_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_service/create_native_creative.py b/examples/dfp/v201702/creative_service/create_native_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_service/get_all_creatives.py b/examples/dfp/v201702/creative_service/get_all_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_service/get_image_creatives.py b/examples/dfp/v201702/creative_service/get_image_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_service/update_creatives.py b/examples/dfp/v201702/creative_service/update_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_set_service/__init__.py b/examples/dfp/v201702/creative_set_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_set_service/create_creative_set.py b/examples/dfp/v201702/creative_set_service/create_creative_set.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_set_service/update_creative_set.py b/examples/dfp/v201702/creative_set_service/update_creative_set.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_template_service/__init__.py b/examples/dfp/v201702/creative_template_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_field_service/__init__.py b/examples/dfp/v201702/custom_field_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py b/examples/dfp/v201702/custom_field_service/create_custom_field_options.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_field_service/create_custom_fields.py b/examples/dfp/v201702/custom_field_service/create_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_field_service/update_custom_fields.py b/examples/dfp/v201702/custom_field_service/update_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_targeting_service/__init__.py b/examples/dfp/v201702/custom_targeting_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/exchange_rate_service/__init__.py b/examples/dfp/v201702/exchange_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast.py b/examples/dfp/v201702/forecast_service/get_availability_forecast.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/inventory_service/__init__.py b/examples/dfp/v201702/inventory_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/inventory_service/archive_ad_units.py b/examples/dfp/v201702/inventory_service/archive_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/inventory_service/create_ad_units.py b/examples/dfp/v201702/inventory_service/create_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_units.py b/examples/dfp/v201702/inventory_service/get_all_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/inventory_service/update_ad_units.py b/examples/dfp/v201702/inventory_service/update_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/label_service/__init__.py b/examples/dfp/v201702/label_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/label_service/create_labels.py b/examples/dfp/v201702/label_service/create_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/label_service/deactivate_labels.py b/examples/dfp/v201702/label_service/deactivate_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/label_service/get_active_labels.py b/examples/dfp/v201702/label_service/get_active_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/label_service/get_all_labels.py b/examples/dfp/v201702/label_service/get_all_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/label_service/update_labels.py b/examples/dfp/v201702/label_service/update_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_creative_association_service/__init__.py b/examples/dfp/v201702/line_item_creative_association_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py b/examples/dfp/v201702/line_item_creative_association_service/create_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/__init__.py b/examples/dfp/v201702/line_item_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/activate_line_items.py b/examples/dfp/v201702/line_item_service/activate_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/create_line_items.py b/examples/dfp/v201702/line_item_service/create_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/create_video_line_item.py b/examples/dfp/v201702/line_item_service/create_video_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/get_all_line_items.py b/examples/dfp/v201702/line_item_service/get_all_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/pause_line_items.py b/examples/dfp/v201702/line_item_service/pause_line_items.py index babafa4b..42ed186a 100755 --- a/examples/dfp/v201702/line_item_service/pause_line_items.py +++ b/examples/dfp/v201702/line_item_service/pause_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/line_item_service/target_custom_criteria.py b/examples/dfp/v201702/line_item_service/target_custom_criteria.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/line_item_service/update_line_items.py b/examples/dfp/v201702/line_item_service/update_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/native_style_service/__init__.py b/examples/dfp/v201702/native_style_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/native_style_service/create_native_styles.py b/examples/dfp/v201702/native_style_service/create_native_styles.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/native_style_service/get_all_native_styles.py b/examples/dfp/v201702/native_style_service/get_all_native_styles.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/network_service/__init__.py b/examples/dfp/v201702/network_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/network_service/get_all_networks.py b/examples/dfp/v201702/network_service/get_all_networks.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/network_service/make_test_network.py b/examples/dfp/v201702/network_service/make_test_network.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/order_service/__init__.py b/examples/dfp/v201702/order_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/order_service/approve_orders.py b/examples/dfp/v201702/order_service/approve_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/order_service/create_orders.py b/examples/dfp/v201702/order_service/create_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/order_service/get_all_orders.py b/examples/dfp/v201702/order_service/get_all_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/order_service/get_orders_starting_soon.py b/examples/dfp/v201702/order_service/get_orders_starting_soon.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/order_service/update_orders.py b/examples/dfp/v201702/order_service/update_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/package_service/create_packages.py b/examples/dfp/v201702/package_service/create_packages.py index a0466f72..3b4929b8 100755 --- a/examples/dfp/v201702/package_service/create_packages.py +++ b/examples/dfp/v201702/package_service/create_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py index 721d4e43..901d0967 100755 --- a/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py +++ b/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/package_service/get_all_packages.py b/examples/dfp/v201702/package_service/get_all_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/package_service/get_in_progress_packages.py b/examples/dfp/v201702/package_service/get_in_progress_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/placement_service/create_placements.py b/examples/dfp/v201702/placement_service/create_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/placement_service/deactivate_placements.py b/examples/dfp/v201702/placement_service/deactivate_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/placement_service/get_active_placements.py b/examples/dfp/v201702/placement_service/get_active_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/placement_service/get_all_placements.py b/examples/dfp/v201702/placement_service/get_all_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/placement_service/update_placements.py b/examples/dfp/v201702/placement_service/update_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/premium_rate_service/__init__.py b/examples/dfp/v201702/premium_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py b/examples/dfp/v201702/premium_rate_service/create_premium_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py b/examples/dfp/v201702/premium_rate_service/update_premium_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_package_item_service/create_product_package_item.py b/examples/dfp/v201702/product_package_item_service/create_product_package_item.py index 4c31eef9..3234b2e3 100755 --- a/examples/dfp/v201702/product_package_item_service/create_product_package_item.py +++ b/examples/dfp/v201702/product_package_item_service/create_product_package_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_package_service/create_product_packages.py b/examples/dfp/v201702/product_package_service/create_product_packages.py index ec3173e0..12310f60 100755 --- a/examples/dfp/v201702/product_package_service/create_product_packages.py +++ b/examples/dfp/v201702/product_package_service/create_product_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/product_package_service/get_active_product_packages.py b/examples/dfp/v201702/product_package_service/get_active_product_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_package_service/get_all_product_packages.py b/examples/dfp/v201702/product_package_service/get_all_product_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_service/__init__.py b/examples/dfp/v201702/product_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_service/get_all_products.py b/examples/dfp/v201702/product_service/get_all_products.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_service/get_products_for_product_template.py b/examples/dfp/v201702/product_service/get_products_for_product_template.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_service/update_products.py b/examples/dfp/v201702/product_service/update_products.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_template_service/__init__.py b/examples/dfp/v201702/product_template_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_template_service/activate_product_templates.py b/examples/dfp/v201702/product_template_service/activate_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_template_service/create_product_templates.py b/examples/dfp/v201702/product_template_service/create_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_template_service/get_all_product_templates.py b/examples/dfp/v201702/product_template_service/get_all_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/product_template_service/update_product_templates.py b/examples/dfp/v201702/product_template_service/update_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_line_item_service/__init__.py b/examples/dfp/v201702/proposal_line_item_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/__init__.py b/examples/dfp/v201702/proposal_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/create_proposals.py b/examples/dfp/v201702/proposal_service/create_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/get_all_proposals.py b/examples/dfp/v201702/proposal_service/get_all_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py b/examples/dfp/v201702/proposal_service/get_marketplace_comments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/proposal_service/update_proposals.py b/examples/dfp/v201702/proposal_service/update_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/publisher_query_language_service/__init__.py b/examples/dfp/v201702/publisher_query_language_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/rate_card_service/__init__.py b/examples/dfp/v201702/rate_card_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/rate_card_service/create_rate_cards.py b/examples/dfp/v201702/rate_card_service/create_rate_cards.py index 45f30941..86ae53a0 100755 --- a/examples/dfp/v201702/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201702/rate_card_service/create_rate_cards.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/report_service/__init__.py b/examples/dfp/v201702/report_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/report_service/run_delivery_report.py b/examples/dfp/v201702/report_service/run_delivery_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/report_service/run_inventory_report.py b/examples/dfp/v201702/report_service/run_inventory_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/report_service/run_reach_report.py b/examples/dfp/v201702/report_service/run_reach_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py b/examples/dfp/v201702/report_service/run_report_with_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/report_service/run_sales_report.py b/examples/dfp/v201702/report_service/run_sales_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/report_service/run_saved_query.py b/examples/dfp/v201702/report_service/run_saved_query.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/suggested_ad_unit_service/__init__.py b/examples/dfp/v201702/suggested_ad_unit_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/team_service/__init__.py b/examples/dfp/v201702/team_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/team_service/create_teams.py b/examples/dfp/v201702/team_service/create_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/team_service/get_all_teams.py b/examples/dfp/v201702/team_service/get_all_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/team_service/update_teams.py b/examples/dfp/v201702/team_service/update_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_service/__init__.py b/examples/dfp/v201702/user_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_service/create_users.py b/examples/dfp/v201702/user_service/create_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_service/deactivate_users.py b/examples/dfp/v201702/user_service/deactivate_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_service/get_all_roles.py b/examples/dfp/v201702/user_service/get_all_roles.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_service/get_all_users.py b/examples/dfp/v201702/user_service/get_all_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_service/get_current_user.py b/examples/dfp/v201702/user_service/get_current_user.py index 2c056f48..81794ed3 100755 --- a/examples/dfp/v201702/user_service/get_current_user.py +++ b/examples/dfp/v201702/user_service/get_current_user.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201702/user_service/get_user_by_email_address.py b/examples/dfp/v201702/user_service/get_user_by_email_address.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_service/update_users.py b/examples/dfp/v201702/user_service/update_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_team_association_service/__init__.py b/examples/dfp/v201702/user_team_association_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/workflow_request_service/__init__.py b/examples/dfp/v201702/workflow_request_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_group_service/__init__.py b/examples/dfp/v201705/activity_group_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_group_service/create_activity_groups.py b/examples/dfp/v201705/activity_group_service/create_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201705/activity_group_service/get_active_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_group_service/update_activity_groups.py b/examples/dfp/v201705/activity_group_service/update_activity_groups.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_service/__init__.py b/examples/dfp/v201705/activity_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_service/create_activities.py b/examples/dfp/v201705/activity_service/create_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_service/get_active_activities.py b/examples/dfp/v201705/activity_service/get_active_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_service/get_all_activities.py b/examples/dfp/v201705/activity_service/get_all_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/activity_service/update_activities.py b/examples/dfp/v201705/activity_service/update_activities.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/audience_segment_service/__init__.py b/examples/dfp/v201705/audience_segment_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/audience_segment_service/create_audience_segments.py b/examples/dfp/v201705/audience_segment_service/create_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/audience_segment_service/update_audience_segments.py b/examples/dfp/v201705/audience_segment_service/update_audience_segments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/base_rate_service/__init__.py b/examples/dfp/v201705/base_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/base_rate_service/create_product_base_rates.py b/examples/dfp/v201705/base_rate_service/create_product_base_rates.py old mode 100644 new mode 100755 index 453ab744..8422c666 --- a/examples/dfp/v201705/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/create_product_base_rates.py @@ -36,7 +36,9 @@ def main(client, product_id, rate_card_id): # Create a product base rate. product_base_rate = { 'xsi_type': 'ProductBaseRate', + # Set the rate card ID that the product base rate belongs to. 'rateCardId': rate_card_id, + # Set the product id the base rate will be applied to. 'productId': product_id, # Set the rate to be $2. 'rate': { @@ -45,7 +47,7 @@ def main(client, product_id, rate_card_id): } } - # Create base rates on the server. + # Create the product base rate on the server. base_rates = base_rate_service.createBaseRates( [product_base_rate]) diff --git a/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py index 67397296..bd7779cb 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # @@ -34,7 +34,7 @@ def main(client): base_rate_service = client.GetService('BaseRateService', version='v201705') # Create a base rate for a product package item. - base_rate = { + product_package_item_base_rate = { 'xsi_type': 'ProductPackageItemBaseRate', # Set the rate card ID that the product package item base rate # belongs to. @@ -51,7 +51,7 @@ def main(client): } # Create the product package item base rate on the server. - result = base_rate_service.createBaseRates([base_rate]) + result = base_rate_service.createBaseRates([product_package_item_base_rate]) for new_base_rate in result: print ('A product package item base rate with ID %d and rate %f %s ' diff --git a/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py old mode 100644 new mode 100755 index 2d42c897..0e4e4f91 --- a/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py @@ -36,7 +36,9 @@ def main(client, product_template_id, rate_card_id): # Create a product template base rate. product_template_base_rate = { 'xsi_type': 'ProductTemplateBaseRate', + # Set the rate card ID that the product template base rate belongs to. 'rateCardId': rate_card_id, + # Set the product template the base rate will be applied to. 'productTemplateId': product_template_id, # Set the rate to be $2. 'rate': { @@ -45,7 +47,7 @@ def main(client, product_template_id, rate_card_id): } } - # Create base rates on the server. + # Create the product template item base rate on the server. base_rates = base_rate_service.createBaseRates( [product_template_base_rate]) diff --git a/examples/dfp/v201705/base_rate_service/get_all_base_rates.py b/examples/dfp/v201705/base_rate_service/get_all_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/base_rate_service/update_base_rates.py b/examples/dfp/v201705/base_rate_service/update_base_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/company_service/__init__.py b/examples/dfp/v201705/company_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/company_service/create_companies.py b/examples/dfp/v201705/company_service/create_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/company_service/get_advertisers.py b/examples/dfp/v201705/company_service/get_advertisers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/company_service/get_all_companies.py b/examples/dfp/v201705/company_service/get_all_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/company_service/update_companies.py b/examples/dfp/v201705/company_service/update_companies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/contact_service/__init__.py b/examples/dfp/v201705/contact_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/contact_service/create_contacts.py b/examples/dfp/v201705/contact_service/create_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/contact_service/get_all_contacts.py b/examples/dfp/v201705/contact_service/get_all_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/contact_service/get_uninvited_contacts.py b/examples/dfp/v201705/contact_service/get_uninvited_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/contact_service/update_contacts.py b/examples/dfp/v201705/contact_service/update_contacts.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/content_service/__init__.py b/examples/dfp/v201705/content_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/content_service/get_all_content.py b/examples/dfp/v201705/content_service/get_all_content.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_service/__init__.py b/examples/dfp/v201705/creative_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_service/copy_image_creatives.py b/examples/dfp/v201705/creative_service/copy_image_creatives.py index 1b57ed44..9d0308cb 100755 --- a/examples/dfp/v201705/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201705/creative_service/copy_image_creatives.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201705/creative_service/create_creative_from_template.py b/examples/dfp/v201705/creative_service/create_creative_from_template.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_service/create_creatives.py b/examples/dfp/v201705/creative_service/create_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_service/create_custom_creative.py b/examples/dfp/v201705/creative_service/create_custom_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_service/create_native_creative.py b/examples/dfp/v201705/creative_service/create_native_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_service/get_all_creatives.py b/examples/dfp/v201705/creative_service/get_all_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_service/get_image_creatives.py b/examples/dfp/v201705/creative_service/get_image_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_service/update_creatives.py b/examples/dfp/v201705/creative_service/update_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_set_service/__init__.py b/examples/dfp/v201705/creative_set_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_set_service/create_creative_set.py b/examples/dfp/v201705/creative_set_service/create_creative_set.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_set_service/update_creative_set.py b/examples/dfp/v201705/creative_set_service/update_creative_set.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_template_service/__init__.py b/examples/dfp/v201705/creative_template_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_field_service/__init__.py b/examples/dfp/v201705/custom_field_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_field_service/create_custom_field_options.py b/examples/dfp/v201705/custom_field_service/create_custom_field_options.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_field_service/create_custom_fields.py b/examples/dfp/v201705/custom_field_service/create_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_field_service/update_custom_fields.py b/examples/dfp/v201705/custom_field_service/update_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_targeting_service/__init__.py b/examples/dfp/v201705/custom_targeting_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/exchange_rate_service/__init__.py b/examples/dfp/v201705/exchange_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/forecast_service/get_availability_forecast.py b/examples/dfp/v201705/forecast_service/get_availability_forecast.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/inventory_service/__init__.py b/examples/dfp/v201705/inventory_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/inventory_service/archive_ad_units.py b/examples/dfp/v201705/inventory_service/archive_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/inventory_service/create_ad_units.py b/examples/dfp/v201705/inventory_service/create_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/inventory_service/get_all_ad_units.py b/examples/dfp/v201705/inventory_service/get_all_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/inventory_service/update_ad_units.py b/examples/dfp/v201705/inventory_service/update_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/label_service/__init__.py b/examples/dfp/v201705/label_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/label_service/create_labels.py b/examples/dfp/v201705/label_service/create_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/label_service/deactivate_labels.py b/examples/dfp/v201705/label_service/deactivate_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/label_service/get_active_labels.py b/examples/dfp/v201705/label_service/get_active_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/label_service/get_all_labels.py b/examples/dfp/v201705/label_service/get_all_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/label_service/update_labels.py b/examples/dfp/v201705/label_service/update_labels.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_creative_association_service/__init__.py b/examples/dfp/v201705/line_item_creative_association_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_creative_association_service/create_licas.py b/examples/dfp/v201705/line_item_creative_association_service/create_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py b/examples/dfp/v201705/line_item_creative_association_service/update_licas.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/__init__.py b/examples/dfp/v201705/line_item_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/activate_line_items.py b/examples/dfp/v201705/line_item_service/activate_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/create_line_items.py b/examples/dfp/v201705/line_item_service/create_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/create_video_line_item.py b/examples/dfp/v201705/line_item_service/create_video_line_item.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/get_all_line_items.py b/examples/dfp/v201705/line_item_service/get_all_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/pause_line_items.py b/examples/dfp/v201705/line_item_service/pause_line_items.py index 7425cd52..988f3c5f 100755 --- a/examples/dfp/v201705/line_item_service/pause_line_items.py +++ b/examples/dfp/v201705/line_item_service/pause_line_items.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201705/line_item_service/target_custom_criteria.py b/examples/dfp/v201705/line_item_service/target_custom_criteria.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/line_item_service/update_line_items.py b/examples/dfp/v201705/line_item_service/update_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/native_style_service/__init__.py b/examples/dfp/v201705/native_style_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/native_style_service/create_native_styles.py b/examples/dfp/v201705/native_style_service/create_native_styles.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/native_style_service/get_all_native_styles.py b/examples/dfp/v201705/native_style_service/get_all_native_styles.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/network_service/__init__.py b/examples/dfp/v201705/network_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/network_service/get_all_networks.py b/examples/dfp/v201705/network_service/get_all_networks.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/network_service/make_test_network.py b/examples/dfp/v201705/network_service/make_test_network.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/order_service/__init__.py b/examples/dfp/v201705/order_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/order_service/approve_orders.py b/examples/dfp/v201705/order_service/approve_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/order_service/create_orders.py b/examples/dfp/v201705/order_service/create_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/order_service/get_all_orders.py b/examples/dfp/v201705/order_service/get_all_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/order_service/get_orders_starting_soon.py b/examples/dfp/v201705/order_service/get_orders_starting_soon.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/order_service/update_orders.py b/examples/dfp/v201705/order_service/update_orders.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/package_service/create_packages.py b/examples/dfp/v201705/package_service/create_packages.py index 2b786612..a2cb8a28 100755 --- a/examples/dfp/v201705/package_service/create_packages.py +++ b/examples/dfp/v201705/package_service/create_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py index c2d9c41d..c7c4c8d9 100755 --- a/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py +++ b/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201705/package_service/get_all_packages.py b/examples/dfp/v201705/package_service/get_all_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/package_service/get_in_progress_packages.py b/examples/dfp/v201705/package_service/get_in_progress_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/placement_service/create_placements.py b/examples/dfp/v201705/placement_service/create_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/placement_service/deactivate_placements.py b/examples/dfp/v201705/placement_service/deactivate_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/placement_service/get_active_placements.py b/examples/dfp/v201705/placement_service/get_active_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/placement_service/get_all_placements.py b/examples/dfp/v201705/placement_service/get_all_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/placement_service/update_placements.py b/examples/dfp/v201705/placement_service/update_placements.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/premium_rate_service/__init__.py b/examples/dfp/v201705/premium_rate_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/premium_rate_service/create_premium_rates.py b/examples/dfp/v201705/premium_rate_service/create_premium_rates.py old mode 100644 new mode 100755 index 5d0dc4f7..7af12b3e --- a/examples/dfp/v201705/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201705/premium_rate_service/create_premium_rates.py @@ -57,7 +57,10 @@ def main(client, rate_card_id): 'adjustmentType': 'ABSOLUTE_VALUE' } - # Create premium_rate objects. + # Create premium rate. + # Associate premium rate with the rate card and set premium information. + # This premium will apply for proposal line items targeting 'any' ad unit + # for both CPM and CPC rate types. premium_rate = { 'rateCardId': rate_card_id, 'pricingMethod': 'ANY_VALUE', diff --git a/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/premium_rate_service/update_premium_rates.py b/examples/dfp/v201705/premium_rate_service/update_premium_rates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_package_item_service/create_product_package_item.py b/examples/dfp/v201705/product_package_item_service/create_product_package_item.py index fdb25318..9df8892f 100755 --- a/examples/dfp/v201705/product_package_item_service/create_product_package_item.py +++ b/examples/dfp/v201705/product_package_item_service/create_product_package_item.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_package_service/create_product_packages.py b/examples/dfp/v201705/product_package_service/create_product_packages.py index 3d69c3b6..49ba7a3a 100755 --- a/examples/dfp/v201705/product_package_service/create_product_packages.py +++ b/examples/dfp/v201705/product_package_service/create_product_packages.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201705/product_package_service/get_active_product_packages.py b/examples/dfp/v201705/product_package_service/get_active_product_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_package_service/get_all_product_packages.py b/examples/dfp/v201705/product_package_service/get_all_product_packages.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_service/__init__.py b/examples/dfp/v201705/product_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_service/get_all_products.py b/examples/dfp/v201705/product_service/get_all_products.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_service/get_products_for_product_template.py b/examples/dfp/v201705/product_service/get_products_for_product_template.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_service/update_products.py b/examples/dfp/v201705/product_service/update_products.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_template_service/__init__.py b/examples/dfp/v201705/product_template_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_template_service/activate_product_templates.py b/examples/dfp/v201705/product_template_service/activate_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_template_service/create_product_templates.py b/examples/dfp/v201705/product_template_service/create_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_template_service/get_all_product_templates.py b/examples/dfp/v201705/product_template_service/get_all_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/product_template_service/update_product_templates.py b/examples/dfp/v201705/product_template_service/update_product_templates.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_line_item_service/__init__.py b/examples/dfp/v201705/proposal_line_item_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/__init__.py b/examples/dfp/v201705/proposal_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/create_proposals.py b/examples/dfp/v201705/proposal_service/create_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/get_all_proposals.py b/examples/dfp/v201705/proposal_service/get_all_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/get_marketplace_comments.py b/examples/dfp/v201705/proposal_service/get_marketplace_comments.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/proposal_service/update_proposals.py b/examples/dfp/v201705/proposal_service/update_proposals.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/publisher_query_language_service/__init__.py b/examples/dfp/v201705/publisher_query_language_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/rate_card_service/__init__.py b/examples/dfp/v201705/rate_card_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/rate_card_service/create_rate_cards.py b/examples/dfp/v201705/rate_card_service/create_rate_cards.py index a895a013..e15299d1 100755 --- a/examples/dfp/v201705/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201705/rate_card_service/create_rate_cards.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py old mode 100644 new mode 100755 index b7c931b7..7f8536cd --- a/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -31,16 +31,10 @@ def main(client): first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) - query = 'WHERE startDate = :startDate' - values = [ - {'key': 'startDate', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_month.strftime('%Y-%m-01') - }}, - ] # Create a statement to select reconciliation reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('startDate = :startDate') + .WithBindVariable('startDate', last_month)) # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. diff --git a/examples/dfp/v201705/report_service/__init__.py b/examples/dfp/v201705/report_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/report_service/run_delivery_report.py b/examples/dfp/v201705/report_service/run_delivery_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/report_service/run_inventory_report.py b/examples/dfp/v201705/report_service/run_inventory_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/report_service/run_reach_report.py b/examples/dfp/v201705/report_service/run_reach_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/report_service/run_report_with_custom_fields.py b/examples/dfp/v201705/report_service/run_report_with_custom_fields.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/report_service/run_sales_report.py b/examples/dfp/v201705/report_service/run_sales_report.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/report_service/run_saved_query.py b/examples/dfp/v201705/report_service/run_saved_query.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/suggested_ad_unit_service/__init__.py b/examples/dfp/v201705/suggested_ad_unit_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/team_service/__init__.py b/examples/dfp/v201705/team_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/team_service/create_teams.py b/examples/dfp/v201705/team_service/create_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/team_service/get_all_teams.py b/examples/dfp/v201705/team_service/get_all_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/team_service/update_teams.py b/examples/dfp/v201705/team_service/update_teams.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_service/__init__.py b/examples/dfp/v201705/user_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_service/create_users.py b/examples/dfp/v201705/user_service/create_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_service/deactivate_users.py b/examples/dfp/v201705/user_service/deactivate_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_service/get_all_roles.py b/examples/dfp/v201705/user_service/get_all_roles.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_service/get_all_users.py b/examples/dfp/v201705/user_service/get_all_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_service/get_current_user.py b/examples/dfp/v201705/user_service/get_current_user.py index e83ae73f..99fde64c 100755 --- a/examples/dfp/v201705/user_service/get_current_user.py +++ b/examples/dfp/v201705/user_service/get_current_user.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python # # Copyright 2017 Google Inc. All Rights Reserved. # diff --git a/examples/dfp/v201705/user_service/get_user_by_email_address.py b/examples/dfp/v201705/user_service/get_user_by_email_address.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_service/update_users.py b/examples/dfp/v201705/user_service/update_users.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_team_association_service/__init__.py b/examples/dfp/v201705/user_team_association_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/workflow_request_service/__init__.py b/examples/dfp/v201705/workflow_request_service/__init__.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py old mode 100644 new mode 100755 diff --git a/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py old mode 100644 new mode 100755 diff --git a/googleads/adwords.py b/googleads/adwords.py index 4952ff7c..407dd175 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -172,6 +172,55 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201705': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignBidModifierService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignGroupPerformanceTargetService': 'cm', + 'CampaignGroupService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineCallConversionFeedService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } diff --git a/googleads/common.py b/googleads/common.py index 8c95d4b3..d3f9114f 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -61,7 +61,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '5.5.0' +VERSION = '5.6.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' diff --git a/setup.py b/setup.py old mode 100644 new mode 100755 From 46d3123b5167482f878a6d8052b052e27ab1e036 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 1 Jun 2017 12:38:21 -0400 Subject: [PATCH 078/180] Commiting latest changes. From bc3423e368f80948b09463f4803f369ef4760b6c Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 27 Jun 2017 17:10:45 -0400 Subject: [PATCH 079/180] AdWords v201607 Sunset. --- ChangeLog | 14 +- README.md | 12 +- .../adwords/adwords_appengine_demo/ChangeLog | 12 +- .../adwords/adwords_appengine_demo/README.md | 34 +- .../adwords/adwords_appengine_demo/app.yaml | 4 + .../handlers/api_handler.py | 5 +- .../handlers/ndb_handler.py | 6 +- .../templates/show_credentials.html | 6 +- .../views/update_credentials_view.py | 2 +- ...create_adwords_client_with_access_token.py | 86 +++ ...eate_adwords_client_with_refresh_token.py} | 0 examples/adwords/v201607/__init__.py | 15 - .../v201607/account_management/__init__.py | 15 - .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 99 ---- .../get_account_hierarchy.py | 104 ---- .../v201607/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 223 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 126 ----- .../advanced_operations/add_html5_ad.py | 111 ---- .../add_responsive_display_ad.py | 91 --- .../add_text_ad_with_upgraded_urls.py | 111 ---- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 171 ------ .../v201607/basic_operations/__init__.py | 15 - .../v201607/basic_operations/add_ad_groups.py | 115 ---- .../v201607/basic_operations/add_campaigns.py | 125 ----- .../basic_operations/add_expanded_text_ads.py | 74 --- .../v201607/basic_operations/add_keywords.py | 92 --- .../v201607/basic_operations/add_text_ads.py | 93 ---- .../v201607/basic_operations/get_ad_groups.py | 76 --- .../v201607/basic_operations/get_campaigns.py | 74 --- .../get_campaigns_with_awql.py | 64 --- .../basic_operations/get_expanded_text_ads.py | 90 --- .../v201607/basic_operations/get_keywords.py | 87 --- .../v201607/basic_operations/get_text_ads.py | 80 --- .../v201607/basic_operations/pause_ad.py | 61 -- .../v201607/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 58 -- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201607/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 426 -------------- .../v201607/campaign_management/add_draft.py | 81 --- .../campaign_management/add_experiment.py | 127 ----- ...dd_keywords_using_incremental_batch_job.py | 259 --------- .../v201607/campaign_management/add_trial.py | 116 ---- .../get_all_disapproved_ads.py | 74 --- .../get_all_disapproved_ads_with_awql.py | 63 --- .../get_campaigns_by_label.py | 85 --- .../campaign_management/graduate_trial.py | 79 --- .../campaign_management/promote_experiment.py | 60 -- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201607/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 120 ---- .../handle_policy_violation_error.py | 117 ---- .../adwords/v201607/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 ------ .../adwords/v201607/extensions/add_prices.py | 144 ----- .../v201607/extensions/add_site_links.py | 146 ----- .../extensions/add_site_links_using_feeds.py | 236 -------- .../adwords/v201607/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 ------------------ examples/adwords/v201607/misc/__init__.py | 15 - .../v201607/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201607/misc/upload_image.py | 66 --- .../v201607/misc/upload_media_bundle.py | 59 -- .../adwords/v201607/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 180 ------ ...aign_criterion_bid_modifier_simulations.py | 96 ---- .../get_keyword_bid_simulations.py | 81 --- .../v201607/optimization/get_keyword_ideas.py | 100 ---- .../adwords/v201607/remarketing/__init__.py | 15 - .../v201607/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 70 --- .../remarketing/add_crm_based_user_list.py | 94 ---- .../remarketing/add_rule_based_user_lists.py | 183 ------ .../remarketing/upload_offline_conversions.py | 75 --- .../adwords/v201607/reporting/__init__.py | 15 - .../reporting/download_criteria_report.py | 61 -- .../download_criteria_report_as_stream.py | 77 --- ...oad_criteria_report_as_stream_with_awql.py | 81 --- .../download_criteria_report_as_string.py | 59 -- ...oad_criteria_report_as_string_with_awql.py | 55 -- .../download_criteria_report_with_awql.py | 59 -- .../v201607/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 230 -------- examples/adwords/v201607/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 281 ---------- .../v201607/shopping/add_product_scope.py | 104 ---- .../v201607/shopping/add_shopping_campaign.py | 121 ---- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201607/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 145 ----- .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201607/targeting/lookup_location.py | 82 --- .../account_management/accept_service_link.py | 8 +- .../account_management/create_account.py | 2 +- .../account_management/get_account_changes.py | 4 +- .../advanced_operations/add_ad_customizer.py | 4 +- .../advanced_operations/add_html5_ad.py | 2 +- .../use_shared_bidding_strategy.py | 6 +- .../v201609/basic_operations/add_ad_groups.py | 2 +- .../v201609/basic_operations/add_campaigns.py | 2 +- .../v201609/basic_operations/add_keywords.py | 4 +- .../v201609/basic_operations/get_ad_groups.py | 2 +- .../v201609/basic_operations/get_campaigns.py | 2 +- .../get_campaigns_with_awql.py | 2 +- .../v201609/basic_operations/get_keywords.py | 4 +- .../v201609/basic_operations/get_text_ads.py | 2 +- .../v201609/basic_operations/pause_ad.py | 2 +- .../v201609/basic_operations/remove_ad.py | 2 +- .../basic_operations/remove_ad_group.py | 2 +- .../basic_operations/remove_campaign.py | 2 +- .../basic_operations/remove_keyword.py | 4 +- .../basic_operations/update_ad_group.py | 2 +- .../basic_operations/update_campaign.py | 2 +- .../basic_operations/update_keyword.py | 8 +- .../add_campaign_labels.py | 2 +- .../get_all_disapproved_ads.py | 2 +- .../get_all_disapproved_ads_with_awql.py | 2 +- .../get_campaigns_by_label.py | 2 +- .../campaign_management/set_ad_parameters.py | 8 +- .../set_criterion_bid_modifier.py | 4 +- .../campaign_management/validate_text_ad.py | 2 +- .../error_handling/handle_partial_failures.py | 10 +- .../handle_policy_violation_error.py | 8 +- .../extensions/add_site_links_using_feeds.py | 6 +- .../v201609/misc/get_all_images_and_videos.py | 6 +- examples/adwords/v201609/misc/upload_image.py | 2 +- .../get_keyword_bid_simulations.py | 4 +- .../v201609/optimization/get_keyword_ideas.py | 4 +- .../v201609/remarketing/add_audience.py | 2 +- .../remarketing/add_conversion_tracker.py | 4 +- .../remarketing/upload_offline_conversions.py | 8 +- .../download_criteria_report_with_awql.py | 2 +- .../v201609/reporting/get_report_fields.py | 2 +- .../v201609/shopping/add_shopping_campaign.py | 6 +- .../add_campaign_targeting_criteria.py | 4 +- .../add_demographic_targeting_criteria.py | 2 +- .../get_targetable_languages_and_carriers.py | 4 +- .../v201609/targeting/lookup_location.py | 4 +- .../account_management/accept_service_link.py | 8 +- .../account_management/create_account.py | 2 +- .../account_management/get_account_changes.py | 4 +- .../advanced_operations/add_ad_customizer.py | 4 +- .../advanced_operations/add_html5_ad.py | 2 +- .../use_shared_bidding_strategy.py | 6 +- .../v201702/basic_operations/add_ad_groups.py | 2 +- .../v201702/basic_operations/add_campaigns.py | 2 +- .../v201702/basic_operations/add_keywords.py | 4 +- .../v201702/basic_operations/get_ad_groups.py | 2 +- .../v201702/basic_operations/get_campaigns.py | 2 +- .../get_campaigns_with_awql.py | 2 +- .../v201702/basic_operations/get_keywords.py | 4 +- .../v201702/basic_operations/get_text_ads.py | 2 +- .../v201702/basic_operations/pause_ad.py | 2 +- .../v201702/basic_operations/remove_ad.py | 2 +- .../basic_operations/remove_ad_group.py | 2 +- .../basic_operations/remove_campaign.py | 2 +- .../basic_operations/remove_keyword.py | 4 +- .../basic_operations/update_ad_group.py | 2 +- .../basic_operations/update_campaign.py | 2 +- .../basic_operations/update_keyword.py | 8 +- .../add_campaign_labels.py | 2 +- .../get_all_disapproved_ads.py | 2 +- .../get_all_disapproved_ads_with_awql.py | 2 +- .../get_campaigns_by_label.py | 2 +- .../campaign_management/set_ad_parameters.py | 8 +- .../set_criterion_bid_modifier.py | 4 +- .../campaign_management/validate_text_ad.py | 2 +- .../error_handling/handle_partial_failures.py | 4 +- .../handle_policy_violation_error.py | 4 +- .../extensions/add_site_links_using_feeds.py | 6 +- .../v201702/misc/get_all_images_and_videos.py | 6 +- examples/adwords/v201702/misc/upload_image.py | 2 +- .../get_keyword_bid_simulations.py | 4 +- .../v201702/optimization/get_keyword_ideas.py | 4 +- .../v201702/remarketing/add_audience.py | 2 +- .../remarketing/add_conversion_tracker.py | 4 +- .../remarketing/upload_offline_conversions.py | 8 +- .../download_criteria_report_with_awql.py | 2 +- .../v201702/reporting/get_report_fields.py | 2 +- .../v201702/shopping/add_shopping_campaign.py | 6 +- .../add_shopping_campaign_for_showcase_ads.py | 2 +- .../add_campaign_targeting_criteria.py | 4 +- .../add_demographic_targeting_criteria.py | 2 +- .../get_targetable_languages_and_carriers.py | 4 +- .../v201702/targeting/lookup_location.py | 4 +- .../account_management/accept_service_link.py | 8 +- .../account_management/create_account.py | 2 +- .../account_management/get_account_changes.py | 4 +- .../advanced_operations/add_ad_customizer.py | 4 +- .../advanced_operations/add_html5_ad.py | 2 +- .../use_shared_bidding_strategy.py | 6 +- .../v201705/basic_operations/add_ad_groups.py | 2 +- .../v201705/basic_operations/add_campaigns.py | 2 +- .../v201705/basic_operations/add_keywords.py | 4 +- .../v201705/basic_operations/get_ad_groups.py | 2 +- .../v201705/basic_operations/get_campaigns.py | 2 +- .../get_campaigns_with_awql.py | 2 +- .../v201705/basic_operations/get_keywords.py | 4 +- .../v201705/basic_operations/get_text_ads.py | 78 --- .../v201705/basic_operations/pause_ad.py | 2 +- .../v201705/basic_operations/remove_ad.py | 4 +- .../basic_operations/remove_ad_group.py | 2 +- .../basic_operations/remove_campaign.py | 2 +- .../basic_operations/remove_keyword.py | 4 +- .../basic_operations/update_ad_group.py | 2 +- .../basic_operations/update_campaign.py | 2 +- .../basic_operations/update_keyword.py | 8 +- .../add_campaign_labels.py | 2 +- .../get_all_disapproved_ads.py | 13 +- .../get_all_disapproved_ads_with_awql.py | 13 +- .../get_campaigns_by_label.py | 2 +- .../campaign_management/set_ad_parameters.py | 8 +- .../set_criterion_bid_modifier.py | 4 +- .../campaign_management/validate_text_ad.py | 2 +- .../error_handling/handle_partial_failures.py | 4 +- .../handle_policy_violation_error.py | 4 +- .../extensions/add_site_links_using_feeds.py | 6 +- .../v201705/misc/get_all_images_and_videos.py | 6 +- examples/adwords/v201705/misc/upload_image.py | 2 +- .../get_keyword_bid_simulations.py | 4 +- .../v201705/optimization/get_keyword_ideas.py | 4 +- .../v201705/remarketing/add_audience.py | 2 +- .../remarketing/add_conversion_tracker.py | 4 +- .../remarketing/upload_offline_conversions.py | 8 +- .../v201705/reporting/get_report_fields.py | 2 +- .../v201705/shopping/add_shopping_campaign.py | 6 +- .../add_shopping_campaign_for_showcase_ads.py | 2 +- .../add_campaign_targeting_criteria.py | 4 +- .../add_demographic_targeting_criteria.py | 2 +- .../get_targetable_languages_and_carriers.py | 4 +- .../v201705/targeting/lookup_location.py | 4 +- .../create_dfp_client_with_access_token.py | 81 +++ ...> create_dfp_client_with_refresh_token.py} | 2 +- .../create_dfp_client_with_service_account.py | 2 +- .../create_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/create_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../create_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 4 +- .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/update_base_rates.py | 4 +- .../company_service/create_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/create_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 4 +- .../create_native_creative.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../update_creative_set.py | 2 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../update_creative_wrappers.py | 2 +- .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../set_line_item_custom_field_value.py | 6 +- .../update_custom_fields.py | 4 +- ...create_custom_targeting_keys_and_values.py | 10 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 2 +- .../v201611/label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../v201611/label_service/update_labels.py | 2 +- .../create_licas.py | 4 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 6 +- .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 6 +- .../create_video_line_item.py | 6 +- .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 4 +- .../network_service/get_all_networks.py | 2 +- .../network_service/make_test_network.py | 2 +- .../v201611/order_service/approve_orders.py | 2 +- .../v201611/order_service/create_orders.py | 2 +- .../v201611/order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 2 +- .../deactivate_placements.py | 2 +- .../placement_service/update_placements.py | 4 +- .../create_premium_rates.py | 4 +- .../update_premium_rates.py | 6 +- ...sh_programmatic_products_to_marketplace.py | 2 +- .../product_service/update_products.py | 4 +- .../activate_product_templates.py | 2 +- .../create_product_templates.py | 2 +- .../create_programmatic_product_templates.py | 2 +- .../update_product_templates.py | 2 +- .../archive_proposal_line_items.py | 6 +- ...create_programmatic_proposal_line_items.py | 4 +- ...sal_line_items_for_non_sales_management.py | 2 +- .../create_proposal_line_items.py | 4 +- .../update_proposal_line_items.py | 4 +- .../create_programmatic_proposals.py | 2 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 2 +- .../request_buyers_acceptance.py | 8 +- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 4 +- .../report_service/run_delivery_report.py | 2 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../v201611/report_service/run_saved_query.py | 2 +- .../approve_all_suggested_ad_units.py | 2 +- .../dfp/v201611/team_service/create_teams.py | 2 +- .../dfp/v201611/team_service/update_teams.py | 2 +- .../dfp/v201611/user_service/create_users.py | 2 +- .../v201611/user_service/deactivate_users.py | 2 +- .../dfp/v201611/user_service/get_all_roles.py | 2 +- .../dfp/v201611/user_service/update_users.py | 2 +- .../create_user_team_associations.py | 6 +- .../delete_user_team_associations.py | 6 +- .../update_user_team_associations.py | 6 +- .../approve_workflow_approval_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 4 +- .../create_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/create_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../create_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 4 +- .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/update_base_rates.py | 4 +- .../company_service/create_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/create_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 4 +- .../create_native_creative.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../update_creative_set.py | 2 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../update_creative_wrappers.py | 2 +- .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../set_line_item_custom_field_value.py | 6 +- .../update_custom_fields.py | 4 +- ...create_custom_targeting_keys_and_values.py | 10 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 2 +- .../v201702/label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../v201702/label_service/update_labels.py | 2 +- .../create_licas.py | 4 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 6 +- .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 6 +- .../create_video_line_item.py | 6 +- .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 4 +- .../network_service/get_all_networks.py | 2 +- .../network_service/make_test_network.py | 2 +- .../v201702/order_service/approve_orders.py | 2 +- .../v201702/order_service/create_orders.py | 2 +- .../v201702/order_service/update_orders.py | 4 +- .../package_service/create_packages.py | 2 +- .../placement_service/create_placements.py | 2 +- .../deactivate_placements.py | 2 +- .../placement_service/update_placements.py | 4 +- .../create_premium_rates.py | 4 +- .../update_premium_rates.py | 6 +- .../create_product_packages.py | 2 +- ...sh_programmatic_products_to_marketplace.py | 2 +- .../product_service/update_products.py | 4 +- .../activate_product_templates.py | 2 +- .../create_product_templates.py | 2 +- .../create_programmatic_product_templates.py | 2 +- .../update_product_templates.py | 2 +- .../archive_proposal_line_items.py | 6 +- ...create_programmatic_proposal_line_items.py | 4 +- ...sal_line_items_for_non_sales_management.py | 2 +- .../create_proposal_line_items.py | 4 +- .../update_proposal_line_items.py | 4 +- .../create_programmatic_proposals.py | 2 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 2 +- .../request_buyers_acceptance.py | 8 +- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 4 +- .../rate_card_service/create_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 2 +- .../report_service/run_delivery_report.py | 2 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../v201702/report_service/run_saved_query.py | 2 +- .../approve_all_suggested_ad_units.py | 2 +- .../dfp/v201702/team_service/create_teams.py | 2 +- .../dfp/v201702/team_service/update_teams.py | 2 +- .../dfp/v201702/user_service/create_users.py | 2 +- .../v201702/user_service/deactivate_users.py | 2 +- .../dfp/v201702/user_service/get_all_roles.py | 2 +- .../v201702/user_service/get_current_user.py | 2 +- .../dfp/v201702/user_service/update_users.py | 2 +- .../create_user_team_associations.py | 6 +- .../delete_user_team_associations.py | 6 +- .../update_user_team_associations.py | 6 +- .../approve_workflow_approval_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 4 +- .../create_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/create_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../create_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 4 +- .../create_product_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/update_base_rates.py | 4 +- .../company_service/create_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/create_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 4 +- .../create_native_creative.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../update_creative_set.py | 2 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../update_creative_wrappers.py | 2 +- .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../set_line_item_custom_field_value.py | 6 +- .../update_custom_fields.py | 4 +- ...create_custom_targeting_keys_and_values.py | 10 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 2 +- .../v201705/label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../v201705/label_service/update_labels.py | 2 +- .../create_licas.py | 4 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 6 +- .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 6 +- .../create_video_line_item.py | 6 +- .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 4 +- .../network_service/get_all_networks.py | 2 +- .../network_service/make_test_network.py | 2 +- .../v201705/order_service/approve_orders.py | 2 +- .../v201705/order_service/create_orders.py | 2 +- .../v201705/order_service/update_orders.py | 4 +- .../package_service/create_packages.py | 2 +- .../placement_service/create_placements.py | 2 +- .../deactivate_placements.py | 2 +- .../placement_service/update_placements.py | 2 +- .../create_premium_rates.py | 4 +- .../update_premium_rates.py | 6 +- .../create_product_packages.py | 2 +- ...sh_programmatic_products_to_marketplace.py | 2 +- .../product_service/update_products.py | 4 +- .../activate_product_templates.py | 2 +- .../create_product_templates.py | 2 +- .../create_programmatic_product_templates.py | 2 +- .../update_product_templates.py | 2 +- .../archive_proposal_line_items.py | 6 +- ...create_programmatic_proposal_line_items.py | 4 +- ...sal_line_items_for_non_sales_management.py | 2 +- .../create_proposal_line_items.py | 4 +- .../update_proposal_line_items.py | 4 +- .../create_programmatic_proposals.py | 2 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 2 +- .../request_buyers_acceptance.py | 8 +- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 4 +- .../rate_card_service/create_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 2 +- .../report_service/run_delivery_report.py | 2 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../v201705/report_service/run_saved_query.py | 2 +- .../approve_all_suggested_ad_units.py | 2 +- .../dfp/v201705/team_service/create_teams.py | 2 +- .../dfp/v201705/team_service/update_teams.py | 2 +- .../dfp/v201705/user_service/create_users.py | 2 +- .../v201705/user_service/deactivate_users.py | 2 +- .../dfp/v201705/user_service/get_all_roles.py | 2 +- .../v201705/user_service/get_current_user.py | 2 +- .../dfp/v201705/user_service/update_users.py | 2 +- .../create_user_team_associations.py | 6 +- .../delete_user_team_associations.py | 6 +- .../update_user_team_associations.py | 6 +- .../approve_workflow_approval_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 4 +- googleads.yaml | 21 + googleads/adwords.py | 194 +++++-- googleads/common.py | 120 +++- googleads/dfp.py | 29 +- googleads/oauth2.py | 88 ++- googleads/util.py | 119 +++- tests/adwords_test.py | 223 ++++++-- tests/common_test.py | 236 +++++++- tests/dfp_test.py | 118 ++-- tests/oauth2_test.py | 32 +- tests/util_test.py | 185 +++++- 563 files changed, 2074 insertions(+), 10329 deletions(-) create mode 100755 examples/adwords/authentication/create_adwords_client_with_access_token.py rename examples/adwords/authentication/{create_adwords_client_without_yaml.py => create_adwords_client_with_refresh_token.py} (100%) delete mode 100644 examples/adwords/v201607/__init__.py delete mode 100644 examples/adwords/v201607/account_management/__init__.py delete mode 100755 examples/adwords/v201607/account_management/create_account.py delete mode 100755 examples/adwords/v201607/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201607/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201607/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201607/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201607/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201607/basic_operations/__init__.py delete mode 100755 examples/adwords/v201607/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201607/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201607/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201607/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201607/basic_operations/add_text_ads.py delete mode 100755 examples/adwords/v201607/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201607/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201607/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201607/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201607/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201607/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201607/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201607/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201607/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201607/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201607/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201607/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201607/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201607/campaign_management/__init__.py delete mode 100755 examples/adwords/v201607/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201607/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201607/campaign_management/add_experiment.py delete mode 100755 examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201607/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201607/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201607/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201607/campaign_management/promote_experiment.py delete mode 100755 examples/adwords/v201607/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201607/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201607/error_handling/__init__.py delete mode 100755 examples/adwords/v201607/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201607/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201607/extensions/__init__.py delete mode 100755 examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201607/extensions/add_prices.py delete mode 100755 examples/adwords/v201607/extensions/add_site_links.py delete mode 100755 examples/adwords/v201607/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201607/migration/__init__.py delete mode 100755 examples/adwords/v201607/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201607/misc/__init__.py delete mode 100755 examples/adwords/v201607/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201607/misc/upload_image.py delete mode 100755 examples/adwords/v201607/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201607/optimization/__init__.py delete mode 100755 examples/adwords/v201607/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201607/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201607/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201607/remarketing/__init__.py delete mode 100755 examples/adwords/v201607/remarketing/add_audience.py delete mode 100755 examples/adwords/v201607/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201607/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201607/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201607/remarketing/upload_offline_conversions.py delete mode 100644 examples/adwords/v201607/reporting/__init__.py delete mode 100755 examples/adwords/v201607/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201607/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201607/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201607/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201607/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201607/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201607/shopping/__init__.py delete mode 100755 examples/adwords/v201607/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201607/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201607/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201607/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201607/targeting/__init__.py delete mode 100755 examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201607/targeting/lookup_location.py delete mode 100755 examples/adwords/v201705/basic_operations/get_text_ads.py create mode 100755 examples/dfp/authentication/create_dfp_client_with_access_token.py rename examples/dfp/authentication/{create_dfp_client_without_yaml.py => create_dfp_client_with_refresh_token.py} (95%) diff --git a/ChangeLog b/ChangeLog index 03470056..1a9b01da 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,7 +1,17 @@ -5.6.0 -- 06/01/17: +6.0.0 -- 6/27/17: +* Removed support for AdWords v201607. +* Improved logging support. Can now specify logging configuration from the + configuration file. +* Added new GoogleAccessTokenClient, a non-refreshable client that only requires + the access token. +* Resolved issues: +- Issue 84: https://github.com/googleads/googleads-python-lib/issues/84 +- Issue 171: https://github.com/googleads/googleads-python-lib/issues/171 + +5.6.0 -- 6/01/17: * Added support for AdWords v201705. -5.5.0 -- 05/23/17: +5.5.0 -- 5/23/17: * Added more expressive python utility to build DFP PQL statements. * Support building DFP SOAP entities with native python date/datetime objects. * Added support and examples for DFP v201705. diff --git a/README.md b/README.md index d9fb6838..1141e2b4 100644 --- a/README.md +++ b/README.md @@ -101,8 +101,12 @@ for API change announcements and other news. ## How do I log SOAP interactions? -The library uses Python's built in logging framework. If you wish to log your -SOAP interactions to stdout, you can do the following: +The library uses Python's built in logging framework. You can specify your +configuration via the configuration file; see [googleads.yaml](https://github.com/googleads/googleads-python-lib/blob/master/googleads.yaml) +for an example. + +Alternatively, you can manually specify your logging configuration. For example, +if you want to log your SOAP interactions to stdout, you can do the following: ```python logging.basicConfig(level=logging.INFO, format=googleads.util.LOGGER_FORMAT) logging.getLogger('suds.transport').setLevel(logging.DEBUG) @@ -121,6 +125,10 @@ logging.getLogger('googleads.common').removeFilter( googleads.util.GetGoogleAdsCommonFilter()) logging.getLogger('suds.client').removeFilter( googleads.util.GetSudsClientFilter()) +logging.getLogger('suds.mx.core').removeFilter( + googleads.util.GetSudsMXCoreFilter()) +logging.getLogger('suds.mx.literal').removeFilter( + googleads.util.GetSudsMXLiteralFilter()) logging.getLogger('suds.transport').removeFilter( googleads.util.GetSudsTransportFilter()) ``` diff --git a/examples/adwords/adwords_appengine_demo/ChangeLog b/examples/adwords/adwords_appengine_demo/ChangeLog index d2856ece..ba2a6c7c 100644 --- a/examples/adwords/adwords_appengine_demo/ChangeLog +++ b/examples/adwords/adwords_appengine_demo/ChangeLog @@ -1,6 +1,10 @@ -1.0.1 - 1/5/2015 -- Updated dependencies listed in README, for the changes introduced in googleads - 3.0.0. +1.0.2 -- 6/21/16: +- Fixed issue #171: + https://github.com/googleads/googleads-python-lib/issues/171 + +1.0.1 -- 1/5/15: +- Updated dependencies listed in README, for the changes introduced in + googleads 3.0.0. 1.0.0: -- Initial release of the demo. \ No newline at end of file +- Initial release of the demo. diff --git a/examples/adwords/adwords_appengine_demo/README.md b/examples/adwords/adwords_appengine_demo/README.md index 53307a82..1a63f2c7 100644 --- a/examples/adwords/adwords_appengine_demo/README.md +++ b/examples/adwords/adwords_appengine_demo/README.md @@ -36,19 +36,19 @@ prepared your OAuth2 Credentials via the Google Developers Console. 1. Install Python v2.7, which you can get [here](https://www.python.org/downloads). -2. Install [pip](http://pip.readthedocs.org/en/latest/installing.html), +1. Install [pip](http://pip.readthedocs.org/en/latest/installing.html), if you have not done so already. -3. If you don't have one already, +1. If you don't have one already, [sign up for a Google Account](https://www.google.com/accounts/NewAccount). This account will be used to access your AdWords credentials used in making API requests. -4. Download the latest version of the +1. Download the latest version of the [App Engine SDK](https://developers.google.com/appengine/downloads) and unpack its content. This demo should be compatible with v1.9.11+. -5. Install googleads with the following command: +1. Install googleads with the following command: `$ pip install googleads` @@ -57,36 +57,42 @@ prepared your OAuth2 Credentials via the Google Developers Console. should also have installed the dependencies referred to in the following steps. -6. Copy the httplib2 package from your Python installation's dist-packages +1. Copy the httplib2 package from your Python installation's dist-packages directory into this project. -7. Copy the oauth2client package from your Python installation's dist-packages +1. Copy the oauth2client package from your Python installation's dist-packages directory into this project. -8. Copy the pytz package from your Python installation's dist-packages +1. Copy the pyasn1 package from your Python installation's dist-packages directory into this project. -9. Copy socks.py from the PySocks tarball found in your Python installation's +1. Copy socks.py from the PySocks tarball found in your Python installation's dist-packages directory into this project. -10. Copy the suds package from your Python installation's dist-packages +1. Copy the rsa package from your Python installation's dist-packages + into this project. + +1. Copy the suds package from your Python installation's dist-packages + into this project. + +1. Copy xmltodict.py from your Python installation's dist-packages directory directory into this project. -11. Create an App Engine application in the +1. Create an App Engine application in the [Google App Engine Console](https://appengine.google.com/). -12. Go to this project's app.yaml, and enter in your application name for the +1. Go to this project's app.yaml, and enter in your application name for the "application" field. -13. You can now deploy this project by running the following command: +1. You can now deploy this project by running the following command: `python $APPENGINE_SDK_DIR/appcfg --oauth2 update .` -14. When you go to your App for the first time, you will need to log in and +1. When you go to your App for the first time, you will need to log in and provide OAuth2 and AdWords API credentials. You can use credentials generated via the generate_refresh_token.py example. -15. With all information entered, you can now use the UI to view and modify +1. With all information entered, you can now use the UI to view and modify your account details. diff --git a/examples/adwords/adwords_appengine_demo/app.yaml b/examples/adwords/adwords_appengine_demo/app.yaml index 4649e559..094521e9 100644 --- a/examples/adwords/adwords_appengine_demo/app.yaml +++ b/examples/adwords/adwords_appengine_demo/app.yaml @@ -13,3 +13,7 @@ handlers: script: demo.main.app login: required secure: always + +libraries: +- name: ssl + version: latest diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index 0595b40a..83a7c1cb 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -19,12 +19,11 @@ import time -from suds.cache import NoCache - from demo import VERSION from googleads.adwords import AdWordsClient from googleads.errors import GoogleAdsError from googleads.oauth2 import GoogleRefreshTokenClient +from suds.cache import NoCache class APIHandler(object): @@ -48,7 +47,7 @@ def __init__(self, client_id, client_secret, refresh_token, refresh_token) self.client = AdWordsClient(dev_token, credentials, self._USER_AGENT, client_customer_id=manager_account_id, - cache=NoCache) + cache=NoCache()) def AddAdGroup(self, client_customer_id, campaign_id, name, status): """Create a new ad group. diff --git a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py index 9cd6b7ca..897f82da 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/ndb_handler.py @@ -43,14 +43,14 @@ def InitUser(): def UpdateUserCredentials(client_id, client_secret, refresh_token, - manager_account_id, developer_token): + adwords_manager_cid, developer_token): """Update the credentials associated with application user. Args: client_id: str Client Id retrieved from the developer's console. client_secret: str Client Secret retrieved from the developer's console. refresh_token: str Refresh token generated with the above client id/secret. - manager_account_id: str Customer Id for the AdWords manager account. + adwords_manager_cid: str Customer Id for the AdWords manager account. developer_token: str Developer Token for the AdWords account. """ app_user = AppUser.query(AppUser.user == users.get_current_user()).fetch()[0] @@ -58,7 +58,7 @@ def UpdateUserCredentials(client_id, client_secret, refresh_token, app_user.client_id = client_id app_user.client_secret = client_secret app_user.refresh_token = refresh_token - app_user.manager_account_id = manager_account_id + app_user.adwords_manager_cid = adwords_manager_cid app_user.developer_token = developer_token app_user.put() diff --git a/examples/adwords/adwords_appengine_demo/templates/show_credentials.html b/examples/adwords/adwords_appengine_demo/templates/show_credentials.html index 417cb6df..f7edda4a 100644 --- a/examples/adwords/adwords_appengine_demo/templates/show_credentials.html +++ b/examples/adwords/adwords_appengine_demo/templates/show_credentials.html @@ -24,8 +24,8 @@ - + @@ -39,4 +39,4 @@ -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py index 83159ca6..844b7cd4 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py @@ -41,7 +41,7 @@ def post(self): UpdateUserCredentials(self.request.get('client_id'), self.request.get('client_secret'), self.request.get('refresh_token'), - self.request.get('manager_account_id'), + self.request.get('adwords_manager_cid'), self.request.get('dev_token')) self.redirect('/showCredentials') except Exception, e: diff --git a/examples/adwords/authentication/create_adwords_client_with_access_token.py b/examples/adwords/authentication/create_adwords_client_with_access_token.py new file mode 100755 index 00000000..95eea9e8 --- /dev/null +++ b/examples/adwords/authentication/create_adwords_client_with_access_token.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Initializes an AdWordsClient using GoogleAccessTokenClient. + +Note that unlike clients initialized with GoogleRefreshTokenClient, those +initialized with GoogleAccessTokenClient can't refresh. +""" + +import argparse +import datetime +from googleads import adwords +from googleads import oauth2 +import httplib2 +from oauth2client import client + + +GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token' + +# OAuth2 credential information. +DEFAULT_CLIENT_ID = 'INSERT_CLIENT_ID_HERE' +DEFAULT_CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' +DEFAULT_REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE' + +# AdWords API information. +DEFAULT_CLIENT_CUSTOMER_ID = 'INSERT_CLIENT_CUSTOMER_ID_HERE' +DEFAULT_DEVELOPER_TOKEN = 'INSERT_DEVELOPER_TOKEN_HERE' +USER_AGENT = 'INSERT_USER_AGENT_HERE' + + +parser = argparse.ArgumentParser( + description=('Creates an AdWordsClient using a GoogleAccessToken with an ' + 'access token generated with the given credentials.')) +parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID, + help='Client Id retrieved from the Developer\'s Console.') +parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET, + help='Client Secret retrieved from the Developer\'s ' + 'Console.') +parser.add_argument('--refresh_token', default=DEFAULT_REFRESH_TOKEN, + help='The refresh token used to generate an access token.') +parser.add_argument('--client_customer_id', default=DEFAULT_CLIENT_CUSTOMER_ID, + help='The client customer ID for your AdWords account.') +parser.add_argument('--developer_token', default=DEFAULT_DEVELOPER_TOKEN, + help='The refresh token used to generate an access token.') + + +def main(access_token, token_expiry, client_customer_id, developer_token, + user_agent): + oauth2_client = oauth2.GoogleAccessTokenClient(access_token, token_expiry) + + adwords_client = adwords.AdWordsClient( + developer_token, oauth2_client, user_agent, + client_customer_id=client_customer_id) + + customer = adwords_client.GetService('CustomerService').getCustomers()[0] + print 'You are logged in as customer: %s' % customer['customerId'] + + +if __name__ == '__main__': + args = parser.parse_args() + + # Retrieve a new access token for use in this example. In a production + # application, you may use a credential store to share access tokens for a + # given user across applications. + oauth2credentials = client.OAuth2Credentials( + None, args.client_id, args.client_secret, args.refresh_token, + datetime.datetime(1980, 1, 1, 12), GOOGLE_OAUTH2_ENDPOINT, + USER_AGENT) + + oauth2credentials.refresh(httplib2.Http()) + + main(oauth2credentials.access_token, oauth2credentials.token_expiry, + args.client_customer_id, args.developer_token, USER_AGENT) diff --git a/examples/adwords/authentication/create_adwords_client_without_yaml.py b/examples/adwords/authentication/create_adwords_client_with_refresh_token.py similarity index 100% rename from examples/adwords/authentication/create_adwords_client_without_yaml.py rename to examples/adwords/authentication/create_adwords_client_with_refresh_token.py diff --git a/examples/adwords/v201607/__init__.py b/examples/adwords/v201607/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201607/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201607/account_management/__init__.py b/examples/adwords/v201607/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201607/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201607/account_management/create_account.py b/examples/adwords/v201607/account_management/create_account.py deleted file mode 100755 index c3e65a9e..00000000 --- a/examples/adwords/v201607/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201607') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/account_management/get_account_changes.py b/examples/adwords/v201607/account_management/get_account_changes.py deleted file mode 100755 index 91476eb4..00000000 --- a/examples/adwords/v201607/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201607') - campaign_service = client.GetService('CampaignService', version='v201607') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/account_management/get_account_hierarchy.py b/examples/adwords/v201607/account_management/get_account_hierarchy.py deleted file mode 100755 index 33e5127f..00000000 --- a/examples/adwords/v201607/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201607') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/advanced_operations/__init__.py b/examples/adwords/v201607/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201607/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py b/examples/adwords/v201607/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 801af9b8..00000000 --- a/examples/adwords/v201607/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,223 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates TextAds that use ad customizations for the specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add TextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no TextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201607') - - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'description1': 'Only {=%s.Price}' % feed_name, - 'description2': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com' - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201607') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name \'%s\' and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201607') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 11a3ab88..00000000 --- a/examples/adwords/v201607/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201607') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 6b840e23..00000000 --- a/examples/adwords/v201607/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Optionally, you may specify a landscape image. The image needs to be in a - # BASE64 encoded form. Here we download a demo image and encode it for this - # ad. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - }, - { - 'name': 'landscapeImage', - 'field_media': { - 'xsi_type': 'Image', - 'data': image_data - }, - 'type': 'IMAGE' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/advanced_operations/add_html5_ad.py b/examples/adwords/v201607/advanced_operations/add_html5_ad.py deleted file mode 100755 index 188cdff6..00000000 --- a/examples/adwords/v201607/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index 1558a6e4..00000000 --- a/examples/adwords/v201607/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - media_service = client.GetService('MediaService', version='v201607') - - try: - # Create image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - # Make the upload request - image = media_service.upload(image)[0] - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'] - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py b/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py deleted file mode 100755 index 9f9c55f1..00000000 --- a/examples/adwords/v201607/advanced_operations/add_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a text add that uses advanced features of upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Create the text ad - text_ad = { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print ('AdGroupAd with ID %s and display URL \'%s\'was added.' - % (adgroup_ad['ad']['id'], adgroup_ad['ad']['displayUrl'])) - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index c52da2ba..00000000 --- a/examples/adwords/v201607/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201607') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201607') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201607') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index 05fcdf3f..00000000 --- a/examples/adwords/v201607/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201607') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201607') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 3de92cc2..00000000 --- a/examples/adwords/v201607/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201607') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 5521034d..00000000 --- a/examples/adwords/v201607/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201607') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201607') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201607') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201607/basic_operations/__init__.py b/examples/adwords/v201607/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201607/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201607/basic_operations/add_ad_groups.py b/examples/adwords/v201607/basic_operations/add_ad_groups.py deleted file mode 100755 index b0e52a8f..00000000 --- a/examples/adwords/v201607/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201607') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/basic_operations/add_campaigns.py b/examples/adwords/v201607/basic_operations/add_campaigns.py deleted file mode 100755 index 3d3c6d1f..00000000 --- a/examples/adwords/v201607/basic_operations/add_campaigns.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201607') - budget_service = client.GetService('BudgetService', version='v201607') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index 19e48782..00000000 --- a/examples/adwords/v201607/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/add_keywords.py b/examples/adwords/v201607/basic_operations/add_keywords.py deleted file mode 100755 index ed6db735..00000000 --- a/examples/adwords/v201607/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201607') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/add_text_ads.py b/examples/adwords/v201607/basic_operations/add_text_ads.py deleted file mode 100755 index 4c58562c..00000000 --- a/examples/adwords/v201607/basic_operations/add_text_ads.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds several text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Construct operations and add ads. - # If needed, you could specify an exemption request here, e.g.: - # 'exemptionRequests': [{ - # # This comes back in a PolicyViolationError. - # 'key' { - # 'policyName': '...', - # 'violatingText': '...' - # } - # }] - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - }, - # Optional fields. - 'status': 'PAUSED' - } - }, - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Enjoy your stay at Red Planet.', - 'description2': 'Buy your tickets now!', - 'headline': 'Luxury Cruise to Mars' - } - } - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad with id \'%s\' and of type \'%s\' was added.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/get_ad_groups.py b/examples/adwords/v201607/basic_operations/get_ad_groups.py deleted file mode 100755 index 29a50c30..00000000 --- a/examples/adwords/v201607/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201607') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/basic_operations/get_campaigns.py b/examples/adwords/v201607/basic_operations/get_campaigns.py deleted file mode 100755 index 10c362cb..00000000 --- a/examples/adwords/v201607/basic_operations/get_campaigns.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201607') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 8b8043d9..00000000 --- a/examples/adwords/v201607/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201607') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index cf10d064..00000000 --- a/examples/adwords/v201607/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/get_keywords.py b/examples/adwords/v201607/basic_operations/get_keywords.py deleted file mode 100755 index 34a78f7e..00000000 --- a/examples/adwords/v201607/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201607') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/get_text_ads.py b/examples/adwords/v201607/basic_operations/get_text_ads.py deleted file mode 100755 index 0f6663c4..00000000 --- a/examples/adwords/v201607/basic_operations/get_text_ads.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 text ads for a given ad group. - -To add an ad, run add_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/pause_ad.py b/examples/adwords/v201607/basic_operations/pause_ad.py deleted file mode 100755 index cb8fe0f6..00000000 --- a/examples/adwords/v201607/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201607/basic_operations/remove_ad.py b/examples/adwords/v201607/basic_operations/remove_ad.py deleted file mode 100755 index 77c2bf3a..00000000 --- a/examples/adwords/v201607/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201607/basic_operations/remove_ad_group.py b/examples/adwords/v201607/basic_operations/remove_ad_group.py deleted file mode 100755 index 0a9991f7..00000000 --- a/examples/adwords/v201607/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201607') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/remove_campaign.py b/examples/adwords/v201607/basic_operations/remove_campaign.py deleted file mode 100755 index b5c953bd..00000000 --- a/examples/adwords/v201607/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201607') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/basic_operations/remove_keyword.py b/examples/adwords/v201607/basic_operations/remove_keyword.py deleted file mode 100755 index 7b4d815c..00000000 --- a/examples/adwords/v201607/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201607') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201607/basic_operations/update_ad_group.py b/examples/adwords/v201607/basic_operations/update_ad_group.py deleted file mode 100755 index 91b9310d..00000000 --- a/examples/adwords/v201607/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201607') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/basic_operations/update_campaign.py b/examples/adwords/v201607/basic_operations/update_campaign.py deleted file mode 100755 index a55ac7db..00000000 --- a/examples/adwords/v201607/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201607') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/basic_operations/update_keyword.py b/examples/adwords/v201607/basic_operations/update_keyword.py deleted file mode 100755 index 9f498e46..00000000 --- a/examples/adwords/v201607/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201607') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201607/campaign_management/__init__.py b/examples/adwords/v201607/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201607/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201607/campaign_management/add_campaign_labels.py b/examples/adwords/v201607/campaign_management/add_campaign_labels.py deleted file mode 100755 index 69a493c5..00000000 --- a/examples/adwords/v201607/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201607') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index d1e3580d..00000000 --- a/examples/adwords/v201607/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,426 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201607') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201607') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding a TextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new TextAd for each of - the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'TextAd', - 'headline': 'Luxury Cruise to Mars', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'displayUrl': 'www.example.com', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201607') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201607/campaign_management/add_draft.py b/examples/adwords/v201607/campaign_management/add_draft.py deleted file mode 100755 index 0f7757c2..00000000 --- a/examples/adwords/v201607/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201607') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201607') - - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201607/campaign_management/add_experiment.py b/examples/adwords/v201607/campaign_management/add_experiment.py deleted file mode 100755 index aac50210..00000000 --- a/examples/adwords/v201607/campaign_management/add_experiment.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates an experiment. - -The created experiment is using a query percentage of 10, which defines what -fraction of auctions should go to the control split (90%) vs. the experiment -split (10%), then adds experimental bid changes for an ad group, and adds an -experiment-only keyword. To get campaigns, run get_campaigns.py. To get ad -groups, run get_ad_groups.py. To get keywords, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201607') - ad_group_service = client.GetService('AdGroupService', version='v201607') - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201607') - - # Construct operations and add experiment. - tomorrow = datetime.datetime.now() + datetime.timedelta(1) - thirty_days = datetime.datetime.now() + datetime.timedelta(30) - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Interplanetary Experiment #%s' % uuid.uuid4(), - 'queryPercentage': '10', - 'startDateTime': tomorrow.strftime('%Y%m%d %H%M%S'), - # Optional fields. - 'status': 'ENABLED', - 'endDateTime': thirty_days.strftime('%Y%m%d %H%M%S') - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was added.' - % (experiment['name'], experiment['id'])) - - # Construct operations and update ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'experimentData': { - 'xsi_type': 'AdGroupExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'MODIFIED', - 'experimentBidMultipliers': { - 'xsi_type': 'ManualCPCAdGroupExperimentBidMultipliers', - 'maxCpcMultiplier': { - 'multiplier': '0.5' - } - } - } - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated in the ' - 'experiment.' % (ad_group['name'], ad_group['id'])) - - # Construct operations and add ad group crierion. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - }, - 'experimentData': { - 'xsi_type': 'BiddableAdGroupCriterionExperimentData', - 'experimentId': experiment['id'], - 'experimentDeltaStatus': 'EXPERIMENT_ONLY' - } - } - }] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\' and criterion ' - 'id \'%s\' was added to the experiment.' - % (criterion['adGroupId'], criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index aff70d23..00000000 --- a/examples/adwords/v201607/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201607') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201607') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201607') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201607') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201607/campaign_management/add_trial.py b/examples/adwords/v201607/campaign_management/add_trial.py deleted file mode 100755 index 4fa27d82..00000000 --- a/examples/adwords/v201607/campaign_management/add_trial.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201607') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201607') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 3a6691cf..00000000 --- a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 2b7a3862..00000000 --- a/examples/adwords/v201607/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index c585a3d7..00000000 --- a/examples/adwords/v201607/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201607') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201607/campaign_management/graduate_trial.py b/examples/adwords/v201607/campaign_management/graduate_trial.py deleted file mode 100755 index 31423474..00000000 --- a/examples/adwords/v201607/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201607') - budget_service = client.GetService('BudgetService', version='v201607') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201607/campaign_management/promote_experiment.py b/examples/adwords/v201607/campaign_management/promote_experiment.py deleted file mode 100755 index c0a6e044..00000000 --- a/examples/adwords/v201607/campaign_management/promote_experiment.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 promotes an experiment. - -Promoting an experiment permanently applies all the experimental changes made to -its related ad groups, criteria and ads. To add an experiment, run -add_experiment.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -EXPERIMENT_ID = 'INSERT_EXPERIMENT_ID_HERE' - - -def main(client, experiment_id): - # Initialize appropriate service. - experiment_service = client.GetService('ExperimentService', version='v201607') - - # Construct operations and promote experiment. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': experiment_id, - 'status': 'PROMOTED' - } - }] - result = experiment_service.mutate(operations) - - # Display results. - for experiment in result['value']: - print ('Experiment with name \'%s\' and id \'%s\' was promoted.' - % (experiment['name'], experiment['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, EXPERIMENT_ID) diff --git a/examples/adwords/v201607/campaign_management/set_ad_parameters.py b/examples/adwords/v201607/campaign_management/set_ad_parameters.py deleted file mode 100755 index 6cda9f60..00000000 --- a/examples/adwords/v201607/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - ad_param_service = client.GetService('AdParamService', version='v201607') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index f3567567..00000000 --- a/examples/adwords/v201607/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201607') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201607/campaign_management/validate_text_ad.py b/examples/adwords/v201607/campaign_management/validate_text_ad.py deleted file mode 100755 index d19563b2..00000000 --- a/examples/adwords/v201607/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Construct operations to add a text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'url': 'http://www.example.com', - 'displayUrl': 'example.com', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for all astronauts in orbit', - 'headline': 'Luxury Cruise to Mars' - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/error_handling/__init__.py b/examples/adwords/v201607/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201607/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201607/error_handling/handle_partial_failures.py b/examples/adwords/v201607/error_handling/handle_partial_failures.py deleted file mode 100755 index 2ab5ec73..00000000 --- a/examples/adwords/v201607/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201607') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py b/examples/adwords/v201607/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 94782901..00000000 --- a/examples/adwords/v201607/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201607') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - index = int(operation_index[0]) - operation = operations[index] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Set non-exemptable operation to None to mark for deletion - print 'Removing the operation from the request.' - operations[index] = None - else: - # Non-policy error returned, re-throw exception. - raise e - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/extensions/__init__.py b/examples/adwords/v201607/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201607/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 77c04d35..00000000 --- a/examples/adwords/v201607/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201607').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201607') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201607/extensions/add_prices.py b/examples/adwords/v201607/extensions/add_prices.py deleted file mode 100755 index 56f7c658..00000000 --- a/examples/adwords/v201607/extensions/add_prices.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a price extension and associates it with an account. - -Campaign targeting is also set usin the specified campaign ID. To get campaigns, -run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -MICROS_PER_DOLLAR = 1000000 - - -def main(client, campaign_id): - # Initialize appropriate service. - customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201607') - - # To create a price extension, at least three table rows are needed. - table_rows = [ - CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', - 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR'), - CreatePriceTableRow('Hair Cuts', 'Once a month', - 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH'), - CreatePriceTableRow('Skin Care Package', 'Four times a month', - 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH') - ] - - # Create the price extension feed item. - customer_extension_setting = { - 'extensionType': 'PRICE', - 'extensionSetting': { - 'extensions': [{ - 'priceExtensionType': 'SERVICES', - 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', - 'language': 'en', - 'campaignTargeting': { - 'TargetingCampaignId': campaign_id - }, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': 'SATURDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 22, - 'endMinute': 'ZERO' - }, - { - 'dayOfWeek': 'SUNDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 18, - 'endMinute': 'ZERO' - } - ] - }, - 'tableRows': table_rows, - # Price qualifier is optional. - 'priceQualifier': 'FROM', - 'xsi_type': 'PriceFeedItem' - }] - } - } - - # Create an operation to add the feed. - operations = [{ - 'operator': 'ADD', - 'operand': customer_extension_setting - }] - - # Add the price extension. - response = customer_extension_setting_service.mutate(operations) - - # Print the results. - if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit): - """Helper function to generate a single row of a price table. - - Args: - header: A str containing the header text of this row. - description: A str description of this row in the price table. - final_url: A str containing the final URL after all cross domain redirects. - price_in_micros: An int indicating the price of the given currency in - micros. - currency_code: A str indicating the currency code being used. - price_unit: A str enum indicating the price unit for this row. - - Returns: - A dictionary containing the contents of the generated price table row. - """ - return { - 'header': header, - 'description': description, - 'finalUrls': {'urls': [final_url]}, - 'price': { - 'money': { - 'microAmount': price_in_micros, - }, - 'currencyCode': currency_code - }, - 'priceUnit': price_unit, - 'xsi_type': 'PriceTableRow' - } - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/extensions/add_site_links.py b/examples/adwords/v201607/extensions/add_site_links.py deleted file mode 100755 index 24cd06da..00000000 --- a/examples/adwords/v201607/extensions/add_site_links.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201607') - customer_service = client.GetService('CustomerService', version='v201607') - # Find the matching customer and its time zone. The getCustomers method will - # return a single Customer object corresponding to the configured - # clientCustomerId. - customer = customer_service.getCustomers()[0] - customer_tz = timezone(customer['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840}, - # Restrict targeting only to people physically within the United States. - # Otherwise, this could also show to people interested in the United - # States, but not physically located there. - 'geoTargetingRestriction': { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py b/examples/adwords/v201607/extensions/add_site_links_using_feeds.py deleted file mode 100755 index 89e37397..00000000 --- a/examples/adwords/v201607/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_2_TEXT = '3' -PLACEHOLDER_FIELD_LINE_3_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201607') - feed_item_service = client.GetService('FeedItemService', version='v201607') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201607') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201607') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 2 Description'}, - {'type': 'STRING', 'name': 'Line 3 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_2_feed_attribute_id = feed['attributes'][2]['id'] - line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID \'%s\' and Line 3 attribute ID \'%s\'.' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - sitelinks_data['line3FeedId'] = line_3_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line2': 'Home line 2', 'line3': 'Home line 3'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line2': 'Support line 2', 'line3': 'Support line 3'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line2': 'Products line 2', 'line3': 'Products line 3'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'stringValue': item['line3'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - feed_item['geoTargetingRestriction'] = { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/migration/__init__.py b/examples/adwords/v201607/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201607/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201607/migration/migrate_to_extension_settings.py b/examples/adwords/v201607/migration/migrate_to_extension_settings.py deleted file mode 100755 index 8ff3c77a..00000000 --- a/examples/adwords/v201607/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201607') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201607') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201607') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201607') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201607') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201607') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201607') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/misc/__init__.py b/examples/adwords/v201607/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201607/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201607/misc/get_all_images_and_videos.py b/examples/adwords/v201607/misc/get_all_images_and_videos.py deleted file mode 100755 index ed4bd856..00000000 --- a/examples/adwords/v201607/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201607') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/misc/upload_image.py b/examples/adwords/v201607/misc/upload_image.py deleted file mode 100755 index 90903866..00000000 --- a/examples/adwords/v201607/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201607') - - with open(image_filename, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201607/misc/upload_media_bundle.py b/examples/adwords/v201607/misc/upload_media_bundle.py deleted file mode 100755 index c8afb690..00000000 --- a/examples/adwords/v201607/misc/upload_media_bundle.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201607') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/optimization/__init__.py b/examples/adwords/v201607/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201607/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201607/optimization/estimate_keyword_traffic.py b/examples/adwords/v201607/optimization/estimate_keyword_traffic.py deleted file mode 100755 index ed12b2ff..00000000 --- a/examples/adwords/v201607/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201607') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index 3bef47c3..00000000 --- a/examples/adwords/v201607/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201607') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index 974a6e1b..00000000 --- a/examples/adwords/v201607/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201607') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201607/optimization/get_keyword_ideas.py b/examples/adwords/v201607/optimization/get_keyword_ideas.py deleted file mode 100755 index a61cf5b8..00000000 --- a/examples/adwords/v201607/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201607') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/remarketing/__init__.py b/examples/adwords/v201607/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201607/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201607/remarketing/add_audience.py b/examples/adwords/v201607/remarketing/add_audience.py deleted file mode 100755 index 1c514e58..00000000 --- a/examples/adwords/v201607/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201607') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201607') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/remarketing/add_conversion_tracker.py b/examples/adwords/v201607/remarketing/add_conversion_tracker.py deleted file mode 100755 index 83fd087b..00000000 --- a/examples/adwords/v201607/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201607') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/remarketing/add_crm_based_user_list.py b/examples/adwords/v201607/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 36ea549d..00000000 --- a/examples/adwords/v201607/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client, emails): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201607') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. - - Args: - emails: list of str emails to be hashed. - - Returns: - A list of SHA-256 hashed emails. - """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] - - -if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) diff --git a/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index f0bca2bb..00000000 --- a/examples/adwords/v201607/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201607') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/remarketing/upload_offline_conversions.py b/examples/adwords/v201607/remarketing/upload_offline_conversions.py deleted file mode 100755 index bd020229..00000000 --- a/examples/adwords/v201607/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201607') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201607/reporting/__init__.py b/examples/adwords/v201607/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201607/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201607/reporting/download_criteria_report.py b/examples/adwords/v201607/reporting/download_criteria_report.py deleted file mode 100755 index 7912003c..00000000 --- a/examples/adwords/v201607/reporting/download_criteria_report.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201607') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index 1805b421..00000000 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201607') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index f645755d..00000000 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201607') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string.py deleted file mode 100755 index fdc0e538..00000000 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201607') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 63a0e779..00000000 --- a/examples/adwords/v201607/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201607') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 70f8a9e6..00000000 --- a/examples/adwords/v201607/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201607') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - print 'Report was downloaded to \'%s\'.' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201607/reporting/get_report_fields.py b/examples/adwords/v201607/reporting/get_report_fields.py deleted file mode 100755 index 9d238971..00000000 --- a/examples/adwords/v201607/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201607') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201607/reporting/parallel_report_download.py b/examples/adwords/v201607/reporting/parallel_report_download.py deleted file mode 100755 index abccb5e3..00000000 --- a/examples/adwords/v201607/reporting/parallel_report_download.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import logging -import multiprocessing -from Queue import Empty -import time -import googleads - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - client: An AdWordsClient instance. - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201607') - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = self._DownloadReport(customer_id) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - - Raises: - Exception: if no CustomerIds could be found. - - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201607') - - offset = 0 - - # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201607/shopping/__init__.py b/examples/adwords/v201607/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201607/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201607/shopping/add_product_partition_tree.py b/examples/adwords/v201607/shopping/add_product_partition_tree.py deleted file mode 100755 index 183dd4a9..00000000 --- a/examples/adwords/v201607/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201607') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201607/shopping/add_product_scope.py b/examples/adwords/v201607/shopping/add_product_scope.py deleted file mode 100755 index 1c529afc..00000000 --- a/examples/adwords/v201607/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201607') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201607/shopping/add_shopping_campaign.py b/examples/adwords/v201607/shopping/add_shopping_campaign.py deleted file mode 100755 index 0ba1c6f5..00000000 --- a/examples/adwords/v201607/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201607') - ad_group_service = client.GetService('AdGroupService', version='v201607') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201607') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201607/shopping/get_product_category_taxonomy.py b/examples/adwords/v201607/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 470b0546..00000000 --- a/examples/adwords/v201607/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201607') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/targeting/__init__.py b/examples/adwords/v201607/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201607/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index d1f2fbe8..00000000 --- a/examples/adwords/v201607/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201607') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish, florida_tier3] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 951f835e..00000000 --- a/examples/adwords/v201607/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201607') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 4c8b73fd..00000000 --- a/examples/adwords/v201607/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201607') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index d63e173a..00000000 --- a/examples/adwords/v201607/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201607') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201607/targeting/lookup_location.py b/examples/adwords/v201607/targeting/lookup_location.py deleted file mode 100755 index 5950060b..00000000 --- a/examples/adwords/v201607/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201607') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/account_management/accept_service_link.py b/examples/adwords/v201609/account_management/accept_service_link.py index 738c3971..3879171d 100755 --- a/examples/adwords/v201609/account_management/accept_service_link.py +++ b/examples/adwords/v201609/account_management/accept_service_link.py @@ -50,10 +50,10 @@ def main(client, service_link_id): # Display results. for mutated_service_link in mutated_service_links: - print ('Service link with service link ID \'%s\', type \'%s\' was updated ' - 'to status: \'%s\'.' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) + print ('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) if __name__ == '__main__': diff --git a/examples/adwords/v201609/account_management/create_account.py b/examples/adwords/v201609/account_management/create_account.py index cf396cd7..08d431aa 100755 --- a/examples/adwords/v201609/account_management/create_account.py +++ b/examples/adwords/v201609/account_management/create_account.py @@ -53,7 +53,7 @@ def main(client): # Display results. for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' + print ('Account with customer ID "%s" was successfully created.' % account['customerId']) diff --git a/examples/adwords/v201609/account_management/get_account_changes.py b/examples/adwords/v201609/account_management/get_account_changes.py index e1ecae70..5eed06f3 100755 --- a/examples/adwords/v201609/account_management/get_account_changes.py +++ b/examples/adwords/v201609/account_management/get_account_changes.py @@ -65,7 +65,7 @@ def main(client): print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] if account_changes['changedCampaigns']: for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' + print ('Campaign with id "%s" has change status "%s".' % (data['campaignId'], data['campaignChangeStatus'])) if (data['campaignChangeStatus'] != 'NEW' and data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): @@ -77,7 +77,7 @@ def main(client): data['removedCampaignCriteria']) if 'changedAdGroups' in data: for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' + print (' Ad group with id "%s" has change status "%s".' % (ad_group_data['adGroupId'], ad_group_data['adGroupChangeStatus'])) if ad_group_data['adGroupChangeStatus'] != 'NEW': diff --git a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py index 556e21bb..bed81b79 100755 --- a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py @@ -73,7 +73,7 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): if response and 'value' in response: for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + print ('Created an ad with ID "%s", type "%s", and status "%s".' % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) else: raise errors.GoogleAdsError('No ads were added.') @@ -117,7 +117,7 @@ def CreateCustomizerFeed(client, feed_name): 'priceId': feed['feedAttributes'][1]['id'], 'dateId': feed['feedAttributes'][2]['id'] } - print ('Feed with name \'%s\' and ID %s was added with:\n' + print ('Feed with name "%s" and ID %s was added with:\n' '\tName attribute ID %s and price attribute ID %s and date attribute' 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], feed_data['priceId'], feed_data['dateId']) diff --git a/examples/adwords/v201609/advanced_operations/add_html5_ad.py b/examples/adwords/v201609/advanced_operations/add_html5_ad.py index 66817942..ff814915 100755 --- a/examples/adwords/v201609/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201609/advanced_operations/add_html5_ad.py @@ -94,7 +94,7 @@ def main(client, ad_group_id): # Display results. for ad in ads['value']: - print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' % (ad['ad']['id'], ad['ad']['displayUrl'])) diff --git a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py index ddb17669..c3d1d76c 100755 --- a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py @@ -77,7 +77,7 @@ def CreateBiddingStrategy(client): response = bidding_strategy_service.mutate([operation]) new_bidding_strategy = response['value'][0] - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' 'was created.' % (new_bidding_strategy['name'], new_bidding_strategy['id'], new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) @@ -107,7 +107,7 @@ def CreateSharedBudget(client): 'isExplicitlyShared': 'true' } - # Create operation. + # Create operation. operation = { 'operator': 'ADD', 'operand': budget @@ -157,7 +157,7 @@ def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): response = campaign_service.mutate([operation]) new_campaign = response['value'][0] - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' 'was created.' % (new_campaign['name'], new_campaign['id'], new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) diff --git a/examples/adwords/v201609/basic_operations/add_ad_groups.py b/examples/adwords/v201609/basic_operations/add_ad_groups.py index c689f945..79f2a17c 100755 --- a/examples/adwords/v201609/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201609/basic_operations/add_ad_groups.py @@ -104,7 +104,7 @@ def main(client, campaign_id): # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' + print ('Ad group with name "%s" and id "%s" was added.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201609/basic_operations/add_campaigns.py b/examples/adwords/v201609/basic_operations/add_campaigns.py index b7eb979f..c39df642 100755 --- a/examples/adwords/v201609/basic_operations/add_campaigns.py +++ b/examples/adwords/v201609/basic_operations/add_campaigns.py @@ -117,7 +117,7 @@ def main(client): # Display results. for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' + print ('Campaign with name "%s" and id "%s" was added.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201609/basic_operations/add_keywords.py b/examples/adwords/v201609/basic_operations/add_keywords.py index 5dda0f48..1e1ab69c 100755 --- a/examples/adwords/v201609/basic_operations/add_keywords.py +++ b/examples/adwords/v201609/basic_operations/add_keywords.py @@ -78,8 +78,8 @@ def main(client, ad_group_id): # Display results. for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' + print ('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['text'], criterion['criterion']['matchType'])) diff --git a/examples/adwords/v201609/basic_operations/get_ad_groups.py b/examples/adwords/v201609/basic_operations/get_ad_groups.py index 87c7d3df..a345fec7 100755 --- a/examples/adwords/v201609/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201609/basic_operations/get_ad_groups.py @@ -59,7 +59,7 @@ def main(client, campaign_id): # Display results. if 'entries' in page: for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + print ('Ad group with name "%s", id "%s" and status "%s" was ' 'found.' % (ad_group['name'], ad_group['id'], ad_group['status'])) else: diff --git a/examples/adwords/v201609/basic_operations/get_campaigns.py b/examples/adwords/v201609/basic_operations/get_campaigns.py index 9fc2baa1..196e52c7 100755 --- a/examples/adwords/v201609/basic_operations/get_campaigns.py +++ b/examples/adwords/v201609/basic_operations/get_campaigns.py @@ -58,7 +58,7 @@ def main(client): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + print ('Campaign with id "%s", name "%s", and status "%s" was ' 'found.' % (campaign['id'], campaign['name'], campaign['status'])) else: diff --git a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py index 2f8756e0..07508aa4 100755 --- a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py @@ -48,7 +48,7 @@ def main(client): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + print ('Campaign with id "%s", name "%s", and status "%s" was ' 'found.' % (campaign['id'], campaign['name'], campaign['status'])) else: diff --git a/examples/adwords/v201609/basic_operations/get_keywords.py b/examples/adwords/v201609/basic_operations/get_keywords.py index 34871e04..11073cf3 100755 --- a/examples/adwords/v201609/basic_operations/get_keywords.py +++ b/examples/adwords/v201609/basic_operations/get_keywords.py @@ -67,8 +67,8 @@ def main(client, adgroup_id): # Display results. if 'entries' in page: for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( + print ('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( keyword['criterion']['id'], keyword['criterion']['type'], keyword['criterion']['text'], diff --git a/examples/adwords/v201609/basic_operations/get_text_ads.py b/examples/adwords/v201609/basic_operations/get_text_ads.py index bbff33f3..fc926c40 100755 --- a/examples/adwords/v201609/basic_operations/get_text_ads.py +++ b/examples/adwords/v201609/basic_operations/get_text_ads.py @@ -62,7 +62,7 @@ def main(client, ad_group_id): # Display results. if 'entries' in page: for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + print ('Ad with id "%s", status "%s", and of type "%s" was found.' % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) else: print 'No ads were found.' diff --git a/examples/adwords/v201609/basic_operations/pause_ad.py b/examples/adwords/v201609/basic_operations/pause_ad.py index 165af6b0..06cadaa2 100755 --- a/examples/adwords/v201609/basic_operations/pause_ad.py +++ b/examples/adwords/v201609/basic_operations/pause_ad.py @@ -51,7 +51,7 @@ def main(client, ad_group_id, ad_id): # Display results. for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + print 'Ad with id "%s" was updated.'% ad['ad']['id'] if __name__ == '__main__': diff --git a/examples/adwords/v201609/basic_operations/remove_ad.py b/examples/adwords/v201609/basic_operations/remove_ad.py index 82ae7f5a..f7e637c4 100755 --- a/examples/adwords/v201609/basic_operations/remove_ad.py +++ b/examples/adwords/v201609/basic_operations/remove_ad.py @@ -51,7 +51,7 @@ def main(client, ad_group_id, ad_id): # Display results. for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' + print ('Ad with id "%s" and type "%s" was deleted.' % (ad['ad']['id'], ad['ad']['Ad.Type'])) diff --git a/examples/adwords/v201609/basic_operations/remove_ad_group.py b/examples/adwords/v201609/basic_operations/remove_ad_group.py index d9e20868..da407601 100755 --- a/examples/adwords/v201609/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201609/basic_operations/remove_ad_group.py @@ -47,7 +47,7 @@ def main(client, ad_group_id): # Display results. for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + print ('Ad group with name "%s" and id "%s" was deleted.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201609/basic_operations/remove_campaign.py b/examples/adwords/v201609/basic_operations/remove_campaign.py index 73005f0d..8c66adf9 100755 --- a/examples/adwords/v201609/basic_operations/remove_campaign.py +++ b/examples/adwords/v201609/basic_operations/remove_campaign.py @@ -47,7 +47,7 @@ def main(client, campaign_id): # Display results. for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + print ('Campaign with name "%s" and id "%s" was deleted.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201609/basic_operations/remove_keyword.py b/examples/adwords/v201609/basic_operations/remove_keyword.py index e2bde83d..3887fcb5 100755 --- a/examples/adwords/v201609/basic_operations/remove_keyword.py +++ b/examples/adwords/v201609/basic_operations/remove_keyword.py @@ -54,8 +54,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' + print ('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['Criterion.Type'])) diff --git a/examples/adwords/v201609/basic_operations/update_ad_group.py b/examples/adwords/v201609/basic_operations/update_ad_group.py index 3b58a675..bef260f5 100755 --- a/examples/adwords/v201609/basic_operations/update_ad_group.py +++ b/examples/adwords/v201609/basic_operations/update_ad_group.py @@ -47,7 +47,7 @@ def main(client, ad_group_id): # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' + print ('Ad group with name "%s" and id "%s" was updated.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201609/basic_operations/update_campaign.py b/examples/adwords/v201609/basic_operations/update_campaign.py index 96639c47..ca7eb9d5 100755 --- a/examples/adwords/v201609/basic_operations/update_campaign.py +++ b/examples/adwords/v201609/basic_operations/update_campaign.py @@ -47,7 +47,7 @@ def main(client, campaign_id): # Display results. for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' + print ('Campaign with name "%s" and id "%s" was updated.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201609/basic_operations/update_keyword.py b/examples/adwords/v201609/basic_operations/update_keyword.py index 4e056bfb..36e38f72 100755 --- a/examples/adwords/v201609/basic_operations/update_keyword.py +++ b/examples/adwords/v201609/basic_operations/update_keyword.py @@ -65,12 +65,12 @@ def main(client, ad_group_id, criterion_id): if 'value' in ad_group_criteria: for criterion in ad_group_criteria['value']: if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' + print ('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' % (criterion['adGroupId'], criterion['criterion']['id'])) for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) + print '\tType: "%s", value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) else: print 'No ad group criteria were updated.' diff --git a/examples/adwords/v201609/campaign_management/add_campaign_labels.py b/examples/adwords/v201609/campaign_management/add_campaign_labels.py index 4c601330..7020658e 100755 --- a/examples/adwords/v201609/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201609/campaign_management/add_campaign_labels.py @@ -56,7 +56,7 @@ def main(client, campaign_id1, campaign_id2, label_id): # Display results. for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' % (label['campaignId'], label['labelId'])) diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py index 7d4ff086..2272b149 100755 --- a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py @@ -56,7 +56,7 @@ def main(client, campaign_id): # Display results. if 'entries' in ads: for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' + print ('Ad with id "%s" was disapproved for the following reasons: ' % (ad['ad']['id'])) if ad['ad'].get('disapprovalReasons'): for reason in ad['ad']['disapprovalReasons']: diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py index 58915dc3..fb18eef5 100755 --- a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py @@ -45,7 +45,7 @@ def main(client, campaign_id): # Display results. if 'entries' in ads: for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' + print ('Ad with id "%s" was disapproved for the following reasons: ' % (ad['ad']['id'])) if ad['ad'].get('disapprovalReasons'): for reason in ad['ad']['disapprovalReasons']: diff --git a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py index bb0c5664..08b365b3 100755 --- a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py @@ -67,7 +67,7 @@ def main(client, label_id): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + print ('Campaign found with Id "%s", name "%s", and labels: %s' % (campaign['id'], campaign['name'], campaign['labels'])) else: print 'No campaigns were found.' diff --git a/examples/adwords/v201609/campaign_management/set_ad_parameters.py b/examples/adwords/v201609/campaign_management/set_ad_parameters.py index c270e2da..9013f36d 100755 --- a/examples/adwords/v201609/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201609/campaign_management/set_ad_parameters.py @@ -59,8 +59,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + print ('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) # Construct operations for setting ad parameters. operations = [ @@ -87,8 +87,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' + print ('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' % (ad_param['insertionText'], ad_param['criterionId'], ad_param['adGroupId'])) diff --git a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py index 002a05d4..30c5734c 100755 --- a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py @@ -63,8 +63,8 @@ def main(client, campaign_id, bid_modifier): # Display the resulting campaign criteria. for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' + print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['bidModifier'])) diff --git a/examples/adwords/v201609/campaign_management/validate_text_ad.py b/examples/adwords/v201609/campaign_management/validate_text_ad.py index 676ee8db..3c2c3d39 100755 --- a/examples/adwords/v201609/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201609/campaign_management/validate_text_ad.py @@ -74,7 +74,7 @@ def main(client, ad_group_id): try: ad_group_ad_service.mutate(operations) except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) + print 'Validation correctly failed with "%s".' % str(e) if __name__ == '__main__': diff --git a/examples/adwords/v201609/error_handling/handle_partial_failures.py b/examples/adwords/v201609/error_handling/handle_partial_failures.py index 0d50e044..6d2e7f3d 100755 --- a/examples/adwords/v201609/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201609/error_handling/handle_partial_failures.py @@ -94,8 +94,8 @@ def main(client, ad_group_id): # Display results. for criterion in result['value']: if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + print ('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' 'added.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['text'], @@ -104,13 +104,13 @@ def main(client, ad_group_id): for error in result['partialFailureErrors']: index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) if index: - print ('Keyword ad group criterion with ad group id \'%s\' and text ' - '\'%s\' triggered a failure for the following reason: \'%s\'.' + print ('Keyword ad group criterion with ad group id "%s" and text ' + '"%s" triggered a failure for the following reason: "%s".' % (keywords[int(index[0])]['adGroupId'], keywords[int(index[0])]['criterion']['text'], error['errorString'])) else: - print 'The following failure has occurred: \'%s\'.' % error['errorString'] + print 'The following failure has occurred: "%s".' % error['errorString'] if __name__ == '__main__': diff --git a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py index 5f7199d6..ec6cda1a 100755 --- a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py @@ -72,14 +72,14 @@ def main(client, ad_group_id): if operation_index: index = int(operation_index[0]) operation = operations[index] - print ('Ad with headline \'%s\' violated %s policy \'%s\'.' % + print ('Ad with headline "%s" violated %s policy "%s".' % (operation['operand']['ad']['headline'], 'exemptable' if error['isExemptable'] else 'non-exemptable', error['externalPolicyName'])) if error['isExemptable'].lower() == 'true': # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text ' - '\'%s\'.' % + print ('Adding exemption request for policy name "%s" on text ' + '"%s".' % (error['key']['policyName'], error['key']['violatingText'])) if 'exemptionRequests' not in operation: operation['exemptionRequests'] = [] @@ -104,7 +104,7 @@ def main(client, ad_group_id): ads = response['value'] print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % + print (' Ad id is %s, type is %s and status is "%s".' % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) else: print 'No ads were added.' diff --git a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py index 1373c1b1..83eae4ae 100755 --- a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py @@ -76,11 +76,11 @@ def main(client, campaign_id): final_url_feed_attribute_id = feed['attributes'][1]['id'] line_2_feed_attribute_id = feed['attributes'][2]['id'] line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % + print ('Feed with name "%s" and ID "%s" was added with' % (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID \'%s\' and Line 3 attribute ID \'%s\'.' % + print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % (line_2_feed_attribute_id, line_3_feed_attribute_id)) sitelinks_data['feedId'] = feed['id'] sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id diff --git a/examples/adwords/v201609/misc/get_all_images_and_videos.py b/examples/adwords/v201609/misc/get_all_images_and_videos.py index 9b562fab..eabf2367 100755 --- a/examples/adwords/v201609/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201609/misc/get_all_images_and_videos.py @@ -63,14 +63,14 @@ def main(client): except AttributeError: dimensions = {'FULL': {'height': 0, 'width': 0}} if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' ' was found.' % (image['type'], image['mediaId'], dimensions['FULL']['height'], dimensions['FULL']['width'], image['mimeType'])) elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) + print ('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) else: print 'No images/videos were found.' offset += PAGE_SIZE diff --git a/examples/adwords/v201609/misc/upload_image.py b/examples/adwords/v201609/misc/upload_image.py index d4fd4a24..fa4bbe52 100755 --- a/examples/adwords/v201609/misc/upload_image.py +++ b/examples/adwords/v201609/misc/upload_image.py @@ -52,7 +52,7 @@ def main(client, image_filename): if media: dimensions = dict([(entry['key'], entry['value']) for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], dimensions['FULL']['width'], media['mimeType'])) else: diff --git a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py index 5bfbf3af..6305dce5 100755 --- a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py @@ -59,8 +59,8 @@ def main(client, ad_group_id, criterion_id): if 'entries' in bid_landscapes: for bid_landscape in bid_landscapes['entries']: if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + print ('Criterion bid landscape with ad group id "%s", criterion id ' + '"%s", start date "%s", end date "%s", with landscape ' 'points was found:' % (bid_landscape['adGroupId'], bid_landscape['criterionId'], bid_landscape['startDate'], bid_landscape['endDate'])) diff --git a/examples/adwords/v201609/optimization/get_keyword_ideas.py b/examples/adwords/v201609/optimization/get_keyword_ideas.py index 9663b601..3f2cfc5f 100755 --- a/examples/adwords/v201609/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201609/optimization/get_keyword_ideas.py @@ -80,8 +80,8 @@ def main(client): for attribute in result['data']: attributes[attribute['key']] = getattr(attribute['value'], 'value', '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' + print ('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' % (attributes['KEYWORD_TEXT'], attributes['SEARCH_VOLUME'], attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) diff --git a/examples/adwords/v201609/remarketing/add_audience.py b/examples/adwords/v201609/remarketing/add_audience.py index 38652c29..9945364d 100755 --- a/examples/adwords/v201609/remarketing/add_audience.py +++ b/examples/adwords/v201609/remarketing/add_audience.py @@ -85,7 +85,7 @@ def main(client): conversions_map[conversion_tracker['id']] = conversion_tracker for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' + print ('User list with name "%s" and ID "%s" was added.' % (user_list['name'], user_list['id'])) if user_list['conversionTypes']: for conversion_type in user_list['conversionTypes']: diff --git a/examples/adwords/v201609/remarketing/add_conversion_tracker.py b/examples/adwords/v201609/remarketing/add_conversion_tracker.py index 310586ed..44ef43f1 100755 --- a/examples/adwords/v201609/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201609/remarketing/add_conversion_tracker.py @@ -56,8 +56,8 @@ def main(client): # Display results. for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + print ('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.\n' % (conversion_tracker['id'], conversion_tracker['name'], conversion_tracker['status'], conversion_tracker['category'], conversion_tracker['snippet'])) diff --git a/examples/adwords/v201609/remarketing/upload_offline_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_conversions.py index 57d7836d..80704387 100755 --- a/examples/adwords/v201609/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201609/remarketing/upload_offline_conversions.py @@ -61,10 +61,10 @@ def main(client, conversion_name, click_id, conversion_time, conversion_value): [offline_conversion_operation]) new_feed = offline_conversion_response['value'] - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) + print ('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) if __name__ == '__main__': diff --git a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py index bfe1c36c..3ec66566 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py @@ -49,7 +49,7 @@ def main(client, path): skip_column_header=False, skip_report_summary=False, include_zero_impressions=True) - print 'Report was downloaded to \'%s\'.' % path + print 'Report was downloaded to "%s".' % path if __name__ == '__main__': diff --git a/examples/adwords/v201609/reporting/get_report_fields.py b/examples/adwords/v201609/reporting/get_report_fields.py index 4f816fbb..90720035 100755 --- a/examples/adwords/v201609/reporting/get_report_fields.py +++ b/examples/adwords/v201609/reporting/get_report_fields.py @@ -38,7 +38,7 @@ def main(client, report_type): fields = report_definition_service.getReportFields(report_type) # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type + print 'Report type "%s" contains the following fields:' % report_type for field in fields: print ' - %s (%s)' % (field['fieldName'], field['fieldType']) if 'enumValues' in field: diff --git a/examples/adwords/v201609/shopping/add_shopping_campaign.py b/examples/adwords/v201609/shopping/add_shopping_campaign.py index 8bbfcc65..6549b688 100755 --- a/examples/adwords/v201609/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201609/shopping/add_shopping_campaign.py @@ -75,7 +75,7 @@ def main(client, budget_id, merchant_id): result = campaign_service.mutate(campaign_operations) for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' + print ('Campaign with name "%s" and ID "%s" was added.' % (campaign['name'], campaign['id'])) # Create the AdGroup @@ -93,7 +93,7 @@ def main(client, budget_id, merchant_id): ad_group_result = ad_group_service.mutate(adgroup_operations) for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + print ('AdGroup with name "%s" and ID "%s" was added.' % (adgroup['name'], adgroup['id'])) # Create an AdGroup Ad @@ -115,7 +115,7 @@ def main(client, budget_id, merchant_id): ad_result = ad_group_ad_service.mutate([ad_operation]) for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] if __name__ == '__main__': diff --git a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py index 6ad6bf37..25dc2cce 100755 --- a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py @@ -132,8 +132,8 @@ def main(client, campaign_id, location_feed_id=None): # Display the resulting campaign criteria. for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' + print ('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['criterion']['type'])) diff --git a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py index 91158d00..512f489b 100755 --- a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py @@ -82,7 +82,7 @@ def main(client, ad_group_id): for ad_group_criterion in criteria: criterion = ad_group_criterion['criterion'] print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % + 'type "%s" was added.' % (ad_group_criterion['adGroupId'], criterion['id'], criterion['type'])) else: diff --git a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py index 6dec0e63..c96c4d82 100755 --- a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py @@ -36,7 +36,7 @@ def main(client): # Display results. for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' + print ('Language with name "%s" and ID "%s" was found.' % (language['name'], language['id'])) # Get all carriers. @@ -44,7 +44,7 @@ def main(client): # Display results. for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + print ('Carrier with name "%s", ID "%s", and country code "%s" was ' 'found.' % ( carrier['name'], carrier['id'], getattr(carrier, 'countryCode', 'N/A'))) diff --git a/examples/adwords/v201609/targeting/lookup_location.py b/examples/adwords/v201609/targeting/lookup_location.py index 9dcd3b72..8c5d76fa 100755 --- a/examples/adwords/v201609/targeting/lookup_location.py +++ b/examples/adwords/v201609/targeting/lookup_location.py @@ -64,8 +64,8 @@ def main(client): parent_string = ', '.join([GetLocationString(parent)for parent in location_criterion['location'] ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + print ('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' % (location_criterion['searchTerm'], location_criterion['location']['locationName'], location_criterion['location']['displayType'], parent_string, diff --git a/examples/adwords/v201702/account_management/accept_service_link.py b/examples/adwords/v201702/account_management/accept_service_link.py index 4cacf5b4..a6d6a261 100755 --- a/examples/adwords/v201702/account_management/accept_service_link.py +++ b/examples/adwords/v201702/account_management/accept_service_link.py @@ -50,10 +50,10 @@ def main(client, service_link_id): # Display results. for mutated_service_link in mutated_service_links: - print ('Service link with service link ID \'%s\', type \'%s\' was updated ' - 'to status: \'%s\'.' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) + print ('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) if __name__ == '__main__': diff --git a/examples/adwords/v201702/account_management/create_account.py b/examples/adwords/v201702/account_management/create_account.py index baa39e9f..55bbcba6 100755 --- a/examples/adwords/v201702/account_management/create_account.py +++ b/examples/adwords/v201702/account_management/create_account.py @@ -53,7 +53,7 @@ def main(client): # Display results. for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' + print ('Account with customer ID "%s" was successfully created.' % account['customerId']) diff --git a/examples/adwords/v201702/account_management/get_account_changes.py b/examples/adwords/v201702/account_management/get_account_changes.py index 63c920dd..d97a6827 100755 --- a/examples/adwords/v201702/account_management/get_account_changes.py +++ b/examples/adwords/v201702/account_management/get_account_changes.py @@ -65,7 +65,7 @@ def main(client): print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] if account_changes['changedCampaigns']: for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' + print ('Campaign with id "%s" has change status "%s".' % (data['campaignId'], data['campaignChangeStatus'])) if (data['campaignChangeStatus'] != 'NEW' and data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): @@ -77,7 +77,7 @@ def main(client): data['removedCampaignCriteria']) if 'changedAdGroups' in data: for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' + print (' Ad group with id "%s" has change status "%s".' % (ad_group_data['adGroupId'], ad_group_data['adGroupChangeStatus'])) if ad_group_data['adGroupChangeStatus'] != 'NEW': diff --git a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py index 60c582e4..a01996cf 100755 --- a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py @@ -73,7 +73,7 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): if response and 'value' in response: for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + print ('Created an ad with ID "%s", type "%s", and status "%s".' % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) else: raise errors.GoogleAdsError('No ads were added.') @@ -117,7 +117,7 @@ def CreateCustomizerFeed(client, feed_name): 'priceId': feed['feedAttributes'][1]['id'], 'dateId': feed['feedAttributes'][2]['id'] } - print ('Feed with name \'%s\' and ID %s was added with:\n' + print ('Feed with name "%s" and ID %s was added with:\n' '\tName attribute ID %s and price attribute ID %s and date attribute' 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], feed_data['priceId'], feed_data['dateId']) diff --git a/examples/adwords/v201702/advanced_operations/add_html5_ad.py b/examples/adwords/v201702/advanced_operations/add_html5_ad.py index 64c94864..208add9e 100755 --- a/examples/adwords/v201702/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201702/advanced_operations/add_html5_ad.py @@ -94,7 +94,7 @@ def main(client, ad_group_id): # Display results. for ad in ads['value']: - print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' % (ad['ad']['id'], ad['ad']['displayUrl'])) diff --git a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py index 1c535dfb..98dd1275 100755 --- a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py @@ -77,7 +77,7 @@ def CreateBiddingStrategy(client): response = bidding_strategy_service.mutate([operation]) new_bidding_strategy = response['value'][0] - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' 'was created.' % (new_bidding_strategy['name'], new_bidding_strategy['id'], new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) @@ -107,7 +107,7 @@ def CreateSharedBudget(client): 'isExplicitlyShared': 'true' } - # Create operation. + # Create operation. operation = { 'operator': 'ADD', 'operand': budget @@ -157,7 +157,7 @@ def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): response = campaign_service.mutate([operation]) new_campaign = response['value'][0] - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' 'was created.' % (new_campaign['name'], new_campaign['id'], new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) diff --git a/examples/adwords/v201702/basic_operations/add_ad_groups.py b/examples/adwords/v201702/basic_operations/add_ad_groups.py index a561c5ef..9dad1690 100755 --- a/examples/adwords/v201702/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201702/basic_operations/add_ad_groups.py @@ -104,7 +104,7 @@ def main(client, campaign_id): # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' + print ('Ad group with name "%s" and id "%s" was added.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201702/basic_operations/add_campaigns.py b/examples/adwords/v201702/basic_operations/add_campaigns.py index ababe339..49dd97f3 100755 --- a/examples/adwords/v201702/basic_operations/add_campaigns.py +++ b/examples/adwords/v201702/basic_operations/add_campaigns.py @@ -117,7 +117,7 @@ def main(client): # Display results. for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' + print ('Campaign with name "%s" and id "%s" was added.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201702/basic_operations/add_keywords.py b/examples/adwords/v201702/basic_operations/add_keywords.py index d86e4b31..437ffbf2 100755 --- a/examples/adwords/v201702/basic_operations/add_keywords.py +++ b/examples/adwords/v201702/basic_operations/add_keywords.py @@ -78,8 +78,8 @@ def main(client, ad_group_id): # Display results. for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' + print ('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['text'], criterion['criterion']['matchType'])) diff --git a/examples/adwords/v201702/basic_operations/get_ad_groups.py b/examples/adwords/v201702/basic_operations/get_ad_groups.py index 683a3229..0ae7272b 100755 --- a/examples/adwords/v201702/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201702/basic_operations/get_ad_groups.py @@ -59,7 +59,7 @@ def main(client, campaign_id): # Display results. if 'entries' in page: for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + print ('Ad group with name "%s", id "%s" and status "%s" was ' 'found.' % (ad_group['name'], ad_group['id'], ad_group['status'])) else: diff --git a/examples/adwords/v201702/basic_operations/get_campaigns.py b/examples/adwords/v201702/basic_operations/get_campaigns.py index 159e2009..489cddc1 100755 --- a/examples/adwords/v201702/basic_operations/get_campaigns.py +++ b/examples/adwords/v201702/basic_operations/get_campaigns.py @@ -58,7 +58,7 @@ def main(client): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + print ('Campaign with id "%s", name "%s", and status "%s" was ' 'found.' % (campaign['id'], campaign['name'], campaign['status'])) else: diff --git a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py index 3f7f7831..58497c61 100755 --- a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py @@ -48,7 +48,7 @@ def main(client): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + print ('Campaign with id "%s", name "%s", and status "%s" was ' 'found.' % (campaign['id'], campaign['name'], campaign['status'])) else: diff --git a/examples/adwords/v201702/basic_operations/get_keywords.py b/examples/adwords/v201702/basic_operations/get_keywords.py index 87cc693a..83d6ee18 100755 --- a/examples/adwords/v201702/basic_operations/get_keywords.py +++ b/examples/adwords/v201702/basic_operations/get_keywords.py @@ -67,8 +67,8 @@ def main(client, adgroup_id): # Display results. if 'entries' in page: for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( + print ('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( keyword['criterion']['id'], keyword['criterion']['type'], keyword['criterion']['text'], diff --git a/examples/adwords/v201702/basic_operations/get_text_ads.py b/examples/adwords/v201702/basic_operations/get_text_ads.py index 8393d7ae..424ceef6 100755 --- a/examples/adwords/v201702/basic_operations/get_text_ads.py +++ b/examples/adwords/v201702/basic_operations/get_text_ads.py @@ -62,7 +62,7 @@ def main(client, ad_group_id): # Display results. if 'entries' in page: for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' + print ('Ad with id "%s", status "%s", and of type "%s" was found.' % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) else: print 'No ads were found.' diff --git a/examples/adwords/v201702/basic_operations/pause_ad.py b/examples/adwords/v201702/basic_operations/pause_ad.py index 211e67de..c4822b5e 100755 --- a/examples/adwords/v201702/basic_operations/pause_ad.py +++ b/examples/adwords/v201702/basic_operations/pause_ad.py @@ -51,7 +51,7 @@ def main(client, ad_group_id, ad_id): # Display results. for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + print 'Ad with id "%s" was updated.'% ad['ad']['id'] if __name__ == '__main__': diff --git a/examples/adwords/v201702/basic_operations/remove_ad.py b/examples/adwords/v201702/basic_operations/remove_ad.py index 7ea2ce5c..ab8c5d2a 100755 --- a/examples/adwords/v201702/basic_operations/remove_ad.py +++ b/examples/adwords/v201702/basic_operations/remove_ad.py @@ -51,7 +51,7 @@ def main(client, ad_group_id, ad_id): # Display results. for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' + print ('Ad with id "%s" and type "%s" was deleted.' % (ad['ad']['id'], ad['ad']['Ad.Type'])) diff --git a/examples/adwords/v201702/basic_operations/remove_ad_group.py b/examples/adwords/v201702/basic_operations/remove_ad_group.py index 278c6fc6..374865a2 100755 --- a/examples/adwords/v201702/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201702/basic_operations/remove_ad_group.py @@ -47,7 +47,7 @@ def main(client, ad_group_id): # Display results. for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + print ('Ad group with name "%s" and id "%s" was deleted.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201702/basic_operations/remove_campaign.py b/examples/adwords/v201702/basic_operations/remove_campaign.py index 621c2144..3252c2fd 100755 --- a/examples/adwords/v201702/basic_operations/remove_campaign.py +++ b/examples/adwords/v201702/basic_operations/remove_campaign.py @@ -47,7 +47,7 @@ def main(client, campaign_id): # Display results. for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + print ('Campaign with name "%s" and id "%s" was deleted.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201702/basic_operations/remove_keyword.py b/examples/adwords/v201702/basic_operations/remove_keyword.py index 33a7c051..a09c35bb 100755 --- a/examples/adwords/v201702/basic_operations/remove_keyword.py +++ b/examples/adwords/v201702/basic_operations/remove_keyword.py @@ -54,8 +54,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' + print ('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['Criterion.Type'])) diff --git a/examples/adwords/v201702/basic_operations/update_ad_group.py b/examples/adwords/v201702/basic_operations/update_ad_group.py index 5f037c32..a682b3ea 100755 --- a/examples/adwords/v201702/basic_operations/update_ad_group.py +++ b/examples/adwords/v201702/basic_operations/update_ad_group.py @@ -47,7 +47,7 @@ def main(client, ad_group_id): # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' + print ('Ad group with name "%s" and id "%s" was updated.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201702/basic_operations/update_campaign.py b/examples/adwords/v201702/basic_operations/update_campaign.py index 5eec5e13..8505e9c1 100755 --- a/examples/adwords/v201702/basic_operations/update_campaign.py +++ b/examples/adwords/v201702/basic_operations/update_campaign.py @@ -47,7 +47,7 @@ def main(client, campaign_id): # Display results. for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' + print ('Campaign with name "%s" and id "%s" was updated.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201702/basic_operations/update_keyword.py b/examples/adwords/v201702/basic_operations/update_keyword.py index 1e3c8935..5596781f 100755 --- a/examples/adwords/v201702/basic_operations/update_keyword.py +++ b/examples/adwords/v201702/basic_operations/update_keyword.py @@ -65,12 +65,12 @@ def main(client, ad_group_id, criterion_id): if 'value' in ad_group_criteria: for criterion in ad_group_criteria['value']: if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' + print ('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' % (criterion['adGroupId'], criterion['criterion']['id'])) for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) + print '\tType: "%s", value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) else: print 'No ad group criteria were updated.' diff --git a/examples/adwords/v201702/campaign_management/add_campaign_labels.py b/examples/adwords/v201702/campaign_management/add_campaign_labels.py index ef96f5c3..e6b5f147 100755 --- a/examples/adwords/v201702/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201702/campaign_management/add_campaign_labels.py @@ -56,7 +56,7 @@ def main(client, campaign_id1, campaign_id2, label_id): # Display results. for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' % (label['campaignId'], label['labelId'])) diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py index 165fc894..0178909e 100755 --- a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py @@ -56,7 +56,7 @@ def main(client, campaign_id): # Display results. if 'entries' in ads: for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' + print ('Ad with id "%s" was disapproved for the following reasons: ' % (ad['ad']['id'])) if ad['ad'].get('disapprovalReasons'): for reason in ad['ad']['disapprovalReasons']: diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py index 3a3e9d34..87e65980 100755 --- a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py @@ -45,7 +45,7 @@ def main(client, campaign_id): # Display results. if 'entries' in ads: for ad in ads['entries']: - print ('Ad with id \'%s\' was disapproved for the following reasons: ' + print ('Ad with id "%s" was disapproved for the following reasons: ' % (ad['ad']['id'])) if ad['ad'].get('disapprovalReasons'): for reason in ad['ad']['disapprovalReasons']: diff --git a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py index a30ec34b..38e537af 100755 --- a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py @@ -67,7 +67,7 @@ def main(client, label_id): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + print ('Campaign found with Id "%s", name "%s", and labels: %s' % (campaign['id'], campaign['name'], campaign['labels'])) else: print 'No campaigns were found.' diff --git a/examples/adwords/v201702/campaign_management/set_ad_parameters.py b/examples/adwords/v201702/campaign_management/set_ad_parameters.py index 1c11b356..0a4e05b8 100755 --- a/examples/adwords/v201702/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201702/campaign_management/set_ad_parameters.py @@ -59,8 +59,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + print ('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) # Construct operations for setting ad parameters. operations = [ @@ -87,8 +87,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' + print ('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' % (ad_param['insertionText'], ad_param['criterionId'], ad_param['adGroupId'])) diff --git a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py index f9183264..9967bed8 100755 --- a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py @@ -63,8 +63,8 @@ def main(client, campaign_id, bid_modifier): # Display the resulting campaign criteria. for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' + print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['bidModifier'])) diff --git a/examples/adwords/v201702/campaign_management/validate_text_ad.py b/examples/adwords/v201702/campaign_management/validate_text_ad.py index db2b63d6..472a1591 100755 --- a/examples/adwords/v201702/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201702/campaign_management/validate_text_ad.py @@ -74,7 +74,7 @@ def main(client, ad_group_id): try: ad_group_ad_service.mutate(operations) except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) + print 'Validation correctly failed with "%s".' % str(e) if __name__ == '__main__': diff --git a/examples/adwords/v201702/error_handling/handle_partial_failures.py b/examples/adwords/v201702/error_handling/handle_partial_failures.py index b8ad2d65..fb040cc9 100755 --- a/examples/adwords/v201702/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201702/error_handling/handle_partial_failures.py @@ -93,8 +93,8 @@ def main(client, ad_group_id): # Display results. for criterion in result['value']: if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + print ('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' 'added.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['text'], diff --git a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py index a2b4828c..4872235f 100755 --- a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py @@ -119,7 +119,7 @@ def main(client, ad_group_id): ads = response['value'] print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % + print (' Ad id is %s, type is %s and status is "%s".' % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) else: print 'No ads were added.' @@ -151,7 +151,7 @@ def HandleAPIError(error, operation): if is_exemptable: # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text \'%s\'.' + print ('Adding exemption request for policy name "%s" on text "%s".' % (error['key']['policyName'], error['key']['violatingText'])) if 'exemptionRequests' not in operation: operation['exemptionRequests'] = [] diff --git a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py index 786754cf..e7e83d18 100755 --- a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py @@ -76,11 +76,11 @@ def main(client, campaign_id): final_url_feed_attribute_id = feed['attributes'][1]['id'] line_2_feed_attribute_id = feed['attributes'][2]['id'] line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % + print ('Feed with name "%s" and ID "%s" was added with' % (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID \'%s\' and Line 3 attribute ID \'%s\'.' % + print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % (line_2_feed_attribute_id, line_3_feed_attribute_id)) sitelinks_data['feedId'] = feed['id'] sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id diff --git a/examples/adwords/v201702/misc/get_all_images_and_videos.py b/examples/adwords/v201702/misc/get_all_images_and_videos.py index ac28cf74..530b1dad 100755 --- a/examples/adwords/v201702/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201702/misc/get_all_images_and_videos.py @@ -63,14 +63,14 @@ def main(client): except AttributeError: dimensions = {'FULL': {'height': 0, 'width': 0}} if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' ' was found.' % (image['type'], image['mediaId'], dimensions['FULL']['height'], dimensions['FULL']['width'], image['mimeType'])) elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) + print ('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) else: print 'No images/videos were found.' offset += PAGE_SIZE diff --git a/examples/adwords/v201702/misc/upload_image.py b/examples/adwords/v201702/misc/upload_image.py index 95ab3432..24641899 100755 --- a/examples/adwords/v201702/misc/upload_image.py +++ b/examples/adwords/v201702/misc/upload_image.py @@ -52,7 +52,7 @@ def main(client, image_filename): if media: dimensions = dict([(entry['key'], entry['value']) for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], dimensions['FULL']['width'], media['mimeType'])) else: diff --git a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py index 9bad1afd..e564882e 100755 --- a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py @@ -59,8 +59,8 @@ def main(client, ad_group_id, criterion_id): if 'entries' in bid_landscapes: for bid_landscape in bid_landscapes['entries']: if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + print ('Criterion bid landscape with ad group id "%s", criterion id ' + '"%s", start date "%s", end date "%s", with landscape ' 'points was found:' % (bid_landscape['adGroupId'], bid_landscape['criterionId'], bid_landscape['startDate'], bid_landscape['endDate'])) diff --git a/examples/adwords/v201702/optimization/get_keyword_ideas.py b/examples/adwords/v201702/optimization/get_keyword_ideas.py index 0f45a6de..cb4771e6 100755 --- a/examples/adwords/v201702/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201702/optimization/get_keyword_ideas.py @@ -80,8 +80,8 @@ def main(client): for attribute in result['data']: attributes[attribute['key']] = getattr(attribute['value'], 'value', '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' + print ('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' % (attributes['KEYWORD_TEXT'], attributes['SEARCH_VOLUME'], attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) diff --git a/examples/adwords/v201702/remarketing/add_audience.py b/examples/adwords/v201702/remarketing/add_audience.py index 7ebdaa66..1825d482 100755 --- a/examples/adwords/v201702/remarketing/add_audience.py +++ b/examples/adwords/v201702/remarketing/add_audience.py @@ -85,7 +85,7 @@ def main(client): conversions_map[conversion_tracker['id']] = conversion_tracker for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' + print ('User list with name "%s" and ID "%s" was added.' % (user_list['name'], user_list['id'])) if user_list['conversionTypes']: for conversion_type in user_list['conversionTypes']: diff --git a/examples/adwords/v201702/remarketing/add_conversion_tracker.py b/examples/adwords/v201702/remarketing/add_conversion_tracker.py index 2cb2d4e6..35395256 100755 --- a/examples/adwords/v201702/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201702/remarketing/add_conversion_tracker.py @@ -56,8 +56,8 @@ def main(client): # Display results. for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + print ('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.\n' % (conversion_tracker['id'], conversion_tracker['name'], conversion_tracker['status'], conversion_tracker['category'], conversion_tracker['snippet'])) diff --git a/examples/adwords/v201702/remarketing/upload_offline_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_conversions.py index e54e803b..c80147aa 100755 --- a/examples/adwords/v201702/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201702/remarketing/upload_offline_conversions.py @@ -61,10 +61,10 @@ def main(client, conversion_name, click_id, conversion_time, conversion_value): [offline_conversion_operation]) new_feed = offline_conversion_response['value'] - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) + print ('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) if __name__ == '__main__': diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py index bfb72e98..4418d62d 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py @@ -49,7 +49,7 @@ def main(client, path): skip_column_header=False, skip_report_summary=False, include_zero_impressions=True) - print 'Report was downloaded to \'%s\'.' % path + print 'Report was downloaded to "%s".' % path if __name__ == '__main__': diff --git a/examples/adwords/v201702/reporting/get_report_fields.py b/examples/adwords/v201702/reporting/get_report_fields.py index 9ed7c53a..77531ed7 100755 --- a/examples/adwords/v201702/reporting/get_report_fields.py +++ b/examples/adwords/v201702/reporting/get_report_fields.py @@ -38,7 +38,7 @@ def main(client, report_type): fields = report_definition_service.getReportFields(report_type) # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type + print 'Report type "%s" contains the following fields:' % report_type for field in fields: print ' - %s (%s)' % (field['fieldName'], field['fieldType']) if 'enumValues' in field: diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign.py b/examples/adwords/v201702/shopping/add_shopping_campaign.py index 2a13a0d0..87cea0af 100755 --- a/examples/adwords/v201702/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201702/shopping/add_shopping_campaign.py @@ -75,7 +75,7 @@ def main(client, budget_id, merchant_id): result = campaign_service.mutate(campaign_operations) for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' + print ('Campaign with name "%s" and ID "%s" was added.' % (campaign['name'], campaign['id'])) # Create the AdGroup @@ -93,7 +93,7 @@ def main(client, budget_id, merchant_id): ad_group_result = ad_group_service.mutate(adgroup_operations) for adgroup in ad_group_result['value']: - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + print ('AdGroup with name "%s" and ID "%s" was added.' % (adgroup['name'], adgroup['id'])) # Create an AdGroup Ad @@ -115,7 +115,7 @@ def main(client, budget_id, merchant_id): ad_result = ad_group_ad_service.mutate([ad_operation]) for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] if __name__ == '__main__': diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py index a9bb23d4..1931f6c7 100755 --- a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py @@ -229,7 +229,7 @@ def CreateShoppingCampaign(client, budget_id, merchant_id): }] campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name \'%s\' and ID \'%s\' was added.' + print ('Campaign with name "%s" and ID "%s" was added.' % (campaign['name'], campaign['id'])) return campaign diff --git a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py index bd04ea6a..00828814 100755 --- a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py @@ -113,8 +113,8 @@ def main(client, campaign_id, location_feed_id=None): # Display the resulting campaign criteria. for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' + print ('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['criterion']['type'])) diff --git a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py index 0b171549..9d487088 100755 --- a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py @@ -82,7 +82,7 @@ def main(client, ad_group_id): for ad_group_criterion in criteria: criterion = ad_group_criterion['criterion'] print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % + 'type "%s" was added.' % (ad_group_criterion['adGroupId'], criterion['id'], criterion['type'])) else: diff --git a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py index 804a5edb..3bf3412d 100755 --- a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py @@ -36,7 +36,7 @@ def main(client): # Display results. for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' + print ('Language with name "%s" and ID "%s" was found.' % (language['name'], language['id'])) # Get all carriers. @@ -44,7 +44,7 @@ def main(client): # Display results. for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + print ('Carrier with name "%s", ID "%s", and country code "%s" was ' 'found.' % ( carrier['name'], carrier['id'], getattr(carrier, 'countryCode', 'N/A'))) diff --git a/examples/adwords/v201702/targeting/lookup_location.py b/examples/adwords/v201702/targeting/lookup_location.py index dedc5b5c..683a3c2a 100755 --- a/examples/adwords/v201702/targeting/lookup_location.py +++ b/examples/adwords/v201702/targeting/lookup_location.py @@ -64,8 +64,8 @@ def main(client): parent_string = ', '.join([GetLocationString(parent)for parent in location_criterion['location'] ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + print ('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' % (location_criterion['searchTerm'], location_criterion['location']['locationName'], location_criterion['location']['displayType'], parent_string, diff --git a/examples/adwords/v201705/account_management/accept_service_link.py b/examples/adwords/v201705/account_management/accept_service_link.py index 5d2b8de4..1aa603b5 100755 --- a/examples/adwords/v201705/account_management/accept_service_link.py +++ b/examples/adwords/v201705/account_management/accept_service_link.py @@ -50,10 +50,10 @@ def main(client, service_link_id): # Display results. for mutated_service_link in mutated_service_links: - print ('Service link with service link ID \'%s\', type \'%s\' was updated ' - 'to status: \'%s\'.' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) + print ('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) if __name__ == '__main__': diff --git a/examples/adwords/v201705/account_management/create_account.py b/examples/adwords/v201705/account_management/create_account.py index 2c7560e2..9f1392cb 100755 --- a/examples/adwords/v201705/account_management/create_account.py +++ b/examples/adwords/v201705/account_management/create_account.py @@ -53,7 +53,7 @@ def main(client): # Display results. for account in accounts['value']: - print ('Account with customer ID \'%s\' was successfully created.' + print ('Account with customer ID "%s" was successfully created.' % account['customerId']) diff --git a/examples/adwords/v201705/account_management/get_account_changes.py b/examples/adwords/v201705/account_management/get_account_changes.py index fe1dfa94..22ca4637 100755 --- a/examples/adwords/v201705/account_management/get_account_changes.py +++ b/examples/adwords/v201705/account_management/get_account_changes.py @@ -65,7 +65,7 @@ def main(client): print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] if account_changes['changedCampaigns']: for data in account_changes['changedCampaigns']: - print ('Campaign with id \'%s\' has change status \'%s\'.' + print ('Campaign with id "%s" has change status "%s".' % (data['campaignId'], data['campaignChangeStatus'])) if (data['campaignChangeStatus'] != 'NEW' and data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): @@ -77,7 +77,7 @@ def main(client): data['removedCampaignCriteria']) if 'changedAdGroups' in data: for ad_group_data in data['changedAdGroups']: - print (' Ad group with id \'%s\' has change status \'%s\'.' + print (' Ad group with id "%s" has change status "%s".' % (ad_group_data['adGroupId'], ad_group_data['adGroupChangeStatus'])) if ad_group_data['adGroupChangeStatus'] != 'NEW': diff --git a/examples/adwords/v201705/advanced_operations/add_ad_customizer.py b/examples/adwords/v201705/advanced_operations/add_ad_customizer.py index 9d7fec28..bc8718e7 100755 --- a/examples/adwords/v201705/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201705/advanced_operations/add_ad_customizer.py @@ -73,7 +73,7 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): if response and 'value' in response: for ad in response['value']: - print ('Created an ad with ID \'%s\', type \'%s\', and status \'%s\'.' + print ('Created an ad with ID "%s", type "%s", and status "%s".' % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) else: raise errors.GoogleAdsError('No ads were added.') @@ -117,7 +117,7 @@ def CreateCustomizerFeed(client, feed_name): 'priceId': feed['feedAttributes'][1]['id'], 'dateId': feed['feedAttributes'][2]['id'] } - print ('Feed with name \'%s\' and ID %s was added with:\n' + print ('Feed with name "%s" and ID %s was added with:\n' '\tName attribute ID %s and price attribute ID %s and date attribute' 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], feed_data['priceId'], feed_data['dateId']) diff --git a/examples/adwords/v201705/advanced_operations/add_html5_ad.py b/examples/adwords/v201705/advanced_operations/add_html5_ad.py index 011dfc9b..8857c94e 100755 --- a/examples/adwords/v201705/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201705/advanced_operations/add_html5_ad.py @@ -94,7 +94,7 @@ def main(client, ad_group_id): # Display results. for ad in ads['value']: - print ('New HTML5 Ad with id \'%s\' and of display url \'%s\' was added.' + print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' % (ad['ad']['id'], ad['ad']['displayUrl'])) diff --git a/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py index 1a9b9677..9827d33a 100755 --- a/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py @@ -77,7 +77,7 @@ def CreateBiddingStrategy(client): response = bidding_strategy_service.mutate([operation]) new_bidding_strategy = response['value'][0] - print ('Shared bidding strategy with name \'%s\' and ID \'%s\' of type \'%s\'' + print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' 'was created.' % (new_bidding_strategy['name'], new_bidding_strategy['id'], new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) @@ -107,7 +107,7 @@ def CreateSharedBudget(client): 'isExplicitlyShared': 'true' } - # Create operation. + # Create operation. operation = { 'operator': 'ADD', 'operand': budget @@ -157,7 +157,7 @@ def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): response = campaign_service.mutate([operation]) new_campaign = response['value'][0] - print ('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' ' + print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' 'was created.' % (new_campaign['name'], new_campaign['id'], new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) diff --git a/examples/adwords/v201705/basic_operations/add_ad_groups.py b/examples/adwords/v201705/basic_operations/add_ad_groups.py index af65ca0d..5e247208 100755 --- a/examples/adwords/v201705/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201705/basic_operations/add_ad_groups.py @@ -104,7 +104,7 @@ def main(client, campaign_id): # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was added.' + print ('Ad group with name "%s" and id "%s" was added.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201705/basic_operations/add_campaigns.py b/examples/adwords/v201705/basic_operations/add_campaigns.py index b7b3fe8e..6446311b 100755 --- a/examples/adwords/v201705/basic_operations/add_campaigns.py +++ b/examples/adwords/v201705/basic_operations/add_campaigns.py @@ -117,7 +117,7 @@ def main(client): # Display results. for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was added.' + print ('Campaign with name "%s" and id "%s" was added.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201705/basic_operations/add_keywords.py b/examples/adwords/v201705/basic_operations/add_keywords.py index c0cf498b..ab949425 100755 --- a/examples/adwords/v201705/basic_operations/add_keywords.py +++ b/examples/adwords/v201705/basic_operations/add_keywords.py @@ -78,8 +78,8 @@ def main(client, ad_group_id): # Display results. for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id \'%s\', criterion id ' - '\'%s\', text \'%s\', and match type \'%s\' was added.' + print ('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['text'], criterion['criterion']['matchType'])) diff --git a/examples/adwords/v201705/basic_operations/get_ad_groups.py b/examples/adwords/v201705/basic_operations/get_ad_groups.py index c9a96fd8..22561aca 100755 --- a/examples/adwords/v201705/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201705/basic_operations/get_ad_groups.py @@ -59,7 +59,7 @@ def main(client, campaign_id): # Display results. if 'entries' in page: for ad_group in page['entries']: - print ('Ad group with name \'%s\', id \'%s\' and status \'%s\' was ' + print ('Ad group with name "%s", id "%s" and status "%s" was ' 'found.' % (ad_group['name'], ad_group['id'], ad_group['status'])) else: diff --git a/examples/adwords/v201705/basic_operations/get_campaigns.py b/examples/adwords/v201705/basic_operations/get_campaigns.py index d22c960b..63ba8668 100755 --- a/examples/adwords/v201705/basic_operations/get_campaigns.py +++ b/examples/adwords/v201705/basic_operations/get_campaigns.py @@ -58,7 +58,7 @@ def main(client): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + print ('Campaign with id "%s", name "%s", and status "%s" was ' 'found.' % (campaign['id'], campaign['name'], campaign['status'])) else: diff --git a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py index 32eca304..c27da4a5 100755 --- a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py @@ -48,7 +48,7 @@ def main(client): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was ' + print ('Campaign with id "%s", name "%s", and status "%s" was ' 'found.' % (campaign['id'], campaign['name'], campaign['status'])) else: diff --git a/examples/adwords/v201705/basic_operations/get_keywords.py b/examples/adwords/v201705/basic_operations/get_keywords.py index c986061e..4e1a3b80 100755 --- a/examples/adwords/v201705/basic_operations/get_keywords.py +++ b/examples/adwords/v201705/basic_operations/get_keywords.py @@ -67,8 +67,8 @@ def main(client, adgroup_id): # Display results. if 'entries' in page: for keyword in page['entries']: - print ('Keyword ID \'%d\', type \'%s\', text \'%s\', and match type ' - '\'%s\' was found.' % ( + print ('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( keyword['criterion']['id'], keyword['criterion']['type'], keyword['criterion']['text'], diff --git a/examples/adwords/v201705/basic_operations/get_text_ads.py b/examples/adwords/v201705/basic_operations/get_text_ads.py deleted file mode 100755 index 0cb5a31f..00000000 --- a/examples/adwords/v201705/basic_operations/get_text_ads.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 text ads for a given ad group. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id \'%s\', status \'%s\', and of type \'%s\' was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/pause_ad.py b/examples/adwords/v201705/basic_operations/pause_ad.py index 979be365..7ccbb9ab 100755 --- a/examples/adwords/v201705/basic_operations/pause_ad.py +++ b/examples/adwords/v201705/basic_operations/pause_ad.py @@ -51,7 +51,7 @@ def main(client, ad_group_id, ad_id): # Display results. for ad in ads['value']: - print 'Ad with id \'%s\' was updated.'% ad['ad']['id'] + print 'Ad with id "%s" was updated.'% ad['ad']['id'] if __name__ == '__main__': diff --git a/examples/adwords/v201705/basic_operations/remove_ad.py b/examples/adwords/v201705/basic_operations/remove_ad.py index 49db1522..b03e4a83 100755 --- a/examples/adwords/v201705/basic_operations/remove_ad.py +++ b/examples/adwords/v201705/basic_operations/remove_ad.py @@ -16,7 +16,7 @@ """This example deletes an ad using the 'REMOVE' operator. -To get ads, run get_text_ads.py. +To get ads, run get_expanded_text_ads.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -51,7 +51,7 @@ def main(client, ad_group_id, ad_id): # Display results. for ad in result['value']: - print ('Ad with id \'%s\' and type \'%s\' was deleted.' + print ('Ad with id "%s" and type "%s" was deleted.' % (ad['ad']['id'], ad['ad']['Ad.Type'])) diff --git a/examples/adwords/v201705/basic_operations/remove_ad_group.py b/examples/adwords/v201705/basic_operations/remove_ad_group.py index 2426cddf..b5b1933c 100755 --- a/examples/adwords/v201705/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201705/basic_operations/remove_ad_group.py @@ -47,7 +47,7 @@ def main(client, ad_group_id): # Display results. for ad_group in result['value']: - print ('Ad group with name \'%s\' and id \'%s\' was deleted.' + print ('Ad group with name "%s" and id "%s" was deleted.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201705/basic_operations/remove_campaign.py b/examples/adwords/v201705/basic_operations/remove_campaign.py index 672e6611..a87f0af7 100755 --- a/examples/adwords/v201705/basic_operations/remove_campaign.py +++ b/examples/adwords/v201705/basic_operations/remove_campaign.py @@ -47,7 +47,7 @@ def main(client, campaign_id): # Display results. for campaign in result['value']: - print ('Campaign with name \'%s\' and id \'%s\' was deleted.' + print ('Campaign with name "%s" and id "%s" was deleted.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201705/basic_operations/remove_keyword.py b/examples/adwords/v201705/basic_operations/remove_keyword.py index 5229e03b..e8e35f55 100755 --- a/examples/adwords/v201705/basic_operations/remove_keyword.py +++ b/examples/adwords/v201705/basic_operations/remove_keyword.py @@ -54,8 +54,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for criterion in result['value']: - print ('Ad group criterion with ad group id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was deleted.' + print ('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['Criterion.Type'])) diff --git a/examples/adwords/v201705/basic_operations/update_ad_group.py b/examples/adwords/v201705/basic_operations/update_ad_group.py index 8548597e..4a38afd0 100755 --- a/examples/adwords/v201705/basic_operations/update_ad_group.py +++ b/examples/adwords/v201705/basic_operations/update_ad_group.py @@ -47,7 +47,7 @@ def main(client, ad_group_id): # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name \'%s\' and id \'%s\' was updated.' + print ('Ad group with name "%s" and id "%s" was updated.' % (ad_group['name'], ad_group['id'])) diff --git a/examples/adwords/v201705/basic_operations/update_campaign.py b/examples/adwords/v201705/basic_operations/update_campaign.py index cee1f881..75696f9a 100755 --- a/examples/adwords/v201705/basic_operations/update_campaign.py +++ b/examples/adwords/v201705/basic_operations/update_campaign.py @@ -47,7 +47,7 @@ def main(client, campaign_id): # Display results. for campaign in campaigns['value']: - print ('Campaign with name \'%s\' and id \'%s\' was updated.' + print ('Campaign with name "%s" and id "%s" was updated.' % (campaign['name'], campaign['id'])) diff --git a/examples/adwords/v201705/basic_operations/update_keyword.py b/examples/adwords/v201705/basic_operations/update_keyword.py index 965c7190..8e72498e 100755 --- a/examples/adwords/v201705/basic_operations/update_keyword.py +++ b/examples/adwords/v201705/basic_operations/update_keyword.py @@ -65,12 +65,12 @@ def main(client, ad_group_id, criterion_id): if 'value' in ad_group_criteria: for criterion in ad_group_criteria['value']: if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id \'%s\' and criterion id ' - '\'%s\' currently has bids:' + print ('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' % (criterion['adGroupId'], criterion['criterion']['id'])) for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: \'%s\', value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) + print '\tType: "%s", value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) else: print 'No ad group criteria were updated.' diff --git a/examples/adwords/v201705/campaign_management/add_campaign_labels.py b/examples/adwords/v201705/campaign_management/add_campaign_labels.py index f27724d5..1aa8deee 100755 --- a/examples/adwords/v201705/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201705/campaign_management/add_campaign_labels.py @@ -56,7 +56,7 @@ def main(client, campaign_id1, campaign_id2, label_id): # Display results. for label in result['value']: - print ('CampaignLabel with campaignId \'%s\' and labelId \'%s\' was added.' + print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' % (label['campaignId'], label['labelId'])) diff --git a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py index 49283b24..651a882e 100755 --- a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py @@ -45,6 +45,11 @@ def main(client, ad_group_id): 'field': 'AdGroupId', 'operator': 'EQUALS', 'values': [ad_group_id] + }, + { + 'field': 'CombinedApprovalStatus', + 'operator': 'EQUALS', + 'values': 'DISAPPROVED' } ], 'paging': { @@ -62,14 +67,10 @@ def main(client, ad_group_id): if 'entries' in page: for ad in page['entries']: - policy_summary = ad['policySummary'] - - if policy_summary['combinedApprovalStatus'] != 'DISAPPROVED': - continue # Skip ads that are not disapproved. - disapproved_count += 1 + policy_summary = ad['policySummary'] - print ('Ad with id \'%s\' was disapproved with the following policy ' + print ('Ad with id "%s" was disapproved with the following policy ' 'topic entries:' % (ad['ad']['id'])) for policy_topic_entry in policy_summary['policyTopicEntries']: diff --git a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py index a1875525..ca889dae 100755 --- a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py @@ -34,11 +34,12 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') + ad_group_ad_service = client.GetService('AdGroupAdService', + version='v201705') # Construct query and get all ads for a given campaign. query = ('SELECT Id, PolicySummary ' - 'WHERE AdGroupId = %s ' + 'WHERE AdGroupId = %s AND CombinedApprovalStatus = DISAPPROVED ' 'ORDER BY Id' % ad_group_id) more_pages = True disapproved_count = 0 @@ -51,14 +52,10 @@ def main(client, ad_group_id): if 'entries' in page: for ad in page['entries']: - policy_summary = ad['policySummary'] - - if policy_summary['combinedApprovalStatus'] != 'DISAPPROVED': - continue # Skip ads that are not disapproved. - disapproved_count += 1 + policy_summary = ad['policySummary'] - print ('Ad with id \'%s\' was disapproved with the following policy ' + print ('Ad with id "%s" was disapproved with the following policy ' 'topic entries:' % (ad['ad']['id'])) for policy_topic_entry in policy_summary['policyTopicEntries']: diff --git a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py index 512e24fc..cd405d56 100755 --- a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py @@ -67,7 +67,7 @@ def main(client, label_id): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign found with Id \'%s\', name \'%s\', and labels: %s' + print ('Campaign found with Id "%s", name "%s", and labels: %s' % (campaign['id'], campaign['name'], campaign['labels'])) else: print 'No campaigns were found.' diff --git a/examples/adwords/v201705/campaign_management/set_ad_parameters.py b/examples/adwords/v201705/campaign_management/set_ad_parameters.py index 59bcda45..5b1857af 100755 --- a/examples/adwords/v201705/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201705/campaign_management/set_ad_parameters.py @@ -59,8 +59,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for ad in ads: - print ('Text ad with id \'%s\' was successfully added to an ad group with ' - 'id \'%s\'.' % (ad['adGroupId'], ad['ad']['id'])) + print ('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) # Construct operations for setting ad parameters. operations = [ @@ -87,8 +87,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for ad_param in ad_params: - print ('Ad parameter with text \'%s\' was successfully set for criterion ' - 'with id \'%s\' and ad group id \'%s\'.' + print ('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' % (ad_param['insertionText'], ad_param['criterionId'], ad_param['adGroupId'])) diff --git a/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py index bfdbe8b8..f2242439 100755 --- a/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py @@ -63,8 +63,8 @@ def main(client, campaign_id, bid_modifier): # Display the resulting campaign criteria. for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\' and criterion id \'%s\' ' - 'was updated with bid modifier \'%s\'.' + print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['bidModifier'])) diff --git a/examples/adwords/v201705/campaign_management/validate_text_ad.py b/examples/adwords/v201705/campaign_management/validate_text_ad.py index f10b200d..ee011c84 100755 --- a/examples/adwords/v201705/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201705/campaign_management/validate_text_ad.py @@ -74,7 +74,7 @@ def main(client, ad_group_id): try: ad_group_ad_service.mutate(operations) except suds.WebFault, e: - print 'Validation correctly failed with \'%s\'.' % str(e) + print 'Validation correctly failed with "%s".' % str(e) if __name__ == '__main__': diff --git a/examples/adwords/v201705/error_handling/handle_partial_failures.py b/examples/adwords/v201705/error_handling/handle_partial_failures.py index df78f623..34f215ae 100755 --- a/examples/adwords/v201705/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201705/error_handling/handle_partial_failures.py @@ -93,8 +93,8 @@ def main(client, ad_group_id): # Display results. for criterion in result['value']: if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id \'%s\', ' - 'criterion id \'%s\', text \'%s\', and match type \'%s\' was ' + print ('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' 'added.' % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['text'], diff --git a/examples/adwords/v201705/error_handling/handle_policy_violation_error.py b/examples/adwords/v201705/error_handling/handle_policy_violation_error.py index 257ea52c..2ed702db 100755 --- a/examples/adwords/v201705/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201705/error_handling/handle_policy_violation_error.py @@ -119,7 +119,7 @@ def main(client, ad_group_id): ads = response['value'] print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) for ad in ads: - print (' Ad id is %s, type is %s and status is \'%s\'.' % + print (' Ad id is %s, type is %s and status is "%s".' % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) else: print 'No ads were added.' @@ -151,7 +151,7 @@ def HandleAPIError(error, operation): if is_exemptable: # Add exemption request to the operation. - print ('Adding exemption request for policy name \'%s\' on text \'%s\'.' + print ('Adding exemption request for policy name "%s" on text "%s".' % (error['key']['policyName'], error['key']['violatingText'])) if 'exemptionRequests' not in operation: operation['exemptionRequests'] = [] diff --git a/examples/adwords/v201705/extensions/add_site_links_using_feeds.py b/examples/adwords/v201705/extensions/add_site_links_using_feeds.py index ecbf0bd2..a645e66a 100755 --- a/examples/adwords/v201705/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201705/extensions/add_site_links_using_feeds.py @@ -76,11 +76,11 @@ def main(client, campaign_id): final_url_feed_attribute_id = feed['attributes'][1]['id'] line_2_feed_attribute_id = feed['attributes'][2]['id'] line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name \'%s\' and ID \'%s\' was added with' % + print ('Feed with name "%s" and ID "%s" was added with' % (feed['name'], feed['id'])) - print ('\tText attribute ID \'%s\' and Final URL attribute ID \'%s\'.' % + print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID \'%s\' and Line 3 attribute ID \'%s\'.' % + print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % (line_2_feed_attribute_id, line_3_feed_attribute_id)) sitelinks_data['feedId'] = feed['id'] sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id diff --git a/examples/adwords/v201705/misc/get_all_images_and_videos.py b/examples/adwords/v201705/misc/get_all_images_and_videos.py index df28bf8a..7e72ffcd 100755 --- a/examples/adwords/v201705/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201705/misc/get_all_images_and_videos.py @@ -63,14 +63,14 @@ def main(client): except AttributeError: dimensions = {'FULL': {'height': 0, 'width': 0}} if image['type'] == 'IMAGE': - print ('%s with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\'' + print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' ' was found.' % (image['type'], image['mediaId'], dimensions['FULL']['height'], dimensions['FULL']['width'], image['mimeType'])) elif image['type'] == 'VIDEO': - print ('%s with id \'%s\' was found.' % (image['type'], - image['mediaId'])) + print ('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) else: print 'No images/videos were found.' offset += PAGE_SIZE diff --git a/examples/adwords/v201705/misc/upload_image.py b/examples/adwords/v201705/misc/upload_image.py index ff41c3f4..3895aeb0 100755 --- a/examples/adwords/v201705/misc/upload_image.py +++ b/examples/adwords/v201705/misc/upload_image.py @@ -52,7 +52,7 @@ def main(client, image_filename): if media: dimensions = dict([(entry['key'], entry['value']) for entry in media['dimensions']]) - print ('Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was' + print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], dimensions['FULL']['width'], media['mimeType'])) else: diff --git a/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py index 008ed46b..8649c9de 100755 --- a/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py @@ -59,8 +59,8 @@ def main(client, ad_group_id, criterion_id): if 'entries' in bid_landscapes: for bid_landscape in bid_landscapes['entries']: if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id \'%s\', criterion id ' - '\'%s\', start date \'%s\', end date \'%s\', with landscape ' + print ('Criterion bid landscape with ad group id "%s", criterion id ' + '"%s", start date "%s", end date "%s", with landscape ' 'points was found:' % (bid_landscape['adGroupId'], bid_landscape['criterionId'], bid_landscape['startDate'], bid_landscape['endDate'])) diff --git a/examples/adwords/v201705/optimization/get_keyword_ideas.py b/examples/adwords/v201705/optimization/get_keyword_ideas.py index f79fab9d..fb8c12a1 100755 --- a/examples/adwords/v201705/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201705/optimization/get_keyword_ideas.py @@ -80,8 +80,8 @@ def main(client): for attribute in result['data']: attributes[attribute['key']] = getattr(attribute['value'], 'value', '0') - print ('Keyword with \'%s\' text and average monthly search volume ' - '\'%s\' was found with Products and Services categories: %s.' + print ('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' % (attributes['KEYWORD_TEXT'], attributes['SEARCH_VOLUME'], attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) diff --git a/examples/adwords/v201705/remarketing/add_audience.py b/examples/adwords/v201705/remarketing/add_audience.py index 3874b42c..35ca1007 100755 --- a/examples/adwords/v201705/remarketing/add_audience.py +++ b/examples/adwords/v201705/remarketing/add_audience.py @@ -85,7 +85,7 @@ def main(client): conversions_map[conversion_tracker['id']] = conversion_tracker for user_list in result['value']: - print ('User list with name \'%s\' and ID \'%s\' was added.' + print ('User list with name "%s" and ID "%s" was added.' % (user_list['name'], user_list['id'])) if user_list['conversionTypes']: for conversion_type in user_list['conversionTypes']: diff --git a/examples/adwords/v201705/remarketing/add_conversion_tracker.py b/examples/adwords/v201705/remarketing/add_conversion_tracker.py index 039b3932..94a5aa11 100755 --- a/examples/adwords/v201705/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201705/remarketing/add_conversion_tracker.py @@ -56,8 +56,8 @@ def main(client): # Display results. for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id \'%s\', name \'%s\', status \'%s\' ' - 'and category \'%s\' and snippet \n\'%s\'\n was added.\n' % + print ('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.\n' % (conversion_tracker['id'], conversion_tracker['name'], conversion_tracker['status'], conversion_tracker['category'], conversion_tracker['snippet'])) diff --git a/examples/adwords/v201705/remarketing/upload_offline_conversions.py b/examples/adwords/v201705/remarketing/upload_offline_conversions.py index 3e67a371..79c99fa7 100755 --- a/examples/adwords/v201705/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201705/remarketing/upload_offline_conversions.py @@ -61,10 +61,10 @@ def main(client, conversion_name, click_id, conversion_time, conversion_value): [offline_conversion_operation]) new_feed = offline_conversion_response['value'] - print ('Uploaded offline conversion value of \'%s\' for Google Click ID ' - '\'%s\' to \'%s\'.' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) + print ('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) if __name__ == '__main__': diff --git a/examples/adwords/v201705/reporting/get_report_fields.py b/examples/adwords/v201705/reporting/get_report_fields.py index ce5839ac..b93d0518 100755 --- a/examples/adwords/v201705/reporting/get_report_fields.py +++ b/examples/adwords/v201705/reporting/get_report_fields.py @@ -38,7 +38,7 @@ def main(client, report_type): fields = report_definition_service.getReportFields(report_type) # Display results. - print 'Report type \'%s\' contains the following fields:' % report_type + print 'Report type "%s" contains the following fields:' % report_type for field in fields: print ' - %s (%s)' % (field['fieldName'], field['fieldType']) if 'enumValues' in field: diff --git a/examples/adwords/v201705/shopping/add_shopping_campaign.py b/examples/adwords/v201705/shopping/add_shopping_campaign.py index cbebb1ae..d3539331 100755 --- a/examples/adwords/v201705/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201705/shopping/add_shopping_campaign.py @@ -79,7 +79,7 @@ def main(client, budget_id, merchant_id, create_default_partition): result = campaign_service.mutate(campaign_operations) for campaign in result['value']: - print ('Campaign with name \'%s\' and ID \'%s\' was added.' + print ('Campaign with name "%s" and ID "%s" was added.' % (campaign['name'], campaign['id'])) # Create the AdGroup @@ -97,7 +97,7 @@ def main(client, budget_id, merchant_id, create_default_partition): ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] ad_group_id = ad_group['id'] - print ('AdGroup with name \'%s\' and ID \'%s\' was added.' + print ('AdGroup with name "%s" and ID "%s" was added.' % (ad_group['name'], ad_group_id)) # Create an AdGroup Ad @@ -119,7 +119,7 @@ def main(client, budget_id, merchant_id, create_default_partition): ad_result = ad_group_ad_service.mutate([ad_operation]) for adgroup_ad in ad_result['value']: - print 'ProductAd with ID \'%s\' was added.' % adgroup_ad['ad']['id'] + print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] if create_default_partition: CreateDefaultPartition(client, ad_group_id) diff --git a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py index 9e1f8790..e8175611 100755 --- a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py @@ -231,7 +231,7 @@ def CreateShoppingCampaign(client, budget_id, merchant_id): }] campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name \'%s\' and ID \'%s\' was added.' + print ('Campaign with name "%s" and ID "%s" was added.' % (campaign['name'], campaign['id'])) return campaign diff --git a/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py index 15dd21c1..df684e8b 100755 --- a/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py @@ -113,8 +113,8 @@ def main(client, campaign_id, location_feed_id=None): # Display the resulting campaign criteria. for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id \'%s\', criterion id \'%s\', ' - 'and type \'%s\' was added.' + print ('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['criterion']['type'])) diff --git a/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py index c175a2f1..83db7f2a 100755 --- a/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py @@ -82,7 +82,7 @@ def main(client, ad_group_id): for ad_group_criterion in criteria: criterion = ad_group_criterion['criterion'] print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type \'%s\' was added.' % + 'type "%s" was added.' % (ad_group_criterion['adGroupId'], criterion['id'], criterion['type'])) else: diff --git a/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py index 221e8f63..9e782b93 100755 --- a/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py @@ -36,7 +36,7 @@ def main(client): # Display results. for language in languages: - print ('Language with name \'%s\' and ID \'%s\' was found.' + print ('Language with name "%s" and ID "%s" was found.' % (language['name'], language['id'])) # Get all carriers. @@ -44,7 +44,7 @@ def main(client): # Display results. for carrier in carriers: - print ('Carrier with name \'%s\', ID \'%s\', and country code \'%s\' was ' + print ('Carrier with name "%s", ID "%s", and country code "%s" was ' 'found.' % ( carrier['name'], carrier['id'], getattr(carrier, 'countryCode', 'N/A'))) diff --git a/examples/adwords/v201705/targeting/lookup_location.py b/examples/adwords/v201705/targeting/lookup_location.py index 75bbf1c2..aca2b820 100755 --- a/examples/adwords/v201705/targeting/lookup_location.py +++ b/examples/adwords/v201705/targeting/lookup_location.py @@ -64,8 +64,8 @@ def main(client): parent_string = ', '.join([GetLocationString(parent)for parent in location_criterion['location'] ['parentLocations']]) - print ('The search term \'%s\' returned the location \'%s\' of type \'%s\'' - ' with parent locations \'%s\', reach \'%s\' and id \'%s\' (%s)' + print ('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' % (location_criterion['searchTerm'], location_criterion['location']['locationName'], location_criterion['location']['displayType'], parent_string, diff --git a/examples/dfp/authentication/create_dfp_client_with_access_token.py b/examples/dfp/authentication/create_dfp_client_with_access_token.py new file mode 100755 index 00000000..e24690c9 --- /dev/null +++ b/examples/dfp/authentication/create_dfp_client_with_access_token.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Initializes an DfpClient using GoogleAccessTokenClient. + +Note that unlike clients initialized with GoogleRefreshTokenClient, those +initialized with GoogleAccessTokenClient can't refresh. +""" + +import argparse +import datetime +from googleads import dfp +from googleads import oauth2 +import httplib2 +from oauth2client import client + + +GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token' +USER_AGENT = 'INSERT_USER_AGENT_HERE' + +# OAuth2 credential information. +DEFAULT_CLIENT_ID = 'INSERT_CLIENT_ID_HERE' +DEFAULT_CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' +DEFAULT_REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE' + +# DFP API information. +DEFAULT_APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE' + +parser = argparse.ArgumentParser( + description=('Creates an DfpClient using a GoogleAccessToken with an ' + 'access token generated with the given credentials.')) +parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID, + help='Client Id retrieved from the Developer\'s Console.') +parser.add_argument('--client_secret', default=DEFAULT_CLIENT_SECRET, + help='Client Secret retrieved from the Developer\'s ' + 'Console.') +parser.add_argument('--refresh_token', default=DEFAULT_REFRESH_TOKEN, + help='The refresh token used to generate an access token.') +parser.add_argument('--application_name', default=DEFAULT_APPLICATION_NAME, + help='The application name for your DFP account.') + + +def main(access_token, token_expiry, application_name): + oauth2_client = oauth2.GoogleAccessTokenClient(access_token, token_expiry) + + dfp_client = dfp.DfpClient(oauth2_client, application_name) + + networks = dfp_client.GetService('NetworkService').getAllNetworks() + for network in networks: + print ('Network with network code "%s" and display name "%s" was found.' + % (network['networkCode'], network['displayName'])) + + +if __name__ == '__main__': + args = parser.parse_args() + + # Retrieve a new access token for use in this example. In a production + # application, you may use a credential store to share access tokens for a + # given user across applications. + oauth2credentials = client.OAuth2Credentials( + None, args.client_id, args.client_secret, args.refresh_token, + datetime.datetime(1980, 1, 1, 12), GOOGLE_OAUTH2_ENDPOINT, + USER_AGENT) + + oauth2credentials.refresh(httplib2.Http()) + + main(oauth2credentials.access_token, oauth2credentials.token_expiry, + args.application_name) diff --git a/examples/dfp/authentication/create_dfp_client_without_yaml.py b/examples/dfp/authentication/create_dfp_client_with_refresh_token.py similarity index 95% rename from examples/dfp/authentication/create_dfp_client_without_yaml.py rename to examples/dfp/authentication/create_dfp_client_with_refresh_token.py index f857f9bc..3024040b 100755 --- a/examples/dfp/authentication/create_dfp_client_without_yaml.py +++ b/examples/dfp/authentication/create_dfp_client_with_refresh_token.py @@ -44,7 +44,7 @@ def main(client_id, client_secret, refresh_token, application_name): networks = dfp_client.GetService('NetworkService').getAllNetworks() for network in networks: - print ('Network with network code \'%s\' and display name \'%s\' was found.' + print ('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/dfp/authentication/create_dfp_client_with_service_account.py index 11f0462b..8b152927 100755 --- a/examples/dfp/authentication/create_dfp_client_with_service_account.py +++ b/examples/dfp/authentication/create_dfp_client_with_service_account.py @@ -37,7 +37,7 @@ def main(service_account_email, key_file, application_name): networks = dfp_client.GetService('NetworkService').getAllNetworks() for network in networks: - print ('Network with network code \'%s\' and display name \'%s\' was found.' + print ('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) diff --git a/examples/dfp/v201611/activity_group_service/create_activity_groups.py b/examples/dfp/v201611/activity_group_service/create_activity_groups.py index 521c3614..b3b69d40 100755 --- a/examples/dfp/v201611/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/create_activity_groups.py @@ -62,7 +62,7 @@ def main(client, advertiser_company_id): # Display results. for activity_group in activity_groups: - print ('Activity group with ID \'%s\' and name \'%s\' was created.' + print ('Activity group with ID "%s" and name "%s" was created.' % (activity_group['id'], activity_group['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/activity_group_service/update_activity_groups.py b/examples/dfp/v201611/activity_group_service/update_activity_groups.py index 16f81c5d..fcd31d25 100755 --- a/examples/dfp/v201611/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/update_activity_groups.py @@ -65,7 +65,7 @@ def main(client, activity_group_id, advertiser_company_id): updated_activity_groups) for activity_group in activity_groups: - print (('Activity group with ID \'%s\' and name \'%s\' was updated.') + print (('Activity group with ID "%s" and name "%s" was updated.') % (activity_group['id'], activity_group['name'])) else: print 'No activity groups found to update.' diff --git a/examples/dfp/v201611/activity_service/create_activities.py b/examples/dfp/v201611/activity_service/create_activities.py index 539b3284..5d88d43c 100755 --- a/examples/dfp/v201611/activity_service/create_activities.py +++ b/examples/dfp/v201611/activity_service/create_activities.py @@ -59,7 +59,7 @@ def main(client, activity_group_id): # Display results. for activity in activities: - print ('An activity with ID \'%s\', name \'%s\', and type \'%s\' was ' + print ('An activity with ID "%s", name "%s", and type "%s" was ' 'created.' % (activity['id'], activity['name'], activity['type'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/activity_service/update_activities.py b/examples/dfp/v201611/activity_service/update_activities.py index e29e25da..dbcaecf8 100755 --- a/examples/dfp/v201611/activity_service/update_activities.py +++ b/examples/dfp/v201611/activity_service/update_activities.py @@ -61,7 +61,7 @@ def main(client, activity_id): activities = activity_service.updateActivities(updated_activities) for updated_activity in activities: - print (('Activity with ID \'%s\' and name \'%s\' was updated.') + print (('Activity with ID "%s" and name "%s" was updated.') % (updated_activity['id'], updated_activity['name'])) else: print 'No activities found to update.' diff --git a/examples/dfp/v201611/audience_segment_service/create_audience_segments.py b/examples/dfp/v201611/audience_segment_service/create_audience_segments.py index a6e0761b..1cd66b3c 100755 --- a/examples/dfp/v201611/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/create_audience_segments.py @@ -84,7 +84,7 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): audience_segment_service.createAudienceSegments(audience_segment)) for created_audience_segment in audience_segments: - print ('An audience segment with ID \'%s\', name \'%s\', and type \'%s\' ' + print ('An audience segment with ID "%s", name "%s", and type "%s" ' 'was created.' % (created_audience_segment['id'], created_audience_segment['name'], created_audience_segment['type'])) diff --git a/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py index c4056096..2573fcd5 100755 --- a/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py @@ -57,7 +57,7 @@ def main(client, audience_segment_id): for segment in segments: print ( - 'Audience segment with id \'%s\' and name \'%s\' will be populated.' + 'Audience segment with id "%s" and name "%s" will be populated.' % (segment['id'], segment['name'])) action = { diff --git a/examples/dfp/v201611/audience_segment_service/update_audience_segments.py b/examples/dfp/v201611/audience_segment_service/update_audience_segments.py index af75ab18..d358095f 100755 --- a/examples/dfp/v201611/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/update_audience_segments.py @@ -55,7 +55,7 @@ def main(client, audience_segment_id): if 'results' in response: updated_audience_segments = [] for audience_segment in response['results']: - print ('Audience segment with id \'%s\' and name \'%s\' will be updated.' + print ('Audience segment with id "%s" and name "%s" will be updated.' % (audience_segment['id'], audience_segment['name'])) audience_segment['membershipExpirationDays'] = '180' @@ -65,7 +65,7 @@ def main(client, audience_segment_id): updated_audience_segments) for audience_segment in audience_segments: - print ('Audience segment with id \'%s\' and name \'%s\' was updated' % + print ('Audience segment with id "%s" and name "%s" was updated' % (audience_segment['id'], audience_segment['name'])) else: print 'No audience segment found to update.' diff --git a/examples/dfp/v201611/base_rate_service/create_product_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_base_rates.py index 35207890..3a97e258 100755 --- a/examples/dfp/v201611/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/create_product_base_rates.py @@ -51,7 +51,7 @@ def main(client, product_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product base rate with ID \'%s\' and rate \'%.2f\' %s was ' + print ('A product base rate with ID "%s" and rate \'%.2f\' %s was ' 'created.' % (base_rate['id'], base_rate['rate']['microAmount'], base_rate['rate']['currencyCode'])) diff --git a/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py index 61556bbb..a8d974ab 100755 --- a/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py @@ -51,7 +51,7 @@ def main(client, product_template_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product template base rate with ID \'%s\' and rate \'%.2f\' %s' + print ('A product template base rate with ID "%s" and rate \'%.2f\' %s' ' was created.' % (base_rate['id'], base_rate['rate']['microAmount'], base_rate['rate']['currencyCode'])) diff --git a/examples/dfp/v201611/base_rate_service/update_base_rates.py b/examples/dfp/v201611/base_rate_service/update_base_rates.py index e2ac2cff..9f287260 100755 --- a/examples/dfp/v201611/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/update_base_rates.py @@ -64,8 +64,8 @@ def main(client, base_rate_id): # Display results. if base_rates: for base_rate in base_rates: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was updated.' % ( + print ('Base rate with ID "%s" and type "%s" belonging to ' + 'rate card ID "%s" was updated.' % ( base_rate['id'], dfp.DfpClassType(base_rate), base_rate['rateCardId'])) diff --git a/examples/dfp/v201611/company_service/create_companies.py b/examples/dfp/v201611/company_service/create_companies.py index 7acb193d..1f461e28 100755 --- a/examples/dfp/v201611/company_service/create_companies.py +++ b/examples/dfp/v201611/company_service/create_companies.py @@ -53,7 +53,7 @@ def main(client): # Display results. for company in companies: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.' + print ('Company with ID "%s", name "%s", and type "%s" was created.' % (company['id'], company['name'], company['type'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/company_service/update_companies.py b/examples/dfp/v201611/company_service/update_companies.py index 774966df..09b656fb 100755 --- a/examples/dfp/v201611/company_service/update_companies.py +++ b/examples/dfp/v201611/company_service/update_companies.py @@ -62,7 +62,7 @@ def main(client, company_id): # Display results. for company in companies: - print (('Company with ID \'%s\', name \'%s\', and comment \'%s\'' + print (('Company with ID "%s", name "%s", and comment "%s"' 'was updated.') % (company['id'], company['name'], company['comment'])) else: diff --git a/examples/dfp/v201611/contact_service/create_contacts.py b/examples/dfp/v201611/contact_service/create_contacts.py index 3240fdd5..7494c277 100755 --- a/examples/dfp/v201611/contact_service/create_contacts.py +++ b/examples/dfp/v201611/contact_service/create_contacts.py @@ -62,7 +62,7 @@ def main(client, advertiser_company_id, agency_company_id): # Display results. for contact in contacts: - print ('Contact with ID \'%s\' name \'%s\' was created.' + print ('Contact with ID "%s" name "%s" was created.' % (contact['id'], contact['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/contact_service/update_contacts.py b/examples/dfp/v201611/contact_service/update_contacts.py index c2f5f4ad..a50efb09 100755 --- a/examples/dfp/v201611/contact_service/update_contacts.py +++ b/examples/dfp/v201611/contact_service/update_contacts.py @@ -63,7 +63,7 @@ def main(client, contact_id): # Display results. for contact in contacts: - print (('Contact with ID \'%s\', name \'%s\', and address \'%s\' ' + print (('Contact with ID "%s", name "%s", and address "%s" ' 'was updated.') % (contact['id'], contact['name'], contact['address'])) else: diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index f272dd75..a4083936 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -68,7 +68,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Display results. for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id \'%s\' and name \'%s\'' + print ('Content metadata key hierarchy with id "%s" and name "%s"' ' was created.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 8bcc1134..cf56c087 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -64,7 +64,7 @@ def main(client, content_metadata_key_hierarchy_id): # Display results. if content_metadata_key_hierarchies: for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with ID \'%s\' and name \'%s\' ' + print ('Content metadata key hierarchy with ID "%s" and name "%s" ' 'will be deleted.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 26cb8769..d34e26c0 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -83,7 +83,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Display results. for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id \'%s\' and name \'%s\'' + print ('Content metadata key hierarchy with id "%s" and name "%s"' ' was updated.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201611/creative_service/create_creative_from_template.py b/examples/dfp/v201611/creative_service/create_creative_from_template.py index 6be13e5a..d97dff5e 100755 --- a/examples/dfp/v201611/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201611/creative_service/create_creative_from_template.py @@ -102,7 +102,7 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201611/creative_service/create_creatives.py b/examples/dfp/v201611/creative_service/create_creatives.py index f08ae12b..ff4ee4c1 100755 --- a/examples/dfp/v201611/creative_service/create_creatives.py +++ b/examples/dfp/v201611/creative_service/create_creatives.py @@ -80,7 +80,7 @@ def main(client, advertiser_id): # Display results. for creative in creatives: - print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Image creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201611/creative_service/create_custom_creative.py b/examples/dfp/v201611/creative_service/create_custom_creative.py index 1e49b3ec..145e0411 100755 --- a/examples/dfp/v201611/creative_service/create_custom_creative.py +++ b/examples/dfp/v201611/creative_service/create_custom_creative.py @@ -49,7 +49,7 @@ def main(client, advertiser_id): image_data = base64.encodestring(image_data) # Create the HTML snippet used in the custom creative. - html_snippet = ('
Click above for ' + html_snippet = ('
Click above for ' 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%', '%%FILE:IMAGE_ASSET%%') @@ -79,7 +79,7 @@ def main(client, advertiser_id): # Display results. if creatives: creative = creatives[0] - print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201611/creative_service/create_native_creative.py b/examples/dfp/v201611/creative_service/create_native_creative.py index 29f6c7c3..cc31907f 100755 --- a/examples/dfp/v201611/creative_service/create_native_creative.py +++ b/examples/dfp/v201611/creative_service/create_native_creative.py @@ -125,7 +125,7 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Native creative with id \'%s\' and name \'%s\' was ' + print ('Native creative with id "%s" and name "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], creative['previewUrl'])) diff --git a/examples/dfp/v201611/creative_service/update_creatives.py b/examples/dfp/v201611/creative_service/update_creatives.py index aa982eaa..69e8330e 100755 --- a/examples/dfp/v201611/creative_service/update_creatives.py +++ b/examples/dfp/v201611/creative_service/update_creatives.py @@ -69,7 +69,7 @@ def main(client, image_creative_id): # Display results. for creative in creatives: - print ('Image creative with id \'%s\' and destination URL \'%s\' was ' + print ('Image creative with id "%s" and destination URL "%s" was ' 'updated.' % (creative['id'], creative['destinationUrl'])) else: print 'No creatives found to update.' diff --git a/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py index f88a402d..d3961e66 100755 --- a/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py @@ -46,7 +46,7 @@ def main(client, creative_set_id, line_item_id): lica = lica_service.createLineItemCreativeAssociations([lica]) # Display results. - print (('LICA with line item ID \'%s\' and creative set ID \'%s\' was ' + print (('LICA with line item ID "%s" and creative set ID "%s" was ' 'created.') % (lica['lineItemId'], lica['creativeSetId'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/creative_set_service/create_creative_set.py b/examples/dfp/v201611/creative_set_service/create_creative_set.py index dcacbebb..2545bfbc 100755 --- a/examples/dfp/v201611/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201611/creative_set_service/create_creative_set.py @@ -50,7 +50,7 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' + print (('Creative set with ID "%s", master creative ID "%s", and ' 'companion creative IDs {%s} was created.') % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) diff --git a/examples/dfp/v201611/creative_set_service/update_creative_set.py b/examples/dfp/v201611/creative_set_service/update_creative_set.py index 06593b9e..049d6dfd 100755 --- a/examples/dfp/v201611/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201611/creative_set_service/update_creative_set.py @@ -65,7 +65,7 @@ def main(client, creative_set_id, companion_creative_id): # Display results. for creative_set in creative_sets: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' + print (('Creative set with ID "%s", master creative ID "%s", and ' 'companion creative IDs {%s} was updated.') % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) diff --git a/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py index 8ca0984b..34fed979 100755 --- a/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py @@ -54,7 +54,7 @@ def main(client, label_id): # Display results. for creative_wrapper in creative_wrappers: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' + print ('Creative wrapper with ID "%s" applying to label "%s" was ' 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py index 503a8096..1efb160b 100755 --- a/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py @@ -61,8 +61,8 @@ def main(client, label_id): if 'results' in response: # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' with ' - 'status \'%s\' will be deactivated.' % + print ('Creative wrapper with ID "%s" applying to label "%s" with ' + 'status "%s" will be deactivated.' % (creative_wrapper['id'], creative_wrapper['labelId'], creative_wrapper['status'])) diff --git a/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py index 267b2d80..a2218d92 100755 --- a/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py @@ -65,7 +65,7 @@ def main(client, creative_wrapper_id): # Display results. for creative_wrapper in creative_wrappers: - print (('Creative wrapper with ID \'%s\' and wrapping order \'%s\' ' + print (('Creative wrapper with ID "%s" and wrapping order "%s" ' 'was updated.') % (creative_wrapper['id'], creative_wrapper['ordering'])) else: diff --git a/examples/dfp/v201611/custom_field_service/create_custom_field_options.py b/examples/dfp/v201611/custom_field_service/create_custom_field_options.py index f034bbcd..f772f6e8 100755 --- a/examples/dfp/v201611/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201611/custom_field_service/create_custom_field_options.py @@ -58,7 +58,7 @@ def main(client, custom_field_id): # Display results. for custom_field_option in custom_field_options: - print ('Custom field option with ID \'%s\' and name \'%s\' was created.' + print ('Custom field option with ID "%s" and name "%s" was created.' % (custom_field_option['id'], custom_field_option['displayName'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/custom_field_service/create_custom_fields.py b/examples/dfp/v201611/custom_field_service/create_custom_fields.py index 187278cd..559fdea8 100755 --- a/examples/dfp/v201611/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/create_custom_fields.py @@ -57,7 +57,7 @@ def main(client): # Display results. for custom_field in custom_fields: - print ('Custom field with ID \'%s\' and name \'%s\' was created.' + print ('Custom field with ID "%s" and name "%s" was created.' % (custom_field['id'], custom_field['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py index c30fbaf3..20491ecc 100755 --- a/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -64,7 +64,7 @@ def main(client): if 'results' in response: # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' will' + print ('Custom field with ID "%s" and name "%s" will' ' be deactivated.' % (custom_field['id'], custom_field['name'])) result = custom_field_service.performCustomFieldAction( {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) diff --git a/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py index b9b5733e..f90cca51 100755 --- a/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py @@ -137,14 +137,14 @@ def main(client, custom_field_id, drop_down_custom_field_id, for value in line_item['customFieldValues']: if dfp.DfpClassType(value) == 'CustomFieldValue': custom_field_value_string = ( - '{ID: \'%s\', value: \'%s\'}' + '{ID: "%s", value: "%s"}' % (value['customFieldId'], value['value']['value'])) elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( - '{ID: \'%s\', custom field option ID: \'%s\'}' + '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) custom_field_value_strings.append(custom_field_value_string) - print ('Line item with ID \'%s\' set with custom field values %s.' + print ('Line item with ID "%s" set with custom field values %s.' % (line_item['id'], ','.join(custom_field_value_strings))) else: print 'Line item or custom field not found.' diff --git a/examples/dfp/v201611/custom_field_service/update_custom_fields.py b/examples/dfp/v201611/custom_field_service/update_custom_fields.py index 07bd3139..c78deedc 100755 --- a/examples/dfp/v201611/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/update_custom_fields.py @@ -62,8 +62,8 @@ def main(client, custom_field_id): # Display results. for custom_field in custom_fields: - print (('Custom field with ID \'%s\', name \'%s\', and ' - 'description \'%s\' was updated.') + print (('Custom field with ID "%s", name "%s", and ' + 'description "%s" was updated.') % (custom_field['id'], custom_field['name'], custom_field['description'])) else: diff --git a/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py index e73d10dc..eda7d5f2 100755 --- a/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -63,9 +63,9 @@ def main(client): # Display results. if keys: for key in keys: - print ('A custom targeting key with id \'%s\', name \'%s\', and display ' - 'name \'%s\' was created.' % (key['id'], key['name'], - key['displayName'])) + print ('A custom targeting key with id "%s", name "%s", and display ' + 'name "%s" was created.' % (key['id'], key['name'], + key['displayName'])) else: print 'No keys were created.' @@ -119,8 +119,8 @@ def main(client): # Display results. if values: for value in values: - print ('A custom targeting value with id \'%s\', belonging to key with id' - ' \'%s\', name \'%s\', and display name \'%s\' was created.' + print ('A custom targeting value with id "%s", belonging to key with id' + ' "%s", name "%s", and display name "%s" was created.' % (value['id'], value['customTargetingKeyId'], value['name'], value['displayName'])) else: diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py index ab5538e3..901d2d45 100755 --- a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py @@ -59,8 +59,8 @@ def main(client, key_id): # Display results. if keys: for key in keys: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was updated.' + print ('Custom targeting key with id "%s", name "%s", display name ' + '"%s", and type "%s" was updated.' % (key['id'], key['name'], key['displayName'], key['type'])) else: print 'No custom targeting keys were found to update.' diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py index 2f5c0389..c6c9dbdf 100755 --- a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py @@ -60,8 +60,8 @@ def main(client, key_id): # Display results. for value in values: - print ('Custom targeting value with id \'%s\', name \'%s\', and display' - ' name \'%s\' was updated.' + print ('Custom targeting value with id "%s", name "%s", and display' + ' name "%s" was updated.' % (value['id'], value['name'], value['displayName'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: diff --git a/examples/dfp/v201611/inventory_service/archive_ad_units.py b/examples/dfp/v201611/inventory_service/archive_ad_units.py index 0e2a6fd9..768205c0 100755 --- a/examples/dfp/v201611/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201611/inventory_service/archive_ad_units.py @@ -57,7 +57,7 @@ def main(client, parent_id): statement.ToStatement()) if 'results' in response: for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' will be archived.' + print ('Ad unit with ID "%s" and name "%s" will be archived.' % (ad_unit['id'], ad_unit['name'])) # Perform action. result = inventory_service.performAdUnitAction( diff --git a/examples/dfp/v201611/inventory_service/create_ad_units.py b/examples/dfp/v201611/inventory_service/create_ad_units.py index b1cc6bd9..25a9eed9 100755 --- a/examples/dfp/v201611/inventory_service/create_ad_units.py +++ b/examples/dfp/v201611/inventory_service/create_ad_units.py @@ -61,7 +61,7 @@ def main(client, parent_id): # Display results. for ad_unit in ad_units: - print ('Ad unit with ID \'%s\' and name \'%s\' was created.' + print ('Ad unit with ID "%s" and name "%s" was created.' % (ad_unit['id'], ad_unit['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/inventory_service/update_ad_units.py b/examples/dfp/v201611/inventory_service/update_ad_units.py index 9d4d1f67..998d21f7 100755 --- a/examples/dfp/v201611/inventory_service/update_ad_units.py +++ b/examples/dfp/v201611/inventory_service/update_ad_units.py @@ -78,7 +78,7 @@ def main(client, ad_unit_id): ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], size['size']['height']) for size in ad_unit['adUnitSizes']] - print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated' + print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) if __name__ == '__main__': diff --git a/examples/dfp/v201611/label_service/create_labels.py b/examples/dfp/v201611/label_service/create_labels.py index 1afd27e1..712d78af 100755 --- a/examples/dfp/v201611/label_service/create_labels.py +++ b/examples/dfp/v201611/label_service/create_labels.py @@ -46,7 +46,7 @@ def main(client): # Display results. for label in labels: - print ('Label with id \'%s\', name \'%s\', and types {%s} was found.' + print ('Label with id "%s", name "%s", and types {%s} was found.' % (label['id'], label['name'], ','.join(label['types']))) if __name__ == '__main__': diff --git a/examples/dfp/v201611/label_service/deactivate_labels.py b/examples/dfp/v201611/label_service/deactivate_labels.py index 61fc288d..cb5eb853 100755 --- a/examples/dfp/v201611/label_service/deactivate_labels.py +++ b/examples/dfp/v201611/label_service/deactivate_labels.py @@ -47,7 +47,7 @@ def main(client): response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' will be ' + print ('Label with id "%s" and name "%s" will be ' 'deactivated.' % (label['id'], label['name'])) # Perform action. result = label_service.performLabelAction( diff --git a/examples/dfp/v201611/label_service/update_labels.py b/examples/dfp/v201611/label_service/update_labels.py index 008b7913..58d26a94 100755 --- a/examples/dfp/v201611/label_service/update_labels.py +++ b/examples/dfp/v201611/label_service/update_labels.py @@ -58,7 +58,7 @@ def main(client, label_id): labels = label_service.updateLabels(updated_labels) for label in labels: - print ('Label with id \'%s\' and name \'%s\' was updated.' + print ('Label with id "%s" and name "%s" was updated.' % (label['id'], label['name'])) else: print 'No labels found to update.' diff --git a/examples/dfp/v201611/line_item_creative_association_service/create_licas.py b/examples/dfp/v201611/line_item_creative_association_service/create_licas.py index 8f38c48b..51cbb180 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/create_licas.py @@ -45,8 +45,8 @@ def main(client, line_item_id, creative_ids): # Display results. if licas: for lica in licas: - print ('LICA with line item id \'%s\', creative id \'%s\', and ' - 'status \'%s\' was created.' % + print ('LICA with line item id "%s", creative id "%s", and ' + 'status "%s" was created.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) else: print 'No LICAs created.' diff --git a/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py index 7a31fc78..69c2f654 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py @@ -57,8 +57,8 @@ def main(client, line_item_id): statement.ToStatement()) if 'results' in response: for lica in response['results']: - print ('LICA with line item id \'%s\', creative id \'%s\', and status' - ' \'%s\' will be deactivated.' % + print ('LICA with line item id "%s", creative id "%s", and status' + ' "%s" will be deactivated.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) # Perform action. diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py index 8d836a15..c430247e 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py @@ -37,8 +37,8 @@ def main(client): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % + print('LICA with line item ID "%s", creative set ID "%s", and ' + 'status "%s" was found.' % (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: print('Line item creative association with line item ID "%d" and ' diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py index d98789ac..b5825ad3 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py @@ -46,8 +46,8 @@ def main(client, line_item_id): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % + print('LICA with line item ID "%s", creative set ID "%s", and ' + 'status "%s" was found.' % (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: print('Line item creative association with line item ID "%d" and ' diff --git a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py index 54eb403c..96babbdb 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py @@ -50,9 +50,9 @@ def main(client): # Display results. for lica in licas: - print ('LICA with line item id \'%s\', creative id \'%s\', and status ' - '\'%s\' was updated.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print ('LICA with line item id "%s", creative id "%s", and status ' + '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], + lica['status'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201611/line_item_service/activate_line_items.py b/examples/dfp/v201611/line_item_service/activate_line_items.py index 9dc51032..79f98c2c 100755 --- a/examples/dfp/v201611/line_item_service/activate_line_items.py +++ b/examples/dfp/v201611/line_item_service/activate_line_items.py @@ -60,8 +60,8 @@ def main(client, order_id): statement.ToStatement()) if 'results' in response: for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'name \'%s\' will be activated.' % + print ('Line item with id "%s", belonging to order id "%s", and ' + 'name "%s" will be activated.' % (line_item['id'], line_item['orderId'], line_item['name'])) # Perform action. diff --git a/examples/dfp/v201611/line_item_service/create_line_items.py b/examples/dfp/v201611/line_item_service/create_line_items.py index 6497dff0..d02cc9ac 100755 --- a/examples/dfp/v201611/line_item_service/create_line_items.py +++ b/examples/dfp/v201611/line_item_service/create_line_items.py @@ -161,9 +161,9 @@ def main(client, order_id, targeted_placement_ids): # Display results. for line_item in line_items: - print ('Line item with id \'%s\', belonging to order id \'%s\', and named ' - '\'%s\' was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print ('Line item with id "%s", belonging to order id "%s", and named ' + '"%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201611/line_item_service/create_video_line_item.py b/examples/dfp/v201611/line_item_service/create_video_line_item.py index 2e084fed..0f136303 100755 --- a/examples/dfp/v201611/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201611/line_item_service/create_video_line_item.py @@ -130,9 +130,9 @@ def main(client, order_id, targeted_video_ad_unit_id, line_item = line_item_service.createLineItem(line_item) # Display results. - print ('Video line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print ('Video line item with id "%s", belonging to order id "%s", and ' + 'named "%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201611/line_item_service/target_custom_criteria.py b/examples/dfp/v201611/line_item_service/target_custom_criteria.py index b1a47fcd..f52e2c09 100755 --- a/examples/dfp/v201611/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201611/line_item_service/target_custom_criteria.py @@ -101,7 +101,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Display results. if line_item: - print ('Line item with id \'%s\' updated with custom criteria targeting:' + print ('Line item with id "%s" updated with custom criteria targeting:' % line_item['id']) pprint.pprint(line_item['targeting']['customTargeting']) else: diff --git a/examples/dfp/v201611/line_item_service/update_line_items.py b/examples/dfp/v201611/line_item_service/update_line_items.py index e9fb7c38..7b3ae5e6 100755 --- a/examples/dfp/v201611/line_item_service/update_line_items.py +++ b/examples/dfp/v201611/line_item_service/update_line_items.py @@ -67,8 +67,8 @@ def main(client, order_id): # Display results. if line_items: for line_item in line_items: - print ('Line item with id \'%s\', belonging to order id \'%s\', named ' - '\'%s\', and delivery rate \'%s\' was updated.' + print ('Line item with id "%s", belonging to order id "%s", named ' + '"%s", and delivery rate "%s" was updated.' % (line_item['id'], line_item['orderId'], line_item['name'], line_item['deliveryRateType'])) else: diff --git a/examples/dfp/v201611/network_service/get_all_networks.py b/examples/dfp/v201611/network_service/get_all_networks.py index d65e9d49..2b08fa46 100755 --- a/examples/dfp/v201611/network_service/get_all_networks.py +++ b/examples/dfp/v201611/network_service/get_all_networks.py @@ -28,7 +28,7 @@ def main(client): # Print out some information for each network. for network in networks: - print('Network with network code \'%s\' and display name \'%s\' was found.' + print('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) print '\nNumber of results found: %s' % len(networks) diff --git a/examples/dfp/v201611/network_service/make_test_network.py b/examples/dfp/v201611/network_service/make_test_network.py index 6045a0a4..e8d56aa0 100755 --- a/examples/dfp/v201611/network_service/make_test_network.py +++ b/examples/dfp/v201611/network_service/make_test_network.py @@ -40,7 +40,7 @@ def main(client): network = network_service.makeTestNetwork() # Display results. - print ('Test network with network code \'%s\' and display name \'%s\' ' + print ('Test network with network code "%s" and display name "%s" ' 'created.' % (network['networkCode'], network['displayName'])) print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s' % network['networkCode']) diff --git a/examples/dfp/v201611/order_service/approve_orders.py b/examples/dfp/v201611/order_service/approve_orders.py index 5638f2db..d6f8e3a8 100755 --- a/examples/dfp/v201611/order_service/approve_orders.py +++ b/examples/dfp/v201611/order_service/approve_orders.py @@ -51,7 +51,7 @@ def main(client): if 'results' in response: # Display results. for order in response['results']: - print ('Order with id \'%s\', name \'%s\', and status \'%s\' will be ' + print ('Order with id "%s", name "%s", and status "%s" will be ' 'approved.' % (order['id'], order['name'], order['status'])) # Perform action. result = order_service.performOrderAction( diff --git a/examples/dfp/v201611/order_service/create_orders.py b/examples/dfp/v201611/order_service/create_orders.py index cf3fcfb8..21b38ac8 100755 --- a/examples/dfp/v201611/order_service/create_orders.py +++ b/examples/dfp/v201611/order_service/create_orders.py @@ -50,7 +50,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Display results. for order in orders: - print ('Order with id \'%s\' and name \'%s\' was created.' + print ('Order with id "%s" and name "%s" was created.' % (order['id'], order['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/order_service/update_orders.py b/examples/dfp/v201611/order_service/update_orders.py index 58a4e1dc..2d1fe5df 100755 --- a/examples/dfp/v201611/order_service/update_orders.py +++ b/examples/dfp/v201611/order_service/update_orders.py @@ -60,8 +60,8 @@ def main(client, order_id): # Display results. if orders: for order in orders: - print ('Order with id \'%s\', name \'%s\', advertiser id \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Order with id "%s", name "%s", advertiser id "%s", and ' + 'notes "%s" was updated.' % (order['id'], order['name'], order['advertiserId'], order['notes'])) else: diff --git a/examples/dfp/v201611/placement_service/create_placements.py b/examples/dfp/v201611/placement_service/create_placements.py index 58a86237..33627770 100755 --- a/examples/dfp/v201611/placement_service/create_placements.py +++ b/examples/dfp/v201611/placement_service/create_placements.py @@ -98,7 +98,7 @@ def main(client): ad_unit_ids = '' if 'targetedAdUnitIds' in placement: ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) - print ('A Placement with ID \'%s\', name \'%s\', and containing ad units ' + print ('A Placement with ID "%s", name "%s", and containing ad units ' '{%s} was created.' % (placement['id'], placement['name'], ad_unit_ids)) diff --git a/examples/dfp/v201611/placement_service/deactivate_placements.py b/examples/dfp/v201611/placement_service/deactivate_placements.py index f181f445..ef317b06 100755 --- a/examples/dfp/v201611/placement_service/deactivate_placements.py +++ b/examples/dfp/v201611/placement_service/deactivate_placements.py @@ -46,7 +46,7 @@ def main(client, placement_id): statement.ToStatement()) for placement in placements: - print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be ' + print ('Placement with id "%s", name "%s", and status "%s" will be ' 'deactivated.' % (placement['id'], placement['name'], placement['status'])) diff --git a/examples/dfp/v201611/placement_service/update_placements.py b/examples/dfp/v201611/placement_service/update_placements.py index ca053db2..3b797779 100755 --- a/examples/dfp/v201611/placement_service/update_placements.py +++ b/examples/dfp/v201611/placement_service/update_placements.py @@ -55,8 +55,8 @@ def main(client, placement_id): placements = placement_service.updatePlacements(placements) for placement in placements: - print ('Placement with id \'%s\', name \'%s\', and AdSense targeting ' - 'enabled \'%s\' was updated.' + print ('Placement with id "%s", name "%s", and AdSense targeting ' + 'enabled "%s" was updated.' % (placement['id'], placement['name'], placement['isAdSenseTargetingEnabled'])) diff --git a/examples/dfp/v201611/premium_rate_service/create_premium_rates.py b/examples/dfp/v201611/premium_rate_service/create_premium_rates.py index f55590fc..b13cf248 100755 --- a/examples/dfp/v201611/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/create_premium_rates.py @@ -70,8 +70,8 @@ def main(client, rate_card_id): # Display results. for premium_rate in premium_rates: - print ('A premium rate for \'%s\' was added to the rate card with ID' - ' of \'%s\'.\n' + print ('A premium rate for "%s" was added to the rate card with ID' + ' of "%s".\n' % (dfp.DfpClassType(premium_rate['premiumFeature']), premium_rate['id'])) diff --git a/examples/dfp/v201611/premium_rate_service/update_premium_rates.py b/examples/dfp/v201611/premium_rate_service/update_premium_rates.py index 1565b78d..a5adcd8e 100755 --- a/examples/dfp/v201611/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/update_premium_rates.py @@ -76,9 +76,9 @@ def main(client, premium_rate_id): # Display results. if premium_rates: for premium_rate in premium_rates: - print ('Premium rate with ID \'%s\', associated with rate card id' - ' \'%s\' was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) + print ('Premium rate with ID "%s", associated with rate card id' + ' "%s" was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) else: print 'No premium rates were updated.' else: diff --git a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py index 7e18932a..fa4b7b21 100755 --- a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py @@ -48,7 +48,7 @@ def main(client, product_id): statement.ToStatement()) if 'results' in response: for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' will be ' + print ('Product with id "%s" and name "%s" will be ' 'published.' % (product['id'], product['name'])) diff --git a/examples/dfp/v201611/product_service/update_products.py b/examples/dfp/v201611/product_service/update_products.py index 1b16d420..f8f9cd6f 100755 --- a/examples/dfp/v201611/product_service/update_products.py +++ b/examples/dfp/v201611/product_service/update_products.py @@ -58,8 +58,8 @@ def main(client, product_id): # Display results. if products: for product in products: - print ('Product with id \'%s\', name \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Product with id "%s", name "%s", and ' + 'notes "%s" was updated.' % (product['id'], product['name'], product['notes'])) else: print 'No products were updated.' diff --git a/examples/dfp/v201611/product_template_service/activate_product_templates.py b/examples/dfp/v201611/product_template_service/activate_product_templates.py index bdfb9d10..febdb005 100755 --- a/examples/dfp/v201611/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201611/product_template_service/activate_product_templates.py @@ -52,7 +52,7 @@ def main(client, product_template_id): statement.ToStatement()) if 'results' in response: for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' will be ' + print ('Product template with id "%s" and name "%s" will be ' 'activated.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201611/product_template_service/create_product_templates.py b/examples/dfp/v201611/product_template_service/create_product_templates.py index a9621b57..1201f8de 100755 --- a/examples/dfp/v201611/product_template_service/create_product_templates.py +++ b/examples/dfp/v201611/product_template_service/create_product_templates.py @@ -99,7 +99,7 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A product template with ID \'%s\' and name \'%s\' was ' + print ('A product template with ID "%s" and name "%s" was ' 'created.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py index f4f324a8..d39e29f3 100755 --- a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py @@ -80,7 +80,7 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A programmatic product template with ID \'%s\' and name \'%s\' ' + print ('A programmatic product template with ID "%s" and name "%s" ' 'was created.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201611/product_template_service/update_product_templates.py b/examples/dfp/v201611/product_template_service/update_product_templates.py index ca1024c0..c47f2faa 100755 --- a/examples/dfp/v201611/product_template_service/update_product_templates.py +++ b/examples/dfp/v201611/product_template_service/update_product_templates.py @@ -84,7 +84,7 @@ def main(client, product_template_id): # Display results. if product_templates: for product_template in product_templates: - print ('Product template with id \'%s\' and name \'%s\' was ' + print ('Product template with id "%s" and name "%s" was ' 'updated.' % (product_template['id'], product_template['name'])) else: print 'No product templates were updated.' diff --git a/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py index b51de1df..7e84d863 100755 --- a/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py @@ -52,9 +52,9 @@ def main(client, proposal_line_item_id): statement.ToStatement()) if 'results' in response: for proposal_line_item in response['results']: - print ('Proposal line item with id \'%s\', ' - 'belonging to proposal id \'%s\', and ' - 'name \'%s\' will be archived.' % + print ('Proposal line item with id "%s", ' + 'belonging to proposal id "%s", and ' + 'name "%s" will be archived.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py index 4049f29d..906333f4 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -106,8 +106,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item with id \'%s\', belonging to ' - 'proposal id \'%s\', and named \'%s\' was created.' % + print ('Programmatic proposal line item with id "%s", belonging to ' + 'proposal id "%s", and named "%s" was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index e48ee12b..aa3cd41d 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -112,7 +112,7 @@ def main(client, proposal_id, product_id): # Display results. for proposal_line_item in proposal_line_items: print ('Programmatic proposal line item for non-sales management with id ' - '\'%s\', belonging to proposal id \'%s\', and named \'%s\' ' + '"%s", belonging to proposal id "%s", and named "%s" ' 'was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py index 82d4f0f5..4823a1e6 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py @@ -107,8 +107,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Proposal line item with id \'%s\', belonging to proposal id \'%s\'' - ', and named \'%s\' was created.' % + print ('Proposal line item with id "%s", belonging to proposal id "%s"' + ', and named "%s" was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py index 4a05acda..57c7a03b 100755 --- a/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py @@ -61,8 +61,8 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items: for proposal_line_item in proposal_line_items: - print ('Line item with id \'%s\', belonging to proposal id \'%s\' and,' - ' named \'%s\' was updated.' % ( + print ('Line item with id "%s", belonging to proposal id "%s" and,' + ' named "%s" was updated.' % ( proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) else: diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py index 351602fb..ac5b4c30 100755 --- a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py @@ -60,7 +60,7 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, # Display results. for proposal in proposals: - print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + print('Programmatic proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py index d710a59d..e687a8f9 100755 --- a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -51,7 +51,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, # Display results. for proposal in proposals: - print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + print('Programmatic proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) diff --git a/examples/dfp/v201611/proposal_service/create_proposals.py b/examples/dfp/v201611/proposal_service/create_proposals.py index 7c8d676f..da59b791 100755 --- a/examples/dfp/v201611/proposal_service/create_proposals.py +++ b/examples/dfp/v201611/proposal_service/create_proposals.py @@ -67,7 +67,7 @@ def main(client, advertiser_id, primary_salesperson_id, # Display results. for proposal in proposals: - print ('Proposal with id \'%s\' and name \'%s\' was created.' + print ('Proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py index a324420c..bc6c27d4 100755 --- a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py @@ -48,10 +48,10 @@ def main(client, proposal_id): if 'results' in response: # Display results. for proposal in response['results']: - print ('Programmatic proposal with id \'%s\', name \'%s\', and status ' - '\'%s\' will be pushed to Marketplace.' % (proposal['id'], - proposal['name'], - proposal['status'])) + print ('Programmatic proposal with id "%s", name "%s", and status ' + '"%s" will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) diff --git a/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py index 743e511c..1300355f 100755 --- a/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py @@ -50,7 +50,7 @@ def main(client, proposal_id): if 'results' in response: # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\', name \'%s\', and status \'%s\' will be' + print ('Proposal with id "%s", name "%s", and status "%s" will be' ' approved.' % (proposal['id'], proposal['name'], proposal['status'])) # Perform action. diff --git a/examples/dfp/v201611/proposal_service/update_proposals.py b/examples/dfp/v201611/proposal_service/update_proposals.py index a1784550..71ddee70 100755 --- a/examples/dfp/v201611/proposal_service/update_proposals.py +++ b/examples/dfp/v201611/proposal_service/update_proposals.py @@ -58,8 +58,8 @@ def main(client, proposal_id): # Display results. if proposals: for proposal in proposals: - print ('Proposal with id \'%s\', name \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Proposal with id "%s", name "%s", and ' + 'notes "%s" was updated.' % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: print 'No proposals were updated.' diff --git a/examples/dfp/v201611/report_service/run_delivery_report.py b/examples/dfp/v201611/report_service/run_delivery_report.py index 562ae188..5ec23cf4 100755 --- a/examples/dfp/v201611/report_service/run_delivery_report.py +++ b/examples/dfp/v201611/report_service/run_delivery_report.py @@ -87,7 +87,7 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201611/report_service/run_inventory_report.py b/examples/dfp/v201611/report_service/run_inventory_report.py index f4510511..b57d2d6f 100755 --- a/examples/dfp/v201611/report_service/run_inventory_report.py +++ b/examples/dfp/v201611/report_service/run_inventory_report.py @@ -77,7 +77,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201611/report_service/run_reach_report.py b/examples/dfp/v201611/report_service/run_reach_report.py index 723a0a34..837bc456 100755 --- a/examples/dfp/v201611/report_service/run_reach_report.py +++ b/examples/dfp/v201611/report_service/run_reach_report.py @@ -54,7 +54,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) diff --git a/examples/dfp/v201611/report_service/run_report_with_custom_fields.py b/examples/dfp/v201611/report_service/run_report_with_custom_fields.py index e430231e..f7632c2d 100755 --- a/examples/dfp/v201611/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201611/report_service/run_report_with_custom_fields.py @@ -94,7 +94,7 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201611/report_service/run_sales_report.py b/examples/dfp/v201611/report_service/run_sales_report.py index c922edeb..0ea30bf5 100755 --- a/examples/dfp/v201611/report_service/run_sales_report.py +++ b/examples/dfp/v201611/report_service/run_sales_report.py @@ -55,7 +55,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201611/report_service/run_saved_query.py b/examples/dfp/v201611/report_service/run_saved_query.py index dc4f502b..f2bd0f0f 100755 --- a/examples/dfp/v201611/report_service/run_saved_query.py +++ b/examples/dfp/v201611/report_service/run_saved_query.py @@ -73,7 +73,7 @@ def main(client, saved_query_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) else: print 'The query specified is not compatible with the API version.' diff --git a/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 627acc0d..9233f5b0 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -52,7 +52,7 @@ def main(client): if 'results' in response: # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: - print ('Suggested ad unit with id \'%s\', and number of requests \'%s\'' + print ('Suggested ad unit with id "%s", and number of requests "%s"' ' will be approved.' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) diff --git a/examples/dfp/v201611/team_service/create_teams.py b/examples/dfp/v201611/team_service/create_teams.py index 647a85fc..05639a79 100755 --- a/examples/dfp/v201611/team_service/create_teams.py +++ b/examples/dfp/v201611/team_service/create_teams.py @@ -51,7 +51,7 @@ def main(client): # Display results. for team in teams: - print ('Team with ID \'%s\' and name \'%s\' was created.' + print ('Team with ID "%s" and name "%s" was created.' % (team['id'], team['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/team_service/update_teams.py b/examples/dfp/v201611/team_service/update_teams.py index 5c9c4863..8016d1ab 100755 --- a/examples/dfp/v201611/team_service/update_teams.py +++ b/examples/dfp/v201611/team_service/update_teams.py @@ -62,7 +62,7 @@ def main(client, team_id): # Display results. for team in teams: - print ('Team with id \'%s\' and name \'%s\' was updated.' + print ('Team with id "%s" and name "%s" was updated.' % (team['id'], team['name'])) else: print 'No teams found to update.' diff --git a/examples/dfp/v201611/user_service/create_users.py b/examples/dfp/v201611/user_service/create_users.py index e0d42cc8..585f5dcf 100755 --- a/examples/dfp/v201611/user_service/create_users.py +++ b/examples/dfp/v201611/user_service/create_users.py @@ -48,7 +48,7 @@ def main(client, email, name): # Display results. for user in users: - print ('User with id \'%s\', email \'%s\', and role \'%s\' was created.' + print ('User with id "%s", email "%s", and role "%s" was created.' % (user['id'], user['email'], user['roleName'])) if __name__ == '__main__': diff --git a/examples/dfp/v201611/user_service/deactivate_users.py b/examples/dfp/v201611/user_service/deactivate_users.py index 3b86bc76..771244c0 100755 --- a/examples/dfp/v201611/user_service/deactivate_users.py +++ b/examples/dfp/v201611/user_service/deactivate_users.py @@ -50,7 +50,7 @@ def main(client, user_id): users = response['results'] if 'results' in response else [] for user in users: - print ('User with id \'%s\', email \'%s\', and status \'%s\' will be ' + print ('User with id "%s", email "%s", and status "%s" will be ' 'deactivated.' % (user['id'], user['email'], {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) diff --git a/examples/dfp/v201611/user_service/get_all_roles.py b/examples/dfp/v201611/user_service/get_all_roles.py index fb763029..bb2bec62 100755 --- a/examples/dfp/v201611/user_service/get_all_roles.py +++ b/examples/dfp/v201611/user_service/get_all_roles.py @@ -28,7 +28,7 @@ def main(client): # Print out some information for each role. for role in roles: - print('Role with id \'%s\' and name \'%s\' was found.' % + print('Role with id "%s" and name "%s" was found.' % (role['id'], role['name'])) print '\nNumber of results found: %s' % len(roles) diff --git a/examples/dfp/v201611/user_service/update_users.py b/examples/dfp/v201611/user_service/update_users.py index 5060cfb1..1bb5d43a 100755 --- a/examples/dfp/v201611/user_service/update_users.py +++ b/examples/dfp/v201611/user_service/update_users.py @@ -54,7 +54,7 @@ def main(client, user_id): # Update users on server. users = user_service.updateUsers(users) for user in users: - print ('User with id \'%s\' and name \'%s\' was updated.' + print ('User with id "%s" and name "%s" was updated.' % (user['id'], user['name'])) else: print 'No users found to update.' diff --git a/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py index f5ae34cb..73088e81 100755 --- a/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py @@ -55,9 +55,9 @@ def main(client, team_id, user_ids): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('A user team association between user with ID \'%s\' and team with' - ' ID \'%s\'was created.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('A user team association between user with ID "%s" and team with' + ' ID "%s"was created.' % (user_team_association['userId'], + user_team_association['teamId'])) else: print 'No user team associations created.' diff --git a/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py index f096aefd..3d15ff40 100755 --- a/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py @@ -56,9 +56,9 @@ def main(client, user_id): user_team_associations = response['results'] if 'results' in response else [] for user_team_association in user_team_associations: - print ('User team association between user with ID \'%s\' and team with ' - 'ID \'%s\' will be deleted.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('User team association between user with ID "%s" and team with ' + 'ID "%s" will be deleted.' % (user_team_association['userId'], + user_team_association['teamId'])) print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) diff --git a/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py index 194c51d1..de32b653 100755 --- a/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py @@ -71,9 +71,9 @@ def main(client, user_id): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was updated.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('User team association between user with ID "%s" and team with' + ' ID "%s" was updated.' % (user_team_association['userId'], + user_team_association['teamId'])) else: print 'No user team associations were updated.' else: diff --git a/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py index cdf9ea61..6c7dbeb0 100755 --- a/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py @@ -71,7 +71,7 @@ def main(client, proposal_id): if 'results' in response: # Display results. for workflow_approval_request in response['results']: - print ('Workflow approval request with id \'%s\' will be' + print ('Workflow approval request with id "%s" will be' ' approved.' % workflow_approval_request['id']) # Perform action. result = workflow_request_service.performWorkflowRequestAction( diff --git a/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py index 91131414..cdca1668 100755 --- a/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -71,8 +71,8 @@ def main(client, proposal_id): if 'results' in response: # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id \'%s\' for %s ' - 'with id \'%s\' will be triggered.' % + print ('Workflow external condition request with id "%s" for %s ' + 'with id "%s" will be triggered.' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) diff --git a/examples/dfp/v201702/activity_group_service/create_activity_groups.py b/examples/dfp/v201702/activity_group_service/create_activity_groups.py index 33d38425..9f5ec668 100755 --- a/examples/dfp/v201702/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/create_activity_groups.py @@ -62,7 +62,7 @@ def main(client, advertiser_company_id): # Display results. for activity_group in activity_groups: - print ('Activity group with ID \'%s\' and name \'%s\' was created.' + print ('Activity group with ID "%s" and name "%s" was created.' % (activity_group['id'], activity_group['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/activity_group_service/update_activity_groups.py b/examples/dfp/v201702/activity_group_service/update_activity_groups.py index bbdf03cc..d3724557 100755 --- a/examples/dfp/v201702/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/update_activity_groups.py @@ -65,7 +65,7 @@ def main(client, activity_group_id, advertiser_company_id): updated_activity_groups) for activity_group in activity_groups: - print (('Activity group with ID \'%s\' and name \'%s\' was updated.') + print (('Activity group with ID "%s" and name "%s" was updated.') % (activity_group['id'], activity_group['name'])) else: print 'No activity groups found to update.' diff --git a/examples/dfp/v201702/activity_service/create_activities.py b/examples/dfp/v201702/activity_service/create_activities.py index 509c9e0c..62bc032f 100755 --- a/examples/dfp/v201702/activity_service/create_activities.py +++ b/examples/dfp/v201702/activity_service/create_activities.py @@ -59,7 +59,7 @@ def main(client, activity_group_id): # Display results. for activity in activities: - print ('An activity with ID \'%s\', name \'%s\', and type \'%s\' was ' + print ('An activity with ID "%s", name "%s", and type "%s" was ' 'created.' % (activity['id'], activity['name'], activity['type'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/activity_service/update_activities.py b/examples/dfp/v201702/activity_service/update_activities.py index 9421c4fd..86865679 100755 --- a/examples/dfp/v201702/activity_service/update_activities.py +++ b/examples/dfp/v201702/activity_service/update_activities.py @@ -61,7 +61,7 @@ def main(client, activity_id): activities = activity_service.updateActivities(updated_activities) for updated_activity in activities: - print (('Activity with ID \'%s\' and name \'%s\' was updated.') + print (('Activity with ID "%s" and name "%s" was updated.') % (updated_activity['id'], updated_activity['name'])) else: print 'No activities found to update.' diff --git a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py b/examples/dfp/v201702/audience_segment_service/create_audience_segments.py index 44ce90de..f0db7a52 100755 --- a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/create_audience_segments.py @@ -84,7 +84,7 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): audience_segment_service.createAudienceSegments(audience_segment)) for created_audience_segment in audience_segments: - print ('An audience segment with ID \'%s\', name \'%s\', and type \'%s\' ' + print ('An audience segment with ID "%s", name "%s", and type "%s" ' 'was created.' % (created_audience_segment['id'], created_audience_segment['name'], created_audience_segment['type'])) diff --git a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py index 6606ea22..371c6923 100755 --- a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py @@ -57,7 +57,7 @@ def main(client, audience_segment_id): for segment in segments: print ( - 'Audience segment with id \'%s\' and name \'%s\' will be populated.' + 'Audience segment with id "%s" and name "%s" will be populated.' % (segment['id'], segment['name'])) action = { diff --git a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py b/examples/dfp/v201702/audience_segment_service/update_audience_segments.py index fe3bfd6d..2c708dea 100755 --- a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/update_audience_segments.py @@ -55,7 +55,7 @@ def main(client, audience_segment_id): if 'results' in response: updated_audience_segments = [] for audience_segment in response['results']: - print ('Audience segment with id \'%s\' and name \'%s\' will be updated.' + print ('Audience segment with id "%s" and name "%s" will be updated.' % (audience_segment['id'], audience_segment['name'])) audience_segment['membershipExpirationDays'] = '180' @@ -65,7 +65,7 @@ def main(client, audience_segment_id): updated_audience_segments) for audience_segment in audience_segments: - print ('Audience segment with id \'%s\' and name \'%s\' was updated' % + print ('Audience segment with id "%s" and name "%s" was updated' % (audience_segment['id'], audience_segment['name'])) else: print 'No audience segment found to update.' diff --git a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_base_rates.py index 3bb66784..26003719 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/create_product_base_rates.py @@ -51,7 +51,7 @@ def main(client, product_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product base rate with ID \'%s\' and rate \'%.2f\' %s was ' + print ('A product base rate with ID "%s" and rate \'%.2f\' %s was ' 'created.' % (base_rate['id'], base_rate['rate']['microAmount'], base_rate['rate']['currencyCode'])) diff --git a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py index 9ce5c42d..d024f6e8 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py @@ -51,7 +51,7 @@ def main(client, product_template_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product template base rate with ID \'%s\' and rate \'%.2f\' %s' + print ('A product template base rate with ID "%s" and rate \'%.2f\' %s' ' was created.' % (base_rate['id'], base_rate['rate']['microAmount'], base_rate['rate']['currencyCode'])) diff --git a/examples/dfp/v201702/base_rate_service/update_base_rates.py b/examples/dfp/v201702/base_rate_service/update_base_rates.py index d80870bf..a1b1d7fe 100755 --- a/examples/dfp/v201702/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/update_base_rates.py @@ -64,8 +64,8 @@ def main(client, base_rate_id): # Display results. if base_rates: for base_rate in base_rates: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was updated.' % ( + print ('Base rate with ID "%s" and type "%s" belonging to ' + 'rate card ID "%s" was updated.' % ( base_rate['id'], dfp.DfpClassType(base_rate), base_rate['rateCardId'])) diff --git a/examples/dfp/v201702/company_service/create_companies.py b/examples/dfp/v201702/company_service/create_companies.py index ce54ddf5..8b41d9ac 100755 --- a/examples/dfp/v201702/company_service/create_companies.py +++ b/examples/dfp/v201702/company_service/create_companies.py @@ -53,7 +53,7 @@ def main(client): # Display results. for company in companies: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.' + print ('Company with ID "%s", name "%s", and type "%s" was created.' % (company['id'], company['name'], company['type'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/company_service/update_companies.py b/examples/dfp/v201702/company_service/update_companies.py index f64378e1..e1ade3e6 100755 --- a/examples/dfp/v201702/company_service/update_companies.py +++ b/examples/dfp/v201702/company_service/update_companies.py @@ -62,7 +62,7 @@ def main(client, company_id): # Display results. for company in companies: - print (('Company with ID \'%s\', name \'%s\', and comment \'%s\'' + print (('Company with ID "%s", name "%s", and comment "%s"' 'was updated.') % (company['id'], company['name'], company['comment'])) else: diff --git a/examples/dfp/v201702/contact_service/create_contacts.py b/examples/dfp/v201702/contact_service/create_contacts.py index d27881c8..51bd81af 100755 --- a/examples/dfp/v201702/contact_service/create_contacts.py +++ b/examples/dfp/v201702/contact_service/create_contacts.py @@ -62,7 +62,7 @@ def main(client, advertiser_company_id, agency_company_id): # Display results. for contact in contacts: - print ('Contact with ID \'%s\' name \'%s\' was created.' + print ('Contact with ID "%s" name "%s" was created.' % (contact['id'], contact['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/contact_service/update_contacts.py b/examples/dfp/v201702/contact_service/update_contacts.py index 51de259a..d035fc12 100755 --- a/examples/dfp/v201702/contact_service/update_contacts.py +++ b/examples/dfp/v201702/contact_service/update_contacts.py @@ -63,7 +63,7 @@ def main(client, contact_id): # Display results. for contact in contacts: - print (('Contact with ID \'%s\', name \'%s\', and address \'%s\' ' + print (('Contact with ID "%s", name "%s", and address "%s" ' 'was updated.') % (contact['id'], contact['name'], contact['address'])) else: diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index e637128a..2378c8ca 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -68,7 +68,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Display results. for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id \'%s\' and name \'%s\'' + print ('Content metadata key hierarchy with id "%s" and name "%s"' ' was created.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index ade4e7f5..b5400763 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -64,7 +64,7 @@ def main(client, content_metadata_key_hierarchy_id): # Display results. if content_metadata_key_hierarchies: for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with ID \'%s\' and name \'%s\' ' + print ('Content metadata key hierarchy with ID "%s" and name "%s" ' 'will be deleted.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index aed2bad1..b1f5c6bb 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -83,7 +83,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Display results. for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id \'%s\' and name \'%s\'' + print ('Content metadata key hierarchy with id "%s" and name "%s"' ' was updated.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201702/creative_service/copy_image_creatives.py b/examples/dfp/v201702/creative_service/copy_image_creatives.py index 34854b79..7578afdf 100755 --- a/examples/dfp/v201702/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201702/creative_service/copy_image_creatives.py @@ -47,7 +47,7 @@ def main(client): image_creative['name'] = 'Copy of %s' % image_creative['name'] result = creative_service.createCreatives([image_creative])[0] - print ('A creative with ID %d, name \'%s\', and type \'%s\' was created and ' + print ('A creative with ID %d, name "%s", and type "%s" was created and ' 'can be previewed at: %s' % (result['id'], result['name'], dfp.DfpClassType(result), diff --git a/examples/dfp/v201702/creative_service/create_creative_from_template.py b/examples/dfp/v201702/creative_service/create_creative_from_template.py index 2f94513f..13b28235 100755 --- a/examples/dfp/v201702/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201702/creative_service/create_creative_from_template.py @@ -102,7 +102,7 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201702/creative_service/create_creatives.py b/examples/dfp/v201702/creative_service/create_creatives.py index 1226a043..fc3a886d 100755 --- a/examples/dfp/v201702/creative_service/create_creatives.py +++ b/examples/dfp/v201702/creative_service/create_creatives.py @@ -80,7 +80,7 @@ def main(client, advertiser_id): # Display results. for creative in creatives: - print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Image creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201702/creative_service/create_custom_creative.py b/examples/dfp/v201702/creative_service/create_custom_creative.py index d1edd5d9..54de0f4b 100755 --- a/examples/dfp/v201702/creative_service/create_custom_creative.py +++ b/examples/dfp/v201702/creative_service/create_custom_creative.py @@ -49,7 +49,7 @@ def main(client, advertiser_id): image_data = base64.encodestring(image_data) # Create the HTML snippet used in the custom creative. - html_snippet = ('
Click above for ' + html_snippet = ('
Click above for ' 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%', '%%FILE:IMAGE_ASSET%%') @@ -79,7 +79,7 @@ def main(client, advertiser_id): # Display results. if creatives: creative = creatives[0] - print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201702/creative_service/create_native_creative.py b/examples/dfp/v201702/creative_service/create_native_creative.py index 3518ba5d..b2921671 100755 --- a/examples/dfp/v201702/creative_service/create_native_creative.py +++ b/examples/dfp/v201702/creative_service/create_native_creative.py @@ -125,7 +125,7 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Native creative with id \'%s\' and name \'%s\' was ' + print ('Native creative with id "%s" and name "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], creative['previewUrl'])) diff --git a/examples/dfp/v201702/creative_service/update_creatives.py b/examples/dfp/v201702/creative_service/update_creatives.py index ea861269..59dcc8bd 100755 --- a/examples/dfp/v201702/creative_service/update_creatives.py +++ b/examples/dfp/v201702/creative_service/update_creatives.py @@ -69,7 +69,7 @@ def main(client, image_creative_id): # Display results. for creative in creatives: - print ('Image creative with id \'%s\' and destination URL \'%s\' was ' + print ('Image creative with id "%s" and destination URL "%s" was ' 'updated.' % (creative['id'], creative['destinationUrl'])) else: print 'No creatives found to update.' diff --git a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py index 424db9b5..08513acc 100755 --- a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py @@ -46,7 +46,7 @@ def main(client, creative_set_id, line_item_id): lica = lica_service.createLineItemCreativeAssociations([lica]) # Display results. - print (('LICA with line item ID \'%s\' and creative set ID \'%s\' was ' + print (('LICA with line item ID "%s" and creative set ID "%s" was ' 'created.') % (lica['lineItemId'], lica['creativeSetId'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/creative_set_service/create_creative_set.py b/examples/dfp/v201702/creative_set_service/create_creative_set.py index 88706f8c..9118a157 100755 --- a/examples/dfp/v201702/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201702/creative_set_service/create_creative_set.py @@ -50,7 +50,7 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' + print (('Creative set with ID "%s", master creative ID "%s", and ' 'companion creative IDs {%s} was created.') % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) diff --git a/examples/dfp/v201702/creative_set_service/update_creative_set.py b/examples/dfp/v201702/creative_set_service/update_creative_set.py index 9b9090ad..c03266d4 100755 --- a/examples/dfp/v201702/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201702/creative_set_service/update_creative_set.py @@ -65,7 +65,7 @@ def main(client, creative_set_id, companion_creative_id): # Display results. for creative_set in creative_sets: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' + print (('Creative set with ID "%s", master creative ID "%s", and ' 'companion creative IDs {%s} was updated.') % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) diff --git a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py index 8908cf82..2ac46646 100755 --- a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py @@ -54,7 +54,7 @@ def main(client, label_id): # Display results. for creative_wrapper in creative_wrappers: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' + print ('Creative wrapper with ID "%s" applying to label "%s" was ' 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py index 7af7bf90..48c4c1ae 100755 --- a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py @@ -61,8 +61,8 @@ def main(client, label_id): if 'results' in response: # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' with ' - 'status \'%s\' will be deactivated.' % + print ('Creative wrapper with ID "%s" applying to label "%s" with ' + 'status "%s" will be deactivated.' % (creative_wrapper['id'], creative_wrapper['labelId'], creative_wrapper['status'])) diff --git a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py index c0b957ae..5bb8ee6c 100755 --- a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py @@ -65,7 +65,7 @@ def main(client, creative_wrapper_id): # Display results. for creative_wrapper in creative_wrappers: - print (('Creative wrapper with ID \'%s\' and wrapping order \'%s\' ' + print (('Creative wrapper with ID "%s" and wrapping order "%s" ' 'was updated.') % (creative_wrapper['id'], creative_wrapper['ordering'])) else: diff --git a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py b/examples/dfp/v201702/custom_field_service/create_custom_field_options.py index ae2c379c..d2f010bd 100755 --- a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201702/custom_field_service/create_custom_field_options.py @@ -58,7 +58,7 @@ def main(client, custom_field_id): # Display results. for custom_field_option in custom_field_options: - print ('Custom field option with ID \'%s\' and name \'%s\' was created.' + print ('Custom field option with ID "%s" and name "%s" was created.' % (custom_field_option['id'], custom_field_option['displayName'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/custom_field_service/create_custom_fields.py b/examples/dfp/v201702/custom_field_service/create_custom_fields.py index c8a9f338..a823244c 100755 --- a/examples/dfp/v201702/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/create_custom_fields.py @@ -57,7 +57,7 @@ def main(client): # Display results. for custom_field in custom_fields: - print ('Custom field with ID \'%s\' and name \'%s\' was created.' + print ('Custom field with ID "%s" and name "%s" was created.' % (custom_field['id'], custom_field['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py index c173b2bd..51333474 100755 --- a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -64,7 +64,7 @@ def main(client): if 'results' in response: # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' will' + print ('Custom field with ID "%s" and name "%s" will' ' be deactivated.' % (custom_field['id'], custom_field['name'])) result = custom_field_service.performCustomFieldAction( {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) diff --git a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py index 1b35e8a4..63bf186c 100755 --- a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py @@ -137,14 +137,14 @@ def main(client, custom_field_id, drop_down_custom_field_id, for value in line_item['customFieldValues']: if dfp.DfpClassType(value) == 'CustomFieldValue': custom_field_value_string = ( - '{ID: \'%s\', value: \'%s\'}' + '{ID: "%s", value: "%s"}' % (value['customFieldId'], value['value']['value'])) elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( - '{ID: \'%s\', custom field option ID: \'%s\'}' + '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) custom_field_value_strings.append(custom_field_value_string) - print ('Line item with ID \'%s\' set with custom field values %s.' + print ('Line item with ID "%s" set with custom field values %s.' % (line_item['id'], ','.join(custom_field_value_strings))) else: print 'Line item or custom field not found.' diff --git a/examples/dfp/v201702/custom_field_service/update_custom_fields.py b/examples/dfp/v201702/custom_field_service/update_custom_fields.py index f60032f2..5a56bb72 100755 --- a/examples/dfp/v201702/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/update_custom_fields.py @@ -62,8 +62,8 @@ def main(client, custom_field_id): # Display results. for custom_field in custom_fields: - print (('Custom field with ID \'%s\', name \'%s\', and ' - 'description \'%s\' was updated.') + print (('Custom field with ID "%s", name "%s", and ' + 'description "%s" was updated.') % (custom_field['id'], custom_field['name'], custom_field['description'])) else: diff --git a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py index 552dab8d..ed80ede7 100755 --- a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -63,9 +63,9 @@ def main(client): # Display results. if keys: for key in keys: - print ('A custom targeting key with id \'%s\', name \'%s\', and display ' - 'name \'%s\' was created.' % (key['id'], key['name'], - key['displayName'])) + print ('A custom targeting key with id "%s", name "%s", and display ' + 'name "%s" was created.' % (key['id'], key['name'], + key['displayName'])) else: print 'No keys were created.' @@ -119,8 +119,8 @@ def main(client): # Display results. if values: for value in values: - print ('A custom targeting value with id \'%s\', belonging to key with id' - ' \'%s\', name \'%s\', and display name \'%s\' was created.' + print ('A custom targeting value with id "%s", belonging to key with id' + ' "%s", name "%s", and display name "%s" was created.' % (value['id'], value['customTargetingKeyId'], value['name'], value['displayName'])) else: diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py index a3b58a9a..ed87ad62 100755 --- a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py @@ -59,8 +59,8 @@ def main(client, key_id): # Display results. if keys: for key in keys: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was updated.' + print ('Custom targeting key with id "%s", name "%s", display name ' + '"%s", and type "%s" was updated.' % (key['id'], key['name'], key['displayName'], key['type'])) else: print 'No custom targeting keys were found to update.' diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py index dac99134..ca09f287 100755 --- a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py @@ -60,8 +60,8 @@ def main(client, key_id): # Display results. for value in values: - print ('Custom targeting value with id \'%s\', name \'%s\', and display' - ' name \'%s\' was updated.' + print ('Custom targeting value with id "%s", name "%s", and display' + ' name "%s" was updated.' % (value['id'], value['name'], value['displayName'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: diff --git a/examples/dfp/v201702/inventory_service/archive_ad_units.py b/examples/dfp/v201702/inventory_service/archive_ad_units.py index 3be7b81a..b1097b3b 100755 --- a/examples/dfp/v201702/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201702/inventory_service/archive_ad_units.py @@ -57,7 +57,7 @@ def main(client, parent_id): statement.ToStatement()) if 'results' in response: for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' will be archived.' + print ('Ad unit with ID "%s" and name "%s" will be archived.' % (ad_unit['id'], ad_unit['name'])) # Perform action. result = inventory_service.performAdUnitAction( diff --git a/examples/dfp/v201702/inventory_service/create_ad_units.py b/examples/dfp/v201702/inventory_service/create_ad_units.py index 12f157f5..6cf363df 100755 --- a/examples/dfp/v201702/inventory_service/create_ad_units.py +++ b/examples/dfp/v201702/inventory_service/create_ad_units.py @@ -61,7 +61,7 @@ def main(client, parent_id): # Display results. for ad_unit in ad_units: - print ('Ad unit with ID \'%s\' and name \'%s\' was created.' + print ('Ad unit with ID "%s" and name "%s" was created.' % (ad_unit['id'], ad_unit['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/inventory_service/update_ad_units.py b/examples/dfp/v201702/inventory_service/update_ad_units.py index 080cb4a7..75cec0aa 100755 --- a/examples/dfp/v201702/inventory_service/update_ad_units.py +++ b/examples/dfp/v201702/inventory_service/update_ad_units.py @@ -78,7 +78,7 @@ def main(client, ad_unit_id): ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], size['size']['height']) for size in ad_unit['adUnitSizes']] - print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated' + print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) if __name__ == '__main__': diff --git a/examples/dfp/v201702/label_service/create_labels.py b/examples/dfp/v201702/label_service/create_labels.py index b65df339..4c71d810 100755 --- a/examples/dfp/v201702/label_service/create_labels.py +++ b/examples/dfp/v201702/label_service/create_labels.py @@ -46,7 +46,7 @@ def main(client): # Display results. for label in labels: - print ('Label with id \'%s\', name \'%s\', and types {%s} was found.' + print ('Label with id "%s", name "%s", and types {%s} was found.' % (label['id'], label['name'], ','.join(label['types']))) if __name__ == '__main__': diff --git a/examples/dfp/v201702/label_service/deactivate_labels.py b/examples/dfp/v201702/label_service/deactivate_labels.py index 49fd43af..d9e0e71a 100755 --- a/examples/dfp/v201702/label_service/deactivate_labels.py +++ b/examples/dfp/v201702/label_service/deactivate_labels.py @@ -47,7 +47,7 @@ def main(client): response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' will be ' + print ('Label with id "%s" and name "%s" will be ' 'deactivated.' % (label['id'], label['name'])) # Perform action. result = label_service.performLabelAction( diff --git a/examples/dfp/v201702/label_service/update_labels.py b/examples/dfp/v201702/label_service/update_labels.py index 5cc83410..dc1b3ffe 100755 --- a/examples/dfp/v201702/label_service/update_labels.py +++ b/examples/dfp/v201702/label_service/update_labels.py @@ -58,7 +58,7 @@ def main(client, label_id): labels = label_service.updateLabels(updated_labels) for label in labels: - print ('Label with id \'%s\' and name \'%s\' was updated.' + print ('Label with id "%s" and name "%s" was updated.' % (label['id'], label['name'])) else: print 'No labels found to update.' diff --git a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py b/examples/dfp/v201702/line_item_creative_association_service/create_licas.py index e66ebe2d..13743d0a 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/create_licas.py @@ -45,8 +45,8 @@ def main(client, line_item_id, creative_ids): # Display results. if licas: for lica in licas: - print ('LICA with line item id \'%s\', creative id \'%s\', and ' - 'status \'%s\' was created.' % + print ('LICA with line item id "%s", creative id "%s", and ' + 'status "%s" was created.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) else: print 'No LICAs created.' diff --git a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py index 6e835fb8..537ee699 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py @@ -57,8 +57,8 @@ def main(client, line_item_id): statement.ToStatement()) if 'results' in response: for lica in response['results']: - print ('LICA with line item id \'%s\', creative id \'%s\', and status' - ' \'%s\' will be deactivated.' % + print ('LICA with line item id "%s", creative id "%s", and status' + ' "%s" will be deactivated.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) # Perform action. diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py index 459bd82c..ecb592cc 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py @@ -37,8 +37,8 @@ def main(client): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % + print('LICA with line item ID "%s", creative set ID "%s", and ' + 'status "%s" was found.' % (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: print('Line item creative association with line item ID "%d" and ' diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py index 6131cdaf..d61f98f5 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py @@ -46,8 +46,8 @@ def main(client, line_item_id): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % + print('LICA with line item ID "%s", creative set ID "%s", and ' + 'status "%s" was found.' % (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: print('Line item creative association with line item ID "%d" and ' diff --git a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py index 775ce179..d78b2de9 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py @@ -50,9 +50,9 @@ def main(client): # Display results. for lica in licas: - print ('LICA with line item id \'%s\', creative id \'%s\', and status ' - '\'%s\' was updated.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print ('LICA with line item id "%s", creative id "%s", and status ' + '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], + lica['status'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201702/line_item_service/activate_line_items.py b/examples/dfp/v201702/line_item_service/activate_line_items.py index 83f658d4..91dc966b 100755 --- a/examples/dfp/v201702/line_item_service/activate_line_items.py +++ b/examples/dfp/v201702/line_item_service/activate_line_items.py @@ -60,8 +60,8 @@ def main(client, order_id): statement.ToStatement()) if 'results' in response: for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'name \'%s\' will be activated.' % + print ('Line item with id "%s", belonging to order id "%s", and ' + 'name "%s" will be activated.' % (line_item['id'], line_item['orderId'], line_item['name'])) # Perform action. diff --git a/examples/dfp/v201702/line_item_service/create_line_items.py b/examples/dfp/v201702/line_item_service/create_line_items.py index d6df276d..10ab761b 100755 --- a/examples/dfp/v201702/line_item_service/create_line_items.py +++ b/examples/dfp/v201702/line_item_service/create_line_items.py @@ -161,9 +161,9 @@ def main(client, order_id, targeted_placement_ids): # Display results. for line_item in line_items: - print ('Line item with id \'%s\', belonging to order id \'%s\', and named ' - '\'%s\' was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print ('Line item with id "%s", belonging to order id "%s", and named ' + '"%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201702/line_item_service/create_video_line_item.py b/examples/dfp/v201702/line_item_service/create_video_line_item.py index 1c238363..e02c4062 100755 --- a/examples/dfp/v201702/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201702/line_item_service/create_video_line_item.py @@ -130,9 +130,9 @@ def main(client, order_id, targeted_video_ad_unit_id, line_item = line_item_service.createLineItem(line_item) # Display results. - print ('Video line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print ('Video line item with id "%s", belonging to order id "%s", and ' + 'named "%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201702/line_item_service/target_custom_criteria.py b/examples/dfp/v201702/line_item_service/target_custom_criteria.py index 18f6258a..e622c627 100755 --- a/examples/dfp/v201702/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201702/line_item_service/target_custom_criteria.py @@ -101,7 +101,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Display results. if line_item: - print ('Line item with id \'%s\' updated with custom criteria targeting:' + print ('Line item with id "%s" updated with custom criteria targeting:' % line_item['id']) pprint.pprint(line_item['targeting']['customTargeting']) else: diff --git a/examples/dfp/v201702/line_item_service/update_line_items.py b/examples/dfp/v201702/line_item_service/update_line_items.py index f380edbc..62e2371b 100755 --- a/examples/dfp/v201702/line_item_service/update_line_items.py +++ b/examples/dfp/v201702/line_item_service/update_line_items.py @@ -67,8 +67,8 @@ def main(client, order_id): # Display results. if line_items: for line_item in line_items: - print ('Line item with id \'%s\', belonging to order id \'%s\', named ' - '\'%s\', and delivery rate \'%s\' was updated.' + print ('Line item with id "%s", belonging to order id "%s", named ' + '"%s", and delivery rate "%s" was updated.' % (line_item['id'], line_item['orderId'], line_item['name'], line_item['deliveryRateType'])) else: diff --git a/examples/dfp/v201702/network_service/get_all_networks.py b/examples/dfp/v201702/network_service/get_all_networks.py index ed1bb3ef..62107fd8 100755 --- a/examples/dfp/v201702/network_service/get_all_networks.py +++ b/examples/dfp/v201702/network_service/get_all_networks.py @@ -28,7 +28,7 @@ def main(client): # Print out some information for each network. for network in networks: - print('Network with network code \'%s\' and display name \'%s\' was found.' + print('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) print '\nNumber of results found: %s' % len(networks) diff --git a/examples/dfp/v201702/network_service/make_test_network.py b/examples/dfp/v201702/network_service/make_test_network.py index 31397585..f5d0b37f 100755 --- a/examples/dfp/v201702/network_service/make_test_network.py +++ b/examples/dfp/v201702/network_service/make_test_network.py @@ -40,7 +40,7 @@ def main(client): network = network_service.makeTestNetwork() # Display results. - print ('Test network with network code \'%s\' and display name \'%s\' ' + print ('Test network with network code "%s" and display name "%s" ' 'created.' % (network['networkCode'], network['displayName'])) print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s' % network['networkCode']) diff --git a/examples/dfp/v201702/order_service/approve_orders.py b/examples/dfp/v201702/order_service/approve_orders.py index 15fdaf71..e39fba4e 100755 --- a/examples/dfp/v201702/order_service/approve_orders.py +++ b/examples/dfp/v201702/order_service/approve_orders.py @@ -51,7 +51,7 @@ def main(client): if 'results' in response: # Display results. for order in response['results']: - print ('Order with id \'%s\', name \'%s\', and status \'%s\' will be ' + print ('Order with id "%s", name "%s", and status "%s" will be ' 'approved.' % (order['id'], order['name'], order['status'])) # Perform action. result = order_service.performOrderAction( diff --git a/examples/dfp/v201702/order_service/create_orders.py b/examples/dfp/v201702/order_service/create_orders.py index a7bd18a9..8d05ef74 100755 --- a/examples/dfp/v201702/order_service/create_orders.py +++ b/examples/dfp/v201702/order_service/create_orders.py @@ -50,7 +50,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Display results. for order in orders: - print ('Order with id \'%s\' and name \'%s\' was created.' + print ('Order with id "%s" and name "%s" was created.' % (order['id'], order['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/order_service/update_orders.py b/examples/dfp/v201702/order_service/update_orders.py index c4cda3e2..fe962a03 100755 --- a/examples/dfp/v201702/order_service/update_orders.py +++ b/examples/dfp/v201702/order_service/update_orders.py @@ -60,8 +60,8 @@ def main(client, order_id): # Display results. if orders: for order in orders: - print ('Order with id \'%s\', name \'%s\', advertiser id \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Order with id "%s", name "%s", advertiser id "%s", and ' + 'notes "%s" was updated.' % (order['id'], order['name'], order['advertiserId'], order['notes'])) else: diff --git a/examples/dfp/v201702/package_service/create_packages.py b/examples/dfp/v201702/package_service/create_packages.py index 3b4929b8..21dce743 100755 --- a/examples/dfp/v201702/package_service/create_packages.py +++ b/examples/dfp/v201702/package_service/create_packages.py @@ -51,7 +51,7 @@ def main(client): result = package_service.createPackages([package]) for new_package in result: - print ('A package with ID %d and name \'%s\' was created' % + print ('A package with ID %d and name "%s" was created' % (new_package['id'], new_package['name'])) diff --git a/examples/dfp/v201702/placement_service/create_placements.py b/examples/dfp/v201702/placement_service/create_placements.py index d524bcb9..e2de6ff3 100755 --- a/examples/dfp/v201702/placement_service/create_placements.py +++ b/examples/dfp/v201702/placement_service/create_placements.py @@ -98,7 +98,7 @@ def main(client): ad_unit_ids = '' if 'targetedAdUnitIds' in placement: ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) - print ('A Placement with ID \'%s\', name \'%s\', and containing ad units ' + print ('A Placement with ID "%s", name "%s", and containing ad units ' '{%s} was created.' % (placement['id'], placement['name'], ad_unit_ids)) diff --git a/examples/dfp/v201702/placement_service/deactivate_placements.py b/examples/dfp/v201702/placement_service/deactivate_placements.py index 7f840ec4..a7ef1a57 100755 --- a/examples/dfp/v201702/placement_service/deactivate_placements.py +++ b/examples/dfp/v201702/placement_service/deactivate_placements.py @@ -46,7 +46,7 @@ def main(client, placement_id): statement.ToStatement()) for placement in placements: - print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be ' + print ('Placement with id "%s", name "%s", and status "%s" will be ' 'deactivated.' % (placement['id'], placement['name'], placement['status'])) diff --git a/examples/dfp/v201702/placement_service/update_placements.py b/examples/dfp/v201702/placement_service/update_placements.py index 838c6add..8c79b94b 100755 --- a/examples/dfp/v201702/placement_service/update_placements.py +++ b/examples/dfp/v201702/placement_service/update_placements.py @@ -55,8 +55,8 @@ def main(client, placement_id): placements = placement_service.updatePlacements(placements) for placement in placements: - print ('Placement with id \'%s\', name \'%s\', and AdSense targeting ' - 'enabled \'%s\' was updated.' + print ('Placement with id "%s", name "%s", and AdSense targeting ' + 'enabled "%s" was updated.' % (placement['id'], placement['name'], placement['isAdSenseTargetingEnabled'])) diff --git a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py b/examples/dfp/v201702/premium_rate_service/create_premium_rates.py index 665e3676..151942f9 100755 --- a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/create_premium_rates.py @@ -70,8 +70,8 @@ def main(client, rate_card_id): # Display results. for premium_rate in premium_rates: - print ('A premium rate for \'%s\' was added to the rate card with ID' - ' of \'%s\'.\n' + print ('A premium rate for "%s" was added to the rate card with ID' + ' of "%s".\n' % (dfp.DfpClassType(premium_rate['premiumFeature']), premium_rate['id'])) diff --git a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py b/examples/dfp/v201702/premium_rate_service/update_premium_rates.py index 92f6ef31..97cdd2e6 100755 --- a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/update_premium_rates.py @@ -76,9 +76,9 @@ def main(client, premium_rate_id): # Display results. if premium_rates: for premium_rate in premium_rates: - print ('Premium rate with ID \'%s\', associated with rate card id' - ' \'%s\' was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) + print ('Premium rate with ID "%s", associated with rate card id' + ' "%s" was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) else: print 'No premium rates were updated.' else: diff --git a/examples/dfp/v201702/product_package_service/create_product_packages.py b/examples/dfp/v201702/product_package_service/create_product_packages.py index 12310f60..4cd048e2 100755 --- a/examples/dfp/v201702/product_package_service/create_product_packages.py +++ b/examples/dfp/v201702/product_package_service/create_product_packages.py @@ -41,7 +41,7 @@ def main(client): result = product_package_service.createProductPackages([product_package]) for new_product_package in result: - print ('A product package with ID %d and name \'%s\' was created.' % + print ('A product package with ID %d and name "%s" was created.' % (new_product_package['id'], new_product_package['name'])) diff --git a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py index 642c6861..3d9a1c1c 100755 --- a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py @@ -48,7 +48,7 @@ def main(client, product_id): statement.ToStatement()) if 'results' in response: for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' will be ' + print ('Product with id "%s" and name "%s" will be ' 'published.' % (product['id'], product['name'])) diff --git a/examples/dfp/v201702/product_service/update_products.py b/examples/dfp/v201702/product_service/update_products.py index 8d6798ab..d645f89e 100755 --- a/examples/dfp/v201702/product_service/update_products.py +++ b/examples/dfp/v201702/product_service/update_products.py @@ -58,8 +58,8 @@ def main(client, product_id): # Display results. if products: for product in products: - print ('Product with id \'%s\', name \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Product with id "%s", name "%s", and ' + 'notes "%s" was updated.' % (product['id'], product['name'], product['notes'])) else: print 'No products were updated.' diff --git a/examples/dfp/v201702/product_template_service/activate_product_templates.py b/examples/dfp/v201702/product_template_service/activate_product_templates.py index 71fed80d..ffda4dd4 100755 --- a/examples/dfp/v201702/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201702/product_template_service/activate_product_templates.py @@ -52,7 +52,7 @@ def main(client, product_template_id): statement.ToStatement()) if 'results' in response: for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' will be ' + print ('Product template with id "%s" and name "%s" will be ' 'activated.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201702/product_template_service/create_product_templates.py b/examples/dfp/v201702/product_template_service/create_product_templates.py index df5e079f..98ee1982 100755 --- a/examples/dfp/v201702/product_template_service/create_product_templates.py +++ b/examples/dfp/v201702/product_template_service/create_product_templates.py @@ -99,7 +99,7 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A product template with ID \'%s\' and name \'%s\' was ' + print ('A product template with ID "%s" and name "%s" was ' 'created.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py index dc1e4361..0ef99cf9 100755 --- a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py @@ -80,7 +80,7 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A programmatic product template with ID \'%s\' and name \'%s\' ' + print ('A programmatic product template with ID "%s" and name "%s" ' 'was created.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201702/product_template_service/update_product_templates.py b/examples/dfp/v201702/product_template_service/update_product_templates.py index 0dfd3df0..819a9772 100755 --- a/examples/dfp/v201702/product_template_service/update_product_templates.py +++ b/examples/dfp/v201702/product_template_service/update_product_templates.py @@ -84,7 +84,7 @@ def main(client, product_template_id): # Display results. if product_templates: for product_template in product_templates: - print ('Product template with id \'%s\' and name \'%s\' was ' + print ('Product template with id "%s" and name "%s" was ' 'updated.' % (product_template['id'], product_template['name'])) else: print 'No product templates were updated.' diff --git a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py index c4c67210..8584b71b 100755 --- a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py @@ -52,9 +52,9 @@ def main(client, proposal_line_item_id): statement.ToStatement()) if 'results' in response: for proposal_line_item in response['results']: - print ('Proposal line item with id \'%s\', ' - 'belonging to proposal id \'%s\', and ' - 'name \'%s\' will be archived.' % + print ('Proposal line item with id "%s", ' + 'belonging to proposal id "%s", and ' + 'name "%s" will be archived.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py index 6cabdcf7..19ebceab 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -106,8 +106,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item with id \'%s\', belonging to ' - 'proposal id \'%s\', and named \'%s\' was created.' % + print ('Programmatic proposal line item with id "%s", belonging to ' + 'proposal id "%s", and named "%s" was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 9a71f9a5..2338f4ca 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -112,7 +112,7 @@ def main(client, proposal_id, product_id): # Display results. for proposal_line_item in proposal_line_items: print ('Programmatic proposal line item for non-sales management with id ' - '\'%s\', belonging to proposal id \'%s\', and named \'%s\' ' + '"%s", belonging to proposal id "%s", and named "%s" ' 'was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py index 30b464a2..bc746b66 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py @@ -107,8 +107,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Proposal line item with id \'%s\', belonging to proposal id \'%s\'' - ', and named \'%s\' was created.' % + print ('Proposal line item with id "%s", belonging to proposal id "%s"' + ', and named "%s" was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py index b70f2d2c..64648a05 100755 --- a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py @@ -61,8 +61,8 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items: for proposal_line_item in proposal_line_items: - print ('Line item with id \'%s\', belonging to proposal id \'%s\' and,' - ' named \'%s\' was updated.' % ( + print ('Line item with id "%s", belonging to proposal id "%s" and,' + ' named "%s" was updated.' % ( proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) else: diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py index d1b3b011..5b009a95 100755 --- a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py @@ -60,7 +60,7 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, # Display results. for proposal in proposals: - print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + print('Programmatic proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 7978cb5a..2173f106 100755 --- a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -51,7 +51,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, # Display results. for proposal in proposals: - print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + print('Programmatic proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) diff --git a/examples/dfp/v201702/proposal_service/create_proposals.py b/examples/dfp/v201702/proposal_service/create_proposals.py index 679abc33..c8b43bcf 100755 --- a/examples/dfp/v201702/proposal_service/create_proposals.py +++ b/examples/dfp/v201702/proposal_service/create_proposals.py @@ -67,7 +67,7 @@ def main(client, advertiser_id, primary_salesperson_id, # Display results. for proposal in proposals: - print ('Proposal with id \'%s\' and name \'%s\' was created.' + print ('Proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py index 52bdac0f..89f3468a 100755 --- a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py @@ -48,10 +48,10 @@ def main(client, proposal_id): if 'results' in response: # Display results. for proposal in response['results']: - print ('Programmatic proposal with id \'%s\', name \'%s\', and status ' - '\'%s\' will be pushed to Marketplace.' % (proposal['id'], - proposal['name'], - proposal['status'])) + print ('Programmatic proposal with id "%s", name "%s", and status ' + '"%s" will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) diff --git a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py index 8b52311a..f87cf2eb 100755 --- a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py @@ -50,7 +50,7 @@ def main(client, proposal_id): if 'results' in response: # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\', name \'%s\', and status \'%s\' will be' + print ('Proposal with id "%s", name "%s", and status "%s" will be' ' approved.' % (proposal['id'], proposal['name'], proposal['status'])) # Perform action. diff --git a/examples/dfp/v201702/proposal_service/update_proposals.py b/examples/dfp/v201702/proposal_service/update_proposals.py index 3202ad84..41020d8d 100755 --- a/examples/dfp/v201702/proposal_service/update_proposals.py +++ b/examples/dfp/v201702/proposal_service/update_proposals.py @@ -58,8 +58,8 @@ def main(client, proposal_id): # Display results. if proposals: for proposal in proposals: - print ('Proposal with id \'%s\', name \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Proposal with id "%s", name "%s", and ' + 'notes "%s" was updated.' % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: print 'No proposals were updated.' diff --git a/examples/dfp/v201702/rate_card_service/create_rate_cards.py b/examples/dfp/v201702/rate_card_service/create_rate_cards.py index 86ae53a0..e75ee8bd 100755 --- a/examples/dfp/v201702/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201702/rate_card_service/create_rate_cards.py @@ -48,7 +48,7 @@ def main(client): result = rate_card_service.createRateCards([rate_card]) for new_rate_card in result: - print ('A rate card with ID %s, name \'%s\', and currency code \'%s\' ' + print ('A rate card with ID %s, name "%s", and currency code "%s" ' 'was created.' % (new_rate_card['id'], new_rate_card['name'], new_rate_card['currencyCode'])) diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 7825aa01..ad0ccee4 100755 --- a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -56,7 +56,7 @@ def main(client): # Iterate over individual results in the page. for line_item_report in page['results']: print ('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source \'%s\', and reconciled volume %d was ' + 'reconciliation source "%s", and reconciled volume %d was ' 'found.' % (line_item_report['id'], line_item_report['lineItemId'], line_item_report['reconciliationSource'], diff --git a/examples/dfp/v201702/report_service/run_delivery_report.py b/examples/dfp/v201702/report_service/run_delivery_report.py index 94b3b46c..74fdb3f3 100755 --- a/examples/dfp/v201702/report_service/run_delivery_report.py +++ b/examples/dfp/v201702/report_service/run_delivery_report.py @@ -83,7 +83,7 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201702/report_service/run_inventory_report.py b/examples/dfp/v201702/report_service/run_inventory_report.py index d408fda3..01994fe7 100755 --- a/examples/dfp/v201702/report_service/run_inventory_report.py +++ b/examples/dfp/v201702/report_service/run_inventory_report.py @@ -77,7 +77,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201702/report_service/run_reach_report.py b/examples/dfp/v201702/report_service/run_reach_report.py index eee890d2..10e06150 100755 --- a/examples/dfp/v201702/report_service/run_reach_report.py +++ b/examples/dfp/v201702/report_service/run_reach_report.py @@ -54,7 +54,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) diff --git a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py b/examples/dfp/v201702/report_service/run_report_with_custom_fields.py index 909652dc..5ad2f680 100755 --- a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201702/report_service/run_report_with_custom_fields.py @@ -94,7 +94,7 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201702/report_service/run_sales_report.py b/examples/dfp/v201702/report_service/run_sales_report.py index 7daedf37..5aab075c 100755 --- a/examples/dfp/v201702/report_service/run_sales_report.py +++ b/examples/dfp/v201702/report_service/run_sales_report.py @@ -55,7 +55,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201702/report_service/run_saved_query.py b/examples/dfp/v201702/report_service/run_saved_query.py index c501397a..7f3ccad5 100755 --- a/examples/dfp/v201702/report_service/run_saved_query.py +++ b/examples/dfp/v201702/report_service/run_saved_query.py @@ -73,7 +73,7 @@ def main(client, saved_query_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) else: print 'The query specified is not compatible with the API version.' diff --git a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py index bbeaa77f..cdf09c6f 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -52,7 +52,7 @@ def main(client): if 'results' in response: # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: - print ('Suggested ad unit with id \'%s\', and number of requests \'%s\'' + print ('Suggested ad unit with id "%s", and number of requests "%s"' ' will be approved.' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) diff --git a/examples/dfp/v201702/team_service/create_teams.py b/examples/dfp/v201702/team_service/create_teams.py index e250eeaa..f76ae2db 100755 --- a/examples/dfp/v201702/team_service/create_teams.py +++ b/examples/dfp/v201702/team_service/create_teams.py @@ -51,7 +51,7 @@ def main(client): # Display results. for team in teams: - print ('Team with ID \'%s\' and name \'%s\' was created.' + print ('Team with ID "%s" and name "%s" was created.' % (team['id'], team['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/team_service/update_teams.py b/examples/dfp/v201702/team_service/update_teams.py index b60f2930..7a3b8a94 100755 --- a/examples/dfp/v201702/team_service/update_teams.py +++ b/examples/dfp/v201702/team_service/update_teams.py @@ -62,7 +62,7 @@ def main(client, team_id): # Display results. for team in teams: - print ('Team with id \'%s\' and name \'%s\' was updated.' + print ('Team with id "%s" and name "%s" was updated.' % (team['id'], team['name'])) else: print 'No teams found to update.' diff --git a/examples/dfp/v201702/user_service/create_users.py b/examples/dfp/v201702/user_service/create_users.py index 0a90fa02..f375d01c 100755 --- a/examples/dfp/v201702/user_service/create_users.py +++ b/examples/dfp/v201702/user_service/create_users.py @@ -48,7 +48,7 @@ def main(client, email, name): # Display results. for user in users: - print ('User with id \'%s\', email \'%s\', and role \'%s\' was created.' + print ('User with id "%s", email "%s", and role "%s" was created.' % (user['id'], user['email'], user['roleName'])) if __name__ == '__main__': diff --git a/examples/dfp/v201702/user_service/deactivate_users.py b/examples/dfp/v201702/user_service/deactivate_users.py index cc5f6a42..16c07b35 100755 --- a/examples/dfp/v201702/user_service/deactivate_users.py +++ b/examples/dfp/v201702/user_service/deactivate_users.py @@ -50,7 +50,7 @@ def main(client, user_id): users = response['results'] if 'results' in response else [] for user in users: - print ('User with id \'%s\', email \'%s\', and status \'%s\' will be ' + print ('User with id "%s", email "%s", and status "%s" will be ' 'deactivated.' % (user['id'], user['email'], {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) diff --git a/examples/dfp/v201702/user_service/get_all_roles.py b/examples/dfp/v201702/user_service/get_all_roles.py index fb763029..bb2bec62 100755 --- a/examples/dfp/v201702/user_service/get_all_roles.py +++ b/examples/dfp/v201702/user_service/get_all_roles.py @@ -28,7 +28,7 @@ def main(client): # Print out some information for each role. for role in roles: - print('Role with id \'%s\' and name \'%s\' was found.' % + print('Role with id "%s" and name "%s" was found.' % (role['id'], role['name'])) print '\nNumber of results found: %s' % len(roles) diff --git a/examples/dfp/v201702/user_service/get_current_user.py b/examples/dfp/v201702/user_service/get_current_user.py index 81794ed3..56e5931b 100755 --- a/examples/dfp/v201702/user_service/get_current_user.py +++ b/examples/dfp/v201702/user_service/get_current_user.py @@ -27,7 +27,7 @@ def main(client): # Get current user. user = user_service.getCurrentUser() - print ('User with ID %d, name \'%s\', email \'%s\', and role \'%s\' ' + print ('User with ID %d, name "%s", email "%s", and role "%s" ' 'is the current user.' % ( user.id, user.name, user.email, user.roleName )) diff --git a/examples/dfp/v201702/user_service/update_users.py b/examples/dfp/v201702/user_service/update_users.py index 583594e6..07940545 100755 --- a/examples/dfp/v201702/user_service/update_users.py +++ b/examples/dfp/v201702/user_service/update_users.py @@ -54,7 +54,7 @@ def main(client, user_id): # Update users on server. users = user_service.updateUsers(users) for user in users: - print ('User with id \'%s\' and name \'%s\' was updated.' + print ('User with id "%s" and name "%s" was updated.' % (user['id'], user['name'])) else: print 'No users found to update.' diff --git a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py index 540c1da5..c882a441 100755 --- a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py @@ -55,9 +55,9 @@ def main(client, team_id, user_ids): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('A user team association between user with ID \'%s\' and team with' - ' ID \'%s\'was created.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('A user team association between user with ID "%s" and team with' + ' ID "%s"was created.' % (user_team_association['userId'], + user_team_association['teamId'])) else: print 'No user team associations created.' diff --git a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py index f1b0aac4..c971f0d8 100755 --- a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py @@ -56,9 +56,9 @@ def main(client, user_id): user_team_associations = response['results'] if 'results' in response else [] for user_team_association in user_team_associations: - print ('User team association between user with ID \'%s\' and team with ' - 'ID \'%s\' will be deleted.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('User team association between user with ID "%s" and team with ' + 'ID "%s" will be deleted.' % (user_team_association['userId'], + user_team_association['teamId'])) print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) diff --git a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py index c2608859..2b227542 100755 --- a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py @@ -71,9 +71,9 @@ def main(client, user_id): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was updated.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('User team association between user with ID "%s" and team with' + ' ID "%s" was updated.' % (user_team_association['userId'], + user_team_association['teamId'])) else: print 'No user team associations were updated.' else: diff --git a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py index da2d3536..f6a87a54 100755 --- a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py @@ -71,7 +71,7 @@ def main(client, proposal_id): if 'results' in response: # Display results. for workflow_approval_request in response['results']: - print ('Workflow approval request with id \'%s\' will be' + print ('Workflow approval request with id "%s" will be' ' approved.' % workflow_approval_request['id']) # Perform action. result = workflow_request_service.performWorkflowRequestAction( diff --git a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py index 4e39fd7f..fbbb267d 100755 --- a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -71,8 +71,8 @@ def main(client, proposal_id): if 'results' in response: # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id \'%s\' for %s ' - 'with id \'%s\' will be triggered.' % + print ('Workflow external condition request with id "%s" for %s ' + 'with id "%s" will be triggered.' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) diff --git a/examples/dfp/v201705/activity_group_service/create_activity_groups.py b/examples/dfp/v201705/activity_group_service/create_activity_groups.py index ab903e32..f1a8769e 100755 --- a/examples/dfp/v201705/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201705/activity_group_service/create_activity_groups.py @@ -62,7 +62,7 @@ def main(client, advertiser_company_id): # Display results. for activity_group in activity_groups: - print ('Activity group with ID \'%s\' and name \'%s\' was created.' + print ('Activity group with ID "%s" and name "%s" was created.' % (activity_group['id'], activity_group['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/activity_group_service/update_activity_groups.py b/examples/dfp/v201705/activity_group_service/update_activity_groups.py index 5d55d542..df1b623a 100755 --- a/examples/dfp/v201705/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201705/activity_group_service/update_activity_groups.py @@ -65,7 +65,7 @@ def main(client, activity_group_id, advertiser_company_id): updated_activity_groups) for activity_group in activity_groups: - print (('Activity group with ID \'%s\' and name \'%s\' was updated.') + print (('Activity group with ID "%s" and name "%s" was updated.') % (activity_group['id'], activity_group['name'])) else: print 'No activity groups found to update.' diff --git a/examples/dfp/v201705/activity_service/create_activities.py b/examples/dfp/v201705/activity_service/create_activities.py index fd9afebc..60adc312 100755 --- a/examples/dfp/v201705/activity_service/create_activities.py +++ b/examples/dfp/v201705/activity_service/create_activities.py @@ -59,7 +59,7 @@ def main(client, activity_group_id): # Display results. for activity in activities: - print ('An activity with ID \'%s\', name \'%s\', and type \'%s\' was ' + print ('An activity with ID "%s", name "%s", and type "%s" was ' 'created.' % (activity['id'], activity['name'], activity['type'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/activity_service/update_activities.py b/examples/dfp/v201705/activity_service/update_activities.py index b04c5f31..ae4bdcc0 100755 --- a/examples/dfp/v201705/activity_service/update_activities.py +++ b/examples/dfp/v201705/activity_service/update_activities.py @@ -61,7 +61,7 @@ def main(client, activity_id): activities = activity_service.updateActivities(updated_activities) for updated_activity in activities: - print (('Activity with ID \'%s\' and name \'%s\' was updated.') + print (('Activity with ID "%s" and name "%s" was updated.') % (updated_activity['id'], updated_activity['name'])) else: print 'No activities found to update.' diff --git a/examples/dfp/v201705/audience_segment_service/create_audience_segments.py b/examples/dfp/v201705/audience_segment_service/create_audience_segments.py index f580381b..3a942da6 100755 --- a/examples/dfp/v201705/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/create_audience_segments.py @@ -84,7 +84,7 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): audience_segment_service.createAudienceSegments(audience_segment)) for created_audience_segment in audience_segments: - print ('An audience segment with ID \'%s\', name \'%s\', and type \'%s\' ' + print ('An audience segment with ID "%s", name "%s", and type "%s" ' 'was created.' % (created_audience_segment['id'], created_audience_segment['name'], created_audience_segment['type'])) diff --git a/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py index 72cffa44..a3d7fc05 100755 --- a/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py @@ -57,7 +57,7 @@ def main(client, audience_segment_id): for segment in segments: print ( - 'Audience segment with id \'%s\' and name \'%s\' will be populated.' + 'Audience segment with id "%s" and name "%s" will be populated.' % (segment['id'], segment['name'])) action = { diff --git a/examples/dfp/v201705/audience_segment_service/update_audience_segments.py b/examples/dfp/v201705/audience_segment_service/update_audience_segments.py index a7723e62..0fdea19a 100755 --- a/examples/dfp/v201705/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/update_audience_segments.py @@ -55,7 +55,7 @@ def main(client, audience_segment_id): if 'results' in response: updated_audience_segments = [] for audience_segment in response['results']: - print ('Audience segment with id \'%s\' and name \'%s\' will be updated.' + print ('Audience segment with id "%s" and name "%s" will be updated.' % (audience_segment['id'], audience_segment['name'])) audience_segment['membershipExpirationDays'] = '180' @@ -65,7 +65,7 @@ def main(client, audience_segment_id): updated_audience_segments) for audience_segment in audience_segments: - print ('Audience segment with id \'%s\' and name \'%s\' was updated' % + print ('Audience segment with id "%s" and name "%s" was updated' % (audience_segment['id'], audience_segment['name'])) else: print 'No audience segment found to update.' diff --git a/examples/dfp/v201705/base_rate_service/create_product_base_rates.py b/examples/dfp/v201705/base_rate_service/create_product_base_rates.py index 8422c666..b8ae2eac 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/create_product_base_rates.py @@ -53,7 +53,7 @@ def main(client, product_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product base rate with ID \'%s\' and rate \'%.2f\' %s was ' + print ('A product base rate with ID "%s" and rate \'%.2f\' %s was ' 'created.' % (base_rate['id'], base_rate['rate']['microAmount'], base_rate['rate']['currencyCode'])) diff --git a/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py index 0e4e4f91..23b22bb2 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py @@ -53,7 +53,7 @@ def main(client, product_template_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product template base rate with ID \'%s\' and rate \'%.2f\' %s' + print ('A product template base rate with ID "%s" and rate \'%.2f\' %s' ' was created.' % (base_rate['id'], base_rate['rate']['microAmount'], base_rate['rate']['currencyCode'])) diff --git a/examples/dfp/v201705/base_rate_service/update_base_rates.py b/examples/dfp/v201705/base_rate_service/update_base_rates.py index 284f6e47..fd9510c0 100755 --- a/examples/dfp/v201705/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/update_base_rates.py @@ -64,8 +64,8 @@ def main(client, base_rate_id): # Display results. if base_rates: for base_rate in base_rates: - print ('Base rate with ID \'%s\' and type \'%s\' belonging to ' - 'rate card ID \'%s\' was updated.' % ( + print ('Base rate with ID "%s" and type "%s" belonging to ' + 'rate card ID "%s" was updated.' % ( base_rate['id'], dfp.DfpClassType(base_rate), base_rate['rateCardId'])) diff --git a/examples/dfp/v201705/company_service/create_companies.py b/examples/dfp/v201705/company_service/create_companies.py index cbaa7ff1..ac9b5994 100755 --- a/examples/dfp/v201705/company_service/create_companies.py +++ b/examples/dfp/v201705/company_service/create_companies.py @@ -53,7 +53,7 @@ def main(client): # Display results. for company in companies: - print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.' + print ('Company with ID "%s", name "%s", and type "%s" was created.' % (company['id'], company['name'], company['type'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/company_service/update_companies.py b/examples/dfp/v201705/company_service/update_companies.py index 78ecebd8..c6b76cca 100755 --- a/examples/dfp/v201705/company_service/update_companies.py +++ b/examples/dfp/v201705/company_service/update_companies.py @@ -62,7 +62,7 @@ def main(client, company_id): # Display results. for company in companies: - print (('Company with ID \'%s\', name \'%s\', and comment \'%s\'' + print (('Company with ID "%s", name "%s", and comment "%s"' 'was updated.') % (company['id'], company['name'], company['comment'])) else: diff --git a/examples/dfp/v201705/contact_service/create_contacts.py b/examples/dfp/v201705/contact_service/create_contacts.py index 634c774c..858c188a 100755 --- a/examples/dfp/v201705/contact_service/create_contacts.py +++ b/examples/dfp/v201705/contact_service/create_contacts.py @@ -62,7 +62,7 @@ def main(client, advertiser_company_id, agency_company_id): # Display results. for contact in contacts: - print ('Contact with ID \'%s\' name \'%s\' was created.' + print ('Contact with ID "%s" name "%s" was created.' % (contact['id'], contact['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/contact_service/update_contacts.py b/examples/dfp/v201705/contact_service/update_contacts.py index 772869a9..0bc86ca6 100755 --- a/examples/dfp/v201705/contact_service/update_contacts.py +++ b/examples/dfp/v201705/contact_service/update_contacts.py @@ -63,7 +63,7 @@ def main(client, contact_id): # Display results. for contact in contacts: - print (('Contact with ID \'%s\', name \'%s\', and address \'%s\' ' + print (('Contact with ID "%s", name "%s", and address "%s" ' 'was updated.') % (contact['id'], contact['name'], contact['address'])) else: diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 38b4b3b7..c0f39c37 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -68,7 +68,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Display results. for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id \'%s\' and name \'%s\'' + print ('Content metadata key hierarchy with id "%s" and name "%s"' ' was created.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index c605a231..986f2c1d 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -64,7 +64,7 @@ def main(client, content_metadata_key_hierarchy_id): # Display results. if content_metadata_key_hierarchies: for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with ID \'%s\' and name \'%s\' ' + print ('Content metadata key hierarchy with ID "%s" and name "%s" ' 'will be deleted.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 8a2995b9..e6dce35b 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -83,7 +83,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Display results. for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id \'%s\' and name \'%s\'' + print ('Content metadata key hierarchy with id "%s" and name "%s"' ' was updated.' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) diff --git a/examples/dfp/v201705/creative_service/copy_image_creatives.py b/examples/dfp/v201705/creative_service/copy_image_creatives.py index 9d0308cb..b1f69848 100755 --- a/examples/dfp/v201705/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201705/creative_service/copy_image_creatives.py @@ -47,7 +47,7 @@ def main(client): image_creative['name'] = 'Copy of %s' % image_creative['name'] result = creative_service.createCreatives([image_creative])[0] - print ('A creative with ID %d, name \'%s\', and type \'%s\' was created and ' + print ('A creative with ID %d, name "%s", and type "%s" was created and ' 'can be previewed at: %s' % (result['id'], result['name'], dfp.DfpClassType(result), diff --git a/examples/dfp/v201705/creative_service/create_creative_from_template.py b/examples/dfp/v201705/creative_service/create_creative_from_template.py index df861679..38d993e6 100755 --- a/examples/dfp/v201705/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201705/creative_service/create_creative_from_template.py @@ -102,7 +102,7 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201705/creative_service/create_creatives.py b/examples/dfp/v201705/creative_service/create_creatives.py index 419477d7..a9cb9884 100755 --- a/examples/dfp/v201705/creative_service/create_creatives.py +++ b/examples/dfp/v201705/creative_service/create_creatives.py @@ -80,7 +80,7 @@ def main(client, advertiser_id): # Display results. for creative in creatives: - print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Image creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201705/creative_service/create_custom_creative.py b/examples/dfp/v201705/creative_service/create_custom_creative.py index 32dcf3fc..abc6b632 100755 --- a/examples/dfp/v201705/creative_service/create_custom_creative.py +++ b/examples/dfp/v201705/creative_service/create_custom_creative.py @@ -49,7 +49,7 @@ def main(client, advertiser_id): image_data = base64.encodestring(image_data) # Create the HTML snippet used in the custom creative. - html_snippet = ('
Click above for ' + html_snippet = ('
Click above for ' 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%', '%%FILE:IMAGE_ASSET%%') @@ -79,7 +79,7 @@ def main(client, advertiser_id): # Display results. if creatives: creative = creatives[0] - print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was ' + print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], dfp.DfpClassType(creative), creative['previewUrl'])) diff --git a/examples/dfp/v201705/creative_service/create_native_creative.py b/examples/dfp/v201705/creative_service/create_native_creative.py index d7a7c3c1..b32309a3 100755 --- a/examples/dfp/v201705/creative_service/create_native_creative.py +++ b/examples/dfp/v201705/creative_service/create_native_creative.py @@ -125,7 +125,7 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Native creative with id \'%s\' and name \'%s\' was ' + print ('Native creative with id "%s" and name "%s" was ' 'created and can be previewed at %s.' % (creative['id'], creative['name'], creative['previewUrl'])) diff --git a/examples/dfp/v201705/creative_service/update_creatives.py b/examples/dfp/v201705/creative_service/update_creatives.py index 8d10156a..82400db5 100755 --- a/examples/dfp/v201705/creative_service/update_creatives.py +++ b/examples/dfp/v201705/creative_service/update_creatives.py @@ -69,7 +69,7 @@ def main(client, image_creative_id): # Display results. for creative in creatives: - print ('Image creative with id \'%s\' and destination URL \'%s\' was ' + print ('Image creative with id "%s" and destination URL "%s" was ' 'updated.' % (creative['id'], creative['destinationUrl'])) else: print 'No creatives found to update.' diff --git a/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py index b5e98713..bd800084 100755 --- a/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py @@ -46,7 +46,7 @@ def main(client, creative_set_id, line_item_id): lica = lica_service.createLineItemCreativeAssociations([lica]) # Display results. - print (('LICA with line item ID \'%s\' and creative set ID \'%s\' was ' + print (('LICA with line item ID "%s" and creative set ID "%s" was ' 'created.') % (lica['lineItemId'], lica['creativeSetId'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/creative_set_service/create_creative_set.py b/examples/dfp/v201705/creative_set_service/create_creative_set.py index ef60d411..55764d11 100755 --- a/examples/dfp/v201705/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201705/creative_set_service/create_creative_set.py @@ -50,7 +50,7 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' + print (('Creative set with ID "%s", master creative ID "%s", and ' 'companion creative IDs {%s} was created.') % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) diff --git a/examples/dfp/v201705/creative_set_service/update_creative_set.py b/examples/dfp/v201705/creative_set_service/update_creative_set.py index b8289d3c..94cdd8e3 100755 --- a/examples/dfp/v201705/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201705/creative_set_service/update_creative_set.py @@ -65,7 +65,7 @@ def main(client, creative_set_id, companion_creative_id): # Display results. for creative_set in creative_sets: - print (('Creative set with ID \'%s\', master creative ID \'%s\', and ' + print (('Creative set with ID "%s", master creative ID "%s", and ' 'companion creative IDs {%s} was updated.') % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) diff --git a/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py index f0ce0521..d09aa48d 100755 --- a/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py @@ -54,7 +54,7 @@ def main(client, label_id): # Display results. for creative_wrapper in creative_wrappers: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' was ' + print ('Creative wrapper with ID "%s" applying to label "%s" was ' 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py index bf72c2ea..229980be 100755 --- a/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py @@ -61,8 +61,8 @@ def main(client, label_id): if 'results' in response: # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID \'%s\' applying to label \'%s\' with ' - 'status \'%s\' will be deactivated.' % + print ('Creative wrapper with ID "%s" applying to label "%s" with ' + 'status "%s" will be deactivated.' % (creative_wrapper['id'], creative_wrapper['labelId'], creative_wrapper['status'])) diff --git a/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py index ae0a6e83..21258f0b 100755 --- a/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py @@ -65,7 +65,7 @@ def main(client, creative_wrapper_id): # Display results. for creative_wrapper in creative_wrappers: - print (('Creative wrapper with ID \'%s\' and wrapping order \'%s\' ' + print (('Creative wrapper with ID "%s" and wrapping order "%s" ' 'was updated.') % (creative_wrapper['id'], creative_wrapper['ordering'])) else: diff --git a/examples/dfp/v201705/custom_field_service/create_custom_field_options.py b/examples/dfp/v201705/custom_field_service/create_custom_field_options.py index 01c75244..182fc145 100755 --- a/examples/dfp/v201705/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201705/custom_field_service/create_custom_field_options.py @@ -58,7 +58,7 @@ def main(client, custom_field_id): # Display results. for custom_field_option in custom_field_options: - print ('Custom field option with ID \'%s\' and name \'%s\' was created.' + print ('Custom field option with ID "%s" and name "%s" was created.' % (custom_field_option['id'], custom_field_option['displayName'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/custom_field_service/create_custom_fields.py b/examples/dfp/v201705/custom_field_service/create_custom_fields.py index a02265dc..89d1069e 100755 --- a/examples/dfp/v201705/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201705/custom_field_service/create_custom_fields.py @@ -57,7 +57,7 @@ def main(client): # Display results. for custom_field in custom_fields: - print ('Custom field with ID \'%s\' and name \'%s\' was created.' + print ('Custom field with ID "%s" and name "%s" was created.' % (custom_field['id'], custom_field['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py index 3d3b2446..ece9ff34 100755 --- a/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -64,7 +64,7 @@ def main(client): if 'results' in response: # Display results. for custom_field in response['results']: - print ('Custom field with ID \'%s\' and name \'%s\' will' + print ('Custom field with ID "%s" and name "%s" will' ' be deactivated.' % (custom_field['id'], custom_field['name'])) result = custom_field_service.performCustomFieldAction( {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) diff --git a/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py index 0951a546..5080e010 100755 --- a/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py @@ -137,14 +137,14 @@ def main(client, custom_field_id, drop_down_custom_field_id, for value in line_item['customFieldValues']: if dfp.DfpClassType(value) == 'CustomFieldValue': custom_field_value_string = ( - '{ID: \'%s\', value: \'%s\'}' + '{ID: "%s", value: "%s"}' % (value['customFieldId'], value['value']['value'])) elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( - '{ID: \'%s\', custom field option ID: \'%s\'}' + '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) custom_field_value_strings.append(custom_field_value_string) - print ('Line item with ID \'%s\' set with custom field values %s.' + print ('Line item with ID "%s" set with custom field values %s.' % (line_item['id'], ','.join(custom_field_value_strings))) else: print 'Line item or custom field not found.' diff --git a/examples/dfp/v201705/custom_field_service/update_custom_fields.py b/examples/dfp/v201705/custom_field_service/update_custom_fields.py index 73cf0845..7a1b54c0 100755 --- a/examples/dfp/v201705/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201705/custom_field_service/update_custom_fields.py @@ -62,8 +62,8 @@ def main(client, custom_field_id): # Display results. for custom_field in custom_fields: - print (('Custom field with ID \'%s\', name \'%s\', and ' - 'description \'%s\' was updated.') + print (('Custom field with ID "%s", name "%s", and ' + 'description "%s" was updated.') % (custom_field['id'], custom_field['name'], custom_field['description'])) else: diff --git a/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py index e337aebf..0c979863 100755 --- a/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -63,9 +63,9 @@ def main(client): # Display results. if keys: for key in keys: - print ('A custom targeting key with id \'%s\', name \'%s\', and display ' - 'name \'%s\' was created.' % (key['id'], key['name'], - key['displayName'])) + print ('A custom targeting key with id "%s", name "%s", and display ' + 'name "%s" was created.' % (key['id'], key['name'], + key['displayName'])) else: print 'No keys were created.' @@ -119,8 +119,8 @@ def main(client): # Display results. if values: for value in values: - print ('A custom targeting value with id \'%s\', belonging to key with id' - ' \'%s\', name \'%s\', and display name \'%s\' was created.' + print ('A custom targeting value with id "%s", belonging to key with id' + ' "%s", name "%s", and display name "%s" was created.' % (value['id'], value['customTargetingKeyId'], value['name'], value['displayName'])) else: diff --git a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py index a6bbeebe..738097d6 100755 --- a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py @@ -59,8 +59,8 @@ def main(client, key_id): # Display results. if keys: for key in keys: - print ('Custom targeting key with id \'%s\', name \'%s\', display name ' - '\'%s\', and type \'%s\' was updated.' + print ('Custom targeting key with id "%s", name "%s", display name ' + '"%s", and type "%s" was updated.' % (key['id'], key['name'], key['displayName'], key['type'])) else: print 'No custom targeting keys were found to update.' diff --git a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py index 1cc85c81..edf57cd7 100755 --- a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py @@ -60,8 +60,8 @@ def main(client, key_id): # Display results. for value in values: - print ('Custom targeting value with id \'%s\', name \'%s\', and display' - ' name \'%s\' was updated.' + print ('Custom targeting value with id "%s", name "%s", and display' + ' name "%s" was updated.' % (value['id'], value['name'], value['displayName'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: diff --git a/examples/dfp/v201705/inventory_service/archive_ad_units.py b/examples/dfp/v201705/inventory_service/archive_ad_units.py index 753304b2..72aae7d5 100755 --- a/examples/dfp/v201705/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201705/inventory_service/archive_ad_units.py @@ -57,7 +57,7 @@ def main(client, parent_id): statement.ToStatement()) if 'results' in response: for ad_unit in response['results']: - print ('Ad unit with ID \'%s\' and name \'%s\' will be archived.' + print ('Ad unit with ID "%s" and name "%s" will be archived.' % (ad_unit['id'], ad_unit['name'])) # Perform action. result = inventory_service.performAdUnitAction( diff --git a/examples/dfp/v201705/inventory_service/create_ad_units.py b/examples/dfp/v201705/inventory_service/create_ad_units.py index bc8ddc7a..0781c1b7 100755 --- a/examples/dfp/v201705/inventory_service/create_ad_units.py +++ b/examples/dfp/v201705/inventory_service/create_ad_units.py @@ -61,7 +61,7 @@ def main(client, parent_id): # Display results. for ad_unit in ad_units: - print ('Ad unit with ID \'%s\' and name \'%s\' was created.' + print ('Ad unit with ID "%s" and name "%s" was created.' % (ad_unit['id'], ad_unit['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/inventory_service/update_ad_units.py b/examples/dfp/v201705/inventory_service/update_ad_units.py index 09ad3296..3c601f56 100755 --- a/examples/dfp/v201705/inventory_service/update_ad_units.py +++ b/examples/dfp/v201705/inventory_service/update_ad_units.py @@ -78,7 +78,7 @@ def main(client, ad_unit_id): ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], size['size']['height']) for size in ad_unit['adUnitSizes']] - print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated' + print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) if __name__ == '__main__': diff --git a/examples/dfp/v201705/label_service/create_labels.py b/examples/dfp/v201705/label_service/create_labels.py index a9e68ec1..6e99a2f8 100755 --- a/examples/dfp/v201705/label_service/create_labels.py +++ b/examples/dfp/v201705/label_service/create_labels.py @@ -46,7 +46,7 @@ def main(client): # Display results. for label in labels: - print ('Label with id \'%s\', name \'%s\', and types {%s} was found.' + print ('Label with id "%s", name "%s", and types {%s} was found.' % (label['id'], label['name'], ','.join(label['types']))) if __name__ == '__main__': diff --git a/examples/dfp/v201705/label_service/deactivate_labels.py b/examples/dfp/v201705/label_service/deactivate_labels.py index 84882fa1..f44d2454 100755 --- a/examples/dfp/v201705/label_service/deactivate_labels.py +++ b/examples/dfp/v201705/label_service/deactivate_labels.py @@ -47,7 +47,7 @@ def main(client): response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: for label in response['results']: - print ('Label with id \'%s\' and name \'%s\' will be ' + print ('Label with id "%s" and name "%s" will be ' 'deactivated.' % (label['id'], label['name'])) # Perform action. result = label_service.performLabelAction( diff --git a/examples/dfp/v201705/label_service/update_labels.py b/examples/dfp/v201705/label_service/update_labels.py index 620836ff..236748f2 100755 --- a/examples/dfp/v201705/label_service/update_labels.py +++ b/examples/dfp/v201705/label_service/update_labels.py @@ -58,7 +58,7 @@ def main(client, label_id): labels = label_service.updateLabels(updated_labels) for label in labels: - print ('Label with id \'%s\' and name \'%s\' was updated.' + print ('Label with id "%s" and name "%s" was updated.' % (label['id'], label['name'])) else: print 'No labels found to update.' diff --git a/examples/dfp/v201705/line_item_creative_association_service/create_licas.py b/examples/dfp/v201705/line_item_creative_association_service/create_licas.py index 606cbc37..117caadb 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/create_licas.py @@ -45,8 +45,8 @@ def main(client, line_item_id, creative_ids): # Display results. if licas: for lica in licas: - print ('LICA with line item id \'%s\', creative id \'%s\', and ' - 'status \'%s\' was created.' % + print ('LICA with line item id "%s", creative id "%s", and ' + 'status "%s" was created.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) else: print 'No LICAs created.' diff --git a/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py index e4368471..89417839 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py @@ -57,8 +57,8 @@ def main(client, line_item_id): statement.ToStatement()) if 'results' in response: for lica in response['results']: - print ('LICA with line item id \'%s\', creative id \'%s\', and status' - ' \'%s\' will be deactivated.' % + print ('LICA with line item id "%s", creative id "%s", and status' + ' "%s" will be deactivated.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) # Perform action. diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py index d4d05a62..e670adea 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py @@ -37,8 +37,8 @@ def main(client): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % + print('LICA with line item ID "%s", creative set ID "%s", and ' + 'status "%s" was found.' % (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: print('Line item creative association with line item ID "%d" and ' diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py index 4884013a..3630dd39 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py @@ -46,8 +46,8 @@ def main(client, line_item_id): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: - print('LICA with line item ID \'%s\', creative set ID \'%s\', and ' - 'status \'%s\' was found.' % + print('LICA with line item ID "%s", creative set ID "%s", and ' + 'status "%s" was found.' % (lica['lineItemId'], lica['creativeSetId'], lica['status'])) else: print('Line item creative association with line item ID "%d" and ' diff --git a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py b/examples/dfp/v201705/line_item_creative_association_service/update_licas.py index 43b3baa8..fefe3090 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/update_licas.py @@ -50,9 +50,9 @@ def main(client): # Display results. for lica in licas: - print ('LICA with line item id \'%s\', creative id \'%s\', and status ' - '\'%s\' was updated.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print ('LICA with line item id "%s", creative id "%s", and status ' + '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], + lica['status'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break diff --git a/examples/dfp/v201705/line_item_service/activate_line_items.py b/examples/dfp/v201705/line_item_service/activate_line_items.py index 6089b870..090c845e 100755 --- a/examples/dfp/v201705/line_item_service/activate_line_items.py +++ b/examples/dfp/v201705/line_item_service/activate_line_items.py @@ -60,8 +60,8 @@ def main(client, order_id): statement.ToStatement()) if 'results' in response: for line_item in response['results']: - print ('Line item with id \'%s\', belonging to order id \'%s\', and ' - 'name \'%s\' will be activated.' % + print ('Line item with id "%s", belonging to order id "%s", and ' + 'name "%s" will be activated.' % (line_item['id'], line_item['orderId'], line_item['name'])) # Perform action. diff --git a/examples/dfp/v201705/line_item_service/create_line_items.py b/examples/dfp/v201705/line_item_service/create_line_items.py index 438b0480..9c2e9338 100755 --- a/examples/dfp/v201705/line_item_service/create_line_items.py +++ b/examples/dfp/v201705/line_item_service/create_line_items.py @@ -155,9 +155,9 @@ def main(client, order_id, targeted_placement_ids): # Display results. for line_item in line_items: - print ('Line item with id \'%s\', belonging to order id \'%s\', and named ' - '\'%s\' was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print ('Line item with id "%s", belonging to order id "%s", and named ' + '"%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201705/line_item_service/create_video_line_item.py b/examples/dfp/v201705/line_item_service/create_video_line_item.py index 9a9f3c8e..63b94339 100755 --- a/examples/dfp/v201705/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201705/line_item_service/create_video_line_item.py @@ -124,9 +124,9 @@ def main(client, order_id, targeted_video_ad_unit_id, line_item = line_item_service.createLineItem(line_item) # Display results. - print ('Video line item with id \'%s\', belonging to order id \'%s\', and ' - 'named \'%s\' was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print ('Video line item with id "%s", belonging to order id "%s", and ' + 'named "%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201705/line_item_service/target_custom_criteria.py b/examples/dfp/v201705/line_item_service/target_custom_criteria.py index 4ba0dd29..de386341 100755 --- a/examples/dfp/v201705/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201705/line_item_service/target_custom_criteria.py @@ -101,7 +101,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Display results. if line_item: - print ('Line item with id \'%s\' updated with custom criteria targeting:' + print ('Line item with id "%s" updated with custom criteria targeting:' % line_item['id']) pprint.pprint(line_item['targeting']['customTargeting']) else: diff --git a/examples/dfp/v201705/line_item_service/update_line_items.py b/examples/dfp/v201705/line_item_service/update_line_items.py index 9f819ec7..7360fcb0 100755 --- a/examples/dfp/v201705/line_item_service/update_line_items.py +++ b/examples/dfp/v201705/line_item_service/update_line_items.py @@ -67,8 +67,8 @@ def main(client, order_id): # Display results. if line_items: for line_item in line_items: - print ('Line item with id \'%s\', belonging to order id \'%s\', named ' - '\'%s\', and delivery rate \'%s\' was updated.' + print ('Line item with id "%s", belonging to order id "%s", named ' + '"%s", and delivery rate "%s" was updated.' % (line_item['id'], line_item['orderId'], line_item['name'], line_item['deliveryRateType'])) else: diff --git a/examples/dfp/v201705/network_service/get_all_networks.py b/examples/dfp/v201705/network_service/get_all_networks.py index 31eb685d..1d835878 100755 --- a/examples/dfp/v201705/network_service/get_all_networks.py +++ b/examples/dfp/v201705/network_service/get_all_networks.py @@ -28,7 +28,7 @@ def main(client): # Print out some information for each network. for network in networks: - print('Network with network code \'%s\' and display name \'%s\' was found.' + print('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) print '\nNumber of results found: %s' % len(networks) diff --git a/examples/dfp/v201705/network_service/make_test_network.py b/examples/dfp/v201705/network_service/make_test_network.py index 850e411c..72797388 100755 --- a/examples/dfp/v201705/network_service/make_test_network.py +++ b/examples/dfp/v201705/network_service/make_test_network.py @@ -40,7 +40,7 @@ def main(client): network = network_service.makeTestNetwork() # Display results. - print ('Test network with network code \'%s\' and display name \'%s\' ' + print ('Test network with network code "%s" and display name "%s" ' 'created.' % (network['networkCode'], network['displayName'])) print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s' % network['networkCode']) diff --git a/examples/dfp/v201705/order_service/approve_orders.py b/examples/dfp/v201705/order_service/approve_orders.py index d1bfee2b..173400dc 100755 --- a/examples/dfp/v201705/order_service/approve_orders.py +++ b/examples/dfp/v201705/order_service/approve_orders.py @@ -51,7 +51,7 @@ def main(client): if 'results' in response: # Display results. for order in response['results']: - print ('Order with id \'%s\', name \'%s\', and status \'%s\' will be ' + print ('Order with id "%s", name "%s", and status "%s" will be ' 'approved.' % (order['id'], order['name'], order['status'])) # Perform action. result = order_service.performOrderAction( diff --git a/examples/dfp/v201705/order_service/create_orders.py b/examples/dfp/v201705/order_service/create_orders.py index d911d238..d3a6a4cc 100755 --- a/examples/dfp/v201705/order_service/create_orders.py +++ b/examples/dfp/v201705/order_service/create_orders.py @@ -50,7 +50,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Display results. for order in orders: - print ('Order with id \'%s\' and name \'%s\' was created.' + print ('Order with id "%s" and name "%s" was created.' % (order['id'], order['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/order_service/update_orders.py b/examples/dfp/v201705/order_service/update_orders.py index 04d2f339..a6a6ab9b 100755 --- a/examples/dfp/v201705/order_service/update_orders.py +++ b/examples/dfp/v201705/order_service/update_orders.py @@ -60,8 +60,8 @@ def main(client, order_id): # Display results. if orders: for order in orders: - print ('Order with id \'%s\', name \'%s\', advertiser id \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Order with id "%s", name "%s", advertiser id "%s", and ' + 'notes "%s" was updated.' % (order['id'], order['name'], order['advertiserId'], order['notes'])) else: diff --git a/examples/dfp/v201705/package_service/create_packages.py b/examples/dfp/v201705/package_service/create_packages.py index a2cb8a28..3e22ba82 100755 --- a/examples/dfp/v201705/package_service/create_packages.py +++ b/examples/dfp/v201705/package_service/create_packages.py @@ -51,7 +51,7 @@ def main(client): result = package_service.createPackages([package]) for new_package in result: - print ('A package with ID %d and name \'%s\' was created' % + print ('A package with ID %d and name "%s" was created' % (new_package['id'], new_package['name'])) diff --git a/examples/dfp/v201705/placement_service/create_placements.py b/examples/dfp/v201705/placement_service/create_placements.py index 2f37f07e..b05669de 100755 --- a/examples/dfp/v201705/placement_service/create_placements.py +++ b/examples/dfp/v201705/placement_service/create_placements.py @@ -98,7 +98,7 @@ def main(client): ad_unit_ids = '' if 'targetedAdUnitIds' in placement: ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) - print ('A Placement with ID \'%s\', name \'%s\', and containing ad units ' + print ('A Placement with ID "%s", name "%s", and containing ad units ' '{%s} was created.' % (placement['id'], placement['name'], ad_unit_ids)) diff --git a/examples/dfp/v201705/placement_service/deactivate_placements.py b/examples/dfp/v201705/placement_service/deactivate_placements.py index 1c42338d..804772cb 100755 --- a/examples/dfp/v201705/placement_service/deactivate_placements.py +++ b/examples/dfp/v201705/placement_service/deactivate_placements.py @@ -46,7 +46,7 @@ def main(client, placement_id): statement.ToStatement()) for placement in placements: - print ('Placement with id \'%s\', name \'%s\', and status \'%s\' will be ' + print ('Placement with id "%s", name "%s", and status "%s" will be ' 'deactivated.' % (placement['id'], placement['name'], placement['status'])) diff --git a/examples/dfp/v201705/placement_service/update_placements.py b/examples/dfp/v201705/placement_service/update_placements.py index 64f37c19..371f6187 100755 --- a/examples/dfp/v201705/placement_service/update_placements.py +++ b/examples/dfp/v201705/placement_service/update_placements.py @@ -49,7 +49,7 @@ def main(client, placement_id): updated_placements = placement_service.updatePlacements([placement]) for placement in updated_placements: - print ("Placement with id \'%s\' and name '%s' was updated." + print ('Placement with id "%s" and name "%s" was updated.' % (placement['id'], placement['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/premium_rate_service/create_premium_rates.py b/examples/dfp/v201705/premium_rate_service/create_premium_rates.py index 7af12b3e..fa6b6b19 100755 --- a/examples/dfp/v201705/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201705/premium_rate_service/create_premium_rates.py @@ -73,8 +73,8 @@ def main(client, rate_card_id): # Display results. for premium_rate in premium_rates: - print ('A premium rate for \'%s\' was added to the rate card with ID' - ' of \'%s\'.\n' + print ('A premium rate for "%s" was added to the rate card with ID' + ' of "%s".\n' % (dfp.DfpClassType(premium_rate['premiumFeature']), premium_rate['id'])) diff --git a/examples/dfp/v201705/premium_rate_service/update_premium_rates.py b/examples/dfp/v201705/premium_rate_service/update_premium_rates.py index 7bc56a29..6058b78b 100755 --- a/examples/dfp/v201705/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201705/premium_rate_service/update_premium_rates.py @@ -76,9 +76,9 @@ def main(client, premium_rate_id): # Display results. if premium_rates: for premium_rate in premium_rates: - print ('Premium rate with ID \'%s\', associated with rate card id' - ' \'%s\' was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) + print ('Premium rate with ID "%s", associated with rate card id' + ' "%s" was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) else: print 'No premium rates were updated.' else: diff --git a/examples/dfp/v201705/product_package_service/create_product_packages.py b/examples/dfp/v201705/product_package_service/create_product_packages.py index 49ba7a3a..5c8f128c 100755 --- a/examples/dfp/v201705/product_package_service/create_product_packages.py +++ b/examples/dfp/v201705/product_package_service/create_product_packages.py @@ -41,7 +41,7 @@ def main(client): result = product_package_service.createProductPackages([product_package]) for new_product_package in result: - print ('A product package with ID %d and name \'%s\' was created.' % + print ('A product package with ID %d and name "%s" was created.' % (new_product_package['id'], new_product_package['name'])) diff --git a/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py index 843ab498..4ee33f05 100755 --- a/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py @@ -48,7 +48,7 @@ def main(client, product_id): statement.ToStatement()) if 'results' in response: for product in response['results']: - print ('Product with id \'%s\' and name \'%s\' will be ' + print ('Product with id "%s" and name "%s" will be ' 'published.' % (product['id'], product['name'])) diff --git a/examples/dfp/v201705/product_service/update_products.py b/examples/dfp/v201705/product_service/update_products.py index 28ce433b..af2905db 100755 --- a/examples/dfp/v201705/product_service/update_products.py +++ b/examples/dfp/v201705/product_service/update_products.py @@ -58,8 +58,8 @@ def main(client, product_id): # Display results. if products: for product in products: - print ('Product with id \'%s\', name \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Product with id "%s", name "%s", and ' + 'notes "%s" was updated.' % (product['id'], product['name'], product['notes'])) else: print 'No products were updated.' diff --git a/examples/dfp/v201705/product_template_service/activate_product_templates.py b/examples/dfp/v201705/product_template_service/activate_product_templates.py index 6914a56f..a15d5102 100755 --- a/examples/dfp/v201705/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201705/product_template_service/activate_product_templates.py @@ -52,7 +52,7 @@ def main(client, product_template_id): statement.ToStatement()) if 'results' in response: for product_template in response['results']: - print ('Product template with id \'%s\' and name \'%s\' will be ' + print ('Product template with id "%s" and name "%s" will be ' 'activated.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201705/product_template_service/create_product_templates.py b/examples/dfp/v201705/product_template_service/create_product_templates.py index a12ae992..94f5a3d3 100755 --- a/examples/dfp/v201705/product_template_service/create_product_templates.py +++ b/examples/dfp/v201705/product_template_service/create_product_templates.py @@ -99,7 +99,7 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A product template with ID \'%s\' and name \'%s\' was ' + print ('A product template with ID "%s" and name "%s" was ' 'created.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py index 60ec4793..3d917835 100755 --- a/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py @@ -80,7 +80,7 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A programmatic product template with ID \'%s\' and name \'%s\' ' + print ('A programmatic product template with ID "%s" and name "%s" ' 'was created.' % (product_template['id'], product_template['name'])) diff --git a/examples/dfp/v201705/product_template_service/update_product_templates.py b/examples/dfp/v201705/product_template_service/update_product_templates.py index 77b5f174..8116f7f3 100755 --- a/examples/dfp/v201705/product_template_service/update_product_templates.py +++ b/examples/dfp/v201705/product_template_service/update_product_templates.py @@ -84,7 +84,7 @@ def main(client, product_template_id): # Display results. if product_templates: for product_template in product_templates: - print ('Product template with id \'%s\' and name \'%s\' was ' + print ('Product template with id "%s" and name "%s" was ' 'updated.' % (product_template['id'], product_template['name'])) else: print 'No product templates were updated.' diff --git a/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py index b025e997..b2b6c76c 100755 --- a/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py @@ -52,9 +52,9 @@ def main(client, proposal_line_item_id): statement.ToStatement()) if 'results' in response: for proposal_line_item in response['results']: - print ('Proposal line item with id \'%s\', ' - 'belonging to proposal id \'%s\', and ' - 'name \'%s\' will be archived.' % + print ('Proposal line item with id "%s", ' + 'belonging to proposal id "%s", and ' + 'name "%s" will be archived.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py index 662dbb09..e9e2ab71 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -91,8 +91,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item with id \'%s\', belonging to ' - 'proposal id \'%s\', and named \'%s\' was created.' % + print ('Programmatic proposal line item with id "%s", belonging to ' + 'proposal id "%s", and named "%s" was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 461f4b7a..bb198790 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -97,7 +97,7 @@ def main(client, proposal_id, product_id): # Display results. for proposal_line_item in proposal_line_items: print ('Programmatic proposal line item for non-sales management with id ' - '\'%s\', belonging to proposal id \'%s\', and named \'%s\' ' + '"%s", belonging to proposal id "%s", and named "%s" ' 'was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py index 3dc6440c..616195f3 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py @@ -92,8 +92,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Proposal line item with id \'%s\', belonging to proposal id \'%s\'' - ', and named \'%s\' was created.' % + print ('Proposal line item with id "%s", belonging to proposal id "%s"' + ', and named "%s" was created.' % (proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) diff --git a/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py index 0139cffe..16f4bc98 100755 --- a/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py @@ -61,8 +61,8 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items: for proposal_line_item in proposal_line_items: - print ('Line item with id \'%s\', belonging to proposal id \'%s\' and,' - ' named \'%s\' was updated.' % ( + print ('Line item with id "%s", belonging to proposal id "%s" and,' + ' named "%s" was updated.' % ( proposal_line_item['id'], proposal_line_item['proposalId'], proposal_line_item['name'])) else: diff --git a/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py index dfe5a683..02277928 100755 --- a/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py @@ -60,7 +60,7 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, # Display results. for proposal in proposals: - print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + print('Programmatic proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) diff --git a/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 017a24d4..1db0c9e0 100755 --- a/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -51,7 +51,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, # Display results. for proposal in proposals: - print('Programmatic proposal with id \'%s\' and name \'%s\' was created.' % + print('Programmatic proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) diff --git a/examples/dfp/v201705/proposal_service/create_proposals.py b/examples/dfp/v201705/proposal_service/create_proposals.py index 26c261a5..d2a2e346 100755 --- a/examples/dfp/v201705/proposal_service/create_proposals.py +++ b/examples/dfp/v201705/proposal_service/create_proposals.py @@ -67,7 +67,7 @@ def main(client, advertiser_id, primary_salesperson_id, # Display results. for proposal in proposals: - print ('Proposal with id \'%s\' and name \'%s\' was created.' + print ('Proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py index 577e69d1..68e3598e 100755 --- a/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py @@ -48,10 +48,10 @@ def main(client, proposal_id): if 'results' in response: # Display results. for proposal in response['results']: - print ('Programmatic proposal with id \'%s\', name \'%s\', and status ' - '\'%s\' will be pushed to Marketplace.' % (proposal['id'], - proposal['name'], - proposal['status'])) + print ('Programmatic proposal with id "%s", name "%s", and status ' + '"%s" will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) diff --git a/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py index 4a8b98b4..51f8b2b2 100755 --- a/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py @@ -50,7 +50,7 @@ def main(client, proposal_id): if 'results' in response: # Display results. for proposal in response['results']: - print ('Proposal with id \'%s\', name \'%s\', and status \'%s\' will be' + print ('Proposal with id "%s", name "%s", and status "%s" will be' ' approved.' % (proposal['id'], proposal['name'], proposal['status'])) # Perform action. diff --git a/examples/dfp/v201705/proposal_service/update_proposals.py b/examples/dfp/v201705/proposal_service/update_proposals.py index b0d0dab6..7f4e6d13 100755 --- a/examples/dfp/v201705/proposal_service/update_proposals.py +++ b/examples/dfp/v201705/proposal_service/update_proposals.py @@ -58,8 +58,8 @@ def main(client, proposal_id): # Display results. if proposals: for proposal in proposals: - print ('Proposal with id \'%s\', name \'%s\', and ' - 'notes \'%s\' was updated.' + print ('Proposal with id "%s", name "%s", and ' + 'notes "%s" was updated.' % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: print 'No proposals were updated.' diff --git a/examples/dfp/v201705/rate_card_service/create_rate_cards.py b/examples/dfp/v201705/rate_card_service/create_rate_cards.py index e15299d1..38142f18 100755 --- a/examples/dfp/v201705/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201705/rate_card_service/create_rate_cards.py @@ -48,7 +48,7 @@ def main(client): result = rate_card_service.createRateCards([rate_card]) for new_rate_card in result: - print ('A rate card with ID %s, name \'%s\', and currency code \'%s\' ' + print ('A rate card with ID %s, name "%s", and currency code "%s" ' 'was created.' % (new_rate_card['id'], new_rate_card['name'], new_rate_card['currencyCode'])) diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 31b1337e..98a6c659 100755 --- a/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -56,7 +56,7 @@ def main(client): # Iterate over individual results in the page. for line_item_report in page['results']: print ('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source \'%s\', and reconciled volume %d was ' + 'reconciliation source "%s", and reconciled volume %d was ' 'found.' % (line_item_report['id'], line_item_report['lineItemId'], line_item_report['reconciliationSource'], diff --git a/examples/dfp/v201705/report_service/run_delivery_report.py b/examples/dfp/v201705/report_service/run_delivery_report.py index 098ec309..055969a3 100755 --- a/examples/dfp/v201705/report_service/run_delivery_report.py +++ b/examples/dfp/v201705/report_service/run_delivery_report.py @@ -83,7 +83,7 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201705/report_service/run_inventory_report.py b/examples/dfp/v201705/report_service/run_inventory_report.py index 329978f3..3e07905a 100755 --- a/examples/dfp/v201705/report_service/run_inventory_report.py +++ b/examples/dfp/v201705/report_service/run_inventory_report.py @@ -77,7 +77,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201705/report_service/run_reach_report.py b/examples/dfp/v201705/report_service/run_reach_report.py index 640e2887..ffd4f971 100755 --- a/examples/dfp/v201705/report_service/run_reach_report.py +++ b/examples/dfp/v201705/report_service/run_reach_report.py @@ -54,7 +54,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) diff --git a/examples/dfp/v201705/report_service/run_report_with_custom_fields.py b/examples/dfp/v201705/report_service/run_report_with_custom_fields.py index 16656a86..20f080f5 100755 --- a/examples/dfp/v201705/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201705/report_service/run_report_with_custom_fields.py @@ -94,7 +94,7 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201705/report_service/run_sales_report.py b/examples/dfp/v201705/report_service/run_sales_report.py index 3347fc79..cf7d623b 100755 --- a/examples/dfp/v201705/report_service/run_sales_report.py +++ b/examples/dfp/v201705/report_service/run_sales_report.py @@ -55,7 +55,7 @@ def main(client): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': diff --git a/examples/dfp/v201705/report_service/run_saved_query.py b/examples/dfp/v201705/report_service/run_saved_query.py index e23b1699..7a8fdd94 100755 --- a/examples/dfp/v201705/report_service/run_saved_query.py +++ b/examples/dfp/v201705/report_service/run_saved_query.py @@ -73,7 +73,7 @@ def main(client, saved_query_id): report_file.close() # Display results. - print 'Report job with id \'%s\' downloaded to:\n%s' % ( + print 'Report job with id "%s" downloaded to:\n%s' % ( report_job_id, report_file.name) else: print 'The query specified is not compatible with the API version.' diff --git a/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py index c2dab5d4..0a2bd663 100755 --- a/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -52,7 +52,7 @@ def main(client): if 'results' in response: # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: - print ('Suggested ad unit with id \'%s\', and number of requests \'%s\'' + print ('Suggested ad unit with id "%s", and number of requests "%s"' ' will be approved.' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) diff --git a/examples/dfp/v201705/team_service/create_teams.py b/examples/dfp/v201705/team_service/create_teams.py index 94884e71..05b40daf 100755 --- a/examples/dfp/v201705/team_service/create_teams.py +++ b/examples/dfp/v201705/team_service/create_teams.py @@ -51,7 +51,7 @@ def main(client): # Display results. for team in teams: - print ('Team with ID \'%s\' and name \'%s\' was created.' + print ('Team with ID "%s" and name "%s" was created.' % (team['id'], team['name'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/team_service/update_teams.py b/examples/dfp/v201705/team_service/update_teams.py index 04373311..aad3c8e6 100755 --- a/examples/dfp/v201705/team_service/update_teams.py +++ b/examples/dfp/v201705/team_service/update_teams.py @@ -62,7 +62,7 @@ def main(client, team_id): # Display results. for team in teams: - print ('Team with id \'%s\' and name \'%s\' was updated.' + print ('Team with id "%s" and name "%s" was updated.' % (team['id'], team['name'])) else: print 'No teams found to update.' diff --git a/examples/dfp/v201705/user_service/create_users.py b/examples/dfp/v201705/user_service/create_users.py index 0098e05c..dd1043b3 100755 --- a/examples/dfp/v201705/user_service/create_users.py +++ b/examples/dfp/v201705/user_service/create_users.py @@ -48,7 +48,7 @@ def main(client, email, name): # Display results. for user in users: - print ('User with id \'%s\', email \'%s\', and role \'%s\' was created.' + print ('User with id "%s", email "%s", and role "%s" was created.' % (user['id'], user['email'], user['roleName'])) if __name__ == '__main__': diff --git a/examples/dfp/v201705/user_service/deactivate_users.py b/examples/dfp/v201705/user_service/deactivate_users.py index bf736c09..cf9590a6 100755 --- a/examples/dfp/v201705/user_service/deactivate_users.py +++ b/examples/dfp/v201705/user_service/deactivate_users.py @@ -50,7 +50,7 @@ def main(client, user_id): users = response['results'] if 'results' in response else [] for user in users: - print ('User with id \'%s\', email \'%s\', and status \'%s\' will be ' + print ('User with id "%s", email "%s", and status "%s" will be ' 'deactivated.' % (user['id'], user['email'], {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) diff --git a/examples/dfp/v201705/user_service/get_all_roles.py b/examples/dfp/v201705/user_service/get_all_roles.py index fb763029..bb2bec62 100755 --- a/examples/dfp/v201705/user_service/get_all_roles.py +++ b/examples/dfp/v201705/user_service/get_all_roles.py @@ -28,7 +28,7 @@ def main(client): # Print out some information for each role. for role in roles: - print('Role with id \'%s\' and name \'%s\' was found.' % + print('Role with id "%s" and name "%s" was found.' % (role['id'], role['name'])) print '\nNumber of results found: %s' % len(roles) diff --git a/examples/dfp/v201705/user_service/get_current_user.py b/examples/dfp/v201705/user_service/get_current_user.py index 99fde64c..f2d762de 100755 --- a/examples/dfp/v201705/user_service/get_current_user.py +++ b/examples/dfp/v201705/user_service/get_current_user.py @@ -27,7 +27,7 @@ def main(client): # Get current user. user = user_service.getCurrentUser() - print ('User with ID %d, name \'%s\', email \'%s\', and role \'%s\' ' + print ('User with ID %d, name "%s", email "%s", and role "%s" ' 'is the current user.' % ( user.id, user.name, user.email, user.roleName )) diff --git a/examples/dfp/v201705/user_service/update_users.py b/examples/dfp/v201705/user_service/update_users.py index c7182647..e072358e 100755 --- a/examples/dfp/v201705/user_service/update_users.py +++ b/examples/dfp/v201705/user_service/update_users.py @@ -54,7 +54,7 @@ def main(client, user_id): # Update users on server. users = user_service.updateUsers(users) for user in users: - print ('User with id \'%s\' and name \'%s\' was updated.' + print ('User with id "%s" and name "%s" was updated.' % (user['id'], user['name'])) else: print 'No users found to update.' diff --git a/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py index 840f0a4d..28a2bf1a 100755 --- a/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py @@ -55,9 +55,9 @@ def main(client, team_id, user_ids): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('A user team association between user with ID \'%s\' and team with' - ' ID \'%s\'was created.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('A user team association between user with ID "%s" and team with' + ' ID "%s"was created.' % (user_team_association['userId'], + user_team_association['teamId'])) else: print 'No user team associations created.' diff --git a/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py index 8a7f873a..d00f760d 100755 --- a/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py @@ -56,9 +56,9 @@ def main(client, user_id): user_team_associations = response['results'] if 'results' in response else [] for user_team_association in user_team_associations: - print ('User team association between user with ID \'%s\' and team with ' - 'ID \'%s\' will be deleted.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('User team association between user with ID "%s" and team with ' + 'ID "%s" will be deleted.' % (user_team_association['userId'], + user_team_association['teamId'])) print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) diff --git a/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py index b5ab14a0..2266e140 100755 --- a/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py @@ -71,9 +71,9 @@ def main(client, user_id): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('User team association between user with ID \'%s\' and team with' - ' ID \'%s\' was updated.' % (user_team_association['userId'], - user_team_association['teamId'])) + print ('User team association between user with ID "%s" and team with' + ' ID "%s" was updated.' % (user_team_association['userId'], + user_team_association['teamId'])) else: print 'No user team associations were updated.' else: diff --git a/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py index 1092d9af..503c9eab 100755 --- a/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py @@ -71,7 +71,7 @@ def main(client, proposal_id): if 'results' in response: # Display results. for workflow_approval_request in response['results']: - print ('Workflow approval request with id \'%s\' will be' + print ('Workflow approval request with id "%s" will be' ' approved.' % workflow_approval_request['id']) # Perform action. result = workflow_request_service.performWorkflowRequestAction( diff --git a/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py index 53ca3c6f..d966ae68 100755 --- a/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -71,8 +71,8 @@ def main(client, proposal_id): if 'results' in response: # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id \'%s\' for %s ' - 'with id \'%s\' will be triggered.' % + print ('Workflow external condition request with id "%s" for %s ' + 'with id "%s" will be triggered.' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) diff --git a/googleads.yaml b/googleads.yaml index 830874c7..1d081749 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -75,6 +75,27 @@ dfp: ############################################################################### # enable_compression: False ############################################################################### +# Logging configuration (optional) # +# Below you may specify the logging configuration. This will be provided as # +# an input to logging.config.dictConfig. # +############################################################################### +# logging: + # version: 1 + # disable_existing_loggers: False + # formatters: + # default_fmt: + # format: ext://googleads.util.LOGGER_FORMAT + # handlers: + # default_handler: + # class: logging.StreamHandler + # formatter: default_fmt + # level: INFO + # loggers: + # Configure root logger + # "": + # handlers: [default_handler] + # level: INFO +############################################################################### # Proxy configurations (optional) # # Below you may specify an HTTP or HTTPS Proxy to be used when making API # # requests. # diff --git a/googleads/adwords.py b/googleads/adwords.py index 407dd175..04b2d2ec 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -16,6 +16,7 @@ from collections import namedtuple import io +import logging import os import re import sys @@ -32,55 +33,15 @@ import googleads.common import googleads.errors + +_report_logger = logging.getLogger('%s.%s' % (__name__, 'report_downloader')) +_batch_job_logger = logging.getLogger('%s.%s' + % (__name__, 'batch_job_helper')) + + # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201607': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'ExperimentService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201609': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', @@ -256,9 +217,6 @@ class AdWordsClient(object): succeed, to result in a complete failure with no changes made or a partial failure with some changes made. Only certain services respect this header. - https_proxy: A string identifying the URL of a proxy that all HTTPS requests - should be routed through. Modifying this value will not affect any SOAP - service clients you've already created. """ # The key in the storage yaml which contains AdWords data. @@ -362,7 +320,6 @@ def __init__(self, developer_token, oauth2_client, """ self.developer_token = developer_token self.oauth2_client = oauth2_client - self.oauth2_client.Refresh() self.client_customer_id = kwargs.get('client_customer_id') self.user_agent = user_agent # Verify that the provided user_agent contains only ASCII characters. In @@ -455,8 +412,8 @@ def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], in future releases to point to what is then the latest version. server: A string identifying the webserver hosting the AdWords API. - Returns: - An initialized BatchJobHelper tied to this client. + Returns: + An initialized BatchJobHelper tied to this client. """ if not server: server = _DEFAULT_ENDPOINT @@ -765,13 +722,14 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): new_content_length += padded_request_length request_body += ' ' * padding_length req.get_method = lambda: 'PUT' # Modify this into a PUT request. + req.data = request_body.encode('utf-8') req.add_header('Content-Length', padded_request_length) req.add_header('Content-Range', 'bytes %s-%s/%s' % ( current_content_length, new_content_length - 1, new_content_length if is_last else '*' )) - req.data = request_body.encode('utf-8') + return req def _BuildUploadRequestBody(self, operations, has_prefix=True, @@ -1157,14 +1115,51 @@ def UploadOperations(self, operations, is_last=False): # Make the request, ignoring the urllib2.HTTPError raised due to HTTP status # code 308 (for resumable uploads). try: + _batch_job_logger.debug('Outgoing request: %s %s %s', + req.get_full_url(), req.headers, req.data) + self._url_opener.open(req) + + if _batch_job_logger.isEnabledFor(logging.INFO): + _batch_job_logger.info('Request summary: %s', + self._ExtractRequestSummaryFields(req)) except urllib2.HTTPError as e: if e.code != 308: + if _batch_job_logger.isEnabledFor(logging.WARNING): + _batch_job_logger.warning( + 'Request summary: %s', + self._ExtractRequestSummaryFields(req, error=e)) raise # Update upload status. self._current_content_length += len(req.data) self._is_last = is_last + def _ExtractRequestSummaryFields(self, request, error=None): + """Extract fields used in the summary logs. + + Args: + request: a urllib2.Request instance configured to make the request. + [optional] + error: a urllib2.HttpError instance used to retrieve error details. + + Returns: + A dict containing the fields to be output in the summary logs. + """ + headers = request.headers + summary_fields = { + 'server': request.get_full_url(), + 'contentRange': headers['Content-range'], + 'contentLength': headers['Content-length'] + } + + if error: + summary_fields['isError'] = True + summary_fields['errorMessage'] = error.reason + else: + summary_fields['isError'] = False + + return summary_fields + @googleads.common.RegisterUtility( 'ReportDownloader', {'DownloadReport': 'File', @@ -1187,6 +1182,8 @@ class ReportDownloader(object): _SCHEMA_FORMAT = '/'.join([_END_POINT_FORMAT, 'reportDefinition.xsd']) # The name of the complex type representing a report definition. _REPORT_DEFINITION_NAME = 'reportDefinition' + # Used to extract the reporting URL for logging. + _SERVER_PATTERN = re.compile('https?://(.+?)/.*') def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -1229,7 +1226,7 @@ def _DownloadReportCheckFormat(self, file_format, output): is_valid_gzip_mode = 'b' in mode and ('+' in mode or 'w' in mode) if (file_format.startswith('GZIPPED_') - and not (is_valid_gzip_mode or type(output) is io.BytesIO)): + and not (is_valid_gzip_mode or isinstance(output, io.BytesIO))): raise googleads.errors.GoogleAdsValueError('Need to specify a binary' ' output for GZIPPED formats.') @@ -1592,14 +1589,101 @@ def _DownloadReportAsStream(self, post_body, **kwargs): """ if sys.version_info[0] == 3: post_body = bytes(post_body, 'utf8') + request = urllib2.Request( self._end_point, post_body, self._header_handler.GetReportDownloadHeaders(**kwargs)) try: - return self.url_opener.open(request) + if _report_logger.isEnabledFor(logging.DEBUG): + _report_logger.debug('Outgoing request: %s %s', + self._SanitizeRequestHeaders(request.headers), + post_body) + + response = self.url_opener.open(request) + + if _report_logger.isEnabledFor(logging.INFO): + _report_logger.info( + 'Request Summary: %s', self._ExtractRequestSummaryFields(request)) + + if _report_logger.isEnabledFor(logging.DEBUG): + _report_logger.debug('Incoming response: %s %s %s REDACTED REPORT DATA', + self._ExtractResponseHeaders(response.headers), + response.code, response.msg) + return response except urllib2.HTTPError as e: + if _report_logger.isEnabledFor(logging.WARNING): + _report_logger.warning( + 'Request Summary: %s', self._ExtractRequestSummaryFields( + request, error=e)) raise self._ExtractError(e) + def _SanitizeRequestHeaders(self, headers): + """Removes sensitive data from request headers for use in logging. + + Args: + headers: a dict containing the headers to be sanitized. + + Returns: + A dict containing a sanitized copy of the provided headers. + """ + sanitized_headers = dict(headers) + + sanitized_headers['Developertoken'] = 'REDACTED' + sanitized_headers['Authorization'] = 'REDACTED' + + return sanitized_headers + + def _ExtractResponseHeaders(self, headers): + """Extracts the given headers to a dict for logging. + + Args: + headers: a httplib.HTTPMessage instance containing response headers. + + Returns: + A dict containing the contents of the response headers. + """ + header_lines = str(headers).split('\n') + headers = {} + + for header_line in header_lines: + if header_line: + k, v = header_line.split(': ') + headers[k] = v + + return headers + + def _ExtractRequestSummaryFields(self, request, error=None): + """Extract fields used in the summary logs. + + Args: + request: a urllib2.Request instance. + [optional] + error: a urllib2.HttpError instance used to retrieve error details. + + Returns: + A dict containing the fields to be output in the summary logs. + """ + server = (self._SERVER_PATTERN.search(request.get_full_url()) + .group(1)) + headers = request.headers + + summary_fields = { + 'clientCustomerId': headers.get('Clientcustomerid'), + 'includeZeroImpressions': headers.get('Includezeroimpressions', False), + 'server': server, + 'skipColumnHeader': headers.get('Skipcolumnheader', False), + 'skipReportHeader': headers.get('Skipreportheader', False), + 'skipReportSummary': headers.get('Skipreportsummary', False), + } + + if error: + summary_fields['isError'] = True + summary_fields['errorMessage'] = error.read() + else: + summary_fields['isError'] = False + + return summary_fields + def _SerializeAwql(self, query, file_format): """Serializes an AWQL query and file format for transport. diff --git a/googleads/common.py b/googleads/common.py index d3f9114f..90129116 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -18,7 +18,9 @@ import datetime from functools import wraps import inspect +import locale import logging +import logging.config import os import ssl import sys @@ -47,10 +49,13 @@ logging.getLogger('suds.client').addFilter(googleads.util.GetSudsClientFilter()) +logging.getLogger('suds.mx.core').addFilter( + googleads.util.GetSudsMXCoreFilter()) +logging.getLogger('suds.mx.literal').addFilter( + googleads.util.GetSudsMXLiteralFilter()) logging.getLogger('suds.transport.http').addFilter( googleads.util.GetSudsTransportFilter()) _logger = logging.getLogger(__name__) -_logger.addFilter(googleads.util.GetGoogleAdsCommonFilter()) _PY_VERSION_MAJOR = sys.version_info.major _PY_VERSION_MINOR = sys.version_info.minor @@ -61,8 +66,9 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '5.6.0' +VERSION = '6.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION +_LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' _HTTPS_PROXY_YAML_KEY = 'https_proxy' _PROXY_CONFIG_KEY = 'proxy_config' @@ -149,6 +155,12 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, information necessary to instantiate a client object - either a required_client_values key was missing or an OAuth2 key was missing. """ + data = yaml.safe_load(yaml_doc) or {} + + logging_config = data.get(_LOGGING_KEY) + if logging_config: + logging.config.dictConfig(logging_config) + # Warn users on deprecated Python versions on initialization. if _PY_VERSION_MAJOR == 2: if _PY_VERSION_MINOR == 7 and _PY_VERSION_MICRO < 9: @@ -158,7 +170,11 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, _PY_VERSION_MINOR, _PY_VERSION_MICRO) - data = yaml.safe_load(yaml_doc) or {} + # Warn users about using non-utf8 encoding + _, encoding = locale.getdefaultlocale() + if encoding is None or encoding.lower() != 'utf-8': + _logger.warn('Your default encoding, %s, is not UTF-8. Please run this' + ' script with UTF-8 encoding to avoid errors.', encoding) try: product_data = data[product_yaml_key] @@ -472,7 +488,7 @@ def _RecurseOverObject(obj, factory, parent=None): def _IsSudsIterable(obj): """A short helper method to determine if a field is iterable for Suds.""" - return (obj and not isinstance(obj, basestring) and hasattr(obj, '__iter__')) + return obj and not isinstance(obj, basestring) and hasattr(obj, '__iter__') def IncludeUtilitiesInUserAgent(value): @@ -725,13 +741,17 @@ def _CreateMethod(self, method_name): def MakeSoapRequest(*args): """Perform a SOAP call.""" self._header_handler.SetHeaders(self.suds_client) + try: return soap_service_method( *[_PackForSuds(arg, self.suds_client.factory, self._datetime_packer) for arg in args]) except suds.WebFault as e: - _logger.error('Server raised fault in response.') - _logger.info('Failure response:\n%s', e.document) + if _logger.isEnabledFor(logging.WARNING): + _logger.warning('Response summary - %s', + _ExtractResponseSummaryFields(e.document)) + + _logger.info('SOAP response:\n%s', e.document) if not hasattr(e.fault, 'detail'): raise @@ -763,5 +783,89 @@ def SetHeaders(self, client): class LoggingMessagePlugin(suds.plugin.MessagePlugin): """A MessagePlugin used to log request summaries.""" - def sending(self, context): - _logger.info('Request made.') + def marshalled(self, context): + if _logger.isEnabledFor(logging.INFO): + _logger.info('Request summary - %s', + _ExtractRequestSummaryFields(context.envelope)) + + def parsed(self, context): + if _logger.isEnabledFor(logging.INFO): + _logger.info('Response summary - %s', + _ExtractResponseSummaryFields(context.reply)) + + +def _ExtractRequestSummaryFields(document): + """Extract logging fields from the request's suds.sax.element.Element. + + Args: + document: A suds.sax.element.Element instance containing the API request. + + Returns: + A dict mapping logging field names to their corresponding value. + """ + headers = document.childAtPath('Header/RequestHeader') + body = document.childAtPath('Body') + + summary_fields = { + 'methodName': body.getChildren()[0].name + } + + # Extract AdWords-specific fields if they exist. + # Note: We need to check if None because this will always evaluate False. + client_customer_id = headers.getChild('clientCustomerId') + if client_customer_id is not None: + summary_fields['clientCustomerId'] = client_customer_id.text + + # Extract DFP-specific fields if they exist. + # Note: We need to check if None because this will always evaluate False. + network_code = headers.getChild('networkCode') + if network_code is not None: + summary_fields['networkCode'] = network_code.text + + return summary_fields + + +def _ExtractResponseSummaryFields(document): + """Extract logging fields from the response's suds.sax.document.Document. + + Args: + document: A suds.sax.document.Document instance containing the parsed + API response for a given API request. + + Returns: + A dict mapping logging field names to their corresponding value. + """ + headers = document.childAtPath('Envelope/Header/ResponseHeader') + body = document.childAtPath('Envelope/Body') + summary_fields = {} + + if headers is not None: + summary_fields['requestId'] = headers.getChild('requestId').text + summary_fields['responseTime'] = headers.getChild('responseTime').text + + # Extract AdWords-specific summary fields if they are present. + # Note: We need to check if None because this will always evaluate False. + service_name = headers.getChild('serviceName') + if service_name is not None: + summary_fields['serviceName'] = service_name.text + + method_name = headers.getChild('methodName') + if method_name is not None: + summary_fields['methodName'] = method_name.text + + operations = headers.getChild('operations') + if operations is not None: + summary_fields['operations'] = operations.text + + if body is not None: + # Extract fault if it exists. + fault = body.getChild('Fault') + if fault is not None: + summary_fields['isFault'] = True + # Cap length of faultstring to 16k characters for summary. + summary_fields['faultMessage'] = fault.getChild( + 'faultstring').text[:16000] + else: + summary_fields['isFault'] = False + + return summary_fields diff --git a/googleads/dfp.py b/googleads/dfp.py index c2202de3..ee7fe18b 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -38,6 +38,12 @@ SUGGESTED_PAGE_LIMIT = 500 # The chunk size used for report downloads. _CHUNK_SIZE = 16 * 1024 + + +_data_downloader_logger = logging.getLogger( + '%s.%s' % (__name__, 'data_downloader')) + + # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { 'v201608': @@ -140,9 +146,6 @@ class DfpClient(object): network_code: A string identifying the network code of the network you are accessing. All requests other than some NetworkService calls require this header to be set. - https_proxy: A string identifying the URL of a proxy that all HTTPS requests - should be routed through. Modifying this value will not affect any SOAP - service clients you've already created. """ # The key in the storage yaml which contains DFP data. @@ -151,8 +154,7 @@ class DfpClient(object): _REQUIRED_INIT_VALUES = ('application_name',) # A list of values which may optionally be provided when using DFP. _OPTIONAL_INIT_VALUES = ( - 'network_code', 'https_proxy', - googleads.common.ENABLE_COMPRESSION_KEY) + 'network_code', googleads.common.ENABLE_COMPRESSION_KEY) # The format of SOAP service WSDLs. A server, version, and service name need # to be formatted in. _SOAP_SERVICE_FORMAT = '%s/apis/ads/publisher/%s/%s?wsdl' @@ -240,6 +242,8 @@ def __init__(self, oauth2_client, application_name, network_code=None, if enable_compression: self.application_name = '%s (gzip)' % self.application_name + self.message_plugin = googleads.common.LoggingMessagePlugin() + def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -267,7 +271,8 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server = server[:-1] if server[-1] == '/' else server kwargs = {'timeout': 3600, - 'transport': self.proxy_config.GetSudsProxyTransport()} + 'transport': self.proxy_config.GetSudsProxyTransport(), + 'plugins': [self.message_plugin]} if self.cache: kwargs['cache'] = self.cache @@ -728,7 +733,7 @@ def WaitForReport(self, report_job): status = service.getReportJob(report_job_id)['reportJobStatus'] while status != 'COMPLETED' and status != 'FAILED': - logging.debug('Report job status: %s', status) + _data_downloader_logger.debug('Report job status: %s', status) time.sleep(30) if self._version > 'v201502': status = service.getReportJobStatus(report_job_id) @@ -738,7 +743,7 @@ def WaitForReport(self, report_job): if status == 'FAILED': raise googleads.errors.DfpReportError(report_job_id) else: - logging.debug('Report has completed successfully') + _data_downloader_logger.debug('Report has completed successfully') return report_job_id def DownloadReportToFile(self, report_job_id, export_format, outfile, @@ -769,7 +774,15 @@ def DownloadReportToFile(self, report_job_id, export_format, outfile, 'useGzipCompression': use_gzip_compression } report_url = service.getReportDownloadUrlWithOptions(report_job_id, opts) + _data_downloader_logger.info('Request Summary: Report job ID: %s, %s', + report_job_id, opts) + response = self.url_opener.open(report_url) + + _data_downloader_logger.debug( + 'Incoming response: %s %s REDACTED REPORT DATA', response.code, + response.msg) + while True: chunk = response.read(_CHUNK_SIZE) if not chunk: break diff --git a/googleads/oauth2.py b/googleads/oauth2.py index 806aa896..b26a763a 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -70,11 +70,7 @@ def GetAPIScope(api_name): class GoogleOAuth2Client(object): - """An OAuth2 client for use with Google APIs. - - This interface assumes all responsibilty for refreshing credentials when - necessary. - """ + """An OAuth2 client for use with Google APIs.""" # The web address for generating OAuth2 credentials at Google. _GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token' # We will refresh an OAuth2 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE @@ -97,12 +93,68 @@ def CreateHttpHeader(self): """ raise NotImplementedError('You must subclass GoogleOAuth2Client.') + +class GoogleRefreshableOAuth2Client(GoogleOAuth2Client): + """A refreshable OAuth2 client for use with Google APIs. + + This interface assumes all responsibility for refreshing credentials when + necessary. + """ + def Refresh(self): """Refreshes the access token used by the client.""" - raise NotImplementedError('You must subclass GoogleOAuth2Client.') + raise NotImplementedError( + 'You must subclass GoogleRefreshableOAuth2Client.') + + +class GoogleAccessTokenClient(GoogleOAuth2Client): + """A simple client for using OAuth2 for Google APIs with an access token. + This class is not capable of supporting any flows other than taking an + existing, active access token. It does not matter which of Google's OAuth2 + flows you used to generate the access token (installed application, web flow, + etc.). + + When the provided access token expires, a GoogleAdsError will be raised. + """ + + def __init__(self, access_token, token_expiry): + """Initializes a GoogleAccessTokenClient. + + Args: + access_token: A string containing your access token. + token_expiry: A datetime instance indicating when the given access token + expires. + """ + self.oauth2credentials = oauth2client.client.OAuth2Credentials( + access_token, None, None, None, token_expiry, + self._GOOGLE_OAUTH2_ENDPOINT, self._USER_AGENT) + + def CreateHttpHeader(self): + """Creates an OAuth2 HTTP header. -class GoogleRefreshTokenClient(GoogleOAuth2Client): + The OAuth2 credentials will be refreshed as necessary. In the event that + the credentials fail to refresh, a message is logged but no exception is + raised. + + Returns: + A dictionary containing one entry: the OAuth2 Bearer header under the + 'Authorization' key. + + Raises: + GoogleAdsError: If the access token has expired. + """ + oauth2_header = {} + + if (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() + < datetime.timedelta(0)): + raise googleads.errors.GoogleAdsError('Access token has expired.') + + self.oauth2credentials.apply(oauth2_header) + return oauth2_header + + +class GoogleRefreshTokenClient(GoogleRefreshableOAuth2Client): """A simple client for using OAuth2 for Google APIs with a refresh token. This class is not capable of supporting any flows other than taking an @@ -114,24 +166,28 @@ class GoogleRefreshTokenClient(GoogleOAuth2Client): proxy_info: A ProxyInfo instance used for refresh requests. """ - def __init__(self, client_id, client_secret, refresh_token, - proxy_config=None): + def __init__(self, client_id, client_secret, refresh_token, **kwargs): """Initializes a GoogleRefreshTokenClient. Args: client_id: A string containing your client ID. client_secret: A string containing your client secret. refresh_token: A string containing your refresh token. - [optional] + **kwargs: Keyword arguments. + + Keyword Arguments: + access_token: A string containing your access token. + token_expiry: A datetime instance indicating when the given access token + expires. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. """ self.oauth2credentials = oauth2client.client.OAuth2Credentials( - None, client_id, client_secret, refresh_token, - datetime.datetime(1980, 1, 1, 12), self._GOOGLE_OAUTH2_ENDPOINT, - self._USER_AGENT) - self.proxy_config = (proxy_config if proxy_config else - googleads.common.ProxyConfig()) + kwargs.get('access_token'), client_id, client_secret, refresh_token, + kwargs.get('token_expiry', datetime.datetime(1980, 1, 1, 12)), + self._GOOGLE_OAUTH2_ENDPOINT, self._USER_AGENT) + self.proxy_config = kwargs.get('proxy_config', + googleads.common.ProxyConfig()) def CreateHttpHeader(self): """Creates an OAuth2 HTTP header. @@ -170,7 +226,7 @@ def Refresh(self): self.proxy_config.disable_certificate_validation))) -class GoogleServiceAccountClient(GoogleOAuth2Client): +class GoogleServiceAccountClient(GoogleRefreshableOAuth2Client): """A simple client for using OAuth2 for Google APIs with a service account. This class is not capable of supporting any flows other than generating diff --git a/googleads/util.py b/googleads/util.py index 80ed8aa4..f2741994 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -28,6 +28,8 @@ _COMMON_FILTER = None _SUDS_CLIENT_FILTER = None +_SUDS_MX_CORE_FILTER = None +_SUDS_MX_LITERAL_FILTER = None _SUDS_TRANSPORT_FILTER = None LOGGER_FORMAT = '[%(asctime)s - %(name)s - %(levelname)s] %(message)s' @@ -46,6 +48,20 @@ def GetSudsClientFilter(): return _SUDS_CLIENT_FILTER +def GetSudsMXCoreFilter(): + global _SUDS_MX_CORE_FILTER + if not _SUDS_MX_CORE_FILTER: + _SUDS_MX_CORE_FILTER = _SudsMXCoreFilter() + return _SUDS_MX_CORE_FILTER + + +def GetSudsMXLiteralFilter(): + global _SUDS_MX_LITERAL_FILTER + if not _SUDS_MX_LITERAL_FILTER: + _SUDS_MX_LITERAL_FILTER = _SudsMXLiteralFilter() + return _SUDS_MX_LITERAL_FILTER + + def GetSudsTransportFilter(): global _SUDS_TRANSPORT_FILTER if not _SUDS_TRANSPORT_FILTER: @@ -137,7 +153,7 @@ class _AbstractDevTokenSOAPFilter(logging.Filter): _AUTHORIZATION_HEADER = 'Authorization' _DEVELOPER_TOKEN_SUB = re.compile( r'(?<=\).*?(?=\)') - _OMITTED = 'OMITTED' + _REDACTED = 'REDACTED' def filter(self, record): raise NotImplementedError('You must implement filter().') @@ -149,7 +165,7 @@ class _GoogleAdsCommonFilter(_AbstractDevTokenSOAPFilter): def filter(self, record): if record.levelno == logging.INFO and record.args: content = record.args[0].str() - content = self._DEVELOPER_TOKEN_SUB.sub(self._OMITTED, content) + content = self._DEVELOPER_TOKEN_SUB.sub(self._REDACTED, content) record.args = (content,) return True @@ -165,15 +181,106 @@ def filter(self, record): # If the original suds.sax.document.Document is modified, that will also # modify the request itself. Instead, replace it with its sanitized text. record.args = (args[0], self._DEVELOPER_TOKEN_SUB.sub( - self._OMITTED, args[1].str())) + self._REDACTED, args[1].str())) elif record.msg == self._SUDS_CLIENT_HEADERS_MSG: sanitized_headers = record.args.copy() if self._AUTHORIZATION_HEADER in sanitized_headers: - sanitized_headers[self._AUTHORIZATION_HEADER] = self._OMITTED + sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED record.args = sanitized_headers return True +class _SudsMXCoreFilter(_AbstractDevTokenSOAPFilter): + """Removes sensitive data from logs generated by suds.mx.core.""" + + _DEVELOPER_TOKEN = 'developerToken' + _REQUEST_HEADER = 'RequestHeader' + + def filter(self, record): + for i in range(len(record.args)): + arg = record.args[i] + + if isinstance(arg, suds.mx.Content): + if arg.tag == self._REQUEST_HEADER: + # Rather than modifying the argument directly, sets args to a modified + # copy so that we don't overwrite the headers to be sent in the actual + # request. + d = dict(arg.value) + if self._DEVELOPER_TOKEN in d: + d[self._DEVELOPER_TOKEN] = self._REDACTED + record.args = list(record.args) + record.args[i] = suds.mx.Content(tag=self._REQUEST_HEADER, value=d) + break + if arg.tag == self._DEVELOPER_TOKEN: + # Rather than modifying the argument directly, sets args to a modified + # copy so that we don't overwrite the headers to be sent in the actual + # request. + record.args = list(record.args) + record.args[i] = suds.mx.Content( + tag=self._DEVELOPER_TOKEN, value=self._REDACTED) + break + elif isinstance(arg, suds.sax.element.Element): + if arg.name == self._REQUEST_HEADER: + # Only produce a modified copy of the RequestHeader element if it + # contains a developer token. + if arg.getChild(self._DEVELOPER_TOKEN) is not None: + request_header = suds.sax.element.Element( + arg.name, parent=arg.parent) + + for child in arg.getChildren(): + copied_child = suds.sax.element.Element( + child.name, parent=request_header) + + if child.name == self._DEVELOPER_TOKEN: + copied_child.text = suds.sax.text.Text(self._REDACTED) + else: + copied_child.text = child.text + + request_header.append(copied_child) + + # Rather than modifying the argument directly, sets args to a + # modified copy so that we don't overwrite the headers to be sent in + # the actual request. + record.args = list(record.args) + record.args[i] = request_header + break + + return True + + +class _SudsMXLiteralFilter(_AbstractDevTokenSOAPFilter): + """Removes sensitive data from logs generated by suds.mx.literal.""" + + _DEVELOPER_TOKEN = 'developerToken' + _REQUEST_HEADER = 'RequestHeader' + + def filter(self, record): + for i in range(len(record.args)): + arg = record.args[i] + + if isinstance(arg, suds.mx.Content): + if arg.tag == self._REQUEST_HEADER: + # Rather than modifying the argument directly, sets args to a modified + # copy so that we don't overwrite the headers to be sent in the actual + # request. + d = dict(arg.value) + if self._DEVELOPER_TOKEN in d: + d[self._DEVELOPER_TOKEN] = self._REDACTED + record.args = list(record.args) + record.args[i] = suds.mx.Content(tag=self._REQUEST_HEADER, value=d) + break + if arg.tag == self._DEVELOPER_TOKEN: + # Rather than modifying the argument directly, sets args to a modified + # copy so that we don't overwrite the headers to be sent in the actual + # request. + record.args = list(record.args) + record.args[i] = suds.mx.Content(tag=self._DEVELOPER_TOKEN, + value=self._REDACTED) + break + + return True + + class _SudsTransportFilter(_AbstractDevTokenSOAPFilter): """Removes sensitive data from logs generated by suds.transport.""" @@ -184,10 +291,10 @@ def filter(self, record): new_arg = suds.transport.Request(arg.url) sanitized_headers = arg.headers.copy() if self._AUTHORIZATION_HEADER in sanitized_headers: - sanitized_headers[self._AUTHORIZATION_HEADER] = self._OMITTED + sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED new_arg.headers = sanitized_headers new_arg.message = self._DEVELOPER_TOKEN_SUB.sub( - self._OMITTED, arg.message.decode('utf-8')) + self._REDACTED, arg.message.decode('utf-8')) record.args = (new_arg,) return True diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 145a13ed..8b25b0b0 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -559,6 +559,8 @@ def testUploadOperations(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.Mock() mock_request.data = 'in disguise.' + mock_request.get_full_url.return_value = 'https://google.com/' + mock_request.headers = {'Content-range': 0, 'Content-length': 0} mock_build_request.return_value = mock_request with mock.patch('googleads.adwords.IncrementalUploadHelper' '._InitializeURL') as mock_init: @@ -1405,6 +1407,26 @@ def testUploadOperations(self): self.incremental_uploader.UploadOperations([[]], True) mock_open.assert_called_with(mock_request) + def testUploadOperationsWithError(self): + error_url = 'https://google.com/' + error_code = '404' + error_message = 'I AM ERROR' + error_headers = {} + http_error = urllib2.HTTPError( + error_url, error_code, error_message, error_headers, None) + + with mock.patch('googleads.adwords.BatchJobHelper.' + '_SudsUploadRequestBuilder.' + 'BuildUploadRequest') as mock_build_request: + mock_request = mock.MagicMock() + mock_build_request.return_value = mock_request + with mock.patch('urllib2.OpenerDirector.open') as mock_open: + mock_open.side_effect = http_error + self.assertRaises( + urllib2.HTTPError, self.incremental_uploader.UploadOperations, + [[]], True) + mock_open.assert_called_with(mock_request) + def testUploadOperationsAfterFinished(self): with mock.patch('googleads.adwords.BatchJobHelper.' '_SudsUploadRequestBuilder.' @@ -1534,15 +1556,24 @@ def testDownloadReport(self): post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers - content = u'CONTENT STRING 广告客户' - fake_request = io.StringIO() if PYTHON2 else io.BytesIO() - fake_request.write(content if PYTHON2 else bytes(content, 'utf-8')) - fake_request.seek(0) + report_data = u'CONTENT STRING 广告客户' + report_contents = io.StringIO() if PYTHON2 else io.BytesIO() + report_contents.write(report_data if PYTHON2 + else bytes(report_data, 'utf-8')) + report_contents.seek(0) + fake_response = mock.Mock() + fake_response.read = report_contents.read + fake_response.msg = 'fake message' + fake_response.code = '200' self.marshaller.process.return_value = serialized_report with mock.patch('suds.mx.Content') as mock_content: with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - self.opener.open.return_value = fake_request + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = 'https://google.com/' + mock_request_instance.headers = {} + self.opener.open.return_value = fake_response self.report_downloader.DownloadReport(report_definition, output_file, skip_report_header=True, use_raw_enum_values=False) @@ -1552,10 +1583,55 @@ def testDownloadReport(self): self.opener.open.assert_called_once_with(mock_request.return_value) self.marshaller.process.assert_called_once_with( mock_content.return_value) - self.assertEqual(content, output_file.getvalue()) + self.assertEqual(report_data, output_file.getvalue()) self.header_handler.GetReportDownloadHeaders.assert_called_once_with( skip_report_header=True, use_raw_enum_values=False) + def testDownloadReportWithAllLoggingEnabled(self): + output_file = io.StringIO() + report_definition = {'table': 'campaigns', + 'downloadFormat': 'CSV'} + serialized_report = 'nuinbwuign' + post_body = urllib.urlencode({'__rdxml': serialized_report}) + if not PYTHON2: + post_body = bytes(post_body, 'utf-8') + headers = {'Authorization': 'ya29.something'} + self.header_handler.GetReportDownloadHeaders.return_value = headers + report_data = u'CONTENT STRING 广告客户' + report_contents = io.StringIO() if PYTHON2 else io.BytesIO() + report_contents.write(report_data if PYTHON2 + else bytes(report_data, 'utf-8')) + report_contents.seek(0) + fake_response = mock.Mock() + fake_response.read = report_contents.read + fake_response.headers = '\nsomekey: somevalue\n' + fake_response.msg = 'fake message' + fake_response.code = '200' + self.marshaller.process.return_value = serialized_report + + with mock.patch('suds.mx.Content') as mock_content: + with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: + with mock.patch('googleads.adwords._report_logger') as mock_logger: + mock_logger.isEnabledFor.return_value = True + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = ( + 'https://google.com/') + mock_request_instance.headers = {} + self.opener.open.return_value = fake_response + self.report_downloader.DownloadReport(report_definition, output_file, + skip_report_header=True, + use_raw_enum_values=False) + mock_request.assert_called_once_with( + ('https://adwords.google.com/api/adwords/reportdownload/%s' + % self.version), post_body, headers) + self.opener.open.assert_called_once_with(mock_request.return_value) + self.marshaller.process.assert_called_once_with( + mock_content.return_value) + self.assertEqual(report_data, output_file.getvalue()) + self.header_handler.GetReportDownloadHeaders.assert_called_once_with( + skip_report_header=True, use_raw_enum_values=False) + def testDownloadReportAsString(self): report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} @@ -1565,16 +1641,25 @@ def testDownloadReportAsString(self): post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers - content = u'CONTENT STRING アングリーバード' - fake_request = io.BytesIO() - fake_request.write(content.encode('utf-8') if PYTHON2 - else bytes(content, 'utf-8')) - fake_request.seek(0) + report_data = u'CONTENT STRING アングリーバード' + report_contents = io.BytesIO() + report_contents.write(report_data.encode('utf-8') if PYTHON2 + else bytes(report_data, 'utf-8')) + report_contents.seek(0) + fake_response = mock.Mock() + fake_response.read = report_contents.read + fake_response.msg = 'fake message' + fake_response.code = '200' self.marshaller.process.return_value = serialized_report with mock.patch('suds.mx.Content') as mock_content: with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - self.opener.open.return_value = fake_request + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = ( + 'https://google.com/') + mock_request_instance.headers = {} + self.opener.open.return_value = fake_response s = self.report_downloader.DownloadReportAsString(report_definition) mock_request.assert_called_once_with( ('https://adwords.google.com/api/adwords/reportdownload/%s' @@ -1582,7 +1667,7 @@ def testDownloadReportAsString(self): self.opener.open.assert_called_once_with(mock_request.return_value) self.marshaller.process.assert_called_once_with( mock_content.return_value) - self.assertEqual(content, s) + self.assertEqual(report_data, s) self.header_handler.GetReportDownloadHeaders.assert_called_once_with() def testDownloadReportAsStringWithAwql(self): @@ -1593,13 +1678,22 @@ def testDownloadReportAsStringWithAwql(self): post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers - content = u'CONTENT STRING アングリーバード' - fake_request = io.BytesIO() - fake_request.write(content.encode('utf-8') if PYTHON2 - else bytes(content, 'utf-8')) - fake_request.seek(0) + report_data = u'CONTENT STRING アングリーバード' + report_contents = io.BytesIO() + report_contents.write(report_data.encode('utf-8') if PYTHON2 + else bytes(report_data, 'utf-8')) + report_contents.seek(0) + fake_response = mock.Mock() + fake_response.read = report_contents.read + fake_response.msg = 'fake message' + fake_response.code = '200' + with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - self.opener.open.return_value = fake_request + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = 'https://google.com/' + mock_request_instance.headers = {} + self.opener.open.return_value = fake_response s = self.report_downloader.DownloadReportAsStringWithAwql( query, file_format, include_zero_impressions=True, use_raw_enum_values=False) @@ -1607,7 +1701,7 @@ def testDownloadReportAsStringWithAwql(self): ('https://adwords.google.com/api/adwords/reportdownload/%s' % self.version), post_body, headers) self.opener.open.assert_called_once_with(mock_request.return_value) - self.assertEqual(content, s) + self.assertEqual(report_data, s) self.header_handler.GetReportDownloadHeaders.assert_called_once_with( include_zero_impressions=True, use_raw_enum_values=False) @@ -1676,16 +1770,25 @@ def testDownloadReport_failure(self): post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers - content = u'Page not found. :-(' - fake_request = io.StringIO() if PYTHON2 else io.BytesIO() - fake_request.write(content if PYTHON2 else bytes(content, 'utf-8')) - fake_request.seek(0) - error = urllib2.HTTPError('', 400, 'Bad Request', {}, fp=fake_request) + report_data = u'Page not found. :-(' + report_contents = io.StringIO() if PYTHON2 else io.BytesIO() + report_contents.write(report_data if PYTHON2 else bytes(report_data, + 'utf-8')) + report_contents.seek(0) + fake_response = mock.Mock() + fake_response.read = report_contents.read + fake_response.msg = 'fake message' + fake_response.code = '200' + error = urllib2.HTTPError('', 400, 'Bad Request', {}, fp=fake_response) self.marshaller.process.return_value = serialized_report with mock.patch('suds.mx.Content') as mock_content: with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = 'https://google.com/' + mock_request_instance.headers = {} self.opener.open.side_effect = error self.assertRaises( googleads.errors.AdWordsReportError, @@ -1710,13 +1813,22 @@ def testDownloadReportWithAwql(self): post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers - content = u'CONTENT STRING 广告客户' - fake_request = io.StringIO() if PYTHON2 else io.BytesIO() - fake_request.write(content if PYTHON2 else bytes(content, 'utf-8')) - fake_request.seek(0) + report_data = u'CONTENT STRING 广告客户' + report_contents = io.StringIO() if PYTHON2 else io.BytesIO() + report_contents.write(report_data if PYTHON2 else bytes(report_data, + 'utf-8')) + report_contents.seek(0) + fake_response = mock.Mock() + fake_response.read = report_contents.read + fake_response.msg = 'fake message' + fake_response.code = '200' with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - self.opener.open.return_value = fake_request + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = 'https://google.com/' + mock_request_instance.headers = {} + self.opener.open.return_value = fake_response self.report_downloader.DownloadReportWithAwql( query, file_format, output_file) @@ -1725,7 +1837,7 @@ def testDownloadReportWithAwql(self): % self.version), post_body, headers) self.opener.open.assert_called_once_with(mock_request.return_value) - self.assertEqual(content, output_file.getvalue()) + self.assertEqual(report_data, output_file.getvalue()) self.header_handler.GetReportDownloadHeaders.assert_called_once_with() def testDownloadReportWithBytesIO(self): @@ -1738,16 +1850,24 @@ def testDownloadReportWithBytesIO(self): post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers - content = u'CONTENT STRING 广告客户' - fake_request = io.BytesIO() - fake_request.write(content.encode('utf-8') if PYTHON2 - else bytes(content, 'utf-8')) - fake_request.seek(0) + report_data = u'CONTENT STRING 广告客户' + report_contents = io.BytesIO() + report_contents.write(report_data.encode('utf-8') if PYTHON2 + else bytes(report_data, 'utf-8')) + report_contents.seek(0) + fake_response = mock.Mock() + fake_response.read = report_contents.read + fake_response.msg = 'fake message' + fake_response.code = '200' self.marshaller.process.return_value = serialized_report with mock.patch('suds.mx.Content') as mock_content: with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - self.opener.open.return_value = fake_request + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = 'https://google.com/' + mock_request_instance.headers = {} + self.opener.open.return_value = fake_response self.report_downloader.DownloadReport(report_definition, output_file) mock_request.assert_called_once_with( ('https://adwords.google.com/api/adwords/reportdownload/%s' @@ -1755,7 +1875,7 @@ def testDownloadReportWithBytesIO(self): self.opener.open.assert_called_once_with(mock_request.return_value) self.marshaller.process.assert_called_once_with( mock_content.return_value) - self.assertEqual(content, output_file.getvalue().decode('utf-8')) + self.assertEqual(report_data, output_file.getvalue().decode('utf-8')) self.header_handler.GetReportDownloadHeaders.assert_called_once_with() def testExtractError_badRequest(self): @@ -1818,6 +1938,33 @@ def testExtractError_notBadRequest(self): self.assertEqual(content, rval.content) self.assertIsInstance(rval, googleads.errors.AdWordsReportError) + def testSanitizeRequestHeaders(self): + redacted_text = 'REDACTED' + headers = { + 'foo': 'bar', + 'Developertoken': 'abc123doremi', + 'Authorization': 'Authorization', + 'lorem': 'ipsum' + } + + sanitized_headers = self.report_downloader._SanitizeRequestHeaders(headers) + + self.assertNotEqual(headers, sanitized_headers) + self.assertEqual(sanitized_headers['Developertoken'], redacted_text) + self.assertEqual(sanitized_headers['Authorization'], redacted_text) + + def testExtractResponseHeaders(self): + headers = '\n\n\nfoo: bar\nlorem: ipsum\ntomayto: tomahto\n' + expected_headers = { + 'foo': 'bar', + 'lorem': 'ipsum', + 'tomayto': 'tomahto' + } + + dict_headers = self.report_downloader._ExtractResponseHeaders(headers) + + self.assertEqual(dict_headers, expected_headers) + if __name__ == '__main__': unittest.main() diff --git a/tests/common_test.py b/tests/common_test.py index b09c1ae2..20261188 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -61,6 +61,10 @@ def setUp(self): self.test2_name = 'Test2' self.test2_version = 'testing' + locale_patcher = mock.patch('googleads.common.locale.getdefaultlocale', + return_value=('en_us', 'UTF-8')) + self.locale_patcher = locale_patcher.start() + @googleads.common.RegisterUtility(self.test1_name) class Test1(object): @@ -77,10 +81,29 @@ def test(self): self.test1 = Test1 self.test2 = Test2 + def tearDown(self): + self.locale_patcher.stop() + + def testShouldWarnWithBadEncoding(self): + self.locale_patcher.return_value = (None, None) + yaml_doc = self._CreateYamlDoc({'one': {'needed': 'd', 'keys': 'e'}}, + 'one', self._OAUTH_INSTALLED_APP_DICT) + test_major_value = 2 + test_minor_value = 6 + test_micro_value = 9 + with mock.patch('googleads.common._PY_VERSION_MAJOR', test_major_value): + with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): + with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): + with mock.patch('googleads.common._logger') as mock_logger: + with mock.patch( + 'googleads.common.open', self.fake_open, create=True): + googleads.common.LoadFromString(yaml_doc, 'one', + ['needed', 'keys'], ['other']) + mock_logger.warn.assert_called_once() + def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): """Return the filename of a yaml file created for testing.""" yaml_file = self.tempfile.NamedTemporaryFile(delete=False) - with self.fake_open(yaml_file.name, 'w') as yaml_handle: for key in data: if key is insert_oauth2_key: @@ -116,8 +139,9 @@ def testLoadFromStorage_missingRequiredKey(self): def testLoadFromStorage(self): # No optional keys present. - yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e'}}, - 'one', self._OAUTH_INSTALLED_APP_DICT) + yaml_fname = self._CreateYamlFile( + {'one': {'needed': 'd', 'keys': 'e'}}, 'one', + self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: @@ -136,27 +160,31 @@ def testLoadFromStorage(self): rval) self.assertTrue(googleads.common._utility_registry._enabled) - # The optional key is present. - yaml_fname = self._CreateYamlFile({'one': {'needed': 'd', 'keys': 'e', - 'other': 'f'}}, 'one', - self._OAUTH_INSTALLED_APP_DICT) + # Optional logging configuration key is present. + logging_config = {'foo': 'bar'} + yaml_fname = self._CreateYamlFile( + {'one': {'needed': 'd', 'keys': 'e', 'other': 'f'}, + googleads.common._LOGGING_KEY: logging_config}, + 'one', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: - proxy_config.return_value = mock.Mock() - rval = googleads.common.LoadFromStorage( - yaml_fname, 'one', ['needed', 'keys'], ['other']) - proxy_config.assert_called_once_with( - http_proxy=None, https_proxy=None, cafile=None, - disable_certificate_validation=False) - mock_client.assert_called_once_with( - 'a', 'b', 'c', proxy_config=proxy_config.return_value) - self.assertEqual({'oauth2_client': mock_client.return_value, - 'needed': 'd', 'keys': 'e', 'other': 'f', - 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, - rval) - self.assertTrue(googleads.common._utility_registry._enabled) + with mock.patch('logging.config.dictConfig') as mock_dict_config: + proxy_config.return_value = mock.Mock() + rval = googleads.common.LoadFromStorage( + yaml_fname, 'one', ['needed', 'keys'], ['other']) + proxy_config.assert_called_once_with( + http_proxy=None, https_proxy=None, cafile=None, + disable_certificate_validation=False) + mock_client.assert_called_once_with( + 'a', 'b', 'c', proxy_config=proxy_config.return_value) + mock_dict_config.assert_called_once_with(logging_config) + self.assertEqual({'oauth2_client': mock_client.return_value, + 'needed': 'd', 'keys': 'e', 'other': 'f', + 'proxy_config': proxy_config.return_value, + googleads.common.ENABLE_COMPRESSION_KEY: False}, + rval) + self.assertTrue(googleads.common._utility_registry._enabled) def testLoadFromStorage_relativePath(self): fake_os = fake_filesystem.FakeOsModule(self.filesystem) @@ -192,6 +220,147 @@ def _CreateYamlDoc(self, data, insert_oauth2_key=None, oauth_dict=None): data[key].update(oauth_dict) return yaml.dump(data) + def testExtractRequestSummaryFieldsForAdWords(self): + root = suds.sax.element.Element('root', parent=None) + client_customer_id = '111-222-3333' + ccid_element = suds.sax.element.Element('clientCustomerId', parent=None) + ccid_element.text = client_customer_id + request_header_element = suds.sax.element.Element('RequestHeader', + parent=None) + header_element = suds.sax.element.Element('Header', parent=None) + method_name = 'someMethodName' + method_element = suds.sax.element.Element(method_name) + body = suds.sax.element.Element('Body', parent=None) + request_header_element.append(ccid_element) + header_element.append(request_header_element) + body.append(method_element) + root.append((header_element, body)) + expected_result = { + 'methodName': method_name, + 'clientCustomerId': client_customer_id + } + + self.assertEqual(expected_result, + googleads.common._ExtractRequestSummaryFields(root)) + + def testExtractRequestSummaryFieldsForDfp(self): + root = suds.sax.element.Element('root', parent=None) + network_code = '111111111' + nc_element = suds.sax.element.Element('networkCode', parent=None) + nc_element.text = network_code + request_header_element = suds.sax.element.Element('RequestHeader', + parent=None) + header_element = suds.sax.element.Element('Header', parent=None) + method_name = 'someMethodName' + method_element = suds.sax.element.Element(method_name) + body = suds.sax.element.Element('Body', parent=None) + request_header_element.append(nc_element) + header_element.append(request_header_element) + body.append(method_element) + root.append((header_element, body)) + expected_result = { + 'methodName': method_name, + 'networkCode': network_code + } + + self.assertEqual(expected_result, + googleads.common._ExtractRequestSummaryFields(root)) + + def testExtractResponseSummaryFieldsWithAdWordsFields(self): + root = suds.sax.element.Element('Envelope', parent=None) + doc = suds.sax.document.Document(root=root) + request_id = '0' + response_time = '1000' + service_name = 'SomeService' + method_name = 'someMethodName' + operations = '0' + rid_element = suds.sax.element.Element('requestId', parent=None) + rid_element.text = request_id + rt_element = suds.sax.element.Element('responseTime', parent=None) + rt_element.text = response_time + service_element = suds.sax.element.Element('serviceName', parent=None) + service_element.text = service_name + method_element = suds.sax.element.Element('methodName', parent=None) + method_element.text = method_name + ops_element = suds.sax.element.Element('operations', parent=None) + ops_element.text = operations + response_header_element = suds.sax.element.Element('ResponseHeader', + parent=None) + header_element = suds.sax.element.Element('Header', parent=None) + body = suds.sax.element.Element('Body', parent=None) + response_header_element.append((rid_element, rt_element, service_element, + method_element, ops_element)) + header_element.append(response_header_element) + root.append((header_element, body)) + expected_result = { + 'requestId': request_id, + 'responseTime': response_time, + 'isFault': False, + 'serviceName': service_name, + 'methodName': method_name, + 'operations': operations + } + + self.assertEqual(expected_result, + googleads.common._ExtractResponseSummaryFields(doc)) + + def testExtractResponseSummaryFieldsWithFault(self): + root = suds.sax.element.Element('Envelope', parent=None) + doc = suds.sax.document.Document(root=root) + request_id = '0' + response_time = '1000' + fault_string = 'I AM ERROR' + rid_element = suds.sax.element.Element('requestId', parent=None) + rid_element.text = suds.sax.text.Text(request_id) + rt_element = suds.sax.element.Element('responseTime', parent=None) + rt_element.text = suds.sax.text.Text(response_time) + response_header_element = suds.sax.element.Element('ResponseHeader', + parent=None) + header_element = suds.sax.element.Element('Header', parent=None) + response_header_element.append((rid_element, rt_element)) + header_element.append(response_header_element) + fault_element = suds.sax.element.Element('Fault', parent=None) + fault_string_element = suds.sax.element.Element('faultstring', parent=None) + fault_string_element.text = suds.sax.text.Text(fault_string) + body = suds.sax.element.Element('Body', parent=None) + fault_element.append(fault_string_element) + body.append(fault_element) + root.append((header_element, body)) + expected_result = { + 'requestId': request_id, + 'responseTime': response_time, + 'isFault': True, + 'faultMessage': fault_string + } + + self.assertEqual(expected_result, + googleads.common._ExtractResponseSummaryFields(doc)) + + def testExtractResponseSummaryFieldsWithoutFault(self): + root = suds.sax.element.Element('Envelope', parent=None) + doc = suds.sax.document.Document(root=root) + request_id = '0' + response_time = '1000' + rid_element = suds.sax.element.Element('requestId', parent=None) + rid_element.text = request_id + rt_element = suds.sax.element.Element('responseTime', parent=None) + rt_element.text = response_time + response_header_element = suds.sax.element.Element('ResponseHeader', + parent=None) + header_element = suds.sax.element.Element('Header', parent=None) + body = suds.sax.element.Element('Body', parent=None) + response_header_element.append((rid_element, rt_element)) + header_element.append(response_header_element) + root.append((header_element, body)) + expected_result = { + 'requestId': request_id, + 'responseTime': response_time, + 'isFault': False + } + + self.assertEqual(expected_result, + googleads.common._ExtractResponseSummaryFields(doc)) + def testLoadFromString_deprecatedWarningLoggerByMicroValue(self): yaml_doc = self._CreateYamlDoc({ 'one': { @@ -845,6 +1014,31 @@ def testSetHeaders(self): mock.Mock()) +class LoggingMessagePluginTest(unittest.TestCase): + """Tests for the googleads.common.LoggingMessagePlugin class.""" + + def setUp(self): + self.logging_message_plugin = googleads.common.LoggingMessagePlugin() + + def testMarshalled(self): + envelope = 'envelope' + marshalled_context = mock.Mock() + marshalled_context.envelope = envelope + + with mock.patch('googleads.common._ExtractRequestSummaryFields') as mk_ext: + self.logging_message_plugin.marshalled(marshalled_context) + mk_ext.assert_called_once_with(envelope) + + def testParsed(self): + reply = 'reply' + parsed_context = mock.Mock() + parsed_context.reply = reply + + with mock.patch('googleads.common._ExtractResponseSummaryFields') as mk_ext: + self.logging_message_plugin.parsed(parsed_context) + mk_ext.assert_called_once_with(reply) + + class ProxyConfigTest(unittest.TestCase): """Tests fpr the googleads.common.ProxyConfig class.""" diff --git a/tests/dfp_test.py b/tests/dfp_test.py index ccee282a..d62e1d35 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -308,7 +308,6 @@ def testInitializeWithUselessApplicationName(self): def testGetService_success(self): service = googleads.dfp._SERVICE_MAP[self.version][0] - dfp_client = self.CreateDfpClient() # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -318,45 +317,30 @@ def testGetService_success(self): 'ProxyConfig._SudsProxyTransport') as mock_transport: with mock.patch('googleads.common.' 'SudsServiceProxy') as mock_service_proxy: - mock_service_proxy.return_value = mock.Mock() - mock_transport.return_value = mock.Mock() - mock_client.return_value = mock.Mock() - mock_client.return_value.sd.__getitem__ = mock.Mock() - suds_service = dfp_client.GetService(service, self.version, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), timeout=3600, - transport=mock_transport.return_value) - self.assertEqual(suds_service, mock_service_proxy.return_value) - mock_service_proxy.assert_called_once_with( - mock_client.return_value, - dfp_client._header_handler, - googleads.dfp._DFPDateTimePacker) - - def testGetService_successWithFileCache(self): - service = googleads.dfp._SERVICE_MAP[self.version][0] - dfp_client = self.CreateDfpClient(cache=suds.cache.FileCache) - - # Use a custom server. Also test what happens if the server ends with a - # trailing slash - server = 'https://testing.test.com/' - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.' - 'ProxyConfig._SudsProxyTransport') as mock_transport: - mock_transport.return_value = mock.Mock() - suds_service = dfp_client.GetService(service, self.version, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), timeout=3600, - cache=suds.cache.FileCache, transport=mock_transport.return_value) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + with mock.patch('googleads.common.LoggingMessagePlugin') as mck_plugn: + mock_plugin_instance = mock.Mock() + mck_plugn.return_value = mock_plugin_instance + dfp_client = self.CreateDfpClient() + mock_service_proxy.return_value = mock.Mock() + mock_transport.return_value = mock.Mock() + mock_client.return_value = mock.Mock() + mock_client.return_value.sd.__getitem__ = mock.Mock() + suds_service = dfp_client.GetService(service, self.version, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service), timeout=3600, + transport=mock_transport.return_value, + plugins=[mock_plugin_instance]) + self.assertEqual(suds_service, mock_service_proxy.return_value) + mock_service_proxy.assert_called_once_with( + mock_client.return_value, + dfp_client._header_handler, + googleads.dfp._DFPDateTimePacker) def testGetService_successWithNoCache(self): service = googleads.dfp._SERVICE_MAP[self.version][0] no_cache = suds.cache.NoCache() - dfp_client = self.CreateDfpClient(cache=no_cache) # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -364,33 +348,42 @@ def testGetService_successWithNoCache(self): with mock.patch('suds.client.Client') as mock_client: with mock.patch('googleads.common.' 'ProxyConfig._SudsProxyTransport') as mock_transport: - mock_transport.return_value = mock.Mock() - suds_service = dfp_client.GetService(service, self.version, server) + with mock.patch('googleads.common.LoggingMessagePlugin') as mck_plugn: + mock_plugin_instance = mock.Mock() + mck_plugn.return_value = mock_plugin_instance + dfp_client = self.CreateDfpClient(cache=no_cache) + mock_transport.return_value = mock.Mock() + suds_service = dfp_client.GetService(service, self.version, server) - mock_client.assert_called_once_with( - 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), timeout=3600, - cache=no_cache, transport=mock_transport.return_value) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + mock_client.assert_called_once_with( + 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service), timeout=3600, + cache=no_cache, transport=mock_transport.return_value, + plugins=[mock_plugin_instance]) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_successWithoutProxy(self): service = googleads.dfp._SERVICE_MAP[self.version][0] - dfp_client = self.CreateDfpClient() - # Use the default server without a proxy. - dfp_client.proxy_option = None with mock.patch('suds.client.Client') as mock_client: with mock.patch('googleads.common.' 'ProxyConfig._SudsProxyTransport') as mock_transport: - mock_transport.return_value = mock.Mock() - suds_service = dfp_client.GetService(service, self.version) + with mock.patch('googleads.common.LoggingMessagePlugin') as mck_plugn: + mock_plugin_instance = mock.Mock() + mck_plugn.return_value = mock_plugin_instance + dfp_client = self.CreateDfpClient() + # Use the default server without a proxy. + dfp_client.proxy_option = None + mock_transport.return_value = mock.Mock() + suds_service = dfp_client.GetService(service, self.version) - mock_client.assert_called_once_with( - 'https://ads.google.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), timeout=3600, - transport=mock_transport.return_value) - self.assertFalse(mock_client.return_value.set_options.called) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + mock_client.assert_called_once_with( + 'https://ads.google.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service), timeout=3600, + transport=mock_transport.return_value, + plugins=[mock_plugin_instance]) + self.assertFalse(mock_client.return_value.set_options.called) + self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_badService(self): dfp_client = self.CreateDfpClient() @@ -656,10 +649,14 @@ def testDownloadReportToFile(self): report_format = 'CSV_DUMP' report_job_id = 't68t3278y429' report_download_url = 'http://google.com/something' - report_contents = 'THIS IS YOUR REPORT!' - fake_request = StringIO.StringIO() - fake_request.write(report_contents) - fake_request.seek(0) + report_data = 'THIS IS YOUR REPORT!' + report_contents = StringIO.StringIO() + report_contents.write(report_data) + report_contents.seek(0) + fake_response = mock.Mock() + fake_response.read = report_contents.read + fake_response.msg = 'fake message' + fake_response.code = '200' outfile = StringIO.StringIO() download_func = self.report_service.getReportDownloadUrlWithOptions @@ -667,7 +664,8 @@ def testDownloadReportToFile(self): with mock.patch('urllib2.OpenerDirector.open' if sys.version_info[0] == 2 else 'urllib.request.OpenerDirector.open') as mock_open: - mock_open.return_value = fake_request + mock_open.return_value = fake_response + self.report_downloader.DownloadReportToFile( report_job_id, report_format, outfile) default_opts = { @@ -678,7 +676,7 @@ def testDownloadReportToFile(self): } download_func.assert_called_once_with(report_job_id, default_opts) mock_open.assert_called_once_with(report_download_url) - self.assertEqual(report_contents, outfile.getvalue()) + self.assertEqual(report_data, outfile.getvalue()) def testGetReportService(self): self.report_downloader._dfp_client = mock.Mock() diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index 58cc19cb..b21a0a5d 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -64,11 +64,37 @@ def testCreateHttpHeader(self): NotImplementedError, googleads.oauth2.GoogleOAuth2Client().CreateHttpHeader) + +class GoogleRefreshableOAuth2ClientTest(unittest.TestCase): + """Tests for the googleads.oauth2.GoogleRefreshableOAuth2Client class.""" + def testRefresh(self): """For coverage.""" self.assertRaises( NotImplementedError, - googleads.oauth2.GoogleOAuth2Client().Refresh) + googleads.oauth2.GoogleRefreshableOAuth2Client().Refresh) + + +class GoogleAccessTokenClientTest(unittest.TestCase): + """Tests for the googleads.oauth2.GoogleAccessTokenClient class.""" + + def setUp(self): + self.access_token = 'a' + self.token_expiry = (datetime.datetime.utcnow() + + datetime.timedelta(seconds=3600)) + self.expired_token_expiry = datetime.datetime(1980, 1, 1, 12) + + def testCreateHttpHeader(self): + client = googleads.oauth2.GoogleAccessTokenClient( + self.access_token, self.token_expiry) + expected_header = {'Authorization': 'Bearer %s' % self.access_token} + self.assertEqual(client.CreateHttpHeader(), expected_header) + + def testCreateHttpHeaderWithExpiredToken(self): + expired_client = googleads.oauth2.GoogleAccessTokenClient( + self.access_token, self.expired_token_expiry) + self.assertRaises(googleads.errors.GoogleAdsError, + expired_client.CreateHttpHeader) class GoogleRefreshTokenClientTest(unittest.TestCase): @@ -117,7 +143,9 @@ def refresh(mock_http): self.oauth2_credentials): self.googleads_client = googleads.oauth2.GoogleRefreshTokenClient( self.client_id, self.client_secret, self.refresh_token, - self.proxy_config) + proxy_config=self.proxy_config, + access_token=self.access_token_unrefreshed, + token_expiry=self.mock_oauth2_credentials.token_expiry) def testCreateHttpHeader_noRefresh(self): header = {'Authorization': 'Bearer %s' % self.access_token_unrefreshed} diff --git a/tests/util_test.py b/tests/util_test.py index a6ba7587..5081d98a 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -272,7 +272,7 @@ class GoogleAdsCommonFilterTest(unittest.TestCase): def setUp(self): self.filter = googleads.util.GetGoogleAdsCommonFilter() - self.omitted_text = 'OMITTED' + self.redacted_text = 'REDACTED' self.dev_token_template = ('%s') def testGetGoogleAdsCommonFilter(self): @@ -284,7 +284,7 @@ def testFilterAtInfoLevel(self): record.args = [self.dev_token_template % 'test'] self.filter.filter(record) self.assertEqual( - record.args, (self.dev_token_template % self.omitted_text,)) + record.args, (self.dev_token_template % self.redacted_text,)) def testFilterAtUnfilteredLevel(self): expected_args = (1, 2, 3, 4, 5) @@ -300,7 +300,7 @@ class SudsClientFilterTest(unittest.TestCase): def setUp(self): self.filter = googleads.util.GetSudsClientFilter() - self.omitted_text = 'OMITTED' + self.redacted_text = 'REDACTED' self.dev_token_template = 'DevToken' self.location = 'https://www.google.com' test_dir = os.path.dirname(__file__) @@ -321,7 +321,7 @@ def testFilterWithSudsClientSOAPMessage(self): self.filter.filter(record) self.assertEqual(record.args, (self.location, (self.test_request_envelope_template - % self.omitted_text))) + % self.redacted_text))) def testFilterWithSudsClientHeadersMessage(self): record = mock.Mock() @@ -329,17 +329,186 @@ def testFilterWithSudsClientHeadersMessage(self): record.args = {'Content-Type': 'text/xml; charset=utf-8', 'Authorization': 'Bearer abc123doremi'} expected_args = {'Content-Type': 'text/xml; charset=utf-8', - 'Authorization': self.omitted_text} + 'Authorization': self.redacted_text} self.filter.filter(record) self.assertEqual(record.args, expected_args) +class SudsMXCoreFilterTest(unittest.TestCase): + """Tests for the SudsMXCoreFilter utility.""" + + _DEVELOPER_TOKEN = 'developerToken' + _REQUEST_HEADER = 'RequestHeader' + + def setUp(self): + self.filter = googleads.util.GetSudsMXCoreFilter() + self.redacted_text = 'REDACTED' + self.developer_token_value = 'abc123doremi' + + def testGetSudsMXCoreFilter(self): + self.assertIs(self.filter, googleads.util.GetSudsMXCoreFilter()) + + def testFilterWithContentDeveloperToken(self): + content = suds.mx.Content(tag=self._DEVELOPER_TOKEN, + value=self.developer_token_value) + + record = mock.Mock() + record.args = [content] + + self.filter.filter(record) + # Verify that the original copy wasn't modified. + self.assertEqual(content.value, self.developer_token_value) + # Verify that the args were modified. + self.assertEqual(record.args[0].value, self.redacted_text) + + def testFilterWithContentRequestHeader(self): + request_header_value = { + self._DEVELOPER_TOKEN: self.developer_token_value + } + expected_filtered_value = { + self._DEVELOPER_TOKEN: self.redacted_text + } + content = suds.mx.Content(tag=self._REQUEST_HEADER, + value=request_header_value) + + record = mock.Mock() + record.args = [content] + + self.filter.filter(record) + # Verify that the original copy wasn't modified. + self.assertEqual(request_header_value[self._DEVELOPER_TOKEN], + self.developer_token_value) + # Verify that the args were modified. + self.assertEqual(record.args[0].value, expected_filtered_value) + + def testFilterWithElementRequestHeader(self): + request_header_element = suds.sax.element.Element( + self._REQUEST_HEADER, parent=None) + child = suds.sax.element.Element(self._DEVELOPER_TOKEN, parent=None) + child.text = suds.sax.text.Text(self.developer_token_value) + request_header_element.append(child) + + record = mock.Mock() + record.args = [request_header_element] + + self.filter.filter(record) + # Verify that the original copy wasn't modified. + self.assertEqual(child.text, suds.sax.text.Text(self.developer_token_value)) + # Verify that the args were modified. + self.assertEqual(record.args[0].getChild(self._DEVELOPER_TOKEN).text, + suds.sax.text.Text(self.redacted_text)) + + def testFilterWithNoArgs(self): + record = mock.Mock() + record.args = [] + self.filter.filter(record) + + def testFilterWithNoRequestHeader(self): + foo_value = 'bar' + lorem_value = 'ipsum' + potayto_value = 'potahto' + request_header_value = { + 'foo': foo_value, + 'lorem': lorem_value, + 'potayto': potayto_value + } + content = suds.mx.Content(tag=self._REQUEST_HEADER, + value=request_header_value) + + record = mock.Mock() + record.args = [content] + + self.filter.filter(record) + # Verify that the original copy wasn't modified. + self.assertEqual(request_header_value['foo'], foo_value) + self.assertEqual(request_header_value['lorem'], lorem_value) + self.assertEqual(request_header_value['potayto'], potayto_value) + # Verify that the args weren't modified. + self.assertEqual(record.args[0].value, request_header_value) + + +class SudsMXLiteralFilterTest(unittest.TestCase): + """Tests for the SudsMXLiteralFilter utility.""" + + _DEVELOPER_TOKEN = 'developerToken' + _REQUEST_HEADER = 'RequestHeader' + + def setUp(self): + self.filter = googleads.util.GetSudsMXLiteralFilter() + self.redacted_text = 'REDACTED' + self.developer_token_value = 'abc123doremi' + + def testGetSudsMXLiteralFilter(self): + self.assertIs(self.filter, googleads.util.GetSudsMXLiteralFilter()) + + def testFilterWithContentDeveloperToken(self): + content = suds.mx.Content(tag=self._DEVELOPER_TOKEN, + value=self.developer_token_value) + + record = mock.Mock() + record.args = [content] + + self.filter.filter(record) + # Verify that the original copy wasn't modified. + self.assertEqual(content.value, self.developer_token_value) + # Verify that the args were modified. + self.assertEqual(record.args[0].value, self.redacted_text) + + def testFilterWithContentRequestHeader(self): + request_header_value = { + self._DEVELOPER_TOKEN: self.developer_token_value + } + expected_filtered_value = { + self._DEVELOPER_TOKEN: self.redacted_text + } + content = suds.mx.Content(tag=self._REQUEST_HEADER, + value=request_header_value) + + record = mock.Mock() + record.args = [content] + + self.filter.filter(record) + # Verify that the original copy wasn't modified. + self.assertEqual(request_header_value[self._DEVELOPER_TOKEN], + self.developer_token_value) + # Verify that the args were modified. + self.assertEqual(record.args[0].value, expected_filtered_value) + + def testFilterWithNoArgs(self): + record = mock.Mock() + record.args = [] + self.filter.filter(record) + + def testFilterWithNoRequestHeader(self): + foo_value = 'bar' + lorem_value = 'ipsum' + potayto_value = 'potahto' + request_header_value = { + 'foo': foo_value, + 'lorem': lorem_value, + 'potayto': potayto_value + } + content = suds.mx.Content(tag=self._REQUEST_HEADER, + value=request_header_value) + + record = mock.Mock() + record.args = [content] + + self.filter.filter(record) + # Verify that the original copy wasn't modified. + self.assertEqual(request_header_value['foo'], foo_value) + self.assertEqual(request_header_value['lorem'], lorem_value) + self.assertEqual(request_header_value['potayto'], potayto_value) + # Verify that the args weren't modified. + self.assertEqual(record.args[0].value, request_header_value) + + class SudsTransportFilterTest(unittest.TestCase): """Tests for the SudsTransportFilter utility.""" def setUp(self): self.filter = googleads.util.GetSudsTransportFilter() - self.omitted_text = 'OMITTED' + self.redacted_text = 'REDACTED' self.dev_token_template = 'DevToken' self.location = 'https://www.google.com' test_dir = os.path.dirname(__file__) @@ -357,13 +526,13 @@ def testFilterSudsTransportRequest(self): request_instance.message = (self.test_request_envelope_template % self.dev_token_template) expected_headers = {'User-Agent': 'user-agent', - 'Authorization': self.omitted_text} + 'Authorization': self.redacted_text} record = mock.Mock() record.args = (request_instance,) self.filter.filter(record) self.assertEqual(record.args[0].headers, expected_headers) self.assertEqual(record.args[0].message, - self.test_request_envelope_template % self.omitted_text) + self.test_request_envelope_template % self.redacted_text) if __name__ == '__main__': From 07c8698a67a4b60c87a0b6e1f4c0d7d12b19e4ff Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 27 Jun 2017 17:12:14 -0400 Subject: [PATCH 080/180] Commiting latest changes. From c43b8e4d33547bdfc3ba61fa55dba6ada8da0200 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 9 Aug 2017 15:15:20 -0400 Subject: [PATCH 081/180] AdWords v201708 Release. --- examples/adwords/v201708/__init__.py | 15 + .../v201708/account_management/__init__.py | 15 + .../account_management/accept_service_link.py | 62 +++ .../account_management/create_account.py | 63 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201708/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 222 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 126 +++++ .../add_dynamic_page_feed.py | 295 ++++++++++ .../add_dynamic_search_ads_campaign.py | 257 +++++++++ ...add_expanded_text_ad_with_upgraded_urls.py | 109 ++++ .../advanced_operations/add_html5_ad.py | 111 ++++ .../add_responsive_display_ad.py | 158 ++++++ .../add_universal_app_campaign.py | 217 ++++++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201708/basic_operations/__init__.py | 15 + .../v201708/basic_operations/add_ad_groups.py | 115 ++++ .../v201708/basic_operations/add_campaigns.py | 128 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201708/basic_operations/add_keywords.py | 92 +++ .../v201708/basic_operations/get_ad_groups.py | 76 +++ .../v201708/basic_operations/get_campaigns.py | 74 +++ .../get_campaigns_with_awql.py | 64 +++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201708/basic_operations/get_keywords.py | 87 +++ .../v201708/basic_operations/pause_ad.py | 61 ++ .../v201708/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 58 ++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201708/campaign_management/__init__.py | 15 + ...campaign_groups_and_performance_targets.py | 152 +++++ .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 428 ++++++++++++++ .../v201708/campaign_management/add_draft.py | 81 +++ ...dd_keywords_using_incremental_batch_job.py | 259 +++++++++ .../v201708/campaign_management/add_trial.py | 116 ++++ .../get_all_disapproved_ads.py | 92 +++ .../get_all_disapproved_ads_with_awql.py | 76 +++ .../get_campaigns_by_label.py | 85 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201708/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 131 +++++ .../handle_policy_violation_error.py | 167 ++++++ .../adwords/v201708/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../adwords/v201708/extensions/add_prices.py | 157 ++++++ .../v201708/extensions/add_site_links.py | 146 +++++ .../extensions/add_site_links_using_feeds.py | 236 ++++++++ .../adwords/v201708/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 527 ++++++++++++++++++ examples/adwords/v201708/misc/__init__.py | 15 + .../v201708/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201708/misc/upload_image.py | 66 +++ .../v201708/misc/upload_media_bundle.py | 59 ++ .../adwords/v201708/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 180 ++++++ ...aign_criterion_bid_modifier_simulations.py | 96 ++++ .../get_keyword_bid_simulations.py | 81 +++ .../v201708/optimization/get_keyword_ideas.py | 100 ++++ .../adwords/v201708/remarketing/__init__.py | 15 + .../v201708/remarketing/add_audience.py | 103 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_conversion_trackers.py | 106 ++++ .../remarketing/add_crm_based_user_list.py | 101 ++++ .../remarketing/add_rule_based_user_lists.py | 235 ++++++++ .../upload_offline_call_conversions.py | 77 +++ .../remarketing/upload_offline_conversions.py | 82 +++ .../adwords/v201708/reporting/__init__.py | 15 + ...oad_criteria_report_as_stream_with_awql.py | 81 +++ ...criteria_report_as_stream_with_selector.py | 77 +++ ...oad_criteria_report_as_string_with_awql.py | 55 ++ ...criteria_report_as_string_with_selector.py | 59 ++ .../download_criteria_report_with_awql.py | 55 ++ .../download_criteria_report_with_selector.py | 60 ++ .../v201708/reporting/get_report_fields.py | 52 ++ .../reporting/parallel_report_download.py | 230 ++++++++ examples/adwords/v201708/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 281 ++++++++++ .../v201708/shopping/add_product_scope.py | 104 ++++ .../v201708/shopping/add_shopping_campaign.py | 172 ++++++ .../add_shopping_campaign_for_showcase_ads.py | 404 ++++++++++++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201708/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 126 +++++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201708/targeting/lookup_location.py | 82 +++ .../get_all_activity_groups.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../get_all_audience_segments.py | 4 +- .../base_rate_service/get_all_base_rates.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../contact_service/get_all_contacts.py | 4 +- ...et_all_content_metadata_key_hierarchies.py | 4 +- .../content_service/get_all_content.py | 4 +- .../creative_service/get_all_creatives.py | 4 +- .../get_all_creative_sets.py | 4 +- .../get_all_creative_templates.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../get_all_custom_fields.py | 4 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- .../get_all_exchange_rates.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../v201611/label_service/get_all_labels.py | 4 +- .../get_all_licas.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/get_all_line_items.py | 4 +- .../v201611/order_service/get_all_orders.py | 4 +- .../package_service/get_all_packages.py | 4 +- .../placement_service/create_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../get_all_premium_rates.py | 4 +- .../get_all_product_package_items.py | 4 +- .../get_all_product_packages.py | 4 +- .../product_service/get_all_products.py | 4 +- .../get_all_product_templates.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../proposal_service/get_all_proposals.py | 4 +- .../rate_card_service/get_all_rate_cards.py | 4 +- .../get_all_reconciliation_reports.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- .../dfp/v201611/team_service/get_all_teams.py | 4 +- .../dfp/v201611/user_service/get_all_users.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_all_activity_groups.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../get_all_audience_segments.py | 4 +- .../base_rate_service/get_all_base_rates.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../contact_service/get_all_contacts.py | 4 +- ...et_all_content_metadata_key_hierarchies.py | 4 +- .../content_service/get_all_content.py | 4 +- .../creative_service/get_all_creatives.py | 4 +- .../get_all_creative_sets.py | 4 +- .../get_all_creative_templates.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../get_all_custom_fields.py | 4 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- .../get_all_exchange_rates.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../v201702/label_service/get_all_labels.py | 4 +- .../get_all_licas.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_all_native_styles.py | 4 +- .../v201702/order_service/get_all_orders.py | 4 +- .../package_service/get_all_packages.py | 4 +- .../placement_service/create_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../get_all_premium_rates.py | 4 +- .../get_all_product_package_items.py | 4 +- .../get_all_product_packages.py | 4 +- .../product_service/get_all_products.py | 4 +- .../get_all_product_templates.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../proposal_service/get_all_proposals.py | 4 +- .../rate_card_service/get_all_rate_cards.py | 4 +- .../get_all_reconciliation_reports.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- .../dfp/v201702/team_service/get_all_teams.py | 4 +- .../dfp/v201702/user_service/get_all_users.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_all_activity_groups.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../get_all_audience_segments.py | 4 +- .../base_rate_service/get_all_base_rates.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../contact_service/get_all_contacts.py | 4 +- ...et_all_content_metadata_key_hierarchies.py | 4 +- .../content_service/get_all_content.py | 4 +- .../creative_service/get_all_creatives.py | 4 +- .../get_all_creative_sets.py | 4 +- .../get_all_creative_templates.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../get_all_custom_fields.py | 4 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- .../get_all_exchange_rates.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../v201705/label_service/get_all_labels.py | 4 +- .../get_all_licas.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_all_native_styles.py | 4 +- .../v201705/order_service/get_all_orders.py | 4 +- .../package_service/get_all_packages.py | 4 +- .../placement_service/create_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../get_all_premium_rates.py | 4 +- .../get_all_product_package_items.py | 4 +- .../get_all_product_packages.py | 4 +- .../product_service/get_all_products.py | 4 +- .../get_all_product_templates.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../proposal_service/get_all_proposals.py | 4 +- .../rate_card_service/get_all_rate_cards.py | 4 +- .../get_all_reconciliation_reports.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- .../dfp/v201705/team_service/get_all_teams.py | 4 +- .../dfp/v201705/user_service/get_all_users.py | 4 +- .../get_all_user_team_associations.py | 4 +- googleads/adwords.py | 50 ++ 214 files changed, 11047 insertions(+), 226 deletions(-) create mode 100644 examples/adwords/v201708/__init__.py create mode 100644 examples/adwords/v201708/account_management/__init__.py create mode 100755 examples/adwords/v201708/account_management/accept_service_link.py create mode 100755 examples/adwords/v201708/account_management/create_account.py create mode 100755 examples/adwords/v201708/account_management/get_account_changes.py create mode 100755 examples/adwords/v201708/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201708/advanced_operations/__init__.py create mode 100755 examples/adwords/v201708/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201708/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201708/advanced_operations/add_dynamic_page_feed.py create mode 100755 examples/adwords/v201708/advanced_operations/add_dynamic_search_ads_campaign.py create mode 100755 examples/adwords/v201708/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201708/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py create mode 100755 examples/adwords/v201708/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201708/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201708/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201708/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201708/basic_operations/__init__.py create mode 100755 examples/adwords/v201708/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201708/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201708/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201708/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201708/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201708/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201708/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201708/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201708/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201708/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201708/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201708/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201708/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201708/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201708/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201708/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201708/campaign_management/__init__.py create mode 100755 examples/adwords/v201708/campaign_management/add_campaign_groups_and_performance_targets.py create mode 100755 examples/adwords/v201708/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201708/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201708/campaign_management/add_draft.py create mode 100755 examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201708/campaign_management/add_trial.py create mode 100755 examples/adwords/v201708/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201708/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201708/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201708/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201708/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201708/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201708/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201708/error_handling/__init__.py create mode 100755 examples/adwords/v201708/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201708/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201708/extensions/__init__.py create mode 100755 examples/adwords/v201708/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201708/extensions/add_prices.py create mode 100755 examples/adwords/v201708/extensions/add_site_links.py create mode 100755 examples/adwords/v201708/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201708/migration/__init__.py create mode 100755 examples/adwords/v201708/migration/migrate_to_extension_settings.py create mode 100644 examples/adwords/v201708/misc/__init__.py create mode 100755 examples/adwords/v201708/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201708/misc/upload_image.py create mode 100755 examples/adwords/v201708/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201708/optimization/__init__.py create mode 100755 examples/adwords/v201708/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201708/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201708/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201708/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201708/remarketing/__init__.py create mode 100755 examples/adwords/v201708/remarketing/add_audience.py create mode 100755 examples/adwords/v201708/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201708/remarketing/add_conversion_trackers.py create mode 100755 examples/adwords/v201708/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201708/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201708/remarketing/upload_offline_call_conversions.py create mode 100755 examples/adwords/v201708/remarketing/upload_offline_conversions.py create mode 100644 examples/adwords/v201708/reporting/__init__.py create mode 100755 examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_selector.py create mode 100755 examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201708/reporting/download_criteria_report_as_string_with_selector.py create mode 100755 examples/adwords/v201708/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201708/reporting/download_criteria_report_with_selector.py create mode 100755 examples/adwords/v201708/reporting/get_report_fields.py create mode 100755 examples/adwords/v201708/reporting/parallel_report_download.py create mode 100644 examples/adwords/v201708/shopping/__init__.py create mode 100755 examples/adwords/v201708/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201708/shopping/add_product_scope.py create mode 100755 examples/adwords/v201708/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py create mode 100755 examples/adwords/v201708/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201708/targeting/__init__.py create mode 100755 examples/adwords/v201708/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201708/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201708/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201708/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201708/targeting/lookup_location.py diff --git a/examples/adwords/v201708/__init__.py b/examples/adwords/v201708/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201708/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201708/account_management/__init__.py b/examples/adwords/v201708/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201708/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201708/account_management/accept_service_link.py b/examples/adwords/v201708/account_management/accept_service_link.py new file mode 100755 index 00000000..c560727b --- /dev/null +++ b/examples/adwords/v201708/account_management/accept_service_link.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' + + +def main(client, service_link_id): + # Initialize appropriate service. + customer_service = client.GetService( + 'CustomerService', version='v201708') + + # Create the operation to set the status to ACTIVE. + operations = [{ + 'operator': 'SET', + 'operand': { + 'serviceLinkId': service_link_id, + 'serviceType': 'MERCHANT_CENTER', + 'linkStatus': 'ACTIVE', + } + }] + + # Update the service link. + mutated_service_links = customer_service.mutateServiceLinks(operations) + + # Display results. + for mutated_service_link in mutated_service_links: + print ('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201708/account_management/create_account.py b/examples/adwords/v201708/account_management/create_account.py new file mode 100755 index 00000000..4fb7e68e --- /dev/null +++ b/examples/adwords/v201708/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201708') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID "%s" was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/account_management/get_account_changes.py b/examples/adwords/v201708/account_management/get_account_changes.py new file mode 100755 index 00000000..47d547b6 --- /dev/null +++ b/examples/adwords/v201708/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201708') + campaign_service = client.GetService('CampaignService', version='v201708') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id "%s" has change status "%s".' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id "%s" has change status "%s".' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/account_management/get_account_hierarchy.py b/examples/adwords/v201708/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..42a1f7c6 --- /dev/null +++ b/examples/adwords/v201708/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201708') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/__init__.py b/examples/adwords/v201708/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201708/advanced_operations/add_ad_customizer.py b/examples/adwords/v201708/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..a30054cb --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_ad_customizer.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates ExpandedTextAds that use ad customizations for specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no ExpandedTextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201708') + + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'headlinePart2': 'Only {=%s.Price}' % feed_name, + 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': expanded_text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID "%s", type "%s", and status "%s".' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201708') + + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name "%s" and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService', 'v201708') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + return {'operator': 'ADD', 'operand': feed_item} + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201708/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201708/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..c04e39f7 --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201708') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..90f7106b --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Optionally, you may specify a landscape image. The image needs to be in a + # BASE64 encoded form. Here we download a demo image and encode it for this + # ad. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + }, + { + 'name': 'landscapeImage', + 'fieldMedia': { + 'xsi_type': 'Image', + 'data': image_data + }, + 'type': 'IMAGE' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201708/advanced_operations/add_dynamic_page_feed.py new file mode 100755 index 00000000..ed3f853f --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_dynamic_page_feed.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. + +To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +from collections import namedtuple +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + +# Used to keep track of DSA page feed details. +_DSAFeedDetails = namedtuple( + '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) +# ID that corresponds to the labels. +DSA_LABEL_FIELD_ID = 2 +# The criterion type to be used for DSA page feeds. +DSA_PAGE_FEED_CRITERION_TYPE = 61 +DSA_PAGE_URL_LABEL = 'discounts' +# ID that corresponds to the page URLs. +DSA_PAGE_URLS_FIELD_ID = 1 + + +def main(client, campaign_id, ad_group_id): + # Get the page feed details. This code example creates a new feed, but you can + # fetch and re-use an existing feed. + feed_details = _CreateFeed(client) + _CreateFeedMapping(client, feed_details) + _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) + + # Associate the page feed with the campaign. + _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) + + # Optional: Target web pages matching the feed's label in the ad group. + _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) + + print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + + +def _CreateFeed(client): + """Creates the feed for DSA page URLs. + + Args: + client: an AdWordsClient instance. + + Returns: + A _DSAFeedDetails instance containing details about the created feed. + """ + # Get the FeedService. + feed_service = client.GetService('FeedService', version='v201708') + + # Create operation. + operation = { + # Create the feed. + 'operand': { + 'name': 'DSA Feed %s' % uuid.uuid4(), + # Create attributes. + 'attributes': [ + {'type': 'URL_LIST', 'name': 'Page URL'}, + {'type': 'STRING_LIST', 'name': 'Label'} + ], + 'origin': 'USER' + }, + 'operator': 'ADD' + } + + # Add the feed. + feed = feed_service.mutate([operation])['value'][0] + return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], + feed['attributes'][1]['id']) + + +def _CreateFeedMapping(client, feed_details): + """Creates the feed mapping for DSA page feeds. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + """ + # Get the FeedMappingService. + feed_mapping_service = client.GetService('FeedMappingService', + version='v201708') + + # Create the operation. + operation = { + # Create the feed mapping. + 'operand': { + 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, + 'feedId': feed_details.feed_id, + # Map the feedAttributeIds to the fieldId constants. + 'attributeFieldMappings': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'fieldId': DSA_PAGE_URLS_FIELD_ID + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'fieldId': DSA_LABEL_FIELD_ID + } + ] + }, + 'operator': 'ADD' + } + + # Add the feed mapping. + feed_mapping_service.mutate([operation]) + + +def _CreateFeedItems(client, feed_details, label_name): + """Creates the page URLs in the DSA page feed. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + label_name: a str containing the page feed URL label. + """ + # Get the FeedItemService. + feed_item_service = client.GetService('FeedItemService', version='v201708') + + # Optional: You can include the {feeditem} valuetrack parameter to track which + # page feed items lead to each click. + urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', + 'http://www.example.com/discounts/hotel-deals?id={feeditem}', + 'http://www.example.com/discounts/flight-deals?id={feeditem}') + + # Create the operation. + operations = [{ + # Create the feed item. + 'operand': { + 'feedId': feed_details.feed_id, + 'attributeValues': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'stringValues': [url] + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'stringValues': [label_name] + } + ] + }, + 'operator': 'ADD' + } for url in urls] + + # Add the feed item. + feed_item_service.mutate(operations) + + +def _UpdateCampaignDSASetting(client, campaign_id, feed_id): + """Updates the campaign DSA setting to DSA pagefeeds. + + Args: + client: an AdWordsClient instance. + campaign_id: a str Campaign ID. + feed_id: a str page Feed ID. + + Raises: + ValueError: If the given campaign is found not to be a dynamic search ad + campaign. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201708') + + selector = { + 'fields': ['Id', 'Settings'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [campaign_id] + }] + } + + response = campaign_service.get(selector) + + if response['totalNumEntries']: + campaign = response['entries'][0] + else: + raise ValueError('No campaign with ID "%d" exists.' % campaign_id) + + if not campaign['settings']: + raise ValueError('This is not a DSA campaign.') + + dsa_setting = None + + campaign_settings = campaign['settings'] + + for setting in campaign_settings: + if setting['Setting.Type'] == 'DynamicSearchAdsSetting': + dsa_setting = setting + break + + if dsa_setting is None: + raise ValueError('This is not a DSA campaign.') + + dsa_setting['pageFeed'] = { + 'feedIds': [feed_id] + } + + # Optional: Specify whether only the supplied URLs should be used with your + # Dynamic Search Ads. + dsa_setting['useSuppliedUrlsOnly'] = True + + operation = { + 'operand': { + 'id': campaign_id, + 'settings': campaign_settings + }, + 'operator': 'SET' + } + + campaign_service.mutate([operation]) + print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id) + + +def _AddDSATargeting(client, ad_group_id, label_name): + """Set custom targeting for the page feed URLs based on a list of labels. + + Args: + client: an AdWordsClient instance. + ad_group_id: a str AdGroup ID. + label_name: a str label name. + + Returns: + A suds.sudsobject.Object representing the newly created webpage criterion. + """ + # Get the AdGroupCriterionService. + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201708') + + # Create the operation. + operation = { + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Test criterion', + # Add a condition for label=specified_label_name. + 'conditions': [{ + 'operand': 'CUSTOM_LABEL', + 'argument': label_name + }], + } + }, + # Set a custom bid for this criterion + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 1500000 + } + }] + } + }, + 'operator': 'ADD' + } + + criterion = ad_group_criterion_service.mutate([operation])['value'][0] + print 'Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus']) + return criterion + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201708/advanced_operations/add_dynamic_search_ads_campaign.py new file mode 100755 index 00000000..42b61fb1 --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_dynamic_search_ads_campaign.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Dynamic Search Ads campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + budget = _CreateBudget(client) + campaign_id = _CreateCampaign(client, budget) + ad_group_id = _CreateAdGroup(client, campaign_id) + _CreateExpandedDSA(client, ad_group_id) + _AddWebPageCriteria(client, ad_group_id) + + print 'Dynamic Search Ads campaign setup is complete.' + + +def _CreateBudget(client): + """Creates the budget. + + Args: + client: an AdWordsClient instance. + + Returns: + a suds.sudsobject.Object representation of the created budget. + """ + budget_service = client.GetService('BudgetService', version='v201708') + + # Create the campaign budget + operation = { + 'operand': { + 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), + 'deliveryMethod': 'STANDARD', + 'amount': { + 'microAmount': 500000 + } + }, + 'operator': 'ADD' + } + + budget = budget_service.mutate([operation])['value'][0] + + print 'Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name']) + + return budget + + +def _CreateCampaign(client, budget): + """Creates the campaign. + + Args: + client: an AdWordsClient instance. + budget: a suds.sudsobject.Object representation of a created budget. + + Returns: + An integer campaign ID. + """ + campaign_service = client.GetService('CampaignService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # prevent the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'budget': budget, + # Required: Set the campaign's Dynamic Search Ad settings. + 'settings': [{ + 'xsi_type': 'DynamicSearchAdsSetting', + # Required: Set the domain name and language. + 'domainName': 'example.com', + 'languageCode': 'en' + }], + # Optional: Set the start date. + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + # Optional: Set the end date. + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + }] + + campaign = campaign_service.mutate(operations)['value'][0] + campaign_id = campaign['id'] + + print 'Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name']) + + return campaign_id + + +def _CreateAdGroup(client, campaign_id): + """Creates an ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: an integer campaign ID. + + Returns: + An integer ad group ID. + """ + ad_group_service = client.GetService('AdGroupService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'adGroupType': 'SEARCH_DYNAMIC_ADS', + 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '3000000' + }, + }] + } + } + }] + + ad_group = ad_group_service.mutate(operations)['value'][0] + ad_group_id = ad_group['id'] + + print 'Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name']) + + return ad_group_id + + +def _CreateExpandedDSA(client, ad_group_id): + """Creates the expanded Dynamic Search Ad. + + Args: + client: an AdwordsClient instance. + ad_group_id: an integer ID of the ad group in which the DSA is added. + """ + # Get the AdGroupAdService. + ad_group_ad_service = client.GetService('AdGroupAdService') + + # Create the operation + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + # Create the expanded dynamic search ad. This ad will have its + # headline and final URL auto-generated at serving time according to + # domain name specific information provided by DynamicSearchAdsSetting + # at the campaign level. + 'ad': { + 'xsi_type': 'ExpandedDynamicSearchAd', + # Set the ad description. + 'description': 'Buy your tickets now!' + }, + # Optional: Set the status. + 'status': 'PAUSED', + } + }] + + # Create the ad. + ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] + + # Display the results. + print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' + 'added' % (ad['id'], ad['description'])) + + +def _AddWebPageCriteria(client, ad_group_id): + """Adds a web page criterion to target Dynamic Search Ads. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID of the ad group the criteria is being added to. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201708') + + operations = [{ + 'operator': 'ADD', + # Create biddable ad group criterion. + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion for special offers for children. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Special offers for children.', + 'conditions': [ + { + 'operand': 'URL', + 'argument': '/marscruise/children' + }, + { + 'operand': 'PAGE_TITLE', + 'argument': 'Special Offer' + } + ] + } + }, + 'userStatus': 'PAUSED', + # Optional: set a custom bid. + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000L + } + }] + } + } + }] + + criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201708/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..763963b8 --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Create the expanded text ad + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': expanded_text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_html5_ad.py b/examples/adwords/v201708/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..716d008a --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_html5_ad.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..439cf8a9 --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + media_service = client.GetService('MediaService', version='v201708') + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + + try: + # Create marketing image. + marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/3b9Wfh') + + # Create square marketing image. + square_marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/mtt54n') + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': marketing_image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'], + # Optional: Set a square marketing image to the ad. + 'squareMarketingImage': { + 'mediaId': square_marketing_image['mediaId'] + }, + # Optional: Set call-to-action text. + 'callToActionText': 'Shop Now', + # Optional: Set dynamic display ad settings, composed of + # landscape logo image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( + media_service, opener), + # Whitelisted accounts only: Set color settings using + # hexadecimal numbers. + # Set allowFlexibleColor to False if you want your ads to render + # by always using your colors strictly. + # 'mainColor': '#0000ff', + # 'accentColor': '#ffff00', + # 'allowFlexibleColor': False + # Whitelisted accounts only: Set the format setting that the ad + # will be served in. + # 'formatSetting': 'NON_NATIVE' + + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + image_data = base64.b64encode(opener.open(url).read()) + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +def _CreateDynamicDisplayAdSettings(media_service, opener): + """Creates settings for dynamic display ad. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + + Returns: + The dynamic display ad settings. + """ + image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + + logo = { + 'type': 'IMAGE', + 'mediaId': image['mediaId'], + 'xsi_type': 'Image' + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!', + 'xsi_type': 'DynamicSettings', + } + + return dynamic_settings + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py new file mode 100755 index 00000000..8a58b41a --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Universal App campaign. + +To get campaigns, run get_campaigns.py. To upload image assets for this +campaign, run upload_image.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201708') + + budget_id = CreateBudget(client) + + # Create the Universal App campaign. + universal_app_campaign = { + 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'MULTI_CHANNEL', + 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', + # Set the campaign's bidding strategy. Universal app campaigns only + # support TARGET_CPA bidding strategy. + 'biddingStrategyConfiguration': { + # Set the target CPA to $1 / app install. + 'biddingScheme': { + 'xsi_type': 'TargetCpaBiddingScheme', + 'targetCpa': { + 'microAmount': '1000000' + } + }, + 'biddingStrategyType': 'TARGET_CPA' + }, + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + + universal_app_campaign['settings'] = [ + # Set the campaign's assets and ad text ideas. These values will + # be used to generate ads. + { + 'xsi_type': 'UniversalAppCampaignSetting', + 'appId': 'com.labpixies.colordrips', + 'description1': 'A cool puzzle game', + 'description2': 'Remove connected blocks', + 'description3': '3 difficulty levels', + 'description4': '4 colorful fun skins', + # Optional: You can set up to 10 image assets for your campaign. + # See upload_image.py for an example on how to upload images. + # + # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] + } + ] + + # Optimize this campaign for getting new users for your app. + universal_app_campaign_setting = universal_app_campaign['settings'][0] + universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( + 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') + + # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, + # then also specify your in-app conversion types so AdWords can focus your + # campaign on people who are most likely to complete the corresponding in-app + # actions. + # + # Conversions type IDs can be retrieved using ConversionTrackerService.get. + # universal_app_campaign['selectiveOptimization'] = { + # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] + # } + + # Optional: Set the campaign settings for Advanced location options. + universal_app_campaign['settings'].append({ + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + }) + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': universal_app_campaign + }] + + campaigns = campaign_service.mutate(operations)['value'] + + # Display results. + if campaigns: + for campaign in campaigns: + print ('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + # Optional: Set the campaign's location and language targeting. No other + # targeting criteria can be used for Universal App campaigns. + SetCampaignTargetingCriteria(client, campaign) + else: + print 'No Universal App campaigns were added.' + + +def CreateBudget(client): + """Creates a budget and returns its budgetId. + + Args: + client: An AdWordsClient instance. + + Returns: + An int budgetId for the created Budget. + """ + budget_service = client.GetService('BudgetService', version='v201708') + + # Create a budget. + budget = { + 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Create the budget and return its ID. + budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] + + return budget_id + + +def SetCampaignTargetingCriteria(client, campaign): + """Sets targeting criteria for the given campaign. + + Args: + client: An AdWordsClient instance. + campaign: A suds object representing the campaign we wish to attach + targeting criteria. + """ + campaign_criterion_service = client.GetService('CampaignCriterionService') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + criteria = [ + { + 'xsi_type': 'Location', + 'id': 21137 # California + }, + { + 'xsi_type': 'Location', + 'id': 2484 # Mexico + }, + { + 'xsi_type': 'Language', + 'id': 1000 # English + }, + { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + ] + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign['id'], + 'criterion': criterion + } + } for criterion in criteria] + + response = campaign_criterion_service.mutate(operations) + + if response and 'value' in response: + # Display the added campaign targets. + for criterion in response['value']: + print ('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], + criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201708/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..9cdaf1d0 --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201708') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201708') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201708') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201708/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..bb7f53ef --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201708') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201708') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201708/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..f1221628 --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201708') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201708/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..35adfb5b --- /dev/null +++ b/examples/adwords/v201708/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201708') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201708') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201708') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201708/basic_operations/__init__.py b/examples/adwords/v201708/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201708/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201708/basic_operations/add_ad_groups.py b/examples/adwords/v201708/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..7511bdc1 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201708') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name "%s" and id "%s" was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/basic_operations/add_campaigns.py b/examples/adwords/v201708/basic_operations/add_campaigns.py new file mode 100755 index 00000000..164225cf --- /dev/null +++ b/examples/adwords/v201708/basic_operations/add_campaigns.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201708') + budget_service = client.GetService('BudgetService', version='v201708') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'adServingOptimizationStatus': 'ROTATE', + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201708/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..2a329428 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/add_keywords.py b/examples/adwords/v201708/basic_operations/add_keywords.py new file mode 100755 index 00000000..481823f6 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201708') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/get_ad_groups.py b/examples/adwords/v201708/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..027236ed --- /dev/null +++ b/examples/adwords/v201708/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201708') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name "%s", id "%s" and status "%s" was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/basic_operations/get_campaigns.py b/examples/adwords/v201708/basic_operations/get_campaigns.py new file mode 100755 index 00000000..0a562cc1 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/get_campaigns.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201708') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..b40a3fd3 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201708') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201708/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..06e08c6d --- /dev/null +++ b/examples/adwords/v201708/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an expanded text ad, run add_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/get_keywords.py b/examples/adwords/v201708/basic_operations/get_keywords.py new file mode 100755 index 00000000..94ee1727 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201708') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/pause_ad.py b/examples/adwords/v201708/basic_operations/pause_ad.py new file mode 100755 index 00000000..4c58dd12 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id "%s" was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201708/basic_operations/remove_ad.py b/examples/adwords/v201708/basic_operations/remove_ad.py new file mode 100755 index 00000000..cdb787ab --- /dev/null +++ b/examples/adwords/v201708/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id "%s" and type "%s" was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201708/basic_operations/remove_ad_group.py b/examples/adwords/v201708/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..862eea48 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201708') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name "%s" and id "%s" was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/remove_campaign.py b/examples/adwords/v201708/basic_operations/remove_campaign.py new file mode 100755 index 00000000..97ada6f4 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201708') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name "%s" and id "%s" was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/basic_operations/remove_keyword.py b/examples/adwords/v201708/basic_operations/remove_keyword.py new file mode 100755 index 00000000..7ff28025 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201708') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201708/basic_operations/update_ad_group.py b/examples/adwords/v201708/basic_operations/update_ad_group.py new file mode 100755 index 00000000..a69959f3 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/update_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201708') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name "%s" and id "%s" was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/update_campaign.py b/examples/adwords/v201708/basic_operations/update_campaign.py new file mode 100755 index 00000000..1d76f345 --- /dev/null +++ b/examples/adwords/v201708/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201708') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/basic_operations/update_keyword.py b/examples/adwords/v201708/basic_operations/update_keyword.py new file mode 100755 index 00000000..b0110dbe --- /dev/null +++ b/examples/adwords/v201708/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201708') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: "%s", value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201708/campaign_management/__init__.py b/examples/adwords/v201708/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201708/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201708/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201708/campaign_management/add_campaign_groups_and_performance_targets.py new file mode 100755 index 00000000..08224ca5 --- /dev/null +++ b/examples/adwords/v201708/campaign_management/add_campaign_groups_and_performance_targets.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a campaign group and sets a performance target for it. + +To get campaigns, run get_campaigns.py. To download reports, run +download_criteria_report_with_awql.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id1, campaign_id2): + campaign_group_id = _CreateCampaignGroup(client) + _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) + _CreatePerformanceTarget(client, campaign_group_id) + print 'Campaign group and its performance target were setup successfully.' + + +def _CreateCampaignGroup(client): + """Create a campaign group. + + Args: + client: an AdWordsClient instance. + + Returns: + The integer ID of the created campaign group. + """ + # Get the CampaignGroupService. + campaign_group_service = client.GetService('CampaignGroupService', + version='v201708') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the campaign group. + 'operand': { + 'name': 'Mars campaign group #%d' % uuid.uuid4() + } + }] + + campaign_group = campaign_group_service.mutate(operations)['value'][0] + campaign_group_id = campaign_group['id'] + + # Display the results. + print 'Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name']) + + return campaign_group_id + + +def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): + """Adds multiple campaigns to a campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + campaign_ids: a list of integer IDs for campaigns. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201708') + + # Create the operations. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'campaignGroupId': campaign_group_id + } + } for campaign_id in campaign_ids] + + campaign_service.mutate(operations) + + # Display the results. + print ('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + + +def _CreatePerformanceTarget(client, campaign_group_id): + """Creates a performance target for the campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + """ + # Get the CampaignGroupPerformanceTargetService. + cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', + version='v201708') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the performance target. + 'operand': { + 'campaignGroupId': campaign_group_id, + 'performanceTarget': { + # Keep the CPC for the campaigns < $3. + 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', + 'efficiencyTargetValue': 3000000, + # Keep the maximum spend under $50. + 'spendTargetType': 'MAXIMUM', + 'spendTarget': { + 'microAmount': 500000000 + }, + # Aim for at least 3000 clicks. + 'volumeGoalType': 'MAXIMIZE_CLICKS', + 'volumeTargetValue': 3000, + # Start the performance target today, and run it for the next 90 + # days. + 'startDate': datetime.datetime.now().strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(90)).strftime('%Y%m%d') + } + } + }] + + cgpt = cgpt_service.mutate(operations)['value'][0] + + # Display the results. + print ('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201708/campaign_management/add_campaign_labels.py b/examples/adwords/v201708/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..5d1424af --- /dev/null +++ b/examples/adwords/v201708/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201708') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201708/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201708/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..b4c0fc2d --- /dev/null +++ b/examples/adwords/v201708/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201708') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201708') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding an ExpandedTextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new ExpandedTextAd for + each of the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once + # you've added targeting and the ads are ready to serve. + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201708') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201708/campaign_management/add_draft.py b/examples/adwords/v201708/campaign_management/add_draft.py new file mode 100755 index 00000000..2b41bcf7 --- /dev/null +++ b/examples/adwords/v201708/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + draft_service = client.GetService('DraftService', version='v201708') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201708') + + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..627cf52b --- /dev/null +++ b/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201708') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201708') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201708') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201708') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201708/campaign_management/add_trial.py b/examples/adwords/v201708/campaign_management/add_trial.py new file mode 100755 index 00000000..caef4dc3 --- /dev/null +++ b/examples/adwords/v201708/campaign_management/add_trial.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201708') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201708') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201708/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201708/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..89f5d5de --- /dev/null +++ b/examples/adwords/v201708/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'PolicySummary'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CombinedApprovalStatus', + 'operator': 'EQUALS', + 'values': 'DISAPPROVED' + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + disapproved_count = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.get(selector) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % (ad['ad']['id'])) + + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201708/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..8f2f59fc --- /dev/null +++ b/examples/adwords/v201708/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', + version='v201708') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, PolicySummary ' + 'WHERE AdGroupId = %s AND CombinedApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % ad_group_id) + more_pages = True + disapproved_count = 0 + offset = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.query(query + ' LIMIT %s, %s' % ( + offset, PAGE_SIZE)) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % (ad['ad']['id'])) + + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..9c7199e5 --- /dev/null +++ b/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201708') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id "%s", name "%s", and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201708/campaign_management/graduate_trial.py b/examples/adwords/v201708/campaign_management/graduate_trial.py new file mode 100755 index 00000000..13238d5e --- /dev/null +++ b/examples/adwords/v201708/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201708') + budget_service = client.GetService('BudgetService', version='v201708') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201708/campaign_management/set_ad_parameters.py b/examples/adwords/v201708/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..8817b1d2 --- /dev/null +++ b/examples/adwords/v201708/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + ad_param_service = client.GetService('AdParamService', version='v201708') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201708/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201708/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..a669602a --- /dev/null +++ b/examples/adwords/v201708/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201708') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201708/campaign_management/validate_text_ad.py b/examples/adwords/v201708/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..ab35e92e --- /dev/null +++ b/examples/adwords/v201708/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +No objects will be created, but exceptions will still be returned. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Construct operations to add an expanded text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'] + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for all astronauts in orbit', + 'finalUrls': ['http://www.example.com'], + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with "%s".' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/error_handling/__init__.py b/examples/adwords/v201708/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201708/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201708/error_handling/handle_partial_failures.py b/examples/adwords/v201708/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..ded63de8 --- /dev/null +++ b/examples/adwords/v201708/error_handling/handle_partial_failures.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201708') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + if (first_field_path_element and + first_field_path_element['field'] == 'operations' and + first_field_path_element['index']): + operation_index = first_field_path_element['index'] + + adgroup_criterion = operations[operation_index]['operand'] + + print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' + 'a failure for the following reason: %s.' + % (adgroup_criterion['adGroupId'], + adgroup_criterion['criterion']['text'], + error['errorString'])) + else: + print ('A failure has occurred for the following reasons: %s\n' + % error['errorString']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/error_handling/handle_policy_violation_error.py b/examples/adwords/v201708/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..8d845823 --- /dev/null +++ b/examples/adwords/v201708/error_handling/handle_policy_violation_error.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201708') + + # Create expanded text ad that violates an exemptable policy. + exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise!!!', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + # Create text ad that violates a non-exemptable policy. + non_exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise with too long of a headline.', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + operations = [exemptable_expanded_text_ad_operation, + non_exemptable_expanded_text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + # Get the index of the failed operation from the error's field path + # elements. + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + # If the operation index is not present on the first error field path + # element, then there's no way to determine which operation to remove, + # so simply throw the exception. + if (not (first_field_path_element + and first_field_path_element['field'] == 'operations' + and first_field_path_element['index'])): + raise e + + operation_index = first_field_path_element['index'] + index = int(operation_index[0]) + operation = operations[index] + if not HandleAPIError(error, operation): + # Set non-exemptable operation to None to mark for deletion. + print ('Removing operation with non-exemptable error at index %s.' + % operation_index) + operations[index] = None + + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is "%s".' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +def HandleAPIError(error, operation): + """Makes an exemption for exemptable PolicyViolationErrors. + + Args: + error: the error associated with the given operation. + operation: the operation associated with the given error. + + Returns: + A boolean that is True if the given error was an exemptable + PolicyViolationError; otherwise, returns False. + """ + is_exemptable = False + + # Determine if the operation can be resubmitted with an exemption request. + if error['ApiError.Type'] == 'PolicyViolationError': + expanded_text_ad = operation['operand']['ad'] + is_exemptable = (error['isExemptable'] if 'isExemptable' in error else + False) + print ('Ad with headline "%s - %s" violated %s policy "%s".' % + (expanded_text_ad['headlinePart1'], + expanded_text_ad['headlinePart2'], + 'exemptable' if is_exemptable else 'non-exemptable', + error['externalPolicyName'])) + + if is_exemptable: + # Add exemption request to the operation. + print ('Adding exemption request for policy name "%s" on text "%s".' + % (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({'key': error['key']}) + + return is_exemptable + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/extensions/__init__.py b/examples/adwords/v201708/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201708/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201708/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201708/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..4fb7c6d4 --- /dev/null +++ b/examples/adwords/v201708/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201708').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201708') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201708/extensions/add_prices.py b/examples/adwords/v201708/extensions/add_prices.py new file mode 100755 index 00000000..6a1a71cf --- /dev/null +++ b/examples/adwords/v201708/extensions/add_prices.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201708') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', + final_mobile_url='http://m.example.com/scrubs'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url='http://m.example.com/haircuts'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url=( + 'http://m.example.com/skincarepackage')) + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit, final_mobile_url=None): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + final_mobile_url: A str containing the final mobile URL after all cross + domain redirects. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + table_row = { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + if final_mobile_url: + table_row['finalMobileUrls'] = { + 'urls': [final_mobile_url] + } + + return table_row + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/extensions/add_site_links.py b/examples/adwords/v201708/extensions/add_site_links.py new file mode 100755 index 00000000..0fa4f94e --- /dev/null +++ b/examples/adwords/v201708/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201708') + customer_service = client.GetService('CustomerService', version='v201708') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/extensions/add_site_links_using_feeds.py b/examples/adwords/v201708/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..e144bfda --- /dev/null +++ b/examples/adwords/v201708/extensions/add_site_links_using_feeds.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201708') + feed_item_service = client.GetService('FeedItemService', version='v201708') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201708') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201708') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name "%s" and ID "%s" was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line2': 'Home line 2', 'line3': 'Home line 3'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line2': 'Support line 2', 'line3': 'Support line 3'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line2': 'Products line 2', 'line3': 'Products line 3'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + feed_item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/migration/__init__.py b/examples/adwords/v201708/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201708/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201708/migration/migrate_to_extension_settings.py b/examples/adwords/v201708/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..4ea8d97c --- /dev/null +++ b/examples/adwords/v201708/migration/migrate_to_extension_settings.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201708') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201708') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201708') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201708') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201708') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201708') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201708') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/misc/__init__.py b/examples/adwords/v201708/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201708/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201708/misc/get_all_images_and_videos.py b/examples/adwords/v201708/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..6c0a60a9 --- /dev/null +++ b/examples/adwords/v201708/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201708') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/misc/upload_image.py b/examples/adwords/v201708/misc/upload_image.py new file mode 100755 index 00000000..3fbb2ea4 --- /dev/null +++ b/examples/adwords/v201708/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201708') + + with open(image_filename, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201708/misc/upload_media_bundle.py b/examples/adwords/v201708/misc/upload_media_bundle.py new file mode 100755 index 00000000..d6c498ee --- /dev/null +++ b/examples/adwords/v201708/misc/upload_media_bundle.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201708') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + return base64.b64encode(response.read()) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/optimization/__init__.py b/examples/adwords/v201708/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201708/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201708/optimization/estimate_keyword_traffic.py b/examples/adwords/v201708/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..df1df334 --- /dev/null +++ b/examples/adwords/v201708/optimization/estimate_keyword_traffic.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201708') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201708/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..666df862 --- /dev/null +++ b/examples/adwords/v201708/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201708') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201708/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..96f989da --- /dev/null +++ b/examples/adwords/v201708/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201708') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ] + } + bid_landscapes = data_service.getCriterionBidLandscape(selector) + + # Display results. + if 'entries' in bid_landscapes: + for bid_landscape in bid_landscapes['entries']: + if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': + print ('Criterion bid landscape with ad group id "%s", criterion id ' + '"%s", start date "%s", end date "%s", with landscape ' + 'points was found:' + % (bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + else: + print 'No bid landscapes found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201708/optimization/get_keyword_ideas.py b/examples/adwords/v201708/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..2afa7bb8 --- /dev/null +++ b/examples/adwords/v201708/optimization/get_keyword_ideas.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201708') + + # Construct selector object and retrieve related keywords. + offset = 0 + selector = { + 'searchParameters': [ + { + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }, + { + # Language setting (optional). + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }, + { + # Network search parameter (optional) + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + } + ], + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS', + 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', + 'CATEGORY_PRODUCTS_AND_SERVICES'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr(attribute['value'], 'value', + '0') + print ('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/__init__.py b/examples/adwords/v201708/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201708/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201708/remarketing/add_audience.py b/examples/adwords/v201708/remarketing/add_audience.py new file mode 100755 index 00000000..7d4c4236 --- /dev/null +++ b/examples/adwords/v201708/remarketing/add_audience.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201708') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201708') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name "%s" and ID "%s" was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/add_conversion_tracker.py b/examples/adwords/v201708/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..d9fedbac --- /dev/null +++ b/examples/adwords/v201708/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201708') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/add_conversion_trackers.py b/examples/adwords/v201708/remarketing/add_conversion_trackers.py new file mode 100755 index 00000000..dfce443b --- /dev/null +++ b/examples/adwords/v201708/remarketing/add_conversion_trackers.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds AdWords conversion trackers. + +Adds an AdWords conversion tracker and an upload conversion tracker. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201708') + + # Create an AdWords conversion tracker. + adwords_conversion_tracker = { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'name': 'Upload Conversion #%s' % uuid.uuid4(), + # Optional fields. + # Set an appropriate category. This will be set to DEFAULT if not + # specified. + 'category': 'LEAD', + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90', + # Set the default currency code to use for conversions that do + # not specify a conversion currency. This must be an ISO 4217 3-character + # code such as "EUR" or "USD". + # If this field is not set, AdWords will use the account's currency. + 'defaultRevenueCurrencyCode': 'EUR', + # Set the default revenue value to use for conversions that do not specify + # a converison value. Note that this value should NOT be in micros. + 'defaultRevenueValue': '2.50', + # To upload fractional conversion credits, mark the upload conversion as + # externally attributed. To learn more about importing externally + # attributed conversions, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'isExternallyAttributed': 'true' + } + + # Construct operations. + operations = [{ + 'operator': 'ADD', + 'operand': conversion_tracker + } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] + + # Add the conversions. + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + if (conversion_tracker['ConversionTracker.Type'] + is 'AdWordsConversionTracker'): + print ('Conversion tracker with ID "%d", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + else: + print ('Conversion with ID "%d", name "%s", status "%s", and category ' + '"%s" was added.' + % (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/add_crm_based_user_list.py b/examples/adwords/v201708/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..75501240 --- /dev/null +++ b/examples/adwords/v201708/remarketing/add_crm_based_user_list.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201708') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180 + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + + emails = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] + + # Optional: AddressInfo is only accessible to whitelisted customers. + # If you are not on the whitelist, you should leave this code commented out. + # members.append({ + # 'addressInfo': { + # 'hashedFirstName': NormalizeAndSHA256('John'), + # 'hashedLastName': NormalizeAndSHA256('Doe'), + # 'countryCode': 'US', + # 'zipCode': '10001' + # } + # }) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'membersList': members + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def NormalizeAndSHA256(s): + """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. + + Args: + s: The string to perform this operation on. + + Returns: + A normalized and SHA-256 hashed string. + """ + return hashlib.sha256(s.strip().lower()).hexdigest() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201708/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..c85dbd85 --- /dev/null +++ b/examples/adwords/v201708/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201708') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords knows how to apply the + # rules. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ], + # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF + # means 'at least one item in each rule item group must match', and DNF + # means 'at least one entire rule item group must match'. + # DateSpecificRuleUserList only supports DNF. You can also omit the rule + # type altogether to default to DNF. + 'ruleType': 'DNF' + } + + # Third and fourth rule item groups. + # Visitors of a page who visited another page. + site1_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example1' + } + } + site2_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example2' + } + } + + # Create two rules to show that a visitor browsed two sites. + user_visited_site1_rule = { + 'groups': [{ + 'items': [site1_rule_item] + }] + } + + user_visited_site2_rule = { + 'groups': [{ + 'items': [site2_rule_item] + }] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule, + # Optional: Set the populationStatus to REQUESTED to include past users in + # the user list. + 'prepopulationStatus': 'REQUESTED' + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create the user list for "Visitors of a page who did visit another page". + # To create a user list for "Visitors of a page who did not visit another + # page", change the ruleOperator from AND to AND_NOT. + combined_user_list = { + 'xsi_type': 'CombinedRuleUserList', + 'name': 'Combined rule user lst create at ${creation_time}', + 'description': 'Users who visited two sites.', + 'leftOperand': user_visited_site1_rule, + 'rightOperand': user_visited_site2_rule, + 'ruleOperator': 'AND' + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list, + combined_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201708/remarketing/upload_offline_call_conversions.py new file mode 100755 index 00000000..eacb7fb1 --- /dev/null +++ b/examples/adwords/v201708/remarketing/upload_offline_call_conversions.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for calls related to ads in your account. + +To set up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CALLER_ID = 'INSERT_CALLER_ID_HERE' +# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats +# For time zones, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +CALL_START_TIME = 'INSERT_CALL_START_TIME' +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, caller_id, call_start_time, conversion_name, conversion_time, + conversion_value): + # Initialize appropriate services. + occ_feed_service = client.GetService( + 'OfflineCallConversionFeedService', version='v201708') + + # Associate offline call conversions with the existing named conversion + # tracker. If this tracker was newly created, it may be a few hours before it + # can accept conversions. + feed = { + 'callerId': caller_id, + 'callStartTime': call_start_time, + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + } + + occ_operations = [{'operator': 'ADD', 'operand': feed}] + + occ_response = occ_feed_service.mutate(occ_operations) + values = occ_response['value'] + + if values: + for occ_feed in values: + print ('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + else: + print 'No offline call conversions were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, + CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201708/remarketing/upload_offline_conversions.py b/examples/adwords/v201708/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..f7d7743a --- /dev/null +++ b/examples/adwords/v201708/remarketing/upload_offline_conversions.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201708') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id, + # Optional: To upload fractional conversion credits, set the external + # attribution model and credit. To use this feature, your conversion + # tracker should be marked as externally attributed. To learn more about + # importing externally attributed conversins, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'externalAttributionCredit': 0.3, + # 'externalAttributionModel': 'Linear' + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201708/reporting/__init__.py b/examples/adwords/v201708/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201708/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..e59ef1f4 --- /dev/null +++ b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201708') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_selector.py new file mode 100755 index 00000000..ebdb879a --- /dev/null +++ b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_selector.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201708') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..0eb63ede --- /dev/null +++ b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201708') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_selector.py new file mode 100755 index 00000000..652102c1 --- /dev/null +++ b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_selector.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201708') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..a2ae571c --- /dev/null +++ b/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import sys +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201708') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + # You can provide a file object to write the output to. For this + # demonstration we use sys.stdout to write the report to the screen. + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', sys.stdout, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201708/reporting/download_criteria_report_with_selector.py new file mode 100755 index 00000000..86216732 --- /dev/null +++ b/examples/adwords/v201708/reporting/download_criteria_report_with_selector.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201708') + + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201708/reporting/get_report_fields.py b/examples/adwords/v201708/reporting/get_report_fields.py new file mode 100755 index 00000000..11db3d53 --- /dev/null +++ b/examples/adwords/v201708/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201708') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type "%s" contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201708/reporting/parallel_report_download.py b/examples/adwords/v201708/reporting/parallel_report_download.py new file mode 100755 index 00000000..5672e238 --- /dev/null +++ b/examples/adwords/v201708/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201708') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201708') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201708/shopping/__init__.py b/examples/adwords/v201708/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201708/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201708/shopping/add_product_partition_tree.py b/examples/adwords/v201708/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..8c976668 --- /dev/null +++ b/examples/adwords/v201708/shopping/add_product_partition_tree.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201708') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201708/shopping/add_product_scope.py b/examples/adwords/v201708/shopping/add_product_scope.py new file mode 100755 index 00000000..802ff956 --- /dev/null +++ b/examples/adwords/v201708/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201708') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/shopping/add_shopping_campaign.py b/examples/adwords/v201708/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..a43290a9 --- /dev/null +++ b/examples/adwords/v201708/shopping/add_shopping_campaign.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +# If set to true, a default partition will be created. If running the +# add_product_partition_tree.py example right after this example, make +# sure this stays set to false. +CREATE_DEFAULT_PARTITION = False +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id, create_default_partition): + campaign_service = client.GetService('CampaignService', version='v201708') + ad_group_service = client.GetService('AdGroupService', version='v201708') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + ad_group = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': ad_group + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': ad_group_id, + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201708') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + }, + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 500000 + } + }] + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py new file mode 100755 index 00000000..7b372563 --- /dev/null +++ b/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py @@ -0,0 +1,404 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds a Shopping campaign for Showcase ads. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import uuid + +from googleads import adwords +from suds import WebFault + + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' +EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' +COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + # Note: Showcase ads require either ManualCpc or EnhancedCpc in the + # campaign's BiddingStrategyConfiguration. + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, budget_id, merchant_id, expanded_image_filepath, + collapsed_image_filepath): + try: + # Create the Shopping Campaign + campaign = CreateShoppingCampaign(client, budget_id, merchant_id) + + # Create the AdGroup + adgroup = CreateAdGroup(client, campaign['id']) + + # Create a Showcase Ad + CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath) + + product_partition_tree = CreateProductPartition(client, adgroup['id']) + print 'Final tree:\n%s' % product_partition_tree + except WebFault: + print 'Failed to create shopping campaign for showcase ads.' + raise + + +def CreateShoppingCampaign(client, budget_id, merchant_id): + """Creates a shopping campaign with the given budget and merchant IDs. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + shopping campaign. + + Returns: + The created Shopping Campaign as a sudsobject. + """ + campaign_service = client.GetService('CampaignService', 'v201708') + + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + campaign = campaign_service.mutate(campaign_operations)['value'][0] + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + return campaign + + +def CreateAdGroup(client, campaign_id): + """Creates an AdGroup for the given shopping campaign ID. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a shopping campaign. + + Returns: + The created AdGroup as a sudsobject. + """ + ad_group_service = client.GetService('AdGroupService', 'v201708') + + adgroup = { + # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS + 'adGroupType': 'SHOPPING_SHOWCASE_ADS', + 'campaignId': campaign_id, + 'name': 'AdGroup #%s' % uuid.uuid4(), + # REQUIRED: Set the ad group's bidding strategy configuration. + 'biddingStrategyConfiguration': { + # Showcase ads require either ManualCpc or EnhancedCpc. + 'biddingStrategyType': 'MANUAL_CPC', + # Optional: Set the bids + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 100000 + } + }] + } + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) + + return adgroup + + +def CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath): + """Creates a showcase add for the given AdGroup with the given images. + + Args: + client: an AdWordsClient instance. + adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + expanded_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's expandedImage. + collapsed_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's collapsedImage. + + Returns: + The created Showcase Ad as a sudsobject. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201708') + + showcase_ad = { + 'adGroupId': adgroup['id'], + 'ad': { + 'xsi_type': 'ShowcaseAd', + 'Ad.Type': 'ShowcaseAd', + # Required: set the ad's name, final URLs, and display URL. + 'name': 'Showcase ad #%s' % uuid.uuid4(), + 'finalUrls': 'http://example.com/showcase', + 'displayUrl': 'example.com', + # Required: Set the ad's expanded image. + 'expandedImage': { + 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] + }, + # Optional: Set the collapsed image. + 'collapsedImage': { + 'mediaId': + UploadImage(client, collapsed_image_filepath)['mediaId'] + } + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': showcase_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] + + print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + + return showcase_ad + + +def UploadImage(client, filepath): + """Uploads a .jpg image with the given filepath via the AdWords MediaService. + + Args: + client: an AdWordsClient instance. + filepath: a str filepath to the .jpg file to be uploaded. + + Returns: + The created Image as a sudsobject. + """ + media_service = client.GetService('MediaService', 'v201708') + + with open(filepath, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + image = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + + image = media_service.upload(image)[0] + + return image + + +def CreateProductPartition(client, adgroup_id): + """Creates a ProductPartition tree for the given AdGroup ID. + + Args: + client: an AdWordsClient instance. + adgroup_id: a str AdGroup ID. + + Returns: + The ProductPartition tree as a sudsobject. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + 'v201708') + helper = ProductPartitionHelper(adgroup_id) + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition) + helper.CreateUnit(root, used_product_canonical_condition) + helper.CreateUnit(root, other_product_canonical_condition) + + result = ad_group_criterion_service.mutate(helper.operations) + return result['value'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, + COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201708/shopping/get_product_category_taxonomy.py b/examples/adwords/v201708/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..b0647465 --- /dev/null +++ b/examples/adwords/v201708/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201708') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/targeting/__init__.py b/examples/adwords/v201708/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201708/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201708/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201708/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..33fbee64 --- /dev/null +++ b/examples/adwords/v201708/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201708') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201708/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201708/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..2998b4a0 --- /dev/null +++ b/examples/adwords/v201708/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201708') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type "%s" was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201708/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..7a56aa9d --- /dev/null +++ b/examples/adwords/v201708/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201708') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201708/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..4a7376d5 --- /dev/null +++ b/examples/adwords/v201708/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201708') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name "%s" and ID "%s" was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name "%s", ID "%s", and country code "%s" was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201708/targeting/lookup_location.py b/examples/adwords/v201708/targeting/lookup_location.py new file mode 100755 index 00000000..aa5c8886 --- /dev/null +++ b/examples/adwords/v201708/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201708') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py index ab7f822a..f5cec62a 100755 --- a/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py @@ -26,7 +26,7 @@ def main(client): 'ActivityGroupService', version='v201611') # Create a statement to select activity groups. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/activity_service/get_all_activities.py b/examples/dfp/v201611/activity_service/get_all_activities.py index 345093be..1efa1c37 100755 --- a/examples/dfp/v201611/activity_service/get_all_activities.py +++ b/examples/dfp/v201611/activity_service/get_all_activities.py @@ -25,7 +25,7 @@ def main(client): activity_service = client.GetService('ActivityService', version='v201611') # Create a statement to select activities. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each activity. print('Activity with ID "%d" and name "%s" was found.\n' % (activity['id'], activity['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py index 363cf3e3..dd26b060 100755 --- a/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py @@ -26,7 +26,7 @@ def main(client): 'AudienceSegmentService', version='v201611') # Create a statement to select audience segments. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. @@ -39,7 +39,7 @@ def main(client): print('Audience segment with ID "%d", name "%s", and size "%d" was ' 'found.\n' % (audience_segment['id'], audience_segment['name'], audience_segment['size'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/base_rate_service/get_all_base_rates.py b/examples/dfp/v201611/base_rate_service/get_all_base_rates.py index 280a4a44..e0d87151 100755 --- a/examples/dfp/v201611/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201611/base_rate_service/get_all_base_rates.py @@ -25,7 +25,7 @@ def main(client): base_rate_service = client.GetService('BaseRateService', version='v201611') # Create a statement to select base rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. @@ -38,7 +38,7 @@ def main(client): print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), base_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/company_service/get_all_companies.py b/examples/dfp/v201611/company_service/get_all_companies.py index 6cf9e4b2..2b2722cf 100755 --- a/examples/dfp/v201611/company_service/get_all_companies.py +++ b/examples/dfp/v201611/company_service/get_all_companies.py @@ -25,7 +25,7 @@ def main(client): company_service = client.GetService('CompanyService', version='v201611') # Create a statement to select companies. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/contact_service/get_all_contacts.py b/examples/dfp/v201611/contact_service/get_all_contacts.py index 690cf588..a9f5b5cc 100755 --- a/examples/dfp/v201611/contact_service/get_all_contacts.py +++ b/examples/dfp/v201611/contact_service/get_all_contacts.py @@ -25,7 +25,7 @@ def main(client): contact_service = client.GetService('ContactService', version='v201611') # Create a statement to select contacts. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 1d4bb01d..ce3f01fc 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -26,7 +26,7 @@ def main(client): 'ContentMetadataKeyHierarchyService', version='v201611') # Create a statement to select content metadata key hierarchies. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been @@ -42,7 +42,7 @@ def main(client): print('Content metadata key hierarchy with ID "%d" and name "%s" was ' 'found.\n' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/content_service/get_all_content.py b/examples/dfp/v201611/content_service/get_all_content.py index 6e8f8e12..f3f4dc8d 100755 --- a/examples/dfp/v201611/content_service/get_all_content.py +++ b/examples/dfp/v201611/content_service/get_all_content.py @@ -25,7 +25,7 @@ def main(client): content_service = client.GetService('ContentService', version='v201611') # Create a statement to select content. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % (content['id'], content['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/creative_service/get_all_creatives.py b/examples/dfp/v201611/creative_service/get_all_creatives.py index d2689507..33041108 100755 --- a/examples/dfp/v201611/creative_service/get_all_creatives.py +++ b/examples/dfp/v201611/creative_service/get_all_creatives.py @@ -25,7 +25,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201611') # Create a statement to select creatives. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % (creative['id'], creative['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py index c335a39d..916bc1fb 100755 --- a/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py @@ -26,7 +26,7 @@ def main(client): 'CreativeSetService', version='v201611') # Create a statement to select creative sets. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % (creative_set['id'], creative_set['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py index da163f3f..319d4f06 100755 --- a/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py @@ -26,7 +26,7 @@ def main(client): 'CreativeTemplateService', version='v201611') # Create a statement to select creative templates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % (creative_template['id'], creative_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py index 70375e7a..47413e35 100755 --- a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py @@ -26,7 +26,7 @@ def main(client): 'CreativeWrapperService', version='v201611') # Create a statement to select creative wrappers. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py index 52c3644a..ee5cea0a 100755 --- a/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py @@ -26,7 +26,7 @@ def main(client): 'CustomFieldService', version='v201611') # Create a statement to select custom fields. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % (custom_field['id'], custom_field['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 0299462f..10da9eec 100755 --- a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201611') # Create statement to get all targeting keys. - targeting_key_statement = dfp.FilterStatement() + targeting_key_statement = dfp.StatementBuilder() all_keys = [] @@ -36,7 +36,7 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break diff --git a/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py index 87cf9558..4441723e 100755 --- a/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py @@ -26,7 +26,7 @@ def main(client): 'ExchangeRateService', version='v201611') # Create a statement to select exchange rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. @@ -41,7 +41,7 @@ def main(client): 'and exchange rate "%d" was found.\n' % (exchange_rate['id'], exchange_rate['currencyCode'], exchange_rate['direction'], exchange_rate['exchangeRate'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_units.py b/examples/dfp/v201611/inventory_service/get_all_ad_units.py index 115fce79..1b03c653 100755 --- a/examples/dfp/v201611/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201611/inventory_service/get_all_ad_units.py @@ -25,7 +25,7 @@ def main(client): ad_unit_service = client.GetService('InventoryService', version='v201611') # Create a statement to select ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/label_service/get_all_labels.py b/examples/dfp/v201611/label_service/get_all_labels.py index f1e248ab..31e84da7 100755 --- a/examples/dfp/v201611/label_service/get_all_labels.py +++ b/examples/dfp/v201611/label_service/get_all_labels.py @@ -25,7 +25,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201611') # Create a statement to select labels. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], label['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py index c430247e..a2c24e44 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py @@ -26,7 +26,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201611') # Create a statement to select line item creative associations. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. @@ -44,7 +44,7 @@ def main(client): print('Line item creative association with line item ID "%d" and ' 'creative ID "%d" was found.\n' % (lica['lineItemId'], lica['creativeId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py index 96babbdb..ab035121 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201611/line_item_creative_association_service/update_licas.py @@ -31,7 +31,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201611') # Create statement object to get all LICAs. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() while True: # Get LICAs by statement. @@ -53,7 +53,7 @@ def main(client): print ('LICA with line item id "%s", creative id "%s", and status ' '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/line_item_service/get_all_line_items.py b/examples/dfp/v201611/line_item_service/get_all_line_items.py index 5ecc7951..7a606837 100755 --- a/examples/dfp/v201611/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201611/line_item_service/get_all_line_items.py @@ -25,7 +25,7 @@ def main(client): line_item_service = client.GetService('LineItemService', version='v201611') # Create a statement to select line items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/order_service/get_all_orders.py b/examples/dfp/v201611/order_service/get_all_orders.py index 433a8ea5..9dc88d9b 100755 --- a/examples/dfp/v201611/order_service/get_all_orders.py +++ b/examples/dfp/v201611/order_service/get_all_orders.py @@ -25,7 +25,7 @@ def main(client): order_service = client.GetService('OrderService', version='v201611') # Create a statement to select orders. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], order['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/package_service/get_all_packages.py b/examples/dfp/v201611/package_service/get_all_packages.py index ff146100..288867af 100755 --- a/examples/dfp/v201611/package_service/get_all_packages.py +++ b/examples/dfp/v201611/package_service/get_all_packages.py @@ -25,7 +25,7 @@ def main(client): pkg_service = client.GetService('PackageService', version='v201611') # Create a statement to select packages. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. @@ -37,7 +37,7 @@ def main(client): print( 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/placement_service/create_placements.py b/examples/dfp/v201611/placement_service/create_placements.py index 33627770..0ab85871 100755 --- a/examples/dfp/v201611/placement_service/create_placements.py +++ b/examples/dfp/v201611/placement_service/create_placements.py @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() while True: response = inventory_service.getAdUnitsByStatement( @@ -76,7 +76,7 @@ def main(client): elif size['width'] == '468' and size['height'] == '60': banner_ad_unit_placement['targetedAdUnitIds'].append( ad_unit['id']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/placement_service/get_all_placements.py b/examples/dfp/v201611/placement_service/get_all_placements.py index 8b567738..1a27a5a1 100755 --- a/examples/dfp/v201611/placement_service/get_all_placements.py +++ b/examples/dfp/v201611/placement_service/get_all_placements.py @@ -25,7 +25,7 @@ def main(client): placement_service = client.GetService('PlacementService', version='v201611') # Create a statement to select placements. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % (placement['id'], placement['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py index b75ad98e..3c5819ff 100755 --- a/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py @@ -26,7 +26,7 @@ def main(client): 'PremiumRateService', version='v201611') # Create a statement to select premium rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. @@ -40,7 +40,7 @@ def main(client): 'id "%d" was found.\n' % (premium_rate['id'], dfp.DfpClassType(premium_rate), premium_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py index 661309d2..1aae8913 100755 --- a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageItemService', version='v201611') # Create a statement to select product package items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. @@ -40,7 +40,7 @@ def main(client): 'package id "%d" was found.\n' % (product_package_item['id'], product_package_item['productId'], product_package_item['productPackageId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/product_package_service/get_all_product_packages.py b/examples/dfp/v201611/product_package_service/get_all_product_packages.py index 3f101e1c..9b8f94b6 100755 --- a/examples/dfp/v201611/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201611/product_package_service/get_all_product_packages.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageService', version='v201611') # Create a statement to select product packages. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % (product_package['id'], product_package['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/product_service/get_all_products.py b/examples/dfp/v201611/product_service/get_all_products.py index 9affd0eb..c2f7f122 100755 --- a/examples/dfp/v201611/product_service/get_all_products.py +++ b/examples/dfp/v201611/product_service/get_all_products.py @@ -25,7 +25,7 @@ def main(client): product_service = client.GetService('ProductService', version='v201611') # Create a statement to select products. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % (product['id'], product['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/product_template_service/get_all_product_templates.py b/examples/dfp/v201611/product_template_service/get_all_product_templates.py index 5cef24bb..39359fd4 100755 --- a/examples/dfp/v201611/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201611/product_template_service/get_all_product_templates.py @@ -26,7 +26,7 @@ def main(client): 'ProductTemplateService', version='v201611') # Create a statement to select product templates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % (product_template['id'], product_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py index 6edebf35..bbe0c654 100755 --- a/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py @@ -26,7 +26,7 @@ def main(client): 'ProposalLineItemService', version='v201611') # Create a statement to select proposal line items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % (proposal_line_item['id'], proposal_line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/proposal_service/get_all_proposals.py b/examples/dfp/v201611/proposal_service/get_all_proposals.py index 0d95fb42..82798691 100755 --- a/examples/dfp/v201611/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201611/proposal_service/get_all_proposals.py @@ -25,7 +25,7 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201611') # Create a statement to select proposals. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % (proposal['id'], proposal['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py index 44e7743b..6d6494ce 100755 --- a/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py @@ -25,7 +25,7 @@ def main(client): rate_card_service = client.GetService('RateCardService', version='v201611') # Create a statement to select rate cards. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. @@ -38,7 +38,7 @@ def main(client): print('Rate card with ID "%d", name "%s", and currency code "%s" was ' 'found.\n' % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py index 2a6ef8ac..5cafef53 100755 --- a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py @@ -26,7 +26,7 @@ def main(client): 'ReconciliationReportService', version='v201611') # Create a statement to select reconciliation reports. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. @@ -43,7 +43,7 @@ def main(client): ' found.\n' % (reconciliation_report['id'], reconciliation_report['startDate']['month'], reconciliation_report['startDate']['year'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py index 0ee867c9..ed673cf1 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -26,7 +26,7 @@ def main(client): 'SuggestedAdUnitService', version='v201611') # Create a statement to select suggested ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -39,7 +39,7 @@ def main(client): print( 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/team_service/get_all_teams.py b/examples/dfp/v201611/team_service/get_all_teams.py index 4ed692d0..67d53835 100755 --- a/examples/dfp/v201611/team_service/get_all_teams.py +++ b/examples/dfp/v201611/team_service/get_all_teams.py @@ -25,7 +25,7 @@ def main(client): team_service = client.GetService('TeamService', version='v201611') # Create a statement to select teams. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each team. print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], team['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/user_service/get_all_users.py b/examples/dfp/v201611/user_service/get_all_users.py index fb7db4fb..2a8f6ee2 100755 --- a/examples/dfp/v201611/user_service/get_all_users.py +++ b/examples/dfp/v201611/user_service/get_all_users.py @@ -25,7 +25,7 @@ def main(client): user_service = client.GetService('UserService', version='v201611') # Create a statement to select users. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], user['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py index 7436e16b..58775565 100755 --- a/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py @@ -26,7 +26,7 @@ def main(client): 'UserTeamAssociationService', version='v201611') # Create a statement to select user team associations. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -39,7 +39,7 @@ def main(client): print('User team association with team id "%d" and user id "%d" was ' 'found.\n' % (user_team_association['teamId'], user_team_association['userId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py index 67036748..d49855a1 100755 --- a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py @@ -26,7 +26,7 @@ def main(client): 'ActivityGroupService', version='v201702') # Create a statement to select activity groups. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/activity_service/get_all_activities.py b/examples/dfp/v201702/activity_service/get_all_activities.py index bc4e2f5f..32b6c58e 100755 --- a/examples/dfp/v201702/activity_service/get_all_activities.py +++ b/examples/dfp/v201702/activity_service/get_all_activities.py @@ -25,7 +25,7 @@ def main(client): activity_service = client.GetService('ActivityService', version='v201702') # Create a statement to select activities. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each activity. print('Activity with ID "%d" and name "%s" was found.\n' % (activity['id'], activity['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py index 5c3a084d..ab4ab4ca 100755 --- a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py @@ -26,7 +26,7 @@ def main(client): 'AudienceSegmentService', version='v201702') # Create a statement to select audience segments. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. @@ -39,7 +39,7 @@ def main(client): print('Audience segment with ID "%d", name "%s", and size "%d" was ' 'found.\n' % (audience_segment['id'], audience_segment['name'], audience_segment['size'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py b/examples/dfp/v201702/base_rate_service/get_all_base_rates.py index c37b8465..44b6c365 100755 --- a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201702/base_rate_service/get_all_base_rates.py @@ -25,7 +25,7 @@ def main(client): base_rate_service = client.GetService('BaseRateService', version='v201702') # Create a statement to select base rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. @@ -38,7 +38,7 @@ def main(client): print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), base_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/company_service/get_all_companies.py b/examples/dfp/v201702/company_service/get_all_companies.py index 1a91f814..6693f930 100755 --- a/examples/dfp/v201702/company_service/get_all_companies.py +++ b/examples/dfp/v201702/company_service/get_all_companies.py @@ -25,7 +25,7 @@ def main(client): company_service = client.GetService('CompanyService', version='v201702') # Create a statement to select companies. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/contact_service/get_all_contacts.py b/examples/dfp/v201702/contact_service/get_all_contacts.py index 1b56cbb5..7fbd79d8 100755 --- a/examples/dfp/v201702/contact_service/get_all_contacts.py +++ b/examples/dfp/v201702/contact_service/get_all_contacts.py @@ -25,7 +25,7 @@ def main(client): contact_service = client.GetService('ContactService', version='v201702') # Create a statement to select contacts. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 47ea5d16..fe1d9afb 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -26,7 +26,7 @@ def main(client): 'ContentMetadataKeyHierarchyService', version='v201702') # Create a statement to select content metadata key hierarchies. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been @@ -42,7 +42,7 @@ def main(client): print('Content metadata key hierarchy with ID "%d" and name "%s" was ' 'found.\n' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/content_service/get_all_content.py b/examples/dfp/v201702/content_service/get_all_content.py index d1982060..5649d6ae 100755 --- a/examples/dfp/v201702/content_service/get_all_content.py +++ b/examples/dfp/v201702/content_service/get_all_content.py @@ -25,7 +25,7 @@ def main(client): content_service = client.GetService('ContentService', version='v201702') # Create a statement to select content. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % (content['id'], content['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/creative_service/get_all_creatives.py b/examples/dfp/v201702/creative_service/get_all_creatives.py index ccc2d0ee..e96715de 100755 --- a/examples/dfp/v201702/creative_service/get_all_creatives.py +++ b/examples/dfp/v201702/creative_service/get_all_creatives.py @@ -25,7 +25,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201702') # Create a statement to select creatives. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % (creative['id'], creative['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py index 742cde34..6e8bd9fa 100755 --- a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py @@ -26,7 +26,7 @@ def main(client): 'CreativeSetService', version='v201702') # Create a statement to select creative sets. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % (creative_set['id'], creative_set['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py index bc75624f..39ced2d2 100755 --- a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py @@ -26,7 +26,7 @@ def main(client): 'CreativeTemplateService', version='v201702') # Create a statement to select creative templates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % (creative_template['id'], creative_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py index bb42768b..26fb962d 100755 --- a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py @@ -26,7 +26,7 @@ def main(client): 'CreativeWrapperService', version='v201702') # Create a statement to select creative wrappers. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py index 6b982c43..a823a7a6 100755 --- a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py @@ -26,7 +26,7 @@ def main(client): 'CustomFieldService', version='v201702') # Create a statement to select custom fields. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % (custom_field['id'], custom_field['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 79e404ea..fbafecd9 100755 --- a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201702') # Create statement to get all targeting keys. - targeting_key_statement = dfp.FilterStatement() + targeting_key_statement = dfp.StatementBuilder() all_keys = [] @@ -36,7 +36,7 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break diff --git a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py index 8a17ff5e..7c4d95b6 100755 --- a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py @@ -26,7 +26,7 @@ def main(client): 'ExchangeRateService', version='v201702') # Create a statement to select exchange rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. @@ -41,7 +41,7 @@ def main(client): 'and exchange rate "%d" was found.\n' % (exchange_rate['id'], exchange_rate['currencyCode'], exchange_rate['direction'], exchange_rate['exchangeRate'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_units.py b/examples/dfp/v201702/inventory_service/get_all_ad_units.py index 83f9037b..90a2da31 100755 --- a/examples/dfp/v201702/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201702/inventory_service/get_all_ad_units.py @@ -25,7 +25,7 @@ def main(client): ad_unit_service = client.GetService('InventoryService', version='v201702') # Create a statement to select ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/label_service/get_all_labels.py b/examples/dfp/v201702/label_service/get_all_labels.py index 9d5bcd1d..d4ae0fc6 100755 --- a/examples/dfp/v201702/label_service/get_all_labels.py +++ b/examples/dfp/v201702/label_service/get_all_labels.py @@ -25,7 +25,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201702') # Create a statement to select labels. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], label['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py index ecb592cc..71e757ad 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py @@ -26,7 +26,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201702') # Create a statement to select line item creative associations. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. @@ -44,7 +44,7 @@ def main(client): print('Line item creative association with line item ID "%d" and ' 'creative ID "%d" was found.\n' % (lica['lineItemId'], lica['creativeId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py index d78b2de9..783a1e87 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201702/line_item_creative_association_service/update_licas.py @@ -31,7 +31,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201702') # Create statement object to get all LICAs. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() while True: # Get LICAs by statement. @@ -53,7 +53,7 @@ def main(client): print ('LICA with line item id "%s", creative id "%s", and status ' '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/line_item_service/get_all_line_items.py b/examples/dfp/v201702/line_item_service/get_all_line_items.py index 95d1c439..07cee823 100755 --- a/examples/dfp/v201702/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201702/line_item_service/get_all_line_items.py @@ -25,7 +25,7 @@ def main(client): line_item_service = client.GetService('LineItemService', version='v201702') # Create a statement to select line items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/native_style_service/get_all_native_styles.py b/examples/dfp/v201702/native_style_service/get_all_native_styles.py index dbdfdfef..0f48cfa8 100755 --- a/examples/dfp/v201702/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201702/native_style_service/get_all_native_styles.py @@ -26,7 +26,7 @@ def main(client): version='v201702') # Create a statement to select native styles. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each native style. print('Native style with ID "%d" and name "%s" was found.\n' % (native_style['id'], native_style['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/order_service/get_all_orders.py b/examples/dfp/v201702/order_service/get_all_orders.py index 7da87b2e..2c34d9f2 100755 --- a/examples/dfp/v201702/order_service/get_all_orders.py +++ b/examples/dfp/v201702/order_service/get_all_orders.py @@ -25,7 +25,7 @@ def main(client): order_service = client.GetService('OrderService', version='v201702') # Create a statement to select orders. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], order['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/package_service/get_all_packages.py b/examples/dfp/v201702/package_service/get_all_packages.py index f21ee014..1db46c9b 100755 --- a/examples/dfp/v201702/package_service/get_all_packages.py +++ b/examples/dfp/v201702/package_service/get_all_packages.py @@ -25,7 +25,7 @@ def main(client): pkg_service = client.GetService('PackageService', version='v201702') # Create a statement to select packages. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. @@ -37,7 +37,7 @@ def main(client): print( 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/placement_service/create_placements.py b/examples/dfp/v201702/placement_service/create_placements.py index e2de6ff3..485ffe1c 100755 --- a/examples/dfp/v201702/placement_service/create_placements.py +++ b/examples/dfp/v201702/placement_service/create_placements.py @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() while True: response = inventory_service.getAdUnitsByStatement( @@ -76,7 +76,7 @@ def main(client): elif size['width'] == '468' and size['height'] == '60': banner_ad_unit_placement['targetedAdUnitIds'].append( ad_unit['id']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/placement_service/get_all_placements.py b/examples/dfp/v201702/placement_service/get_all_placements.py index ed3e9c41..b40c18b9 100755 --- a/examples/dfp/v201702/placement_service/get_all_placements.py +++ b/examples/dfp/v201702/placement_service/get_all_placements.py @@ -25,7 +25,7 @@ def main(client): placement_service = client.GetService('PlacementService', version='v201702') # Create a statement to select placements. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % (placement['id'], placement['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py index f94d682c..4294dfb3 100755 --- a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py @@ -26,7 +26,7 @@ def main(client): 'PremiumRateService', version='v201702') # Create a statement to select premium rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. @@ -40,7 +40,7 @@ def main(client): 'id "%d" was found.\n' % (premium_rate['id'], dfp.DfpClassType(premium_rate), premium_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py index a497fd47..a379b9fc 100755 --- a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageItemService', version='v201702') # Create a statement to select product package items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. @@ -40,7 +40,7 @@ def main(client): 'package id "%d" was found.\n' % (product_package_item['id'], product_package_item['productId'], product_package_item['productPackageId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/product_package_service/get_all_product_packages.py b/examples/dfp/v201702/product_package_service/get_all_product_packages.py index 19e33a1d..910cc35a 100755 --- a/examples/dfp/v201702/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201702/product_package_service/get_all_product_packages.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageService', version='v201702') # Create a statement to select product packages. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % (product_package['id'], product_package['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/product_service/get_all_products.py b/examples/dfp/v201702/product_service/get_all_products.py index 11fd193f..8dd669b5 100755 --- a/examples/dfp/v201702/product_service/get_all_products.py +++ b/examples/dfp/v201702/product_service/get_all_products.py @@ -25,7 +25,7 @@ def main(client): product_service = client.GetService('ProductService', version='v201702') # Create a statement to select products. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % (product['id'], product['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/product_template_service/get_all_product_templates.py b/examples/dfp/v201702/product_template_service/get_all_product_templates.py index d2be8378..4f79ceb9 100755 --- a/examples/dfp/v201702/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201702/product_template_service/get_all_product_templates.py @@ -26,7 +26,7 @@ def main(client): 'ProductTemplateService', version='v201702') # Create a statement to select product templates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % (product_template['id'], product_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py index 0f2050c5..17ee0df9 100755 --- a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py @@ -26,7 +26,7 @@ def main(client): 'ProposalLineItemService', version='v201702') # Create a statement to select proposal line items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % (proposal_line_item['id'], proposal_line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/proposal_service/get_all_proposals.py b/examples/dfp/v201702/proposal_service/get_all_proposals.py index 7fffa0f3..53ad307c 100755 --- a/examples/dfp/v201702/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201702/proposal_service/get_all_proposals.py @@ -25,7 +25,7 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201702') # Create a statement to select proposals. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % (proposal['id'], proposal['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py index ff302fca..a3753055 100755 --- a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py @@ -25,7 +25,7 @@ def main(client): rate_card_service = client.GetService('RateCardService', version='v201702') # Create a statement to select rate cards. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. @@ -38,7 +38,7 @@ def main(client): print('Rate card with ID "%d", name "%s", and currency code "%s" was ' 'found.\n' % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py index d3ea80f3..35287882 100755 --- a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py @@ -26,7 +26,7 @@ def main(client): 'ReconciliationReportService', version='v201702') # Create a statement to select reconciliation reports. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. @@ -43,7 +43,7 @@ def main(client): ' found.\n' % (reconciliation_report['id'], reconciliation_report['startDate']['month'], reconciliation_report['startDate']['year'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py index 706fb9c3..cc211cfe 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -26,7 +26,7 @@ def main(client): 'SuggestedAdUnitService', version='v201702') # Create a statement to select suggested ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -39,7 +39,7 @@ def main(client): print( 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/team_service/get_all_teams.py b/examples/dfp/v201702/team_service/get_all_teams.py index 23f54d2c..03fdf947 100755 --- a/examples/dfp/v201702/team_service/get_all_teams.py +++ b/examples/dfp/v201702/team_service/get_all_teams.py @@ -25,7 +25,7 @@ def main(client): team_service = client.GetService('TeamService', version='v201702') # Create a statement to select teams. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each team. print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], team['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/user_service/get_all_users.py b/examples/dfp/v201702/user_service/get_all_users.py index 698024a5..e35e600b 100755 --- a/examples/dfp/v201702/user_service/get_all_users.py +++ b/examples/dfp/v201702/user_service/get_all_users.py @@ -25,7 +25,7 @@ def main(client): user_service = client.GetService('UserService', version='v201702') # Create a statement to select users. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], user['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py index cf5ff6c9..6343bbae 100755 --- a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py @@ -26,7 +26,7 @@ def main(client): 'UserTeamAssociationService', version='v201702') # Create a statement to select user team associations. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -39,7 +39,7 @@ def main(client): print('User team association with team id "%d" and user id "%d" was ' 'found.\n' % (user_team_association['teamId'], user_team_association['userId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py index 7d51c2cc..cc7eaf66 100755 --- a/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py @@ -26,7 +26,7 @@ def main(client): 'ActivityGroupService', version='v201705') # Create a statement to select activity groups. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/activity_service/get_all_activities.py b/examples/dfp/v201705/activity_service/get_all_activities.py index e8db21bc..a3b4412b 100755 --- a/examples/dfp/v201705/activity_service/get_all_activities.py +++ b/examples/dfp/v201705/activity_service/get_all_activities.py @@ -25,7 +25,7 @@ def main(client): activity_service = client.GetService('ActivityService', version='v201705') # Create a statement to select activities. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each activity. print('Activity with ID "%d" and name "%s" was found.\n' % (activity['id'], activity['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py index f3ce56ba..f0aad4be 100755 --- a/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py @@ -26,7 +26,7 @@ def main(client): 'AudienceSegmentService', version='v201705') # Create a statement to select audience segments. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. @@ -39,7 +39,7 @@ def main(client): print('Audience segment with ID "%d", name "%s", and size "%d" was ' 'found.\n' % (audience_segment['id'], audience_segment['name'], audience_segment['size'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/base_rate_service/get_all_base_rates.py b/examples/dfp/v201705/base_rate_service/get_all_base_rates.py index cc762428..0d42dfc2 100755 --- a/examples/dfp/v201705/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201705/base_rate_service/get_all_base_rates.py @@ -25,7 +25,7 @@ def main(client): base_rate_service = client.GetService('BaseRateService', version='v201705') # Create a statement to select base rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. @@ -38,7 +38,7 @@ def main(client): print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), base_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/company_service/get_all_companies.py b/examples/dfp/v201705/company_service/get_all_companies.py index 7bb631bb..61e10d09 100755 --- a/examples/dfp/v201705/company_service/get_all_companies.py +++ b/examples/dfp/v201705/company_service/get_all_companies.py @@ -25,7 +25,7 @@ def main(client): company_service = client.GetService('CompanyService', version='v201705') # Create a statement to select companies. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/contact_service/get_all_contacts.py b/examples/dfp/v201705/contact_service/get_all_contacts.py index 42fdd9fd..c8e1c3e9 100755 --- a/examples/dfp/v201705/contact_service/get_all_contacts.py +++ b/examples/dfp/v201705/contact_service/get_all_contacts.py @@ -25,7 +25,7 @@ def main(client): contact_service = client.GetService('ContactService', version='v201705') # Create a statement to select contacts. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 4284380e..ce28be95 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -26,7 +26,7 @@ def main(client): 'ContentMetadataKeyHierarchyService', version='v201705') # Create a statement to select content metadata key hierarchies. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been @@ -42,7 +42,7 @@ def main(client): print('Content metadata key hierarchy with ID "%d" and name "%s" was ' 'found.\n' % (content_metadata_key_hierarchy['id'], content_metadata_key_hierarchy['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/content_service/get_all_content.py b/examples/dfp/v201705/content_service/get_all_content.py index c2bd7aee..5a73428e 100755 --- a/examples/dfp/v201705/content_service/get_all_content.py +++ b/examples/dfp/v201705/content_service/get_all_content.py @@ -25,7 +25,7 @@ def main(client): content_service = client.GetService('ContentService', version='v201705') # Create a statement to select content. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % (content['id'], content['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/creative_service/get_all_creatives.py b/examples/dfp/v201705/creative_service/get_all_creatives.py index d400094b..809b4d2e 100755 --- a/examples/dfp/v201705/creative_service/get_all_creatives.py +++ b/examples/dfp/v201705/creative_service/get_all_creatives.py @@ -25,7 +25,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201705') # Create a statement to select creatives. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % (creative['id'], creative['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py index 90257068..de0d3ef5 100755 --- a/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py @@ -26,7 +26,7 @@ def main(client): 'CreativeSetService', version='v201705') # Create a statement to select creative sets. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % (creative_set['id'], creative_set['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py index 7bdec81f..7550f838 100755 --- a/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py @@ -26,7 +26,7 @@ def main(client): 'CreativeTemplateService', version='v201705') # Create a statement to select creative templates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % (creative_template['id'], creative_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py index 7b783565..8e63e641 100755 --- a/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py @@ -26,7 +26,7 @@ def main(client): 'CreativeWrapperService', version='v201705') # Create a statement to select creative wrappers. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py index 42631ca9..740a05bf 100755 --- a/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py @@ -26,7 +26,7 @@ def main(client): 'CustomFieldService', version='v201705') # Create a statement to select custom fields. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % (custom_field['id'], custom_field['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 3e937fd0..97c46ba1 100755 --- a/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201705') # Create statement to get all targeting keys. - targeting_key_statement = dfp.FilterStatement() + targeting_key_statement = dfp.StatementBuilder() all_keys = [] @@ -36,7 +36,7 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break diff --git a/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py index 69f5daac..39f6e4f6 100755 --- a/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py @@ -26,7 +26,7 @@ def main(client): 'ExchangeRateService', version='v201705') # Create a statement to select exchange rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. @@ -41,7 +41,7 @@ def main(client): 'and exchange rate "%d" was found.\n' % (exchange_rate['id'], exchange_rate['currencyCode'], exchange_rate['direction'], exchange_rate['exchangeRate'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/inventory_service/get_all_ad_units.py b/examples/dfp/v201705/inventory_service/get_all_ad_units.py index 1e2b0cb2..809dd346 100755 --- a/examples/dfp/v201705/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201705/inventory_service/get_all_ad_units.py @@ -25,7 +25,7 @@ def main(client): ad_unit_service = client.GetService('InventoryService', version='v201705') # Create a statement to select ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % (ad_unit['id'], ad_unit['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/label_service/get_all_labels.py b/examples/dfp/v201705/label_service/get_all_labels.py index a89f62b2..6a29dedf 100755 --- a/examples/dfp/v201705/label_service/get_all_labels.py +++ b/examples/dfp/v201705/label_service/get_all_labels.py @@ -25,7 +25,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201705') # Create a statement to select labels. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], label['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py index e670adea..55b0a511 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py @@ -26,7 +26,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201705') # Create a statement to select line item creative associations. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. @@ -44,7 +44,7 @@ def main(client): print('Line item creative association with line item ID "%d" and ' 'creative ID "%d" was found.\n' % (lica['lineItemId'], lica['creativeId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py b/examples/dfp/v201705/line_item_creative_association_service/update_licas.py index fefe3090..b3973bf0 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201705/line_item_creative_association_service/update_licas.py @@ -31,7 +31,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201705') # Create statement object to get all LICAs. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() while True: # Get LICAs by statement. @@ -53,7 +53,7 @@ def main(client): print ('LICA with line item id "%s", creative id "%s", and status ' '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], lica['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/line_item_service/get_all_line_items.py b/examples/dfp/v201705/line_item_service/get_all_line_items.py index 441fc5bc..90e12640 100755 --- a/examples/dfp/v201705/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201705/line_item_service/get_all_line_items.py @@ -25,7 +25,7 @@ def main(client): line_item_service = client.GetService('LineItemService', version='v201705') # Create a statement to select line items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/native_style_service/get_all_native_styles.py b/examples/dfp/v201705/native_style_service/get_all_native_styles.py index 915d5624..86c2da5c 100755 --- a/examples/dfp/v201705/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201705/native_style_service/get_all_native_styles.py @@ -26,7 +26,7 @@ def main(client): version='v201705') # Create a statement to select native styles. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each native style. print('Native style with ID "%d" and name "%s" was found.\n' % (native_style['id'], native_style['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/order_service/get_all_orders.py b/examples/dfp/v201705/order_service/get_all_orders.py index cc192e1c..d19fb7f6 100755 --- a/examples/dfp/v201705/order_service/get_all_orders.py +++ b/examples/dfp/v201705/order_service/get_all_orders.py @@ -25,7 +25,7 @@ def main(client): order_service = client.GetService('OrderService', version='v201705') # Create a statement to select orders. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], order['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/package_service/get_all_packages.py b/examples/dfp/v201705/package_service/get_all_packages.py index 809a8f24..e5369e61 100755 --- a/examples/dfp/v201705/package_service/get_all_packages.py +++ b/examples/dfp/v201705/package_service/get_all_packages.py @@ -25,7 +25,7 @@ def main(client): pkg_service = client.GetService('PackageService', version='v201705') # Create a statement to select packages. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. @@ -37,7 +37,7 @@ def main(client): print( 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/placement_service/create_placements.py b/examples/dfp/v201705/placement_service/create_placements.py index b05669de..293167ba 100755 --- a/examples/dfp/v201705/placement_service/create_placements.py +++ b/examples/dfp/v201705/placement_service/create_placements.py @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() while True: response = inventory_service.getAdUnitsByStatement( @@ -76,7 +76,7 @@ def main(client): elif size['width'] == '468' and size['height'] == '60': banner_ad_unit_placement['targetedAdUnitIds'].append( ad_unit['id']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/placement_service/get_all_placements.py b/examples/dfp/v201705/placement_service/get_all_placements.py index 5acce24b..20889bf0 100755 --- a/examples/dfp/v201705/placement_service/get_all_placements.py +++ b/examples/dfp/v201705/placement_service/get_all_placements.py @@ -25,7 +25,7 @@ def main(client): placement_service = client.GetService('PlacementService', version='v201705') # Create a statement to select placements. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. @@ -37,7 +37,7 @@ def main(client): # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % (placement['id'], placement['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py index a8803339..21c6b3d6 100755 --- a/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py @@ -26,7 +26,7 @@ def main(client): 'PremiumRateService', version='v201705') # Create a statement to select premium rates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. @@ -40,7 +40,7 @@ def main(client): 'id "%d" was found.\n' % (premium_rate['id'], dfp.DfpClassType(premium_rate), premium_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py index 274d0d56..536f23bb 100755 --- a/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageItemService', version='v201705') # Create a statement to select product package items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. @@ -40,7 +40,7 @@ def main(client): 'package id "%d" was found.\n' % (product_package_item['id'], product_package_item['productId'], product_package_item['productPackageId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/product_package_service/get_all_product_packages.py b/examples/dfp/v201705/product_package_service/get_all_product_packages.py index b8e1910e..06c1abed 100755 --- a/examples/dfp/v201705/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201705/product_package_service/get_all_product_packages.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageService', version='v201705') # Create a statement to select product packages. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % (product_package['id'], product_package['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/product_service/get_all_products.py b/examples/dfp/v201705/product_service/get_all_products.py index 51ff246e..8ac87c31 100755 --- a/examples/dfp/v201705/product_service/get_all_products.py +++ b/examples/dfp/v201705/product_service/get_all_products.py @@ -25,7 +25,7 @@ def main(client): product_service = client.GetService('ProductService', version='v201705') # Create a statement to select products. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % (product['id'], product['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/product_template_service/get_all_product_templates.py b/examples/dfp/v201705/product_template_service/get_all_product_templates.py index d9469444..7114a26a 100755 --- a/examples/dfp/v201705/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201705/product_template_service/get_all_product_templates.py @@ -26,7 +26,7 @@ def main(client): 'ProductTemplateService', version='v201705') # Create a statement to select product templates. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % (product_template['id'], product_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py index 4b0a2fb6..254e0dd0 100755 --- a/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py @@ -26,7 +26,7 @@ def main(client): 'ProposalLineItemService', version='v201705') # Create a statement to select proposal line items. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. @@ -38,7 +38,7 @@ def main(client): # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % (proposal_line_item['id'], proposal_line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/proposal_service/get_all_proposals.py b/examples/dfp/v201705/proposal_service/get_all_proposals.py index bc68a5ef..57258dca 100755 --- a/examples/dfp/v201705/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201705/proposal_service/get_all_proposals.py @@ -25,7 +25,7 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201705') # Create a statement to select proposals. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % (proposal['id'], proposal['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py index 4183924e..73469628 100755 --- a/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py @@ -25,7 +25,7 @@ def main(client): rate_card_service = client.GetService('RateCardService', version='v201705') # Create a statement to select rate cards. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. @@ -38,7 +38,7 @@ def main(client): print('Rate card with ID "%d", name "%s", and currency code "%s" was ' 'found.\n' % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py index 68e6dee5..54fdc3a0 100755 --- a/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py @@ -26,7 +26,7 @@ def main(client): 'ReconciliationReportService', version='v201705') # Create a statement to select reconciliation reports. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. @@ -43,7 +43,7 @@ def main(client): ' found.\n' % (reconciliation_report['id'], reconciliation_report['startDate']['month'], reconciliation_report['startDate']['year'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py index 7b4842a1..39046b06 100755 --- a/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -26,7 +26,7 @@ def main(client): 'SuggestedAdUnitService', version='v201705') # Create a statement to select suggested ad units. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -39,7 +39,7 @@ def main(client): print( 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/team_service/get_all_teams.py b/examples/dfp/v201705/team_service/get_all_teams.py index 2c34c9cd..1b5b9364 100755 --- a/examples/dfp/v201705/team_service/get_all_teams.py +++ b/examples/dfp/v201705/team_service/get_all_teams.py @@ -25,7 +25,7 @@ def main(client): team_service = client.GetService('TeamService', version='v201705') # Create a statement to select teams. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each team. print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], team['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/user_service/get_all_users.py b/examples/dfp/v201705/user_service/get_all_users.py index 8319149c..54d5bac9 100755 --- a/examples/dfp/v201705/user_service/get_all_users.py +++ b/examples/dfp/v201705/user_service/get_all_users.py @@ -25,7 +25,7 @@ def main(client): user_service = client.GetService('UserService', version='v201705') # Create a statement to select users. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. @@ -36,7 +36,7 @@ def main(client): # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], user['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py index 88208c16..4daad809 100755 --- a/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py @@ -26,7 +26,7 @@ def main(client): 'UserTeamAssociationService', version='v201705') # Create a statement to select user team associations. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -39,7 +39,7 @@ def main(client): print('User team association with team id "%d" and user id "%d" was ' 'found.\n' % (user_team_association['teamId'], user_team_association['userId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/googleads/adwords.py b/googleads/adwords.py index 04b2d2ec..02c901a3 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -182,6 +182,56 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201708': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignBidModifierService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignGroupPerformanceTargetService': 'cm', + 'CampaignGroupService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineCallConversionFeedService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'OfflineDataUploadService': 'cm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } From 60d6c71df3907f71d9b79b14b7a26ddec582ab18 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 9 Aug 2017 15:17:02 -0400 Subject: [PATCH 082/180] Commiting latest changes. From 5701dd2913d2635736129861886193c3f293c705 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 9 Aug 2017 15:20:12 -0400 Subject: [PATCH 083/180] Commiting latest changes. From 4d9c239a40201d086a311ece1c0a36bc347fda0c Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 9 Aug 2017 15:39:43 -0400 Subject: [PATCH 084/180] AdWords v201708 Release --- ChangeLog | 3 +++ googleads/common.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index 1a9b01da..371748cc 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +6.1.0 -- 8/9/17: +* Added support for AdWords v201708. + 6.0.0 -- 6/27/17: * Removed support for AdWords v201607. * Improved logging support. Can now specify logging configuration from the diff --git a/googleads/common.py b/googleads/common.py index 90129116..01265371 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -66,7 +66,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '6.0.0' +VERSION = '6.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' From 5aafb265f75d1b0c8fea05b15b2862cab71e3bf2 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 9 Aug 2017 15:41:20 -0400 Subject: [PATCH 085/180] Commiting latest changes. From 91ffb8ff13258d3d65626f57b276a6d31b62c34f Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Wed, 16 Aug 2017 07:30:25 -0400 Subject: [PATCH 086/180] Committing recent changes. --- ChangeLog | 4 + ..._item_reports_for_reconciliation_report.py | 75 ------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 2 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 6 +- .../create_product_package_item_base_rates.py | 66 ++++++ .../create_product_template_base_rates.py | 6 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 2 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 60 +++++ .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../update_creative_set.py | 2 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../create_creative_wrappers.py | 6 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 2 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 2 +- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 2 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- ...efined_custom_targeting_keys_and_values.py | 4 +- .../update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../update_exchange_rates.py | 2 +- .../get_availability_forecast.py | 22 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 2 +- .../inventory_service/create_ad_units.py | 2 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 2 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../label_service/get_active_labels.py | 2 +- .../label_service/get_all_labels.py | 2 +- .../label_service/update_labels.py | 2 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 2 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 2 +- .../line_item_service/create_line_items.py | 20 +- .../create_video_line_item.py | 20 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../line_item_service/pause_line_items.py | 74 ++++++ .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 2 +- .../v201708/native_style_service/__init__.py | 15 ++ .../create_native_styles.py | 180 +++++++++++++++ .../get_all_native_styles.py | 51 +++++ .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 2 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 2 +- .../order_service/update_orders.py | 2 +- .../package_service/create_packages.py | 61 +++++ ...reate_proposal_line_items_from_packages.py | 68 ++++++ .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 2 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 2 +- .../get_active_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 40 ++-- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 7 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 2 +- .../update_premium_rates.py | 2 +- .../create_product_package_item.py | 62 ++++++ .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 2 +- .../create_product_packages.py | 51 +++++ .../get_active_product_packages.py | 2 +- .../get_all_product_packages.py | 2 +- .../product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 4 +- .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- ...sh_programmatic_products_to_marketplace.py | 2 +- .../product_service/update_products.py | 2 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 2 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 2 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 2 +- ...create_programmatic_proposal_line_items.py | 33 +-- ...sal_line_items_for_non_sales_management.py | 33 +-- .../create_proposal_line_items.py | 33 +-- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 2 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 40 ++-- .../get_proposals_pending_approval.py | 2 +- .../request_buyers_acceptance.py | 2 +- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 2 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_recent_changes.py | 210 ++++++++++++++++++ .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 60 +++++ .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 75 +++++++ ...update_reconciliation_line_item_reports.py | 67 ++++++ ...order_reports_for_reconciliation_report.py | 2 +- .../submit_reconciliation_order_reports.py | 71 ++++++ ...n_report_rows_for_reconciliation_report.py | 18 +- .../update_reconciliation_report_rows.py | 75 +++++++ .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 14 +- .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 12 +- .../report_service/run_inventory_report.py | 4 +- .../report_service/run_reach_report.py | 2 +- .../run_report_with_custom_fields.py | 4 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 2 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 2 +- .../team_service/update_teams.py | 2 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 2 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 2 +- .../v201708/user_service/get_current_user.py | 39 ++++ .../user_service/get_user_by_email_address.py | 2 +- .../user_service/update_users.py | 2 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py | 2 +- ...et_workflow_external_condition_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 2 +- googleads/common.py | 2 +- googleads/dfp.py | 27 +-- 232 files changed, 1595 insertions(+), 460 deletions(-) delete mode 100755 examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename examples/dfp/{v201611 => v201708}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201611 => v201708}/activity_group_service/get_active_activity_groups.py (97%) rename examples/dfp/{v201611 => v201708}/activity_group_service/get_all_activity_groups.py (97%) rename examples/dfp/{v201611 => v201708}/activity_group_service/update_activity_groups.py (97%) rename examples/dfp/{v201611 => v201708}/activity_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/activity_service/create_activities.py (99%) rename examples/dfp/{v201611 => v201708}/activity_service/get_active_activities.py (99%) rename examples/dfp/{v201611 => v201708}/activity_service/get_all_activities.py (99%) rename examples/dfp/{v201611 => v201708}/activity_service/update_activities.py (99%) rename examples/dfp/{v201611 => v201708}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/audience_segment_service/create_audience_segments.py (98%) rename examples/dfp/{v201611 => v201708}/audience_segment_service/get_all_audience_segments.py (97%) rename examples/dfp/{v201611 => v201708}/audience_segment_service/get_first_party_audience_segments.py (97%) rename examples/dfp/{v201611 => v201708}/audience_segment_service/populate_first_party_audience_segments.py (97%) rename examples/dfp/{v201611 => v201708}/audience_segment_service/update_audience_segments.py (98%) rename examples/dfp/{v201611 => v201708}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/base_rate_service/create_product_base_rates.py (89%) create mode 100755 examples/dfp/v201708/base_rate_service/create_product_package_item_base_rates.py rename examples/dfp/{v201611 => v201708}/base_rate_service/create_product_template_base_rates.py (88%) rename examples/dfp/{v201611 => v201708}/base_rate_service/get_all_base_rates.py (99%) rename examples/dfp/{v201611 => v201708}/base_rate_service/get_base_rates_for_rate_card.py (99%) rename examples/dfp/{v201611 => v201708}/base_rate_service/update_base_rates.py (99%) rename examples/dfp/{v201611 => v201708}/company_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/company_service/create_companies.py (99%) rename examples/dfp/{v201611 => v201708}/company_service/get_advertisers.py (99%) rename examples/dfp/{v201611 => v201708}/company_service/get_all_companies.py (99%) rename examples/dfp/{v201611 => v201708}/company_service/update_companies.py (99%) rename examples/dfp/{v201611 => v201708}/contact_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201611 => v201708}/contact_service/get_all_contacts.py (99%) rename examples/dfp/{v201611 => v201708}/contact_service/get_uninvited_contacts.py (99%) rename examples/dfp/{v201611 => v201708}/contact_service/update_contacts.py (99%) rename examples/dfp/{v201611 => v201708}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201611 => v201708}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201611 => v201708}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201611 => v201708}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (98%) rename examples/dfp/{v201611 => v201708}/content_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/content_service/get_all_content.py (99%) rename examples/dfp/{v201611 => v201708}/creative_service/__init__.py (100%) create mode 100755 examples/dfp/v201708/creative_service/copy_image_creatives.py rename examples/dfp/{v201611 => v201708}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201611 => v201708}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201611 => v201708}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201611 => v201708}/creative_service/create_native_creative.py (99%) rename examples/dfp/{v201611 => v201708}/creative_service/get_all_creatives.py (99%) rename examples/dfp/{v201611 => v201708}/creative_service/get_image_creatives.py (99%) rename examples/dfp/{v201611 => v201708}/creative_service/update_creatives.py (99%) rename examples/dfp/{v201611 => v201708}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201611 => v201708}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201611 => v201708}/creative_set_service/get_all_creative_sets.py (97%) rename examples/dfp/{v201611 => v201708}/creative_set_service/get_creative_sets_for_master_creative.py (97%) rename examples/dfp/{v201611 => v201708}/creative_set_service/update_creative_set.py (97%) rename examples/dfp/{v201611 => v201708}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/creative_template_service/get_all_creative_templates.py (97%) rename examples/dfp/{v201611 => v201708}/creative_template_service/get_system_defined_creative_templates.py (97%) rename examples/dfp/{v201611 => v201708}/creative_wrapper_service/create_creative_wrappers.py (91%) rename examples/dfp/{v201611 => v201708}/creative_wrapper_service/deactivate_creative_wrapper.py (97%) rename examples/dfp/{v201611 => v201708}/creative_wrapper_service/get_active_creative_wrappers.py (97%) rename examples/dfp/{v201611 => v201708}/creative_wrapper_service/get_all_creative_wrappers.py (97%) rename examples/dfp/{v201611 => v201708}/creative_wrapper_service/update_creative_wrappers.py (97%) rename examples/dfp/{v201611 => v201708}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201611 => v201708}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201611 => v201708}/custom_field_service/deactivate_all_line_item_custom_fields.py (98%) rename examples/dfp/{v201611 => v201708}/custom_field_service/get_all_custom_fields.py (97%) rename examples/dfp/{v201611 => v201708}/custom_field_service/get_custom_fields_for_line_items.py (97%) rename examples/dfp/{v201611 => v201708}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201611 => v201708}/custom_field_service/update_custom_fields.py (98%) rename examples/dfp/{v201611 => v201708}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201611 => v201708}/custom_targeting_service/delete_custom_targeting_keys.py (98%) rename examples/dfp/{v201611 => v201708}/custom_targeting_service/delete_custom_targeting_values.py (98%) rename examples/dfp/{v201611 => v201708}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/dfp/{v201611 => v201708}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (96%) rename examples/dfp/{v201611 => v201708}/custom_targeting_service/update_custom_targeting_keys.py (97%) rename examples/dfp/{v201611 => v201708}/custom_targeting_service/update_custom_targeting_values.py (97%) rename examples/dfp/{v201611 => v201708}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201611 => v201708}/exchange_rate_service/get_all_exchange_rates.py (97%) rename examples/dfp/{v201611 => v201708}/exchange_rate_service/get_exchange_rates_for_currency_code.py (97%) rename examples/dfp/{v201611 => v201708}/exchange_rate_service/update_exchange_rates.py (97%) rename examples/dfp/{v201611 => v201708}/forecast_service/get_availability_forecast.py (92%) rename examples/dfp/{v201611 => v201708}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/dfp/{v201611 => v201708}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/dfp/{v201611 => v201708}/inventory_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/inventory_service/archive_ad_units.py (99%) rename examples/dfp/{v201611 => v201708}/inventory_service/create_ad_units.py (99%) rename examples/dfp/{v201611 => v201708}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/dfp/{v201611 => v201708}/inventory_service/get_all_ad_units.py (99%) rename examples/dfp/{v201611 => v201708}/inventory_service/update_ad_units.py (99%) rename examples/dfp/{v201611 => v201708}/label_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/label_service/create_labels.py (99%) rename examples/dfp/{v201611 => v201708}/label_service/deactivate_labels.py (99%) rename examples/dfp/{v201611 => v201708}/label_service/get_active_labels.py (99%) rename examples/dfp/{v201611 => v201708}/label_service/get_all_labels.py (99%) rename examples/dfp/{v201611 => v201708}/label_service/update_labels.py (99%) rename examples/dfp/{v201611 => v201708}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201611 => v201708}/line_item_creative_association_service/deactivate_licas.py (97%) rename examples/dfp/{v201611 => v201708}/line_item_creative_association_service/get_all_licas.py (97%) rename examples/dfp/{v201611 => v201708}/line_item_creative_association_service/get_licas_for_line_item.py (97%) rename examples/dfp/{v201611 => v201708}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201611 => v201708}/line_item_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/line_item_service/activate_line_items.py (99%) rename examples/dfp/{v201611 => v201708}/line_item_service/create_line_items.py (93%) rename examples/dfp/{v201611 => v201708}/line_item_service/create_video_line_item.py (92%) rename examples/dfp/{v201611 => v201708}/line_item_service/get_all_line_items.py (99%) rename examples/dfp/{v201611 => v201708}/line_item_service/get_line_items_that_need_creatives.py (99%) rename examples/dfp/{v201611 => v201708}/line_item_service/get_recently_updated_line_items.py (99%) create mode 100755 examples/dfp/v201708/line_item_service/pause_line_items.py rename examples/dfp/{v201611 => v201708}/line_item_service/target_custom_criteria.py (99%) rename examples/dfp/{v201611 => v201708}/line_item_service/update_line_items.py (99%) create mode 100755 examples/dfp/v201708/native_style_service/__init__.py create mode 100755 examples/dfp/v201708/native_style_service/create_native_styles.py create mode 100755 examples/dfp/v201708/native_style_service/get_all_native_styles.py rename examples/dfp/{v201611 => v201708}/network_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/network_service/get_all_networks.py (99%) rename examples/dfp/{v201611 => v201708}/network_service/make_test_network.py (99%) rename examples/dfp/{v201611 => v201708}/order_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/order_service/approve_orders.py (99%) rename examples/dfp/{v201611 => v201708}/order_service/create_orders.py (99%) rename examples/dfp/{v201611 => v201708}/order_service/get_all_orders.py (99%) rename examples/dfp/{v201611 => v201708}/order_service/get_orders_starting_soon.py (99%) rename examples/dfp/{v201611 => v201708}/order_service/update_orders.py (99%) create mode 100755 examples/dfp/v201708/package_service/create_packages.py create mode 100755 examples/dfp/v201708/package_service/create_proposal_line_items_from_packages.py rename examples/dfp/{v201611 => v201708}/package_service/get_all_packages.py (99%) rename examples/dfp/{v201611 => v201708}/package_service/get_in_progress_packages.py (99%) rename examples/dfp/{v201611 => v201708}/placement_service/create_placements.py (99%) rename examples/dfp/{v201611 => v201708}/placement_service/deactivate_placements.py (99%) rename examples/dfp/{v201611 => v201708}/placement_service/get_active_placements.py (99%) rename examples/dfp/{v201611 => v201708}/placement_service/get_all_placements.py (99%) rename examples/dfp/{v201611 => v201708}/placement_service/update_placements.py (57%) rename examples/dfp/{v201611 => v201708}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/premium_rate_service/create_premium_rates.py (90%) rename examples/dfp/{v201611 => v201708}/premium_rate_service/get_all_premium_rates.py (97%) rename examples/dfp/{v201611 => v201708}/premium_rate_service/get_premium_rates_for_rate_card.py (97%) rename examples/dfp/{v201611 => v201708}/premium_rate_service/update_premium_rates.py (97%) create mode 100755 examples/dfp/v201708/product_package_item_service/create_product_package_item.py rename examples/dfp/{v201611 => v201708}/product_package_item_service/get_all_product_package_items.py (97%) rename examples/dfp/{v201611 => v201708}/product_package_item_service/get_product_package_items_for_product_package.py (97%) create mode 100755 examples/dfp/v201708/product_package_service/create_product_packages.py rename examples/dfp/{v201611 => v201708}/product_package_service/get_active_product_packages.py (97%) rename examples/dfp/{v201611 => v201708}/product_package_service/get_all_product_packages.py (97%) rename examples/dfp/{v201611 => v201708}/product_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/product_service/create_programmatic_products_for_non_sales_management.py (99%) rename examples/dfp/{v201611 => v201708}/product_service/get_all_products.py (99%) rename examples/dfp/{v201611 => v201708}/product_service/get_products_for_product_template.py (99%) rename examples/dfp/{v201611 => v201708}/product_service/publish_programmatic_products_to_marketplace.py (99%) rename examples/dfp/{v201611 => v201708}/product_service/update_products.py (99%) rename examples/dfp/{v201611 => v201708}/product_template_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/product_template_service/activate_product_templates.py (97%) rename examples/dfp/{v201611 => v201708}/product_template_service/create_product_templates.py (97%) rename examples/dfp/{v201611 => v201708}/product_template_service/create_programmatic_product_templates.py (96%) rename examples/dfp/{v201611 => v201708}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201611 => v201708}/product_template_service/get_sponsorship_product_templates.py (97%) rename examples/dfp/{v201611 => v201708}/product_template_service/update_product_templates.py (98%) rename examples/dfp/{v201611 => v201708}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/proposal_line_item_service/archive_proposal_line_items.py (98%) rename examples/dfp/{v201611 => v201708}/proposal_line_item_service/create_programmatic_proposal_line_items.py (82%) rename examples/dfp/{v201611 => v201708}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (82%) rename examples/dfp/{v201611 => v201708}/proposal_line_item_service/create_proposal_line_items.py (82%) rename examples/dfp/{v201611 => v201708}/proposal_line_item_service/get_all_proposal_line_items.py (97%) rename examples/dfp/{v201611 => v201708}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (97%) rename examples/dfp/{v201611 => v201708}/proposal_line_item_service/update_proposal_line_items.py (97%) rename examples/dfp/{v201611 => v201708}/proposal_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/proposal_service/create_programmatic_proposals.py (98%) rename examples/dfp/{v201611 => v201708}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (99%) rename examples/dfp/{v201611 => v201708}/proposal_service/create_proposals.py (99%) rename examples/dfp/{v201611 => v201708}/proposal_service/get_all_proposals.py (99%) rename examples/dfp/{v201611 => v201708}/proposal_service/get_marketplace_comments.py (55%) rename examples/dfp/{v201611 => v201708}/proposal_service/get_proposals_pending_approval.py (99%) rename examples/dfp/{v201611 => v201708}/proposal_service/request_buyers_acceptance.py (99%) rename examples/dfp/{v201611 => v201708}/proposal_service/submit_proposals_for_approval.py (99%) rename examples/dfp/{v201611 => v201708}/proposal_service/update_proposals.py (99%) rename examples/dfp/{v201611 => v201708}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/dfp/{v201611 => v201708}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) create mode 100755 examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py rename examples/dfp/{v201611 => v201708}/rate_card_service/__init__.py (100%) create mode 100755 examples/dfp/v201708/rate_card_service/create_rate_cards.py rename examples/dfp/{v201611 => v201708}/rate_card_service/get_all_rate_cards.py (99%) rename examples/dfp/{v201611 => v201708}/rate_card_service/get_marketplace_rate_cards.py (99%) create mode 100755 examples/dfp/v201708/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py create mode 100755 examples/dfp/v201708/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename examples/dfp/{v201611 => v201708}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (97%) create mode 100755 examples/dfp/v201708/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename examples/dfp/{v201611 => v201708}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (90%) create mode 100755 examples/dfp/v201708/reconciliation_report_row_service/update_reconciliation_report_rows.py rename examples/dfp/{v201611 => v201708}/reconciliation_report_service/get_all_reconciliation_reports.py (97%) rename examples/dfp/{v201611 => v201708}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (86%) rename examples/dfp/{v201611 => v201708}/report_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/report_service/run_delivery_report.py (87%) rename examples/dfp/{v201611 => v201708}/report_service/run_inventory_report.py (97%) rename examples/dfp/{v201611 => v201708}/report_service/run_reach_report.py (96%) rename examples/dfp/{v201611 => v201708}/report_service/run_report_with_custom_fields.py (97%) rename examples/dfp/{v201611 => v201708}/report_service/run_sales_report.py (96%) rename examples/dfp/{v201611 => v201708}/report_service/run_saved_query.py (97%) rename examples/dfp/{v201611 => v201708}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (97%) rename examples/dfp/{v201611 => v201708}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) rename examples/dfp/{v201611 => v201708}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (97%) rename examples/dfp/{v201611 => v201708}/team_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/team_service/create_teams.py (96%) rename examples/dfp/{v201611 => v201708}/team_service/get_all_teams.py (95%) rename examples/dfp/{v201611 => v201708}/team_service/update_teams.py (96%) rename examples/dfp/{v201611 => v201708}/user_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/user_service/create_users.py (95%) rename examples/dfp/{v201611 => v201708}/user_service/deactivate_users.py (96%) rename examples/dfp/{v201611 => v201708}/user_service/get_all_roles.py (100%) rename examples/dfp/{v201611 => v201708}/user_service/get_all_users.py (95%) create mode 100755 examples/dfp/v201708/user_service/get_current_user.py rename examples/dfp/{v201611 => v201708}/user_service/get_user_by_email_address.py (96%) rename examples/dfp/{v201611 => v201708}/user_service/update_users.py (96%) rename examples/dfp/{v201611 => v201708}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201611 => v201708}/user_team_association_service/delete_user_team_associations.py (98%) rename examples/dfp/{v201611 => v201708}/user_team_association_service/get_all_user_team_associations.py (97%) rename examples/dfp/{v201611 => v201708}/user_team_association_service/get_user_team_associations_for_user.py (97%) rename examples/dfp/{v201611 => v201708}/user_team_association_service/update_user_team_associations.py (98%) rename examples/dfp/{v201611 => v201708}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201611 => v201708}/workflow_request_service/approve_workflow_approval_requests.py (97%) rename examples/dfp/{v201611 => v201708}/workflow_request_service/get_workflow_approval_requests.py (97%) rename examples/dfp/{v201611 => v201708}/workflow_request_service/get_workflow_external_condition_requests.py (97%) rename examples/dfp/{v201611 => v201708}/workflow_request_service/trigger_workflow_external_condition_requests.py (98%) diff --git a/ChangeLog b/ChangeLog index 371748cc..1f081cd8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +7.0.0 -- 8/15/17 +* Added support and examples for DFP v201708. +* Removed support and examples for DFP v201608. + 6.1.0 -- 8/9/17: * Added support for AdWords v201708. diff --git a/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py deleted file mode 100755 index bd042bb6..00000000 --- a/examples/dfp/v201611/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. -"""Gets a reconciliation report's data for line items that served through DFP. -""" - -# Import appropriate modules from the client library. -from googleads import dfp - -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_line_item_report_service = client.GetService( - 'ReconciliationLineItemReportService', version='v201611') - query = ('WHERE reconciliationReportId = :reconciliationReportId AND ' - 'lineItemId != :lineItemId') - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - }}, - ] - # Create a statement to select reconciliation line item reports. - statement = dfp.FilterStatement(query, values) - - # Retrieve a small amount of reconciliation line item reports at a time, - # paging through until all reconciliation line item reports have been - # retrieved. - while True: - response = ( - reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement( - statement.ToStatement())) - if 'results' in response: - for reconciliation_line_item_report in response['results']: - # Print out some information for each reconciliation line item report. - print( - 'Reconciliation line item report with ID "%d", line item ID "%d", ' - 'reconciliation source "%s", and reconciled volume "%d" was ' - 'found.\n' % - (reconciliation_line_item_report['id'], - reconciliation_line_item_report['lineItemId'], - reconciliation_line_item_report['reconciliationSource'], - reconciliation_line_item_report['reconciledVolume'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201611/activity_group_service/__init__.py b/examples/dfp/v201708/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201611/activity_group_service/__init__.py rename to examples/dfp/v201708/activity_group_service/__init__.py diff --git a/examples/dfp/v201611/activity_group_service/create_activity_groups.py b/examples/dfp/v201708/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201611/activity_group_service/create_activity_groups.py rename to examples/dfp/v201708/activity_group_service/create_activity_groups.py index b3b69d40..88ab5d56 100755 --- a/examples/dfp/v201611/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201708/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201611') + version='v201708') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py similarity index 97% rename from examples/dfp/v201611/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201708/activity_group_service/get_active_activity_groups.py index c6dd6db3..25819435 100755 --- a/examples/dfp/v201611/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201611') + 'ActivityGroupService', version='v201708') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201708/activity_group_service/get_all_activity_groups.py similarity index 97% rename from examples/dfp/v201611/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201708/activity_group_service/get_all_activity_groups.py index f5cec62a..0f62b15d 100755 --- a/examples/dfp/v201611/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201708/activity_group_service/get_all_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201611') + 'ActivityGroupService', version='v201708') # Create a statement to select activity groups. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/activity_group_service/update_activity_groups.py b/examples/dfp/v201708/activity_group_service/update_activity_groups.py similarity index 97% rename from examples/dfp/v201611/activity_group_service/update_activity_groups.py rename to examples/dfp/v201708/activity_group_service/update_activity_groups.py index fcd31d25..b7b26734 100755 --- a/examples/dfp/v201611/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201708/activity_group_service/update_activity_groups.py @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201611') + version='v201708') # Create statement object to select a single activity groups by ID. values = [{ diff --git a/examples/dfp/v201611/activity_service/__init__.py b/examples/dfp/v201708/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201611/activity_service/__init__.py rename to examples/dfp/v201708/activity_service/__init__.py diff --git a/examples/dfp/v201611/activity_service/create_activities.py b/examples/dfp/v201708/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201611/activity_service/create_activities.py rename to examples/dfp/v201708/activity_service/create_activities.py index 5d88d43c..445d68a1 100755 --- a/examples/dfp/v201611/activity_service/create_activities.py +++ b/examples/dfp/v201708/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201611') + activity_service = client.GetService('ActivityService', version='v201708') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201611/activity_service/get_active_activities.py b/examples/dfp/v201708/activity_service/get_active_activities.py similarity index 99% rename from examples/dfp/v201611/activity_service/get_active_activities.py rename to examples/dfp/v201708/activity_service/get_active_activities.py index 45cf581f..fb1479c8 100755 --- a/examples/dfp/v201611/activity_service/get_active_activities.py +++ b/examples/dfp/v201708/activity_service/get_active_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201611') + activity_service = client.GetService('ActivityService', version='v201708') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201611/activity_service/get_all_activities.py b/examples/dfp/v201708/activity_service/get_all_activities.py similarity index 99% rename from examples/dfp/v201611/activity_service/get_all_activities.py rename to examples/dfp/v201708/activity_service/get_all_activities.py index 1efa1c37..004a61cb 100755 --- a/examples/dfp/v201611/activity_service/get_all_activities.py +++ b/examples/dfp/v201708/activity_service/get_all_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201611') + activity_service = client.GetService('ActivityService', version='v201708') # Create a statement to select activities. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/activity_service/update_activities.py b/examples/dfp/v201708/activity_service/update_activities.py similarity index 99% rename from examples/dfp/v201611/activity_service/update_activities.py rename to examples/dfp/v201708/activity_service/update_activities.py index dbcaecf8..9fab0a5f 100755 --- a/examples/dfp/v201611/activity_service/update_activities.py +++ b/examples/dfp/v201708/activity_service/update_activities.py @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201611') + activity_service = client.GetService('ActivityService', version='v201708') # Create statement object to select one activity by ID to update. values = [{ diff --git a/examples/dfp/v201611/audience_segment_service/__init__.py b/examples/dfp/v201708/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201611/audience_segment_service/__init__.py rename to examples/dfp/v201708/audience_segment_service/__init__.py diff --git a/examples/dfp/v201611/audience_segment_service/create_audience_segments.py b/examples/dfp/v201708/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/dfp/v201611/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201708/audience_segment_service/create_audience_segments.py index 1cd66b3c..6c43175a 100755 --- a/examples/dfp/v201611/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201611') - network_service = client.GetService('NetworkService', version='v201611') + 'AudienceSegmentService', version='v201708') + network_service = client.GetService('NetworkService', version='v201708') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201708/audience_segment_service/get_all_audience_segments.py similarity index 97% rename from examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201708/audience_segment_service/get_all_audience_segments.py index dd26b060..95f5cff5 100755 --- a/examples/dfp/v201611/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/get_all_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201611') + 'AudienceSegmentService', version='v201708') # Create a statement to select audience segments. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py similarity index 97% rename from examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py index b7e7b758..12e3fc76 100755 --- a/examples/dfp/v201611/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201611') + 'AudienceSegmentService', version='v201708') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py similarity index 97% rename from examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py index 2573fcd5..affc42f5 100755 --- a/examples/dfp/v201611/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py @@ -30,7 +30,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201611') + 'AudienceSegmentService', version='v201708') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201611/audience_segment_service/update_audience_segments.py b/examples/dfp/v201708/audience_segment_service/update_audience_segments.py similarity index 98% rename from examples/dfp/v201611/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201708/audience_segment_service/update_audience_segments.py index d358095f..4e697e4e 100755 --- a/examples/dfp/v201611/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/update_audience_segments.py @@ -29,7 +29,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201611') + 'AudienceSegmentService', version='v201708') # Create statement object to get the specified first party audience segment. values = ( diff --git a/examples/dfp/v201611/base_rate_service/__init__.py b/examples/dfp/v201708/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201611/base_rate_service/__init__.py rename to examples/dfp/v201708/base_rate_service/__init__.py diff --git a/examples/dfp/v201611/base_rate_service/create_product_base_rates.py b/examples/dfp/v201708/base_rate_service/create_product_base_rates.py similarity index 89% rename from examples/dfp/v201611/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201708/base_rate_service/create_product_base_rates.py index 3a97e258..1381e5e3 100755 --- a/examples/dfp/v201611/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201708/base_rate_service/create_product_base_rates.py @@ -31,12 +31,14 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201611') + 'BaseRateService', version='v201708') # Create a product base rate. product_base_rate = { 'xsi_type': 'ProductBaseRate', + # Set the rate card ID that the product base rate belongs to. 'rateCardId': rate_card_id, + # Set the product id the base rate will be applied to. 'productId': product_id, # Set the rate to be $2. 'rate': { @@ -45,7 +47,7 @@ def main(client, product_id, rate_card_id): } } - # Create base rates on the server. + # Create the product base rate on the server. base_rates = base_rate_service.createBaseRates( [product_base_rate]) diff --git a/examples/dfp/v201708/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201708/base_rate_service/create_product_package_item_base_rates.py new file mode 100755 index 00000000..48fb04e6 --- /dev/null +++ b/examples/dfp/v201708/base_rate_service/create_product_package_item_base_rates.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a product package item base rate. + +To determine which base rates exist, run get_all_base_rates.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the rate card ID to add the base rate to. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + +# Set the product package item to apply this base rate to. +PRODUCT_PACKAGE_ITEM_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201708') + + # Create a base rate for a product package item. + product_package_item_base_rate = { + 'xsi_type': 'ProductPackageItemBaseRate', + # Set the rate card ID that the product package item base rate + # belongs to. + 'rateCardId': RATE_CARD_ID, + # Set the product package item the base rate will be applied to. + 'productPackageItemId': PRODUCT_PACKAGE_ITEM_ID, + # Create a rate worth $2 USD and set that on the product package item + # base rate. + 'rate': { + 'xsi_type': 'Money', + 'currencyCode': 'USD', + 'microAmount': 2000000, + } + } + + # Create the product package item base rate on the server. + result = base_rate_service.createBaseRates([product_package_item_base_rate]) + + for new_base_rate in result: + print ('A product package item base rate with ID %d and rate %f %s ' + 'was created.' % (new_base_rate['id'], + new_base_rate['microAmount'], + new_base_rate['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201708/base_rate_service/create_product_template_base_rates.py similarity index 88% rename from examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201708/base_rate_service/create_product_template_base_rates.py index a8d974ab..47c7ac5d 100755 --- a/examples/dfp/v201611/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201708/base_rate_service/create_product_template_base_rates.py @@ -31,12 +31,14 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201611') + 'BaseRateService', version='v201708') # Create a product template base rate. product_template_base_rate = { 'xsi_type': 'ProductTemplateBaseRate', + # Set the rate card ID that the product template base rate belongs to. 'rateCardId': rate_card_id, + # Set the product template the base rate will be applied to. 'productTemplateId': product_template_id, # Set the rate to be $2. 'rate': { @@ -45,7 +47,7 @@ def main(client, product_template_id, rate_card_id): } } - # Create base rates on the server. + # Create the product template item base rate on the server. base_rates = base_rate_service.createBaseRates( [product_template_base_rate]) diff --git a/examples/dfp/v201611/base_rate_service/get_all_base_rates.py b/examples/dfp/v201708/base_rate_service/get_all_base_rates.py similarity index 99% rename from examples/dfp/v201611/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201708/base_rate_service/get_all_base_rates.py index e0d87151..fd54eae1 100755 --- a/examples/dfp/v201611/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201708/base_rate_service/get_all_base_rates.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201611') + base_rate_service = client.GetService('BaseRateService', version='v201708') # Create a statement to select base rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py similarity index 99% rename from examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py rename to examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py index 6601eb10..944b1f69 100755 --- a/examples/dfp/v201611/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py @@ -24,7 +24,7 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201611') + base_rate_service = client.GetService('BaseRateService', version='v201708') query = 'WHERE rateCardId = :rateCardId' values = [ {'key': 'rateCardId', diff --git a/examples/dfp/v201611/base_rate_service/update_base_rates.py b/examples/dfp/v201708/base_rate_service/update_base_rates.py similarity index 99% rename from examples/dfp/v201611/base_rate_service/update_base_rates.py rename to examples/dfp/v201708/base_rate_service/update_base_rates.py index 9f287260..cca97a1f 100755 --- a/examples/dfp/v201611/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201708/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201611') + base_rate_service = client.GetService('BaseRateService', version='v201708') # Create a filter statement for base rates for a single rate card. values = [{ diff --git a/examples/dfp/v201611/company_service/__init__.py b/examples/dfp/v201708/company_service/__init__.py similarity index 100% rename from examples/dfp/v201611/company_service/__init__.py rename to examples/dfp/v201708/company_service/__init__.py diff --git a/examples/dfp/v201611/company_service/create_companies.py b/examples/dfp/v201708/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201611/company_service/create_companies.py rename to examples/dfp/v201708/company_service/create_companies.py index 1f461e28..2bf4d295 100755 --- a/examples/dfp/v201611/company_service/create_companies.py +++ b/examples/dfp/v201708/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201611') + company_service = client.GetService('CompanyService', version='v201708') # Create company objects. companies = [ diff --git a/examples/dfp/v201611/company_service/get_advertisers.py b/examples/dfp/v201708/company_service/get_advertisers.py similarity index 99% rename from examples/dfp/v201611/company_service/get_advertisers.py rename to examples/dfp/v201708/company_service/get_advertisers.py index 6d651cec..4f32da18 100755 --- a/examples/dfp/v201611/company_service/get_advertisers.py +++ b/examples/dfp/v201708/company_service/get_advertisers.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201611') + company_service = client.GetService('CompanyService', version='v201708') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201611/company_service/get_all_companies.py b/examples/dfp/v201708/company_service/get_all_companies.py similarity index 99% rename from examples/dfp/v201611/company_service/get_all_companies.py rename to examples/dfp/v201708/company_service/get_all_companies.py index 2b2722cf..31598c8a 100755 --- a/examples/dfp/v201611/company_service/get_all_companies.py +++ b/examples/dfp/v201708/company_service/get_all_companies.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201611') + company_service = client.GetService('CompanyService', version='v201708') # Create a statement to select companies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/company_service/update_companies.py b/examples/dfp/v201708/company_service/update_companies.py similarity index 99% rename from examples/dfp/v201611/company_service/update_companies.py rename to examples/dfp/v201708/company_service/update_companies.py index 09b656fb..d4678799 100755 --- a/examples/dfp/v201611/company_service/update_companies.py +++ b/examples/dfp/v201708/company_service/update_companies.py @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201611') + company_service = client.GetService('CompanyService', version='v201708') # Create statement object to only select a single company by ID. values = [{ diff --git a/examples/dfp/v201611/contact_service/__init__.py b/examples/dfp/v201708/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201611/contact_service/__init__.py rename to examples/dfp/v201708/contact_service/__init__.py diff --git a/examples/dfp/v201611/contact_service/create_contacts.py b/examples/dfp/v201708/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201611/contact_service/create_contacts.py rename to examples/dfp/v201708/contact_service/create_contacts.py index 7494c277..feb24480 100755 --- a/examples/dfp/v201611/contact_service/create_contacts.py +++ b/examples/dfp/v201708/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201611') + contact_service = client.GetService('ContactService', version='v201708') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201611/contact_service/get_all_contacts.py b/examples/dfp/v201708/contact_service/get_all_contacts.py similarity index 99% rename from examples/dfp/v201611/contact_service/get_all_contacts.py rename to examples/dfp/v201708/contact_service/get_all_contacts.py index a9f5b5cc..0b3d94ef 100755 --- a/examples/dfp/v201611/contact_service/get_all_contacts.py +++ b/examples/dfp/v201708/contact_service/get_all_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201611') + contact_service = client.GetService('ContactService', version='v201708') # Create a statement to select contacts. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/contact_service/get_uninvited_contacts.py b/examples/dfp/v201708/contact_service/get_uninvited_contacts.py similarity index 99% rename from examples/dfp/v201611/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201708/contact_service/get_uninvited_contacts.py index 8d84ca0c..730aaa96 100755 --- a/examples/dfp/v201611/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201708/contact_service/get_uninvited_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201611') + contact_service = client.GetService('ContactService', version='v201708') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201611/contact_service/update_contacts.py b/examples/dfp/v201708/contact_service/update_contacts.py similarity index 99% rename from examples/dfp/v201611/contact_service/update_contacts.py rename to examples/dfp/v201708/contact_service/update_contacts.py index a50efb09..b98d25f1 100755 --- a/examples/dfp/v201611/contact_service/update_contacts.py +++ b/examples/dfp/v201708/contact_service/update_contacts.py @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201611') + contact_service = client.GetService('ContactService', version='v201708') # Create statement object to select the single contact by ID. values = [{ diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201611/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201708/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201708/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index a4083936..4b45d9a1 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201708/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201611') + 'ContentMetadataKeyHierarchyService', version='v201708') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index cf56c087..95899906 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,7 +40,7 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201611') + 'ContentMetadataKeyHierarchyService', version='v201708') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201708/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index ce3f01fc..3b5c748e 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201708/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201611') + 'ContentMetadataKeyHierarchyService', version='v201708') # Create a statement to select content metadata key hierarchies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 98% rename from examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index d34e26c0..e276a2d6 100755 --- a/examples/dfp/v201611/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201611') + 'ContentMetadataKeyHierarchyService', version='v201708') # Create a query to select a single content metadata key hierarchy. values = [{ diff --git a/examples/dfp/v201611/content_service/__init__.py b/examples/dfp/v201708/content_service/__init__.py similarity index 100% rename from examples/dfp/v201611/content_service/__init__.py rename to examples/dfp/v201708/content_service/__init__.py diff --git a/examples/dfp/v201611/content_service/get_all_content.py b/examples/dfp/v201708/content_service/get_all_content.py similarity index 99% rename from examples/dfp/v201611/content_service/get_all_content.py rename to examples/dfp/v201708/content_service/get_all_content.py index f3f4dc8d..b1d79f11 100755 --- a/examples/dfp/v201611/content_service/get_all_content.py +++ b/examples/dfp/v201708/content_service/get_all_content.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201611') + content_service = client.GetService('ContentService', version='v201708') # Create a statement to select content. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/creative_service/__init__.py b/examples/dfp/v201708/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201611/creative_service/__init__.py rename to examples/dfp/v201708/creative_service/__init__.py diff --git a/examples/dfp/v201708/creative_service/copy_image_creatives.py b/examples/dfp/v201708/creative_service/copy_image_creatives.py new file mode 100755 index 00000000..2075602c --- /dev/null +++ b/examples/dfp/v201708/creative_service/copy_image_creatives.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a copy of an image creative. + +To determine which image creatives exist, run get_image_creatives.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201708') + + # Create a statement to get the image creative. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', CREATIVE_ID)) + + # Get the creative. + query_result = creative_service.getCreativesByStatement( + statement.ToStatement()) + + image_creative = query_result['results'][0] + + # Build the new creative, set id to None to create a copy. + image_creative['id'] = None + image_creative['name'] = 'Copy of %s' % image_creative['name'] + + result = creative_service.createCreatives([image_creative])[0] + print ('A creative with ID %d, name "%s", and type "%s" was created and ' + 'can be previewed at: %s' % (result['id'], + result['name'], + dfp.DfpClassType(result), + result['previewUrl'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/creative_service/create_creative_from_template.py b/examples/dfp/v201708/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201611/creative_service/create_creative_from_template.py rename to examples/dfp/v201708/creative_service/create_creative_from_template.py index d97dff5e..6e5cd544 100755 --- a/examples/dfp/v201611/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201708/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201611') + creative_service = client.GetService('CreativeService', version='v201708') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201611/creative_service/create_creatives.py b/examples/dfp/v201708/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201611/creative_service/create_creatives.py rename to examples/dfp/v201708/creative_service/create_creatives.py index ff4ee4c1..6514ff8a 100755 --- a/examples/dfp/v201611/creative_service/create_creatives.py +++ b/examples/dfp/v201708/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201611') + creative_service = client.GetService('CreativeService', version='v201708') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201611/creative_service/create_custom_creative.py b/examples/dfp/v201708/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201611/creative_service/create_custom_creative.py rename to examples/dfp/v201708/creative_service/create_custom_creative.py index 145e0411..d62d27cb 100755 --- a/examples/dfp/v201611/creative_service/create_custom_creative.py +++ b/examples/dfp/v201708/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201611') + creative_service = client.GetService('CreativeService', version='v201708') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201611/creative_service/create_native_creative.py b/examples/dfp/v201708/creative_service/create_native_creative.py similarity index 99% rename from examples/dfp/v201611/creative_service/create_native_creative.py rename to examples/dfp/v201708/creative_service/create_native_creative.py index cc31907f..c92e4926 100755 --- a/examples/dfp/v201611/creative_service/create_native_creative.py +++ b/examples/dfp/v201708/creative_service/create_native_creative.py @@ -46,7 +46,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201611') + creative_service = client.GetService('CreativeService', version='v201708') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/dfp/v201611/creative_service/get_all_creatives.py b/examples/dfp/v201708/creative_service/get_all_creatives.py similarity index 99% rename from examples/dfp/v201611/creative_service/get_all_creatives.py rename to examples/dfp/v201708/creative_service/get_all_creatives.py index 33041108..1feeb89e 100755 --- a/examples/dfp/v201611/creative_service/get_all_creatives.py +++ b/examples/dfp/v201708/creative_service/get_all_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201611') + creative_service = client.GetService('CreativeService', version='v201708') # Create a statement to select creatives. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/creative_service/get_image_creatives.py b/examples/dfp/v201708/creative_service/get_image_creatives.py similarity index 99% rename from examples/dfp/v201611/creative_service/get_image_creatives.py rename to examples/dfp/v201708/creative_service/get_image_creatives.py index 7e628eaf..a90f06bf 100755 --- a/examples/dfp/v201611/creative_service/get_image_creatives.py +++ b/examples/dfp/v201708/creative_service/get_image_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201611') + creative_service = client.GetService('CreativeService', version='v201708') query = 'WHERE creativeType = :creativeType' values = [ {'key': 'creativeType', diff --git a/examples/dfp/v201611/creative_service/update_creatives.py b/examples/dfp/v201708/creative_service/update_creatives.py similarity index 99% rename from examples/dfp/v201611/creative_service/update_creatives.py rename to examples/dfp/v201708/creative_service/update_creatives.py index 69e8330e..15b95828 100755 --- a/examples/dfp/v201611/creative_service/update_creatives.py +++ b/examples/dfp/v201708/creative_service/update_creatives.py @@ -34,7 +34,7 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201611') + creative_service = client.GetService('CreativeService', version='v201708') # Create statement object to get all image creatives. values = [{ diff --git a/examples/dfp/v201611/creative_set_service/__init__.py b/examples/dfp/v201708/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201611/creative_set_service/__init__.py rename to examples/dfp/v201708/creative_set_service/__init__.py diff --git a/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201708/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201708/creative_set_service/associate_creative_set_to_line_item.py index d3961e66..7d82f843 100755 --- a/examples/dfp/v201611/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201708/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201611') + 'LineItemCreativeAssociationService', version='v201708') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201611/creative_set_service/create_creative_set.py b/examples/dfp/v201708/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201611/creative_set_service/create_creative_set.py rename to examples/dfp/v201708/creative_set_service/create_creative_set.py index 2545bfbc..42c3e30d 100755 --- a/examples/dfp/v201611/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201708/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201611') + version='v201708') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201708/creative_set_service/get_all_creative_sets.py similarity index 97% rename from examples/dfp/v201611/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201708/creative_set_service/get_all_creative_sets.py index 916bc1fb..b725512a 100755 --- a/examples/dfp/v201611/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201708/creative_set_service/get_all_creative_sets.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201611') + 'CreativeSetService', version='v201708') # Create a statement to select creative sets. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py similarity index 97% rename from examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py index c8b6e7b3..5b313769 100755 --- a/examples/dfp/v201611/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,7 +25,7 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201611') + 'CreativeSetService', version='v201708') query = 'WHERE masterCreativeId = :masterCreativeId' values = [ {'key': 'masterCreativeId', diff --git a/examples/dfp/v201611/creative_set_service/update_creative_set.py b/examples/dfp/v201708/creative_set_service/update_creative_set.py similarity index 97% rename from examples/dfp/v201611/creative_set_service/update_creative_set.py rename to examples/dfp/v201708/creative_set_service/update_creative_set.py index 049d6dfd..8c2edd8c 100755 --- a/examples/dfp/v201611/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201708/creative_set_service/update_creative_set.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201611') + version='v201708') # Create statement to select a single creative set by ID. values = [{ diff --git a/examples/dfp/v201611/creative_template_service/__init__.py b/examples/dfp/v201708/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201611/creative_template_service/__init__.py rename to examples/dfp/v201708/creative_template_service/__init__.py diff --git a/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201708/creative_template_service/get_all_creative_templates.py similarity index 97% rename from examples/dfp/v201611/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201708/creative_template_service/get_all_creative_templates.py index 319d4f06..afa32653 100755 --- a/examples/dfp/v201611/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201708/creative_template_service/get_all_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201611') + 'CreativeTemplateService', version='v201708') # Create a statement to select creative templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py similarity index 97% rename from examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py rename to examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py index d8ec1221..6148b764 100755 --- a/examples/dfp/v201611/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201611') + 'CreativeTemplateService', version='v201708') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201708/creative_wrapper_service/create_creative_wrappers.py similarity index 91% rename from examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201708/creative_wrapper_service/create_creative_wrappers.py index 34fed979..23002ace 100755 --- a/examples/dfp/v201611/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201708/creative_wrapper_service/create_creative_wrappers.py @@ -37,15 +37,15 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201611') + version='v201708') # Create creative wrapper objects. creative_wrapper = { # A label can only be associated with one creative wrapper. 'labelId': label_id, 'ordering': 'INNER', - 'header': {'htmlSnippet': 'My creative wrapper header'}, - 'footer': {'htmlSnippet': 'My creative wrapper footer'} + 'htmlHeader': 'My creative wrapper header', + 'htmlFooter': 'My creative wrapper footer' } # Add creative wrapper. diff --git a/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 97% rename from examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py index 1efb160b..47490b87 100755 --- a/examples/dfp/v201611/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201611') + version='v201708') # Create a query to select the active creative wrappers for the given label. values = [{ diff --git a/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py similarity index 97% rename from examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py index e03ad03c..a2cc780e 100755 --- a/examples/dfp/v201611/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201611') + 'CreativeWrapperService', version='v201708') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201708/creative_wrapper_service/get_all_creative_wrappers.py similarity index 97% rename from examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201708/creative_wrapper_service/get_all_creative_wrappers.py index 47413e35..5ac7fd17 100755 --- a/examples/dfp/v201611/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201708/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201611') + 'CreativeWrapperService', version='v201708') # Create a statement to select creative wrappers. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py similarity index 97% rename from examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py index a2218d92..f387dea1 100755 --- a/examples/dfp/v201611/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201611') + version='v201708') # Create statement to get a creative wrapper by ID. values = [{ diff --git a/examples/dfp/v201611/custom_field_service/__init__.py b/examples/dfp/v201708/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201611/custom_field_service/__init__.py rename to examples/dfp/v201708/custom_field_service/__init__.py diff --git a/examples/dfp/v201611/custom_field_service/create_custom_field_options.py b/examples/dfp/v201708/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201611/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201708/custom_field_service/create_custom_field_options.py index f772f6e8..f8c86710 100755 --- a/examples/dfp/v201611/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201708/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201611') + 'CustomFieldService', version='v201708') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201611/custom_field_service/create_custom_fields.py b/examples/dfp/v201708/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201611/custom_field_service/create_custom_fields.py rename to examples/dfp/v201708/custom_field_service/create_custom_fields.py index 559fdea8..ff120365 100755 --- a/examples/dfp/v201611/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201708/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201611') + 'CustomFieldService', version='v201708') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 98% rename from examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py index 20491ecc..acb693c7 100755 --- a/examples/dfp/v201611/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201611') + 'CustomFieldService', version='v201708') # Create statement to select only active custom fields that apply to # line items. diff --git a/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201708/custom_field_service/get_all_custom_fields.py similarity index 97% rename from examples/dfp/v201611/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201708/custom_field_service/get_all_custom_fields.py index ee5cea0a..c0442894 100755 --- a/examples/dfp/v201611/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201708/custom_field_service/get_all_custom_fields.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201611') + 'CustomFieldService', version='v201708') # Create a statement to select custom fields. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py similarity index 97% rename from examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py rename to examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py index 3619465e..f02cf122 100755 --- a/examples/dfp/v201611/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201611') + 'CustomFieldService', version='v201708') query = 'WHERE entityType = :entityType' values = [ {'key': 'entityType', diff --git a/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201708/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201708/custom_field_service/set_line_item_custom_field_value.py index f90cca51..ca7affe8 100755 --- a/examples/dfp/v201611/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201708/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201611') + 'CustomFieldService', version='v201708') - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201611/custom_field_service/update_custom_fields.py b/examples/dfp/v201708/custom_field_service/update_custom_fields.py similarity index 98% rename from examples/dfp/v201611/custom_field_service/update_custom_fields.py rename to examples/dfp/v201708/custom_field_service/update_custom_fields.py index c78deedc..72d95b25 100755 --- a/examples/dfp/v201611/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201708/custom_field_service/update_custom_fields.py @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201611') + 'CustomFieldService', version='v201708') # Create statement to get a custom field. values = [{ diff --git a/examples/dfp/v201611/custom_targeting_service/__init__.py b/examples/dfp/v201708/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201611/custom_targeting_service/__init__.py rename to examples/dfp/v201708/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201708/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201708/custom_targeting_service/create_custom_targeting_keys_and_values.py index eda7d5f2..5f064369 100755 --- a/examples/dfp/v201611/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201708/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201611') + 'CustomTargetingService', version='v201708') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py similarity index 98% rename from examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py index f0a506ad..469439f3 100755 --- a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201611') + 'CustomTargetingService', version='v201708') values = [{ 'key': 'name', diff --git a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_values.py similarity index 98% rename from examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_values.py index 04741b86..b62d564e 100755 --- a/examples/dfp/v201611/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_values.py @@ -36,7 +36,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201611') + 'CustomTargetingService', version='v201708') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201708/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201708/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 10da9eec..7d9d8478 100755 --- a/examples/dfp/v201611/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201708/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201611') + 'CustomTargetingService', version='v201708') # Create statement to get all targeting keys. targeting_key_statement = dfp.StatementBuilder() @@ -46,7 +46,7 @@ def main(client): ', '.join([str(key['id']) for key in all_keys])) statement = dfp.FilterStatement(query) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( diff --git a/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 96% rename from examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index eb30a6c4..092568ea 100755 --- a/examples/dfp/v201611/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201611') + 'CustomTargetingService', version='v201708') # Create statement to get targeting keys for predefined values. query = ('WHERE type = :type') @@ -54,7 +54,7 @@ def main(client): ', '.join([str(key['id']) for key in all_keys])) statement = dfp.FilterStatement(query) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py similarity index 97% rename from examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py index 901d2d45..e8716202 100755 --- a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201611') + 'CustomTargetingService', version='v201708') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py similarity index 97% rename from examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py index c6c9dbdf..63e365e5 100755 --- a/examples/dfp/v201611/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201611') + 'CustomTargetingService', version='v201708') values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201611/exchange_rate_service/__init__.py b/examples/dfp/v201708/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201611/exchange_rate_service/__init__.py rename to examples/dfp/v201708/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201708/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201708/exchange_rate_service/create_exchange_rates.py index 8c01eea9..7753ab93 100755 --- a/examples/dfp/v201611/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201708/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201611') + version='v201708') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201708/exchange_rate_service/get_all_exchange_rates.py similarity index 97% rename from examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201708/exchange_rate_service/get_all_exchange_rates.py index 4441723e..21075009 100755 --- a/examples/dfp/v201611/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201708/exchange_rate_service/get_all_exchange_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201611') + 'ExchangeRateService', version='v201708') # Create a statement to select exchange rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 97% rename from examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py index 15d04ceb..bf5f03b6 100755 --- a/examples/dfp/v201611/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,7 +25,7 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201611') + 'ExchangeRateService', version='v201708') query = 'WHERE currencyCode = :currencyCode' values = [ {'key': 'currencyCode', diff --git a/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py similarity index 97% rename from examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py index 438e9245..62331fae 100755 --- a/examples/dfp/v201611/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201611') + version='v201708') # Create a statement to get an exchange rate by its ID. values = [{ diff --git a/examples/dfp/v201611/forecast_service/get_availability_forecast.py b/examples/dfp/v201708/forecast_service/get_availability_forecast.py similarity index 92% rename from examples/dfp/v201611/forecast_service/get_availability_forecast.py rename to examples/dfp/v201708/forecast_service/get_availability_forecast.py index c3f2d621..f502aade 100755 --- a/examples/dfp/v201611/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201708/forecast_service/get_availability_forecast.py @@ -24,10 +24,11 @@ """ -from datetime import date +import datetime # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set the ID of the advertiser (company) to forecast for. Setting an advertiser # will cause the forecast to apply the appropriate unified blocking rules. @@ -36,12 +37,15 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201611') - network_service = client.GetService('NetworkService', version='v201611') + forecast_service = client.GetService('ForecastService', version='v201708') + network_service = client.GetService('NetworkService', version='v201708') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=30) + # Create prospective line item. line_item = { 'targeting': { @@ -70,17 +74,7 @@ def main(client, advertiser_id): ], 'lineItemType': 'SPONSORSHIP', 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/New_York' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py index d929dd42..ba38ebc0 100755 --- a/examples/dfp/v201611/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201611') + forecast_service = client.GetService('ForecastService', version='v201708') # Set forecasting options. forecast_options = { diff --git a/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201708/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201708/forecast_service/get_delivery_forecast_for_line_items.py index b0b87c5f..3d4b8a2b 100755 --- a/examples/dfp/v201611/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201708/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201611') + forecast_service = client.GetService('ForecastService', version='v201708') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201611/inventory_service/__init__.py b/examples/dfp/v201708/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201611/inventory_service/__init__.py rename to examples/dfp/v201708/inventory_service/__init__.py diff --git a/examples/dfp/v201611/inventory_service/archive_ad_units.py b/examples/dfp/v201708/inventory_service/archive_ad_units.py similarity index 99% rename from examples/dfp/v201611/inventory_service/archive_ad_units.py rename to examples/dfp/v201708/inventory_service/archive_ad_units.py index 768205c0..b64b0a36 100755 --- a/examples/dfp/v201611/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201708/inventory_service/archive_ad_units.py @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201611') + inventory_service = client.GetService('InventoryService', version='v201708') # Create a query to select ad units under the parent ad unit and the parent ad # unit. diff --git a/examples/dfp/v201611/inventory_service/create_ad_units.py b/examples/dfp/v201708/inventory_service/create_ad_units.py similarity index 99% rename from examples/dfp/v201611/inventory_service/create_ad_units.py rename to examples/dfp/v201708/inventory_service/create_ad_units.py index 25a9eed9..18a012be 100755 --- a/examples/dfp/v201611/inventory_service/create_ad_units.py +++ b/examples/dfp/v201708/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201611') + inventory_service = client.GetService('InventoryService', version='v201708') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201708/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201708/inventory_service/get_all_ad_unit_sizes.py index f792276c..78fcd659 100755 --- a/examples/dfp/v201611/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201708/inventory_service/get_all_ad_unit_sizes.py @@ -23,12 +23,12 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201611') + 'InventoryService', version='v201708') # Create a statement to select ad unit sizes. statement = dfp.FilterStatement() - # Retreive a small amount of ad unit sizes at a time, paging + # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. response = ad_unit_size_service.getAdUnitSizesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201611/inventory_service/get_all_ad_units.py b/examples/dfp/v201708/inventory_service/get_all_ad_units.py similarity index 99% rename from examples/dfp/v201611/inventory_service/get_all_ad_units.py rename to examples/dfp/v201708/inventory_service/get_all_ad_units.py index 1b03c653..cb5aba78 100755 --- a/examples/dfp/v201611/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201708/inventory_service/get_all_ad_units.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201611') + ad_unit_service = client.GetService('InventoryService', version='v201708') # Create a statement to select ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/inventory_service/update_ad_units.py b/examples/dfp/v201708/inventory_service/update_ad_units.py similarity index 99% rename from examples/dfp/v201611/inventory_service/update_ad_units.py rename to examples/dfp/v201708/inventory_service/update_ad_units.py index 998d21f7..7dec87a9 100755 --- a/examples/dfp/v201611/inventory_service/update_ad_units.py +++ b/examples/dfp/v201708/inventory_service/update_ad_units.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201611') + inventory_service = client.GetService('InventoryService', version='v201708') # Create a statement to select a single ad unit by ID. values = [{ diff --git a/examples/dfp/v201611/label_service/__init__.py b/examples/dfp/v201708/label_service/__init__.py similarity index 100% rename from examples/dfp/v201611/label_service/__init__.py rename to examples/dfp/v201708/label_service/__init__.py diff --git a/examples/dfp/v201611/label_service/create_labels.py b/examples/dfp/v201708/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201611/label_service/create_labels.py rename to examples/dfp/v201708/label_service/create_labels.py index 712d78af..7ca9f6ea 100755 --- a/examples/dfp/v201611/label_service/create_labels.py +++ b/examples/dfp/v201708/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201611') + label_service = client.GetService('LabelService', version='v201708') # Create label objects. labels = [] diff --git a/examples/dfp/v201611/label_service/deactivate_labels.py b/examples/dfp/v201708/label_service/deactivate_labels.py similarity index 99% rename from examples/dfp/v201611/label_service/deactivate_labels.py rename to examples/dfp/v201708/label_service/deactivate_labels.py index cb5eb853..2af49168 100755 --- a/examples/dfp/v201611/label_service/deactivate_labels.py +++ b/examples/dfp/v201708/label_service/deactivate_labels.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201611') + label_service = client.GetService('LabelService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/label_service/get_active_labels.py b/examples/dfp/v201708/label_service/get_active_labels.py similarity index 99% rename from examples/dfp/v201611/label_service/get_active_labels.py rename to examples/dfp/v201708/label_service/get_active_labels.py index 6783a30b..415672a7 100755 --- a/examples/dfp/v201611/label_service/get_active_labels.py +++ b/examples/dfp/v201708/label_service/get_active_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201611') + label_service = client.GetService('LabelService', version='v201708') query = 'WHERE isActive = :isActive' values = [ {'key': 'isActive', diff --git a/examples/dfp/v201611/label_service/get_all_labels.py b/examples/dfp/v201708/label_service/get_all_labels.py similarity index 99% rename from examples/dfp/v201611/label_service/get_all_labels.py rename to examples/dfp/v201708/label_service/get_all_labels.py index 31e84da7..ddfb7b83 100755 --- a/examples/dfp/v201611/label_service/get_all_labels.py +++ b/examples/dfp/v201708/label_service/get_all_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201611') + label_service = client.GetService('LabelService', version='v201708') # Create a statement to select labels. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/label_service/update_labels.py b/examples/dfp/v201708/label_service/update_labels.py similarity index 99% rename from examples/dfp/v201611/label_service/update_labels.py rename to examples/dfp/v201708/label_service/update_labels.py index 58d26a94..bccf95a7 100755 --- a/examples/dfp/v201611/label_service/update_labels.py +++ b/examples/dfp/v201708/label_service/update_labels.py @@ -29,7 +29,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201611') + label_service = client.GetService('LabelService', version='v201708') # Create a statement to select only active labels. values = [ diff --git a/examples/dfp/v201611/line_item_creative_association_service/__init__.py b/examples/dfp/v201708/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201611/line_item_creative_association_service/__init__.py rename to examples/dfp/v201708/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201611/line_item_creative_association_service/create_licas.py b/examples/dfp/v201708/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201611/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201708/line_item_creative_association_service/create_licas.py index 51cbb180..1d53af3f 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201708/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201611') + 'LineItemCreativeAssociationService', version='v201708') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py similarity index 97% rename from examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py index 69c2f654..0b13f4bf 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201611') + 'LineItemCreativeAssociationService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201708/line_item_creative_association_service/get_all_licas.py similarity index 97% rename from examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201708/line_item_creative_association_service/get_all_licas.py index a2c24e44..3fc04519 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201708/line_item_creative_association_service/get_all_licas.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201611') + 'LineItemCreativeAssociationService', version='v201708') # Create a statement to select line item creative associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py similarity index 97% rename from examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py index b5825ad3..15eb13a8 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,7 +25,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201611') + 'LineItemCreativeAssociationService', version='v201708') query = 'WHERE lineItemId = :lineItemId' values = [ {'key': 'lineItemId', diff --git a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py b/examples/dfp/v201708/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201611/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201708/line_item_creative_association_service/update_licas.py index ab035121..1e59bd1b 100755 --- a/examples/dfp/v201611/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201708/line_item_creative_association_service/update_licas.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201611') + 'LineItemCreativeAssociationService', version='v201708') # Create statement object to get all LICAs. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/line_item_service/__init__.py b/examples/dfp/v201708/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201611/line_item_service/__init__.py rename to examples/dfp/v201708/line_item_service/__init__.py diff --git a/examples/dfp/v201611/line_item_service/activate_line_items.py b/examples/dfp/v201708/line_item_service/activate_line_items.py similarity index 99% rename from examples/dfp/v201611/line_item_service/activate_line_items.py rename to examples/dfp/v201708/line_item_service/activate_line_items.py index 79f98c2c..0cc56b63 100755 --- a/examples/dfp/v201611/line_item_service/activate_line_items.py +++ b/examples/dfp/v201708/line_item_service/activate_line_items.py @@ -33,7 +33,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/line_item_service/create_line_items.py b/examples/dfp/v201708/line_item_service/create_line_items.py similarity index 93% rename from examples/dfp/v201611/line_item_service/create_line_items.py rename to examples/dfp/v201708/line_item_service/create_line_items.py index d02cc9ac..c49f8035 100755 --- a/examples/dfp/v201611/line_item_service/create_line_items.py +++ b/examples/dfp/v201708/line_item_service/create_line_items.py @@ -22,11 +22,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set order that the created line item will belong to and add the id of a # placement containing ad units to target. @@ -36,7 +37,10 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) # Create line item objects. line_items = [] @@ -128,17 +132,7 @@ def main(client, order_id, targeted_placement_ids): ], 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'STANDARD', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201611/line_item_service/create_video_line_item.py b/examples/dfp/v201708/line_item_service/create_video_line_item.py similarity index 92% rename from examples/dfp/v201611/line_item_service/create_video_line_item.py rename to examples/dfp/v201708/line_item_service/create_video_line_item.py index 0f136303..1af5df50 100755 --- a/examples/dfp/v201611/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201708/line_item_service/create_video_line_item.py @@ -24,11 +24,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set order that all created line item will belong to and the video ad unit id # to target. @@ -46,7 +47,10 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) # Create line item object. line_item = { @@ -99,17 +103,7 @@ def main(client, order_id, targeted_video_ad_unit_id, 'companionDeliveryOption': 'OPTIONAL', 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'SPONSORSHIP', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201611/line_item_service/get_all_line_items.py b/examples/dfp/v201708/line_item_service/get_all_line_items.py similarity index 99% rename from examples/dfp/v201611/line_item_service/get_all_line_items.py rename to examples/dfp/v201708/line_item_service/get_all_line_items.py index 7a606837..abf2df90 100755 --- a/examples/dfp/v201611/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201708/line_item_service/get_all_line_items.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') # Create a statement to select line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py similarity index 99% rename from examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py rename to examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py index 511926d5..1a6e2835 100755 --- a/examples/dfp/v201611/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') query = 'WHERE isMissingCreatives = :isMissingCreatives' values = [ {'key': 'isMissingCreatives', diff --git a/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py similarity index 99% rename from examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py index 09d4cc5b..39b0e992 100755 --- a/examples/dfp/v201611/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' values = [ {'key': 'lastModifiedDateTime', diff --git a/examples/dfp/v201708/line_item_service/pause_line_items.py b/examples/dfp/v201708/line_item_service/pause_line_items.py new file mode 100755 index 00000000..c7d78b61 --- /dev/null +++ b/examples/dfp/v201708/line_item_service/pause_line_items.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 pauses a line item. + +Line items must be paused before they can be updated. To determine which line +items exist, run get_all_line_items.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201708') + + # Create a statement to select the line item. + # Change this to operate on more than one Line Item. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', LINE_ITEM_ID)) + + result_set_size = 0 + should_continue = True + + # Iterate over paged results from the statement. + while should_continue: + page = line_item_service.getLineItemsByStatement(statement.ToStatement()) + if 'results' in page: + result_set_size = page['totalResultSetSize'] + # Iterate over individual results in the page. + for line_item in page['results']: + print 'Pausing line item with ID %d' % line_item['id'] + # Update statement for next page. + statement.offset += statement.limit + should_continue = statement.offset < result_set_size + + print 'Pausing %d line item(s)' % result_set_size + + if result_set_size > 0: + statement.offset = None + statement.limit = None + + # Perform Pause action on all Line Items that match the statement. + update_result = line_item_service.performLineItemAction( + {'xsi_type': 'PauseLineItems'}, statement.ToStatement()) + + if update_result and update_result['numChanges'] > 0: + print 'Updated %d line item(s)' % update_result['numChanges'] + else: + print 'No line items were paused' + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/line_item_service/target_custom_criteria.py b/examples/dfp/v201708/line_item_service/target_custom_criteria.py similarity index 99% rename from examples/dfp/v201611/line_item_service/target_custom_criteria.py rename to examples/dfp/v201708/line_item_service/target_custom_criteria.py index f52e2c09..a55368b6 100755 --- a/examples/dfp/v201611/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201708/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201611/line_item_service/update_line_items.py b/examples/dfp/v201708/line_item_service/update_line_items.py similarity index 99% rename from examples/dfp/v201611/line_item_service/update_line_items.py rename to examples/dfp/v201708/line_item_service/update_line_items.py index 7b3ae5e6..8990c58f 100755 --- a/examples/dfp/v201611/line_item_service/update_line_items.py +++ b/examples/dfp/v201708/line_item_service/update_line_items.py @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') # Create statement object to only select line items with even delivery rates. values = [{ diff --git a/examples/dfp/v201708/native_style_service/__init__.py b/examples/dfp/v201708/native_style_service/__init__.py new file mode 100755 index 00000000..473ddba1 --- /dev/null +++ b/examples/dfp/v201708/native_style_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. diff --git a/examples/dfp/v201708/native_style_service/create_native_styles.py b/examples/dfp/v201708/native_style_service/create_native_styles.py new file mode 100755 index 00000000..7f761dc6 --- /dev/null +++ b/examples/dfp/v201708/native_style_service/create_native_styles.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Creates a native app install ad.""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp + + +# This is the creative template ID for the system-defined native app install ad +# format, which we will create the native style from. Use +# CreativeTemplateService.getCreativeTemplateByStatement() and +# CreativeTemplate.isNativeEligible() to get other native ad formats available +# in your network. +CREATIVE_TEMPLATE_ID = 10004400 +WIDTH = 300 +HEIGHT = 345 + +HTML_SNIPPET = """
+ +
Ad
+
+ + + +
+
+ +
+
+ [%Body%] +
+
[%Price%]
+ +
+""" + +CSS_SNIPPET = """body { + background-color: rgba(255, 255, 255, 1); + font-family: "Roboto-Regular", sans-serif; + font-weight: normal; + font-size: 12px; + line-height: 14px; +} +.attribution { + background-color: rgba(236, 182, 0, 1); + color: rgba(255, 255, 255, 1); + font-size: 13px; + display: table; + margin: 4px 8px; + padding: 0 3px; + border-radius: 2px; +} +.image { + text-align: center; + margin: 8px; +} +.image img, +.image-link { + width: 100%; +} +.app-icon { + float: left; + margin: 0 8px 4px 8px; + height: 40px; + width: 40px; + background-color: transparent; +} +.app-icon img { + height: 100%; + width: 100%; + border-radius: 20%; +} +.title, +.promo-headline { + font-weight: bold; + font-size: 14px; + line-height: 20px; + margin: 8px 8px 4px 8px; +} +.title a, +.promo-headline { + color: rgba(112, 112, 112, 1); + text-decoration: none; +} +.reviews { + float: left; +} +.reviews svg { + fill: rgba(0, 0, 0, 0.7); +} +.body { + clear: left; + margin: 8px; +} +.body a { + color: rgba(110, 110, 110, 1); + text-decoration: none; +} +.price { + display: none; +} +.button { + font-size: 14px; + font-weight: bold; + float: right; + margin: 0px 16px 16px 0px; + white-space: nowrap; +} +.button a { + color: #2196F3; + text-decoration: none; +} +.button svg { + display: none; +} +""" + + +def main(client, html_snippet, css_snippet, creative_template_id, width, + height): + # Initialize appropriate service. + native_style_service = client.GetService('NativeStyleService', + version='v201708') + + native_style = { + 'name': 'Native style #%d' % uuid.uuid4(), + 'htmlSnippet': html_snippet, + 'cssSnippet': css_snippet, + 'creativeTemplateId': creative_template_id, + 'size': { + 'width': width, + 'height': height, + 'isAspectRatio': False + } + } + + # Create the native style on the server. + native_styles = native_style_service.createNativeStyles([native_style]) + + # Display results. + for native_style in native_styles: + print ('A Native style with ID "%s", name "%s", and creative template ID' + '"%d" was created.' % (native_style['id'], native_style['name'], + native_style['creativeTemplateId'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, WIDTH, + HEIGHT) diff --git a/examples/dfp/v201708/native_style_service/get_all_native_styles.py b/examples/dfp/v201708/native_style_service/get_all_native_styles.py new file mode 100755 index 00000000..9ecf88a5 --- /dev/null +++ b/examples/dfp/v201708/native_style_service/get_all_native_styles.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 native styles.""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + native_style_service = client.GetService('NativeStyleService', + version='v201708') + + # Create a statement to select native styles. + statement = dfp.StatementBuilder() + + # Retrieve a small amount of native styles at a time, paging + # through until all native styles have been retrieved. + while True: + response = native_style_service.getNativeStylesByStatement( + statement.ToStatement()) + if 'results' in response: + for native_style in response['results']: + # Print out some information for each native style. + print('Native style with ID "%d" and name "%s" was found.\n' % + (native_style['id'], native_style['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/network_service/__init__.py b/examples/dfp/v201708/network_service/__init__.py similarity index 100% rename from examples/dfp/v201611/network_service/__init__.py rename to examples/dfp/v201708/network_service/__init__.py diff --git a/examples/dfp/v201611/network_service/get_all_networks.py b/examples/dfp/v201708/network_service/get_all_networks.py similarity index 99% rename from examples/dfp/v201611/network_service/get_all_networks.py rename to examples/dfp/v201708/network_service/get_all_networks.py index 2b08fa46..b7ddc500 100755 --- a/examples/dfp/v201611/network_service/get_all_networks.py +++ b/examples/dfp/v201708/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201611') + network_service = client.GetService('NetworkService', version='v201708') networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201611/network_service/make_test_network.py b/examples/dfp/v201708/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201611/network_service/make_test_network.py rename to examples/dfp/v201708/network_service/make_test_network.py index e8d56aa0..aae855ff 100755 --- a/examples/dfp/v201611/network_service/make_test_network.py +++ b/examples/dfp/v201708/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201611') + network_service = client.GetService('NetworkService', version='v201708') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/dfp/v201611/order_service/__init__.py b/examples/dfp/v201708/order_service/__init__.py similarity index 100% rename from examples/dfp/v201611/order_service/__init__.py rename to examples/dfp/v201708/order_service/__init__.py diff --git a/examples/dfp/v201611/order_service/approve_orders.py b/examples/dfp/v201708/order_service/approve_orders.py similarity index 99% rename from examples/dfp/v201611/order_service/approve_orders.py rename to examples/dfp/v201708/order_service/approve_orders.py index d6f8e3a8..4b47b3bd 100755 --- a/examples/dfp/v201611/order_service/approve_orders.py +++ b/examples/dfp/v201708/order_service/approve_orders.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201611') + order_service = client.GetService('OrderService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/order_service/create_orders.py b/examples/dfp/v201708/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201611/order_service/create_orders.py rename to examples/dfp/v201708/order_service/create_orders.py index 21b38ac8..2e14104b 100755 --- a/examples/dfp/v201611/order_service/create_orders.py +++ b/examples/dfp/v201708/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201611') + order_service = client.GetService('OrderService', version='v201708') # Create order objects. orders = [] diff --git a/examples/dfp/v201611/order_service/get_all_orders.py b/examples/dfp/v201708/order_service/get_all_orders.py similarity index 99% rename from examples/dfp/v201611/order_service/get_all_orders.py rename to examples/dfp/v201708/order_service/get_all_orders.py index 9dc88d9b..5081c2b0 100755 --- a/examples/dfp/v201611/order_service/get_all_orders.py +++ b/examples/dfp/v201708/order_service/get_all_orders.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201611') + order_service = client.GetService('OrderService', version='v201708') # Create a statement to select orders. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/order_service/get_orders_starting_soon.py b/examples/dfp/v201708/order_service/get_orders_starting_soon.py similarity index 99% rename from examples/dfp/v201611/order_service/get_orders_starting_soon.py rename to examples/dfp/v201708/order_service/get_orders_starting_soon.py index 892291b0..60d0f60a 100755 --- a/examples/dfp/v201611/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201708/order_service/get_orders_starting_soon.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201611') + order_service = client.GetService('OrderService', version='v201708') query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' '<= :soon') values = [ diff --git a/examples/dfp/v201611/order_service/update_orders.py b/examples/dfp/v201708/order_service/update_orders.py similarity index 99% rename from examples/dfp/v201611/order_service/update_orders.py rename to examples/dfp/v201708/order_service/update_orders.py index 2d1fe5df..a7930f84 100755 --- a/examples/dfp/v201611/order_service/update_orders.py +++ b/examples/dfp/v201708/order_service/update_orders.py @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201611') + order_service = client.GetService('OrderService', version='v201708') # Create statement object to select a single order by an ID. values = [{ diff --git a/examples/dfp/v201708/package_service/create_packages.py b/examples/dfp/v201708/package_service/create_packages.py new file mode 100755 index 00000000..b6169a6e --- /dev/null +++ b/examples/dfp/v201708/package_service/create_packages.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a package. + +To determine which packages exist, run get_all_packages.py. +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the ID of the product package to create the package from. +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + +# Set the ID of the proposal to create proposal line items under. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the rate card the proposal line items belonging to the product +# package are priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client): + # Initialize appropriate service. + package_service = client.GetService('PackageService', version='v201708') + + # Create local package. + package = { + 'name': 'Package #%d' % random.randint(0, 1000000), + 'proposalId': PROPOSAL_ID, + 'productPackageId': PRODUCT_PACKAGE_ID, + 'rateCardId': RATE_CARD_ID, + } + + # Create the package on the server. + result = package_service.createPackages([package]) + + for new_package in result: + print ('A package with ID %d and name "%s" was created' % + (new_package['id'], new_package['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201708/package_service/create_proposal_line_items_from_packages.py new file mode 100755 index 00000000..0bcc0191 --- /dev/null +++ b/examples/dfp/v201708/package_service/create_proposal_line_items_from_packages.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a copy of an image creative. + +To determine which image creatives exist, run get_image_creatives.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the line item to pause. +PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + package_service = client.GetService('PackageService', version='v201708') + + # Create a statement to select the single package. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', PACKAGE_ID)) + + # Get the package. + query_result = package_service.getPackagesByStatement(statement.ToStatement()) + + package = query_result['results'][0] + + print ('Package with ID %d will create proposal line items using product ' + 'package with ID %d.' % (package['id'], + package['productPackageId'])) + + # Remove limit and offset from statement. + statement.limit = None + statement.offset = None + + # Perform update packages action. + result = package_service.performPackageAction( + {'xsi_type': 'CreateProposalLineItemsFromPackages'}, + statement.ToStatement()) + + if result and result['numChanges'] > 0: + print ('Number of packages that proposal line items were created for: %d' % + result['numChanges']) + else: + print 'No proposal line items were created.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/package_service/get_all_packages.py b/examples/dfp/v201708/package_service/get_all_packages.py similarity index 99% rename from examples/dfp/v201611/package_service/get_all_packages.py rename to examples/dfp/v201708/package_service/get_all_packages.py index 288867af..30d8ac03 100755 --- a/examples/dfp/v201611/package_service/get_all_packages.py +++ b/examples/dfp/v201708/package_service/get_all_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201611') + pkg_service = client.GetService('PackageService', version='v201708') # Create a statement to select packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/package_service/get_in_progress_packages.py b/examples/dfp/v201708/package_service/get_in_progress_packages.py similarity index 99% rename from examples/dfp/v201611/package_service/get_in_progress_packages.py rename to examples/dfp/v201708/package_service/get_in_progress_packages.py index a72be863..0498d893 100755 --- a/examples/dfp/v201611/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201708/package_service/get_in_progress_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201611') + pkg_service = client.GetService('PackageService', version='v201708') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201611/placement_service/create_placements.py b/examples/dfp/v201708/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201611/placement_service/create_placements.py rename to examples/dfp/v201708/placement_service/create_placements.py index 0ab85871..8e272493 100755 --- a/examples/dfp/v201611/placement_service/create_placements.py +++ b/examples/dfp/v201708/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201611') - inventory_service = client.GetService('InventoryService', version='v201611') + placement_service = client.GetService('PlacementService', version='v201708') + inventory_service = client.GetService('InventoryService', version='v201708') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201611/placement_service/deactivate_placements.py b/examples/dfp/v201708/placement_service/deactivate_placements.py similarity index 99% rename from examples/dfp/v201611/placement_service/deactivate_placements.py rename to examples/dfp/v201708/placement_service/deactivate_placements.py index ef317b06..ab6bc811 100755 --- a/examples/dfp/v201611/placement_service/deactivate_placements.py +++ b/examples/dfp/v201708/placement_service/deactivate_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201611') + placement_service = client.GetService('PlacementService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/placement_service/get_active_placements.py b/examples/dfp/v201708/placement_service/get_active_placements.py similarity index 99% rename from examples/dfp/v201611/placement_service/get_active_placements.py rename to examples/dfp/v201708/placement_service/get_active_placements.py index ed52aced..7a4149b5 100755 --- a/examples/dfp/v201611/placement_service/get_active_placements.py +++ b/examples/dfp/v201708/placement_service/get_active_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201611') + placement_service = client.GetService('PlacementService', version='v201708') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201611/placement_service/get_all_placements.py b/examples/dfp/v201708/placement_service/get_all_placements.py similarity index 99% rename from examples/dfp/v201611/placement_service/get_all_placements.py rename to examples/dfp/v201708/placement_service/get_all_placements.py index 1a27a5a1..26fbdc39 100755 --- a/examples/dfp/v201611/placement_service/get_all_placements.py +++ b/examples/dfp/v201708/placement_service/get_all_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201611') + placement_service = client.GetService('PlacementService', version='v201708') # Create a statement to select placements. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/placement_service/update_placements.py b/examples/dfp/v201708/placement_service/update_placements.py similarity index 57% rename from examples/dfp/v201611/placement_service/update_placements.py rename to examples/dfp/v201708/placement_service/update_placements.py index 3b797779..400a5389 100755 --- a/examples/dfp/v201611/placement_service/update_placements.py +++ b/examples/dfp/v201708/placement_service/update_placements.py @@ -28,37 +28,29 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201611') -# Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + placement_service = client.GetService('PlacementService', version='v201708') + + # Create query. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', placement_id)) # Get placements by statement. - placements = placement_service.getPlacementsByStatement( + page = placement_service.getPlacementsByStatement( statement.ToStatement()) - for placement in placements: - if not placement['targetingDescription']: - placement['targetingDescription'] = 'Generic description' - placement['targetingAdLocation'] = 'All images on sports pages.' - placement['targetingSiteName'] = 'http://code.google.com' - placement['isAdSenseTargetingEnabled'] = 'true' + placement = page['results'][0] + + placement['description'] = 'This placement contains all leaderboards.' # Update placements remotely. - placements = placement_service.updatePlacements(placements) + updated_placements = placement_service.updatePlacements([placement]) - for placement in placements: - print ('Placement with id "%s", name "%s", and AdSense targeting ' - 'enabled "%s" was updated.' - % (placement['id'], placement['name'], - placement['isAdSenseTargetingEnabled'])) + for placement in updated_placements: + print ('Placement with id "%s" and name "%s" was updated.' + % (placement['id'], placement['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201611/premium_rate_service/__init__.py b/examples/dfp/v201708/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201611/premium_rate_service/__init__.py rename to examples/dfp/v201708/premium_rate_service/__init__.py diff --git a/examples/dfp/v201611/premium_rate_service/create_premium_rates.py b/examples/dfp/v201708/premium_rate_service/create_premium_rates.py similarity index 90% rename from examples/dfp/v201611/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201708/premium_rate_service/create_premium_rates.py index b13cf248..bc7065ca 100755 --- a/examples/dfp/v201611/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201708/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201611') + version='v201708') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { @@ -57,7 +57,10 @@ def main(client, rate_card_id): 'adjustmentType': 'ABSOLUTE_VALUE' } - # Create premium_rate objects. + # Create premium rate. + # Associate premium rate with the rate card and set premium information. + # This premium will apply for proposal line items targeting 'any' ad unit + # for both CPM and CPC rate types. premium_rate = { 'rateCardId': rate_card_id, 'pricingMethod': 'ANY_VALUE', diff --git a/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201708/premium_rate_service/get_all_premium_rates.py similarity index 97% rename from examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201708/premium_rate_service/get_all_premium_rates.py index 3c5819ff..1ee67756 100755 --- a/examples/dfp/v201611/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201708/premium_rate_service/get_all_premium_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201611') + 'PremiumRateService', version='v201708') # Create a statement to select premium rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 97% rename from examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py index acac01fc..b0b0d3cb 100755 --- a/examples/dfp/v201611/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,7 +25,7 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201611') + 'PremiumRateService', version='v201708') query = 'WHERE rateCardId = :rateCardId' values = [ {'key': 'rateCardId', diff --git a/examples/dfp/v201611/premium_rate_service/update_premium_rates.py b/examples/dfp/v201708/premium_rate_service/update_premium_rates.py similarity index 97% rename from examples/dfp/v201611/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201708/premium_rate_service/update_premium_rates.py index a5adcd8e..054c0d99 100755 --- a/examples/dfp/v201611/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201708/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201611') + version='v201708') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201708/product_package_item_service/create_product_package_item.py b/examples/dfp/v201708/product_package_item_service/create_product_package_item.py new file mode 100755 index 00000000..e5f1fbdd --- /dev/null +++ b/examples/dfp/v201708/product_package_item_service/create_product_package_item.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a product package item. + +To determine which product package items exist, run +get_all_product_package_items.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the product package to add product package items to. +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + +# Set the ID of the product to generate a product package item from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client): + product_package_item_service = client.GetService('ProductPackageItemService', + version='v201708') + + product_package_item = { + # Set the product from which the product package item is created. + 'productId': PRODUCT_ID, + # Set the product package that the product package item belongs to. + 'productPackageId': PRODUCT_PACKAGE_ID, + # Specify if the product package item is required for this + # product package. + 'isMandatory': True + } + + # Create the product package item on the server. + result = product_package_item_service.createProductPackageItems( + [product_package_item]) + + for new_product_package_item in result: + print ('A product package with ID %d created from product ID %d ' + 'belonging to product package with ID %d was created.' % + (new_product_package_item['id'], + new_product_package_item['productId'], + new_product_package_item['productPackageId'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201708/product_package_item_service/get_all_product_package_items.py similarity index 97% rename from examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py rename to examples/dfp/v201708/product_package_item_service/get_all_product_package_items.py index 1aae8913..4cd57d50 100755 --- a/examples/dfp/v201611/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201708/product_package_item_service/get_all_product_package_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201611') + 'ProductPackageItemService', version='v201708') # Create a statement to select product package items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py similarity index 97% rename from examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py index f0f398f0..9f66019d 100755 --- a/examples/dfp/v201611/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,7 +25,7 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201611') + 'ProductPackageItemService', version='v201708') query = 'WHERE productPackageId = :productPackageId' values = [ {'key': 'productPackageId', diff --git a/examples/dfp/v201708/product_package_service/create_product_packages.py b/examples/dfp/v201708/product_package_service/create_product_packages.py new file mode 100755 index 00000000..692cd436 --- /dev/null +++ b/examples/dfp/v201708/product_package_service/create_product_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a product package. + +To determine which product packages exist, run get_all_product_packages.py +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the ID of the rate card to associate with the product package. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client): + product_package_service = client.GetService('ProductPackageService', + version='v201708') + + # Create a local product package. + product_package = { + 'name': 'Product Package #%d' % random.randint(0, 100000000), + 'rateCardIds': [RATE_CARD_ID] + } + + result = product_package_service.createProductPackages([product_package]) + + for new_product_package in result: + print ('A product package with ID %d and name "%s" was created.' % + (new_product_package['id'], new_product_package['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/product_package_service/get_active_product_packages.py b/examples/dfp/v201708/product_package_service/get_active_product_packages.py similarity index 97% rename from examples/dfp/v201611/product_package_service/get_active_product_packages.py rename to examples/dfp/v201708/product_package_service/get_active_product_packages.py index c6e038db..cb56d6e0 100755 --- a/examples/dfp/v201611/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201708/product_package_service/get_active_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201611') + 'ProductPackageService', version='v201708') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201611/product_package_service/get_all_product_packages.py b/examples/dfp/v201708/product_package_service/get_all_product_packages.py similarity index 97% rename from examples/dfp/v201611/product_package_service/get_all_product_packages.py rename to examples/dfp/v201708/product_package_service/get_all_product_packages.py index 9b8f94b6..f0d84bc8 100755 --- a/examples/dfp/v201611/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201708/product_package_service/get_all_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201611') + 'ProductPackageService', version='v201708') # Create a statement to select product packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/product_service/__init__.py b/examples/dfp/v201708/product_service/__init__.py similarity index 100% rename from examples/dfp/v201611/product_service/__init__.py rename to examples/dfp/v201708/product_service/__init__.py diff --git a/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py similarity index 99% rename from examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py rename to examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py index 5e876e25..fdf43b91 100755 --- a/examples/dfp/v201611/product_service/create_programmatic_products_for_non_sales_management.py +++ b/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py @@ -24,8 +24,8 @@ def main(client): - product_service = client.GetService('ProductService', version='v201611') - network_service = client.GetService('NetworkService', version='v201611') + product_service = client.GetService('ProductService', version='v201708') + network_service = client.GetService('NetworkService', version='v201708') product = { # Setting required Marketplace Information. diff --git a/examples/dfp/v201611/product_service/get_all_products.py b/examples/dfp/v201708/product_service/get_all_products.py similarity index 99% rename from examples/dfp/v201611/product_service/get_all_products.py rename to examples/dfp/v201708/product_service/get_all_products.py index c2f7f122..74928f05 100755 --- a/examples/dfp/v201611/product_service/get_all_products.py +++ b/examples/dfp/v201708/product_service/get_all_products.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201611') + product_service = client.GetService('ProductService', version='v201708') # Create a statement to select products. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/product_service/get_products_for_product_template.py b/examples/dfp/v201708/product_service/get_products_for_product_template.py similarity index 99% rename from examples/dfp/v201611/product_service/get_products_for_product_template.py rename to examples/dfp/v201708/product_service/get_products_for_product_template.py index e483c802..a5fe62ea 100755 --- a/examples/dfp/v201611/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201708/product_service/get_products_for_product_template.py @@ -24,7 +24,7 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201611') + product_service = client.GetService('ProductService', version='v201708') query = 'WHERE productTemplateId = :productTemplateId' values = [ diff --git a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py similarity index 99% rename from examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py rename to examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py index fa4b7b21..f8ee622d 100755 --- a/examples/dfp/v201611/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py @@ -27,7 +27,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201611') + product_service = client.GetService('ProductService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/product_service/update_products.py b/examples/dfp/v201708/product_service/update_products.py similarity index 99% rename from examples/dfp/v201611/product_service/update_products.py rename to examples/dfp/v201708/product_service/update_products.py index f8f9cd6f..91cb2076 100755 --- a/examples/dfp/v201611/product_service/update_products.py +++ b/examples/dfp/v201708/product_service/update_products.py @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201611') + product_service = client.GetService('ProductService', version='v201708') # Create statement object to select a single product by an ID. values = [{ diff --git a/examples/dfp/v201611/product_template_service/__init__.py b/examples/dfp/v201708/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201611/product_template_service/__init__.py rename to examples/dfp/v201708/product_template_service/__init__.py diff --git a/examples/dfp/v201611/product_template_service/activate_product_templates.py b/examples/dfp/v201708/product_template_service/activate_product_templates.py similarity index 97% rename from examples/dfp/v201611/product_template_service/activate_product_templates.py rename to examples/dfp/v201708/product_template_service/activate_product_templates.py index febdb005..09cb0c7f 100755 --- a/examples/dfp/v201611/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201708/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201611') + 'ProductTemplateService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/product_template_service/create_product_templates.py b/examples/dfp/v201708/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201611/product_template_service/create_product_templates.py rename to examples/dfp/v201708/product_template_service/create_product_templates.py index 1201f8de..1146f315 100755 --- a/examples/dfp/v201611/product_template_service/create_product_templates.py +++ b/examples/dfp/v201708/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201611') + 'ProductTemplateService', version='v201708') network_service = client.GetService( - 'NetworkService', version='v201611') + 'NetworkService', version='v201708') # Create a product template. product_template = { diff --git a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201708/product_template_service/create_programmatic_product_templates.py similarity index 96% rename from examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py rename to examples/dfp/v201708/product_template_service/create_programmatic_product_templates.py index d39e29f3..d896d79e 100755 --- a/examples/dfp/v201611/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201708/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201611') + 'ProductTemplateService', version='v201708') network_service = client.GetService( - 'NetworkService', version='v201611') + 'NetworkService', version='v201708') product_template = { # Setting required Marketplace information. diff --git a/examples/dfp/v201611/product_template_service/get_all_product_templates.py b/examples/dfp/v201708/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201611/product_template_service/get_all_product_templates.py rename to examples/dfp/v201708/product_template_service/get_all_product_templates.py index 39359fd4..0f8b4731 100755 --- a/examples/dfp/v201611/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201708/product_template_service/get_all_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201611') + 'ProductTemplateService', version='v201708') # Create a statement to select product templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py similarity index 97% rename from examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py index 5689bc2f..eecc85f7 100755 --- a/examples/dfp/v201611/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201611') + 'ProductTemplateService', version='v201708') query = 'WHERE lineItemType = :lineItemType' values = [ {'key': 'lineItemType', diff --git a/examples/dfp/v201611/product_template_service/update_product_templates.py b/examples/dfp/v201708/product_template_service/update_product_templates.py similarity index 98% rename from examples/dfp/v201611/product_template_service/update_product_templates.py rename to examples/dfp/v201708/product_template_service/update_product_templates.py index c47f2faa..f0b8420a 100755 --- a/examples/dfp/v201611/product_template_service/update_product_templates.py +++ b/examples/dfp/v201708/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201611') + 'ProductTemplateService', version='v201708') # Create a statement to select a single product template by ID. values = [{ diff --git a/examples/dfp/v201611/proposal_line_item_service/__init__.py b/examples/dfp/v201708/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201611/proposal_line_item_service/__init__.py rename to examples/dfp/v201708/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py similarity index 98% rename from examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py index 7e84d863..9da431e6 100755 --- a/examples/dfp/v201611/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201611') + 'ProposalLineItemService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 82% rename from examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items.py index 906333f4..4c9ac80a 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -18,11 +18,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set the ID of the programmatic proposal that the proposal line item will # belong to. @@ -39,13 +40,16 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201611') - network_service = client.GetService('NetworkService', version='v201611') + 'ProposalLineItemService', version='v201708') + network_service = client.GetService('NetworkService', version='v201708') # Get the root ad unit to target. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + # Create a single programmatic proposal line item. proposal_line_item = { # Setting required Marketplace information. @@ -64,27 +68,8 @@ def main(client, proposal_id, product_id, rate_card_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'goal': { 'units': '1000', 'unitType': 'IMPRESSIONS', diff --git a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 82% rename from examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index aa3cd41d..71210849 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -18,11 +18,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -33,8 +34,11 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201611') - network_service = client.GetService('NetworkService', version='v201611') + 'ProposalLineItemService', version='v201708') + network_service = client.GetService('NetworkService', version='v201708') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) # Get the root ad unit to target. root_ad_unit_id = ( @@ -58,27 +62,8 @@ def main(client, proposal_id, product_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'creativePlaceholders': [{ 'size': { 'width': '300', diff --git a/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/create_proposal_line_items.py similarity index 82% rename from examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201708/proposal_line_item_service/create_proposal_line_items.py index 4823a1e6..227cc3e1 100755 --- a/examples/dfp/v201611/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/create_proposal_line_items.py @@ -22,11 +22,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -41,8 +42,11 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201611') - network_service = client.GetService('NetworkService', version='v201611') + 'ProposalLineItemService', version='v201708') + network_service = client.GetService('NetworkService', version='v201708') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) # Get the root ad unit to target. root_ad_unit_id = ( @@ -61,27 +65,8 @@ def main(client, proposal_id, product_id, rate_card_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'deliveryRateType': 'EVENLY', 'creativeRotationType': 'OPTIMIZED', 'billingCap': 'CAPPED_CUMULATIVE', diff --git a/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/get_all_proposal_line_items.py similarity index 97% rename from examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201708/proposal_line_item_service/get_all_proposal_line_items.py index bbe0c654..5e162cd9 100755 --- a/examples/dfp/v201611/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201611') + 'ProposalLineItemService', version='v201708') # Create a statement to select proposal line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 97% rename from examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py index aaf6c0bd..31a210bc 100755 --- a/examples/dfp/v201611/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,7 +25,7 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201611') + 'ProposalLineItemService', version='v201708') query = 'WHERE proposalId = :proposalId' values = [ {'key': 'proposalId', diff --git a/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py similarity index 97% rename from examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py index 57c7a03b..7e905ac2 100755 --- a/examples/dfp/v201611/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201611') + 'ProposalLineItemService', version='v201708') # Create statement to select a proposal line item. values = [{ diff --git a/examples/dfp/v201611/proposal_service/__init__.py b/examples/dfp/v201708/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201611/proposal_service/__init__.py rename to examples/dfp/v201708/proposal_service/__init__.py diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201708/proposal_service/create_programmatic_proposals.py similarity index 98% rename from examples/dfp/v201611/proposal_service/create_programmatic_proposals.py rename to examples/dfp/v201708/proposal_service/create_programmatic_proposals.py index ac5b4c30..9e863535 100755 --- a/examples/dfp/v201611/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201708/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201611') - network_service = client.GetService('NetworkService', version='v201611') + proposal_service = client.GetService('ProposalService', version='v201708') + network_service = client.GetService('NetworkService', version='v201708') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201708/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 99% rename from examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/dfp/v201708/proposal_service/create_programmatic_proposals_for_non_sales_management.py index e687a8f9..14230f75 100755 --- a/examples/dfp/v201611/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201708/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201611') + proposal_service = client.GetService('ProposalService', version='v201708') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201611/proposal_service/create_proposals.py b/examples/dfp/v201708/proposal_service/create_proposals.py similarity index 99% rename from examples/dfp/v201611/proposal_service/create_proposals.py rename to examples/dfp/v201708/proposal_service/create_proposals.py index da59b791..cf336380 100755 --- a/examples/dfp/v201611/proposal_service/create_proposals.py +++ b/examples/dfp/v201708/proposal_service/create_proposals.py @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201611') - network_service = client.GetService('NetworkService', version='v201611') + proposal_service = client.GetService('ProposalService', version='v201708') + network_service = client.GetService('NetworkService', version='v201708') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201611/proposal_service/get_all_proposals.py b/examples/dfp/v201708/proposal_service/get_all_proposals.py similarity index 99% rename from examples/dfp/v201611/proposal_service/get_all_proposals.py rename to examples/dfp/v201708/proposal_service/get_all_proposals.py index 82798691..1b8cbb9a 100755 --- a/examples/dfp/v201611/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201708/proposal_service/get_all_proposals.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201611') + proposal_service = client.GetService('ProposalService', version='v201708') # Create a statement to select proposals. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/proposal_service/get_marketplace_comments.py b/examples/dfp/v201708/proposal_service/get_marketplace_comments.py similarity index 55% rename from examples/dfp/v201611/proposal_service/get_marketplace_comments.py rename to examples/dfp/v201708/proposal_service/get_marketplace_comments.py index f27b86c3..288a73d3 100755 --- a/examples/dfp/v201611/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201708/proposal_service/get_marketplace_comments.py @@ -14,46 +14,38 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets the Marketplace comments for a programmatic proposal. -""" +"""This example gets the Marketplace comments for a programmatic proposal.""" # Import appropriate modules from the client library. from datetime import datetime from googleads import dfp + PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201611') + 'ProposalService', version='v201708') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} - # Retrieve a small amount of marketplace comments at a time, paging - # through until all marketplace comments have been retrieved. - while True: - response = marketplace_comment_service.getMarketplaceCommentsByStatement( - statement) - if 'results' in response: - for marketplace_comment in response['results']: - # Print out some information for each marketplace comment. - date_time = marketplace_comment['creationTime'] - date_time_string = datetime(date_time['date']['year'], - date_time['date']['month'], - date_time['date']['day'], date_time['hour'], - date_time['minute'], - date_time['second']).isoformat() - - print( - 'Marketplace comment with creation time "%s"and comment "%s" was ' - 'found.\n' - % (date_time_string, marketplace_comment['comment'])) - else: - break + response = marketplace_comment_service.getMarketplaceCommentsByStatement( + statement) + + # Print out some information for each marketplace comment. + for marketplace_comment in response['results']: + date_time = marketplace_comment['creationTime'] + date_time_string = datetime(date_time['date']['year'], + date_time['date']['month'], + date_time['date']['day'], date_time['hour'], + date_time['minute'], + date_time['second']).isoformat() + print('Marketplace comment with creation time "%s"and comment "%s" was ' + 'found.\n' % (date_time_string, marketplace_comment['comment'])) print '\nNumber of results found: %s' % response['totalResultSetSize'] diff --git a/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py similarity index 99% rename from examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py rename to examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py index 51471fa2..9ee049f0 100755 --- a/examples/dfp/v201611/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201611') + proposal_service = client.GetService('ProposalService', version='v201708') query = 'WHERE status = :status' values = [ {'key': 'status', diff --git a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py similarity index 99% rename from examples/dfp/v201611/proposal_service/request_buyers_acceptance.py rename to examples/dfp/v201708/proposal_service/request_buyers_acceptance.py index bc6c27d4..2d7a14ac 100755 --- a/examples/dfp/v201611/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py @@ -26,7 +26,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201611') + proposal_service = client.GetService('ProposalService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py similarity index 99% rename from examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py index 1300355f..c76ccfad 100755 --- a/examples/dfp/v201611/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201611') + proposal_service = client.GetService('ProposalService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/proposal_service/update_proposals.py b/examples/dfp/v201708/proposal_service/update_proposals.py similarity index 99% rename from examples/dfp/v201611/proposal_service/update_proposals.py rename to examples/dfp/v201708/proposal_service/update_proposals.py index 71ddee70..f4083ba9 100755 --- a/examples/dfp/v201611/proposal_service/update_proposals.py +++ b/examples/dfp/v201708/proposal_service/update_proposals.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201611') + proposal_service = client.GetService('ProposalService', version='v201708') # Create statement object to select a single proposal by an ID. values = [{ diff --git a/examples/dfp/v201611/publisher_query_language_service/__init__.py b/examples/dfp/v201708/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201611/publisher_query_language_service/__init__.py rename to examples/dfp/v201708/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201708/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201708/publisher_query_language_service/fetch_match_tables.py index c85d1f22..cc495e72 100755 --- a/examples/dfp/v201611/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201708/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201611') + report_downloader = client.GetDataDownloader(version='v201708') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201708/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/dfp/v201708/publisher_query_language_service/get_all_programmatic_buyers.py index d49d945b..7f5895ce 100755 --- a/examples/dfp/v201611/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201708/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201611') + data_downloader = client.GetDataDownloader(version='v201708') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py new file mode 100755 index 00000000..d1b35a8a --- /dev/null +++ b/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Gets recent changes in your network using the Change_History table. + +A full list of available tables can be found at: +https://developers.google.com/doubleclick-publishers/docs/reference/latest/PublisherQueryLanguageService +""" + +from datetime import date +from datetime import datetime +from datetime import timedelta + +# Import appropriate modules from the client library. +from googleads import dfp +import pytz + + +def main(client): + # Initialize appropriate service. + pql_service = client.GetService('PublisherQueryLanguageService', 'v201708') + + end_date = date.today() + start_date = end_date - timedelta(days=1) + initial_query = ( + 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' + 'FROM Change_History ' + 'WHERE ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime ' + 'ORDER BY ChangeDateTime DESC') + pagination_query = ( + 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' + 'FROM Change_History ' + 'WHERE Id < :id ' + 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' + 'ORDER BY ChangeDateTime DESC') + values = [ + { + 'key': 'startDateTime', + 'value': { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': start_date.year, + 'month': start_date.month, + 'day': start_date.day + } + } + } + }, + { + 'key': 'endDateTime', + 'value': { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': end_date.year, + 'month': end_date.month, + 'day': end_date.day + } + } + } + } + ] + + statement = dfp.FilterStatement(initial_query, values) + keep_iterating = True + i = 0 + total_rows = [] + + while keep_iterating: + response = pql_service.select(statement.ToStatement()) + column_types = ([column_type['labelName'] + for column_type in response['columnTypes']]) + rows = response['rows'] + rows_length = len(rows) + total_rows.extend(rows) + + if rows and rows_length > 0: + # Get the earliest change ID in the result set. + last_row = rows[-1] + last_id = last_row['values'][0]['value'] + i += 1 + statement = UpdateFilterStatement( + statement, pagination_query, values, last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' + % (i, rows_length, last_id)) + + keep_iterating = rows and len(rows) == statement.limit + + # Print out columns header + print ','.join(column_types) + + # Print out every row + for row in total_rows: + print ConvertValueForCsv(row) + + +def UpdateFilterStatement(statement, query, values, last_id): + """Updates the FilterStatement in order to page through results. + + Args: + statement: an instantiated FilterStatement. + query: a str query that will be used to update the FilterStatement. + values: a list of bind variables to be updated. + last_id: a str representing the earliest change ID in a result set. + + Returns: + FilterStatement the updated statement. + """ + # Use the earliest change ID in the result set to page. + updated_values = [{ + 'key': 'id', + 'value': { + 'xsi_type': 'TextValue', + 'value': last_id + } + }] + updated_values.extend(values) + + statement.where_clause = query + statement.values = updated_values + + return statement + + +def ConvertValueForCsv(pql_value): + """Sanitizes a field value from a Value object to a CSV suitable format. + + Args: + pql_value: dict a dictionary containing the data for a single field of an + entity. + + Returns: + str a CSV writer friendly value formatted by Value.Type. + """ + if 'value' in pql_value: + field = pql_value['value'] + elif 'values' in pql_value: + field = pql_value['values'] + else: + field = None + + if field: + if isinstance(field, list): + return ','.join(['"%s"' % str(ConvertValueForCsv(single_field)) + for single_field in field]) + else: + class_type = dfp.DfpClassType(pql_value) + + if class_type == 'TextValue': + return field.replace('"', '""').encode('UTF8') + elif class_type == 'NumberValue': + return float(field) if '.' in field else int(field) + elif class_type == 'DateTimeValue': + return ConvertDateTimeToOffset(field) + elif class_type == 'DateValue': + return date(int(field['date']['year']), + int(field['date']['month']), + int(field['date']['day'])).isoformat() + else: + return field + else: + return '-' + + +def ConvertDateTimeToOffset(date_time_value): + """Converts the PQL formatted response for a dateTime object. + + Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.' + + Args: + date_time_value: dict The date time value from the PQL response. + + Returns: + str: A string representation of the date time value uniform to + ReportService. + """ + date_time_obj = datetime(int(date_time_value['date']['year']), + int(date_time_value['date']['month']), + int(date_time_value['date']['day']), + int(date_time_value['hour']), + int(date_time_value['minute']), + int(date_time_value['second'])) + date_time_str = pytz.timezone( + date_time_value['timeZoneID']).localize(date_time_obj).isoformat() + + if date_time_str[-5:] == '00:00': + return date_time_str[:-6] + 'Z' + else: + return date_time_str + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/rate_card_service/__init__.py b/examples/dfp/v201708/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201611/rate_card_service/__init__.py rename to examples/dfp/v201708/rate_card_service/__init__.py diff --git a/examples/dfp/v201708/rate_card_service/create_rate_cards.py b/examples/dfp/v201708/rate_card_service/create_rate_cards.py new file mode 100755 index 00000000..ebe65a36 --- /dev/null +++ b/examples/dfp/v201708/rate_card_service/create_rate_cards.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a new rate card. + +To determine which rate cards exist, run get_all_rate_cards.py. +""" + +# Import appropriate modules from the client library. +import random + +from googleads import dfp + +# Set the IDs of the teams this rate card should be visible to. +TEAM_IDS = ['INSERT_TEAM_ID_HERE'] + +# Set the currency code to create the rate card with. +CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201708') + + # Create a rate card. + rate_card = { + 'name': 'RateCard #%d' % random.randint(0, 100000000), + 'currencyCode': CURRENCY_CODE, + 'pricingModel': 'NET', + } + + # This field is optional. + rate_card['appliedTeamIds'] = TEAM_IDS + + result = rate_card_service.createRateCards([rate_card]) + + for new_rate_card in result: + print ('A rate card with ID %s, name "%s", and currency code "%s" ' + 'was created.' % (new_rate_card['id'], + new_rate_card['name'], + new_rate_card['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201708/rate_card_service/get_all_rate_cards.py similarity index 99% rename from examples/dfp/v201611/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201708/rate_card_service/get_all_rate_cards.py index 6d6494ce..3dbeea8f 100755 --- a/examples/dfp/v201611/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201708/rate_card_service/get_all_rate_cards.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201611') + rate_card_service = client.GetService('RateCardService', version='v201708') # Create a statement to select rate cards. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py similarity index 99% rename from examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py rename to examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py index cb79ef97..3d328885 100755 --- a/examples/dfp/v201611/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201611') + rate_card_service = client.GetService('RateCardService', version='v201708') query = 'WHERE forMarketplace = :forMarketplace' values = [ {'key': 'forMarketplace', diff --git a/examples/dfp/v201708/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201708/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py new file mode 100755 index 00000000..926f3fa2 --- /dev/null +++ b/examples/dfp/v201708/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 line item reports for a given reconciliation report. + +To determine how many reconciliation reports exist, +run get_all_reconciliation_reports.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation report to query. +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_line_item_report_service = (client.GetService( + 'ReconciliationLineItemReportService', version='v201708')) + + # Create a statement to select reconciliation line item reports. + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reconciliationReportId AND ' + 'lineItemId != :lineItemId')) + .OrderBy('lineItemId', ascending=True) + .WithBindVariable('reconciliationReportId', + RECONCILIATION_REPORT_ID) + .WithBindVariable('lineItemId', 0)) + + # Retrieve a small amount of reconciliation line item reports at a time, + # paging through until all reconciliation line item reports have been + # retrieved. + result_set_size = 0 + should_continue = True + + while should_continue: + page = (reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement( + statement.ToStatement())) + if 'results' in page: + result_set_size += page['totalResultSetSize'] + # Iterate over individual results in the page. + for line_item_report in page['results']: + print ('Reconciliation line item report with ID %d, line item ID %d, ' + 'reconciliation source "%s", and reconciled volume %d was ' + 'found.' % (line_item_report['id'], + line_item_report['lineItemId'], + line_item_report['reconciliationSource'], + (line_item_report['reconciledVolume'] + if 'reconciledVolume' in line_item_report else 0))) + # Update statement for next page. + statement.offset += statement.limit + should_continue = statement.offset < result_set_size + + print 'Number of results found: %d' % result_set_size + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201708/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py new file mode 100755 index 00000000..1dd11335 --- /dev/null +++ b/examples/dfp/v201708/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 updates a reconciliation line item report. + +To get reconciliation line item reports for a reconciliation report, run +get_reconciliation_line_item_reports_for_reconciliation_report.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation line item report to update. +RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_line_item_report_service = (client.GetService( + 'ReconciliationLineItemReportService', version='v201708')) + + # Create a statement to select a reconciliation line item report. + statement = (dfp.StatementBuilder() + .Where('id = :lineItemReportId') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('lineItemReportId', + RECONCILIATION_LINE_ITEM_REPORT_ID)) + + # Get reconciliation line item reports by statement. + page = (reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement(statement.ToStatement())) + + line_item_report = page['results'][0] + + # Set and use a manual volume for billing. This example splits the difference + # between DFP and the third party volume. + line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + + line_item_report['thirdPartyVolume']) / 2 + line_item_report['reconciliationSource'] = 'MANUAL' + + result = (reconciliation_line_item_report_service + .updateReconciliationLineItemReports([line_item_report])) + + for updated_report in result: + print ('Reconciliation line item report with ID %d for line item ID %d was ' + 'updated, with manual volume %d' % (updated_report['id'], + updated_report['lineItemId'], + updated_report['manualVolume'])) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 97% rename from examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 8f4ecfeb..6e07ba1e 100755 --- a/examples/dfp/v201611/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,7 +25,7 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201611') + 'ReconciliationOrderReportService', version='v201708') query = 'WHERE reconciliationReportId = :reconciliationReportId' values = [ {'key': 'reconciliationReportId', diff --git a/examples/dfp/v201708/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201708/reconciliation_order_report_service/submit_reconciliation_order_reports.py new file mode 100755 index 00000000..0eef8e42 --- /dev/null +++ b/examples/dfp/v201708/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 submits a reconciliation order report. + +To get all reconciliation order reports for a reconciliation report, +run get get_reconciliation_order_reports_for_reconciliation_report.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation order report to submit. +RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_order_report_service = (client.GetService( + 'ReconciliationOrderReportService', version='v201708')) + + # Create a statement to select reconciliation order reports. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', RECONCILIATION_ORDER_REPORT_ID)) + + # Get reconciliation order reports by statement. + page = (reconciliation_order_report_service + .getReconciliationOrderReportsByStatement(statement.ToStatement())) + + report = page['results'][0] + + print ('Reconciliation order report with ID %d will be submitted.' % + report['id']) + + # Remove limit and offset from statement. + statement.limit = None + statement.offset = None + + # Perform action. + result = (reconciliation_order_report_service + .performReconciliationOrderReportAction( + {'xsi_type': 'SubmitReconciliationOrderReports'}, + statement.ToStatement())) + + if result and result['numChanges'] > 0: + print ('Number of reconciliation order reports submitted: %d' % + result['numChanges']) + else: + print 'No reconciliation order reports were submitted.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 90% rename from examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index ae5681f7..d00d24c7 100755 --- a/examples/dfp/v201611/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -13,28 +13,30 @@ # 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. + """Gets a reconciliation report's rows for line items that served through DFP. """ # Import appropriate modules from the client library. from googleads import dfp +# Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201611') + 'ReconciliationReportRowService', version='v201708') query = ('WHERE reconciliationReportId = %s AND ' 'lineItemId != :lineItemId') % reconciliation_report_id - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - }}, - ] + values = [{ + 'key': 'lineItemId', + 'value': { + 'xsi_type': 'NumberValue', + 'value': '0' + } + }] # Create a statement to select reconciliation report rows. statement = dfp.FilterStatement(query, values) diff --git a/examples/dfp/v201708/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201708/reconciliation_report_row_service/update_reconciliation_report_rows.py new file mode 100755 index 00000000..9a8ceae4 --- /dev/null +++ b/examples/dfp/v201708/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 updates a reconciliation report row. + +To determine which reconciliation report rows exist, +run get_reconciliation_report_rows_for_reconciliation_report.py +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the ID of the reconciliation report row. +RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' + +# Set the ID of the reconciliation report. +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_report_row_service = (client.GetService( + 'ReconciliationReportRowService', version='v201708')) + + # Create a statement to select reconciliation report rows. + statement = (dfp.StatementBuilder() + .Where(('id = :reconciliationReportRowId AND ' + 'reconciliationReportId = :reconciliationReportId')) + .OrderBy('id', ascending=True) + .WithBindVariable('reconciliationReportRowId', + RECONCILIATION_REPORT_ROW_ID) + .WithBindVariable('reconciliationReportId', + RECONCILIATION_REPORT_ID)) + + # Get reconciliation report rows by statement. + page = (reconciliation_report_row_service + .getReconciliationReportRowsByStatement(statement.ToStatement())) + + row = page['results'][0] + + # Set a comment on the reconciliation report row. + row['comments'] = ('Third part volume didn\'t match DFP - we agreed to split ' + 'the difference') + + # Set and use a manual volume for billing. + row['manualVolume'] = (row['dfpVolume'] + row['thirdPartyVolume']) / 2 + row['reconciliationSource'] = 'MANUAL' + + updated_rows = (reconciliation_report_row_service + .updateReconciliationReportRows([row])) + + for updated_row in updated_rows: + print ('Reconciliation report row for line item ID %d and creative ID %d ' + 'was updated, with manual volume %d' % (updated_row['lineItemId'], + updated_row['creativeId'], + updated_row['manualVolume'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201708/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 97% rename from examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/dfp/v201708/reconciliation_report_service/get_all_reconciliation_reports.py index 5cafef53..ffa37af6 100755 --- a/examples/dfp/v201611/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201708/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201611') + 'ReconciliationReportService', version='v201708') # Create a statement to select reconciliation reports. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201708/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 86% rename from examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/dfp/v201708/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index e73149f9..133f4195 100755 --- a/examples/dfp/v201611/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201708/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,21 +26,15 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201611') + 'ReconciliationReportService', version='v201708') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) - query = 'WHERE startDate = :startDate' - values = [ - {'key': 'startDate', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_month.strftime('%Y-%m-01') - }}, - ] # Create a statement to select reconciliation reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('startDate = :startDate') + .WithBindVariable('startDate', last_month)) # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. diff --git a/examples/dfp/v201611/report_service/__init__.py b/examples/dfp/v201708/report_service/__init__.py similarity index 100% rename from examples/dfp/v201611/report_service/__init__.py rename to examples/dfp/v201708/report_service/__init__.py diff --git a/examples/dfp/v201611/report_service/run_delivery_report.py b/examples/dfp/v201708/report_service/run_delivery_report.py similarity index 87% rename from examples/dfp/v201611/report_service/run_delivery_report.py rename to examples/dfp/v201708/report_service/run_delivery_report.py index 5ec23cf4..cffd7138 100755 --- a/examples/dfp/v201611/report_service/run_delivery_report.py +++ b/examples/dfp/v201708/report_service/run_delivery_report.py @@ -43,7 +43,7 @@ def main(client, order_id): 'values': values} # Set the start and end dates of the report to run (past 8 days). - end_date = datetime.now() + end_date = datetime.now().date() start_date = end_date - timedelta(days=8) # Create report job. @@ -57,17 +57,13 @@ def main(client, order_id): 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], 'dateRangeType': 'CUSTOM_DATE', - 'startDate': {'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day}, - 'endDate': {'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day} + 'startDate': start_date, + 'endDate': end_date } } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201611') + report_downloader = client.GetDataDownloader(version='v201708') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201611/report_service/run_inventory_report.py b/examples/dfp/v201708/report_service/run_inventory_report.py similarity index 97% rename from examples/dfp/v201611/report_service/run_inventory_report.py rename to examples/dfp/v201708/report_service/run_inventory_report.py index b57d2d6f..4cb31c49 100755 --- a/examples/dfp/v201611/report_service/run_inventory_report.py +++ b/examples/dfp/v201708/report_service/run_inventory_report.py @@ -25,9 +25,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201611') + network_service = client.GetService('NetworkService', version='v201708') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201611') + report_downloader = client.GetDataDownloader(version='v201708') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201611/report_service/run_reach_report.py b/examples/dfp/v201708/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201611/report_service/run_reach_report.py rename to examples/dfp/v201708/report_service/run_reach_report.py index 837bc456..a50d6169 100755 --- a/examples/dfp/v201611/report_service/run_reach_report.py +++ b/examples/dfp/v201708/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201611') + report_downloader = client.GetDataDownloader(version='v201708') # Create report job. report_job = { diff --git a/examples/dfp/v201611/report_service/run_report_with_custom_fields.py b/examples/dfp/v201708/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/dfp/v201611/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201708/report_service/run_report_with_custom_fields.py index f7632c2d..e482d20f 100755 --- a/examples/dfp/v201611/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201708/report_service/run_report_with_custom_fields.py @@ -28,9 +28,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201611') + line_item_service = client.GetService('LineItemService', version='v201708') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201611') + report_downloader = client.GetDataDownloader(version='v201708') # Filter for line items of a given order. values = [{ diff --git a/examples/dfp/v201611/report_service/run_sales_report.py b/examples/dfp/v201708/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201611/report_service/run_sales_report.py rename to examples/dfp/v201708/report_service/run_sales_report.py index 0ea30bf5..cdea66fb 100755 --- a/examples/dfp/v201611/report_service/run_sales_report.py +++ b/examples/dfp/v201708/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201611') + report_downloader = client.GetDataDownloader(version='v201708') # Create report job. report_job = { diff --git a/examples/dfp/v201611/report_service/run_saved_query.py b/examples/dfp/v201708/report_service/run_saved_query.py similarity index 97% rename from examples/dfp/v201611/report_service/run_saved_query.py rename to examples/dfp/v201708/report_service/run_saved_query.py index f2bd0f0f..0529d694 100755 --- a/examples/dfp/v201611/report_service/run_saved_query.py +++ b/examples/dfp/v201708/report_service/run_saved_query.py @@ -28,10 +28,10 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201611') + report_service = client.GetService('ReportService', version='v201708') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201611') + report_downloader = client.GetDataDownloader(version='v201708') # Create statement object to filter for an order. values = [{ diff --git a/examples/dfp/v201611/suggested_ad_unit_service/__init__.py b/examples/dfp/v201708/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201611/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201708/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201708/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201708/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 9233f5b0..e21553b0 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201708/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201611') + 'SuggestedAdUnitService', version='v201708') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201708/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201708/suggested_ad_unit_service/get_all_suggested_ad_units.py index ed673cf1..4bd9cb1f 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201708/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201611') + 'SuggestedAdUnitService', version='v201708') # Create a statement to select suggested ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index a4981ca6..fc262e7f 100755 --- a/examples/dfp/v201611/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,7 +25,7 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201611') + 'SuggestedAdUnitService', version='v201708') query = 'WHERE numRequests >= :numRequests' values = [ {'key': 'numRequests', diff --git a/examples/dfp/v201611/team_service/__init__.py b/examples/dfp/v201708/team_service/__init__.py similarity index 100% rename from examples/dfp/v201611/team_service/__init__.py rename to examples/dfp/v201708/team_service/__init__.py diff --git a/examples/dfp/v201611/team_service/create_teams.py b/examples/dfp/v201708/team_service/create_teams.py similarity index 96% rename from examples/dfp/v201611/team_service/create_teams.py rename to examples/dfp/v201708/team_service/create_teams.py index 05639a79..7e446598 100755 --- a/examples/dfp/v201611/team_service/create_teams.py +++ b/examples/dfp/v201708/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201611') + team_service = client.GetService('TeamService', version='v201708') # Create team objects. teams = [] diff --git a/examples/dfp/v201611/team_service/get_all_teams.py b/examples/dfp/v201708/team_service/get_all_teams.py similarity index 95% rename from examples/dfp/v201611/team_service/get_all_teams.py rename to examples/dfp/v201708/team_service/get_all_teams.py index 67d53835..765cd03e 100755 --- a/examples/dfp/v201611/team_service/get_all_teams.py +++ b/examples/dfp/v201708/team_service/get_all_teams.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201611') + team_service = client.GetService('TeamService', version='v201708') # Create a statement to select teams. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/team_service/update_teams.py b/examples/dfp/v201708/team_service/update_teams.py similarity index 96% rename from examples/dfp/v201611/team_service/update_teams.py rename to examples/dfp/v201708/team_service/update_teams.py index 8016d1ab..ee9340cd 100755 --- a/examples/dfp/v201611/team_service/update_teams.py +++ b/examples/dfp/v201708/team_service/update_teams.py @@ -34,7 +34,7 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201611') + team_service = client.GetService('TeamService', version='v201708') # Create a filter statement to select a single team by ID. values = [{ diff --git a/examples/dfp/v201611/user_service/__init__.py b/examples/dfp/v201708/user_service/__init__.py similarity index 100% rename from examples/dfp/v201611/user_service/__init__.py rename to examples/dfp/v201708/user_service/__init__.py diff --git a/examples/dfp/v201611/user_service/create_users.py b/examples/dfp/v201708/user_service/create_users.py similarity index 95% rename from examples/dfp/v201611/user_service/create_users.py rename to examples/dfp/v201708/user_service/create_users.py index 585f5dcf..2e2474f6 100755 --- a/examples/dfp/v201611/user_service/create_users.py +++ b/examples/dfp/v201708/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201611') + user_service = client.GetService('UserService', version='v201708') # Create user objects. users = [ diff --git a/examples/dfp/v201611/user_service/deactivate_users.py b/examples/dfp/v201708/user_service/deactivate_users.py similarity index 96% rename from examples/dfp/v201611/user_service/deactivate_users.py rename to examples/dfp/v201708/user_service/deactivate_users.py index 771244c0..41563678 100755 --- a/examples/dfp/v201611/user_service/deactivate_users.py +++ b/examples/dfp/v201708/user_service/deactivate_users.py @@ -30,7 +30,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201611') + user_service = client.GetService('UserService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/user_service/get_all_roles.py b/examples/dfp/v201708/user_service/get_all_roles.py similarity index 100% rename from examples/dfp/v201611/user_service/get_all_roles.py rename to examples/dfp/v201708/user_service/get_all_roles.py diff --git a/examples/dfp/v201611/user_service/get_all_users.py b/examples/dfp/v201708/user_service/get_all_users.py similarity index 95% rename from examples/dfp/v201611/user_service/get_all_users.py rename to examples/dfp/v201708/user_service/get_all_users.py index 2a8f6ee2..7ec1f61c 100755 --- a/examples/dfp/v201611/user_service/get_all_users.py +++ b/examples/dfp/v201708/user_service/get_all_users.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201611') + user_service = client.GetService('UserService', version='v201708') # Create a statement to select users. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/user_service/get_current_user.py b/examples/dfp/v201708/user_service/get_current_user.py new file mode 100755 index 00000000..5f1b32e5 --- /dev/null +++ b/examples/dfp/v201708/user_service/get_current_user.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 the current user.""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201708') + + # Get current user. + user = user_service.getCurrentUser() + + print ('User with ID %d, name "%s", email "%s", and role "%s" ' + 'is the current user.' % ( + user.id, user.name, user.email, user.roleName + )) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201611/user_service/get_user_by_email_address.py b/examples/dfp/v201708/user_service/get_user_by_email_address.py similarity index 96% rename from examples/dfp/v201611/user_service/get_user_by_email_address.py rename to examples/dfp/v201708/user_service/get_user_by_email_address.py index ae14fc25..364bdc60 100755 --- a/examples/dfp/v201611/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201708/user_service/get_user_by_email_address.py @@ -24,7 +24,7 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201611') + user_service = client.GetService('UserService', version='v201708') query = 'WHERE email = :email' values = [ {'key': 'email', diff --git a/examples/dfp/v201611/user_service/update_users.py b/examples/dfp/v201708/user_service/update_users.py similarity index 96% rename from examples/dfp/v201611/user_service/update_users.py rename to examples/dfp/v201708/user_service/update_users.py index 1bb5d43a..0354b8fa 100755 --- a/examples/dfp/v201611/user_service/update_users.py +++ b/examples/dfp/v201708/user_service/update_users.py @@ -28,7 +28,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201611') + user_service = client.GetService('UserService', version='v201708') # Create query. values = [{ diff --git a/examples/dfp/v201611/user_team_association_service/__init__.py b/examples/dfp/v201708/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201611/user_team_association_service/__init__.py rename to examples/dfp/v201708/user_team_association_service/__init__.py diff --git a/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201708/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201611/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201708/user_team_association_service/create_user_team_associations.py index 73088e81..de11c509 100755 --- a/examples/dfp/v201611/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201708/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201611') + 'UserTeamAssociationService', version='v201708') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py similarity index 98% rename from examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py index 3d15ff40..748bb82b 100755 --- a/examples/dfp/v201611/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201611') + 'UserTeamAssociationService', version='v201708') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201708/user_team_association_service/get_all_user_team_associations.py similarity index 97% rename from examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201708/user_team_association_service/get_all_user_team_associations.py index 58775565..df40c5ad 100755 --- a/examples/dfp/v201611/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201708/user_team_association_service/get_all_user_team_associations.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201611') + 'UserTeamAssociationService', version='v201708') # Create a statement to select user team associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py similarity index 97% rename from examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py index 8a939a7d..a2a56fa7 100755 --- a/examples/dfp/v201611/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py @@ -25,7 +25,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201611') + 'UserTeamAssociationService', version='v201708') query = 'WHERE userId = :userId' values = [ {'key': 'userId', diff --git a/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py similarity index 98% rename from examples/dfp/v201611/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201708/user_team_association_service/update_user_team_associations.py index de32b653..c6dcc284 100755 --- a/examples/dfp/v201611/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201611') + 'UserTeamAssociationService', version='v201708') # Create filter text to select user team associations by the user ID. values = [{ diff --git a/examples/dfp/v201611/workflow_request_service/__init__.py b/examples/dfp/v201708/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201611/workflow_request_service/__init__.py rename to examples/dfp/v201708/workflow_request_service/__init__.py diff --git a/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py similarity index 97% rename from examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py index 6c7dbeb0..8ff9c893 100755 --- a/examples/dfp/v201611/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201611') + version='v201708') # Create query. values = [ diff --git a/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py similarity index 97% rename from examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py rename to examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py index cab51b81..94390849 100755 --- a/examples/dfp/v201611/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201611') + 'WorkflowRequestService', version='v201708') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py similarity index 97% rename from examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py index 11651506..77e947ab 100755 --- a/examples/dfp/v201611/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201611') + 'WorkflowRequestService', version='v201708') query = 'WHERE type = :type' values = [ {'key': 'type', diff --git a/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 98% rename from examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py index cdca1668..7a11e501 100755 --- a/examples/dfp/v201611/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201611') + version='v201708') # Create query. values = [ diff --git a/googleads/common.py b/googleads/common.py index 01265371..6f01d0e2 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -66,7 +66,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '6.1.0' +VERSION = '7.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' diff --git a/googleads/dfp.py b/googleads/dfp.py index ee7fe18b..16fc2204 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -46,7 +46,7 @@ # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201608': + 'v201611': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -56,18 +56,18 @@ 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NetworkService', 'OrderService', + 'PackageService', 'PlacementService', 'PremiumRateService', + 'ProductService', 'ProductPackageService', 'ProductPackageItemService', + 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201611': + 'v201702': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -78,17 +78,18 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NetworkService', 'OrderService', - 'PackageService', 'PlacementService', 'PremiumRateService', - 'ProductService', 'ProductPackageService', 'ProductPackageItemService', - 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201702': + 'v201705': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -110,7 +111,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201705': + 'v201708': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', From 3b7e87d352815b20cfae1d4802cc4fdc5d681d1f Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Wed, 16 Aug 2017 21:31:46 +1000 Subject: [PATCH 087/180] Commiting latest changes. From fddb83a9fce8fcd3a4f7c3a0360271db4de17efa Mon Sep 17 00:00:00 2001 From: Nicolas Couture Date: Thu, 14 Sep 2017 06:16:13 +0000 Subject: [PATCH 088/180] installation instructions improvements - remove extranuous installation instructions - add requirements.txt - add appengine_config.py, use of lib/ dir for 3rd party Python libs - declare default service name in app.yaml - ask for installation of the Google Cloud SDK instead of App Engine SDK; + install steps use `gcloud` over `appcfg` --- .../adwords/adwords_appengine_demo/README.md | 34 ++++--------------- .../adwords/adwords_appengine_demo/app.yaml | 3 +- .../appengine_config.py | 7 ++++ .../adwords_appengine_demo/requirements.txt | 1 + 4 files changed, 16 insertions(+), 29 deletions(-) create mode 100644 examples/adwords/adwords_appengine_demo/appengine_config.py create mode 100644 examples/adwords/adwords_appengine_demo/requirements.txt diff --git a/examples/adwords/adwords_appengine_demo/README.md b/examples/adwords/adwords_appengine_demo/README.md index 1a63f2c7..87e48df6 100644 --- a/examples/adwords/adwords_appengine_demo/README.md +++ b/examples/adwords/adwords_appengine_demo/README.md @@ -44,40 +44,20 @@ prepared your OAuth2 Credentials via the Google Developers Console. This account will be used to access your AdWords credentials used in making API requests. -1. Download the latest version of the - [App Engine SDK](https://developers.google.com/appengine/downloads) and - unpack its content. This demo should be compatible with v1.9.11+. +1. Install Google Cloud SDK (https://cloud.google.com/appengine/docs/flexible/python/download). -1. Install googleads with the following command: + `$ curl --capath /etc/ssl/certs https://sdk.cloud.google.com | bash` - `$ pip install googleads` +1. Install googleads with the following command, executed from this file's + parent directory: + + `$ pip install -r requirements.txt lib` Then copy the googleads package from your Python installation's dist-packages directory into this project. The installation of googleads should also have installed the dependencies referred to in the following steps. -1. Copy the httplib2 package from your Python installation's dist-packages - directory into this project. - -1. Copy the oauth2client package from your Python installation's dist-packages - directory into this project. - -1. Copy the pyasn1 package from your Python installation's dist-packages - directory into this project. - -1. Copy socks.py from the PySocks tarball found in your Python installation's - dist-packages directory into this project. - -1. Copy the rsa package from your Python installation's dist-packages - into this project. - -1. Copy the suds package from your Python installation's dist-packages - into this project. - -1. Copy xmltodict.py from your Python installation's dist-packages directory - directory into this project. - 1. Create an App Engine application in the [Google App Engine Console](https://appengine.google.com/). @@ -86,7 +66,7 @@ prepared your OAuth2 Credentials via the Google Developers Console. 1. You can now deploy this project by running the following command: - `python $APPENGINE_SDK_DIR/appcfg --oauth2 update .` + `gcloud app deploy app.yaml -v v1` 1. When you go to your App for the first time, you will need to log in and provide OAuth2 and AdWords API credentials. You can use credentials diff --git a/examples/adwords/adwords_appengine_demo/app.yaml b/examples/adwords/adwords_appengine_demo/app.yaml index 094521e9..021ea8b9 100644 --- a/examples/adwords/adwords_appengine_demo/app.yaml +++ b/examples/adwords/adwords_appengine_demo/app.yaml @@ -1,5 +1,4 @@ -application: INSERT_APP_NAME_HERE -version: 1 +service: default runtime: python27 api_version: 1 threadsafe: false diff --git a/examples/adwords/adwords_appengine_demo/appengine_config.py b/examples/adwords/adwords_appengine_demo/appengine_config.py new file mode 100644 index 00000000..841620a4 --- /dev/null +++ b/examples/adwords/adwords_appengine_demo/appengine_config.py @@ -0,0 +1,7 @@ +# appengine_config.py +import os +from google.appengine.ext import vendor + +# Add any libraries install in the "lib" folder. +vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')) + diff --git a/examples/adwords/adwords_appengine_demo/requirements.txt b/examples/adwords/adwords_appengine_demo/requirements.txt new file mode 100644 index 00000000..48187cb5 --- /dev/null +++ b/examples/adwords/adwords_appengine_demo/requirements.txt @@ -0,0 +1 @@ +googleads==7.0.0 From 131c673d537bf0c4dbabd9d6db9eab57806e2bd9 Mon Sep 17 00:00:00 2001 From: Konstantin Lebedev Date: Fri, 22 Sep 2017 20:14:45 +0300 Subject: [PATCH 089/180] Fix empty content in AdWordsReportError --- googleads/adwords.py | 10 ++++++---- tests/adwords_test.py | 14 +++++++++----- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/googleads/adwords.py b/googleads/adwords.py index 02c901a3..2c477ac6 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -1661,11 +1661,13 @@ def _DownloadReportAsStream(self, post_body, **kwargs): response.code, response.msg) return response except urllib2.HTTPError as e: + # Content from HTTPError instance can be read only one time. + error = self._ExtractError(e) if _report_logger.isEnabledFor(logging.WARNING): _report_logger.warning( 'Request Summary: %s', self._ExtractRequestSummaryFields( - request, error=e)) - raise self._ExtractError(e) + request, error=error)) + raise error def _SanitizeRequestHeaders(self, headers): """Removes sensitive data from request headers for use in logging. @@ -1708,7 +1710,7 @@ def _ExtractRequestSummaryFields(self, request, error=None): Args: request: a urllib2.Request instance. [optional] - error: a urllib2.HttpError instance used to retrieve error details. + error: a AdWordsReportError instance used to retrieve error details. Returns: A dict containing the fields to be output in the summary logs. @@ -1728,7 +1730,7 @@ def _ExtractRequestSummaryFields(self, request, error=None): if error: summary_fields['isError'] = True - summary_fields['errorMessage'] = error.read() + summary_fields['errorMessage'] = error.content else: summary_fields['isError'] = False diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 8b25b0b0..a935ff9e 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -1783,17 +1783,21 @@ def testDownloadReport_failure(self): self.marshaller.process.return_value = serialized_report + request = mock.patch(URL_REQUEST_PATH + '.Request') + logger = mock.patch('googleads.adwords._report_logger') + with mock.patch('suds.mx.Content') as mock_content: - with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: + with request as mock_request, logger as mock_logger: + mock_logger.isEnabledFor.return_value = True mock_request_instance = mock.Mock() mock_request.return_value = mock_request_instance mock_request_instance.get_full_url.return_value = 'https://google.com/' mock_request_instance.headers = {} self.opener.open.side_effect = error - self.assertRaises( - googleads.errors.AdWordsReportError, - self.report_downloader.DownloadReport, report_definition, - output_file) + + with self.assertRaises(googleads.errors.AdWordsReportError) as ex: + self.report_downloader.DownloadReport(report_definition, output_file) + self.assertEqual(ex.exception.content, report_data) mock_request.assert_called_once_with( ('https://adwords.google.com/api/adwords/reportdownload/%s' From 4eae32944734dba7fae3f4123e227b6c7ec3da85 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 22 Sep 2017 15:24:47 -0400 Subject: [PATCH 090/180] AdWords v201609 sunset. --- ChangeLog | 6 + examples/adwords/v201609/__init__.py | 15 - .../v201609/account_management/__init__.py | 15 - .../account_management/accept_service_link.py | 62 --- .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 99 ---- .../get_account_hierarchy.py | 104 ---- .../v201609/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 222 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 126 ----- ...add_expanded_text_ad_with_upgraded_urls.py | 109 ---- .../advanced_operations/add_html5_ad.py | 111 ---- .../add_responsive_display_ad.py | 91 --- .../add_universal_app_campaign.py | 216 ------- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 171 ------ .../v201609/basic_operations/__init__.py | 15 - .../v201609/basic_operations/add_ad_groups.py | 115 ---- .../v201609/basic_operations/add_campaigns.py | 128 ----- .../basic_operations/add_expanded_text_ads.py | 74 --- .../v201609/basic_operations/add_keywords.py | 92 --- .../v201609/basic_operations/get_ad_groups.py | 76 --- .../v201609/basic_operations/get_campaigns.py | 74 --- .../get_campaigns_with_awql.py | 64 --- .../basic_operations/get_expanded_text_ads.py | 90 --- .../v201609/basic_operations/get_keywords.py | 87 --- .../v201609/basic_operations/get_text_ads.py | 78 --- .../v201609/basic_operations/pause_ad.py | 61 -- .../v201609/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 58 -- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201609/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 428 -------------- .../v201609/campaign_management/add_draft.py | 81 --- ...dd_keywords_using_incremental_batch_job.py | 259 --------- .../v201609/campaign_management/add_trial.py | 116 ---- .../get_all_disapproved_ads.py | 74 --- .../get_all_disapproved_ads_with_awql.py | 63 --- .../get_campaigns_by_label.py | 85 --- .../campaign_management/graduate_trial.py | 79 --- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201609/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 120 ---- .../handle_policy_violation_error.py | 117 ---- .../adwords/v201609/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 ------ .../adwords/v201609/extensions/add_prices.py | 144 ----- .../v201609/extensions/add_site_links.py | 146 ----- .../extensions/add_site_links_using_feeds.py | 236 -------- .../adwords/v201609/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 ------------------ examples/adwords/v201609/misc/__init__.py | 15 - .../v201609/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201609/misc/upload_image.py | 66 --- .../v201609/misc/upload_media_bundle.py | 59 -- .../adwords/v201609/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 180 ------ ...aign_criterion_bid_modifier_simulations.py | 96 ---- .../get_keyword_bid_simulations.py | 81 --- .../v201609/optimization/get_keyword_ideas.py | 100 ---- .../adwords/v201609/remarketing/__init__.py | 15 - .../v201609/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 70 --- .../remarketing/add_crm_based_user_list.py | 94 ---- .../remarketing/add_rule_based_user_lists.py | 183 ------ .../upload_offline_call_conversions.py | 77 --- .../remarketing/upload_offline_conversions.py | 75 --- .../adwords/v201609/reporting/__init__.py | 15 - .../reporting/download_criteria_report.py | 61 -- .../download_criteria_report_as_stream.py | 77 --- ...oad_criteria_report_as_stream_with_awql.py | 81 --- .../download_criteria_report_as_string.py | 59 -- ...oad_criteria_report_as_string_with_awql.py | 55 -- .../download_criteria_report_with_awql.py | 59 -- .../v201609/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 230 -------- examples/adwords/v201609/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 281 ---------- .../v201609/shopping/add_product_scope.py | 104 ---- .../v201609/shopping/add_shopping_campaign.py | 125 ----- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201609/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 145 ----- .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201609/targeting/lookup_location.py | 82 --- .../advanced_operations/add_ad_customizer.py | 8 +- .../add_universal_app_campaign.py | 2 +- .../v201708/optimization/get_keyword_ideas.py | 83 +-- .../get_active_activity_groups.py | 12 +- .../update_activity_groups.py | 16 +- .../activity_service/get_active_activities.py | 12 +- .../activity_service/update_activities.py | 14 +- .../get_first_party_audience_segments.py | 12 +- .../populate_first_party_audience_segments.py | 21 +- .../update_audience_segments.py | 21 +- .../get_base_rates_for_rate_card.py | 12 +- .../base_rate_service/update_base_rates.py | 14 +- .../company_service/get_advertisers.py | 12 +- .../company_service/update_companies.py | 14 +- .../contact_service/get_uninvited_contacts.py | 12 +- .../contact_service/update_contacts.py | 14 +- ...delete_content_metadata_key_hierarchies.py | 15 +- ...update_content_metadata_key_hierarchies.py | 15 +- .../creative_service/get_image_creatives.py | 12 +- .../creative_service/update_creatives.py | 21 +- .../get_creative_sets_for_master_creative.py | 12 +- .../update_creative_set.py | 13 +- .../get_system_defined_creative_templates.py | 12 +- .../deactivate_creative_wrapper.py | 20 +- .../get_active_creative_wrappers.py | 12 +- .../update_creative_wrappers.py | 14 +- .../deactivate_all_line_item_custom_fields.py | 22 +- .../get_custom_fields_for_line_items.py | 12 +- .../update_custom_fields.py | 13 +- .../delete_custom_targeting_keys.py | 13 +- ...efined_custom_targeting_keys_and_values.py | 22 +- .../update_custom_targeting_keys.py | 14 +- .../update_custom_targeting_values.py | 13 +- .../get_exchange_rates_for_currency_code.py | 12 +- .../update_exchange_rates.py | 14 +- .../inventory_service/archive_ad_units.py | 13 +- .../inventory_service/update_ad_units.py | 13 +- .../label_service/deactivate_labels.py | 13 +- .../label_service/get_active_labels.py | 12 +- .../v201708/label_service/update_labels.py | 15 +- .../deactivate_licas.py | 20 +- .../get_licas_for_line_item.py | 12 +- .../line_item_service/activate_line_items.py | 20 +- .../get_line_items_that_need_creatives.py | 12 +- .../get_recently_updated_line_items.py | 18 +- .../target_custom_criteria.py | 14 +- .../line_item_service/update_line_items.py | 22 +- .../v201708/order_service/approve_orders.py | 17 +- .../order_service/get_orders_starting_soon.py | 31 +- .../v201708/order_service/update_orders.py | 13 +- .../get_in_progress_packages.py | 12 +- .../deactivate_placements.py | 14 +- .../get_active_placements.py | 12 +- .../get_premium_rates_for_rate_card.py | 12 +- .../update_premium_rates.py | 14 +- ...oduct_package_items_for_product_package.py | 12 +- .../get_active_product_packages.py | 12 +- .../get_products_for_product_template.py | 12 +- ...sh_programmatic_products_to_marketplace.py | 13 +- .../product_service/update_products.py | 14 +- .../activate_product_templates.py | 13 +- .../get_sponsorship_product_templates.py | 12 +- .../update_product_templates.py | 14 +- .../archive_proposal_line_items.py | 13 +- .../get_proposal_line_items_for_proposal.py | 12 +- .../update_proposal_line_items.py | 13 +- .../get_proposals_pending_approval.py | 12 +- .../request_buyers_acceptance.py | 15 +- .../submit_proposals_for_approval.py | 15 +- .../proposal_service/update_proposals.py | 14 +- .../get_recent_changes.py | 92 +-- .../get_marketplace_rate_cards.py | 12 +- ...order_reports_for_reconciliation_report.py | 13 +- ...n_report_rows_for_reconciliation_report.py | 16 +- .../report_service/run_delivery_report.py | 16 +- .../report_service/run_inventory_report.py | 16 +- .../run_report_with_custom_fields.py | 22 +- .../v201708/report_service/run_saved_query.py | 13 +- ...get_highly_requested_suggested_ad_units.py | 12 +- .../dfp/v201708/team_service/update_teams.py | 13 +- .../v201708/user_service/deactivate_users.py | 15 +- .../user_service/get_user_by_email_address.py | 12 +- .../dfp/v201708/user_service/update_users.py | 15 +- .../delete_user_team_associations.py | 21 +- .../get_user_team_associations_for_user.py | 12 +- .../update_user_team_associations.py | 15 +- .../approve_workflow_approval_requests.py | 34 +- .../get_workflow_approval_requests.py | 12 +- ...et_workflow_external_condition_requests.py | 12 +- ...er_workflow_external_condition_requests.py | 34 +- googleads/adwords.py | 55 +- googleads/common.py | 39 +- googleads/dfp.py | 4 +- tests/adwords_test.py | 57 +- tests/common_test.py | 41 +- tests/test_data/adwords_googleads.yaml | 5 + .../batch_job_util_budget_template.txt | 6 + ...h_job_util_campaign_criterion_template.txt | 7 + ...batch_job_util_campaign_label_template.txt | 2 + .../batch_job_util_invalid_request.txt | 9 + .../test_data/batch_job_util_not_request.txt | 1 + .../batch_job_util_operations_template.txt | 7 + .../batch_job_util_raw_request_template.txt | 17 + .../batch_job_util_response_template.txt | 1 + .../batch_job_util_upload_template.txt | 5 + .../compact_fault_response_envelope.txt | 8 + .../empty_fault_response_envelope.txt | 19 + tests/test_data/fault_response_envelope.txt | 25 + tests/test_data/gzip_response.bin | Bin 0 -> 394 bytes .../multi_errors_fault_response_envelope.txt | 31 ++ tests/test_data/request_envelope_template.txt | 27 + 208 files changed, 704 insertions(+), 10513 deletions(-) delete mode 100644 examples/adwords/v201609/__init__.py delete mode 100644 examples/adwords/v201609/account_management/__init__.py delete mode 100755 examples/adwords/v201609/account_management/accept_service_link.py delete mode 100755 examples/adwords/v201609/account_management/create_account.py delete mode 100755 examples/adwords/v201609/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201609/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201609/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201609/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201609/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py delete mode 100755 examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201609/basic_operations/__init__.py delete mode 100755 examples/adwords/v201609/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201609/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201609/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201609/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201609/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201609/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201609/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201609/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201609/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201609/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201609/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201609/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201609/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201609/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201609/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201609/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201609/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201609/campaign_management/__init__.py delete mode 100755 examples/adwords/v201609/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201609/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201609/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201609/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201609/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201609/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201609/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201609/error_handling/__init__.py delete mode 100755 examples/adwords/v201609/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201609/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201609/extensions/__init__.py delete mode 100755 examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201609/extensions/add_prices.py delete mode 100755 examples/adwords/v201609/extensions/add_site_links.py delete mode 100755 examples/adwords/v201609/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201609/migration/__init__.py delete mode 100755 examples/adwords/v201609/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201609/misc/__init__.py delete mode 100755 examples/adwords/v201609/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201609/misc/upload_image.py delete mode 100755 examples/adwords/v201609/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201609/optimization/__init__.py delete mode 100755 examples/adwords/v201609/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201609/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201609/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201609/remarketing/__init__.py delete mode 100755 examples/adwords/v201609/remarketing/add_audience.py delete mode 100755 examples/adwords/v201609/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201609/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201609/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201609/remarketing/upload_offline_call_conversions.py delete mode 100755 examples/adwords/v201609/remarketing/upload_offline_conversions.py delete mode 100644 examples/adwords/v201609/reporting/__init__.py delete mode 100755 examples/adwords/v201609/reporting/download_criteria_report.py delete mode 100755 examples/adwords/v201609/reporting/download_criteria_report_as_stream.py delete mode 100755 examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201609/reporting/download_criteria_report_as_string.py delete mode 100755 examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201609/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201609/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201609/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201609/shopping/__init__.py delete mode 100755 examples/adwords/v201609/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201609/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201609/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201609/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201609/targeting/__init__.py delete mode 100755 examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201609/targeting/lookup_location.py create mode 100644 tests/test_data/adwords_googleads.yaml create mode 100644 tests/test_data/batch_job_util_budget_template.txt create mode 100644 tests/test_data/batch_job_util_campaign_criterion_template.txt create mode 100644 tests/test_data/batch_job_util_campaign_label_template.txt create mode 100644 tests/test_data/batch_job_util_invalid_request.txt create mode 100644 tests/test_data/batch_job_util_not_request.txt create mode 100644 tests/test_data/batch_job_util_operations_template.txt create mode 100644 tests/test_data/batch_job_util_raw_request_template.txt create mode 100644 tests/test_data/batch_job_util_response_template.txt create mode 100644 tests/test_data/batch_job_util_upload_template.txt create mode 100644 tests/test_data/compact_fault_response_envelope.txt create mode 100644 tests/test_data/empty_fault_response_envelope.txt create mode 100644 tests/test_data/fault_response_envelope.txt create mode 100644 tests/test_data/gzip_response.bin create mode 100644 tests/test_data/multi_errors_fault_response_envelope.txt create mode 100644 tests/test_data/request_envelope_template.txt diff --git a/ChangeLog b/ChangeLog index 1f081cd8..d8b93fd0 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +8.0.0 -- 8/22/17 +* Removed support and examples for AdWords v201609. +* Resolved issues: +- Issue 219: https://github.com/googleads/googleads-python-lib/issues/219 +- Issue 220: https://github.com/googleads/googleads-python-lib/issues/220 + 7.0.0 -- 8/15/17 * Added support and examples for DFP v201708. * Removed support and examples for DFP v201608. diff --git a/examples/adwords/v201609/__init__.py b/examples/adwords/v201609/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201609/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201609/account_management/__init__.py b/examples/adwords/v201609/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201609/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201609/account_management/accept_service_link.py b/examples/adwords/v201609/account_management/accept_service_link.py deleted file mode 100755 index 3879171d..00000000 --- a/examples/adwords/v201609/account_management/accept_service_link.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' - - -def main(client, service_link_id): - # Initialize appropriate service. - customer_service = client.GetService( - 'CustomerService', version='v201609') - - # Create the operation to set the status to ACTIVE. - operations = [{ - 'operator': 'SET', - 'operand': { - 'serviceLinkId': service_link_id, - 'serviceType': 'MERCHANT_CENTER', - 'linkStatus': 'ACTIVE', - } - }] - - # Update the service link. - mutated_service_links = customer_service.mutateServiceLinks(operations) - - # Display results. - for mutated_service_link in mutated_service_links: - print ('Service link with service link ID "%s", type "%s" was updated ' - 'to status: "%s".' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201609/account_management/create_account.py b/examples/adwords/v201609/account_management/create_account.py deleted file mode 100755 index 08d431aa..00000000 --- a/examples/adwords/v201609/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201609') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID "%s" was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/account_management/get_account_changes.py b/examples/adwords/v201609/account_management/get_account_changes.py deleted file mode 100755 index 5eed06f3..00000000 --- a/examples/adwords/v201609/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201609') - campaign_service = client.GetService('CampaignService', version='v201609') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id "%s" has change status "%s".' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id "%s" has change status "%s".' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/account_management/get_account_hierarchy.py b/examples/adwords/v201609/account_management/get_account_hierarchy.py deleted file mode 100755 index ef7e6ffe..00000000 --- a/examples/adwords/v201609/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201609') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/advanced_operations/__init__.py b/examples/adwords/v201609/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201609/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py b/examples/adwords/v201609/advanced_operations/add_ad_customizer.py deleted file mode 100755 index bed81b79..00000000 --- a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates ExpandedTextAds that use ad customizations for specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no ExpandedTextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201609') - - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'headlinePart2': 'Only {=%s.Price}' % feed_name, - 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': expanded_text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID "%s", type "%s", and status "%s".' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201609') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name "%s" and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201609') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index a14d1440..00000000 --- a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201609') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index cbf0f447..00000000 --- a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Optionally, you may specify a landscape image. The image needs to be in a - # BASE64 encoded form. Here we download a demo image and encode it for this - # ad. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - }, - { - 'name': 'landscapeImage', - 'fieldMedia': { - 'xsi_type': 'Image', - 'data': image_data - }, - 'type': 'IMAGE' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py deleted file mode 100755 index 453bca8f..00000000 --- a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Create the expanded text ad - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': expanded_text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_html5_ad.py b/examples/adwords/v201609/advanced_operations/add_html5_ad.py deleted file mode 100755 index ff814915..00000000 --- a/examples/adwords/v201609/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index 82f1def5..00000000 --- a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - media_service = client.GetService('MediaService', version='v201609') - - try: - # Create image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - # Make the upload request - image = media_service.upload(image)[0] - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'] - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py deleted file mode 100755 index b10e292d..00000000 --- a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Universal App campaign. - -To get campaigns, run get_campaigns.py. To upload image assets for this -campaign, run upload_image.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201609') - - budget_id = CreateBudget(client) - - # Create the Universal App campaign. - universal_app_campaign = { - 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'MULTI_CHANNEL', - 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', - # Set the campaign's bidding strategy. Universal app campaigns only - # support TARGET_CPA bidding strategy. - 'biddingStrategyConfiguration': { - # Set the target CPA to $1 / app install. - 'biddingScheme': { - 'xsi_type': 'TargetCpaBiddingScheme', - 'targetCpa': { - 'microAmount': '1000000' - } - }, - 'biddingStrategyType': 'TARGET_CPA' - }, - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - - universal_app_campaign['settings'] = [ - # Set the campaign's assets and ad text ideas. These values will - # be used to generate ads. - { - 'xsi_type': 'UniversalAppCampaignSetting', - 'appId': 'com.interplanetarycruise.booking', - 'description1': 'Best Space Cruise Line', - 'description2': 'Visit all the planets', - 'description3': 'Trips 7 days a week', - 'description4': 'Buy your tickets now!', - # Optional: You can set up to 10 image assets for your campaign. - # See upload_image.py for an example on how to upload images. - # - # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] - } - ] - - # Optimize this campaign for getting new users for your app. - universal_app_campaign_setting = universal_app_campaign['settings'][0] - universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( - 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') - - # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, - # then also specify your in-app conversion types so AdWords can focus your - # campaign on people who are most likely to complete the corresponding in-app - # actions. - # - # Conversions type IDs can be retrieved using ConversionTrackerService.get. - # universal_app_campaign['selectiveOptimization'] = { - # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] - # } - - # Optional: Set the campaign settings for Advanced location options. - universal_app_campaign['settings'].append({ - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - }) - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': universal_app_campaign - }] - - campaigns = campaign_service.mutate(operations)['value'] - - # Display results. - if campaigns: - for campaign in campaigns: - print ('Universal App Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - # Optional: Set the campaign's location and language targeting. No other - # targeting criteria can be used for Universal App campaigns. - SetCampaignTargetingCriteria(client, campaign) - else: - print 'No Universal App campaigns were added.' - - -def CreateBudget(client): - """Creates a budget and returns its budgetId. - - Args: - client: An AdWordsClient instance. - - Returns: - An int budgetId for the created Budget. - """ - budget_service = client.GetService('BudgetService', version='v201609') - - # Create a budget. - budget = { - 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': False - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Create the budget and return its ID. - budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - - return budget_id - -def SetCampaignTargetingCriteria(client, campaign): - """Sets targeting criteria for the given campaign. - - Args: - client: An AdWordsClient instance. - campaign: A suds object representing the campaign we wish to attach - targeting criteria. - """ - campaign_criterion_service = client.GetService('CampaignCriterionService') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - criteria = [ - { - 'xsi_type': 'Location', - 'id': 21137 # California - }, - { - 'xsi_type': 'Location', - 'id': 2484 # Mexico - }, - { - 'xsi_type': 'Language', - 'id': 1000 # English - }, - { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - ] - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign['id'], - 'criterion': criterion - } - } for criterion in criteria] - - response = campaign_criterion_service.mutate(operations) - - if response and 'value' in response: - # Display the added campaign targets. - for criterion in response['value']: - print ('Campaign criteria of type "%s" and id "%s" was added.' - % (criterion['criterion']['type'], - criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 37033b06..00000000 --- a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201609') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201609') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201609') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index 59f7da6f..00000000 --- a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201609') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201609') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 9c183775..00000000 --- a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201609') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index c3d1d76c..00000000 --- a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201609') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201609') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201609/basic_operations/__init__.py b/examples/adwords/v201609/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201609/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201609/basic_operations/add_ad_groups.py b/examples/adwords/v201609/basic_operations/add_ad_groups.py deleted file mode 100755 index 79f2a17c..00000000 --- a/examples/adwords/v201609/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201609') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/basic_operations/add_campaigns.py b/examples/adwords/v201609/basic_operations/add_campaigns.py deleted file mode 100755 index c39df642..00000000 --- a/examples/adwords/v201609/basic_operations/add_campaigns.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201609') - budget_service = client.GetService('BudgetService', version='v201609') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index 4d5221db..00000000 --- a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/add_keywords.py b/examples/adwords/v201609/basic_operations/add_keywords.py deleted file mode 100755 index 1e1ab69c..00000000 --- a/examples/adwords/v201609/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id "%s", criterion id ' - '"%s", text "%s", and match type "%s" was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/get_ad_groups.py b/examples/adwords/v201609/basic_operations/get_ad_groups.py deleted file mode 100755 index a345fec7..00000000 --- a/examples/adwords/v201609/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201609') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name "%s", id "%s" and status "%s" was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/basic_operations/get_campaigns.py b/examples/adwords/v201609/basic_operations/get_campaigns.py deleted file mode 100755 index 196e52c7..00000000 --- a/examples/adwords/v201609/basic_operations/get_campaigns.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 07508aa4..00000000 --- a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index c4d9a2f5..00000000 --- a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/get_keywords.py b/examples/adwords/v201609/basic_operations/get_keywords.py deleted file mode 100755 index 11073cf3..00000000 --- a/examples/adwords/v201609/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID "%s", type "%s", text "%s", and match type ' - '"%s" was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/get_text_ads.py b/examples/adwords/v201609/basic_operations/get_text_ads.py deleted file mode 100755 index fc926c40..00000000 --- a/examples/adwords/v201609/basic_operations/get_text_ads.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 text ads for a given ad group. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id "%s", status "%s", and of type "%s" was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/pause_ad.py b/examples/adwords/v201609/basic_operations/pause_ad.py deleted file mode 100755 index 06cadaa2..00000000 --- a/examples/adwords/v201609/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id "%s" was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201609/basic_operations/remove_ad.py b/examples/adwords/v201609/basic_operations/remove_ad.py deleted file mode 100755 index f7e637c4..00000000 --- a/examples/adwords/v201609/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id "%s" and type "%s" was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201609/basic_operations/remove_ad_group.py b/examples/adwords/v201609/basic_operations/remove_ad_group.py deleted file mode 100755 index da407601..00000000 --- a/examples/adwords/v201609/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201609') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name "%s" and id "%s" was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/remove_campaign.py b/examples/adwords/v201609/basic_operations/remove_campaign.py deleted file mode 100755 index 8c66adf9..00000000 --- a/examples/adwords/v201609/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name "%s" and id "%s" was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/basic_operations/remove_keyword.py b/examples/adwords/v201609/basic_operations/remove_keyword.py deleted file mode 100755 index 3887fcb5..00000000 --- a/examples/adwords/v201609/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id "%s", criterion id "%s", ' - 'and type "%s" was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201609/basic_operations/update_ad_group.py b/examples/adwords/v201609/basic_operations/update_ad_group.py deleted file mode 100755 index bef260f5..00000000 --- a/examples/adwords/v201609/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201609') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/basic_operations/update_campaign.py b/examples/adwords/v201609/basic_operations/update_campaign.py deleted file mode 100755 index ca7eb9d5..00000000 --- a/examples/adwords/v201609/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/basic_operations/update_keyword.py b/examples/adwords/v201609/basic_operations/update_keyword.py deleted file mode 100755 index 36e38f72..00000000 --- a/examples/adwords/v201609/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id "%s" and criterion id ' - '"%s" currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: "%s", value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201609/campaign_management/__init__.py b/examples/adwords/v201609/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201609/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201609/campaign_management/add_campaign_labels.py b/examples/adwords/v201609/campaign_management/add_campaign_labels.py deleted file mode 100755 index 7020658e..00000000 --- a/examples/adwords/v201609/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index 60e3ce09..00000000 --- a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,428 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201609') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201609') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding an ExpandedTextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new ExpandedTextAd for - each of the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once - # you've added targeting and the ads are ready to serve. - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201609') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201609/campaign_management/add_draft.py b/examples/adwords/v201609/campaign_management/add_draft.py deleted file mode 100755 index e04ddbf5..00000000 --- a/examples/adwords/v201609/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201609') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201609') - - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index d9a2bfb5..00000000 --- a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201609') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201609') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201609') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201609') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201609/campaign_management/add_trial.py b/examples/adwords/v201609/campaign_management/add_trial.py deleted file mode 100755 index f5af4a13..00000000 --- a/examples/adwords/v201609/campaign_management/add_trial.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201609') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201609') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 2272b149..00000000 --- a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id "%s" was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index fb18eef5..00000000 --- a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id "%s" was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 08b365b3..00000000 --- a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id "%s", name "%s", and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201609/campaign_management/graduate_trial.py b/examples/adwords/v201609/campaign_management/graduate_trial.py deleted file mode 100755 index 6888c53a..00000000 --- a/examples/adwords/v201609/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201609') - budget_service = client.GetService('BudgetService', version='v201609') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201609/campaign_management/set_ad_parameters.py b/examples/adwords/v201609/campaign_management/set_ad_parameters.py deleted file mode 100755 index 9013f36d..00000000 --- a/examples/adwords/v201609/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - ad_param_service = client.GetService('AdParamService', version='v201609') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id "%s" was successfully added to an ad group with ' - 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text "%s" was successfully set for criterion ' - 'with id "%s" and ad group id "%s".' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index 30c5734c..00000000 --- a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201609') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' - 'was updated with bid modifier "%s".' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201609/campaign_management/validate_text_ad.py b/examples/adwords/v201609/campaign_management/validate_text_ad.py deleted file mode 100755 index 3c2c3d39..00000000 --- a/examples/adwords/v201609/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -No objects will be created, but exceptions will still be returned. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct operations to add an expanded text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'] - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for all astronauts in orbit', - 'finalUrls': ['http://www.example.com'], - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with "%s".' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/error_handling/__init__.py b/examples/adwords/v201609/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201609/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201609/error_handling/handle_partial_failures.py b/examples/adwords/v201609/error_handling/handle_partial_failures.py deleted file mode 100755 index 6d2e7f3d..00000000 --- a/examples/adwords/v201609/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id "%s", ' - 'criterion id "%s", text "%s", and match type "%s" was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id "%s" and text ' - '"%s" triggered a failure for the following reason: "%s".' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) - else: - print 'The following failure has occurred: "%s".' % error['errorString'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py deleted file mode 100755 index ec6cda1a..00000000 --- a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201609') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - index = int(operation_index[0]) - operation = operations[index] - print ('Ad with headline "%s" violated %s policy "%s".' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name "%s" on text ' - '"%s".' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Set non-exemptable operation to None to mark for deletion - print 'Removing the operation from the request.' - operations[index] = None - else: - # Non-policy error returned, re-throw exception. - raise e - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is "%s".' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/extensions/__init__.py b/examples/adwords/v201609/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201609/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 80ee4f96..00000000 --- a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201609').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201609') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201609/extensions/add_prices.py b/examples/adwords/v201609/extensions/add_prices.py deleted file mode 100755 index 771c6615..00000000 --- a/examples/adwords/v201609/extensions/add_prices.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a price extension and associates it with an account. - -Campaign targeting is also set usin the specified campaign ID. To get campaigns, -run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -MICROS_PER_DOLLAR = 1000000 - - -def main(client, campaign_id): - # Initialize appropriate service. - customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201609') - - # To create a price extension, at least three table rows are needed. - table_rows = [ - CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', - 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR'), - CreatePriceTableRow('Hair Cuts', 'Once a month', - 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH'), - CreatePriceTableRow('Skin Care Package', 'Four times a month', - 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH') - ] - - # Create the price extension feed item. - customer_extension_setting = { - 'extensionType': 'PRICE', - 'extensionSetting': { - 'extensions': [{ - 'priceExtensionType': 'SERVICES', - 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', - 'language': 'en', - 'campaignTargeting': { - 'TargetingCampaignId': campaign_id - }, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': 'SATURDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 22, - 'endMinute': 'ZERO' - }, - { - 'dayOfWeek': 'SUNDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 18, - 'endMinute': 'ZERO' - } - ] - }, - 'tableRows': table_rows, - # Price qualifier is optional. - 'priceQualifier': 'FROM', - 'xsi_type': 'PriceFeedItem' - }] - } - } - - # Create an operation to add the feed. - operations = [{ - 'operator': 'ADD', - 'operand': customer_extension_setting - }] - - # Add the price extension. - response = customer_extension_setting_service.mutate(operations) - - # Print the results. - if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit): - """Helper function to generate a single row of a price table. - - Args: - header: A str containing the header text of this row. - description: A str description of this row in the price table. - final_url: A str containing the final URL after all cross domain redirects. - price_in_micros: An int indicating the price of the given currency in - micros. - currency_code: A str indicating the currency code being used. - price_unit: A str enum indicating the price unit for this row. - - Returns: - A dictionary containing the contents of the generated price table row. - """ - return { - 'header': header, - 'description': description, - 'finalUrls': {'urls': [final_url]}, - 'price': { - 'money': { - 'microAmount': price_in_micros, - }, - 'currencyCode': currency_code - }, - 'priceUnit': price_unit, - 'xsi_type': 'PriceTableRow' - } - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/extensions/add_site_links.py b/examples/adwords/v201609/extensions/add_site_links.py deleted file mode 100755 index 65806e36..00000000 --- a/examples/adwords/v201609/extensions/add_site_links.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201609') - customer_service = client.GetService('CustomerService', version='v201609') - # Find the matching customer and its time zone. The getCustomers method will - # return a single Customer object corresponding to the configured - # clientCustomerId. - customer = customer_service.getCustomers()[0] - customer_tz = timezone(customer['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840}, - # Restrict targeting only to people physically within the United States. - # Otherwise, this could also show to people interested in the United - # States, but not physically located there. - 'geoTargetingRestriction': { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py b/examples/adwords/v201609/extensions/add_site_links_using_feeds.py deleted file mode 100755 index 83eae4ae..00000000 --- a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_2_TEXT = '3' -PLACEHOLDER_FIELD_LINE_3_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201609') - feed_item_service = client.GetService('FeedItemService', version='v201609') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201609') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201609') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 2 Description'}, - {'type': 'STRING', 'name': 'Line 3 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_2_feed_attribute_id = feed['attributes'][2]['id'] - line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name "%s" and ID "%s" was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - sitelinks_data['line3FeedId'] = line_3_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line2': 'Home line 2', 'line3': 'Home line 3'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line2': 'Support line 2', 'line3': 'Support line 3'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line2': 'Products line 2', 'line3': 'Products line 3'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'stringValue': item['line3'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - feed_item['geoTargetingRestriction'] = { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/migration/__init__.py b/examples/adwords/v201609/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201609/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201609/migration/migrate_to_extension_settings.py b/examples/adwords/v201609/migration/migrate_to_extension_settings.py deleted file mode 100755 index 9cbbdc17..00000000 --- a/examples/adwords/v201609/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201609') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201609') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201609') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201609') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201609') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201609') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201609') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/misc/__init__.py b/examples/adwords/v201609/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201609/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201609/misc/get_all_images_and_videos.py b/examples/adwords/v201609/misc/get_all_images_and_videos.py deleted file mode 100755 index eabf2367..00000000 --- a/examples/adwords/v201609/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201609') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id "%s" was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/misc/upload_image.py b/examples/adwords/v201609/misc/upload_image.py deleted file mode 100755 index fa4bbe52..00000000 --- a/examples/adwords/v201609/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201609') - - with open(image_filename, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201609/misc/upload_media_bundle.py b/examples/adwords/v201609/misc/upload_media_bundle.py deleted file mode 100755 index fee2cc1b..00000000 --- a/examples/adwords/v201609/misc/upload_media_bundle.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201609') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - return base64.b64encode(response.read()) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/optimization/__init__.py b/examples/adwords/v201609/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201609/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py b/examples/adwords/v201609/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 70c3ea73..00000000 --- a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201609') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index 4a6039d6..00000000 --- a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201609') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index 6305dce5..00000000 --- a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201609') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id "%s", criterion id ' - '"%s", start date "%s", end date "%s", with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201609/optimization/get_keyword_ideas.py b/examples/adwords/v201609/optimization/get_keyword_ideas.py deleted file mode 100755 index 3f2cfc5f..00000000 --- a/examples/adwords/v201609/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201609') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with "%s" text and average monthly search volume ' - '"%s" was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/__init__.py b/examples/adwords/v201609/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201609/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201609/remarketing/add_audience.py b/examples/adwords/v201609/remarketing/add_audience.py deleted file mode 100755 index 9945364d..00000000 --- a/examples/adwords/v201609/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201609') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201609') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name "%s" and ID "%s" was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/add_conversion_tracker.py b/examples/adwords/v201609/remarketing/add_conversion_tracker.py deleted file mode 100755 index 44ef43f1..00000000 --- a/examples/adwords/v201609/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201609') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" and snippet \n"%s"\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py b/examples/adwords/v201609/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 75b54471..00000000 --- a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client, emails): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201609') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. - - Args: - emails: list of str emails to be hashed. - - Returns: - A list of SHA-256 hashed emails. - """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] - - -if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) diff --git a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 9833ba06..00000000 --- a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201609') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py deleted file mode 100755 index d8efc864..00000000 --- a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for calls related to ads in your account. - -To set up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CALLER_ID = 'INSERT_CALLER_ID_HERE' -# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats -# For time zones, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -CALL_START_TIME = 'INSERT_CALL_START_TIME' -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, caller_id, call_start_time, conversion_name, conversion_time, - conversion_value): - # Initialize appropriate services. - occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201609') - - # Associate offline call conversions with the existing named conversion - # tracker. If this tracker was newly created, it may be a few hours before it - # can accept conversions. - feed = { - 'callerId': caller_id, - 'callStartTime': call_start_time, - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - } - - occ_operations = [{'operator': 'ADD', 'operand': feed}] - - occ_response = occ_feed_service.mutate(occ_operations) - values = occ_response['value'] - - if values: - for occ_feed in values: - print ('Uploaded offline call conversion value of "%s" for caller ID ' - '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) - else: - print 'No offline call conversions were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, - CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201609/remarketing/upload_offline_conversions.py b/examples/adwords/v201609/remarketing/upload_offline_conversions.py deleted file mode 100755 index 80704387..00000000 --- a/examples/adwords/v201609/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201609') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of "%s" for Google Click ID ' - '"%s" to "%s".' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201609/reporting/__init__.py b/examples/adwords/v201609/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201609/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201609/reporting/download_criteria_report.py b/examples/adwords/v201609/reporting/download_criteria_report.py deleted file mode 100755 index 993e67c6..00000000 --- a/examples/adwords/v201609/reporting/download_criteria_report.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201609') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py deleted file mode 100755 index 3beaf5ed..00000000 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201609') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 0514d0ff..00000000 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201609') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string.py deleted file mode 100755 index fd34b76f..00000000 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201609') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index c482909a..00000000 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201609') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 3ec66566..00000000 --- a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201609') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - print 'Report was downloaded to "%s".' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201609/reporting/get_report_fields.py b/examples/adwords/v201609/reporting/get_report_fields.py deleted file mode 100755 index 90720035..00000000 --- a/examples/adwords/v201609/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201609') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type "%s" contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201609/reporting/parallel_report_download.py b/examples/adwords/v201609/reporting/parallel_report_download.py deleted file mode 100755 index 136080f4..00000000 --- a/examples/adwords/v201609/reporting/parallel_report_download.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import logging -import multiprocessing -from Queue import Empty -import time -import googleads - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - client: An AdWordsClient instance. - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201609') - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = self._DownloadReport(customer_id) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - - Raises: - Exception: if no CustomerIds could be found. - - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201609') - - offset = 0 - - # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201609/shopping/__init__.py b/examples/adwords/v201609/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201609/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201609/shopping/add_product_partition_tree.py b/examples/adwords/v201609/shopping/add_product_partition_tree.py deleted file mode 100755 index 595c9d20..00000000 --- a/examples/adwords/v201609/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201609/shopping/add_product_scope.py b/examples/adwords/v201609/shopping/add_product_scope.py deleted file mode 100755 index 0e1a0db0..00000000 --- a/examples/adwords/v201609/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201609') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/shopping/add_shopping_campaign.py b/examples/adwords/v201609/shopping/add_shopping_campaign.py deleted file mode 100755 index 6549b688..00000000 --- a/examples/adwords/v201609/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201609') - ad_group_service = client.GetService('AdGroupService', version='v201609') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py b/examples/adwords/v201609/shopping/get_product_category_taxonomy.py deleted file mode 100755 index e2143ef4..00000000 --- a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201609') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/targeting/__init__.py b/examples/adwords/v201609/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201609/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 25dc2cce..00000000 --- a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201609') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish, florida_tier3] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s", criterion id "%s", ' - 'and type "%s" was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 512f489b..00000000 --- a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type "%s" was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index bf4bf0f0..00000000 --- a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201609') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index c96c4d82..00000000 --- a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201609') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name "%s" and ID "%s" was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name "%s", ID "%s", and country code "%s" was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201609/targeting/lookup_location.py b/examples/adwords/v201609/targeting/lookup_location.py deleted file mode 100755 index 8c5d76fa..00000000 --- a/examples/adwords/v201609/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201609') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term "%s" returned the location "%s" of type "%s"' - ' with parent locations "%s", reach "%s" and id "%s" (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/add_ad_customizer.py b/examples/adwords/v201708/advanced_operations/add_ad_customizer.py index a30054cb..2c72f3bf 100755 --- a/examples/adwords/v201708/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201708/advanced_operations/add_ad_customizer.py @@ -92,7 +92,6 @@ def CreateCustomizerFeed(client, feed_name): # Get the AdCustomizerFeedService ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', 'v201708') - customizer_feed = { 'feedName': feed_name, 'feedAttributes': [ @@ -204,7 +203,12 @@ def CreateFeedItemAddOperation(name, price, date, adgroup_id, ] } - return {'operator': 'ADD', 'operand': feed_item} + operation = { + 'operator': 'ADD', + 'operand': feed_item + } + + return operation def main(client, adgroup_ids, feed_name=FEED_NAME): diff --git a/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py index 8a58b41a..f0d9f1f5 100755 --- a/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py @@ -80,7 +80,7 @@ def main(client): 'description2': 'Remove connected blocks', 'description3': '3 difficulty levels', 'description4': '4 colorful fun skins', - # Optional: You can set up to 10 image assets for your campaign. + # Optional: You can set up to 20 image assets for your campaign. # See upload_image.py for an example on how to upload images. # # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] diff --git a/examples/adwords/v201708/optimization/get_keyword_ideas.py b/examples/adwords/v201708/optimization/get_keyword_ideas.py index 2afa7bb8..2d195173 100755 --- a/examples/adwords/v201708/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201708/optimization/get_keyword_ideas.py @@ -26,49 +26,62 @@ from googleads import adwords +# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' PAGE_SIZE = 100 -def main(client): +def main(client, ad_group_id=None): # Initialize appropriate service. targeting_idea_service = client.GetService( 'TargetingIdeaService', version='v201708') # Construct selector object and retrieve related keywords. - offset = 0 selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } + 'requestType': 'IDEAS' + } + + selector['requestedAttributeTypes'] = [ + 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] + + offset = 0 + selector['paging'] = { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) } + + selector['searchParameters'] = [{ + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }] + + # Language setting (optional). + selector['searchParameters'].append({ + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }) + + # Network search parameter (optional) + selector['searchParameters'].append({ + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + }) + + # Use an existing ad group to generate ideas (optional) + if ad_group_id is not None: + selector['searchParameters'].append({ + 'xsi_type': 'SeedAdGroupIdSearchParameter', + 'adGroupId': ad_group_id + }) + more_pages = True while more_pages: page = targeting_idea_service.get(selector) @@ -78,8 +91,8 @@ def main(client): for result in page['entries']: attributes = {} for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') + attributes[attribute['key']] = getattr( + attribute['value'], 'value', '0') print ('Keyword with "%s" text and average monthly search volume ' '"%s" was found with Products and Services categories: %s.' % (attributes['KEYWORD_TEXT'], @@ -97,4 +110,4 @@ def main(client): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) + main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py index 25819435..b27e5d58 100755 --- a/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( 'ActivityGroupService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select activity groups. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/dfp/v201708/activity_group_service/update_activity_groups.py b/examples/dfp/v201708/activity_group_service/update_activity_groups.py index b7b26734..7d8fd136 100755 --- a/examples/dfp/v201708/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201708/activity_group_service/update_activity_groups.py @@ -40,17 +40,10 @@ def main(client, activity_group_id, advertiser_company_id): version='v201708') # Create statement object to select a single activity groups by ID. - values = [{ - 'key': 'activityGroupId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_group_id - } - }] - query = 'WHERE id = :activityGroupId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityGroupId') + .WithBindVariable('activityGroupId', long(activity_group_id)) + .Limit(1)) # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( @@ -70,6 +63,7 @@ def main(client, activity_group_id, advertiser_company_id): else: print 'No activity groups found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/activity_service/get_active_activities.py b/examples/dfp/v201708/activity_service/get_active_activities.py index fb1479c8..94d18be9 100755 --- a/examples/dfp/v201708/activity_service/get_active_activities.py +++ b/examples/dfp/v201708/activity_service/get_active_activities.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. activity_service = client.GetService('ActivityService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select activities. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/dfp/v201708/activity_service/update_activities.py b/examples/dfp/v201708/activity_service/update_activities.py index 9fab0a5f..851a411e 100755 --- a/examples/dfp/v201708/activity_service/update_activities.py +++ b/examples/dfp/v201708/activity_service/update_activities.py @@ -38,15 +38,10 @@ def main(client, activity_id): activity_service = client.GetService('ActivityService', version='v201708') # Create statement object to select one activity by ID to update. - values = [{ - 'key': 'activityId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_id - } - }] - query = 'WHERE id = :activityId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityId') + .WithBindVariable('activityId', long(activity_id)) + .Limit(1)) # Get activities by statement. response = activity_service.getActivitiesByStatement( @@ -66,6 +61,7 @@ def main(client, activity_id): else: print 'No activities found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py index 12e3fc76..a7bf8ee2 100755 --- a/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - }}, - ] # Create a statement to select audience segments. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'FIRST_PARTY')) # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py index affc42f5..1f74c70a 100755 --- a/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py @@ -33,21 +33,12 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201708') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201708/audience_segment_service/update_audience_segments.py b/examples/dfp/v201708/audience_segment_service/update_audience_segments.py index 4e697e4e..34270902 100755 --- a/examples/dfp/v201708/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/update_audience_segments.py @@ -32,21 +32,12 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201708') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) # Get audience segments by statement. response = audience_segment_service.getAudienceSegmentsByStatement( diff --git a/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py index 944b1f69..f4528e2a 100755 --- a/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py @@ -25,16 +25,10 @@ def main(client, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService('BaseRateService', version='v201708') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] # Create a statement to select base rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/dfp/v201708/base_rate_service/update_base_rates.py b/examples/dfp/v201708/base_rate_service/update_base_rates.py index cca97a1f..1d88d78f 100755 --- a/examples/dfp/v201708/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201708/base_rate_service/update_base_rates.py @@ -32,15 +32,11 @@ def main(client, base_rate_id): base_rate_service = client.GetService('BaseRateService', version='v201708') # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': base_rate_id - } - }] - query = 'where id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', long(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( diff --git a/examples/dfp/v201708/company_service/get_advertisers.py b/examples/dfp/v201708/company_service/get_advertisers.py index 4f32da18..03ea7369 100755 --- a/examples/dfp/v201708/company_service/get_advertisers.py +++ b/examples/dfp/v201708/company_service/get_advertisers.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. company_service = client.GetService('CompanyService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - }}, - ] # Create a statement to select companies. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'ADVERTISER')) # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/dfp/v201708/company_service/update_companies.py b/examples/dfp/v201708/company_service/update_companies.py index d4678799..c515a0e5 100755 --- a/examples/dfp/v201708/company_service/update_companies.py +++ b/examples/dfp/v201708/company_service/update_companies.py @@ -38,15 +38,10 @@ def main(client, company_id): company_service = client.GetService('CompanyService', version='v201708') # Create statement object to only select a single company by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': company_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(company_id)) + .Limit(1)) # Get companies by statement. response = company_service.getCompaniesByStatement( @@ -68,6 +63,7 @@ def main(client, company_id): else: print 'No companies found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/contact_service/get_uninvited_contacts.py b/examples/dfp/v201708/contact_service/get_uninvited_contacts.py index 730aaa96..e67bd402 100755 --- a/examples/dfp/v201708/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201708/contact_service/get_uninvited_contacts.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. contact_service = client.GetService('ContactService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - }}, - ] # Create a statement to select contacts. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'UNINVITED')) # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/dfp/v201708/contact_service/update_contacts.py b/examples/dfp/v201708/contact_service/update_contacts.py index b98d25f1..1a14eb95 100755 --- a/examples/dfp/v201708/contact_service/update_contacts.py +++ b/examples/dfp/v201708/contact_service/update_contacts.py @@ -38,15 +38,10 @@ def main(client, contact_id): contact_service = client.GetService('ContactService', version='v201708') # Create statement object to select the single contact by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': contact_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(contact_id)) + .Limit(1)) # Get contacts by statement. response = contact_service.getContactsByStatement( @@ -69,6 +64,7 @@ def main(client, contact_id): else: print 'No contacts found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 95899906..54e36cb6 100755 --- a/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -43,16 +43,12 @@ def main(client, content_metadata_key_hierarchy_id): 'ContentMetadataKeyHierarchyService', version='v201708') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -78,6 +74,7 @@ def main(client, content_metadata_key_hierarchy_id): print ('Number of content metadata key hierarchies deleted: %s' % result['numChanges']) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index e276a2d6..253fbd5a 100755 --- a/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -45,16 +45,12 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): 'ContentMetadataKeyHierarchyService', version='v201708') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -90,6 +86,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): else: print 'No content metadata key hierarchies were found' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/creative_service/get_image_creatives.py b/examples/dfp/v201708/creative_service/get_image_creatives.py index a90f06bf..fc099545 100755 --- a/examples/dfp/v201708/creative_service/get_image_creatives.py +++ b/examples/dfp/v201708/creative_service/get_image_creatives.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. creative_service = client.GetService('CreativeService', version='v201708') - query = 'WHERE creativeType = :creativeType' - values = [ - {'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': '_image_creative' - }}, - ] # Create a statement to select creatives. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('creativeType = :creativeType') + .WithBindVariable('creativeType', '_image_creative')) # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/dfp/v201708/creative_service/update_creatives.py b/examples/dfp/v201708/creative_service/update_creatives.py index 15b95828..c58e300a 100755 --- a/examples/dfp/v201708/creative_service/update_creatives.py +++ b/examples/dfp/v201708/creative_service/update_creatives.py @@ -37,21 +37,11 @@ def main(client, image_creative_id): creative_service = client.GetService('CreativeService', version='v201708') # Create statement object to get all image creatives. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }, { - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': image_creative_id - } - }] - query = 'WHERE creativeType = :type AND id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('creativeType = :type AND id = :id') + .WithBindVariable('type', 'ImageCreative') + .WithBindVariable('id', long(image_creative_id)) + .Limit(1)) # Get creatives by statement. response = creative_service.getCreativesByStatement( @@ -74,6 +64,7 @@ def main(client, image_creative_id): else: print 'No creatives found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py index 5b313769..39b53de7 100755 --- a/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py @@ -26,16 +26,10 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( 'CreativeSetService', version='v201708') - query = 'WHERE masterCreativeId = :masterCreativeId' - values = [ - {'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'TextValue', - 'value': master_creative_id - }}, - ] # Create a statement to select creative sets. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('masterCreativeId = :masterCreativeId') + .WithBindVariable('masterCreativeId', master_creative_id)) # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/dfp/v201708/creative_set_service/update_creative_set.py b/examples/dfp/v201708/creative_set_service/update_creative_set.py index 8c2edd8c..6ba670e7 100755 --- a/examples/dfp/v201708/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201708/creative_set_service/update_creative_set.py @@ -40,15 +40,9 @@ def main(client, creative_set_id, companion_creative_id): version='v201708') # Create statement to select a single creative set by ID. - values = [{ - 'key': 'creativeSetId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_set_id - } - }] - query = 'WHERE id = :creativeSetId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeSetId') + .WithBindVariable('creativeSetId', long(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -72,6 +66,7 @@ def main(client, creative_set_id, companion_creative_id): else: print 'No creative sets found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py index 6148b764..b9855e66 100755 --- a/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( 'CreativeTemplateService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - }}, - ] # Create a statement to select creative templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'SYSTEM_DEFINED')) # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py index 47490b87..f19a7775 100755 --- a/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py @@ -36,21 +36,10 @@ def main(client, label_id): version='v201708') # Create a query to select the active creative wrappers for the given label. - values = [{ - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status AND labelId = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status AND labelId = :labelId') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('labelId', long(label_id))) creative_wrappers_deactivated = 0 @@ -82,6 +71,7 @@ def main(client, label_id): else: print 'No creative wrappers were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py index a2cc780e..7a583480 100755 --- a/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( 'CreativeWrapperService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select creative wrappers. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py index f387dea1..5243704d 100755 --- a/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py @@ -39,15 +39,10 @@ def main(client, creative_wrapper_id): version='v201708') # Create statement to get a creative wrapper by ID. - values = [{ - 'key': 'creativeWrapperId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_wrapper_id - } - }] - query = 'WHERE id = :creativeWrapperId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeWrapperId') + .WithBindVariable('creativeWrapperId', + long(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -71,6 +66,7 @@ def main(client, creative_wrapper_id): else: print 'No creative wrappers found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py index acb693c7..04ebc205 100755 --- a/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -37,23 +37,10 @@ def main(client): # Create statement to select only active custom fields that apply to # line items. - values = [ - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }, { - 'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - } - ] - query = 'WHERE entityType = :entityType and isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType and isActive = :isActive') + .WithBindVariable('entityType', 'LINE_ITEM') + .WithBindVariable('isActive', True)) custom_fields_deactivated = 0 @@ -79,6 +66,7 @@ def main(client): else: print 'No custom fields were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py index f02cf122..b28d3963 100755 --- a/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( 'CustomFieldService', version='v201708') - query = 'WHERE entityType = :entityType' - values = [ - {'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - }}, - ] # Create a statement to select custom fields. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType') + .WithBindVariable('entityType', 'LINE_ITEM')) # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/dfp/v201708/custom_field_service/update_custom_fields.py b/examples/dfp/v201708/custom_field_service/update_custom_fields.py index 72d95b25..36c95bc5 100755 --- a/examples/dfp/v201708/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201708/custom_field_service/update_custom_fields.py @@ -39,15 +39,9 @@ def main(client, custom_field_id): 'CustomFieldService', version='v201708') # Create statement to get a custom field. - values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - query = 'WHERE id = :customFieldId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', long(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -69,6 +63,7 @@ def main(client, custom_field_id): else: print 'No custom fields found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py index 469439f3..3ed109af 100755 --- a/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py @@ -38,15 +38,9 @@ def main(client, key_name): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201708') - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': key_name - } - }] - query = 'WHERE name = :name' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('name = :name') + .WithBindVariable('name', key_name)) deleted_custom_targeting_keys = 0 @@ -76,6 +70,7 @@ def main(client, key_name): else: print 'No custom targeting keys were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 092568ea..c4b77aa8 100755 --- a/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -26,15 +26,9 @@ def main(client): 'CustomTargetingService', version='v201708') # Create statement to get targeting keys for predefined values. - query = ('WHERE type = :type') - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] - targeting_key_statement = dfp.FilterStatement(query, values) + targeting_key_statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'PREDEFINED')) all_keys = [] @@ -44,15 +38,15 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (:ids)') + .WithBindVariable('ids', [key['id'] for key in all_keys])) # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. @@ -67,7 +61,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py index e8716202..39ef1be7 100755 --- a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py @@ -32,15 +32,10 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201708') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE id = :keyId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :keyId') + .WithBindVariable('keyId', long(key_id)) + .Limit(1)) # Get custom targeting keys by statement. response = custom_targeting_service.getCustomTargetingKeysByStatement( @@ -65,6 +60,7 @@ def main(client, key_id): else: print 'No custom targeting keys were found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py index 63e365e5..f0c8d675 100755 --- a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py @@ -32,15 +32,9 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201708') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', long(key_id))) while True: # Get custom targeting values by statement. @@ -70,6 +64,7 @@ def main(client, key_id): if response['totalResultSetSize'] == 0: print 'No custom targeting values were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py index bf5f03b6..e8174907 100755 --- a/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -26,16 +26,10 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( 'ExchangeRateService', version='v201708') - query = 'WHERE currencyCode = :currencyCode' - values = [ - {'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - }}, - ] # Create a statement to select exchange rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('currencyCode = :currencyCode') + .WithBindVariable('currencyCode', currency_code)) # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py index 62331fae..ad85b0b3 100755 --- a/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py @@ -33,16 +33,10 @@ def main(client, exchange_rate_id): version='v201708') # Create a statement to get an exchange rate by its ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': exchange_rate_id - } - }] - query = 'WHERE id = :id' - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(exchange_rate_id)) + .Limit(1)) # Get rate cards by statement. response = exchange_rate_service.getExchangeRatesByStatement( diff --git a/examples/dfp/v201708/inventory_service/archive_ad_units.py b/examples/dfp/v201708/inventory_service/archive_ad_units.py index b64b0a36..6ea176a3 100755 --- a/examples/dfp/v201708/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201708/inventory_service/archive_ad_units.py @@ -39,15 +39,9 @@ def main(client, parent_id): # Create a query to select ad units under the parent ad unit and the parent ad # unit. - values = [{ - 'key': 'parentId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': parent_id - } - }] - query = 'WHERE parentId = :parentId or id = :parentId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId or id = :parentId') + .WithBindVariable('parentId', long(parent_id))) ad_units_archived = 0 @@ -74,6 +68,7 @@ def main(client, parent_id): else: print 'No ad units were archived.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/inventory_service/update_ad_units.py b/examples/dfp/v201708/inventory_service/update_ad_units.py index 7dec87a9..fa5c54f3 100755 --- a/examples/dfp/v201708/inventory_service/update_ad_units.py +++ b/examples/dfp/v201708/inventory_service/update_ad_units.py @@ -39,15 +39,9 @@ def main(client, ad_unit_id): inventory_service = client.GetService('InventoryService', version='v201708') # Create a statement to select a single ad unit by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': ad_unit_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', ad_unit_id)) # Get ad units by statement. response = inventory_service.getAdUnitsByStatement( @@ -81,6 +75,7 @@ def main(client, ad_unit_id): print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/label_service/deactivate_labels.py b/examples/dfp/v201708/label_service/deactivate_labels.py index 2af49168..9cc3f342 100755 --- a/examples/dfp/v201708/label_service/deactivate_labels.py +++ b/examples/dfp/v201708/label_service/deactivate_labels.py @@ -30,15 +30,9 @@ def main(client): label_service = client.GetService('LabelService', version='v201708') # Create query. - values = [{ - 'key': 'isActive', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'true' - } - }] - query = 'WHERE isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) labels_deactivated = 0 @@ -64,6 +58,7 @@ def main(client): else: print 'No labels were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/label_service/get_active_labels.py b/examples/dfp/v201708/label_service/get_active_labels.py index 415672a7..7ee62101 100755 --- a/examples/dfp/v201708/label_service/get_active_labels.py +++ b/examples/dfp/v201708/label_service/get_active_labels.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201708') - query = 'WHERE isActive = :isActive' - values = [ - {'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] # Create a statement to select labels. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/dfp/v201708/label_service/update_labels.py b/examples/dfp/v201708/label_service/update_labels.py index bccf95a7..a9d859f1 100755 --- a/examples/dfp/v201708/label_service/update_labels.py +++ b/examples/dfp/v201708/label_service/update_labels.py @@ -32,17 +32,9 @@ def main(client, label_id): label_service = client.GetService('LabelService', version='v201708') # Create a statement to select only active labels. - values = [ - { - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - } - ] - query = 'WHERE id = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :labelId') + .WithBindVariable('labelId', long(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -63,6 +55,7 @@ def main(client, label_id): else: print 'No labels found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py index 0b13f4bf..8885ecc0 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py @@ -33,21 +33,10 @@ def main(client, line_item_id): 'LineItemCreativeAssociationService', version='v201708') # Create query. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE lineItemId = :lineItemId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId AND status = :status') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('lineItemId', long(line_item_id))) num_deactivated_licas = 0 @@ -77,6 +66,7 @@ def main(client, line_item_id): else: print 'No LICAs were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py index 15eb13a8..3200cb4a 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py @@ -26,16 +26,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( 'LineItemCreativeAssociationService', version='v201708') - query = 'WHERE lineItemId = :lineItemId' - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'TextValue', - 'value': line_item_id - }}, - ] # Create a statement to select line item creative associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId') + .WithBindVariable('lineItemId', line_item_id)) # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/dfp/v201708/line_item_service/activate_line_items.py b/examples/dfp/v201708/line_item_service/activate_line_items.py index 0cc56b63..0df9b340 100755 --- a/examples/dfp/v201708/line_item_service/activate_line_items.py +++ b/examples/dfp/v201708/line_item_service/activate_line_items.py @@ -36,21 +36,10 @@ def main(client, order_id): line_item_service = client.GetService('LineItemService', version='v201708') # Create query. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' - } - }] - query = 'WHERE orderId = :orderId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId AND status = :status') + .WithBindVariable('status', 'NEEDS_CREATIVES') + .WithBindVariable('orderId', long(order_id))) line_items_activated = 0 @@ -79,6 +68,7 @@ def main(client, order_id): else: print 'No line items were activated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py index 1a6e2835..ab1cd2f4 100755 --- a/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. line_item_service = client.GetService('LineItemService', version='v201708') - query = 'WHERE isMissingCreatives = :isMissingCreatives' - values = [ - {'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isMissingCreatives = :isMissingCreatives') + .WithBindVariable('isMissingCreatives', True)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py index 39b0e992..6970ebdb 100755 --- a/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py @@ -21,22 +21,20 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. line_item_service = client.GetService('LineItemService', version='v201708') - query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' - values = [ - {'key': 'lastModifiedDateTime', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() - timedelta(days=1)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201708/line_item_service/target_custom_criteria.py b/examples/dfp/v201708/line_item_service/target_custom_criteria.py index a55368b6..c1e1c746 100755 --- a/examples/dfp/v201708/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201708/line_item_service/target_custom_criteria.py @@ -81,15 +81,10 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - query = 'WHERE id = :lineItemId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', long(line_item_id)) + .Limit(1)) # Set custom criteria targeting on the line item. line_item = line_item_service.getLineItemsByStatement( @@ -107,6 +102,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, else: print 'No line items were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/line_item_service/update_line_items.py b/examples/dfp/v201708/line_item_service/update_line_items.py index 8990c58f..fa7abe6c 100755 --- a/examples/dfp/v201708/line_item_service/update_line_items.py +++ b/examples/dfp/v201708/line_item_service/update_line_items.py @@ -32,22 +32,13 @@ def main(client, order_id): line_item_service = client.GetService('LineItemService', version='v201708') # Create statement object to only select line items with even delivery rates. - values = [{ - 'key': 'deliveryRateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'EVENLY' - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId' - statement = dfp.FilterStatement(query, values, 500) + statement = (dfp.StatementBuilder() + .Where(('deliveryRateType = :deliveryRateType AND ' + 'orderId = :orderId')) + .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('deliveryRateType', 'EVENLY') + .Limit(500)) # Get line items by statement. response = line_item_service.getLineItemsByStatement( @@ -76,6 +67,7 @@ def main(client, order_id): else: print 'No line items found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/order_service/approve_orders.py b/examples/dfp/v201708/order_service/approve_orders.py index 4b47b3bd..cc7c4ca4 100755 --- a/examples/dfp/v201708/order_service/approve_orders.py +++ b/examples/dfp/v201708/order_service/approve_orders.py @@ -30,19 +30,12 @@ def main(client): # Initialize appropriate service. order_service = client.GetService('OrderService', version='v201708') - # Create query. - values = [{ - 'key': 'today', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S') - } - }] - query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')' - ' AND endDateTime >= :today AND isArchived = FALSE') - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + today = datetime.date.today() + statement = (dfp.StatementBuilder() + .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' + 'AND endDateTime >= :today AND isArchived = FALSE')) + .WithBindVariable('today', today)) orders_approved = 0 # Get orders by statement. diff --git a/examples/dfp/v201708/order_service/get_orders_starting_soon.py b/examples/dfp/v201708/order_service/get_orders_starting_soon.py index 60d0f60a..367de8fa 100755 --- a/examples/dfp/v201708/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201708/order_service/get_orders_starting_soon.py @@ -21,33 +21,22 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. order_service = client.GetService('OrderService', version='v201708') - query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' - '<= :soon') - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'APPROVED' - }}, - {'key': 'now', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') - }}, - {'key': 'soon', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() + timedelta(days=5)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + now = datetime.now(tz=pytz.timezone('America/New_York')) + soon = now + timedelta(days=5) + # Create a statement to select orders. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('status = :status AND startDateTime >= :now ' + 'AND startDateTime <= :soon')) + .WithBindVariable('status', 'APPROVED') + .WithBindVariable('now', now) + .WithBindVariable('soon', soon)) # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/dfp/v201708/order_service/update_orders.py b/examples/dfp/v201708/order_service/update_orders.py index a7930f84..66bdbe8d 100755 --- a/examples/dfp/v201708/order_service/update_orders.py +++ b/examples/dfp/v201708/order_service/update_orders.py @@ -31,16 +31,10 @@ def main(client, order_id): order_service = client.GetService('OrderService', version='v201708') # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :orderId') + .WithBindVariable('orderId', long(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -69,6 +63,7 @@ def main(client, order_id): else: print 'No orders found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/package_service/get_in_progress_packages.py b/examples/dfp/v201708/package_service/get_in_progress_packages.py index 0498d893..b84a4599 100755 --- a/examples/dfp/v201708/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201708/package_service/get_in_progress_packages.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. pkg_service = client.GetService('PackageService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'IN_PROGRESS' - }}, - ] # Create a statement to select packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'IN_PROGRESS')) # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/dfp/v201708/placement_service/deactivate_placements.py b/examples/dfp/v201708/placement_service/deactivate_placements.py index ab6bc811..01d3f564 100755 --- a/examples/dfp/v201708/placement_service/deactivate_placements.py +++ b/examples/dfp/v201708/placement_service/deactivate_placements.py @@ -31,15 +31,10 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201708') # Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :placementId') + .WithBindVariable('placementId', long(placement_id)) + .Limit(1)) # Get placements by statement. placements = placement_service.getPlacementsByStatement( @@ -60,6 +55,7 @@ def main(client, placement_id): else: print 'No placements were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/placement_service/get_active_placements.py b/examples/dfp/v201708/placement_service/get_active_placements.py index 7a4149b5..bcf3b097 100755 --- a/examples/dfp/v201708/placement_service/get_active_placements.py +++ b/examples/dfp/v201708/placement_service/get_active_placements.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. placement_service = client.GetService('PlacementService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select placements. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py index b0b0d3cb..8baf7e7c 100755 --- a/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py @@ -26,16 +26,10 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( 'PremiumRateService', version='v201708') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] # Create a statement to select premium rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/dfp/v201708/premium_rate_service/update_premium_rates.py b/examples/dfp/v201708/premium_rate_service/update_premium_rates.py index 054c0d99..bce51970 100755 --- a/examples/dfp/v201708/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201708/premium_rate_service/update_premium_rates.py @@ -33,15 +33,11 @@ def main(client, premium_rate_id): version='v201708') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': premium_rate_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(premium_rate_id)) + .Limit(1)) # Get the premium rate. response = premium_rate_service.getPremiumRatesByStatement( diff --git a/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py index 9f66019d..9b28e75e 100755 --- a/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py @@ -26,16 +26,10 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( 'ProductPackageItemService', version='v201708') - query = 'WHERE productPackageId = :productPackageId' - values = [ - {'key': 'productPackageId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_package_id - }}, - ] # Create a statement to select product package items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productPackageId = :productPackageId') + .WithBindVariable('productPackageId', product_package_id)) # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/dfp/v201708/product_package_service/get_active_product_packages.py b/examples/dfp/v201708/product_package_service/get_active_product_packages.py index cb56d6e0..7fec7d3c 100755 --- a/examples/dfp/v201708/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201708/product_package_service/get_active_product_packages.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( 'ProductPackageService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select product packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/dfp/v201708/product_service/get_products_for_product_template.py b/examples/dfp/v201708/product_service/get_products_for_product_template.py index a5fe62ea..bdf48f18 100755 --- a/examples/dfp/v201708/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201708/product_service/get_products_for_product_template.py @@ -26,16 +26,10 @@ def main(client, product_template_id): # Initialize appropriate service. product_service = client.GetService('ProductService', version='v201708') - query = 'WHERE productTemplateId = :productTemplateId' - values = [ - {'key': 'productTemplateId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_template_id - }}, - ] # Create a statement to select products. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productTemplateId = :productTemplateId') + .WithBindVariable('productTemplateId', product_template_id)) # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py index f8ee622d..4ecb0509 100755 --- a/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py @@ -30,15 +30,10 @@ def main(client, product_id): product_service = client.GetService('ProductService', version='v201708') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) products_published = 0 diff --git a/examples/dfp/v201708/product_service/update_products.py b/examples/dfp/v201708/product_service/update_products.py index 91cb2076..581c144b 100755 --- a/examples/dfp/v201708/product_service/update_products.py +++ b/examples/dfp/v201708/product_service/update_products.py @@ -32,15 +32,10 @@ def main(client, product_id): product_service = client.GetService('ProductService', version='v201708') # Create statement object to select a single product by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, product_id): else: print 'No products found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/product_template_service/activate_product_templates.py b/examples/dfp/v201708/product_template_service/activate_product_templates.py index 09cb0c7f..062ab9b8 100755 --- a/examples/dfp/v201708/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201708/product_template_service/activate_product_templates.py @@ -34,15 +34,10 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201708') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) product_templates_activated = 0 diff --git a/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py index eecc85f7..8678245e 100755 --- a/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( 'ProductTemplateService', version='v201708') - query = 'WHERE lineItemType = :lineItemType' - values = [ - {'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - }}, - ] # Create a statement to select product templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemType = :lineItemType') + .WithBindVariable('lineItemType', 'SPONSORSHIP')) # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/dfp/v201708/product_template_service/update_product_templates.py b/examples/dfp/v201708/product_template_service/update_product_templates.py index f0b8420a..6824719d 100755 --- a/examples/dfp/v201708/product_template_service/update_product_templates.py +++ b/examples/dfp/v201708/product_template_service/update_product_templates.py @@ -33,15 +33,11 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201708') # Create a statement to select a single product template by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) # Get product templates by statement. response = product_template_service.getProductTemplatesByStatement( diff --git a/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py index 9da431e6..4d460956 100755 --- a/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py @@ -34,15 +34,10 @@ def main(client, proposal_line_item_id): 'ProposalLineItemService', version='v201708') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) proposal_line_items_archived = 0 diff --git a/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 31a210bc..5bd3138d 100755 --- a/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -26,16 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( 'ProposalLineItemService', version='v201708') - query = 'WHERE proposalId = :proposalId' - values = [ - {'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - }}, - ] # Create a statement to select proposal line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('proposalId = :proposalId') + .WithBindVariable('proposalId', proposal_id)) # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py index 7e905ac2..ffda2e86 100755 --- a/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py @@ -34,16 +34,11 @@ def main(client, proposal_line_item_id): 'ProposalLineItemService', version='v201708') # Create statement to select a proposal line item. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) # Get proposal line items by statement. response = proposal_line_item_service.getProposalLineItemsByStatement( diff --git a/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py index 9ee049f0..fb7354a9 100755 --- a/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. proposal_service = client.GetService('ProposalService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - }}, - ] # Create a statement to select proposals. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'PENDING_APPROVAL')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py index 2d7a14ac..b8c8690b 100755 --- a/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py @@ -29,17 +29,9 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201708') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo programmatic proposals were pushed to Marketplace.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py index c76ccfad..a426566f 100755 --- a/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py @@ -31,17 +31,9 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201708') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo proposals were approved.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/proposal_service/update_proposals.py b/examples/dfp/v201708/proposal_service/update_proposals.py index f4083ba9..29f4bc91 100755 --- a/examples/dfp/v201708/proposal_service/update_proposals.py +++ b/examples/dfp/v201708/proposal_service/update_proposals.py @@ -31,16 +31,11 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201708') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', long(proposal_id)) + .Limit(1)) # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, proposal_id): else: print 'No proposals found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py index d1b35a8a..e696588b 100755 --- a/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py +++ b/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py @@ -33,50 +33,21 @@ def main(client): # Initialize appropriate service. pql_service = client.GetService('PublisherQueryLanguageService', 'v201708') - end_date = date.today() + end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) - initial_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE ChangeDateTime > :startDateTime ' - 'AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - pagination_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE Id < :id ' - 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - values = [ - { - 'key': 'startDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day - } - } - } - }, - { - 'key': 'endDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day - } - } - } - } - ] - - statement = dfp.FilterStatement(initial_query, values) + initial_query = ('ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime') + pagination_query = 'Id < :id AND ' + initial_query + + statement = (dfp.StatementBuilder() + .Select(('Id, ChangeDateTime, EntityId, EntityType, ' + 'Operation, UserId')) + .From('Change_History') + .Where(initial_query) + .OrderBy('ChangeDateTime', ascending=False) + .WithBindVariable('startDateTime', start_date) + .WithBindVariable('endDateTime', end_date)) + keep_iterating = True i = 0 total_rows = [] @@ -94,8 +65,11 @@ def main(client): last_row = rows[-1] last_id = last_row['values'][0]['value'] i += 1 - statement = UpdateFilterStatement( - statement, pagination_query, values, last_id) + + # Update the statement using the earliest row in the previous result. + statement.Where(pagination_query) + statement.WithBindVariable('id', last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' % (i, rows_length, last_id)) @@ -109,34 +83,6 @@ def main(client): print ConvertValueForCsv(row) -def UpdateFilterStatement(statement, query, values, last_id): - """Updates the FilterStatement in order to page through results. - - Args: - statement: an instantiated FilterStatement. - query: a str query that will be used to update the FilterStatement. - values: a list of bind variables to be updated. - last_id: a str representing the earliest change ID in a result set. - - Returns: - FilterStatement the updated statement. - """ - # Use the earliest change ID in the result set to page. - updated_values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_id - } - }] - updated_values.extend(values) - - statement.where_clause = query - statement.values = updated_values - - return statement - - def ConvertValueForCsv(pql_value): """Sanitizes a field value from a Value object to a CSV suitable format. diff --git a/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py index 3d328885..e6c21125 100755 --- a/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. rate_card_service = client.GetService('RateCardService', version='v201708') - query = 'WHERE forMarketplace = :forMarketplace' - values = [ - {'key': 'forMarketplace', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] # Create a statement to select rate cards. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('forMarketplace = :forMarketplace') + .WithBindVariable('forMarketplace', True)) # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 6e07ba1e..c0a53e7a 100755 --- a/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -26,16 +26,11 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( 'ReconciliationOrderReportService', version='v201708') - query = 'WHERE reconciliationReportId = :reconciliationReportId' - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - ] # Create a statement to select reconciliation order reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('reconciliationReportId = :reconciliationReportId') + .WithBindVariable('reconciliationReportId', + reconciliation_report_id)) # Retrieve a small amount of reconciliation order reports at a time, paging # through until all reconciliation order reports have been retrieved. diff --git a/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index d00d24c7..1e8943f7 100755 --- a/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -28,17 +28,13 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( 'ReconciliationReportRowService', version='v201708') - query = ('WHERE reconciliationReportId = %s AND ' - 'lineItemId != :lineItemId') % reconciliation_report_id - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - } - }] + # Create a statement to select reconciliation report rows. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reportId ' + 'AND lineItemId != :lineItemId')) + .WithBindVariable('lineItemId', 0) + .WithBindVariable('reportId', long(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. diff --git a/examples/dfp/v201708/report_service/run_delivery_report.py b/examples/dfp/v201708/report_service/run_delivery_report.py index cffd7138..cf6beb2e 100755 --- a/examples/dfp/v201708/report_service/run_delivery_report.py +++ b/examples/dfp/v201708/report_service/run_delivery_report.py @@ -32,15 +32,11 @@ def main(client, order_id): # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - filter_statement = {'query': 'WHERE ORDER_ID = :id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('ORDER_ID = :id') + .WithBindVariable('id', long(order_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Set the start and end dates of the report to run (past 8 days). end_date = datetime.now().date() @@ -52,7 +48,7 @@ def main(client, order_id): 'dimensions': ['ORDER_ID', 'ORDER_NAME'], 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', 'ORDER_END_DATE_TIME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], diff --git a/examples/dfp/v201708/report_service/run_inventory_report.py b/examples/dfp/v201708/report_service/run_inventory_report.py index 4cb31c49..f4a6d7c9 100755 --- a/examples/dfp/v201708/report_service/run_inventory_report.py +++ b/examples/dfp/v201708/report_service/run_inventory_report.py @@ -34,15 +34,11 @@ def main(client): network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - values = [{ - 'key': 'parent_ad_unit_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': root_ad_unit_id - } - }] - filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') + .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Create report job. report_job = { @@ -55,7 +51,7 @@ def main(client): 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', - 'statement': filter_statement + 'statement': statement.ToStatement() } } diff --git a/examples/dfp/v201708/report_service/run_report_with_custom_fields.py b/examples/dfp/v201708/report_service/run_report_with_custom_fields.py index e482d20f..3cb787c7 100755 --- a/examples/dfp/v201708/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201708/report_service/run_report_with_custom_fields.py @@ -33,17 +33,9 @@ def main(client, order_id): report_downloader = client.GetDataDownloader(version='v201708') # Filter for line items of a given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE orderId = :orderId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId') + .WithBindVariable('orderId', long(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -62,14 +54,16 @@ def main(client, order_id): else: break - # Create statement object to filter for an order. - filter_statement = {'query': query, 'values': values} + # Modify statement for reports + statement.limit = None + statement.offset = None + statement.Where('ORDER_ID = :orderId') # Create report job. report_job = { 'reportQuery': { 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', 'customFieldIds': list(custom_field_ids) diff --git a/examples/dfp/v201708/report_service/run_saved_query.py b/examples/dfp/v201708/report_service/run_saved_query.py index 0529d694..9b03ffcb 100755 --- a/examples/dfp/v201708/report_service/run_saved_query.py +++ b/examples/dfp/v201708/report_service/run_saved_query.py @@ -34,15 +34,10 @@ def main(client, saved_query_id): report_downloader = client.GetDataDownloader(version='v201708') # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': saved_query_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(saved_query_id)) + .Limit(1)) response = report_service.getSavedQueriesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index fc262e7f..7c2655d0 100755 --- a/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -26,16 +26,10 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( 'SuggestedAdUnitService', version='v201708') - query = 'WHERE numRequests >= :numRequests' - values = [ - {'key': 'numRequests', - 'value': { - 'xsi_type': 'TextValue', - 'value': num_requests - }}, - ] # Create a statement to select suggested ad units. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests >= :numRequests') + .WithBindVariable('numRequests', long(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/dfp/v201708/team_service/update_teams.py b/examples/dfp/v201708/team_service/update_teams.py index ee9340cd..c292badc 100755 --- a/examples/dfp/v201708/team_service/update_teams.py +++ b/examples/dfp/v201708/team_service/update_teams.py @@ -37,15 +37,9 @@ def main(client, team_id): team_service = client.GetService('TeamService', version='v201708') # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :teamId') + .WithBindVariable('teamId', long(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -67,6 +61,7 @@ def main(client, team_id): else: print 'No teams found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/user_service/deactivate_users.py b/examples/dfp/v201708/user_service/deactivate_users.py index 41563678..8f9afa46 100755 --- a/examples/dfp/v201708/user_service/deactivate_users.py +++ b/examples/dfp/v201708/user_service/deactivate_users.py @@ -33,17 +33,9 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201708') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -66,6 +58,7 @@ def main(client, user_id): else: print 'No users were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/user_service/get_user_by_email_address.py b/examples/dfp/v201708/user_service/get_user_by_email_address.py index 364bdc60..24671e74 100755 --- a/examples/dfp/v201708/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201708/user_service/get_user_by_email_address.py @@ -25,16 +25,10 @@ def main(client, email_address): # Initialize appropriate service. user_service = client.GetService('UserService', version='v201708') - query = 'WHERE email = :email' - values = [ - {'key': 'email', - 'value': { - 'xsi_type': 'TextValue', - 'value': email_address - }}, - ] # Create a statement to select users. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('email = :email') + .WithBindVariable('email', email_address)) # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/dfp/v201708/user_service/update_users.py b/examples/dfp/v201708/user_service/update_users.py index 0354b8fa..cd415ff5 100755 --- a/examples/dfp/v201708/user_service/update_users.py +++ b/examples/dfp/v201708/user_service/update_users.py @@ -31,17 +31,9 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201708') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -59,6 +51,7 @@ def main(client, user_id): else: print 'No users found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py index 748bb82b..8cce293c 100755 --- a/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py @@ -38,17 +38,9 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201708') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -62,10 +54,14 @@ def main(client, user_id): print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) + # Action doesn't require limit/offset + statement.limit = None + statement.offset = None + # Perform action. result = user_team_association_service.performUserTeamAssociationAction( {'xsi_type': 'DeleteUserTeamAssociations'}, - {'query': query, 'values': values}) + statement.ToStatement()) # Display results. if result and int(result['numChanges']) > 0: @@ -74,6 +70,7 @@ def main(client, user_id): else: print 'No user team associations were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py index a2a56fa7..fa78d834 100755 --- a/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py @@ -26,16 +26,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( 'UserTeamAssociationService', version='v201708') - query = 'WHERE userId = :userId' - values = [ - {'key': 'userId', - 'value': { - 'xsi_type': 'TextValue', - 'value': user_id - }}, - ] # Create a statement to select user team associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py index c6dcc284..8e3152c7 100755 --- a/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py @@ -40,17 +40,9 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201708') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -79,6 +71,7 @@ def main(client, user_id): else: print 'No user team associations found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py index 8ff9c893..d9d9ff51 100755 --- a/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py @@ -33,35 +33,13 @@ def main(client, proposal_id): workflow_request_service = client.GetService('WorkflowRequestService', version='v201708') - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) workflow_approval_requests_approved = 0 # Get workflow approval requests by statement. diff --git a/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py index 94390849..26d50042 100755 --- a/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py @@ -27,16 +27,10 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - }}, - ] # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py index 77e947ab..a0a39fd3 100755 --- a/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py @@ -27,16 +27,10 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - }}, - ] # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py index 7a11e501..79fef4c0 100755 --- a/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -33,35 +33,13 @@ def main(client, proposal_id): workflow_request_service = client.GetService('WorkflowRequestService', version='v201708') - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) workflow_external_condition_requests_triggered = 0 # Get workflow external condition requests by statement. diff --git a/googleads/adwords.py b/googleads/adwords.py index 2c477ac6..c38ce9cf 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -42,52 +42,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201609': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineCallConversionFeedService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201702': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', @@ -249,7 +203,7 @@ _DEFAULT_USER_AGENT = 'unknown' -class AdWordsClient(object): +class AdWordsClient(googleads.common.CommonClient): """A central location to set headers and create web service clients. Attributes: @@ -368,6 +322,8 @@ def __init__(self, developer_token, oauth2_client, GoogleAdsValueError: If the provided user_agent contains non-ASCII characters. """ + super(AdWordsClient, self).__init__() + self.developer_token = developer_token self.oauth2_client = oauth2_client self.client_customer_id = kwargs.get('client_customer_id') @@ -1661,7 +1617,6 @@ def _DownloadReportAsStream(self, post_body, **kwargs): response.code, response.msg) return response except urllib2.HTTPError as e: - # Content from HTTPError instance can be read only one time. error = self._ExtractError(e) if _report_logger.isEnabledFor(logging.WARNING): _report_logger.warning( @@ -1710,7 +1665,9 @@ def _ExtractRequestSummaryFields(self, request, error=None): Args: request: a urllib2.Request instance. [optional] - error: a AdWordsReportError instance used to retrieve error details. + error: a googleads.errors.AdWordsReportError instance or subclass used to + retrieve error details. This should only be present when an error + occurred, otherwise it should be set to None for successful requests. Returns: A dict containing the fields to be output in the summary logs. diff --git a/googleads/common.py b/googleads/common.py index 6f01d0e2..6f60d143 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -66,7 +66,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '7.0.0' +VERSION = '8.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' @@ -128,6 +128,26 @@ def GenerateLibSig(short_name): return ' (%s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION) +class CommonClient(object): + """Contains shared startup code between DFP and AdWords clients.""" + + def __init__(self): + # Warn users on deprecated Python versions on initialization. + if _PY_VERSION_MAJOR == 2: + if _PY_VERSION_MINOR == 7 and _PY_VERSION_MICRO < 9: + _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, + _PY_VERSION_MINOR, _PY_VERSION_MICRO) + elif _PY_VERSION_MINOR < 7: + _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, + _PY_VERSION_MINOR, _PY_VERSION_MICRO) + + # Warn users about using non-utf8 encoding + _, encoding = locale.getdefaultlocale() + if encoding is None or encoding.lower() != 'utf-8': + _logger.warn('Your default encoding, %s, is not UTF-8. Please run this' + ' script with UTF-8 encoding to avoid errors.', encoding) + + def LoadFromString(yaml_doc, product_yaml_key, required_client_values, optional_product_values): """Loads the data necessary for instantiating a client from file storage. @@ -161,21 +181,6 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, if logging_config: logging.config.dictConfig(logging_config) - # Warn users on deprecated Python versions on initialization. - if _PY_VERSION_MAJOR == 2: - if _PY_VERSION_MINOR == 7 and _PY_VERSION_MICRO < 9: - _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, - _PY_VERSION_MINOR, _PY_VERSION_MICRO) - elif _PY_VERSION_MINOR < 7: - _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, - _PY_VERSION_MINOR, _PY_VERSION_MICRO) - - # Warn users about using non-utf8 encoding - _, encoding = locale.getdefaultlocale() - if encoding is None or encoding.lower() != 'utf-8': - _logger.warn('Your default encoding, %s, is not UTF-8. Please run this' - ' script with UTF-8 encoding to avoid errors.', encoding) - try: product_data = data[product_yaml_key] except KeyError: @@ -751,7 +756,7 @@ def MakeSoapRequest(*args): _logger.warning('Response summary - %s', _ExtractResponseSummaryFields(e.document)) - _logger.info('SOAP response:\n%s', e.document) + _logger.info('SOAP response:\n%s', e.document.str()) if not hasattr(e.fault, 'detail'): raise diff --git a/googleads/dfp.py b/googleads/dfp.py index 16fc2204..adbbed34 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -136,7 +136,7 @@ } -class DfpClient(object): +class DfpClient(googleads.common.CommonClient): """A central location to set headers and create web service clients. Attributes: @@ -227,6 +227,8 @@ def __init__(self, oauth2_client, application_name, network_code=None, of the SOAP response. If True, the SOAP response will use gzip compression, and will be decompressed for you automatically. """ + super(DfpClient, self).__init__() + if not application_name or (DEFAULT_APPLICATION_NAME in application_name): raise googleads.errors.GoogleAdsValueError( 'Application name must be set and not contain the default [%s]' % diff --git a/tests/adwords_test.py b/tests/adwords_test.py index a935ff9e..96ea7966 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -1774,6 +1774,7 @@ def testDownloadReport_failure(self): report_contents = io.StringIO() if PYTHON2 else io.BytesIO() report_contents.write(report_data if PYTHON2 else bytes(report_data, 'utf-8')) + logger_request_summary_template = 'Request Summary: %s' report_contents.seek(0) fake_response = mock.Mock() fake_response.read = report_contents.read @@ -1783,30 +1784,40 @@ def testDownloadReport_failure(self): self.marshaller.process.return_value = serialized_report - request = mock.patch(URL_REQUEST_PATH + '.Request') - logger = mock.patch('googleads.adwords._report_logger') - with mock.patch('suds.mx.Content') as mock_content: - with request as mock_request, logger as mock_logger: - mock_logger.isEnabledFor.return_value = True - mock_request_instance = mock.Mock() - mock_request.return_value = mock_request_instance - mock_request_instance.get_full_url.return_value = 'https://google.com/' - mock_request_instance.headers = {} - self.opener.open.side_effect = error - - with self.assertRaises(googleads.errors.AdWordsReportError) as ex: - self.report_downloader.DownloadReport(report_definition, output_file) - self.assertEqual(ex.exception.content, report_data) - - mock_request.assert_called_once_with( - ('https://adwords.google.com/api/adwords/reportdownload/%s' - % self.version), post_body, headers) - self.opener.open.assert_called_once_with(mock_request.return_value) - self.marshaller.process.assert_called_once_with( - mock_content.return_value) - self.assertEqual('', output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with() + with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: + with mock.patch('googleads.adwords._report_logger') as mock_logger: + with mock.patch('googleads.adwords.ReportDownloader' + '._ExtractRequestSummaryFields') as mock_extract_fds: + mock_logger.isEnabledFor.return_value = True + mock_extract_fds_return_value = mock.Mock() + mock_extract_fds.return_value = mock_extract_fds_return_value + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = ( + 'https://google.com/') + mock_request_instance.headers = {} + self.opener.open.side_effect = error + + try: + self.report_downloader.DownloadReport( + report_definition, output_file) + except googleads.errors.AdWordsReportError as ex: + mock_extract_fds.assert_called_once_with( + mock_request_instance, error=ex) + mock_logger.warning.assert_called_once_with( + logger_request_summary_template, + mock_extract_fds_return_value) + + mock_request.assert_called_once_with( + ('https://adwords.google.com/api/adwords/reportdownload/%s' + % self.version), post_body, headers) + self.opener.open.assert_called_once_with(mock_request.return_value) + self.marshaller.process.assert_called_once_with( + mock_content.return_value) + self.assertEqual('', output_file.getvalue()) + h_handler = self.header_handler + h_handler.GetReportDownloadHeaders.assert_called_once_with() def testDownloadReportWithAwql(self): output_file = io.StringIO() diff --git a/tests/common_test.py b/tests/common_test.py index 20261188..dedbb651 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -86,8 +86,6 @@ def tearDown(self): def testShouldWarnWithBadEncoding(self): self.locale_patcher.return_value = (None, None) - yaml_doc = self._CreateYamlDoc({'one': {'needed': 'd', 'keys': 'e'}}, - 'one', self._OAUTH_INSTALLED_APP_DICT) test_major_value = 2 test_minor_value = 6 test_micro_value = 9 @@ -95,11 +93,8 @@ def testShouldWarnWithBadEncoding(self): with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): with mock.patch('googleads.common._logger') as mock_logger: - with mock.patch( - 'googleads.common.open', self.fake_open, create=True): - googleads.common.LoadFromString(yaml_doc, 'one', - ['needed', 'keys'], ['other']) - mock_logger.warn.assert_called_once() + googleads.common.CommonClient() + mock_logger.warn.assert_called_once() def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): """Return the filename of a yaml file created for testing.""" @@ -361,13 +356,7 @@ def testExtractResponseSummaryFieldsWithoutFault(self): self.assertEqual(expected_result, googleads.common._ExtractResponseSummaryFields(doc)) - def testLoadFromString_deprecatedWarningLoggerByMicroValue(self): - yaml_doc = self._CreateYamlDoc({ - 'one': { - 'needed': 'd', - 'keys': 'e' - } - }, 'one', self._OAUTH_INSTALLED_APP_DICT) + def testCommonClient_deprecatedWarningLoggerByMicroValue(self): test_major_value = 2 test_minor_value = 7 test_micro_value = 6 @@ -375,17 +364,12 @@ def testLoadFromString_deprecatedWarningLoggerByMicroValue(self): with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): with mock.patch('googleads.common._logger') as mock_logger: - with mock.patch( - 'googleads.common.open', self.fake_open, create=True): - googleads.common.LoadFromString(yaml_doc, 'one', - ['needed', 'keys'], ['other']) - mock_logger.warning.assert_called_once_with( - googleads.common._DEPRECATED_VERSION_TEMPLATE, - test_major_value, test_minor_value, test_micro_value) + googleads.common.CommonClient() + mock_logger.warning.assert_called_once_with( + googleads.common._DEPRECATED_VERSION_TEMPLATE, + test_major_value, test_minor_value, test_micro_value) def testLoadFromString_deprecatedWarningLoggerByMinorValue(self): - yaml_doc = self._CreateYamlDoc({'one': {'needed': 'd', 'keys': 'e'}}, - 'one', self._OAUTH_INSTALLED_APP_DICT) test_major_value = 2 test_minor_value = 6 test_micro_value = 9 @@ -393,13 +377,10 @@ def testLoadFromString_deprecatedWarningLoggerByMinorValue(self): with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): with mock.patch('googleads.common._logger') as mock_logger: - with mock.patch( - 'googleads.common.open', self.fake_open, create=True): - googleads.common.LoadFromString(yaml_doc, 'one', - ['needed', 'keys'], ['other']) - mock_logger.warning.assert_called_once_with( - googleads.common._DEPRECATED_VERSION_TEMPLATE, - test_major_value, test_minor_value, test_micro_value) + googleads.common.CommonClient() + mock_logger.warning.assert_called_once_with( + googleads.common._DEPRECATED_VERSION_TEMPLATE, + test_major_value, test_minor_value, test_micro_value) def testLoadFromString_emptyYamlString(self): yaml_doc = '' diff --git a/tests/test_data/adwords_googleads.yaml b/tests/test_data/adwords_googleads.yaml new file mode 100644 index 00000000..31fc1b92 --- /dev/null +++ b/tests/test_data/adwords_googleads.yaml @@ -0,0 +1,5 @@ +adwords: + developer_token: developer_token + client_id: client_id + client_secret: client_secret + refresh_token: refresh_token diff --git a/tests/test_data/batch_job_util_budget_template.txt b/tests/test_data/batch_job_util_budget_template.txt new file mode 100644 index 00000000..e0e48f3a --- /dev/null +++ b/tests/test_data/batch_job_util_budget_template.txt @@ -0,0 +1,6 @@ + %s + %s + + %s + + %s \ No newline at end of file diff --git a/tests/test_data/batch_job_util_campaign_criterion_template.txt b/tests/test_data/batch_job_util_campaign_criterion_template.txt new file mode 100644 index 00000000..62d743ab --- /dev/null +++ b/tests/test_data/batch_job_util_campaign_criterion_template.txt @@ -0,0 +1,7 @@ + %s + %s + + %s + %s + %s + diff --git a/tests/test_data/batch_job_util_campaign_label_template.txt b/tests/test_data/batch_job_util_campaign_label_template.txt new file mode 100644 index 00000000..88eff6ba --- /dev/null +++ b/tests/test_data/batch_job_util_campaign_label_template.txt @@ -0,0 +1,2 @@ + %s + %s \ No newline at end of file diff --git a/tests/test_data/batch_job_util_invalid_request.txt b/tests/test_data/batch_job_util_invalid_request.txt new file mode 100644 index 00000000..9bc8b869 --- /dev/null +++ b/tests/test_data/batch_job_util_invalid_request.txt @@ -0,0 +1,9 @@ + + + + Die monster. You don't belong in this world! + + + What is a man? A miserable little pile of secrets. But enough talk... Have at you! + + \ No newline at end of file diff --git a/tests/test_data/batch_job_util_not_request.txt b/tests/test_data/batch_job_util_not_request.txt new file mode 100644 index 00000000..b45ef6fe --- /dev/null +++ b/tests/test_data/batch_job_util_not_request.txt @@ -0,0 +1 @@ +Hello, World! \ No newline at end of file diff --git a/tests/test_data/batch_job_util_operations_template.txt b/tests/test_data/batch_job_util_operations_template.txt new file mode 100644 index 00000000..f31c7b83 --- /dev/null +++ b/tests/test_data/batch_job_util_operations_template.txt @@ -0,0 +1,7 @@ + + %s + %s + +%s + + \ No newline at end of file diff --git a/tests/test_data/batch_job_util_raw_request_template.txt b/tests/test_data/batch_job_util_raw_request_template.txt new file mode 100644 index 00000000..fd7e0e6f --- /dev/null +++ b/tests/test_data/batch_job_util_raw_request_template.txt @@ -0,0 +1,17 @@ + + + + + 000-000-0000 + xxxxxxxxxxxxxxxxxxxx + notarealemail@fake.com (AwApi-Python, googleads/3.8.0, Python/2.7.6) + false + false + + + + +%s + + + \ No newline at end of file diff --git a/tests/test_data/batch_job_util_response_template.txt b/tests/test_data/batch_job_util_response_template.txt new file mode 100644 index 00000000..4ccd1d1e --- /dev/null +++ b/tests/test_data/batch_job_util_response_template.txt @@ -0,0 +1 @@ +410230034Batch budget #c776b6f1-5db6-47fc-96ef-1208edb6d898Money50000000STANDARDtrueENABLED0%s%s%s%s%s%s%s%sMoney%s%s%sENABLED%sManualCpcBiddingSchemefalse1 \ No newline at end of file diff --git a/tests/test_data/batch_job_util_upload_template.txt b/tests/test_data/batch_job_util_upload_template.txt new file mode 100644 index 00000000..61301f64 --- /dev/null +++ b/tests/test_data/batch_job_util_upload_template.txt @@ -0,0 +1,5 @@ + + +%s + \ No newline at end of file diff --git a/tests/test_data/compact_fault_response_envelope.txt b/tests/test_data/compact_fault_response_envelope.txt new file mode 100644 index 00000000..5f1d1e11 --- /dev/null +++ b/tests/test_data/compact_fault_response_envelope.txt @@ -0,0 +1,8 @@ + + + + soap:Client + Unmarshalling Error: For input string: "INSERT_ADVERTISER_COMPANY_ID_HERE" + + + \ No newline at end of file diff --git a/tests/test_data/empty_fault_response_envelope.txt b/tests/test_data/empty_fault_response_envelope.txt new file mode 100644 index 00000000..8b8ac82b --- /dev/null +++ b/tests/test_data/empty_fault_response_envelope.txt @@ -0,0 +1,19 @@ + + + + 644a8c6efd398cf8643c29ff68fe574e + 22 + + + + + soap:Server + [AuthenticationError.NETWORK_CODE_REQUIRED @ ] + + + An error message without errors sibling tags + + + + + \ No newline at end of file diff --git a/tests/test_data/fault_response_envelope.txt b/tests/test_data/fault_response_envelope.txt new file mode 100644 index 00000000..ecf77c26 --- /dev/null +++ b/tests/test_data/fault_response_envelope.txt @@ -0,0 +1,25 @@ + + + + 644a8c6efd398cf8643c29ff68fe574e + 22 + + + + + soap:Server + [AuthenticationError.NETWORK_CODE_REQUIRED @ ] + + + [AuthenticationError.NETWORK_CODE_REQUIRED @ ] + + + + AuthenticationError.NETWORK_CODE_REQUIRED + NETWORK_CODE_REQUIRED + + + + + + \ No newline at end of file diff --git a/tests/test_data/gzip_response.bin b/tests/test_data/gzip_response.bin new file mode 100644 index 0000000000000000000000000000000000000000..567068aba2b84b4ede2c238fd3107c86445a51f4 GIT binary patch literal 394 zcmV;50d@W#iwFP!000000Hu=MZrd;ngRKV*p@5F z+4A<4WKUxbcTlYray3N2EO^%wY^(U-p|{;_rn^%sXce(qHr|%k+C&Q z1@Qk%a4YeY@`p*YmH5nVFumhh&zW-o5GN%C|SASW408W|%joShM08a_PO#lD@ literal 0 HcmV?d00001 diff --git a/tests/test_data/multi_errors_fault_response_envelope.txt b/tests/test_data/multi_errors_fault_response_envelope.txt new file mode 100644 index 00000000..2ca18d4a --- /dev/null +++ b/tests/test_data/multi_errors_fault_response_envelope.txt @@ -0,0 +1,31 @@ + + + + 644a8c6efd398cf8643c29ff68fe574e + 22 + + + + + soap:Server + [Error 1, Error 2] + + + Multiple errors occurred + + + + ERROR_1 + NETWORK_CODE_REQUIRED + + + + + ERROR_2 + NETWORK_CODE_REQUIRED + + + + + + \ No newline at end of file diff --git a/tests/test_data/request_envelope_template.txt b/tests/test_data/request_envelope_template.txt new file mode 100644 index 00000000..37e84386 --- /dev/null +++ b/tests/test_data/request_envelope_template.txt @@ -0,0 +1,27 @@ + + + + + xxx-yyy-zzzz + %s + testing! + false + false + + + + + + ADD + + Test Budget #123456 + + 50000000 + + STANDARD + true + + + + + \ No newline at end of file From 0d89166663601b1d6d79db01042cf89e0023eb6c Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 22 Sep 2017 15:26:14 -0400 Subject: [PATCH 091/180] Commiting latest changes. From 844ddbd54ad0e3fc221daf50d61105132574cace Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 22 Sep 2017 15:27:47 -0400 Subject: [PATCH 092/180] Commiting latest changes. From 91fef479b1573d15f3cc83ef8281872ea5236ada Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 22 Sep 2017 15:56:42 -0400 Subject: [PATCH 093/180] Commiting latest changes. From 0f2e88eac5fc02ca5b86093f0ef967201e7deeea Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 22 Sep 2017 16:01:57 -0400 Subject: [PATCH 094/180] Commiting latest changes. From 2ad7e6151a5ee5b98a0e4e5cf8b01f5d4a66f66b Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 11 Oct 2017 18:03:16 -0400 Subject: [PATCH 095/180] AdWords v201710 release. --- ChangeLog | 6 + .../add_click_to_download_ad.py | 4 +- .../advanced_operations/add_html5_ad.py | 3 +- .../add_responsive_display_ad.py | 4 +- .../v201702/misc/upload_media_bundle.py | 3 +- .../add_click_to_download_ad.py | 4 +- .../advanced_operations/add_html5_ad.py | 3 +- .../add_responsive_display_ad.py | 4 +- .../v201705/misc/upload_media_bundle.py | 3 +- .../add_click_to_download_ad.py | 4 +- .../advanced_operations/add_html5_ad.py | 3 +- .../add_responsive_display_ad.py | 3 +- .../v201708/misc/upload_media_bundle.py | 3 +- examples/adwords/v201710/__init__.py | 15 + .../v201710/account_management/__init__.py | 15 + .../account_management/accept_service_link.py | 62 +++ .../account_management/create_account.py | 63 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201710/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 226 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 128 +++++ .../add_dynamic_page_feed.py | 295 ++++++++++ .../add_dynamic_search_ads_campaign.py | 257 +++++++++ ...add_expanded_text_ad_with_upgraded_urls.py | 109 ++++ .../advanced_operations/add_html5_ad.py | 112 ++++ .../add_responsive_display_ad.py | 159 ++++++ .../add_universal_app_campaign.py | 217 ++++++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201710/basic_operations/__init__.py | 15 + .../v201710/basic_operations/add_ad_groups.py | 115 ++++ .../v201710/basic_operations/add_campaigns.py | 127 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201710/basic_operations/add_keywords.py | 92 +++ .../v201710/basic_operations/get_ad_groups.py | 76 +++ .../v201710/basic_operations/get_campaigns.py | 74 +++ .../get_campaigns_with_awql.py | 64 +++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201710/basic_operations/get_keywords.py | 87 +++ .../v201710/basic_operations/pause_ad.py | 61 ++ .../v201710/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 58 ++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201710/campaign_management/__init__.py | 15 + ...campaign_groups_and_performance_targets.py | 152 +++++ .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 428 ++++++++++++++ .../v201710/campaign_management/add_draft.py | 81 +++ ...dd_keywords_using_incremental_batch_job.py | 259 +++++++++ .../v201710/campaign_management/add_trial.py | 116 ++++ .../get_all_disapproved_ads.py | 103 ++++ .../get_all_disapproved_ads_with_awql.py | 86 +++ .../get_campaigns_by_label.py | 85 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201710/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 131 +++++ .../handle_policy_violation_error.py | 167 ++++++ .../adwords/v201710/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../adwords/v201710/extensions/add_prices.py | 157 ++++++ .../v201710/extensions/add_site_links.py | 146 +++++ .../extensions/add_site_links_using_feeds.py | 236 ++++++++ .../adwords/v201710/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 527 ++++++++++++++++++ examples/adwords/v201710/misc/__init__.py | 15 + .../v201710/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201710/misc/upload_image.py | 66 +++ .../v201710/misc/upload_media_bundle.py | 60 ++ .../adwords/v201710/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 180 ++++++ ...aign_criterion_bid_modifier_simulations.py | 97 ++++ .../get_keyword_bid_simulations.py | 99 ++++ .../v201710/optimization/get_keyword_ideas.py | 113 ++++ .../adwords/v201710/remarketing/__init__.py | 15 + .../v201710/remarketing/add_audience.py | 103 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_conversion_trackers.py | 103 ++++ .../remarketing/add_crm_based_user_list.py | 101 ++++ .../remarketing/add_rule_based_user_lists.py | 235 ++++++++ .../upload_offline_call_conversions.py | 77 +++ .../remarketing/upload_offline_conversions.py | 82 +++ .../remarketing/upload_offline_data.py | 172 ++++++ .../adwords/v201710/reporting/__init__.py | 15 + ...oad_criteria_report_as_stream_with_awql.py | 81 +++ ...criteria_report_as_stream_with_selector.py | 77 +++ ...oad_criteria_report_as_string_with_awql.py | 55 ++ ...criteria_report_as_string_with_selector.py | 59 ++ .../download_criteria_report_with_awql.py | 55 ++ .../download_criteria_report_with_selector.py | 60 ++ .../v201710/reporting/get_report_fields.py | 52 ++ .../reporting/parallel_report_download.py | 230 ++++++++ examples/adwords/v201710/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 281 ++++++++++ .../v201710/shopping/add_product_scope.py | 104 ++++ .../v201710/shopping/add_shopping_campaign.py | 172 ++++++ .../add_shopping_campaign_for_showcase_ads.py | 404 ++++++++++++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201710/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 126 +++++ .../add_customer_negative_criteria.py | 74 +++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201710/targeting/lookup_location.py | 82 +++ .../create_native_creative.py | 6 +- .../create_native_creative.py | 6 +- .../create_native_creative.py | 6 +- ...matic_products_for_non_sales_management.py | 6 +- googleads/adwords.py | 62 ++- googleads/common.py | 2 +- tests/adwords_test.py | 19 + 122 files changed, 11205 insertions(+), 24 deletions(-) create mode 100644 examples/adwords/v201710/__init__.py create mode 100644 examples/adwords/v201710/account_management/__init__.py create mode 100755 examples/adwords/v201710/account_management/accept_service_link.py create mode 100755 examples/adwords/v201710/account_management/create_account.py create mode 100755 examples/adwords/v201710/account_management/get_account_changes.py create mode 100755 examples/adwords/v201710/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201710/advanced_operations/__init__.py create mode 100755 examples/adwords/v201710/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py create mode 100755 examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py create mode 100755 examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201710/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py create mode 100755 examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201710/basic_operations/__init__.py create mode 100755 examples/adwords/v201710/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201710/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201710/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201710/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201710/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201710/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201710/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201710/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201710/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201710/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201710/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201710/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201710/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201710/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201710/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201710/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201710/campaign_management/__init__.py create mode 100755 examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py create mode 100755 examples/adwords/v201710/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201710/campaign_management/add_draft.py create mode 100755 examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201710/campaign_management/add_trial.py create mode 100755 examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201710/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201710/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201710/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201710/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201710/error_handling/__init__.py create mode 100755 examples/adwords/v201710/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201710/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201710/extensions/__init__.py create mode 100755 examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201710/extensions/add_prices.py create mode 100755 examples/adwords/v201710/extensions/add_site_links.py create mode 100755 examples/adwords/v201710/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201710/migration/__init__.py create mode 100755 examples/adwords/v201710/migration/migrate_to_extension_settings.py create mode 100644 examples/adwords/v201710/misc/__init__.py create mode 100755 examples/adwords/v201710/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201710/misc/upload_image.py create mode 100755 examples/adwords/v201710/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201710/optimization/__init__.py create mode 100755 examples/adwords/v201710/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201710/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201710/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201710/remarketing/__init__.py create mode 100755 examples/adwords/v201710/remarketing/add_audience.py create mode 100755 examples/adwords/v201710/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201710/remarketing/add_conversion_trackers.py create mode 100755 examples/adwords/v201710/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201710/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201710/remarketing/upload_offline_call_conversions.py create mode 100755 examples/adwords/v201710/remarketing/upload_offline_conversions.py create mode 100755 examples/adwords/v201710/remarketing/upload_offline_data.py create mode 100644 examples/adwords/v201710/reporting/__init__.py create mode 100755 examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py create mode 100755 examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py create mode 100755 examples/adwords/v201710/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201710/reporting/download_criteria_report_with_selector.py create mode 100755 examples/adwords/v201710/reporting/get_report_fields.py create mode 100755 examples/adwords/v201710/reporting/parallel_report_download.py create mode 100644 examples/adwords/v201710/shopping/__init__.py create mode 100755 examples/adwords/v201710/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201710/shopping/add_product_scope.py create mode 100755 examples/adwords/v201710/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py create mode 100755 examples/adwords/v201710/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201710/targeting/__init__.py create mode 100755 examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201710/targeting/add_customer_negative_criteria.py create mode 100755 examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201710/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index d8b93fd0..5349db0d 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +8.1.0 -- 10/11/17 +* Added support for AdWords v201710. +* Resolved issues: +- Issue 224: https://github.com/googleads/googleads-python-lib/issues/224 +- Issue 228: https://github.com/googleads/googleads-python-lib/issues/228 + 8.0.0 -- 8/22/17 * Removed support and examples for AdWords v201609. * Resolved issues: diff --git a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py index fd3011b8..e859e050 100755 --- a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py @@ -43,7 +43,9 @@ def main(client, ad_group_id): # BASE64 encoded form. Here we download a demo image and encode it for this # ad. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201702/advanced_operations/add_html5_ad.py b/examples/adwords/v201702/advanced_operations/add_html5_ad.py index 208add9e..77b7cfd4 100755 --- a/examples/adwords/v201702/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201702/advanced_operations/add_html5_ad.py @@ -101,7 +101,8 @@ def main(client, ad_group_id): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py index 052d9e23..b38bc350 100755 --- a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py @@ -42,7 +42,9 @@ def main(client, ad_group_id): try: # Create image. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + .decode('utf-8')) image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201702/misc/upload_media_bundle.py b/examples/adwords/v201702/misc/upload_media_bundle.py index 16b63bd2..144f6846 100755 --- a/examples/adwords/v201702/misc/upload_media_bundle.py +++ b/examples/adwords/v201702/misc/upload_media_bundle.py @@ -50,7 +50,8 @@ def main(client): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py index 93de192f..284bd2dd 100755 --- a/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py @@ -43,7 +43,9 @@ def main(client, ad_group_id): # BASE64 encoded form. Here we download a demo image and encode it for this # ad. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201705/advanced_operations/add_html5_ad.py b/examples/adwords/v201705/advanced_operations/add_html5_ad.py index 8857c94e..988d2c93 100755 --- a/examples/adwords/v201705/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201705/advanced_operations/add_html5_ad.py @@ -101,7 +101,8 @@ def main(client, ad_group_id): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py index 996b976b..f096b1d8 100755 --- a/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py @@ -42,7 +42,9 @@ def main(client, ad_group_id): try: # Create image. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + .decode('utf-8')) image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201705/misc/upload_media_bundle.py b/examples/adwords/v201705/misc/upload_media_bundle.py index 0329dcd6..61856b0f 100755 --- a/examples/adwords/v201705/misc/upload_media_bundle.py +++ b/examples/adwords/v201705/misc/upload_media_bundle.py @@ -50,7 +50,8 @@ def main(client): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py index 90f7106b..f720e51c 100755 --- a/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py @@ -43,7 +43,9 @@ def main(client, ad_group_id): # BASE64 encoded form. Here we download a demo image and encode it for this # ad. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201708/advanced_operations/add_html5_ad.py b/examples/adwords/v201708/advanced_operations/add_html5_ad.py index 716d008a..a9fc5973 100755 --- a/examples/adwords/v201708/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201708/advanced_operations/add_html5_ad.py @@ -101,7 +101,8 @@ def main(client, ad_group_id): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py index 439cf8a9..626532b6 100755 --- a/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py @@ -113,7 +113,8 @@ def _CreateImage(media_service, opener, url): Returns: The image that was successfully uploaded. """ - image_data = base64.b64encode(opener.open(url).read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201708/misc/upload_media_bundle.py b/examples/adwords/v201708/misc/upload_media_bundle.py index d6c498ee..33d32a35 100755 --- a/examples/adwords/v201708/misc/upload_media_bundle.py +++ b/examples/adwords/v201708/misc/upload_media_bundle.py @@ -50,7 +50,8 @@ def main(client): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201710/__init__.py b/examples/adwords/v201710/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201710/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201710/account_management/__init__.py b/examples/adwords/v201710/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201710/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201710/account_management/accept_service_link.py b/examples/adwords/v201710/account_management/accept_service_link.py new file mode 100755 index 00000000..522f8305 --- /dev/null +++ b/examples/adwords/v201710/account_management/accept_service_link.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' + + +def main(client, service_link_id): + # Initialize appropriate service. + customer_service = client.GetService( + 'CustomerService', version='v201710') + + # Create the operation to set the status to ACTIVE. + operations = [{ + 'operator': 'SET', + 'operand': { + 'serviceLinkId': service_link_id, + 'serviceType': 'MERCHANT_CENTER', + 'linkStatus': 'ACTIVE', + } + }] + + # Update the service link. + mutated_service_links = customer_service.mutateServiceLinks(operations) + + # Display results. + for mutated_service_link in mutated_service_links: + print ('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201710/account_management/create_account.py b/examples/adwords/v201710/account_management/create_account.py new file mode 100755 index 00000000..8daaceb5 --- /dev/null +++ b/examples/adwords/v201710/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201710') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID "%s" was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/account_management/get_account_changes.py b/examples/adwords/v201710/account_management/get_account_changes.py new file mode 100755 index 00000000..5bd8dfc2 --- /dev/null +++ b/examples/adwords/v201710/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201710') + campaign_service = client.GetService('CampaignService', version='v201710') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id "%s" has change status "%s".' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id "%s" has change status "%s".' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/account_management/get_account_hierarchy.py b/examples/adwords/v201710/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..2c3727bd --- /dev/null +++ b/examples/adwords/v201710/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201710') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/__init__.py b/examples/adwords/v201710/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201710/advanced_operations/add_ad_customizer.py b/examples/adwords/v201710/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..48042172 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_ad_customizer.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates ExpandedTextAds that use ad customizations for specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no ExpandedTextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201710') + + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'headlinePart2': 'Only {=%s.Price}' % feed_name, + 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': expanded_text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID "%s", type "%s", and status "%s".' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201710') + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name "%s" and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService', 'v201710') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + operation = { + 'operator': 'ADD', + 'operand': feed_item + } + + return operation + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..d48ba4bf --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201710') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..679abda7 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Optionally, you may specify a landscape image. The image needs to be in a + # BASE64 encoded form. Here we download a demo image and encode it for this + # ad. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + }, + { + 'name': 'landscapeImage', + 'fieldMedia': { + 'xsi_type': 'Image', + 'data': image_data + }, + 'type': 'IMAGE' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py new file mode 100755 index 00000000..838b04e5 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. + +To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +from collections import namedtuple +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + +# Used to keep track of DSA page feed details. +_DSAFeedDetails = namedtuple( + '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) +# ID that corresponds to the labels. +DSA_LABEL_FIELD_ID = 2 +# The criterion type to be used for DSA page feeds. +DSA_PAGE_FEED_CRITERION_TYPE = 61 +DSA_PAGE_URL_LABEL = 'discounts' +# ID that corresponds to the page URLs. +DSA_PAGE_URLS_FIELD_ID = 1 + + +def main(client, campaign_id, ad_group_id): + # Get the page feed details. This code example creates a new feed, but you can + # fetch and re-use an existing feed. + feed_details = _CreateFeed(client) + _CreateFeedMapping(client, feed_details) + _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) + + # Associate the page feed with the campaign. + _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) + + # Optional: Target web pages matching the feed's label in the ad group. + _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) + + print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + + +def _CreateFeed(client): + """Creates the feed for DSA page URLs. + + Args: + client: an AdWordsClient instance. + + Returns: + A _DSAFeedDetails instance containing details about the created feed. + """ + # Get the FeedService. + feed_service = client.GetService('FeedService', version='v201710') + + # Create operation. + operation = { + # Create the feed. + 'operand': { + 'name': 'DSA Feed %s' % uuid.uuid4(), + # Create attributes. + 'attributes': [ + {'type': 'URL_LIST', 'name': 'Page URL'}, + {'type': 'STRING_LIST', 'name': 'Label'} + ], + 'origin': 'USER' + }, + 'operator': 'ADD' + } + + # Add the feed. + feed = feed_service.mutate([operation])['value'][0] + return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], + feed['attributes'][1]['id']) + + +def _CreateFeedMapping(client, feed_details): + """Creates the feed mapping for DSA page feeds. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + """ + # Get the FeedMappingService. + feed_mapping_service = client.GetService('FeedMappingService', + version='v201710') + + # Create the operation. + operation = { + # Create the feed mapping. + 'operand': { + 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, + 'feedId': feed_details.feed_id, + # Map the feedAttributeIds to the fieldId constants. + 'attributeFieldMappings': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'fieldId': DSA_PAGE_URLS_FIELD_ID + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'fieldId': DSA_LABEL_FIELD_ID + } + ] + }, + 'operator': 'ADD' + } + + # Add the feed mapping. + feed_mapping_service.mutate([operation]) + + +def _CreateFeedItems(client, feed_details, label_name): + """Creates the page URLs in the DSA page feed. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + label_name: a str containing the page feed URL label. + """ + # Get the FeedItemService. + feed_item_service = client.GetService('FeedItemService', version='v201710') + + # Optional: You can include the {feeditem} valuetrack parameter to track which + # page feed items lead to each click. + urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', + 'http://www.example.com/discounts/hotel-deals?id={feeditem}', + 'http://www.example.com/discounts/flight-deals?id={feeditem}') + + # Create the operation. + operations = [{ + # Create the feed item. + 'operand': { + 'feedId': feed_details.feed_id, + 'attributeValues': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'stringValues': [url] + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'stringValues': [label_name] + } + ] + }, + 'operator': 'ADD' + } for url in urls] + + # Add the feed item. + feed_item_service.mutate(operations) + + +def _UpdateCampaignDSASetting(client, campaign_id, feed_id): + """Updates the campaign DSA setting to DSA pagefeeds. + + Args: + client: an AdWordsClient instance. + campaign_id: a str Campaign ID. + feed_id: a str page Feed ID. + + Raises: + ValueError: If the given campaign is found not to be a dynamic search ad + campaign. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201710') + + selector = { + 'fields': ['Id', 'Settings'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [campaign_id] + }] + } + + response = campaign_service.get(selector) + + if response['totalNumEntries']: + campaign = response['entries'][0] + else: + raise ValueError('No campaign with ID "%d" exists.' % campaign_id) + + if not campaign['settings']: + raise ValueError('This is not a DSA campaign.') + + dsa_setting = None + + campaign_settings = campaign['settings'] + + for setting in campaign_settings: + if setting['Setting.Type'] == 'DynamicSearchAdsSetting': + dsa_setting = setting + break + + if dsa_setting is None: + raise ValueError('This is not a DSA campaign.') + + dsa_setting['pageFeed'] = { + 'feedIds': [feed_id] + } + + # Optional: Specify whether only the supplied URLs should be used with your + # Dynamic Search Ads. + dsa_setting['useSuppliedUrlsOnly'] = True + + operation = { + 'operand': { + 'id': campaign_id, + 'settings': campaign_settings + }, + 'operator': 'SET' + } + + campaign_service.mutate([operation]) + print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id) + + +def _AddDSATargeting(client, ad_group_id, label_name): + """Set custom targeting for the page feed URLs based on a list of labels. + + Args: + client: an AdWordsClient instance. + ad_group_id: a str AdGroup ID. + label_name: a str label name. + + Returns: + A suds.sudsobject.Object representing the newly created webpage criterion. + """ + # Get the AdGroupCriterionService. + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201710') + + # Create the operation. + operation = { + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Test criterion', + # Add a condition for label=specified_label_name. + 'conditions': [{ + 'operand': 'CUSTOM_LABEL', + 'argument': label_name + }], + } + }, + # Set a custom bid for this criterion + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 1500000 + } + }] + } + }, + 'operator': 'ADD' + } + + criterion = ad_group_criterion_service.mutate([operation])['value'][0] + print 'Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus']) + return criterion + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py new file mode 100755 index 00000000..ba304ce5 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Dynamic Search Ads campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + budget = _CreateBudget(client) + campaign_id = _CreateCampaign(client, budget) + ad_group_id = _CreateAdGroup(client, campaign_id) + _CreateExpandedDSA(client, ad_group_id) + _AddWebPageCriteria(client, ad_group_id) + + print 'Dynamic Search Ads campaign setup is complete.' + + +def _CreateBudget(client): + """Creates the budget. + + Args: + client: an AdWordsClient instance. + + Returns: + a suds.sudsobject.Object representation of the created budget. + """ + budget_service = client.GetService('BudgetService', version='v201710') + + # Create the campaign budget + operation = { + 'operand': { + 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), + 'deliveryMethod': 'STANDARD', + 'amount': { + 'microAmount': 500000 + } + }, + 'operator': 'ADD' + } + + budget = budget_service.mutate([operation])['value'][0] + + print 'Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name']) + + return budget + + +def _CreateCampaign(client, budget): + """Creates the campaign. + + Args: + client: an AdWordsClient instance. + budget: a suds.sudsobject.Object representation of a created budget. + + Returns: + An integer campaign ID. + """ + campaign_service = client.GetService('CampaignService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # prevent the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'budget': budget, + # Required: Set the campaign's Dynamic Search Ad settings. + 'settings': [{ + 'xsi_type': 'DynamicSearchAdsSetting', + # Required: Set the domain name and language. + 'domainName': 'example.com', + 'languageCode': 'en' + }], + # Optional: Set the start date. + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + # Optional: Set the end date. + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + }] + + campaign = campaign_service.mutate(operations)['value'][0] + campaign_id = campaign['id'] + + print 'Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name']) + + return campaign_id + + +def _CreateAdGroup(client, campaign_id): + """Creates an ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: an integer campaign ID. + + Returns: + An integer ad group ID. + """ + ad_group_service = client.GetService('AdGroupService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'adGroupType': 'SEARCH_DYNAMIC_ADS', + 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '3000000' + }, + }] + } + } + }] + + ad_group = ad_group_service.mutate(operations)['value'][0] + ad_group_id = ad_group['id'] + + print 'Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name']) + + return ad_group_id + + +def _CreateExpandedDSA(client, ad_group_id): + """Creates the expanded Dynamic Search Ad. + + Args: + client: an AdwordsClient instance. + ad_group_id: an integer ID of the ad group in which the DSA is added. + """ + # Get the AdGroupAdService. + ad_group_ad_service = client.GetService('AdGroupAdService') + + # Create the operation + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + # Create the expanded dynamic search ad. This ad will have its + # headline and final URL auto-generated at serving time according to + # domain name specific information provided by DynamicSearchAdsSetting + # at the campaign level. + 'ad': { + 'xsi_type': 'ExpandedDynamicSearchAd', + # Set the ad description. + 'description': 'Buy your tickets now!' + }, + # Optional: Set the status. + 'status': 'PAUSED', + } + }] + + # Create the ad. + ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] + + # Display the results. + print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' + 'added' % (ad['id'], ad['description'])) + + +def _AddWebPageCriteria(client, ad_group_id): + """Adds a web page criterion to target Dynamic Search Ads. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID of the ad group the criteria is being added to. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201710') + + operations = [{ + 'operator': 'ADD', + # Create biddable ad group criterion. + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion for special offers for children. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Special offers for children.', + 'conditions': [ + { + 'operand': 'URL', + 'argument': '/marscruise/children' + }, + { + 'operand': 'PAGE_TITLE', + 'argument': 'Special Offer' + } + ] + } + }, + 'userStatus': 'PAUSED', + # Optional: set a custom bid. + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000L + } + }] + } + } + }] + + criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..f5edfb5b --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Create the expanded text ad + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' + '&promocode={_promocode}&u={lpurl}'), + 'urlCustomParameters': { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + }, + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': expanded_text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_html5_ad.py b/examples/adwords/v201710/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..db7eee3e --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_html5_ad.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..02701412 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + media_service = client.GetService('MediaService', version='v201710') + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + + try: + # Create marketing image. + marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/3b9Wfh') + + # Create square marketing image. + square_marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/mtt54n') + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': marketing_image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'], + # Optional: Set a square marketing image to the ad. + 'squareMarketingImage': { + 'mediaId': square_marketing_image['mediaId'] + }, + # Optional: Set call-to-action text. + 'callToActionText': 'Shop Now', + # Optional: Set dynamic display ad settings, composed of + # landscape logo image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( + media_service, opener), + # Whitelisted accounts only: Set color settings using + # hexadecimal numbers. + # Set allowFlexibleColor to False if you want your ads to render + # by always using your colors strictly. + # 'mainColor': '#0000ff', + # 'accentColor': '#ffff00', + # 'allowFlexibleColor': False + # Whitelisted accounts only: Set the format setting that the ad + # will be served in. + # 'formatSetting': 'NON_NATIVE' + + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +def _CreateDynamicDisplayAdSettings(media_service, opener): + """Creates settings for dynamic display ad. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + + Returns: + The dynamic display ad settings. + """ + image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + + logo = { + 'type': 'IMAGE', + 'mediaId': image['mediaId'], + 'xsi_type': 'Image' + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!', + 'xsi_type': 'DynamicSettings', + } + + return dynamic_settings + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py new file mode 100755 index 00000000..27db64ed --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Universal App campaign. + +To get campaigns, run get_campaigns.py. To upload image assets for this +campaign, run upload_image.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201710') + + budget_id = CreateBudget(client) + + # Create the Universal App campaign. + universal_app_campaign = { + 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'MULTI_CHANNEL', + 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', + # Set the campaign's bidding strategy. Universal app campaigns only + # support TARGET_CPA bidding strategy. + 'biddingStrategyConfiguration': { + # Set the target CPA to $1 / app install. + 'biddingScheme': { + 'xsi_type': 'TargetCpaBiddingScheme', + 'targetCpa': { + 'microAmount': '1000000' + } + }, + 'biddingStrategyType': 'TARGET_CPA' + }, + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + + universal_app_campaign['settings'] = [ + # Set the campaign's assets and ad text ideas. These values will + # be used to generate ads. + { + 'xsi_type': 'UniversalAppCampaignSetting', + 'appId': 'com.labpixies.colordrips', + 'description1': 'A cool puzzle game', + 'description2': 'Remove connected blocks', + 'description3': '3 difficulty levels', + 'description4': '4 colorful fun skins', + # Optional: You can set up to 20 image assets for your campaign. + # See upload_image.py for an example on how to upload images. + # + # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] + } + ] + + # Optimize this campaign for getting new users for your app. + universal_app_campaign_setting = universal_app_campaign['settings'][0] + universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( + 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') + + # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, + # then also specify your in-app conversion types so AdWords can focus your + # campaign on people who are most likely to complete the corresponding in-app + # actions. + # + # Conversions type IDs can be retrieved using ConversionTrackerService.get. + # universal_app_campaign['selectiveOptimization'] = { + # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] + # } + + # Optional: Set the campaign settings for Advanced location options. + universal_app_campaign['settings'].append({ + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + }) + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': universal_app_campaign + }] + + campaigns = campaign_service.mutate(operations)['value'] + + # Display results. + if campaigns: + for campaign in campaigns: + print ('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + # Optional: Set the campaign's location and language targeting. No other + # targeting criteria can be used for Universal App campaigns. + SetCampaignTargetingCriteria(client, campaign) + else: + print 'No Universal App campaigns were added.' + + +def CreateBudget(client): + """Creates a budget and returns its budgetId. + + Args: + client: An AdWordsClient instance. + + Returns: + An int budgetId for the created Budget. + """ + budget_service = client.GetService('BudgetService', version='v201710') + + # Create a budget. + budget = { + 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Create the budget and return its ID. + budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] + + return budget_id + + +def SetCampaignTargetingCriteria(client, campaign): + """Sets targeting criteria for the given campaign. + + Args: + client: An AdWordsClient instance. + campaign: A suds object representing the campaign we wish to attach + targeting criteria. + """ + campaign_criterion_service = client.GetService('CampaignCriterionService') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + criteria = [ + { + 'xsi_type': 'Location', + 'id': 21137 # California + }, + { + 'xsi_type': 'Location', + 'id': 2484 # Mexico + }, + { + 'xsi_type': 'Language', + 'id': 1000 # English + }, + { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + ] + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign['id'], + 'criterion': criterion + } + } for criterion in criteria] + + response = campaign_criterion_service.mutate(operations) + + if response and 'value' in response: + # Display the added campaign targets. + for criterion in response['value']: + print ('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], + criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..e510d813 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201710') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201710') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201710') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..34c27532 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201710') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201710') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..5e65078a --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201710') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..ab912ab5 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201710') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201710') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201710') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201710/basic_operations/__init__.py b/examples/adwords/v201710/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201710/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201710/basic_operations/add_ad_groups.py b/examples/adwords/v201710/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..e38048e1 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201710') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name "%s" and id "%s" was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/basic_operations/add_campaigns.py b/examples/adwords/v201710/basic_operations/add_campaigns.py new file mode 100755 index 00000000..7789c2c1 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/add_campaigns.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201710') + budget_service = client.GetService('BudgetService', version='v201710') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201710/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..d3394999 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/add_keywords.py b/examples/adwords/v201710/basic_operations/add_keywords.py new file mode 100755 index 00000000..4b1b0cec --- /dev/null +++ b/examples/adwords/v201710/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201710') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/get_ad_groups.py b/examples/adwords/v201710/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..719942e1 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201710') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name "%s", id "%s" and status "%s" was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/basic_operations/get_campaigns.py b/examples/adwords/v201710/basic_operations/get_campaigns.py new file mode 100755 index 00000000..b2a01f80 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/get_campaigns.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import time +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201710') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..5e15cf7c --- /dev/null +++ b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201710') + + # Construct query and get all campaigns. + offset = 0 + query = 'SELECT Id, Name, Status ORDER BY Name' + + more_pages = True + while more_pages: + page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201710/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..77046b40 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an expanded text ad, run add_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/get_keywords.py b/examples/adwords/v201710/basic_operations/get_keywords.py new file mode 100755 index 00000000..5feec2b1 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201710') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/pause_ad.py b/examples/adwords/v201710/basic_operations/pause_ad.py new file mode 100755 index 00000000..f51e1f90 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id "%s" was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201710/basic_operations/remove_ad.py b/examples/adwords/v201710/basic_operations/remove_ad.py new file mode 100755 index 00000000..4ea3a4ec --- /dev/null +++ b/examples/adwords/v201710/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id "%s" and type "%s" was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201710/basic_operations/remove_ad_group.py b/examples/adwords/v201710/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..2a372bc8 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201710') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name "%s" and id "%s" was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/remove_campaign.py b/examples/adwords/v201710/basic_operations/remove_campaign.py new file mode 100755 index 00000000..4e4e84f6 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201710') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name "%s" and id "%s" was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/basic_operations/remove_keyword.py b/examples/adwords/v201710/basic_operations/remove_keyword.py new file mode 100755 index 00000000..a5a13312 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201710') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201710/basic_operations/update_ad_group.py b/examples/adwords/v201710/basic_operations/update_ad_group.py new file mode 100755 index 00000000..d17a8cc8 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/update_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201710') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name "%s" and id "%s" was updated.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/update_campaign.py b/examples/adwords/v201710/basic_operations/update_campaign.py new file mode 100755 index 00000000..9f0e4dc2 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201710') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/basic_operations/update_keyword.py b/examples/adwords/v201710/basic_operations/update_keyword.py new file mode 100755 index 00000000..b140a592 --- /dev/null +++ b/examples/adwords/v201710/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201710') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: "%s", value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201710/campaign_management/__init__.py b/examples/adwords/v201710/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py new file mode 100755 index 00000000..27cc2172 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a campaign group and sets a performance target for it. + +To get campaigns, run get_campaigns.py. To download reports, run +download_criteria_report_with_awql.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id1, campaign_id2): + campaign_group_id = _CreateCampaignGroup(client) + _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) + _CreatePerformanceTarget(client, campaign_group_id) + print 'Campaign group and its performance target were setup successfully.' + + +def _CreateCampaignGroup(client): + """Create a campaign group. + + Args: + client: an AdWordsClient instance. + + Returns: + The integer ID of the created campaign group. + """ + # Get the CampaignGroupService. + campaign_group_service = client.GetService('CampaignGroupService', + version='v201710') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the campaign group. + 'operand': { + 'name': 'Mars campaign group #%d' % uuid.uuid4() + } + }] + + campaign_group = campaign_group_service.mutate(operations)['value'][0] + campaign_group_id = campaign_group['id'] + + # Display the results. + print 'Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name']) + + return campaign_group_id + + +def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): + """Adds multiple campaigns to a campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + campaign_ids: a list of integer IDs for campaigns. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201710') + + # Create the operations. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'campaignGroupId': campaign_group_id + } + } for campaign_id in campaign_ids] + + campaign_service.mutate(operations) + + # Display the results. + print ('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + + +def _CreatePerformanceTarget(client, campaign_group_id): + """Creates a performance target for the campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + """ + # Get the CampaignGroupPerformanceTargetService. + cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', + version='v201710') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the performance target. + 'operand': { + 'campaignGroupId': campaign_group_id, + 'performanceTarget': { + # Keep the CPC for the campaigns < $3. + 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', + 'efficiencyTargetValue': 3000000, + # Keep the maximum spend under $50. + 'spendTargetType': 'MAXIMUM', + 'spendTarget': { + 'microAmount': 500000000 + }, + # Aim for at least 3000 clicks. + 'volumeGoalType': 'MAXIMIZE_CLICKS', + 'volumeTargetValue': 3000, + # Start the performance target today, and run it for the next 90 + # days. + 'startDate': datetime.datetime.now().strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(90)).strftime('%Y%m%d') + } + } + }] + + cgpt = cgpt_service.mutate(operations)['value'][0] + + # Display the results. + print ('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201710/campaign_management/add_campaign_labels.py b/examples/adwords/v201710/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..ec7f1adc --- /dev/null +++ b/examples/adwords/v201710/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201710') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..1d00652b --- /dev/null +++ b/examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201710') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201710') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding an ExpandedTextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new ExpandedTextAd for + each of the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once + # you've added targeting and the ads are ready to serve. + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201710') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201710/campaign_management/add_draft.py b/examples/adwords/v201710/campaign_management/add_draft.py new file mode 100755 index 00000000..4a63c846 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + draft_service = client.GetService('DraftService', version='v201710') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201710') + + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..5fddf5b5 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201710') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201710') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201710') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201710') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201710/campaign_management/add_trial.py b/examples/adwords/v201710/campaign_management/add_trial.py new file mode 100755 index 00000000..00382eef --- /dev/null +++ b/examples/adwords/v201710/campaign_management/add_trial.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201710') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201710') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..b5e858b7 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'PolicySummary'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CombinedApprovalStatus', + 'operator': 'EQUALS', + 'values': 'DISAPPROVED' + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + disapproved_count = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.get(selector) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName'], + policy_topic_entry['policyTopicHelpCenterUrl']) + # Display the attributes and values that triggered the policy topic. + policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] + if policy_topic_evidences: + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..2f621a9b --- /dev/null +++ b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', + version='v201710') + + # Construct query and get all ads for a given campaign. + query = ('SELECT Id, PolicySummary ' + 'WHERE AdGroupId = %s AND CombinedApprovalStatus = DISAPPROVED ' + 'ORDER BY Id' % ad_group_id) + more_pages = True + disapproved_count = 0 + offset = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.query(query + ' LIMIT %s, %s' % ( + offset, PAGE_SIZE)) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + # Display the attributes and values that triggered the policy topic. + policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] + if policy_topic_evidences: + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + offset += PAGE_SIZE + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..4aee0506 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201710') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id "%s", name "%s", and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + time.sleep(1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201710/campaign_management/graduate_trial.py b/examples/adwords/v201710/campaign_management/graduate_trial.py new file mode 100755 index 00000000..c4f1945b --- /dev/null +++ b/examples/adwords/v201710/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201710') + budget_service = client.GetService('BudgetService', version='v201710') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201710/campaign_management/set_ad_parameters.py b/examples/adwords/v201710/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..e3a54c48 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + ad_param_service = client.GetService('AdParamService', version='v201710') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..e2a524d7 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201710') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201710/campaign_management/validate_text_ad.py b/examples/adwords/v201710/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..a5cd9f11 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +No objects will be created, but exceptions will still be returned. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Construct operations to add an expanded text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'] + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for all astronauts in orbit', + 'finalUrls': ['http://www.example.com'], + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with "%s".' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/error_handling/__init__.py b/examples/adwords/v201710/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201710/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201710/error_handling/handle_partial_failures.py b/examples/adwords/v201710/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..1a4633ba --- /dev/null +++ b/examples/adwords/v201710/error_handling/handle_partial_failures.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201710') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + if (first_field_path_element and + first_field_path_element['field'] == 'operations' and + first_field_path_element['index']): + operation_index = first_field_path_element['index'] + + adgroup_criterion = operations[operation_index]['operand'] + + print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' + 'a failure for the following reason: %s.' + % (adgroup_criterion['adGroupId'], + adgroup_criterion['criterion']['text'], + error['errorString'])) + else: + print ('A failure has occurred for the following reasons: %s\n' + % error['errorString']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/error_handling/handle_policy_violation_error.py b/examples/adwords/v201710/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..cb8f9ac0 --- /dev/null +++ b/examples/adwords/v201710/error_handling/handle_policy_violation_error.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201710') + + # Create expanded text ad that violates an exemptable policy. + exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise!!!', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + # Create text ad that violates a non-exemptable policy. + non_exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise with too long of a headline.', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + operations = [exemptable_expanded_text_ad_operation, + non_exemptable_expanded_text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + # Get the index of the failed operation from the error's field path + # elements. + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + # If the operation index is not present on the first error field path + # element, then there's no way to determine which operation to remove, + # so simply throw the exception. + if (not (first_field_path_element + and first_field_path_element['field'] == 'operations' + and first_field_path_element['index'])): + raise e + + operation_index = first_field_path_element['index'] + index = int(operation_index[0]) + operation = operations[index] + if not HandleAPIError(error, operation): + # Set non-exemptable operation to None to mark for deletion. + print ('Removing operation with non-exemptable error at index %s.' + % operation_index) + operations[index] = None + + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is "%s".' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +def HandleAPIError(error, operation): + """Makes an exemption for exemptable PolicyViolationErrors. + + Args: + error: the error associated with the given operation. + operation: the operation associated with the given error. + + Returns: + A boolean that is True if the given error was an exemptable + PolicyViolationError; otherwise, returns False. + """ + is_exemptable = False + + # Determine if the operation can be resubmitted with an exemption request. + if error['ApiError.Type'] == 'PolicyViolationError': + expanded_text_ad = operation['operand']['ad'] + is_exemptable = (error['isExemptable'] if 'isExemptable' in error else + False) + print ('Ad with headline "%s - %s" violated %s policy "%s".' % + (expanded_text_ad['headlinePart1'], + expanded_text_ad['headlinePart2'], + 'exemptable' if is_exemptable else 'non-exemptable', + error['externalPolicyName'])) + + if is_exemptable: + # Add exemption request to the operation. + print ('Adding exemption request for policy name "%s" on text "%s".' + % (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({'key': error['key']}) + + return is_exemptable + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/extensions/__init__.py b/examples/adwords/v201710/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201710/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..2410773f --- /dev/null +++ b/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201710').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201710') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201710/extensions/add_prices.py b/examples/adwords/v201710/extensions/add_prices.py new file mode 100755 index 00000000..b1856b3d --- /dev/null +++ b/examples/adwords/v201710/extensions/add_prices.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201710') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', + final_mobile_url='http://m.example.com/scrubs'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url='http://m.example.com/haircuts'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url=( + 'http://m.example.com/skincarepackage')) + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit, final_mobile_url=None): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + final_mobile_url: A str containing the final mobile URL after all cross + domain redirects. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + table_row = { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + if final_mobile_url: + table_row['finalMobileUrls'] = { + 'urls': [final_mobile_url] + } + + return table_row + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/extensions/add_site_links.py b/examples/adwords/v201710/extensions/add_site_links.py new file mode 100755 index 00000000..0405eef8 --- /dev/null +++ b/examples/adwords/v201710/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201710') + customer_service = client.GetService('CustomerService', version='v201710') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/extensions/add_site_links_using_feeds.py b/examples/adwords/v201710/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..a80525df --- /dev/null +++ b/examples/adwords/v201710/extensions/add_site_links_using_feeds.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201710') + feed_item_service = client.GetService('FeedItemService', version='v201710') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201710') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201710') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name "%s" and ID "%s" was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line2': 'Home line 2', 'line3': 'Home line 3'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line2': 'Support line 2', 'line3': 'Support line 3'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line2': 'Products line 2', 'line3': 'Products line 3'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + feed_item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/migration/__init__.py b/examples/adwords/v201710/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201710/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201710/migration/migrate_to_extension_settings.py b/examples/adwords/v201710/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..aaf75c22 --- /dev/null +++ b/examples/adwords/v201710/migration/migrate_to_extension_settings.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201710') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201710') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201710') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201710') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201710') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201710') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201710') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/misc/__init__.py b/examples/adwords/v201710/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201710/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201710/misc/get_all_images_and_videos.py b/examples/adwords/v201710/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..98a258aa --- /dev/null +++ b/examples/adwords/v201710/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201710') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/misc/upload_image.py b/examples/adwords/v201710/misc/upload_image.py new file mode 100755 index 00000000..ba035520 --- /dev/null +++ b/examples/adwords/v201710/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201710') + + with open(image_filename, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201710/misc/upload_media_bundle.py b/examples/adwords/v201710/misc/upload_media_bundle.py new file mode 100755 index 00000000..966f4b63 --- /dev/null +++ b/examples/adwords/v201710/misc/upload_media_bundle.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201710') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/optimization/__init__.py b/examples/adwords/v201710/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201710/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201710/optimization/estimate_keyword_traffic.py b/examples/adwords/v201710/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..0b96d72a --- /dev/null +++ b/examples/adwords/v201710/optimization/estimate_keyword_traffic.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201710') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..2139b135 --- /dev/null +++ b/examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201710') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201710/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..c25bf993 --- /dev/null +++ b/examples/adwords/v201710/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201710') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages: + num_landscape_points = 0 + page = data_service.getCriterionBidLandscape(selector) + + if page and 'entries' in page: + entries = page['entries'] + print 'Bid landscape(s) retrieved: %d.' % len(entries) + + for bid_landscape in entries: + print ('Retrieved keyword bid landscape with ad group ID "%d", ' + 'keyword ID "%d", start date "%s", end date "%s", ' + 'with landscape points:' % ( + bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + num_landscape_points += 1 + print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'])) + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201710/optimization/get_keyword_ideas.py b/examples/adwords/v201710/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..a307aac8 --- /dev/null +++ b/examples/adwords/v201710/optimization/get_keyword_ideas.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id=None): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201710') + + # Construct selector object and retrieve related keywords. + selector = { + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS' + } + + selector['requestedAttributeTypes'] = [ + 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] + + offset = 0 + selector['paging'] = { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + + selector['searchParameters'] = [{ + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }] + + # Language setting (optional). + selector['searchParameters'].append({ + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }) + + # Network search parameter (optional) + selector['searchParameters'].append({ + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + }) + + # Use an existing ad group to generate ideas (optional) + if ad_group_id is not None: + selector['searchParameters'].append({ + 'xsi_type': 'SeedAdGroupIdSearchParameter', + 'adGroupId': ad_group_id + }) + + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr( + attribute['value'], 'value', '0') + print ('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201710/remarketing/__init__.py b/examples/adwords/v201710/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201710/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201710/remarketing/add_audience.py b/examples/adwords/v201710/remarketing/add_audience.py new file mode 100755 index 00000000..f9fd2d60 --- /dev/null +++ b/examples/adwords/v201710/remarketing/add_audience.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201710') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201710') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + result = user_list_service.mutate(operations) + + # Display results. + if 'value' in result: + conversion_ids = [] + for user_list in result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + selector = { + 'fields': ['Name', 'Status', 'Category'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': conversion_ids + }], + 'ordering': [{ + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }] + } + + pages = conversion_tracker_service.get(selector) + conversions_map = {} + if pages['entries']: + for conversion_tracker in pages['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in result['value']: + print ('User list with name "%s" and ID "%s" was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Conversion type code snippet associated to the list:\n%s\n' + % conversion_tracker['snippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/add_conversion_tracker.py b/examples/adwords/v201710/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..0b059389 --- /dev/null +++ b/examples/adwords/v201710/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201710') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/add_conversion_trackers.py b/examples/adwords/v201710/remarketing/add_conversion_trackers.py new file mode 100755 index 00000000..1bf5ed31 --- /dev/null +++ b/examples/adwords/v201710/remarketing/add_conversion_trackers.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds AdWords conversion trackers. + +Adds an AdWords conversion tracker and an upload conversion tracker. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201710') + + # Create an AdWords conversion tracker. + adwords_conversion_tracker = { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'name': 'Upload Conversion #%s' % uuid.uuid4(), + # Optional fields. + # Set an appropriate category. This will be set to DEFAULT if not + # specified. + 'category': 'LEAD', + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90', + # Set the default currency code to use for conversions that do + # not specify a conversion currency. This must be an ISO 4217 3-character + # code such as "EUR" or "USD". + # If this field is not set, AdWords will use the account's currency. + 'defaultRevenueCurrencyCode': 'EUR', + # Set the default revenue value to use for conversions that do not specify + # a converison value. Note that this value should NOT be in micros. + 'defaultRevenueValue': '2.50', + # To upload fractional conversion credits, mark the upload conversion as + # externally attributed. To learn more about importing externally + # attributed conversions, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'isExternallyAttributed': 'true' + } + + # Construct operations. + operations = [{ + 'operator': 'ADD', + 'operand': conversion_tracker + } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] + + # Add the conversions. + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + if (conversion_tracker['ConversionTracker.Type'] + is 'AdWordsConversionTracker'): + print ('Conversion tracker with ID "%d", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + else: + print ('Conversion with ID "%d", name "%s", status "%s", and category ' + '"%s" was added.' + % (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/add_crm_based_user_list.py b/examples/adwords/v201710/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..faaf9c84 --- /dev/null +++ b/examples/adwords/v201710/remarketing/add_crm_based_user_list.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201710') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # Maximum lifespan is 180 days. + 'membershipLifeSpan': 180 + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + + emails = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] + + # Optional: AddressInfo is only accessible to whitelisted customers. + # If you are not on the whitelist, you should leave this code commented out. + # members.append({ + # 'addressInfo': { + # 'hashedFirstName': NormalizeAndSHA256('John'), + # 'hashedLastName': NormalizeAndSHA256('Doe'), + # 'countryCode': 'US', + # 'zipCode': '10001' + # } + # }) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'membersList': members + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def NormalizeAndSHA256(s): + """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. + + Args: + s: The string to perform this operation on. + + Returns: + A normalized and SHA-256 hashed string. + """ + return hashlib.sha256(s.strip().lower()).hexdigest() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201710/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..521d2cee --- /dev/null +++ b/examples/adwords/v201710/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201710') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords knows how to apply the + # rules. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ], + # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF + # means 'at least one item in each rule item group must match', and DNF + # means 'at least one entire rule item group must match'. + # DateSpecificRuleUserList only supports DNF. You can also omit the rule + # type altogether to default to DNF. + 'ruleType': 'DNF' + } + + # Third and fourth rule item groups. + # Visitors of a page who visited another page. + site1_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example1' + } + } + site2_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example2' + } + } + + # Create two rules to show that a visitor browsed two sites. + user_visited_site1_rule = { + 'groups': [{ + 'items': [site1_rule_item] + }] + } + + user_visited_site2_rule = { + 'groups': [{ + 'items': [site2_rule_item] + }] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule, + # Optional: Set the populationStatus to REQUESTED to include past users in + # the user list. + 'prepopulationStatus': 'REQUESTED' + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create the user list for "Visitors of a page who did visit another page". + # To create a user list for "Visitors of a page who did not visit another + # page", change the ruleOperator from AND to AND_NOT. + combined_user_list = { + 'xsi_type': 'CombinedRuleUserList', + 'name': 'Combined rule user lst create at ${creation_time}', + 'description': 'Users who visited two sites.', + 'leftOperand': user_visited_site1_rule, + 'rightOperand': user_visited_site2_rule, + 'ruleOperator': 'AND' + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list, + combined_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201710/remarketing/upload_offline_call_conversions.py new file mode 100755 index 00000000..4bb6851b --- /dev/null +++ b/examples/adwords/v201710/remarketing/upload_offline_call_conversions.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for calls related to ads in your account. + +To set up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CALLER_ID = 'INSERT_CALLER_ID_HERE' +# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats +# For time zones, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +CALL_START_TIME = 'INSERT_CALL_START_TIME' +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, caller_id, call_start_time, conversion_name, conversion_time, + conversion_value): + # Initialize appropriate services. + occ_feed_service = client.GetService( + 'OfflineCallConversionFeedService', version='v201710') + + # Associate offline call conversions with the existing named conversion + # tracker. If this tracker was newly created, it may be a few hours before it + # can accept conversions. + feed = { + 'callerId': caller_id, + 'callStartTime': call_start_time, + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + } + + occ_operations = [{'operator': 'ADD', 'operand': feed}] + + occ_response = occ_feed_service.mutate(occ_operations) + values = occ_response['value'] + + if values: + for occ_feed in values: + print ('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + else: + print 'No offline call conversions were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, + CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201710/remarketing/upload_offline_conversions.py b/examples/adwords/v201710/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..7671c7b5 --- /dev/null +++ b/examples/adwords/v201710/remarketing/upload_offline_conversions.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201710') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id, + # Optional: To upload fractional conversion credits, set the external + # attribution model and credit. To use this feature, your conversion + # tracker should be marked as externally attributed. To learn more about + # importing externally attributed conversins, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'externalAttributionCredit': 0.3, + # 'externalAttributionModel': 'Linear' + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201710/remarketing/upload_offline_data.py b/examples/adwords/v201710/remarketing/upload_offline_data.py new file mode 100755 index 00000000..c687000d --- /dev/null +++ b/examples/adwords/v201710/remarketing/upload_offline_data.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 shows how to upload offline data for store sales transactions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import datetime +import hashlib + +from googleads import adwords +import pytz + + +_DT_FORMAT = '%Y%m%d %H%M%S' +# User identifier types whose values must be hashed. +_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', + 'HASHED_LAST_NAME', 'HASHED_PHONE') +# The timezone to be used in this example. For valid timezone IDs, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +_TIMEZONE = pytz.timezone('America/New_York') +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Insert email addresses below for creating user identifiers. +EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] +# The external upload ID can be any number that you use to keep track of your +# uploads. +EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' + + +def main(client, conversion_name, external_upload_id, email_addresses): + # Initialize appropriate services. + offline_data_upload_service = client.GetService( + 'OfflineDataUploadService', version='v201710') + + # Create the first offline data for upload. + # This transaction occurred 7 days ago with an amount of $200 USD. + transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=7)) + offline_data_1 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[0]), + _CreateUserIdentifier(identifier_type='STATE', value='New York') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_1), + 'transactionAmount': { + 'currencyCode': 'USD', + 'money': { + 'microAmount': 200000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create the second offline data for upload. + # This transaction occurred 14 days ago with amount of 450 EUR. + transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=14)) + offline_data_2 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[1]), + _CreateUserIdentifier(identifier_type='STATE', value='California') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_2), + 'transactionAmount': { + 'currencyCode': 'EUR', + 'money': { + 'microAmount': 450000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create offline data upload + offline_data_upload = { + 'externalUploadId': external_upload_id, + 'offlineDataList': [offline_data_1, offline_data_2], + # Optional: You can set the type of this upload. + # 'uploadType': 'STORE_SALES_UPLOAD_FIRST_PARTY' + } + + # Create an offline data upload operation. + operations = [{ + 'operator': 'ADD', + 'operand': offline_data_upload + }] + + # Upload offline data on the server and print the result. + result = offline_data_upload_service.mutate(operations) + offline_data_upload = result['value'][0] + + print ('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) + + # Print any partial data errors from the response. The order of the partial + # data errors list is the same as the uploaded offline data list in the + # request. + for i, partial_data_error in enumerate( + offline_data_upload['partialDataErrors']): + # If a partial error occurred for this offline data, print the error. Note + # that non-errors for a given offline data would be set to None. + if partial_data_error: + print ('Found a partial error for offline data #%d with error string: %s' + % (i, partial_data_error['errorString'])) + + +def _CreateUserIdentifier(identifier_type=None, value=None): + """Creates a user identifier from the specified type and value. + + Args: + identifier_type: a str specifying the type of user identifier. + value: a str value of the identifier; to be hashed using SHA-256 if needed. + + Returns: + A dict specifying a user identifier, with a value hashed using SHA-256 if + needed. + """ + if identifier_type in _HASHED_IDENTIFIER_TYPES: + # If the user identifier type is a hashed type, normalize and hash the + # value. + value = hashlib.sha256(value.strip().lower()).hexdigest() + + user_identifier = { + 'userIdentifierType': identifier_type, + 'value': value + } + + return user_identifier + + +def _GetFormattedDateTime(dt): + """Formats the given datetime and timezone for use with AdWords. + + Args: + dt: a datetime instance. + + Returns: + A str representation of the datetime in the correct format for AdWords. + """ + return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, EMAIL_ADDRESSES) diff --git a/examples/adwords/v201710/reporting/__init__.py b/examples/adwords/v201710/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201710/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..7c984bb2 --- /dev/null +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201710') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py new file mode 100755 index 00000000..0c453b81 --- /dev/null +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201710') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..6586e7f7 --- /dev/null +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201710') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py new file mode 100755 index 00000000..536d32d7 --- /dev/null +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201710') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..6d92fb42 --- /dev/null +++ b/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import sys +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201710') + + # Create report query. + report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' + 'FinalUrls, Impressions, Clicks, Cost ' + 'FROM CRITERIA_PERFORMANCE_REPORT ' + 'WHERE Status IN [ENABLED, PAUSED] ' + 'DURING LAST_7_DAYS') + + # You can provide a file object to write the output to. For this + # demonstration we use sys.stdout to write the report to the screen. + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', sys.stdout, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py new file mode 100755 index 00000000..0e262215 --- /dev/null +++ b/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201710') + + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201710/reporting/get_report_fields.py b/examples/adwords/v201710/reporting/get_report_fields.py new file mode 100755 index 00000000..5d6b7fa9 --- /dev/null +++ b/examples/adwords/v201710/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201710') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type "%s" contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201710/reporting/parallel_report_download.py b/examples/adwords/v201710/reporting/parallel_report_download.py new file mode 100755 index 00000000..0f916494 --- /dev/null +++ b/examples/adwords/v201710/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201710') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201710') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201710/shopping/__init__.py b/examples/adwords/v201710/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201710/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201710/shopping/add_product_partition_tree.py b/examples/adwords/v201710/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..a146762e --- /dev/null +++ b/examples/adwords/v201710/shopping/add_product_partition_tree.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201710') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201710/shopping/add_product_scope.py b/examples/adwords/v201710/shopping/add_product_scope.py new file mode 100755 index 00000000..65b384c7 --- /dev/null +++ b/examples/adwords/v201710/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201710') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/shopping/add_shopping_campaign.py b/examples/adwords/v201710/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..81815a25 --- /dev/null +++ b/examples/adwords/v201710/shopping/add_shopping_campaign.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +# If set to true, a default partition will be created. If running the +# add_product_partition_tree.py example right after this example, make +# sure this stays set to false. +CREATE_DEFAULT_PARTITION = False +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id, create_default_partition): + campaign_service = client.GetService('CampaignService', version='v201710') + ad_group_service = client.GetService('AdGroupService', version='v201710') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + ad_group = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': ad_group + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': ad_group_id, + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201710') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + }, + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 500000 + } + }] + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py new file mode 100755 index 00000000..f348c422 --- /dev/null +++ b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py @@ -0,0 +1,404 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds a Shopping campaign for Showcase ads. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import uuid + +from googleads import adwords +from suds import WebFault + + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' +EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' +COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server we + # do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + next_id = -1 + + # The set of mutate operations needed to create the current tree. + operations = [] + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + # Note: Showcase ads require either ManualCpc or EnhancedCpc in the + # campaign's BiddingStrategyConfiguration. + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, budget_id, merchant_id, expanded_image_filepath, + collapsed_image_filepath): + try: + # Create the Shopping Campaign + campaign = CreateShoppingCampaign(client, budget_id, merchant_id) + + # Create the AdGroup + adgroup = CreateAdGroup(client, campaign['id']) + + # Create a Showcase Ad + CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath) + + product_partition_tree = CreateProductPartition(client, adgroup['id']) + print 'Final tree:\n%s' % product_partition_tree + except WebFault: + print 'Failed to create shopping campaign for showcase ads.' + raise + + +def CreateShoppingCampaign(client, budget_id, merchant_id): + """Creates a shopping campaign with the given budget and merchant IDs. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + shopping campaign. + + Returns: + The created Shopping Campaign as a sudsobject. + """ + campaign_service = client.GetService('CampaignService', 'v201710') + + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + campaign = campaign_service.mutate(campaign_operations)['value'][0] + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + return campaign + + +def CreateAdGroup(client, campaign_id): + """Creates an AdGroup for the given shopping campaign ID. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a shopping campaign. + + Returns: + The created AdGroup as a sudsobject. + """ + ad_group_service = client.GetService('AdGroupService', 'v201710') + + adgroup = { + # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS + 'adGroupType': 'SHOPPING_SHOWCASE_ADS', + 'campaignId': campaign_id, + 'name': 'AdGroup #%s' % uuid.uuid4(), + # REQUIRED: Set the ad group's bidding strategy configuration. + 'biddingStrategyConfiguration': { + # Showcase ads require either ManualCpc or EnhancedCpc. + 'biddingStrategyType': 'MANUAL_CPC', + # Optional: Set the bids + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 100000 + } + }] + } + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) + + return adgroup + + +def CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath): + """Creates a showcase add for the given AdGroup with the given images. + + Args: + client: an AdWordsClient instance. + adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + expanded_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's expandedImage. + collapsed_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's collapsedImage. + + Returns: + The created Showcase Ad as a sudsobject. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201710') + + showcase_ad = { + 'adGroupId': adgroup['id'], + 'ad': { + 'xsi_type': 'ShowcaseAd', + 'Ad.Type': 'ShowcaseAd', + # Required: set the ad's name, final URLs, and display URL. + 'name': 'Showcase ad #%s' % uuid.uuid4(), + 'finalUrls': 'http://example.com/showcase', + 'displayUrl': 'example.com', + # Required: Set the ad's expanded image. + 'expandedImage': { + 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] + }, + # Optional: Set the collapsed image. + 'collapsedImage': { + 'mediaId': + UploadImage(client, collapsed_image_filepath)['mediaId'] + } + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': showcase_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] + + print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + + return showcase_ad + + +def UploadImage(client, filepath): + """Uploads a .jpg image with the given filepath via the AdWords MediaService. + + Args: + client: an AdWordsClient instance. + filepath: a str filepath to the .jpg file to be uploaded. + + Returns: + The created Image as a sudsobject. + """ + media_service = client.GetService('MediaService', 'v201710') + + with open(filepath, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + image = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + + image = media_service.upload(image)[0] + + return image + + +def CreateProductPartition(client, adgroup_id): + """Creates a ProductPartition tree for the given AdGroup ID. + + Args: + client: an AdWordsClient instance. + adgroup_id: a str AdGroup ID. + + Returns: + The ProductPartition tree as a sudsobject. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + 'v201710') + helper = ProductPartitionHelper(adgroup_id) + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition) + helper.CreateUnit(root, used_product_canonical_condition) + helper.CreateUnit(root, other_product_canonical_condition) + + result = ad_group_criterion_service.mutate(helper.operations) + return result['value'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, + COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201710/shopping/get_product_category_taxonomy.py b/examples/adwords/v201710/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..8a769c26 --- /dev/null +++ b/examples/adwords/v201710/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201710') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/targeting/__init__.py b/examples/adwords/v201710/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201710/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..1b464c56 --- /dev/null +++ b/examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201710') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201710/targeting/add_customer_negative_criteria.py b/examples/adwords/v201710/targeting/add_customer_negative_criteria.py new file mode 100755 index 00000000..474b9430 --- /dev/null +++ b/examples/adwords/v201710/targeting/add_customer_negative_criteria.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds various types of negative criteria to a customer. + +These criteria will be applied to all campaigns for the customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_negative_criterion_service = client.GetService( + 'CustomerNegativeCriterionService', version='v201710') + + criteria = [ + # Exclude tragedy & conflict content. + { + 'xsi_type': 'ContentLabel', + 'contentLabelType': 'TRAGEDY' + }, + # Exclude a specific placement. + { + 'xsi_type': 'Placement', + 'url': 'http://www.example.com' + } + # Additional criteria types are available for this service. See the types + # listed under Criterion here: + # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion + ] + + # Create operations to add each of the criteria above. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'criterion': criterion + } + } for criterion in criteria] + + # Make the mutate request. + result = customer_negative_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for negative_criterion in result['value']: + print ('Customer negative criterion with criterion ID "%s", and type "%s" ' + 'was added.' % (negative_criterion['criterion']['id'], + negative_criterion['criterion']['type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..da284e19 --- /dev/null +++ b/examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201710') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type "%s" was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..a5fc78b7 --- /dev/null +++ b/examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201710') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..c874487d --- /dev/null +++ b/examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201710') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name "%s" and ID "%s" was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name "%s", ID "%s", and country code "%s" was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201710/targeting/lookup_location.py b/examples/adwords/v201710/targeting/lookup_location.py new file mode 100755 index 00000000..4ba82ba7 --- /dev/null +++ b/examples/adwords/v201710/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201710') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/dfp/v201702/creative_service/create_native_creative.py b/examples/dfp/v201702/creative_service/create_native_creative.py index b2921671..075f7841 100755 --- a/examples/dfp/v201702/creative_service/create_native_creative.py +++ b/examples/dfp/v201702/creative_service/create_native_creative.py @@ -52,10 +52,12 @@ def main(client, advertiser_id): creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - image_data = base64.b64encode(image_data) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(image_data).decode('utf-8') app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - app_icon_data = base64.b64encode(app_icon_data) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + app_icon_data = base64.b64encode(app_icon_data).decode('utf-8') # Create creative from templates. creative = { diff --git a/examples/dfp/v201705/creative_service/create_native_creative.py b/examples/dfp/v201705/creative_service/create_native_creative.py index b32309a3..0421823d 100755 --- a/examples/dfp/v201705/creative_service/create_native_creative.py +++ b/examples/dfp/v201705/creative_service/create_native_creative.py @@ -52,10 +52,12 @@ def main(client, advertiser_id): creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - image_data = base64.b64encode(image_data) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(image_data).decode('utf-8') app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - app_icon_data = base64.b64encode(app_icon_data) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + app_icon_data = base64.b64encode(app_icon_data).decode('utf-8') # Create creative from templates. creative = { diff --git a/examples/dfp/v201708/creative_service/create_native_creative.py b/examples/dfp/v201708/creative_service/create_native_creative.py index c92e4926..22566070 100755 --- a/examples/dfp/v201708/creative_service/create_native_creative.py +++ b/examples/dfp/v201708/creative_service/create_native_creative.py @@ -52,10 +52,12 @@ def main(client, advertiser_id): creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - image_data = base64.b64encode(image_data) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(image_data).decode('utf-8') app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - app_icon_data = base64.b64encode(app_icon_data) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + app_icon_data = base64.b64encode(app_icon_data).decode('utf-8') # Create creative from templates. creative = { diff --git a/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py index fdf43b91..c09c6054 100755 --- a/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py +++ b/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py @@ -40,7 +40,7 @@ def main(client): 'rateType': 'CPM', 'lineItemType': 'STANDARD', 'priority': 8, - 'environment': 'BROWSER', + 'environmentType': 'BROWSER', 'rate': { 'currencyCode': 'USD', 'microAmount': '6000000' @@ -61,10 +61,10 @@ def main(client): ], 'builtInTargeting': { 'inventoryTargeting': { - 'adUnitTargeting': { + 'targetedAdUnits': { 'adUnitId': network_service.getCurrentNetwork()[ 'effectiveRootAdUnitId'], - 'includeDescendents': 'true' + 'includeDescendants': 'true' } } }, diff --git a/googleads/adwords.py b/googleads/adwords.py index c38ce9cf..c5b930ce 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -178,7 +178,58 @@ 'MediaService': 'cm', 'OfflineCallConversionFeedService': 'cm', 'OfflineConversionFeedService': 'cm', - 'OfflineDataUploadService': 'cm', + 'OfflineDataUploadService': 'rm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' + }, + 'v201710': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignBidModifierService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignGroupPerformanceTargetService': 'cm', + 'CampaignGroupService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerNegativeCriterionService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'FeedItemService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineCallConversionFeedService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'OfflineDataUploadService': 'rm', 'ReportDefinitionService': 'cm', 'SharedCriterionService': 'cm', 'SharedSetService': 'cm', @@ -664,11 +715,18 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): 'CampaignService', 'mutate'), 'CampaignLabelOperation': _OPERATION('CampaignLabelOperation', 'CampaignService', 'mutateLabel'), + 'CampaignSharedSetOperation': _OPERATION( + 'CampaignSharedSetOperation', 'CampaignSharedSetService', + 'mutate'), 'CustomerExtensionSettingOperation': _OPERATION( 'CustomerExtensionSettingOperation', 'CustomerExtensionSettingService', 'mutate'), 'FeedItemOperation': _OPERATION('FeedItemOperation', 'FeedItemService', - 'mutate') + 'mutate'), + 'SharedCriterionOperation': _OPERATION( + 'SharedCriterionOperation', 'SharedCriterionService', 'mutate'), + 'SharedSetOperation': _OPERATION('SharedSetOperation', + 'SharedSetService', 'mutate') } def __init__(self, client, **kwargs): diff --git a/googleads/common.py b/googleads/common.py index 6f60d143..d21cbcf2 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -66,7 +66,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '8.0.0' +VERSION = '8.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 96ea7966..1a301bc5 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -539,6 +539,25 @@ def testSetClientCustomerId(self): self.assertEqual(ccid, soap_header.clientCustomerId) +class AdWordsClientIntegrationTest(unittest.TestCase): + """Integration tests for googleads.adwords.AdWordsClient.""" + + def testServiceMap(self): + server = googleads.adwords._DEFAULT_ENDPOINT + service_map = googleads.adwords._SERVICE_MAP + wsdl_url_template = googleads.adwords.AdWordsClient._SOAP_SERVICE_FORMAT + + for version, services in service_map.items(): + for service, mapping in services.items(): + wsdl_url = wsdl_url_template % (server, mapping, version, service) + try: + urllib2.urlopen(wsdl_url) + except urllib2.HTTPError: + raise ValueError('AdWords API %s does not contain "%s" with mapping ' + '"%s". The generated WSDL URL does not exist:\n%s' + % (version, service, mapping, wsdl_url)) + + class BatchJobHelperTest(unittest.TestCase): """Test suite for BatchJobHelper utility.""" From 18c083ca1c7657dd13c8f67c120ad550d5964dd5 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 11 Oct 2017 18:04:49 -0400 Subject: [PATCH 096/180] Commiting latest changes. From e8c9664b49726fcae354db1e08d0ace8fd529fd0 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 14 Nov 2017 16:43:55 -0500 Subject: [PATCH 097/180] Committing latest changes. --- ChangeLog | 8 + ...oad_criteria_report_as_stream_with_awql.py | 13 +- ...oad_criteria_report_as_string_with_awql.py | 13 +- .../download_criteria_report_with_awql.py | 13 +- .../get_campaigns_with_awql.py | 17 +- .../get_all_disapproved_ads_with_awql.py | 26 +- .../migrate_to_extension_settings.py | 1 - ...oad_criteria_report_as_stream_with_awql.py | 13 +- ...oad_criteria_report_as_string_with_awql.py | 13 +- .../download_criteria_report_with_awql.py | 13 +- .../run_report_and_create_match_table.py | 88 ++ .../run_report_and_create_match_table.py | 88 ++ .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 14 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 18 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 14 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 16 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 14 +- .../populate_first_party_audience_segments.py | 23 +- .../update_audience_segments.py | 23 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 6 +- .../create_product_package_item_base_rates.py | 6 +- .../create_product_template_base_rates.py | 6 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 14 +- .../base_rate_service/update_base_rates.py | 16 +- .../cdn_configuration_service}/__init__.py | 0 .../create_cdn_configurations.py | 89 +++ .../get_all_cdn_configurations.py | 54 ++ .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 14 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 16 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 14 +- .../contact_service/update_contacts.py | 16 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 17 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 17 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 8 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 14 +- .../creative_service/update_creatives.py | 23 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 14 +- .../update_creative_set.py | 15 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 14 +- .../create_creative_wrappers.py | 6 +- .../deactivate_creative_wrapper.py | 22 +- .../get_active_creative_wrappers.py | 14 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 16 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 24 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 14 +- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 15 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 17 +- .../delete_custom_targeting_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- ...efined_custom_targeting_keys_and_values.py | 26 +- .../update_custom_targeting_keys.py | 16 +- .../update_custom_targeting_values.py | 15 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 14 +- .../update_exchange_rates.py | 16 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 15 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 115 +++ .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 58 ++ .../inventory_service/update_ad_units.py | 15 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 15 +- .../label_service/get_active_labels.py | 14 +- .../label_service/get_all_labels.py | 2 +- .../label_service/update_labels.py | 17 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 22 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 14 +- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 22 +- .../line_item_service/create_line_items.py | 20 +- .../create_video_line_item.py | 20 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 14 +- .../get_recently_updated_line_items.py | 20 +- .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 16 +- .../line_item_service/update_line_items.py | 24 +- .../v201711/native_style_service/__init__.py | 15 + .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 2 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 37 + .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 19 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 33 +- .../order_service/update_orders.py | 15 +- .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 14 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 16 +- .../get_active_placements.py | 14 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 40 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 7 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 14 +- .../update_premium_rates.py | 16 +- .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 14 +- .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 14 +- .../get_all_product_packages.py | 2 +- .../product_service/__init__.py | 0 ...matic_products_for_non_sales_management.py | 10 +- .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 16 +- ...sh_programmatic_products_to_marketplace.py | 15 +- .../product_service/update_products.py | 16 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 15 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 14 +- .../update_product_templates.py | 16 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 15 +- ...create_programmatic_proposal_line_items.py | 33 +- ...sal_line_items_for_non_sales_management.py | 33 +- .../create_proposal_line_items.py | 33 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 14 +- .../update_proposal_line_items.py | 15 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 14 +- .../request_buyers_acceptance.py | 17 +- .../submit_proposals_for_approval.py | 17 +- .../proposal_service/update_proposals.py | 16 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 55 ++ .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 53 ++ .../get_line_items_named_like.py | 48 ++ .../get_recent_changes.py | 94 +-- .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 14 +- ..._item_reports_for_reconciliation_report.py | 2 +- ...update_reconciliation_line_item_reports.py | 2 +- ...order_reports_for_reconciliation_report.py | 15 +- .../submit_reconciliation_order_reports.py | 2 +- ...n_report_rows_for_reconciliation_report.py | 18 +- .../update_reconciliation_report_rows.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 14 +- .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 18 +- .../report_service/run_inventory_report.py | 20 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 88 ++ .../run_report_with_custom_fields.py | 26 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 17 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 14 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 2 +- .../team_service/update_teams.py | 15 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 17 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 2 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 14 +- .../user_service/update_users.py | 17 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 23 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 14 +- .../update_user_team_associations.py | 17 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 36 +- .../get_workflow_approval_requests.py | 14 +- ...et_workflow_external_condition_requests.py | 14 +- ...er_workflow_external_condition_requests.py | 36 +- googleads/adwords.py | 749 +++++++++++++++++- googleads/common.py | 40 +- googleads/dfp.py | 121 +-- setup.py | 10 +- tests/__init__.py | 0 tests/adwords_test.py | 507 +++++++++++- tests/common_test.py | 181 +++-- tests/dfp_test.py | 75 +- tests/oauth2_test.py | 74 +- tests/test_data/test.crt | 18 + tests/testing.py | 32 + tests/util_test.py | 40 +- 262 files changed, 3169 insertions(+), 1607 deletions(-) create mode 100755 examples/dfp/v201705/report_service/run_report_and_create_match_table.py create mode 100755 examples/dfp/v201708/report_service/run_report_and_create_match_table.py rename examples/dfp/{v201702 => v201711}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201702 => v201711}/activity_group_service/get_active_activity_groups.py (86%) rename examples/dfp/{v201702 => v201711}/activity_group_service/get_all_activity_groups.py (97%) rename examples/dfp/{v201702 => v201711}/activity_group_service/update_activity_groups.py (87%) rename examples/dfp/{v201702 => v201711}/activity_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/activity_service/create_activities.py (99%) rename examples/dfp/{v201702 => v201711}/activity_service/get_active_activities.py (87%) rename examples/dfp/{v201702 => v201711}/activity_service/get_all_activities.py (99%) rename examples/dfp/{v201702 => v201711}/activity_service/update_activities.py (90%) rename examples/dfp/{v201702 => v201711}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/audience_segment_service/create_audience_segments.py (98%) rename examples/dfp/{v201702 => v201711}/audience_segment_service/get_all_audience_segments.py (97%) rename examples/dfp/{v201702 => v201711}/audience_segment_service/get_first_party_audience_segments.py (86%) rename examples/dfp/{v201702 => v201711}/audience_segment_service/populate_first_party_audience_segments.py (80%) rename examples/dfp/{v201702 => v201711}/audience_segment_service/update_audience_segments.py (81%) rename examples/dfp/{v201702 => v201711}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/base_rate_service/create_product_base_rates.py (89%) rename examples/dfp/{v201702 => v201711}/base_rate_service/create_product_package_item_base_rates.py (94%) rename examples/dfp/{v201702 => v201711}/base_rate_service/create_product_template_base_rates.py (88%) rename examples/dfp/{v201702 => v201711}/base_rate_service/get_all_base_rates.py (99%) rename examples/dfp/{v201702 => v201711}/base_rate_service/get_base_rates_for_rate_card.py (88%) rename examples/dfp/{v201702 => v201711}/base_rate_service/update_base_rates.py (90%) rename examples/dfp/{v201702/native_style_service => v201711/cdn_configuration_service}/__init__.py (100%) create mode 100755 examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py create mode 100755 examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py rename examples/dfp/{v201702 => v201711}/company_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/company_service/create_companies.py (99%) rename examples/dfp/{v201702 => v201711}/company_service/get_advertisers.py (88%) rename examples/dfp/{v201702 => v201711}/company_service/get_all_companies.py (99%) rename examples/dfp/{v201702 => v201711}/company_service/update_companies.py (90%) rename examples/dfp/{v201702 => v201711}/contact_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201702 => v201711}/contact_service/get_all_contacts.py (99%) rename examples/dfp/{v201702 => v201711}/contact_service/get_uninvited_contacts.py (87%) rename examples/dfp/{v201702 => v201711}/contact_service/update_contacts.py (90%) rename examples/dfp/{v201702 => v201711}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201702 => v201711}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (90%) rename examples/dfp/{v201702 => v201711}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201702 => v201711}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (91%) rename examples/dfp/{v201702 => v201711}/content_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/content_service/get_all_content.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/creative_service/copy_image_creatives.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/create_native_creative.py (94%) rename examples/dfp/{v201702 => v201711}/creative_service/get_all_creatives.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/get_image_creatives.py (86%) rename examples/dfp/{v201702 => v201711}/creative_service/update_creatives.py (85%) rename examples/dfp/{v201702 => v201711}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201702 => v201711}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201702 => v201711}/creative_set_service/get_all_creative_sets.py (97%) rename examples/dfp/{v201702 => v201711}/creative_set_service/get_creative_sets_for_master_creative.py (85%) rename examples/dfp/{v201702 => v201711}/creative_set_service/update_creative_set.py (89%) rename examples/dfp/{v201702 => v201711}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/creative_template_service/get_all_creative_templates.py (97%) rename examples/dfp/{v201702 => v201711}/creative_template_service/get_system_defined_creative_templates.py (86%) rename examples/dfp/{v201702 => v201711}/creative_wrapper_service/create_creative_wrappers.py (91%) rename examples/dfp/{v201702 => v201711}/creative_wrapper_service/deactivate_creative_wrapper.py (85%) rename examples/dfp/{v201702 => v201711}/creative_wrapper_service/get_active_creative_wrappers.py (86%) rename examples/dfp/{v201702 => v201711}/creative_wrapper_service/get_all_creative_wrappers.py (97%) rename examples/dfp/{v201702 => v201711}/creative_wrapper_service/update_creative_wrappers.py (88%) rename examples/dfp/{v201702 => v201711}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201702 => v201711}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201702 => v201711}/custom_field_service/deactivate_all_line_item_custom_fields.py (82%) rename examples/dfp/{v201702 => v201711}/custom_field_service/get_all_custom_fields.py (97%) rename examples/dfp/{v201702 => v201711}/custom_field_service/get_custom_fields_for_line_items.py (85%) rename examples/dfp/{v201702 => v201711}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201702 => v201711}/custom_field_service/update_custom_fields.py (88%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/delete_custom_targeting_keys.py (90%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/delete_custom_targeting_values.py (98%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (78%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/update_custom_targeting_keys.py (88%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/update_custom_targeting_values.py (88%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/get_all_exchange_rates.py (97%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/get_exchange_rates_for_currency_code.py (86%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/update_exchange_rates.py (87%) rename examples/dfp/{v201702 => v201711}/forecast_service/get_availability_forecast.py (99%) rename examples/dfp/{v201702 => v201711}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/dfp/{v201702 => v201711}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/dfp/{v201702 => v201711}/inventory_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/inventory_service/archive_ad_units.py (90%) rename examples/dfp/{v201702 => v201711}/inventory_service/create_ad_units.py (99%) create mode 100755 examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py rename examples/dfp/{v201702 => v201711}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/dfp/{v201702 => v201711}/inventory_service/get_all_ad_units.py (99%) create mode 100755 examples/dfp/v201711/inventory_service/get_top_level_ad_units.py rename examples/dfp/{v201702 => v201711}/inventory_service/update_ad_units.py (92%) rename examples/dfp/{v201702 => v201711}/label_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/label_service/create_labels.py (99%) rename examples/dfp/{v201702 => v201711}/label_service/deactivate_labels.py (89%) rename examples/dfp/{v201702 => v201711}/label_service/get_active_labels.py (87%) rename examples/dfp/{v201702 => v201711}/label_service/get_all_labels.py (99%) rename examples/dfp/{v201702 => v201711}/label_service/update_labels.py (87%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/deactivate_licas.py (83%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/get_all_licas.py (97%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/get_licas_for_line_item.py (87%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201702 => v201711}/line_item_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/line_item_service/activate_line_items.py (86%) rename examples/dfp/{v201702 => v201711}/line_item_service/create_line_items.py (93%) rename examples/dfp/{v201702 => v201711}/line_item_service/create_video_line_item.py (92%) rename examples/dfp/{v201702 => v201711}/line_item_service/get_all_line_items.py (99%) rename examples/dfp/{v201702 => v201711}/line_item_service/get_line_items_that_need_creatives.py (86%) rename examples/dfp/{v201702 => v201711}/line_item_service/get_recently_updated_line_items.py (82%) rename examples/dfp/{v201702 => v201711}/line_item_service/pause_line_items.py (99%) rename examples/dfp/{v201702 => v201711}/line_item_service/target_custom_criteria.py (93%) rename examples/dfp/{v201702 => v201711}/line_item_service/update_line_items.py (84%) create mode 100755 examples/dfp/v201711/native_style_service/__init__.py rename examples/dfp/{v201702 => v201711}/native_style_service/create_native_styles.py (98%) rename examples/dfp/{v201702 => v201711}/native_style_service/get_all_native_styles.py (96%) rename examples/dfp/{v201702 => v201711}/network_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/network_service/get_all_networks.py (99%) create mode 100755 examples/dfp/v201711/network_service/get_current_network.py rename examples/dfp/{v201702 => v201711}/network_service/make_test_network.py (99%) rename examples/dfp/{v201702 => v201711}/order_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/order_service/approve_orders.py (84%) rename examples/dfp/{v201702 => v201711}/order_service/create_orders.py (99%) rename examples/dfp/{v201702 => v201711}/order_service/get_all_orders.py (99%) rename examples/dfp/{v201702 => v201711}/order_service/get_orders_starting_soon.py (73%) rename examples/dfp/{v201702 => v201711}/order_service/update_orders.py (90%) rename examples/dfp/{v201702 => v201711}/package_service/create_packages.py (99%) rename examples/dfp/{v201702 => v201711}/package_service/create_proposal_line_items_from_packages.py (99%) rename examples/dfp/{v201702 => v201711}/package_service/get_all_packages.py (99%) rename examples/dfp/{v201702 => v201711}/package_service/get_in_progress_packages.py (87%) rename examples/dfp/{v201702 => v201711}/placement_service/create_placements.py (99%) rename examples/dfp/{v201702 => v201711}/placement_service/deactivate_placements.py (88%) rename examples/dfp/{v201702 => v201711}/placement_service/get_active_placements.py (87%) rename examples/dfp/{v201702 => v201711}/placement_service/get_all_placements.py (99%) rename examples/dfp/{v201702 => v201711}/placement_service/update_placements.py (57%) rename examples/dfp/{v201702 => v201711}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/premium_rate_service/create_premium_rates.py (90%) rename examples/dfp/{v201702 => v201711}/premium_rate_service/get_all_premium_rates.py (97%) rename examples/dfp/{v201702 => v201711}/premium_rate_service/get_premium_rates_for_rate_card.py (87%) rename examples/dfp/{v201702 => v201711}/premium_rate_service/update_premium_rates.py (90%) rename examples/dfp/{v201702 => v201711}/product_package_item_service/create_product_package_item.py (99%) rename examples/dfp/{v201702 => v201711}/product_package_item_service/get_all_product_package_items.py (97%) rename examples/dfp/{v201702 => v201711}/product_package_item_service/get_product_package_items_for_product_package.py (86%) rename examples/dfp/{v201702 => v201711}/product_package_service/create_product_packages.py (96%) rename examples/dfp/{v201702 => v201711}/product_package_service/get_active_product_packages.py (86%) rename examples/dfp/{v201702 => v201711}/product_package_service/get_all_product_packages.py (97%) rename examples/dfp/{v201702 => v201711}/product_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/product_service/create_programmatic_products_for_non_sales_management.py (94%) rename examples/dfp/{v201702 => v201711}/product_service/get_all_products.py (99%) rename examples/dfp/{v201702 => v201711}/product_service/get_products_for_product_template.py (86%) rename examples/dfp/{v201702 => v201711}/product_service/publish_programmatic_products_to_marketplace.py (90%) rename examples/dfp/{v201702 => v201711}/product_service/update_products.py (90%) rename examples/dfp/{v201702 => v201711}/product_template_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/product_template_service/activate_product_templates.py (89%) rename examples/dfp/{v201702 => v201711}/product_template_service/create_product_templates.py (97%) rename examples/dfp/{v201702 => v201711}/product_template_service/create_programmatic_product_templates.py (96%) rename examples/dfp/{v201702 => v201711}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201702 => v201711}/product_template_service/get_sponsorship_product_templates.py (85%) rename examples/dfp/{v201702 => v201711}/product_template_service/update_product_templates.py (90%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/archive_proposal_line_items.py (89%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/create_programmatic_proposal_line_items.py (82%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (82%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/create_proposal_line_items.py (82%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/get_all_proposal_line_items.py (97%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (86%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/update_proposal_line_items.py (89%) rename examples/dfp/{v201702 => v201711}/proposal_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/proposal_service/create_programmatic_proposals.py (98%) rename examples/dfp/{v201702 => v201711}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (99%) rename examples/dfp/{v201702 => v201711}/proposal_service/create_proposals.py (99%) rename examples/dfp/{v201702 => v201711}/proposal_service/get_all_proposals.py (99%) rename examples/dfp/{v201702 => v201711}/proposal_service/get_marketplace_comments.py (97%) rename examples/dfp/{v201702 => v201711}/proposal_service/get_proposals_pending_approval.py (87%) rename examples/dfp/{v201702 => v201711}/proposal_service/request_buyers_acceptance.py (89%) rename examples/dfp/{v201702 => v201711}/proposal_service/submit_proposals_for_approval.py (88%) rename examples/dfp/{v201702 => v201711}/proposal_service/update_proposals.py (89%) rename examples/dfp/{v201702 => v201711}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/publisher_query_language_service/fetch_match_tables.py (96%) create mode 100755 examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py rename examples/dfp/{v201702 => v201711}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) create mode 100755 examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py create mode 100755 examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py rename examples/dfp/{v201702 => v201711}/publisher_query_language_service/get_recent_changes.py (66%) rename examples/dfp/{v201702 => v201711}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/rate_card_service/create_rate_cards.py (99%) rename examples/dfp/{v201702 => v201711}/rate_card_service/get_all_rate_cards.py (99%) rename examples/dfp/{v201702 => v201711}/rate_card_service/get_marketplace_rate_cards.py (87%) rename examples/dfp/{v201702 => v201711}/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (97%) rename examples/dfp/{v201702 => v201711}/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (97%) rename examples/dfp/{v201702 => v201711}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (85%) rename examples/dfp/{v201702 => v201711}/reconciliation_order_report_service/submit_reconciliation_order_reports.py (97%) rename examples/dfp/{v201702 => v201711}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (85%) rename examples/dfp/{v201702 => v201711}/reconciliation_report_row_service/update_reconciliation_report_rows.py (97%) rename examples/dfp/{v201702 => v201711}/reconciliation_report_service/get_all_reconciliation_reports.py (97%) rename examples/dfp/{v201702 => v201711}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (86%) rename examples/dfp/{v201702 => v201711}/report_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/report_service/run_delivery_report.py (88%) rename examples/dfp/{v201702 => v201711}/report_service/run_inventory_report.py (86%) rename examples/dfp/{v201702 => v201711}/report_service/run_reach_report.py (96%) create mode 100755 examples/dfp/v201711/report_service/run_report_and_create_match_table.py rename examples/dfp/{v201702 => v201711}/report_service/run_report_with_custom_fields.py (85%) rename examples/dfp/{v201702 => v201711}/report_service/run_sales_report.py (96%) rename examples/dfp/{v201702 => v201711}/report_service/run_saved_query.py (89%) rename examples/dfp/{v201702 => v201711}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (97%) rename examples/dfp/{v201702 => v201711}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) rename examples/dfp/{v201702 => v201711}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (86%) rename examples/dfp/{v201702 => v201711}/team_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/team_service/create_teams.py (99%) rename examples/dfp/{v201702 => v201711}/team_service/get_all_teams.py (99%) rename examples/dfp/{v201702 => v201711}/team_service/update_teams.py (90%) rename examples/dfp/{v201702 => v201711}/user_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/user_service/create_users.py (99%) rename examples/dfp/{v201702 => v201711}/user_service/deactivate_users.py (89%) rename examples/dfp/{v201702 => v201711}/user_service/get_all_roles.py (100%) rename examples/dfp/{v201702 => v201711}/user_service/get_all_users.py (99%) rename examples/dfp/{v201702 => v201711}/user_service/get_current_user.py (99%) rename examples/dfp/{v201702 => v201711}/user_service/get_user_by_email_address.py (88%) rename examples/dfp/{v201702 => v201711}/user_service/update_users.py (86%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/delete_user_team_associations.py (87%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/get_all_user_team_associations.py (97%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/get_user_team_associations_for_user.py (87%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/update_user_team_associations.py (89%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/approve_workflow_approval_requests.py (76%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/get_workflow_approval_requests.py (87%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/get_workflow_external_condition_requests.py (86%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/trigger_workflow_external_condition_requests.py (78%) create mode 100644 tests/__init__.py create mode 100644 tests/test_data/test.crt create mode 100644 tests/testing.py diff --git a/ChangeLog b/ChangeLog index 5349db0d..4f962b18 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,11 @@ +9.0.0 -- 11/14/17 +* Added support and examples for DFP v201711 +* Removed support and examples for DFP v201611 +* DFP PQL queries can now accept simple python dicts for variable substitution. +* Resolved issues: +- Issue 230: https://github.com/googleads/googleads-python-lib/issues/230 + + 8.1.0 -- 10/11/17 * Added support for AdWords v201710. * Resolved issues: diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py index e59ef1f4..aab506db 100755 --- a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py @@ -47,11 +47,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201708') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py index 0eb63ede..820add34 100755 --- a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py @@ -37,11 +37,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201708') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py index a2ae571c..6913de8a 100755 --- a/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py @@ -34,11 +34,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201708') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) # You can provide a file object to write the output to. For this # demonstration we use sys.stdout to write the report to the screen. diff --git a/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py index 5e15cf7c..72078fc0 100755 --- a/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py @@ -38,13 +38,14 @@ def main(client): campaign_service = client.GetService('CampaignService', version='v201710') # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'Name', 'Status') + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, PAGE_SIZE) + .Build()) + + for page in query.Pager(campaign_service): # Display results. if 'entries' in page: for campaign in page['entries']: @@ -53,8 +54,6 @@ def main(client): campaign['status'])) else: print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) time.sleep(1) diff --git a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py index 2f621a9b..c8d69dd6 100755 --- a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py @@ -38,17 +38,18 @@ def main(client, ad_group_id): version='v201710') # Construct query and get all ads for a given campaign. - query = ('SELECT Id, PolicySummary ' - 'WHERE AdGroupId = %s AND CombinedApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % ad_group_id) - more_pages = True + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'PolicySummary') + .Where('AdGroupId').EqualTo(ad_group_id) + .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') + .OrderBy('Id') + .Limit(0, PAGE_SIZE) + .Build()) disapproved_count = 0 - offset = 0 # Display results. - while more_pages: - page = ad_group_ad_service.query(query + ' LIMIT %s, %s' % ( - offset, PAGE_SIZE)) + while True: + page = ad_group_ad_service.query(query) if 'entries' in page: for ad in page['entries']: @@ -63,8 +64,8 @@ def main(client, ad_group_id): policy_topic_entry['policyTopicId'], policy_topic_entry['policyTopicName']) # Display the attributes and values that triggered the policy topic. - policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] - if policy_topic_evidences: + if ('policyTopicEvidences' in policy_topic_entry + and policy_topic_entry['policyTopicEvidences']): for evidence in policy_topic_entry['policyTopicEvidences']: print (' evidence type: %s' % evidence['policyTopicEvidenceType']) @@ -73,8 +74,9 @@ def main(client, ad_group_id): for index, evidence_text in enumerate(evidence_text_list): print ' evidence text[%d]: %s' % (index, evidence_text) - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) + if not query.HasNext(page): + break + query.NextPage() print '%d disapproved ads were found.' % disapproved_count diff --git a/examples/adwords/v201710/migration/migrate_to_extension_settings.py b/examples/adwords/v201710/migration/migrate_to_extension_settings.py index aaf75c22..8302525d 100755 --- a/examples/adwords/v201710/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201710/migration/migrate_to_extension_settings.py @@ -52,7 +52,6 @@ 'TRACKING_URL_TEMPLATE': 7 } - PAGE_SIZE = 500 diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py index 7c984bb2..6bd15e45 100755 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py @@ -47,11 +47,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201710') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py index 6586e7f7..fcf87588 100755 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py @@ -37,11 +37,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201710') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py index 6d92fb42..38bf210c 100755 --- a/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py @@ -34,11 +34,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201710') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) # You can provide a file object to write the output to. For this # demonstration we use sys.stdout to write the report to the screen. diff --git a/examples/dfp/v201705/report_service/run_report_and_create_match_table.py b/examples/dfp/v201705/report_service/run_report_and_create_match_table.py new file mode 100755 index 00000000..498cb9b0 --- /dev/null +++ b/examples/dfp/v201705/report_service/run_report_and_create_match_table.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Runs a report for LineItems with additional data from a PQL table. + +Fetches a basic report over a network's LineItems and then adds some +extra columns which might be useful for future analysis, such as +LineItemType, from the PQL Line_Item table, creating a match table. +""" + +from datetime import date +from datetime import timedelta +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + +try: + import pandas +except ImportError: + raise ImportError('This example requires the pandas library to be installed.') + + +def main(client): + # Set the start and end dates of the report to run (past 8 days). + end_date = date.today() + start_date = end_date - timedelta(days=8) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': start_date, + 'endDate': end_date + } + } + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201705') + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + with tempfile.NamedTemporaryFile( + suffix='.csv.gz', mode='wb', delete=False) as report_file: + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, 'CSV_DUMP', report_file) + + # Create a PQL query to fetch the line item data + line_items_pql_query = ('SELECT Id, LineItemType, Status FROM Line_Item') + + # Download the response from PQL select statement + line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) + + # Use pandas to join the two csv files into a match table + report = pandas.read_csv(report_file.name) + line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0]) + merged_result = pandas.merge(report, line_items, + left_on='Dimension.LINE_ITEM_ID', right_on='id') + merged_result.to_csv('~/complete_line_items_report.csv', index=False) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/report_service/run_report_and_create_match_table.py b/examples/dfp/v201708/report_service/run_report_and_create_match_table.py new file mode 100755 index 00000000..572d2c3c --- /dev/null +++ b/examples/dfp/v201708/report_service/run_report_and_create_match_table.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Runs a report for LineItems with additional data from a PQL table. + +Fetches a basic report over a network's LineItems and then adds some +extra columns which might be useful for future analysis, such as +LineItemType, from the PQL Line_Item table, creating a match table. +""" + +from datetime import date +from datetime import timedelta +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + +try: + import pandas +except ImportError: + raise ImportError('This example requires the pandas library to be installed.') + + +def main(client): + # Set the start and end dates of the report to run (past 8 days). + end_date = date.today() + start_date = end_date - timedelta(days=8) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': start_date, + 'endDate': end_date + } + } + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201708') + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + with tempfile.NamedTemporaryFile( + suffix='.csv.gz', mode='wb', delete=False) as report_file: + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, 'CSV_DUMP', report_file) + + # Create a PQL query to fetch the line item data + line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem') + + # Download the response from PQL select statement + line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) + + # Use pandas to join the two csv files into a match table + report = pandas.read_csv(report_file.name) + line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0]) + merged_result = pandas.merge(report, line_items, + left_on='Dimension.LINE_ITEM_ID', right_on='id') + merged_result.to_csv('~/complete_line_items_report.csv', index=False) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/activity_group_service/__init__.py b/examples/dfp/v201711/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201702/activity_group_service/__init__.py rename to examples/dfp/v201711/activity_group_service/__init__.py diff --git a/examples/dfp/v201702/activity_group_service/create_activity_groups.py b/examples/dfp/v201711/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201702/activity_group_service/create_activity_groups.py rename to examples/dfp/v201711/activity_group_service/create_activity_groups.py index 9f5ec668..cba5979e 100755 --- a/examples/dfp/v201702/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201702') + version='v201711') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py similarity index 86% rename from examples/dfp/v201702/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201711/activity_group_service/get_active_activity_groups.py index a5059f06..7b074ea4 100755 --- a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'ActivityGroupService', version='v201711') # Create a statement to select activity groups. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py similarity index 97% rename from examples/dfp/v201702/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201711/activity_group_service/get_all_activity_groups.py index d49855a1..7d51a7a9 100755 --- a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201702') + 'ActivityGroupService', version='v201711') # Create a statement to select activity groups. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/activity_group_service/update_activity_groups.py b/examples/dfp/v201711/activity_group_service/update_activity_groups.py similarity index 87% rename from examples/dfp/v201702/activity_group_service/update_activity_groups.py rename to examples/dfp/v201711/activity_group_service/update_activity_groups.py index d3724557..5cd9e5d8 100755 --- a/examples/dfp/v201702/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/update_activity_groups.py @@ -37,20 +37,13 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201702') + version='v201711') # Create statement object to select a single activity groups by ID. - values = [{ - 'key': 'activityGroupId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_group_id - } - }] - query = 'WHERE id = :activityGroupId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityGroupId') + .WithBindVariable('activityGroupId', long(activity_group_id)) + .Limit(1)) # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( @@ -70,6 +63,7 @@ def main(client, activity_group_id, advertiser_company_id): else: print 'No activity groups found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/activity_service/__init__.py b/examples/dfp/v201711/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201702/activity_service/__init__.py rename to examples/dfp/v201711/activity_service/__init__.py diff --git a/examples/dfp/v201702/activity_service/create_activities.py b/examples/dfp/v201711/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201702/activity_service/create_activities.py rename to examples/dfp/v201711/activity_service/create_activities.py index 62bc032f..3926d5c0 100755 --- a/examples/dfp/v201702/activity_service/create_activities.py +++ b/examples/dfp/v201711/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201702') + activity_service = client.GetService('ActivityService', version='v201711') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201702/activity_service/get_active_activities.py b/examples/dfp/v201711/activity_service/get_active_activities.py similarity index 87% rename from examples/dfp/v201702/activity_service/get_active_activities.py rename to examples/dfp/v201711/activity_service/get_active_activities.py index 6f3e5f14..e255d8b0 100755 --- a/examples/dfp/v201702/activity_service/get_active_activities.py +++ b/examples/dfp/v201711/activity_service/get_active_activities.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + activity_service = client.GetService('ActivityService', version='v201711') # Create a statement to select activities. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/dfp/v201702/activity_service/get_all_activities.py b/examples/dfp/v201711/activity_service/get_all_activities.py similarity index 99% rename from examples/dfp/v201702/activity_service/get_all_activities.py rename to examples/dfp/v201711/activity_service/get_all_activities.py index 32b6c58e..304c1d3c 100755 --- a/examples/dfp/v201702/activity_service/get_all_activities.py +++ b/examples/dfp/v201711/activity_service/get_all_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201702') + activity_service = client.GetService('ActivityService', version='v201711') # Create a statement to select activities. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/activity_service/update_activities.py b/examples/dfp/v201711/activity_service/update_activities.py similarity index 90% rename from examples/dfp/v201702/activity_service/update_activities.py rename to examples/dfp/v201711/activity_service/update_activities.py index 86865679..a1d20c13 100755 --- a/examples/dfp/v201702/activity_service/update_activities.py +++ b/examples/dfp/v201711/activity_service/update_activities.py @@ -35,18 +35,13 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201702') + activity_service = client.GetService('ActivityService', version='v201711') # Create statement object to select one activity by ID to update. - values = [{ - 'key': 'activityId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_id - } - }] - query = 'WHERE id = :activityId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityId') + .WithBindVariable('activityId', long(activity_id)) + .Limit(1)) # Get activities by statement. response = activity_service.getActivitiesByStatement( @@ -66,6 +61,7 @@ def main(client, activity_id): else: print 'No activities found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/audience_segment_service/__init__.py b/examples/dfp/v201711/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201702/audience_segment_service/__init__.py rename to examples/dfp/v201711/audience_segment_service/__init__.py diff --git a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py b/examples/dfp/v201711/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/dfp/v201702/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/create_audience_segments.py index f0db7a52..16b08496 100755 --- a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + 'AudienceSegmentService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py similarity index 97% rename from examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py index ab4ab4ca..1990fdd6 100755 --- a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') + 'AudienceSegmentService', version='v201711') # Create a statement to select audience segments. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py similarity index 86% rename from examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py index 65dbc7be..7a96417b 100755 --- a/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - }}, - ] + 'AudienceSegmentService', version='v201711') # Create a statement to select audience segments. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'FIRST_PARTY')) # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py similarity index 80% rename from examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py index 371c6923..082df910 100755 --- a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py @@ -30,24 +30,15 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') + 'AudienceSegmentService', version='v201711') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py b/examples/dfp/v201711/audience_segment_service/update_audience_segments.py similarity index 81% rename from examples/dfp/v201702/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/update_audience_segments.py index 2c708dea..3ede3c29 100755 --- a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/update_audience_segments.py @@ -29,24 +29,15 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') + 'AudienceSegmentService', version='v201711') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) # Get audience segments by statement. response = audience_segment_service.getAudienceSegmentsByStatement( diff --git a/examples/dfp/v201702/base_rate_service/__init__.py b/examples/dfp/v201711/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201702/base_rate_service/__init__.py rename to examples/dfp/v201711/base_rate_service/__init__.py diff --git a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py b/examples/dfp/v201711/base_rate_service/create_product_base_rates.py similarity index 89% rename from examples/dfp/v201702/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201711/base_rate_service/create_product_base_rates.py index 26003719..cc083cd8 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/create_product_base_rates.py @@ -31,12 +31,14 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201702') + 'BaseRateService', version='v201711') # Create a product base rate. product_base_rate = { 'xsi_type': 'ProductBaseRate', + # Set the rate card ID that the product base rate belongs to. 'rateCardId': rate_card_id, + # Set the product id the base rate will be applied to. 'productId': product_id, # Set the rate to be $2. 'rate': { @@ -45,7 +47,7 @@ def main(client, product_id, rate_card_id): } } - # Create base rates on the server. + # Create the product base rate on the server. base_rates = base_rate_service.createBaseRates( [product_base_rate]) diff --git a/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py similarity index 94% rename from examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py rename to examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py index 63ffec25..2a6ea9ac 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py @@ -31,10 +31,10 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201702') + base_rate_service = client.GetService('BaseRateService', version='v201711') # Create a base rate for a product package item. - base_rate = { + product_package_item_base_rate = { 'xsi_type': 'ProductPackageItemBaseRate', # Set the rate card ID that the product package item base rate # belongs to. @@ -51,7 +51,7 @@ def main(client): } # Create the product package item base rate on the server. - result = base_rate_service.createBaseRates([base_rate]) + result = base_rate_service.createBaseRates([product_package_item_base_rate]) for new_base_rate in result: print ('A product package item base rate with ID %d and rate %f %s ' diff --git a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py similarity index 88% rename from examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py index d024f6e8..2f46ab9a 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py @@ -31,12 +31,14 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201702') + 'BaseRateService', version='v201711') # Create a product template base rate. product_template_base_rate = { 'xsi_type': 'ProductTemplateBaseRate', + # Set the rate card ID that the product template base rate belongs to. 'rateCardId': rate_card_id, + # Set the product template the base rate will be applied to. 'productTemplateId': product_template_id, # Set the rate to be $2. 'rate': { @@ -45,7 +47,7 @@ def main(client, product_template_id, rate_card_id): } } - # Create base rates on the server. + # Create the product template item base rate on the server. base_rates = base_rate_service.createBaseRates( [product_template_base_rate]) diff --git a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py b/examples/dfp/v201711/base_rate_service/get_all_base_rates.py similarity index 99% rename from examples/dfp/v201702/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201711/base_rate_service/get_all_base_rates.py index 44b6c365..324d1e17 100755 --- a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/get_all_base_rates.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201702') + base_rate_service = client.GetService('BaseRateService', version='v201711') # Create a statement to select base rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py similarity index 88% rename from examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py rename to examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py index d72c1f61..b4d547b0 100755 --- a/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py @@ -24,17 +24,11 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201702') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] + base_rate_service = client.GetService('BaseRateService', version='v201711') # Create a statement to select base rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/dfp/v201702/base_rate_service/update_base_rates.py b/examples/dfp/v201711/base_rate_service/update_base_rates.py similarity index 90% rename from examples/dfp/v201702/base_rate_service/update_base_rates.py rename to examples/dfp/v201711/base_rate_service/update_base_rates.py index a1b1d7fe..936444d2 100755 --- a/examples/dfp/v201702/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/update_base_rates.py @@ -29,18 +29,14 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201702') + base_rate_service = client.GetService('BaseRateService', version='v201711') # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': base_rate_id - } - }] - query = 'where id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', long(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( diff --git a/examples/dfp/v201702/native_style_service/__init__.py b/examples/dfp/v201711/cdn_configuration_service/__init__.py similarity index 100% rename from examples/dfp/v201702/native_style_service/__init__.py rename to examples/dfp/v201711/cdn_configuration_service/__init__.py diff --git a/examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py b/examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py new file mode 100755 index 00000000..f646f7fc --- /dev/null +++ b/examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 code example creates new cdn configurations. + +To determine which configurations exist, run get_all_cdn_configurations.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201711') + + # Create cdn config objects. + # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. + configs = [{ + # Basic example with no security policies. + 'name': 'ApiConfig1', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + } + } + }, { + # Complex example with security policies. + 'name': 'ApiConfig2', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': False, + 'tokenAuthenticationKey': 'abc123', + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': True, + 'originForwardingType': 'CONVENTIONAL', + 'originPathPrefix': '/path/to/my/origin' + } + } + } + }] + + # Add configs. + configs = cdn_config_service.createCdnConfigurations(configs) + + # Display results. + for config in configs: + print('Created CDN configuration with type "%s" and name "%s".' + % (config['cdnConfigurationType'], config['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py b/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py new file mode 100755 index 00000000..3815c731 --- /dev/null +++ b/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 CDN configuration objects. + +Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be +returned. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201711') + + # Create a statement to select cdn configurations. + statement = dfp.StatementBuilder() + + # Retrieve a small number of configs at a time, paging + # through until all have been retrieved. + while True: + response = (cdn_config_service + .getCdnConfigurationsByStatement(statement.ToStatement())) + if 'results' in response: + for cdn in response['results']: + # Print out some information for each company. + print('Found CDN configuration with type "%s" and name "%s".' + % (cdn['cdnConfigurationType'], cdn['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/company_service/__init__.py b/examples/dfp/v201711/company_service/__init__.py similarity index 100% rename from examples/dfp/v201702/company_service/__init__.py rename to examples/dfp/v201711/company_service/__init__.py diff --git a/examples/dfp/v201702/company_service/create_companies.py b/examples/dfp/v201711/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201702/company_service/create_companies.py rename to examples/dfp/v201711/company_service/create_companies.py index 8b41d9ac..035983be 100755 --- a/examples/dfp/v201702/company_service/create_companies.py +++ b/examples/dfp/v201711/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201702') + company_service = client.GetService('CompanyService', version='v201711') # Create company objects. companies = [ diff --git a/examples/dfp/v201702/company_service/get_advertisers.py b/examples/dfp/v201711/company_service/get_advertisers.py similarity index 88% rename from examples/dfp/v201702/company_service/get_advertisers.py rename to examples/dfp/v201711/company_service/get_advertisers.py index 7e8085ac..5f44d794 100755 --- a/examples/dfp/v201702/company_service/get_advertisers.py +++ b/examples/dfp/v201711/company_service/get_advertisers.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - }}, - ] + company_service = client.GetService('CompanyService', version='v201711') # Create a statement to select companies. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'ADVERTISER')) # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/dfp/v201702/company_service/get_all_companies.py b/examples/dfp/v201711/company_service/get_all_companies.py similarity index 99% rename from examples/dfp/v201702/company_service/get_all_companies.py rename to examples/dfp/v201711/company_service/get_all_companies.py index 6693f930..afbb57e9 100755 --- a/examples/dfp/v201702/company_service/get_all_companies.py +++ b/examples/dfp/v201711/company_service/get_all_companies.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201702') + company_service = client.GetService('CompanyService', version='v201711') # Create a statement to select companies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/company_service/update_companies.py b/examples/dfp/v201711/company_service/update_companies.py similarity index 90% rename from examples/dfp/v201702/company_service/update_companies.py rename to examples/dfp/v201711/company_service/update_companies.py index e1ade3e6..7142dddb 100755 --- a/examples/dfp/v201702/company_service/update_companies.py +++ b/examples/dfp/v201711/company_service/update_companies.py @@ -35,18 +35,13 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201702') + company_service = client.GetService('CompanyService', version='v201711') # Create statement object to only select a single company by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': company_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(company_id)) + .Limit(1)) # Get companies by statement. response = company_service.getCompaniesByStatement( @@ -68,6 +63,7 @@ def main(client, company_id): else: print 'No companies found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/contact_service/__init__.py b/examples/dfp/v201711/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201702/contact_service/__init__.py rename to examples/dfp/v201711/contact_service/__init__.py diff --git a/examples/dfp/v201702/contact_service/create_contacts.py b/examples/dfp/v201711/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201702/contact_service/create_contacts.py rename to examples/dfp/v201711/contact_service/create_contacts.py index 51bd81af..89872c6a 100755 --- a/examples/dfp/v201702/contact_service/create_contacts.py +++ b/examples/dfp/v201711/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201702') + contact_service = client.GetService('ContactService', version='v201711') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201702/contact_service/get_all_contacts.py b/examples/dfp/v201711/contact_service/get_all_contacts.py similarity index 99% rename from examples/dfp/v201702/contact_service/get_all_contacts.py rename to examples/dfp/v201711/contact_service/get_all_contacts.py index 7fbd79d8..0c824ad3 100755 --- a/examples/dfp/v201702/contact_service/get_all_contacts.py +++ b/examples/dfp/v201711/contact_service/get_all_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201702') + contact_service = client.GetService('ContactService', version='v201711') # Create a statement to select contacts. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/contact_service/get_uninvited_contacts.py b/examples/dfp/v201711/contact_service/get_uninvited_contacts.py similarity index 87% rename from examples/dfp/v201702/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201711/contact_service/get_uninvited_contacts.py index def756c1..65b0e339 100755 --- a/examples/dfp/v201702/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201711/contact_service/get_uninvited_contacts.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - }}, - ] + contact_service = client.GetService('ContactService', version='v201711') # Create a statement to select contacts. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'UNINVITED')) # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/dfp/v201702/contact_service/update_contacts.py b/examples/dfp/v201711/contact_service/update_contacts.py similarity index 90% rename from examples/dfp/v201702/contact_service/update_contacts.py rename to examples/dfp/v201711/contact_service/update_contacts.py index d035fc12..dbab02df 100755 --- a/examples/dfp/v201702/contact_service/update_contacts.py +++ b/examples/dfp/v201711/contact_service/update_contacts.py @@ -35,18 +35,13 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201702') + contact_service = client.GetService('ContactService', version='v201711') # Create statement object to select the single contact by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': contact_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(contact_id)) + .Limit(1)) # Get contacts by statement. response = contact_service.getContactsByStatement( @@ -69,6 +64,7 @@ def main(client, contact_id): else: print 'No contacts found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 2378c8ca..672b1efe 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201702') + 'ContentMetadataKeyHierarchyService', version='v201711') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 90% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index b5400763..30327029 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,19 +40,15 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201702') + 'ContentMetadataKeyHierarchyService', version='v201711') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -78,6 +74,7 @@ def main(client, content_metadata_key_hierarchy_id): print ('Number of content metadata key hierarchies deleted: %s' % result['numChanges']) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index fe1d9afb..66c97f64 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201702') + 'ContentMetadataKeyHierarchyService', version='v201711') # Create a statement to select content metadata key hierarchies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index b1f5c6bb..81672538 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,19 +42,15 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201702') + 'ContentMetadataKeyHierarchyService', version='v201711') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -90,6 +86,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): else: print 'No content metadata key hierarchies were found' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/content_service/__init__.py b/examples/dfp/v201711/content_service/__init__.py similarity index 100% rename from examples/dfp/v201702/content_service/__init__.py rename to examples/dfp/v201711/content_service/__init__.py diff --git a/examples/dfp/v201702/content_service/get_all_content.py b/examples/dfp/v201711/content_service/get_all_content.py similarity index 99% rename from examples/dfp/v201702/content_service/get_all_content.py rename to examples/dfp/v201711/content_service/get_all_content.py index 5649d6ae..cf7e3661 100755 --- a/examples/dfp/v201702/content_service/get_all_content.py +++ b/examples/dfp/v201711/content_service/get_all_content.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201702') + content_service = client.GetService('ContentService', version='v201711') # Create a statement to select content. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_service/__init__.py b/examples/dfp/v201711/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201702/creative_service/__init__.py rename to examples/dfp/v201711/creative_service/__init__.py diff --git a/examples/dfp/v201702/creative_service/copy_image_creatives.py b/examples/dfp/v201711/creative_service/copy_image_creatives.py similarity index 99% rename from examples/dfp/v201702/creative_service/copy_image_creatives.py rename to examples/dfp/v201711/creative_service/copy_image_creatives.py index 7578afdf..6554acb1 100755 --- a/examples/dfp/v201702/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201711/creative_service/copy_image_creatives.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Create a statement to get the image creative. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_service/create_creative_from_template.py b/examples/dfp/v201711/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201702/creative_service/create_creative_from_template.py rename to examples/dfp/v201711/creative_service/create_creative_from_template.py index 13b28235..64bd5e63 100755 --- a/examples/dfp/v201702/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201711/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201702/creative_service/create_creatives.py b/examples/dfp/v201711/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201702/creative_service/create_creatives.py rename to examples/dfp/v201711/creative_service/create_creatives.py index fc3a886d..c315d9ea 100755 --- a/examples/dfp/v201702/creative_service/create_creatives.py +++ b/examples/dfp/v201711/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201702/creative_service/create_custom_creative.py b/examples/dfp/v201711/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201702/creative_service/create_custom_creative.py rename to examples/dfp/v201711/creative_service/create_custom_creative.py index 54de0f4b..99ef3a2d 100755 --- a/examples/dfp/v201702/creative_service/create_custom_creative.py +++ b/examples/dfp/v201711/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201702/creative_service/create_native_creative.py b/examples/dfp/v201711/creative_service/create_native_creative.py similarity index 94% rename from examples/dfp/v201702/creative_service/create_native_creative.py rename to examples/dfp/v201711/creative_service/create_native_creative.py index 075f7841..d28f8cdc 100755 --- a/examples/dfp/v201702/creative_service/create_native_creative.py +++ b/examples/dfp/v201711/creative_service/create_native_creative.py @@ -46,18 +46,16 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Use the system defined native app install creative template. creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = base64.b64encode(image_data).decode('utf-8') + image_data = base64.b64encode(image_data) app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - app_icon_data = base64.b64encode(app_icon_data).decode('utf-8') + app_icon_data = base64.b64encode(app_icon_data) # Create creative from templates. creative = { diff --git a/examples/dfp/v201702/creative_service/get_all_creatives.py b/examples/dfp/v201711/creative_service/get_all_creatives.py similarity index 99% rename from examples/dfp/v201702/creative_service/get_all_creatives.py rename to examples/dfp/v201711/creative_service/get_all_creatives.py index e96715de..a326edc7 100755 --- a/examples/dfp/v201702/creative_service/get_all_creatives.py +++ b/examples/dfp/v201711/creative_service/get_all_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Create a statement to select creatives. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_service/get_image_creatives.py b/examples/dfp/v201711/creative_service/get_image_creatives.py similarity index 86% rename from examples/dfp/v201702/creative_service/get_image_creatives.py rename to examples/dfp/v201711/creative_service/get_image_creatives.py index e63a52d4..1b9daa8c 100755 --- a/examples/dfp/v201702/creative_service/get_image_creatives.py +++ b/examples/dfp/v201711/creative_service/get_image_creatives.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') - query = 'WHERE creativeType = :creativeType' - values = [ - {'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': '_image_creative' - }}, - ] + creative_service = client.GetService('CreativeService', version='v201711') # Create a statement to select creatives. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('creativeType = :creativeType') + .WithBindVariable('creativeType', '_image_creative')) # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/dfp/v201702/creative_service/update_creatives.py b/examples/dfp/v201711/creative_service/update_creatives.py similarity index 85% rename from examples/dfp/v201702/creative_service/update_creatives.py rename to examples/dfp/v201711/creative_service/update_creatives.py index 59dcc8bd..c718b379 100755 --- a/examples/dfp/v201702/creative_service/update_creatives.py +++ b/examples/dfp/v201711/creative_service/update_creatives.py @@ -34,24 +34,14 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Create statement object to get all image creatives. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }, { - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': image_creative_id - } - }] - query = 'WHERE creativeType = :type AND id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('creativeType = :type AND id = :id') + .WithBindVariable('type', 'ImageCreative') + .WithBindVariable('id', long(image_creative_id)) + .Limit(1)) # Get creatives by statement. response = creative_service.getCreativesByStatement( @@ -74,6 +64,7 @@ def main(client, image_creative_id): else: print 'No creatives found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/creative_set_service/__init__.py b/examples/dfp/v201711/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201702/creative_set_service/__init__.py rename to examples/dfp/v201711/creative_set_service/__init__.py diff --git a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py index 08513acc..579c7746 100755 --- a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201702/creative_set_service/create_creative_set.py b/examples/dfp/v201711/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201702/creative_set_service/create_creative_set.py rename to examples/dfp/v201711/creative_set_service/create_creative_set.py index 9118a157..c734a6fd 100755 --- a/examples/dfp/v201702/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201711/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201702') + version='v201711') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py similarity index 97% rename from examples/dfp/v201702/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201711/creative_set_service/get_all_creative_sets.py index 6e8bd9fa..ffabc63c 100755 --- a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201702') + 'CreativeSetService', version='v201711') # Create a statement to select creative sets. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py similarity index 85% rename from examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py index 859b9aeb..c2aaa861 100755 --- a/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,17 +25,11 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201702') - query = 'WHERE masterCreativeId = :masterCreativeId' - values = [ - {'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'TextValue', - 'value': master_creative_id - }}, - ] + 'CreativeSetService', version='v201711') # Create a statement to select creative sets. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('masterCreativeId = :masterCreativeId') + .WithBindVariable('masterCreativeId', master_creative_id)) # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/dfp/v201702/creative_set_service/update_creative_set.py b/examples/dfp/v201711/creative_set_service/update_creative_set.py similarity index 89% rename from examples/dfp/v201702/creative_set_service/update_creative_set.py rename to examples/dfp/v201711/creative_set_service/update_creative_set.py index c03266d4..44737177 100755 --- a/examples/dfp/v201702/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201711/creative_set_service/update_creative_set.py @@ -37,18 +37,12 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201702') + version='v201711') # Create statement to select a single creative set by ID. - values = [{ - 'key': 'creativeSetId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_set_id - } - }] - query = 'WHERE id = :creativeSetId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeSetId') + .WithBindVariable('creativeSetId', long(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -72,6 +66,7 @@ def main(client, creative_set_id, companion_creative_id): else: print 'No creative sets found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/creative_template_service/__init__.py b/examples/dfp/v201711/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201702/creative_template_service/__init__.py rename to examples/dfp/v201711/creative_template_service/__init__.py diff --git a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py similarity index 97% rename from examples/dfp/v201702/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201711/creative_template_service/get_all_creative_templates.py index 39ced2d2..ed5f73f5 100755 --- a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201702') + 'CreativeTemplateService', version='v201711') # Create a statement to select creative templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py similarity index 86% rename from examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py rename to examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py index b4748eba..a76a87fd 100755 --- a/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - }}, - ] + 'CreativeTemplateService', version='v201711') # Create a statement to select creative templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'SYSTEM_DEFINED')) # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py similarity index 91% rename from examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py index 2ac46646..ba0d2ca5 100755 --- a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py @@ -37,15 +37,15 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201702') + version='v201711') # Create creative wrapper objects. creative_wrapper = { # A label can only be associated with one creative wrapper. 'labelId': label_id, 'ordering': 'INNER', - 'header': {'htmlSnippet': 'My creative wrapper header'}, - 'footer': {'htmlSnippet': 'My creative wrapper footer'} + 'htmlHeader': 'My creative wrapper header', + 'htmlFooter': 'My creative wrapper footer' } # Add creative wrapper. diff --git a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 85% rename from examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py index 48c4c1ae..7d560973 100755 --- a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,24 +33,13 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201702') + version='v201711') # Create a query to select the active creative wrappers for the given label. - values = [{ - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status AND labelId = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status AND labelId = :labelId') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('labelId', long(label_id))) creative_wrappers_deactivated = 0 @@ -82,6 +71,7 @@ def main(client, label_id): else: print 'No creative wrappers were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py similarity index 86% rename from examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py index c3200282..98f9f576 100755 --- a/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'CreativeWrapperService', version='v201711') # Create a statement to select creative wrappers. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py similarity index 97% rename from examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py index 26fb962d..30780139 100755 --- a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201702') + 'CreativeWrapperService', version='v201711') # Create a statement to select creative wrappers. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py similarity index 88% rename from examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py index 5bb8ee6c..b4161728 100755 --- a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py @@ -36,18 +36,13 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201702') + version='v201711') # Create statement to get a creative wrapper by ID. - values = [{ - 'key': 'creativeWrapperId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_wrapper_id - } - }] - query = 'WHERE id = :creativeWrapperId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeWrapperId') + .WithBindVariable('creativeWrapperId', + long(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -71,6 +66,7 @@ def main(client, creative_wrapper_id): else: print 'No creative wrappers found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_field_service/__init__.py b/examples/dfp/v201711/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201702/custom_field_service/__init__.py rename to examples/dfp/v201711/custom_field_service/__init__.py diff --git a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py b/examples/dfp/v201711/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201702/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201711/custom_field_service/create_custom_field_options.py index d2f010bd..3c890017 100755 --- a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201711/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201711') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201702/custom_field_service/create_custom_fields.py b/examples/dfp/v201711/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201702/custom_field_service/create_custom_fields.py rename to examples/dfp/v201711/custom_field_service/create_custom_fields.py index a823244c..58500da2 100755 --- a/examples/dfp/v201702/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201711') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 82% rename from examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py index 51333474..ac1e29fa 100755 --- a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,27 +33,14 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201711') # Create statement to select only active custom fields that apply to # line items. - values = [ - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }, { - 'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - } - ] - query = 'WHERE entityType = :entityType and isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType and isActive = :isActive') + .WithBindVariable('entityType', 'LINE_ITEM') + .WithBindVariable('isActive', True)) custom_fields_deactivated = 0 @@ -79,6 +66,7 @@ def main(client): else: print 'No custom fields were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py similarity index 97% rename from examples/dfp/v201702/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201711/custom_field_service/get_all_custom_fields.py index a823a7a6..bd60ea4c 100755 --- a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201711') # Create a statement to select custom fields. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py similarity index 85% rename from examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py rename to examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py index a350fc29..ba26fb6e 100755 --- a/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') - query = 'WHERE entityType = :entityType' - values = [ - {'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - }}, - ] + 'CustomFieldService', version='v201711') # Create a statement to select custom fields. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType') + .WithBindVariable('entityType', 'LINE_ITEM')) # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py index 63bf186c..2c0c0ad1 100755 --- a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201711') - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201702/custom_field_service/update_custom_fields.py b/examples/dfp/v201711/custom_field_service/update_custom_fields.py similarity index 88% rename from examples/dfp/v201702/custom_field_service/update_custom_fields.py rename to examples/dfp/v201711/custom_field_service/update_custom_fields.py index 5a56bb72..1b6403c7 100755 --- a/examples/dfp/v201702/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/update_custom_fields.py @@ -36,18 +36,12 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201711') # Create statement to get a custom field. - values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - query = 'WHERE id = :customFieldId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', long(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -69,6 +63,7 @@ def main(client, custom_field_id): else: print 'No custom fields found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_targeting_service/__init__.py b/examples/dfp/v201711/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201702/custom_targeting_service/__init__.py rename to examples/dfp/v201711/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py index ed80ede7..0fd0c263 100755 --- a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py similarity index 90% rename from examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py index abb78c9d..defeb67f 100755 --- a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,17 +36,11 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') - - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': key_name - } - }] - query = 'WHERE name = :name' - statement = dfp.FilterStatement(query, values) + 'CustomTargetingService', version='v201711') + + statement = (dfp.StatementBuilder() + .Where('name = :name') + .WithBindVariable('name', key_name)) deleted_custom_targeting_keys = 0 @@ -76,6 +70,7 @@ def main(client, key_name): else: print 'No custom targeting keys were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py similarity index 98% rename from examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py index 84af48bb..91c3fd9c 100755 --- a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py @@ -36,7 +36,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index fbafecd9..4559215e 100755 --- a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') # Create statement to get all targeting keys. targeting_key_statement = dfp.StatementBuilder() @@ -46,7 +46,7 @@ def main(client): ', '.join([str(key['id']) for key in all_keys])) statement = dfp.FilterStatement(query) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( diff --git a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 78% rename from examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 8e297f13..d9f0f076 100755 --- a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,18 +23,12 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') # Create statement to get targeting keys for predefined values. - query = ('WHERE type = :type') - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] - targeting_key_statement = dfp.FilterStatement(query, values) + targeting_key_statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'PREDEFINED')) all_keys = [] @@ -44,17 +38,17 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (:ids)') + .WithBindVariable('ids', [key['id'] for key in all_keys])) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( @@ -67,7 +61,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py similarity index 88% rename from examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py index ed87ad62..0b6ebc81 100755 --- a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py @@ -30,17 +30,12 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE id = :keyId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :keyId') + .WithBindVariable('keyId', long(key_id)) + .Limit(1)) # Get custom targeting keys by statement. response = custom_targeting_service.getCustomTargetingKeysByStatement( @@ -65,6 +60,7 @@ def main(client, key_id): else: print 'No custom targeting keys were found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py similarity index 88% rename from examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py index ca09f287..edf52d61 100755 --- a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py @@ -30,17 +30,11 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', long(key_id))) while True: # Get custom targeting values by statement. @@ -70,6 +64,7 @@ def main(client, key_id): if response['totalResultSetSize'] == 0: print 'No custom targeting values were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/exchange_rate_service/__init__.py b/examples/dfp/v201711/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201702/exchange_rate_service/__init__.py rename to examples/dfp/v201711/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py index 2cdc541f..8be06ec7 100755 --- a/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201702') + version='v201711') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py similarity index 97% rename from examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py index 7c4d95b6..5b9c8ae3 100755 --- a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201702') + 'ExchangeRateService', version='v201711') # Create a statement to select exchange rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 86% rename from examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py index f2b683f1..3b09f1dd 100755 --- a/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,17 +25,11 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201702') - query = 'WHERE currencyCode = :currencyCode' - values = [ - {'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - }}, - ] + 'ExchangeRateService', version='v201711') # Create a statement to select exchange rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('currencyCode = :currencyCode') + .WithBindVariable('currencyCode', currency_code)) # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py similarity index 87% rename from examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py index 26dc9f69..61a3a46d 100755 --- a/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py @@ -30,19 +30,13 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201702') + version='v201711') # Create a statement to get an exchange rate by its ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': exchange_rate_id - } - }] - query = 'WHERE id = :id' - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(exchange_rate_id)) + .Limit(1)) # Get rate cards by statement. response = exchange_rate_service.getExchangeRatesByStatement( diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast.py b/examples/dfp/v201711/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/dfp/v201702/forecast_service/get_availability_forecast.py rename to examples/dfp/v201711/forecast_service/get_availability_forecast.py index 7ed5d8f1..331913f4 100755 --- a/examples/dfp/v201702/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201711/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + forecast_service = client.GetService('ForecastService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py index ea625ff7..370679ee 100755 --- a/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201702') + forecast_service = client.GetService('ForecastService', version='v201711') # Set forecasting options. forecast_options = { diff --git a/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py index 3d6187f7..38f54050 100755 --- a/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201702') + forecast_service = client.GetService('ForecastService', version='v201711') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201702/inventory_service/__init__.py b/examples/dfp/v201711/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201702/inventory_service/__init__.py rename to examples/dfp/v201711/inventory_service/__init__.py diff --git a/examples/dfp/v201702/inventory_service/archive_ad_units.py b/examples/dfp/v201711/inventory_service/archive_ad_units.py similarity index 90% rename from examples/dfp/v201702/inventory_service/archive_ad_units.py rename to examples/dfp/v201711/inventory_service/archive_ad_units.py index b1097b3b..b7222ecf 100755 --- a/examples/dfp/v201702/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201711/inventory_service/archive_ad_units.py @@ -35,19 +35,13 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201702') + inventory_service = client.GetService('InventoryService', version='v201711') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - values = [{ - 'key': 'parentId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': parent_id - } - }] - query = 'WHERE parentId = :parentId or id = :parentId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId or id = :parentId') + .WithBindVariable('parentId', long(parent_id))) ad_units_archived = 0 @@ -74,6 +68,7 @@ def main(client, parent_id): else: print 'No ad units were archived.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/inventory_service/create_ad_units.py b/examples/dfp/v201711/inventory_service/create_ad_units.py similarity index 99% rename from examples/dfp/v201702/inventory_service/create_ad_units.py rename to examples/dfp/v201711/inventory_service/create_ad_units.py index 6cf363df..b017e0dd 100755 --- a/examples/dfp/v201702/inventory_service/create_ad_units.py +++ b/examples/dfp/v201711/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201702') + inventory_service = client.GetService('InventoryService', version='v201711') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py new file mode 100755 index 00000000..059e2af7 --- /dev/null +++ b/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 prints all ad unit names as a tree.""" + + +# Import appropriate modules from the client library. +import collections +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201711') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select only the root ad unit by ID. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', root_ad_unit_id)) + + # Make a request for the root ad unit + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + root_ad_unit = response['results'][0] + + all_ad_units = get_all_ad_units(inventory_service) + + display_hierarchy(root_ad_unit, all_ad_units) + + +def get_all_ad_units(inventory_service): + """Download all ad units. + + Args: + inventory_service: An instance of the InventoryService. + + Returns: + A list containing all ad units. + """ + # Create a statement to get all ad units. + statement = (dfp.StatementBuilder() + .OrderBy('id', ascending=True)) + + # Pull down all ad units into a list + keep_iterating = True + total_results = 0 + found_ad_units = [] + while keep_iterating: + page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in page: + total_results = page['totalResultSetSize'] + found_ad_units.extend(page['results']) + + statement.offset += statement.limit + keep_iterating = statement.offset < total_results + + return found_ad_units + + +def display_hierarchy(root_ad_unit, all_ad_units): + """Display the ad units as a tree. + + Args: + root_ad_unit: The root ad unit to begin from. + all_ad_units: A list containing all ad units. + """ + # Create a dict mapping the ids of parents to lists of their children. + parent_id_to_children = collections.defaultdict(list) + for ad_unit in all_ad_units: + if 'parentId' in ad_unit: + parent_id_to_children[ad_unit['parentId']].append(ad_unit) + parent_id_to_children = dict(parent_id_to_children) + + display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0) + + +def display_hierarchy_helper(root, parent_id_to_children, depth): + """Recursive helper for displaying the hierarchy. + + Args: + root: The current root ad unit. + parent_id_to_children: The overall map of parent ids to children. + depth: The current depth. + """ + print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id']) + + # Recurse for each child of this root that has children. + for child in parent_id_to_children.get(root['id'], []): + display_hierarchy_helper(child, parent_id_to_children, depth + 1) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py index 3af222b4..aba7e9e5 100755 --- a/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py @@ -23,12 +23,12 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201702') + 'InventoryService', version='v201711') # Create a statement to select ad unit sizes. statement = dfp.FilterStatement() - # Retreive a small amount of ad unit sizes at a time, paging + # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. response = ad_unit_size_service.getAdUnitSizesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_units.py b/examples/dfp/v201711/inventory_service/get_all_ad_units.py similarity index 99% rename from examples/dfp/v201702/inventory_service/get_all_ad_units.py rename to examples/dfp/v201711/inventory_service/get_all_ad_units.py index 90a2da31..0b7f1585 100755 --- a/examples/dfp/v201702/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201711/inventory_service/get_all_ad_units.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201702') + ad_unit_service = client.GetService('InventoryService', version='v201711') # Create a statement to select ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py new file mode 100755 index 00000000..7e3a4200 --- /dev/null +++ b/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 child ad units of the effective root ad unit.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201711') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + parent_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select ad units under the parent ad unit. + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId') + .OrderBy('id', ascending=True) + .WithBindVariable('parentId', parent_ad_unit_id)) + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response: + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/inventory_service/update_ad_units.py b/examples/dfp/v201711/inventory_service/update_ad_units.py similarity index 92% rename from examples/dfp/v201702/inventory_service/update_ad_units.py rename to examples/dfp/v201711/inventory_service/update_ad_units.py index 75cec0aa..c1c3b0e0 100755 --- a/examples/dfp/v201702/inventory_service/update_ad_units.py +++ b/examples/dfp/v201711/inventory_service/update_ad_units.py @@ -36,18 +36,12 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201702') + inventory_service = client.GetService('InventoryService', version='v201711') # Create a statement to select a single ad unit by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': ad_unit_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', ad_unit_id)) # Get ad units by statement. response = inventory_service.getAdUnitsByStatement( @@ -81,6 +75,7 @@ def main(client, ad_unit_id): print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/label_service/__init__.py b/examples/dfp/v201711/label_service/__init__.py similarity index 100% rename from examples/dfp/v201702/label_service/__init__.py rename to examples/dfp/v201711/label_service/__init__.py diff --git a/examples/dfp/v201702/label_service/create_labels.py b/examples/dfp/v201711/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201702/label_service/create_labels.py rename to examples/dfp/v201711/label_service/create_labels.py index 4c71d810..f4d95ddc 100755 --- a/examples/dfp/v201702/label_service/create_labels.py +++ b/examples/dfp/v201711/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') + label_service = client.GetService('LabelService', version='v201711') # Create label objects. labels = [] diff --git a/examples/dfp/v201702/label_service/deactivate_labels.py b/examples/dfp/v201711/label_service/deactivate_labels.py similarity index 89% rename from examples/dfp/v201702/label_service/deactivate_labels.py rename to examples/dfp/v201711/label_service/deactivate_labels.py index d9e0e71a..04227aff 100755 --- a/examples/dfp/v201702/label_service/deactivate_labels.py +++ b/examples/dfp/v201711/label_service/deactivate_labels.py @@ -27,18 +27,12 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') + label_service = client.GetService('LabelService', version='v201711') # Create query. - values = [{ - 'key': 'isActive', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'true' - } - }] - query = 'WHERE isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) labels_deactivated = 0 @@ -64,6 +58,7 @@ def main(client): else: print 'No labels were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/label_service/get_active_labels.py b/examples/dfp/v201711/label_service/get_active_labels.py similarity index 87% rename from examples/dfp/v201702/label_service/get_active_labels.py rename to examples/dfp/v201711/label_service/get_active_labels.py index 895be48f..8e419288 100755 --- a/examples/dfp/v201702/label_service/get_active_labels.py +++ b/examples/dfp/v201711/label_service/get_active_labels.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') - query = 'WHERE isActive = :isActive' - values = [ - {'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + label_service = client.GetService('LabelService', version='v201711') # Create a statement to select labels. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/dfp/v201702/label_service/get_all_labels.py b/examples/dfp/v201711/label_service/get_all_labels.py similarity index 99% rename from examples/dfp/v201702/label_service/get_all_labels.py rename to examples/dfp/v201711/label_service/get_all_labels.py index d4ae0fc6..2ac0531b 100755 --- a/examples/dfp/v201702/label_service/get_all_labels.py +++ b/examples/dfp/v201711/label_service/get_all_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') + label_service = client.GetService('LabelService', version='v201711') # Create a statement to select labels. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/label_service/update_labels.py b/examples/dfp/v201711/label_service/update_labels.py similarity index 87% rename from examples/dfp/v201702/label_service/update_labels.py rename to examples/dfp/v201711/label_service/update_labels.py index dc1b3ffe..bebbe0d7 100755 --- a/examples/dfp/v201702/label_service/update_labels.py +++ b/examples/dfp/v201711/label_service/update_labels.py @@ -29,20 +29,12 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') + label_service = client.GetService('LabelService', version='v201711') # Create a statement to select only active labels. - values = [ - { - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - } - ] - query = 'WHERE id = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :labelId') + .WithBindVariable('labelId', long(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -63,6 +55,7 @@ def main(client, label_id): else: print 'No labels found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_creative_association_service/__init__.py b/examples/dfp/v201711/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201702/line_item_creative_association_service/__init__.py rename to examples/dfp/v201711/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py b/examples/dfp/v201711/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201702/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201711/line_item_creative_association_service/create_licas.py index 13743d0a..7a6b7e1f 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py similarity index 83% rename from examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py index 537ee699..453cd6ef 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py @@ -30,24 +30,13 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') # Create query. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE lineItemId = :lineItemId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId AND status = :status') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('lineItemId', long(line_item_id))) num_deactivated_licas = 0 @@ -77,6 +66,7 @@ def main(client, line_item_id): else: print 'No LICAs were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py similarity index 97% rename from examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py index 71e757ad..24b02c79 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') # Create a statement to select line item creative associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py similarity index 87% rename from examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py index d61f98f5..0f6a4ea4 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,17 +25,11 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') - query = 'WHERE lineItemId = :lineItemId' - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'TextValue', - 'value': line_item_id - }}, - ] + 'LineItemCreativeAssociationService', version='v201711') # Create a statement to select line item creative associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId') + .WithBindVariable('lineItemId', line_item_id)) # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py b/examples/dfp/v201711/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201702/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201711/line_item_creative_association_service/update_licas.py index 783a1e87..f52e4727 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/update_licas.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') # Create statement object to get all LICAs. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/line_item_service/__init__.py b/examples/dfp/v201711/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201702/line_item_service/__init__.py rename to examples/dfp/v201711/line_item_service/__init__.py diff --git a/examples/dfp/v201702/line_item_service/activate_line_items.py b/examples/dfp/v201711/line_item_service/activate_line_items.py similarity index 86% rename from examples/dfp/v201702/line_item_service/activate_line_items.py rename to examples/dfp/v201711/line_item_service/activate_line_items.py index 91dc966b..c8f08513 100755 --- a/examples/dfp/v201702/line_item_service/activate_line_items.py +++ b/examples/dfp/v201711/line_item_service/activate_line_items.py @@ -33,24 +33,13 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # Create query. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' - } - }] - query = 'WHERE orderId = :orderId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId AND status = :status') + .WithBindVariable('status', 'NEEDS_CREATIVES') + .WithBindVariable('orderId', long(order_id))) line_items_activated = 0 @@ -79,6 +68,7 @@ def main(client, order_id): else: print 'No line items were activated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_service/create_line_items.py b/examples/dfp/v201711/line_item_service/create_line_items.py similarity index 93% rename from examples/dfp/v201702/line_item_service/create_line_items.py rename to examples/dfp/v201711/line_item_service/create_line_items.py index 10ab761b..71c64228 100755 --- a/examples/dfp/v201702/line_item_service/create_line_items.py +++ b/examples/dfp/v201711/line_item_service/create_line_items.py @@ -22,11 +22,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set order that the created line item will belong to and add the id of a # placement containing ad units to target. @@ -36,7 +37,10 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) # Create line item objects. line_items = [] @@ -128,17 +132,7 @@ def main(client, order_id, targeted_placement_ids): ], 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'STANDARD', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201702/line_item_service/create_video_line_item.py b/examples/dfp/v201711/line_item_service/create_video_line_item.py similarity index 92% rename from examples/dfp/v201702/line_item_service/create_video_line_item.py rename to examples/dfp/v201711/line_item_service/create_video_line_item.py index e02c4062..551c853c 100755 --- a/examples/dfp/v201702/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201711/line_item_service/create_video_line_item.py @@ -24,11 +24,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set order that all created line item will belong to and the video ad unit id # to target. @@ -46,7 +47,10 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) # Create line item object. line_item = { @@ -99,17 +103,7 @@ def main(client, order_id, targeted_video_ad_unit_id, 'companionDeliveryOption': 'OPTIONAL', 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'SPONSORSHIP', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201702/line_item_service/get_all_line_items.py b/examples/dfp/v201711/line_item_service/get_all_line_items.py similarity index 99% rename from examples/dfp/v201702/line_item_service/get_all_line_items.py rename to examples/dfp/v201711/line_item_service/get_all_line_items.py index 07cee823..7f9b8b1a 100755 --- a/examples/dfp/v201702/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201711/line_item_service/get_all_line_items.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # Create a statement to select line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py similarity index 86% rename from examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py rename to examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py index cfba2dd4..686e20b6 100755 --- a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') - query = 'WHERE isMissingCreatives = :isMissingCreatives' - values = [ - {'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + line_item_service = client.GetService('LineItemService', version='v201711') # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isMissingCreatives = :isMissingCreatives') + .WithBindVariable('isMissingCreatives', True)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py similarity index 82% rename from examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py index f23a397b..533e0bae 100755 --- a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py @@ -21,22 +21,20 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') - query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' - values = [ - {'key': 'lastModifiedDateTime', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() - timedelta(days=1)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + line_item_service = client.GetService('LineItemService', version='v201711') + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201702/line_item_service/pause_line_items.py b/examples/dfp/v201711/line_item_service/pause_line_items.py similarity index 99% rename from examples/dfp/v201702/line_item_service/pause_line_items.py rename to examples/dfp/v201711/line_item_service/pause_line_items.py index 42ed186a..d8261d8c 100755 --- a/examples/dfp/v201702/line_item_service/pause_line_items.py +++ b/examples/dfp/v201711/line_item_service/pause_line_items.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # Create a statement to select the line item. # Change this to operate on more than one Line Item. diff --git a/examples/dfp/v201702/line_item_service/target_custom_criteria.py b/examples/dfp/v201711/line_item_service/target_custom_criteria.py similarity index 93% rename from examples/dfp/v201702/line_item_service/target_custom_criteria.py rename to examples/dfp/v201711/line_item_service/target_custom_criteria.py index e622c627..7299e656 100755 --- a/examples/dfp/v201702/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201711/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # create custom criterias custom_criteria1 = { @@ -81,15 +81,10 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - query = 'WHERE id = :lineItemId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', long(line_item_id)) + .Limit(1)) # Set custom criteria targeting on the line item. line_item = line_item_service.getLineItemsByStatement( @@ -107,6 +102,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, else: print 'No line items were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_service/update_line_items.py b/examples/dfp/v201711/line_item_service/update_line_items.py similarity index 84% rename from examples/dfp/v201702/line_item_service/update_line_items.py rename to examples/dfp/v201711/line_item_service/update_line_items.py index 62e2371b..ba6e8ae1 100755 --- a/examples/dfp/v201702/line_item_service/update_line_items.py +++ b/examples/dfp/v201711/line_item_service/update_line_items.py @@ -29,25 +29,16 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # Create statement object to only select line items with even delivery rates. - values = [{ - 'key': 'deliveryRateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'EVENLY' - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId' - statement = dfp.FilterStatement(query, values, 500) + statement = (dfp.StatementBuilder() + .Where(('deliveryRateType = :deliveryRateType AND ' + 'orderId = :orderId')) + .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('deliveryRateType', 'EVENLY') + .Limit(500)) # Get line items by statement. response = line_item_service.getLineItemsByStatement( @@ -76,6 +67,7 @@ def main(client, order_id): else: print 'No line items found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201711/native_style_service/__init__.py b/examples/dfp/v201711/native_style_service/__init__.py new file mode 100755 index 00000000..473ddba1 --- /dev/null +++ b/examples/dfp/v201711/native_style_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. diff --git a/examples/dfp/v201702/native_style_service/create_native_styles.py b/examples/dfp/v201711/native_style_service/create_native_styles.py similarity index 98% rename from examples/dfp/v201702/native_style_service/create_native_styles.py rename to examples/dfp/v201711/native_style_service/create_native_styles.py index f1204fa2..7923a081 100755 --- a/examples/dfp/v201702/native_style_service/create_native_styles.py +++ b/examples/dfp/v201711/native_style_service/create_native_styles.py @@ -149,7 +149,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201702') + version='v201711') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/dfp/v201702/native_style_service/get_all_native_styles.py b/examples/dfp/v201711/native_style_service/get_all_native_styles.py similarity index 96% rename from examples/dfp/v201702/native_style_service/get_all_native_styles.py rename to examples/dfp/v201711/native_style_service/get_all_native_styles.py index 0f48cfa8..419ea950 100755 --- a/examples/dfp/v201702/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201711/native_style_service/get_all_native_styles.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201702') + version='v201711') # Create a statement to select native styles. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/network_service/__init__.py b/examples/dfp/v201711/network_service/__init__.py similarity index 100% rename from examples/dfp/v201702/network_service/__init__.py rename to examples/dfp/v201711/network_service/__init__.py diff --git a/examples/dfp/v201702/network_service/get_all_networks.py b/examples/dfp/v201711/network_service/get_all_networks.py similarity index 99% rename from examples/dfp/v201702/network_service/get_all_networks.py rename to examples/dfp/v201711/network_service/get_all_networks.py index 62107fd8..d040f75a 100755 --- a/examples/dfp/v201702/network_service/get_all_networks.py +++ b/examples/dfp/v201711/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201702') + network_service = client.GetService('NetworkService', version='v201711') networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201711/network_service/get_current_network.py b/examples/dfp/v201711/network_service/get_current_network.py new file mode 100755 index 00000000..e112d553 --- /dev/null +++ b/examples/dfp/v201711/network_service/get_current_network.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 the current network.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201711') + + current_network = network_service.getCurrentNetwork() + + print ("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/network_service/make_test_network.py b/examples/dfp/v201711/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201702/network_service/make_test_network.py rename to examples/dfp/v201711/network_service/make_test_network.py index f5d0b37f..8782a971 100755 --- a/examples/dfp/v201702/network_service/make_test_network.py +++ b/examples/dfp/v201711/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201702') + network_service = client.GetService('NetworkService', version='v201711') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/dfp/v201702/order_service/__init__.py b/examples/dfp/v201711/order_service/__init__.py similarity index 100% rename from examples/dfp/v201702/order_service/__init__.py rename to examples/dfp/v201711/order_service/__init__.py diff --git a/examples/dfp/v201702/order_service/approve_orders.py b/examples/dfp/v201711/order_service/approve_orders.py similarity index 84% rename from examples/dfp/v201702/order_service/approve_orders.py rename to examples/dfp/v201711/order_service/approve_orders.py index e39fba4e..51f84adc 100755 --- a/examples/dfp/v201702/order_service/approve_orders.py +++ b/examples/dfp/v201711/order_service/approve_orders.py @@ -28,21 +28,14 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') - - # Create query. - values = [{ - 'key': 'today', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S') - } - }] - query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')' - ' AND endDateTime >= :today AND isArchived = FALSE') + order_service = client.GetService('OrderService', version='v201711') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + today = datetime.date.today() + statement = (dfp.StatementBuilder() + .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' + 'AND endDateTime >= :today AND isArchived = FALSE')) + .WithBindVariable('today', today)) orders_approved = 0 # Get orders by statement. diff --git a/examples/dfp/v201702/order_service/create_orders.py b/examples/dfp/v201711/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201702/order_service/create_orders.py rename to examples/dfp/v201711/order_service/create_orders.py index 8d05ef74..f2b5628f 100755 --- a/examples/dfp/v201702/order_service/create_orders.py +++ b/examples/dfp/v201711/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') + order_service = client.GetService('OrderService', version='v201711') # Create order objects. orders = [] diff --git a/examples/dfp/v201702/order_service/get_all_orders.py b/examples/dfp/v201711/order_service/get_all_orders.py similarity index 99% rename from examples/dfp/v201702/order_service/get_all_orders.py rename to examples/dfp/v201711/order_service/get_all_orders.py index 2c34d9f2..244b582a 100755 --- a/examples/dfp/v201702/order_service/get_all_orders.py +++ b/examples/dfp/v201711/order_service/get_all_orders.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') + order_service = client.GetService('OrderService', version='v201711') # Create a statement to select orders. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/order_service/get_orders_starting_soon.py b/examples/dfp/v201711/order_service/get_orders_starting_soon.py similarity index 73% rename from examples/dfp/v201702/order_service/get_orders_starting_soon.py rename to examples/dfp/v201711/order_service/get_orders_starting_soon.py index b99060c3..af8f7247 100755 --- a/examples/dfp/v201702/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201711/order_service/get_orders_starting_soon.py @@ -21,33 +21,22 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') - query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' - '<= :soon') - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'APPROVED' - }}, - {'key': 'now', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') - }}, - {'key': 'soon', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() + timedelta(days=5)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + order_service = client.GetService('OrderService', version='v201711') + now = datetime.now(tz=pytz.timezone('America/New_York')) + soon = now + timedelta(days=5) + # Create a statement to select orders. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('status = :status AND startDateTime >= :now ' + 'AND startDateTime <= :soon')) + .WithBindVariable('status', 'APPROVED') + .WithBindVariable('now', now) + .WithBindVariable('soon', soon)) # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/dfp/v201702/order_service/update_orders.py b/examples/dfp/v201711/order_service/update_orders.py similarity index 90% rename from examples/dfp/v201702/order_service/update_orders.py rename to examples/dfp/v201711/order_service/update_orders.py index fe962a03..ee06522e 100755 --- a/examples/dfp/v201702/order_service/update_orders.py +++ b/examples/dfp/v201711/order_service/update_orders.py @@ -28,19 +28,13 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') + order_service = client.GetService('OrderService', version='v201711') # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :orderId') + .WithBindVariable('orderId', long(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -69,6 +63,7 @@ def main(client, order_id): else: print 'No orders found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/package_service/create_packages.py b/examples/dfp/v201711/package_service/create_packages.py similarity index 99% rename from examples/dfp/v201702/package_service/create_packages.py rename to examples/dfp/v201711/package_service/create_packages.py index 21dce743..cafb0c42 100755 --- a/examples/dfp/v201702/package_service/create_packages.py +++ b/examples/dfp/v201711/package_service/create_packages.py @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201702') + package_service = client.GetService('PackageService', version='v201711') # Create local package. package = { diff --git a/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py similarity index 99% rename from examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py rename to examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py index 901d0967..4029c889 100755 --- a/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py +++ b/examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201702') + package_service = client.GetService('PackageService', version='v201711') # Create a statement to select the single package. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/package_service/get_all_packages.py b/examples/dfp/v201711/package_service/get_all_packages.py similarity index 99% rename from examples/dfp/v201702/package_service/get_all_packages.py rename to examples/dfp/v201711/package_service/get_all_packages.py index 1db46c9b..a759e6e8 100755 --- a/examples/dfp/v201702/package_service/get_all_packages.py +++ b/examples/dfp/v201711/package_service/get_all_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201702') + pkg_service = client.GetService('PackageService', version='v201711') # Create a statement to select packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/package_service/get_in_progress_packages.py b/examples/dfp/v201711/package_service/get_in_progress_packages.py similarity index 87% rename from examples/dfp/v201702/package_service/get_in_progress_packages.py rename to examples/dfp/v201711/package_service/get_in_progress_packages.py index 23994ed3..48ad8b79 100755 --- a/examples/dfp/v201702/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201711/package_service/get_in_progress_packages.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'IN_PROGRESS' - }}, - ] + pkg_service = client.GetService('PackageService', version='v201711') # Create a statement to select packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'IN_PROGRESS')) # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/dfp/v201702/placement_service/create_placements.py b/examples/dfp/v201711/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201702/placement_service/create_placements.py rename to examples/dfp/v201711/placement_service/create_placements.py index 485ffe1c..d974198e 100755 --- a/examples/dfp/v201702/placement_service/create_placements.py +++ b/examples/dfp/v201711/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') - inventory_service = client.GetService('InventoryService', version='v201702') + placement_service = client.GetService('PlacementService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201711') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201702/placement_service/deactivate_placements.py b/examples/dfp/v201711/placement_service/deactivate_placements.py similarity index 88% rename from examples/dfp/v201702/placement_service/deactivate_placements.py rename to examples/dfp/v201711/placement_service/deactivate_placements.py index a7ef1a57..6d0bc0f8 100755 --- a/examples/dfp/v201702/placement_service/deactivate_placements.py +++ b/examples/dfp/v201711/placement_service/deactivate_placements.py @@ -28,18 +28,13 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') + placement_service = client.GetService('PlacementService', version='v201711') # Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :placementId') + .WithBindVariable('placementId', long(placement_id)) + .Limit(1)) # Get placements by statement. placements = placement_service.getPlacementsByStatement( @@ -60,6 +55,7 @@ def main(client, placement_id): else: print 'No placements were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/placement_service/get_active_placements.py b/examples/dfp/v201711/placement_service/get_active_placements.py similarity index 87% rename from examples/dfp/v201702/placement_service/get_active_placements.py rename to examples/dfp/v201711/placement_service/get_active_placements.py index 64e4ff18..816c1bb3 100755 --- a/examples/dfp/v201702/placement_service/get_active_placements.py +++ b/examples/dfp/v201711/placement_service/get_active_placements.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + placement_service = client.GetService('PlacementService', version='v201711') # Create a statement to select placements. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/dfp/v201702/placement_service/get_all_placements.py b/examples/dfp/v201711/placement_service/get_all_placements.py similarity index 99% rename from examples/dfp/v201702/placement_service/get_all_placements.py rename to examples/dfp/v201711/placement_service/get_all_placements.py index b40c18b9..7fce181e 100755 --- a/examples/dfp/v201702/placement_service/get_all_placements.py +++ b/examples/dfp/v201711/placement_service/get_all_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') + placement_service = client.GetService('PlacementService', version='v201711') # Create a statement to select placements. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/placement_service/update_placements.py b/examples/dfp/v201711/placement_service/update_placements.py similarity index 57% rename from examples/dfp/v201702/placement_service/update_placements.py rename to examples/dfp/v201711/placement_service/update_placements.py index 8c79b94b..a2663891 100755 --- a/examples/dfp/v201702/placement_service/update_placements.py +++ b/examples/dfp/v201711/placement_service/update_placements.py @@ -28,37 +28,29 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') -# Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + placement_service = client.GetService('PlacementService', version='v201711') + + # Create query. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', placement_id)) # Get placements by statement. - placements = placement_service.getPlacementsByStatement( + page = placement_service.getPlacementsByStatement( statement.ToStatement()) - for placement in placements: - if not placement['targetingDescription']: - placement['targetingDescription'] = 'Generic description' - placement['targetingAdLocation'] = 'All images on sports pages.' - placement['targetingSiteName'] = 'http://code.google.com' - placement['isAdSenseTargetingEnabled'] = 'true' + placement = page['results'][0] + + placement['description'] = 'This placement contains all leaderboards.' # Update placements remotely. - placements = placement_service.updatePlacements(placements) + updated_placements = placement_service.updatePlacements([placement]) - for placement in placements: - print ('Placement with id "%s", name "%s", and AdSense targeting ' - 'enabled "%s" was updated.' - % (placement['id'], placement['name'], - placement['isAdSenseTargetingEnabled'])) + for placement in updated_placements: + print ('Placement with id "%s" and name "%s" was updated.' + % (placement['id'], placement['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201702/premium_rate_service/__init__.py b/examples/dfp/v201711/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201702/premium_rate_service/__init__.py rename to examples/dfp/v201711/premium_rate_service/__init__.py diff --git a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py b/examples/dfp/v201711/premium_rate_service/create_premium_rates.py similarity index 90% rename from examples/dfp/v201702/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201711/premium_rate_service/create_premium_rates.py index 151942f9..7d35fa92 100755 --- a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201711/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201702') + version='v201711') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { @@ -57,7 +57,10 @@ def main(client, rate_card_id): 'adjustmentType': 'ABSOLUTE_VALUE' } - # Create premium_rate objects. + # Create premium rate. + # Associate premium rate with the rate card and set premium information. + # This premium will apply for proposal line items targeting 'any' ad unit + # for both CPM and CPC rate types. premium_rate = { 'rateCardId': rate_card_id, 'pricingMethod': 'ANY_VALUE', diff --git a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py similarity index 97% rename from examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py index 4294dfb3..67ae3b82 100755 --- a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201702') + 'PremiumRateService', version='v201711') # Create a statement to select premium rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 87% rename from examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py index 24349a44..efd4e313 100755 --- a/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,17 +25,11 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201702') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] + 'PremiumRateService', version='v201711') # Create a statement to select premium rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py b/examples/dfp/v201711/premium_rate_service/update_premium_rates.py similarity index 90% rename from examples/dfp/v201702/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201711/premium_rate_service/update_premium_rates.py index 97cdd2e6..9cb338da 100755 --- a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201711/premium_rate_service/update_premium_rates.py @@ -30,18 +30,14 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201702') + version='v201711') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': premium_rate_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(premium_rate_id)) + .Limit(1)) # Get the premium rate. response = premium_rate_service.getPremiumRatesByStatement( diff --git a/examples/dfp/v201702/product_package_item_service/create_product_package_item.py b/examples/dfp/v201711/product_package_item_service/create_product_package_item.py similarity index 99% rename from examples/dfp/v201702/product_package_item_service/create_product_package_item.py rename to examples/dfp/v201711/product_package_item_service/create_product_package_item.py index 3234b2e3..be418ec4 100755 --- a/examples/dfp/v201702/product_package_item_service/create_product_package_item.py +++ b/examples/dfp/v201711/product_package_item_service/create_product_package_item.py @@ -32,7 +32,7 @@ def main(client): product_package_item_service = client.GetService('ProductPackageItemService', - version='v201702') + version='v201711') product_package_item = { # Set the product from which the product package item is created. diff --git a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py similarity index 97% rename from examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py rename to examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py index a379b9fc..6cabd514 100755 --- a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201702') + 'ProductPackageItemService', version='v201711') # Create a statement to select product package items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py similarity index 86% rename from examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py index 439d98c4..b7d4900f 100755 --- a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,17 +25,11 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201702') - query = 'WHERE productPackageId = :productPackageId' - values = [ - {'key': 'productPackageId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_package_id - }}, - ] + 'ProductPackageItemService', version='v201711') # Create a statement to select product package items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productPackageId = :productPackageId') + .WithBindVariable('productPackageId', product_package_id)) # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/dfp/v201702/product_package_service/create_product_packages.py b/examples/dfp/v201711/product_package_service/create_product_packages.py similarity index 96% rename from examples/dfp/v201702/product_package_service/create_product_packages.py rename to examples/dfp/v201711/product_package_service/create_product_packages.py index 4cd048e2..049ff271 100755 --- a/examples/dfp/v201702/product_package_service/create_product_packages.py +++ b/examples/dfp/v201711/product_package_service/create_product_packages.py @@ -30,7 +30,7 @@ def main(client): product_package_service = client.GetService('ProductPackageService', - version='v201702') + version='v201711') # Create a local product package. product_package = { diff --git a/examples/dfp/v201702/product_package_service/get_active_product_packages.py b/examples/dfp/v201711/product_package_service/get_active_product_packages.py similarity index 86% rename from examples/dfp/v201702/product_package_service/get_active_product_packages.py rename to examples/dfp/v201711/product_package_service/get_active_product_packages.py index 33facad4..b747a2a0 100755 --- a/examples/dfp/v201702/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201711/product_package_service/get_active_product_packages.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'ProductPackageService', version='v201711') # Create a statement to select product packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/dfp/v201702/product_package_service/get_all_product_packages.py b/examples/dfp/v201711/product_package_service/get_all_product_packages.py similarity index 97% rename from examples/dfp/v201702/product_package_service/get_all_product_packages.py rename to examples/dfp/v201711/product_package_service/get_all_product_packages.py index 910cc35a..c1d566cb 100755 --- a/examples/dfp/v201702/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201711/product_package_service/get_all_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201702') + 'ProductPackageService', version='v201711') # Create a statement to select product packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/product_service/__init__.py b/examples/dfp/v201711/product_service/__init__.py similarity index 100% rename from examples/dfp/v201702/product_service/__init__.py rename to examples/dfp/v201711/product_service/__init__.py diff --git a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201711/product_service/create_programmatic_products_for_non_sales_management.py similarity index 94% rename from examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py rename to examples/dfp/v201711/product_service/create_programmatic_products_for_non_sales_management.py index 237453a9..997e7db4 100755 --- a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py +++ b/examples/dfp/v201711/product_service/create_programmatic_products_for_non_sales_management.py @@ -24,8 +24,8 @@ def main(client): - product_service = client.GetService('ProductService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + product_service = client.GetService('ProductService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') product = { # Setting required Marketplace Information. @@ -40,7 +40,7 @@ def main(client): 'rateType': 'CPM', 'lineItemType': 'STANDARD', 'priority': 8, - 'environment': 'BROWSER', + 'environmentType': 'BROWSER', 'rate': { 'currencyCode': 'USD', 'microAmount': '6000000' @@ -61,10 +61,10 @@ def main(client): ], 'builtInTargeting': { 'inventoryTargeting': { - 'adUnitTargeting': { + 'targetedAdUnits': { 'adUnitId': network_service.getCurrentNetwork()[ 'effectiveRootAdUnitId'], - 'includeDescendents': 'true' + 'includeDescendants': 'true' } } }, diff --git a/examples/dfp/v201702/product_service/get_all_products.py b/examples/dfp/v201711/product_service/get_all_products.py similarity index 99% rename from examples/dfp/v201702/product_service/get_all_products.py rename to examples/dfp/v201711/product_service/get_all_products.py index 8dd669b5..5b88012d 100755 --- a/examples/dfp/v201702/product_service/get_all_products.py +++ b/examples/dfp/v201711/product_service/get_all_products.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201702') + product_service = client.GetService('ProductService', version='v201711') # Create a statement to select products. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/product_service/get_products_for_product_template.py b/examples/dfp/v201711/product_service/get_products_for_product_template.py similarity index 86% rename from examples/dfp/v201702/product_service/get_products_for_product_template.py rename to examples/dfp/v201711/product_service/get_products_for_product_template.py index 367db302..42ef9bdf 100755 --- a/examples/dfp/v201702/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201711/product_service/get_products_for_product_template.py @@ -24,18 +24,12 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201702') - - query = 'WHERE productTemplateId = :productTemplateId' - values = [ - {'key': 'productTemplateId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_template_id - }}, - ] + product_service = client.GetService('ProductService', version='v201711') + # Create a statement to select products. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productTemplateId = :productTemplateId') + .WithBindVariable('productTemplateId', product_template_id)) # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201711/product_service/publish_programmatic_products_to_marketplace.py similarity index 90% rename from examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py rename to examples/dfp/v201711/product_service/publish_programmatic_products_to_marketplace.py index 3d9a1c1c..5a94c148 100755 --- a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py +++ b/examples/dfp/v201711/product_service/publish_programmatic_products_to_marketplace.py @@ -27,18 +27,13 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201702') + product_service = client.GetService('ProductService', version='v201711') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) products_published = 0 diff --git a/examples/dfp/v201702/product_service/update_products.py b/examples/dfp/v201711/product_service/update_products.py similarity index 90% rename from examples/dfp/v201702/product_service/update_products.py rename to examples/dfp/v201711/product_service/update_products.py index d645f89e..b1d37737 100755 --- a/examples/dfp/v201702/product_service/update_products.py +++ b/examples/dfp/v201711/product_service/update_products.py @@ -29,18 +29,13 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201702') + product_service = client.GetService('ProductService', version='v201711') # Create statement object to select a single product by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, product_id): else: print 'No products found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/product_template_service/__init__.py b/examples/dfp/v201711/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201702/product_template_service/__init__.py rename to examples/dfp/v201711/product_template_service/__init__.py diff --git a/examples/dfp/v201702/product_template_service/activate_product_templates.py b/examples/dfp/v201711/product_template_service/activate_product_templates.py similarity index 89% rename from examples/dfp/v201702/product_template_service/activate_product_templates.py rename to examples/dfp/v201711/product_template_service/activate_product_templates.py index ffda4dd4..87bae3ca 100755 --- a/examples/dfp/v201702/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201711/product_template_service/activate_product_templates.py @@ -31,18 +31,13 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201711') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) product_templates_activated = 0 diff --git a/examples/dfp/v201702/product_template_service/create_product_templates.py b/examples/dfp/v201711/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201702/product_template_service/create_product_templates.py rename to examples/dfp/v201711/product_template_service/create_product_templates.py index 98ee1982..2f7c2afb 100755 --- a/examples/dfp/v201702/product_template_service/create_product_templates.py +++ b/examples/dfp/v201711/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201711') network_service = client.GetService( - 'NetworkService', version='v201702') + 'NetworkService', version='v201711') # Create a product template. product_template = { diff --git a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py similarity index 96% rename from examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py rename to examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py index 0ef99cf9..f7cc4b99 100755 --- a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201711') network_service = client.GetService( - 'NetworkService', version='v201702') + 'NetworkService', version='v201711') product_template = { # Setting required Marketplace information. diff --git a/examples/dfp/v201702/product_template_service/get_all_product_templates.py b/examples/dfp/v201711/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201702/product_template_service/get_all_product_templates.py rename to examples/dfp/v201711/product_template_service/get_all_product_templates.py index 4f79ceb9..4d7f7680 100755 --- a/examples/dfp/v201702/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201711/product_template_service/get_all_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201711') # Create a statement to select product templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py similarity index 85% rename from examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py index 44b3b3a1..9a6c9fc2 100755 --- a/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') - query = 'WHERE lineItemType = :lineItemType' - values = [ - {'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - }}, - ] + 'ProductTemplateService', version='v201711') # Create a statement to select product templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemType = :lineItemType') + .WithBindVariable('lineItemType', 'SPONSORSHIP')) # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/dfp/v201702/product_template_service/update_product_templates.py b/examples/dfp/v201711/product_template_service/update_product_templates.py similarity index 90% rename from examples/dfp/v201702/product_template_service/update_product_templates.py rename to examples/dfp/v201711/product_template_service/update_product_templates.py index 819a9772..40bc6c41 100755 --- a/examples/dfp/v201702/product_template_service/update_product_templates.py +++ b/examples/dfp/v201711/product_template_service/update_product_templates.py @@ -30,18 +30,14 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201711') # Create a statement to select a single product template by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) # Get product templates by statement. response = product_template_service.getProductTemplatesByStatement( diff --git a/examples/dfp/v201702/proposal_line_item_service/__init__.py b/examples/dfp/v201711/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201702/proposal_line_item_service/__init__.py rename to examples/dfp/v201711/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py similarity index 89% rename from examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py index 8584b71b..3001c92c 100755 --- a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py @@ -31,18 +31,13 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') + 'ProposalLineItemService', version='v201711') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) proposal_line_items_archived = 0 diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 82% rename from examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py index 19ebceab..1654e9aa 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -18,11 +18,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set the ID of the programmatic proposal that the proposal line item will # belong to. @@ -39,13 +40,16 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + 'ProposalLineItemService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') # Get the root ad unit to target. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + # Create a single programmatic proposal line item. proposal_line_item = { # Setting required Marketplace information. @@ -64,27 +68,8 @@ def main(client, proposal_id, product_id, rate_card_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'goal': { 'units': '1000', 'unitType': 'IMPRESSIONS', diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 82% rename from examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 2338f4ca..0f204be9 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -18,11 +18,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -33,8 +34,11 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + 'ProposalLineItemService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) # Get the root ad unit to target. root_ad_unit_id = ( @@ -58,27 +62,8 @@ def main(client, proposal_id, product_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'creativePlaceholders': [{ 'size': { 'width': '300', diff --git a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py similarity index 82% rename from examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py index bc746b66..972bb150 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py @@ -22,11 +22,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -41,8 +42,11 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + 'ProposalLineItemService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) # Get the root ad unit to target. root_ad_unit_id = ( @@ -61,27 +65,8 @@ def main(client, proposal_id, product_id, rate_card_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'deliveryRateType': 'EVENLY', 'creativeRotationType': 'OPTIMIZED', 'billingCap': 'CAPPED_CUMULATIVE', diff --git a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py similarity index 97% rename from examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py index 17ee0df9..9fb0218c 100755 --- a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') + 'ProposalLineItemService', version='v201711') # Create a statement to select proposal line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 86% rename from examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py index f0224ecf..a82722d8 100755 --- a/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,17 +25,11 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') - query = 'WHERE proposalId = :proposalId' - values = [ - {'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - }}, - ] + 'ProposalLineItemService', version='v201711') # Create a statement to select proposal line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('proposalId = :proposalId') + .WithBindVariable('proposalId', proposal_id)) # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py similarity index 89% rename from examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py index 64648a05..930fd72e 100755 --- a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py @@ -31,19 +31,14 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') + 'ProposalLineItemService', version='v201711') # Create statement to select a proposal line item. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) # Get proposal line items by statement. response = proposal_line_item_service.getProposalLineItemsByStatement( diff --git a/examples/dfp/v201702/proposal_service/__init__.py b/examples/dfp/v201711/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201702/proposal_service/__init__.py rename to examples/dfp/v201711/proposal_service/__init__.py diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201711/proposal_service/create_programmatic_proposals.py similarity index 98% rename from examples/dfp/v201702/proposal_service/create_programmatic_proposals.py rename to examples/dfp/v201711/proposal_service/create_programmatic_proposals.py index 5b009a95..861f71b0 100755 --- a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201711/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 99% rename from examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 2173f106..fdef1830 100755 --- a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201702/proposal_service/create_proposals.py b/examples/dfp/v201711/proposal_service/create_proposals.py similarity index 99% rename from examples/dfp/v201702/proposal_service/create_proposals.py rename to examples/dfp/v201711/proposal_service/create_proposals.py index c8b43bcf..0a800e90 100755 --- a/examples/dfp/v201702/proposal_service/create_proposals.py +++ b/examples/dfp/v201711/proposal_service/create_proposals.py @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201702/proposal_service/get_all_proposals.py b/examples/dfp/v201711/proposal_service/get_all_proposals.py similarity index 99% rename from examples/dfp/v201702/proposal_service/get_all_proposals.py rename to examples/dfp/v201711/proposal_service/get_all_proposals.py index 53ad307c..10699516 100755 --- a/examples/dfp/v201702/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201711/proposal_service/get_all_proposals.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') # Create a statement to select proposals. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py b/examples/dfp/v201711/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/dfp/v201702/proposal_service/get_marketplace_comments.py rename to examples/dfp/v201711/proposal_service/get_marketplace_comments.py index b5d81c05..08ae7a05 100755 --- a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201711/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201702') + 'ProposalService', version='v201711') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py similarity index 87% rename from examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py rename to examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py index 33041f4a..dcf4fca4 100755 --- a/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - }}, - ] + proposal_service = client.GetService('ProposalService', version='v201711') # Create a statement to select proposals. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'PENDING_APPROVAL')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py similarity index 89% rename from examples/dfp/v201702/proposal_service/request_buyers_acceptance.py rename to examples/dfp/v201711/proposal_service/request_buyers_acceptance.py index 89f3468a..502d591a 100755 --- a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py @@ -26,20 +26,12 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo programmatic proposals were pushed to Marketplace.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py similarity index 88% rename from examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py index f87cf2eb..ecb8c5d1 100755 --- a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py @@ -28,20 +28,12 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo proposals were approved.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/proposal_service/update_proposals.py b/examples/dfp/v201711/proposal_service/update_proposals.py similarity index 89% rename from examples/dfp/v201702/proposal_service/update_proposals.py rename to examples/dfp/v201711/proposal_service/update_proposals.py index 41020d8d..29339cca 100755 --- a/examples/dfp/v201702/proposal_service/update_proposals.py +++ b/examples/dfp/v201711/proposal_service/update_proposals.py @@ -28,19 +28,14 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', long(proposal_id)) + .Limit(1)) # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, proposal_id): else: print 'No proposals found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/publisher_query_language_service/__init__.py b/examples/dfp/v201711/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201702/publisher_query_language_service/__init__.py rename to examples/dfp/v201711/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py index 6983c467..6f4c30fa 100755 --- a/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201711') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py b/examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py new file mode 100755 index 00000000..9c715c66 --- /dev/null +++ b/examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 browsers available to target from the Browser table. + +Other tables include 'Bandwidth_Group', 'Browser_Language', +'Device_Capability', 'Operating_System', etc... + +A full list of available criteria tables can be found at +https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService +""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201711') + + with tempfile.NamedTemporaryFile( + prefix='browser_data_', + suffix='.csv', mode='w', delete=False) as browser_data_file: + + browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion ' + 'FROM Browser ' + 'ORDER BY BrowserName ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + browser_pql_query, browser_data_file) + + print 'Saved browser data to... %s' % browser_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py index bc5ed6a9..1373e34c 100755 --- a/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201702') + data_downloader = client.GetDataDownloader(version='v201711') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py new file mode 100755 index 00000000..ee80ecce --- /dev/null +++ b/examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 downloads geo targeting constants using PQL.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the type of geo target to query for. +GEO_TARGET_TYPE = 'City' + + +def main(client, geo_target_type): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201711') + + with tempfile.NamedTemporaryFile( + prefix='geo_data_', + suffix='.csv', mode='w', delete=False) as geo_data_file: + + geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' + 'CountryCode ' + 'FROM Geo_Target ' + 'WHERE Type = :type AND Targetable = true ' + 'ORDER BY CountryCode ASC, Name ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + geo_pql_query, geo_data_file, {'type': geo_target_type}) + + print 'Saved geo data to... %s' % geo_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, GEO_TARGET_TYPE) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py new file mode 100755 index 00000000..baba6a1d --- /dev/null +++ b/examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 fetches line items from the pql table with a LIKE clause.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201711') + + with tempfile.NamedTemporaryFile( + prefix='line_items_', + suffix='.csv', mode='w', delete=False) as line_items_file: + + line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item " + "WHERE Name LIKE 'line item%' " + "ORDER BY Id ASC") + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + line_items_pql_query, line_items_file) + + print 'Saved line items to... %s' % line_items_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py similarity index 66% rename from examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py rename to examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py index 76c9f061..41eb34c6 100755 --- a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py +++ b/examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py @@ -31,52 +31,23 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201702') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201711') - end_date = date.today() + end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) - initial_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE ChangeDateTime > :startDateTime ' - 'AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - pagination_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE Id < :id ' - 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - values = [ - { - 'key': 'startDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day - } - } - } - }, - { - 'key': 'endDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day - } - } - } - } - ] - - statement = dfp.FilterStatement(initial_query, values) + initial_query = ('ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime') + pagination_query = 'Id < :id AND ' + initial_query + + statement = (dfp.StatementBuilder() + .Select(('Id, ChangeDateTime, EntityId, EntityType, ' + 'Operation, UserId')) + .From('Change_History') + .Where(initial_query) + .OrderBy('ChangeDateTime', ascending=False) + .WithBindVariable('startDateTime', start_date) + .WithBindVariable('endDateTime', end_date)) + keep_iterating = True i = 0 total_rows = [] @@ -94,8 +65,11 @@ def main(client): last_row = rows[-1] last_id = last_row['values'][0]['value'] i += 1 - statement = UpdateFilterStatement( - statement, pagination_query, values, last_id) + + # Update the statement using the earliest row in the previous result. + statement.Where(pagination_query) + statement.WithBindVariable('id', last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' % (i, rows_length, last_id)) @@ -109,34 +83,6 @@ def main(client): print ConvertValueForCsv(row) -def UpdateFilterStatement(statement, query, values, last_id): - """Updates the FilterStatement in order to page through results. - - Args: - statement: an instantiated FilterStatement. - query: a str query that will be used to update the FilterStatement. - values: a list of bind variables to be updated. - last_id: a str representing the earliest change ID in a result set. - - Returns: - FilterStatement the updated statement. - """ - # Use the earliest change ID in the result set to page. - updated_values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_id - } - }] - updated_values.extend(values) - - statement.where_clause = query - statement.values = updated_values - - return statement - - def ConvertValueForCsv(pql_value): """Sanitizes a field value from a Value object to a CSV suitable format. diff --git a/examples/dfp/v201702/rate_card_service/__init__.py b/examples/dfp/v201711/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201702/rate_card_service/__init__.py rename to examples/dfp/v201711/rate_card_service/__init__.py diff --git a/examples/dfp/v201702/rate_card_service/create_rate_cards.py b/examples/dfp/v201711/rate_card_service/create_rate_cards.py similarity index 99% rename from examples/dfp/v201702/rate_card_service/create_rate_cards.py rename to examples/dfp/v201711/rate_card_service/create_rate_cards.py index e75ee8bd..d7acfcf9 100755 --- a/examples/dfp/v201702/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201711/rate_card_service/create_rate_cards.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201702') + rate_card_service = client.GetService('RateCardService', version='v201711') # Create a rate card. rate_card = { diff --git a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py similarity index 99% rename from examples/dfp/v201702/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201711/rate_card_service/get_all_rate_cards.py index a3753055..2c0d78e4 100755 --- a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201702') + rate_card_service = client.GetService('RateCardService', version='v201711') # Create a statement to select rate cards. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py similarity index 87% rename from examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py rename to examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py index c300b3b9..c3c213bb 100755 --- a/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201702') - query = 'WHERE forMarketplace = :forMarketplace' - values = [ - {'key': 'forMarketplace', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + rate_card_service = client.GetService('RateCardService', version='v201711') # Create a statement to select rate cards. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('forMarketplace = :forMarketplace') + .WithBindVariable('forMarketplace', True)) # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 97% rename from examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index ad0ccee4..d669cb83 100755 --- a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201702')) + 'ReconciliationLineItemReportService', version='v201711')) # Create a statement to select reconciliation line item reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 97% rename from examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 1f9b1e48..bdd94b5a 100755 --- a/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201702')) + 'ReconciliationLineItemReportService', version='v201711')) # Create a statement to select a reconciliation line item report. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 60c73c91..7e298979 100755 --- a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,17 +25,12 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201702') - query = 'WHERE reconciliationReportId = :reconciliationReportId' - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - ] + 'ReconciliationOrderReportService', version='v201711') # Create a statement to select reconciliation order reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('reconciliationReportId = :reconciliationReportId') + .WithBindVariable('reconciliationReportId', + reconciliation_report_id)) # Retrieve a small amount of reconciliation order reports at a time, paging # through until all reconciliation order reports have been retrieved. diff --git a/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 97% rename from examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 35d94c91..4e3b4a82 100755 --- a/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201702')) + 'ReconciliationOrderReportService', version='v201711')) # Create a statement to select reconciliation order reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 21daadd3..9b414ea1 100755 --- a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -27,18 +27,14 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201702') - query = ('WHERE reconciliationReportId = %s AND ' - 'lineItemId != :lineItemId') % reconciliation_report_id - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - } - }] + 'ReconciliationReportRowService', version='v201711') + # Create a statement to select reconciliation report rows. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reportId ' + 'AND lineItemId != :lineItemId')) + .WithBindVariable('lineItemId', 0) + .WithBindVariable('reportId', long(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. diff --git a/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 97% rename from examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py index fff5f766..99b28783 100755 --- a/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201702')) + 'ReconciliationReportRowService', version='v201711')) # Create a statement to select reconciliation report rows. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 97% rename from examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py index 35287882..15825fe0 100755 --- a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201702') + 'ReconciliationReportService', version='v201711') # Create a statement to select reconciliation reports. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 86% rename from examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 64b14308..c391ab1b 100755 --- a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,21 +26,15 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201702') + 'ReconciliationReportService', version='v201711') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) - query = 'WHERE startDate = :startDate' - values = [ - {'key': 'startDate', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_month.strftime('%Y-%m-01') - }}, - ] # Create a statement to select reconciliation reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('startDate = :startDate') + .WithBindVariable('startDate', last_month)) # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. diff --git a/examples/dfp/v201702/report_service/__init__.py b/examples/dfp/v201711/report_service/__init__.py similarity index 100% rename from examples/dfp/v201702/report_service/__init__.py rename to examples/dfp/v201711/report_service/__init__.py diff --git a/examples/dfp/v201702/report_service/run_delivery_report.py b/examples/dfp/v201711/report_service/run_delivery_report.py similarity index 88% rename from examples/dfp/v201702/report_service/run_delivery_report.py rename to examples/dfp/v201711/report_service/run_delivery_report.py index 74fdb3f3..3bbc7c8f 100755 --- a/examples/dfp/v201702/report_service/run_delivery_report.py +++ b/examples/dfp/v201711/report_service/run_delivery_report.py @@ -32,15 +32,11 @@ def main(client, order_id): # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - filter_statement = {'query': 'WHERE ORDER_ID = :id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('ORDER_ID = :id') + .WithBindVariable('id', long(order_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Set the start and end dates of the report to run (past 8 days). end_date = datetime.now().date() @@ -52,7 +48,7 @@ def main(client, order_id): 'dimensions': ['ORDER_ID', 'ORDER_NAME'], 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', 'ORDER_END_DATE_TIME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], @@ -63,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201711') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201702/report_service/run_inventory_report.py b/examples/dfp/v201711/report_service/run_inventory_report.py similarity index 86% rename from examples/dfp/v201702/report_service/run_inventory_report.py rename to examples/dfp/v201711/report_service/run_inventory_report.py index 01994fe7..2bffebeb 100755 --- a/examples/dfp/v201702/report_service/run_inventory_report.py +++ b/examples/dfp/v201711/report_service/run_inventory_report.py @@ -25,24 +25,20 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201702') + network_service = client.GetService('NetworkService', version='v201711') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201711') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - values = [{ - 'key': 'parent_ad_unit_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': root_ad_unit_id - } - }] - filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') + .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Create report job. report_job = { @@ -55,7 +51,7 @@ def main(client): 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', - 'statement': filter_statement + 'statement': statement.ToStatement() } } diff --git a/examples/dfp/v201702/report_service/run_reach_report.py b/examples/dfp/v201711/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201702/report_service/run_reach_report.py rename to examples/dfp/v201711/report_service/run_reach_report.py index 10e06150..53b8ab8f 100755 --- a/examples/dfp/v201702/report_service/run_reach_report.py +++ b/examples/dfp/v201711/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201711') # Create report job. report_job = { diff --git a/examples/dfp/v201711/report_service/run_report_and_create_match_table.py b/examples/dfp/v201711/report_service/run_report_and_create_match_table.py new file mode 100755 index 00000000..777304d0 --- /dev/null +++ b/examples/dfp/v201711/report_service/run_report_and_create_match_table.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Runs a report for LineItems with additional data from a PQL table. + +Fetches a basic report over a network's LineItems and then adds some +extra columns which might be useful for future analysis, such as +LineItemType, from the PQL Line_Item table, creating a match table. +""" + +from datetime import date +from datetime import timedelta +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + +try: + import pandas +except ImportError: + raise ImportError('This example requires the pandas library to be installed.') + + +def main(client): + # Set the start and end dates of the report to run (past 8 days). + end_date = date.today() + start_date = end_date - timedelta(days=8) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': start_date, + 'endDate': end_date + } + } + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201711') + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + with tempfile.NamedTemporaryFile( + suffix='.csv.gz', mode='wb', delete=False) as report_file: + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, 'CSV_DUMP', report_file) + + # Create a PQL query to fetch the line item data + line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem') + + # Download the response from PQL select statement + line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) + + # Use pandas to join the two csv files into a match table + report = pandas.read_csv(report_file.name) + line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0]) + merged_result = pandas.merge(report, line_items, + left_on='Dimension.LINE_ITEM_ID', right_on='id') + merged_result.to_csv('~/complete_line_items_report.csv', index=False) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py b/examples/dfp/v201711/report_service/run_report_with_custom_fields.py similarity index 85% rename from examples/dfp/v201702/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201711/report_service/run_report_with_custom_fields.py index 5ad2f680..c302079c 100755 --- a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201711/report_service/run_report_with_custom_fields.py @@ -28,22 +28,14 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201711') # Filter for line items of a given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE orderId = :orderId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId') + .WithBindVariable('orderId', long(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -62,14 +54,16 @@ def main(client, order_id): else: break - # Create statement object to filter for an order. - filter_statement = {'query': query, 'values': values} + # Modify statement for reports + statement.limit = None + statement.offset = None + statement.Where('ORDER_ID = :orderId') # Create report job. report_job = { 'reportQuery': { 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', 'customFieldIds': list(custom_field_ids) diff --git a/examples/dfp/v201702/report_service/run_sales_report.py b/examples/dfp/v201711/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201702/report_service/run_sales_report.py rename to examples/dfp/v201711/report_service/run_sales_report.py index 5aab075c..e5b5663d 100755 --- a/examples/dfp/v201702/report_service/run_sales_report.py +++ b/examples/dfp/v201711/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201711') # Create report job. report_job = { diff --git a/examples/dfp/v201702/report_service/run_saved_query.py b/examples/dfp/v201711/report_service/run_saved_query.py similarity index 89% rename from examples/dfp/v201702/report_service/run_saved_query.py rename to examples/dfp/v201711/report_service/run_saved_query.py index 7f3ccad5..16ce73f3 100755 --- a/examples/dfp/v201702/report_service/run_saved_query.py +++ b/examples/dfp/v201711/report_service/run_saved_query.py @@ -28,21 +28,16 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201702') + report_service = client.GetService('ReportService', version='v201711') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201711') # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': saved_query_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(saved_query_id)) + .Limit(1)) response = report_service.getSavedQueriesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201702/suggested_ad_unit_service/__init__.py b/examples/dfp/v201711/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201702/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201711/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py index cdf09c6f..9babe2de 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201702') + 'SuggestedAdUnitService', version='v201711') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py index cc211cfe..eecffd62 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201702') + 'SuggestedAdUnitService', version='v201711') # Create a statement to select suggested ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 86% rename from examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index de26bdf9..175f870c 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,17 +25,11 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201702') - query = 'WHERE numRequests >= :numRequests' - values = [ - {'key': 'numRequests', - 'value': { - 'xsi_type': 'TextValue', - 'value': num_requests - }}, - ] + 'SuggestedAdUnitService', version='v201711') # Create a statement to select suggested ad units. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests >= :numRequests') + .WithBindVariable('numRequests', long(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/dfp/v201702/team_service/__init__.py b/examples/dfp/v201711/team_service/__init__.py similarity index 100% rename from examples/dfp/v201702/team_service/__init__.py rename to examples/dfp/v201711/team_service/__init__.py diff --git a/examples/dfp/v201702/team_service/create_teams.py b/examples/dfp/v201711/team_service/create_teams.py similarity index 99% rename from examples/dfp/v201702/team_service/create_teams.py rename to examples/dfp/v201711/team_service/create_teams.py index f76ae2db..df551d17 100755 --- a/examples/dfp/v201702/team_service/create_teams.py +++ b/examples/dfp/v201711/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201702') + team_service = client.GetService('TeamService', version='v201711') # Create team objects. teams = [] diff --git a/examples/dfp/v201702/team_service/get_all_teams.py b/examples/dfp/v201711/team_service/get_all_teams.py similarity index 99% rename from examples/dfp/v201702/team_service/get_all_teams.py rename to examples/dfp/v201711/team_service/get_all_teams.py index 03fdf947..8a639323 100755 --- a/examples/dfp/v201702/team_service/get_all_teams.py +++ b/examples/dfp/v201711/team_service/get_all_teams.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201702') + team_service = client.GetService('TeamService', version='v201711') # Create a statement to select teams. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/team_service/update_teams.py b/examples/dfp/v201711/team_service/update_teams.py similarity index 90% rename from examples/dfp/v201702/team_service/update_teams.py rename to examples/dfp/v201711/team_service/update_teams.py index 7a3b8a94..2f10953a 100755 --- a/examples/dfp/v201702/team_service/update_teams.py +++ b/examples/dfp/v201711/team_service/update_teams.py @@ -34,18 +34,12 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201702') + team_service = client.GetService('TeamService', version='v201711') # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :teamId') + .WithBindVariable('teamId', long(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -67,6 +61,7 @@ def main(client, team_id): else: print 'No teams found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_service/__init__.py b/examples/dfp/v201711/user_service/__init__.py similarity index 100% rename from examples/dfp/v201702/user_service/__init__.py rename to examples/dfp/v201711/user_service/__init__.py diff --git a/examples/dfp/v201702/user_service/create_users.py b/examples/dfp/v201711/user_service/create_users.py similarity index 99% rename from examples/dfp/v201702/user_service/create_users.py rename to examples/dfp/v201711/user_service/create_users.py index f375d01c..cbdf701b 100755 --- a/examples/dfp/v201702/user_service/create_users.py +++ b/examples/dfp/v201711/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201711') # Create user objects. users = [ diff --git a/examples/dfp/v201702/user_service/deactivate_users.py b/examples/dfp/v201711/user_service/deactivate_users.py similarity index 89% rename from examples/dfp/v201702/user_service/deactivate_users.py rename to examples/dfp/v201711/user_service/deactivate_users.py index 16c07b35..60cabd9a 100755 --- a/examples/dfp/v201702/user_service/deactivate_users.py +++ b/examples/dfp/v201711/user_service/deactivate_users.py @@ -30,20 +30,12 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201711') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -66,6 +58,7 @@ def main(client, user_id): else: print 'No users were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_service/get_all_roles.py b/examples/dfp/v201711/user_service/get_all_roles.py similarity index 100% rename from examples/dfp/v201702/user_service/get_all_roles.py rename to examples/dfp/v201711/user_service/get_all_roles.py diff --git a/examples/dfp/v201702/user_service/get_all_users.py b/examples/dfp/v201711/user_service/get_all_users.py similarity index 99% rename from examples/dfp/v201702/user_service/get_all_users.py rename to examples/dfp/v201711/user_service/get_all_users.py index e35e600b..0c57a8d7 100755 --- a/examples/dfp/v201702/user_service/get_all_users.py +++ b/examples/dfp/v201711/user_service/get_all_users.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201711') # Create a statement to select users. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/user_service/get_current_user.py b/examples/dfp/v201711/user_service/get_current_user.py similarity index 99% rename from examples/dfp/v201702/user_service/get_current_user.py rename to examples/dfp/v201711/user_service/get_current_user.py index 56e5931b..c1f43169 100755 --- a/examples/dfp/v201702/user_service/get_current_user.py +++ b/examples/dfp/v201711/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201711') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201702/user_service/get_user_by_email_address.py b/examples/dfp/v201711/user_service/get_user_by_email_address.py similarity index 88% rename from examples/dfp/v201702/user_service/get_user_by_email_address.py rename to examples/dfp/v201711/user_service/get_user_by_email_address.py index 5e661c78..2d3ed8c8 100755 --- a/examples/dfp/v201702/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201711/user_service/get_user_by_email_address.py @@ -24,17 +24,11 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') - query = 'WHERE email = :email' - values = [ - {'key': 'email', - 'value': { - 'xsi_type': 'TextValue', - 'value': email_address - }}, - ] + user_service = client.GetService('UserService', version='v201711') # Create a statement to select users. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('email = :email') + .WithBindVariable('email', email_address)) # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/dfp/v201702/user_service/update_users.py b/examples/dfp/v201711/user_service/update_users.py similarity index 86% rename from examples/dfp/v201702/user_service/update_users.py rename to examples/dfp/v201711/user_service/update_users.py index 07940545..70a566c0 100755 --- a/examples/dfp/v201702/user_service/update_users.py +++ b/examples/dfp/v201711/user_service/update_users.py @@ -28,20 +28,12 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201711') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -59,6 +51,7 @@ def main(client, user_id): else: print 'No users found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_team_association_service/__init__.py b/examples/dfp/v201711/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201702/user_team_association_service/__init__.py rename to examples/dfp/v201711/user_team_association_service/__init__.py diff --git a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201702/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201711/user_team_association_service/create_user_team_associations.py index c882a441..5a8ee9cd 100755 --- a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') + 'UserTeamAssociationService', version='v201711') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py similarity index 87% rename from examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py index c971f0d8..b0dd9259 100755 --- a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py @@ -35,20 +35,12 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') + 'UserTeamAssociationService', version='v201711') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -62,10 +54,14 @@ def main(client, user_id): print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) + # Action doesn't require limit/offset + statement.limit = None + statement.offset = None + # Perform action. result = user_team_association_service.performUserTeamAssociationAction( {'xsi_type': 'DeleteUserTeamAssociations'}, - {'query': query, 'values': values}) + statement.ToStatement()) # Display results. if result and int(result['numChanges']) > 0: @@ -74,6 +70,7 @@ def main(client, user_id): else: print 'No user team associations were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py similarity index 97% rename from examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py index 6343bbae..14783340 100755 --- a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') + 'UserTeamAssociationService', version='v201711') # Create a statement to select user team associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py similarity index 87% rename from examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py index 1af444b9..c09c240c 100755 --- a/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py @@ -25,17 +25,11 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') - query = 'WHERE userId = :userId' - values = [ - {'key': 'userId', - 'value': { - 'xsi_type': 'TextValue', - 'value': user_id - }}, - ] + 'UserTeamAssociationService', version='v201711') # Create a statement to select user team associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py similarity index 89% rename from examples/dfp/v201702/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201711/user_team_association_service/update_user_team_associations.py index 2b227542..43bc0e8d 100755 --- a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py @@ -37,20 +37,12 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') + 'UserTeamAssociationService', version='v201711') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -79,6 +71,7 @@ def main(client, user_id): else: print 'No user team associations found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/workflow_request_service/__init__.py b/examples/dfp/v201711/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201702/workflow_request_service/__init__.py rename to examples/dfp/v201711/workflow_request_service/__init__.py diff --git a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py similarity index 76% rename from examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py index f6a87a54..0b176750 100755 --- a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py @@ -31,37 +31,15 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201702') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') + version='v201711') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) workflow_approval_requests_approved = 0 # Get workflow approval requests by statement. diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py similarity index 87% rename from examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py rename to examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py index 5894de86..5485408c 100755 --- a/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py @@ -26,17 +26,11 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - }}, - ] + 'WorkflowRequestService', version='v201711') # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py similarity index 86% rename from examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py index 162b64ff..f098692f 100755 --- a/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,17 +26,11 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - }}, - ] + 'WorkflowRequestService', version='v201711') # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 78% rename from examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py index fbbb267d..35624bcf 100755 --- a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,37 +31,15 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201702') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') + version='v201711') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) workflow_external_condition_requests_triggered = 0 # Get workflow external condition requests by statement. diff --git a/googleads/adwords.py b/googleads/adwords.py index c5b930ce..84db6f5f 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -15,6 +15,7 @@ """Client library for the AdWords API.""" from collections import namedtuple +import datetime import io import logging import os @@ -282,8 +283,8 @@ class AdWordsClient(googleads.common.CommonClient): # AdWords. _OPTIONAL_INIT_VALUES = ( 'validate_only', 'partial_failure', 'client_customer_id', 'user_agent', - 'report_downloader_headers', - googleads.common.ENABLE_COMPRESSION_KEY) + 'report_downloader_headers', + googleads.common.ENABLE_COMPRESSION_KEY) # The format of SOAP service WSDLs. A server, namespace, version, and service # name need to be formatted in. @@ -453,7 +454,8 @@ def GetService(self, service_name, version=None, server=None): **kwargs) return googleads.common.SudsServiceProxy( - client, _AdWordsHeaderHandler(self, version, self.enable_compression)) + client, _AdWordsHeaderHandler(self, version, self.enable_compression), + packer=_AdWordsPacker) def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -623,6 +625,26 @@ def GetReportDownloadHeaders(self, **kwargs): return headers +class _AdWordsPacker(googleads.common.SudsPacker): + """A utility applying customized packing logic for AdWords.""" + + @classmethod + def Pack(cls, obj): + """Pack the given object using AdWords-specific logic. + + Args: + obj: an object to be packed for suds using AdWords-specific logic, if + applicable. + + Returns: + The given object packed with AdWords-specific logic for suds, if + applicable. Otherwise, returns the given object unmodified. + """ + if isinstance(obj, ServiceQuery): + return str(obj) + return obj + + @googleads.common.RegisterUtility('BatchJobHelper') class BatchJobHelper(object): """A utility that simplifies working with the BatchJobService.""" @@ -894,7 +916,7 @@ def _GenerateOperationsXML(self, operations): Raises: GoogleAdsValueError: if no xsi_type is specified for the operations. """ - # Verify that all operations included specify an xsi_type. + # Verify that all operations included specify an xsi_type. if operations: if any('xsi_type' not in operation for operation in operations): raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( @@ -1529,8 +1551,8 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, The report contents will be written to the given output. Args: - query: A string containing the query which specifies the data you want - your report to include. + query: A string or ReportQuery object containing the query which + specifies the data you want your report to include. file_format: A string representing the output format for your report. Acceptable values can be found in our API documentation: https://developers.google.com/adwords/api/docs/guides/reporting @@ -1755,7 +1777,8 @@ def _SerializeAwql(self, query, file_format): """Serializes an AWQL query and file format for transport. Args: - query: A string representing the AWQL query used in the report. + query: A string or ReportQuery object representing the AWQL query used in + the report. file_format: A string representing the file format of the generated report. @@ -1763,7 +1786,7 @@ def _SerializeAwql(self, query, file_format): The given query and format URL encoded into the format needed for an AdWords report request as a string. This is intended to be a POST body. """ - return urllib.urlencode({'__fmt': file_format, '__rdquery': query}) + return urllib.urlencode({'__fmt': file_format, '__rdquery': str(query)}) def _SerializeReportDefinition(self, report_definition): """Serializes a report definition for transport. @@ -1808,3 +1831,713 @@ def _ExtractError(self, error): pass return googleads.errors.AdWordsReportError( error.code, error, content) + + +class _QueryBuilder(object): + """A query builder for building AWQL (AdWords Query Language) queries.""" + + def __init__(self, query_builder=None): + """Creates the query builder with the optional specified query builder. + + This class shouldn't be instantiated directly or extended. Use + ReportQueryBuilder if you want to create a query for reporting or + ServiceQueryBuilder if you want to create a query for services. + + Args: + query_builder: An optional query builder whose properties will be copied + over to this instance. + + Returns: + The query builder. + + Raises: + GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder + type. + """ + if query_builder is None: + self.where_builders = [] + else: + try: + self.where_builders = list(query_builder.where_builders) + except (AttributeError, TypeError): + raise googleads.errors.GoogleAdsValueError( + 'The passed query builder should be of the QueryBuilder type.') + + def Select(self, *fields): + """Sets a provided list of fields as selected fields for the query. + + Args: + *fields: The specified list of fields to be added to a SELECT clause. + + Returns: + This query builder. + """ + raise NotImplementedError('You must subclass _QueryBuilder.') + + def Where(self, field): + """Creates a WHERE builder using a provided field. + + Args: + field: the field to be added as an argument in the WHERE clause. + + Returns: + The created WHERE builder. + """ + where_builder = _WhereBuilder(self, field) + self.where_builders.append(where_builder) + return where_builder + + +class _WhereBuilder(object): + """A WHERE builder for building a WHERE clause in AWQL queries.""" + + def __init__(self, query_builder, field): + """Creates the WHERE builder with specified query builder and field. + + This class should be instantiated through _QueryBuilder.Where. Don't call + this constructor directly. + + Args: + query_builder: The query builder that this WHERE builder links to. + field: The field to be used in the WHERE condition. + + Returns: + The WHERE builder. + """ + self._field = field + self._query_builder = query_builder + self._awql = None + + def EqualTo(self, value): + """Sets the type of the WHERE clause as "equal to". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '=') + return self._query_builder + + def NotEqualTo(self, value): + """Sets the type of the WHERE clause as "not equal to". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '!=') + return self._query_builder + + def GreaterThan(self, value): + """Sets the type of the WHERE clause as "greater than". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '>') + return self._query_builder + + def GreaterThanOrEqualTo(self, value): + """Sets the type of the WHERE clause as "greater than or equal to". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '>=') + return self._query_builder + + def LessThan(self, value): + """Sets the type of the WHERE clause as "less than". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '<') + return self._query_builder + + def LessThanOrEqualTo(self, value): + """Sets the type of the WHERE clause as "less than or equal to. + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '<=') + return self._query_builder + + def StartsWith(self, value): + """Sets the type of the WHERE clause as "starts with". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, 'STARTS_WITH') + return self._query_builder + + def StartsWithIgnoreCase(self, value): + """Sets the type of the WHERE clause as "starts with ignore case". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, + 'STARTS_WITH_IGNORE_CASE') + return self._query_builder + + def Contains(self, value): + """Sets the type of the WHERE clause as "contains". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, 'CONTAINS') + return self._query_builder + + def ContainsIgnoreCase(self, value): + """Sets the type of the WHERE clause as "contains ignore case". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, 'CONTAINS_IGNORE_CASE') + return self._query_builder + + def DoesNotContain(self, value): + """Sets the type of the WHERE clause as "does not contain". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, 'DOES_NOT_CONTAIN') + return self._query_builder + + def DoesNotContainIgnoreCase(self, value): + """Sets the type of the WHERE clause as "doesn not contain ignore case". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition( + value, 'DOES_NOT_CONTAIN_IGNORE_CASE') + return self._query_builder + + def In(self, *values): + """Sets the type of the WHERE clause as "in". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'IN') + return self._query_builder + + def NotIn(self, *values): + """Sets the type of the WHERE clause as "in". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'NOT_IN') + return self._query_builder + + def ContainsAny(self, *values): + """Sets the type of the WHERE clause as "contains any". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ANY') + return self._query_builder + + def ContainsNone(self, *values): + """Sets the type of the WHERE clause as "contains none". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_NONE') + return self._query_builder + + def ContainsAll(self, *values): + """Sets the type of the WHERE clause as "contains all". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ALL') + return self._query_builder + + def Build(self): + """Builds the WHERE clause by returning the stored AWQL. + + Returns: + The resulting WHERE clause in AWQL format. + """ + return self._awql + + def _CreateSingleValueCondition(self, value, operator): + """Creates a single-value condition with the provided value and operator.""" + if isinstance(value, str) or isinstance(value, unicode): + value = '"%s"' % value + return '%s %s %s' % (self._field, operator, value) + + def _CreateMultipleValuesCondition(self, values, operator): + """Creates a condition with the provided list of values and operator.""" + values = ['"%s"' % value if isinstance(value, str) or + isinstance(value, unicode) else str(value) for value in values] + return '%s %s [%s]' % (self._field, operator, ', '.join(values)) + + +@googleads.common.RegisterUtility('ReportQueryBuilder') +class ReportQueryBuilder(_QueryBuilder): + """A query builder for building AWQL queries for reporting.""" + + def __init__(self, query_builder=None): + """Creates the report query builder with the optionally specified builder. + + Creates the report query builder by initializing all attributes including + the report name, time range, start and end date. If the optional query + builder are specified, copy all its attributes to this instance. + + Args: + query_builder: An optional query builder whose attributes will be copied + over to this instance. + + Returns: + This report query builder. + + Raises: + GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder + type. + """ + _QueryBuilder.__init__(self, query_builder) + if query_builder is None: + self.select = None + self.from_report = None + self.date_range = None + self.start_date = None + self.end_date = None + else: + try: + self.select = list(query_builder.select) + self.from_report = query_builder.from_report + self.date_range = query_builder.date_range + self.start_date = query_builder.start_date + self.end_date = query_builder.end_date + except (AttributeError, TypeError): + raise googleads.errors.GoogleAdsValueError( + 'The passed query builder should be of ReportQueryBuilder type.') + + def Select(self, *fields): + """Sets a provided list of fields as selected fields for the query. + + Subsequent calls to this method overwrite the entire set of selected fields + with the new one. + + Args: + *fields: The specified list of fields to be added to a SELECT clause. + + Returns: + This report query builder. + """ + self.select = list(fields) + return self + + def From(self, report_name): + """Sets a provided report name as the argument to FROM clause. + + Args: + report_name: The specified report name. + + Returns: + This report query builder. + """ + self.from_report = report_name + return self + + def During(self, date_range=None, start_date=None, end_date=None): + """Sets arguments for the DURING clause of the query. + + Sets arguments for the DURING clause using the provided date range or start + and end dates. Only the date range or start and end date should be + specified. If both are supplied, an error will be thrown. A valid date range + string can be found at + https://developers.google.com/adwords/api/docs/guides/reporting#date_ranges. + Start and end dates should be in 'YYYYMMDD' format. + + Args: + date_range: The specified date range string, e.g., YESTERDAY. + start_date: The start date string in 'YYYYMMDD' format or an instance of + datetime.date. + end_date: The end date string in 'YYYYMMDD' format or an instance of + datetime.date. + + Returns: + This report query builder. + + Raises: + ValueError: If all the arguments are None or both date_range and start + and end dates have values or if start_date has value but end_date + doesn't (and vice versa). + """ + if date_range is None and (start_date is None or end_date is None): + raise ValueError( + 'Either date_range or both start_date and end_date must not be None.') + if date_range is not None and (start_date is not None + or end_date is not None): + raise ValueError( + 'If date_range is not None, start_date and end_date must be None ' + '(and vice versa).') + self.date_range = date_range + self.start_date = start_date + self.end_date = end_date + return self + + def Build(self): + """Builds a ReportQuery object containing the created AWQL query. + + Returns: + The created ReportQuery object. + + Raises: + ValueError: If the selected fields or report name is not specified. + """ + if self.select is None: + raise ValueError('Must use Select() to specify SELECT clause for valid' + ' AWQL first.') + if self.from_report is None: + raise ValueError('Must use From() to specify FROM clause for valid AWQL' + ' first.') + + parts = ['SELECT ', (', '.join(self.select))] + parts.extend([' FROM ', self.from_report]) + where_clause = (' WHERE %s' % ' AND '.join([builder.Build() for builder + in self.where_builders]) + if self.where_builders else '') + parts += where_clause + + if self.date_range: + parts.extend([' DURING ', self.date_range]) + elif self._start_date and self._end_date: + parts.extend([' DURING ', '%s,%s' % (self._start_date, self._end_date)]) + awql = ''.join(parts) + + return ReportQuery(awql) + + @property + def start_date(self): + """Gets the start date of the query.""" + return self._start_date + + @start_date.setter + def start_date(self, start_date): + """Sets the start date of the query to the provided value.""" + if isinstance(start_date, datetime.date): + self._start_date = '{:%Y%m%d}'.format(start_date) + else: + self._start_date = start_date + + @property + def end_date(self): + """Gets the end date of the query.""" + return self._end_date + + @end_date.setter + def end_date(self, end_date): + """Sets the end date of the query to the provided value.""" + if isinstance(end_date, datetime.date): + self._end_date = '{:%Y%m%d}'.format(end_date) + else: + self._end_date = end_date + + +class ReportQuery(object): + """A report query storing an AWQL query.""" + + def __init__(self, awql): + """Creates a report query instance storing the provided AWQL query.""" + self._awql = awql + + def __str__(self): + """Returns the stored AWQL query.""" + return self._awql + + +@googleads.common.RegisterUtility('ServiceQueryBuilder') +class ServiceQueryBuilder(_QueryBuilder): + """A query builder for building AWQL queries for services.""" + + _ORDER_BY_CLAUSE = namedtuple('OrderByClause', ['field', 'direction']) + + def __init__(self, query_builder=None): + """Creates the service query builder with the optionally specified builder. + + Creates the service query builder by initializing all attributes including + oder by list, start index, and page size. + If the optional query builder are specified, copy all its attributes to this + instance. + + Args: + query_builder: An optional query builder whose attributes will be copied + over to this instance. + + Returns: + This service query builder. + + Raises: + GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder + type. + """ + _QueryBuilder.__init__(self, query_builder) + if query_builder is None: + self.select = set() + self.order_by_list = [] + self.start_index = None + self.page_size = None + else: + try: + self.select = query_builder.select + self.order_by_list = query_builder.order_by_list + self.start_index = query_builder.start_index + self.page_size = query_builder.page_size + except (AttributeError, TypeError): + raise googleads.errors.GoogleAdsValueError( + 'The passed query builder should be of ServiceQueryBuilder type.') + + def Select(self, *fields): + """Sets a provided list of fields as selected fields for the query. + + Subsequent calls to this method overwrite the entire set of selected fields + with the new one. Duplicate field names will be treated as one field. + + Args: + *fields: The specified list of fields to be added to a SELECT clause. + + Returns: + This service query builder. + """ + self.select.update(fields) + return self + + def OrderBy(self, field, ascending=True): + """Adds the provided field to the order-by list with the provided direction. + + Args: + field: The specified field to be added to the order-by list. + ascending: If true, the newly created order-by clause will be in ascending + order. Otherwise, it will be in descending order. + + Returns: + This service query builder. + """ + order_by = self._ORDER_BY_CLAUSE(field, 'ASC' if ascending else 'DESC') + self.order_by_list.append(order_by) + return self + + def Limit(self, start_index, page_size): + """Sets the LIMIT clause using the provided start index and page size. + + Args: + start_index: The specified start index for the LIMIT clause. + page_size: The optional page size for the LIMIT clause. + + Returns: + This service query builder. + + Raises: + ValueError: If start_index is None but the page_size is not None or vice + versa. + """ + if ((start_index is None and page_size is not None) + or (start_index is not None and page_size is None)): + raise ValueError('Either both start_index and page_size must be None, or' + ' neither') + self.start_index = start_index + self.page_size = page_size + return self + + def Build(self): + """Builds a ServiceQuery object containing AWQL queries. + + Returns: + The created ServiceQuery object. + + Raises: + ValueError: If the selected fields or service name is not specified. + """ + if not self.select: + raise ValueError('Must use Select() to specify SELECT clause for valid' + ' AWQL first') + + parts = ['SELECT ', (', '.join(self.select))] + where_clause = (' WHERE %s' % ' AND '.join(builder.Build() for builder + in self.where_builders) + if self.where_builders else '') + parts += where_clause + + if self.order_by_list: + parts.extend([' ORDER BY ', + ', '.join('%s %s' % (order_by.field, order_by.direction) + for order_by in self.order_by_list)]) + awql = ''.join(parts) + + return ServiceQuery(awql, self.start_index, self.page_size) + + @property + def select(self): + """Gets the select set of the query.""" + return self._select + + @select.setter + def select(self, select): + """Sets the select set of the query to the copy of provided value.""" + self._select = set(select) + + @property + def order_by_list(self): + """Gets the order-by list of the query.""" + return self._order_by_list + + @order_by_list.setter + def order_by_list(self, order_by_list): + """Sets the order-by list of the query to the copy of provided value.""" + self._order_by_list = list(order_by_list) + + +class ServiceQuery(object): + """A service query storing an AWQL query.""" + + def __init__(self, awql, start_index, page_size): + """Creates a service query instance storing the provided AWQL query.""" + self._awql = awql + self._start_index = start_index + self._page_size = page_size + self._total_num_entries = None + + def NextPage(self, page_size=None): + """Sets the LIMIT clause of the AWQL to the next page. + + This method is meant to be used with HasNext(). + The page_size is necessary when using DataService, as its paging mechanism + is different from other services. For details, see + https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results. + When the page_size is None, this object's page size is used instead. + + Args: + page_size: The optional page size used to increment the index in the LIMIT + clause. + + Returns: + This service query object. + + Raises: + ValueError: If the start index of this object is None, meaning that the + LIMIT clause hasn't been set before. + """ + if self._start_index is None: + raise ValueError('Cannot page through query with no LIMIT clause.') + increment = self._page_size if page_size is None else page_size + self._start_index += increment + return self + + def HasNext(self, page, page_size=None): + """Checks if there is still a page left to query. + + This method is meant to be used with NextPage(). + The page_size is necessary when using DataService, as its paging mechanism + is different from other services. For details, see + https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results. + When the page_size is None, this object's page size is used instead. + + Args: + page: A dict containing the 'totalNumEntries' key whose value represents + the total number of results from making the query to the AdWords API + services. + page_size: The optional page size used to increment the index in the LIMIT + clause. + + Returns: + True if there is still a page left. + + Raises: + ValueError: If the start index of this object is None, meaning that the + LIMIT clause hasn't been set before. + """ + if self._start_index is None: + raise ValueError('Cannot page through query with no LIMIT clause.') + if not self._total_num_entries: + self._total_num_entries = page['totalNumEntries'] + increment = self._page_size if page_size is None else page_size + return self._start_index + increment < self._total_num_entries + + def Pager(self, service): + """A page generator for this service query and the provided service. + + This generates a page as a result from using the provided service's query() + method until there are no more results to fetch. + + Args: + service: The service object for making a query using this service query. + + Yields: + A resulting page from querying the provided service. + """ + has_page = True + while has_page: + page = service.query(self) + yield page + has_page = self.HasNext(page) + if has_page: + self.NextPage() + + def __str__(self): + """Returns the stored AWQL query combined with the LIMIT clause.""" + awql = self._awql + ' LIMIT %s,%s' % (self._start_index, self._page_size) + return awql diff --git a/googleads/common.py b/googleads/common.py index d21cbcf2..8ab42b00 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -15,7 +15,6 @@ """Common client library functions and classes used by all products.""" -import datetime from functools import wraps import inspect import locale @@ -66,7 +65,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '8.1.0' +VERSION = '9.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' @@ -396,7 +395,7 @@ def _ExtractProxy(proxy_yaml_key, proxy_config_data): return proxy -def _PackForSuds(obj, factory, datetime_packer=None): +def _PackForSuds(obj, factory, packer=None): """Packs SOAP input into the format we want for suds. The main goal here is to pack dictionaries with an 'xsi_type' key into @@ -411,15 +410,17 @@ def _PackForSuds(obj, factory, datetime_packer=None): for instances of unpacked dictionaries or lists. factory: The suds.client.Factory object which can create instances of the classes generated from the WSDL. - datetime_packer: A product specific function to unwrap date/datetimes. + packer: An optional subclass of googleads.common.SudsPacker that provides + customized packing logic. Returns: If the given obj was a dictionary that contained the 'xsi_type' key, this will be an instance of a class generated from the WSDL. Otherwise, this will be the same data type as the input obj was. """ - if datetime_packer and isinstance(obj, (datetime.datetime, datetime.date)): - obj = datetime_packer(obj) + if packer: + obj = packer.Pack(obj) + if obj in ({}, None): # Force suds to serialize empty objects. There are legitimate use cases for # this, for example passing in an empty SearchCriteria object to a DFA @@ -450,16 +451,16 @@ def _PackForSuds(obj, factory, datetime_packer=None): for key in obj: if key == 'xsi_type': continue setattr(new_obj, key, _PackForSuds(obj[key], factory, - datetime_packer=datetime_packer)) + packer=packer)) else: new_obj = {} for key in obj: new_obj[key] = _PackForSuds(obj[key], factory, - datetime_packer=datetime_packer) + packer=packer) return new_obj elif isinstance(obj, (list, tuple)): return [_PackForSuds(item, factory, - datetime_packer=datetime_packer) for item in obj] + packer=packer) for item in obj] else: _RecurseOverObject(obj, factory) return obj @@ -694,6 +695,18 @@ def u2handlers(self): return return_handlers +class SudsPacker(object): + """A utility class to be passed to _PackForSuds for customized packing. + + A subclass should be used in cases where custom logic is needed to pack a + given object in _PackForSuds. + """ + + @classmethod + def Pack(cls, obj): + raise NotImplementedError('You must subclass SudsPacker.') + + class SudsServiceProxy(object): """Wraps a suds service object, allowing custom logic to be injected. @@ -708,7 +721,7 @@ class SudsServiceProxy(object): the client and its factory, """ - def __init__(self, suds_client, header_handler, datetime_packer=None): + def __init__(self, suds_client, header_handler, packer=None): """Initializes a suds service proxy. Args: @@ -717,12 +730,13 @@ def __init__(self, suds_client, header_handler, datetime_packer=None): object. header_handler: A HeaderHandler responsible for setting the SOAP and HTTP headers on the service client. - datetime_packer: A product specific function to unwrap date/datetimes. + packer: An optional subclass of googleads.common.SudsPacker that provides + customized packing logic. """ self.suds_client = suds_client self._header_handler = header_handler self._method_proxies = {} - self._datetime_packer = datetime_packer + self._packer = packer def __getattr__(self, attr): if attr in self.suds_client.wsdl.services[0].ports[0].methods: @@ -750,7 +764,7 @@ def MakeSoapRequest(*args): try: return soap_service_method( *[_PackForSuds(arg, self.suds_client.factory, - self._datetime_packer) for arg in args]) + self._packer) for arg in args]) except suds.WebFault as e: if _logger.isEnabledFor(logging.WARNING): _logger.warning('Response summary - %s', diff --git a/googleads/dfp.py b/googleads/dfp.py index adbbed34..5cf1f7cc 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -46,7 +46,7 @@ # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201611': + 'v201702': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -57,17 +57,18 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NetworkService', 'OrderService', - 'PackageService', 'PlacementService', 'PremiumRateService', - 'ProductService', 'ProductPackageService', 'ProductPackageItemService', - 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201702': + 'v201705': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -89,7 +90,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201705': + 'v201708': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -111,15 +112,15 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201708': + 'v201711': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentMetadataKeyHierarchyService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', - 'InventoryService', 'LabelService', + 'CdnConfigurationService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentMetadataKeyHierarchyService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', @@ -217,8 +218,8 @@ def __init__(self, oauth2_client, application_name, network_code=None, application [optional] network_code: A string identifying the network code of the network you are - accessing. All requests other than getAllNetworks and getCurrentUser - calls require this header to be set. + accessing. All requests other than getAllNetworks require this header + to be set. cache: A subclass of suds.cache.Cache. If not set, this will default to an instance of suds.cache.ObjectCache. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy @@ -300,7 +301,7 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], 'versions: %s' % (version, _SERVICE_MAP.keys())) return googleads.common.SudsServiceProxy(client, self._header_handler, - _DFPDateTimePacker) + packer=_DfpPacker) def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -364,6 +365,53 @@ def SetHeaders(self, suds_client): headers=http_headers) +class _DfpPacker(googleads.common.SudsPacker): + """A utility applying customized packing logic for DFP.""" + + @classmethod + def Pack(cls, obj): + """Pack the given object using DFP-specific logic. + + Args: + obj: an object to be packed for suds using DFP-specific logic, if + applicable. + + Returns: + The given object packed with DFP-specific logic for suds, if applicable. + Otherwise, returns the given object unmodified. + """ + if isinstance(obj, (datetime.datetime, datetime.date)): + return cls.DfpDateTimePacker(obj) + return obj + + @classmethod + def DfpDateTimePacker(cls, value): + """Returns dicts formatted for DFP SOAP based on date/datetime. + + Args: + value: A date or datetime object to be converted. + + Returns: + The value object correctly represented for DFP SOAP. + """ + + if isinstance(value, datetime.datetime): + if value.tzinfo is None: + raise googleads.errors.GoogleAdsValueError( + 'Datetime %s is not timezone aware.' % value + ) + + return { + 'date': cls.DfpDateTimePacker(value.date()), + 'hour': value.hour, + 'minute': value.minute, + 'second': value.second, + 'timeZoneID': value.tzinfo.zone, + } + elif isinstance(value, datetime.date): + return {'year': value.year, 'month': value.month, 'day': value.day} + + @googleads.common.RegisterUtility('StatementBuilder') class StatementBuilder(object): """Provides the ability to programmatically construct PQL queries.""" @@ -543,33 +591,6 @@ def WithBindVariable(self, key, value): return self -def _DFPDateTimePacker(value): - """Returns dicts formatted for DFP SOAP based on date/datetime. - - Args: - value: A date or datetime object to be converted. - - Returns: - The value object correctly represented for DFP SOAP. - """ - - if isinstance(value, datetime.datetime): - if value.tzinfo is None: - raise googleads.errors.GoogleAdsValueError( - 'Datetime %s is not timezone aware.' % value - ) - - return { - 'date': _DFPDateTimePacker(value.date()), - 'hour': value.hour, - 'minute': value.minute, - 'second': value.second, - 'timeZoneID': value.tzinfo.zone, - } - elif isinstance(value, datetime.date): - return {'year': value.year, 'month': value.month, 'day': value.day} - - class PQLHelper(object): """Utility class for PQL.""" @@ -798,7 +819,8 @@ def DownloadPqlResultToList(self, pql_query, values=None): pql_query: str a statement filter to apply (the query should not include the limit or the offset) [optional] - values: list dict of bind values to use with the pql_query. + values: A dict of python objects or a list of raw SOAP values to bind + to the pql_query. Returns: a list of lists with the first being the header row and each subsequent @@ -816,7 +838,8 @@ def DownloadPqlResultToCsv(self, pql_query, file_handle, values=None): the limit or the offset) file_handle: file the file object to write to. [optional] - values: list dict of bind values to use with the pql_query. + values: A dict of python objects or a list of raw SOAP values to bind + to the pql_query. """ pql_writer = csv.writer(file_handle, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) @@ -875,8 +898,12 @@ def _PageThroughPqlSet(self, pql_query, output_function, values): the limit or the offset) output_function: the function to call to output the results (csv or in memory) - values: list dict of bind values to use with the pql_query. + values: A dict of python objects or a list of raw SOAP values to bind + to the pql_query. """ + if isinstance(values, dict): + values = PQLHelper.GetQueryValuesFromDict(values) + pql_service = self._GetPqlService() current_offset = 0 diff --git a/setup.py b/setup.py index 5b323e1d..2c978f1e 100755 --- a/setup.py +++ b/setup.py @@ -24,9 +24,11 @@ PACKAGES = ['googleads'] -DEPENDENCIES = ['httplib2>=0.9.2', 'oauth2client>=4.0.0,<5.0.0', - 'suds-jurko>=0.6', 'pysocks>=1.5.6', 'pytz>=2015.7', - 'PyYAML>=3.11', 'xmltodict>=0.9.2'] +DEPENDENCIES = ['httplib2>=0.9.2,<1.0.0', 'oauth2client>=4.0.0,<5.0.0', + 'suds-jurko>=0.6,<0.7', 'pysocks>=1.5.6,<2.0.0', 'pytz>=2015.7', + 'PyYAML>=3.11,<4.0', 'xmltodict>=0.9.2,<1.0.0'] + +TEST_DEPENDENCIES = ['mock>=2.0.0,<3.0.0', 'pyfakefs>=3.2,<4.0'] CLASSIFIERS = [ 'Intended Audience :: Developers', @@ -116,4 +118,6 @@ def GetVersion(): keywords='adwords dfp google', classifiers=CLASSIFIERS, install_requires=DEPENDENCIES, + tests_require=TEST_DEPENDENCIES, + test_suite='tests', **extra_params) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 1a301bc5..d364cc50 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -16,8 +16,10 @@ """Unit tests to cover the adwords module.""" +import datetime import io import os +import re import StringIO import sys import tempfile @@ -30,6 +32,7 @@ import googleads.adwords import googleads.common import googleads.errors +import testing import mock import suds @@ -121,7 +124,7 @@ def GetProxyConfig(http_host=None, http_port=None, https_host=None, disable_certificate_validation=disable_certificate_validation) -class AdWordsHeaderHandlerTest(unittest.TestCase): +class AdWordsHeaderHandlerTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.adwords._AdWordsHeaderHandler class.""" def setUp(self): @@ -407,21 +410,30 @@ def testGetService_success(self): server = 'https://testing.test.com/' with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' - ) as mock_transport: - mock_plugin.return_value = mock.Mock() - mock_transport.return_value = mock.Mock() - client = GetAdWordsClient() - suds_service = client.GetService( - service, CURRENT_VERSION, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, CURRENT_VERSION, service), - transport=mock_transport.return_value, timeout=3600, - plugins=[mock_plugin.return_value]) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + with mock.patch('googleads.adwords._AdWordsHeaderHandler') as mock_awhh: + with mock.patch('suds.client.Client') as mock_client: + with mock.patch('googleads.common.' + 'SudsServiceProxy') as mock_service_proxy: + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' + ) as mock_transport: + mock_plugin.return_value = mock.Mock() + mock_awhh.return_value = mock.Mock() + mock_service_proxy.return_value = mock.Mock() + mock_transport.return_value = mock.Mock() + client = GetAdWordsClient() + suds_service = client.GetService( + service, CURRENT_VERSION, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' + % (namespace, CURRENT_VERSION, service), + transport=mock_transport.return_value, timeout=3600, + plugins=[mock_plugin.return_value]) + self.assertEqual(suds_service, mock_service_proxy.return_value) + mock_service_proxy.assert_called_once_with( + mock_client.return_value, + mock_awhh.return_value, + packer=googleads.adwords._AdWordsPacker) def testGetService_successWithFileCache(self): service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] @@ -558,7 +570,31 @@ def testServiceMap(self): % (version, service, mapping, wsdl_url)) -class BatchJobHelperTest(unittest.TestCase): +class AdWordsPackerTest(unittest.TestCase): + """Tests for the googleads.adwords._AdWordsPacker class.""" + + def setUp(self): + self.packer = googleads.adwords._AdWordsPacker + + def testAdWordsPackerForServiceQuery(self): + query = (googleads.adwords.ServiceQueryBuilder() + .Select('Id', 'Name', 'Status') + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, 100) + .Build()) + + query_regex = (r'SELECT (.*) WHERE Status = "ENABLED"' + r' ORDER BY Name ASC LIMIT 0,100') + + self.assertRegexpMatches(self.packer.Pack(query), query_regex) + + def testAdWordsPackerForUnsupportedObjectType(self): + obj = object() + self.assertEqual(self.packer.Pack(obj), obj) + + +class BatchJobHelperTest(testing.CleanUtilityRegistryTestCase): """Test suite for BatchJobHelper utility.""" @@ -589,7 +625,7 @@ def testUploadOperations(self): mock_open.assert_called_with(mock_request) -class BatchJobUploadRequestBuilderTest(unittest.TestCase): +class BatchJobUploadRequestBuilderTest(testing.CleanUtilityRegistryTestCase): """Test suite for the BatchJobUploadRequestBuilder.""" @@ -1358,7 +1394,7 @@ def testBuildUploadRequestBodyWithOnlyPrefix(self): self.assertTrue(increment == self.request_body_start) -class IncrementalUploadHelperTest(unittest.TestCase): +class IncrementalUploadHelperTest(testing.CleanUtilityRegistryTestCase): """Test suite for the IncrementalUploadHelper.""" @@ -1459,7 +1495,7 @@ def testUploadOperationsAfterFinished(self): self.incremental_uploader.UploadOperations, {}) -class ResponseParserTest(unittest.TestCase): +class ResponseParserTest(testing.CleanUtilityRegistryTestCase): """Test suite for the ResponseParser.""" def setUp(self): @@ -1541,7 +1577,7 @@ def testParseUnicodeResponse(self): self.assertTrue(campaign['name'] == name) -class ReportDownloaderTest(unittest.TestCase): +class ReportDownloaderTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.adwords.ReportDownloader class.""" def setUp(self): @@ -1840,7 +1876,10 @@ def testDownloadReport_failure(self): def testDownloadReportWithAwql(self): output_file = io.StringIO() - query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' + query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId').From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .Build()) file_format = 'CSV' post_body = urllib.urlencode({'__fmt': file_format, '__rdquery': query}) if not PYTHON2: @@ -2000,5 +2039,429 @@ def testExtractResponseHeaders(self): self.assertEqual(dict_headers, expected_headers) +class QueryBuilderTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.adwords._QueryBuilder class.""" + + def testSelect(self): + with self.assertRaises(NotImplementedError): + googleads.adwords._QueryBuilder().Select() + + def testFailUsingCopyConstructor(self): + with self.assertRaises(googleads.errors.GoogleAdsValueError): + (googleads.adwords + ._QueryBuilder('SELECT Id FROM CAMPAIGN_PERFORMANCE_REPORT')) + + +class ReportQueryBuilderTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.adwords.ReportQueryBuilder class.""" + + def testCopyConstructor(self): + # Test using date range. + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT' + ' WHERE CampaignStatus = "ENABLED" DURING YESTERDAY') + previous_query_builder = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .During('YESTERDAY')) + actual_query = (googleads.adwords.ReportQueryBuilder(previous_query_builder) + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + # Test using start and end dates. + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT' + ' WHERE CampaignStatus = "ENABLED"' + ' DURING 20170101,20170131') + previous_query_builder = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .During(start_date='20170101', + end_date='20170131')) + actual_query = (googleads.adwords.ReportQueryBuilder(previous_query_builder) + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testFailUsingCopyConstructor(self): + builder = googleads.adwords._QueryBuilder() + builder.select = 'Id' + with self.assertRaises(googleads.errors.GoogleAdsValueError): + googleads.adwords.ReportQueryBuilder(builder) + + def testBuild(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_stringWhereValue(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT' + ' WHERE CampaignStatus = "ENABLED" DURING YESTERDAY') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .During('YESTERDAY') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_numericWhereValue(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' ADGROUP_PERFORMANCE_REPORT' + ' WHERE AverageCpm >= 5.6 DURING TODAY') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('ADGROUP_PERFORMANCE_REPORT') + .Where('AverageCpm').GreaterThanOrEqualTo(5.6) + .During('TODAY') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_multipleStringWhereValues(self): + expected_awql = ('SELECT Id, CampaignId, CampaignName FROM' + ' AD_PERFORMANCE_REPORT' + ' WHERE CampaignName CONTAINS_ALL ["white", "black"]' + ' DURING LAST_WEEK') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('Id', 'CampaignId', 'CampaignName') + .From('AD_PERFORMANCE_REPORT') + .Where('CampaignName').ContainsAll('white', 'black') + .During('LAST_WEEK') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_multipleNumericWhereValues(self): + expected_awql = ('SELECT Id, CampaignId, CampaignName FROM' + ' AD_PERFORMANCE_REPORT' + ' WHERE CampaignId IN [1234, 5678] DURING LAST_WEEK') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('Id', 'CampaignId', 'CampaignName') + .From('AD_PERFORMANCE_REPORT') + .Where('CampaignId').In(1234, 5678) + .During('LAST_WEEK') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_multipleWhereConditions(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' ADGROUP_PERFORMANCE_REPORT' + ' WHERE Clicks >= 500 AND CampaignName' + ' CONTAINS_IGNORE_CASE "promotion"' + ' AND AdGroupName STARTS_WITH "adwords_"' + ' AND BiddingStrategyName STARTS_WITH_IGNORE_CASE "europe"' + ' AND CustomerDescriptiveName CONTAINS "goog"' + ' AND CustomerDescriptiveName DOES_NOT_CONTAIN "asia"' + ' AND AccountDescriptiveName DOES_NOT_CONTAIN_IGNORE_CASE' + ' "group 3" AND CampaignStatus != "REMOVED"' + ' AND AdGroupStatus NOT_IN ["REMOVED", "PAUSED"]' + ' AND AdNetworkType1 CONTAINS_ANY ["SEARCH", "DISPLAY"]' + ' AND AdNetworkType2 CONTAINS_NONE' + ' ["YOUTUBE_SEARCH", "UNKNOWN"] AND AverageCpv > 20.7' + ' AND AllConversions < 100.6' + ' DURING 20170601,20170630') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('ADGROUP_PERFORMANCE_REPORT') + .Where('Clicks').GreaterThanOrEqualTo(500) + .Where('CampaignName').ContainsIgnoreCase('promotion') + .Where('AdGroupName').StartsWith('adwords_') + .Where('BiddingStrategyName').StartsWithIgnoreCase('europe') + .Where('CustomerDescriptiveName').Contains('goog') + .Where('CustomerDescriptiveName').DoesNotContain('asia') + .Where('AccountDescriptiveName').DoesNotContainIgnoreCase( + 'group 3') + .Where('CampaignStatus').NotEqualTo('REMOVED') + .Where('AdGroupStatus').NotIn('REMOVED', 'PAUSED') + .Where('AdNetworkType1').ContainsAny('SEARCH', 'DISPLAY') + .Where('AdNetworkType2').ContainsNone('YOUTUBE_SEARCH', + 'UNKNOWN') + .Where('AverageCpv').GreaterThan(20.7) + .Where('AllConversions').LessThan(100.6) + .During(start_date='20170601', end_date='20170630') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_noWhereClause(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' ADGROUP_PERFORMANCE_REPORT DURING TODAY') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('ADGROUP_PERFORMANCE_REPORT') + .During('TODAY') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_noDuringClause(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' ADGROUP_PERFORMANCE_REPORT' + ' WHERE Clicks <= 500') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('ADGROUP_PERFORMANCE_REPORT') + .Where('Clicks').LessThanOrEqualTo(500) + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_selectIsNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().Build() + + def testBuild_fromIsNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().Select('Id').Build() + + def testDuring_usingPythonDateTime(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT' + ' WHERE CampaignStatus = "ENABLED"' + ' DURING 20170501,20170531') + start_date = datetime.date(2017, 5, 1) + end_date = start_date + datetime.timedelta(days=30) + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .During(start_date=start_date, end_date=end_date) + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testDuring_allParametersNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().During() + + def testDuring_allParametersNotNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().During('TODAY', '20170101', + '20170131') + + def testDuring_startOrEndDateNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().During(start_date='20170101') + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().During(end_date='20170131') + + +class ServiceQueryBuilderTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.adwords.ServiceQueryBuilder class.""" + + def testCopyConstructor(self): + awql_regex = (r'SELECT (.*) WHERE Status = "ENABLED"' + r' ORDER BY Name ASC LIMIT 0,100') + selected_fields = ['Id', 'Name'] + previous_query_builder = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, 100)) + + actual_query = googleads.adwords.ServiceQueryBuilder( + previous_query_builder).Build() + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause can show fields listed in any orders. + self.assertItemsEqual(selected_fields, + [field.strip() for field + in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testFailUsingCopyConstructor(self): + builder = googleads.adwords._QueryBuilder() + builder.select = 'Id' + with self.assertRaises(googleads.errors.GoogleAdsValueError): + googleads.adwords.ServiceQueryBuilder(builder) + + def testBuild(self): + awql_regex = (r'SELECT (.*) LIMIT 0,100') + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 100) + .Build()) + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause can show fields listed in any orders. + self.assertItemsEqual(selected_fields, + [field.strip() for field + in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testBuild_duplicateSelectedFieldsRetainOnlyUnique(self): + awql_regex = (r'SELECT (.*) LIMIT 0,100') + selected_fields = ['Id', 'Name', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 100) + .Build()) + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause retains only unique fields. + self.assertItemsEqual(set(selected_fields), + [field.strip() for field + in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testBuild_whereConditions(self): + awql_regex = (r'SELECT (.*)' + r' WHERE Name CONTAINS_IGNORE_CASE "promotion"' + r' AND Status NOT_IN \["REMOVED", "PAUSED"\]' + r' ORDER BY Name ASC' + r' LIMIT 100,100') + selected_fields = ['Id', 'Name', 'Status'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Where('Name').ContainsIgnoreCase('promotion') + .Where('Status').NotIn('REMOVED', 'PAUSED') + .OrderBy('Name') + .Limit(100, 100) + .Build()) + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause can show fields listed in any orders. + self.assertItemsEqual(selected_fields, + [field.strip() for field + in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testBuild_orderByDesc(self): + awql_regex = (r'SELECT (.*)' + r' ORDER BY Name DESC' + r' LIMIT 100,100') + selected_fields = ['Id', 'Name', 'Status'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .OrderBy('Name', ascending=False) + .Limit(100, 100) + .Build()) + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause can show fields listed in any orders. + self.assertItemsEqual(selected_fields, + [field.strip() for field + in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testBuild_selectIsNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ServiceQueryBuilder().Build() + + def testBuild_limitStartIndexOrPageSizeIsNoneButNotTheOther(self): + # A page size is not specified. + with self.assertRaises(ValueError): + (googleads.adwords.ServiceQueryBuilder() + .Select('Id') + .OrderBy('Name', ascending=False) + .Limit(100, None) + .Build()) + # A start index is not specified. + with self.assertRaises(ValueError): + (googleads.adwords.ServiceQueryBuilder() + .Select('Id') + .OrderBy('Name', ascending=False) + .Limit(None, 100) + .Build()) + + +class ServiceQueryTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.adwords.ServiceQuery class.""" + + def testNextPage(self): + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 100) + .Build()) + # Do next page and check if the LIMIT clause is modified correctly. + awql_regex = (r'SELECT (.*) LIMIT 100,100') + actual_query.NextPage() + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testNextPage_userProvidedPage(self): + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 100) + .Build()) + # Do next page and check if the LIMIT clause is modified correctly. + awql_regex = (r'SELECT (.*) LIMIT 50,100') + actual_query.NextPage(50) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testNextPageFail(self): + actual_query = googleads.adwords.ServiceQuery('SELECT Id, Name', None, 100) + + with self.assertRaises(ValueError): + actual_query.NextPage() + + def testHasNext(self): + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 1) + .Build()) + awql_regex = (r'SELECT (.*) LIMIT 0,1') + self.assertRegexpMatches(str(actual_query), awql_regex) + + page = {'totalNumEntries': 3} + + self.assertTrue(actual_query.HasNext(page)) + awql_regex = (r'SELECT (.*) LIMIT 1,1') + actual_query.NextPage() + self.assertRegexpMatches(str(actual_query), awql_regex) + + self.assertTrue(actual_query.HasNext(page)) + awql_regex = (r'SELECT (.*) LIMIT 2,1') + actual_query.NextPage() + self.assertRegexpMatches(str(actual_query), awql_regex) + + self.assertFalse(actual_query.HasNext(page)) + + def testHasNext_userProvidedPage(self): + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 1) + .Build()) + awql_regex = (r'SELECT (.*) LIMIT 0,1') + self.assertRegexpMatches(str(actual_query), awql_regex) + + page = {'totalNumEntries': 80} + self.assertFalse(actual_query.HasNext(page, 100)) + + def testHasNextFail(self): + actual_query = googleads.adwords.ServiceQuery('SELECT Id, Name', None, 100) + + page = {'totalNumEntries': 10} + with self.assertRaises(ValueError): + actual_query.HasNext(page) + + def testPager(self): + service = 'CampaignService' + fake_page = {'totalNumEntries': 3} + + with mock.patch('suds.client.Client'): + client = GetAdWordsClient(cache=suds.cache.FileCache) + service = client.GetService(service, CURRENT_VERSION) + with mock.patch.object(service, 'query', + return_value=fake_page, autospec=True): + query = (googleads.adwords.ServiceQueryBuilder() + .Select('Id', 'Name') + .Limit(0, 1) + .Build()) + i = 0 + for page in query.Pager(service): + self.assertEqual(fake_page['totalNumEntries'], + page['totalNumEntries']) + i += 1 + # Pager should return the number of page equal to the 'totalNumEntries' + # returned by a service. + self.assertEqual(fake_page['totalNumEntries'], i) + + if __name__ == '__main__': unittest.main() diff --git a/tests/common_test.py b/tests/common_test.py index dedbb651..282bfb03 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -15,8 +15,10 @@ """Unit tests to cover the common module.""" -import datetime import io +import numbers +import os +import ssl import unittest from urllib import addinfourl import urllib2 @@ -32,9 +34,10 @@ import googleads.common import googleads.errors import googleads.oauth2 +import testing -class CommonTest(unittest.TestCase): +class CommonTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.common module.""" # Dictionaries with all the required OAuth2 keys @@ -82,6 +85,7 @@ def test(self): self.test2 = Test2 def tearDown(self): + super(CommonTest, self).tearDown() self.locale_patcher.stop() def testShouldWarnWithBadEncoding(self): @@ -921,6 +925,24 @@ def testPackForSuds(self): 'metadata': {'xsi_type': 'metadata', 'a': {'b': 'c'}}}, {'i do not have': 'a type'}], input_list) + def testPackForSuds_applyCustomPacker(self): + class CustomPacker(googleads.common.SudsPacker): + @classmethod + def Pack(cls, obj): + if isinstance(obj, numbers.Number): + return {'xsi_type': 'Integer', 'value': str(int(obj))} + return obj + + factory = mock.Mock() + factory.create.return_value = mock.MagicMock() + factory.create.return_value.__iter__.return_value = iter( + [('Number.Type', 0), ('value', 1)]) + number = 3.14159265358979323846264 + + rval = googleads.common._PackForSuds(number, factory, CustomPacker) + self.assertEqual('Integer', getattr(rval, 'Number.Type')) + self.assertEqual('3', rval.value) + def testPackForSuds_secondNamespace(self): factory = mock.Mock() factory.create.side_effect = [suds.TypeNotFound(''), mock.MagicMock()] @@ -930,29 +952,6 @@ def testPackForSuds_secondNamespace(self): factory.create.assert_any_call('ns0:EliteCampaign') self.assertEqual('Sales', rval.name) - def testPackForSuds_datetime_packer(self): - factory = mock.Mock() - factory.create.return_value = mock.MagicMock() - factory.create.return_value.__iter__.return_value = iter( - [('abc', 0)]) - - def sample_packer(dt): - return {'xsi_type': 'abc', 'test': dt.year} - - # Test that our packer function is called for datetimes - rval = googleads.common._PackForSuds( - {'param': datetime.datetime(2017, 1, 1, 0, 0, 0)}, - factory, datetime_packer=sample_packer) - - self.assertEqual(2017, rval['param'].test) - - # Test that our packer function is called for dates - rval = googleads.common._PackForSuds( - {'param': datetime.date(2017, 1, 1)}, - factory, datetime_packer=sample_packer) - - self.assertEqual(2017, rval['param'].test) - class SudsServiceProxyTest(unittest.TestCase): """Tests for the googleads.common.SudsServiceProxy class.""" @@ -1006,18 +1005,24 @@ def testMarshalled(self): marshalled_context = mock.Mock() marshalled_context.envelope = envelope - with mock.patch('googleads.common._ExtractRequestSummaryFields') as mk_ext: - self.logging_message_plugin.marshalled(marshalled_context) - mk_ext.assert_called_once_with(envelope) + with mock.patch('googleads.common._logger') as mock_logger: + mock_logger.isEnabledFor.return_value = True + with mock.patch( + 'googleads.common._ExtractRequestSummaryFields') as mk_ext: + self.logging_message_plugin.marshalled(marshalled_context) + mk_ext.assert_called_once_with(envelope) def testParsed(self): reply = 'reply' parsed_context = mock.Mock() parsed_context.reply = reply - with mock.patch('googleads.common._ExtractResponseSummaryFields') as mk_ext: - self.logging_message_plugin.parsed(parsed_context) - mk_ext.assert_called_once_with(reply) + with mock.patch('googleads.common._logger') as mock_logger: + mock_logger.isEnabledFor.return_value = True + with mock.patch( + 'googleads.common._ExtractResponseSummaryFields') as mk_ext: + self.logging_message_plugin.parsed(parsed_context) + mk_ext.assert_called_once_with(reply) class ProxyConfigTest(unittest.TestCase): @@ -1030,7 +1035,7 @@ def setUp(self): self.proxy_port2 = 'port2' self.username = 'username' self.password = 'password' - self.cafile = '/tmp/file.ca' + self.cafile = os.path.join(os.path.dirname(__file__), 'test_data/test.crt') self.proxy_no_credentials = googleads.common.ProxyConfig.Proxy( self.proxy_host1, self.proxy_port1) @@ -1063,17 +1068,25 @@ def testProxyToStringWithOnlyUsername(self): def testProxyConfigGetHandlersWithNoProxyOrSSLContext(self): proxy_config = googleads.common.ProxyConfig() - self.assertEqual(proxy_config.GetHandlers(), []) + with mock.patch('urllib2.HTTPSHandler') as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertIn(https_handler_instance, proxy_config.GetHandlers()) def testProxyConfigGetHandlersWithProxy(self): http_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, self.proxy_port1) with mock.patch('urllib2.ProxyHandler') as proxy_handler: - proxy_handler.return_value = mock.Mock() + proxy_handler_instance = mock.Mock() + proxy_handler.return_value = proxy_handler_instance proxy_config = googleads.common.ProxyConfig(http_proxy=http_proxy) - self.assertEqual(proxy_config.GetHandlers(), [proxy_handler.return_value]) - proxy_handler.assert_called_once_with( - {'http': '%s' % str(http_proxy)}) + with mock.patch('urllib2.HTTPSHandler') as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual(proxy_config.GetHandlers(), + [https_handler_instance, proxy_handler_instance]) + proxy_handler.assert_called_once_with( + {'http': '%s' % str(http_proxy)}) def testProxyConfigGetHandlersWithProxyAndSLLContext(self): https_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, @@ -1096,17 +1109,23 @@ def testProxyConfigGetHandlersWithProxyAndSLLContext(self): def testProxyConfigWithNoProxy(self): proxy_config = googleads.common.ProxyConfig() self.assertEqual(proxy_config.proxy_info, None) - self.assertEqual(proxy_config.GetHandlers(), []) - # Note: The ssl_context will always be None on incompatible versions of - # Python. The version used internally doesn't support this feature. Another - # impact is that HTTPSHandler will never be invoked in these tests. - self.assertEqual(proxy_config._ssl_context, None) + + with mock.patch('urllib2.HTTPSHandler') as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual(proxy_config.GetHandlers(), + [https_handler_instance]) + self.assertIsInstance( + proxy_config._ssl_context, ssl.SSLContext) with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([]) - self.assertEqual(t.return_value, transport) + with mock.patch('urllib2.HTTPSHandler') as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with([https_handler_instance]) + self.assertEqual(t.return_value, transport) def testProxyConfigWithHTTPProxy(self): with mock.patch('httplib2.ProxyInfo') as proxy_info: @@ -1120,20 +1139,23 @@ def testProxyConfigWithHTTPProxy(self): self.assertEqual(proxy_config.proxy_info, proxy_info.return_value) self.assertEqual(proxy_config._proxy_option, {'http': '%s:%s' % ( self.proxy_host1, self.proxy_port1)}) - # Note: The ssl_context will always be None on incompatible versions of - # Python. The version used internally doesn't support this feature. Another - # impact is that HTTPSHandler will never be invoked in these tests. - self.assertEqual(proxy_config._ssl_context, None) + self.assertIsInstance( + proxy_config._ssl_context, ssl.SSLContext) with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() with mock.patch('urllib2.ProxyHandler') as proxy_handler: - proxy_handler.return_value = mock.Mock() - self.assertEqual(proxy_config.GetHandlers(), - [proxy_handler.return_value]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([proxy_handler.return_value]) - self.assertEqual(t.return_value, transport) + proxy_handler_instance = mock.Mock() + proxy_handler.return_value = proxy_handler_instance + with mock.patch('urllib2.HTTPSHandler') as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual(proxy_config.GetHandlers(), + [https_handler_instance, proxy_handler_instance]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with( + [https_handler_instance, proxy_handler_instance]) + self.assertEqual(t.return_value, transport) def testProxyConfigWithHTTPSProxy(self): with mock.patch('httplib2.ProxyInfo') as proxy_info: @@ -1149,22 +1171,26 @@ def testProxyConfigWithHTTPSProxy(self): self.assertEqual(proxy_config._proxy_option, {'https': '%s:%s@%s:%s' % ( self.username, self.password, self.proxy_host2, self.proxy_port2)}) - # Note: The ssl_context will always be None on incompatible versions of - # Python. The version used internally doesn't support this feature. Another - # impact is that HTTPSHandler will never be invoked in these tests. - self.assertEqual(proxy_config._ssl_context, None) + self.assertIsInstance( + proxy_config._ssl_context, ssl.SSLContext) self.assertEqual(proxy_config.cafile, self.cafile) self.assertEqual(proxy_config.disable_certificate_validation, False) with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() with mock.patch('urllib2.ProxyHandler') as proxy_handler: - proxy_handler.return_value = mock.Mock() - self.assertEqual(proxy_config.GetHandlers(), - [proxy_handler.return_value]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([proxy_handler.return_value]) - self.assertEqual(t.return_value, transport) + proxy_handler_instance = mock.Mock() + proxy_handler.return_value = proxy_handler_instance + with mock.patch('urllib2.HTTPSHandler') as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual( + proxy_config.GetHandlers(), + [https_handler_instance, proxy_handler_instance]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with( + [https_handler_instance, proxy_handler_instance]) + self.assertEqual(t.return_value, transport) def testProxyConfigWithHTTPAndHTTPSProxy(self): with mock.patch('httplib2.ProxyInfo') as proxy_info: @@ -1182,22 +1208,27 @@ def testProxyConfigWithHTTPAndHTTPSProxy(self): 'http': '%s:%s@%s:%s' % (self.username, self.password, self.proxy_host2, self.proxy_port2), 'https': '%s:%s' % (self.proxy_host1, self.proxy_port1)}) - # Note: The ssl_context will always be None on incompatible versions of - # Python. The version used internally doesn't support this feature. Another - # impact is that HTTPSHandler will never be invoked in these tests. - self.assertEqual(proxy_config._ssl_context, None) + + self.assertIsInstance(proxy_config._ssl_context, ssl.SSLContext) self.assertEqual(proxy_config.cafile, None) self.assertEqual(proxy_config.disable_certificate_validation, True) with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() with mock.patch('urllib2.ProxyHandler') as proxy_handler: - proxy_handler.return_value = mock.Mock() - self.assertEqual(proxy_config.GetHandlers(), - [proxy_handler.return_value]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([proxy_handler.return_value]) - self.assertEqual(t.return_value, transport) + proxy_handler_instance = mock.Mock() + proxy_handler.return_value = proxy_handler_instance + + with mock.patch('urllib2.HTTPSHandler') as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual( + proxy_config.GetHandlers(), + [https_handler_instance, proxy_handler_instance]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with( + [https_handler_instance, proxy_handler_instance]) + self.assertEqual(t.return_value, transport) class TestSudsRequestPatcher(unittest.TestCase): diff --git a/tests/dfp_test.py b/tests/dfp_test.py index d62e1d35..58de1607 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -28,6 +28,7 @@ import googleads.dfp import googleads.common import googleads.errors +import testing class BaseValue(object): @@ -106,7 +107,7 @@ def DecideValue(original_object): return BooleanValue(original_object) -class DfpHeaderHandlerTest(unittest.TestCase): +class DfpHeaderHandlerTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.dfp._DfpHeaderHandler class.""" def setUp(self): @@ -336,7 +337,7 @@ def testGetService_success(self): mock_service_proxy.assert_called_once_with( mock_client.return_value, dfp_client._header_handler, - googleads.dfp._DFPDateTimePacker) + packer=googleads.dfp._DfpPacker) def testGetService_successWithNoCache(self): service = googleads.dfp._SERVICE_MAP[self.version][0] @@ -410,25 +411,33 @@ def testGetService_transportError(self): dfp_client.GetService, service, self.version) -class DateTimePackerTest(unittest.TestCase): +class DfpPackerTest(unittest.TestCase): + """Tests for the googleads.dfp._DfpPacker class.""" - def testUnwrapDate(self): + def setUp(self): + self.packer = googleads.dfp._DfpPacker + + def testPackDate(self): input_date = datetime.date(2017, 1, 2) - result = googleads.dfp._DFPDateTimePacker(input_date) + result = self.packer.Pack(input_date) self.assertEqual(result, {'year': 2017, 'month': 1, 'day': 2}) - def testUnwrapDateTime(self): + def testPackDateTime(self): input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) input_date = pytz.timezone('America/New_York').localize(input_date) - result = googleads.dfp._DFPDateTimePacker(input_date) + result = self.packer.Pack(input_date) self.assertEqual(result, {'date': {'year': 2017, 'month': 1, 'day': 2}, 'hour': 3, 'minute': 4, 'second': 5, 'timeZoneID': 'America/New_York'}) - def testUnwrapDateTimeNeedsTimeZone(self): + def testPackDateTimeNeedsTimeZone(self): input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) self.assertRaises(googleads.errors.GoogleAdsValueError, - googleads.dfp._DFPDateTimePacker, input_date) + self.packer.Pack, input_date) + + def testPackUnsupportedObjectType(self): + obj = object() + self.assertEqual(googleads.dfp._DfpPacker.Pack(obj), obj) class DataDownloaderTest(unittest.TestCase): @@ -613,6 +622,50 @@ def testDownloadPqlResultToList(self): self.generic_header[1]['labelName']], row1, row2], result_set) + def testDownloadPqlResultToListWithOldValuesList(self): + self.pql_service.select.return_value = {'rows': self.generic_rval, + 'columnTypes': self.generic_header} + + result_set = self.report_downloader.DownloadPqlResultToList( + 'SELECT Id, Name FROM Line_Item WHERE Id = :id', + [{'key': 'id', 'value': {'xsi_type': 'NumberValue', 'value': 1}}]) + + row1 = [self.report_downloader._ConvertValueForCsv(field) + for field in self.generic_rval[0]['values']] + row2 = [self.report_downloader._ConvertValueForCsv(field) + for field in self.generic_rval[1]['values']] + + self.pql_service.select.assert_called_once_with( + {'values': [{'key': 'id', + 'value': {'xsi_type': 'NumberValue', 'value': 1}}], + 'query': ('SELECT Id, Name FROM Line_Item ' + 'WHERE Id = :id LIMIT 500 OFFSET 0')}) + self.assertEqual([[self.generic_header[0]['labelName'], + self.generic_header[1]['labelName']], + row1, row2], result_set) + + def testDownloadPqlResultToListWithDict(self): + self.pql_service.select.return_value = {'rows': self.generic_rval, + 'columnTypes': self.generic_header} + + result_set = self.report_downloader.DownloadPqlResultToList( + 'SELECT Id, Name FROM Line_Item WHERE Id = :id', + {'id': 1}) + + row1 = [self.report_downloader._ConvertValueForCsv(field) + for field in self.generic_rval[0]['values']] + row2 = [self.report_downloader._ConvertValueForCsv(field) + for field in self.generic_rval[1]['values']] + + self.pql_service.select.assert_called_once_with( + {'values': [{'key': 'id', + 'value': {'xsi_type': 'NumberValue', 'value': 1}}], + 'query': ('SELECT Id, Name FROM Line_Item ' + 'WHERE Id = :id LIMIT 500 OFFSET 0')}) + self.assertEqual([[self.generic_header[0]['labelName'], + self.generic_header[1]['labelName']], + row1, row2], result_set) + def testDownloadPqlResultToList_NoRows(self): self.pql_service.select.return_value = {} @@ -695,7 +748,7 @@ def testGetPqlService(self): 'PublisherQueryLanguageService', self.version, 'https://ads.google.com') -class StatementBuilderTest(unittest.TestCase): +class StatementBuilderTest(testing.CleanUtilityRegistryTestCase): """Tests for the StatementBuilder class.""" def testBuildBasicSelectFrom(self): @@ -953,7 +1006,7 @@ def testBreakWithBadSelectFrom(self): test_statement.ToStatement) -class FilterStatementTest(unittest.TestCase): +class FilterStatementTest(testing.CleanUtilityRegistryTestCase): """Tests for the FilterStatement class.""" def testFilterStatement(self): diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index b21a0a5d..0c16b6cd 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -26,11 +26,16 @@ import googleads.errors import googleads.oauth2 -import fake_filesystem -import fake_tempfile +from pyfakefs import fake_filesystem +from pyfakefs import fake_tempfile from oauth2client.client import AccessTokenRefreshError from oauth2client.client import OAuth2Credentials -from oauth2client.client import SignedJwtAssertionCredentials + +if googleads.oauth2.DEPRECATED_OAUTH2CLIENT: + _SA_CRED_PATH = ('oauth2client.client' + '.SignedJwtAssertionCredentials') +else: + _SA_CRED_PATH = 'oauth2client.service_account.ServiceAccountCredentials' class GetAPIScopeTest(unittest.TestCase): @@ -209,15 +214,18 @@ def setUp(self): self.opener.disable_ssl_certificate_valiation = ( self.proxy_config.disable_certificate_validation) - # Mock out oauth2client.client.SignedJwtAssertionCredentials for - # testing. - self.oauth2_credentials = mock.Mock( - spec=SignedJwtAssertionCredentials) + # Mock out service account credentials for testing. + self.oauth2_credentials = mock.Mock() self.oauth2_credentials.return_value = mock.Mock() - self.mock_oauth2_credentials = (self.oauth2_credentials.return_value) + self.mock_oauth2_credentials = self.oauth2_credentials.return_value self.mock_oauth2_credentials.access_token = 'x' self.mock_oauth2_credentials.token_expiry = datetime.datetime( 1980, 1, 1, 12) + # Also mock out instantiation methods for newer oauth2client versions. + self.oauth2_credentials.from_p12_keyfile.return_value = ( + self.mock_oauth2_credentials) + self.oauth2_credentials.from_json_keyfile_name.return_value = ( + self.mock_oauth2_credentials) def apply(headers): headers['Authorization'] = ('Bearer %s' @@ -233,9 +241,7 @@ def refresh(mock_http): self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply) self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh) with mock.patch('__builtin__.open', self.fake_open): - with mock.patch('oauth2client.client' - '.SignedJwtAssertionCredentials', - self.oauth2_credentials): + with mock.patch(_SA_CRED_PATH, self.oauth2_credentials): self.googleads_client = googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, self.key_file_path, self.private_key_password, proxy_config=self.proxy_config) @@ -307,21 +313,35 @@ def testCreateGoogleServiceAccountClient_DelegatedP12OAuth2Client4(self): mock_create_delegated.assert_called_once_with(self.delegated_account) def testCreateGoogleServiceAccountClient_DelegatedP12OAuth2ClientDepr(self): - # Mock out the oauth2client 1.4.12 oauth2client.service_account module to + # Mock out the oauth2client 1.4.12 oauth2client.client module to # verify that the correct parts are called. - with mock.patch('googleads.oauth2.oauth2client.client' - '.SignedJwtAssertionCredentials') as mock_credentials: - with mock.patch('%s.open' % googleads.oauth2.__name__, self.fake_open, - create=True): - googleads.oauth2.GoogleServiceAccountClient( - self.scope, client_email=self.service_account_email, - key_file=self.key_file_path, sub=self.delegated_account) - mock_credentials.assert_called_once_with( - self.service_account_email, self.private_key, self.scope, - private_key_password=self.private_key_password, - user_agent='Google Ads Python Client Library', - token_uri='https://accounts.google.com/o/oauth2/token', - sub=self.delegated_account) + mock_oauth2client_depr = mock.Mock() + mock_client_module = mock.Mock() + mock_signed_jwt_credentials = mock.Mock() + mock_signed_jwt_credentials_instance = mock.Mock() + mock_signed_jwt_credentials.return_value = ( + mock_signed_jwt_credentials_instance) + mock_client_module.SignedJwtAssertionCredentials = ( + mock_signed_jwt_credentials) + mock_oauth2client_depr.client = mock_client_module + mock_oauth2client_depr.__version__ = '1.4.12' + + # Mock out the oauth2client 1.4.12 oauth2client.client module to + # verify that the correct parts are called. + with mock.patch('googleads.oauth2.oauth2client', + mock_oauth2client_depr): + with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', True): + with mock.patch('%s.open' % googleads.oauth2.__name__, self.fake_open, + create=True): + googleads.oauth2.GoogleServiceAccountClient( + self.scope, client_email=self.service_account_email, + key_file=self.key_file_path, sub=self.delegated_account) + mock_signed_jwt_credentials.assert_called_once_with( + self.service_account_email, self.private_key, self.scope, + private_key_password=self.private_key_password, + user_agent='Google Ads Python Client Library', + token_uri='https://accounts.google.com/o/oauth2/token', + sub=self.delegated_account) def testCreateGoogleServiceAccountClient_JsonOAuth2Client4(self): # Mock out the oauth2client 4.0.0 oauth2client.service_account module to @@ -418,9 +438,7 @@ def testIssue123(self): See: https://github.com/googleads/googleads-python-lib/issues/123 """ with mock.patch('__builtin__.open'): - with mock.patch('oauth2client.client' - '.SignedJwtAssertionCredentials', - self.oauth2_credentials): + with mock.patch(_SA_CRED_PATH, self.oauth2_credentials): googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, '/dev/null', self.private_key_password) diff --git a/tests/test_data/test.crt b/tests/test_data/test.crt new file mode 100644 index 00000000..f87867fc --- /dev/null +++ b/tests/test_data/test.crt @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC/DCCAmWgAwIBAgIJAI3wDXTv4zWcMA0GCSqGSIb3DQEBBQUAMIGWMQswCQYD +VQQGEwJVUzELMAkGA1UECAwCTlkxETAPBgNVBAcMCE5ldyBZb3JrMQ8wDQYDVQQK +DAZHb29nbGUxIDAeBgNVBAsMF0FkcyBEZXZlbG9wZXIgUmVsYXRpb25zMQwwCgYD +VQQDDANNVFMxJjAkBgkqhkiG9w0BCQEWF21zYW5pc2NhbGNoaUBnb29nbGUuY29t +MB4XDTE3MDkxODEzNDgxMVoXDTE4MDkxODEzNDgxMVowgZYxCzAJBgNVBAYTAlVT +MQswCQYDVQQIDAJOWTERMA8GA1UEBwwITmV3IFlvcmsxDzANBgNVBAoMBkdvb2ds +ZTEgMB4GA1UECwwXQWRzIERldmVsb3BlciBSZWxhdGlvbnMxDDAKBgNVBAMMA01U +UzEmMCQGCSqGSIb3DQEJARYXbXNhbmlzY2FsY2hpQGdvb2dsZS5jb20wgZ8wDQYJ +KoZIhvcNAQEBBQADgY0AMIGJAoGBANFRqR3lsWEl7EaIIIWj9m6/1wiTu0SHsgfd +RIu+RieqkxRS2Gvnv8PIePb3P2QhtCPj6LjGQc+RB4XccyILKhK6T8cCUhEFB7F3 +JCrwJlJjShmPijSPPFyrZpj8xT/QGMQzrpxi/Qy/+1x7LG6tPHis5Fnhyzqu7i93 +6AlBzBAfAgMBAAGjUDBOMB0GA1UdDgQWBBQln01dzl4gpE6EEcbbavKiYK/6sTAf +BgNVHSMEGDAWgBQln01dzl4gpE6EEcbbavKiYK/6sTAMBgNVHRMEBTADAQH/MA0G +CSqGSIb3DQEBBQUAA4GBAAFr5vsQXMSbiFzfdPmbkQF2J+jtvXQId3zBJF4h4ZVq +VMN9Rw4+zZVq8KUf77y6z0wzdFDU4BRLPI9hEKdik2qf7kyFoNnG3JqYprW9BbCi +efh5JhiR7PpLsvqvr5x8Yv1tOe1CHKASCRlKEu79YuxQpx3mYG7N6qbFhJPsfpHY +-----END CERTIFICATE----- diff --git a/tests/testing.py b/tests/testing.py new file mode 100644 index 00000000..07d3f34c --- /dev/null +++ b/tests/testing.py @@ -0,0 +1,32 @@ +# Copyright 2017 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. + +"""Functions and classes used for unit tests.""" + + +import unittest + +import googleads.common + + +class CleanUtilityRegistryTestCase(unittest.TestCase): + """Base class for testing content affecting the UtilityRegistry. + + Subclasses will clear the UtilityRegistry between each test to ensure that it + is in a clean state before the next test. + """ + + def tearDown(self): + """Ensures that the UtilityRegistry is cleared between tests.""" + googleads.common._utility_registry.Clear() diff --git a/tests/util_test.py b/tests/util_test.py index 5081d98a..0df66036 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -168,22 +168,24 @@ def testSudsJurkoSendWithException(self): cs = self.adwords_client_with_compression.GetService('CampaignService') with mock.patch('suds.transport.http.HttpTransport.u2open') as mock_u2open: - with open(os.path.join( - test_dir, 'test_data/compact_fault_response_envelope.txt'), 'rb' - ) as handler: - url = 'https://ads.google.com' - code = 500 - msg = '' - hdrs = [] - mock_u2open.side_effect = urllib2.HTTPError(url, code, msg, hdrs, - handler) - try: - cs.get() - except suds.WebFault, e: - self.assertEqual( - 'Unmarshalling Error: For input string: ' - '"INSERT_ADVERTISER_COMPANY_ID_HERE" ', - e.fault.faultstring) + with mock.patch('httplib.HTTPMessage') as mock_headers: + mock_headers.get.return_value = None + with open(os.path.join( + test_dir, 'test_data/compact_fault_response_envelope.txt'), 'rb' + ) as handler: + url = 'https://ads.google.com' + code = 500 + msg = '' + hdrs = mock_headers + mock_u2open.side_effect = urllib2.HTTPError(url, code, msg, hdrs, + handler) + try: + cs.get() + except suds.WebFault, e: + self.assertEqual( + 'Unmarshalling Error: For input string: ' + '"INSERT_ADVERTISER_COMPANY_ID_HERE" ', + e.fault.faultstring) def testSingleErrorListIssue90(self): """Verifies that issue 90 has been resolved with the patch.""" @@ -281,7 +283,11 @@ def testGetGoogleAdsCommonFilter(self): def testFilterAtInfoLevel(self): record = mock.Mock() record.levelno = logging.INFO - record.args = [self.dev_token_template % 'test'] + + doc = mock.Mock() + doc.str.return_value = self.dev_token_template % 'test' + + record.args = [doc] self.filter.filter(record) self.assertEqual( record.args, (self.dev_token_template % self.redacted_text,)) From 89bc2a4bcb8328307fa67202355cab12dfbf9724 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 14 Nov 2017 16:45:20 -0500 Subject: [PATCH 098/180] Commiting latest changes. From a1340161bb5f42a9aba95db750fce3dfa81939ed Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 13 Feb 2018 16:07:19 -0500 Subject: [PATCH 099/180] DFP v201802 release --- ChangeLog | 12 + examples/adwords/v201702/__init__.py | 15 - .../v201702/account_management/__init__.py | 15 - .../account_management/accept_service_link.py | 62 --- .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 99 ---- .../get_account_hierarchy.py | 104 ---- .../v201702/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 222 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 128 ----- ...add_expanded_text_ad_with_upgraded_urls.py | 109 ---- .../advanced_operations/add_html5_ad.py | 112 ---- .../add_responsive_display_ad.py | 93 ---- .../add_universal_app_campaign.py | 217 -------- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 171 ------ .../v201702/basic_operations/__init__.py | 15 - .../v201702/basic_operations/add_ad_groups.py | 115 ---- .../v201702/basic_operations/add_campaigns.py | 128 ----- .../basic_operations/add_expanded_text_ads.py | 74 --- .../v201702/basic_operations/add_keywords.py | 92 --- .../v201702/basic_operations/get_ad_groups.py | 76 --- .../v201702/basic_operations/get_campaigns.py | 74 --- .../get_campaigns_with_awql.py | 64 --- .../basic_operations/get_expanded_text_ads.py | 90 --- .../v201702/basic_operations/get_keywords.py | 87 --- .../v201702/basic_operations/get_text_ads.py | 78 --- .../v201702/basic_operations/pause_ad.py | 61 -- .../v201702/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 58 -- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201702/campaign_management/__init__.py | 15 - .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 428 -------------- .../v201702/campaign_management/add_draft.py | 81 --- ...dd_keywords_using_incremental_batch_job.py | 259 --------- .../v201702/campaign_management/add_trial.py | 116 ---- .../get_all_disapproved_ads.py | 74 --- .../get_all_disapproved_ads_with_awql.py | 63 --- .../get_campaigns_by_label.py | 85 --- .../campaign_management/graduate_trial.py | 79 --- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201702/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 131 ----- .../handle_policy_violation_error.py | 167 ------ .../adwords/v201702/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 ------ .../adwords/v201702/extensions/add_prices.py | 157 ------ .../v201702/extensions/add_site_links.py | 146 ----- .../extensions/add_site_links_using_feeds.py | 236 -------- .../adwords/v201702/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 ------------------ examples/adwords/v201702/misc/__init__.py | 15 - .../v201702/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201702/misc/upload_image.py | 66 --- .../v201702/misc/upload_media_bundle.py | 60 -- .../adwords/v201702/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 180 ------ ...aign_criterion_bid_modifier_simulations.py | 96 ---- .../get_keyword_bid_simulations.py | 81 --- .../v201702/optimization/get_keyword_ideas.py | 100 ---- .../adwords/v201702/remarketing/__init__.py | 15 - .../v201702/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 70 --- .../remarketing/add_crm_based_user_list.py | 94 ---- .../remarketing/add_rule_based_user_lists.py | 186 ------- .../upload_offline_call_conversions.py | 77 --- .../remarketing/upload_offline_conversions.py | 75 --- .../adwords/v201702/reporting/__init__.py | 15 - ...oad_criteria_report_as_stream_with_awql.py | 81 --- ...criteria_report_as_stream_with_selector.py | 77 --- ...oad_criteria_report_as_string_with_awql.py | 55 -- ...criteria_report_as_string_with_selector.py | 59 -- .../download_criteria_report_with_awql.py | 59 -- .../download_criteria_report_with_selector.py | 61 -- .../v201702/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 230 -------- .../shopping/add_product_partition_tree.py | 281 ---------- .../v201702/shopping/add_product_scope.py | 104 ---- .../v201702/shopping/add_shopping_campaign.py | 125 ----- .../add_shopping_campaign_for_showcase_ads.py | 402 ------------- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201702/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 126 ----- .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201702/targeting/lookup_location.py | 82 --- .../v201705/basic_operations/get_campaigns.py | 2 - .../get_campaigns_with_awql.py | 2 - ...dd_keywords_using_incremental_batch_job.py | 5 +- .../get_campaigns_by_label.py | 2 - .../shopping/add_product_partition_tree.py | 24 +- .../add_shopping_campaign_for_showcase_ads.py | 24 +- .../v201708/basic_operations/get_campaigns.py | 2 - .../get_campaigns_with_awql.py | 2 - ...dd_keywords_using_incremental_batch_job.py | 5 +- .../get_campaigns_by_label.py | 2 - .../remarketing/upload_offline_data.py | 199 +++++++ .../shopping/add_product_partition_tree.py | 25 +- .../add_shopping_campaign_for_showcase_ads.py | 24 +- ...add_expanded_text_ad_with_upgraded_urls.py | 42 +- .../v201710/basic_operations/get_campaigns.py | 2 - .../get_campaigns_with_awql.py | 2 - .../basic_operations/update_ad_group.py | 37 +- ...dd_keywords_using_incremental_batch_job.py | 6 +- .../get_campaigns_by_label.py | 2 - .../remarketing/upload_offline_data.py | 54 +- .../shopping/add_product_partition_tree.py | 24 +- .../add_shopping_campaign_for_showcase_ads.py | 24 +- ...matic_products_for_non_sales_management.py | 84 --- ...sh_programmatic_products_to_marketplace.py | 74 --- .../company_service/update_companies.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../get_availability_forecast.py | 16 +- ...get_availability_forecast_for_line_item.py | 16 +- ...matic_products_for_non_sales_management.py | 84 --- ...sh_programmatic_products_to_marketplace.py | 69 --- .../report_service/run_inventory_report.py | 2 +- .../company_service/update_companies.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../get_availability_forecast.py | 16 +- ...get_availability_forecast_for_line_item.py | 16 +- ...matic_products_for_non_sales_management.py | 84 --- ...sh_programmatic_products_to_marketplace.py | 69 --- .../report_service/run_inventory_report.py | 2 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 14 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 18 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 14 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 16 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 14 +- .../populate_first_party_audience_segments.py | 23 +- .../update_audience_segments.py | 23 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_package_item_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 14 +- .../base_rate_service/update_base_rates.py | 16 +- .../cdn_configuration_service}/__init__.py | 0 .../create_cdn_configurations.py | 89 +++ .../get_all_cdn_configurations.py | 54 ++ .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 14 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 18 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 14 +- .../contact_service/update_contacts.py | 16 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 17 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 17 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 8 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 14 +- .../creative_service/update_creatives.py | 23 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 14 +- .../update_creative_set.py | 15 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 14 +- .../create_creative_wrappers.py | 6 +- .../deactivate_creative_wrapper.py | 22 +- .../get_active_creative_wrappers.py | 14 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 16 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 24 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 14 +- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 15 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 17 +- .../delete_custom_targeting_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- ...efined_custom_targeting_keys_and_values.py | 26 +- .../update_custom_targeting_keys.py | 16 +- .../update_custom_targeting_values.py | 15 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 14 +- .../update_exchange_rates.py | 16 +- .../get_availability_forecast.py | 20 +- ...get_availability_forecast_for_line_item.py | 17 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 15 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 115 ++++ .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 58 ++ .../inventory_service/update_ad_units.py | 15 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 15 +- .../label_service/get_active_labels.py | 14 +- .../label_service/get_all_labels.py | 2 +- .../label_service/update_labels.py | 17 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 22 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 14 +- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 22 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 14 +- .../get_recently_updated_line_items.py | 20 +- .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 16 +- .../line_item_service/update_line_items.py | 24 +- .../v201802/native_style_service}/__init__.py | 6 +- .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 2 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 37 ++ .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 19 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 33 +- .../order_service/update_orders.py | 15 +- .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 14 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 16 +- .../get_active_placements.py | 14 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 4 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 14 +- .../update_premium_rates.py | 16 +- .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 14 +- .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 14 +- .../get_all_product_packages.py | 2 +- .../product_service/__init__.py | 0 .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 16 +- .../product_service/update_products.py | 16 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 15 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 14 +- .../update_product_templates.py | 16 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 15 +- ...create_programmatic_proposal_line_items.py | 4 +- ...sal_line_items_for_non_sales_management.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 14 +- .../update_proposal_line_items.py | 15 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 14 +- .../request_buyers_acceptance.py | 17 +- .../submit_proposals_for_approval.py | 17 +- .../proposal_service/update_proposals.py | 16 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 55 ++ .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 53 ++ .../get_line_items_named_like.py | 48 ++ .../get_recent_changes.py | 94 +--- .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 14 +- ..._item_reports_for_reconciliation_report.py | 2 +- ...update_reconciliation_line_item_reports.py | 2 +- ...order_reports_for_reconciliation_report.py | 15 +- .../submit_reconciliation_order_reports.py | 2 +- ...n_report_rows_for_reconciliation_report.py | 18 +- .../update_reconciliation_report_rows.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 2 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 66 +++ .../report_service/run_delivery_report.py | 18 +- .../report_service/run_inventory_report.py | 22 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 4 +- .../run_report_with_custom_fields.py | 26 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 17 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 14 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 2 +- .../team_service/update_teams.py | 15 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 17 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 2 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 14 +- .../user_service/update_users.py | 17 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 23 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 14 +- .../update_user_team_associations.py | 17 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 36 +- .../get_workflow_approval_requests.py | 14 +- ...et_workflow_external_condition_requests.py | 14 +- ...er_workflow_external_condition_requests.py | 36 +- googleads/adwords.py | 47 -- googleads/common.py | 28 +- googleads/dfp.py | 29 +- googleads/util.py | 7 +- setup.py | 4 +- tests/adwords_test.py | 216 +++---- tests/common_test.py | 76 +-- tests/dfp_test.py | 12 +- tests/oauth2_test.py | 15 +- tests/util_test.py | 26 +- 382 files changed, 1871 insertions(+), 11895 deletions(-) delete mode 100644 examples/adwords/v201702/__init__.py delete mode 100644 examples/adwords/v201702/account_management/__init__.py delete mode 100755 examples/adwords/v201702/account_management/accept_service_link.py delete mode 100755 examples/adwords/v201702/account_management/create_account.py delete mode 100755 examples/adwords/v201702/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201702/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201702/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201702/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201702/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py delete mode 100755 examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201702/basic_operations/__init__.py delete mode 100755 examples/adwords/v201702/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201702/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201702/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201702/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201702/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201702/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201702/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201702/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201702/basic_operations/get_text_ads.py delete mode 100755 examples/adwords/v201702/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201702/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201702/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201702/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201702/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201702/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201702/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201702/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201702/campaign_management/__init__.py delete mode 100755 examples/adwords/v201702/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201702/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201702/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201702/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201702/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201702/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201702/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201702/error_handling/__init__.py delete mode 100755 examples/adwords/v201702/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201702/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201702/extensions/__init__.py delete mode 100755 examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201702/extensions/add_prices.py delete mode 100755 examples/adwords/v201702/extensions/add_site_links.py delete mode 100755 examples/adwords/v201702/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201702/migration/__init__.py delete mode 100755 examples/adwords/v201702/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201702/misc/__init__.py delete mode 100755 examples/adwords/v201702/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201702/misc/upload_image.py delete mode 100755 examples/adwords/v201702/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201702/optimization/__init__.py delete mode 100755 examples/adwords/v201702/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201702/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201702/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201702/remarketing/__init__.py delete mode 100755 examples/adwords/v201702/remarketing/add_audience.py delete mode 100755 examples/adwords/v201702/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201702/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201702/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201702/remarketing/upload_offline_call_conversions.py delete mode 100755 examples/adwords/v201702/remarketing/upload_offline_conversions.py delete mode 100644 examples/adwords/v201702/reporting/__init__.py delete mode 100755 examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py delete mode 100755 examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py delete mode 100755 examples/adwords/v201702/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201702/reporting/download_criteria_report_with_selector.py delete mode 100755 examples/adwords/v201702/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201702/reporting/parallel_report_download.py delete mode 100755 examples/adwords/v201702/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201702/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201702/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py delete mode 100755 examples/adwords/v201702/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201702/targeting/__init__.py delete mode 100755 examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201702/targeting/lookup_location.py create mode 100755 examples/adwords/v201708/remarketing/upload_offline_data.py delete mode 100755 examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py delete mode 100755 examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py delete mode 100755 examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py delete mode 100755 examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py delete mode 100755 examples/dfp/v201711/product_service/create_programmatic_products_for_non_sales_management.py delete mode 100755 examples/dfp/v201711/product_service/publish_programmatic_products_to_marketplace.py rename examples/dfp/{v201705 => v201802}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201705 => v201802}/activity_group_service/get_active_activity_groups.py (86%) rename examples/dfp/{v201705 => v201802}/activity_group_service/get_all_activity_groups.py (97%) rename examples/dfp/{v201705 => v201802}/activity_group_service/update_activity_groups.py (87%) rename examples/dfp/{v201705 => v201802}/activity_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/activity_service/create_activities.py (99%) rename examples/dfp/{v201705 => v201802}/activity_service/get_active_activities.py (87%) rename examples/dfp/{v201705 => v201802}/activity_service/get_all_activities.py (99%) rename examples/dfp/{v201705 => v201802}/activity_service/update_activities.py (90%) rename examples/dfp/{v201705 => v201802}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/audience_segment_service/create_audience_segments.py (98%) rename examples/dfp/{v201705 => v201802}/audience_segment_service/get_all_audience_segments.py (97%) rename examples/dfp/{v201705 => v201802}/audience_segment_service/get_first_party_audience_segments.py (86%) rename examples/dfp/{v201705 => v201802}/audience_segment_service/populate_first_party_audience_segments.py (80%) rename examples/dfp/{v201705 => v201802}/audience_segment_service/update_audience_segments.py (81%) rename examples/dfp/{v201705 => v201802}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201705 => v201802}/base_rate_service/create_product_package_item_base_rates.py (99%) rename examples/dfp/{v201705 => v201802}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201705 => v201802}/base_rate_service/get_all_base_rates.py (99%) rename examples/dfp/{v201705 => v201802}/base_rate_service/get_base_rates_for_rate_card.py (88%) rename examples/dfp/{v201705 => v201802}/base_rate_service/update_base_rates.py (90%) rename examples/dfp/{v201705/native_style_service => v201802/cdn_configuration_service}/__init__.py (100%) create mode 100755 examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py create mode 100755 examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py rename examples/dfp/{v201705 => v201802}/company_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/company_service/create_companies.py (99%) rename examples/dfp/{v201705 => v201802}/company_service/get_advertisers.py (88%) rename examples/dfp/{v201705 => v201802}/company_service/get_all_companies.py (99%) rename examples/dfp/{v201705 => v201802}/company_service/update_companies.py (89%) rename examples/dfp/{v201705 => v201802}/contact_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201705 => v201802}/contact_service/get_all_contacts.py (99%) rename examples/dfp/{v201705 => v201802}/contact_service/get_uninvited_contacts.py (87%) rename examples/dfp/{v201705 => v201802}/contact_service/update_contacts.py (90%) rename examples/dfp/{v201705 => v201802}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201705 => v201802}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (90%) rename examples/dfp/{v201705 => v201802}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201705 => v201802}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (91%) rename examples/dfp/{v201705 => v201802}/content_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/content_service/get_all_content.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/creative_service/copy_image_creatives.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/create_native_creative.py (94%) rename examples/dfp/{v201705 => v201802}/creative_service/get_all_creatives.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/get_image_creatives.py (86%) rename examples/dfp/{v201705 => v201802}/creative_service/update_creatives.py (85%) rename examples/dfp/{v201705 => v201802}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201705 => v201802}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201705 => v201802}/creative_set_service/get_all_creative_sets.py (97%) rename examples/dfp/{v201705 => v201802}/creative_set_service/get_creative_sets_for_master_creative.py (85%) rename examples/dfp/{v201705 => v201802}/creative_set_service/update_creative_set.py (89%) rename examples/dfp/{v201705 => v201802}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/creative_template_service/get_all_creative_templates.py (97%) rename examples/dfp/{v201705 => v201802}/creative_template_service/get_system_defined_creative_templates.py (86%) rename examples/dfp/{v201705 => v201802}/creative_wrapper_service/create_creative_wrappers.py (91%) rename examples/dfp/{v201705 => v201802}/creative_wrapper_service/deactivate_creative_wrapper.py (85%) rename examples/dfp/{v201705 => v201802}/creative_wrapper_service/get_active_creative_wrappers.py (86%) rename examples/dfp/{v201705 => v201802}/creative_wrapper_service/get_all_creative_wrappers.py (97%) rename examples/dfp/{v201705 => v201802}/creative_wrapper_service/update_creative_wrappers.py (88%) rename examples/dfp/{v201705 => v201802}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201705 => v201802}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201705 => v201802}/custom_field_service/deactivate_all_line_item_custom_fields.py (82%) rename examples/dfp/{v201705 => v201802}/custom_field_service/get_all_custom_fields.py (97%) rename examples/dfp/{v201705 => v201802}/custom_field_service/get_custom_fields_for_line_items.py (85%) rename examples/dfp/{v201705 => v201802}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201705 => v201802}/custom_field_service/update_custom_fields.py (88%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/delete_custom_targeting_keys.py (90%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/delete_custom_targeting_values.py (98%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (78%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/update_custom_targeting_keys.py (88%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/update_custom_targeting_values.py (88%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/get_all_exchange_rates.py (97%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/get_exchange_rates_for_currency_code.py (86%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/update_exchange_rates.py (87%) rename examples/dfp/{v201705 => v201802}/forecast_service/get_availability_forecast.py (90%) rename examples/dfp/{v201705 => v201802}/forecast_service/get_availability_forecast_for_line_item.py (83%) rename examples/dfp/{v201705 => v201802}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/dfp/{v201705 => v201802}/inventory_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/inventory_service/archive_ad_units.py (90%) rename examples/dfp/{v201705 => v201802}/inventory_service/create_ad_units.py (99%) create mode 100755 examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py rename examples/dfp/{v201705 => v201802}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/dfp/{v201705 => v201802}/inventory_service/get_all_ad_units.py (99%) create mode 100755 examples/dfp/v201802/inventory_service/get_top_level_ad_units.py rename examples/dfp/{v201705 => v201802}/inventory_service/update_ad_units.py (92%) rename examples/dfp/{v201705 => v201802}/label_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/label_service/create_labels.py (99%) rename examples/dfp/{v201705 => v201802}/label_service/deactivate_labels.py (89%) rename examples/dfp/{v201705 => v201802}/label_service/get_active_labels.py (87%) rename examples/dfp/{v201705 => v201802}/label_service/get_all_labels.py (99%) rename examples/dfp/{v201705 => v201802}/label_service/update_labels.py (87%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/deactivate_licas.py (83%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/get_all_licas.py (97%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/get_licas_for_line_item.py (87%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201705 => v201802}/line_item_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/line_item_service/activate_line_items.py (86%) rename examples/dfp/{v201705 => v201802}/line_item_service/create_line_items.py (99%) rename examples/dfp/{v201705 => v201802}/line_item_service/create_video_line_item.py (99%) rename examples/dfp/{v201705 => v201802}/line_item_service/get_all_line_items.py (99%) rename examples/dfp/{v201705 => v201802}/line_item_service/get_line_items_that_need_creatives.py (86%) rename examples/dfp/{v201705 => v201802}/line_item_service/get_recently_updated_line_items.py (82%) rename examples/dfp/{v201705 => v201802}/line_item_service/pause_line_items.py (99%) rename examples/dfp/{v201705 => v201802}/line_item_service/target_custom_criteria.py (93%) rename examples/dfp/{v201705 => v201802}/line_item_service/update_line_items.py (84%) rename examples/{adwords/v201702/shopping => dfp/v201802/native_style_service}/__init__.py (87%) mode change 100644 => 100755 rename examples/dfp/{v201705 => v201802}/native_style_service/create_native_styles.py (98%) rename examples/dfp/{v201705 => v201802}/native_style_service/get_all_native_styles.py (96%) rename examples/dfp/{v201705 => v201802}/network_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/network_service/get_all_networks.py (99%) create mode 100755 examples/dfp/v201802/network_service/get_current_network.py rename examples/dfp/{v201705 => v201802}/network_service/make_test_network.py (99%) rename examples/dfp/{v201705 => v201802}/order_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/order_service/approve_orders.py (84%) rename examples/dfp/{v201705 => v201802}/order_service/create_orders.py (99%) rename examples/dfp/{v201705 => v201802}/order_service/get_all_orders.py (99%) rename examples/dfp/{v201705 => v201802}/order_service/get_orders_starting_soon.py (73%) rename examples/dfp/{v201705 => v201802}/order_service/update_orders.py (90%) rename examples/dfp/{v201705 => v201802}/package_service/create_packages.py (99%) rename examples/dfp/{v201705 => v201802}/package_service/create_proposal_line_items_from_packages.py (99%) rename examples/dfp/{v201705 => v201802}/package_service/get_all_packages.py (99%) rename examples/dfp/{v201705 => v201802}/package_service/get_in_progress_packages.py (87%) rename examples/dfp/{v201705 => v201802}/placement_service/create_placements.py (99%) rename examples/dfp/{v201705 => v201802}/placement_service/deactivate_placements.py (88%) rename examples/dfp/{v201705 => v201802}/placement_service/get_active_placements.py (87%) rename examples/dfp/{v201705 => v201802}/placement_service/get_all_placements.py (99%) rename examples/dfp/{v201705 => v201802}/placement_service/update_placements.py (96%) rename examples/dfp/{v201705 => v201802}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/premium_rate_service/create_premium_rates.py (97%) rename examples/dfp/{v201705 => v201802}/premium_rate_service/get_all_premium_rates.py (97%) rename examples/dfp/{v201705 => v201802}/premium_rate_service/get_premium_rates_for_rate_card.py (87%) rename examples/dfp/{v201705 => v201802}/premium_rate_service/update_premium_rates.py (90%) rename examples/dfp/{v201705 => v201802}/product_package_item_service/create_product_package_item.py (99%) rename examples/dfp/{v201705 => v201802}/product_package_item_service/get_all_product_package_items.py (97%) rename examples/dfp/{v201705 => v201802}/product_package_item_service/get_product_package_items_for_product_package.py (86%) rename examples/dfp/{v201705 => v201802}/product_package_service/create_product_packages.py (96%) rename examples/dfp/{v201705 => v201802}/product_package_service/get_active_product_packages.py (86%) rename examples/dfp/{v201705 => v201802}/product_package_service/get_all_product_packages.py (97%) rename examples/dfp/{v201705 => v201802}/product_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/product_service/get_all_products.py (99%) rename examples/dfp/{v201705 => v201802}/product_service/get_products_for_product_template.py (86%) rename examples/dfp/{v201705 => v201802}/product_service/update_products.py (90%) rename examples/dfp/{v201705 => v201802}/product_template_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/product_template_service/activate_product_templates.py (89%) rename examples/dfp/{v201705 => v201802}/product_template_service/create_product_templates.py (97%) rename examples/dfp/{v201705 => v201802}/product_template_service/create_programmatic_product_templates.py (96%) rename examples/dfp/{v201705 => v201802}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201705 => v201802}/product_template_service/get_sponsorship_product_templates.py (85%) rename examples/dfp/{v201705 => v201802}/product_template_service/update_product_templates.py (90%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/archive_proposal_line_items.py (89%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/create_programmatic_proposal_line_items.py (98%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (98%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/get_all_proposal_line_items.py (97%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (86%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/update_proposal_line_items.py (89%) rename examples/dfp/{v201705 => v201802}/proposal_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/proposal_service/create_programmatic_proposals.py (98%) rename examples/dfp/{v201705 => v201802}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (99%) rename examples/dfp/{v201705 => v201802}/proposal_service/create_proposals.py (99%) rename examples/dfp/{v201705 => v201802}/proposal_service/get_all_proposals.py (99%) rename examples/dfp/{v201705 => v201802}/proposal_service/get_marketplace_comments.py (97%) rename examples/dfp/{v201705 => v201802}/proposal_service/get_proposals_pending_approval.py (87%) rename examples/dfp/{v201705 => v201802}/proposal_service/request_buyers_acceptance.py (89%) rename examples/dfp/{v201705 => v201802}/proposal_service/submit_proposals_for_approval.py (88%) rename examples/dfp/{v201705 => v201802}/proposal_service/update_proposals.py (89%) rename examples/dfp/{v201705 => v201802}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/publisher_query_language_service/fetch_match_tables.py (96%) create mode 100755 examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py rename examples/dfp/{v201705 => v201802}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) create mode 100755 examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py create mode 100755 examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py rename examples/dfp/{v201705 => v201802}/publisher_query_language_service/get_recent_changes.py (66%) rename examples/dfp/{v201705 => v201802}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/rate_card_service/create_rate_cards.py (99%) rename examples/dfp/{v201705 => v201802}/rate_card_service/get_all_rate_cards.py (99%) rename examples/dfp/{v201705 => v201802}/rate_card_service/get_marketplace_rate_cards.py (87%) rename examples/dfp/{v201705 => v201802}/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (97%) rename examples/dfp/{v201705 => v201802}/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (97%) rename examples/dfp/{v201705 => v201802}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (85%) rename examples/dfp/{v201705 => v201802}/reconciliation_order_report_service/submit_reconciliation_order_reports.py (97%) rename examples/dfp/{v201705 => v201802}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (85%) rename examples/dfp/{v201705 => v201802}/reconciliation_report_row_service/update_reconciliation_report_rows.py (97%) rename examples/dfp/{v201705 => v201802}/reconciliation_report_service/get_all_reconciliation_reports.py (97%) rename examples/dfp/{v201705 => v201802}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (97%) rename examples/dfp/{v201705 => v201802}/report_service/__init__.py (100%) create mode 100755 examples/dfp/v201802/report_service/run_ad_exchange_report.py rename examples/dfp/{v201705 => v201802}/report_service/run_delivery_report.py (88%) rename examples/dfp/{v201705 => v201802}/report_service/run_inventory_report.py (83%) rename examples/dfp/{v201705 => v201802}/report_service/run_reach_report.py (96%) rename examples/dfp/{v201705 => v201802}/report_service/run_report_and_create_match_table.py (97%) rename examples/dfp/{v201705 => v201802}/report_service/run_report_with_custom_fields.py (85%) rename examples/dfp/{v201705 => v201802}/report_service/run_sales_report.py (96%) rename examples/dfp/{v201705 => v201802}/report_service/run_saved_query.py (89%) rename examples/dfp/{v201705 => v201802}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (97%) rename examples/dfp/{v201705 => v201802}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) rename examples/dfp/{v201705 => v201802}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (86%) rename examples/dfp/{v201705 => v201802}/team_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/team_service/create_teams.py (96%) rename examples/dfp/{v201705 => v201802}/team_service/get_all_teams.py (95%) rename examples/dfp/{v201705 => v201802}/team_service/update_teams.py (87%) rename examples/dfp/{v201705 => v201802}/user_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/user_service/create_users.py (95%) rename examples/dfp/{v201705 => v201802}/user_service/deactivate_users.py (86%) rename examples/dfp/{v201705 => v201802}/user_service/get_all_roles.py (100%) rename examples/dfp/{v201705 => v201802}/user_service/get_all_users.py (95%) rename examples/dfp/{v201705 => v201802}/user_service/get_current_user.py (94%) rename examples/dfp/{v201705 => v201802}/user_service/get_user_by_email_address.py (85%) rename examples/dfp/{v201705 => v201802}/user_service/update_users.py (83%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/delete_user_team_associations.py (87%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/get_all_user_team_associations.py (97%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/get_user_team_associations_for_user.py (87%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/update_user_team_associations.py (89%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/approve_workflow_approval_requests.py (76%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/get_workflow_approval_requests.py (87%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/get_workflow_external_condition_requests.py (86%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/trigger_workflow_external_condition_requests.py (78%) diff --git a/ChangeLog b/ChangeLog index 4f962b18..0bac30da 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,15 @@ +10.0.0 -- 02/13/18 +* Added support and examples for DFP v201802. +* Removed support and examples for AdWords v201702. +* Resolved issues: +- Issue 229: https://github.com/googleads/googleads-python-lib/issues/229 +- Issue 236: https://github.com/googleads/googleads-python-lib/issues/236 + +9.0.1 -- 12/22/17 +* Improved Python 3 compatibility of library and tests. +* Fixed reported issue with the ProductPartitionHelper utility used in AdWords + shopping examples. + 9.0.0 -- 11/14/17 * Added support and examples for DFP v201711 * Removed support and examples for DFP v201611 diff --git a/examples/adwords/v201702/__init__.py b/examples/adwords/v201702/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201702/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201702/account_management/__init__.py b/examples/adwords/v201702/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201702/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201702/account_management/accept_service_link.py b/examples/adwords/v201702/account_management/accept_service_link.py deleted file mode 100755 index a6d6a261..00000000 --- a/examples/adwords/v201702/account_management/accept_service_link.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' - - -def main(client, service_link_id): - # Initialize appropriate service. - customer_service = client.GetService( - 'CustomerService', version='v201702') - - # Create the operation to set the status to ACTIVE. - operations = [{ - 'operator': 'SET', - 'operand': { - 'serviceLinkId': service_link_id, - 'serviceType': 'MERCHANT_CENTER', - 'linkStatus': 'ACTIVE', - } - }] - - # Update the service link. - mutated_service_links = customer_service.mutateServiceLinks(operations) - - # Display results. - for mutated_service_link in mutated_service_links: - print ('Service link with service link ID "%s", type "%s" was updated ' - 'to status: "%s".' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201702/account_management/create_account.py b/examples/adwords/v201702/account_management/create_account.py deleted file mode 100755 index 55bbcba6..00000000 --- a/examples/adwords/v201702/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201702') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID "%s" was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/account_management/get_account_changes.py b/examples/adwords/v201702/account_management/get_account_changes.py deleted file mode 100755 index d97a6827..00000000 --- a/examples/adwords/v201702/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201702') - campaign_service = client.GetService('CampaignService', version='v201702') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id "%s" has change status "%s".' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id "%s" has change status "%s".' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/account_management/get_account_hierarchy.py b/examples/adwords/v201702/account_management/get_account_hierarchy.py deleted file mode 100755 index e95787ee..00000000 --- a/examples/adwords/v201702/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201702') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/advanced_operations/__init__.py b/examples/adwords/v201702/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201702/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py b/examples/adwords/v201702/advanced_operations/add_ad_customizer.py deleted file mode 100755 index a01996cf..00000000 --- a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates ExpandedTextAds that use ad customizations for specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no ExpandedTextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201702') - - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'headlinePart2': 'Only {=%s.Price}' % feed_name, - 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': expanded_text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID "%s", type "%s", and status "%s".' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201702') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name "%s" and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201702') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 71bfb4a3..00000000 --- a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201702') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index e859e050..00000000 --- a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Optionally, you may specify a landscape image. The image needs to be in a - # BASE64 encoded form. Here we download a demo image and encode it for this - # ad. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) - .decode('utf-8')) - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - }, - { - 'name': 'landscapeImage', - 'fieldMedia': { - 'xsi_type': 'Image', - 'data': image_data - }, - 'type': 'IMAGE' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py deleted file mode 100755 index 0aea3dd7..00000000 --- a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Create the expanded text ad - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': expanded_text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_html5_ad.py b/examples/adwords/v201702/advanced_operations/add_html5_ad.py deleted file mode 100755 index 77b7cfd4..00000000 --- a/examples/adwords/v201702/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index b38bc350..00000000 --- a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - media_service = client.GetService('MediaService', version='v201702') - - try: - # Create image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = (base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) - .decode('utf-8')) - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - # Make the upload request - image = media_service.upload(image)[0] - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'] - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py deleted file mode 100755 index 72e19e88..00000000 --- a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Universal App campaign. - -To get campaigns, run get_campaigns.py. To upload image assets for this -campaign, run upload_image.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201702') - - budget_id = CreateBudget(client) - - # Create the Universal App campaign. - universal_app_campaign = { - 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'MULTI_CHANNEL', - 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', - # Set the campaign's bidding strategy. Universal app campaigns only - # support TARGET_CPA bidding strategy. - 'biddingStrategyConfiguration': { - # Set the target CPA to $1 / app install. - 'biddingScheme': { - 'xsi_type': 'TargetCpaBiddingScheme', - 'targetCpa': { - 'microAmount': '1000000' - } - }, - 'biddingStrategyType': 'TARGET_CPA' - }, - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - - universal_app_campaign['settings'] = [ - # Set the campaign's assets and ad text ideas. These values will - # be used to generate ads. - { - 'xsi_type': 'UniversalAppCampaignSetting', - 'appId': 'com.labpixies.colordrips', - 'description1': 'A cool puzzle game', - 'description2': 'Remove connected blocks', - 'description3': '3 difficulty levels', - 'description4': '4 colorful fun skins', - # Optional: You can set up to 10 image assets for your campaign. - # See upload_image.py for an example on how to upload images. - # - # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] - } - ] - - # Optimize this campaign for getting new users for your app. - universal_app_campaign_setting = universal_app_campaign['settings'][0] - universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( - 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') - - # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, - # then also specify your in-app conversion types so AdWords can focus your - # campaign on people who are most likely to complete the corresponding in-app - # actions. - # - # Conversions type IDs can be retrieved using ConversionTrackerService.get. - # universal_app_campaign['selectiveOptimization'] = { - # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] - # } - - # Optional: Set the campaign settings for Advanced location options. - universal_app_campaign['settings'].append({ - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - }) - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': universal_app_campaign - }] - - campaigns = campaign_service.mutate(operations)['value'] - - # Display results. - if campaigns: - for campaign in campaigns: - print ('Universal App Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - # Optional: Set the campaign's location and language targeting. No other - # targeting criteria can be used for Universal App campaigns. - SetCampaignTargetingCriteria(client, campaign) - else: - print 'No Universal App campaigns were added.' - - -def CreateBudget(client): - """Creates a budget and returns its budgetId. - - Args: - client: An AdWordsClient instance. - - Returns: - An int budgetId for the created Budget. - """ - budget_service = client.GetService('BudgetService', version='v201702') - - # Create a budget. - budget = { - 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': False - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Create the budget and return its ID. - budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - - return budget_id - - -def SetCampaignTargetingCriteria(client, campaign): - """Sets targeting criteria for the given campaign. - - Args: - client: An AdWordsClient instance. - campaign: A suds object representing the campaign we wish to attach - targeting criteria. - """ - campaign_criterion_service = client.GetService('CampaignCriterionService') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - criteria = [ - { - 'xsi_type': 'Location', - 'id': 21137 # California - }, - { - 'xsi_type': 'Location', - 'id': 2484 # Mexico - }, - { - 'xsi_type': 'Language', - 'id': 1000 # English - }, - { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - ] - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign['id'], - 'criterion': criterion - } - } for criterion in criteria] - - response = campaign_criterion_service.mutate(operations) - - if response and 'value' in response: - # Display the added campaign targets. - for criterion in response['value']: - print ('Campaign criteria of type "%s" and id "%s" was added.' - % (criterion['criterion']['type'], - criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 4fcf2ef8..00000000 --- a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201702') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201702') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201702') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index edc6c1df..00000000 --- a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201702') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201702') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 21cdf0eb..00000000 --- a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201702') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 98dd1275..00000000 --- a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201702') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201702') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201702/basic_operations/__init__.py b/examples/adwords/v201702/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201702/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201702/basic_operations/add_ad_groups.py b/examples/adwords/v201702/basic_operations/add_ad_groups.py deleted file mode 100755 index 9dad1690..00000000 --- a/examples/adwords/v201702/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201702') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/basic_operations/add_campaigns.py b/examples/adwords/v201702/basic_operations/add_campaigns.py deleted file mode 100755 index 49dd97f3..00000000 --- a/examples/adwords/v201702/basic_operations/add_campaigns.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201702') - budget_service = client.GetService('BudgetService', version='v201702') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index 45a007d3..00000000 --- a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/add_keywords.py b/examples/adwords/v201702/basic_operations/add_keywords.py deleted file mode 100755 index 437ffbf2..00000000 --- a/examples/adwords/v201702/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id "%s", criterion id ' - '"%s", text "%s", and match type "%s" was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/get_ad_groups.py b/examples/adwords/v201702/basic_operations/get_ad_groups.py deleted file mode 100755 index 0ae7272b..00000000 --- a/examples/adwords/v201702/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201702') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name "%s", id "%s" and status "%s" was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/basic_operations/get_campaigns.py b/examples/adwords/v201702/basic_operations/get_campaigns.py deleted file mode 100755 index 489cddc1..00000000 --- a/examples/adwords/v201702/basic_operations/get_campaigns.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import time -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 58497c61..00000000 --- a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index 414b76e7..00000000 --- a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/get_keywords.py b/examples/adwords/v201702/basic_operations/get_keywords.py deleted file mode 100755 index 83d6ee18..00000000 --- a/examples/adwords/v201702/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID "%s", type "%s", text "%s", and match type ' - '"%s" was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/get_text_ads.py b/examples/adwords/v201702/basic_operations/get_text_ads.py deleted file mode 100755 index 424ceef6..00000000 --- a/examples/adwords/v201702/basic_operations/get_text_ads.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 text ads for a given ad group. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('Ad with id "%s", status "%s", and of type "%s" was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/pause_ad.py b/examples/adwords/v201702/basic_operations/pause_ad.py deleted file mode 100755 index c4822b5e..00000000 --- a/examples/adwords/v201702/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id "%s" was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201702/basic_operations/remove_ad.py b/examples/adwords/v201702/basic_operations/remove_ad.py deleted file mode 100755 index ab8c5d2a..00000000 --- a/examples/adwords/v201702/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id "%s" and type "%s" was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201702/basic_operations/remove_ad_group.py b/examples/adwords/v201702/basic_operations/remove_ad_group.py deleted file mode 100755 index 374865a2..00000000 --- a/examples/adwords/v201702/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201702') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name "%s" and id "%s" was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/remove_campaign.py b/examples/adwords/v201702/basic_operations/remove_campaign.py deleted file mode 100755 index 3252c2fd..00000000 --- a/examples/adwords/v201702/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name "%s" and id "%s" was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/basic_operations/remove_keyword.py b/examples/adwords/v201702/basic_operations/remove_keyword.py deleted file mode 100755 index a09c35bb..00000000 --- a/examples/adwords/v201702/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id "%s", criterion id "%s", ' - 'and type "%s" was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201702/basic_operations/update_ad_group.py b/examples/adwords/v201702/basic_operations/update_ad_group.py deleted file mode 100755 index a682b3ea..00000000 --- a/examples/adwords/v201702/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201702') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/basic_operations/update_campaign.py b/examples/adwords/v201702/basic_operations/update_campaign.py deleted file mode 100755 index 8505e9c1..00000000 --- a/examples/adwords/v201702/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/basic_operations/update_keyword.py b/examples/adwords/v201702/basic_operations/update_keyword.py deleted file mode 100755 index 5596781f..00000000 --- a/examples/adwords/v201702/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id "%s" and criterion id ' - '"%s" currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: "%s", value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201702/campaign_management/__init__.py b/examples/adwords/v201702/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201702/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201702/campaign_management/add_campaign_labels.py b/examples/adwords/v201702/campaign_management/add_campaign_labels.py deleted file mode 100755 index e6b5f147..00000000 --- a/examples/adwords/v201702/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index 9d6dfc03..00000000 --- a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,428 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201702') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201702') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding an ExpandedTextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new ExpandedTextAd for - each of the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once - # you've added targeting and the ads are ready to serve. - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201702') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201702/campaign_management/add_draft.py b/examples/adwords/v201702/campaign_management/add_draft.py deleted file mode 100755 index 6cd4fcc6..00000000 --- a/examples/adwords/v201702/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201702') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201702') - - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index 54aefb49..00000000 --- a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201702') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201702') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201702') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201702') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/campaign_management/add_trial.py b/examples/adwords/v201702/campaign_management/add_trial.py deleted file mode 100755 index a77755a9..00000000 --- a/examples/adwords/v201702/campaign_management/add_trial.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201702') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201702') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 0178909e..00000000 --- a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id "%s" was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 87e65980..00000000 --- a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id "%s" was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 38e537af..00000000 --- a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id "%s", name "%s", and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201702/campaign_management/graduate_trial.py b/examples/adwords/v201702/campaign_management/graduate_trial.py deleted file mode 100755 index 324d00f1..00000000 --- a/examples/adwords/v201702/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201702') - budget_service = client.GetService('BudgetService', version='v201702') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201702/campaign_management/set_ad_parameters.py b/examples/adwords/v201702/campaign_management/set_ad_parameters.py deleted file mode 100755 index 0a4e05b8..00000000 --- a/examples/adwords/v201702/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - ad_param_service = client.GetService('AdParamService', version='v201702') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id "%s" was successfully added to an ad group with ' - 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text "%s" was successfully set for criterion ' - 'with id "%s" and ad group id "%s".' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index 9967bed8..00000000 --- a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201702') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' - 'was updated with bid modifier "%s".' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201702/campaign_management/validate_text_ad.py b/examples/adwords/v201702/campaign_management/validate_text_ad.py deleted file mode 100755 index 472a1591..00000000 --- a/examples/adwords/v201702/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -No objects will be created, but exceptions will still be returned. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct operations to add an expanded text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'] - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for all astronauts in orbit', - 'finalUrls': ['http://www.example.com'], - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with "%s".' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/error_handling/__init__.py b/examples/adwords/v201702/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201702/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201702/error_handling/handle_partial_failures.py b/examples/adwords/v201702/error_handling/handle_partial_failures.py deleted file mode 100755 index fb040cc9..00000000 --- a/examples/adwords/v201702/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id "%s", ' - 'criterion id "%s", text "%s", and match type "%s" was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - if (first_field_path_element and - first_field_path_element['field'] == 'operations' and - first_field_path_element['index']): - operation_index = first_field_path_element['index'] - - adgroup_criterion = operations[operation_index]['operand'] - - print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' - 'a failure for the following reason: %s.' - % (adgroup_criterion['adGroupId'], - adgroup_criterion['criterion']['text'], - error['errorString'])) - else: - print ('A failure has occured for the following reasons: %s\n' - % error['errorString']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py b/examples/adwords/v201702/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 4872235f..00000000 --- a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201702') - - # Create expanded text ad that violates an exemptable policy. - exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise!!!', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - # Create text ad that violates a non-exemptable policy. - non_exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise with too long of a headline.', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - operations = [exemptable_expanded_text_ad_operation, - non_exemptable_expanded_text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - # Get the index of the failed operation from the error's field path - # elements. - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - # If the operation index is not present on the first error field path - # element, then there's no way to determine which operation to remove, - # so simply throw the exception. - if (not (first_field_path_element - and first_field_path_element['field'] == 'operations' - and first_field_path_element['index'])): - raise e - - operation_index = first_field_path_element['index'] - index = int(operation_index[0]) - operation = operations[index] - if not HandleAPIError(error, operation): - # Set non-exemptable operation to None to mark for deletion. - print ('Removing operation with non-exemptable error at index %s.' - % operation_index) - operations[index] = None - - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is "%s".' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -def HandleAPIError(error, operation): - """Makes an exemption for exemptable PolicyViolationErrors. - - Args: - error: the error associated with the given operation. - operation: the operation associated with the given error. - - Returns: - A boolean that is True if the given error was an exemptable - PolicyViolationError; otherwise, returns False. - """ - is_exemptable = False - - # Determine if the operation can be resubmitted with an exemption request. - if error['ApiError.Type'] == 'PolicyViolationError': - expanded_text_ad = operation['operand']['ad'] - is_exemptable = (error['isExemptable'] if 'isExemptable' in error else - False) - print ('Ad with headline "%s - %s" violated %s policy "%s".' % - (expanded_text_ad['headlinePart1'], - expanded_text_ad['headlinePart2'], - 'exemptable' if is_exemptable else 'non-exemptable', - error['externalPolicyName'])) - - if is_exemptable: - # Add exemption request to the operation. - print ('Adding exemption request for policy name "%s" on text "%s".' - % (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({'key': error['key']}) - - return is_exemptable - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/extensions/__init__.py b/examples/adwords/v201702/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201702/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index c346ce2a..00000000 --- a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201702').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201702') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201702/extensions/add_prices.py b/examples/adwords/v201702/extensions/add_prices.py deleted file mode 100755 index 62d0f3a8..00000000 --- a/examples/adwords/v201702/extensions/add_prices.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a price extension and associates it with an account. - -Campaign targeting is also set usin the specified campaign ID. To get campaigns, -run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -MICROS_PER_DOLLAR = 1000000 - - -def main(client, campaign_id): - # Initialize appropriate service. - customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201702') - - # To create a price extension, at least three table rows are needed. - table_rows = [ - CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', - 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', - final_mobile_url='http://m.example.com/scrubs'), - CreatePriceTableRow('Hair Cuts', 'Once a month', - 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url='http://m.example.com/haircuts'), - CreatePriceTableRow('Skin Care Package', 'Four times a month', - 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url=( - 'http://m.example.com/skincarepackage')) - ] - - # Create the price extension feed item. - customer_extension_setting = { - 'extensionType': 'PRICE', - 'extensionSetting': { - 'extensions': [{ - 'priceExtensionType': 'SERVICES', - 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', - 'language': 'en', - 'campaignTargeting': { - 'TargetingCampaignId': campaign_id - }, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': 'SATURDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 22, - 'endMinute': 'ZERO' - }, - { - 'dayOfWeek': 'SUNDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 18, - 'endMinute': 'ZERO' - } - ] - }, - 'tableRows': table_rows, - # Price qualifier is optional. - 'priceQualifier': 'FROM', - 'xsi_type': 'PriceFeedItem' - }] - } - } - - # Create an operation to add the feed. - operations = [{ - 'operator': 'ADD', - 'operand': customer_extension_setting - }] - - # Add the price extension. - response = customer_extension_setting_service.mutate(operations) - - # Print the results. - if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit, final_mobile_url=None): - """Helper function to generate a single row of a price table. - - Args: - header: A str containing the header text of this row. - description: A str description of this row in the price table. - final_url: A str containing the final URL after all cross domain redirects. - price_in_micros: An int indicating the price of the given currency in - micros. - currency_code: A str indicating the currency code being used. - price_unit: A str enum indicating the price unit for this row. - final_mobile_url: A str containing the final mobile URL after all cross - domain redirects. - - Returns: - A dictionary containing the contents of the generated price table row. - """ - table_row = { - 'header': header, - 'description': description, - 'finalUrls': {'urls': [final_url]}, - 'price': { - 'money': { - 'microAmount': price_in_micros, - }, - 'currencyCode': currency_code - }, - 'priceUnit': price_unit, - 'xsi_type': 'PriceTableRow' - } - - if final_mobile_url: - table_row['finalMobileUrls'] = { - 'urls': [final_mobile_url] - } - - return table_row - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/extensions/add_site_links.py b/examples/adwords/v201702/extensions/add_site_links.py deleted file mode 100755 index ef29007c..00000000 --- a/examples/adwords/v201702/extensions/add_site_links.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201702') - customer_service = client.GetService('CustomerService', version='v201702') - # Find the matching customer and its time zone. The getCustomers method will - # return a single Customer object corresponding to the configured - # clientCustomerId. - customer = customer_service.getCustomers()[0] - customer_tz = timezone(customer['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840}, - # Restrict targeting only to people physically within the United States. - # Otherwise, this could also show to people interested in the United - # States, but not physically located there. - 'geoTargetingRestriction': { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py b/examples/adwords/v201702/extensions/add_site_links_using_feeds.py deleted file mode 100755 index e7e83d18..00000000 --- a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_2_TEXT = '3' -PLACEHOLDER_FIELD_LINE_3_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201702') - feed_item_service = client.GetService('FeedItemService', version='v201702') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201702') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201702') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 2 Description'}, - {'type': 'STRING', 'name': 'Line 3 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_2_feed_attribute_id = feed['attributes'][2]['id'] - line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name "%s" and ID "%s" was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - sitelinks_data['line3FeedId'] = line_3_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line2': 'Home line 2', 'line3': 'Home line 3'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line2': 'Support line 2', 'line3': 'Support line 3'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line2': 'Products line 2', 'line3': 'Products line 3'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'stringValue': item['line3'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - feed_item['geoTargetingRestriction'] = { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/migration/__init__.py b/examples/adwords/v201702/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201702/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201702/migration/migrate_to_extension_settings.py b/examples/adwords/v201702/migration/migrate_to_extension_settings.py deleted file mode 100755 index efb27656..00000000 --- a/examples/adwords/v201702/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201702') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201702') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201702') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201702') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201702') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201702') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201702') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/misc/__init__.py b/examples/adwords/v201702/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201702/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201702/misc/get_all_images_and_videos.py b/examples/adwords/v201702/misc/get_all_images_and_videos.py deleted file mode 100755 index 530b1dad..00000000 --- a/examples/adwords/v201702/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201702') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id "%s" was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/misc/upload_image.py b/examples/adwords/v201702/misc/upload_image.py deleted file mode 100755 index 24641899..00000000 --- a/examples/adwords/v201702/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201702') - - with open(image_filename, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201702/misc/upload_media_bundle.py b/examples/adwords/v201702/misc/upload_media_bundle.py deleted file mode 100755 index 144f6846..00000000 --- a/examples/adwords/v201702/misc/upload_media_bundle.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201702') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/optimization/__init__.py b/examples/adwords/v201702/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201702/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py b/examples/adwords/v201702/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 49b75cde..00000000 --- a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201702') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index 0e2d96a0..00000000 --- a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201702') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index e564882e..00000000 --- a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201702') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id "%s", criterion id ' - '"%s", start date "%s", end date "%s", with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201702/optimization/get_keyword_ideas.py b/examples/adwords/v201702/optimization/get_keyword_ideas.py deleted file mode 100755 index cb4771e6..00000000 --- a/examples/adwords/v201702/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201702') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with "%s" text and average monthly search volume ' - '"%s" was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/__init__.py b/examples/adwords/v201702/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201702/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201702/remarketing/add_audience.py b/examples/adwords/v201702/remarketing/add_audience.py deleted file mode 100755 index 1825d482..00000000 --- a/examples/adwords/v201702/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201702') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201702') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name "%s" and ID "%s" was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/add_conversion_tracker.py b/examples/adwords/v201702/remarketing/add_conversion_tracker.py deleted file mode 100755 index 35395256..00000000 --- a/examples/adwords/v201702/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201702') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" and snippet \n"%s"\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py b/examples/adwords/v201702/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 37fefc3b..00000000 --- a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client, emails): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201702') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. - - Args: - emails: list of str emails to be hashed. - - Returns: - A list of SHA-256 hashed emails. - """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] - - -if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) diff --git a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 907e2fa2..00000000 --- a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201702') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule, - # Optional: Set the populationStatus to REQUESTED to include past users in - # the user list. - 'prepopulationStatus': 'REQUESTED' - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py deleted file mode 100755 index 27e355c4..00000000 --- a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for calls related to ads in your account. - -To set up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CALLER_ID = 'INSERT_CALLER_ID_HERE' -# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats -# For time zones, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -CALL_START_TIME = 'INSERT_CALL_START_TIME' -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, caller_id, call_start_time, conversion_name, conversion_time, - conversion_value): - # Initialize appropriate services. - occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201702') - - # Associate offline call conversions with the existing named conversion - # tracker. If this tracker was newly created, it may be a few hours before it - # can accept conversions. - feed = { - 'callerId': caller_id, - 'callStartTime': call_start_time, - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - } - - occ_operations = [{'operator': 'ADD', 'operand': feed}] - - occ_response = occ_feed_service.mutate(occ_operations) - values = occ_response['value'] - - if values: - for occ_feed in values: - print ('Uploaded offline call conversion value of "%s" for caller ID ' - '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) - else: - print 'No offline call conversions were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, - CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201702/remarketing/upload_offline_conversions.py b/examples/adwords/v201702/remarketing/upload_offline_conversions.py deleted file mode 100755 index c80147aa..00000000 --- a/examples/adwords/v201702/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201702') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of "%s" for Google Click ID ' - '"%s" to "%s".' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201702/reporting/__init__.py b/examples/adwords/v201702/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201702/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 58394d18..00000000 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201702') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py deleted file mode 100755 index 5930c757..00000000 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201702') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 63e08165..00000000 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201702') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py deleted file mode 100755 index dad7f93c..00000000 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201702') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 4418d62d..00000000 --- a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201702') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - print 'Report was downloaded to "%s".' % path - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, PATH) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py deleted file mode 100755 index 97f07edf..00000000 --- a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201702') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201702/reporting/get_report_fields.py b/examples/adwords/v201702/reporting/get_report_fields.py deleted file mode 100755 index 77531ed7..00000000 --- a/examples/adwords/v201702/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201702') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type "%s" contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201702/reporting/parallel_report_download.py b/examples/adwords/v201702/reporting/parallel_report_download.py deleted file mode 100755 index 6bbc7f90..00000000 --- a/examples/adwords/v201702/reporting/parallel_report_download.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import logging -import multiprocessing -from Queue import Empty -import time -import googleads - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - client: An AdWordsClient instance. - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201702') - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = self._DownloadReport(customer_id) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - - Raises: - Exception: if no CustomerIds could be found. - - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201702') - - offset = 0 - - # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201702/shopping/add_product_partition_tree.py b/examples/adwords/v201702/shopping/add_product_partition_tree.py deleted file mode 100755 index c31a4fdb..00000000 --- a/examples/adwords/v201702/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/shopping/add_product_scope.py b/examples/adwords/v201702/shopping/add_product_scope.py deleted file mode 100755 index a9d24334..00000000 --- a/examples/adwords/v201702/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201702') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign.py b/examples/adwords/v201702/shopping/add_shopping_campaign.py deleted file mode 100755 index 87cea0af..00000000 --- a/examples/adwords/v201702/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201702') - ad_group_service = client.GetService('AdGroupService', version='v201702') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - adgroup = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) - - for adgroup in ad_group_result['value']: - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': adgroup['id'], - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID) diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py deleted file mode 100755 index 1931f6c7..00000000 --- a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py +++ /dev/null @@ -1,402 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds a Shopping campaign for Showcase ads. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import base64 -import uuid - -from googleads import adwords -from suds import WebFault - - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' -COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, budget_id, merchant_id, expanded_image_filepath, - collapsed_image_filepath): - try: - # Create the Shopping Campaign - campaign = CreateShoppingCampaign(client, budget_id, merchant_id) - - # Create the AdGroup - adgroup = CreateAdGroup(client, campaign['id']) - - # Create a Showcase Ad - CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath) - - product_partition_tree = CreateProductPartition(client, adgroup['id']) - print 'Final tree:\n%s' % product_partition_tree - except WebFault: - print 'Failed to create shopping campaign for showcase ads.' - raise - - -def CreateShoppingCampaign(client, budget_id, merchant_id): - """Creates a shopping campaign with the given budget and merchant IDs. - - Args: - client: an AdWordsClient instance. - budget_id: the str ID of the budget to be associated with the shopping - campaign. - merchant_id: the str ID of the merchant account to be associated with the - shopping campaign. - - Returns: - The created Shopping Campaign as a sudsobject. - """ - campaign_service = client.GetService('CampaignService', 'v201702') - - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - return campaign - - -def CreateAdGroup(client, campaign_id): - """Creates an AdGroup for the given shopping campaign ID. - - Args: - client: an AdWordsClient instance. - campaign_id: the str ID of a shopping campaign. - - Returns: - The created AdGroup as a sudsobject. - """ - ad_group_service = client.GetService('AdGroupService', 'v201702') - - adgroup = { - # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS - 'adGroupType': 'SHOPPING_SHOWCASE_ADS', - 'campaignId': campaign_id, - 'name': 'AdGroup #%s' % uuid.uuid4(), - # REQUIRED: Set the ad group's bidding strategy configuration. - 'biddingStrategyConfiguration': { - # Showcase ads require either ManualCpc or EnhancedCpc. - 'biddingStrategyType': 'MANUAL_CPC', - # Optional: Set the bids - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 100000 - } - }] - } - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - return adgroup - - -def CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath): - """Creates a showcase add for the given AdGroup with the given images. - - Args: - client: an AdWordsClient instance. - adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. - expanded_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's expandedImage. - collapsed_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's collapsedImage. - - Returns: - The created Showcase Ad as a sudsobject. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201702') - - showcase_ad = { - 'adGroupId': adgroup['id'], - 'ad': { - 'xsi_type': 'ShowcaseAd', - 'Ad.Type': 'ShowcaseAd', - # Required: set the ad's name, final URLs, and display URL. - 'name': 'Showcase ad #%s' % uuid.uuid4(), - 'finalUrls': 'http://example.com/showcase', - 'displayUrl': 'example.com', - # Required: Set the ad's expanded image. - 'expandedImage': { - 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] - }, - # Optional: Set the collapsed image. - 'collapsedImage': { - 'mediaId': - UploadImage(client, collapsed_image_filepath)['mediaId'] - } - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': showcase_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] - - print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] - - return showcase_ad - - -def UploadImage(client, filepath): - """Uploads a .jpg image with the given filepath via the AdWords MediaService. - - Args: - client: an AdWordsClient instance. - filepath: a str filepath to the .jpg file to be uploaded. - - Returns: - The created Image as a sudsobject. - """ - media_service = client.GetService('MediaService', 'v201702') - - with open(filepath, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - image = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - - image = media_service.upload(image)[0] - - return image - - -def CreateProductPartition(client, adgroup_id): - """Creates a ProductPartition tree for the given AdGroup ID. - - Args: - client: an AdWordsClient instance. - adgroup_id: a str AdGroup ID. - - Returns: - The ProductPartition tree as a sudsobject. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - 'v201702') - helper = ProductPartitionHelper(adgroup_id) - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition) - helper.CreateUnit(root, used_product_canonical_condition) - helper.CreateUnit(root, other_product_canonical_condition) - - result = ad_group_criterion_service.mutate(helper.operations) - return result['value'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, - COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py b/examples/adwords/v201702/shopping/get_product_category_taxonomy.py deleted file mode 100755 index af75ea9d..00000000 --- a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201702') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/targeting/__init__.py b/examples/adwords/v201702/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201702/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 00828814..00000000 --- a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201702') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s", criterion id "%s", ' - 'and type "%s" was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 9d487088..00000000 --- a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type "%s" was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 45aaf587..00000000 --- a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201702') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index 3bf3412d..00000000 --- a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201702') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name "%s" and ID "%s" was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name "%s", ID "%s", and country code "%s" was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201702/targeting/lookup_location.py b/examples/adwords/v201702/targeting/lookup_location.py deleted file mode 100755 index 683a3c2a..00000000 --- a/examples/adwords/v201702/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201702') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term "%s" returned the location "%s" of type "%s"' - ' with parent locations "%s", reach "%s" and id "%s" (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/basic_operations/get_campaigns.py b/examples/adwords/v201705/basic_operations/get_campaigns.py index 63ba8668..fac8642e 100755 --- a/examples/adwords/v201705/basic_operations/get_campaigns.py +++ b/examples/adwords/v201705/basic_operations/get_campaigns.py @@ -27,7 +27,6 @@ import logging -import time from googleads import adwords logging.basicConfig(level=logging.INFO) @@ -66,7 +65,6 @@ def main(client): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py index c27da4a5..29e06c4a 100755 --- a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -55,7 +54,6 @@ def main(client): print 'No campaigns were found.' offset += PAGE_SIZE more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py index 4ca7c4ad..9485c4ae 100755 --- a/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py @@ -14,11 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This uses the BatchJobService to incrementally create a complete Campaign. -The complete Campaign created by this example also includes AdGroups and -KeyWords. +"""This example illustrates how to incrementally upload keywords. +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. """ import random diff --git a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py index cd405d56..6273a119 100755 --- a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -75,7 +74,6 @@ def main(client, label_id): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201705/shopping/add_product_partition_tree.py b/examples/adwords/v201705/shopping/add_product_partition_tree.py index 5098996d..d2fda6e1 100755 --- a/examples/adwords/v201705/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201705/shopping/add_product_partition_tree.py @@ -33,19 +33,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -53,6 +40,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): diff --git a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py index e8175611..e9ad6e50 100755 --- a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py @@ -38,19 +38,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -58,6 +45,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): diff --git a/examples/adwords/v201708/basic_operations/get_campaigns.py b/examples/adwords/v201708/basic_operations/get_campaigns.py index 0a562cc1..712cce1c 100755 --- a/examples/adwords/v201708/basic_operations/get_campaigns.py +++ b/examples/adwords/v201708/basic_operations/get_campaigns.py @@ -27,7 +27,6 @@ import logging -import time from googleads import adwords logging.basicConfig(level=logging.INFO) @@ -66,7 +65,6 @@ def main(client): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py index b40a3fd3..53555067 100755 --- a/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -55,7 +54,6 @@ def main(client): print 'No campaigns were found.' offset += PAGE_SIZE more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py index 627cf52b..3a07fca4 100755 --- a/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py @@ -14,11 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This uses the BatchJobService to incrementally create a complete Campaign. -The complete Campaign created by this example also includes AdGroups and -KeyWords. +"""This example illustrates how to incrementally upload keywords. +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. """ import random diff --git a/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py index 9c7199e5..81b30437 100755 --- a/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -75,7 +74,6 @@ def main(client, label_id): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201708/remarketing/upload_offline_data.py b/examples/adwords/v201708/remarketing/upload_offline_data.py new file mode 100755 index 00000000..12e6513d --- /dev/null +++ b/examples/adwords/v201708/remarketing/upload_offline_data.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 shows how to upload offline data for store sales transactions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import datetime +import hashlib + +from googleads import adwords +import pytz + + +_DT_FORMAT = '%Y%m%d %H%M%S' +# User identifier types whose values must be hashed. +_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', + 'HASHED_LAST_NAME', 'HASHED_PHONE') +# The timezone to be used in this example. For valid timezone IDs, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +_TIMEZONE = pytz.timezone('America/New_York') +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Insert email addresses below for creating user identifiers. +EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] +# The external upload ID can be any number that you use to keep track of your +# uploads. +EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' +# Advertiser upload time to partner. +# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, +# see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' +# Indicates the version of the bridge map. +BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' +# The ID of the third party uploading the transaction feed. +PARTNER_ID = 'INSERT_PARTNER_ID_HERE' + + +def main(client, conversion_name, external_upload_id, email_addresses, + advertiser_upload_time, bridge_map_version_id, partner_id): + # Initialize appropriate services. + offline_data_upload_service = client.GetService( + 'OfflineDataUploadService', version='v201708') + + # Create the first offline data for upload. + # This transaction occurred 7 days ago with an amount of $200 USD. + transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=7)) + offline_data_1 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[0]), + _CreateUserIdentifier(identifier_type='STATE', value='New York') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_1), + 'transactionAmount': { + 'currencyCode': 'USD', + 'money': { + 'microAmount': 200000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create the second offline data for upload. + # This transaction occurred 14 days ago with amount of 450 EUR. + transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=14)) + offline_data_2 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[1]), + _CreateUserIdentifier(identifier_type='STATE', value='California') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_2), + 'transactionAmount': { + 'currencyCode': 'EUR', + 'money': { + 'microAmount': 450000000 + } + }, + 'conversionName': conversion_name + } + } + + # Set the metadata of this upload. + upload_metadata = { + 'StoreSalesUploadCommonMetadata': { + 'xsi_type': 'ThirdPartyUploadMetadata', + 'loyaltyRate': 1.0, + 'transactionUploadRate': 1.0, + 'advertiserUploadTime': advertiser_upload_time, + 'validTransactionRate': 1.0, + 'partnerMatchRate': 1.0, + 'partnerUploadRate': 1.0, + 'bridgeMapVersionId': bridge_map_version_id, + 'partnerId': partner_id + } + } + + # Create offline data upload + offline_data_upload = { + 'externalUploadId': external_upload_id, + 'offlineDataList': [offline_data_1, offline_data_2], + # Set the type of this upload. + 'uploadType': 'STORE_SALES_UPLOAD_THIRD_PARTY', + 'uploadMetadata': upload_metadata + } + + # Create an offline data upload operation. + operations = [{ + 'operator': 'ADD', + 'operand': offline_data_upload + }] + + # Upload offline data on the server and print the result. + result = offline_data_upload_service.mutate(operations) + offline_data_upload = result['value'][0] + + print ('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) + + # Print any partial data errors from the response. The order of the partial + # data errors list is the same as the uploaded offline data list in the + # request. + for i, partial_data_error in enumerate( + offline_data_upload['partialDataErrors']): + # If a partial error occurred for this offline data, print the error. Note + # that non-errors for a given offline data would be set to None. + if partial_data_error: + print ('Found a partial error for offline data #%d with error string: %s' + % (i, partial_data_error['errorString'])) + + +def _CreateUserIdentifier(identifier_type=None, value=None): + """Creates a user identifier from the specified type and value. + + Args: + identifier_type: a str specifying the type of user identifier. + value: a str value of the identifier; to be hashed using SHA-256 if needed. + + Returns: + A dict specifying a user identifier, with a value hashed using SHA-256 if + needed. + """ + if identifier_type in _HASHED_IDENTIFIER_TYPES: + # If the user identifier type is a hashed type, normalize and hash the + # value. + value = hashlib.sha256(value.strip().lower()).hexdigest() + + user_identifier = { + 'userIdentifierType': identifier_type, + 'value': value + } + + return user_identifier + + +def _GetFormattedDateTime(dt): + """Formats the given datetime and timezone for use with AdWords. + + Args: + dt: a datetime instance. + + Returns: + A str representation of the datetime in the correct format for AdWords. + """ + return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, EMAIL_ADDRESSES, + ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201708/shopping/add_product_partition_tree.py b/examples/adwords/v201708/shopping/add_product_partition_tree.py index 8c976668..3009ad9e 100755 --- a/examples/adwords/v201708/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201708/shopping/add_product_partition_tree.py @@ -33,19 +33,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -54,6 +41,18 @@ def __init__(self, adgroup_id): tree to. """ self.adgroup_id = adgroup_id + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): """Creates a subdivision node. diff --git a/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py index 7b372563..bf9ee8a9 100755 --- a/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py @@ -38,19 +38,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -58,6 +45,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): diff --git a/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py index f5edfb5b..16e68459 100755 --- a/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -40,25 +40,6 @@ def main(client, adgroup_id): 'headlinePart1': 'Luxury Cruise to Mars', 'headlinePart2': 'Visit the Red Planet in style.', 'description': 'Low-gravity fun for everyone!', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, # Specify a list of final URLs. This field cannot be set if URL # field is set, or finalUrls is unset. This may be specified at ad, # criterion, and feed item levels. @@ -75,6 +56,29 @@ def main(client, adgroup_id): ] } + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + expanded_text_ad['trackingUrlTemplate'] = ( + 'http://tracker.example.com/?season={_season}&promocode={_promocode}' + '&u={lpurl}' + ) + + expanded_text_ad['urlCustomParameters'] = { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + } + text_adgroup_ad = { 'adGroupId': adgroup_id, 'ad': expanded_text_ad, diff --git a/examples/adwords/v201710/basic_operations/get_campaigns.py b/examples/adwords/v201710/basic_operations/get_campaigns.py index b2a01f80..3d540ad4 100755 --- a/examples/adwords/v201710/basic_operations/get_campaigns.py +++ b/examples/adwords/v201710/basic_operations/get_campaigns.py @@ -27,7 +27,6 @@ import logging -import time from googleads import adwords logging.basicConfig(level=logging.INFO) @@ -66,7 +65,6 @@ def main(client): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py index 72078fc0..360d3d4a 100755 --- a/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -54,7 +53,6 @@ def main(client): campaign['status'])) else: print 'No campaigns were found.' - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201710/basic_operations/update_ad_group.py b/examples/adwords/v201710/basic_operations/update_ad_group.py index d17a8cc8..eac1d446 100755 --- a/examples/adwords/v201710/basic_operations/update_ad_group.py +++ b/examples/adwords/v201710/basic_operations/update_ad_group.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates status for a given ad group. +"""This example updates the CPC bid and status for a given ad group. To get ad groups, run get_ad_groups.py. @@ -29,9 +29,10 @@ AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' -def main(client, ad_group_id): +def main(client, ad_group_id, bid_micro_amount=None): # Initialize appropriate service. ad_group_service = client.GetService('AdGroupService', version='v201710') @@ -43,16 +44,42 @@ def main(client, ad_group_id): 'status': 'PAUSED' } }] + + if bid_micro_amount: + operations[0]['operand']['biddingStrategyConfiguration'] = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': bid_micro_amount, + } + }] + } + ad_groups = ad_group_service.mutate(operations) # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was updated.' - % (ad_group['name'], ad_group['id'])) + bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] + # Find the CpcBid in the bidding strategy configuration's bids collection. + cpc_bid_micros = None + + if bidding_strategy_configuration: + bids = bidding_strategy_configuration['bids'] + + if bids: + for bid in bids: + if bid['Bids.Type'] == 'CpcBid': + cpc_bid_micros = bid['bid']['microAmount'] + break + + print ('Ad group with name "%s", and id "%s" was updated to have status ' + '"%s" and CPC bid %d.' + % (ad_group['name'], ad_group['id'], ad_group['status'], + cpc_bid_micros)) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) + main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py index 5fddf5b5..1cb8bfe6 100755 --- a/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py @@ -14,11 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. +"""This example illustrates how to incrementally upload keywords. +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. """ import random diff --git a/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py index 4aee0506..e3ab0b1a 100755 --- a/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -75,7 +74,6 @@ def main(client, label_id): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201710/remarketing/upload_offline_data.py b/examples/adwords/v201710/remarketing/upload_offline_data.py index c687000d..7004738f 100755 --- a/examples/adwords/v201710/remarketing/upload_offline_data.py +++ b/examples/adwords/v201710/remarketing/upload_offline_data.py @@ -44,9 +44,28 @@ # The external upload ID can be any number that you use to keep track of your # uploads. EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' +# Store sales upload common metadata types +METADATA_TYPE_1P = 'FirstPartyUploadMetadata' +METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' +# Set the below constant to METADATA_TYPE_3P if uploading third-party data. +STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P +# The three constants below are needed when uploading third-party data. They +# are not used when uploading first-party data. +# Advertiser upload time to partner. +# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, +# see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' +# Indicates the version of the bridge map. +BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' +# The ID of the third party uploading the transaction feed. +PARTNER_ID = 'INSERT_PARTNER_ID_HERE' -def main(client, conversion_name, external_upload_id, email_addresses): +def main(client, conversion_name, external_upload_id, + store_sales_upload_common_metadata_type, email_addresses, + advertiser_upload_time=None, bridge_map_version_id=None, + partner_id=None): # Initialize appropriate services. offline_data_upload_service = client.GetService( 'OfflineDataUploadService', version='v201710') @@ -95,12 +114,37 @@ def main(client, conversion_name, external_upload_id, email_addresses): } } + # Set the type and metadata of this upload. + upload_metadata = { + 'StoreSalesUploadCommonMetadata': { + 'xsi_type': store_sales_upload_common_metadata_type, + 'loyaltyRate': 1.0, + 'transactionUploadRate': 1.0, + } + } + + if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: + upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' + elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: + upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' + upload_metadata['StoreSalesUploadCommonMetadata'].update({ + 'advertiserUploadTime': advertiser_upload_time, + 'validTransactionRate': 1.0, + 'partnerMatchRate': 1.0, + 'partnerUploadRate': 1.0, + 'bridgeMapVersionId': bridge_map_version_id, + 'partnerId': partner_id + }) + else: + raise ValueError('Unknown metadata type.') + # Create offline data upload offline_data_upload = { 'externalUploadId': external_upload_id, 'offlineDataList': [offline_data_1, offline_data_2], - # Optional: You can set the type of this upload. - # 'uploadType': 'STORE_SALES_UPLOAD_FIRST_PARTY' + # Set the type of this upload. + 'uploadType': upload_type, + 'uploadMetadata': upload_metadata } # Create an offline data upload operation. @@ -169,4 +213,6 @@ def _GetFormattedDateTime(dt): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, EMAIL_ADDRESSES) + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, + STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, + ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201710/shopping/add_product_partition_tree.py b/examples/adwords/v201710/shopping/add_product_partition_tree.py index a146762e..0897675e 100755 --- a/examples/adwords/v201710/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201710/shopping/add_product_partition_tree.py @@ -33,19 +33,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -53,6 +40,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): diff --git a/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py index f348c422..f8c1959f 100755 --- a/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py @@ -38,19 +38,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -58,6 +45,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): diff --git a/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py deleted file mode 100755 index a93d2d7f..00000000 --- a/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product for non-sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - product_service = client.GetService('ProductService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') - - product = { - # Setting required Marketplace Information. - 'productMarketplaceInfo': { - 'additionalTerms': 'Remember to also discuss that thing.', - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for products. - 'name': ('Product #%d' % uuid.uuid4()), - 'productType': 'DFP', - 'rateType': 'CPM', - 'lineItemType': 'STANDARD', - 'priority': 8, - 'environment': 'BROWSER', - 'rate': { - 'currencyCode': 'USD', - 'microAmount': '6000000' - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'builtInTargeting': { - 'inventoryTargeting': { - 'adUnitTargeting': { - 'adUnitId': network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId'], - 'includeDescendents': 'true' - } - } - }, - } - - products = product_service.createProducts([product]) - - if products: - for product in products: - print ('A programmatic product for non-sales management with ID "%s"' - ' and name "%s" was created.' % (product['id'], product['name'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py deleted file mode 100755 index 4ee33f05..00000000 --- a/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example publishes a product to Marketplace. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the product to publish. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201705') - - # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - products_published = 0 - - # Get products by statement. - while True: - response = product_service.getProductsByStatement( - statement.ToStatement()) - if 'results' in response: - for product in response['results']: - print ('Product with id "%s" and name "%s" will be ' - 'published.' % (product['id'], - product['name'])) - - # Perform action. - result = product_service.performProductAction( - {'xsi_type': 'PublishProducts'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - products_published += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if products_published > 0: - print 'Number of programmatic products published: %s' % products_published - else: - print 'No products were published.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201708/company_service/update_companies.py b/examples/dfp/v201708/company_service/update_companies.py index c515a0e5..ac9399ff 100755 --- a/examples/dfp/v201708/company_service/update_companies.py +++ b/examples/dfp/v201708/company_service/update_companies.py @@ -58,7 +58,7 @@ def main(client, company_id): # Display results. for company in companies: print (('Company with ID "%s", name "%s", and comment "%s"' - 'was updated.') + ' was updated.') % (company['id'], company['name'], company['comment'])) else: print 'No companies found to update.' diff --git a/examples/dfp/v201708/creative_service/get_image_creatives.py b/examples/dfp/v201708/creative_service/get_image_creatives.py index fc099545..4d2a923a 100755 --- a/examples/dfp/v201708/creative_service/get_image_creatives.py +++ b/examples/dfp/v201708/creative_service/get_image_creatives.py @@ -26,7 +26,7 @@ def main(client): # Create a statement to select creatives. statement = (dfp.StatementBuilder() .Where('creativeType = :creativeType') - .WithBindVariable('creativeType', '_image_creative')) + .WithBindVariable('creativeType', 'ImageCreative')) # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/dfp/v201708/forecast_service/get_availability_forecast.py b/examples/dfp/v201708/forecast_service/get_availability_forecast.py index f502aade..99583ae3 100755 --- a/examples/dfp/v201708/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201708/forecast_service/get_availability_forecast.py @@ -105,11 +105,14 @@ def main(client, advertiser_id): forecast = forecast_service.getAvailabilityForecast( prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -117,9 +120,10 @@ def main(client, advertiser_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py index ba38ebc0..ac71f295 100755 --- a/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py @@ -42,11 +42,14 @@ def main(client, line_item_id): forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -54,9 +57,10 @@ def main(client, line_item_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py deleted file mode 100755 index c09c6054..00000000 --- a/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product for non-sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - product_service = client.GetService('ProductService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') - - product = { - # Setting required Marketplace Information. - 'productMarketplaceInfo': { - 'additionalTerms': 'Remember to also discuss that thing.', - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for products. - 'name': ('Product #%d' % uuid.uuid4()), - 'productType': 'DFP', - 'rateType': 'CPM', - 'lineItemType': 'STANDARD', - 'priority': 8, - 'environmentType': 'BROWSER', - 'rate': { - 'currencyCode': 'USD', - 'microAmount': '6000000' - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'builtInTargeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId'], - 'includeDescendants': 'true' - } - } - }, - } - - products = product_service.createProducts([product]) - - if products: - for product in products: - print ('A programmatic product for non-sales management with ID "%s"' - ' and name "%s" was created.' % (product['id'], product['name'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py deleted file mode 100755 index 4ecb0509..00000000 --- a/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example publishes a product to Marketplace. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the product to publish. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201708') - - # Create query. - statement = (dfp.StatementBuilder() - .Where('id = :id') - .WithBindVariable('id', long(product_id)) - .Limit(1)) - - products_published = 0 - - # Get products by statement. - while True: - response = product_service.getProductsByStatement( - statement.ToStatement()) - if 'results' in response: - for product in response['results']: - print ('Product with id "%s" and name "%s" will be ' - 'published.' % (product['id'], - product['name'])) - - # Perform action. - result = product_service.performProductAction( - {'xsi_type': 'PublishProducts'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - products_published += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if products_published > 0: - print 'Number of programmatic products published: %s' % products_published - else: - print 'No products were published.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201708/report_service/run_inventory_report.py b/examples/dfp/v201708/report_service/run_inventory_report.py index f4a6d7c9..b134c2d2 100755 --- a/examples/dfp/v201708/report_service/run_inventory_report.py +++ b/examples/dfp/v201708/report_service/run_inventory_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report equal to the "Whole network report" on the DFP website.""" +"""This example runs a typical daily inventory report.""" import tempfile diff --git a/examples/dfp/v201711/company_service/update_companies.py b/examples/dfp/v201711/company_service/update_companies.py index 7142dddb..96cc22fd 100755 --- a/examples/dfp/v201711/company_service/update_companies.py +++ b/examples/dfp/v201711/company_service/update_companies.py @@ -58,7 +58,7 @@ def main(client, company_id): # Display results. for company in companies: print (('Company with ID "%s", name "%s", and comment "%s"' - 'was updated.') + ' was updated.') % (company['id'], company['name'], company['comment'])) else: print 'No companies found to update.' diff --git a/examples/dfp/v201711/creative_service/get_image_creatives.py b/examples/dfp/v201711/creative_service/get_image_creatives.py index 1b9daa8c..5091c9da 100755 --- a/examples/dfp/v201711/creative_service/get_image_creatives.py +++ b/examples/dfp/v201711/creative_service/get_image_creatives.py @@ -26,7 +26,7 @@ def main(client): # Create a statement to select creatives. statement = (dfp.StatementBuilder() .Where('creativeType = :creativeType') - .WithBindVariable('creativeType', '_image_creative')) + .WithBindVariable('creativeType', 'ImageCreative')) # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/dfp/v201711/forecast_service/get_availability_forecast.py b/examples/dfp/v201711/forecast_service/get_availability_forecast.py index 331913f4..24916d0b 100755 --- a/examples/dfp/v201711/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201711/forecast_service/get_availability_forecast.py @@ -105,11 +105,14 @@ def main(client, advertiser_id): forecast = forecast_service.getAvailabilityForecast( prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -117,9 +120,10 @@ def main(client, advertiser_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py index 370679ee..3820ae8f 100755 --- a/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py @@ -42,11 +42,14 @@ def main(client, line_item_id): forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -54,9 +57,10 @@ def main(client, line_item_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201711/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201711/product_service/create_programmatic_products_for_non_sales_management.py deleted file mode 100755 index 997e7db4..00000000 --- a/examples/dfp/v201711/product_service/create_programmatic_products_for_non_sales_management.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product for non-sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - product_service = client.GetService('ProductService', version='v201711') - network_service = client.GetService('NetworkService', version='v201711') - - product = { - # Setting required Marketplace Information. - 'productMarketplaceInfo': { - 'additionalTerms': 'Remember to also discuss that thing.', - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for products. - 'name': ('Product #%d' % uuid.uuid4()), - 'productType': 'DFP', - 'rateType': 'CPM', - 'lineItemType': 'STANDARD', - 'priority': 8, - 'environmentType': 'BROWSER', - 'rate': { - 'currencyCode': 'USD', - 'microAmount': '6000000' - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'builtInTargeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId'], - 'includeDescendants': 'true' - } - } - }, - } - - products = product_service.createProducts([product]) - - if products: - for product in products: - print ('A programmatic product for non-sales management with ID "%s"' - ' and name "%s" was created.' % (product['id'], product['name'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201711/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201711/product_service/publish_programmatic_products_to_marketplace.py deleted file mode 100755 index 5a94c148..00000000 --- a/examples/dfp/v201711/product_service/publish_programmatic_products_to_marketplace.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example publishes a product to Marketplace. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the product to publish. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201711') - - # Create query. - statement = (dfp.StatementBuilder() - .Where('id = :id') - .WithBindVariable('id', long(product_id)) - .Limit(1)) - - products_published = 0 - - # Get products by statement. - while True: - response = product_service.getProductsByStatement( - statement.ToStatement()) - if 'results' in response: - for product in response['results']: - print ('Product with id "%s" and name "%s" will be ' - 'published.' % (product['id'], - product['name'])) - - # Perform action. - result = product_service.performProductAction( - {'xsi_type': 'PublishProducts'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - products_published += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if products_published > 0: - print 'Number of programmatic products published: %s' % products_published - else: - print 'No products were published.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201711/report_service/run_inventory_report.py b/examples/dfp/v201711/report_service/run_inventory_report.py index 2bffebeb..a7abcb2e 100755 --- a/examples/dfp/v201711/report_service/run_inventory_report.py +++ b/examples/dfp/v201711/report_service/run_inventory_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report equal to the "Whole network report" on the DFP website.""" +"""This example runs a typical daily inventory report.""" import tempfile diff --git a/examples/dfp/v201705/activity_group_service/__init__.py b/examples/dfp/v201802/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201705/activity_group_service/__init__.py rename to examples/dfp/v201802/activity_group_service/__init__.py diff --git a/examples/dfp/v201705/activity_group_service/create_activity_groups.py b/examples/dfp/v201802/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201705/activity_group_service/create_activity_groups.py rename to examples/dfp/v201802/activity_group_service/create_activity_groups.py index f1a8769e..0ab733fb 100755 --- a/examples/dfp/v201705/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201705') + version='v201802') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201705/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py similarity index 86% rename from examples/dfp/v201705/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201802/activity_group_service/get_active_activity_groups.py index 945ac5dd..c4e09074 100755 --- a/examples/dfp/v201705/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'ActivityGroupService', version='v201802') # Create a statement to select activity groups. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py similarity index 97% rename from examples/dfp/v201705/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201802/activity_group_service/get_all_activity_groups.py index cc7eaf66..dd9a08e4 100755 --- a/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201705') + 'ActivityGroupService', version='v201802') # Create a statement to select activity groups. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/activity_group_service/update_activity_groups.py b/examples/dfp/v201802/activity_group_service/update_activity_groups.py similarity index 87% rename from examples/dfp/v201705/activity_group_service/update_activity_groups.py rename to examples/dfp/v201802/activity_group_service/update_activity_groups.py index df1b623a..c25929a7 100755 --- a/examples/dfp/v201705/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/update_activity_groups.py @@ -37,20 +37,13 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201705') + version='v201802') # Create statement object to select a single activity groups by ID. - values = [{ - 'key': 'activityGroupId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_group_id - } - }] - query = 'WHERE id = :activityGroupId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityGroupId') + .WithBindVariable('activityGroupId', long(activity_group_id)) + .Limit(1)) # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( @@ -70,6 +63,7 @@ def main(client, activity_group_id, advertiser_company_id): else: print 'No activity groups found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/activity_service/__init__.py b/examples/dfp/v201802/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201705/activity_service/__init__.py rename to examples/dfp/v201802/activity_service/__init__.py diff --git a/examples/dfp/v201705/activity_service/create_activities.py b/examples/dfp/v201802/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201705/activity_service/create_activities.py rename to examples/dfp/v201802/activity_service/create_activities.py index 60adc312..2277e7d3 100755 --- a/examples/dfp/v201705/activity_service/create_activities.py +++ b/examples/dfp/v201802/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201705') + activity_service = client.GetService('ActivityService', version='v201802') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201705/activity_service/get_active_activities.py b/examples/dfp/v201802/activity_service/get_active_activities.py similarity index 87% rename from examples/dfp/v201705/activity_service/get_active_activities.py rename to examples/dfp/v201802/activity_service/get_active_activities.py index e9e16a6e..0b32f027 100755 --- a/examples/dfp/v201705/activity_service/get_active_activities.py +++ b/examples/dfp/v201802/activity_service/get_active_activities.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + activity_service = client.GetService('ActivityService', version='v201802') # Create a statement to select activities. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/dfp/v201705/activity_service/get_all_activities.py b/examples/dfp/v201802/activity_service/get_all_activities.py similarity index 99% rename from examples/dfp/v201705/activity_service/get_all_activities.py rename to examples/dfp/v201802/activity_service/get_all_activities.py index a3b4412b..d44eef63 100755 --- a/examples/dfp/v201705/activity_service/get_all_activities.py +++ b/examples/dfp/v201802/activity_service/get_all_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201705') + activity_service = client.GetService('ActivityService', version='v201802') # Create a statement to select activities. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/activity_service/update_activities.py b/examples/dfp/v201802/activity_service/update_activities.py similarity index 90% rename from examples/dfp/v201705/activity_service/update_activities.py rename to examples/dfp/v201802/activity_service/update_activities.py index ae4bdcc0..2225e1d4 100755 --- a/examples/dfp/v201705/activity_service/update_activities.py +++ b/examples/dfp/v201802/activity_service/update_activities.py @@ -35,18 +35,13 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201705') + activity_service = client.GetService('ActivityService', version='v201802') # Create statement object to select one activity by ID to update. - values = [{ - 'key': 'activityId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_id - } - }] - query = 'WHERE id = :activityId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityId') + .WithBindVariable('activityId', long(activity_id)) + .Limit(1)) # Get activities by statement. response = activity_service.getActivitiesByStatement( @@ -66,6 +61,7 @@ def main(client, activity_id): else: print 'No activities found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/audience_segment_service/__init__.py b/examples/dfp/v201802/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201705/audience_segment_service/__init__.py rename to examples/dfp/v201802/audience_segment_service/__init__.py diff --git a/examples/dfp/v201705/audience_segment_service/create_audience_segments.py b/examples/dfp/v201802/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/dfp/v201705/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/create_audience_segments.py index 3a942da6..010d0124 100755 --- a/examples/dfp/v201705/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + 'AudienceSegmentService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py similarity index 97% rename from examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py index f0aad4be..07e9fa8c 100755 --- a/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') + 'AudienceSegmentService', version='v201802') # Create a statement to select audience segments. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py similarity index 86% rename from examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py index faec6a63..8c88c322 100755 --- a/examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - }}, - ] + 'AudienceSegmentService', version='v201802') # Create a statement to select audience segments. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'FIRST_PARTY')) # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py similarity index 80% rename from examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py index a3d7fc05..0fa30e62 100755 --- a/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py @@ -30,24 +30,15 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') + 'AudienceSegmentService', version='v201802') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201705/audience_segment_service/update_audience_segments.py b/examples/dfp/v201802/audience_segment_service/update_audience_segments.py similarity index 81% rename from examples/dfp/v201705/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/update_audience_segments.py index 0fdea19a..e0b559d1 100755 --- a/examples/dfp/v201705/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/update_audience_segments.py @@ -29,24 +29,15 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') + 'AudienceSegmentService', version='v201802') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) # Get audience segments by statement. response = audience_segment_service.getAudienceSegmentsByStatement( diff --git a/examples/dfp/v201705/base_rate_service/__init__.py b/examples/dfp/v201802/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201705/base_rate_service/__init__.py rename to examples/dfp/v201802/base_rate_service/__init__.py diff --git a/examples/dfp/v201705/base_rate_service/create_product_base_rates.py b/examples/dfp/v201802/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201705/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201802/base_rate_service/create_product_base_rates.py index b8ae2eac..54aa61a1 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201705') + 'BaseRateService', version='v201802') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py similarity index 99% rename from examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py rename to examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py index bd7779cb..d7a50f50 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201705') + base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a base rate for a product package item. product_package_item_base_rate = { diff --git a/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py index 23b22bb2..f259ca28 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201705') + 'BaseRateService', version='v201802') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201705/base_rate_service/get_all_base_rates.py b/examples/dfp/v201802/base_rate_service/get_all_base_rates.py similarity index 99% rename from examples/dfp/v201705/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201802/base_rate_service/get_all_base_rates.py index 0d42dfc2..743db7e5 100755 --- a/examples/dfp/v201705/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/get_all_base_rates.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201705') + base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a statement to select base rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py similarity index 88% rename from examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py rename to examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py index 5ebb7edf..40848144 100755 --- a/examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py @@ -24,17 +24,11 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201705') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] + base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a statement to select base rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/dfp/v201705/base_rate_service/update_base_rates.py b/examples/dfp/v201802/base_rate_service/update_base_rates.py similarity index 90% rename from examples/dfp/v201705/base_rate_service/update_base_rates.py rename to examples/dfp/v201802/base_rate_service/update_base_rates.py index fd9510c0..48c74f3a 100755 --- a/examples/dfp/v201705/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/update_base_rates.py @@ -29,18 +29,14 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201705') + base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': base_rate_id - } - }] - query = 'where id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', long(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( diff --git a/examples/dfp/v201705/native_style_service/__init__.py b/examples/dfp/v201802/cdn_configuration_service/__init__.py similarity index 100% rename from examples/dfp/v201705/native_style_service/__init__.py rename to examples/dfp/v201802/cdn_configuration_service/__init__.py diff --git a/examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py b/examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py new file mode 100755 index 00000000..f0dfe4ce --- /dev/null +++ b/examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 code example creates new cdn configurations. + +To determine which configurations exist, run get_all_cdn_configurations.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201802') + + # Create cdn config objects. + # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. + configs = [{ + # Basic example with no security policies. + 'name': 'ApiConfig1', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + } + } + }, { + # Complex example with security policies. + 'name': 'ApiConfig2', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': False, + 'tokenAuthenticationKey': 'abc123', + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': True, + 'originForwardingType': 'CONVENTIONAL', + 'originPathPrefix': '/path/to/my/origin' + } + } + } + }] + + # Add configs. + configs = cdn_config_service.createCdnConfigurations(configs) + + # Display results. + for config in configs: + print('Created CDN configuration with type "%s" and name "%s".' + % (config['cdnConfigurationType'], config['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py b/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py new file mode 100755 index 00000000..02e8b463 --- /dev/null +++ b/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 CDN configuration objects. + +Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be +returned. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201802') + + # Create a statement to select cdn configurations. + statement = dfp.StatementBuilder() + + # Retrieve a small number of configs at a time, paging + # through until all have been retrieved. + while True: + response = (cdn_config_service + .getCdnConfigurationsByStatement(statement.ToStatement())) + if 'results' in response: + for cdn in response['results']: + # Print out some information for each company. + print('Found CDN configuration with type "%s" and name "%s".' + % (cdn['cdnConfigurationType'], cdn['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/company_service/__init__.py b/examples/dfp/v201802/company_service/__init__.py similarity index 100% rename from examples/dfp/v201705/company_service/__init__.py rename to examples/dfp/v201802/company_service/__init__.py diff --git a/examples/dfp/v201705/company_service/create_companies.py b/examples/dfp/v201802/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201705/company_service/create_companies.py rename to examples/dfp/v201802/company_service/create_companies.py index ac9b5994..3106f133 100755 --- a/examples/dfp/v201705/company_service/create_companies.py +++ b/examples/dfp/v201802/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201705') + company_service = client.GetService('CompanyService', version='v201802') # Create company objects. companies = [ diff --git a/examples/dfp/v201705/company_service/get_advertisers.py b/examples/dfp/v201802/company_service/get_advertisers.py similarity index 88% rename from examples/dfp/v201705/company_service/get_advertisers.py rename to examples/dfp/v201802/company_service/get_advertisers.py index 16e506d9..ee3242fe 100755 --- a/examples/dfp/v201705/company_service/get_advertisers.py +++ b/examples/dfp/v201802/company_service/get_advertisers.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - }}, - ] + company_service = client.GetService('CompanyService', version='v201802') # Create a statement to select companies. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'ADVERTISER')) # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/dfp/v201705/company_service/get_all_companies.py b/examples/dfp/v201802/company_service/get_all_companies.py similarity index 99% rename from examples/dfp/v201705/company_service/get_all_companies.py rename to examples/dfp/v201802/company_service/get_all_companies.py index 61e10d09..cabe543b 100755 --- a/examples/dfp/v201705/company_service/get_all_companies.py +++ b/examples/dfp/v201802/company_service/get_all_companies.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201705') + company_service = client.GetService('CompanyService', version='v201802') # Create a statement to select companies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/company_service/update_companies.py b/examples/dfp/v201802/company_service/update_companies.py similarity index 89% rename from examples/dfp/v201705/company_service/update_companies.py rename to examples/dfp/v201802/company_service/update_companies.py index c6b76cca..65a71808 100755 --- a/examples/dfp/v201705/company_service/update_companies.py +++ b/examples/dfp/v201802/company_service/update_companies.py @@ -35,18 +35,13 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201705') + company_service = client.GetService('CompanyService', version='v201802') # Create statement object to only select a single company by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': company_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(company_id)) + .Limit(1)) # Get companies by statement. response = company_service.getCompaniesByStatement( @@ -63,11 +58,12 @@ def main(client, company_id): # Display results. for company in companies: print (('Company with ID "%s", name "%s", and comment "%s"' - 'was updated.') + ' was updated.') % (company['id'], company['name'], company['comment'])) else: print 'No companies found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/contact_service/__init__.py b/examples/dfp/v201802/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201705/contact_service/__init__.py rename to examples/dfp/v201802/contact_service/__init__.py diff --git a/examples/dfp/v201705/contact_service/create_contacts.py b/examples/dfp/v201802/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201705/contact_service/create_contacts.py rename to examples/dfp/v201802/contact_service/create_contacts.py index 858c188a..80687d64 100755 --- a/examples/dfp/v201705/contact_service/create_contacts.py +++ b/examples/dfp/v201802/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201705') + contact_service = client.GetService('ContactService', version='v201802') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201705/contact_service/get_all_contacts.py b/examples/dfp/v201802/contact_service/get_all_contacts.py similarity index 99% rename from examples/dfp/v201705/contact_service/get_all_contacts.py rename to examples/dfp/v201802/contact_service/get_all_contacts.py index c8e1c3e9..edde878e 100755 --- a/examples/dfp/v201705/contact_service/get_all_contacts.py +++ b/examples/dfp/v201802/contact_service/get_all_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201705') + contact_service = client.GetService('ContactService', version='v201802') # Create a statement to select contacts. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/contact_service/get_uninvited_contacts.py b/examples/dfp/v201802/contact_service/get_uninvited_contacts.py similarity index 87% rename from examples/dfp/v201705/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201802/contact_service/get_uninvited_contacts.py index 911225a5..99b67b8a 100755 --- a/examples/dfp/v201705/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201802/contact_service/get_uninvited_contacts.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - }}, - ] + contact_service = client.GetService('ContactService', version='v201802') # Create a statement to select contacts. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'UNINVITED')) # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/dfp/v201705/contact_service/update_contacts.py b/examples/dfp/v201802/contact_service/update_contacts.py similarity index 90% rename from examples/dfp/v201705/contact_service/update_contacts.py rename to examples/dfp/v201802/contact_service/update_contacts.py index 0bc86ca6..4091cac3 100755 --- a/examples/dfp/v201705/contact_service/update_contacts.py +++ b/examples/dfp/v201802/contact_service/update_contacts.py @@ -35,18 +35,13 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201705') + contact_service = client.GetService('ContactService', version='v201802') # Create statement object to select the single contact by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': contact_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(contact_id)) + .Limit(1)) # Get contacts by statement. response = contact_service.getContactsByStatement( @@ -69,6 +64,7 @@ def main(client, contact_id): else: print 'No contacts found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index c0f39c37..5b0c261e 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201705') + 'ContentMetadataKeyHierarchyService', version='v201802') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 90% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 986f2c1d..24acd69a 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,19 +40,15 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201705') + 'ContentMetadataKeyHierarchyService', version='v201802') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -78,6 +74,7 @@ def main(client, content_metadata_key_hierarchy_id): print ('Number of content metadata key hierarchies deleted: %s' % result['numChanges']) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index ce28be95..afe409a3 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201705') + 'ContentMetadataKeyHierarchyService', version='v201802') # Create a statement to select content metadata key hierarchies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index e6dce35b..cbef227b 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,19 +42,15 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201705') + 'ContentMetadataKeyHierarchyService', version='v201802') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -90,6 +86,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): else: print 'No content metadata key hierarchies were found' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/content_service/__init__.py b/examples/dfp/v201802/content_service/__init__.py similarity index 100% rename from examples/dfp/v201705/content_service/__init__.py rename to examples/dfp/v201802/content_service/__init__.py diff --git a/examples/dfp/v201705/content_service/get_all_content.py b/examples/dfp/v201802/content_service/get_all_content.py similarity index 99% rename from examples/dfp/v201705/content_service/get_all_content.py rename to examples/dfp/v201802/content_service/get_all_content.py index 5a73428e..4eac419f 100755 --- a/examples/dfp/v201705/content_service/get_all_content.py +++ b/examples/dfp/v201802/content_service/get_all_content.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201705') + content_service = client.GetService('ContentService', version='v201802') # Create a statement to select content. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_service/__init__.py b/examples/dfp/v201802/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201705/creative_service/__init__.py rename to examples/dfp/v201802/creative_service/__init__.py diff --git a/examples/dfp/v201705/creative_service/copy_image_creatives.py b/examples/dfp/v201802/creative_service/copy_image_creatives.py similarity index 99% rename from examples/dfp/v201705/creative_service/copy_image_creatives.py rename to examples/dfp/v201802/creative_service/copy_image_creatives.py index b1f69848..9a5270da 100755 --- a/examples/dfp/v201705/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201802/creative_service/copy_image_creatives.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to get the image creative. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_service/create_creative_from_template.py b/examples/dfp/v201802/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201705/creative_service/create_creative_from_template.py rename to examples/dfp/v201802/creative_service/create_creative_from_template.py index 38d993e6..0184f00b 100755 --- a/examples/dfp/v201705/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201802/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201705/creative_service/create_creatives.py b/examples/dfp/v201802/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201705/creative_service/create_creatives.py rename to examples/dfp/v201802/creative_service/create_creatives.py index a9cb9884..785ecce6 100755 --- a/examples/dfp/v201705/creative_service/create_creatives.py +++ b/examples/dfp/v201802/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201705/creative_service/create_custom_creative.py b/examples/dfp/v201802/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201705/creative_service/create_custom_creative.py rename to examples/dfp/v201802/creative_service/create_custom_creative.py index abc6b632..57d11581 100755 --- a/examples/dfp/v201705/creative_service/create_custom_creative.py +++ b/examples/dfp/v201802/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201705/creative_service/create_native_creative.py b/examples/dfp/v201802/creative_service/create_native_creative.py similarity index 94% rename from examples/dfp/v201705/creative_service/create_native_creative.py rename to examples/dfp/v201802/creative_service/create_native_creative.py index 0421823d..0af31046 100755 --- a/examples/dfp/v201705/creative_service/create_native_creative.py +++ b/examples/dfp/v201802/creative_service/create_native_creative.py @@ -46,18 +46,16 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Use the system defined native app install creative template. creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = base64.b64encode(image_data).decode('utf-8') + image_data = base64.b64encode(image_data) app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - app_icon_data = base64.b64encode(app_icon_data).decode('utf-8') + app_icon_data = base64.b64encode(app_icon_data) # Create creative from templates. creative = { diff --git a/examples/dfp/v201705/creative_service/get_all_creatives.py b/examples/dfp/v201802/creative_service/get_all_creatives.py similarity index 99% rename from examples/dfp/v201705/creative_service/get_all_creatives.py rename to examples/dfp/v201802/creative_service/get_all_creatives.py index 809b4d2e..63febc23 100755 --- a/examples/dfp/v201705/creative_service/get_all_creatives.py +++ b/examples/dfp/v201802/creative_service/get_all_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to select creatives. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_service/get_image_creatives.py b/examples/dfp/v201802/creative_service/get_image_creatives.py similarity index 86% rename from examples/dfp/v201705/creative_service/get_image_creatives.py rename to examples/dfp/v201802/creative_service/get_image_creatives.py index bc977ea8..43c97189 100755 --- a/examples/dfp/v201705/creative_service/get_image_creatives.py +++ b/examples/dfp/v201802/creative_service/get_image_creatives.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') - query = 'WHERE creativeType = :creativeType' - values = [ - {'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': '_image_creative' - }}, - ] + creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to select creatives. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('creativeType = :creativeType') + .WithBindVariable('creativeType', 'ImageCreative')) # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/dfp/v201705/creative_service/update_creatives.py b/examples/dfp/v201802/creative_service/update_creatives.py similarity index 85% rename from examples/dfp/v201705/creative_service/update_creatives.py rename to examples/dfp/v201802/creative_service/update_creatives.py index 82400db5..36b9ac84 100755 --- a/examples/dfp/v201705/creative_service/update_creatives.py +++ b/examples/dfp/v201802/creative_service/update_creatives.py @@ -34,24 +34,14 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Create statement object to get all image creatives. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }, { - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': image_creative_id - } - }] - query = 'WHERE creativeType = :type AND id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('creativeType = :type AND id = :id') + .WithBindVariable('type', 'ImageCreative') + .WithBindVariable('id', long(image_creative_id)) + .Limit(1)) # Get creatives by statement. response = creative_service.getCreativesByStatement( @@ -74,6 +64,7 @@ def main(client, image_creative_id): else: print 'No creatives found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/creative_set_service/__init__.py b/examples/dfp/v201802/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201705/creative_set_service/__init__.py rename to examples/dfp/v201802/creative_set_service/__init__.py diff --git a/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py index bd800084..339e5627 100755 --- a/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201705/creative_set_service/create_creative_set.py b/examples/dfp/v201802/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201705/creative_set_service/create_creative_set.py rename to examples/dfp/v201802/creative_set_service/create_creative_set.py index 55764d11..f3af2365 100755 --- a/examples/dfp/v201705/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201802/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201705') + version='v201802') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py similarity index 97% rename from examples/dfp/v201705/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201802/creative_set_service/get_all_creative_sets.py index de0d3ef5..b3c337f3 100755 --- a/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201705') + 'CreativeSetService', version='v201802') # Create a statement to select creative sets. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py similarity index 85% rename from examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py index 2d4208d4..e6defb2b 100755 --- a/examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,17 +25,11 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201705') - query = 'WHERE masterCreativeId = :masterCreativeId' - values = [ - {'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'TextValue', - 'value': master_creative_id - }}, - ] + 'CreativeSetService', version='v201802') # Create a statement to select creative sets. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('masterCreativeId = :masterCreativeId') + .WithBindVariable('masterCreativeId', master_creative_id)) # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/dfp/v201705/creative_set_service/update_creative_set.py b/examples/dfp/v201802/creative_set_service/update_creative_set.py similarity index 89% rename from examples/dfp/v201705/creative_set_service/update_creative_set.py rename to examples/dfp/v201802/creative_set_service/update_creative_set.py index 94cdd8e3..36be393c 100755 --- a/examples/dfp/v201705/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201802/creative_set_service/update_creative_set.py @@ -37,18 +37,12 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201705') + version='v201802') # Create statement to select a single creative set by ID. - values = [{ - 'key': 'creativeSetId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_set_id - } - }] - query = 'WHERE id = :creativeSetId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeSetId') + .WithBindVariable('creativeSetId', long(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -72,6 +66,7 @@ def main(client, creative_set_id, companion_creative_id): else: print 'No creative sets found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/creative_template_service/__init__.py b/examples/dfp/v201802/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201705/creative_template_service/__init__.py rename to examples/dfp/v201802/creative_template_service/__init__.py diff --git a/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py similarity index 97% rename from examples/dfp/v201705/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201802/creative_template_service/get_all_creative_templates.py index 7550f838..2795bdd9 100755 --- a/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201705') + 'CreativeTemplateService', version='v201802') # Create a statement to select creative templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py similarity index 86% rename from examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py rename to examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py index 920c4974..63958253 100755 --- a/examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - }}, - ] + 'CreativeTemplateService', version='v201802') # Create a statement to select creative templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'SYSTEM_DEFINED')) # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py similarity index 91% rename from examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py index d09aa48d..624413df 100755 --- a/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py @@ -37,15 +37,15 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201705') + version='v201802') # Create creative wrapper objects. creative_wrapper = { # A label can only be associated with one creative wrapper. 'labelId': label_id, 'ordering': 'INNER', - 'header': {'htmlSnippet': 'My creative wrapper header'}, - 'footer': {'htmlSnippet': 'My creative wrapper footer'} + 'htmlHeader': 'My creative wrapper header', + 'htmlFooter': 'My creative wrapper footer' } # Add creative wrapper. diff --git a/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 85% rename from examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py index 229980be..f8e913db 100755 --- a/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,24 +33,13 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201705') + version='v201802') # Create a query to select the active creative wrappers for the given label. - values = [{ - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status AND labelId = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status AND labelId = :labelId') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('labelId', long(label_id))) creative_wrappers_deactivated = 0 @@ -82,6 +71,7 @@ def main(client, label_id): else: print 'No creative wrappers were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py similarity index 86% rename from examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py index 2bc54fc4..90f75cd8 100755 --- a/examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'CreativeWrapperService', version='v201802') # Create a statement to select creative wrappers. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py similarity index 97% rename from examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py index 8e63e641..1e2bd8b9 100755 --- a/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201705') + 'CreativeWrapperService', version='v201802') # Create a statement to select creative wrappers. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py similarity index 88% rename from examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py index 21258f0b..75f7e964 100755 --- a/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py @@ -36,18 +36,13 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201705') + version='v201802') # Create statement to get a creative wrapper by ID. - values = [{ - 'key': 'creativeWrapperId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_wrapper_id - } - }] - query = 'WHERE id = :creativeWrapperId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeWrapperId') + .WithBindVariable('creativeWrapperId', + long(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -71,6 +66,7 @@ def main(client, creative_wrapper_id): else: print 'No creative wrappers found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_field_service/__init__.py b/examples/dfp/v201802/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201705/custom_field_service/__init__.py rename to examples/dfp/v201802/custom_field_service/__init__.py diff --git a/examples/dfp/v201705/custom_field_service/create_custom_field_options.py b/examples/dfp/v201802/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201705/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201802/custom_field_service/create_custom_field_options.py index 182fc145..8129c823 100755 --- a/examples/dfp/v201705/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201802/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201802') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201705/custom_field_service/create_custom_fields.py b/examples/dfp/v201802/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201705/custom_field_service/create_custom_fields.py rename to examples/dfp/v201802/custom_field_service/create_custom_fields.py index 89d1069e..1aaf1209 100755 --- a/examples/dfp/v201705/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201802') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 82% rename from examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py index ece9ff34..97cd279d 100755 --- a/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,27 +33,14 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201802') # Create statement to select only active custom fields that apply to # line items. - values = [ - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }, { - 'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - } - ] - query = 'WHERE entityType = :entityType and isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType and isActive = :isActive') + .WithBindVariable('entityType', 'LINE_ITEM') + .WithBindVariable('isActive', True)) custom_fields_deactivated = 0 @@ -79,6 +66,7 @@ def main(client): else: print 'No custom fields were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py similarity index 97% rename from examples/dfp/v201705/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201802/custom_field_service/get_all_custom_fields.py index 740a05bf..afe4646c 100755 --- a/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201802') # Create a statement to select custom fields. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py similarity index 85% rename from examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py rename to examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py index a5df35ad..411ff23b 100755 --- a/examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') - query = 'WHERE entityType = :entityType' - values = [ - {'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - }}, - ] + 'CustomFieldService', version='v201802') # Create a statement to select custom fields. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType') + .WithBindVariable('entityType', 'LINE_ITEM')) # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py index 5080e010..c9f9354a 100755 --- a/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201802') - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201705/custom_field_service/update_custom_fields.py b/examples/dfp/v201802/custom_field_service/update_custom_fields.py similarity index 88% rename from examples/dfp/v201705/custom_field_service/update_custom_fields.py rename to examples/dfp/v201802/custom_field_service/update_custom_fields.py index 7a1b54c0..cdebe296 100755 --- a/examples/dfp/v201705/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/update_custom_fields.py @@ -36,18 +36,12 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201802') # Create statement to get a custom field. - values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - query = 'WHERE id = :customFieldId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', long(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -69,6 +63,7 @@ def main(client, custom_field_id): else: print 'No custom fields found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_targeting_service/__init__.py b/examples/dfp/v201802/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201705/custom_targeting_service/__init__.py rename to examples/dfp/v201802/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py index 0c979863..708a712a 100755 --- a/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py similarity index 90% rename from examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py index 03c46640..2f325004 100755 --- a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,17 +36,11 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') - - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': key_name - } - }] - query = 'WHERE name = :name' - statement = dfp.FilterStatement(query, values) + 'CustomTargetingService', version='v201802') + + statement = (dfp.StatementBuilder() + .Where('name = :name') + .WithBindVariable('name', key_name)) deleted_custom_targeting_keys = 0 @@ -76,6 +70,7 @@ def main(client, key_name): else: print 'No custom targeting keys were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py similarity index 98% rename from examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py index 9a09683d..86c0d4e1 100755 --- a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py @@ -36,7 +36,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 97c46ba1..b445ccdc 100755 --- a/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') # Create statement to get all targeting keys. targeting_key_statement = dfp.StatementBuilder() @@ -46,7 +46,7 @@ def main(client): ', '.join([str(key['id']) for key in all_keys])) statement = dfp.FilterStatement(query) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( diff --git a/examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 78% rename from examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index eda4ac5b..9c6a4660 100755 --- a/examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,18 +23,12 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') # Create statement to get targeting keys for predefined values. - query = ('WHERE type = :type') - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] - targeting_key_statement = dfp.FilterStatement(query, values) + targeting_key_statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'PREDEFINED')) all_keys = [] @@ -44,17 +38,17 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (:ids)') + .WithBindVariable('ids', [key['id'] for key in all_keys])) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( @@ -67,7 +61,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py similarity index 88% rename from examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py index 738097d6..81ce3523 100755 --- a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py @@ -30,17 +30,12 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE id = :keyId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :keyId') + .WithBindVariable('keyId', long(key_id)) + .Limit(1)) # Get custom targeting keys by statement. response = custom_targeting_service.getCustomTargetingKeysByStatement( @@ -65,6 +60,7 @@ def main(client, key_id): else: print 'No custom targeting keys were found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py similarity index 88% rename from examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py index edf57cd7..d1a1e9c3 100755 --- a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py @@ -30,17 +30,11 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', long(key_id))) while True: # Get custom targeting values by statement. @@ -70,6 +64,7 @@ def main(client, key_id): if response['totalResultSetSize'] == 0: print 'No custom targeting values were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/exchange_rate_service/__init__.py b/examples/dfp/v201802/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201705/exchange_rate_service/__init__.py rename to examples/dfp/v201802/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py index 4fd18507..66706137 100755 --- a/examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201705') + version='v201802') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py similarity index 97% rename from examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py index 39f6e4f6..497f5630 100755 --- a/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201705') + 'ExchangeRateService', version='v201802') # Create a statement to select exchange rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 86% rename from examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py index acac6d8c..896d0ac4 100755 --- a/examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,17 +25,11 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201705') - query = 'WHERE currencyCode = :currencyCode' - values = [ - {'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - }}, - ] + 'ExchangeRateService', version='v201802') # Create a statement to select exchange rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('currencyCode = :currencyCode') + .WithBindVariable('currencyCode', currency_code)) # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py similarity index 87% rename from examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py index dae8aad9..a95e076f 100755 --- a/examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py @@ -30,19 +30,13 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201705') + version='v201802') # Create a statement to get an exchange rate by its ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': exchange_rate_id - } - }] - query = 'WHERE id = :id' - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(exchange_rate_id)) + .Limit(1)) # Get rate cards by statement. response = exchange_rate_service.getExchangeRatesByStatement( diff --git a/examples/dfp/v201705/forecast_service/get_availability_forecast.py b/examples/dfp/v201802/forecast_service/get_availability_forecast.py similarity index 90% rename from examples/dfp/v201705/forecast_service/get_availability_forecast.py rename to examples/dfp/v201802/forecast_service/get_availability_forecast.py index 0bb2e691..29da19fc 100755 --- a/examples/dfp/v201705/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201802/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + forecast_service = client.GetService('ForecastService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] @@ -105,11 +105,14 @@ def main(client, advertiser_id): forecast = forecast_service.getAvailabilityForecast( prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -117,9 +120,10 @@ def main(client, advertiser_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py similarity index 83% rename from examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py index ff2263e0..f7914e26 100755 --- a/examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201705') + forecast_service = client.GetService('ForecastService', version='v201802') # Set forecasting options. forecast_options = { @@ -42,11 +42,14 @@ def main(client, line_item_id): forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -54,7 +57,7 @@ def main(client, line_item_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) if __name__ == '__main__': diff --git a/examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py index 42f8aa03..f6277566 100755 --- a/examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201705') + forecast_service = client.GetService('ForecastService', version='v201802') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201705/inventory_service/__init__.py b/examples/dfp/v201802/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201705/inventory_service/__init__.py rename to examples/dfp/v201802/inventory_service/__init__.py diff --git a/examples/dfp/v201705/inventory_service/archive_ad_units.py b/examples/dfp/v201802/inventory_service/archive_ad_units.py similarity index 90% rename from examples/dfp/v201705/inventory_service/archive_ad_units.py rename to examples/dfp/v201802/inventory_service/archive_ad_units.py index 72aae7d5..5d118eb8 100755 --- a/examples/dfp/v201705/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201802/inventory_service/archive_ad_units.py @@ -35,19 +35,13 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201705') + inventory_service = client.GetService('InventoryService', version='v201802') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - values = [{ - 'key': 'parentId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': parent_id - } - }] - query = 'WHERE parentId = :parentId or id = :parentId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId or id = :parentId') + .WithBindVariable('parentId', long(parent_id))) ad_units_archived = 0 @@ -74,6 +68,7 @@ def main(client, parent_id): else: print 'No ad units were archived.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/inventory_service/create_ad_units.py b/examples/dfp/v201802/inventory_service/create_ad_units.py similarity index 99% rename from examples/dfp/v201705/inventory_service/create_ad_units.py rename to examples/dfp/v201802/inventory_service/create_ad_units.py index 0781c1b7..708709f9 100755 --- a/examples/dfp/v201705/inventory_service/create_ad_units.py +++ b/examples/dfp/v201802/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201705') + inventory_service = client.GetService('InventoryService', version='v201802') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py new file mode 100755 index 00000000..e86eb93b --- /dev/null +++ b/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 prints all ad unit names as a tree.""" + + +# Import appropriate modules from the client library. +import collections +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201802') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select only the root ad unit by ID. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', root_ad_unit_id)) + + # Make a request for the root ad unit + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + root_ad_unit = response['results'][0] + + all_ad_units = get_all_ad_units(inventory_service) + + display_hierarchy(root_ad_unit, all_ad_units) + + +def get_all_ad_units(inventory_service): + """Download all ad units. + + Args: + inventory_service: An instance of the InventoryService. + + Returns: + A list containing all ad units. + """ + # Create a statement to get all ad units. + statement = (dfp.StatementBuilder() + .OrderBy('id', ascending=True)) + + # Pull down all ad units into a list + keep_iterating = True + total_results = 0 + found_ad_units = [] + while keep_iterating: + page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in page: + total_results = page['totalResultSetSize'] + found_ad_units.extend(page['results']) + + statement.offset += statement.limit + keep_iterating = statement.offset < total_results + + return found_ad_units + + +def display_hierarchy(root_ad_unit, all_ad_units): + """Display the ad units as a tree. + + Args: + root_ad_unit: The root ad unit to begin from. + all_ad_units: A list containing all ad units. + """ + # Create a dict mapping the ids of parents to lists of their children. + parent_id_to_children = collections.defaultdict(list) + for ad_unit in all_ad_units: + if 'parentId' in ad_unit: + parent_id_to_children[ad_unit['parentId']].append(ad_unit) + parent_id_to_children = dict(parent_id_to_children) + + display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0) + + +def display_hierarchy_helper(root, parent_id_to_children, depth): + """Recursive helper for displaying the hierarchy. + + Args: + root: The current root ad unit. + parent_id_to_children: The overall map of parent ids to children. + depth: The current depth. + """ + print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id']) + + # Recurse for each child of this root that has children. + for child in parent_id_to_children.get(root['id'], []): + display_hierarchy_helper(child, parent_id_to_children, depth + 1) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py index ac351ef1..999c3c7a 100755 --- a/examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py @@ -23,12 +23,12 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201705') + 'InventoryService', version='v201802') # Create a statement to select ad unit sizes. statement = dfp.FilterStatement() - # Retreive a small amount of ad unit sizes at a time, paging + # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. response = ad_unit_size_service.getAdUnitSizesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201705/inventory_service/get_all_ad_units.py b/examples/dfp/v201802/inventory_service/get_all_ad_units.py similarity index 99% rename from examples/dfp/v201705/inventory_service/get_all_ad_units.py rename to examples/dfp/v201802/inventory_service/get_all_ad_units.py index 809dd346..c42ea962 100755 --- a/examples/dfp/v201705/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201802/inventory_service/get_all_ad_units.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201705') + ad_unit_service = client.GetService('InventoryService', version='v201802') # Create a statement to select ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py new file mode 100755 index 00000000..f58ddeb5 --- /dev/null +++ b/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 child ad units of the effective root ad unit.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201802') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + parent_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select ad units under the parent ad unit. + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId') + .OrderBy('id', ascending=True) + .WithBindVariable('parentId', parent_ad_unit_id)) + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response: + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/inventory_service/update_ad_units.py b/examples/dfp/v201802/inventory_service/update_ad_units.py similarity index 92% rename from examples/dfp/v201705/inventory_service/update_ad_units.py rename to examples/dfp/v201802/inventory_service/update_ad_units.py index 3c601f56..a7a4e217 100755 --- a/examples/dfp/v201705/inventory_service/update_ad_units.py +++ b/examples/dfp/v201802/inventory_service/update_ad_units.py @@ -36,18 +36,12 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201705') + inventory_service = client.GetService('InventoryService', version='v201802') # Create a statement to select a single ad unit by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': ad_unit_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', ad_unit_id)) # Get ad units by statement. response = inventory_service.getAdUnitsByStatement( @@ -81,6 +75,7 @@ def main(client, ad_unit_id): print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/label_service/__init__.py b/examples/dfp/v201802/label_service/__init__.py similarity index 100% rename from examples/dfp/v201705/label_service/__init__.py rename to examples/dfp/v201802/label_service/__init__.py diff --git a/examples/dfp/v201705/label_service/create_labels.py b/examples/dfp/v201802/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201705/label_service/create_labels.py rename to examples/dfp/v201802/label_service/create_labels.py index 6e99a2f8..c6e3d203 100755 --- a/examples/dfp/v201705/label_service/create_labels.py +++ b/examples/dfp/v201802/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') + label_service = client.GetService('LabelService', version='v201802') # Create label objects. labels = [] diff --git a/examples/dfp/v201705/label_service/deactivate_labels.py b/examples/dfp/v201802/label_service/deactivate_labels.py similarity index 89% rename from examples/dfp/v201705/label_service/deactivate_labels.py rename to examples/dfp/v201802/label_service/deactivate_labels.py index f44d2454..f71ab6f5 100755 --- a/examples/dfp/v201705/label_service/deactivate_labels.py +++ b/examples/dfp/v201802/label_service/deactivate_labels.py @@ -27,18 +27,12 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') + label_service = client.GetService('LabelService', version='v201802') # Create query. - values = [{ - 'key': 'isActive', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'true' - } - }] - query = 'WHERE isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) labels_deactivated = 0 @@ -64,6 +58,7 @@ def main(client): else: print 'No labels were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/label_service/get_active_labels.py b/examples/dfp/v201802/label_service/get_active_labels.py similarity index 87% rename from examples/dfp/v201705/label_service/get_active_labels.py rename to examples/dfp/v201802/label_service/get_active_labels.py index 9a6ce559..023a2816 100755 --- a/examples/dfp/v201705/label_service/get_active_labels.py +++ b/examples/dfp/v201802/label_service/get_active_labels.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') - query = 'WHERE isActive = :isActive' - values = [ - {'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + label_service = client.GetService('LabelService', version='v201802') # Create a statement to select labels. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/dfp/v201705/label_service/get_all_labels.py b/examples/dfp/v201802/label_service/get_all_labels.py similarity index 99% rename from examples/dfp/v201705/label_service/get_all_labels.py rename to examples/dfp/v201802/label_service/get_all_labels.py index 6a29dedf..7546eb12 100755 --- a/examples/dfp/v201705/label_service/get_all_labels.py +++ b/examples/dfp/v201802/label_service/get_all_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') + label_service = client.GetService('LabelService', version='v201802') # Create a statement to select labels. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/label_service/update_labels.py b/examples/dfp/v201802/label_service/update_labels.py similarity index 87% rename from examples/dfp/v201705/label_service/update_labels.py rename to examples/dfp/v201802/label_service/update_labels.py index 236748f2..91b7d025 100755 --- a/examples/dfp/v201705/label_service/update_labels.py +++ b/examples/dfp/v201802/label_service/update_labels.py @@ -29,20 +29,12 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') + label_service = client.GetService('LabelService', version='v201802') # Create a statement to select only active labels. - values = [ - { - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - } - ] - query = 'WHERE id = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :labelId') + .WithBindVariable('labelId', long(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -63,6 +55,7 @@ def main(client, label_id): else: print 'No labels found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/line_item_creative_association_service/__init__.py b/examples/dfp/v201802/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201705/line_item_creative_association_service/__init__.py rename to examples/dfp/v201802/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201705/line_item_creative_association_service/create_licas.py b/examples/dfp/v201802/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201705/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201802/line_item_creative_association_service/create_licas.py index 117caadb..dcad9d0c 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py similarity index 83% rename from examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py index 89417839..38d6475d 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py @@ -30,24 +30,13 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') # Create query. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE lineItemId = :lineItemId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId AND status = :status') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('lineItemId', long(line_item_id))) num_deactivated_licas = 0 @@ -77,6 +66,7 @@ def main(client, line_item_id): else: print 'No LICAs were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py similarity index 97% rename from examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py index 55b0a511..a3e8cc11 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') # Create a statement to select line item creative associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py similarity index 87% rename from examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py index 3630dd39..1fb91b67 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,17 +25,11 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') - query = 'WHERE lineItemId = :lineItemId' - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'TextValue', - 'value': line_item_id - }}, - ] + 'LineItemCreativeAssociationService', version='v201802') # Create a statement to select line item creative associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId') + .WithBindVariable('lineItemId', line_item_id)) # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py b/examples/dfp/v201802/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201705/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201802/line_item_creative_association_service/update_licas.py index b3973bf0..e5b6dc12 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/update_licas.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') # Create statement object to get all LICAs. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/line_item_service/__init__.py b/examples/dfp/v201802/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201705/line_item_service/__init__.py rename to examples/dfp/v201802/line_item_service/__init__.py diff --git a/examples/dfp/v201705/line_item_service/activate_line_items.py b/examples/dfp/v201802/line_item_service/activate_line_items.py similarity index 86% rename from examples/dfp/v201705/line_item_service/activate_line_items.py rename to examples/dfp/v201802/line_item_service/activate_line_items.py index 090c845e..a4d05caa 100755 --- a/examples/dfp/v201705/line_item_service/activate_line_items.py +++ b/examples/dfp/v201802/line_item_service/activate_line_items.py @@ -33,24 +33,13 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # Create query. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' - } - }] - query = 'WHERE orderId = :orderId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId AND status = :status') + .WithBindVariable('status', 'NEEDS_CREATIVES') + .WithBindVariable('orderId', long(order_id))) line_items_activated = 0 @@ -79,6 +68,7 @@ def main(client, order_id): else: print 'No line items were activated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/line_item_service/create_line_items.py b/examples/dfp/v201802/line_item_service/create_line_items.py similarity index 99% rename from examples/dfp/v201705/line_item_service/create_line_items.py rename to examples/dfp/v201802/line_item_service/create_line_items.py index 9c2e9338..1e5af88b 100755 --- a/examples/dfp/v201705/line_item_service/create_line_items.py +++ b/examples/dfp/v201802/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/dfp/v201705/line_item_service/create_video_line_item.py b/examples/dfp/v201802/line_item_service/create_video_line_item.py similarity index 99% rename from examples/dfp/v201705/line_item_service/create_video_line_item.py rename to examples/dfp/v201802/line_item_service/create_video_line_item.py index 63b94339..fcb84fec 100755 --- a/examples/dfp/v201705/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201802/line_item_service/create_video_line_item.py @@ -47,7 +47,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/dfp/v201705/line_item_service/get_all_line_items.py b/examples/dfp/v201802/line_item_service/get_all_line_items.py similarity index 99% rename from examples/dfp/v201705/line_item_service/get_all_line_items.py rename to examples/dfp/v201802/line_item_service/get_all_line_items.py index 90e12640..4e8ea547 100755 --- a/examples/dfp/v201705/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201802/line_item_service/get_all_line_items.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # Create a statement to select line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py similarity index 86% rename from examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py rename to examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py index 27e2cca5..46639e3a 100755 --- a/examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') - query = 'WHERE isMissingCreatives = :isMissingCreatives' - values = [ - {'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + line_item_service = client.GetService('LineItemService', version='v201802') # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isMissingCreatives = :isMissingCreatives') + .WithBindVariable('isMissingCreatives', True)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py similarity index 82% rename from examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py index bd8e23ca..6190ced8 100755 --- a/examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py @@ -21,22 +21,20 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') - query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' - values = [ - {'key': 'lastModifiedDateTime', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() - timedelta(days=1)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + line_item_service = client.GetService('LineItemService', version='v201802') + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201705/line_item_service/pause_line_items.py b/examples/dfp/v201802/line_item_service/pause_line_items.py similarity index 99% rename from examples/dfp/v201705/line_item_service/pause_line_items.py rename to examples/dfp/v201802/line_item_service/pause_line_items.py index 988f3c5f..62481bf9 100755 --- a/examples/dfp/v201705/line_item_service/pause_line_items.py +++ b/examples/dfp/v201802/line_item_service/pause_line_items.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # Create a statement to select the line item. # Change this to operate on more than one Line Item. diff --git a/examples/dfp/v201705/line_item_service/target_custom_criteria.py b/examples/dfp/v201802/line_item_service/target_custom_criteria.py similarity index 93% rename from examples/dfp/v201705/line_item_service/target_custom_criteria.py rename to examples/dfp/v201802/line_item_service/target_custom_criteria.py index de386341..810372a2 100755 --- a/examples/dfp/v201705/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201802/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # create custom criterias custom_criteria1 = { @@ -81,15 +81,10 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - query = 'WHERE id = :lineItemId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', long(line_item_id)) + .Limit(1)) # Set custom criteria targeting on the line item. line_item = line_item_service.getLineItemsByStatement( @@ -107,6 +102,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, else: print 'No line items were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/line_item_service/update_line_items.py b/examples/dfp/v201802/line_item_service/update_line_items.py similarity index 84% rename from examples/dfp/v201705/line_item_service/update_line_items.py rename to examples/dfp/v201802/line_item_service/update_line_items.py index 7360fcb0..a98c03db 100755 --- a/examples/dfp/v201705/line_item_service/update_line_items.py +++ b/examples/dfp/v201802/line_item_service/update_line_items.py @@ -29,25 +29,16 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # Create statement object to only select line items with even delivery rates. - values = [{ - 'key': 'deliveryRateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'EVENLY' - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId' - statement = dfp.FilterStatement(query, values, 500) + statement = (dfp.StatementBuilder() + .Where(('deliveryRateType = :deliveryRateType AND ' + 'orderId = :orderId')) + .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('deliveryRateType', 'EVENLY') + .Limit(500)) # Get line items by statement. response = line_item_service.getLineItemsByStatement( @@ -76,6 +67,7 @@ def main(client, order_id): else: print 'No line items found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/adwords/v201702/shopping/__init__.py b/examples/dfp/v201802/native_style_service/__init__.py old mode 100644 new mode 100755 similarity index 87% rename from examples/adwords/v201702/shopping/__init__.py rename to examples/dfp/v201802/native_style_service/__init__.py index be510830..473ddba1 --- a/examples/adwords/v201702/shopping/__init__.py +++ b/examples/dfp/v201802/native_style_service/__init__.py @@ -1,4 +1,6 @@ -# Copyright 2016 Google Inc. All Rights Reserved. +#!/usr/bin/env python +# +# Copyright 2017 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. @@ -11,5 +13,3 @@ # 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. - -"""Shopping examples.""" diff --git a/examples/dfp/v201705/native_style_service/create_native_styles.py b/examples/dfp/v201802/native_style_service/create_native_styles.py similarity index 98% rename from examples/dfp/v201705/native_style_service/create_native_styles.py rename to examples/dfp/v201802/native_style_service/create_native_styles.py index 65005e99..f71eff5a 100755 --- a/examples/dfp/v201705/native_style_service/create_native_styles.py +++ b/examples/dfp/v201802/native_style_service/create_native_styles.py @@ -149,7 +149,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201705') + version='v201802') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/dfp/v201705/native_style_service/get_all_native_styles.py b/examples/dfp/v201802/native_style_service/get_all_native_styles.py similarity index 96% rename from examples/dfp/v201705/native_style_service/get_all_native_styles.py rename to examples/dfp/v201802/native_style_service/get_all_native_styles.py index 86c2da5c..f5a8cc41 100755 --- a/examples/dfp/v201705/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201802/native_style_service/get_all_native_styles.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201705') + version='v201802') # Create a statement to select native styles. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/network_service/__init__.py b/examples/dfp/v201802/network_service/__init__.py similarity index 100% rename from examples/dfp/v201705/network_service/__init__.py rename to examples/dfp/v201802/network_service/__init__.py diff --git a/examples/dfp/v201705/network_service/get_all_networks.py b/examples/dfp/v201802/network_service/get_all_networks.py similarity index 99% rename from examples/dfp/v201705/network_service/get_all_networks.py rename to examples/dfp/v201802/network_service/get_all_networks.py index 1d835878..df2354a6 100755 --- a/examples/dfp/v201705/network_service/get_all_networks.py +++ b/examples/dfp/v201802/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201705') + network_service = client.GetService('NetworkService', version='v201802') networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201802/network_service/get_current_network.py b/examples/dfp/v201802/network_service/get_current_network.py new file mode 100755 index 00000000..58f87509 --- /dev/null +++ b/examples/dfp/v201802/network_service/get_current_network.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 the current network.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201802') + + current_network = network_service.getCurrentNetwork() + + print ("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/network_service/make_test_network.py b/examples/dfp/v201802/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201705/network_service/make_test_network.py rename to examples/dfp/v201802/network_service/make_test_network.py index 72797388..b3e938fb 100755 --- a/examples/dfp/v201705/network_service/make_test_network.py +++ b/examples/dfp/v201802/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201705') + network_service = client.GetService('NetworkService', version='v201802') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/dfp/v201705/order_service/__init__.py b/examples/dfp/v201802/order_service/__init__.py similarity index 100% rename from examples/dfp/v201705/order_service/__init__.py rename to examples/dfp/v201802/order_service/__init__.py diff --git a/examples/dfp/v201705/order_service/approve_orders.py b/examples/dfp/v201802/order_service/approve_orders.py similarity index 84% rename from examples/dfp/v201705/order_service/approve_orders.py rename to examples/dfp/v201802/order_service/approve_orders.py index 173400dc..4d23d77b 100755 --- a/examples/dfp/v201705/order_service/approve_orders.py +++ b/examples/dfp/v201802/order_service/approve_orders.py @@ -28,21 +28,14 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') - - # Create query. - values = [{ - 'key': 'today', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S') - } - }] - query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')' - ' AND endDateTime >= :today AND isArchived = FALSE') + order_service = client.GetService('OrderService', version='v201802') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + today = datetime.date.today() + statement = (dfp.StatementBuilder() + .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' + 'AND endDateTime >= :today AND isArchived = FALSE')) + .WithBindVariable('today', today)) orders_approved = 0 # Get orders by statement. diff --git a/examples/dfp/v201705/order_service/create_orders.py b/examples/dfp/v201802/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201705/order_service/create_orders.py rename to examples/dfp/v201802/order_service/create_orders.py index d3a6a4cc..7fe46aae 100755 --- a/examples/dfp/v201705/order_service/create_orders.py +++ b/examples/dfp/v201802/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') + order_service = client.GetService('OrderService', version='v201802') # Create order objects. orders = [] diff --git a/examples/dfp/v201705/order_service/get_all_orders.py b/examples/dfp/v201802/order_service/get_all_orders.py similarity index 99% rename from examples/dfp/v201705/order_service/get_all_orders.py rename to examples/dfp/v201802/order_service/get_all_orders.py index d19fb7f6..c2f7f0c1 100755 --- a/examples/dfp/v201705/order_service/get_all_orders.py +++ b/examples/dfp/v201802/order_service/get_all_orders.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') + order_service = client.GetService('OrderService', version='v201802') # Create a statement to select orders. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/order_service/get_orders_starting_soon.py b/examples/dfp/v201802/order_service/get_orders_starting_soon.py similarity index 73% rename from examples/dfp/v201705/order_service/get_orders_starting_soon.py rename to examples/dfp/v201802/order_service/get_orders_starting_soon.py index 2083de56..7f53e5b3 100755 --- a/examples/dfp/v201705/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201802/order_service/get_orders_starting_soon.py @@ -21,33 +21,22 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') - query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' - '<= :soon') - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'APPROVED' - }}, - {'key': 'now', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') - }}, - {'key': 'soon', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() + timedelta(days=5)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + order_service = client.GetService('OrderService', version='v201802') + now = datetime.now(tz=pytz.timezone('America/New_York')) + soon = now + timedelta(days=5) + # Create a statement to select orders. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('status = :status AND startDateTime >= :now ' + 'AND startDateTime <= :soon')) + .WithBindVariable('status', 'APPROVED') + .WithBindVariable('now', now) + .WithBindVariable('soon', soon)) # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/dfp/v201705/order_service/update_orders.py b/examples/dfp/v201802/order_service/update_orders.py similarity index 90% rename from examples/dfp/v201705/order_service/update_orders.py rename to examples/dfp/v201802/order_service/update_orders.py index a6a6ab9b..761c8f47 100755 --- a/examples/dfp/v201705/order_service/update_orders.py +++ b/examples/dfp/v201802/order_service/update_orders.py @@ -28,19 +28,13 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') + order_service = client.GetService('OrderService', version='v201802') # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :orderId') + .WithBindVariable('orderId', long(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -69,6 +63,7 @@ def main(client, order_id): else: print 'No orders found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/package_service/create_packages.py b/examples/dfp/v201802/package_service/create_packages.py similarity index 99% rename from examples/dfp/v201705/package_service/create_packages.py rename to examples/dfp/v201802/package_service/create_packages.py index 3e22ba82..e3103d0a 100755 --- a/examples/dfp/v201705/package_service/create_packages.py +++ b/examples/dfp/v201802/package_service/create_packages.py @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201705') + package_service = client.GetService('PackageService', version='v201802') # Create local package. package = { diff --git a/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py similarity index 99% rename from examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py rename to examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py index c7c4c8d9..a59ae877 100755 --- a/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py +++ b/examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201705') + package_service = client.GetService('PackageService', version='v201802') # Create a statement to select the single package. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/package_service/get_all_packages.py b/examples/dfp/v201802/package_service/get_all_packages.py similarity index 99% rename from examples/dfp/v201705/package_service/get_all_packages.py rename to examples/dfp/v201802/package_service/get_all_packages.py index e5369e61..f00ded0c 100755 --- a/examples/dfp/v201705/package_service/get_all_packages.py +++ b/examples/dfp/v201802/package_service/get_all_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201705') + pkg_service = client.GetService('PackageService', version='v201802') # Create a statement to select packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/package_service/get_in_progress_packages.py b/examples/dfp/v201802/package_service/get_in_progress_packages.py similarity index 87% rename from examples/dfp/v201705/package_service/get_in_progress_packages.py rename to examples/dfp/v201802/package_service/get_in_progress_packages.py index a22049a9..c0feec6d 100755 --- a/examples/dfp/v201705/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201802/package_service/get_in_progress_packages.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'IN_PROGRESS' - }}, - ] + pkg_service = client.GetService('PackageService', version='v201802') # Create a statement to select packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'IN_PROGRESS')) # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/dfp/v201705/placement_service/create_placements.py b/examples/dfp/v201802/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201705/placement_service/create_placements.py rename to examples/dfp/v201802/placement_service/create_placements.py index 293167ba..cb1e5335 100755 --- a/examples/dfp/v201705/placement_service/create_placements.py +++ b/examples/dfp/v201802/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') - inventory_service = client.GetService('InventoryService', version='v201705') + placement_service = client.GetService('PlacementService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201802') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201705/placement_service/deactivate_placements.py b/examples/dfp/v201802/placement_service/deactivate_placements.py similarity index 88% rename from examples/dfp/v201705/placement_service/deactivate_placements.py rename to examples/dfp/v201802/placement_service/deactivate_placements.py index 804772cb..cd9b2536 100755 --- a/examples/dfp/v201705/placement_service/deactivate_placements.py +++ b/examples/dfp/v201802/placement_service/deactivate_placements.py @@ -28,18 +28,13 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') + placement_service = client.GetService('PlacementService', version='v201802') # Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :placementId') + .WithBindVariable('placementId', long(placement_id)) + .Limit(1)) # Get placements by statement. placements = placement_service.getPlacementsByStatement( @@ -60,6 +55,7 @@ def main(client, placement_id): else: print 'No placements were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/placement_service/get_active_placements.py b/examples/dfp/v201802/placement_service/get_active_placements.py similarity index 87% rename from examples/dfp/v201705/placement_service/get_active_placements.py rename to examples/dfp/v201802/placement_service/get_active_placements.py index 3d2b4511..d085a5fb 100755 --- a/examples/dfp/v201705/placement_service/get_active_placements.py +++ b/examples/dfp/v201802/placement_service/get_active_placements.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + placement_service = client.GetService('PlacementService', version='v201802') # Create a statement to select placements. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/dfp/v201705/placement_service/get_all_placements.py b/examples/dfp/v201802/placement_service/get_all_placements.py similarity index 99% rename from examples/dfp/v201705/placement_service/get_all_placements.py rename to examples/dfp/v201802/placement_service/get_all_placements.py index 20889bf0..2217dedf 100755 --- a/examples/dfp/v201705/placement_service/get_all_placements.py +++ b/examples/dfp/v201802/placement_service/get_all_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') + placement_service = client.GetService('PlacementService', version='v201802') # Create a statement to select placements. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/placement_service/update_placements.py b/examples/dfp/v201802/placement_service/update_placements.py similarity index 96% rename from examples/dfp/v201705/placement_service/update_placements.py rename to examples/dfp/v201802/placement_service/update_placements.py index 371f6187..e629c072 100755 --- a/examples/dfp/v201705/placement_service/update_placements.py +++ b/examples/dfp/v201802/placement_service/update_placements.py @@ -28,14 +28,14 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') + placement_service = client.GetService('PlacementService', version='v201802') # Create query. statement = (dfp.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) - .WithBindVariable('id', PLACEMENT_ID)) + .WithBindVariable('id', placement_id)) # Get placements by statement. page = placement_service.getPlacementsByStatement( diff --git a/examples/dfp/v201705/premium_rate_service/__init__.py b/examples/dfp/v201802/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201705/premium_rate_service/__init__.py rename to examples/dfp/v201802/premium_rate_service/__init__.py diff --git a/examples/dfp/v201705/premium_rate_service/create_premium_rates.py b/examples/dfp/v201802/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/dfp/v201705/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201802/premium_rate_service/create_premium_rates.py index fa6b6b19..d9398c0e 100755 --- a/examples/dfp/v201705/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201802/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201705') + version='v201802') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py similarity index 97% rename from examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py index 21c6b3d6..134fb4b4 100755 --- a/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201705') + 'PremiumRateService', version='v201802') # Create a statement to select premium rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 87% rename from examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py index b374c9cf..26962a18 100755 --- a/examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,17 +25,11 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201705') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] + 'PremiumRateService', version='v201802') # Create a statement to select premium rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/dfp/v201705/premium_rate_service/update_premium_rates.py b/examples/dfp/v201802/premium_rate_service/update_premium_rates.py similarity index 90% rename from examples/dfp/v201705/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201802/premium_rate_service/update_premium_rates.py index 6058b78b..05594e2f 100755 --- a/examples/dfp/v201705/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201802/premium_rate_service/update_premium_rates.py @@ -30,18 +30,14 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201705') + version='v201802') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': premium_rate_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(premium_rate_id)) + .Limit(1)) # Get the premium rate. response = premium_rate_service.getPremiumRatesByStatement( diff --git a/examples/dfp/v201705/product_package_item_service/create_product_package_item.py b/examples/dfp/v201802/product_package_item_service/create_product_package_item.py similarity index 99% rename from examples/dfp/v201705/product_package_item_service/create_product_package_item.py rename to examples/dfp/v201802/product_package_item_service/create_product_package_item.py index 9df8892f..e1647699 100755 --- a/examples/dfp/v201705/product_package_item_service/create_product_package_item.py +++ b/examples/dfp/v201802/product_package_item_service/create_product_package_item.py @@ -32,7 +32,7 @@ def main(client): product_package_item_service = client.GetService('ProductPackageItemService', - version='v201705') + version='v201802') product_package_item = { # Set the product from which the product package item is created. diff --git a/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py similarity index 97% rename from examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py rename to examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py index 536f23bb..78937795 100755 --- a/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201705') + 'ProductPackageItemService', version='v201802') # Create a statement to select product package items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py similarity index 86% rename from examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py index dfabfe6f..c353c58c 100755 --- a/examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,17 +25,11 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201705') - query = 'WHERE productPackageId = :productPackageId' - values = [ - {'key': 'productPackageId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_package_id - }}, - ] + 'ProductPackageItemService', version='v201802') # Create a statement to select product package items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productPackageId = :productPackageId') + .WithBindVariable('productPackageId', product_package_id)) # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/dfp/v201705/product_package_service/create_product_packages.py b/examples/dfp/v201802/product_package_service/create_product_packages.py similarity index 96% rename from examples/dfp/v201705/product_package_service/create_product_packages.py rename to examples/dfp/v201802/product_package_service/create_product_packages.py index 5c8f128c..36339471 100755 --- a/examples/dfp/v201705/product_package_service/create_product_packages.py +++ b/examples/dfp/v201802/product_package_service/create_product_packages.py @@ -30,7 +30,7 @@ def main(client): product_package_service = client.GetService('ProductPackageService', - version='v201705') + version='v201802') # Create a local product package. product_package = { diff --git a/examples/dfp/v201705/product_package_service/get_active_product_packages.py b/examples/dfp/v201802/product_package_service/get_active_product_packages.py similarity index 86% rename from examples/dfp/v201705/product_package_service/get_active_product_packages.py rename to examples/dfp/v201802/product_package_service/get_active_product_packages.py index a08b4733..73d509a0 100755 --- a/examples/dfp/v201705/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201802/product_package_service/get_active_product_packages.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'ProductPackageService', version='v201802') # Create a statement to select product packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/dfp/v201705/product_package_service/get_all_product_packages.py b/examples/dfp/v201802/product_package_service/get_all_product_packages.py similarity index 97% rename from examples/dfp/v201705/product_package_service/get_all_product_packages.py rename to examples/dfp/v201802/product_package_service/get_all_product_packages.py index 06c1abed..51227e64 100755 --- a/examples/dfp/v201705/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201802/product_package_service/get_all_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201705') + 'ProductPackageService', version='v201802') # Create a statement to select product packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/product_service/__init__.py b/examples/dfp/v201802/product_service/__init__.py similarity index 100% rename from examples/dfp/v201705/product_service/__init__.py rename to examples/dfp/v201802/product_service/__init__.py diff --git a/examples/dfp/v201705/product_service/get_all_products.py b/examples/dfp/v201802/product_service/get_all_products.py similarity index 99% rename from examples/dfp/v201705/product_service/get_all_products.py rename to examples/dfp/v201802/product_service/get_all_products.py index 8ac87c31..9b9fc377 100755 --- a/examples/dfp/v201705/product_service/get_all_products.py +++ b/examples/dfp/v201802/product_service/get_all_products.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201705') + product_service = client.GetService('ProductService', version='v201802') # Create a statement to select products. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/product_service/get_products_for_product_template.py b/examples/dfp/v201802/product_service/get_products_for_product_template.py similarity index 86% rename from examples/dfp/v201705/product_service/get_products_for_product_template.py rename to examples/dfp/v201802/product_service/get_products_for_product_template.py index 94d11ad7..adb92de4 100755 --- a/examples/dfp/v201705/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201802/product_service/get_products_for_product_template.py @@ -24,18 +24,12 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201705') - - query = 'WHERE productTemplateId = :productTemplateId' - values = [ - {'key': 'productTemplateId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_template_id - }}, - ] + product_service = client.GetService('ProductService', version='v201802') + # Create a statement to select products. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productTemplateId = :productTemplateId') + .WithBindVariable('productTemplateId', product_template_id)) # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/dfp/v201705/product_service/update_products.py b/examples/dfp/v201802/product_service/update_products.py similarity index 90% rename from examples/dfp/v201705/product_service/update_products.py rename to examples/dfp/v201802/product_service/update_products.py index af2905db..8697a04c 100755 --- a/examples/dfp/v201705/product_service/update_products.py +++ b/examples/dfp/v201802/product_service/update_products.py @@ -29,18 +29,13 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201705') + product_service = client.GetService('ProductService', version='v201802') # Create statement object to select a single product by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, product_id): else: print 'No products found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/product_template_service/__init__.py b/examples/dfp/v201802/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201705/product_template_service/__init__.py rename to examples/dfp/v201802/product_template_service/__init__.py diff --git a/examples/dfp/v201705/product_template_service/activate_product_templates.py b/examples/dfp/v201802/product_template_service/activate_product_templates.py similarity index 89% rename from examples/dfp/v201705/product_template_service/activate_product_templates.py rename to examples/dfp/v201802/product_template_service/activate_product_templates.py index a15d5102..6d517f59 100755 --- a/examples/dfp/v201705/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201802/product_template_service/activate_product_templates.py @@ -31,18 +31,13 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201802') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) product_templates_activated = 0 diff --git a/examples/dfp/v201705/product_template_service/create_product_templates.py b/examples/dfp/v201802/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201705/product_template_service/create_product_templates.py rename to examples/dfp/v201802/product_template_service/create_product_templates.py index 94f5a3d3..d8cbf034 100755 --- a/examples/dfp/v201705/product_template_service/create_product_templates.py +++ b/examples/dfp/v201802/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201802') network_service = client.GetService( - 'NetworkService', version='v201705') + 'NetworkService', version='v201802') # Create a product template. product_template = { diff --git a/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py similarity index 96% rename from examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py rename to examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py index 3d917835..19b4d348 100755 --- a/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201802') network_service = client.GetService( - 'NetworkService', version='v201705') + 'NetworkService', version='v201802') product_template = { # Setting required Marketplace information. diff --git a/examples/dfp/v201705/product_template_service/get_all_product_templates.py b/examples/dfp/v201802/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201705/product_template_service/get_all_product_templates.py rename to examples/dfp/v201802/product_template_service/get_all_product_templates.py index 7114a26a..11f57816 100755 --- a/examples/dfp/v201705/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201802/product_template_service/get_all_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201802') # Create a statement to select product templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py similarity index 85% rename from examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py index a5108bf0..6c6e6f1b 100755 --- a/examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') - query = 'WHERE lineItemType = :lineItemType' - values = [ - {'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - }}, - ] + 'ProductTemplateService', version='v201802') # Create a statement to select product templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemType = :lineItemType') + .WithBindVariable('lineItemType', 'SPONSORSHIP')) # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/dfp/v201705/product_template_service/update_product_templates.py b/examples/dfp/v201802/product_template_service/update_product_templates.py similarity index 90% rename from examples/dfp/v201705/product_template_service/update_product_templates.py rename to examples/dfp/v201802/product_template_service/update_product_templates.py index 8116f7f3..36dda17f 100755 --- a/examples/dfp/v201705/product_template_service/update_product_templates.py +++ b/examples/dfp/v201802/product_template_service/update_product_templates.py @@ -30,18 +30,14 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201802') # Create a statement to select a single product template by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) # Get product templates by statement. response = product_template_service.getProductTemplatesByStatement( diff --git a/examples/dfp/v201705/proposal_line_item_service/__init__.py b/examples/dfp/v201802/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201705/proposal_line_item_service/__init__.py rename to examples/dfp/v201802/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py similarity index 89% rename from examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py index b2b6c76c..095c02b1 100755 --- a/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py @@ -31,18 +31,13 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') + 'ProposalLineItemService', version='v201802') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) proposal_line_items_archived = 0 diff --git a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 98% rename from examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py index e9e2ab71..ed61a734 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -40,8 +40,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + 'ProposalLineItemService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') # Get the root ad unit to target. root_ad_unit_id = ( diff --git a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 98% rename from examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index bb198790..e49b1679 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -34,8 +34,8 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + 'ProposalLineItemService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py index 616195f3..25106570 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py @@ -42,8 +42,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + 'ProposalLineItemService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py similarity index 97% rename from examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py index 254e0dd0..a448e012 100755 --- a/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') + 'ProposalLineItemService', version='v201802') # Create a statement to select proposal line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 86% rename from examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 3600e25d..03368306 100755 --- a/examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,17 +25,11 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') - query = 'WHERE proposalId = :proposalId' - values = [ - {'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - }}, - ] + 'ProposalLineItemService', version='v201802') # Create a statement to select proposal line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('proposalId = :proposalId') + .WithBindVariable('proposalId', proposal_id)) # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py similarity index 89% rename from examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py index 16f4bc98..4a559c5f 100755 --- a/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py @@ -31,19 +31,14 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') + 'ProposalLineItemService', version='v201802') # Create statement to select a proposal line item. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) # Get proposal line items by statement. response = proposal_line_item_service.getProposalLineItemsByStatement( diff --git a/examples/dfp/v201705/proposal_service/__init__.py b/examples/dfp/v201802/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201705/proposal_service/__init__.py rename to examples/dfp/v201802/proposal_service/__init__.py diff --git a/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201802/proposal_service/create_programmatic_proposals.py similarity index 98% rename from examples/dfp/v201705/proposal_service/create_programmatic_proposals.py rename to examples/dfp/v201802/proposal_service/create_programmatic_proposals.py index 02277928..b367a445 100755 --- a/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201802/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 99% rename from examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 1db0c9e0..9021632a 100755 --- a/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201705/proposal_service/create_proposals.py b/examples/dfp/v201802/proposal_service/create_proposals.py similarity index 99% rename from examples/dfp/v201705/proposal_service/create_proposals.py rename to examples/dfp/v201802/proposal_service/create_proposals.py index d2a2e346..5cfe3820 100755 --- a/examples/dfp/v201705/proposal_service/create_proposals.py +++ b/examples/dfp/v201802/proposal_service/create_proposals.py @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201705/proposal_service/get_all_proposals.py b/examples/dfp/v201802/proposal_service/get_all_proposals.py similarity index 99% rename from examples/dfp/v201705/proposal_service/get_all_proposals.py rename to examples/dfp/v201802/proposal_service/get_all_proposals.py index 57258dca..ee9a6082 100755 --- a/examples/dfp/v201705/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201802/proposal_service/get_all_proposals.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') # Create a statement to select proposals. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/proposal_service/get_marketplace_comments.py b/examples/dfp/v201802/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/dfp/v201705/proposal_service/get_marketplace_comments.py rename to examples/dfp/v201802/proposal_service/get_marketplace_comments.py index 56839ca9..63e4683b 100755 --- a/examples/dfp/v201705/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201802/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201705') + 'ProposalService', version='v201802') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py similarity index 87% rename from examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py rename to examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py index 0da9e017..6f6d47d6 100755 --- a/examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - }}, - ] + proposal_service = client.GetService('ProposalService', version='v201802') # Create a statement to select proposals. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'PENDING_APPROVAL')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py similarity index 89% rename from examples/dfp/v201705/proposal_service/request_buyers_acceptance.py rename to examples/dfp/v201802/proposal_service/request_buyers_acceptance.py index 68e3598e..baabcef4 100755 --- a/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py @@ -26,20 +26,12 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo programmatic proposals were pushed to Marketplace.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py similarity index 88% rename from examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py index 51f8b2b2..98cf90cb 100755 --- a/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py @@ -28,20 +28,12 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo proposals were approved.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/proposal_service/update_proposals.py b/examples/dfp/v201802/proposal_service/update_proposals.py similarity index 89% rename from examples/dfp/v201705/proposal_service/update_proposals.py rename to examples/dfp/v201802/proposal_service/update_proposals.py index 7f4e6d13..3cbe6e7d 100755 --- a/examples/dfp/v201705/proposal_service/update_proposals.py +++ b/examples/dfp/v201802/proposal_service/update_proposals.py @@ -28,19 +28,14 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', long(proposal_id)) + .Limit(1)) # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, proposal_id): else: print 'No proposals found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/publisher_query_language_service/__init__.py b/examples/dfp/v201802/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201705/publisher_query_language_service/__init__.py rename to examples/dfp/v201802/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py index f6b3d558..49c456d6 100755 --- a/examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201802') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py b/examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py new file mode 100755 index 00000000..e3c0ac25 --- /dev/null +++ b/examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 browsers available to target from the Browser table. + +Other tables include 'Bandwidth_Group', 'Browser_Language', +'Device_Capability', 'Operating_System', etc... + +A full list of available criteria tables can be found at +https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService +""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201802') + + with tempfile.NamedTemporaryFile( + prefix='browser_data_', + suffix='.csv', mode='w', delete=False) as browser_data_file: + + browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion ' + 'FROM Browser ' + 'ORDER BY BrowserName ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + browser_pql_query, browser_data_file) + + print 'Saved browser data to... %s' % browser_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py index cdda977e..51243ca7 100755 --- a/examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201705') + data_downloader = client.GetDataDownloader(version='v201802') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py new file mode 100755 index 00000000..80183382 --- /dev/null +++ b/examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 downloads geo targeting constants using PQL.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the type of geo target to query for. +GEO_TARGET_TYPE = 'City' + + +def main(client, geo_target_type): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201802') + + with tempfile.NamedTemporaryFile( + prefix='geo_data_', + suffix='.csv', mode='w', delete=False) as geo_data_file: + + geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' + 'CountryCode ' + 'FROM Geo_Target ' + 'WHERE Type = :type AND Targetable = true ' + 'ORDER BY CountryCode ASC, Name ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + geo_pql_query, geo_data_file, {'type': geo_target_type}) + + print 'Saved geo data to... %s' % geo_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, GEO_TARGET_TYPE) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py new file mode 100755 index 00000000..0d14cd53 --- /dev/null +++ b/examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 fetches line items from the pql table with a LIKE clause.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201802') + + with tempfile.NamedTemporaryFile( + prefix='line_items_', + suffix='.csv', mode='w', delete=False) as line_items_file: + + line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item " + "WHERE Name LIKE 'line item%' " + "ORDER BY Id ASC") + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + line_items_pql_query, line_items_file) + + print 'Saved line items to... %s' % line_items_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py similarity index 66% rename from examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py rename to examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py index 70c30b66..61f13440 100755 --- a/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py +++ b/examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py @@ -31,52 +31,23 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201705') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201802') - end_date = date.today() + end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) - initial_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE ChangeDateTime > :startDateTime ' - 'AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - pagination_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE Id < :id ' - 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - values = [ - { - 'key': 'startDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day - } - } - } - }, - { - 'key': 'endDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day - } - } - } - } - ] - - statement = dfp.FilterStatement(initial_query, values) + initial_query = ('ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime') + pagination_query = 'Id < :id AND ' + initial_query + + statement = (dfp.StatementBuilder() + .Select(('Id, ChangeDateTime, EntityId, EntityType, ' + 'Operation, UserId')) + .From('Change_History') + .Where(initial_query) + .OrderBy('ChangeDateTime', ascending=False) + .WithBindVariable('startDateTime', start_date) + .WithBindVariable('endDateTime', end_date)) + keep_iterating = True i = 0 total_rows = [] @@ -94,8 +65,11 @@ def main(client): last_row = rows[-1] last_id = last_row['values'][0]['value'] i += 1 - statement = UpdateFilterStatement( - statement, pagination_query, values, last_id) + + # Update the statement using the earliest row in the previous result. + statement.Where(pagination_query) + statement.WithBindVariable('id', last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' % (i, rows_length, last_id)) @@ -109,34 +83,6 @@ def main(client): print ConvertValueForCsv(row) -def UpdateFilterStatement(statement, query, values, last_id): - """Updates the FilterStatement in order to page through results. - - Args: - statement: an instantiated FilterStatement. - query: a str query that will be used to update the FilterStatement. - values: a list of bind variables to be updated. - last_id: a str representing the earliest change ID in a result set. - - Returns: - FilterStatement the updated statement. - """ - # Use the earliest change ID in the result set to page. - updated_values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_id - } - }] - updated_values.extend(values) - - statement.where_clause = query - statement.values = updated_values - - return statement - - def ConvertValueForCsv(pql_value): """Sanitizes a field value from a Value object to a CSV suitable format. diff --git a/examples/dfp/v201705/rate_card_service/__init__.py b/examples/dfp/v201802/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201705/rate_card_service/__init__.py rename to examples/dfp/v201802/rate_card_service/__init__.py diff --git a/examples/dfp/v201705/rate_card_service/create_rate_cards.py b/examples/dfp/v201802/rate_card_service/create_rate_cards.py similarity index 99% rename from examples/dfp/v201705/rate_card_service/create_rate_cards.py rename to examples/dfp/v201802/rate_card_service/create_rate_cards.py index 38142f18..bbb198d0 100755 --- a/examples/dfp/v201705/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/create_rate_cards.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201705') + rate_card_service = client.GetService('RateCardService', version='v201802') # Create a rate card. rate_card = { diff --git a/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py similarity index 99% rename from examples/dfp/v201705/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201802/rate_card_service/get_all_rate_cards.py index 73469628..c0fd27a7 100755 --- a/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201705') + rate_card_service = client.GetService('RateCardService', version='v201802') # Create a statement to select rate cards. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py similarity index 87% rename from examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py rename to examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py index 232f0fd7..5220fc13 100755 --- a/examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201705') - query = 'WHERE forMarketplace = :forMarketplace' - values = [ - {'key': 'forMarketplace', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + rate_card_service = client.GetService('RateCardService', version='v201802') # Create a statement to select rate cards. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('forMarketplace = :forMarketplace') + .WithBindVariable('forMarketplace', True)) # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 97% rename from examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 98a6c659..bbb62cd9 100755 --- a/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201705')) + 'ReconciliationLineItemReportService', version='v201802')) # Create a statement to select reconciliation line item reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 97% rename from examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index f80694cf..bdcd877e 100755 --- a/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201705')) + 'ReconciliationLineItemReportService', version='v201802')) # Create a statement to select a reconciliation line item report. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index e9ce5265..9926d667 100755 --- a/examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,17 +25,12 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201705') - query = 'WHERE reconciliationReportId = :reconciliationReportId' - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - ] + 'ReconciliationOrderReportService', version='v201802') # Create a statement to select reconciliation order reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('reconciliationReportId = :reconciliationReportId') + .WithBindVariable('reconciliationReportId', + reconciliation_report_id)) # Retrieve a small amount of reconciliation order reports at a time, paging # through until all reconciliation order reports have been retrieved. diff --git a/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 97% rename from examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py index f282ce56..07b8c4f4 100755 --- a/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201705')) + 'ReconciliationOrderReportService', version='v201802')) # Create a statement to select reconciliation order reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 46803c99..b2fe2fbc 100755 --- a/examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -27,18 +27,14 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201705') - query = ('WHERE reconciliationReportId = %s AND ' - 'lineItemId != :lineItemId') % reconciliation_report_id - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - } - }] + 'ReconciliationReportRowService', version='v201802') + # Create a statement to select reconciliation report rows. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reportId ' + 'AND lineItemId != :lineItemId')) + .WithBindVariable('lineItemId', 0) + .WithBindVariable('reportId', long(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. diff --git a/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 97% rename from examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py index 38158171..fa7f2cc1 100755 --- a/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201705')) + 'ReconciliationReportRowService', version='v201802')) # Create a statement to select reconciliation report rows. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 97% rename from examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py index 54fdc3a0..7c465090 100755 --- a/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201705') + 'ReconciliationReportService', version='v201802') # Create a statement to select reconciliation reports. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 97% rename from examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 7f8536cd..4674bc93 100755 --- a/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201705') + 'ReconciliationReportService', version='v201802') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) diff --git a/examples/dfp/v201705/report_service/__init__.py b/examples/dfp/v201802/report_service/__init__.py similarity index 100% rename from examples/dfp/v201705/report_service/__init__.py rename to examples/dfp/v201802/report_service/__init__.py diff --git a/examples/dfp/v201802/report_service/run_ad_exchange_report.py b/examples/dfp/v201802/report_service/run_ad_exchange_report.py new file mode 100755 index 00000000..f6ebfee5 --- /dev/null +++ b/examples/dfp/v201802/report_service/run_ad_exchange_report.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Runs a report on Ad Exchange data via the DFP API.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201802') + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'], + 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS', + 'AD_EXCHANGE_ESTIMATED_REVENUE'], + 'dateRangeType': 'LAST_WEEK', + 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time + 'adxReportCurrency': 'EUR' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/report_service/run_delivery_report.py b/examples/dfp/v201802/report_service/run_delivery_report.py similarity index 88% rename from examples/dfp/v201705/report_service/run_delivery_report.py rename to examples/dfp/v201802/report_service/run_delivery_report.py index 055969a3..48fa9bcf 100755 --- a/examples/dfp/v201705/report_service/run_delivery_report.py +++ b/examples/dfp/v201802/report_service/run_delivery_report.py @@ -32,15 +32,11 @@ def main(client, order_id): # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - filter_statement = {'query': 'WHERE ORDER_ID = :id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('ORDER_ID = :id') + .WithBindVariable('id', long(order_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Set the start and end dates of the report to run (past 8 days). end_date = datetime.now().date() @@ -52,7 +48,7 @@ def main(client, order_id): 'dimensions': ['ORDER_ID', 'ORDER_NAME'], 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', 'ORDER_END_DATE_TIME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], @@ -63,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201802') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201705/report_service/run_inventory_report.py b/examples/dfp/v201802/report_service/run_inventory_report.py similarity index 83% rename from examples/dfp/v201705/report_service/run_inventory_report.py rename to examples/dfp/v201802/report_service/run_inventory_report.py index 3e07905a..be8e2835 100755 --- a/examples/dfp/v201705/report_service/run_inventory_report.py +++ b/examples/dfp/v201802/report_service/run_inventory_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report equal to the "Whole network report" on the DFP website.""" +"""This example runs a typical daily inventory report.""" import tempfile @@ -25,24 +25,20 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201705') + network_service = client.GetService('NetworkService', version='v201802') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201802') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - values = [{ - 'key': 'parent_ad_unit_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': root_ad_unit_id - } - }] - filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') + .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Create report job. report_job = { @@ -55,7 +51,7 @@ def main(client): 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', - 'statement': filter_statement + 'statement': statement.ToStatement() } } diff --git a/examples/dfp/v201705/report_service/run_reach_report.py b/examples/dfp/v201802/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201705/report_service/run_reach_report.py rename to examples/dfp/v201802/report_service/run_reach_report.py index ffd4f971..1f83a5ec 100755 --- a/examples/dfp/v201705/report_service/run_reach_report.py +++ b/examples/dfp/v201802/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201802') # Create report job. report_job = { diff --git a/examples/dfp/v201705/report_service/run_report_and_create_match_table.py b/examples/dfp/v201802/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/dfp/v201705/report_service/run_report_and_create_match_table.py rename to examples/dfp/v201802/report_service/run_report_and_create_match_table.py index 498cb9b0..def767a9 100755 --- a/examples/dfp/v201705/report_service/run_report_and_create_match_table.py +++ b/examples/dfp/v201802/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201802') try: # Run the report and wait for it to finish. @@ -69,7 +69,7 @@ def main(client): report_job_id, 'CSV_DUMP', report_file) # Create a PQL query to fetch the line item data - line_items_pql_query = ('SELECT Id, LineItemType, Status FROM Line_Item') + line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem') # Download the response from PQL select statement line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) diff --git a/examples/dfp/v201705/report_service/run_report_with_custom_fields.py b/examples/dfp/v201802/report_service/run_report_with_custom_fields.py similarity index 85% rename from examples/dfp/v201705/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201802/report_service/run_report_with_custom_fields.py index 20f080f5..0b7aa111 100755 --- a/examples/dfp/v201705/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201802/report_service/run_report_with_custom_fields.py @@ -28,22 +28,14 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201802') # Filter for line items of a given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE orderId = :orderId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId') + .WithBindVariable('orderId', long(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -62,14 +54,16 @@ def main(client, order_id): else: break - # Create statement object to filter for an order. - filter_statement = {'query': query, 'values': values} + # Modify statement for reports + statement.limit = None + statement.offset = None + statement.Where('ORDER_ID = :orderId') # Create report job. report_job = { 'reportQuery': { 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', 'customFieldIds': list(custom_field_ids) diff --git a/examples/dfp/v201705/report_service/run_sales_report.py b/examples/dfp/v201802/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201705/report_service/run_sales_report.py rename to examples/dfp/v201802/report_service/run_sales_report.py index cf7d623b..d8411c93 100755 --- a/examples/dfp/v201705/report_service/run_sales_report.py +++ b/examples/dfp/v201802/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201802') # Create report job. report_job = { diff --git a/examples/dfp/v201705/report_service/run_saved_query.py b/examples/dfp/v201802/report_service/run_saved_query.py similarity index 89% rename from examples/dfp/v201705/report_service/run_saved_query.py rename to examples/dfp/v201802/report_service/run_saved_query.py index 7a8fdd94..ca0815df 100755 --- a/examples/dfp/v201705/report_service/run_saved_query.py +++ b/examples/dfp/v201802/report_service/run_saved_query.py @@ -28,21 +28,16 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201705') + report_service = client.GetService('ReportService', version='v201802') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201802') # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': saved_query_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(saved_query_id)) + .Limit(1)) response = report_service.getSavedQueriesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201705/suggested_ad_unit_service/__init__.py b/examples/dfp/v201802/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201705/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201802/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 0a2bd663..e1333c59 100755 --- a/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201705') + 'SuggestedAdUnitService', version='v201802') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py index 39046b06..d8f8e923 100755 --- a/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201705') + 'SuggestedAdUnitService', version='v201802') # Create a statement to select suggested ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 86% rename from examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 355b47c3..8b2f5184 100755 --- a/examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,17 +25,11 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201705') - query = 'WHERE numRequests >= :numRequests' - values = [ - {'key': 'numRequests', - 'value': { - 'xsi_type': 'TextValue', - 'value': num_requests - }}, - ] + 'SuggestedAdUnitService', version='v201802') # Create a statement to select suggested ad units. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests >= :numRequests') + .WithBindVariable('numRequests', long(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/dfp/v201705/team_service/__init__.py b/examples/dfp/v201802/team_service/__init__.py similarity index 100% rename from examples/dfp/v201705/team_service/__init__.py rename to examples/dfp/v201802/team_service/__init__.py diff --git a/examples/dfp/v201705/team_service/create_teams.py b/examples/dfp/v201802/team_service/create_teams.py similarity index 96% rename from examples/dfp/v201705/team_service/create_teams.py rename to examples/dfp/v201802/team_service/create_teams.py index 05b40daf..5265d8d0 100755 --- a/examples/dfp/v201705/team_service/create_teams.py +++ b/examples/dfp/v201802/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201705') + team_service = client.GetService('TeamService', version='v201802') # Create team objects. teams = [] diff --git a/examples/dfp/v201705/team_service/get_all_teams.py b/examples/dfp/v201802/team_service/get_all_teams.py similarity index 95% rename from examples/dfp/v201705/team_service/get_all_teams.py rename to examples/dfp/v201802/team_service/get_all_teams.py index 1b5b9364..11e8653e 100755 --- a/examples/dfp/v201705/team_service/get_all_teams.py +++ b/examples/dfp/v201802/team_service/get_all_teams.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201705') + team_service = client.GetService('TeamService', version='v201802') # Create a statement to select teams. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/team_service/update_teams.py b/examples/dfp/v201802/team_service/update_teams.py similarity index 87% rename from examples/dfp/v201705/team_service/update_teams.py rename to examples/dfp/v201802/team_service/update_teams.py index aad3c8e6..2e6a8c45 100755 --- a/examples/dfp/v201705/team_service/update_teams.py +++ b/examples/dfp/v201802/team_service/update_teams.py @@ -34,18 +34,12 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201705') + team_service = client.GetService('TeamService', version='v201802') # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :teamId') + .WithBindVariable('teamId', long(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -67,6 +61,7 @@ def main(client, team_id): else: print 'No teams found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/user_service/__init__.py b/examples/dfp/v201802/user_service/__init__.py similarity index 100% rename from examples/dfp/v201705/user_service/__init__.py rename to examples/dfp/v201802/user_service/__init__.py diff --git a/examples/dfp/v201705/user_service/create_users.py b/examples/dfp/v201802/user_service/create_users.py similarity index 95% rename from examples/dfp/v201705/user_service/create_users.py rename to examples/dfp/v201802/user_service/create_users.py index dd1043b3..021bb596 100755 --- a/examples/dfp/v201705/user_service/create_users.py +++ b/examples/dfp/v201802/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201802') # Create user objects. users = [ diff --git a/examples/dfp/v201705/user_service/deactivate_users.py b/examples/dfp/v201802/user_service/deactivate_users.py similarity index 86% rename from examples/dfp/v201705/user_service/deactivate_users.py rename to examples/dfp/v201802/user_service/deactivate_users.py index cf9590a6..771357d1 100755 --- a/examples/dfp/v201705/user_service/deactivate_users.py +++ b/examples/dfp/v201802/user_service/deactivate_users.py @@ -30,20 +30,12 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201802') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -66,6 +58,7 @@ def main(client, user_id): else: print 'No users were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/user_service/get_all_roles.py b/examples/dfp/v201802/user_service/get_all_roles.py similarity index 100% rename from examples/dfp/v201705/user_service/get_all_roles.py rename to examples/dfp/v201802/user_service/get_all_roles.py diff --git a/examples/dfp/v201705/user_service/get_all_users.py b/examples/dfp/v201802/user_service/get_all_users.py similarity index 95% rename from examples/dfp/v201705/user_service/get_all_users.py rename to examples/dfp/v201802/user_service/get_all_users.py index 54d5bac9..36c26a79 100755 --- a/examples/dfp/v201705/user_service/get_all_users.py +++ b/examples/dfp/v201802/user_service/get_all_users.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201802') # Create a statement to select users. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/user_service/get_current_user.py b/examples/dfp/v201802/user_service/get_current_user.py similarity index 94% rename from examples/dfp/v201705/user_service/get_current_user.py rename to examples/dfp/v201802/user_service/get_current_user.py index f2d762de..d04dcb56 100755 --- a/examples/dfp/v201705/user_service/get_current_user.py +++ b/examples/dfp/v201802/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201802') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201705/user_service/get_user_by_email_address.py b/examples/dfp/v201802/user_service/get_user_by_email_address.py similarity index 85% rename from examples/dfp/v201705/user_service/get_user_by_email_address.py rename to examples/dfp/v201802/user_service/get_user_by_email_address.py index 72a800b8..5c1cdb20 100755 --- a/examples/dfp/v201705/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201802/user_service/get_user_by_email_address.py @@ -24,17 +24,11 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') - query = 'WHERE email = :email' - values = [ - {'key': 'email', - 'value': { - 'xsi_type': 'TextValue', - 'value': email_address - }}, - ] + user_service = client.GetService('UserService', version='v201802') # Create a statement to select users. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('email = :email') + .WithBindVariable('email', email_address)) # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/dfp/v201705/user_service/update_users.py b/examples/dfp/v201802/user_service/update_users.py similarity index 83% rename from examples/dfp/v201705/user_service/update_users.py rename to examples/dfp/v201802/user_service/update_users.py index e072358e..2786043e 100755 --- a/examples/dfp/v201705/user_service/update_users.py +++ b/examples/dfp/v201802/user_service/update_users.py @@ -28,20 +28,12 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201802') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -59,6 +51,7 @@ def main(client, user_id): else: print 'No users found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/user_team_association_service/__init__.py b/examples/dfp/v201802/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201705/user_team_association_service/__init__.py rename to examples/dfp/v201802/user_team_association_service/__init__.py diff --git a/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201705/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201802/user_team_association_service/create_user_team_associations.py index 28a2bf1a..6f55df77 100755 --- a/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') + 'UserTeamAssociationService', version='v201802') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py similarity index 87% rename from examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py index d00f760d..85d04bc8 100755 --- a/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py @@ -35,20 +35,12 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') + 'UserTeamAssociationService', version='v201802') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -62,10 +54,14 @@ def main(client, user_id): print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) + # Action doesn't require limit/offset + statement.limit = None + statement.offset = None + # Perform action. result = user_team_association_service.performUserTeamAssociationAction( {'xsi_type': 'DeleteUserTeamAssociations'}, - {'query': query, 'values': values}) + statement.ToStatement()) # Display results. if result and int(result['numChanges']) > 0: @@ -74,6 +70,7 @@ def main(client, user_id): else: print 'No user team associations were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py similarity index 97% rename from examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py index 4daad809..631a9734 100755 --- a/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') + 'UserTeamAssociationService', version='v201802') # Create a statement to select user team associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py similarity index 87% rename from examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py index 7e492989..8413cad0 100755 --- a/examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py @@ -25,17 +25,11 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') - query = 'WHERE userId = :userId' - values = [ - {'key': 'userId', - 'value': { - 'xsi_type': 'TextValue', - 'value': user_id - }}, - ] + 'UserTeamAssociationService', version='v201802') # Create a statement to select user team associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py similarity index 89% rename from examples/dfp/v201705/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201802/user_team_association_service/update_user_team_associations.py index 2266e140..4f88e43f 100755 --- a/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py @@ -37,20 +37,12 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') + 'UserTeamAssociationService', version='v201802') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -79,6 +71,7 @@ def main(client, user_id): else: print 'No user team associations found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/workflow_request_service/__init__.py b/examples/dfp/v201802/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201705/workflow_request_service/__init__.py rename to examples/dfp/v201802/workflow_request_service/__init__.py diff --git a/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py similarity index 76% rename from examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py index 503c9eab..5efc45eb 100755 --- a/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py @@ -31,37 +31,15 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201705') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') + version='v201802') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) workflow_approval_requests_approved = 0 # Get workflow approval requests by statement. diff --git a/examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py similarity index 87% rename from examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py rename to examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py index c1276194..b2635616 100755 --- a/examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py @@ -26,17 +26,11 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - }}, - ] + 'WorkflowRequestService', version='v201802') # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py similarity index 86% rename from examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py index 7e7da01f..71c4541e 100755 --- a/examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,17 +26,11 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - }}, - ] + 'WorkflowRequestService', version='v201802') # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 78% rename from examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py index d966ae68..394922c9 100755 --- a/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,37 +31,15 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201705') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') + version='v201802') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) workflow_external_condition_requests_triggered = 0 # Get workflow external condition requests by statement. diff --git a/googleads/adwords.py b/googleads/adwords.py index 84db6f5f..04d7169d 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -30,7 +30,6 @@ import suds.xsd.doctor import xmltodict import yaml - import googleads.common import googleads.errors @@ -43,52 +42,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201702': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineCallConversionFeedService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201705': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', diff --git a/googleads/common.py b/googleads/common.py index 8ab42b00..b8c50a8e 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -14,7 +14,6 @@ """Common client library functions and classes used by all products.""" - from functools import wraps import inspect import locale @@ -27,13 +26,11 @@ import urllib2 import warnings - import httplib2 import socks import suds import suds.transport.http import yaml - import googleads.errors import googleads.oauth2 import googleads.util @@ -65,7 +62,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '9.0.0' +VERSION = '10.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' @@ -270,9 +267,8 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, required_client_values, optional_product_values) except googleads.errors.GoogleAdsValueError as e: - e.message = ('Given yaml file, %s, ' - 'could not find some keys. %s' % (path, e.message)) - raise + raise googleads.errors.GoogleAdsValueError( + 'Given yaml file, %s, could not find some keys. %s' % (path, e)) return client_kwargs @@ -524,6 +520,22 @@ def RegisterUtility(utility_name, version_mapping=None): Returns: The decorated class. """ + def IsFunctionOrMethod(member): + """Determines if given member is a function or method. + + These two are used in combination to ensure that inspect finds all of a + given utility class's methods in both Python 2 and 3. + + Args: + member: object that is a member of a class, to be determined whether it is + a function or method. + + Returns: + A boolean that is True if the provided member is a function or method, or + False if it isn't. + """ + return inspect.isfunction(member) or inspect.ismethod(member) + def MethodDecorator(utility_method, version): """Decorates a method in the utility class.""" registry_name = ('%s/%s' % (utility_name, version) if version @@ -537,7 +549,7 @@ def Wrapper(*args, **kwargs): def ClassDecorator(cls): """Decorates a utility class.""" - for name, method in inspect.getmembers(cls, inspect.ismethod): + for name, method in inspect.getmembers(cls, predicate=IsFunctionOrMethod): # Public methods of the class will have the decorator applied. if not name.startswith('_'): # The decorator will only be applied to unbound methods; this prevents diff --git a/googleads/dfp.py b/googleads/dfp.py index 5cf1f7cc..8269b202 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -20,13 +20,13 @@ import logging import numbers import os +import sys import time import urllib2 import pytz import suds.client import suds.transport - import googleads.common import googleads.errors @@ -46,7 +46,7 @@ # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201702': + 'v201705': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -68,7 +68,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201705': + 'v201708': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -90,15 +90,15 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201708': + 'v201711': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentMetadataKeyHierarchyService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', - 'InventoryService', 'LabelService', + 'CdnConfigurationService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentMetadataKeyHierarchyService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', @@ -112,7 +112,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201711': + 'v201802': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', @@ -876,7 +876,12 @@ def _ConvertValueForCsv(self, pql_value): class_type = DfpClassType(pql_value) if class_type == 'TextValue': - return field.replace('"', '""').encode('UTF8') + s = field.replace('"', '""') + + # Encode UTF-8 characters for Python 2 only. + if sys.version_info.major < 3: + s = s.encode('UTF8') + return s elif class_type == 'NumberValue': return float(field) if '.' in field else int(field) elif class_type == 'DateTimeValue': diff --git a/googleads/util.py b/googleads/util.py index f2741994..4b9ab013 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -134,6 +134,8 @@ def PatchedHttpTransportSend(self, request): raise suds.transport.TransportError(e.msg, e.code, e.fp) self.getcookies(fp, u2request) + # Note: Python 2 returns httplib.HTTPMessage, and Python 3 returns + # http.client.HTTPMessage, which differ slightly. headers = (fp.headers.dict if sys.version_info < (3, 0) else fp.headers) result = suds.transport.Reply(200, headers, fp.read()) @@ -293,8 +295,11 @@ def filter(self, record): if self._AUTHORIZATION_HEADER in sanitized_headers: sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED new_arg.headers = sanitized_headers + msg = arg.message + if sys.version_info.major < 3: + msg = msg.decode('utf-8') new_arg.message = self._DEVELOPER_TOKEN_SUB.sub( - self._REDACTED, arg.message.decode('utf-8')) + self._REDACTED, msg) record.args = (new_arg,) return True diff --git a/setup.py b/setup.py index 2c978f1e..f453fad2 100755 --- a/setup.py +++ b/setup.py @@ -28,7 +28,9 @@ 'suds-jurko>=0.6,<0.7', 'pysocks>=1.5.6,<2.0.0', 'pytz>=2015.7', 'PyYAML>=3.11,<4.0', 'xmltodict>=0.9.2,<1.0.0'] -TEST_DEPENDENCIES = ['mock>=2.0.0,<3.0.0', 'pyfakefs>=3.2,<4.0'] +# Note: Breaking change introduced in pyfakefs 3.3. +TEST_DEPENDENCIES = ['mock>=2.0.0,<3.0.0', 'pyfakefs>=3.2,<3.3', + 'six>=1.11.0,<2.0.0'] CLASSIFIERS = [ 'Intended Audience :: Developers', diff --git a/tests/adwords_test.py b/tests/adwords_test.py index d364cc50..da380225 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -20,25 +20,20 @@ import io import os import re -import StringIO -import sys import tempfile import unittest -import urllib -import urllib2 from xml.etree import ElementTree - import googleads.adwords import googleads.common import googleads.errors -import testing import mock +import six import suds +from . import testing -PYTHON2 = sys.version_info[0] == 2 -URL_REQUEST_PATH = ('urllib2' if PYTHON2 else 'urllib.request') +URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] @@ -403,7 +398,7 @@ def testLoadFromStorageWithNoUserAgent(self): self.assertEquals(client.user_agent, 'unknown') def testGetService_success(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -436,7 +431,7 @@ def testGetService_success(self): packer=googleads.adwords._AdWordsPacker) def testGetService_successWithFileCache(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -460,7 +455,7 @@ def testGetService_successWithFileCache(self): self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_successWithNoCache(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -484,7 +479,7 @@ def testGetService_successWithNoCache(self): self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_successWithoutProxy(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use the default server without a proxy. @@ -517,7 +512,7 @@ def testGetService_badVersion(self): 'CampaignService', '11111') def testGetService_compressionEnabled(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] client = GetAdWordsClient() client.enable_compression = True @@ -563,8 +558,8 @@ def testServiceMap(self): for service, mapping in services.items(): wsdl_url = wsdl_url_template % (server, mapping, version, service) try: - urllib2.urlopen(wsdl_url) - except urllib2.HTTPError: + six.moves.urllib.request.urlopen(wsdl_url) + except six.moves.urllib.error.HTTPError: raise ValueError('AdWords API %s does not contain "%s" with mapping ' '"%s". The generated WSDL URL does not exist:\n%s' % (version, service, mapping, wsdl_url)) @@ -620,7 +615,8 @@ def testUploadOperations(self): with mock.patch('googleads.adwords.IncrementalUploadHelper' '._InitializeURL') as mock_init: mock_init.return_value = 'https://www.google.com' - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch( + '%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: self.batch_job_helper.UploadOperations([[]]) mock_open.assert_called_with(mock_request) @@ -817,7 +813,7 @@ def GenerateValidRequest(self, operation_type, num_operations=1): self.ExpandOperandTemplate(operation_type, op['operand']) ) for op in ops]) - request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % ( + request = self.RAW_API_REQUEST_TEMPLATE % ( self.version, self.version, method, ops_xml, method) return (ops, request) @@ -998,7 +994,7 @@ def testGenerateRawRequestXMLFromSingleOperation(self): operations = mutate[i] self.assertEqual(operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1009,7 +1005,8 @@ def testGenerateRawRequestXMLFromSingleOperation(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1018,7 +1015,7 @@ def testGenerateRawRequestXMLFromSingleOperation(self): ops[i]['operand']['name']) amount = operand.find('{%s}amount' % self.request_builder._adwords_endpoint) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1045,7 +1042,7 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1054,7 +1051,8 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1063,7 +1061,7 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): ops[i]['operand']['name']) amount = operand.find( '{%s}amount' % self.request_builder._adwords_endpoint) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1089,7 +1087,7 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): operations = mutate[i] self.assertEqual(operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1100,7 +1098,8 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1109,7 +1108,7 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): ops[i]['operand']['name']) amount = operand.find('{%s}amount' % self.request_builder._adwords_endpoint) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1127,14 +1126,14 @@ def testGetRawOperationsFromValidSingleOperationMutateLabelRequest(self): mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual(mutate.tag, '{%s}mutateLabel' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1143,7 +1142,8 @@ def testGetRawOperationsFromValidSingleOperationMutateLabelRequest(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(int(operand.find( '{%s}campaignId' % self.request_builder._adwords_endpoint).text), ops[i]['operand']['campaignId']) @@ -1163,14 +1163,14 @@ def testGetRawOperationsFromValidSingleOperationRequest(self): mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual(mutate.tag, '{%s}mutate' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1179,7 +1179,8 @@ def testGetRawOperationsFromValidSingleOperationRequest(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1188,7 +1189,7 @@ def testGetRawOperationsFromValidSingleOperationRequest(self): ops[i]['operand']['name']) amount = operand.find( '{%s}amount' % self.request_builder._adwords_endpoint) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1210,14 +1211,14 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): self.assertEqual( mutate.tag, '{%s}mutate' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1226,7 +1227,8 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): ops[i]['xsi_type']) operand = (operations.find( '{%s}operand' % self.request_builder._adwords_endpoint)) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1235,7 +1237,7 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): ops[i]['operand']['name']) amount = (operand.find( '{%s}amount' % self.request_builder._adwords_endpoint)) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1256,14 +1258,14 @@ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): self.assertEqual( mutate.tag, u'{%s}mutate' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1272,7 +1274,8 @@ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): ops[i]['xsi_type']) operand = (operations.find( '{%s}operand' % self.request_builder._adwords_endpoint)) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1281,7 +1284,7 @@ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): ops[i]['operand']['name']) amount = (operand.find( '{%s}amount' % self.request_builder._adwords_endpoint)) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1301,7 +1304,7 @@ def testGetRawOperationsFromValidZeroOperationRequest(self): self.assertEqual( mutate.tag, '{%s}mutate' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) def testGetRawOperationsFromInvalidRequest(self): """Test whether an invalid API request raises an Exception.""" @@ -1406,7 +1409,7 @@ def setUp(self): self.original_url = 'https://goo.gl/w8tkpK' self.initialized_url = 'https://goo.gl/Xtaq83' - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: mock_open.return_value.headers = { 'location': self.initialized_url } @@ -1431,9 +1434,9 @@ def testDump(self): self.assertEqual(expected, dump_data) def testLoad(self): - s = StringIO.StringIO(self.incremental_uploader_dump) + s = six.StringIO(self.incremental_uploader_dump) - with mock.patch('urllib2.urlopen') as mock_open: + with mock.patch('%s.urlopen' % URL_REQUEST_PATH) as mock_open: mock_open.return_value.headers = { 'location': self.initialized_url } @@ -1458,7 +1461,7 @@ def testUploadOperations(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: self.incremental_uploader.UploadOperations([[]], True) mock_open.assert_called_with(mock_request) @@ -1467,7 +1470,7 @@ def testUploadOperationsWithError(self): error_code = '404' error_message = 'I AM ERROR' error_headers = {} - http_error = urllib2.HTTPError( + http_error = six.moves.urllib.error.HTTPError( error_url, error_code, error_message, error_headers, None) with mock.patch('googleads.adwords.BatchJobHelper.' @@ -1475,11 +1478,11 @@ def testUploadOperationsWithError(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: mock_open.side_effect = http_error self.assertRaises( - urllib2.HTTPError, self.incremental_uploader.UploadOperations, - [[]], True) + six.moves.urllib.error.HTTPError, + self.incremental_uploader.UploadOperations, [[]], True) mock_open.assert_called_with(mock_request) def testUploadOperationsAfterFinished(self): @@ -1488,7 +1491,7 @@ def testUploadOperationsAfterFinished(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('urllib2.OpenerDirector.open'): + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH): self.incremental_uploader.UploadOperations([[]], True) self.assertRaises( googleads.errors.AdWordsBatchJobServiceInvalidOperationError, @@ -1602,18 +1605,18 @@ def setUp(self): self.adwords_client, self.version) def testDownloadReport(self): - output_file = io.StringIO() + output_file = six.StringIO() report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} serialized_report = 'nuinbwuign' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' - report_contents = io.StringIO() if PYTHON2 else io.BytesIO() - report_contents.write(report_data if PYTHON2 + report_contents = six.StringIO() if six.PY2 else io.BytesIO() + report_contents.write(report_data if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1643,18 +1646,18 @@ def testDownloadReport(self): skip_report_header=True, use_raw_enum_values=False) def testDownloadReportWithAllLoggingEnabled(self): - output_file = io.StringIO() + output_file = six.StringIO() report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} serialized_report = 'nuinbwuign' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' - report_contents = io.StringIO() if PYTHON2 else io.BytesIO() - report_contents.write(report_data if PYTHON2 + report_contents = six.StringIO() if six.PY2 else io.BytesIO() + report_contents.write(report_data if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1691,14 +1694,14 @@ def testDownloadReportAsString(self): report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} serialized_report = 'nuinbwuign' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING アングリーバード' report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if PYTHON2 + report_contents.write(report_data.encode('utf-8') if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1728,14 +1731,15 @@ def testDownloadReportAsString(self): def testDownloadReportAsStringWithAwql(self): query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' file_format = 'CSV' - post_body = urllib.urlencode({'__fmt': file_format, '__rdquery': query}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__fmt': file_format, + '__rdquery': query}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING アングリーバード' report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if PYTHON2 + report_contents.write(report_data.encode('utf-8') if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1761,7 +1765,7 @@ def testDownloadReportAsStringWithAwql(self): include_zero_impressions=True, use_raw_enum_values=False) def testDownloadReportCheckFormat_CSVStringSuccess(self): - output_file = io.StringIO() + output_file = six.StringIO() try: self.report_downloader._DownloadReportCheckFormat('CSV', output_file) @@ -1770,7 +1774,7 @@ def testDownloadReportCheckFormat_CSVStringSuccess(self): 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDBinaryFileSuccess(self): - output_file = io.StringIO() + output_file = six.StringIO() try: self.report_downloader._DownloadReportCheckFormat('CSV', output_file) @@ -1789,14 +1793,14 @@ def testDownloadReportCheckFormat_GZIPPEDBytesIOSuccess(self): 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDStringFailure(self): - output_file = io.StringIO() + output_file = six.StringIO() self.assertRaises(googleads.errors.GoogleAdsValueError, self.report_downloader._DownloadReportCheckFormat, 'GZIPPED_CSV', output_file) def testDownloadReportCheckFormat_Issue152(self): - output_file = io.StringIO() + output_file = six.StringIO() output_file.mode = 'w+b' # Verify writing and reading works. try: @@ -1816,18 +1820,18 @@ def testDownloadReportCheckFormat_Issue152(self): 'unexpectedly!') def testDownloadReport_failure(self): - output_file = io.StringIO() + output_file = six.StringIO() report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} serialized_report = 'hjuibnibguo' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'Page not found. :-(' - report_contents = io.StringIO() if PYTHON2 else io.BytesIO() - report_contents.write(report_data if PYTHON2 else bytes(report_data, + report_contents = six.StringIO() if six.PY2 else io.BytesIO() + report_contents.write(report_data if six.PY2 else bytes(report_data, 'utf-8')) logger_request_summary_template = 'Request Summary: %s' report_contents.seek(0) @@ -1835,7 +1839,8 @@ def testDownloadReport_failure(self): fake_response.read = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - error = urllib2.HTTPError('', 400, 'Bad Request', {}, fp=fake_response) + error = six.moves.urllib.error.HTTPError('', 400, 'Bad Request', {}, + fp=fake_response) self.marshaller.process.return_value = serialized_report @@ -1875,21 +1880,22 @@ def testDownloadReport_failure(self): h_handler.GetReportDownloadHeaders.assert_called_once_with() def testDownloadReportWithAwql(self): - output_file = io.StringIO() + output_file = six.StringIO() query = (googleads.adwords.ReportQueryBuilder() .Select('CampaignId').From('CAMPAIGN_PERFORMANCE_REPORT') .Where('CampaignStatus').EqualTo('ENABLED') .Build()) file_format = 'CSV' - post_body = urllib.urlencode({'__fmt': file_format, '__rdquery': query}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__fmt': file_format, + '__rdquery': query}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' - report_contents = io.StringIO() if PYTHON2 else io.BytesIO() - report_contents.write(report_data if PYTHON2 else bytes(report_data, - 'utf-8')) + report_contents = six.StringIO() if six.PY2 else io.BytesIO() + report_contents.write(report_data if six.PY2 + else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() fake_response.read = report_contents.read @@ -1918,14 +1924,14 @@ def testDownloadReportWithBytesIO(self): report_definition = {'table': 'campaigns', 'downloadFormat': 'GZIPPED_CSV'} serialized_report = 'nuinbwuign' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if PYTHON2 + report_contents.write(report_data.encode('utf-8') if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1962,7 +1968,7 @@ def testExtractError_badRequest(self): '%s%s' '%s') content = content_template % (type_, trigger, field_path) - response.read.return_value = (content if PYTHON2 + response.read.return_value = (content if six.PY2 else bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) @@ -1976,7 +1982,7 @@ def testExtractError_badRequest(self): # Check that if the XML fields are empty, this still functions. content = content_template % ('', '', '') - response.read.return_value = (content if PYTHON2 + response.read.return_value = (content if six.PY2 else bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) self.assertEqual(None, rval.type) @@ -1989,7 +1995,7 @@ def testExtractError_malformedBadRequest(self): content = ('' '12345678' '') - response.read.return_value = (content if PYTHON2 + response.read.return_value = (content if six.PY2 else bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) @@ -2002,7 +2008,7 @@ def testExtractError_notBadRequest(self): response = mock.Mock() response.code = 400 content = 'Page not found!' - response.read.return_value = (content if PYTHON2 + response.read.return_value = (content if six.PY2 else bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) @@ -2265,9 +2271,9 @@ def testCopyConstructor(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause can show fields listed in any orders. - self.assertItemsEqual(selected_fields, - [field.strip() for field - in match.group(1).split(',')]) + six.assertCountEqual( + self, selected_fields, + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testFailUsingCopyConstructor(self): @@ -2286,9 +2292,9 @@ def testBuild(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause can show fields listed in any orders. - self.assertItemsEqual(selected_fields, - [field.strip() for field - in match.group(1).split(',')]) + six.assertCountEqual( + self, selected_fields, + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testBuild_duplicateSelectedFieldsRetainOnlyUnique(self): @@ -2301,9 +2307,9 @@ def testBuild_duplicateSelectedFieldsRetainOnlyUnique(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause retains only unique fields. - self.assertItemsEqual(set(selected_fields), - [field.strip() for field - in match.group(1).split(',')]) + six.assertCountEqual( + self, set(selected_fields), + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testBuild_whereConditions(self): @@ -2323,9 +2329,9 @@ def testBuild_whereConditions(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause can show fields listed in any orders. - self.assertItemsEqual(selected_fields, - [field.strip() for field - in match.group(1).split(',')]) + six.assertCountEqual( + self, selected_fields, + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testBuild_orderByDesc(self): @@ -2341,9 +2347,9 @@ def testBuild_orderByDesc(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause can show fields listed in any orders. - self.assertItemsEqual(selected_fields, - [field.strip() for field - in match.group(1).split(',')]) + six.assertCountEqual( + self, selected_fields, + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testBuild_selectIsNone(self): diff --git a/tests/common_test.py b/tests/common_test.py index 282bfb03..ade2282d 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -15,26 +15,26 @@ """Unit tests to cover the common module.""" -import io import numbers import os import ssl import unittest -from urllib import addinfourl -import urllib2 import warnings - from pyfakefs import fake_filesystem from pyfakefs import fake_tempfile import mock +import six import suds import yaml import googleads.common import googleads.errors import googleads.oauth2 -import testing +from . import testing + + +URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' class CommonTest(testing.CleanUtilityRegistryTestCase): @@ -1068,7 +1068,7 @@ def testProxyToStringWithOnlyUsername(self): def testProxyConfigGetHandlersWithNoProxyOrSSLContext(self): proxy_config = googleads.common.ProxyConfig() - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance self.assertIn(https_handler_instance, proxy_config.GetHandlers()) @@ -1076,11 +1076,11 @@ def testProxyConfigGetHandlersWithNoProxyOrSSLContext(self): def testProxyConfigGetHandlersWithProxy(self): http_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, self.proxy_port1) - with mock.patch('urllib2.ProxyHandler') as proxy_handler: + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: proxy_handler_instance = mock.Mock() proxy_handler.return_value = proxy_handler_instance proxy_config = googleads.common.ProxyConfig(http_proxy=http_proxy) - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance self.assertEqual(proxy_config.GetHandlers(), @@ -1093,9 +1093,9 @@ def testProxyConfigGetHandlersWithProxyAndSLLContext(self): self.proxy_port1) with mock.patch('googleads.common.ProxyConfig._InitSSLContext') as ssl_ctxt: ssl_ctxt.return_value = 'CONTEXT' - with mock.patch('urllib2.ProxyHandler') as proxy_handler: + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: proxy_handler.return_value = mock.Mock() - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler.return_value = mock.Mock() proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) self.assertEqual(proxy_config.GetHandlers(), @@ -1110,7 +1110,7 @@ def testProxyConfigWithNoProxy(self): proxy_config = googleads.common.ProxyConfig() self.assertEqual(proxy_config.proxy_info, None) - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance self.assertEqual(proxy_config.GetHandlers(), @@ -1120,7 +1120,7 @@ def testProxyConfigWithNoProxy(self): with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance transport = proxy_config.GetSudsProxyTransport() @@ -1144,10 +1144,10 @@ def testProxyConfigWithHTTPProxy(self): with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - with mock.patch('urllib2.ProxyHandler') as proxy_handler: + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: proxy_handler_instance = mock.Mock() proxy_handler.return_value = proxy_handler_instance - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance self.assertEqual(proxy_config.GetHandlers(), @@ -1178,10 +1178,10 @@ def testProxyConfigWithHTTPSProxy(self): with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - with mock.patch('urllib2.ProxyHandler') as proxy_handler: + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: proxy_handler_instance = mock.Mock() proxy_handler.return_value = proxy_handler_instance - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance self.assertEqual( @@ -1215,11 +1215,11 @@ def testProxyConfigWithHTTPAndHTTPSProxy(self): with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - with mock.patch('urllib2.ProxyHandler') as proxy_handler: + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: proxy_handler_instance = mock.Mock() proxy_handler.return_value = proxy_handler_instance - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance self.assertEqual( @@ -1238,16 +1238,24 @@ class MockHeaders(object): def __init__(self, d): self.dict = d + # If testing on Python 3, add get method to better mimic the + # http.client.HTTPMessage behavior. + if six.PY3: + def py3_get(s): + return self.dict.get(s) + self.get = py3_get + def testInflateSuccessfulRequestIfGzipped(self): with mock.patch('suds.transport.http.HttpTransport.getcookies'): - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: with mock.patch('gzip.GzipFile.read') as mock_read: - resp_fp = io.BytesIO() - resp_fp.write('abc') + resp_fp = six.BytesIO() + resp_fp.write(b'abc') resp_fp.flush() resp_fp.seek(0) - resp = addinfourl(resp_fp, self.MockHeaders( - {'content-encoding': 'gzip'}), 'https://example.com', code=200) + resp = six.moves.urllib.response.addinfourl( + resp_fp, self.MockHeaders({'content-encoding': 'gzip'}), + 'https://example.com', code=200) mock_open.return_value = resp req = suds.transport.Request('https://example.com', @@ -1258,26 +1266,22 @@ def testInflateSuccessfulRequestIfGzipped(self): def testInflateFailedRequestIfGzipped(self): with mock.patch('suds.transport.http.HttpTransport.getcookies'): - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: with mock.patch('gzip.GzipFile') as mock_gzip: gzip_instance_mock = mock.MagicMock mock_gzip.return_value = gzip_instance_mock - resp_fp = io.BytesIO() - resp_fp.write('abc') + resp_fp = six.BytesIO() + resp_fp.write(b'abc') resp_fp.flush() resp_fp.seek(0) - resp = addinfourl(resp_fp, - self.MockHeaders({'content-encoding': 'gzip'}), - 'https://example.com', code=200) + resp = six.moves.urllib.response.addinfourl( + resp_fp, self.MockHeaders({'content-encoding': 'gzip'}), + 'https://example.com', code=200) def fail_to_open(*args, **kwargs): - raise urllib2.HTTPError( - 'https://example.com', - 500, - 'oops!', - {'content-encoding': 'gzip'}, - resp - ) + raise six.moves.urllib.error.HTTPError( + 'https://example.com', 500, 'oops!', + {'content-encoding': 'gzip'}, resp) mock_open.side_effect = fail_to_open req = suds.transport.Request('https://example.com', diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 58de1607..9c138a6b 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -16,19 +16,17 @@ import datetime -import StringIO import sys import unittest - import mock import pytz +import six import suds.transport - import googleads.dfp import googleads.common import googleads.errors -import testing +from . import testing class BaseValue(object): @@ -571,7 +569,7 @@ def setUp(self): }] def testDownloadPqlResultSetToCsv(self): - csv_file = StringIO.StringIO() + csv_file = six.StringIO() self.pql_service.select.return_value = {'rows': self.generic_rval, 'columnTypes': self.generic_header} @@ -703,14 +701,14 @@ def testDownloadReportToFile(self): report_job_id = 't68t3278y429' report_download_url = 'http://google.com/something' report_data = 'THIS IS YOUR REPORT!' - report_contents = StringIO.StringIO() + report_contents = six.StringIO() report_contents.write(report_data) report_contents.seek(0) fake_response = mock.Mock() fake_response.read = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - outfile = StringIO.StringIO() + outfile = six.StringIO() download_func = self.report_service.getReportDownloadUrlWithOptions download_func.return_value = report_download_url diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index 0c16b6cd..939e96d2 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -18,25 +18,26 @@ import datetime import unittest - import httplib2 import mock - +import six import googleads.common import googleads.errors import googleads.oauth2 - from pyfakefs import fake_filesystem from pyfakefs import fake_tempfile from oauth2client.client import AccessTokenRefreshError from oauth2client.client import OAuth2Credentials + if googleads.oauth2.DEPRECATED_OAUTH2CLIENT: _SA_CRED_PATH = ('oauth2client.client' '.SignedJwtAssertionCredentials') else: _SA_CRED_PATH = 'oauth2client.service_account.ServiceAccountCredentials' +_BUILTIN_PATH = '__builtin__' if six.PY2 else 'builtins' + class GetAPIScopeTest(unittest.TestCase): """Tests for the googleads.oauth2.GetAPIScope function.""" @@ -185,7 +186,7 @@ class GoogleServiceAccountTest(unittest.TestCase): def setUp(self): self.scope = 'scope' self.service_account_email = 'email@email.com' - self.private_key = 'IT\'S A SECRET TO EVERYBODY.' + self.private_key = b'IT\'S A SECRET TO EVERYBODY.' self.private_key_password = 'notasecret' self.delegated_account = 'delegated_account@delegated.com' https_proxy_host = 'myproxy.com' @@ -203,7 +204,7 @@ def setUp(self): self.fake_open = fake_filesystem.FakeFileOpen(filesystem) self.key_file_path = tempfile.NamedTemporaryFile(delete=False).name - with self.fake_open(self.key_file_path, 'w') as file_handle: + with self.fake_open(self.key_file_path, 'wb') as file_handle: file_handle.write(self.private_key) # Mock out httplib2.Http for testing. @@ -240,7 +241,7 @@ def refresh(mock_http): self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply) self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh) - with mock.patch('__builtin__.open', self.fake_open): + with mock.patch('%s.open' % _BUILTIN_PATH, self.fake_open): with mock.patch(_SA_CRED_PATH, self.oauth2_credentials): self.googleads_client = googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, self.key_file_path, @@ -437,7 +438,7 @@ def testIssue123(self): See: https://github.com/googleads/googleads-python-lib/issues/123 """ - with mock.patch('__builtin__.open'): + with mock.patch('%s.open' % _BUILTIN_PATH): with mock.patch(_SA_CRED_PATH, self.oauth2_credentials): googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, '/dev/null', diff --git a/tests/util_test.py b/tests/util_test.py index 0df66036..c11e8d1b 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -18,18 +18,20 @@ import os import re import unittest -import urllib2 from xml.etree import ElementTree - import googleads.adwords import googleads.dfp import googleads.util import mock +import six import suds import suds.transport +_HTTP_CLIENT_PATH = 'httplib' if six.PY2 else 'http.client' + + class PatchesTest(unittest.TestCase): """Tests for the PatchHelper utility.""" @@ -84,6 +86,8 @@ def testPatchedSudsJurkoAppender(self): request = line_item_service.performLineItemAction( line_item_action, statement.ToStatement()).envelope line_item_service.suds_client.set_options(nosend=False) + if six.PY3: + request = request.decode('utf-8') # Strip namespace prefixes and parse. parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) line_item_action = parsed_request.find('Body').find('performLineItemAction') @@ -117,6 +121,8 @@ def testPatchedSudsJurkoAppenderIssue63(self): adgroup_criterion_service.suds_client.set_options(nosend=True) request = adgroup_criterion_service.mutate(operations).envelope adgroup_criterion_service.suds_client.set_options(nosend=False) + if six.PY3: + request = request.decode('utf-8') # Strip namespace prefixes and parse. parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) operand = parsed_request.find('Body').find('mutate').find( @@ -136,6 +142,8 @@ def testPatchedSudsJurkoAppenderIssue78(self): customer_service.suds_client.set_options(nosend=True) request = customer_service.mutate(customer).envelope customer_service.suds_client.set_options(nosend=False) + if six.PY3: + request = request.decode('utf-8') # Strip namespace prefixes and parse. parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) tracking_url_template = parsed_request.find('Body').find('mutate').find( @@ -168,7 +176,7 @@ def testSudsJurkoSendWithException(self): cs = self.adwords_client_with_compression.GetService('CampaignService') with mock.patch('suds.transport.http.HttpTransport.u2open') as mock_u2open: - with mock.patch('httplib.HTTPMessage') as mock_headers: + with mock.patch('%s.HTTPMessage' % _HTTP_CLIENT_PATH) as mock_headers: mock_headers.get.return_value = None with open(os.path.join( test_dir, 'test_data/compact_fault_response_envelope.txt'), 'rb' @@ -177,11 +185,11 @@ def testSudsJurkoSendWithException(self): code = 500 msg = '' hdrs = mock_headers - mock_u2open.side_effect = urllib2.HTTPError(url, code, msg, hdrs, - handler) + mock_u2open.side_effect = six.moves.urllib.error.HTTPError( + url, code, msg, hdrs, handler) try: cs.get() - except suds.WebFault, e: + except suds.WebFault as e: self.assertEqual( 'Unmarshalling Error: For input string: ' '"INSERT_ADVERTISER_COMPANY_ID_HERE" ', @@ -209,7 +217,7 @@ def testSingleErrorListIssue90(self): mock_send.return_value = reply_instance try: line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault, e: + except suds.WebFault as e: errors = e.fault.detail.ApiExceptionFault.errors self.assertIsInstance(errors, list) self.assertEqual(1, len(errors)) @@ -236,7 +244,7 @@ def testSingleErrorListIssue90_emptyErrors(self): mock_send.return_value = reply_instance try: line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault, e: + except suds.WebFault as e: errors = e.fault.detail.ApiExceptionFault.errors self.assertIsInstance(errors, list) self.assertEqual(0, len(errors)) @@ -263,7 +271,7 @@ def testSingleErrorListIssue90_multipleErrors(self): mock_send.return_value = reply_instance try: line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault, e: + except suds.WebFault as e: errors = e.fault.detail.ApiExceptionFault.errors self.assertIsInstance(errors, list) self.assertEqual(2, len(errors)) From 3cc75af7e46f0a6afc2dedb8068305e02d5251e5 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 13 Feb 2018 16:08:51 -0500 Subject: [PATCH 100/180] Commiting latest changes. From b9bb0e9206dae0d370775a8e60dccc008cccb999 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 1 Mar 2018 16:52:47 -0500 Subject: [PATCH 101/180] AdWords v201802 release --- ChangeLog | 5 + examples/adwords/v201802/__init__.py | 15 + .../v201802/account_management/__init__.py | 15 + .../account_management/accept_service_link.py | 62 +++ .../account_management/create_account.py | 69 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201802/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 226 ++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 128 +++++ .../add_dynamic_page_feed.py | 295 ++++++++++ .../add_dynamic_search_ads_campaign.py | 257 +++++++++ ...add_expanded_text_ad_with_upgraded_urls.py | 113 ++++ .../advanced_operations/add_gmail_ad.py | 117 ++++ .../advanced_operations/add_html5_ad.py | 112 ++++ .../add_responsive_display_ad.py | 159 ++++++ ...d_shopping_dynamic_remarketing_campaign.py | 305 ++++++++++ .../add_universal_app_campaign.py | 218 ++++++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201802/basic_operations/__init__.py | 15 + .../v201802/basic_operations/add_ad_groups.py | 115 ++++ .../v201802/basic_operations/add_campaigns.py | 127 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201802/basic_operations/add_keywords.py | 92 +++ .../v201802/basic_operations/get_ad_groups.py | 76 +++ .../v201802/basic_operations/get_campaigns.py | 72 +++ .../get_campaigns_with_awql.py | 61 ++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201802/basic_operations/get_keywords.py | 87 +++ .../v201802/basic_operations/pause_ad.py | 61 ++ .../v201802/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 85 +++ .../basic_operations/update_campaign.py | 58 ++ .../basic_operations/update_keyword.py | 82 +++ .../v201802/campaign_management/__init__.py | 15 + ...campaign_groups_and_performance_targets.py | 152 +++++ .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 428 ++++++++++++++ .../v201802/campaign_management/add_draft.py | 81 +++ ...dd_keywords_using_incremental_batch_job.py | 257 +++++++++ .../v201802/campaign_management/add_trial.py | 116 ++++ .../get_all_disapproved_ads.py | 103 ++++ .../get_all_disapproved_ads_with_awql.py | 88 +++ .../get_campaigns_by_label.py | 83 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201802/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 131 +++++ .../handle_policy_violation_error.py | 167 ++++++ .../adwords/v201802/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 159 ++++++ .../adwords/v201802/extensions/add_prices.py | 157 ++++++ .../v201802/extensions/add_site_links.py | 146 +++++ .../extensions/add_site_links_using_feeds.py | 236 ++++++++ .../adwords/v201802/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 526 ++++++++++++++++++ examples/adwords/v201802/misc/__init__.py | 15 + .../v201802/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201802/misc/upload_image.py | 66 +++ .../v201802/misc/upload_media_bundle.py | 60 ++ .../adwords/v201802/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 180 ++++++ ...aign_criterion_bid_modifier_simulations.py | 97 ++++ .../get_keyword_bid_simulations.py | 104 ++++ .../v201802/optimization/get_keyword_ideas.py | 113 ++++ .../adwords/v201802/remarketing/__init__.py | 15 + .../v201802/remarketing/add_audience.py | 104 ++++ .../remarketing/add_conversion_tracker.py | 70 +++ .../remarketing/add_conversion_trackers.py | 101 ++++ .../remarketing/add_crm_based_user_list.py | 104 ++++ .../remarketing/add_rule_based_user_lists.py | 235 ++++++++ .../upload_offline_call_conversions.py | 77 +++ .../remarketing/upload_offline_conversions.py | 82 +++ .../remarketing/upload_offline_data.py | 259 +++++++++ .../adwords/v201802/reporting/__init__.py | 15 + ...oad_criteria_report_as_stream_with_awql.py | 84 +++ ...criteria_report_as_stream_with_selector.py | 77 +++ ...oad_criteria_report_as_string_with_awql.py | 58 ++ ...criteria_report_as_string_with_selector.py | 59 ++ .../download_criteria_report_with_awql.py | 58 ++ .../download_criteria_report_with_selector.py | 60 ++ .../v201802/reporting/get_report_fields.py | 52 ++ .../reporting/parallel_report_download.py | 230 ++++++++ examples/adwords/v201802/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 279 ++++++++++ .../v201802/shopping/add_product_scope.py | 104 ++++ .../v201802/shopping/add_shopping_campaign.py | 172 ++++++ .../add_shopping_campaign_for_showcase_ads.py | 402 +++++++++++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201802/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 126 +++++ .../add_customer_negative_criteria.py | 74 +++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201802/targeting/lookup_location.py | 82 +++ .../set_line_item_custom_field_value.py | 43 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 21 +- ...et_all_custom_targeting_keys_and_values.py | 8 +- .../get_all_ad_unit_sizes.py | 2 +- .../approve_all_suggested_ad_units.py | 14 +- googleads/adwords.py | 54 ++ googleads/common.py | 14 +- tests/common_test.py | 26 + 114 files changed, 11756 insertions(+), 63 deletions(-) create mode 100644 examples/adwords/v201802/__init__.py create mode 100644 examples/adwords/v201802/account_management/__init__.py create mode 100755 examples/adwords/v201802/account_management/accept_service_link.py create mode 100755 examples/adwords/v201802/account_management/create_account.py create mode 100755 examples/adwords/v201802/account_management/get_account_changes.py create mode 100755 examples/adwords/v201802/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201802/advanced_operations/__init__.py create mode 100755 examples/adwords/v201802/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py create mode 100755 examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py create mode 100755 examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201802/advanced_operations/add_gmail_ad.py create mode 100755 examples/adwords/v201802/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py create mode 100755 examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py create mode 100755 examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201802/basic_operations/__init__.py create mode 100755 examples/adwords/v201802/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201802/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201802/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201802/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201802/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201802/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201802/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201802/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201802/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201802/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201802/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201802/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201802/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201802/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201802/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201802/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201802/campaign_management/__init__.py create mode 100755 examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py create mode 100755 examples/adwords/v201802/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201802/campaign_management/add_draft.py create mode 100755 examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201802/campaign_management/add_trial.py create mode 100755 examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201802/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201802/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201802/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201802/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201802/error_handling/__init__.py create mode 100755 examples/adwords/v201802/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201802/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201802/extensions/__init__.py create mode 100755 examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201802/extensions/add_prices.py create mode 100755 examples/adwords/v201802/extensions/add_site_links.py create mode 100755 examples/adwords/v201802/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201802/migration/__init__.py create mode 100755 examples/adwords/v201802/migration/migrate_to_extension_settings.py create mode 100644 examples/adwords/v201802/misc/__init__.py create mode 100755 examples/adwords/v201802/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201802/misc/upload_image.py create mode 100755 examples/adwords/v201802/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201802/optimization/__init__.py create mode 100755 examples/adwords/v201802/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201802/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201802/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201802/remarketing/__init__.py create mode 100755 examples/adwords/v201802/remarketing/add_audience.py create mode 100755 examples/adwords/v201802/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201802/remarketing/add_conversion_trackers.py create mode 100755 examples/adwords/v201802/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201802/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201802/remarketing/upload_offline_call_conversions.py create mode 100755 examples/adwords/v201802/remarketing/upload_offline_conversions.py create mode 100755 examples/adwords/v201802/remarketing/upload_offline_data.py create mode 100644 examples/adwords/v201802/reporting/__init__.py create mode 100755 examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py create mode 100755 examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py create mode 100755 examples/adwords/v201802/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201802/reporting/download_criteria_report_with_selector.py create mode 100755 examples/adwords/v201802/reporting/get_report_fields.py create mode 100755 examples/adwords/v201802/reporting/parallel_report_download.py create mode 100644 examples/adwords/v201802/shopping/__init__.py create mode 100755 examples/adwords/v201802/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201802/shopping/add_product_scope.py create mode 100755 examples/adwords/v201802/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py create mode 100755 examples/adwords/v201802/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201802/targeting/__init__.py create mode 100755 examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201802/targeting/add_customer_negative_criteria.py create mode 100755 examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201802/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 0bac30da..96c46836 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +10.1.0 -- 03/01/18 +* Added support and examples for AdWords v201802. +* Added new BuildOpener utility method to ProxyConfig, which returns an + OpenerDirector instance configured for the ProxyConfig settings. + 10.0.0 -- 02/13/18 * Added support and examples for DFP v201802. * Removed support and examples for AdWords v201702. diff --git a/examples/adwords/v201802/__init__.py b/examples/adwords/v201802/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201802/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201802/account_management/__init__.py b/examples/adwords/v201802/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201802/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201802/account_management/accept_service_link.py b/examples/adwords/v201802/account_management/accept_service_link.py new file mode 100755 index 00000000..b01f7180 --- /dev/null +++ b/examples/adwords/v201802/account_management/accept_service_link.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' + + +def main(client, service_link_id): + # Initialize appropriate service. + customer_service = client.GetService( + 'CustomerService', version='v201802') + + # Create the operation to set the status to ACTIVE. + operations = [{ + 'operator': 'SET', + 'operand': { + 'serviceLinkId': service_link_id, + 'serviceType': 'MERCHANT_CENTER', + 'linkStatus': 'ACTIVE', + } + }] + + # Update the service link. + mutated_service_links = customer_service.mutateServiceLinks(operations) + + # Display results. + for mutated_service_link in mutated_service_links: + print ('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201802/account_management/create_account.py b/examples/adwords/v201802/account_management/create_account.py new file mode 100755 index 00000000..c345e9da --- /dev/null +++ b/examples/adwords/v201802/account_management/create_account.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201802') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + }, + # For whitelisted users only, uncomment the inviteeEmail and inviteeRole + # attributes to invite a user to have access to an account on an ADD. An + # email will be sent inviting the user to have access to the newly created + # account. + # 'inviteeEmail': 'invited_user1@example.com', + # 'inviteeRole': 'ADMINISTRATIVE' + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID "%s" was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/account_management/get_account_changes.py b/examples/adwords/v201802/account_management/get_account_changes.py new file mode 100755 index 00000000..659a4606 --- /dev/null +++ b/examples/adwords/v201802/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201802') + campaign_service = client.GetService('CampaignService', version='v201802') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id "%s" has change status "%s".' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id "%s" has change status "%s".' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/account_management/get_account_hierarchy.py b/examples/adwords/v201802/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..4cffedc7 --- /dev/null +++ b/examples/adwords/v201802/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201802') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/__init__.py b/examples/adwords/v201802/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201802/advanced_operations/add_ad_customizer.py b/examples/adwords/v201802/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..adff3d83 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_ad_customizer.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates ExpandedTextAds that use ad customizations for specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no ExpandedTextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201802') + + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'headlinePart2': 'Only {=%s.Price}' % feed_name, + 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': expanded_text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID "%s", type "%s", and status "%s".' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201802') + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name "%s" and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService', 'v201802') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + adgroup_ids[1], ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + +def CreateFeedItemAddOperation(name, price, date, adgroup_id, + ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values and AdGroupTargeting when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + adgroup_id: the ID of the ad_group to target with the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'adGroupTargeting': { + 'TargetingAdGroupId': adgroup_id + }, + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + operation = { + 'operator': 'ADD', + 'operand': feed_item + } + + return operation + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..e09b1d5a --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201802') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..ee473887 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Optionally, you may specify a landscape image. The image needs to be in a + # BASE64 encoded form. Here we download a demo image and encode it for this + # ad. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + }, + { + 'name': 'landscapeImage', + 'fieldMedia': { + 'xsi_type': 'Image', + 'data': image_data + }, + 'type': 'IMAGE' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py new file mode 100755 index 00000000..2bbaf050 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. + +To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +from collections import namedtuple +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + +# Used to keep track of DSA page feed details. +_DSAFeedDetails = namedtuple( + '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) +# ID that corresponds to the labels. +DSA_LABEL_FIELD_ID = 2 +# The criterion type to be used for DSA page feeds. +DSA_PAGE_FEED_CRITERION_TYPE = 61 +DSA_PAGE_URL_LABEL = 'discounts' +# ID that corresponds to the page URLs. +DSA_PAGE_URLS_FIELD_ID = 1 + + +def main(client, campaign_id, ad_group_id): + # Get the page feed details. This code example creates a new feed, but you can + # fetch and re-use an existing feed. + feed_details = _CreateFeed(client) + _CreateFeedMapping(client, feed_details) + _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) + + # Associate the page feed with the campaign. + _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) + + # Optional: Target web pages matching the feed's label in the ad group. + _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) + + print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + + +def _CreateFeed(client): + """Creates the feed for DSA page URLs. + + Args: + client: an AdWordsClient instance. + + Returns: + A _DSAFeedDetails instance containing details about the created feed. + """ + # Get the FeedService. + feed_service = client.GetService('FeedService', version='v201802') + + # Create operation. + operation = { + # Create the feed. + 'operand': { + 'name': 'DSA Feed %s' % uuid.uuid4(), + # Create attributes. + 'attributes': [ + {'type': 'URL_LIST', 'name': 'Page URL'}, + {'type': 'STRING_LIST', 'name': 'Label'} + ], + 'origin': 'USER' + }, + 'operator': 'ADD' + } + + # Add the feed. + feed = feed_service.mutate([operation])['value'][0] + return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], + feed['attributes'][1]['id']) + + +def _CreateFeedMapping(client, feed_details): + """Creates the feed mapping for DSA page feeds. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + """ + # Get the FeedMappingService. + feed_mapping_service = client.GetService('FeedMappingService', + version='v201802') + + # Create the operation. + operation = { + # Create the feed mapping. + 'operand': { + 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, + 'feedId': feed_details.feed_id, + # Map the feedAttributeIds to the fieldId constants. + 'attributeFieldMappings': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'fieldId': DSA_PAGE_URLS_FIELD_ID + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'fieldId': DSA_LABEL_FIELD_ID + } + ] + }, + 'operator': 'ADD' + } + + # Add the feed mapping. + feed_mapping_service.mutate([operation]) + + +def _CreateFeedItems(client, feed_details, label_name): + """Creates the page URLs in the DSA page feed. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + label_name: a str containing the page feed URL label. + """ + # Get the FeedItemService. + feed_item_service = client.GetService('FeedItemService', version='v201802') + + # Optional: You can include the {feeditem} valuetrack parameter to track which + # page feed items lead to each click. + urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', + 'http://www.example.com/discounts/hotel-deals?id={feeditem}', + 'http://www.example.com/discounts/flight-deals?id={feeditem}') + + # Create the operation. + operations = [{ + # Create the feed item. + 'operand': { + 'feedId': feed_details.feed_id, + 'attributeValues': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'stringValues': [url] + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'stringValues': [label_name] + } + ] + }, + 'operator': 'ADD' + } for url in urls] + + # Add the feed item. + feed_item_service.mutate(operations) + + +def _UpdateCampaignDSASetting(client, campaign_id, feed_id): + """Updates the campaign DSA setting to DSA pagefeeds. + + Args: + client: an AdWordsClient instance. + campaign_id: a str Campaign ID. + feed_id: a str page Feed ID. + + Raises: + ValueError: If the given campaign is found not to be a dynamic search ad + campaign. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201802') + + selector = { + 'fields': ['Id', 'Settings'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [campaign_id] + }] + } + + response = campaign_service.get(selector) + + if response['totalNumEntries']: + campaign = response['entries'][0] + else: + raise ValueError('No campaign with ID "%d" exists.' % campaign_id) + + if not campaign['settings']: + raise ValueError('This is not a DSA campaign.') + + dsa_setting = None + + campaign_settings = campaign['settings'] + + for setting in campaign_settings: + if setting['Setting.Type'] == 'DynamicSearchAdsSetting': + dsa_setting = setting + break + + if dsa_setting is None: + raise ValueError('This is not a DSA campaign.') + + dsa_setting['pageFeed'] = { + 'feedIds': [feed_id] + } + + # Optional: Specify whether only the supplied URLs should be used with your + # Dynamic Search Ads. + dsa_setting['useSuppliedUrlsOnly'] = True + + operation = { + 'operand': { + 'id': campaign_id, + 'settings': campaign_settings + }, + 'operator': 'SET' + } + + campaign_service.mutate([operation]) + print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id) + + +def _AddDSATargeting(client, ad_group_id, label_name): + """Set custom targeting for the page feed URLs based on a list of labels. + + Args: + client: an AdWordsClient instance. + ad_group_id: a str AdGroup ID. + label_name: a str label name. + + Returns: + A suds.sudsobject.Object representing the newly created webpage criterion. + """ + # Get the AdGroupCriterionService. + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201802') + + # Create the operation. + operation = { + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Test criterion', + # Add a condition for label=specified_label_name. + 'conditions': [{ + 'operand': 'CUSTOM_LABEL', + 'argument': label_name + }], + } + }, + # Set a custom bid for this criterion + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 1500000 + } + }] + } + }, + 'operator': 'ADD' + } + + criterion = ad_group_criterion_service.mutate([operation])['value'][0] + print 'Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus']) + return criterion + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py new file mode 100755 index 00000000..439c7ba7 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Dynamic Search Ads campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + budget = _CreateBudget(client) + campaign_id = _CreateCampaign(client, budget) + ad_group_id = _CreateAdGroup(client, campaign_id) + _CreateExpandedDSA(client, ad_group_id) + _AddWebPageCriteria(client, ad_group_id) + + print 'Dynamic Search Ads campaign setup is complete.' + + +def _CreateBudget(client): + """Creates the budget. + + Args: + client: an AdWordsClient instance. + + Returns: + a suds.sudsobject.Object representation of the created budget. + """ + budget_service = client.GetService('BudgetService', version='v201802') + + # Create the campaign budget + operation = { + 'operand': { + 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), + 'deliveryMethod': 'STANDARD', + 'amount': { + 'microAmount': 500000 + } + }, + 'operator': 'ADD' + } + + budget = budget_service.mutate([operation])['value'][0] + + print 'Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name']) + + return budget + + +def _CreateCampaign(client, budget): + """Creates the campaign. + + Args: + client: an AdWordsClient instance. + budget: a suds.sudsobject.Object representation of a created budget. + + Returns: + An integer campaign ID. + """ + campaign_service = client.GetService('CampaignService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # prevent the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'budget': budget, + # Required: Set the campaign's Dynamic Search Ad settings. + 'settings': [{ + 'xsi_type': 'DynamicSearchAdsSetting', + # Required: Set the domain name and language. + 'domainName': 'example.com', + 'languageCode': 'en' + }], + # Optional: Set the start date. + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + # Optional: Set the end date. + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + }] + + campaign = campaign_service.mutate(operations)['value'][0] + campaign_id = campaign['id'] + + print 'Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name']) + + return campaign_id + + +def _CreateAdGroup(client, campaign_id): + """Creates an ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: an integer campaign ID. + + Returns: + An integer ad group ID. + """ + ad_group_service = client.GetService('AdGroupService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'adGroupType': 'SEARCH_DYNAMIC_ADS', + 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '3000000' + }, + }] + } + } + }] + + ad_group = ad_group_service.mutate(operations)['value'][0] + ad_group_id = ad_group['id'] + + print 'Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name']) + + return ad_group_id + + +def _CreateExpandedDSA(client, ad_group_id): + """Creates the expanded Dynamic Search Ad. + + Args: + client: an AdwordsClient instance. + ad_group_id: an integer ID of the ad group in which the DSA is added. + """ + # Get the AdGroupAdService. + ad_group_ad_service = client.GetService('AdGroupAdService') + + # Create the operation + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + # Create the expanded dynamic search ad. This ad will have its + # headline and final URL auto-generated at serving time according to + # domain name specific information provided by DynamicSearchAdsSetting + # at the campaign level. + 'ad': { + 'xsi_type': 'ExpandedDynamicSearchAd', + # Set the ad description. + 'description': 'Buy your tickets now!' + }, + # Optional: Set the status. + 'status': 'PAUSED', + } + }] + + # Create the ad. + ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] + + # Display the results. + print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' + 'added' % (ad['id'], ad['description'])) + + +def _AddWebPageCriteria(client, ad_group_id): + """Adds a web page criterion to target Dynamic Search Ads. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID of the ad group the criteria is being added to. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201802') + + operations = [{ + 'operator': 'ADD', + # Create biddable ad group criterion. + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion for special offers for children. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Special offers for children.', + 'conditions': [ + { + 'operand': 'URL', + 'argument': '/marscruise/children' + }, + { + 'operand': 'PAGE_TITLE', + 'argument': 'Special Offer' + } + ] + } + }, + 'userStatus': 'PAUSED', + # Optional: set a custom bid. + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000L + } + }] + } + } + }] + + criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..55bc2357 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Create the expanded text ad + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + expanded_text_ad['trackingUrlTemplate'] = ( + 'http://tracker.example.com/?season={_season}&promocode={_promocode}' + '&u={lpurl}' + ) + + expanded_text_ad['urlCustomParameters'] = { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': expanded_text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_gmail_ad.py b/examples/adwords/v201802/advanced_operations/add_gmail_ad.py new file mode 100755 index 00000000..adab3ab8 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_gmail_ad.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example adds a Gmail ad to a given ad group. + +The ad group's campaign needs to have an AdvertisingChannelType of DISPLAY and +AdvertisingChannelSubType of DISPLAY_GMAIL_AD. + +To get your ad groups, run get_ad_groups.py. +""" + + +import base64 + +# Import appropriate classes from the client library. +from googleads import adwords + + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + media_service = client.GetService('MediaService', 'v201802') + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') + opener = client.proxy_config.BuildOpener() + + try: + # This ad format doesn't allow the creation of an image using the Image.data + # field. An image must first be created using the MediaService, and an + # Image.mediaId must be populated when creating the ad. + uploaded_logo_image = _CreateImage( + media_service, opener, 'https://goo.gl/mtt54n') + uploaded_marketing_image = _CreateImage( + media_service, opener, 'http://goo.gl/3b9Wfh') + + teaser = { + 'headline': 'Dream', + 'description': 'Create your own adventure', + 'businessName': 'Interplanetary Ships', + 'logoImage': uploaded_logo_image + } + + # Creates a Gmail ad. + gmail_ad = { + 'xsi_type': 'GmailAd', + 'teaser': teaser, + 'marketingImage': uploaded_marketing_image, + 'marketingImageHeadline': 'Travel', + 'marketingImageDescription': 'Take to the skies!', + 'finalUrls': ['http://wwww.example.com'] + } + + # Creates ad group ad for the Gmail ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': gmail_ad, + # Optional: Set additional settings. + 'status': 'PAUSED' + } + + # Creates ad group ad operations. + operations = [{ + 'operator': 'ADD', + 'operand': ad_group_ad + }] + + # Adds a Gmail ad. + ad_group_ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad_group_ad in ad_group_ads['value']: + print ('A Gmail ad with id "%d" and short headline "%s" was ' + 'added.' % (ad_group_ad['ad']['id'], + ad_group_ad['ad']['teaser']['headline'])) + except Exception as e: + raise Exception('Failed to create Gmail ad: %s' % e) + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_html5_ad.py b/examples/adwords/v201802/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..ddf76b1c --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_html5_ad.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..7fb6a193 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + media_service = client.GetService('MediaService', version='v201802') + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + + try: + # Create marketing image. + marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/3b9Wfh') + + # Create square marketing image. + square_marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/mtt54n') + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': marketing_image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'], + # Optional: Set a square marketing image to the ad. + 'squareMarketingImage': { + 'mediaId': square_marketing_image['mediaId'] + }, + # Optional: Set call-to-action text. + 'callToActionText': 'Shop Now', + # Optional: Set dynamic display ad settings, composed of + # landscape logo image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( + media_service, opener), + # Whitelisted accounts only: Set color settings using + # hexadecimal numbers. + # Set allowFlexibleColor to False if you want your ads to render + # by always using your colors strictly. + # 'mainColor': '#0000ff', + # 'accentColor': '#ffff00', + # 'allowFlexibleColor': False + # Whitelisted accounts only: Set the format setting that the ad + # will be served in. + # 'formatSetting': 'NON_NATIVE' + + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +def _CreateDynamicDisplayAdSettings(media_service, opener): + """Creates settings for dynamic display ad. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + + Returns: + The dynamic display ad settings. + """ + image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + + logo = { + 'type': 'IMAGE', + 'mediaId': image['mediaId'], + 'xsi_type': 'Image' + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!', + 'xsi_type': 'DynamicSettings', + } + + return dynamic_settings + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py new file mode 100755 index 00000000..2c41fe1a --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Adds a Shopping dynamic remarketing campaign for the Display Network. + +This example steps through the following: +* Creates a new Display Network campaign. +* Links the campaign with Merchant Center. +* Links the user list to the ad group. +* Creates a responsive display ad to render the dynamic text. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import base64 +import uuid + +from googleads import adwords + + +MERCHANT_ID = 'INSERT_MERCHANT_CENTER_ID_HERE' +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +USER_LIST_ID = 'INSERT_USER_LIST_ID_HERE' + + +def main(client, merchant_id, budget_id, user_list_id): + opener = client.proxy_config.BuildOpener() + + campaign = CreateCampaign(client, merchant_id, budget_id) + campaign_id = campaign['id'] + print 'Campaign with name "%s" and ID "%d" was added.' % ( + campaign['name'], campaign_id) + + ad_group = CreateAdGroup(client, campaign_id) + ad_group_id = ad_group['id'] + print 'Ad group with name "%s" and ID "%d" was added.' % ( + ad_group['name'], ad_group_id) + + ad_group_ad = CreateAd(client, opener, ad_group_id) + print 'Responsive display ad with ID "%d" was added.' % ( + ad_group_ad['ad']['id']) + + AttachUserList(client, ad_group_id, user_list_id) + print 'User list with ID "%d" was attached to ad group with ID "%d".' % ( + user_list_id, ad_group_id) + + +def CreateCampaign(client, merchant_id, budget_id): + """Creates a new Display Network campaign. + + Args: + client: an AdWordsClient instance. + merchant_id: a int merchant center ID. + budget_id: a int budget ID. + + Returns: + The campaign that was successfully created. + """ + campaign_service = client.GetService('CampaignService', 'v201802') + + campaign = { + 'name': 'Shopping campaign #%d' % uuid.uuid4(), + # Dynamic remarketing campaigns are only available on the Google Display + # Network. + 'advertisingChannelType': 'DISPLAY', + 'status': 'PAUSED', + 'budget': { + 'budgetId': budget_id + }, + # This example uses a Manual CPC bidding strategy, but you should select + # the strategy that best aligns with your sales goals. More details here: + # https://support.google.com/adwords/answer/2472725 + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [{ + 'xsi_type': 'ShoppingSetting', + # Campaigns with numerically higher priorities take precedence over + # those with lower priorities. + 'campaignPriority': 0, + 'merchantId': merchant_id, + # Display network campaigns do not support partition by country. The + # only supported value is "ZZ". This signals that products from all + # countries are available in this campaign. The actual products which + # serve are based on the products tagged in the user list entry. + 'salesCountry': 'ZZ', + # Optional: Enable local inventory ads (items for sale in physical + # stores.) + 'enableLocal': True, + # Optional: Declare whether purchases are only made on the merchant + # store, or completed on Google. + 'purchasePlatform': 'MERCHANT' + }] + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + return campaign_service.mutate(operations)['value'][0] + + +def CreateAdGroup(client, campaign_id): + """Creates a dynamic remarketing campaign. + + Args: + client: an AdWordsClient instance. + campaign_id: an int campaign ID. + + Returns: + The ad group that was successfully created. + """ + ad_group_service = client.GetService('AdGroupService', 'v201802') + + ad_group = { + 'name': 'Dynamic remarketing ad group', + 'campaignId': campaign_id, + 'status': 'ENABLED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': ad_group + }] + + return ad_group_service.mutate(operations)['value'][0] + + +def CreateAd(client, opener, ad_group_id): + """Creates a ResponsiveDisplayAd. + + Args: + client: an AdWordsClient instance. + opener: an OpenerDirector instance. + ad_group_id: an int ad group ID. + + Returns: + The ad group ad that was successfully created. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') + media_service = client.GetService('MediaService', 'v201802') + + marketing_image_id = _CreateImage( + media_service, opener, 'https://goo.gl/3b9Wfh') + logo_image_id = _CreateImage(media_service, opener, 'https://goo.gl/mtt54n') + + ad = { + 'xsi_type': 'ResponsiveDisplayAd', + # This ad format doesn't allow the creation of an image using the + # Image.data field. An image must first be created using the MediaService, + # and Image.mediaId must be populated when creating the ad. + 'marketingImage': { + 'xsi_type': 'Image', + 'mediaId': marketing_image_id + }, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://wwww.example.com'], + # Optional: Call to action text. + # Valid texts: https://support.google.com/adwords/answer/7005917 + 'callToActionText': 'Apply Now', + # Optional: Set dynamic display ad settings, composed of landscape logo + # image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': CreateDynamicDisplayAdSettings( + client, opener), + # Optional: Create a logo image and set it to the ad. + 'logoImage': { + 'xsi_type': 'Image', + 'mediaId': logo_image_id + }, + # Optional: Create a square marketing image and set it to the ad. + 'squareMarketingImage': { + 'xsi_type': 'Image', + 'mediaId': logo_image_id + }, + # Whitelisted accounts only: Set color settings using hexadecimal values. + # Set allowFlexibleColor to False if you want your ads to render by always + # using your colors strictly. + # 'mainColor': '#000fff', + # 'accentColor': '#fff000', + # 'allowFlexibleColor': False, + # Whitelisted accounts only: Set the format setting that the ad will be + # served in. + # 'formatSetting': 'NON_NATIVE' + } + + ad_group_ad = { + 'ad': ad, + 'adGroupId': ad_group_id + } + + operations = [{ + 'operation': 'ADD', + 'operand': ad_group_ad + }] + + return ad_group_ad_service.mutate(operations)['value'][0] + + +def AttachUserList(client, ad_group_id, user_list_id): + """Links the provided ad group and user list. + + Args: + client: an AdWordsClient instance. + ad_group_id: an int ad group ID. + user_list_id: an int user list ID. + + Returns: + The ad group criterion that was successfully created. + """ + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', 'v201802') + + user_list = { + 'xsi_type': 'CriterionUserList', + 'userListId': user_list_id + } + + ad_group_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'criterion': user_list, + 'adGroupId': ad_group_id + } + + operations = [{ + 'operator': 'ADD', + 'operand': ad_group_criterion + }] + + return ad_group_criterion_service.mutate(operations)['value'][0] + + +def CreateDynamicDisplayAdSettings(client, opener): + """Creates dynamic display ad settings. + + Args: + client: an AdWordsClient instance. + opener: an OpenerDirector instance. + + Returns: + A dict containing the dynamic display ad settings. + """ + media_service = client.GetService('MediaService', 'v201802') + + logo = { + 'xsi_type': 'Image', + 'mediaId': _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!' + } + + return dynamic_settings + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, MERCHANT_ID, BUDGET_ID, USER_LIST_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py new file mode 100755 index 00000000..e992b18c --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Universal App campaign. + +To get campaigns, run get_campaigns.py. To upload image assets for this +campaign, run upload_image.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201802') + + budget_id = CreateBudget(client) + + # Create the Universal App campaign. + universal_app_campaign = { + 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'MULTI_CHANNEL', + 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', + # Set the campaign's bidding strategy. Universal app campaigns only + # support TARGET_CPA bidding strategy. + 'biddingStrategyConfiguration': { + # Set the target CPA to $1 / app install. + 'biddingScheme': { + 'xsi_type': 'TargetCpaBiddingScheme', + 'targetCpa': { + 'microAmount': '1000000' + } + }, + 'biddingStrategyType': 'TARGET_CPA' + }, + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + + universal_app_campaign['settings'] = [ + # Set the campaign's assets and ad text ideas. These values will + # be used to generate ads. + { + 'xsi_type': 'UniversalAppCampaignSetting', + 'appId': 'com.labpixies.colordrips', + 'appVendor': 'VENDOR_GOOGLE_MARKET', + 'description1': 'A cool puzzle game', + 'description2': 'Remove connected blocks', + 'description3': '3 difficulty levels', + 'description4': '4 colorful fun skins', + # Optional: You can set up to 20 image assets for your campaign. + # See upload_image.py for an example on how to upload images. + # + # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] + } + ] + + # Optimize this campaign for getting new users for your app. + universal_app_campaign_setting = universal_app_campaign['settings'][0] + universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( + 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') + + # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, + # then also specify your in-app conversion types so AdWords can focus your + # campaign on people who are most likely to complete the corresponding in-app + # actions. + # + # Conversions type IDs can be retrieved using ConversionTrackerService.get. + # universal_app_campaign['selectiveOptimization'] = { + # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] + # } + + # Optional: Set the campaign settings for Advanced location options. + universal_app_campaign['settings'].append({ + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + }) + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': universal_app_campaign + }] + + campaigns = campaign_service.mutate(operations)['value'] + + # Display results. + if campaigns: + for campaign in campaigns: + print ('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + # Optional: Set the campaign's location and language targeting. No other + # targeting criteria can be used for Universal App campaigns. + SetCampaignTargetingCriteria(client, campaign) + else: + print 'No Universal App campaigns were added.' + + +def CreateBudget(client): + """Creates a budget and returns its budgetId. + + Args: + client: An AdWordsClient instance. + + Returns: + An int budgetId for the created Budget. + """ + budget_service = client.GetService('BudgetService', version='v201802') + + # Create a budget. + budget = { + 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Create the budget and return its ID. + budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] + + return budget_id + + +def SetCampaignTargetingCriteria(client, campaign): + """Sets targeting criteria for the given campaign. + + Args: + client: An AdWordsClient instance. + campaign: A suds object representing the campaign we wish to attach + targeting criteria. + """ + campaign_criterion_service = client.GetService('CampaignCriterionService') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + criteria = [ + { + 'xsi_type': 'Location', + 'id': 21137 # California + }, + { + 'xsi_type': 'Location', + 'id': 2484 # Mexico + }, + { + 'xsi_type': 'Language', + 'id': 1000 # English + }, + { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + ] + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign['id'], + 'criterion': criterion + } + } for criterion in criteria] + + response = campaign_criterion_service.mutate(operations) + + if response and 'value' in response: + # Display the added campaign targets. + for criterion in response['value']: + print ('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], + criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..7efcf236 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201802') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201802') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201802') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..7a91a4df --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201802') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201802') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..10bca1ce --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201802') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..47639262 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201802') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201802') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201802') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201802/basic_operations/__init__.py b/examples/adwords/v201802/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201802/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201802/basic_operations/add_ad_groups.py b/examples/adwords/v201802/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..a56ec582 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201802') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name "%s" and id "%s" was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/basic_operations/add_campaigns.py b/examples/adwords/v201802/basic_operations/add_campaigns.py new file mode 100755 index 00000000..929d2657 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/add_campaigns.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201802') + budget_service = client.GetService('BudgetService', version='v201802') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201802/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..e8963345 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/add_keywords.py b/examples/adwords/v201802/basic_operations/add_keywords.py new file mode 100755 index 00000000..1e46a98a --- /dev/null +++ b/examples/adwords/v201802/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201802') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/get_ad_groups.py b/examples/adwords/v201802/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..f2fda1ba --- /dev/null +++ b/examples/adwords/v201802/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201802') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name "%s", id "%s" and status "%s" was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/basic_operations/get_campaigns.py b/examples/adwords/v201802/basic_operations/get_campaigns.py new file mode 100755 index 00000000..5a67c342 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/get_campaigns.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201802') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..7220e6f0 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201802') + + # Construct query and get all campaigns. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'Name', 'Status') + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, PAGE_SIZE) + .Build()) + + for page in query.Pager(campaign_service): + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201802/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..64e656d5 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an expanded text ad, run add_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/get_keywords.py b/examples/adwords/v201802/basic_operations/get_keywords.py new file mode 100755 index 00000000..012ab9c3 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201802') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/pause_ad.py b/examples/adwords/v201802/basic_operations/pause_ad.py new file mode 100755 index 00000000..d9c00409 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id "%s" was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201802/basic_operations/remove_ad.py b/examples/adwords/v201802/basic_operations/remove_ad.py new file mode 100755 index 00000000..7eb35a05 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id "%s" and type "%s" was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201802/basic_operations/remove_ad_group.py b/examples/adwords/v201802/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..7d82f4ef --- /dev/null +++ b/examples/adwords/v201802/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201802') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name "%s" and id "%s" was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/remove_campaign.py b/examples/adwords/v201802/basic_operations/remove_campaign.py new file mode 100755 index 00000000..b4a55598 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201802') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name "%s" and id "%s" was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/basic_operations/remove_keyword.py b/examples/adwords/v201802/basic_operations/remove_keyword.py new file mode 100755 index 00000000..63ee1239 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201802') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201802/basic_operations/update_ad_group.py b/examples/adwords/v201802/basic_operations/update_ad_group.py new file mode 100755 index 00000000..7f06c46c --- /dev/null +++ b/examples/adwords/v201802/basic_operations/update_ad_group.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the CPC bid and status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' + + +def main(client, ad_group_id, bid_micro_amount=None): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201802') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + + if bid_micro_amount: + operations[0]['operand']['biddingStrategyConfiguration'] = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': bid_micro_amount, + } + }] + } + + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] + # Find the CpcBid in the bidding strategy configuration's bids collection. + cpc_bid_micros = None + + if bidding_strategy_configuration: + bids = bidding_strategy_configuration['bids'] + + if bids: + for bid in bids: + if bid['Bids.Type'] == 'CpcBid': + cpc_bid_micros = bid['bid']['microAmount'] + break + + print ('Ad group with name "%s", and id "%s" was updated to have status ' + '"%s" and CPC bid %d.' + % (ad_group['name'], ad_group['id'], ad_group['status'], + cpc_bid_micros)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201802/basic_operations/update_campaign.py b/examples/adwords/v201802/basic_operations/update_campaign.py new file mode 100755 index 00000000..70bd4546 --- /dev/null +++ b/examples/adwords/v201802/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201802') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/basic_operations/update_keyword.py b/examples/adwords/v201802/basic_operations/update_keyword.py new file mode 100755 index 00000000..fd0527bb --- /dev/null +++ b/examples/adwords/v201802/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201802') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: "%s", value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201802/campaign_management/__init__.py b/examples/adwords/v201802/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py new file mode 100755 index 00000000..9576a872 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a campaign group and sets a performance target for it. + +To get campaigns, run get_campaigns.py. To download reports, run +download_criteria_report_with_awql.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id1, campaign_id2): + campaign_group_id = _CreateCampaignGroup(client) + _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) + _CreatePerformanceTarget(client, campaign_group_id) + print 'Campaign group and its performance target were setup successfully.' + + +def _CreateCampaignGroup(client): + """Create a campaign group. + + Args: + client: an AdWordsClient instance. + + Returns: + The integer ID of the created campaign group. + """ + # Get the CampaignGroupService. + campaign_group_service = client.GetService('CampaignGroupService', + version='v201802') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the campaign group. + 'operand': { + 'name': 'Mars campaign group #%d' % uuid.uuid4() + } + }] + + campaign_group = campaign_group_service.mutate(operations)['value'][0] + campaign_group_id = campaign_group['id'] + + # Display the results. + print 'Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name']) + + return campaign_group_id + + +def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): + """Adds multiple campaigns to a campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + campaign_ids: a list of integer IDs for campaigns. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201802') + + # Create the operations. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'campaignGroupId': campaign_group_id + } + } for campaign_id in campaign_ids] + + campaign_service.mutate(operations) + + # Display the results. + print ('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + + +def _CreatePerformanceTarget(client, campaign_group_id): + """Creates a performance target for the campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + """ + # Get the CampaignGroupPerformanceTargetService. + cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', + version='v201802') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the performance target. + 'operand': { + 'campaignGroupId': campaign_group_id, + 'performanceTarget': { + # Keep the CPC for the campaigns < $3. + 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', + 'efficiencyTargetValue': 3000000, + # Keep the maximum spend under $50. + 'spendTargetType': 'MAXIMUM', + 'spendTarget': { + 'microAmount': 500000000 + }, + # Aim for at least 3000 clicks. + 'volumeGoalType': 'MAXIMIZE_CLICKS', + 'volumeTargetValue': 3000, + # Start the performance target today, and run it for the next 90 + # days. + 'startDate': datetime.datetime.now().strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(90)).strftime('%Y%m%d') + } + } + }] + + cgpt = cgpt_service.mutate(operations)['value'][0] + + # Display the results. + print ('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201802/campaign_management/add_campaign_labels.py b/examples/adwords/v201802/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..0b59df85 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201802') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..0cc20483 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201802') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201802') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding an ExpandedTextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new ExpandedTextAd for + each of the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once + # you've added targeting and the ads are ready to serve. + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201802') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201802/campaign_management/add_draft.py b/examples/adwords/v201802/campaign_management/add_draft.py new file mode 100755 index 00000000..afeef760 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + draft_service = client.GetService('DraftService', version='v201802') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201802') + + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..6e8eb880 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to incrementally upload keywords. + +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201802') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201802') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201802') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201802') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/campaign_management/add_trial.py b/examples/adwords/v201802/campaign_management/add_trial.py new file mode 100755 index 00000000..931a66ee --- /dev/null +++ b/examples/adwords/v201802/campaign_management/add_trial.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201802') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201802') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..cfb8ef3f --- /dev/null +++ b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'PolicySummary'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CombinedApprovalStatus', + 'operator': 'EQUALS', + 'values': 'DISAPPROVED' + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + disapproved_count = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.get(selector) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName'], + policy_topic_entry['policyTopicHelpCenterUrl']) + # Display the attributes and values that triggered the policy topic. + policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] + if policy_topic_evidences: + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..ba8ab982 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', + version='v201802') + + # Construct query and get all ads for a given campaign. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'PolicySummary') + .Where('AdGroupId').EqualTo(ad_group_id) + .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') + .OrderBy('Id') + .Limit(0, PAGE_SIZE) + .Build()) + disapproved_count = 0 + + # Display results. + while True: + page = ad_group_ad_service.query(query) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + # Display the attributes and values that triggered the policy topic. + if ('policyTopicEvidences' in policy_topic_entry + and policy_topic_entry['policyTopicEvidences']): + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + if not query.HasNext(page): + break + query.NextPage() + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201802/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..37deb3d7 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201802') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id "%s", name "%s", and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201802/campaign_management/graduate_trial.py b/examples/adwords/v201802/campaign_management/graduate_trial.py new file mode 100755 index 00000000..970eaf3e --- /dev/null +++ b/examples/adwords/v201802/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201802') + budget_service = client.GetService('BudgetService', version='v201802') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201802/campaign_management/set_ad_parameters.py b/examples/adwords/v201802/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..4c44ff29 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + ad_param_service = client.GetService('AdParamService', version='v201802') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..0fb52250 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201802') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201802/campaign_management/validate_text_ad.py b/examples/adwords/v201802/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..d657e884 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +No objects will be created, but exceptions will still be returned. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import suds + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Construct operations to add an expanded text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'] + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for all astronauts in orbit', + 'finalUrls': ['http://www.example.com'], + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except suds.WebFault, e: + print 'Validation correctly failed with "%s".' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/error_handling/__init__.py b/examples/adwords/v201802/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201802/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201802/error_handling/handle_partial_failures.py b/examples/adwords/v201802/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..9efc7237 --- /dev/null +++ b/examples/adwords/v201802/error_handling/handle_partial_failures.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201802') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + if (first_field_path_element and + first_field_path_element['field'] == 'operations' and + first_field_path_element['index']): + operation_index = first_field_path_element['index'] + + adgroup_criterion = operations[operation_index]['operand'] + + print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' + 'a failure for the following reason: %s.' + % (adgroup_criterion['adGroupId'], + adgroup_criterion['criterion']['text'], + error['errorString'])) + else: + print ('A failure has occurred for the following reasons: %s\n' + % error['errorString']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/error_handling/handle_policy_violation_error.py b/examples/adwords/v201802/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..e4623468 --- /dev/null +++ b/examples/adwords/v201802/error_handling/handle_policy_violation_error.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') + + # Create expanded text ad that violates an exemptable policy. + exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise!!!', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + # Create text ad that violates a non-exemptable policy. + non_exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise with too long of a headline.', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + operations = [exemptable_expanded_text_ad_operation, + non_exemptable_expanded_text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + # Get the index of the failed operation from the error's field path + # elements. + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + # If the operation index is not present on the first error field path + # element, then there's no way to determine which operation to remove, + # so simply throw the exception. + if (not (first_field_path_element + and first_field_path_element['field'] == 'operations' + and first_field_path_element['index'])): + raise e + + operation_index = first_field_path_element['index'] + index = int(operation_index[0]) + operation = operations[index] + if not HandleAPIError(error, operation): + # Set non-exemptable operation to None to mark for deletion. + print ('Removing operation with non-exemptable error at index %s.' + % operation_index) + operations[index] = None + + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is "%s".' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +def HandleAPIError(error, operation): + """Makes an exemption for exemptable PolicyViolationErrors. + + Args: + error: the error associated with the given operation. + operation: the operation associated with the given error. + + Returns: + A boolean that is True if the given error was an exemptable + PolicyViolationError; otherwise, returns False. + """ + is_exemptable = False + + # Determine if the operation can be resubmitted with an exemption request. + if error['ApiError.Type'] == 'PolicyViolationError': + expanded_text_ad = operation['operand']['ad'] + is_exemptable = (error['isExemptable'] if 'isExemptable' in error else + False) + print ('Ad with headline "%s - %s" violated %s policy "%s".' % + (expanded_text_ad['headlinePart1'], + expanded_text_ad['headlinePart2'], + 'exemptable' if is_exemptable else 'non-exemptable', + error['externalPolicyName'])) + + if is_exemptable: + # Add exemption request to the operation. + print ('Adding exemption request for policy name "%s" on text "%s".' + % (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({'key': error['key']}) + + return is_exemptable + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/extensions/__init__.py b/examples/adwords/v201802/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201802/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..40381a65 --- /dev/null +++ b/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +# Import appropriate modules from the client library. +import suds + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201802').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201802') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except suds.WebFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201802/extensions/add_prices.py b/examples/adwords/v201802/extensions/add_prices.py new file mode 100755 index 00000000..9d77294d --- /dev/null +++ b/examples/adwords/v201802/extensions/add_prices.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201802') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', + final_mobile_url='http://m.example.com/scrubs'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url='http://m.example.com/haircuts'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url=( + 'http://m.example.com/skincarepackage')) + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit, final_mobile_url=None): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + final_mobile_url: A str containing the final mobile URL after all cross + domain redirects. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + table_row = { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + if final_mobile_url: + table_row['finalMobileUrls'] = { + 'urls': [final_mobile_url] + } + + return table_row + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/extensions/add_site_links.py b/examples/adwords/v201802/extensions/add_site_links.py new file mode 100755 index 00000000..2a13cbcb --- /dev/null +++ b/examples/adwords/v201802/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201802') + customer_service = client.GetService('CustomerService', version='v201802') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/extensions/add_site_links_using_feeds.py b/examples/adwords/v201802/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..738ffda7 --- /dev/null +++ b/examples/adwords/v201802/extensions/add_site_links_using_feeds.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201802') + feed_item_service = client.GetService('FeedItemService', version='v201802') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201802') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201802') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name "%s" and ID "%s" was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line2': 'Home line 2', 'line3': 'Home line 3'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line2': 'Support line 2', 'line3': 'Support line 3'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line2': 'Products line 2', 'line3': 'Products line 3'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Use geographical targeting on a feed. + # The IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + if 'locationId' in item: + feed_item['geoTargeting'] = { + 'id': item['locationId'] + } + feed_item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %s was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %s and placeholder type %s was saved for feed' + ' with ID %s.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %s was associated with feed with ID %s.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/migration/__init__.py b/examples/adwords/v201802/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201802/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201802/migration/migrate_to_extension_settings.py b/examples/adwords/v201802/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..3dbb69ff --- /dev/null +++ b/examples/adwords/v201802/migration/migrate_to_extension_settings.py @@ -0,0 +1,526 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201802') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + 'scheduling': site_link_from_feed['scheduling'] + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201802') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201802') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201802') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201802') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201802') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201802') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + if 'scheduling' in feed_item: + site_link_from_feed['scheduling'] = feed_item['scheduling'] + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/misc/__init__.py b/examples/adwords/v201802/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201802/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201802/misc/get_all_images_and_videos.py b/examples/adwords/v201802/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..294477ef --- /dev/null +++ b/examples/adwords/v201802/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201802') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/misc/upload_image.py b/examples/adwords/v201802/misc/upload_image.py new file mode 100755 index 00000000..d80c284d --- /dev/null +++ b/examples/adwords/v201802/misc/upload_image.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import base64 +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201802') + + with open(image_filename, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201802/misc/upload_media_bundle.py b/examples/adwords/v201802/misc/upload_media_bundle.py new file mode 100755 index 00000000..e09a3a1e --- /dev/null +++ b/examples/adwords/v201802/misc/upload_media_bundle.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import base64 +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201802') + # Create HTML5 media. + base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( + 'https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': base64_encoded_html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetBase64EncodedHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/optimization/__init__.py b/examples/adwords/v201802/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201802/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201802/optimization/estimate_keyword_traffic.py b/examples/adwords/v201802/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..28465e7a --- /dev/null +++ b/examples/adwords/v201802/optimization/estimate_keyword_traffic.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201802') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..ec07bb79 --- /dev/null +++ b/examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201802') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201802/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..edc2c8f3 --- /dev/null +++ b/examples/adwords/v201802/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201802') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'BiddableConversions', 'BiddableConversionsValue', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages: + num_landscape_points = 0 + page = data_service.getCriterionBidLandscape(selector) + + if page and 'entries' in page: + entries = page['entries'] + print 'Bid landscape(s) retrieved: %d.' % len(entries) + + for bid_landscape in entries: + print ('Retrieved keyword bid landscape with ad group ID "%d", ' + 'keyword ID "%d", start date "%s", end date "%s", ' + 'with landscape points:' % ( + bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + num_landscape_points += 1 + print (' bid: %s => clicks: %s, cost: %s, impressions: %s, ' + 'biddable conversions: %.2f, ' + 'biddable conversions value: %.2f' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'], + bid_landscape_point['biddableConversions'], + bid_landscape_point['biddableConversionsValue'])) + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201802/optimization/get_keyword_ideas.py b/examples/adwords/v201802/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..d2e42701 --- /dev/null +++ b/examples/adwords/v201802/optimization/get_keyword_ideas.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id=None): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201802') + + # Construct selector object and retrieve related keywords. + selector = { + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS' + } + + selector['requestedAttributeTypes'] = [ + 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] + + offset = 0 + selector['paging'] = { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + + selector['searchParameters'] = [{ + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }] + + # Language setting (optional). + selector['searchParameters'].append({ + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }) + + # Network search parameter (optional) + selector['searchParameters'].append({ + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + }) + + # Use an existing ad group to generate ideas (optional) + if ad_group_id is not None: + selector['searchParameters'].append({ + 'xsi_type': 'SeedAdGroupIdSearchParameter', + 'adGroupId': ad_group_id + }) + + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr( + attribute['value'], 'value', '0') + print ('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201802/remarketing/__init__.py b/examples/adwords/v201802/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201802/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201802/remarketing/add_audience.py b/examples/adwords/v201802/remarketing/add_audience.py new file mode 100755 index 00000000..2d5de75e --- /dev/null +++ b/examples/adwords/v201802/remarketing/add_audience.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201802') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201802') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + user_list_result = user_list_service.mutate(operations) + + # Capture the ID(s) of the conversion. + if 'value' in user_list_result: + conversion_ids = [] + for user_list in user_list_result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + # Create query. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'GoogleGlobalSiteTag', 'GoogleEventSnippet') + .Where('Id').In(*conversion_ids) + .Limit(0, PAGE_SIZE) + .Build()) + + conversions_map = {} + + # Get all conversion trackers. + for page in query.Pager(conversion_tracker_service): + if 'entries' in page: + for conversion_tracker in page['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in user_list_result['value']: + print ('User list with name "%s" and ID "%s" was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print ('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/add_conversion_tracker.py b/examples/adwords/v201802/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..fedea7a0 --- /dev/null +++ b/examples/adwords/v201802/remarketing/add_conversion_tracker.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201802') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + 'textFormat': 'HIDDEN', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'conversionPageLanguage': 'en', + 'backgroundColor': '#0000FF', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/add_conversion_trackers.py b/examples/adwords/v201802/remarketing/add_conversion_trackers.py new file mode 100755 index 00000000..5e96e8c8 --- /dev/null +++ b/examples/adwords/v201802/remarketing/add_conversion_trackers.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds AdWords conversion trackers. + +Adds an AdWords conversion tracker and an upload conversion tracker. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201802') + + # Create an AdWords conversion tracker. + adwords_conversion_tracker = { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'name': 'Upload Conversion #%s' % uuid.uuid4(), + # Optional fields. + # Set an appropriate category. This will be set to DEFAULT if not + # specified. + 'category': 'LEAD', + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90', + # Set the default currency code to use for conversions that do + # not specify a conversion currency. This must be an ISO 4217 3-character + # code such as "EUR" or "USD". + # If this field is not set, AdWords will use the account's currency. + 'defaultRevenueCurrencyCode': 'EUR', + # Set the default revenue value to use for conversions that do not specify + # a converison value. Note that this value should NOT be in micros. + 'defaultRevenueValue': '2.50', + # To upload fractional conversion credits, mark the upload conversion as + # externally attributed. To learn more about importing externally + # attributed conversions, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'isExternallyAttributed': 'true' + } + + # Construct operations. + operations = [{ + 'operator': 'ADD', + 'operand': conversion_tracker + } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] + + # Add the conversions. + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion with ID "%d", name "%s", status "%s", and category ' + '"%s" was added.' + % (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + if (conversion_tracker['ConversionTracker.Type'] + == 'AdWordsConversionTracker'): + print ('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print ('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/add_crm_based_user_list.py b/examples/adwords/v201802/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..e542c0fc --- /dev/null +++ b/examples/adwords/v201802/remarketing/add_crm_based_user_list.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201802') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # See limit here: + # https://support.google.com/adwords/answer/6276125#requirements + 'membershipLifeSpan': 30, + 'uploadKeyType': 'CONTACT_INFO' + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + + emails = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] + + # Add address info. + members.append({ + 'addressInfo': { + # First and last name must be normalized and hashed. + 'hashedFirstName': NormalizeAndSHA256('John'), + 'hashedLastName': NormalizeAndSHA256('Doe'), + # Country code and zip code are sent in plaintext. + 'countryCode': 'US', + 'zipCode': '10001' + } + }) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'membersList': members + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def NormalizeAndSHA256(s): + """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. + + Args: + s: The string to perform this operation on. + + Returns: + A normalized and SHA-256 hashed string. + """ + return hashlib.sha256(s.strip().lower()).hexdigest() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201802/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..d291310e --- /dev/null +++ b/examples/adwords/v201802/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201802') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords knows how to apply the + # rules. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ], + # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF + # means 'at least one item in each rule item group must match', and DNF + # means 'at least one entire rule item group must match'. + # DateSpecificRuleUserList only supports DNF. You can also omit the rule + # type altogether to default to DNF. + 'ruleType': 'DNF' + } + + # Third and fourth rule item groups. + # Visitors of a page who visited another page. + site1_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example1' + } + } + site2_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example2' + } + } + + # Create two rules to show that a visitor browsed two sites. + user_visited_site1_rule = { + 'groups': [{ + 'items': [site1_rule_item] + }] + } + + user_visited_site2_rule = { + 'groups': [{ + 'items': [site2_rule_item] + }] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule, + # Optional: Set the populationStatus to REQUESTED to include past users in + # the user list. + 'prepopulationStatus': 'REQUESTED' + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create the user list for "Visitors of a page who did visit another page". + # To create a user list for "Visitors of a page who did not visit another + # page", change the ruleOperator from AND to AND_NOT. + combined_user_list = { + 'xsi_type': 'CombinedRuleUserList', + 'name': 'Combined rule user lst create at ${creation_time}', + 'description': 'Users who visited two sites.', + 'leftOperand': user_visited_site1_rule, + 'rightOperand': user_visited_site2_rule, + 'ruleOperator': 'AND' + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list, + combined_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201802/remarketing/upload_offline_call_conversions.py new file mode 100755 index 00000000..4321e895 --- /dev/null +++ b/examples/adwords/v201802/remarketing/upload_offline_call_conversions.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for calls related to ads in your account. + +To set up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CALLER_ID = 'INSERT_CALLER_ID_HERE' +# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats +# For time zones, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +CALL_START_TIME = 'INSERT_CALL_START_TIME' +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, caller_id, call_start_time, conversion_name, conversion_time, + conversion_value): + # Initialize appropriate services. + occ_feed_service = client.GetService( + 'OfflineCallConversionFeedService', version='v201802') + + # Associate offline call conversions with the existing named conversion + # tracker. If this tracker was newly created, it may be a few hours before it + # can accept conversions. + feed = { + 'callerId': caller_id, + 'callStartTime': call_start_time, + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + } + + occ_operations = [{'operator': 'ADD', 'operand': feed}] + + occ_response = occ_feed_service.mutate(occ_operations) + values = occ_response['value'] + + if values: + for occ_feed in values: + print ('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + else: + print 'No offline call conversions were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, + CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201802/remarketing/upload_offline_conversions.py b/examples/adwords/v201802/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..3d84c0c4 --- /dev/null +++ b/examples/adwords/v201802/remarketing/upload_offline_conversions.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201802') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id, + # Optional: To upload fractional conversion credits, set the external + # attribution model and credit. To use this feature, your conversion + # tracker should be marked as externally attributed. To learn more about + # importing externally attributed conversins, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'externalAttributionCredit': 0.3, + # 'externalAttributionModel': 'Linear' + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201802/remarketing/upload_offline_data.py b/examples/adwords/v201802/remarketing/upload_offline_data.py new file mode 100755 index 00000000..6f834e3e --- /dev/null +++ b/examples/adwords/v201802/remarketing/upload_offline_data.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 shows how to upload offline data for store sales transactions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import datetime +import hashlib + +from googleads import adwords +import pytz + + +_DT_FORMAT = '%Y%m%d %H%M%S' +# User identifier types whose values must be hashed. +_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', + 'HASHED_LAST_NAME', 'HASHED_PHONE') +# The timezone to be used in this example. For valid timezone IDs, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +_TIMEZONE = pytz.timezone('America/New_York') +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Insert email addresses below for creating user identifiers. +EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] +# The external upload ID can be any number that you use to keep track of your +# uploads. +EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' +# Store sales upload common metadata types +METADATA_TYPE_1P = 'FirstPartyUploadMetadata' +METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' +# Set the below constant to METADATA_TYPE_3P if uploading third-party data. +STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P +# The three constants below are needed when uploading third-party data. They +# are not used when uploading first-party data. +# Advertiser upload time to partner. +# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, +# see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' +# Indicates the version of the bridge map. +BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' +# The ID of the third party uploading the transaction feed. +PARTNER_ID = 'INSERT_PARTNER_ID_HERE' + + +def main(client, conversion_name, external_upload_id, + store_sales_upload_common_metadata_type, email_addresses, + advertiser_upload_time=None, bridge_map_version_id=None, + partner_id=None): + # Set partial failure to True since this example demonstrates how to handle + # partial errors. + client.partial_failure = True + # Initialize appropriate services. + offline_data_upload_service = client.GetService( + 'OfflineDataUploadService', version='v201802') + + # Create the first offline data for upload. + # This transaction occurred 7 days ago with an amount of $200 USD. + transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=7)) + offline_data_1 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[0]), + _CreateUserIdentifier(identifier_type='STATE', value='New York') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_1), + 'transactionAmount': { + 'currencyCode': 'USD', + 'money': { + 'microAmount': 200000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create the second offline data for upload. + # This transaction occurred 14 days ago with amount of 450 EUR. + transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=14)) + offline_data_2 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[1]), + _CreateUserIdentifier(identifier_type='STATE', value='California') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_2), + 'transactionAmount': { + 'currencyCode': 'EUR', + 'money': { + 'microAmount': 450000000 + } + }, + 'conversionName': conversion_name + } + } + + # Set the type and metadata of this upload. + upload_metadata = { + 'StoreSalesUploadCommonMetadata': { + 'xsi_type': store_sales_upload_common_metadata_type, + 'loyaltyRate': 1.0, + 'transactionUploadRate': 1.0, + } + } + + if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: + upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' + elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: + upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' + upload_metadata['StoreSalesUploadCommonMetadata'].update({ + 'advertiserUploadTime': advertiser_upload_time, + 'validTransactionRate': 1.0, + 'partnerMatchRate': 1.0, + 'partnerUploadRate': 1.0, + 'bridgeMapVersionId': bridge_map_version_id, + 'partnerId': partner_id + }) + else: + raise ValueError('Unknown metadata type.') + + # Create offline data upload + offline_data_upload = { + 'externalUploadId': external_upload_id, + 'offlineDataList': [offline_data_1, offline_data_2], + # Set the type of this upload. + 'uploadType': upload_type, + 'uploadMetadata': upload_metadata + } + + # Create an offline data upload operation. + operations = [{ + 'operator': 'ADD', + 'operand': offline_data_upload + }] + + # Upload offline data on the server and print the result. + result = offline_data_upload_service.mutate(operations) + offline_data_upload = result['value'][0] + + print ('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) + + # Print any partial data errors from the response. + if result['partialFailureErrors']: + for api_error in result['partialFailureErrors']: + # Get the index of the failed operation from the error's field path + # elements. + operation_index = _GetFieldPathElementIndex(api_error, 'operations') + + if operation_index: + failed_offline_data_upload = operations[operation_index]['operand'] + # Get the index of the entry in the offline data list from the error's + # field path elements. + offline_data_list_index = _GetFieldPathElementIndex( + api_error, 'offlineDataList') + print ('Offline data list entry "%d" in operation "%d" with external ' + 'upload ID "%d" and type "%s" has triggered failure for the ' + 'following reason: "%s"' % ( + offline_data_list_index, operation_index, + failed_offline_data_upload['externalUploadId'], + failed_offline_data_upload['uploadType'], + api_error['errorString'])) + else: + print ('A failure has occurred for the following reason: "%s".' % ( + api_error['errorString'])) + + +def _CreateUserIdentifier(identifier_type=None, value=None): + """Creates a user identifier from the specified type and value. + + Args: + identifier_type: a str specifying the type of user identifier. + value: a str value of the identifier; to be hashed using SHA-256 if needed. + + Returns: + A dict specifying a user identifier, with a value hashed using SHA-256 if + needed. + """ + if identifier_type in _HASHED_IDENTIFIER_TYPES: + # If the user identifier type is a hashed type, normalize and hash the + # value. + value = hashlib.sha256(value.strip().lower()).hexdigest() + + user_identifier = { + 'userIdentifierType': identifier_type, + 'value': value + } + + return user_identifier + + +def _GetFieldPathElementIndex(api_error, field): + """Retrieve the index of a given field in the api_error's fieldPathElements. + + Args: + api_error: a dict containing a partialFailureError returned from the AdWords + API. + field: a str field for which this determines the index in the api_error's + fieldPathElements. + + Returns: + An int index of the field path element, or None if the specified field can't + be found in the api_error. + """ + field_path_elements = api_error['fieldPathElements'] + + if field_path_elements: + found_index = [field_path_element['index'] + for field_path_element in field_path_elements + if field_path_element['field'] == field] + if found_index: + return found_index + + return None + + +def _GetFormattedDateTime(dt): + """Formats the given datetime and timezone for use with AdWords. + + Args: + dt: a datetime instance. + + Returns: + A str representation of the datetime in the correct format for AdWords. + """ + return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, + STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, + ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201802/reporting/__init__.py b/examples/adwords/v201802/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201802/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..3266a5a5 --- /dev/null +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys + +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201802') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py new file mode 100755 index 00000000..9525feb1 --- /dev/null +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import StringIO +import sys +from googleads import adwords + + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201802') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..561e0d96 --- /dev/null +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201802') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py new file mode 100755 index 00000000..64f72313 --- /dev/null +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201802') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..baeaa32b --- /dev/null +++ b/examples/adwords/v201802/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import sys +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201802') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + # You can provide a file object to write the output to. For this + # demonstration we use sys.stdout to write the report to the screen. + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', sys.stdout, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py new file mode 100755 index 00000000..dc38faba --- /dev/null +++ b/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import logging +import sys +from googleads import adwords + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201802') + + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201802/reporting/get_report_fields.py b/examples/adwords/v201802/reporting/get_report_fields.py new file mode 100755 index 00000000..87fa380c --- /dev/null +++ b/examples/adwords/v201802/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201802') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type "%s" contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201802/reporting/parallel_report_download.py b/examples/adwords/v201802/reporting/parallel_report_download.py new file mode 100755 index 00000000..c5d284c3 --- /dev/null +++ b/examples/adwords/v201802/reporting/parallel_report_download.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import logging +import multiprocessing +from Queue import Empty +import time +import googleads + +logging.basicConfig(level=logging.INFO) +logging.getLogger('suds.transport').setLevel(logging.DEBUG) + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(client, report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + _FILENAME_TEMPLATE = 'adgroup_%d.csv' + _FILEPATH_TEMPLATE = '%s/%s' + + def __init__(self, client, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + client: An AdWordsClient instance. + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_downloader = client.GetReportDownloader(version='v201802') + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def _DownloadReport(self, customer_id): + filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, + self._FILENAME_TEMPLATE % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (self.ident, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + self.report_downloader.DownloadReport( + self.report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError, e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + except Exception, e: + print 'Report failed for customer ID "%s".' % customer_id + print 'e: %s' % e.__class__ + return (False, {'customerId': customer_id, 'code': None, + 'message': e.message}) + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = self._DownloadReport(customer_id) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + + Raises: + Exception: if no CustomerIds could be found. + + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201802') + + offset = 0 + + # Get the account hierarchy for this account. + selector = {'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE)}} + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201802/shopping/__init__.py b/examples/adwords/v201802/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201802/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201802/shopping/add_product_partition_tree.py b/examples/adwords/v201802/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..7c4dd3d5 --- /dev/null +++ b/examples/adwords/v201802/shopping/add_product_partition_tree.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201802') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/shopping/add_product_scope.py b/examples/adwords/v201802/shopping/add_product_scope.py new file mode 100755 index 00000000..c8a893ed --- /dev/null +++ b/examples/adwords/v201802/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201802') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/shopping/add_shopping_campaign.py b/examples/adwords/v201802/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..eab1d0d8 --- /dev/null +++ b/examples/adwords/v201802/shopping/add_shopping_campaign.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +# If set to true, a default partition will be created. If running the +# add_product_partition_tree.py example right after this example, make +# sure this stays set to false. +CREATE_DEFAULT_PARTITION = False +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id, create_default_partition): + campaign_service = client.GetService('CampaignService', version='v201802') + ad_group_service = client.GetService('AdGroupService', version='v201802') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + ad_group = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': ad_group + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': ad_group_id, + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201802') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + }, + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 500000 + } + }] + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py new file mode 100755 index 00000000..dd7cf540 --- /dev/null +++ b/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py @@ -0,0 +1,402 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds a Shopping campaign for Showcase ads. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import uuid + +from googleads import adwords +from suds import WebFault + + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' +EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' +COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + # Note: Showcase ads require either ManualCpc or EnhancedCpc in the + # campaign's BiddingStrategyConfiguration. + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, budget_id, merchant_id, expanded_image_filepath, + collapsed_image_filepath): + try: + # Create the Shopping Campaign + campaign = CreateShoppingCampaign(client, budget_id, merchant_id) + + # Create the AdGroup + adgroup = CreateAdGroup(client, campaign['id']) + + # Create a Showcase Ad + CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath) + + product_partition_tree = CreateProductPartition(client, adgroup['id']) + print 'Final tree:\n%s' % product_partition_tree + except WebFault: + print 'Failed to create shopping campaign for showcase ads.' + raise + + +def CreateShoppingCampaign(client, budget_id, merchant_id): + """Creates a shopping campaign with the given budget and merchant IDs. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + shopping campaign. + + Returns: + The created Shopping Campaign as a sudsobject. + """ + campaign_service = client.GetService('CampaignService', 'v201802') + + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + campaign = campaign_service.mutate(campaign_operations)['value'][0] + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + return campaign + + +def CreateAdGroup(client, campaign_id): + """Creates an AdGroup for the given shopping campaign ID. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a shopping campaign. + + Returns: + The created AdGroup as a sudsobject. + """ + ad_group_service = client.GetService('AdGroupService', 'v201802') + + adgroup = { + # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS + 'adGroupType': 'SHOPPING_SHOWCASE_ADS', + 'campaignId': campaign_id, + 'name': 'AdGroup #%s' % uuid.uuid4(), + # REQUIRED: Set the ad group's bidding strategy configuration. + 'biddingStrategyConfiguration': { + # Showcase ads require either ManualCpc or EnhancedCpc. + 'biddingStrategyType': 'MANUAL_CPC', + # Optional: Set the bids + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 100000 + } + }] + } + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) + + return adgroup + + +def CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath): + """Creates a showcase add for the given AdGroup with the given images. + + Args: + client: an AdWordsClient instance. + adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + expanded_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's expandedImage. + collapsed_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's collapsedImage. + + Returns: + The created Showcase Ad as a sudsobject. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') + + showcase_ad = { + 'adGroupId': adgroup['id'], + 'ad': { + 'xsi_type': 'ShowcaseAd', + 'Ad.Type': 'ShowcaseAd', + # Required: set the ad's name, final URLs, and display URL. + 'name': 'Showcase ad #%s' % uuid.uuid4(), + 'finalUrls': 'http://example.com/showcase', + 'displayUrl': 'example.com', + # Required: Set the ad's expanded image. + 'expandedImage': { + 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] + }, + # Optional: Set the collapsed image. + 'collapsedImage': { + 'mediaId': + UploadImage(client, collapsed_image_filepath)['mediaId'] + } + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': showcase_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] + + print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + + return showcase_ad + + +def UploadImage(client, filepath): + """Uploads a .jpg image with the given filepath via the AdWords MediaService. + + Args: + client: an AdWordsClient instance. + filepath: a str filepath to the .jpg file to be uploaded. + + Returns: + The created Image as a sudsobject. + """ + media_service = client.GetService('MediaService', 'v201802') + + with open(filepath, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + image = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + + image = media_service.upload(image)[0] + + return image + + +def CreateProductPartition(client, adgroup_id): + """Creates a ProductPartition tree for the given AdGroup ID. + + Args: + client: an AdWordsClient instance. + adgroup_id: a str AdGroup ID. + + Returns: + The ProductPartition tree as a sudsobject. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + 'v201802') + helper = ProductPartitionHelper(adgroup_id) + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition) + helper.CreateUnit(root, used_product_canonical_condition) + helper.CreateUnit(root, other_product_canonical_condition) + + result = ad_group_criterion_service.mutate(helper.operations) + return result['value'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, + COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201802/shopping/get_product_category_taxonomy.py b/examples/adwords/v201802/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..59b8a20c --- /dev/null +++ b/examples/adwords/v201802/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201802') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/targeting/__init__.py b/examples/adwords/v201802/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201802/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..ca6bc2fd --- /dev/null +++ b/examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201802') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201802/targeting/add_customer_negative_criteria.py b/examples/adwords/v201802/targeting/add_customer_negative_criteria.py new file mode 100755 index 00000000..772ebeb1 --- /dev/null +++ b/examples/adwords/v201802/targeting/add_customer_negative_criteria.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds various types of negative criteria to a customer. + +These criteria will be applied to all campaigns for the customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_negative_criterion_service = client.GetService( + 'CustomerNegativeCriterionService', version='v201802') + + criteria = [ + # Exclude tragedy & conflict content. + { + 'xsi_type': 'ContentLabel', + 'contentLabelType': 'TRAGEDY' + }, + # Exclude a specific placement. + { + 'xsi_type': 'Placement', + 'url': 'http://www.example.com' + } + # Additional criteria types are available for this service. See the types + # listed under Criterion here: + # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion + ] + + # Create operations to add each of the criteria above. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'criterion': criterion + } + } for criterion in criteria] + + # Make the mutate request. + result = customer_negative_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for negative_criterion in result['value']: + print ('Customer negative criterion with criterion ID "%s", and type "%s" ' + 'was added.' % (negative_criterion['criterion']['id'], + negative_criterion['criterion']['type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..c53b5d3b --- /dev/null +++ b/examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201802') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type "%s" was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..ec37619b --- /dev/null +++ b/examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201802') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..a14ac2df --- /dev/null +++ b/examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201802') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name "%s" and ID "%s" was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name "%s", ID "%s", and country code "%s" was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201802/targeting/lookup_location.py b/examples/adwords/v201802/targeting/lookup_location.py new file mode 100755 index 00000000..ad885dd4 --- /dev/null +++ b/examples/adwords/v201802/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201802') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py index c9f9354a..3553cb4e 100755 --- a/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py @@ -47,48 +47,31 @@ def main(client, custom_field_id, drop_down_custom_field_id, line_item_service = client.GetService('LineItemService', version='v201802') # Create statement to get a custom field. - custom_field_values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - custom_field_query = 'WHERE id = :customFieldId' - custom_field_statement = dfp.FilterStatement( - custom_field_query, custom_field_values, 1) + custom_field_statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', custom_field_id) + .Limit(1)) # Get custom field. custom_field = custom_field_service.getCustomFieldsByStatement( custom_field_statement.ToStatement())['results'][0] # Create statement to get a drop down custom field. - drop_down_custom_field_values = [{ - 'key': 'dropDownCustomFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': drop_down_custom_field_id - } - }] - drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId' - drop_down_custom_field_statement = dfp.FilterStatement( - drop_down_custom_field_query, drop_down_custom_field_values, 1) + drop_down_custom_field_statement = ( + dfp.StatementBuilder() + .Where('id = :dropDownCustomFieldId') + .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) + .Limit(1)) # Get drop-down custom field. drop_down_custom_field = custom_field_service.getCustomFieldsByStatement( drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - line_item_query = 'WHERE id = :lineItemId' - line_item_statement = dfp.FilterStatement( - line_item_query, line_item_values, 1) + line_item_statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', line_item_id) + .Limit(1)) # Get line item. line_item = line_item_service.getLineItemsByStatement( diff --git a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py index 2f325004..d90b4079 100755 --- a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py @@ -51,8 +51,8 @@ def main(client, key_name): if 'results' in response: key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) - key_statement = dfp.FilterStatement(key_query) + key_statement = (dfp.StatementBuilder() + .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. result = custom_targeting_service.performCustomTargetingKeyAction( @@ -60,7 +60,7 @@ def main(client, key_name): if result and int(result['numChanges']) > 0: deleted_custom_targeting_keys += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py index 86c0d4e1..2a46afba 100755 --- a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py @@ -38,15 +38,9 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201802') - filter_values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, filter_values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', key_id)) deleted_custom_targeting_values = 0 @@ -57,16 +51,17 @@ def main(client, key_id): if 'results' in response: value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_query = ('WHERE customTargetingKeyId = :keyId ' - 'AND id IN (%s)' % ', '.join(value_ids)) - value_statement = dfp.FilterStatement(value_query, filter_values) + value_statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId ' + 'AND id IN (%s)' % ', '.join(value_ids)) + .WithBindVariable('keyId', key_id)) # Delete custom targeting values. result = custom_targeting_service.performCustomTargetingValueAction( action, value_statement.ToStatement()) if result and int(result['numChanges']) > 0: deleted_custom_targeting_values += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index b445ccdc..8b378fca 100755 --- a/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -42,9 +42,9 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys]))) # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. @@ -59,7 +59,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py index 999c3c7a..4858e6fc 100755 --- a/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py @@ -26,7 +26,7 @@ def main(client): 'InventoryService', version='v201802') # Create a statement to select ad unit sizes. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py index e1333c59..b850097f 100755 --- a/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -31,18 +31,10 @@ def main(client): suggested_ad_unit_service = client.GetService( 'SuggestedAdUnitService', version='v201802') - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': THRESHOLD_NUMBER_OF_REQUESTS - } - }] - - query = 'WHERE numRequests > :numRequests' - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests > :numRequests') + .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 # Get suggested ad units by statement. diff --git a/googleads/adwords.py b/googleads/adwords.py index 04d7169d..caf15a07 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -191,6 +191,58 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201802': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdwordsUserListService': 'rm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignBidModifierService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignGroupPerformanceTargetService': 'cm', + 'CampaignGroupService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerNegativeCriterionService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'FeedItemService': 'cm', + 'FeedItemTargetService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineCallConversionFeedService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'OfflineDataUploadService': 'rm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } @@ -698,6 +750,8 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): 'CustomerExtensionSettingService', 'mutate'), 'FeedItemOperation': _OPERATION('FeedItemOperation', 'FeedItemService', 'mutate'), + 'FeedItemTargetOperation': _OPERATION( + 'FeedItemTargetOperation', 'FeedItemTargetService', 'mutate'), 'SharedCriterionOperation': _OPERATION( 'SharedCriterionOperation', 'SharedCriterionService', 'mutate'), 'SharedSetOperation': _OPERATION('SharedSetOperation', diff --git a/googleads/common.py b/googleads/common.py index b8c50a8e..f2b38495 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -62,7 +62,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '10.0.0' +VERSION = '10.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' @@ -629,6 +629,18 @@ def _InitSSLContext(self, cafile=None, return ssl_context + def BuildOpener(self): + """Builds an OpenerDirector instance using the ProxyConfig settings. + + In Python 2, this will return a urllib2.OpenerDirector instance. In Python + 3, this will return a urllib.request.OpenerDirector instance. + + Returns: + An OpenerDirector instance instantiated with settings defined in the + ProxyConfig instance. + """ + return urllib2.build_opener(*self.GetHandlers()) + def GetHandlers(self): """Retrieve the appropriate urllib2 handlers for the given configuration. diff --git a/tests/common_test.py b/tests/common_test.py index ade2282d..f069e569 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -1044,6 +1044,32 @@ def setUp(self): self.proxy_host2, self.proxy_port2, username=self.username, password=self.password) + def testBuildOpenerWithConfig(self): + https_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, + self.proxy_port1) + proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) + + with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mck_build_opener: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as mck_https_hndlr: + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as mck_prxy_hndlr: + mck_https_hndlr_instance = mock.Mock() + mck_https_hndlr.return_value = mck_https_hndlr_instance + mck_prxy_hndlr_instance = mock.Mock() + mck_prxy_hndlr.return_value = mck_prxy_hndlr_instance + proxy_config.BuildOpener() + mck_build_opener.assert_called_once_with( + *[mck_https_hndlr_instance, mck_prxy_hndlr_instance]) + + def testBuildOpenerWithDefaultConfig(self): + proxy_config = googleads.common.ProxyConfig() + + with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mck_build_opener: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as mock_https_hndlr: + mock_https_hndlr_instance = mock.Mock + mock_https_hndlr.return_value = mock_https_hndlr_instance + proxy_config.BuildOpener() + mck_build_opener.assert_called_once_with(*[mock_https_hndlr_instance]) + def testProxyToStringWithCredentials(self): proxy = googleads.common.ProxyConfig.Proxy( self.proxy_host1, self.proxy_port1, username=self.username, From 52190c6597398b90468e82b71a0a937699096aa3 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 1 Mar 2018 16:54:34 -0500 Subject: [PATCH 102/180] Commiting latest changes. From 704abd775266053add0b295eb86906f18c94d1aa Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Thu, 15 Mar 2018 15:58:28 -0400 Subject: [PATCH 103/180] Updating PR. --- ChangeLog | 40 + .../adwords/adwords_appengine_demo/README.md | 50 +- .../appengine_config.py | 18 +- .../adwords_appengine_demo/requirements.txt | 2 +- .../add_responsive_display_ad.py | 91 -- .../get_all_disapproved_ads.py | 74 -- .../get_all_disapproved_ads_with_awql.py | 63 -- .../handle_policy_violation_error.py | 117 --- .../add_responsive_display_ad.py | 91 -- .../get_all_disapproved_ads.py | 74 -- .../get_all_disapproved_ads_with_awql.py | 63 -- .../add_click_to_download_ad.py | 4 +- .../advanced_operations/add_html5_ad.py | 3 +- .../add_responsive_display_ad.py | 4 +- .../v201705/basic_operations/get_campaigns.py | 2 - .../get_campaigns_with_awql.py | 2 - ...dd_keywords_using_incremental_batch_job.py | 5 +- .../get_campaigns_by_label.py | 2 - .../v201705/misc/upload_media_bundle.py | 3 +- .../shopping/add_product_partition_tree.py | 24 +- .../add_shopping_campaign_for_showcase_ads.py | 24 +- .../advanced_operations/add_ad_customizer.py | 8 +- .../add_click_to_download_ad.py | 4 +- .../advanced_operations/add_html5_ad.py | 3 +- .../add_responsive_display_ad.py | 3 +- .../add_universal_app_campaign.py | 2 +- .../v201708/basic_operations/get_campaigns.py | 2 - .../get_campaigns_with_awql.py | 2 - ...dd_keywords_using_incremental_batch_job.py | 5 +- .../get_campaigns_by_label.py | 2 - .../v201708/misc/upload_media_bundle.py | 3 +- .../v201708/optimization/get_keyword_ideas.py | 83 +- .../remarketing/upload_offline_data.py | 199 +++++ ...oad_criteria_report_as_stream_with_awql.py | 13 +- ...oad_criteria_report_as_string_with_awql.py | 13 +- .../download_criteria_report_with_awql.py | 13 +- .../shopping/add_product_partition_tree.py | 25 +- .../add_shopping_campaign_for_showcase_ads.py | 24 +- .../adwords/{v201609 => v201710}/__init__.py | 0 .../account_management/__init__.py | 0 .../account_management/accept_service_link.py | 2 +- .../account_management/create_account.py | 2 +- .../account_management/get_account_changes.py | 4 +- .../get_account_hierarchy.py | 2 +- .../advanced_operations/__init__.py | 0 .../advanced_operations/add_ad_customizer.py | 14 +- .../add_ad_group_bid_modifier.py | 2 +- .../add_click_to_download_ad.py | 6 +- .../add_dynamic_page_feed.py | 295 +++++++ .../add_dynamic_search_ads_campaign.py | 257 ++++++ ...add_expanded_text_ad_with_upgraded_urls.py | 44 +- .../advanced_operations/add_html5_ad.py | 5 +- .../add_responsive_display_ad.py | 159 ++++ .../add_universal_app_campaign.py | 6 +- .../create_and_attach_shared_keyword_set.py | 6 +- ...ind_and_remove_criteria_from_shared_set.py | 4 +- .../get_ad_group_bid_modifier.py | 2 +- .../use_shared_bidding_strategy.py | 6 +- .../basic_operations/__init__.py | 0 .../basic_operations/add_ad_groups.py | 2 +- .../basic_operations/add_campaigns.py | 5 +- .../basic_operations/add_expanded_text_ads.py | 2 +- .../basic_operations/add_keywords.py | 2 +- .../basic_operations/get_ad_groups.py | 2 +- .../basic_operations/get_campaigns.py | 4 +- .../get_campaigns_with_awql.py | 21 +- .../basic_operations/get_expanded_text_ads.py | 2 +- .../basic_operations/get_keywords.py | 2 +- .../basic_operations/pause_ad.py | 2 +- .../basic_operations/remove_ad.py | 4 +- .../basic_operations/remove_ad_group.py | 2 +- .../basic_operations/remove_campaign.py | 2 +- .../basic_operations/remove_keyword.py | 2 +- .../basic_operations/update_ad_group.py | 39 +- .../basic_operations/update_campaign.py | 2 +- .../basic_operations/update_keyword.py | 2 +- .../campaign_management/__init__.py | 0 ...campaign_groups_and_performance_targets.py | 152 ++++ .../add_campaign_labels.py | 2 +- .../add_complete_campaigns_using_batch_job.py | 10 +- .../campaign_management/add_draft.py | 4 +- ...dd_keywords_using_incremental_batch_job.py | 22 +- .../campaign_management/add_trial.py | 4 +- .../get_all_disapproved_ads.py} | 47 +- .../get_all_disapproved_ads_with_awql.py | 88 ++ .../get_campaigns_by_label.py | 4 +- .../campaign_management/graduate_trial.py | 4 +- .../campaign_management/set_ad_parameters.py | 4 +- .../set_criterion_bid_modifier.py | 2 +- .../campaign_management/validate_text_ad.py | 2 +- .../error_handling/__init__.py | 0 .../error_handling/handle_partial_failures.py | 4 +- .../handle_policy_violation_error.py | 2 +- .../extensions/__init__.py | 0 ..._google_my_business_location_extensions.py | 4 +- .../extensions/add_prices.py | 4 +- .../extensions/add_site_links.py | 4 +- .../extensions/add_site_links_using_feeds.py | 8 +- .../migration/__init__.py | 0 .../migrate_to_extension_settings.py | 15 +- .../{v201609 => v201710}/misc/__init__.py | 0 .../misc/get_all_images_and_videos.py | 2 +- .../{v201609 => v201710}/misc/upload_image.py | 2 +- .../misc/upload_media_bundle.py | 5 +- .../optimization/__init__.py | 0 .../optimization/estimate_keyword_traffic.py | 2 +- ...aign_criterion_bid_modifier_simulations.py | 9 +- .../get_keyword_bid_simulations.py | 48 +- .../optimization/get_keyword_ideas.py | 85 +- .../remarketing/__init__.py | 0 .../remarketing/add_audience.py | 4 +- .../remarketing/add_conversion_tracker.py | 2 +- .../remarketing/add_conversion_trackers.py | 103 +++ .../remarketing/add_crm_based_user_list.py | 41 +- .../remarketing/add_rule_based_user_lists.py | 59 +- .../upload_offline_call_conversions.py | 4 +- .../remarketing/upload_offline_conversions.py | 13 +- .../remarketing/upload_offline_data.py | 218 +++++ .../reporting/__init__.py | 0 ...oad_criteria_report_as_stream_with_awql.py | 15 +- ...riteria_report_as_stream_with_selector.py} | 2 +- ...oad_criteria_report_as_string_with_awql.py | 15 +- ...riteria_report_as_string_with_selector.py} | 2 +- .../download_criteria_report_with_awql.py | 39 +- ...download_criteria_report_with_selector.py} | 3 +- .../reporting/get_report_fields.py | 2 +- .../reporting/parallel_report_download.py | 4 +- .../{v201609 => v201710}/shopping/__init__.py | 0 .../shopping/add_product_partition_tree.py | 26 +- .../shopping/add_product_scope.py | 2 +- .../shopping/add_shopping_campaign.py | 71 +- .../add_shopping_campaign_for_showcase_ads.py | 36 +- .../shopping/get_product_category_taxonomy.py | 2 +- .../targeting/__init__.py | 0 .../add_campaign_targeting_criteria.py | 2 +- .../add_customer_negative_criteria.py | 74 ++ .../add_demographic_targeting_criteria.py | 2 +- .../get_campaign_targeting_criteria.py | 2 +- .../get_targetable_languages_and_carriers.py | 2 +- .../targeting/lookup_location.py | 2 +- .../adwords/{v201702 => v201802}/__init__.py | 0 .../account_management/__init__.py | 0 .../account_management/accept_service_link.py | 2 +- .../account_management/create_account.py | 10 +- .../account_management/get_account_changes.py | 4 +- .../get_account_hierarchy.py | 2 +- .../advanced_operations/__init__.py | 0 .../advanced_operations/add_ad_customizer.py | 14 +- .../add_ad_group_bid_modifier.py | 2 +- .../add_click_to_download_ad.py | 6 +- .../add_dynamic_page_feed.py | 295 +++++++ .../add_dynamic_search_ads_campaign.py | 257 ++++++ ...add_expanded_text_ad_with_upgraded_urls.py | 44 +- .../advanced_operations/add_gmail_ad.py | 117 +++ .../advanced_operations/add_html5_ad.py | 5 +- .../add_responsive_display_ad.py | 159 ++++ ...d_shopping_dynamic_remarketing_campaign.py | 305 +++++++ .../add_universal_app_campaign.py | 24 +- .../create_and_attach_shared_keyword_set.py | 6 +- ...ind_and_remove_criteria_from_shared_set.py | 4 +- .../get_ad_group_bid_modifier.py | 2 +- .../use_shared_bidding_strategy.py | 6 +- .../basic_operations/__init__.py | 0 .../basic_operations/add_ad_groups.py | 2 +- .../basic_operations/add_campaigns.py | 5 +- .../basic_operations/add_expanded_text_ads.py | 2 +- .../basic_operations/add_keywords.py | 2 +- .../basic_operations/get_ad_groups.py | 2 +- .../basic_operations/get_campaigns.py | 4 +- .../get_campaigns_with_awql.py | 21 +- .../basic_operations/get_expanded_text_ads.py | 2 +- .../basic_operations/get_keywords.py | 2 +- .../basic_operations/pause_ad.py | 2 +- .../basic_operations/remove_ad.py | 4 +- .../basic_operations/remove_ad_group.py | 2 +- .../basic_operations/remove_campaign.py | 2 +- .../basic_operations/remove_keyword.py | 2 +- .../basic_operations/update_ad_group.py | 39 +- .../basic_operations/update_campaign.py | 2 +- .../basic_operations/update_keyword.py | 2 +- .../campaign_management/__init__.py | 0 ...campaign_groups_and_performance_targets.py | 152 ++++ .../add_campaign_labels.py | 2 +- .../add_complete_campaigns_using_batch_job.py | 10 +- .../campaign_management/add_draft.py | 4 +- ...dd_keywords_using_incremental_batch_job.py | 22 +- .../campaign_management/add_trial.py | 4 +- .../get_all_disapproved_ads.py} | 47 +- .../get_all_disapproved_ads_with_awql.py | 88 ++ .../get_campaigns_by_label.py | 4 +- .../campaign_management/graduate_trial.py | 4 +- .../campaign_management/set_ad_parameters.py | 4 +- .../set_criterion_bid_modifier.py | 2 +- .../campaign_management/validate_text_ad.py | 2 +- .../error_handling/__init__.py | 0 .../error_handling/handle_partial_failures.py | 31 +- .../handle_policy_violation_error.py | 167 ++++ .../extensions/__init__.py | 0 ..._google_my_business_location_extensions.py | 4 +- .../extensions/add_prices.py | 25 +- .../extensions/add_site_links.py | 4 +- .../extensions/add_site_links_using_feeds.py | 8 +- .../migration/__init__.py | 0 .../migrate_to_extension_settings.py | 17 +- .../{v201702 => v201802}/misc/__init__.py | 0 .../misc/get_all_images_and_videos.py | 2 +- .../{v201702 => v201802}/misc/upload_image.py | 2 +- .../misc/upload_media_bundle.py | 5 +- .../optimization/__init__.py | 0 .../optimization/estimate_keyword_traffic.py | 2 +- ...aign_criterion_bid_modifier_simulations.py | 9 +- .../get_keyword_bid_simulations.py | 57 +- .../optimization/get_keyword_ideas.py | 85 +- .../remarketing/__init__.py | 0 .../remarketing/add_audience.py | 53 +- .../remarketing/add_conversion_tracker.py | 2 +- .../remarketing/add_conversion_trackers.py | 101 +++ .../remarketing/add_crm_based_user_list.py | 48 +- .../remarketing/add_rule_based_user_lists.py | 64 +- .../upload_offline_call_conversions.py | 4 +- .../remarketing/upload_offline_conversions.py | 13 +- .../remarketing/upload_offline_data.py | 259 ++++++ .../reporting/__init__.py | 0 ...oad_criteria_report_as_stream_with_awql.py | 15 +- ...criteria_report_as_stream_with_selector.py | 2 +- ...oad_criteria_report_as_string_with_awql.py | 15 +- ...criteria_report_as_string_with_selector.py | 2 +- .../download_criteria_report_with_awql.py | 39 +- .../download_criteria_report_with_selector.py | 3 +- .../reporting/get_report_fields.py | 2 +- .../reporting/parallel_report_download.py | 4 +- .../{v201702 => v201802}/shopping/__init__.py | 0 .../shopping/add_product_partition_tree.py | 26 +- .../shopping/add_product_scope.py | 2 +- .../shopping/add_shopping_campaign.py | 71 +- .../add_shopping_campaign_for_showcase_ads.py | 402 +++++++++ .../shopping/get_product_category_taxonomy.py | 2 +- .../targeting/__init__.py | 0 .../add_campaign_targeting_criteria.py | 23 +- .../add_customer_negative_criteria.py | 74 ++ .../add_demographic_targeting_criteria.py | 2 +- .../get_campaign_targeting_criteria.py | 2 +- .../get_targetable_languages_and_carriers.py | 2 +- .../targeting/lookup_location.py | 2 +- ...matic_products_for_non_sales_management.py | 84 -- ...sh_programmatic_products_to_marketplace.py | 74 -- ...matic_products_for_non_sales_management.py | 84 -- ...sh_programmatic_products_to_marketplace.py | 74 -- .../get_active_activity_groups.py | 12 +- .../update_activity_groups.py | 16 +- .../activity_service/get_active_activities.py | 12 +- .../activity_service/update_activities.py | 14 +- .../get_first_party_audience_segments.py | 12 +- .../populate_first_party_audience_segments.py | 21 +- .../update_audience_segments.py | 21 +- .../get_base_rates_for_rate_card.py | 12 +- .../base_rate_service/update_base_rates.py | 14 +- .../company_service/get_advertisers.py | 12 +- .../company_service/update_companies.py | 16 +- .../contact_service/get_uninvited_contacts.py | 12 +- .../contact_service/update_contacts.py | 14 +- ...delete_content_metadata_key_hierarchies.py | 15 +- ...update_content_metadata_key_hierarchies.py | 15 +- .../create_native_creative.py | 6 +- .../creative_service/get_image_creatives.py | 12 +- .../creative_service/update_creatives.py | 21 +- .../get_creative_sets_for_master_creative.py | 12 +- .../update_creative_set.py | 13 +- .../get_system_defined_creative_templates.py | 12 +- .../deactivate_creative_wrapper.py | 20 +- .../get_active_creative_wrappers.py | 12 +- .../update_creative_wrappers.py | 14 +- .../deactivate_all_line_item_custom_fields.py | 22 +- .../get_custom_fields_for_line_items.py | 12 +- .../update_custom_fields.py | 13 +- .../delete_custom_targeting_keys.py | 13 +- ...efined_custom_targeting_keys_and_values.py | 22 +- .../update_custom_targeting_keys.py | 14 +- .../update_custom_targeting_values.py | 13 +- .../get_exchange_rates_for_currency_code.py | 12 +- .../update_exchange_rates.py | 14 +- .../get_availability_forecast.py | 16 +- ...get_availability_forecast_for_line_item.py | 16 +- .../inventory_service/archive_ad_units.py | 13 +- .../inventory_service/update_ad_units.py | 13 +- .../label_service/deactivate_labels.py | 13 +- .../label_service/get_active_labels.py | 12 +- .../v201708/label_service/update_labels.py | 15 +- .../deactivate_licas.py | 20 +- .../get_licas_for_line_item.py | 12 +- .../line_item_service/activate_line_items.py | 20 +- .../get_line_items_that_need_creatives.py | 12 +- .../get_recently_updated_line_items.py | 18 +- .../target_custom_criteria.py | 14 +- .../line_item_service/update_line_items.py | 22 +- .../v201708/order_service/approve_orders.py | 17 +- .../order_service/get_orders_starting_soon.py | 31 +- .../v201708/order_service/update_orders.py | 13 +- .../get_in_progress_packages.py | 12 +- .../deactivate_placements.py | 14 +- .../get_active_placements.py | 12 +- .../get_premium_rates_for_rate_card.py | 12 +- .../update_premium_rates.py | 14 +- ...oduct_package_items_for_product_package.py | 12 +- .../get_active_product_packages.py | 12 +- ...matic_products_for_non_sales_management.py | 84 -- .../get_products_for_product_template.py | 12 +- ...sh_programmatic_products_to_marketplace.py | 74 -- .../product_service/update_products.py | 14 +- .../activate_product_templates.py | 13 +- .../get_sponsorship_product_templates.py | 12 +- .../update_product_templates.py | 14 +- .../archive_proposal_line_items.py | 13 +- .../get_proposal_line_items_for_proposal.py | 12 +- .../update_proposal_line_items.py | 13 +- .../get_proposals_pending_approval.py | 12 +- .../request_buyers_acceptance.py | 15 +- .../submit_proposals_for_approval.py | 15 +- .../proposal_service/update_proposals.py | 14 +- .../get_recent_changes.py | 92 +- .../get_marketplace_rate_cards.py | 12 +- ...order_reports_for_reconciliation_report.py | 13 +- ...n_report_rows_for_reconciliation_report.py | 16 +- .../report_service/run_delivery_report.py | 16 +- .../report_service/run_inventory_report.py | 18 +- .../run_report_and_create_match_table.py | 88 ++ .../run_report_with_custom_fields.py | 22 +- .../v201708/report_service/run_saved_query.py | 13 +- ...get_highly_requested_suggested_ad_units.py | 12 +- .../dfp/v201708/team_service/update_teams.py | 13 +- .../v201708/user_service/deactivate_users.py | 15 +- .../user_service/get_user_by_email_address.py | 12 +- .../dfp/v201708/user_service/update_users.py | 15 +- .../delete_user_team_associations.py | 21 +- .../get_user_team_associations_for_user.py | 12 +- .../update_user_team_associations.py | 15 +- .../approve_workflow_approval_requests.py | 34 +- .../get_workflow_approval_requests.py | 12 +- ...et_workflow_external_condition_requests.py | 12 +- ...er_workflow_external_condition_requests.py | 34 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 14 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 18 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 14 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 16 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 14 +- .../populate_first_party_audience_segments.py | 23 +- .../update_audience_segments.py | 23 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_package_item_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 14 +- .../base_rate_service/update_base_rates.py | 16 +- .../cdn_configuration_service}/__init__.py | 0 .../create_cdn_configurations.py | 89 ++ .../get_all_cdn_configurations.py | 54 ++ .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 14 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 18 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 14 +- .../contact_service/update_contacts.py | 16 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 17 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 17 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 14 +- .../creative_service/update_creatives.py | 23 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 14 +- .../update_creative_set.py | 15 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 14 +- .../create_creative_wrappers.py | 6 +- .../deactivate_creative_wrapper.py | 22 +- .../get_active_creative_wrappers.py | 14 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 16 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 24 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 14 +- .../set_line_item_custom_field_value.py | 4 +- .../update_custom_fields.py | 15 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 17 +- .../delete_custom_targeting_values.py | 2 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- ...efined_custom_targeting_keys_and_values.py | 26 +- .../update_custom_targeting_keys.py | 16 +- .../update_custom_targeting_values.py | 15 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 14 +- .../update_exchange_rates.py | 16 +- .../get_availability_forecast.py | 20 +- ...get_availability_forecast_for_line_item.py | 18 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 15 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 115 +++ .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 58 ++ .../inventory_service/update_ad_units.py | 15 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 15 +- .../label_service/get_active_labels.py | 14 +- .../label_service/get_all_labels.py | 2 +- .../label_service/update_labels.py | 17 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 22 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 14 +- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 22 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 14 +- .../get_recently_updated_line_items.py | 20 +- .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 16 +- .../line_item_service/update_line_items.py | 24 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 2 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 37 + .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 19 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 33 +- .../order_service/update_orders.py | 15 +- .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 14 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 16 +- .../get_active_placements.py | 14 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 4 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 14 +- .../update_premium_rates.py | 16 +- .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 14 +- .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 14 +- .../get_all_product_packages.py | 2 +- .../product_service/__init__.py | 0 .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 16 +- .../product_service/update_products.py | 16 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 15 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 14 +- .../update_product_templates.py | 16 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 15 +- ...create_programmatic_proposal_line_items.py | 4 +- ...sal_line_items_for_non_sales_management.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 14 +- .../update_proposal_line_items.py | 15 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 14 +- .../request_buyers_acceptance.py | 17 +- .../submit_proposals_for_approval.py | 17 +- .../proposal_service/update_proposals.py | 16 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 55 ++ .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 53 ++ .../get_line_items_named_like.py | 48 ++ .../get_recent_changes.py | 94 +-- .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 14 +- ..._item_reports_for_reconciliation_report.py | 2 +- ...update_reconciliation_line_item_reports.py | 2 +- ...order_reports_for_reconciliation_report.py | 15 +- .../submit_reconciliation_order_reports.py | 2 +- ...n_report_rows_for_reconciliation_report.py | 18 +- .../update_reconciliation_report_rows.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 2 +- .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 18 +- .../report_service/run_inventory_report.py | 22 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 88 ++ .../run_report_with_custom_fields.py | 26 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 17 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 14 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 2 +- .../team_service/update_teams.py | 15 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 17 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 2 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 14 +- .../user_service/update_users.py | 17 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 23 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 14 +- .../update_user_team_associations.py | 17 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 36 +- .../get_workflow_approval_requests.py | 14 +- ...et_workflow_external_condition_requests.py | 14 +- ...er_workflow_external_condition_requests.py | 36 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 14 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 18 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 14 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 16 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 14 +- .../populate_first_party_audience_segments.py | 23 +- .../update_audience_segments.py | 23 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 6 +- .../create_product_package_item_base_rates.py | 6 +- .../create_product_template_base_rates.py | 6 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 14 +- .../base_rate_service/update_base_rates.py | 16 +- .../cdn_configuration_service/__init__.py | 15 + .../create_cdn_configurations.py | 89 ++ .../get_all_cdn_configurations.py | 54 ++ .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 14 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 18 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 14 +- .../contact_service/update_contacts.py | 16 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...delete_content_metadata_key_hierarchies.py | 17 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 17 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 14 +- .../creative_service/update_creatives.py | 23 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 14 +- .../update_creative_set.py | 15 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 14 +- .../create_creative_wrappers.py | 6 +- .../deactivate_creative_wrapper.py | 22 +- .../get_active_creative_wrappers.py | 14 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 16 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 24 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 14 +- .../set_line_item_custom_field_value.py | 47 +- .../update_custom_fields.py | 15 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 23 +- .../delete_custom_targeting_values.py | 23 +- ...et_all_custom_targeting_keys_and_values.py | 12 +- ...efined_custom_targeting_keys_and_values.py | 26 +- .../update_custom_targeting_keys.py | 16 +- .../update_custom_targeting_values.py | 15 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 14 +- .../update_exchange_rates.py | 16 +- .../get_availability_forecast.py | 20 +- ...get_availability_forecast_for_line_item.py | 17 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 15 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 115 +++ .../get_all_ad_unit_sizes.py | 6 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 58 ++ .../inventory_service/update_ad_units.py | 15 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 15 +- .../label_service/get_active_labels.py | 14 +- .../label_service/get_all_labels.py | 2 +- .../label_service/update_labels.py | 17 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 22 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 14 +- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 22 +- .../line_item_service/create_line_items.py | 20 +- .../create_video_line_item.py | 20 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 14 +- .../get_recently_updated_line_items.py | 20 +- .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 16 +- .../line_item_service/update_line_items.py | 24 +- .../v201802/native_style_service/__init__.py | 15 + .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 2 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 37 + .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 19 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 33 +- .../order_service/update_orders.py | 15 +- .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 14 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 16 +- .../get_active_placements.py | 14 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 40 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 7 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 14 +- .../update_premium_rates.py | 16 +- .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 14 +- .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 14 +- .../get_all_product_packages.py | 2 +- .../product_service/__init__.py | 0 .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 16 +- .../product_service/update_products.py | 16 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 15 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 14 +- .../update_product_templates.py | 16 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 15 +- ...create_programmatic_proposal_line_items.py | 33 +- ...sal_line_items_for_non_sales_management.py | 33 +- .../create_proposal_line_items.py | 33 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 14 +- .../update_proposal_line_items.py | 15 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 14 +- .../request_buyers_acceptance.py | 17 +- .../submit_proposals_for_approval.py | 17 +- .../proposal_service/update_proposals.py | 16 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 55 ++ .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 53 ++ .../get_line_items_named_like.py | 48 ++ .../get_recent_changes.py | 94 +-- .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 14 +- ..._item_reports_for_reconciliation_report.py | 2 +- ...update_reconciliation_line_item_reports.py | 2 +- ...order_reports_for_reconciliation_report.py | 15 +- .../submit_reconciliation_order_reports.py | 2 +- ...n_report_rows_for_reconciliation_report.py | 18 +- .../update_reconciliation_report_rows.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 14 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 66 ++ .../report_service/run_delivery_report.py | 18 +- .../report_service/run_inventory_report.py | 22 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 88 ++ .../run_report_with_custom_fields.py | 26 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 17 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 16 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 14 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 2 +- .../team_service/update_teams.py | 15 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 17 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 2 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 14 +- .../user_service/update_users.py | 17 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 23 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 14 +- .../update_user_team_associations.py | 17 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 36 +- .../get_workflow_approval_requests.py | 14 +- ...et_workflow_external_condition_requests.py | 14 +- ...er_workflow_external_condition_requests.py | 36 +- googleads/adwords.py | 797 +++++++++++++++++- googleads/common.py | 115 ++- googleads/dfp.py | 146 ++-- googleads/util.py | 7 +- setup.py | 12 +- tests/__init__.py | 0 tests/adwords_test.py | 757 ++++++++++++++--- tests/common_test.py | 308 ++++--- tests/dfp_test.py | 85 +- tests/oauth2_test.py | 89 +- tests/test_data/adwords_googleads.yaml | 5 + .../batch_job_util_budget_template.txt | 6 + ...h_job_util_campaign_criterion_template.txt | 7 + ...batch_job_util_campaign_label_template.txt | 2 + .../batch_job_util_invalid_request.txt | 9 + .../test_data/batch_job_util_not_request.txt | 1 + .../batch_job_util_operations_template.txt | 7 + .../batch_job_util_raw_request_template.txt | 17 + .../batch_job_util_response_template.txt | 1 + .../batch_job_util_upload_template.txt | 5 + .../compact_fault_response_envelope.txt | 8 + .../empty_fault_response_envelope.txt | 19 + tests/test_data/fault_response_envelope.txt | 25 + tests/test_data/gzip_response.bin | Bin 0 -> 394 bytes .../multi_errors_fault_response_envelope.txt | 31 + tests/test_data/request_envelope_template.txt | 27 + tests/test_data/test.crt | 18 + tests/testing.py | 32 + tests/util_test.py | 58 +- 842 files changed, 10572 insertions(+), 5936 deletions(-) delete mode 100755 examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201609/error_handling/handle_policy_violation_error.py delete mode 100755 examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201708/remarketing/upload_offline_data.py rename examples/adwords/{v201609 => v201710}/__init__.py (100%) rename examples/adwords/{v201609 => v201710}/account_management/__init__.py (100%) rename examples/adwords/{v201609 => v201710}/account_management/accept_service_link.py (97%) rename examples/adwords/{v201702 => v201710}/account_management/create_account.py (97%) rename examples/adwords/{v201609 => v201710}/account_management/get_account_changes.py (98%) rename examples/adwords/{v201702 => v201710}/account_management/get_account_hierarchy.py (98%) rename examples/adwords/{v201609 => v201710}/advanced_operations/__init__.py (100%) rename examples/adwords/{v201609 => v201710}/advanced_operations/add_ad_customizer.py (97%) rename examples/adwords/{v201609 => v201710}/advanced_operations/add_ad_group_bid_modifier.py (97%) rename examples/adwords/{v201702 => v201710}/advanced_operations/add_click_to_download_ad.py (95%) create mode 100755 examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py create mode 100755 examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py rename examples/adwords/{v201609 => v201710}/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py (78%) rename examples/adwords/{v201609 => v201710}/advanced_operations/add_html5_ad.py (95%) create mode 100755 examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py rename examples/adwords/{v201702 => v201710}/advanced_operations/add_universal_app_campaign.py (98%) rename examples/adwords/{v201702 => v201710}/advanced_operations/create_and_attach_shared_keyword_set.py (97%) rename examples/adwords/{v201702 => v201710}/advanced_operations/find_and_remove_criteria_from_shared_set.py (98%) rename examples/adwords/{v201702 => v201710}/advanced_operations/get_ad_group_bid_modifier.py (97%) rename examples/adwords/{v201702 => v201710}/advanced_operations/use_shared_bidding_strategy.py (98%) rename examples/adwords/{v201609 => v201710}/basic_operations/__init__.py (100%) rename examples/adwords/{v201609 => v201710}/basic_operations/add_ad_groups.py (99%) rename examples/adwords/{v201702 => v201710}/basic_operations/add_campaigns.py (98%) rename examples/adwords/{v201609 => v201710}/basic_operations/add_expanded_text_ads.py (99%) rename examples/adwords/{v201609 => v201710}/basic_operations/add_keywords.py (98%) rename examples/adwords/{v201609 => v201710}/basic_operations/get_ad_groups.py (99%) rename examples/adwords/{v201609 => v201710}/basic_operations/get_campaigns.py (97%) rename examples/adwords/{v201702 => v201710}/basic_operations/get_campaigns_with_awql.py (84%) rename examples/adwords/{v201702 => v201710}/basic_operations/get_expanded_text_ads.py (99%) rename examples/adwords/{v201702 => v201710}/basic_operations/get_keywords.py (98%) rename examples/adwords/{v201702 => v201710}/basic_operations/pause_ad.py (99%) rename examples/adwords/{v201702 => v201710}/basic_operations/remove_ad.py (96%) rename examples/adwords/{v201702 => v201710}/basic_operations/remove_ad_group.py (99%) rename examples/adwords/{v201702 => v201710}/basic_operations/remove_campaign.py (99%) rename examples/adwords/{v201702 => v201710}/basic_operations/remove_keyword.py (97%) rename examples/adwords/{v201702 => v201710}/basic_operations/update_ad_group.py (56%) rename examples/adwords/{v201609 => v201710}/basic_operations/update_campaign.py (99%) rename examples/adwords/{v201609 => v201710}/basic_operations/update_keyword.py (98%) rename examples/adwords/{v201609 => v201710}/campaign_management/__init__.py (100%) create mode 100755 examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py rename examples/adwords/{v201609 => v201710}/campaign_management/add_campaign_labels.py (99%) rename examples/adwords/{v201609 => v201710}/campaign_management/add_complete_campaigns_using_batch_job.py (98%) rename examples/adwords/{v201609 => v201710}/campaign_management/add_draft.py (97%) rename examples/adwords/{v201609 => v201710}/campaign_management/add_keywords_using_incremental_batch_job.py (94%) rename examples/adwords/{v201702 => v201710}/campaign_management/add_trial.py (98%) rename examples/adwords/{v201702/basic_operations/get_text_ads.py => v201710/campaign_management/get_all_disapproved_ads.py} (55%) create mode 100755 examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py rename examples/adwords/{v201609 => v201710}/campaign_management/get_campaigns_by_label.py (98%) rename examples/adwords/{v201702 => v201710}/campaign_management/graduate_trial.py (99%) rename examples/adwords/{v201702 => v201710}/campaign_management/set_ad_parameters.py (99%) rename examples/adwords/{v201702 => v201710}/campaign_management/set_criterion_bid_modifier.py (97%) rename examples/adwords/{v201702 => v201710}/campaign_management/validate_text_ad.py (99%) rename examples/adwords/{v201609 => v201710}/error_handling/__init__.py (100%) rename examples/adwords/{v201702 => v201710}/error_handling/handle_partial_failures.py (97%) rename examples/adwords/{v201702 => v201710}/error_handling/handle_policy_violation_error.py (99%) rename examples/adwords/{v201609 => v201710}/extensions/__init__.py (100%) rename examples/adwords/{v201702 => v201710}/extensions/add_google_my_business_location_extensions.py (98%) rename examples/adwords/{v201702 => v201710}/extensions/add_prices.py (97%) rename examples/adwords/{v201702 => v201710}/extensions/add_site_links.py (98%) rename examples/adwords/{v201702 => v201710}/extensions/add_site_links_using_feeds.py (98%) rename examples/adwords/{v201609 => v201710}/migration/__init__.py (100%) rename examples/adwords/{v201702 => v201710}/migration/migrate_to_extension_settings.py (98%) rename examples/adwords/{v201609 => v201710}/misc/__init__.py (100%) rename examples/adwords/{v201702 => v201710}/misc/get_all_images_and_videos.py (99%) rename examples/adwords/{v201609 => v201710}/misc/upload_image.py (99%) rename examples/adwords/{v201609 => v201710}/misc/upload_media_bundle.py (93%) rename examples/adwords/{v201609 => v201710}/optimization/__init__.py (100%) rename examples/adwords/{v201609 => v201710}/optimization/estimate_keyword_traffic.py (99%) rename examples/adwords/{v201702 => v201710}/optimization/get_campaign_criterion_bid_modifier_simulations.py (96%) rename examples/adwords/{v201702 => v201710}/optimization/get_keyword_bid_simulations.py (68%) rename examples/adwords/{v201609 => v201710}/optimization/get_keyword_ideas.py (56%) rename examples/adwords/{v201609 => v201710}/remarketing/__init__.py (100%) rename examples/adwords/{v201702 => v201710}/remarketing/add_audience.py (96%) rename examples/adwords/{v201609 => v201710}/remarketing/add_conversion_tracker.py (97%) create mode 100755 examples/adwords/v201710/remarketing/add_conversion_trackers.py rename examples/adwords/{v201609 => v201710}/remarketing/add_crm_based_user_list.py (72%) rename examples/adwords/{v201702 => v201710}/remarketing/add_rule_based_user_lists.py (75%) rename examples/adwords/{v201609 => v201710}/remarketing/upload_offline_call_conversions.py (95%) rename examples/adwords/{v201702 => v201710}/remarketing/upload_offline_conversions.py (79%) create mode 100755 examples/adwords/v201710/remarketing/upload_offline_data.py rename examples/adwords/{v201609 => v201710}/reporting/__init__.py (100%) rename examples/adwords/{v201609 => v201710}/reporting/download_criteria_report_as_stream_with_awql.py (82%) rename examples/adwords/{v201609/reporting/download_criteria_report_as_stream.py => v201710/reporting/download_criteria_report_as_stream_with_selector.py} (97%) rename examples/adwords/{v201609 => v201710}/reporting/download_criteria_report_as_string_with_awql.py (76%) rename examples/adwords/{v201609/reporting/download_criteria_report_as_string.py => v201710/reporting/download_criteria_report_as_string_with_selector.py} (96%) rename examples/adwords/{v201609 => v201710}/reporting/download_criteria_report_with_awql.py (57%) rename examples/adwords/{v201609/reporting/download_criteria_report.py => v201710/reporting/download_criteria_report_with_selector.py} (95%) rename examples/adwords/{v201702 => v201710}/reporting/get_report_fields.py (96%) rename examples/adwords/{v201609 => v201710}/reporting/parallel_report_download.py (99%) rename examples/adwords/{v201609 => v201710}/shopping/__init__.py (100%) rename examples/adwords/{v201702 => v201710}/shopping/add_product_partition_tree.py (91%) rename examples/adwords/{v201702 => v201710}/shopping/add_product_scope.py (98%) rename examples/adwords/{v201609 => v201710}/shopping/add_shopping_campaign.py (62%) rename examples/adwords/{v201702 => v201710}/shopping/add_shopping_campaign_for_showcase_ads.py (91%) rename examples/adwords/{v201702 => v201710}/shopping/get_product_category_taxonomy.py (99%) rename examples/adwords/{v201609 => v201710}/targeting/__init__.py (100%) rename examples/adwords/{v201702 => v201710}/targeting/add_campaign_targeting_criteria.py (98%) create mode 100755 examples/adwords/v201710/targeting/add_customer_negative_criteria.py rename examples/adwords/{v201609 => v201710}/targeting/add_demographic_targeting_criteria.py (98%) rename examples/adwords/{v201609 => v201710}/targeting/get_campaign_targeting_criteria.py (98%) rename examples/adwords/{v201609 => v201710}/targeting/get_targetable_languages_and_carriers.py (97%) rename examples/adwords/{v201609 => v201710}/targeting/lookup_location.py (98%) rename examples/adwords/{v201702 => v201802}/__init__.py (100%) rename examples/adwords/{v201702 => v201802}/account_management/__init__.py (100%) rename examples/adwords/{v201702 => v201802}/account_management/accept_service_link.py (97%) rename examples/adwords/{v201609 => v201802}/account_management/create_account.py (82%) rename examples/adwords/{v201702 => v201802}/account_management/get_account_changes.py (98%) rename examples/adwords/{v201609 => v201802}/account_management/get_account_hierarchy.py (98%) rename examples/adwords/{v201702 => v201802}/advanced_operations/__init__.py (100%) rename examples/adwords/{v201702 => v201802}/advanced_operations/add_ad_customizer.py (97%) rename examples/adwords/{v201702 => v201802}/advanced_operations/add_ad_group_bid_modifier.py (97%) rename examples/adwords/{v201609 => v201802}/advanced_operations/add_click_to_download_ad.py (95%) create mode 100755 examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py create mode 100755 examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py rename examples/adwords/{v201702 => v201802}/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py (78%) create mode 100755 examples/adwords/v201802/advanced_operations/add_gmail_ad.py rename examples/adwords/{v201702 => v201802}/advanced_operations/add_html5_ad.py (95%) create mode 100755 examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py rename examples/adwords/{v201609 => v201802}/advanced_operations/add_universal_app_campaign.py (93%) rename examples/adwords/{v201609 => v201802}/advanced_operations/create_and_attach_shared_keyword_set.py (96%) rename examples/adwords/{v201609 => v201802}/advanced_operations/find_and_remove_criteria_from_shared_set.py (97%) rename examples/adwords/{v201609 => v201802}/advanced_operations/get_ad_group_bid_modifier.py (97%) rename examples/adwords/{v201609 => v201802}/advanced_operations/use_shared_bidding_strategy.py (98%) rename examples/adwords/{v201702 => v201802}/basic_operations/__init__.py (100%) rename examples/adwords/{v201702 => v201802}/basic_operations/add_ad_groups.py (99%) rename examples/adwords/{v201609 => v201802}/basic_operations/add_campaigns.py (98%) rename examples/adwords/{v201702 => v201802}/basic_operations/add_expanded_text_ads.py (99%) rename examples/adwords/{v201702 => v201802}/basic_operations/add_keywords.py (98%) rename examples/adwords/{v201702 => v201802}/basic_operations/get_ad_groups.py (99%) rename examples/adwords/{v201702 => v201802}/basic_operations/get_campaigns.py (97%) rename examples/adwords/{v201609 => v201802}/basic_operations/get_campaigns_with_awql.py (84%) rename examples/adwords/{v201609 => v201802}/basic_operations/get_expanded_text_ads.py (99%) rename examples/adwords/{v201609 => v201802}/basic_operations/get_keywords.py (98%) rename examples/adwords/{v201609 => v201802}/basic_operations/pause_ad.py (99%) rename examples/adwords/{v201609 => v201802}/basic_operations/remove_ad.py (96%) rename examples/adwords/{v201609 => v201802}/basic_operations/remove_ad_group.py (99%) rename examples/adwords/{v201609 => v201802}/basic_operations/remove_campaign.py (99%) rename examples/adwords/{v201609 => v201802}/basic_operations/remove_keyword.py (97%) rename examples/adwords/{v201609 => v201802}/basic_operations/update_ad_group.py (56%) rename examples/adwords/{v201702 => v201802}/basic_operations/update_campaign.py (99%) rename examples/adwords/{v201702 => v201802}/basic_operations/update_keyword.py (98%) rename examples/adwords/{v201702 => v201802}/campaign_management/__init__.py (100%) create mode 100755 examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py rename examples/adwords/{v201702 => v201802}/campaign_management/add_campaign_labels.py (99%) rename examples/adwords/{v201702 => v201802}/campaign_management/add_complete_campaigns_using_batch_job.py (98%) rename examples/adwords/{v201702 => v201802}/campaign_management/add_draft.py (97%) rename examples/adwords/{v201702 => v201802}/campaign_management/add_keywords_using_incremental_batch_job.py (94%) rename examples/adwords/{v201609 => v201802}/campaign_management/add_trial.py (98%) rename examples/adwords/{v201609/basic_operations/get_text_ads.py => v201802/campaign_management/get_all_disapproved_ads.py} (55%) create mode 100755 examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py rename examples/adwords/{v201702 => v201802}/campaign_management/get_campaigns_by_label.py (98%) rename examples/adwords/{v201609 => v201802}/campaign_management/graduate_trial.py (99%) rename examples/adwords/{v201609 => v201802}/campaign_management/set_ad_parameters.py (99%) rename examples/adwords/{v201609 => v201802}/campaign_management/set_criterion_bid_modifier.py (97%) rename examples/adwords/{v201609 => v201802}/campaign_management/validate_text_ad.py (99%) rename examples/adwords/{v201702 => v201802}/error_handling/__init__.py (100%) rename examples/adwords/{v201609 => v201802}/error_handling/handle_partial_failures.py (78%) create mode 100755 examples/adwords/v201802/error_handling/handle_policy_violation_error.py rename examples/adwords/{v201702 => v201802}/extensions/__init__.py (100%) rename examples/adwords/{v201609 => v201802}/extensions/add_google_my_business_location_extensions.py (97%) rename examples/adwords/{v201609 => v201802}/extensions/add_prices.py (88%) rename examples/adwords/{v201609 => v201802}/extensions/add_site_links.py (98%) rename examples/adwords/{v201609 => v201802}/extensions/add_site_links_using_feeds.py (98%) rename examples/adwords/{v201702 => v201802}/migration/__init__.py (100%) rename examples/adwords/{v201609 => v201802}/migration/migrate_to_extension_settings.py (98%) rename examples/adwords/{v201702 => v201802}/misc/__init__.py (100%) rename examples/adwords/{v201609 => v201802}/misc/get_all_images_and_videos.py (99%) rename examples/adwords/{v201702 => v201802}/misc/upload_image.py (99%) rename examples/adwords/{v201702 => v201802}/misc/upload_media_bundle.py (93%) rename examples/adwords/{v201702 => v201802}/optimization/__init__.py (100%) rename examples/adwords/{v201702 => v201802}/optimization/estimate_keyword_traffic.py (99%) rename examples/adwords/{v201609 => v201802}/optimization/get_campaign_criterion_bid_modifier_simulations.py (94%) rename examples/adwords/{v201609 => v201802}/optimization/get_keyword_bid_simulations.py (59%) rename examples/adwords/{v201702 => v201802}/optimization/get_keyword_ideas.py (56%) rename examples/adwords/{v201702 => v201802}/remarketing/__init__.py (100%) rename examples/adwords/{v201609 => v201802}/remarketing/add_audience.py (69%) rename examples/adwords/{v201702 => v201802}/remarketing/add_conversion_tracker.py (97%) create mode 100755 examples/adwords/v201802/remarketing/add_conversion_trackers.py rename examples/adwords/{v201702 => v201802}/remarketing/add_crm_based_user_list.py (68%) rename examples/adwords/{v201609 => v201802}/remarketing/add_rule_based_user_lists.py (73%) rename examples/adwords/{v201702 => v201802}/remarketing/upload_offline_call_conversions.py (95%) rename examples/adwords/{v201609 => v201802}/remarketing/upload_offline_conversions.py (79%) create mode 100755 examples/adwords/v201802/remarketing/upload_offline_data.py rename examples/adwords/{v201702 => v201802}/reporting/__init__.py (100%) rename examples/adwords/{v201702 => v201802}/reporting/download_criteria_report_as_stream_with_awql.py (82%) rename examples/adwords/{v201702 => v201802}/reporting/download_criteria_report_as_stream_with_selector.py (97%) rename examples/adwords/{v201702 => v201802}/reporting/download_criteria_report_as_string_with_awql.py (76%) rename examples/adwords/{v201702 => v201802}/reporting/download_criteria_report_as_string_with_selector.py (96%) rename examples/adwords/{v201702 => v201802}/reporting/download_criteria_report_with_awql.py (58%) rename examples/adwords/{v201702 => v201802}/reporting/download_criteria_report_with_selector.py (95%) rename examples/adwords/{v201609 => v201802}/reporting/get_report_fields.py (96%) rename examples/adwords/{v201702 => v201802}/reporting/parallel_report_download.py (99%) rename examples/adwords/{v201702 => v201802}/shopping/__init__.py (100%) rename examples/adwords/{v201609 => v201802}/shopping/add_product_partition_tree.py (91%) rename examples/adwords/{v201609 => v201802}/shopping/add_product_scope.py (98%) rename examples/adwords/{v201702 => v201802}/shopping/add_shopping_campaign.py (62%) create mode 100755 examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py rename examples/adwords/{v201609 => v201802}/shopping/get_product_category_taxonomy.py (99%) rename examples/adwords/{v201702 => v201802}/targeting/__init__.py (100%) rename examples/adwords/{v201609 => v201802}/targeting/add_campaign_targeting_criteria.py (82%) create mode 100755 examples/adwords/v201802/targeting/add_customer_negative_criteria.py rename examples/adwords/{v201702 => v201802}/targeting/add_demographic_targeting_criteria.py (98%) rename examples/adwords/{v201702 => v201802}/targeting/get_campaign_targeting_criteria.py (98%) rename examples/adwords/{v201702 => v201802}/targeting/get_targetable_languages_and_carriers.py (97%) rename examples/adwords/{v201702 => v201802}/targeting/lookup_location.py (98%) delete mode 100755 examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py delete mode 100755 examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py delete mode 100755 examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py delete mode 100755 examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py delete mode 100755 examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py delete mode 100755 examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py create mode 100755 examples/dfp/v201708/report_service/run_report_and_create_match_table.py rename examples/dfp/{v201702 => v201711}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201702 => v201711}/activity_group_service/get_active_activity_groups.py (86%) rename examples/dfp/{v201702 => v201711}/activity_group_service/get_all_activity_groups.py (97%) rename examples/dfp/{v201705 => v201711}/activity_group_service/update_activity_groups.py (87%) rename examples/dfp/{v201702 => v201711}/activity_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/activity_service/create_activities.py (99%) rename examples/dfp/{v201705 => v201711}/activity_service/get_active_activities.py (87%) rename examples/dfp/{v201705 => v201711}/activity_service/get_all_activities.py (99%) rename examples/dfp/{v201705 => v201711}/activity_service/update_activities.py (90%) rename examples/dfp/{v201702 => v201711}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/audience_segment_service/create_audience_segments.py (98%) rename examples/dfp/{v201705 => v201711}/audience_segment_service/get_all_audience_segments.py (97%) rename examples/dfp/{v201705 => v201711}/audience_segment_service/get_first_party_audience_segments.py (86%) rename examples/dfp/{v201705 => v201711}/audience_segment_service/populate_first_party_audience_segments.py (80%) rename examples/dfp/{v201702 => v201711}/audience_segment_service/update_audience_segments.py (81%) rename examples/dfp/{v201702 => v201711}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201705 => v201711}/base_rate_service/create_product_package_item_base_rates.py (99%) rename examples/dfp/{v201705 => v201711}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201705 => v201711}/base_rate_service/get_all_base_rates.py (99%) rename examples/dfp/{v201705 => v201711}/base_rate_service/get_base_rates_for_rate_card.py (88%) rename examples/dfp/{v201705 => v201711}/base_rate_service/update_base_rates.py (90%) rename examples/dfp/{v201702/native_style_service => v201711/cdn_configuration_service}/__init__.py (100%) create mode 100755 examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py create mode 100755 examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py rename examples/dfp/{v201702 => v201711}/company_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/company_service/create_companies.py (99%) rename examples/dfp/{v201702 => v201711}/company_service/get_advertisers.py (88%) rename examples/dfp/{v201702 => v201711}/company_service/get_all_companies.py (99%) rename examples/dfp/{v201705 => v201711}/company_service/update_companies.py (89%) rename examples/dfp/{v201702 => v201711}/contact_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201705 => v201711}/contact_service/get_all_contacts.py (99%) rename examples/dfp/{v201702 => v201711}/contact_service/get_uninvited_contacts.py (87%) rename examples/dfp/{v201702 => v201711}/contact_service/update_contacts.py (90%) rename examples/dfp/{v201702 => v201711}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201705 => v201711}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (90%) rename examples/dfp/{v201705 => v201711}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201702 => v201711}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (91%) rename examples/dfp/{v201702 => v201711}/content_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/content_service/get_all_content.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/creative_service/copy_image_creatives.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201705 => v201711}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201705 => v201711}/creative_service/create_native_creative.py (99%) rename examples/dfp/{v201702 => v201711}/creative_service/get_all_creatives.py (99%) rename examples/dfp/{v201705 => v201711}/creative_service/get_image_creatives.py (86%) rename examples/dfp/{v201702 => v201711}/creative_service/update_creatives.py (85%) rename examples/dfp/{v201702 => v201711}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201702 => v201711}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201702 => v201711}/creative_set_service/get_all_creative_sets.py (97%) rename examples/dfp/{v201705 => v201711}/creative_set_service/get_creative_sets_for_master_creative.py (85%) rename examples/dfp/{v201702 => v201711}/creative_set_service/update_creative_set.py (89%) rename examples/dfp/{v201702 => v201711}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/creative_template_service/get_all_creative_templates.py (97%) rename examples/dfp/{v201705 => v201711}/creative_template_service/get_system_defined_creative_templates.py (86%) rename examples/dfp/{v201702 => v201711}/creative_wrapper_service/create_creative_wrappers.py (91%) rename examples/dfp/{v201705 => v201711}/creative_wrapper_service/deactivate_creative_wrapper.py (85%) rename examples/dfp/{v201705 => v201711}/creative_wrapper_service/get_active_creative_wrappers.py (86%) rename examples/dfp/{v201705 => v201711}/creative_wrapper_service/get_all_creative_wrappers.py (97%) rename examples/dfp/{v201705 => v201711}/creative_wrapper_service/update_creative_wrappers.py (88%) rename examples/dfp/{v201702 => v201711}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201702 => v201711}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201705 => v201711}/custom_field_service/deactivate_all_line_item_custom_fields.py (82%) rename examples/dfp/{v201705 => v201711}/custom_field_service/get_all_custom_fields.py (97%) rename examples/dfp/{v201702 => v201711}/custom_field_service/get_custom_fields_for_line_items.py (85%) rename examples/dfp/{v201705 => v201711}/custom_field_service/set_line_item_custom_field_value.py (98%) rename examples/dfp/{v201705 => v201711}/custom_field_service/update_custom_fields.py (88%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/delete_custom_targeting_keys.py (90%) rename examples/dfp/{v201705 => v201711}/custom_targeting_service/delete_custom_targeting_values.py (98%) rename examples/dfp/{v201705 => v201711}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (78%) rename examples/dfp/{v201702 => v201711}/custom_targeting_service/update_custom_targeting_keys.py (88%) rename examples/dfp/{v201705 => v201711}/custom_targeting_service/update_custom_targeting_values.py (88%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201705 => v201711}/exchange_rate_service/get_all_exchange_rates.py (97%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/get_exchange_rates_for_currency_code.py (86%) rename examples/dfp/{v201702 => v201711}/exchange_rate_service/update_exchange_rates.py (87%) rename examples/dfp/{v201705 => v201711}/forecast_service/get_availability_forecast.py (90%) rename examples/dfp/{v201705 => v201711}/forecast_service/get_availability_forecast_for_line_item.py (83%) rename examples/dfp/{v201705 => v201711}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/dfp/{v201702 => v201711}/inventory_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/inventory_service/archive_ad_units.py (90%) rename examples/dfp/{v201705 => v201711}/inventory_service/create_ad_units.py (99%) create mode 100755 examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py rename examples/dfp/{v201705 => v201711}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/dfp/{v201705 => v201711}/inventory_service/get_all_ad_units.py (99%) create mode 100755 examples/dfp/v201711/inventory_service/get_top_level_ad_units.py rename examples/dfp/{v201705 => v201711}/inventory_service/update_ad_units.py (92%) rename examples/dfp/{v201702 => v201711}/label_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/label_service/create_labels.py (99%) rename examples/dfp/{v201702 => v201711}/label_service/deactivate_labels.py (89%) rename examples/dfp/{v201705 => v201711}/label_service/get_active_labels.py (87%) rename examples/dfp/{v201702 => v201711}/label_service/get_all_labels.py (99%) rename examples/dfp/{v201705 => v201711}/label_service/update_labels.py (87%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/deactivate_licas.py (83%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/get_all_licas.py (97%) rename examples/dfp/{v201702 => v201711}/line_item_creative_association_service/get_licas_for_line_item.py (87%) rename examples/dfp/{v201705 => v201711}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201702 => v201711}/line_item_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/line_item_service/activate_line_items.py (86%) rename examples/dfp/{v201705 => v201711}/line_item_service/create_line_items.py (99%) rename examples/dfp/{v201705 => v201711}/line_item_service/create_video_line_item.py (99%) rename examples/dfp/{v201702 => v201711}/line_item_service/get_all_line_items.py (99%) rename examples/dfp/{v201705 => v201711}/line_item_service/get_line_items_that_need_creatives.py (86%) rename examples/dfp/{v201705 => v201711}/line_item_service/get_recently_updated_line_items.py (82%) rename examples/dfp/{v201705 => v201711}/line_item_service/pause_line_items.py (99%) rename examples/dfp/{v201702 => v201711}/line_item_service/target_custom_criteria.py (93%) rename examples/dfp/{v201702 => v201711}/line_item_service/update_line_items.py (84%) rename examples/dfp/{v201705 => v201711}/native_style_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/native_style_service/create_native_styles.py (98%) rename examples/dfp/{v201705 => v201711}/native_style_service/get_all_native_styles.py (96%) rename examples/dfp/{v201702 => v201711}/network_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/network_service/get_all_networks.py (99%) create mode 100755 examples/dfp/v201711/network_service/get_current_network.py rename examples/dfp/{v201705 => v201711}/network_service/make_test_network.py (99%) rename examples/dfp/{v201702 => v201711}/order_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/order_service/approve_orders.py (84%) rename examples/dfp/{v201705 => v201711}/order_service/create_orders.py (99%) rename examples/dfp/{v201702 => v201711}/order_service/get_all_orders.py (99%) rename examples/dfp/{v201702 => v201711}/order_service/get_orders_starting_soon.py (73%) rename examples/dfp/{v201705 => v201711}/order_service/update_orders.py (90%) rename examples/dfp/{v201702 => v201711}/package_service/create_packages.py (99%) rename examples/dfp/{v201705 => v201711}/package_service/create_proposal_line_items_from_packages.py (99%) rename examples/dfp/{v201705 => v201711}/package_service/get_all_packages.py (99%) rename examples/dfp/{v201705 => v201711}/package_service/get_in_progress_packages.py (87%) rename examples/dfp/{v201705 => v201711}/placement_service/create_placements.py (99%) rename examples/dfp/{v201702 => v201711}/placement_service/deactivate_placements.py (88%) rename examples/dfp/{v201705 => v201711}/placement_service/get_active_placements.py (87%) rename examples/dfp/{v201702 => v201711}/placement_service/get_all_placements.py (99%) rename examples/dfp/{v201705 => v201711}/placement_service/update_placements.py (96%) rename examples/dfp/{v201702 => v201711}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/premium_rate_service/create_premium_rates.py (97%) rename examples/dfp/{v201705 => v201711}/premium_rate_service/get_all_premium_rates.py (97%) rename examples/dfp/{v201702 => v201711}/premium_rate_service/get_premium_rates_for_rate_card.py (87%) rename examples/dfp/{v201705 => v201711}/premium_rate_service/update_premium_rates.py (90%) rename examples/dfp/{v201705 => v201711}/product_package_item_service/create_product_package_item.py (99%) rename examples/dfp/{v201705 => v201711}/product_package_item_service/get_all_product_package_items.py (97%) rename examples/dfp/{v201702 => v201711}/product_package_item_service/get_product_package_items_for_product_package.py (86%) rename examples/dfp/{v201705 => v201711}/product_package_service/create_product_packages.py (96%) rename examples/dfp/{v201705 => v201711}/product_package_service/get_active_product_packages.py (86%) rename examples/dfp/{v201702 => v201711}/product_package_service/get_all_product_packages.py (97%) rename examples/dfp/{v201702 => v201711}/product_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/product_service/get_all_products.py (99%) rename examples/dfp/{v201702 => v201711}/product_service/get_products_for_product_template.py (86%) rename examples/dfp/{v201705 => v201711}/product_service/update_products.py (90%) rename examples/dfp/{v201702 => v201711}/product_template_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/product_template_service/activate_product_templates.py (89%) rename examples/dfp/{v201705 => v201711}/product_template_service/create_product_templates.py (97%) rename examples/dfp/{v201702 => v201711}/product_template_service/create_programmatic_product_templates.py (96%) rename examples/dfp/{v201702 => v201711}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201702 => v201711}/product_template_service/get_sponsorship_product_templates.py (85%) rename examples/dfp/{v201705 => v201711}/product_template_service/update_product_templates.py (90%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/proposal_line_item_service/archive_proposal_line_items.py (89%) rename examples/dfp/{v201705 => v201711}/proposal_line_item_service/create_programmatic_proposal_line_items.py (98%) rename examples/dfp/{v201705 => v201711}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (98%) rename examples/dfp/{v201705 => v201711}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/get_all_proposal_line_items.py (97%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (86%) rename examples/dfp/{v201702 => v201711}/proposal_line_item_service/update_proposal_line_items.py (89%) rename examples/dfp/{v201702 => v201711}/proposal_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/proposal_service/create_programmatic_proposals.py (98%) rename examples/dfp/{v201702 => v201711}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (99%) rename examples/dfp/{v201702 => v201711}/proposal_service/create_proposals.py (99%) rename examples/dfp/{v201705 => v201711}/proposal_service/get_all_proposals.py (99%) rename examples/dfp/{v201702 => v201711}/proposal_service/get_marketplace_comments.py (97%) rename examples/dfp/{v201702 => v201711}/proposal_service/get_proposals_pending_approval.py (87%) rename examples/dfp/{v201705 => v201711}/proposal_service/request_buyers_acceptance.py (89%) rename examples/dfp/{v201705 => v201711}/proposal_service/submit_proposals_for_approval.py (88%) rename examples/dfp/{v201702 => v201711}/proposal_service/update_proposals.py (89%) rename examples/dfp/{v201702 => v201711}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/publisher_query_language_service/fetch_match_tables.py (96%) create mode 100755 examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py rename examples/dfp/{v201705 => v201711}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) create mode 100755 examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py create mode 100755 examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py rename examples/dfp/{v201702 => v201711}/publisher_query_language_service/get_recent_changes.py (66%) rename examples/dfp/{v201702 => v201711}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/rate_card_service/create_rate_cards.py (99%) rename examples/dfp/{v201705 => v201711}/rate_card_service/get_all_rate_cards.py (99%) rename examples/dfp/{v201705 => v201711}/rate_card_service/get_marketplace_rate_cards.py (87%) rename examples/dfp/{v201702 => v201711}/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (97%) rename examples/dfp/{v201702 => v201711}/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (97%) rename examples/dfp/{v201705 => v201711}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (85%) rename examples/dfp/{v201702 => v201711}/reconciliation_order_report_service/submit_reconciliation_order_reports.py (97%) rename examples/dfp/{v201702 => v201711}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (85%) rename examples/dfp/{v201702 => v201711}/reconciliation_report_row_service/update_reconciliation_report_rows.py (97%) rename examples/dfp/{v201705 => v201711}/reconciliation_report_service/get_all_reconciliation_reports.py (97%) rename examples/dfp/{v201705 => v201711}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (97%) rename examples/dfp/{v201702 => v201711}/report_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/report_service/run_delivery_report.py (88%) rename examples/dfp/{v201705 => v201711}/report_service/run_inventory_report.py (83%) rename examples/dfp/{v201705 => v201711}/report_service/run_reach_report.py (96%) create mode 100755 examples/dfp/v201711/report_service/run_report_and_create_match_table.py rename examples/dfp/{v201705 => v201711}/report_service/run_report_with_custom_fields.py (85%) rename examples/dfp/{v201705 => v201711}/report_service/run_sales_report.py (96%) rename examples/dfp/{v201705 => v201711}/report_service/run_saved_query.py (89%) rename examples/dfp/{v201702 => v201711}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (97%) rename examples/dfp/{v201705 => v201711}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) rename examples/dfp/{v201702 => v201711}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (86%) rename examples/dfp/{v201702 => v201711}/team_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/team_service/create_teams.py (99%) rename examples/dfp/{v201705 => v201711}/team_service/get_all_teams.py (99%) rename examples/dfp/{v201702 => v201711}/team_service/update_teams.py (90%) rename examples/dfp/{v201702 => v201711}/user_service/__init__.py (100%) rename examples/dfp/{v201705 => v201711}/user_service/create_users.py (99%) rename examples/dfp/{v201702 => v201711}/user_service/deactivate_users.py (89%) rename examples/dfp/{v201702 => v201711}/user_service/get_all_roles.py (100%) rename examples/dfp/{v201705 => v201711}/user_service/get_all_users.py (99%) rename examples/dfp/{v201702 => v201711}/user_service/get_current_user.py (99%) rename examples/dfp/{v201705 => v201711}/user_service/get_user_by_email_address.py (88%) rename examples/dfp/{v201705 => v201711}/user_service/update_users.py (86%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201705 => v201711}/user_team_association_service/delete_user_team_associations.py (87%) rename examples/dfp/{v201705 => v201711}/user_team_association_service/get_all_user_team_associations.py (97%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/get_user_team_associations_for_user.py (87%) rename examples/dfp/{v201702 => v201711}/user_team_association_service/update_user_team_associations.py (89%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/approve_workflow_approval_requests.py (76%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/get_workflow_approval_requests.py (87%) rename examples/dfp/{v201702 => v201711}/workflow_request_service/get_workflow_external_condition_requests.py (86%) rename examples/dfp/{v201705 => v201711}/workflow_request_service/trigger_workflow_external_condition_requests.py (78%) rename examples/dfp/{v201705 => v201802}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201705 => v201802}/activity_group_service/get_active_activity_groups.py (86%) rename examples/dfp/{v201705 => v201802}/activity_group_service/get_all_activity_groups.py (97%) rename examples/dfp/{v201702 => v201802}/activity_group_service/update_activity_groups.py (87%) rename examples/dfp/{v201705 => v201802}/activity_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/activity_service/create_activities.py (99%) rename examples/dfp/{v201702 => v201802}/activity_service/get_active_activities.py (87%) rename examples/dfp/{v201702 => v201802}/activity_service/get_all_activities.py (99%) rename examples/dfp/{v201702 => v201802}/activity_service/update_activities.py (90%) rename examples/dfp/{v201705 => v201802}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/audience_segment_service/create_audience_segments.py (98%) rename examples/dfp/{v201702 => v201802}/audience_segment_service/get_all_audience_segments.py (97%) rename examples/dfp/{v201702 => v201802}/audience_segment_service/get_first_party_audience_segments.py (86%) rename examples/dfp/{v201702 => v201802}/audience_segment_service/populate_first_party_audience_segments.py (80%) rename examples/dfp/{v201705 => v201802}/audience_segment_service/update_audience_segments.py (81%) rename examples/dfp/{v201705 => v201802}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/base_rate_service/create_product_base_rates.py (89%) rename examples/dfp/{v201702 => v201802}/base_rate_service/create_product_package_item_base_rates.py (94%) rename examples/dfp/{v201702 => v201802}/base_rate_service/create_product_template_base_rates.py (88%) rename examples/dfp/{v201702 => v201802}/base_rate_service/get_all_base_rates.py (99%) rename examples/dfp/{v201702 => v201802}/base_rate_service/get_base_rates_for_rate_card.py (88%) rename examples/dfp/{v201702 => v201802}/base_rate_service/update_base_rates.py (90%) create mode 100755 examples/dfp/v201802/cdn_configuration_service/__init__.py create mode 100755 examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py create mode 100755 examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py rename examples/dfp/{v201705 => v201802}/company_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/company_service/create_companies.py (99%) rename examples/dfp/{v201705 => v201802}/company_service/get_advertisers.py (88%) rename examples/dfp/{v201705 => v201802}/company_service/get_all_companies.py (99%) rename examples/dfp/{v201702 => v201802}/company_service/update_companies.py (89%) rename examples/dfp/{v201705 => v201802}/contact_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201702 => v201802}/contact_service/get_all_contacts.py (99%) rename examples/dfp/{v201705 => v201802}/contact_service/get_uninvited_contacts.py (87%) rename examples/dfp/{v201705 => v201802}/contact_service/update_contacts.py (90%) rename examples/dfp/{v201705 => v201802}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201702 => v201802}/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (90%) rename examples/dfp/{v201702 => v201802}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201705 => v201802}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (91%) rename examples/dfp/{v201705 => v201802}/content_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/content_service/get_all_content.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/creative_service/copy_image_creatives.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201702 => v201802}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201702 => v201802}/creative_service/create_native_creative.py (99%) rename examples/dfp/{v201705 => v201802}/creative_service/get_all_creatives.py (99%) rename examples/dfp/{v201702 => v201802}/creative_service/get_image_creatives.py (86%) rename examples/dfp/{v201705 => v201802}/creative_service/update_creatives.py (85%) rename examples/dfp/{v201705 => v201802}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201705 => v201802}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201705 => v201802}/creative_set_service/get_all_creative_sets.py (97%) rename examples/dfp/{v201702 => v201802}/creative_set_service/get_creative_sets_for_master_creative.py (85%) rename examples/dfp/{v201705 => v201802}/creative_set_service/update_creative_set.py (89%) rename examples/dfp/{v201705 => v201802}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/creative_template_service/get_all_creative_templates.py (97%) rename examples/dfp/{v201702 => v201802}/creative_template_service/get_system_defined_creative_templates.py (86%) rename examples/dfp/{v201705 => v201802}/creative_wrapper_service/create_creative_wrappers.py (91%) rename examples/dfp/{v201702 => v201802}/creative_wrapper_service/deactivate_creative_wrapper.py (85%) rename examples/dfp/{v201702 => v201802}/creative_wrapper_service/get_active_creative_wrappers.py (86%) rename examples/dfp/{v201702 => v201802}/creative_wrapper_service/get_all_creative_wrappers.py (97%) rename examples/dfp/{v201702 => v201802}/creative_wrapper_service/update_creative_wrappers.py (88%) rename examples/dfp/{v201705 => v201802}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201705 => v201802}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201702 => v201802}/custom_field_service/deactivate_all_line_item_custom_fields.py (82%) rename examples/dfp/{v201702 => v201802}/custom_field_service/get_all_custom_fields.py (97%) rename examples/dfp/{v201705 => v201802}/custom_field_service/get_custom_fields_for_line_items.py (85%) rename examples/dfp/{v201702 => v201802}/custom_field_service/set_line_item_custom_field_value.py (82%) rename examples/dfp/{v201702 => v201802}/custom_field_service/update_custom_fields.py (88%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/delete_custom_targeting_keys.py (84%) rename examples/dfp/{v201702 => v201802}/custom_targeting_service/delete_custom_targeting_values.py (81%) rename examples/dfp/{v201702 => v201802}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (87%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (78%) rename examples/dfp/{v201705 => v201802}/custom_targeting_service/update_custom_targeting_keys.py (88%) rename examples/dfp/{v201702 => v201802}/custom_targeting_service/update_custom_targeting_values.py (88%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201702 => v201802}/exchange_rate_service/get_all_exchange_rates.py (97%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/get_exchange_rates_for_currency_code.py (86%) rename examples/dfp/{v201705 => v201802}/exchange_rate_service/update_exchange_rates.py (87%) rename examples/dfp/{v201702 => v201802}/forecast_service/get_availability_forecast.py (90%) rename examples/dfp/{v201702 => v201802}/forecast_service/get_availability_forecast_for_line_item.py (83%) rename examples/dfp/{v201702 => v201802}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/dfp/{v201705 => v201802}/inventory_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/inventory_service/archive_ad_units.py (90%) rename examples/dfp/{v201702 => v201802}/inventory_service/create_ad_units.py (99%) create mode 100755 examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py rename examples/dfp/{v201702 => v201802}/inventory_service/get_all_ad_unit_sizes.py (90%) rename examples/dfp/{v201702 => v201802}/inventory_service/get_all_ad_units.py (99%) create mode 100755 examples/dfp/v201802/inventory_service/get_top_level_ad_units.py rename examples/dfp/{v201702 => v201802}/inventory_service/update_ad_units.py (92%) rename examples/dfp/{v201705 => v201802}/label_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/label_service/create_labels.py (99%) rename examples/dfp/{v201705 => v201802}/label_service/deactivate_labels.py (89%) rename examples/dfp/{v201702 => v201802}/label_service/get_active_labels.py (87%) rename examples/dfp/{v201705 => v201802}/label_service/get_all_labels.py (99%) rename examples/dfp/{v201702 => v201802}/label_service/update_labels.py (87%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/deactivate_licas.py (83%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/get_all_licas.py (97%) rename examples/dfp/{v201705 => v201802}/line_item_creative_association_service/get_licas_for_line_item.py (87%) rename examples/dfp/{v201702 => v201802}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201705 => v201802}/line_item_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/line_item_service/activate_line_items.py (86%) rename examples/dfp/{v201702 => v201802}/line_item_service/create_line_items.py (93%) rename examples/dfp/{v201702 => v201802}/line_item_service/create_video_line_item.py (92%) rename examples/dfp/{v201705 => v201802}/line_item_service/get_all_line_items.py (99%) rename examples/dfp/{v201702 => v201802}/line_item_service/get_line_items_that_need_creatives.py (86%) rename examples/dfp/{v201702 => v201802}/line_item_service/get_recently_updated_line_items.py (82%) rename examples/dfp/{v201702 => v201802}/line_item_service/pause_line_items.py (99%) rename examples/dfp/{v201705 => v201802}/line_item_service/target_custom_criteria.py (93%) rename examples/dfp/{v201705 => v201802}/line_item_service/update_line_items.py (84%) create mode 100755 examples/dfp/v201802/native_style_service/__init__.py rename examples/dfp/{v201702 => v201802}/native_style_service/create_native_styles.py (98%) rename examples/dfp/{v201702 => v201802}/native_style_service/get_all_native_styles.py (96%) rename examples/dfp/{v201705 => v201802}/network_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/network_service/get_all_networks.py (99%) create mode 100755 examples/dfp/v201802/network_service/get_current_network.py rename examples/dfp/{v201702 => v201802}/network_service/make_test_network.py (99%) rename examples/dfp/{v201705 => v201802}/order_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/order_service/approve_orders.py (84%) rename examples/dfp/{v201702 => v201802}/order_service/create_orders.py (99%) rename examples/dfp/{v201705 => v201802}/order_service/get_all_orders.py (99%) rename examples/dfp/{v201705 => v201802}/order_service/get_orders_starting_soon.py (73%) rename examples/dfp/{v201702 => v201802}/order_service/update_orders.py (90%) rename examples/dfp/{v201705 => v201802}/package_service/create_packages.py (99%) rename examples/dfp/{v201702 => v201802}/package_service/create_proposal_line_items_from_packages.py (99%) rename examples/dfp/{v201702 => v201802}/package_service/get_all_packages.py (99%) rename examples/dfp/{v201702 => v201802}/package_service/get_in_progress_packages.py (87%) rename examples/dfp/{v201702 => v201802}/placement_service/create_placements.py (99%) rename examples/dfp/{v201705 => v201802}/placement_service/deactivate_placements.py (88%) rename examples/dfp/{v201702 => v201802}/placement_service/get_active_placements.py (87%) rename examples/dfp/{v201705 => v201802}/placement_service/get_all_placements.py (99%) rename examples/dfp/{v201702 => v201802}/placement_service/update_placements.py (57%) rename examples/dfp/{v201705 => v201802}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/premium_rate_service/create_premium_rates.py (90%) rename examples/dfp/{v201702 => v201802}/premium_rate_service/get_all_premium_rates.py (97%) rename examples/dfp/{v201705 => v201802}/premium_rate_service/get_premium_rates_for_rate_card.py (87%) rename examples/dfp/{v201702 => v201802}/premium_rate_service/update_premium_rates.py (90%) rename examples/dfp/{v201702 => v201802}/product_package_item_service/create_product_package_item.py (99%) rename examples/dfp/{v201702 => v201802}/product_package_item_service/get_all_product_package_items.py (97%) rename examples/dfp/{v201705 => v201802}/product_package_item_service/get_product_package_items_for_product_package.py (86%) rename examples/dfp/{v201702 => v201802}/product_package_service/create_product_packages.py (96%) rename examples/dfp/{v201702 => v201802}/product_package_service/get_active_product_packages.py (86%) rename examples/dfp/{v201705 => v201802}/product_package_service/get_all_product_packages.py (97%) rename examples/dfp/{v201705 => v201802}/product_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/product_service/get_all_products.py (99%) rename examples/dfp/{v201705 => v201802}/product_service/get_products_for_product_template.py (86%) rename examples/dfp/{v201702 => v201802}/product_service/update_products.py (90%) rename examples/dfp/{v201705 => v201802}/product_template_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/product_template_service/activate_product_templates.py (89%) rename examples/dfp/{v201702 => v201802}/product_template_service/create_product_templates.py (97%) rename examples/dfp/{v201705 => v201802}/product_template_service/create_programmatic_product_templates.py (96%) rename examples/dfp/{v201705 => v201802}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201705 => v201802}/product_template_service/get_sponsorship_product_templates.py (85%) rename examples/dfp/{v201702 => v201802}/product_template_service/update_product_templates.py (90%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/proposal_line_item_service/archive_proposal_line_items.py (89%) rename examples/dfp/{v201702 => v201802}/proposal_line_item_service/create_programmatic_proposal_line_items.py (82%) rename examples/dfp/{v201702 => v201802}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (82%) rename examples/dfp/{v201702 => v201802}/proposal_line_item_service/create_proposal_line_items.py (82%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/get_all_proposal_line_items.py (97%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (86%) rename examples/dfp/{v201705 => v201802}/proposal_line_item_service/update_proposal_line_items.py (89%) rename examples/dfp/{v201705 => v201802}/proposal_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/proposal_service/create_programmatic_proposals.py (98%) rename examples/dfp/{v201705 => v201802}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (99%) rename examples/dfp/{v201705 => v201802}/proposal_service/create_proposals.py (99%) rename examples/dfp/{v201702 => v201802}/proposal_service/get_all_proposals.py (99%) rename examples/dfp/{v201705 => v201802}/proposal_service/get_marketplace_comments.py (97%) rename examples/dfp/{v201705 => v201802}/proposal_service/get_proposals_pending_approval.py (87%) rename examples/dfp/{v201702 => v201802}/proposal_service/request_buyers_acceptance.py (89%) rename examples/dfp/{v201702 => v201802}/proposal_service/submit_proposals_for_approval.py (88%) rename examples/dfp/{v201705 => v201802}/proposal_service/update_proposals.py (89%) rename examples/dfp/{v201705 => v201802}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/publisher_query_language_service/fetch_match_tables.py (96%) create mode 100755 examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py rename examples/dfp/{v201702 => v201802}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) create mode 100755 examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py create mode 100755 examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py rename examples/dfp/{v201705 => v201802}/publisher_query_language_service/get_recent_changes.py (66%) rename examples/dfp/{v201705 => v201802}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/rate_card_service/create_rate_cards.py (99%) rename examples/dfp/{v201702 => v201802}/rate_card_service/get_all_rate_cards.py (99%) rename examples/dfp/{v201702 => v201802}/rate_card_service/get_marketplace_rate_cards.py (87%) rename examples/dfp/{v201705 => v201802}/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (97%) rename examples/dfp/{v201705 => v201802}/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (97%) rename examples/dfp/{v201702 => v201802}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (85%) rename examples/dfp/{v201705 => v201802}/reconciliation_order_report_service/submit_reconciliation_order_reports.py (97%) rename examples/dfp/{v201705 => v201802}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (85%) rename examples/dfp/{v201705 => v201802}/reconciliation_report_row_service/update_reconciliation_report_rows.py (97%) rename examples/dfp/{v201702 => v201802}/reconciliation_report_service/get_all_reconciliation_reports.py (97%) rename examples/dfp/{v201702 => v201802}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (86%) rename examples/dfp/{v201705 => v201802}/report_service/__init__.py (100%) create mode 100755 examples/dfp/v201802/report_service/run_ad_exchange_report.py rename examples/dfp/{v201702 => v201802}/report_service/run_delivery_report.py (88%) rename examples/dfp/{v201702 => v201802}/report_service/run_inventory_report.py (83%) rename examples/dfp/{v201702 => v201802}/report_service/run_reach_report.py (96%) create mode 100755 examples/dfp/v201802/report_service/run_report_and_create_match_table.py rename examples/dfp/{v201702 => v201802}/report_service/run_report_with_custom_fields.py (85%) rename examples/dfp/{v201702 => v201802}/report_service/run_sales_report.py (96%) rename examples/dfp/{v201702 => v201802}/report_service/run_saved_query.py (89%) rename examples/dfp/{v201705 => v201802}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (88%) rename examples/dfp/{v201702 => v201802}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) rename examples/dfp/{v201705 => v201802}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (86%) rename examples/dfp/{v201705 => v201802}/team_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/team_service/create_teams.py (96%) rename examples/dfp/{v201702 => v201802}/team_service/get_all_teams.py (96%) rename examples/dfp/{v201705 => v201802}/team_service/update_teams.py (87%) rename examples/dfp/{v201705 => v201802}/user_service/__init__.py (100%) rename examples/dfp/{v201702 => v201802}/user_service/create_users.py (96%) rename examples/dfp/{v201705 => v201802}/user_service/deactivate_users.py (86%) rename examples/dfp/{v201705 => v201802}/user_service/get_all_roles.py (100%) rename examples/dfp/{v201702 => v201802}/user_service/get_all_users.py (96%) rename examples/dfp/{v201705 => v201802}/user_service/get_current_user.py (94%) rename examples/dfp/{v201702 => v201802}/user_service/get_user_by_email_address.py (85%) rename examples/dfp/{v201702 => v201802}/user_service/update_users.py (83%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201702 => v201802}/user_team_association_service/delete_user_team_associations.py (87%) rename examples/dfp/{v201702 => v201802}/user_team_association_service/get_all_user_team_associations.py (97%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/get_user_team_associations_for_user.py (87%) rename examples/dfp/{v201705 => v201802}/user_team_association_service/update_user_team_associations.py (89%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/approve_workflow_approval_requests.py (76%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/get_workflow_approval_requests.py (87%) rename examples/dfp/{v201705 => v201802}/workflow_request_service/get_workflow_external_condition_requests.py (86%) rename examples/dfp/{v201702 => v201802}/workflow_request_service/trigger_workflow_external_condition_requests.py (78%) create mode 100644 tests/__init__.py create mode 100644 tests/test_data/adwords_googleads.yaml create mode 100644 tests/test_data/batch_job_util_budget_template.txt create mode 100644 tests/test_data/batch_job_util_campaign_criterion_template.txt create mode 100644 tests/test_data/batch_job_util_campaign_label_template.txt create mode 100644 tests/test_data/batch_job_util_invalid_request.txt create mode 100644 tests/test_data/batch_job_util_not_request.txt create mode 100644 tests/test_data/batch_job_util_operations_template.txt create mode 100644 tests/test_data/batch_job_util_raw_request_template.txt create mode 100644 tests/test_data/batch_job_util_response_template.txt create mode 100644 tests/test_data/batch_job_util_upload_template.txt create mode 100644 tests/test_data/compact_fault_response_envelope.txt create mode 100644 tests/test_data/empty_fault_response_envelope.txt create mode 100644 tests/test_data/fault_response_envelope.txt create mode 100644 tests/test_data/gzip_response.bin create mode 100644 tests/test_data/multi_errors_fault_response_envelope.txt create mode 100644 tests/test_data/request_envelope_template.txt create mode 100644 tests/test_data/test.crt create mode 100644 tests/testing.py diff --git a/ChangeLog b/ChangeLog index 1f081cd8..7fe99848 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,43 @@ +10.1.1 -- 03/16/18 +* Accepted PR #222, to improve AdWords App Engine sample. + +10.1.0 -- 03/01/18 +* Added support and examples for AdWords v201802. +* Added new BuildOpener utility method to ProxyConfig, which returns an + OpenerDirector instance configured for the ProxyConfig settings. + +10.0.0 -- 02/13/18 +* Added support and examples for DFP v201802. +* Removed support and examples for AdWords v201702. +* Resolved issues: +- Issue 229: https://github.com/googleads/googleads-python-lib/issues/229 +- Issue 236: https://github.com/googleads/googleads-python-lib/issues/236 + +9.0.1 -- 12/22/17 +* Improved Python 3 compatibility of library and tests. +* Fixed reported issue with the ProductPartitionHelper utility used in AdWords + shopping examples. + +9.0.0 -- 11/14/17 +* Added support and examples for DFP v201711 +* Removed support and examples for DFP v201611 +* DFP PQL queries can now accept simple python dicts for variable substitution. +* Resolved issues: +- Issue 230: https://github.com/googleads/googleads-python-lib/issues/230 + + +8.1.0 -- 10/11/17 +* Added support for AdWords v201710. +* Resolved issues: +- Issue 224: https://github.com/googleads/googleads-python-lib/issues/224 +- Issue 228: https://github.com/googleads/googleads-python-lib/issues/228 + +8.0.0 -- 8/22/17 +* Removed support and examples for AdWords v201609. +* Resolved issues: +- Issue 219: https://github.com/googleads/googleads-python-lib/issues/219 +- Issue 220: https://github.com/googleads/googleads-python-lib/issues/220 + 7.0.0 -- 8/15/17 * Added support and examples for DFP v201708. * Removed support and examples for DFP v201608. diff --git a/examples/adwords/adwords_appengine_demo/README.md b/examples/adwords/adwords_appengine_demo/README.md index 87e48df6..b43b39ba 100644 --- a/examples/adwords/adwords_appengine_demo/README.md +++ b/examples/adwords/adwords_appengine_demo/README.md @@ -33,7 +33,7 @@ Task Queue API to handle requests asynchronously. You can read more about this This guide assumes that you have already set up your AdWords account and have prepared your OAuth2 Credentials via the Google Developers Console. -1. Install Python v2.7, which you can get +1. Install Python v2.7.9 or higher, which you can get [here](https://www.python.org/downloads). 1. Install [pip](http://pip.readthedocs.org/en/latest/installing.html), @@ -44,36 +44,42 @@ prepared your OAuth2 Credentials via the Google Developers Console. This account will be used to access your AdWords credentials used in making API requests. -1. Install Google Cloud SDK (https://cloud.google.com/appengine/docs/flexible/python/download). +1. Install the [Google Cloud SDK](https://cloud.google.com/sdk/downloads). - `$ curl --capath /etc/ssl/certs https://sdk.cloud.google.com | bash` +1. Install googleads ands its dependencies locally with the following command, + executed from this file's parent directory: -1. Install googleads with the following command, executed from this file's - parent directory: + `$ pip install -r requirements.txt -t lib` - `$ pip install -r requirements.txt lib` +1. If you don't already have one, create a new project in the + [Google Cloud Console](https://console.cloud.google.com). Note the Project + ID, which you will need in the next step. - Then copy the googleads package from your Python installation's - dist-packages directory into this project. The installation of googleads - should also have installed the dependencies referred to in the following - steps. +1. Configure the Google Cloud SDK with the following steps: -1. Create an App Engine application in the - [Google App Engine Console](https://appengine.google.com/). + * While logged into the Google Account you used to create your project, run + the following command: -1. Go to this project's app.yaml, and enter in your application name for the - "application" field. + `gcloud auth login` -1. You can now deploy this project by running the following command: + * Set your project as the current project with the following command: + + `gcloud config set project ENTER_PROJECT_ID_HERE` + +1. You can now deploy this application by running the following command: `gcloud app deploy app.yaml -v v1` +1. To view your application in your web browser, run the following command: + + `gcloud app browse` + 1. When you go to your App for the first time, you will need to log in and - provide OAuth2 and AdWords API credentials. You can use credentials - generated via the generate_refresh_token.py example. + provide OAuth2 and AdWords API credentials. You can use credentials + generated via the generate_refresh_token.py example. 1. With all information entered, you can now use the UI to view and modify - your account details. + your account details. ## Where do I submit bug reports and/or feature requests? @@ -84,12 +90,14 @@ Submit bug reports or feature requests to our ## External Dependencies: -* [Python v2.7](https://www.python.org/downloads/) +* [Python v2.7.9+](https://www.python.org/downloads/) * [httplib2 v0.9+](https://pypi.python.org/pypi/httplib2) -* [oauth2client v1.4.5+](https://pypi.python.org/pypi/oauth2client/) +* [oauth2client v4.0.0+](https://pypi.python.org/pypi/oauth2client/) * [pysocks v1.5.0+](https://pypi.python.org/pypi/PySocks/) * [pytz 2014.7+](https://pypi.python.org/pypi/pytz) +* [PyYAML 3.11+](https://pypi.python.org/pypi/PyYAML) * [suds-jurko 0.6+](https://pypi.python.org/pypi/suds-jurko) +* [xmltodict 0.9.2+](https://pypi.python.org/pypi/xmltodict) * [App Engine SDK v1.9.11+](https://developers.google.com/appengine/downloads) -* [Google Ads Python Client Library v2.1.0+](https://github.com/googleads/googleads-python-lib) +* [Google Ads Python Client Library v10.1.0+](https://github.com/googleads/googleads-python-lib) * [Google Account](https://www.google.com/accounts/NewAccount) diff --git a/examples/adwords/adwords_appengine_demo/appengine_config.py b/examples/adwords/adwords_appengine_demo/appengine_config.py index 841620a4..5c567b83 100644 --- a/examples/adwords/adwords_appengine_demo/appengine_config.py +++ b/examples/adwords/adwords_appengine_demo/appengine_config.py @@ -1,4 +1,20 @@ -# appengine_config.py +# Copyright 2018 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. + +"""Configuration module for the AdWords App Engine demo.""" + + import os from google.appengine.ext import vendor diff --git a/examples/adwords/adwords_appengine_demo/requirements.txt b/examples/adwords/adwords_appengine_demo/requirements.txt index 48187cb5..92408dbf 100644 --- a/examples/adwords/adwords_appengine_demo/requirements.txt +++ b/examples/adwords/adwords_appengine_demo/requirements.txt @@ -1 +1 @@ -googleads==7.0.0 +googleads==10.1.1 diff --git a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index 82f1def5..00000000 --- a/examples/adwords/v201609/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - media_service = client.GetService('MediaService', version='v201609') - - try: - # Create image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - # Make the upload request - image = media_service.upload(image)[0] - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'] - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 2272b149..00000000 --- a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id "%s" was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index fb18eef5..00000000 --- a/examples/adwords/v201609/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id "%s" was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py b/examples/adwords/v201609/error_handling/handle_policy_violation_error.py deleted file mode 100755 index ec6cda1a..00000000 --- a/examples/adwords/v201609/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201609') - - # Create text ad. - text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'TextAd', - 'headline': 'Mars Cruise!!!', - 'description1': 'Visit the Red Planet in style.', - 'description2': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'www.example.com', - } - } - } - - operations = [text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - if error['ApiError.Type'] == 'PolicyViolationError': - operation_index = re.findall(r'operations\[(.*)\]\.', - error['fieldPath']) - if operation_index: - index = int(operation_index[0]) - operation = operations[index] - print ('Ad with headline "%s" violated %s policy "%s".' % - (operation['operand']['ad']['headline'], - 'exemptable' if error['isExemptable'] else 'non-exemptable', - error['externalPolicyName'])) - if error['isExemptable'].lower() == 'true': - # Add exemption request to the operation. - print ('Adding exemption request for policy name "%s" on text ' - '"%s".' % - (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({ - 'key': error['key'] - }) - else: - # Set non-exemptable operation to None to mark for deletion - print 'Removing the operation from the request.' - operations[index] = None - else: - # Non-policy error returned, re-throw exception. - raise e - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is "%s".' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index 052d9e23..00000000 --- a/examples/adwords/v201702/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - media_service = client.GetService('MediaService', version='v201702') - - try: - # Create image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - # Make the upload request - image = media_service.upload(image)[0] - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'] - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 0178909e..00000000 --- a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct selector and get all ads for a given ad group. - selector = { - 'fields': ['Id', 'AdGroupAdDisapprovalReasons'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'AdGroupCreativeApprovalStatus', - 'operator': 'IN', - 'values': ['DISAPPROVED'] - } - ] - } - ads = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id "%s" was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 87e65980..00000000 --- a/examples/adwords/v201702/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, AdGroupAdDisapprovalReasons ' - 'WHERE CampaignId = %s AND ' - 'AdGroupCreativeApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % campaign_id) - ads = ad_group_ad_service.query(query) - - # Display results. - if 'entries' in ads: - for ad in ads['entries']: - print ('Ad with id "%s" was disapproved for the following reasons: ' - % (ad['ad']['id'])) - if ad['ad'].get('disapprovalReasons'): - for reason in ad['ad']['disapprovalReasons']: - print '\t%s' % reason - else: - print '\tReason not provided.' - else: - print 'No disapproved ads were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py index 93de192f..284bd2dd 100755 --- a/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py @@ -43,7 +43,9 @@ def main(client, ad_group_id): # BASE64 encoded form. Here we download a demo image and encode it for this # ad. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201705/advanced_operations/add_html5_ad.py b/examples/adwords/v201705/advanced_operations/add_html5_ad.py index 8857c94e..988d2c93 100755 --- a/examples/adwords/v201705/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201705/advanced_operations/add_html5_ad.py @@ -101,7 +101,8 @@ def main(client, ad_group_id): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py index 996b976b..f096b1d8 100755 --- a/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py @@ -42,7 +42,9 @@ def main(client, ad_group_id): try: # Create image. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) + .decode('utf-8')) image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201705/basic_operations/get_campaigns.py b/examples/adwords/v201705/basic_operations/get_campaigns.py index 63ba8668..fac8642e 100755 --- a/examples/adwords/v201705/basic_operations/get_campaigns.py +++ b/examples/adwords/v201705/basic_operations/get_campaigns.py @@ -27,7 +27,6 @@ import logging -import time from googleads import adwords logging.basicConfig(level=logging.INFO) @@ -66,7 +65,6 @@ def main(client): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py index c27da4a5..29e06c4a 100755 --- a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -55,7 +54,6 @@ def main(client): print 'No campaigns were found.' offset += PAGE_SIZE more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py index 4ca7c4ad..9485c4ae 100755 --- a/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py @@ -14,11 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This uses the BatchJobService to incrementally create a complete Campaign. -The complete Campaign created by this example also includes AdGroups and -KeyWords. +"""This example illustrates how to incrementally upload keywords. +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. """ import random diff --git a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py index cd405d56..6273a119 100755 --- a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -75,7 +74,6 @@ def main(client, label_id): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201705/misc/upload_media_bundle.py b/examples/adwords/v201705/misc/upload_media_bundle.py index 0329dcd6..61856b0f 100755 --- a/examples/adwords/v201705/misc/upload_media_bundle.py +++ b/examples/adwords/v201705/misc/upload_media_bundle.py @@ -50,7 +50,8 @@ def main(client): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201705/shopping/add_product_partition_tree.py b/examples/adwords/v201705/shopping/add_product_partition_tree.py index 5098996d..d2fda6e1 100755 --- a/examples/adwords/v201705/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201705/shopping/add_product_partition_tree.py @@ -33,19 +33,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -53,6 +40,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): diff --git a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py index e8175611..e9ad6e50 100755 --- a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py @@ -38,19 +38,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -58,6 +45,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): diff --git a/examples/adwords/v201708/advanced_operations/add_ad_customizer.py b/examples/adwords/v201708/advanced_operations/add_ad_customizer.py index a30054cb..2c72f3bf 100755 --- a/examples/adwords/v201708/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201708/advanced_operations/add_ad_customizer.py @@ -92,7 +92,6 @@ def CreateCustomizerFeed(client, feed_name): # Get the AdCustomizerFeedService ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', 'v201708') - customizer_feed = { 'feedName': feed_name, 'feedAttributes': [ @@ -204,7 +203,12 @@ def CreateFeedItemAddOperation(name, price, date, adgroup_id, ] } - return {'operator': 'ADD', 'operand': feed_item} + operation = { + 'operator': 'ADD', + 'operand': feed_item + } + + return operation def main(client, adgroup_ids, feed_name=FEED_NAME): diff --git a/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py index 90f7106b..f720e51c 100755 --- a/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py @@ -43,7 +43,9 @@ def main(client, ad_group_id): # BASE64 encoded form. Here we download a demo image and encode it for this # ad. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201708/advanced_operations/add_html5_ad.py b/examples/adwords/v201708/advanced_operations/add_html5_ad.py index 716d008a..a9fc5973 100755 --- a/examples/adwords/v201708/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201708/advanced_operations/add_html5_ad.py @@ -101,7 +101,8 @@ def main(client, ad_group_id): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py index 439cf8a9..626532b6 100755 --- a/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py @@ -113,7 +113,8 @@ def _CreateImage(media_service, opener, url): Returns: The image that was successfully uploaded. """ - image_data = base64.b64encode(opener.open(url).read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py index 8a58b41a..f0d9f1f5 100755 --- a/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py @@ -80,7 +80,7 @@ def main(client): 'description2': 'Remove connected blocks', 'description3': '3 difficulty levels', 'description4': '4 colorful fun skins', - # Optional: You can set up to 10 image assets for your campaign. + # Optional: You can set up to 20 image assets for your campaign. # See upload_image.py for an example on how to upload images. # # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] diff --git a/examples/adwords/v201708/basic_operations/get_campaigns.py b/examples/adwords/v201708/basic_operations/get_campaigns.py index 0a562cc1..712cce1c 100755 --- a/examples/adwords/v201708/basic_operations/get_campaigns.py +++ b/examples/adwords/v201708/basic_operations/get_campaigns.py @@ -27,7 +27,6 @@ import logging -import time from googleads import adwords logging.basicConfig(level=logging.INFO) @@ -66,7 +65,6 @@ def main(client): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py index b40a3fd3..53555067 100755 --- a/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -55,7 +54,6 @@ def main(client): print 'No campaigns were found.' offset += PAGE_SIZE more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py index 627cf52b..3a07fca4 100755 --- a/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py @@ -14,11 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This uses the BatchJobService to incrementally create a complete Campaign. -The complete Campaign created by this example also includes AdGroups and -KeyWords. +"""This example illustrates how to incrementally upload keywords. +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. """ import random diff --git a/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py index 9c7199e5..81b30437 100755 --- a/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -75,7 +74,6 @@ def main(client, label_id): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201708/misc/upload_media_bundle.py b/examples/adwords/v201708/misc/upload_media_bundle.py index d6c498ee..33d32a35 100755 --- a/examples/adwords/v201708/misc/upload_media_bundle.py +++ b/examples/adwords/v201708/misc/upload_media_bundle.py @@ -50,7 +50,8 @@ def main(client): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201708/optimization/get_keyword_ideas.py b/examples/adwords/v201708/optimization/get_keyword_ideas.py index 2afa7bb8..2d195173 100755 --- a/examples/adwords/v201708/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201708/optimization/get_keyword_ideas.py @@ -26,49 +26,62 @@ from googleads import adwords +# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' PAGE_SIZE = 100 -def main(client): +def main(client, ad_group_id=None): # Initialize appropriate service. targeting_idea_service = client.GetService( 'TargetingIdeaService', version='v201708') # Construct selector object and retrieve related keywords. - offset = 0 selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } + 'requestType': 'IDEAS' + } + + selector['requestedAttributeTypes'] = [ + 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] + + offset = 0 + selector['paging'] = { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) } + + selector['searchParameters'] = [{ + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }] + + # Language setting (optional). + selector['searchParameters'].append({ + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }) + + # Network search parameter (optional) + selector['searchParameters'].append({ + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + }) + + # Use an existing ad group to generate ideas (optional) + if ad_group_id is not None: + selector['searchParameters'].append({ + 'xsi_type': 'SeedAdGroupIdSearchParameter', + 'adGroupId': ad_group_id + }) + more_pages = True while more_pages: page = targeting_idea_service.get(selector) @@ -78,8 +91,8 @@ def main(client): for result in page['entries']: attributes = {} for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') + attributes[attribute['key']] = getattr( + attribute['value'], 'value', '0') print ('Keyword with "%s" text and average monthly search volume ' '"%s" was found with Products and Services categories: %s.' % (attributes['KEYWORD_TEXT'], @@ -97,4 +110,4 @@ def main(client): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) + main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201708/remarketing/upload_offline_data.py b/examples/adwords/v201708/remarketing/upload_offline_data.py new file mode 100755 index 00000000..12e6513d --- /dev/null +++ b/examples/adwords/v201708/remarketing/upload_offline_data.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 shows how to upload offline data for store sales transactions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import datetime +import hashlib + +from googleads import adwords +import pytz + + +_DT_FORMAT = '%Y%m%d %H%M%S' +# User identifier types whose values must be hashed. +_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', + 'HASHED_LAST_NAME', 'HASHED_PHONE') +# The timezone to be used in this example. For valid timezone IDs, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +_TIMEZONE = pytz.timezone('America/New_York') +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Insert email addresses below for creating user identifiers. +EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] +# The external upload ID can be any number that you use to keep track of your +# uploads. +EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' +# Advertiser upload time to partner. +# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, +# see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' +# Indicates the version of the bridge map. +BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' +# The ID of the third party uploading the transaction feed. +PARTNER_ID = 'INSERT_PARTNER_ID_HERE' + + +def main(client, conversion_name, external_upload_id, email_addresses, + advertiser_upload_time, bridge_map_version_id, partner_id): + # Initialize appropriate services. + offline_data_upload_service = client.GetService( + 'OfflineDataUploadService', version='v201708') + + # Create the first offline data for upload. + # This transaction occurred 7 days ago with an amount of $200 USD. + transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=7)) + offline_data_1 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[0]), + _CreateUserIdentifier(identifier_type='STATE', value='New York') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_1), + 'transactionAmount': { + 'currencyCode': 'USD', + 'money': { + 'microAmount': 200000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create the second offline data for upload. + # This transaction occurred 14 days ago with amount of 450 EUR. + transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=14)) + offline_data_2 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[1]), + _CreateUserIdentifier(identifier_type='STATE', value='California') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_2), + 'transactionAmount': { + 'currencyCode': 'EUR', + 'money': { + 'microAmount': 450000000 + } + }, + 'conversionName': conversion_name + } + } + + # Set the metadata of this upload. + upload_metadata = { + 'StoreSalesUploadCommonMetadata': { + 'xsi_type': 'ThirdPartyUploadMetadata', + 'loyaltyRate': 1.0, + 'transactionUploadRate': 1.0, + 'advertiserUploadTime': advertiser_upload_time, + 'validTransactionRate': 1.0, + 'partnerMatchRate': 1.0, + 'partnerUploadRate': 1.0, + 'bridgeMapVersionId': bridge_map_version_id, + 'partnerId': partner_id + } + } + + # Create offline data upload + offline_data_upload = { + 'externalUploadId': external_upload_id, + 'offlineDataList': [offline_data_1, offline_data_2], + # Set the type of this upload. + 'uploadType': 'STORE_SALES_UPLOAD_THIRD_PARTY', + 'uploadMetadata': upload_metadata + } + + # Create an offline data upload operation. + operations = [{ + 'operator': 'ADD', + 'operand': offline_data_upload + }] + + # Upload offline data on the server and print the result. + result = offline_data_upload_service.mutate(operations) + offline_data_upload = result['value'][0] + + print ('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) + + # Print any partial data errors from the response. The order of the partial + # data errors list is the same as the uploaded offline data list in the + # request. + for i, partial_data_error in enumerate( + offline_data_upload['partialDataErrors']): + # If a partial error occurred for this offline data, print the error. Note + # that non-errors for a given offline data would be set to None. + if partial_data_error: + print ('Found a partial error for offline data #%d with error string: %s' + % (i, partial_data_error['errorString'])) + + +def _CreateUserIdentifier(identifier_type=None, value=None): + """Creates a user identifier from the specified type and value. + + Args: + identifier_type: a str specifying the type of user identifier. + value: a str value of the identifier; to be hashed using SHA-256 if needed. + + Returns: + A dict specifying a user identifier, with a value hashed using SHA-256 if + needed. + """ + if identifier_type in _HASHED_IDENTIFIER_TYPES: + # If the user identifier type is a hashed type, normalize and hash the + # value. + value = hashlib.sha256(value.strip().lower()).hexdigest() + + user_identifier = { + 'userIdentifierType': identifier_type, + 'value': value + } + + return user_identifier + + +def _GetFormattedDateTime(dt): + """Formats the given datetime and timezone for use with AdWords. + + Args: + dt: a datetime instance. + + Returns: + A str representation of the datetime in the correct format for AdWords. + """ + return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, EMAIL_ADDRESSES, + ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py index e59ef1f4..aab506db 100755 --- a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py @@ -47,11 +47,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201708') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py index 0eb63ede..820add34 100755 --- a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py @@ -37,11 +37,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201708') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py index a2ae571c..6913de8a 100755 --- a/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py @@ -34,11 +34,14 @@ def main(client): report_downloader = client.GetReportDownloader(version='v201708') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) # You can provide a file object to write the output to. For this # demonstration we use sys.stdout to write the report to the screen. diff --git a/examples/adwords/v201708/shopping/add_product_partition_tree.py b/examples/adwords/v201708/shopping/add_product_partition_tree.py index 8c976668..3009ad9e 100755 --- a/examples/adwords/v201708/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201708/shopping/add_product_partition_tree.py @@ -33,19 +33,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -54,6 +41,18 @@ def __init__(self, adgroup_id): tree to. """ self.adgroup_id = adgroup_id + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): """Creates a subdivision node. diff --git a/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py index 7b372563..bf9ee8a9 100755 --- a/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py @@ -38,19 +38,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -58,6 +45,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): diff --git a/examples/adwords/v201609/__init__.py b/examples/adwords/v201710/__init__.py similarity index 100% rename from examples/adwords/v201609/__init__.py rename to examples/adwords/v201710/__init__.py diff --git a/examples/adwords/v201609/account_management/__init__.py b/examples/adwords/v201710/account_management/__init__.py similarity index 100% rename from examples/adwords/v201609/account_management/__init__.py rename to examples/adwords/v201710/account_management/__init__.py diff --git a/examples/adwords/v201609/account_management/accept_service_link.py b/examples/adwords/v201710/account_management/accept_service_link.py similarity index 97% rename from examples/adwords/v201609/account_management/accept_service_link.py rename to examples/adwords/v201710/account_management/accept_service_link.py index 3879171d..522f8305 100755 --- a/examples/adwords/v201609/account_management/accept_service_link.py +++ b/examples/adwords/v201710/account_management/accept_service_link.py @@ -33,7 +33,7 @@ def main(client, service_link_id): # Initialize appropriate service. customer_service = client.GetService( - 'CustomerService', version='v201609') + 'CustomerService', version='v201710') # Create the operation to set the status to ACTIVE. operations = [{ diff --git a/examples/adwords/v201702/account_management/create_account.py b/examples/adwords/v201710/account_management/create_account.py similarity index 97% rename from examples/adwords/v201702/account_management/create_account.py rename to examples/adwords/v201710/account_management/create_account.py index 55bbcba6..8daaceb5 100755 --- a/examples/adwords/v201702/account_management/create_account.py +++ b/examples/adwords/v201710/account_management/create_account.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201702') + 'ManagedCustomerService', version='v201710') today = datetime.today().strftime('%Y%m%d %H:%M:%S') # Construct operations and add campaign. diff --git a/examples/adwords/v201609/account_management/get_account_changes.py b/examples/adwords/v201710/account_management/get_account_changes.py similarity index 98% rename from examples/adwords/v201609/account_management/get_account_changes.py rename to examples/adwords/v201710/account_management/get_account_changes.py index 5eed06f3..5bd8dfc2 100755 --- a/examples/adwords/v201609/account_management/get_account_changes.py +++ b/examples/adwords/v201710/account_management/get_account_changes.py @@ -31,8 +31,8 @@ def main(client): # Initialize appropriate service. customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201609') - campaign_service = client.GetService('CampaignService', version='v201609') + 'CustomerSyncService', version='v201710') + campaign_service = client.GetService('CampaignService', version='v201710') # Construct selector and get all campaigns. selector = { diff --git a/examples/adwords/v201702/account_management/get_account_hierarchy.py b/examples/adwords/v201710/account_management/get_account_hierarchy.py similarity index 98% rename from examples/adwords/v201702/account_management/get_account_hierarchy.py rename to examples/adwords/v201710/account_management/get_account_hierarchy.py index e95787ee..2c3727bd 100755 --- a/examples/adwords/v201702/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201710/account_management/get_account_hierarchy.py @@ -48,7 +48,7 @@ def DisplayAccountTree(account, accounts, links, depth=0): def main(client): # Initialize appropriate service. managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201702') + 'ManagedCustomerService', version='v201710') # Construct selector to get all accounts. offset = 0 diff --git a/examples/adwords/v201609/advanced_operations/__init__.py b/examples/adwords/v201710/advanced_operations/__init__.py similarity index 100% rename from examples/adwords/v201609/advanced_operations/__init__.py rename to examples/adwords/v201710/advanced_operations/__init__.py diff --git a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py b/examples/adwords/v201710/advanced_operations/add_ad_customizer.py similarity index 97% rename from examples/adwords/v201609/advanced_operations/add_ad_customizer.py rename to examples/adwords/v201710/advanced_operations/add_ad_customizer.py index bed81b79..48042172 100755 --- a/examples/adwords/v201609/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201710/advanced_operations/add_ad_customizer.py @@ -49,7 +49,7 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): GoogleAdsError: if no ExpandedTextAds were added. """ # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201609') + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201710') expanded_text_ad = { 'xsi_type': 'ExpandedTextAd', @@ -91,8 +91,7 @@ def CreateCustomizerFeed(client, feed_name): """ # Get the AdCustomizerFeedService ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201609') - + 'v201710') customizer_feed = { 'feedName': feed_name, 'feedAttributes': [ @@ -141,7 +140,7 @@ def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): GoogleAdsError: if no FeedItems were added. """ # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201609') + feed_item_service = client.GetService('FeedItemService', 'v201710') now = datetime.now() mars_date = datetime(now.year, now.month, 1, 0, 0) venus_date = datetime(now.year, now.month, 15, 0, 0) @@ -204,7 +203,12 @@ def CreateFeedItemAddOperation(name, price, date, adgroup_id, ] } - return {'operator': 'ADD', 'operand': feed_item} + operation = { + 'operator': 'ADD', + 'operand': feed_item + } + + return operation def main(client, adgroup_ids, feed_name=FEED_NAME): diff --git a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py similarity index 97% rename from examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py rename to examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py index a14d1440..d48ba4bf 100755 --- a/examples/adwords/v201609/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py @@ -35,7 +35,7 @@ def main(client, ad_group_id, bid_modifier): # Initialize appropriate service. ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201609') + 'AdGroupBidModifierService', version='v201710') # Mobile criterion ID. criterion_id = '30001' diff --git a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py similarity index 95% rename from examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py rename to examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py index fd3011b8..679abda7 100755 --- a/examples/adwords/v201702/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py @@ -37,13 +37,15 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Optionally, you may specify a landscape image. The image needs to be in a # BASE64 encoded form. Here we download a demo image and encode it for this # ad. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py new file mode 100755 index 00000000..838b04e5 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. + +To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +from collections import namedtuple +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + +# Used to keep track of DSA page feed details. +_DSAFeedDetails = namedtuple( + '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) +# ID that corresponds to the labels. +DSA_LABEL_FIELD_ID = 2 +# The criterion type to be used for DSA page feeds. +DSA_PAGE_FEED_CRITERION_TYPE = 61 +DSA_PAGE_URL_LABEL = 'discounts' +# ID that corresponds to the page URLs. +DSA_PAGE_URLS_FIELD_ID = 1 + + +def main(client, campaign_id, ad_group_id): + # Get the page feed details. This code example creates a new feed, but you can + # fetch and re-use an existing feed. + feed_details = _CreateFeed(client) + _CreateFeedMapping(client, feed_details) + _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) + + # Associate the page feed with the campaign. + _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) + + # Optional: Target web pages matching the feed's label in the ad group. + _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) + + print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + + +def _CreateFeed(client): + """Creates the feed for DSA page URLs. + + Args: + client: an AdWordsClient instance. + + Returns: + A _DSAFeedDetails instance containing details about the created feed. + """ + # Get the FeedService. + feed_service = client.GetService('FeedService', version='v201710') + + # Create operation. + operation = { + # Create the feed. + 'operand': { + 'name': 'DSA Feed %s' % uuid.uuid4(), + # Create attributes. + 'attributes': [ + {'type': 'URL_LIST', 'name': 'Page URL'}, + {'type': 'STRING_LIST', 'name': 'Label'} + ], + 'origin': 'USER' + }, + 'operator': 'ADD' + } + + # Add the feed. + feed = feed_service.mutate([operation])['value'][0] + return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], + feed['attributes'][1]['id']) + + +def _CreateFeedMapping(client, feed_details): + """Creates the feed mapping for DSA page feeds. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + """ + # Get the FeedMappingService. + feed_mapping_service = client.GetService('FeedMappingService', + version='v201710') + + # Create the operation. + operation = { + # Create the feed mapping. + 'operand': { + 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, + 'feedId': feed_details.feed_id, + # Map the feedAttributeIds to the fieldId constants. + 'attributeFieldMappings': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'fieldId': DSA_PAGE_URLS_FIELD_ID + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'fieldId': DSA_LABEL_FIELD_ID + } + ] + }, + 'operator': 'ADD' + } + + # Add the feed mapping. + feed_mapping_service.mutate([operation]) + + +def _CreateFeedItems(client, feed_details, label_name): + """Creates the page URLs in the DSA page feed. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + label_name: a str containing the page feed URL label. + """ + # Get the FeedItemService. + feed_item_service = client.GetService('FeedItemService', version='v201710') + + # Optional: You can include the {feeditem} valuetrack parameter to track which + # page feed items lead to each click. + urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', + 'http://www.example.com/discounts/hotel-deals?id={feeditem}', + 'http://www.example.com/discounts/flight-deals?id={feeditem}') + + # Create the operation. + operations = [{ + # Create the feed item. + 'operand': { + 'feedId': feed_details.feed_id, + 'attributeValues': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'stringValues': [url] + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'stringValues': [label_name] + } + ] + }, + 'operator': 'ADD' + } for url in urls] + + # Add the feed item. + feed_item_service.mutate(operations) + + +def _UpdateCampaignDSASetting(client, campaign_id, feed_id): + """Updates the campaign DSA setting to DSA pagefeeds. + + Args: + client: an AdWordsClient instance. + campaign_id: a str Campaign ID. + feed_id: a str page Feed ID. + + Raises: + ValueError: If the given campaign is found not to be a dynamic search ad + campaign. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201710') + + selector = { + 'fields': ['Id', 'Settings'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [campaign_id] + }] + } + + response = campaign_service.get(selector) + + if response['totalNumEntries']: + campaign = response['entries'][0] + else: + raise ValueError('No campaign with ID "%d" exists.' % campaign_id) + + if not campaign['settings']: + raise ValueError('This is not a DSA campaign.') + + dsa_setting = None + + campaign_settings = campaign['settings'] + + for setting in campaign_settings: + if setting['Setting.Type'] == 'DynamicSearchAdsSetting': + dsa_setting = setting + break + + if dsa_setting is None: + raise ValueError('This is not a DSA campaign.') + + dsa_setting['pageFeed'] = { + 'feedIds': [feed_id] + } + + # Optional: Specify whether only the supplied URLs should be used with your + # Dynamic Search Ads. + dsa_setting['useSuppliedUrlsOnly'] = True + + operation = { + 'operand': { + 'id': campaign_id, + 'settings': campaign_settings + }, + 'operator': 'SET' + } + + campaign_service.mutate([operation]) + print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id) + + +def _AddDSATargeting(client, ad_group_id, label_name): + """Set custom targeting for the page feed URLs based on a list of labels. + + Args: + client: an AdWordsClient instance. + ad_group_id: a str AdGroup ID. + label_name: a str label name. + + Returns: + A suds.sudsobject.Object representing the newly created webpage criterion. + """ + # Get the AdGroupCriterionService. + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201710') + + # Create the operation. + operation = { + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Test criterion', + # Add a condition for label=specified_label_name. + 'conditions': [{ + 'operand': 'CUSTOM_LABEL', + 'argument': label_name + }], + } + }, + # Set a custom bid for this criterion + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 1500000 + } + }] + } + }, + 'operator': 'ADD' + } + + criterion = ad_group_criterion_service.mutate([operation])['value'][0] + print 'Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus']) + return criterion + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py new file mode 100755 index 00000000..ba304ce5 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Dynamic Search Ads campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + budget = _CreateBudget(client) + campaign_id = _CreateCampaign(client, budget) + ad_group_id = _CreateAdGroup(client, campaign_id) + _CreateExpandedDSA(client, ad_group_id) + _AddWebPageCriteria(client, ad_group_id) + + print 'Dynamic Search Ads campaign setup is complete.' + + +def _CreateBudget(client): + """Creates the budget. + + Args: + client: an AdWordsClient instance. + + Returns: + a suds.sudsobject.Object representation of the created budget. + """ + budget_service = client.GetService('BudgetService', version='v201710') + + # Create the campaign budget + operation = { + 'operand': { + 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), + 'deliveryMethod': 'STANDARD', + 'amount': { + 'microAmount': 500000 + } + }, + 'operator': 'ADD' + } + + budget = budget_service.mutate([operation])['value'][0] + + print 'Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name']) + + return budget + + +def _CreateCampaign(client, budget): + """Creates the campaign. + + Args: + client: an AdWordsClient instance. + budget: a suds.sudsobject.Object representation of a created budget. + + Returns: + An integer campaign ID. + """ + campaign_service = client.GetService('CampaignService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # prevent the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'budget': budget, + # Required: Set the campaign's Dynamic Search Ad settings. + 'settings': [{ + 'xsi_type': 'DynamicSearchAdsSetting', + # Required: Set the domain name and language. + 'domainName': 'example.com', + 'languageCode': 'en' + }], + # Optional: Set the start date. + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + # Optional: Set the end date. + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + }] + + campaign = campaign_service.mutate(operations)['value'][0] + campaign_id = campaign['id'] + + print 'Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name']) + + return campaign_id + + +def _CreateAdGroup(client, campaign_id): + """Creates an ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: an integer campaign ID. + + Returns: + An integer ad group ID. + """ + ad_group_service = client.GetService('AdGroupService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'adGroupType': 'SEARCH_DYNAMIC_ADS', + 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '3000000' + }, + }] + } + } + }] + + ad_group = ad_group_service.mutate(operations)['value'][0] + ad_group_id = ad_group['id'] + + print 'Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name']) + + return ad_group_id + + +def _CreateExpandedDSA(client, ad_group_id): + """Creates the expanded Dynamic Search Ad. + + Args: + client: an AdwordsClient instance. + ad_group_id: an integer ID of the ad group in which the DSA is added. + """ + # Get the AdGroupAdService. + ad_group_ad_service = client.GetService('AdGroupAdService') + + # Create the operation + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + # Create the expanded dynamic search ad. This ad will have its + # headline and final URL auto-generated at serving time according to + # domain name specific information provided by DynamicSearchAdsSetting + # at the campaign level. + 'ad': { + 'xsi_type': 'ExpandedDynamicSearchAd', + # Set the ad description. + 'description': 'Buy your tickets now!' + }, + # Optional: Set the status. + 'status': 'PAUSED', + } + }] + + # Create the ad. + ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] + + # Display the results. + print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' + 'added' % (ad['id'], ad['description'])) + + +def _AddWebPageCriteria(client, ad_group_id): + """Adds a web page criterion to target Dynamic Search Ads. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID of the ad group the criteria is being added to. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201710') + + operations = [{ + 'operator': 'ADD', + # Create biddable ad group criterion. + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion for special offers for children. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Special offers for children.', + 'conditions': [ + { + 'operand': 'URL', + 'argument': '/marscruise/children' + }, + { + 'operand': 'PAGE_TITLE', + 'argument': 'Special Offer' + } + ] + } + }, + 'userStatus': 'PAUSED', + # Optional: set a custom bid. + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000L + } + }] + } + } + }] + + criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py similarity index 78% rename from examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py rename to examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py index 453bca8f..16e68459 100755 --- a/examples/adwords/v201609/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -32,7 +32,7 @@ def main(client, adgroup_id): # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201609') + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201710') # Create the expanded text ad expanded_text_ad = { @@ -40,25 +40,6 @@ def main(client, adgroup_id): 'headlinePart1': 'Luxury Cruise to Mars', 'headlinePart2': 'Visit the Red Planet in style.', 'description': 'Low-gravity fun for everyone!', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, # Specify a list of final URLs. This field cannot be set if URL # field is set, or finalUrls is unset. This may be specified at ad, # criterion, and feed item levels. @@ -75,6 +56,29 @@ def main(client, adgroup_id): ] } + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + expanded_text_ad['trackingUrlTemplate'] = ( + 'http://tracker.example.com/?season={_season}&promocode={_promocode}' + '&u={lpurl}' + ) + + expanded_text_ad['urlCustomParameters'] = { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + } + text_adgroup_ad = { 'adGroupId': adgroup_id, 'ad': expanded_text_ad, diff --git a/examples/adwords/v201609/advanced_operations/add_html5_ad.py b/examples/adwords/v201710/advanced_operations/add_html5_ad.py similarity index 95% rename from examples/adwords/v201609/advanced_operations/add_html5_ad.py rename to examples/adwords/v201710/advanced_operations/add_html5_ad.py index ff814915..db7eee3e 100755 --- a/examples/adwords/v201609/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201710/advanced_operations/add_html5_ad.py @@ -36,7 +36,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Create HTML5 media. base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( @@ -101,7 +101,8 @@ def main(client, ad_group_id): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..02701412 --- /dev/null +++ b/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + media_service = client.GetService('MediaService', version='v201710') + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + + try: + # Create marketing image. + marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/3b9Wfh') + + # Create square marketing image. + square_marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/mtt54n') + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': marketing_image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'], + # Optional: Set a square marketing image to the ad. + 'squareMarketingImage': { + 'mediaId': square_marketing_image['mediaId'] + }, + # Optional: Set call-to-action text. + 'callToActionText': 'Shop Now', + # Optional: Set dynamic display ad settings, composed of + # landscape logo image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( + media_service, opener), + # Whitelisted accounts only: Set color settings using + # hexadecimal numbers. + # Set allowFlexibleColor to False if you want your ads to render + # by always using your colors strictly. + # 'mainColor': '#0000ff', + # 'accentColor': '#ffff00', + # 'allowFlexibleColor': False + # Whitelisted accounts only: Set the format setting that the ad + # will be served in. + # 'formatSetting': 'NON_NATIVE' + + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +def _CreateDynamicDisplayAdSettings(media_service, opener): + """Creates settings for dynamic display ad. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + + Returns: + The dynamic display ad settings. + """ + image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + + logo = { + 'type': 'IMAGE', + 'mediaId': image['mediaId'], + 'xsi_type': 'Image' + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!', + 'xsi_type': 'DynamicSettings', + } + + return dynamic_settings + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py similarity index 98% rename from examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py rename to examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py index 72e19e88..27db64ed 100755 --- a/examples/adwords/v201702/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201710') budget_id = CreateBudget(client) @@ -80,7 +80,7 @@ def main(client): 'description2': 'Remove connected blocks', 'description3': '3 difficulty levels', 'description4': '4 colorful fun skins', - # Optional: You can set up to 10 image assets for your campaign. + # Optional: You can set up to 20 image assets for your campaign. # See upload_image.py for an example on how to upload images. # # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] @@ -138,7 +138,7 @@ def CreateBudget(client): Returns: An int budgetId for the created Budget. """ - budget_service = client.GetService('BudgetService', version='v201702') + budget_service = client.GetService('BudgetService', version='v201710') # Create a budget. budget = { diff --git a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py similarity index 97% rename from examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py rename to examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py index 4fcf2ef8..e510d813 100755 --- a/examples/adwords/v201702/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py @@ -34,11 +34,11 @@ def main(client, campaign_id): # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201702') + shared_set_service = client.GetService('SharedSetService', version='v201710') shared_criterion_service = client.GetService('SharedCriterionService', - version='v201702') + version='v201710') campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201702') + version='v201710') # Keywords to create a shared set of. keywords = ['mars cruise', 'mars hotels'] diff --git a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py similarity index 98% rename from examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py rename to examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py index edc6c1df..34c27532 100755 --- a/examples/adwords/v201702/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -33,9 +33,9 @@ def main(client, campaign_id): # Initialize appropriate services. shared_criterion_service = client.GetService('SharedCriterionService', - version='v201702') + version='v201710') campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201702') + version='v201710') shared_set_ids = [] criterion_ids = [] diff --git a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py similarity index 97% rename from examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py rename to examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py index 21cdf0eb..5e65078a 100755 --- a/examples/adwords/v201702/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201702') + 'AdGroupBidModifierService', version='v201710') # Get all ad group bid modifiers for the campaign. selector = { diff --git a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py similarity index 98% rename from examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py rename to examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py index 98dd1275..ab912ab5 100755 --- a/examples/adwords/v201702/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py @@ -54,7 +54,7 @@ def CreateBiddingStrategy(client): """ # Initialize appropriate service. bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201702') + 'BiddingStrategyService', version='v201710') # Create a shared bidding strategy. shared_bidding_strategy = { @@ -95,7 +95,7 @@ def CreateSharedBudget(client): dict An object representing a shared budget. """ # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201702') + budget_service = client.GetService('BudgetService', version='v201710') # Create a shared budget budget = { @@ -129,7 +129,7 @@ def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): dict An object representing a campaign. """ # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201710') # Create campaign. campaign = { diff --git a/examples/adwords/v201609/basic_operations/__init__.py b/examples/adwords/v201710/basic_operations/__init__.py similarity index 100% rename from examples/adwords/v201609/basic_operations/__init__.py rename to examples/adwords/v201710/basic_operations/__init__.py diff --git a/examples/adwords/v201609/basic_operations/add_ad_groups.py b/examples/adwords/v201710/basic_operations/add_ad_groups.py similarity index 99% rename from examples/adwords/v201609/basic_operations/add_ad_groups.py rename to examples/adwords/v201710/basic_operations/add_ad_groups.py index 79f2a17c..e38048e1 100755 --- a/examples/adwords/v201609/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201710/basic_operations/add_ad_groups.py @@ -35,7 +35,7 @@ def main(client, campaign_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201609') + ad_group_service = client.GetService('AdGroupService', version='v201710') # Construct operations and add ad groups. operations = [{ diff --git a/examples/adwords/v201702/basic_operations/add_campaigns.py b/examples/adwords/v201710/basic_operations/add_campaigns.py similarity index 98% rename from examples/adwords/v201702/basic_operations/add_campaigns.py rename to examples/adwords/v201710/basic_operations/add_campaigns.py index 49dd97f3..7789c2c1 100755 --- a/examples/adwords/v201702/basic_operations/add_campaigns.py +++ b/examples/adwords/v201710/basic_operations/add_campaigns.py @@ -33,8 +33,8 @@ def main(client): # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201702') - budget_service = client.GetService('BudgetService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201710') + budget_service = client.GetService('BudgetService', version='v201710') # Create a budget, which can be shared by multiple campaigns. budget = { @@ -82,7 +82,6 @@ def main(client): # Optional fields 'startDate': (datetime.datetime.now() + datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', 'frequencyCap': { 'impressions': '5', 'timeUnit': 'DAY', diff --git a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201710/basic_operations/add_expanded_text_ads.py similarity index 99% rename from examples/adwords/v201609/basic_operations/add_expanded_text_ads.py rename to examples/adwords/v201710/basic_operations/add_expanded_text_ads.py index 4d5221db..d3394999 100755 --- a/examples/adwords/v201609/basic_operations/add_expanded_text_ads.py +++ b/examples/adwords/v201710/basic_operations/add_expanded_text_ads.py @@ -36,7 +36,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') operations = [ { diff --git a/examples/adwords/v201609/basic_operations/add_keywords.py b/examples/adwords/v201710/basic_operations/add_keywords.py similarity index 98% rename from examples/adwords/v201609/basic_operations/add_keywords.py rename to examples/adwords/v201710/basic_operations/add_keywords.py index 1e1ab69c..4b1b0cec 100755 --- a/examples/adwords/v201609/basic_operations/add_keywords.py +++ b/examples/adwords/v201710/basic_operations/add_keywords.py @@ -34,7 +34,7 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') + 'AdGroupCriterionService', version='v201710') # Construct keyword ad group criterion object. keyword1 = { diff --git a/examples/adwords/v201609/basic_operations/get_ad_groups.py b/examples/adwords/v201710/basic_operations/get_ad_groups.py similarity index 99% rename from examples/adwords/v201609/basic_operations/get_ad_groups.py rename to examples/adwords/v201710/basic_operations/get_ad_groups.py index a345fec7..719942e1 100755 --- a/examples/adwords/v201609/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201710/basic_operations/get_ad_groups.py @@ -34,7 +34,7 @@ def main(client, campaign_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201609') + ad_group_service = client.GetService('AdGroupService', version='v201710') # Construct selector and get all ad groups. offset = 0 diff --git a/examples/adwords/v201609/basic_operations/get_campaigns.py b/examples/adwords/v201710/basic_operations/get_campaigns.py similarity index 97% rename from examples/adwords/v201609/basic_operations/get_campaigns.py rename to examples/adwords/v201710/basic_operations/get_campaigns.py index 196e52c7..3d540ad4 100755 --- a/examples/adwords/v201609/basic_operations/get_campaigns.py +++ b/examples/adwords/v201710/basic_operations/get_campaigns.py @@ -27,7 +27,6 @@ import logging -import time from googleads import adwords logging.basicConfig(level=logging.INFO) @@ -39,7 +38,7 @@ def main(client): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201710') # Construct selector and get all campaigns. offset = 0 @@ -66,7 +65,6 @@ def main(client): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py similarity index 84% rename from examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py rename to examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py index 58497c61..360d3d4a 100755 --- a/examples/adwords/v201702/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -35,16 +34,17 @@ def main(client): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201710') # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'Name', 'Status') + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, PAGE_SIZE) + .Build()) + + for page in query.Pager(campaign_service): # Display results. if 'entries' in page: for campaign in page['entries']: @@ -53,9 +53,6 @@ def main(client): campaign['status'])) else: print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201710/basic_operations/get_expanded_text_ads.py similarity index 99% rename from examples/adwords/v201702/basic_operations/get_expanded_text_ads.py rename to examples/adwords/v201710/basic_operations/get_expanded_text_ads.py index 414b76e7..77046b40 100755 --- a/examples/adwords/v201702/basic_operations/get_expanded_text_ads.py +++ b/examples/adwords/v201710/basic_operations/get_expanded_text_ads.py @@ -34,7 +34,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Construct selector and get all ads for a given ad group. offset = 0 diff --git a/examples/adwords/v201702/basic_operations/get_keywords.py b/examples/adwords/v201710/basic_operations/get_keywords.py similarity index 98% rename from examples/adwords/v201702/basic_operations/get_keywords.py rename to examples/adwords/v201710/basic_operations/get_keywords.py index 83d6ee18..5feec2b1 100755 --- a/examples/adwords/v201702/basic_operations/get_keywords.py +++ b/examples/adwords/v201710/basic_operations/get_keywords.py @@ -36,7 +36,7 @@ def main(client, adgroup_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') + 'AdGroupCriterionService', version='v201710') # Construct selector and get all ad group criteria. offset = 0 diff --git a/examples/adwords/v201702/basic_operations/pause_ad.py b/examples/adwords/v201710/basic_operations/pause_ad.py similarity index 99% rename from examples/adwords/v201702/basic_operations/pause_ad.py rename to examples/adwords/v201710/basic_operations/pause_ad.py index c4822b5e..f51e1f90 100755 --- a/examples/adwords/v201702/basic_operations/pause_ad.py +++ b/examples/adwords/v201710/basic_operations/pause_ad.py @@ -34,7 +34,7 @@ def main(client, ad_group_id, ad_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Construct operations and update an ad. operations = [{ diff --git a/examples/adwords/v201702/basic_operations/remove_ad.py b/examples/adwords/v201710/basic_operations/remove_ad.py similarity index 96% rename from examples/adwords/v201702/basic_operations/remove_ad.py rename to examples/adwords/v201710/basic_operations/remove_ad.py index ab8c5d2a..4ea3a4ec 100755 --- a/examples/adwords/v201702/basic_operations/remove_ad.py +++ b/examples/adwords/v201710/basic_operations/remove_ad.py @@ -16,7 +16,7 @@ """This example deletes an ad using the 'REMOVE' operator. -To get ads, run get_text_ads.py. +To get ads, run get_expanded_text_ads.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -34,7 +34,7 @@ def main(client, ad_group_id, ad_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Construct operations and delete ad. operations = [{ diff --git a/examples/adwords/v201702/basic_operations/remove_ad_group.py b/examples/adwords/v201710/basic_operations/remove_ad_group.py similarity index 99% rename from examples/adwords/v201702/basic_operations/remove_ad_group.py rename to examples/adwords/v201710/basic_operations/remove_ad_group.py index 374865a2..2a372bc8 100755 --- a/examples/adwords/v201702/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201710/basic_operations/remove_ad_group.py @@ -33,7 +33,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201702') + ad_group_service = client.GetService('AdGroupService', version='v201710') # Construct operations and delete ad group. operations = [{ diff --git a/examples/adwords/v201702/basic_operations/remove_campaign.py b/examples/adwords/v201710/basic_operations/remove_campaign.py similarity index 99% rename from examples/adwords/v201702/basic_operations/remove_campaign.py rename to examples/adwords/v201710/basic_operations/remove_campaign.py index 3252c2fd..4e4e84f6 100755 --- a/examples/adwords/v201702/basic_operations/remove_campaign.py +++ b/examples/adwords/v201710/basic_operations/remove_campaign.py @@ -33,7 +33,7 @@ def main(client, campaign_id): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201710') # Construct operations and delete campaign. operations = [{ diff --git a/examples/adwords/v201702/basic_operations/remove_keyword.py b/examples/adwords/v201710/basic_operations/remove_keyword.py similarity index 97% rename from examples/adwords/v201702/basic_operations/remove_keyword.py rename to examples/adwords/v201710/basic_operations/remove_keyword.py index a09c35bb..a5a13312 100755 --- a/examples/adwords/v201702/basic_operations/remove_keyword.py +++ b/examples/adwords/v201710/basic_operations/remove_keyword.py @@ -35,7 +35,7 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') + 'AdGroupCriterionService', version='v201710') # Construct operations and delete ad group criteria. operations = [ diff --git a/examples/adwords/v201702/basic_operations/update_ad_group.py b/examples/adwords/v201710/basic_operations/update_ad_group.py similarity index 56% rename from examples/adwords/v201702/basic_operations/update_ad_group.py rename to examples/adwords/v201710/basic_operations/update_ad_group.py index a682b3ea..eac1d446 100755 --- a/examples/adwords/v201702/basic_operations/update_ad_group.py +++ b/examples/adwords/v201710/basic_operations/update_ad_group.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates status for a given ad group. +"""This example updates the CPC bid and status for a given ad group. To get ad groups, run get_ad_groups.py. @@ -29,11 +29,12 @@ AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' -def main(client, ad_group_id): +def main(client, ad_group_id, bid_micro_amount=None): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201702') + ad_group_service = client.GetService('AdGroupService', version='v201710') # Construct operations and update an ad group. operations = [{ @@ -43,16 +44,42 @@ def main(client, ad_group_id): 'status': 'PAUSED' } }] + + if bid_micro_amount: + operations[0]['operand']['biddingStrategyConfiguration'] = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': bid_micro_amount, + } + }] + } + ad_groups = ad_group_service.mutate(operations) # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was updated.' - % (ad_group['name'], ad_group['id'])) + bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] + # Find the CpcBid in the bidding strategy configuration's bids collection. + cpc_bid_micros = None + + if bidding_strategy_configuration: + bids = bidding_strategy_configuration['bids'] + + if bids: + for bid in bids: + if bid['Bids.Type'] == 'CpcBid': + cpc_bid_micros = bid['bid']['microAmount'] + break + + print ('Ad group with name "%s", and id "%s" was updated to have status ' + '"%s" and CPC bid %d.' + % (ad_group['name'], ad_group['id'], ad_group['status'], + cpc_bid_micros)) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) + main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201609/basic_operations/update_campaign.py b/examples/adwords/v201710/basic_operations/update_campaign.py similarity index 99% rename from examples/adwords/v201609/basic_operations/update_campaign.py rename to examples/adwords/v201710/basic_operations/update_campaign.py index ca7eb9d5..9f0e4dc2 100755 --- a/examples/adwords/v201609/basic_operations/update_campaign.py +++ b/examples/adwords/v201710/basic_operations/update_campaign.py @@ -33,7 +33,7 @@ def main(client, campaign_id): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201710') # Construct operations and update campaign. operations = [{ diff --git a/examples/adwords/v201609/basic_operations/update_keyword.py b/examples/adwords/v201710/basic_operations/update_keyword.py similarity index 98% rename from examples/adwords/v201609/basic_operations/update_keyword.py rename to examples/adwords/v201710/basic_operations/update_keyword.py index 36e38f72..b140a592 100755 --- a/examples/adwords/v201609/basic_operations/update_keyword.py +++ b/examples/adwords/v201710/basic_operations/update_keyword.py @@ -35,7 +35,7 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') + 'AdGroupCriterionService', version='v201710') # Construct operations and update bids. diff --git a/examples/adwords/v201609/campaign_management/__init__.py b/examples/adwords/v201710/campaign_management/__init__.py similarity index 100% rename from examples/adwords/v201609/campaign_management/__init__.py rename to examples/adwords/v201710/campaign_management/__init__.py diff --git a/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py new file mode 100755 index 00000000..27cc2172 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a campaign group and sets a performance target for it. + +To get campaigns, run get_campaigns.py. To download reports, run +download_criteria_report_with_awql.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id1, campaign_id2): + campaign_group_id = _CreateCampaignGroup(client) + _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) + _CreatePerformanceTarget(client, campaign_group_id) + print 'Campaign group and its performance target were setup successfully.' + + +def _CreateCampaignGroup(client): + """Create a campaign group. + + Args: + client: an AdWordsClient instance. + + Returns: + The integer ID of the created campaign group. + """ + # Get the CampaignGroupService. + campaign_group_service = client.GetService('CampaignGroupService', + version='v201710') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the campaign group. + 'operand': { + 'name': 'Mars campaign group #%d' % uuid.uuid4() + } + }] + + campaign_group = campaign_group_service.mutate(operations)['value'][0] + campaign_group_id = campaign_group['id'] + + # Display the results. + print 'Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name']) + + return campaign_group_id + + +def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): + """Adds multiple campaigns to a campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + campaign_ids: a list of integer IDs for campaigns. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201710') + + # Create the operations. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'campaignGroupId': campaign_group_id + } + } for campaign_id in campaign_ids] + + campaign_service.mutate(operations) + + # Display the results. + print ('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + + +def _CreatePerformanceTarget(client, campaign_group_id): + """Creates a performance target for the campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + """ + # Get the CampaignGroupPerformanceTargetService. + cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', + version='v201710') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the performance target. + 'operand': { + 'campaignGroupId': campaign_group_id, + 'performanceTarget': { + # Keep the CPC for the campaigns < $3. + 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', + 'efficiencyTargetValue': 3000000, + # Keep the maximum spend under $50. + 'spendTargetType': 'MAXIMUM', + 'spendTarget': { + 'microAmount': 500000000 + }, + # Aim for at least 3000 clicks. + 'volumeGoalType': 'MAXIMIZE_CLICKS', + 'volumeTargetValue': 3000, + # Start the performance target today, and run it for the next 90 + # days. + 'startDate': datetime.datetime.now().strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(90)).strftime('%Y%m%d') + } + } + }] + + cgpt = cgpt_service.mutate(operations)['value'][0] + + # Display the results. + print ('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201609/campaign_management/add_campaign_labels.py b/examples/adwords/v201710/campaign_management/add_campaign_labels.py similarity index 99% rename from examples/adwords/v201609/campaign_management/add_campaign_labels.py rename to examples/adwords/v201710/campaign_management/add_campaign_labels.py index 7020658e..ec7f1adc 100755 --- a/examples/adwords/v201609/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201710/campaign_management/add_campaign_labels.py @@ -33,7 +33,7 @@ def main(client, campaign_id1, campaign_id2, label_id): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201710') operations = [ { diff --git a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py similarity index 98% rename from examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py rename to examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py index 60e3ce09..1d00652b 100755 --- a/examples/adwords/v201609/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py @@ -38,7 +38,7 @@ def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201609') + batch_job_helper = client.GetBatchJobHelper(version='v201710') # Create a BatchJob. batch_job = AddBatchJob(client) @@ -82,7 +82,7 @@ def AddBatchJob(client): The new BatchJob created by the request. """ # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201609') + batch_job_service = client.GetService('BatchJobService', version='v201710') # Create a BatchJob. batch_job_operations = [{ 'operand': {}, @@ -347,7 +347,7 @@ def GetBatchJob(client, batch_job_id): Returns: The BatchJob associated with the given id. """ - batch_job_service = client.GetService('BatchJobService', 'v201609') + batch_job_service = client.GetService('BatchJobService', 'v201710') selector = { 'fields': ['Id', 'Status', 'DownloadUrl'], @@ -370,8 +370,8 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, Args: client: an instantiated AdWordsClient used to poll the BatchJob. batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. Returns: A str containing the downloadUrl of the completed BatchJob. diff --git a/examples/adwords/v201609/campaign_management/add_draft.py b/examples/adwords/v201710/campaign_management/add_draft.py similarity index 97% rename from examples/adwords/v201609/campaign_management/add_draft.py rename to examples/adwords/v201710/campaign_management/add_draft.py index e04ddbf5..4a63c846 100755 --- a/examples/adwords/v201609/campaign_management/add_draft.py +++ b/examples/adwords/v201710/campaign_management/add_draft.py @@ -35,7 +35,7 @@ def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201609') + draft_service = client.GetService('DraftService', version='v201710') draft = { 'baseCampaignId': base_campaign_id, @@ -50,7 +50,7 @@ def main(client, base_campaign_id): # real campaign. For example, you may add criteria, adjust bids, or even # include additional ads. Adding a criteria is shown here. campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201609') + version='v201710') criterion = { 'xsi_type': 'Language', diff --git a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py similarity index 94% rename from examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py rename to examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py index d9a2bfb5..1cb8bfe6 100755 --- a/examples/adwords/v201609/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py @@ -14,11 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. +"""This example illustrates how to incrementally upload keywords. +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. """ import random @@ -37,7 +35,7 @@ def main(client, adgroup_id): # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201609') + batch_job_helper = client.GetBatchJobHelper(version='v201710') # Create a BatchJob. batch_job = AddBatchJob(client) @@ -79,7 +77,7 @@ def AddBatchJob(client): The new BatchJob created by the request. """ # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201609') + batch_job_service = client.GetService('BatchJobService', version='v201710') # Create a BatchJob. batch_job_operations = [{ 'operand': {}, @@ -128,10 +126,10 @@ def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): Args: client: an instantiated AdWordsClient used to cancel the BatchJob. batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has been canceled. """ - batch_job_service = client.GetService('BatchJobService', 'v201609') + batch_job_service = client.GetService('BatchJobService', 'v201710') batch_job['status'] = 'CANCELING' operation = { @@ -171,7 +169,7 @@ def GetBatchJob(client, batch_job_id): Returns: The BatchJob associated with the given id. """ - batch_job_service = client.GetService('BatchJobService', 'v201609') + batch_job_service = client.GetService('BatchJobService', 'v201710') selector = { 'fields': ['Id', 'Status', 'DownloadUrl'], @@ -194,8 +192,8 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, Args: client: an instantiated AdWordsClient used to poll the BatchJob. batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. Returns: A str containing the downloadUrl of the completed BatchJob. diff --git a/examples/adwords/v201702/campaign_management/add_trial.py b/examples/adwords/v201710/campaign_management/add_trial.py similarity index 98% rename from examples/adwords/v201702/campaign_management/add_trial.py rename to examples/adwords/v201710/campaign_management/add_trial.py index a77755a9..00382eef 100755 --- a/examples/adwords/v201702/campaign_management/add_trial.py +++ b/examples/adwords/v201710/campaign_management/add_trial.py @@ -39,9 +39,9 @@ def main(client, base_campaign_id, draft_id): # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201702') + trial_service = client.GetService('TrialService', version='v201710') trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201702') + version='v201710') trial = { 'draftId': draft_id, diff --git a/examples/adwords/v201702/basic_operations/get_text_ads.py b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py similarity index 55% rename from examples/adwords/v201702/basic_operations/get_text_ads.py rename to examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py index 424ceef6..b5e858b7 100755 --- a/examples/adwords/v201702/basic_operations/get_text_ads.py +++ b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py @@ -14,7 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all text ads for a given ad group. +"""This example gets all disapproved ads for a given campaign. + +To add an ad, run add_ads.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -26,18 +28,18 @@ from googleads import adwords -PAGE_SIZE = 500 AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Construct selector and get all ads for a given ad group. offset = 0 selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], + 'fields': ['Id', 'PolicySummary'], 'predicates': [ { 'field': 'AdGroupId', @@ -45,9 +47,9 @@ def main(client, ad_group_id): 'values': [ad_group_id] }, { - 'field': 'AdType', + 'field': 'CombinedApprovalStatus', 'operator': 'EQUALS', - 'values': ['TEXT_AD'] + 'values': 'DISAPPROVED' } ], 'paging': { @@ -55,21 +57,44 @@ def main(client, ad_group_id): 'numberResults': str(PAGE_SIZE) } } + more_pages = True + disapproved_count = 0 + + # Display results. while more_pages: page = ad_group_ad_service.get(selector) - # Display results. if 'entries' in page: for ad in page['entries']: - print ('Ad with id "%s", status "%s", and of type "%s" was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName'], + policy_topic_entry['policyTopicHelpCenterUrl']) + # Display the attributes and values that triggered the policy topic. + policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] + if policy_topic_evidences: + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) + print '%d disapproved ads were found.' % disapproved_count + if __name__ == '__main__': # Initialize client object. diff --git a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..c8d69dd6 --- /dev/null +++ b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', + version='v201710') + + # Construct query and get all ads for a given campaign. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'PolicySummary') + .Where('AdGroupId').EqualTo(ad_group_id) + .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') + .OrderBy('Id') + .Limit(0, PAGE_SIZE) + .Build()) + disapproved_count = 0 + + # Display results. + while True: + page = ad_group_ad_service.query(query) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + # Display the attributes and values that triggered the policy topic. + if ('policyTopicEvidences' in policy_topic_entry + and policy_topic_entry['policyTopicEvidences']): + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + if not query.HasNext(page): + break + query.NextPage() + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py similarity index 98% rename from examples/adwords/v201609/campaign_management/get_campaigns_by_label.py rename to examples/adwords/v201710/campaign_management/get_campaigns_by_label.py index 08b365b3..e3ab0b1a 100755 --- a/examples/adwords/v201609/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -36,7 +35,7 @@ def main(client, label_id): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201710') offset = 0 selector = { @@ -75,7 +74,6 @@ def main(client, label_id): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201702/campaign_management/graduate_trial.py b/examples/adwords/v201710/campaign_management/graduate_trial.py similarity index 99% rename from examples/adwords/v201702/campaign_management/graduate_trial.py rename to examples/adwords/v201710/campaign_management/graduate_trial.py index 324d00f1..c4f1945b 100755 --- a/examples/adwords/v201702/campaign_management/graduate_trial.py +++ b/examples/adwords/v201710/campaign_management/graduate_trial.py @@ -36,8 +36,8 @@ def main(client, trial_id): # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201702') - budget_service = client.GetService('BudgetService', version='v201702') + trial_service = client.GetService('TrialService', version='v201710') + budget_service = client.GetService('BudgetService', version='v201710') # To graduate a trial, you must specify a different budget from the base # campaign. The base campaign (in order to have had a trial based on it) must diff --git a/examples/adwords/v201702/campaign_management/set_ad_parameters.py b/examples/adwords/v201710/campaign_management/set_ad_parameters.py similarity index 99% rename from examples/adwords/v201702/campaign_management/set_ad_parameters.py rename to examples/adwords/v201710/campaign_management/set_ad_parameters.py index 0a4e05b8..e3a54c48 100755 --- a/examples/adwords/v201702/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201710/campaign_management/set_ad_parameters.py @@ -35,8 +35,8 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') - ad_param_service = client.GetService('AdParamService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') + ad_param_service = client.GetService('AdParamService', version='v201710') # Construct operations for adding text ad object and add to an ad group. operations = [{ diff --git a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py similarity index 97% rename from examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py rename to examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py index 9967bed8..e2a524d7 100755 --- a/examples/adwords/v201702/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py @@ -34,7 +34,7 @@ def main(client, campaign_id, bid_modifier): # Initialize appropriate service. campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201702') + 'CampaignCriterionService', version='v201710') # Create mobile platform.The ID can be found in the documentation. # https://developers.google.com/adwords/api/docs/appendix/platforms diff --git a/examples/adwords/v201702/campaign_management/validate_text_ad.py b/examples/adwords/v201710/campaign_management/validate_text_ad.py similarity index 99% rename from examples/adwords/v201702/campaign_management/validate_text_ad.py rename to examples/adwords/v201710/campaign_management/validate_text_ad.py index 472a1591..a5cd9f11 100755 --- a/examples/adwords/v201702/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201710/campaign_management/validate_text_ad.py @@ -36,7 +36,7 @@ def main(client, ad_group_id): # Initialize appropriate service with validate only flag enabled. client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Construct operations to add an expanded text ad. operations = [{ diff --git a/examples/adwords/v201609/error_handling/__init__.py b/examples/adwords/v201710/error_handling/__init__.py similarity index 100% rename from examples/adwords/v201609/error_handling/__init__.py rename to examples/adwords/v201710/error_handling/__init__.py diff --git a/examples/adwords/v201702/error_handling/handle_partial_failures.py b/examples/adwords/v201710/error_handling/handle_partial_failures.py similarity index 97% rename from examples/adwords/v201702/error_handling/handle_partial_failures.py rename to examples/adwords/v201710/error_handling/handle_partial_failures.py index fb040cc9..1a4633ba 100755 --- a/examples/adwords/v201702/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201710/error_handling/handle_partial_failures.py @@ -38,7 +38,7 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') + 'AdGroupCriterionService', version='v201710') # Construct keyword ad group criteria objects. keywords = [ @@ -120,7 +120,7 @@ def main(client, ad_group_id): adgroup_criterion['criterion']['text'], error['errorString'])) else: - print ('A failure has occured for the following reasons: %s\n' + print ('A failure has occurred for the following reasons: %s\n' % error['errorString']) diff --git a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py b/examples/adwords/v201710/error_handling/handle_policy_violation_error.py similarity index 99% rename from examples/adwords/v201702/error_handling/handle_policy_violation_error.py rename to examples/adwords/v201710/error_handling/handle_policy_violation_error.py index 4872235f..cb8f9ac0 100755 --- a/examples/adwords/v201702/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201710/error_handling/handle_policy_violation_error.py @@ -34,7 +34,7 @@ def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201710') # Create expanded text ad that violates an exemptable policy. exemptable_expanded_text_ad_operation = { diff --git a/examples/adwords/v201609/extensions/__init__.py b/examples/adwords/v201710/extensions/__init__.py similarity index 100% rename from examples/adwords/v201609/extensions/__init__.py rename to examples/adwords/v201710/extensions/__init__.py diff --git a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py similarity index 98% rename from examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py rename to examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py index c346ce2a..2410773f 100755 --- a/examples/adwords/v201702/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py @@ -91,7 +91,7 @@ def main(client, gmb_email_address, gmb_access_token, 'operand': feed }] - gmb_response = client.GetService('FeedService', version='v201702').mutate( + gmb_response = client.GetService('FeedService', version='v201710').mutate( gmb_operations) added_feed = gmb_response['value'][0] print 'Added GMB feed with ID: %d\n' % added_feed['id'] @@ -119,7 +119,7 @@ def main(client, gmb_email_address, gmb_access_token, } customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201702') + 'CustomerFeedService', version='v201710') added_customer_feed = None i = 0 diff --git a/examples/adwords/v201702/extensions/add_prices.py b/examples/adwords/v201710/extensions/add_prices.py similarity index 97% rename from examples/adwords/v201702/extensions/add_prices.py rename to examples/adwords/v201710/extensions/add_prices.py index 62d0f3a8..b1856b3d 100755 --- a/examples/adwords/v201702/extensions/add_prices.py +++ b/examples/adwords/v201710/extensions/add_prices.py @@ -38,7 +38,7 @@ def main(client, campaign_id): # Initialize appropriate service. customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201702') + 'CustomerExtensionSettingService', 'v201710') # To create a price extension, at least three table rows are needed. table_rows = [ @@ -48,7 +48,7 @@ def main(client, campaign_id): final_mobile_url='http://m.example.com/scrubs'), CreatePriceTableRow('Hair Cuts', 'Once a month', 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', final_mobile_url='http://m.example.com/haircuts'), CreatePriceTableRow('Skin Care Package', 'Four times a month', 'https://www.examples.com/skincarepackage', diff --git a/examples/adwords/v201702/extensions/add_site_links.py b/examples/adwords/v201710/extensions/add_site_links.py similarity index 98% rename from examples/adwords/v201702/extensions/add_site_links.py rename to examples/adwords/v201710/extensions/add_site_links.py index ef29007c..0405eef8 100755 --- a/examples/adwords/v201702/extensions/add_site_links.py +++ b/examples/adwords/v201710/extensions/add_site_links.py @@ -36,8 +36,8 @@ def main(client, campaign_id): # Initialize appropriate services. campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201702') - customer_service = client.GetService('CustomerService', version='v201702') + 'CampaignExtensionSettingService', version='v201710') + customer_service = client.GetService('CustomerService', version='v201710') # Find the matching customer and its time zone. The getCustomers method will # return a single Customer object corresponding to the configured # clientCustomerId. diff --git a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py b/examples/adwords/v201710/extensions/add_site_links_using_feeds.py similarity index 98% rename from examples/adwords/v201702/extensions/add_site_links_using_feeds.py rename to examples/adwords/v201710/extensions/add_site_links_using_feeds.py index e7e83d18..a80525df 100755 --- a/examples/adwords/v201702/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201710/extensions/add_site_links_using_feeds.py @@ -46,12 +46,12 @@ def main(client, campaign_id): # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201702') - feed_item_service = client.GetService('FeedItemService', version='v201702') + feed_service = client.GetService('FeedService', version='v201710') + feed_item_service = client.GetService('FeedItemService', version='v201710') feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201702') + 'FeedMappingService', version='v201710') campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201702') + 'CampaignFeedService', version='v201710') sitelinks_data = {} diff --git a/examples/adwords/v201609/migration/__init__.py b/examples/adwords/v201710/migration/__init__.py similarity index 100% rename from examples/adwords/v201609/migration/__init__.py rename to examples/adwords/v201710/migration/__init__.py diff --git a/examples/adwords/v201702/migration/migrate_to_extension_settings.py b/examples/adwords/v201710/migration/migrate_to_extension_settings.py similarity index 98% rename from examples/adwords/v201702/migration/migrate_to_extension_settings.py rename to examples/adwords/v201710/migration/migrate_to_extension_settings.py index efb27656..8302525d 100755 --- a/examples/adwords/v201702/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201710/migration/migrate_to_extension_settings.py @@ -52,7 +52,6 @@ 'TRACKING_URL_TEMPLATE': 7 } - PAGE_SIZE = 500 @@ -69,7 +68,7 @@ def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, platform_restrictions: an optional Platform Restriction for the Feed items. """ campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201702') + 'CampaignExtensionSettingService', 'v201710') extension_feed_items = [{ CreateSitelinkFeedItem(feed_items, feed_item_id) @@ -140,7 +139,7 @@ def DeleteCampaignFeed(client, campaign_feed): client: an AdWordsClient instance. campaign_feed: the campaign feed to delete. """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201702') + campaign_feed_service = client.GetService('CampaignFeedService', 'v201710') operation = { 'operand': campaign_feed, @@ -161,7 +160,7 @@ def DeleteOldFeedItems(client, feed_item_ids, feed): if not feed_item_ids: return - feed_item_service = client.GetService('FeedItemService', 'v201702') + feed_item_service = client.GetService('FeedItemService', 'v201710') operations = [{ 'operator': 'REMOVE', @@ -185,7 +184,7 @@ def GetCampaignFeeds(client, feed, placeholder_type): Returns: A list of Feed Item Ids. """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201702') + campaign_feed_service = client.GetService('CampaignFeedService', 'v201710') campaign_feeds = [] more_pages = True @@ -236,7 +235,7 @@ def GetFeeds(client): Returns: A list containing all enabled Feeds. """ - feed_service = client.GetService('FeedService', 'v201702') + feed_service = client.GetService('FeedService', 'v201710') feeds = [] more_pages = True @@ -283,7 +282,7 @@ def GetFeedItems(client, feed): Returns: The Feed Items associated with the given Feed. """ - feed_item_service = client.GetService('FeedItemService', 'v201702') + feed_item_service = client.GetService('FeedItemService', 'v201710') feed_items = [] more_pages = True @@ -359,7 +358,7 @@ def GetFeedMapping(client, feed, placeholder_type): Returns: A dictionary containing the Feed Mapping. """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201702') + feed_mapping_service = client.GetService('FeedMappingService', 'v201710') attribute_mappings = {} more_pages = True diff --git a/examples/adwords/v201609/misc/__init__.py b/examples/adwords/v201710/misc/__init__.py similarity index 100% rename from examples/adwords/v201609/misc/__init__.py rename to examples/adwords/v201710/misc/__init__.py diff --git a/examples/adwords/v201702/misc/get_all_images_and_videos.py b/examples/adwords/v201710/misc/get_all_images_and_videos.py similarity index 99% rename from examples/adwords/v201702/misc/get_all_images_and_videos.py rename to examples/adwords/v201710/misc/get_all_images_and_videos.py index 530b1dad..98a258aa 100755 --- a/examples/adwords/v201702/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201710/misc/get_all_images_and_videos.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201702') + media_service = client.GetService('MediaService', version='v201710') # Construct selector and get all images. offset = 0 diff --git a/examples/adwords/v201609/misc/upload_image.py b/examples/adwords/v201710/misc/upload_image.py similarity index 99% rename from examples/adwords/v201609/misc/upload_image.py rename to examples/adwords/v201710/misc/upload_image.py index fa4bbe52..ba035520 100755 --- a/examples/adwords/v201609/misc/upload_image.py +++ b/examples/adwords/v201710/misc/upload_image.py @@ -35,7 +35,7 @@ def main(client, image_filename): # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201609') + media_service = client.GetService('MediaService', version='v201710') with open(image_filename, 'rb') as image_handle: image_data = base64.encodestring(image_handle.read()).decode('utf-8') diff --git a/examples/adwords/v201609/misc/upload_media_bundle.py b/examples/adwords/v201710/misc/upload_media_bundle.py similarity index 93% rename from examples/adwords/v201609/misc/upload_media_bundle.py rename to examples/adwords/v201710/misc/upload_media_bundle.py index fee2cc1b..966f4b63 100755 --- a/examples/adwords/v201609/misc/upload_media_bundle.py +++ b/examples/adwords/v201710/misc/upload_media_bundle.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201609') + media_service = client.GetService('MediaService', version='v201710') # Create HTML5 media. base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( 'https://goo.gl/9Y7qI2') @@ -50,7 +50,8 @@ def main(client): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201609/optimization/__init__.py b/examples/adwords/v201710/optimization/__init__.py similarity index 100% rename from examples/adwords/v201609/optimization/__init__.py rename to examples/adwords/v201710/optimization/__init__.py diff --git a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py b/examples/adwords/v201710/optimization/estimate_keyword_traffic.py similarity index 99% rename from examples/adwords/v201609/optimization/estimate_keyword_traffic.py rename to examples/adwords/v201710/optimization/estimate_keyword_traffic.py index 70c3ea73..0b96d72a 100755 --- a/examples/adwords/v201609/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201710/optimization/estimate_keyword_traffic.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201609') + 'TrafficEstimatorService', version='v201710') # Construct selector object and retrieve traffic estimates. keywords = [ diff --git a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py similarity index 96% rename from examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py rename to examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py index 0e2d96a0..2139b135 100755 --- a/examples/adwords/v201702/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ b/examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -29,12 +29,12 @@ CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 +PAGE_SIZE = 100 def main(client, campaign_id): # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201702') + data_service = client.GetService('DataService', version='v201710') # Get all the campaigns for this account. selector = { @@ -83,10 +83,11 @@ def main(client, campaign_id): else: print 'No bid modifier landscapes found.' - # Need to increment by the total # of landscape points within the page. + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. offset += num_landscape_points selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) + more_pages = num_landscape_points >= PAGE_SIZE if __name__ == '__main__': diff --git a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201710/optimization/get_keyword_bid_simulations.py similarity index 68% rename from examples/adwords/v201702/optimization/get_keyword_bid_simulations.py rename to examples/adwords/v201710/optimization/get_keyword_bid_simulations.py index e564882e..c25bf993 100755 --- a/examples/adwords/v201702/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201710/optimization/get_keyword_bid_simulations.py @@ -30,11 +30,12 @@ AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' CRITERION_ID = 'INSERT_CRITERION_ID_HERE' +PAGE_SIZE = 100 def main(client, ad_group_id, criterion_id): # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201702') + data_service = client.GetService('DataService', version='v201710') # Construct bid landscape selector object and retrieve bid landscape. selector = { @@ -51,27 +52,44 @@ def main(client, ad_group_id, criterion_id): 'operator': 'EQUALS', 'values': [criterion_id] } - ] + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id "%s", criterion id ' - '"%s", start date "%s", end date "%s", with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages: + num_landscape_points = 0 + page = data_service.getCriterionBidLandscape(selector) + + if page and 'entries' in page: + entries = page['entries'] + print 'Bid landscape(s) retrieved: %d.' % len(entries) + + for bid_landscape in entries: + print ('Retrieved keyword bid landscape with ad group ID "%d", ' + 'keyword ID "%d", start date "%s", end date "%s", ' + 'with landscape points:' % ( + bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) for bid_landscape_point in bid_landscape['landscapePoints']: + num_landscape_points += 1 print (' bid: %s => clicks: %s, cost: %s, impressions: %s' % (bid_landscape_point['bid']['microAmount'], bid_landscape_point['clicks'], bid_landscape_point['cost']['microAmount'], bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE if __name__ == '__main__': diff --git a/examples/adwords/v201609/optimization/get_keyword_ideas.py b/examples/adwords/v201710/optimization/get_keyword_ideas.py similarity index 56% rename from examples/adwords/v201609/optimization/get_keyword_ideas.py rename to examples/adwords/v201710/optimization/get_keyword_ideas.py index 3f2cfc5f..a307aac8 100755 --- a/examples/adwords/v201609/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201710/optimization/get_keyword_ideas.py @@ -26,49 +26,62 @@ from googleads import adwords +# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' PAGE_SIZE = 100 -def main(client): +def main(client, ad_group_id=None): # Initialize appropriate service. targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201609') + 'TargetingIdeaService', version='v201710') # Construct selector object and retrieve related keywords. - offset = 0 selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } + 'requestType': 'IDEAS' + } + + selector['requestedAttributeTypes'] = [ + 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] + + offset = 0 + selector['paging'] = { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) } + + selector['searchParameters'] = [{ + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }] + + # Language setting (optional). + selector['searchParameters'].append({ + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }) + + # Network search parameter (optional) + selector['searchParameters'].append({ + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + }) + + # Use an existing ad group to generate ideas (optional) + if ad_group_id is not None: + selector['searchParameters'].append({ + 'xsi_type': 'SeedAdGroupIdSearchParameter', + 'adGroupId': ad_group_id + }) + more_pages = True while more_pages: page = targeting_idea_service.get(selector) @@ -78,8 +91,8 @@ def main(client): for result in page['entries']: attributes = {} for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') + attributes[attribute['key']] = getattr( + attribute['value'], 'value', '0') print ('Keyword with "%s" text and average monthly search volume ' '"%s" was found with Products and Services categories: %s.' % (attributes['KEYWORD_TEXT'], @@ -97,4 +110,4 @@ def main(client): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) + main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201609/remarketing/__init__.py b/examples/adwords/v201710/remarketing/__init__.py similarity index 100% rename from examples/adwords/v201609/remarketing/__init__.py rename to examples/adwords/v201710/remarketing/__init__.py diff --git a/examples/adwords/v201702/remarketing/add_audience.py b/examples/adwords/v201710/remarketing/add_audience.py similarity index 96% rename from examples/adwords/v201702/remarketing/add_audience.py rename to examples/adwords/v201710/remarketing/add_audience.py index 1825d482..f9fd2d60 100755 --- a/examples/adwords/v201702/remarketing/add_audience.py +++ b/examples/adwords/v201710/remarketing/add_audience.py @@ -31,9 +31,9 @@ def main(client): # Initialize appropriate service. user_list_service = client.GetService( - 'AdwordsUserListService', version='v201702') + 'AdwordsUserListService', version='v201710') conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201702') + 'ConversionTrackerService', version='v201710') # Construct operations and add a user list. operations = [ diff --git a/examples/adwords/v201609/remarketing/add_conversion_tracker.py b/examples/adwords/v201710/remarketing/add_conversion_tracker.py similarity index 97% rename from examples/adwords/v201609/remarketing/add_conversion_tracker.py rename to examples/adwords/v201710/remarketing/add_conversion_tracker.py index 44ef43f1..0b059389 100755 --- a/examples/adwords/v201609/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201710/remarketing/add_conversion_tracker.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201609') + 'ConversionTrackerService', version='v201710') # Construct operations and add conversion_tracker. operations = [ diff --git a/examples/adwords/v201710/remarketing/add_conversion_trackers.py b/examples/adwords/v201710/remarketing/add_conversion_trackers.py new file mode 100755 index 00000000..1bf5ed31 --- /dev/null +++ b/examples/adwords/v201710/remarketing/add_conversion_trackers.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds AdWords conversion trackers. + +Adds an AdWords conversion tracker and an upload conversion tracker. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201710') + + # Create an AdWords conversion tracker. + adwords_conversion_tracker = { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'name': 'Upload Conversion #%s' % uuid.uuid4(), + # Optional fields. + # Set an appropriate category. This will be set to DEFAULT if not + # specified. + 'category': 'LEAD', + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90', + # Set the default currency code to use for conversions that do + # not specify a conversion currency. This must be an ISO 4217 3-character + # code such as "EUR" or "USD". + # If this field is not set, AdWords will use the account's currency. + 'defaultRevenueCurrencyCode': 'EUR', + # Set the default revenue value to use for conversions that do not specify + # a converison value. Note that this value should NOT be in micros. + 'defaultRevenueValue': '2.50', + # To upload fractional conversion credits, mark the upload conversion as + # externally attributed. To learn more about importing externally + # attributed conversions, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'isExternallyAttributed': 'true' + } + + # Construct operations. + operations = [{ + 'operator': 'ADD', + 'operand': conversion_tracker + } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] + + # Add the conversions. + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + if (conversion_tracker['ConversionTracker.Type'] + is 'AdWordsConversionTracker'): + print ('Conversion tracker with ID "%d", name "%s", status "%s" ' + 'and category "%s" and snippet \n"%s"\n was added.' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'], + conversion_tracker['snippet'])) + else: + print ('Conversion with ID "%d", name "%s", status "%s", and category ' + '"%s" was added.' + % (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py b/examples/adwords/v201710/remarketing/add_crm_based_user_list.py similarity index 72% rename from examples/adwords/v201609/remarketing/add_crm_based_user_list.py rename to examples/adwords/v201710/remarketing/add_crm_based_user_list.py index 75b54471..faaf9c84 100755 --- a/examples/adwords/v201609/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201710/remarketing/add_crm_based_user_list.py @@ -31,9 +31,9 @@ from googleads import adwords -def main(client, emails): +def main(client): # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201609') + user_list_service = client.GetService('AdwordsUserListService', 'v201710') user_list = { 'xsi_type': 'CrmBasedUserList', @@ -51,13 +51,26 @@ def main(client, emails): result = user_list_service.mutate(operations) user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) + + emails = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] + + # Optional: AddressInfo is only accessible to whitelisted customers. + # If you are not on the whitelist, you should leave this code commented out. + # members.append({ + # 'addressInfo': { + # 'hashedFirstName': NormalizeAndSHA256('John'), + # 'hashedLastName': NormalizeAndSHA256('Doe'), + # 'countryCode': 'US', + # 'zipCode': '10001' + # } + # }) mutate_members_operation = { 'operand': { 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails + 'membersList': members }, 'operator': 'ADD' } @@ -70,25 +83,19 @@ def main(client, emails): % (user_list['name'], user_list['id'])) -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. +def NormalizeAndSHA256(s): + """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. Args: - emails: list of str emails to be hashed. + s: The string to perform this operation on. Returns: - A list of SHA-256 hashed emails. + A normalized and SHA-256 hashed string. """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + return hashlib.sha256(s.strip().lower()).hexdigest() if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) + main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201710/remarketing/add_rule_based_user_lists.py similarity index 75% rename from examples/adwords/v201702/remarketing/add_rule_based_user_lists.py rename to examples/adwords/v201710/remarketing/add_rule_based_user_lists.py index 907e2fa2..521d2cee 100755 --- a/examples/adwords/v201702/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201710/remarketing/add_rule_based_user_lists.py @@ -38,7 +38,7 @@ def main(client): # Initialize appropriate service. adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201702') + 'AdwordsUserListService', version='v201710') # First rule item group - users who visited the checkout page and had more # than one item in their shopping cart. @@ -97,13 +97,49 @@ def main(client): 'items': [start_date_rule_item, three_months_later_rule_item] } - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. + # Combine the rule item groups into a Rule so AdWords knows how to apply the + # rules. rule = { 'groups': [ checkout_multiple_item_group, checked_out_date_range_item_group - ] + ], + # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF + # means 'at least one item in each rule item group must match', and DNF + # means 'at least one entire rule item group must match'. + # DateSpecificRuleUserList only supports DNF. You can also omit the rule + # type altogether to default to DNF. + 'ruleType': 'DNF' + } + + # Third and fourth rule item groups. + # Visitors of a page who visited another page. + site1_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example1' + } + } + site2_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example2' + } + } + + # Create two rules to show that a visitor browsed two sites. + user_visited_site1_rule = { + 'groups': [{ + 'items': [site1_rule_item] + }] + } + + user_visited_site2_rule = { + 'groups': [{ + 'items': [site2_rule_item] + }] } # Create the user list with no restrictions on site visit date. @@ -137,12 +173,25 @@ def main(client): 'endDate': end_date.strftime('%Y%m%d') } + # Create the user list for "Visitors of a page who did visit another page". + # To create a user list for "Visitors of a page who did not visit another + # page", change the ruleOperator from AND to AND_NOT. + combined_user_list = { + 'xsi_type': 'CombinedRuleUserList', + 'name': 'Combined rule user lst create at ${creation_time}', + 'description': 'Users who visited two sites.', + 'leftOperand': user_visited_site1_rule, + 'rightOperand': user_visited_site2_rule, + 'ruleOperator': 'AND' + } + # Create operations to add the user lists. operations = [ { 'operand': user_list, 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] + } for user_list in [expression_user_list, date_user_list, + combined_user_list] ] # Submit the operations. diff --git a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201710/remarketing/upload_offline_call_conversions.py similarity index 95% rename from examples/adwords/v201609/remarketing/upload_offline_call_conversions.py rename to examples/adwords/v201710/remarketing/upload_offline_call_conversions.py index d8efc864..4bb6851b 100755 --- a/examples/adwords/v201609/remarketing/upload_offline_call_conversions.py +++ b/examples/adwords/v201710/remarketing/upload_offline_call_conversions.py @@ -16,7 +16,7 @@ """Imports offline conversion values for calls related to ads in your account. -To set up a conversion tracker, run the add_conversion_tracker.py example. +To set up a conversion tracker, run the add_conversion_trackers.py example. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -43,7 +43,7 @@ def main(client, caller_id, call_start_time, conversion_name, conversion_time, conversion_value): # Initialize appropriate services. occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201609') + 'OfflineCallConversionFeedService', version='v201710') # Associate offline call conversions with the existing named conversion # tracker. If this tracker was newly created, it may be a few hours before it diff --git a/examples/adwords/v201702/remarketing/upload_offline_conversions.py b/examples/adwords/v201710/remarketing/upload_offline_conversions.py similarity index 79% rename from examples/adwords/v201702/remarketing/upload_offline_conversions.py rename to examples/adwords/v201710/remarketing/upload_offline_conversions.py index c80147aa..7671c7b5 100755 --- a/examples/adwords/v201702/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201710/remarketing/upload_offline_conversions.py @@ -17,7 +17,7 @@ """Imports offline conversion values for specific clicks into your account. To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. +up a conversion tracker, run the add_conversion_trackers.py example. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -40,7 +40,7 @@ def main(client, conversion_name, click_id, conversion_time, conversion_value): # Initialize appropriate services. offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201702') + 'OfflineConversionFeedService', version='v201710') # Associate offline conversions with the existing named conversion tracker. If # this tracker was newly created, it may be a few hours before it can accept @@ -49,7 +49,14 @@ def main(client, conversion_name, click_id, conversion_time, conversion_value): 'conversionName': conversion_name, 'conversionTime': conversion_time, 'conversionValue': conversion_value, - 'googleClickId': click_id + 'googleClickId': click_id, + # Optional: To upload fractional conversion credits, set the external + # attribution model and credit. To use this feature, your conversion + # tracker should be marked as externally attributed. To learn more about + # importing externally attributed conversins, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'externalAttributionCredit': 0.3, + # 'externalAttributionModel': 'Linear' } offline_conversion_operation = { diff --git a/examples/adwords/v201710/remarketing/upload_offline_data.py b/examples/adwords/v201710/remarketing/upload_offline_data.py new file mode 100755 index 00000000..7004738f --- /dev/null +++ b/examples/adwords/v201710/remarketing/upload_offline_data.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 shows how to upload offline data for store sales transactions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import datetime +import hashlib + +from googleads import adwords +import pytz + + +_DT_FORMAT = '%Y%m%d %H%M%S' +# User identifier types whose values must be hashed. +_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', + 'HASHED_LAST_NAME', 'HASHED_PHONE') +# The timezone to be used in this example. For valid timezone IDs, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +_TIMEZONE = pytz.timezone('America/New_York') +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Insert email addresses below for creating user identifiers. +EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] +# The external upload ID can be any number that you use to keep track of your +# uploads. +EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' +# Store sales upload common metadata types +METADATA_TYPE_1P = 'FirstPartyUploadMetadata' +METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' +# Set the below constant to METADATA_TYPE_3P if uploading third-party data. +STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P +# The three constants below are needed when uploading third-party data. They +# are not used when uploading first-party data. +# Advertiser upload time to partner. +# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, +# see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' +# Indicates the version of the bridge map. +BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' +# The ID of the third party uploading the transaction feed. +PARTNER_ID = 'INSERT_PARTNER_ID_HERE' + + +def main(client, conversion_name, external_upload_id, + store_sales_upload_common_metadata_type, email_addresses, + advertiser_upload_time=None, bridge_map_version_id=None, + partner_id=None): + # Initialize appropriate services. + offline_data_upload_service = client.GetService( + 'OfflineDataUploadService', version='v201710') + + # Create the first offline data for upload. + # This transaction occurred 7 days ago with an amount of $200 USD. + transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=7)) + offline_data_1 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[0]), + _CreateUserIdentifier(identifier_type='STATE', value='New York') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_1), + 'transactionAmount': { + 'currencyCode': 'USD', + 'money': { + 'microAmount': 200000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create the second offline data for upload. + # This transaction occurred 14 days ago with amount of 450 EUR. + transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=14)) + offline_data_2 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[1]), + _CreateUserIdentifier(identifier_type='STATE', value='California') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_2), + 'transactionAmount': { + 'currencyCode': 'EUR', + 'money': { + 'microAmount': 450000000 + } + }, + 'conversionName': conversion_name + } + } + + # Set the type and metadata of this upload. + upload_metadata = { + 'StoreSalesUploadCommonMetadata': { + 'xsi_type': store_sales_upload_common_metadata_type, + 'loyaltyRate': 1.0, + 'transactionUploadRate': 1.0, + } + } + + if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: + upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' + elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: + upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' + upload_metadata['StoreSalesUploadCommonMetadata'].update({ + 'advertiserUploadTime': advertiser_upload_time, + 'validTransactionRate': 1.0, + 'partnerMatchRate': 1.0, + 'partnerUploadRate': 1.0, + 'bridgeMapVersionId': bridge_map_version_id, + 'partnerId': partner_id + }) + else: + raise ValueError('Unknown metadata type.') + + # Create offline data upload + offline_data_upload = { + 'externalUploadId': external_upload_id, + 'offlineDataList': [offline_data_1, offline_data_2], + # Set the type of this upload. + 'uploadType': upload_type, + 'uploadMetadata': upload_metadata + } + + # Create an offline data upload operation. + operations = [{ + 'operator': 'ADD', + 'operand': offline_data_upload + }] + + # Upload offline data on the server and print the result. + result = offline_data_upload_service.mutate(operations) + offline_data_upload = result['value'][0] + + print ('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) + + # Print any partial data errors from the response. The order of the partial + # data errors list is the same as the uploaded offline data list in the + # request. + for i, partial_data_error in enumerate( + offline_data_upload['partialDataErrors']): + # If a partial error occurred for this offline data, print the error. Note + # that non-errors for a given offline data would be set to None. + if partial_data_error: + print ('Found a partial error for offline data #%d with error string: %s' + % (i, partial_data_error['errorString'])) + + +def _CreateUserIdentifier(identifier_type=None, value=None): + """Creates a user identifier from the specified type and value. + + Args: + identifier_type: a str specifying the type of user identifier. + value: a str value of the identifier; to be hashed using SHA-256 if needed. + + Returns: + A dict specifying a user identifier, with a value hashed using SHA-256 if + needed. + """ + if identifier_type in _HASHED_IDENTIFIER_TYPES: + # If the user identifier type is a hashed type, normalize and hash the + # value. + value = hashlib.sha256(value.strip().lower()).hexdigest() + + user_identifier = { + 'userIdentifierType': identifier_type, + 'value': value + } + + return user_identifier + + +def _GetFormattedDateTime(dt): + """Formats the given datetime and timezone for use with AdWords. + + Args: + dt: a datetime instance. + + Returns: + A str representation of the datetime in the correct format for AdWords. + """ + return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, + STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, + ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201609/reporting/__init__.py b/examples/adwords/v201710/reporting/__init__.py similarity index 100% rename from examples/adwords/v201609/reporting/__init__.py rename to examples/adwords/v201710/reporting/__init__.py diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py similarity index 82% rename from examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py rename to examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py index 0514d0ff..6bd15e45 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py @@ -44,14 +44,17 @@ def main(client): # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201609') + report_downloader = client.GetReportDownloader(version='v201710') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py similarity index 97% rename from examples/adwords/v201609/reporting/download_criteria_report_as_stream.py rename to examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py index 3beaf5ed..0c453b81 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_stream.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py @@ -40,7 +40,7 @@ def main(client): - report_downloader = client.GetReportDownloader(version='v201609') + report_downloader = client.GetReportDownloader(version='v201710') # Create report definition. report = { diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py similarity index 76% rename from examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py rename to examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py index c482909a..fcf87588 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py @@ -34,14 +34,17 @@ def main(client): # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201609') + report_downloader = client.GetReportDownloader(version='v201710') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py similarity index 96% rename from examples/adwords/v201609/reporting/download_criteria_report_as_string.py rename to examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py index fd34b76f..536d32d7 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_as_string.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py @@ -34,7 +34,7 @@ def main(client): - report_downloader = client.GetReportDownloader(version='v201609') + report_downloader = client.GetReportDownloader(version='v201710') # Create report definition. report = { diff --git a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py similarity index 57% rename from examples/adwords/v201609/reporting/download_criteria_report_with_awql.py rename to examples/adwords/v201710/reporting/download_criteria_report_with_awql.py index 3ec66566..38bf210c 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py @@ -25,35 +25,34 @@ """ +import sys from googleads import adwords -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): +def main(client): # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201609') + report_downloader = client.GetReportDownloader(version='v201710') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - print 'Report was downloaded to "%s".' % path + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + # You can provide a file object to write the output to. For this + # demonstration we use sys.stdout to write the report to the screen. + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', sys.stdout, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, PATH) + main(adwords_client) diff --git a/examples/adwords/v201609/reporting/download_criteria_report.py b/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py similarity index 95% rename from examples/adwords/v201609/reporting/download_criteria_report.py rename to examples/adwords/v201710/reporting/download_criteria_report_with_selector.py index 993e67c6..0e262215 100755 --- a/examples/adwords/v201609/reporting/download_criteria_report.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py @@ -35,9 +35,8 @@ def main(client): - report_downloader = client.GetReportDownloader(version='v201609') + report_downloader = client.GetReportDownloader(version='v201710') - # Create report definition. report = { 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', 'dateRangeType': 'LAST_7_DAYS', diff --git a/examples/adwords/v201702/reporting/get_report_fields.py b/examples/adwords/v201710/reporting/get_report_fields.py similarity index 96% rename from examples/adwords/v201702/reporting/get_report_fields.py rename to examples/adwords/v201710/reporting/get_report_fields.py index 77531ed7..5d6b7fa9 100755 --- a/examples/adwords/v201702/reporting/get_report_fields.py +++ b/examples/adwords/v201710/reporting/get_report_fields.py @@ -32,7 +32,7 @@ def main(client, report_type): # Initialize appropriate service. report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201702') + 'ReportDefinitionService', version='v201710') # Get report fields. fields = report_definition_service.getReportFields(report_type) diff --git a/examples/adwords/v201609/reporting/parallel_report_download.py b/examples/adwords/v201710/reporting/parallel_report_download.py similarity index 99% rename from examples/adwords/v201609/reporting/parallel_report_download.py rename to examples/adwords/v201710/reporting/parallel_report_download.py index 136080f4..0f916494 100755 --- a/examples/adwords/v201609/reporting/parallel_report_download.py +++ b/examples/adwords/v201710/reporting/parallel_report_download.py @@ -128,7 +128,7 @@ def __init__(self, client, report_download_directory, report_definition, downloads will be saved to. """ super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201609') + self.report_downloader = client.GetReportDownloader(version='v201710') self.report_download_directory = report_download_directory self.report_definition = report_definition self.input_queue = input_queue @@ -191,7 +191,7 @@ def GetCustomerIDs(client): # For this example, we will use ManagedCustomerService to get all IDs in # hierarchy that do not belong to MCC accounts. managed_customer_service = client.GetService('ManagedCustomerService', - version='v201609') + version='v201710') offset = 0 diff --git a/examples/adwords/v201609/shopping/__init__.py b/examples/adwords/v201710/shopping/__init__.py similarity index 100% rename from examples/adwords/v201609/shopping/__init__.py rename to examples/adwords/v201710/shopping/__init__.py diff --git a/examples/adwords/v201702/shopping/add_product_partition_tree.py b/examples/adwords/v201710/shopping/add_product_partition_tree.py similarity index 91% rename from examples/adwords/v201702/shopping/add_product_partition_tree.py rename to examples/adwords/v201710/shopping/add_product_partition_tree.py index c31a4fdb..0897675e 100755 --- a/examples/adwords/v201702/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201710/shopping/add_product_partition_tree.py @@ -33,19 +33,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -53,6 +40,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): @@ -158,7 +156,7 @@ def CreateAddOperation(self, criterion): def main(client, adgroup_id): """Runs the example.""" adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') + 'AdGroupCriterionService', version='v201710') helper = ProductPartitionHelper(adgroup_id) diff --git a/examples/adwords/v201702/shopping/add_product_scope.py b/examples/adwords/v201710/shopping/add_product_scope.py similarity index 98% rename from examples/adwords/v201702/shopping/add_product_scope.py rename to examples/adwords/v201710/shopping/add_product_scope.py index a9d24334..65b384c7 100755 --- a/examples/adwords/v201702/shopping/add_product_scope.py +++ b/examples/adwords/v201710/shopping/add_product_scope.py @@ -32,7 +32,7 @@ def main(client, campaign_id): campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201702') + 'CampaignCriterionService', version='v201710') product_scope = { 'xsi_type': 'ProductScope', diff --git a/examples/adwords/v201609/shopping/add_shopping_campaign.py b/examples/adwords/v201710/shopping/add_shopping_campaign.py similarity index 62% rename from examples/adwords/v201609/shopping/add_shopping_campaign.py rename to examples/adwords/v201710/shopping/add_shopping_campaign.py index 6549b688..81815a25 100755 --- a/examples/adwords/v201609/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201710/shopping/add_shopping_campaign.py @@ -30,13 +30,17 @@ from googleads import adwords BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +# If set to true, a default partition will be created. If running the +# add_product_partition_tree.py example right after this example, make +# sure this stays set to false. +CREATE_DEFAULT_PARTITION = False MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201609') - ad_group_service = client.GetService('AdGroupService', version='v201609') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') +def main(client, budget_id, merchant_id, create_default_partition): + campaign_service = client.GetService('CampaignService', version='v201710') + ad_group_service = client.GetService('AdGroupService', version='v201710') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Create campaign campaign = { @@ -79,26 +83,26 @@ def main(client, budget_id, merchant_id): % (campaign['name'], campaign['id'])) # Create the AdGroup - adgroup = { + ad_group = { 'campaignId': campaign['id'], 'name': 'AdGroup #%s' % uuid.uuid4() } adgroup_operations = { 'operator': 'ADD', - 'operand': adgroup + 'operand': ad_group } # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] - for adgroup in ad_group_result['value']: - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) + print ('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) # Create an AdGroup Ad adgroup_ad = { - 'adGroupId': adgroup['id'], + 'adGroupId': ad_group_id, # Create ProductAd 'ad': { 'xsi_type': 'ProductAd', @@ -117,9 +121,52 @@ def main(client, budget_id, merchant_id): for adgroup_ad in ad_result['value']: print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201710') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + }, + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 500000 + } + }] + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID, MERCHANT_ID) + main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py similarity index 91% rename from examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py rename to examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py index 1931f6c7..f8c1959f 100755 --- a/examples/adwords/v201702/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py @@ -38,19 +38,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -58,6 +45,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): @@ -112,6 +110,8 @@ def CreateUnit(self, parent=None, value=None, bid_amount=None): unit['caseValue'] = value if bid_amount is not None and bid_amount > 0: + # Note: Showcase ads require either ManualCpc or EnhancedCpc in the + # campaign's BiddingStrategyConfiguration. bidding_strategy_configuration = { 'bids': [{ 'xsi_type': 'CpcBid', @@ -193,7 +193,7 @@ def CreateShoppingCampaign(client, budget_id, merchant_id): Returns: The created Shopping Campaign as a sudsobject. """ - campaign_service = client.GetService('CampaignService', 'v201702') + campaign_service = client.GetService('CampaignService', 'v201710') campaign = { 'name': 'Shopping campaign #%s' % uuid.uuid4(), @@ -245,7 +245,7 @@ def CreateAdGroup(client, campaign_id): Returns: The created AdGroup as a sudsobject. """ - ad_group_service = client.GetService('AdGroupService', 'v201702') + ad_group_service = client.GetService('AdGroupService', 'v201710') adgroup = { # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS @@ -295,7 +295,7 @@ def CreateShowcaseAd(client, adgroup, expanded_image_filepath, Returns: The created Showcase Ad as a sudsobject. """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201710') showcase_ad = { 'adGroupId': adgroup['id'], @@ -341,7 +341,7 @@ def UploadImage(client, filepath): Returns: The created Image as a sudsobject. """ - media_service = client.GetService('MediaService', 'v201702') + media_service = client.GetService('MediaService', 'v201710') with open(filepath, 'rb') as image_handle: image_data = base64.encodestring(image_handle.read()).decode('utf-8') @@ -368,7 +368,7 @@ def CreateProductPartition(client, adgroup_id): The ProductPartition tree as a sudsobject. """ ad_group_criterion_service = client.GetService('AdGroupCriterionService', - 'v201702') + 'v201710') helper = ProductPartitionHelper(adgroup_id) root = helper.CreateSubdivision() diff --git a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py b/examples/adwords/v201710/shopping/get_product_category_taxonomy.py similarity index 99% rename from examples/adwords/v201702/shopping/get_product_category_taxonomy.py rename to examples/adwords/v201710/shopping/get_product_category_taxonomy.py index af75ea9d..8a769c26 100755 --- a/examples/adwords/v201702/shopping/get_product_category_taxonomy.py +++ b/examples/adwords/v201710/shopping/get_product_category_taxonomy.py @@ -29,7 +29,7 @@ def main(client): - service = client.GetService('ConstantDataService', version='v201702') + service = client.GetService('ConstantDataService', version='v201710') selector = { 'predicates': [ diff --git a/examples/adwords/v201609/targeting/__init__.py b/examples/adwords/v201710/targeting/__init__.py similarity index 100% rename from examples/adwords/v201609/targeting/__init__.py rename to examples/adwords/v201710/targeting/__init__.py diff --git a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py similarity index 98% rename from examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py rename to examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py index 00828814..1b464c56 100755 --- a/examples/adwords/v201702/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py @@ -39,7 +39,7 @@ def main(client, campaign_id, location_feed_id=None): # Initialize appropriate service. campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201702') + 'CampaignCriterionService', version='v201710') # Create locations. The IDs can be found in the documentation or retrieved # with the LocationCriterionService. diff --git a/examples/adwords/v201710/targeting/add_customer_negative_criteria.py b/examples/adwords/v201710/targeting/add_customer_negative_criteria.py new file mode 100755 index 00000000..474b9430 --- /dev/null +++ b/examples/adwords/v201710/targeting/add_customer_negative_criteria.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds various types of negative criteria to a customer. + +These criteria will be applied to all campaigns for the customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_negative_criterion_service = client.GetService( + 'CustomerNegativeCriterionService', version='v201710') + + criteria = [ + # Exclude tragedy & conflict content. + { + 'xsi_type': 'ContentLabel', + 'contentLabelType': 'TRAGEDY' + }, + # Exclude a specific placement. + { + 'xsi_type': 'Placement', + 'url': 'http://www.example.com' + } + # Additional criteria types are available for this service. See the types + # listed under Criterion here: + # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion + ] + + # Create operations to add each of the criteria above. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'criterion': criterion + } + } for criterion in criteria] + + # Make the mutate request. + result = customer_negative_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for negative_criterion in result['value']: + print ('Customer negative criterion with criterion ID "%s", and type "%s" ' + 'was added.' % (negative_criterion['criterion']['id'], + negative_criterion['criterion']['type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py similarity index 98% rename from examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py rename to examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py index 512f489b..da284e19 100755 --- a/examples/adwords/v201609/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py @@ -37,7 +37,7 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') + 'AdGroupCriterionService', version='v201710') # Create the ad group criteria. ad_group_criteria = [ diff --git a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py similarity index 98% rename from examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py rename to examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py index bf4bf0f0..a5fc78b7 100755 --- a/examples/adwords/v201609/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201609') + 'CampaignCriterionService', version='v201710') # Construct selector and get all campaign targets. offset = 0 diff --git a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py similarity index 97% rename from examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py rename to examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py index c96c4d82..c874487d 100755 --- a/examples/adwords/v201609/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. constant_data_service = client.GetService( - 'ConstantDataService', version='v201609') + 'ConstantDataService', version='v201710') # Get all languages. languages = constant_data_service.getLanguageCriterion() diff --git a/examples/adwords/v201609/targeting/lookup_location.py b/examples/adwords/v201710/targeting/lookup_location.py similarity index 98% rename from examples/adwords/v201609/targeting/lookup_location.py rename to examples/adwords/v201710/targeting/lookup_location.py index 8c5d76fa..4ba82ba7 100755 --- a/examples/adwords/v201609/targeting/lookup_location.py +++ b/examples/adwords/v201710/targeting/lookup_location.py @@ -34,7 +34,7 @@ def GetLocationString(location): def main(client): # Initialize appropriate service. location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201609') + 'LocationCriterionService', version='v201710') location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] diff --git a/examples/adwords/v201702/__init__.py b/examples/adwords/v201802/__init__.py similarity index 100% rename from examples/adwords/v201702/__init__.py rename to examples/adwords/v201802/__init__.py diff --git a/examples/adwords/v201702/account_management/__init__.py b/examples/adwords/v201802/account_management/__init__.py similarity index 100% rename from examples/adwords/v201702/account_management/__init__.py rename to examples/adwords/v201802/account_management/__init__.py diff --git a/examples/adwords/v201702/account_management/accept_service_link.py b/examples/adwords/v201802/account_management/accept_service_link.py similarity index 97% rename from examples/adwords/v201702/account_management/accept_service_link.py rename to examples/adwords/v201802/account_management/accept_service_link.py index a6d6a261..b01f7180 100755 --- a/examples/adwords/v201702/account_management/accept_service_link.py +++ b/examples/adwords/v201802/account_management/accept_service_link.py @@ -33,7 +33,7 @@ def main(client, service_link_id): # Initialize appropriate service. customer_service = client.GetService( - 'CustomerService', version='v201702') + 'CustomerService', version='v201802') # Create the operation to set the status to ACTIVE. operations = [{ diff --git a/examples/adwords/v201609/account_management/create_account.py b/examples/adwords/v201802/account_management/create_account.py similarity index 82% rename from examples/adwords/v201609/account_management/create_account.py rename to examples/adwords/v201802/account_management/create_account.py index 08d431aa..c345e9da 100755 --- a/examples/adwords/v201609/account_management/create_account.py +++ b/examples/adwords/v201802/account_management/create_account.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201609') + 'ManagedCustomerService', version='v201802') today = datetime.today().strftime('%Y%m%d %H:%M:%S') # Construct operations and add campaign. @@ -44,7 +44,13 @@ def main(client): 'name': 'Account created with ManagedCustomerService on %s' % today, 'currencyCode': 'EUR', 'dateTimeZone': 'Europe/London', - } + }, + # For whitelisted users only, uncomment the inviteeEmail and inviteeRole + # attributes to invite a user to have access to an account on an ADD. An + # email will be sent inviting the user to have access to the newly created + # account. + # 'inviteeEmail': 'invited_user1@example.com', + # 'inviteeRole': 'ADMINISTRATIVE' }] # Create the account. It is possible to create multiple accounts with one diff --git a/examples/adwords/v201702/account_management/get_account_changes.py b/examples/adwords/v201802/account_management/get_account_changes.py similarity index 98% rename from examples/adwords/v201702/account_management/get_account_changes.py rename to examples/adwords/v201802/account_management/get_account_changes.py index d97a6827..659a4606 100755 --- a/examples/adwords/v201702/account_management/get_account_changes.py +++ b/examples/adwords/v201802/account_management/get_account_changes.py @@ -31,8 +31,8 @@ def main(client): # Initialize appropriate service. customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201702') - campaign_service = client.GetService('CampaignService', version='v201702') + 'CustomerSyncService', version='v201802') + campaign_service = client.GetService('CampaignService', version='v201802') # Construct selector and get all campaigns. selector = { diff --git a/examples/adwords/v201609/account_management/get_account_hierarchy.py b/examples/adwords/v201802/account_management/get_account_hierarchy.py similarity index 98% rename from examples/adwords/v201609/account_management/get_account_hierarchy.py rename to examples/adwords/v201802/account_management/get_account_hierarchy.py index ef7e6ffe..4cffedc7 100755 --- a/examples/adwords/v201609/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201802/account_management/get_account_hierarchy.py @@ -48,7 +48,7 @@ def DisplayAccountTree(account, accounts, links, depth=0): def main(client): # Initialize appropriate service. managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201609') + 'ManagedCustomerService', version='v201802') # Construct selector to get all accounts. offset = 0 diff --git a/examples/adwords/v201702/advanced_operations/__init__.py b/examples/adwords/v201802/advanced_operations/__init__.py similarity index 100% rename from examples/adwords/v201702/advanced_operations/__init__.py rename to examples/adwords/v201802/advanced_operations/__init__.py diff --git a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py b/examples/adwords/v201802/advanced_operations/add_ad_customizer.py similarity index 97% rename from examples/adwords/v201702/advanced_operations/add_ad_customizer.py rename to examples/adwords/v201802/advanced_operations/add_ad_customizer.py index a01996cf..adff3d83 100755 --- a/examples/adwords/v201702/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201802/advanced_operations/add_ad_customizer.py @@ -49,7 +49,7 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): GoogleAdsError: if no ExpandedTextAds were added. """ # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201702') + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201802') expanded_text_ad = { 'xsi_type': 'ExpandedTextAd', @@ -91,8 +91,7 @@ def CreateCustomizerFeed(client, feed_name): """ # Get the AdCustomizerFeedService ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201702') - + 'v201802') customizer_feed = { 'feedName': feed_name, 'feedAttributes': [ @@ -141,7 +140,7 @@ def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): GoogleAdsError: if no FeedItems were added. """ # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201702') + feed_item_service = client.GetService('FeedItemService', 'v201802') now = datetime.now() mars_date = datetime(now.year, now.month, 1, 0, 0) venus_date = datetime(now.year, now.month, 15, 0, 0) @@ -204,7 +203,12 @@ def CreateFeedItemAddOperation(name, price, date, adgroup_id, ] } - return {'operator': 'ADD', 'operand': feed_item} + operation = { + 'operator': 'ADD', + 'operand': feed_item + } + + return operation def main(client, adgroup_ids, feed_name=FEED_NAME): diff --git a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py similarity index 97% rename from examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py rename to examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py index 71bfb4a3..e09b1d5a 100755 --- a/examples/adwords/v201702/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py @@ -35,7 +35,7 @@ def main(client, ad_group_id, bid_modifier): # Initialize appropriate service. ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201702') + 'AdGroupBidModifierService', version='v201802') # Mobile criterion ID. criterion_id = '30001' diff --git a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py similarity index 95% rename from examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py rename to examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py index cbf0f447..ee473887 100755 --- a/examples/adwords/v201609/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py @@ -37,13 +37,15 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Optionally, you may specify a landscape image. The image needs to be in a # BASE64 encoded form. Here we download a demo image and encode it for this # ad. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - image_data = base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) + .decode('utf-8')) # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py new file mode 100755 index 00000000..2bbaf050 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. + +To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +from collections import namedtuple +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + +# Used to keep track of DSA page feed details. +_DSAFeedDetails = namedtuple( + '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) +# ID that corresponds to the labels. +DSA_LABEL_FIELD_ID = 2 +# The criterion type to be used for DSA page feeds. +DSA_PAGE_FEED_CRITERION_TYPE = 61 +DSA_PAGE_URL_LABEL = 'discounts' +# ID that corresponds to the page URLs. +DSA_PAGE_URLS_FIELD_ID = 1 + + +def main(client, campaign_id, ad_group_id): + # Get the page feed details. This code example creates a new feed, but you can + # fetch and re-use an existing feed. + feed_details = _CreateFeed(client) + _CreateFeedMapping(client, feed_details) + _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) + + # Associate the page feed with the campaign. + _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) + + # Optional: Target web pages matching the feed's label in the ad group. + _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) + + print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + + +def _CreateFeed(client): + """Creates the feed for DSA page URLs. + + Args: + client: an AdWordsClient instance. + + Returns: + A _DSAFeedDetails instance containing details about the created feed. + """ + # Get the FeedService. + feed_service = client.GetService('FeedService', version='v201802') + + # Create operation. + operation = { + # Create the feed. + 'operand': { + 'name': 'DSA Feed %s' % uuid.uuid4(), + # Create attributes. + 'attributes': [ + {'type': 'URL_LIST', 'name': 'Page URL'}, + {'type': 'STRING_LIST', 'name': 'Label'} + ], + 'origin': 'USER' + }, + 'operator': 'ADD' + } + + # Add the feed. + feed = feed_service.mutate([operation])['value'][0] + return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], + feed['attributes'][1]['id']) + + +def _CreateFeedMapping(client, feed_details): + """Creates the feed mapping for DSA page feeds. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + """ + # Get the FeedMappingService. + feed_mapping_service = client.GetService('FeedMappingService', + version='v201802') + + # Create the operation. + operation = { + # Create the feed mapping. + 'operand': { + 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, + 'feedId': feed_details.feed_id, + # Map the feedAttributeIds to the fieldId constants. + 'attributeFieldMappings': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'fieldId': DSA_PAGE_URLS_FIELD_ID + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'fieldId': DSA_LABEL_FIELD_ID + } + ] + }, + 'operator': 'ADD' + } + + # Add the feed mapping. + feed_mapping_service.mutate([operation]) + + +def _CreateFeedItems(client, feed_details, label_name): + """Creates the page URLs in the DSA page feed. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + label_name: a str containing the page feed URL label. + """ + # Get the FeedItemService. + feed_item_service = client.GetService('FeedItemService', version='v201802') + + # Optional: You can include the {feeditem} valuetrack parameter to track which + # page feed items lead to each click. + urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', + 'http://www.example.com/discounts/hotel-deals?id={feeditem}', + 'http://www.example.com/discounts/flight-deals?id={feeditem}') + + # Create the operation. + operations = [{ + # Create the feed item. + 'operand': { + 'feedId': feed_details.feed_id, + 'attributeValues': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'stringValues': [url] + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'stringValues': [label_name] + } + ] + }, + 'operator': 'ADD' + } for url in urls] + + # Add the feed item. + feed_item_service.mutate(operations) + + +def _UpdateCampaignDSASetting(client, campaign_id, feed_id): + """Updates the campaign DSA setting to DSA pagefeeds. + + Args: + client: an AdWordsClient instance. + campaign_id: a str Campaign ID. + feed_id: a str page Feed ID. + + Raises: + ValueError: If the given campaign is found not to be a dynamic search ad + campaign. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201802') + + selector = { + 'fields': ['Id', 'Settings'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [campaign_id] + }] + } + + response = campaign_service.get(selector) + + if response['totalNumEntries']: + campaign = response['entries'][0] + else: + raise ValueError('No campaign with ID "%d" exists.' % campaign_id) + + if not campaign['settings']: + raise ValueError('This is not a DSA campaign.') + + dsa_setting = None + + campaign_settings = campaign['settings'] + + for setting in campaign_settings: + if setting['Setting.Type'] == 'DynamicSearchAdsSetting': + dsa_setting = setting + break + + if dsa_setting is None: + raise ValueError('This is not a DSA campaign.') + + dsa_setting['pageFeed'] = { + 'feedIds': [feed_id] + } + + # Optional: Specify whether only the supplied URLs should be used with your + # Dynamic Search Ads. + dsa_setting['useSuppliedUrlsOnly'] = True + + operation = { + 'operand': { + 'id': campaign_id, + 'settings': campaign_settings + }, + 'operator': 'SET' + } + + campaign_service.mutate([operation]) + print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id) + + +def _AddDSATargeting(client, ad_group_id, label_name): + """Set custom targeting for the page feed URLs based on a list of labels. + + Args: + client: an AdWordsClient instance. + ad_group_id: a str AdGroup ID. + label_name: a str label name. + + Returns: + A suds.sudsobject.Object representing the newly created webpage criterion. + """ + # Get the AdGroupCriterionService. + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201802') + + # Create the operation. + operation = { + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Test criterion', + # Add a condition for label=specified_label_name. + 'conditions': [{ + 'operand': 'CUSTOM_LABEL', + 'argument': label_name + }], + } + }, + # Set a custom bid for this criterion + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 1500000 + } + }] + } + }, + 'operator': 'ADD' + } + + criterion = ad_group_criterion_service.mutate([operation])['value'][0] + print 'Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus']) + return criterion + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py new file mode 100755 index 00000000..439c7ba7 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Dynamic Search Ads campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + budget = _CreateBudget(client) + campaign_id = _CreateCampaign(client, budget) + ad_group_id = _CreateAdGroup(client, campaign_id) + _CreateExpandedDSA(client, ad_group_id) + _AddWebPageCriteria(client, ad_group_id) + + print 'Dynamic Search Ads campaign setup is complete.' + + +def _CreateBudget(client): + """Creates the budget. + + Args: + client: an AdWordsClient instance. + + Returns: + a suds.sudsobject.Object representation of the created budget. + """ + budget_service = client.GetService('BudgetService', version='v201802') + + # Create the campaign budget + operation = { + 'operand': { + 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), + 'deliveryMethod': 'STANDARD', + 'amount': { + 'microAmount': 500000 + } + }, + 'operator': 'ADD' + } + + budget = budget_service.mutate([operation])['value'][0] + + print 'Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name']) + + return budget + + +def _CreateCampaign(client, budget): + """Creates the campaign. + + Args: + client: an AdWordsClient instance. + budget: a suds.sudsobject.Object representation of a created budget. + + Returns: + An integer campaign ID. + """ + campaign_service = client.GetService('CampaignService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # prevent the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'budget': budget, + # Required: Set the campaign's Dynamic Search Ad settings. + 'settings': [{ + 'xsi_type': 'DynamicSearchAdsSetting', + # Required: Set the domain name and language. + 'domainName': 'example.com', + 'languageCode': 'en' + }], + # Optional: Set the start date. + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + # Optional: Set the end date. + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + }] + + campaign = campaign_service.mutate(operations)['value'][0] + campaign_id = campaign['id'] + + print 'Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name']) + + return campaign_id + + +def _CreateAdGroup(client, campaign_id): + """Creates an ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: an integer campaign ID. + + Returns: + An integer ad group ID. + """ + ad_group_service = client.GetService('AdGroupService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'adGroupType': 'SEARCH_DYNAMIC_ADS', + 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '3000000' + }, + }] + } + } + }] + + ad_group = ad_group_service.mutate(operations)['value'][0] + ad_group_id = ad_group['id'] + + print 'Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name']) + + return ad_group_id + + +def _CreateExpandedDSA(client, ad_group_id): + """Creates the expanded Dynamic Search Ad. + + Args: + client: an AdwordsClient instance. + ad_group_id: an integer ID of the ad group in which the DSA is added. + """ + # Get the AdGroupAdService. + ad_group_ad_service = client.GetService('AdGroupAdService') + + # Create the operation + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + # Create the expanded dynamic search ad. This ad will have its + # headline and final URL auto-generated at serving time according to + # domain name specific information provided by DynamicSearchAdsSetting + # at the campaign level. + 'ad': { + 'xsi_type': 'ExpandedDynamicSearchAd', + # Set the ad description. + 'description': 'Buy your tickets now!' + }, + # Optional: Set the status. + 'status': 'PAUSED', + } + }] + + # Create the ad. + ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] + + # Display the results. + print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' + 'added' % (ad['id'], ad['description'])) + + +def _AddWebPageCriteria(client, ad_group_id): + """Adds a web page criterion to target Dynamic Search Ads. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID of the ad group the criteria is being added to. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201802') + + operations = [{ + 'operator': 'ADD', + # Create biddable ad group criterion. + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion for special offers for children. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Special offers for children.', + 'conditions': [ + { + 'operand': 'URL', + 'argument': '/marscruise/children' + }, + { + 'operand': 'PAGE_TITLE', + 'argument': 'Special Offer' + } + ] + } + }, + 'userStatus': 'PAUSED', + # Optional: set a custom bid. + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000L + } + }] + } + } + }] + + criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py similarity index 78% rename from examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py rename to examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py index 0aea3dd7..55bc2357 100755 --- a/examples/adwords/v201702/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -32,7 +32,7 @@ def main(client, adgroup_id): # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201702') + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201802') # Create the expanded text ad expanded_text_ad = { @@ -40,25 +40,6 @@ def main(client, adgroup_id): 'headlinePart1': 'Luxury Cruise to Mars', 'headlinePart2': 'Visit the Red Planet in style.', 'description': 'Low-gravity fun for everyone!', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, # Specify a list of final URLs. This field cannot be set if URL # field is set, or finalUrls is unset. This may be specified at ad, # criterion, and feed item levels. @@ -75,6 +56,29 @@ def main(client, adgroup_id): ] } + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + expanded_text_ad['trackingUrlTemplate'] = ( + 'http://tracker.example.com/?season={_season}&promocode={_promocode}' + '&u={lpurl}' + ) + + expanded_text_ad['urlCustomParameters'] = { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + } + text_adgroup_ad = { 'adGroupId': adgroup_id, 'ad': expanded_text_ad, diff --git a/examples/adwords/v201802/advanced_operations/add_gmail_ad.py b/examples/adwords/v201802/advanced_operations/add_gmail_ad.py new file mode 100755 index 00000000..adab3ab8 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_gmail_ad.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example adds a Gmail ad to a given ad group. + +The ad group's campaign needs to have an AdvertisingChannelType of DISPLAY and +AdvertisingChannelSubType of DISPLAY_GMAIL_AD. + +To get your ad groups, run get_ad_groups.py. +""" + + +import base64 + +# Import appropriate classes from the client library. +from googleads import adwords + + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + media_service = client.GetService('MediaService', 'v201802') + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') + opener = client.proxy_config.BuildOpener() + + try: + # This ad format doesn't allow the creation of an image using the Image.data + # field. An image must first be created using the MediaService, and an + # Image.mediaId must be populated when creating the ad. + uploaded_logo_image = _CreateImage( + media_service, opener, 'https://goo.gl/mtt54n') + uploaded_marketing_image = _CreateImage( + media_service, opener, 'http://goo.gl/3b9Wfh') + + teaser = { + 'headline': 'Dream', + 'description': 'Create your own adventure', + 'businessName': 'Interplanetary Ships', + 'logoImage': uploaded_logo_image + } + + # Creates a Gmail ad. + gmail_ad = { + 'xsi_type': 'GmailAd', + 'teaser': teaser, + 'marketingImage': uploaded_marketing_image, + 'marketingImageHeadline': 'Travel', + 'marketingImageDescription': 'Take to the skies!', + 'finalUrls': ['http://wwww.example.com'] + } + + # Creates ad group ad for the Gmail ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': gmail_ad, + # Optional: Set additional settings. + 'status': 'PAUSED' + } + + # Creates ad group ad operations. + operations = [{ + 'operator': 'ADD', + 'operand': ad_group_ad + }] + + # Adds a Gmail ad. + ad_group_ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad_group_ad in ad_group_ads['value']: + print ('A Gmail ad with id "%d" and short headline "%s" was ' + 'added.' % (ad_group_ad['ad']['id'], + ad_group_ad['ad']['teaser']['headline'])) + except Exception as e: + raise Exception('Failed to create Gmail ad: %s' % e) + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201702/advanced_operations/add_html5_ad.py b/examples/adwords/v201802/advanced_operations/add_html5_ad.py similarity index 95% rename from examples/adwords/v201702/advanced_operations/add_html5_ad.py rename to examples/adwords/v201802/advanced_operations/add_html5_ad.py index 208add9e..ddf76b1c 100755 --- a/examples/adwords/v201702/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201802/advanced_operations/add_html5_ad.py @@ -36,7 +36,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Create HTML5 media. base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( @@ -101,7 +101,8 @@ def main(client, ad_group_id): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..7fb6a193 --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import base64 +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + media_service = client.GetService('MediaService', version='v201802') + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + + try: + # Create marketing image. + marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/3b9Wfh') + + # Create square marketing image. + square_marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/mtt54n') + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': marketing_image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'], + # Optional: Set a square marketing image to the ad. + 'squareMarketingImage': { + 'mediaId': square_marketing_image['mediaId'] + }, + # Optional: Set call-to-action text. + 'callToActionText': 'Shop Now', + # Optional: Set dynamic display ad settings, composed of + # landscape logo image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( + media_service, opener), + # Whitelisted accounts only: Set color settings using + # hexadecimal numbers. + # Set allowFlexibleColor to False if you want your ads to render + # by always using your colors strictly. + # 'mainColor': '#0000ff', + # 'accentColor': '#ffff00', + # 'allowFlexibleColor': False + # Whitelisted accounts only: Set the format setting that the ad + # will be served in. + # 'formatSetting': 'NON_NATIVE' + + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +def _CreateDynamicDisplayAdSettings(media_service, opener): + """Creates settings for dynamic display ad. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + + Returns: + The dynamic display ad settings. + """ + image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + + logo = { + 'type': 'IMAGE', + 'mediaId': image['mediaId'], + 'xsi_type': 'Image' + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!', + 'xsi_type': 'DynamicSettings', + } + + return dynamic_settings + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py new file mode 100755 index 00000000..2c41fe1a --- /dev/null +++ b/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Adds a Shopping dynamic remarketing campaign for the Display Network. + +This example steps through the following: +* Creates a new Display Network campaign. +* Links the campaign with Merchant Center. +* Links the user list to the ad group. +* Creates a responsive display ad to render the dynamic text. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import base64 +import uuid + +from googleads import adwords + + +MERCHANT_ID = 'INSERT_MERCHANT_CENTER_ID_HERE' +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +USER_LIST_ID = 'INSERT_USER_LIST_ID_HERE' + + +def main(client, merchant_id, budget_id, user_list_id): + opener = client.proxy_config.BuildOpener() + + campaign = CreateCampaign(client, merchant_id, budget_id) + campaign_id = campaign['id'] + print 'Campaign with name "%s" and ID "%d" was added.' % ( + campaign['name'], campaign_id) + + ad_group = CreateAdGroup(client, campaign_id) + ad_group_id = ad_group['id'] + print 'Ad group with name "%s" and ID "%d" was added.' % ( + ad_group['name'], ad_group_id) + + ad_group_ad = CreateAd(client, opener, ad_group_id) + print 'Responsive display ad with ID "%d" was added.' % ( + ad_group_ad['ad']['id']) + + AttachUserList(client, ad_group_id, user_list_id) + print 'User list with ID "%d" was attached to ad group with ID "%d".' % ( + user_list_id, ad_group_id) + + +def CreateCampaign(client, merchant_id, budget_id): + """Creates a new Display Network campaign. + + Args: + client: an AdWordsClient instance. + merchant_id: a int merchant center ID. + budget_id: a int budget ID. + + Returns: + The campaign that was successfully created. + """ + campaign_service = client.GetService('CampaignService', 'v201802') + + campaign = { + 'name': 'Shopping campaign #%d' % uuid.uuid4(), + # Dynamic remarketing campaigns are only available on the Google Display + # Network. + 'advertisingChannelType': 'DISPLAY', + 'status': 'PAUSED', + 'budget': { + 'budgetId': budget_id + }, + # This example uses a Manual CPC bidding strategy, but you should select + # the strategy that best aligns with your sales goals. More details here: + # https://support.google.com/adwords/answer/2472725 + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [{ + 'xsi_type': 'ShoppingSetting', + # Campaigns with numerically higher priorities take precedence over + # those with lower priorities. + 'campaignPriority': 0, + 'merchantId': merchant_id, + # Display network campaigns do not support partition by country. The + # only supported value is "ZZ". This signals that products from all + # countries are available in this campaign. The actual products which + # serve are based on the products tagged in the user list entry. + 'salesCountry': 'ZZ', + # Optional: Enable local inventory ads (items for sale in physical + # stores.) + 'enableLocal': True, + # Optional: Declare whether purchases are only made on the merchant + # store, or completed on Google. + 'purchasePlatform': 'MERCHANT' + }] + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + return campaign_service.mutate(operations)['value'][0] + + +def CreateAdGroup(client, campaign_id): + """Creates a dynamic remarketing campaign. + + Args: + client: an AdWordsClient instance. + campaign_id: an int campaign ID. + + Returns: + The ad group that was successfully created. + """ + ad_group_service = client.GetService('AdGroupService', 'v201802') + + ad_group = { + 'name': 'Dynamic remarketing ad group', + 'campaignId': campaign_id, + 'status': 'ENABLED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': ad_group + }] + + return ad_group_service.mutate(operations)['value'][0] + + +def CreateAd(client, opener, ad_group_id): + """Creates a ResponsiveDisplayAd. + + Args: + client: an AdWordsClient instance. + opener: an OpenerDirector instance. + ad_group_id: an int ad group ID. + + Returns: + The ad group ad that was successfully created. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') + media_service = client.GetService('MediaService', 'v201802') + + marketing_image_id = _CreateImage( + media_service, opener, 'https://goo.gl/3b9Wfh') + logo_image_id = _CreateImage(media_service, opener, 'https://goo.gl/mtt54n') + + ad = { + 'xsi_type': 'ResponsiveDisplayAd', + # This ad format doesn't allow the creation of an image using the + # Image.data field. An image must first be created using the MediaService, + # and Image.mediaId must be populated when creating the ad. + 'marketingImage': { + 'xsi_type': 'Image', + 'mediaId': marketing_image_id + }, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://wwww.example.com'], + # Optional: Call to action text. + # Valid texts: https://support.google.com/adwords/answer/7005917 + 'callToActionText': 'Apply Now', + # Optional: Set dynamic display ad settings, composed of landscape logo + # image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': CreateDynamicDisplayAdSettings( + client, opener), + # Optional: Create a logo image and set it to the ad. + 'logoImage': { + 'xsi_type': 'Image', + 'mediaId': logo_image_id + }, + # Optional: Create a square marketing image and set it to the ad. + 'squareMarketingImage': { + 'xsi_type': 'Image', + 'mediaId': logo_image_id + }, + # Whitelisted accounts only: Set color settings using hexadecimal values. + # Set allowFlexibleColor to False if you want your ads to render by always + # using your colors strictly. + # 'mainColor': '#000fff', + # 'accentColor': '#fff000', + # 'allowFlexibleColor': False, + # Whitelisted accounts only: Set the format setting that the ad will be + # served in. + # 'formatSetting': 'NON_NATIVE' + } + + ad_group_ad = { + 'ad': ad, + 'adGroupId': ad_group_id + } + + operations = [{ + 'operation': 'ADD', + 'operand': ad_group_ad + }] + + return ad_group_ad_service.mutate(operations)['value'][0] + + +def AttachUserList(client, ad_group_id, user_list_id): + """Links the provided ad group and user list. + + Args: + client: an AdWordsClient instance. + ad_group_id: an int ad group ID. + user_list_id: an int user list ID. + + Returns: + The ad group criterion that was successfully created. + """ + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', 'v201802') + + user_list = { + 'xsi_type': 'CriterionUserList', + 'userListId': user_list_id + } + + ad_group_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'criterion': user_list, + 'adGroupId': ad_group_id + } + + operations = [{ + 'operator': 'ADD', + 'operand': ad_group_criterion + }] + + return ad_group_criterion_service.mutate(operations)['value'][0] + + +def CreateDynamicDisplayAdSettings(client, opener): + """Creates dynamic display ad settings. + + Args: + client: an AdWordsClient instance. + opener: an OpenerDirector instance. + + Returns: + A dict containing the dynamic display ad settings. + """ + media_service = client.GetService('MediaService', 'v201802') + + logo = { + 'xsi_type': 'Image', + 'mediaId': _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!' + } + + return dynamic_settings + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, MERCHANT_ID, BUDGET_ID, USER_LIST_ID) diff --git a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py similarity index 93% rename from examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py rename to examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py index b10e292d..e992b18c 100755 --- a/examples/adwords/v201609/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201802') budget_id = CreateBudget(client) @@ -50,7 +50,7 @@ def main(client): # Set the campaign's bidding strategy. Universal app campaigns only # support TARGET_CPA bidding strategy. 'biddingStrategyConfiguration': { - # Set the target CPA to $1 / app install. + # Set the target CPA to $1 / app install. 'biddingScheme': { 'xsi_type': 'TargetCpaBiddingScheme', 'targetCpa': { @@ -75,12 +75,13 @@ def main(client): # be used to generate ads. { 'xsi_type': 'UniversalAppCampaignSetting', - 'appId': 'com.interplanetarycruise.booking', - 'description1': 'Best Space Cruise Line', - 'description2': 'Visit all the planets', - 'description3': 'Trips 7 days a week', - 'description4': 'Buy your tickets now!', - # Optional: You can set up to 10 image assets for your campaign. + 'appId': 'com.labpixies.colordrips', + 'appVendor': 'VENDOR_GOOGLE_MARKET', + 'description1': 'A cool puzzle game', + 'description2': 'Remove connected blocks', + 'description3': '3 difficulty levels', + 'description4': '4 colorful fun skins', + # Optional: You can set up to 20 image assets for your campaign. # See upload_image.py for an example on how to upload images. # # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] @@ -131,14 +132,14 @@ def main(client): def CreateBudget(client): """Creates a budget and returns its budgetId. - + Args: client: An AdWordsClient instance. - + Returns: An int budgetId for the created Budget. """ - budget_service = client.GetService('BudgetService', version='v201609') + budget_service = client.GetService('BudgetService', version='v201802') # Create a budget. budget = { @@ -160,6 +161,7 @@ def CreateBudget(client): return budget_id + def SetCampaignTargetingCriteria(client, campaign): """Sets targeting criteria for the given campaign. diff --git a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py similarity index 96% rename from examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py rename to examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py index 37033b06..7efcf236 100755 --- a/examples/adwords/v201609/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py @@ -34,11 +34,11 @@ def main(client, campaign_id): # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201609') + shared_set_service = client.GetService('SharedSetService', version='v201802') shared_criterion_service = client.GetService('SharedCriterionService', - version='v201609') + version='v201802') campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201609') + version='v201802') # Keywords to create a shared set of. keywords = ['mars cruise', 'mars hotels'] diff --git a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py similarity index 97% rename from examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py rename to examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py index 59f7da6f..7a91a4df 100755 --- a/examples/adwords/v201609/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -33,9 +33,9 @@ def main(client, campaign_id): # Initialize appropriate services. shared_criterion_service = client.GetService('SharedCriterionService', - version='v201609') + version='v201802') campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201609') + version='v201802') shared_set_ids = [] criterion_ids = [] diff --git a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py similarity index 97% rename from examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py rename to examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py index 9c183775..10bca1ce 100755 --- a/examples/adwords/v201609/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py @@ -32,7 +32,7 @@ def main(client): # Initialize appropriate service. ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201609') + 'AdGroupBidModifierService', version='v201802') # Get all ad group bid modifiers for the campaign. selector = { diff --git a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py similarity index 98% rename from examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py rename to examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py index c3d1d76c..47639262 100755 --- a/examples/adwords/v201609/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py @@ -54,7 +54,7 @@ def CreateBiddingStrategy(client): """ # Initialize appropriate service. bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201609') + 'BiddingStrategyService', version='v201802') # Create a shared bidding strategy. shared_bidding_strategy = { @@ -95,7 +95,7 @@ def CreateSharedBudget(client): dict An object representing a shared budget. """ # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201609') + budget_service = client.GetService('BudgetService', version='v201802') # Create a shared budget budget = { @@ -129,7 +129,7 @@ def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): dict An object representing a campaign. """ # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201802') # Create campaign. campaign = { diff --git a/examples/adwords/v201702/basic_operations/__init__.py b/examples/adwords/v201802/basic_operations/__init__.py similarity index 100% rename from examples/adwords/v201702/basic_operations/__init__.py rename to examples/adwords/v201802/basic_operations/__init__.py diff --git a/examples/adwords/v201702/basic_operations/add_ad_groups.py b/examples/adwords/v201802/basic_operations/add_ad_groups.py similarity index 99% rename from examples/adwords/v201702/basic_operations/add_ad_groups.py rename to examples/adwords/v201802/basic_operations/add_ad_groups.py index 9dad1690..a56ec582 100755 --- a/examples/adwords/v201702/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201802/basic_operations/add_ad_groups.py @@ -35,7 +35,7 @@ def main(client, campaign_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201702') + ad_group_service = client.GetService('AdGroupService', version='v201802') # Construct operations and add ad groups. operations = [{ diff --git a/examples/adwords/v201609/basic_operations/add_campaigns.py b/examples/adwords/v201802/basic_operations/add_campaigns.py similarity index 98% rename from examples/adwords/v201609/basic_operations/add_campaigns.py rename to examples/adwords/v201802/basic_operations/add_campaigns.py index c39df642..929d2657 100755 --- a/examples/adwords/v201609/basic_operations/add_campaigns.py +++ b/examples/adwords/v201802/basic_operations/add_campaigns.py @@ -33,8 +33,8 @@ def main(client): # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201609') - budget_service = client.GetService('BudgetService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201802') + budget_service = client.GetService('BudgetService', version='v201802') # Create a budget, which can be shared by multiple campaigns. budget = { @@ -82,7 +82,6 @@ def main(client): # Optional fields 'startDate': (datetime.datetime.now() + datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', 'frequencyCap': { 'impressions': '5', 'timeUnit': 'DAY', diff --git a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201802/basic_operations/add_expanded_text_ads.py similarity index 99% rename from examples/adwords/v201702/basic_operations/add_expanded_text_ads.py rename to examples/adwords/v201802/basic_operations/add_expanded_text_ads.py index 45a007d3..e8963345 100755 --- a/examples/adwords/v201702/basic_operations/add_expanded_text_ads.py +++ b/examples/adwords/v201802/basic_operations/add_expanded_text_ads.py @@ -36,7 +36,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') operations = [ { diff --git a/examples/adwords/v201702/basic_operations/add_keywords.py b/examples/adwords/v201802/basic_operations/add_keywords.py similarity index 98% rename from examples/adwords/v201702/basic_operations/add_keywords.py rename to examples/adwords/v201802/basic_operations/add_keywords.py index 437ffbf2..1e46a98a 100755 --- a/examples/adwords/v201702/basic_operations/add_keywords.py +++ b/examples/adwords/v201802/basic_operations/add_keywords.py @@ -34,7 +34,7 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') + 'AdGroupCriterionService', version='v201802') # Construct keyword ad group criterion object. keyword1 = { diff --git a/examples/adwords/v201702/basic_operations/get_ad_groups.py b/examples/adwords/v201802/basic_operations/get_ad_groups.py similarity index 99% rename from examples/adwords/v201702/basic_operations/get_ad_groups.py rename to examples/adwords/v201802/basic_operations/get_ad_groups.py index 0ae7272b..f2fda1ba 100755 --- a/examples/adwords/v201702/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201802/basic_operations/get_ad_groups.py @@ -34,7 +34,7 @@ def main(client, campaign_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201702') + ad_group_service = client.GetService('AdGroupService', version='v201802') # Construct selector and get all ad groups. offset = 0 diff --git a/examples/adwords/v201702/basic_operations/get_campaigns.py b/examples/adwords/v201802/basic_operations/get_campaigns.py similarity index 97% rename from examples/adwords/v201702/basic_operations/get_campaigns.py rename to examples/adwords/v201802/basic_operations/get_campaigns.py index 489cddc1..5a67c342 100755 --- a/examples/adwords/v201702/basic_operations/get_campaigns.py +++ b/examples/adwords/v201802/basic_operations/get_campaigns.py @@ -27,7 +27,6 @@ import logging -import time from googleads import adwords logging.basicConfig(level=logging.INFO) @@ -39,7 +38,7 @@ def main(client): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201802') # Construct selector and get all campaigns. offset = 0 @@ -66,7 +65,6 @@ def main(client): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py similarity index 84% rename from examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py rename to examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py index 07508aa4..7220e6f0 100755 --- a/examples/adwords/v201609/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -35,16 +34,17 @@ def main(client): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201802') # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'Name', 'Status') + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, PAGE_SIZE) + .Build()) + + for page in query.Pager(campaign_service): # Display results. if 'entries' in page: for campaign in page['entries']: @@ -53,9 +53,6 @@ def main(client): campaign['status'])) else: print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201802/basic_operations/get_expanded_text_ads.py similarity index 99% rename from examples/adwords/v201609/basic_operations/get_expanded_text_ads.py rename to examples/adwords/v201802/basic_operations/get_expanded_text_ads.py index c4d9a2f5..64e656d5 100755 --- a/examples/adwords/v201609/basic_operations/get_expanded_text_ads.py +++ b/examples/adwords/v201802/basic_operations/get_expanded_text_ads.py @@ -34,7 +34,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Construct selector and get all ads for a given ad group. offset = 0 diff --git a/examples/adwords/v201609/basic_operations/get_keywords.py b/examples/adwords/v201802/basic_operations/get_keywords.py similarity index 98% rename from examples/adwords/v201609/basic_operations/get_keywords.py rename to examples/adwords/v201802/basic_operations/get_keywords.py index 11073cf3..012ab9c3 100755 --- a/examples/adwords/v201609/basic_operations/get_keywords.py +++ b/examples/adwords/v201802/basic_operations/get_keywords.py @@ -36,7 +36,7 @@ def main(client, adgroup_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') + 'AdGroupCriterionService', version='v201802') # Construct selector and get all ad group criteria. offset = 0 diff --git a/examples/adwords/v201609/basic_operations/pause_ad.py b/examples/adwords/v201802/basic_operations/pause_ad.py similarity index 99% rename from examples/adwords/v201609/basic_operations/pause_ad.py rename to examples/adwords/v201802/basic_operations/pause_ad.py index 06cadaa2..d9c00409 100755 --- a/examples/adwords/v201609/basic_operations/pause_ad.py +++ b/examples/adwords/v201802/basic_operations/pause_ad.py @@ -34,7 +34,7 @@ def main(client, ad_group_id, ad_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Construct operations and update an ad. operations = [{ diff --git a/examples/adwords/v201609/basic_operations/remove_ad.py b/examples/adwords/v201802/basic_operations/remove_ad.py similarity index 96% rename from examples/adwords/v201609/basic_operations/remove_ad.py rename to examples/adwords/v201802/basic_operations/remove_ad.py index f7e637c4..7eb35a05 100755 --- a/examples/adwords/v201609/basic_operations/remove_ad.py +++ b/examples/adwords/v201802/basic_operations/remove_ad.py @@ -16,7 +16,7 @@ """This example deletes an ad using the 'REMOVE' operator. -To get ads, run get_text_ads.py. +To get ads, run get_expanded_text_ads.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -34,7 +34,7 @@ def main(client, ad_group_id, ad_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Construct operations and delete ad. operations = [{ diff --git a/examples/adwords/v201609/basic_operations/remove_ad_group.py b/examples/adwords/v201802/basic_operations/remove_ad_group.py similarity index 99% rename from examples/adwords/v201609/basic_operations/remove_ad_group.py rename to examples/adwords/v201802/basic_operations/remove_ad_group.py index da407601..7d82f4ef 100755 --- a/examples/adwords/v201609/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201802/basic_operations/remove_ad_group.py @@ -33,7 +33,7 @@ def main(client, ad_group_id): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201609') + ad_group_service = client.GetService('AdGroupService', version='v201802') # Construct operations and delete ad group. operations = [{ diff --git a/examples/adwords/v201609/basic_operations/remove_campaign.py b/examples/adwords/v201802/basic_operations/remove_campaign.py similarity index 99% rename from examples/adwords/v201609/basic_operations/remove_campaign.py rename to examples/adwords/v201802/basic_operations/remove_campaign.py index 8c66adf9..b4a55598 100755 --- a/examples/adwords/v201609/basic_operations/remove_campaign.py +++ b/examples/adwords/v201802/basic_operations/remove_campaign.py @@ -33,7 +33,7 @@ def main(client, campaign_id): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201609') + campaign_service = client.GetService('CampaignService', version='v201802') # Construct operations and delete campaign. operations = [{ diff --git a/examples/adwords/v201609/basic_operations/remove_keyword.py b/examples/adwords/v201802/basic_operations/remove_keyword.py similarity index 97% rename from examples/adwords/v201609/basic_operations/remove_keyword.py rename to examples/adwords/v201802/basic_operations/remove_keyword.py index 3887fcb5..63ee1239 100755 --- a/examples/adwords/v201609/basic_operations/remove_keyword.py +++ b/examples/adwords/v201802/basic_operations/remove_keyword.py @@ -35,7 +35,7 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') + 'AdGroupCriterionService', version='v201802') # Construct operations and delete ad group criteria. operations = [ diff --git a/examples/adwords/v201609/basic_operations/update_ad_group.py b/examples/adwords/v201802/basic_operations/update_ad_group.py similarity index 56% rename from examples/adwords/v201609/basic_operations/update_ad_group.py rename to examples/adwords/v201802/basic_operations/update_ad_group.py index bef260f5..7f06c46c 100755 --- a/examples/adwords/v201609/basic_operations/update_ad_group.py +++ b/examples/adwords/v201802/basic_operations/update_ad_group.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example updates status for a given ad group. +"""This example updates the CPC bid and status for a given ad group. To get ad groups, run get_ad_groups.py. @@ -29,11 +29,12 @@ AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' -def main(client, ad_group_id): +def main(client, ad_group_id, bid_micro_amount=None): # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201609') + ad_group_service = client.GetService('AdGroupService', version='v201802') # Construct operations and update an ad group. operations = [{ @@ -43,16 +44,42 @@ def main(client, ad_group_id): 'status': 'PAUSED' } }] + + if bid_micro_amount: + operations[0]['operand']['biddingStrategyConfiguration'] = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': bid_micro_amount, + } + }] + } + ad_groups = ad_group_service.mutate(operations) # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was updated.' - % (ad_group['name'], ad_group['id'])) + bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] + # Find the CpcBid in the bidding strategy configuration's bids collection. + cpc_bid_micros = None + + if bidding_strategy_configuration: + bids = bidding_strategy_configuration['bids'] + + if bids: + for bid in bids: + if bid['Bids.Type'] == 'CpcBid': + cpc_bid_micros = bid['bid']['microAmount'] + break + + print ('Ad group with name "%s", and id "%s" was updated to have status ' + '"%s" and CPC bid %d.' + % (ad_group['name'], ad_group['id'], ad_group['status'], + cpc_bid_micros)) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) + main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201702/basic_operations/update_campaign.py b/examples/adwords/v201802/basic_operations/update_campaign.py similarity index 99% rename from examples/adwords/v201702/basic_operations/update_campaign.py rename to examples/adwords/v201802/basic_operations/update_campaign.py index 8505e9c1..70bd4546 100755 --- a/examples/adwords/v201702/basic_operations/update_campaign.py +++ b/examples/adwords/v201802/basic_operations/update_campaign.py @@ -33,7 +33,7 @@ def main(client, campaign_id): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201802') # Construct operations and update campaign. operations = [{ diff --git a/examples/adwords/v201702/basic_operations/update_keyword.py b/examples/adwords/v201802/basic_operations/update_keyword.py similarity index 98% rename from examples/adwords/v201702/basic_operations/update_keyword.py rename to examples/adwords/v201802/basic_operations/update_keyword.py index 5596781f..fd0527bb 100755 --- a/examples/adwords/v201702/basic_operations/update_keyword.py +++ b/examples/adwords/v201802/basic_operations/update_keyword.py @@ -35,7 +35,7 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') + 'AdGroupCriterionService', version='v201802') # Construct operations and update bids. diff --git a/examples/adwords/v201702/campaign_management/__init__.py b/examples/adwords/v201802/campaign_management/__init__.py similarity index 100% rename from examples/adwords/v201702/campaign_management/__init__.py rename to examples/adwords/v201802/campaign_management/__init__.py diff --git a/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py new file mode 100755 index 00000000..9576a872 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a campaign group and sets a performance target for it. + +To get campaigns, run get_campaigns.py. To download reports, run +download_criteria_report_with_awql.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id1, campaign_id2): + campaign_group_id = _CreateCampaignGroup(client) + _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) + _CreatePerformanceTarget(client, campaign_group_id) + print 'Campaign group and its performance target were setup successfully.' + + +def _CreateCampaignGroup(client): + """Create a campaign group. + + Args: + client: an AdWordsClient instance. + + Returns: + The integer ID of the created campaign group. + """ + # Get the CampaignGroupService. + campaign_group_service = client.GetService('CampaignGroupService', + version='v201802') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the campaign group. + 'operand': { + 'name': 'Mars campaign group #%d' % uuid.uuid4() + } + }] + + campaign_group = campaign_group_service.mutate(operations)['value'][0] + campaign_group_id = campaign_group['id'] + + # Display the results. + print 'Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name']) + + return campaign_group_id + + +def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): + """Adds multiple campaigns to a campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + campaign_ids: a list of integer IDs for campaigns. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201802') + + # Create the operations. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'campaignGroupId': campaign_group_id + } + } for campaign_id in campaign_ids] + + campaign_service.mutate(operations) + + # Display the results. + print ('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + + +def _CreatePerformanceTarget(client, campaign_group_id): + """Creates a performance target for the campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + """ + # Get the CampaignGroupPerformanceTargetService. + cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', + version='v201802') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the performance target. + 'operand': { + 'campaignGroupId': campaign_group_id, + 'performanceTarget': { + # Keep the CPC for the campaigns < $3. + 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', + 'efficiencyTargetValue': 3000000, + # Keep the maximum spend under $50. + 'spendTargetType': 'MAXIMUM', + 'spendTarget': { + 'microAmount': 500000000 + }, + # Aim for at least 3000 clicks. + 'volumeGoalType': 'MAXIMIZE_CLICKS', + 'volumeTargetValue': 3000, + # Start the performance target today, and run it for the next 90 + # days. + 'startDate': datetime.datetime.now().strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(90)).strftime('%Y%m%d') + } + } + }] + + cgpt = cgpt_service.mutate(operations)['value'][0] + + # Display the results. + print ('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201702/campaign_management/add_campaign_labels.py b/examples/adwords/v201802/campaign_management/add_campaign_labels.py similarity index 99% rename from examples/adwords/v201702/campaign_management/add_campaign_labels.py rename to examples/adwords/v201802/campaign_management/add_campaign_labels.py index e6b5f147..0b59df85 100755 --- a/examples/adwords/v201702/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201802/campaign_management/add_campaign_labels.py @@ -33,7 +33,7 @@ def main(client, campaign_id1, campaign_id2, label_id): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201802') operations = [ { diff --git a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py similarity index 98% rename from examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py rename to examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py index 9d6dfc03..0cc20483 100755 --- a/examples/adwords/v201702/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py @@ -38,7 +38,7 @@ def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201702') + batch_job_helper = client.GetBatchJobHelper(version='v201802') # Create a BatchJob. batch_job = AddBatchJob(client) @@ -82,7 +82,7 @@ def AddBatchJob(client): The new BatchJob created by the request. """ # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201702') + batch_job_service = client.GetService('BatchJobService', version='v201802') # Create a BatchJob. batch_job_operations = [{ 'operand': {}, @@ -347,7 +347,7 @@ def GetBatchJob(client, batch_job_id): Returns: The BatchJob associated with the given id. """ - batch_job_service = client.GetService('BatchJobService', 'v201702') + batch_job_service = client.GetService('BatchJobService', 'v201802') selector = { 'fields': ['Id', 'Status', 'DownloadUrl'], @@ -370,8 +370,8 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, Args: client: an instantiated AdWordsClient used to poll the BatchJob. batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. Returns: A str containing the downloadUrl of the completed BatchJob. diff --git a/examples/adwords/v201702/campaign_management/add_draft.py b/examples/adwords/v201802/campaign_management/add_draft.py similarity index 97% rename from examples/adwords/v201702/campaign_management/add_draft.py rename to examples/adwords/v201802/campaign_management/add_draft.py index 6cd4fcc6..afeef760 100755 --- a/examples/adwords/v201702/campaign_management/add_draft.py +++ b/examples/adwords/v201802/campaign_management/add_draft.py @@ -35,7 +35,7 @@ def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201702') + draft_service = client.GetService('DraftService', version='v201802') draft = { 'baseCampaignId': base_campaign_id, @@ -50,7 +50,7 @@ def main(client, base_campaign_id): # real campaign. For example, you may add criteria, adjust bids, or even # include additional ads. Adding a criteria is shown here. campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201702') + version='v201802') criterion = { 'xsi_type': 'Language', diff --git a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py similarity index 94% rename from examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py rename to examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py index 54aefb49..6e8eb880 100755 --- a/examples/adwords/v201702/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py @@ -14,11 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This uses the BatchJobService to incrementally create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. +"""This example illustrates how to incrementally upload keywords. +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. """ import random @@ -37,7 +35,7 @@ def main(client, adgroup_id): # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201702') + batch_job_helper = client.GetBatchJobHelper(version='v201802') # Create a BatchJob. batch_job = AddBatchJob(client) @@ -79,7 +77,7 @@ def AddBatchJob(client): The new BatchJob created by the request. """ # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201702') + batch_job_service = client.GetService('BatchJobService', version='v201802') # Create a BatchJob. batch_job_operations = [{ 'operand': {}, @@ -128,10 +126,10 @@ def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): Args: client: an instantiated AdWordsClient used to cancel the BatchJob. batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has been canceled. """ - batch_job_service = client.GetService('BatchJobService', 'v201702') + batch_job_service = client.GetService('BatchJobService', 'v201802') batch_job['status'] = 'CANCELING' operation = { @@ -171,7 +169,7 @@ def GetBatchJob(client, batch_job_id): Returns: The BatchJob associated with the given id. """ - batch_job_service = client.GetService('BatchJobService', 'v201702') + batch_job_service = client.GetService('BatchJobService', 'v201802') selector = { 'fields': ['Id', 'Status', 'DownloadUrl'], @@ -194,8 +192,8 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, Args: client: an instantiated AdWordsClient used to poll the BatchJob. batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. Returns: A str containing the downloadUrl of the completed BatchJob. diff --git a/examples/adwords/v201609/campaign_management/add_trial.py b/examples/adwords/v201802/campaign_management/add_trial.py similarity index 98% rename from examples/adwords/v201609/campaign_management/add_trial.py rename to examples/adwords/v201802/campaign_management/add_trial.py index f5af4a13..931a66ee 100755 --- a/examples/adwords/v201609/campaign_management/add_trial.py +++ b/examples/adwords/v201802/campaign_management/add_trial.py @@ -39,9 +39,9 @@ def main(client, base_campaign_id, draft_id): # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201609') + trial_service = client.GetService('TrialService', version='v201802') trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201609') + version='v201802') trial = { 'draftId': draft_id, diff --git a/examples/adwords/v201609/basic_operations/get_text_ads.py b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py similarity index 55% rename from examples/adwords/v201609/basic_operations/get_text_ads.py rename to examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py index fc926c40..cfb8ef3f 100755 --- a/examples/adwords/v201609/basic_operations/get_text_ads.py +++ b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py @@ -14,7 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all text ads for a given ad group. +"""This example gets all disapproved ads for a given campaign. + +To add an ad, run add_ads.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -26,18 +28,18 @@ from googleads import adwords -PAGE_SIZE = 500 AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 def main(client, ad_group_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Construct selector and get all ads for a given ad group. offset = 0 selector = { - 'fields': ['Id', 'AdGroupId', 'Status'], + 'fields': ['Id', 'PolicySummary'], 'predicates': [ { 'field': 'AdGroupId', @@ -45,9 +47,9 @@ def main(client, ad_group_id): 'values': [ad_group_id] }, { - 'field': 'AdType', + 'field': 'CombinedApprovalStatus', 'operator': 'EQUALS', - 'values': ['TEXT_AD'] + 'values': 'DISAPPROVED' } ], 'paging': { @@ -55,21 +57,44 @@ def main(client, ad_group_id): 'numberResults': str(PAGE_SIZE) } } + more_pages = True + disapproved_count = 0 + + # Display results. while more_pages: page = ad_group_ad_service.get(selector) - # Display results. if 'entries' in page: for ad in page['entries']: - print ('Ad with id "%s", status "%s", and of type "%s" was found.' - % (ad['ad']['id'], ad['status'], ad['ad']['Ad.Type'])) - else: - print 'No ads were found.' + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName'], + policy_topic_entry['policyTopicHelpCenterUrl']) + # Display the attributes and values that triggered the policy topic. + policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] + if policy_topic_evidences: + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) + print '%d disapproved ads were found.' % disapproved_count + if __name__ == '__main__': # Initialize client object. diff --git a/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..ba8ab982 --- /dev/null +++ b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', + version='v201802') + + # Construct query and get all ads for a given campaign. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'PolicySummary') + .Where('AdGroupId').EqualTo(ad_group_id) + .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') + .OrderBy('Id') + .Limit(0, PAGE_SIZE) + .Build()) + disapproved_count = 0 + + # Display results. + while True: + page = ad_group_ad_service.query(query) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + # Display the attributes and values that triggered the policy topic. + if ('policyTopicEvidences' in policy_topic_entry + and policy_topic_entry['policyTopicEvidences']): + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + if not query.HasNext(page): + break + query.NextPage() + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201802/campaign_management/get_campaigns_by_label.py similarity index 98% rename from examples/adwords/v201702/campaign_management/get_campaigns_by_label.py rename to examples/adwords/v201802/campaign_management/get_campaigns_by_label.py index 38e537af..37deb3d7 100755 --- a/examples/adwords/v201702/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201802/campaign_management/get_campaigns_by_label.py @@ -26,7 +26,6 @@ """ -import time from googleads import adwords @@ -36,7 +35,7 @@ def main(client, label_id): # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201702') + campaign_service = client.GetService('CampaignService', version='v201802') offset = 0 selector = { @@ -75,7 +74,6 @@ def main(client, label_id): offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - time.sleep(1) if __name__ == '__main__': diff --git a/examples/adwords/v201609/campaign_management/graduate_trial.py b/examples/adwords/v201802/campaign_management/graduate_trial.py similarity index 99% rename from examples/adwords/v201609/campaign_management/graduate_trial.py rename to examples/adwords/v201802/campaign_management/graduate_trial.py index 6888c53a..970eaf3e 100755 --- a/examples/adwords/v201609/campaign_management/graduate_trial.py +++ b/examples/adwords/v201802/campaign_management/graduate_trial.py @@ -36,8 +36,8 @@ def main(client, trial_id): # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201609') - budget_service = client.GetService('BudgetService', version='v201609') + trial_service = client.GetService('TrialService', version='v201802') + budget_service = client.GetService('BudgetService', version='v201802') # To graduate a trial, you must specify a different budget from the base # campaign. The base campaign (in order to have had a trial based on it) must diff --git a/examples/adwords/v201609/campaign_management/set_ad_parameters.py b/examples/adwords/v201802/campaign_management/set_ad_parameters.py similarity index 99% rename from examples/adwords/v201609/campaign_management/set_ad_parameters.py rename to examples/adwords/v201802/campaign_management/set_ad_parameters.py index 9013f36d..4c44ff29 100755 --- a/examples/adwords/v201609/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201802/campaign_management/set_ad_parameters.py @@ -35,8 +35,8 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') - ad_param_service = client.GetService('AdParamService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') + ad_param_service = client.GetService('AdParamService', version='v201802') # Construct operations for adding text ad object and add to an ad group. operations = [{ diff --git a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py similarity index 97% rename from examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py rename to examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py index 30c5734c..0fb52250 100755 --- a/examples/adwords/v201609/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py @@ -34,7 +34,7 @@ def main(client, campaign_id, bid_modifier): # Initialize appropriate service. campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201609') + 'CampaignCriterionService', version='v201802') # Create mobile platform.The ID can be found in the documentation. # https://developers.google.com/adwords/api/docs/appendix/platforms diff --git a/examples/adwords/v201609/campaign_management/validate_text_ad.py b/examples/adwords/v201802/campaign_management/validate_text_ad.py similarity index 99% rename from examples/adwords/v201609/campaign_management/validate_text_ad.py rename to examples/adwords/v201802/campaign_management/validate_text_ad.py index 3c2c3d39..d657e884 100755 --- a/examples/adwords/v201609/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201802/campaign_management/validate_text_ad.py @@ -36,7 +36,7 @@ def main(client, ad_group_id): # Initialize appropriate service with validate only flag enabled. client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201609') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Construct operations to add an expanded text ad. operations = [{ diff --git a/examples/adwords/v201702/error_handling/__init__.py b/examples/adwords/v201802/error_handling/__init__.py similarity index 100% rename from examples/adwords/v201702/error_handling/__init__.py rename to examples/adwords/v201802/error_handling/__init__.py diff --git a/examples/adwords/v201609/error_handling/handle_partial_failures.py b/examples/adwords/v201802/error_handling/handle_partial_failures.py similarity index 78% rename from examples/adwords/v201609/error_handling/handle_partial_failures.py rename to examples/adwords/v201802/error_handling/handle_partial_failures.py index 6d2e7f3d..9efc7237 100755 --- a/examples/adwords/v201609/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201802/error_handling/handle_partial_failures.py @@ -26,7 +26,6 @@ """ -import re from googleads import adwords @@ -39,7 +38,7 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') + 'AdGroupCriterionService', version='v201802') # Construct keyword ad group criteria objects. keywords = [ @@ -102,15 +101,27 @@ def main(client, ad_group_id): criterion['criterion']['matchType'])) for error in result['partialFailureErrors']: - index = re.findall(r'operations\[(.*)\]\.', error['fieldPath']) - if index: - print ('Keyword ad group criterion with ad group id "%s" and text ' - '"%s" triggered a failure for the following reason: "%s".' - % (keywords[int(index[0])]['adGroupId'], - keywords[int(index[0])]['criterion']['text'], - error['errorString'])) + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + if (first_field_path_element and + first_field_path_element['field'] == 'operations' and + first_field_path_element['index']): + operation_index = first_field_path_element['index'] + + adgroup_criterion = operations[operation_index]['operand'] + + print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' + 'a failure for the following reason: %s.' + % (adgroup_criterion['adGroupId'], + adgroup_criterion['criterion']['text'], + error['errorString'])) else: - print 'The following failure has occurred: "%s".' % error['errorString'] + print ('A failure has occurred for the following reasons: %s\n' + % error['errorString']) if __name__ == '__main__': diff --git a/examples/adwords/v201802/error_handling/handle_policy_violation_error.py b/examples/adwords/v201802/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..e4623468 --- /dev/null +++ b/examples/adwords/v201802/error_handling/handle_policy_violation_error.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import suds + +from googleads import adwords + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') + + # Create expanded text ad that violates an exemptable policy. + exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise!!!', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + # Create text ad that violates a non-exemptable policy. + non_exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise with too long of a headline.', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + operations = [exemptable_expanded_text_ad_operation, + non_exemptable_expanded_text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except suds.WebFault, e: + for error in e.fault.detail.ApiExceptionFault.errors: + # Get the index of the failed operation from the error's field path + # elements. + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + # If the operation index is not present on the first error field path + # element, then there's no way to determine which operation to remove, + # so simply throw the exception. + if (not (first_field_path_element + and first_field_path_element['field'] == 'operations' + and first_field_path_element['index'])): + raise e + + operation_index = first_field_path_element['index'] + index = int(operation_index[0]) + operation = operations[index] + if not HandleAPIError(error, operation): + # Set non-exemptable operation to None to mark for deletion. + print ('Removing operation with non-exemptable error at index %s.' + % operation_index) + operations[index] = None + + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is "%s".' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +def HandleAPIError(error, operation): + """Makes an exemption for exemptable PolicyViolationErrors. + + Args: + error: the error associated with the given operation. + operation: the operation associated with the given error. + + Returns: + A boolean that is True if the given error was an exemptable + PolicyViolationError; otherwise, returns False. + """ + is_exemptable = False + + # Determine if the operation can be resubmitted with an exemption request. + if error['ApiError.Type'] == 'PolicyViolationError': + expanded_text_ad = operation['operand']['ad'] + is_exemptable = (error['isExemptable'] if 'isExemptable' in error else + False) + print ('Ad with headline "%s - %s" violated %s policy "%s".' % + (expanded_text_ad['headlinePart1'], + expanded_text_ad['headlinePart2'], + 'exemptable' if is_exemptable else 'non-exemptable', + error['externalPolicyName'])) + + if is_exemptable: + # Add exemption request to the operation. + print ('Adding exemption request for policy name "%s" on text "%s".' + % (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({'key': error['key']}) + + return is_exemptable + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201702/extensions/__init__.py b/examples/adwords/v201802/extensions/__init__.py similarity index 100% rename from examples/adwords/v201702/extensions/__init__.py rename to examples/adwords/v201802/extensions/__init__.py diff --git a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py similarity index 97% rename from examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py rename to examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py index 80ee4f96..40381a65 100755 --- a/examples/adwords/v201609/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py @@ -91,7 +91,7 @@ def main(client, gmb_email_address, gmb_access_token, 'operand': feed }] - gmb_response = client.GetService('FeedService', version='v201609').mutate( + gmb_response = client.GetService('FeedService', version='v201802').mutate( gmb_operations) added_feed = gmb_response['value'][0] print 'Added GMB feed with ID: %d\n' % added_feed['id'] @@ -119,7 +119,7 @@ def main(client, gmb_email_address, gmb_access_token, } customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201609') + 'CustomerFeedService', version='v201802') added_customer_feed = None i = 0 diff --git a/examples/adwords/v201609/extensions/add_prices.py b/examples/adwords/v201802/extensions/add_prices.py similarity index 88% rename from examples/adwords/v201609/extensions/add_prices.py rename to examples/adwords/v201802/extensions/add_prices.py index 771c6615..9d77294d 100755 --- a/examples/adwords/v201609/extensions/add_prices.py +++ b/examples/adwords/v201802/extensions/add_prices.py @@ -38,19 +38,23 @@ def main(client, campaign_id): # Initialize appropriate service. customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201609') + 'CustomerExtensionSettingService', 'v201802') # To create a price extension, at least three table rows are needed. table_rows = [ CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR'), + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', + final_mobile_url='http://m.example.com/scrubs'), CreatePriceTableRow('Hair Cuts', 'Once a month', 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH'), + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url='http://m.example.com/haircuts'), CreatePriceTableRow('Skin Care Package', 'Four times a month', 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH') + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url=( + 'http://m.example.com/skincarepackage')) ] # Create the price extension feed item. @@ -108,7 +112,7 @@ def main(client, campaign_id): def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit): + currency_code, price_unit, final_mobile_url=None): """Helper function to generate a single row of a price table. Args: @@ -119,11 +123,13 @@ def CreatePriceTableRow(header, description, final_url, price_in_micros, micros. currency_code: A str indicating the currency code being used. price_unit: A str enum indicating the price unit for this row. + final_mobile_url: A str containing the final mobile URL after all cross + domain redirects. Returns: A dictionary containing the contents of the generated price table row. """ - return { + table_row = { 'header': header, 'description': description, 'finalUrls': {'urls': [final_url]}, @@ -137,6 +143,13 @@ def CreatePriceTableRow(header, description, final_url, price_in_micros, 'xsi_type': 'PriceTableRow' } + if final_mobile_url: + table_row['finalMobileUrls'] = { + 'urls': [final_mobile_url] + } + + return table_row + if __name__ == '__main__': # Initialize client object. diff --git a/examples/adwords/v201609/extensions/add_site_links.py b/examples/adwords/v201802/extensions/add_site_links.py similarity index 98% rename from examples/adwords/v201609/extensions/add_site_links.py rename to examples/adwords/v201802/extensions/add_site_links.py index 65806e36..2a13cbcb 100755 --- a/examples/adwords/v201609/extensions/add_site_links.py +++ b/examples/adwords/v201802/extensions/add_site_links.py @@ -36,8 +36,8 @@ def main(client, campaign_id): # Initialize appropriate services. campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201609') - customer_service = client.GetService('CustomerService', version='v201609') + 'CampaignExtensionSettingService', version='v201802') + customer_service = client.GetService('CustomerService', version='v201802') # Find the matching customer and its time zone. The getCustomers method will # return a single Customer object corresponding to the configured # clientCustomerId. diff --git a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py b/examples/adwords/v201802/extensions/add_site_links_using_feeds.py similarity index 98% rename from examples/adwords/v201609/extensions/add_site_links_using_feeds.py rename to examples/adwords/v201802/extensions/add_site_links_using_feeds.py index 83eae4ae..738ffda7 100755 --- a/examples/adwords/v201609/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201802/extensions/add_site_links_using_feeds.py @@ -46,12 +46,12 @@ def main(client, campaign_id): # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201609') - feed_item_service = client.GetService('FeedItemService', version='v201609') + feed_service = client.GetService('FeedService', version='v201802') + feed_item_service = client.GetService('FeedItemService', version='v201802') feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201609') + 'FeedMappingService', version='v201802') campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201609') + 'CampaignFeedService', version='v201802') sitelinks_data = {} diff --git a/examples/adwords/v201702/migration/__init__.py b/examples/adwords/v201802/migration/__init__.py similarity index 100% rename from examples/adwords/v201702/migration/__init__.py rename to examples/adwords/v201802/migration/__init__.py diff --git a/examples/adwords/v201609/migration/migrate_to_extension_settings.py b/examples/adwords/v201802/migration/migrate_to_extension_settings.py similarity index 98% rename from examples/adwords/v201609/migration/migrate_to_extension_settings.py rename to examples/adwords/v201802/migration/migrate_to_extension_settings.py index 9cbbdc17..3dbb69ff 100755 --- a/examples/adwords/v201609/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201802/migration/migrate_to_extension_settings.py @@ -52,7 +52,6 @@ 'TRACKING_URL_TEMPLATE': 7 } - PAGE_SIZE = 500 @@ -69,7 +68,7 @@ def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, platform_restrictions: an optional Platform Restriction for the Feed items. """ campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201609') + 'CampaignExtensionSettingService', 'v201802') extension_feed_items = [{ CreateSitelinkFeedItem(feed_items, feed_item_id) @@ -140,7 +139,7 @@ def DeleteCampaignFeed(client, campaign_feed): client: an AdWordsClient instance. campaign_feed: the campaign feed to delete. """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201609') + campaign_feed_service = client.GetService('CampaignFeedService', 'v201802') operation = { 'operand': campaign_feed, @@ -161,7 +160,7 @@ def DeleteOldFeedItems(client, feed_item_ids, feed): if not feed_item_ids: return - feed_item_service = client.GetService('FeedItemService', 'v201609') + feed_item_service = client.GetService('FeedItemService', 'v201802') operations = [{ 'operator': 'REMOVE', @@ -185,7 +184,7 @@ def GetCampaignFeeds(client, feed, placeholder_type): Returns: A list of Feed Item Ids. """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201609') + campaign_feed_service = client.GetService('CampaignFeedService', 'v201802') campaign_feeds = [] more_pages = True @@ -236,7 +235,7 @@ def GetFeeds(client): Returns: A list containing all enabled Feeds. """ - feed_service = client.GetService('FeedService', 'v201609') + feed_service = client.GetService('FeedService', 'v201802') feeds = [] more_pages = True @@ -283,7 +282,7 @@ def GetFeedItems(client, feed): Returns: The Feed Items associated with the given Feed. """ - feed_item_service = client.GetService('FeedItemService', 'v201609') + feed_item_service = client.GetService('FeedItemService', 'v201802') feed_items = [] more_pages = True @@ -359,7 +358,7 @@ def GetFeedMapping(client, feed, placeholder_type): Returns: A dictionary containing the Feed Mapping. """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201609') + feed_mapping_service = client.GetService('FeedMappingService', 'v201802') attribute_mappings = {} more_pages = True @@ -411,7 +410,7 @@ def GetPlatformRestrictions(campaign_feed): """Get the Platform Restrictions for a given Campaign Feed. Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. + campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for. Returns: The Platform Restrictions for the given feed. diff --git a/examples/adwords/v201702/misc/__init__.py b/examples/adwords/v201802/misc/__init__.py similarity index 100% rename from examples/adwords/v201702/misc/__init__.py rename to examples/adwords/v201802/misc/__init__.py diff --git a/examples/adwords/v201609/misc/get_all_images_and_videos.py b/examples/adwords/v201802/misc/get_all_images_and_videos.py similarity index 99% rename from examples/adwords/v201609/misc/get_all_images_and_videos.py rename to examples/adwords/v201802/misc/get_all_images_and_videos.py index eabf2367..294477ef 100755 --- a/examples/adwords/v201609/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201802/misc/get_all_images_and_videos.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201609') + media_service = client.GetService('MediaService', version='v201802') # Construct selector and get all images. offset = 0 diff --git a/examples/adwords/v201702/misc/upload_image.py b/examples/adwords/v201802/misc/upload_image.py similarity index 99% rename from examples/adwords/v201702/misc/upload_image.py rename to examples/adwords/v201802/misc/upload_image.py index 24641899..d80c284d 100755 --- a/examples/adwords/v201702/misc/upload_image.py +++ b/examples/adwords/v201802/misc/upload_image.py @@ -35,7 +35,7 @@ def main(client, image_filename): # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201702') + media_service = client.GetService('MediaService', version='v201802') with open(image_filename, 'rb') as image_handle: image_data = base64.encodestring(image_handle.read()).decode('utf-8') diff --git a/examples/adwords/v201702/misc/upload_media_bundle.py b/examples/adwords/v201802/misc/upload_media_bundle.py similarity index 93% rename from examples/adwords/v201702/misc/upload_media_bundle.py rename to examples/adwords/v201802/misc/upload_media_bundle.py index 16b63bd2..e09a3a1e 100755 --- a/examples/adwords/v201702/misc/upload_media_bundle.py +++ b/examples/adwords/v201802/misc/upload_media_bundle.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201702') + media_service = client.GetService('MediaService', version='v201802') # Create HTML5 media. base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( 'https://goo.gl/9Y7qI2') @@ -50,7 +50,8 @@ def main(client): def GetBase64EncodedHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) - return base64.b64encode(response.read()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return base64.b64encode(response.read()).decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201702/optimization/__init__.py b/examples/adwords/v201802/optimization/__init__.py similarity index 100% rename from examples/adwords/v201702/optimization/__init__.py rename to examples/adwords/v201802/optimization/__init__.py diff --git a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py b/examples/adwords/v201802/optimization/estimate_keyword_traffic.py similarity index 99% rename from examples/adwords/v201702/optimization/estimate_keyword_traffic.py rename to examples/adwords/v201802/optimization/estimate_keyword_traffic.py index 49b75cde..28465e7a 100755 --- a/examples/adwords/v201702/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201802/optimization/estimate_keyword_traffic.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201702') + 'TrafficEstimatorService', version='v201802') # Construct selector object and retrieve traffic estimates. keywords = [ diff --git a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py similarity index 94% rename from examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py rename to examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py index 4a6039d6..ec07bb79 100755 --- a/examples/adwords/v201609/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ b/examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -29,12 +29,12 @@ CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 +PAGE_SIZE = 100 def main(client, campaign_id): # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201609') + data_service = client.GetService('DataService', version='v201802') # Get all the campaigns for this account. selector = { @@ -83,10 +83,11 @@ def main(client, campaign_id): else: print 'No bid modifier landscapes found.' - # Need to increment by the total # of landscape points within the page. + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. offset += num_landscape_points selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) + more_pages = num_landscape_points >= PAGE_SIZE if __name__ == '__main__': diff --git a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201802/optimization/get_keyword_bid_simulations.py similarity index 59% rename from examples/adwords/v201609/optimization/get_keyword_bid_simulations.py rename to examples/adwords/v201802/optimization/get_keyword_bid_simulations.py index 6305dce5..edc2c8f3 100755 --- a/examples/adwords/v201609/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201802/optimization/get_keyword_bid_simulations.py @@ -30,15 +30,17 @@ AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' CRITERION_ID = 'INSERT_CRITERION_ID_HERE' +PAGE_SIZE = 100 def main(client, ad_group_id, criterion_id): # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201609') + data_service = client.GetService('DataService', version='v201802') # Construct bid landscape selector object and retrieve bid landscape. selector = { 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'BiddableConversions', 'BiddableConversionsValue', 'LocalClicks', 'LocalCost', 'LocalImpressions'], 'predicates': [ { @@ -51,27 +53,48 @@ def main(client, ad_group_id, criterion_id): 'operator': 'EQUALS', 'values': [criterion_id] } - ] + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id "%s", criterion id ' - '"%s", start date "%s", end date "%s", with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages: + num_landscape_points = 0 + page = data_service.getCriterionBidLandscape(selector) + + if page and 'entries' in page: + entries = page['entries'] + print 'Bid landscape(s) retrieved: %d.' % len(entries) + + for bid_landscape in entries: + print ('Retrieved keyword bid landscape with ad group ID "%d", ' + 'keyword ID "%d", start date "%s", end date "%s", ' + 'with landscape points:' % ( + bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' + num_landscape_points += 1 + print (' bid: %s => clicks: %s, cost: %s, impressions: %s, ' + 'biddable conversions: %.2f, ' + 'biddable conversions value: %.2f' % (bid_landscape_point['bid']['microAmount'], bid_landscape_point['clicks'], bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' + bid_landscape_point['impressions'], + bid_landscape_point['biddableConversions'], + bid_landscape_point['biddableConversionsValue'])) + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE if __name__ == '__main__': diff --git a/examples/adwords/v201702/optimization/get_keyword_ideas.py b/examples/adwords/v201802/optimization/get_keyword_ideas.py similarity index 56% rename from examples/adwords/v201702/optimization/get_keyword_ideas.py rename to examples/adwords/v201802/optimization/get_keyword_ideas.py index cb4771e6..d2e42701 100755 --- a/examples/adwords/v201702/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201802/optimization/get_keyword_ideas.py @@ -26,49 +26,62 @@ from googleads import adwords +# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' PAGE_SIZE = 100 -def main(client): +def main(client, ad_group_id=None): # Initialize appropriate service. targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201702') + 'TargetingIdeaService', version='v201802') # Construct selector object and retrieve related keywords. - offset = 0 selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } + 'requestType': 'IDEAS' + } + + selector['requestedAttributeTypes'] = [ + 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] + + offset = 0 + selector['paging'] = { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) } + + selector['searchParameters'] = [{ + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }] + + # Language setting (optional). + selector['searchParameters'].append({ + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }) + + # Network search parameter (optional) + selector['searchParameters'].append({ + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + }) + + # Use an existing ad group to generate ideas (optional) + if ad_group_id is not None: + selector['searchParameters'].append({ + 'xsi_type': 'SeedAdGroupIdSearchParameter', + 'adGroupId': ad_group_id + }) + more_pages = True while more_pages: page = targeting_idea_service.get(selector) @@ -78,8 +91,8 @@ def main(client): for result in page['entries']: attributes = {} for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') + attributes[attribute['key']] = getattr( + attribute['value'], 'value', '0') print ('Keyword with "%s" text and average monthly search volume ' '"%s" was found with Products and Services categories: %s.' % (attributes['KEYWORD_TEXT'], @@ -97,4 +110,4 @@ def main(client): # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) + main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201702/remarketing/__init__.py b/examples/adwords/v201802/remarketing/__init__.py similarity index 100% rename from examples/adwords/v201702/remarketing/__init__.py rename to examples/adwords/v201802/remarketing/__init__.py diff --git a/examples/adwords/v201609/remarketing/add_audience.py b/examples/adwords/v201802/remarketing/add_audience.py similarity index 69% rename from examples/adwords/v201609/remarketing/add_audience.py rename to examples/adwords/v201802/remarketing/add_audience.py index 9945364d..2d5de75e 100755 --- a/examples/adwords/v201609/remarketing/add_audience.py +++ b/examples/adwords/v201802/remarketing/add_audience.py @@ -28,12 +28,15 @@ from googleads import adwords +PAGE_SIZE = 100 + + def main(client): # Initialize appropriate service. user_list_service = client.GetService( - 'AdwordsUserListService', version='v201609') + 'AdwordsUserListService', version='v201802') conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201609') + 'ConversionTrackerService', version='v201802') # Construct operations and add a user list. operations = [ @@ -55,43 +58,41 @@ def main(client): } } ] - result = user_list_service.mutate(operations) + user_list_result = user_list_service.mutate(operations) - # Display results. - if 'value' in result: + # Capture the ID(s) of the conversion. + if 'value' in user_list_result: conversion_ids = [] - for user_list in result['value']: + for user_list in user_list_result['value']: if user_list['conversionTypes']: for conversion_type in user_list['conversionTypes']: conversion_ids.append(conversion_type['id']) - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) + # Create query. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'GoogleGlobalSiteTag', 'GoogleEventSnippet') + .Where('Id').In(*conversion_ids) + .Limit(0, PAGE_SIZE) + .Build()) + conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - for user_list in result['value']: + # Get all conversion trackers. + for page in query.Pager(conversion_tracker_service): + if 'entries' in page: + for conversion_tracker in page['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in user_list_result['value']: print ('User list with name "%s" and ID "%s" was added.' % (user_list['name'], user_list['id'])) if user_list['conversionTypes']: for conversion_type in user_list['conversionTypes']: conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) + print ('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print ('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) else: print 'No user lists were added.' diff --git a/examples/adwords/v201702/remarketing/add_conversion_tracker.py b/examples/adwords/v201802/remarketing/add_conversion_tracker.py similarity index 97% rename from examples/adwords/v201702/remarketing/add_conversion_tracker.py rename to examples/adwords/v201802/remarketing/add_conversion_tracker.py index 35395256..fedea7a0 100755 --- a/examples/adwords/v201702/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201802/remarketing/add_conversion_tracker.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201702') + 'ConversionTrackerService', version='v201802') # Construct operations and add conversion_tracker. operations = [ diff --git a/examples/adwords/v201802/remarketing/add_conversion_trackers.py b/examples/adwords/v201802/remarketing/add_conversion_trackers.py new file mode 100755 index 00000000..5e96e8c8 --- /dev/null +++ b/examples/adwords/v201802/remarketing/add_conversion_trackers.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds AdWords conversion trackers. + +Adds an AdWords conversion tracker and an upload conversion tracker. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201802') + + # Create an AdWords conversion tracker. + adwords_conversion_tracker = { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'name': 'Upload Conversion #%s' % uuid.uuid4(), + # Optional fields. + # Set an appropriate category. This will be set to DEFAULT if not + # specified. + 'category': 'LEAD', + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90', + # Set the default currency code to use for conversions that do + # not specify a conversion currency. This must be an ISO 4217 3-character + # code such as "EUR" or "USD". + # If this field is not set, AdWords will use the account's currency. + 'defaultRevenueCurrencyCode': 'EUR', + # Set the default revenue value to use for conversions that do not specify + # a converison value. Note that this value should NOT be in micros. + 'defaultRevenueValue': '2.50', + # To upload fractional conversion credits, mark the upload conversion as + # externally attributed. To learn more about importing externally + # attributed conversions, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'isExternallyAttributed': 'true' + } + + # Construct operations. + operations = [{ + 'operator': 'ADD', + 'operand': conversion_tracker + } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] + + # Add the conversions. + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion with ID "%d", name "%s", status "%s", and category ' + '"%s" was added.' + % (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + if (conversion_tracker['ConversionTracker.Type'] + == 'AdWordsConversionTracker'): + print ('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print ('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py b/examples/adwords/v201802/remarketing/add_crm_based_user_list.py similarity index 68% rename from examples/adwords/v201702/remarketing/add_crm_based_user_list.py rename to examples/adwords/v201802/remarketing/add_crm_based_user_list.py index 37fefc3b..e542c0fc 100755 --- a/examples/adwords/v201702/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201802/remarketing/add_crm_based_user_list.py @@ -31,16 +31,18 @@ from googleads import adwords -def main(client, emails): +def main(client): # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201702') + user_list_service = client.GetService('AdwordsUserListService', 'v201802') user_list = { 'xsi_type': 'CrmBasedUserList', 'name': 'Customer relationship management list #%d' % uuid.uuid4(), 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 + # See limit here: + # https://support.google.com/adwords/answer/6276125#requirements + 'membershipLifeSpan': 30, + 'uploadKeyType': 'CONTACT_INFO' } # Create an operation to add the user list. @@ -51,13 +53,27 @@ def main(client, emails): result = user_list_service.mutate(operations) user_list_id = result['value'][0]['id'] - hashed_emails = HashEmails(emails) + + emails = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] + + # Add address info. + members.append({ + 'addressInfo': { + # First and last name must be normalized and hashed. + 'hashedFirstName': NormalizeAndSHA256('John'), + 'hashedLastName': NormalizeAndSHA256('Doe'), + # Country code and zip code are sent in plaintext. + 'countryCode': 'US', + 'zipCode': '10001' + } + }) mutate_members_operation = { 'operand': { 'userListId': user_list_id, - 'dataType': 'EMAIL_SHA256', - 'members': hashed_emails + 'membersList': members }, 'operator': 'ADD' } @@ -70,25 +86,19 @@ def main(client, emails): % (user_list['name'], user_list['id'])) -def HashEmails(emails): - """Hashes the given emails using SHA-256. - - Note: Emails are stripped of any whitespace and set to lowercase before - hashing. +def NormalizeAndSHA256(s): + """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. Args: - emails: list of str emails to be hashed. + s: The string to perform this operation on. Returns: - A list of SHA-256 hashed emails. + A normalized and SHA-256 hashed string. """ - return [hashlib.sha256(email.strip().lower()).hexdigest() for email in emails] + return hashlib.sha256(s.strip().lower()).hexdigest() if __name__ == '__main__': - EMAILS = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, EMAILS) + main(adwords_client) diff --git a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201802/remarketing/add_rule_based_user_lists.py similarity index 73% rename from examples/adwords/v201609/remarketing/add_rule_based_user_lists.py rename to examples/adwords/v201802/remarketing/add_rule_based_user_lists.py index 9833ba06..d291310e 100755 --- a/examples/adwords/v201609/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201802/remarketing/add_rule_based_user_lists.py @@ -38,7 +38,7 @@ def main(client): # Initialize appropriate service. adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201609') + 'AdwordsUserListService', version='v201802') # First rule item group - users who visited the checkout page and had more # than one item in their shopping cart. @@ -97,13 +97,49 @@ def main(client): 'items': [start_date_rule_item, three_months_later_rule_item] } - # Combine the rule item groups into a Rule so AdWords will logically OR the - # groups together. + # Combine the rule item groups into a Rule so AdWords knows how to apply the + # rules. rule = { 'groups': [ checkout_multiple_item_group, checked_out_date_range_item_group - ] + ], + # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF + # means 'at least one item in each rule item group must match', and DNF + # means 'at least one entire rule item group must match'. + # DateSpecificRuleUserList only supports DNF. You can also omit the rule + # type altogether to default to DNF. + 'ruleType': 'DNF' + } + + # Third and fourth rule item groups. + # Visitors of a page who visited another page. + site1_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example1' + } + } + site2_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example2' + } + } + + # Create two rules to show that a visitor browsed two sites. + user_visited_site1_rule = { + 'groups': [{ + 'items': [site1_rule_item] + }] + } + + user_visited_site2_rule = { + 'groups': [{ + 'items': [site2_rule_item] + }] } # Create the user list with no restrictions on site visit date. @@ -114,7 +150,10 @@ def main(client): 'description': 'Users who checked out in three month window OR visited' ' the checkout page with more than one item in their' ' cart.', - 'rule': rule + 'rule': rule, + # Optional: Set the populationStatus to REQUESTED to include past users in + # the user list. + 'prepopulationStatus': 'REQUESTED' } # Create the user list restricted to users who visit your site within the next @@ -134,12 +173,25 @@ def main(client): 'endDate': end_date.strftime('%Y%m%d') } + # Create the user list for "Visitors of a page who did visit another page". + # To create a user list for "Visitors of a page who did not visit another + # page", change the ruleOperator from AND to AND_NOT. + combined_user_list = { + 'xsi_type': 'CombinedRuleUserList', + 'name': 'Combined rule user lst create at ${creation_time}', + 'description': 'Users who visited two sites.', + 'leftOperand': user_visited_site1_rule, + 'rightOperand': user_visited_site2_rule, + 'ruleOperator': 'AND' + } + # Create operations to add the user lists. operations = [ { 'operand': user_list, 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] + } for user_list in [expression_user_list, date_user_list, + combined_user_list] ] # Submit the operations. diff --git a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201802/remarketing/upload_offline_call_conversions.py similarity index 95% rename from examples/adwords/v201702/remarketing/upload_offline_call_conversions.py rename to examples/adwords/v201802/remarketing/upload_offline_call_conversions.py index 27e355c4..4321e895 100755 --- a/examples/adwords/v201702/remarketing/upload_offline_call_conversions.py +++ b/examples/adwords/v201802/remarketing/upload_offline_call_conversions.py @@ -16,7 +16,7 @@ """Imports offline conversion values for calls related to ads in your account. -To set up a conversion tracker, run the add_conversion_tracker.py example. +To set up a conversion tracker, run the add_conversion_trackers.py example. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -43,7 +43,7 @@ def main(client, caller_id, call_start_time, conversion_name, conversion_time, conversion_value): # Initialize appropriate services. occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201702') + 'OfflineCallConversionFeedService', version='v201802') # Associate offline call conversions with the existing named conversion # tracker. If this tracker was newly created, it may be a few hours before it diff --git a/examples/adwords/v201609/remarketing/upload_offline_conversions.py b/examples/adwords/v201802/remarketing/upload_offline_conversions.py similarity index 79% rename from examples/adwords/v201609/remarketing/upload_offline_conversions.py rename to examples/adwords/v201802/remarketing/upload_offline_conversions.py index 80704387..3d84c0c4 100755 --- a/examples/adwords/v201609/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201802/remarketing/upload_offline_conversions.py @@ -17,7 +17,7 @@ """Imports offline conversion values for specific clicks into your account. To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. +up a conversion tracker, run the add_conversion_trackers.py example. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -40,7 +40,7 @@ def main(client, conversion_name, click_id, conversion_time, conversion_value): # Initialize appropriate services. offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201609') + 'OfflineConversionFeedService', version='v201802') # Associate offline conversions with the existing named conversion tracker. If # this tracker was newly created, it may be a few hours before it can accept @@ -49,7 +49,14 @@ def main(client, conversion_name, click_id, conversion_time, conversion_value): 'conversionName': conversion_name, 'conversionTime': conversion_time, 'conversionValue': conversion_value, - 'googleClickId': click_id + 'googleClickId': click_id, + # Optional: To upload fractional conversion credits, set the external + # attribution model and credit. To use this feature, your conversion + # tracker should be marked as externally attributed. To learn more about + # importing externally attributed conversins, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'externalAttributionCredit': 0.3, + # 'externalAttributionModel': 'Linear' } offline_conversion_operation = { diff --git a/examples/adwords/v201802/remarketing/upload_offline_data.py b/examples/adwords/v201802/remarketing/upload_offline_data.py new file mode 100755 index 00000000..6f834e3e --- /dev/null +++ b/examples/adwords/v201802/remarketing/upload_offline_data.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 shows how to upload offline data for store sales transactions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import datetime +import hashlib + +from googleads import adwords +import pytz + + +_DT_FORMAT = '%Y%m%d %H%M%S' +# User identifier types whose values must be hashed. +_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', + 'HASHED_LAST_NAME', 'HASHED_PHONE') +# The timezone to be used in this example. For valid timezone IDs, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +_TIMEZONE = pytz.timezone('America/New_York') +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Insert email addresses below for creating user identifiers. +EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] +# The external upload ID can be any number that you use to keep track of your +# uploads. +EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' +# Store sales upload common metadata types +METADATA_TYPE_1P = 'FirstPartyUploadMetadata' +METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' +# Set the below constant to METADATA_TYPE_3P if uploading third-party data. +STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P +# The three constants below are needed when uploading third-party data. They +# are not used when uploading first-party data. +# Advertiser upload time to partner. +# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, +# see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' +# Indicates the version of the bridge map. +BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' +# The ID of the third party uploading the transaction feed. +PARTNER_ID = 'INSERT_PARTNER_ID_HERE' + + +def main(client, conversion_name, external_upload_id, + store_sales_upload_common_metadata_type, email_addresses, + advertiser_upload_time=None, bridge_map_version_id=None, + partner_id=None): + # Set partial failure to True since this example demonstrates how to handle + # partial errors. + client.partial_failure = True + # Initialize appropriate services. + offline_data_upload_service = client.GetService( + 'OfflineDataUploadService', version='v201802') + + # Create the first offline data for upload. + # This transaction occurred 7 days ago with an amount of $200 USD. + transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=7)) + offline_data_1 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[0]), + _CreateUserIdentifier(identifier_type='STATE', value='New York') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_1), + 'transactionAmount': { + 'currencyCode': 'USD', + 'money': { + 'microAmount': 200000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create the second offline data for upload. + # This transaction occurred 14 days ago with amount of 450 EUR. + transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=14)) + offline_data_2 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[1]), + _CreateUserIdentifier(identifier_type='STATE', value='California') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_2), + 'transactionAmount': { + 'currencyCode': 'EUR', + 'money': { + 'microAmount': 450000000 + } + }, + 'conversionName': conversion_name + } + } + + # Set the type and metadata of this upload. + upload_metadata = { + 'StoreSalesUploadCommonMetadata': { + 'xsi_type': store_sales_upload_common_metadata_type, + 'loyaltyRate': 1.0, + 'transactionUploadRate': 1.0, + } + } + + if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: + upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' + elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: + upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' + upload_metadata['StoreSalesUploadCommonMetadata'].update({ + 'advertiserUploadTime': advertiser_upload_time, + 'validTransactionRate': 1.0, + 'partnerMatchRate': 1.0, + 'partnerUploadRate': 1.0, + 'bridgeMapVersionId': bridge_map_version_id, + 'partnerId': partner_id + }) + else: + raise ValueError('Unknown metadata type.') + + # Create offline data upload + offline_data_upload = { + 'externalUploadId': external_upload_id, + 'offlineDataList': [offline_data_1, offline_data_2], + # Set the type of this upload. + 'uploadType': upload_type, + 'uploadMetadata': upload_metadata + } + + # Create an offline data upload operation. + operations = [{ + 'operator': 'ADD', + 'operand': offline_data_upload + }] + + # Upload offline data on the server and print the result. + result = offline_data_upload_service.mutate(operations) + offline_data_upload = result['value'][0] + + print ('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) + + # Print any partial data errors from the response. + if result['partialFailureErrors']: + for api_error in result['partialFailureErrors']: + # Get the index of the failed operation from the error's field path + # elements. + operation_index = _GetFieldPathElementIndex(api_error, 'operations') + + if operation_index: + failed_offline_data_upload = operations[operation_index]['operand'] + # Get the index of the entry in the offline data list from the error's + # field path elements. + offline_data_list_index = _GetFieldPathElementIndex( + api_error, 'offlineDataList') + print ('Offline data list entry "%d" in operation "%d" with external ' + 'upload ID "%d" and type "%s" has triggered failure for the ' + 'following reason: "%s"' % ( + offline_data_list_index, operation_index, + failed_offline_data_upload['externalUploadId'], + failed_offline_data_upload['uploadType'], + api_error['errorString'])) + else: + print ('A failure has occurred for the following reason: "%s".' % ( + api_error['errorString'])) + + +def _CreateUserIdentifier(identifier_type=None, value=None): + """Creates a user identifier from the specified type and value. + + Args: + identifier_type: a str specifying the type of user identifier. + value: a str value of the identifier; to be hashed using SHA-256 if needed. + + Returns: + A dict specifying a user identifier, with a value hashed using SHA-256 if + needed. + """ + if identifier_type in _HASHED_IDENTIFIER_TYPES: + # If the user identifier type is a hashed type, normalize and hash the + # value. + value = hashlib.sha256(value.strip().lower()).hexdigest() + + user_identifier = { + 'userIdentifierType': identifier_type, + 'value': value + } + + return user_identifier + + +def _GetFieldPathElementIndex(api_error, field): + """Retrieve the index of a given field in the api_error's fieldPathElements. + + Args: + api_error: a dict containing a partialFailureError returned from the AdWords + API. + field: a str field for which this determines the index in the api_error's + fieldPathElements. + + Returns: + An int index of the field path element, or None if the specified field can't + be found in the api_error. + """ + field_path_elements = api_error['fieldPathElements'] + + if field_path_elements: + found_index = [field_path_element['index'] + for field_path_element in field_path_elements + if field_path_element['field'] == field] + if found_index: + return found_index + + return None + + +def _GetFormattedDateTime(dt): + """Formats the given datetime and timezone for use with AdWords. + + Args: + dt: a datetime instance. + + Returns: + A str representation of the datetime in the correct format for AdWords. + """ + return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, + STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, + ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201702/reporting/__init__.py b/examples/adwords/v201802/reporting/__init__.py similarity index 100% rename from examples/adwords/v201702/reporting/__init__.py rename to examples/adwords/v201802/reporting/__init__.py diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py similarity index 82% rename from examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py rename to examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py index 58394d18..3266a5a5 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py @@ -44,14 +44,17 @@ def main(client): # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201702') + report_downloader = client.GetReportDownloader(version='v201802') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py similarity index 97% rename from examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py rename to examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py index 5930c757..9525feb1 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_stream_with_selector.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py @@ -40,7 +40,7 @@ def main(client): - report_downloader = client.GetReportDownloader(version='v201702') + report_downloader = client.GetReportDownloader(version='v201802') # Create report definition. report = { diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py similarity index 76% rename from examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py rename to examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py index 63e08165..561e0d96 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py @@ -34,14 +34,17 @@ def main(client): # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201702') + report_downloader = client.GetReportDownloader(version='v201802') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) print report_downloader.DownloadReportAsStringWithAwql( report_query, 'CSV', skip_report_header=False, skip_column_header=False, diff --git a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py similarity index 96% rename from examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py rename to examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py index dad7f93c..64f72313 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_as_string_with_selector.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py @@ -34,7 +34,7 @@ def main(client): - report_downloader = client.GetReportDownloader(version='v201702') + report_downloader = client.GetReportDownloader(version='v201802') # Create report definition. report = { diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_with_awql.py similarity index 58% rename from examples/adwords/v201702/reporting/download_criteria_report_with_awql.py rename to examples/adwords/v201802/reporting/download_criteria_report_with_awql.py index 4418d62d..baeaa32b 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_with_awql.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_with_awql.py @@ -25,35 +25,34 @@ """ +import sys from googleads import adwords -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client, path): +def main(client): # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201702') + report_downloader = client.GetReportDownloader(version='v201802') # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - with open(path, 'w') as output_file: - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', output_file, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - print 'Report was downloaded to "%s".' % path + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + # You can provide a file object to write the output to. For this + # demonstration we use sys.stdout to write the report to the screen. + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', sys.stdout, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, PATH) + main(adwords_client) diff --git a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py similarity index 95% rename from examples/adwords/v201702/reporting/download_criteria_report_with_selector.py rename to examples/adwords/v201802/reporting/download_criteria_report_with_selector.py index 97f07edf..dc38faba 100755 --- a/examples/adwords/v201702/reporting/download_criteria_report_with_selector.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py @@ -35,9 +35,8 @@ def main(client): - report_downloader = client.GetReportDownloader(version='v201702') + report_downloader = client.GetReportDownloader(version='v201802') - # Create report definition. report = { 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', 'dateRangeType': 'LAST_7_DAYS', diff --git a/examples/adwords/v201609/reporting/get_report_fields.py b/examples/adwords/v201802/reporting/get_report_fields.py similarity index 96% rename from examples/adwords/v201609/reporting/get_report_fields.py rename to examples/adwords/v201802/reporting/get_report_fields.py index 90720035..87fa380c 100755 --- a/examples/adwords/v201609/reporting/get_report_fields.py +++ b/examples/adwords/v201802/reporting/get_report_fields.py @@ -32,7 +32,7 @@ def main(client, report_type): # Initialize appropriate service. report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201609') + 'ReportDefinitionService', version='v201802') # Get report fields. fields = report_definition_service.getReportFields(report_type) diff --git a/examples/adwords/v201702/reporting/parallel_report_download.py b/examples/adwords/v201802/reporting/parallel_report_download.py similarity index 99% rename from examples/adwords/v201702/reporting/parallel_report_download.py rename to examples/adwords/v201802/reporting/parallel_report_download.py index 6bbc7f90..c5d284c3 100755 --- a/examples/adwords/v201702/reporting/parallel_report_download.py +++ b/examples/adwords/v201802/reporting/parallel_report_download.py @@ -128,7 +128,7 @@ def __init__(self, client, report_download_directory, report_definition, downloads will be saved to. """ super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201702') + self.report_downloader = client.GetReportDownloader(version='v201802') self.report_download_directory = report_download_directory self.report_definition = report_definition self.input_queue = input_queue @@ -191,7 +191,7 @@ def GetCustomerIDs(client): # For this example, we will use ManagedCustomerService to get all IDs in # hierarchy that do not belong to MCC accounts. managed_customer_service = client.GetService('ManagedCustomerService', - version='v201702') + version='v201802') offset = 0 diff --git a/examples/adwords/v201702/shopping/__init__.py b/examples/adwords/v201802/shopping/__init__.py similarity index 100% rename from examples/adwords/v201702/shopping/__init__.py rename to examples/adwords/v201802/shopping/__init__.py diff --git a/examples/adwords/v201609/shopping/add_product_partition_tree.py b/examples/adwords/v201802/shopping/add_product_partition_tree.py similarity index 91% rename from examples/adwords/v201609/shopping/add_product_partition_tree.py rename to examples/adwords/v201802/shopping/add_product_partition_tree.py index 595c9d20..7c4dd3d5 100755 --- a/examples/adwords/v201609/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201802/shopping/add_product_partition_tree.py @@ -33,19 +33,6 @@ class ProductPartitionHelper(object): """A helper for creating ProductPartition trees.""" - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server we - # do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - next_id = -1 - - # The set of mutate operations needed to create the current tree. - operations = [] - def __init__(self, adgroup_id): """Initializer. @@ -53,6 +40,17 @@ def __init__(self, adgroup_id): adgroup_id: The ID of the AdGroup that we wish to attach the partition tree to. """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] self.adgroup_id = adgroup_id def CreateSubdivision(self, parent=None, value=None): @@ -158,7 +156,7 @@ def CreateAddOperation(self, criterion): def main(client, adgroup_id): """Runs the example.""" adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201609') + 'AdGroupCriterionService', version='v201802') helper = ProductPartitionHelper(adgroup_id) diff --git a/examples/adwords/v201609/shopping/add_product_scope.py b/examples/adwords/v201802/shopping/add_product_scope.py similarity index 98% rename from examples/adwords/v201609/shopping/add_product_scope.py rename to examples/adwords/v201802/shopping/add_product_scope.py index 0e1a0db0..c8a893ed 100755 --- a/examples/adwords/v201609/shopping/add_product_scope.py +++ b/examples/adwords/v201802/shopping/add_product_scope.py @@ -32,7 +32,7 @@ def main(client, campaign_id): campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201609') + 'CampaignCriterionService', version='v201802') product_scope = { 'xsi_type': 'ProductScope', diff --git a/examples/adwords/v201702/shopping/add_shopping_campaign.py b/examples/adwords/v201802/shopping/add_shopping_campaign.py similarity index 62% rename from examples/adwords/v201702/shopping/add_shopping_campaign.py rename to examples/adwords/v201802/shopping/add_shopping_campaign.py index 87cea0af..eab1d0d8 100755 --- a/examples/adwords/v201702/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201802/shopping/add_shopping_campaign.py @@ -30,13 +30,17 @@ from googleads import adwords BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +# If set to true, a default partition will be created. If running the +# add_product_partition_tree.py example right after this example, make +# sure this stays set to false. +CREATE_DEFAULT_PARTITION = False MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -def main(client, budget_id, merchant_id): - campaign_service = client.GetService('CampaignService', version='v201702') - ad_group_service = client.GetService('AdGroupService', version='v201702') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201702') +def main(client, budget_id, merchant_id, create_default_partition): + campaign_service = client.GetService('CampaignService', version='v201802') + ad_group_service = client.GetService('AdGroupService', version='v201802') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Create campaign campaign = { @@ -79,26 +83,26 @@ def main(client, budget_id, merchant_id): % (campaign['name'], campaign['id'])) # Create the AdGroup - adgroup = { + ad_group = { 'campaignId': campaign['id'], 'name': 'AdGroup #%s' % uuid.uuid4() } adgroup_operations = { 'operator': 'ADD', - 'operand': adgroup + 'operand': ad_group } # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group_result = ad_group_service.mutate(adgroup_operations) + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] - for adgroup in ad_group_result['value']: - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) + print ('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) # Create an AdGroup Ad adgroup_ad = { - 'adGroupId': adgroup['id'], + 'adGroupId': ad_group_id, # Create ProductAd 'ad': { 'xsi_type': 'ProductAd', @@ -117,9 +121,52 @@ def main(client, budget_id, merchant_id): for adgroup_ad in ad_result['value']: print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201802') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + }, + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 500000 + } + }] + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID, MERCHANT_ID) + main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py new file mode 100755 index 00000000..dd7cf540 --- /dev/null +++ b/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py @@ -0,0 +1,402 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds a Shopping campaign for Showcase ads. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import base64 +import uuid + +from googleads import adwords +from suds import WebFault + + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' +EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' +COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + # Note: Showcase ads require either ManualCpc or EnhancedCpc in the + # campaign's BiddingStrategyConfiguration. + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, budget_id, merchant_id, expanded_image_filepath, + collapsed_image_filepath): + try: + # Create the Shopping Campaign + campaign = CreateShoppingCampaign(client, budget_id, merchant_id) + + # Create the AdGroup + adgroup = CreateAdGroup(client, campaign['id']) + + # Create a Showcase Ad + CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath) + + product_partition_tree = CreateProductPartition(client, adgroup['id']) + print 'Final tree:\n%s' % product_partition_tree + except WebFault: + print 'Failed to create shopping campaign for showcase ads.' + raise + + +def CreateShoppingCampaign(client, budget_id, merchant_id): + """Creates a shopping campaign with the given budget and merchant IDs. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + shopping campaign. + + Returns: + The created Shopping Campaign as a sudsobject. + """ + campaign_service = client.GetService('CampaignService', 'v201802') + + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + campaign = campaign_service.mutate(campaign_operations)['value'][0] + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + return campaign + + +def CreateAdGroup(client, campaign_id): + """Creates an AdGroup for the given shopping campaign ID. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a shopping campaign. + + Returns: + The created AdGroup as a sudsobject. + """ + ad_group_service = client.GetService('AdGroupService', 'v201802') + + adgroup = { + # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS + 'adGroupType': 'SHOPPING_SHOWCASE_ADS', + 'campaignId': campaign_id, + 'name': 'AdGroup #%s' % uuid.uuid4(), + # REQUIRED: Set the ad group's bidding strategy configuration. + 'biddingStrategyConfiguration': { + # Showcase ads require either ManualCpc or EnhancedCpc. + 'biddingStrategyType': 'MANUAL_CPC', + # Optional: Set the bids + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 100000 + } + }] + } + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) + + return adgroup + + +def CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath): + """Creates a showcase add for the given AdGroup with the given images. + + Args: + client: an AdWordsClient instance. + adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + expanded_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's expandedImage. + collapsed_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's collapsedImage. + + Returns: + The created Showcase Ad as a sudsobject. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') + + showcase_ad = { + 'adGroupId': adgroup['id'], + 'ad': { + 'xsi_type': 'ShowcaseAd', + 'Ad.Type': 'ShowcaseAd', + # Required: set the ad's name, final URLs, and display URL. + 'name': 'Showcase ad #%s' % uuid.uuid4(), + 'finalUrls': 'http://example.com/showcase', + 'displayUrl': 'example.com', + # Required: Set the ad's expanded image. + 'expandedImage': { + 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] + }, + # Optional: Set the collapsed image. + 'collapsedImage': { + 'mediaId': + UploadImage(client, collapsed_image_filepath)['mediaId'] + } + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': showcase_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] + + print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + + return showcase_ad + + +def UploadImage(client, filepath): + """Uploads a .jpg image with the given filepath via the AdWords MediaService. + + Args: + client: an AdWordsClient instance. + filepath: a str filepath to the .jpg file to be uploaded. + + Returns: + The created Image as a sudsobject. + """ + media_service = client.GetService('MediaService', 'v201802') + + with open(filepath, 'rb') as image_handle: + image_data = base64.encodestring(image_handle.read()).decode('utf-8') + + image = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + + image = media_service.upload(image)[0] + + return image + + +def CreateProductPartition(client, adgroup_id): + """Creates a ProductPartition tree for the given AdGroup ID. + + Args: + client: an AdWordsClient instance. + adgroup_id: a str AdGroup ID. + + Returns: + The ProductPartition tree as a sudsobject. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + 'v201802') + helper = ProductPartitionHelper(adgroup_id) + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition) + helper.CreateUnit(root, used_product_canonical_condition) + helper.CreateUnit(root, other_product_canonical_condition) + + result = ad_group_criterion_service.mutate(helper.operations) + return result['value'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, + COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py b/examples/adwords/v201802/shopping/get_product_category_taxonomy.py similarity index 99% rename from examples/adwords/v201609/shopping/get_product_category_taxonomy.py rename to examples/adwords/v201802/shopping/get_product_category_taxonomy.py index e2143ef4..59b8a20c 100755 --- a/examples/adwords/v201609/shopping/get_product_category_taxonomy.py +++ b/examples/adwords/v201802/shopping/get_product_category_taxonomy.py @@ -29,7 +29,7 @@ def main(client): - service = client.GetService('ConstantDataService', version='v201609') + service = client.GetService('ConstantDataService', version='v201802') selector = { 'predicates': [ diff --git a/examples/adwords/v201702/targeting/__init__.py b/examples/adwords/v201802/targeting/__init__.py similarity index 100% rename from examples/adwords/v201702/targeting/__init__.py rename to examples/adwords/v201802/targeting/__init__.py diff --git a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py similarity index 82% rename from examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py rename to examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py index 25dc2cce..ca6bc2fd 100755 --- a/examples/adwords/v201609/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py @@ -39,7 +39,7 @@ def main(client, campaign_id, location_feed_id=None): # Initialize appropriate service. campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201609') + 'CampaignCriterionService', version='v201802') # Create locations. The IDs can be found in the documentation or retrieved # with the LocationCriterionService. @@ -63,25 +63,6 @@ def main(client, campaign_id, location_feed_id=None): 'id': '1003' } - # Create location groups. The IDs can be found in the documentation or - # retrieved with the LocationCriterionService. - florida_tier3 = { - 'xsi_type': 'LocationGroups', - 'matchingFunction': { - 'operator': 'AND', - 'lhsOperand': [{ - 'xsi_type': 'IncomeOperand', - # Tiers are numbered 1-10, and represent 10% segments of earners. - # For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc. - # Tiers 6 through 10 are grouped into TIER_6_TO_10. - 'tier': 'TIER_3' - }], - 'rhsOperand': [{ - 'xsi_type': 'GeoTargetOperand', - 'locations': [1015116] # Miami, FL - }] - }, - } # Create a negative campaign criterion operation. negative_campaign_criterion_operand = { 'xsi_type': 'NegativeCampaignCriterion', @@ -92,7 +73,7 @@ def main(client, campaign_id, location_feed_id=None): 'text': 'jupiter cruise' } } - criteria = [california, mexico, english, spanish, florida_tier3] + criteria = [california, mexico, english, spanish] if location_feed_id: # Distance targeting. Area of 10 miles around targets above. criteria.append({ diff --git a/examples/adwords/v201802/targeting/add_customer_negative_criteria.py b/examples/adwords/v201802/targeting/add_customer_negative_criteria.py new file mode 100755 index 00000000..772ebeb1 --- /dev/null +++ b/examples/adwords/v201802/targeting/add_customer_negative_criteria.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds various types of negative criteria to a customer. + +These criteria will be applied to all campaigns for the customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_negative_criterion_service = client.GetService( + 'CustomerNegativeCriterionService', version='v201802') + + criteria = [ + # Exclude tragedy & conflict content. + { + 'xsi_type': 'ContentLabel', + 'contentLabelType': 'TRAGEDY' + }, + # Exclude a specific placement. + { + 'xsi_type': 'Placement', + 'url': 'http://www.example.com' + } + # Additional criteria types are available for this service. See the types + # listed under Criterion here: + # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion + ] + + # Create operations to add each of the criteria above. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'criterion': criterion + } + } for criterion in criteria] + + # Make the mutate request. + result = customer_negative_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for negative_criterion in result['value']: + print ('Customer negative criterion with criterion ID "%s", and type "%s" ' + 'was added.' % (negative_criterion['criterion']['id'], + negative_criterion['criterion']['type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py similarity index 98% rename from examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py rename to examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py index 9d487088..c53b5d3b 100755 --- a/examples/adwords/v201702/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py @@ -37,7 +37,7 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201702') + 'AdGroupCriterionService', version='v201802') # Create the ad group criteria. ad_group_criteria = [ diff --git a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py similarity index 98% rename from examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py rename to examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py index 45aaf587..ec37619b 100755 --- a/examples/adwords/v201702/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201702') + 'CampaignCriterionService', version='v201802') # Construct selector and get all campaign targets. offset = 0 diff --git a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py similarity index 97% rename from examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py rename to examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py index 3bf3412d..a14ac2df 100755 --- a/examples/adwords/v201702/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. constant_data_service = client.GetService( - 'ConstantDataService', version='v201702') + 'ConstantDataService', version='v201802') # Get all languages. languages = constant_data_service.getLanguageCriterion() diff --git a/examples/adwords/v201702/targeting/lookup_location.py b/examples/adwords/v201802/targeting/lookup_location.py similarity index 98% rename from examples/adwords/v201702/targeting/lookup_location.py rename to examples/adwords/v201802/targeting/lookup_location.py index 683a3c2a..ad885dd4 100755 --- a/examples/adwords/v201702/targeting/lookup_location.py +++ b/examples/adwords/v201802/targeting/lookup_location.py @@ -34,7 +34,7 @@ def GetLocationString(location): def main(client): # Initialize appropriate service. location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201702') + 'LocationCriterionService', version='v201802') location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] diff --git a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py deleted file mode 100755 index 237453a9..00000000 --- a/examples/dfp/v201702/product_service/create_programmatic_products_for_non_sales_management.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product for non-sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - product_service = client.GetService('ProductService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') - - product = { - # Setting required Marketplace Information. - 'productMarketplaceInfo': { - 'additionalTerms': 'Remember to also discuss that thing.', - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for products. - 'name': ('Product #%d' % uuid.uuid4()), - 'productType': 'DFP', - 'rateType': 'CPM', - 'lineItemType': 'STANDARD', - 'priority': 8, - 'environment': 'BROWSER', - 'rate': { - 'currencyCode': 'USD', - 'microAmount': '6000000' - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'builtInTargeting': { - 'inventoryTargeting': { - 'adUnitTargeting': { - 'adUnitId': network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId'], - 'includeDescendents': 'true' - } - } - }, - } - - products = product_service.createProducts([product]) - - if products: - for product in products: - print ('A programmatic product for non-sales management with ID "%s"' - ' and name "%s" was created.' % (product['id'], product['name'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py deleted file mode 100755 index 3d9a1c1c..00000000 --- a/examples/dfp/v201702/product_service/publish_programmatic_products_to_marketplace.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example publishes a product to Marketplace. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the product to publish. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201702') - - # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - products_published = 0 - - # Get products by statement. - while True: - response = product_service.getProductsByStatement( - statement.ToStatement()) - if 'results' in response: - for product in response['results']: - print ('Product with id "%s" and name "%s" will be ' - 'published.' % (product['id'], - product['name'])) - - # Perform action. - result = product_service.performProductAction( - {'xsi_type': 'PublishProducts'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - products_published += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if products_published > 0: - print 'Number of programmatic products published: %s' % products_published - else: - print 'No products were published.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py deleted file mode 100755 index a93d2d7f..00000000 --- a/examples/dfp/v201705/product_service/create_programmatic_products_for_non_sales_management.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product for non-sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - product_service = client.GetService('ProductService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') - - product = { - # Setting required Marketplace Information. - 'productMarketplaceInfo': { - 'additionalTerms': 'Remember to also discuss that thing.', - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for products. - 'name': ('Product #%d' % uuid.uuid4()), - 'productType': 'DFP', - 'rateType': 'CPM', - 'lineItemType': 'STANDARD', - 'priority': 8, - 'environment': 'BROWSER', - 'rate': { - 'currencyCode': 'USD', - 'microAmount': '6000000' - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'builtInTargeting': { - 'inventoryTargeting': { - 'adUnitTargeting': { - 'adUnitId': network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId'], - 'includeDescendents': 'true' - } - } - }, - } - - products = product_service.createProducts([product]) - - if products: - for product in products: - print ('A programmatic product for non-sales management with ID "%s"' - ' and name "%s" was created.' % (product['id'], product['name'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py deleted file mode 100755 index 4ee33f05..00000000 --- a/examples/dfp/v201705/product_service/publish_programmatic_products_to_marketplace.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example publishes a product to Marketplace. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the product to publish. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201705') - - # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - products_published = 0 - - # Get products by statement. - while True: - response = product_service.getProductsByStatement( - statement.ToStatement()) - if 'results' in response: - for product in response['results']: - print ('Product with id "%s" and name "%s" will be ' - 'published.' % (product['id'], - product['name'])) - - # Perform action. - result = product_service.performProductAction( - {'xsi_type': 'PublishProducts'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - products_published += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if products_published > 0: - print 'Number of programmatic products published: %s' % products_published - else: - print 'No products were published.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py index 25819435..b27e5d58 100755 --- a/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( 'ActivityGroupService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select activity groups. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/dfp/v201708/activity_group_service/update_activity_groups.py b/examples/dfp/v201708/activity_group_service/update_activity_groups.py index b7b26734..7d8fd136 100755 --- a/examples/dfp/v201708/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201708/activity_group_service/update_activity_groups.py @@ -40,17 +40,10 @@ def main(client, activity_group_id, advertiser_company_id): version='v201708') # Create statement object to select a single activity groups by ID. - values = [{ - 'key': 'activityGroupId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_group_id - } - }] - query = 'WHERE id = :activityGroupId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityGroupId') + .WithBindVariable('activityGroupId', long(activity_group_id)) + .Limit(1)) # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( @@ -70,6 +63,7 @@ def main(client, activity_group_id, advertiser_company_id): else: print 'No activity groups found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/activity_service/get_active_activities.py b/examples/dfp/v201708/activity_service/get_active_activities.py index fb1479c8..94d18be9 100755 --- a/examples/dfp/v201708/activity_service/get_active_activities.py +++ b/examples/dfp/v201708/activity_service/get_active_activities.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. activity_service = client.GetService('ActivityService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select activities. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/dfp/v201708/activity_service/update_activities.py b/examples/dfp/v201708/activity_service/update_activities.py index 9fab0a5f..851a411e 100755 --- a/examples/dfp/v201708/activity_service/update_activities.py +++ b/examples/dfp/v201708/activity_service/update_activities.py @@ -38,15 +38,10 @@ def main(client, activity_id): activity_service = client.GetService('ActivityService', version='v201708') # Create statement object to select one activity by ID to update. - values = [{ - 'key': 'activityId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_id - } - }] - query = 'WHERE id = :activityId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityId') + .WithBindVariable('activityId', long(activity_id)) + .Limit(1)) # Get activities by statement. response = activity_service.getActivitiesByStatement( @@ -66,6 +61,7 @@ def main(client, activity_id): else: print 'No activities found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py index 12e3fc76..a7bf8ee2 100755 --- a/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - }}, - ] # Create a statement to select audience segments. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'FIRST_PARTY')) # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py index affc42f5..1f74c70a 100755 --- a/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py @@ -33,21 +33,12 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201708') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201708/audience_segment_service/update_audience_segments.py b/examples/dfp/v201708/audience_segment_service/update_audience_segments.py index 4e697e4e..34270902 100755 --- a/examples/dfp/v201708/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201708/audience_segment_service/update_audience_segments.py @@ -32,21 +32,12 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201708') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) # Get audience segments by statement. response = audience_segment_service.getAudienceSegmentsByStatement( diff --git a/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py index 944b1f69..f4528e2a 100755 --- a/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py @@ -25,16 +25,10 @@ def main(client, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService('BaseRateService', version='v201708') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] # Create a statement to select base rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/dfp/v201708/base_rate_service/update_base_rates.py b/examples/dfp/v201708/base_rate_service/update_base_rates.py index cca97a1f..1d88d78f 100755 --- a/examples/dfp/v201708/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201708/base_rate_service/update_base_rates.py @@ -32,15 +32,11 @@ def main(client, base_rate_id): base_rate_service = client.GetService('BaseRateService', version='v201708') # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': base_rate_id - } - }] - query = 'where id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', long(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( diff --git a/examples/dfp/v201708/company_service/get_advertisers.py b/examples/dfp/v201708/company_service/get_advertisers.py index 4f32da18..03ea7369 100755 --- a/examples/dfp/v201708/company_service/get_advertisers.py +++ b/examples/dfp/v201708/company_service/get_advertisers.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. company_service = client.GetService('CompanyService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - }}, - ] # Create a statement to select companies. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'ADVERTISER')) # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/dfp/v201708/company_service/update_companies.py b/examples/dfp/v201708/company_service/update_companies.py index d4678799..ac9399ff 100755 --- a/examples/dfp/v201708/company_service/update_companies.py +++ b/examples/dfp/v201708/company_service/update_companies.py @@ -38,15 +38,10 @@ def main(client, company_id): company_service = client.GetService('CompanyService', version='v201708') # Create statement object to only select a single company by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': company_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(company_id)) + .Limit(1)) # Get companies by statement. response = company_service.getCompaniesByStatement( @@ -63,11 +58,12 @@ def main(client, company_id): # Display results. for company in companies: print (('Company with ID "%s", name "%s", and comment "%s"' - 'was updated.') + ' was updated.') % (company['id'], company['name'], company['comment'])) else: print 'No companies found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/contact_service/get_uninvited_contacts.py b/examples/dfp/v201708/contact_service/get_uninvited_contacts.py index 730aaa96..e67bd402 100755 --- a/examples/dfp/v201708/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201708/contact_service/get_uninvited_contacts.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. contact_service = client.GetService('ContactService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - }}, - ] # Create a statement to select contacts. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'UNINVITED')) # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/dfp/v201708/contact_service/update_contacts.py b/examples/dfp/v201708/contact_service/update_contacts.py index b98d25f1..1a14eb95 100755 --- a/examples/dfp/v201708/contact_service/update_contacts.py +++ b/examples/dfp/v201708/contact_service/update_contacts.py @@ -38,15 +38,10 @@ def main(client, contact_id): contact_service = client.GetService('ContactService', version='v201708') # Create statement object to select the single contact by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': contact_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(contact_id)) + .Limit(1)) # Get contacts by statement. response = contact_service.getContactsByStatement( @@ -69,6 +64,7 @@ def main(client, contact_id): else: print 'No contacts found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 95899906..54e36cb6 100755 --- a/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -43,16 +43,12 @@ def main(client, content_metadata_key_hierarchy_id): 'ContentMetadataKeyHierarchyService', version='v201708') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -78,6 +74,7 @@ def main(client, content_metadata_key_hierarchy_id): print ('Number of content metadata key hierarchies deleted: %s' % result['numChanges']) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index e276a2d6..253fbd5a 100755 --- a/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -45,16 +45,12 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): 'ContentMetadataKeyHierarchyService', version='v201708') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -90,6 +86,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): else: print 'No content metadata key hierarchies were found' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/creative_service/create_native_creative.py b/examples/dfp/v201708/creative_service/create_native_creative.py index c92e4926..22566070 100755 --- a/examples/dfp/v201708/creative_service/create_native_creative.py +++ b/examples/dfp/v201708/creative_service/create_native_creative.py @@ -52,10 +52,12 @@ def main(client, advertiser_id): creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - image_data = base64.b64encode(image_data) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = base64.b64encode(image_data).decode('utf-8') app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - app_icon_data = base64.b64encode(app_icon_data) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + app_icon_data = base64.b64encode(app_icon_data).decode('utf-8') # Create creative from templates. creative = { diff --git a/examples/dfp/v201708/creative_service/get_image_creatives.py b/examples/dfp/v201708/creative_service/get_image_creatives.py index a90f06bf..4d2a923a 100755 --- a/examples/dfp/v201708/creative_service/get_image_creatives.py +++ b/examples/dfp/v201708/creative_service/get_image_creatives.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. creative_service = client.GetService('CreativeService', version='v201708') - query = 'WHERE creativeType = :creativeType' - values = [ - {'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': '_image_creative' - }}, - ] # Create a statement to select creatives. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('creativeType = :creativeType') + .WithBindVariable('creativeType', 'ImageCreative')) # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/dfp/v201708/creative_service/update_creatives.py b/examples/dfp/v201708/creative_service/update_creatives.py index 15b95828..c58e300a 100755 --- a/examples/dfp/v201708/creative_service/update_creatives.py +++ b/examples/dfp/v201708/creative_service/update_creatives.py @@ -37,21 +37,11 @@ def main(client, image_creative_id): creative_service = client.GetService('CreativeService', version='v201708') # Create statement object to get all image creatives. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }, { - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': image_creative_id - } - }] - query = 'WHERE creativeType = :type AND id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('creativeType = :type AND id = :id') + .WithBindVariable('type', 'ImageCreative') + .WithBindVariable('id', long(image_creative_id)) + .Limit(1)) # Get creatives by statement. response = creative_service.getCreativesByStatement( @@ -74,6 +64,7 @@ def main(client, image_creative_id): else: print 'No creatives found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py index 5b313769..39b53de7 100755 --- a/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py @@ -26,16 +26,10 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( 'CreativeSetService', version='v201708') - query = 'WHERE masterCreativeId = :masterCreativeId' - values = [ - {'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'TextValue', - 'value': master_creative_id - }}, - ] # Create a statement to select creative sets. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('masterCreativeId = :masterCreativeId') + .WithBindVariable('masterCreativeId', master_creative_id)) # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/dfp/v201708/creative_set_service/update_creative_set.py b/examples/dfp/v201708/creative_set_service/update_creative_set.py index 8c2edd8c..6ba670e7 100755 --- a/examples/dfp/v201708/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201708/creative_set_service/update_creative_set.py @@ -40,15 +40,9 @@ def main(client, creative_set_id, companion_creative_id): version='v201708') # Create statement to select a single creative set by ID. - values = [{ - 'key': 'creativeSetId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_set_id - } - }] - query = 'WHERE id = :creativeSetId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeSetId') + .WithBindVariable('creativeSetId', long(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -72,6 +66,7 @@ def main(client, creative_set_id, companion_creative_id): else: print 'No creative sets found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py index 6148b764..b9855e66 100755 --- a/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( 'CreativeTemplateService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - }}, - ] # Create a statement to select creative templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'SYSTEM_DEFINED')) # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py index 47490b87..f19a7775 100755 --- a/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py @@ -36,21 +36,10 @@ def main(client, label_id): version='v201708') # Create a query to select the active creative wrappers for the given label. - values = [{ - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status AND labelId = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status AND labelId = :labelId') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('labelId', long(label_id))) creative_wrappers_deactivated = 0 @@ -82,6 +71,7 @@ def main(client, label_id): else: print 'No creative wrappers were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py index a2cc780e..7a583480 100755 --- a/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( 'CreativeWrapperService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select creative wrappers. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py index f387dea1..5243704d 100755 --- a/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py @@ -39,15 +39,10 @@ def main(client, creative_wrapper_id): version='v201708') # Create statement to get a creative wrapper by ID. - values = [{ - 'key': 'creativeWrapperId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_wrapper_id - } - }] - query = 'WHERE id = :creativeWrapperId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeWrapperId') + .WithBindVariable('creativeWrapperId', + long(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -71,6 +66,7 @@ def main(client, creative_wrapper_id): else: print 'No creative wrappers found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py index acb693c7..04ebc205 100755 --- a/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -37,23 +37,10 @@ def main(client): # Create statement to select only active custom fields that apply to # line items. - values = [ - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }, { - 'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - } - ] - query = 'WHERE entityType = :entityType and isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType and isActive = :isActive') + .WithBindVariable('entityType', 'LINE_ITEM') + .WithBindVariable('isActive', True)) custom_fields_deactivated = 0 @@ -79,6 +66,7 @@ def main(client): else: print 'No custom fields were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py index f02cf122..b28d3963 100755 --- a/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( 'CustomFieldService', version='v201708') - query = 'WHERE entityType = :entityType' - values = [ - {'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - }}, - ] # Create a statement to select custom fields. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType') + .WithBindVariable('entityType', 'LINE_ITEM')) # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/dfp/v201708/custom_field_service/update_custom_fields.py b/examples/dfp/v201708/custom_field_service/update_custom_fields.py index 72d95b25..36c95bc5 100755 --- a/examples/dfp/v201708/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201708/custom_field_service/update_custom_fields.py @@ -39,15 +39,9 @@ def main(client, custom_field_id): 'CustomFieldService', version='v201708') # Create statement to get a custom field. - values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - query = 'WHERE id = :customFieldId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', long(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -69,6 +63,7 @@ def main(client, custom_field_id): else: print 'No custom fields found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py index 469439f3..3ed109af 100755 --- a/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py @@ -38,15 +38,9 @@ def main(client, key_name): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201708') - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': key_name - } - }] - query = 'WHERE name = :name' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('name = :name') + .WithBindVariable('name', key_name)) deleted_custom_targeting_keys = 0 @@ -76,6 +70,7 @@ def main(client, key_name): else: print 'No custom targeting keys were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 092568ea..c4b77aa8 100755 --- a/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -26,15 +26,9 @@ def main(client): 'CustomTargetingService', version='v201708') # Create statement to get targeting keys for predefined values. - query = ('WHERE type = :type') - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] - targeting_key_statement = dfp.FilterStatement(query, values) + targeting_key_statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'PREDEFINED')) all_keys = [] @@ -44,15 +38,15 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (:ids)') + .WithBindVariable('ids', [key['id'] for key in all_keys])) # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. @@ -67,7 +61,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py index e8716202..39ef1be7 100755 --- a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py @@ -32,15 +32,10 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201708') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE id = :keyId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :keyId') + .WithBindVariable('keyId', long(key_id)) + .Limit(1)) # Get custom targeting keys by statement. response = custom_targeting_service.getCustomTargetingKeysByStatement( @@ -65,6 +60,7 @@ def main(client, key_id): else: print 'No custom targeting keys were found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py index 63e365e5..f0c8d675 100755 --- a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py @@ -32,15 +32,9 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201708') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', long(key_id))) while True: # Get custom targeting values by statement. @@ -70,6 +64,7 @@ def main(client, key_id): if response['totalResultSetSize'] == 0: print 'No custom targeting values were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py index bf5f03b6..e8174907 100755 --- a/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -26,16 +26,10 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( 'ExchangeRateService', version='v201708') - query = 'WHERE currencyCode = :currencyCode' - values = [ - {'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - }}, - ] # Create a statement to select exchange rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('currencyCode = :currencyCode') + .WithBindVariable('currencyCode', currency_code)) # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py index 62331fae..ad85b0b3 100755 --- a/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py @@ -33,16 +33,10 @@ def main(client, exchange_rate_id): version='v201708') # Create a statement to get an exchange rate by its ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': exchange_rate_id - } - }] - query = 'WHERE id = :id' - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(exchange_rate_id)) + .Limit(1)) # Get rate cards by statement. response = exchange_rate_service.getExchangeRatesByStatement( diff --git a/examples/dfp/v201708/forecast_service/get_availability_forecast.py b/examples/dfp/v201708/forecast_service/get_availability_forecast.py index f502aade..99583ae3 100755 --- a/examples/dfp/v201708/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201708/forecast_service/get_availability_forecast.py @@ -105,11 +105,14 @@ def main(client, advertiser_id): forecast = forecast_service.getAvailabilityForecast( prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -117,9 +120,10 @@ def main(client, advertiser_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py index ba38ebc0..ac71f295 100755 --- a/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py @@ -42,11 +42,14 @@ def main(client, line_item_id): forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -54,9 +57,10 @@ def main(client, line_item_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/inventory_service/archive_ad_units.py b/examples/dfp/v201708/inventory_service/archive_ad_units.py index b64b0a36..6ea176a3 100755 --- a/examples/dfp/v201708/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201708/inventory_service/archive_ad_units.py @@ -39,15 +39,9 @@ def main(client, parent_id): # Create a query to select ad units under the parent ad unit and the parent ad # unit. - values = [{ - 'key': 'parentId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': parent_id - } - }] - query = 'WHERE parentId = :parentId or id = :parentId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId or id = :parentId') + .WithBindVariable('parentId', long(parent_id))) ad_units_archived = 0 @@ -74,6 +68,7 @@ def main(client, parent_id): else: print 'No ad units were archived.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/inventory_service/update_ad_units.py b/examples/dfp/v201708/inventory_service/update_ad_units.py index 7dec87a9..fa5c54f3 100755 --- a/examples/dfp/v201708/inventory_service/update_ad_units.py +++ b/examples/dfp/v201708/inventory_service/update_ad_units.py @@ -39,15 +39,9 @@ def main(client, ad_unit_id): inventory_service = client.GetService('InventoryService', version='v201708') # Create a statement to select a single ad unit by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': ad_unit_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', ad_unit_id)) # Get ad units by statement. response = inventory_service.getAdUnitsByStatement( @@ -81,6 +75,7 @@ def main(client, ad_unit_id): print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/label_service/deactivate_labels.py b/examples/dfp/v201708/label_service/deactivate_labels.py index 2af49168..9cc3f342 100755 --- a/examples/dfp/v201708/label_service/deactivate_labels.py +++ b/examples/dfp/v201708/label_service/deactivate_labels.py @@ -30,15 +30,9 @@ def main(client): label_service = client.GetService('LabelService', version='v201708') # Create query. - values = [{ - 'key': 'isActive', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'true' - } - }] - query = 'WHERE isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) labels_deactivated = 0 @@ -64,6 +58,7 @@ def main(client): else: print 'No labels were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/label_service/get_active_labels.py b/examples/dfp/v201708/label_service/get_active_labels.py index 415672a7..7ee62101 100755 --- a/examples/dfp/v201708/label_service/get_active_labels.py +++ b/examples/dfp/v201708/label_service/get_active_labels.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201708') - query = 'WHERE isActive = :isActive' - values = [ - {'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] # Create a statement to select labels. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/dfp/v201708/label_service/update_labels.py b/examples/dfp/v201708/label_service/update_labels.py index bccf95a7..a9d859f1 100755 --- a/examples/dfp/v201708/label_service/update_labels.py +++ b/examples/dfp/v201708/label_service/update_labels.py @@ -32,17 +32,9 @@ def main(client, label_id): label_service = client.GetService('LabelService', version='v201708') # Create a statement to select only active labels. - values = [ - { - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - } - ] - query = 'WHERE id = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :labelId') + .WithBindVariable('labelId', long(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -63,6 +55,7 @@ def main(client, label_id): else: print 'No labels found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py index 0b13f4bf..8885ecc0 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py @@ -33,21 +33,10 @@ def main(client, line_item_id): 'LineItemCreativeAssociationService', version='v201708') # Create query. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE lineItemId = :lineItemId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId AND status = :status') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('lineItemId', long(line_item_id))) num_deactivated_licas = 0 @@ -77,6 +66,7 @@ def main(client, line_item_id): else: print 'No LICAs were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py index 15eb13a8..3200cb4a 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py @@ -26,16 +26,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( 'LineItemCreativeAssociationService', version='v201708') - query = 'WHERE lineItemId = :lineItemId' - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'TextValue', - 'value': line_item_id - }}, - ] # Create a statement to select line item creative associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId') + .WithBindVariable('lineItemId', line_item_id)) # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/dfp/v201708/line_item_service/activate_line_items.py b/examples/dfp/v201708/line_item_service/activate_line_items.py index 0cc56b63..0df9b340 100755 --- a/examples/dfp/v201708/line_item_service/activate_line_items.py +++ b/examples/dfp/v201708/line_item_service/activate_line_items.py @@ -36,21 +36,10 @@ def main(client, order_id): line_item_service = client.GetService('LineItemService', version='v201708') # Create query. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' - } - }] - query = 'WHERE orderId = :orderId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId AND status = :status') + .WithBindVariable('status', 'NEEDS_CREATIVES') + .WithBindVariable('orderId', long(order_id))) line_items_activated = 0 @@ -79,6 +68,7 @@ def main(client, order_id): else: print 'No line items were activated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py index 1a6e2835..ab1cd2f4 100755 --- a/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. line_item_service = client.GetService('LineItemService', version='v201708') - query = 'WHERE isMissingCreatives = :isMissingCreatives' - values = [ - {'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isMissingCreatives = :isMissingCreatives') + .WithBindVariable('isMissingCreatives', True)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py index 39b0e992..6970ebdb 100755 --- a/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py @@ -21,22 +21,20 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. line_item_service = client.GetService('LineItemService', version='v201708') - query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' - values = [ - {'key': 'lastModifiedDateTime', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() - timedelta(days=1)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201708/line_item_service/target_custom_criteria.py b/examples/dfp/v201708/line_item_service/target_custom_criteria.py index a55368b6..c1e1c746 100755 --- a/examples/dfp/v201708/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201708/line_item_service/target_custom_criteria.py @@ -81,15 +81,10 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - query = 'WHERE id = :lineItemId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', long(line_item_id)) + .Limit(1)) # Set custom criteria targeting on the line item. line_item = line_item_service.getLineItemsByStatement( @@ -107,6 +102,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, else: print 'No line items were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/line_item_service/update_line_items.py b/examples/dfp/v201708/line_item_service/update_line_items.py index 8990c58f..fa7abe6c 100755 --- a/examples/dfp/v201708/line_item_service/update_line_items.py +++ b/examples/dfp/v201708/line_item_service/update_line_items.py @@ -32,22 +32,13 @@ def main(client, order_id): line_item_service = client.GetService('LineItemService', version='v201708') # Create statement object to only select line items with even delivery rates. - values = [{ - 'key': 'deliveryRateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'EVENLY' - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId' - statement = dfp.FilterStatement(query, values, 500) + statement = (dfp.StatementBuilder() + .Where(('deliveryRateType = :deliveryRateType AND ' + 'orderId = :orderId')) + .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('deliveryRateType', 'EVENLY') + .Limit(500)) # Get line items by statement. response = line_item_service.getLineItemsByStatement( @@ -76,6 +67,7 @@ def main(client, order_id): else: print 'No line items found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/order_service/approve_orders.py b/examples/dfp/v201708/order_service/approve_orders.py index 4b47b3bd..cc7c4ca4 100755 --- a/examples/dfp/v201708/order_service/approve_orders.py +++ b/examples/dfp/v201708/order_service/approve_orders.py @@ -30,19 +30,12 @@ def main(client): # Initialize appropriate service. order_service = client.GetService('OrderService', version='v201708') - # Create query. - values = [{ - 'key': 'today', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S') - } - }] - query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')' - ' AND endDateTime >= :today AND isArchived = FALSE') - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + today = datetime.date.today() + statement = (dfp.StatementBuilder() + .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' + 'AND endDateTime >= :today AND isArchived = FALSE')) + .WithBindVariable('today', today)) orders_approved = 0 # Get orders by statement. diff --git a/examples/dfp/v201708/order_service/get_orders_starting_soon.py b/examples/dfp/v201708/order_service/get_orders_starting_soon.py index 60d0f60a..367de8fa 100755 --- a/examples/dfp/v201708/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201708/order_service/get_orders_starting_soon.py @@ -21,33 +21,22 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. order_service = client.GetService('OrderService', version='v201708') - query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' - '<= :soon') - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'APPROVED' - }}, - {'key': 'now', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') - }}, - {'key': 'soon', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() + timedelta(days=5)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + now = datetime.now(tz=pytz.timezone('America/New_York')) + soon = now + timedelta(days=5) + # Create a statement to select orders. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('status = :status AND startDateTime >= :now ' + 'AND startDateTime <= :soon')) + .WithBindVariable('status', 'APPROVED') + .WithBindVariable('now', now) + .WithBindVariable('soon', soon)) # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/dfp/v201708/order_service/update_orders.py b/examples/dfp/v201708/order_service/update_orders.py index a7930f84..66bdbe8d 100755 --- a/examples/dfp/v201708/order_service/update_orders.py +++ b/examples/dfp/v201708/order_service/update_orders.py @@ -31,16 +31,10 @@ def main(client, order_id): order_service = client.GetService('OrderService', version='v201708') # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :orderId') + .WithBindVariable('orderId', long(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -69,6 +63,7 @@ def main(client, order_id): else: print 'No orders found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/package_service/get_in_progress_packages.py b/examples/dfp/v201708/package_service/get_in_progress_packages.py index 0498d893..b84a4599 100755 --- a/examples/dfp/v201708/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201708/package_service/get_in_progress_packages.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. pkg_service = client.GetService('PackageService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'IN_PROGRESS' - }}, - ] # Create a statement to select packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'IN_PROGRESS')) # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/dfp/v201708/placement_service/deactivate_placements.py b/examples/dfp/v201708/placement_service/deactivate_placements.py index ab6bc811..01d3f564 100755 --- a/examples/dfp/v201708/placement_service/deactivate_placements.py +++ b/examples/dfp/v201708/placement_service/deactivate_placements.py @@ -31,15 +31,10 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201708') # Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :placementId') + .WithBindVariable('placementId', long(placement_id)) + .Limit(1)) # Get placements by statement. placements = placement_service.getPlacementsByStatement( @@ -60,6 +55,7 @@ def main(client, placement_id): else: print 'No placements were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/placement_service/get_active_placements.py b/examples/dfp/v201708/placement_service/get_active_placements.py index 7a4149b5..bcf3b097 100755 --- a/examples/dfp/v201708/placement_service/get_active_placements.py +++ b/examples/dfp/v201708/placement_service/get_active_placements.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. placement_service = client.GetService('PlacementService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select placements. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py index b0b0d3cb..8baf7e7c 100755 --- a/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py @@ -26,16 +26,10 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( 'PremiumRateService', version='v201708') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] # Create a statement to select premium rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/dfp/v201708/premium_rate_service/update_premium_rates.py b/examples/dfp/v201708/premium_rate_service/update_premium_rates.py index 054c0d99..bce51970 100755 --- a/examples/dfp/v201708/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201708/premium_rate_service/update_premium_rates.py @@ -33,15 +33,11 @@ def main(client, premium_rate_id): version='v201708') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': premium_rate_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(premium_rate_id)) + .Limit(1)) # Get the premium rate. response = premium_rate_service.getPremiumRatesByStatement( diff --git a/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py index 9f66019d..9b28e75e 100755 --- a/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py @@ -26,16 +26,10 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( 'ProductPackageItemService', version='v201708') - query = 'WHERE productPackageId = :productPackageId' - values = [ - {'key': 'productPackageId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_package_id - }}, - ] # Create a statement to select product package items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productPackageId = :productPackageId') + .WithBindVariable('productPackageId', product_package_id)) # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/dfp/v201708/product_package_service/get_active_product_packages.py b/examples/dfp/v201708/product_package_service/get_active_product_packages.py index cb56d6e0..7fec7d3c 100755 --- a/examples/dfp/v201708/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201708/product_package_service/get_active_product_packages.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( 'ProductPackageService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] # Create a statement to select product packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py b/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py deleted file mode 100755 index fdf43b91..00000000 --- a/examples/dfp/v201708/product_service/create_programmatic_products_for_non_sales_management.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product for non-sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import dfp - - -def main(client): - product_service = client.GetService('ProductService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') - - product = { - # Setting required Marketplace Information. - 'productMarketplaceInfo': { - 'additionalTerms': 'Remember to also discuss that thing.', - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for products. - 'name': ('Product #%d' % uuid.uuid4()), - 'productType': 'DFP', - 'rateType': 'CPM', - 'lineItemType': 'STANDARD', - 'priority': 8, - 'environment': 'BROWSER', - 'rate': { - 'currencyCode': 'USD', - 'microAmount': '6000000' - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'builtInTargeting': { - 'inventoryTargeting': { - 'adUnitTargeting': { - 'adUnitId': network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId'], - 'includeDescendents': 'true' - } - } - }, - } - - products = product_service.createProducts([product]) - - if products: - for product in products: - print ('A programmatic product for non-sales management with ID "%s"' - ' and name "%s" was created.' % (product['id'], product['name'])) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) diff --git a/examples/dfp/v201708/product_service/get_products_for_product_template.py b/examples/dfp/v201708/product_service/get_products_for_product_template.py index a5fe62ea..bdf48f18 100755 --- a/examples/dfp/v201708/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201708/product_service/get_products_for_product_template.py @@ -26,16 +26,10 @@ def main(client, product_template_id): # Initialize appropriate service. product_service = client.GetService('ProductService', version='v201708') - query = 'WHERE productTemplateId = :productTemplateId' - values = [ - {'key': 'productTemplateId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_template_id - }}, - ] # Create a statement to select products. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productTemplateId = :productTemplateId') + .WithBindVariable('productTemplateId', product_template_id)) # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py b/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py deleted file mode 100755 index f8ee622d..00000000 --- a/examples/dfp/v201708/product_service/publish_programmatic_products_to_marketplace.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example publishes a product to Marketplace. -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the id of the product to publish. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201708') - - # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) - - products_published = 0 - - # Get products by statement. - while True: - response = product_service.getProductsByStatement( - statement.ToStatement()) - if 'results' in response: - for product in response['results']: - print ('Product with id "%s" and name "%s" will be ' - 'published.' % (product['id'], - product['name'])) - - # Perform action. - result = product_service.performProductAction( - {'xsi_type': 'PublishProducts'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - products_published += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if products_published > 0: - print 'Number of programmatic products published: %s' % products_published - else: - print 'No products were published.' - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) diff --git a/examples/dfp/v201708/product_service/update_products.py b/examples/dfp/v201708/product_service/update_products.py index 91cb2076..581c144b 100755 --- a/examples/dfp/v201708/product_service/update_products.py +++ b/examples/dfp/v201708/product_service/update_products.py @@ -32,15 +32,10 @@ def main(client, product_id): product_service = client.GetService('ProductService', version='v201708') # Create statement object to select a single product by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, product_id): else: print 'No products found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/product_template_service/activate_product_templates.py b/examples/dfp/v201708/product_template_service/activate_product_templates.py index 09cb0c7f..062ab9b8 100755 --- a/examples/dfp/v201708/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201708/product_template_service/activate_product_templates.py @@ -34,15 +34,10 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201708') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) product_templates_activated = 0 diff --git a/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py index eecc85f7..8678245e 100755 --- a/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( 'ProductTemplateService', version='v201708') - query = 'WHERE lineItemType = :lineItemType' - values = [ - {'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - }}, - ] # Create a statement to select product templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemType = :lineItemType') + .WithBindVariable('lineItemType', 'SPONSORSHIP')) # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/dfp/v201708/product_template_service/update_product_templates.py b/examples/dfp/v201708/product_template_service/update_product_templates.py index f0b8420a..6824719d 100755 --- a/examples/dfp/v201708/product_template_service/update_product_templates.py +++ b/examples/dfp/v201708/product_template_service/update_product_templates.py @@ -33,15 +33,11 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201708') # Create a statement to select a single product template by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) # Get product templates by statement. response = product_template_service.getProductTemplatesByStatement( diff --git a/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py index 9da431e6..4d460956 100755 --- a/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py @@ -34,15 +34,10 @@ def main(client, proposal_line_item_id): 'ProposalLineItemService', version='v201708') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) proposal_line_items_archived = 0 diff --git a/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 31a210bc..5bd3138d 100755 --- a/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -26,16 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( 'ProposalLineItemService', version='v201708') - query = 'WHERE proposalId = :proposalId' - values = [ - {'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - }}, - ] # Create a statement to select proposal line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('proposalId = :proposalId') + .WithBindVariable('proposalId', proposal_id)) # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py index 7e905ac2..ffda2e86 100755 --- a/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py @@ -34,16 +34,11 @@ def main(client, proposal_line_item_id): 'ProposalLineItemService', version='v201708') # Create statement to select a proposal line item. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) # Get proposal line items by statement. response = proposal_line_item_service.getProposalLineItemsByStatement( diff --git a/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py index 9ee049f0..fb7354a9 100755 --- a/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py @@ -23,16 +23,10 @@ def main(client): # Initialize appropriate service. proposal_service = client.GetService('ProposalService', version='v201708') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - }}, - ] # Create a statement to select proposals. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'PENDING_APPROVAL')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py index 2d7a14ac..b8c8690b 100755 --- a/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py @@ -29,17 +29,9 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201708') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo programmatic proposals were pushed to Marketplace.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py index c76ccfad..a426566f 100755 --- a/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py @@ -31,17 +31,9 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201708') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo proposals were approved.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/proposal_service/update_proposals.py b/examples/dfp/v201708/proposal_service/update_proposals.py index f4083ba9..29f4bc91 100755 --- a/examples/dfp/v201708/proposal_service/update_proposals.py +++ b/examples/dfp/v201708/proposal_service/update_proposals.py @@ -31,16 +31,11 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201708') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', long(proposal_id)) + .Limit(1)) # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, proposal_id): else: print 'No proposals found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py index d1b35a8a..e696588b 100755 --- a/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py +++ b/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py @@ -33,50 +33,21 @@ def main(client): # Initialize appropriate service. pql_service = client.GetService('PublisherQueryLanguageService', 'v201708') - end_date = date.today() + end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) - initial_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE ChangeDateTime > :startDateTime ' - 'AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - pagination_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE Id < :id ' - 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - values = [ - { - 'key': 'startDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day - } - } - } - }, - { - 'key': 'endDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day - } - } - } - } - ] - - statement = dfp.FilterStatement(initial_query, values) + initial_query = ('ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime') + pagination_query = 'Id < :id AND ' + initial_query + + statement = (dfp.StatementBuilder() + .Select(('Id, ChangeDateTime, EntityId, EntityType, ' + 'Operation, UserId')) + .From('Change_History') + .Where(initial_query) + .OrderBy('ChangeDateTime', ascending=False) + .WithBindVariable('startDateTime', start_date) + .WithBindVariable('endDateTime', end_date)) + keep_iterating = True i = 0 total_rows = [] @@ -94,8 +65,11 @@ def main(client): last_row = rows[-1] last_id = last_row['values'][0]['value'] i += 1 - statement = UpdateFilterStatement( - statement, pagination_query, values, last_id) + + # Update the statement using the earliest row in the previous result. + statement.Where(pagination_query) + statement.WithBindVariable('id', last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' % (i, rows_length, last_id)) @@ -109,34 +83,6 @@ def main(client): print ConvertValueForCsv(row) -def UpdateFilterStatement(statement, query, values, last_id): - """Updates the FilterStatement in order to page through results. - - Args: - statement: an instantiated FilterStatement. - query: a str query that will be used to update the FilterStatement. - values: a list of bind variables to be updated. - last_id: a str representing the earliest change ID in a result set. - - Returns: - FilterStatement the updated statement. - """ - # Use the earliest change ID in the result set to page. - updated_values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_id - } - }] - updated_values.extend(values) - - statement.where_clause = query - statement.values = updated_values - - return statement - - def ConvertValueForCsv(pql_value): """Sanitizes a field value from a Value object to a CSV suitable format. diff --git a/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py index 3d328885..e6c21125 100755 --- a/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py @@ -24,16 +24,10 @@ def main(client): # Initialize appropriate service. rate_card_service = client.GetService('RateCardService', version='v201708') - query = 'WHERE forMarketplace = :forMarketplace' - values = [ - {'key': 'forMarketplace', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] # Create a statement to select rate cards. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('forMarketplace = :forMarketplace') + .WithBindVariable('forMarketplace', True)) # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 6e07ba1e..c0a53e7a 100755 --- a/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -26,16 +26,11 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( 'ReconciliationOrderReportService', version='v201708') - query = 'WHERE reconciliationReportId = :reconciliationReportId' - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - ] # Create a statement to select reconciliation order reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('reconciliationReportId = :reconciliationReportId') + .WithBindVariable('reconciliationReportId', + reconciliation_report_id)) # Retrieve a small amount of reconciliation order reports at a time, paging # through until all reconciliation order reports have been retrieved. diff --git a/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index d00d24c7..1e8943f7 100755 --- a/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -28,17 +28,13 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( 'ReconciliationReportRowService', version='v201708') - query = ('WHERE reconciliationReportId = %s AND ' - 'lineItemId != :lineItemId') % reconciliation_report_id - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - } - }] + # Create a statement to select reconciliation report rows. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reportId ' + 'AND lineItemId != :lineItemId')) + .WithBindVariable('lineItemId', 0) + .WithBindVariable('reportId', long(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. diff --git a/examples/dfp/v201708/report_service/run_delivery_report.py b/examples/dfp/v201708/report_service/run_delivery_report.py index cffd7138..cf6beb2e 100755 --- a/examples/dfp/v201708/report_service/run_delivery_report.py +++ b/examples/dfp/v201708/report_service/run_delivery_report.py @@ -32,15 +32,11 @@ def main(client, order_id): # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - filter_statement = {'query': 'WHERE ORDER_ID = :id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('ORDER_ID = :id') + .WithBindVariable('id', long(order_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Set the start and end dates of the report to run (past 8 days). end_date = datetime.now().date() @@ -52,7 +48,7 @@ def main(client, order_id): 'dimensions': ['ORDER_ID', 'ORDER_NAME'], 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', 'ORDER_END_DATE_TIME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], diff --git a/examples/dfp/v201708/report_service/run_inventory_report.py b/examples/dfp/v201708/report_service/run_inventory_report.py index 4cb31c49..b134c2d2 100755 --- a/examples/dfp/v201708/report_service/run_inventory_report.py +++ b/examples/dfp/v201708/report_service/run_inventory_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report equal to the "Whole network report" on the DFP website.""" +"""This example runs a typical daily inventory report.""" import tempfile @@ -34,15 +34,11 @@ def main(client): network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - values = [{ - 'key': 'parent_ad_unit_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': root_ad_unit_id - } - }] - filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') + .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Create report job. report_job = { @@ -55,7 +51,7 @@ def main(client): 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', - 'statement': filter_statement + 'statement': statement.ToStatement() } } diff --git a/examples/dfp/v201708/report_service/run_report_and_create_match_table.py b/examples/dfp/v201708/report_service/run_report_and_create_match_table.py new file mode 100755 index 00000000..572d2c3c --- /dev/null +++ b/examples/dfp/v201708/report_service/run_report_and_create_match_table.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Runs a report for LineItems with additional data from a PQL table. + +Fetches a basic report over a network's LineItems and then adds some +extra columns which might be useful for future analysis, such as +LineItemType, from the PQL Line_Item table, creating a match table. +""" + +from datetime import date +from datetime import timedelta +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + +try: + import pandas +except ImportError: + raise ImportError('This example requires the pandas library to be installed.') + + +def main(client): + # Set the start and end dates of the report to run (past 8 days). + end_date = date.today() + start_date = end_date - timedelta(days=8) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': start_date, + 'endDate': end_date + } + } + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201708') + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + with tempfile.NamedTemporaryFile( + suffix='.csv.gz', mode='wb', delete=False) as report_file: + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, 'CSV_DUMP', report_file) + + # Create a PQL query to fetch the line item data + line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem') + + # Download the response from PQL select statement + line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) + + # Use pandas to join the two csv files into a match table + report = pandas.read_csv(report_file.name) + line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0]) + merged_result = pandas.merge(report, line_items, + left_on='Dimension.LINE_ITEM_ID', right_on='id') + merged_result.to_csv('~/complete_line_items_report.csv', index=False) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/report_service/run_report_with_custom_fields.py b/examples/dfp/v201708/report_service/run_report_with_custom_fields.py index e482d20f..3cb787c7 100755 --- a/examples/dfp/v201708/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201708/report_service/run_report_with_custom_fields.py @@ -33,17 +33,9 @@ def main(client, order_id): report_downloader = client.GetDataDownloader(version='v201708') # Filter for line items of a given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE orderId = :orderId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId') + .WithBindVariable('orderId', long(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -62,14 +54,16 @@ def main(client, order_id): else: break - # Create statement object to filter for an order. - filter_statement = {'query': query, 'values': values} + # Modify statement for reports + statement.limit = None + statement.offset = None + statement.Where('ORDER_ID = :orderId') # Create report job. report_job = { 'reportQuery': { 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', 'customFieldIds': list(custom_field_ids) diff --git a/examples/dfp/v201708/report_service/run_saved_query.py b/examples/dfp/v201708/report_service/run_saved_query.py index 0529d694..9b03ffcb 100755 --- a/examples/dfp/v201708/report_service/run_saved_query.py +++ b/examples/dfp/v201708/report_service/run_saved_query.py @@ -34,15 +34,10 @@ def main(client, saved_query_id): report_downloader = client.GetDataDownloader(version='v201708') # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': saved_query_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(saved_query_id)) + .Limit(1)) response = report_service.getSavedQueriesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index fc262e7f..7c2655d0 100755 --- a/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -26,16 +26,10 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( 'SuggestedAdUnitService', version='v201708') - query = 'WHERE numRequests >= :numRequests' - values = [ - {'key': 'numRequests', - 'value': { - 'xsi_type': 'TextValue', - 'value': num_requests - }}, - ] # Create a statement to select suggested ad units. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests >= :numRequests') + .WithBindVariable('numRequests', long(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/dfp/v201708/team_service/update_teams.py b/examples/dfp/v201708/team_service/update_teams.py index ee9340cd..c292badc 100755 --- a/examples/dfp/v201708/team_service/update_teams.py +++ b/examples/dfp/v201708/team_service/update_teams.py @@ -37,15 +37,9 @@ def main(client, team_id): team_service = client.GetService('TeamService', version='v201708') # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :teamId') + .WithBindVariable('teamId', long(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -67,6 +61,7 @@ def main(client, team_id): else: print 'No teams found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/user_service/deactivate_users.py b/examples/dfp/v201708/user_service/deactivate_users.py index 41563678..8f9afa46 100755 --- a/examples/dfp/v201708/user_service/deactivate_users.py +++ b/examples/dfp/v201708/user_service/deactivate_users.py @@ -33,17 +33,9 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201708') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -66,6 +58,7 @@ def main(client, user_id): else: print 'No users were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/user_service/get_user_by_email_address.py b/examples/dfp/v201708/user_service/get_user_by_email_address.py index 364bdc60..24671e74 100755 --- a/examples/dfp/v201708/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201708/user_service/get_user_by_email_address.py @@ -25,16 +25,10 @@ def main(client, email_address): # Initialize appropriate service. user_service = client.GetService('UserService', version='v201708') - query = 'WHERE email = :email' - values = [ - {'key': 'email', - 'value': { - 'xsi_type': 'TextValue', - 'value': email_address - }}, - ] # Create a statement to select users. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('email = :email') + .WithBindVariable('email', email_address)) # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/dfp/v201708/user_service/update_users.py b/examples/dfp/v201708/user_service/update_users.py index 0354b8fa..cd415ff5 100755 --- a/examples/dfp/v201708/user_service/update_users.py +++ b/examples/dfp/v201708/user_service/update_users.py @@ -31,17 +31,9 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201708') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -59,6 +51,7 @@ def main(client, user_id): else: print 'No users found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py index 748bb82b..8cce293c 100755 --- a/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py @@ -38,17 +38,9 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201708') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -62,10 +54,14 @@ def main(client, user_id): print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) + # Action doesn't require limit/offset + statement.limit = None + statement.offset = None + # Perform action. result = user_team_association_service.performUserTeamAssociationAction( {'xsi_type': 'DeleteUserTeamAssociations'}, - {'query': query, 'values': values}) + statement.ToStatement()) # Display results. if result and int(result['numChanges']) > 0: @@ -74,6 +70,7 @@ def main(client, user_id): else: print 'No user team associations were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py index a2a56fa7..fa78d834 100755 --- a/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py @@ -26,16 +26,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( 'UserTeamAssociationService', version='v201708') - query = 'WHERE userId = :userId' - values = [ - {'key': 'userId', - 'value': { - 'xsi_type': 'TextValue', - 'value': user_id - }}, - ] # Create a statement to select user team associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py index c6dcc284..8e3152c7 100755 --- a/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py @@ -40,17 +40,9 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201708') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -79,6 +71,7 @@ def main(client, user_id): else: print 'No user team associations found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py index 8ff9c893..d9d9ff51 100755 --- a/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py @@ -33,35 +33,13 @@ def main(client, proposal_id): workflow_request_service = client.GetService('WorkflowRequestService', version='v201708') - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) workflow_approval_requests_approved = 0 # Get workflow approval requests by statement. diff --git a/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py index 94390849..26d50042 100755 --- a/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py @@ -27,16 +27,10 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - }}, - ] # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py index 77e947ab..a0a39fd3 100755 --- a/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py @@ -27,16 +27,10 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201708') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - }}, - ] # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py index 7a11e501..79fef4c0 100755 --- a/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -33,35 +33,13 @@ def main(client, proposal_id): workflow_request_service = client.GetService('WorkflowRequestService', version='v201708') - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) workflow_external_condition_requests_triggered = 0 # Get workflow external condition requests by statement. diff --git a/examples/dfp/v201702/activity_group_service/__init__.py b/examples/dfp/v201711/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201702/activity_group_service/__init__.py rename to examples/dfp/v201711/activity_group_service/__init__.py diff --git a/examples/dfp/v201702/activity_group_service/create_activity_groups.py b/examples/dfp/v201711/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201702/activity_group_service/create_activity_groups.py rename to examples/dfp/v201711/activity_group_service/create_activity_groups.py index 9f5ec668..cba5979e 100755 --- a/examples/dfp/v201702/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201702') + version='v201711') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py similarity index 86% rename from examples/dfp/v201702/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201711/activity_group_service/get_active_activity_groups.py index a5059f06..7b074ea4 100755 --- a/examples/dfp/v201702/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'ActivityGroupService', version='v201711') # Create a statement to select activity groups. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py similarity index 97% rename from examples/dfp/v201702/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201711/activity_group_service/get_all_activity_groups.py index d49855a1..7d51a7a9 100755 --- a/examples/dfp/v201702/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201702') + 'ActivityGroupService', version='v201711') # Create a statement to select activity groups. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/activity_group_service/update_activity_groups.py b/examples/dfp/v201711/activity_group_service/update_activity_groups.py similarity index 87% rename from examples/dfp/v201705/activity_group_service/update_activity_groups.py rename to examples/dfp/v201711/activity_group_service/update_activity_groups.py index df1b623a..5cd9e5d8 100755 --- a/examples/dfp/v201705/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/update_activity_groups.py @@ -37,20 +37,13 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201705') + version='v201711') # Create statement object to select a single activity groups by ID. - values = [{ - 'key': 'activityGroupId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_group_id - } - }] - query = 'WHERE id = :activityGroupId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityGroupId') + .WithBindVariable('activityGroupId', long(activity_group_id)) + .Limit(1)) # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( @@ -70,6 +63,7 @@ def main(client, activity_group_id, advertiser_company_id): else: print 'No activity groups found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/activity_service/__init__.py b/examples/dfp/v201711/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201702/activity_service/__init__.py rename to examples/dfp/v201711/activity_service/__init__.py diff --git a/examples/dfp/v201705/activity_service/create_activities.py b/examples/dfp/v201711/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201705/activity_service/create_activities.py rename to examples/dfp/v201711/activity_service/create_activities.py index 60adc312..3926d5c0 100755 --- a/examples/dfp/v201705/activity_service/create_activities.py +++ b/examples/dfp/v201711/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201705') + activity_service = client.GetService('ActivityService', version='v201711') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201705/activity_service/get_active_activities.py b/examples/dfp/v201711/activity_service/get_active_activities.py similarity index 87% rename from examples/dfp/v201705/activity_service/get_active_activities.py rename to examples/dfp/v201711/activity_service/get_active_activities.py index e9e16a6e..e255d8b0 100755 --- a/examples/dfp/v201705/activity_service/get_active_activities.py +++ b/examples/dfp/v201711/activity_service/get_active_activities.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + activity_service = client.GetService('ActivityService', version='v201711') # Create a statement to select activities. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/dfp/v201705/activity_service/get_all_activities.py b/examples/dfp/v201711/activity_service/get_all_activities.py similarity index 99% rename from examples/dfp/v201705/activity_service/get_all_activities.py rename to examples/dfp/v201711/activity_service/get_all_activities.py index a3b4412b..304c1d3c 100755 --- a/examples/dfp/v201705/activity_service/get_all_activities.py +++ b/examples/dfp/v201711/activity_service/get_all_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201705') + activity_service = client.GetService('ActivityService', version='v201711') # Create a statement to select activities. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/activity_service/update_activities.py b/examples/dfp/v201711/activity_service/update_activities.py similarity index 90% rename from examples/dfp/v201705/activity_service/update_activities.py rename to examples/dfp/v201711/activity_service/update_activities.py index ae4bdcc0..a1d20c13 100755 --- a/examples/dfp/v201705/activity_service/update_activities.py +++ b/examples/dfp/v201711/activity_service/update_activities.py @@ -35,18 +35,13 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201705') + activity_service = client.GetService('ActivityService', version='v201711') # Create statement object to select one activity by ID to update. - values = [{ - 'key': 'activityId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_id - } - }] - query = 'WHERE id = :activityId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityId') + .WithBindVariable('activityId', long(activity_id)) + .Limit(1)) # Get activities by statement. response = activity_service.getActivitiesByStatement( @@ -66,6 +61,7 @@ def main(client, activity_id): else: print 'No activities found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/audience_segment_service/__init__.py b/examples/dfp/v201711/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201702/audience_segment_service/__init__.py rename to examples/dfp/v201711/audience_segment_service/__init__.py diff --git a/examples/dfp/v201705/audience_segment_service/create_audience_segments.py b/examples/dfp/v201711/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/dfp/v201705/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/create_audience_segments.py index 3a942da6..16b08496 100755 --- a/examples/dfp/v201705/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + 'AudienceSegmentService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py similarity index 97% rename from examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py index f0aad4be..1990fdd6 100755 --- a/examples/dfp/v201705/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') + 'AudienceSegmentService', version='v201711') # Create a statement to select audience segments. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py similarity index 86% rename from examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py index faec6a63..7a96417b 100755 --- a/examples/dfp/v201705/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - }}, - ] + 'AudienceSegmentService', version='v201711') # Create a statement to select audience segments. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'FIRST_PARTY')) # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py similarity index 80% rename from examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py index a3d7fc05..082df910 100755 --- a/examples/dfp/v201705/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py @@ -30,24 +30,15 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') + 'AudienceSegmentService', version='v201711') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py b/examples/dfp/v201711/audience_segment_service/update_audience_segments.py similarity index 81% rename from examples/dfp/v201702/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201711/audience_segment_service/update_audience_segments.py index 2c708dea..3ede3c29 100755 --- a/examples/dfp/v201702/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/update_audience_segments.py @@ -29,24 +29,15 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') + 'AudienceSegmentService', version='v201711') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) # Get audience segments by statement. response = audience_segment_service.getAudienceSegmentsByStatement( diff --git a/examples/dfp/v201702/base_rate_service/__init__.py b/examples/dfp/v201711/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201702/base_rate_service/__init__.py rename to examples/dfp/v201711/base_rate_service/__init__.py diff --git a/examples/dfp/v201705/base_rate_service/create_product_base_rates.py b/examples/dfp/v201711/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201705/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201711/base_rate_service/create_product_base_rates.py index b8ae2eac..cc083cd8 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201705') + 'BaseRateService', version='v201711') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py similarity index 99% rename from examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py rename to examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py index bd7779cb..2a6ea9ac 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201705') + base_rate_service = client.GetService('BaseRateService', version='v201711') # Create a base rate for a product package item. product_package_item_base_rate = { diff --git a/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py index 23b22bb2..2f46ab9a 100755 --- a/examples/dfp/v201705/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201705') + 'BaseRateService', version='v201711') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201705/base_rate_service/get_all_base_rates.py b/examples/dfp/v201711/base_rate_service/get_all_base_rates.py similarity index 99% rename from examples/dfp/v201705/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201711/base_rate_service/get_all_base_rates.py index 0d42dfc2..324d1e17 100755 --- a/examples/dfp/v201705/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/get_all_base_rates.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201705') + base_rate_service = client.GetService('BaseRateService', version='v201711') # Create a statement to select base rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py similarity index 88% rename from examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py rename to examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py index 5ebb7edf..b4d547b0 100755 --- a/examples/dfp/v201705/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py @@ -24,17 +24,11 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201705') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] + base_rate_service = client.GetService('BaseRateService', version='v201711') # Create a statement to select base rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/dfp/v201705/base_rate_service/update_base_rates.py b/examples/dfp/v201711/base_rate_service/update_base_rates.py similarity index 90% rename from examples/dfp/v201705/base_rate_service/update_base_rates.py rename to examples/dfp/v201711/base_rate_service/update_base_rates.py index fd9510c0..936444d2 100755 --- a/examples/dfp/v201705/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/update_base_rates.py @@ -29,18 +29,14 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201705') + base_rate_service = client.GetService('BaseRateService', version='v201711') # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': base_rate_id - } - }] - query = 'where id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', long(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( diff --git a/examples/dfp/v201702/native_style_service/__init__.py b/examples/dfp/v201711/cdn_configuration_service/__init__.py similarity index 100% rename from examples/dfp/v201702/native_style_service/__init__.py rename to examples/dfp/v201711/cdn_configuration_service/__init__.py diff --git a/examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py b/examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py new file mode 100755 index 00000000..f646f7fc --- /dev/null +++ b/examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 code example creates new cdn configurations. + +To determine which configurations exist, run get_all_cdn_configurations.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201711') + + # Create cdn config objects. + # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. + configs = [{ + # Basic example with no security policies. + 'name': 'ApiConfig1', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + } + } + }, { + # Complex example with security policies. + 'name': 'ApiConfig2', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': False, + 'tokenAuthenticationKey': 'abc123', + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': True, + 'originForwardingType': 'CONVENTIONAL', + 'originPathPrefix': '/path/to/my/origin' + } + } + } + }] + + # Add configs. + configs = cdn_config_service.createCdnConfigurations(configs) + + # Display results. + for config in configs: + print('Created CDN configuration with type "%s" and name "%s".' + % (config['cdnConfigurationType'], config['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py b/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py new file mode 100755 index 00000000..3815c731 --- /dev/null +++ b/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 CDN configuration objects. + +Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be +returned. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201711') + + # Create a statement to select cdn configurations. + statement = dfp.StatementBuilder() + + # Retrieve a small number of configs at a time, paging + # through until all have been retrieved. + while True: + response = (cdn_config_service + .getCdnConfigurationsByStatement(statement.ToStatement())) + if 'results' in response: + for cdn in response['results']: + # Print out some information for each company. + print('Found CDN configuration with type "%s" and name "%s".' + % (cdn['cdnConfigurationType'], cdn['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/company_service/__init__.py b/examples/dfp/v201711/company_service/__init__.py similarity index 100% rename from examples/dfp/v201702/company_service/__init__.py rename to examples/dfp/v201711/company_service/__init__.py diff --git a/examples/dfp/v201702/company_service/create_companies.py b/examples/dfp/v201711/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201702/company_service/create_companies.py rename to examples/dfp/v201711/company_service/create_companies.py index 8b41d9ac..035983be 100755 --- a/examples/dfp/v201702/company_service/create_companies.py +++ b/examples/dfp/v201711/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201702') + company_service = client.GetService('CompanyService', version='v201711') # Create company objects. companies = [ diff --git a/examples/dfp/v201702/company_service/get_advertisers.py b/examples/dfp/v201711/company_service/get_advertisers.py similarity index 88% rename from examples/dfp/v201702/company_service/get_advertisers.py rename to examples/dfp/v201711/company_service/get_advertisers.py index 7e8085ac..5f44d794 100755 --- a/examples/dfp/v201702/company_service/get_advertisers.py +++ b/examples/dfp/v201711/company_service/get_advertisers.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - }}, - ] + company_service = client.GetService('CompanyService', version='v201711') # Create a statement to select companies. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'ADVERTISER')) # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/dfp/v201702/company_service/get_all_companies.py b/examples/dfp/v201711/company_service/get_all_companies.py similarity index 99% rename from examples/dfp/v201702/company_service/get_all_companies.py rename to examples/dfp/v201711/company_service/get_all_companies.py index 6693f930..afbb57e9 100755 --- a/examples/dfp/v201702/company_service/get_all_companies.py +++ b/examples/dfp/v201711/company_service/get_all_companies.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201702') + company_service = client.GetService('CompanyService', version='v201711') # Create a statement to select companies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/company_service/update_companies.py b/examples/dfp/v201711/company_service/update_companies.py similarity index 89% rename from examples/dfp/v201705/company_service/update_companies.py rename to examples/dfp/v201711/company_service/update_companies.py index c6b76cca..96cc22fd 100755 --- a/examples/dfp/v201705/company_service/update_companies.py +++ b/examples/dfp/v201711/company_service/update_companies.py @@ -35,18 +35,13 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201705') + company_service = client.GetService('CompanyService', version='v201711') # Create statement object to only select a single company by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': company_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(company_id)) + .Limit(1)) # Get companies by statement. response = company_service.getCompaniesByStatement( @@ -63,11 +58,12 @@ def main(client, company_id): # Display results. for company in companies: print (('Company with ID "%s", name "%s", and comment "%s"' - 'was updated.') + ' was updated.') % (company['id'], company['name'], company['comment'])) else: print 'No companies found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/contact_service/__init__.py b/examples/dfp/v201711/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201702/contact_service/__init__.py rename to examples/dfp/v201711/contact_service/__init__.py diff --git a/examples/dfp/v201705/contact_service/create_contacts.py b/examples/dfp/v201711/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201705/contact_service/create_contacts.py rename to examples/dfp/v201711/contact_service/create_contacts.py index 858c188a..89872c6a 100755 --- a/examples/dfp/v201705/contact_service/create_contacts.py +++ b/examples/dfp/v201711/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201705') + contact_service = client.GetService('ContactService', version='v201711') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201705/contact_service/get_all_contacts.py b/examples/dfp/v201711/contact_service/get_all_contacts.py similarity index 99% rename from examples/dfp/v201705/contact_service/get_all_contacts.py rename to examples/dfp/v201711/contact_service/get_all_contacts.py index c8e1c3e9..0c824ad3 100755 --- a/examples/dfp/v201705/contact_service/get_all_contacts.py +++ b/examples/dfp/v201711/contact_service/get_all_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201705') + contact_service = client.GetService('ContactService', version='v201711') # Create a statement to select contacts. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/contact_service/get_uninvited_contacts.py b/examples/dfp/v201711/contact_service/get_uninvited_contacts.py similarity index 87% rename from examples/dfp/v201702/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201711/contact_service/get_uninvited_contacts.py index def756c1..65b0e339 100755 --- a/examples/dfp/v201702/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201711/contact_service/get_uninvited_contacts.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - }}, - ] + contact_service = client.GetService('ContactService', version='v201711') # Create a statement to select contacts. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'UNINVITED')) # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/dfp/v201702/contact_service/update_contacts.py b/examples/dfp/v201711/contact_service/update_contacts.py similarity index 90% rename from examples/dfp/v201702/contact_service/update_contacts.py rename to examples/dfp/v201711/contact_service/update_contacts.py index d035fc12..dbab02df 100755 --- a/examples/dfp/v201702/contact_service/update_contacts.py +++ b/examples/dfp/v201711/contact_service/update_contacts.py @@ -35,18 +35,13 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201702') + contact_service = client.GetService('ContactService', version='v201711') # Create statement object to select the single contact by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': contact_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(contact_id)) + .Limit(1)) # Get contacts by statement. response = contact_service.getContactsByStatement( @@ -69,6 +64,7 @@ def main(client, contact_id): else: print 'No contacts found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index c0f39c37..672b1efe 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201705') + 'ContentMetadataKeyHierarchyService', version='v201711') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 90% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 986f2c1d..30327029 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,19 +40,15 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201705') + 'ContentMetadataKeyHierarchyService', version='v201711') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -78,6 +74,7 @@ def main(client, content_metadata_key_hierarchy_id): print ('Number of content metadata key hierarchies deleted: %s' % result['numChanges']) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index ce28be95..66c97f64 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201705') + 'ContentMetadataKeyHierarchyService', version='v201711') # Create a statement to select content metadata key hierarchies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index b1f5c6bb..81672538 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,19 +42,15 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201702') + 'ContentMetadataKeyHierarchyService', version='v201711') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -90,6 +86,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): else: print 'No content metadata key hierarchies were found' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/content_service/__init__.py b/examples/dfp/v201711/content_service/__init__.py similarity index 100% rename from examples/dfp/v201702/content_service/__init__.py rename to examples/dfp/v201711/content_service/__init__.py diff --git a/examples/dfp/v201705/content_service/get_all_content.py b/examples/dfp/v201711/content_service/get_all_content.py similarity index 99% rename from examples/dfp/v201705/content_service/get_all_content.py rename to examples/dfp/v201711/content_service/get_all_content.py index 5a73428e..cf7e3661 100755 --- a/examples/dfp/v201705/content_service/get_all_content.py +++ b/examples/dfp/v201711/content_service/get_all_content.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201705') + content_service = client.GetService('ContentService', version='v201711') # Create a statement to select content. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_service/__init__.py b/examples/dfp/v201711/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201702/creative_service/__init__.py rename to examples/dfp/v201711/creative_service/__init__.py diff --git a/examples/dfp/v201702/creative_service/copy_image_creatives.py b/examples/dfp/v201711/creative_service/copy_image_creatives.py similarity index 99% rename from examples/dfp/v201702/creative_service/copy_image_creatives.py rename to examples/dfp/v201711/creative_service/copy_image_creatives.py index 7578afdf..6554acb1 100755 --- a/examples/dfp/v201702/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201711/creative_service/copy_image_creatives.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Create a statement to get the image creative. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_service/create_creative_from_template.py b/examples/dfp/v201711/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201702/creative_service/create_creative_from_template.py rename to examples/dfp/v201711/creative_service/create_creative_from_template.py index 13b28235..64bd5e63 100755 --- a/examples/dfp/v201702/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201711/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201702/creative_service/create_creatives.py b/examples/dfp/v201711/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201702/creative_service/create_creatives.py rename to examples/dfp/v201711/creative_service/create_creatives.py index fc3a886d..c315d9ea 100755 --- a/examples/dfp/v201702/creative_service/create_creatives.py +++ b/examples/dfp/v201711/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201705/creative_service/create_custom_creative.py b/examples/dfp/v201711/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201705/creative_service/create_custom_creative.py rename to examples/dfp/v201711/creative_service/create_custom_creative.py index abc6b632..99ef3a2d 100755 --- a/examples/dfp/v201705/creative_service/create_custom_creative.py +++ b/examples/dfp/v201711/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201711') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201705/creative_service/create_native_creative.py b/examples/dfp/v201711/creative_service/create_native_creative.py similarity index 99% rename from examples/dfp/v201705/creative_service/create_native_creative.py rename to examples/dfp/v201711/creative_service/create_native_creative.py index b32309a3..d28f8cdc 100755 --- a/examples/dfp/v201705/creative_service/create_native_creative.py +++ b/examples/dfp/v201711/creative_service/create_native_creative.py @@ -46,7 +46,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201711') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/dfp/v201702/creative_service/get_all_creatives.py b/examples/dfp/v201711/creative_service/get_all_creatives.py similarity index 99% rename from examples/dfp/v201702/creative_service/get_all_creatives.py rename to examples/dfp/v201711/creative_service/get_all_creatives.py index e96715de..a326edc7 100755 --- a/examples/dfp/v201702/creative_service/get_all_creatives.py +++ b/examples/dfp/v201711/creative_service/get_all_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Create a statement to select creatives. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_service/get_image_creatives.py b/examples/dfp/v201711/creative_service/get_image_creatives.py similarity index 86% rename from examples/dfp/v201705/creative_service/get_image_creatives.py rename to examples/dfp/v201711/creative_service/get_image_creatives.py index bc977ea8..5091c9da 100755 --- a/examples/dfp/v201705/creative_service/get_image_creatives.py +++ b/examples/dfp/v201711/creative_service/get_image_creatives.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') - query = 'WHERE creativeType = :creativeType' - values = [ - {'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': '_image_creative' - }}, - ] + creative_service = client.GetService('CreativeService', version='v201711') # Create a statement to select creatives. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('creativeType = :creativeType') + .WithBindVariable('creativeType', 'ImageCreative')) # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/dfp/v201702/creative_service/update_creatives.py b/examples/dfp/v201711/creative_service/update_creatives.py similarity index 85% rename from examples/dfp/v201702/creative_service/update_creatives.py rename to examples/dfp/v201711/creative_service/update_creatives.py index 59dcc8bd..c718b379 100755 --- a/examples/dfp/v201702/creative_service/update_creatives.py +++ b/examples/dfp/v201711/creative_service/update_creatives.py @@ -34,24 +34,14 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201711') # Create statement object to get all image creatives. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }, { - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': image_creative_id - } - }] - query = 'WHERE creativeType = :type AND id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('creativeType = :type AND id = :id') + .WithBindVariable('type', 'ImageCreative') + .WithBindVariable('id', long(image_creative_id)) + .Limit(1)) # Get creatives by statement. response = creative_service.getCreativesByStatement( @@ -74,6 +64,7 @@ def main(client, image_creative_id): else: print 'No creatives found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/creative_set_service/__init__.py b/examples/dfp/v201711/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201702/creative_set_service/__init__.py rename to examples/dfp/v201711/creative_set_service/__init__.py diff --git a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py index 08513acc..579c7746 100755 --- a/examples/dfp/v201702/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201702/creative_set_service/create_creative_set.py b/examples/dfp/v201711/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201702/creative_set_service/create_creative_set.py rename to examples/dfp/v201711/creative_set_service/create_creative_set.py index 9118a157..c734a6fd 100755 --- a/examples/dfp/v201702/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201711/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201702') + version='v201711') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py similarity index 97% rename from examples/dfp/v201702/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201711/creative_set_service/get_all_creative_sets.py index 6e8bd9fa..ffabc63c 100755 --- a/examples/dfp/v201702/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201702') + 'CreativeSetService', version='v201711') # Create a statement to select creative sets. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py similarity index 85% rename from examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py index 2d4208d4..c2aaa861 100755 --- a/examples/dfp/v201705/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,17 +25,11 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201705') - query = 'WHERE masterCreativeId = :masterCreativeId' - values = [ - {'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'TextValue', - 'value': master_creative_id - }}, - ] + 'CreativeSetService', version='v201711') # Create a statement to select creative sets. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('masterCreativeId = :masterCreativeId') + .WithBindVariable('masterCreativeId', master_creative_id)) # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/dfp/v201702/creative_set_service/update_creative_set.py b/examples/dfp/v201711/creative_set_service/update_creative_set.py similarity index 89% rename from examples/dfp/v201702/creative_set_service/update_creative_set.py rename to examples/dfp/v201711/creative_set_service/update_creative_set.py index c03266d4..44737177 100755 --- a/examples/dfp/v201702/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201711/creative_set_service/update_creative_set.py @@ -37,18 +37,12 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201702') + version='v201711') # Create statement to select a single creative set by ID. - values = [{ - 'key': 'creativeSetId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_set_id - } - }] - query = 'WHERE id = :creativeSetId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeSetId') + .WithBindVariable('creativeSetId', long(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -72,6 +66,7 @@ def main(client, creative_set_id, companion_creative_id): else: print 'No creative sets found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/creative_template_service/__init__.py b/examples/dfp/v201711/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201702/creative_template_service/__init__.py rename to examples/dfp/v201711/creative_template_service/__init__.py diff --git a/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py similarity index 97% rename from examples/dfp/v201705/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201711/creative_template_service/get_all_creative_templates.py index 7550f838..ed5f73f5 100755 --- a/examples/dfp/v201705/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201705') + 'CreativeTemplateService', version='v201711') # Create a statement to select creative templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py similarity index 86% rename from examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py rename to examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py index 920c4974..a76a87fd 100755 --- a/examples/dfp/v201705/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - }}, - ] + 'CreativeTemplateService', version='v201711') # Create a statement to select creative templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'SYSTEM_DEFINED')) # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py similarity index 91% rename from examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py index 2ac46646..ba0d2ca5 100755 --- a/examples/dfp/v201702/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py @@ -37,15 +37,15 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201702') + version='v201711') # Create creative wrapper objects. creative_wrapper = { # A label can only be associated with one creative wrapper. 'labelId': label_id, 'ordering': 'INNER', - 'header': {'htmlSnippet': 'My creative wrapper header'}, - 'footer': {'htmlSnippet': 'My creative wrapper footer'} + 'htmlHeader': 'My creative wrapper header', + 'htmlFooter': 'My creative wrapper footer' } # Add creative wrapper. diff --git a/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 85% rename from examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py index 229980be..7d560973 100755 --- a/examples/dfp/v201705/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,24 +33,13 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201705') + version='v201711') # Create a query to select the active creative wrappers for the given label. - values = [{ - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status AND labelId = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status AND labelId = :labelId') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('labelId', long(label_id))) creative_wrappers_deactivated = 0 @@ -82,6 +71,7 @@ def main(client, label_id): else: print 'No creative wrappers were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py similarity index 86% rename from examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py index 2bc54fc4..98f9f576 100755 --- a/examples/dfp/v201705/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'CreativeWrapperService', version='v201711') # Create a statement to select creative wrappers. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py similarity index 97% rename from examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py index 8e63e641..30780139 100755 --- a/examples/dfp/v201705/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201705') + 'CreativeWrapperService', version='v201711') # Create a statement to select creative wrappers. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py similarity index 88% rename from examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py index 21258f0b..b4161728 100755 --- a/examples/dfp/v201705/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py @@ -36,18 +36,13 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201705') + version='v201711') # Create statement to get a creative wrapper by ID. - values = [{ - 'key': 'creativeWrapperId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_wrapper_id - } - }] - query = 'WHERE id = :creativeWrapperId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeWrapperId') + .WithBindVariable('creativeWrapperId', + long(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -71,6 +66,7 @@ def main(client, creative_wrapper_id): else: print 'No creative wrappers found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_field_service/__init__.py b/examples/dfp/v201711/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201702/custom_field_service/__init__.py rename to examples/dfp/v201711/custom_field_service/__init__.py diff --git a/examples/dfp/v201705/custom_field_service/create_custom_field_options.py b/examples/dfp/v201711/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201705/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201711/custom_field_service/create_custom_field_options.py index 182fc145..3c890017 100755 --- a/examples/dfp/v201705/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201711/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201711') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201702/custom_field_service/create_custom_fields.py b/examples/dfp/v201711/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201702/custom_field_service/create_custom_fields.py rename to examples/dfp/v201711/custom_field_service/create_custom_fields.py index a823244c..58500da2 100755 --- a/examples/dfp/v201702/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201711') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 82% rename from examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py index ece9ff34..ac1e29fa 100755 --- a/examples/dfp/v201705/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,27 +33,14 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201711') # Create statement to select only active custom fields that apply to # line items. - values = [ - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }, { - 'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - } - ] - query = 'WHERE entityType = :entityType and isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType and isActive = :isActive') + .WithBindVariable('entityType', 'LINE_ITEM') + .WithBindVariable('isActive', True)) custom_fields_deactivated = 0 @@ -79,6 +66,7 @@ def main(client): else: print 'No custom fields were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py similarity index 97% rename from examples/dfp/v201705/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201711/custom_field_service/get_all_custom_fields.py index 740a05bf..bd60ea4c 100755 --- a/examples/dfp/v201705/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201711') # Create a statement to select custom fields. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py similarity index 85% rename from examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py rename to examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py index a350fc29..ba26fb6e 100755 --- a/examples/dfp/v201702/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') - query = 'WHERE entityType = :entityType' - values = [ - {'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - }}, - ] + 'CustomFieldService', version='v201711') # Create a statement to select custom fields. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType') + .WithBindVariable('entityType', 'LINE_ITEM')) # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py similarity index 98% rename from examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py index 5080e010..2c0c0ad1 100755 --- a/examples/dfp/v201705/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py @@ -42,9 +42,9 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201711') - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201711') # Create statement to get a custom field. custom_field_values = [{ diff --git a/examples/dfp/v201705/custom_field_service/update_custom_fields.py b/examples/dfp/v201711/custom_field_service/update_custom_fields.py similarity index 88% rename from examples/dfp/v201705/custom_field_service/update_custom_fields.py rename to examples/dfp/v201711/custom_field_service/update_custom_fields.py index 7a1b54c0..1b6403c7 100755 --- a/examples/dfp/v201705/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/update_custom_fields.py @@ -36,18 +36,12 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201711') # Create statement to get a custom field. - values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - query = 'WHERE id = :customFieldId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', long(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -69,6 +63,7 @@ def main(client, custom_field_id): else: print 'No custom fields found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_targeting_service/__init__.py b/examples/dfp/v201711/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201702/custom_targeting_service/__init__.py rename to examples/dfp/v201711/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py index ed80ede7..0fd0c263 100755 --- a/examples/dfp/v201702/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py similarity index 90% rename from examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py index abb78c9d..defeb67f 100755 --- a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,17 +36,11 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') - - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': key_name - } - }] - query = 'WHERE name = :name' - statement = dfp.FilterStatement(query, values) + 'CustomTargetingService', version='v201711') + + statement = (dfp.StatementBuilder() + .Where('name = :name') + .WithBindVariable('name', key_name)) deleted_custom_targeting_keys = 0 @@ -76,6 +70,7 @@ def main(client, key_name): else: print 'No custom targeting keys were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py similarity index 98% rename from examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py index 9a09683d..91c3fd9c 100755 --- a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py @@ -36,7 +36,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201711') filter_values = [{ 'key': 'keyId', diff --git a/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 97c46ba1..4559215e 100755 --- a/examples/dfp/v201705/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201711') # Create statement to get all targeting keys. targeting_key_statement = dfp.StatementBuilder() @@ -46,7 +46,7 @@ def main(client): ', '.join([str(key['id']) for key in all_keys])) statement = dfp.FilterStatement(query) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( diff --git a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 78% rename from examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 8e297f13..d9f0f076 100755 --- a/examples/dfp/v201702/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,18 +23,12 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') # Create statement to get targeting keys for predefined values. - query = ('WHERE type = :type') - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] - targeting_key_statement = dfp.FilterStatement(query, values) + targeting_key_statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'PREDEFINED')) all_keys = [] @@ -44,17 +38,17 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (:ids)') + .WithBindVariable('ids', [key['id'] for key in all_keys])) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( @@ -67,7 +61,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py similarity index 88% rename from examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py index ed87ad62..0b6ebc81 100755 --- a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py @@ -30,17 +30,12 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201711') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE id = :keyId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :keyId') + .WithBindVariable('keyId', long(key_id)) + .Limit(1)) # Get custom targeting keys by statement. response = custom_targeting_service.getCustomTargetingKeysByStatement( @@ -65,6 +60,7 @@ def main(client, key_id): else: print 'No custom targeting keys were found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py similarity index 88% rename from examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py index edf57cd7..edf52d61 100755 --- a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py @@ -30,17 +30,11 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201711') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', long(key_id))) while True: # Get custom targeting values by statement. @@ -70,6 +64,7 @@ def main(client, key_id): if response['totalResultSetSize'] == 0: print 'No custom targeting values were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/exchange_rate_service/__init__.py b/examples/dfp/v201711/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201702/exchange_rate_service/__init__.py rename to examples/dfp/v201711/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py index 2cdc541f..8be06ec7 100755 --- a/examples/dfp/v201702/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201702') + version='v201711') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py similarity index 97% rename from examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py index 39f6e4f6..5b9c8ae3 100755 --- a/examples/dfp/v201705/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201705') + 'ExchangeRateService', version='v201711') # Create a statement to select exchange rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 86% rename from examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py index f2b683f1..3b09f1dd 100755 --- a/examples/dfp/v201702/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,17 +25,11 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201702') - query = 'WHERE currencyCode = :currencyCode' - values = [ - {'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - }}, - ] + 'ExchangeRateService', version='v201711') # Create a statement to select exchange rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('currencyCode = :currencyCode') + .WithBindVariable('currencyCode', currency_code)) # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py similarity index 87% rename from examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py index 26dc9f69..61a3a46d 100755 --- a/examples/dfp/v201702/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py @@ -30,19 +30,13 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201702') + version='v201711') # Create a statement to get an exchange rate by its ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': exchange_rate_id - } - }] - query = 'WHERE id = :id' - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(exchange_rate_id)) + .Limit(1)) # Get rate cards by statement. response = exchange_rate_service.getExchangeRatesByStatement( diff --git a/examples/dfp/v201705/forecast_service/get_availability_forecast.py b/examples/dfp/v201711/forecast_service/get_availability_forecast.py similarity index 90% rename from examples/dfp/v201705/forecast_service/get_availability_forecast.py rename to examples/dfp/v201711/forecast_service/get_availability_forecast.py index 0bb2e691..24916d0b 100755 --- a/examples/dfp/v201705/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201711/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + forecast_service = client.GetService('ForecastService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] @@ -105,11 +105,14 @@ def main(client, advertiser_id): forecast = forecast_service.getAvailabilityForecast( prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -117,9 +120,10 @@ def main(client, advertiser_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py similarity index 83% rename from examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py index ff2263e0..3820ae8f 100755 --- a/examples/dfp/v201705/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201705') + forecast_service = client.GetService('ForecastService', version='v201711') # Set forecasting options. forecast_options = { @@ -42,11 +42,14 @@ def main(client, line_item_id): forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -54,9 +57,10 @@ def main(client, line_item_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py index 42f8aa03..38f54050 100755 --- a/examples/dfp/v201705/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201705') + forecast_service = client.GetService('ForecastService', version='v201711') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201702/inventory_service/__init__.py b/examples/dfp/v201711/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201702/inventory_service/__init__.py rename to examples/dfp/v201711/inventory_service/__init__.py diff --git a/examples/dfp/v201702/inventory_service/archive_ad_units.py b/examples/dfp/v201711/inventory_service/archive_ad_units.py similarity index 90% rename from examples/dfp/v201702/inventory_service/archive_ad_units.py rename to examples/dfp/v201711/inventory_service/archive_ad_units.py index b1097b3b..b7222ecf 100755 --- a/examples/dfp/v201702/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201711/inventory_service/archive_ad_units.py @@ -35,19 +35,13 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201702') + inventory_service = client.GetService('InventoryService', version='v201711') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - values = [{ - 'key': 'parentId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': parent_id - } - }] - query = 'WHERE parentId = :parentId or id = :parentId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId or id = :parentId') + .WithBindVariable('parentId', long(parent_id))) ad_units_archived = 0 @@ -74,6 +68,7 @@ def main(client, parent_id): else: print 'No ad units were archived.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/inventory_service/create_ad_units.py b/examples/dfp/v201711/inventory_service/create_ad_units.py similarity index 99% rename from examples/dfp/v201705/inventory_service/create_ad_units.py rename to examples/dfp/v201711/inventory_service/create_ad_units.py index 0781c1b7..b017e0dd 100755 --- a/examples/dfp/v201705/inventory_service/create_ad_units.py +++ b/examples/dfp/v201711/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201705') + inventory_service = client.GetService('InventoryService', version='v201711') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py new file mode 100755 index 00000000..059e2af7 --- /dev/null +++ b/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 prints all ad unit names as a tree.""" + + +# Import appropriate modules from the client library. +import collections +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201711') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select only the root ad unit by ID. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', root_ad_unit_id)) + + # Make a request for the root ad unit + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + root_ad_unit = response['results'][0] + + all_ad_units = get_all_ad_units(inventory_service) + + display_hierarchy(root_ad_unit, all_ad_units) + + +def get_all_ad_units(inventory_service): + """Download all ad units. + + Args: + inventory_service: An instance of the InventoryService. + + Returns: + A list containing all ad units. + """ + # Create a statement to get all ad units. + statement = (dfp.StatementBuilder() + .OrderBy('id', ascending=True)) + + # Pull down all ad units into a list + keep_iterating = True + total_results = 0 + found_ad_units = [] + while keep_iterating: + page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in page: + total_results = page['totalResultSetSize'] + found_ad_units.extend(page['results']) + + statement.offset += statement.limit + keep_iterating = statement.offset < total_results + + return found_ad_units + + +def display_hierarchy(root_ad_unit, all_ad_units): + """Display the ad units as a tree. + + Args: + root_ad_unit: The root ad unit to begin from. + all_ad_units: A list containing all ad units. + """ + # Create a dict mapping the ids of parents to lists of their children. + parent_id_to_children = collections.defaultdict(list) + for ad_unit in all_ad_units: + if 'parentId' in ad_unit: + parent_id_to_children[ad_unit['parentId']].append(ad_unit) + parent_id_to_children = dict(parent_id_to_children) + + display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0) + + +def display_hierarchy_helper(root, parent_id_to_children, depth): + """Recursive helper for displaying the hierarchy. + + Args: + root: The current root ad unit. + parent_id_to_children: The overall map of parent ids to children. + depth: The current depth. + """ + print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id']) + + # Recurse for each child of this root that has children. + for child in parent_id_to_children.get(root['id'], []): + display_hierarchy_helper(child, parent_id_to_children, depth + 1) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py index ac351ef1..aba7e9e5 100755 --- a/examples/dfp/v201705/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py @@ -23,12 +23,12 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201705') + 'InventoryService', version='v201711') # Create a statement to select ad unit sizes. statement = dfp.FilterStatement() - # Retreive a small amount of ad unit sizes at a time, paging + # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. response = ad_unit_size_service.getAdUnitSizesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201705/inventory_service/get_all_ad_units.py b/examples/dfp/v201711/inventory_service/get_all_ad_units.py similarity index 99% rename from examples/dfp/v201705/inventory_service/get_all_ad_units.py rename to examples/dfp/v201711/inventory_service/get_all_ad_units.py index 809dd346..0b7f1585 100755 --- a/examples/dfp/v201705/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201711/inventory_service/get_all_ad_units.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201705') + ad_unit_service = client.GetService('InventoryService', version='v201711') # Create a statement to select ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py new file mode 100755 index 00000000..7e3a4200 --- /dev/null +++ b/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 child ad units of the effective root ad unit.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201711') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + parent_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select ad units under the parent ad unit. + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId') + .OrderBy('id', ascending=True) + .WithBindVariable('parentId', parent_ad_unit_id)) + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response: + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/inventory_service/update_ad_units.py b/examples/dfp/v201711/inventory_service/update_ad_units.py similarity index 92% rename from examples/dfp/v201705/inventory_service/update_ad_units.py rename to examples/dfp/v201711/inventory_service/update_ad_units.py index 3c601f56..c1c3b0e0 100755 --- a/examples/dfp/v201705/inventory_service/update_ad_units.py +++ b/examples/dfp/v201711/inventory_service/update_ad_units.py @@ -36,18 +36,12 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201705') + inventory_service = client.GetService('InventoryService', version='v201711') # Create a statement to select a single ad unit by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': ad_unit_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', ad_unit_id)) # Get ad units by statement. response = inventory_service.getAdUnitsByStatement( @@ -81,6 +75,7 @@ def main(client, ad_unit_id): print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/label_service/__init__.py b/examples/dfp/v201711/label_service/__init__.py similarity index 100% rename from examples/dfp/v201702/label_service/__init__.py rename to examples/dfp/v201711/label_service/__init__.py diff --git a/examples/dfp/v201702/label_service/create_labels.py b/examples/dfp/v201711/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201702/label_service/create_labels.py rename to examples/dfp/v201711/label_service/create_labels.py index 4c71d810..f4d95ddc 100755 --- a/examples/dfp/v201702/label_service/create_labels.py +++ b/examples/dfp/v201711/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') + label_service = client.GetService('LabelService', version='v201711') # Create label objects. labels = [] diff --git a/examples/dfp/v201702/label_service/deactivate_labels.py b/examples/dfp/v201711/label_service/deactivate_labels.py similarity index 89% rename from examples/dfp/v201702/label_service/deactivate_labels.py rename to examples/dfp/v201711/label_service/deactivate_labels.py index d9e0e71a..04227aff 100755 --- a/examples/dfp/v201702/label_service/deactivate_labels.py +++ b/examples/dfp/v201711/label_service/deactivate_labels.py @@ -27,18 +27,12 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') + label_service = client.GetService('LabelService', version='v201711') # Create query. - values = [{ - 'key': 'isActive', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'true' - } - }] - query = 'WHERE isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) labels_deactivated = 0 @@ -64,6 +58,7 @@ def main(client): else: print 'No labels were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/label_service/get_active_labels.py b/examples/dfp/v201711/label_service/get_active_labels.py similarity index 87% rename from examples/dfp/v201705/label_service/get_active_labels.py rename to examples/dfp/v201711/label_service/get_active_labels.py index 9a6ce559..8e419288 100755 --- a/examples/dfp/v201705/label_service/get_active_labels.py +++ b/examples/dfp/v201711/label_service/get_active_labels.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') - query = 'WHERE isActive = :isActive' - values = [ - {'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + label_service = client.GetService('LabelService', version='v201711') # Create a statement to select labels. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/dfp/v201702/label_service/get_all_labels.py b/examples/dfp/v201711/label_service/get_all_labels.py similarity index 99% rename from examples/dfp/v201702/label_service/get_all_labels.py rename to examples/dfp/v201711/label_service/get_all_labels.py index d4ae0fc6..2ac0531b 100755 --- a/examples/dfp/v201702/label_service/get_all_labels.py +++ b/examples/dfp/v201711/label_service/get_all_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') + label_service = client.GetService('LabelService', version='v201711') # Create a statement to select labels. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/label_service/update_labels.py b/examples/dfp/v201711/label_service/update_labels.py similarity index 87% rename from examples/dfp/v201705/label_service/update_labels.py rename to examples/dfp/v201711/label_service/update_labels.py index 236748f2..bebbe0d7 100755 --- a/examples/dfp/v201705/label_service/update_labels.py +++ b/examples/dfp/v201711/label_service/update_labels.py @@ -29,20 +29,12 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') + label_service = client.GetService('LabelService', version='v201711') # Create a statement to select only active labels. - values = [ - { - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - } - ] - query = 'WHERE id = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :labelId') + .WithBindVariable('labelId', long(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -63,6 +55,7 @@ def main(client, label_id): else: print 'No labels found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_creative_association_service/__init__.py b/examples/dfp/v201711/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201702/line_item_creative_association_service/__init__.py rename to examples/dfp/v201711/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py b/examples/dfp/v201711/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201702/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201711/line_item_creative_association_service/create_licas.py index 13743d0a..7a6b7e1f 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py similarity index 83% rename from examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py index 537ee699..453cd6ef 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py @@ -30,24 +30,13 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') # Create query. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE lineItemId = :lineItemId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId AND status = :status') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('lineItemId', long(line_item_id))) num_deactivated_licas = 0 @@ -77,6 +66,7 @@ def main(client, line_item_id): else: print 'No LICAs were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py similarity index 97% rename from examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py index 71e757ad..24b02c79 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201711') # Create a statement to select line item creative associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py similarity index 87% rename from examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py index d61f98f5..0f6a4ea4 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,17 +25,11 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') - query = 'WHERE lineItemId = :lineItemId' - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'TextValue', - 'value': line_item_id - }}, - ] + 'LineItemCreativeAssociationService', version='v201711') # Create a statement to select line item creative associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId') + .WithBindVariable('lineItemId', line_item_id)) # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py b/examples/dfp/v201711/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201705/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201711/line_item_creative_association_service/update_licas.py index b3973bf0..f52e4727 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/update_licas.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201711') # Create statement object to get all LICAs. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/line_item_service/__init__.py b/examples/dfp/v201711/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201702/line_item_service/__init__.py rename to examples/dfp/v201711/line_item_service/__init__.py diff --git a/examples/dfp/v201705/line_item_service/activate_line_items.py b/examples/dfp/v201711/line_item_service/activate_line_items.py similarity index 86% rename from examples/dfp/v201705/line_item_service/activate_line_items.py rename to examples/dfp/v201711/line_item_service/activate_line_items.py index 090c845e..c8f08513 100755 --- a/examples/dfp/v201705/line_item_service/activate_line_items.py +++ b/examples/dfp/v201711/line_item_service/activate_line_items.py @@ -33,24 +33,13 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201711') # Create query. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' - } - }] - query = 'WHERE orderId = :orderId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId AND status = :status') + .WithBindVariable('status', 'NEEDS_CREATIVES') + .WithBindVariable('orderId', long(order_id))) line_items_activated = 0 @@ -79,6 +68,7 @@ def main(client, order_id): else: print 'No line items were activated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/line_item_service/create_line_items.py b/examples/dfp/v201711/line_item_service/create_line_items.py similarity index 99% rename from examples/dfp/v201705/line_item_service/create_line_items.py rename to examples/dfp/v201711/line_item_service/create_line_items.py index 9c2e9338..71c64228 100755 --- a/examples/dfp/v201705/line_item_service/create_line_items.py +++ b/examples/dfp/v201711/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201711') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/dfp/v201705/line_item_service/create_video_line_item.py b/examples/dfp/v201711/line_item_service/create_video_line_item.py similarity index 99% rename from examples/dfp/v201705/line_item_service/create_video_line_item.py rename to examples/dfp/v201711/line_item_service/create_video_line_item.py index 63b94339..551c853c 100755 --- a/examples/dfp/v201705/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201711/line_item_service/create_video_line_item.py @@ -47,7 +47,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201711') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/dfp/v201702/line_item_service/get_all_line_items.py b/examples/dfp/v201711/line_item_service/get_all_line_items.py similarity index 99% rename from examples/dfp/v201702/line_item_service/get_all_line_items.py rename to examples/dfp/v201711/line_item_service/get_all_line_items.py index 07cee823..7f9b8b1a 100755 --- a/examples/dfp/v201702/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201711/line_item_service/get_all_line_items.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # Create a statement to select line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py similarity index 86% rename from examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py rename to examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py index 27e2cca5..686e20b6 100755 --- a/examples/dfp/v201705/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') - query = 'WHERE isMissingCreatives = :isMissingCreatives' - values = [ - {'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + line_item_service = client.GetService('LineItemService', version='v201711') # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isMissingCreatives = :isMissingCreatives') + .WithBindVariable('isMissingCreatives', True)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py similarity index 82% rename from examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py index bd8e23ca..533e0bae 100755 --- a/examples/dfp/v201705/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py @@ -21,22 +21,20 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') - query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' - values = [ - {'key': 'lastModifiedDateTime', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() - timedelta(days=1)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + line_item_service = client.GetService('LineItemService', version='v201711') + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201705/line_item_service/pause_line_items.py b/examples/dfp/v201711/line_item_service/pause_line_items.py similarity index 99% rename from examples/dfp/v201705/line_item_service/pause_line_items.py rename to examples/dfp/v201711/line_item_service/pause_line_items.py index 988f3c5f..d8261d8c 100755 --- a/examples/dfp/v201705/line_item_service/pause_line_items.py +++ b/examples/dfp/v201711/line_item_service/pause_line_items.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201711') # Create a statement to select the line item. # Change this to operate on more than one Line Item. diff --git a/examples/dfp/v201702/line_item_service/target_custom_criteria.py b/examples/dfp/v201711/line_item_service/target_custom_criteria.py similarity index 93% rename from examples/dfp/v201702/line_item_service/target_custom_criteria.py rename to examples/dfp/v201711/line_item_service/target_custom_criteria.py index e622c627..7299e656 100755 --- a/examples/dfp/v201702/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201711/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # create custom criterias custom_criteria1 = { @@ -81,15 +81,10 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - query = 'WHERE id = :lineItemId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', long(line_item_id)) + .Limit(1)) # Set custom criteria targeting on the line item. line_item = line_item_service.getLineItemsByStatement( @@ -107,6 +102,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, else: print 'No line items were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_service/update_line_items.py b/examples/dfp/v201711/line_item_service/update_line_items.py similarity index 84% rename from examples/dfp/v201702/line_item_service/update_line_items.py rename to examples/dfp/v201711/line_item_service/update_line_items.py index 62e2371b..ba6e8ae1 100755 --- a/examples/dfp/v201702/line_item_service/update_line_items.py +++ b/examples/dfp/v201711/line_item_service/update_line_items.py @@ -29,25 +29,16 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201711') # Create statement object to only select line items with even delivery rates. - values = [{ - 'key': 'deliveryRateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'EVENLY' - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId' - statement = dfp.FilterStatement(query, values, 500) + statement = (dfp.StatementBuilder() + .Where(('deliveryRateType = :deliveryRateType AND ' + 'orderId = :orderId')) + .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('deliveryRateType', 'EVENLY') + .Limit(500)) # Get line items by statement. response = line_item_service.getLineItemsByStatement( @@ -76,6 +67,7 @@ def main(client, order_id): else: print 'No line items found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/native_style_service/__init__.py b/examples/dfp/v201711/native_style_service/__init__.py similarity index 100% rename from examples/dfp/v201705/native_style_service/__init__.py rename to examples/dfp/v201711/native_style_service/__init__.py diff --git a/examples/dfp/v201705/native_style_service/create_native_styles.py b/examples/dfp/v201711/native_style_service/create_native_styles.py similarity index 98% rename from examples/dfp/v201705/native_style_service/create_native_styles.py rename to examples/dfp/v201711/native_style_service/create_native_styles.py index 65005e99..7923a081 100755 --- a/examples/dfp/v201705/native_style_service/create_native_styles.py +++ b/examples/dfp/v201711/native_style_service/create_native_styles.py @@ -149,7 +149,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201705') + version='v201711') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/dfp/v201705/native_style_service/get_all_native_styles.py b/examples/dfp/v201711/native_style_service/get_all_native_styles.py similarity index 96% rename from examples/dfp/v201705/native_style_service/get_all_native_styles.py rename to examples/dfp/v201711/native_style_service/get_all_native_styles.py index 86c2da5c..419ea950 100755 --- a/examples/dfp/v201705/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201711/native_style_service/get_all_native_styles.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201705') + version='v201711') # Create a statement to select native styles. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/network_service/__init__.py b/examples/dfp/v201711/network_service/__init__.py similarity index 100% rename from examples/dfp/v201702/network_service/__init__.py rename to examples/dfp/v201711/network_service/__init__.py diff --git a/examples/dfp/v201702/network_service/get_all_networks.py b/examples/dfp/v201711/network_service/get_all_networks.py similarity index 99% rename from examples/dfp/v201702/network_service/get_all_networks.py rename to examples/dfp/v201711/network_service/get_all_networks.py index 62107fd8..d040f75a 100755 --- a/examples/dfp/v201702/network_service/get_all_networks.py +++ b/examples/dfp/v201711/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201702') + network_service = client.GetService('NetworkService', version='v201711') networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201711/network_service/get_current_network.py b/examples/dfp/v201711/network_service/get_current_network.py new file mode 100755 index 00000000..e112d553 --- /dev/null +++ b/examples/dfp/v201711/network_service/get_current_network.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 the current network.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201711') + + current_network = network_service.getCurrentNetwork() + + print ("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/network_service/make_test_network.py b/examples/dfp/v201711/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201705/network_service/make_test_network.py rename to examples/dfp/v201711/network_service/make_test_network.py index 72797388..8782a971 100755 --- a/examples/dfp/v201705/network_service/make_test_network.py +++ b/examples/dfp/v201711/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201705') + network_service = client.GetService('NetworkService', version='v201711') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/dfp/v201702/order_service/__init__.py b/examples/dfp/v201711/order_service/__init__.py similarity index 100% rename from examples/dfp/v201702/order_service/__init__.py rename to examples/dfp/v201711/order_service/__init__.py diff --git a/examples/dfp/v201705/order_service/approve_orders.py b/examples/dfp/v201711/order_service/approve_orders.py similarity index 84% rename from examples/dfp/v201705/order_service/approve_orders.py rename to examples/dfp/v201711/order_service/approve_orders.py index 173400dc..51f84adc 100755 --- a/examples/dfp/v201705/order_service/approve_orders.py +++ b/examples/dfp/v201711/order_service/approve_orders.py @@ -28,21 +28,14 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') - - # Create query. - values = [{ - 'key': 'today', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S') - } - }] - query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')' - ' AND endDateTime >= :today AND isArchived = FALSE') + order_service = client.GetService('OrderService', version='v201711') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + today = datetime.date.today() + statement = (dfp.StatementBuilder() + .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' + 'AND endDateTime >= :today AND isArchived = FALSE')) + .WithBindVariable('today', today)) orders_approved = 0 # Get orders by statement. diff --git a/examples/dfp/v201705/order_service/create_orders.py b/examples/dfp/v201711/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201705/order_service/create_orders.py rename to examples/dfp/v201711/order_service/create_orders.py index d3a6a4cc..f2b5628f 100755 --- a/examples/dfp/v201705/order_service/create_orders.py +++ b/examples/dfp/v201711/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') + order_service = client.GetService('OrderService', version='v201711') # Create order objects. orders = [] diff --git a/examples/dfp/v201702/order_service/get_all_orders.py b/examples/dfp/v201711/order_service/get_all_orders.py similarity index 99% rename from examples/dfp/v201702/order_service/get_all_orders.py rename to examples/dfp/v201711/order_service/get_all_orders.py index 2c34d9f2..244b582a 100755 --- a/examples/dfp/v201702/order_service/get_all_orders.py +++ b/examples/dfp/v201711/order_service/get_all_orders.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') + order_service = client.GetService('OrderService', version='v201711') # Create a statement to select orders. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/order_service/get_orders_starting_soon.py b/examples/dfp/v201711/order_service/get_orders_starting_soon.py similarity index 73% rename from examples/dfp/v201702/order_service/get_orders_starting_soon.py rename to examples/dfp/v201711/order_service/get_orders_starting_soon.py index b99060c3..af8f7247 100755 --- a/examples/dfp/v201702/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201711/order_service/get_orders_starting_soon.py @@ -21,33 +21,22 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') - query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' - '<= :soon') - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'APPROVED' - }}, - {'key': 'now', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') - }}, - {'key': 'soon', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() + timedelta(days=5)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + order_service = client.GetService('OrderService', version='v201711') + now = datetime.now(tz=pytz.timezone('America/New_York')) + soon = now + timedelta(days=5) + # Create a statement to select orders. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('status = :status AND startDateTime >= :now ' + 'AND startDateTime <= :soon')) + .WithBindVariable('status', 'APPROVED') + .WithBindVariable('now', now) + .WithBindVariable('soon', soon)) # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/dfp/v201705/order_service/update_orders.py b/examples/dfp/v201711/order_service/update_orders.py similarity index 90% rename from examples/dfp/v201705/order_service/update_orders.py rename to examples/dfp/v201711/order_service/update_orders.py index a6a6ab9b..ee06522e 100755 --- a/examples/dfp/v201705/order_service/update_orders.py +++ b/examples/dfp/v201711/order_service/update_orders.py @@ -28,19 +28,13 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') + order_service = client.GetService('OrderService', version='v201711') # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :orderId') + .WithBindVariable('orderId', long(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -69,6 +63,7 @@ def main(client, order_id): else: print 'No orders found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/package_service/create_packages.py b/examples/dfp/v201711/package_service/create_packages.py similarity index 99% rename from examples/dfp/v201702/package_service/create_packages.py rename to examples/dfp/v201711/package_service/create_packages.py index 21dce743..cafb0c42 100755 --- a/examples/dfp/v201702/package_service/create_packages.py +++ b/examples/dfp/v201711/package_service/create_packages.py @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201702') + package_service = client.GetService('PackageService', version='v201711') # Create local package. package = { diff --git a/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py similarity index 99% rename from examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py rename to examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py index c7c4c8d9..4029c889 100755 --- a/examples/dfp/v201705/package_service/create_proposal_line_items_from_packages.py +++ b/examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201705') + package_service = client.GetService('PackageService', version='v201711') # Create a statement to select the single package. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/package_service/get_all_packages.py b/examples/dfp/v201711/package_service/get_all_packages.py similarity index 99% rename from examples/dfp/v201705/package_service/get_all_packages.py rename to examples/dfp/v201711/package_service/get_all_packages.py index e5369e61..a759e6e8 100755 --- a/examples/dfp/v201705/package_service/get_all_packages.py +++ b/examples/dfp/v201711/package_service/get_all_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201705') + pkg_service = client.GetService('PackageService', version='v201711') # Create a statement to select packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/package_service/get_in_progress_packages.py b/examples/dfp/v201711/package_service/get_in_progress_packages.py similarity index 87% rename from examples/dfp/v201705/package_service/get_in_progress_packages.py rename to examples/dfp/v201711/package_service/get_in_progress_packages.py index a22049a9..48ad8b79 100755 --- a/examples/dfp/v201705/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201711/package_service/get_in_progress_packages.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'IN_PROGRESS' - }}, - ] + pkg_service = client.GetService('PackageService', version='v201711') # Create a statement to select packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'IN_PROGRESS')) # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/dfp/v201705/placement_service/create_placements.py b/examples/dfp/v201711/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201705/placement_service/create_placements.py rename to examples/dfp/v201711/placement_service/create_placements.py index 293167ba..d974198e 100755 --- a/examples/dfp/v201705/placement_service/create_placements.py +++ b/examples/dfp/v201711/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') - inventory_service = client.GetService('InventoryService', version='v201705') + placement_service = client.GetService('PlacementService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201711') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201702/placement_service/deactivate_placements.py b/examples/dfp/v201711/placement_service/deactivate_placements.py similarity index 88% rename from examples/dfp/v201702/placement_service/deactivate_placements.py rename to examples/dfp/v201711/placement_service/deactivate_placements.py index a7ef1a57..6d0bc0f8 100755 --- a/examples/dfp/v201702/placement_service/deactivate_placements.py +++ b/examples/dfp/v201711/placement_service/deactivate_placements.py @@ -28,18 +28,13 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') + placement_service = client.GetService('PlacementService', version='v201711') # Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :placementId') + .WithBindVariable('placementId', long(placement_id)) + .Limit(1)) # Get placements by statement. placements = placement_service.getPlacementsByStatement( @@ -60,6 +55,7 @@ def main(client, placement_id): else: print 'No placements were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/placement_service/get_active_placements.py b/examples/dfp/v201711/placement_service/get_active_placements.py similarity index 87% rename from examples/dfp/v201705/placement_service/get_active_placements.py rename to examples/dfp/v201711/placement_service/get_active_placements.py index 3d2b4511..816c1bb3 100755 --- a/examples/dfp/v201705/placement_service/get_active_placements.py +++ b/examples/dfp/v201711/placement_service/get_active_placements.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + placement_service = client.GetService('PlacementService', version='v201711') # Create a statement to select placements. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/dfp/v201702/placement_service/get_all_placements.py b/examples/dfp/v201711/placement_service/get_all_placements.py similarity index 99% rename from examples/dfp/v201702/placement_service/get_all_placements.py rename to examples/dfp/v201711/placement_service/get_all_placements.py index b40c18b9..7fce181e 100755 --- a/examples/dfp/v201702/placement_service/get_all_placements.py +++ b/examples/dfp/v201711/placement_service/get_all_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') + placement_service = client.GetService('PlacementService', version='v201711') # Create a statement to select placements. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/placement_service/update_placements.py b/examples/dfp/v201711/placement_service/update_placements.py similarity index 96% rename from examples/dfp/v201705/placement_service/update_placements.py rename to examples/dfp/v201711/placement_service/update_placements.py index 371f6187..a2663891 100755 --- a/examples/dfp/v201705/placement_service/update_placements.py +++ b/examples/dfp/v201711/placement_service/update_placements.py @@ -28,14 +28,14 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') + placement_service = client.GetService('PlacementService', version='v201711') # Create query. statement = (dfp.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) - .WithBindVariable('id', PLACEMENT_ID)) + .WithBindVariable('id', placement_id)) # Get placements by statement. page = placement_service.getPlacementsByStatement( diff --git a/examples/dfp/v201702/premium_rate_service/__init__.py b/examples/dfp/v201711/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201702/premium_rate_service/__init__.py rename to examples/dfp/v201711/premium_rate_service/__init__.py diff --git a/examples/dfp/v201705/premium_rate_service/create_premium_rates.py b/examples/dfp/v201711/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/dfp/v201705/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201711/premium_rate_service/create_premium_rates.py index fa6b6b19..7d35fa92 100755 --- a/examples/dfp/v201705/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201711/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201705') + version='v201711') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py similarity index 97% rename from examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py index 21c6b3d6..67ae3b82 100755 --- a/examples/dfp/v201705/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201705') + 'PremiumRateService', version='v201711') # Create a statement to select premium rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 87% rename from examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py index 24349a44..efd4e313 100755 --- a/examples/dfp/v201702/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,17 +25,11 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201702') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] + 'PremiumRateService', version='v201711') # Create a statement to select premium rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/dfp/v201705/premium_rate_service/update_premium_rates.py b/examples/dfp/v201711/premium_rate_service/update_premium_rates.py similarity index 90% rename from examples/dfp/v201705/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201711/premium_rate_service/update_premium_rates.py index 6058b78b..9cb338da 100755 --- a/examples/dfp/v201705/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201711/premium_rate_service/update_premium_rates.py @@ -30,18 +30,14 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201705') + version='v201711') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': premium_rate_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(premium_rate_id)) + .Limit(1)) # Get the premium rate. response = premium_rate_service.getPremiumRatesByStatement( diff --git a/examples/dfp/v201705/product_package_item_service/create_product_package_item.py b/examples/dfp/v201711/product_package_item_service/create_product_package_item.py similarity index 99% rename from examples/dfp/v201705/product_package_item_service/create_product_package_item.py rename to examples/dfp/v201711/product_package_item_service/create_product_package_item.py index 9df8892f..be418ec4 100755 --- a/examples/dfp/v201705/product_package_item_service/create_product_package_item.py +++ b/examples/dfp/v201711/product_package_item_service/create_product_package_item.py @@ -32,7 +32,7 @@ def main(client): product_package_item_service = client.GetService('ProductPackageItemService', - version='v201705') + version='v201711') product_package_item = { # Set the product from which the product package item is created. diff --git a/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py similarity index 97% rename from examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py rename to examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py index 536f23bb..6cabd514 100755 --- a/examples/dfp/v201705/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201705') + 'ProductPackageItemService', version='v201711') # Create a statement to select product package items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py similarity index 86% rename from examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py index 439d98c4..b7d4900f 100755 --- a/examples/dfp/v201702/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,17 +25,11 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201702') - query = 'WHERE productPackageId = :productPackageId' - values = [ - {'key': 'productPackageId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_package_id - }}, - ] + 'ProductPackageItemService', version='v201711') # Create a statement to select product package items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productPackageId = :productPackageId') + .WithBindVariable('productPackageId', product_package_id)) # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/dfp/v201705/product_package_service/create_product_packages.py b/examples/dfp/v201711/product_package_service/create_product_packages.py similarity index 96% rename from examples/dfp/v201705/product_package_service/create_product_packages.py rename to examples/dfp/v201711/product_package_service/create_product_packages.py index 5c8f128c..049ff271 100755 --- a/examples/dfp/v201705/product_package_service/create_product_packages.py +++ b/examples/dfp/v201711/product_package_service/create_product_packages.py @@ -30,7 +30,7 @@ def main(client): product_package_service = client.GetService('ProductPackageService', - version='v201705') + version='v201711') # Create a local product package. product_package = { diff --git a/examples/dfp/v201705/product_package_service/get_active_product_packages.py b/examples/dfp/v201711/product_package_service/get_active_product_packages.py similarity index 86% rename from examples/dfp/v201705/product_package_service/get_active_product_packages.py rename to examples/dfp/v201711/product_package_service/get_active_product_packages.py index a08b4733..b747a2a0 100755 --- a/examples/dfp/v201705/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201711/product_package_service/get_active_product_packages.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'ProductPackageService', version='v201711') # Create a statement to select product packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/dfp/v201702/product_package_service/get_all_product_packages.py b/examples/dfp/v201711/product_package_service/get_all_product_packages.py similarity index 97% rename from examples/dfp/v201702/product_package_service/get_all_product_packages.py rename to examples/dfp/v201711/product_package_service/get_all_product_packages.py index 910cc35a..c1d566cb 100755 --- a/examples/dfp/v201702/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201711/product_package_service/get_all_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201702') + 'ProductPackageService', version='v201711') # Create a statement to select product packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/product_service/__init__.py b/examples/dfp/v201711/product_service/__init__.py similarity index 100% rename from examples/dfp/v201702/product_service/__init__.py rename to examples/dfp/v201711/product_service/__init__.py diff --git a/examples/dfp/v201702/product_service/get_all_products.py b/examples/dfp/v201711/product_service/get_all_products.py similarity index 99% rename from examples/dfp/v201702/product_service/get_all_products.py rename to examples/dfp/v201711/product_service/get_all_products.py index 8dd669b5..5b88012d 100755 --- a/examples/dfp/v201702/product_service/get_all_products.py +++ b/examples/dfp/v201711/product_service/get_all_products.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201702') + product_service = client.GetService('ProductService', version='v201711') # Create a statement to select products. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/product_service/get_products_for_product_template.py b/examples/dfp/v201711/product_service/get_products_for_product_template.py similarity index 86% rename from examples/dfp/v201702/product_service/get_products_for_product_template.py rename to examples/dfp/v201711/product_service/get_products_for_product_template.py index 367db302..42ef9bdf 100755 --- a/examples/dfp/v201702/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201711/product_service/get_products_for_product_template.py @@ -24,18 +24,12 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201702') - - query = 'WHERE productTemplateId = :productTemplateId' - values = [ - {'key': 'productTemplateId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_template_id - }}, - ] + product_service = client.GetService('ProductService', version='v201711') + # Create a statement to select products. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productTemplateId = :productTemplateId') + .WithBindVariable('productTemplateId', product_template_id)) # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/dfp/v201705/product_service/update_products.py b/examples/dfp/v201711/product_service/update_products.py similarity index 90% rename from examples/dfp/v201705/product_service/update_products.py rename to examples/dfp/v201711/product_service/update_products.py index af2905db..b1d37737 100755 --- a/examples/dfp/v201705/product_service/update_products.py +++ b/examples/dfp/v201711/product_service/update_products.py @@ -29,18 +29,13 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201705') + product_service = client.GetService('ProductService', version='v201711') # Create statement object to select a single product by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, product_id): else: print 'No products found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/product_template_service/__init__.py b/examples/dfp/v201711/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201702/product_template_service/__init__.py rename to examples/dfp/v201711/product_template_service/__init__.py diff --git a/examples/dfp/v201705/product_template_service/activate_product_templates.py b/examples/dfp/v201711/product_template_service/activate_product_templates.py similarity index 89% rename from examples/dfp/v201705/product_template_service/activate_product_templates.py rename to examples/dfp/v201711/product_template_service/activate_product_templates.py index a15d5102..87bae3ca 100755 --- a/examples/dfp/v201705/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201711/product_template_service/activate_product_templates.py @@ -31,18 +31,13 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201711') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) product_templates_activated = 0 diff --git a/examples/dfp/v201705/product_template_service/create_product_templates.py b/examples/dfp/v201711/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201705/product_template_service/create_product_templates.py rename to examples/dfp/v201711/product_template_service/create_product_templates.py index 94f5a3d3..2f7c2afb 100755 --- a/examples/dfp/v201705/product_template_service/create_product_templates.py +++ b/examples/dfp/v201711/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201711') network_service = client.GetService( - 'NetworkService', version='v201705') + 'NetworkService', version='v201711') # Create a product template. product_template = { diff --git a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py similarity index 96% rename from examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py rename to examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py index 0ef99cf9..f7cc4b99 100755 --- a/examples/dfp/v201702/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201711') network_service = client.GetService( - 'NetworkService', version='v201702') + 'NetworkService', version='v201711') product_template = { # Setting required Marketplace information. diff --git a/examples/dfp/v201702/product_template_service/get_all_product_templates.py b/examples/dfp/v201711/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201702/product_template_service/get_all_product_templates.py rename to examples/dfp/v201711/product_template_service/get_all_product_templates.py index 4f79ceb9..4d7f7680 100755 --- a/examples/dfp/v201702/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201711/product_template_service/get_all_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201711') # Create a statement to select product templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py similarity index 85% rename from examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py index 44b3b3a1..9a6c9fc2 100755 --- a/examples/dfp/v201702/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') - query = 'WHERE lineItemType = :lineItemType' - values = [ - {'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - }}, - ] + 'ProductTemplateService', version='v201711') # Create a statement to select product templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemType = :lineItemType') + .WithBindVariable('lineItemType', 'SPONSORSHIP')) # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/dfp/v201705/product_template_service/update_product_templates.py b/examples/dfp/v201711/product_template_service/update_product_templates.py similarity index 90% rename from examples/dfp/v201705/product_template_service/update_product_templates.py rename to examples/dfp/v201711/product_template_service/update_product_templates.py index 8116f7f3..40bc6c41 100755 --- a/examples/dfp/v201705/product_template_service/update_product_templates.py +++ b/examples/dfp/v201711/product_template_service/update_product_templates.py @@ -30,18 +30,14 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201711') # Create a statement to select a single product template by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) # Get product templates by statement. response = product_template_service.getProductTemplatesByStatement( diff --git a/examples/dfp/v201702/proposal_line_item_service/__init__.py b/examples/dfp/v201711/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201702/proposal_line_item_service/__init__.py rename to examples/dfp/v201711/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py similarity index 89% rename from examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py index b2b6c76c..3001c92c 100755 --- a/examples/dfp/v201705/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py @@ -31,18 +31,13 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') + 'ProposalLineItemService', version='v201711') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) proposal_line_items_archived = 0 diff --git a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 98% rename from examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py index e9e2ab71..1654e9aa 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -40,8 +40,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + 'ProposalLineItemService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') # Get the root ad unit to target. root_ad_unit_id = ( diff --git a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 98% rename from examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index bb198790..0f204be9 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -34,8 +34,8 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + 'ProposalLineItemService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py index 616195f3..972bb150 100755 --- a/examples/dfp/v201705/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py @@ -42,8 +42,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + 'ProposalLineItemService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py similarity index 97% rename from examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py index 17ee0df9..9fb0218c 100755 --- a/examples/dfp/v201702/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') + 'ProposalLineItemService', version='v201711') # Create a statement to select proposal line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 86% rename from examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py index f0224ecf..a82722d8 100755 --- a/examples/dfp/v201702/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,17 +25,11 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') - query = 'WHERE proposalId = :proposalId' - values = [ - {'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - }}, - ] + 'ProposalLineItemService', version='v201711') # Create a statement to select proposal line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('proposalId = :proposalId') + .WithBindVariable('proposalId', proposal_id)) # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py similarity index 89% rename from examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py index 64648a05..930fd72e 100755 --- a/examples/dfp/v201702/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py @@ -31,19 +31,14 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') + 'ProposalLineItemService', version='v201711') # Create statement to select a proposal line item. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) # Get proposal line items by statement. response = proposal_line_item_service.getProposalLineItemsByStatement( diff --git a/examples/dfp/v201702/proposal_service/__init__.py b/examples/dfp/v201711/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201702/proposal_service/__init__.py rename to examples/dfp/v201711/proposal_service/__init__.py diff --git a/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201711/proposal_service/create_programmatic_proposals.py similarity index 98% rename from examples/dfp/v201705/proposal_service/create_programmatic_proposals.py rename to examples/dfp/v201711/proposal_service/create_programmatic_proposals.py index 02277928..861f71b0 100755 --- a/examples/dfp/v201705/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201711/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 99% rename from examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 2173f106..fdef1830 100755 --- a/examples/dfp/v201702/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201702/proposal_service/create_proposals.py b/examples/dfp/v201711/proposal_service/create_proposals.py similarity index 99% rename from examples/dfp/v201702/proposal_service/create_proposals.py rename to examples/dfp/v201711/proposal_service/create_proposals.py index c8b43bcf..0a800e90 100755 --- a/examples/dfp/v201702/proposal_service/create_proposals.py +++ b/examples/dfp/v201711/proposal_service/create_proposals.py @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') + network_service = client.GetService('NetworkService', version='v201711') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201705/proposal_service/get_all_proposals.py b/examples/dfp/v201711/proposal_service/get_all_proposals.py similarity index 99% rename from examples/dfp/v201705/proposal_service/get_all_proposals.py rename to examples/dfp/v201711/proposal_service/get_all_proposals.py index 57258dca..10699516 100755 --- a/examples/dfp/v201705/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201711/proposal_service/get_all_proposals.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201711') # Create a statement to select proposals. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py b/examples/dfp/v201711/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/dfp/v201702/proposal_service/get_marketplace_comments.py rename to examples/dfp/v201711/proposal_service/get_marketplace_comments.py index b5d81c05..08ae7a05 100755 --- a/examples/dfp/v201702/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201711/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201702') + 'ProposalService', version='v201711') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py similarity index 87% rename from examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py rename to examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py index 33041f4a..dcf4fca4 100755 --- a/examples/dfp/v201702/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - }}, - ] + proposal_service = client.GetService('ProposalService', version='v201711') # Create a statement to select proposals. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'PENDING_APPROVAL')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py similarity index 89% rename from examples/dfp/v201705/proposal_service/request_buyers_acceptance.py rename to examples/dfp/v201711/proposal_service/request_buyers_acceptance.py index 68e3598e..502d591a 100755 --- a/examples/dfp/v201705/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py @@ -26,20 +26,12 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201711') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo programmatic proposals were pushed to Marketplace.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py similarity index 88% rename from examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py index 51f8b2b2..ecb8c5d1 100755 --- a/examples/dfp/v201705/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py @@ -28,20 +28,12 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201711') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo proposals were approved.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/proposal_service/update_proposals.py b/examples/dfp/v201711/proposal_service/update_proposals.py similarity index 89% rename from examples/dfp/v201702/proposal_service/update_proposals.py rename to examples/dfp/v201711/proposal_service/update_proposals.py index 41020d8d..29339cca 100755 --- a/examples/dfp/v201702/proposal_service/update_proposals.py +++ b/examples/dfp/v201711/proposal_service/update_proposals.py @@ -28,19 +28,14 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201711') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', long(proposal_id)) + .Limit(1)) # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, proposal_id): else: print 'No proposals found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/publisher_query_language_service/__init__.py b/examples/dfp/v201711/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201702/publisher_query_language_service/__init__.py rename to examples/dfp/v201711/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py index f6b3d558..6f4c30fa 100755 --- a/examples/dfp/v201705/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201711') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py b/examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py new file mode 100755 index 00000000..9c715c66 --- /dev/null +++ b/examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 browsers available to target from the Browser table. + +Other tables include 'Bandwidth_Group', 'Browser_Language', +'Device_Capability', 'Operating_System', etc... + +A full list of available criteria tables can be found at +https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService +""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201711') + + with tempfile.NamedTemporaryFile( + prefix='browser_data_', + suffix='.csv', mode='w', delete=False) as browser_data_file: + + browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion ' + 'FROM Browser ' + 'ORDER BY BrowserName ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + browser_pql_query, browser_data_file) + + print 'Saved browser data to... %s' % browser_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py index cdda977e..1373e34c 100755 --- a/examples/dfp/v201705/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201705') + data_downloader = client.GetDataDownloader(version='v201711') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py new file mode 100755 index 00000000..ee80ecce --- /dev/null +++ b/examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 downloads geo targeting constants using PQL.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the type of geo target to query for. +GEO_TARGET_TYPE = 'City' + + +def main(client, geo_target_type): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201711') + + with tempfile.NamedTemporaryFile( + prefix='geo_data_', + suffix='.csv', mode='w', delete=False) as geo_data_file: + + geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' + 'CountryCode ' + 'FROM Geo_Target ' + 'WHERE Type = :type AND Targetable = true ' + 'ORDER BY CountryCode ASC, Name ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + geo_pql_query, geo_data_file, {'type': geo_target_type}) + + print 'Saved geo data to... %s' % geo_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, GEO_TARGET_TYPE) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py new file mode 100755 index 00000000..baba6a1d --- /dev/null +++ b/examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 fetches line items from the pql table with a LIKE clause.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201711') + + with tempfile.NamedTemporaryFile( + prefix='line_items_', + suffix='.csv', mode='w', delete=False) as line_items_file: + + line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item " + "WHERE Name LIKE 'line item%' " + "ORDER BY Id ASC") + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + line_items_pql_query, line_items_file) + + print 'Saved line items to... %s' % line_items_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py similarity index 66% rename from examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py rename to examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py index 76c9f061..41eb34c6 100755 --- a/examples/dfp/v201702/publisher_query_language_service/get_recent_changes.py +++ b/examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py @@ -31,52 +31,23 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201702') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201711') - end_date = date.today() + end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) - initial_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE ChangeDateTime > :startDateTime ' - 'AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - pagination_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE Id < :id ' - 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - values = [ - { - 'key': 'startDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day - } - } - } - }, - { - 'key': 'endDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day - } - } - } - } - ] - - statement = dfp.FilterStatement(initial_query, values) + initial_query = ('ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime') + pagination_query = 'Id < :id AND ' + initial_query + + statement = (dfp.StatementBuilder() + .Select(('Id, ChangeDateTime, EntityId, EntityType, ' + 'Operation, UserId')) + .From('Change_History') + .Where(initial_query) + .OrderBy('ChangeDateTime', ascending=False) + .WithBindVariable('startDateTime', start_date) + .WithBindVariable('endDateTime', end_date)) + keep_iterating = True i = 0 total_rows = [] @@ -94,8 +65,11 @@ def main(client): last_row = rows[-1] last_id = last_row['values'][0]['value'] i += 1 - statement = UpdateFilterStatement( - statement, pagination_query, values, last_id) + + # Update the statement using the earliest row in the previous result. + statement.Where(pagination_query) + statement.WithBindVariable('id', last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' % (i, rows_length, last_id)) @@ -109,34 +83,6 @@ def main(client): print ConvertValueForCsv(row) -def UpdateFilterStatement(statement, query, values, last_id): - """Updates the FilterStatement in order to page through results. - - Args: - statement: an instantiated FilterStatement. - query: a str query that will be used to update the FilterStatement. - values: a list of bind variables to be updated. - last_id: a str representing the earliest change ID in a result set. - - Returns: - FilterStatement the updated statement. - """ - # Use the earliest change ID in the result set to page. - updated_values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_id - } - }] - updated_values.extend(values) - - statement.where_clause = query - statement.values = updated_values - - return statement - - def ConvertValueForCsv(pql_value): """Sanitizes a field value from a Value object to a CSV suitable format. diff --git a/examples/dfp/v201702/rate_card_service/__init__.py b/examples/dfp/v201711/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201702/rate_card_service/__init__.py rename to examples/dfp/v201711/rate_card_service/__init__.py diff --git a/examples/dfp/v201702/rate_card_service/create_rate_cards.py b/examples/dfp/v201711/rate_card_service/create_rate_cards.py similarity index 99% rename from examples/dfp/v201702/rate_card_service/create_rate_cards.py rename to examples/dfp/v201711/rate_card_service/create_rate_cards.py index e75ee8bd..d7acfcf9 100755 --- a/examples/dfp/v201702/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201711/rate_card_service/create_rate_cards.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201702') + rate_card_service = client.GetService('RateCardService', version='v201711') # Create a rate card. rate_card = { diff --git a/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py similarity index 99% rename from examples/dfp/v201705/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201711/rate_card_service/get_all_rate_cards.py index 73469628..2c0d78e4 100755 --- a/examples/dfp/v201705/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201705') + rate_card_service = client.GetService('RateCardService', version='v201711') # Create a statement to select rate cards. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py similarity index 87% rename from examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py rename to examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py index 232f0fd7..c3c213bb 100755 --- a/examples/dfp/v201705/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201705') - query = 'WHERE forMarketplace = :forMarketplace' - values = [ - {'key': 'forMarketplace', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + rate_card_service = client.GetService('RateCardService', version='v201711') # Create a statement to select rate cards. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('forMarketplace = :forMarketplace') + .WithBindVariable('forMarketplace', True)) # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 97% rename from examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index ad0ccee4..d669cb83 100755 --- a/examples/dfp/v201702/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201702')) + 'ReconciliationLineItemReportService', version='v201711')) # Create a statement to select reconciliation line item reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 97% rename from examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 1f9b1e48..bdd94b5a 100755 --- a/examples/dfp/v201702/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201702')) + 'ReconciliationLineItemReportService', version='v201711')) # Create a statement to select a reconciliation line item report. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index e9ce5265..7e298979 100755 --- a/examples/dfp/v201705/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,17 +25,12 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201705') - query = 'WHERE reconciliationReportId = :reconciliationReportId' - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - ] + 'ReconciliationOrderReportService', version='v201711') # Create a statement to select reconciliation order reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('reconciliationReportId = :reconciliationReportId') + .WithBindVariable('reconciliationReportId', + reconciliation_report_id)) # Retrieve a small amount of reconciliation order reports at a time, paging # through until all reconciliation order reports have been retrieved. diff --git a/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 97% rename from examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 35d94c91..4e3b4a82 100755 --- a/examples/dfp/v201702/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201702')) + 'ReconciliationOrderReportService', version='v201711')) # Create a statement to select reconciliation order reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 21daadd3..9b414ea1 100755 --- a/examples/dfp/v201702/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -27,18 +27,14 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201702') - query = ('WHERE reconciliationReportId = %s AND ' - 'lineItemId != :lineItemId') % reconciliation_report_id - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - } - }] + 'ReconciliationReportRowService', version='v201711') + # Create a statement to select reconciliation report rows. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reportId ' + 'AND lineItemId != :lineItemId')) + .WithBindVariable('lineItemId', 0) + .WithBindVariable('reportId', long(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. diff --git a/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 97% rename from examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py index fff5f766..99b28783 100755 --- a/examples/dfp/v201702/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201702')) + 'ReconciliationReportRowService', version='v201711')) # Create a statement to select reconciliation report rows. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 97% rename from examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py index 54fdc3a0..15825fe0 100755 --- a/examples/dfp/v201705/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201705') + 'ReconciliationReportService', version='v201711') # Create a statement to select reconciliation reports. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 97% rename from examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 7f8536cd..c391ab1b 100755 --- a/examples/dfp/v201705/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201705') + 'ReconciliationReportService', version='v201711') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) diff --git a/examples/dfp/v201702/report_service/__init__.py b/examples/dfp/v201711/report_service/__init__.py similarity index 100% rename from examples/dfp/v201702/report_service/__init__.py rename to examples/dfp/v201711/report_service/__init__.py diff --git a/examples/dfp/v201705/report_service/run_delivery_report.py b/examples/dfp/v201711/report_service/run_delivery_report.py similarity index 88% rename from examples/dfp/v201705/report_service/run_delivery_report.py rename to examples/dfp/v201711/report_service/run_delivery_report.py index 055969a3..3bbc7c8f 100755 --- a/examples/dfp/v201705/report_service/run_delivery_report.py +++ b/examples/dfp/v201711/report_service/run_delivery_report.py @@ -32,15 +32,11 @@ def main(client, order_id): # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - filter_statement = {'query': 'WHERE ORDER_ID = :id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('ORDER_ID = :id') + .WithBindVariable('id', long(order_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Set the start and end dates of the report to run (past 8 days). end_date = datetime.now().date() @@ -52,7 +48,7 @@ def main(client, order_id): 'dimensions': ['ORDER_ID', 'ORDER_NAME'], 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', 'ORDER_END_DATE_TIME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], @@ -63,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201711') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201705/report_service/run_inventory_report.py b/examples/dfp/v201711/report_service/run_inventory_report.py similarity index 83% rename from examples/dfp/v201705/report_service/run_inventory_report.py rename to examples/dfp/v201711/report_service/run_inventory_report.py index 3e07905a..a7abcb2e 100755 --- a/examples/dfp/v201705/report_service/run_inventory_report.py +++ b/examples/dfp/v201711/report_service/run_inventory_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report equal to the "Whole network report" on the DFP website.""" +"""This example runs a typical daily inventory report.""" import tempfile @@ -25,24 +25,20 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201705') + network_service = client.GetService('NetworkService', version='v201711') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201711') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - values = [{ - 'key': 'parent_ad_unit_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': root_ad_unit_id - } - }] - filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') + .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Create report job. report_job = { @@ -55,7 +51,7 @@ def main(client): 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', - 'statement': filter_statement + 'statement': statement.ToStatement() } } diff --git a/examples/dfp/v201705/report_service/run_reach_report.py b/examples/dfp/v201711/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201705/report_service/run_reach_report.py rename to examples/dfp/v201711/report_service/run_reach_report.py index ffd4f971..53b8ab8f 100755 --- a/examples/dfp/v201705/report_service/run_reach_report.py +++ b/examples/dfp/v201711/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201711') # Create report job. report_job = { diff --git a/examples/dfp/v201711/report_service/run_report_and_create_match_table.py b/examples/dfp/v201711/report_service/run_report_and_create_match_table.py new file mode 100755 index 00000000..777304d0 --- /dev/null +++ b/examples/dfp/v201711/report_service/run_report_and_create_match_table.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Runs a report for LineItems with additional data from a PQL table. + +Fetches a basic report over a network's LineItems and then adds some +extra columns which might be useful for future analysis, such as +LineItemType, from the PQL Line_Item table, creating a match table. +""" + +from datetime import date +from datetime import timedelta +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + +try: + import pandas +except ImportError: + raise ImportError('This example requires the pandas library to be installed.') + + +def main(client): + # Set the start and end dates of the report to run (past 8 days). + end_date = date.today() + start_date = end_date - timedelta(days=8) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': start_date, + 'endDate': end_date + } + } + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201711') + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + with tempfile.NamedTemporaryFile( + suffix='.csv.gz', mode='wb', delete=False) as report_file: + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, 'CSV_DUMP', report_file) + + # Create a PQL query to fetch the line item data + line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem') + + # Download the response from PQL select statement + line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) + + # Use pandas to join the two csv files into a match table + report = pandas.read_csv(report_file.name) + line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0]) + merged_result = pandas.merge(report, line_items, + left_on='Dimension.LINE_ITEM_ID', right_on='id') + merged_result.to_csv('~/complete_line_items_report.csv', index=False) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/report_service/run_report_with_custom_fields.py b/examples/dfp/v201711/report_service/run_report_with_custom_fields.py similarity index 85% rename from examples/dfp/v201705/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201711/report_service/run_report_with_custom_fields.py index 20f080f5..c302079c 100755 --- a/examples/dfp/v201705/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201711/report_service/run_report_with_custom_fields.py @@ -28,22 +28,14 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201711') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201711') # Filter for line items of a given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE orderId = :orderId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId') + .WithBindVariable('orderId', long(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -62,14 +54,16 @@ def main(client, order_id): else: break - # Create statement object to filter for an order. - filter_statement = {'query': query, 'values': values} + # Modify statement for reports + statement.limit = None + statement.offset = None + statement.Where('ORDER_ID = :orderId') # Create report job. report_job = { 'reportQuery': { 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', 'customFieldIds': list(custom_field_ids) diff --git a/examples/dfp/v201705/report_service/run_sales_report.py b/examples/dfp/v201711/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201705/report_service/run_sales_report.py rename to examples/dfp/v201711/report_service/run_sales_report.py index cf7d623b..e5b5663d 100755 --- a/examples/dfp/v201705/report_service/run_sales_report.py +++ b/examples/dfp/v201711/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201711') # Create report job. report_job = { diff --git a/examples/dfp/v201705/report_service/run_saved_query.py b/examples/dfp/v201711/report_service/run_saved_query.py similarity index 89% rename from examples/dfp/v201705/report_service/run_saved_query.py rename to examples/dfp/v201711/report_service/run_saved_query.py index 7a8fdd94..16ce73f3 100755 --- a/examples/dfp/v201705/report_service/run_saved_query.py +++ b/examples/dfp/v201711/report_service/run_saved_query.py @@ -28,21 +28,16 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201705') + report_service = client.GetService('ReportService', version='v201711') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201705') + report_downloader = client.GetDataDownloader(version='v201711') # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': saved_query_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(saved_query_id)) + .Limit(1)) response = report_service.getSavedQueriesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201702/suggested_ad_unit_service/__init__.py b/examples/dfp/v201711/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201702/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201711/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 0a2bd663..9babe2de 100755 --- a/examples/dfp/v201705/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201705') + 'SuggestedAdUnitService', version='v201711') values = [{ 'key': 'numRequests', diff --git a/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py index 39046b06..eecffd62 100755 --- a/examples/dfp/v201705/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201705') + 'SuggestedAdUnitService', version='v201711') # Create a statement to select suggested ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 86% rename from examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index de26bdf9..175f870c 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,17 +25,11 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201702') - query = 'WHERE numRequests >= :numRequests' - values = [ - {'key': 'numRequests', - 'value': { - 'xsi_type': 'TextValue', - 'value': num_requests - }}, - ] + 'SuggestedAdUnitService', version='v201711') # Create a statement to select suggested ad units. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests >= :numRequests') + .WithBindVariable('numRequests', long(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/dfp/v201702/team_service/__init__.py b/examples/dfp/v201711/team_service/__init__.py similarity index 100% rename from examples/dfp/v201702/team_service/__init__.py rename to examples/dfp/v201711/team_service/__init__.py diff --git a/examples/dfp/v201705/team_service/create_teams.py b/examples/dfp/v201711/team_service/create_teams.py similarity index 99% rename from examples/dfp/v201705/team_service/create_teams.py rename to examples/dfp/v201711/team_service/create_teams.py index 05b40daf..df551d17 100755 --- a/examples/dfp/v201705/team_service/create_teams.py +++ b/examples/dfp/v201711/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201705') + team_service = client.GetService('TeamService', version='v201711') # Create team objects. teams = [] diff --git a/examples/dfp/v201705/team_service/get_all_teams.py b/examples/dfp/v201711/team_service/get_all_teams.py similarity index 99% rename from examples/dfp/v201705/team_service/get_all_teams.py rename to examples/dfp/v201711/team_service/get_all_teams.py index 1b5b9364..8a639323 100755 --- a/examples/dfp/v201705/team_service/get_all_teams.py +++ b/examples/dfp/v201711/team_service/get_all_teams.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201705') + team_service = client.GetService('TeamService', version='v201711') # Create a statement to select teams. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/team_service/update_teams.py b/examples/dfp/v201711/team_service/update_teams.py similarity index 90% rename from examples/dfp/v201702/team_service/update_teams.py rename to examples/dfp/v201711/team_service/update_teams.py index 7a3b8a94..2f10953a 100755 --- a/examples/dfp/v201702/team_service/update_teams.py +++ b/examples/dfp/v201711/team_service/update_teams.py @@ -34,18 +34,12 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201702') + team_service = client.GetService('TeamService', version='v201711') # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :teamId') + .WithBindVariable('teamId', long(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -67,6 +61,7 @@ def main(client, team_id): else: print 'No teams found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_service/__init__.py b/examples/dfp/v201711/user_service/__init__.py similarity index 100% rename from examples/dfp/v201702/user_service/__init__.py rename to examples/dfp/v201711/user_service/__init__.py diff --git a/examples/dfp/v201705/user_service/create_users.py b/examples/dfp/v201711/user_service/create_users.py similarity index 99% rename from examples/dfp/v201705/user_service/create_users.py rename to examples/dfp/v201711/user_service/create_users.py index dd1043b3..cbdf701b 100755 --- a/examples/dfp/v201705/user_service/create_users.py +++ b/examples/dfp/v201711/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201711') # Create user objects. users = [ diff --git a/examples/dfp/v201702/user_service/deactivate_users.py b/examples/dfp/v201711/user_service/deactivate_users.py similarity index 89% rename from examples/dfp/v201702/user_service/deactivate_users.py rename to examples/dfp/v201711/user_service/deactivate_users.py index 16c07b35..60cabd9a 100755 --- a/examples/dfp/v201702/user_service/deactivate_users.py +++ b/examples/dfp/v201711/user_service/deactivate_users.py @@ -30,20 +30,12 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201711') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -66,6 +58,7 @@ def main(client, user_id): else: print 'No users were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_service/get_all_roles.py b/examples/dfp/v201711/user_service/get_all_roles.py similarity index 100% rename from examples/dfp/v201702/user_service/get_all_roles.py rename to examples/dfp/v201711/user_service/get_all_roles.py diff --git a/examples/dfp/v201705/user_service/get_all_users.py b/examples/dfp/v201711/user_service/get_all_users.py similarity index 99% rename from examples/dfp/v201705/user_service/get_all_users.py rename to examples/dfp/v201711/user_service/get_all_users.py index 54d5bac9..0c57a8d7 100755 --- a/examples/dfp/v201705/user_service/get_all_users.py +++ b/examples/dfp/v201711/user_service/get_all_users.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201711') # Create a statement to select users. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/user_service/get_current_user.py b/examples/dfp/v201711/user_service/get_current_user.py similarity index 99% rename from examples/dfp/v201702/user_service/get_current_user.py rename to examples/dfp/v201711/user_service/get_current_user.py index 56e5931b..c1f43169 100755 --- a/examples/dfp/v201702/user_service/get_current_user.py +++ b/examples/dfp/v201711/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201711') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201705/user_service/get_user_by_email_address.py b/examples/dfp/v201711/user_service/get_user_by_email_address.py similarity index 88% rename from examples/dfp/v201705/user_service/get_user_by_email_address.py rename to examples/dfp/v201711/user_service/get_user_by_email_address.py index 72a800b8..2d3ed8c8 100755 --- a/examples/dfp/v201705/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201711/user_service/get_user_by_email_address.py @@ -24,17 +24,11 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') - query = 'WHERE email = :email' - values = [ - {'key': 'email', - 'value': { - 'xsi_type': 'TextValue', - 'value': email_address - }}, - ] + user_service = client.GetService('UserService', version='v201711') # Create a statement to select users. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('email = :email') + .WithBindVariable('email', email_address)) # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/dfp/v201705/user_service/update_users.py b/examples/dfp/v201711/user_service/update_users.py similarity index 86% rename from examples/dfp/v201705/user_service/update_users.py rename to examples/dfp/v201711/user_service/update_users.py index e072358e..70a566c0 100755 --- a/examples/dfp/v201705/user_service/update_users.py +++ b/examples/dfp/v201711/user_service/update_users.py @@ -28,20 +28,12 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201711') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -59,6 +51,7 @@ def main(client, user_id): else: print 'No users found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_team_association_service/__init__.py b/examples/dfp/v201711/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201702/user_team_association_service/__init__.py rename to examples/dfp/v201711/user_team_association_service/__init__.py diff --git a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201702/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201711/user_team_association_service/create_user_team_associations.py index c882a441..5a8ee9cd 100755 --- a/examples/dfp/v201702/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') + 'UserTeamAssociationService', version='v201711') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py similarity index 87% rename from examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py index d00f760d..b0dd9259 100755 --- a/examples/dfp/v201705/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py @@ -35,20 +35,12 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') + 'UserTeamAssociationService', version='v201711') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -62,10 +54,14 @@ def main(client, user_id): print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) + # Action doesn't require limit/offset + statement.limit = None + statement.offset = None + # Perform action. result = user_team_association_service.performUserTeamAssociationAction( {'xsi_type': 'DeleteUserTeamAssociations'}, - {'query': query, 'values': values}) + statement.ToStatement()) # Display results. if result and int(result['numChanges']) > 0: @@ -74,6 +70,7 @@ def main(client, user_id): else: print 'No user team associations were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py similarity index 97% rename from examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py index 4daad809..14783340 100755 --- a/examples/dfp/v201705/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') + 'UserTeamAssociationService', version='v201711') # Create a statement to select user team associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py similarity index 87% rename from examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py index 1af444b9..c09c240c 100755 --- a/examples/dfp/v201702/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py @@ -25,17 +25,11 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') - query = 'WHERE userId = :userId' - values = [ - {'key': 'userId', - 'value': { - 'xsi_type': 'TextValue', - 'value': user_id - }}, - ] + 'UserTeamAssociationService', version='v201711') # Create a statement to select user team associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py similarity index 89% rename from examples/dfp/v201702/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201711/user_team_association_service/update_user_team_associations.py index 2b227542..43bc0e8d 100755 --- a/examples/dfp/v201702/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py @@ -37,20 +37,12 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') + 'UserTeamAssociationService', version='v201711') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -79,6 +71,7 @@ def main(client, user_id): else: print 'No user team associations found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/workflow_request_service/__init__.py b/examples/dfp/v201711/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201702/workflow_request_service/__init__.py rename to examples/dfp/v201711/workflow_request_service/__init__.py diff --git a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py similarity index 76% rename from examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py index f6a87a54..0b176750 100755 --- a/examples/dfp/v201702/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py @@ -31,37 +31,15 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201702') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') + version='v201711') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) workflow_approval_requests_approved = 0 # Get workflow approval requests by statement. diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py similarity index 87% rename from examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py rename to examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py index 5894de86..5485408c 100755 --- a/examples/dfp/v201702/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py @@ -26,17 +26,11 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - }}, - ] + 'WorkflowRequestService', version='v201711') # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py similarity index 86% rename from examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py index 162b64ff..f098692f 100755 --- a/examples/dfp/v201702/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,17 +26,11 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - }}, - ] + 'WorkflowRequestService', version='v201711') # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 78% rename from examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py index d966ae68..35624bcf 100755 --- a/examples/dfp/v201705/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,37 +31,15 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201705') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') + version='v201711') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) workflow_external_condition_requests_triggered = 0 # Get workflow external condition requests by statement. diff --git a/examples/dfp/v201705/activity_group_service/__init__.py b/examples/dfp/v201802/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201705/activity_group_service/__init__.py rename to examples/dfp/v201802/activity_group_service/__init__.py diff --git a/examples/dfp/v201705/activity_group_service/create_activity_groups.py b/examples/dfp/v201802/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201705/activity_group_service/create_activity_groups.py rename to examples/dfp/v201802/activity_group_service/create_activity_groups.py index f1a8769e..0ab733fb 100755 --- a/examples/dfp/v201705/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201705') + version='v201802') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201705/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py similarity index 86% rename from examples/dfp/v201705/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201802/activity_group_service/get_active_activity_groups.py index 945ac5dd..c4e09074 100755 --- a/examples/dfp/v201705/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'ActivityGroupService', version='v201802') # Create a statement to select activity groups. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py similarity index 97% rename from examples/dfp/v201705/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201802/activity_group_service/get_all_activity_groups.py index cc7eaf66..dd9a08e4 100755 --- a/examples/dfp/v201705/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201705') + 'ActivityGroupService', version='v201802') # Create a statement to select activity groups. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/activity_group_service/update_activity_groups.py b/examples/dfp/v201802/activity_group_service/update_activity_groups.py similarity index 87% rename from examples/dfp/v201702/activity_group_service/update_activity_groups.py rename to examples/dfp/v201802/activity_group_service/update_activity_groups.py index d3724557..c25929a7 100755 --- a/examples/dfp/v201702/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/update_activity_groups.py @@ -37,20 +37,13 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201702') + version='v201802') # Create statement object to select a single activity groups by ID. - values = [{ - 'key': 'activityGroupId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_group_id - } - }] - query = 'WHERE id = :activityGroupId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityGroupId') + .WithBindVariable('activityGroupId', long(activity_group_id)) + .Limit(1)) # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( @@ -70,6 +63,7 @@ def main(client, activity_group_id, advertiser_company_id): else: print 'No activity groups found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/activity_service/__init__.py b/examples/dfp/v201802/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201705/activity_service/__init__.py rename to examples/dfp/v201802/activity_service/__init__.py diff --git a/examples/dfp/v201702/activity_service/create_activities.py b/examples/dfp/v201802/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201702/activity_service/create_activities.py rename to examples/dfp/v201802/activity_service/create_activities.py index 62bc032f..2277e7d3 100755 --- a/examples/dfp/v201702/activity_service/create_activities.py +++ b/examples/dfp/v201802/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201702') + activity_service = client.GetService('ActivityService', version='v201802') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201702/activity_service/get_active_activities.py b/examples/dfp/v201802/activity_service/get_active_activities.py similarity index 87% rename from examples/dfp/v201702/activity_service/get_active_activities.py rename to examples/dfp/v201802/activity_service/get_active_activities.py index 6f3e5f14..0b32f027 100755 --- a/examples/dfp/v201702/activity_service/get_active_activities.py +++ b/examples/dfp/v201802/activity_service/get_active_activities.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + activity_service = client.GetService('ActivityService', version='v201802') # Create a statement to select activities. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/dfp/v201702/activity_service/get_all_activities.py b/examples/dfp/v201802/activity_service/get_all_activities.py similarity index 99% rename from examples/dfp/v201702/activity_service/get_all_activities.py rename to examples/dfp/v201802/activity_service/get_all_activities.py index 32b6c58e..d44eef63 100755 --- a/examples/dfp/v201702/activity_service/get_all_activities.py +++ b/examples/dfp/v201802/activity_service/get_all_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201702') + activity_service = client.GetService('ActivityService', version='v201802') # Create a statement to select activities. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/activity_service/update_activities.py b/examples/dfp/v201802/activity_service/update_activities.py similarity index 90% rename from examples/dfp/v201702/activity_service/update_activities.py rename to examples/dfp/v201802/activity_service/update_activities.py index 86865679..2225e1d4 100755 --- a/examples/dfp/v201702/activity_service/update_activities.py +++ b/examples/dfp/v201802/activity_service/update_activities.py @@ -35,18 +35,13 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201702') + activity_service = client.GetService('ActivityService', version='v201802') # Create statement object to select one activity by ID to update. - values = [{ - 'key': 'activityId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': activity_id - } - }] - query = 'WHERE id = :activityId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :activityId') + .WithBindVariable('activityId', long(activity_id)) + .Limit(1)) # Get activities by statement. response = activity_service.getActivitiesByStatement( @@ -66,6 +61,7 @@ def main(client, activity_id): else: print 'No activities found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/audience_segment_service/__init__.py b/examples/dfp/v201802/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201705/audience_segment_service/__init__.py rename to examples/dfp/v201802/audience_segment_service/__init__.py diff --git a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py b/examples/dfp/v201802/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/dfp/v201702/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/create_audience_segments.py index f0db7a52..010d0124 100755 --- a/examples/dfp/v201702/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + 'AudienceSegmentService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py similarity index 97% rename from examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py index ab4ab4ca..07e9fa8c 100755 --- a/examples/dfp/v201702/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') + 'AudienceSegmentService', version='v201802') # Create a statement to select audience segments. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py similarity index 86% rename from examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py index 65dbc7be..8c88c322 100755 --- a/examples/dfp/v201702/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - }}, - ] + 'AudienceSegmentService', version='v201802') # Create a statement to select audience segments. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'FIRST_PARTY')) # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py similarity index 80% rename from examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py index 371c6923..0fa30e62 100755 --- a/examples/dfp/v201702/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py @@ -30,24 +30,15 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201702') + 'AudienceSegmentService', version='v201802') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201705/audience_segment_service/update_audience_segments.py b/examples/dfp/v201802/audience_segment_service/update_audience_segments.py similarity index 81% rename from examples/dfp/v201705/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201802/audience_segment_service/update_audience_segments.py index 0fdea19a..e0b559d1 100755 --- a/examples/dfp/v201705/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/update_audience_segments.py @@ -29,24 +29,15 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201705') + 'AudienceSegmentService', version='v201802') # Create statement object to get the specified first party audience segment. - values = ( - [{'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'FIRST_PARTY' - } - }, - {'key': 'audience_segment_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': audience_segment_id - } - }]) - query = 'WHERE Type = :type AND Id = :audience_segment_id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) # Get audience segments by statement. response = audience_segment_service.getAudienceSegmentsByStatement( diff --git a/examples/dfp/v201705/base_rate_service/__init__.py b/examples/dfp/v201802/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201705/base_rate_service/__init__.py rename to examples/dfp/v201802/base_rate_service/__init__.py diff --git a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py b/examples/dfp/v201802/base_rate_service/create_product_base_rates.py similarity index 89% rename from examples/dfp/v201702/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201802/base_rate_service/create_product_base_rates.py index 26003719..54aa61a1 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/create_product_base_rates.py @@ -31,12 +31,14 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201702') + 'BaseRateService', version='v201802') # Create a product base rate. product_base_rate = { 'xsi_type': 'ProductBaseRate', + # Set the rate card ID that the product base rate belongs to. 'rateCardId': rate_card_id, + # Set the product id the base rate will be applied to. 'productId': product_id, # Set the rate to be $2. 'rate': { @@ -45,7 +47,7 @@ def main(client, product_id, rate_card_id): } } - # Create base rates on the server. + # Create the product base rate on the server. base_rates = base_rate_service.createBaseRates( [product_base_rate]) diff --git a/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py similarity index 94% rename from examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py rename to examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py index 63ffec25..d7a50f50 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py @@ -31,10 +31,10 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201702') + base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a base rate for a product package item. - base_rate = { + product_package_item_base_rate = { 'xsi_type': 'ProductPackageItemBaseRate', # Set the rate card ID that the product package item base rate # belongs to. @@ -51,7 +51,7 @@ def main(client): } # Create the product package item base rate on the server. - result = base_rate_service.createBaseRates([base_rate]) + result = base_rate_service.createBaseRates([product_package_item_base_rate]) for new_base_rate in result: print ('A product package item base rate with ID %d and rate %f %s ' diff --git a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py similarity index 88% rename from examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py index d024f6e8..f259ca28 100755 --- a/examples/dfp/v201702/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py @@ -31,12 +31,14 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201702') + 'BaseRateService', version='v201802') # Create a product template base rate. product_template_base_rate = { 'xsi_type': 'ProductTemplateBaseRate', + # Set the rate card ID that the product template base rate belongs to. 'rateCardId': rate_card_id, + # Set the product template the base rate will be applied to. 'productTemplateId': product_template_id, # Set the rate to be $2. 'rate': { @@ -45,7 +47,7 @@ def main(client, product_template_id, rate_card_id): } } - # Create base rates on the server. + # Create the product template item base rate on the server. base_rates = base_rate_service.createBaseRates( [product_template_base_rate]) diff --git a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py b/examples/dfp/v201802/base_rate_service/get_all_base_rates.py similarity index 99% rename from examples/dfp/v201702/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201802/base_rate_service/get_all_base_rates.py index 44b6c365..743db7e5 100755 --- a/examples/dfp/v201702/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/get_all_base_rates.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201702') + base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a statement to select base rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py similarity index 88% rename from examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py rename to examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py index d72c1f61..40848144 100755 --- a/examples/dfp/v201702/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py @@ -24,17 +24,11 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201702') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] + base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a statement to select base rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/dfp/v201702/base_rate_service/update_base_rates.py b/examples/dfp/v201802/base_rate_service/update_base_rates.py similarity index 90% rename from examples/dfp/v201702/base_rate_service/update_base_rates.py rename to examples/dfp/v201802/base_rate_service/update_base_rates.py index a1b1d7fe..48c74f3a 100755 --- a/examples/dfp/v201702/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/update_base_rates.py @@ -29,18 +29,14 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201702') + base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a filter statement for base rates for a single rate card. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': base_rate_id - } - }] - query = 'where id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', long(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( diff --git a/examples/dfp/v201802/cdn_configuration_service/__init__.py b/examples/dfp/v201802/cdn_configuration_service/__init__.py new file mode 100755 index 00000000..473ddba1 --- /dev/null +++ b/examples/dfp/v201802/cdn_configuration_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. diff --git a/examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py b/examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py new file mode 100755 index 00000000..f0dfe4ce --- /dev/null +++ b/examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 code example creates new cdn configurations. + +To determine which configurations exist, run get_all_cdn_configurations.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201802') + + # Create cdn config objects. + # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. + configs = [{ + # Basic example with no security policies. + 'name': 'ApiConfig1', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + } + } + }, { + # Complex example with security policies. + 'name': 'ApiConfig2', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': False, + 'tokenAuthenticationKey': 'abc123', + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': True, + 'originForwardingType': 'CONVENTIONAL', + 'originPathPrefix': '/path/to/my/origin' + } + } + } + }] + + # Add configs. + configs = cdn_config_service.createCdnConfigurations(configs) + + # Display results. + for config in configs: + print('Created CDN configuration with type "%s" and name "%s".' + % (config['cdnConfigurationType'], config['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py b/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py new file mode 100755 index 00000000..02e8b463 --- /dev/null +++ b/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 CDN configuration objects. + +Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be +returned. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201802') + + # Create a statement to select cdn configurations. + statement = dfp.StatementBuilder() + + # Retrieve a small number of configs at a time, paging + # through until all have been retrieved. + while True: + response = (cdn_config_service + .getCdnConfigurationsByStatement(statement.ToStatement())) + if 'results' in response: + for cdn in response['results']: + # Print out some information for each company. + print('Found CDN configuration with type "%s" and name "%s".' + % (cdn['cdnConfigurationType'], cdn['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/company_service/__init__.py b/examples/dfp/v201802/company_service/__init__.py similarity index 100% rename from examples/dfp/v201705/company_service/__init__.py rename to examples/dfp/v201802/company_service/__init__.py diff --git a/examples/dfp/v201705/company_service/create_companies.py b/examples/dfp/v201802/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201705/company_service/create_companies.py rename to examples/dfp/v201802/company_service/create_companies.py index ac9b5994..3106f133 100755 --- a/examples/dfp/v201705/company_service/create_companies.py +++ b/examples/dfp/v201802/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201705') + company_service = client.GetService('CompanyService', version='v201802') # Create company objects. companies = [ diff --git a/examples/dfp/v201705/company_service/get_advertisers.py b/examples/dfp/v201802/company_service/get_advertisers.py similarity index 88% rename from examples/dfp/v201705/company_service/get_advertisers.py rename to examples/dfp/v201802/company_service/get_advertisers.py index 16e506d9..ee3242fe 100755 --- a/examples/dfp/v201705/company_service/get_advertisers.py +++ b/examples/dfp/v201802/company_service/get_advertisers.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ADVERTISER' - }}, - ] + company_service = client.GetService('CompanyService', version='v201802') # Create a statement to select companies. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'ADVERTISER')) # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/dfp/v201705/company_service/get_all_companies.py b/examples/dfp/v201802/company_service/get_all_companies.py similarity index 99% rename from examples/dfp/v201705/company_service/get_all_companies.py rename to examples/dfp/v201802/company_service/get_all_companies.py index 61e10d09..cabe543b 100755 --- a/examples/dfp/v201705/company_service/get_all_companies.py +++ b/examples/dfp/v201802/company_service/get_all_companies.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201705') + company_service = client.GetService('CompanyService', version='v201802') # Create a statement to select companies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/company_service/update_companies.py b/examples/dfp/v201802/company_service/update_companies.py similarity index 89% rename from examples/dfp/v201702/company_service/update_companies.py rename to examples/dfp/v201802/company_service/update_companies.py index e1ade3e6..65a71808 100755 --- a/examples/dfp/v201702/company_service/update_companies.py +++ b/examples/dfp/v201802/company_service/update_companies.py @@ -35,18 +35,13 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201702') + company_service = client.GetService('CompanyService', version='v201802') # Create statement object to only select a single company by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': company_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(company_id)) + .Limit(1)) # Get companies by statement. response = company_service.getCompaniesByStatement( @@ -63,11 +58,12 @@ def main(client, company_id): # Display results. for company in companies: print (('Company with ID "%s", name "%s", and comment "%s"' - 'was updated.') + ' was updated.') % (company['id'], company['name'], company['comment'])) else: print 'No companies found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/contact_service/__init__.py b/examples/dfp/v201802/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201705/contact_service/__init__.py rename to examples/dfp/v201802/contact_service/__init__.py diff --git a/examples/dfp/v201702/contact_service/create_contacts.py b/examples/dfp/v201802/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201702/contact_service/create_contacts.py rename to examples/dfp/v201802/contact_service/create_contacts.py index 51bd81af..80687d64 100755 --- a/examples/dfp/v201702/contact_service/create_contacts.py +++ b/examples/dfp/v201802/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201702') + contact_service = client.GetService('ContactService', version='v201802') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201702/contact_service/get_all_contacts.py b/examples/dfp/v201802/contact_service/get_all_contacts.py similarity index 99% rename from examples/dfp/v201702/contact_service/get_all_contacts.py rename to examples/dfp/v201802/contact_service/get_all_contacts.py index 7fbd79d8..edde878e 100755 --- a/examples/dfp/v201702/contact_service/get_all_contacts.py +++ b/examples/dfp/v201802/contact_service/get_all_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201702') + contact_service = client.GetService('ContactService', version='v201802') # Create a statement to select contacts. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/contact_service/get_uninvited_contacts.py b/examples/dfp/v201802/contact_service/get_uninvited_contacts.py similarity index 87% rename from examples/dfp/v201705/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201802/contact_service/get_uninvited_contacts.py index 911225a5..99b67b8a 100755 --- a/examples/dfp/v201705/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201802/contact_service/get_uninvited_contacts.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'UNINVITED' - }}, - ] + contact_service = client.GetService('ContactService', version='v201802') # Create a statement to select contacts. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'UNINVITED')) # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/dfp/v201705/contact_service/update_contacts.py b/examples/dfp/v201802/contact_service/update_contacts.py similarity index 90% rename from examples/dfp/v201705/contact_service/update_contacts.py rename to examples/dfp/v201802/contact_service/update_contacts.py index 0bc86ca6..4091cac3 100755 --- a/examples/dfp/v201705/contact_service/update_contacts.py +++ b/examples/dfp/v201802/contact_service/update_contacts.py @@ -35,18 +35,13 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201705') + contact_service = client.GetService('ContactService', version='v201802') # Create statement object to select the single contact by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': contact_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(contact_id)) + .Limit(1)) # Get contacts by statement. response = contact_service.getContactsByStatement( @@ -69,6 +64,7 @@ def main(client, contact_id): else: print 'No contacts found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 2378c8ca..5b0c261e 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201702') + 'ContentMetadataKeyHierarchyService', version='v201802') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 90% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index b5400763..24acd69a 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -40,19 +40,15 @@ def main(client, content_metadata_key_hierarchy_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201702') + 'ContentMetadataKeyHierarchyService', version='v201802') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -78,6 +74,7 @@ def main(client, content_metadata_key_hierarchy_id): print ('Number of content metadata key hierarchies deleted: %s' % result['numChanges']) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index fe1d9afb..afe409a3 100755 --- a/examples/dfp/v201702/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201702') + 'ContentMetadataKeyHierarchyService', version='v201802') # Create a statement to select content metadata key hierarchies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index e6dce35b..cbef227b 100755 --- a/examples/dfp/v201705/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,19 +42,15 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201705') + 'ContentMetadataKeyHierarchyService', version='v201802') # Create a query to select a single content metadata key hierarchy. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': content_metadata_key_hierarchy_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) # Get a single content metadata key hierarchy by statement. response = (content_metadata_key_hierarchy_service @@ -90,6 +86,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): else: print 'No content metadata key hierarchies were found' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/content_service/__init__.py b/examples/dfp/v201802/content_service/__init__.py similarity index 100% rename from examples/dfp/v201705/content_service/__init__.py rename to examples/dfp/v201802/content_service/__init__.py diff --git a/examples/dfp/v201702/content_service/get_all_content.py b/examples/dfp/v201802/content_service/get_all_content.py similarity index 99% rename from examples/dfp/v201702/content_service/get_all_content.py rename to examples/dfp/v201802/content_service/get_all_content.py index 5649d6ae..4eac419f 100755 --- a/examples/dfp/v201702/content_service/get_all_content.py +++ b/examples/dfp/v201802/content_service/get_all_content.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201702') + content_service = client.GetService('ContentService', version='v201802') # Create a statement to select content. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_service/__init__.py b/examples/dfp/v201802/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201705/creative_service/__init__.py rename to examples/dfp/v201802/creative_service/__init__.py diff --git a/examples/dfp/v201705/creative_service/copy_image_creatives.py b/examples/dfp/v201802/creative_service/copy_image_creatives.py similarity index 99% rename from examples/dfp/v201705/creative_service/copy_image_creatives.py rename to examples/dfp/v201802/creative_service/copy_image_creatives.py index b1f69848..9a5270da 100755 --- a/examples/dfp/v201705/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201802/creative_service/copy_image_creatives.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to get the image creative. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/creative_service/create_creative_from_template.py b/examples/dfp/v201802/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201705/creative_service/create_creative_from_template.py rename to examples/dfp/v201802/creative_service/create_creative_from_template.py index 38d993e6..0184f00b 100755 --- a/examples/dfp/v201705/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201802/creative_service/create_creative_from_template.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201705/creative_service/create_creatives.py b/examples/dfp/v201802/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201705/creative_service/create_creatives.py rename to examples/dfp/v201802/creative_service/create_creatives.py index a9cb9884..785ecce6 100755 --- a/examples/dfp/v201705/creative_service/create_creatives.py +++ b/examples/dfp/v201802/creative_service/create_creatives.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201702/creative_service/create_custom_creative.py b/examples/dfp/v201802/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201702/creative_service/create_custom_creative.py rename to examples/dfp/v201802/creative_service/create_custom_creative.py index 54de0f4b..57d11581 100755 --- a/examples/dfp/v201702/creative_service/create_custom_creative.py +++ b/examples/dfp/v201802/creative_service/create_custom_creative.py @@ -41,7 +41,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201802') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201702/creative_service/create_native_creative.py b/examples/dfp/v201802/creative_service/create_native_creative.py similarity index 99% rename from examples/dfp/v201702/creative_service/create_native_creative.py rename to examples/dfp/v201802/creative_service/create_native_creative.py index b2921671..0af31046 100755 --- a/examples/dfp/v201702/creative_service/create_native_creative.py +++ b/examples/dfp/v201802/creative_service/create_native_creative.py @@ -46,7 +46,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') + creative_service = client.GetService('CreativeService', version='v201802') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/dfp/v201705/creative_service/get_all_creatives.py b/examples/dfp/v201802/creative_service/get_all_creatives.py similarity index 99% rename from examples/dfp/v201705/creative_service/get_all_creatives.py rename to examples/dfp/v201802/creative_service/get_all_creatives.py index 809b4d2e..63febc23 100755 --- a/examples/dfp/v201705/creative_service/get_all_creatives.py +++ b/examples/dfp/v201802/creative_service/get_all_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to select creatives. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_service/get_image_creatives.py b/examples/dfp/v201802/creative_service/get_image_creatives.py similarity index 86% rename from examples/dfp/v201702/creative_service/get_image_creatives.py rename to examples/dfp/v201802/creative_service/get_image_creatives.py index e63a52d4..43c97189 100755 --- a/examples/dfp/v201702/creative_service/get_image_creatives.py +++ b/examples/dfp/v201802/creative_service/get_image_creatives.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201702') - query = 'WHERE creativeType = :creativeType' - values = [ - {'key': 'creativeType', - 'value': { - 'xsi_type': 'TextValue', - 'value': '_image_creative' - }}, - ] + creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to select creatives. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('creativeType = :creativeType') + .WithBindVariable('creativeType', 'ImageCreative')) # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/dfp/v201705/creative_service/update_creatives.py b/examples/dfp/v201802/creative_service/update_creatives.py similarity index 85% rename from examples/dfp/v201705/creative_service/update_creatives.py rename to examples/dfp/v201802/creative_service/update_creatives.py index 82400db5..36b9ac84 100755 --- a/examples/dfp/v201705/creative_service/update_creatives.py +++ b/examples/dfp/v201802/creative_service/update_creatives.py @@ -34,24 +34,14 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201705') + creative_service = client.GetService('CreativeService', version='v201802') # Create statement object to get all image creatives. - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ImageCreative' - } - }, { - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': image_creative_id - } - }] - query = 'WHERE creativeType = :type AND id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('creativeType = :type AND id = :id') + .WithBindVariable('type', 'ImageCreative') + .WithBindVariable('id', long(image_creative_id)) + .Limit(1)) # Get creatives by statement. response = creative_service.getCreativesByStatement( @@ -74,6 +64,7 @@ def main(client, image_creative_id): else: print 'No creatives found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/creative_set_service/__init__.py b/examples/dfp/v201802/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201705/creative_set_service/__init__.py rename to examples/dfp/v201802/creative_set_service/__init__.py diff --git a/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py index bd800084..339e5627 100755 --- a/examples/dfp/v201705/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201705/creative_set_service/create_creative_set.py b/examples/dfp/v201802/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201705/creative_set_service/create_creative_set.py rename to examples/dfp/v201802/creative_set_service/create_creative_set.py index 55764d11..f3af2365 100755 --- a/examples/dfp/v201705/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201802/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201705') + version='v201802') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py similarity index 97% rename from examples/dfp/v201705/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201802/creative_set_service/get_all_creative_sets.py index de0d3ef5..b3c337f3 100755 --- a/examples/dfp/v201705/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201705') + 'CreativeSetService', version='v201802') # Create a statement to select creative sets. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py similarity index 85% rename from examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py index 859b9aeb..e6defb2b 100755 --- a/examples/dfp/v201702/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,17 +25,11 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201702') - query = 'WHERE masterCreativeId = :masterCreativeId' - values = [ - {'key': 'masterCreativeId', - 'value': { - 'xsi_type': 'TextValue', - 'value': master_creative_id - }}, - ] + 'CreativeSetService', version='v201802') # Create a statement to select creative sets. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('masterCreativeId = :masterCreativeId') + .WithBindVariable('masterCreativeId', master_creative_id)) # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/dfp/v201705/creative_set_service/update_creative_set.py b/examples/dfp/v201802/creative_set_service/update_creative_set.py similarity index 89% rename from examples/dfp/v201705/creative_set_service/update_creative_set.py rename to examples/dfp/v201802/creative_set_service/update_creative_set.py index 94cdd8e3..36be393c 100755 --- a/examples/dfp/v201705/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201802/creative_set_service/update_creative_set.py @@ -37,18 +37,12 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201705') + version='v201802') # Create statement to select a single creative set by ID. - values = [{ - 'key': 'creativeSetId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_set_id - } - }] - query = 'WHERE id = :creativeSetId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeSetId') + .WithBindVariable('creativeSetId', long(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -72,6 +66,7 @@ def main(client, creative_set_id, companion_creative_id): else: print 'No creative sets found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/creative_template_service/__init__.py b/examples/dfp/v201802/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201705/creative_template_service/__init__.py rename to examples/dfp/v201802/creative_template_service/__init__.py diff --git a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py similarity index 97% rename from examples/dfp/v201702/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201802/creative_template_service/get_all_creative_templates.py index 39ced2d2..2795bdd9 100755 --- a/examples/dfp/v201702/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201702') + 'CreativeTemplateService', version='v201802') # Create a statement to select creative templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py similarity index 86% rename from examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py rename to examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py index b4748eba..63958253 100755 --- a/examples/dfp/v201702/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201702') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SYSTEM_DEFINED' - }}, - ] + 'CreativeTemplateService', version='v201802') # Create a statement to select creative templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'SYSTEM_DEFINED')) # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py similarity index 91% rename from examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py index d09aa48d..624413df 100755 --- a/examples/dfp/v201705/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py @@ -37,15 +37,15 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201705') + version='v201802') # Create creative wrapper objects. creative_wrapper = { # A label can only be associated with one creative wrapper. 'labelId': label_id, 'ordering': 'INNER', - 'header': {'htmlSnippet': 'My creative wrapper header'}, - 'footer': {'htmlSnippet': 'My creative wrapper footer'} + 'htmlHeader': 'My creative wrapper header', + 'htmlFooter': 'My creative wrapper footer' } # Add creative wrapper. diff --git a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 85% rename from examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py index 48c4c1ae..f8e913db 100755 --- a/examples/dfp/v201702/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,24 +33,13 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201702') + version='v201802') # Create a query to select the active creative wrappers for the given label. - values = [{ - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE status = :status AND labelId = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status AND labelId = :labelId') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('labelId', long(label_id))) creative_wrappers_deactivated = 0 @@ -82,6 +71,7 @@ def main(client, label_id): else: print 'No creative wrappers were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py similarity index 86% rename from examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py index c3200282..90f75cd8 100755 --- a/examples/dfp/v201702/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'CreativeWrapperService', version='v201802') # Create a statement to select creative wrappers. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py similarity index 97% rename from examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py index 26fb962d..1e2bd8b9 100755 --- a/examples/dfp/v201702/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201702') + 'CreativeWrapperService', version='v201802') # Create a statement to select creative wrappers. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py similarity index 88% rename from examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py index 5bb8ee6c..75f7e964 100755 --- a/examples/dfp/v201702/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py @@ -36,18 +36,13 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201702') + version='v201802') # Create statement to get a creative wrapper by ID. - values = [{ - 'key': 'creativeWrapperId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': creative_wrapper_id - } - }] - query = 'WHERE id = :creativeWrapperId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :creativeWrapperId') + .WithBindVariable('creativeWrapperId', + long(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -71,6 +66,7 @@ def main(client, creative_wrapper_id): else: print 'No creative wrappers found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_field_service/__init__.py b/examples/dfp/v201802/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201705/custom_field_service/__init__.py rename to examples/dfp/v201802/custom_field_service/__init__.py diff --git a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py b/examples/dfp/v201802/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201702/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201802/custom_field_service/create_custom_field_options.py index d2f010bd..8129c823 100755 --- a/examples/dfp/v201702/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201802/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201802') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201705/custom_field_service/create_custom_fields.py b/examples/dfp/v201802/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201705/custom_field_service/create_custom_fields.py rename to examples/dfp/v201802/custom_field_service/create_custom_fields.py index 89d1069e..1aaf1209 100755 --- a/examples/dfp/v201705/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') + 'CustomFieldService', version='v201802') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 82% rename from examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py index 51333474..97cd279d 100755 --- a/examples/dfp/v201702/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,27 +33,14 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201802') # Create statement to select only active custom fields that apply to # line items. - values = [ - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - } - }, { - 'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - } - } - ] - query = 'WHERE entityType = :entityType and isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType and isActive = :isActive') + .WithBindVariable('entityType', 'LINE_ITEM') + .WithBindVariable('isActive', True)) custom_fields_deactivated = 0 @@ -79,6 +66,7 @@ def main(client): else: print 'No custom fields were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py similarity index 97% rename from examples/dfp/v201702/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201802/custom_field_service/get_all_custom_fields.py index a823a7a6..afe4646c 100755 --- a/examples/dfp/v201702/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201802') # Create a statement to select custom fields. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py similarity index 85% rename from examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py rename to examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py index a5df35ad..411ff23b 100755 --- a/examples/dfp/v201705/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201705') - query = 'WHERE entityType = :entityType' - values = [ - {'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'LINE_ITEM' - }}, - ] + 'CustomFieldService', version='v201802') # Create a statement to select custom fields. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('entityType = :entityType') + .WithBindVariable('entityType', 'LINE_ITEM')) # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py similarity index 82% rename from examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py index 63bf186c..3553cb4e 100755 --- a/examples/dfp/v201702/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py @@ -42,53 +42,36 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201802') - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201802') # Create statement to get a custom field. - custom_field_values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - custom_field_query = 'WHERE id = :customFieldId' - custom_field_statement = dfp.FilterStatement( - custom_field_query, custom_field_values, 1) + custom_field_statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', custom_field_id) + .Limit(1)) # Get custom field. custom_field = custom_field_service.getCustomFieldsByStatement( custom_field_statement.ToStatement())['results'][0] # Create statement to get a drop down custom field. - drop_down_custom_field_values = [{ - 'key': 'dropDownCustomFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': drop_down_custom_field_id - } - }] - drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId' - drop_down_custom_field_statement = dfp.FilterStatement( - drop_down_custom_field_query, drop_down_custom_field_values, 1) + drop_down_custom_field_statement = ( + dfp.StatementBuilder() + .Where('id = :dropDownCustomFieldId') + .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) + .Limit(1)) # Get drop-down custom field. drop_down_custom_field = custom_field_service.getCustomFieldsByStatement( drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - line_item_query = 'WHERE id = :lineItemId' - line_item_statement = dfp.FilterStatement( - line_item_query, line_item_values, 1) + line_item_statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', line_item_id) + .Limit(1)) # Get line item. line_item = line_item_service.getLineItemsByStatement( diff --git a/examples/dfp/v201702/custom_field_service/update_custom_fields.py b/examples/dfp/v201802/custom_field_service/update_custom_fields.py similarity index 88% rename from examples/dfp/v201702/custom_field_service/update_custom_fields.py rename to examples/dfp/v201802/custom_field_service/update_custom_fields.py index 5a56bb72..cdebe296 100755 --- a/examples/dfp/v201702/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/update_custom_fields.py @@ -36,18 +36,12 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201702') + 'CustomFieldService', version='v201802') # Create statement to get a custom field. - values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - query = 'WHERE id = :customFieldId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', long(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -69,6 +63,7 @@ def main(client, custom_field_id): else: print 'No custom fields found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/custom_targeting_service/__init__.py b/examples/dfp/v201802/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201705/custom_targeting_service/__init__.py rename to examples/dfp/v201802/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py index 0c979863..708a712a 100755 --- a/examples/dfp/v201705/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py similarity index 84% rename from examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py index 03c46640..d90b4079 100755 --- a/examples/dfp/v201705/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,17 +36,11 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') - - values = [{ - 'key': 'name', - 'value': { - 'xsi_type': 'TextValue', - 'value': key_name - } - }] - query = 'WHERE name = :name' - statement = dfp.FilterStatement(query, values) + 'CustomTargetingService', version='v201802') + + statement = (dfp.StatementBuilder() + .Where('name = :name') + .WithBindVariable('name', key_name)) deleted_custom_targeting_keys = 0 @@ -57,8 +51,8 @@ def main(client, key_name): if 'results' in response: key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) - key_statement = dfp.FilterStatement(key_query) + key_statement = (dfp.StatementBuilder() + .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. result = custom_targeting_service.performCustomTargetingKeyAction( @@ -66,7 +60,7 @@ def main(client, key_name): if result and int(result['numChanges']) > 0: deleted_custom_targeting_keys += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -76,6 +70,7 @@ def main(client, key_name): else: print 'No custom targeting keys were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py similarity index 81% rename from examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py index 84af48bb..2a46afba 100755 --- a/examples/dfp/v201702/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py @@ -36,17 +36,11 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201802') - filter_values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, filter_values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', key_id)) deleted_custom_targeting_values = 0 @@ -57,16 +51,17 @@ def main(client, key_id): if 'results' in response: value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_query = ('WHERE customTargetingKeyId = :keyId ' - 'AND id IN (%s)' % ', '.join(value_ids)) - value_statement = dfp.FilterStatement(value_query, filter_values) + value_statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId ' + 'AND id IN (%s)' % ', '.join(value_ids)) + .WithBindVariable('keyId', key_id)) # Delete custom targeting values. result = custom_targeting_service.performCustomTargetingValueAction( action, value_statement.ToStatement()) if result and int(result['numChanges']) > 0: deleted_custom_targeting_values += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 87% rename from examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index fbafecd9..8b378fca 100755 --- a/examples/dfp/v201702/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201802') # Create statement to get all targeting keys. targeting_key_statement = dfp.StatementBuilder() @@ -42,11 +42,11 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys]))) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( @@ -59,7 +59,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 78% rename from examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index eda4ac5b..9c6a4660 100755 --- a/examples/dfp/v201705/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,18 +23,12 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') # Create statement to get targeting keys for predefined values. - query = ('WHERE type = :type') - values = [{ - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PREDEFINED' - } - }] - targeting_key_statement = dfp.FilterStatement(query, values) + targeting_key_statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'PREDEFINED')) all_keys = [] @@ -44,17 +38,17 @@ def main(client): targeting_key_statement.ToStatement()) if 'results' in response: all_keys.extend(response['results']) - targeting_key_statement.offset += dfp.SUGGESTED_PAGE_LIMIT + targeting_key_statement.offset += targeting_key_statement.limit else: break if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (:ids)') + .WithBindVariable('ids', [key['id'] for key in all_keys])) - # Retreive a small amount of custom targeting values at a time, paging + # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( @@ -67,7 +61,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py similarity index 88% rename from examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py index 738097d6..81ce3523 100755 --- a/examples/dfp/v201705/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py @@ -30,17 +30,12 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201705') + 'CustomTargetingService', version='v201802') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE id = :keyId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :keyId') + .WithBindVariable('keyId', long(key_id)) + .Limit(1)) # Get custom targeting keys by statement. response = custom_targeting_service.getCustomTargetingKeysByStatement( @@ -65,6 +60,7 @@ def main(client, key_id): else: print 'No custom targeting keys were found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py similarity index 88% rename from examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py index ca09f287..d1a1e9c3 100755 --- a/examples/dfp/v201702/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py @@ -30,17 +30,11 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201702') + 'CustomTargetingService', version='v201802') - values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', long(key_id))) while True: # Get custom targeting values by statement. @@ -70,6 +64,7 @@ def main(client, key_id): if response['totalResultSetSize'] == 0: print 'No custom targeting values were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/exchange_rate_service/__init__.py b/examples/dfp/v201802/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201705/exchange_rate_service/__init__.py rename to examples/dfp/v201802/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py index 4fd18507..66706137 100755 --- a/examples/dfp/v201705/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201705') + version='v201802') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py similarity index 97% rename from examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py index 7c4d95b6..497f5630 100755 --- a/examples/dfp/v201702/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201702') + 'ExchangeRateService', version='v201802') # Create a statement to select exchange rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 86% rename from examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py index acac6d8c..896d0ac4 100755 --- a/examples/dfp/v201705/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,17 +25,11 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201705') - query = 'WHERE currencyCode = :currencyCode' - values = [ - {'key': 'currencyCode', - 'value': { - 'xsi_type': 'TextValue', - 'value': currency_code - }}, - ] + 'ExchangeRateService', version='v201802') # Create a statement to select exchange rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('currencyCode = :currencyCode') + .WithBindVariable('currencyCode', currency_code)) # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py similarity index 87% rename from examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py index dae8aad9..a95e076f 100755 --- a/examples/dfp/v201705/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py @@ -30,19 +30,13 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201705') + version='v201802') # Create a statement to get an exchange rate by its ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': exchange_rate_id - } - }] - query = 'WHERE id = :id' - # Create a filter statement. - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(exchange_rate_id)) + .Limit(1)) # Get rate cards by statement. response = exchange_rate_service.getExchangeRatesByStatement( diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast.py b/examples/dfp/v201802/forecast_service/get_availability_forecast.py similarity index 90% rename from examples/dfp/v201702/forecast_service/get_availability_forecast.py rename to examples/dfp/v201802/forecast_service/get_availability_forecast.py index 7ed5d8f1..29da19fc 100755 --- a/examples/dfp/v201702/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201802/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + forecast_service = client.GetService('ForecastService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] @@ -105,11 +105,14 @@ def main(client, advertiser_id): forecast = forecast_service.getAvailabilityForecast( prospective_line_item, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -117,9 +120,10 @@ def main(client, advertiser_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py similarity index 83% rename from examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py index ea625ff7..f7914e26 100755 --- a/examples/dfp/v201702/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201702') + forecast_service = client.GetService('ForecastService', version='v201802') # Set forecasting options. forecast_options = { @@ -42,11 +42,14 @@ def main(client, line_item_id): forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) matched = long(forecast['matchedUnits']) - available_percent = (((long(forecast['availableUnits'])/ - (matched * 1.0)) * 100) - if matched != 0 else 0) - contending_line_items = ([] if 'contendingLineItems' not in forecast - else forecast['contendingLineItems']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. print '%s %s matched.' % (matched, forecast['unitType'].lower()) @@ -54,7 +57,7 @@ def main(client, line_item_id): print '%d contending line items.' % len(contending_line_items) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/(matched * 1.0)) * 100 + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) if __name__ == '__main__': diff --git a/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py index 3d6187f7..f6277566 100755 --- a/examples/dfp/v201702/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201702') + forecast_service = client.GetService('ForecastService', version='v201802') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201705/inventory_service/__init__.py b/examples/dfp/v201802/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201705/inventory_service/__init__.py rename to examples/dfp/v201802/inventory_service/__init__.py diff --git a/examples/dfp/v201705/inventory_service/archive_ad_units.py b/examples/dfp/v201802/inventory_service/archive_ad_units.py similarity index 90% rename from examples/dfp/v201705/inventory_service/archive_ad_units.py rename to examples/dfp/v201802/inventory_service/archive_ad_units.py index 72aae7d5..5d118eb8 100755 --- a/examples/dfp/v201705/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201802/inventory_service/archive_ad_units.py @@ -35,19 +35,13 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201705') + inventory_service = client.GetService('InventoryService', version='v201802') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - values = [{ - 'key': 'parentId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': parent_id - } - }] - query = 'WHERE parentId = :parentId or id = :parentId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId or id = :parentId') + .WithBindVariable('parentId', long(parent_id))) ad_units_archived = 0 @@ -74,6 +68,7 @@ def main(client, parent_id): else: print 'No ad units were archived.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/inventory_service/create_ad_units.py b/examples/dfp/v201802/inventory_service/create_ad_units.py similarity index 99% rename from examples/dfp/v201702/inventory_service/create_ad_units.py rename to examples/dfp/v201802/inventory_service/create_ad_units.py index 6cf363df..708709f9 100755 --- a/examples/dfp/v201702/inventory_service/create_ad_units.py +++ b/examples/dfp/v201802/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201702') + inventory_service = client.GetService('InventoryService', version='v201802') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py new file mode 100755 index 00000000..e86eb93b --- /dev/null +++ b/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 prints all ad unit names as a tree.""" + + +# Import appropriate modules from the client library. +import collections +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201802') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select only the root ad unit by ID. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', root_ad_unit_id)) + + # Make a request for the root ad unit + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + root_ad_unit = response['results'][0] + + all_ad_units = get_all_ad_units(inventory_service) + + display_hierarchy(root_ad_unit, all_ad_units) + + +def get_all_ad_units(inventory_service): + """Download all ad units. + + Args: + inventory_service: An instance of the InventoryService. + + Returns: + A list containing all ad units. + """ + # Create a statement to get all ad units. + statement = (dfp.StatementBuilder() + .OrderBy('id', ascending=True)) + + # Pull down all ad units into a list + keep_iterating = True + total_results = 0 + found_ad_units = [] + while keep_iterating: + page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in page: + total_results = page['totalResultSetSize'] + found_ad_units.extend(page['results']) + + statement.offset += statement.limit + keep_iterating = statement.offset < total_results + + return found_ad_units + + +def display_hierarchy(root_ad_unit, all_ad_units): + """Display the ad units as a tree. + + Args: + root_ad_unit: The root ad unit to begin from. + all_ad_units: A list containing all ad units. + """ + # Create a dict mapping the ids of parents to lists of their children. + parent_id_to_children = collections.defaultdict(list) + for ad_unit in all_ad_units: + if 'parentId' in ad_unit: + parent_id_to_children[ad_unit['parentId']].append(ad_unit) + parent_id_to_children = dict(parent_id_to_children) + + display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0) + + +def display_hierarchy_helper(root, parent_id_to_children, depth): + """Recursive helper for displaying the hierarchy. + + Args: + root: The current root ad unit. + parent_id_to_children: The overall map of parent ids to children. + depth: The current depth. + """ + print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id']) + + # Recurse for each child of this root that has children. + for child in parent_id_to_children.get(root['id'], []): + display_hierarchy_helper(child, parent_id_to_children, depth + 1) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py similarity index 90% rename from examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py index 3af222b4..4858e6fc 100755 --- a/examples/dfp/v201702/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py @@ -23,12 +23,12 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201702') + 'InventoryService', version='v201802') # Create a statement to select ad unit sizes. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() - # Retreive a small amount of ad unit sizes at a time, paging + # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. response = ad_unit_size_service.getAdUnitSizesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201702/inventory_service/get_all_ad_units.py b/examples/dfp/v201802/inventory_service/get_all_ad_units.py similarity index 99% rename from examples/dfp/v201702/inventory_service/get_all_ad_units.py rename to examples/dfp/v201802/inventory_service/get_all_ad_units.py index 90a2da31..c42ea962 100755 --- a/examples/dfp/v201702/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201802/inventory_service/get_all_ad_units.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201702') + ad_unit_service = client.GetService('InventoryService', version='v201802') # Create a statement to select ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py new file mode 100755 index 00000000..f58ddeb5 --- /dev/null +++ b/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 child ad units of the effective root ad unit.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201802') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + parent_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select ad units under the parent ad unit. + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId') + .OrderBy('id', ascending=True) + .WithBindVariable('parentId', parent_ad_unit_id)) + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response: + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/inventory_service/update_ad_units.py b/examples/dfp/v201802/inventory_service/update_ad_units.py similarity index 92% rename from examples/dfp/v201702/inventory_service/update_ad_units.py rename to examples/dfp/v201802/inventory_service/update_ad_units.py index 75cec0aa..a7a4e217 100755 --- a/examples/dfp/v201702/inventory_service/update_ad_units.py +++ b/examples/dfp/v201802/inventory_service/update_ad_units.py @@ -36,18 +36,12 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201702') + inventory_service = client.GetService('InventoryService', version='v201802') # Create a statement to select a single ad unit by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': ad_unit_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', ad_unit_id)) # Get ad units by statement. response = inventory_service.getAdUnitsByStatement( @@ -81,6 +75,7 @@ def main(client, ad_unit_id): print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/label_service/__init__.py b/examples/dfp/v201802/label_service/__init__.py similarity index 100% rename from examples/dfp/v201705/label_service/__init__.py rename to examples/dfp/v201802/label_service/__init__.py diff --git a/examples/dfp/v201705/label_service/create_labels.py b/examples/dfp/v201802/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201705/label_service/create_labels.py rename to examples/dfp/v201802/label_service/create_labels.py index 6e99a2f8..c6e3d203 100755 --- a/examples/dfp/v201705/label_service/create_labels.py +++ b/examples/dfp/v201802/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') + label_service = client.GetService('LabelService', version='v201802') # Create label objects. labels = [] diff --git a/examples/dfp/v201705/label_service/deactivate_labels.py b/examples/dfp/v201802/label_service/deactivate_labels.py similarity index 89% rename from examples/dfp/v201705/label_service/deactivate_labels.py rename to examples/dfp/v201802/label_service/deactivate_labels.py index f44d2454..f71ab6f5 100755 --- a/examples/dfp/v201705/label_service/deactivate_labels.py +++ b/examples/dfp/v201802/label_service/deactivate_labels.py @@ -27,18 +27,12 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') + label_service = client.GetService('LabelService', version='v201802') # Create query. - values = [{ - 'key': 'isActive', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'true' - } - }] - query = 'WHERE isActive = :isActive' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) labels_deactivated = 0 @@ -64,6 +58,7 @@ def main(client): else: print 'No labels were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/label_service/get_active_labels.py b/examples/dfp/v201802/label_service/get_active_labels.py similarity index 87% rename from examples/dfp/v201702/label_service/get_active_labels.py rename to examples/dfp/v201802/label_service/get_active_labels.py index 895be48f..023a2816 100755 --- a/examples/dfp/v201702/label_service/get_active_labels.py +++ b/examples/dfp/v201802/label_service/get_active_labels.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') - query = 'WHERE isActive = :isActive' - values = [ - {'key': 'isActive', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + label_service = client.GetService('LabelService', version='v201802') # Create a statement to select labels. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/dfp/v201705/label_service/get_all_labels.py b/examples/dfp/v201802/label_service/get_all_labels.py similarity index 99% rename from examples/dfp/v201705/label_service/get_all_labels.py rename to examples/dfp/v201802/label_service/get_all_labels.py index 6a29dedf..7546eb12 100755 --- a/examples/dfp/v201705/label_service/get_all_labels.py +++ b/examples/dfp/v201802/label_service/get_all_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201705') + label_service = client.GetService('LabelService', version='v201802') # Create a statement to select labels. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/label_service/update_labels.py b/examples/dfp/v201802/label_service/update_labels.py similarity index 87% rename from examples/dfp/v201702/label_service/update_labels.py rename to examples/dfp/v201802/label_service/update_labels.py index dc1b3ffe..91b7d025 100755 --- a/examples/dfp/v201702/label_service/update_labels.py +++ b/examples/dfp/v201802/label_service/update_labels.py @@ -29,20 +29,12 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201702') + label_service = client.GetService('LabelService', version='v201802') # Create a statement to select only active labels. - values = [ - { - 'key': 'labelId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': label_id - } - } - ] - query = 'WHERE id = :labelId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :labelId') + .WithBindVariable('labelId', long(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -63,6 +55,7 @@ def main(client, label_id): else: print 'No labels found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/line_item_creative_association_service/__init__.py b/examples/dfp/v201802/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201705/line_item_creative_association_service/__init__.py rename to examples/dfp/v201802/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201705/line_item_creative_association_service/create_licas.py b/examples/dfp/v201802/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201705/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201802/line_item_creative_association_service/create_licas.py index 117caadb..dcad9d0c 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py similarity index 83% rename from examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py index 89417839..38d6475d 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py @@ -30,24 +30,13 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') # Create query. - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - } - }] - query = 'WHERE lineItemId = :lineItemId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId AND status = :status') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('lineItemId', long(line_item_id))) num_deactivated_licas = 0 @@ -77,6 +66,7 @@ def main(client, line_item_id): else: print 'No LICAs were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py similarity index 97% rename from examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py index 55b0a511..a3e8cc11 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') + 'LineItemCreativeAssociationService', version='v201802') # Create a statement to select line item creative associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py similarity index 87% rename from examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py index 3630dd39..1fb91b67 100755 --- a/examples/dfp/v201705/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,17 +25,11 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201705') - query = 'WHERE lineItemId = :lineItemId' - values = [ - {'key': 'lineItemId', - 'value': { - 'xsi_type': 'TextValue', - 'value': line_item_id - }}, - ] + 'LineItemCreativeAssociationService', version='v201802') # Create a statement to select line item creative associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemId = :lineItemId') + .WithBindVariable('lineItemId', line_item_id)) # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py b/examples/dfp/v201802/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201702/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201802/line_item_creative_association_service/update_licas.py index 783a1e87..e5b6dc12 100755 --- a/examples/dfp/v201702/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/update_licas.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201702') + 'LineItemCreativeAssociationService', version='v201802') # Create statement object to get all LICAs. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/line_item_service/__init__.py b/examples/dfp/v201802/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201705/line_item_service/__init__.py rename to examples/dfp/v201802/line_item_service/__init__.py diff --git a/examples/dfp/v201702/line_item_service/activate_line_items.py b/examples/dfp/v201802/line_item_service/activate_line_items.py similarity index 86% rename from examples/dfp/v201702/line_item_service/activate_line_items.py rename to examples/dfp/v201802/line_item_service/activate_line_items.py index 91dc966b..a4d05caa 100755 --- a/examples/dfp/v201702/line_item_service/activate_line_items.py +++ b/examples/dfp/v201802/line_item_service/activate_line_items.py @@ -33,24 +33,13 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201802') # Create query. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' - } - }] - query = 'WHERE orderId = :orderId AND status = :status' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId AND status = :status') + .WithBindVariable('status', 'NEEDS_CREATIVES') + .WithBindVariable('orderId', long(order_id))) line_items_activated = 0 @@ -79,6 +68,7 @@ def main(client, order_id): else: print 'No line items were activated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/line_item_service/create_line_items.py b/examples/dfp/v201802/line_item_service/create_line_items.py similarity index 93% rename from examples/dfp/v201702/line_item_service/create_line_items.py rename to examples/dfp/v201802/line_item_service/create_line_items.py index 10ab761b..1e5af88b 100755 --- a/examples/dfp/v201702/line_item_service/create_line_items.py +++ b/examples/dfp/v201802/line_item_service/create_line_items.py @@ -22,11 +22,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set order that the created line item will belong to and add the id of a # placement containing ad units to target. @@ -36,7 +37,10 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201802') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) # Create line item objects. line_items = [] @@ -128,17 +132,7 @@ def main(client, order_id, targeted_placement_ids): ], 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'STANDARD', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201702/line_item_service/create_video_line_item.py b/examples/dfp/v201802/line_item_service/create_video_line_item.py similarity index 92% rename from examples/dfp/v201702/line_item_service/create_video_line_item.py rename to examples/dfp/v201802/line_item_service/create_video_line_item.py index e02c4062..fcb84fec 100755 --- a/examples/dfp/v201702/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201802/line_item_service/create_video_line_item.py @@ -24,11 +24,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set order that all created line item will belong to and the video ad unit id # to target. @@ -46,7 +47,10 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201802') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) # Create line item object. line_item = { @@ -99,17 +103,7 @@ def main(client, order_id, targeted_video_ad_unit_id, 'companionDeliveryOption': 'OPTIONAL', 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'SPONSORSHIP', - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'endDateTime': end_datetime, 'costType': 'CPM', 'costPerUnit': { 'currencyCode': 'USD', diff --git a/examples/dfp/v201705/line_item_service/get_all_line_items.py b/examples/dfp/v201802/line_item_service/get_all_line_items.py similarity index 99% rename from examples/dfp/v201705/line_item_service/get_all_line_items.py rename to examples/dfp/v201802/line_item_service/get_all_line_items.py index 90e12640..4e8ea547 100755 --- a/examples/dfp/v201705/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201802/line_item_service/get_all_line_items.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # Create a statement to select line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py similarity index 86% rename from examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py rename to examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py index cfba2dd4..46639e3a 100755 --- a/examples/dfp/v201702/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') - query = 'WHERE isMissingCreatives = :isMissingCreatives' - values = [ - {'key': 'isMissingCreatives', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + line_item_service = client.GetService('LineItemService', version='v201802') # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('isMissingCreatives = :isMissingCreatives') + .WithBindVariable('isMissingCreatives', True)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py similarity index 82% rename from examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py index f23a397b..6190ced8 100755 --- a/examples/dfp/v201702/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py @@ -21,22 +21,20 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') - query = 'WHERE lastModifiedDateTime >= :lastModifiedDateTime' - values = [ - {'key': 'lastModifiedDateTime', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() - timedelta(days=1)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + line_item_service = client.GetService('LineItemService', version='v201802') + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + # Create a statement to select line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/dfp/v201702/line_item_service/pause_line_items.py b/examples/dfp/v201802/line_item_service/pause_line_items.py similarity index 99% rename from examples/dfp/v201702/line_item_service/pause_line_items.py rename to examples/dfp/v201802/line_item_service/pause_line_items.py index 42ed186a..62481bf9 100755 --- a/examples/dfp/v201702/line_item_service/pause_line_items.py +++ b/examples/dfp/v201802/line_item_service/pause_line_items.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201802') # Create a statement to select the line item. # Change this to operate on more than one Line Item. diff --git a/examples/dfp/v201705/line_item_service/target_custom_criteria.py b/examples/dfp/v201802/line_item_service/target_custom_criteria.py similarity index 93% rename from examples/dfp/v201705/line_item_service/target_custom_criteria.py rename to examples/dfp/v201802/line_item_service/target_custom_criteria.py index de386341..810372a2 100755 --- a/examples/dfp/v201705/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201802/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # create custom criterias custom_criteria1 = { @@ -81,15 +81,10 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - query = 'WHERE id = :lineItemId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', long(line_item_id)) + .Limit(1)) # Set custom criteria targeting on the line item. line_item = line_item_service.getLineItemsByStatement( @@ -107,6 +102,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, else: print 'No line items were updated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/line_item_service/update_line_items.py b/examples/dfp/v201802/line_item_service/update_line_items.py similarity index 84% rename from examples/dfp/v201705/line_item_service/update_line_items.py rename to examples/dfp/v201802/line_item_service/update_line_items.py index 7360fcb0..a98c03db 100755 --- a/examples/dfp/v201705/line_item_service/update_line_items.py +++ b/examples/dfp/v201802/line_item_service/update_line_items.py @@ -29,25 +29,16 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201705') + line_item_service = client.GetService('LineItemService', version='v201802') # Create statement object to only select line items with even delivery rates. - values = [{ - 'key': 'deliveryRateType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'EVENLY' - } - }, { - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId' - statement = dfp.FilterStatement(query, values, 500) + statement = (dfp.StatementBuilder() + .Where(('deliveryRateType = :deliveryRateType AND ' + 'orderId = :orderId')) + .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('deliveryRateType', 'EVENLY') + .Limit(500)) # Get line items by statement. response = line_item_service.getLineItemsByStatement( @@ -76,6 +67,7 @@ def main(client, order_id): else: print 'No line items found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201802/native_style_service/__init__.py b/examples/dfp/v201802/native_style_service/__init__.py new file mode 100755 index 00000000..473ddba1 --- /dev/null +++ b/examples/dfp/v201802/native_style_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. diff --git a/examples/dfp/v201702/native_style_service/create_native_styles.py b/examples/dfp/v201802/native_style_service/create_native_styles.py similarity index 98% rename from examples/dfp/v201702/native_style_service/create_native_styles.py rename to examples/dfp/v201802/native_style_service/create_native_styles.py index f1204fa2..f71eff5a 100755 --- a/examples/dfp/v201702/native_style_service/create_native_styles.py +++ b/examples/dfp/v201802/native_style_service/create_native_styles.py @@ -149,7 +149,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201702') + version='v201802') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/dfp/v201702/native_style_service/get_all_native_styles.py b/examples/dfp/v201802/native_style_service/get_all_native_styles.py similarity index 96% rename from examples/dfp/v201702/native_style_service/get_all_native_styles.py rename to examples/dfp/v201802/native_style_service/get_all_native_styles.py index 0f48cfa8..f5a8cc41 100755 --- a/examples/dfp/v201702/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201802/native_style_service/get_all_native_styles.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201702') + version='v201802') # Create a statement to select native styles. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/network_service/__init__.py b/examples/dfp/v201802/network_service/__init__.py similarity index 100% rename from examples/dfp/v201705/network_service/__init__.py rename to examples/dfp/v201802/network_service/__init__.py diff --git a/examples/dfp/v201705/network_service/get_all_networks.py b/examples/dfp/v201802/network_service/get_all_networks.py similarity index 99% rename from examples/dfp/v201705/network_service/get_all_networks.py rename to examples/dfp/v201802/network_service/get_all_networks.py index 1d835878..df2354a6 100755 --- a/examples/dfp/v201705/network_service/get_all_networks.py +++ b/examples/dfp/v201802/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201705') + network_service = client.GetService('NetworkService', version='v201802') networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201802/network_service/get_current_network.py b/examples/dfp/v201802/network_service/get_current_network.py new file mode 100755 index 00000000..58f87509 --- /dev/null +++ b/examples/dfp/v201802/network_service/get_current_network.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 the current network.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201802') + + current_network = network_service.getCurrentNetwork() + + print ("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/network_service/make_test_network.py b/examples/dfp/v201802/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201702/network_service/make_test_network.py rename to examples/dfp/v201802/network_service/make_test_network.py index f5d0b37f..b3e938fb 100755 --- a/examples/dfp/v201702/network_service/make_test_network.py +++ b/examples/dfp/v201802/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201702') + network_service = client.GetService('NetworkService', version='v201802') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/dfp/v201705/order_service/__init__.py b/examples/dfp/v201802/order_service/__init__.py similarity index 100% rename from examples/dfp/v201705/order_service/__init__.py rename to examples/dfp/v201802/order_service/__init__.py diff --git a/examples/dfp/v201702/order_service/approve_orders.py b/examples/dfp/v201802/order_service/approve_orders.py similarity index 84% rename from examples/dfp/v201702/order_service/approve_orders.py rename to examples/dfp/v201802/order_service/approve_orders.py index e39fba4e..4d23d77b 100755 --- a/examples/dfp/v201702/order_service/approve_orders.py +++ b/examples/dfp/v201802/order_service/approve_orders.py @@ -28,21 +28,14 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') - - # Create query. - values = [{ - 'key': 'today', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.date.today().strftime('%Y-%m-%dT%H:%M:%S') - } - }] - query = ('WHERE status in (\'DRAFT\', \'PENDING_APPROVAL\')' - ' AND endDateTime >= :today AND isArchived = FALSE') + order_service = client.GetService('OrderService', version='v201802') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + today = datetime.date.today() + statement = (dfp.StatementBuilder() + .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' + 'AND endDateTime >= :today AND isArchived = FALSE')) + .WithBindVariable('today', today)) orders_approved = 0 # Get orders by statement. diff --git a/examples/dfp/v201702/order_service/create_orders.py b/examples/dfp/v201802/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201702/order_service/create_orders.py rename to examples/dfp/v201802/order_service/create_orders.py index 8d05ef74..7fe46aae 100755 --- a/examples/dfp/v201702/order_service/create_orders.py +++ b/examples/dfp/v201802/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') + order_service = client.GetService('OrderService', version='v201802') # Create order objects. orders = [] diff --git a/examples/dfp/v201705/order_service/get_all_orders.py b/examples/dfp/v201802/order_service/get_all_orders.py similarity index 99% rename from examples/dfp/v201705/order_service/get_all_orders.py rename to examples/dfp/v201802/order_service/get_all_orders.py index d19fb7f6..c2f7f0c1 100755 --- a/examples/dfp/v201705/order_service/get_all_orders.py +++ b/examples/dfp/v201802/order_service/get_all_orders.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') + order_service = client.GetService('OrderService', version='v201802') # Create a statement to select orders. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/order_service/get_orders_starting_soon.py b/examples/dfp/v201802/order_service/get_orders_starting_soon.py similarity index 73% rename from examples/dfp/v201705/order_service/get_orders_starting_soon.py rename to examples/dfp/v201802/order_service/get_orders_starting_soon.py index 2083de56..7f53e5b3 100755 --- a/examples/dfp/v201705/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201802/order_service/get_orders_starting_soon.py @@ -21,33 +21,22 @@ from datetime import timedelta from googleads import dfp +import pytz def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201705') - query = ('WHERE status = :status and startDateTime >= :now and startDateTime ' - '<= :soon') - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'APPROVED' - }}, - {'key': 'now', - 'value': { - 'xsi_type': 'TextValue', - 'value': datetime.now().strftime('%Y-%m-%dT%H:%M:%S') - }}, - {'key': 'soon', - 'value': { - 'xsi_type': 'TextValue', - 'value': (datetime.now() + timedelta(days=5)) - .strftime('%Y-%m-%dT%H:%M:%S') - }}, - ] + order_service = client.GetService('OrderService', version='v201802') + now = datetime.now(tz=pytz.timezone('America/New_York')) + soon = now + timedelta(days=5) + # Create a statement to select orders. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('status = :status AND startDateTime >= :now ' + 'AND startDateTime <= :soon')) + .WithBindVariable('status', 'APPROVED') + .WithBindVariable('now', now) + .WithBindVariable('soon', soon)) # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/dfp/v201702/order_service/update_orders.py b/examples/dfp/v201802/order_service/update_orders.py similarity index 90% rename from examples/dfp/v201702/order_service/update_orders.py rename to examples/dfp/v201802/order_service/update_orders.py index fe962a03..761c8f47 100755 --- a/examples/dfp/v201702/order_service/update_orders.py +++ b/examples/dfp/v201802/order_service/update_orders.py @@ -28,19 +28,13 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201702') + order_service = client.GetService('OrderService', version='v201802') # Create statement object to select a single order by an ID. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE id = :orderId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :orderId') + .WithBindVariable('orderId', long(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -69,6 +63,7 @@ def main(client, order_id): else: print 'No orders found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/package_service/create_packages.py b/examples/dfp/v201802/package_service/create_packages.py similarity index 99% rename from examples/dfp/v201705/package_service/create_packages.py rename to examples/dfp/v201802/package_service/create_packages.py index 3e22ba82..e3103d0a 100755 --- a/examples/dfp/v201705/package_service/create_packages.py +++ b/examples/dfp/v201802/package_service/create_packages.py @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201705') + package_service = client.GetService('PackageService', version='v201802') # Create local package. package = { diff --git a/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py similarity index 99% rename from examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py rename to examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py index 901d0967..a59ae877 100755 --- a/examples/dfp/v201702/package_service/create_proposal_line_items_from_packages.py +++ b/examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201702') + package_service = client.GetService('PackageService', version='v201802') # Create a statement to select the single package. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/package_service/get_all_packages.py b/examples/dfp/v201802/package_service/get_all_packages.py similarity index 99% rename from examples/dfp/v201702/package_service/get_all_packages.py rename to examples/dfp/v201802/package_service/get_all_packages.py index 1db46c9b..f00ded0c 100755 --- a/examples/dfp/v201702/package_service/get_all_packages.py +++ b/examples/dfp/v201802/package_service/get_all_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201702') + pkg_service = client.GetService('PackageService', version='v201802') # Create a statement to select packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/package_service/get_in_progress_packages.py b/examples/dfp/v201802/package_service/get_in_progress_packages.py similarity index 87% rename from examples/dfp/v201702/package_service/get_in_progress_packages.py rename to examples/dfp/v201802/package_service/get_in_progress_packages.py index 23994ed3..c0feec6d 100755 --- a/examples/dfp/v201702/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201802/package_service/get_in_progress_packages.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'IN_PROGRESS' - }}, - ] + pkg_service = client.GetService('PackageService', version='v201802') # Create a statement to select packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'IN_PROGRESS')) # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/dfp/v201702/placement_service/create_placements.py b/examples/dfp/v201802/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201702/placement_service/create_placements.py rename to examples/dfp/v201802/placement_service/create_placements.py index 485ffe1c..cb1e5335 100755 --- a/examples/dfp/v201702/placement_service/create_placements.py +++ b/examples/dfp/v201802/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') - inventory_service = client.GetService('InventoryService', version='v201702') + placement_service = client.GetService('PlacementService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201802') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201705/placement_service/deactivate_placements.py b/examples/dfp/v201802/placement_service/deactivate_placements.py similarity index 88% rename from examples/dfp/v201705/placement_service/deactivate_placements.py rename to examples/dfp/v201802/placement_service/deactivate_placements.py index 804772cb..cd9b2536 100755 --- a/examples/dfp/v201705/placement_service/deactivate_placements.py +++ b/examples/dfp/v201802/placement_service/deactivate_placements.py @@ -28,18 +28,13 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') + placement_service = client.GetService('PlacementService', version='v201802') # Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :placementId') + .WithBindVariable('placementId', long(placement_id)) + .Limit(1)) # Get placements by statement. placements = placement_service.getPlacementsByStatement( @@ -60,6 +55,7 @@ def main(client, placement_id): else: print 'No placements were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/placement_service/get_active_placements.py b/examples/dfp/v201802/placement_service/get_active_placements.py similarity index 87% rename from examples/dfp/v201702/placement_service/get_active_placements.py rename to examples/dfp/v201802/placement_service/get_active_placements.py index 64e4ff18..d085a5fb 100755 --- a/examples/dfp/v201702/placement_service/get_active_placements.py +++ b/examples/dfp/v201802/placement_service/get_active_placements.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + placement_service = client.GetService('PlacementService', version='v201802') # Create a statement to select placements. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/dfp/v201705/placement_service/get_all_placements.py b/examples/dfp/v201802/placement_service/get_all_placements.py similarity index 99% rename from examples/dfp/v201705/placement_service/get_all_placements.py rename to examples/dfp/v201802/placement_service/get_all_placements.py index 20889bf0..2217dedf 100755 --- a/examples/dfp/v201705/placement_service/get_all_placements.py +++ b/examples/dfp/v201802/placement_service/get_all_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201705') + placement_service = client.GetService('PlacementService', version='v201802') # Create a statement to select placements. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/placement_service/update_placements.py b/examples/dfp/v201802/placement_service/update_placements.py similarity index 57% rename from examples/dfp/v201702/placement_service/update_placements.py rename to examples/dfp/v201802/placement_service/update_placements.py index 8c79b94b..e629c072 100755 --- a/examples/dfp/v201702/placement_service/update_placements.py +++ b/examples/dfp/v201802/placement_service/update_placements.py @@ -28,37 +28,29 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201702') -# Create query. - values = [{ - 'key': 'placementId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': placement_id - } - }] - query = 'WHERE id = :placementId' - statement = dfp.FilterStatement(query, values, 1) + placement_service = client.GetService('PlacementService', version='v201802') + + # Create query. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', placement_id)) # Get placements by statement. - placements = placement_service.getPlacementsByStatement( + page = placement_service.getPlacementsByStatement( statement.ToStatement()) - for placement in placements: - if not placement['targetingDescription']: - placement['targetingDescription'] = 'Generic description' - placement['targetingAdLocation'] = 'All images on sports pages.' - placement['targetingSiteName'] = 'http://code.google.com' - placement['isAdSenseTargetingEnabled'] = 'true' + placement = page['results'][0] + + placement['description'] = 'This placement contains all leaderboards.' # Update placements remotely. - placements = placement_service.updatePlacements(placements) + updated_placements = placement_service.updatePlacements([placement]) - for placement in placements: - print ('Placement with id "%s", name "%s", and AdSense targeting ' - 'enabled "%s" was updated.' - % (placement['id'], placement['name'], - placement['isAdSenseTargetingEnabled'])) + for placement in updated_placements: + print ('Placement with id "%s" and name "%s" was updated.' + % (placement['id'], placement['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/dfp/v201705/premium_rate_service/__init__.py b/examples/dfp/v201802/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201705/premium_rate_service/__init__.py rename to examples/dfp/v201802/premium_rate_service/__init__.py diff --git a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py b/examples/dfp/v201802/premium_rate_service/create_premium_rates.py similarity index 90% rename from examples/dfp/v201702/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201802/premium_rate_service/create_premium_rates.py index 151942f9..d9398c0e 100755 --- a/examples/dfp/v201702/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201802/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201702') + version='v201802') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { @@ -57,7 +57,10 @@ def main(client, rate_card_id): 'adjustmentType': 'ABSOLUTE_VALUE' } - # Create premium_rate objects. + # Create premium rate. + # Associate premium rate with the rate card and set premium information. + # This premium will apply for proposal line items targeting 'any' ad unit + # for both CPM and CPC rate types. premium_rate = { 'rateCardId': rate_card_id, 'pricingMethod': 'ANY_VALUE', diff --git a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py similarity index 97% rename from examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py index 4294dfb3..134fb4b4 100755 --- a/examples/dfp/v201702/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201702') + 'PremiumRateService', version='v201802') # Create a statement to select premium rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 87% rename from examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py index b374c9cf..26962a18 100755 --- a/examples/dfp/v201705/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,17 +25,11 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201705') - query = 'WHERE rateCardId = :rateCardId' - values = [ - {'key': 'rateCardId', - 'value': { - 'xsi_type': 'TextValue', - 'value': rate_card_id - }}, - ] + 'PremiumRateService', version='v201802') # Create a statement to select premium rates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py b/examples/dfp/v201802/premium_rate_service/update_premium_rates.py similarity index 90% rename from examples/dfp/v201702/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201802/premium_rate_service/update_premium_rates.py index 97cdd2e6..05594e2f 100755 --- a/examples/dfp/v201702/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201802/premium_rate_service/update_premium_rates.py @@ -30,18 +30,14 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201702') + version='v201802') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': premium_rate_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(premium_rate_id)) + .Limit(1)) # Get the premium rate. response = premium_rate_service.getPremiumRatesByStatement( diff --git a/examples/dfp/v201702/product_package_item_service/create_product_package_item.py b/examples/dfp/v201802/product_package_item_service/create_product_package_item.py similarity index 99% rename from examples/dfp/v201702/product_package_item_service/create_product_package_item.py rename to examples/dfp/v201802/product_package_item_service/create_product_package_item.py index 3234b2e3..e1647699 100755 --- a/examples/dfp/v201702/product_package_item_service/create_product_package_item.py +++ b/examples/dfp/v201802/product_package_item_service/create_product_package_item.py @@ -32,7 +32,7 @@ def main(client): product_package_item_service = client.GetService('ProductPackageItemService', - version='v201702') + version='v201802') product_package_item = { # Set the product from which the product package item is created. diff --git a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py similarity index 97% rename from examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py rename to examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py index a379b9fc..78937795 100755 --- a/examples/dfp/v201702/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201702') + 'ProductPackageItemService', version='v201802') # Create a statement to select product package items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py similarity index 86% rename from examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py index dfabfe6f..c353c58c 100755 --- a/examples/dfp/v201705/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,17 +25,11 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201705') - query = 'WHERE productPackageId = :productPackageId' - values = [ - {'key': 'productPackageId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_package_id - }}, - ] + 'ProductPackageItemService', version='v201802') # Create a statement to select product package items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productPackageId = :productPackageId') + .WithBindVariable('productPackageId', product_package_id)) # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/dfp/v201702/product_package_service/create_product_packages.py b/examples/dfp/v201802/product_package_service/create_product_packages.py similarity index 96% rename from examples/dfp/v201702/product_package_service/create_product_packages.py rename to examples/dfp/v201802/product_package_service/create_product_packages.py index 4cd048e2..36339471 100755 --- a/examples/dfp/v201702/product_package_service/create_product_packages.py +++ b/examples/dfp/v201802/product_package_service/create_product_packages.py @@ -30,7 +30,7 @@ def main(client): product_package_service = client.GetService('ProductPackageService', - version='v201702') + version='v201802') # Create a local product package. product_package = { diff --git a/examples/dfp/v201702/product_package_service/get_active_product_packages.py b/examples/dfp/v201802/product_package_service/get_active_product_packages.py similarity index 86% rename from examples/dfp/v201702/product_package_service/get_active_product_packages.py rename to examples/dfp/v201802/product_package_service/get_active_product_packages.py index 33facad4..73d509a0 100755 --- a/examples/dfp/v201702/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201802/product_package_service/get_active_product_packages.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201702') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'ACTIVE' - }}, - ] + 'ProductPackageService', version='v201802') # Create a statement to select product packages. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/dfp/v201705/product_package_service/get_all_product_packages.py b/examples/dfp/v201802/product_package_service/get_all_product_packages.py similarity index 97% rename from examples/dfp/v201705/product_package_service/get_all_product_packages.py rename to examples/dfp/v201802/product_package_service/get_all_product_packages.py index 06c1abed..51227e64 100755 --- a/examples/dfp/v201705/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201802/product_package_service/get_all_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201705') + 'ProductPackageService', version='v201802') # Create a statement to select product packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/product_service/__init__.py b/examples/dfp/v201802/product_service/__init__.py similarity index 100% rename from examples/dfp/v201705/product_service/__init__.py rename to examples/dfp/v201802/product_service/__init__.py diff --git a/examples/dfp/v201705/product_service/get_all_products.py b/examples/dfp/v201802/product_service/get_all_products.py similarity index 99% rename from examples/dfp/v201705/product_service/get_all_products.py rename to examples/dfp/v201802/product_service/get_all_products.py index 8ac87c31..9b9fc377 100755 --- a/examples/dfp/v201705/product_service/get_all_products.py +++ b/examples/dfp/v201802/product_service/get_all_products.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201705') + product_service = client.GetService('ProductService', version='v201802') # Create a statement to select products. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/product_service/get_products_for_product_template.py b/examples/dfp/v201802/product_service/get_products_for_product_template.py similarity index 86% rename from examples/dfp/v201705/product_service/get_products_for_product_template.py rename to examples/dfp/v201802/product_service/get_products_for_product_template.py index 94d11ad7..adb92de4 100755 --- a/examples/dfp/v201705/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201802/product_service/get_products_for_product_template.py @@ -24,18 +24,12 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201705') - - query = 'WHERE productTemplateId = :productTemplateId' - values = [ - {'key': 'productTemplateId', - 'value': { - 'xsi_type': 'TextValue', - 'value': product_template_id - }}, - ] + product_service = client.GetService('ProductService', version='v201802') + # Create a statement to select products. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('productTemplateId = :productTemplateId') + .WithBindVariable('productTemplateId', product_template_id)) # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/dfp/v201702/product_service/update_products.py b/examples/dfp/v201802/product_service/update_products.py similarity index 90% rename from examples/dfp/v201702/product_service/update_products.py rename to examples/dfp/v201802/product_service/update_products.py index d645f89e..8697a04c 100755 --- a/examples/dfp/v201702/product_service/update_products.py +++ b/examples/dfp/v201802/product_service/update_products.py @@ -29,18 +29,13 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201702') + product_service = client.GetService('ProductService', version='v201802') # Create statement object to select a single product by an ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, product_id): else: print 'No products found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/product_template_service/__init__.py b/examples/dfp/v201802/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201705/product_template_service/__init__.py rename to examples/dfp/v201802/product_template_service/__init__.py diff --git a/examples/dfp/v201702/product_template_service/activate_product_templates.py b/examples/dfp/v201802/product_template_service/activate_product_templates.py similarity index 89% rename from examples/dfp/v201702/product_template_service/activate_product_templates.py rename to examples/dfp/v201802/product_template_service/activate_product_templates.py index ffda4dd4..6d517f59 100755 --- a/examples/dfp/v201702/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201802/product_template_service/activate_product_templates.py @@ -31,18 +31,13 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201802') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) product_templates_activated = 0 diff --git a/examples/dfp/v201702/product_template_service/create_product_templates.py b/examples/dfp/v201802/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201702/product_template_service/create_product_templates.py rename to examples/dfp/v201802/product_template_service/create_product_templates.py index 98ee1982..d8cbf034 100755 --- a/examples/dfp/v201702/product_template_service/create_product_templates.py +++ b/examples/dfp/v201802/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201802') network_service = client.GetService( - 'NetworkService', version='v201702') + 'NetworkService', version='v201802') # Create a product template. product_template = { diff --git a/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py similarity index 96% rename from examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py rename to examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py index 3d917835..19b4d348 100755 --- a/examples/dfp/v201705/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201802') network_service = client.GetService( - 'NetworkService', version='v201705') + 'NetworkService', version='v201802') product_template = { # Setting required Marketplace information. diff --git a/examples/dfp/v201705/product_template_service/get_all_product_templates.py b/examples/dfp/v201802/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201705/product_template_service/get_all_product_templates.py rename to examples/dfp/v201802/product_template_service/get_all_product_templates.py index 7114a26a..11f57816 100755 --- a/examples/dfp/v201705/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201802/product_template_service/get_all_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') + 'ProductTemplateService', version='v201802') # Create a statement to select product templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py similarity index 85% rename from examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py index a5108bf0..6c6e6f1b 100755 --- a/examples/dfp/v201705/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201705') - query = 'WHERE lineItemType = :lineItemType' - values = [ - {'key': 'lineItemType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'SPONSORSHIP' - }}, - ] + 'ProductTemplateService', version='v201802') # Create a statement to select product templates. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('lineItemType = :lineItemType') + .WithBindVariable('lineItemType', 'SPONSORSHIP')) # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/dfp/v201702/product_template_service/update_product_templates.py b/examples/dfp/v201802/product_template_service/update_product_templates.py similarity index 90% rename from examples/dfp/v201702/product_template_service/update_product_templates.py rename to examples/dfp/v201802/product_template_service/update_product_templates.py index 819a9772..36dda17f 100755 --- a/examples/dfp/v201702/product_template_service/update_product_templates.py +++ b/examples/dfp/v201802/product_template_service/update_product_templates.py @@ -30,18 +30,14 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201702') + 'ProductTemplateService', version='v201802') # Create a statement to select a single product template by ID. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': product_template_id - } - }] - query = 'WHERE id = :id ORDER BY id ASC' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) # Get product templates by statement. response = product_template_service.getProductTemplatesByStatement( diff --git a/examples/dfp/v201705/proposal_line_item_service/__init__.py b/examples/dfp/v201802/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201705/proposal_line_item_service/__init__.py rename to examples/dfp/v201802/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py similarity index 89% rename from examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py index 8584b71b..095c02b1 100755 --- a/examples/dfp/v201702/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py @@ -31,18 +31,13 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') + 'ProposalLineItemService', version='v201802') # Create query. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) proposal_line_items_archived = 0 diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 82% rename from examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py index 19ebceab..ed61a734 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -18,11 +18,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set the ID of the programmatic proposal that the proposal line item will # belong to. @@ -39,13 +40,16 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + 'ProposalLineItemService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') # Get the root ad unit to target. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + # Create a single programmatic proposal line item. proposal_line_item = { # Setting required Marketplace information. @@ -64,27 +68,8 @@ def main(client, proposal_id, product_id, rate_card_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'goal': { 'units': '1000', 'unitType': 'IMPRESSIONS', diff --git a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 82% rename from examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 2338f4ca..e49b1679 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -18,11 +18,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -33,8 +34,11 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + 'ProposalLineItemService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) # Get the root ad unit to target. root_ad_unit_id = ( @@ -58,27 +62,8 @@ def main(client, proposal_id, product_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'creativePlaceholders': [{ 'size': { 'width': '300', diff --git a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py similarity index 82% rename from examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py index bc746b66..25106570 100755 --- a/examples/dfp/v201702/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py @@ -22,11 +22,12 @@ """ -from datetime import date +import datetime import uuid # Import appropriate modules from the client library. from googleads import dfp +import pytz # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -41,8 +42,11 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + 'ProposalLineItemService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) # Get the root ad unit to target. root_ad_unit_id = ( @@ -61,27 +65,8 @@ def main(client, proposal_id, product_id, rate_card_id): } } }, - 'startDateTime': { - 'date': { - 'year': str(date.today().year), - 'month': str(date.today().month), - 'day': str(date.today().day) - }, - 'hour': '23', - 'minute': '59', - 'second': '59' - }, - 'endDateTime': { - 'date': { - 'year': str(date.today().year + 1), - 'month': '9', - 'day': '30' - }, - 'hour': '0', - 'minute': '0', - 'second': '0', - 'timeZoneID': 'America/Los_Angeles' - }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, 'deliveryRateType': 'EVENLY', 'creativeRotationType': 'OPTIMIZED', 'billingCap': 'CAPPED_CUMULATIVE', diff --git a/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py similarity index 97% rename from examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py index 254e0dd0..a448e012 100755 --- a/examples/dfp/v201705/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') + 'ProposalLineItemService', version='v201802') # Create a statement to select proposal line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 86% rename from examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 3600e25d..03368306 100755 --- a/examples/dfp/v201705/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,17 +25,11 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') - query = 'WHERE proposalId = :proposalId' - values = [ - {'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - }}, - ] + 'ProposalLineItemService', version='v201802') # Create a statement to select proposal line items. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('proposalId = :proposalId') + .WithBindVariable('proposalId', proposal_id)) # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py similarity index 89% rename from examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py index 16f4bc98..4a559c5f 100755 --- a/examples/dfp/v201705/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py @@ -31,19 +31,14 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201705') + 'ProposalLineItemService', version='v201802') # Create statement to select a proposal line item. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_line_item_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) # Get proposal line items by statement. response = proposal_line_item_service.getProposalLineItemsByStatement( diff --git a/examples/dfp/v201705/proposal_service/__init__.py b/examples/dfp/v201802/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201705/proposal_service/__init__.py rename to examples/dfp/v201802/proposal_service/__init__.py diff --git a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201802/proposal_service/create_programmatic_proposals.py similarity index 98% rename from examples/dfp/v201702/proposal_service/create_programmatic_proposals.py rename to examples/dfp/v201802/proposal_service/create_programmatic_proposals.py index 5b009a95..b367a445 100755 --- a/examples/dfp/v201702/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201802/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201702') - network_service = client.GetService('NetworkService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 99% rename from examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 1db0c9e0..9021632a 100755 --- a/examples/dfp/v201705/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201705/proposal_service/create_proposals.py b/examples/dfp/v201802/proposal_service/create_proposals.py similarity index 99% rename from examples/dfp/v201705/proposal_service/create_proposals.py rename to examples/dfp/v201802/proposal_service/create_proposals.py index d2a2e346..5cfe3820 100755 --- a/examples/dfp/v201705/proposal_service/create_proposals.py +++ b/examples/dfp/v201802/proposal_service/create_proposals.py @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201705') - network_service = client.GetService('NetworkService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') + network_service = client.GetService('NetworkService', version='v201802') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201702/proposal_service/get_all_proposals.py b/examples/dfp/v201802/proposal_service/get_all_proposals.py similarity index 99% rename from examples/dfp/v201702/proposal_service/get_all_proposals.py rename to examples/dfp/v201802/proposal_service/get_all_proposals.py index 53ad307c..ee9a6082 100755 --- a/examples/dfp/v201702/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201802/proposal_service/get_all_proposals.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201802') # Create a statement to select proposals. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/proposal_service/get_marketplace_comments.py b/examples/dfp/v201802/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/dfp/v201705/proposal_service/get_marketplace_comments.py rename to examples/dfp/v201802/proposal_service/get_marketplace_comments.py index 56839ca9..63e4683b 100755 --- a/examples/dfp/v201705/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201802/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201705') + 'ProposalService', version='v201802') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py similarity index 87% rename from examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py rename to examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py index 0da9e017..6f6d47d6 100755 --- a/examples/dfp/v201705/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py @@ -22,17 +22,11 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') - query = 'WHERE status = :status' - values = [ - {'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PENDING_APPROVAL' - }}, - ] + proposal_service = client.GetService('ProposalService', version='v201802') # Create a statement to select proposals. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('status = :status') + .WithBindVariable('status', 'PENDING_APPROVAL')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py similarity index 89% rename from examples/dfp/v201702/proposal_service/request_buyers_acceptance.py rename to examples/dfp/v201802/proposal_service/request_buyers_acceptance.py index 89f3468a..baabcef4 100755 --- a/examples/dfp/v201702/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py @@ -26,20 +26,12 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201802') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo programmatic proposals were pushed to Marketplace.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py similarity index 88% rename from examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py index f87cf2eb..98cf90cb 100755 --- a/examples/dfp/v201702/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py @@ -28,20 +28,12 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201702') + proposal_service = client.GetService('ProposalService', version='v201802') # Create query. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 # Get proposals by statement. @@ -68,6 +60,7 @@ def main(client, proposal_id): else: print '\nNo proposals were approved.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/proposal_service/update_proposals.py b/examples/dfp/v201802/proposal_service/update_proposals.py similarity index 89% rename from examples/dfp/v201705/proposal_service/update_proposals.py rename to examples/dfp/v201802/proposal_service/update_proposals.py index 7f4e6d13..3cbe6e7d 100755 --- a/examples/dfp/v201705/proposal_service/update_proposals.py +++ b/examples/dfp/v201802/proposal_service/update_proposals.py @@ -28,19 +28,14 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201705') + proposal_service = client.GetService('ProposalService', version='v201802') # Create statement object to select a single proposal by an ID. - values = [{ - 'key': 'proposalId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': proposal_id - } - }] - query = 'WHERE id = :proposalId' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :proposalId') + .WithBindVariable('proposalId', long(proposal_id)) + .Limit(1)) # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) @@ -66,6 +61,7 @@ def main(client, proposal_id): else: print 'No proposals found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/publisher_query_language_service/__init__.py b/examples/dfp/v201802/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201705/publisher_query_language_service/__init__.py rename to examples/dfp/v201802/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py index 6983c467..49c456d6 100755 --- a/examples/dfp/v201702/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201802') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py b/examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py new file mode 100755 index 00000000..e3c0ac25 --- /dev/null +++ b/examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 browsers available to target from the Browser table. + +Other tables include 'Bandwidth_Group', 'Browser_Language', +'Device_Capability', 'Operating_System', etc... + +A full list of available criteria tables can be found at +https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService +""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201802') + + with tempfile.NamedTemporaryFile( + prefix='browser_data_', + suffix='.csv', mode='w', delete=False) as browser_data_file: + + browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion ' + 'FROM Browser ' + 'ORDER BY BrowserName ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + browser_pql_query, browser_data_file) + + print 'Saved browser data to... %s' % browser_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py index bc5ed6a9..51243ca7 100755 --- a/examples/dfp/v201702/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201702') + data_downloader = client.GetDataDownloader(version='v201802') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py new file mode 100755 index 00000000..80183382 --- /dev/null +++ b/examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 downloads geo targeting constants using PQL.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the type of geo target to query for. +GEO_TARGET_TYPE = 'City' + + +def main(client, geo_target_type): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201802') + + with tempfile.NamedTemporaryFile( + prefix='geo_data_', + suffix='.csv', mode='w', delete=False) as geo_data_file: + + geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' + 'CountryCode ' + 'FROM Geo_Target ' + 'WHERE Type = :type AND Targetable = true ' + 'ORDER BY CountryCode ASC, Name ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + geo_pql_query, geo_data_file, {'type': geo_target_type}) + + print 'Saved geo data to... %s' % geo_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, GEO_TARGET_TYPE) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py new file mode 100755 index 00000000..0d14cd53 --- /dev/null +++ b/examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 fetches line items from the pql table with a LIKE clause.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201802') + + with tempfile.NamedTemporaryFile( + prefix='line_items_', + suffix='.csv', mode='w', delete=False) as line_items_file: + + line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item " + "WHERE Name LIKE 'line item%' " + "ORDER BY Id ASC") + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + line_items_pql_query, line_items_file) + + print 'Saved line items to... %s' % line_items_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py similarity index 66% rename from examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py rename to examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py index 70c30b66..61f13440 100755 --- a/examples/dfp/v201705/publisher_query_language_service/get_recent_changes.py +++ b/examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py @@ -31,52 +31,23 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201705') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201802') - end_date = date.today() + end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) - initial_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE ChangeDateTime > :startDateTime ' - 'AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - pagination_query = ( - 'SELECT Id, ChangeDateTime, EntityId, EntityType, Operation, UserId ' - 'FROM Change_History ' - 'WHERE Id < :id ' - 'AND ChangeDateTime > :startDateTime AND ChangeDateTime < :endDateTime ' - 'ORDER BY ChangeDateTime DESC') - values = [ - { - 'key': 'startDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': start_date.year, - 'month': start_date.month, - 'day': start_date.day - } - } - } - }, - { - 'key': 'endDateTime', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': end_date.year, - 'month': end_date.month, - 'day': end_date.day - } - } - } - } - ] - - statement = dfp.FilterStatement(initial_query, values) + initial_query = ('ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime') + pagination_query = 'Id < :id AND ' + initial_query + + statement = (dfp.StatementBuilder() + .Select(('Id, ChangeDateTime, EntityId, EntityType, ' + 'Operation, UserId')) + .From('Change_History') + .Where(initial_query) + .OrderBy('ChangeDateTime', ascending=False) + .WithBindVariable('startDateTime', start_date) + .WithBindVariable('endDateTime', end_date)) + keep_iterating = True i = 0 total_rows = [] @@ -94,8 +65,11 @@ def main(client): last_row = rows[-1] last_id = last_row['values'][0]['value'] i += 1 - statement = UpdateFilterStatement( - statement, pagination_query, values, last_id) + + # Update the statement using the earliest row in the previous result. + statement.Where(pagination_query) + statement.WithBindVariable('id', last_id) + print ('%d) %d changes prior to ID "%s" were found.\n' % (i, rows_length, last_id)) @@ -109,34 +83,6 @@ def main(client): print ConvertValueForCsv(row) -def UpdateFilterStatement(statement, query, values, last_id): - """Updates the FilterStatement in order to page through results. - - Args: - statement: an instantiated FilterStatement. - query: a str query that will be used to update the FilterStatement. - values: a list of bind variables to be updated. - last_id: a str representing the earliest change ID in a result set. - - Returns: - FilterStatement the updated statement. - """ - # Use the earliest change ID in the result set to page. - updated_values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_id - } - }] - updated_values.extend(values) - - statement.where_clause = query - statement.values = updated_values - - return statement - - def ConvertValueForCsv(pql_value): """Sanitizes a field value from a Value object to a CSV suitable format. diff --git a/examples/dfp/v201705/rate_card_service/__init__.py b/examples/dfp/v201802/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201705/rate_card_service/__init__.py rename to examples/dfp/v201802/rate_card_service/__init__.py diff --git a/examples/dfp/v201705/rate_card_service/create_rate_cards.py b/examples/dfp/v201802/rate_card_service/create_rate_cards.py similarity index 99% rename from examples/dfp/v201705/rate_card_service/create_rate_cards.py rename to examples/dfp/v201802/rate_card_service/create_rate_cards.py index 38142f18..bbb198d0 100755 --- a/examples/dfp/v201705/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/create_rate_cards.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201705') + rate_card_service = client.GetService('RateCardService', version='v201802') # Create a rate card. rate_card = { diff --git a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py similarity index 99% rename from examples/dfp/v201702/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201802/rate_card_service/get_all_rate_cards.py index a3753055..c0fd27a7 100755 --- a/examples/dfp/v201702/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201702') + rate_card_service = client.GetService('RateCardService', version='v201802') # Create a statement to select rate cards. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py similarity index 87% rename from examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py rename to examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py index c300b3b9..5220fc13 100755 --- a/examples/dfp/v201702/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py @@ -23,17 +23,11 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201702') - query = 'WHERE forMarketplace = :forMarketplace' - values = [ - {'key': 'forMarketplace', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': 'true' - }}, - ] + rate_card_service = client.GetService('RateCardService', version='v201802') # Create a statement to select rate cards. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('forMarketplace = :forMarketplace') + .WithBindVariable('forMarketplace', True)) # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 97% rename from examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 98a6c659..bbb62cd9 100755 --- a/examples/dfp/v201705/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201705')) + 'ReconciliationLineItemReportService', version='v201802')) # Create a statement to select reconciliation line item reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 97% rename from examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index f80694cf..bdcd877e 100755 --- a/examples/dfp/v201705/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201705')) + 'ReconciliationLineItemReportService', version='v201802')) # Create a statement to select a reconciliation line item report. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 60c73c91..9926d667 100755 --- a/examples/dfp/v201702/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,17 +25,12 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201702') - query = 'WHERE reconciliationReportId = :reconciliationReportId' - values = [ - {'key': 'reconciliationReportId', - 'value': { - 'xsi_type': 'TextValue', - 'value': reconciliation_report_id - }}, - ] + 'ReconciliationOrderReportService', version='v201802') # Create a statement to select reconciliation order reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('reconciliationReportId = :reconciliationReportId') + .WithBindVariable('reconciliationReportId', + reconciliation_report_id)) # Retrieve a small amount of reconciliation order reports at a time, paging # through until all reconciliation order reports have been retrieved. diff --git a/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 97% rename from examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py index f282ce56..07b8c4f4 100755 --- a/examples/dfp/v201705/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201705')) + 'ReconciliationOrderReportService', version='v201802')) # Create a statement to select reconciliation order reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 46803c99..b2fe2fbc 100755 --- a/examples/dfp/v201705/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -27,18 +27,14 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201705') - query = ('WHERE reconciliationReportId = %s AND ' - 'lineItemId != :lineItemId') % reconciliation_report_id - values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': '0' - } - }] + 'ReconciliationReportRowService', version='v201802') + # Create a statement to select reconciliation report rows. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('reconciliationReportId = :reportId ' + 'AND lineItemId != :lineItemId')) + .WithBindVariable('lineItemId', 0) + .WithBindVariable('reportId', long(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. diff --git a/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 97% rename from examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py index 38158171..fa7f2cc1 100755 --- a/examples/dfp/v201705/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201705')) + 'ReconciliationReportRowService', version='v201802')) # Create a statement to select reconciliation report rows. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 97% rename from examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py index 35287882..7c465090 100755 --- a/examples/dfp/v201702/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201702') + 'ReconciliationReportService', version='v201802') # Create a statement to select reconciliation reports. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 86% rename from examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 64b14308..4674bc93 100755 --- a/examples/dfp/v201702/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,21 +26,15 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201702') + 'ReconciliationReportService', version='v201802') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) - query = 'WHERE startDate = :startDate' - values = [ - {'key': 'startDate', - 'value': { - 'xsi_type': 'TextValue', - 'value': last_month.strftime('%Y-%m-01') - }}, - ] # Create a statement to select reconciliation reports. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('startDate = :startDate') + .WithBindVariable('startDate', last_month)) # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. diff --git a/examples/dfp/v201705/report_service/__init__.py b/examples/dfp/v201802/report_service/__init__.py similarity index 100% rename from examples/dfp/v201705/report_service/__init__.py rename to examples/dfp/v201802/report_service/__init__.py diff --git a/examples/dfp/v201802/report_service/run_ad_exchange_report.py b/examples/dfp/v201802/report_service/run_ad_exchange_report.py new file mode 100755 index 00000000..f6ebfee5 --- /dev/null +++ b/examples/dfp/v201802/report_service/run_ad_exchange_report.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Runs a report on Ad Exchange data via the DFP API.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201802') + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'], + 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS', + 'AD_EXCHANGE_ESTIMATED_REVENUE'], + 'dateRangeType': 'LAST_WEEK', + 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time + 'adxReportCurrency': 'EUR' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/report_service/run_delivery_report.py b/examples/dfp/v201802/report_service/run_delivery_report.py similarity index 88% rename from examples/dfp/v201702/report_service/run_delivery_report.py rename to examples/dfp/v201802/report_service/run_delivery_report.py index 74fdb3f3..48fa9bcf 100755 --- a/examples/dfp/v201702/report_service/run_delivery_report.py +++ b/examples/dfp/v201802/report_service/run_delivery_report.py @@ -32,15 +32,11 @@ def main(client, order_id): # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - filter_statement = {'query': 'WHERE ORDER_ID = :id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('ORDER_ID = :id') + .WithBindVariable('id', long(order_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Set the start and end dates of the report to run (past 8 days). end_date = datetime.now().date() @@ -52,7 +48,7 @@ def main(client, order_id): 'dimensions': ['ORDER_ID', 'ORDER_NAME'], 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', 'ORDER_END_DATE_TIME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], @@ -63,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201802') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201702/report_service/run_inventory_report.py b/examples/dfp/v201802/report_service/run_inventory_report.py similarity index 83% rename from examples/dfp/v201702/report_service/run_inventory_report.py rename to examples/dfp/v201802/report_service/run_inventory_report.py index 01994fe7..be8e2835 100755 --- a/examples/dfp/v201702/report_service/run_inventory_report.py +++ b/examples/dfp/v201802/report_service/run_inventory_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report equal to the "Whole network report" on the DFP website.""" +"""This example runs a typical daily inventory report.""" import tempfile @@ -25,24 +25,20 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201702') + network_service = client.GetService('NetworkService', version='v201802') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201802') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - values = [{ - 'key': 'parent_ad_unit_id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': root_ad_unit_id - } - }] - filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id', - 'values': values} + statement = (dfp.StatementBuilder() + .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') + .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) # Create report job. report_job = { @@ -55,7 +51,7 @@ def main(client): 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', - 'statement': filter_statement + 'statement': statement.ToStatement() } } diff --git a/examples/dfp/v201702/report_service/run_reach_report.py b/examples/dfp/v201802/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201702/report_service/run_reach_report.py rename to examples/dfp/v201802/report_service/run_reach_report.py index 10e06150..1f83a5ec 100755 --- a/examples/dfp/v201702/report_service/run_reach_report.py +++ b/examples/dfp/v201802/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201802') # Create report job. report_job = { diff --git a/examples/dfp/v201802/report_service/run_report_and_create_match_table.py b/examples/dfp/v201802/report_service/run_report_and_create_match_table.py new file mode 100755 index 00000000..def767a9 --- /dev/null +++ b/examples/dfp/v201802/report_service/run_report_and_create_match_table.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Runs a report for LineItems with additional data from a PQL table. + +Fetches a basic report over a network's LineItems and then adds some +extra columns which might be useful for future analysis, such as +LineItemType, from the PQL Line_Item table, creating a match table. +""" + +from datetime import date +from datetime import timedelta +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + +try: + import pandas +except ImportError: + raise ImportError('This example requires the pandas library to be installed.') + + +def main(client): + # Set the start and end dates of the report to run (past 8 days). + end_date = date.today() + start_date = end_date - timedelta(days=8) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': start_date, + 'endDate': end_date + } + } + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201802') + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + with tempfile.NamedTemporaryFile( + suffix='.csv.gz', mode='wb', delete=False) as report_file: + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, 'CSV_DUMP', report_file) + + # Create a PQL query to fetch the line item data + line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem') + + # Download the response from PQL select statement + line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) + + # Use pandas to join the two csv files into a match table + report = pandas.read_csv(report_file.name) + line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0]) + merged_result = pandas.merge(report, line_items, + left_on='Dimension.LINE_ITEM_ID', right_on='id') + merged_result.to_csv('~/complete_line_items_report.csv', index=False) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py b/examples/dfp/v201802/report_service/run_report_with_custom_fields.py similarity index 85% rename from examples/dfp/v201702/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201802/report_service/run_report_with_custom_fields.py index 5ad2f680..0b7aa111 100755 --- a/examples/dfp/v201702/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201802/report_service/run_report_with_custom_fields.py @@ -28,22 +28,14 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201702') + line_item_service = client.GetService('LineItemService', version='v201802') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201802') # Filter for line items of a given order. - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }] - query = 'WHERE orderId = :orderId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('orderId = :orderId') + .WithBindVariable('orderId', long(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -62,14 +54,16 @@ def main(client, order_id): else: break - # Create statement object to filter for an order. - filter_statement = {'query': query, 'values': values} + # Modify statement for reports + statement.limit = None + statement.offset = None + statement.Where('ORDER_ID = :orderId') # Create report job. report_job = { 'reportQuery': { 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': filter_statement, + 'statement': statement.ToStatement(), 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', 'customFieldIds': list(custom_field_ids) diff --git a/examples/dfp/v201702/report_service/run_sales_report.py b/examples/dfp/v201802/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201702/report_service/run_sales_report.py rename to examples/dfp/v201802/report_service/run_sales_report.py index 5aab075c..d8411c93 100755 --- a/examples/dfp/v201702/report_service/run_sales_report.py +++ b/examples/dfp/v201802/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201802') # Create report job. report_job = { diff --git a/examples/dfp/v201702/report_service/run_saved_query.py b/examples/dfp/v201802/report_service/run_saved_query.py similarity index 89% rename from examples/dfp/v201702/report_service/run_saved_query.py rename to examples/dfp/v201802/report_service/run_saved_query.py index 7f3ccad5..ca0815df 100755 --- a/examples/dfp/v201702/report_service/run_saved_query.py +++ b/examples/dfp/v201802/report_service/run_saved_query.py @@ -28,21 +28,16 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201702') + report_service = client.GetService('ReportService', version='v201802') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201702') + report_downloader = client.GetDataDownloader(version='v201802') # Create statement object to filter for an order. - values = [{ - 'key': 'id', - 'value': { - 'xsi_type': 'NumberValue', - 'value': saved_query_id - } - }] - query = 'WHERE id = :id' - statement = dfp.FilterStatement(query, values, 1) + statement = (dfp.StatementBuilder() + .Where('id = :id') + .WithBindVariable('id', long(saved_query_id)) + .Limit(1)) response = report_service.getSavedQueriesByStatement( statement.ToStatement()) diff --git a/examples/dfp/v201705/suggested_ad_unit_service/__init__.py b/examples/dfp/v201802/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201705/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201802/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 88% rename from examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py index cdf09c6f..b850097f 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,20 +29,12 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201702') - - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': THRESHOLD_NUMBER_OF_REQUESTS - } - }] - - query = 'WHERE numRequests > :numRequests' + 'SuggestedAdUnitService', version='v201802') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests > :numRequests') + .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 # Get suggested ad units by statement. diff --git a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py index cc211cfe..d8f8e923 100755 --- a/examples/dfp/v201702/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201702') + 'SuggestedAdUnitService', version='v201802') # Create a statement to select suggested ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 86% rename from examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 355b47c3..8b2f5184 100755 --- a/examples/dfp/v201705/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,17 +25,11 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201705') - query = 'WHERE numRequests >= :numRequests' - values = [ - {'key': 'numRequests', - 'value': { - 'xsi_type': 'TextValue', - 'value': num_requests - }}, - ] + 'SuggestedAdUnitService', version='v201802') # Create a statement to select suggested ad units. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests >= :numRequests') + .WithBindVariable('numRequests', long(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/dfp/v201705/team_service/__init__.py b/examples/dfp/v201802/team_service/__init__.py similarity index 100% rename from examples/dfp/v201705/team_service/__init__.py rename to examples/dfp/v201802/team_service/__init__.py diff --git a/examples/dfp/v201702/team_service/create_teams.py b/examples/dfp/v201802/team_service/create_teams.py similarity index 96% rename from examples/dfp/v201702/team_service/create_teams.py rename to examples/dfp/v201802/team_service/create_teams.py index f76ae2db..5265d8d0 100755 --- a/examples/dfp/v201702/team_service/create_teams.py +++ b/examples/dfp/v201802/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201702') + team_service = client.GetService('TeamService', version='v201802') # Create team objects. teams = [] diff --git a/examples/dfp/v201702/team_service/get_all_teams.py b/examples/dfp/v201802/team_service/get_all_teams.py similarity index 96% rename from examples/dfp/v201702/team_service/get_all_teams.py rename to examples/dfp/v201802/team_service/get_all_teams.py index 03fdf947..11e8653e 100755 --- a/examples/dfp/v201702/team_service/get_all_teams.py +++ b/examples/dfp/v201802/team_service/get_all_teams.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201702') + team_service = client.GetService('TeamService', version='v201802') # Create a statement to select teams. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/team_service/update_teams.py b/examples/dfp/v201802/team_service/update_teams.py similarity index 87% rename from examples/dfp/v201705/team_service/update_teams.py rename to examples/dfp/v201802/team_service/update_teams.py index aad3c8e6..2e6a8c45 100755 --- a/examples/dfp/v201705/team_service/update_teams.py +++ b/examples/dfp/v201802/team_service/update_teams.py @@ -34,18 +34,12 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201705') + team_service = client.GetService('TeamService', version='v201802') # Create a filter statement to select a single team by ID. - values = [{ - 'key': 'teamId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': team_id - } - }] - query = 'WHERE id = :teamId' - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :teamId') + .WithBindVariable('teamId', long(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -67,6 +61,7 @@ def main(client, team_id): else: print 'No teams found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/user_service/__init__.py b/examples/dfp/v201802/user_service/__init__.py similarity index 100% rename from examples/dfp/v201705/user_service/__init__.py rename to examples/dfp/v201802/user_service/__init__.py diff --git a/examples/dfp/v201702/user_service/create_users.py b/examples/dfp/v201802/user_service/create_users.py similarity index 96% rename from examples/dfp/v201702/user_service/create_users.py rename to examples/dfp/v201802/user_service/create_users.py index f375d01c..021bb596 100755 --- a/examples/dfp/v201702/user_service/create_users.py +++ b/examples/dfp/v201802/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201802') # Create user objects. users = [ diff --git a/examples/dfp/v201705/user_service/deactivate_users.py b/examples/dfp/v201802/user_service/deactivate_users.py similarity index 86% rename from examples/dfp/v201705/user_service/deactivate_users.py rename to examples/dfp/v201802/user_service/deactivate_users.py index cf9590a6..771357d1 100755 --- a/examples/dfp/v201705/user_service/deactivate_users.py +++ b/examples/dfp/v201802/user_service/deactivate_users.py @@ -30,20 +30,12 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201802') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -66,6 +58,7 @@ def main(client, user_id): else: print 'No users were deactivated.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/user_service/get_all_roles.py b/examples/dfp/v201802/user_service/get_all_roles.py similarity index 100% rename from examples/dfp/v201705/user_service/get_all_roles.py rename to examples/dfp/v201802/user_service/get_all_roles.py diff --git a/examples/dfp/v201702/user_service/get_all_users.py b/examples/dfp/v201802/user_service/get_all_users.py similarity index 96% rename from examples/dfp/v201702/user_service/get_all_users.py rename to examples/dfp/v201802/user_service/get_all_users.py index e35e600b..36c26a79 100755 --- a/examples/dfp/v201702/user_service/get_all_users.py +++ b/examples/dfp/v201802/user_service/get_all_users.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201802') # Create a statement to select users. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/user_service/get_current_user.py b/examples/dfp/v201802/user_service/get_current_user.py similarity index 94% rename from examples/dfp/v201705/user_service/get_current_user.py rename to examples/dfp/v201802/user_service/get_current_user.py index f2d762de..d04dcb56 100755 --- a/examples/dfp/v201705/user_service/get_current_user.py +++ b/examples/dfp/v201802/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201705') + user_service = client.GetService('UserService', version='v201802') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201702/user_service/get_user_by_email_address.py b/examples/dfp/v201802/user_service/get_user_by_email_address.py similarity index 85% rename from examples/dfp/v201702/user_service/get_user_by_email_address.py rename to examples/dfp/v201802/user_service/get_user_by_email_address.py index 5e661c78..5c1cdb20 100755 --- a/examples/dfp/v201702/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201802/user_service/get_user_by_email_address.py @@ -24,17 +24,11 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') - query = 'WHERE email = :email' - values = [ - {'key': 'email', - 'value': { - 'xsi_type': 'TextValue', - 'value': email_address - }}, - ] + user_service = client.GetService('UserService', version='v201802') # Create a statement to select users. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('email = :email') + .WithBindVariable('email', email_address)) # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/dfp/v201702/user_service/update_users.py b/examples/dfp/v201802/user_service/update_users.py similarity index 83% rename from examples/dfp/v201702/user_service/update_users.py rename to examples/dfp/v201802/user_service/update_users.py index 07940545..2786043e 100755 --- a/examples/dfp/v201702/user_service/update_users.py +++ b/examples/dfp/v201802/user_service/update_users.py @@ -28,20 +28,12 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201702') + user_service = client.GetService('UserService', version='v201802') # Create query. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE id = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -59,6 +51,7 @@ def main(client, user_id): else: print 'No users found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/user_team_association_service/__init__.py b/examples/dfp/v201802/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201705/user_team_association_service/__init__.py rename to examples/dfp/v201802/user_team_association_service/__init__.py diff --git a/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201705/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201802/user_team_association_service/create_user_team_associations.py index 28a2bf1a..6f55df77 100755 --- a/examples/dfp/v201705/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') + 'UserTeamAssociationService', version='v201802') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py similarity index 87% rename from examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py index c971f0d8..85d04bc8 100755 --- a/examples/dfp/v201702/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py @@ -35,20 +35,12 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') + 'UserTeamAssociationService', version='v201802') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -62,10 +54,14 @@ def main(client, user_id): print ('Number of teams that the user will be removed from: %s' % len(user_team_associations)) + # Action doesn't require limit/offset + statement.limit = None + statement.offset = None + # Perform action. result = user_team_association_service.performUserTeamAssociationAction( {'xsi_type': 'DeleteUserTeamAssociations'}, - {'query': query, 'values': values}) + statement.ToStatement()) # Display results. if result and int(result['numChanges']) > 0: @@ -74,6 +70,7 @@ def main(client, user_id): else: print 'No user team associations were deleted.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py similarity index 97% rename from examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py index 6343bbae..631a9734 100755 --- a/examples/dfp/v201702/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201702') + 'UserTeamAssociationService', version='v201802') # Create a statement to select user team associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py similarity index 87% rename from examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py index 7e492989..8413cad0 100755 --- a/examples/dfp/v201705/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py @@ -25,17 +25,11 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') - query = 'WHERE userId = :userId' - values = [ - {'key': 'userId', - 'value': { - 'xsi_type': 'TextValue', - 'value': user_id - }}, - ] + 'UserTeamAssociationService', version='v201802') # Create a statement to select user team associations. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py similarity index 89% rename from examples/dfp/v201705/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201802/user_team_association_service/update_user_team_associations.py index 2266e140..4f88e43f 100755 --- a/examples/dfp/v201705/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py @@ -37,20 +37,12 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201705') + 'UserTeamAssociationService', version='v201802') # Create filter text to select user team associations by the user ID. - values = [{ - 'key': 'userId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': user_id - } - }] - query = 'WHERE userId = :userId' - - # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -79,6 +71,7 @@ def main(client, user_id): else: print 'No user team associations found to update.' + if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201705/workflow_request_service/__init__.py b/examples/dfp/v201802/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201705/workflow_request_service/__init__.py rename to examples/dfp/v201802/workflow_request_service/__init__.py diff --git a/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py similarity index 76% rename from examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py index 503c9eab..5efc45eb 100755 --- a/examples/dfp/v201705/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py @@ -31,37 +31,15 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201705') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') + version='v201802') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) workflow_approval_requests_approved = 0 # Get workflow approval requests by statement. diff --git a/examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py similarity index 87% rename from examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py rename to examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py index c1276194..b2635616 100755 --- a/examples/dfp/v201705/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py @@ -26,17 +26,11 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_APPROVAL_REQUEST' - }}, - ] + 'WorkflowRequestService', version='v201802') # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py similarity index 86% rename from examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py index 7e7da01f..71c4541e 100755 --- a/examples/dfp/v201705/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,17 +26,11 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201705') - query = 'WHERE type = :type' - values = [ - {'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - }}, - ] + 'WorkflowRequestService', version='v201802') # Create a statement to select workflow requests. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) # Retrieve a small amount of workflow requests at a time, paging # through until all workflow requests have been retrieved. diff --git a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 78% rename from examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py index fbbb267d..394922c9 100755 --- a/examples/dfp/v201702/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,37 +31,15 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201702') - - # Create query. - values = [ - { - 'key': 'entityId', - 'value': { - 'xsi_type': 'TextValue', - 'value': proposal_id - } - }, - { - 'key': 'entityType', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'PROPOSAL' - } - }, - { - 'key': 'type', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'WORKFLOW_EXTERNAL_CONDITION_REQUEST' - } - } - ] - query = ('WHERE entityId = :entityId and entityType = :entityType ' - 'and type = :type') + version='v201802') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) workflow_external_condition_requests_triggered = 0 # Get workflow external condition requests by statement. diff --git a/googleads/adwords.py b/googleads/adwords.py index 02c901a3..caf15a07 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -15,6 +15,7 @@ """Client library for the AdWords API.""" from collections import namedtuple +import datetime import io import logging import os @@ -29,7 +30,6 @@ import suds.xsd.doctor import xmltodict import yaml - import googleads.common import googleads.errors @@ -42,7 +42,7 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201609': { + 'v201705': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', 'AdGroupAdService': 'cm', @@ -57,9 +57,12 @@ 'BiddingStrategyService': 'cm', 'BudgetOrderService': 'billing', 'BudgetService': 'cm', + 'CampaignBidModifierService': 'cm', 'CampaignCriterionService': 'cm', 'CampaignExtensionSettingService': 'cm', 'CampaignFeedService': 'cm', + 'CampaignGroupPerformanceTargetService': 'cm', + 'CampaignGroupService': 'cm', 'CampaignService': 'cm', 'CampaignSharedSetService': 'cm', 'ConstantDataService': 'cm', @@ -88,7 +91,7 @@ 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' }, - 'v201702': { + 'v201708': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', 'AdGroupAdService': 'cm', @@ -103,9 +106,12 @@ 'BiddingStrategyService': 'cm', 'BudgetOrderService': 'billing', 'BudgetService': 'cm', + 'CampaignBidModifierService': 'cm', 'CampaignCriterionService': 'cm', 'CampaignExtensionSettingService': 'cm', 'CampaignFeedService': 'cm', + 'CampaignGroupPerformanceTargetService': 'cm', + 'CampaignGroupService': 'cm', 'CampaignService': 'cm', 'CampaignSharedSetService': 'cm', 'ConstantDataService': 'cm', @@ -126,6 +132,7 @@ 'MediaService': 'cm', 'OfflineCallConversionFeedService': 'cm', 'OfflineConversionFeedService': 'cm', + 'OfflineDataUploadService': 'rm', 'ReportDefinitionService': 'cm', 'SharedCriterionService': 'cm', 'SharedSetService': 'cm', @@ -134,7 +141,7 @@ 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' }, - 'v201705': { + 'v201710': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', 'AdGroupAdService': 'cm', @@ -161,6 +168,7 @@ 'ConversionTrackerService': 'cm', 'CustomerExtensionSettingService': 'cm', 'CustomerFeedService': 'cm', + 'CustomerNegativeCriterionService': 'cm', 'CustomerService': 'mcm', 'CustomerSyncService': 'ch', 'DataService': 'cm', @@ -175,6 +183,7 @@ 'MediaService': 'cm', 'OfflineCallConversionFeedService': 'cm', 'OfflineConversionFeedService': 'cm', + 'OfflineDataUploadService': 'rm', 'ReportDefinitionService': 'cm', 'SharedCriterionService': 'cm', 'SharedSetService': 'cm', @@ -183,7 +192,7 @@ 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' }, - 'v201708': { + 'v201802': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', 'AdGroupAdService': 'cm', @@ -210,12 +219,14 @@ 'ConversionTrackerService': 'cm', 'CustomerExtensionSettingService': 'cm', 'CustomerFeedService': 'cm', + 'CustomerNegativeCriterionService': 'cm', 'CustomerService': 'mcm', 'CustomerSyncService': 'ch', 'DataService': 'cm', 'DraftAsyncErrorService': 'cm', 'DraftService': 'cm', 'FeedItemService': 'cm', + 'FeedItemTargetService': 'cm', 'FeedMappingService': 'cm', 'FeedService': 'cm', 'LabelService': 'cm', @@ -224,7 +235,7 @@ 'MediaService': 'cm', 'OfflineCallConversionFeedService': 'cm', 'OfflineConversionFeedService': 'cm', - 'OfflineDataUploadService': 'cm', + 'OfflineDataUploadService': 'rm', 'ReportDefinitionService': 'cm', 'SharedCriterionService': 'cm', 'SharedSetService': 'cm', @@ -249,7 +260,7 @@ _DEFAULT_USER_AGENT = 'unknown' -class AdWordsClient(object): +class AdWordsClient(googleads.common.CommonClient): """A central location to set headers and create web service clients. Attributes: @@ -277,8 +288,8 @@ class AdWordsClient(object): # AdWords. _OPTIONAL_INIT_VALUES = ( 'validate_only', 'partial_failure', 'client_customer_id', 'user_agent', - 'report_downloader_headers', - googleads.common.ENABLE_COMPRESSION_KEY) + 'report_downloader_headers', + googleads.common.ENABLE_COMPRESSION_KEY) # The format of SOAP service WSDLs. A server, namespace, version, and service # name need to be formatted in. @@ -368,6 +379,8 @@ def __init__(self, developer_token, oauth2_client, GoogleAdsValueError: If the provided user_agent contains non-ASCII characters. """ + super(AdWordsClient, self).__init__() + self.developer_token = developer_token self.oauth2_client = oauth2_client self.client_customer_id = kwargs.get('client_customer_id') @@ -446,7 +459,8 @@ def GetService(self, service_name, version=None, server=None): **kwargs) return googleads.common.SudsServiceProxy( - client, _AdWordsHeaderHandler(self, version, self.enable_compression)) + client, _AdWordsHeaderHandler(self, version, self.enable_compression), + packer=_AdWordsPacker) def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -616,6 +630,26 @@ def GetReportDownloadHeaders(self, **kwargs): return headers +class _AdWordsPacker(googleads.common.SudsPacker): + """A utility applying customized packing logic for AdWords.""" + + @classmethod + def Pack(cls, obj): + """Pack the given object using AdWords-specific logic. + + Args: + obj: an object to be packed for suds using AdWords-specific logic, if + applicable. + + Returns: + The given object packed with AdWords-specific logic for suds, if + applicable. Otherwise, returns the given object unmodified. + """ + if isinstance(obj, ServiceQuery): + return str(obj) + return obj + + @googleads.common.RegisterUtility('BatchJobHelper') class BatchJobHelper(object): """A utility that simplifies working with the BatchJobService.""" @@ -708,11 +742,20 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): 'CampaignService', 'mutate'), 'CampaignLabelOperation': _OPERATION('CampaignLabelOperation', 'CampaignService', 'mutateLabel'), + 'CampaignSharedSetOperation': _OPERATION( + 'CampaignSharedSetOperation', 'CampaignSharedSetService', + 'mutate'), 'CustomerExtensionSettingOperation': _OPERATION( 'CustomerExtensionSettingOperation', 'CustomerExtensionSettingService', 'mutate'), 'FeedItemOperation': _OPERATION('FeedItemOperation', 'FeedItemService', - 'mutate') + 'mutate'), + 'FeedItemTargetOperation': _OPERATION( + 'FeedItemTargetOperation', 'FeedItemTargetService', 'mutate'), + 'SharedCriterionOperation': _OPERATION( + 'SharedCriterionOperation', 'SharedCriterionService', 'mutate'), + 'SharedSetOperation': _OPERATION('SharedSetOperation', + 'SharedSetService', 'mutate') } def __init__(self, client, **kwargs): @@ -880,7 +923,7 @@ def _GenerateOperationsXML(self, operations): Raises: GoogleAdsValueError: if no xsi_type is specified for the operations. """ - # Verify that all operations included specify an xsi_type. + # Verify that all operations included specify an xsi_type. if operations: if any('xsi_type' not in operation for operation in operations): raise googleads.errors.AdWordsBatchJobServiceInvalidOperationError( @@ -1515,8 +1558,8 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, The report contents will be written to the given output. Args: - query: A string containing the query which specifies the data you want - your report to include. + query: A string or ReportQuery object containing the query which + specifies the data you want your report to include. file_format: A string representing the output format for your report. Acceptable values can be found in our API documentation: https://developers.google.com/adwords/api/docs/guides/reporting @@ -1661,11 +1704,12 @@ def _DownloadReportAsStream(self, post_body, **kwargs): response.code, response.msg) return response except urllib2.HTTPError as e: + error = self._ExtractError(e) if _report_logger.isEnabledFor(logging.WARNING): _report_logger.warning( 'Request Summary: %s', self._ExtractRequestSummaryFields( - request, error=e)) - raise self._ExtractError(e) + request, error=error)) + raise error def _SanitizeRequestHeaders(self, headers): """Removes sensitive data from request headers for use in logging. @@ -1708,7 +1752,9 @@ def _ExtractRequestSummaryFields(self, request, error=None): Args: request: a urllib2.Request instance. [optional] - error: a urllib2.HttpError instance used to retrieve error details. + error: a googleads.errors.AdWordsReportError instance or subclass used to + retrieve error details. This should only be present when an error + occurred, otherwise it should be set to None for successful requests. Returns: A dict containing the fields to be output in the summary logs. @@ -1728,7 +1774,7 @@ def _ExtractRequestSummaryFields(self, request, error=None): if error: summary_fields['isError'] = True - summary_fields['errorMessage'] = error.read() + summary_fields['errorMessage'] = error.content else: summary_fields['isError'] = False @@ -1738,7 +1784,8 @@ def _SerializeAwql(self, query, file_format): """Serializes an AWQL query and file format for transport. Args: - query: A string representing the AWQL query used in the report. + query: A string or ReportQuery object representing the AWQL query used in + the report. file_format: A string representing the file format of the generated report. @@ -1746,7 +1793,7 @@ def _SerializeAwql(self, query, file_format): The given query and format URL encoded into the format needed for an AdWords report request as a string. This is intended to be a POST body. """ - return urllib.urlencode({'__fmt': file_format, '__rdquery': query}) + return urllib.urlencode({'__fmt': file_format, '__rdquery': str(query)}) def _SerializeReportDefinition(self, report_definition): """Serializes a report definition for transport. @@ -1791,3 +1838,713 @@ def _ExtractError(self, error): pass return googleads.errors.AdWordsReportError( error.code, error, content) + + +class _QueryBuilder(object): + """A query builder for building AWQL (AdWords Query Language) queries.""" + + def __init__(self, query_builder=None): + """Creates the query builder with the optional specified query builder. + + This class shouldn't be instantiated directly or extended. Use + ReportQueryBuilder if you want to create a query for reporting or + ServiceQueryBuilder if you want to create a query for services. + + Args: + query_builder: An optional query builder whose properties will be copied + over to this instance. + + Returns: + The query builder. + + Raises: + GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder + type. + """ + if query_builder is None: + self.where_builders = [] + else: + try: + self.where_builders = list(query_builder.where_builders) + except (AttributeError, TypeError): + raise googleads.errors.GoogleAdsValueError( + 'The passed query builder should be of the QueryBuilder type.') + + def Select(self, *fields): + """Sets a provided list of fields as selected fields for the query. + + Args: + *fields: The specified list of fields to be added to a SELECT clause. + + Returns: + This query builder. + """ + raise NotImplementedError('You must subclass _QueryBuilder.') + + def Where(self, field): + """Creates a WHERE builder using a provided field. + + Args: + field: the field to be added as an argument in the WHERE clause. + + Returns: + The created WHERE builder. + """ + where_builder = _WhereBuilder(self, field) + self.where_builders.append(where_builder) + return where_builder + + +class _WhereBuilder(object): + """A WHERE builder for building a WHERE clause in AWQL queries.""" + + def __init__(self, query_builder, field): + """Creates the WHERE builder with specified query builder and field. + + This class should be instantiated through _QueryBuilder.Where. Don't call + this constructor directly. + + Args: + query_builder: The query builder that this WHERE builder links to. + field: The field to be used in the WHERE condition. + + Returns: + The WHERE builder. + """ + self._field = field + self._query_builder = query_builder + self._awql = None + + def EqualTo(self, value): + """Sets the type of the WHERE clause as "equal to". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '=') + return self._query_builder + + def NotEqualTo(self, value): + """Sets the type of the WHERE clause as "not equal to". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '!=') + return self._query_builder + + def GreaterThan(self, value): + """Sets the type of the WHERE clause as "greater than". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '>') + return self._query_builder + + def GreaterThanOrEqualTo(self, value): + """Sets the type of the WHERE clause as "greater than or equal to". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '>=') + return self._query_builder + + def LessThan(self, value): + """Sets the type of the WHERE clause as "less than". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '<') + return self._query_builder + + def LessThanOrEqualTo(self, value): + """Sets the type of the WHERE clause as "less than or equal to. + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, '<=') + return self._query_builder + + def StartsWith(self, value): + """Sets the type of the WHERE clause as "starts with". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, 'STARTS_WITH') + return self._query_builder + + def StartsWithIgnoreCase(self, value): + """Sets the type of the WHERE clause as "starts with ignore case". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, + 'STARTS_WITH_IGNORE_CASE') + return self._query_builder + + def Contains(self, value): + """Sets the type of the WHERE clause as "contains". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, 'CONTAINS') + return self._query_builder + + def ContainsIgnoreCase(self, value): + """Sets the type of the WHERE clause as "contains ignore case". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, 'CONTAINS_IGNORE_CASE') + return self._query_builder + + def DoesNotContain(self, value): + """Sets the type of the WHERE clause as "does not contain". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition(value, 'DOES_NOT_CONTAIN') + return self._query_builder + + def DoesNotContainIgnoreCase(self, value): + """Sets the type of the WHERE clause as "doesn not contain ignore case". + + Args: + value: The value to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateSingleValueCondition( + value, 'DOES_NOT_CONTAIN_IGNORE_CASE') + return self._query_builder + + def In(self, *values): + """Sets the type of the WHERE clause as "in". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'IN') + return self._query_builder + + def NotIn(self, *values): + """Sets the type of the WHERE clause as "in". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'NOT_IN') + return self._query_builder + + def ContainsAny(self, *values): + """Sets the type of the WHERE clause as "contains any". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ANY') + return self._query_builder + + def ContainsNone(self, *values): + """Sets the type of the WHERE clause as "contains none". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_NONE') + return self._query_builder + + def ContainsAll(self, *values): + """Sets the type of the WHERE clause as "contains all". + + Args: + *values: The values to be used in the WHERE condition. + + Returns: + The query builder that this WHERE builder links to. + """ + self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ALL') + return self._query_builder + + def Build(self): + """Builds the WHERE clause by returning the stored AWQL. + + Returns: + The resulting WHERE clause in AWQL format. + """ + return self._awql + + def _CreateSingleValueCondition(self, value, operator): + """Creates a single-value condition with the provided value and operator.""" + if isinstance(value, str) or isinstance(value, unicode): + value = '"%s"' % value + return '%s %s %s' % (self._field, operator, value) + + def _CreateMultipleValuesCondition(self, values, operator): + """Creates a condition with the provided list of values and operator.""" + values = ['"%s"' % value if isinstance(value, str) or + isinstance(value, unicode) else str(value) for value in values] + return '%s %s [%s]' % (self._field, operator, ', '.join(values)) + + +@googleads.common.RegisterUtility('ReportQueryBuilder') +class ReportQueryBuilder(_QueryBuilder): + """A query builder for building AWQL queries for reporting.""" + + def __init__(self, query_builder=None): + """Creates the report query builder with the optionally specified builder. + + Creates the report query builder by initializing all attributes including + the report name, time range, start and end date. If the optional query + builder are specified, copy all its attributes to this instance. + + Args: + query_builder: An optional query builder whose attributes will be copied + over to this instance. + + Returns: + This report query builder. + + Raises: + GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder + type. + """ + _QueryBuilder.__init__(self, query_builder) + if query_builder is None: + self.select = None + self.from_report = None + self.date_range = None + self.start_date = None + self.end_date = None + else: + try: + self.select = list(query_builder.select) + self.from_report = query_builder.from_report + self.date_range = query_builder.date_range + self.start_date = query_builder.start_date + self.end_date = query_builder.end_date + except (AttributeError, TypeError): + raise googleads.errors.GoogleAdsValueError( + 'The passed query builder should be of ReportQueryBuilder type.') + + def Select(self, *fields): + """Sets a provided list of fields as selected fields for the query. + + Subsequent calls to this method overwrite the entire set of selected fields + with the new one. + + Args: + *fields: The specified list of fields to be added to a SELECT clause. + + Returns: + This report query builder. + """ + self.select = list(fields) + return self + + def From(self, report_name): + """Sets a provided report name as the argument to FROM clause. + + Args: + report_name: The specified report name. + + Returns: + This report query builder. + """ + self.from_report = report_name + return self + + def During(self, date_range=None, start_date=None, end_date=None): + """Sets arguments for the DURING clause of the query. + + Sets arguments for the DURING clause using the provided date range or start + and end dates. Only the date range or start and end date should be + specified. If both are supplied, an error will be thrown. A valid date range + string can be found at + https://developers.google.com/adwords/api/docs/guides/reporting#date_ranges. + Start and end dates should be in 'YYYYMMDD' format. + + Args: + date_range: The specified date range string, e.g., YESTERDAY. + start_date: The start date string in 'YYYYMMDD' format or an instance of + datetime.date. + end_date: The end date string in 'YYYYMMDD' format or an instance of + datetime.date. + + Returns: + This report query builder. + + Raises: + ValueError: If all the arguments are None or both date_range and start + and end dates have values or if start_date has value but end_date + doesn't (and vice versa). + """ + if date_range is None and (start_date is None or end_date is None): + raise ValueError( + 'Either date_range or both start_date and end_date must not be None.') + if date_range is not None and (start_date is not None + or end_date is not None): + raise ValueError( + 'If date_range is not None, start_date and end_date must be None ' + '(and vice versa).') + self.date_range = date_range + self.start_date = start_date + self.end_date = end_date + return self + + def Build(self): + """Builds a ReportQuery object containing the created AWQL query. + + Returns: + The created ReportQuery object. + + Raises: + ValueError: If the selected fields or report name is not specified. + """ + if self.select is None: + raise ValueError('Must use Select() to specify SELECT clause for valid' + ' AWQL first.') + if self.from_report is None: + raise ValueError('Must use From() to specify FROM clause for valid AWQL' + ' first.') + + parts = ['SELECT ', (', '.join(self.select))] + parts.extend([' FROM ', self.from_report]) + where_clause = (' WHERE %s' % ' AND '.join([builder.Build() for builder + in self.where_builders]) + if self.where_builders else '') + parts += where_clause + + if self.date_range: + parts.extend([' DURING ', self.date_range]) + elif self._start_date and self._end_date: + parts.extend([' DURING ', '%s,%s' % (self._start_date, self._end_date)]) + awql = ''.join(parts) + + return ReportQuery(awql) + + @property + def start_date(self): + """Gets the start date of the query.""" + return self._start_date + + @start_date.setter + def start_date(self, start_date): + """Sets the start date of the query to the provided value.""" + if isinstance(start_date, datetime.date): + self._start_date = '{:%Y%m%d}'.format(start_date) + else: + self._start_date = start_date + + @property + def end_date(self): + """Gets the end date of the query.""" + return self._end_date + + @end_date.setter + def end_date(self, end_date): + """Sets the end date of the query to the provided value.""" + if isinstance(end_date, datetime.date): + self._end_date = '{:%Y%m%d}'.format(end_date) + else: + self._end_date = end_date + + +class ReportQuery(object): + """A report query storing an AWQL query.""" + + def __init__(self, awql): + """Creates a report query instance storing the provided AWQL query.""" + self._awql = awql + + def __str__(self): + """Returns the stored AWQL query.""" + return self._awql + + +@googleads.common.RegisterUtility('ServiceQueryBuilder') +class ServiceQueryBuilder(_QueryBuilder): + """A query builder for building AWQL queries for services.""" + + _ORDER_BY_CLAUSE = namedtuple('OrderByClause', ['field', 'direction']) + + def __init__(self, query_builder=None): + """Creates the service query builder with the optionally specified builder. + + Creates the service query builder by initializing all attributes including + oder by list, start index, and page size. + If the optional query builder are specified, copy all its attributes to this + instance. + + Args: + query_builder: An optional query builder whose attributes will be copied + over to this instance. + + Returns: + This service query builder. + + Raises: + GoogleAdsValueError: If the passed query_builder isn't of the QueryBuilder + type. + """ + _QueryBuilder.__init__(self, query_builder) + if query_builder is None: + self.select = set() + self.order_by_list = [] + self.start_index = None + self.page_size = None + else: + try: + self.select = query_builder.select + self.order_by_list = query_builder.order_by_list + self.start_index = query_builder.start_index + self.page_size = query_builder.page_size + except (AttributeError, TypeError): + raise googleads.errors.GoogleAdsValueError( + 'The passed query builder should be of ServiceQueryBuilder type.') + + def Select(self, *fields): + """Sets a provided list of fields as selected fields for the query. + + Subsequent calls to this method overwrite the entire set of selected fields + with the new one. Duplicate field names will be treated as one field. + + Args: + *fields: The specified list of fields to be added to a SELECT clause. + + Returns: + This service query builder. + """ + self.select.update(fields) + return self + + def OrderBy(self, field, ascending=True): + """Adds the provided field to the order-by list with the provided direction. + + Args: + field: The specified field to be added to the order-by list. + ascending: If true, the newly created order-by clause will be in ascending + order. Otherwise, it will be in descending order. + + Returns: + This service query builder. + """ + order_by = self._ORDER_BY_CLAUSE(field, 'ASC' if ascending else 'DESC') + self.order_by_list.append(order_by) + return self + + def Limit(self, start_index, page_size): + """Sets the LIMIT clause using the provided start index and page size. + + Args: + start_index: The specified start index for the LIMIT clause. + page_size: The optional page size for the LIMIT clause. + + Returns: + This service query builder. + + Raises: + ValueError: If start_index is None but the page_size is not None or vice + versa. + """ + if ((start_index is None and page_size is not None) + or (start_index is not None and page_size is None)): + raise ValueError('Either both start_index and page_size must be None, or' + ' neither') + self.start_index = start_index + self.page_size = page_size + return self + + def Build(self): + """Builds a ServiceQuery object containing AWQL queries. + + Returns: + The created ServiceQuery object. + + Raises: + ValueError: If the selected fields or service name is not specified. + """ + if not self.select: + raise ValueError('Must use Select() to specify SELECT clause for valid' + ' AWQL first') + + parts = ['SELECT ', (', '.join(self.select))] + where_clause = (' WHERE %s' % ' AND '.join(builder.Build() for builder + in self.where_builders) + if self.where_builders else '') + parts += where_clause + + if self.order_by_list: + parts.extend([' ORDER BY ', + ', '.join('%s %s' % (order_by.field, order_by.direction) + for order_by in self.order_by_list)]) + awql = ''.join(parts) + + return ServiceQuery(awql, self.start_index, self.page_size) + + @property + def select(self): + """Gets the select set of the query.""" + return self._select + + @select.setter + def select(self, select): + """Sets the select set of the query to the copy of provided value.""" + self._select = set(select) + + @property + def order_by_list(self): + """Gets the order-by list of the query.""" + return self._order_by_list + + @order_by_list.setter + def order_by_list(self, order_by_list): + """Sets the order-by list of the query to the copy of provided value.""" + self._order_by_list = list(order_by_list) + + +class ServiceQuery(object): + """A service query storing an AWQL query.""" + + def __init__(self, awql, start_index, page_size): + """Creates a service query instance storing the provided AWQL query.""" + self._awql = awql + self._start_index = start_index + self._page_size = page_size + self._total_num_entries = None + + def NextPage(self, page_size=None): + """Sets the LIMIT clause of the AWQL to the next page. + + This method is meant to be used with HasNext(). + The page_size is necessary when using DataService, as its paging mechanism + is different from other services. For details, see + https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results. + When the page_size is None, this object's page size is used instead. + + Args: + page_size: The optional page size used to increment the index in the LIMIT + clause. + + Returns: + This service query object. + + Raises: + ValueError: If the start index of this object is None, meaning that the + LIMIT clause hasn't been set before. + """ + if self._start_index is None: + raise ValueError('Cannot page through query with no LIMIT clause.') + increment = self._page_size if page_size is None else page_size + self._start_index += increment + return self + + def HasNext(self, page, page_size=None): + """Checks if there is still a page left to query. + + This method is meant to be used with NextPage(). + The page_size is necessary when using DataService, as its paging mechanism + is different from other services. For details, see + https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results. + When the page_size is None, this object's page size is used instead. + + Args: + page: A dict containing the 'totalNumEntries' key whose value represents + the total number of results from making the query to the AdWords API + services. + page_size: The optional page size used to increment the index in the LIMIT + clause. + + Returns: + True if there is still a page left. + + Raises: + ValueError: If the start index of this object is None, meaning that the + LIMIT clause hasn't been set before. + """ + if self._start_index is None: + raise ValueError('Cannot page through query with no LIMIT clause.') + if not self._total_num_entries: + self._total_num_entries = page['totalNumEntries'] + increment = self._page_size if page_size is None else page_size + return self._start_index + increment < self._total_num_entries + + def Pager(self, service): + """A page generator for this service query and the provided service. + + This generates a page as a result from using the provided service's query() + method until there are no more results to fetch. + + Args: + service: The service object for making a query using this service query. + + Yields: + A resulting page from querying the provided service. + """ + has_page = True + while has_page: + page = service.query(self) + yield page + has_page = self.HasNext(page) + if has_page: + self.NextPage() + + def __str__(self): + """Returns the stored AWQL query combined with the LIMIT clause.""" + awql = self._awql + ' LIMIT %s,%s' % (self._start_index, self._page_size) + return awql diff --git a/googleads/common.py b/googleads/common.py index 6f01d0e2..2c3df313 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -14,8 +14,6 @@ """Common client library functions and classes used by all products.""" - -import datetime from functools import wraps import inspect import locale @@ -28,13 +26,11 @@ import urllib2 import warnings - import httplib2 import socks import suds import suds.transport.http import yaml - import googleads.errors import googleads.oauth2 import googleads.util @@ -66,7 +62,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '7.0.0' +VERSION = '10.1.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http_proxy' @@ -128,6 +124,26 @@ def GenerateLibSig(short_name): return ' (%s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION) +class CommonClient(object): + """Contains shared startup code between DFP and AdWords clients.""" + + def __init__(self): + # Warn users on deprecated Python versions on initialization. + if _PY_VERSION_MAJOR == 2: + if _PY_VERSION_MINOR == 7 and _PY_VERSION_MICRO < 9: + _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, + _PY_VERSION_MINOR, _PY_VERSION_MICRO) + elif _PY_VERSION_MINOR < 7: + _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, + _PY_VERSION_MINOR, _PY_VERSION_MICRO) + + # Warn users about using non-utf8 encoding + _, encoding = locale.getdefaultlocale() + if encoding is None or encoding.lower() != 'utf-8': + _logger.warn('Your default encoding, %s, is not UTF-8. Please run this' + ' script with UTF-8 encoding to avoid errors.', encoding) + + def LoadFromString(yaml_doc, product_yaml_key, required_client_values, optional_product_values): """Loads the data necessary for instantiating a client from file storage. @@ -161,21 +177,6 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, if logging_config: logging.config.dictConfig(logging_config) - # Warn users on deprecated Python versions on initialization. - if _PY_VERSION_MAJOR == 2: - if _PY_VERSION_MINOR == 7 and _PY_VERSION_MICRO < 9: - _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, - _PY_VERSION_MINOR, _PY_VERSION_MICRO) - elif _PY_VERSION_MINOR < 7: - _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, - _PY_VERSION_MINOR, _PY_VERSION_MICRO) - - # Warn users about using non-utf8 encoding - _, encoding = locale.getdefaultlocale() - if encoding is None or encoding.lower() != 'utf-8': - _logger.warn('Your default encoding, %s, is not UTF-8. Please run this' - ' script with UTF-8 encoding to avoid errors.', encoding) - try: product_data = data[product_yaml_key] except KeyError: @@ -266,9 +267,8 @@ def LoadFromStorage(path, product_yaml_key, required_client_values, required_client_values, optional_product_values) except googleads.errors.GoogleAdsValueError as e: - e.message = ('Given yaml file, %s, ' - 'could not find some keys. %s' % (path, e.message)) - raise + raise googleads.errors.GoogleAdsValueError( + 'Given yaml file, %s, could not find some keys. %s' % (path, e)) return client_kwargs @@ -391,7 +391,7 @@ def _ExtractProxy(proxy_yaml_key, proxy_config_data): return proxy -def _PackForSuds(obj, factory, datetime_packer=None): +def _PackForSuds(obj, factory, packer=None): """Packs SOAP input into the format we want for suds. The main goal here is to pack dictionaries with an 'xsi_type' key into @@ -406,15 +406,17 @@ def _PackForSuds(obj, factory, datetime_packer=None): for instances of unpacked dictionaries or lists. factory: The suds.client.Factory object which can create instances of the classes generated from the WSDL. - datetime_packer: A product specific function to unwrap date/datetimes. + packer: An optional subclass of googleads.common.SudsPacker that provides + customized packing logic. Returns: If the given obj was a dictionary that contained the 'xsi_type' key, this will be an instance of a class generated from the WSDL. Otherwise, this will be the same data type as the input obj was. """ - if datetime_packer and isinstance(obj, (datetime.datetime, datetime.date)): - obj = datetime_packer(obj) + if packer: + obj = packer.Pack(obj) + if obj in ({}, None): # Force suds to serialize empty objects. There are legitimate use cases for # this, for example passing in an empty SearchCriteria object to a DFA @@ -445,16 +447,16 @@ def _PackForSuds(obj, factory, datetime_packer=None): for key in obj: if key == 'xsi_type': continue setattr(new_obj, key, _PackForSuds(obj[key], factory, - datetime_packer=datetime_packer)) + packer=packer)) else: new_obj = {} for key in obj: new_obj[key] = _PackForSuds(obj[key], factory, - datetime_packer=datetime_packer) + packer=packer) return new_obj elif isinstance(obj, (list, tuple)): return [_PackForSuds(item, factory, - datetime_packer=datetime_packer) for item in obj] + packer=packer) for item in obj] else: _RecurseOverObject(obj, factory) return obj @@ -518,6 +520,22 @@ def RegisterUtility(utility_name, version_mapping=None): Returns: The decorated class. """ + def IsFunctionOrMethod(member): + """Determines if given member is a function or method. + + These two are used in combination to ensure that inspect finds all of a + given utility class's methods in both Python 2 and 3. + + Args: + member: object that is a member of a class, to be determined whether it is + a function or method. + + Returns: + A boolean that is True if the provided member is a function or method, or + False if it isn't. + """ + return inspect.isfunction(member) or inspect.ismethod(member) + def MethodDecorator(utility_method, version): """Decorates a method in the utility class.""" registry_name = ('%s/%s' % (utility_name, version) if version @@ -531,7 +549,7 @@ def Wrapper(*args, **kwargs): def ClassDecorator(cls): """Decorates a utility class.""" - for name, method in inspect.getmembers(cls, inspect.ismethod): + for name, method in inspect.getmembers(cls, predicate=IsFunctionOrMethod): # Public methods of the class will have the decorator applied. if not name.startswith('_'): # The decorator will only be applied to unbound methods; this prevents @@ -611,6 +629,18 @@ def _InitSSLContext(self, cafile=None, return ssl_context + def BuildOpener(self): + """Builds an OpenerDirector instance using the ProxyConfig settings. + + In Python 2, this will return a urllib2.OpenerDirector instance. In Python + 3, this will return a urllib.request.OpenerDirector instance. + + Returns: + An OpenerDirector instance instantiated with settings defined in the + ProxyConfig instance. + """ + return urllib2.build_opener(*self.GetHandlers()) + def GetHandlers(self): """Retrieve the appropriate urllib2 handlers for the given configuration. @@ -689,6 +719,18 @@ def u2handlers(self): return return_handlers +class SudsPacker(object): + """A utility class to be passed to _PackForSuds for customized packing. + + A subclass should be used in cases where custom logic is needed to pack a + given object in _PackForSuds. + """ + + @classmethod + def Pack(cls, obj): + raise NotImplementedError('You must subclass SudsPacker.') + + class SudsServiceProxy(object): """Wraps a suds service object, allowing custom logic to be injected. @@ -703,7 +745,7 @@ class SudsServiceProxy(object): the client and its factory, """ - def __init__(self, suds_client, header_handler, datetime_packer=None): + def __init__(self, suds_client, header_handler, packer=None): """Initializes a suds service proxy. Args: @@ -712,12 +754,13 @@ def __init__(self, suds_client, header_handler, datetime_packer=None): object. header_handler: A HeaderHandler responsible for setting the SOAP and HTTP headers on the service client. - datetime_packer: A product specific function to unwrap date/datetimes. + packer: An optional subclass of googleads.common.SudsPacker that provides + customized packing logic. """ self.suds_client = suds_client self._header_handler = header_handler self._method_proxies = {} - self._datetime_packer = datetime_packer + self._packer = packer def __getattr__(self, attr): if attr in self.suds_client.wsdl.services[0].ports[0].methods: @@ -745,13 +788,13 @@ def MakeSoapRequest(*args): try: return soap_service_method( *[_PackForSuds(arg, self.suds_client.factory, - self._datetime_packer) for arg in args]) + self._packer) for arg in args]) except suds.WebFault as e: if _logger.isEnabledFor(logging.WARNING): _logger.warning('Response summary - %s', _ExtractResponseSummaryFields(e.document)) - _logger.info('SOAP response:\n%s', e.document) + _logger.info('SOAP response:\n%s', e.document.str()) if not hasattr(e.fault, 'detail'): raise diff --git a/googleads/dfp.py b/googleads/dfp.py index 16fc2204..8269b202 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -20,13 +20,13 @@ import logging import numbers import os +import sys import time import urllib2 import pytz import suds.client import suds.transport - import googleads.common import googleads.errors @@ -46,7 +46,7 @@ # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201611': + 'v201705': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -57,17 +57,18 @@ 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NetworkService', 'OrderService', - 'PackageService', 'PlacementService', 'PremiumRateService', - 'ProductService', 'ProductPackageService', 'ProductPackageItemService', - 'ProductTemplateService', 'ProposalLineItemService', 'ProposalService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'RateCardService', 'ReconciliationOrderReportService', 'ReconciliationReportRowService', 'ReconciliationLineItemReportService', 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201702': + 'v201708': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -89,15 +90,15 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201705': + 'v201711': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentMetadataKeyHierarchyService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', - 'InventoryService', 'LabelService', + 'CdnConfigurationService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentMetadataKeyHierarchyService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', @@ -111,15 +112,15 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201708': + 'v201802': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentMetadataKeyHierarchyService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', - 'InventoryService', 'LabelService', + 'CdnConfigurationService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentMetadataKeyHierarchyService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', @@ -136,7 +137,7 @@ } -class DfpClient(object): +class DfpClient(googleads.common.CommonClient): """A central location to set headers and create web service clients. Attributes: @@ -217,8 +218,8 @@ def __init__(self, oauth2_client, application_name, network_code=None, application [optional] network_code: A string identifying the network code of the network you are - accessing. All requests other than getAllNetworks and getCurrentUser - calls require this header to be set. + accessing. All requests other than getAllNetworks require this header + to be set. cache: A subclass of suds.cache.Cache. If not set, this will default to an instance of suds.cache.ObjectCache. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy @@ -227,6 +228,8 @@ def __init__(self, oauth2_client, application_name, network_code=None, of the SOAP response. If True, the SOAP response will use gzip compression, and will be decompressed for you automatically. """ + super(DfpClient, self).__init__() + if not application_name or (DEFAULT_APPLICATION_NAME in application_name): raise googleads.errors.GoogleAdsValueError( 'Application name must be set and not contain the default [%s]' % @@ -298,7 +301,7 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], 'versions: %s' % (version, _SERVICE_MAP.keys())) return googleads.common.SudsServiceProxy(client, self._header_handler, - _DFPDateTimePacker) + packer=_DfpPacker) def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -362,6 +365,53 @@ def SetHeaders(self, suds_client): headers=http_headers) +class _DfpPacker(googleads.common.SudsPacker): + """A utility applying customized packing logic for DFP.""" + + @classmethod + def Pack(cls, obj): + """Pack the given object using DFP-specific logic. + + Args: + obj: an object to be packed for suds using DFP-specific logic, if + applicable. + + Returns: + The given object packed with DFP-specific logic for suds, if applicable. + Otherwise, returns the given object unmodified. + """ + if isinstance(obj, (datetime.datetime, datetime.date)): + return cls.DfpDateTimePacker(obj) + return obj + + @classmethod + def DfpDateTimePacker(cls, value): + """Returns dicts formatted for DFP SOAP based on date/datetime. + + Args: + value: A date or datetime object to be converted. + + Returns: + The value object correctly represented for DFP SOAP. + """ + + if isinstance(value, datetime.datetime): + if value.tzinfo is None: + raise googleads.errors.GoogleAdsValueError( + 'Datetime %s is not timezone aware.' % value + ) + + return { + 'date': cls.DfpDateTimePacker(value.date()), + 'hour': value.hour, + 'minute': value.minute, + 'second': value.second, + 'timeZoneID': value.tzinfo.zone, + } + elif isinstance(value, datetime.date): + return {'year': value.year, 'month': value.month, 'day': value.day} + + @googleads.common.RegisterUtility('StatementBuilder') class StatementBuilder(object): """Provides the ability to programmatically construct PQL queries.""" @@ -541,33 +591,6 @@ def WithBindVariable(self, key, value): return self -def _DFPDateTimePacker(value): - """Returns dicts formatted for DFP SOAP based on date/datetime. - - Args: - value: A date or datetime object to be converted. - - Returns: - The value object correctly represented for DFP SOAP. - """ - - if isinstance(value, datetime.datetime): - if value.tzinfo is None: - raise googleads.errors.GoogleAdsValueError( - 'Datetime %s is not timezone aware.' % value - ) - - return { - 'date': _DFPDateTimePacker(value.date()), - 'hour': value.hour, - 'minute': value.minute, - 'second': value.second, - 'timeZoneID': value.tzinfo.zone, - } - elif isinstance(value, datetime.date): - return {'year': value.year, 'month': value.month, 'day': value.day} - - class PQLHelper(object): """Utility class for PQL.""" @@ -796,7 +819,8 @@ def DownloadPqlResultToList(self, pql_query, values=None): pql_query: str a statement filter to apply (the query should not include the limit or the offset) [optional] - values: list dict of bind values to use with the pql_query. + values: A dict of python objects or a list of raw SOAP values to bind + to the pql_query. Returns: a list of lists with the first being the header row and each subsequent @@ -814,7 +838,8 @@ def DownloadPqlResultToCsv(self, pql_query, file_handle, values=None): the limit or the offset) file_handle: file the file object to write to. [optional] - values: list dict of bind values to use with the pql_query. + values: A dict of python objects or a list of raw SOAP values to bind + to the pql_query. """ pql_writer = csv.writer(file_handle, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) @@ -851,7 +876,12 @@ def _ConvertValueForCsv(self, pql_value): class_type = DfpClassType(pql_value) if class_type == 'TextValue': - return field.replace('"', '""').encode('UTF8') + s = field.replace('"', '""') + + # Encode UTF-8 characters for Python 2 only. + if sys.version_info.major < 3: + s = s.encode('UTF8') + return s elif class_type == 'NumberValue': return float(field) if '.' in field else int(field) elif class_type == 'DateTimeValue': @@ -873,8 +903,12 @@ def _PageThroughPqlSet(self, pql_query, output_function, values): the limit or the offset) output_function: the function to call to output the results (csv or in memory) - values: list dict of bind values to use with the pql_query. + values: A dict of python objects or a list of raw SOAP values to bind + to the pql_query. """ + if isinstance(values, dict): + values = PQLHelper.GetQueryValuesFromDict(values) + pql_service = self._GetPqlService() current_offset = 0 diff --git a/googleads/util.py b/googleads/util.py index f2741994..4b9ab013 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -134,6 +134,8 @@ def PatchedHttpTransportSend(self, request): raise suds.transport.TransportError(e.msg, e.code, e.fp) self.getcookies(fp, u2request) + # Note: Python 2 returns httplib.HTTPMessage, and Python 3 returns + # http.client.HTTPMessage, which differ slightly. headers = (fp.headers.dict if sys.version_info < (3, 0) else fp.headers) result = suds.transport.Reply(200, headers, fp.read()) @@ -293,8 +295,11 @@ def filter(self, record): if self._AUTHORIZATION_HEADER in sanitized_headers: sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED new_arg.headers = sanitized_headers + msg = arg.message + if sys.version_info.major < 3: + msg = msg.decode('utf-8') new_arg.message = self._DEVELOPER_TOKEN_SUB.sub( - self._REDACTED, arg.message.decode('utf-8')) + self._REDACTED, msg) record.args = (new_arg,) return True diff --git a/setup.py b/setup.py index 5b323e1d..f453fad2 100755 --- a/setup.py +++ b/setup.py @@ -24,9 +24,13 @@ PACKAGES = ['googleads'] -DEPENDENCIES = ['httplib2>=0.9.2', 'oauth2client>=4.0.0,<5.0.0', - 'suds-jurko>=0.6', 'pysocks>=1.5.6', 'pytz>=2015.7', - 'PyYAML>=3.11', 'xmltodict>=0.9.2'] +DEPENDENCIES = ['httplib2>=0.9.2,<1.0.0', 'oauth2client>=4.0.0,<5.0.0', + 'suds-jurko>=0.6,<0.7', 'pysocks>=1.5.6,<2.0.0', 'pytz>=2015.7', + 'PyYAML>=3.11,<4.0', 'xmltodict>=0.9.2,<1.0.0'] + +# Note: Breaking change introduced in pyfakefs 3.3. +TEST_DEPENDENCIES = ['mock>=2.0.0,<3.0.0', 'pyfakefs>=3.2,<3.3', + 'six>=1.11.0,<2.0.0'] CLASSIFIERS = [ 'Intended Audience :: Developers', @@ -116,4 +120,6 @@ def GetVersion(): keywords='adwords dfp google', classifiers=CLASSIFIERS, install_requires=DEPENDENCIES, + tests_require=TEST_DEPENDENCIES, + test_suite='tests', **extra_params) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 8b25b0b0..da380225 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -16,26 +16,24 @@ """Unit tests to cover the adwords module.""" +import datetime import io import os -import StringIO -import sys +import re import tempfile import unittest -import urllib -import urllib2 from xml.etree import ElementTree - import googleads.adwords import googleads.common import googleads.errors import mock +import six import suds +from . import testing -PYTHON2 = sys.version_info[0] == 2 -URL_REQUEST_PATH = ('urllib2' if PYTHON2 else 'urllib.request') +URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] @@ -121,7 +119,7 @@ def GetProxyConfig(http_host=None, http_port=None, https_host=None, disable_certificate_validation=disable_certificate_validation) -class AdWordsHeaderHandlerTest(unittest.TestCase): +class AdWordsHeaderHandlerTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.adwords._AdWordsHeaderHandler class.""" def setUp(self): @@ -400,31 +398,40 @@ def testLoadFromStorageWithNoUserAgent(self): self.assertEquals(client.user_agent, 'unknown') def testGetService_success(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use a custom server. Also test what happens if the server ends with a # trailing slash server = 'https://testing.test.com/' with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' - ) as mock_transport: - mock_plugin.return_value = mock.Mock() - mock_transport.return_value = mock.Mock() - client = GetAdWordsClient() - suds_service = client.GetService( - service, CURRENT_VERSION, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, CURRENT_VERSION, service), - transport=mock_transport.return_value, timeout=3600, - plugins=[mock_plugin.return_value]) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + with mock.patch('googleads.adwords._AdWordsHeaderHandler') as mock_awhh: + with mock.patch('suds.client.Client') as mock_client: + with mock.patch('googleads.common.' + 'SudsServiceProxy') as mock_service_proxy: + with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' + ) as mock_transport: + mock_plugin.return_value = mock.Mock() + mock_awhh.return_value = mock.Mock() + mock_service_proxy.return_value = mock.Mock() + mock_transport.return_value = mock.Mock() + client = GetAdWordsClient() + suds_service = client.GetService( + service, CURRENT_VERSION, server) + + mock_client.assert_called_once_with( + 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' + % (namespace, CURRENT_VERSION, service), + transport=mock_transport.return_value, timeout=3600, + plugins=[mock_plugin.return_value]) + self.assertEqual(suds_service, mock_service_proxy.return_value) + mock_service_proxy.assert_called_once_with( + mock_client.return_value, + mock_awhh.return_value, + packer=googleads.adwords._AdWordsPacker) def testGetService_successWithFileCache(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -448,7 +455,7 @@ def testGetService_successWithFileCache(self): self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_successWithNoCache(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -472,7 +479,7 @@ def testGetService_successWithNoCache(self): self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_successWithoutProxy(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] # Use the default server without a proxy. @@ -505,7 +512,7 @@ def testGetService_badVersion(self): 'CampaignService', '11111') def testGetService_compressionEnabled(self): - service = googleads.adwords._SERVICE_MAP[CURRENT_VERSION].keys()[0] + service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] client = GetAdWordsClient() client.enable_compression = True @@ -539,7 +546,50 @@ def testSetClientCustomerId(self): self.assertEqual(ccid, soap_header.clientCustomerId) -class BatchJobHelperTest(unittest.TestCase): +class AdWordsClientIntegrationTest(unittest.TestCase): + """Integration tests for googleads.adwords.AdWordsClient.""" + + def testServiceMap(self): + server = googleads.adwords._DEFAULT_ENDPOINT + service_map = googleads.adwords._SERVICE_MAP + wsdl_url_template = googleads.adwords.AdWordsClient._SOAP_SERVICE_FORMAT + + for version, services in service_map.items(): + for service, mapping in services.items(): + wsdl_url = wsdl_url_template % (server, mapping, version, service) + try: + six.moves.urllib.request.urlopen(wsdl_url) + except six.moves.urllib.error.HTTPError: + raise ValueError('AdWords API %s does not contain "%s" with mapping ' + '"%s". The generated WSDL URL does not exist:\n%s' + % (version, service, mapping, wsdl_url)) + + +class AdWordsPackerTest(unittest.TestCase): + """Tests for the googleads.adwords._AdWordsPacker class.""" + + def setUp(self): + self.packer = googleads.adwords._AdWordsPacker + + def testAdWordsPackerForServiceQuery(self): + query = (googleads.adwords.ServiceQueryBuilder() + .Select('Id', 'Name', 'Status') + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, 100) + .Build()) + + query_regex = (r'SELECT (.*) WHERE Status = "ENABLED"' + r' ORDER BY Name ASC LIMIT 0,100') + + self.assertRegexpMatches(self.packer.Pack(query), query_regex) + + def testAdWordsPackerForUnsupportedObjectType(self): + obj = object() + self.assertEqual(self.packer.Pack(obj), obj) + + +class BatchJobHelperTest(testing.CleanUtilityRegistryTestCase): """Test suite for BatchJobHelper utility.""" @@ -565,12 +615,13 @@ def testUploadOperations(self): with mock.patch('googleads.adwords.IncrementalUploadHelper' '._InitializeURL') as mock_init: mock_init.return_value = 'https://www.google.com' - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch( + '%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: self.batch_job_helper.UploadOperations([[]]) mock_open.assert_called_with(mock_request) -class BatchJobUploadRequestBuilderTest(unittest.TestCase): +class BatchJobUploadRequestBuilderTest(testing.CleanUtilityRegistryTestCase): """Test suite for the BatchJobUploadRequestBuilder.""" @@ -762,7 +813,7 @@ def GenerateValidRequest(self, operation_type, num_operations=1): self.ExpandOperandTemplate(operation_type, op['operand']) ) for op in ops]) - request = self.RAW_API_REQUEST_TEMPLATE.decode('utf-8') % ( + request = self.RAW_API_REQUEST_TEMPLATE % ( self.version, self.version, method, ops_xml, method) return (ops, request) @@ -943,7 +994,7 @@ def testGenerateRawRequestXMLFromSingleOperation(self): operations = mutate[i] self.assertEqual(operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -954,7 +1005,8 @@ def testGenerateRawRequestXMLFromSingleOperation(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -963,7 +1015,7 @@ def testGenerateRawRequestXMLFromSingleOperation(self): ops[i]['operand']['name']) amount = operand.find('{%s}amount' % self.request_builder._adwords_endpoint) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -990,7 +1042,7 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -999,7 +1051,8 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1008,7 +1061,7 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): ops[i]['operand']['name']) amount = operand.find( '{%s}amount' % self.request_builder._adwords_endpoint) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1034,7 +1087,7 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): operations = mutate[i] self.assertEqual(operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1045,7 +1098,8 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1054,7 +1108,7 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): ops[i]['operand']['name']) amount = operand.find('{%s}amount' % self.request_builder._adwords_endpoint) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1072,14 +1126,14 @@ def testGetRawOperationsFromValidSingleOperationMutateLabelRequest(self): mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual(mutate.tag, '{%s}mutateLabel' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1088,7 +1142,8 @@ def testGetRawOperationsFromValidSingleOperationMutateLabelRequest(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(int(operand.find( '{%s}campaignId' % self.request_builder._adwords_endpoint).text), ops[i]['operand']['campaignId']) @@ -1108,14 +1163,14 @@ def testGetRawOperationsFromValidSingleOperationRequest(self): mutate = self.request_builder._GetRawOperationsFromXML(request) self.assertEqual(mutate.tag, '{%s}mutate' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1124,7 +1179,8 @@ def testGetRawOperationsFromValidSingleOperationRequest(self): ops[i]['xsi_type']) operand = operations.find( '{%s}operand' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1133,7 +1189,7 @@ def testGetRawOperationsFromValidSingleOperationRequest(self): ops[i]['operand']['name']) amount = operand.find( '{%s}amount' % self.request_builder._adwords_endpoint) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1155,14 +1211,14 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): self.assertEqual( mutate.tag, '{%s}mutate' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1171,7 +1227,8 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): ops[i]['xsi_type']) operand = (operations.find( '{%s}operand' % self.request_builder._adwords_endpoint)) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1180,7 +1237,7 @@ def testGetRawOperationsFromValidMultipleOperationRequest(self): ops[i]['operand']['name']) amount = (operand.find( '{%s}amount' % self.request_builder._adwords_endpoint)) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1201,14 +1258,14 @@ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): self.assertEqual( mutate.tag, u'{%s}mutate' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) for i in range(0, operations_amount): operations = mutate[i] self.assertEqual( operations.tag, '{%s}operations' % self.request_builder._adwords_endpoint) - self.assertTrue(len(operations._children) == len(ops[i].keys())) + self.assertTrue(len(operations.getchildren()) == len(ops[i].keys())) self.assertEqual(operations.find( '{%s}operator' % self.request_builder._adwords_endpoint).text, ops[i]['operator']) @@ -1217,7 +1274,8 @@ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): ops[i]['xsi_type']) operand = (operations.find( '{%s}operand' % self.request_builder._adwords_endpoint)) - self.assertTrue(len(operand._children) == len(ops[i]['operand'].keys())) + self.assertTrue(len(operand.getchildren()) == + len(ops[i]['operand'].keys())) self.assertEqual(operand.find( '{%s}budgetId' % self.request_builder._adwords_endpoint).text, ops[i]['operand']['budgetId']) @@ -1226,7 +1284,7 @@ def testGetRawOperationsFromValidMultipleOperationUnicodeRequest(self): ops[i]['operand']['name']) amount = (operand.find( '{%s}amount' % self.request_builder._adwords_endpoint)) - self.assertTrue(len(amount._children) == + self.assertTrue(len(amount.getchildren()) == len(ops[i]['operand']['amount'].keys())) self.assertEqual(amount.find( '{%s}microAmount' % self.request_builder._adwords_endpoint).text, @@ -1246,7 +1304,7 @@ def testGetRawOperationsFromValidZeroOperationRequest(self): self.assertEqual( mutate.tag, '{%s}mutate' % self.request_builder._adwords_endpoint) - self.assertTrue(len(mutate._children) == operations_amount) + self.assertTrue(len(mutate.getchildren()) == operations_amount) def testGetRawOperationsFromInvalidRequest(self): """Test whether an invalid API request raises an Exception.""" @@ -1339,7 +1397,7 @@ def testBuildUploadRequestBodyWithOnlyPrefix(self): self.assertTrue(increment == self.request_body_start) -class IncrementalUploadHelperTest(unittest.TestCase): +class IncrementalUploadHelperTest(testing.CleanUtilityRegistryTestCase): """Test suite for the IncrementalUploadHelper.""" @@ -1351,7 +1409,7 @@ def setUp(self): self.original_url = 'https://goo.gl/w8tkpK' self.initialized_url = 'https://goo.gl/Xtaq83' - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: mock_open.return_value.headers = { 'location': self.initialized_url } @@ -1376,9 +1434,9 @@ def testDump(self): self.assertEqual(expected, dump_data) def testLoad(self): - s = StringIO.StringIO(self.incremental_uploader_dump) + s = six.StringIO(self.incremental_uploader_dump) - with mock.patch('urllib2.urlopen') as mock_open: + with mock.patch('%s.urlopen' % URL_REQUEST_PATH) as mock_open: mock_open.return_value.headers = { 'location': self.initialized_url } @@ -1403,7 +1461,7 @@ def testUploadOperations(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: self.incremental_uploader.UploadOperations([[]], True) mock_open.assert_called_with(mock_request) @@ -1412,7 +1470,7 @@ def testUploadOperationsWithError(self): error_code = '404' error_message = 'I AM ERROR' error_headers = {} - http_error = urllib2.HTTPError( + http_error = six.moves.urllib.error.HTTPError( error_url, error_code, error_message, error_headers, None) with mock.patch('googleads.adwords.BatchJobHelper.' @@ -1420,11 +1478,11 @@ def testUploadOperationsWithError(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: mock_open.side_effect = http_error self.assertRaises( - urllib2.HTTPError, self.incremental_uploader.UploadOperations, - [[]], True) + six.moves.urllib.error.HTTPError, + self.incremental_uploader.UploadOperations, [[]], True) mock_open.assert_called_with(mock_request) def testUploadOperationsAfterFinished(self): @@ -1433,14 +1491,14 @@ def testUploadOperationsAfterFinished(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('urllib2.OpenerDirector.open'): + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH): self.incremental_uploader.UploadOperations([[]], True) self.assertRaises( googleads.errors.AdWordsBatchJobServiceInvalidOperationError, self.incremental_uploader.UploadOperations, {}) -class ResponseParserTest(unittest.TestCase): +class ResponseParserTest(testing.CleanUtilityRegistryTestCase): """Test suite for the ResponseParser.""" def setUp(self): @@ -1522,7 +1580,7 @@ def testParseUnicodeResponse(self): self.assertTrue(campaign['name'] == name) -class ReportDownloaderTest(unittest.TestCase): +class ReportDownloaderTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.adwords.ReportDownloader class.""" def setUp(self): @@ -1547,18 +1605,18 @@ def setUp(self): self.adwords_client, self.version) def testDownloadReport(self): - output_file = io.StringIO() + output_file = six.StringIO() report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} serialized_report = 'nuinbwuign' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' - report_contents = io.StringIO() if PYTHON2 else io.BytesIO() - report_contents.write(report_data if PYTHON2 + report_contents = six.StringIO() if six.PY2 else io.BytesIO() + report_contents.write(report_data if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1588,18 +1646,18 @@ def testDownloadReport(self): skip_report_header=True, use_raw_enum_values=False) def testDownloadReportWithAllLoggingEnabled(self): - output_file = io.StringIO() + output_file = six.StringIO() report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} serialized_report = 'nuinbwuign' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' - report_contents = io.StringIO() if PYTHON2 else io.BytesIO() - report_contents.write(report_data if PYTHON2 + report_contents = six.StringIO() if six.PY2 else io.BytesIO() + report_contents.write(report_data if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1636,14 +1694,14 @@ def testDownloadReportAsString(self): report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} serialized_report = 'nuinbwuign' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING アングリーバード' report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if PYTHON2 + report_contents.write(report_data.encode('utf-8') if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1673,14 +1731,15 @@ def testDownloadReportAsString(self): def testDownloadReportAsStringWithAwql(self): query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' file_format = 'CSV' - post_body = urllib.urlencode({'__fmt': file_format, '__rdquery': query}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__fmt': file_format, + '__rdquery': query}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING アングリーバード' report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if PYTHON2 + report_contents.write(report_data.encode('utf-8') if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1706,7 +1765,7 @@ def testDownloadReportAsStringWithAwql(self): include_zero_impressions=True, use_raw_enum_values=False) def testDownloadReportCheckFormat_CSVStringSuccess(self): - output_file = io.StringIO() + output_file = six.StringIO() try: self.report_downloader._DownloadReportCheckFormat('CSV', output_file) @@ -1715,7 +1774,7 @@ def testDownloadReportCheckFormat_CSVStringSuccess(self): 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDBinaryFileSuccess(self): - output_file = io.StringIO() + output_file = six.StringIO() try: self.report_downloader._DownloadReportCheckFormat('CSV', output_file) @@ -1734,14 +1793,14 @@ def testDownloadReportCheckFormat_GZIPPEDBytesIOSuccess(self): 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDStringFailure(self): - output_file = io.StringIO() + output_file = six.StringIO() self.assertRaises(googleads.errors.GoogleAdsValueError, self.report_downloader._DownloadReportCheckFormat, 'GZIPPED_CSV', output_file) def testDownloadReportCheckFormat_Issue152(self): - output_file = io.StringIO() + output_file = six.StringIO() output_file.mode = 'w+b' # Verify writing and reading works. try: @@ -1761,62 +1820,82 @@ def testDownloadReportCheckFormat_Issue152(self): 'unexpectedly!') def testDownloadReport_failure(self): - output_file = io.StringIO() + output_file = six.StringIO() report_definition = {'table': 'campaigns', 'downloadFormat': 'CSV'} serialized_report = 'hjuibnibguo' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'Page not found. :-(' - report_contents = io.StringIO() if PYTHON2 else io.BytesIO() - report_contents.write(report_data if PYTHON2 else bytes(report_data, + report_contents = six.StringIO() if six.PY2 else io.BytesIO() + report_contents.write(report_data if six.PY2 else bytes(report_data, 'utf-8')) + logger_request_summary_template = 'Request Summary: %s' report_contents.seek(0) fake_response = mock.Mock() fake_response.read = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - error = urllib2.HTTPError('', 400, 'Bad Request', {}, fp=fake_response) + error = six.moves.urllib.error.HTTPError('', 400, 'Bad Request', {}, + fp=fake_response) self.marshaller.process.return_value = serialized_report with mock.patch('suds.mx.Content') as mock_content: with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - mock_request_instance = mock.Mock() - mock_request.return_value = mock_request_instance - mock_request_instance.get_full_url.return_value = 'https://google.com/' - mock_request_instance.headers = {} - self.opener.open.side_effect = error - self.assertRaises( - googleads.errors.AdWordsReportError, - self.report_downloader.DownloadReport, report_definition, - output_file) - - mock_request.assert_called_once_with( - ('https://adwords.google.com/api/adwords/reportdownload/%s' - % self.version), post_body, headers) - self.opener.open.assert_called_once_with(mock_request.return_value) - self.marshaller.process.assert_called_once_with( - mock_content.return_value) - self.assertEqual('', output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with() + with mock.patch('googleads.adwords._report_logger') as mock_logger: + with mock.patch('googleads.adwords.ReportDownloader' + '._ExtractRequestSummaryFields') as mock_extract_fds: + mock_logger.isEnabledFor.return_value = True + mock_extract_fds_return_value = mock.Mock() + mock_extract_fds.return_value = mock_extract_fds_return_value + mock_request_instance = mock.Mock() + mock_request.return_value = mock_request_instance + mock_request_instance.get_full_url.return_value = ( + 'https://google.com/') + mock_request_instance.headers = {} + self.opener.open.side_effect = error + + try: + self.report_downloader.DownloadReport( + report_definition, output_file) + except googleads.errors.AdWordsReportError as ex: + mock_extract_fds.assert_called_once_with( + mock_request_instance, error=ex) + mock_logger.warning.assert_called_once_with( + logger_request_summary_template, + mock_extract_fds_return_value) + + mock_request.assert_called_once_with( + ('https://adwords.google.com/api/adwords/reportdownload/%s' + % self.version), post_body, headers) + self.opener.open.assert_called_once_with(mock_request.return_value) + self.marshaller.process.assert_called_once_with( + mock_content.return_value) + self.assertEqual('', output_file.getvalue()) + h_handler = self.header_handler + h_handler.GetReportDownloadHeaders.assert_called_once_with() def testDownloadReportWithAwql(self): - output_file = io.StringIO() - query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' + output_file = six.StringIO() + query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId').From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .Build()) file_format = 'CSV' - post_body = urllib.urlencode({'__fmt': file_format, '__rdquery': query}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__fmt': file_format, + '__rdquery': query}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' - report_contents = io.StringIO() if PYTHON2 else io.BytesIO() - report_contents.write(report_data if PYTHON2 else bytes(report_data, - 'utf-8')) + report_contents = six.StringIO() if six.PY2 else io.BytesIO() + report_contents.write(report_data if six.PY2 + else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() fake_response.read = report_contents.read @@ -1845,14 +1924,14 @@ def testDownloadReportWithBytesIO(self): report_definition = {'table': 'campaigns', 'downloadFormat': 'GZIPPED_CSV'} serialized_report = 'nuinbwuign' - post_body = urllib.urlencode({'__rdxml': serialized_report}) - if not PYTHON2: + post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) + if six.PY3: post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if PYTHON2 + report_contents.write(report_data.encode('utf-8') if six.PY2 else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() @@ -1889,7 +1968,7 @@ def testExtractError_badRequest(self): '%s%s' '%s') content = content_template % (type_, trigger, field_path) - response.read.return_value = (content if PYTHON2 + response.read.return_value = (content if six.PY2 else bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) @@ -1903,7 +1982,7 @@ def testExtractError_badRequest(self): # Check that if the XML fields are empty, this still functions. content = content_template % ('', '', '') - response.read.return_value = (content if PYTHON2 + response.read.return_value = (content if six.PY2 else bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) self.assertEqual(None, rval.type) @@ -1916,7 +1995,7 @@ def testExtractError_malformedBadRequest(self): content = ('' '12345678' '') - response.read.return_value = (content if PYTHON2 + response.read.return_value = (content if six.PY2 else bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) @@ -1929,7 +2008,7 @@ def testExtractError_notBadRequest(self): response = mock.Mock() response.code = 400 content = 'Page not found!' - response.read.return_value = (content if PYTHON2 + response.read.return_value = (content if six.PY2 else bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) @@ -1966,5 +2045,429 @@ def testExtractResponseHeaders(self): self.assertEqual(dict_headers, expected_headers) +class QueryBuilderTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.adwords._QueryBuilder class.""" + + def testSelect(self): + with self.assertRaises(NotImplementedError): + googleads.adwords._QueryBuilder().Select() + + def testFailUsingCopyConstructor(self): + with self.assertRaises(googleads.errors.GoogleAdsValueError): + (googleads.adwords + ._QueryBuilder('SELECT Id FROM CAMPAIGN_PERFORMANCE_REPORT')) + + +class ReportQueryBuilderTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.adwords.ReportQueryBuilder class.""" + + def testCopyConstructor(self): + # Test using date range. + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT' + ' WHERE CampaignStatus = "ENABLED" DURING YESTERDAY') + previous_query_builder = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .During('YESTERDAY')) + actual_query = (googleads.adwords.ReportQueryBuilder(previous_query_builder) + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + # Test using start and end dates. + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT' + ' WHERE CampaignStatus = "ENABLED"' + ' DURING 20170101,20170131') + previous_query_builder = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .During(start_date='20170101', + end_date='20170131')) + actual_query = (googleads.adwords.ReportQueryBuilder(previous_query_builder) + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testFailUsingCopyConstructor(self): + builder = googleads.adwords._QueryBuilder() + builder.select = 'Id' + with self.assertRaises(googleads.errors.GoogleAdsValueError): + googleads.adwords.ReportQueryBuilder(builder) + + def testBuild(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_stringWhereValue(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT' + ' WHERE CampaignStatus = "ENABLED" DURING YESTERDAY') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .During('YESTERDAY') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_numericWhereValue(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' ADGROUP_PERFORMANCE_REPORT' + ' WHERE AverageCpm >= 5.6 DURING TODAY') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('ADGROUP_PERFORMANCE_REPORT') + .Where('AverageCpm').GreaterThanOrEqualTo(5.6) + .During('TODAY') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_multipleStringWhereValues(self): + expected_awql = ('SELECT Id, CampaignId, CampaignName FROM' + ' AD_PERFORMANCE_REPORT' + ' WHERE CampaignName CONTAINS_ALL ["white", "black"]' + ' DURING LAST_WEEK') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('Id', 'CampaignId', 'CampaignName') + .From('AD_PERFORMANCE_REPORT') + .Where('CampaignName').ContainsAll('white', 'black') + .During('LAST_WEEK') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_multipleNumericWhereValues(self): + expected_awql = ('SELECT Id, CampaignId, CampaignName FROM' + ' AD_PERFORMANCE_REPORT' + ' WHERE CampaignId IN [1234, 5678] DURING LAST_WEEK') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('Id', 'CampaignId', 'CampaignName') + .From('AD_PERFORMANCE_REPORT') + .Where('CampaignId').In(1234, 5678) + .During('LAST_WEEK') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_multipleWhereConditions(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' ADGROUP_PERFORMANCE_REPORT' + ' WHERE Clicks >= 500 AND CampaignName' + ' CONTAINS_IGNORE_CASE "promotion"' + ' AND AdGroupName STARTS_WITH "adwords_"' + ' AND BiddingStrategyName STARTS_WITH_IGNORE_CASE "europe"' + ' AND CustomerDescriptiveName CONTAINS "goog"' + ' AND CustomerDescriptiveName DOES_NOT_CONTAIN "asia"' + ' AND AccountDescriptiveName DOES_NOT_CONTAIN_IGNORE_CASE' + ' "group 3" AND CampaignStatus != "REMOVED"' + ' AND AdGroupStatus NOT_IN ["REMOVED", "PAUSED"]' + ' AND AdNetworkType1 CONTAINS_ANY ["SEARCH", "DISPLAY"]' + ' AND AdNetworkType2 CONTAINS_NONE' + ' ["YOUTUBE_SEARCH", "UNKNOWN"] AND AverageCpv > 20.7' + ' AND AllConversions < 100.6' + ' DURING 20170601,20170630') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('ADGROUP_PERFORMANCE_REPORT') + .Where('Clicks').GreaterThanOrEqualTo(500) + .Where('CampaignName').ContainsIgnoreCase('promotion') + .Where('AdGroupName').StartsWith('adwords_') + .Where('BiddingStrategyName').StartsWithIgnoreCase('europe') + .Where('CustomerDescriptiveName').Contains('goog') + .Where('CustomerDescriptiveName').DoesNotContain('asia') + .Where('AccountDescriptiveName').DoesNotContainIgnoreCase( + 'group 3') + .Where('CampaignStatus').NotEqualTo('REMOVED') + .Where('AdGroupStatus').NotIn('REMOVED', 'PAUSED') + .Where('AdNetworkType1').ContainsAny('SEARCH', 'DISPLAY') + .Where('AdNetworkType2').ContainsNone('YOUTUBE_SEARCH', + 'UNKNOWN') + .Where('AverageCpv').GreaterThan(20.7) + .Where('AllConversions').LessThan(100.6) + .During(start_date='20170601', end_date='20170630') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_noWhereClause(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' ADGROUP_PERFORMANCE_REPORT DURING TODAY') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('ADGROUP_PERFORMANCE_REPORT') + .During('TODAY') + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_noDuringClause(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' ADGROUP_PERFORMANCE_REPORT' + ' WHERE Clicks <= 500') + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('ADGROUP_PERFORMANCE_REPORT') + .Where('Clicks').LessThanOrEqualTo(500) + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testBuild_selectIsNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().Build() + + def testBuild_fromIsNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().Select('Id').Build() + + def testDuring_usingPythonDateTime(self): + expected_awql = ('SELECT CampaignId, CampaignName FROM' + ' CAMPAIGN_PERFORMANCE_REPORT' + ' WHERE CampaignStatus = "ENABLED"' + ' DURING 20170501,20170531') + start_date = datetime.date(2017, 5, 1) + end_date = start_date + datetime.timedelta(days=30) + actual_query = (googleads.adwords.ReportQueryBuilder() + .Select('CampaignId', 'CampaignName') + .From('CAMPAIGN_PERFORMANCE_REPORT') + .Where('CampaignStatus').EqualTo('ENABLED') + .During(start_date=start_date, end_date=end_date) + .Build()) + self.assertEqual(expected_awql, str(actual_query)) + + def testDuring_allParametersNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().During() + + def testDuring_allParametersNotNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().During('TODAY', '20170101', + '20170131') + + def testDuring_startOrEndDateNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().During(start_date='20170101') + with self.assertRaises(ValueError): + googleads.adwords.ReportQueryBuilder().During(end_date='20170131') + + +class ServiceQueryBuilderTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.adwords.ServiceQueryBuilder class.""" + + def testCopyConstructor(self): + awql_regex = (r'SELECT (.*) WHERE Status = "ENABLED"' + r' ORDER BY Name ASC LIMIT 0,100') + selected_fields = ['Id', 'Name'] + previous_query_builder = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, 100)) + + actual_query = googleads.adwords.ServiceQueryBuilder( + previous_query_builder).Build() + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause can show fields listed in any orders. + six.assertCountEqual( + self, selected_fields, + [field.strip() for field in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testFailUsingCopyConstructor(self): + builder = googleads.adwords._QueryBuilder() + builder.select = 'Id' + with self.assertRaises(googleads.errors.GoogleAdsValueError): + googleads.adwords.ServiceQueryBuilder(builder) + + def testBuild(self): + awql_regex = (r'SELECT (.*) LIMIT 0,100') + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 100) + .Build()) + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause can show fields listed in any orders. + six.assertCountEqual( + self, selected_fields, + [field.strip() for field in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testBuild_duplicateSelectedFieldsRetainOnlyUnique(self): + awql_regex = (r'SELECT (.*) LIMIT 0,100') + selected_fields = ['Id', 'Name', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 100) + .Build()) + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause retains only unique fields. + six.assertCountEqual( + self, set(selected_fields), + [field.strip() for field in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testBuild_whereConditions(self): + awql_regex = (r'SELECT (.*)' + r' WHERE Name CONTAINS_IGNORE_CASE "promotion"' + r' AND Status NOT_IN \["REMOVED", "PAUSED"\]' + r' ORDER BY Name ASC' + r' LIMIT 100,100') + selected_fields = ['Id', 'Name', 'Status'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Where('Name').ContainsIgnoreCase('promotion') + .Where('Status').NotIn('REMOVED', 'PAUSED') + .OrderBy('Name') + .Limit(100, 100) + .Build()) + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause can show fields listed in any orders. + six.assertCountEqual( + self, selected_fields, + [field.strip() for field in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testBuild_orderByDesc(self): + awql_regex = (r'SELECT (.*)' + r' ORDER BY Name DESC' + r' LIMIT 100,100') + selected_fields = ['Id', 'Name', 'Status'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .OrderBy('Name', ascending=False) + .Limit(100, 100) + .Build()) + match = re.match(awql_regex, str(actual_query)) + + # The SELECT clause can show fields listed in any orders. + six.assertCountEqual( + self, selected_fields, + [field.strip() for field in match.group(1).split(',')]) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testBuild_selectIsNone(self): + with self.assertRaises(ValueError): + googleads.adwords.ServiceQueryBuilder().Build() + + def testBuild_limitStartIndexOrPageSizeIsNoneButNotTheOther(self): + # A page size is not specified. + with self.assertRaises(ValueError): + (googleads.adwords.ServiceQueryBuilder() + .Select('Id') + .OrderBy('Name', ascending=False) + .Limit(100, None) + .Build()) + # A start index is not specified. + with self.assertRaises(ValueError): + (googleads.adwords.ServiceQueryBuilder() + .Select('Id') + .OrderBy('Name', ascending=False) + .Limit(None, 100) + .Build()) + + +class ServiceQueryTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.adwords.ServiceQuery class.""" + + def testNextPage(self): + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 100) + .Build()) + # Do next page and check if the LIMIT clause is modified correctly. + awql_regex = (r'SELECT (.*) LIMIT 100,100') + actual_query.NextPage() + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testNextPage_userProvidedPage(self): + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 100) + .Build()) + # Do next page and check if the LIMIT clause is modified correctly. + awql_regex = (r'SELECT (.*) LIMIT 50,100') + actual_query.NextPage(50) + self.assertRegexpMatches(str(actual_query), awql_regex) + + def testNextPageFail(self): + actual_query = googleads.adwords.ServiceQuery('SELECT Id, Name', None, 100) + + with self.assertRaises(ValueError): + actual_query.NextPage() + + def testHasNext(self): + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 1) + .Build()) + awql_regex = (r'SELECT (.*) LIMIT 0,1') + self.assertRegexpMatches(str(actual_query), awql_regex) + + page = {'totalNumEntries': 3} + + self.assertTrue(actual_query.HasNext(page)) + awql_regex = (r'SELECT (.*) LIMIT 1,1') + actual_query.NextPage() + self.assertRegexpMatches(str(actual_query), awql_regex) + + self.assertTrue(actual_query.HasNext(page)) + awql_regex = (r'SELECT (.*) LIMIT 2,1') + actual_query.NextPage() + self.assertRegexpMatches(str(actual_query), awql_regex) + + self.assertFalse(actual_query.HasNext(page)) + + def testHasNext_userProvidedPage(self): + selected_fields = ['Id', 'Name'] + actual_query = (googleads.adwords.ServiceQueryBuilder() + .Select(*selected_fields) + .Limit(0, 1) + .Build()) + awql_regex = (r'SELECT (.*) LIMIT 0,1') + self.assertRegexpMatches(str(actual_query), awql_regex) + + page = {'totalNumEntries': 80} + self.assertFalse(actual_query.HasNext(page, 100)) + + def testHasNextFail(self): + actual_query = googleads.adwords.ServiceQuery('SELECT Id, Name', None, 100) + + page = {'totalNumEntries': 10} + with self.assertRaises(ValueError): + actual_query.HasNext(page) + + def testPager(self): + service = 'CampaignService' + fake_page = {'totalNumEntries': 3} + + with mock.patch('suds.client.Client'): + client = GetAdWordsClient(cache=suds.cache.FileCache) + service = client.GetService(service, CURRENT_VERSION) + with mock.patch.object(service, 'query', + return_value=fake_page, autospec=True): + query = (googleads.adwords.ServiceQueryBuilder() + .Select('Id', 'Name') + .Limit(0, 1) + .Build()) + i = 0 + for page in query.Pager(service): + self.assertEqual(fake_page['totalNumEntries'], + page['totalNumEntries']) + i += 1 + # Pager should return the number of page equal to the 'totalNumEntries' + # returned by a service. + self.assertEqual(fake_page['totalNumEntries'], i) + + if __name__ == '__main__': unittest.main() diff --git a/tests/common_test.py b/tests/common_test.py index 20261188..f069e569 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -15,26 +15,29 @@ """Unit tests to cover the common module.""" -import datetime -import io +import numbers +import os +import ssl import unittest -from urllib import addinfourl -import urllib2 import warnings - from pyfakefs import fake_filesystem from pyfakefs import fake_tempfile import mock +import six import suds import yaml import googleads.common import googleads.errors import googleads.oauth2 +from . import testing + + +URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' -class CommonTest(unittest.TestCase): +class CommonTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.common module.""" # Dictionaries with all the required OAuth2 keys @@ -82,12 +85,11 @@ def test(self): self.test2 = Test2 def tearDown(self): + super(CommonTest, self).tearDown() self.locale_patcher.stop() def testShouldWarnWithBadEncoding(self): self.locale_patcher.return_value = (None, None) - yaml_doc = self._CreateYamlDoc({'one': {'needed': 'd', 'keys': 'e'}}, - 'one', self._OAUTH_INSTALLED_APP_DICT) test_major_value = 2 test_minor_value = 6 test_micro_value = 9 @@ -95,11 +97,8 @@ def testShouldWarnWithBadEncoding(self): with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): with mock.patch('googleads.common._logger') as mock_logger: - with mock.patch( - 'googleads.common.open', self.fake_open, create=True): - googleads.common.LoadFromString(yaml_doc, 'one', - ['needed', 'keys'], ['other']) - mock_logger.warn.assert_called_once() + googleads.common.CommonClient() + mock_logger.warn.assert_called_once() def _CreateYamlFile(self, data, insert_oauth2_key=None, oauth_dict=None): """Return the filename of a yaml file created for testing.""" @@ -361,13 +360,7 @@ def testExtractResponseSummaryFieldsWithoutFault(self): self.assertEqual(expected_result, googleads.common._ExtractResponseSummaryFields(doc)) - def testLoadFromString_deprecatedWarningLoggerByMicroValue(self): - yaml_doc = self._CreateYamlDoc({ - 'one': { - 'needed': 'd', - 'keys': 'e' - } - }, 'one', self._OAUTH_INSTALLED_APP_DICT) + def testCommonClient_deprecatedWarningLoggerByMicroValue(self): test_major_value = 2 test_minor_value = 7 test_micro_value = 6 @@ -375,17 +368,12 @@ def testLoadFromString_deprecatedWarningLoggerByMicroValue(self): with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): with mock.patch('googleads.common._logger') as mock_logger: - with mock.patch( - 'googleads.common.open', self.fake_open, create=True): - googleads.common.LoadFromString(yaml_doc, 'one', - ['needed', 'keys'], ['other']) - mock_logger.warning.assert_called_once_with( - googleads.common._DEPRECATED_VERSION_TEMPLATE, - test_major_value, test_minor_value, test_micro_value) + googleads.common.CommonClient() + mock_logger.warning.assert_called_once_with( + googleads.common._DEPRECATED_VERSION_TEMPLATE, + test_major_value, test_minor_value, test_micro_value) def testLoadFromString_deprecatedWarningLoggerByMinorValue(self): - yaml_doc = self._CreateYamlDoc({'one': {'needed': 'd', 'keys': 'e'}}, - 'one', self._OAUTH_INSTALLED_APP_DICT) test_major_value = 2 test_minor_value = 6 test_micro_value = 9 @@ -393,13 +381,10 @@ def testLoadFromString_deprecatedWarningLoggerByMinorValue(self): with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): with mock.patch('googleads.common._logger') as mock_logger: - with mock.patch( - 'googleads.common.open', self.fake_open, create=True): - googleads.common.LoadFromString(yaml_doc, 'one', - ['needed', 'keys'], ['other']) - mock_logger.warning.assert_called_once_with( - googleads.common._DEPRECATED_VERSION_TEMPLATE, - test_major_value, test_minor_value, test_micro_value) + googleads.common.CommonClient() + mock_logger.warning.assert_called_once_with( + googleads.common._DEPRECATED_VERSION_TEMPLATE, + test_major_value, test_minor_value, test_micro_value) def testLoadFromString_emptyYamlString(self): yaml_doc = '' @@ -940,6 +925,24 @@ def testPackForSuds(self): 'metadata': {'xsi_type': 'metadata', 'a': {'b': 'c'}}}, {'i do not have': 'a type'}], input_list) + def testPackForSuds_applyCustomPacker(self): + class CustomPacker(googleads.common.SudsPacker): + @classmethod + def Pack(cls, obj): + if isinstance(obj, numbers.Number): + return {'xsi_type': 'Integer', 'value': str(int(obj))} + return obj + + factory = mock.Mock() + factory.create.return_value = mock.MagicMock() + factory.create.return_value.__iter__.return_value = iter( + [('Number.Type', 0), ('value', 1)]) + number = 3.14159265358979323846264 + + rval = googleads.common._PackForSuds(number, factory, CustomPacker) + self.assertEqual('Integer', getattr(rval, 'Number.Type')) + self.assertEqual('3', rval.value) + def testPackForSuds_secondNamespace(self): factory = mock.Mock() factory.create.side_effect = [suds.TypeNotFound(''), mock.MagicMock()] @@ -949,29 +952,6 @@ def testPackForSuds_secondNamespace(self): factory.create.assert_any_call('ns0:EliteCampaign') self.assertEqual('Sales', rval.name) - def testPackForSuds_datetime_packer(self): - factory = mock.Mock() - factory.create.return_value = mock.MagicMock() - factory.create.return_value.__iter__.return_value = iter( - [('abc', 0)]) - - def sample_packer(dt): - return {'xsi_type': 'abc', 'test': dt.year} - - # Test that our packer function is called for datetimes - rval = googleads.common._PackForSuds( - {'param': datetime.datetime(2017, 1, 1, 0, 0, 0)}, - factory, datetime_packer=sample_packer) - - self.assertEqual(2017, rval['param'].test) - - # Test that our packer function is called for dates - rval = googleads.common._PackForSuds( - {'param': datetime.date(2017, 1, 1)}, - factory, datetime_packer=sample_packer) - - self.assertEqual(2017, rval['param'].test) - class SudsServiceProxyTest(unittest.TestCase): """Tests for the googleads.common.SudsServiceProxy class.""" @@ -1025,18 +1005,24 @@ def testMarshalled(self): marshalled_context = mock.Mock() marshalled_context.envelope = envelope - with mock.patch('googleads.common._ExtractRequestSummaryFields') as mk_ext: - self.logging_message_plugin.marshalled(marshalled_context) - mk_ext.assert_called_once_with(envelope) + with mock.patch('googleads.common._logger') as mock_logger: + mock_logger.isEnabledFor.return_value = True + with mock.patch( + 'googleads.common._ExtractRequestSummaryFields') as mk_ext: + self.logging_message_plugin.marshalled(marshalled_context) + mk_ext.assert_called_once_with(envelope) def testParsed(self): reply = 'reply' parsed_context = mock.Mock() parsed_context.reply = reply - with mock.patch('googleads.common._ExtractResponseSummaryFields') as mk_ext: - self.logging_message_plugin.parsed(parsed_context) - mk_ext.assert_called_once_with(reply) + with mock.patch('googleads.common._logger') as mock_logger: + mock_logger.isEnabledFor.return_value = True + with mock.patch( + 'googleads.common._ExtractResponseSummaryFields') as mk_ext: + self.logging_message_plugin.parsed(parsed_context) + mk_ext.assert_called_once_with(reply) class ProxyConfigTest(unittest.TestCase): @@ -1049,7 +1035,7 @@ def setUp(self): self.proxy_port2 = 'port2' self.username = 'username' self.password = 'password' - self.cafile = '/tmp/file.ca' + self.cafile = os.path.join(os.path.dirname(__file__), 'test_data/test.crt') self.proxy_no_credentials = googleads.common.ProxyConfig.Proxy( self.proxy_host1, self.proxy_port1) @@ -1058,6 +1044,32 @@ def setUp(self): self.proxy_host2, self.proxy_port2, username=self.username, password=self.password) + def testBuildOpenerWithConfig(self): + https_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, + self.proxy_port1) + proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) + + with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mck_build_opener: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as mck_https_hndlr: + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as mck_prxy_hndlr: + mck_https_hndlr_instance = mock.Mock() + mck_https_hndlr.return_value = mck_https_hndlr_instance + mck_prxy_hndlr_instance = mock.Mock() + mck_prxy_hndlr.return_value = mck_prxy_hndlr_instance + proxy_config.BuildOpener() + mck_build_opener.assert_called_once_with( + *[mck_https_hndlr_instance, mck_prxy_hndlr_instance]) + + def testBuildOpenerWithDefaultConfig(self): + proxy_config = googleads.common.ProxyConfig() + + with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mck_build_opener: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as mock_https_hndlr: + mock_https_hndlr_instance = mock.Mock + mock_https_hndlr.return_value = mock_https_hndlr_instance + proxy_config.BuildOpener() + mck_build_opener.assert_called_once_with(*[mock_https_hndlr_instance]) + def testProxyToStringWithCredentials(self): proxy = googleads.common.ProxyConfig.Proxy( self.proxy_host1, self.proxy_port1, username=self.username, @@ -1082,26 +1094,34 @@ def testProxyToStringWithOnlyUsername(self): def testProxyConfigGetHandlersWithNoProxyOrSSLContext(self): proxy_config = googleads.common.ProxyConfig() - self.assertEqual(proxy_config.GetHandlers(), []) + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertIn(https_handler_instance, proxy_config.GetHandlers()) def testProxyConfigGetHandlersWithProxy(self): http_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, self.proxy_port1) - with mock.patch('urllib2.ProxyHandler') as proxy_handler: - proxy_handler.return_value = mock.Mock() + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: + proxy_handler_instance = mock.Mock() + proxy_handler.return_value = proxy_handler_instance proxy_config = googleads.common.ProxyConfig(http_proxy=http_proxy) - self.assertEqual(proxy_config.GetHandlers(), [proxy_handler.return_value]) - proxy_handler.assert_called_once_with( - {'http': '%s' % str(http_proxy)}) + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual(proxy_config.GetHandlers(), + [https_handler_instance, proxy_handler_instance]) + proxy_handler.assert_called_once_with( + {'http': '%s' % str(http_proxy)}) def testProxyConfigGetHandlersWithProxyAndSLLContext(self): https_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, self.proxy_port1) with mock.patch('googleads.common.ProxyConfig._InitSSLContext') as ssl_ctxt: ssl_ctxt.return_value = 'CONTEXT' - with mock.patch('urllib2.ProxyHandler') as proxy_handler: + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: proxy_handler.return_value = mock.Mock() - with mock.patch('urllib2.HTTPSHandler') as https_handler: + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler.return_value = mock.Mock() proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) self.assertEqual(proxy_config.GetHandlers(), @@ -1115,17 +1135,23 @@ def testProxyConfigGetHandlersWithProxyAndSLLContext(self): def testProxyConfigWithNoProxy(self): proxy_config = googleads.common.ProxyConfig() self.assertEqual(proxy_config.proxy_info, None) - self.assertEqual(proxy_config.GetHandlers(), []) - # Note: The ssl_context will always be None on incompatible versions of - # Python. The version used internally doesn't support this feature. Another - # impact is that HTTPSHandler will never be invoked in these tests. - self.assertEqual(proxy_config._ssl_context, None) + + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual(proxy_config.GetHandlers(), + [https_handler_instance]) + self.assertIsInstance( + proxy_config._ssl_context, ssl.SSLContext) with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([]) - self.assertEqual(t.return_value, transport) + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with([https_handler_instance]) + self.assertEqual(t.return_value, transport) def testProxyConfigWithHTTPProxy(self): with mock.patch('httplib2.ProxyInfo') as proxy_info: @@ -1139,20 +1165,23 @@ def testProxyConfigWithHTTPProxy(self): self.assertEqual(proxy_config.proxy_info, proxy_info.return_value) self.assertEqual(proxy_config._proxy_option, {'http': '%s:%s' % ( self.proxy_host1, self.proxy_port1)}) - # Note: The ssl_context will always be None on incompatible versions of - # Python. The version used internally doesn't support this feature. Another - # impact is that HTTPSHandler will never be invoked in these tests. - self.assertEqual(proxy_config._ssl_context, None) + self.assertIsInstance( + proxy_config._ssl_context, ssl.SSLContext) with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - with mock.patch('urllib2.ProxyHandler') as proxy_handler: - proxy_handler.return_value = mock.Mock() - self.assertEqual(proxy_config.GetHandlers(), - [proxy_handler.return_value]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([proxy_handler.return_value]) - self.assertEqual(t.return_value, transport) + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: + proxy_handler_instance = mock.Mock() + proxy_handler.return_value = proxy_handler_instance + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual(proxy_config.GetHandlers(), + [https_handler_instance, proxy_handler_instance]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with( + [https_handler_instance, proxy_handler_instance]) + self.assertEqual(t.return_value, transport) def testProxyConfigWithHTTPSProxy(self): with mock.patch('httplib2.ProxyInfo') as proxy_info: @@ -1168,22 +1197,26 @@ def testProxyConfigWithHTTPSProxy(self): self.assertEqual(proxy_config._proxy_option, {'https': '%s:%s@%s:%s' % ( self.username, self.password, self.proxy_host2, self.proxy_port2)}) - # Note: The ssl_context will always be None on incompatible versions of - # Python. The version used internally doesn't support this feature. Another - # impact is that HTTPSHandler will never be invoked in these tests. - self.assertEqual(proxy_config._ssl_context, None) + self.assertIsInstance( + proxy_config._ssl_context, ssl.SSLContext) self.assertEqual(proxy_config.cafile, self.cafile) self.assertEqual(proxy_config.disable_certificate_validation, False) with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - with mock.patch('urllib2.ProxyHandler') as proxy_handler: - proxy_handler.return_value = mock.Mock() - self.assertEqual(proxy_config.GetHandlers(), - [proxy_handler.return_value]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([proxy_handler.return_value]) - self.assertEqual(t.return_value, transport) + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: + proxy_handler_instance = mock.Mock() + proxy_handler.return_value = proxy_handler_instance + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual( + proxy_config.GetHandlers(), + [https_handler_instance, proxy_handler_instance]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with( + [https_handler_instance, proxy_handler_instance]) + self.assertEqual(t.return_value, transport) def testProxyConfigWithHTTPAndHTTPSProxy(self): with mock.patch('httplib2.ProxyInfo') as proxy_info: @@ -1201,22 +1234,27 @@ def testProxyConfigWithHTTPAndHTTPSProxy(self): 'http': '%s:%s@%s:%s' % (self.username, self.password, self.proxy_host2, self.proxy_port2), 'https': '%s:%s' % (self.proxy_host1, self.proxy_port1)}) - # Note: The ssl_context will always be None on incompatible versions of - # Python. The version used internally doesn't support this feature. Another - # impact is that HTTPSHandler will never be invoked in these tests. - self.assertEqual(proxy_config._ssl_context, None) + + self.assertIsInstance(proxy_config._ssl_context, ssl.SSLContext) self.assertEqual(proxy_config.cafile, None) self.assertEqual(proxy_config.disable_certificate_validation, True) with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: t.return_value = mock.Mock() - with mock.patch('urllib2.ProxyHandler') as proxy_handler: - proxy_handler.return_value = mock.Mock() - self.assertEqual(proxy_config.GetHandlers(), - [proxy_handler.return_value]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([proxy_handler.return_value]) - self.assertEqual(t.return_value, transport) + with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: + proxy_handler_instance = mock.Mock() + proxy_handler.return_value = proxy_handler_instance + + with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: + https_handler_instance = mock.Mock() + https_handler.return_value = https_handler_instance + self.assertEqual( + proxy_config.GetHandlers(), + [https_handler_instance, proxy_handler_instance]) + transport = proxy_config.GetSudsProxyTransport() + t.assert_called_once_with( + [https_handler_instance, proxy_handler_instance]) + self.assertEqual(t.return_value, transport) class TestSudsRequestPatcher(unittest.TestCase): @@ -1226,16 +1264,24 @@ class MockHeaders(object): def __init__(self, d): self.dict = d + # If testing on Python 3, add get method to better mimic the + # http.client.HTTPMessage behavior. + if six.PY3: + def py3_get(s): + return self.dict.get(s) + self.get = py3_get + def testInflateSuccessfulRequestIfGzipped(self): with mock.patch('suds.transport.http.HttpTransport.getcookies'): - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: with mock.patch('gzip.GzipFile.read') as mock_read: - resp_fp = io.BytesIO() - resp_fp.write('abc') + resp_fp = six.BytesIO() + resp_fp.write(b'abc') resp_fp.flush() resp_fp.seek(0) - resp = addinfourl(resp_fp, self.MockHeaders( - {'content-encoding': 'gzip'}), 'https://example.com', code=200) + resp = six.moves.urllib.response.addinfourl( + resp_fp, self.MockHeaders({'content-encoding': 'gzip'}), + 'https://example.com', code=200) mock_open.return_value = resp req = suds.transport.Request('https://example.com', @@ -1246,26 +1292,22 @@ def testInflateSuccessfulRequestIfGzipped(self): def testInflateFailedRequestIfGzipped(self): with mock.patch('suds.transport.http.HttpTransport.getcookies'): - with mock.patch('urllib2.OpenerDirector.open') as mock_open: + with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: with mock.patch('gzip.GzipFile') as mock_gzip: gzip_instance_mock = mock.MagicMock mock_gzip.return_value = gzip_instance_mock - resp_fp = io.BytesIO() - resp_fp.write('abc') + resp_fp = six.BytesIO() + resp_fp.write(b'abc') resp_fp.flush() resp_fp.seek(0) - resp = addinfourl(resp_fp, - self.MockHeaders({'content-encoding': 'gzip'}), - 'https://example.com', code=200) + resp = six.moves.urllib.response.addinfourl( + resp_fp, self.MockHeaders({'content-encoding': 'gzip'}), + 'https://example.com', code=200) def fail_to_open(*args, **kwargs): - raise urllib2.HTTPError( - 'https://example.com', - 500, - 'oops!', - {'content-encoding': 'gzip'}, - resp - ) + raise six.moves.urllib.error.HTTPError( + 'https://example.com', 500, 'oops!', + {'content-encoding': 'gzip'}, resp) mock_open.side_effect = fail_to_open req = suds.transport.Request('https://example.com', diff --git a/tests/dfp_test.py b/tests/dfp_test.py index d62e1d35..9c138a6b 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -16,18 +16,17 @@ import datetime -import StringIO import sys import unittest - import mock import pytz +import six import suds.transport - import googleads.dfp import googleads.common import googleads.errors +from . import testing class BaseValue(object): @@ -106,7 +105,7 @@ def DecideValue(original_object): return BooleanValue(original_object) -class DfpHeaderHandlerTest(unittest.TestCase): +class DfpHeaderHandlerTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.dfp._DfpHeaderHandler class.""" def setUp(self): @@ -336,7 +335,7 @@ def testGetService_success(self): mock_service_proxy.assert_called_once_with( mock_client.return_value, dfp_client._header_handler, - googleads.dfp._DFPDateTimePacker) + packer=googleads.dfp._DfpPacker) def testGetService_successWithNoCache(self): service = googleads.dfp._SERVICE_MAP[self.version][0] @@ -410,25 +409,33 @@ def testGetService_transportError(self): dfp_client.GetService, service, self.version) -class DateTimePackerTest(unittest.TestCase): +class DfpPackerTest(unittest.TestCase): + """Tests for the googleads.dfp._DfpPacker class.""" - def testUnwrapDate(self): + def setUp(self): + self.packer = googleads.dfp._DfpPacker + + def testPackDate(self): input_date = datetime.date(2017, 1, 2) - result = googleads.dfp._DFPDateTimePacker(input_date) + result = self.packer.Pack(input_date) self.assertEqual(result, {'year': 2017, 'month': 1, 'day': 2}) - def testUnwrapDateTime(self): + def testPackDateTime(self): input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) input_date = pytz.timezone('America/New_York').localize(input_date) - result = googleads.dfp._DFPDateTimePacker(input_date) + result = self.packer.Pack(input_date) self.assertEqual(result, {'date': {'year': 2017, 'month': 1, 'day': 2}, 'hour': 3, 'minute': 4, 'second': 5, 'timeZoneID': 'America/New_York'}) - def testUnwrapDateTimeNeedsTimeZone(self): + def testPackDateTimeNeedsTimeZone(self): input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) self.assertRaises(googleads.errors.GoogleAdsValueError, - googleads.dfp._DFPDateTimePacker, input_date) + self.packer.Pack, input_date) + + def testPackUnsupportedObjectType(self): + obj = object() + self.assertEqual(googleads.dfp._DfpPacker.Pack(obj), obj) class DataDownloaderTest(unittest.TestCase): @@ -562,7 +569,7 @@ def setUp(self): }] def testDownloadPqlResultSetToCsv(self): - csv_file = StringIO.StringIO() + csv_file = six.StringIO() self.pql_service.select.return_value = {'rows': self.generic_rval, 'columnTypes': self.generic_header} @@ -613,6 +620,50 @@ def testDownloadPqlResultToList(self): self.generic_header[1]['labelName']], row1, row2], result_set) + def testDownloadPqlResultToListWithOldValuesList(self): + self.pql_service.select.return_value = {'rows': self.generic_rval, + 'columnTypes': self.generic_header} + + result_set = self.report_downloader.DownloadPqlResultToList( + 'SELECT Id, Name FROM Line_Item WHERE Id = :id', + [{'key': 'id', 'value': {'xsi_type': 'NumberValue', 'value': 1}}]) + + row1 = [self.report_downloader._ConvertValueForCsv(field) + for field in self.generic_rval[0]['values']] + row2 = [self.report_downloader._ConvertValueForCsv(field) + for field in self.generic_rval[1]['values']] + + self.pql_service.select.assert_called_once_with( + {'values': [{'key': 'id', + 'value': {'xsi_type': 'NumberValue', 'value': 1}}], + 'query': ('SELECT Id, Name FROM Line_Item ' + 'WHERE Id = :id LIMIT 500 OFFSET 0')}) + self.assertEqual([[self.generic_header[0]['labelName'], + self.generic_header[1]['labelName']], + row1, row2], result_set) + + def testDownloadPqlResultToListWithDict(self): + self.pql_service.select.return_value = {'rows': self.generic_rval, + 'columnTypes': self.generic_header} + + result_set = self.report_downloader.DownloadPqlResultToList( + 'SELECT Id, Name FROM Line_Item WHERE Id = :id', + {'id': 1}) + + row1 = [self.report_downloader._ConvertValueForCsv(field) + for field in self.generic_rval[0]['values']] + row2 = [self.report_downloader._ConvertValueForCsv(field) + for field in self.generic_rval[1]['values']] + + self.pql_service.select.assert_called_once_with( + {'values': [{'key': 'id', + 'value': {'xsi_type': 'NumberValue', 'value': 1}}], + 'query': ('SELECT Id, Name FROM Line_Item ' + 'WHERE Id = :id LIMIT 500 OFFSET 0')}) + self.assertEqual([[self.generic_header[0]['labelName'], + self.generic_header[1]['labelName']], + row1, row2], result_set) + def testDownloadPqlResultToList_NoRows(self): self.pql_service.select.return_value = {} @@ -650,14 +701,14 @@ def testDownloadReportToFile(self): report_job_id = 't68t3278y429' report_download_url = 'http://google.com/something' report_data = 'THIS IS YOUR REPORT!' - report_contents = StringIO.StringIO() + report_contents = six.StringIO() report_contents.write(report_data) report_contents.seek(0) fake_response = mock.Mock() fake_response.read = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - outfile = StringIO.StringIO() + outfile = six.StringIO() download_func = self.report_service.getReportDownloadUrlWithOptions download_func.return_value = report_download_url @@ -695,7 +746,7 @@ def testGetPqlService(self): 'PublisherQueryLanguageService', self.version, 'https://ads.google.com') -class StatementBuilderTest(unittest.TestCase): +class StatementBuilderTest(testing.CleanUtilityRegistryTestCase): """Tests for the StatementBuilder class.""" def testBuildBasicSelectFrom(self): @@ -953,7 +1004,7 @@ def testBreakWithBadSelectFrom(self): test_statement.ToStatement) -class FilterStatementTest(unittest.TestCase): +class FilterStatementTest(testing.CleanUtilityRegistryTestCase): """Tests for the FilterStatement class.""" def testFilterStatement(self): diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index b21a0a5d..939e96d2 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -18,19 +18,25 @@ import datetime import unittest - import httplib2 import mock - +import six import googleads.common import googleads.errors import googleads.oauth2 - -import fake_filesystem -import fake_tempfile +from pyfakefs import fake_filesystem +from pyfakefs import fake_tempfile from oauth2client.client import AccessTokenRefreshError from oauth2client.client import OAuth2Credentials -from oauth2client.client import SignedJwtAssertionCredentials + + +if googleads.oauth2.DEPRECATED_OAUTH2CLIENT: + _SA_CRED_PATH = ('oauth2client.client' + '.SignedJwtAssertionCredentials') +else: + _SA_CRED_PATH = 'oauth2client.service_account.ServiceAccountCredentials' + +_BUILTIN_PATH = '__builtin__' if six.PY2 else 'builtins' class GetAPIScopeTest(unittest.TestCase): @@ -180,7 +186,7 @@ class GoogleServiceAccountTest(unittest.TestCase): def setUp(self): self.scope = 'scope' self.service_account_email = 'email@email.com' - self.private_key = 'IT\'S A SECRET TO EVERYBODY.' + self.private_key = b'IT\'S A SECRET TO EVERYBODY.' self.private_key_password = 'notasecret' self.delegated_account = 'delegated_account@delegated.com' https_proxy_host = 'myproxy.com' @@ -198,7 +204,7 @@ def setUp(self): self.fake_open = fake_filesystem.FakeFileOpen(filesystem) self.key_file_path = tempfile.NamedTemporaryFile(delete=False).name - with self.fake_open(self.key_file_path, 'w') as file_handle: + with self.fake_open(self.key_file_path, 'wb') as file_handle: file_handle.write(self.private_key) # Mock out httplib2.Http for testing. @@ -209,15 +215,18 @@ def setUp(self): self.opener.disable_ssl_certificate_valiation = ( self.proxy_config.disable_certificate_validation) - # Mock out oauth2client.client.SignedJwtAssertionCredentials for - # testing. - self.oauth2_credentials = mock.Mock( - spec=SignedJwtAssertionCredentials) + # Mock out service account credentials for testing. + self.oauth2_credentials = mock.Mock() self.oauth2_credentials.return_value = mock.Mock() - self.mock_oauth2_credentials = (self.oauth2_credentials.return_value) + self.mock_oauth2_credentials = self.oauth2_credentials.return_value self.mock_oauth2_credentials.access_token = 'x' self.mock_oauth2_credentials.token_expiry = datetime.datetime( 1980, 1, 1, 12) + # Also mock out instantiation methods for newer oauth2client versions. + self.oauth2_credentials.from_p12_keyfile.return_value = ( + self.mock_oauth2_credentials) + self.oauth2_credentials.from_json_keyfile_name.return_value = ( + self.mock_oauth2_credentials) def apply(headers): headers['Authorization'] = ('Bearer %s' @@ -232,10 +241,8 @@ def refresh(mock_http): self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply) self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh) - with mock.patch('__builtin__.open', self.fake_open): - with mock.patch('oauth2client.client' - '.SignedJwtAssertionCredentials', - self.oauth2_credentials): + with mock.patch('%s.open' % _BUILTIN_PATH, self.fake_open): + with mock.patch(_SA_CRED_PATH, self.oauth2_credentials): self.googleads_client = googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, self.key_file_path, self.private_key_password, proxy_config=self.proxy_config) @@ -307,21 +314,35 @@ def testCreateGoogleServiceAccountClient_DelegatedP12OAuth2Client4(self): mock_create_delegated.assert_called_once_with(self.delegated_account) def testCreateGoogleServiceAccountClient_DelegatedP12OAuth2ClientDepr(self): - # Mock out the oauth2client 1.4.12 oauth2client.service_account module to + # Mock out the oauth2client 1.4.12 oauth2client.client module to # verify that the correct parts are called. - with mock.patch('googleads.oauth2.oauth2client.client' - '.SignedJwtAssertionCredentials') as mock_credentials: - with mock.patch('%s.open' % googleads.oauth2.__name__, self.fake_open, - create=True): - googleads.oauth2.GoogleServiceAccountClient( - self.scope, client_email=self.service_account_email, - key_file=self.key_file_path, sub=self.delegated_account) - mock_credentials.assert_called_once_with( - self.service_account_email, self.private_key, self.scope, - private_key_password=self.private_key_password, - user_agent='Google Ads Python Client Library', - token_uri='https://accounts.google.com/o/oauth2/token', - sub=self.delegated_account) + mock_oauth2client_depr = mock.Mock() + mock_client_module = mock.Mock() + mock_signed_jwt_credentials = mock.Mock() + mock_signed_jwt_credentials_instance = mock.Mock() + mock_signed_jwt_credentials.return_value = ( + mock_signed_jwt_credentials_instance) + mock_client_module.SignedJwtAssertionCredentials = ( + mock_signed_jwt_credentials) + mock_oauth2client_depr.client = mock_client_module + mock_oauth2client_depr.__version__ = '1.4.12' + + # Mock out the oauth2client 1.4.12 oauth2client.client module to + # verify that the correct parts are called. + with mock.patch('googleads.oauth2.oauth2client', + mock_oauth2client_depr): + with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', True): + with mock.patch('%s.open' % googleads.oauth2.__name__, self.fake_open, + create=True): + googleads.oauth2.GoogleServiceAccountClient( + self.scope, client_email=self.service_account_email, + key_file=self.key_file_path, sub=self.delegated_account) + mock_signed_jwt_credentials.assert_called_once_with( + self.service_account_email, self.private_key, self.scope, + private_key_password=self.private_key_password, + user_agent='Google Ads Python Client Library', + token_uri='https://accounts.google.com/o/oauth2/token', + sub=self.delegated_account) def testCreateGoogleServiceAccountClient_JsonOAuth2Client4(self): # Mock out the oauth2client 4.0.0 oauth2client.service_account module to @@ -417,10 +438,8 @@ def testIssue123(self): See: https://github.com/googleads/googleads-python-lib/issues/123 """ - with mock.patch('__builtin__.open'): - with mock.patch('oauth2client.client' - '.SignedJwtAssertionCredentials', - self.oauth2_credentials): + with mock.patch('%s.open' % _BUILTIN_PATH): + with mock.patch(_SA_CRED_PATH, self.oauth2_credentials): googleads.oauth2.GoogleServiceAccountClient( self.scope, self.service_account_email, '/dev/null', self.private_key_password) diff --git a/tests/test_data/adwords_googleads.yaml b/tests/test_data/adwords_googleads.yaml new file mode 100644 index 00000000..31fc1b92 --- /dev/null +++ b/tests/test_data/adwords_googleads.yaml @@ -0,0 +1,5 @@ +adwords: + developer_token: developer_token + client_id: client_id + client_secret: client_secret + refresh_token: refresh_token diff --git a/tests/test_data/batch_job_util_budget_template.txt b/tests/test_data/batch_job_util_budget_template.txt new file mode 100644 index 00000000..e0e48f3a --- /dev/null +++ b/tests/test_data/batch_job_util_budget_template.txt @@ -0,0 +1,6 @@ + %s + %s + + %s + + %s \ No newline at end of file diff --git a/tests/test_data/batch_job_util_campaign_criterion_template.txt b/tests/test_data/batch_job_util_campaign_criterion_template.txt new file mode 100644 index 00000000..62d743ab --- /dev/null +++ b/tests/test_data/batch_job_util_campaign_criterion_template.txt @@ -0,0 +1,7 @@ + %s + %s + + %s + %s + %s + diff --git a/tests/test_data/batch_job_util_campaign_label_template.txt b/tests/test_data/batch_job_util_campaign_label_template.txt new file mode 100644 index 00000000..88eff6ba --- /dev/null +++ b/tests/test_data/batch_job_util_campaign_label_template.txt @@ -0,0 +1,2 @@ + %s + %s \ No newline at end of file diff --git a/tests/test_data/batch_job_util_invalid_request.txt b/tests/test_data/batch_job_util_invalid_request.txt new file mode 100644 index 00000000..9bc8b869 --- /dev/null +++ b/tests/test_data/batch_job_util_invalid_request.txt @@ -0,0 +1,9 @@ + + + + Die monster. You don't belong in this world! + + + What is a man? A miserable little pile of secrets. But enough talk... Have at you! + + \ No newline at end of file diff --git a/tests/test_data/batch_job_util_not_request.txt b/tests/test_data/batch_job_util_not_request.txt new file mode 100644 index 00000000..b45ef6fe --- /dev/null +++ b/tests/test_data/batch_job_util_not_request.txt @@ -0,0 +1 @@ +Hello, World! \ No newline at end of file diff --git a/tests/test_data/batch_job_util_operations_template.txt b/tests/test_data/batch_job_util_operations_template.txt new file mode 100644 index 00000000..f31c7b83 --- /dev/null +++ b/tests/test_data/batch_job_util_operations_template.txt @@ -0,0 +1,7 @@ + + %s + %s + +%s + + \ No newline at end of file diff --git a/tests/test_data/batch_job_util_raw_request_template.txt b/tests/test_data/batch_job_util_raw_request_template.txt new file mode 100644 index 00000000..fd7e0e6f --- /dev/null +++ b/tests/test_data/batch_job_util_raw_request_template.txt @@ -0,0 +1,17 @@ + + + + + 000-000-0000 + xxxxxxxxxxxxxxxxxxxx + notarealemail@fake.com (AwApi-Python, googleads/3.8.0, Python/2.7.6) + false + false + + + + +%s + + + \ No newline at end of file diff --git a/tests/test_data/batch_job_util_response_template.txt b/tests/test_data/batch_job_util_response_template.txt new file mode 100644 index 00000000..4ccd1d1e --- /dev/null +++ b/tests/test_data/batch_job_util_response_template.txt @@ -0,0 +1 @@ +410230034Batch budget #c776b6f1-5db6-47fc-96ef-1208edb6d898Money50000000STANDARDtrueENABLED0%s%s%s%s%s%s%s%sMoney%s%s%sENABLED%sManualCpcBiddingSchemefalse1 \ No newline at end of file diff --git a/tests/test_data/batch_job_util_upload_template.txt b/tests/test_data/batch_job_util_upload_template.txt new file mode 100644 index 00000000..61301f64 --- /dev/null +++ b/tests/test_data/batch_job_util_upload_template.txt @@ -0,0 +1,5 @@ + + +%s + \ No newline at end of file diff --git a/tests/test_data/compact_fault_response_envelope.txt b/tests/test_data/compact_fault_response_envelope.txt new file mode 100644 index 00000000..5f1d1e11 --- /dev/null +++ b/tests/test_data/compact_fault_response_envelope.txt @@ -0,0 +1,8 @@ + + + + soap:Client + Unmarshalling Error: For input string: "INSERT_ADVERTISER_COMPANY_ID_HERE" + + + \ No newline at end of file diff --git a/tests/test_data/empty_fault_response_envelope.txt b/tests/test_data/empty_fault_response_envelope.txt new file mode 100644 index 00000000..8b8ac82b --- /dev/null +++ b/tests/test_data/empty_fault_response_envelope.txt @@ -0,0 +1,19 @@ + + + + 644a8c6efd398cf8643c29ff68fe574e + 22 + + + + + soap:Server + [AuthenticationError.NETWORK_CODE_REQUIRED @ ] + + + An error message without errors sibling tags + + + + + \ No newline at end of file diff --git a/tests/test_data/fault_response_envelope.txt b/tests/test_data/fault_response_envelope.txt new file mode 100644 index 00000000..ecf77c26 --- /dev/null +++ b/tests/test_data/fault_response_envelope.txt @@ -0,0 +1,25 @@ + + + + 644a8c6efd398cf8643c29ff68fe574e + 22 + + + + + soap:Server + [AuthenticationError.NETWORK_CODE_REQUIRED @ ] + + + [AuthenticationError.NETWORK_CODE_REQUIRED @ ] + + + + AuthenticationError.NETWORK_CODE_REQUIRED + NETWORK_CODE_REQUIRED + + + + + + \ No newline at end of file diff --git a/tests/test_data/gzip_response.bin b/tests/test_data/gzip_response.bin new file mode 100644 index 0000000000000000000000000000000000000000..567068aba2b84b4ede2c238fd3107c86445a51f4 GIT binary patch literal 394 zcmV;50d@W#iwFP!000000Hu=MZrd;ngRKV*p@5F z+4A<4WKUxbcTlYray3N2EO^%wY^(U-p|{;_rn^%sXce(qHr|%k+C&Q z1@Qk%a4YeY@`p*YmH5nVFumhh&zW-o5GN%C|SASW408W|%joShM08a_PO#lD@ literal 0 HcmV?d00001 diff --git a/tests/test_data/multi_errors_fault_response_envelope.txt b/tests/test_data/multi_errors_fault_response_envelope.txt new file mode 100644 index 00000000..2ca18d4a --- /dev/null +++ b/tests/test_data/multi_errors_fault_response_envelope.txt @@ -0,0 +1,31 @@ + + + + 644a8c6efd398cf8643c29ff68fe574e + 22 + + + + + soap:Server + [Error 1, Error 2] + + + Multiple errors occurred + + + + ERROR_1 + NETWORK_CODE_REQUIRED + + + + + ERROR_2 + NETWORK_CODE_REQUIRED + + + + + + \ No newline at end of file diff --git a/tests/test_data/request_envelope_template.txt b/tests/test_data/request_envelope_template.txt new file mode 100644 index 00000000..37e84386 --- /dev/null +++ b/tests/test_data/request_envelope_template.txt @@ -0,0 +1,27 @@ + + + + + xxx-yyy-zzzz + %s + testing! + false + false + + + + + + ADD + + Test Budget #123456 + + 50000000 + + STANDARD + true + + + + + \ No newline at end of file diff --git a/tests/test_data/test.crt b/tests/test_data/test.crt new file mode 100644 index 00000000..f87867fc --- /dev/null +++ b/tests/test_data/test.crt @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC/DCCAmWgAwIBAgIJAI3wDXTv4zWcMA0GCSqGSIb3DQEBBQUAMIGWMQswCQYD +VQQGEwJVUzELMAkGA1UECAwCTlkxETAPBgNVBAcMCE5ldyBZb3JrMQ8wDQYDVQQK +DAZHb29nbGUxIDAeBgNVBAsMF0FkcyBEZXZlbG9wZXIgUmVsYXRpb25zMQwwCgYD +VQQDDANNVFMxJjAkBgkqhkiG9w0BCQEWF21zYW5pc2NhbGNoaUBnb29nbGUuY29t +MB4XDTE3MDkxODEzNDgxMVoXDTE4MDkxODEzNDgxMVowgZYxCzAJBgNVBAYTAlVT +MQswCQYDVQQIDAJOWTERMA8GA1UEBwwITmV3IFlvcmsxDzANBgNVBAoMBkdvb2ds +ZTEgMB4GA1UECwwXQWRzIERldmVsb3BlciBSZWxhdGlvbnMxDDAKBgNVBAMMA01U +UzEmMCQGCSqGSIb3DQEJARYXbXNhbmlzY2FsY2hpQGdvb2dsZS5jb20wgZ8wDQYJ +KoZIhvcNAQEBBQADgY0AMIGJAoGBANFRqR3lsWEl7EaIIIWj9m6/1wiTu0SHsgfd +RIu+RieqkxRS2Gvnv8PIePb3P2QhtCPj6LjGQc+RB4XccyILKhK6T8cCUhEFB7F3 +JCrwJlJjShmPijSPPFyrZpj8xT/QGMQzrpxi/Qy/+1x7LG6tPHis5Fnhyzqu7i93 +6AlBzBAfAgMBAAGjUDBOMB0GA1UdDgQWBBQln01dzl4gpE6EEcbbavKiYK/6sTAf +BgNVHSMEGDAWgBQln01dzl4gpE6EEcbbavKiYK/6sTAMBgNVHRMEBTADAQH/MA0G +CSqGSIb3DQEBBQUAA4GBAAFr5vsQXMSbiFzfdPmbkQF2J+jtvXQId3zBJF4h4ZVq +VMN9Rw4+zZVq8KUf77y6z0wzdFDU4BRLPI9hEKdik2qf7kyFoNnG3JqYprW9BbCi +efh5JhiR7PpLsvqvr5x8Yv1tOe1CHKASCRlKEu79YuxQpx3mYG7N6qbFhJPsfpHY +-----END CERTIFICATE----- diff --git a/tests/testing.py b/tests/testing.py new file mode 100644 index 00000000..07d3f34c --- /dev/null +++ b/tests/testing.py @@ -0,0 +1,32 @@ +# Copyright 2017 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. + +"""Functions and classes used for unit tests.""" + + +import unittest + +import googleads.common + + +class CleanUtilityRegistryTestCase(unittest.TestCase): + """Base class for testing content affecting the UtilityRegistry. + + Subclasses will clear the UtilityRegistry between each test to ensure that it + is in a clean state before the next test. + """ + + def tearDown(self): + """Ensures that the UtilityRegistry is cleared between tests.""" + googleads.common._utility_registry.Clear() diff --git a/tests/util_test.py b/tests/util_test.py index 5081d98a..c11e8d1b 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -18,18 +18,20 @@ import os import re import unittest -import urllib2 from xml.etree import ElementTree - import googleads.adwords import googleads.dfp import googleads.util import mock +import six import suds import suds.transport +_HTTP_CLIENT_PATH = 'httplib' if six.PY2 else 'http.client' + + class PatchesTest(unittest.TestCase): """Tests for the PatchHelper utility.""" @@ -84,6 +86,8 @@ def testPatchedSudsJurkoAppender(self): request = line_item_service.performLineItemAction( line_item_action, statement.ToStatement()).envelope line_item_service.suds_client.set_options(nosend=False) + if six.PY3: + request = request.decode('utf-8') # Strip namespace prefixes and parse. parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) line_item_action = parsed_request.find('Body').find('performLineItemAction') @@ -117,6 +121,8 @@ def testPatchedSudsJurkoAppenderIssue63(self): adgroup_criterion_service.suds_client.set_options(nosend=True) request = adgroup_criterion_service.mutate(operations).envelope adgroup_criterion_service.suds_client.set_options(nosend=False) + if six.PY3: + request = request.decode('utf-8') # Strip namespace prefixes and parse. parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) operand = parsed_request.find('Body').find('mutate').find( @@ -136,6 +142,8 @@ def testPatchedSudsJurkoAppenderIssue78(self): customer_service.suds_client.set_options(nosend=True) request = customer_service.mutate(customer).envelope customer_service.suds_client.set_options(nosend=False) + if six.PY3: + request = request.decode('utf-8') # Strip namespace prefixes and parse. parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) tracking_url_template = parsed_request.find('Body').find('mutate').find( @@ -168,22 +176,24 @@ def testSudsJurkoSendWithException(self): cs = self.adwords_client_with_compression.GetService('CampaignService') with mock.patch('suds.transport.http.HttpTransport.u2open') as mock_u2open: - with open(os.path.join( - test_dir, 'test_data/compact_fault_response_envelope.txt'), 'rb' - ) as handler: - url = 'https://ads.google.com' - code = 500 - msg = '' - hdrs = [] - mock_u2open.side_effect = urllib2.HTTPError(url, code, msg, hdrs, - handler) - try: - cs.get() - except suds.WebFault, e: - self.assertEqual( - 'Unmarshalling Error: For input string: ' - '"INSERT_ADVERTISER_COMPANY_ID_HERE" ', - e.fault.faultstring) + with mock.patch('%s.HTTPMessage' % _HTTP_CLIENT_PATH) as mock_headers: + mock_headers.get.return_value = None + with open(os.path.join( + test_dir, 'test_data/compact_fault_response_envelope.txt'), 'rb' + ) as handler: + url = 'https://ads.google.com' + code = 500 + msg = '' + hdrs = mock_headers + mock_u2open.side_effect = six.moves.urllib.error.HTTPError( + url, code, msg, hdrs, handler) + try: + cs.get() + except suds.WebFault as e: + self.assertEqual( + 'Unmarshalling Error: For input string: ' + '"INSERT_ADVERTISER_COMPANY_ID_HERE" ', + e.fault.faultstring) def testSingleErrorListIssue90(self): """Verifies that issue 90 has been resolved with the patch.""" @@ -207,7 +217,7 @@ def testSingleErrorListIssue90(self): mock_send.return_value = reply_instance try: line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault, e: + except suds.WebFault as e: errors = e.fault.detail.ApiExceptionFault.errors self.assertIsInstance(errors, list) self.assertEqual(1, len(errors)) @@ -234,7 +244,7 @@ def testSingleErrorListIssue90_emptyErrors(self): mock_send.return_value = reply_instance try: line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault, e: + except suds.WebFault as e: errors = e.fault.detail.ApiExceptionFault.errors self.assertIsInstance(errors, list) self.assertEqual(0, len(errors)) @@ -261,7 +271,7 @@ def testSingleErrorListIssue90_multipleErrors(self): mock_send.return_value = reply_instance try: line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault, e: + except suds.WebFault as e: errors = e.fault.detail.ApiExceptionFault.errors self.assertIsInstance(errors, list) self.assertEqual(2, len(errors)) @@ -281,7 +291,11 @@ def testGetGoogleAdsCommonFilter(self): def testFilterAtInfoLevel(self): record = mock.Mock() record.levelno = logging.INFO - record.args = [self.dev_token_template % 'test'] + + doc = mock.Mock() + doc.str.return_value = self.dev_token_template % 'test' + + record.args = [doc] self.filter.filter(record) self.assertEqual( record.args, (self.dev_token_template % self.redacted_text,)) From 1fc418905cf215c39cd367bfe013b78e91c3f257 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 28 Mar 2018 16:27:08 -0400 Subject: [PATCH 104/180] AdWords v201705/v201708 sunset, Zeep/google-auth migration --- ChangeLog | 41 + README.md | 58 +- .../appengine_config.py | 4 +- ...ate_adwords_client_with_service_account.py | 12 +- .../authentication/generate_refresh_token.py | 75 +- examples/adwords/v201705/__init__.py | 15 - .../v201705/account_management/__init__.py | 15 - .../account_management/accept_service_link.py | 62 - .../account_management/create_account.py | 63 - .../account_management/get_account_changes.py | 99 - .../get_account_hierarchy.py | 104 - .../v201705/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 222 - .../add_ad_group_bid_modifier.py | 75 - .../add_click_to_download_ad.py | 128 - .../add_dynamic_page_feed.py | 295 - .../add_dynamic_search_ads_campaign.py | 257 - ...add_expanded_text_ad_with_upgraded_urls.py | 109 - .../advanced_operations/add_html5_ad.py | 112 - .../add_responsive_display_ad.py | 93 - .../add_universal_app_campaign.py | 217 - .../create_and_attach_shared_keyword_set.py | 128 - ...ind_and_remove_criteria_from_shared_set.py | 155 - .../get_ad_group_bid_modifier.py | 73 - .../use_shared_bidding_strategy.py | 171 - .../v201705/basic_operations/__init__.py | 15 - .../v201705/basic_operations/add_ad_groups.py | 115 - .../v201705/basic_operations/add_campaigns.py | 128 - .../basic_operations/add_expanded_text_ads.py | 74 - .../v201705/basic_operations/add_keywords.py | 92 - .../v201705/basic_operations/get_ad_groups.py | 76 - .../v201705/basic_operations/get_campaigns.py | 72 - .../get_campaigns_with_awql.py | 62 - .../basic_operations/get_expanded_text_ads.py | 90 - .../v201705/basic_operations/get_keywords.py | 87 - .../v201705/basic_operations/pause_ad.py | 61 - .../v201705/basic_operations/remove_ad.py | 62 - .../basic_operations/remove_ad_group.py | 58 - .../basic_operations/remove_campaign.py | 58 - .../basic_operations/remove_keyword.py | 67 - .../basic_operations/update_ad_group.py | 58 - .../basic_operations/update_campaign.py | 58 - .../basic_operations/update_keyword.py | 82 - .../v201705/campaign_management/__init__.py | 15 - ...campaign_groups_and_performance_targets.py | 152 - .../add_campaign_labels.py | 67 - .../add_complete_campaigns_using_batch_job.py | 428 - .../v201705/campaign_management/add_draft.py | 81 - ...dd_keywords_using_incremental_batch_job.py | 258 - .../v201705/campaign_management/add_trial.py | 116 - .../get_all_disapproved_ads.py | 92 - .../get_all_disapproved_ads_with_awql.py | 76 - .../get_campaigns_by_label.py | 83 - .../campaign_management/graduate_trial.py | 79 - .../campaign_management/set_ad_parameters.py | 100 - .../set_criterion_bid_modifier.py | 77 - .../campaign_management/validate_text_ad.py | 84 - .../v201705/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 131 - .../handle_policy_violation_error.py | 167 - .../adwords/v201705/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 - .../adwords/v201705/extensions/add_prices.py | 157 - .../v201705/extensions/add_site_links.py | 146 - .../extensions/add_site_links_using_feeds.py | 236 - .../adwords/v201705/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 - examples/adwords/v201705/misc/__init__.py | 15 - .../v201705/misc/get_all_images_and_videos.py | 85 - examples/adwords/v201705/misc/upload_image.py | 66 - .../v201705/misc/upload_media_bundle.py | 60 - .../adwords/v201705/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 180 - ...aign_criterion_bid_modifier_simulations.py | 96 - .../get_keyword_bid_simulations.py | 81 - .../v201705/optimization/get_keyword_ideas.py | 100 - .../adwords/v201705/remarketing/__init__.py | 15 - .../v201705/remarketing/add_audience.py | 103 - .../remarketing/add_conversion_tracker.py | 70 - .../remarketing/add_crm_based_user_list.py | 101 - .../remarketing/add_rule_based_user_lists.py | 192 - .../upload_offline_call_conversions.py | 77 - .../remarketing/upload_offline_conversions.py | 75 - .../adwords/v201705/reporting/__init__.py | 15 - ...oad_criteria_report_as_stream_with_awql.py | 81 - ...criteria_report_as_stream_with_selector.py | 77 - ...oad_criteria_report_as_string_with_awql.py | 55 - ...criteria_report_as_string_with_selector.py | 59 - .../download_criteria_report_with_awql.py | 55 - .../download_criteria_report_with_selector.py | 60 - .../v201705/reporting/get_report_fields.py | 52 - .../reporting/parallel_report_download.py | 230 - examples/adwords/v201705/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 279 - .../v201705/shopping/add_product_scope.py | 104 - .../v201705/shopping/add_shopping_campaign.py | 172 - .../add_shopping_campaign_for_showcase_ads.py | 402 - .../shopping/get_product_category_taxonomy.py | 96 - .../adwords/v201705/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 126 - .../add_demographic_targeting_criteria.py | 96 - .../get_campaign_targeting_criteria.py | 85 - .../get_targetable_languages_and_carriers.py | 57 - .../v201705/targeting/lookup_location.py | 82 - examples/adwords/v201708/__init__.py | 15 - .../v201708/account_management/__init__.py | 15 - .../account_management/accept_service_link.py | 62 - .../account_management/create_account.py | 63 - .../account_management/get_account_changes.py | 99 - .../get_account_hierarchy.py | 104 - .../v201708/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 226 - .../add_ad_group_bid_modifier.py | 75 - .../add_click_to_download_ad.py | 128 - .../add_dynamic_page_feed.py | 295 - .../add_dynamic_search_ads_campaign.py | 257 - ...add_expanded_text_ad_with_upgraded_urls.py | 109 - .../advanced_operations/add_html5_ad.py | 112 - .../add_responsive_display_ad.py | 159 - .../add_universal_app_campaign.py | 217 - .../create_and_attach_shared_keyword_set.py | 128 - ...ind_and_remove_criteria_from_shared_set.py | 155 - .../get_ad_group_bid_modifier.py | 73 - .../use_shared_bidding_strategy.py | 171 - .../v201708/basic_operations/__init__.py | 15 - .../v201708/basic_operations/add_ad_groups.py | 115 - .../v201708/basic_operations/add_campaigns.py | 128 - .../basic_operations/add_expanded_text_ads.py | 74 - .../v201708/basic_operations/add_keywords.py | 92 - .../v201708/basic_operations/get_ad_groups.py | 76 - .../v201708/basic_operations/get_campaigns.py | 72 - .../get_campaigns_with_awql.py | 62 - .../basic_operations/get_expanded_text_ads.py | 90 - .../v201708/basic_operations/get_keywords.py | 87 - .../v201708/basic_operations/pause_ad.py | 61 - .../v201708/basic_operations/remove_ad.py | 62 - .../basic_operations/remove_ad_group.py | 58 - .../basic_operations/remove_campaign.py | 58 - .../basic_operations/remove_keyword.py | 67 - .../basic_operations/update_ad_group.py | 58 - .../basic_operations/update_campaign.py | 58 - .../basic_operations/update_keyword.py | 82 - .../v201708/campaign_management/__init__.py | 15 - ...campaign_groups_and_performance_targets.py | 152 - .../add_campaign_labels.py | 67 - .../add_complete_campaigns_using_batch_job.py | 428 - .../v201708/campaign_management/add_draft.py | 81 - ...dd_keywords_using_incremental_batch_job.py | 258 - .../v201708/campaign_management/add_trial.py | 116 - .../get_all_disapproved_ads.py | 92 - .../get_all_disapproved_ads_with_awql.py | 76 - .../get_campaigns_by_label.py | 83 - .../campaign_management/graduate_trial.py | 79 - .../campaign_management/set_ad_parameters.py | 100 - .../set_criterion_bid_modifier.py | 77 - .../campaign_management/validate_text_ad.py | 84 - .../v201708/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 131 - .../handle_policy_violation_error.py | 167 - .../adwords/v201708/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 159 - .../adwords/v201708/extensions/add_prices.py | 157 - .../v201708/extensions/add_site_links.py | 146 - .../extensions/add_site_links_using_feeds.py | 236 - .../adwords/v201708/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 527 - examples/adwords/v201708/misc/__init__.py | 15 - .../v201708/misc/get_all_images_and_videos.py | 85 - examples/adwords/v201708/misc/upload_image.py | 66 - .../v201708/misc/upload_media_bundle.py | 60 - .../adwords/v201708/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 180 - ...aign_criterion_bid_modifier_simulations.py | 96 - .../get_keyword_bid_simulations.py | 81 - .../v201708/optimization/get_keyword_ideas.py | 113 - .../adwords/v201708/remarketing/__init__.py | 15 - .../v201708/remarketing/add_audience.py | 103 - .../remarketing/add_conversion_tracker.py | 70 - .../remarketing/add_conversion_trackers.py | 106 - .../remarketing/add_crm_based_user_list.py | 101 - .../remarketing/add_rule_based_user_lists.py | 235 - .../upload_offline_call_conversions.py | 77 - .../remarketing/upload_offline_conversions.py | 82 - .../remarketing/upload_offline_data.py | 199 - .../adwords/v201708/reporting/__init__.py | 15 - ...oad_criteria_report_as_stream_with_awql.py | 84 - ...criteria_report_as_stream_with_selector.py | 77 - ...oad_criteria_report_as_string_with_awql.py | 58 - ...criteria_report_as_string_with_selector.py | 59 - .../download_criteria_report_with_awql.py | 58 - .../download_criteria_report_with_selector.py | 60 - .../v201708/reporting/get_report_fields.py | 52 - .../reporting/parallel_report_download.py | 230 - examples/adwords/v201708/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 280 - .../v201708/shopping/add_product_scope.py | 104 - .../v201708/shopping/add_shopping_campaign.py | 172 - .../add_shopping_campaign_for_showcase_ads.py | 402 - .../shopping/get_product_category_taxonomy.py | 96 - .../adwords/v201708/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 126 - .../add_demographic_targeting_criteria.py | 96 - .../get_campaign_targeting_criteria.py | 85 - .../get_targetable_languages_and_carriers.py | 57 - .../v201708/targeting/lookup_location.py | 82 - .../add_click_to_download_ad.py | 9 +- .../add_dynamic_page_feed.py | 4 +- .../advanced_operations/add_html5_ad.py | 10 +- .../add_responsive_display_ad.py | 3 +- .../campaign_management/validate_text_ad.py | 4 +- .../error_handling/handle_partial_failures.py | 4 +- .../handle_policy_violation_error.py | 11 +- ..._google_my_business_location_extensions.py | 5 +- examples/adwords/v201710/misc/upload_image.py | 3 +- .../v201710/misc/upload_media_bundle.py | 10 +- .../add_shopping_campaign_for_showcase_ads.py | 7 +- .../add_click_to_download_ad.py | 9 +- .../add_dynamic_page_feed.py | 4 +- .../advanced_operations/add_gmail_ad.py | 4 +- .../advanced_operations/add_html5_ad.py | 10 +- .../add_responsive_display_ad.py | 3 +- ...d_shopping_dynamic_remarketing_campaign.py | 3 +- .../campaign_management/validate_text_ad.py | 4 +- .../error_handling/handle_partial_failures.py | 4 +- .../handle_policy_violation_error.py | 13 +- ..._google_my_business_location_extensions.py | 5 +- .../extensions/add_site_links_using_feeds.py | 33 +- examples/adwords/v201802/misc/upload_image.py | 3 +- .../v201802/misc/upload_media_bundle.py | 10 +- .../remarketing/add_crm_based_user_list.py | 4 +- .../add_shopping_campaign_for_showcase_ads.py | 7 +- .../create_dfp_client_with_service_account.py | 7 +- .../authentication/generate_refresh_token.py | 73 +- .../create_creative_from_template.py | 2 - .../creative_service/create_creatives.py | 3 +- .../create_custom_creative.py | 2 - .../create_native_creative.py | 5 +- .../create_creative_from_template.py | 2 - .../creative_service/create_creatives.py | 3 +- .../create_custom_creative.py | 2 - .../create_native_creative.py | 3 - .../get_active_activity_groups.py | 2 +- .../activity_service/get_active_activities.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../get_base_rates_for_rate_card.py | 2 +- .../company_service/get_advertisers.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../create_creative_from_template.py | 2 - .../creative_service/create_creatives.py | 3 +- .../create_custom_creative.py | 2 - .../create_native_creative.py | 3 - .../creative_service/get_image_creatives.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../inventory_service/archive_ad_units.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../label_service/get_active_labels.py | 2 +- .../deactivate_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../line_item_service/activate_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../v201802/order_service/approve_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 2 +- .../get_in_progress_packages.py | 2 +- .../get_active_placements.py | 2 +- .../get_premium_rates_for_rate_card.py | 2 +- ...oduct_package_items_for_product_package.py | 2 +- .../get_active_product_packages.py | 2 +- .../get_products_for_product_template.py | 2 +- .../activate_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../archive_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../get_proposals_pending_approval.py | 2 +- .../request_buyers_acceptance.py | 2 +- .../submit_proposals_for_approval.py | 2 +- .../get_marketplace_rate_cards.py | 2 +- ...order_reports_for_reconciliation_report.py | 2 +- ...n_report_rows_for_reconciliation_report.py | 2 +- ...iliation_report_for_last_billing_period.py | 2 +- .../run_report_with_custom_fields.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 2 +- .../user_service/get_user_by_email_address.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py | 2 +- ...et_workflow_external_condition_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 2 +- googleads.yaml | 34 +- googleads/adwords.py | 392 +- googleads/common.py | 801 +- googleads/dfp.py | 80 +- googleads/errors.py | 14 + googleads/oauth2.py | 147 +- googleads/util.py | 102 +- setup.py | 8 +- tests/adwords_test.py | 998 +- tests/common_test.py | 843 +- tests/dfp_test.py | 166 +- tests/oauth2_test.py | 473 +- tests/test_data/adwords_report_definition.xsd | 155 + tests/test_data/adwords_report_post_body.txt | 1 + ...adwords_report_post_body_no_formatting.txt | 1 + tests/test_data/dfp_report_service.xml | 9326 +++++++++++++++++ .../empty_fault_response_envelope.txt | 4 +- tests/test_data/fault_response_envelope.txt | 4 +- .../multi_errors_fault_response_envelope.txt | 4 +- tests/testing.py | 39 + tests/util_test.py | 326 +- 317 files changed, 12430 insertions(+), 23612 deletions(-) mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/appengine_config.py delete mode 100644 examples/adwords/v201705/__init__.py delete mode 100644 examples/adwords/v201705/account_management/__init__.py delete mode 100755 examples/adwords/v201705/account_management/accept_service_link.py delete mode 100755 examples/adwords/v201705/account_management/create_account.py delete mode 100755 examples/adwords/v201705/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201705/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201705/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_dynamic_page_feed.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_dynamic_search_ads_campaign.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201705/advanced_operations/add_universal_app_campaign.py delete mode 100755 examples/adwords/v201705/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201705/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201705/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201705/basic_operations/__init__.py delete mode 100755 examples/adwords/v201705/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201705/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201705/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201705/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201705/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201705/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201705/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201705/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201705/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201705/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201705/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201705/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201705/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201705/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201705/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201705/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201705/campaign_management/__init__.py delete mode 100755 examples/adwords/v201705/campaign_management/add_campaign_groups_and_performance_targets.py delete mode 100755 examples/adwords/v201705/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201705/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201705/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201705/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201705/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201705/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201705/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201705/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201705/error_handling/__init__.py delete mode 100755 examples/adwords/v201705/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201705/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201705/extensions/__init__.py delete mode 100755 examples/adwords/v201705/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201705/extensions/add_prices.py delete mode 100755 examples/adwords/v201705/extensions/add_site_links.py delete mode 100755 examples/adwords/v201705/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201705/migration/__init__.py delete mode 100755 examples/adwords/v201705/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201705/misc/__init__.py delete mode 100755 examples/adwords/v201705/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201705/misc/upload_image.py delete mode 100755 examples/adwords/v201705/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201705/optimization/__init__.py delete mode 100755 examples/adwords/v201705/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201705/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201705/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201705/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201705/remarketing/__init__.py delete mode 100755 examples/adwords/v201705/remarketing/add_audience.py delete mode 100755 examples/adwords/v201705/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201705/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201705/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201705/remarketing/upload_offline_call_conversions.py delete mode 100755 examples/adwords/v201705/remarketing/upload_offline_conversions.py delete mode 100644 examples/adwords/v201705/reporting/__init__.py delete mode 100755 examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_selector.py delete mode 100755 examples/adwords/v201705/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201705/reporting/download_criteria_report_as_string_with_selector.py delete mode 100755 examples/adwords/v201705/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201705/reporting/download_criteria_report_with_selector.py delete mode 100755 examples/adwords/v201705/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201705/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201705/shopping/__init__.py delete mode 100755 examples/adwords/v201705/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201705/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201705/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py delete mode 100755 examples/adwords/v201705/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201705/targeting/__init__.py delete mode 100755 examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201705/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201705/targeting/lookup_location.py delete mode 100644 examples/adwords/v201708/__init__.py delete mode 100644 examples/adwords/v201708/account_management/__init__.py delete mode 100755 examples/adwords/v201708/account_management/accept_service_link.py delete mode 100755 examples/adwords/v201708/account_management/create_account.py delete mode 100755 examples/adwords/v201708/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201708/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201708/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_dynamic_page_feed.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_dynamic_search_ads_campaign.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py delete mode 100755 examples/adwords/v201708/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201708/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201708/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201708/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201708/basic_operations/__init__.py delete mode 100755 examples/adwords/v201708/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201708/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201708/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201708/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201708/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201708/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201708/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201708/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201708/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201708/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201708/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201708/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201708/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201708/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201708/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201708/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201708/campaign_management/__init__.py delete mode 100755 examples/adwords/v201708/campaign_management/add_campaign_groups_and_performance_targets.py delete mode 100755 examples/adwords/v201708/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201708/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201708/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201708/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201708/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201708/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201708/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201708/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201708/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201708/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201708/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201708/error_handling/__init__.py delete mode 100755 examples/adwords/v201708/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201708/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201708/extensions/__init__.py delete mode 100755 examples/adwords/v201708/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201708/extensions/add_prices.py delete mode 100755 examples/adwords/v201708/extensions/add_site_links.py delete mode 100755 examples/adwords/v201708/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201708/migration/__init__.py delete mode 100755 examples/adwords/v201708/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201708/misc/__init__.py delete mode 100755 examples/adwords/v201708/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201708/misc/upload_image.py delete mode 100755 examples/adwords/v201708/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201708/optimization/__init__.py delete mode 100755 examples/adwords/v201708/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201708/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201708/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201708/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201708/remarketing/__init__.py delete mode 100755 examples/adwords/v201708/remarketing/add_audience.py delete mode 100755 examples/adwords/v201708/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201708/remarketing/add_conversion_trackers.py delete mode 100755 examples/adwords/v201708/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201708/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201708/remarketing/upload_offline_call_conversions.py delete mode 100755 examples/adwords/v201708/remarketing/upload_offline_conversions.py delete mode 100755 examples/adwords/v201708/remarketing/upload_offline_data.py delete mode 100644 examples/adwords/v201708/reporting/__init__.py delete mode 100755 examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_selector.py delete mode 100755 examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201708/reporting/download_criteria_report_as_string_with_selector.py delete mode 100755 examples/adwords/v201708/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201708/reporting/download_criteria_report_with_selector.py delete mode 100755 examples/adwords/v201708/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201708/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201708/shopping/__init__.py delete mode 100755 examples/adwords/v201708/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201708/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201708/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py delete mode 100755 examples/adwords/v201708/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201708/targeting/__init__.py delete mode 100755 examples/adwords/v201708/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201708/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201708/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201708/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201708/targeting/lookup_location.py create mode 100644 tests/test_data/adwords_report_definition.xsd create mode 100644 tests/test_data/adwords_report_post_body.txt create mode 100644 tests/test_data/adwords_report_post_body_no_formatting.txt create mode 100644 tests/test_data/dfp_report_service.xml diff --git a/ChangeLog b/ChangeLog index 7fe99848..8613c576 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,44 @@ +11.0.0 -- 03/21/18 +* Removed support and examples for AdWords v201705, and v201708. +* The default SOAP backend is now zeep. If you encounter any issues, + please report them and use your googleads.yaml file to revert back + to suds. +- Zeep logs to the googleads.soap channel. +- When using zeep (the default), you no longer need to encode your + image assets to base64, this will be done automatically. +* Sunset oauth2client, replaced with google-auth. + https://google-auth.readthedocs.io/en/latest/ +- Updated googleads.yaml to remove service_account_email configurations that + are no longer necessary. +- Removed httplib2 dependency. +- Added google-auth, google-auth-oauthlib, and requests as dependencies. +- AdWords and DFP auth examples have been updated to use new OAuth 2.0 + dependencies. +* Fixed a bug in IncrementalUploadHelper where the specified server would be + lost in serialization/deserialization. +* Breaking changes: +* Connection faults are now raised as GoogleAdsSoapTransportError + instances instead of suds errors. +- Soap faults are now raised as GoogleAdsServerFault instances instead of suds + errors. +- GoogleServiceAccountClient no longer supports P12 key files. +- GoogleServiceAccountClient's initializer arguments have been refactored; + `key_file` is now a required positional argument, `client_email` and + `private_key_password` have been removed. +- Removed Proxy from common.py. When creating a ProxyConfig, you must now + provide the full URI for http_proxy and https_proxy rather than a Proxy + instance. For an example of what these would look like, see: + http://docs.python-requests.org/en/master/user/advanced/#proxies +- The proxy_config used in googleads.yaml has been updated to better resemble + proxy configuration for the underlying HTTP library. The http_proxy and + https_proxy configurations have been removed, and replaced with http and + https. These take the full proxy URI as their value. +- Removed proxy_info attribute from ProxyConfig. +- Refactored proxy_option attribute in ProxyConfig, renamed to proxies. +* Resolved issues: +- Issue 251: https://github.com/googleads/googleads-python-lib/issues/251 +- Issue 254: https://github.com/googleads/googleads-python-lib/issues/254 + 10.1.1 -- 03/16/18 * Accepted PR #222, to improve AdWords App Engine sample. diff --git a/README.md b/README.md index 1141e2b4..147dcd43 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,14 @@ configuration via the configuration file; see [googleads.yaml](https://github.co for an example. Alternatively, you can manually specify your logging configuration. For example, -if you want to log your SOAP interactions to stdout, you can do the following: +if you want to log your SOAP interactions to stdout, and you are using the Zeep soap library, you +can do the following: +```python +logging.basicConfig(level=logging.INFO, format=googleads.util.LOGGER_FORMAT) +logging.getLogger('googleads.soap').setLevel(logging.DEBUG) +``` + +If you are using suds, you can achieve the same like this: ```python logging.basicConfig(level=logging.INFO, format=googleads.util.LOGGER_FORMAT) logging.getLogger('suds.transport').setLevel(logging.DEBUG) @@ -116,7 +123,22 @@ which is configured to write the output to a file. ## How do I disable log filters? -By default, this library will apply log filters to the `googleads.common`, +The zeep plugin used for logging strips sensitive data from its output. If you would like this data +included in logs, you'll need to implement your own simple logging plugin. For example: +```python +class DangerousZeepLogger(zeep.Plugin): + def ingress(self, envelope, http_headers, operation): + logging.debug('Incoming response: \n%s', etree.tostring(envelope, pretty_print=True)) + return envelope, http_headers + + def egress(self, envelope, http_headers, operation, binding_options): + logging.debug('Incoming response: \n%s', etree.tostring(envelope, pretty_print=True)) + return envelope, http_headers + +adwords_client.zeep_client.plugins.append(DangerousZeepLogger()) +``` + +When using suds, this library will apply log filters to the `googleads.common`, `suds.client`, and `suds.transport` loggers in order to omit sensitive data. If you need to see this data in your logs, you can disable the filters with the following: @@ -134,10 +156,10 @@ logging.getLogger('suds.transport').removeFilter( ``` -## I'm familiar with suds. Can I use suds features with this library? +## I'm familiar with suds/zeep. Can I use those features in the library? Yes, you can. The services returned by the `client.GetService()` functions all -have a reference to the underlying suds client stored in the `suds_client` -attribute. You can retrieve the client and use it in familiar ways: +have a reference to the underlying client stored in the `zeep_client` or `suds_client` +attributes. You can retrieve the client and use it in familiar ways: ```python client = AdWordsClient.LoadFromStorage() campaign_service = client.GetService('CampaignService') @@ -170,17 +192,25 @@ suds_client.set_options( suds_client.service.mutate([operation]) ``` -## How can I configure or disable caching for the suds client? +## How can I configure or disable caching? -By default, the suds clients are cached because reading and digesting the WSDL +By default, clients are cached because reading and digesting the WSDL can be expensive. However, the default caching method requires permission to access a local file system that may not be available in certain hosting environments such as App Engine. -You can pass an implementation of `suds.cache.Cache` to the `AdWordsClient` or +You can pass an implementation of `suds.cache.Cache` or `zeep.cache.Base` to the `AdWordsClient` or `DfpClient` initializer to modify the default caching behavior. -For example, configuring a different location and duration of the cache file: +For example, configuring a different location and duration of the cache file with zeep +```python +doc_cache = zeep.cache.SqliteCache(path=cache_path) +adwords_client = adwords.AdWordsClient( + developer_token, oauth2_client, user_agent, + client_customer_id=client_customer_id, cache=doc_cache) +``` + +And with suds: ```python doc_cache = suds.cache.DocumentCache(location=cache_path, days=2) adwords_client = adwords.AdWordsClient( @@ -188,7 +218,14 @@ adwords_client = adwords.AdWordsClient( client_customer_id=client_customer_id, cache=doc_cache) ``` -You can also disable caching in similar fashion: +You can also disable caching in similar fashion with zeep +```python +adwords_client = adwords.AdWordsClient( + developer_token, oauth2_client, user_agent, + client_customer_id=client_customer_id, cache=None) +``` + +And with suds: ```python adwords_client = adwords.AdWordsClient( developer_token, oauth2_client, user_agent, @@ -212,6 +249,7 @@ have Python 2.7.9 (or higher) or Python 3.4 (or higher) installed. - pytz -- https://pypi.python.org/pypi/pytz - pyYAML -- https://pypi.python.org/pypi/pyYAML/ - xmltodict -- https://pypi.python.org/pypi/xmltodict/ + - zeep -- https://pypi.python.org/pypi/zeep - mock -- https://pypi.python.org/pypi/mock (only needed to run unit tests) - pyfakefs -- https://pypi.python.org/pypi/pyfakefs diff --git a/examples/adwords/adwords_appengine_demo/appengine_config.py b/examples/adwords/adwords_appengine_demo/appengine_config.py old mode 100644 new mode 100755 index 5c567b83..3df1ea8e --- a/examples/adwords/adwords_appengine_demo/appengine_config.py +++ b/examples/adwords/adwords_appengine_demo/appengine_config.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python +# # Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,6 +20,6 @@ import os from google.appengine.ext import vendor -# Add any libraries install in the "lib" folder. +# Add any libraries installed in the "lib" folder to the path. vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')) diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index b4b0b4f9..2a171b43 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -22,7 +22,6 @@ # OAuth2 credential information. In a real application, you'd probably be # pulling these values from a credential storage. -SERVICE_ACCOUNT_EMAIL = 'INSERT_SERVICE_ACCOUNT_EMAIL_HERE' KEY_FILE = 'INSERT_PATH_TO_KEY_FILE' SERVICE_ACCOUNT_USER = 'INSERT_IMPERSONATED_EMAIL_HERE' @@ -32,11 +31,10 @@ CLIENT_CUSTOMER_ID = 'INSERT_CLIENT_CUSTOMER_ID_HERE' -def main(service_account_email, key_file, service_account_user, - developer_token, user_agent, client_customer_id): +def main(key_file, service_account_user, developer_token, user_agent, + client_customer_id): oauth2_client = oauth2.GoogleServiceAccountClient( - oauth2.GetAPIScope('adwords'), service_account_email, key_file, - sub=service_account_user) + key_file, oauth2.GetAPIScope('adwords'), sub=service_account_user) adwords_client = adwords.AdWordsClient( developer_token, oauth2_client, user_agent, @@ -53,5 +51,5 @@ def main(service_account_email, key_file, service_account_user, if __name__ == '__main__': - main(SERVICE_ACCOUNT_EMAIL, KEY_FILE, SERVICE_ACCOUNT_USER, - DEVELOPER_TOKEN, USER_AGENT, CLIENT_CUSTOMER_ID) + main(KEY_FILE, SERVICE_ACCOUNT_USER, DEVELOPER_TOKEN, USER_AGENT, + CLIENT_CUSTOMER_ID) diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 0f5d1829..ed879c45 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -20,7 +20,8 @@ import argparse import sys -from oauth2client import client +from google_auth_oauthlib.flow import InstalledAppFlow +from oauthlib.oauth2.rfc6749.errors import InvalidGrantError # Your OAuth2 Client ID and Secret. If you do not have an ID and Secret yet, # please go to https://console.developers.google.com and create a set. @@ -29,6 +30,9 @@ # The AdWords API OAuth2 scope. SCOPE = u'https://www.googleapis.com/auth/adwords' +# The redirect URI set for the given Client ID. The redirect URI for Client ID +# generated for an installed application will always have this value. +_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' parser = argparse.ArgumentParser(description='Generates a refresh token with ' 'the provided credentials.') @@ -42,31 +46,68 @@ 'refresh token. Each scope should be separated by a comma.') +class ClientConfigBuilder(object): + """Helper class used to build a client config dict used in the OAuth 2.0 flow. + """ + _DEFAULT_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' + _DEFAULT_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' + CLIENT_TYPE_WEB = 'web' + CLIENT_TYPE_INSTALLED_APP = 'installed' + + def __init__(self, client_type=None, client_id=None, client_secret=None, + auth_uri=_DEFAULT_AUTH_URI, token_uri=_DEFAULT_TOKEN_URI): + self.client_type = client_type + self.client_id = client_id + self.client_secret = client_secret + self.auth_uri = auth_uri + self.token_uri = token_uri + + def Build(self): + """Builds a client config dictionary used in the OAuth 2.0 flow.""" + if all((self.client_type, self.client_id, self.client_secret, + self.auth_uri, self.token_uri)): + client_config = { + self.client_type: { + 'client_id': self.client_id, + 'client_secret': self.client_secret, + 'auth_uri': self.auth_uri, + 'token_uri': self.token_uri + } + } + else: + raise ValueError('Required field is missing.') + + return client_config + + def main(client_id, client_secret, scopes): """Retrieve and display the access and refresh token.""" - flow = client.OAuth2WebServerFlow( - client_id=client_id, - client_secret=client_secret, - scope=scopes, - user_agent='Ads Python Client Library', - redirect_uri='urn:ietf:wg:oauth:2.0:oob') + client_config = ClientConfigBuilder( + client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id, + client_secret=client_secret) + + flow = InstalledAppFlow.from_client_config( + client_config.Build(), scopes=scopes) + # Note that from_client_config will not produce a flow with the + # redirect_uris (if any) set in the client_config. This must be set + # separately. + flow.redirect_uri = _REDIRECT_URI - authorize_url = flow.step1_get_authorize_url() + auth_url, _ = flow.authorization_url(prompt='consent') - print ('Log into the Google Account you use to access your AdWords account' - 'and go to the following URL: \n%s\n' % (authorize_url)) + print ('Log into the Google Account you use to access your AdWords account ' + 'and go to the following URL: \n%s\n' % auth_url) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: - credential = flow.step2_exchange(code) - except client.FlowExchangeError, e: - print 'Authentication has failed: %s' % e + flow.fetch_token(code=code) + except InvalidGrantError as ex: + print 'Authentication has failed: %s' % ex sys.exit(1) - else: - print ('OAuth2 authorization successful!\n\n' - 'Your access token is:\n %s\n\nYour refresh token is:\n %s' - % (credential.access_token, credential.refresh_token)) + + print 'Access token: %s' % flow.credentials.token + print 'Refresh token: %s' % flow.credentials.refresh_token if __name__ == '__main__': diff --git a/examples/adwords/v201705/__init__.py b/examples/adwords/v201705/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201705/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201705/account_management/__init__.py b/examples/adwords/v201705/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201705/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201705/account_management/accept_service_link.py b/examples/adwords/v201705/account_management/accept_service_link.py deleted file mode 100755 index 1aa603b5..00000000 --- a/examples/adwords/v201705/account_management/accept_service_link.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' - - -def main(client, service_link_id): - # Initialize appropriate service. - customer_service = client.GetService( - 'CustomerService', version='v201705') - - # Create the operation to set the status to ACTIVE. - operations = [{ - 'operator': 'SET', - 'operand': { - 'serviceLinkId': service_link_id, - 'serviceType': 'MERCHANT_CENTER', - 'linkStatus': 'ACTIVE', - } - }] - - # Update the service link. - mutated_service_links = customer_service.mutateServiceLinks(operations) - - # Display results. - for mutated_service_link in mutated_service_links: - print ('Service link with service link ID "%s", type "%s" was updated ' - 'to status: "%s".' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201705/account_management/create_account.py b/examples/adwords/v201705/account_management/create_account.py deleted file mode 100755 index 9f1392cb..00000000 --- a/examples/adwords/v201705/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201705') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID "%s" was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/account_management/get_account_changes.py b/examples/adwords/v201705/account_management/get_account_changes.py deleted file mode 100755 index 22ca4637..00000000 --- a/examples/adwords/v201705/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201705') - campaign_service = client.GetService('CampaignService', version='v201705') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id "%s" has change status "%s".' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id "%s" has change status "%s".' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/account_management/get_account_hierarchy.py b/examples/adwords/v201705/account_management/get_account_hierarchy.py deleted file mode 100755 index 8644b35b..00000000 --- a/examples/adwords/v201705/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201705') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/advanced_operations/__init__.py b/examples/adwords/v201705/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201705/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201705/advanced_operations/add_ad_customizer.py b/examples/adwords/v201705/advanced_operations/add_ad_customizer.py deleted file mode 100755 index bc8718e7..00000000 --- a/examples/adwords/v201705/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates ExpandedTextAds that use ad customizations for specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no ExpandedTextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201705') - - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'headlinePart2': 'Only {=%s.Price}' % feed_name, - 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': expanded_text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID "%s", type "%s", and status "%s".' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201705') - - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name "%s" and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201705') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - return {'operator': 'ADD', 'operand': feed_item} - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201705/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201705/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 993bd6f5..00000000 --- a/examples/adwords/v201705/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201705') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 284bd2dd..00000000 --- a/examples/adwords/v201705/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Optionally, you may specify a landscape image. The image needs to be in a - # BASE64 encoded form. Here we download a demo image and encode it for this - # ad. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) - .decode('utf-8')) - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - }, - { - 'name': 'landscapeImage', - 'fieldMedia': { - 'xsi_type': 'Image', - 'data': image_data - }, - 'type': 'IMAGE' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201705/advanced_operations/add_dynamic_page_feed.py deleted file mode 100755 index bd16bc9a..00000000 --- a/examples/adwords/v201705/advanced_operations/add_dynamic_page_feed.py +++ /dev/null @@ -1,295 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. - -To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -from collections import namedtuple -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - -# Used to keep track of DSA page feed details. -_DSAFeedDetails = namedtuple( - '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) -# ID that corresponds to the labels. -DSA_LABEL_FIELD_ID = 2 -# The criterion type to be used for DSA page feeds. -DSA_PAGE_FEED_CRITERION_TYPE = 61 -DSA_PAGE_URL_LABEL = 'discounts' -# ID that corresponds to the page URLs. -DSA_PAGE_URLS_FIELD_ID = 1 - - -def main(client, campaign_id, ad_group_id): - # Get the page feed details. This code example creates a new feed, but you can - # fetch and re-use an existing feed. - feed_details = _CreateFeed(client) - _CreateFeedMapping(client, feed_details) - _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) - - # Associate the page feed with the campaign. - _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) - - # Optional: Target web pages matching the feed's label in the ad group. - _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) - - print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id - - -def _CreateFeed(client): - """Creates the feed for DSA page URLs. - - Args: - client: an AdWordsClient instance. - - Returns: - A _DSAFeedDetails instance containing details about the created feed. - """ - # Get the FeedService. - feed_service = client.GetService('FeedService', version='v201705') - - # Create operation. - operation = { - # Create the feed. - 'operand': { - 'name': 'DSA Feed %s' % uuid.uuid4(), - # Create attributes. - 'attributes': [ - {'type': 'URL_LIST', 'name': 'Page URL'}, - {'type': 'STRING_LIST', 'name': 'Label'} - ], - 'origin': 'USER' - }, - 'operator': 'ADD' - } - - # Add the feed. - feed = feed_service.mutate([operation])['value'][0] - return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], - feed['attributes'][1]['id']) - - -def _CreateFeedMapping(client, feed_details): - """Creates the feed mapping for DSA page feeds. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - """ - # Get the FeedMappingService. - feed_mapping_service = client.GetService('FeedMappingService', - version='v201705') - - # Create the operation. - operation = { - # Create the feed mapping. - 'operand': { - 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, - 'feedId': feed_details.feed_id, - # Map the feedAttributeIds to the fieldId constants. - 'attributeFieldMappings': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'fieldId': DSA_PAGE_URLS_FIELD_ID - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'fieldId': DSA_LABEL_FIELD_ID - } - ] - }, - 'operator': 'ADD' - } - - # Add the feed mapping. - feed_mapping_service.mutate([operation]) - - -def _CreateFeedItems(client, feed_details, label_name): - """Creates the page URLs in the DSA page feed. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - label_name: a str containing the page feed URL label. - """ - # Get the FeedItemService. - feed_item_service = client.GetService('FeedItemService', version='v201705') - - # Optional: You can include the {feeditem} valuetrack parameter to track which - # page feed items lead to each click. - urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', - 'http://www.example.com/discounts/hotel-deals?id={feeditem}', - 'http://www.example.com/discounts/flight-deals?id={feeditem}') - - # Create the operation. - operations = [{ - # Create the feed item. - 'operand': { - 'feedId': feed_details.feed_id, - 'attributeValues': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'stringValues': [url] - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'stringValues': [label_name] - } - ] - }, - 'operator': 'ADD' - } for url in urls] - - # Add the feed item. - feed_item_service.mutate(operations) - - -def _UpdateCampaignDSASetting(client, campaign_id, feed_id): - """Updates the campaign DSA setting to DSA pagefeeds. - - Args: - client: an AdWordsClient instance. - campaign_id: a str Campaign ID. - feed_id: a str page Feed ID. - - Raises: - ValueError: If the given campaign is found not to be a dynamic search ad - campaign. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201705') - - selector = { - 'fields': ['Id', 'Settings'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [campaign_id] - }] - } - - response = campaign_service.get(selector) - - if response['totalNumEntries']: - campaign = response['entries'][0] - else: - raise ValueError('No campaign with ID "%d" exists.' % campaign_id) - - if not campaign['settings']: - raise ValueError('This is not a DSA campaign.') - - dsa_setting = None - - campaign_settings = campaign['settings'] - - for setting in campaign_settings: - if setting['Setting.Type'] == 'DynamicSearchAdsSetting': - dsa_setting = setting - break - - if dsa_setting is None: - raise ValueError('This is not a DSA campaign.') - - dsa_setting['pageFeed'] = { - 'feedIds': [feed_id] - } - - # Optional: Specify whether only the supplied URLs should be used with your - # Dynamic Search Ads. - dsa_setting['useSuppliedUrlsOnly'] = True - - operation = { - 'operand': { - 'id': campaign_id, - 'settings': campaign_settings - }, - 'operator': 'SET' - } - - campaign_service.mutate([operation]) - print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( - campaign_id, feed_id) - - -def _AddDSATargeting(client, ad_group_id, label_name): - """Set custom targeting for the page feed URLs based on a list of labels. - - Args: - client: an AdWordsClient instance. - ad_group_id: a str AdGroup ID. - label_name: a str label name. - - Returns: - A suds.sudsobject.Object representing the newly created webpage criterion. - """ - # Get the AdGroupCriterionService. - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201705') - - # Create the operation. - operation = { - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Test criterion', - # Add a condition for label=specified_label_name. - 'conditions': [{ - 'operand': 'CUSTOM_LABEL', - 'argument': label_name - }], - } - }, - # Set a custom bid for this criterion - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 1500000 - } - }] - } - }, - 'operator': 'ADD' - } - - criterion = ad_group_criterion_service.mutate([operation])['value'][0] - print 'Web page criterion with ID "%d" and status "%s" was created.' % ( - criterion['criterion']['id'], criterion['userStatus']) - return criterion - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201705/advanced_operations/add_dynamic_search_ads_campaign.py deleted file mode 100755 index 4eb2f319..00000000 --- a/examples/adwords/v201705/advanced_operations/add_dynamic_search_ads_campaign.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Dynamic Search Ads campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - budget = _CreateBudget(client) - campaign_id = _CreateCampaign(client, budget) - ad_group_id = _CreateAdGroup(client, campaign_id) - _CreateExpandedDSA(client, ad_group_id) - _AddWebPageCriteria(client, ad_group_id) - - print 'Dynamic Search Ads campaign setup is complete.' - - -def _CreateBudget(client): - """Creates the budget. - - Args: - client: an AdWordsClient instance. - - Returns: - a suds.sudsobject.Object representation of the created budget. - """ - budget_service = client.GetService('BudgetService', version='v201705') - - # Create the campaign budget - operation = { - 'operand': { - 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), - 'deliveryMethod': 'STANDARD', - 'amount': { - 'microAmount': 500000 - } - }, - 'operator': 'ADD' - } - - budget = budget_service.mutate([operation])['value'][0] - - print 'Budget with ID "%d" and name "%s" was created.' % ( - budget['budgetId'], budget['name']) - - return budget - - -def _CreateCampaign(client, budget): - """Creates the campaign. - - Args: - client: an AdWordsClient instance. - budget: a suds.sudsobject.Object representation of a created budget. - - Returns: - An integer campaign ID. - """ - campaign_service = client.GetService('CampaignService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # prevent the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'budget': budget, - # Required: Set the campaign's Dynamic Search Ad settings. - 'settings': [{ - 'xsi_type': 'DynamicSearchAdsSetting', - # Required: Set the domain name and language. - 'domainName': 'example.com', - 'languageCode': 'en' - }], - # Optional: Set the start date. - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - # Optional: Set the end date. - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - }] - - campaign = campaign_service.mutate(operations)['value'][0] - campaign_id = campaign['id'] - - print 'Campaign with ID "%d" and name "%s" was added.' % ( - campaign_id, campaign['name']) - - return campaign_id - - -def _CreateAdGroup(client, campaign_id): - """Creates an ad group. - - Args: - client: an AdWordsClient instance. - campaign_id: an integer campaign ID. - - Returns: - An integer ad group ID. - """ - ad_group_service = client.GetService('AdGroupService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'adGroupType': 'SEARCH_DYNAMIC_ADS', - 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '3000000' - }, - }] - } - } - }] - - ad_group = ad_group_service.mutate(operations)['value'][0] - ad_group_id = ad_group['id'] - - print 'Ad group with ID "%d" and name "%s" was created.' % ( - ad_group_id, ad_group['name']) - - return ad_group_id - - -def _CreateExpandedDSA(client, ad_group_id): - """Creates the expanded Dynamic Search Ad. - - Args: - client: an AdwordsClient instance. - ad_group_id: an integer ID of the ad group in which the DSA is added. - """ - # Get the AdGroupAdService. - ad_group_ad_service = client.GetService('AdGroupAdService') - - # Create the operation - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - # Create the expanded dynamic search ad. This ad will have its - # headline and final URL auto-generated at serving time according to - # domain name specific information provided by DynamicSearchAdsSetting - # at the campaign level. - 'ad': { - 'xsi_type': 'ExpandedDynamicSearchAd', - # Set the ad description. - 'description': 'Buy your tickets now!' - }, - # Optional: Set the status. - 'status': 'PAUSED', - } - }] - - # Create the ad. - ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] - - # Display the results. - print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' - 'added' % (ad['id'], ad['description'])) - - -def _AddWebPageCriteria(client, ad_group_id): - """Adds a web page criterion to target Dynamic Search Ads. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID of the ad group the criteria is being added to. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201705') - - operations = [{ - 'operator': 'ADD', - # Create biddable ad group criterion. - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion for special offers for children. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Special offers for children.', - 'conditions': [ - { - 'operand': 'URL', - 'argument': '/marscruise/children' - }, - { - 'operand': 'PAGE_TITLE', - 'argument': 'Special Offer' - } - ] - } - }, - 'userStatus': 'PAUSED', - # Optional: set a custom bid. - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000L - } - }] - } - } - }] - - criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( - criterion['criterion']['id'], criterion['adGroupId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201705/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py deleted file mode 100755 index 067f0d8c..00000000 --- a/examples/adwords/v201705/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Create the expanded text ad - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': expanded_text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_html5_ad.py b/examples/adwords/v201705/advanced_operations/add_html5_ad.py deleted file mode 100755 index 988d2c93..00000000 --- a/examples/adwords/v201705/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index f096b1d8..00000000 --- a/examples/adwords/v201705/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,93 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - media_service = client.GetService('MediaService', version='v201705') - - try: - # Create image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = (base64.b64encode(opener.open('https://goo.gl/3b9Wfh').read()) - .decode('utf-8')) - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - # Make the upload request - image = media_service.upload(image)[0] - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'] - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201705/advanced_operations/add_universal_app_campaign.py deleted file mode 100755 index 93ce0930..00000000 --- a/examples/adwords/v201705/advanced_operations/add_universal_app_campaign.py +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Universal App campaign. - -To get campaigns, run get_campaigns.py. To upload image assets for this -campaign, run upload_image.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201705') - - budget_id = CreateBudget(client) - - # Create the Universal App campaign. - universal_app_campaign = { - 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'MULTI_CHANNEL', - 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', - # Set the campaign's bidding strategy. Universal app campaigns only - # support TARGET_CPA bidding strategy. - 'biddingStrategyConfiguration': { - # Set the target CPA to $1 / app install. - 'biddingScheme': { - 'xsi_type': 'TargetCpaBiddingScheme', - 'targetCpa': { - 'microAmount': '1000000' - } - }, - 'biddingStrategyType': 'TARGET_CPA' - }, - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - - universal_app_campaign['settings'] = [ - # Set the campaign's assets and ad text ideas. These values will - # be used to generate ads. - { - 'xsi_type': 'UniversalAppCampaignSetting', - 'appId': 'com.labpixies.colordrips', - 'description1': 'A cool puzzle game', - 'description2': 'Remove connected blocks', - 'description3': '3 difficulty levels', - 'description4': '4 colorful fun skins', - # Optional: You can set up to 10 image assets for your campaign. - # See upload_image.py for an example on how to upload images. - # - # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] - } - ] - - # Optimize this campaign for getting new users for your app. - universal_app_campaign_setting = universal_app_campaign['settings'][0] - universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( - 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') - - # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, - # then also specify your in-app conversion types so AdWords can focus your - # campaign on people who are most likely to complete the corresponding in-app - # actions. - # - # Conversions type IDs can be retrieved using ConversionTrackerService.get. - # universal_app_campaign['selectiveOptimization'] = { - # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] - # } - - # Optional: Set the campaign settings for Advanced location options. - universal_app_campaign['settings'].append({ - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - }) - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': universal_app_campaign - }] - - campaigns = campaign_service.mutate(operations)['value'] - - # Display results. - if campaigns: - for campaign in campaigns: - print ('Universal App Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - # Optional: Set the campaign's location and language targeting. No other - # targeting criteria can be used for Universal App campaigns. - SetCampaignTargetingCriteria(client, campaign) - else: - print 'No Universal App campaigns were added.' - - -def CreateBudget(client): - """Creates a budget and returns its budgetId. - - Args: - client: An AdWordsClient instance. - - Returns: - An int budgetId for the created Budget. - """ - budget_service = client.GetService('BudgetService', version='v201705') - - # Create a budget. - budget = { - 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': False - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Create the budget and return its ID. - budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - - return budget_id - - -def SetCampaignTargetingCriteria(client, campaign): - """Sets targeting criteria for the given campaign. - - Args: - client: An AdWordsClient instance. - campaign: A suds object representing the campaign we wish to attach - targeting criteria. - """ - campaign_criterion_service = client.GetService('CampaignCriterionService') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - criteria = [ - { - 'xsi_type': 'Location', - 'id': 21137 # California - }, - { - 'xsi_type': 'Location', - 'id': 2484 # Mexico - }, - { - 'xsi_type': 'Language', - 'id': 1000 # English - }, - { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - ] - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign['id'], - 'criterion': criterion - } - } for criterion in criteria] - - response = campaign_criterion_service.mutate(operations) - - if response and 'value' in response: - # Display the added campaign targets. - for criterion in response['value']: - print ('Campaign criteria of type "%s" and id "%s" was added.' - % (criterion['criterion']['type'], - criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201705/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 95cf7815..00000000 --- a/examples/adwords/v201705/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201705') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201705') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201705') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201705/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index 03e3fa1b..00000000 --- a/examples/adwords/v201705/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201705') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201705') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201705/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 7e6c0840..00000000 --- a/examples/adwords/v201705/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201705') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 9827d33a..00000000 --- a/examples/adwords/v201705/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201705') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201705') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201705') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201705/basic_operations/__init__.py b/examples/adwords/v201705/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201705/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201705/basic_operations/add_ad_groups.py b/examples/adwords/v201705/basic_operations/add_ad_groups.py deleted file mode 100755 index 5e247208..00000000 --- a/examples/adwords/v201705/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201705') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/basic_operations/add_campaigns.py b/examples/adwords/v201705/basic_operations/add_campaigns.py deleted file mode 100755 index 6446311b..00000000 --- a/examples/adwords/v201705/basic_operations/add_campaigns.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201705') - budget_service = client.GetService('BudgetService', version='v201705') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201705/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index ea8a38f9..00000000 --- a/examples/adwords/v201705/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/add_keywords.py b/examples/adwords/v201705/basic_operations/add_keywords.py deleted file mode 100755 index ab949425..00000000 --- a/examples/adwords/v201705/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201705') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id "%s", criterion id ' - '"%s", text "%s", and match type "%s" was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/get_ad_groups.py b/examples/adwords/v201705/basic_operations/get_ad_groups.py deleted file mode 100755 index 22561aca..00000000 --- a/examples/adwords/v201705/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201705') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name "%s", id "%s" and status "%s" was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/basic_operations/get_campaigns.py b/examples/adwords/v201705/basic_operations/get_campaigns.py deleted file mode 100755 index fac8642e..00000000 --- a/examples/adwords/v201705/basic_operations/get_campaigns.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201705') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 29e06c4a..00000000 --- a/examples/adwords/v201705/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201705') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201705/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index ffaeedaa..00000000 --- a/examples/adwords/v201705/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/get_keywords.py b/examples/adwords/v201705/basic_operations/get_keywords.py deleted file mode 100755 index 4e1a3b80..00000000 --- a/examples/adwords/v201705/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201705') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID "%s", type "%s", text "%s", and match type ' - '"%s" was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/pause_ad.py b/examples/adwords/v201705/basic_operations/pause_ad.py deleted file mode 100755 index 7ccbb9ab..00000000 --- a/examples/adwords/v201705/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id "%s" was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201705/basic_operations/remove_ad.py b/examples/adwords/v201705/basic_operations/remove_ad.py deleted file mode 100755 index b03e4a83..00000000 --- a/examples/adwords/v201705/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id "%s" and type "%s" was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201705/basic_operations/remove_ad_group.py b/examples/adwords/v201705/basic_operations/remove_ad_group.py deleted file mode 100755 index b5b1933c..00000000 --- a/examples/adwords/v201705/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201705') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name "%s" and id "%s" was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/remove_campaign.py b/examples/adwords/v201705/basic_operations/remove_campaign.py deleted file mode 100755 index a87f0af7..00000000 --- a/examples/adwords/v201705/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201705') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name "%s" and id "%s" was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/basic_operations/remove_keyword.py b/examples/adwords/v201705/basic_operations/remove_keyword.py deleted file mode 100755 index e8e35f55..00000000 --- a/examples/adwords/v201705/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201705') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id "%s", criterion id "%s", ' - 'and type "%s" was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201705/basic_operations/update_ad_group.py b/examples/adwords/v201705/basic_operations/update_ad_group.py deleted file mode 100755 index 4a38afd0..00000000 --- a/examples/adwords/v201705/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201705') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/basic_operations/update_campaign.py b/examples/adwords/v201705/basic_operations/update_campaign.py deleted file mode 100755 index 75696f9a..00000000 --- a/examples/adwords/v201705/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201705') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/basic_operations/update_keyword.py b/examples/adwords/v201705/basic_operations/update_keyword.py deleted file mode 100755 index 8e72498e..00000000 --- a/examples/adwords/v201705/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201705') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id "%s" and criterion id ' - '"%s" currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: "%s", value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201705/campaign_management/__init__.py b/examples/adwords/v201705/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201705/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201705/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201705/campaign_management/add_campaign_groups_and_performance_targets.py deleted file mode 100755 index 9fda448f..00000000 --- a/examples/adwords/v201705/campaign_management/add_campaign_groups_and_performance_targets.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a campaign group and sets a performance target for it. - -To get campaigns, run get_campaigns.py. To download reports, run -download_criteria_report_with_awql.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id1, campaign_id2): - campaign_group_id = _CreateCampaignGroup(client) - _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) - _CreatePerformanceTarget(client, campaign_group_id) - print 'Campaign group and its performance target were setup successfully.' - - -def _CreateCampaignGroup(client): - """Create a campaign group. - - Args: - client: an AdWordsClient instance. - - Returns: - The integer ID of the created campaign group. - """ - # Get the CampaignGroupService. - campaign_group_service = client.GetService('CampaignGroupService', - version='v201705') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the campaign group. - 'operand': { - 'name': 'Mars campaign group #%d' % uuid.uuid4() - } - }] - - campaign_group = campaign_group_service.mutate(operations)['value'][0] - campaign_group_id = campaign_group['id'] - - # Display the results. - print 'Campaign group with ID "%d" and name "%s" was created.' % ( - campaign_group_id, campaign_group['name']) - - return campaign_group_id - - -def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): - """Adds multiple campaigns to a campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - campaign_ids: a list of integer IDs for campaigns. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201705') - - # Create the operations. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'campaignGroupId': campaign_group_id - } - } for campaign_id in campaign_ids] - - campaign_service.mutate(operations) - - # Display the results. - print ('The following campaign IDs were added to the campaign group with ID ' - '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) - - -def _CreatePerformanceTarget(client, campaign_group_id): - """Creates a performance target for the campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - """ - # Get the CampaignGroupPerformanceTargetService. - cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', - version='v201705') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the performance target. - 'operand': { - 'campaignGroupId': campaign_group_id, - 'performanceTarget': { - # Keep the CPC for the campaigns < $3. - 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', - 'efficiencyTargetValue': 3000000, - # Keep the maximum spend under $50. - 'spendTargetType': 'MAXIMUM', - 'spendTarget': { - 'microAmount': 500000000 - }, - # Aim for at least 3000 clicks. - 'volumeGoalType': 'MAXIMIZE_CLICKS', - 'volumeTargetValue': 3000, - # Start the performance target today, and run it for the next 90 - # days. - 'startDate': datetime.datetime.now().strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(90)).strftime('%Y%m%d') - } - } - }] - - cgpt = cgpt_service.mutate(operations)['value'][0] - - # Display the results. - print ('Campaign performance target with ID "%d" was added for campaign ' - 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201705/campaign_management/add_campaign_labels.py b/examples/adwords/v201705/campaign_management/add_campaign_labels.py deleted file mode 100755 index 1aa8deee..00000000 --- a/examples/adwords/v201705/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201705') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201705/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201705/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index 30076238..00000000 --- a/examples/adwords/v201705/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,428 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201705') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201705') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding an ExpandedTextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new ExpandedTextAd for - each of the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once - # you've added targeting and the ads are ready to serve. - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201705') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201705/campaign_management/add_draft.py b/examples/adwords/v201705/campaign_management/add_draft.py deleted file mode 100755 index 3fd211dc..00000000 --- a/examples/adwords/v201705/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201705') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201705') - - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index 9485c4ae..00000000 --- a/examples/adwords/v201705/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,258 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to incrementally upload keywords. - -Uses the BatchJobService and BatchJobHelper to incrementally upload operations. -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201705') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201705') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201705') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201705') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the the BatchJob will - be checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201705/campaign_management/add_trial.py b/examples/adwords/v201705/campaign_management/add_trial.py deleted file mode 100755 index 580f0c91..00000000 --- a/examples/adwords/v201705/campaign_management/add_trial.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201705') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201705') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 651a882e..00000000 --- a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'PolicySummary'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CombinedApprovalStatus', - 'operator': 'EQUALS', - 'values': 'DISAPPROVED' - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - disapproved_count = 0 - - # Display results. - while more_pages: - page = ad_group_ad_service.get(selector) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % (ad['ad']['id'])) - - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName']) - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index ca889dae..00000000 --- a/examples/adwords/v201705/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', - version='v201705') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, PolicySummary ' - 'WHERE AdGroupId = %s AND CombinedApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % ad_group_id) - more_pages = True - disapproved_count = 0 - offset = 0 - - # Display results. - while more_pages: - page = ad_group_ad_service.query(query + ' LIMIT %s, %s' % ( - offset, PAGE_SIZE)) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % (ad['ad']['id'])) - - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName']) - - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 6273a119..00000000 --- a/examples/adwords/v201705/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201705') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id "%s", name "%s", and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201705/campaign_management/graduate_trial.py b/examples/adwords/v201705/campaign_management/graduate_trial.py deleted file mode 100755 index da3fb1e0..00000000 --- a/examples/adwords/v201705/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201705') - budget_service = client.GetService('BudgetService', version='v201705') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201705/campaign_management/set_ad_parameters.py b/examples/adwords/v201705/campaign_management/set_ad_parameters.py deleted file mode 100755 index 5b1857af..00000000 --- a/examples/adwords/v201705/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - ad_param_service = client.GetService('AdParamService', version='v201705') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id "%s" was successfully added to an ad group with ' - 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text "%s" was successfully set for criterion ' - 'with id "%s" and ad group id "%s".' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index f2242439..00000000 --- a/examples/adwords/v201705/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201705') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' - 'was updated with bid modifier "%s".' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201705/campaign_management/validate_text_ad.py b/examples/adwords/v201705/campaign_management/validate_text_ad.py deleted file mode 100755 index ee011c84..00000000 --- a/examples/adwords/v201705/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -No objects will be created, but exceptions will still be returned. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Construct operations to add an expanded text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'] - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for all astronauts in orbit', - 'finalUrls': ['http://www.example.com'], - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with "%s".' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/error_handling/__init__.py b/examples/adwords/v201705/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201705/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201705/error_handling/handle_partial_failures.py b/examples/adwords/v201705/error_handling/handle_partial_failures.py deleted file mode 100755 index 34f215ae..00000000 --- a/examples/adwords/v201705/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201705') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id "%s", ' - 'criterion id "%s", text "%s", and match type "%s" was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - if (first_field_path_element and - first_field_path_element['field'] == 'operations' and - first_field_path_element['index']): - operation_index = first_field_path_element['index'] - - adgroup_criterion = operations[operation_index]['operand'] - - print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' - 'a failure for the following reason: %s.' - % (adgroup_criterion['adGroupId'], - adgroup_criterion['criterion']['text'], - error['errorString'])) - else: - print ('A failure has occured for the following reasons: %s\n' - % error['errorString']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/error_handling/handle_policy_violation_error.py b/examples/adwords/v201705/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 2ed702db..00000000 --- a/examples/adwords/v201705/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201705') - - # Create expanded text ad that violates an exemptable policy. - exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise!!!', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - # Create text ad that violates a non-exemptable policy. - non_exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise with too long of a headline.', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - operations = [exemptable_expanded_text_ad_operation, - non_exemptable_expanded_text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - # Get the index of the failed operation from the error's field path - # elements. - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - # If the operation index is not present on the first error field path - # element, then there's no way to determine which operation to remove, - # so simply throw the exception. - if (not (first_field_path_element - and first_field_path_element['field'] == 'operations' - and first_field_path_element['index'])): - raise e - - operation_index = first_field_path_element['index'] - index = int(operation_index[0]) - operation = operations[index] - if not HandleAPIError(error, operation): - # Set non-exemptable operation to None to mark for deletion. - print ('Removing operation with non-exemptable error at index %s.' - % operation_index) - operations[index] = None - - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is "%s".' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -def HandleAPIError(error, operation): - """Makes an exemption for exemptable PolicyViolationErrors. - - Args: - error: the error associated with the given operation. - operation: the operation associated with the given error. - - Returns: - A boolean that is True if the given error was an exemptable - PolicyViolationError; otherwise, returns False. - """ - is_exemptable = False - - # Determine if the operation can be resubmitted with an exemption request. - if error['ApiError.Type'] == 'PolicyViolationError': - expanded_text_ad = operation['operand']['ad'] - is_exemptable = (error['isExemptable'] if 'isExemptable' in error else - False) - print ('Ad with headline "%s - %s" violated %s policy "%s".' % - (expanded_text_ad['headlinePart1'], - expanded_text_ad['headlinePart2'], - 'exemptable' if is_exemptable else 'non-exemptable', - error['externalPolicyName'])) - - if is_exemptable: - # Add exemption request to the operation. - print ('Adding exemption request for policy name "%s" on text "%s".' - % (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({'key': error['key']}) - - return is_exemptable - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/extensions/__init__.py b/examples/adwords/v201705/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201705/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201705/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201705/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 8f7db504..00000000 --- a/examples/adwords/v201705/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201705').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201705') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201705/extensions/add_prices.py b/examples/adwords/v201705/extensions/add_prices.py deleted file mode 100755 index 77106251..00000000 --- a/examples/adwords/v201705/extensions/add_prices.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a price extension and associates it with an account. - -Campaign targeting is also set usin the specified campaign ID. To get campaigns, -run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -MICROS_PER_DOLLAR = 1000000 - - -def main(client, campaign_id): - # Initialize appropriate service. - customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201705') - - # To create a price extension, at least three table rows are needed. - table_rows = [ - CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', - 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', - final_mobile_url='http://m.example.com/scrubs'), - CreatePriceTableRow('Hair Cuts', 'Once a month', - 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url='http://m.example.com/haircuts'), - CreatePriceTableRow('Skin Care Package', 'Four times a month', - 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url=( - 'http://m.example.com/skincarepackage')) - ] - - # Create the price extension feed item. - customer_extension_setting = { - 'extensionType': 'PRICE', - 'extensionSetting': { - 'extensions': [{ - 'priceExtensionType': 'SERVICES', - 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', - 'language': 'en', - 'campaignTargeting': { - 'TargetingCampaignId': campaign_id - }, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': 'SATURDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 22, - 'endMinute': 'ZERO' - }, - { - 'dayOfWeek': 'SUNDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 18, - 'endMinute': 'ZERO' - } - ] - }, - 'tableRows': table_rows, - # Price qualifier is optional. - 'priceQualifier': 'FROM', - 'xsi_type': 'PriceFeedItem' - }] - } - } - - # Create an operation to add the feed. - operations = [{ - 'operator': 'ADD', - 'operand': customer_extension_setting - }] - - # Add the price extension. - response = customer_extension_setting_service.mutate(operations) - - # Print the results. - if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit, final_mobile_url=None): - """Helper function to generate a single row of a price table. - - Args: - header: A str containing the header text of this row. - description: A str description of this row in the price table. - final_url: A str containing the final URL after all cross domain redirects. - price_in_micros: An int indicating the price of the given currency in - micros. - currency_code: A str indicating the currency code being used. - price_unit: A str enum indicating the price unit for this row. - final_mobile_url: A str containing the final mobile URL after all cross - domain redirects. - - Returns: - A dictionary containing the contents of the generated price table row. - """ - table_row = { - 'header': header, - 'description': description, - 'finalUrls': {'urls': [final_url]}, - 'price': { - 'money': { - 'microAmount': price_in_micros, - }, - 'currencyCode': currency_code - }, - 'priceUnit': price_unit, - 'xsi_type': 'PriceTableRow' - } - - if final_mobile_url: - table_row['finalMobileUrls'] = { - 'urls': [final_mobile_url] - } - - return table_row - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/extensions/add_site_links.py b/examples/adwords/v201705/extensions/add_site_links.py deleted file mode 100755 index 44842a60..00000000 --- a/examples/adwords/v201705/extensions/add_site_links.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201705') - customer_service = client.GetService('CustomerService', version='v201705') - # Find the matching customer and its time zone. The getCustomers method will - # return a single Customer object corresponding to the configured - # clientCustomerId. - customer = customer_service.getCustomers()[0] - customer_tz = timezone(customer['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840}, - # Restrict targeting only to people physically within the United States. - # Otherwise, this could also show to people interested in the United - # States, but not physically located there. - 'geoTargetingRestriction': { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/extensions/add_site_links_using_feeds.py b/examples/adwords/v201705/extensions/add_site_links_using_feeds.py deleted file mode 100755 index a645e66a..00000000 --- a/examples/adwords/v201705/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_2_TEXT = '3' -PLACEHOLDER_FIELD_LINE_3_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201705') - feed_item_service = client.GetService('FeedItemService', version='v201705') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201705') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201705') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 2 Description'}, - {'type': 'STRING', 'name': 'Line 3 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_2_feed_attribute_id = feed['attributes'][2]['id'] - line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name "%s" and ID "%s" was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - sitelinks_data['line3FeedId'] = line_3_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line2': 'Home line 2', 'line3': 'Home line 3'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line2': 'Support line 2', 'line3': 'Support line 3'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line2': 'Products line 2', 'line3': 'Products line 3'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'stringValue': item['line3'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - feed_item['geoTargetingRestriction'] = { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/migration/__init__.py b/examples/adwords/v201705/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201705/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201705/migration/migrate_to_extension_settings.py b/examples/adwords/v201705/migration/migrate_to_extension_settings.py deleted file mode 100755 index 1aa8b180..00000000 --- a/examples/adwords/v201705/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201705') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201705') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201705') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201705') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201705') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201705') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201705') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/misc/__init__.py b/examples/adwords/v201705/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201705/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201705/misc/get_all_images_and_videos.py b/examples/adwords/v201705/misc/get_all_images_and_videos.py deleted file mode 100755 index 7e72ffcd..00000000 --- a/examples/adwords/v201705/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201705') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id "%s" was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/misc/upload_image.py b/examples/adwords/v201705/misc/upload_image.py deleted file mode 100755 index 3895aeb0..00000000 --- a/examples/adwords/v201705/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201705') - - with open(image_filename, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201705/misc/upload_media_bundle.py b/examples/adwords/v201705/misc/upload_media_bundle.py deleted file mode 100755 index 61856b0f..00000000 --- a/examples/adwords/v201705/misc/upload_media_bundle.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201705') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/optimization/__init__.py b/examples/adwords/v201705/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201705/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201705/optimization/estimate_keyword_traffic.py b/examples/adwords/v201705/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 69cc319f..00000000 --- a/examples/adwords/v201705/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201705') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201705/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index 6d9f7c8d..00000000 --- a/examples/adwords/v201705/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201705') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index 8649c9de..00000000 --- a/examples/adwords/v201705/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201705') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id "%s", criterion id ' - '"%s", start date "%s", end date "%s", with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201705/optimization/get_keyword_ideas.py b/examples/adwords/v201705/optimization/get_keyword_ideas.py deleted file mode 100755 index fb8c12a1..00000000 --- a/examples/adwords/v201705/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201705') - - # Construct selector object and retrieve related keywords. - offset = 0 - selector = { - 'searchParameters': [ - { - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }, - { - # Language setting (optional). - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }, - { - # Network search parameter (optional) - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - } - ], - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS', - 'requestedAttributeTypes': ['KEYWORD_TEXT', 'SEARCH_VOLUME', - 'CATEGORY_PRODUCTS_AND_SERVICES'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr(attribute['value'], 'value', - '0') - print ('Keyword with "%s" text and average monthly search volume ' - '"%s" was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/__init__.py b/examples/adwords/v201705/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201705/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201705/remarketing/add_audience.py b/examples/adwords/v201705/remarketing/add_audience.py deleted file mode 100755 index 35ca1007..00000000 --- a/examples/adwords/v201705/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201705') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201705') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name "%s" and ID "%s" was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/add_conversion_tracker.py b/examples/adwords/v201705/remarketing/add_conversion_tracker.py deleted file mode 100755 index 94a5aa11..00000000 --- a/examples/adwords/v201705/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201705') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" and snippet \n"%s"\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/add_crm_based_user_list.py b/examples/adwords/v201705/remarketing/add_crm_based_user_list.py deleted file mode 100755 index ab80f224..00000000 --- a/examples/adwords/v201705/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201705') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - - emails = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] - - # Optional: AddressInfo is only accessible to whitelisted customers. - # If you are not on the whitelist, you should leave this code commented out. - # members.append({ - # 'addressInfo': { - # 'hashedFirstName': NormalizeAndSHA256('John'), - # 'hashedLastName': NormalizeAndSHA256('Doe'), - # 'countryCode': 'US', - # 'zipCode': '10001' - # } - # }) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'membersList': members - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def NormalizeAndSHA256(s): - """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. - - Args: - s: The string to perform this operation on. - - Returns: - A normalized and SHA-256 hashed string. - """ - return hashlib.sha256(s.strip().lower()).hexdigest() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201705/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index dce0078b..00000000 --- a/examples/adwords/v201705/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201705') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords knows how to apply the - # rules. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ], - # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF - # means 'at least one item in each rule item group must match', and DNF - # means 'at least one entire rule item group must match'. - # DateSpecificRuleUserList only supports DNF. You can also omit the rule - # type altogether to default to DNF. - 'ruleType': 'DNF' - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule, - # Optional: Set the populationStatus to REQUESTED to include past users in - # the user list. - 'prepopulationStatus': 'REQUESTED' - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201705/remarketing/upload_offline_call_conversions.py deleted file mode 100755 index 3c234236..00000000 --- a/examples/adwords/v201705/remarketing/upload_offline_call_conversions.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for calls related to ads in your account. - -To set up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CALLER_ID = 'INSERT_CALLER_ID_HERE' -# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats -# For time zones, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -CALL_START_TIME = 'INSERT_CALL_START_TIME' -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, caller_id, call_start_time, conversion_name, conversion_time, - conversion_value): - # Initialize appropriate services. - occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201705') - - # Associate offline call conversions with the existing named conversion - # tracker. If this tracker was newly created, it may be a few hours before it - # can accept conversions. - feed = { - 'callerId': caller_id, - 'callStartTime': call_start_time, - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - } - - occ_operations = [{'operator': 'ADD', 'operand': feed}] - - occ_response = occ_feed_service.mutate(occ_operations) - values = occ_response['value'] - - if values: - for occ_feed in values: - print ('Uploaded offline call conversion value of "%s" for caller ID ' - '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) - else: - print 'No offline call conversions were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, - CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201705/remarketing/upload_offline_conversions.py b/examples/adwords/v201705/remarketing/upload_offline_conversions.py deleted file mode 100755 index 79c99fa7..00000000 --- a/examples/adwords/v201705/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_tracker.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201705') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of "%s" for Google Click ID ' - '"%s" to "%s".' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201705/reporting/__init__.py b/examples/adwords/v201705/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201705/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index a879538c..00000000 --- a/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201705') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_selector.py deleted file mode 100755 index b3d789cf..00000000 --- a/examples/adwords/v201705/reporting/download_criteria_report_as_stream_with_selector.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201705') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 4de147f4..00000000 --- a/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201705') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_selector.py deleted file mode 100755 index 42c70e5b..00000000 --- a/examples/adwords/v201705/reporting/download_criteria_report_as_string_with_selector.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201705') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201705/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index a9ddc13f..00000000 --- a/examples/adwords/v201705/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import sys -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201705') - - # Create report query. - report_query = ('SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, ' - 'FinalUrls, Impressions, Clicks, Cost ' - 'FROM CRITERIA_PERFORMANCE_REPORT ' - 'WHERE Status IN [ENABLED, PAUSED] ' - 'DURING LAST_7_DAYS') - - # You can provide a file object to write the output to. For this - # demonstration we use sys.stdout to write the report to the screen. - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', sys.stdout, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201705/reporting/download_criteria_report_with_selector.py deleted file mode 100755 index e1fda28d..00000000 --- a/examples/adwords/v201705/reporting/download_criteria_report_with_selector.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201705') - - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201705/reporting/get_report_fields.py b/examples/adwords/v201705/reporting/get_report_fields.py deleted file mode 100755 index b93d0518..00000000 --- a/examples/adwords/v201705/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201705') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type "%s" contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201705/reporting/parallel_report_download.py b/examples/adwords/v201705/reporting/parallel_report_download.py deleted file mode 100755 index 0a4578fd..00000000 --- a/examples/adwords/v201705/reporting/parallel_report_download.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import logging -import multiprocessing -from Queue import Empty -import time -import googleads - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - client: An AdWordsClient instance. - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201705') - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = self._DownloadReport(customer_id) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - - Raises: - Exception: if no CustomerIds could be found. - - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201705') - - offset = 0 - - # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201705/shopping/__init__.py b/examples/adwords/v201705/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201705/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201705/shopping/add_product_partition_tree.py b/examples/adwords/v201705/shopping/add_product_partition_tree.py deleted file mode 100755 index d2fda6e1..00000000 --- a/examples/adwords/v201705/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,279 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201705') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201705/shopping/add_product_scope.py b/examples/adwords/v201705/shopping/add_product_scope.py deleted file mode 100755 index 47642112..00000000 --- a/examples/adwords/v201705/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201705') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201705/shopping/add_shopping_campaign.py b/examples/adwords/v201705/shopping/add_shopping_campaign.py deleted file mode 100755 index d3539331..00000000 --- a/examples/adwords/v201705/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -# If set to true, a default partition will be created. If running the -# add_product_partition_tree.py example right after this example, make -# sure this stays set to false. -CREATE_DEFAULT_PARTITION = False -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id, create_default_partition): - campaign_service = client.GetService('CampaignService', version='v201705') - ad_group_service = client.GetService('AdGroupService', version='v201705') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201705') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - ad_group = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': ad_group - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] - ad_group_id = ad_group['id'] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (ad_group['name'], ad_group_id)) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': ad_group_id, - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - - if create_default_partition: - CreateDefaultPartition(client, ad_group_id) - - -def CreateDefaultPartition(client, ad_group_id): - """Creates a default partition. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID for an ad group. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201705') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Make sure that caseValue and parentCriterionId are left unspecified. - # This makes this partition as generic as possible to use as a - # fallback when others don't match. - 'criterion': { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - }, - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 500000 - } - }] - } - } - }] - - ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' - % (ad_group_criterion['criterion']['id'], - ad_group_criterion['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py deleted file mode 100755 index e9ad6e50..00000000 --- a/examples/adwords/v201705/shopping/add_shopping_campaign_for_showcase_ads.py +++ /dev/null @@ -1,402 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds a Shopping campaign for Showcase ads. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import base64 -import uuid - -from googleads import adwords -from suds import WebFault - - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' -COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - # Note: Showcase ads require either ManualCpc or EnhancedCpc in the - # campaign's BiddingStrategyConfiguration. - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, budget_id, merchant_id, expanded_image_filepath, - collapsed_image_filepath): - try: - # Create the Shopping Campaign - campaign = CreateShoppingCampaign(client, budget_id, merchant_id) - - # Create the AdGroup - adgroup = CreateAdGroup(client, campaign['id']) - - # Create a Showcase Ad - CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath) - - product_partition_tree = CreateProductPartition(client, adgroup['id']) - print 'Final tree:\n%s' % product_partition_tree - except WebFault: - print 'Failed to create shopping campaign for showcase ads.' - raise - - -def CreateShoppingCampaign(client, budget_id, merchant_id): - """Creates a shopping campaign with the given budget and merchant IDs. - - Args: - client: an AdWordsClient instance. - budget_id: the str ID of the budget to be associated with the shopping - campaign. - merchant_id: the str ID of the merchant account to be associated with the - shopping campaign. - - Returns: - The created Shopping Campaign as a sudsobject. - """ - campaign_service = client.GetService('CampaignService', 'v201705') - - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - return campaign - - -def CreateAdGroup(client, campaign_id): - """Creates an AdGroup for the given shopping campaign ID. - - Args: - client: an AdWordsClient instance. - campaign_id: the str ID of a shopping campaign. - - Returns: - The created AdGroup as a sudsobject. - """ - ad_group_service = client.GetService('AdGroupService', 'v201705') - - adgroup = { - # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS - 'adGroupType': 'SHOPPING_SHOWCASE_ADS', - 'campaignId': campaign_id, - 'name': 'AdGroup #%s' % uuid.uuid4(), - # REQUIRED: Set the ad group's bidding strategy configuration. - 'biddingStrategyConfiguration': { - # Showcase ads require either ManualCpc or EnhancedCpc. - 'biddingStrategyType': 'MANUAL_CPC', - # Optional: Set the bids - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 100000 - } - }] - } - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - return adgroup - - -def CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath): - """Creates a showcase add for the given AdGroup with the given images. - - Args: - client: an AdWordsClient instance. - adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. - expanded_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's expandedImage. - collapsed_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's collapsedImage. - - Returns: - The created Showcase Ad as a sudsobject. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201705') - - showcase_ad = { - 'adGroupId': adgroup['id'], - 'ad': { - 'xsi_type': 'ShowcaseAd', - 'Ad.Type': 'ShowcaseAd', - # Required: set the ad's name, final URLs, and display URL. - 'name': 'Showcase ad #%s' % uuid.uuid4(), - 'finalUrls': 'http://example.com/showcase', - 'displayUrl': 'example.com', - # Required: Set the ad's expanded image. - 'expandedImage': { - 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] - }, - # Optional: Set the collapsed image. - 'collapsedImage': { - 'mediaId': - UploadImage(client, collapsed_image_filepath)['mediaId'] - } - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': showcase_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] - - print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] - - return showcase_ad - - -def UploadImage(client, filepath): - """Uploads a .jpg image with the given filepath via the AdWords MediaService. - - Args: - client: an AdWordsClient instance. - filepath: a str filepath to the .jpg file to be uploaded. - - Returns: - The created Image as a sudsobject. - """ - media_service = client.GetService('MediaService', 'v201705') - - with open(filepath, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - image = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - - image = media_service.upload(image)[0] - - return image - - -def CreateProductPartition(client, adgroup_id): - """Creates a ProductPartition tree for the given AdGroup ID. - - Args: - client: an AdWordsClient instance. - adgroup_id: a str AdGroup ID. - - Returns: - The ProductPartition tree as a sudsobject. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - 'v201705') - helper = ProductPartitionHelper(adgroup_id) - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition) - helper.CreateUnit(root, used_product_canonical_condition) - helper.CreateUnit(root, other_product_canonical_condition) - - result = ad_group_criterion_service.mutate(helper.operations) - return result['value'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, - COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201705/shopping/get_product_category_taxonomy.py b/examples/adwords/v201705/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 23495f92..00000000 --- a/examples/adwords/v201705/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201705') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/targeting/__init__.py b/examples/adwords/v201705/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201705/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index df684e8b..00000000 --- a/examples/adwords/v201705/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201705') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s", criterion id "%s", ' - 'and type "%s" was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 83db7f2a..00000000 --- a/examples/adwords/v201705/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201705') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type "%s" was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201705/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201705/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 14ad4409..00000000 --- a/examples/adwords/v201705/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201705') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index 9e782b93..00000000 --- a/examples/adwords/v201705/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201705') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name "%s" and ID "%s" was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name "%s", ID "%s", and country code "%s" was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201705/targeting/lookup_location.py b/examples/adwords/v201705/targeting/lookup_location.py deleted file mode 100755 index aca2b820..00000000 --- a/examples/adwords/v201705/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201705') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term "%s" returned the location "%s" of type "%s"' - ' with parent locations "%s", reach "%s" and id "%s" (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/__init__.py b/examples/adwords/v201708/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201708/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201708/account_management/__init__.py b/examples/adwords/v201708/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201708/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201708/account_management/accept_service_link.py b/examples/adwords/v201708/account_management/accept_service_link.py deleted file mode 100755 index c560727b..00000000 --- a/examples/adwords/v201708/account_management/accept_service_link.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' - - -def main(client, service_link_id): - # Initialize appropriate service. - customer_service = client.GetService( - 'CustomerService', version='v201708') - - # Create the operation to set the status to ACTIVE. - operations = [{ - 'operator': 'SET', - 'operand': { - 'serviceLinkId': service_link_id, - 'serviceType': 'MERCHANT_CENTER', - 'linkStatus': 'ACTIVE', - } - }] - - # Update the service link. - mutated_service_links = customer_service.mutateServiceLinks(operations) - - # Display results. - for mutated_service_link in mutated_service_links: - print ('Service link with service link ID "%s", type "%s" was updated ' - 'to status: "%s".' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201708/account_management/create_account.py b/examples/adwords/v201708/account_management/create_account.py deleted file mode 100755 index 4fb7e68e..00000000 --- a/examples/adwords/v201708/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201708') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID "%s" was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/account_management/get_account_changes.py b/examples/adwords/v201708/account_management/get_account_changes.py deleted file mode 100755 index 47d547b6..00000000 --- a/examples/adwords/v201708/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201708') - campaign_service = client.GetService('CampaignService', version='v201708') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id "%s" has change status "%s".' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id "%s" has change status "%s".' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/account_management/get_account_hierarchy.py b/examples/adwords/v201708/account_management/get_account_hierarchy.py deleted file mode 100755 index 42a1f7c6..00000000 --- a/examples/adwords/v201708/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201708') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/__init__.py b/examples/adwords/v201708/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201708/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201708/advanced_operations/add_ad_customizer.py b/examples/adwords/v201708/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 2c72f3bf..00000000 --- a/examples/adwords/v201708/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates ExpandedTextAds that use ad customizations for specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no ExpandedTextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201708') - - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'headlinePart2': 'Only {=%s.Price}' % feed_name, - 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': expanded_text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID "%s", type "%s", and status "%s".' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201708') - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name "%s" and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201708') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - operation = { - 'operator': 'ADD', - 'operand': feed_item - } - - return operation - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201708/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201708/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index c04e39f7..00000000 --- a/examples/adwords/v201708/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201708') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index f720e51c..00000000 --- a/examples/adwords/v201708/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Optionally, you may specify a landscape image. The image needs to be in a - # BASE64 encoded form. Here we download a demo image and encode it for this - # ad. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) - .decode('utf-8')) - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - }, - { - 'name': 'landscapeImage', - 'fieldMedia': { - 'xsi_type': 'Image', - 'data': image_data - }, - 'type': 'IMAGE' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201708/advanced_operations/add_dynamic_page_feed.py deleted file mode 100755 index ed3f853f..00000000 --- a/examples/adwords/v201708/advanced_operations/add_dynamic_page_feed.py +++ /dev/null @@ -1,295 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. - -To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -from collections import namedtuple -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - -# Used to keep track of DSA page feed details. -_DSAFeedDetails = namedtuple( - '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) -# ID that corresponds to the labels. -DSA_LABEL_FIELD_ID = 2 -# The criterion type to be used for DSA page feeds. -DSA_PAGE_FEED_CRITERION_TYPE = 61 -DSA_PAGE_URL_LABEL = 'discounts' -# ID that corresponds to the page URLs. -DSA_PAGE_URLS_FIELD_ID = 1 - - -def main(client, campaign_id, ad_group_id): - # Get the page feed details. This code example creates a new feed, but you can - # fetch and re-use an existing feed. - feed_details = _CreateFeed(client) - _CreateFeedMapping(client, feed_details) - _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) - - # Associate the page feed with the campaign. - _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) - - # Optional: Target web pages matching the feed's label in the ad group. - _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) - - print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id - - -def _CreateFeed(client): - """Creates the feed for DSA page URLs. - - Args: - client: an AdWordsClient instance. - - Returns: - A _DSAFeedDetails instance containing details about the created feed. - """ - # Get the FeedService. - feed_service = client.GetService('FeedService', version='v201708') - - # Create operation. - operation = { - # Create the feed. - 'operand': { - 'name': 'DSA Feed %s' % uuid.uuid4(), - # Create attributes. - 'attributes': [ - {'type': 'URL_LIST', 'name': 'Page URL'}, - {'type': 'STRING_LIST', 'name': 'Label'} - ], - 'origin': 'USER' - }, - 'operator': 'ADD' - } - - # Add the feed. - feed = feed_service.mutate([operation])['value'][0] - return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], - feed['attributes'][1]['id']) - - -def _CreateFeedMapping(client, feed_details): - """Creates the feed mapping for DSA page feeds. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - """ - # Get the FeedMappingService. - feed_mapping_service = client.GetService('FeedMappingService', - version='v201708') - - # Create the operation. - operation = { - # Create the feed mapping. - 'operand': { - 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, - 'feedId': feed_details.feed_id, - # Map the feedAttributeIds to the fieldId constants. - 'attributeFieldMappings': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'fieldId': DSA_PAGE_URLS_FIELD_ID - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'fieldId': DSA_LABEL_FIELD_ID - } - ] - }, - 'operator': 'ADD' - } - - # Add the feed mapping. - feed_mapping_service.mutate([operation]) - - -def _CreateFeedItems(client, feed_details, label_name): - """Creates the page URLs in the DSA page feed. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - label_name: a str containing the page feed URL label. - """ - # Get the FeedItemService. - feed_item_service = client.GetService('FeedItemService', version='v201708') - - # Optional: You can include the {feeditem} valuetrack parameter to track which - # page feed items lead to each click. - urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', - 'http://www.example.com/discounts/hotel-deals?id={feeditem}', - 'http://www.example.com/discounts/flight-deals?id={feeditem}') - - # Create the operation. - operations = [{ - # Create the feed item. - 'operand': { - 'feedId': feed_details.feed_id, - 'attributeValues': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'stringValues': [url] - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'stringValues': [label_name] - } - ] - }, - 'operator': 'ADD' - } for url in urls] - - # Add the feed item. - feed_item_service.mutate(operations) - - -def _UpdateCampaignDSASetting(client, campaign_id, feed_id): - """Updates the campaign DSA setting to DSA pagefeeds. - - Args: - client: an AdWordsClient instance. - campaign_id: a str Campaign ID. - feed_id: a str page Feed ID. - - Raises: - ValueError: If the given campaign is found not to be a dynamic search ad - campaign. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201708') - - selector = { - 'fields': ['Id', 'Settings'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [campaign_id] - }] - } - - response = campaign_service.get(selector) - - if response['totalNumEntries']: - campaign = response['entries'][0] - else: - raise ValueError('No campaign with ID "%d" exists.' % campaign_id) - - if not campaign['settings']: - raise ValueError('This is not a DSA campaign.') - - dsa_setting = None - - campaign_settings = campaign['settings'] - - for setting in campaign_settings: - if setting['Setting.Type'] == 'DynamicSearchAdsSetting': - dsa_setting = setting - break - - if dsa_setting is None: - raise ValueError('This is not a DSA campaign.') - - dsa_setting['pageFeed'] = { - 'feedIds': [feed_id] - } - - # Optional: Specify whether only the supplied URLs should be used with your - # Dynamic Search Ads. - dsa_setting['useSuppliedUrlsOnly'] = True - - operation = { - 'operand': { - 'id': campaign_id, - 'settings': campaign_settings - }, - 'operator': 'SET' - } - - campaign_service.mutate([operation]) - print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( - campaign_id, feed_id) - - -def _AddDSATargeting(client, ad_group_id, label_name): - """Set custom targeting for the page feed URLs based on a list of labels. - - Args: - client: an AdWordsClient instance. - ad_group_id: a str AdGroup ID. - label_name: a str label name. - - Returns: - A suds.sudsobject.Object representing the newly created webpage criterion. - """ - # Get the AdGroupCriterionService. - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201708') - - # Create the operation. - operation = { - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Test criterion', - # Add a condition for label=specified_label_name. - 'conditions': [{ - 'operand': 'CUSTOM_LABEL', - 'argument': label_name - }], - } - }, - # Set a custom bid for this criterion - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 1500000 - } - }] - } - }, - 'operator': 'ADD' - } - - criterion = ad_group_criterion_service.mutate([operation])['value'][0] - print 'Web page criterion with ID "%d" and status "%s" was created.' % ( - criterion['criterion']['id'], criterion['userStatus']) - return criterion - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201708/advanced_operations/add_dynamic_search_ads_campaign.py deleted file mode 100755 index 42b61fb1..00000000 --- a/examples/adwords/v201708/advanced_operations/add_dynamic_search_ads_campaign.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Dynamic Search Ads campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - budget = _CreateBudget(client) - campaign_id = _CreateCampaign(client, budget) - ad_group_id = _CreateAdGroup(client, campaign_id) - _CreateExpandedDSA(client, ad_group_id) - _AddWebPageCriteria(client, ad_group_id) - - print 'Dynamic Search Ads campaign setup is complete.' - - -def _CreateBudget(client): - """Creates the budget. - - Args: - client: an AdWordsClient instance. - - Returns: - a suds.sudsobject.Object representation of the created budget. - """ - budget_service = client.GetService('BudgetService', version='v201708') - - # Create the campaign budget - operation = { - 'operand': { - 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), - 'deliveryMethod': 'STANDARD', - 'amount': { - 'microAmount': 500000 - } - }, - 'operator': 'ADD' - } - - budget = budget_service.mutate([operation])['value'][0] - - print 'Budget with ID "%d" and name "%s" was created.' % ( - budget['budgetId'], budget['name']) - - return budget - - -def _CreateCampaign(client, budget): - """Creates the campaign. - - Args: - client: an AdWordsClient instance. - budget: a suds.sudsobject.Object representation of a created budget. - - Returns: - An integer campaign ID. - """ - campaign_service = client.GetService('CampaignService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # prevent the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'budget': budget, - # Required: Set the campaign's Dynamic Search Ad settings. - 'settings': [{ - 'xsi_type': 'DynamicSearchAdsSetting', - # Required: Set the domain name and language. - 'domainName': 'example.com', - 'languageCode': 'en' - }], - # Optional: Set the start date. - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - # Optional: Set the end date. - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - }] - - campaign = campaign_service.mutate(operations)['value'][0] - campaign_id = campaign['id'] - - print 'Campaign with ID "%d" and name "%s" was added.' % ( - campaign_id, campaign['name']) - - return campaign_id - - -def _CreateAdGroup(client, campaign_id): - """Creates an ad group. - - Args: - client: an AdWordsClient instance. - campaign_id: an integer campaign ID. - - Returns: - An integer ad group ID. - """ - ad_group_service = client.GetService('AdGroupService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'adGroupType': 'SEARCH_DYNAMIC_ADS', - 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '3000000' - }, - }] - } - } - }] - - ad_group = ad_group_service.mutate(operations)['value'][0] - ad_group_id = ad_group['id'] - - print 'Ad group with ID "%d" and name "%s" was created.' % ( - ad_group_id, ad_group['name']) - - return ad_group_id - - -def _CreateExpandedDSA(client, ad_group_id): - """Creates the expanded Dynamic Search Ad. - - Args: - client: an AdwordsClient instance. - ad_group_id: an integer ID of the ad group in which the DSA is added. - """ - # Get the AdGroupAdService. - ad_group_ad_service = client.GetService('AdGroupAdService') - - # Create the operation - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - # Create the expanded dynamic search ad. This ad will have its - # headline and final URL auto-generated at serving time according to - # domain name specific information provided by DynamicSearchAdsSetting - # at the campaign level. - 'ad': { - 'xsi_type': 'ExpandedDynamicSearchAd', - # Set the ad description. - 'description': 'Buy your tickets now!' - }, - # Optional: Set the status. - 'status': 'PAUSED', - } - }] - - # Create the ad. - ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] - - # Display the results. - print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' - 'added' % (ad['id'], ad['description'])) - - -def _AddWebPageCriteria(client, ad_group_id): - """Adds a web page criterion to target Dynamic Search Ads. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID of the ad group the criteria is being added to. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201708') - - operations = [{ - 'operator': 'ADD', - # Create biddable ad group criterion. - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion for special offers for children. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Special offers for children.', - 'conditions': [ - { - 'operand': 'URL', - 'argument': '/marscruise/children' - }, - { - 'operand': 'PAGE_TITLE', - 'argument': 'Special Offer' - } - ] - } - }, - 'userStatus': 'PAUSED', - # Optional: set a custom bid. - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000L - } - }] - } - } - }] - - criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( - criterion['criterion']['id'], criterion['adGroupId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201708/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py deleted file mode 100755 index 763963b8..00000000 --- a/examples/adwords/v201708/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Create the expanded text ad - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - 'trackingUrlTemplate': ('http://tracker.example.com/?season={_season}' - '&promocode={_promocode}&u={lpurl}'), - 'urlCustomParameters': { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - }, - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': expanded_text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_html5_ad.py b/examples/adwords/v201708/advanced_operations/add_html5_ad.py deleted file mode 100755 index a9fc5973..00000000 --- a/examples/adwords/v201708/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index 626532b6..00000000 --- a/examples/adwords/v201708/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import base64 -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - media_service = client.GetService('MediaService', version='v201708') - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - - try: - # Create marketing image. - marketing_image = _CreateImage(media_service, opener, - 'https://goo.gl/3b9Wfh') - - # Create square marketing image. - square_marketing_image = _CreateImage(media_service, opener, - 'https://goo.gl/mtt54n') - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': marketing_image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'], - # Optional: Set a square marketing image to the ad. - 'squareMarketingImage': { - 'mediaId': square_marketing_image['mediaId'] - }, - # Optional: Set call-to-action text. - 'callToActionText': 'Shop Now', - # Optional: Set dynamic display ad settings, composed of - # landscape logo image, promotion text, and price prefix. - 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( - media_service, opener), - # Whitelisted accounts only: Set color settings using - # hexadecimal numbers. - # Set allowFlexibleColor to False if you want your ads to render - # by always using your colors strictly. - # 'mainColor': '#0000ff', - # 'accentColor': '#ffff00', - # 'allowFlexibleColor': False - # Whitelisted accounts only: Set the format setting that the ad - # will be served in. - # 'formatSetting': 'NON_NATIVE' - - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -def _CreateImage(media_service, opener, url): - """Creates an image and uploads it to the server. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - url: a str URL used to load image data. - - Returns: - The image that was successfully uploaded. - """ - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - return media_service.upload(image)[0] - - -def _CreateDynamicDisplayAdSettings(media_service, opener): - """Creates settings for dynamic display ad. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - - Returns: - The dynamic display ad settings. - """ - image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') - - logo = { - 'type': 'IMAGE', - 'mediaId': image['mediaId'], - 'xsi_type': 'Image' - } - - dynamic_settings = { - 'landscapeLogoImage': logo, - 'pricePrefix': 'as low as', - 'promoText': 'Free shipping!', - 'xsi_type': 'DynamicSettings', - } - - return dynamic_settings - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py deleted file mode 100755 index f0d9f1f5..00000000 --- a/examples/adwords/v201708/advanced_operations/add_universal_app_campaign.py +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Universal App campaign. - -To get campaigns, run get_campaigns.py. To upload image assets for this -campaign, run upload_image.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201708') - - budget_id = CreateBudget(client) - - # Create the Universal App campaign. - universal_app_campaign = { - 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'MULTI_CHANNEL', - 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', - # Set the campaign's bidding strategy. Universal app campaigns only - # support TARGET_CPA bidding strategy. - 'biddingStrategyConfiguration': { - # Set the target CPA to $1 / app install. - 'biddingScheme': { - 'xsi_type': 'TargetCpaBiddingScheme', - 'targetCpa': { - 'microAmount': '1000000' - } - }, - 'biddingStrategyType': 'TARGET_CPA' - }, - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - - universal_app_campaign['settings'] = [ - # Set the campaign's assets and ad text ideas. These values will - # be used to generate ads. - { - 'xsi_type': 'UniversalAppCampaignSetting', - 'appId': 'com.labpixies.colordrips', - 'description1': 'A cool puzzle game', - 'description2': 'Remove connected blocks', - 'description3': '3 difficulty levels', - 'description4': '4 colorful fun skins', - # Optional: You can set up to 20 image assets for your campaign. - # See upload_image.py for an example on how to upload images. - # - # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] - } - ] - - # Optimize this campaign for getting new users for your app. - universal_app_campaign_setting = universal_app_campaign['settings'][0] - universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( - 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') - - # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, - # then also specify your in-app conversion types so AdWords can focus your - # campaign on people who are most likely to complete the corresponding in-app - # actions. - # - # Conversions type IDs can be retrieved using ConversionTrackerService.get. - # universal_app_campaign['selectiveOptimization'] = { - # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] - # } - - # Optional: Set the campaign settings for Advanced location options. - universal_app_campaign['settings'].append({ - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - }) - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': universal_app_campaign - }] - - campaigns = campaign_service.mutate(operations)['value'] - - # Display results. - if campaigns: - for campaign in campaigns: - print ('Universal App Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - # Optional: Set the campaign's location and language targeting. No other - # targeting criteria can be used for Universal App campaigns. - SetCampaignTargetingCriteria(client, campaign) - else: - print 'No Universal App campaigns were added.' - - -def CreateBudget(client): - """Creates a budget and returns its budgetId. - - Args: - client: An AdWordsClient instance. - - Returns: - An int budgetId for the created Budget. - """ - budget_service = client.GetService('BudgetService', version='v201708') - - # Create a budget. - budget = { - 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': False - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Create the budget and return its ID. - budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - - return budget_id - - -def SetCampaignTargetingCriteria(client, campaign): - """Sets targeting criteria for the given campaign. - - Args: - client: An AdWordsClient instance. - campaign: A suds object representing the campaign we wish to attach - targeting criteria. - """ - campaign_criterion_service = client.GetService('CampaignCriterionService') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - criteria = [ - { - 'xsi_type': 'Location', - 'id': 21137 # California - }, - { - 'xsi_type': 'Location', - 'id': 2484 # Mexico - }, - { - 'xsi_type': 'Language', - 'id': 1000 # English - }, - { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - ] - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign['id'], - 'criterion': criterion - } - } for criterion in criteria] - - response = campaign_criterion_service.mutate(operations) - - if response and 'value' in response: - # Display the added campaign targets. - for criterion in response['value']: - print ('Campaign criteria of type "%s" and id "%s" was added.' - % (criterion['criterion']['type'], - criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201708/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 9cdaf1d0..00000000 --- a/examples/adwords/v201708/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201708') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201708') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201708') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201708/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index bb7f53ef..00000000 --- a/examples/adwords/v201708/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201708') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201708') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201708/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index f1221628..00000000 --- a/examples/adwords/v201708/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201708') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201708/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 35adfb5b..00000000 --- a/examples/adwords/v201708/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201708') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201708') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201708') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201708/basic_operations/__init__.py b/examples/adwords/v201708/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201708/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201708/basic_operations/add_ad_groups.py b/examples/adwords/v201708/basic_operations/add_ad_groups.py deleted file mode 100755 index 7511bdc1..00000000 --- a/examples/adwords/v201708/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201708') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/basic_operations/add_campaigns.py b/examples/adwords/v201708/basic_operations/add_campaigns.py deleted file mode 100755 index 164225cf..00000000 --- a/examples/adwords/v201708/basic_operations/add_campaigns.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201708') - budget_service = client.GetService('BudgetService', version='v201708') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'adServingOptimizationStatus': 'ROTATE', - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201708/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index 2a329428..00000000 --- a/examples/adwords/v201708/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/add_keywords.py b/examples/adwords/v201708/basic_operations/add_keywords.py deleted file mode 100755 index 481823f6..00000000 --- a/examples/adwords/v201708/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201708') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id "%s", criterion id ' - '"%s", text "%s", and match type "%s" was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/get_ad_groups.py b/examples/adwords/v201708/basic_operations/get_ad_groups.py deleted file mode 100755 index 027236ed..00000000 --- a/examples/adwords/v201708/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201708') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name "%s", id "%s" and status "%s" was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/basic_operations/get_campaigns.py b/examples/adwords/v201708/basic_operations/get_campaigns.py deleted file mode 100755 index 712cce1c..00000000 --- a/examples/adwords/v201708/basic_operations/get_campaigns.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201708') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 53555067..00000000 --- a/examples/adwords/v201708/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201708') - - # Construct query and get all campaigns. - offset = 0 - query = 'SELECT Id, Name, Status ORDER BY Name' - - more_pages = True - while more_pages: - page = campaign_service.query(query + ' LIMIT %s, %s' % (offset, PAGE_SIZE)) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201708/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index 06e08c6d..00000000 --- a/examples/adwords/v201708/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/get_keywords.py b/examples/adwords/v201708/basic_operations/get_keywords.py deleted file mode 100755 index 94ee1727..00000000 --- a/examples/adwords/v201708/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201708') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID "%s", type "%s", text "%s", and match type ' - '"%s" was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/pause_ad.py b/examples/adwords/v201708/basic_operations/pause_ad.py deleted file mode 100755 index 4c58dd12..00000000 --- a/examples/adwords/v201708/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id "%s" was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201708/basic_operations/remove_ad.py b/examples/adwords/v201708/basic_operations/remove_ad.py deleted file mode 100755 index cdb787ab..00000000 --- a/examples/adwords/v201708/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id "%s" and type "%s" was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201708/basic_operations/remove_ad_group.py b/examples/adwords/v201708/basic_operations/remove_ad_group.py deleted file mode 100755 index 862eea48..00000000 --- a/examples/adwords/v201708/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201708') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name "%s" and id "%s" was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/remove_campaign.py b/examples/adwords/v201708/basic_operations/remove_campaign.py deleted file mode 100755 index 97ada6f4..00000000 --- a/examples/adwords/v201708/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201708') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name "%s" and id "%s" was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/basic_operations/remove_keyword.py b/examples/adwords/v201708/basic_operations/remove_keyword.py deleted file mode 100755 index 7ff28025..00000000 --- a/examples/adwords/v201708/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201708') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id "%s", criterion id "%s", ' - 'and type "%s" was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201708/basic_operations/update_ad_group.py b/examples/adwords/v201708/basic_operations/update_ad_group.py deleted file mode 100755 index a69959f3..00000000 --- a/examples/adwords/v201708/basic_operations/update_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201708') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was updated.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/basic_operations/update_campaign.py b/examples/adwords/v201708/basic_operations/update_campaign.py deleted file mode 100755 index 1d76f345..00000000 --- a/examples/adwords/v201708/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201708') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/basic_operations/update_keyword.py b/examples/adwords/v201708/basic_operations/update_keyword.py deleted file mode 100755 index b0110dbe..00000000 --- a/examples/adwords/v201708/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201708') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id "%s" and criterion id ' - '"%s" currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: "%s", value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201708/campaign_management/__init__.py b/examples/adwords/v201708/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201708/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201708/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201708/campaign_management/add_campaign_groups_and_performance_targets.py deleted file mode 100755 index 08224ca5..00000000 --- a/examples/adwords/v201708/campaign_management/add_campaign_groups_and_performance_targets.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a campaign group and sets a performance target for it. - -To get campaigns, run get_campaigns.py. To download reports, run -download_criteria_report_with_awql.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id1, campaign_id2): - campaign_group_id = _CreateCampaignGroup(client) - _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) - _CreatePerformanceTarget(client, campaign_group_id) - print 'Campaign group and its performance target were setup successfully.' - - -def _CreateCampaignGroup(client): - """Create a campaign group. - - Args: - client: an AdWordsClient instance. - - Returns: - The integer ID of the created campaign group. - """ - # Get the CampaignGroupService. - campaign_group_service = client.GetService('CampaignGroupService', - version='v201708') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the campaign group. - 'operand': { - 'name': 'Mars campaign group #%d' % uuid.uuid4() - } - }] - - campaign_group = campaign_group_service.mutate(operations)['value'][0] - campaign_group_id = campaign_group['id'] - - # Display the results. - print 'Campaign group with ID "%d" and name "%s" was created.' % ( - campaign_group_id, campaign_group['name']) - - return campaign_group_id - - -def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): - """Adds multiple campaigns to a campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - campaign_ids: a list of integer IDs for campaigns. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201708') - - # Create the operations. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'campaignGroupId': campaign_group_id - } - } for campaign_id in campaign_ids] - - campaign_service.mutate(operations) - - # Display the results. - print ('The following campaign IDs were added to the campaign group with ID ' - '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) - - -def _CreatePerformanceTarget(client, campaign_group_id): - """Creates a performance target for the campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - """ - # Get the CampaignGroupPerformanceTargetService. - cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', - version='v201708') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the performance target. - 'operand': { - 'campaignGroupId': campaign_group_id, - 'performanceTarget': { - # Keep the CPC for the campaigns < $3. - 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', - 'efficiencyTargetValue': 3000000, - # Keep the maximum spend under $50. - 'spendTargetType': 'MAXIMUM', - 'spendTarget': { - 'microAmount': 500000000 - }, - # Aim for at least 3000 clicks. - 'volumeGoalType': 'MAXIMIZE_CLICKS', - 'volumeTargetValue': 3000, - # Start the performance target today, and run it for the next 90 - # days. - 'startDate': datetime.datetime.now().strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(90)).strftime('%Y%m%d') - } - } - }] - - cgpt = cgpt_service.mutate(operations)['value'][0] - - # Display the results. - print ('Campaign performance target with ID "%d" was added for campaign ' - 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201708/campaign_management/add_campaign_labels.py b/examples/adwords/v201708/campaign_management/add_campaign_labels.py deleted file mode 100755 index 5d1424af..00000000 --- a/examples/adwords/v201708/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201708') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201708/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201708/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index b4c0fc2d..00000000 --- a/examples/adwords/v201708/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,428 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201708') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201708') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding an ExpandedTextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new ExpandedTextAd for - each of the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once - # you've added targeting and the ads are ready to serve. - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201708') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201708/campaign_management/add_draft.py b/examples/adwords/v201708/campaign_management/add_draft.py deleted file mode 100755 index 2b41bcf7..00000000 --- a/examples/adwords/v201708/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201708') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201708') - - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index 3a07fca4..00000000 --- a/examples/adwords/v201708/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,258 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to incrementally upload keywords. - -Uses the BatchJobService and BatchJobHelper to incrementally upload operations. -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201708') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201708') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201708') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201708') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201708/campaign_management/add_trial.py b/examples/adwords/v201708/campaign_management/add_trial.py deleted file mode 100755 index caef4dc3..00000000 --- a/examples/adwords/v201708/campaign_management/add_trial.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201708') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201708') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201708/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201708/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index 89f5d5de..00000000 --- a/examples/adwords/v201708/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'PolicySummary'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CombinedApprovalStatus', - 'operator': 'EQUALS', - 'values': 'DISAPPROVED' - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - disapproved_count = 0 - - # Display results. - while more_pages: - page = ad_group_ad_service.get(selector) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % (ad['ad']['id'])) - - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName']) - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201708/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 8f2f59fc..00000000 --- a/examples/adwords/v201708/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', - version='v201708') - - # Construct query and get all ads for a given campaign. - query = ('SELECT Id, PolicySummary ' - 'WHERE AdGroupId = %s AND CombinedApprovalStatus = DISAPPROVED ' - 'ORDER BY Id' % ad_group_id) - more_pages = True - disapproved_count = 0 - offset = 0 - - # Display results. - while more_pages: - page = ad_group_ad_service.query(query + ' LIMIT %s, %s' % ( - offset, PAGE_SIZE)) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % (ad['ad']['id'])) - - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName']) - - offset += PAGE_SIZE - more_pages = offset < int(page['totalNumEntries']) - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 81b30437..00000000 --- a/examples/adwords/v201708/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201708') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id "%s", name "%s", and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201708/campaign_management/graduate_trial.py b/examples/adwords/v201708/campaign_management/graduate_trial.py deleted file mode 100755 index 13238d5e..00000000 --- a/examples/adwords/v201708/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201708') - budget_service = client.GetService('BudgetService', version='v201708') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201708/campaign_management/set_ad_parameters.py b/examples/adwords/v201708/campaign_management/set_ad_parameters.py deleted file mode 100755 index 8817b1d2..00000000 --- a/examples/adwords/v201708/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - ad_param_service = client.GetService('AdParamService', version='v201708') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id "%s" was successfully added to an ad group with ' - 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text "%s" was successfully set for criterion ' - 'with id "%s" and ad group id "%s".' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201708/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201708/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index a669602a..00000000 --- a/examples/adwords/v201708/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201708') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' - 'was updated with bid modifier "%s".' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201708/campaign_management/validate_text_ad.py b/examples/adwords/v201708/campaign_management/validate_text_ad.py deleted file mode 100755 index ab35e92e..00000000 --- a/examples/adwords/v201708/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -No objects will be created, but exceptions will still be returned. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import suds - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Construct operations to add an expanded text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'] - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for all astronauts in orbit', - 'finalUrls': ['http://www.example.com'], - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except suds.WebFault, e: - print 'Validation correctly failed with "%s".' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/error_handling/__init__.py b/examples/adwords/v201708/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201708/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201708/error_handling/handle_partial_failures.py b/examples/adwords/v201708/error_handling/handle_partial_failures.py deleted file mode 100755 index ded63de8..00000000 --- a/examples/adwords/v201708/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201708') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id "%s", ' - 'criterion id "%s", text "%s", and match type "%s" was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - if (first_field_path_element and - first_field_path_element['field'] == 'operations' and - first_field_path_element['index']): - operation_index = first_field_path_element['index'] - - adgroup_criterion = operations[operation_index]['operand'] - - print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' - 'a failure for the following reason: %s.' - % (adgroup_criterion['adGroupId'], - adgroup_criterion['criterion']['text'], - error['errorString'])) - else: - print ('A failure has occurred for the following reasons: %s\n' - % error['errorString']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/error_handling/handle_policy_violation_error.py b/examples/adwords/v201708/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 8d845823..00000000 --- a/examples/adwords/v201708/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import suds - -from googleads import adwords - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201708') - - # Create expanded text ad that violates an exemptable policy. - exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise!!!', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - # Create text ad that violates a non-exemptable policy. - non_exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise with too long of a headline.', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - operations = [exemptable_expanded_text_ad_operation, - non_exemptable_expanded_text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - # Get the index of the failed operation from the error's field path - # elements. - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - # If the operation index is not present on the first error field path - # element, then there's no way to determine which operation to remove, - # so simply throw the exception. - if (not (first_field_path_element - and first_field_path_element['field'] == 'operations' - and first_field_path_element['index'])): - raise e - - operation_index = first_field_path_element['index'] - index = int(operation_index[0]) - operation = operations[index] - if not HandleAPIError(error, operation): - # Set non-exemptable operation to None to mark for deletion. - print ('Removing operation with non-exemptable error at index %s.' - % operation_index) - operations[index] = None - - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is "%s".' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -def HandleAPIError(error, operation): - """Makes an exemption for exemptable PolicyViolationErrors. - - Args: - error: the error associated with the given operation. - operation: the operation associated with the given error. - - Returns: - A boolean that is True if the given error was an exemptable - PolicyViolationError; otherwise, returns False. - """ - is_exemptable = False - - # Determine if the operation can be resubmitted with an exemption request. - if error['ApiError.Type'] == 'PolicyViolationError': - expanded_text_ad = operation['operand']['ad'] - is_exemptable = (error['isExemptable'] if 'isExemptable' in error else - False) - print ('Ad with headline "%s - %s" violated %s policy "%s".' % - (expanded_text_ad['headlinePart1'], - expanded_text_ad['headlinePart2'], - 'exemptable' if is_exemptable else 'non-exemptable', - error['externalPolicyName'])) - - if is_exemptable: - # Add exemption request to the operation. - print ('Adding exemption request for policy name "%s" on text "%s".' - % (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({'key': error['key']}) - - return is_exemptable - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/extensions/__init__.py b/examples/adwords/v201708/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201708/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201708/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201708/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 4fb7c6d4..00000000 --- a/examples/adwords/v201708/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -# Import appropriate modules from the client library. -import suds - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201708').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201708') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except suds.WebFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201708/extensions/add_prices.py b/examples/adwords/v201708/extensions/add_prices.py deleted file mode 100755 index 6a1a71cf..00000000 --- a/examples/adwords/v201708/extensions/add_prices.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a price extension and associates it with an account. - -Campaign targeting is also set usin the specified campaign ID. To get campaigns, -run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -MICROS_PER_DOLLAR = 1000000 - - -def main(client, campaign_id): - # Initialize appropriate service. - customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201708') - - # To create a price extension, at least three table rows are needed. - table_rows = [ - CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', - 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', - final_mobile_url='http://m.example.com/scrubs'), - CreatePriceTableRow('Hair Cuts', 'Once a month', - 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url='http://m.example.com/haircuts'), - CreatePriceTableRow('Skin Care Package', 'Four times a month', - 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url=( - 'http://m.example.com/skincarepackage')) - ] - - # Create the price extension feed item. - customer_extension_setting = { - 'extensionType': 'PRICE', - 'extensionSetting': { - 'extensions': [{ - 'priceExtensionType': 'SERVICES', - 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', - 'language': 'en', - 'campaignTargeting': { - 'TargetingCampaignId': campaign_id - }, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': 'SATURDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 22, - 'endMinute': 'ZERO' - }, - { - 'dayOfWeek': 'SUNDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 18, - 'endMinute': 'ZERO' - } - ] - }, - 'tableRows': table_rows, - # Price qualifier is optional. - 'priceQualifier': 'FROM', - 'xsi_type': 'PriceFeedItem' - }] - } - } - - # Create an operation to add the feed. - operations = [{ - 'operator': 'ADD', - 'operand': customer_extension_setting - }] - - # Add the price extension. - response = customer_extension_setting_service.mutate(operations) - - # Print the results. - if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit, final_mobile_url=None): - """Helper function to generate a single row of a price table. - - Args: - header: A str containing the header text of this row. - description: A str description of this row in the price table. - final_url: A str containing the final URL after all cross domain redirects. - price_in_micros: An int indicating the price of the given currency in - micros. - currency_code: A str indicating the currency code being used. - price_unit: A str enum indicating the price unit for this row. - final_mobile_url: A str containing the final mobile URL after all cross - domain redirects. - - Returns: - A dictionary containing the contents of the generated price table row. - """ - table_row = { - 'header': header, - 'description': description, - 'finalUrls': {'urls': [final_url]}, - 'price': { - 'money': { - 'microAmount': price_in_micros, - }, - 'currencyCode': currency_code - }, - 'priceUnit': price_unit, - 'xsi_type': 'PriceTableRow' - } - - if final_mobile_url: - table_row['finalMobileUrls'] = { - 'urls': [final_mobile_url] - } - - return table_row - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/extensions/add_site_links.py b/examples/adwords/v201708/extensions/add_site_links.py deleted file mode 100755 index 0fa4f94e..00000000 --- a/examples/adwords/v201708/extensions/add_site_links.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201708') - customer_service = client.GetService('CustomerService', version='v201708') - # Find the matching customer and its time zone. The getCustomers method will - # return a single Customer object corresponding to the configured - # clientCustomerId. - customer = customer_service.getCustomers()[0] - customer_tz = timezone(customer['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840}, - # Restrict targeting only to people physically within the United States. - # Otherwise, this could also show to people interested in the United - # States, but not physically located there. - 'geoTargetingRestriction': { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/extensions/add_site_links_using_feeds.py b/examples/adwords/v201708/extensions/add_site_links_using_feeds.py deleted file mode 100755 index e144bfda..00000000 --- a/examples/adwords/v201708/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_2_TEXT = '3' -PLACEHOLDER_FIELD_LINE_3_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201708') - feed_item_service = client.GetService('FeedItemService', version='v201708') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201708') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201708') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 2 Description'}, - {'type': 'STRING', 'name': 'Line 3 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_2_feed_attribute_id = feed['attributes'][2]['id'] - line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name "%s" and ID "%s" was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - sitelinks_data['line3FeedId'] = line_3_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line2': 'Home line 2', 'line3': 'Home line 3'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line2': 'Support line 2', 'line3': 'Support line 3'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line2': 'Products line 2', 'line3': 'Products line 3'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'stringValue': item['line3'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - feed_item['geoTargetingRestriction'] = { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/migration/__init__.py b/examples/adwords/v201708/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201708/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201708/migration/migrate_to_extension_settings.py b/examples/adwords/v201708/migration/migrate_to_extension_settings.py deleted file mode 100755 index 4ea8d97c..00000000 --- a/examples/adwords/v201708/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201708') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201708') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201708') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201708') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201708') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201708') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201708') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/misc/__init__.py b/examples/adwords/v201708/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201708/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201708/misc/get_all_images_and_videos.py b/examples/adwords/v201708/misc/get_all_images_and_videos.py deleted file mode 100755 index 6c0a60a9..00000000 --- a/examples/adwords/v201708/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201708') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id "%s" was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/misc/upload_image.py b/examples/adwords/v201708/misc/upload_image.py deleted file mode 100755 index 3fbb2ea4..00000000 --- a/examples/adwords/v201708/misc/upload_image.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import base64 -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201708') - - with open(image_filename, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201708/misc/upload_media_bundle.py b/examples/adwords/v201708/misc/upload_media_bundle.py deleted file mode 100755 index 33d32a35..00000000 --- a/examples/adwords/v201708/misc/upload_media_bundle.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import base64 -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201708') - # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetBase64EncodedHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/optimization/__init__.py b/examples/adwords/v201708/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201708/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201708/optimization/estimate_keyword_traffic.py b/examples/adwords/v201708/optimization/estimate_keyword_traffic.py deleted file mode 100755 index df1df334..00000000 --- a/examples/adwords/v201708/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201708') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201708/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index 666df862..00000000 --- a/examples/adwords/v201708/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201708') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201708/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index 96f989da..00000000 --- a/examples/adwords/v201708/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201708') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ] - } - bid_landscapes = data_service.getCriterionBidLandscape(selector) - - # Display results. - if 'entries' in bid_landscapes: - for bid_landscape in bid_landscapes['entries']: - if bid_landscape['BidLandscape.Type'] == 'CriterionBidLandscape': - print ('Criterion bid landscape with ad group id "%s", criterion id ' - '"%s", start date "%s", end date "%s", with landscape ' - 'points was found:' - % (bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - else: - print 'No bid landscapes found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201708/optimization/get_keyword_ideas.py b/examples/adwords/v201708/optimization/get_keyword_ideas.py deleted file mode 100755 index 2d195173..00000000 --- a/examples/adwords/v201708/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id=None): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201708') - - # Construct selector object and retrieve related keywords. - selector = { - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS' - } - - selector['requestedAttributeTypes'] = [ - 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] - - offset = 0 - selector['paging'] = { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - - selector['searchParameters'] = [{ - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }] - - # Language setting (optional). - selector['searchParameters'].append({ - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }) - - # Network search parameter (optional) - selector['searchParameters'].append({ - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - }) - - # Use an existing ad group to generate ideas (optional) - if ad_group_id is not None: - selector['searchParameters'].append({ - 'xsi_type': 'SeedAdGroupIdSearchParameter', - 'adGroupId': ad_group_id - }) - - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr( - attribute['value'], 'value', '0') - print ('Keyword with "%s" text and average monthly search volume ' - '"%s" was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201708/remarketing/__init__.py b/examples/adwords/v201708/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201708/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201708/remarketing/add_audience.py b/examples/adwords/v201708/remarketing/add_audience.py deleted file mode 100755 index 7d4c4236..00000000 --- a/examples/adwords/v201708/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201708') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201708') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name "%s" and ID "%s" was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/add_conversion_tracker.py b/examples/adwords/v201708/remarketing/add_conversion_tracker.py deleted file mode 100755 index d9fedbac..00000000 --- a/examples/adwords/v201708/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201708') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" and snippet \n"%s"\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/add_conversion_trackers.py b/examples/adwords/v201708/remarketing/add_conversion_trackers.py deleted file mode 100755 index dfce443b..00000000 --- a/examples/adwords/v201708/remarketing/add_conversion_trackers.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds AdWords conversion trackers. - -Adds an AdWords conversion tracker and an upload conversion tracker. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201708') - - # Create an AdWords conversion tracker. - adwords_conversion_tracker = { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'name': 'Upload Conversion #%s' % uuid.uuid4(), - # Optional fields. - # Set an appropriate category. This will be set to DEFAULT if not - # specified. - 'category': 'LEAD', - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90', - # Set the default currency code to use for conversions that do - # not specify a conversion currency. This must be an ISO 4217 3-character - # code such as "EUR" or "USD". - # If this field is not set, AdWords will use the account's currency. - 'defaultRevenueCurrencyCode': 'EUR', - # Set the default revenue value to use for conversions that do not specify - # a converison value. Note that this value should NOT be in micros. - 'defaultRevenueValue': '2.50', - # To upload fractional conversion credits, mark the upload conversion as - # externally attributed. To learn more about importing externally - # attributed conversions, see: - # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions - # 'isExternallyAttributed': 'true' - } - - # Construct operations. - operations = [{ - 'operator': 'ADD', - 'operand': conversion_tracker - } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] - - # Add the conversions. - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - if (conversion_tracker['ConversionTracker.Type'] - is 'AdWordsConversionTracker'): - print ('Conversion tracker with ID "%d", name "%s", status "%s" ' - 'and category "%s" and snippet \n"%s"\n was added.' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - else: - print ('Conversion with ID "%d", name "%s", status "%s", and category ' - '"%s" was added.' - % (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/add_crm_based_user_list.py b/examples/adwords/v201708/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 75501240..00000000 --- a/examples/adwords/v201708/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201708') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - - emails = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] - - # Optional: AddressInfo is only accessible to whitelisted customers. - # If you are not on the whitelist, you should leave this code commented out. - # members.append({ - # 'addressInfo': { - # 'hashedFirstName': NormalizeAndSHA256('John'), - # 'hashedLastName': NormalizeAndSHA256('Doe'), - # 'countryCode': 'US', - # 'zipCode': '10001' - # } - # }) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'membersList': members - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def NormalizeAndSHA256(s): - """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. - - Args: - s: The string to perform this operation on. - - Returns: - A normalized and SHA-256 hashed string. - """ - return hashlib.sha256(s.strip().lower()).hexdigest() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201708/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index c85dbd85..00000000 --- a/examples/adwords/v201708/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201708') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords knows how to apply the - # rules. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ], - # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF - # means 'at least one item in each rule item group must match', and DNF - # means 'at least one entire rule item group must match'. - # DateSpecificRuleUserList only supports DNF. You can also omit the rule - # type altogether to default to DNF. - 'ruleType': 'DNF' - } - - # Third and fourth rule item groups. - # Visitors of a page who visited another page. - site1_rule_item = { - 'StringRuleItem': { - 'key': {'name': 'url__'}, - 'op': 'EQUALS', - 'value': 'example.com/example1' - } - } - site2_rule_item = { - 'StringRuleItem': { - 'key': {'name': 'url__'}, - 'op': 'EQUALS', - 'value': 'example.com/example2' - } - } - - # Create two rules to show that a visitor browsed two sites. - user_visited_site1_rule = { - 'groups': [{ - 'items': [site1_rule_item] - }] - } - - user_visited_site2_rule = { - 'groups': [{ - 'items': [site2_rule_item] - }] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule, - # Optional: Set the populationStatus to REQUESTED to include past users in - # the user list. - 'prepopulationStatus': 'REQUESTED' - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create the user list for "Visitors of a page who did visit another page". - # To create a user list for "Visitors of a page who did not visit another - # page", change the ruleOperator from AND to AND_NOT. - combined_user_list = { - 'xsi_type': 'CombinedRuleUserList', - 'name': 'Combined rule user lst create at ${creation_time}', - 'description': 'Users who visited two sites.', - 'leftOperand': user_visited_site1_rule, - 'rightOperand': user_visited_site2_rule, - 'ruleOperator': 'AND' - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list, - combined_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201708/remarketing/upload_offline_call_conversions.py deleted file mode 100755 index eacb7fb1..00000000 --- a/examples/adwords/v201708/remarketing/upload_offline_call_conversions.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for calls related to ads in your account. - -To set up a conversion tracker, run the add_conversion_trackers.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CALLER_ID = 'INSERT_CALLER_ID_HERE' -# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats -# For time zones, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -CALL_START_TIME = 'INSERT_CALL_START_TIME' -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, caller_id, call_start_time, conversion_name, conversion_time, - conversion_value): - # Initialize appropriate services. - occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201708') - - # Associate offline call conversions with the existing named conversion - # tracker. If this tracker was newly created, it may be a few hours before it - # can accept conversions. - feed = { - 'callerId': caller_id, - 'callStartTime': call_start_time, - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - } - - occ_operations = [{'operator': 'ADD', 'operand': feed}] - - occ_response = occ_feed_service.mutate(occ_operations) - values = occ_response['value'] - - if values: - for occ_feed in values: - print ('Uploaded offline call conversion value of "%s" for caller ID ' - '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) - else: - print 'No offline call conversions were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, - CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201708/remarketing/upload_offline_conversions.py b/examples/adwords/v201708/remarketing/upload_offline_conversions.py deleted file mode 100755 index f7d7743a..00000000 --- a/examples/adwords/v201708/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_trackers.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201708') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id, - # Optional: To upload fractional conversion credits, set the external - # attribution model and credit. To use this feature, your conversion - # tracker should be marked as externally attributed. To learn more about - # importing externally attributed conversins, see: - # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions - # 'externalAttributionCredit': 0.3, - # 'externalAttributionModel': 'Linear' - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of "%s" for Google Click ID ' - '"%s" to "%s".' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201708/remarketing/upload_offline_data.py b/examples/adwords/v201708/remarketing/upload_offline_data.py deleted file mode 100755 index 12e6513d..00000000 --- a/examples/adwords/v201708/remarketing/upload_offline_data.py +++ /dev/null @@ -1,199 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 shows how to upload offline data for store sales transactions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import datetime -import hashlib - -from googleads import adwords -import pytz - - -_DT_FORMAT = '%Y%m%d %H%M%S' -# User identifier types whose values must be hashed. -_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', - 'HASHED_LAST_NAME', 'HASHED_PHONE') -# The timezone to be used in this example. For valid timezone IDs, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -_TIMEZONE = pytz.timezone('America/New_York') -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Insert email addresses below for creating user identifiers. -EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] -# The external upload ID can be any number that you use to keep track of your -# uploads. -EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' -# Advertiser upload time to partner. -# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, -# see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' -# Indicates the version of the bridge map. -BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' -# The ID of the third party uploading the transaction feed. -PARTNER_ID = 'INSERT_PARTNER_ID_HERE' - - -def main(client, conversion_name, external_upload_id, email_addresses, - advertiser_upload_time, bridge_map_version_id, partner_id): - # Initialize appropriate services. - offline_data_upload_service = client.GetService( - 'OfflineDataUploadService', version='v201708') - - # Create the first offline data for upload. - # This transaction occurred 7 days ago with an amount of $200 USD. - transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - - datetime.timedelta(days=7)) - offline_data_1 = { - 'StoreSalesTransaction': { - 'userIdentifiers': [ - _CreateUserIdentifier(identifier_type='HASHED_EMAIL', - value=email_addresses[0]), - _CreateUserIdentifier(identifier_type='STATE', value='New York') - ], - 'transactionTime': _GetFormattedDateTime(transaction_time_1), - 'transactionAmount': { - 'currencyCode': 'USD', - 'money': { - 'microAmount': 200000000 - } - }, - 'conversionName': conversion_name - } - } - - # Create the second offline data for upload. - # This transaction occurred 14 days ago with amount of 450 EUR. - transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - - datetime.timedelta(days=14)) - offline_data_2 = { - 'StoreSalesTransaction': { - 'userIdentifiers': [ - _CreateUserIdentifier(identifier_type='HASHED_EMAIL', - value=email_addresses[1]), - _CreateUserIdentifier(identifier_type='STATE', value='California') - ], - 'transactionTime': _GetFormattedDateTime(transaction_time_2), - 'transactionAmount': { - 'currencyCode': 'EUR', - 'money': { - 'microAmount': 450000000 - } - }, - 'conversionName': conversion_name - } - } - - # Set the metadata of this upload. - upload_metadata = { - 'StoreSalesUploadCommonMetadata': { - 'xsi_type': 'ThirdPartyUploadMetadata', - 'loyaltyRate': 1.0, - 'transactionUploadRate': 1.0, - 'advertiserUploadTime': advertiser_upload_time, - 'validTransactionRate': 1.0, - 'partnerMatchRate': 1.0, - 'partnerUploadRate': 1.0, - 'bridgeMapVersionId': bridge_map_version_id, - 'partnerId': partner_id - } - } - - # Create offline data upload - offline_data_upload = { - 'externalUploadId': external_upload_id, - 'offlineDataList': [offline_data_1, offline_data_2], - # Set the type of this upload. - 'uploadType': 'STORE_SALES_UPLOAD_THIRD_PARTY', - 'uploadMetadata': upload_metadata - } - - # Create an offline data upload operation. - operations = [{ - 'operator': 'ADD', - 'operand': offline_data_upload - }] - - # Upload offline data on the server and print the result. - result = offline_data_upload_service.mutate(operations) - offline_data_upload = result['value'][0] - - print ('Uploaded offline data with external upload ID "%d" and upload status ' - '"%s".' % (offline_data_upload['externalUploadId'], - offline_data_upload['uploadStatus'])) - - # Print any partial data errors from the response. The order of the partial - # data errors list is the same as the uploaded offline data list in the - # request. - for i, partial_data_error in enumerate( - offline_data_upload['partialDataErrors']): - # If a partial error occurred for this offline data, print the error. Note - # that non-errors for a given offline data would be set to None. - if partial_data_error: - print ('Found a partial error for offline data #%d with error string: %s' - % (i, partial_data_error['errorString'])) - - -def _CreateUserIdentifier(identifier_type=None, value=None): - """Creates a user identifier from the specified type and value. - - Args: - identifier_type: a str specifying the type of user identifier. - value: a str value of the identifier; to be hashed using SHA-256 if needed. - - Returns: - A dict specifying a user identifier, with a value hashed using SHA-256 if - needed. - """ - if identifier_type in _HASHED_IDENTIFIER_TYPES: - # If the user identifier type is a hashed type, normalize and hash the - # value. - value = hashlib.sha256(value.strip().lower()).hexdigest() - - user_identifier = { - 'userIdentifierType': identifier_type, - 'value': value - } - - return user_identifier - - -def _GetFormattedDateTime(dt): - """Formats the given datetime and timezone for use with AdWords. - - Args: - dt: a datetime instance. - - Returns: - A str representation of the datetime in the correct format for AdWords. - """ - return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, EMAIL_ADDRESSES, - ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201708/reporting/__init__.py b/examples/adwords/v201708/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201708/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index aab506db..00000000 --- a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys - -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201708') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_selector.py deleted file mode 100755 index ebdb879a..00000000 --- a/examples/adwords/v201708/reporting/download_criteria_report_as_stream_with_selector.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import StringIO -import sys -from googleads import adwords - - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201708') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 820add34..00000000 --- a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201708') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_selector.py deleted file mode 100755 index 652102c1..00000000 --- a/examples/adwords/v201708/reporting/download_criteria_report_as_string_with_selector.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201708') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 6913de8a..00000000 --- a/examples/adwords/v201708/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import sys -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201708') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - # You can provide a file object to write the output to. For this - # demonstration we use sys.stdout to write the report to the screen. - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', sys.stdout, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201708/reporting/download_criteria_report_with_selector.py deleted file mode 100755 index 86216732..00000000 --- a/examples/adwords/v201708/reporting/download_criteria_report_with_selector.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import logging -import sys -from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201708') - - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201708/reporting/get_report_fields.py b/examples/adwords/v201708/reporting/get_report_fields.py deleted file mode 100755 index 11db3d53..00000000 --- a/examples/adwords/v201708/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201708') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type "%s" contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201708/reporting/parallel_report_download.py b/examples/adwords/v201708/reporting/parallel_report_download.py deleted file mode 100755 index 5672e238..00000000 --- a/examples/adwords/v201708/reporting/parallel_report_download.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import logging -import multiprocessing -from Queue import Empty -import time -import googleads - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - client: An AdWordsClient instance. - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201708') - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = self._DownloadReport(customer_id) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - - Raises: - Exception: if no CustomerIds could be found. - - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201708') - - offset = 0 - - # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201708/shopping/__init__.py b/examples/adwords/v201708/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201708/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201708/shopping/add_product_partition_tree.py b/examples/adwords/v201708/shopping/add_product_partition_tree.py deleted file mode 100755 index 3009ad9e..00000000 --- a/examples/adwords/v201708/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,280 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - self.adgroup_id = adgroup_id - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201708') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201708/shopping/add_product_scope.py b/examples/adwords/v201708/shopping/add_product_scope.py deleted file mode 100755 index 802ff956..00000000 --- a/examples/adwords/v201708/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201708') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201708/shopping/add_shopping_campaign.py b/examples/adwords/v201708/shopping/add_shopping_campaign.py deleted file mode 100755 index a43290a9..00000000 --- a/examples/adwords/v201708/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -# If set to true, a default partition will be created. If running the -# add_product_partition_tree.py example right after this example, make -# sure this stays set to false. -CREATE_DEFAULT_PARTITION = False -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id, create_default_partition): - campaign_service = client.GetService('CampaignService', version='v201708') - ad_group_service = client.GetService('AdGroupService', version='v201708') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201708') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - ad_group = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': ad_group - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] - ad_group_id = ad_group['id'] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (ad_group['name'], ad_group_id)) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': ad_group_id, - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - - if create_default_partition: - CreateDefaultPartition(client, ad_group_id) - - -def CreateDefaultPartition(client, ad_group_id): - """Creates a default partition. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID for an ad group. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201708') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Make sure that caseValue and parentCriterionId are left unspecified. - # This makes this partition as generic as possible to use as a - # fallback when others don't match. - 'criterion': { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - }, - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 500000 - } - }] - } - } - }] - - ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' - % (ad_group_criterion['criterion']['id'], - ad_group_criterion['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py deleted file mode 100755 index bf9ee8a9..00000000 --- a/examples/adwords/v201708/shopping/add_shopping_campaign_for_showcase_ads.py +++ /dev/null @@ -1,402 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds a Shopping campaign for Showcase ads. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import base64 -import uuid - -from googleads import adwords -from suds import WebFault - - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' -COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - # Note: Showcase ads require either ManualCpc or EnhancedCpc in the - # campaign's BiddingStrategyConfiguration. - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, budget_id, merchant_id, expanded_image_filepath, - collapsed_image_filepath): - try: - # Create the Shopping Campaign - campaign = CreateShoppingCampaign(client, budget_id, merchant_id) - - # Create the AdGroup - adgroup = CreateAdGroup(client, campaign['id']) - - # Create a Showcase Ad - CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath) - - product_partition_tree = CreateProductPartition(client, adgroup['id']) - print 'Final tree:\n%s' % product_partition_tree - except WebFault: - print 'Failed to create shopping campaign for showcase ads.' - raise - - -def CreateShoppingCampaign(client, budget_id, merchant_id): - """Creates a shopping campaign with the given budget and merchant IDs. - - Args: - client: an AdWordsClient instance. - budget_id: the str ID of the budget to be associated with the shopping - campaign. - merchant_id: the str ID of the merchant account to be associated with the - shopping campaign. - - Returns: - The created Shopping Campaign as a sudsobject. - """ - campaign_service = client.GetService('CampaignService', 'v201708') - - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - return campaign - - -def CreateAdGroup(client, campaign_id): - """Creates an AdGroup for the given shopping campaign ID. - - Args: - client: an AdWordsClient instance. - campaign_id: the str ID of a shopping campaign. - - Returns: - The created AdGroup as a sudsobject. - """ - ad_group_service = client.GetService('AdGroupService', 'v201708') - - adgroup = { - # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS - 'adGroupType': 'SHOPPING_SHOWCASE_ADS', - 'campaignId': campaign_id, - 'name': 'AdGroup #%s' % uuid.uuid4(), - # REQUIRED: Set the ad group's bidding strategy configuration. - 'biddingStrategyConfiguration': { - # Showcase ads require either ManualCpc or EnhancedCpc. - 'biddingStrategyType': 'MANUAL_CPC', - # Optional: Set the bids - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 100000 - } - }] - } - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - return adgroup - - -def CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath): - """Creates a showcase add for the given AdGroup with the given images. - - Args: - client: an AdWordsClient instance. - adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. - expanded_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's expandedImage. - collapsed_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's collapsedImage. - - Returns: - The created Showcase Ad as a sudsobject. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201708') - - showcase_ad = { - 'adGroupId': adgroup['id'], - 'ad': { - 'xsi_type': 'ShowcaseAd', - 'Ad.Type': 'ShowcaseAd', - # Required: set the ad's name, final URLs, and display URL. - 'name': 'Showcase ad #%s' % uuid.uuid4(), - 'finalUrls': 'http://example.com/showcase', - 'displayUrl': 'example.com', - # Required: Set the ad's expanded image. - 'expandedImage': { - 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] - }, - # Optional: Set the collapsed image. - 'collapsedImage': { - 'mediaId': - UploadImage(client, collapsed_image_filepath)['mediaId'] - } - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': showcase_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] - - print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] - - return showcase_ad - - -def UploadImage(client, filepath): - """Uploads a .jpg image with the given filepath via the AdWords MediaService. - - Args: - client: an AdWordsClient instance. - filepath: a str filepath to the .jpg file to be uploaded. - - Returns: - The created Image as a sudsobject. - """ - media_service = client.GetService('MediaService', 'v201708') - - with open(filepath, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') - - image = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - - image = media_service.upload(image)[0] - - return image - - -def CreateProductPartition(client, adgroup_id): - """Creates a ProductPartition tree for the given AdGroup ID. - - Args: - client: an AdWordsClient instance. - adgroup_id: a str AdGroup ID. - - Returns: - The ProductPartition tree as a sudsobject. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - 'v201708') - helper = ProductPartitionHelper(adgroup_id) - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition) - helper.CreateUnit(root, used_product_canonical_condition) - helper.CreateUnit(root, other_product_canonical_condition) - - result = ad_group_criterion_service.mutate(helper.operations) - return result['value'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, - COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201708/shopping/get_product_category_taxonomy.py b/examples/adwords/v201708/shopping/get_product_category_taxonomy.py deleted file mode 100755 index b0647465..00000000 --- a/examples/adwords/v201708/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201708') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/targeting/__init__.py b/examples/adwords/v201708/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201708/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201708/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201708/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 33fbee64..00000000 --- a/examples/adwords/v201708/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201708') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s", criterion id "%s", ' - 'and type "%s" was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201708/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201708/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 2998b4a0..00000000 --- a/examples/adwords/v201708/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201708') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type "%s" was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201708/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201708/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 7a56aa9d..00000000 --- a/examples/adwords/v201708/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201708') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201708/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index 4a7376d5..00000000 --- a/examples/adwords/v201708/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201708') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name "%s" and ID "%s" was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name "%s", ID "%s", and country code "%s" was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201708/targeting/lookup_location.py b/examples/adwords/v201708/targeting/lookup_location.py deleted file mode 100755 index aa5c8886..00000000 --- a/examples/adwords/v201708/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201708') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term "%s" returned the location "%s" of type "%s"' - ' with parent locations "%s", reach "%s" and id "%s" (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py index 679abda7..2bd5158a 100755 --- a/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py @@ -26,7 +26,6 @@ """ -import base64 import urllib2 from googleads import adwords @@ -39,13 +38,11 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - # Optionally, you may specify a landscape image. The image needs to be in a - # BASE64 encoded form. Here we download a demo image and encode it for this - # ad. + # Optionally, you may specify a landscape image. + # Here we download a demo image. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) - .decode('utf-8')) + image_data = opener.open('http://goo.gl/9JmyKk').read().decode('utf-8') # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py index 838b04e5..a3fd7125 100755 --- a/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py +++ b/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py @@ -142,8 +142,8 @@ def _CreateFeedItems(client, feed_details, label_name): # Get the FeedItemService. feed_item_service = client.GetService('FeedItemService', version='v201710') - # Optional: You can include the {feeditem} valuetrack parameter to track which - # page feed items lead to each click. + # For page feed URL recommendations and rules, see: + # https://support.google.com/adwords/answer/7166527 urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', 'http://www.example.com/discounts/hotel-deals?id={feeditem}', 'http://www.example.com/discounts/flight-deals?id={feeditem}') diff --git a/examples/adwords/v201710/advanced_operations/add_html5_ad.py b/examples/adwords/v201710/advanced_operations/add_html5_ad.py index db7eee3e..9133e386 100755 --- a/examples/adwords/v201710/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201710/advanced_operations/add_html5_ad.py @@ -26,7 +26,6 @@ """ -import base64 import urllib2 from googleads import adwords @@ -39,12 +38,11 @@ def main(client, ad_group_id): ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') + html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') # Create a media bundle containing the zip file with all the HTML5 components. media_bundle = { 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, + 'data': html5_zip, 'entryPoint': 'carousel/index.html', 'type': 'MEDIA_BUNDLE' } @@ -98,11 +96,11 @@ def main(client, ad_group_id): % (ad['ad']['id'], ad['ad']['displayUrl'])) -def GetBase64EncodedHTML5ZipFromUrl(url): +def GetHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') + return response.read().decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py index 02701412..ec102603 100755 --- a/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py @@ -25,7 +25,6 @@ """ -import base64 import urllib2 from googleads import adwords @@ -114,7 +113,7 @@ def _CreateImage(media_service, opener, url): The image that was successfully uploaded. """ # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image_data = opener.open(url).read().decode('utf-8') image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201710/campaign_management/validate_text_ad.py b/examples/adwords/v201710/campaign_management/validate_text_ad.py index a5cd9f11..a11fb2fa 100755 --- a/examples/adwords/v201710/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201710/campaign_management/validate_text_ad.py @@ -25,9 +25,9 @@ """ -import suds from googleads import adwords +from googleads import errors AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' @@ -73,7 +73,7 @@ def main(client, ad_group_id): }] try: ad_group_ad_service.mutate(operations) - except suds.WebFault, e: + except errors.GoogleAdsServerFault, e: print 'Validation correctly failed with "%s".' % str(e) diff --git a/examples/adwords/v201710/error_handling/handle_partial_failures.py b/examples/adwords/v201710/error_handling/handle_partial_failures.py index 1a4633ba..e9819dcf 100755 --- a/examples/adwords/v201710/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201710/error_handling/handle_partial_failures.py @@ -109,12 +109,12 @@ def main(client, ad_group_id): if (first_field_path_element and first_field_path_element['field'] == 'operations' and - first_field_path_element['index']): + 'index' in first_field_path_element): operation_index = first_field_path_element['index'] adgroup_criterion = operations[operation_index]['operand'] - print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' + print('Ad group criterion with ad group ID %s and keyword "%s" triggered ' 'a failure for the following reason: %s.' % (adgroup_criterion['adGroupId'], adgroup_criterion['criterion']['text'], diff --git a/examples/adwords/v201710/error_handling/handle_policy_violation_error.py b/examples/adwords/v201710/error_handling/handle_policy_violation_error.py index cb8f9ac0..3e77917c 100755 --- a/examples/adwords/v201710/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201710/error_handling/handle_policy_violation_error.py @@ -26,9 +26,9 @@ """ -import suds from googleads import adwords +from googleads import errors AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' @@ -81,7 +81,7 @@ def main(client, ad_group_id): client.validate_only = True ad_group_ad_service.mutate(operations) print 'Validation successful, no errors returned.' - except suds.WebFault, e: + except errors.GoogleAdsServerFault, e: for error in e.fault.detail.ApiExceptionFault.errors: # Get the index of the failed operation from the error's field path # elements. @@ -96,16 +96,15 @@ def main(client, ad_group_id): # so simply throw the exception. if (not (first_field_path_element and first_field_path_element['field'] == 'operations' - and first_field_path_element['index'])): + and 'index' in first_field_path_element)): raise e - operation_index = first_field_path_element['index'] - index = int(operation_index[0]) + index = long(first_field_path_element['index']) operation = operations[index] if not HandleAPIError(error, operation): # Set non-exemptable operation to None to mark for deletion. print ('Removing operation with non-exemptable error at index %s.' - % operation_index) + % index) operations[index] = None # Remove the non-exemptable operations. diff --git a/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py index 2410773f..2c02dcce 100755 --- a/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py @@ -30,9 +30,6 @@ import time import uuid -# Import appropriate modules from the client library. -import suds - from googleads import adwords from googleads import errors @@ -127,7 +124,7 @@ def main(client, gmb_email_address, gmb_access_token, try: added_customer_feed = customer_feed_service.mutate([ customer_feed_operation])['value'][0] - except suds.WebFault: + except errors.GoogleAdsServerFault: # Wait using exponential backoff policy sleep_seconds = 2 ** i print ('Attempt %d to add the CustomerFeed was not successful.' diff --git a/examples/adwords/v201710/misc/upload_image.py b/examples/adwords/v201710/misc/upload_image.py index ba035520..da63e423 100755 --- a/examples/adwords/v201710/misc/upload_image.py +++ b/examples/adwords/v201710/misc/upload_image.py @@ -26,7 +26,6 @@ """ -import base64 from googleads import adwords @@ -38,7 +37,7 @@ def main(client, image_filename): media_service = client.GetService('MediaService', version='v201710') with open(image_filename, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') + image_data = image_handle.read().decode('utf-8') # Construct media and upload image. media = [{ diff --git a/examples/adwords/v201710/misc/upload_media_bundle.py b/examples/adwords/v201710/misc/upload_media_bundle.py index 966f4b63..0ba908a8 100755 --- a/examples/adwords/v201710/misc/upload_media_bundle.py +++ b/examples/adwords/v201710/misc/upload_media_bundle.py @@ -18,7 +18,6 @@ """ -import base64 import urllib2 from googleads import adwords @@ -27,12 +26,11 @@ def main(client): # Initialize appropriate service. media_service = client.GetService('MediaService', version='v201710') # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') + html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') # Create a media bundle containing the zip file with all the HTML5 components. media = [{ 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, + 'data': html5_zip, 'type': 'MEDIA_BUNDLE' }] # Upload HTML5 zip. @@ -47,11 +45,11 @@ def main(client): media['dimensions'][0]['value']['height'], media['mimeType'])) -def GetBase64EncodedHTML5ZipFromUrl(url): +def GetHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') + return response.read().decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py index f8c1959f..ba402775 100755 --- a/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py @@ -22,11 +22,10 @@ section of our README. """ -import base64 import uuid from googleads import adwords -from suds import WebFault +from googleads import errors BUDGET_ID = 'INSERT_BUDGET_ID_HERE' @@ -175,7 +174,7 @@ def main(client, budget_id, merchant_id, expanded_image_filepath, product_partition_tree = CreateProductPartition(client, adgroup['id']) print 'Final tree:\n%s' % product_partition_tree - except WebFault: + except errors.GoogleAdsServerFault: print 'Failed to create shopping campaign for showcase ads.' raise @@ -344,7 +343,7 @@ def UploadImage(client, filepath): media_service = client.GetService('MediaService', 'v201710') with open(filepath, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') + image_data = image_handle.read().decode('utf-8') image = [{ 'xsi_type': 'Image', diff --git a/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py index ee473887..f34c33bd 100755 --- a/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py +++ b/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py @@ -26,7 +26,6 @@ """ -import base64 import urllib2 from googleads import adwords @@ -39,13 +38,11 @@ def main(client, ad_group_id): # Initialize appropriate service. ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - # Optionally, you may specify a landscape image. The image needs to be in a - # BASE64 encoded form. Here we download a demo image and encode it for this - # ad. + # Optionally, you may specify a landscape image. + # Here we download a demo image. opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = (base64.b64encode(opener.open('http://goo.gl/9JmyKk').read()) - .decode('utf-8')) + image_data = opener.open('http://goo.gl/9JmyKk').read().decode('utf-8') # Create the template elements for the ad. You can refer to # https://developers.google.com/adwords/api/docs/appendix/templateads diff --git a/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py index 2bbaf050..8ea1a2e4 100755 --- a/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py +++ b/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py @@ -142,8 +142,8 @@ def _CreateFeedItems(client, feed_details, label_name): # Get the FeedItemService. feed_item_service = client.GetService('FeedItemService', version='v201802') - # Optional: You can include the {feeditem} valuetrack parameter to track which - # page feed items lead to each click. + # For page feed URL recommendations and rules, see: + # https://support.google.com/adwords/answer/7166527 urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', 'http://www.example.com/discounts/hotel-deals?id={feeditem}', 'http://www.example.com/discounts/flight-deals?id={feeditem}') diff --git a/examples/adwords/v201802/advanced_operations/add_gmail_ad.py b/examples/adwords/v201802/advanced_operations/add_gmail_ad.py index adab3ab8..daa400de 100755 --- a/examples/adwords/v201802/advanced_operations/add_gmail_ad.py +++ b/examples/adwords/v201802/advanced_operations/add_gmail_ad.py @@ -23,8 +23,6 @@ """ -import base64 - # Import appropriate classes from the client library. from googleads import adwords @@ -101,7 +99,7 @@ def _CreateImage(media_service, opener, url): The image that was successfully uploaded. """ # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image_data = opener.open(url).read().decode('utf-8') image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201802/advanced_operations/add_html5_ad.py b/examples/adwords/v201802/advanced_operations/add_html5_ad.py index ddf76b1c..d0f2810f 100755 --- a/examples/adwords/v201802/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201802/advanced_operations/add_html5_ad.py @@ -26,7 +26,6 @@ """ -import base64 import urllib2 from googleads import adwords @@ -39,12 +38,11 @@ def main(client, ad_group_id): ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') + html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') # Create a media bundle containing the zip file with all the HTML5 components. media_bundle = { 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, + 'data': html5_zip, 'entryPoint': 'carousel/index.html', 'type': 'MEDIA_BUNDLE' } @@ -98,11 +96,11 @@ def main(client, ad_group_id): % (ad['ad']['id'], ad['ad']['displayUrl'])) -def GetBase64EncodedHTML5ZipFromUrl(url): +def GetHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') + return response.read().decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py index 7fb6a193..1eadade0 100755 --- a/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py @@ -25,7 +25,6 @@ """ -import base64 import urllib2 from googleads import adwords @@ -114,7 +113,7 @@ def _CreateImage(media_service, opener, url): The image that was successfully uploaded. """ # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image_data = opener.open(url).read().decode('utf-8') image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py index 2c41fe1a..19b90065 100755 --- a/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py +++ b/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py @@ -29,7 +29,6 @@ """ -import base64 import uuid from googleads import adwords @@ -288,7 +287,7 @@ def _CreateImage(media_service, opener, url): The image that was successfully uploaded. """ # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = base64.b64encode(opener.open(url).read()).decode('utf-8') + image_data = opener.open(url).read().decode('utf-8') image = { 'type': 'IMAGE', 'data': image_data, diff --git a/examples/adwords/v201802/campaign_management/validate_text_ad.py b/examples/adwords/v201802/campaign_management/validate_text_ad.py index d657e884..904392e8 100755 --- a/examples/adwords/v201802/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201802/campaign_management/validate_text_ad.py @@ -25,9 +25,9 @@ """ -import suds from googleads import adwords +from googleads import errors AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' @@ -73,7 +73,7 @@ def main(client, ad_group_id): }] try: ad_group_ad_service.mutate(operations) - except suds.WebFault, e: + except errors.GoogleAdsServerFault, e: print 'Validation correctly failed with "%s".' % str(e) diff --git a/examples/adwords/v201802/error_handling/handle_partial_failures.py b/examples/adwords/v201802/error_handling/handle_partial_failures.py index 9efc7237..cdcad6b6 100755 --- a/examples/adwords/v201802/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201802/error_handling/handle_partial_failures.py @@ -109,12 +109,12 @@ def main(client, ad_group_id): if (first_field_path_element and first_field_path_element['field'] == 'operations' and - first_field_path_element['index']): + 'index' in first_field_path_element): operation_index = first_field_path_element['index'] adgroup_criterion = operations[operation_index]['operand'] - print('Ad group criterion with ad group ID %d and keyword "%s" triggered ' + print('Ad group criterion with ad group ID %s and keyword "%s" triggered ' 'a failure for the following reason: %s.' % (adgroup_criterion['adGroupId'], adgroup_criterion['criterion']['text'], diff --git a/examples/adwords/v201802/error_handling/handle_policy_violation_error.py b/examples/adwords/v201802/error_handling/handle_policy_violation_error.py index e4623468..b13a2263 100755 --- a/examples/adwords/v201802/error_handling/handle_policy_violation_error.py +++ b/examples/adwords/v201802/error_handling/handle_policy_violation_error.py @@ -26,9 +26,9 @@ """ -import suds from googleads import adwords +from googleads import errors AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' @@ -81,8 +81,8 @@ def main(client, ad_group_id): client.validate_only = True ad_group_ad_service.mutate(operations) print 'Validation successful, no errors returned.' - except suds.WebFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: + except errors.GoogleAdsServerFault, e: + for error in e.errors: # Get the index of the failed operation from the error's field path # elements. field_path_elements = error['fieldPathElements'] @@ -96,16 +96,15 @@ def main(client, ad_group_id): # so simply throw the exception. if (not (first_field_path_element and first_field_path_element['field'] == 'operations' - and first_field_path_element['index'])): + and 'index' in first_field_path_element)): raise e - operation_index = first_field_path_element['index'] - index = int(operation_index[0]) + index = long(first_field_path_element['index']) operation = operations[index] if not HandleAPIError(error, operation): # Set non-exemptable operation to None to mark for deletion. print ('Removing operation with non-exemptable error at index %s.' - % operation_index) + % index) operations[index] = None # Remove the non-exemptable operations. diff --git a/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py index 40381a65..c152f6da 100755 --- a/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py @@ -30,9 +30,6 @@ import time import uuid -# Import appropriate modules from the client library. -import suds - from googleads import adwords from googleads import errors @@ -127,7 +124,7 @@ def main(client, gmb_email_address, gmb_access_token, try: added_customer_feed = customer_feed_service.mutate([ customer_feed_operation])['value'][0] - except suds.WebFault: + except errors.GoogleAdsServerFault: # Wait using exponential backoff policy sleep_seconds = 2 ** i print ('Attempt %d to add the CustomerFeed was not successful.' diff --git a/examples/adwords/v201802/extensions/add_site_links_using_feeds.py b/examples/adwords/v201802/extensions/add_site_links_using_feeds.py index 738ffda7..b4d07fdd 100755 --- a/examples/adwords/v201802/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201802/extensions/add_site_links_using_feeds.py @@ -42,12 +42,16 @@ PLACEHOLDER_FIELD_LINE_3_TEXT = '4' CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Optional: Ad group to restrict targeting to. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -def main(client, campaign_id): +def main(client, campaign_id, ad_group_id=None): # Initialize appropriate service. feed_service = client.GetService('FeedService', version='v201802') feed_item_service = client.GetService('FeedItemService', version='v201802') + feed_item_target_service = client.GetService('FeedItemTargetService', + version='v201802') feed_mapping_service = client.GetService( 'FeedMappingService', version='v201802') campaign_feed_service = client.GetService( @@ -228,9 +232,34 @@ def main(client, campaign_id): else: raise errors.GoogleAdsError('No campaign feeds were added.') + # Optional: Restrict the first feed item to only serve with ads for the + # specified ad group ID. + if ad_group_id: + feed_item_target = { + 'xsi_type': 'FeedItemAdGroupTarget', + 'feedId': sitelinks_data['feedId'], + 'feedItemId': sitelinks_data['feedItemIds'][0], + 'adGroupId': ad_group_id + } + + operations = [{ + 'operator': 'ADD', + 'operand': feed_item_target + }] + + response = feed_item_target_service.mutate(operations) + + if 'value' in response: + print ('Feed item target for feed ID "%d" and feed item ID "%d" was ' + 'created to restrict serving to ad group ID "%d".' + % (feed_item_target['feedId'], feed_item_target['feedItemId'], + feed_item_target['adGroupId'])) if __name__ == '__main__': # Initialize client object. adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) + if AD_GROUP_ID == 'INSERT_AD_GROUP_ID_HERE': + main(adwords_client, CAMPAIGN_ID) + else: + main(adwords_client, CAMPAIGN_ID, ad_group_id=AD_GROUP_ID) diff --git a/examples/adwords/v201802/misc/upload_image.py b/examples/adwords/v201802/misc/upload_image.py index d80c284d..afbdc996 100755 --- a/examples/adwords/v201802/misc/upload_image.py +++ b/examples/adwords/v201802/misc/upload_image.py @@ -26,7 +26,6 @@ """ -import base64 from googleads import adwords @@ -38,7 +37,7 @@ def main(client, image_filename): media_service = client.GetService('MediaService', version='v201802') with open(image_filename, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') + image_data = image_handle.read().decode('utf-8') # Construct media and upload image. media = [{ diff --git a/examples/adwords/v201802/misc/upload_media_bundle.py b/examples/adwords/v201802/misc/upload_media_bundle.py index e09a3a1e..74ec7032 100755 --- a/examples/adwords/v201802/misc/upload_media_bundle.py +++ b/examples/adwords/v201802/misc/upload_media_bundle.py @@ -18,7 +18,6 @@ """ -import base64 import urllib2 from googleads import adwords @@ -27,12 +26,11 @@ def main(client): # Initialize appropriate service. media_service = client.GetService('MediaService', version='v201802') # Create HTML5 media. - base64_encoded_html5_zip = GetBase64EncodedHTML5ZipFromUrl( - 'https://goo.gl/9Y7qI2') + html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') # Create a media bundle containing the zip file with all the HTML5 components. media = [{ 'xsi_type': 'MediaBundle', - 'data': base64_encoded_html5_zip, + 'data': html5_zip, 'type': 'MEDIA_BUNDLE' }] # Upload HTML5 zip. @@ -47,11 +45,11 @@ def main(client): media['dimensions'][0]['value']['height'], media['mimeType'])) -def GetBase64EncodedHTML5ZipFromUrl(url): +def GetHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" response = urllib2.urlopen(url) # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return base64.b64encode(response.read()).decode('utf-8') + return response.read().decode('utf-8') if __name__ == '__main__': diff --git a/examples/adwords/v201802/remarketing/add_crm_based_user_list.py b/examples/adwords/v201802/remarketing/add_crm_based_user_list.py index e542c0fc..4ca088c6 100755 --- a/examples/adwords/v201802/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201802/remarketing/add_crm_based_user_list.py @@ -39,8 +39,8 @@ def main(client): 'xsi_type': 'CrmBasedUserList', 'name': 'Customer relationship management list #%d' % uuid.uuid4(), 'description': 'A list of customers that originated from email addresses', - # See limit here: - # https://support.google.com/adwords/answer/6276125#requirements + # CRM-based user lists can use a membershipLifeSpan of 10000 to indicate + # unlimited; otherwise normal values apply. 'membershipLifeSpan': 30, 'uploadKeyType': 'CONTACT_INFO' } diff --git a/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py index dd7cf540..6e6d14b4 100755 --- a/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py @@ -22,11 +22,10 @@ section of our README. """ -import base64 import uuid from googleads import adwords -from suds import WebFault +from googleads import errors BUDGET_ID = 'INSERT_BUDGET_ID_HERE' @@ -175,7 +174,7 @@ def main(client, budget_id, merchant_id, expanded_image_filepath, product_partition_tree = CreateProductPartition(client, adgroup['id']) print 'Final tree:\n%s' % product_partition_tree - except WebFault: + except errors.GoogleAdsServerFault: print 'Failed to create shopping campaign for showcase ads.' raise @@ -344,7 +343,7 @@ def UploadImage(client, filepath): media_service = client.GetService('MediaService', 'v201802') with open(filepath, 'rb') as image_handle: - image_data = base64.encodestring(image_handle.read()).decode('utf-8') + image_data = image_handle.read().decode('utf-8') image = [{ 'xsi_type': 'Image', diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/dfp/authentication/create_dfp_client_with_service_account.py index 8b152927..f5081e32 100755 --- a/examples/dfp/authentication/create_dfp_client_with_service_account.py +++ b/examples/dfp/authentication/create_dfp_client_with_service_account.py @@ -22,16 +22,15 @@ # OAuth2 credential information. In a real application, you'd probably be # pulling these values from a credential storage. -SERVICE_ACCOUNT_EMAIL = 'INSERT_SERVICE_ACCOUNT_EMAIL' KEY_FILE = 'INSERT_KEY_FILE_PATH' # DFP API information. APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE' -def main(service_account_email, key_file, application_name): +def main(key_file, application_name): oauth2_client = oauth2.GoogleServiceAccountClient( - oauth2.GetAPIScope('dfp'), service_account_email, key_file) + key_file, oauth2.GetAPIScope('dfp')) dfp_client = dfp.DfpClient(oauth2_client, application_name) @@ -42,4 +41,4 @@ def main(service_account_email, key_file, application_name): if __name__ == '__main__': - main(SERVICE_ACCOUNT_EMAIL, KEY_FILE, APPLICATION_NAME) + main(KEY_FILE, APPLICATION_NAME) diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/dfp/authentication/generate_refresh_token.py index 4e261fe2..54e5f3c2 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/dfp/authentication/generate_refresh_token.py @@ -20,7 +20,8 @@ import argparse import sys -from oauth2client import client +from google_auth_oauthlib.flow import InstalledAppFlow +from oauthlib.oauth2.rfc6749.errors import InvalidGrantError # Your OAuth2 Client ID and Secret. If you do not have an ID and Secret yet, # please go to https://console.developers.google.com and create a set. @@ -29,6 +30,9 @@ # The DFP API OAuth2 scope. SCOPE = u'https://www.googleapis.com/auth/dfp' +# The redirect URI set for the given Client ID. The redirect URI for Client ID +# generated for an installed application will always have this value. +_REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' parser = argparse.ArgumentParser(description='Generates a refresh token with ' 'the provided credentials.') @@ -42,31 +46,68 @@ 'refresh token. Each scope should be separated by a comma.') +class ClientConfigBuilder(object): + """Helper class used to build a client config dict used in the OAuth 2.0 flow. + """ + _DEFAULT_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth' + _DEFAULT_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token' + CLIENT_TYPE_WEB = 'web' + CLIENT_TYPE_INSTALLED_APP = 'installed' + + def __init__(self, client_type=None, client_id=None, client_secret=None, + auth_uri=_DEFAULT_AUTH_URI, token_uri=_DEFAULT_TOKEN_URI): + self.client_type = client_type + self.client_id = client_id + self.client_secret = client_secret + self.auth_uri = auth_uri + self.token_uri = token_uri + + def Build(self): + """Builds a client config dictionary used in the OAuth 2.0 flow.""" + if all((self.client_type, self.client_id, self.client_secret, + self.auth_uri, self.token_uri)): + client_config = { + self.client_type: { + 'client_id': self.client_id, + 'client_secret': self.client_secret, + 'auth_uri': self.auth_uri, + 'token_uri': self.token_uri + } + } + else: + raise ValueError('Required field is missing.') + + return client_config + + def main(client_id, client_secret, scopes): """Retrieve and display the access and refresh token.""" - flow = client.OAuth2WebServerFlow( - client_id=client_id, - client_secret=client_secret, - scope=scopes, - user_agent='Ads Python Client Library', - redirect_uri='urn:ietf:wg:oauth:2.0:oob') + client_config = ClientConfigBuilder( + client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id, + client_secret=client_secret) + + flow = InstalledAppFlow.from_client_config( + client_config.Build(), scopes=scopes) + # Note that from_client_config will not produce a flow with the + # redirect_uris (if any) set in the client_config. This must be set + # separately. + flow.redirect_uri = _REDIRECT_URI - authorize_url = flow.step1_get_authorize_url() + auth_url, _ = flow.authorization_url(prompt='consent') print ('Log into the Google Account you use to access your DFP account' - 'and go to the following URL: \n%s\n' % (authorize_url)) + 'and go to the following URL: \n%s\n' % (auth_url)) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: - credential = flow.step2_exchange(code) - except client.FlowExchangeError, e: - print 'Authentication has failed: %s' % e + flow.fetch_token(code=code) + except InvalidGrantError as ex: + print 'Authentication has failed: %s' % ex sys.exit(1) - else: - print ('OAuth2 authorization successful!\n\n' - 'Your access token is:\n %s\n\nYour refresh token is:\n %s' - % (credential.access_token, credential.refresh_token)) + + print 'Access token: %s' % flow.credentials.token + print 'Refresh token: %s' % flow.credentials.refresh_token if __name__ == '__main__': diff --git a/examples/dfp/v201708/creative_service/create_creative_from_template.py b/examples/dfp/v201708/creative_service/create_creative_from_template.py index 6e5cd544..3ccfa050 100755 --- a/examples/dfp/v201708/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201708/creative_service/create_creative_from_template.py @@ -28,7 +28,6 @@ """ -import base64 import os import uuid @@ -50,7 +49,6 @@ def main(client, advertiser_id): file_name = 'image%s.jpg' % uuid.uuid4() image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() - image_data = base64.encodestring(image_data) size = { 'width': '300', 'height': '250' diff --git a/examples/dfp/v201708/creative_service/create_creatives.py b/examples/dfp/v201708/creative_service/create_creatives.py index 6514ff8a..14668389 100755 --- a/examples/dfp/v201708/creative_service/create_creatives.py +++ b/examples/dfp/v201708/creative_service/create_creatives.py @@ -27,7 +27,6 @@ """ -import base64 import os import uuid @@ -46,7 +45,7 @@ def main(client, advertiser_id): creatives = [] with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r') as image: - image_data = base64.encodestring(image.read()) + image_data = image.read() for _ in xrange(5): # Create creative size. diff --git a/examples/dfp/v201708/creative_service/create_custom_creative.py b/examples/dfp/v201708/creative_service/create_custom_creative.py index d62d27cb..47f8c23c 100755 --- a/examples/dfp/v201708/creative_service/create_custom_creative.py +++ b/examples/dfp/v201708/creative_service/create_custom_creative.py @@ -28,7 +28,6 @@ """ -import base64 import os import uuid @@ -46,7 +45,6 @@ def main(client, advertiser_id): # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() - image_data = base64.encodestring(image_data) # Create the HTML snippet used in the custom creative. html_snippet = ('
Click above for ' diff --git a/examples/dfp/v201708/creative_service/create_native_creative.py b/examples/dfp/v201708/creative_service/create_native_creative.py index 22566070..5bb0de13 100755 --- a/examples/dfp/v201708/creative_service/create_native_creative.py +++ b/examples/dfp/v201708/creative_service/create_native_creative.py @@ -29,7 +29,6 @@ section of our README. """ -import base64 import urllib2 import uuid @@ -53,11 +52,11 @@ def main(client, advertiser_id): image_data = urllib2.urlopen(ICON_URL).read() # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = base64.b64encode(image_data).decode('utf-8') + image_data = image_data.decode('utf-8') app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - app_icon_data = base64.b64encode(app_icon_data).decode('utf-8') + app_icon_data = app_icon_data.decode('utf-8') # Create creative from templates. creative = { diff --git a/examples/dfp/v201711/creative_service/create_creative_from_template.py b/examples/dfp/v201711/creative_service/create_creative_from_template.py index 64bd5e63..129b9623 100755 --- a/examples/dfp/v201711/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201711/creative_service/create_creative_from_template.py @@ -28,7 +28,6 @@ """ -import base64 import os import uuid @@ -50,7 +49,6 @@ def main(client, advertiser_id): file_name = 'image%s.jpg' % uuid.uuid4() image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() - image_data = base64.encodestring(image_data) size = { 'width': '300', 'height': '250' diff --git a/examples/dfp/v201711/creative_service/create_creatives.py b/examples/dfp/v201711/creative_service/create_creatives.py index c315d9ea..fac92a31 100755 --- a/examples/dfp/v201711/creative_service/create_creatives.py +++ b/examples/dfp/v201711/creative_service/create_creatives.py @@ -27,7 +27,6 @@ """ -import base64 import os import uuid @@ -46,7 +45,7 @@ def main(client, advertiser_id): creatives = [] with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r') as image: - image_data = base64.encodestring(image.read()) + image_data = image.read() for _ in xrange(5): # Create creative size. diff --git a/examples/dfp/v201711/creative_service/create_custom_creative.py b/examples/dfp/v201711/creative_service/create_custom_creative.py index 99ef3a2d..60a683eb 100755 --- a/examples/dfp/v201711/creative_service/create_custom_creative.py +++ b/examples/dfp/v201711/creative_service/create_custom_creative.py @@ -28,7 +28,6 @@ """ -import base64 import os import uuid @@ -46,7 +45,6 @@ def main(client, advertiser_id): # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() - image_data = base64.encodestring(image_data) # Create the HTML snippet used in the custom creative. html_snippet = ('
Click above for ' diff --git a/examples/dfp/v201711/creative_service/create_native_creative.py b/examples/dfp/v201711/creative_service/create_native_creative.py index d28f8cdc..75ebfa86 100755 --- a/examples/dfp/v201711/creative_service/create_native_creative.py +++ b/examples/dfp/v201711/creative_service/create_native_creative.py @@ -29,7 +29,6 @@ section of our README. """ -import base64 import urllib2 import uuid @@ -52,10 +51,8 @@ def main(client, advertiser_id): creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - image_data = base64.b64encode(image_data) app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - app_icon_data = base64.b64encode(app_icon_data) # Create creative from templates. creative = { diff --git a/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py index c4e09074..c954ffbe 100755 --- a/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py @@ -39,7 +39,7 @@ def main(client): # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/activity_service/get_active_activities.py b/examples/dfp/v201802/activity_service/get_active_activities.py index 0b32f027..5686aa52 100755 --- a/examples/dfp/v201802/activity_service/get_active_activities.py +++ b/examples/dfp/v201802/activity_service/get_active_activities.py @@ -38,7 +38,7 @@ def main(client): # Print out some information for each activity. print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % (activity['id'], activity['name'], activity['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py index 8c88c322..48aa0349 100755 --- a/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py @@ -40,7 +40,7 @@ def main(client): print('Audience segment with ID "%d", name "%s", and size "%d" was ' 'found.\n' % (audience_segment['id'], audience_segment['name'], audience_segment['size'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py index 40848144..2bc4555b 100755 --- a/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py @@ -42,7 +42,7 @@ def main(client, rate_card_id): 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), base_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/company_service/get_advertisers.py b/examples/dfp/v201802/company_service/get_advertisers.py index ee3242fe..ecb16c39 100755 --- a/examples/dfp/v201802/company_service/get_advertisers.py +++ b/examples/dfp/v201802/company_service/get_advertisers.py @@ -37,7 +37,7 @@ def main(client): # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/contact_service/get_uninvited_contacts.py b/examples/dfp/v201802/contact_service/get_uninvited_contacts.py index 99b67b8a..6063cad2 100755 --- a/examples/dfp/v201802/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201802/contact_service/get_uninvited_contacts.py @@ -37,7 +37,7 @@ def main(client): # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/creative_service/create_creative_from_template.py b/examples/dfp/v201802/creative_service/create_creative_from_template.py index 0184f00b..5c426783 100755 --- a/examples/dfp/v201802/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201802/creative_service/create_creative_from_template.py @@ -28,7 +28,6 @@ """ -import base64 import os import uuid @@ -50,7 +49,6 @@ def main(client, advertiser_id): file_name = 'image%s.jpg' % uuid.uuid4() image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() - image_data = base64.encodestring(image_data) size = { 'width': '300', 'height': '250' diff --git a/examples/dfp/v201802/creative_service/create_creatives.py b/examples/dfp/v201802/creative_service/create_creatives.py index 785ecce6..af9e329f 100755 --- a/examples/dfp/v201802/creative_service/create_creatives.py +++ b/examples/dfp/v201802/creative_service/create_creatives.py @@ -27,7 +27,6 @@ """ -import base64 import os import uuid @@ -46,7 +45,7 @@ def main(client, advertiser_id): creatives = [] with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r') as image: - image_data = base64.encodestring(image.read()) + image_data = image.read() for _ in xrange(5): # Create creative size. diff --git a/examples/dfp/v201802/creative_service/create_custom_creative.py b/examples/dfp/v201802/creative_service/create_custom_creative.py index 57d11581..de42ae87 100755 --- a/examples/dfp/v201802/creative_service/create_custom_creative.py +++ b/examples/dfp/v201802/creative_service/create_custom_creative.py @@ -28,7 +28,6 @@ """ -import base64 import os import uuid @@ -46,7 +45,6 @@ def main(client, advertiser_id): # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', 'medium_rectangle.jpg'), 'r').read() - image_data = base64.encodestring(image_data) # Create the HTML snippet used in the custom creative. html_snippet = ('
Click above for ' diff --git a/examples/dfp/v201802/creative_service/create_native_creative.py b/examples/dfp/v201802/creative_service/create_native_creative.py index 0af31046..a52f3501 100755 --- a/examples/dfp/v201802/creative_service/create_native_creative.py +++ b/examples/dfp/v201802/creative_service/create_native_creative.py @@ -29,7 +29,6 @@ section of our README. """ -import base64 import urllib2 import uuid @@ -52,10 +51,8 @@ def main(client, advertiser_id): creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - image_data = base64.b64encode(image_data) app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - app_icon_data = base64.b64encode(app_icon_data) # Create creative from templates. creative = { diff --git a/examples/dfp/v201802/creative_service/get_image_creatives.py b/examples/dfp/v201802/creative_service/get_image_creatives.py index 43c97189..f6099acd 100755 --- a/examples/dfp/v201802/creative_service/get_image_creatives.py +++ b/examples/dfp/v201802/creative_service/get_image_creatives.py @@ -37,7 +37,7 @@ def main(client): # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % (creative['id'], creative['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/creative_service/update_creatives.py b/examples/dfp/v201802/creative_service/update_creatives.py index 36b9ac84..74726456 100755 --- a/examples/dfp/v201802/creative_service/update_creatives.py +++ b/examples/dfp/v201802/creative_service/update_creatives.py @@ -36,7 +36,7 @@ def main(client, image_creative_id): # Initialize appropriate service. creative_service = client.GetService('CreativeService', version='v201802') - # Create statement object to get all image creatives. + # Create statement object to get the creative by ID. statement = (dfp.StatementBuilder() .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') diff --git a/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py index e6defb2b..ffd023d7 100755 --- a/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py @@ -41,7 +41,7 @@ def main(client, master_creative_id): # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % (creative_set['id'], creative_set['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py index 63958253..202b14d1 100755 --- a/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py @@ -39,7 +39,7 @@ def main(client): # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % (creative_template['id'], creative_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py index f8e913db..3f46de24 100755 --- a/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py @@ -60,7 +60,7 @@ def main(client, label_id): {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: creative_wrappers_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py index 90f75cd8..d2a29cd9 100755 --- a/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py @@ -39,7 +39,7 @@ def main(client): # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py index 97cd279d..16d45c12 100755 --- a/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -57,7 +57,7 @@ def main(client): {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: custom_fields_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py index 411ff23b..9a47c4f1 100755 --- a/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py @@ -39,7 +39,7 @@ def main(client): # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % (custom_field['id'], custom_field['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py index d1a1e9c3..5ce26863 100755 --- a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py @@ -57,7 +57,7 @@ def main(client, key_id): print ('Custom targeting value with id "%s", name "%s", and display' ' name "%s" was updated.' % (value['id'], value['name'], value['displayName'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py index 896d0ac4..dc7344e1 100755 --- a/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -43,7 +43,7 @@ def main(client, currency_code): 'rate "%.2f" was found.\n' % (exchange_rate['id'], exchange_rate['currencyCode'], float(exchange_rate['exchangeRate'] / 1000000))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/inventory_service/archive_ad_units.py b/examples/dfp/v201802/inventory_service/archive_ad_units.py index 5d118eb8..6cfb83dc 100755 --- a/examples/dfp/v201802/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201802/inventory_service/archive_ad_units.py @@ -58,7 +58,7 @@ def main(client, parent_id): {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: ad_units_archived += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/label_service/deactivate_labels.py b/examples/dfp/v201802/label_service/deactivate_labels.py index f71ab6f5..14f1ea6a 100755 --- a/examples/dfp/v201802/label_service/deactivate_labels.py +++ b/examples/dfp/v201802/label_service/deactivate_labels.py @@ -48,7 +48,7 @@ def main(client): {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: labels_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/label_service/get_active_labels.py b/examples/dfp/v201802/label_service/get_active_labels.py index 023a2816..d480c9a1 100755 --- a/examples/dfp/v201802/label_service/get_active_labels.py +++ b/examples/dfp/v201802/label_service/get_active_labels.py @@ -37,7 +37,7 @@ def main(client): # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], label['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py index 38d6475d..fd01bc98 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py @@ -56,7 +56,7 @@ def main(client, line_item_id): statement.ToStatement()) if result and int(result['numChanges']) > 0: num_deactivated_licas += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py index 1fb91b67..81427789 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py @@ -47,7 +47,7 @@ def main(client, line_item_id): print('Line item creative association with line item ID "%d" and ' 'creative ID "%d" was found.\n' % (lica['lineItemId'], lica['creativeId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/line_item_service/activate_line_items.py b/examples/dfp/v201802/line_item_service/activate_line_items.py index a4d05caa..20c52f69 100755 --- a/examples/dfp/v201802/line_item_service/activate_line_items.py +++ b/examples/dfp/v201802/line_item_service/activate_line_items.py @@ -58,7 +58,7 @@ def main(client, order_id): {'xsi_type': 'ActivateLineItems'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: line_items_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py index 46639e3a..3213cc3c 100755 --- a/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py @@ -38,7 +38,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py index 6190ced8..be801307 100755 --- a/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py @@ -46,7 +46,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/order_service/approve_orders.py b/examples/dfp/v201802/order_service/approve_orders.py index 4d23d77b..8d87302c 100755 --- a/examples/dfp/v201802/order_service/approve_orders.py +++ b/examples/dfp/v201802/order_service/approve_orders.py @@ -51,7 +51,7 @@ def main(client): {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: orders_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/order_service/get_orders_starting_soon.py b/examples/dfp/v201802/order_service/get_orders_starting_soon.py index 7f53e5b3..eefdb762 100755 --- a/examples/dfp/v201802/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201802/order_service/get_orders_starting_soon.py @@ -47,7 +47,7 @@ def main(client): # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], order['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/package_service/get_in_progress_packages.py b/examples/dfp/v201802/package_service/get_in_progress_packages.py index c0feec6d..ed7c1af0 100755 --- a/examples/dfp/v201802/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201802/package_service/get_in_progress_packages.py @@ -38,7 +38,7 @@ def main(client): print( 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/placement_service/get_active_placements.py b/examples/dfp/v201802/placement_service/get_active_placements.py index d085a5fb..5e9fa95a 100755 --- a/examples/dfp/v201802/placement_service/get_active_placements.py +++ b/examples/dfp/v201802/placement_service/get_active_placements.py @@ -38,7 +38,7 @@ def main(client): # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % (placement['id'], placement['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py index 26962a18..caf5b5e6 100755 --- a/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py @@ -43,7 +43,7 @@ def main(client, rate_card_id): 'ID "%d" was found.\n' % (premium_rate['id'], premium_rate['premium feature'], premium_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py index c353c58c..7d14808a 100755 --- a/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py @@ -43,7 +43,7 @@ def main(client, product_package_id): 'package ID "%d" was found.\n' % (product_package_item['id'], product_package_item['productId'], product_package_item['productPackageId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/product_package_service/get_active_product_packages.py b/examples/dfp/v201802/product_package_service/get_active_product_packages.py index 73d509a0..0782a636 100755 --- a/examples/dfp/v201802/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201802/product_package_service/get_active_product_packages.py @@ -39,7 +39,7 @@ def main(client): # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % (product_package['id'], product_package['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/product_service/get_products_for_product_template.py b/examples/dfp/v201802/product_service/get_products_for_product_template.py index adb92de4..abb5c1ba 100755 --- a/examples/dfp/v201802/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201802/product_service/get_products_for_product_template.py @@ -40,7 +40,7 @@ def main(client, product_template_id): # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % (product['id'], product['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/product_template_service/activate_product_templates.py b/examples/dfp/v201802/product_template_service/activate_product_templates.py index 6d517f59..cf5dc6b0 100755 --- a/examples/dfp/v201802/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201802/product_template_service/activate_product_templates.py @@ -56,7 +56,7 @@ def main(client, product_template_id): {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: product_templates_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py index 6c6e6f1b..97b5ef0f 100755 --- a/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py @@ -39,7 +39,7 @@ def main(client): # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % (product_template['id'], product_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py index 095c02b1..7d0d0918 100755 --- a/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py @@ -58,7 +58,7 @@ def main(client, proposal_line_item_id): {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposal_line_items_archived += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 03368306..29df584f 100755 --- a/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -41,7 +41,7 @@ def main(client, proposal_id): # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % (proposal_line_item['id'], proposal_line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py index 6f6d47d6..19c3fa3d 100755 --- a/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py @@ -37,7 +37,7 @@ def main(client): # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % (proposal['id'], proposal['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py index baabcef4..b68da967 100755 --- a/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py @@ -49,7 +49,7 @@ def main(client, proposal_id): {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposals_pushed_to_marketplace += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py index 98cf90cb..600a5763 100755 --- a/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py @@ -50,7 +50,7 @@ def main(client, proposal_id): {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposals_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py index 5220fc13..b413ebda 100755 --- a/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py @@ -41,7 +41,7 @@ def main(client): 'Rate card with ID "%d", name "%s", and currency code "%s" was ' 'found.\n' % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 9926d667..5fd1484e 100755 --- a/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -45,7 +45,7 @@ def main(client, reconciliation_report_id): print('Reconciliation order report with ID "%d" and status "%s" was ' 'found.\n' % (reconciliation_order_report['id'], reconciliation_order_report['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index b2fe2fbc..5efaa779 100755 --- a/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -51,7 +51,7 @@ def main(client, reconciliation_report_id): (reconciliation_report_row['id'], reconciliation_report_row['reconciliationSource'], reconciliation_report_row['reconciledVolume'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 4674bc93..e6e12730 100755 --- a/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -50,7 +50,7 @@ def main(client): 'Reconciliation report with ID "%d" and start date "%s" was found.' '\n' % (reconciliation_report['id'], last_month.strftime('%Y-%m-01'))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/report_service/run_report_with_custom_fields.py b/examples/dfp/v201802/report_service/run_report_with_custom_fields.py index 0b7aa111..d1f76e9e 100755 --- a/examples/dfp/v201802/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201802/report_service/run_report_with_custom_fields.py @@ -50,7 +50,7 @@ def main(client, order_id): if 'customFieldValues' in line_item: for custom_field_value in line_item['customFieldValues']: custom_field_ids.add(custom_field_value['customFieldId']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 8b2f5184..7c8fbdbe 100755 --- a/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -42,7 +42,7 @@ def main(client, num_requests): print( 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/user_service/get_user_by_email_address.py b/examples/dfp/v201802/user_service/get_user_by_email_address.py index 5c1cdb20..0e492886 100755 --- a/examples/dfp/v201802/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201802/user_service/get_user_by_email_address.py @@ -39,7 +39,7 @@ def main(client, email_address): # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], user['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py index 8413cad0..165a24e6 100755 --- a/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py @@ -42,7 +42,7 @@ def main(client, user_id): print('User team association with user ID "%d" and team ID "%d" was ' 'found.\n' % (user_team_association['userId'], user_team_association['teamId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py index 5efc45eb..e65fd9f8 100755 --- a/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py @@ -58,7 +58,7 @@ def main(client, proposal_id): statement.ToStatement()) if result and int(result['numChanges']) > 0: workflow_approval_requests_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py index b2635616..7dd04f12 100755 --- a/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py @@ -44,7 +44,7 @@ def main(client): '"%d" was found.\n' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py index 71c4541e..9ed72aac 100755 --- a/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py @@ -44,7 +44,7 @@ def main(client): '"%d" was found.\n' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py index 394922c9..d682dfdc 100755 --- a/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -61,7 +61,7 @@ def main(client, proposal_id): if result and int(result['numChanges']) > 0: workflow_external_condition_requests_triggered += int( result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/googleads.yaml b/googleads.yaml index 1d081749..d2247f99 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -23,8 +23,7 @@ adwords: client_secret: INSERT_CLIENT_SECRET_HERE refresh_token: INSERT_REFRESH_TOKEN_HERE # The following values configure the client for the service account flow. - # service_account_email: INSERT_SERVICE_ACCOUNT_EMAIL_HERE - # path_to_private_key_file: INSERT_PATH_TO_FILE_HERE + # path_to_private_key_file: INSERT_PATH_TO_JSON_KEY_FILE_HERE # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT ############################################################################# # ReportDownloader Headers # @@ -57,9 +56,8 @@ dfp: # flow you're not using. # ############################################################################# # The following values configure the client for the service account flow. - path_to_private_key_file: INSERT_PATH_TO_FILE_HERE - # Only needed when using P12 - # service_account_email: INSERT_SERVICE_ACCOUNT_EMAIL_HERE + path_to_private_key_file: INSERT_PATH_TO_JSON_KEY_FILE_HERE + # delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT # The following values configure the client for the installed application # flow. # client_id: INSERT_OAUTH_2_CLIENT_ID_HERE @@ -98,25 +96,18 @@ dfp: ############################################################################### # Proxy configurations (optional) # # Below you may specify an HTTP or HTTPS Proxy to be used when making API # -# requests. # +# requests. Note: You must specify the scheme used for the proxy endpoint. # +# # +# For additional information on configuring these values, see: # +# http://docs.python-requests.org/en/master/user/advanced/#proxies # ############################################################################### # proxy_config: + # http: INSERT_HTTP_PROXY_URI_HERE + # https: INSERT_HTTPS_PROXY_URI_HERE # If specified, the given cafile will only be used if certificate validation # is not disabled. # cafile: INSERT_PATH_HERE # disable_certificate_validation: False - # http_proxy: - # host: INSERT_HOST_HERE - # port: INSERT_PROXY_PORT_HERE - # The following values are optional: - # username: INSERT_USERNAME_HERE - # password: INSERT_PASSWORD_HERE - # https_proxy: - # host: INSERT_HOST_HERE - # port: INSERT_PROXY_PORT_HERE - # The following values are optional: - # username: INSERT_USERNAME_HERE - # password: INSERT_PASSWORD_HERE ################################################################################ # Utilities Included (optional) # # Below you may specify whether the library will include utilities used in the # @@ -124,3 +115,10 @@ dfp: # agent. # ################################################################################ # include_utilities_in_user_agent: True +################################################################################ +# SOAP implementation (optional) # +# Specify which SOAP implementation to use. This library currently supports # +# suds and zeep. Zeep is more modern, and is the default, if you have any # +# issues please report them and fall back to suds. # +################################################################################ +# soap_impl: zeep diff --git a/googleads/adwords.py b/googleads/adwords.py index caf15a07..12c7f7da 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -14,6 +14,7 @@ """Client library for the AdWords API.""" +import abc from collections import namedtuple import datetime import io @@ -25,9 +26,6 @@ import urllib2 from xml.etree import ElementTree -import suds.client -import suds.mx.literal -import suds.xsd.doctor import xmltodict import yaml import googleads.common @@ -38,109 +36,11 @@ _batch_job_logger = logging.getLogger('%s.%s' % (__name__, 'batch_job_helper')) - +# The chunk size used for report downloads. +_CHUNK_SIZE = 16 * 1024 # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201705': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignBidModifierService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignGroupPerformanceTargetService': 'cm', - 'CampaignGroupService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineCallConversionFeedService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, - 'v201708': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignBidModifierService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignGroupPerformanceTargetService': 'cm', - 'CampaignGroupService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineCallConversionFeedService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'OfflineDataUploadService': 'rm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201710': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', @@ -338,7 +238,8 @@ def LoadFromStorage(cls, path=None): cls._OPTIONAL_INIT_VALUES)) def __init__(self, developer_token, oauth2_client, - user_agent=_DEFAULT_USER_AGENT, **kwargs): + user_agent=_DEFAULT_USER_AGENT, soap_impl='zeep', + timeout=3600, **kwargs): """Initializes an AdWordsClient. For more information on these arguments, see our SOAP headers guide: @@ -351,6 +252,9 @@ def __init__(self, developer_token, oauth2_client, user_agent: An arbitrary string containing only ASCII characters that will be used to identify your application. If not set, this will default to the string value "unknown". + soap_impl: A string identifying which SOAP implementation to use. The + options are 'zeep' or 'suds'. + timeout: An integer time in MS to time out connections to AdWords. **kwargs: Optional keyword arguments. Keyword Arguments: @@ -365,8 +269,9 @@ def __init__(self, developer_token, oauth2_client, succeed, to result in a complete failure with no changes made or a partial failure with some changes made. Only certain services respect this header. - cache: A subclass of suds.cache.Cache. If not set, this will default to an - instance of suds.cache.ObjectCache. + cache: A subclass of zeep.cache.Base or suds.cache.Cache. If not set, + this will default to a basic file cache. To disable caching for Zeep, + pass googleads.common.ZeepServiceProxy.NO_CACHE. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. report_downloader_headers: A dict containing optional headers to be used @@ -385,6 +290,7 @@ def __init__(self, developer_token, oauth2_client, self.oauth2_client = oauth2_client self.client_customer_id = kwargs.get('client_customer_id') self.user_agent = user_agent + self.soap_impl = soap_impl # Verify that the provided user_agent contains only ASCII characters. In # both Python 2 and Python 3, a UnicodeEncodeError will be raised if it # contains a non-ASCII character. @@ -407,6 +313,7 @@ def __init__(self, developer_token, oauth2_client, self.user_agent = '%s (gzip)' % self.user_agent self.message_plugin = googleads.common.LoggingMessagePlugin() + self.timeout = timeout def GetService(self, service_name, version=None, server=None): """Creates a service client for the given service. @@ -421,8 +328,8 @@ def GetService(self, service_name, version=None, server=None): server: A string identifying the webserver hosting the AdWords API. Returns: - A suds.client.ServiceSelector which has the headers and proxy configured - for use. + A googleads.common.GoogleSoapService instance which has the headers + and proxy configured for use. Raises: A GoogleAdsValueError if the service or version provided do not exist. @@ -446,21 +353,16 @@ def GetService(self, service_name, version=None, server=None): raise googleads.errors.GoogleAdsValueError( msg_fmt % ('version', version, _SERVICE_MAP.keys())) - kwargs = {'timeout': 3600, - 'transport': self.proxy_config.GetSudsProxyTransport(), - 'plugins': [self.message_plugin]} + service = googleads.common.GetServiceClassForLibrary(self.soap_impl)( + self._SOAP_SERVICE_FORMAT % ( + server, version_service_mapping, version, service_name), + _AdWordsHeaderHandler(self, version, self.enable_compression), + _AdWordsPacker, + self.proxy_config, + self.timeout, + cache=self.cache) - if self.cache: - kwargs['cache'] = self.cache - - client = suds.client.Client( - self._SOAP_SERVICE_FORMAT % - (server, version_service_mapping, version, service_name), - **kwargs) - - return googleads.common.SudsServiceProxy( - client, _AdWordsHeaderHandler(self, version, self.enable_compression), - packer=_AdWordsPacker) + return service def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -486,7 +388,7 @@ def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], self, version=version, server=server) response_parser = BatchJobHelper.GetResponseParser() - return BatchJobHelper(request_builder, response_parser, version=version) + return BatchJobHelper(request_builder, response_parser) def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): @@ -548,13 +450,17 @@ def __init__(self, adwords_client, version, enable_compression): self._version = version self.enable_compression = enable_compression - def SetHeaders(self, suds_client): - """Sets the SOAP and HTTP headers on the given suds client. + def GetSOAPHeaders(self, create_method): + """Returns the SOAP headers required for request authorization. Args: - suds_client: An initialized suds.client.Client. + create_method: The SOAP library specific method used to instantiate SOAP + objects. + + Returns: + A SOAP object containing the headers. """ - header = suds_client.factory.create(self._SOAP_HEADER_CLASS % self._version) + header = create_method(self._SOAP_HEADER_CLASS % self._version) header.clientCustomerId = self._adwords_client.client_customer_id header.developerToken = self._adwords_client.developer_token header.userAgent = ''.join([ @@ -562,14 +468,18 @@ def SetHeaders(self, suds_client): googleads.common.GenerateLibSig(self._PRODUCT_SIG)]) header.validateOnly = self._adwords_client.validate_only header.partialFailure = self._adwords_client.partial_failure + return header + def GetHTTPHeaders(self): + """Returns the HTTP headers required for request authorization. + + Returns: + A dictionary containing the required headers. + """ http_headers = self._adwords_client.oauth2_client.CreateHttpHeader() if self.enable_compression: http_headers['accept-encoding'] = 'gzip' - - suds_client.set_options( - soapheaders=header, - headers=http_headers) + return http_headers def GetReportDownloadHeaders(self, **kwargs): """Returns a dictionary of headers for a report download request. @@ -630,7 +540,7 @@ def GetReportDownloadHeaders(self, **kwargs): return headers -class _AdWordsPacker(googleads.common.SudsPacker): +class _AdWordsPacker(googleads.common.SoapPacker): """A utility applying customized packing logic for AdWords.""" @classmethod @@ -638,11 +548,11 @@ def Pack(cls, obj): """Pack the given object using AdWords-specific logic. Args: - obj: an object to be packed for suds using AdWords-specific logic, if + obj: an object to be packed for SOAP using AdWords-specific logic, if applicable. Returns: - The given object packed with AdWords-specific logic for suds, if + The given object packed with AdWords-specific logic for SOAP, if applicable. Otherwise, returns the given object unmodified. """ if isinstance(obj, ServiceQuery): @@ -657,6 +567,9 @@ class BatchJobHelper(object): class AbstractResponseParser(object): """Interface for parsing responses from the BatchJobService.""" + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod def ParseResponse(self, batch_job_response): """Parses a Batch Job Service response.. @@ -664,7 +577,6 @@ def ParseResponse(self, batch_job_response): batch_job_response: a str containing the response from the BatchJobService. """ - raise NotImplementedError('You must implement ParseResponse().') class _XMLToDictResponseParser(AbstractResponseParser): """Parses responses from the BatchJobService, returning as a dictionary.""" @@ -684,6 +596,9 @@ def ParseResponse(self, batch_job_response): class AbstractUploadRequestBuilder(object): """Interface for building requests used to upload batch job operations.""" + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod def BuildUploadRequest(self, upload_url, operations, **kwargs): """Builds the BatchJob upload request. @@ -697,9 +612,25 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): A urllib2.Request instance with the correct method, headers, and padding (if required) for the batch job upload. """ - raise NotImplementedError('You must implement BuildUploadRequest().') - class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): + @abc.abstractmethod + def GetVersion(self): + """Retrieves the version of AdWords used to build requests. + + Returns: + A str indicating the version of AdWords for which requests are being + built. + """ + + @abc.abstractmethod + def GetServer(self): + """Retrieves the endpoint used to access the AdWords API. + + Returns: + A str indicating the version of AdWords endpoint being used. + """ + + class _UploadRequestBuilder(AbstractUploadRequestBuilder): """Builds requests used to upload operations for Batch Jobs.""" # Used to remove namespace from xsi:type Element attributes. _ATTRIB_NAMESPACE_SUB = re.compile('ns[0-1]:') @@ -757,9 +688,10 @@ class _SudsUploadRequestBuilder(AbstractUploadRequestBuilder): 'SharedSetOperation': _OPERATION('SharedSetOperation', 'SharedSetService', 'mutate') } + XSI_TYPE_STRING = '{http://www.w3.org/2001/XMLSchema-instance}type' def __init__(self, client, **kwargs): - """Initializes a _SudsUploadRequestBuilder. + """Initializes an _UploadRequestBuilder. Arguments: client: an AdWordsClient instance. @@ -771,9 +703,9 @@ def __init__(self, client, **kwargs): """ self.client = client self._version = kwargs.get('version', sorted(_SERVICE_MAP.keys())[-1]) - server = kwargs.get('server', _DEFAULT_ENDPOINT) + self.server = kwargs.get('server', _DEFAULT_ENDPOINT) self._adwords_endpoint = ('%s/api/adwords/cm/%s' % - (server, self._version)) + (self.server, self._version)) self._adwords_namespace = ('{%s}' % self._adwords_endpoint) # Used to remove the AdWords namespace from Element tags. self._tag_namespace_sub = re.compile(self._adwords_namespace) @@ -825,6 +757,23 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): return req + def GetVersion(self): + """Retrieves the version of AdWords used to build requests. + + Returns: + A str indicating the version of AdWords for which requests are being + built. + """ + return self._version + + def GetServer(self): + """Retrieves the endpoint used to access the AdWords API. + + Returns: + A str indicating the version of AdWords endpoint being used. + """ + return self.server + def _BuildUploadRequestBody(self, operations, has_prefix=True, has_suffix=True): """Builds an unpadded body containing operations for a BatchJob upload. @@ -853,8 +802,7 @@ def _ExtractOperations(self, full_soap_xml): """Extracts operations from API Request XML for use with BatchJobService. Args: - full_soap_xml: The full XML for the desired operation, as generated by - suds. + full_soap_xml: The full XML for the desired operation. Returns: A string containing only the operations portion of the full XML request, @@ -879,7 +827,7 @@ def _ExtractOperations(self, full_soap_xml): if operation_type is None: raise googleads.errors.GoogleAdsValueError('No xsi_type specified ' 'for the operations.') - operations.attrib['xsi:type'] = operation_type.text + operations.attrib[self.XSI_TYPE_STRING] = operation_type.text operations_xml = ''.join([ElementTree.tostring(operation).decode('utf-8') for operation in method]) # Force removal of this line, which suds produces. @@ -940,19 +888,15 @@ def _GenerateRawRequestXML(self, operations): service. Returns: - A str containing the raw XML of the request to the given service that - would execute the given operations. + An element containing the raw XML of the request to the given service + that would execute the given operations. Raises: KeyError: If the given operation type is not supported. """ operation = self._OPERATION_MAP[operations[0]['xsi_type']] service = self.client.GetService(operation.service, self._version) - service.suds_client.set_options(nosend=True) - service_request = (getattr(service, operation.method) - (operations).envelope) - service.suds_client.set_options(nosend=False) - return service_request + return service.GetRequestXML(operation.method, operations) def _GetPaddingLength(self, length): """Retrieve the padding to be used in an incremental upload. @@ -971,8 +915,7 @@ def _GetRawOperationsFromXML(self, raw_request_xml): """Retrieve the raw set of operations from the request XML. Args: - raw_request_xml: The full XML for the desired operation, as generated by - suds. + raw_request_xml: The full XML for the desired operation. Returns: An unmodified Element containing the operations from the raw request @@ -981,12 +924,10 @@ def _GetRawOperationsFromXML(self, raw_request_xml): Raises: AttributeError: if the provided XML isn't from AdWords. """ - root = ElementTree.fromstring(raw_request_xml) - return root.find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find( - './/') + return raw_request_xml.find( + '{http://schemas.xmlsoap.org/soap/envelope/}Body').find('.//') - def __init__(self, request_builder, response_parser, - version=sorted(_SERVICE_MAP.keys())[-1]): + def __init__(self, request_builder, response_parser): """Initializes the BatchJobHelper. For general use, consider using AdWordsClient's GetBatchJobHelper method to @@ -996,14 +937,10 @@ def __init__(self, request_builder, response_parser, Args: request_builder: an AbstractUploadRequestBuilder instance. response_parser: an AbstractResponseParser instance. - version: A string identifying the AdWords version to connect to. This - defaults to what is currently the latest version. This will be updated - in future releases to point to what is then the latest version. """ self._temporary_id = 0 # Used for temporary IDs in BatchJobService. self._request_builder = request_builder self._response_parser = response_parser - self._version = version def GetId(self): """Produces a distinct sequential ID for the BatchJobService. @@ -1015,14 +952,13 @@ def GetId(self): return self._temporary_id def GetIncrementalUploadHelper(self, upload_url, current_content_length=0): - return IncrementalUploadHelper(self._request_builder, upload_url, - current_content_length, - version=self._version) + return IncrementalUploadHelper( + self._request_builder, upload_url, current_content_length) @classmethod def GetRequestBuilder(cls, *args, **kwargs): """Get a new AbstractUploadRequestBuilder instance.""" - return cls._SudsUploadRequestBuilder(*args, **kwargs) + return cls._UploadRequestBuilder(*args, **kwargs) @classmethod def GetResponseParser(cls, *args, **kwargs): @@ -1056,8 +992,7 @@ def UploadOperations(self, upload_url, *operations): *operations: one or more lists of operations as would be sent to the AdWords API for the associated service. """ - uploader = IncrementalUploadHelper(self._request_builder, upload_url, - version=self._version) + uploader = IncrementalUploadHelper(self._request_builder, upload_url) uploader.UploadOperations(operations, is_last=True) @@ -1093,21 +1028,21 @@ def Load(cls, file_input, client=None): raise googleads.errors.GoogleAdsError( 'Error loading IncrementalUploadHelper from file: %s' % str(e)) - batch_job_helper = client.GetBatchJobHelper(version=data['version']) - request_builder = batch_job_helper.GetRequestBuilder( - client, version=data['version']) - try: + request_builder = BatchJobHelper.GetRequestBuilder( + client, version=data['version'], server=data['server'] + ) + return cls(request_builder, data['upload_url'], current_content_length=data['current_content_length'], - is_last=data['is_last'], version=data['version']) + is_last=data['is_last']) except KeyError as e: raise googleads.errors.GoogleAdsValueError( 'Can\'t parse IncrementalUploadHelper from file. Required field ' '"%s" is missing.' % e.message) def __init__(self, request_builder, upload_url, current_content_length=0, - is_last=False, version=sorted(_SERVICE_MAP.keys())[-1]): + is_last=False): """Initializes the IncrementalUpload. Args: @@ -1116,20 +1051,15 @@ def __init__(self, request_builder, upload_url, current_content_length=0, current_content_length: an integer identifying the current content length of data uploaded to the Batch Job. is_last: a boolean indicating whether this is the final increment. - version: A string identifying the AdWords version to connect to. This - defaults to what is currently the latest version. This will be updated - in future releases to point to what is then the latest version. Raises: GoogleAdsValueError: if the content length is lower than 0. """ - self._version = version self._request_builder = request_builder if current_content_length < 0: raise googleads.errors.GoogleAdsValueError( 'Current content length %s is < 0.' % current_content_length) self._current_content_length = current_content_length self._is_last = is_last - self._url_opener = urllib2.build_opener( *self._request_builder.client.proxy_config.GetHandlers()) self._upload_url = self._InitializeURL(upload_url, current_content_length) @@ -1175,8 +1105,9 @@ def Dump(self, output): data = { 'current_content_length': self._current_content_length, 'is_last': self._is_last, + 'server': self._request_builder.GetServer(), 'upload_url': self._upload_url, - 'version': self._version + 'version': self._request_builder.GetVersion() } try: @@ -1301,18 +1232,15 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], self._header_handler = _AdWordsHeaderHandler( adwords_client, version, self._adwords_client.enable_compression) self.proxy_config = self._adwords_client.proxy_config - self.url_opener = urllib2.build_opener(*self.proxy_config.GetHandlers()) + handlers = self.proxy_config.GetHandlers() + self.url_opener = urllib2.build_opener(*handlers) schema_url = self._SCHEMA_FORMAT % (server, version) - schema = suds.client.Client( - schema_url, - doctor=suds.xsd.doctor.ImportDoctor(suds.xsd.doctor.Import( - self._namespace, schema_url)), - transport=self.proxy_config.GetSudsProxyTransport(), - cache=self._adwords_client.cache).wsdl.schema - self._report_definition_type = schema.elements[ - (self._REPORT_DEFINITION_NAME, self._namespace)] - self._marshaller = suds.mx.literal.Literal(schema) + service_class = (googleads.common + .GetSchemaHelperForLibrary(adwords_client.soap_impl)) + self.schema_helper = service_class( + schema_url, self._adwords_client.timeout, + self.proxy_config, self._namespace, self._adwords_client.cache) def _DownloadReportCheckFormat(self, file_format, output): mode = getattr(output, 'mode', 'w') @@ -1635,11 +1563,15 @@ def _DownloadReport(self, post_body, output, **kwargs): """ response = None try: + # New response = self._DownloadReportAsStream(post_body, **kwargs) - output.write(response.read().decode() if sys.version_info[0] == 3 - and (getattr(output, 'mode', 'w') == 'w' - and type(output) is not io.BytesIO) - else response.read()) + while True: + chunk = response.read(_CHUNK_SIZE) + if not chunk: break + output.write(chunk.decode('utf-8') if sys.version_info[0] == 3 + and (getattr(output, 'mode', 'w') == 'w' + and not isinstance(output, io.BytesIO)) + else chunk) finally: if response: response.close() @@ -1807,10 +1739,9 @@ def _SerializeReportDefinition(self, report_definition): the format needed for an AdWords report request as a string. This is intended to be a POST body. """ - content = suds.mx.Content( - tag=self._REPORT_DEFINITION_NAME, value=report_definition, - name=self._REPORT_DEFINITION_NAME, type=self._report_definition_type) - return urllib.urlencode({'__rdxml': self._marshaller.process(content)}) + return urllib.urlencode( + {'__rdxml': self.schema_helper.GetSoapXMLForComplexType( + self._REPORT_DEFINITION_NAME, report_definition)}) def _ExtractError(self, error): """Attempts to extract information from a report download error XML message. @@ -2461,6 +2392,13 @@ def order_by_list(self, order_by_list): class ServiceQuery(object): """A service query storing an AWQL query.""" + _BID_LANDSCAPE_PAGES = ('AdGroupBidLandscapePage', + 'CriterionBidLandscapePage') + _LANDSCAPE_POINTS = 'landscapePoints' + _TOTAL_NUM_ENTRIES = 'totalNumEntries' + _ENTRIES = 'entries' + _PAGE_TYPE = 'Page.Type' + def __init__(self, awql, start_index, page_size): """Creates a service query instance storing the provided AWQL query.""" self._awql = awql @@ -2468,18 +2406,20 @@ def __init__(self, awql, start_index, page_size): self._page_size = page_size self._total_num_entries = None - def NextPage(self, page_size=None): + def NextPage(self, page=None): """Sets the LIMIT clause of the AWQL to the next page. - This method is meant to be used with HasNext(). - The page_size is necessary when using DataService, as its paging mechanism - is different from other services. For details, see + This method is meant to be used with HasNext(). When using DataService, + page is needed, as its paging mechanism is different from other services. + For details, see https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results. - When the page_size is None, this object's page size is used instead. Args: - page_size: The optional page size used to increment the index in the LIMIT - clause. + page: An optional dict-like page returned in an API response, where the + type depends on the configured SOAP client. The page contains the + 'totalNumEntries' key whose value represents the total number of + results from making the query to the AdWords API services. This page + is required when using this method with DataService. Returns: This service query object. @@ -2490,25 +2430,31 @@ def NextPage(self, page_size=None): """ if self._start_index is None: raise ValueError('Cannot page through query with no LIMIT clause.') - increment = self._page_size if page_size is None else page_size + + # DataService has a different paging mechanism, resulting in different + # method of determining if there is still a page left. + page_size = None + if (page and self._PAGE_TYPE in page + and page[self._PAGE_TYPE] in self._BID_LANDSCAPE_PAGES): + page_size = sum([len(bid_landscape[self._LANDSCAPE_POINTS]) + for bid_landscape in page[self._ENTRIES]]) + + increment = page_size or self._page_size self._start_index += increment return self - def HasNext(self, page, page_size=None): + def HasNext(self, page): """Checks if there is still a page left to query. - This method is meant to be used with NextPage(). - The page_size is necessary when using DataService, as its paging mechanism - is different from other services. For details, see + This method is meant to be used with NextPage(). When using DataService, + the paging mechanism is different from other services. For details, see https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results. - When the page_size is None, this object's page size is used instead. Args: - page: A dict containing the 'totalNumEntries' key whose value represents - the total number of results from making the query to the AdWords API - services. - page_size: The optional page size used to increment the index in the LIMIT - clause. + page: A dict-like page returned in an API response, where the type depends + on the configured SOAP client. The page contains the 'totalNumEntries' + key whose value represents the total number of results from making the + query to the AdWords API services. Returns: True if there is still a page left. @@ -2519,10 +2465,20 @@ def HasNext(self, page, page_size=None): """ if self._start_index is None: raise ValueError('Cannot page through query with no LIMIT clause.') + if page is None: + raise ValueError('The passed page cannot be None.') + + # DataService has a different paging mechanism, resulting in different + # method of determining if there is still a page left. + if (self._PAGE_TYPE in page + and page[self._PAGE_TYPE] in self._BID_LANDSCAPE_PAGES): + total_landscape_points = sum([len(bid_landscape[self._LANDSCAPE_POINTS]) + for bid_landscape in page[self._ENTRIES]]) + return total_landscape_points >= self._page_size + if not self._total_num_entries: - self._total_num_entries = page['totalNumEntries'] - increment = self._page_size if page_size is None else page_size - return self._start_index + increment < self._total_num_entries + self._total_num_entries = page[self._TOTAL_NUM_ENTRIES] + return self._start_index + self._page_size < self._total_num_entries def Pager(self, service): """A page generator for this service query and the provided service. diff --git a/googleads/common.py b/googleads/common.py index 2c3df313..1e94b963 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -14,8 +14,12 @@ """Common client library functions and classes used by all products.""" +import abc +import base64 +import binascii from functools import wraps import inspect +from itertools import izip import locale import logging import logging.config @@ -26,11 +30,23 @@ import urllib2 import warnings -import httplib2 -import socks +import lxml.builder +import lxml.etree +import requests.exceptions import suds +import suds.cache +import suds.client +import suds.mx.literal +import suds.plugin import suds.transport.http +import suds.xsd.doctor import yaml +import zeep +import zeep.cache +import zeep.exceptions +import zeep.helpers +import zeep.transports +import zeep.xsd import googleads.errors import googleads.oauth2 import googleads.util @@ -62,11 +78,11 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '10.1.1' +VERSION = '11.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' -_HTTP_PROXY_YAML_KEY = 'http_proxy' -_HTTPS_PROXY_YAML_KEY = 'https_proxy' +_HTTP_PROXY_YAML_KEY = 'http' +_HTTPS_PROXY_YAML_KEY = 'https' _PROXY_CONFIG_KEY = 'proxy_config' _PYTHON_VERSION = 'Python/%d.%d.%d' % ( _PY_VERSION_MAJOR, _PY_VERSION_MINOR, _PY_VERSION_MICRO) @@ -76,26 +92,17 @@ _OAUTH2_INSTALLED_APP_KEYS = ('client_id', 'client_secret', 'refresh_token') # The keys in the authentication dictionary that are used to construct service -# account OAuth2 credentials. This will differ based on the oauth2client -# installation. -if googleads.oauth2.DEPRECATED_OAUTH2CLIENT: - _OAUTH2_SERVICE_ACCT_KEYS = ('service_account_email', - 'path_to_private_key_file') - _OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL = ('delegated_account',) -else: - _OAUTH2_SERVICE_ACCT_KEYS = ('path_to_private_key_file',) - _OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL = ('delegated_account', - 'service_account_email') - -# The keys in the http_proxy and https_proxy dictionaries that are used to -# construct a Proxy, HTTPSProxy, and ProxyConfig instances. -# instance. -_PROXY_KEYS = ('host', 'port') +# account OAuth2 credentials. +_OAUTH2_SERVICE_ACCT_KEYS = ('path_to_private_key_file',) +_OAUTH2_SERVICE_ACCT_KEYS_OPTIONAL = ('delegated_account',) # A key used to configure the client to accept and automatically decompress # gzip encoded SOAP responses. ENABLE_COMPRESSION_KEY = 'enable_compression' +# A key used to specify the SOAP implementation to use. +SOAP_IMPLEMENTATION_KEY = 'soap_impl' + # Global variables used to enable and store utility usage stats. _utility_registry = googleads.util.UtilityRegistry() _UTILITY_REGISTER_YAML_KEY = 'include_utilities_in_user_agent' @@ -114,7 +121,8 @@ def GenerateLibSig(short_name): A library signature string to append to user-supplied user-agent value. """ with _UTILITY_LOCK: - utilities_used = ', '.join([utility for utility in _utility_registry]) + utilities_used = ', '.join([utility for utility + in sorted(_utility_registry)]) _utility_registry.Clear() if utilities_used: @@ -212,6 +220,9 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, client_kwargs[ENABLE_COMPRESSION_KEY] = data.get( ENABLE_COMPRESSION_KEY, False) + if SOAP_IMPLEMENTATION_KEY in data: + client_kwargs[SOAP_IMPLEMENTATION_KEY] = data[SOAP_IMPLEMENTATION_KEY] + for value in optional_product_values: if value in product_data: client_kwargs[value] = product_data[value] @@ -302,11 +313,10 @@ def _ExtractOAuth2Client(product_yaml_key, product_data, proxy_config): del product_data[key] elif all(config in product_data for config in _OAUTH2_SERVICE_ACCT_KEYS): oauth2_args = [ + product_data['path_to_private_key_file'], googleads.oauth2.GetAPIScope(product_yaml_key), ] oauth2_kwargs.update({ - 'client_email': product_data.get('service_account_email'), - 'key_file': product_data['path_to_private_key_file'], 'sub': product_data.get('delegated_account') }) oauth2_client = googleads.oauth2.GoogleServiceAccountClient @@ -344,8 +354,9 @@ def _ExtractProxyConfig(product_yaml_key, proxy_config_data): cafile = proxy_config_data.get('cafile', None) disable_certificate_validation = proxy_config_data.get( 'disable_certificate_validation', False) - http_proxy = _ExtractProxy(_HTTP_PROXY_YAML_KEY, proxy_config_data) - https_proxy = _ExtractProxy(_HTTPS_PROXY_YAML_KEY, proxy_config_data) + + http_proxy = proxy_config_data.get(_HTTP_PROXY_YAML_KEY) + https_proxy = proxy_config_data.get(_HTTPS_PROXY_YAML_KEY) proxy_config = ProxyConfig( http_proxy=http_proxy, https_proxy=https_proxy, @@ -355,42 +366,6 @@ def _ExtractProxyConfig(product_yaml_key, proxy_config_data): return proxy_config -def _ExtractProxy(proxy_yaml_key, proxy_config_data): - """Extracts a ProxyConfig.Proxy from the proxy_config for a given key. - - Args: - proxy_yaml_key: a key specifying the type of proxy for which data is being - loaded. - proxy_config_data: a dict containing the proxy configurations loaded from - the YAML file. - - Returns: - If the proxy_yaml_key exists in the proxy_config_data, this will return a - ProxyConfig.Proxy instance initialized with the data associated with it. - Otherwise, this will return None. - - Raises: - A GoogleAdsValueError if one of the required keys specified by _PROXY_KEYS - is missing. - """ - proxy = None - try: - if proxy_yaml_key in proxy_config_data: - proxy_data = proxy_config_data.get(proxy_yaml_key) - original_proxy_keys = list(proxy_data.keys()) - proxy = ProxyConfig.Proxy(proxy_data['host'], - proxy_data['port'], - username=proxy_data.get('username'), - password=proxy_data.get('password')) - except KeyError: - raise googleads.errors.GoogleAdsValueError( - 'Your yaml file is missing some of the required proxy values. Required ' - 'values are: %s, actual values are %s' % - (_PROXY_KEYS, original_proxy_keys)) - - return proxy - - def _PackForSuds(obj, factory, packer=None): """Packs SOAP input into the format we want for suds. @@ -406,7 +381,7 @@ def _PackForSuds(obj, factory, packer=None): for instances of unpacked dictionaries or lists. factory: The suds.client.Factory object which can create instances of the classes generated from the WSDL. - packer: An optional subclass of googleads.common.SudsPacker that provides + packer: An optional subclass of googleads.common.SoapPacker that provides customized packing logic. Returns: @@ -504,6 +479,16 @@ def IncludeUtilitiesInUserAgent(value): _utility_registry.SetEnabled(value) +def AddToUtilityRegistry(utility_name): + """Directly add a utility to the registry, not a decorator. + + Args: + utility_name: The name of the utility to add. + """ + with _UTILITY_LOCK: + _utility_registry.Add(utility_name) + + def RegisterUtility(utility_name, version_mapping=None): """Decorator that registers a class with the given utility name. @@ -542,8 +527,7 @@ def MethodDecorator(utility_method, version): else utility_name) @wraps(utility_method) def Wrapper(*args, **kwargs): - with _UTILITY_LOCK: - _utility_registry.Add(registry_name) + AddToUtilityRegistry(registry_name) return utility_method(*args, **kwargs) return Wrapper @@ -570,31 +554,17 @@ def __init__(self, http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False): self._http_proxy = http_proxy self._https_proxy = https_proxy - # Initialize httplib2.ProxyInfo used by oauth2client and a proxy option - # dictionary used to generate the urllib2.ProxyHandler used by suds and - # urllib2. For the ProxyInfo object, the HTTPS proxy will always be used - # over the HTTP proxy if it is available. - self.proxy_info = None - self._proxy_option = {} + self.proxies = {} if self._https_proxy: - self.proxy_info = httplib2.ProxyInfo( - socks.PROXY_TYPE_HTTP, self._https_proxy.host, self._https_proxy.port, - proxy_user=self._https_proxy.username, - proxy_pass=self._https_proxy.password) - self._proxy_option['https'] = str(self._https_proxy) + self.proxies['https'] = str(self._https_proxy) if self._http_proxy: - if not self.proxy_info: - self.proxy_info = httplib2.ProxyInfo( - socks.PROXY_TYPE_HTTP, self._http_proxy.host, self._http_proxy.port, - proxy_user=self._http_proxy.username, - proxy_pass=self._http_proxy.password) - self._proxy_option['http'] = str(self._http_proxy) + self.proxies['http'] = str(self._http_proxy) self.disable_certificate_validation = disable_certificate_validation self.cafile = None if disable_certificate_validation else cafile # Initialize the context used to generate the urllib2.HTTPSHandler (in # Python 2.7.9+ and 3.4+) used by suds and urllib2. - self._ssl_context = self._InitSSLContext( + self.ssl_context = self._InitSSLContext( self.cafile, self.disable_certificate_validation) def _InitSSLContext(self, cafile=None, @@ -650,11 +620,11 @@ def GetHandlers(self): """ handlers = [] - if self._ssl_context: - handlers.append(urllib2.HTTPSHandler(context=self._ssl_context)) + if self.ssl_context: + handlers.append(urllib2.HTTPSHandler(context=self.ssl_context)) - if self._proxy_option: - handlers.append(urllib2.ProxyHandler(self._proxy_option)) + if self.proxies: + handlers.append(urllib2.ProxyHandler(self.proxies)) return handlers @@ -670,68 +640,267 @@ def GetSudsProxyTransport(self): """ return self._SudsProxyTransport(self.GetHandlers()) - class Proxy(object): - """Defines settings for a proxy connection.""" - STR_TEMPLATE = '%s:%s' - CRED_TEMPLATE = '%s@%s' +class _ZeepProxyTransport(zeep.transports.Transport): + """A Zeep transport which configures caching, proxy support, and timeouts.""" + def __init__(self, timeout, proxy_config, cache): + """Initializes _ZeepProxyTransport. - def __init__(self, host, port, username=None, password=''): - self.host = host - self.port = port - self.username = username - self.password = password + Args: + timeout: An integer timeout in MS for connections. + proxy_config: A ProxyConfig instance representing proxy settings. + cache: A zeep.cache.Base instance representing a cache strategy to employ. + """ + if not cache: + cache = zeep.cache.SqliteCache() + elif cache == ZeepServiceProxy.NO_CACHE: + cache = None - def __str__(self): - if self.username: - s = self.CRED_TEMPLATE % ( - self.STR_TEMPLATE % ( - self.username, self.password), - self.STR_TEMPLATE % (self.host, self.port)) - else: - s = self.STR_TEMPLATE % (self.host, self.port) - return s + super(_ZeepProxyTransport, self).__init__( + timeout=timeout, operation_timeout=timeout, cache=cache) - class _SudsProxyTransport(suds.transport.http.HttpTransport): - """A transport that applies the given handlers for usage with a proxy.""" + self.session.proxies = proxy_config.proxies - def __init__(self, handlers, **kwargs): - """Initializes SudsHTTPSTransport. - Args: - handlers: an iterable of urllib2.BaseHandler subclasses. - **kwargs: Keyword arguments. - """ - kwargs['timeout'] = 3600 - suds.transport.http.HttpTransport.__init__(self, **kwargs) - self.handlers = handlers +class _SudsProxyTransport(suds.transport.http.HttpTransport): + """A transport that applies the given handlers for usage with a proxy.""" - def u2handlers(self): - """Get a collection of urllib2 handlers to be installed in the opener. + def __init__(self, timeout, proxy_config): + """Initializes SudsHTTPSTransport. - Returns: - A list of handlers to be installed to the OpenerDirector used by suds. - """ - # Start with the default set of handlers. - return_handlers = suds.transport.http.HttpTransport.u2handlers(self) - return_handlers.extend(self.handlers) + Args: + timeout: An integer for the connection timeout time. + proxy_config: A ProxyConfig instance representing proxy settings. + """ + suds.transport.http.HttpTransport.__init__(self, timeout=timeout) + self.handlers = proxy_config.GetHandlers() - return return_handlers + def u2handlers(self): + """Get a collection of urllib2 handlers to be installed in the opener. + Returns: + A list of handlers to be installed to the OpenerDirector used by suds. + """ + # Start with the default set of handlers. + return_handlers = suds.transport.http.HttpTransport.u2handlers(self) + return_handlers.extend(self.handlers) -class SudsPacker(object): - """A utility class to be passed to _PackForSuds for customized packing. + return return_handlers + + +class SoapPacker(object): + """A utility class to be passed to argument packing functions. A subclass should be used in cases where custom logic is needed to pack a - given object in _PackForSuds. + given object in argument packing functions. """ @classmethod def Pack(cls, obj): - raise NotImplementedError('You must subclass SudsPacker.') + raise NotImplementedError('You must subclass SoapPacker.') + +def GetSchemaHelperForLibrary(lib_name): + if lib_name == 'suds': + return SudsSchemaHelper + elif lib_name == 'zeep': + return ZeepSchemaHelper + +class GoogleSchemaHelper(object): + """Base class for type to xml conversion. + + Only used for AdWords reporting specialness. A subclass should be created + for each underlying SOAP implementation. + """ + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod + def GetSoapXMLForComplexType(self, type_name, value): + """Return an XML string representing a SOAP complex type. + + Args: + type_name: The name of the type with namespace prefix if necessary. + value: A python dictionary to hydrate the type instance with. + + Returns: + A string containing the SOAP XML for the type. + """ + return + +class SudsSchemaHelper(GoogleSchemaHelper): + """Suds schema helper implementation.""" + def __init__(self, endpoint, timeout, + proxy_config, namespace_override, cache): + """Initializes a SudsSchemaHelper. + + Args: + endpoint: A string representing the URL to connect to. + timeout: An integer timeout in MS used to determine connection timeouts. + proxy_config: A googleads.common.ProxyConfig instance which represents + the proxy settings needed. + namespace_override: A string to doctor the WSDL namespace with. + cache: An instance of suds.cache.Cache to use for caching. + """ + transport = _SudsProxyTransport(timeout, proxy_config) + try: + doctor = suds.xsd.doctor.ImportDoctor( + suds.xsd.doctor.Import( + namespace_override, endpoint)) + self.suds_client = suds.client.Client( + endpoint, + transport=transport, + plugins=[LoggingMessagePlugin()], + cache=cache, + doctor=doctor) + self._namespace_override = namespace_override + except suds.transport.TransportError as e: + raise googleads.errors.GoogleAdsSoapTransportError(str(e)) + + def GetSoapXMLForComplexType(self, type_name, value): + """Return an XML string representing a SOAP complex type. + + Args: + type_name: The name of the type with namespace prefix if necessary. + value: A python dictionary to hydrate the type instance with. + + Returns: + A string containing the SOAP XML for the type. + """ + schema = self.suds_client.wsdl.schema + definition_type = schema.elements[(type_name, self._namespace_override)] + marshaller = suds.mx.literal.Literal(schema) + content = suds.mx.Content( + tag=type_name, value=value, + name=type_name, type=definition_type) + data = marshaller.process(content) + return data + +class ZeepSchemaHelper(GoogleSchemaHelper): + """Zeep schema helper implementation.""" + def __init__(self, endpoint, timeout, + proxy_config, namespace_override, cache): + """Initializes a ZeepSchemaHelper. + + Args: + endpoint: A string representing the URL to connect to. + timeout: An integer timeout in MS used to determine connection timeouts. + proxy_config: A googleads.common.ProxyConfig instance which represents + the proxy settings needed. + namespace_override: A string to doctor the WSDL namespace with. + cache: An instance of zeep.cache.Base to use for caching. + """ + transport = _ZeepProxyTransport(timeout, proxy_config, cache) + try: + data = transport.load(endpoint) + except requests.exceptions.HTTPError as e: + raise googleads.errors.GoogleAdsSoapTransportError(str(e)) + + self.schema = zeep.xsd.Schema(lxml.etree.fromstring(data)) + self._namespace_override = namespace_override + self._element_maker = lxml.builder.ElementMaker( + namespace=namespace_override, nsmap={'tns': namespace_override}) + + def GetSoapXMLForComplexType(self, type_name, value): + """Return an XML string representing a SOAP complex type. + + Args: + type_name: The name of the type with namespace prefix if necessary. + value: A python dictionary to hydrate the type instance with. + Returns: + A string containing the SOAP XML for the type. + """ + element = self.schema.get_element( + '{%s}%s' % (self._namespace_override, type_name)) + result_element = self._element_maker(element.qname.localname) + element_value = element(**value) + element.type.render(result_element, element_value) + data = lxml.etree.tostring(result_element).strip() + return data + +def GetServiceClassForLibrary(lib_name): + if lib_name == 'suds': + return SudsServiceProxy + elif lib_name == 'zeep': + return ZeepServiceProxy + + +class GoogleSoapService(object): + """Base class for a SOAP service representation. + + A subclass should be created for each underlying SOAP implementation. + """ + __metaclass__ = abc.ABCMeta + + def __init__(self, header_handler, packer): + """Initializes a SOAP service. + + Args: + header_handler: A googleads.common.HeaderHandler instance used to set + SOAP and HTTP headers. + packer: A googleads.common.SoapPacker instance used to transform + entities. + """ + self._header_handler = header_handler + self._packer = packer + self._method_proxies = {} + + + @abc.abstractmethod + def CreateSoapElementForType(self, type_name): + """Create an instance of a SOAP type. -class SudsServiceProxy(object): + Args: + type_name: The name of the type. + + Returns: + An instance of type type_name. + """ + + @abc.abstractmethod + def GetRequestXML(self, method, *args): + """Get the raw SOAP XML for a request. + + Args: + method: The method name. + *args: A list of arguments to be passed to the method. + + Returns: + An element containing the raw XML that would be sent as the request. + """ + + @abc.abstractmethod + def _WsdlHasMethod(self, method_name): + """Determine if the wsdl contains a method. + + Args: + method_name: The name of the method to search. + + Returns: + True if the method is in the WSDL, otherwise False. + """ + + @abc.abstractmethod + def _CreateMethod(self, method_name): + """Create a method wrapping an invocation to the SOAP service. + + Args: + method_name: A string identifying the name of the SOAP method to call. + + Returns: + A callable that can be used to make the desired SOAP request. + """ + + def __getattr__(self, attr): + """Support service.method() syntax.""" + if self._WsdlHasMethod(attr): + if attr not in self._method_proxies: + self._method_proxies[attr] = self._CreateMethod(attr) + return self._method_proxies[attr] + else: + raise googleads.errors.GoogleAdsValueError('Service %s not found' % attr) + + +class SudsServiceProxy(GoogleSoapService): """Wraps a suds service object, allowing custom logic to be injected. This class is responsible for refreshing the HTTP and SOAP headers, so changes @@ -745,30 +914,87 @@ class SudsServiceProxy(object): the client and its factory, """ - def __init__(self, suds_client, header_handler, packer=None): + def __init__(self, endpoint, header_handler, packer, proxy_config, + timeout, cache=None): """Initializes a suds service proxy. Args: - suds_client: The suds.client.Client whose service will be wrapped. Note - that this is the client itself, not the client's embedded service - object. + endpoint: A URL for the service. header_handler: A HeaderHandler responsible for setting the SOAP and HTTP headers on the service client. - packer: An optional subclass of googleads.common.SudsPacker that provides + packer: An optional subclass of googleads.common.SoapPacker that provides customized packing logic. + proxy_config: A ProxyConfig that represents proxy settings. + timeout: An integer to set the connection timeout. + cache: A suds.cache.Cache instance to pass to the underlying SOAP + library for caching. + + Raises: + ValueError: The wrong type was given for caching. """ - self.suds_client = suds_client - self._header_handler = header_handler + super(SudsServiceProxy, self).__init__(header_handler, packer) + + if cache and not isinstance(cache, suds.cache.Cache): + raise ValueError('Must use a proper suds cache with suds.') + + transport = _SudsProxyTransport(timeout, proxy_config) self._method_proxies = {} - self._packer = packer + try: + self.suds_client = suds.client.Client( + endpoint, + timeout=timeout, + cache=cache, + transport=transport, + plugins=[LoggingMessagePlugin()]) + except suds.transport.TransportError as e: + raise googleads.errors.GoogleAdsSoapTransportError(str(e)) - def __getattr__(self, attr): - if attr in self.suds_client.wsdl.services[0].ports[0].methods: - if attr not in self._method_proxies: - self._method_proxies[attr] = self._CreateMethod(attr) - return self._method_proxies[attr] - else: - return getattr(self.suds_client.service, attr) + + def GetRequestXML(self, method, *args): + """Get the raw SOAP XML for a request. + + Args: + method: The method name. + *args: A list of arguments to be passed to the method. + + Returns: + An element containing the raw XML that would be sent as the request. + """ + self.suds_client.set_options(nosend=True) + service_request = (getattr(self, method))(*args).envelope + self.suds_client.set_options(nosend=False) + return lxml.etree.fromstring(service_request) + + def CreateSoapElementForType(self, type_name): + """Create an instance of a SOAP type. + + Args: + type_name: The name of the type. + + Returns: + An instance of type type_name. + """ + return self.suds_client.factory.create(type_name) + + def SetHeaders(self, soap_headers, http_headers): + """Set the headers for the underlying client. + + Args: + soap_headers: A SOAP element for the SOAP headers. + http_headers: A dictionary for the http headers. + """ + self.suds_client.set_options(soapheaders=soap_headers, headers=http_headers) + + def _WsdlHasMethod(self, method_name): + """Determine if the wsdl contains a method. + + Args: + method_name: The name of the method to search. + + Returns: + True if the method is in the WSDL, otherwise False. + """ + return method_name in self.suds_client.wsdl.services[0].ports[0].methods def _CreateMethod(self, method_name): """Create a method wrapping an invocation to the SOAP service. @@ -783,7 +1009,10 @@ def _CreateMethod(self, method_name): def MakeSoapRequest(*args): """Perform a SOAP call.""" - self._header_handler.SetHeaders(self.suds_client) + AddToUtilityRegistry('suds') + self.SetHeaders( + self._header_handler.GetSOAPHeaders(self.CreateSoapElementForType), + self._header_handler.GetHTTPHeaders()) try: return soap_service_method( @@ -797,30 +1026,298 @@ def MakeSoapRequest(*args): _logger.info('SOAP response:\n%s', e.document.str()) if not hasattr(e.fault, 'detail'): - raise + exc = (googleads.errors. + GoogleAdsServerFault(e.document, message=e.fault.faultstring)) + raise exc # Done this way for 2to3 # Before re-throwing the WebFault exception, an error object needs to be # wrapped in a list for safe iteration. fault = e.fault.detail.ApiExceptionFault if not hasattr(fault, 'errors') or fault.errors is None: - e.fault.detail.ApiExceptionFault.errors = [] - raise + exc = (googleads.errors. + GoogleAdsServerFault(e.document, message=e.fault.faultstring)) + raise exc # Done this way for 2to3 obj = fault.errors if not isinstance(obj, list): fault.errors = [obj] - raise + exc = googleads.errors.GoogleAdsServerFault(e.document, fault.errors, + message=e.fault.faultstring) + raise exc # Done this way for 2to3 + + return MakeSoapRequest + + +class _ZeepAuthHeaderPlugin(zeep.Plugin): + """A zeep plugin responsible for setting our custom HTTP headers.""" + + def __init__(self, header_handler): + """Instantiate a new _ZeepAuthHeaderPlugin. + + Args: + header_handler: A googleads.common.HeaderHandler instance. + """ + self._header_handler = header_handler + + def egress(self, envelope, http_headers, operation, binding_options): + """Overriding the egress function to set our headers. + + Args: + envelope: An Element with the SOAP request data. + http_headers: A dict of the current http headers. + operation: The SoapOperation instance. + binding_options: An options dict for the SOAP binding. + + Returns: + A tuple of the envelope and headers. + """ + custom_headers = self._header_handler.GetHTTPHeaders() + http_headers.update(custom_headers) + return envelope, http_headers + + + + +class ZeepServiceProxy(GoogleSoapService): + """Wraps a zeep service object, allowing custom logic to be injected. + + This class is responsible for refreshing the HTTP and SOAP headers, so changes + to the client object will be reflected in future SOAP calls, and for + transforming SOAP call input parameters, allowing dictionary syntax to be used + with all SOAP complex types. + + Attributes: + zeep_client: The zeep.Client this service belongs to. If you are + familiar with zeep, you can utilize this directly. + """ + + NO_CACHE = 'zeep_no_cache' + + def __init__(self, endpoint, header_handler, packer, + proxy_config, timeout, cache=None): + """Initializes a zeep service proxy. + + Args: + endpoint: A URL for the service. + header_handler: A HeaderHandler responsible for setting the SOAP and HTTP + headers on the service client. + packer: An optional subclass of googleads.common.SoapPacker that provides + customized packing logic. + proxy_config: A ProxyConfig that represents proxy settings. + timeout: An integer to set the connection timeout. + cache: An instance of zeep.cache.Base to pass to the underlying SOAP + library for caching. A file cache by default. To disable, pass + googleads.common.ZeepServiceProxy.NO_CACHE. + + Raises: + ValueError: The wrong type was given for caching. + """ + super(ZeepServiceProxy, self).__init__(header_handler, packer) + + if cache and not (isinstance(cache, zeep.cache.Base) or + cache == self.NO_CACHE): + raise ValueError('Must use a proper zeep cache with zeep.') + + transport = _ZeepProxyTransport(timeout, proxy_config, cache) + plugins = [_ZeepAuthHeaderPlugin(header_handler), + googleads.util.ZeepLogger()] + try: + self.zeep_client = zeep.Client( + endpoint, transport=transport, plugins=plugins) + except requests.exceptions.HTTPError as e: + raise googleads.errors.GoogleAdsSoapTransportError(str(e)) + + first_service = list(self.zeep_client.wsdl.services.itervalues())[0] + first_port = list(first_service.ports.itervalues())[0] + self._method_bindings = first_port.binding + + def CreateSoapElementForType(self, type_name): + """Create an instance of a SOAP type. + + Args: + type_name: The name of the type. + + Returns: + An instance of type type_name. + """ + return self.zeep_client.get_type(type_name)() + + def GetRequestXML(self, method, *args): + """Get the raw SOAP XML for a request. + + Args: + method: The method name. + *args: A list of arguments to be passed to the method. + + Returns: + An element containing the raw XML that would be sent as the request. + """ + packed_args = self._PackArguments(method, args, set_type_attrs=True) + headers = self._GetZeepFormattedSOAPHeaders() + + return self.zeep_client.create_message( + self.zeep_client.service, method, *packed_args, _soapheaders=headers) + + def _WsdlHasMethod(self, method_name): + """Determine if a method is in the wsdl. + + Args: + method_name: The name of the method. + + Returns: + True if the method is in the wsdl, otherwise False. + """ + try: + self._method_bindings.get(method_name) + return True + except ValueError: + return False + + def _GetBindingNamespace(self): + """Return a string with the namespace of the service binding in the WSDL.""" + return (list(self.zeep_client.wsdl.bindings.itervalues())[0] + .port_name.namespace) + + def _PackArguments(self, method_name, args, set_type_attrs=False): + """Properly pack input dictionaries for zeep. + + Pack a list of python dictionaries into XML objects. Dictionaries which + contain an 'xsi_type' entry are converted into that type instead of the + argument default. This allows creation of complex objects which include + inherited types. + + Args: + method_name: The name of the method that will be called. + args: A list of dictionaries containing arguments to the method. + set_type_attrs: A boolean indicating whether or not attributes that end + in .Type should be set. This is only necessary for batch job service. + + Returns: + A list of XML objects that can be passed to zeep. + """ + # Get the params for the method to find the initial types to instantiate. + op_params = self.zeep_client.get_element( + '{%s}%s' % (self._GetBindingNamespace(), method_name)).type.elements + result = [self._PackArgumentsHelper(param, param_data, set_type_attrs) + for ((_, param), param_data) in izip(op_params, args)] + return result + + @classmethod + def _IsBase64(cls, s): + """An imperfect but decent method for determining if a string is base64. + + Args: + s: A string with the data to test. + + Returns: + True if s is base64, else False. + """ + try: + if base64.b64encode(base64.b64decode(s)).decode('utf-8') == s: + return True + except (TypeError, binascii.Error): + pass + return False + + def _PackArgumentsHelper(self, elem, data, set_type_attrs): + """Recursive helper for PackArguments. + + Args: + elem: The element type we are creating. + data: The data to instantiate it with. + set_type_attrs: A boolean indicating whether or not attributes that end + in .Type should be set. This is only necessary for batch job service. + + Returns: + An instance of type 'elem'. + """ + if self._packer: + data = self._packer.Pack(data) + + if isinstance(data, dict): # Dict so it's a complex type. + xsi_type = data.get('xsi_type') + if xsi_type: # This has a type override so look it up. + elem_type = self.zeep_client.get_type( + '{%s}%s' % (self._GetBindingNamespace(), xsi_type)) + else: + elem_type = elem.type + elem_arguments = dict(elem_type.elements) + # A post order traversal of the original data, need to instantiate from + # the bottom up. + instantiated_arguments = { + k: self._PackArgumentsHelper(elem_arguments[k], v, set_type_attrs) + for k, v in data.iteritems() if k != 'xsi_type'} + if set_type_attrs: + found_type_attr = next((e_name for e_name, _ in elem_type.elements + if e_name.endswith('.Type')), None) + if found_type_attr: + instantiated_arguments[found_type_attr] = xsi_type + # Now go back through the tree instantiating SOAP types as we go. + return elem_type(**instantiated_arguments) + elif isinstance(data, (list, tuple)): + return [self._PackArgumentsHelper(elem, item, set_type_attrs) + for item in data] + else: + if elem.type.name == 'base64Binary' and self._IsBase64(data): + _logger.warn('Passing data to base64 field %s that may ' + 'already be encoded. Do not pre-encode base64 ' + 'fields with zeep.', elem.name) + return data + + def _GetZeepFormattedSOAPHeaders(self): + """Returns a dict with SOAP headers in the right format for zeep.""" + headers = self._header_handler.GetSOAPHeaders(self.CreateSoapElementForType) + soap_headers = {'RequestHeader': headers} + return soap_headers + + def _CreateMethod(self, method_name): + """Create a method wrapping an invocation to the SOAP service. + + Args: + method_name: A string identifying the name of the SOAP method to call. + + Returns: + A callable that can be used to make the desired SOAP request. + """ + soap_service_method = self.zeep_client.service[method_name] + + def MakeSoapRequest(*args): + AddToUtilityRegistry('zeep') + soap_headers = self._GetZeepFormattedSOAPHeaders() + packed_args = self._PackArguments(method_name, args) + try: + return soap_service_method( + *packed_args, _soapheaders=soap_headers)['body']['rval'] + except zeep.exceptions.Fault as e: + error_list = () + if e.detail is not None: + underlying_exception = e.detail.find( + '{%s}ApiExceptionFault' % self._GetBindingNamespace()) + fault_type = self.zeep_client.get_element( + '{%s}ApiExceptionFault' % self._GetBindingNamespace()) + fault = fault_type.parse( + underlying_exception, self.zeep_client.wsdl.types) + error_list = fault.errors or error_list + raise googleads.errors.GoogleAdsServerFault( + e.detail, errors=error_list, message=e.message) return MakeSoapRequest class HeaderHandler(object): """A generic header handler interface that must be subclassed by each API.""" - def SetHeaders(self, client): - """Sets the SOAP and HTTP headers on the given suds client.""" - raise NotImplementedError('You must subclass HeaderHandler.') + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod + def GetSOAPHeaders(self, create_method): + """Returns the required SOAP Headers.""" + + @abc.abstractmethod + def GetHTTPHeaders(self): + """Returns the required HTTP headers.""" + class LoggingMessagePlugin(suds.plugin.MessagePlugin): diff --git a/googleads/dfp.py b/googleads/dfp.py index 8269b202..1e414ee7 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -25,8 +25,6 @@ import urllib2 import pytz -import suds.client -import suds.transport import googleads.common import googleads.errors @@ -204,7 +202,7 @@ def LoadFromStorage(cls, path=None): cls._OPTIONAL_INIT_VALUES)) def __init__(self, oauth2_client, application_name, network_code=None, - cache=None, proxy_config=None, + cache=None, proxy_config=None, soap_impl='zeep', timeout=3600, enable_compression=False): """Initializes a DfpClient. @@ -220,10 +218,14 @@ def __init__(self, oauth2_client, application_name, network_code=None, network_code: A string identifying the network code of the network you are accessing. All requests other than getAllNetworks require this header to be set. - cache: A subclass of suds.cache.Cache. If not set, this will default to an - instance of suds.cache.ObjectCache. + cache: A subclass of zeep.cache.Base or suds.cache.Cache. If not set, + this will default to a basic file cache. To disable caching for Zeep, + pass googleads.common.ZeepServiceProxy.NO_CACHE. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. + soap_impl: A string identifying which SOAP implementation to use. The + options are 'zeep' or 'suds'. + timeout: An integer timeout in MS for connections made to DFP. enable_compression: A boolean indicating if you want to enable compression of the SOAP response. If True, the SOAP response will use gzip compression, and will be decompressed for you automatically. @@ -246,7 +248,8 @@ def __init__(self, oauth2_client, application_name, network_code=None, if enable_compression: self.application_name = '%s (gzip)' % self.application_name - self.message_plugin = googleads.common.LoggingMessagePlugin() + self.soap_impl = soap_impl + self.timeout = timeout def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], @@ -263,8 +266,8 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server: A string identifying the webserver hosting the DFP API. Returns: - A suds.client.ServiceSelector which has the headers and proxy configured - for use. + A googleads.common.GoogleSoapService instance which has the headers + and proxy configured for use. Raises: A GoogleAdsValueError if the service or version provided do not exist. @@ -274,19 +277,17 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server = server[:-1] if server[-1] == '/' else server - kwargs = {'timeout': 3600, - 'transport': self.proxy_config.GetSudsProxyTransport(), - 'plugins': [self.message_plugin]} - - if self.cache: - kwargs['cache'] = self.cache - try: - client = suds.client.Client( + service = googleads.common.GetServiceClassForLibrary(self.soap_impl)( self._SOAP_SERVICE_FORMAT % (server, version, service_name), - **kwargs) - - except suds.transport.TransportError: + self._header_handler, + _DfpPacker, + self.proxy_config, + self.timeout, + cache=self.cache) + + return service + except googleads.errors.GoogleAdsSoapTransportError: if version in _SERVICE_MAP: if service_name in _SERVICE_MAP[version]: raise @@ -300,9 +301,6 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], 'Unrecognized version of the DFP API. Version given: %s Supported ' 'versions: %s' % (version, _SERVICE_MAP.keys())) - return googleads.common.SudsServiceProxy(client, self._header_handler, - packer=_DfpPacker) - def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): """Creates a downloader for DFP reports and PQL result sets. @@ -332,7 +330,7 @@ class _DfpHeaderHandler(googleads.common.HeaderHandler): # The library signature for DFP, to be appended to all application_names. _PRODUCT_SIG = 'DfpApi-Python' # The name of the WSDL-defined SOAP Header class used in all requests. - _SOAP_HEADER_CLASS = 'SoapRequestHeader' + _SOAP_HEADER_CLASS = 'ns0:SoapRequestHeader' def __init__(self, dfp_client, enable_compression): """Initializes a DfpHeaderHandler. @@ -348,24 +346,37 @@ def __init__(self, dfp_client, enable_compression): self._dfp_client = dfp_client self.enable_compression = enable_compression - def SetHeaders(self, suds_client): - """Sets the SOAP and HTTP headers on the given suds client.""" - header = suds_client.factory.create(self._SOAP_HEADER_CLASS) + def GetSOAPHeaders(self, create_method): + """Returns the SOAP headers required for request authorization. + + Args: + create_method: The SOAP library specific method used to instantiate SOAP + objects. + + Returns: + A SOAP object containing the headers. + """ + header = create_method(self._SOAP_HEADER_CLASS) header.networkCode = self._dfp_client.network_code header.applicationName = ''.join([ self._dfp_client.application_name, googleads.common.GenerateLibSig(self._PRODUCT_SIG)]) + return header + def GetHTTPHeaders(self): + """Returns the HTTP headers required for request authorization. + + Returns: + A dictionary containing the required headers. + """ http_headers = self._dfp_client.oauth2_client.CreateHttpHeader() if self.enable_compression: http_headers['accept-encoding'] = 'gzip' - suds_client.set_options( - soapheaders=header, - headers=http_headers) + return http_headers -class _DfpPacker(googleads.common.SudsPacker): +class _DfpPacker(googleads.common.SoapPacker): """A utility applying customized packing logic for DFP.""" @classmethod @@ -373,11 +384,11 @@ def Pack(cls, obj): """Pack the given object using DFP-specific logic. Args: - obj: an object to be packed for suds using DFP-specific logic, if + obj: an object to be packed for SOAP using DFP-specific logic, if applicable. Returns: - The given object packed with DFP-specific logic for suds, if applicable. + The given object packed with DFP-specific logic for SOAP, if applicable. Otherwise, returns the given object unmodified. """ if isinstance(obj, (datetime.datetime, datetime.date)): @@ -719,7 +730,8 @@ def __init__(self, dfp_client, version=sorted(_SERVICE_MAP.keys())[-1], self._report_service = None self._pql_service = None self.proxy_config = self._dfp_client.proxy_config - self.url_opener = urllib2.build_opener(*self.proxy_config.GetHandlers()) + handlers = self.proxy_config.GetHandlers() + self.url_opener = urllib2.build_opener(*handlers) def _GetReportService(self): """Lazily initializes a report service client.""" @@ -740,7 +752,7 @@ def WaitForReport(self, report_job): Args: report_job: The report job to wait for. This may be a dictionary or an - instance of the suds-generated ReportJob class. + instance of the SOAP ReportJob class. Returns: The completed report job's ID as a string. diff --git a/googleads/errors.py b/googleads/errors.py index 89252f40..3aec1374 100644 --- a/googleads/errors.py +++ b/googleads/errors.py @@ -25,6 +25,20 @@ class GoogleAdsValueError(GoogleAdsError): pass +class GoogleAdsSoapTransportError(GoogleAdsError): + pass + + +class GoogleAdsServerFault(GoogleAdsError): + + def __init__(self, document, errors=(), message=None): + super(GoogleAdsServerFault, self).__init__( + message if message else 'Server Error') + + self.errors = errors + self.document = document + + class AdWordsReportError(GoogleAdsError): """Error indicating that an AdWords report download request failed. diff --git a/googleads/oauth2.py b/googleads/oauth2.py index b26a763a..7bb76540 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -23,23 +23,11 @@ from independently refreshing the credentials. """ -import datetime - - import googleads.errors -import httplib2 -import oauth2client.client - -if oauth2client.__version__ >= '4.0.0': - import oauth2client.service_account - DEPRECATED_OAUTH2CLIENT = False -elif (oauth2client.__version__ >= '1.4.12' and - oauth2client.__version__ < '2.0.0'): - DEPRECATED_OAUTH2CLIENT = True -else: - raise googleads.errors.GoogleAdsError( - 'Unsupported version of oauth2client is installed. To use this library, ' - 'upgrade to oauth2client 4.0.0.') +import requests +import google.auth.transport.requests +import google.oauth2.credentials +import google.oauth2.service_account # The scopes used for authorizing with the APIs supported by this library. @@ -73,9 +61,6 @@ class GoogleOAuth2Client(object): """An OAuth2 client for use with Google APIs.""" # The web address for generating OAuth2 credentials at Google. _GOOGLE_OAUTH2_ENDPOINT = 'https://accounts.google.com/o/oauth2/token' - # We will refresh an OAuth2 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE - # minutes in advance of its expiration. - _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5 # The placeholder URL is used when adding the access token to our request. A # well-formed URL is required, but since we're using HTTP header placement for # the token, this URL is completely unused. @@ -126,9 +111,9 @@ def __init__(self, access_token, token_expiry): token_expiry: A datetime instance indicating when the given access token expires. """ - self.oauth2credentials = oauth2client.client.OAuth2Credentials( - access_token, None, None, None, token_expiry, - self._GOOGLE_OAUTH2_ENDPOINT, self._USER_AGENT) + self.creds = google.oauth2.credentials.Credentials( + token=access_token) + self.creds.expiry = token_expiry def CreateHttpHeader(self): """Creates an OAuth2 HTTP header. @@ -146,11 +131,10 @@ def CreateHttpHeader(self): """ oauth2_header = {} - if (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() - < datetime.timedelta(0)): + if self.creds.expired: raise googleads.errors.GoogleAdsError('Access token has expired.') - self.oauth2credentials.apply(oauth2_header) + self.creds.apply(oauth2_header) return oauth2_header @@ -182,10 +166,11 @@ def __init__(self, client_id, client_secret, refresh_token, **kwargs): proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. """ - self.oauth2credentials = oauth2client.client.OAuth2Credentials( - kwargs.get('access_token'), client_id, client_secret, refresh_token, - kwargs.get('token_expiry', datetime.datetime(1980, 1, 1, 12)), - self._GOOGLE_OAUTH2_ENDPOINT, self._USER_AGENT) + self.creds = google.oauth2.credentials.Credentials( + kwargs.get('access_token'), refresh_token=refresh_token, + client_id=client_id, client_secret=client_secret, + token_uri=self._GOOGLE_OAUTH2_ENDPOINT) + self.creds.expiry = kwargs.get('token_expiry') self.proxy_config = kwargs.get('proxy_config', googleads.common.ProxyConfig()) @@ -201,29 +186,29 @@ def CreateHttpHeader(self): 'Authorization' key. Raises: - AccessTokenRefreshError: If the refresh fails. + google.auth.exceptions.RefreshError: If the refresh fails. """ oauth2_header = {} - if (self.oauth2credentials.token_expiry is not None and - (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() < - datetime.timedelta(minutes=self._OAUTH2_REFRESH_MINUTES_IN_ADVANCE))): + if self.creds.expiry is None or self.creds.expired: self.Refresh() - self.oauth2credentials.apply(oauth2_header) + self.creds.apply(oauth2_header) return oauth2_header def Refresh(self): """Uses the Refresh Token to retrieve and set a new Access Token. Raises: - AccessTokenRefreshError: If the refresh fails. + google.auth.exceptions.RefreshError: If the refresh fails. """ - self.oauth2credentials.refresh(httplib2.Http( - proxy_info=self.proxy_config.proxy_info, - ca_certs=self.proxy_config.cafile, - disable_ssl_certificate_validation=( - self.proxy_config.disable_certificate_validation))) + with requests.Session() as session: + session.proxies = self.proxy_config.proxies + session.verify = not self.proxy_config.disable_certificate_validation + session.cert = self.proxy_config.cafile + + self.creds.refresh( + google.auth.transport.requests.Request(session=session)) class GoogleServiceAccountClient(GoogleRefreshableOAuth2Client): @@ -236,25 +221,17 @@ class GoogleServiceAccountClient(GoogleRefreshableOAuth2Client): Attributes: proxy_info: A ProxyInfo instance used for refresh requests. """ - # We will refresh an OAuth2 credential _OAUTH2_REFRESH_MINUTES_IN_ADVANCE - # minutes in advance of its expiration. - _OAUTH2_REFRESH_MINUTES_IN_ADVANCE = 5 _USER_AGENT = 'Google Ads Python Client Library' _FILE_NOT_FOUND_TEMPLATE = 'The specified key file (%s) does not exist.' - def __init__(self, scope, client_email=None, key_file=None, - private_key_password='notasecret', sub=None, proxy_config=None): + def __init__(self, key_file, scope, sub=None, proxy_config=None): """Initializes a GoogleServiceAccountClient. Args: + key_file: A string containing the path to your Service Account + JSON key file. scope: The scope of the API you're authorizing for. - client_email: A string containing your Service Account's email. If this is - set when using oauth2client 4.0.0, it will be assumed that you are - providing a P12 key file. A JSON key file does not require a client - email. - key_file: A string containing the path to your key file. [optional] - private_key_password: A string containing the password for your key file. sub: A string containing the email address of a user account you want to impersonate. proxy_config: A googleads.common.ProxyConfig instance. @@ -263,45 +240,13 @@ def __init__(self, scope, client_email=None, key_file=None, GoogleAdsError: If an unsupported version of oauth2client is installed. GoogleAdsValueError: If the given key file does not exist. """ - if DEPRECATED_OAUTH2CLIENT: - # Instantiate credentials using oauth2client version < 2.0.0. - try: - with open(key_file, 'rb') as f: - private_key = f.read() - except IOError: - raise googleads.errors.GoogleAdsValueError( - self._FILE_NOT_FOUND_TEMPLATE % key_file) - - self.oauth2credentials = ( - oauth2client.client.SignedJwtAssertionCredentials( - client_email, private_key, scope, - private_key_password=private_key_password, - user_agent=self._USER_AGENT, - token_uri=self._GOOGLE_OAUTH2_ENDPOINT, - sub=sub)) - else: - # Instantiate credentials using oauth2client 4.0.0. - if client_email: - # Instantiate credentials for P12 key file. - try: - self.oauth2credentials = ( - oauth2client.service_account.ServiceAccountCredentials - .from_p12_keyfile(client_email, key_file, scopes=scope)) - except IOError: - raise googleads.errors.GoogleAdsValueError( - self._FILE_NOT_FOUND_TEMPLATE % key_file) - else: - # Instantiate credentials for JSON key file. - try: - self.oauth2credentials = ( - oauth2client.service_account.ServiceAccountCredentials - .from_json_keyfile_name(key_file, scopes=scope)) - except IOError: - raise googleads.errors.GoogleAdsValueError( - self._FILE_NOT_FOUND_TEMPLATE % key_file) - # If sub is specified, apply it for domain-wide delegation of authority. - if sub: - self.oauth2credentials = self.oauth2credentials.create_delegated(sub) + try: + self.creds = ( + google.oauth2.service_account.Credentials.from_service_account_file( + key_file, scopes=[scope], subject=sub)) + except IOError: + raise googleads.errors.GoogleAdsValueError( + self._FILE_NOT_FOUND_TEMPLATE % key_file) self.proxy_config = (proxy_config if proxy_config else googleads.common.ProxyConfig()) @@ -319,26 +264,26 @@ def CreateHttpHeader(self): 'Authorization' key. Raises: - AccessTokenRefreshError: If the refresh fails. + google.auth.exceptions.RefreshError: If the refresh fails. """ oauth2_header = {} - if (self.oauth2credentials.token_expiry is not None and - (self.oauth2credentials.token_expiry - datetime.datetime.utcnow() < - datetime.timedelta(minutes=self._OAUTH2_REFRESH_MINUTES_IN_ADVANCE))): + if self.creds.expiry is None or self.creds.expired: self.Refresh() - self.oauth2credentials.apply(oauth2_header) + self.creds.apply(oauth2_header) return oauth2_header def Refresh(self): """Retrieve and set a new Access Token. Raises: - AccessTokenRefreshError: If the refresh fails. + google.auth.exceptions.RefreshError: If the refresh fails. """ - self.oauth2credentials.refresh(httplib2.Http( - proxy_info=self.proxy_config.proxy_info, - ca_certs=self.proxy_config.cafile, - disable_ssl_certificate_validation=( - self.proxy_config.disable_certificate_validation))) + with requests.Session() as session: + session.proxies = self.proxy_config.proxies + session.verify = not self.proxy_config.disable_certificate_validation + session.cert = self.proxy_config.cafile + + self.creds.refresh( + google.auth.transport.requests.Request(session=session)) diff --git a/googleads/util.py b/googleads/util.py index 4b9ab013..83158969 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -23,7 +23,11 @@ import urllib2 +from lxml import etree import suds +import suds.mx +import suds.mx.appender +import zeep _COMMON_FILTER = None @@ -152,9 +156,11 @@ def PatchedHttpTransportSend(self, request): class _AbstractDevTokenSOAPFilter(logging.Filter): """Interface for sanitizing logs containing SOAP request/response data.""" - _AUTHORIZATION_HEADER = 'Authorization' + _AUTHORIZATION_HEADER = 'authorization' _DEVELOPER_TOKEN_SUB = re.compile( - r'(?<=\).*?(?=\)') + r'(?<=\<(?:tns|ns0):developerToken\>)' + r'.*?' + r'(?=\)') _REDACTED = 'REDACTED' def filter(self, record): @@ -188,6 +194,7 @@ def filter(self, record): sanitized_headers = record.args.copy() if self._AUTHORIZATION_HEADER in sanitized_headers: sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED + sanitized_headers.pop(self._AUTHORIZATION_HEADER.capitalize(), None) record.args = sanitized_headers return True @@ -294,16 +301,99 @@ def filter(self, record): sanitized_headers = arg.headers.copy() if self._AUTHORIZATION_HEADER in sanitized_headers: sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED + sanitized_headers.pop(self._AUTHORIZATION_HEADER.capitalize(), None) new_arg.headers = sanitized_headers - msg = arg.message - if sys.version_info.major < 3: - msg = msg.decode('utf-8') new_arg.message = self._DEVELOPER_TOKEN_SUB.sub( - self._REDACTED, msg) + self._REDACTED, arg.message.decode('utf-8')) record.args = (new_arg,) return True +_RESPONSE_XML_LOG_LINE = 'Incoming response: \n%s' +_REQUEST_LOG_LINE = 'Request made: Service: "%s" Method: "%s" URL: "%s"' +_REQUEST_XML_LOG_LINE = 'Outgoing request: %s\n%s' +_SOAP_NAMESPACE = 'http://schemas.xmlsoap.org/soap/envelope/' +_FAULT_XPATH = './/{%s}Fault' % _SOAP_NAMESPACE +_HEADER_XPATH = './/{%s}Header' % _SOAP_NAMESPACE +_REMOVE_NS_REGEXP = re.compile(r'^\{.*?\}') + + +class ZeepLogger(zeep.Plugin, _AbstractDevTokenSOAPFilter): + """Log zeep request/response data while removing sensitive information.""" + + def __init__(self): + """Instantiates a new ZeepLogger.""" + super(_AbstractDevTokenSOAPFilter, self).__init__() + self._logger = logging.getLogger('googleads.soap') + + def ingress(self, envelope, http_headers, operation): + """Overrides the ingress function for response logging. + + Args: + envelope: An Element with the SOAP request data. + http_headers: A dict of the current http headers. + operation: The SoapOperation instance. + + Returns: + A tuple of the envelope and headers. + """ + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.debug(_RESPONSE_XML_LOG_LINE, + etree.tostring(envelope, pretty_print=True)) + + if self._logger.isEnabledFor(logging.WARN): + warn_data = {} + header = envelope.find(_HEADER_XPATH) + fault = envelope.find(_FAULT_XPATH) + if fault is not None: + warn_data['faultMessage'] = fault.find('faultstring').text + + if header is not None: + header_data = { + re.sub(_REMOVE_NS_REGEXP, '', child.tag): child.text + for child in header[0]} + warn_data.update(header_data) + + if 'serviceName' not in warn_data: + warn_data['serviceName'] = operation.binding.wsdl.services.keys()[0] + + if 'methodName' not in warn_data: + warn_data['methodName'] = operation.name + + self._logger.warn('Error summary: %s', warn_data) + + return envelope, http_headers + + def egress(self, envelope, http_headers, operation, binding_options): + """Overrides the egress function ror request logging. + + Args: + envelope: An Element with the SOAP request data. + http_headers: A dict of the current http headers. + operation: The SoapOperation instance. + binding_options: An options dict for the SOAP binding. + + Returns: + A tuple of the envelope and headers. + """ + if self._logger.isEnabledFor(logging.INFO): + service_name = operation.binding.wsdl.services.keys()[0] + self._logger.info(_REQUEST_LOG_LINE, service_name, operation.name, + binding_options['address']) + + if self._logger.isEnabledFor(logging.DEBUG): + http_headers_safe = http_headers.copy() + if self._AUTHORIZATION_HEADER in http_headers_safe: + http_headers_safe[self._AUTHORIZATION_HEADER] = self._REDACTED + + request_string = etree.tostring(envelope, pretty_print=True) + safe_request = self._DEVELOPER_TOKEN_SUB.sub( + self._REDACTED, request_string.decode('utf-8')) + self._logger.debug( + _REQUEST_XML_LOG_LINE, http_headers_safe, safe_request) + + return envelope, http_headers + class UtilityRegistry(object): """Utility that registers product utilities used in generating a request.""" diff --git a/setup.py b/setup.py index f453fad2..5ffa6319 100755 --- a/setup.py +++ b/setup.py @@ -24,9 +24,11 @@ PACKAGES = ['googleads'] -DEPENDENCIES = ['httplib2>=0.9.2,<1.0.0', 'oauth2client>=4.0.0,<5.0.0', - 'suds-jurko>=0.6,<0.7', 'pysocks>=1.5.6,<2.0.0', 'pytz>=2015.7', - 'PyYAML>=3.11,<4.0', 'xmltodict>=0.9.2,<1.0.0'] +DEPENDENCIES = ['google-auth>=1.0.0,<2.0.0', + 'google-auth-oauthlib>=0.0.1,<1.0.0', 'pytz>=2015.7', + 'PyYAML>=3.11,<4.0', 'requests>=2.0.0,<3.0.0', + 'suds-jurko>=0.6,<0.7', 'xmltodict>=0.9.2,<1.0.0', + 'zeep>=2.5.0'] # Note: Breaking change introduced in pyfakefs 3.3. TEST_DEPENDENCIES = ['mock>=2.0.0,<3.0.0', 'pyfakefs>=3.2,<3.3', diff --git a/tests/adwords_test.py b/tests/adwords_test.py index da380225..c9d6ca3b 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -27,22 +27,30 @@ import googleads.adwords import googleads.common import googleads.errors +import lxml.etree import mock import six import suds +import yaml +import yaml +import zeep.transports from . import testing +try: + import urllib2 +except ImportError: + import urllib.request as urllib2 # For Py3 - -URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] +TEST_DIR = os.path.dirname(__file__) -def GetAdWordsClient(**kwargs): +def GetAdWordsClient(soap_impl, **kwargs): """Returns an initialized AdwordsClient for use in testing. If not specified, the keyword arguments will be set to default test values. Args: + soap_impl: The SOAP implementation to pass to the client. **kwargs: Optional keyword arguments that can be provided to customize the generated AdWordsClient. Keyword Arguments: @@ -55,6 +63,7 @@ def GetAdWordsClient(**kwargs): report_downloader_headers: A dict containing optional report downloader headers. user_agent: A str value for the AdWordsClient's user_agent. + timeout: An integer timeout in MS for connections. Returns: An AdWordsClient instance intended for testing. @@ -65,6 +74,7 @@ def GetAdWordsClient(**kwargs): validate_only = kwargs.get('validate_only', False) partial_failure = kwargs.get('partial_failure', False) report_downloader_headers = kwargs.get('report_downloader_headers', {}) + timeout = kwargs.get('timeout', 3600) if 'oauth2_client' in kwargs: oauth2_client = kwargs['oauth2_client'] @@ -79,25 +89,23 @@ def GetAdWordsClient(**kwargs): cache=kwargs.get('cache'), proxy_config=kwargs.get('proxy_config'), validate_only=validate_only, partial_failure=partial_failure, - report_downloader_headers=report_downloader_headers) + report_downloader_headers=report_downloader_headers, + soap_impl=soap_impl, timeout=timeout) return client -def GetProxyConfig(http_host=None, http_port=None, https_host=None, - https_port=None, cafile=None, +def GetProxyConfig(http_proxy_uri=None, https_proxy_uri=None, cafile=None, disable_certificate_validation=None): """Returns an initialized ProxyConfig for use in testing. Args: - http_host: A str containing the url or IP of an http proxy host. If this is - not specified, the ProxyConfig will be initialized without an HTTP proxy - configured. - http_port: An int port number for the HTTP proxy host. - https_host: A str containing the url or IP of an https proxy host. If this - is not specified, the ProxyConfig will be initialized without an HTTPS - proxy configured. - https_port: An int port number for the HTTPS proxy host. + http_proxy_uri: A str containing the full URI for the http proxy host. If + this is not specified, the ProxyConfig will be initialized without an + HTTP proxy configured. + https_proxy_uri: A str containing the full URI for the https proxy host. If + this is not specified, the ProxyConfig will be initialized without an + HTTPS proxy configured. cafile: A str containing the path to a custom ca file. disable_certificate_validation: A boolean indicating whether or not to disable certificate validation. @@ -105,17 +113,8 @@ def GetProxyConfig(http_host=None, http_port=None, https_host=None, Returns: An initialized ProxyConfig using the given configurations. """ - http_proxy = None - https_proxy = None - - if http_host: - http_proxy = googleads.common.ProxyConfig.Proxy(http_host, http_port) - - if https_host: - https_proxy = googleads.common.ProxyConfig.Proxy(https_host, https_port) - return googleads.common.ProxyConfig( - http_proxy, https_proxy, cafile=cafile, + http_proxy_uri, https_proxy_uri, cafile=cafile, disable_certificate_validation=disable_certificate_validation) @@ -137,9 +136,9 @@ def setUp(self): self.default_sig_template = ' (%s, %s, %s)' self.util_sig_template = ' (%s, %s, %s, %s)' self.aw_client = GetAdWordsClient( - ccid=self.ccid, dev_token=self.dev_token, user_agent=self.user_agent, - oauth2_client=self.oauth2_client, validate_only=self.validate_only, - partial_failure=self.partial_failure, + 'zeep', ccid=self.ccid, dev_token=self.dev_token, + user_agent=self.user_agent, oauth2_client=self.oauth2_client, + validate_only=self.validate_only, partial_failure=self.partial_failure, report_downloader_headers=self.report_downloader_headers) self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.aw_client, CURRENT_VERSION, self.enable_compression) @@ -152,14 +151,18 @@ def Test(self): self.test_utility = TestUtility() - def testSetHeaders(self): - suds_client = mock.Mock() - self.header_handler.SetHeaders(suds_client) + def testGetHTTPHeaders(self): + header_result = self.header_handler.GetHTTPHeaders() + # Check that the returned headers have the correct values. + self.assertEqual(header_result, self.oauth_header) + + def testGetSOAPHeaders(self): + create_method = mock.Mock() + soap_header = self.header_handler.GetSOAPHeaders(create_method) # Check that the SOAP header has the correct values. - suds_client.factory.create.assert_called_once_with( + create_method.assert_called_once_with( '{https://adwords.google.com/api/adwords/cm/%s}SoapHeader' % CURRENT_VERSION) - soap_header = suds_client.factory.create.return_value self.assertEqual(self.ccid, soap_header.clientCustomerId) self.assertEqual(self.dev_token, soap_header.developerToken) self.assertEqual( @@ -169,18 +172,14 @@ def testSetHeaders(self): soap_header.userAgent) self.assertEqual(self.validate_only, soap_header.validateOnly) self.assertEqual(self.partial_failure, soap_header.partialFailure) - # Check that the suds client has the correct values. - suds_client.set_options.assert_any_call( - soapheaders=soap_header, headers=self.oauth_header) - def testSetHeadersUserAgentWithUtility(self): - suds_client = mock.Mock() + def testGetHeadersUserAgentWithUtility(self): + create_method = mock.Mock() with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: self.test_utility.Test() # This will register TestUtility. - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value + soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( ''.join([self.user_agent, @@ -192,15 +191,14 @@ def testSetHeadersUserAgentWithUtility(self): ]), soap_header.userAgent) - def testSetHeadersUserAgentWithAndWithoutUtility(self): - suds_client = mock.Mock() + def testGetHeadersUserAgentWithAndWithoutUtility(self): + create_method = mock.Mock() with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: # Check headers when utility registered. self.test_utility.Test() # This will register TestUtility. - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value + soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( ''.join([self.user_agent, @@ -213,8 +211,7 @@ def testSetHeadersUserAgentWithAndWithoutUtility(self): soap_header.userAgent) # Check headers when no utility should be registered. - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value + soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( ''.join([self.user_agent, self.default_sig_template % ( @@ -226,8 +223,7 @@ def testSetHeadersUserAgentWithAndWithoutUtility(self): # Verify that utility is registered in subsequent uses. self.test_utility.Test() # This will register TestUtility. - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value + soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( ''.join([self.user_agent, @@ -341,15 +337,12 @@ class AdWordsClientTest(unittest.TestCase): def setUp(self): self.load_from_storage_path = os.path.join( os.path.dirname(__file__), 'test_data/adwords_googleads.yaml') - self.https_proxy_host = 'myproxy' - self.https_proxy_port = 443 - self.proxy_config = GetProxyConfig(https_host=self.https_proxy_host, - https_port=self.https_proxy_port) + self.https_proxy_uri = 'http://myproxy:443' + self.proxy_config = GetProxyConfig(https_proxy_uri=self.https_proxy_uri) self.file_cache = suds.cache.FileCache self.no_cache = suds.cache.NoCache() - self.adwords_client = GetAdWordsClient() - self.aw_client = GetAdWordsClient( - proxy_config=self.proxy_config) + self.adwords_client = GetAdWordsClient('zeep') + self.aw_client = GetAdWordsClient('zeep', proxy_config=self.proxy_config) self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.adwords_client, CURRENT_VERSION, False) @@ -357,8 +350,7 @@ def setUp(self): def testLoadFromStorage(self): with mock.patch('googleads.oauth2.GoogleRefreshTokenClient.Refresh'): self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage( - path=self.load_from_storage_path), - googleads.adwords.AdWordsClient) + path=self.load_from_storage_path), googleads.adwords.AdWordsClient) def testLoadFromStorageWithCompressionEnabled(self): enable_compression = True @@ -395,109 +387,42 @@ def testLoadFromStorageWithNoUserAgent(self): } client = googleads.adwords.AdWordsClient.LoadFromStorage() - self.assertEquals(client.user_agent, 'unknown') + self.assertEqual(client.user_agent, 'unknown') def testGetService_success(self): - service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] - namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] - # Use a custom server. Also test what happens if the server ends with a - # trailing slash - server = 'https://testing.test.com/' - - with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: - with mock.patch('googleads.adwords._AdWordsHeaderHandler') as mock_awhh: - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.' - 'SudsServiceProxy') as mock_service_proxy: - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' - ) as mock_transport: - mock_plugin.return_value = mock.Mock() - mock_awhh.return_value = mock.Mock() - mock_service_proxy.return_value = mock.Mock() - mock_transport.return_value = mock.Mock() - client = GetAdWordsClient() - suds_service = client.GetService( - service, CURRENT_VERSION, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, CURRENT_VERSION, service), - transport=mock_transport.return_value, timeout=3600, - plugins=[mock_plugin.return_value]) - self.assertEqual(suds_service, mock_service_proxy.return_value) - mock_service_proxy.assert_called_once_with( - mock_client.return_value, - mock_awhh.return_value, - packer=googleads.adwords._AdWordsPacker) - - def testGetService_successWithFileCache(self): - service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] - namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] - # Use a custom server. Also test what happens if the server ends with a - # trailing slash - server = 'https://testing.test.com/' + client = GetAdWordsClient( + 'zeep', timeout='timeout', cache='cache', proxy_config='proxy_config') + client.enable_compression = True - with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' - ) as mock_transport: - mock_plugin.return_value = mock.Mock() - mock_transport.return_value = mock.Mock() - client = GetAdWordsClient(cache=self.file_cache) - suds_service = client.GetService( - service, CURRENT_VERSION, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, CURRENT_VERSION, service), - transport=mock_transport.return_value, timeout=3600, - cache=self.file_cache, plugins=[mock_plugin.return_value]) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) - - def testGetService_successWithNoCache(self): - service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] - namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] + service_name = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] + namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service_name] # Use a custom server. Also test what happens if the server ends with a # trailing slash server = 'https://testing.test.com/' - with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' - ) as mock_transport: - mock_plugin.return_value = mock.Mock() - mock_transport.return_value = mock.Mock() - client = GetAdWordsClient(cache=self.no_cache) - suds_service = client.GetService( - service, CURRENT_VERSION, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, CURRENT_VERSION, service), - transport=mock_transport.return_value, timeout=3600, - cache=self.no_cache, plugins=[mock_plugin.return_value]) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) - - def testGetService_successWithoutProxy(self): - service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] - namespace = googleads.adwords._SERVICE_MAP[CURRENT_VERSION][service] - - # Use the default server without a proxy. - with mock.patch('googleads.common.LoggingMessagePlugin') as mock_plugin: - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport' - ) as mock_transport: - mock_transport.return_value = mock.Mock() - client = GetAdWordsClient() - suds_service = client.GetService(service, CURRENT_VERSION) - - mock_client.assert_called_once_with( - 'https://adwords.google.com/api/adwords/%s/%s/%s?wsdl' - % (namespace, CURRENT_VERSION, service), - transport=mock_transport.return_value, timeout=3600, - plugins=[mock_plugin.return_value]) - self.assertFalse(mock_client.return_value.set_options.called) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) + with mock.patch('googleads.common.' + 'GetServiceClassForLibrary') as mock_get_service: + with mock.patch('googleads.adwords.' + '_AdWordsHeaderHandler') as mock_header_handler: + mock_header_handler.return_value = 'header_handler' + + impl = mock.Mock() + mock_service = mock.Mock() + impl.return_value = mock_service + mock_get_service.return_value = impl + + service = client.GetService(service_name, CURRENT_VERSION, server) + mock_header_handler.assert_called_once_with( + client, CURRENT_VERSION, True) + impl.assert_called_once_with( + 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' % ( + namespace, CURRENT_VERSION, service_name), + 'header_handler', + googleads.adwords._AdWordsPacker, + 'proxy_config', + 'timeout', + cache='cache') + self.assertEqual(service, mock_service) def testGetService_badService(self): version = CURRENT_VERSION @@ -511,17 +436,6 @@ def testGetService_badVersion(self): googleads.errors.GoogleAdsValueError, self.adwords_client.GetService, 'CampaignService', '11111') - def testGetService_compressionEnabled(self): - service = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] - client = GetAdWordsClient() - client.enable_compression = True - - with mock.patch('suds.client.Client'): - with mock.patch('googleads.adwords._AdWordsHeaderHandler') as mock_h: - client.GetService(service, CURRENT_VERSION) - mock_h.assert_called_once_with(client, CURRENT_VERSION, - client.enable_compression) - def testGetBatchJobHelper(self): with mock.patch('googleads.adwords.BatchJobHelper') as mock_helper: self.assertEqual( @@ -537,13 +451,12 @@ def testGetReportDownloader(self): self.adwords_client, 'version', 'server') def testSetClientCustomerId(self): - suds_client = mock.Mock() + create_method = mock.Mock() ccid = 'modified' # Check that the SOAP header has the modified client customer id. self.adwords_client.SetClientCustomerId(ccid) - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value - self.assertEqual(ccid, soap_header.clientCustomerId) + header_result = self.header_handler.GetSOAPHeaders(create_method) + self.assertEqual(ccid, header_result.clientCustomerId) class AdWordsClientIntegrationTest(unittest.TestCase): @@ -595,7 +508,7 @@ class BatchJobHelperTest(testing.CleanUtilityRegistryTestCase): def setUp(self): """Prepare tests.""" - self.client = GetAdWordsClient() + self.client = GetAdWordsClient('zeep') self.batch_job_helper = self.client.GetBatchJobHelper() def testGetId(self): @@ -605,7 +518,7 @@ def testGetId(self): def testUploadOperations(self): with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' 'BuildUploadRequest') as mock_build_request: mock_request = mock.Mock() mock_request.data = 'in disguise.' @@ -615,27 +528,26 @@ def testUploadOperations(self): with mock.patch('googleads.adwords.IncrementalUploadHelper' '._InitializeURL') as mock_init: mock_init.return_value = 'https://www.google.com' - with mock.patch( - '%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: + with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: self.batch_job_helper.UploadOperations([[]]) mock_open.assert_called_with(mock_request) +@testing.MultiBackendTest class BatchJobUploadRequestBuilderTest(testing.CleanUtilityRegistryTestCase): """Test suite for the BatchJobUploadRequestBuilder.""" ENVELOPE_NS = 'http://schemas.xmlsoap.org/soap/envelope/' - def setUp(self): + def setUp(self, soap_impl): """Prepare tests.""" - self.client = GetAdWordsClient() + self.client = GetAdWordsClient(soap_impl) self.request_builder = self.client.GetBatchJobHelper()._request_builder self.version = self.request_builder._version self.upload_url = 'https://goo.gl/IaQQsJ' self.sample_xml = ('!n3vERg0Nn4Run4r0und4NDd35Er7Y0u!~' '') - sample_xml_length = len(self.sample_xml) self.complete_request_body = '%s%s%s' % ( self.request_builder._UPLOAD_PREFIX_TEMPLATE % ( self.request_builder._adwords_endpoint), @@ -815,6 +727,9 @@ def GenerateValidRequest(self, operation_type, num_operations=1): request = self.RAW_API_REQUEST_TEMPLATE % ( self.version, self.version, method, ops_xml, method) + if six.PY3: + request = bytes(request, 'utf-8') + request = lxml.etree.fromstring(request) return (ops, request) @@ -838,6 +753,7 @@ def GenerateValidUnicodeRequest(self, operations): request = (self.RAW_API_REQUEST_TEMPLATE % ( self.version, self.version, method, ops_xml, method)).encode('utf-8') + request = lxml.etree.fromstring(request) return (ops, request) @@ -901,8 +817,7 @@ def testFormatForBatchJobService(self): operations_amount = 5 _, ops = self.GenerateOperations('CampaignCriterionOperation', operations_amount) - root = ElementTree.fromstring(self.request_builder._GenerateRawRequestXML( - ops)) + root = self.request_builder._GenerateRawRequestXML(ops) body = root.find('{%s}Body' % self.ENVELOPE_NS) mutate = body.find('{%s}mutate' % self.request_builder._adwords_endpoint) self.request_builder._FormatForBatchJobService(mutate) @@ -968,8 +883,7 @@ def testGenerateRawRequestXMLFromCampaignLabelOperation(self): 'operand': {'campaignId': 0, 'labelId': 0} }] - root = ElementTree.fromstring( - self.request_builder._GenerateRawRequestXML(ops)) + root = self.request_builder._GenerateRawRequestXML(ops) self.assertTrue(len(root) == 2) body = root.find('{%s}Body' % self.ENVELOPE_NS) self.assertTrue(len(body) == 1) @@ -982,8 +896,7 @@ def testGenerateRawRequestXMLFromSingleOperation(self): operations_amount = 1 _, ops = self.GenerateOperations('BudgetOperation', operations_amount) - root = ElementTree.fromstring( - self.request_builder._GenerateRawRequestXML(ops)) + root = self.request_builder._GenerateRawRequestXML(ops) self.assertTrue(len(root) == 2) body = root.find('{%s}Body' % self.ENVELOPE_NS) self.assertTrue(len(body) == 1) @@ -1029,8 +942,7 @@ def testGenerateRawRequestXMLFromMultipleOperations(self): operations_amount = 5 _, ops = self.GenerateOperations('BudgetOperation', operations_amount) - root = ElementTree.fromstring( - self.request_builder._GenerateRawRequestXML(ops)) + root = self.request_builder._GenerateRawRequestXML(ops) self.assertTrue(len(root) == 2) body = root.find('{%s}Body' % self.ENVELOPE_NS) self.assertTrue(len(body) == 1) @@ -1075,8 +987,7 @@ def testGenerateRawUnicodeRequestXMLFromSingleOperation(self): operations_amount = 1 ops = self.GenerateUnicodeBudgetOperations(operations_amount) - root = ElementTree.fromstring( - self.request_builder._GenerateRawRequestXML(ops)) + root = self.request_builder._GenerateRawRequestXML(ops) self.assertTrue(len(root) == 2) body = root.find(u'{%s}Body' % self.ENVELOPE_NS) self.assertTrue(len(body) == 1) @@ -1314,14 +1225,14 @@ def testGetRawOperationsFromInvalidRequest(self): def testGetRawOperationsFromNotXMLRequest(self): """Test whether non-XML input raises an Exception.""" - self.assertRaises(ElementTree.ParseError, + self.assertRaises(AttributeError, self.request_builder._GetRawOperationsFromXML, self.NOT_API_REQUEST) def testBuildRequestForSingleUpload(self): """Test whether a single upload request is build correctly.""" with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_BuildUploadRequestBody') as mock_request_body_builder: mock_request_body_builder.return_value = self.sample_xml req = self.request_builder.BuildUploadRequest(self.upload_url, [[]], @@ -1332,7 +1243,7 @@ def testBuildRequestForSingleUpload(self): def testBuildRequestForIncrementalUpload(self): """Test whether an incremental upload request is built correctly.""" with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_BuildUploadRequestBody') as mock_request_body_builder: mock_request_body_builder.return_value = self.sample_xml req = self.request_builder.BuildUploadRequest( @@ -1344,11 +1255,11 @@ def testBuildRequestForIncrementalUpload(self): def testBuildUploadRequestBody(self): """Test whether a a complete request body is built correctly.""" with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_GenerateOperationsXML') as mock_generate_xml: mock_generate_xml.return_value = self.sample_xml with mock.patch('googleads.adwords.BatchJobHelper._' - 'SudsUploadRequestBuilder.' + 'UploadRequestBuilder.' '_GetPaddingLength') as mock_get_padding_length: mock_get_padding_length.return_value = 0 increment = self.request_builder._BuildUploadRequestBody([[]]) @@ -1357,11 +1268,11 @@ def testBuildUploadRequestBody(self): def testBuildUploadRequestBodyWithSuffix(self): """Test whether a request body is built correctly with only the suffix.""" with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_GenerateOperationsXML') as mock_generate_xml: mock_generate_xml.return_value = self.sample_xml with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_GetPaddingLength') as mock_get_padding_length: mock_get_padding_length.return_value = 0 increment = self.request_builder._BuildUploadRequestBody( @@ -1371,11 +1282,11 @@ def testBuildUploadRequestBodyWithSuffix(self): def testBuildUploadRequestBodyWithoutPrefixOrSuffix(self): """Test whether a request body is built correctly without prefix/suffix.""" with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_GenerateOperationsXML') as mock_generate_xml: mock_generate_xml.return_value = self.sample_xml with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_GetPaddingLength') as mock_get_padding_length: mock_get_padding_length.return_value = 0 increment = self.request_builder._BuildUploadRequestBody( @@ -1385,11 +1296,11 @@ def testBuildUploadRequestBodyWithoutPrefixOrSuffix(self): def testBuildUploadRequestBodyWithOnlyPrefix(self): """Test whether a request body is built correctly with only the prefix.""" with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_GenerateOperationsXML') as mock_generate_xml: mock_generate_xml.return_value = self.sample_xml with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' '_GetPaddingLength') as mock_get_padding_length: mock_get_padding_length.return_value = 0 increment = self.request_builder._BuildUploadRequestBody( @@ -1403,13 +1314,15 @@ class IncrementalUploadHelperTest(testing.CleanUtilityRegistryTestCase): def setUp(self): """Prepare tests.""" - self.client = GetAdWordsClient() - self.batch_job_helper = self.client.GetBatchJobHelper() - self.version = self.batch_job_helper._version + self.client = GetAdWordsClient('zeep') + self.server = 'https://test.com' + self.version = 'test_version' + self.batch_job_helper = self.client.GetBatchJobHelper( + version=self.version, server=self.server) self.original_url = 'https://goo.gl/w8tkpK' self.initialized_url = 'https://goo.gl/Xtaq83' - with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: + with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: mock_open.return_value.headers = { 'location': self.initialized_url } @@ -1419,24 +1332,25 @@ def setUp(self): self.incremental_uploader_dump = ( '{current_content_length: 0, is_last: false, ' - 'upload_url: \'https://goo.gl/Xtaq83\', version: %s}\n' % self.version) + 'server: \'https://test.com\', upload_url: \'https://goo.gl/Xtaq83\',' + 'version: %s}\n' % self.version) def testDump(self): - expected = self.incremental_uploader_dump + expected = yaml.load(self.incremental_uploader_dump) with tempfile.NamedTemporaryFile(delete=False, mode='w') as t: name = t.name self.incremental_uploader.Dump(t) with open(name, mode='r') as handler: - dump_data = handler.read() + dump_data = yaml.safe_load(handler) self.assertEqual(expected, dump_data) def testLoad(self): s = six.StringIO(self.incremental_uploader_dump) - with mock.patch('%s.urlopen' % URL_REQUEST_PATH) as mock_open: + with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: mock_open.return_value.headers = { 'location': self.initialized_url } @@ -1454,14 +1368,16 @@ def testLoad(self): self.version) self.assertEquals(restored_uploader._upload_url, self.incremental_uploader._upload_url) + self.assertEquals(restored_uploader._request_builder.GetServer(), + self.server) def testUploadOperations(self): with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: + with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: self.incremental_uploader.UploadOperations([[]], True) mock_open.assert_called_with(mock_request) @@ -1474,11 +1390,11 @@ def testUploadOperationsWithError(self): error_url, error_code, error_message, error_headers, None) with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: + with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: mock_open.side_effect = http_error self.assertRaises( six.moves.urllib.error.HTTPError, @@ -1487,11 +1403,11 @@ def testUploadOperationsWithError(self): def testUploadOperationsAfterFinished(self): with mock.patch('googleads.adwords.BatchJobHelper.' - '_SudsUploadRequestBuilder.' + '_UploadRequestBuilder.' 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH): + with mock.patch.object(urllib2.OpenerDirector, 'open'): self.incremental_uploader.UploadOperations([[]], True) self.assertRaises( googleads.errors.AdWordsBatchJobServiceInvalidOperationError, @@ -1503,7 +1419,7 @@ class ResponseParserTest(testing.CleanUtilityRegistryTestCase): def setUp(self): """Prepare tests.""" - self.client = GetAdWordsClient() + self.client = GetAdWordsClient('zeep') self.response_parser = googleads.adwords.BatchJobHelper.GetResponseParser() @classmethod @@ -1580,6 +1496,243 @@ def testParseUnicodeResponse(self): self.assertTrue(campaign['name'] == name) +def GetVersionedXSD(version): + report_xsd = os.path.join( + TEST_DIR, 'test_data/adwords_report_definition.xsd') + + with open(report_xsd, 'rb') as f: + data = f.read() + if six.PY3: + return data.replace(b'{VERSION}', bytes(version, 'utf-8')) + else: + return data.replace('{VERSION}', version) + + +class ReportDownloaderZeepTest(testing.CleanUtilityRegistryTestCase): + + def setUp(self): + self.version = CURRENT_VERSION + self.opener = mock.Mock() + self.adwords_client = mock.Mock() + self.adwords_client.proxy_config = GetProxyConfig() + self.adwords_client.soap_impl = 'zeep' + self.header_handler = mock.Mock() + + # It's unfortunate that the target output is different between suds and + # zeep. The reason is because suds pretty prints its xml in a very hardcoded + # hack way, and zeep does not. Not doing it is better. + post_body_path = os.path.join( + TEST_DIR, 'test_data/adwords_report_post_body_no_formatting.txt') + with open(post_body_path, 'r') as f: + self.post_body_data = f.read().replace('{VERSION}', self.version) + + class XSDTransport(zeep.transports.Transport): + + def load(self, url): + return GetVersionedXSD(CURRENT_VERSION) + + with mock.patch( + 'googleads.adwords._AdWordsHeaderHandler') as mock_handler: + mock_handler.return_value = self.header_handler + + with mock.patch('googleads.common._ZeepProxyTransport') as mock_transport: + mock_transport.return_value = XSDTransport() + + self.adwords_client.soap_impl = 'zeep' + self.report_downloader = googleads.adwords.ReportDownloader( + self.adwords_client, self.version + ) + self.report_downloader.url_opener = self.opener + + @mock.patch('googleads.adwords._report_logger') + @mock.patch.object(urllib2, 'Request') + def testDownloadReportWithZeep(self, mock_request, mock_logger): + mock_logger.isEnabledFor.return_value = True + output_file = six.StringIO() + report_definition = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + with mock.patch.object(self.report_downloader, + '_header_handler') as mock_header_handler, \ + (mock.patch.object( + self.report_downloader, + '_ExtractRequestSummaryFields')) as mock_extract_request_summary, \ + (mock.patch.object( + self.report_downloader, + '_ExtractResponseHeaders')) as mock_extract_response_headers: + response_data = u'ABC 广告客户' + response_fp = six.BytesIO() + response_fp.write(response_data if six.PY2 else bytes(response_data, + 'utf-8')) + response_fp.seek(0) + mock_response = mock.Mock() + mock_response.read.side_effect = response_fp.read + mock_response.code = '200' + self.opener.open.return_value = mock_response + + self.report_downloader.DownloadReport(report_definition, output_file, + skip_report_header=True, + use_raw_enum_values=False) + + mock_request.assert_called_once_with( + self.report_downloader._end_point, + (self.post_body_data if six.PY2 + else bytes(self.post_body_data, 'utf-8')), + mock_header_handler.GetReportDownloadHeaders.return_value) + + output_file.seek(0) + self.assertEqual(output_file.read(), response_data) + mock_extract_request_summary.assert_called_once_with( + mock_request.return_value) + mock_extract_response_headers.assert_called_once_with( + mock_response.headers) + + +class ReportDownloaderSudsTest(testing.CleanUtilityRegistryTestCase): + """Reporting integration tests for suds.""" + + def setUp(self): + self.version = CURRENT_VERSION + self.marshaller = mock.Mock() + self.header_handler = mock.Mock() + self.adwords_client = mock.Mock() + self.adwords_client.proxy_config = GetProxyConfig() + self.adwords_client.cache = suds.cache.NoCache() + self.opener = mock.Mock() + + post_body_path = os.path.join(TEST_DIR, + 'test_data/adwords_report_post_body.txt') + with open(post_body_path, 'r') as f: + self.post_body_data = f.read().replace('{VERSION}', self.version) + + class XSDTransport(suds.transport.Transport): + + def __init__(self): + suds.transport.Transport.__init__(self) + self.handlers = [] + + def open(self, request): + fp = io.BytesIO() + fp.write(GetVersionedXSD(CURRENT_VERSION)) + fp.seek(0) + return fp + + with mock.patch( + 'googleads.adwords._AdWordsHeaderHandler') as mock_handler: + mock_handler.return_value = self.header_handler + + with mock.patch('googleads.common._SudsProxyTransport') as mock_transport: + mock_transport.return_value = XSDTransport() + + self.adwords_client.soap_impl = 'suds' + self.report_downloader = googleads.adwords.ReportDownloader( + self.adwords_client, self.version + ) + self.report_downloader.url_opener = self.opener + + @mock.patch('googleads.adwords._report_logger') + @mock.patch.object(urllib2, 'Request') + def testDownloadReportWithSuds(self, mock_request, mock_logger): + mock_logger.isEnabledFor.return_value = True + output_file = six.StringIO() + report_definition = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + with mock.patch.object(self.report_downloader, + '_header_handler') as mock_header_handler, \ + (mock.patch.object( + self.report_downloader, + '_ExtractRequestSummaryFields')) as mock_extract_request_summary, \ + (mock.patch.object( + self.report_downloader, + '_ExtractResponseHeaders')) as mock_extract_response_headers: + response_data = u'ABC 广告客户' + response_fp = six.BytesIO() + response_fp.write(response_data if six.PY2 else bytes(response_data, + 'utf-8')) + response_fp.seek(0) + mock_response = mock.Mock() + mock_response.read.side_effect = response_fp.read + mock_response.code = '200' + self.opener.open.return_value = mock_response + + self.report_downloader.DownloadReport(report_definition, output_file, + skip_report_header=True, + use_raw_enum_values=False) + + mock_request.assert_called_once_with( + self.report_downloader._end_point, + (self.post_body_data if six.PY2 + else bytes(self.post_body_data, 'utf-8')), + mock_header_handler.GetReportDownloadHeaders.return_value) + + output_file.seek(0) + self.assertEqual(output_file.read(), response_data) + mock_extract_request_summary.assert_called_once_with( + mock_request.return_value) + mock_extract_response_headers.assert_called_once_with( + mock_response.headers) + + @mock.patch.object(urllib2, 'Request') + def testDownloadReportWithBytesIO(self, mock_request): + output_file = six.BytesIO() + report_definition = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + with mock.patch.object(self.report_downloader, + '_header_handler') as mock_header_handler, \ + (mock.patch.object(self.report_downloader, + '_ExtractRequestSummaryFields')), \ + (mock.patch.object(self.report_downloader, + '_ExtractResponseHeaders')): + response_data = u'CONTENT STRING 广告客户' + response_fp = six.BytesIO() + response_fp.write(response_data.encode('utf-8')) + response_fp.seek(0) + mock_response = mock.Mock() + mock_response.read.side_effect = response_fp.read + mock_response.code = '200' + self.opener.open.return_value = mock_response + + self.report_downloader.DownloadReport(report_definition, + output_file, + skip_report_header=True, + use_raw_enum_values=False) + + mock_request.assert_called_once_with( + self.report_downloader._end_point, + (self.post_body_data if six.PY2 + else bytes(self.post_body_data, 'utf-8')), + mock_header_handler.GetReportDownloadHeaders.return_value) + + output_file.seek(0) + self.assertEqual(output_file.read().decode('utf-8'), response_data) + + class ReportDownloaderTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.adwords.ReportDownloader class.""" @@ -1589,144 +1742,41 @@ def setUp(self): self.header_handler = mock.Mock() self.adwords_client = mock.Mock() self.adwords_client.proxy_config = GetProxyConfig() + self.adwords_client.cache = suds.cache.NoCache() self.opener = mock.Mock() - with mock.patch('suds.client.Client'): - with mock.patch('suds.xsd.doctor'): - with mock.patch('suds.mx.literal.Literal') as mock_literal: - with mock.patch( - 'googleads.adwords._AdWordsHeaderHandler') as mock_handler: - with mock.patch( - URL_REQUEST_PATH + '.OpenerDirector') as mock_opener: - mock_literal.return_value = self.marshaller - mock_handler.return_value = self.header_handler - mock_opener.return_value = self.opener - self.report_downloader = googleads.adwords.ReportDownloader( - self.adwords_client, self.version) - - def testDownloadReport(self): - output_file = six.StringIO() - report_definition = {'table': 'campaigns', - 'downloadFormat': 'CSV'} - serialized_report = 'nuinbwuign' - post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) - if six.PY3: - post_body = bytes(post_body, 'utf-8') - headers = {'Authorization': 'ya29.something'} - self.header_handler.GetReportDownloadHeaders.return_value = headers - report_data = u'CONTENT STRING 广告客户' - report_contents = six.StringIO() if six.PY2 else io.BytesIO() - report_contents.write(report_data if six.PY2 - else bytes(report_data, 'utf-8')) - report_contents.seek(0) - fake_response = mock.Mock() - fake_response.read = report_contents.read - fake_response.msg = 'fake message' - fake_response.code = '200' - self.marshaller.process.return_value = serialized_report - - with mock.patch('suds.mx.Content') as mock_content: - with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - mock_request_instance = mock.Mock() - mock_request.return_value = mock_request_instance - mock_request_instance.get_full_url.return_value = 'https://google.com/' - mock_request_instance.headers = {} - self.opener.open.return_value = fake_response - self.report_downloader.DownloadReport(report_definition, output_file, - skip_report_header=True, - use_raw_enum_values=False) - mock_request.assert_called_once_with( - ('https://adwords.google.com/api/adwords/reportdownload/%s' - % self.version), post_body, headers) - self.opener.open.assert_called_once_with(mock_request.return_value) - self.marshaller.process.assert_called_once_with( - mock_content.return_value) - self.assertEqual(report_data, output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - skip_report_header=True, use_raw_enum_values=False) - - def testDownloadReportWithAllLoggingEnabled(self): - output_file = six.StringIO() - report_definition = {'table': 'campaigns', - 'downloadFormat': 'CSV'} - serialized_report = 'nuinbwuign' - post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) - if six.PY3: - post_body = bytes(post_body, 'utf-8') - headers = {'Authorization': 'ya29.something'} - self.header_handler.GetReportDownloadHeaders.return_value = headers - report_data = u'CONTENT STRING 广告客户' - report_contents = six.StringIO() if six.PY2 else io.BytesIO() - report_contents.write(report_data if six.PY2 - else bytes(report_data, 'utf-8')) - report_contents.seek(0) - fake_response = mock.Mock() - fake_response.read = report_contents.read - fake_response.headers = '\nsomekey: somevalue\n' - fake_response.msg = 'fake message' - fake_response.code = '200' - self.marshaller.process.return_value = serialized_report - - with mock.patch('suds.mx.Content') as mock_content: - with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - with mock.patch('googleads.adwords._report_logger') as mock_logger: - mock_logger.isEnabledFor.return_value = True - mock_request_instance = mock.Mock() - mock_request.return_value = mock_request_instance - mock_request_instance.get_full_url.return_value = ( - 'https://google.com/') - mock_request_instance.headers = {} - self.opener.open.return_value = fake_response - self.report_downloader.DownloadReport(report_definition, output_file, - skip_report_header=True, - use_raw_enum_values=False) - mock_request.assert_called_once_with( - ('https://adwords.google.com/api/adwords/reportdownload/%s' - % self.version), post_body, headers) - self.opener.open.assert_called_once_with(mock_request.return_value) - self.marshaller.process.assert_called_once_with( - mock_content.return_value) - self.assertEqual(report_data, output_file.getvalue()) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with( - skip_report_header=True, use_raw_enum_values=False) - - def testDownloadReportAsString(self): - report_definition = {'table': 'campaigns', - 'downloadFormat': 'CSV'} - serialized_report = 'nuinbwuign' - post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) - if six.PY3: - post_body = bytes(post_body, 'utf-8') - headers = {'Authorization': 'ya29.something'} - self.header_handler.GetReportDownloadHeaders.return_value = headers - report_data = u'CONTENT STRING アングリーバード' - report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if six.PY2 - else bytes(report_data, 'utf-8')) - report_contents.seek(0) - fake_response = mock.Mock() - fake_response.read = report_contents.read - fake_response.msg = 'fake message' - fake_response.code = '200' - self.marshaller.process.return_value = serialized_report - - with mock.patch('suds.mx.Content') as mock_content: - with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - mock_request_instance = mock.Mock() - mock_request.return_value = mock_request_instance - mock_request_instance.get_full_url.return_value = ( - 'https://google.com/') - mock_request_instance.headers = {} - self.opener.open.return_value = fake_response - s = self.report_downloader.DownloadReportAsString(report_definition) - mock_request.assert_called_once_with( - ('https://adwords.google.com/api/adwords/reportdownload/%s' - % self.version), post_body, headers) - self.opener.open.assert_called_once_with(mock_request.return_value) - self.marshaller.process.assert_called_once_with( - mock_content.return_value) - self.assertEqual(report_data, s) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with() + with mock.patch( + 'googleads.adwords._AdWordsHeaderHandler') as mock_handler, \ + mock.patch('googleads.adwords.googleads.common' + '.GetSchemaHelperForLibrary') as mock_get_schema: + mock_handler.return_value = self.header_handler + mock_get_schema.return_value = mock.Mock() + + self.report_downloader = googleads.adwords.ReportDownloader( + self.adwords_client, self.version + ) + + self.report_downloader.url_opener = self.opener + + @mock.patch.object(urllib2.OpenerDirector, 'open') + def testDownloadReportAsString(self, mock_request): + serialize_response = mock.Mock() + with mock.patch.object( + self.report_downloader, + '_DownloadReportAsStream') as mock_internal_download, \ + mock.patch.object( + self.report_downloader, + '_SerializeReportDefinition') as mock_internal_serialize: + mock_internal_serialize.return_value = serialize_response + + self.report_downloader.DownloadReportAsString( + 'report_definition', + some_arg='abc') + + mock_internal_serialize.assert_called_once_with('report_definition') + mock_internal_download.assert_called_once_with( + serialize_response, + some_arg='abc') def testDownloadReportAsStringWithAwql(self): query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' @@ -1743,11 +1793,11 @@ def testDownloadReportAsStringWithAwql(self): else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() - fake_response.read = report_contents.read + fake_response.read.side_effect = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: + with mock.patch.object(urllib2, 'Request') as mock_request: mock_request_instance = mock.Mock() mock_request.return_value = mock_request_instance mock_request_instance.get_full_url.return_value = 'https://google.com/' @@ -1821,63 +1871,32 @@ def testDownloadReportCheckFormat_Issue152(self): def testDownloadReport_failure(self): output_file = six.StringIO() - report_definition = {'table': 'campaigns', - 'downloadFormat': 'CSV'} - serialized_report = 'hjuibnibguo' - post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) - if six.PY3: - post_body = bytes(post_body, 'utf-8') - headers = {'Authorization': 'ya29.something'} - self.header_handler.GetReportDownloadHeaders.return_value = headers - report_data = u'Page not found. :-(' - report_contents = six.StringIO() if six.PY2 else io.BytesIO() - report_contents.write(report_data if six.PY2 else bytes(report_data, - 'utf-8')) - logger_request_summary_template = 'Request Summary: %s' - report_contents.seek(0) - fake_response = mock.Mock() - fake_response.read = report_contents.read - fake_response.msg = 'fake message' - fake_response.code = '200' - error = six.moves.urllib.error.HTTPError('', 400, 'Bad Request', {}, - fp=fake_response) - - self.marshaller.process.return_value = serialized_report - - with mock.patch('suds.mx.Content') as mock_content: - with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - with mock.patch('googleads.adwords._report_logger') as mock_logger: - with mock.patch('googleads.adwords.ReportDownloader' - '._ExtractRequestSummaryFields') as mock_extract_fds: - mock_logger.isEnabledFor.return_value = True - mock_extract_fds_return_value = mock.Mock() - mock_extract_fds.return_value = mock_extract_fds_return_value - mock_request_instance = mock.Mock() - mock_request.return_value = mock_request_instance - mock_request_instance.get_full_url.return_value = ( - 'https://google.com/') - mock_request_instance.headers = {} - self.opener.open.side_effect = error - - try: - self.report_downloader.DownloadReport( - report_definition, output_file) - except googleads.errors.AdWordsReportError as ex: - mock_extract_fds.assert_called_once_with( - mock_request_instance, error=ex) - mock_logger.warning.assert_called_once_with( - logger_request_summary_template, - mock_extract_fds_return_value) - - mock_request.assert_called_once_with( - ('https://adwords.google.com/api/adwords/reportdownload/%s' - % self.version), post_body, headers) - self.opener.open.assert_called_once_with(mock_request.return_value) - self.marshaller.process.assert_called_once_with( - mock_content.return_value) - self.assertEqual('', output_file.getvalue()) - h_handler = self.header_handler - h_handler.GetReportDownloadHeaders.assert_called_once_with() + report_definition = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + with mock.patch.object(self.report_downloader.url_opener, + 'open') as mock_open: + response_data = 'bad stuff happened' + response_fp = six.BytesIO() + response_fp.write(response_data if six.PY2 else bytes( + response_data, 'utf-8')) + response_fp.seek(0) + + mock_open.side_effect = six.moves.urllib.error.HTTPError( + 'http://abc', '500', 'whoops!', {}, response_fp) + with mock.patch.object(self.report_downloader, '_header_handler'): + with self.assertRaises(googleads.errors.AdWordsReportError): + self.report_downloader.DownloadReport(report_definition, output_file, + skip_report_header=True, + use_raw_enum_values=False) def testDownloadReportWithAwql(self): output_file = six.StringIO() @@ -1898,11 +1917,11 @@ def testDownloadReportWithAwql(self): else bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() - fake_response.read = report_contents.read + fake_response.read.side_effect = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: + with mock.patch.object(urllib2, 'Request') as mock_request: mock_request_instance = mock.Mock() mock_request.return_value = mock_request_instance mock_request_instance.get_full_url.return_value = 'https://google.com/' @@ -1919,57 +1938,22 @@ def testDownloadReportWithAwql(self): self.assertEqual(report_data, output_file.getvalue()) self.header_handler.GetReportDownloadHeaders.assert_called_once_with() - def testDownloadReportWithBytesIO(self): - output_file = io.BytesIO() - report_definition = {'table': 'campaigns', - 'downloadFormat': 'GZIPPED_CSV'} - serialized_report = 'nuinbwuign' - post_body = six.moves.urllib.parse.urlencode({'__rdxml': serialized_report}) - if six.PY3: - post_body = bytes(post_body, 'utf-8') - headers = {'Authorization': 'ya29.something'} - self.header_handler.GetReportDownloadHeaders.return_value = headers - report_data = u'CONTENT STRING 广告客户' - report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if six.PY2 - else bytes(report_data, 'utf-8')) - report_contents.seek(0) - fake_response = mock.Mock() - fake_response.read = report_contents.read - fake_response.msg = 'fake message' - fake_response.code = '200' - self.marshaller.process.return_value = serialized_report - - with mock.patch('suds.mx.Content') as mock_content: - with mock.patch(URL_REQUEST_PATH + '.Request') as mock_request: - mock_request_instance = mock.Mock() - mock_request.return_value = mock_request_instance - mock_request_instance.get_full_url.return_value = 'https://google.com/' - mock_request_instance.headers = {} - self.opener.open.return_value = fake_response - self.report_downloader.DownloadReport(report_definition, output_file) - mock_request.assert_called_once_with( - ('https://adwords.google.com/api/adwords/reportdownload/%s' - % self.version), post_body, headers) - self.opener.open.assert_called_once_with(mock_request.return_value) - self.marshaller.process.assert_called_once_with( - mock_content.return_value) - self.assertEqual(report_data, output_file.getvalue().decode('utf-8')) - self.header_handler.GetReportDownloadHeaders.assert_called_once_with() - def testExtractError_badRequest(self): response = mock.Mock() response.code = 400 type_ = 'ReportDownloadError.INVALID_REPORT_DEFINITION_XML' trigger = 'Invalid enumeration.' field_path = 'Criteria.Type' - content_template = ( + error_template = ( '' '%s%s' '%s') - content = content_template % (type_, trigger, field_path) - response.read.return_value = (content if six.PY2 - else bytes(content, 'utf-8')) + response_data = error_template % (type_, trigger, field_path) + response_fp = six.BytesIO() + response_fp.write(response_data if six.PY2 + else bytes(response_data, 'utf-8')) + response_fp.seek(0) + response.read.side_effect = response_fp.read rval = self.report_downloader._ExtractError(response) self.assertEqual(type_, rval.type) @@ -1977,13 +1961,16 @@ def testExtractError_badRequest(self): self.assertEqual(field_path, rval.field_path) self.assertEqual(response.code, rval.code) self.assertEqual(response, rval.error) - self.assertEqual(content, rval.content) + self.assertEqual(response_data, rval.content) self.assertIsInstance(rval, googleads.errors.AdWordsReportBadRequestError) # Check that if the XML fields are empty, this still functions. - content = content_template % ('', '', '') - response.read.return_value = (content if six.PY2 - else bytes(content, 'utf-8')) + response_data = error_template % ('', '', '') + response_fp = six.BytesIO() + response_fp.write(response_data if six.PY2 + else bytes(response_data, 'utf-8')) + response_fp.seek(0) + response.read.side_effect = response_fp.read rval = self.report_downloader._ExtractError(response) self.assertEqual(None, rval.type) self.assertEqual(None, rval.trigger) @@ -1992,16 +1979,20 @@ def testExtractError_badRequest(self): def testExtractError_malformedBadRequest(self): response = mock.Mock() response.code = 400 - content = ('' - '12345678' - '') - response.read.return_value = (content if six.PY2 - else bytes(content, 'utf-8')) + response_data = ('' + '1234' + '5678' + '') + response_fp = six.BytesIO() + response_fp.write(response_data if six.PY2 + else bytes(response_data, 'utf-8')) + response_fp.seek(0) + response.read.side_effect = response_fp.read rval = self.report_downloader._ExtractError(response) self.assertEqual(response.code, rval.code) self.assertEqual(response, rval.error) - self.assertEqual(content, rval.content) + self.assertEqual(response_data, rval.content) self.assertIsInstance(rval, googleads.errors.AdWordsReportError) def testExtractError_notBadRequest(self): @@ -2387,15 +2378,25 @@ def testNextPage(self): actual_query.NextPage() self.assertRegexpMatches(str(actual_query), awql_regex) - def testNextPage_userProvidedPage(self): + def testNextPageForDataService(self): selected_fields = ['Id', 'Name'] - actual_query = (googleads.adwords.ServiceQueryBuilder() - .Select(*selected_fields) - .Limit(0, 100) - .Build()) - # Do next page and check if the LIMIT clause is modified correctly. - awql_regex = (r'SELECT (.*) LIMIT 50,100') - actual_query.NextPage(50) + actual_query = ( + googleads.adwords.ServiceQueryBuilder().Select(*selected_fields).Limit( + 0, 2).Build()) + page = { + 'totalNumEntries': 3, + 'Page.Type': 'CriterionBidLandscapePage', + 'entries': [{ + 'landscapePoints': ['fakePoint1', 'fakePoint2'] + }, { + 'landscapePoints': ['fakePoint3', 'fakePoint4'] + }] + } + + # The LIMIT clause should be incremented by the number of bid landscape + # points of the page. + awql_regex = (r'SELECT (.*) LIMIT 4,2') + actual_query.NextPage(page) self.assertRegexpMatches(str(actual_query), awql_regex) def testNextPageFail(self): @@ -2427,17 +2428,30 @@ def testHasNext(self): self.assertFalse(actual_query.HasNext(page)) - def testHasNext_userProvidedPage(self): + def testHasNextForDataService(self): + page = { + 'totalNumEntries': 3, + 'Page.Type': 'AdGroupBidLandscapePage', + 'entries': [{ + 'landscapePoints': ['fakePoint1', 'fakePoint2'] + }, { + 'landscapePoints': ['fakePoint3', 'fakePoint4'] + }] + } selected_fields = ['Id', 'Name'] - actual_query = (googleads.adwords.ServiceQueryBuilder() - .Select(*selected_fields) - .Limit(0, 1) - .Build()) - awql_regex = (r'SELECT (.*) LIMIT 0,1') - self.assertRegexpMatches(str(actual_query), awql_regex) + page_size = 2 + actual_query = ( + googleads.adwords.ServiceQueryBuilder().Select(*selected_fields).Limit( + 0, page_size).Build()) + # 2 * 2 landscape points are greater than page_size. + self.assertTrue(actual_query.HasNext(page)) - page = {'totalNumEntries': 80} - self.assertFalse(actual_query.HasNext(page, 100)) + page_size = 10 + actual_query = ( + googleads.adwords.ServiceQueryBuilder().Select(*selected_fields).Limit( + 0, page_size).Build()) + # 2 * 2 landscape points are less than page_size. + self.assertFalse(actual_query.HasNext(page)) def testHasNextFail(self): actual_query = googleads.adwords.ServiceQuery('SELECT Id, Name', None, 100) @@ -2447,26 +2461,22 @@ def testHasNextFail(self): actual_query.HasNext(page) def testPager(self): - service = 'CampaignService' fake_page = {'totalNumEntries': 3} + service = mock.Mock() + service.query.return_value = fake_page - with mock.patch('suds.client.Client'): - client = GetAdWordsClient(cache=suds.cache.FileCache) - service = client.GetService(service, CURRENT_VERSION) - with mock.patch.object(service, 'query', - return_value=fake_page, autospec=True): - query = (googleads.adwords.ServiceQueryBuilder() - .Select('Id', 'Name') - .Limit(0, 1) - .Build()) - i = 0 - for page in query.Pager(service): - self.assertEqual(fake_page['totalNumEntries'], - page['totalNumEntries']) - i += 1 - # Pager should return the number of page equal to the 'totalNumEntries' - # returned by a service. - self.assertEqual(fake_page['totalNumEntries'], i) + query = (googleads.adwords.ServiceQueryBuilder() + .Select('Id', 'Name') + .Limit(0, 1) + .Build()) + i = 0 + for page in query.Pager(service): + self.assertEqual(fake_page['totalNumEntries'], + page['totalNumEntries']) + i += 1 + # Pager should return the number of page equal to the 'totalNumEntries' + # returned by a service. + self.assertEqual(fake_page['totalNumEntries'], i) if __name__ == '__main__': diff --git a/tests/common_test.py b/tests/common_test.py index f069e569..e460867f 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -15,6 +15,7 @@ """Unit tests to cover the common module.""" +from contextlib import contextmanager import numbers import os import ssl @@ -24,17 +25,22 @@ from pyfakefs import fake_filesystem from pyfakefs import fake_tempfile import mock +import requests.exceptions import six import suds +import suds.cache import yaml +import zeep.cache import googleads.common import googleads.errors import googleads.oauth2 from . import testing +import zeep.exceptions URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' +TEST_DIR = os.path.dirname(__file__) class CommonTest(testing.CleanUtilityRegistryTestCase): @@ -44,22 +50,17 @@ class CommonTest(testing.CleanUtilityRegistryTestCase): _OAUTH_INSTALLED_APP_DICT = {'client_id': 'a', 'client_secret': 'b', 'refresh_token': 'c'} _OAUTH_SERVICE_ACCT_DICT = { - 'service_account_email': 'service_account@example.com', - 'path_to_private_key_file': '/test/test.p12', + 'path_to_private_key_file': '/test/test.json', 'delegated_account': 'delegated_account@example.com'} def setUp(self): self.filesystem = fake_filesystem.FakeFilesystem() self.tempfile = fake_tempfile.FakeTempfileModule(self.filesystem) self.fake_open = fake_filesystem.FakeFileOpen(self.filesystem) - self.host1 = 'h1' - self.port1 = 1 - self.host2 = 'h2' - self.port2 = 2 - self.uplink_host = '127.0.0.1' - self.uplink_port = 999 - self.username = 'username' - self.password = 'password' + self.uri1 = 'http://h1:1' + self.uri1_w_creds = 'http://username:password@h1:1' + self.uri2 = 'http://h2:2' + self.uplink_uri = 'http://127.0.0.1:999' self.test1_name = 'Test1' self.test2_name = 'Test2' self.test2_version = 'testing' @@ -159,11 +160,12 @@ def testLoadFromStorage(self): rval) self.assertTrue(googleads.common._utility_registry._enabled) - # Optional logging configuration key is present. + # Optional keys present logging_config = {'foo': 'bar'} yaml_fname = self._CreateYamlFile( {'one': {'needed': 'd', 'keys': 'e', 'other': 'f'}, - googleads.common._LOGGING_KEY: logging_config}, + googleads.common._LOGGING_KEY: logging_config, + googleads.common.SOAP_IMPLEMENTATION_KEY: 'suds'}, 'one', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): @@ -181,7 +183,8 @@ def testLoadFromStorage(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'other': 'f', 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.SOAP_IMPLEMENTATION_KEY: 'suds'}, rval) self.assertTrue(googleads.common._utility_registry._enabled) @@ -440,15 +443,6 @@ def testLoadFromString_missingPartialInstalledAppOAuthCredential(self): googleads.common.LoadFromString, yaml_doc, 'woo', [], []) - def testLoadFromString_missingPartialServiceAcctOAuthCredential(self): - yaml_doc = self._CreateYamlDoc({'woo': {}}, 'woo', { - 'service_account_email': 'abc@xyz.com'}) - with mock.patch('googleads.common.open', self.fake_open, create=True): - self.assertRaises( - googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromString, - yaml_doc, 'woo', [], []) - def testLoadFromString_passesWithNoRequiredKeys(self): yaml_doc = self._CreateYamlDoc({'woo': {}}, 'woo', self._OAUTH_INSTALLED_APP_DICT) @@ -471,24 +465,18 @@ def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { - 'http_proxy': {'host': self.host1, 'port': self.port1}, - 'https_proxy': {'host': self.host2, 'port': self.port2}}}, + 'http': self.uri1, + 'https': self.uri2}}, insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: - proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromString( - yaml_doc, 'adwords', [], []) - proxy.assert_has_calls([mock.call(self.host1, self.port1, - username=None, password=None), - mock.call(self.host2, self.port2, - username=None, password=None)]) + rval = googleads.common.LoadFromString( + yaml_doc, 'adwords', [], []) + proxy_config.assert_called_once_with( - http_proxy=proxy.return_value, - https_proxy=proxy.return_value, cafile=None, + http_proxy=self.uri1, https_proxy=self.uri2, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( 'a', 'b', 'c', proxy_config=proxy_config.return_value) @@ -497,35 +485,25 @@ def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) def testHTTPSProxyExtendsSSLSockTimeout(self): - with mock.patch('googleads.oauth2.GoogleRefreshTokenClient'): - with mock.patch('googleads.common.open', self.fake_open, create=True): - with mock.patch('suds.transport.http.' - 'HttpTransport.__init__') as mock_transport: - proxy_config = googleads.common.ProxyConfig() - proxy_config.GetSudsProxyTransport() - mock_transport.assert_called_once() - # 90 is the default, don't expect an exact value so that we can change - # the timeout in the code without returning here. - self.assertGreater(mock_transport.call_args_list[0][1]['timeout'], 90) + proxy_config = mock.MagicMock() + with mock.patch('suds.transport.http.' + 'HttpTransport.__init__') as mock_transport: + googleads.common._SudsProxyTransport(1000, proxy_config) + self.assertEqual(mock_transport.call_args_list[0][1]['timeout'], 1000) def testLoadFromString_passesWithHTTPProxy(self): yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { - 'http_proxy': {'host': self.host1, 'port': self.port1}}}, + 'http': self.uri1}}, insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: - proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromString( - yaml_doc, 'adwords', [], []) - - proxy.assert_called_once_with(self.host1, self.port1, - username=None, password=None) - proxy_config.assert_called_once_with(http_proxy=proxy.return_value, + rval = googleads.common.LoadFromString( + yaml_doc, 'adwords', [], []) + proxy_config.assert_called_once_with(http_proxy=self.uri1, https_proxy=None, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( @@ -538,23 +516,15 @@ def testLoadFromString_passesWithHTTPProxyLogin(self): yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { - 'http_proxy': {'host': self.host1, 'port': self.port1, - 'username': self.username, - 'password': self.password}}}, + 'http': self.uri1_w_creds}}, insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: - proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromString( - yaml_doc, 'adwords', [], []) + rval = googleads.common.LoadFromString(yaml_doc, 'adwords', [], []) - proxy.assert_called_once_with(self.host1, self.port1, - username=self.username, - password=self.password) - proxy_config.assert_called_once_with(http_proxy=proxy.return_value, + proxy_config.assert_called_once_with(http_proxy=self.uri1_w_creds, https_proxy=None, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( @@ -567,21 +537,16 @@ def testLoadFromString_passesWithHTTPSProxy(self): yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { - 'https_proxy': {'host': self.host1, 'port': self.port1}}}, + 'https': self.uri1}}, insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: - proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromString( - yaml_doc, 'adwords', [], []) + rval = googleads.common.LoadFromString(yaml_doc, 'adwords', [], []) - proxy.assert_called_once_with(self.host1, self.port1, - username=None, password=None) proxy_config.assert_called_once_with(http_proxy=None, - https_proxy=proxy.return_value, + https_proxy=self.uri1, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( @@ -594,24 +559,16 @@ def testLoadFromString_passesWithHTTPSProxyLogin(self): yaml_doc = self._CreateYamlDoc( {'adwords': {}, 'proxy_config': { - 'https_proxy': {'host': self.host1, 'port': self.port1, - 'username': self.username, - 'password': self.password}}}, + 'https': self.uri1_w_creds}}, insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() - with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: - proxy.return_value = mock.Mock() - rval = googleads.common.LoadFromString( - yaml_doc, 'adwords', [], []) + rval = googleads.common.LoadFromString(yaml_doc, 'adwords', [], []) - proxy.assert_called_once_with(self.host1, self.port1, - username=self.username, - password=self.password) proxy_config.assert_called_once_with(http_proxy=None, - https_proxy=proxy.return_value, + https_proxy=self.uri1_w_creds, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( @@ -620,23 +577,6 @@ def testLoadFromString_passesWithHTTPSProxyLogin(self): 'proxy_config': proxy_config.return_value, googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) - def testLoadFromString_failsWithMisconfiguredProxy(self): - yaml_doc = self._CreateYamlDoc( - {'adwords': {}, - 'proxy_config': { - 'http_proxy': {'host': self.host1}}}, - insert_oauth2_key='adwords', oauth_dict=self._OAUTH_INSTALLED_APP_DICT) - - with mock.patch('googleads.oauth2.GoogleRefreshTokenClient'): - with mock.patch('googleads.common.open', self.fake_open, create=True): - with mock.patch('googleads.common.ProxyConfig') as proxy_config: - proxy_config.return_value = mock.Mock() - with mock.patch('googleads.common.ProxyConfig.Proxy') as proxy: - proxy.return_value = mock.Mock() - self.assertRaises(googleads.errors.GoogleAdsValueError, - googleads.common.LoadFromString, - yaml_doc, 'adwords', [], []) - def testLoadFromString_missingRequiredKeys(self): with mock.patch('googleads.common.open', self.fake_open, create=True): # Both keys are missing. @@ -705,7 +645,7 @@ def testLoadFromString(self): rval) self.assertTrue(googleads.common._utility_registry._enabled) - def testLoadFromString_serviceAccountWithDeprecatedOAuth2Client(self): + def testLoadFromString_serviceAccount(self): dfp_scope = googleads.oauth2.GetAPIScope('dfp') # No optional keys present. yaml_doc = self._CreateYamlDoc( @@ -723,8 +663,7 @@ def testLoadFromString_serviceAccountWithDeprecatedOAuth2Client(self): http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( - dfp_scope, client_email='service_account@example.com', - key_file='/test/test.p12', sub='delegated_account@example.com', + '/test/test.json', dfp_scope, sub='delegated_account@example.com', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, @@ -748,8 +687,7 @@ def testLoadFromString_serviceAccountWithDeprecatedOAuth2Client(self): http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( - dfp_scope, client_email='service_account@example.com', - key_file='/test/test.p12', sub='delegated_account@example.com', + '/test/test.json', dfp_scope, sub='delegated_account@example.com', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, @@ -915,7 +853,7 @@ def testPackForSuds(self): rval = googleads.common._PackForSuds(input_list, factory) factory.create.assert_any_call('EliteCampaign') factory.create.assert_any_call('metadata') - self.assertIsInstance(rval, list) + self.assertEqual(len(rval), 2) self.assertEqual('Sales', rval[0].name) self.assertIsInstance(rval[0].id, suds.null) self.assertEqual({'b': 'c'}, rval[0].metadata.a) @@ -926,7 +864,7 @@ def testPackForSuds(self): {'i do not have': 'a type'}], input_list) def testPackForSuds_applyCustomPacker(self): - class CustomPacker(googleads.common.SudsPacker): + class CustomPacker(googleads.common.SoapPacker): @classmethod def Pack(cls, obj): if isinstance(obj, numbers.Number): @@ -953,45 +891,444 @@ def testPackForSuds_secondNamespace(self): self.assertEqual('Sales', rval.name) +@contextmanager +def mock_zeep_client(): + mock_port = mock.MagicMock() + mock_port.binding = mock.MagicMock() + mock_service = mock.MagicMock() + mock_service.ports.itervalues.return_value = iter([mock_port]) + mock_service.ports.values.return_value = iter([mock_port]) # For py3 + + with mock.patch('googleads.common.zeep.Client') as mock_client: + mock_services = mock_client.return_value.wsdl.services + mock_services.itervalues.return_value = iter([mock_service]) + mock_services.values.return_value = iter([mock_service]) # For py3 + + yield mock_client + + +class ZeepServiceProxyTest(unittest.TestCase): + + def setUp(self): + super(ZeepServiceProxyTest, self).setUp() + + self.empty_proxy_config = googleads.common.ProxyConfig() + self.timeout_100 = 100 + + def testCreateZeepClient(self): + header_handler = mock.Mock() + packer = mock.Mock() + + class MyCache(zeep.cache.Base): + pass + cache = MyCache() + + with mock_zeep_client() as mock_client, \ + mock.patch('googleads.common._ZeepAuthHeaderPlugin') as zeep_auth, \ + mock.patch('googleads.common._ZeepProxyTransport') as zeep_transport, \ + mock.patch('googleads.util.ZeepLogger') as zeep_logger: + zeep_wrapper = googleads.common.ZeepServiceProxy( + 'http://abc', header_handler, packer, 'proxy', 'timeout', cache) + + zeep_auth.assert_called_once_with(header_handler) + plugins = [zeep_auth.return_value, zeep_logger.return_value] + transport = zeep_transport.return_value + zeep_transport.assert_called_once_with('timeout', 'proxy', cache) + mock_client.assert_called_once_with( + 'http://abc', transport=transport, plugins=plugins) + self.assertEqual(zeep_wrapper.zeep_client, mock_client.return_value) + + def testCreateSoapElementForType(self): + header_handler = mock.Mock() + packer = mock.Mock() + + with mock_zeep_client(): + zeep_wrapper = googleads.common.ZeepServiceProxy( + 'http://abc', header_handler, packer, + self.empty_proxy_config, self.timeout_100) + + type_mock = mock.Mock() + zeep_wrapper.zeep_client.get_type.return_value = type_mock + result = zeep_wrapper.CreateSoapElementForType('MyType') + self.assertEqual(result, type_mock.return_value) + zeep_wrapper.zeep_client.get_type.assert_called_once_with('MyType') + + def testWsdlHasMethod(self): + header_handler = mock.Mock() + packer = mock.Mock() + + with mock_zeep_client(): + zeep_wrapper = googleads.common.ZeepServiceProxy( + 'http://abc', header_handler, packer, + self.empty_proxy_config, self.timeout_100) + + with mock.patch.object(zeep_wrapper, '_method_bindings') as mock_bindings: + get_method = mock_bindings.get + + self.assertTrue(zeep_wrapper._WsdlHasMethod('abc')) + + get_method.side_effect = ValueError + self.assertFalse(zeep_wrapper._WsdlHasMethod('abc')) + + def testZeepErrorRaisesGoogleError(self): + with mock_zeep_client() as mock_client: + mock_client.side_effect = requests.exceptions.HTTPError + + with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError): + googleads.common.ZeepServiceProxy( + 'http://abc', None, None, self.empty_proxy_config, self.timeout_100) + + @mock.patch('googleads.common._ZeepProxyTransport') + def testSchemaHelperRaisesGoogleError(self, mock_transport_class): + mock_transport_class.return_value.load.side_effect = ( + requests.exceptions.HTTPError) + + with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError): + googleads.common.ZeepSchemaHelper(None, None, None, 100, None) + + def testGetRequestXML(self): + header_handler = mock.Mock() + packer = mock.Mock() + + with mock_zeep_client(): + zeep_wrapper = googleads.common.ZeepServiceProxy( + 'http://abc', header_handler, packer, + self.empty_proxy_config, self.timeout_100) + + mock_create = zeep_wrapper.zeep_client.create_message + + with mock.patch.object( + zeep_wrapper, + '_GetZeepFormattedSOAPHeaders') as mock_get_headers, \ + mock.patch.object(zeep_wrapper, '_PackArguments') as mock_pack: + mock_pack.return_value = [1, 2, 3] + + result = zeep_wrapper.GetRequestXML('someMethod', 'a', 1, 2) + + self.assertEqual(result, mock_create.return_value) + mock_pack.assert_called_once_with( + 'someMethod', ('a', 1, 2), set_type_attrs=True) + mock_create.assert_called_once_with( + zeep_wrapper.zeep_client.service, 'someMethod', 1, 2, 3, + _soapheaders=mock_get_headers.return_value) + + def testBadCacheType(self): + header_handler = mock.Mock() + packer = mock.Mock() + + with mock_zeep_client(), self.assertRaises(ValueError): + googleads.common.ZeepServiceProxy( + 'http://abc', header_handler, packer, + self.empty_proxy_config, self.timeout_100, cache='not_a_zeep_cache') + + def testAllowsNoCache(self): + header_handler = mock.Mock() + packer = mock.Mock() + + with mock_zeep_client(),\ + mock.patch('googleads.common._ZeepProxyTransport') as zeep_transport: + googleads.common.ZeepServiceProxy( + 'http://abc', header_handler, packer, + self.empty_proxy_config, self.timeout_100, + cache=googleads.common.ZeepServiceProxy.NO_CACHE) + + zeep_transport.assert_called_once_with( + self.timeout_100, self.empty_proxy_config, + googleads.common.ZeepServiceProxy.NO_CACHE) + + def testFaultWithErrors(self): + detail = mock.Mock() + fault = zeep.exceptions.Fault('message', detail=detail) + header_handler = mock.Mock() + packer = mock.Mock() + + with mock_zeep_client(): + zeep_wrapper = googleads.common.ZeepServiceProxy( + 'http://abc', header_handler, packer, + googleads.common.ProxyConfig(), 100) + + zeep_wrapper.zeep_client.service['mymethod'].side_effect = fault + zeep_wrapper._GetBindingNamespace = mock.Mock() + + with self.assertRaises(googleads.errors.GoogleAdsServerFault) as e: + zeep_wrapper.mymethod() + + self.assertEqual(e.exception.document, detail) + self.assertIn('message', str(e.exception)) + + def testIsBase64(self): + result = googleads.common.ZeepServiceProxy._IsBase64('abcd') + self.assertTrue(result) + + def testIsBase64Exception(self): + result = googleads.common.ZeepServiceProxy._IsBase64('abc') + self.assertFalse(result) + + def testIsBase64DataBad(self): + result = googleads.common.ZeepServiceProxy._IsBase64('%%%%') + self.assertFalse(result) + + +class TestZeepArgumentPacking(unittest.TestCase): + + def setUp(self): + header_handler = mock.Mock() + + wsdl_path = os.path.join(TEST_DIR, 'test_data/dfp_report_service.xml') + self.zeep_client = googleads.common.ZeepServiceProxy( + wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100) + + def testPackArgumentsPrimitivesOnly(self): + result = self.zeep_client._PackArguments('getReportJobStatus', [5]) + six.assertCountEqual(self, result, [5]) + + def testPackArgumentsWithSimpleDict(self): + opts = { + 'exportFormat': 'CSV', + 'includeReportProperties': False, + 'includeTotalsRow': True, + 'useGzipCompression': False} + result = self.zeep_client._PackArguments( + 'getReportDownloadUrlWithOptions', [123, opts]) + self.assertEqual(result[0], 123) + self.assertEqual(result[1].exportFormat, 'CSV') + self.assertEqual(result[1].includeTotalsRow, True) + + def testPackArgumentsWithCustomTypeAndList(self): + data = { + 'reportQuery': { + 'adUnitView': 'HIERARCHICAL', + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS'], + 'dateRangeType': 'LAST_WEEK', + 'dimensions': ['DATE', 'AD_UNIT_NAME'], + 'statement': { + 'query': 'WHERE PARENT_AD_UNIT_ID = :parentAdUnitId', + 'values': [{ + 'key': 'parentAdUnitId', + 'value': { + 'value': 606389, 'xsi_type': 'NumberValue'}}]}}} + result = self.zeep_client._PackArguments('runReportJob', [data]) + self.assertEqual(result[0].reportQuery.adUnitView, 'HIERARCHICAL') + self.assertEqual(result[0].reportQuery.dimensions[1], 'AD_UNIT_NAME') + number_value = result[0].reportQuery.statement.values[0].value + number_type = self.zeep_client.zeep_client.get_type('ns0:NumberValue') + self.assertEqual(type(number_value), number_type._value_class) + + def testPackArgumentsWithCustomPacker(self): + class CustomPacker(googleads.common.SoapPacker): + + @classmethod + def Pack(cls, obj): + if isinstance(obj, numbers.Number): + return '50' + return obj + + self.zeep_client._packer = CustomPacker + result = self.zeep_client._PackArguments('getReportJobStatus', [5])[0] + self.assertEqual(result, '50') + + def testPackArgumentsBase64Warning(self): + image_type = self.zeep_client.zeep_client.get_type('ns0:Image') + b64_type = image_type.elements[0][1] + data = 'abcd' # This is valid base64 + + with mock.patch('googleads.common._logger'): + self.zeep_client._PackArgumentsHelper(b64_type, data, False) + self.assertTrue(len(googleads.common._logger.warn.mock_calls)) + + class SudsServiceProxyTest(unittest.TestCase): """Tests for the googleads.common.SudsServiceProxy class.""" - def setUp(self): - self.header_handler = mock.Mock() - self.port = mock.Mock() - self.port.methods = ('SoapMethod',) - self.services = mock.Mock() - self.services.ports = [self.port] - self.client = mock.Mock() - self.client.wsdl.services = [self.services] - self.datetime_packer = mock.Mock() - self.suds_service_wrapper = googleads.common.SudsServiceProxy( - self.client, self.header_handler, self.datetime_packer) - - def testSudsServiceProxy(self): - self.assertEqual(self.suds_service_wrapper.SoapMethod, - self.suds_service_wrapper._method_proxies['SoapMethod']) - self.assertEqual(self.suds_service_wrapper.NotSoapMethod, - self.client.service.NotSoapMethod) - - with mock.patch('googleads.common._PackForSuds') as mock_pack_for_suds: - mock_pack_for_suds.return_value = 'modified_test' - self.suds_service_wrapper.SoapMethod('test') - mock_pack_for_suds.assert_called_once_with('test', self.client.factory, - self.datetime_packer) - - self.client.service.SoapMethod.assert_called_once_with('modified_test') - self.header_handler.SetHeaders.assert_called_once_with(self.client) - - -class HeaderHandlerTest(unittest.TestCase): - """Tests for the googleads.common.HeaderHeader class.""" + def testCreateSudsClient(self): + class MyCache(suds.cache.Cache): + pass + + cache = MyCache() + header_handler = mock.Mock() + packer = mock.Mock() + proxy_config = mock.Mock() + + with mock.patch('googleads.common.suds.client.Client') as mock_suds_client: + mock_suds_client.return_value = 'suds_client' + + with mock.patch('googleads.common.LoggingMessagePlugin') as mock_logging: + mock_logging.return_value = 'logging' + + with mock.patch('googleads.common' + '._SudsProxyTransport') as mock_transport: + mock_transport.return_value = 'transport' + + suds_wrapper = googleads.common.SudsServiceProxy( + 'https://endpoint', header_handler, packer, proxy_config, + 1000, cache) + + mock_transport.assert_called_once_with(1000, proxy_config) + mock_suds_client.assert_called_once_with( + 'https://endpoint', timeout=1000, cache=cache, + transport='transport', plugins=['logging']) + self.assertEqual(suds_wrapper.suds_client, 'suds_client') + + @contextmanager + def mock_suds_api(self): + with mock.patch('googleads.common._SudsProxyTransport'), \ + mock.patch('googleads.common.suds.client.Client') as mock_suds_client: + yield mock_suds_client + + def testSudsErrorRaisesGoogleError(self): + with self.mock_suds_api() as mock_suds_client: + mock_suds_client.side_effect = suds.transport.TransportError(None, None) + with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError): + googleads.common.SudsServiceProxy( + 'https://endpoint', None, None, None, 1000, None) + + def testSchemaHelperRaisesGoogleError(self): + with self.mock_suds_api() as mock_suds_client: + mock_suds_client.side_effect = suds.transport.TransportError(None, None) + + with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError): + googleads.common.SudsSchemaHelper(None, None, None, 100, None) + + + def testGetMethod(self): + header_handler = mock.Mock() + wrapped_method = mock.Mock() + wrapped_method.return_value = 'wrap_result' + + with self.mock_suds_api() as mock_suds_client_class: + mock_suds_client = mock.MagicMock() + mock_suds_client_class.return_value = mock_suds_client + + suds_wrapper = googleads.common.SudsServiceProxy( + 'https://endpoint', header_handler, None, None, 1000, None + ) + + with mock.patch.object(suds_wrapper, '_CreateMethod') as mock_create: + mock_create.return_value = wrapped_method + + services_dict = {'method1': True} + suds_contains_method = (mock_suds_client.wsdl.services[0].ports[0] + .methods.__contains__) + suds_contains_method.side_effect = services_dict.__contains__ + result = suds_wrapper.method1() + self.assertEqual(result, 'wrap_result') + + @contextmanager + def get_suds_api_with_mocked_method(self, mock_method): + header_handler = mock.Mock() + with self.mock_suds_api() as mock_suds_client_class: + mock_suds_client = mock.MagicMock() + mock_suds_client_class.return_value = mock_suds_client + + suds_wrapper = googleads.common.SudsServiceProxy( + 'https://endpoint', header_handler, None, None, 1000, None + ) + with mock.patch('googleads.common._ExtractResponseSummaryFields'): + with mock.patch.object(suds_wrapper, + '_WsdlHasMethod') as mock_has_method: + mock_has_method.return_value = True + + suds_wrapper.suds_client.service.method1 = mock_method + suds_wrapper._method_proxies['method1'] = ( + suds_wrapper._CreateMethod('method1')) + + yield suds_wrapper + + def testNoDetailError(self): + mock_method = mock.Mock() + mock_document = mock.Mock() + + class MockFault(object): + faultstring = 'abc' + + mock_method.side_effect = suds.WebFault(MockFault(), mock_document) + + with self.get_suds_api_with_mocked_method(mock_method) as suds_wrapper: + with self.assertRaises(googleads.errors.GoogleAdsServerFault) as e: + suds_wrapper.method1() + + self.assertEqual(len(e.exception.errors), 0) + self.assertEqual(e.exception.document, mock_document) + self.assertIn('abc', str(e.exception)) + + def testEmptyListError(self): + mock_method = mock.Mock() + mock_document = mock.Mock() + + class MockFault(object): + faultstring = 'abc' + detail = mock.Mock() + + def __init__(self): + self.detail.ApiExceptionFault.errors = None + + mock_fault = MockFault() + + mock_method.side_effect = suds.WebFault(mock_fault, mock_document) + + with self.get_suds_api_with_mocked_method(mock_method) as suds_wrapper: + with self.assertRaises(googleads.errors.GoogleAdsServerFault) as e: + suds_wrapper.method1() + self.assertEqual(len(e.exception.errors), 0) + self.assertEqual(e.exception.document, mock_document) + self.assertIn('abc', str(e.exception)) + + def testFaultWithErrors(self): + mock_method = mock.Mock() + mock_document = mock.Mock() + + class MockFault(object): + faultstring = 'abc' + detail = mock.Mock() + + def __init__(self): + self.detail.ApiExceptionFault.errors = ['1', '2', '3'] + + mock_fault = MockFault() + + mock_method.side_effect = suds.WebFault(mock_fault, mock_document) + + with self.get_suds_api_with_mocked_method(mock_method) as suds_wrapper: + with self.assertRaises(googleads.errors.GoogleAdsServerFault) as e: + suds_wrapper.method1() + six.assertCountEqual(self, e.exception.errors, ['1', '2', '3']) + self.assertEqual(e.exception.document, mock_document) + self.assertIn('abc', str(e.exception)) + + def testGetRequestXML(self): + mock_method = mock.Mock() + mock_method.return_value.envelope = '' + + with self.get_suds_api_with_mocked_method(mock_method) as suds_wrapper, \ + mock.patch.object(suds_wrapper, 'SetHeaders'): + ops = ['abc', '123'] + result = suds_wrapper.GetRequestXML('method1', ops) + toggle_calls = [mock.call(nosend=True), mock.call(nosend=False)] + suds_wrapper.suds_client.set_options.assert_has_calls(toggle_calls) + self.assertEqual(result.tag, 'a') + + def testCreateSoapElementForType(self): + with self.mock_suds_api(): + suds_wrapper = googleads.common.SudsServiceProxy( + 'https://endpoint', None, None, None, 1000, None) + suds_wrapper.suds_client.factory.create.return_value = 'result' + + result = suds_wrapper.CreateSoapElementForType('MyType') + self.assertEqual(result, 'result') def testSetHeaders(self): - """For coverage.""" - self.assertRaises( - NotImplementedError, googleads.common.HeaderHandler().SetHeaders, - mock.Mock()) + with self.mock_suds_api(): + suds_wrapper = googleads.common.SudsServiceProxy( + 'https://endpoint', None, None, None, 1000, None) + + suds_wrapper.SetHeaders('soap', 'http') + suds_wrapper.suds_client.set_options.assert_called_once_with( + soapheaders='soap', headers='http') + + def testBadCache(self): + with self.mock_suds_api(), self.assertRaises(ValueError): + googleads.common.SudsServiceProxy( + 'https://endpoint', None, None, None, 1000, 'not_a_suds_cache') class LoggingMessagePluginTest(unittest.TestCase): @@ -1026,28 +1363,16 @@ def testParsed(self): class ProxyConfigTest(unittest.TestCase): - """Tests fpr the googleads.common.ProxyConfig class.""" + """Tests for the googleads.common.ProxyConfig class.""" def setUp(self): - self.proxy_host1 = 'host1' - self.proxy_port1 = 'port1' - self.proxy_host2 = 'host2' - self.proxy_port2 = 'port2' - self.username = 'username' - self.password = 'password' self.cafile = os.path.join(os.path.dirname(__file__), 'test_data/test.crt') - - self.proxy_no_credentials = googleads.common.ProxyConfig.Proxy( - self.proxy_host1, self.proxy_port1) - - self.proxy_with_credentials = googleads.common.ProxyConfig.Proxy( - self.proxy_host2, self.proxy_port2, username=self.username, - password=self.password) + self.proxy_no_credentials = 'http://host1:port1' + self.proxy_with_credentials = 'http://username:password@host2:port2' def testBuildOpenerWithConfig(self): - https_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, - self.proxy_port1) - proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) + proxy_config = googleads.common.ProxyConfig( + https_proxy=self.proxy_no_credentials) with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mck_build_opener: with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as mck_https_hndlr: @@ -1070,206 +1395,102 @@ def testBuildOpenerWithDefaultConfig(self): proxy_config.BuildOpener() mck_build_opener.assert_called_once_with(*[mock_https_hndlr_instance]) - def testProxyToStringWithCredentials(self): - proxy = googleads.common.ProxyConfig.Proxy( - self.proxy_host1, self.proxy_port1, username=self.username, - password=self.password) - self.assertEqual(str(proxy), - '%s:%s@%s:%s' % (self.username, self.password, - self.proxy_host1, - self.proxy_port1)) - - def testProxyToStringWithoutCredentials(self): - proxy = googleads.common.ProxyConfig.Proxy( - self.proxy_host2, self.proxy_port2) - self.assertEqual(str(proxy), - '%s:%s' % (self.proxy_host2, self.proxy_port2)) - - def testProxyToStringWithOnlyUsername(self): - proxy = googleads.common.ProxyConfig.Proxy( - self.proxy_host1, self.proxy_port1, username=self.username) - self.assertEqual(str(proxy), - '%s:@%s:%s' % (self.username, self.proxy_host1, - self.proxy_port1)) - def testProxyConfigGetHandlersWithNoProxyOrSSLContext(self): proxy_config = googleads.common.ProxyConfig() with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance - self.assertIn(https_handler_instance, proxy_config.GetHandlers()) + + transport = googleads.common._SudsProxyTransport(0, proxy_config) + self.assertIn(https_handler_instance, transport.handlers) def testProxyConfigGetHandlersWithProxy(self): - http_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, - self.proxy_port1) with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: proxy_handler_instance = mock.Mock() proxy_handler.return_value = proxy_handler_instance - proxy_config = googleads.common.ProxyConfig(http_proxy=http_proxy) + proxy_config = googleads.common.ProxyConfig( + http_proxy=self.proxy_no_credentials) with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler_instance = mock.Mock() https_handler.return_value = https_handler_instance - self.assertEqual(proxy_config.GetHandlers(), + + transport = googleads.common._SudsProxyTransport(0, proxy_config) + self.assertEqual(transport.handlers, [https_handler_instance, proxy_handler_instance]) proxy_handler.assert_called_once_with( - {'http': '%s' % str(http_proxy)}) + {'http': self.proxy_no_credentials}) def testProxyConfigGetHandlersWithProxyAndSLLContext(self): - https_proxy = googleads.common.ProxyConfig.Proxy(self.proxy_host1, - self.proxy_port1) with mock.patch('googleads.common.ProxyConfig._InitSSLContext') as ssl_ctxt: ssl_ctxt.return_value = 'CONTEXT' with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: proxy_handler.return_value = mock.Mock() with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: https_handler.return_value = mock.Mock() - proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) - self.assertEqual(proxy_config.GetHandlers(), + + proxy_config = googleads.common.ProxyConfig( + https_proxy=self.proxy_no_credentials) + transport = googleads.common._SudsProxyTransport(0, proxy_config) + self.assertEqual(transport.handlers, [https_handler.return_value, proxy_handler.return_value]) proxy_handler.assert_called_once_with( - {'https': '%s' % str(https_proxy)}) + {'https': self.proxy_no_credentials}) https_handler.assert_called_once_with( context=ssl_ctxt.return_value) def testProxyConfigWithNoProxy(self): proxy_config = googleads.common.ProxyConfig() - self.assertEqual(proxy_config.proxy_info, None) - - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: - https_handler_instance = mock.Mock() - https_handler.return_value = https_handler_instance - self.assertEqual(proxy_config.GetHandlers(), - [https_handler_instance]) - self.assertIsInstance( - proxy_config._ssl_context, ssl.SSLContext) - - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: - t.return_value = mock.Mock() - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: - https_handler_instance = mock.Mock() - https_handler.return_value = https_handler_instance - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with([https_handler_instance]) - self.assertEqual(t.return_value, transport) + self.assertEqual(proxy_config.proxies, {}) + self.assertIsInstance( + proxy_config.ssl_context, ssl.SSLContext) def testProxyConfigWithHTTPProxy(self): - with mock.patch('httplib2.ProxyInfo') as proxy_info: - proxy_info.return_value = mock.Mock() - with mock.patch('socks.PROXY_TYPE_HTTP') as proxy_type: - proxy_config = googleads.common.ProxyConfig( - http_proxy=self.proxy_no_credentials) - proxy_info.assert_called_once_with( - proxy_type, self.proxy_host1, self.proxy_port1, - proxy_user=None, proxy_pass='') - self.assertEqual(proxy_config.proxy_info, proxy_info.return_value) - self.assertEqual(proxy_config._proxy_option, {'http': '%s:%s' % ( - self.proxy_host1, self.proxy_port1)}) + proxy_config = googleads.common.ProxyConfig( + http_proxy=self.proxy_no_credentials) + self.assertEqual(proxy_config.proxies, {'http': self.proxy_no_credentials}) self.assertIsInstance( - proxy_config._ssl_context, ssl.SSLContext) - - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: - t.return_value = mock.Mock() - with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: - proxy_handler_instance = mock.Mock() - proxy_handler.return_value = proxy_handler_instance - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: - https_handler_instance = mock.Mock() - https_handler.return_value = https_handler_instance - self.assertEqual(proxy_config.GetHandlers(), - [https_handler_instance, proxy_handler_instance]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with( - [https_handler_instance, proxy_handler_instance]) - self.assertEqual(t.return_value, transport) + proxy_config.ssl_context, ssl.SSLContext) def testProxyConfigWithHTTPSProxy(self): - with mock.patch('httplib2.ProxyInfo') as proxy_info: - proxy_info.return_value = mock.Mock() - with mock.patch('socks.PROXY_TYPE_HTTP') as proxy_type: - proxy_config = googleads.common.ProxyConfig( - https_proxy=self.proxy_with_credentials, - cafile=self.cafile) - proxy_info.assert_called_once_with( - proxy_type, self.proxy_host2, self.proxy_port2, - proxy_user=self.username, proxy_pass=self.password) - self.assertEqual(proxy_config.proxy_info, proxy_info.return_value) - self.assertEqual(proxy_config._proxy_option, {'https': '%s:%s@%s:%s' % ( - self.username, self.password, self.proxy_host2, - self.proxy_port2)}) + proxy_config = googleads.common.ProxyConfig( + https_proxy=self.proxy_with_credentials, + cafile=self.cafile) + self.assertEqual(proxy_config.proxies, { + 'https': self.proxy_with_credentials}) self.assertIsInstance( - proxy_config._ssl_context, ssl.SSLContext) + proxy_config.ssl_context, ssl.SSLContext) self.assertEqual(proxy_config.cafile, self.cafile) self.assertEqual(proxy_config.disable_certificate_validation, False) - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: - t.return_value = mock.Mock() - with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: - proxy_handler_instance = mock.Mock() - proxy_handler.return_value = proxy_handler_instance - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: - https_handler_instance = mock.Mock() - https_handler.return_value = https_handler_instance - self.assertEqual( - proxy_config.GetHandlers(), - [https_handler_instance, proxy_handler_instance]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with( - [https_handler_instance, proxy_handler_instance]) - self.assertEqual(t.return_value, transport) - def testProxyConfigWithHTTPAndHTTPSProxy(self): - with mock.patch('httplib2.ProxyInfo') as proxy_info: - proxy_info.return_value = mock.Mock() - with mock.patch('socks.PROXY_TYPE_HTTP') as proxy_type: - proxy_config = googleads.common.ProxyConfig( - http_proxy=self.proxy_with_credentials, - https_proxy=self.proxy_no_credentials, - disable_certificate_validation=True) - proxy_info.assert_called_once_with( - proxy_type, self.proxy_host1, self.proxy_port1, - proxy_user=None, proxy_pass='') - self.assertEqual(proxy_config.proxy_info, proxy_info.return_value) - self.assertEqual(proxy_config._proxy_option, { - 'http': '%s:%s@%s:%s' % (self.username, self.password, - self.proxy_host2, self.proxy_port2), - 'https': '%s:%s' % (self.proxy_host1, self.proxy_port1)}) - - self.assertIsInstance(proxy_config._ssl_context, ssl.SSLContext) + proxy_config = googleads.common.ProxyConfig( + http_proxy=self.proxy_with_credentials, + https_proxy=self.proxy_no_credentials, + disable_certificate_validation=True) + self.assertEqual(proxy_config.proxies, { + 'http': self.proxy_with_credentials, + 'https': self.proxy_no_credentials}) + + self.assertIsInstance(proxy_config.ssl_context, ssl.SSLContext) self.assertEqual(proxy_config.cafile, None) self.assertEqual(proxy_config.disable_certificate_validation, True) - with mock.patch('googleads.common.ProxyConfig._SudsProxyTransport') as t: - t.return_value = mock.Mock() - with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: - proxy_handler_instance = mock.Mock() - proxy_handler.return_value = proxy_handler_instance - - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: - https_handler_instance = mock.Mock() - https_handler.return_value = https_handler_instance - self.assertEqual( - proxy_config.GetHandlers(), - [https_handler_instance, proxy_handler_instance]) - transport = proxy_config.GetSudsProxyTransport() - t.assert_called_once_with( - [https_handler_instance, proxy_handler_instance]) - self.assertEqual(t.return_value, transport) +class MockHeaders(object): -class TestSudsRequestPatcher(unittest.TestCase): + def __init__(self, d): + self.dict = d - class MockHeaders(object): + # If testing on Python 3, add get method to better mimic the + # http.client.HTTPMessage behavior. + if six.PY3: + def py3_get(s): + return self.dict.get(s) + self.get = py3_get - def __init__(self, d): - self.dict = d - # If testing on Python 3, add get method to better mimic the - # http.client.HTTPMessage behavior. - if six.PY3: - def py3_get(s): - return self.dict.get(s) - self.get = py3_get +class TestSudsRequestPatcher(unittest.TestCase): def testInflateSuccessfulRequestIfGzipped(self): with mock.patch('suds.transport.http.HttpTransport.getcookies'): @@ -1280,7 +1501,7 @@ def testInflateSuccessfulRequestIfGzipped(self): resp_fp.flush() resp_fp.seek(0) resp = six.moves.urllib.response.addinfourl( - resp_fp, self.MockHeaders({'content-encoding': 'gzip'}), + resp_fp, MockHeaders({'content-encoding': 'gzip'}), 'https://example.com', code=200) mock_open.return_value = resp @@ -1301,7 +1522,7 @@ def testInflateFailedRequestIfGzipped(self): resp_fp.flush() resp_fp.seek(0) resp = six.moves.urllib.response.addinfourl( - resp_fp, self.MockHeaders({'content-encoding': 'gzip'}), + resp_fp, MockHeaders({'content-encoding': 'gzip'}), 'https://example.com', code=200) def fail_to_open(*args, **kwargs): diff --git a/tests/dfp_test.py b/tests/dfp_test.py index 9c138a6b..f80153b6 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -22,7 +22,6 @@ import mock import pytz import six -import suds.transport import googleads.dfp import googleads.common import googleads.errors @@ -118,7 +117,7 @@ def setUp(self): self.util_sig_template = ' (%s, %s, %s, %s)' self.network_code = 'my network code is code' self.app_name = 'application name' - self.oauth_header = {'oauth', 'header'} + self.oauth_header = {'oauth': 'header'} @googleads.common.RegisterUtility(self.utility_name) class TestUtility(object): @@ -128,42 +127,41 @@ def Test(self): self.test_utility = TestUtility() - def testSetHeaders(self): - suds_client = mock.Mock() - self.dfp_client.network_code = self.network_code - self.dfp_client.application_name = self.app_name + def testGetHTTPHeaders(self): self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( self.oauth_header) - self.header_handler.SetHeaders(suds_client) + header_result = self.header_handler.GetHTTPHeaders() + + # Check that the returned headers have the correct values. + self.assertEqual(header_result, self.oauth_header) + + def testGetSOAPHeaders(self): + create_method = mock.Mock() + self.dfp_client.network_code = self.network_code + self.dfp_client.application_name = self.app_name + + header_result = self.header_handler.GetSOAPHeaders(create_method) # Check that the SOAP header has the correct values. - suds_client.factory.create.assert_called_once_with('SoapRequestHeader') - soap_header = suds_client.factory.create.return_value - self.assertEqual(self.network_code, soap_header.networkCode) + create_method.assert_called_once_with('ns0:SoapRequestHeader') + self.assertEqual(self.network_code, header_result.networkCode) self.assertEqual( ''.join([ self.app_name, googleads.common.GenerateLibSig( googleads.dfp._DfpHeaderHandler._PRODUCT_SIG)]), - soap_header.applicationName) - - # Check that the suds client has the correct values. - suds_client.set_options.assert_any_call(soapheaders=soap_header, - headers=self.oauth_header) + header_result.applicationName) - def testSetHeadersUserAgentWithUtility(self): - suds_client = mock.Mock() + def testGetSOAPHeadersUserAgentWithUtility(self): + create_method = mock.Mock() self.dfp_client.network_code = self.network_code self.dfp_client.application_name = self.app_name - self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( - self.oauth_header) with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: self.test_utility.Test() # This will register TestUtility. - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value + soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( ''.join([self.app_name, self.util_sig_template % ( @@ -173,20 +171,17 @@ def testSetHeadersUserAgentWithUtility(self): self.utility_name)]), soap_header.applicationName) - def testSetHeadersUserAgentWithAndWithoutUtility(self): - suds_client = mock.Mock() + def testGetHeadersUserAgentWithAndWithoutUtility(self): + create_method = mock.Mock() self.dfp_client.network_code = self.network_code self.dfp_client.application_name = self.app_name - self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( - self.oauth_header) with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: # Check headers when utility registered. self.test_utility.Test() # This will register TestUtility. - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value + soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( ''.join([self.app_name, self.util_sig_template % ( @@ -197,8 +192,7 @@ def testSetHeadersUserAgentWithAndWithoutUtility(self): soap_header.applicationName) # Check headers when no utility should be registered. - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value + soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( ''.join([self.app_name, self.default_sig_template % ( @@ -209,8 +203,7 @@ def testSetHeadersUserAgentWithAndWithoutUtility(self): # Verify that utility is registered in subsequent uses. self.test_utility.Test() # This will register TestUtility. - self.header_handler.SetHeaders(suds_client) - soap_header = suds_client.factory.create.return_value + soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( ''.join([self.app_name, self.util_sig_template % ( @@ -232,8 +225,7 @@ def setUp(self): self.oauth2_client.CreateHttpHeader.return_value = {} self.proxy_host = 'myproxy' self.proxy_port = 443 - self.https_proxy = googleads.common.ProxyConfig.Proxy(host=self.proxy_host, - port=self.proxy_port) + self.https_proxy = 'http://myproxy:443' self.proxy_config = googleads.common.ProxyConfig( https_proxy=self.https_proxy) self.cache = None @@ -306,96 +298,46 @@ def testInitializeWithUselessApplicationName(self): self.https_proxy, self.cache) def testGetService_success(self): - service = googleads.dfp._SERVICE_MAP[self.version][0] + dfp_client = self.CreateDfpClient( + cache='cache', proxy_config='proxy', timeout='timeout') + service_name = googleads.dfp._SERVICE_MAP[self.version][0] # Use a custom server. Also test what happens if the server ends with a # trailing slash server = 'https://testing.test.com/' - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.' - 'ProxyConfig._SudsProxyTransport') as mock_transport: - with mock.patch('googleads.common.' - 'SudsServiceProxy') as mock_service_proxy: - with mock.patch('googleads.common.LoggingMessagePlugin') as mck_plugn: - mock_plugin_instance = mock.Mock() - mck_plugn.return_value = mock_plugin_instance - dfp_client = self.CreateDfpClient() - mock_service_proxy.return_value = mock.Mock() - mock_transport.return_value = mock.Mock() - mock_client.return_value = mock.Mock() - mock_client.return_value.sd.__getitem__ = mock.Mock() - suds_service = dfp_client.GetService(service, self.version, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), timeout=3600, - transport=mock_transport.return_value, - plugins=[mock_plugin_instance]) - self.assertEqual(suds_service, mock_service_proxy.return_value) - mock_service_proxy.assert_called_once_with( - mock_client.return_value, - dfp_client._header_handler, - packer=googleads.dfp._DfpPacker) - - def testGetService_successWithNoCache(self): - service = googleads.dfp._SERVICE_MAP[self.version][0] - no_cache = suds.cache.NoCache() + with mock.patch('googleads.common.' + 'GetServiceClassForLibrary') as mock_get_service: + impl = mock.Mock() + mock_service = mock.Mock() + impl.return_value = mock_service + mock_get_service.return_value = impl - # Use a custom server. Also test what happens if the server ends with a - # trailing slash - server = 'https://testing.test.com/' - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.' - 'ProxyConfig._SudsProxyTransport') as mock_transport: - with mock.patch('googleads.common.LoggingMessagePlugin') as mck_plugn: - mock_plugin_instance = mock.Mock() - mck_plugn.return_value = mock_plugin_instance - dfp_client = self.CreateDfpClient(cache=no_cache) - mock_transport.return_value = mock.Mock() - suds_service = dfp_client.GetService(service, self.version, server) - - mock_client.assert_called_once_with( - 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), timeout=3600, - cache=no_cache, transport=mock_transport.return_value, - plugins=[mock_plugin_instance]) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) - - def testGetService_successWithoutProxy(self): - service = googleads.dfp._SERVICE_MAP[self.version][0] + service = dfp_client.GetService(service_name, self.version, server) + + impl.assert_called_once_with( + 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' + % (self.version, service_name), dfp_client._header_handler, + googleads.dfp._DfpPacker, 'proxy', 'timeout', + cache='cache') + self.assertEqual(service, mock_service) - with mock.patch('suds.client.Client') as mock_client: - with mock.patch('googleads.common.' - 'ProxyConfig._SudsProxyTransport') as mock_transport: - with mock.patch('googleads.common.LoggingMessagePlugin') as mck_plugn: - mock_plugin_instance = mock.Mock() - mck_plugn.return_value = mock_plugin_instance - dfp_client = self.CreateDfpClient() - # Use the default server without a proxy. - dfp_client.proxy_option = None - mock_transport.return_value = mock.Mock() - suds_service = dfp_client.GetService(service, self.version) - - mock_client.assert_called_once_with( - 'https://ads.google.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service), timeout=3600, - transport=mock_transport.return_value, - plugins=[mock_plugin_instance]) - self.assertFalse(mock_client.return_value.set_options.called) - self.assertIsInstance(suds_service, googleads.common.SudsServiceProxy) def testGetService_badService(self): dfp_client = self.CreateDfpClient() - with mock.patch('suds.client.Client') as mock_client: - mock_client.side_effect = suds.transport.TransportError('', '') + with mock.patch('googleads.common.' + 'GetServiceClassForLibrary') as mock_get_service: + mock_get_service.side_effect = ( + googleads.errors.GoogleAdsSoapTransportError('', '')) self.assertRaises( googleads.errors.GoogleAdsValueError, dfp_client.GetService, 'GYIVyievfyiovslf', self.version) def testGetService_badVersion(self): dfp_client = self.CreateDfpClient() - with mock.patch('suds.client.Client') as mock_client: - mock_client.side_effect = suds.transport.TransportError('', '') + with mock.patch('googleads.common.' + 'GetServiceClassForLibrary') as mock_get_service: + mock_get_service.side_effect = ( + googleads.errors.GoogleAdsSoapTransportError('', '')) self.assertRaises( googleads.errors.GoogleAdsValueError, dfp_client.GetService, 'CampaignService', '11111') @@ -403,9 +345,11 @@ def testGetService_badVersion(self): def testGetService_transportError(self): service = googleads.dfp._SERVICE_MAP[self.version][0] dfp_client = self.CreateDfpClient() - with mock.patch('suds.client.Client') as mock_client: - mock_client.side_effect = suds.transport.TransportError('', '') - self.assertRaises(suds.transport.TransportError, + with mock.patch('googleads.common.' + 'GetServiceClassForLibrary') as mock_get_service: + mock_get_service.side_effect = ( + googleads.errors.GoogleAdsSoapTransportError('', '')) + self.assertRaises(googleads.errors.GoogleAdsSoapTransportError, dfp_client.GetService, service, self.version) diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index 939e96d2..eca30dce 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -18,7 +18,6 @@ import datetime import unittest -import httplib2 import mock import six import googleads.common @@ -26,16 +25,11 @@ import googleads.oauth2 from pyfakefs import fake_filesystem from pyfakefs import fake_tempfile -from oauth2client.client import AccessTokenRefreshError -from oauth2client.client import OAuth2Credentials +from google.auth.exceptions import RefreshError +from google.auth.transport import Request +from google.oauth2.credentials import Credentials -if googleads.oauth2.DEPRECATED_OAUTH2CLIENT: - _SA_CRED_PATH = ('oauth2client.client' - '.SignedJwtAssertionCredentials') -else: - _SA_CRED_PATH = 'oauth2client.service_account.ServiceAccountCredentials' - _BUILTIN_PATH = '__builtin__' if six.PY2 else 'builtins' @@ -93,7 +87,7 @@ def setUp(self): def testCreateHttpHeader(self): client = googleads.oauth2.GoogleAccessTokenClient( self.access_token, self.token_expiry) - expected_header = {'Authorization': 'Bearer %s' % self.access_token} + expected_header = {'authorization': 'Bearer %s' % self.access_token} self.assertEqual(client.CreateHttpHeader(), expected_header) def testCreateHttpHeaderWithExpiredToken(self): @@ -110,74 +104,99 @@ def setUp(self): self.client_id = 'client_id' self.client_secret = 'itsasecret' self.refresh_token = 'refreshing' - https_proxy_host = 'myproxy.com' - https_proxy_port = 443 - self.https_proxy = googleads.common.ProxyConfig.Proxy(https_proxy_host, - https_proxy_port) - self.proxy_config = googleads.common.ProxyConfig( - https_proxy=self.https_proxy) self.access_token_unrefreshed = 'a' self.access_token_refreshed = 'b' - # Mock out httplib2.Http for testing. - self.http = mock.Mock(spec=httplib2.Http) - self.opener = self.http.return_value = mock.Mock() - self.opener.proxy_info = self.proxy_config.proxy_info - self.opener.ca_certs = self.proxy_config.cafile - self.opener.disable_ssl_certificate_valiation = ( - self.proxy_config.disable_certificate_validation) - - # Mock out oauth2client.client.OAuth2Credentials for testing - self.oauth2_credentials = mock.Mock(spec=OAuth2Credentials) - self.oauth2_credentials.return_value = mock.Mock() - self.mock_oauth2_credentials = (self.oauth2_credentials.return_value) - self.mock_oauth2_credentials.access_token = self.access_token_unrefreshed - self.mock_oauth2_credentials.token_expiry = datetime.datetime(1980, 1, 1, - 12) - - def apply(headers): - headers['Authorization'] = ('Bearer %s' - % self.mock_oauth2_credentials.access_token) - - def refresh(mock_http): - self.mock_oauth2_credentials.access_token = self.access_token_refreshed - self.mock_oauth2_credentials.token_expiry = datetime.datetime.utcnow() - - self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply) - self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh) - with mock.patch('oauth2client.client.OAuth2Credentials', - self.oauth2_credentials): - self.googleads_client = googleads.oauth2.GoogleRefreshTokenClient( + # Mock out google.auth.transport.Request for testing. + self.mock_req = mock.Mock(spec=Request) + self.mock_req.return_value = mock.Mock() + self.mock_req_instance = self.mock_req.return_value + + # Mock out google.oauth2.credentials.Credentials for testing + self.mock_credentials = mock.Mock(spec=Credentials) + self.mock_credentials.return_value = mock.Mock() + self.mock_credentials_instance = self.mock_credentials.return_value + self.mock_credentials_instance.token = self.access_token_unrefreshed + self.mock_credentials_instance.expiry = datetime.datetime(1980, 1, 1, 12) + self.mock_credentials_instance.expired = True + + def apply(headers, token=None): + headers['authorization'] = ('Bearer %s' + % self.mock_credentials_instance.token) + + def refresh(request): + self.mock_credentials_instance.token = self.access_token_refreshed + self.mock_credentials_instance.expiry = datetime.datetime.utcnow() + + self.mock_credentials_instance.apply = mock.Mock(side_effect=apply) + self.mock_credentials_instance.refresh = mock.Mock(side_effect=refresh) + with mock.patch('google.oauth2.credentials.Credentials', + self.mock_credentials): + self.refresh_client = googleads.oauth2.GoogleRefreshTokenClient( self.client_id, self.client_secret, self.refresh_token, - proxy_config=self.proxy_config, access_token=self.access_token_unrefreshed, - token_expiry=self.mock_oauth2_credentials.token_expiry) + token_expiry=self.mock_credentials_instance.expiry) def testCreateHttpHeader_noRefresh(self): - header = {'Authorization': 'Bearer %s' % self.access_token_unrefreshed} - self.mock_oauth2_credentials.token_expiry = None - self.assertEqual(header, self.googleads_client.CreateHttpHeader()) + header = {'authorization': 'Bearer %s' % self.access_token_unrefreshed} + self.mock_credentials_instance.expiry = ( + datetime.datetime.utcnow() + datetime.timedelta(hours=1)) + self.mock_credentials_instance.expired = False + self.assertEqual(header, self.refresh_client.CreateHttpHeader()) def testCreateHttpHeader_refresh(self): - header = {u'Authorization': 'Bearer %s' % self.access_token_refreshed} - - with mock.patch('httplib2.Http', self.http): - self.assertEqual(header, self.googleads_client.CreateHttpHeader()) - self.http.assert_called_once_with( - ca_certs=None, proxy_info=self.proxy_config.proxy_info, - disable_ssl_certificate_validation=( - self.proxy_config.disable_certificate_validation)) - self.mock_oauth2_credentials.refresh.assert_called_once_with( - self.opener) + expected_header = {u'authorization': 'Bearer %s' + % self.access_token_refreshed} + + with mock.patch('requests.Session') as mock_session: + mock_session_instance = mock.MagicMock() + mock_session.return_value = mock_session_instance + mock_session_instance.__enter__.return_value = mock_session_instance + mock_session_instance.__exit__.return_value = None + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + header = self.refresh_client.CreateHttpHeader() + self.assertEqual(mock_session_instance.proxies, {}) + self.assertEqual(mock_session_instance.verify, True) + self.assertEqual(mock_session_instance.cert, None) + self.mock_req.assert_called_once_with(session=mock_session_instance) + self.assertEqual(expected_header, header) + self.mock_credentials_instance.refresh.assert_called_once_with( + self.mock_req_instance) + + def testCreateHttpHeader_refreshWithConfiguredProxyConfig(self): + https_proxy = 'http://myproxy.com:443' + expected_proxies = {'https': https_proxy} + proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) + self.refresh_client.proxy_config = proxy_config + + expected_header = {u'authorization': 'Bearer %s' + % self.access_token_refreshed} + + with mock.patch('requests.Session') as mock_session: + mock_session_instance = mock.MagicMock() + mock_session.return_value = mock_session_instance + mock_session_instance.__enter__.return_value = mock_session_instance + mock_session_instance.__exit__.return_value = None + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + header = self.refresh_client.CreateHttpHeader() + self.assertEqual(mock_session_instance.proxies, expected_proxies) + self.assertEqual(mock_session_instance.verify, + not proxy_config.disable_certificate_validation) + self.assertEqual(mock_session_instance.cert, + proxy_config.cafile) + self.mock_req.assert_called_once_with(session=mock_session_instance) + self.assertEqual(expected_header, header) + self.mock_credentials_instance.refresh.assert_called_once_with( + self.mock_req_instance) def testCreateHttpHeader_refreshFails(self): - self.mock_oauth2_credentials.refresh.side_effect = AccessTokenRefreshError( + self.mock_credentials_instance.refresh.side_effect = RefreshError( 'Invalid response 400') - with mock.patch('httplib2.Http', self.http): - self.assertRaises(AccessTokenRefreshError, - self.googleads_client.CreateHttpHeader) - self.assertFalse(self.mock_oauth2_credentials.apply.called) + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + self.assertRaises(RefreshError, + self.refresh_client.CreateHttpHeader) + self.assertFalse(self.mock_credentials_instance.apply.called) class GoogleServiceAccountTest(unittest.TestCase): @@ -185,264 +204,128 @@ class GoogleServiceAccountTest(unittest.TestCase): def setUp(self): self.scope = 'scope' - self.service_account_email = 'email@email.com' self.private_key = b'IT\'S A SECRET TO EVERYBODY.' - self.private_key_password = 'notasecret' self.delegated_account = 'delegated_account@delegated.com' - https_proxy_host = 'myproxy.com' - https_proxy_port = 443 - https_proxy = googleads.common.ProxyConfig.Proxy(https_proxy_host, - https_proxy_port) - self.proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) - self.https_proxy = '%s:%s' % (https_proxy_host, https_proxy_port) - self.access_token_unrefreshed = 'a' - self.access_token_refreshed = 'b' # Mock out filesystem and file for testing. filesystem = fake_filesystem.FakeFilesystem() tempfile = fake_tempfile.FakeTempfileModule(filesystem) self.fake_open = fake_filesystem.FakeFileOpen(filesystem) self.key_file_path = tempfile.NamedTemporaryFile(delete=False).name + self.cert_file_path = tempfile.NamedTemporaryFile( + delete=False, prefix='cert_', suffix='.pem').name with self.fake_open(self.key_file_path, 'wb') as file_handle: file_handle.write(self.private_key) - # Mock out httplib2.Http for testing. - self.http = mock.Mock(spec=httplib2.Http) - self.opener = self.http.return_value = mock.Mock() - self.opener.proxy_info = self.proxy_config.proxy_info - self.opener.ca_certs = self.proxy_config.cafile - self.opener.disable_ssl_certificate_valiation = ( - self.proxy_config.disable_certificate_validation) + self.access_token_unrefreshed = 'a' + self.access_token_refreshed = 'b' + + # Mock out google.auth.transport.Request for testing. + self.mock_req = mock.Mock(spec=Request) + self.mock_req.return_value = mock.Mock() + self.mock_req_instance = self.mock_req.return_value # Mock out service account credentials for testing. - self.oauth2_credentials = mock.Mock() - self.oauth2_credentials.return_value = mock.Mock() - self.mock_oauth2_credentials = self.oauth2_credentials.return_value - self.mock_oauth2_credentials.access_token = 'x' - self.mock_oauth2_credentials.token_expiry = datetime.datetime( + self.mock_credentials = mock.Mock() + self.mock_credentials.from_service_account_file.return_value = mock.Mock() + self.mock_credentials_instance = ( + self.mock_credentials.from_service_account_file.return_value + ) + self.mock_credentials_instance.token = 'x' + self.mock_credentials_instance.expiry = datetime.datetime( 1980, 1, 1, 12) - # Also mock out instantiation methods for newer oauth2client versions. - self.oauth2_credentials.from_p12_keyfile.return_value = ( - self.mock_oauth2_credentials) - self.oauth2_credentials.from_json_keyfile_name.return_value = ( - self.mock_oauth2_credentials) - - def apply(headers): - headers['Authorization'] = ('Bearer %s' - % self.mock_oauth2_credentials.access_token) - - def refresh(mock_http): - self.mock_oauth2_credentials.access_token = ( + self.mock_credentials_instance.expired = True + + def apply(headers, token=None): + headers['authorization'] = ('Bearer %s' + % self.mock_credentials_instance.token) + + def refresh(request): + self.mock_credentials_instance.token = ( self.access_token_unrefreshed if - self.mock_oauth2_credentials.access_token is 'x' + self.mock_credentials_instance.token is 'x' else self.access_token_refreshed) - self.mock_oauth2_credentials.token_expiry = datetime.datetime.utcnow() + self.mock_credentials_instance.token_expiry = datetime.datetime.utcnow() - self.mock_oauth2_credentials.apply = mock.Mock(side_effect=apply) - self.mock_oauth2_credentials.refresh = mock.Mock(side_effect=refresh) + self.mock_credentials_instance.apply = mock.Mock(side_effect=apply) + self.mock_credentials_instance.refresh = mock.Mock(side_effect=refresh) with mock.patch('%s.open' % _BUILTIN_PATH, self.fake_open): - with mock.patch(_SA_CRED_PATH, self.oauth2_credentials): - self.googleads_client = googleads.oauth2.GoogleServiceAccountClient( - self.scope, self.service_account_email, self.key_file_path, - self.private_key_password, proxy_config=self.proxy_config) + with mock.patch('google.oauth2.service_account.Credentials', + self.mock_credentials): + self.sa_client = googleads.oauth2.GoogleServiceAccountClient( + self.key_file_path, self.scope) # Undo the call count for the auto-refresh - self.mock_oauth2_credentials.refresh.reset_mock() - - def testCreateGoogleServiceAccountClient_DelegatedJsonOAuth2Client4(self): - # Mock out the oauth2client 4.0.0 oauth2client.service_account module to - # verify that the correct parts are called. - mock_oauth2client_4 = mock.Mock() - mock_service_account_module = mock.Mock() - mock_service_account_credentials = mock.Mock() - mock_service_account_credentials_instance = mock.Mock() - mock_from_json_keyfile_name = mock.Mock() - mock_create_delegated = mock.Mock() - mock_service_account_credentials_instance.create_delegated = ( - mock_create_delegated) - mock_from_json_keyfile_name.return_value = ( - mock_service_account_credentials_instance) - mock_service_account_credentials.from_json_keyfile_name = ( - mock_from_json_keyfile_name) - mock_service_account_module.ServiceAccountCredentials = ( - mock_service_account_credentials) - mock_oauth2client_4.service_account = mock_service_account_module - mock_oauth2client_4.__version__ = '4.0.0' - with mock.patch('googleads.oauth2.oauth2client', - mock_oauth2client_4): - with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', False): - mock_oauth2client_4.service_account = mock_service_account_module - # Create a GoogleServiceAccountClient and verify that the - # ServiceAccountCredentials were correctly instantiated. - googleads.oauth2.GoogleServiceAccountClient( - self.scope, client_email=None, key_file=self.key_file_path, - sub=self.delegated_account) - mock_from_json_keyfile_name.assert_called_once_with( - self.key_file_path, scopes=self.scope) - mock_create_delegated.assert_called_once_with(self.delegated_account) - - def testCreateGoogleServiceAccountClient_DelegatedP12OAuth2Client4(self): - # Mock out the oauth2client 4.0.0 oauth2client.service_account module to - # verify that the correct parts are called. - mock_oauth2client_4 = mock.Mock() - mock_service_account_module = mock.Mock() - mock_service_account_credentials = mock.Mock() - mock_service_account_credentials_instance = mock.Mock() - mock_from_p12_keyfile = mock.Mock() - mock_create_delegated = mock.Mock() - mock_service_account_credentials_instance.create_delegated = ( - mock_create_delegated) - mock_from_p12_keyfile.return_value = ( - mock_service_account_credentials_instance) - mock_service_account_credentials.from_p12_keyfile = ( - mock_from_p12_keyfile) - mock_service_account_module.ServiceAccountCredentials = ( - mock_service_account_credentials) - mock_oauth2client_4.service_account = mock_service_account_module - mock_oauth2client_4.__version__ = '4.0.0' - with mock.patch('googleads.oauth2.oauth2client', - mock_oauth2client_4): - with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', False): - mock_oauth2client_4.service_account = mock_service_account_module - # Create a GoogleServiceAccountClient and verify that the - # ServiceAccountCredentials were correctly instantiated. - googleads.oauth2.GoogleServiceAccountClient( - self.scope, client_email=self.service_account_email, - key_file=self.key_file_path, sub=self.delegated_account) - mock_from_p12_keyfile.assert_called_once_with( - self.service_account_email, self.key_file_path, scopes=self.scope) - mock_create_delegated.assert_called_once_with(self.delegated_account) - - def testCreateGoogleServiceAccountClient_DelegatedP12OAuth2ClientDepr(self): - # Mock out the oauth2client 1.4.12 oauth2client.client module to - # verify that the correct parts are called. - mock_oauth2client_depr = mock.Mock() - mock_client_module = mock.Mock() - mock_signed_jwt_credentials = mock.Mock() - mock_signed_jwt_credentials_instance = mock.Mock() - mock_signed_jwt_credentials.return_value = ( - mock_signed_jwt_credentials_instance) - mock_client_module.SignedJwtAssertionCredentials = ( - mock_signed_jwt_credentials) - mock_oauth2client_depr.client = mock_client_module - mock_oauth2client_depr.__version__ = '1.4.12' - - # Mock out the oauth2client 1.4.12 oauth2client.client module to - # verify that the correct parts are called. - with mock.patch('googleads.oauth2.oauth2client', - mock_oauth2client_depr): - with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', True): - with mock.patch('%s.open' % googleads.oauth2.__name__, self.fake_open, - create=True): - googleads.oauth2.GoogleServiceAccountClient( - self.scope, client_email=self.service_account_email, - key_file=self.key_file_path, sub=self.delegated_account) - mock_signed_jwt_credentials.assert_called_once_with( - self.service_account_email, self.private_key, self.scope, - private_key_password=self.private_key_password, - user_agent='Google Ads Python Client Library', - token_uri='https://accounts.google.com/o/oauth2/token', - sub=self.delegated_account) - - def testCreateGoogleServiceAccountClient_JsonOAuth2Client4(self): - # Mock out the oauth2client 4.0.0 oauth2client.service_account module to - # verify that the correct parts are called. - mock_oauth2client_4 = mock.Mock() - mock_service_account_module = mock.Mock() - mock_service_account_credentials = mock.Mock() - mock_service_account_credentials_instance = mock.Mock() - mock_from_json_keyfile_name = mock.Mock() - mock_create_delegated = mock.Mock() - mock_service_account_credentials_instance.create_delegated = ( - mock_create_delegated) - mock_from_json_keyfile_name.return_value = ( - mock_service_account_credentials_instance) - mock_service_account_credentials.from_json_keyfile_name = ( - mock_from_json_keyfile_name) - mock_service_account_module.ServiceAccountCredentials = ( - mock_service_account_credentials) - mock_oauth2client_4.service_account = mock_service_account_module - mock_oauth2client_4.__version__ = '4.0.0' - with mock.patch('googleads.oauth2.oauth2client', - mock_oauth2client_4): - with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', False): - mock_oauth2client_4.service_account = mock_service_account_module - # Create a GoogleServiceAccountClient and verify that the - # ServiceAccountCredentials were correctly instantiated. - googleads.oauth2.GoogleServiceAccountClient( - self.scope, client_email=None, key_file=self.key_file_path) - mock_from_json_keyfile_name.assert_called_once_with( - self.key_file_path, scopes=self.scope) - mock_create_delegated.assert_not_called() - - def testCreateGoogleServiceAccountClient_P12OAuth2Client4(self): - # Mock out the oauth2client 4.0.0 oauth2client.service_account module to - # verify that the correct parts are called. - mock_oauth2client_4 = mock.Mock() - mock_service_account_module = mock.Mock() - mock_service_account_credentials = mock.Mock() - mock_service_account_credentials_instance = mock.Mock() - mock_from_p12_keyfile = mock.Mock() - mock_create_delegated = mock.Mock() - mock_service_account_credentials_instance.create_delegated = ( - mock_create_delegated) - mock_from_p12_keyfile.return_value = ( - mock_service_account_credentials_instance) - mock_service_account_credentials.from_p12_keyfile = ( - mock_from_p12_keyfile) - mock_service_account_module.ServiceAccountCredentials = ( - mock_service_account_credentials) - mock_oauth2client_4.service_account = mock_service_account_module - mock_oauth2client_4.__version__ = '4.0.0' - with mock.patch('googleads.oauth2.oauth2client', - mock_oauth2client_4): - with mock.patch('googleads.oauth2.DEPRECATED_OAUTH2CLIENT', False): - mock_oauth2client_4.service_account = mock_service_account_module - # Create a GoogleServiceAccountClient and verify that the - # ServiceAccountCredentials were correctly instantiated. - googleads.oauth2.GoogleServiceAccountClient( - self.scope, client_email=self.service_account_email, - key_file=self.key_file_path) - mock_from_p12_keyfile.assert_called_once_with( - self.service_account_email, self.key_file_path, scopes=self.scope) - mock_create_delegated.assert_not_called() + self.mock_credentials_instance.refresh.reset_mock() + + def testCreateDelegatedGoogleServiceAccountClient(self): + with mock.patch('google.oauth2.service_account.Credentials') as mock_cred: + # Create a GoogleServiceAccountClient and verify that the delegated + # service account Credentials were correctly instantiated. + googleads.oauth2.GoogleServiceAccountClient( + self.key_file_path, self.scope, sub=self.delegated_account) + mock_cred.from_service_account_file.assert_called_once_with( + self.key_file_path, scopes=[self.scope], + subject=self.delegated_account) def testCreateHttpHeader_noRefresh(self): - header = {'Authorization': 'Bearer %s' % self.access_token_unrefreshed} - self.mock_oauth2_credentials.token_expiry = None - self.assertEqual(header, self.googleads_client.CreateHttpHeader()) + header = {'authorization': 'Bearer %s' % self.access_token_unrefreshed} + self.mock_credentials_instance.expiry = ( + datetime.datetime.utcnow() + datetime.timedelta(hours=1)) + self.mock_credentials_instance.expired = False + self.assertEqual(header, self.sa_client.CreateHttpHeader()) def testCreateHttpHeader_refresh(self): - header = {u'Authorization': 'Bearer %s' % self.access_token_refreshed} - - with mock.patch('httplib2.Http', self.http): - self.assertEqual(header, self.googleads_client.CreateHttpHeader()) - self.http.assert_called_once_with( - ca_certs=None, proxy_info=self.proxy_config.proxy_info, - disable_ssl_certificate_validation=( - self.proxy_config.disable_certificate_validation)) - self.mock_oauth2_credentials.refresh.assert_called_once_with( - self.opener) + expected_header = {'authorization': 'Bearer %s' + % self.access_token_refreshed} + with mock.patch('requests.Session') as mock_session: + mock_session_instance = mock.MagicMock() + mock_session.return_value = mock_session_instance + mock_session_instance.__enter__.return_value = mock_session_instance + mock_session_instance.__exit__.return_value = None + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + header = self.sa_client.CreateHttpHeader() + self.assertEqual(mock_session_instance.proxies, {}) + self.assertEqual(mock_session_instance.verify, True) + self.assertEqual(mock_session_instance.cert, None) + self.mock_req.assert_called_once_with(session=mock_session_instance) + self.assertEqual(expected_header, header) + self.mock_credentials_instance.refresh.assert_called_once_with( + self.mock_req_instance) + + def testCreateHttpHeader_refreshWithConfiguredProxyConfig(self): + https_proxy = 'http://myproxy.com:443' + proxy_config = googleads.common.ProxyConfig(https_proxy=https_proxy) + expected_proxies = {'https': https_proxy} + self.sa_client.proxy_config = proxy_config + + expected_header = {'authorization': 'Bearer %s' + % self.access_token_refreshed} + + with mock.patch('requests.Session') as mock_session: + mock_session_instance = mock.MagicMock() + mock_session.return_value = mock_session_instance + mock_session_instance.__enter__.return_value = mock_session_instance + mock_session_instance.__exit__.return_value = None + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + header = self.sa_client.CreateHttpHeader() + self.assertEqual(mock_session_instance.proxies, expected_proxies) + self.assertEqual(mock_session_instance.verify, + not proxy_config.disable_certificate_validation) + self.assertEqual(mock_session_instance.cert, + proxy_config.cafile) + self.mock_req.assert_called_once_with(session=mock_session_instance) + self.assertEqual(expected_header, header) + self.mock_credentials_instance.refresh.assert_called_once_with( + self.mock_req_instance) def testCreateHttpHeader_refreshFails(self): - self.mock_oauth2_credentials.refresh.side_effect = AccessTokenRefreshError( + self.mock_credentials_instance.refresh.side_effect = RefreshError( 'Invalid response 400') - with mock.patch('httplib2.Http', self.http): - self.assertRaises(AccessTokenRefreshError, - self.googleads_client.CreateHttpHeader) - self.assertFalse(self.mock_oauth2_credentials.apply.called) - - def testIssue123(self): - """Test that verifies the fix for Issue #123 on the GitHub Issue Tracker. - - See: https://github.com/googleads/googleads-python-lib/issues/123 - """ - with mock.patch('%s.open' % _BUILTIN_PATH): - with mock.patch(_SA_CRED_PATH, self.oauth2_credentials): - googleads.oauth2.GoogleServiceAccountClient( - self.scope, self.service_account_email, '/dev/null', - self.private_key_password) + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + self.assertRaises(RefreshError, self.sa_client.CreateHttpHeader) + self.assertFalse(self.mock_credentials_instance.apply.called) if __name__ == '__main__': diff --git a/tests/test_data/adwords_report_definition.xsd b/tests/test_data/adwords_report_definition.xsd new file mode 100644 index 00000000..c707f2ae --- /dev/null +++ b/tests/test_data/adwords_report_definition.xsd @@ -0,0 +1,155 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/test_data/adwords_report_post_body.txt b/tests/test_data/adwords_report_post_body.txt new file mode 100644 index 00000000..c4afcd1f --- /dev/null +++ b/tests/test_data/adwords_report_post_body.txt @@ -0,0 +1 @@ +__rdxml=%3Ctns%3AreportDefinition+xmlns%3Atns%3D%22https%3A%2F%2Fadwords.google.com%2Fapi%2Fadwords%2Fcm%2F{VERSION}%22%3E%0A+++%3Ctns%3Aselector%3E%0A++++++%3Ctns%3Afields%3ECampaignId%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EAdGroupId%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EId%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3ECriteriaType%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3ECriteria%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EFinalUrls%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EImpressions%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3EClicks%3C%2Ftns%3Afields%3E%0A++++++%3Ctns%3Afields%3ECost%3C%2Ftns%3Afields%3E%0A+++%3C%2Ftns%3Aselector%3E%0A+++%3Ctns%3AreportName%3ELast+7+days+CRITERIA_PERFORMANCE_REPORT%3C%2Ftns%3AreportName%3E%0A+++%3Ctns%3AreportType%3ECRITERIA_PERFORMANCE_REPORT%3C%2Ftns%3AreportType%3E%0A+++%3Ctns%3AdateRangeType%3ELAST_7_DAYS%3C%2Ftns%3AdateRangeType%3E%0A+++%3Ctns%3AdownloadFormat%3ECSV%3C%2Ftns%3AdownloadFormat%3E%0A%3C%2Ftns%3AreportDefinition%3E \ No newline at end of file diff --git a/tests/test_data/adwords_report_post_body_no_formatting.txt b/tests/test_data/adwords_report_post_body_no_formatting.txt new file mode 100644 index 00000000..f85dd7b7 --- /dev/null +++ b/tests/test_data/adwords_report_post_body_no_formatting.txt @@ -0,0 +1 @@ +__rdxml=%3Ctns%3AreportDefinition+xmlns%3Atns%3D%22https%3A%2F%2Fadwords.google.com%2Fapi%2Fadwords%2Fcm%2F{VERSION}%22%3E%3Ctns%3Aselector%3E%3Ctns%3Afields%3ECampaignId%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EAdGroupId%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EId%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3ECriteriaType%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3ECriteria%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EFinalUrls%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EImpressions%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3EClicks%3C%2Ftns%3Afields%3E%3Ctns%3Afields%3ECost%3C%2Ftns%3Afields%3E%3C%2Ftns%3Aselector%3E%3Ctns%3AreportName%3ELast+7+days+CRITERIA_PERFORMANCE_REPORT%3C%2Ftns%3AreportName%3E%3Ctns%3AreportType%3ECRITERIA_PERFORMANCE_REPORT%3C%2Ftns%3AreportType%3E%3Ctns%3AdateRangeType%3ELAST_7_DAYS%3C%2Ftns%3AdateRangeType%3E%3Ctns%3AdownloadFormat%3ECSV%3C%2Ftns%3AdownloadFormat%3E%3C%2Ftns%3AreportDefinition%3E \ No newline at end of file diff --git a/tests/test_data/dfp_report_service.xml b/tests/test_data/dfp_report_service.xml new file mode 100644 index 00000000..ff84c1a0 --- /dev/null +++ b/tests/test_data/dfp_report_service.xml @@ -0,0 +1,9326 @@ + + + + + + + + + + + + + + + Encapsulates an Image media. For {@code SET},{@code REMOVE} operations in MediaService, use {@code mediaId}. + + + + + + + + Raw image data. + + + + + + + + + + Contains an object value. + <p> + <b>This object is experimental! + <code>ObjectValue</code> is an experimental, innovative, and rapidly + changing new feature for DFP. Unfortunately, being on the bleeding edge means that we may make + backwards-incompatible changes to + <code>ObjectValue</code>. We will inform the community when this feature + is no longer experimental.</b> + + + + + + + + + + + + The API error base class that provides details about an error that occurred + while processing a service request. + + <p>The OGNL field path is provided for parsers to identify the request data + element that may have caused the error.</p> + + + + + + + The OGNL field path to identify cause of error. + + + + + + + A parsed copy of the field path. For example, the field path "operations[1].operand" + corresponds to this list: {FieldPathElement(field = "operations", index = 1), + FieldPathElement(field = "operand", index = null)}. + + + + + + + The data that caused the error. + + + + + + + A simple string representation of the error and reason. + + + + + + + + + Exception class for holding a list of service errors. + + + + + + + + + List of errors. + + + + + + + + + + + Errors related to the usage of API versions. + + + + + + + + + + + + + + Base class for exceptions. + + + + + + + Error message. + + + + + + + + + An error for an exception that occurred when authenticating. + + + + + + + + + + + + + + Contains a boolean value. + + + + + + + + + The boolean value. + + + + + + + + + + + Error for the size of the collection being too large + + + + + + + + + + + + + + A place for common errors that can be used across services. + + + + + + + + + + + + + + Errors related to currency codes. + + + + + + + + + + + + + + Represents a date. + + + + + + + Year (e.g., 2009) + + + + + + + Month (1..12) + + + + + + + Day (1..31) + + + + + + + + + Represents a date combined with the time of day. + + + + + + + + + + + + + + Contains a date-time value. + + + + + + + + + The {@code DateTime} value. + + + + + + + + + + + Contains a date value. + + + + + + + + + The {@code Date} value. + + + + + + + + + + + Errors related to feature management. If you attempt using a feature that is not available to + the current network you'll receive a FeatureError with the missing feature as the trigger. + + + + + + + + + + + + + + A segment of a field path. Each dot in a field path defines a new segment. + + + + + + + The name of a field in lower camelcase. (e.g. "biddingStrategy") + + + + + + + For list fields, this is a 0-indexed position in the list. Null for non-list fields. + + + + + + + + + Indicates that a server-side error has occured. {@code InternalApiError}s + are generally not the result of an invalid request or message sent by the + client. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Caused by supplying a null value for an attribute that cannot be null. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Contains a numeric value. + + + + + + + + + The numeric value represented as a string. + + + + + + + + + + + Lists errors related to parsing. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Errors related to incorrect permission. + + + + + + + + + + + + + + An error that occurs while executing a PQL query contained in + a {@link Statement} object. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + An error that occurs while parsing a PQL query contained in a + {@link Statement} object. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Describes a client-side error on which a user is attempting + to perform an action to which they have no quota remaining. + + + + + + + + + + + + + + Represents the options for an API report download request. + See {@link ReportService#getReportDownloadUrlWithOptions}. + + + + + + + The {@link ExportFormat} used to generate the report. + Default value is {@link ExportFormat#CSV_DUMP}. + + + + + + + Whether or not to include the report properties (e.g. network, user, date generated...) + in the generated report. + Default is false. + + + + + + + Whether or not to include the totals row. + Default is true for all formats except {@link ExportFormat#CSV_DUMP}. + + + + + + + Whether or not to compress the report file to a gzip file. + Default is true. + <p> + Regardless of value, gzip http compression is available from the URL by normal means. + + + + + + + + + An error for an exception that occurred while running the report. + + + + + + + + + + + + + + Represents a report job that will be run to retrieve performance and + statistics information about ad campaigns, networks, inventory and sales. + + + + + + + The unique ID of the {@code ReportJob}. This value is read-only and is + assigned by Google. + + + + + + + Holds the filtering criteria. + + + + + + + + + A {@code ReportQuery} object allows you to specify the selection criteria for + generating a report. Only reports with at least one {@link Column} are supported. + + + + + + + The list of break-down types being requested in the report. + The generated report will contain the dimensions in the same order as requested. + This field is required. + + + + + + + The ad unit view for the report. Defaults to {@link AdUnitView#TOP_LEVEL}. + + + + + + + The list of trafficking statistics and revenue information being requested + in the report. The generated report will contain the columns in the same + order as requested. This field is required. + + + + + + + The list of break-down attributes being requested in this report. Some + {@link DimensionAttribute} values can only be used with certain + {@link Dimension} values that must be included in the {@link #dimensions} + attribute. The generated report will contain the attributes in the same + order as requested. + + + + + + + The list of {@link CustomField#id} being requested in this report. + To add a {@link CustomField} to the report, you must include + its corresponding {@link Dimension}, determined by the {@link CustomField#entityType}, + as a {@link #dimensions dimension}. + + <table> + <tr> + <th scope="col" colspan="2">{@link CustomFieldEntityType#entityType}</th> + </tr> + <tr> + <td>{@link CustomFieldEntityType#LINE_ITEM}</td><td>{@link Dimension#LINE_ITEM_NAME}</td> + </tr> + <tr> + <td>{@link CustomFieldEntityType#ORDER}</td><td>{@link Dimension#ORDER_NAME}</td> + </tr> + <tr> + <td>{@link CustomFieldEntityType#CREATIVE}</td><td>{@link Dimension#CREATIVE_NAME}</td> + </tr> + <tr> + <td>{@link CustomFieldEntityType#PRODUCT_TEMPLATE}</td> + <td>{@link Dimension#PRODUCT_TEMPLATE_NAME}</td> + </tr> + <tr> + <td>{@link CustomFieldEntityType#PRODUCT}</td><td>{@link Dimension#PRODUCT_NAME}</td> + </tr> + <tr> + <td>{@link CustomFieldEntityType#PROPOSAL}</td><td>{@link Dimension#PROPOSAL_NAME}</td> + </tr> + <tr> + <td>{@link CustomFieldEntityType#PROPOSAL_LINE_ITEM}</td> + <td>{@link Dimension#PROPOSAL_LINE_ITEM_NAME}</td> + </tr> + </table> + + + + + + + The list of content metadata hierarchy custom targeting key {@link CustomTargetingKey#id IDs} + being requested in this report. Each of these IDs must have been defined in the + {@link ContentMetadataKeyHierarchy content metadata key hierarchy}. This will include + dimensions in the form of {@code CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[id]_ID} and + {@code CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[id]_VALUE} where where {@code ID} is the ID of + the {@link CustomTargetingValue#id custom targeting value} and {@code VALUE} is the + {@link CustomTargetingValue#name name}. + <p> + To add {@link CustomTargetingKey#id IDs}, you must include {@link Dimension#CONTENT_HIERARCHY} + in {@link #dimensions}, and specify a non-empty list of custom targeting key IDs. The order of + content hierarchy columns in the report correspond to the place of + {@link Dimension#CONTENT_HIERARCHY} in {@link #dimensions}. For example, if {@link #dimensions} + contains the following dimensions in the order: {@link Dimension#ADVERTISER_NAME}, + {@link Dimension#CONTENT_HIERARCHY} and {@link Dimension#COUNTRY_NAME}, and + {@link #contentMetadataKeyHierarchyCustomTargetingKeyIds} contains the following IDs in the + order: 1001 and 1002. The order of dimensions in the report will be: + Dimension.ADVERTISER_NAME, + Dimension.CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[1001]_VALUE, + Dimension.CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[1002]_VALUE, + Dimension.COUNTRY_NAME, + Dimension.ADVERTISER_ID, + Dimension.CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[1001]_ID, + Dimension.CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[1002]_ID, + Dimension.COUNTRY_CRITERIA_ID + + + + + + + The start date from which the reporting information is gathered. The + {@code ReportQuery#dateRangeType} field must be set to + {@link DateRangeType#CUSTOM_DATE} in order to use this. + + + + + + + The end date upto which the reporting information is gathered. The + {@code ReportQuery#dateRangeType} field must be set to + {@link DateRangeType#CUSTOM_DATE} in order to use this. + + + + + + + The period of time for which the reporting data is being generated. In + order to define custom time periods, set this to + {@link DateRangeType#CUSTOM_DATE}. If set to {@link DateRangeType#CUSTOM_DATE}, then + {@link ReportQuery#startDate} and {@link ReportQuery#endDate} will be used. + + + + + + + Specifies a filter to use for reporting on data. This filter will be used + in conjunction (joined with an AND statement) with the date range selected + through {@link #dateRangeType}, {@link #startDate}, and {@link #endDate} + and the dimension filters selected through {@link #dimensionFilters}. + + The syntax currently allowed for {@link Statement#query} is<br> + <code> [WHERE <condition> {AND <condition> ...}]<code><br> + <p><condition></code><br> + &nbsp;&nbsp;&nbsp;&nbsp; <code>:= <property> = <value></code><br> + <code><condition></code><br> + &nbsp;&nbsp;&nbsp;&nbsp; <code>:= <property> = <bind variable></code><br> + <code><condition> := <property> IN <list></code><br> + <code><bind variable> := :<name></code><br> + </code> where property is the enumeration name of a {@link Dimension} that + can be filtered. + <p> + For example, the statement "WHERE LINE_ITEM_ID IN (34344, 23235)" can be used + to generate a report for a specific set of line items + <p> + Filtering on IDs is highly recommended over filtering on names, especially + for geographical entities. When filtering on names, matching is case + sensitive. + + + + + + + Whether report includes rows with all zero metric values. This field is only eligible + for sales reports. This field is optional and defaults to {@code false}. + + + + + + + The currency for Ad Exchange revenue metrics. This field is only valid for Ad Exchange metrics, + and an exception will be thrown if this field is used with non-Ad Exchange metrics. Defaults to + the network currency if left {@code null}. The supported currency codes can be found in + <a href="https://support.google.com/adxseller/answer/6019533"> this Help Center article.</a> + + + + + + + Gets the {@link TimeZoneType} for this report, which determines the time zone used for the + report's date range. Defaults to {@link TimeZoneType.PUBLISHER}. + + + + + + + + + A list of all errors to be used for validating sizes of collections. + + + + + + + + + + + + + + Errors due to missing required field. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + A saved {@link ReportQuery} representing the selection criteria for running a report. + + + + + + + The ID of the saved query. + + + + + + + The name of the saved query. + + + + + + + The {@link ReportQuery} representing the selection criteria for the saved query. + This will be non-null if and only if {@link SavedQuery#isCompatibleWithApiVersion} is + {@code true}. + + + + + + + Whether or not the saved query is compatible with the current API version. + This will be {@code true} if and only if {@link SavedQuery#reportQuery} is non-null. + A saved query will be incompatible with the API if it uses columns, dimensions, or other + reporting features from the UI that are not available in the {@link ReportQuery} entity. + + + + + + + + + A page of {@link SavedQuery} objects. + + + + + + + The size of the total result set to which this page belongs. + + + + + + + The absolute index in the total result set on which this page begins. + + + + + + + The collection of saved queries contained within this page. + + + + + + + + + Errors related to the server. + + + + + + + + + + + + + + Contains a set of {@link Value Values}. May not contain duplicates. + + + + + + + + + The values. They must all be the same type of {@code Value} and not contain duplicates. + + + + + + + + + + + Represents the SOAP request header used by API requests. + + + + + + + The network code to use in the context of a request. + + + + + + + The name of client library application. + + + + + + + + + Represents the SOAP request header used by API responses. + + + + + + + + + + + Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a + PQL query. Statements are typically used to retrieve objects of a predefined + domain type, which makes SELECT clause unnecessary. + <p> + An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id + LIMIT 30"}. + </p> + <p> + Statements support bind variables. These are substitutes for literals + and can be thought of as input parameters to a PQL query. + </p> + <p> + An example of such a query might be {@code "WHERE id = :idValue"}. + </p> + <p> + Statements also support use of the LIKE keyword. This provides partial and + wildcard string matching. + </p> + <p> + An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}. + </p> + The value for the variable idValue must then be set with an object of type + {@link Value}, e.g., {@link NumberValue}, {@link TextValue} or + {@link BooleanValue}. + + + + + + + Holds the query in PQL syntax. The syntax is:<br> + <code>[WHERE <condition> {[AND | OR] <condition> ...}]</code><br> + <code>[ORDER BY <property> [ASC | DESC]]</code><br> + <code>[LIMIT {[<offset>,] <count>} | {<count> OFFSET <offset>}]</code><br> + <p> + <code><condition></code><br> + &nbsp;&nbsp;&nbsp;&nbsp; + <code>:= <property> {< | <= | > | >= | = | != } <value></code><br> + <code><condition></code><br> + &nbsp;&nbsp;&nbsp;&nbsp; + <code>:= <property> {< | <= | > | >= | = | != } <bind variable></code><br> + <code><condition> := <property> IN <list></code><br> + <code><condition> := <property> IS NULL</code><br> + <code><condition> := <property> LIKE <wildcard%match></code><br> + <code><bind variable> := :<name></code><br> + </p> + + + + + + + Holds keys and values for bind variables and their values. The key is the + name of the bind variable. The value is the literal value of the variable. + <p> + In the example {@code "WHERE status = :bindStatus ORDER BY id LIMIT 30"}, + the bind variable, represented by {@code :bindStatus} is named {@code + bindStatus}, which would also be the parameter map key. The bind variable's + value would be represented by a parameter map value of type + {@link TextValue}. The final result, for example, would be an entry of + {@code "bindStatus" => StringParam("ACTIVE")}. + </p> + + + + + + + + + An error that occurs while parsing {@link Statement} objects. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + A list of error code for reporting invalid content of input strings. + + + + + + + + + + + + + + Errors for Strings which do not meet given length constraints. + + + + + + + + + + + + + + This represents an entry in a map with a key of type String + and value of type Value. + + + + + + + + + + + Contains a string value. + + + + + + + + + The string value. + + + + + + + + + + + {@code Value} represents a value. + + + + + + + + A view for an ad unit report. + + + + + + + Only the top level ad units. Metrics include events for their + descendants that are not filtered out. + + + + + + + All the ad units. Metrics do not include events for the descendants. + + + + + + + Use the ad unit hierarchy. There will be as many ad unit columns as + levels of ad units in the generated report: + <ul> + <li> + The column {@link Dimension#AD_UNIT_NAME} is replaced with columns + "Ad unit 1", "Ad unit 2", ... "Ad unit n". + If level is not applicable to a row, "N/A" is returned as the value. + </li> + <li> + The column {@link Dimension#AD_UNIT_ID} is replaced with columns + "Ad unit ID 1", "Ad unit ID 2", ... "Ad unit ID n". + If level is not applicable to a row, "N/A" is returned as the value. + </li> + </ul> + <p> + Metrics do not include events for the descendants. + + + + + + + + + + + Indicates that the operation is not allowed in the version the request + was made in. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + + + The SOAP message contains a request header with an ambiguous definition + of the authentication header fields. This means either the {@code + authToken} and {@code oAuthToken} fields were both null or both were + specified. Exactly one value should be specified with each request. + + + + + + + The login provided is invalid. + + + + + + + Tried to authenticate with provided information, but failed. + + + + + + + The OAuth provided is invalid. + + + + + + + The specified service to use was not recognized. + + + + + + + The SOAP message is missing a request header with an {@code authToken} + and optional {@code networkCode}. + + + + + + + The HTTP request is missing a request header with an {@code authToken} + + + + + + + The request is missing an {@code authToken} + + + + + + + The customer is not whitelisted for API access. + + + + + + + The user is not associated with any network. + + + + + + + No network for the given {@code networkCode} was found. + + + + + + + The user has access to more than one network, but did not provide a + {@code networkCode}. + + + + + + + An error happened on the server side during connection to authentication + service. + + + + + + + The user tried to create a test network using an account that already is + associated with a network. + + + + + + + The account is blocked and under investigation by the collections team. Please contact + Google for more information. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + {@code Column} provides all the trafficking statistics and revenue + information available for the chosen {@link Dimension} objects. + <p> + Columns with {@code INVENTORY_LEVEL} should not be used with dimensions + relating to line items, orders, companies and creatives, + such as {@link Dimension#LINE_ITEM_NAME}. + Columns with {@code LINE_ITEM_LEVEL} can only be used if you have line item-level + dynamic allocation enabled on your network. + + + + + + + The number of impressions delivered by the ad server. + <p>Corresponds to "Ad server impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The number of downloaded impressions delivered by the ad server. + <p>Corresponds to "Ad server downloaded impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The number of impressions delivered by the ad server by explicit custom criteria targeting. + <p>Corresponds to "Ad server targeted impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of clicks delivered by the ad server. + <p>Corresponds to "Ad server clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The number of clicks delivered by the ad server by explicit custom criteria targeting. + <p>Corresponds to "Ad server targeted clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The CTR for an ad delivered by the ad server. + <p>Corresponds to "Ad server CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The CPM and CPC revenue earned, calculated in publisher currency, + for the ads delivered by the ad server. + <p>Corresponds to "Ad server CPM and CPC revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The CPD revenue earned, calculated in publisher currency, + for the ads delivered by the ad server. + <p>Corresponds to "Ad server CPD revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The CPA revenue earned, calculated in publisher currency, for the ads delivered by the + ad server. + <p>Corresponds to "CPA revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The CPM, CPC and CPD revenue earned, calculated in publisher currency, + for the ads delivered by the ad server. + <p>Can correspond to any of the following in the DFP UI: Ad server CPM, CPC, CPD, and vCPM revenue, Ad server CPM, CPC and CPD revenue. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The average estimated cost-per-thousand-impressions earned from the CPM and CPC ads + delivered by the ad server. + <p>Corresponds to "Ad server average eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The average estimated cost-per-thousand-impressions earned from the CPM, CPC and CPD ads + delivered by the ad server. + + + + + + + The ratio of the number of impressions delivered to the total impressions + delivered when no {@link LineItem} reservation could be found by the ad server + for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + Represented as a percentage. + <p>Corresponds to "Ad server impressions (%)" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of the number of impressions delivered to the total impressions + delivered by the ad server for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "Ad server impressions (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of the number of clicks delivered to the total clicks delivered + when no {@link LineItem} reservation could be found by the ad server for + inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + Represented as a percentage. + <p>Corresponds to "Ad server clicks (%)" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of the number of clicks delivered to the total clicks delivered + by the ad server for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "Ad server clicks (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of revenue generated by ad server to the total CPM and CPC revenue earned + by ads delivered when no {@link LineItem} reservation could be found by + the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + Represented as a percentage. + <p>Corresponds to "Ad server revenue (%)" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of revenue generated by ad server to the total CPM, CPC and CPD revenue earned + by ads delivered when no {@link LineItem} reservation could be found by + the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + Represented as a percentage. + + + + + + + The ratio of revenue generated by ad server to the total CPM and CPC revenue earned by + the ads delivered for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "Ad server revenue (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of revenue generated by ad server to the total CPM, CPC and CPD revenue earned by + the ads delivered for line item-level dynamic allocation. + Represented as a percentage. + + + + + + + The number of times that the code for an ad is served by the ad server. + <p>Corresponds to "Ad server code served count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The number of downloaded impressions delivered by the ad server including impressions + recognized as spam. + <p>Corresponds to "Ad server unfiltered downloaded impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of clicks delivered by the ad server including clicks recognized as spam. + <p>Corresponds to "Ad server unfiltered clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions a dynamic allocation ad delivered when no {@link LineItem} + reservation could be found by the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange impressions, AdSense impressions. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions an AdSense ad delivered for line item-level dynamic allocation. + <p>Corresponds to "AdSense impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of impressions an AdSense ad delivered for line item-level dynamic allocation by + explicit custom criteria targeting. + <p>Corresponds to "AdSense targeted impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of clicks a dynamic allocation ad delivered when no {@link LineItem} + reservation could be found by the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange clicks, AdSense clicks. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of clicks an AdSense ad delivered for line item-level dynamic allocation. + <p>Corresponds to "AdSense clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of clicks an AdSense ad delivered for line item-level dynamic allocation by + explicit custom criteria targeting. + <p>Corresponds to "AdSense targeted clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of clicks a dynamic allocation ad delivered to the number of impressions it + delivered when no {@link LineItem} reservation could be found by the ad server for + inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange CTR, AdSense CTR. Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of clicks an AdSense reservation ad delivered to the number of + impressions it delivered, including line item-level dynamic allocation. + <p>Corresponds to "AdSense CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Revenue generated from ads delivered for dynamic allocation when no {@link LineItem} + reservation could be found by the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange revenue, AdSense revenue. Compatible with the HISTORICAL report type.</p> + + + + + + + Revenue generated from AdSense ads delivered for line item-level dynamic allocation. + <p>Corresponds to "AdSense revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The average estimated cost-per-thousand-impressions earned from dynamic allocation + ads delivered when no {@link LineItem} reservation could be found by + the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange average eCPM, AdSense average eCPM. Compatible with the HISTORICAL report type.</p> + + + + + + + The average estimated cost-per-thousand-impressions earned from the ads + delivered by AdSense for line item-level dynamic allocation. + <p>Corresponds to "AdSense average eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of the number of impressions delivered by dynamic allocation ads + to the total impressions delivered when no {@link LineItem} reservation could + be found by the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + Represented as a percentage. + <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange impressions (%), AdSense impressions (%). Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of the number of impressions delivered by AdSense reservation + ads to the total impressions delivered for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "AdSense impressions (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of the number of clicks delivered by dynamic allocation ads + to the total clicks delivered when no {@link LineItem} reservation could be + found by the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + Represented as a percentage. + <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange clicks (%), AdSense clicks (%). Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of the number of clicks delivered by AdSense reservation ads to + the total clicks delivered for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "AdSense clicks (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of revenue to the total revenue earned from the dynamic allocation + CPM and CPC ads delivered when no {@link LineItem} reservation could be found + by the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + Represented as a percentage. + <p>Can correspond to any of the following in the DFP UI: AdSense / Ad Exchange revenue (%), AdSense revenue (%). Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of revenue to the total revenue earned from the dynamic allocation + CPM, CPC and CPD ads delivered when no {@link LineItem} reservation could be found + by the ad server for inventory-level dynamic allocation. + For premium networks, this includes line item-level dynamic allocation as well. + Represented as a percentage. + + + + + + + The ratio of revenue to the total revenue earned from the CPM and CPC ads + delivered by AdSense for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "AdSense revenue (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of revenue to the total revenue earned from the CPM, CPC and CPD ads + delivered by AdSense for line item-level dynamic allocation. + Represented as a percentage. + + + + + + + The number of impressions an Ad Exchange ad delivered for line item-level dynamic allocation. + <p>Corresponds to "Ad Exchange impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Ad Impressions on mapped Ad Exchange properties. When multiple text ads fill a single display + slot it is only counted once, when the top text ad is recognized. In these cases, the Ad + Impression is attributed to the top text ad. + <p>Corresponds to "Ad impressions" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Number of requests where a buyer was matched with the Ad request, for mapped Ad Exchange + properties. + <p>Corresponds to "Matched requests" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Ad revenue per 1000 ad impressions, for mapped Ad Exchange properties. + <p>Corresponds to "Ad eCPM" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The number of clicks delivered by mapped Ad Exchange properties. + <p>Corresponds to "Clicks" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The estimated net revenue generated by mapped Ad Exchange properties. + <p>Corresponds to "Estimated revenue" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The coverage reported by mapped Ad Exchange properties. + <p>Corresponds to "Coverage" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The matched queries click-through rate delivered by mapped Ad Exchange properties. + <p>Corresponds to "CTR" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The total lift generated by mapped Ad Exchange properties. + <p>Corresponds to "Lift" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The cost-per-click generated by mapped Ad Exchange properties. + <p>Corresponds to "CPC" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The number of ad requests issued by mapped Ad Exchange properties. + <p>Corresponds to "Ad requests" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The average estimated cost-per-thousand-ad requests earned by mapped Ad Exchange properties. + <p>Corresponds to "Ad request eCPM" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The click-through rate of ad requests issued by mapped Ad Exchange properties. + <p>Corresponds to "Ad request CTR" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The click-through rate of impressions issued by mapped Ad Exchange properties. + <p>Corresponds to "Ad CTR" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The video drop off rate for mapped Ad Exchange properties. + <p>Corresponds to "Video drop-off rate" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The video abandonment rate for mapped Ad Exchange properties. + <p>Corresponds to "Video abandonment rate" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The average estimated cost-per-thousand-impressions generated by mapped Ad Exchange properties. + <p>Corresponds to "Matched eCPM" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The estimated percentage of impressions generated by mapped Ad Exchange properties that are + eligible for Active View measurement. + <p>Corresponds to "Active view measurable" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The percentage of viewable impressions out of all measurable impressions generated by mapped + Ad Exchange properties. + <p>Corresponds to "Active view viewable" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The average time (in seconds) that an individual ad impression generated by mapped Ad Exchange + properties was viewable. + <p>Corresponds to "Average viewable time (secs)" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Total number of impressions generated by mapped Ad Exchange properties that were eligible to + measure viewability. + <p>Corresponds to "Active view enabled impressions" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Total number of eligible impressions generated by mapped Ad Exchange properties that were + measurable by Active View. + <p>Corresponds to "Active view measured impressions" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Total number of Active View measurable impressions generated by mapped Ad Exchange properties + that were viewable. + <p>Corresponds to "Active view viewed impressions" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Number of responses that shows that a buyer is bidding, for mapped Ad Exchange properties. + <p>Corresponds to "Deals bid responses" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Deal ad requests for mapped Ad Exchange properties which were ?matched? with demand from the + buyer associated with the Deal. Each ?Deals matched request? represents one opportunity for the + Deal Buyer to serve their ad in the context of the Deal. + <p>Corresponds to "Deals matched requests" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Total ad requests associated with a given Deal, for mapped Ad Exchange properties. + <p>Corresponds to "Deals ad requests" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Deals matched requests divided by Deals ad requests, for mapped Ad Exchange properties. + <p>Corresponds to "Deals match rate" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + A count of how many users watch the first 25% of a video ad, for mapped Ad Exchange properties. + + + + + + + A count of how many users watch the first 75% of a video ad, for mapped Ad Exchange properties. + + + + + + + Percentage of times a user clicked Skip, for mapped Ad Exchange properties. + <p>Corresponds to "TrueView skip rate" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Number of times a video ad has been viewed to completion or watched to 30 seconds, whichever + happens first, for mapped Ad Exchange properties. + <p>Corresponds to "TrueView views" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + TrueView views divided by TrueView impressions, for mapped Ad Exchange properties. + <p>Corresponds to "TrueView VTR" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + The third-party fill rate by Ad Exchange properties linked to DFP. + + <p><b>This experimental column only works with Ad Exchange web properties linked with an active + status.</b> + + <p>This field is deprecated and will be removed in v201805. + <p>Corresponds to "Mediation fill rate" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Impressions generated for mediation requests. This includes third-party network and + Ad Exchange impressions for mediation. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with the HISTORICAL report type.</p> + + + + + + + Estimated revenue generated for mediation requests. This combines estimated revenue from + third-parties along with Ad Exchange. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with the HISTORICAL report type.</p> + + + + + + + The average estimated cost-per-thousand-impressions earned from mediation ads. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with the HISTORICAL report type.</p> + + + + + + + Mediation third-party average cost-per-thousand-impressions. + <p>Compatible with the HISTORICAL report type.</p> + + + + + + + Mediation fill rate indicating how often a network fills an ad request. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with the HISTORICAL report type.</p> + + + + + + + Mediation passbacks recorded when a network does not fill an ad request. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions an Ad Exchange ad delivered for line item-level dynamic allocation + by explicit custom criteria targeting. + <p>Corresponds to "Ad Exchange targeted impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of clicks an Ad Exchange ad delivered for line item-level dynamic allocation. + <p>Corresponds to "Ad Exchange clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of clicks an Ad Exchange ad delivered for line item-level dynamic allocation by + explicit custom criteria targeting. + <p>Corresponds to "Ad Exchange targeted clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of clicks an Ad Exchange ad delivered to the number of + impressions it delivered for line item-level dynamic allocation. + <p>Corresponds to "Ad Exchange CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of the number of impressions delivered to the total impressions delivered + by Ad Exchange for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "Ad Exchange impressions (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of the number of clicks delivered to the total clicks delivered + by Ad Exchange for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "Ad Exchange clicks (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Revenue generated from Ad Exchange ads delivered for line item-level dynamic allocation. + Represented in publisher currency and time zone. + <p>Corresponds to "Ad Exchange revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of revenue generated by Ad Exchange to the total revenue earned + by CPM and CPC ads delivered for line item-level dynamic allocation. + Represented as a percentage. + <p>Corresponds to "Ad Exchange revenue (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of revenue generated by Ad Exchange to the total revenue earned + by CPM, CPC and CPD ads delivered for line item-level dynamic allocation. + Represented as a percentage. + + + + + + + The average estimated cost-per-thousand-impressions earned from the + delivery of Ad Exchange ads for line item-level dynamic allocation. + <p>Corresponds to "Ad Exchange average eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total number of impressions delivered by the ad servers + including inventory-level dynamic allocation. + <p>Corresponds to "Total impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The total number of impressions delivered including line item-level dynamic allocation. + <p>Corresponds to "Total impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The total number of impressions delivered including line item-level dynamic allocation by + explicit custom criteria targeting. + <p>Corresponds to "Total targeted impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The total number of clicks delivered by the ad servers + including inventory-level dynamic allocation. + <p>Corresponds to "Total clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The total number of clicks delivered including line item-level dynamic allocation. + <p>Corresponds to "Total clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The total number of clicks delivered including line item-level dynamic allocation by + explicit custom criteria targeting + <p>Corresponds to "Total targeted clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of total clicks on ads delivered by the ad servers to the total number + of impressions delivered for an ad including inventory-level dynamic allocation. + <p>Corresponds to "Total CTR" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The ratio of total clicks on ads delivered by the ad servers to the total number + of impressions delivered for an ad including line item-level dynamic allocation. + <p>Corresponds to "Total CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The total CPM and CPC revenue generated by the ad servers + including inventory-level dynamic allocation. + <p>Corresponds to "Total CPM and CPC revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The total CPM, CPC and CPD revenue generated by the ad servers + including inventory-level dynamic allocation. + + + + + + + The total CPM and CPC revenue generated by the ad servers + including line item-level dynamic allocation. + <p>Corresponds to "Total CPM and CPC revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The total CPM, CPC and CPD revenue generated by the ad servers + including line item-level dynamic allocation. + <p>Can correspond to any of the following in the DFP UI: Total CPM, CPC, CPD, and vCPM revenue, Total CPM, CPC and CPD revenue. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + Estimated cost-per-thousand-impressions (eCPM) of CPM and CPC ads delivered by the + ad servers including inventory-level dynamic allocation. + <p>Corresponds to "Total average eCPM" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Estimated cost-per-thousand-impressions (eCPM) of CPM, CPC and CPD ads delivered by the + ad servers including inventory-level dynamic allocation. + + + + + + + Estimated cost-per-thousand-impressions (eCPM) of CPM and CPC ads delivered by the + ad servers including line item-level dynamic allocation. + <p>Corresponds to "Total average eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + Estimated cost-per-thousand-impressions (eCPM) of CPM, CPC and CPD ads delivered by the + ad servers including line item-level dynamic allocation. + + + + + + + The total number of times that the code for an ad is served by the ad server including + inventory-level dynamic allocation. + <p>Corresponds to "Total code served count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The total number of missed impressions due to the ad servers' inability to + find ads to serve, including inventory-level dynamic allocation. + <p>Corresponds to "Unfilled impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The number of control (unoptimized) impressions delivered for an ad for + which the optimization feature has been enabled. + <p>Corresponds to "Control impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Number of clicks resulting from the delivery of control (unoptimized) + impressions for an ad for which the optimization feature has been enabled. + <p>Corresponds to "Control clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The CTR for control (unoptimized) impressions for an order for which the + optimization feature has been enabled. + <p>Corresponds to "Control CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Number of optimized impressions delivered for an ad for which the + optimization feature has been enabled. + <p>Corresponds to "Optimized impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Number of clicks resulting from the delivery of optimized impressions for + an ad for which the optimization feature has been enabled. + <p>Corresponds to "Optimized clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Number of non-optimized impressions delivered for an ad for which the + optimization feature has been enabled. + <p>Corresponds to "Non-optimized impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Number of clicks resulting from the delivery of non-optimized impressions for + an ad for which the optimization feature has been enabled. + <p>Corresponds to "Non-optimized clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Number of extra clicks resulting from the delivery of optimized impressions + for an ad for which the optimization feature has been enabled. + <p>Corresponds to "Extra clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The CTR for optimized impressions for an ad for which the optimization + feature has been enabled. + <p>Corresponds to "Optimized CTR" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The percentage by which optimized CTRs are greater than the unoptimized + CTRs. This is calculated as (({@link Column#OPTIMIZATION_OPTIMIZED_CTR}/ + {@link Column#OPTIMIZATION_CONTROL_CTR}) - 1) * 100 for an ad for which the + optimization feature has been enabled. + <p>Corresponds to "Lift" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The line item coverage measures how often the traffic was sent for + optimization. + <p>Corresponds to "Percent optimized" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of impressions that were behind schedule at the time of their delivery. + <p>Corresponds to "Impressions that are behind schedule" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of impressions that did not have any clicks recorded in the recent past. + <p>Corresponds to "Impressions with no clicks recorded" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of impressions that were delivered as sponsorship items. + <p>Corresponds to "Sponsorship impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of impressions that were set to deliver as fast as possible. + <p>Corresponds to "Impressions serving as fast as possible" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of impressions that have no absolute lifetime delivery goals. + <p>Corresponds to "Impressions with no lifetime goal" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Total revenue resulting from the delivery of control (unoptimized) + impressions for an ad for which the optimization feature has been enabled. + <p>Corresponds to "Control revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Total revenue resulting from the delivery of optimized impressions for + an ad for which the optimization feature has been enabled. + <p>Corresponds to "Optimized revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Estimated cost-per-thousand-impressions (eCPM) of control (unoptimized) + impressions for an ad for which the optimization feature has been enabled. + <p>Corresponds to "Control eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Estimated cost-per-thousand-impressions (eCPM) of optimized + impressions for an ad for which the optimization feature has been enabled. + <p>Corresponds to "Optimized eCPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Freed-up impressions as a result of optimization. + <p>Corresponds to "Freed-up impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Relative change in eCPM as a result of optimization. + <p>Corresponds to "eCPM lift" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The average number of ads displayed to each unique visitor. + <p>Corresponds to "Average impressions / visitor" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The average revenue earned per unique visitor. + <p>Corresponds to "Average revenue / visitor" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The number of unique visitors. + <p>Corresponds to "Unique visitors" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The number of people in the given demographic bucket. + <p>Corresponds to "Population" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The number of unique users reached in the given demographic bucket. + <p>Corresponds to "Unique viewers" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + Percentage of the number of unique users reached in the given demographic bucket (out of the + number of unique users reached in all demographics). + <p>Corresponds to "% Composition unique viewers" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The number of impressions in the given demographic bucket. + <p>Corresponds to "Impressions" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + Percentage of the number of impressions in the given demographic bucket (out of the number of + impressions in all demographics). + <p>Corresponds to "% Composition impressions" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The audience reach calculated as {@link #GRP_UNIQUE_AUDIENCE} / {@link #GRP_POPULATION}. + <p>Corresponds to "% Population reach" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The audience average frequency calculated as {@link #GRP_AUDIENCE_IMPRESSIONS} / {@link + #GRP_UNIQUE_AUDIENCE}. + <p>Corresponds to "Average frequency" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The gross rating points (GRP) calculated as {@link #GRP_AUDIENCE_REACH} * {@link + #GRP_AUDIENCE_AVERAGE_FREQUENCY} * 100. + <p>Corresponds to "Target rating points" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The number of impressions for a particular SDK mediation creative. + <p>Corresponds to "SDK mediation creative impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of clicks for a particular SDK mediation creative. + <p>Corresponds to "SDK mediation creative clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of forecasted impressions for future sell-through reports. + + <p>This metric is available for the next 90 days with a daily break down and for the next 12 + months with a monthly break down. + <p>Corresponds to "Forecasted impressions" in the DFP UI. Compatible with the SELL_THROUGH report type.</p> + + + + + + + The number of available impressions for future sell-through reports. + + <p>This metric is available for the next 90 days with a daily break down + and for the next 12 months with a monthly break down. + <p>Corresponds to "Available impressions" in the DFP UI. Compatible with the SELL_THROUGH report type.</p> + + + + + + + The number of reserved impressions for future sell-through reports. + + <p>This metric is available for the next 90 days with a daily break down + and for the next 12 months with a monthly break down. + <p>Corresponds to "Reserved impressions" in the DFP UI. Compatible with the SELL_THROUGH report type.</p> + + + + + + + The sell-through rate for impressions for future sell-through reports. + + <p>This metric is available for the next 90 days with a daily break down + and for the next 12 months with a monthly break down. + <p>Corresponds to "Sell-through rate" in the DFP UI. Compatible with the SELL_THROUGH report type.</p> + + + + + + + The total number of times a backup image is served in place of a rich media ad. + <p>Corresponds to "Backup image impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The amount of time(seconds) that each rich media ad is displayed to users. + <p>Corresponds to "Total display time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The average amount of time(seconds) that each rich media ad is displayed to users. + <p>Corresponds to "Average display time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times an expanding ad was expanded. + <p>Corresponds to "Total expansions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The average amount of time(seconds) that an expanding ad is viewed in an expanded state. + <p>Corresponds to "Average expanding time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The average amount of time(seconds) that a user interacts with a rich media ad. + <p>Corresponds to "Interaction time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times that a user interacts with a rich media ad. + <p>Corresponds to "Total interactions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of rich media ad interactions to the number of times the ad was displayed. + Represented as a percentage. + <p>Corresponds to "Interaction rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The average amount of time(seconds) that a user interacts with a rich media ad. + <p>Corresponds to "Average interaction time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of impressions where a user interacted with a rich media ad. + <p>Corresponds to "Interactive impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times that a user manually closes a floating, expanding, + in-page with overlay, or in-page with floating ad. + <p>Corresponds to "Manual closes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + A metric that measures an impression only once when a user opens an ad in full screen mode. + <p>Corresponds to "Full-screen impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a user clicked on the graphical controls of a video player. + <p>Corresponds to "Total video interactions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The ratio of video interactions to video plays. + Represented as a percentage. + <p>Corresponds to "Video interaction rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a rich media video was muted. + <p>Corresponds to "Mute" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a rich media video was paused. + <p>Corresponds to "Pause" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a rich media video was played. + <p>Corresponds to "Plays" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a rich media video was played upto midpoint. + <p>Corresponds to "Midpoint" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a rich media video was fully played. + <p>Corresponds to "Complete" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a rich media video was restarted. + <p>Corresponds to "Replays" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a rich media video was stopped. + <p>Corresponds to "Stops" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of times a rich media video was unmuted. + <p>Corresponds to "Unmute" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The average amount of time(seconds) that a rich media video was viewed per view. + <p>Corresponds to "Average view time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The percentage of a video watched by a user. + <p>Corresponds to "View rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The amount of time (seconds) that a user interacts with a rich media ad. + <p>Corresponds to "Custom event - time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The number of times a user views and interacts with a specified part of a rich media ad. + <p>Corresponds to "Custom event - count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The number of impressions where the video was played. + <p>Corresponds to "Start" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The number of times the video played to 25% of its length. + <p>Corresponds to "First quartile" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The number of times the video reached its midpoint during play. + <p>Corresponds to "Midpoint" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The number of times the video played to 75% of its length. + <p>Corresponds to "Third quartile" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The number of times the video played to completion. + <p>Corresponds to "Complete" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Average percentage of the video watched by users. + <p>Corresponds to "Average view rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Average time(seconds) users watched the video. + <p>Corresponds to "Average view time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Percentage of times the video played to the end. + <p>Corresponds to "Completion rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The number of times an error occurred, such as a VAST redirect error, a video playback error, + or an invalid response error. + <p>Corresponds to "Total error count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Duration of the video creative. + <p>Corresponds to "Video length" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The number of times a skip button is shown in video. + <p>Corresponds to "Skip button shown" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The number of engaged views i.e. ad is viewed to completion + or for 30s, whichever comes first. + <p>Corresponds to "Engaged view" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + View-through rate represented as a percentage. + <p>Corresponds to "View-through rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Number of times that the publisher specified a video ad played automatically. + <p>Corresponds to "Auto-plays" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of times that the publisher specified a video ad was clicked to play. + <p>Corresponds to "Click-to-plays" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Error rate is the percentage of video error count from (error count + total impressions). + <p>Corresponds to "Total error rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 100. + <p>Corresponds to "VAST error 100 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 101. + <p>Corresponds to "VAST error 101 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 102. + <p>Corresponds to "VAST error 102 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 200. + <p>Corresponds to "VAST error 200 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 201. + <p>Corresponds to "VAST error 201 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 202. + <p>Corresponds to "VAST error 202 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 203. + <p>Corresponds to "VAST error 203 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 300. + <p>Corresponds to "VAST error 300 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 301. + <p>Corresponds to "VAST error 301 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 302. + <p>Corresponds to "VAST error 302 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 303. + <p>Corresponds to "VAST error 303 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 400. + <p>Corresponds to "VAST error 400 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 401. + <p>Corresponds to "VAST error 401 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 402. + <p>Corresponds to "VAST error 402 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 403. + <p>Corresponds to "VAST error 403 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 405. + <p>Corresponds to "VAST error 405 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 500. + <p>Corresponds to "VAST error 500 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 501. + <p>Corresponds to "VAST error 501 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 502. + <p>Corresponds to "VAST error 502 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 503. + <p>Corresponds to "VAST error 503 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 600. + <p>Corresponds to "VAST error 600 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 601. + <p>Corresponds to "VAST error 601 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 602. + <p>Corresponds to "VAST error 602 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 603. + <p>Corresponds to "VAST error 603 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 604. + <p>Corresponds to "VAST error 604 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 900. + <p>Corresponds to "VAST error 900 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Number of VAST video errors of type 901. + <p>Corresponds to "VAST error 901 count" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times user paused ad clip. + <p>Corresponds to "Pause" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times the user unpaused the video. + <p>Corresponds to "Resume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times a user rewinds the video. + <p>Corresponds to "Rewind" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times video player was in mute state during play + of ad clip. + <p>Corresponds to "Mute" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times a user unmutes the video. + <p>Corresponds to "Unmute" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times a user collapses a video, + either to its original size or to a different size. + <p>Corresponds to "Collapse" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times a user expands a video. + <p>Corresponds to "Expand" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times ad clip played in full screen mode. + <p>Corresponds to "Full screen" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of user interactions with a video, on average, + such as pause, full screen, mute, etc. + <p>Corresponds to "Average interaction rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Video interaction event: The number of times a skippable video is skipped. + <p>Corresponds to "Video skipped" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The number of control starts. + <p>Corresponds to "Control starts" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of optimized starts. + <p>Corresponds to "Optimized starts" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of control completes. + <p>Corresponds to "Control completes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of optimized completes. + <p>Corresponds to "Optimized completes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The rate of control completions. + <p>Corresponds to "Control completion rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The rate of optimized completions. + <p>Corresponds to "Optimized completion rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The percentage by which optimized completion rate is greater than the unoptimized completion + rate. This is calculated as (( {@link Column#VIDEO_OPTIMIZATION_OPTIMIZED_COMPLETION_RATE}/ + {@link Column#VIDEO_OPTIMIZATION_CONTROL_COMPLETION_RATE}) - 1) * 100 for an ad for which the + optimization feature has been enabled. + <p>Corresponds to "Completion rate lift" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of control skip buttons shown. + <p>Corresponds to "Control skip button shown" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of optimized skip buttons shown. + <p>Corresponds to "Optimized skip button shown" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of control engaged views. + <p>Corresponds to "Control engaged view" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of optimized engaged views. + <p>Corresponds to "Optimized engaged view" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The control view-through rate. + <p>Corresponds to "Control view-through rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The optimized view-through rate. + <p>Corresponds to "Optimized view-through rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The percentage by which optimized view-through rate is greater than the unoptimized + view-through rate. This is calculated as (( {@link + Column#VIDEO_OPTIMIZATION_OPTIMIZED_VIEW_THROUGH_RATE}/ {@link + Column#VIDEO_OPTIMIZATION_CONTROL_VIEW_THROUGH_RATE}) - 1) * 100 for an ad for which the + optimization feature has been enabled. + <p>Corresponds to "View-through rate lift" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total number of impressions viewed on the user's screen. + <p>Corresponds to "Total Active View viewable impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The total number of impressions that were sampled and measured by active view. + <p>Corresponds to "Total Active View measurable impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The percentage of total impressions viewed on the user's screen (out of the total impressions + measurable by active view). + + + + + + + Total number of impressions that were eligible to measure viewability. + <p>Corresponds to "Total Active View eligible impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The percentage of total impressions that were measurable by active view (out of all the total + impressions sampled for active view). + <p>Corresponds to "Total Active View % measurable impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + Active View total average time in seconds that specific impressions are reported as being + viewable. + <p>Corresponds to "Total Active View Average Viewable Time (seconds)" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions delivered by the ad server viewed on the user's screen. + <p>Corresponds to "Ad server Active View viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions delivered by the ad server that were sampled, and measurable by + active view. + <p>Corresponds to "Ad server Active View measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The percentage of impressions delivered by the ad server viewed on the user's screen (out of + the ad server impressions measurable by active view). + <p>Corresponds to "Ad server Active View % viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Total number of impressions delivered by the ad server that were eligible to measure + viewability. + <p>Corresponds to "Ad server Active View eligible impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The percentage of impressions delivered by the ad server that were measurable by active view ( + out of all the ad server impressions sampled for active view). + <p>Corresponds to "Ad server Active View % measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Active View ad server revenue. + <p>Corresponds to "Ad Server Active View Revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Active View ad server average time in seconds that specific impressions are reported as being + viewable. + <p>Corresponds to "Ad Server Active View Average Viewable Time (seconds)" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions delivered by AdSense viewed on the user's screen, + <p>Corresponds to "AdSense Active View viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions delivered by AdSense that were sampled, and measurable by active + view. + <p>Corresponds to "AdSense Active View measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The percentage of impressions delivered by AdSense viewed on the user's screen (out of AdSense + impressions measurable by active view). + <p>Corresponds to "AdSense Active View % viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Total number of impressions delivered by AdSense that were eligible to measure viewability. + <p>Corresponds to "AdSense Active View eligible impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The percentage of impressions delivered by AdSense that were measurable by active view ( out of + all AdSense impressions sampled for active view). + <p>Corresponds to "AdSense Active View % measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Active View AdSense revenue. + <p>Corresponds to "AdSense Active View Revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Active View AdSense average time in seconds that specific impressions are reported as being + viewable. + <p>Corresponds to "AdSense Active View Average Viewable Time (seconds)" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions delivered by Ad Exchange viewed on the user's screen, + <p>Corresponds to "Ad Exchange Active View viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The number of impressions delivered by Ad Exchange that were sampled, and measurable by active + view. + <p>Corresponds to "Ad Exchange Active View measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The percentage of impressions delivered by Ad Exchange viewed on the user's screen (out of Ad + Exchange impressions measurable by active view). + <p>Corresponds to "Ad Exchange Active View % viewable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Total number of impressions delivered by Ad Exchange that were eligible to measure viewability. + <p>Corresponds to "Ad Exchange Active View eligible impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The percentage of impressions delivered by Ad Exchange that were measurable by active view ( + out of all Ad Exchange impressions sampled for active view). + <p>Corresponds to "Ad Exchange Active View % measurable impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Active View AdExchange revenue. + <p>Corresponds to "Ad Exchange Active View Revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Active View AdExchange average time in seconds that specific impressions are reported as being + viewable. + <p>Corresponds to "Ad Exchange Active View Average Viewable Time (seconds)" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Active View total revenue. + <p>Corresponds to "Total Active View Revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Cost for audience extension + ie. cost the publisher had to pay in order to buy the inventory. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Number of view-through conversions. + + + + + + + Number of view-through conversions per thousand impressions. + <p>Corresponds to "Conversions per thousand impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Number of click-through conversions. + <p>Corresponds to "Click-through conversions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + Number of click-through conversions per click. + <p>Corresponds to "Conversions per click" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + Revenue for view-through conversions. + <p>Corresponds to "Advertiser view-through sales" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + Revenue for click-through conversions. + <p>Corresponds to "Advertiser click-through sales" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + Total number of conversions. + <p>Corresponds to "Total conversions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + Total revenue for conversions. + <p>Corresponds to "Total advertiser sales" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + The number of impressions sent to Ad Exchange / AdSense, regardless of whether they + won or lost (total number of dynamic allocation impressions). + <p>Corresponds to "Impressions competing" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of unfilled queries that attempted dynamic allocation by Ad Exchange / AdSense. + <p>Corresponds to "Unfilled competing impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of Ad Exchange / AdSense and DFP impressions. + <p>Corresponds to "Eligible impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The difference between eligible impressions and competing impressions in dynamic allocation. + + + + + + + The percentage of eligible impressions that are not competing in dynamic allocation. + <p>Corresponds to "Impressions not competing (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The percent of eligible impressions participating in dynamic allocation. + + + + + + + The percent of total dynamic allocation queries that won. + <p>Corresponds to "Dynamic allocation match rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted net revenue of the {@link ProposalLineItem}. + <p>Corresponds to "Contracted revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted net revenue in the local currency of the {@link ProposalLineItem}. + + See {@link #CONTRACTED_REVENUE_CONTRACTED_NET_REVENUE} + <p>Can correspond to any of the following in the DFP UI: Contracted revenue (local), Contracted revenue (net) (local). Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted gross revenue of the {@link ProposalLineItem}, including agency commission. + <p>Corresponds to "Contracted revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted gross revenue in the local currency of the {@link ProposalLineItem}, including + agency commission. + + See {@link #CONTRACTED_REVENUE_CONTRACTED_GROSS_REVENUE} + <p>Corresponds to "Contracted revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The value added tax on contracted net revenue of the {@link ProposalLineItem} or + {@link Proposal}. + <p>Corresponds to "Contracted VAT" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The value added tax on contracted net revenue in the local currency of the + {@link ProposalLineItem} or {@link Proposal}. + + See {@link #CONTRACTED_REVENUE_CONTRACTED_VAT} + <p>Corresponds to "Contracted VAT (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted agency commission of the {@link ProposalLineItem} or {@link Proposal}. + <p>Corresponds to "Contracted agency commission" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted agency commission in the local currency of the {@link ProposalLineItem} or + {@link Proposal}. + + See {@link #CONTRACTED_REVENUE_CONTRACTED_AGENCY_COMMISSION} + <p>Corresponds to "Contracted agency commission (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted impressions of the {@link ProposalLineItem}. + <p>Corresponds to "Contracted impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted clicks of the {@link ProposalLineItem}. + <p>Corresponds to "Contracted clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted volume of the {@link ProposalLineItem}. Volume represents impressions for + rate type CPM, clicks for CPC, and days for CPD. + <p>Corresponds to "Contracted volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The budget of the {@link Proposal}. + <p>Corresponds to "Budget" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The remaining budget of the {@link Proposal}. It is calculated by subtracting the contracted + net revenue from the budget. + <p>Corresponds to "Remaining budget" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The buffered impressions of the {@link ProposalLineItem}. + <p>Corresponds to "Buffered impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The buffered clicks of the {@link ProposalLineItem}. + <p>Corresponds to "Buffered clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The scheduled impressions of a {@link ProposalLineItem}. It is the sum of + {@link #SALES_CONTRACT_CONTRACTED_IMPRESSIONS} and + {@link #SALES_CONTRACT_BUFFERED_IMPRESSIONS}. + <p>Corresponds to "Scheduled impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The scheduled clicks of a {@link ProposalLineItem}. It is the sum of + {@link #SALES_CONTRACT_CONTRACTED_CLICKS} and {@link #SALES_CONTRACT_BUFFERED_CLICKS}. + <p>Corresponds to "Scheduled clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The scheduled volume of a {@link ProposalLineItem}. It is the sum of + {@link #SALES_CONTRACT_CONTRACTED_VOLUME} and buffered volume. + <p>Corresponds to "Scheduled volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The scheduled net revenue of a {@link ProposalLineItem}. + <p>Corresponds to "Scheduled revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The scheduled net revenue in the local currency of a {@link ProposalLineItem}. + <p>Corresponds to "Scheduled revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The scheduled gross revenue of a {@link ProposalLineItem}. + <p>Corresponds to "Scheduled revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The scheduled gross revenue in the local currency of a {@link ProposalLineItem}. + <p>Corresponds to "Scheduled revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total budget of the {@link Proposal}. It differs from {@link #SALES_CONTRACT_BUDGET} since + it always contains the total budget, not the prorated budget. + <p>Corresponds to "Total budget" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total remaining budget of the {@link Proposal}. It differs from {@link + #SALES_CONTRACT_REMAINING_BUDGET} since it always contains the total remaining budget, not the + prorated remaining budget. + <p>Corresponds to "Total remaining budget" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total contracted volume of the {@link ProposalLineItem}. It differs from {@link + #SALES_CONTRACT_CONTRACTED_VOLUME} that the volume is not prorated with regard to the date + range. + <p>Corresponds to "Total contracted volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total contracted net revenue of the {@link ProposalLineItem}. It differs from {@link + #CONTRACTED_REVENUE_CONTRACTED_NET_REVENUE} that the revenue is not prorated with regard to the + date range. + <p>Corresponds to "Total contracted revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total contracted net revenue in the local currency of the {@link ProposalLineItem}. It + differs from {@link #CONTRACTED_REVENUE_LOCAL_CONTRACTED_NET_REVENUE} that the revenue is not + prorated with regard to the date range. + + <p>See {@link #SALES_TOTAL_TOTAL_CONTRACTED_NET_REVENUE} + <p>Corresponds to "Total contracted revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total contracted gross revenue of the {@link ProposalLineItem}. It differs from {@link + #CONTRACTED_REVENUE_CONTRACTED_GROSS_REVENUE} that the revenue is not prorated with regard to + the date range. + <p>Corresponds to "Total contracted revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total contracted gross revenue in the local currency of the {@link ProposalLineItem}. It + differs from {@link #CONTRACTED_REVENUE_LOCAL_CONTRACTED_GROSS_REVENUE} that the revenue is not + prorated with regard to the date range. + + <p>See {@link #SALES_TOTAL_TOTAL_CONTRACTED_GROSS_REVENUE} + <p>Corresponds to "Total contracted revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total contracted agency commission of the {@link ProposalLineItem}. It differs from {@link + #CONTRACTED_REVENUE_CONTRACTED_AGENCY_COMMISSION} that the revenue is not prorated with regard + to the date range. + <p>Corresponds to "Total contracted agency commission" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total contracted agency commission in the local currency of the {@link ProposalLineItem}. + It differs from {@link #CONTRACTED_REVENUE_LOCAL_CONTRACTED_AGENCY_COMMISSION} that the revenue + is not prorated with regard to the date range. + + <p>See {@link #SALES_TOTAL_TOTAL_CONTRACTED_AGENCY_COMMISSION} + <p>Corresponds to "Total contracted agency commission (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total net revenue plus its value added tax of the {@link ProposalLineItem}. The revenue is + not prorated with regard to the date range. + <p>Corresponds to "Total contracted revenue with VAT (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total net revenue plus its value added tax in the local currency of the {@link + ProposalLineItem}. The revenue is not prorated with regard to the date range. + + <p>See {@link #SALES_TOTAL_TOTAL_CONTRACTED_WITH_VAT} + <p>Corresponds to "Total contracted revenue with VAT (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total scheduled volume of the {@link ProposalLineItem}. It differs from {@link + #SCHEDULED_SCHEDULED_VOLUME} that the volume is not prorated with regard to the date range. + <p>Corresponds to "Total scheduled volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total scheduled net revenue of the {@link ProposalLineItem}. It differs from {@link + #SCHEDULED_SCHEDULED_NET_REVENUE} that the revenue is not prorated with regard to the date + range. + <p>Corresponds to "Total scheduled revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total scheduled net revenue in the local currency of the {@link ProposalLineItem}. It + differs from {@link #SCHEDULED_LOCAL_SCHEDULED_NET_REVENUE} that the revenue is not prorated + with regard to the date range. + + <p>See {@link #SALES_TOTAL_TOTAL_SCHEDULED_NET_REVENUE} + <p>Corresponds to "Total scheduled revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total scheduled gross revenue of the {@link ProposalLineItem}. It differs from {@link + #SCHEDULED_SCHEDULED_GROSS_REVENUE} that the revenue is not prorated with regard to the date + range. + <p>Corresponds to "Total scheduled revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The total scheduled gross revenue in the local currency of the {@link ProposalLineItem}. It + differs from {@link #SCHEDULED_LOCAL_SCHEDULED_GROSS_REVENUE} that the revenue is not prorated + with regard to the date range. + + <p>See {@link #SALES_TOTAL_TOTAL_SCHEDULED_GROSS_REVENUE} + <p>Corresponds to "Total scheduled revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unreconciled net revenue of the {@link ProposalLineItem}. It is the portion of {@link + #UNIFIED_REVENUE_UNIFIED_NET_REVENUE} coming from unreconciled DFP volume. + <p>Corresponds to "Unreconciled revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unreconciled net revenue of the {@link ProposalLineItem} in local currency. It is the + portion of {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_NET_REVENUE} coming from unreconciled DFP + volume. + + <p>See {@link #UNIFIED_REVENUE_UNRECONCILED_NET_REVENUE} + <p>Corresponds to "Unreconciled revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unreconciled gross revenue of the {@link ProposalLineItem}. It is the portion of {@link + #UNIFIED_REVENUE_UNIFIED_GROSS_REVENUE} coming from unreconciled DFP volume. + <p>Corresponds to "Unreconciled revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unreconciled gross revenue of the {@link ProposalLineItem} in local currency. It is the + portion of {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_GROSS_REVENUE} coming from unreconciled DFP + volume. + + <p>See {@link #UNIFIED_REVENUE_UNRECONCILED_GROSS_REVENUE} + <p>Corresponds to "Unreconciled revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The forecasted net revenue of the {@link ProposalLineItem}. It is the portion of {@link + #UNIFIED_REVENUE_UNIFIED_NET_REVENUE} coming from forecasted DFP volume. + <p>Corresponds to "Forecasted revenue (net)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The forecasted net revenue of the {@link ProposalLineItem} in local currency. It is the portion + of {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_NET_REVENUE} coming from forecasted DFP volume. + + <p>See {@link #UNIFIED_REVENUE_FORECASTED_NET_REVENUE} + <p>Corresponds to "Forecasted revenue (net) (local)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The forecasted gross revenue of the {@link ProposalLineItem}. It is the portion of {@link + #UNIFIED_REVENUE_UNIFIED_GROSS_REVENUE} coming from forecasted DFP volume. + <p>Corresponds to "Forecasted revenue (gross)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The forecasted gross revenue of the {@link ProposalLineItem} in local currency. It is the + portion of {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_GROSS_REVENUE} coming from forecasted DFP + volume. + + <p>See {@link #UNIFIED_REVENUE_FORECASTED_GROSS_REVENUE} + <p>Corresponds to "Forecasted revenue (gross) (local)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The unified net revenue of the {@link ProposalLineItem}. It is a combination of {@link + #UNIFIED_REVENUE_UNRECONCILED_NET_REVENUE}, {@link #BILLING_BILLABLE_NET_REVENUE}, and {@link + #UNIFIED_REVENUE_FORECASTED_NET_REVENUE} when query date range spans historical delivery and + forecasted delivery. + <p>Corresponds to "Unified revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unified net revenue of the {@link ProposalLineItem} in local currency. It is a + combination of {@link #UNIFIED_REVENUE_LOCAL_UNRECONCILED_NET_REVENUE}, + {@link #BILLING_LOCAL_BILLABLE_NET_REVENUE}, + and {@link #UNIFIED_REVENUE_LOCAL_FORECASTED_NET_REVENUE} when query date range spans + historical delivery and forecasted delivery. + + See {@link #UNIFIED_REVENUE_UNIFIED_NET_REVENUE} + <p>Corresponds to "Unified revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unified net revenue of the {@link ProposalLineItem}. It is a combination of + {@link #UNIFIED_REVENUE_UNRECONCILED_GROSS_REVENUE}, {@link #BILLING_BILLABLE_GROSS_REVENUE}, + and {@link #UNIFIED_REVENUE_FORECASTED_GROSS_REVENUE} when query date range spans historical + delivery and forecasted delivery. + <p>Corresponds to "Unified revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unified gross revenue of the {@link ProposalLineItem} in local currency. It is a + combination of {@link #UNIFIED_REVENUE_LOCAL_UNRECONCILED_GROSS_REVENUE}, + {@link #BILLING_LOCAL_BILLABLE_GROSS_REVENUE}, and + {@link #UNIFIED_REVENUE_LOCAL_FORECASTED_GROSS_REVENUE} when query date range spans historical + delivery and forecasted delivery. + + See {@link #UNIFIED_REVENUE_UNIFIED_GROSS_REVENUE} + <p>Corresponds to "Unified revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unified agency commission of the {@link ProposalLineItem}. It is a combination of the + unreconciled agency commission, the {@link #BILLING_BILLABLE_AGENCY_COMMISSION}, + and the forecasted agency commission when query date range spans historical delivery and + forecasted delivery. + <p>Corresponds to "Unified agency commission" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unified agency commission of the {@link ProposalLineItem} in local currency. It is a + combination of the unreconciled agency commission, the + {@link #BILLING_BILLABLE_AGENCY_COMMISSION}, and the forecasted agency commission when query + date range spans historical delivery and forecasted delivery. + + See {@link #UNIFIED_REVENUE_UNIFIED_AGENCY_COMMISSION} + <p>Corresponds to "Unified agency commission (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The unreconciled volume of the {@link ProposalLineItem} for each cycle. Volume represents + impressions for rate type CPM, clicks for CPC and days for CPD. This fact can only be run + in proposal or proposal line item time zone. + <p>Corresponds to "Unreconciled volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The forecasted volume of the {@link ProposalLineItem} for each cycle. Volume represents + impressions for rate type CPM, clicks for CPC and days for CPD. This fact can only be run + in proposal or proposal line item time zone. + <p>Corresponds to "Forecasted volume" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The unified volume of the {@link ProposalLineItem} for each cycle. Volume represents + impressions for rate type CPM, clicks for CPC and days for CPD. This fact can only be run + in proposal or proposal line item time zone. + <p>Corresponds to "Unified volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The expected revenue of the {@link ProposalLineItem}. It is equivalent to + {@link #UNIFIED_REVENUE_UNIFIED_NET_REVENUE} when the {@link ProposalLineItem} is sold and + {@link #SALES_PIPELINE_PIPELINE_NET_REVENUE} otherwise. + <p>Corresponds to "Expected revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The expected revenue of the {@link ProposalLineItem} in local currency. It is equivalent to + {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_NET_REVENUE} when the {@link ProposalLineItem} is sold + and {@link #SALES_PIPELINE_LOCAL_PIPELINE_NET_REVENUE} otherwise. + + <p>See {@link #EXPECTED_REVENUE_EXPECTED_NET_REVENUE} + <p>Corresponds to "Expected revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The expected gross revenue of the {@link ProposalLineItem}. It is equivalent to {@link + #UNIFIED_REVENUE_UNIFIED_GROSS_REVENUE} when the {@link ProposalLineItem} is sold and {@link + #SALES_PIPELINE_PIPELINE_GROSS_REVENUE} otherwise. + <p>Corresponds to "Expected revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The expected gross revenue of the {@link ProposalLineItem} in local currency. It is equivalent + to {@link #UNIFIED_REVENUE_LOCAL_UNIFIED_GROSS_REVENUE} when the {@link ProposalLineItem} is + sold and {@link #SALES_PIPELINE_LOCAL_PIPELINE_GROSS_REVENUE} otherwise. + + <p>See {@link #EXPECTED_REVENUE_EXPECTED_GROSS_REVENUE} + <p>Corresponds to "Expected revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The pipeline net revenue of the {@link ProposalLineItem}. There is no revenue for sold {@link + ProposalLineItem proposal line items}. For unsold {@link ProposalLineItem proposal line items}, + it is calculated by multiplying {@link Proposal#probabilityOfClose} by the contracted revenue + when inventory is not reserved; otherwise it is calcualted by multiplying {@link + Proposal#probabilityOfClose} by the forecasted revenue. + <p>Corresponds to "Pipeline revenue (net)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The pipeline net revenue in the local currency of the {@link ProposalLineItem}. There is no + revenue for sold {@link ProposalLineItem proposal line items}. For unsold + {@link ProposalLineItem proposal line items}, it is calculated by multiplying + {@link Proposal#probabilityOfClose} by the contracted revenue when inventory is not reserved; + otherwise it is calcualted by multiplying {@link Proposal#probabilityOfClose} by the forecasted + revenue. + + See {@link #SALES_PIPELINE_PIPELINE_NET_REVENUE} + <p>Corresponds to "Pipeline revenue (net) (local)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The pipeline gross revenue of the {@link ProposalLineItem}. There is no revenue for sold + {@link ProposalLineItem proposal line items}. For unsold + {@link ProposalLineItem proposal line items}, it is calculated by multiplying + {@link Proposal#probabilityOfClose} by the contracted revenue including agency commission when + inventory is not reserved; otherwise it is calcualted by multiplying + {@link Proposal#probabilityOfClose} by the forecasted revenue including agency commission. + <p>Corresponds to "Pipeline revenue (gross)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The pipeline gross revenue in the local currency of the {@link ProposalLineItem}. There is no + revenue for sold {@link ProposalLineItem proposal line items}. For unsold + {@link ProposalLineItem proposal line items}, it is calculated by multiplying + {@link Proposal#probabilityOfClose} by the contracted revenue including agency commission when + inventory is not reserved; otherwise it is calcualted by multiplying + {@link Proposal#probabilityOfClose} by the forecasted revenue including agency commission. + + See {@link #SALES_PIPELINE_PIPELINE_GROSS_REVENUE} + <p>Corresponds to "Pipeline revenue (gross) (local)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The pipeline agency commission of the {@link ProposalLineItem}. There is no revenue for sold + {@link ProposalLineItem proposal line items}. For unsold + {@link ProposalLineItem proposal line items}, it is calculated against gross pipeline revenue. + <p>Corresponds to "Pipeline agency commission" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The pipeline agency commission in the local currency of the {@link ProposalLineItem}. There is + no revenue for sold {@link ProposalLineItem proposal line items}. For unsold + {@link ProposalLineItem proposal line items}, it is calculated against gross pipeline revenue + in local currency of the {@link ProposalLineItem}. + + See {@link #SALES_PIPELINE_PIPELINE_AGENCY_COMMISSION} + <p>Corresponds to "Pipeline agency commission (local)" in the DFP UI. Compatible with the SALES report type.</p> + + + + + + + The DFP volume of the {@link ProposalLineItem}, which is used for reconciliation. Volume + represents impressions for rate type CPM, clicks for CPC and days for CPD. + <p>Corresponds to "DFP volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The third party volume of the {@link ProposalLineItem}, which is used for reconciliation. + Volume represents impressions for rate type CPM, clicks for CPC and days for CPD. + <p>Corresponds to "Third-party volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The reconciled volume of the {@link ProposalLineItem}, which is used for reconciliation. Volume + represents impressions for rate type CPM, clicks for CPC and days for CPD. + <p>Corresponds to "Reconciled volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The discrepancy percentage between DFP volume and third party volume. + <p>Corresponds to "Discrepancy (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The reconciled revenue of the {@link LineItem}. + <p>Corresponds to "Reconciled revenue" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The discrepancy between DFP impressions and third party impressions. + <p>Corresponds to "Impression discrepancy" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The discrepancy between DFP clicks and third party clicks. + <p>Corresponds to "Click discrepancy" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The discrepancy between DFP revenue and third party revenue. + <p>Corresponds to "Revenue discrepancy" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable net revenue of the {@link ProposalLineItem}. It is calculated from reconciled + volume and rate, with cap applied. + <p>Corresponds to "Billable revenue (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable net revenue in the local currency of the {@link ProposalLineItem}. It is + calculated from reconciled volume and rate, with cap applied. + + See {@link #BILLING_BILLABLE_NET_REVENUE} + <p>Corresponds to "Billable revenue (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable gross revenue of the {@link ProposalLineItem}. It is calculated from reconciled + volume and rate, with cap applied, and including agency commission. + <p>Corresponds to "Billable revenue (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable gross revenue in the local currency of the {@link ProposalLineItem}. It is + calculated from reconciled volume and rate, with cap applied, and including agency commission. + + See {@link #BILLING_BILLABLE_GROSS_REVENUE} + <p>Corresponds to "Billable revenue (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable net revenue of the {@link ProposalLineItem} before manual adjustment. It is + calculated from reconciled volume and rate, with cap applied, before manual adjustment. + <p>Corresponds to "Billable revenue before manual adjustment (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable net revenue in local currency of the {@link ProposalLineItem} before manual + adjustment. It is calculated from reconciled volume and rate, with cap applied, before manual + adjustment. + + <p>See {@link #BILLING_BILLABLE_NET_REVENUE_BEFORE_MANUAL_ADJUSTMENT} + <p>Corresponds to "Billable revenue before manual adjustment (net) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable gross revenue of the {@link ProposalLineItem} before manual adjustment. It is + calculated from reconciled volume and rate, with cap applied, before manual adjustment. + <p>Corresponds to "Billable revenue before manual adjustment (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable net revenue in local currency of the {@link ProposalLineItem} before manual + adjustment. It is calculated from reconciled volume and rate, with cap applied, before manual + adjustment. + + <p>See {@link #BILLING_BILLABLE_GROSS_REVENUE_BEFORE_MANUAL_ADJUSTMENT} + <p>Corresponds to "Billable revenue before manual adjustment (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The value added tax on billable net revenue of the {@link ProposalLineItem} or {@link + Proposal}. + <p>Corresponds to "Billable VAT" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The value added tax on billable net revenue in the local currency of the + {@link ProposalLineItem} or {@link Proposal}. + + See {@link #BILLING_BILLABLE_VAT} + <p>Corresponds to "Billable VAT (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable agency commission of the {@link ProposalLineItem} or {@link Proposal}. + <p>Corresponds to "Billable agency commission" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable agency commission in the local currency of the {@link ProposalLineItem} or + {@link Proposal}. + + See {@link #BILLING_BILLABLE_AGENCY_COMMISSION} + <p>Corresponds to "Billable agency commission (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The cap quantity of the {@link ProposalLineItem} for each cycle. Quantity represents + impressions for rate type CPM, clicks for CPC and days for CPD. + <p>Corresponds to "Cap quantity" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable volume of the {@link ProposalLineItem} for each cycle. Billable volumes are + calculated by applying cap quantity to reconciled volumes. Volume represents impressions for + rate type CPM, clicks for CPC and days for CPD. + <p>Corresponds to "Billable volume" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The delivery rollover volume of the {@link ProposalLineItem} from previous cycle. Volume + represents impressions for rate type CPM, clicks for CPC and days for CPD. + <p>Corresponds to "Delivery rollover" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The CPM calcuated by {@link #BILLING_BILLABLE_NET_REVENUE} and {@link #AD_SERVER_IMPRESSIONS}. + <p>Corresponds to "Realized CPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The rate calcuated by {@link #BILLING_BILLABLE_NET_REVENUE} and DFP volume. + <p>Corresponds to "Realized rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted net overall discount of the {@link ProposalLineItem}. + <p>Corresponds to "Contracted overall discount (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The billable net overall discount of the {@link ProposalLineItem}. + <p>Corresponds to "Billable overall discount (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The contracted non-billable (net) of the {@link ProposalLineItem}. + The non-billable means revenue that marked as make good, added value or barter. + <p>Corresponds to "Contracted non-billable (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SALES, BUSINESS_INTELLIGENCE.</p> + + + + + + + The number of invoiced impressions. + <p>Corresponds to "Invoiced impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + The number of invoiced unfilled impressions. + <p>Corresponds to "Invoiced unfilled impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SAMPLED_HISTORICAL.</p> + + + + + + + The total number of impressions tracked for Nielsen Digital Ad Ratings measurement. + <p>Corresponds to "Impressions" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The total number of impressions for in-target demographic tracked for Nielsen Digital Ad + Ratings measurement. + <p>Corresponds to "In-target impressions" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The population in the demographic. + <p>Corresponds to "Population base" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The total population for all in-target demographics. + <p>Compatible with the REACH report type.</p> + + + + + + + The total number of different people within the selected demographic who were reached. + <p>Corresponds to "Unique audience" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The total number of different people within all in-target demographics who were reached. + <p>Compatible with the REACH report type.</p> + + + + + + + The unique audience reached as a percentage of the population base. + <p>Corresponds to "% audience reach" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The unique audience reached as a percentage of the population base for all in-target + demographics. + <p>Compatible with the REACH report type.</p> + + + + + + + The average number of times that a person within the target audience sees an advertisement. + <p>Corresponds to "Average frequency" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The average number of times that a person within the target audience sees an advertisement + for all in-target demographics. + <p>Compatible with the REACH report type.</p> + + + + + + + The unit of audience volume, which is based on the percentage of the reached target audience + population multiplied by the average frequency. + <p>Corresponds to "Gross rating points" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The unit of audience volume, which is based on the percentage of the reached target audience + population multiplied by the average frequency, for all in-target demographics. + <p>Compatible with the REACH report type.</p> + + + + + + + The share of impressions that reached the target demographic. + <p>Corresponds to "% impression share" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The share of impressions that reached all in-target demographics. + <p>Corresponds to "In-target % impression share" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The share of the total population represented by the population base. + <p>Corresponds to "% population share" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The share of the total population for all in-target demographics represented by the + population base. + <p>Compatible with the REACH report type.</p> + + + + + + + The share of the unique audience in the demographic. + <p>Corresponds to "% audience share" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The share of the unique audience for all in-target demographics. + <p>Compatible with the REACH report type.</p> + + + + + + + The relative unique audience in the demographic compared with its share of the overall + population. + <p>Corresponds to "Audience index" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The relative unique audience for all in-target demographics compared with its share of the + overall population. + <p>Compatible with the REACH report type.</p> + + + + + + + The relative impressions per person in the demographic compared with the impressions per person + for the overall population. + <p>Corresponds to "Impressions index" in the DFP UI. Compatible with the REACH report type.</p> + + + + + + + The relative impressions per person for all in-target demographics compared with the + impressions per person for the overall population. + <p>Compatible with the REACH report type.</p> + + + + + + + The host impressions in the partner management. + <p>Corresponds to "Host impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The host clicks in the partner management. + <p>Corresponds to "Host clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The host CTR in the partner management. + <p>Corresponds to "Host CTR" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The unfilled impressions in the partner management. + <p>Corresponds to "Unfilled impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, PARTNER_FINANCE.</p> + + + + + + + The partner impressions in the partner management. + <p>Corresponds to "Partner impressions" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The partner clicks in the partner management. + <p>Corresponds to "Partner clicks" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The partner CTR in the partner management. + <p>Corresponds to "Partner CTR" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + The gross revenue in the partner management. + <p>Corresponds to "Gross revenue" in the DFP UI. Compatible with the HISTORICAL report type.</p> + + + + + + + Monthly host impressions for partner finance reports. + <p>Corresponds to "Host impressions" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p> + + + + + + + Monthly host revenue for partner finance reports. + <p>Corresponds to "Host revenue" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p> + + + + + + + Monthly host eCPM for partner finance reports. + <p>Corresponds to "Host eCPM" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p> + + + + + + + Monthly partner revenue for partner finance reports. + <p>Corresponds to "Partner revenue" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p> + + + + + + + Monthly partner eCPM for partner finance reports. + <p>Corresponds to "Partner eCPM" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p> + + + + + + + Monthly gross revenue for partner finance reports. + <p>Corresponds to "Gross revenue" in the DFP UI. Compatible with the PARTNER_FINANCE report type.</p> + + + + + + + + + Describes reasons for common errors + + + + + + + Indicates that an attempt was made to retrieve an entity that does not + exist. + + + + + + + Indicates that an attempt was made to create an entity that already + exists. + + + + + + + Indicates that a value is not applicable for given use case. + + + + + + + Indicates that two elements in the collection were identical. + + + + + + + Indicates that an attempt was made to change an immutable field. + + + + + + + Indicates that another request attempted to update the same data in the same network + at about the same time. Please wait and try the request again. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + The reason behind the currency code error. + + + + + + + The currency code is invalid and does not follow ISO 4217. + + + + + + + The currency code is valid, but is not supported. + + + + + + + + + Represents a period of time. + + + + + + + The current day. + + + + + + + The previous day. + + + + + + + The last week, from monday to sunday. + + + + + + + The previous month. + + + + + + + The last 3 full months. For example, if today is May 5, 2017, then LAST_3_MONTHS would go from + February 1 to April 30. + + + + + + + The last 5 months and the current month to date. This date range is only + usable for the columns {@link Column#REACH_FREQUENCY}, + {@link Column#REACH_AVERAGE_REVENUE} and {@link Column#REACH}. + + + + + + + Specifying this value will enable the user to specify + {@link ReportQuery#startDate} and {@link ReportQuery#endDate}. + + + + + + + The next day. + + + + + + + The next ninety days. + + + + + + + The next week, from monday to sunday. + + + + + + + The next month. + + + + + + + Beginning of the next day until the end of the next month. + + + + + + + The next quarter. + + + + + + + The next three months. + + + + + + + The next twelve months. + + + + + + + + + {@code Dimension} provides the break-down and filterable types available for + running a {@link ReportJob}. Aggregate and percentage columns will be + calculated based on these groupings. + + + + + + + Breaks down reporting data by month and year in the network time zone. Can + be used to filter on month using ISO 4601 format 'YYYY-MM'. + + <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following + time zone types: + <ul> + <li> {@link TimeZoneType.PUBLISHER} + <li> {@link TimeZoneType.PROPOSAL_LOCAL} + </ul> + <p>Corresponds to "Month and year" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, PARTNER_FINANCE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by week of the year in the network time zone. + Cannot be used for filtering. + + <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following + time zone types: + <ul> + <li> {@link TimeZoneType.PUBLISHER} + <li> {@link TimeZoneType.PROPOSAL_LOCAL} + </ul> + <p>Corresponds to "Week" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by date in the network time zone. Can be used to + filter by date using ISO 8601's format 'YYYY-MM-DD'". + + <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following + time zone types: + <ul> + <li> {@link TimeZoneType.PUBLISHER} + <li> {@link TimeZoneType.PROPOSAL_LOCAL} + </ul> + <p>Corresponds to "Date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by day of the week in the network time zone. Can + be used to filter by day of the week using the index of the day (from 1 for + Monday is 1 to 7 for Sunday). + <p>Corresponds to "Day of week" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by hour of the day in the network time zone. Can + be used to filter by hour of the day (from 0 to 23). + <p>Corresponds to "Hour" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link LineItem#id}. Can be used to + filter by {@link LineItem#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by line item. {@link LineItem#name} and + {@link LineItem#id} are automatically included as columns in the report. + Can be used to filter by {@link LineItem#name}. + <p>Corresponds to "Line item" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link LineItem#lineItemType}. Can be used + to filter by line item type using {@link LineItemType} enumeration names. + <p>Corresponds to "Line item type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by aggregated demand channel type. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Order#id}. Can be used to filter by + {@link Order#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by order. {@link Order#name} and + {@link Order#id} are automatically included as columns in the report. Can + be used to filter by {@link Order#name}. + <p>Corresponds to "Order" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Delivery status of the order. Not available as a dimension to report on, + but exists as a dimension in order to filter on it using PQL. + Valid values are 'STARTED', 'NOT_STARTED' and 'COMPLETED'. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by advertising company {@link Company#id}. Can + be used to filter by {@link Company#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by advertising company. {@link Company#name} and + {@link Company#id} are automatically included as columns in the report. + Can be used to filter by {@link Company#name}. + <p>Corresponds to "Advertiser" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The network that provided the ad for SDK ad mediation. + + <p>If selected for a report, that report will include only SDK mediation ads and will not + contain non-SDK mediation ads. + + <p>SDK mediation ads are ads for mobile devices. They have a list of ad networks which can + provide ads to serve. Not every ad network will have an ad to serve so the device will try each + network one-by-one until it finds an ad network with an ad to serve. The ad network that ends + up serving the ad will appear here. Note that this id does not correlate to anything in the + companies table and is not the same id as is served by {@link #ADVERTISER_ID}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + The name of the network defined in {@link #AD_NETWORK_ID}. + <p>Corresponds to "Ad network name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by salesperson {@link User#id}. Can be used to + filter by {@link User#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by salesperson. {@link User#name} and + {@link User#id} of the salesperson are automatically included as columns in + the report. Can be used to filter by {@link User#name}. + <p>Corresponds to "Salesperson" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Creative#id} or creative set id + (master's {@link Creative#id}) if the creative is part of a creative set. + Can be used to filter by {@link Creative#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by creative. {@link Creative#name} and + {@link Creative#id} are automatically included as columns in the report. + Can be used to filter by {@link Creative#name}. + <p>Corresponds to "Creative" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by creative type. + <p>Corresponds to "Creative type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by creative billing type. + <p>Corresponds to "Creative billing type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by custom event ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by custom event name. + <p>Corresponds to "Custom event" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by custom event type (timer/exit/counter). + <p>Corresponds to "Custom event type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Creative#size}. Cannot be used for + filtering. + <p>Corresponds to "Creative size" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link AdUnit#id}. Can be used to filter by + {@link AdUnit#id}. {@link #AD_UNIT_NAME}, i.e. {@link AdUnit#name}, is + automatically included as a dimension in the report. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by ad unit. {@link AdUnit#name} and + {@link AdUnit#id} are automatically included as columns in the report. Can + be used to filter by {@link AdUnit#name}. + <p>Corresponds to "Ad unit" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Used to filter on all the descendants of an ad unit by {@link AdUnit#id}. Not available as a + dimension to report on. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Used to filter on all the descendants of an ad unit by {@link AdUnit#name}. Not available as a + dimension to report on. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Placement#id}. Can be used to filter + by {@link Placement#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by placement. {@link Placement#name} and + {@link Placement#id} are automatically included as columns in the report. + Can be used to filter by {@link Placement#name}. + <p>Corresponds to "Placement" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Status of the placement. Not available as a dimension to report on, but + exists as a dimension in order to filter on it using PQL. Can be used to + filter on {@link Placement#status} by using {@link InventoryStatus} + enumeration names. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by criteria predefined by DoubleClick For Publishers like the + operating system, browser etc. Cannot be used for filtering. + <p>Corresponds to "Targeting" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + The ID of the device category to which an ad is being targeted. + + Can be used to filter by device category ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + The category of device (smartphone, feature phone, tablet, or desktop) to which an ad is being + targeted. + + Can be used to filter by device category name. + <p>Corresponds to "Device category" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by country criteria ID. Can be used to filter by + country criteria ID. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by country name. The country name and the + country criteria ID are automatically included as columns in the report. + Can be used to filter by country name using the US English name. + <p>Corresponds to "Country" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by region criteria ID. Can be used to filter by + region criteria ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by region name. The region name and the region + criteria ID are automatically included as columns in the report. Can be + used to filter by region name using the US English name. + <p>Corresponds to "Region" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by city criteria ID. Can be used to filter by + city criteria ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by city name. The city name and the city + criteria ID are automatically included as columns in the report. Can be + used to filter by city name using the US English name. + <p>Corresponds to "City" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by metro criteria ID. Can be used to filter by + metro criteria ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by metro name. The metro name and the metro + criteria ID are automatically included as columns in the report. Can be + used to filter by metro name using the US English name. + <p>Corresponds to "Metro" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by postal code criteria ID. Can be used to + filter by postal code criteria ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by postal code. The postal code and the postal + code criteria ID are automatically included as columns in the report. Can + be used to filter by postal code. + <p>Corresponds to "Postal code" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by {@link CustomTargetingValue#id}. Can be used + to filter by {@link CustomTargetingValue#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES.</p> + + + + + + + Breaks down reporting data by custom criteria. The {@link CustomTargetingValue} is + displayed in the form: + <ul> + <li> + car=honda when value match type is + {@link CustomTargetingValue.MatchType#EXACT} + </li> + <li> + car~honda when value match type is + {@link CustomTargetingValue.MatchType#BROAD} + </li> + <li> + car=*honda when value match type is + {@link CustomTargetingValue.MatchType#PREFIX} + </li> + <li> + car~*honda when value match type is + {@link CustomTargetingValue.MatchType#BROAD_PREFIX} + </li> + </ul> + {@link #CUSTOM_TARGETING_VALUE_ID}, i.e. {@link CustomTargetingValue#id} is + automatically included as a column in the report. + Cannot be used for filtering; use {@link #CUSTOM_TARGETING_VALUE_ID} instead. + <p> + When using this {@code Dimension}, metrics for freeform key values are only + reported on when they are registered with {@code CustomTargetingService}. + <p>Corresponds to "Key-values" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES.</p> + + + + + + + Breaks down reporting data by activity ID. Can be used to filter by + activity ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by activity. The activity name and the activity + ID are automatically included as columns in the report. Can be used to + filter by activity name. + <p>Corresponds to "Activity" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by activity group ID. Can be used to filter by + activity group ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by activity group. The activity group name and + the activity group ID are automatically included as columns in the report. + Can be used to filter by activity group name. + <p>Corresponds to "Activity group" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by {@link Content#id}. Can be used to filter by + {@link Content#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by content. {@link Content#name} and + {@link Content#id} are automatically included as columns in the report. Can + be used to filter by {@link Content#name}. + <p>Corresponds to "Content" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link ContentBundle#id}. Can be used to filter + by {@link ContentBundle#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by content bundle. {@link ContentBundle#name} and + {@link ContentBundle#id} are automatically included as columns in the + report. Can be used to filter by {@link ContentBundle#name}. + <p>Corresponds to "Content bundle" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by the content hierarchy. To use this dimension, a list of custom + targeting key IDs must be specified in + {@link ReportQuery#contentMetadataKeyHierarchyCustomTargetingKeyIds}. + <p> + This dimension can be used as a filter in the {@link Statement} in PQL syntax: + CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[contentMetadataKeyHierarchyCustomTargetingKeyId]_ID = + {@link CustomTargetingValue#id custom targeting value ID} + <p> + For example: WHERE CONTENT_HIERARCHY_CUSTOM_TARGETING_KEY[4242]_ID = 53423 + + + + + + + Breaks down reporting data by the fallback position of the video ad, i.e., + {@code NON_FALLBACK}, {@code FALLBACK_POSITION_1}, {@code FALLBACK_POSITION_2}, etc. Can be + used for filtering. + <p>Corresponds to "Fallback position" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by the position of the video ad within the video stream, i.e., + {@code UNKNOWN_POSITION}, {@code PREROLL}, {@code POSTROLL}, {@code UNKNOWN_MIDROLL}, + {@code MIDROLL_1}, {@code MIDROLL_2}, etc. {@code UNKNOWN_MIDROLL} represents a midroll, but + which specific midroll is unknown. Can be used for filtering. + <p>Corresponds to "Position of pod" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by the position of the video ad within the pod, i.e., + {@code UNKNOWN_POSITION}, {@code POSITION_1}, {@code POSITION_2}, etc. + Can be used for filtering. + <p>Corresponds to "Position in pod" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by partner {@link Company#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p> + + + + + + + Breaks down reporting data by partner {@link Company#name} and {@link Company#id} are + automatically included as columns in the report. + <p>Corresponds to "Partner" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p> + + + + + + + Breaks down reporting data by partner label {@link Label#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p> + + + + + + + Breaks down reporting data by partner label. {@link Label#name} and {@link Label#id} are + automatically included as columns in the report. + <p>Corresponds to "Partner label" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p> + + + + + + + Breaks down reporting data by partner assignment id. + <p>Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p> + + + + + + + Breaks down reporting data by partner assignment name. ParnterAssignment name + and id are automatically included as columns in the report. + <p>Corresponds to "Assignment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, PARTNER_FINANCE.</p> + + + + + + + Breaks down reporting data by gender and age group, i.e., MALE_13_TO_17, MALE_18_TO_24, + MALE_25_TO_34, MALE_35_TO_44, MALE_45_TO_54, MALE_55_TO_64, MALE_65_PLUS, FEMALE_13_TO_17, + FEMALE_18_TO_24, FEMALE_25_TO_34, FEMALE_35_TO_44, FEMALE_45_TO_54, FEMALE_55_TO_64, + FEMALE_65_PLUS, UNKNOWN_0_TO_17 and UNKNOWN. Whenever this dimension is selected, {@link + #COUNTRY_NAME} must be selected. + + <p>This dimension is supported only for GRP columns. + <p>Can correspond to any of the following in the DFP UI: Demographics, comScore vCE demographics. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Size of the creative requested for an ad. + <p>Corresponds to "Ad request size" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by the ad unit sizes specified in ad requests. + + <p>Formatted as comma separated values, e.g. "300x250,300x250v,300x60". + + <p>This dimension is supported only for sell-through columns. + <p>Corresponds to "Ad request sizes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH.</p> + + + + + + + Breaks down reporting data by the custom criteria specified in ad requests. + + <p>Formatted as comma separated + {@link CustomTargetingKey key}-{@link CustomTargetingValue values}, where a key-value is + formatted as {@code key1=value_1|...|value_n,key2=value_1|...|value_n,...}. + + <p>This dimension is supported only for sell-through columns. + <p>Corresponds to "Key-values" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH.</p> + + + + + + + The unique identifier used for an ad network that is associated with the company that the ad is + served for. + <p>Compatible with any of the following report types: BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + The name of the ad network that is associated with the company that the ad is served for. + <p>Corresponds to "Buyer" in the DFP UI. Compatible with any of the following report types: BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Whether the report contains only Ad Exchange traffic fulfilled by First Look Deals + or omits it. If this filter isn't included, the report will include + First Look Deals traffic in addition to any other traffic. + Not available as a dimension to report on. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by mediation group ID. A mediation group is an abstraction of + inventory used in the DFP Mediation. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by mediation group name. A mediation group is an abstraction of + inventory used in the DFP Mediation. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by yield group ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by yield group name. + <p>Corresponds to "Yield group" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by yield partner. + <p>Corresponds to "Yield partner" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO.</p> + + + + + + + Breaks down reporting data by the tag of a yield partner in a yield group. + <p>Corresponds to "Yield partner tag" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by mediation network. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange network tag name. + + <p>This field is deprecated and will be removed in v201805. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by mediation type. A mediation type can be web, mobile app or + video. + <p>Corresponds to "Mediation type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by native template (also known as creative template) ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by native template (also known as creative template) name. + <p>Corresponds to "Native ad format name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by native style ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by native style name. + <p>Corresponds to "Native style name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by mobile app name. Can be used for filtering. + <p>Corresponds to "App names" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by device name. Can be used for filtering. + <p>Corresponds to "Devices" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by inventory type. Can be used for filtering. + <p>Corresponds to "Inventory types" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by request type. Can be used for filtering. + <p>Corresponds to "Request type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + ID of the advertiser that filled the ad either directly (through DFP) or indirectly via + Google Ad Exchange or another ad network or exchange. + <p>Compatible with any of the following report types: BUSINESS_INTELLIGENCE, SAMPLED_HISTORICAL.</p> + + + + + + + Name of the advertiser that filled the ad either directly (through DFP) or indirectly via + Google Ad Exchange or another ad network or exchange. + <p>Corresponds to "Verified advertiser" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Status of the ad unit. Not available as a dimension to report on, + but exists as a dimension in order to filter on it using PQL. + Valid values correspond to {@link InventoryStatus}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Creative#id}. This includes regular creatives, + and master and companions in case of creative sets. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by creative. This includes regular creatives, + and master and companions in case of creative sets. + <p>Corresponds to "Master and Companion creative" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link ProposalLineItem#id}. Can be used to filter by + {@link ProposalLineItem#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link ProposalLineItem#name}. Can be used to filter by + {@link ProposalLineItem#name}. + <p>Corresponds to "Proposal line item" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Proposal#id}. Can be used to filter by + {@link Proposal#id}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Proposal#name}. Can be used to filter by + {@link Proposal#name}. + <p>Corresponds to "Proposal" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by salesperson {@link User#id}, including both salesperson and + secondary salespeople. Can be used to filter by all salespeople {@link User#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by salesperson {@link User#name}, including both salesperson and + secondary salespeople. Can be used to filter by all salespeople {@link User#name}. + <p>Corresponds to "All salespeople" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Used to filter by {@link User#id} in sales team. Sales team includes salesperson, secondary + salesperson, sales planners. Not available as a dimension to report on. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Used to filter by {@link User#name} in sales team. Sales team includes salesperson, secondary + salesperson, sales planners. Not available as a dimension to report on. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by proposal agency {@link Company#id}. Can be used to filter by + proposal agency {@link Company#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by proposal agency {@link Company#name}. Can be used to filter by + proposal agency {@link Company#name}. + <p>Corresponds to "Proposal agency" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Product#id}. Can be used to filter by {@link Product#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Product#name}. + <p>Corresponds to "Product" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link ProductTemplate#id}. Can be used to filter by + {@link ProductTemplate#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link ProductTemplate#name}. Can be used to filter by + {@link ProductTemplate#name}. + <p>Corresponds to "Product template" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link RateCard#id}. Can be used to filter by {@link + RateCard#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link RateCard#name}. Can be used to filter by {@link + RateCard#name}. + <p>Corresponds to "Rate card" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Used to filter by {@link Workflow#id}. Not available as a dimension to report on. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Used to filter by {@link Workflow#name}. Not available as a dimension to report on. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Package#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link Package#name}. + <p>Corresponds to "Package" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link ProductPackage#id}. Can be used to filter by + {@link ProductPackage#id}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by {@link ProductPackage#name}. Can be used to filter by + {@link ProductPackage#name}. + <p>Corresponds to "Product package" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by billable audience segment ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by billable audience segment name. + <p>Corresponds to "Audience segment (billable)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by audience segment data provider name. + <p>Corresponds to "Data partner" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange inventory size. + <p>Corresponds to "Inventory sizes" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange inventory size code. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange device category. + <p>Corresponds to "Device categories" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange pricing rule ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange pricing rule. + <p>Corresponds to "Pricing rules" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange tag. + <p>Corresponds to "Tags" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange URL. + <p>Corresponds to "URLs" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down data by Ad Exchange mapped web property code. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange creative size. + <p>Corresponds to "Creative sizes" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange ad type. + <p>Corresponds to "Ad Types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange channel. + <p>Corresponds to "Channels" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange product. + <p>Corresponds to "Products" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange product code. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange site. + <p>Corresponds to "Sites" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange request source. + <p>Corresponds to "Request sources" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by the Ad Exchange advertiser name that bids + on ads. + <p>Corresponds to "Advertisers" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by the Ad Exchange brand name that bids on + ads. + <p>Corresponds to "Brands" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange agency. + <p>Corresponds to "Agencies" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange bid type code. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange branding type code. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange branding type. Examples: + Branded, Anonymous. + <p>Corresponds to "Branding types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange ad network name. Example: + Google Adwords. + <p>Corresponds to "Buyer networks" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange ad network ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange custom channel code. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange custom channel ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange date, in Ad Exchange timezone. + + <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following + time zone types: + <ul> + <li> {@link TimeZoneType.AD_EXCHANGE} + </ul> + <p>Corresponds to "Days" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange deal id. + <p>Corresponds to "Deal IDs" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange deal name. + <p>Corresponds to "Deal names" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange deal/transaction type. Example: + Open auction. + <p>Corresponds to "Transaction types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange DSP buyer network name. + <p>Corresponds to "DSPs" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange expansion type. + <p>Corresponds to "Expandable types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange country code. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange country name. + <p>Corresponds to "Countries" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange DFP ad unit ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange DFP ad unit. + <p>Corresponds to "DFP Ad Units" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange inventory ownership. + <p>Corresponds to "Inventory ownership" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange advertiser domain. + <p>Corresponds to "Advertiser domains" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange mobile app name. + <p>Corresponds to "App names" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange mobile carrier name. + <p>Corresponds to "Carrier names" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange mobile device name. + <p>Corresponds to "Devices" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange mobile inventory type. + <p>Corresponds to "Inventory types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange month, in Ad Exchange timezone. + + <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following + time zone types: + <ul> + <li> {@link TimeZoneType.AD_EXCHANGE} + </ul> + <p>Corresponds to "Months" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange network partner name. + <p>Corresponds to "Network partner names" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange operating system version. + <p>Corresponds to "Operating systems" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange tags. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange targeting type code. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange targeting type. + <p>Corresponds to "Targeting types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange transaction type code + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange URL ID. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange user bandwidth. + <p>Corresponds to "Bandwidth" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange video ad duration. + <p>Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange raw video ad duration. + <p>Corresponds to "Video ad durations" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange video ad type. + <p>Corresponds to "Video ad types" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange week, in Ad Exchange timezone. + + <p><b>Note:</b> In v201802 and later, this dimension is compatible with the following + time zone types: + <ul> + <li> {@link TimeZoneType.AD_EXCHANGE} + </ul> + <p>Corresponds to "Weeks" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange ad location. + <p>Corresponds to "Ad locations" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Breaks down mapped Ad Exchange web property data by Ad Exchange advertiser vertical. + <p>Corresponds to "Advertiser verticals" in the DFP UI. Compatible with the AD_EXCHANGE_HISTORICAL report type.</p> + + + + + + + Campaign date segment of Nielsen Digital Ad Ratings reporting. + <p>Corresponds to "Nielsen Digital Ad Ratings segment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by gender and age group, i.e., MALE_18_TO_20, MALE_21_TO_24, + MALE_25_TO_29, MALE_30_TO_35, MALE_35_TO_39, MALE_40_TO_44, MALE_45_TO_49, MALE_50_TO_54, + MALE_55_TO_64, MALE_65_PLUS, FEMALE_18_TO_20, FEMALE_21_TO_24, FEMALE_25_TO_29, + FEMALE_30_TO_34, FEMALE_35_TO_39, FEMALE_40_TO_44, FEMALE_45_TO_49, FEMALE_50_TO_54, + FEMALE_55_TO_64, FEMALE_65_PLUS, and OTHER. + + + + + + + Data restatement date of Nielsen Digital Ad Ratings data. + <p>Corresponds to "Nielsen Digital Ad Ratings restatement date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH.</p> + + + + + + + Breaks down reporting data by {@link ProposalMarketplaceInfo#buyerAccountId}. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by programmatic buyer name. + <p>Corresponds to "Programmatic buyer" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by requested ad size(s). + This can be a chain of sizes or a single size. + <p>Corresponds to "Requested ad sizes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by the creative size the ad was delivered to. + <p>Corresponds to "Creative size (delivered)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by demand channels. + <p>Compatible with any of the following report types: HISTORICAL, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Breaks down reporting data by demand channel name. + <p>Corresponds to "Demand channel" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + + + {@code DimensionAttribute} provides additional fields associated with a + {@link Dimension}. It can only be selected with its corresponding + {@link Dimension}. For example, {@link DimensionAttribute#ORDER_PO_NUMBER} + can only be used if the {@link ReportQuery#dimensions} contains + {@link Dimension#ORDER_NAME}. + + + + + + + Represents {@link LineItem#effectiveAppliedLabels} as a comma separated list of + {@link Label#name} for {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Line item labels" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link LineItem#effectiveAppliedLabels} as a comma separated list of + {@link Label#id} for {@link Dimension#LINE_ITEM_NAME}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Generated as {@code true} for {@link Dimension#LINE_ITEM_NAME} which is eligible + for optimization, {@code false} otherwise. + Can be used for filtering. + <p>Corresponds to "Optimizable" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Indicates the progress made for the delivery of the {@link Dimension#LINE_ITEM_NAME}. + + <table> + <tr> + <th scope="col">Progress</th> <th scope="col">Definition</th> + </tr> + <tr> + <td>100%</td> + <td>The {@link LineItem} is on track to deliver in full as per + {@link LineItem#unitsBought}.</td> + </tr> + <tr> + <td>&gt; 100%</td> + <td>The {@link LineItem} is on track to overdeliver.</td> + </tr> + <tr> + <td>&lt; 100%</td> + <td>The {@link LineItem} is on track to underdeliver.</td> + </tr> + <tr> + <td>N/A</td> + <td>The {@link LineItem} does not have any quantity goals, or there is + insufficient information about the {@link LineItem}.</td> + </tr> + </table> + <p>Corresponds to "Delivery Indicator" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link LineItem#deliveryRateType} for {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Delivery pacing" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link LineItem#frequencyCaps} as a comma separated list of + "{@link FrequencyCap#maxImpressions} impressions per/every {@link FrequencyCap#numTimeUnits} + {@link FrequencyCap#timeUnit}" (e.g. "10 impressions every day,500 impressions per lifetime") + for {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Frequency cap" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the monthly reconciliation status of the line item for + {@link Dimension#LINE_ITEM_NAME} and {@link Dimension#MONTH_YEAR}. + <p>Corresponds to "Line item reconciliation status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL, PARTNER_FINANCE.</p> + + + + + + + Represents the monthly last reconciliation date time of the line item for + {@link Dimension#LINE_ITEM_NAME} and {@link Dimension#MONTH_YEAR}. + <p>Corresponds to "Line item last reconciliation time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL, PARTNER_FINANCE.</p> + + + + + + + Represents {@link Company#externalId} for {@link Dimension#ADVERTISER_NAME}. + <p>Corresponds to "External advertiser ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Company#type} for {@link Dimension#ADVERTISER_NAME}. + Can be used for filtering. + <p>Corresponds to "Advertiser type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Company#creditStatus} for {@link Dimension#ADVERTISER_NAME}. + Can be used for filtering. + <p>Corresponds to "Advertiser credit status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents name and email address in the form of name(email) of primary contact for {@link + Dimension#ADVERTISER_NAME}. + <p>Corresponds to "Advertiser primary contact" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the start date (in YYYY-MM-DD format) for {@link Dimension#ORDER_NAME}. + Can be used for filtering. + <p>Corresponds to "Order start date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the end date (in YYYY-MM-DD format) for {@link Dimension#ORDER_NAME}. + Can be used for filtering. + <p>Corresponds to "Order end date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Order#externalOrderId} for {@link Dimension#ORDER_NAME}. + <p>Corresponds to "External order ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Order#poNumber} for {@link Dimension#ORDER_NAME}. + Can be used for filtering. + <p>Corresponds to "Order PO number" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Order#orderIsProgrammatic} for {@link Dimension#ORDER_NAME}. + Can be used for filtering. + <p>Corresponds to "Programmatic order" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the name of {@link Order#agencyId} for {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Agency" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Order#agencyId} for {@link Dimension#ORDER_NAME}. + Can be used for filtering. + <p>Corresponds to "Agency ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Order#effectiveAppliedLabels} as a comma separated list of + {@link Label#name} for {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Order labels" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Order#effectiveAppliedLabels} as a comma separated list of + {@link Label#id} for {@link Dimension#ORDER_NAME}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The name and email address in the form of name(email) of the trafficker for + {@link Dimension#ORDER_NAME} + <p>Corresponds to "Trafficker" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Order#traffickerId} for {@link Dimension#ORDER_NAME}. + Can be used for filtering. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The names and email addresses as a comma separated list of name(email) of the + {@link Order#secondaryTraffickerIds} for {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Secondary traffickers" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The name and email address in the form of name(email) of the + {@link Order#salespersonId} for {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Salesperson" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The names and email addresses as a comma separated list of name(email) of the + {@link Order#secondarySalespersonIds} for {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Secondary salespeople" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The total number of impressions delivered over the lifetime of an + {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Order lifetime impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The total number of clicks delivered over the lifetime of an + {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Order lifetime clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The cost of booking all the CPM ads for {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Booked CPM" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The cost of booking all the CPC ads for {@link Dimension#ORDER_NAME}. + <p>Corresponds to "Booked CPC" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the start date (in YYYY-MM-DD format) for {@link Dimension#LINE_ITEM_NAME}. + Can be used for filtering. + <p>Corresponds to "Line item start date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the end date (in YYYY-MM-DD format) for {@link Dimension#LINE_ITEM_NAME}. + Can be used for filtering. + <p>Corresponds to "Line item end date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link LineItem#externalId} for {@link Dimension#LINE_ITEM_NAME}. + Can be used for filtering. + <p>Corresponds to "External Line Item ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link LineItem#costType} for {@link Dimension#LINE_ITEM_NAME}. + Can be used for filtering. + <p>Corresponds to "Cost type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link LineItem#costPerUnit} for {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the 3 letter currency code for {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Currency code" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The total number of impressions, clicks or days that is reserved + for {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Goal quantity" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The ratio between the goal quantity for {@link Dimension#LINE_ITEM_NAME} of + {@link LineItemType#SPONSORSHIP} and the {@link #LINE_ITEM_GOAL_QUANTITY}. + Represented as a number between 0..100. + <p>Corresponds to "Sponsorship goal (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The total number of impressions delivered over the lifetime of a + {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Line item lifetime impressions" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The total number of clicks delivered over the lifetime of a + {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Line item lifetime clicks" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link LineItem#priority} for {@link Dimension#LINE_ITEM_NAME} as + a value between 1 and 16. + Can be used for filtering. + <p>Corresponds to "Line item priority" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Indicates if a creative is a regular creative or creative set. + Values will be 'Creative' or 'Creative set' + <p>Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The type of creative in a creative set - master or companion. + <p>Corresponds to "Master or Companion" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link LineItem#contractedUnitsBought} quantity + for {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Contracted quantity" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link LineItem#discount} for {@link Dimension#LINE_ITEM_NAME}. + The number is either a percentage or an absolute value depending on + {@link LineItem#discountType}. + <p>Corresponds to "Discount" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + The cost of booking for a non-CPD {@link Dimension#LINE_ITEM_NAME}. + <p>Corresponds to "Booked revenue (exclude CPD)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Company#appliedLabels} as a comma separated list of + {@link Label#name} for {@link Dimension#ADVERTISER_NAME}. + <p>Corresponds to "Advertiser labels" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Company#appliedLabels} as a comma separated list of + {@link Label#id} for {@link Dimension#ADVERTISER_NAME}. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the click-through URL for {@link Dimension#CREATIVE_NAME}. + <p>Corresponds to "Click-through URL" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents whether a creative is SSL-compliant. + <p>Corresponds to "Creative SSL scan result" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents whether a creative's SSL status was overridden. + <p>Corresponds to "Creative SSL compliance override" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + Represents a {@link LineItemCreativeAssociation#startDateTime} for a + {@link Dimension#LINE_ITEM_NAME} and a {@link Dimension#CREATIVE_NAME}. + Includes the date without the time. + <p>Corresponds to "Creative start date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL, SELL_THROUGH, SALES.</p> + + + + + + + Represents a {@link LineItemCreativeAssociation#endDateTime} for a + {@link Dimension#LINE_ITEM_NAME} and a {@link Dimension#CREATIVE_NAME}. + Includes the date without the time. + <p>Corresponds to "Creative end date" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, DATA_LEAKAGE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL, SELL_THROUGH, SALES.</p> + + + + + + + Represents {@link Proposal#startDateTime} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Proposal start time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#endDateTime} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Proposal end time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#creationDateTime} for {@link Dimension#PROPOSAL_NAME}. Can be used + for filtering. + <p>Corresponds to "Creation time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the sold time for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Sold time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#isSold} for {@link Dimension#PROPOSAL_NAME}. Can be used for + filtering. + <p>Corresponds to "Sold" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#probabilityOfClose} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Probability of close" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#status} for {@link Dimension#PROPOSAL_NAME}. + This attribute includes post-sold statuses, e.g. DRAFT(SOLD) until v201611. + Starting from v201702, it will not include post-sold statuses. + Can be used for filtering. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents archival status for {@link Dimension#PROPOSAL_NAME}, the values are ARCHIVED + and NOT_ARCHIVED. Can be used for filtering. + <p>Corresponds to "Proposal archival status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#currency} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Currency" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#exchangeRate} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Exchange rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#agencyCommission} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Agency commission rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#valueAddedTax} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "VAT rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#proposalDiscount} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Proposal discount" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#advertiserDiscount} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Advertiser discount" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the advertiser name of {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Advertiser" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the advertiser id of {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Advertiser ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the agency names as a comma separated string for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Agencies" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the agency ids as a comma separated string for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Agency IDs" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#poNumber} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "PO number" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents name and email address in the form of name(email) of primary salesperson for + {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Salesperson" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents name and email addresses in the form of name(email) of secondary salespeople as a + comma separated string for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Secondary salespeople" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents name and email address in the form of name(email) of creator for {@link + Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Creator" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents name and email addresses in the form of name(email) of {@link + Proposal#salesPlannerIds} as a comma separated list string for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Sales planners" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#pricingModel} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Pricing model" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#billingSource} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Proposal billing source" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#billingCap} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Proposal caps and rollovers" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#billingSchedule} for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Proposal billing schedule" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#appliedTeamIds} as a comma separated list of {@link Team#name}s for + {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Teams" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the approval stage for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Approval stage" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the inventory release date time for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Inventory release time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#budget} in local currency for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Budget (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the remaining budget in local currency for {@link Dimension#PROPOSAL_NAME}. + <p>Corresponds to "Remaining budget (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents whether the {@link Proposal#billingBase} is {@link BillingBase#REVENUE}. + <p>Corresponds to "Proposal flat fee" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Proposal#isProgrammatic} for {@link Dimension#PROPOSAL_NAME}. Not available + as an attribute to report on, but exists as an attribute for filtering using PQL. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#startDateTime} for + {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Proposal line item start time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#endDateTime} for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Proposal line item end time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#rateType} for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + Can be used for filtering. + <p>Corresponds to "Proposal line item rate type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the reservation status of {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. Can be used for + filtering. + <p>Corresponds to "Reservation status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#costPerUnit} for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Rate (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#costPerUnit} in local currency for + {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + + See {@link #PROPOSAL_LINE_ITEM_COST_PER_UNIT} + <p>Can correspond to any of the following in the DFP UI: Rate (local), Rate (net) (local). Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents gross cost per unit for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Rate (gross)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents gross cost per unit in local currency for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + + See {@link #PROPOSAL_LINE_ITEM_COST_PER_UNIT_GROSS} + <p>Corresponds to "Rate (gross) (local)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents line item type (if applicable) and line item priority (if applicable) for + {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Proposal line item type / priority" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the size of {@link ProposalLineItem#creativePlaceholders} + for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Sizes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents archival status for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}, the values are + ARCHIVED and NOT_ARCHIVED. Can be used for filtering. + <p>Corresponds to "Proposal line item archival status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the product adjustment of {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Product adjustment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#contractedQuantityBuffer} for + {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Buffer (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the listing rate (net) of {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Listing rate (net)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#billingSource} for + {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Proposal line item billing source" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#billingCap} for {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Proposal line item caps and rollovers" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#billingSchedule} for + {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Proposal line item billing schedule" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Goal#units} of {@link ProposalLineItem#goal} for {@link + Dimension#PROPOSAL_LINE_ITEM_NAME} The attribute is available only if {@link + ProposalLineItem#lineItemType} is of type {@link LineItemType#SPONSORSHIP}, {@link + LineItemType#HOUSE}, {@link LineItemType#NETWORK}, or {@link LineItemType#BUMPER}. + <p>Corresponds to "Goal (%)" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProposalLineItem#costAdjustment} for {@link + Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Cost adjustment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link ProposalLineItem#notes comments} for {@link + Dimension#PROPOSAL_LINE_ITEM_NAME}. + <p>Corresponds to "Proposal line item comments" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the monthly reconciliation status of the proposal line item for + {@link Dimension#PROPOSAL_LINE_ITEM_NAME} and {@link Dimension#MONTH_YEAR}. + <p>Corresponds to "Proposal line item reconciliation status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL, PARTNER_FINANCE.</p> + + + + + + + Represents the monthly last reconciliation date time of the proposal line item for + {@link Dimension#PROPOSAL_LINE_ITEM_NAME} and {@link Dimension#MONTH_YEAR}. + <p>Corresponds to "Proposal line item last reconciliation time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL, PARTNER_FINANCE.</p> + + + + + + + Represents whether the {@link ProposalLineItem#billingBase} is {@link BillingBase#REVENUE}. + <p>Corresponds to "Proposal line item flat fee" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the corresponding product package item's archival status of + {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. Not available as an attribute + to report on, but exists as an attribute for filtering using PQL. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link ProposalLineItem#lineItemType} of + {@link Dimension#PROPOSAL_LINE_ITEM_NAME}. Only used for filtering. + <p>Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProductTemplate#rateType} for {@link Dimension#PRODUCT_TEMPLATE_NAME}. + <p>Corresponds to "Product template rate type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProductTemplate#status} for {@link Dimension#PRODUCT_TEMPLATE_NAME}. + <p>Corresponds to "Product template status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the line item type (if applicable) and line item priority + (if applicable) of {@link Dimension#PRODUCT_TEMPLATE_NAME}. + <p>Corresponds to "Product template type / priority" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProductTemplate#productType} for {@link Dimension#PRODUCT_TEMPLATE_NAME}. + <p>Corresponds to "Product template product type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProductTemplate#description} for {@link Dimension#PRODUCT_TEMPLATE_NAME}. + <p>Corresponds to "Description" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the product template's name of {@link Dimension#PRODUCT_NAME}. + <p>Corresponds to "Product template name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Product#rateType} for {@link Dimension#PRODUCT_NAME}. + <p>Corresponds to "Product rate type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Product#status} for {@link Dimension#PRODUCT_NAME}. + <p>Corresponds to "Product status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the line item type (if applicable) and line item priority + (if applicable) of {@link Dimension#PRODUCT_NAME}. + <p>Corresponds to "Product type / priority" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the product type of {@link Dimension#PRODUCT_NAME}. + <p>Corresponds to "Product product type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Product#notes} for {@link Dimension#PRODUCT_NAME}. + <p>Corresponds to "Product notes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Product#creativePlaceholders} for {@link Dimension#PRODUCT_NAME}. + <p>Corresponds to "Inventory sizes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link Dimension#PRODUCT_NAME}'s rate in a {@link Dimension#RATE_CARD_NAME}. + <p>Corresponds to "Product rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link Dimension#PRODUCT_NAME}'s rate in a {@link Dimension#RATE_CARD_NAME} + and {@link Dimension#PRODUCT_PACKAGE_NAME}. + <p>Corresponds to "Packaged product rate" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link Company#type} of {@link Dimension#PROPOSAL_AGENCY_NAME}. + <p>Corresponds to "Proposal agency type" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link Company#creditStatus} of {@link Dimension#PROPOSAL_AGENCY_NAME}. + <p>Corresponds to "Proposal agency credit status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Company#externalId} for {@link Dimension#PROPOSAL_AGENCY_NAME}. + <p>Corresponds to "External agency ID" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Company#comment} for {@link Dimension#PROPOSAL_AGENCY_NAME}. + <p>Corresponds to "Proposal agency comment" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link Dimension#ALL_SALESPEOPLE_NAME}'s contribution to a {@link + Dimension#PROPOSAL_NAME}. This is different from {@link #SALESPERSON_PROPOSAL_CONTRIBUTION} as + this will include both primary and secondary salespeople. + <p>Corresponds to "Salespeople proposal contribution" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL, SELL_THROUGH.</p> + + + + + + + Represents the {@link Dimension#SALESPERSON_NAME}'s contribution to a {@link + Dimension#PROPOSAL_NAME}. + + <p>See {@link #SALESPERSON_PROPOSAL_CONTRIBUTION}. + <p>Corresponds to "Salesperson proposal contribution" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, DATA_LEAKAGE, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProductPackage#notes} for {@link Dimension#PRODUCT_PACKAGE_NAME}. + <p>Corresponds to "Product package notes" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the products as a comma separated list of name for + {@link Dimension#PRODUCT_PACKAGE_NAME}. + <p>Corresponds to "Product package items" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link ProductPackage#status} for {@link Dimension#PRODUCT_PACKAGE_NAME}. + <p>Corresponds to "Product package status" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Package#comments} for {@link Dimension#PACKAGE_NAME}. + <p>Corresponds to "Package comments" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Package#startDateTime} for {@Dimension#PACKAGE_NAME}. + <p>Corresponds to "Package start time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link Package#endDateTime} for {@Dimension#PACKAGE_NAME}. + <p>Corresponds to "Package end time" in the DFP UI. Compatible with any of the following report types: HISTORICAL, REACH, SALES, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link CmsContent#displayName} within the first element of + {@link Content#cmsContent} for {@link Dimension#CONTENT_NAME}. + <p>Corresponds to "Content source name" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Represents the {@link CmsContent#cmsContentId} within the first element of + {@link Content#cmsContent} for {@link Dimension#CONTENT_NAME}. + <p>Corresponds to "ID of the video in the content source" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SAMPLED_HISTORICAL.</p> + + + + + + + Represents {@link AdUnit#adUnitCode} for {@link Dimension#AD_UNIT_NAME}. + <p>Corresponds to "Ad unit code" in the DFP UI. Compatible with any of the following report types: HISTORICAL, SELL_THROUGH, REACH, SALES, BUSINESS_INTELLIGENCE, DFP_HISTORICAL_DATA_STUDIO, SAMPLED_HISTORICAL.</p> + + + + + + + + + The file formats available for creating the report. + + + + + + + The report file is generated as a list of Tab Separated Values. + + + + + + + The report file is generated as a list of tab-separated values for Excel. + + + + + + + The report file is generated as a list of Comma Separated Values, + to be used with automated machine processing. + <p> + <ul> + <li>There is no pretty printing for the output, and no total row.</li> + <li>Column headers are the qualified name e.g. "Dimension.ORDER_NAME".</li> + <li>Network currency Monetary amounts are represented as micros in the + {@link Network#currencyCode currency of the network}.</li> + <li>Starting from v201705, local currency Monetary amounts are represented + as currency symbol + ' ' + micros. </li> + <li>Dates are formatted according to the ISO 8601 standard YYYY-MM-DD</li> + <li>DateTimes are formatted according to the ISO 8601 standard + YYYY-MM-DDThh:mm:ss[+-]hh:mm</li> + </ul> + + + + + + + The report file is generated as XML. + + + + + + + The report file is generated as an Office Open XML spreadsheet + designed for Excel 2007+. + + + + + + + + + + + A feature is being used that is not enabled on the current network. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + The single reason for the internal API error. + + + + + + + API encountered an unexpected internal error. + + + + + + + A temporary error occurred during the request. Please retry. + + + + + + + The cause of the error is not known or only defined in newer versions. + + + + + + + The API is currently unavailable for a planned downtime. + + + + + + + Mutate succeeded but server was unable to build response. Client should not retry mutate. + + + + + + + + + The reasons for the target error. + + + + + + + Assuming that a method will not have more than 3 arguments, if it does, + return NULL + + + + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + The reasons for the target error. + + + + + + + Indicates an error in parsing an attribute. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + Describes reasons for permission errors. + + + + + + + User does not have the required permission for the request. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + The reasons for the target error. + + + + + + + Indicates that there was an error executing the PQL. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + The reasons for the target error. + + + + + + + Indicates that there was a PQL syntax error. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + + + The number of requests made per second is too high and has exceeded the + allowable limit. The recommended approach to handle this error is to wait + about 5 seconds and then retry the request. Note that this does not + guarantee the request will succeed. If it fails again, try increasing the + wait time. + <p>Another way to mitigate this error is to limit requests to 2 per second for + Small Business networks, or 8 per second for Premium networks. Once again + this does not guarantee that every request will succeed, but may help + reduce the number of times you receive this error. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + This user has exceeded the allowed number of new report requests per hour + (this includes both reports run via the UI and reports + run via {@link ReportService#runReportJob}). + The recommended approach to handle this error is to wait about 10 minutes + and then retry the request. Note that this does not guarantee the request + will succeed. If it fails again, try increasing the wait time. + <p>Another way to mitigate this error is to limit the number of new report + requests to 250 per hour per user. Once again, this does not guarantee that + every request will succeed, but may help reduce the number of times you + receive this error. + + + + + + + + + + + Default {@code ReportError} when the reason is not among any already + defined. + + + + + + + User does not have permission to access the report. + + + + + + + User does not have permission to view one or more {@link Dimension}. + + + + + + + User has no permission to view one or more attributes. + + + + + + + User does not have permission to view one or more {@link Column}. + + + + + + + The user has exceeded the limit on the number of reports that can be run + concurrently. The current limit is 30 per user. + + + + + + + The report query exceeds the maximum allowed number of characters. + + + + + + + Invalid report job state for the given operation. + + + + + + + Invalid {@link Dimension} objects specified. + + + + + + + The attribute ID(s) are not valid. + + + + + + + The API error when running the report with {@link ContentHierarchyDimension}. There are three + reasons for this error. + <ol> + <li>{@link ReportQuery#dimensions} contains {@link Dimension#CONTENT_HIERARCHY}, but + {@link ReportQuery#contentMetadataHierarchyCustomTargetingKeyIds} is empty.</li> + + <li>{@link ReportQuery#contentMetadataHierarchyCustomTargetingKeyIds} is non-empty, but + {@link ReportQuery#dimensions} does not contain {@link Dimension#CONTENT_HIERARCHY}.</li> + + <li>The {@link ReportQuery#contentMetadataKeyHierarchyCustomTargetingKeyIds} specified along + with the {@link Dimension#CONTENT_HIERARCHY} are not valid, i.e., these IDs are not defined + in the content hierarchy by the publisher.</li> + </ol> + + + + + + + Invalid {@link Column} objects specified. + + + + + + + Invalid {@link DimensionFilter} objects specified. + + + + + + + Invalid date. + + + + + + + The start date for running the report should not be later than the end + date. + + + + + + + The start date for running the report should not be more than + three years before now. + + + + + + + The list of {@link Dimension} and {@link Column} objects cannot be empty. + + + + + + + Attribute has to be selected in combination with dimensions. + + + + + + + The provided report violates one or more constraints, which govern incompatibilities and + requirements between different report properties. Some reasons for constraint violations + include: + <ul> + <li> Not all {@link Column} objects requested are supported for the given set + of {@link Dimension} objects. + <li> The report's date range is not compatible with the given set of {@link Column} + objects. + <li> The report's {@link TimeZoneType} is not compatible with the given set of + {@link Column} and {@link Dimension} objects (version 201802 and later). + <li> The report's currency is not compatible with the given set of {@link Column} objects + (version 201802 and later). + </ul> + + + + + + + Failed to store/cache a report. + + + + + + + The requested report does not exist. + + + + + + + User has no permission to view in another network. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + Represents the status of a {@link ReportJob} running on the server. + + + + + + + The {@link ReportJob} has completed successfully and is ready to download. + + + + + + + The {@link ReportJob} is still being executed. + + + + + + + The {@link ReportJob} has failed to run to completion. + + + + + + + + + + + A required collection is missing. + + + + + + + Collection size is too large. + + + + + + + Collection size is too small. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + The reasons for the target error. + + + + + + + Missing required field. + + + + + + + + + Describes reasons for server errors + + + + + + + Indicates that an unexpected error occured. + + + + + + + Indicates that the server is currently experiencing a high load. Please + wait and try your request again. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + + + A bind variable has not been bound to a value. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + The reasons for the target error. + + + + + + + + The input string value contains disallowed characters. + + + + + + + The input string value is invalid for the associated field. + + + + + + + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + + + Enumerates all allowed time zones that can be used in reports. Note that some time zones are only + compatible with specific fields. + + + + + + + The value returned if the actual value is not exposed by the requested API version. + + + + + + + Use the proposal or proposal line item time zone. This time zone is only compatible with sales + metrics and attributes. + + <p>For example, if + {@link com.google.ads.publisher.api.service.reports.Column#SALES_CONTRACT_CONTRACTED_CLICKS} is + included in a report with this flag set to {@code true}, then it will be calculated using the + {@link ProposalLineItem#timeZoneId} of the proposal line item the metric is for. If + {@link com.google.ads.publisher.api.service.reports.DimensionAttribute#PROPOSAL_CREATION_DATE_TIME} + is included in a report with this flag set to {@code true}, then a proposal's creation date + time will be formatted in {@link Proposal#timeZoneId} of that proposal. + + + + + + + Use the publisher's time zone. For DFP reports, this time zone is compatible with all + metrics. For Ad Exchange reports, this time zone is not compatible with "Bids" and "Deals" + metrics. + + <p><b>Note:</b> if your report includes "time unit" dimensions, only the DFP "time unit" + dimensions are compatible with this timezone, e.g.: + <ul> + <li> {@link com.google.ads.publisher.api.service.reports.Dimension.DATE} + <li> {@link com.google.ads.publisher.api.service.reports.Dimension.WEEK} + <li> {@link com.google.ads.publisher.api.service.reports.Dimension.MONTH_AND_YEAR} + </ul> + + + + + + + Use the Ad Exchange time zone (Pacific Time Zone). This time zone is only compatible with + Ad Exchange metrics. + + <p><b>Note:</b> if your report includes "time unit" dimensions, only the Ad Exchange + "time unit" dimensions are compatible with this timezone, e.g.: + <ul> + <li> {@link com.google.ads.publisher.api.service.reports.Dimension.AD_EXCHANGE_DATE} + <li> {@link com.google.ads.publisher.api.service.reports.Dimension.AD_EXCHANGE_WEEK} + <li> {@link com.google.ads.publisher.api.service.reports.Dimension.AD_EXCHANGE_MONTH} + </ul> + + + + + + + + + Returns the URL at which the report file can be downloaded. + <p> + The report will be generated as a gzip archive, containing the report file itself. + + @param reportJobId the ID of the {@link ReportJob} + @param exportFormat the {@link ExportFormat} for the report file + @return the URL for report file download + + + + + + + + + + + + + + + + + + + + A fault element of type ApiException. + + + + + + + Returns the URL at which the report file can be downloaded, and allows for customization + of the downloaded report. + <p> + By default, the report will be generated as a gzip archive, containing the report file itself. + This can be changed by setting {@link ReportDownloadOptions#useGzipCompression} to false. + + @param reportJobId the ID of the {@link ReportJob} + @param reportDownloadOptions the {@link ReportDownloadOptions} for the request + @return the URL for report file download + + + + + + + + + + + + + + + + + + + + Returns the {@link ReportJobStatus} of the report job with the specified ID. + + + + + + + + + + + + + + + + + + + Retrieves a page of the saved queries either created by or shared with the current user. Each + {@link SavedQuery} in the page, if it is compatible with the current API version, will + contain a {@link ReportQuery} object which can be optionally modified and used to create a + {@link ReportJob}. This can then be passed to {@link ReportService#runReportJob}. + The following fields are supported for filtering: + + <table> + <tr> + <th scope="col">PQL Property</th> <th scope="col">Object Property</th> + </tr> + <tr> + <td>{@code id}</td> + <td>{@link SavedQuery#id}</td> + </tr> + <tr> + <td>{@code name}</td> + <td>{@link SavedQuery#name}</td> + </tr> + </table> + + @param filterStatement a Publisher Query Language statement used to filter which saved queries + should be returned. + @return a {@link SavedQueryPage} that contains all {@link SavedQuery} instances which satisfy + the given statement. + + + + + + + + + + + + + + + + + + + Initiates the execution of a {@link ReportQuery} on the server. + + <p>The following fields are required: + <ul> + <li>{@link ReportJob#reportQuery}</li> + </ul> + + @param reportJob the report job to run + @return the report job with its ID filled in + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Provides methods for executing a {@link ReportJob} and retrieving performance + and statistics about ad campaigns, networks, inventory and sales. + <p>Follow the steps outlined below:</p> + <p> + <ul> + <li>Create the {@code ReportJob} object by invoking + {@link ReportService#runReportJob}.</li> + <li>Poll the {@code ReportJob} object using + {@link ReportService#getReportJob}.</li> + <li>Continue to poll the {@code ReportJob} object until the + {@link ReportJob#reportJobStatus} field is equal to + {@link ReportJobStatus#COMPLETED} or {@link ReportJobStatus#FAILED}.</li> + <li>If successful, fetch the URL for downloading the report by invoking + {@link ReportService#getReportDownloadURL}.</li> + </ul> + </p> + + <h4>Test network behavior</h4> + + <p> + The networks created using {@link NetworkService#makeTestNetwork} are unable + to provide reports that would be comparable to the production environment + because reports require traffic history. + In the test networks, reports will consistently return no data for all reports. + </p> + + + + Returns the URL at which the report file can be downloaded. + <p> + The report will be generated as a gzip archive, containing the report file itself. + + @param reportJobId the ID of the {@link ReportJob} + @param exportFormat the {@link ExportFormat} for the report file + @return the URL for report file download + + + + + + + + Returns the URL at which the report file can be downloaded, and allows for customization + of the downloaded report. + <p> + By default, the report will be generated as a gzip archive, containing the report file itself. + This can be changed by setting {@link ReportDownloadOptions#useGzipCompression} to false. + + @param reportJobId the ID of the {@link ReportJob} + @param reportDownloadOptions the {@link ReportDownloadOptions} for the request + @return the URL for report file download + + + + + + + + Returns the {@link ReportJobStatus} of the report job with the specified ID. + + + + + + + + Retrieves a page of the saved queries either created by or shared with the current user. Each + {@link SavedQuery} in the page, if it is compatible with the current API version, will + contain a {@link ReportQuery} object which can be optionally modified and used to create a + {@link ReportJob}. This can then be passed to {@link ReportService#runReportJob}. + The following fields are supported for filtering: + + <table> + <tr> + <th scope="col">PQL Property</th> <th scope="col">Object Property</th> + </tr> + <tr> + <td>{@code id}</td> + <td>{@link SavedQuery#id}</td> + </tr> + <tr> + <td>{@code name}</td> + <td>{@link SavedQuery#name}</td> + </tr> + </table> + + @param filterStatement a Publisher Query Language statement used to filter which saved queries + should be returned. + @return a {@link SavedQueryPage} that contains all {@link SavedQuery} instances which satisfy + the given statement. + + + + + + + + Initiates the execution of a {@link ReportQuery} on the server. + + <p>The following fields are required: + <ul> + <li>{@link ReportJob#reportQuery}</li> + </ul> + + @param reportJob the report job to run + @return the report job with its ID filled in + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/test_data/empty_fault_response_envelope.txt b/tests/test_data/empty_fault_response_envelope.txt index 8b8ac82b..de942d40 100644 --- a/tests/test_data/empty_fault_response_envelope.txt +++ b/tests/test_data/empty_fault_response_envelope.txt @@ -1,6 +1,6 @@ - + 644a8c6efd398cf8643c29ff68fe574e 22 @@ -10,7 +10,7 @@ soap:Server [AuthenticationError.NETWORK_CODE_REQUIRED @ ] - + An error message without errors sibling tags diff --git a/tests/test_data/fault_response_envelope.txt b/tests/test_data/fault_response_envelope.txt index ecf77c26..4e2624ce 100644 --- a/tests/test_data/fault_response_envelope.txt +++ b/tests/test_data/fault_response_envelope.txt @@ -1,6 +1,6 @@ - + 644a8c6efd398cf8643c29ff68fe574e 22 @@ -10,7 +10,7 @@ soap:Server [AuthenticationError.NETWORK_CODE_REQUIRED @ ] - + [AuthenticationError.NETWORK_CODE_REQUIRED @ ] diff --git a/tests/test_data/multi_errors_fault_response_envelope.txt b/tests/test_data/multi_errors_fault_response_envelope.txt index 2ca18d4a..007df960 100644 --- a/tests/test_data/multi_errors_fault_response_envelope.txt +++ b/tests/test_data/multi_errors_fault_response_envelope.txt @@ -1,6 +1,6 @@ - + 644a8c6efd398cf8643c29ff68fe574e 22 @@ -10,7 +10,7 @@ soap:Server [Error 1, Error 2] - + Multiple errors occurred diff --git a/tests/testing.py b/tests/testing.py index 07d3f34c..2757a64e 100644 --- a/tests/testing.py +++ b/tests/testing.py @@ -15,6 +15,7 @@ """Functions and classes used for unit tests.""" +import functools import unittest import googleads.common @@ -30,3 +31,41 @@ class CleanUtilityRegistryTestCase(unittest.TestCase): def tearDown(self): """Ensures that the UtilityRegistry is cleared between tests.""" googleads.common._utility_registry.Clear() + +_SOAP_BACKENDS = ['suds', 'zeep'] + + +def _CreatePatchedSetUp(func): + """Create a setUp function that includes the SOAP implementation. + + Args: + func: A reference to the original setUp function. + + Returns: + The result of func called with soap_impl. + """ + @functools.wraps(func) + def SetUp(self): + soap_impl = 'suds' if '_suds' in str(self) else 'zeep' + return func(self, soap_impl) + return SetUp + + +def MultiBackendTest(cls): + """A decorator that patches a test suite to test with zeep and suds. + + Args: + cls: The test suite to patch + + Returns: + The patched suite. + """ + for name, func in list(cls.__dict__.items()): + if name.startswith('test'): + for backend in _SOAP_BACKENDS: + # Create a new test with _suds and _zeep + setattr(cls, '%s_%s' % (name, backend), func) + # Delete the original test + delattr(cls, name) + cls.setUp = _CreatePatchedSetUp(cls.setUp) + return cls diff --git a/tests/util_test.py b/tests/util_test.py index c11e8d1b..393ab815 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -14,28 +14,33 @@ """Unit tests to cover the errors module.""" +from contextlib import contextmanager import logging import os -import re import unittest -from xml.etree import ElementTree import googleads.adwords import googleads.dfp +import googleads.errors import googleads.util +from lxml import etree import mock import six import suds import suds.transport +from . import testing _HTTP_CLIENT_PATH = 'httplib' if six.PY2 else 'http.client' +@testing.MultiBackendTest class PatchesTest(unittest.TestCase): """Tests for the PatchHelper utility.""" - def setUp(self): + def setUp(self, soap_impl): + self.soap_impl = soap_impl + oauth_header = {'Authorization': 'header'} oauth2_client = mock.Mock() oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) @@ -46,18 +51,26 @@ def setUp(self): user_agent = '4M153rAb13p1l30F53CR37s' self.adwords_client = googleads.adwords.AdWordsClient( dev_token, oauth2_client, user_agent, - client_customer_id=client_customer_id) + client_customer_id=client_customer_id, soap_impl=soap_impl) # AdWordsClient setup (compression enabled) self.adwords_client_with_compression = googleads.adwords.AdWordsClient( dev_token, oauth2_client, user_agent, client_customer_id=client_customer_id, - enable_compression=True) + enable_compression=True, soap_impl=soap_impl) + self.adwords_version = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] + self.adwords_namespace_partial = ( + 'https://adwords.google.com/api/adwords/%s/' + self.adwords_version) # DfpClient setup network_code = '12345' application_name = 'application name' self.dfp_client = googleads.dfp.DfpClient( - oauth2_client, application_name, network_code) + oauth2_client, application_name, network_code, soap_impl=soap_impl) + + self.dfp_version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1] + self.dfp_namespace = ( + 'https://www.google.com/apis/ads/publisher/%s' + % self.dfp_version) def testPatchedSudsJurkoAppender(self): """Tests to confirm that the appender no longer removes empty objects.""" @@ -80,19 +93,16 @@ def testPatchedSudsJurkoAppender(self): statement = googleads.dfp.FilterStatement(query, values) line_item_service = self.dfp_client.GetService('LineItemService') - line_item_service.suds_client.set_options(nosend=True) + line_item_action = {'xsi_type': 'ActivateLineItems'} - # Perform the ActivateLineItems action. - request = line_item_service.performLineItemAction( - line_item_action, statement.ToStatement()).envelope - line_item_service.suds_client.set_options(nosend=False) - if six.PY3: - request = request.decode('utf-8') - # Strip namespace prefixes and parse. - parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) - line_item_action = parsed_request.find('Body').find('performLineItemAction') + request = line_item_service.GetRequestXML( + 'performLineItemAction', line_item_action, statement.ToStatement()) + + line_item_action = request.find( + './/{%s}lineItemAction' % self.dfp_namespace) + # Assert that the request includes the action. - self.assertTrue(line_item_action is not None) + self.assertIsNotNone(line_item_action) def testPatchedSudsJurkoAppenderIssue63(self): """Verifies that issue 63 has been resolved with the patch.""" @@ -118,20 +128,14 @@ def testPatchedSudsJurkoAppenderIssue63(self): }] adgroup_criterion_service = self.adwords_client.GetService( 'AdGroupCriterionService') - adgroup_criterion_service.suds_client.set_options(nosend=True) - request = adgroup_criterion_service.mutate(operations).envelope - adgroup_criterion_service.suds_client.set_options(nosend=False) - if six.PY3: - request = request.decode('utf-8') - # Strip namespace prefixes and parse. - parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) - operand = parsed_request.find('Body').find('mutate').find( - 'operations').find('operand') - final_mobile_urls = operand.find('finalMobileUrls') - final_urls = operand.find('finalUrls') + request = adgroup_criterion_service.GetRequestXML('mutate', operations) + final_mobile_urls = request.find('.//{%s}finalMobileUrls' % + self.adwords_namespace_partial % 'cm') + final_urls = request.find('.//{%s}finalUrls' % + self.adwords_namespace_partial % 'cm') # Assert that the request includes the empty urls. - self.assertTrue(final_mobile_urls is not None) - self.assertTrue(final_urls is not None) + self.assertIsNotNone(final_mobile_urls) + self.assertIsNotNone(final_urls) def testPatchedSudsJurkoAppenderIssue78(self): """Verifies that issue 78 has been resolved with the patch.""" @@ -139,20 +143,18 @@ def testPatchedSudsJurkoAppenderIssue78(self): # trackingUrl template. In the bug, this would be excluded from the output. customer = {'trackingUrlTemplate': '', 'xsi_type': 'Customer'} customer_service = self.adwords_client.GetService('CustomerService') - customer_service.suds_client.set_options(nosend=True) - request = customer_service.mutate(customer).envelope - customer_service.suds_client.set_options(nosend=False) - if six.PY3: - request = request.decode('utf-8') - # Strip namespace prefixes and parse. - parsed_request = ElementTree.fromstring(re.sub('ns[0-1]:', '', request)) - tracking_url_template = parsed_request.find('Body').find('mutate').find( - 'customer').find('trackingUrlTemplate') + request = customer_service.GetRequestXML('mutate', customer) + tracking_url_template = request.find( + './/{%s}trackingUrlTemplate' % self.adwords_namespace_partial % 'mcm') # Assert that the request includes the empty trackingUrlTemplate. - self.assertTrue(tracking_url_template is not None) + self.assertIsNotNone(tracking_url_template) def testSudsJurkoSendWithCompression(self): """Verifies that the patched HttpTransport.send can decode gzip response.""" + # Not applicable to zeep + if self.soap_impl == 'zeep': + return + test_dir = os.path.dirname(__file__) cs = self.adwords_client_with_compression.GetService('CampaignService') @@ -172,6 +174,10 @@ def testSudsJurkoSendWithCompression(self): def testSudsJurkoSendWithException(self): """Verifies that the patched HttpTransport.send can escalate HTTPError.""" + # Not applicable to zeep + if self.soap_impl == 'zeep': + return + test_dir = os.path.dirname(__file__) cs = self.adwords_client_with_compression.GetService('CampaignService') @@ -189,65 +195,69 @@ def testSudsJurkoSendWithException(self): url, code, msg, hdrs, handler) try: cs.get() - except suds.WebFault as e: + except googleads.errors.GoogleAdsServerFault as e: self.assertEqual( 'Unmarshalling Error: For input string: ' '"INSERT_ADVERTISER_COMPANY_ID_HERE" ', - e.fault.faultstring) - - def testSingleErrorListIssue90(self): - """Verifies that issue 90 has been resolved with the patch.""" - query = 'WHERE 1 = 0' - statement = googleads.dfp.FilterStatement(query) - line_item_service = self.dfp_client.GetService('LineItemService') - line_item_action = {'xsi_type': 'ActivateLineItems'} - st = statement.ToStatement() + str(e)) + @contextmanager + def mock_fault_response(self, response_file, version): test_dir = os.path.dirname(__file__) + with open(os.path.join(test_dir, response_file), 'rb') as handler: + response_data = handler.read() + if six.PY3: + response_data = response_data.replace( + b'{VERSION}', bytes(version, 'utf-8')) + else: + response_data = response_data.replace('{VERSION}', version) - with mock.patch('suds.transport.http.HttpTransport.send') as mock_send: - with open(os.path.join( - test_dir, 'test_data/fault_response_envelope.txt'), 'rb' - ) as handler: + if self.soap_impl == 'suds': + with mock.patch('suds.transport.http.HttpTransport.send') as mock_send: # Use a fake reply containing a fault SOAP response. reply_instance = mock.Mock() reply_instance.code = 500 reply_instance.headers = {} - reply_instance.message = handler.read() + reply_instance.message = response_data mock_send.return_value = reply_instance - try: - line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault as e: - errors = e.fault.detail.ApiExceptionFault.errors - self.assertIsInstance(errors, list) - self.assertEqual(1, len(errors)) + yield + else: + with mock.patch('zeep.transports.Transport.post') as mock_post: + reply_instance = mock.Mock() + reply_instance.status_code = 500 + reply_instance.headers = {} + reply_instance.content = response_data + mock_post.return_value = reply_instance + yield - def testSingleErrorListIssue90_emptyErrors(self): + def testSingleErrorListIssue90(self): """Verifies that issue 90 has been resolved with the patch.""" query = 'WHERE 1 = 0' statement = googleads.dfp.FilterStatement(query) line_item_service = self.dfp_client.GetService('LineItemService') line_item_action = {'xsi_type': 'ActivateLineItems'} st = statement.ToStatement() + with self.mock_fault_response( + 'test_data/fault_response_envelope.txt', self.dfp_version): + try: + line_item_service.performLineItemAction(line_item_action, st) + except googleads.errors.GoogleAdsServerFault as e: + self.assertEqual(1, len(e.errors)) - test_dir = os.path.dirname(__file__) + def testSingleErrorListIssue90_emptyErrors(self): + """Verifies that issue 90 has been resolved with the patch.""" + query = 'WHERE 1 = 0' + statement = googleads.dfp.FilterStatement(query) + line_item_service = self.dfp_client.GetService('LineItemService') + line_item_action = {'xsi_type': 'ActivateLineItems'} + st = statement.ToStatement() - with mock.patch('suds.transport.http.HttpTransport.send') as mock_send: - with open(os.path.join( - test_dir, 'test_data/empty_fault_response_envelope.txt'), 'rb' - ) as handler: - # Use a fake reply containing a fault SOAP response. - reply_instance = mock.Mock() - reply_instance.code = 500 - reply_instance.headers = {} - reply_instance.message = handler.read() - mock_send.return_value = reply_instance - try: - line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault as e: - errors = e.fault.detail.ApiExceptionFault.errors - self.assertIsInstance(errors, list) - self.assertEqual(0, len(errors)) + with self.mock_fault_response( + 'test_data/empty_fault_response_envelope.txt', self.dfp_version): + try: + line_item_service.performLineItemAction(line_item_action, st) + except googleads.errors.GoogleAdsServerFault as e: + self.assertEqual(0, len(e.errors)) def testSingleErrorListIssue90_multipleErrors(self): """Verifies that issue 90 has been resolved with the patch.""" @@ -257,24 +267,12 @@ def testSingleErrorListIssue90_multipleErrors(self): line_item_action = {'xsi_type': 'ActivateLineItems'} st = statement.ToStatement() - test_dir = os.path.dirname(__file__) - - with mock.patch('suds.transport.http.HttpTransport.send') as mock_send: - with open(os.path.join( - test_dir, 'test_data/multi_errors_fault_response_envelope.txt'), 'rb' - ) as handler: - # Use a fake reply containing a fault SOAP response. - reply_instance = mock.Mock() - reply_instance.code = 500 - reply_instance.headers = {} - reply_instance.message = handler.read() - mock_send.return_value = reply_instance - try: - line_item_service.performLineItemAction(line_item_action, st) - except suds.WebFault as e: - errors = e.fault.detail.ApiExceptionFault.errors - self.assertIsInstance(errors, list) - self.assertEqual(2, len(errors)) + with self.mock_fault_response( + 'test_data/multi_errors_fault_response_envelope.txt', self.dfp_version): + try: + line_item_service.performLineItemAction(line_item_action, st) + except googleads.errors.GoogleAdsServerFault as e: + self.assertEqual(2, len(e.errors)) class GoogleAdsCommonFilterTest(unittest.TestCase): @@ -341,9 +339,9 @@ def testFilterWithSudsClientHeadersMessage(self): record = mock.Mock() record.msg = 'headers = %s' record.args = {'Content-Type': 'text/xml; charset=utf-8', - 'Authorization': 'Bearer abc123doremi'} + 'authorization': 'Bearer abc123doremi'} expected_args = {'Content-Type': 'text/xml; charset=utf-8', - 'Authorization': self.redacted_text} + 'authorization': self.redacted_text} self.filter.filter(record) self.assertEqual(record.args, expected_args) @@ -536,11 +534,11 @@ def testGetSudsTransportFilter(self): def testFilterSudsTransportRequest(self): request_instance = suds.transport.Request('https://www.google.com') request_instance.headers = {'User-Agent': 'user-agent', - 'Authorization': 'abc123doremi'} + 'authorization': 'abc123doremi'} request_instance.message = (self.test_request_envelope_template % - self.dev_token_template) + self.dev_token_template).encode('utf-8') expected_headers = {'User-Agent': 'user-agent', - 'Authorization': self.redacted_text} + 'authorization': self.redacted_text} record = mock.Mock() record.args = (request_instance,) self.filter.filter(record) @@ -548,6 +546,130 @@ def testFilterSudsTransportRequest(self): self.assertEqual(record.args[0].message, self.test_request_envelope_template % self.redacted_text) +XML_WITH_DEV_TOKEN = ( + '' + 'a token' + 'hi' + '') +XML_WITH_DEV_TOKEN_SAFE = etree.fromstring( + XML_WITH_DEV_TOKEN.replace('a token', 'REDACTED')) +XML_WITH_DEV_TOKEN = etree.fromstring(XML_WITH_DEV_TOKEN) +XML_PRETTY = etree.tostring(XML_WITH_DEV_TOKEN, pretty_print=True) +XML_PRETTY_SAFE = etree.tostring(XML_WITH_DEV_TOKEN_SAFE, pretty_print=True) +if six.PY3: + XML_PRETTY_SAFE = XML_PRETTY_SAFE.decode('utf-8') +XML_WITH_FAULT = etree.fromstring( + '' + '' + 'value' + '' + '' + 'hi' + '' + '') + +ZEEP_HEADER = {'abc': 'hi', 'authorization': 'secret'} +ZEEP_HEADER_SAFE = ZEEP_HEADER.copy() +ZEEP_HEADER_SAFE['authorization'] = 'REDACTED' +BINDING_OPTIONS = {'address': 'myaddress'} + + +class ZeepLoggerTest(unittest.TestCase): + + def setUp(self): + self.logger = mock.Mock() + self.zeep_logger = googleads.util.ZeepLogger() + self.zeep_logger._logger = self.logger + self.operation = mock.Mock() + self.operation.name = 'opname' + if six.PY2: + self.operation.binding.wsdl.services.keys.return_value = ['service_name'] + else: + self.operation.binding.wsdl.services.keys.return_value = ( + iter(['service_name'])) + + def enable_log_levels(self, *levels): + self.logger.isEnabledFor.side_effect = lambda lvl: lvl in levels + + def testIngressPassesThroughArguments(self): + self.enable_log_levels() + + # This result isn't related to logging, just confirming that the plugin + # is passing along the data unmodified. + result = self.zeep_logger.ingress( + XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation) + + self.assertEqual(result, (XML_WITH_DEV_TOKEN, ZEEP_HEADER)) + + def testIngressNoLoggingByDefault(self): + self.enable_log_levels() + + self.zeep_logger.ingress( + XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation) + + self.logger.debug.assert_not_called() + + def testIngressDebugLogging(self): + self.enable_log_levels(logging.DEBUG) + + # Re-using the XML with for convenience, but this + # is testing inbound data, which would not have anything sensitive in it. + self.zeep_logger.ingress( + XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation) + + self.logger.debug.assert_called_once_with( + googleads.util._RESPONSE_XML_LOG_LINE, XML_PRETTY) + + def testIngressFaultLogging(self): + self.enable_log_levels(logging.WARN) + + self.zeep_logger.ingress( + XML_WITH_FAULT, ZEEP_HEADER, self.operation) + + self.assertEqual({'faultMessage': 'hi', + 'key': 'value', + 'methodName': 'opname', + 'serviceName': 'service_name'}, + self.logger.warn.mock_calls[0][1][1]) + + def testEgressPassesThroughArguments(self): + self.enable_log_levels() + + self.enable_log_levels(logging.DEBUG) + + # This result isn't related to logging, just confirming that the plugin + # is passing along the data unmodified. + result = self.zeep_logger.egress( + XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS) + + self.assertEqual(result, (XML_WITH_DEV_TOKEN, ZEEP_HEADER)) + + def testEgressNoLoggingByDefault(self): + self.enable_log_levels() + + self.zeep_logger.egress( + XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS) + + self.logger.debug.assert_not_called() + + def testEgressDebugLogging(self): + self.enable_log_levels(logging.DEBUG) + self.zeep_logger.egress( + XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS) + + # With egress, they should be redacted. + self.logger.debug.assert_called_once_with( + googleads.util._REQUEST_XML_LOG_LINE, ZEEP_HEADER_SAFE, XML_PRETTY_SAFE) + + def testEgressInfoLogging(self): + + self.enable_log_levels(logging.INFO) + self.zeep_logger.egress( + XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS) + + self.logger.info.assert_called_once_with( + googleads.util._REQUEST_LOG_LINE, 'service_name', 'opname', 'myaddress') + if __name__ == '__main__': unittest.main() From b93ae8e74f48407df13c9f32f0e5af703c5789c3 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 28 Mar 2018 16:29:57 -0400 Subject: [PATCH 105/180] Commiting latest changes. From aeb11762ca1b5e8267a3b2f2317b523c5aa8cf2f Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Fri, 6 Apr 2018 15:51:37 -0400 Subject: [PATCH 106/180] Committing latest changes. --- ChangeLog | 5 + README.md | 3 +- .../optimization/estimate_keyword_traffic.py | 6 +- .../optimization/estimate_keyword_traffic.py | 6 +- .../activate_live_stream_events.py | 71 + .../create_live_stream_events.py | 68 + .../get_all_live_stream_events.py | 52 + .../register_sessions_for_monitoring.py | 45 + .../update_live_stream_events.py | 69 + .../activate_live_stream_events.py | 71 + .../create_live_stream_events.py | 68 + .../get_all_live_stream_events.py | 52 + .../register_sessions_for_monitoring.py | 45 + .../update_live_stream_events.py | 69 + .../activate_live_stream_events.py | 71 + .../create_live_stream_events.py | 68 + .../get_all_live_stream_events.py | 52 + .../register_sessions_for_monitoring.py | 45 + .../update_live_stream_events.py | 69 + googleads/common.py | 16 +- tests/common_test.py | 20 + tests/test_data/traffic_estimator_service.xml | 3313 +++++++++++++++++ 22 files changed, 4276 insertions(+), 8 deletions(-) create mode 100755 examples/dfp/v201708/live_stream_event_service/activate_live_stream_events.py create mode 100755 examples/dfp/v201708/live_stream_event_service/create_live_stream_events.py create mode 100755 examples/dfp/v201708/live_stream_event_service/get_all_live_stream_events.py create mode 100755 examples/dfp/v201708/live_stream_event_service/register_sessions_for_monitoring.py create mode 100755 examples/dfp/v201708/live_stream_event_service/update_live_stream_events.py create mode 100755 examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py create mode 100755 examples/dfp/v201711/live_stream_event_service/create_live_stream_events.py create mode 100755 examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py create mode 100755 examples/dfp/v201711/live_stream_event_service/register_sessions_for_monitoring.py create mode 100755 examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py create mode 100755 examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py create mode 100755 examples/dfp/v201802/live_stream_event_service/create_live_stream_events.py create mode 100755 examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py create mode 100755 examples/dfp/v201802/live_stream_event_service/register_sessions_for_monitoring.py create mode 100755 examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py create mode 100644 tests/test_data/traffic_estimator_service.xml diff --git a/ChangeLog b/ChangeLog index 8613c576..31f4bdd8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +11.0.1 -- 04/06/18 +* Fixed bug related to creating types from services that + contain multiple schemas. +* Fixed bug in README.md related to zeep caching. + 11.0.0 -- 03/21/18 * Removed support and examples for AdWords v201705, and v201708. * The default SOAP backend is now zeep. If you encounter any issues, diff --git a/README.md b/README.md index 147dcd43..254ee506 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,8 @@ You can also disable caching in similar fashion with zeep ```python adwords_client = adwords.AdWordsClient( developer_token, oauth2_client, user_agent, - client_customer_id=client_customer_id, cache=None) + client_customer_id=client_customer_id, + cache=googleads.common.ZeepServiceProxy.NO_CACHE) ``` And with suds: diff --git a/examples/adwords/v201710/optimization/estimate_keyword_traffic.py b/examples/adwords/v201710/optimization/estimate_keyword_traffic.py index 0b96d72a..5250262e 100755 --- a/examples/adwords/v201710/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201710/optimization/estimate_keyword_traffic.py @@ -157,10 +157,12 @@ def DisplayEstimate(message, min_estimate, max_estimate): # Find the mean of the min and max values. mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate else None) + if 'averageCpc' in min_estimate + and min_estimate['averageCpc'] else None) mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], max_estimate['averagePosition']) - if 'averagePosition' in min_estimate else None) + if 'averagePosition' in min_estimate + and min_estimate['averagePosition'] else None) mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], max_estimate['clicksPerDay']) mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], diff --git a/examples/adwords/v201802/optimization/estimate_keyword_traffic.py b/examples/adwords/v201802/optimization/estimate_keyword_traffic.py index 28465e7a..1d9575ac 100755 --- a/examples/adwords/v201802/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201802/optimization/estimate_keyword_traffic.py @@ -157,10 +157,12 @@ def DisplayEstimate(message, min_estimate, max_estimate): # Find the mean of the min and max values. mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate else None) + if 'averageCpc' in min_estimate + and min_estimate['averageCpc'] else None) mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], max_estimate['averagePosition']) - if 'averagePosition' in min_estimate else None) + if 'averagePosition' in min_estimate + and min_estimate['averagePosition'] else None) mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], max_estimate['clicksPerDay']) mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], diff --git a/examples/dfp/v201708/live_stream_event_service/activate_live_stream_events.py b/examples/dfp/v201708/live_stream_event_service/activate_live_stream_events.py new file mode 100755 index 00000000..fa0a8f2a --- /dev/null +++ b/examples/dfp/v201708/live_stream_event_service/activate_live_stream_events.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example activates paused live stream events.""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the LiveStreamEvent to get live stream events from. +LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' + + +def main(client, live_stream_event_id): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201708') + + # Create query to find paused live stream events. + statement = (dfp.StatementBuilder() + .Where(('id = :id AND ' + 'status = :status')) + .WithBindVariable('status', 'PAUSED') + .WithBindVariable('id', long(live_stream_event_id)) + .Limit(500)) + + live_stream_events_activated = 0 + + # Get live stream events by statement. + while True: + response = live_stream_event_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + if 'results' in response: + for live_stream_event in response['results']: + print('live stream event with id "%s" and name "%s" will be activated.' + % (live_stream_event['id'], live_stream_event['name'])) + + # Perform action. + result = live_stream_event_service.performLiveStreamEventAction({ + 'xsi_type': 'ActivateLiveStreamEvents' + }, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + live_stream_events_activated += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if live_stream_events_activated > 0: + print '# of live stream events activated: %s' % ( + live_stream_events_activated) + else: + print 'No live stream events were activated.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201708/live_stream_event_service/create_live_stream_events.py b/examples/dfp/v201708/live_stream_event_service/create_live_stream_events.py new file mode 100755 index 00000000..5ce194c3 --- /dev/null +++ b/examples/dfp/v201708/live_stream_event_service/create_live_stream_events.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example creates new live stream events. + +To determine which live stream events exist, run get_all_live_stream_events.py. +To determine which cdn configurations exist, run get_cdn_configurations.py. +""" + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp +import pytz + +# Set content urls and adTags to use +CONTENT_URLS = ['INSERT_CONTENT_URLS_HERE'] +AD_TAGS = ['INSERT_AD_TAGS_HERE'] + + +def main(client, content_urls, ad_tags): + # Initialize appropriate services. + live_events_service = client.GetService( + 'LiveStreamEventService', version='v201708') + + # Stream will play for 365 days + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + + # Create live stream event objects + live_stream_events = [{ + 'name': 'Live Stream Event #%s' % uuid.uuid4(), + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, + 'contentUrls': content_urls, + 'adTags': ad_tags + }] + + # Add live stream events. + live_stream_events = live_events_service.createLiveStreamEvents( + live_stream_events) + + # Display results. + for live_stream_event in live_stream_events: + print( + 'Live stream event with id "%s", named "%s" and status %s was created.' + % (live_stream_event['id'], live_stream_event['name'], + live_stream_event['status'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, CONTENT_URLS, AD_TAGS) diff --git a/examples/dfp/v201708/live_stream_event_service/get_all_live_stream_events.py b/examples/dfp/v201708/live_stream_event_service/get_all_live_stream_events.py new file mode 100755 index 00000000..a6eccb88 --- /dev/null +++ b/examples/dfp/v201708/live_stream_event_service/get_all_live_stream_events.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 live stream events. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201708') + + # Create a statement to select live stream events. + statement = dfp.StatementBuilder() + + # Retrieve a small amount of live stream events at a time, paging + # through until all live stream events have been retrieved. + while True: + response = live_stream_event_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + if 'results' in response: + for live_stream_event in response['results']: + # Print out some information for each live stream event. + print('live stream event with id "%d" and name "%s" was found.' % + (live_stream_event['id'], live_stream_event['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/live_stream_event_service/register_sessions_for_monitoring.py b/examples/dfp/v201708/live_stream_event_service/register_sessions_for_monitoring.py new file mode 100755 index 00000000..906ff712 --- /dev/null +++ b/examples/dfp/v201708/live_stream_event_service/register_sessions_for_monitoring.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 registers all live stream event-sessions ids for monitoring.""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# List of session ids +SESSION_IDS = ['INSERT_SESSION_IDS_HERE'] + + +def main(client, session_ids): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201708') + + # Retrieve all sessions id that are being monitored + session_ids = live_stream_event_service.registerSessionsForMonitoring( + session_ids) + if session_ids: + for session_id in session_ids: + # Print out some information for each live stream event. + print 'Session with ID "%s" registered for monitoring.' % (session_id) + + print '\nNumber of results found: %s' % session_ids.size + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, SESSION_IDS) diff --git a/examples/dfp/v201708/live_stream_event_service/update_live_stream_events.py b/examples/dfp/v201708/live_stream_event_service/update_live_stream_events.py new file mode 100755 index 00000000..3bae28dd --- /dev/null +++ b/examples/dfp/v201708/live_stream_event_service/update_live_stream_events.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example updates live stream events. + +To determine which live stream events exist, run get_all_live_stream_events.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set ID of the LiveStreamEvent to get live stream events from. +LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' + + +def main(client, live_stream_event_id): + # Initialize appropriate services. + live_stream_events_service = client.GetService( + 'LiveStreamEventService', version='v201708') + + # Create statement object to only select matching live stream event. + statement = (dfp.StatementBuilder() + .Where(('Id = :id')) + .WithBindVariable('id', long(live_stream_event_id)) + .Limit(500)) + + # Get live stream events by statement. + response = live_stream_events_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + + # Set adTags to be updated. + new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE'] + + if 'results' in response: + # Update each local live stream event by changing its attributes. + updated_live_stream_events = [] + for live_stream_event in response['results']: + live_stream_event['startDateTimeType'] = 'IMMEDIATELY' + live_stream_event['adTags'] = new_ad_tags + updated_live_stream_events.append(live_stream_event) + + # Update live stream events. + live_stream_events = live_stream_events_service.updateLiveStreamEvents( + updated_live_stream_events) + + # Display results. + for live_stream_event in live_stream_events: + print('Live stream event with id "%s", named "%s" and status %s was ' + 'updated.' % (live_stream_event['id'], live_stream_event['name'], + live_stream_event['status'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py b/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py new file mode 100755 index 00000000..6074664b --- /dev/null +++ b/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example activates paused live stream events.""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the LiveStreamEvent to get live stream events from. +LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' + + +def main(client, live_stream_event_id): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201711') + + # Create query to find paused live stream events. + statement = (dfp.StatementBuilder() + .Where(('id = :id AND ' + 'status = :status')) + .WithBindVariable('status', 'PAUSED') + .WithBindVariable('id', long(live_stream_event_id)) + .Limit(500)) + + live_stream_events_activated = 0 + + # Get live stream events by statement. + while True: + response = live_stream_event_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + if 'results' in response: + for live_stream_event in response['results']: + print('live stream event with id "%s" and name "%s" will be activated.' + % (live_stream_event['id'], live_stream_event['name'])) + + # Perform action. + result = live_stream_event_service.performLiveStreamEventAction({ + 'xsi_type': 'ActivateLiveStreamEvents' + }, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + live_stream_events_activated += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if live_stream_events_activated > 0: + print '# of live stream events activated: %s' % ( + live_stream_events_activated) + else: + print 'No live stream events were activated.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201711/live_stream_event_service/create_live_stream_events.py b/examples/dfp/v201711/live_stream_event_service/create_live_stream_events.py new file mode 100755 index 00000000..d8769d38 --- /dev/null +++ b/examples/dfp/v201711/live_stream_event_service/create_live_stream_events.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example creates new live stream events. + +To determine which live stream events exist, run get_all_live_stream_events.py. +To determine which cdn configurations exist, run get_cdn_configurations.py. +""" + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp +import pytz + +# Set content urls and adTags to use +CONTENT_URLS = ['INSERT_CONTENT_URLS_HERE'] +AD_TAGS = ['INSERT_AD_TAGS_HERE'] + + +def main(client, content_urls, ad_tags): + # Initialize appropriate services. + live_events_service = client.GetService( + 'LiveStreamEventService', version='v201711') + + # Stream will play for 365 days + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + + # Create live stream event objects + live_stream_events = [{ + 'name': 'Live Stream Event #%s' % uuid.uuid4(), + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, + 'contentUrls': content_urls, + 'adTags': ad_tags + }] + + # Add live stream events. + live_stream_events = live_events_service.createLiveStreamEvents( + live_stream_events) + + # Display results. + for live_stream_event in live_stream_events: + print( + 'Live stream event with id "%s", named "%s" and status %s was created.' + % (live_stream_event['id'], live_stream_event['name'], + live_stream_event['status'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, CONTENT_URLS, AD_TAGS) diff --git a/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py b/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py new file mode 100755 index 00000000..9154377a --- /dev/null +++ b/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 live stream events. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201711') + + # Create a statement to select live stream events. + statement = dfp.StatementBuilder() + + # Retrieve a small amount of live stream events at a time, paging + # through until all live stream events have been retrieved. + while True: + response = live_stream_event_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + if 'results' in response: + for live_stream_event in response['results']: + # Print out some information for each live stream event. + print('live stream event with id "%d" and name "%s" was found.' % + (live_stream_event['id'], live_stream_event['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201711/live_stream_event_service/register_sessions_for_monitoring.py b/examples/dfp/v201711/live_stream_event_service/register_sessions_for_monitoring.py new file mode 100755 index 00000000..7a155778 --- /dev/null +++ b/examples/dfp/v201711/live_stream_event_service/register_sessions_for_monitoring.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 registers all live stream event-sessions ids for monitoring.""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# List of session ids +SESSION_IDS = ['INSERT_SESSION_IDS_HERE'] + + +def main(client, session_ids): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201711') + + # Retrieve all sessions id that are being monitored + session_ids = live_stream_event_service.registerSessionsForMonitoring( + session_ids) + if session_ids: + for session_id in session_ids: + # Print out some information for each live stream event. + print 'Session with ID "%s" registered for monitoring.' % (session_id) + + print '\nNumber of results found: %s' % session_ids.size + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, SESSION_IDS) diff --git a/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py b/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py new file mode 100755 index 00000000..95653f6f --- /dev/null +++ b/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example updates live stream events. + +To determine which live stream events exist, run get_all_live_stream_events.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set ID of the LiveStreamEvent to get live stream events from. +LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' + + +def main(client, live_stream_event_id): + # Initialize appropriate services. + live_stream_events_service = client.GetService( + 'LiveStreamEventService', version='v201711') + + # Create statement object to only select matching live stream event. + statement = (dfp.StatementBuilder() + .Where(('Id = :id')) + .WithBindVariable('id', long(live_stream_event_id)) + .Limit(500)) + + # Get live stream events by statement. + response = live_stream_events_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + + # Set adTags to be updated. + new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE'] + + if 'results' in response: + # Update each local live stream event by changing its attributes. + updated_live_stream_events = [] + for live_stream_event in response['results']: + live_stream_event['startDateTimeType'] = 'IMMEDIATELY' + live_stream_event['adTags'] = new_ad_tags + updated_live_stream_events.append(live_stream_event) + + # Update live stream events. + live_stream_events = live_stream_events_service.updateLiveStreamEvents( + updated_live_stream_events) + + # Display results. + for live_stream_event in live_stream_events: + print('Live stream event with id "%s", named "%s" and status %s was ' + 'updated.' % (live_stream_event['id'], live_stream_event['name'], + live_stream_event['status'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py b/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py new file mode 100755 index 00000000..04b5d933 --- /dev/null +++ b/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example activates paused live stream events.""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the id of the LiveStreamEvent to get live stream events from. +LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' + + +def main(client, live_stream_event_id): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201802') + + # Create query to find paused live stream events. + statement = (dfp.StatementBuilder() + .Where(('id = :id AND ' + 'status = :status')) + .WithBindVariable('status', 'PAUSED') + .WithBindVariable('id', long(live_stream_event_id)) + .Limit(500)) + + live_stream_events_activated = 0 + + # Get live stream events by statement. + while True: + response = live_stream_event_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + if 'results' in response: + for live_stream_event in response['results']: + print('live stream event with id "%s" and name "%s" will be activated.' + % (live_stream_event['id'], live_stream_event['name'])) + + # Perform action. + result = live_stream_event_service.performLiveStreamEventAction({ + 'xsi_type': 'ActivateLiveStreamEvents' + }, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + live_stream_events_activated += int(result['numChanges']) + statement.offset += dfp.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if live_stream_events_activated > 0: + print '# of live stream events activated: %s' % ( + live_stream_events_activated) + else: + print 'No live stream events were activated.' + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201802/live_stream_event_service/create_live_stream_events.py b/examples/dfp/v201802/live_stream_event_service/create_live_stream_events.py new file mode 100755 index 00000000..927fe5fa --- /dev/null +++ b/examples/dfp/v201802/live_stream_event_service/create_live_stream_events.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example creates new live stream events. + +To determine which live stream events exist, run get_all_live_stream_events.py. +To determine which cdn configurations exist, run get_cdn_configurations.py. +""" + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import dfp +import pytz + +# Set content urls and adTags to use +CONTENT_URLS = ['INSERT_CONTENT_URLS_HERE'] +AD_TAGS = ['INSERT_AD_TAGS_HERE'] + + +def main(client, content_urls, ad_tags): + # Initialize appropriate services. + live_events_service = client.GetService( + 'LiveStreamEventService', version='v201802') + + # Stream will play for 365 days + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + + # Create live stream event objects + live_stream_events = [{ + 'name': 'Live Stream Event #%s' % uuid.uuid4(), + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, + 'contentUrls': content_urls, + 'adTags': ad_tags + }] + + # Add live stream events. + live_stream_events = live_events_service.createLiveStreamEvents( + live_stream_events) + + # Display results. + for live_stream_event in live_stream_events: + print( + 'Live stream event with id "%s", named "%s" and status %s was created.' + % (live_stream_event['id'], live_stream_event['name'], + live_stream_event['status'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, CONTENT_URLS, AD_TAGS) diff --git a/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py b/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py new file mode 100755 index 00000000..b8b4a57d --- /dev/null +++ b/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 live stream events. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201802') + + # Create a statement to select live stream events. + statement = dfp.StatementBuilder() + + # Retrieve a small amount of live stream events at a time, paging + # through until all live stream events have been retrieved. + while True: + response = live_stream_event_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + if 'results' in response: + for live_stream_event in response['results']: + # Print out some information for each live stream event. + print('live stream event with id "%d" and name "%s" was found.' % + (live_stream_event['id'], live_stream_event['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201802/live_stream_event_service/register_sessions_for_monitoring.py b/examples/dfp/v201802/live_stream_event_service/register_sessions_for_monitoring.py new file mode 100755 index 00000000..9330bb0f --- /dev/null +++ b/examples/dfp/v201802/live_stream_event_service/register_sessions_for_monitoring.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 registers all live stream event-sessions ids for monitoring.""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# List of session ids +SESSION_IDS = ['INSERT_SESSION_IDS_HERE'] + + +def main(client, session_ids): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201802') + + # Retrieve all sessions id that are being monitored + session_ids = live_stream_event_service.registerSessionsForMonitoring( + session_ids) + if session_ids: + for session_id in session_ids: + # Print out some information for each live stream event. + print 'Session with ID "%s" registered for monitoring.' % (session_id) + + print '\nNumber of results found: %s' % session_ids.size + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, SESSION_IDS) diff --git a/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py b/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py new file mode 100755 index 00000000..2023e9ae --- /dev/null +++ b/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example updates live stream events. + +To determine which live stream events exist, run get_all_live_stream_events.py. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set ID of the LiveStreamEvent to get live stream events from. +LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' + + +def main(client, live_stream_event_id): + # Initialize appropriate services. + live_stream_events_service = client.GetService( + 'LiveStreamEventService', version='v201802') + + # Create statement object to only select matching live stream event. + statement = (dfp.StatementBuilder() + .Where(('Id = :id')) + .WithBindVariable('id', long(live_stream_event_id)) + .Limit(500)) + + # Get live stream events by statement. + response = live_stream_events_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + + # Set adTags to be updated. + new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE'] + + if 'results' in response: + # Update each local live stream event by changing its attributes. + updated_live_stream_events = [] + for live_stream_event in response['results']: + live_stream_event['startDateTimeType'] = 'IMMEDIATELY' + live_stream_event['adTags'] = new_ad_tags + updated_live_stream_events.append(live_stream_event) + + # Update live stream events. + live_stream_events = live_stream_events_service.updateLiveStreamEvents( + updated_live_stream_events) + + # Display results. + for live_stream_event in live_stream_events: + print('Live stream event with id "%s", named "%s" and status %s was ' + 'updated.' % (live_stream_event['id'], live_stream_event['name'], + live_stream_event['status'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, LIVE_STREAM_EVENT_ID) diff --git a/googleads/common.py b/googleads/common.py index 1e94b963..3ea06a9b 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '11.0.0' +VERSION = '11.0.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' @@ -1239,8 +1239,18 @@ def _PackArgumentsHelper(self, elem, data, set_type_attrs): if isinstance(data, dict): # Dict so it's a complex type. xsi_type = data.get('xsi_type') if xsi_type: # This has a type override so look it up. - elem_type = self.zeep_client.get_type( - '{%s}%s' % (self._GetBindingNamespace(), xsi_type)) + elem_type = None + last_exception = None + for ns_prefix in self.zeep_client.wsdl.types.prefix_map.values(): + try: + elem_type = self.zeep_client.get_type( + '{%s}%s' % (ns_prefix, xsi_type)) + except zeep.exceptions.LookupError as e: + last_exception = e + continue + break + if not elem_type: + raise last_exception else: elem_type = elem.type elem_arguments = dict(elem_type.elements) diff --git a/tests/common_test.py b/tests/common_test.py index e460867f..a99e8852 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -1136,6 +1136,26 @@ def testPackArgumentsBase64Warning(self): self.zeep_client._PackArgumentsHelper(b64_type, data, False) self.assertTrue(len(googleads.common._logger.warn.mock_calls)) + def testPackArgumentsMultipleSchemas(self): + header_handler = mock.Mock() + + wsdl_path = os.path.join( + TEST_DIR, 'test_data/traffic_estimator_service.xml') + zeep_client = googleads.common.ZeepServiceProxy( + wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100) + + element = zeep_client.zeep_client.get_type('ns0:Criterion') + data = {'xsi_type': 'Location', 'id': '2840'} + + result = zeep_client._PackArgumentsHelper(element, data, False) + self.assertEqual(result.id, '2840') + + def testPackArgumentsBadType(self): + element = self.zeep_client.zeep_client.get_type('ns0:Image') + data = {'xsi_type': 'nope'} + with self.assertRaises(zeep.exceptions.LookupError): + self.zeep_client._PackArgumentsHelper(element, data, False) + class SudsServiceProxyTest(unittest.TestCase): """Tests for the googleads.common.SudsServiceProxy class.""" diff --git a/tests/test_data/traffic_estimator_service.xml b/tests/test_data/traffic_estimator_service.xml new file mode 100644 index 00000000..23c762c4 --- /dev/null +++ b/tests/test_data/traffic_estimator_service.xml @@ -0,0 +1,3313 @@ + + + + + + + + + + Errors that are thrown when a non-AdX feature is accessed by an AdX customer. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + The API error base class that provides details about an error that occurred + while processing a service request. + + <p>The OGNL field path is provided for parsers to identify the request data + element that may have caused the error.</p> + + + + + + + The OGNL field path to identify cause of error. + + + + + + + A parsed copy of the field path. For example, the field path "operations[1].operand" + corresponds to this list: {FieldPathElement(field = "operations", index = 1), + FieldPathElement(field = "operand", index = null)}. + + + + + + + The data that caused the error. + + + + + + + A simple string representation of the error and reason. + + + + + + + Indicates that this instance is a subtype of ApiError. + Although this field is returned in the response, it is ignored on input + and cannot be selected. Specify xsi:type instead. + + + + + + + + + Exception class for holding a list of service errors. + + + + + + + + + List of errors. + + + + + + + + + + + Base class for exceptions. + + + + + + + Error message. + + + + + + + Indicates that this instance is a subtype of ApplicationException. + Although this field is returned in the response, it is ignored on input + and cannot be selected. Specify xsi:type instead. + + + + + + + + + Errors returned when Authentication failed. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Errors encountered when trying to authorize a user. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Error due to user not accepting the AdWords terms of service. + + + + + + + + + + + + + + Errors associated with the size of the given collection being + out of bounds. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Comparable types for constructing ranges with. + + + + + + + Indicates that this instance is a subtype of ComparableValue. + Although this field is returned in the response, it is ignored on input + and cannot be selected. Specify xsi:type instead. + + + + + + + + + Represents a criterion (such as a keyword, placement, or vertical). + <span class="constraint AdxEnabled">This is disabled for AdX when it is contained within Operators: ADD, SET.</span> + + + + + + + ID of this criterion. + <span class="constraint Selectable">This field can be selected using the value "Id".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : SET, REMOVE.</span> + + + + + + + <span class="constraint Selectable">This field can be selected using the value "CriteriaType".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + Indicates that this instance is a subtype of Criterion. + Although this field is returned in the response, it is ignored on input + and cannot be selected. Specify xsi:type instead. + + + + + + + + + Errors that are thrown due to a database access problem. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Errors associated with invalid dates and date ranges. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Errors related to distinct ids or content. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Number value type for constructing double valued ranges. + + + + + + + + + the underlying double value. + + + + + + + + + + + Reports permission problems trying to access an entity. + + + + + + + + + Reason for this error. + + + + + + + + + + + An id did not correspond to an entity, or it referred to an entity which does not belong to the + customer. + + + + + + + + + Reason for this error. + + + + + + + + + + + A segment of a field path. Each dot in a field path defines a new segment. + + + + + + + The name of a field in lower camelcase. (e.g. "biddingStrategy") + + + + + + + For list fields, this is a 0-indexed position in the list. Null for non-list fields. + + + + + + + + + Errors associated with the ids. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Indicates that a server-side error has occured. {@code InternalApiError}s + are generally not the result of an invalid request or message sent by the + client. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Represents a keyword. + <span class="constraint AdxEnabled">This is disabled for AdX when it is contained within Operators: ADD, SET.</span> + + + + + + + + + Text of this keyword (at most 80 characters and ten words). + <span class="constraint Selectable">This field can be selected using the value "KeywordText".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint MatchesRegex">Keyword text must not contain NUL (code point 0x0) characters. This is checked by the regular expression '[^\x00]*'.</span> + <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span> + + + + + + + Match type of this keyword. + <span class="constraint Selectable">This field can be selected using the value "KeywordMatchType".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span> + + + + + + + + + + + Represents a Language criterion. + <p>A criterion of this type can only be created using an ID. + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + + + + + Represents Location criterion. + <p>A criterion of this type can only be created using an ID. + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + Name of the location criterion. <b> Note:</b> This field is filterable only in + LocationCriterionService. If used as a filter, a location name cannot be greater than 300 + characters. + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + Display type of the location criterion. + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + The targeting status of the location criterion. + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + Ordered list of parents of the location criterion. + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + + + + + Number value type for constructing long valued ranges. + + + + + + + + + the underlying long value. + + + + + + + + + + + Represents the mobile app category to be targeted. + <a href="/adwords/api/docs/appendix/mobileappcategories">View the complete list of + available mobile app categories</a>. + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + ID of this mobile app category. A complete list of the available mobile app categories is + available <a href="/adwords/api/docs/appendix/mobileappcategories">here</a>. + <span class="constraint Selectable">This field can be selected using the value "MobileAppCategoryId".</span> + <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span> + + + + + + + Name of this mobile app category. + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + + + + + Represents the mobile application to be targeted. + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + A string that uniquely identifies a mobile application to AdWords API. The format of this + string is "<code>{platform}-{platform_native_id}</code>", where <code>platform</code> is "1" + for iOS apps and "2" for Android apps, and where <code>platform_native_id</code> is the mobile + application identifier native to the corresponding platform. + For iOS, this native identifier is the 9 digit string that appears at the end of an App Store + URL (e.g., "476943146" for "Flood-It! 2" whose App Store link is + http://itunes.apple.com/us/app/flood-it!-2/id476943146). + For Android, this native identifier is the application's package name (e.g., + "com.labpixies.colordrips" for "Color Drips" given Google Play link + https://play.google.com/store/apps/details?id=com.labpixies.colordrips). + A well formed app id for AdWords API would thus be "1-476943146" for iOS and + "2-com.labpixies.colordrips" for Android. + <span class="constraint Selectable">This field can be selected using the value "AppId".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span> + + + + + + + Title of this mobile application. + <span class="constraint Selectable">This field can be selected using the value "DisplayName".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + + + + + Represents a money amount. + + + + + + + + + Amount in micros. One million is equivalent to one unit. + + + + + + + + + + + Network settings for a Campaign. + + + + + + + Ads will be served with Google.com search results. + <span class="constraint AdxEnabled">This is disabled for AdX.</span> + <span class="constraint CampaignType">This field may only be set to true for campaign channel type SEARCH.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span> +<span class="constraint CampaignType">This field may only be set to false for campaign channel type DISPLAY.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_UNIVERSAL_ADS.</span> + + + + + + + Ads will be served on partner sites in the Google Search Network + (requires {@code GOOGLE_SEARCH}). + <span class="constraint AdxEnabled">This is disabled for AdX.</span> + <span class="constraint CampaignType">This field may only be set to true for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_UNIVERSAL_ADS.</span> + + + + + + + Ads will be served on specified placements in the Google Display Network. + Placements are specified using {@code Placement} criteria. + <span class="constraint CampaignType">This field may only be set to true for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span> +<span class="constraint CampaignType">This field may only be set to false for campaign channel subtype SEARCH_MOBILE_APP.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_UNIVERSAL_ADS.</span> + + + + + + + Ads will be served on the Google Partner Network. This is available to + only some specific Google partner accounts. + <span class="constraint AdxEnabled">This is disabled for AdX.</span> + <span class="constraint CampaignType">This field may only be set to false for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span> + + + + + + + + + Errors corresponding with violation of a NOT EMPTY check. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Errors associated with violation of a NOT NULL check. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Number value types for constructing number valued ranges. + + + + + + + + + + + + Operation not permitted due to the invoked service's access policy. + + + + + + + + + + + + + + Errors due to the use of unsupported operations. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + A placement used for modifying bids for sites when targeting the content + network. + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + Url of the placement. + + <p>For example, "http://www.domain.com". + <span class="constraint Selectable">This field can be selected using the value "PlacementUrl".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint Required">This field is required and should not be {@code null} when it is contained within {@link Operator}s : ADD.</span> + + + + + + + + + + + Represents Platform criterion. + <p>A criterion of this type can only be created using an ID. + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + + + + + Encapsulates the errors thrown during developer quota checks. + + + + + + + + + + + + + + A list of all errors associated with the Range constraint. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Signals that a call failed because a measured rate exceeded. + + + + + + + + + The error reason represented by an enum. + + + + + + + Cause of the rate exceeded error. + + + + + + + The scope of the rate (ACCOUNT/DEVELOPER). + + + + + + + The amount of time (in seconds) the client should wait before retrying the request. + + + + + + + + + + + Errors from attempting to write to read-only fields. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + A list of all errors associated with the @RegionCode constraints. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Indicates that a field was rejected due to compatibility issues. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Encapsulates the generic errors thrown when there's an error with user + request. + + + + + + + + + + + + + + Errors due to missing required field. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Indicates that the number of entries in the request or response exceeds the system limit. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Defines the required and optional elements within the header of a SOAP request. + + + + + + + The header identifies the customer id of the client of the AdWords manager, if an AdWords + manager is acting on behalf of their client or the customer id of the advertiser managing their + own account. + + + + + + + Developer token to identify that the person making the call has enough + quota. + + + + + + + UserAgent is used to track distribution of API client programs and + application usage. The client is responsible for putting in a meaningful + value for tracking purposes. To be clear this is not the same as an HTTP + user agent. + + + + + + + Used to validate the request without executing it. + + + + + + + If true, API will try to commit as many error free operations as possible and + report the other operations' errors. + + <p>Ignored for non-mutate calls. + + + + + + + + + Defines the elements within the header of a SOAP response. + + + + + + + Unique id that identifies this request. If developers have any support issues, sending us + this id will enable us to find their request more easily. + + + + + + + The name of the service being invoked. + + + + + + + The name of the method being invoked. + + + + + + + Number of operations performed for this SOAP request. + + + + + + + Elapsed time in milliseconds between the AdWords API receiving the request and sending the + response. + + + + + + + + + A list of error code for reporting invalid content of input strings. + + + + + + + + + + + + + + Errors associated with the length of the given string being + out of bounds. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + User Interest represents a particular interest-based vertical to be targeted. + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + Id of this user interest. This is a required field. + <span class="constraint Selectable">This field can be selected using the value "UserInterestId".</span> + + + + + + + Parent Id of this user interest. + <span class="constraint Selectable">This field can be selected using the value "UserInterestParentId".</span> + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + Name of this user interest. + <span class="constraint Selectable">This field can be selected using the value "UserInterestName".</span> + + + + + + + + + + + UserList - represents a user list that is defined by the advertiser to be targeted. + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + Id of this user list. This is a required field. + <span class="constraint Selectable">This field can be selected using the value "UserListId".</span> + + + + + + + <span class="constraint Selectable">This field can be selected using the value "UserListName".</span> + + + + + + + <span class="constraint Selectable">This field can be selected using the value "UserListMembershipStatus".</span><span class="constraint Filterable">This field can be filtered on.</span> + + + + + + + Determines whether a user list is eligible for targeting in the google.com + (search) network. + <span class="constraint Selectable">This field can be selected using the value "UserListEligibleForSearch".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + Determines whether a user list is eligible for targeting in the display network. + <span class="constraint Selectable">This field can be selected using the value "UserListEligibleForDisplay".</span><span class="constraint Filterable">This field can be filtered on.</span> + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + + + + + Use verticals to target or exclude placements in the Google Display Network + based on the category into which the placement falls (for example, "Pets &amp; + Animals/Pets/Dogs"). + <a href="/adwords/api/docs/appendix/verticals">View the complete list + of available vertical categories.</a> + <span class="constraint AdxEnabled">This is enabled for AdX.</span> + + + + + + + + + Id of this vertical. + <span class="constraint Selectable">This field can be selected using the value "VerticalId".</span> + + + + + + + Id of the parent of this vertical. + <span class="constraint Selectable">This field can be selected using the value "VerticalParentId".</span> + <span class="constraint ReadOnly">This field is read only and will be ignored when sent to the API.</span> + + + + + + + The category to target or exclude. Each subsequent element in the array + describes a more specific sub-category. For example, + <code>{"Pets &amp; Animals", "Pets", "Dogs"}</code> represents the "Pets &amp; + Animals/Pets/Dogs" category. A complete list of available vertical categories + is available <a href="/adwords/api/docs/appendix/verticals">here</a> + This field is required and must not be empty. + <span class="constraint Selectable">This field can be selected using the value "Path".</span> + + + + + + + + + + + The reasons for the AdX error. + + + + + + + Attempt to use non-AdX feature by AdX customer. + + + + + + + + + The single reason for the authentication failure. + + + + + + + Authentication of the request failed. + + + + + + + Client Customer Id is required if CustomerIdMode is set to CLIENT_EXTERNAL_CUSTOMER_ID. + Starting version V201409 ClientCustomerId will be required for all requests except + for {@link CustomerService#get} + + + + + + + Client Email is required if CustomerIdMode is set to CLIENT_EXTERNAL_EMAIL_FIELD. + + + + + + + Client customer Id is not a number. + + + + + + + Client customer Id is not a number. + + + + + + + Client email is not a valid customer email. + + + + + + + No customer found for the customer id provided in the header. + + + + + + + Client's Google Account is deleted. + + + + + + + Google account login token in the cookie is invalid. + + + + + + + problem occurred during Google account authentication. + + + + + + + The user in the google account login token does not match the UserId in the cookie. + + + + + + + Login cookie is required for authentication. + + + + + + + User in the cookie is not a valid Ads user. + + + + + + + Oauth token in the header is not valid. + + + + + + + Oauth token in the header has expired. + + + + + + + Oauth token in the header has been disabled. + + + + + + + Oauth token in the header has been revoked. + + + + + + + Oauth token HTTP header is malformed. + + + + + + + Login cookie is not valid. + + + + + + + Failed to decrypt the login cookie. + + + + + + + User Id in the header is not a valid id. + + + + + + + + + The reasons for the authorization error. + + + + + + + Could not complete authorization due to an internal problem. + + + + + + + Customer has no AdWords account. + + + + + + + User doesn't have permission to access customer. + + + + + + + Effective user doesn't have permission to access this customer. + + + + + + + Access denied since the customer is not active. + + + + + + + User has read-only permission cannot mutate. + + + + + + + No customer found. + + + + + + + Developer doesn't have permission to access service. + + + + + + + + + Enums for the various reasons an error can be thrown as a result of + ClientTerms violation. + + + + + + + Customer has not agreed to the latest AdWords Terms & Conditions + + + + + + + + + The reasons for the target error. + + + + + + + + + + + The types of criteria. + + + + + + + Content label for exclusion. + + + + + + + Keyword. e.g. 'mars cruise' + + + + + + + Placement. aka Website. e.g. 'www.flowers4sale.com' + + + + + + + Vertical, e.g. 'category::Animals>Pets' This is for vertical targeting on the content + network. + + + + + + + User lists, are links to sets of users defined by the advertiser. + + + + + + + User interests, categories of interests the user is interested in. + + + + + + + Mobile applications to target. + + + + + + + Mobile application categories to target. + + + + + + + Product partition (product group) in a shopping campaign. + + + + + + + IP addresses to exclude. + + + + + + + Webpages of an advertiser's website to target. + + + + + + + Languages to target. + + + + + + + Geographic regions to target. + + + + + + + Age Range to exclude. + + + + + + + Mobile carriers to target. + + + + + + + Mobile operating system versions to target. + + + + + + + Mobile devices to target. + + + + + + + Gender to exclude. + + + + + + + Parent to target and exclude. + + + + + + + Proximity (area within a radius) to target. + + + + + + + Platforms to target. + + + + + + + Representing preferred content bid modifier. + + + + + + + AdSchedule or specific days and time intervals to target. + + + + + + + Targeting based on location groups. + + + + + + + Scope of products. Contains a list of product dimensions, all of which a product has to match + to be included in the campaign. + + + + + + + YouTube video to target. + + + + + + + YouTube channel to target. + + + + + + + Enables advertisers to target paid apps. + + + + + + + Income range to target and exclude. + + + + + + + Interaction type to bid modify. + + + + + + + <span class="constraint Rejected">Used for return value only. An enumeration could not be processed, typically due to incompatibility with your WSDL version.</span> + + + + + + + + + The reasons for the database error. + + + + + + + A concurrency problem occurred as two threads were attempting to modify same object. + + + + + + + The permission was denied to access an object. + + + + + + + The user's access to an object has been prohibited. + + + + + + + Requested campaign belongs to a product that is not supported by the api. + + + + + + + a duplicate key was detected upon insertion + + + + + + + a database error has occurred + + + + + + + an unknown error has occurred + + + + + + + + + The reasons for the target error. + + + + + + + Given field values do not correspond to a valid date. + + + + + + + Given field values do not correspond to a valid date time. + + + + + + + The string date's format should be yyyymmdd. + + + + + + + The string date range's format should be yyyymmdd yyyymmdd. + + + + + + + The string date time's format should be yyyymmdd hhmmss [tz]. + + + + + + + Date is before allowed minimum. + + + + + + + Date is after allowed maximum. + + + + + + + Date range bounds are not in order. + + + + + + + Both dates in range are null. + + + + + + + + + The reasons for the validation error. + + + + + + + + + + + + + User did not have read access. + + + + + + + User did not have write access. + + + + + + + + + + + The specified id refered to an entity which either doesn't exist or is not accessible to the + customer. e.g. campaign belongs to another customer. + + + + + + + + + The reasons for the target error. + + + + + + + Id not found + + + + + + + + + The single reason for the internal API error. + + + + + + + API encountered an unexpected internal error. + + + + + + + A temporary error occurred during the request. Please retry. + + + + + + + The cause of the error is not known or only defined in newer versions. + + + + + + + The API is currently unavailable for a planned downtime. + + + + + + + Mutate succeeded but server was unable to build response. Client should not retry mutate. + + + + + + + + + Match type of a keyword. i.e. the way we match a keyword string with + search queries. + + + + + + + Exact match + + + + + + + Phrase match + + + + + + + Broad match + + + + + + + + + Enum that represents the different Targeting Status values for a Location criterion. + + + + + + + The location is active. + + + + + + + The location is not available for targeting. + + + + + + + The location is phasing out, it will marked obsolete soon. + + + + + + + + + The reasons for the validation error. + + + + + + + + + + The reasons for the validation error. + + + + + + + Specified list/container must not contain any null elements + + + + + + + + + The reasons for the operation access error. + + + + + + + Unauthorized invocation of a service's method (get, mutate, etc.) + + + + + + + Unauthorized ADD operation in invoking a service's mutate method. + + + + + + + Unauthorized REMOVE operation in invoking a service's mutate method. + + + + + + + Unauthorized SET operation in invoking a service's mutate method. + + + + + + + A mutate action is not allowed on this campaign, from this client. + + + + + + + This operation is not permitted on this campaign type + + + + + + + An ADD operation may not set status to REMOVED. + + + + + + + This operation is not allowed because the campaign or adgroup is removed. + + + + + + + This operation is not permitted on this ad group type. + + + + + + + The reason the invoked method or operation is prohibited is not known + (the client may be of an older version than the server). + + + + + + + + + The reasons for the validation error. + + + + + + + + + + Enums for all the reasons an error can be thrown to the user during + billing quota checks. + + + + + + + Customer passed in an invalid token in the header. + + + + + + + Customer is marked delinquent. + + + + + + + Customer is a fraudulent. + + + + + + + Inactive Account. + + + + + + + Signup not complete + + + + + + + Developer token is not approved for production access, and the customer + is attempting to access a production account. + + + + + + + Terms and conditions are not signed. + + + + + + + Monthly budget quota reached. + + + + + + + Monthly budget quota exceeded. + + + + + + + + + The reasons for the target error. + + + + + + + + + + + The reason for the rate exceeded error. + + + + + + + Rate exceeded. + + + + + + + + + The reasons for the target error. + + + + + + + + + + The reasons for the validation error. + + + + + + + + + + The reasons for the target error. + + + + + + + Unknown value encountered + + + + + + + + + + + Error reason is unknown. + + + + + + + Invalid input. + + + + + + + The api version in the request has been discontinued. Please update + to the new AdWords API version. + + + + + + + + + The reasons for the target error. + + + + + + + Missing required field. + + + + + + + + + The reasons for Ad Scheduling errors. + + + + + + + The number of entries in the request exceeds the system limit. + + + + + + + The number of entries in the response exceeds the system limit. + + + + + + + The account is too large to load. + + + + + + + <span class="constraint Rejected">Used for return value only. An enumeration could not be processed, typically due to incompatibility with your WSDL version.</span> + + + + + + + + + The reasons for the target error. + + + + + + + + The input string value contains disallowed characters. + + + + + + + The input string value is invalid for the associated field. + + + + + + + + + The reasons for the target error. + + + + + + + + + + + Membership status of the user list. + + + + + + + Open status - list is accruing members and can be targeted to. + + + + + + + Closed status - No new members being added. Can not be used for targeting a new campaign. + Existing campaigns can still work as long as the list is not removed as a targeting criteria. + + + + + + + + + + + + + + + + + Represents the estimate results for a single ad group. + + + + + + + + + The adGroupId of the ad group specified in the request. + + This will be <code>null</code> for new ad groups. + + + + + + + The estimates for the keywords specified in the request. + + The list of estimates are returned in the same order as the keywords that + were sent in the request. + + + + + + + + + + + Represents an ad group that will be estimated. Ad groups may be all + new or all existing, or a mixture of new and existing. Only existing + campaigns can contain estimates for existing ad groups.<p> + + <p>To make a keyword estimates request in which estimates do not consider + existing account information (e.g. historical ad group performance), set both + {@link #adGroupId} and the enclosing {@link CampaignEstimateRequest}'s + {@code campaignId} to {@code null}. + + <p>For more details on usage, refer to document at + {@link CampaignEstimateRequest}. + + + + + + + + + The adGroupId for an ad group that belongs to the containing campaign from + {@link CampaignEstimateRequest} or {@code null}. + + <p>For usage, refer to document from {@link CampaignEstimateRequest}. + + + + + + + The keywords to estimate. + <span class="constraint ContentsDistinct">This field must contain distinct elements.</span> + <span class="constraint ContentsNotNull">This field must not contain {@code null} elements.</span> + <span class="constraint Required">This field is required and should not be {@code null}.</span> + + + + + + + The max CPC bid to use for estimates for this ad group. + + <p>This value overrides the max CPC of AdGroup specified by + {@link #adGroupId}. + + + + + + + + + + + Represents the estimate results for a single campaign. + + + + + + + + + The campaignId of the campaign specified in the request. + + This will be <code>null</code> for new campaigns. + + + + + + + The estimates for the ad groups belonging to this campaign in the request. + + They will be returned in the same order that they were sent in the request. + + + + + + + Traffic estimates segmented by platform for this campaign. + + + + + + + + + + + Represents a campaign that will be estimated.<p> + + Returns traffic estimates for the requested set of campaigns. + The campaigns can be all new or all existing, or a mixture of + new and existing. Only existing campaigns may contain estimates for existing + ad groups.<p> + + For existing campaigns, the campaign and optionally the ad group will be + used as context to produce more accurate estimates. Traffic estimates may + only be requested on keywords, so regardless of whether campaign and ad group + IDs are provided or left blank, at least one keyword is required to estimate + traffic.<p> + + To make a keyword estimates request in which estimates do not consider + existing account information (e.g. historical ad group performance), set + {@link #campaignId} to {@code null}. + + + + + + + + + The campaignId of an existing campaign or {@code null}.<p> + + Refer to the {@link CampaignEstimateRequest} documentation for + detailed usage. + + + + + + + The list of ad groups to estimate. This field is required and should not be {@code null}. At + least one ad group is required. + + <p>New campaigns may only contain new ad groups. If an + {@link AdGroupEstimateRequest} has an adGroupId but the campaign is new, + the API will return an error. + <span class="constraint ContentsNotNull">This field must not contain {@code null} elements.</span> + + + + + + + A list of {@link Criterion}s to be used for this Campaign. Criteria + provide information about geographical and language targeting. + + <p>Values in this field override the current targets in the Campaign + specified by {@link #campaignId} by the following mechanism: + + <p>This field accepts two types of {@link Criterion}s: {@link Location}, which should contain + all geographic targeting and {@link Language}, which should contain all language targeting. + If {@link Location}s are passed in, all geographic targeting in the campaign will be + overridden. If any {@link Language}s are passed in, all language targeting in the campaign + will be overridden. + + <p>If multiple {@link Location}s are specified, the traffic estimate will + be the sum of the estimates for each targeted area. This means that if + criteria are chosen which overlap each other (for example, targeting both + a country and a city within that country), the traffic estimate will be + be larger than if no overlap were present - i. e., the overlap region will + be double-counted in the estimate. + + <p>If no criteria are specified and this is for a new campaign then it + will default to all languages in all countries and territories, and + Google search. + + <p>If no criteria are specified and this is for an existing campaign + then the current targeting on that campaign will be used. + + <p>While there's no solid limit on number of criteria, + TrafficEstimatorService may return error with TOO_MANY_TARGETS if the + request contains too many criteria across all + {@link CampaignEstimateRequest}s in a {@link TrafficEstimatorSelector}. + + <p>Supported Criteria : {@link Language} and {@link Location}. + <span class="constraint ContentsDistinct">This field must contain distinct elements.</span> + <span class="constraint ContentsNotNull">This field must not contain {@code null} elements.</span> + + + + + + + A {@link NetworkSetting} to be used for this Campaign. The value of this + field overrides the current targets in the Campaign specified by + {@link #campaignId}. + + <p>For non Google partner accounts, only + {@link NetworkSetting#targetGoogleSearch} and + {@link NetworkSetting#targetSearchNetwork} are supported, they may be + combined to sum the estimates. + + <p>For some Google partner accounts, in addition + {@link NetworkSetting#getTargetPartnerSearchNetwork} is supported. + + <p>If all request network settings and Campaign's network settings are + empty, the default is {@link NetworkSetting#targetGoogleSearch}. + + + + + + + Daily campaign budget to use in traffic estimation. If not specified, + the daily budget is unlimited. + + + + + + + + + + + Errors for currency codes. + + + + + + + + + The error reason represented by an enum. + + + + + + + + + + + Abstract class representing an reply to an {@link EstimateRequest}. + + + + + + + Indicates that this instance is a subtype of Estimate. + Although this field is returned in the response, it is ignored on input + and cannot be selected. Specify xsi:type instead. + + + + + + + + + Abstract class representing a request to estimate stats. + + + + + + + Indicates that this instance is a subtype of EstimateRequest. + Although this field is returned in the response, it is ignored on input + and cannot be selected. Specify xsi:type instead. + + + + + + + + + Represents the traffic estimate result for a single keyword. + + + + + + + + + The existing criterionId for this keyword, if any. + + This will not be returned if this is a new keyword. + + + + + + + The lower bound on the estimated stats. + + <p>This is not a guarantee that actual performance will never be lower than + these stats. + + + + + + + The upper bound on the estimated stats. + + <p>This is not a guarantee that actual performance will never be higher than + these stats. + + + + + + + + + + + Represents a keyword to be estimated. + + + + + + + + + The {@link Keyword} to estimate. The keyword text is required regardless + of whether the keyword ID is included. The keyword ID is optional and has + the following characteristics: + <ul> + <li>When omitted, the ID indicates a new keyword to be estimated.</li> + <li>When present with a campaign and ad group also specified, the ID should + be for an existing keyword in the ad group. This can improve the estimates + since historical performance is known.</li> + <li>When present without a campaign and ad group specified, the ID is + ignored.</li> + </ul> + <span class="constraint Required">This field is required and should not be {@code null}.</span> + + + + + + + The max CPC bid for this keyword. + + In general, the {@code maxCpc} of a {@link KeywordEstimateRequest} is + optional, since there is usually another {@code maxCpc} that can be used, + such as the {@code maxCpc} on an existing keyword, an existing or + overriding {@code maxCpc} of containing {@link AdGroupEstimateRequest}. + However, if there is no backup value of {@code maxCpc} anywhere along the + line, you must provide a value for {@code maxCpc} in + {@link KeywordEstimateRequest}. This would happen, for example, if the + {@link KeywordEstimateRequest} is for a new keyword. + + + + + + + Whether the keyword is negative or not. The default value is false. + If negative, no current ad group ads will appear for searches containing + this keyword.<p> + + The estimate for negative keywords should reflect no traffic and zero CPC, + but including a negative keyword will affect the other estimates in the + request. + + + + + + + + + + + Contains a campaign level estimate for a specified {@link Platform}. + + + + + + + The {@link Platform} associated with this estimate. + <span class="constraint Required">This field is required and should not be {@code null}.</span> + + + + + + + Minimum estimate for the specified {@link Platform}. + + + + + + + Maximum estimate for the specified {@link Platform}. + + + + + + + + + Represents a set of stats for a daily traffic estimate. + + <p>{@code averageCpc}, {@code averagePosition} and {@code clickThroughRate} will be + {@code null} when not defined and {@code clicksPerDay} or {@code impressionsPerDay} + is {@code 0}, respectively.</p> + + + + + + + The estimated average CPC. + + + + + + + The estimated average position. + + + + + + + The estimated click through rate. + + + + + + + The estimated number of clicks, in floating point representation. + + + + + + + The estimated number of impressions, in floating point representation. + + + + + + + The estimated total cost. + + + + + + + + + Base error class for {@link TrafficEstimatorService}. + + + + + + + + + + + + + + Contains results of traffic estimation request. + + + + + + + The estimates for the campaigns specified in the request. + + They are listed in the same order as the campaigns that were sent in the + request. + + + + + + + + + Contains a list of campaigns to perform a traffic estimate on. + + + + + + + A list of all campaigns to estimate.<p> + + To create a Keyword estimates request, use {@code null} campaign id. + <span class="constraint CollectionSize">The maximum size of this collection is 5.</span> + <span class="constraint ContentsDistinct">This field must contain distinct elements.</span> + <span class="constraint ContentsNotNull">This field must not contain {@code null} elements.</span> + <span class="constraint NotEmpty">This field must contain at least one element.</span> + <span class="constraint Required">This field is required and should not be {@code null}.</span> + + + + + + + To request a list of campaign level estimates segmented by platform. + + + + + + + + + Encodes the reason (cause) of a particular {@link CurrencyCodeError}. + + + + + + + + + + + + When the request with {@code null} campaign ID in {@link CampaignEstimateRequest} contains an + {@link AdGroupEstimateRequest} with an ID. + + + + + + + When the request with {@code null} adgroup ID in {@link AdGroupEstimateRequest} contains a + {@link KeywordEstimateRequest} with an ID. + + + + + + + All {@link KeywordEstimateRequest} items should have maxCpc associated with them. + + + + + + + When there are more {@link KeywordEstimateRequest}s in the request than + TrafficEstimatorService allows. + + + + + + + When there are more {@link CampaignEstimateRequest}s in the request than + TrafficEstimatorService allows. + + + + + + + When there are more {@link AdGroupEstimateRequest}s in the request than + TrafficEstimatorService allows. + + + + + + + When there are more targets in the request than TrafficEstimatorService allows. See + documentation on {@link CampaignEstimateRequest} for more information about this error. + + + + + + + Request contains a keyword that is too long for backends to handle. + + + + + + + Request contains a keyword that contains broad match modifiers. + + + + + + + When an unexpected error occurs. + + + + + + + When backend service calls fail. + + + + + + + + + Returns traffic estimates for specified criteria. + + @param selector Campaigns, ad groups and keywords for which traffic + should be estimated. + @return Traffic estimation results. + @throws ApiException if problems occurred while retrieving estimates + + + + + + + + <span class="constraint Required">This field is required and should not be {@code null}.</span> + + + + + + + + + + + + + + + + + A fault element of type ApiException. + + + + + + + + + + + + + + + + + + + + + + + + + Use this service to request traffic estimates for proposed or existing campaigns, ad + groups, and keywords. + + <p> + To simply retrieve estimates for a list of proposed keywords, create a + {@linkplain CampaignEstimateRequest campaign estimate request} and a child + {@linkplain AdGroupEstimateRequest ad group estimate request} with {@code null} IDs, + and then set the + {@link AdGroupEstimateRequest#keywordEstimateRequests keywordEstimateRequests} + to contain the keywords.</p> + + <p>You can refine the traffic estimates by setting + {@linkplain CampaignEstimateRequest#targets campaign targeting options} in the request. + If an ad group ID is provided, all creatives from that ad group will be loaded and used + to improve estimates.</p> + + <p>The maximum number of {@linkplain KeywordEstimateRequest keyword estimate + requests} across all campaign estimate requests and + ad group estimate requests is 2500.</p> + + <p>The maximum number of {@linkplain AdGroupEstimateRequest adgroup estimate + requests} across all campaign estimate requests is 50.</p> + + <p>Note that the API returns intervals whereas the Traffic Estimator UI displays averages. + Estimates are account specific since they are based on creatives already in the account. + When comparing numbers, use the same account for the API and UI.</p> + <span class="constraint AdxEnabled">This is disabled for AdX.</span> + + + + Returns traffic estimates for specified criteria. + + @param selector Campaigns, ad groups and keywords for which traffic + should be estimated. + @return Traffic estimation results. + @throws ApiException if problems occurred while retrieving estimates + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 7830f303a63217e7c7190f9b085bce9c4f677727 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Fri, 6 Apr 2018 15:53:53 -0400 Subject: [PATCH 107/180] Commiting latest changes. From 5ca481341595e971dd07e6d350909a58fbbf1002 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 15 May 2018 14:51:45 -0400 Subject: [PATCH 108/180] Commiting latest changes. --- ChangeLog | 12 + .../adwords/adwords_appengine_demo/ChangeLog | 4 + .../adwords/adwords_appengine_demo/app.yaml | 2 + .../appengine_config.py | 1 - .../adwords_appengine_demo/demo/__init__.py | 2 +- .../adwords_appengine_demo/demo/main.py | 3 + .../handlers/api_handler.py | 4 +- .../adwords_appengine_demo/requirements.txt | 2 +- .../v201710/basic_operations/get_campaigns.py | 4 - ...oad_criteria_report_as_stream_with_awql.py | 5 - ...criteria_report_as_stream_with_selector.py | 5 - ...criteria_report_as_string_with_selector.py | 4 - .../download_criteria_report_with_selector.py | 4 - .../reporting/parallel_report_download.py | 214 ++++++++++-------- .../v201802/basic_operations/get_campaigns.py | 4 - ...oad_criteria_report_as_stream_with_awql.py | 5 - ...criteria_report_as_stream_with_selector.py | 5 - ...criteria_report_as_string_with_selector.py | 4 - .../download_criteria_report_with_selector.py | 4 - .../reporting/parallel_report_download.py | 214 ++++++++++-------- ...delete_content_metadata_key_hierarchies.py | 81 ------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 2 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_package_item_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 4 +- .../base_rate_service/update_base_rates.py | 2 +- .../cdn_configuration_service}/__init__.py | 0 .../create_cdn_configurations.py | 89 ++++++++ .../get_all_cdn_configurations.py | 54 +++++ .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 2 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 2 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 2 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 6 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 2 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 2 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 47 ++-- .../update_custom_fields.py | 2 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 8 +- .../delete_custom_targeting_values.py | 23 +- ...et_all_custom_targeting_keys_and_values.py | 10 +- ...efined_custom_targeting_keys_and_values.py | 2 +- .../update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 4 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 4 +- .../update_exchange_rates.py | 2 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 3 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 115 ++++++++++ .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 58 +++++ .../inventory_service/update_ad_units.py | 2 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 2 +- .../label_service/update_labels.py | 2 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 2 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 2 +- .../activate_live_stream_events.py | 2 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 2 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 2 +- .../v201805/native_style_service/__init__.py | 15 ++ .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 2 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 37 +++ .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 2 +- .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 4 +- .../placement_service/create_placements.py | 4 +- .../deactivate_placements.py | 2 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 2 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 4 +- .../update_premium_rates.py | 2 +- .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 4 +- .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 4 +- .../get_all_product_packages.py | 2 +- .../product_service/__init__.py | 0 .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 4 +- .../product_service/update_products.py | 2 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 4 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 4 +- .../update_product_templates.py | 2 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- ...create_programmatic_proposal_line_items.py | 4 +- ...sal_line_items_for_non_sales_management.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 2 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../submit_proposals_for_approval.py | 4 +- .../proposal_service/update_proposals.py | 2 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 55 +++++ .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 53 +++++ .../get_line_items_named_like.py | 48 ++++ .../get_recent_changes.py | 2 +- .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 4 +- ..._item_reports_for_reconciliation_report.py | 2 +- ...update_reconciliation_line_item_reports.py | 2 +- ...order_reports_for_reconciliation_report.py | 4 +- .../submit_reconciliation_order_reports.py | 2 +- ...n_report_rows_for_reconciliation_report.py | 4 +- .../update_reconciliation_report_rows.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 66 ++++++ .../report_service/run_delivery_report.py | 2 +- .../report_service/run_inventory_report.py | 4 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 6 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 16 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 2 +- .../team_service/update_teams.py | 2 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 2 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 2 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 2 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 2 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 4 +- .../get_workflow_approval_requests.py | 4 +- ...et_workflow_external_condition_requests.py | 4 +- ...er_workflow_external_condition_requests.py | 4 +- googleads.yaml | 7 + googleads/adwords.py | 24 +- googleads/common.py | 36 ++- googleads/dfp.py | 40 ++-- tests/adwords_test.py | 81 +++++-- tests/common_test.py | 63 ++++-- tests/dfp_test.py | 40 +++- 269 files changed, 1361 insertions(+), 724 deletions(-) delete mode 100755 examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename examples/dfp/{v201708 => v201805}/activity_group_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/activity_group_service/create_activity_groups.py (97%) rename examples/dfp/{v201708 => v201805}/activity_group_service/get_active_activity_groups.py (94%) rename examples/dfp/{v201708 => v201805}/activity_group_service/get_all_activity_groups.py (97%) rename examples/dfp/{v201708 => v201805}/activity_group_service/update_activity_groups.py (97%) rename examples/dfp/{v201708 => v201805}/activity_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/activity_service/create_activities.py (99%) rename examples/dfp/{v201708 => v201805}/activity_service/get_active_activities.py (96%) rename examples/dfp/{v201708 => v201805}/activity_service/get_all_activities.py (99%) rename examples/dfp/{v201708 => v201805}/activity_service/update_activities.py (99%) rename examples/dfp/{v201708 => v201805}/audience_segment_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/audience_segment_service/create_audience_segments.py (98%) rename examples/dfp/{v201708 => v201805}/audience_segment_service/get_all_audience_segments.py (97%) rename examples/dfp/{v201708 => v201805}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/dfp/{v201708 => v201805}/audience_segment_service/populate_first_party_audience_segments.py (97%) rename examples/dfp/{v201708 => v201805}/audience_segment_service/update_audience_segments.py (97%) rename examples/dfp/{v201708 => v201805}/base_rate_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/base_rate_service/create_product_base_rates.py (97%) rename examples/dfp/{v201708 => v201805}/base_rate_service/create_product_package_item_base_rates.py (99%) rename examples/dfp/{v201708 => v201805}/base_rate_service/create_product_template_base_rates.py (97%) rename examples/dfp/{v201708 => v201805}/base_rate_service/get_all_base_rates.py (99%) rename examples/dfp/{v201708 => v201805}/base_rate_service/get_base_rates_for_rate_card.py (96%) rename examples/dfp/{v201708 => v201805}/base_rate_service/update_base_rates.py (99%) rename examples/dfp/{v201708/native_style_service => v201805/cdn_configuration_service}/__init__.py (100%) create mode 100755 examples/dfp/v201805/cdn_configuration_service/create_cdn_configurations.py create mode 100755 examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py rename examples/dfp/{v201708 => v201805}/company_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/company_service/create_companies.py (99%) rename examples/dfp/{v201708 => v201805}/company_service/get_advertisers.py (96%) rename examples/dfp/{v201708 => v201805}/company_service/get_all_companies.py (99%) rename examples/dfp/{v201708 => v201805}/company_service/update_companies.py (99%) rename examples/dfp/{v201708 => v201805}/contact_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/contact_service/create_contacts.py (99%) rename examples/dfp/{v201708 => v201805}/contact_service/get_all_contacts.py (99%) rename examples/dfp/{v201708 => v201805}/contact_service/get_uninvited_contacts.py (96%) rename examples/dfp/{v201708 => v201805}/contact_service/update_contacts.py (99%) rename examples/dfp/{v201708 => v201805}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/dfp/{v201708 => v201805}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (96%) rename examples/dfp/{v201708 => v201805}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (98%) rename examples/dfp/{v201708 => v201805}/content_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/content_service/get_all_content.py (99%) rename examples/dfp/{v201708 => v201805}/creative_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/creative_service/copy_image_creatives.py (99%) rename examples/dfp/{v201708 => v201805}/creative_service/create_creative_from_template.py (99%) rename examples/dfp/{v201708 => v201805}/creative_service/create_creatives.py (99%) rename examples/dfp/{v201708 => v201805}/creative_service/create_custom_creative.py (99%) rename examples/dfp/{v201708 => v201805}/creative_service/create_native_creative.py (95%) rename examples/dfp/{v201708 => v201805}/creative_service/get_all_creatives.py (99%) rename examples/dfp/{v201708 => v201805}/creative_service/get_image_creatives.py (96%) rename examples/dfp/{v201708 => v201805}/creative_service/update_creatives.py (97%) rename examples/dfp/{v201708 => v201805}/creative_set_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/dfp/{v201708 => v201805}/creative_set_service/create_creative_set.py (97%) rename examples/dfp/{v201708 => v201805}/creative_set_service/get_all_creative_sets.py (97%) rename examples/dfp/{v201708 => v201805}/creative_set_service/get_creative_sets_for_master_creative.py (95%) rename examples/dfp/{v201708 => v201805}/creative_set_service/update_creative_set.py (97%) rename examples/dfp/{v201708 => v201805}/creative_template_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/creative_template_service/get_all_creative_templates.py (97%) rename examples/dfp/{v201708 => v201805}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/dfp/{v201708 => v201805}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/dfp/{v201708 => v201805}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/dfp/{v201708 => v201805}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/dfp/{v201708 => v201805}/creative_wrapper_service/get_all_creative_wrappers.py (97%) rename examples/dfp/{v201708 => v201805}/creative_wrapper_service/update_creative_wrappers.py (97%) rename examples/dfp/{v201708 => v201805}/custom_field_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/custom_field_service/create_custom_field_options.py (97%) rename examples/dfp/{v201708 => v201805}/custom_field_service/create_custom_fields.py (97%) rename examples/dfp/{v201708 => v201805}/custom_field_service/deactivate_all_line_item_custom_fields.py (96%) rename examples/dfp/{v201708 => v201805}/custom_field_service/get_all_custom_fields.py (97%) rename examples/dfp/{v201708 => v201805}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/dfp/{v201708 => v201805}/custom_field_service/set_line_item_custom_field_value.py (82%) rename examples/dfp/{v201708 => v201805}/custom_field_service/update_custom_fields.py (98%) rename examples/dfp/{v201708 => v201805}/custom_targeting_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201708 => v201805}/custom_targeting_service/delete_custom_targeting_keys.py (91%) rename examples/dfp/{v201708 => v201805}/custom_targeting_service/delete_custom_targeting_values.py (81%) rename examples/dfp/{v201708 => v201805}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (90%) rename examples/dfp/{v201708 => v201805}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (98%) rename examples/dfp/{v201708 => v201805}/custom_targeting_service/update_custom_targeting_keys.py (97%) rename examples/dfp/{v201708 => v201805}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/dfp/{v201708 => v201805}/exchange_rate_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/dfp/{v201708 => v201805}/exchange_rate_service/get_all_exchange_rates.py (97%) rename examples/dfp/{v201708 => v201805}/exchange_rate_service/get_exchange_rates_for_currency_code.py (95%) rename examples/dfp/{v201708 => v201805}/exchange_rate_service/update_exchange_rates.py (97%) rename examples/dfp/{v201708 => v201805}/forecast_service/get_availability_forecast.py (99%) rename examples/dfp/{v201708 => v201805}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/dfp/{v201708 => v201805}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/dfp/{v201708 => v201805}/inventory_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/inventory_service/archive_ad_units.py (97%) rename examples/dfp/{v201708 => v201805}/inventory_service/create_ad_units.py (99%) create mode 100755 examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py rename examples/dfp/{v201708 => v201805}/inventory_service/get_all_ad_unit_sizes.py (94%) rename examples/dfp/{v201708 => v201805}/inventory_service/get_all_ad_units.py (99%) create mode 100755 examples/dfp/v201805/inventory_service/get_top_level_ad_units.py rename examples/dfp/{v201708 => v201805}/inventory_service/update_ad_units.py (99%) rename examples/dfp/{v201708 => v201805}/label_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/label_service/create_labels.py (99%) rename examples/dfp/{v201708 => v201805}/label_service/deactivate_labels.py (97%) rename examples/dfp/{v201708 => v201805}/label_service/get_active_labels.py (96%) rename examples/dfp/{v201708 => v201805}/label_service/get_all_labels.py (99%) rename examples/dfp/{v201708 => v201805}/label_service/update_labels.py (99%) rename examples/dfp/{v201708 => v201805}/line_item_creative_association_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/line_item_creative_association_service/create_licas.py (96%) rename examples/dfp/{v201708 => v201805}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/dfp/{v201708 => v201805}/line_item_creative_association_service/get_all_licas.py (97%) rename examples/dfp/{v201708 => v201805}/line_item_creative_association_service/get_licas_for_line_item.py (95%) rename examples/dfp/{v201708 => v201805}/line_item_creative_association_service/update_licas.py (97%) rename examples/dfp/{v201708 => v201805}/line_item_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/line_item_service/activate_line_items.py (97%) rename examples/dfp/{v201708 => v201805}/line_item_service/create_line_items.py (99%) rename examples/dfp/{v201708 => v201805}/line_item_service/create_video_line_item.py (99%) rename examples/dfp/{v201708 => v201805}/line_item_service/get_all_line_items.py (99%) rename examples/dfp/{v201708 => v201805}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/dfp/{v201708 => v201805}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/dfp/{v201708 => v201805}/line_item_service/pause_line_items.py (99%) rename examples/dfp/{v201708 => v201805}/line_item_service/target_custom_criteria.py (99%) rename examples/dfp/{v201708 => v201805}/line_item_service/update_line_items.py (99%) rename examples/dfp/{v201708 => v201805}/live_stream_event_service/activate_live_stream_events.py (97%) rename examples/dfp/{v201708 => v201805}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/dfp/{v201708 => v201805}/live_stream_event_service/get_all_live_stream_events.py (97%) rename examples/dfp/{v201708 => v201805}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/dfp/{v201708 => v201805}/live_stream_event_service/update_live_stream_events.py (97%) create mode 100755 examples/dfp/v201805/native_style_service/__init__.py rename examples/dfp/{v201708 => v201805}/native_style_service/create_native_styles.py (98%) rename examples/dfp/{v201708 => v201805}/native_style_service/get_all_native_styles.py (96%) rename examples/dfp/{v201708 => v201805}/network_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/network_service/get_all_networks.py (99%) create mode 100755 examples/dfp/v201805/network_service/get_current_network.py rename examples/dfp/{v201708 => v201805}/network_service/make_test_network.py (99%) rename examples/dfp/{v201708 => v201805}/order_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/order_service/approve_orders.py (97%) rename examples/dfp/{v201708 => v201805}/order_service/create_orders.py (99%) rename examples/dfp/{v201708 => v201805}/order_service/get_all_orders.py (99%) rename examples/dfp/{v201708 => v201805}/order_service/get_orders_starting_soon.py (97%) rename examples/dfp/{v201708 => v201805}/order_service/update_orders.py (99%) rename examples/dfp/{v201708 => v201805}/package_service/create_packages.py (99%) rename examples/dfp/{v201708 => v201805}/package_service/create_proposal_line_items_from_packages.py (99%) rename examples/dfp/{v201708 => v201805}/package_service/get_all_packages.py (99%) rename examples/dfp/{v201708 => v201805}/package_service/get_in_progress_packages.py (96%) rename examples/dfp/{v201708 => v201805}/placement_service/create_placements.py (99%) rename examples/dfp/{v201708 => v201805}/placement_service/deactivate_placements.py (99%) rename examples/dfp/{v201708 => v201805}/placement_service/get_active_placements.py (96%) rename examples/dfp/{v201708 => v201805}/placement_service/get_all_placements.py (99%) rename examples/dfp/{v201708 => v201805}/placement_service/update_placements.py (99%) rename examples/dfp/{v201708 => v201805}/premium_rate_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/premium_rate_service/create_premium_rates.py (97%) rename examples/dfp/{v201708 => v201805}/premium_rate_service/get_all_premium_rates.py (97%) rename examples/dfp/{v201708 => v201805}/premium_rate_service/get_premium_rates_for_rate_card.py (95%) rename examples/dfp/{v201708 => v201805}/premium_rate_service/update_premium_rates.py (97%) rename examples/dfp/{v201708 => v201805}/product_package_item_service/create_product_package_item.py (99%) rename examples/dfp/{v201708 => v201805}/product_package_item_service/get_all_product_package_items.py (97%) rename examples/dfp/{v201708 => v201805}/product_package_item_service/get_product_package_items_for_product_package.py (95%) rename examples/dfp/{v201708 => v201805}/product_package_service/create_product_packages.py (96%) rename examples/dfp/{v201708 => v201805}/product_package_service/get_active_product_packages.py (94%) rename examples/dfp/{v201708 => v201805}/product_package_service/get_all_product_packages.py (97%) rename examples/dfp/{v201708 => v201805}/product_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/product_service/get_all_products.py (99%) rename examples/dfp/{v201708 => v201805}/product_service/get_products_for_product_template.py (96%) rename examples/dfp/{v201708 => v201805}/product_service/update_products.py (99%) rename examples/dfp/{v201708 => v201805}/product_template_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/product_template_service/activate_product_templates.py (95%) rename examples/dfp/{v201708 => v201805}/product_template_service/create_product_templates.py (97%) rename examples/dfp/{v201708 => v201805}/product_template_service/create_programmatic_product_templates.py (96%) rename examples/dfp/{v201708 => v201805}/product_template_service/get_all_product_templates.py (97%) rename examples/dfp/{v201708 => v201805}/product_template_service/get_sponsorship_product_templates.py (94%) rename examples/dfp/{v201708 => v201805}/product_template_service/update_product_templates.py (98%) rename examples/dfp/{v201708 => v201805}/proposal_line_item_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/proposal_line_item_service/archive_proposal_line_items.py (96%) rename examples/dfp/{v201708 => v201805}/proposal_line_item_service/create_programmatic_proposal_line_items.py (98%) rename examples/dfp/{v201708 => v201805}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (98%) rename examples/dfp/{v201708 => v201805}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/dfp/{v201708 => v201805}/proposal_line_item_service/get_all_proposal_line_items.py (97%) rename examples/dfp/{v201708 => v201805}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/dfp/{v201708 => v201805}/proposal_line_item_service/update_proposal_line_items.py (97%) rename examples/dfp/{v201708 => v201805}/proposal_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/proposal_service/create_programmatic_proposals.py (98%) rename examples/dfp/{v201708 => v201805}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (99%) rename examples/dfp/{v201708 => v201805}/proposal_service/create_proposals.py (99%) rename examples/dfp/{v201708 => v201805}/proposal_service/get_all_proposals.py (99%) rename examples/dfp/{v201708 => v201805}/proposal_service/get_marketplace_comments.py (97%) rename examples/dfp/{v201708 => v201805}/proposal_service/get_proposals_pending_approval.py (96%) rename examples/dfp/{v201708 => v201805}/proposal_service/request_buyers_acceptance.py (97%) rename examples/dfp/{v201708 => v201805}/proposal_service/submit_proposals_for_approval.py (97%) rename examples/dfp/{v201708 => v201805}/proposal_service/update_proposals.py (99%) rename examples/dfp/{v201708 => v201805}/publisher_query_language_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/publisher_query_language_service/fetch_match_tables.py (96%) create mode 100755 examples/dfp/v201805/publisher_query_language_service/get_all_browsers.py rename examples/dfp/{v201708 => v201805}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) create mode 100755 examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py create mode 100755 examples/dfp/v201805/publisher_query_language_service/get_line_items_named_like.py rename examples/dfp/{v201708 => v201805}/publisher_query_language_service/get_recent_changes.py (99%) rename examples/dfp/{v201708 => v201805}/rate_card_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/rate_card_service/create_rate_cards.py (99%) rename examples/dfp/{v201708 => v201805}/rate_card_service/get_all_rate_cards.py (99%) rename examples/dfp/{v201708 => v201805}/rate_card_service/get_marketplace_rate_cards.py (96%) rename examples/dfp/{v201708 => v201805}/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (97%) rename examples/dfp/{v201708 => v201805}/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (97%) rename examples/dfp/{v201708 => v201805}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (95%) rename examples/dfp/{v201708 => v201805}/reconciliation_order_report_service/submit_reconciliation_order_reports.py (97%) rename examples/dfp/{v201708 => v201805}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (95%) rename examples/dfp/{v201708 => v201805}/reconciliation_report_row_service/update_reconciliation_report_rows.py (97%) rename examples/dfp/{v201708 => v201805}/reconciliation_report_service/get_all_reconciliation_reports.py (97%) rename examples/dfp/{v201708 => v201805}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (95%) rename examples/dfp/{v201708 => v201805}/report_service/__init__.py (100%) create mode 100755 examples/dfp/v201805/report_service/run_ad_exchange_report.py rename examples/dfp/{v201708 => v201805}/report_service/run_delivery_report.py (97%) rename examples/dfp/{v201708 => v201805}/report_service/run_inventory_report.py (97%) rename examples/dfp/{v201708 => v201805}/report_service/run_reach_report.py (96%) rename examples/dfp/{v201708 => v201805}/report_service/run_report_and_create_match_table.py (97%) rename examples/dfp/{v201708 => v201805}/report_service/run_report_with_custom_fields.py (95%) rename examples/dfp/{v201708 => v201805}/report_service/run_sales_report.py (96%) rename examples/dfp/{v201708 => v201805}/report_service/run_saved_query.py (97%) rename examples/dfp/{v201708 => v201805}/suggested_ad_unit_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (88%) rename examples/dfp/{v201708 => v201805}/suggested_ad_unit_service/get_all_suggested_ad_units.py (97%) rename examples/dfp/{v201708 => v201805}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (95%) rename examples/dfp/{v201708 => v201805}/team_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/team_service/create_teams.py (96%) rename examples/dfp/{v201708 => v201805}/team_service/get_all_teams.py (95%) rename examples/dfp/{v201708 => v201805}/team_service/update_teams.py (96%) rename examples/dfp/{v201708 => v201805}/user_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/user_service/create_users.py (95%) rename examples/dfp/{v201708 => v201805}/user_service/deactivate_users.py (96%) rename examples/dfp/{v201708 => v201805}/user_service/get_all_roles.py (100%) rename examples/dfp/{v201708 => v201805}/user_service/get_all_users.py (95%) rename examples/dfp/{v201708 => v201805}/user_service/get_current_user.py (94%) rename examples/dfp/{v201708 => v201805}/user_service/get_user_by_email_address.py (93%) rename examples/dfp/{v201708 => v201805}/user_service/update_users.py (96%) rename examples/dfp/{v201708 => v201805}/user_team_association_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/user_team_association_service/create_user_team_associations.py (97%) rename examples/dfp/{v201708 => v201805}/user_team_association_service/delete_user_team_associations.py (97%) rename examples/dfp/{v201708 => v201805}/user_team_association_service/get_all_user_team_associations.py (97%) rename examples/dfp/{v201708 => v201805}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/dfp/{v201708 => v201805}/user_team_association_service/update_user_team_associations.py (98%) rename examples/dfp/{v201708 => v201805}/workflow_request_service/__init__.py (100%) rename examples/dfp/{v201708 => v201805}/workflow_request_service/approve_workflow_approval_requests.py (95%) rename examples/dfp/{v201708 => v201805}/workflow_request_service/get_workflow_approval_requests.py (95%) rename examples/dfp/{v201708 => v201805}/workflow_request_service/get_workflow_external_condition_requests.py (95%) rename examples/dfp/{v201708 => v201805}/workflow_request_service/trigger_workflow_external_condition_requests.py (96%) diff --git a/ChangeLog b/ChangeLog index 31f4bdd8..1564409f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,15 @@ +12.0.0 -- 05/15/18 +* Added support and examples for DFP v201805. +* Removed support for DFP v201705. +* Removed examples for DFP v201708. +* Using the wrong cache type will now raise GoogleAdsValueError instead of ValueError. +* Added support for setting custom HTTP headers. +* Resolved issues: +- Issue 246: https://github.com/googleads/googleads-python-lib/issues/246 +- Issue 262: https://github.com/googleads/googleads-python-lib/issues/262 +- Issue 273: https://github.com/googleads/googleads-python-lib/issues/273 +- Issue 250: https://github.com/googleads/googleads-python-lib/issues/250 + 11.0.1 -- 04/06/18 * Fixed bug related to creating types from services that contain multiple schemas. diff --git a/examples/adwords/adwords_appengine_demo/ChangeLog b/examples/adwords/adwords_appengine_demo/ChangeLog index ba2a6c7c..122ba206 100644 --- a/examples/adwords/adwords_appengine_demo/ChangeLog +++ b/examples/adwords/adwords_appengine_demo/ChangeLog @@ -1,3 +1,7 @@ +1.0.3 -- 5/15/18: +- Fixed issue #273: + https://github.com/googleads/googleads-python-lib/issues/273 + 1.0.2 -- 6/21/16: - Fixed issue #171: https://github.com/googleads/googleads-python-lib/issues/171 diff --git a/examples/adwords/adwords_appengine_demo/app.yaml b/examples/adwords/adwords_appengine_demo/app.yaml index 021ea8b9..9f42af24 100644 --- a/examples/adwords/adwords_appengine_demo/app.yaml +++ b/examples/adwords/adwords_appengine_demo/app.yaml @@ -16,3 +16,5 @@ handlers: libraries: - name: ssl version: latest +- name: lxml + version: latest diff --git a/examples/adwords/adwords_appengine_demo/appengine_config.py b/examples/adwords/adwords_appengine_demo/appengine_config.py index 3df1ea8e..80144509 100755 --- a/examples/adwords/adwords_appengine_demo/appengine_config.py +++ b/examples/adwords/adwords_appengine_demo/appengine_config.py @@ -22,4 +22,3 @@ # Add any libraries installed in the "lib" folder to the path. vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')) - diff --git a/examples/adwords/adwords_appengine_demo/demo/__init__.py b/examples/adwords/adwords_appengine_demo/demo/__init__.py index edf49e56..cb442cd4 100755 --- a/examples/adwords/adwords_appengine_demo/demo/__init__.py +++ b/examples/adwords/adwords_appengine_demo/demo/__init__.py @@ -16,4 +16,4 @@ """AdWords App Engine demo web application.""" DEBUG = False # Enable to see debug logs in the App Engine console. -VERSION = '1.0.0' +VERSION = '1.0.3' diff --git a/examples/adwords/adwords_appengine_demo/demo/main.py b/examples/adwords/adwords_appengine_demo/demo/main.py index 1dfb904c..466a788c 100755 --- a/examples/adwords/adwords_appengine_demo/demo/main.py +++ b/examples/adwords/adwords_appengine_demo/demo/main.py @@ -20,6 +20,7 @@ from demo import DEBUG +from requests_toolbelt.adapters import appengine from views import AddAdGroup from views import AddCampaign from views import InitView @@ -32,6 +33,8 @@ from views import UpdateCredentials import webapp2 +# Patch requests library for use on App Engine. +appengine.monkeypatch() app = webapp2.WSGIApplication([('/', InitView), ('/showCredentials', ShowCredentials), diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index 83a7c1cb..29e86706 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -21,9 +21,9 @@ from demo import VERSION from googleads.adwords import AdWordsClient +from googleads.common import ZeepServiceProxy from googleads.errors import GoogleAdsError from googleads.oauth2 import GoogleRefreshTokenClient -from suds.cache import NoCache class APIHandler(object): @@ -47,7 +47,7 @@ def __init__(self, client_id, client_secret, refresh_token, refresh_token) self.client = AdWordsClient(dev_token, credentials, self._USER_AGENT, client_customer_id=manager_account_id, - cache=NoCache()) + cache=ZeepServiceProxy.NO_CACHE) def AddAdGroup(self, client_customer_id, campaign_id, name, status): """Create a new ad group. diff --git a/examples/adwords/adwords_appengine_demo/requirements.txt b/examples/adwords/adwords_appengine_demo/requirements.txt index 92408dbf..64e96f18 100644 --- a/examples/adwords/adwords_appengine_demo/requirements.txt +++ b/examples/adwords/adwords_appengine_demo/requirements.txt @@ -1 +1 @@ -googleads==10.1.1 +googleads==12.0.0 diff --git a/examples/adwords/v201710/basic_operations/get_campaigns.py b/examples/adwords/v201710/basic_operations/get_campaigns.py index 3d540ad4..01c017d3 100755 --- a/examples/adwords/v201710/basic_operations/get_campaigns.py +++ b/examples/adwords/v201710/basic_operations/get_campaigns.py @@ -26,12 +26,8 @@ """ -import logging from googleads import adwords -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - PAGE_SIZE = 100 diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py index 6bd15e45..aa1294e9 100755 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py @@ -26,16 +26,11 @@ """ -import logging import StringIO import sys from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - # Specify where to download the file here. PATH = '/tmp/report_download.csv' # The chunk size used for the report download. diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py index 0c453b81..f83a49c6 100755 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py @@ -26,15 +26,10 @@ """ -import logging import StringIO import sys from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - # The chunk size used for the report download. CHUNK_SIZE = 16 * 1024 diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py index 536d32d7..b947dfb9 100755 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py @@ -26,12 +26,8 @@ """ -import logging from googleads import adwords -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - def main(client): report_downloader = client.GetReportDownloader(version='v201710') diff --git a/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py index 0e262215..dfd83fec 100755 --- a/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py +++ b/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py @@ -26,13 +26,9 @@ """ -import logging import sys from googleads import adwords -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - def main(client): report_downloader = client.GetReportDownloader(version='v201710') diff --git a/examples/adwords/v201710/reporting/parallel_report_download.py b/examples/adwords/v201710/reporting/parallel_report_download.py index 0f916494..3734b53a 100755 --- a/examples/adwords/v201710/reporting/parallel_report_download.py +++ b/examples/adwords/v201710/reporting/parallel_report_download.py @@ -22,17 +22,15 @@ "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. - """ -import logging import multiprocessing +import os from Queue import Empty import time -import googleads -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) +import googleads.adwords +import googleads.errors # Timeout between retries in seconds. BACKOFF_FACTOR = 5 @@ -46,76 +44,61 @@ REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) +def _DownloadReport(process_id, report_download_directory, customer_id, + report_definition): + """Helper function used by ReportWorker to download customer report. - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] + Note that multiprocessing differs between Windows / Unix environments. A + Process or its subclasses in Windows must be serializable with pickle, but + that is not possible for AdWordsClient or ReportDownloader. This top-level + function is used as a work-around for Windows support. - for process in processes: - process.start() + Args: + process_id: The PID of the process downloading the report. + report_download_directory: A string indicating the directory where you + would like to download the reports. + customer_id: A str AdWords customer ID for which the report is being + downloaded. + report_definition: A dict containing the report definition to be used. - for process in processes: - process.join() + Returns: + A tuple indicating a boolean success/failure status, and dict request + context. + """ + report_downloader = (googleads.adwords.AdWordsClient.LoadFromStorage() + .GetReportDownloader()) - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + filepath = os.path.join(report_download_directory, + 'adgroup_%d.csv' % customer_id) + retry_count = 0 while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (process_id, retry_count, customer_id, filepath)) try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) + with open(filepath, 'wb') as handler: + report_downloader.DownloadReport( + report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError as e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) class ReportWorker(multiprocessing.Process): """A worker Process used to download reports for a set of customer IDs.""" - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, + def __init__(self, report_download_directory, report_definition, input_queue, success_queue, failure_queue): """Initializes a ReportWorker. Args: - client: An AdWordsClient instance. report_download_directory: A string indicating the directory where you would like to download the reports. report_definition: A dict containing the report definition that you would @@ -128,48 +111,20 @@ def __init__(self, client, report_download_directory, report_definition, downloads will be saved to. """ super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201710') self.report_download_directory = report_download_directory self.report_definition = report_definition self.input_queue = input_queue self.success_queue = success_queue self.failure_queue = failure_queue - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - def run(self): while True: try: customer_id = self.input_queue.get(timeout=0.01) except Empty: break - result = self._DownloadReport(customer_id) + result = _DownloadReport(self.ident, self.report_download_directory, + customer_id, self.report_definition) (self.success_queue if result[0] else self.failure_queue).put(result[1]) @@ -181,10 +136,8 @@ def GetCustomerIDs(client): Args: client: an AdWordsClient instance. - Raises: Exception: if no CustomerIds could be found. - Returns: A Queue instance containing all CustomerIds in the account hierarchy. """ @@ -196,15 +149,18 @@ def GetCustomerIDs(client): offset = 0 # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} + selector = { + 'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } # Using Queue to balance load between processes. queue = multiprocessing.Queue() @@ -225,6 +181,64 @@ def GetCustomerIDs(client): return queue +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + if __name__ == '__main__': adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201802/basic_operations/get_campaigns.py b/examples/adwords/v201802/basic_operations/get_campaigns.py index 5a67c342..a4169de6 100755 --- a/examples/adwords/v201802/basic_operations/get_campaigns.py +++ b/examples/adwords/v201802/basic_operations/get_campaigns.py @@ -26,12 +26,8 @@ """ -import logging from googleads import adwords -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - PAGE_SIZE = 100 diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py index 3266a5a5..fce40cd5 100755 --- a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py @@ -26,16 +26,11 @@ """ -import logging import StringIO import sys from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - # Specify where to download the file here. PATH = '/tmp/report_download.csv' # The chunk size used for the report download. diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py index 9525feb1..80276d22 100755 --- a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py @@ -26,15 +26,10 @@ """ -import logging import StringIO import sys from googleads import adwords - -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - # The chunk size used for the report download. CHUNK_SIZE = 16 * 1024 diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py index 64f72313..47f71143 100755 --- a/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py @@ -26,12 +26,8 @@ """ -import logging from googleads import adwords -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - def main(client): report_downloader = client.GetReportDownloader(version='v201802') diff --git a/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py index dc38faba..b457899e 100755 --- a/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py +++ b/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py @@ -26,13 +26,9 @@ """ -import logging import sys from googleads import adwords -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) - def main(client): report_downloader = client.GetReportDownloader(version='v201802') diff --git a/examples/adwords/v201802/reporting/parallel_report_download.py b/examples/adwords/v201802/reporting/parallel_report_download.py index c5d284c3..f34b2f31 100755 --- a/examples/adwords/v201802/reporting/parallel_report_download.py +++ b/examples/adwords/v201802/reporting/parallel_report_download.py @@ -22,17 +22,15 @@ "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. - """ -import logging import multiprocessing +import os from Queue import Empty import time -import googleads -logging.basicConfig(level=logging.INFO) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) +import googleads.adwords +import googleads.errors # Timeout between retries in seconds. BACKOFF_FACTOR = 5 @@ -46,76 +44,61 @@ REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) +def _DownloadReport(process_id, report_download_directory, customer_id, + report_definition): + """Helper function used by ReportWorker to download customer report. - # Start all the processes. - processes = [ReportWorker(client, report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] + Note that multiprocessing differs between Windows / Unix environments. A + Process or its subclasses in Windows must be serializable with pickle, but + that is not possible for AdWordsClient or ReportDownloader. This top-level + function is used as a work-around for Windows support. - for process in processes: - process.start() + Args: + process_id: The PID of the process downloading the report. + report_download_directory: A string indicating the directory where you + would like to download the reports. + customer_id: A str AdWords customer ID for which the report is being + downloaded. + report_definition: A dict containing the report definition to be used. - for process in processes: - process.join() + Returns: + A tuple indicating a boolean success/failure status, and dict request + context. + """ + report_downloader = (googleads.adwords.AdWordsClient.LoadFromStorage() + .GetReportDownloader()) - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + filepath = os.path.join(report_download_directory, + 'adgroup_%d.csv' % customer_id) + retry_count = 0 while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (process_id, retry_count, customer_id, filepath)) try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) + with open(filepath, 'wb') as handler: + report_downloader.DownloadReport( + report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError as e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) class ReportWorker(multiprocessing.Process): """A worker Process used to download reports for a set of customer IDs.""" - _FILENAME_TEMPLATE = 'adgroup_%d.csv' - _FILEPATH_TEMPLATE = '%s/%s' - - def __init__(self, client, report_download_directory, report_definition, + def __init__(self, report_download_directory, report_definition, input_queue, success_queue, failure_queue): """Initializes a ReportWorker. Args: - client: An AdWordsClient instance. report_download_directory: A string indicating the directory where you would like to download the reports. report_definition: A dict containing the report definition that you would @@ -128,48 +111,20 @@ def __init__(self, client, report_download_directory, report_definition, downloads will be saved to. """ super(ReportWorker, self).__init__() - self.report_downloader = client.GetReportDownloader(version='v201802') self.report_download_directory = report_download_directory self.report_definition = report_definition self.input_queue = input_queue self.success_queue = success_queue self.failure_queue = failure_queue - def _DownloadReport(self, customer_id): - filepath = self._FILEPATH_TEMPLATE % (self.report_download_directory, - self._FILENAME_TEMPLATE % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (self.ident, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - self.report_downloader.DownloadReport( - self.report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError, e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - except Exception, e: - print 'Report failed for customer ID "%s".' % customer_id - print 'e: %s' % e.__class__ - return (False, {'customerId': customer_id, 'code': None, - 'message': e.message}) - def run(self): while True: try: customer_id = self.input_queue.get(timeout=0.01) except Empty: break - result = self._DownloadReport(customer_id) + result = _DownloadReport(self.ident, self.report_download_directory, + customer_id, self.report_definition) (self.success_queue if result[0] else self.failure_queue).put(result[1]) @@ -181,10 +136,8 @@ def GetCustomerIDs(client): Args: client: an AdWordsClient instance. - Raises: Exception: if no CustomerIds could be found. - Returns: A Queue instance containing all CustomerIds in the account hierarchy. """ @@ -196,15 +149,18 @@ def GetCustomerIDs(client): offset = 0 # Get the account hierarchy for this account. - selector = {'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE)}} + selector = { + 'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } # Using Queue to balance load between processes. queue = multiprocessing.Queue() @@ -225,6 +181,64 @@ def GetCustomerIDs(client): return queue +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + if __name__ == '__main__': adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py deleted file mode 100755 index 54e36cb6..00000000 --- a/examples/dfp/v201708/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example deletes content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the content metadata key hierarchy to delete. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') - - -def main(client, content_metadata_key_hierarchy_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201708') - - # Create a query to select a single content metadata key hierarchy. - - statement = (dfp.StatementBuilder() - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) - .Limit(1)) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())[0]) - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - # Display results. - if content_metadata_key_hierarchies: - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with ID "%s" and name "%s" ' - 'will be deleted.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - # Perform action. - result = (content_metadata_key_hierarchy_service - .performContentMetadataKeyHierarchyAction( - {'type': 'DeleteContentMetadataKeyHierarchies'}, - statement.ToStatement()))[0] - - # Display results. - print ('Number of content metadata key hierarchies deleted: %s' % - result['numChanges']) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID) diff --git a/examples/dfp/v201708/activity_group_service/__init__.py b/examples/dfp/v201805/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201708/activity_group_service/__init__.py rename to examples/dfp/v201805/activity_group_service/__init__.py diff --git a/examples/dfp/v201708/activity_group_service/create_activity_groups.py b/examples/dfp/v201805/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/dfp/v201708/activity_group_service/create_activity_groups.py rename to examples/dfp/v201805/activity_group_service/create_activity_groups.py index 88ab5d56..022cd7c2 100755 --- a/examples/dfp/v201708/activity_group_service/create_activity_groups.py +++ b/examples/dfp/v201805/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201708') + version='v201805') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201805/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/dfp/v201708/activity_group_service/get_active_activity_groups.py rename to examples/dfp/v201805/activity_group_service/get_active_activity_groups.py index b27e5d58..39873e5b 100755 --- a/examples/dfp/v201708/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201805/activity_group_service/get_active_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201708') + 'ActivityGroupService', version='v201805') # Create a statement to select activity groups. statement = (dfp.StatementBuilder() .Where('status = :status') @@ -39,7 +39,7 @@ def main(client): # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201805/activity_group_service/get_all_activity_groups.py similarity index 97% rename from examples/dfp/v201708/activity_group_service/get_all_activity_groups.py rename to examples/dfp/v201805/activity_group_service/get_all_activity_groups.py index 0f62b15d..6e9a1947 100755 --- a/examples/dfp/v201708/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201805/activity_group_service/get_all_activity_groups.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201708') + 'ActivityGroupService', version='v201805') # Create a statement to select activity groups. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/activity_group_service/update_activity_groups.py b/examples/dfp/v201805/activity_group_service/update_activity_groups.py similarity index 97% rename from examples/dfp/v201708/activity_group_service/update_activity_groups.py rename to examples/dfp/v201805/activity_group_service/update_activity_groups.py index 7d8fd136..0a5f87f9 100755 --- a/examples/dfp/v201708/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201805/activity_group_service/update_activity_groups.py @@ -37,7 +37,7 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201708') + version='v201805') # Create statement object to select a single activity groups by ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/activity_service/__init__.py b/examples/dfp/v201805/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201708/activity_service/__init__.py rename to examples/dfp/v201805/activity_service/__init__.py diff --git a/examples/dfp/v201708/activity_service/create_activities.py b/examples/dfp/v201805/activity_service/create_activities.py similarity index 99% rename from examples/dfp/v201708/activity_service/create_activities.py rename to examples/dfp/v201805/activity_service/create_activities.py index 445d68a1..8d16515e 100755 --- a/examples/dfp/v201708/activity_service/create_activities.py +++ b/examples/dfp/v201805/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201708') + activity_service = client.GetService('ActivityService', version='v201805') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/dfp/v201708/activity_service/get_active_activities.py b/examples/dfp/v201805/activity_service/get_active_activities.py similarity index 96% rename from examples/dfp/v201708/activity_service/get_active_activities.py rename to examples/dfp/v201805/activity_service/get_active_activities.py index 94d18be9..6de67205 100755 --- a/examples/dfp/v201708/activity_service/get_active_activities.py +++ b/examples/dfp/v201805/activity_service/get_active_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201708') + activity_service = client.GetService('ActivityService', version='v201805') # Create a statement to select activities. statement = (dfp.StatementBuilder() .Where('status = :status') @@ -38,7 +38,7 @@ def main(client): # Print out some information for each activity. print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % (activity['id'], activity['name'], activity['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/activity_service/get_all_activities.py b/examples/dfp/v201805/activity_service/get_all_activities.py similarity index 99% rename from examples/dfp/v201708/activity_service/get_all_activities.py rename to examples/dfp/v201805/activity_service/get_all_activities.py index 004a61cb..8cb0ffe1 100755 --- a/examples/dfp/v201708/activity_service/get_all_activities.py +++ b/examples/dfp/v201805/activity_service/get_all_activities.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201708') + activity_service = client.GetService('ActivityService', version='v201805') # Create a statement to select activities. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/activity_service/update_activities.py b/examples/dfp/v201805/activity_service/update_activities.py similarity index 99% rename from examples/dfp/v201708/activity_service/update_activities.py rename to examples/dfp/v201805/activity_service/update_activities.py index 851a411e..95007511 100755 --- a/examples/dfp/v201708/activity_service/update_activities.py +++ b/examples/dfp/v201805/activity_service/update_activities.py @@ -35,7 +35,7 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201708') + activity_service = client.GetService('ActivityService', version='v201805') # Create statement object to select one activity by ID to update. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/audience_segment_service/__init__.py b/examples/dfp/v201805/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201708/audience_segment_service/__init__.py rename to examples/dfp/v201805/audience_segment_service/__init__.py diff --git a/examples/dfp/v201708/audience_segment_service/create_audience_segments.py b/examples/dfp/v201805/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/dfp/v201708/audience_segment_service/create_audience_segments.py rename to examples/dfp/v201805/audience_segment_service/create_audience_segments.py index 6c43175a..becf3ce0 100755 --- a/examples/dfp/v201708/audience_segment_service/create_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') + 'AudienceSegmentService', version='v201805') + network_service = client.GetService('NetworkService', version='v201805') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/dfp/v201708/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py similarity index 97% rename from examples/dfp/v201708/audience_segment_service/get_all_audience_segments.py rename to examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py index 95f5cff5..412b91e2 100755 --- a/examples/dfp/v201708/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201708') + 'AudienceSegmentService', version='v201805') # Create a statement to select audience segments. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py rename to examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py index a7bf8ee2..6e68f588 100755 --- a/examples/dfp/v201708/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201708') + 'AudienceSegmentService', version='v201805') # Create a statement to select audience segments. statement = (dfp.StatementBuilder() .Where('type = :type') @@ -40,7 +40,7 @@ def main(client): print('Audience segment with ID "%d", name "%s", and size "%d" was ' 'found.\n' % (audience_segment['id'], audience_segment['name'], audience_segment['size'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py similarity index 97% rename from examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py rename to examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py index 1f74c70a..e0c2a855 100755 --- a/examples/dfp/v201708/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py @@ -30,7 +30,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201708') + 'AudienceSegmentService', version='v201805') # Create statement object to get the specified first party audience segment. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/audience_segment_service/update_audience_segments.py b/examples/dfp/v201805/audience_segment_service/update_audience_segments.py similarity index 97% rename from examples/dfp/v201708/audience_segment_service/update_audience_segments.py rename to examples/dfp/v201805/audience_segment_service/update_audience_segments.py index 34270902..bf2e0980 100755 --- a/examples/dfp/v201708/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/update_audience_segments.py @@ -29,7 +29,7 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201708') + 'AudienceSegmentService', version='v201805') # Create statement object to get the specified first party audience segment. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/base_rate_service/__init__.py b/examples/dfp/v201805/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201708/base_rate_service/__init__.py rename to examples/dfp/v201805/base_rate_service/__init__.py diff --git a/examples/dfp/v201708/base_rate_service/create_product_base_rates.py b/examples/dfp/v201805/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/dfp/v201708/base_rate_service/create_product_base_rates.py rename to examples/dfp/v201805/base_rate_service/create_product_base_rates.py index 1381e5e3..0948d09f 100755 --- a/examples/dfp/v201708/base_rate_service/create_product_base_rates.py +++ b/examples/dfp/v201805/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201708') + 'BaseRateService', version='v201805') # Create a product base rate. product_base_rate = { diff --git a/examples/dfp/v201708/base_rate_service/create_product_package_item_base_rates.py b/examples/dfp/v201805/base_rate_service/create_product_package_item_base_rates.py similarity index 99% rename from examples/dfp/v201708/base_rate_service/create_product_package_item_base_rates.py rename to examples/dfp/v201805/base_rate_service/create_product_package_item_base_rates.py index 48fb04e6..50532194 100755 --- a/examples/dfp/v201708/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/dfp/v201805/base_rate_service/create_product_package_item_base_rates.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201708') + base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a base rate for a product package item. product_package_item_base_rate = { diff --git a/examples/dfp/v201708/base_rate_service/create_product_template_base_rates.py b/examples/dfp/v201805/base_rate_service/create_product_template_base_rates.py similarity index 97% rename from examples/dfp/v201708/base_rate_service/create_product_template_base_rates.py rename to examples/dfp/v201805/base_rate_service/create_product_template_base_rates.py index 47c7ac5d..4d6bbe06 100755 --- a/examples/dfp/v201708/base_rate_service/create_product_template_base_rates.py +++ b/examples/dfp/v201805/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201708') + 'BaseRateService', version='v201805') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/dfp/v201708/base_rate_service/get_all_base_rates.py b/examples/dfp/v201805/base_rate_service/get_all_base_rates.py similarity index 99% rename from examples/dfp/v201708/base_rate_service/get_all_base_rates.py rename to examples/dfp/v201805/base_rate_service/get_all_base_rates.py index fd54eae1..2835cbd5 100755 --- a/examples/dfp/v201708/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201805/base_rate_service/get_all_base_rates.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201708') + base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a statement to select base rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py similarity index 96% rename from examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py rename to examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py index f4528e2a..406a065d 100755 --- a/examples/dfp/v201708/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py @@ -24,7 +24,7 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201708') + base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a statement to select base rates. statement = (dfp.StatementBuilder() .Where('rateCardId = :rateCardId') @@ -42,7 +42,7 @@ def main(client, rate_card_id): 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), base_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/base_rate_service/update_base_rates.py b/examples/dfp/v201805/base_rate_service/update_base_rates.py similarity index 99% rename from examples/dfp/v201708/base_rate_service/update_base_rates.py rename to examples/dfp/v201805/base_rate_service/update_base_rates.py index 1d88d78f..00cb642e 100755 --- a/examples/dfp/v201708/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201805/base_rate_service/update_base_rates.py @@ -29,7 +29,7 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201708') + base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a filter statement for base rates for a single rate card. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/native_style_service/__init__.py b/examples/dfp/v201805/cdn_configuration_service/__init__.py similarity index 100% rename from examples/dfp/v201708/native_style_service/__init__.py rename to examples/dfp/v201805/cdn_configuration_service/__init__.py diff --git a/examples/dfp/v201805/cdn_configuration_service/create_cdn_configurations.py b/examples/dfp/v201805/cdn_configuration_service/create_cdn_configurations.py new file mode 100755 index 00000000..3887620e --- /dev/null +++ b/examples/dfp/v201805/cdn_configuration_service/create_cdn_configurations.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 code example creates new cdn configurations. + +To determine which configurations exist, run get_all_cdn_configurations.py. +""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201805') + + # Create cdn config objects. + # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. + configs = [{ + # Basic example with no security policies. + 'name': 'ApiConfig1', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + } + } + }, { + # Complex example with security policies. + 'name': 'ApiConfig2', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': False, + 'tokenAuthenticationKey': 'abc123', + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': True, + 'originForwardingType': 'CONVENTIONAL', + 'originPathPrefix': '/path/to/my/origin' + } + } + } + }] + + # Add configs. + configs = cdn_config_service.createCdnConfigurations(configs) + + # Display results. + for config in configs: + print('Created CDN configuration with type "%s" and name "%s".' + % (config['cdnConfigurationType'], config['name'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py b/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py new file mode 100755 index 00000000..d423e351 --- /dev/null +++ b/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 CDN configuration objects. + +Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be +returned. +""" + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201805') + + # Create a statement to select cdn configurations. + statement = dfp.StatementBuilder() + + # Retrieve a small number of configs at a time, paging + # through until all have been retrieved. + while True: + response = (cdn_config_service + .getCdnConfigurationsByStatement(statement.ToStatement())) + if 'results' in response: + for cdn in response['results']: + # Print out some information for each company. + print('Found CDN configuration with type "%s" and name "%s".' + % (cdn['cdnConfigurationType'], cdn['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/company_service/__init__.py b/examples/dfp/v201805/company_service/__init__.py similarity index 100% rename from examples/dfp/v201708/company_service/__init__.py rename to examples/dfp/v201805/company_service/__init__.py diff --git a/examples/dfp/v201708/company_service/create_companies.py b/examples/dfp/v201805/company_service/create_companies.py similarity index 99% rename from examples/dfp/v201708/company_service/create_companies.py rename to examples/dfp/v201805/company_service/create_companies.py index 2bf4d295..a638349b 100755 --- a/examples/dfp/v201708/company_service/create_companies.py +++ b/examples/dfp/v201805/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201708') + company_service = client.GetService('CompanyService', version='v201805') # Create company objects. companies = [ diff --git a/examples/dfp/v201708/company_service/get_advertisers.py b/examples/dfp/v201805/company_service/get_advertisers.py similarity index 96% rename from examples/dfp/v201708/company_service/get_advertisers.py rename to examples/dfp/v201805/company_service/get_advertisers.py index 03ea7369..b046434d 100755 --- a/examples/dfp/v201708/company_service/get_advertisers.py +++ b/examples/dfp/v201805/company_service/get_advertisers.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201708') + company_service = client.GetService('CompanyService', version='v201805') # Create a statement to select companies. statement = (dfp.StatementBuilder() .Where('type = :type') @@ -37,7 +37,7 @@ def main(client): # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/company_service/get_all_companies.py b/examples/dfp/v201805/company_service/get_all_companies.py similarity index 99% rename from examples/dfp/v201708/company_service/get_all_companies.py rename to examples/dfp/v201805/company_service/get_all_companies.py index 31598c8a..e089d9c2 100755 --- a/examples/dfp/v201708/company_service/get_all_companies.py +++ b/examples/dfp/v201805/company_service/get_all_companies.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201708') + company_service = client.GetService('CompanyService', version='v201805') # Create a statement to select companies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/company_service/update_companies.py b/examples/dfp/v201805/company_service/update_companies.py similarity index 99% rename from examples/dfp/v201708/company_service/update_companies.py rename to examples/dfp/v201805/company_service/update_companies.py index ac9399ff..9fe4af37 100755 --- a/examples/dfp/v201708/company_service/update_companies.py +++ b/examples/dfp/v201805/company_service/update_companies.py @@ -35,7 +35,7 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201708') + company_service = client.GetService('CompanyService', version='v201805') # Create statement object to only select a single company by ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/contact_service/__init__.py b/examples/dfp/v201805/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201708/contact_service/__init__.py rename to examples/dfp/v201805/contact_service/__init__.py diff --git a/examples/dfp/v201708/contact_service/create_contacts.py b/examples/dfp/v201805/contact_service/create_contacts.py similarity index 99% rename from examples/dfp/v201708/contact_service/create_contacts.py rename to examples/dfp/v201805/contact_service/create_contacts.py index feb24480..e7bd1718 100755 --- a/examples/dfp/v201708/contact_service/create_contacts.py +++ b/examples/dfp/v201805/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201708') + contact_service = client.GetService('ContactService', version='v201805') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/dfp/v201708/contact_service/get_all_contacts.py b/examples/dfp/v201805/contact_service/get_all_contacts.py similarity index 99% rename from examples/dfp/v201708/contact_service/get_all_contacts.py rename to examples/dfp/v201805/contact_service/get_all_contacts.py index 0b3d94ef..780c4d2b 100755 --- a/examples/dfp/v201708/contact_service/get_all_contacts.py +++ b/examples/dfp/v201805/contact_service/get_all_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201708') + contact_service = client.GetService('ContactService', version='v201805') # Create a statement to select contacts. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/contact_service/get_uninvited_contacts.py b/examples/dfp/v201805/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/dfp/v201708/contact_service/get_uninvited_contacts.py rename to examples/dfp/v201805/contact_service/get_uninvited_contacts.py index e67bd402..04d8f1e6 100755 --- a/examples/dfp/v201708/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201805/contact_service/get_uninvited_contacts.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201708') + contact_service = client.GetService('ContactService', version='v201805') # Create a statement to select contacts. statement = (dfp.StatementBuilder() .Where('status = :status') @@ -37,7 +37,7 @@ def main(client): # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/contact_service/update_contacts.py b/examples/dfp/v201805/contact_service/update_contacts.py similarity index 99% rename from examples/dfp/v201708/contact_service/update_contacts.py rename to examples/dfp/v201805/contact_service/update_contacts.py index 1a14eb95..ed8cfb8a 100755 --- a/examples/dfp/v201708/contact_service/update_contacts.py +++ b/examples/dfp/v201805/contact_service/update_contacts.py @@ -35,7 +35,7 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201708') + contact_service = client.GetService('ContactService', version='v201805') # Create statement object to select the single contact by ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/__init__.py b/examples/dfp/v201805/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201708/content_metadata_key_hierarchy_service/__init__.py rename to examples/dfp/v201805/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/dfp/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/dfp/v201708/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/dfp/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 4b45d9a1..d5287824 100755 --- a/examples/dfp/v201708/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201708') + 'ContentMetadataKeyHierarchyService', version='v201805') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 96% rename from examples/dfp/v201708/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 3b5c748e..724b2128 100755 --- a/examples/dfp/v201708/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201708') + 'ContentMetadataKeyHierarchyService', version='v201805') # Create a statement to select content metadata key hierarchies. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/dfp/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 98% rename from examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/dfp/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 253fbd5a..7b5bd910 100755 --- a/examples/dfp/v201708/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201708') + 'ContentMetadataKeyHierarchyService', version='v201805') # Create a query to select a single content metadata key hierarchy. diff --git a/examples/dfp/v201708/content_service/__init__.py b/examples/dfp/v201805/content_service/__init__.py similarity index 100% rename from examples/dfp/v201708/content_service/__init__.py rename to examples/dfp/v201805/content_service/__init__.py diff --git a/examples/dfp/v201708/content_service/get_all_content.py b/examples/dfp/v201805/content_service/get_all_content.py similarity index 99% rename from examples/dfp/v201708/content_service/get_all_content.py rename to examples/dfp/v201805/content_service/get_all_content.py index b1d79f11..996f9b9a 100755 --- a/examples/dfp/v201708/content_service/get_all_content.py +++ b/examples/dfp/v201805/content_service/get_all_content.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201708') + content_service = client.GetService('ContentService', version='v201805') # Create a statement to select content. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/creative_service/__init__.py b/examples/dfp/v201805/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201708/creative_service/__init__.py rename to examples/dfp/v201805/creative_service/__init__.py diff --git a/examples/dfp/v201708/creative_service/copy_image_creatives.py b/examples/dfp/v201805/creative_service/copy_image_creatives.py similarity index 99% rename from examples/dfp/v201708/creative_service/copy_image_creatives.py rename to examples/dfp/v201805/creative_service/copy_image_creatives.py index 2075602c..b93d4a25 100755 --- a/examples/dfp/v201708/creative_service/copy_image_creatives.py +++ b/examples/dfp/v201805/creative_service/copy_image_creatives.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201708') + creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to get the image creative. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/creative_service/create_creative_from_template.py b/examples/dfp/v201805/creative_service/create_creative_from_template.py similarity index 99% rename from examples/dfp/v201708/creative_service/create_creative_from_template.py rename to examples/dfp/v201805/creative_service/create_creative_from_template.py index 3ccfa050..886b68e2 100755 --- a/examples/dfp/v201708/creative_service/create_creative_from_template.py +++ b/examples/dfp/v201805/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201708') + creative_service = client.GetService('CreativeService', version='v201805') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/dfp/v201708/creative_service/create_creatives.py b/examples/dfp/v201805/creative_service/create_creatives.py similarity index 99% rename from examples/dfp/v201708/creative_service/create_creatives.py rename to examples/dfp/v201805/creative_service/create_creatives.py index 14668389..7db03fb4 100755 --- a/examples/dfp/v201708/creative_service/create_creatives.py +++ b/examples/dfp/v201805/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201708') + creative_service = client.GetService('CreativeService', version='v201805') # Create creative objects. creatives = [] diff --git a/examples/dfp/v201708/creative_service/create_custom_creative.py b/examples/dfp/v201805/creative_service/create_custom_creative.py similarity index 99% rename from examples/dfp/v201708/creative_service/create_custom_creative.py rename to examples/dfp/v201805/creative_service/create_custom_creative.py index 47f8c23c..be7a9b10 100755 --- a/examples/dfp/v201708/creative_service/create_custom_creative.py +++ b/examples/dfp/v201805/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201708') + creative_service = client.GetService('CreativeService', version='v201805') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/dfp/v201708/creative_service/create_native_creative.py b/examples/dfp/v201805/creative_service/create_native_creative.py similarity index 95% rename from examples/dfp/v201708/creative_service/create_native_creative.py rename to examples/dfp/v201805/creative_service/create_native_creative.py index 5bb0de13..6a72df5d 100755 --- a/examples/dfp/v201708/creative_service/create_native_creative.py +++ b/examples/dfp/v201805/creative_service/create_native_creative.py @@ -45,18 +45,14 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201708') + creative_service = client.GetService('CreativeService', version='v201805') # Use the system defined native app install creative template. creative_template_id = '10004400' image_data = urllib2.urlopen(ICON_URL).read() - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = image_data.decode('utf-8') app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - app_icon_data = app_icon_data.decode('utf-8') # Create creative from templates. creative = { diff --git a/examples/dfp/v201708/creative_service/get_all_creatives.py b/examples/dfp/v201805/creative_service/get_all_creatives.py similarity index 99% rename from examples/dfp/v201708/creative_service/get_all_creatives.py rename to examples/dfp/v201805/creative_service/get_all_creatives.py index 1feeb89e..20762dcb 100755 --- a/examples/dfp/v201708/creative_service/get_all_creatives.py +++ b/examples/dfp/v201805/creative_service/get_all_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201708') + creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to select creatives. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/creative_service/get_image_creatives.py b/examples/dfp/v201805/creative_service/get_image_creatives.py similarity index 96% rename from examples/dfp/v201708/creative_service/get_image_creatives.py rename to examples/dfp/v201805/creative_service/get_image_creatives.py index 4d2a923a..759bdd13 100755 --- a/examples/dfp/v201708/creative_service/get_image_creatives.py +++ b/examples/dfp/v201805/creative_service/get_image_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201708') + creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to select creatives. statement = (dfp.StatementBuilder() .Where('creativeType = :creativeType') @@ -37,7 +37,7 @@ def main(client): # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % (creative['id'], creative['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/creative_service/update_creatives.py b/examples/dfp/v201805/creative_service/update_creatives.py similarity index 97% rename from examples/dfp/v201708/creative_service/update_creatives.py rename to examples/dfp/v201805/creative_service/update_creatives.py index c58e300a..580cba24 100755 --- a/examples/dfp/v201708/creative_service/update_creatives.py +++ b/examples/dfp/v201805/creative_service/update_creatives.py @@ -34,9 +34,9 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201708') + creative_service = client.GetService('CreativeService', version='v201805') - # Create statement object to get all image creatives. + # Create statement object to get the creative by ID. statement = (dfp.StatementBuilder() .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') diff --git a/examples/dfp/v201708/creative_set_service/__init__.py b/examples/dfp/v201805/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201708/creative_set_service/__init__.py rename to examples/dfp/v201805/creative_set_service/__init__.py diff --git a/examples/dfp/v201708/creative_set_service/associate_creative_set_to_line_item.py b/examples/dfp/v201805/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/dfp/v201708/creative_set_service/associate_creative_set_to_line_item.py rename to examples/dfp/v201805/creative_set_service/associate_creative_set_to_line_item.py index 7d82f843..83d523fc 100755 --- a/examples/dfp/v201708/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/dfp/v201805/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201708') + 'LineItemCreativeAssociationService', version='v201805') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/dfp/v201708/creative_set_service/create_creative_set.py b/examples/dfp/v201805/creative_set_service/create_creative_set.py similarity index 97% rename from examples/dfp/v201708/creative_set_service/create_creative_set.py rename to examples/dfp/v201805/creative_set_service/create_creative_set.py index 42c3e30d..056db8a0 100755 --- a/examples/dfp/v201708/creative_set_service/create_creative_set.py +++ b/examples/dfp/v201805/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201708') + version='v201805') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/dfp/v201708/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201805/creative_set_service/get_all_creative_sets.py similarity index 97% rename from examples/dfp/v201708/creative_set_service/get_all_creative_sets.py rename to examples/dfp/v201805/creative_set_service/get_all_creative_sets.py index b725512a..6a623305 100755 --- a/examples/dfp/v201708/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201805/creative_set_service/get_all_creative_sets.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201708') + 'CreativeSetService', version='v201805') # Create a statement to select creative sets. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py similarity index 95% rename from examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py index 39b53de7..ccf51553 100755 --- a/examples/dfp/v201708/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,7 +25,7 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201708') + 'CreativeSetService', version='v201805') # Create a statement to select creative sets. statement = (dfp.StatementBuilder() .Where('masterCreativeId = :masterCreativeId') @@ -41,7 +41,7 @@ def main(client, master_creative_id): # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % (creative_set['id'], creative_set['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/creative_set_service/update_creative_set.py b/examples/dfp/v201805/creative_set_service/update_creative_set.py similarity index 97% rename from examples/dfp/v201708/creative_set_service/update_creative_set.py rename to examples/dfp/v201805/creative_set_service/update_creative_set.py index 6ba670e7..cd1ed1fc 100755 --- a/examples/dfp/v201708/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201805/creative_set_service/update_creative_set.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201708') + version='v201805') # Create statement to select a single creative set by ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/creative_template_service/__init__.py b/examples/dfp/v201805/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201708/creative_template_service/__init__.py rename to examples/dfp/v201805/creative_template_service/__init__.py diff --git a/examples/dfp/v201708/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201805/creative_template_service/get_all_creative_templates.py similarity index 97% rename from examples/dfp/v201708/creative_template_service/get_all_creative_templates.py rename to examples/dfp/v201805/creative_template_service/get_all_creative_templates.py index afa32653..bba87e16 100755 --- a/examples/dfp/v201708/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201805/creative_template_service/get_all_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201708') + 'CreativeTemplateService', version='v201805') # Create a statement to select creative templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py rename to examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py index b9855e66..8b77114b 100755 --- a/examples/dfp/v201708/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201708') + 'CreativeTemplateService', version='v201805') # Create a statement to select creative templates. statement = (dfp.StatementBuilder() .Where('type = :type') @@ -39,7 +39,7 @@ def main(client): # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % (creative_template['id'], creative_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/creative_wrapper_service/create_creative_wrappers.py b/examples/dfp/v201805/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/dfp/v201708/creative_wrapper_service/create_creative_wrappers.py rename to examples/dfp/v201805/creative_wrapper_service/create_creative_wrappers.py index 23002ace..c0db9688 100755 --- a/examples/dfp/v201708/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/dfp/v201805/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201708') + version='v201805') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py index f19a7775..3a497e4b 100755 --- a/examples/dfp/v201708/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,7 +33,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201708') + version='v201805') # Create a query to select the active creative wrappers for the given label. statement = (dfp.StatementBuilder() @@ -60,7 +60,7 @@ def main(client, label_id): {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: creative_wrappers_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py index 7a583480..78c42a34 100755 --- a/examples/dfp/v201708/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201708') + 'CreativeWrapperService', version='v201805') # Create a statement to select creative wrappers. statement = (dfp.StatementBuilder() .Where('status = :status') @@ -39,7 +39,7 @@ def main(client): # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py similarity index 97% rename from examples/dfp/v201708/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py index 5ac7fd17..ed5bb88b 100755 --- a/examples/dfp/v201708/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201708') + 'CreativeWrapperService', version='v201805') # Create a statement to select creative wrappers. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py similarity index 97% rename from examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py rename to examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py index 5243704d..c291f687 100755 --- a/examples/dfp/v201708/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py @@ -36,7 +36,7 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201708') + version='v201805') # Create statement to get a creative wrapper by ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/custom_field_service/__init__.py b/examples/dfp/v201805/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201708/custom_field_service/__init__.py rename to examples/dfp/v201805/custom_field_service/__init__.py diff --git a/examples/dfp/v201708/custom_field_service/create_custom_field_options.py b/examples/dfp/v201805/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/dfp/v201708/custom_field_service/create_custom_field_options.py rename to examples/dfp/v201805/custom_field_service/create_custom_field_options.py index f8c86710..2ff33db3 100755 --- a/examples/dfp/v201708/custom_field_service/create_custom_field_options.py +++ b/examples/dfp/v201805/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201708') + 'CustomFieldService', version='v201805') # Create custom field options. custom_field_options = [ diff --git a/examples/dfp/v201708/custom_field_service/create_custom_fields.py b/examples/dfp/v201805/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/dfp/v201708/custom_field_service/create_custom_fields.py rename to examples/dfp/v201805/custom_field_service/create_custom_fields.py index ff120365..4a0dde45 100755 --- a/examples/dfp/v201708/custom_field_service/create_custom_fields.py +++ b/examples/dfp/v201805/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201708') + 'CustomFieldService', version='v201805') # Create custom field objects. custom_fields = [ diff --git a/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 96% rename from examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py index 04ebc205..14c46dcc 100755 --- a/examples/dfp/v201708/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201708') + 'CustomFieldService', version='v201805') # Create statement to select only active custom fields that apply to # line items. @@ -57,7 +57,7 @@ def main(client): {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: custom_fields_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201805/custom_field_service/get_all_custom_fields.py similarity index 97% rename from examples/dfp/v201708/custom_field_service/get_all_custom_fields.py rename to examples/dfp/v201805/custom_field_service/get_all_custom_fields.py index c0442894..080ac0e1 100755 --- a/examples/dfp/v201708/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201805/custom_field_service/get_all_custom_fields.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201708') + 'CustomFieldService', version='v201805') # Create a statement to select custom fields. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py rename to examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py index b28d3963..a01cca47 100755 --- a/examples/dfp/v201708/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201708') + 'CustomFieldService', version='v201805') # Create a statement to select custom fields. statement = (dfp.StatementBuilder() .Where('entityType = :entityType') @@ -39,7 +39,7 @@ def main(client): # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % (custom_field['id'], custom_field['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/custom_field_service/set_line_item_custom_field_value.py b/examples/dfp/v201805/custom_field_service/set_line_item_custom_field_value.py similarity index 82% rename from examples/dfp/v201708/custom_field_service/set_line_item_custom_field_value.py rename to examples/dfp/v201805/custom_field_service/set_line_item_custom_field_value.py index ca7affe8..86b820ca 100755 --- a/examples/dfp/v201708/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/dfp/v201805/custom_field_service/set_line_item_custom_field_value.py @@ -42,53 +42,36 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201708') + 'CustomFieldService', version='v201805') - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') # Create statement to get a custom field. - custom_field_values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - custom_field_query = 'WHERE id = :customFieldId' - custom_field_statement = dfp.FilterStatement( - custom_field_query, custom_field_values, 1) + custom_field_statement = (dfp.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', custom_field_id) + .Limit(1)) # Get custom field. custom_field = custom_field_service.getCustomFieldsByStatement( custom_field_statement.ToStatement())['results'][0] # Create statement to get a drop down custom field. - drop_down_custom_field_values = [{ - 'key': 'dropDownCustomFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': drop_down_custom_field_id - } - }] - drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId' - drop_down_custom_field_statement = dfp.FilterStatement( - drop_down_custom_field_query, drop_down_custom_field_values, 1) + drop_down_custom_field_statement = ( + dfp.StatementBuilder() + .Where('id = :dropDownCustomFieldId') + .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) + .Limit(1)) # Get drop-down custom field. drop_down_custom_field = custom_field_service.getCustomFieldsByStatement( drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - line_item_query = 'WHERE id = :lineItemId' - line_item_statement = dfp.FilterStatement( - line_item_query, line_item_values, 1) + line_item_statement = (dfp.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', line_item_id) + .Limit(1)) # Get line item. line_item = line_item_service.getLineItemsByStatement( diff --git a/examples/dfp/v201708/custom_field_service/update_custom_fields.py b/examples/dfp/v201805/custom_field_service/update_custom_fields.py similarity index 98% rename from examples/dfp/v201708/custom_field_service/update_custom_fields.py rename to examples/dfp/v201805/custom_field_service/update_custom_fields.py index 36c95bc5..59123218 100755 --- a/examples/dfp/v201708/custom_field_service/update_custom_fields.py +++ b/examples/dfp/v201805/custom_field_service/update_custom_fields.py @@ -36,7 +36,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201708') + 'CustomFieldService', version='v201805') # Create statement to get a custom field. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/custom_targeting_service/__init__.py b/examples/dfp/v201805/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201708/custom_targeting_service/__init__.py rename to examples/dfp/v201805/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201708/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/dfp/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201708/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/dfp/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py index 5f064369..89b54bf1 100755 --- a/examples/dfp/v201708/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201708') + 'CustomTargetingService', version='v201805') # Create custom targeting key objects. keys = [ diff --git a/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py similarity index 91% rename from examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py index 3ed109af..fb84fea0 100755 --- a/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,7 +36,7 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201708') + 'CustomTargetingService', version='v201805') statement = (dfp.StatementBuilder() .Where('name = :name') @@ -51,8 +51,8 @@ def main(client, key_name): if 'results' in response: key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) - key_statement = dfp.FilterStatement(key_query) + key_statement = (dfp.StatementBuilder() + .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. result = custom_targeting_service.performCustomTargetingKeyAction( @@ -60,7 +60,7 @@ def main(client, key_name): if result and int(result['numChanges']) > 0: deleted_custom_targeting_keys += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py similarity index 81% rename from examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_values.py rename to examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py index b62d564e..e7d96621 100755 --- a/examples/dfp/v201708/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py @@ -36,17 +36,11 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201708') + 'CustomTargetingService', version='v201805') - filter_values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, filter_values) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', key_id)) deleted_custom_targeting_values = 0 @@ -57,16 +51,17 @@ def main(client, key_id): if 'results' in response: value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_query = ('WHERE customTargetingKeyId = :keyId ' - 'AND id IN (%s)' % ', '.join(value_ids)) - value_statement = dfp.FilterStatement(value_query, filter_values) + value_statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId = :keyId ' + 'AND id IN (%s)' % ', '.join(value_ids)) + .WithBindVariable('keyId', key_id)) # Delete custom targeting values. result = custom_targeting_service.performCustomTargetingValueAction( action, value_statement.ToStatement()) if result and int(result['numChanges']) > 0: deleted_custom_targeting_values += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 90% rename from examples/dfp/v201708/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 7d9d8478..d3dd5170 100755 --- a/examples/dfp/v201708/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201708') + 'CustomTargetingService', version='v201805') # Create statement to get all targeting keys. targeting_key_statement = dfp.StatementBuilder() @@ -42,9 +42,9 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (dfp.StatementBuilder() + .Where('customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys]))) # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. @@ -59,7 +59,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 98% rename from examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index c4b77aa8..2c4a894b 100755 --- a/examples/dfp/v201708/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201708') + 'CustomTargetingService', version='v201805') # Create statement to get targeting keys for predefined values. targeting_key_statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py similarity index 97% rename from examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py rename to examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py index 39ef1be7..01a1eb3b 100755 --- a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201708') + 'CustomTargetingService', version='v201805') statement = (dfp.StatementBuilder() .Where('id = :keyId') diff --git a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py rename to examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py index f0c8d675..074683e3 100755 --- a/examples/dfp/v201708/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py @@ -30,7 +30,7 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201708') + 'CustomTargetingService', version='v201805') statement = (dfp.StatementBuilder() .Where('customTargetingKeyId = :keyId') @@ -57,7 +57,7 @@ def main(client, key_id): print ('Custom targeting value with id "%s", name "%s", and display' ' name "%s" was updated.' % (value['id'], value['name'], value['displayName'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/exchange_rate_service/__init__.py b/examples/dfp/v201805/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201708/exchange_rate_service/__init__.py rename to examples/dfp/v201805/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201708/exchange_rate_service/create_exchange_rates.py b/examples/dfp/v201805/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/dfp/v201708/exchange_rate_service/create_exchange_rates.py rename to examples/dfp/v201805/exchange_rate_service/create_exchange_rates.py index 7753ab93..df6307d3 100755 --- a/examples/dfp/v201708/exchange_rate_service/create_exchange_rates.py +++ b/examples/dfp/v201805/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201708') + version='v201805') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/dfp/v201708/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py similarity index 97% rename from examples/dfp/v201708/exchange_rate_service/get_all_exchange_rates.py rename to examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py index 21075009..d23410b5 100755 --- a/examples/dfp/v201708/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201708') + 'ExchangeRateService', version='v201805') # Create a statement to select exchange rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 95% rename from examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py index e8174907..152d1c77 100755 --- a/examples/dfp/v201708/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,7 +25,7 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201708') + 'ExchangeRateService', version='v201805') # Create a statement to select exchange rates. statement = (dfp.StatementBuilder() .Where('currencyCode = :currencyCode') @@ -43,7 +43,7 @@ def main(client, currency_code): 'rate "%.2f" was found.\n' % (exchange_rate['id'], exchange_rate['currencyCode'], float(exchange_rate['exchangeRate'] / 1000000))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py similarity index 97% rename from examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py rename to examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py index ad85b0b3..270a48bc 100755 --- a/examples/dfp/v201708/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py @@ -30,7 +30,7 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201708') + version='v201805') # Create a statement to get an exchange rate by its ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/forecast_service/get_availability_forecast.py b/examples/dfp/v201805/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/dfp/v201708/forecast_service/get_availability_forecast.py rename to examples/dfp/v201805/forecast_service/get_availability_forecast.py index 99583ae3..a857a128 100755 --- a/examples/dfp/v201708/forecast_service/get_availability_forecast.py +++ b/examples/dfp/v201805/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') + forecast_service = client.GetService('ForecastService', version='v201805') + network_service = client.GetService('NetworkService', version='v201805') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py b/examples/dfp/v201805/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py rename to examples/dfp/v201805/forecast_service/get_availability_forecast_for_line_item.py index ac71f295..720da349 100755 --- a/examples/dfp/v201708/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/dfp/v201805/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201708') + forecast_service = client.GetService('ForecastService', version='v201805') # Set forecasting options. forecast_options = { @@ -60,7 +60,6 @@ def main(client, line_item_id): possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() diff --git a/examples/dfp/v201708/forecast_service/get_delivery_forecast_for_line_items.py b/examples/dfp/v201805/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/dfp/v201708/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/dfp/v201805/forecast_service/get_delivery_forecast_for_line_items.py index 3d4b8a2b..f03d6025 100755 --- a/examples/dfp/v201708/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/dfp/v201805/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201708') + forecast_service = client.GetService('ForecastService', version='v201805') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/dfp/v201708/inventory_service/__init__.py b/examples/dfp/v201805/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201708/inventory_service/__init__.py rename to examples/dfp/v201805/inventory_service/__init__.py diff --git a/examples/dfp/v201708/inventory_service/archive_ad_units.py b/examples/dfp/v201805/inventory_service/archive_ad_units.py similarity index 97% rename from examples/dfp/v201708/inventory_service/archive_ad_units.py rename to examples/dfp/v201805/inventory_service/archive_ad_units.py index 6ea176a3..af33872a 100755 --- a/examples/dfp/v201708/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201805/inventory_service/archive_ad_units.py @@ -35,7 +35,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201708') + inventory_service = client.GetService('InventoryService', version='v201805') # Create a query to select ad units under the parent ad unit and the parent ad # unit. @@ -58,7 +58,7 @@ def main(client, parent_id): {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: ad_units_archived += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/inventory_service/create_ad_units.py b/examples/dfp/v201805/inventory_service/create_ad_units.py similarity index 99% rename from examples/dfp/v201708/inventory_service/create_ad_units.py rename to examples/dfp/v201805/inventory_service/create_ad_units.py index 18a012be..f9b48c1b 100755 --- a/examples/dfp/v201708/inventory_service/create_ad_units.py +++ b/examples/dfp/v201805/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201708') + inventory_service = client.GetService('InventoryService', version='v201805') # Create ad unit size. ad_unit_size = { diff --git a/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py new file mode 100755 index 00000000..bee36001 --- /dev/null +++ b/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 prints all ad unit names as a tree.""" + + +# Import appropriate modules from the client library. +import collections +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201805') + inventory_service = client.GetService('InventoryService', version='v201805') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select only the root ad unit by ID. + statement = (dfp.StatementBuilder() + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', root_ad_unit_id)) + + # Make a request for the root ad unit + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + root_ad_unit = response['results'][0] + + all_ad_units = get_all_ad_units(inventory_service) + + display_hierarchy(root_ad_unit, all_ad_units) + + +def get_all_ad_units(inventory_service): + """Download all ad units. + + Args: + inventory_service: An instance of the InventoryService. + + Returns: + A list containing all ad units. + """ + # Create a statement to get all ad units. + statement = (dfp.StatementBuilder() + .OrderBy('id', ascending=True)) + + # Pull down all ad units into a list + keep_iterating = True + total_results = 0 + found_ad_units = [] + while keep_iterating: + page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in page: + total_results = page['totalResultSetSize'] + found_ad_units.extend(page['results']) + + statement.offset += statement.limit + keep_iterating = statement.offset < total_results + + return found_ad_units + + +def display_hierarchy(root_ad_unit, all_ad_units): + """Display the ad units as a tree. + + Args: + root_ad_unit: The root ad unit to begin from. + all_ad_units: A list containing all ad units. + """ + # Create a dict mapping the ids of parents to lists of their children. + parent_id_to_children = collections.defaultdict(list) + for ad_unit in all_ad_units: + if 'parentId' in ad_unit: + parent_id_to_children[ad_unit['parentId']].append(ad_unit) + parent_id_to_children = dict(parent_id_to_children) + + display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0) + + +def display_hierarchy_helper(root, parent_id_to_children, depth): + """Recursive helper for displaying the hierarchy. + + Args: + root: The current root ad unit. + parent_id_to_children: The overall map of parent ids to children. + depth: The current depth. + """ + print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id']) + + # Recurse for each child of this root that has children. + for child in parent_id_to_children.get(root['id'], []): + display_hierarchy_helper(child, parent_id_to_children, depth + 1) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/inventory_service/get_all_ad_unit_sizes.py b/examples/dfp/v201805/inventory_service/get_all_ad_unit_sizes.py similarity index 94% rename from examples/dfp/v201708/inventory_service/get_all_ad_unit_sizes.py rename to examples/dfp/v201805/inventory_service/get_all_ad_unit_sizes.py index 78fcd659..c5c55183 100755 --- a/examples/dfp/v201708/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/dfp/v201805/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201708') + 'InventoryService', version='v201805') # Create a statement to select ad unit sizes. - statement = dfp.FilterStatement() + statement = dfp.StatementBuilder() # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/dfp/v201708/inventory_service/get_all_ad_units.py b/examples/dfp/v201805/inventory_service/get_all_ad_units.py similarity index 99% rename from examples/dfp/v201708/inventory_service/get_all_ad_units.py rename to examples/dfp/v201805/inventory_service/get_all_ad_units.py index cb5aba78..06b7733e 100755 --- a/examples/dfp/v201708/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201805/inventory_service/get_all_ad_units.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201708') + ad_unit_service = client.GetService('InventoryService', version='v201805') # Create a statement to select ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py new file mode 100755 index 00000000..21678b0e --- /dev/null +++ b/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 child ad units of the effective root ad unit.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201805') + inventory_service = client.GetService('InventoryService', version='v201805') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + parent_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select ad units under the parent ad unit. + statement = (dfp.StatementBuilder() + .Where('parentId = :parentId') + .OrderBy('id', ascending=True) + .WithBindVariable('parentId', parent_ad_unit_id)) + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response: + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/inventory_service/update_ad_units.py b/examples/dfp/v201805/inventory_service/update_ad_units.py similarity index 99% rename from examples/dfp/v201708/inventory_service/update_ad_units.py rename to examples/dfp/v201805/inventory_service/update_ad_units.py index fa5c54f3..01e4514d 100755 --- a/examples/dfp/v201708/inventory_service/update_ad_units.py +++ b/examples/dfp/v201805/inventory_service/update_ad_units.py @@ -36,7 +36,7 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201708') + inventory_service = client.GetService('InventoryService', version='v201805') # Create a statement to select a single ad unit by ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/label_service/__init__.py b/examples/dfp/v201805/label_service/__init__.py similarity index 100% rename from examples/dfp/v201708/label_service/__init__.py rename to examples/dfp/v201805/label_service/__init__.py diff --git a/examples/dfp/v201708/label_service/create_labels.py b/examples/dfp/v201805/label_service/create_labels.py similarity index 99% rename from examples/dfp/v201708/label_service/create_labels.py rename to examples/dfp/v201805/label_service/create_labels.py index 7ca9f6ea..43c66f09 100755 --- a/examples/dfp/v201708/label_service/create_labels.py +++ b/examples/dfp/v201805/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201708') + label_service = client.GetService('LabelService', version='v201805') # Create label objects. labels = [] diff --git a/examples/dfp/v201708/label_service/deactivate_labels.py b/examples/dfp/v201805/label_service/deactivate_labels.py similarity index 97% rename from examples/dfp/v201708/label_service/deactivate_labels.py rename to examples/dfp/v201805/label_service/deactivate_labels.py index 9cc3f342..b2d025ba 100755 --- a/examples/dfp/v201708/label_service/deactivate_labels.py +++ b/examples/dfp/v201805/label_service/deactivate_labels.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201708') + label_service = client.GetService('LabelService', version='v201805') # Create query. statement = (dfp.StatementBuilder() @@ -48,7 +48,7 @@ def main(client): {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: labels_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/label_service/get_active_labels.py b/examples/dfp/v201805/label_service/get_active_labels.py similarity index 96% rename from examples/dfp/v201708/label_service/get_active_labels.py rename to examples/dfp/v201805/label_service/get_active_labels.py index 7ee62101..41d7de6d 100755 --- a/examples/dfp/v201708/label_service/get_active_labels.py +++ b/examples/dfp/v201805/label_service/get_active_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201708') + label_service = client.GetService('LabelService', version='v201805') # Create a statement to select labels. statement = (dfp.StatementBuilder() .Where('isActive = :isActive') @@ -37,7 +37,7 @@ def main(client): # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], label['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/label_service/get_all_labels.py b/examples/dfp/v201805/label_service/get_all_labels.py similarity index 99% rename from examples/dfp/v201708/label_service/get_all_labels.py rename to examples/dfp/v201805/label_service/get_all_labels.py index ddfb7b83..f4c9ec1f 100755 --- a/examples/dfp/v201708/label_service/get_all_labels.py +++ b/examples/dfp/v201805/label_service/get_all_labels.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201708') + label_service = client.GetService('LabelService', version='v201805') # Create a statement to select labels. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/label_service/update_labels.py b/examples/dfp/v201805/label_service/update_labels.py similarity index 99% rename from examples/dfp/v201708/label_service/update_labels.py rename to examples/dfp/v201805/label_service/update_labels.py index a9d859f1..1430c929 100755 --- a/examples/dfp/v201708/label_service/update_labels.py +++ b/examples/dfp/v201805/label_service/update_labels.py @@ -29,7 +29,7 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201708') + label_service = client.GetService('LabelService', version='v201805') # Create a statement to select only active labels. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/line_item_creative_association_service/__init__.py b/examples/dfp/v201805/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201708/line_item_creative_association_service/__init__.py rename to examples/dfp/v201805/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201708/line_item_creative_association_service/create_licas.py b/examples/dfp/v201805/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/dfp/v201708/line_item_creative_association_service/create_licas.py rename to examples/dfp/v201805/line_item_creative_association_service/create_licas.py index 1d53af3f..944e76ec 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/create_licas.py +++ b/examples/dfp/v201805/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201708') + 'LineItemCreativeAssociationService', version='v201805') licas = [] for creative_id in creative_ids: diff --git a/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py rename to examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py index 8885ecc0..9db1f987 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201708') + 'LineItemCreativeAssociationService', version='v201805') # Create query. statement = (dfp.StatementBuilder() @@ -56,7 +56,7 @@ def main(client, line_item_id): statement.ToStatement()) if result and int(result['numChanges']) > 0: num_deactivated_licas += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py similarity index 97% rename from examples/dfp/v201708/line_item_creative_association_service/get_all_licas.py rename to examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py index 3fc04519..0d24a221 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201708') + 'LineItemCreativeAssociationService', version='v201805') # Create a statement to select line item creative associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py similarity index 95% rename from examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py index 3200cb4a..2c8c83b8 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,7 +25,7 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201708') + 'LineItemCreativeAssociationService', version='v201805') # Create a statement to select line item creative associations. statement = (dfp.StatementBuilder() .Where('lineItemId = :lineItemId') @@ -47,7 +47,7 @@ def main(client, line_item_id): print('Line item creative association with line item ID "%d" and ' 'creative ID "%d" was found.\n' % (lica['lineItemId'], lica['creativeId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/line_item_creative_association_service/update_licas.py b/examples/dfp/v201805/line_item_creative_association_service/update_licas.py similarity index 97% rename from examples/dfp/v201708/line_item_creative_association_service/update_licas.py rename to examples/dfp/v201805/line_item_creative_association_service/update_licas.py index 1e59bd1b..a8498b4a 100755 --- a/examples/dfp/v201708/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201805/line_item_creative_association_service/update_licas.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201708') + 'LineItemCreativeAssociationService', version='v201805') # Create statement object to get all LICAs. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/line_item_service/__init__.py b/examples/dfp/v201805/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201708/line_item_service/__init__.py rename to examples/dfp/v201805/line_item_service/__init__.py diff --git a/examples/dfp/v201708/line_item_service/activate_line_items.py b/examples/dfp/v201805/line_item_service/activate_line_items.py similarity index 97% rename from examples/dfp/v201708/line_item_service/activate_line_items.py rename to examples/dfp/v201805/line_item_service/activate_line_items.py index 0df9b340..c8646a51 100755 --- a/examples/dfp/v201708/line_item_service/activate_line_items.py +++ b/examples/dfp/v201805/line_item_service/activate_line_items.py @@ -33,7 +33,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') # Create query. statement = (dfp.StatementBuilder() @@ -58,7 +58,7 @@ def main(client, order_id): {'xsi_type': 'ActivateLineItems'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: line_items_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/line_item_service/create_line_items.py b/examples/dfp/v201805/line_item_service/create_line_items.py similarity index 99% rename from examples/dfp/v201708/line_item_service/create_line_items.py rename to examples/dfp/v201805/line_item_service/create_line_items.py index c49f8035..7f352b1d 100755 --- a/examples/dfp/v201708/line_item_service/create_line_items.py +++ b/examples/dfp/v201805/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/dfp/v201708/line_item_service/create_video_line_item.py b/examples/dfp/v201805/line_item_service/create_video_line_item.py similarity index 99% rename from examples/dfp/v201708/line_item_service/create_video_line_item.py rename to examples/dfp/v201805/line_item_service/create_video_line_item.py index 1af5df50..da6abd84 100755 --- a/examples/dfp/v201708/line_item_service/create_video_line_item.py +++ b/examples/dfp/v201805/line_item_service/create_video_line_item.py @@ -47,7 +47,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/dfp/v201708/line_item_service/get_all_line_items.py b/examples/dfp/v201805/line_item_service/get_all_line_items.py similarity index 99% rename from examples/dfp/v201708/line_item_service/get_all_line_items.py rename to examples/dfp/v201805/line_item_service/get_all_line_items.py index abf2df90..f5a603c8 100755 --- a/examples/dfp/v201708/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201805/line_item_service/get_all_line_items.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') # Create a statement to select line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py rename to examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py index ab1cd2f4..b75ea1a8 100755 --- a/examples/dfp/v201708/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') # Create a statement to select line items. statement = (dfp.StatementBuilder() .Where('isMissingCreatives = :isMissingCreatives') @@ -38,7 +38,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py rename to examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py index 6970ebdb..2d92cd8b 100755 --- a/examples/dfp/v201708/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -46,7 +46,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/line_item_service/pause_line_items.py b/examples/dfp/v201805/line_item_service/pause_line_items.py similarity index 99% rename from examples/dfp/v201708/line_item_service/pause_line_items.py rename to examples/dfp/v201805/line_item_service/pause_line_items.py index c7d78b61..40346fe2 100755 --- a/examples/dfp/v201708/line_item_service/pause_line_items.py +++ b/examples/dfp/v201805/line_item_service/pause_line_items.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') # Create a statement to select the line item. # Change this to operate on more than one Line Item. diff --git a/examples/dfp/v201708/line_item_service/target_custom_criteria.py b/examples/dfp/v201805/line_item_service/target_custom_criteria.py similarity index 99% rename from examples/dfp/v201708/line_item_service/target_custom_criteria.py rename to examples/dfp/v201805/line_item_service/target_custom_criteria.py index c1e1c746..7f64049f 100755 --- a/examples/dfp/v201708/line_item_service/target_custom_criteria.py +++ b/examples/dfp/v201805/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') # create custom criterias custom_criteria1 = { diff --git a/examples/dfp/v201708/line_item_service/update_line_items.py b/examples/dfp/v201805/line_item_service/update_line_items.py similarity index 99% rename from examples/dfp/v201708/line_item_service/update_line_items.py rename to examples/dfp/v201805/line_item_service/update_line_items.py index fa7abe6c..8386e7a2 100755 --- a/examples/dfp/v201708/line_item_service/update_line_items.py +++ b/examples/dfp/v201805/line_item_service/update_line_items.py @@ -29,7 +29,7 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') # Create statement object to only select line items with even delivery rates. diff --git a/examples/dfp/v201708/live_stream_event_service/activate_live_stream_events.py b/examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py similarity index 97% rename from examples/dfp/v201708/live_stream_event_service/activate_live_stream_events.py rename to examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py index fa0a8f2a..11c96a9a 100755 --- a/examples/dfp/v201708/live_stream_event_service/activate_live_stream_events.py +++ b/examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py @@ -26,7 +26,7 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201708') + 'LiveStreamEventService', version='v201805') # Create query to find paused live stream events. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/live_stream_event_service/create_live_stream_events.py b/examples/dfp/v201805/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/dfp/v201708/live_stream_event_service/create_live_stream_events.py rename to examples/dfp/v201805/live_stream_event_service/create_live_stream_events.py index 5ce194c3..3ddd62ed 100755 --- a/examples/dfp/v201708/live_stream_event_service/create_live_stream_events.py +++ b/examples/dfp/v201805/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201708') + 'LiveStreamEventService', version='v201805') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/dfp/v201708/live_stream_event_service/get_all_live_stream_events.py b/examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py similarity index 97% rename from examples/dfp/v201708/live_stream_event_service/get_all_live_stream_events.py rename to examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py index a6eccb88..5652fb1d 100755 --- a/examples/dfp/v201708/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201708') + 'LiveStreamEventService', version='v201805') # Create a statement to select live stream events. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/live_stream_event_service/register_sessions_for_monitoring.py b/examples/dfp/v201805/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/dfp/v201708/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/dfp/v201805/live_stream_event_service/register_sessions_for_monitoring.py index 906ff712..b21c87d3 100755 --- a/examples/dfp/v201708/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/dfp/v201805/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201708') + 'LiveStreamEventService', version='v201805') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/dfp/v201708/live_stream_event_service/update_live_stream_events.py b/examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py similarity index 97% rename from examples/dfp/v201708/live_stream_event_service/update_live_stream_events.py rename to examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py index 3bae28dd..b83ec6ca 100755 --- a/examples/dfp/v201708/live_stream_event_service/update_live_stream_events.py +++ b/examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py @@ -29,7 +29,7 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201708') + 'LiveStreamEventService', version='v201805') # Create statement object to only select matching live stream event. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201805/native_style_service/__init__.py b/examples/dfp/v201805/native_style_service/__init__.py new file mode 100755 index 00000000..473ddba1 --- /dev/null +++ b/examples/dfp/v201805/native_style_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. diff --git a/examples/dfp/v201708/native_style_service/create_native_styles.py b/examples/dfp/v201805/native_style_service/create_native_styles.py similarity index 98% rename from examples/dfp/v201708/native_style_service/create_native_styles.py rename to examples/dfp/v201805/native_style_service/create_native_styles.py index 7f761dc6..a4b1838b 100755 --- a/examples/dfp/v201708/native_style_service/create_native_styles.py +++ b/examples/dfp/v201805/native_style_service/create_native_styles.py @@ -149,7 +149,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201708') + version='v201805') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/dfp/v201708/native_style_service/get_all_native_styles.py b/examples/dfp/v201805/native_style_service/get_all_native_styles.py similarity index 96% rename from examples/dfp/v201708/native_style_service/get_all_native_styles.py rename to examples/dfp/v201805/native_style_service/get_all_native_styles.py index 9ecf88a5..a2908ad8 100755 --- a/examples/dfp/v201708/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201805/native_style_service/get_all_native_styles.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201708') + version='v201805') # Create a statement to select native styles. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/network_service/__init__.py b/examples/dfp/v201805/network_service/__init__.py similarity index 100% rename from examples/dfp/v201708/network_service/__init__.py rename to examples/dfp/v201805/network_service/__init__.py diff --git a/examples/dfp/v201708/network_service/get_all_networks.py b/examples/dfp/v201805/network_service/get_all_networks.py similarity index 99% rename from examples/dfp/v201708/network_service/get_all_networks.py rename to examples/dfp/v201805/network_service/get_all_networks.py index b7ddc500..5f7b854d 100755 --- a/examples/dfp/v201708/network_service/get_all_networks.py +++ b/examples/dfp/v201805/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201708') + network_service = client.GetService('NetworkService', version='v201805') networks = network_service.getAllNetworks() diff --git a/examples/dfp/v201805/network_service/get_current_network.py b/examples/dfp/v201805/network_service/get_current_network.py new file mode 100755 index 00000000..519e617d --- /dev/null +++ b/examples/dfp/v201805/network_service/get_current_network.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 the current network.""" + + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201805') + + current_network = network_service.getCurrentNetwork() + + print ("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/network_service/make_test_network.py b/examples/dfp/v201805/network_service/make_test_network.py similarity index 99% rename from examples/dfp/v201708/network_service/make_test_network.py rename to examples/dfp/v201805/network_service/make_test_network.py index aae855ff..df62a590 100755 --- a/examples/dfp/v201708/network_service/make_test_network.py +++ b/examples/dfp/v201805/network_service/make_test_network.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201708') + network_service = client.GetService('NetworkService', version='v201805') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/dfp/v201708/order_service/__init__.py b/examples/dfp/v201805/order_service/__init__.py similarity index 100% rename from examples/dfp/v201708/order_service/__init__.py rename to examples/dfp/v201805/order_service/__init__.py diff --git a/examples/dfp/v201708/order_service/approve_orders.py b/examples/dfp/v201805/order_service/approve_orders.py similarity index 97% rename from examples/dfp/v201708/order_service/approve_orders.py rename to examples/dfp/v201805/order_service/approve_orders.py index cc7c4ca4..f3e667a8 100755 --- a/examples/dfp/v201708/order_service/approve_orders.py +++ b/examples/dfp/v201805/order_service/approve_orders.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201708') + order_service = client.GetService('OrderService', version='v201805') # Create a filter statement. today = datetime.date.today() @@ -51,7 +51,7 @@ def main(client): {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: orders_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/order_service/create_orders.py b/examples/dfp/v201805/order_service/create_orders.py similarity index 99% rename from examples/dfp/v201708/order_service/create_orders.py rename to examples/dfp/v201805/order_service/create_orders.py index 2e14104b..8afced0f 100755 --- a/examples/dfp/v201708/order_service/create_orders.py +++ b/examples/dfp/v201805/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201708') + order_service = client.GetService('OrderService', version='v201805') # Create order objects. orders = [] diff --git a/examples/dfp/v201708/order_service/get_all_orders.py b/examples/dfp/v201805/order_service/get_all_orders.py similarity index 99% rename from examples/dfp/v201708/order_service/get_all_orders.py rename to examples/dfp/v201805/order_service/get_all_orders.py index 5081c2b0..c376c2cc 100755 --- a/examples/dfp/v201708/order_service/get_all_orders.py +++ b/examples/dfp/v201805/order_service/get_all_orders.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201708') + order_service = client.GetService('OrderService', version='v201805') # Create a statement to select orders. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/order_service/get_orders_starting_soon.py b/examples/dfp/v201805/order_service/get_orders_starting_soon.py similarity index 97% rename from examples/dfp/v201708/order_service/get_orders_starting_soon.py rename to examples/dfp/v201805/order_service/get_orders_starting_soon.py index 367de8fa..1be982f8 100755 --- a/examples/dfp/v201708/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201805/order_service/get_orders_starting_soon.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201708') + order_service = client.GetService('OrderService', version='v201805') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) @@ -47,7 +47,7 @@ def main(client): # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], order['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/order_service/update_orders.py b/examples/dfp/v201805/order_service/update_orders.py similarity index 99% rename from examples/dfp/v201708/order_service/update_orders.py rename to examples/dfp/v201805/order_service/update_orders.py index 66bdbe8d..da67c9d1 100755 --- a/examples/dfp/v201708/order_service/update_orders.py +++ b/examples/dfp/v201805/order_service/update_orders.py @@ -28,7 +28,7 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201708') + order_service = client.GetService('OrderService', version='v201805') # Create statement object to select a single order by an ID. diff --git a/examples/dfp/v201708/package_service/create_packages.py b/examples/dfp/v201805/package_service/create_packages.py similarity index 99% rename from examples/dfp/v201708/package_service/create_packages.py rename to examples/dfp/v201805/package_service/create_packages.py index b6169a6e..dcbc8980 100755 --- a/examples/dfp/v201708/package_service/create_packages.py +++ b/examples/dfp/v201805/package_service/create_packages.py @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201708') + package_service = client.GetService('PackageService', version='v201805') # Create local package. package = { diff --git a/examples/dfp/v201708/package_service/create_proposal_line_items_from_packages.py b/examples/dfp/v201805/package_service/create_proposal_line_items_from_packages.py similarity index 99% rename from examples/dfp/v201708/package_service/create_proposal_line_items_from_packages.py rename to examples/dfp/v201805/package_service/create_proposal_line_items_from_packages.py index 0bcc0191..47b5f785 100755 --- a/examples/dfp/v201708/package_service/create_proposal_line_items_from_packages.py +++ b/examples/dfp/v201805/package_service/create_proposal_line_items_from_packages.py @@ -28,7 +28,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201708') + package_service = client.GetService('PackageService', version='v201805') # Create a statement to select the single package. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/package_service/get_all_packages.py b/examples/dfp/v201805/package_service/get_all_packages.py similarity index 99% rename from examples/dfp/v201708/package_service/get_all_packages.py rename to examples/dfp/v201805/package_service/get_all_packages.py index 30d8ac03..0875b1c1 100755 --- a/examples/dfp/v201708/package_service/get_all_packages.py +++ b/examples/dfp/v201805/package_service/get_all_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201708') + pkg_service = client.GetService('PackageService', version='v201805') # Create a statement to select packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/package_service/get_in_progress_packages.py b/examples/dfp/v201805/package_service/get_in_progress_packages.py similarity index 96% rename from examples/dfp/v201708/package_service/get_in_progress_packages.py rename to examples/dfp/v201805/package_service/get_in_progress_packages.py index b84a4599..b0918e84 100755 --- a/examples/dfp/v201708/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201805/package_service/get_in_progress_packages.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201708') + pkg_service = client.GetService('PackageService', version='v201805') # Create a statement to select packages. statement = (dfp.StatementBuilder() .Where('status = :status') @@ -38,7 +38,7 @@ def main(client): print( 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/placement_service/create_placements.py b/examples/dfp/v201805/placement_service/create_placements.py similarity index 99% rename from examples/dfp/v201708/placement_service/create_placements.py rename to examples/dfp/v201805/placement_service/create_placements.py index 8e272493..c37088f8 100755 --- a/examples/dfp/v201708/placement_service/create_placements.py +++ b/examples/dfp/v201805/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201708') - inventory_service = client.GetService('InventoryService', version='v201708') + placement_service = client.GetService('PlacementService', version='v201805') + inventory_service = client.GetService('InventoryService', version='v201805') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { diff --git a/examples/dfp/v201708/placement_service/deactivate_placements.py b/examples/dfp/v201805/placement_service/deactivate_placements.py similarity index 99% rename from examples/dfp/v201708/placement_service/deactivate_placements.py rename to examples/dfp/v201805/placement_service/deactivate_placements.py index 01d3f564..d7b61e2e 100755 --- a/examples/dfp/v201708/placement_service/deactivate_placements.py +++ b/examples/dfp/v201805/placement_service/deactivate_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201708') + placement_service = client.GetService('PlacementService', version='v201805') # Create query. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/placement_service/get_active_placements.py b/examples/dfp/v201805/placement_service/get_active_placements.py similarity index 96% rename from examples/dfp/v201708/placement_service/get_active_placements.py rename to examples/dfp/v201805/placement_service/get_active_placements.py index bcf3b097..39999fd0 100755 --- a/examples/dfp/v201708/placement_service/get_active_placements.py +++ b/examples/dfp/v201805/placement_service/get_active_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201708') + placement_service = client.GetService('PlacementService', version='v201805') # Create a statement to select placements. statement = (dfp.StatementBuilder() .Where('status = :status') @@ -38,7 +38,7 @@ def main(client): # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % (placement['id'], placement['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/placement_service/get_all_placements.py b/examples/dfp/v201805/placement_service/get_all_placements.py similarity index 99% rename from examples/dfp/v201708/placement_service/get_all_placements.py rename to examples/dfp/v201805/placement_service/get_all_placements.py index 26fbdc39..16561f3b 100755 --- a/examples/dfp/v201708/placement_service/get_all_placements.py +++ b/examples/dfp/v201805/placement_service/get_all_placements.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201708') + placement_service = client.GetService('PlacementService', version='v201805') # Create a statement to select placements. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/placement_service/update_placements.py b/examples/dfp/v201805/placement_service/update_placements.py similarity index 99% rename from examples/dfp/v201708/placement_service/update_placements.py rename to examples/dfp/v201805/placement_service/update_placements.py index 400a5389..aad1e1b8 100755 --- a/examples/dfp/v201708/placement_service/update_placements.py +++ b/examples/dfp/v201805/placement_service/update_placements.py @@ -28,7 +28,7 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201708') + placement_service = client.GetService('PlacementService', version='v201805') # Create query. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/premium_rate_service/__init__.py b/examples/dfp/v201805/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201708/premium_rate_service/__init__.py rename to examples/dfp/v201805/premium_rate_service/__init__.py diff --git a/examples/dfp/v201708/premium_rate_service/create_premium_rates.py b/examples/dfp/v201805/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/dfp/v201708/premium_rate_service/create_premium_rates.py rename to examples/dfp/v201805/premium_rate_service/create_premium_rates.py index bc7065ca..31d11807 100755 --- a/examples/dfp/v201708/premium_rate_service/create_premium_rates.py +++ b/examples/dfp/v201805/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201708') + version='v201805') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/dfp/v201708/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py similarity index 97% rename from examples/dfp/v201708/premium_rate_service/get_all_premium_rates.py rename to examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py index 1ee67756..f88f70f6 100755 --- a/examples/dfp/v201708/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201708') + 'PremiumRateService', version='v201805') # Create a statement to select premium rates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 95% rename from examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py index 8baf7e7c..84fd6c4c 100755 --- a/examples/dfp/v201708/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,7 +25,7 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201708') + 'PremiumRateService', version='v201805') # Create a statement to select premium rates. statement = (dfp.StatementBuilder() .Where('rateCardId = :rateCardId') @@ -43,7 +43,7 @@ def main(client, rate_card_id): 'ID "%d" was found.\n' % (premium_rate['id'], premium_rate['premium feature'], premium_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/premium_rate_service/update_premium_rates.py b/examples/dfp/v201805/premium_rate_service/update_premium_rates.py similarity index 97% rename from examples/dfp/v201708/premium_rate_service/update_premium_rates.py rename to examples/dfp/v201805/premium_rate_service/update_premium_rates.py index bce51970..bc1b97f8 100755 --- a/examples/dfp/v201708/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201805/premium_rate_service/update_premium_rates.py @@ -30,7 +30,7 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201708') + version='v201805') # Create statement object to select a single proposal by an ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/product_package_item_service/create_product_package_item.py b/examples/dfp/v201805/product_package_item_service/create_product_package_item.py similarity index 99% rename from examples/dfp/v201708/product_package_item_service/create_product_package_item.py rename to examples/dfp/v201805/product_package_item_service/create_product_package_item.py index e5f1fbdd..9ff0f6a9 100755 --- a/examples/dfp/v201708/product_package_item_service/create_product_package_item.py +++ b/examples/dfp/v201805/product_package_item_service/create_product_package_item.py @@ -32,7 +32,7 @@ def main(client): product_package_item_service = client.GetService('ProductPackageItemService', - version='v201708') + version='v201805') product_package_item = { # Set the product from which the product package item is created. diff --git a/examples/dfp/v201708/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py similarity index 97% rename from examples/dfp/v201708/product_package_item_service/get_all_product_package_items.py rename to examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py index 4cd57d50..bfee8248 100755 --- a/examples/dfp/v201708/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201708') + 'ProductPackageItemService', version='v201805') # Create a statement to select product package items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py similarity index 95% rename from examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py index 9b28e75e..68f18bc2 100755 --- a/examples/dfp/v201708/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,7 +25,7 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201708') + 'ProductPackageItemService', version='v201805') # Create a statement to select product package items. statement = (dfp.StatementBuilder() .Where('productPackageId = :productPackageId') @@ -43,7 +43,7 @@ def main(client, product_package_id): 'package ID "%d" was found.\n' % (product_package_item['id'], product_package_item['productId'], product_package_item['productPackageId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/product_package_service/create_product_packages.py b/examples/dfp/v201805/product_package_service/create_product_packages.py similarity index 96% rename from examples/dfp/v201708/product_package_service/create_product_packages.py rename to examples/dfp/v201805/product_package_service/create_product_packages.py index 692cd436..02418960 100755 --- a/examples/dfp/v201708/product_package_service/create_product_packages.py +++ b/examples/dfp/v201805/product_package_service/create_product_packages.py @@ -30,7 +30,7 @@ def main(client): product_package_service = client.GetService('ProductPackageService', - version='v201708') + version='v201805') # Create a local product package. product_package = { diff --git a/examples/dfp/v201708/product_package_service/get_active_product_packages.py b/examples/dfp/v201805/product_package_service/get_active_product_packages.py similarity index 94% rename from examples/dfp/v201708/product_package_service/get_active_product_packages.py rename to examples/dfp/v201805/product_package_service/get_active_product_packages.py index 7fec7d3c..ce6895bc 100755 --- a/examples/dfp/v201708/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201805/product_package_service/get_active_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201708') + 'ProductPackageService', version='v201805') # Create a statement to select product packages. statement = (dfp.StatementBuilder() .Where('status = :status') @@ -39,7 +39,7 @@ def main(client): # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % (product_package['id'], product_package['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/product_package_service/get_all_product_packages.py b/examples/dfp/v201805/product_package_service/get_all_product_packages.py similarity index 97% rename from examples/dfp/v201708/product_package_service/get_all_product_packages.py rename to examples/dfp/v201805/product_package_service/get_all_product_packages.py index f0d84bc8..0284c676 100755 --- a/examples/dfp/v201708/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201805/product_package_service/get_all_product_packages.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201708') + 'ProductPackageService', version='v201805') # Create a statement to select product packages. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/product_service/__init__.py b/examples/dfp/v201805/product_service/__init__.py similarity index 100% rename from examples/dfp/v201708/product_service/__init__.py rename to examples/dfp/v201805/product_service/__init__.py diff --git a/examples/dfp/v201708/product_service/get_all_products.py b/examples/dfp/v201805/product_service/get_all_products.py similarity index 99% rename from examples/dfp/v201708/product_service/get_all_products.py rename to examples/dfp/v201805/product_service/get_all_products.py index 74928f05..5465d3af 100755 --- a/examples/dfp/v201708/product_service/get_all_products.py +++ b/examples/dfp/v201805/product_service/get_all_products.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201708') + product_service = client.GetService('ProductService', version='v201805') # Create a statement to select products. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/product_service/get_products_for_product_template.py b/examples/dfp/v201805/product_service/get_products_for_product_template.py similarity index 96% rename from examples/dfp/v201708/product_service/get_products_for_product_template.py rename to examples/dfp/v201805/product_service/get_products_for_product_template.py index bdf48f18..d1e68df9 100755 --- a/examples/dfp/v201708/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201805/product_service/get_products_for_product_template.py @@ -24,7 +24,7 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201708') + product_service = client.GetService('ProductService', version='v201805') # Create a statement to select products. statement = (dfp.StatementBuilder() @@ -40,7 +40,7 @@ def main(client, product_template_id): # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % (product['id'], product['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/product_service/update_products.py b/examples/dfp/v201805/product_service/update_products.py similarity index 99% rename from examples/dfp/v201708/product_service/update_products.py rename to examples/dfp/v201805/product_service/update_products.py index 581c144b..55797315 100755 --- a/examples/dfp/v201708/product_service/update_products.py +++ b/examples/dfp/v201805/product_service/update_products.py @@ -29,7 +29,7 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201708') + product_service = client.GetService('ProductService', version='v201805') # Create statement object to select a single product by an ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/product_template_service/__init__.py b/examples/dfp/v201805/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201708/product_template_service/__init__.py rename to examples/dfp/v201805/product_template_service/__init__.py diff --git a/examples/dfp/v201708/product_template_service/activate_product_templates.py b/examples/dfp/v201805/product_template_service/activate_product_templates.py similarity index 95% rename from examples/dfp/v201708/product_template_service/activate_product_templates.py rename to examples/dfp/v201805/product_template_service/activate_product_templates.py index 062ab9b8..a6e68143 100755 --- a/examples/dfp/v201708/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201805/product_template_service/activate_product_templates.py @@ -31,7 +31,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201708') + 'ProductTemplateService', version='v201805') # Create query. statement = (dfp.StatementBuilder() @@ -56,7 +56,7 @@ def main(client, product_template_id): {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: product_templates_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/product_template_service/create_product_templates.py b/examples/dfp/v201805/product_template_service/create_product_templates.py similarity index 97% rename from examples/dfp/v201708/product_template_service/create_product_templates.py rename to examples/dfp/v201805/product_template_service/create_product_templates.py index 1146f315..180a9ed2 100755 --- a/examples/dfp/v201708/product_template_service/create_product_templates.py +++ b/examples/dfp/v201805/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201708') + 'ProductTemplateService', version='v201805') network_service = client.GetService( - 'NetworkService', version='v201708') + 'NetworkService', version='v201805') # Create a product template. product_template = { diff --git a/examples/dfp/v201708/product_template_service/create_programmatic_product_templates.py b/examples/dfp/v201805/product_template_service/create_programmatic_product_templates.py similarity index 96% rename from examples/dfp/v201708/product_template_service/create_programmatic_product_templates.py rename to examples/dfp/v201805/product_template_service/create_programmatic_product_templates.py index d896d79e..da6c8ac8 100755 --- a/examples/dfp/v201708/product_template_service/create_programmatic_product_templates.py +++ b/examples/dfp/v201805/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201708') + 'ProductTemplateService', version='v201805') network_service = client.GetService( - 'NetworkService', version='v201708') + 'NetworkService', version='v201805') product_template = { # Setting required Marketplace information. diff --git a/examples/dfp/v201708/product_template_service/get_all_product_templates.py b/examples/dfp/v201805/product_template_service/get_all_product_templates.py similarity index 97% rename from examples/dfp/v201708/product_template_service/get_all_product_templates.py rename to examples/dfp/v201805/product_template_service/get_all_product_templates.py index 0f8b4731..4654b1a4 100755 --- a/examples/dfp/v201708/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201805/product_template_service/get_all_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201708') + 'ProductTemplateService', version='v201805') # Create a statement to select product templates. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py similarity index 94% rename from examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py rename to examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py index 8678245e..1df80e65 100755 --- a/examples/dfp/v201708/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201708') + 'ProductTemplateService', version='v201805') # Create a statement to select product templates. statement = (dfp.StatementBuilder() .Where('lineItemType = :lineItemType') @@ -39,7 +39,7 @@ def main(client): # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % (product_template['id'], product_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/product_template_service/update_product_templates.py b/examples/dfp/v201805/product_template_service/update_product_templates.py similarity index 98% rename from examples/dfp/v201708/product_template_service/update_product_templates.py rename to examples/dfp/v201805/product_template_service/update_product_templates.py index 6824719d..1533609d 100755 --- a/examples/dfp/v201708/product_template_service/update_product_templates.py +++ b/examples/dfp/v201805/product_template_service/update_product_templates.py @@ -30,7 +30,7 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201708') + 'ProductTemplateService', version='v201805') # Create a statement to select a single product template by ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/proposal_line_item_service/__init__.py b/examples/dfp/v201805/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201708/proposal_line_item_service/__init__.py rename to examples/dfp/v201805/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py similarity index 96% rename from examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py rename to examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py index 4d460956..9e6b738e 100755 --- a/examples/dfp/v201708/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201708') + 'ProposalLineItemService', version='v201805') # Create query. statement = (dfp.StatementBuilder() @@ -58,7 +58,7 @@ def main(client, proposal_line_item_id): {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposal_line_items_archived += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 98% rename from examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py index 4c9ac80a..a42f6dd1 100755 --- a/examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -40,8 +40,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') + 'ProposalLineItemService', version='v201805') + network_service = client.GetService('NetworkService', version='v201805') # Get the root ad unit to target. root_ad_unit_id = ( diff --git a/examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 98% rename from examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 71210849..23456dc5 100755 --- a/examples/dfp/v201708/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -34,8 +34,8 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') + 'ProposalLineItemService', version='v201805') + network_service = client.GetService('NetworkService', version='v201805') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/dfp/v201708/proposal_line_item_service/create_proposal_line_items.py b/examples/dfp/v201805/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/dfp/v201708/proposal_line_item_service/create_proposal_line_items.py rename to examples/dfp/v201805/proposal_line_item_service/create_proposal_line_items.py index 227cc3e1..4ea8e9b4 100755 --- a/examples/dfp/v201708/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/dfp/v201805/proposal_line_item_service/create_proposal_line_items.py @@ -42,8 +42,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') + 'ProposalLineItemService', version='v201805') + network_service = client.GetService('NetworkService', version='v201805') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/dfp/v201708/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py similarity index 97% rename from examples/dfp/v201708/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py index 5e162cd9..45bb7c33 100755 --- a/examples/dfp/v201708/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201708') + 'ProposalLineItemService', version='v201805') # Create a statement to select proposal line items. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 5bd3138d..e39257b6 100755 --- a/examples/dfp/v201708/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,7 +25,7 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201708') + 'ProposalLineItemService', version='v201805') # Create a statement to select proposal line items. statement = (dfp.StatementBuilder() .Where('proposalId = :proposalId') @@ -41,7 +41,7 @@ def main(client, proposal_id): # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % (proposal_line_item['id'], proposal_line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py similarity index 97% rename from examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py rename to examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py index ffda2e86..ec2f4703 100755 --- a/examples/dfp/v201708/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py @@ -31,7 +31,7 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201708') + 'ProposalLineItemService', version='v201805') # Create statement to select a proposal line item. diff --git a/examples/dfp/v201708/proposal_service/__init__.py b/examples/dfp/v201805/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201708/proposal_service/__init__.py rename to examples/dfp/v201805/proposal_service/__init__.py diff --git a/examples/dfp/v201708/proposal_service/create_programmatic_proposals.py b/examples/dfp/v201805/proposal_service/create_programmatic_proposals.py similarity index 98% rename from examples/dfp/v201708/proposal_service/create_programmatic_proposals.py rename to examples/dfp/v201805/proposal_service/create_programmatic_proposals.py index 9e863535..d72aafc6 100755 --- a/examples/dfp/v201708/proposal_service/create_programmatic_proposals.py +++ b/examples/dfp/v201805/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') + proposal_service = client.GetService('ProposalService', version='v201805') + network_service = client.GetService('NetworkService', version='v201805') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201708/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 99% rename from examples/dfp/v201708/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 14230f75..ba0cf308 100755 --- a/examples/dfp/v201708/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201708') + proposal_service = client.GetService('ProposalService', version='v201805') proposal = { # Setting required Marketplace information. diff --git a/examples/dfp/v201708/proposal_service/create_proposals.py b/examples/dfp/v201805/proposal_service/create_proposals.py similarity index 99% rename from examples/dfp/v201708/proposal_service/create_proposals.py rename to examples/dfp/v201805/proposal_service/create_proposals.py index cf336380..6cf119ac 100755 --- a/examples/dfp/v201708/proposal_service/create_proposals.py +++ b/examples/dfp/v201805/proposal_service/create_proposals.py @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201708') - network_service = client.GetService('NetworkService', version='v201708') + proposal_service = client.GetService('ProposalService', version='v201805') + network_service = client.GetService('NetworkService', version='v201805') # Create proposal objects. proposal = { diff --git a/examples/dfp/v201708/proposal_service/get_all_proposals.py b/examples/dfp/v201805/proposal_service/get_all_proposals.py similarity index 99% rename from examples/dfp/v201708/proposal_service/get_all_proposals.py rename to examples/dfp/v201805/proposal_service/get_all_proposals.py index 1b8cbb9a..9526dfd9 100755 --- a/examples/dfp/v201708/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201805/proposal_service/get_all_proposals.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201708') + proposal_service = client.GetService('ProposalService', version='v201805') # Create a statement to select proposals. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/proposal_service/get_marketplace_comments.py b/examples/dfp/v201805/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/dfp/v201708/proposal_service/get_marketplace_comments.py rename to examples/dfp/v201805/proposal_service/get_marketplace_comments.py index 288a73d3..72d835d4 100755 --- a/examples/dfp/v201708/proposal_service/get_marketplace_comments.py +++ b/examples/dfp/v201805/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201708') + 'ProposalService', version='v201805') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py similarity index 96% rename from examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py rename to examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py index fb7354a9..04cfd9b3 100755 --- a/examples/dfp/v201708/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201708') + proposal_service = client.GetService('ProposalService', version='v201805') # Create a statement to select proposals. statement = (dfp.StatementBuilder() .Where('status = :status') @@ -37,7 +37,7 @@ def main(client): # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % (proposal['id'], proposal['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201805/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/dfp/v201708/proposal_service/request_buyers_acceptance.py rename to examples/dfp/v201805/proposal_service/request_buyers_acceptance.py index b8c8690b..70f8b1ae 100755 --- a/examples/dfp/v201708/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201805/proposal_service/request_buyers_acceptance.py @@ -26,7 +26,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201708') + proposal_service = client.GetService('ProposalService', version='v201805') # Create query. statement = (dfp.StatementBuilder() @@ -49,7 +49,7 @@ def main(client, proposal_id): {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposals_pushed_to_marketplace += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py similarity index 97% rename from examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py rename to examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py index a426566f..09deb00b 100755 --- a/examples/dfp/v201708/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201708') + proposal_service = client.GetService('ProposalService', version='v201805') # Create query. statement = (dfp.StatementBuilder() @@ -50,7 +50,7 @@ def main(client, proposal_id): {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposals_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/proposal_service/update_proposals.py b/examples/dfp/v201805/proposal_service/update_proposals.py similarity index 99% rename from examples/dfp/v201708/proposal_service/update_proposals.py rename to examples/dfp/v201805/proposal_service/update_proposals.py index 29f4bc91..417fe19e 100755 --- a/examples/dfp/v201708/proposal_service/update_proposals.py +++ b/examples/dfp/v201805/proposal_service/update_proposals.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201708') + proposal_service = client.GetService('ProposalService', version='v201805') # Create statement object to select a single proposal by an ID. diff --git a/examples/dfp/v201708/publisher_query_language_service/__init__.py b/examples/dfp/v201805/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201708/publisher_query_language_service/__init__.py rename to examples/dfp/v201805/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201708/publisher_query_language_service/fetch_match_tables.py b/examples/dfp/v201805/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/dfp/v201708/publisher_query_language_service/fetch_match_tables.py rename to examples/dfp/v201805/publisher_query_language_service/fetch_match_tables.py index cc495e72..9d1c1c42 100755 --- a/examples/dfp/v201708/publisher_query_language_service/fetch_match_tables.py +++ b/examples/dfp/v201805/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201708') + report_downloader = client.GetDataDownloader(version='v201805') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_all_browsers.py b/examples/dfp/v201805/publisher_query_language_service/get_all_browsers.py new file mode 100755 index 00000000..794362d6 --- /dev/null +++ b/examples/dfp/v201805/publisher_query_language_service/get_all_browsers.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 browsers available to target from the Browser table. + +Other tables include 'Bandwidth_Group', 'Browser_Language', +'Device_Capability', 'Operating_System', etc... + +A full list of available criteria tables can be found at +https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService +""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201805') + + with tempfile.NamedTemporaryFile( + prefix='browser_data_', + suffix='.csv', mode='w', delete=False) as browser_data_file: + + browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion ' + 'FROM Browser ' + 'ORDER BY BrowserName ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + browser_pql_query, browser_data_file) + + print 'Saved browser data to... %s' % browser_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/dfp/v201805/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/dfp/v201708/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/dfp/v201805/publisher_query_language_service/get_all_programmatic_buyers.py index 7f5895ce..cf7d6e7d 100755 --- a/examples/dfp/v201708/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/dfp/v201805/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201708') + data_downloader = client.GetDataDownloader(version='v201805') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py new file mode 100755 index 00000000..0948ced6 --- /dev/null +++ b/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 downloads geo targeting constants using PQL.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + +# Set the type of geo target to query for. +GEO_TARGET_TYPE = 'City' + + +def main(client, geo_target_type): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201805') + + with tempfile.NamedTemporaryFile( + prefix='geo_data_', + suffix='.csv', mode='w', delete=False) as geo_data_file: + + geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' + 'CountryCode ' + 'FROM Geo_Target ' + 'WHERE Type = :type AND Targetable = true ' + 'ORDER BY CountryCode ASC, Name ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + geo_pql_query, geo_data_file, {'type': geo_target_type}) + + print 'Saved geo data to... %s' % geo_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client, GEO_TARGET_TYPE) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_line_items_named_like.py b/examples/dfp/v201805/publisher_query_language_service/get_line_items_named_like.py new file mode 100755 index 00000000..6948300b --- /dev/null +++ b/examples/dfp/v201805/publisher_query_language_service/get_line_items_named_like.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 fetches line items from the pql table with a LIKE clause.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201805') + + with tempfile.NamedTemporaryFile( + prefix='line_items_', + suffix='.csv', mode='w', delete=False) as line_items_file: + + line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item " + "WHERE Name LIKE 'line item%' " + "ORDER BY Id ASC") + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + line_items_pql_query, line_items_file) + + print 'Saved line items to... %s' % line_items_file.name + + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py b/examples/dfp/v201805/publisher_query_language_service/get_recent_changes.py similarity index 99% rename from examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py rename to examples/dfp/v201805/publisher_query_language_service/get_recent_changes.py index e696588b..a312739b 100755 --- a/examples/dfp/v201708/publisher_query_language_service/get_recent_changes.py +++ b/examples/dfp/v201805/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201708') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201805') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) diff --git a/examples/dfp/v201708/rate_card_service/__init__.py b/examples/dfp/v201805/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201708/rate_card_service/__init__.py rename to examples/dfp/v201805/rate_card_service/__init__.py diff --git a/examples/dfp/v201708/rate_card_service/create_rate_cards.py b/examples/dfp/v201805/rate_card_service/create_rate_cards.py similarity index 99% rename from examples/dfp/v201708/rate_card_service/create_rate_cards.py rename to examples/dfp/v201805/rate_card_service/create_rate_cards.py index ebe65a36..1293a26b 100755 --- a/examples/dfp/v201708/rate_card_service/create_rate_cards.py +++ b/examples/dfp/v201805/rate_card_service/create_rate_cards.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201708') + rate_card_service = client.GetService('RateCardService', version='v201805') # Create a rate card. rate_card = { diff --git a/examples/dfp/v201708/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201805/rate_card_service/get_all_rate_cards.py similarity index 99% rename from examples/dfp/v201708/rate_card_service/get_all_rate_cards.py rename to examples/dfp/v201805/rate_card_service/get_all_rate_cards.py index 3dbeea8f..8c5b7a71 100755 --- a/examples/dfp/v201708/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201805/rate_card_service/get_all_rate_cards.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201708') + rate_card_service = client.GetService('RateCardService', version='v201805') # Create a statement to select rate cards. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py similarity index 96% rename from examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py rename to examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py index e6c21125..e6f99eaa 100755 --- a/examples/dfp/v201708/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201708') + rate_card_service = client.GetService('RateCardService', version='v201805') # Create a statement to select rate cards. statement = (dfp.StatementBuilder() .Where('forMarketplace = :forMarketplace') @@ -41,7 +41,7 @@ def main(client): 'Rate card with ID "%d", name "%s", and currency code "%s" was ' 'found.\n' % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 97% rename from examples/dfp/v201708/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 926f3fa2..1c30a413 100755 --- a/examples/dfp/v201708/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201708')) + 'ReconciliationLineItemReportService', version='v201805')) # Create a statement to select reconciliation line item reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/dfp/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 97% rename from examples/dfp/v201708/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/dfp/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 1dd11335..25eb176c 100755 --- a/examples/dfp/v201708/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/dfp/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201708')) + 'ReconciliationLineItemReportService', version='v201805')) # Create a statement to select a reconciliation line item report. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 95% rename from examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index c0a53e7a..4f40500d 100755 --- a/examples/dfp/v201708/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,7 +25,7 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201708') + 'ReconciliationOrderReportService', version='v201805') # Create a statement to select reconciliation order reports. statement = (dfp.StatementBuilder() .Where('reconciliationReportId = :reconciliationReportId') @@ -45,7 +45,7 @@ def main(client, reconciliation_report_id): print('Reconciliation order report with ID "%d" and status "%s" was ' 'found.\n' % (reconciliation_order_report['id'], reconciliation_order_report['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/dfp/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 97% rename from examples/dfp/v201708/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/dfp/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 0eef8e42..1ad5a015 100755 --- a/examples/dfp/v201708/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/dfp/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -30,7 +30,7 @@ def main(client): # Initialize appropriate service. reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201708')) + 'ReconciliationOrderReportService', version='v201805')) # Create a statement to select reconciliation order reports. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 95% rename from examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 1e8943f7..9aa1e8f4 100755 --- a/examples/dfp/v201708/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -27,7 +27,7 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201708') + 'ReconciliationReportRowService', version='v201805') # Create a statement to select reconciliation report rows. statement = (dfp.StatementBuilder() @@ -51,7 +51,7 @@ def main(client, reconciliation_report_id): (reconciliation_report_row['id'], reconciliation_report_row['reconciliationSource'], reconciliation_report_row['reconciledVolume'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/dfp/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 97% rename from examples/dfp/v201708/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/dfp/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py index 9a8ceae4..1afe7030 100755 --- a/examples/dfp/v201708/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/dfp/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201708')) + 'ReconciliationReportRowService', version='v201805')) # Create a statement to select reconciliation report rows. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 97% rename from examples/dfp/v201708/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py index ffa37af6..99ca0297 100755 --- a/examples/dfp/v201708/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201708') + 'ReconciliationReportService', version='v201805') # Create a statement to select reconciliation reports. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 95% rename from examples/dfp/v201708/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 133f4195..5e24719b 100755 --- a/examples/dfp/v201708/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201708') + 'ReconciliationReportService', version='v201805') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) @@ -50,7 +50,7 @@ def main(client): 'Reconciliation report with ID "%d" and start date "%s" was found.' '\n' % (reconciliation_report['id'], last_month.strftime('%Y-%m-01'))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/report_service/__init__.py b/examples/dfp/v201805/report_service/__init__.py similarity index 100% rename from examples/dfp/v201708/report_service/__init__.py rename to examples/dfp/v201805/report_service/__init__.py diff --git a/examples/dfp/v201805/report_service/run_ad_exchange_report.py b/examples/dfp/v201805/report_service/run_ad_exchange_report.py new file mode 100755 index 00000000..e68a20ef --- /dev/null +++ b/examples/dfp/v201805/report_service/run_ad_exchange_report.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Runs a report on Ad Exchange data via the DFP API.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import dfp +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201805') + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'], + 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS', + 'AD_EXCHANGE_ESTIMATED_REVENUE'], + 'dateRangeType': 'LAST_WEEK', + 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time + 'adxReportCurrency': 'EUR' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.DfpReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + dfp_client = dfp.DfpClient.LoadFromStorage() + main(dfp_client) diff --git a/examples/dfp/v201708/report_service/run_delivery_report.py b/examples/dfp/v201805/report_service/run_delivery_report.py similarity index 97% rename from examples/dfp/v201708/report_service/run_delivery_report.py rename to examples/dfp/v201805/report_service/run_delivery_report.py index cf6beb2e..ae9857e8 100755 --- a/examples/dfp/v201708/report_service/run_delivery_report.py +++ b/examples/dfp/v201805/report_service/run_delivery_report.py @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201708') + report_downloader = client.GetDataDownloader(version='v201805') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201708/report_service/run_inventory_report.py b/examples/dfp/v201805/report_service/run_inventory_report.py similarity index 97% rename from examples/dfp/v201708/report_service/run_inventory_report.py rename to examples/dfp/v201805/report_service/run_inventory_report.py index b134c2d2..410f3392 100755 --- a/examples/dfp/v201708/report_service/run_inventory_report.py +++ b/examples/dfp/v201805/report_service/run_inventory_report.py @@ -25,9 +25,9 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201708') + network_service = client.GetService('NetworkService', version='v201805') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201708') + report_downloader = client.GetDataDownloader(version='v201805') # Get root ad unit id for network. root_ad_unit_id = ( diff --git a/examples/dfp/v201708/report_service/run_reach_report.py b/examples/dfp/v201805/report_service/run_reach_report.py similarity index 96% rename from examples/dfp/v201708/report_service/run_reach_report.py rename to examples/dfp/v201805/report_service/run_reach_report.py index a50d6169..8d0af11f 100755 --- a/examples/dfp/v201708/report_service/run_reach_report.py +++ b/examples/dfp/v201805/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201708') + report_downloader = client.GetDataDownloader(version='v201805') # Create report job. report_job = { diff --git a/examples/dfp/v201708/report_service/run_report_and_create_match_table.py b/examples/dfp/v201805/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/dfp/v201708/report_service/run_report_and_create_match_table.py rename to examples/dfp/v201805/report_service/run_report_and_create_match_table.py index 572d2c3c..cab552c7 100755 --- a/examples/dfp/v201708/report_service/run_report_and_create_match_table.py +++ b/examples/dfp/v201805/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201708') + report_downloader = client.GetDataDownloader(version='v201805') try: # Run the report and wait for it to finish. diff --git a/examples/dfp/v201708/report_service/run_report_with_custom_fields.py b/examples/dfp/v201805/report_service/run_report_with_custom_fields.py similarity index 95% rename from examples/dfp/v201708/report_service/run_report_with_custom_fields.py rename to examples/dfp/v201805/report_service/run_report_with_custom_fields.py index 3cb787c7..b3db8e8b 100755 --- a/examples/dfp/v201708/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201805/report_service/run_report_with_custom_fields.py @@ -28,9 +28,9 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201708') + line_item_service = client.GetService('LineItemService', version='v201805') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201708') + report_downloader = client.GetDataDownloader(version='v201805') # Filter for line items of a given order. statement = (dfp.StatementBuilder() @@ -50,7 +50,7 @@ def main(client, order_id): if 'customFieldValues' in line_item: for custom_field_value in line_item['customFieldValues']: custom_field_ids.add(custom_field_value['customFieldId']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/report_service/run_sales_report.py b/examples/dfp/v201805/report_service/run_sales_report.py similarity index 96% rename from examples/dfp/v201708/report_service/run_sales_report.py rename to examples/dfp/v201805/report_service/run_sales_report.py index cdea66fb..30587088 100755 --- a/examples/dfp/v201708/report_service/run_sales_report.py +++ b/examples/dfp/v201805/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201708') + report_downloader = client.GetDataDownloader(version='v201805') # Create report job. report_job = { diff --git a/examples/dfp/v201708/report_service/run_saved_query.py b/examples/dfp/v201805/report_service/run_saved_query.py similarity index 97% rename from examples/dfp/v201708/report_service/run_saved_query.py rename to examples/dfp/v201805/report_service/run_saved_query.py index 9b03ffcb..03d0a556 100755 --- a/examples/dfp/v201708/report_service/run_saved_query.py +++ b/examples/dfp/v201805/report_service/run_saved_query.py @@ -28,10 +28,10 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201708') + report_service = client.GetService('ReportService', version='v201805') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201708') + report_downloader = client.GetDataDownloader(version='v201805') # Create statement object to filter for an order. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/suggested_ad_unit_service/__init__.py b/examples/dfp/v201805/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201708/suggested_ad_unit_service/__init__.py rename to examples/dfp/v201805/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201708/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 88% rename from examples/dfp/v201708/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py index e21553b0..385f20ee 100755 --- a/examples/dfp/v201708/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,20 +29,12 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201708') - - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': THRESHOLD_NUMBER_OF_REQUESTS - } - }] - - query = 'WHERE numRequests > :numRequests' + 'SuggestedAdUnitService', version='v201805') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (dfp.StatementBuilder() + .Where('numRequests > :numRequests') + .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 # Get suggested ad units by statement. diff --git a/examples/dfp/v201708/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 97% rename from examples/dfp/v201708/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py index 4bd9cb1f..3e5b38b6 100755 --- a/examples/dfp/v201708/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201708') + 'SuggestedAdUnitService', version='v201805') # Create a statement to select suggested ad units. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 95% rename from examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 7c2655d0..639a2262 100755 --- a/examples/dfp/v201708/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,7 +25,7 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201708') + 'SuggestedAdUnitService', version='v201805') # Create a statement to select suggested ad units. statement = (dfp.StatementBuilder() .Where('numRequests >= :numRequests') @@ -42,7 +42,7 @@ def main(client, num_requests): print( 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/team_service/__init__.py b/examples/dfp/v201805/team_service/__init__.py similarity index 100% rename from examples/dfp/v201708/team_service/__init__.py rename to examples/dfp/v201805/team_service/__init__.py diff --git a/examples/dfp/v201708/team_service/create_teams.py b/examples/dfp/v201805/team_service/create_teams.py similarity index 96% rename from examples/dfp/v201708/team_service/create_teams.py rename to examples/dfp/v201805/team_service/create_teams.py index 7e446598..47f77d78 100755 --- a/examples/dfp/v201708/team_service/create_teams.py +++ b/examples/dfp/v201805/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201708') + team_service = client.GetService('TeamService', version='v201805') # Create team objects. teams = [] diff --git a/examples/dfp/v201708/team_service/get_all_teams.py b/examples/dfp/v201805/team_service/get_all_teams.py similarity index 95% rename from examples/dfp/v201708/team_service/get_all_teams.py rename to examples/dfp/v201805/team_service/get_all_teams.py index 765cd03e..aa9168b9 100755 --- a/examples/dfp/v201708/team_service/get_all_teams.py +++ b/examples/dfp/v201805/team_service/get_all_teams.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201708') + team_service = client.GetService('TeamService', version='v201805') # Create a statement to select teams. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/team_service/update_teams.py b/examples/dfp/v201805/team_service/update_teams.py similarity index 96% rename from examples/dfp/v201708/team_service/update_teams.py rename to examples/dfp/v201805/team_service/update_teams.py index c292badc..947534c5 100755 --- a/examples/dfp/v201708/team_service/update_teams.py +++ b/examples/dfp/v201805/team_service/update_teams.py @@ -34,7 +34,7 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201708') + team_service = client.GetService('TeamService', version='v201805') # Create a filter statement to select a single team by ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/user_service/__init__.py b/examples/dfp/v201805/user_service/__init__.py similarity index 100% rename from examples/dfp/v201708/user_service/__init__.py rename to examples/dfp/v201805/user_service/__init__.py diff --git a/examples/dfp/v201708/user_service/create_users.py b/examples/dfp/v201805/user_service/create_users.py similarity index 95% rename from examples/dfp/v201708/user_service/create_users.py rename to examples/dfp/v201805/user_service/create_users.py index 2e2474f6..b84079c4 100755 --- a/examples/dfp/v201708/user_service/create_users.py +++ b/examples/dfp/v201805/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201708') + user_service = client.GetService('UserService', version='v201805') # Create user objects. users = [ diff --git a/examples/dfp/v201708/user_service/deactivate_users.py b/examples/dfp/v201805/user_service/deactivate_users.py similarity index 96% rename from examples/dfp/v201708/user_service/deactivate_users.py rename to examples/dfp/v201805/user_service/deactivate_users.py index 8f9afa46..7b9ac397 100755 --- a/examples/dfp/v201708/user_service/deactivate_users.py +++ b/examples/dfp/v201805/user_service/deactivate_users.py @@ -30,7 +30,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201708') + user_service = client.GetService('UserService', version='v201805') # Create query. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/user_service/get_all_roles.py b/examples/dfp/v201805/user_service/get_all_roles.py similarity index 100% rename from examples/dfp/v201708/user_service/get_all_roles.py rename to examples/dfp/v201805/user_service/get_all_roles.py diff --git a/examples/dfp/v201708/user_service/get_all_users.py b/examples/dfp/v201805/user_service/get_all_users.py similarity index 95% rename from examples/dfp/v201708/user_service/get_all_users.py rename to examples/dfp/v201805/user_service/get_all_users.py index 7ec1f61c..69f438b0 100755 --- a/examples/dfp/v201708/user_service/get_all_users.py +++ b/examples/dfp/v201805/user_service/get_all_users.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201708') + user_service = client.GetService('UserService', version='v201805') # Create a statement to select users. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/user_service/get_current_user.py b/examples/dfp/v201805/user_service/get_current_user.py similarity index 94% rename from examples/dfp/v201708/user_service/get_current_user.py rename to examples/dfp/v201805/user_service/get_current_user.py index 5f1b32e5..2eace62d 100755 --- a/examples/dfp/v201708/user_service/get_current_user.py +++ b/examples/dfp/v201805/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201708') + user_service = client.GetService('UserService', version='v201805') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/dfp/v201708/user_service/get_user_by_email_address.py b/examples/dfp/v201805/user_service/get_user_by_email_address.py similarity index 93% rename from examples/dfp/v201708/user_service/get_user_by_email_address.py rename to examples/dfp/v201805/user_service/get_user_by_email_address.py index 24671e74..783cfdbb 100755 --- a/examples/dfp/v201708/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201805/user_service/get_user_by_email_address.py @@ -24,7 +24,7 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201708') + user_service = client.GetService('UserService', version='v201805') # Create a statement to select users. statement = (dfp.StatementBuilder() .Where('email = :email') @@ -39,7 +39,7 @@ def main(client, email_address): # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], user['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/user_service/update_users.py b/examples/dfp/v201805/user_service/update_users.py similarity index 96% rename from examples/dfp/v201708/user_service/update_users.py rename to examples/dfp/v201805/user_service/update_users.py index cd415ff5..289817f7 100755 --- a/examples/dfp/v201708/user_service/update_users.py +++ b/examples/dfp/v201805/user_service/update_users.py @@ -28,7 +28,7 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201708') + user_service = client.GetService('UserService', version='v201805') # Create query. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/user_team_association_service/__init__.py b/examples/dfp/v201805/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201708/user_team_association_service/__init__.py rename to examples/dfp/v201805/user_team_association_service/__init__.py diff --git a/examples/dfp/v201708/user_team_association_service/create_user_team_associations.py b/examples/dfp/v201805/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/dfp/v201708/user_team_association_service/create_user_team_associations.py rename to examples/dfp/v201805/user_team_association_service/create_user_team_associations.py index de11c509..77f34cb4 100755 --- a/examples/dfp/v201708/user_team_association_service/create_user_team_associations.py +++ b/examples/dfp/v201805/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201708') + 'UserTeamAssociationService', version='v201805') user_team_associations = [] for user_id in user_ids: diff --git a/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py b/examples/dfp/v201805/user_team_association_service/delete_user_team_associations.py similarity index 97% rename from examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py rename to examples/dfp/v201805/user_team_association_service/delete_user_team_associations.py index 8cce293c..d591f5e9 100755 --- a/examples/dfp/v201708/user_team_association_service/delete_user_team_associations.py +++ b/examples/dfp/v201805/user_team_association_service/delete_user_team_associations.py @@ -35,7 +35,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201708') + 'UserTeamAssociationService', version='v201805') # Create filter text to select user team associations by the user ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py similarity index 97% rename from examples/dfp/v201708/user_team_association_service/get_all_user_team_associations.py rename to examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py index df40c5ad..ff2d3b9c 100755 --- a/examples/dfp/v201708/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201708') + 'UserTeamAssociationService', version='v201805') # Create a statement to select user team associations. statement = dfp.StatementBuilder() diff --git a/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py rename to examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py index fa78d834..30fd1bf5 100755 --- a/examples/dfp/v201708/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py @@ -25,7 +25,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201708') + 'UserTeamAssociationService', version='v201805') # Create a statement to select user team associations. statement = (dfp.StatementBuilder() .Where('userId = :userId') @@ -42,7 +42,7 @@ def main(client, user_id): print('User team association with user ID "%d" and team ID "%d" was ' 'found.\n' % (user_team_association['userId'], user_team_association['teamId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201805/user_team_association_service/update_user_team_associations.py similarity index 98% rename from examples/dfp/v201708/user_team_association_service/update_user_team_associations.py rename to examples/dfp/v201805/user_team_association_service/update_user_team_associations.py index 8e3152c7..b021ddaa 100755 --- a/examples/dfp/v201708/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201805/user_team_association_service/update_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201708') + 'UserTeamAssociationService', version='v201805') # Create filter text to select user team associations by the user ID. statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201708/workflow_request_service/__init__.py b/examples/dfp/v201805/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201708/workflow_request_service/__init__.py rename to examples/dfp/v201805/workflow_request_service/__init__.py diff --git a/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py similarity index 95% rename from examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py rename to examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py index d9d9ff51..fb814d38 100755 --- a/examples/dfp/v201708/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201708') + version='v201805') # Create a filter statement. statement = (dfp.StatementBuilder() @@ -58,7 +58,7 @@ def main(client, proposal_id): statement.ToStatement()) if result and int(result['numChanges']) > 0: workflow_approval_requests_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py similarity index 95% rename from examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py rename to examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py index 26d50042..92b3bb63 100755 --- a/examples/dfp/v201708/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201708') + 'WorkflowRequestService', version='v201805') # Create a statement to select workflow requests. statement = (dfp.StatementBuilder() .Where('type = :type') @@ -44,7 +44,7 @@ def main(client): '"%d" was found.\n' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py similarity index 95% rename from examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py index a0a39fd3..ff657b8c 100755 --- a/examples/dfp/v201708/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201708') + 'WorkflowRequestService', version='v201805') # Create a statement to select workflow requests. statement = (dfp.StatementBuilder() .Where('type = :type') @@ -44,7 +44,7 @@ def main(client): '"%d" was found.\n' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 96% rename from examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py index 79fef4c0..da7b8c1b 100755 --- a/examples/dfp/v201708/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,7 +31,7 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201708') + version='v201805') # Create a filter statement. statement = (dfp.StatementBuilder() @@ -61,7 +61,7 @@ def main(client, proposal_id): if result and int(result['numChanges']) > 0: workflow_external_condition_requests_triggered += int( result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break diff --git a/googleads.yaml b/googleads.yaml index d2247f99..7e31c359 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -122,3 +122,10 @@ dfp: # issues please report them and fall back to suds. # ################################################################################ # soap_impl: zeep +################################################################################ +# Custom HTTP headers (optional) # +# Specify one or more custom headers to pass along with all requests to # +# the API. # +################################################################################ +# custom_http_headers: +# X-My-Header: 'content' diff --git a/googleads/adwords.py b/googleads/adwords.py index 12c7f7da..598dcc59 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -291,6 +291,7 @@ def __init__(self, developer_token, oauth2_client, self.client_customer_id = kwargs.get('client_customer_id') self.user_agent = user_agent self.soap_impl = soap_impl + self.custom_http_headers = kwargs.get('custom_http_headers') # Verify that the provided user_agent contains only ASCII characters. In # both Python 2 and Python 3, a UnicodeEncodeError will be raised if it # contains a non-ASCII character. @@ -356,7 +357,8 @@ def GetService(self, service_name, version=None, server=None): service = googleads.common.GetServiceClassForLibrary(self.soap_impl)( self._SOAP_SERVICE_FORMAT % ( server, version_service_mapping, version, service_name), - _AdWordsHeaderHandler(self, version, self.enable_compression), + _AdWordsHeaderHandler( + self, version, self.enable_compression, self.custom_http_headers), _AdWordsPacker, self.proxy_config, self.timeout, @@ -433,7 +435,8 @@ class _AdWordsHeaderHandler(googleads.common.HeaderHandler): # The content type of report download requests _CONTENT_TYPE = 'application/x-www-form-urlencoded' - def __init__(self, adwords_client, version, enable_compression): + def __init__(self, adwords_client, version, + enable_compression, custom_http_headers=None): """Initializes an AdWordsHeaderHandler. Args: @@ -445,10 +448,13 @@ def __init__(self, adwords_client, version, enable_compression): enable_compression: A boolean indicating if you want to enable compression of the SOAP response. If True, the SOAP response will use gzip compression, and will be decompressed for you automatically. + custom_http_headers: A dictionary of custom HTTP headers to send with all + requests. """ self._adwords_client = adwords_client self._version = version self.enable_compression = enable_compression + self.custom_http_headers = custom_http_headers or {} def GetSOAPHeaders(self, create_method): """Returns the SOAP headers required for request authorization. @@ -479,6 +485,9 @@ def GetHTTPHeaders(self): http_headers = self._adwords_client.oauth2_client.CreateHttpHeader() if self.enable_compression: http_headers['accept-encoding'] = 'gzip' + + http_headers.update(self.custom_http_headers) + return http_headers def GetReportDownloadHeaders(self, **kwargs): @@ -525,6 +534,7 @@ def GetReportDownloadHeaders(self, **kwargs): googleads.common.GenerateLibSig(self._PRODUCT_SIG), ',gzip']) }) + headers.update(self.custom_http_headers) updated_kwargs = dict(self._adwords_client.report_download_headers) updated_kwargs.update(kwargs) @@ -1062,6 +1072,10 @@ def __init__(self, request_builder, upload_url, current_content_length=0, self._is_last = is_last self._url_opener = urllib2.build_opener( *self._request_builder.client.proxy_config.GetHandlers()) + if self._request_builder.client.custom_http_headers: + self._url_opener.addheaders.extend( + self._request_builder.client.custom_http_headers.items()) + self._upload_url = self._InitializeURL(upload_url, current_content_length) def _InitializeURL(self, upload_url, current_content_length): @@ -1230,10 +1244,14 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], self._namespace = self._NAMESPACE_FORMAT % version self._end_point = self._END_POINT_FORMAT % (server, version) self._header_handler = _AdWordsHeaderHandler( - adwords_client, version, self._adwords_client.enable_compression) + adwords_client, version, self._adwords_client.enable_compression, + self._adwords_client.custom_http_headers) self.proxy_config = self._adwords_client.proxy_config handlers = self.proxy_config.GetHandlers() self.url_opener = urllib2.build_opener(*handlers) + if self._adwords_client.custom_http_headers: + self.url_opener.addheaders.extend( + adwords_client.custom_http_headers.items()) schema_url = self._SCHEMA_FORMAT % (server, version) service_class = (googleads.common diff --git a/googleads/common.py b/googleads/common.py index 3ea06a9b..45edc06b 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '11.0.1' +VERSION = '12.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' @@ -100,6 +100,9 @@ # gzip encoded SOAP responses. ENABLE_COMPRESSION_KEY = 'enable_compression' +# A key used to configure the client to send arbitrary headers in SOAP requests. +CUSTOM_HEADERS_KEY = 'custom_http_headers' + # A key used to specify the SOAP implementation to use. SOAP_IMPLEMENTATION_KEY = 'soap_impl' @@ -220,6 +223,8 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, client_kwargs[ENABLE_COMPRESSION_KEY] = data.get( ENABLE_COMPRESSION_KEY, False) + client_kwargs[CUSTOM_HEADERS_KEY] = data.get(CUSTOM_HEADERS_KEY, None) + if SOAP_IMPLEMENTATION_KEY in data: client_kwargs[SOAP_IMPLEMENTATION_KEY] = data[SOAP_IMPLEMENTATION_KEY] @@ -739,7 +744,15 @@ def __init__(self, endpoint, timeout, the proxy settings needed. namespace_override: A string to doctor the WSDL namespace with. cache: An instance of suds.cache.Cache to use for caching. + + Raises: + GoogleAdsValueError: The wrong type was given for caching. """ + + if cache and not isinstance(cache, suds.cache.Cache): + raise googleads.errors.GoogleAdsValueError( + 'Must use a proper suds cache with suds.') + transport = _SudsProxyTransport(timeout, proxy_config) try: doctor = suds.xsd.doctor.ImportDoctor( @@ -787,7 +800,16 @@ def __init__(self, endpoint, timeout, the proxy settings needed. namespace_override: A string to doctor the WSDL namespace with. cache: An instance of zeep.cache.Base to use for caching. + + Raises: + GoogleAdsValueError: The wrong type was given for caching. """ + + if cache and not (isinstance(cache, zeep.cache.Base) or + cache == ZeepServiceProxy.NO_CACHE): + raise googleads.errors.GoogleAdsValueError( + 'Must use a proper zeep cache with zeep.') + transport = _ZeepProxyTransport(timeout, proxy_config, cache) try: data = transport.load(endpoint) @@ -930,12 +952,13 @@ def __init__(self, endpoint, header_handler, packer, proxy_config, library for caching. Raises: - ValueError: The wrong type was given for caching. + GoogleAdsValueError: The wrong type was given for caching. """ super(SudsServiceProxy, self).__init__(header_handler, packer) if cache and not isinstance(cache, suds.cache.Cache): - raise ValueError('Must use a proper suds cache with suds.') + raise googleads.errors.GoogleAdsValueError( + 'Must use a proper suds cache with suds.') transport = _SudsProxyTransport(timeout, proxy_config) self._method_proxies = {} @@ -1023,7 +1046,7 @@ def MakeSoapRequest(*args): _logger.warning('Response summary - %s', _ExtractResponseSummaryFields(e.document)) - _logger.info('SOAP response:\n%s', e.document.str()) + _logger.debug('SOAP response:\n%s', e.document.str()) if not hasattr(e.fault, 'detail'): exc = (googleads.errors. @@ -1111,13 +1134,14 @@ def __init__(self, endpoint, header_handler, packer, googleads.common.ZeepServiceProxy.NO_CACHE. Raises: - ValueError: The wrong type was given for caching. + GoogleAdsValueError: The wrong type was given for caching. """ super(ZeepServiceProxy, self).__init__(header_handler, packer) if cache and not (isinstance(cache, zeep.cache.Base) or cache == self.NO_CACHE): - raise ValueError('Must use a proper zeep cache with zeep.') + raise googleads.errors.GoogleAdsValueError( + 'Must use a proper zeep cache with zeep.') transport = _ZeepProxyTransport(timeout, proxy_config, cache) plugins = [_ZeepAuthHeaderPlugin(header_handler), diff --git a/googleads/dfp.py b/googleads/dfp.py index 1e414ee7..9d69b44f 100644 --- a/googleads/dfp.py +++ b/googleads/dfp.py @@ -44,7 +44,7 @@ # A giant dictionary of DFP versions and the services they support. _SERVICE_MAP = { - 'v201705': + 'v201708': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CompanyService', 'ContactService', 'ContentBundleService', @@ -66,15 +66,15 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201708': + 'v201711': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentMetadataKeyHierarchyService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', - 'InventoryService', 'LabelService', + 'CdnConfigurationService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentMetadataKeyHierarchyService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', @@ -88,7 +88,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201711': + 'v201802': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', @@ -110,14 +110,15 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201802': + 'v201805': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', 'ContentBundleService', 'ContentMetadataKeyHierarchyService', 'ContentService', 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'ExchangeRateService', 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', @@ -203,6 +204,7 @@ def LoadFromStorage(cls, path=None): def __init__(self, oauth2_client, application_name, network_code=None, cache=None, proxy_config=None, soap_impl='zeep', timeout=3600, + custom_http_headers=None, enable_compression=False): """Initializes a DfpClient. @@ -226,6 +228,8 @@ def __init__(self, oauth2_client, application_name, network_code=None, soap_impl: A string identifying which SOAP implementation to use. The options are 'zeep' or 'suds'. timeout: An integer timeout in MS for connections made to DFP. + custom_http_headers: A dictionary with HTTP headers to add to outgoing + requests. enable_compression: A boolean indicating if you want to enable compression of the SOAP response. If True, the SOAP response will use gzip compression, and will be decompressed for you automatically. @@ -241,7 +245,9 @@ def __init__(self, oauth2_client, application_name, network_code=None, self.application_name = application_name self.network_code = network_code self.cache = cache - self._header_handler = _DfpHeaderHandler(self, enable_compression) + self.custom_http_headers = custom_http_headers + self._header_handler = _DfpHeaderHandler( + self, enable_compression, custom_http_headers) self.proxy_config = (proxy_config if proxy_config else googleads.common.ProxyConfig()) @@ -332,7 +338,7 @@ class _DfpHeaderHandler(googleads.common.HeaderHandler): # The name of the WSDL-defined SOAP Header class used in all requests. _SOAP_HEADER_CLASS = 'ns0:SoapRequestHeader' - def __init__(self, dfp_client, enable_compression): + def __init__(self, dfp_client, enable_compression, custom_http_headers=None): """Initializes a DfpHeaderHandler. Args: @@ -342,9 +348,12 @@ def __init__(self, dfp_client, enable_compression): enable_compression: A boolean indicating if you want to enable compression of the SOAP response. If True, the SOAP response will use gzip compression, and will be decompressed for you automatically. + custom_http_headers: A dictionary of custom HTTP headers to send with all + requests. """ self._dfp_client = dfp_client self.enable_compression = enable_compression + self.custom_http_headers = custom_http_headers or {} def GetSOAPHeaders(self, create_method): """Returns the SOAP headers required for request authorization. @@ -373,6 +382,8 @@ def GetHTTPHeaders(self): if self.enable_compression: http_headers['accept-encoding'] = 'gzip' + http_headers.update(self.custom_http_headers) + return http_headers @@ -732,6 +743,9 @@ def __init__(self, dfp_client, version=sorted(_SERVICE_MAP.keys())[-1], self.proxy_config = self._dfp_client.proxy_config handlers = self.proxy_config.GetHandlers() self.url_opener = urllib2.build_opener(*handlers) + if self._dfp_client.custom_http_headers: + self.url_opener.addheaders.extend( + self._dfp_client.custom_http_headers.items()) def _GetReportService(self): """Lazily initializes a report service client.""" diff --git a/tests/adwords_test.py b/tests/adwords_test.py index c9d6ca3b..72e764f1 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -42,6 +42,7 @@ CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] TEST_DIR = os.path.dirname(__file__) +URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' def GetAdWordsClient(soap_impl, **kwargs): @@ -141,7 +142,7 @@ def setUp(self): validate_only=self.validate_only, partial_failure=self.partial_failure, report_downloader_headers=self.report_downloader_headers) self.header_handler = googleads.adwords._AdWordsHeaderHandler( - self.aw_client, CURRENT_VERSION, self.enable_compression) + self.aw_client, CURRENT_VERSION, self.enable_compression, None) @googleads.common.RegisterUtility(self.utility_name) class TestUtility(object): @@ -156,6 +157,14 @@ def testGetHTTPHeaders(self): # Check that the returned headers have the correct values. self.assertEqual(header_result, self.oauth_header) + def testGetHTTPHeadersWithCustomHeaders(self): + self.header_handler.custom_http_headers = {'X-My-Header': 'abc'} + + header_result = self.header_handler.GetHTTPHeaders() + + self.assertEqual( + header_result, {'Authorization': 'header', 'X-My-Header': 'abc'}) + def testGetSOAPHeaders(self): create_method = mock.Mock() soap_header = self.header_handler.GetSOAPHeaders(create_method) @@ -344,7 +353,7 @@ def setUp(self): self.adwords_client = GetAdWordsClient('zeep') self.aw_client = GetAdWordsClient('zeep', proxy_config=self.proxy_config) self.header_handler = googleads.adwords._AdWordsHeaderHandler( - self.adwords_client, CURRENT_VERSION, False) + self.adwords_client, CURRENT_VERSION, False, None) def testLoadFromStorage(self): @@ -413,7 +422,7 @@ def testGetService_success(self): service = client.GetService(service_name, CURRENT_VERSION, server) mock_header_handler.assert_called_once_with( - client, CURRENT_VERSION, True) + client, CURRENT_VERSION, True, None) impl.assert_called_once_with( 'https://testing.test.com/api/adwords/%s/%s/%s?wsdl' % ( namespace, CURRENT_VERSION, service_name), @@ -1312,6 +1321,11 @@ class IncrementalUploadHelperTest(testing.CleanUtilityRegistryTestCase): """Test suite for the IncrementalUploadHelper.""" + def GetIncrementalUploadHelper(self): + with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: + mock_open.return_value.headers = {'location': self.initialized_url} + return self.batch_job_helper.GetIncrementalUploadHelper(self.original_url) + def setUp(self): """Prepare tests.""" self.client = GetAdWordsClient('zeep') @@ -1321,14 +1335,7 @@ def setUp(self): version=self.version, server=self.server) self.original_url = 'https://goo.gl/w8tkpK' self.initialized_url = 'https://goo.gl/Xtaq83' - - with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: - mock_open.return_value.headers = { - 'location': self.initialized_url - } - self.incremental_uploader = ( - self.batch_job_helper.GetIncrementalUploadHelper( - self.original_url)) + self.incremental_uploader = self.GetIncrementalUploadHelper() self.incremental_uploader_dump = ( '{current_content_length: 0, is_last: false, ' @@ -1413,6 +1420,20 @@ def testUploadOperationsAfterFinished(self): googleads.errors.AdWordsBatchJobServiceInvalidOperationError, self.incremental_uploader.UploadOperations, {}) + def testRequestHasCustomHeaders(self): + class MyOpener(object): + addheaders = [('a', 'b')] + opener = MyOpener() + + with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mock_build_opener,\ + mock.patch('googleads.adwords.IncrementalUploadHelper._InitializeURL'): + mock_build_opener.return_value = opener + self.client.custom_http_headers = {'X-My-Headers': 'abc'} + + self.GetIncrementalUploadHelper() + + self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Headers', 'abc')]) + class ResponseParserTest(testing.CleanUtilityRegistryTestCase): """Test suite for the ResponseParser.""" @@ -1516,6 +1537,8 @@ def setUp(self): self.adwords_client = mock.Mock() self.adwords_client.proxy_config = GetProxyConfig() self.adwords_client.soap_impl = 'zeep' + self.adwords_client.cache = googleads.common.ZeepServiceProxy.NO_CACHE + self.adwords_client.custom_http_headers = False self.header_handler = mock.Mock() # It's unfortunate that the target output is different between suds and @@ -1606,6 +1629,7 @@ def setUp(self): self.adwords_client = mock.Mock() self.adwords_client.proxy_config = GetProxyConfig() self.adwords_client.cache = suds.cache.NoCache() + self.adwords_client.custom_http_headers = False self.opener = mock.Mock() post_body_path = os.path.join(TEST_DIR, @@ -1736,6 +1760,17 @@ def testDownloadReportWithBytesIO(self, mock_request): class ReportDownloaderTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.adwords.ReportDownloader class.""" + def GetReportDownloader(self): + with mock.patch( + 'googleads.adwords._AdWordsHeaderHandler') as mock_handler, \ + mock.patch('googleads.adwords.googleads.common' + '.GetSchemaHelperForLibrary') as mock_get_schema: + mock_handler.return_value = self.header_handler + mock_get_schema.return_value = mock.Mock() + + return googleads.adwords.ReportDownloader( + self.adwords_client, self.version) + def setUp(self): self.version = CURRENT_VERSION self.marshaller = mock.Mock() @@ -1743,20 +1778,24 @@ def setUp(self): self.adwords_client = mock.Mock() self.adwords_client.proxy_config = GetProxyConfig() self.adwords_client.cache = suds.cache.NoCache() + self.adwords_client.custom_http_headers = False self.opener = mock.Mock() - with mock.patch( - 'googleads.adwords._AdWordsHeaderHandler') as mock_handler, \ - mock.patch('googleads.adwords.googleads.common' - '.GetSchemaHelperForLibrary') as mock_get_schema: - mock_handler.return_value = self.header_handler - mock_get_schema.return_value = mock.Mock() + self.report_downloader = self.GetReportDownloader() + self.report_downloader.url_opener = self.opener + + def testSetsCustomHeaders(self): + + class MyOpener(object): + addheaders = [('a', 'b')] + opener = MyOpener() + self.adwords_client.custom_http_headers = {'X-My-Header': 'abc'} - self.report_downloader = googleads.adwords.ReportDownloader( - self.adwords_client, self.version - ) + with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mock_build_opener: + mock_build_opener.return_value = opener + self.GetReportDownloader() - self.report_downloader.url_opener = self.opener + self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Header', 'abc')]) @mock.patch.object(urllib2.OpenerDirector, 'open') def testDownloadReportAsString(self, mock_request): diff --git a/tests/common_test.py b/tests/common_test.py index a99e8852..ef5d276b 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -156,7 +156,8 @@ def testLoadFromStorage(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) self.assertTrue(googleads.common._utility_registry._enabled) @@ -165,7 +166,8 @@ def testLoadFromStorage(self): yaml_fname = self._CreateYamlFile( {'one': {'needed': 'd', 'keys': 'e', 'other': 'f'}, googleads.common._LOGGING_KEY: logging_config, - googleads.common.SOAP_IMPLEMENTATION_KEY: 'suds'}, + googleads.common.SOAP_IMPLEMENTATION_KEY: 'suds', + googleads.common.CUSTOM_HEADERS_KEY: {'X-My-Header': 'abc'}}, 'one', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): @@ -184,7 +186,9 @@ def testLoadFromStorage(self): 'needed': 'd', 'keys': 'e', 'other': 'f', 'proxy_config': proxy_config.return_value, googleads.common.ENABLE_COMPRESSION_KEY: False, - googleads.common.SOAP_IMPLEMENTATION_KEY: 'suds'}, + googleads.common.SOAP_IMPLEMENTATION_KEY: 'suds', + googleads.common.CUSTOM_HEADERS_KEY: { + 'X-My-Header': 'abc'}}, rval) self.assertTrue(googleads.common._utility_registry._enabled) @@ -212,7 +216,8 @@ def testLoadFromStorage_relativePath(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, 'needed': 'd', 'keys': 'e', - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) self.assertTrue(googleads.common._utility_registry._enabled) def _CreateYamlDoc(self, data, insert_oauth2_key=None, oauth_dict=None): @@ -459,7 +464,8 @@ def testLoadFromString_passesWithNoRequiredKeys(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): yaml_doc = self._CreateYamlDoc( @@ -482,7 +488,8 @@ def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) def testHTTPSProxyExtendsSSLSockTimeout(self): proxy_config = mock.MagicMock() @@ -510,7 +517,8 @@ def testLoadFromString_passesWithHTTPProxy(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) def testLoadFromString_passesWithHTTPProxyLogin(self): yaml_doc = self._CreateYamlDoc( @@ -531,7 +539,8 @@ def testLoadFromString_passesWithHTTPProxyLogin(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) def testLoadFromString_passesWithHTTPSProxy(self): yaml_doc = self._CreateYamlDoc( @@ -553,7 +562,8 @@ def testLoadFromString_passesWithHTTPSProxy(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) def testLoadFromString_passesWithHTTPSProxyLogin(self): yaml_doc = self._CreateYamlDoc( @@ -575,7 +585,8 @@ def testLoadFromString_passesWithHTTPSProxyLogin(self): 'a', 'b', 'c', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) def testLoadFromString_missingRequiredKeys(self): with mock.patch('googleads.common.open', self.fake_open, create=True): @@ -619,7 +630,8 @@ def testLoadFromString(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) self.assertTrue(googleads.common._utility_registry._enabled) @@ -641,7 +653,8 @@ def testLoadFromString(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'other': 'f', 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) self.assertTrue(googleads.common._utility_registry._enabled) @@ -668,7 +681,8 @@ def testLoadFromString_serviceAccount(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, 'needed': 'd', 'keys': 'e', - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) self.assertTrue(googleads.common._utility_registry._enabled) # The optional key is present. @@ -692,7 +706,8 @@ def testLoadFromString_serviceAccount(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, 'needed': 'd', 'keys': 'e', 'other': 'f', - googleads.common.ENABLE_COMPRESSION_KEY: False}, rval) + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) self.assertTrue(googleads.common._utility_registry._enabled) @@ -716,7 +731,8 @@ def testLoadFromString_utilityRegistryDisabled(self): self.assertEqual({'oauth2_client': mock_client.return_value, 'needed': 'd', 'keys': 'e', 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False}, + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None}, rval) self.assertFalse(googleads.common._utility_registry._enabled) @@ -739,7 +755,8 @@ def testLoadFromString_warningWithUnrecognizedKey(self): 'oauth2_client': mock_client.return_value, 'Im': 'here', 'proxy_config': proxy_config.return_value, - googleads.common.ENABLE_COMPRESSION_KEY: False + googleads.common.ENABLE_COMPRESSION_KEY: False, + googleads.common.CUSTOM_HEADERS_KEY: None }, rval) self.assertTrue(googleads.common._utility_registry._enabled) self.assertEqual(len(captured_warnings), 1) @@ -1016,11 +1033,16 @@ def testBadCacheType(self): header_handler = mock.Mock() packer = mock.Mock() - with mock_zeep_client(), self.assertRaises(ValueError): + with mock_zeep_client(), \ + self.assertRaises(googleads.errors.GoogleAdsValueError): googleads.common.ZeepServiceProxy( 'http://abc', header_handler, packer, self.empty_proxy_config, self.timeout_100, cache='not_a_zeep_cache') + def testSchemaHelperBadCacheType(self): + with self.assertRaises(googleads.errors.GoogleAdsValueError): + googleads.common.ZeepSchemaHelper(None, None, None, None, 'not_zeep') + def testAllowsNoCache(self): header_handler = mock.Mock() packer = mock.Mock() @@ -1346,10 +1368,15 @@ def testSetHeaders(self): soapheaders='soap', headers='http') def testBadCache(self): - with self.mock_suds_api(), self.assertRaises(ValueError): + with self.mock_suds_api(), \ + self.assertRaises(googleads.errors.GoogleAdsValueError): googleads.common.SudsServiceProxy( 'https://endpoint', None, None, None, 1000, 'not_a_suds_cache') + def testSchemaHelperBadCache(self): + with self.assertRaises(googleads.errors.GoogleAdsValueError): + googleads.common.SudsSchemaHelper(None, None, None, None, 'not_cache') + class LoggingMessagePluginTest(unittest.TestCase): """Tests for the googleads.common.LoggingMessagePlugin class.""" diff --git a/tests/dfp_test.py b/tests/dfp_test.py index f80153b6..c987e152 100644 --- a/tests/dfp_test.py +++ b/tests/dfp_test.py @@ -28,6 +28,9 @@ from . import testing +URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' + + class BaseValue(object): def __init__(self, original_object): @@ -110,8 +113,9 @@ class DfpHeaderHandlerTest(testing.CleanUtilityRegistryTestCase): def setUp(self): self.dfp_client = mock.Mock() self.enable_compression = False + self.custom_headers = () self.header_handler = googleads.dfp._DfpHeaderHandler( - self.dfp_client, self.enable_compression) + self.dfp_client, self.enable_compression, self.custom_headers) self.utility_name = 'TestUtility' self.default_sig_template = ' (%s, %s, %s)' self.util_sig_template = ' (%s, %s, %s, %s)' @@ -136,6 +140,16 @@ def testGetHTTPHeaders(self): # Check that the returned headers have the correct values. self.assertEqual(header_result, self.oauth_header) + def testGetHTTPHeadersWithCustomHeaders(self): + self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( + self.oauth_header) + self.header_handler.custom_http_headers = {'X-My-Header': 'abc'} + + header_result = self.header_handler.GetHTTPHeaders() + + # Check that the returned headers have the correct values. + self.assertEqual(header_result, {'oauth': 'header', 'X-My-Header': 'abc'}) + def testGetSOAPHeaders(self): create_method = mock.Mock() self.dfp_client.network_code = self.network_code @@ -266,6 +280,7 @@ def testLoadFromStorageWithCompressionEnabled(self): enable_compression = True application_name_gzip_template = '%s (gzip)' default_app_name = 'unit testing' + custom_headers = {'X-My-Header': 'abc'} with mock.patch('googleads.common.LoadFromStorage') as mock_load: with mock.patch('googleads.dfp._DfpHeaderHandler') as mock_h: @@ -273,13 +288,15 @@ def testLoadFromStorageWithCompressionEnabled(self): 'network_code': 'abcdEFghIjkLMOpqRs', 'oauth2_client': True, 'application_name': default_app_name, - 'enable_compression': enable_compression + 'enable_compression': enable_compression, + 'custom_http_headers': custom_headers } dfp_client = googleads.dfp.DfpClient.LoadFromStorage() self.assertEqual( application_name_gzip_template % default_app_name, dfp_client.application_name) - mock_h.assert_called_once_with(dfp_client, enable_compression) + mock_h.assert_called_once_with( + dfp_client, enable_compression, custom_headers) @@ -390,10 +407,10 @@ def setUp(self): application_name = 'application name' oauth2_client = 'unused' self.https_proxy = 'myproxy.com:443' - dfp_client = googleads.dfp.DfpClient( + self.dfp_client = googleads.dfp.DfpClient( oauth2_client, application_name, network_code, self.https_proxy) self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1] - self.report_downloader = dfp_client.GetDataDownloader() + self.report_downloader = self.dfp_client.GetDataDownloader() self.pql_service = mock.Mock() self.report_service = mock.Mock() self.report_downloader._pql_service = self.pql_service @@ -689,6 +706,19 @@ def testGetPqlService(self): self.report_downloader._dfp_client.GetService.assert_called_once_with( 'PublisherQueryLanguageService', self.version, 'https://ads.google.com') + def testDownloadHasCustomHeaders(self): + self.dfp_client.custom_http_headers = {'X-My-Headers': 'abc'} + + class MyOpener(object): + addheaders = [('a', 'b')] + opener = MyOpener() + + with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mock_build_opener: + mock_build_opener.return_value = opener + + self.dfp_client.GetDataDownloader() + self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Headers', 'abc')]) + class StatementBuilderTest(testing.CleanUtilityRegistryTestCase): """Tests for the StatementBuilder class.""" From 859d8eee0151f18cf712ab75284ef10017006059 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 15 May 2018 14:54:07 -0400 Subject: [PATCH 109/180] Commiting latest changes. From 5588527aa94e2927359218efdf2542958bae3364 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Thu, 7 Jun 2018 11:21:47 -0400 Subject: [PATCH 110/180] Committing latest changes. --- ChangeLog | 6 + .../remarketing/add_conversion_tracker.py | 8 +- .../remarketing/add_conversion_tracker.py | 8 +- examples/adwords/v201806/__init__.py | 15 + .../v201806/account_management/__init__.py | 15 + .../account_management/accept_service_link.py | 62 +++ .../account_management/create_account.py | 69 +++ .../account_management/get_account_changes.py | 99 ++++ .../get_account_hierarchy.py | 104 ++++ .../v201806/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 257 +++++++++ .../add_ad_group_bid_modifier.py | 75 +++ .../add_click_to_download_ad.py | 125 +++++ .../add_dynamic_page_feed.py | 295 ++++++++++ .../add_dynamic_search_ads_campaign.py | 257 +++++++++ ...add_expanded_text_ad_with_upgraded_urls.py | 113 ++++ .../advanced_operations/add_gmail_ad.py | 115 ++++ .../advanced_operations/add_html5_ad.py | 110 ++++ .../add_multi_asset_responsive_display_ad.py | 177 ++++++ .../add_responsive_display_ad.py | 158 ++++++ ...d_shopping_dynamic_remarketing_campaign.py | 301 ++++++++++ .../add_universal_app_campaign.py | 218 ++++++++ .../create_and_attach_shared_keyword_set.py | 128 +++++ ...ind_and_remove_criteria_from_shared_set.py | 155 ++++++ .../get_ad_group_bid_modifier.py | 73 +++ .../use_shared_bidding_strategy.py | 171 ++++++ .../v201806/basic_operations/__init__.py | 15 + .../v201806/basic_operations/add_ad_groups.py | 115 ++++ .../v201806/basic_operations/add_campaigns.py | 127 +++++ .../basic_operations/add_expanded_text_ads.py | 74 +++ .../v201806/basic_operations/add_keywords.py | 92 +++ .../add_responsive_search_ad.py | 112 ++++ .../v201806/basic_operations/get_ad_groups.py | 76 +++ .../v201806/basic_operations/get_campaigns.py | 68 +++ .../get_campaigns_with_awql.py | 61 ++ .../basic_operations/get_expanded_text_ads.py | 90 +++ .../v201806/basic_operations/get_keywords.py | 87 +++ .../get_responsive_search_ads.py | 100 ++++ .../v201806/basic_operations/pause_ad.py | 61 ++ .../v201806/basic_operations/remove_ad.py | 62 +++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 +++ .../basic_operations/update_ad_group.py | 85 +++ .../basic_operations/update_campaign.py | 58 ++ .../update_expanded_text_ad.py | 74 +++ .../basic_operations/update_keyword.py | 82 +++ .../v201806/campaign_management/__init__.py | 15 + ...campaign_groups_and_performance_targets.py | 152 +++++ .../add_campaign_labels.py | 67 +++ .../add_complete_campaigns_using_batch_job.py | 428 ++++++++++++++ .../v201806/campaign_management/add_draft.py | 81 +++ ...dd_keywords_using_incremental_batch_job.py | 257 +++++++++ .../v201806/campaign_management/add_trial.py | 116 ++++ .../get_all_disapproved_ads.py | 103 ++++ .../get_all_disapproved_ads_with_awql.py | 88 +++ .../get_campaigns_by_label.py | 83 +++ .../campaign_management/graduate_trial.py | 79 +++ .../campaign_management/set_ad_parameters.py | 100 ++++ .../set_criterion_bid_modifier.py | 77 +++ .../campaign_management/validate_text_ad.py | 84 +++ .../v201806/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 131 +++++ .../handle_policy_violation_error.py | 166 ++++++ .../adwords/v201806/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 156 ++++++ .../adwords/v201806/extensions/add_prices.py | 157 ++++++ .../v201806/extensions/add_site_links.py | 146 +++++ .../extensions/add_site_links_using_feeds.py | 303 ++++++++++ .../adwords/v201806/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 526 ++++++++++++++++++ examples/adwords/v201806/misc/__init__.py | 15 + .../v201806/misc/get_all_image_assets.py | 78 +++ .../v201806/misc/get_all_images_and_videos.py | 85 +++ examples/adwords/v201806/misc/upload_image.py | 65 +++ .../v201806/misc/upload_image_asset.py | 71 +++ .../v201806/misc/upload_media_bundle.py | 58 ++ .../adwords/v201806/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 182 ++++++ ...aign_criterion_bid_modifier_simulations.py | 97 ++++ .../get_keyword_bid_simulations.py | 104 ++++ .../v201806/optimization/get_keyword_ideas.py | 113 ++++ .../adwords/v201806/remarketing/__init__.py | 15 + .../v201806/remarketing/add_audience.py | 104 ++++ .../remarketing/add_conversion_tracker.py | 66 +++ .../remarketing/add_conversion_trackers.py | 101 ++++ .../remarketing/add_crm_based_user_list.py | 104 ++++ .../remarketing/add_rule_based_user_lists.py | 235 ++++++++ .../upload_conversion_adjustments.py | 73 +++ .../upload_offline_call_conversions.py | 77 +++ .../remarketing/upload_offline_conversions.py | 82 +++ .../remarketing/upload_offline_data.py | 259 +++++++++ .../adwords/v201806/reporting/__init__.py | 15 + ...oad_criteria_report_as_stream_with_awql.py | 79 +++ ...criteria_report_as_stream_with_selector.py | 72 +++ ...oad_criteria_report_as_string_with_awql.py | 58 ++ ...criteria_report_as_string_with_selector.py | 55 ++ .../download_criteria_report_with_awql.py | 58 ++ .../download_criteria_report_with_selector.py | 56 ++ .../v201806/reporting/get_report_fields.py | 52 ++ .../reporting/parallel_report_download.py | 244 ++++++++ examples/adwords/v201806/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 279 ++++++++++ .../v201806/shopping/add_product_scope.py | 104 ++++ .../v201806/shopping/add_shopping_campaign.py | 172 ++++++ .../add_shopping_campaign_for_showcase_ads.py | 401 +++++++++++++ .../shopping/get_product_category_taxonomy.py | 96 ++++ .../adwords/v201806/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 126 +++++ .../add_customer_negative_criteria.py | 74 +++ .../add_demographic_targeting_criteria.py | 96 ++++ .../get_campaign_targeting_criteria.py | 85 +++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201806/targeting/lookup_location.py | 82 +++ googleads/adwords.py | 58 +- googleads/common.py | 111 ++-- tests/common_test.py | 20 + 117 files changed, 12545 insertions(+), 45 deletions(-) create mode 100644 examples/adwords/v201806/__init__.py create mode 100644 examples/adwords/v201806/account_management/__init__.py create mode 100755 examples/adwords/v201806/account_management/accept_service_link.py create mode 100755 examples/adwords/v201806/account_management/create_account.py create mode 100755 examples/adwords/v201806/account_management/get_account_changes.py create mode 100755 examples/adwords/v201806/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201806/advanced_operations/__init__.py create mode 100755 examples/adwords/v201806/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201806/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201806/advanced_operations/add_click_to_download_ad.py create mode 100755 examples/adwords/v201806/advanced_operations/add_dynamic_page_feed.py create mode 100755 examples/adwords/v201806/advanced_operations/add_dynamic_search_ads_campaign.py create mode 100755 examples/adwords/v201806/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201806/advanced_operations/add_gmail_ad.py create mode 100755 examples/adwords/v201806/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201806/advanced_operations/add_multi_asset_responsive_display_ad.py create mode 100755 examples/adwords/v201806/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201806/advanced_operations/add_shopping_dynamic_remarketing_campaign.py create mode 100755 examples/adwords/v201806/advanced_operations/add_universal_app_campaign.py create mode 100755 examples/adwords/v201806/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201806/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201806/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201806/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201806/basic_operations/__init__.py create mode 100755 examples/adwords/v201806/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201806/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201806/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201806/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201806/basic_operations/add_responsive_search_ad.py create mode 100755 examples/adwords/v201806/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201806/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201806/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201806/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201806/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201806/basic_operations/get_responsive_search_ads.py create mode 100755 examples/adwords/v201806/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201806/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201806/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201806/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201806/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201806/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201806/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201806/basic_operations/update_expanded_text_ad.py create mode 100755 examples/adwords/v201806/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201806/campaign_management/__init__.py create mode 100755 examples/adwords/v201806/campaign_management/add_campaign_groups_and_performance_targets.py create mode 100755 examples/adwords/v201806/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201806/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201806/campaign_management/add_draft.py create mode 100755 examples/adwords/v201806/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201806/campaign_management/add_trial.py create mode 100755 examples/adwords/v201806/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201806/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201806/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201806/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201806/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201806/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201806/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201806/error_handling/__init__.py create mode 100755 examples/adwords/v201806/error_handling/handle_partial_failures.py create mode 100755 examples/adwords/v201806/error_handling/handle_policy_violation_error.py create mode 100644 examples/adwords/v201806/extensions/__init__.py create mode 100755 examples/adwords/v201806/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201806/extensions/add_prices.py create mode 100755 examples/adwords/v201806/extensions/add_site_links.py create mode 100755 examples/adwords/v201806/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201806/migration/__init__.py create mode 100755 examples/adwords/v201806/migration/migrate_to_extension_settings.py create mode 100644 examples/adwords/v201806/misc/__init__.py create mode 100755 examples/adwords/v201806/misc/get_all_image_assets.py create mode 100755 examples/adwords/v201806/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201806/misc/upload_image.py create mode 100755 examples/adwords/v201806/misc/upload_image_asset.py create mode 100755 examples/adwords/v201806/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201806/optimization/__init__.py create mode 100755 examples/adwords/v201806/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201806/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201806/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201806/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201806/remarketing/__init__.py create mode 100755 examples/adwords/v201806/remarketing/add_audience.py create mode 100755 examples/adwords/v201806/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201806/remarketing/add_conversion_trackers.py create mode 100755 examples/adwords/v201806/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201806/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201806/remarketing/upload_conversion_adjustments.py create mode 100755 examples/adwords/v201806/remarketing/upload_offline_call_conversions.py create mode 100755 examples/adwords/v201806/remarketing/upload_offline_conversions.py create mode 100755 examples/adwords/v201806/remarketing/upload_offline_data.py create mode 100644 examples/adwords/v201806/reporting/__init__.py create mode 100755 examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_selector.py create mode 100755 examples/adwords/v201806/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201806/reporting/download_criteria_report_as_string_with_selector.py create mode 100755 examples/adwords/v201806/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201806/reporting/download_criteria_report_with_selector.py create mode 100755 examples/adwords/v201806/reporting/get_report_fields.py create mode 100755 examples/adwords/v201806/reporting/parallel_report_download.py create mode 100644 examples/adwords/v201806/shopping/__init__.py create mode 100755 examples/adwords/v201806/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201806/shopping/add_product_scope.py create mode 100755 examples/adwords/v201806/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201806/shopping/add_shopping_campaign_for_showcase_ads.py create mode 100755 examples/adwords/v201806/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201806/targeting/__init__.py create mode 100755 examples/adwords/v201806/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201806/targeting/add_customer_negative_criteria.py create mode 100755 examples/adwords/v201806/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201806/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201806/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201806/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 1564409f..bb3fd7da 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +12.1.0 -- 06/06/18 +* Added support and examples for AdWords v201806. +* Resolved issues: +- Issue 282: https://github.com/googleads/googleads-python-lib/issues/282 +- Issue 288: https://github.com/googleads/googleads-python-lib/issues/288 + 12.0.0 -- 05/15/18 * Added support and examples for DFP v201805. * Removed support for DFP v201705. diff --git a/examples/adwords/v201710/remarketing/add_conversion_tracker.py b/examples/adwords/v201710/remarketing/add_conversion_tracker.py index 0b059389..389d75d9 100755 --- a/examples/adwords/v201710/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201710/remarketing/add_conversion_tracker.py @@ -41,12 +41,9 @@ def main(client): 'xsi_type': 'AdWordsConversionTracker', 'name': 'Mars cruise customers #%s' % uuid.uuid4(), 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', # Optional fields. 'status': 'ENABLED', 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', 'defaultRevenueValue': '23.41', 'alwaysUseDefaultRevenueValue': 'true' } @@ -57,10 +54,9 @@ def main(client): # Display results. for conversion_tracker in conversion_trackers['value']: print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" and snippet \n"%s"\n was added.\n' % + 'and category "%s" \n was added.\n' % (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) + conversion_tracker['status'], conversion_tracker['category'])) if __name__ == '__main__': diff --git a/examples/adwords/v201802/remarketing/add_conversion_tracker.py b/examples/adwords/v201802/remarketing/add_conversion_tracker.py index fedea7a0..a15199c6 100755 --- a/examples/adwords/v201802/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201802/remarketing/add_conversion_tracker.py @@ -41,12 +41,9 @@ def main(client): 'xsi_type': 'AdWordsConversionTracker', 'name': 'Mars cruise customers #%s' % uuid.uuid4(), 'category': 'DEFAULT', - 'textFormat': 'HIDDEN', # Optional fields. 'status': 'ENABLED', 'viewthroughLookbackWindow': '15', - 'conversionPageLanguage': 'en', - 'backgroundColor': '#0000FF', 'defaultRevenueValue': '23.41', 'alwaysUseDefaultRevenueValue': 'true' } @@ -57,10 +54,9 @@ def main(client): # Display results. for conversion_tracker in conversion_trackers['value']: print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" and snippet \n"%s"\n was added.\n' % + 'and category "%s"\n was added.\n' % (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) + conversion_tracker['status'], conversion_tracker['category'])) if __name__ == '__main__': diff --git a/examples/adwords/v201806/__init__.py b/examples/adwords/v201806/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201806/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201806/account_management/__init__.py b/examples/adwords/v201806/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201806/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201806/account_management/accept_service_link.py b/examples/adwords/v201806/account_management/accept_service_link.py new file mode 100755 index 00000000..9e227b10 --- /dev/null +++ b/examples/adwords/v201806/account_management/accept_service_link.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' + + +def main(client, service_link_id): + # Initialize appropriate service. + customer_service = client.GetService( + 'CustomerService', version='v201806') + + # Create the operation to set the status to ACTIVE. + operations = [{ + 'operator': 'SET', + 'operand': { + 'serviceLinkId': service_link_id, + 'serviceType': 'MERCHANT_CENTER', + 'linkStatus': 'ACTIVE', + } + }] + + # Update the service link. + mutated_service_links = customer_service.mutateServiceLinks(operations) + + # Display results. + for mutated_service_link in mutated_service_links: + print ('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201806/account_management/create_account.py b/examples/adwords/v201806/account_management/create_account.py new file mode 100755 index 00000000..1fe81d49 --- /dev/null +++ b/examples/adwords/v201806/account_management/create_account.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201806') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + }, + # For whitelisted users only, uncomment the inviteeEmail and inviteeRole + # attributes to invite a user to have access to an account on an ADD. An + # email will be sent inviting the user to have access to the newly created + # account. + # 'inviteeEmail': 'invited_user1@example.com', + # 'inviteeRole': 'ADMINISTRATIVE' + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID "%s" was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/account_management/get_account_changes.py b/examples/adwords/v201806/account_management/get_account_changes.py new file mode 100755 index 00000000..645ecfa1 --- /dev/null +++ b/examples/adwords/v201806/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201806') + campaign_service = client.GetService('CampaignService', version='v201806') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id "%s" has change status "%s".' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id "%s" has change status "%s".' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/account_management/get_account_hierarchy.py b/examples/adwords/v201806/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..01a10e01 --- /dev/null +++ b/examples/adwords/v201806/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201806') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/advanced_operations/__init__.py b/examples/adwords/v201806/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201806/advanced_operations/add_ad_customizer.py b/examples/adwords/v201806/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..a983f15c --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_ad_customizer.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates ExpandedTextAds that use ad customizations for specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no ExpandedTextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201806') + + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'headlinePart2': 'Only {=%s.Price}' % feed_name, + 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': expanded_text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID "%s", type "%s", and status "%s".' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201806') + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name "%s" and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id): + """Restricts the feed item to an ad group. + + Args: + client: an AdWordsClient instance. + feed_item: The feed item. + adgroup_id: The ad group ID. + """ + # Get the FeedItemTargetService + feed_item_target_service = client.GetService( + 'FeedItemTargetService', 'v201806') + + # Optional: Restrict the first feed item to only serve with ads for the + # specified ad group ID. + ad_group_target = { + 'xsi_type': 'FeedItemAdGroupTarget', + 'feedId': feed_item['feedId'], + 'feedItemId': feed_item['feedItemId'], + 'adGroupId': adgroup_id + } + + operation = {'operator': 'ADD', 'operand': ad_group_target} + + response = feed_item_target_service.mutate([operation]) + new_ad_group_target = response['value'][0] + + print('Feed item target for feed ID %s and feed item ID %s was created to ' + 'restrict serving to ad group ID %s' % + (new_ad_group_target['feedId'], + new_ad_group_target['feedItemId'], + new_ad_group_target['adGroupId'])) + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService', 'v201806') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + for feed_item, adgroup_id in zip(response['value'], adgroup_ids): + RestrictFeedItemToAdGroup(client, feed_item, adgroup_id) + + +def CreateFeedItemAddOperation(name, price, date, ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + operation = { + 'operator': 'ADD', + 'operand': feed_item + } + + return operation + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201806/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201806/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..3c65fbdf --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201806') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201806/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201806/advanced_operations/add_click_to_download_ad.py new file mode 100755 index 00000000..8cf8c366 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_click_to_download_ad.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. + +This type of ad is also known as an app promotion ad. To list ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Optionally, you may specify a landscape image. + # Here we download a demo image. + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = opener.open('http://goo.gl/9JmyKk').read().decode('utf-8') + + # Create the template elements for the ad. You can refer to + # https://developers.google.com/adwords/api/docs/appendix/templateads + # for the list of available template fields. + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'headline', + 'fieldText': 'Enjoy your drive in Mars', + 'type': 'TEXT' + }, + { + 'name': 'description1', + 'fieldText': 'Realistic physics simulation', + 'type': 'TEXT' + }, + { + 'name': 'description2', + 'fieldText': 'Race against players online', + 'type': 'TEXT' + }, + { + 'name': 'appId', + 'fieldText': 'com.example.demogame', + 'type': 'TEXT' + }, + { + 'name': 'appStore', + 'fieldText': '2', + 'type': 'ENUM' + }, + { + 'name': 'landscapeImage', + 'fieldMedia': { + 'xsi_type': 'Image', + 'data': image_data + }, + 'type': 'IMAGE' + } + ] + } + + # Create click to download ad. + click_to_download_app_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for demo game', + 'templateId': '353', + 'finalUrls': [ + 'http://play.google.com/store/apps/details?id=com.example.demogame' + ], + 'displayUrl': 'play.google.com', + 'templateElements': [ad_data] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': click_to_download_app_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new click-to-download ad with ID "%s" and final URL "%s".' + % (ad['ad']['id'], ad['ad']['finalUrls'][0])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201806/advanced_operations/add_dynamic_page_feed.py new file mode 100755 index 00000000..cdb2b89b --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_dynamic_page_feed.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. + +To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +from collections import namedtuple +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + +# Used to keep track of DSA page feed details. +_DSAFeedDetails = namedtuple( + '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) +# ID that corresponds to the labels. +DSA_LABEL_FIELD_ID = 2 +# The criterion type to be used for DSA page feeds. +DSA_PAGE_FEED_CRITERION_TYPE = 61 +DSA_PAGE_URL_LABEL = 'discounts' +# ID that corresponds to the page URLs. +DSA_PAGE_URLS_FIELD_ID = 1 + + +def main(client, campaign_id, ad_group_id): + # Get the page feed details. This code example creates a new feed, but you can + # fetch and re-use an existing feed. + feed_details = _CreateFeed(client) + _CreateFeedMapping(client, feed_details) + _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) + + # Associate the page feed with the campaign. + _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) + + # Optional: Target web pages matching the feed's label in the ad group. + _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) + + print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + + +def _CreateFeed(client): + """Creates the feed for DSA page URLs. + + Args: + client: an AdWordsClient instance. + + Returns: + A _DSAFeedDetails instance containing details about the created feed. + """ + # Get the FeedService. + feed_service = client.GetService('FeedService', version='v201806') + + # Create operation. + operation = { + # Create the feed. + 'operand': { + 'name': 'DSA Feed %s' % uuid.uuid4(), + # Create attributes. + 'attributes': [ + {'type': 'URL_LIST', 'name': 'Page URL'}, + {'type': 'STRING_LIST', 'name': 'Label'} + ], + 'origin': 'USER' + }, + 'operator': 'ADD' + } + + # Add the feed. + feed = feed_service.mutate([operation])['value'][0] + return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], + feed['attributes'][1]['id']) + + +def _CreateFeedMapping(client, feed_details): + """Creates the feed mapping for DSA page feeds. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + """ + # Get the FeedMappingService. + feed_mapping_service = client.GetService('FeedMappingService', + version='v201806') + + # Create the operation. + operation = { + # Create the feed mapping. + 'operand': { + 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, + 'feedId': feed_details.feed_id, + # Map the feedAttributeIds to the fieldId constants. + 'attributeFieldMappings': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'fieldId': DSA_PAGE_URLS_FIELD_ID + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'fieldId': DSA_LABEL_FIELD_ID + } + ] + }, + 'operator': 'ADD' + } + + # Add the feed mapping. + feed_mapping_service.mutate([operation]) + + +def _CreateFeedItems(client, feed_details, label_name): + """Creates the page URLs in the DSA page feed. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + label_name: a str containing the page feed URL label. + """ + # Get the FeedItemService. + feed_item_service = client.GetService('FeedItemService', version='v201806') + + # For page feed URL recommendations and rules, see: + # https://support.google.com/adwords/answer/7166527 + urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', + 'http://www.example.com/discounts/hotel-deals?id={feeditem}', + 'http://www.example.com/discounts/flight-deals?id={feeditem}') + + # Create the operation. + operations = [{ + # Create the feed item. + 'operand': { + 'feedId': feed_details.feed_id, + 'attributeValues': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'stringValues': [url] + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'stringValues': [label_name] + } + ] + }, + 'operator': 'ADD' + } for url in urls] + + # Add the feed item. + feed_item_service.mutate(operations) + + +def _UpdateCampaignDSASetting(client, campaign_id, feed_id): + """Updates the campaign DSA setting to DSA pagefeeds. + + Args: + client: an AdWordsClient instance. + campaign_id: a str Campaign ID. + feed_id: a str page Feed ID. + + Raises: + ValueError: If the given campaign is found not to be a dynamic search ad + campaign. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201806') + + selector = { + 'fields': ['Id', 'Settings'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [campaign_id] + }] + } + + response = campaign_service.get(selector) + + if response['totalNumEntries']: + campaign = response['entries'][0] + else: + raise ValueError('No campaign with ID "%d" exists.' % campaign_id) + + if not campaign['settings']: + raise ValueError('This is not a DSA campaign.') + + dsa_setting = None + + campaign_settings = campaign['settings'] + + for setting in campaign_settings: + if setting['Setting.Type'] == 'DynamicSearchAdsSetting': + dsa_setting = setting + break + + if dsa_setting is None: + raise ValueError('This is not a DSA campaign.') + + dsa_setting['pageFeed'] = { + 'feedIds': [feed_id] + } + + # Optional: Specify whether only the supplied URLs should be used with your + # Dynamic Search Ads. + dsa_setting['useSuppliedUrlsOnly'] = True + + operation = { + 'operand': { + 'id': campaign_id, + 'settings': campaign_settings + }, + 'operator': 'SET' + } + + campaign_service.mutate([operation]) + print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id) + + +def _AddDSATargeting(client, ad_group_id, label_name): + """Set custom targeting for the page feed URLs based on a list of labels. + + Args: + client: an AdWordsClient instance. + ad_group_id: a str AdGroup ID. + label_name: a str label name. + + Returns: + A suds.sudsobject.Object representing the newly created webpage criterion. + """ + # Get the AdGroupCriterionService. + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201806') + + # Create the operation. + operation = { + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Test criterion', + # Add a condition for label=specified_label_name. + 'conditions': [{ + 'operand': 'CUSTOM_LABEL', + 'argument': label_name + }], + } + }, + # Set a custom bid for this criterion + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 1500000 + } + }] + } + }, + 'operator': 'ADD' + } + + criterion = ad_group_criterion_service.mutate([operation])['value'][0] + print 'Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus']) + return criterion + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201806/advanced_operations/add_dynamic_search_ads_campaign.py new file mode 100755 index 00000000..4c51ac69 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_dynamic_search_ads_campaign.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Dynamic Search Ads campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + budget = _CreateBudget(client) + campaign_id = _CreateCampaign(client, budget) + ad_group_id = _CreateAdGroup(client, campaign_id) + _CreateExpandedDSA(client, ad_group_id) + _AddWebPageCriteria(client, ad_group_id) + + print 'Dynamic Search Ads campaign setup is complete.' + + +def _CreateBudget(client): + """Creates the budget. + + Args: + client: an AdWordsClient instance. + + Returns: + a suds.sudsobject.Object representation of the created budget. + """ + budget_service = client.GetService('BudgetService', version='v201806') + + # Create the campaign budget + operation = { + 'operand': { + 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), + 'deliveryMethod': 'STANDARD', + 'amount': { + 'microAmount': 500000 + } + }, + 'operator': 'ADD' + } + + budget = budget_service.mutate([operation])['value'][0] + + print 'Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name']) + + return budget + + +def _CreateCampaign(client, budget): + """Creates the campaign. + + Args: + client: an AdWordsClient instance. + budget: a suds.sudsobject.Object representation of a created budget. + + Returns: + An integer campaign ID. + """ + campaign_service = client.GetService('CampaignService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # prevent the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'budget': budget, + # Required: Set the campaign's Dynamic Search Ad settings. + 'settings': [{ + 'xsi_type': 'DynamicSearchAdsSetting', + # Required: Set the domain name and language. + 'domainName': 'example.com', + 'languageCode': 'en' + }], + # Optional: Set the start date. + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + # Optional: Set the end date. + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + }] + + campaign = campaign_service.mutate(operations)['value'][0] + campaign_id = campaign['id'] + + print 'Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name']) + + return campaign_id + + +def _CreateAdGroup(client, campaign_id): + """Creates an ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: an integer campaign ID. + + Returns: + An integer ad group ID. + """ + ad_group_service = client.GetService('AdGroupService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'adGroupType': 'SEARCH_DYNAMIC_ADS', + 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '3000000' + }, + }] + } + } + }] + + ad_group = ad_group_service.mutate(operations)['value'][0] + ad_group_id = ad_group['id'] + + print 'Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name']) + + return ad_group_id + + +def _CreateExpandedDSA(client, ad_group_id): + """Creates the expanded Dynamic Search Ad. + + Args: + client: an AdwordsClient instance. + ad_group_id: an integer ID of the ad group in which the DSA is added. + """ + # Get the AdGroupAdService. + ad_group_ad_service = client.GetService('AdGroupAdService') + + # Create the operation + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + # Create the expanded dynamic search ad. This ad will have its + # headline and final URL auto-generated at serving time according to + # domain name specific information provided by DynamicSearchAdsSetting + # at the campaign level. + 'ad': { + 'xsi_type': 'ExpandedDynamicSearchAd', + # Set the ad description. + 'description': 'Buy your tickets now!' + }, + # Optional: Set the status. + 'status': 'PAUSED', + } + }] + + # Create the ad. + ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] + + # Display the results. + print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' + 'added' % (ad['id'], ad['description'])) + + +def _AddWebPageCriteria(client, ad_group_id): + """Adds a web page criterion to target Dynamic Search Ads. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID of the ad group the criteria is being added to. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201806') + + operations = [{ + 'operator': 'ADD', + # Create biddable ad group criterion. + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion for special offers for children. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Special offers for children.', + 'conditions': [ + { + 'operand': 'URL', + 'argument': '/marscruise/children' + }, + { + 'operand': 'PAGE_TITLE', + 'argument': 'Special Offer' + } + ] + } + }, + 'userStatus': 'PAUSED', + # Optional: set a custom bid. + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000L + } + }] + } + } + }] + + criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201806/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..1cb4a046 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Create the expanded text ad + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + expanded_text_ad['trackingUrlTemplate'] = ( + 'http://tracker.example.com/?season={_season}&promocode={_promocode}' + '&u={lpurl}' + ) + + expanded_text_ad['urlCustomParameters'] = { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': expanded_text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_gmail_ad.py b/examples/adwords/v201806/advanced_operations/add_gmail_ad.py new file mode 100755 index 00000000..d7cf578c --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_gmail_ad.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example adds a Gmail ad to a given ad group. + +The ad group's campaign needs to have an AdvertisingChannelType of DISPLAY and +AdvertisingChannelSubType of DISPLAY_GMAIL_AD. + +To get your ad groups, run get_ad_groups.py. +""" + + +# Import appropriate classes from the client library. +from googleads import adwords + + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + media_service = client.GetService('MediaService', 'v201806') + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201806') + opener = client.proxy_config.BuildOpener() + + try: + # This ad format doesn't allow the creation of an image using the Image.data + # field. An image must first be created using the MediaService, and an + # Image.mediaId must be populated when creating the ad. + uploaded_logo_image = _CreateImage( + media_service, opener, 'https://goo.gl/mtt54n') + uploaded_marketing_image = _CreateImage( + media_service, opener, 'http://goo.gl/3b9Wfh') + + teaser = { + 'headline': 'Dream', + 'description': 'Create your own adventure', + 'businessName': 'Interplanetary Ships', + 'logoImage': uploaded_logo_image + } + + # Creates a Gmail ad. + gmail_ad = { + 'xsi_type': 'GmailAd', + 'teaser': teaser, + 'marketingImage': uploaded_marketing_image, + 'marketingImageHeadline': 'Travel', + 'marketingImageDescription': 'Take to the skies!', + 'finalUrls': ['http://wwww.example.com'] + } + + # Creates ad group ad for the Gmail ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': gmail_ad, + # Optional: Set additional settings. + 'status': 'PAUSED' + } + + # Creates ad group ad operations. + operations = [{ + 'operator': 'ADD', + 'operand': ad_group_ad + }] + + # Adds a Gmail ad. + ad_group_ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad_group_ad in ad_group_ads['value']: + print ('A Gmail ad with id "%d" and short headline "%s" was ' + 'added.' % (ad_group_ad['ad']['id'], + ad_group_ad['ad']['teaser']['headline'])) + except Exception as e: + raise Exception('Failed to create Gmail ad: %s' % e) + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = opener.open(url).read().decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_html5_ad.py b/examples/adwords/v201806/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..343ae2c2 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_html5_ad.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Create HTML5 media. + html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return response.read().decode('utf-8') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_multi_asset_responsive_display_ad.py b/examples/adwords/v201806/advanced_operations/add_multi_asset_responsive_display_ad.py new file mode 100755 index 00000000..c6c5273f --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_multi_asset_responsive_display_ad.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 adds a responsive display ad to an ad group. + +Image assets are uploaded using AssetService. To get ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords +import requests + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def UploadImageAsset(client, url): + """Uploads the image from the specified url. + + Args: + client: An AdWordsClient instance. + url: The image URL. + + Returns: + The ID of the uploaded image. + """ + # Initialize appropriate service. + asset_service = client.GetService('AssetService', version='v201806') + + # Download the image. + image_request = requests.get(url) + + # Create the image asset. + image_asset = { + 'xsi_type': 'ImageAsset', + 'imageData': image_request.content, + # This field is optional, and if provided should be unique. + # 'assetName': 'Image asset ' + str(uuid.uuid4()), + } + + # Create the operation. + operation = { + 'operator': 'ADD', + 'operand': image_asset + } + + # Create the asset and return the ID. + result = asset_service.mutate([operation]) + + return result['value'][0]['assetId'] + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Create the ad. + multi_asset_responsive_display_ad = { + 'xsi_type': 'MultiAssetResponsiveDisplayAd', + 'headlines': [{ + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Travel to Mars' + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Travel to Jupiter', + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Travel to Pluto' + } + }], + 'descriptions': [{ + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Visit the planet in a luxury spaceship.', + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'See the planet in style.', + } + }], + 'businessName': 'Galactic Luxury Cruises', + 'longHeadline': { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Visit the planet in a luxury spaceship.', + } + }, + # This ad format does not allow the creation of an image asset by setting + # the asset.imageData field. An image asset must first be created using + # the AssetService, and asset.assetId must be populated when creating + # the ad. + 'marketingImages': [{ + 'asset': { + 'xsi_type': 'ImageAsset', + 'assetId': UploadImageAsset(client, 'https://goo.gl/3b9Wfh') + } + }], + 'squareMarketingImages': [{ + 'asset': { + 'xsi_type': 'ImageAsset', + 'assetId': UploadImageAsset(client, 'https://goo.gl/mtt54n') + } + }], + # Optional values + 'finalUrls': ['http://www.example.com'], + 'callToActionText': 'Shop Now', + # Set color settings using hexadecimal values. Set allowFlexibleColor to + # false if you want your ads to render by always using your colors + # strictly. + 'mainColor': '#0000ff', + 'accentColor': '#ffff00', + 'allowFlexibleColor': False, + 'formatSetting': 'NON_NATIVE', + # Set dynamic display ad settings, composed of landscape logo image, + # promotion text, and price prefix. + 'dynamicSettingsPricePrefix': 'as low as', + 'dynamicSettingsPromoText': 'Free shipping!', + 'logoImages': [{ + 'asset': { + 'xsi_type': 'ImageAsset', + 'assetId': UploadImageAsset(client, 'https://goo.gl/mtt54n') + } + }] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': multi_asset_responsive_display_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new responsive display ad ad with ID "%d" ' + 'and long headline "%s".' + % (ad['ad']['id'], ad['ad']['longHeadline']['asset']['assetText'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201806/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..104c3e09 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + media_service = client.GetService('MediaService', version='v201806') + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + + try: + # Create marketing image. + marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/3b9Wfh') + + # Create square marketing image. + square_marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/mtt54n') + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': marketing_image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'], + # Optional: Set a square marketing image to the ad. + 'squareMarketingImage': { + 'mediaId': square_marketing_image['mediaId'] + }, + # Optional: Set call-to-action text. + 'callToActionText': 'Shop Now', + # Optional: Set dynamic display ad settings, composed of + # landscape logo image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( + media_service, opener), + # Whitelisted accounts only: Set color settings using + # hexadecimal numbers. + # Set allowFlexibleColor to False if you want your ads to render + # by always using your colors strictly. + # 'mainColor': '#0000ff', + # 'accentColor': '#ffff00', + # 'allowFlexibleColor': False + # Whitelisted accounts only: Set the format setting that the ad + # will be served in. + # 'formatSetting': 'NON_NATIVE' + + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = opener.open(url).read().decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +def _CreateDynamicDisplayAdSettings(media_service, opener): + """Creates settings for dynamic display ad. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + + Returns: + The dynamic display ad settings. + """ + image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + + logo = { + 'type': 'IMAGE', + 'mediaId': image['mediaId'], + 'xsi_type': 'Image' + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!', + 'xsi_type': 'DynamicSettings', + } + + return dynamic_settings + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201806/advanced_operations/add_shopping_dynamic_remarketing_campaign.py new file mode 100755 index 00000000..1f36a5fe --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_shopping_dynamic_remarketing_campaign.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Adds a Shopping dynamic remarketing campaign for the Display Network. + +This example steps through the following: +* Creates a new Display Network campaign. +* Links the campaign with Merchant Center. +* Links the user list to the ad group. +* Creates a responsive display ad to render the dynamic text. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import uuid + +from googleads import adwords + + +MERCHANT_ID = 'INSERT_MERCHANT_CENTER_ID_HERE' +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +USER_LIST_ID = 'INSERT_USER_LIST_ID_HERE' + + +def main(client, merchant_id, budget_id, user_list_id): + opener = client.proxy_config.BuildOpener() + + campaign = CreateCampaign(client, merchant_id, budget_id) + campaign_id = campaign['id'] + print 'Campaign with name "%s" and ID "%d" was added.' % ( + campaign['name'], campaign_id) + + ad_group = CreateAdGroup(client, campaign_id) + ad_group_id = ad_group['id'] + print 'Ad group with name "%s" and ID "%d" was added.' % ( + ad_group['name'], ad_group_id) + + ad_group_ad = CreateAd(client, opener, ad_group_id) + print 'Responsive display ad with ID "%d" was added.' % ( + ad_group_ad['ad']['id']) + + AttachUserList(client, ad_group_id, user_list_id) + print 'User list with ID "%d" was attached to ad group with ID "%d".' % ( + user_list_id, ad_group_id) + + +def CreateCampaign(client, merchant_id, budget_id): + """Creates a new Display Network campaign. + + Args: + client: an AdWordsClient instance. + merchant_id: a int merchant center ID. + budget_id: a int budget ID. + + Returns: + The campaign that was successfully created. + """ + campaign_service = client.GetService('CampaignService', 'v201806') + + campaign = { + 'name': 'Shopping campaign #%d' % uuid.uuid4(), + # Dynamic remarketing campaigns are only available on the Google Display + # Network. + 'advertisingChannelType': 'DISPLAY', + 'status': 'PAUSED', + 'budget': { + 'budgetId': budget_id + }, + # This example uses a Manual CPC bidding strategy, but you should select + # the strategy that best aligns with your sales goals. More details here: + # https://support.google.com/adwords/answer/2472725 + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [{ + 'xsi_type': 'ShoppingSetting', + # Campaigns with numerically higher priorities take precedence over + # those with lower priorities. + 'campaignPriority': 0, + 'merchantId': merchant_id, + # Display network campaigns do not support partition by country. The + # only supported value is "ZZ". This signals that products from all + # countries are available in this campaign. The actual products which + # serve are based on the products tagged in the user list entry. + 'salesCountry': 'ZZ', + # Optional: Enable local inventory ads (items for sale in physical + # stores.) + 'enableLocal': True, + }] + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + return campaign_service.mutate(operations)['value'][0] + + +def CreateAdGroup(client, campaign_id): + """Creates a dynamic remarketing campaign. + + Args: + client: an AdWordsClient instance. + campaign_id: an int campaign ID. + + Returns: + The ad group that was successfully created. + """ + ad_group_service = client.GetService('AdGroupService', 'v201806') + + ad_group = { + 'name': 'Dynamic remarketing ad group', + 'campaignId': campaign_id, + 'status': 'ENABLED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': ad_group + }] + + return ad_group_service.mutate(operations)['value'][0] + + +def CreateAd(client, opener, ad_group_id): + """Creates a ResponsiveDisplayAd. + + Args: + client: an AdWordsClient instance. + opener: an OpenerDirector instance. + ad_group_id: an int ad group ID. + + Returns: + The ad group ad that was successfully created. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201806') + media_service = client.GetService('MediaService', 'v201806') + + marketing_image_id = _CreateImage( + media_service, opener, 'https://goo.gl/3b9Wfh') + logo_image_id = _CreateImage(media_service, opener, 'https://goo.gl/mtt54n') + + ad = { + 'xsi_type': 'ResponsiveDisplayAd', + # This ad format doesn't allow the creation of an image using the + # Image.data field. An image must first be created using the MediaService, + # and Image.mediaId must be populated when creating the ad. + 'marketingImage': { + 'xsi_type': 'Image', + 'mediaId': marketing_image_id + }, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://wwww.example.com'], + # Optional: Call to action text. + # Valid texts: https://support.google.com/adwords/answer/7005917 + 'callToActionText': 'Apply Now', + # Optional: Set dynamic display ad settings, composed of landscape logo + # image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': CreateDynamicDisplayAdSettings( + client, opener), + # Optional: Create a logo image and set it to the ad. + 'logoImage': { + 'xsi_type': 'Image', + 'mediaId': logo_image_id + }, + # Optional: Create a square marketing image and set it to the ad. + 'squareMarketingImage': { + 'xsi_type': 'Image', + 'mediaId': logo_image_id + }, + # Whitelisted accounts only: Set color settings using hexadecimal values. + # Set allowFlexibleColor to False if you want your ads to render by always + # using your colors strictly. + # 'mainColor': '#000fff', + # 'accentColor': '#fff000', + # 'allowFlexibleColor': False, + # Whitelisted accounts only: Set the format setting that the ad will be + # served in. + # 'formatSetting': 'NON_NATIVE' + } + + ad_group_ad = { + 'ad': ad, + 'adGroupId': ad_group_id + } + + operations = [{ + 'operation': 'ADD', + 'operand': ad_group_ad + }] + + return ad_group_ad_service.mutate(operations)['value'][0] + + +def AttachUserList(client, ad_group_id, user_list_id): + """Links the provided ad group and user list. + + Args: + client: an AdWordsClient instance. + ad_group_id: an int ad group ID. + user_list_id: an int user list ID. + + Returns: + The ad group criterion that was successfully created. + """ + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', 'v201806') + + user_list = { + 'xsi_type': 'CriterionUserList', + 'userListId': user_list_id + } + + ad_group_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'criterion': user_list, + 'adGroupId': ad_group_id + } + + operations = [{ + 'operator': 'ADD', + 'operand': ad_group_criterion + }] + + return ad_group_criterion_service.mutate(operations)['value'][0] + + +def CreateDynamicDisplayAdSettings(client, opener): + """Creates dynamic display ad settings. + + Args: + client: an AdWordsClient instance. + opener: an OpenerDirector instance. + + Returns: + A dict containing the dynamic display ad settings. + """ + media_service = client.GetService('MediaService', 'v201806') + + logo = { + 'xsi_type': 'Image', + 'mediaId': _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!' + } + + return dynamic_settings + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = opener.open(url).read().decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, MERCHANT_ID, BUDGET_ID, USER_LIST_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201806/advanced_operations/add_universal_app_campaign.py new file mode 100755 index 00000000..3149fb47 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/add_universal_app_campaign.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Universal App campaign. + +To get campaigns, run get_campaigns.py. To upload image assets for this +campaign, run upload_image.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201806') + + budget_id = CreateBudget(client) + + # Create the Universal App campaign. + universal_app_campaign = { + 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'MULTI_CHANNEL', + 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', + # Set the campaign's bidding strategy. Universal app campaigns only + # support TARGET_CPA bidding strategy. + 'biddingStrategyConfiguration': { + # Set the target CPA to $1 / app install. + 'biddingScheme': { + 'xsi_type': 'TargetCpaBiddingScheme', + 'targetCpa': { + 'microAmount': '1000000' + } + }, + 'biddingStrategyType': 'TARGET_CPA' + }, + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + + universal_app_campaign['settings'] = [ + # Set the campaign's assets and ad text ideas. These values will + # be used to generate ads. + { + 'xsi_type': 'UniversalAppCampaignSetting', + 'appId': 'com.labpixies.colordrips', + 'appVendor': 'VENDOR_GOOGLE_MARKET', + 'description1': 'A cool puzzle game', + 'description2': 'Remove connected blocks', + 'description3': '3 difficulty levels', + 'description4': '4 colorful fun skins', + # Optional: You can set up to 20 image assets for your campaign. + # See upload_image.py for an example on how to upload images. + # + # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] + } + ] + + # Optimize this campaign for getting new users for your app. + universal_app_campaign_setting = universal_app_campaign['settings'][0] + universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( + 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') + + # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, + # then also specify your in-app conversion types so AdWords can focus your + # campaign on people who are most likely to complete the corresponding in-app + # actions. + # + # Conversions type IDs can be retrieved using ConversionTrackerService.get. + # universal_app_campaign['selectiveOptimization'] = { + # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] + # } + + # Optional: Set the campaign settings for Advanced location options. + universal_app_campaign['settings'].append({ + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + }) + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': universal_app_campaign + }] + + campaigns = campaign_service.mutate(operations)['value'] + + # Display results. + if campaigns: + for campaign in campaigns: + print ('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + # Optional: Set the campaign's location and language targeting. No other + # targeting criteria can be used for Universal App campaigns. + SetCampaignTargetingCriteria(client, campaign) + else: + print 'No Universal App campaigns were added.' + + +def CreateBudget(client): + """Creates a budget and returns its budgetId. + + Args: + client: An AdWordsClient instance. + + Returns: + An int budgetId for the created Budget. + """ + budget_service = client.GetService('BudgetService', version='v201806') + + # Create a budget. + budget = { + 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Create the budget and return its ID. + budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] + + return budget_id + + +def SetCampaignTargetingCriteria(client, campaign): + """Sets targeting criteria for the given campaign. + + Args: + client: An AdWordsClient instance. + campaign: A suds object representing the campaign we wish to attach + targeting criteria. + """ + campaign_criterion_service = client.GetService('CampaignCriterionService') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + criteria = [ + { + 'xsi_type': 'Location', + 'id': 21137 # California + }, + { + 'xsi_type': 'Location', + 'id': 2484 # Mexico + }, + { + 'xsi_type': 'Language', + 'id': 1000 # English + }, + { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + ] + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign['id'], + 'criterion': criterion + } + } for criterion in criteria] + + response = campaign_criterion_service.mutate(operations) + + if response and 'value' in response: + # Display the added campaign targets. + for criterion in response['value']: + print ('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], + criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201806/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..0bd0a11f --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201806') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201806') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201806') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201806/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..0d6356c1 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201806') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201806') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201806/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..4b470490 --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201806') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201806/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..0f3138da --- /dev/null +++ b/examples/adwords/v201806/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201806') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201806') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201806') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201806/basic_operations/__init__.py b/examples/adwords/v201806/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201806/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201806/basic_operations/add_ad_groups.py b/examples/adwords/v201806/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..c3d54ca0 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201806') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name "%s" and id "%s" was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/basic_operations/add_campaigns.py b/examples/adwords/v201806/basic_operations/add_campaigns.py new file mode 100755 index 00000000..d7b6104b --- /dev/null +++ b/examples/adwords/v201806/basic_operations/add_campaigns.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201806') + budget_service = client.GetService('BudgetService', version='v201806') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201806/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..77459ca7 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'description': 'Buy your tickets now!', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/add_keywords.py b/examples/adwords/v201806/basic_operations/add_keywords.py new file mode 100755 index 00000000..510f1982 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201806') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/add_responsive_search_ad.py b/examples/adwords/v201806/basic_operations/add_responsive_search_ad.py new file mode 100755 index 00000000..e633f505 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/add_responsive_search_ad.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 adds a responsive search ad to a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + responsive_search_ad = { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveSearchAd', + 'finalUrls': ['http://www.example.com/cruise'], + 'path1': 'all-inclusive', + 'path2': 'deals', + 'headlines': [{ + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Cruise to Mars # ' + str(uuid.uuid4())[:8] + }, + 'pinnedField': 'HEADLINE_1' + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Best Space Cruise Line', + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Experience the Stars' + } + }], + 'descriptions': [{ + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Buy your tickets now.' + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Visit the Red Planet', + } + }], + }, + # Optional fields. + 'status': 'PAUSED' + } + + # Create the operations. + operations = [{ + 'operator': 'ADD', + 'operand': responsive_search_ad + }] + + # Create the ad on the server. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + ad = ad['ad'] + print ('Ad of type "%s" with id "%d" was added.\n' + 'Headlines:\n%s\n' + 'Descriptions:\n%s' + % (ad['Ad.Type'], ad['id'], + '\n'.join(['\t%s (pinned to %s)' % + (headline['asset']['assetText'], + headline['pinnedField']) + for headline in ad['headlines']]), + '\n'.join(['\t%s (pinned to %s)' % + (headline['asset']['assetText'], + headline['pinnedField']) + for headline in ad['descriptions']]))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/get_ad_groups.py b/examples/adwords/v201806/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..57909335 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201806') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name "%s", id "%s" and status "%s" was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/basic_operations/get_campaigns.py b/examples/adwords/v201806/basic_operations/get_campaigns.py new file mode 100755 index 00000000..a79a81cc --- /dev/null +++ b/examples/adwords/v201806/basic_operations/get_campaigns.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201806') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201806/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..5d1964d2 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201806') + + # Construct query and get all campaigns. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'Name', 'Status') + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, PAGE_SIZE) + .Build()) + + for page in query.Pager(campaign_service): + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201806/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..0e552503 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an expanded text ad, run add_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/get_keywords.py b/examples/adwords/v201806/basic_operations/get_keywords.py new file mode 100755 index 00000000..d302dcb0 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201806') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/get_responsive_search_ads.py b/examples/adwords/v201806/basic_operations/get_responsive_search_ads.py new file mode 100755 index 00000000..16f5fbbc --- /dev/null +++ b/examples/adwords/v201806/basic_operations/get_responsive_search_ads.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 non-removed responsive search ads in a specified ad group. + +To add responsive search ads, run add_responsive_search_ad.py. To get ad groups, +run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'Status', 'ResponsiveSearchAdHeadlines', + 'ResponsiveSearchAdDescriptions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['RESPONSIVE_SEARCH_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group_ad in page['entries']: + ad = ad_group_ad['ad'] + print ('Responsive search ad with status %s and id "%d" was found.\n' + 'Headlines:\n%s\n' + 'Descriptions:\n%s' + % (ad_group_ad['status'], ad['id'], + '\n'.join(['\t%s (pinned to %s)' % + (headline['asset']['assetText'], + headline['pinnedField']) + for headline in ad['headlines']]), + '\n'.join(['\t%s (pinned to %s)' % + (headline['asset']['assetText'], + headline['pinnedField']) + for headline in ad['descriptions']]))) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/pause_ad.py b/examples/adwords/v201806/basic_operations/pause_ad.py new file mode 100755 index 00000000..be54b6ac --- /dev/null +++ b/examples/adwords/v201806/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id "%s" was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201806/basic_operations/remove_ad.py b/examples/adwords/v201806/basic_operations/remove_ad.py new file mode 100755 index 00000000..4ebcb023 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id "%s" and type "%s" was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201806/basic_operations/remove_ad_group.py b/examples/adwords/v201806/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..45790fd6 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201806') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name "%s" and id "%s" was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/remove_campaign.py b/examples/adwords/v201806/basic_operations/remove_campaign.py new file mode 100755 index 00000000..9c9cae62 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201806') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name "%s" and id "%s" was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/basic_operations/remove_keyword.py b/examples/adwords/v201806/basic_operations/remove_keyword.py new file mode 100755 index 00000000..4a15a2cb --- /dev/null +++ b/examples/adwords/v201806/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201806') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201806/basic_operations/update_ad_group.py b/examples/adwords/v201806/basic_operations/update_ad_group.py new file mode 100755 index 00000000..879c7334 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/update_ad_group.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the CPC bid and status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' + + +def main(client, ad_group_id, bid_micro_amount=None): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201806') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + + if bid_micro_amount: + operations[0]['operand']['biddingStrategyConfiguration'] = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': bid_micro_amount, + } + }] + } + + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] + # Find the CpcBid in the bidding strategy configuration's bids collection. + cpc_bid_micros = None + + if bidding_strategy_configuration: + bids = bidding_strategy_configuration['bids'] + + if bids: + for bid in bids: + if bid['Bids.Type'] == 'CpcBid': + cpc_bid_micros = bid['bid']['microAmount'] + break + + print ('Ad group with name "%s", and id "%s" was updated to have status ' + '"%s" and CPC bid %d.' + % (ad_group['name'], ad_group['id'], ad_group['status'], + cpc_bid_micros)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201806/basic_operations/update_campaign.py b/examples/adwords/v201806/basic_operations/update_campaign.py new file mode 100755 index 00000000..39f999d9 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201806') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/basic_operations/update_expanded_text_ad.py b/examples/adwords/v201806/basic_operations/update_expanded_text_ad.py new file mode 100755 index 00000000..20da1137 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/update_expanded_text_ad.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 updates an expanded text ad. + +To get expanded text ads, run get_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid +from googleads import adwords + + +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_id): + # Initialize appropriate service. + ad_service = client.GetService('AdService', version='v201806') + + # Create an expanded text ad using the provided ad ID. + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'id': ad_id, + 'headlinePart1': 'Cruise to Pluto #' + str(uuid.uuid4())[:8], + 'headlinePart2': 'Tickets on sale now', + 'description': 'Best space cruise ever.', + 'finalUrls': ['http://www.example.com'], + 'finalMobileUrls': ['http://www.example.com/mobile'] + } + + # Create ad group ad operation. + operations = [{ + 'operator': 'SET', + 'operand': expanded_text_ad + }] + + # Updates the ad on ther server. + result = ad_service.mutate(operations) + updated_ad = result['value'][0] + + print 'Expanded text ad with ID %s was updated.' % updated_ad['id'] + print ('\tHeadline part 1: %s\nHeadline part 2: %s\nDescription: %s\n' + 'Final URL: %s\nFinal mobile URL: %s' % + (updated_ad['headlinePart1'], + updated_ad['headlinePart2'], + updated_ad['description'], + updated_ad['finalUrls'][0], + updated_ad['finalMobileUrls'][0])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_ID) diff --git a/examples/adwords/v201806/basic_operations/update_keyword.py b/examples/adwords/v201806/basic_operations/update_keyword.py new file mode 100755 index 00000000..ba612d58 --- /dev/null +++ b/examples/adwords/v201806/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201806') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: "%s", value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201806/campaign_management/__init__.py b/examples/adwords/v201806/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201806/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201806/campaign_management/add_campaign_groups_and_performance_targets.py new file mode 100755 index 00000000..56ea182a --- /dev/null +++ b/examples/adwords/v201806/campaign_management/add_campaign_groups_and_performance_targets.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a campaign group and sets a performance target for it. + +To get campaigns, run get_campaigns.py. To download reports, run +download_criteria_report_with_awql.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id1, campaign_id2): + campaign_group_id = _CreateCampaignGroup(client) + _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) + _CreatePerformanceTarget(client, campaign_group_id) + print 'Campaign group and its performance target were setup successfully.' + + +def _CreateCampaignGroup(client): + """Create a campaign group. + + Args: + client: an AdWordsClient instance. + + Returns: + The integer ID of the created campaign group. + """ + # Get the CampaignGroupService. + campaign_group_service = client.GetService('CampaignGroupService', + version='v201806') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the campaign group. + 'operand': { + 'name': 'Mars campaign group #%d' % uuid.uuid4() + } + }] + + campaign_group = campaign_group_service.mutate(operations)['value'][0] + campaign_group_id = campaign_group['id'] + + # Display the results. + print 'Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name']) + + return campaign_group_id + + +def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): + """Adds multiple campaigns to a campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + campaign_ids: a list of integer IDs for campaigns. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201806') + + # Create the operations. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'campaignGroupId': campaign_group_id + } + } for campaign_id in campaign_ids] + + campaign_service.mutate(operations) + + # Display the results. + print ('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + + +def _CreatePerformanceTarget(client, campaign_group_id): + """Creates a performance target for the campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + """ + # Get the CampaignGroupPerformanceTargetService. + cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', + version='v201806') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the performance target. + 'operand': { + 'campaignGroupId': campaign_group_id, + 'performanceTarget': { + # Keep the CPC for the campaigns < $3. + 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', + 'efficiencyTargetValue': 3000000, + # Keep the maximum spend under $50. + 'spendTargetType': 'MAXIMUM', + 'spendTarget': { + 'microAmount': 500000000 + }, + # Aim for at least 3000 clicks. + 'volumeGoalType': 'MAXIMIZE_CLICKS', + 'volumeTargetValue': 3000, + # Start the performance target today, and run it for the next 90 + # days. + 'startDate': datetime.datetime.now().strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(90)).strftime('%Y%m%d') + } + } + }] + + cgpt = cgpt_service.mutate(operations)['value'][0] + + # Display the results. + print ('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201806/campaign_management/add_campaign_labels.py b/examples/adwords/v201806/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..4e8625d0 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201806') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201806/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201806/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..a1ea42f1 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201806') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201806') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding an ExpandedTextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new ExpandedTextAd for + each of the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once + # you've added targeting and the ads are ready to serve. + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201806') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201806/campaign_management/add_draft.py b/examples/adwords/v201806/campaign_management/add_draft.py new file mode 100755 index 00000000..cd33973d --- /dev/null +++ b/examples/adwords/v201806/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + draft_service = client.GetService('DraftService', version='v201806') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201806') + + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201806/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201806/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..bb37351e --- /dev/null +++ b/examples/adwords/v201806/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to incrementally upload keywords. + +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201806') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201806') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201806') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201806') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/campaign_management/add_trial.py b/examples/adwords/v201806/campaign_management/add_trial.py new file mode 100755 index 00000000..568b9d21 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/add_trial.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201806') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201806') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50 + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201806/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201806/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..a9fbc258 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'PolicySummary'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CombinedApprovalStatus', + 'operator': 'EQUALS', + 'values': 'DISAPPROVED' + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + disapproved_count = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.get(selector) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName'], + policy_topic_entry['policyTopicHelpCenterUrl']) + # Display the attributes and values that triggered the policy topic. + policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] + if policy_topic_evidences: + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201806/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..8fe617a8 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', + version='v201806') + + # Construct query and get all ads for a given campaign. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'PolicySummary') + .Where('AdGroupId').EqualTo(ad_group_id) + .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') + .OrderBy('Id') + .Limit(0, PAGE_SIZE) + .Build()) + disapproved_count = 0 + + # Display results. + while True: + page = ad_group_ad_service.query(query) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + # Display the attributes and values that triggered the policy topic. + if ('policyTopicEvidences' in policy_topic_entry + and policy_topic_entry['policyTopicEvidences']): + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + if not query.HasNext(page): + break + query.NextPage() + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201806/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..4fcdbc14 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201806') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id "%s", name "%s", and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201806/campaign_management/graduate_trial.py b/examples/adwords/v201806/campaign_management/graduate_trial.py new file mode 100755 index 00000000..cb5a2700 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201806') + budget_service = client.GetService('BudgetService', version='v201806') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201806/campaign_management/set_ad_parameters.py b/examples/adwords/v201806/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..a3d0d09f --- /dev/null +++ b/examples/adwords/v201806/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + ad_param_service = client.GetService('AdParamService', version='v201806') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201806/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201806/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..83cfb697 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201806') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201806/campaign_management/validate_text_ad.py b/examples/adwords/v201806/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..b0f58439 --- /dev/null +++ b/examples/adwords/v201806/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +No objects will be created, but exceptions will still be returned. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords +from googleads import errors + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Construct operations to add an expanded text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'] + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for all astronauts in orbit', + 'finalUrls': ['http://www.example.com'], + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except errors.GoogleAdsServerFault, e: + print 'Validation correctly failed with "%s".' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/error_handling/__init__.py b/examples/adwords/v201806/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201806/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201806/error_handling/handle_partial_failures.py b/examples/adwords/v201806/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..1c65cfea --- /dev/null +++ b/examples/adwords/v201806/error_handling/handle_partial_failures.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201806') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + if (first_field_path_element and + first_field_path_element['field'] == 'operations' and + 'index' in first_field_path_element): + operation_index = first_field_path_element['index'] + + adgroup_criterion = operations[operation_index]['operand'] + + print('Ad group criterion with ad group ID %s and keyword "%s" triggered ' + 'a failure for the following reason: %s.' + % (adgroup_criterion['adGroupId'], + adgroup_criterion['criterion']['text'], + error['errorString'])) + else: + print ('A failure has occurred for the following reasons: %s\n' + % error['errorString']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/error_handling/handle_policy_violation_error.py b/examples/adwords/v201806/error_handling/handle_policy_violation_error.py new file mode 100755 index 00000000..976648b3 --- /dev/null +++ b/examples/adwords/v201806/error_handling/handle_policy_violation_error.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle policy violation errors. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + + +from googleads import adwords +from googleads import errors + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201806') + + # Create expanded text ad that violates an exemptable policy. + exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise!!!', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + # Create text ad that violates a non-exemptable policy. + non_exemptable_expanded_text_ad_operation = { + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + # The 'xsi_type' field allows you to specify the xsi:type of the + # object being created. It's only necessary when you must provide + # an explicit type that the client library can't infer. + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Mars Cruise with too long of a headline.', + 'headlinePart2': 'Best space cruise line.', + 'description': 'Visit the Red Planet in style.', + 'finalUrls': ['http://www.example.com'] + } + } + } + + operations = [exemptable_expanded_text_ad_operation, + non_exemptable_expanded_text_ad_operation] + + # Validate the ad. + try: + # Enable "validate only" to check for errors. + client.validate_only = True + ad_group_ad_service.mutate(operations) + print 'Validation successful, no errors returned.' + except errors.GoogleAdsServerFault, e: + for error in e.errors: + # Get the index of the failed operation from the error's field path + # elements. + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + # If the operation index is not present on the first error field path + # element, then there's no way to determine which operation to remove, + # so simply throw the exception. + if (not (first_field_path_element + and first_field_path_element['field'] == 'operations' + and 'index' in first_field_path_element)): + raise e + + index = long(first_field_path_element['index']) + operation = operations[index] + if not HandleAPIError(error, operation): + # Set non-exemptable operation to None to mark for deletion. + print ('Removing operation with non-exemptable error at index %s.' + % index) + operations[index] = None + + # Remove the non-exemptable operations. + operations = [op for op in operations if op is not None] + + # Add these ads. Disable "validate only" so the ads will get created. + client.validate_only = False + if operations: + response = ad_group_ad_service.mutate(operations) + if response and response['value']: + ads = response['value'] + print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) + for ad in ads: + print (' Ad id is %s, type is %s and status is "%s".' % + (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + print 'No ads were added.' + + +def HandleAPIError(error, operation): + """Makes an exemption for exemptable PolicyViolationErrors. + + Args: + error: the error associated with the given operation. + operation: the operation associated with the given error. + + Returns: + A boolean that is True if the given error was an exemptable + PolicyViolationError; otherwise, returns False. + """ + is_exemptable = False + + # Determine if the operation can be resubmitted with an exemption request. + if error['ApiError.Type'] == 'PolicyViolationError': + expanded_text_ad = operation['operand']['ad'] + is_exemptable = (error['isExemptable'] if 'isExemptable' in error else + False) + print ('Ad with headline "%s - %s" violated %s policy "%s".' % + (expanded_text_ad['headlinePart1'], + expanded_text_ad['headlinePart2'], + 'exemptable' if is_exemptable else 'non-exemptable', + error['externalPolicyName'])) + + if is_exemptable: + # Add exemption request to the operation. + print ('Adding exemption request for policy name "%s" on text "%s".' + % (error['key']['policyName'], error['key']['violatingText'])) + if 'exemptionRequests' not in operation: + operation['exemptionRequests'] = [] + operation['exemptionRequests'].append({'key': error['key']}) + + return is_exemptable + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/extensions/__init__.py b/examples/adwords/v201806/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201806/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201806/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201806/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..8f719027 --- /dev/null +++ b/examples/adwords/v201806/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201806').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201806') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except errors.GoogleAdsServerFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201806/extensions/add_prices.py b/examples/adwords/v201806/extensions/add_prices.py new file mode 100755 index 00000000..1963ccd6 --- /dev/null +++ b/examples/adwords/v201806/extensions/add_prices.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201806') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', + final_mobile_url='http://m.example.com/scrubs'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url='http://m.example.com/haircuts'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url=( + 'http://m.example.com/skincarepackage')) + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit, final_mobile_url=None): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + final_mobile_url: A str containing the final mobile URL after all cross + domain redirects. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + table_row = { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + if final_mobile_url: + table_row['finalMobileUrls'] = { + 'urls': [final_mobile_url] + } + + return table_row + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/extensions/add_site_links.py b/examples/adwords/v201806/extensions/add_site_links.py new file mode 100755 index 00000000..fac3a6fb --- /dev/null +++ b/examples/adwords/v201806/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201806') + customer_service = client.GetService('CustomerService', version='v201806') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/extensions/add_site_links_using_feeds.py b/examples/adwords/v201806/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..08086673 --- /dev/null +++ b/examples/adwords/v201806/extensions/add_site_links_using_feeds.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Optional: Ad group to restrict targeting to. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def RestrictFeedItemToGeoTarget(client, feed_item, location_id): + """Restrict a feed item to a geo target location. + + Args: + client: An AdWordsClient instance. + feed_item: A FeedItem. + location_id: The Id of the location to restrict to. + """ + # Retrieve the FeedItemTargetService + feed_item_target_service = client.GetService( + 'FeedItemTargetService', version='v201806') + + # Optional: Restrict the first feed item to only serve with ads for the + # specified geo target. + criterion_target = { + 'xsi_type': 'FeedItemCriterionTarget', + 'feedId': feed_item['feedId'], + 'feedItemId': feed_item['feedItemId'], + # These IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + 'criterion': { + 'xsi_type': 'Location', + 'id': location_id + } + } + + operation = {'operator': 'ADD', 'operand': criterion_target} + + response = feed_item_target_service.mutate([operation]) + new_location_target = response['value'][0] + print('Feed item target for feed ID %d and feed item ID %d was created to ' + 'restrict serving to location ID %d.' % + (new_location_target['feedId'], + new_location_target['feedItemId'], + new_location_target['criterion']['id'])) + + +def main(client, campaign_id, ad_group_id=None): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201806') + feed_item_service = client.GetService('FeedItemService', version='v201806') + feed_item_target_service = client.GetService('FeedItemTargetService', + version='v201806') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201806') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201806') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name "%s" and ID "%d" was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID "%d" and Final URL attribute ID "%d".' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 2 attribute ID "%d" and Line 3 attribute ID "%d".' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line2': 'Home line 2', 'line3': 'Home line 3'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line2': 'Support line 2', 'line3': 'Support line 3'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line2': 'Products line 2', 'line3': 'Products line 3'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line2': 'About line 2', 'line3': 'About line 3', 'locationTarget': True} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Optional: Restrict targeting only to people physically within + # the location. + if 'locationTarget' in item: + item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %d was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Target the "aboutUs" sitelink to geographically target California. + # See https://developers.google.com/adwords/api/docs/appendix/geotargeting for + # location criteria for supported locations. + RestrictFeedItemToGeoTarget(client, response['value'][5], 21137) + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %d and placeholder type %s was saved for feed' + ' with ID %d.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %d was associated with feed with ID %d.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + # Optional: Restrict the first feed item to only serve with ads for the + # specified ad group ID. + if ad_group_id: + feed_item_target = { + 'xsi_type': 'FeedItemAdGroupTarget', + 'feedId': sitelinks_data['feedId'], + 'feedItemId': sitelinks_data['feedItemIds'][0], + 'adGroupId': ad_group_id + } + + operations = [{ + 'operator': 'ADD', + 'operand': feed_item_target + }] + + response = feed_item_target_service.mutate(operations) + + if 'value' in response: + print ('Feed item target for feed ID "%d" and feed item ID "%d" was ' + 'created to restrict serving to ad group ID "%d".' + % (feed_item_target['feedId'], feed_item_target['feedItemId'], + feed_item_target['adGroupId'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + if AD_GROUP_ID == 'INSERT_AD_GROUP_ID_HERE': + main(adwords_client, CAMPAIGN_ID) + else: + main(adwords_client, CAMPAIGN_ID, ad_group_id=AD_GROUP_ID) diff --git a/examples/adwords/v201806/migration/__init__.py b/examples/adwords/v201806/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201806/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201806/migration/migrate_to_extension_settings.py b/examples/adwords/v201806/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..fcdfd777 --- /dev/null +++ b/examples/adwords/v201806/migration/migrate_to_extension_settings.py @@ -0,0 +1,526 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +This code example doesn't migrate scheduling or feeditem-level campaign, +adgroup, keyword, or geo targeting settings. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201806') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201806') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201806') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201806') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201806') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201806') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201806') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/misc/__init__.py b/examples/adwords/v201806/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201806/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201806/misc/get_all_image_assets.py b/examples/adwords/v201806/misc/get_all_image_assets.py new file mode 100755 index 00000000..a29bbf91 --- /dev/null +++ b/examples/adwords/v201806/misc/get_all_image_assets.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 image assets. + +To upload an image asset, run upload_image_asset.py + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + asset_service = client.GetService('AssetService', version='v201806') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['AssetName', 'AssetStatus', 'ImageFileSize', 'ImageWidth', + 'ImageHeight', 'ImageFullSizeUrl'], + 'predicates': [{ + 'field': 'AssetSubtype', + 'operator': 'IN', + 'values': ['IMAGE'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = asset_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + print ('Image asset with id %s, name "%s", and status %s was found.\n' + '\tSize is %sx%s and asset URL is %s.' % + (image['assetId'], image['assetName'], image['assetStatus'], + image['fullSizeInfo']['imageWidth'], + image['fullSizeInfo']['imageHeight'], + image['fullSizeInfo']['imageUrl'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/misc/get_all_images_and_videos.py b/examples/adwords/v201806/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..218173e0 --- /dev/null +++ b/examples/adwords/v201806/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201806') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/misc/upload_image.py b/examples/adwords/v201806/misc/upload_image.py new file mode 100755 index 00000000..75563e6c --- /dev/null +++ b/examples/adwords/v201806/misc/upload_image.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201806') + + with open(image_filename, 'rb') as image_handle: + image_data = image_handle.read().decode('utf-8') + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201806/misc/upload_image_asset.py b/examples/adwords/v201806/misc/upload_image_asset.py new file mode 100755 index 00000000..cfafe6ce --- /dev/null +++ b/examples/adwords/v201806/misc/upload_image_asset.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 uploads an image asset. + +To get image assets, run get_all_image_assets.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +import requests + + +def main(client): + # Initialize appropriate service. + asset_service = client.GetService('AssetService', version='v201806') + + image_request = requests.get('https://goo.gl/3b9Wfh') + image_data = image_request.content + + # Construct media and upload image asset. + image_asset = { + 'xsi_type': 'ImageAsset', + # Optional: Provide a unique friendly name to identify your asset. If you + # specify the assetName field, then both the asset name and the image + # being uploaded should be unique, and should not match another ACTIVE + # asset in this customer account. + # 'assetName': 'Jupiter Trip #' + str(uuid.uuid4())[:8], + 'imageData': image_data, + + } + + operation = {'operator': 'ADD', 'operand': image_asset} + + asset = asset_service.mutate([operation])['value'][0] + + # Display results. + if asset: + print ('Image asset with id %s, name "%s", and status %s was created.\n' + '\tSize is %sx%s and asset URL is %s.' % + (asset['assetId'], asset['assetName'], asset['assetStatus'], + asset['fullSizeInfo']['imageWidth'], + asset['fullSizeInfo']['imageHeight'], + asset['fullSizeInfo']['imageUrl'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/misc/upload_media_bundle.py b/examples/adwords/v201806/misc/upload_media_bundle.py new file mode 100755 index 00000000..83ecb649 --- /dev/null +++ b/examples/adwords/v201806/misc/upload_media_bundle.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201806') + # Create HTML5 media. + html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return response.read().decode('utf-8') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/optimization/__init__.py b/examples/adwords/v201806/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201806/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201806/optimization/estimate_keyword_traffic.py b/examples/adwords/v201806/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..3a4e81bf --- /dev/null +++ b/examples/adwords/v201806/optimization/estimate_keyword_traffic.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201806') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate + and min_estimate['averageCpc'] else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate + and min_estimate['averagePosition'] else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201806/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..13cce825 --- /dev/null +++ b/examples/adwords/v201806/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201806') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..e57a5c27 --- /dev/null +++ b/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201806') + + # Construct bid landscape selector object and retrieve bid landscape. + selector = { + 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'BiddableConversions', 'BiddableConversionsValue', + 'LocalClicks', 'LocalCost', 'LocalImpressions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CriterionId', + 'operator': 'EQUALS', + 'values': [criterion_id] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages: + num_landscape_points = 0 + page = data_service.getCriterionBidLandscape(selector) + + if page and 'entries' in page: + entries = page['entries'] + print 'Bid landscape(s) retrieved: %d.' % len(entries) + + for bid_landscape in entries: + print ('Retrieved keyword bid landscape with ad group ID "%d", ' + 'keyword ID "%d", start date "%s", end date "%s", ' + 'with landscape points:' % ( + bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + num_landscape_points += 1 + print (' bid: %s => clicks: %s, cost: %s, impressions: %s, ' + 'biddable conversions: %.2f, ' + 'biddable conversions value: %.2f' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'], + bid_landscape_point['biddableConversions'], + bid_landscape_point['biddableConversionsValue'])) + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201806/optimization/get_keyword_ideas.py b/examples/adwords/v201806/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..c397aa79 --- /dev/null +++ b/examples/adwords/v201806/optimization/get_keyword_ideas.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id=None): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201806') + + # Construct selector object and retrieve related keywords. + selector = { + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS' + } + + selector['requestedAttributeTypes'] = [ + 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] + + offset = 0 + selector['paging'] = { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + + selector['searchParameters'] = [{ + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }] + + # Language setting (optional). + selector['searchParameters'].append({ + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }) + + # Network search parameter (optional) + selector['searchParameters'].append({ + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + }) + + # Use an existing ad group to generate ideas (optional) + if ad_group_id is not None: + selector['searchParameters'].append({ + 'xsi_type': 'SeedAdGroupIdSearchParameter', + 'adGroupId': ad_group_id + }) + + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr( + attribute['value'], 'value', '0') + print ('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201806/remarketing/__init__.py b/examples/adwords/v201806/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201806/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201806/remarketing/add_audience.py b/examples/adwords/v201806/remarketing/add_audience.py new file mode 100755 index 00000000..ba6be197 --- /dev/null +++ b/examples/adwords/v201806/remarketing/add_audience.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201806') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201806') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + user_list_result = user_list_service.mutate(operations) + + # Capture the ID(s) of the conversion. + if 'value' in user_list_result: + conversion_ids = [] + for user_list in user_list_result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + # Create query. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'GoogleGlobalSiteTag', 'GoogleEventSnippet') + .Where('Id').In(*conversion_ids) + .Limit(0, PAGE_SIZE) + .Build()) + + conversions_map = {} + + # Get all conversion trackers. + for page in query.Pager(conversion_tracker_service): + if 'entries' in page: + for conversion_tracker in page['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in user_list_result['value']: + print ('User list with name "%s" and ID "%s" was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print ('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/add_conversion_tracker.py b/examples/adwords/v201806/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..83e4e38d --- /dev/null +++ b/examples/adwords/v201806/remarketing/add_conversion_tracker.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201806') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/add_conversion_trackers.py b/examples/adwords/v201806/remarketing/add_conversion_trackers.py new file mode 100755 index 00000000..c66a29a7 --- /dev/null +++ b/examples/adwords/v201806/remarketing/add_conversion_trackers.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds AdWords conversion trackers. + +Adds an AdWords conversion tracker and an upload conversion tracker. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201806') + + # Create an AdWords conversion tracker. + adwords_conversion_tracker = { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'name': 'Upload Conversion #%s' % uuid.uuid4(), + # Optional fields. + # Set an appropriate category. This will be set to DEFAULT if not + # specified. + 'category': 'LEAD', + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90', + # Set the default currency code to use for conversions that do + # not specify a conversion currency. This must be an ISO 4217 3-character + # code such as "EUR" or "USD". + # If this field is not set, AdWords will use the account's currency. + 'defaultRevenueCurrencyCode': 'EUR', + # Set the default revenue value to use for conversions that do not specify + # a converison value. Note that this value should NOT be in micros. + 'defaultRevenueValue': '2.50', + # To upload fractional conversion credits, mark the upload conversion as + # externally attributed. To learn more about importing externally + # attributed conversions, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'isExternallyAttributed': 'true' + } + + # Construct operations. + operations = [{ + 'operator': 'ADD', + 'operand': conversion_tracker + } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] + + # Add the conversions. + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion with ID "%d", name "%s", status "%s", and category ' + '"%s" was added.' + % (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + if (conversion_tracker['ConversionTracker.Type'] + == 'AdWordsConversionTracker'): + print ('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print ('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/add_crm_based_user_list.py b/examples/adwords/v201806/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..6569c528 --- /dev/null +++ b/examples/adwords/v201806/remarketing/add_crm_based_user_list.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201806') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # CRM-based user lists can use a membershipLifeSpan of 10000 to indicate + # unlimited; otherwise normal values apply. + 'membershipLifeSpan': 30, + 'uploadKeyType': 'CONTACT_INFO' + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + + emails = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] + + # Add address info. + members.append({ + 'addressInfo': { + # First and last name must be normalized and hashed. + 'hashedFirstName': NormalizeAndSHA256('John'), + 'hashedLastName': NormalizeAndSHA256('Doe'), + # Country code and zip code are sent in plaintext. + 'countryCode': 'US', + 'zipCode': '10001' + } + }) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'membersList': members + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def NormalizeAndSHA256(s): + """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. + + Args: + s: The string to perform this operation on. + + Returns: + A normalized and SHA-256 hashed string. + """ + return hashlib.sha256(s.strip().lower()).hexdigest() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201806/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..8efdfbe4 --- /dev/null +++ b/examples/adwords/v201806/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201806') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords knows how to apply the + # rules. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ], + # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF + # means 'at least one item in each rule item group must match', and DNF + # means 'at least one entire rule item group must match'. + # DateSpecificRuleUserList only supports DNF. You can also omit the rule + # type altogether to default to DNF. + 'ruleType': 'DNF' + } + + # Third and fourth rule item groups. + # Visitors of a page who visited another page. + site1_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example1' + } + } + site2_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example2' + } + } + + # Create two rules to show that a visitor browsed two sites. + user_visited_site1_rule = { + 'groups': [{ + 'items': [site1_rule_item] + }] + } + + user_visited_site2_rule = { + 'groups': [{ + 'items': [site2_rule_item] + }] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule, + # Optional: Set the populationStatus to REQUESTED to include past users in + # the user list. + 'prepopulationStatus': 'REQUESTED' + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create the user list for "Visitors of a page who did visit another page". + # To create a user list for "Visitors of a page who did not visit another + # page", change the ruleOperator from AND to AND_NOT. + combined_user_list = { + 'xsi_type': 'CombinedRuleUserList', + 'name': 'Combined rule user lst create at ${creation_time}', + 'description': 'Users who visited two sites.', + 'leftOperand': user_visited_site1_rule, + 'rightOperand': user_visited_site2_rule, + 'ruleOperator': 'AND' + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list, + combined_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/upload_conversion_adjustments.py b/examples/adwords/v201806/remarketing/upload_conversion_adjustments.py new file mode 100755 index 00000000..a33e8d17 --- /dev/null +++ b/examples/adwords/v201806/remarketing/upload_conversion_adjustments.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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. + +"""Imports conversion adjustments for conversions that already exist. + +To set up a conversion tracker, run the add_conversion_tracker.py example. + +""" + +from googleads import adwords + + +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' + +GCLID = 'INSERT_GCLID_HERE' + +ADJUSTMENT_TYPE = 'INSERT_ADJUSTMENT_TYPE_HERE' + +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' + +ADJUSTMENT_TIME = 'INSERT_ADJUSTMENT_TIME_HERE' + +ADJUSTED_VALUE = 'INSERT_ADJUST_VALUE_HERE' + + +def main(client, conversion_name, gclid, adjustment_type, conversion_time, + adjustment_time, adjusted_value): + # Initialize appropriate services. + offline_conversion_service = client.GetService( + 'OfflineConversionAdjustmentFeedService', version='v201806') + + # Associate conversion adjustments with the existing named conversion tracker. + # The GCLID should have been uploaded before with a conversion. + feed = { + 'xsi_type': 'GclidOfflineConversionAdjustmentFeed', + 'conversionName': conversion_name, + 'googleClickId': gclid, + 'conversionTime': conversion_time, + 'adjustmentType': adjustment_type, + 'adjustmentTime': adjustment_time, + 'adjustedValue': adjusted_value + } + + offline_conversion_operation = {'operator': 'ADD', 'operand': feed} + + offline_conversion_response = offline_conversion_service.mutate( + [offline_conversion_operation]) + + new_feed = offline_conversion_response['value'][0] + + print ('Uploaded offline conversion adjustment value of "%s" for Google ' + 'Click ID "%s"' % (new_feed['adjustedValue'], + new_feed['googleClickId'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, GCLID, ADJUSTMENT_TYPE, CONVERSION_TIME, + ADJUSTMENT_TIME, ADJUSTED_VALUE) diff --git a/examples/adwords/v201806/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201806/remarketing/upload_offline_call_conversions.py new file mode 100755 index 00000000..a35ba52c --- /dev/null +++ b/examples/adwords/v201806/remarketing/upload_offline_call_conversions.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for calls related to ads in your account. + +To set up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CALLER_ID = 'INSERT_CALLER_ID_HERE' +# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats +# For time zones, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +CALL_START_TIME = 'INSERT_CALL_START_TIME' +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, caller_id, call_start_time, conversion_name, conversion_time, + conversion_value): + # Initialize appropriate services. + occ_feed_service = client.GetService( + 'OfflineCallConversionFeedService', version='v201806') + + # Associate offline call conversions with the existing named conversion + # tracker. If this tracker was newly created, it may be a few hours before it + # can accept conversions. + feed = { + 'callerId': caller_id, + 'callStartTime': call_start_time, + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + } + + occ_operations = [{'operator': 'ADD', 'operand': feed}] + + occ_response = occ_feed_service.mutate(occ_operations) + values = occ_response['value'] + + if values: + for occ_feed in values: + print ('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + else: + print 'No offline call conversions were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, + CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201806/remarketing/upload_offline_conversions.py b/examples/adwords/v201806/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..71a5ba5a --- /dev/null +++ b/examples/adwords/v201806/remarketing/upload_offline_conversions.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201806') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id, + # Optional: To upload fractional conversion credits, set the external + # attribution model and credit. To use this feature, your conversion + # tracker should be marked as externally attributed. To learn more about + # importing externally attributed conversins, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'externalAttributionCredit': 0.3, + # 'externalAttributionModel': 'Linear' + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201806/remarketing/upload_offline_data.py b/examples/adwords/v201806/remarketing/upload_offline_data.py new file mode 100755 index 00000000..549fecc5 --- /dev/null +++ b/examples/adwords/v201806/remarketing/upload_offline_data.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 shows how to upload offline data for store sales transactions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import datetime +import hashlib + +from googleads import adwords +import pytz + + +_DT_FORMAT = '%Y%m%d %H%M%S' +# User identifier types whose values must be hashed. +_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', + 'HASHED_LAST_NAME', 'HASHED_PHONE') +# The timezone to be used in this example. For valid timezone IDs, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +_TIMEZONE = pytz.timezone('America/New_York') +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Insert email addresses below for creating user identifiers. +EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] +# The external upload ID can be any number that you use to keep track of your +# uploads. +EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' +# Store sales upload common metadata types +METADATA_TYPE_1P = 'FirstPartyUploadMetadata' +METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' +# Set the below constant to METADATA_TYPE_3P if uploading third-party data. +STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P +# The three constants below are needed when uploading third-party data. They +# are not used when uploading first-party data. +# Advertiser upload time to partner. +# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, +# see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' +# Indicates the version of the bridge map. +BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' +# The ID of the third party uploading the transaction feed. +PARTNER_ID = 'INSERT_PARTNER_ID_HERE' + + +def main(client, conversion_name, external_upload_id, + store_sales_upload_common_metadata_type, email_addresses, + advertiser_upload_time=None, bridge_map_version_id=None, + partner_id=None): + # Set partial failure to True since this example demonstrates how to handle + # partial errors. + client.partial_failure = True + # Initialize appropriate services. + offline_data_upload_service = client.GetService( + 'OfflineDataUploadService', version='v201806') + + # Create the first offline data for upload. + # This transaction occurred 7 days ago with an amount of $200 USD. + transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=7)) + offline_data_1 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[0]), + _CreateUserIdentifier(identifier_type='STATE', value='New York') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_1), + 'transactionAmount': { + 'currencyCode': 'USD', + 'money': { + 'microAmount': 200000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create the second offline data for upload. + # This transaction occurred 14 days ago with amount of 450 EUR. + transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=14)) + offline_data_2 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[1]), + _CreateUserIdentifier(identifier_type='STATE', value='California') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_2), + 'transactionAmount': { + 'currencyCode': 'EUR', + 'money': { + 'microAmount': 450000000 + } + }, + 'conversionName': conversion_name + } + } + + # Set the type and metadata of this upload. + upload_metadata = { + 'StoreSalesUploadCommonMetadata': { + 'xsi_type': store_sales_upload_common_metadata_type, + 'loyaltyRate': 1.0, + 'transactionUploadRate': 1.0, + } + } + + if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: + upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' + elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: + upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' + upload_metadata['StoreSalesUploadCommonMetadata'].update({ + 'advertiserUploadTime': advertiser_upload_time, + 'validTransactionRate': 1.0, + 'partnerMatchRate': 1.0, + 'partnerUploadRate': 1.0, + 'bridgeMapVersionId': bridge_map_version_id, + 'partnerId': partner_id + }) + else: + raise ValueError('Unknown metadata type.') + + # Create offline data upload + offline_data_upload = { + 'externalUploadId': external_upload_id, + 'offlineDataList': [offline_data_1, offline_data_2], + # Set the type of this upload. + 'uploadType': upload_type, + 'uploadMetadata': upload_metadata + } + + # Create an offline data upload operation. + operations = [{ + 'operator': 'ADD', + 'operand': offline_data_upload + }] + + # Upload offline data on the server and print the result. + result = offline_data_upload_service.mutate(operations) + offline_data_upload = result['value'][0] + + print ('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) + + # Print any partial data errors from the response. + if result['partialFailureErrors']: + for api_error in result['partialFailureErrors']: + # Get the index of the failed operation from the error's field path + # elements. + operation_index = _GetFieldPathElementIndex(api_error, 'operations') + + if operation_index: + failed_offline_data_upload = operations[operation_index]['operand'] + # Get the index of the entry in the offline data list from the error's + # field path elements. + offline_data_list_index = _GetFieldPathElementIndex( + api_error, 'offlineDataList') + print ('Offline data list entry "%d" in operation "%d" with external ' + 'upload ID "%d" and type "%s" has triggered failure for the ' + 'following reason: "%s"' % ( + offline_data_list_index, operation_index, + failed_offline_data_upload['externalUploadId'], + failed_offline_data_upload['uploadType'], + api_error['errorString'])) + else: + print ('A failure has occurred for the following reason: "%s".' % ( + api_error['errorString'])) + + +def _CreateUserIdentifier(identifier_type=None, value=None): + """Creates a user identifier from the specified type and value. + + Args: + identifier_type: a str specifying the type of user identifier. + value: a str value of the identifier; to be hashed using SHA-256 if needed. + + Returns: + A dict specifying a user identifier, with a value hashed using SHA-256 if + needed. + """ + if identifier_type in _HASHED_IDENTIFIER_TYPES: + # If the user identifier type is a hashed type, normalize and hash the + # value. + value = hashlib.sha256(value.strip().lower()).hexdigest() + + user_identifier = { + 'userIdentifierType': identifier_type, + 'value': value + } + + return user_identifier + + +def _GetFieldPathElementIndex(api_error, field): + """Retrieve the index of a given field in the api_error's fieldPathElements. + + Args: + api_error: a dict containing a partialFailureError returned from the AdWords + API. + field: a str field for which this determines the index in the api_error's + fieldPathElements. + + Returns: + An int index of the field path element, or None if the specified field can't + be found in the api_error. + """ + field_path_elements = api_error['fieldPathElements'] + + if field_path_elements: + found_index = [field_path_element['index'] + for field_path_element in field_path_elements + if field_path_element['field'] == field] + if found_index: + return found_index + + return None + + +def _GetFormattedDateTime(dt): + """Formats the given datetime and timezone for use with AdWords. + + Args: + dt: a datetime instance. + + Returns: + A str representation of the datetime in the correct format for AdWords. + """ + return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, + STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, + ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201806/reporting/__init__.py b/examples/adwords/v201806/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201806/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..6969c22a --- /dev/null +++ b/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import StringIO +import sys + +from googleads import adwords + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201806') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_selector.py new file mode 100755 index 00000000..5232bbbc --- /dev/null +++ b/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_selector.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import StringIO +import sys +from googleads import adwords + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201806') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..3082b800 --- /dev/null +++ b/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201806') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_selector.py new file mode 100755 index 00000000..1650fe9b --- /dev/null +++ b/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_selector.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201806') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201806/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..14eed254 --- /dev/null +++ b/examples/adwords/v201806/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import sys +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201806') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + # You can provide a file object to write the output to. For this + # demonstration we use sys.stdout to write the report to the screen. + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', sys.stdout, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201806/reporting/download_criteria_report_with_selector.py new file mode 100755 index 00000000..17a8ecbc --- /dev/null +++ b/examples/adwords/v201806/reporting/download_criteria_report_with_selector.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import sys +from googleads import adwords + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201806') + + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201806/reporting/get_report_fields.py b/examples/adwords/v201806/reporting/get_report_fields.py new file mode 100755 index 00000000..121144ed --- /dev/null +++ b/examples/adwords/v201806/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201806') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type "%s" contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201806/reporting/parallel_report_download.py b/examples/adwords/v201806/reporting/parallel_report_download.py new file mode 100755 index 00000000..a4d3fbad --- /dev/null +++ b/examples/adwords/v201806/reporting/parallel_report_download.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import multiprocessing +import os +from Queue import Empty +import time + +import googleads.adwords +import googleads.errors + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def _DownloadReport(process_id, report_download_directory, customer_id, + report_definition): + """Helper function used by ReportWorker to download customer report. + + Note that multiprocessing differs between Windows / Unix environments. A + Process or its subclasses in Windows must be serializable with pickle, but + that is not possible for AdWordsClient or ReportDownloader. This top-level + function is used as a work-around for Windows support. + + Args: + process_id: The PID of the process downloading the report. + report_download_directory: A string indicating the directory where you + would like to download the reports. + customer_id: A str AdWords customer ID for which the report is being + downloaded. + report_definition: A dict containing the report definition to be used. + + Returns: + A tuple indicating a boolean success/failure status, and dict request + context. + """ + report_downloader = (googleads.adwords.AdWordsClient.LoadFromStorage() + .GetReportDownloader()) + + filepath = os.path.join(report_download_directory, + 'adgroup_%d.csv' % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (process_id, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + report_downloader.DownloadReport( + report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError as e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + def __init__(self, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = _DownloadReport(self.ident, self.report_download_directory, + customer_id, self.report_definition) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + Raises: + Exception: if no CustomerIds could be found. + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201806') + + offset = 0 + + # Get the account hierarchy for this account. + selector = { + 'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201806/shopping/__init__.py b/examples/adwords/v201806/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201806/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201806/shopping/add_product_partition_tree.py b/examples/adwords/v201806/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..918bbce1 --- /dev/null +++ b/examples/adwords/v201806/shopping/add_product_partition_tree.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201806') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/shopping/add_product_scope.py b/examples/adwords/v201806/shopping/add_product_scope.py new file mode 100755 index 00000000..17da9cdc --- /dev/null +++ b/examples/adwords/v201806/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201806') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/shopping/add_shopping_campaign.py b/examples/adwords/v201806/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..602e5e5f --- /dev/null +++ b/examples/adwords/v201806/shopping/add_shopping_campaign.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +# If set to true, a default partition will be created. If running the +# add_product_partition_tree.py example right after this example, make +# sure this stays set to false. +CREATE_DEFAULT_PARTITION = False +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id, create_default_partition): + campaign_service = client.GetService('CampaignService', version='v201806') + ad_group_service = client.GetService('AdGroupService', version='v201806') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + ad_group = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': ad_group + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': ad_group_id, + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201806') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + }, + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 500000 + } + }] + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201806/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201806/shopping/add_shopping_campaign_for_showcase_ads.py new file mode 100755 index 00000000..52aaaeb8 --- /dev/null +++ b/examples/adwords/v201806/shopping/add_shopping_campaign_for_showcase_ads.py @@ -0,0 +1,401 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds a Shopping campaign for Showcase ads. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import uuid + +from googleads import adwords +from googleads import errors + + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' +EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' +COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + # Note: Showcase ads require that the campaign has a ManualCpc + # BiddingStrategyConfiguration. + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, budget_id, merchant_id, expanded_image_filepath, + collapsed_image_filepath): + try: + # Create the Shopping Campaign + campaign = CreateShoppingCampaign(client, budget_id, merchant_id) + + # Create the AdGroup + adgroup = CreateAdGroup(client, campaign['id']) + + # Create a Showcase Ad + CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath) + + product_partition_tree = CreateProductPartition(client, adgroup['id']) + print 'Final tree:\n%s' % product_partition_tree + except errors.GoogleAdsServerFault: + print 'Failed to create shopping campaign for showcase ads.' + raise + + +def CreateShoppingCampaign(client, budget_id, merchant_id): + """Creates a shopping campaign with the given budget and merchant IDs. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + shopping campaign. + + Returns: + The created Shopping Campaign as a sudsobject. + """ + campaign_service = client.GetService('CampaignService', 'v201806') + + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + campaign = campaign_service.mutate(campaign_operations)['value'][0] + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + return campaign + + +def CreateAdGroup(client, campaign_id): + """Creates an AdGroup for the given shopping campaign ID. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a shopping campaign. + + Returns: + The created AdGroup as a sudsobject. + """ + ad_group_service = client.GetService('AdGroupService', 'v201806') + + adgroup = { + # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS + 'adGroupType': 'SHOPPING_SHOWCASE_ADS', + 'campaignId': campaign_id, + 'name': 'AdGroup #%s' % uuid.uuid4(), + # REQUIRED: Set the ad group's bidding strategy configuration. + 'biddingStrategyConfiguration': { + # Showcase ads require either ManualCpc or EnhancedCpc. + 'biddingStrategyType': 'MANUAL_CPC', + # Optional: Set the bids + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 100000 + } + }] + } + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) + + return adgroup + + +def CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath): + """Creates a showcase add for the given AdGroup with the given images. + + Args: + client: an AdWordsClient instance. + adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + expanded_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's expandedImage. + collapsed_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's collapsedImage. + + Returns: + The created Showcase Ad as a sudsobject. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201806') + + showcase_ad = { + 'adGroupId': adgroup['id'], + 'ad': { + 'xsi_type': 'ShowcaseAd', + 'Ad.Type': 'ShowcaseAd', + # Required: set the ad's name, final URLs, and display URL. + 'name': 'Showcase ad #%s' % uuid.uuid4(), + 'finalUrls': 'http://example.com/showcase', + 'displayUrl': 'example.com', + # Required: Set the ad's expanded image. + 'expandedImage': { + 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] + }, + # Optional: Set the collapsed image. + 'collapsedImage': { + 'mediaId': + UploadImage(client, collapsed_image_filepath)['mediaId'] + } + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': showcase_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] + + print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + + return showcase_ad + + +def UploadImage(client, filepath): + """Uploads a .jpg image with the given filepath via the AdWords MediaService. + + Args: + client: an AdWordsClient instance. + filepath: a str filepath to the .jpg file to be uploaded. + + Returns: + The created Image as a sudsobject. + """ + media_service = client.GetService('MediaService', 'v201806') + + with open(filepath, 'rb') as image_handle: + image_data = image_handle.read().decode('utf-8') + + image = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + + image = media_service.upload(image)[0] + + return image + + +def CreateProductPartition(client, adgroup_id): + """Creates a ProductPartition tree for the given AdGroup ID. + + Args: + client: an AdWordsClient instance. + adgroup_id: a str AdGroup ID. + + Returns: + The ProductPartition tree as a sudsobject. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + 'v201806') + helper = ProductPartitionHelper(adgroup_id) + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition) + helper.CreateUnit(root, used_product_canonical_condition) + helper.CreateUnit(root, other_product_canonical_condition) + + result = ad_group_criterion_service.mutate(helper.operations) + return result['value'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, + COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201806/shopping/get_product_category_taxonomy.py b/examples/adwords/v201806/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..1f456086 --- /dev/null +++ b/examples/adwords/v201806/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201806') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/targeting/__init__.py b/examples/adwords/v201806/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201806/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201806/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201806/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..969b36ff --- /dev/null +++ b/examples/adwords/v201806/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201806') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201806/targeting/add_customer_negative_criteria.py b/examples/adwords/v201806/targeting/add_customer_negative_criteria.py new file mode 100755 index 00000000..b7325473 --- /dev/null +++ b/examples/adwords/v201806/targeting/add_customer_negative_criteria.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds various types of negative criteria to a customer. + +These criteria will be applied to all campaigns for the customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_negative_criterion_service = client.GetService( + 'CustomerNegativeCriterionService', version='v201806') + + criteria = [ + # Exclude tragedy & conflict content. + { + 'xsi_type': 'ContentLabel', + 'contentLabelType': 'TRAGEDY' + }, + # Exclude a specific placement. + { + 'xsi_type': 'Placement', + 'url': 'http://www.example.com' + } + # Additional criteria types are available for this service. See the types + # listed under Criterion here: + # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion + ] + + # Create operations to add each of the criteria above. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'criterion': criterion + } + } for criterion in criteria] + + # Make the mutate request. + result = customer_negative_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for negative_criterion in result['value']: + print ('Customer negative criterion with criterion ID "%s", and type "%s" ' + 'was added.' % (negative_criterion['criterion']['id'], + negative_criterion['criterion']['type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201806/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..64da5eab --- /dev/null +++ b/examples/adwords/v201806/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201806') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type "%s" was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201806/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..85cbc6d3 --- /dev/null +++ b/examples/adwords/v201806/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201806') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201806/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..6d626eaa --- /dev/null +++ b/examples/adwords/v201806/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201806') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name "%s" and ID "%s" was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name "%s", ID "%s", and country code "%s" was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201806/targeting/lookup_location.py b/examples/adwords/v201806/targeting/lookup_location.py new file mode 100755 index 00000000..decb4f35 --- /dev/null +++ b/examples/adwords/v201806/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201806') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/googleads/adwords.py b/googleads/adwords.py index 598dcc59..222020cc 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -143,6 +143,62 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201806': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdService': 'cm', + 'AdwordsUserListService': 'rm', + 'AssetService': 'cm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignBidModifierService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignGroupPerformanceTargetService': 'cm', + 'CampaignGroupService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomAffinityService': 'rm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerNegativeCriterionService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'FeedItemService': 'cm', + 'FeedItemTargetService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineCallConversionFeedService': 'cm', + 'OfflineConversionAdjustmentFeedService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'OfflineDataUploadService': 'rm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } @@ -899,7 +955,7 @@ def _GenerateRawRequestXML(self, operations): Returns: An element containing the raw XML of the request to the given service - that would execute the given operations. + that would execute the given operations Raises: KeyError: If the given operation type is not supported. diff --git a/googleads/common.py b/googleads/common.py index 45edc06b..61c15360 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '12.0.0' +VERSION = '12.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' @@ -1260,45 +1260,92 @@ def _PackArgumentsHelper(self, elem, data, set_type_attrs): if self._packer: data = self._packer.Pack(data) - if isinstance(data, dict): # Dict so it's a complex type. - xsi_type = data.get('xsi_type') - if xsi_type: # This has a type override so look it up. - elem_type = None - last_exception = None - for ns_prefix in self.zeep_client.wsdl.types.prefix_map.values(): - try: - elem_type = self.zeep_client.get_type( - '{%s}%s' % (ns_prefix, xsi_type)) - except zeep.exceptions.LookupError as e: - last_exception = e - continue - break - if not elem_type: - raise last_exception + if isinstance(data, dict): # Instantiate from simple Python dict + # See if there is a manually specified derived type. + type_override = data.get('xsi_type') + if type_override: + elem_type = self._DiscoverElementTypeFromLocalname(type_override) else: elem_type = elem.type - elem_arguments = dict(elem_type.elements) - # A post order traversal of the original data, need to instantiate from - # the bottom up. - instantiated_arguments = { - k: self._PackArgumentsHelper(elem_arguments[k], v, set_type_attrs) - for k, v in data.iteritems() if k != 'xsi_type'} - if set_type_attrs: - found_type_attr = next((e_name for e_name, _ in elem_type.elements - if e_name.endswith('.Type')), None) - if found_type_attr: - instantiated_arguments[found_type_attr] = xsi_type - # Now go back through the tree instantiating SOAP types as we go. - return elem_type(**instantiated_arguments) + + data_formatted = data.iteritems() + packed_result = self._CreateComplexTypeFromData( + elem_type, type_override is not None, data_formatted, set_type_attrs) + elif isinstance(data, zeep.xsd.CompoundValue): + # Here the data is already a SOAP element but we still need to look + # through it in case it has been edited with Python dicts. + elem_type = data._xsd_type + data_formatted = zip(dir(data), [data[k] for k in dir(data)]) + packed_result = self._CreateComplexTypeFromData( + elem_type, False, data_formatted, set_type_attrs) elif isinstance(data, (list, tuple)): - return [self._PackArgumentsHelper(elem, item, set_type_attrs) - for item in data] + packed_result = [self._PackArgumentsHelper(elem, item, set_type_attrs) + for item in data] else: if elem.type.name == 'base64Binary' and self._IsBase64(data): _logger.warn('Passing data to base64 field %s that may ' 'already be encoded. Do not pre-encode base64 ' 'fields with zeep.', elem.name) - return data + packed_result = data + + return packed_result + + def _DiscoverElementTypeFromLocalname(self, type_localname): + """Searches all namespaces for a type by name. + + Args: + type_localname: The name of the type. + + Returns: + A fully qualified SOAP type with the specified name. + + Raises: + A zeep.exceptions.LookupError if the type cannot be found in any + namespace. + """ + elem_type = None + last_exception = None + for ns_prefix in self.zeep_client.wsdl.types.prefix_map.values(): + try: + elem_type = self.zeep_client.get_type( + '{%s}%s' % (ns_prefix, type_localname)) + except zeep.exceptions.LookupError as e: + last_exception = e + continue + break + if not elem_type: + raise last_exception + return elem_type + + def _CreateComplexTypeFromData( + self, elem_type, type_is_override, data, set_type_attrs): + """Initialize a SOAP element with specific data. + + Args: + elem_type: The type of the element to create. + type_is_override: A boolean specifying if the type is being overridden. + data: The data to hydrate the type with. + set_type_attrs: A boolean indicating whether or not attributes that end + in .Type should be set. This is only necessary for batch job service. + + Returns: + An fully initialized SOAP element. + """ + elem_arguments = dict(elem_type.elements) + + # A post order traversal of the original data, need to instantiate from + # the bottom up. + instantiated_arguments = { + k: self._PackArgumentsHelper(elem_arguments[k], v, set_type_attrs) + for k, v in data if k != 'xsi_type'} + if set_type_attrs: + found_type_attr = next((e_name for e_name, _ in elem_type.elements + if e_name.endswith('.Type')), None) + if found_type_attr and type_is_override: + instantiated_arguments[found_type_attr] = elem_type.qname.localname + # Now go back through the tree instantiating SOAP types as we go. + return elem_type(**instantiated_arguments) + def _GetZeepFormattedSOAPHeaders(self): """Returns a dict with SOAP headers in the right format for zeep.""" diff --git a/tests/common_test.py b/tests/common_test.py index ef5d276b..279fcccc 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -1136,6 +1136,26 @@ def testPackArgumentsWithCustomTypeAndList(self): number_type = self.zeep_client.zeep_client.get_type('ns0:NumberValue') self.assertEqual(type(number_value), number_type._value_class) + def testPackArgumentsLooksThroughSoapElements(self): + map_type = self.zeep_client.zeep_client.get_type('ns0:String_ValueMapEntry') + string_type = self.zeep_client.zeep_client.get_type('ns0:TextValue') + + element = self.zeep_client.zeep_client.get_type('ns0:ReportQuery')() + element.statement = self.zeep_client.zeep_client.get_type('ns0:Statement')() + element.statement.values = [{ + 'key': 'Key1', + 'value': { + 'xsi_type': 'NumberValue', + 'value': 10 + } + }, map_type(key='Key2', value=string_type(value='abc'))] + + result = self.zeep_client._PackArguments( + 'runReportJob', [{'reportQuery': element}]) + result_values = result[0].reportQuery.statement.values + self.assertIsInstance(result_values[0], zeep.xsd.CompoundValue) + self.assertIsInstance(result_values[1], zeep.xsd.CompoundValue) + def testPackArgumentsWithCustomPacker(self): class CustomPacker(googleads.common.SoapPacker): From 901f22e0693e80a5faf8fc32c6c1a63f988b6561 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Thu, 7 Jun 2018 11:23:54 -0400 Subject: [PATCH 111/180] Commiting latest changes. From fb54ae052f3823e7acb76f88def3dcec4228ebf8 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 19 Jun 2018 10:40:01 -0400 Subject: [PATCH 112/180] Committing latest changes. --- ChangeLog | 3 +++ .../activity_group_service/get_active_activity_groups.py | 2 +- .../v201711/activity_group_service/get_all_activity_groups.py | 2 +- .../v201711/activity_group_service/update_activity_groups.py | 2 +- .../dfp/v201711/activity_service/get_active_activities.py | 2 +- examples/dfp/v201711/activity_service/get_all_activities.py | 2 +- examples/dfp/v201711/activity_service/update_activities.py | 2 +- .../audience_segment_service/get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../audience_segment_service/update_audience_segments.py | 2 +- examples/dfp/v201711/base_rate_service/get_all_base_rates.py | 2 +- .../v201711/base_rate_service/get_base_rates_for_rate_card.py | 2 +- examples/dfp/v201711/base_rate_service/update_base_rates.py | 2 +- .../cdn_configuration_service/get_all_cdn_configurations.py | 2 +- examples/dfp/v201711/company_service/get_advertisers.py | 2 +- examples/dfp/v201711/company_service/get_all_companies.py | 2 +- examples/dfp/v201711/company_service/update_companies.py | 2 +- examples/dfp/v201711/contact_service/get_all_contacts.py | 2 +- .../dfp/v201711/contact_service/get_uninvited_contacts.py | 2 +- examples/dfp/v201711/contact_service/update_contacts.py | 2 +- .../get_all_content_metadata_key_hierarchies.py | 2 +- examples/dfp/v201711/content_service/get_all_content.py | 2 +- examples/dfp/v201711/creative_service/get_all_creatives.py | 2 +- examples/dfp/v201711/creative_service/get_image_creatives.py | 2 +- examples/dfp/v201711/creative_service/update_creatives.py | 2 +- .../dfp/v201711/creative_set_service/get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../dfp/v201711/creative_set_service/update_creative_set.py | 2 +- .../creative_template_service/get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../creative_wrapper_service/deactivate_creative_wrapper.py | 2 +- .../creative_wrapper_service/get_active_creative_wrappers.py | 2 +- .../creative_wrapper_service/get_all_creative_wrappers.py | 2 +- .../creative_wrapper_service/update_creative_wrappers.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../dfp/v201711/custom_field_service/get_all_custom_fields.py | 2 +- .../custom_field_service/get_custom_fields_for_line_items.py | 2 +- .../custom_targeting_service/delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 2 +- .../get_all_custom_targeting_keys_and_values.py | 4 ++-- .../get_predefined_custom_targeting_keys_and_values.py | 4 ++-- .../custom_targeting_service/update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../v201711/exchange_rate_service/get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../v201711/exchange_rate_service/update_exchange_rates.py | 2 +- examples/dfp/v201711/inventory_service/archive_ad_units.py | 2 +- .../dfp/v201711/inventory_service/get_ad_unit_hierarchy.py | 2 +- examples/dfp/v201711/inventory_service/get_all_ad_units.py | 2 +- .../dfp/v201711/inventory_service/get_top_level_ad_units.py | 2 +- examples/dfp/v201711/inventory_service/update_ad_units.py | 2 +- examples/dfp/v201711/label_service/deactivate_labels.py | 2 +- examples/dfp/v201711/label_service/get_active_labels.py | 2 +- examples/dfp/v201711/label_service/get_all_labels.py | 2 +- examples/dfp/v201711/label_service/update_labels.py | 2 +- .../deactivate_licas.py | 2 +- .../line_item_creative_association_service/get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../line_item_creative_association_service/update_licas.py | 2 +- examples/dfp/v201711/line_item_service/activate_line_items.py | 2 +- examples/dfp/v201711/line_item_service/get_all_line_items.py | 2 +- .../line_item_service/get_line_items_that_need_creatives.py | 2 +- .../line_item_service/get_recently_updated_line_items.py | 2 +- examples/dfp/v201711/line_item_service/pause_line_items.py | 2 +- examples/dfp/v201711/line_item_service/update_line_items.py | 2 +- .../live_stream_event_service/activate_live_stream_events.py | 2 +- .../live_stream_event_service/get_all_live_stream_events.py | 2 +- .../live_stream_event_service/update_live_stream_events.py | 2 +- .../dfp/v201711/native_style_service/get_all_native_styles.py | 2 +- examples/dfp/v201711/order_service/approve_orders.py | 2 +- examples/dfp/v201711/order_service/get_all_orders.py | 2 +- .../dfp/v201711/order_service/get_orders_starting_soon.py | 2 +- examples/dfp/v201711/order_service/update_orders.py | 2 +- examples/dfp/v201711/package_service/get_all_packages.py | 2 +- .../dfp/v201711/package_service/get_in_progress_packages.py | 2 +- examples/dfp/v201711/placement_service/create_placements.py | 2 +- .../dfp/v201711/placement_service/get_active_placements.py | 2 +- examples/dfp/v201711/placement_service/get_all_placements.py | 2 +- .../dfp/v201711/premium_rate_service/get_all_premium_rates.py | 2 +- .../premium_rate_service/get_premium_rates_for_rate_card.py | 2 +- .../dfp/v201711/premium_rate_service/update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 2 +- .../get_product_package_items_for_product_package.py | 2 +- .../product_package_service/get_active_product_packages.py | 2 +- .../product_package_service/get_all_product_packages.py | 2 +- examples/dfp/v201711/product_service/get_all_products.py | 2 +- .../product_service/get_products_for_product_template.py | 2 +- examples/dfp/v201711/product_service/update_products.py | 2 +- .../product_template_service/activate_product_templates.py | 2 +- .../product_template_service/get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../product_template_service/update_product_templates.py | 2 +- .../proposal_line_item_service/archive_proposal_line_items.py | 2 +- .../proposal_line_item_service/get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../proposal_line_item_service/update_proposal_line_items.py | 2 +- examples/dfp/v201711/proposal_service/get_all_proposals.py | 2 +- .../proposal_service/get_proposals_pending_approval.py | 2 +- .../dfp/v201711/proposal_service/request_buyers_acceptance.py | 2 +- .../v201711/proposal_service/submit_proposals_for_approval.py | 2 +- examples/dfp/v201711/proposal_service/update_proposals.py | 2 +- examples/dfp/v201711/rate_card_service/get_all_rate_cards.py | 2 +- .../v201711/rate_card_service/get_marketplace_rate_cards.py | 2 +- ...onciliation_line_item_reports_for_reconciliation_report.py | 2 +- ..._reconciliation_order_reports_for_reconciliation_report.py | 2 +- ...et_reconciliation_report_rows_for_reconciliation_report.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- .../get_reconciliation_report_for_last_billing_period.py | 2 +- .../v201711/report_service/run_report_with_custom_fields.py | 2 +- examples/dfp/v201711/report_service/run_saved_query.py | 2 +- .../approve_all_suggested_ad_units.py | 2 +- .../suggested_ad_unit_service/get_all_suggested_ad_units.py | 2 +- .../get_highly_requested_suggested_ad_units.py | 2 +- examples/dfp/v201711/team_service/get_all_teams.py | 2 +- examples/dfp/v201711/team_service/update_teams.py | 2 +- examples/dfp/v201711/user_service/get_all_users.py | 2 +- .../dfp/v201711/user_service/get_user_by_email_address.py | 2 +- examples/dfp/v201711/user_service/update_users.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py | 2 +- .../get_workflow_external_condition_requests.py | 2 +- .../trigger_workflow_external_condition_requests.py | 2 +- .../activity_group_service/get_active_activity_groups.py | 2 +- .../v201802/activity_group_service/get_all_activity_groups.py | 2 +- .../v201802/activity_group_service/update_activity_groups.py | 2 +- .../dfp/v201802/activity_service/get_active_activities.py | 2 +- examples/dfp/v201802/activity_service/get_all_activities.py | 2 +- examples/dfp/v201802/activity_service/update_activities.py | 2 +- .../audience_segment_service/get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../audience_segment_service/update_audience_segments.py | 2 +- examples/dfp/v201802/base_rate_service/get_all_base_rates.py | 2 +- .../v201802/base_rate_service/get_base_rates_for_rate_card.py | 2 +- examples/dfp/v201802/base_rate_service/update_base_rates.py | 2 +- .../cdn_configuration_service/get_all_cdn_configurations.py | 2 +- examples/dfp/v201802/company_service/get_advertisers.py | 2 +- examples/dfp/v201802/company_service/get_all_companies.py | 2 +- examples/dfp/v201802/company_service/update_companies.py | 2 +- examples/dfp/v201802/contact_service/get_all_contacts.py | 2 +- .../dfp/v201802/contact_service/get_uninvited_contacts.py | 2 +- examples/dfp/v201802/contact_service/update_contacts.py | 2 +- .../get_all_content_metadata_key_hierarchies.py | 2 +- examples/dfp/v201802/content_service/get_all_content.py | 2 +- examples/dfp/v201802/creative_service/get_all_creatives.py | 2 +- examples/dfp/v201802/creative_service/get_image_creatives.py | 2 +- examples/dfp/v201802/creative_service/update_creatives.py | 2 +- .../dfp/v201802/creative_set_service/get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../dfp/v201802/creative_set_service/update_creative_set.py | 2 +- .../creative_template_service/get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../creative_wrapper_service/deactivate_creative_wrapper.py | 2 +- .../creative_wrapper_service/get_active_creative_wrappers.py | 2 +- .../creative_wrapper_service/get_all_creative_wrappers.py | 2 +- .../creative_wrapper_service/update_creative_wrappers.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../dfp/v201802/custom_field_service/get_all_custom_fields.py | 2 +- .../custom_field_service/get_custom_fields_for_line_items.py | 2 +- .../custom_targeting_service/delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 2 +- .../get_all_custom_targeting_keys_and_values.py | 4 ++-- .../get_predefined_custom_targeting_keys_and_values.py | 4 ++-- .../custom_targeting_service/update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../v201802/exchange_rate_service/get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../v201802/exchange_rate_service/update_exchange_rates.py | 2 +- examples/dfp/v201802/inventory_service/archive_ad_units.py | 2 +- .../dfp/v201802/inventory_service/get_ad_unit_hierarchy.py | 2 +- examples/dfp/v201802/inventory_service/get_all_ad_units.py | 2 +- .../dfp/v201802/inventory_service/get_top_level_ad_units.py | 2 +- examples/dfp/v201802/inventory_service/update_ad_units.py | 2 +- examples/dfp/v201802/label_service/deactivate_labels.py | 2 +- examples/dfp/v201802/label_service/get_active_labels.py | 2 +- examples/dfp/v201802/label_service/get_all_labels.py | 2 +- examples/dfp/v201802/label_service/update_labels.py | 2 +- .../deactivate_licas.py | 2 +- .../line_item_creative_association_service/get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../line_item_creative_association_service/update_licas.py | 2 +- examples/dfp/v201802/line_item_service/activate_line_items.py | 2 +- examples/dfp/v201802/line_item_service/get_all_line_items.py | 2 +- .../line_item_service/get_line_items_that_need_creatives.py | 2 +- .../line_item_service/get_recently_updated_line_items.py | 2 +- examples/dfp/v201802/line_item_service/pause_line_items.py | 2 +- examples/dfp/v201802/line_item_service/update_line_items.py | 2 +- .../live_stream_event_service/activate_live_stream_events.py | 2 +- .../live_stream_event_service/get_all_live_stream_events.py | 2 +- .../live_stream_event_service/update_live_stream_events.py | 2 +- .../dfp/v201802/native_style_service/get_all_native_styles.py | 2 +- examples/dfp/v201802/order_service/approve_orders.py | 2 +- examples/dfp/v201802/order_service/get_all_orders.py | 2 +- .../dfp/v201802/order_service/get_orders_starting_soon.py | 2 +- examples/dfp/v201802/order_service/update_orders.py | 2 +- examples/dfp/v201802/package_service/get_all_packages.py | 2 +- .../dfp/v201802/package_service/get_in_progress_packages.py | 2 +- examples/dfp/v201802/placement_service/create_placements.py | 2 +- .../dfp/v201802/placement_service/get_active_placements.py | 2 +- examples/dfp/v201802/placement_service/get_all_placements.py | 2 +- .../dfp/v201802/premium_rate_service/get_all_premium_rates.py | 2 +- .../premium_rate_service/get_premium_rates_for_rate_card.py | 2 +- .../dfp/v201802/premium_rate_service/update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 2 +- .../get_product_package_items_for_product_package.py | 2 +- .../product_package_service/get_active_product_packages.py | 2 +- .../product_package_service/get_all_product_packages.py | 2 +- examples/dfp/v201802/product_service/get_all_products.py | 2 +- .../product_service/get_products_for_product_template.py | 2 +- examples/dfp/v201802/product_service/update_products.py | 2 +- .../product_template_service/activate_product_templates.py | 2 +- .../product_template_service/get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../product_template_service/update_product_templates.py | 2 +- .../proposal_line_item_service/archive_proposal_line_items.py | 2 +- .../proposal_line_item_service/get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../proposal_line_item_service/update_proposal_line_items.py | 2 +- examples/dfp/v201802/proposal_service/get_all_proposals.py | 2 +- .../proposal_service/get_proposals_pending_approval.py | 2 +- .../dfp/v201802/proposal_service/request_buyers_acceptance.py | 2 +- .../v201802/proposal_service/submit_proposals_for_approval.py | 2 +- examples/dfp/v201802/proposal_service/update_proposals.py | 2 +- examples/dfp/v201802/rate_card_service/get_all_rate_cards.py | 2 +- .../v201802/rate_card_service/get_marketplace_rate_cards.py | 2 +- ...onciliation_line_item_reports_for_reconciliation_report.py | 2 +- ..._reconciliation_order_reports_for_reconciliation_report.py | 2 +- ...et_reconciliation_report_rows_for_reconciliation_report.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- .../get_reconciliation_report_for_last_billing_period.py | 2 +- .../v201802/report_service/run_report_with_custom_fields.py | 2 +- examples/dfp/v201802/report_service/run_saved_query.py | 2 +- .../approve_all_suggested_ad_units.py | 2 +- .../suggested_ad_unit_service/get_all_suggested_ad_units.py | 2 +- .../get_highly_requested_suggested_ad_units.py | 2 +- examples/dfp/v201802/team_service/get_all_teams.py | 2 +- examples/dfp/v201802/team_service/update_teams.py | 2 +- examples/dfp/v201802/user_service/get_all_users.py | 2 +- .../dfp/v201802/user_service/get_user_by_email_address.py | 2 +- examples/dfp/v201802/user_service/update_users.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py | 2 +- .../get_workflow_external_condition_requests.py | 2 +- .../trigger_workflow_external_condition_requests.py | 2 +- .../activity_group_service/get_active_activity_groups.py | 2 +- .../v201805/activity_group_service/get_all_activity_groups.py | 2 +- .../v201805/activity_group_service/update_activity_groups.py | 2 +- .../dfp/v201805/activity_service/get_active_activities.py | 2 +- examples/dfp/v201805/activity_service/get_all_activities.py | 2 +- examples/dfp/v201805/activity_service/update_activities.py | 2 +- .../audience_segment_service/get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../audience_segment_service/update_audience_segments.py | 2 +- examples/dfp/v201805/base_rate_service/get_all_base_rates.py | 2 +- .../v201805/base_rate_service/get_base_rates_for_rate_card.py | 2 +- examples/dfp/v201805/base_rate_service/update_base_rates.py | 2 +- .../cdn_configuration_service/get_all_cdn_configurations.py | 2 +- examples/dfp/v201805/company_service/get_advertisers.py | 2 +- examples/dfp/v201805/company_service/get_all_companies.py | 2 +- examples/dfp/v201805/company_service/update_companies.py | 2 +- examples/dfp/v201805/contact_service/get_all_contacts.py | 2 +- .../dfp/v201805/contact_service/get_uninvited_contacts.py | 2 +- examples/dfp/v201805/contact_service/update_contacts.py | 2 +- .../get_all_content_metadata_key_hierarchies.py | 2 +- examples/dfp/v201805/content_service/get_all_content.py | 2 +- examples/dfp/v201805/creative_service/get_all_creatives.py | 2 +- examples/dfp/v201805/creative_service/get_image_creatives.py | 2 +- examples/dfp/v201805/creative_service/update_creatives.py | 2 +- .../dfp/v201805/creative_set_service/get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../dfp/v201805/creative_set_service/update_creative_set.py | 2 +- .../creative_template_service/get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../creative_wrapper_service/deactivate_creative_wrapper.py | 2 +- .../creative_wrapper_service/get_active_creative_wrappers.py | 2 +- .../creative_wrapper_service/get_all_creative_wrappers.py | 2 +- .../creative_wrapper_service/update_creative_wrappers.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../dfp/v201805/custom_field_service/get_all_custom_fields.py | 2 +- .../custom_field_service/get_custom_fields_for_line_items.py | 2 +- .../custom_targeting_service/delete_custom_targeting_keys.py | 2 +- .../delete_custom_targeting_values.py | 2 +- .../get_all_custom_targeting_keys_and_values.py | 4 ++-- .../get_predefined_custom_targeting_keys_and_values.py | 4 ++-- .../custom_targeting_service/update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../v201805/exchange_rate_service/get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../v201805/exchange_rate_service/update_exchange_rates.py | 2 +- examples/dfp/v201805/inventory_service/archive_ad_units.py | 2 +- .../dfp/v201805/inventory_service/get_ad_unit_hierarchy.py | 2 +- examples/dfp/v201805/inventory_service/get_all_ad_units.py | 2 +- .../dfp/v201805/inventory_service/get_top_level_ad_units.py | 2 +- examples/dfp/v201805/inventory_service/update_ad_units.py | 2 +- examples/dfp/v201805/label_service/deactivate_labels.py | 2 +- examples/dfp/v201805/label_service/get_active_labels.py | 2 +- examples/dfp/v201805/label_service/get_all_labels.py | 2 +- examples/dfp/v201805/label_service/update_labels.py | 2 +- .../deactivate_licas.py | 2 +- .../line_item_creative_association_service/get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../line_item_creative_association_service/update_licas.py | 2 +- examples/dfp/v201805/line_item_service/activate_line_items.py | 2 +- examples/dfp/v201805/line_item_service/get_all_line_items.py | 2 +- .../line_item_service/get_line_items_that_need_creatives.py | 2 +- .../line_item_service/get_recently_updated_line_items.py | 2 +- examples/dfp/v201805/line_item_service/pause_line_items.py | 2 +- examples/dfp/v201805/line_item_service/update_line_items.py | 2 +- .../live_stream_event_service/activate_live_stream_events.py | 2 +- .../live_stream_event_service/get_all_live_stream_events.py | 2 +- .../live_stream_event_service/update_live_stream_events.py | 2 +- .../dfp/v201805/native_style_service/get_all_native_styles.py | 2 +- examples/dfp/v201805/order_service/approve_orders.py | 2 +- examples/dfp/v201805/order_service/get_all_orders.py | 2 +- .../dfp/v201805/order_service/get_orders_starting_soon.py | 2 +- examples/dfp/v201805/order_service/update_orders.py | 2 +- examples/dfp/v201805/package_service/get_all_packages.py | 2 +- .../dfp/v201805/package_service/get_in_progress_packages.py | 2 +- examples/dfp/v201805/placement_service/create_placements.py | 2 +- .../dfp/v201805/placement_service/get_active_placements.py | 2 +- examples/dfp/v201805/placement_service/get_all_placements.py | 2 +- .../dfp/v201805/premium_rate_service/get_all_premium_rates.py | 2 +- .../premium_rate_service/get_premium_rates_for_rate_card.py | 2 +- .../dfp/v201805/premium_rate_service/update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 2 +- .../get_product_package_items_for_product_package.py | 2 +- .../product_package_service/get_active_product_packages.py | 2 +- .../product_package_service/get_all_product_packages.py | 2 +- examples/dfp/v201805/product_service/get_all_products.py | 2 +- .../product_service/get_products_for_product_template.py | 2 +- examples/dfp/v201805/product_service/update_products.py | 2 +- .../product_template_service/activate_product_templates.py | 2 +- .../product_template_service/get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../product_template_service/update_product_templates.py | 2 +- .../proposal_line_item_service/archive_proposal_line_items.py | 2 +- .../proposal_line_item_service/get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../proposal_line_item_service/update_proposal_line_items.py | 2 +- examples/dfp/v201805/proposal_service/get_all_proposals.py | 2 +- .../proposal_service/get_proposals_pending_approval.py | 2 +- .../dfp/v201805/proposal_service/request_buyers_acceptance.py | 2 +- .../v201805/proposal_service/submit_proposals_for_approval.py | 2 +- examples/dfp/v201805/proposal_service/update_proposals.py | 2 +- examples/dfp/v201805/rate_card_service/get_all_rate_cards.py | 2 +- .../v201805/rate_card_service/get_marketplace_rate_cards.py | 2 +- ...onciliation_line_item_reports_for_reconciliation_report.py | 2 +- ..._reconciliation_order_reports_for_reconciliation_report.py | 2 +- ...et_reconciliation_report_rows_for_reconciliation_report.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- .../get_reconciliation_report_for_last_billing_period.py | 2 +- .../v201805/report_service/run_report_with_custom_fields.py | 2 +- examples/dfp/v201805/report_service/run_saved_query.py | 2 +- .../approve_all_suggested_ad_units.py | 2 +- .../suggested_ad_unit_service/get_all_suggested_ad_units.py | 2 +- .../get_highly_requested_suggested_ad_units.py | 2 +- examples/dfp/v201805/team_service/get_all_teams.py | 2 +- examples/dfp/v201805/team_service/update_teams.py | 2 +- examples/dfp/v201805/user_service/get_all_users.py | 2 +- .../dfp/v201805/user_service/get_user_by_email_address.py | 2 +- examples/dfp/v201805/user_service/update_users.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py | 2 +- .../get_workflow_external_condition_requests.py | 2 +- .../trigger_workflow_external_condition_requests.py | 2 +- 376 files changed, 384 insertions(+), 381 deletions(-) diff --git a/ChangeLog b/ChangeLog index bb3fd7da..9882eca8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +12.2.0 -- 06/18/18 +- Fixed some DFP examples that would loop forever with Zeep. + 12.1.0 -- 06/06/18 * Added support and examples for AdWords v201806. * Resolved issues: diff --git a/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py index 7b074ea4..299400e3 100755 --- a/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py @@ -34,7 +34,7 @@ def main(client): while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for activity_group in response['results']: # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py index 7d51a7a9..85724d16 100755 --- a/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py @@ -33,7 +33,7 @@ def main(client): while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for activity_group in response['results']: # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/activity_group_service/update_activity_groups.py b/examples/dfp/v201711/activity_group_service/update_activity_groups.py index 5cd9e5d8..2eca7bac 100755 --- a/examples/dfp/v201711/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201711/activity_group_service/update_activity_groups.py @@ -48,7 +48,7 @@ def main(client, activity_group_id, advertiser_company_id): # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_activity_groups = [] for activity_group in response['results']: activity_group['companyIds'].append(advertiser_company_id) diff --git a/examples/dfp/v201711/activity_service/get_active_activities.py b/examples/dfp/v201711/activity_service/get_active_activities.py index e255d8b0..388c45d3 100755 --- a/examples/dfp/v201711/activity_service/get_active_activities.py +++ b/examples/dfp/v201711/activity_service/get_active_activities.py @@ -33,7 +33,7 @@ def main(client): while True: response = activity_service.getActivitiesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for activity in response['results']: # Print out some information for each activity. print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201711/activity_service/get_all_activities.py b/examples/dfp/v201711/activity_service/get_all_activities.py index 304c1d3c..8c110756 100755 --- a/examples/dfp/v201711/activity_service/get_all_activities.py +++ b/examples/dfp/v201711/activity_service/get_all_activities.py @@ -32,7 +32,7 @@ def main(client): while True: response = activity_service.getActivitiesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for activity in response['results']: # Print out some information for each activity. print('Activity with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/activity_service/update_activities.py b/examples/dfp/v201711/activity_service/update_activities.py index a1d20c13..2a18d886 100755 --- a/examples/dfp/v201711/activity_service/update_activities.py +++ b/examples/dfp/v201711/activity_service/update_activities.py @@ -46,7 +46,7 @@ def main(client, activity_id): # Get activities by statement. response = activity_service.getActivitiesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_activities = [] for activity in response['results']: # Update the expected URL. diff --git a/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py index 1990fdd6..9b67be8e 100755 --- a/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py @@ -33,7 +33,7 @@ def main(client): while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for audience_segment in response['results']: # Print out some information for each audience segment. print('Audience segment with ID "%d", name "%s", and size "%d" was ' diff --git a/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py index 7a96417b..52cfba47 100755 --- a/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py @@ -34,7 +34,7 @@ def main(client): while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for audience_segment in response['results']: # Print out some information for each audience segment. print('Audience segment with ID "%d", name "%s", and size "%d" was ' diff --git a/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py index 082df910..da8128dd 100755 --- a/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py @@ -43,7 +43,7 @@ def main(client, audience_segment_id): response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): segments = response['results'] for segment in segments: diff --git a/examples/dfp/v201711/audience_segment_service/update_audience_segments.py b/examples/dfp/v201711/audience_segment_service/update_audience_segments.py index 3ede3c29..fe640635 100755 --- a/examples/dfp/v201711/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201711/audience_segment_service/update_audience_segments.py @@ -43,7 +43,7 @@ def main(client, audience_segment_id): response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_audience_segments = [] for audience_segment in response['results']: print ('Audience segment with id "%s" and name "%s" will be updated.' diff --git a/examples/dfp/v201711/base_rate_service/get_all_base_rates.py b/examples/dfp/v201711/base_rate_service/get_all_base_rates.py index 324d1e17..497c7fc8 100755 --- a/examples/dfp/v201711/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/get_all_base_rates.py @@ -32,7 +32,7 @@ def main(client): while True: response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' diff --git a/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py index b4d547b0..c0c5dbdb 100755 --- a/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py @@ -35,7 +35,7 @@ def main(client, rate_card_id): while True: response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' diff --git a/examples/dfp/v201711/base_rate_service/update_base_rates.py b/examples/dfp/v201711/base_rate_service/update_base_rates.py index 936444d2..2f695c66 100755 --- a/examples/dfp/v201711/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201711/base_rate_service/update_base_rates.py @@ -42,7 +42,7 @@ def main(client, base_rate_id): response = base_rate_service.getBaseRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local base rate object by changing its value to $3 USD. new_rate = { 'currencyCode': 'USD', diff --git a/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py b/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py index 3815c731..a8b7332e 100755 --- a/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py @@ -36,7 +36,7 @@ def main(client): while True: response = (cdn_config_service .getCdnConfigurationsByStatement(statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for cdn in response['results']: # Print out some information for each company. print('Found CDN configuration with type "%s" and name "%s".' diff --git a/examples/dfp/v201711/company_service/get_advertisers.py b/examples/dfp/v201711/company_service/get_advertisers.py index 5f44d794..80a3bf1b 100755 --- a/examples/dfp/v201711/company_service/get_advertisers.py +++ b/examples/dfp/v201711/company_service/get_advertisers.py @@ -32,7 +32,7 @@ def main(client): # through until all companies have been retrieved. while True: response = company_service.getCompaniesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for company in response['results']: # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201711/company_service/get_all_companies.py b/examples/dfp/v201711/company_service/get_all_companies.py index afbb57e9..6854ff2a 100755 --- a/examples/dfp/v201711/company_service/get_all_companies.py +++ b/examples/dfp/v201711/company_service/get_all_companies.py @@ -31,7 +31,7 @@ def main(client): # through until all companies have been retrieved. while True: response = company_service.getCompaniesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for company in response['results']: # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201711/company_service/update_companies.py b/examples/dfp/v201711/company_service/update_companies.py index 96cc22fd..35d735b6 100755 --- a/examples/dfp/v201711/company_service/update_companies.py +++ b/examples/dfp/v201711/company_service/update_companies.py @@ -46,7 +46,7 @@ def main(client, company_id): # Get companies by statement. response = company_service.getCompaniesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_companies = [] for company in response['results']: company['comment'] += ' Updated.' diff --git a/examples/dfp/v201711/contact_service/get_all_contacts.py b/examples/dfp/v201711/contact_service/get_all_contacts.py index 0c824ad3..8d5156c4 100755 --- a/examples/dfp/v201711/contact_service/get_all_contacts.py +++ b/examples/dfp/v201711/contact_service/get_all_contacts.py @@ -31,7 +31,7 @@ def main(client): # through until all contacts have been retrieved. while True: response = contact_service.getContactsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for contact in response['results']: # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/contact_service/get_uninvited_contacts.py b/examples/dfp/v201711/contact_service/get_uninvited_contacts.py index 65b0e339..02135586 100755 --- a/examples/dfp/v201711/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201711/contact_service/get_uninvited_contacts.py @@ -32,7 +32,7 @@ def main(client): # through until all contacts have been retrieved. while True: response = contact_service.getContactsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for contact in response['results']: # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/contact_service/update_contacts.py b/examples/dfp/v201711/contact_service/update_contacts.py index dbab02df..1bb70dd6 100755 --- a/examples/dfp/v201711/contact_service/update_contacts.py +++ b/examples/dfp/v201711/contact_service/update_contacts.py @@ -47,7 +47,7 @@ def main(client, contact_id): response = contact_service.getContactsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_contacts = [] for contact in response['results']: contact['address'] = '123 New Street, New York, NY, 10011' diff --git a/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 66c97f64..b80db960 100755 --- a/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -36,7 +36,7 @@ def main(client): content_metadata_key_hierarchy_service .getContentMetadataKeyHierarchiesByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for content_metadata_key_hierarchy in response['results']: # Print out some information for each content metadata key hierarchy. print('Content metadata key hierarchy with ID "%d" and name "%s" was ' diff --git a/examples/dfp/v201711/content_service/get_all_content.py b/examples/dfp/v201711/content_service/get_all_content.py index cf7e3661..95f17770 100755 --- a/examples/dfp/v201711/content_service/get_all_content.py +++ b/examples/dfp/v201711/content_service/get_all_content.py @@ -31,7 +31,7 @@ def main(client): # through until all content have been retrieved. while True: response = content_service.getContentByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for content in response['results']: # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/creative_service/get_all_creatives.py b/examples/dfp/v201711/creative_service/get_all_creatives.py index a326edc7..73a134c6 100755 --- a/examples/dfp/v201711/creative_service/get_all_creatives.py +++ b/examples/dfp/v201711/creative_service/get_all_creatives.py @@ -31,7 +31,7 @@ def main(client): # through until all creatives have been retrieved. while True: response = creative_service.getCreativesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative in response['results']: # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/creative_service/get_image_creatives.py b/examples/dfp/v201711/creative_service/get_image_creatives.py index 5091c9da..213ccd96 100755 --- a/examples/dfp/v201711/creative_service/get_image_creatives.py +++ b/examples/dfp/v201711/creative_service/get_image_creatives.py @@ -32,7 +32,7 @@ def main(client): # through until all creatives have been retrieved. while True: response = creative_service.getCreativesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative in response['results']: # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/creative_service/update_creatives.py b/examples/dfp/v201711/creative_service/update_creatives.py index c718b379..f92fffb8 100755 --- a/examples/dfp/v201711/creative_service/update_creatives.py +++ b/examples/dfp/v201711/creative_service/update_creatives.py @@ -47,7 +47,7 @@ def main(client, image_creative_id): response = creative_service.getCreativesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local creative object by changing its destination URL. updated_creatives = [] for creative in response['results']: diff --git a/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py index ffabc63c..1cabf48d 100755 --- a/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_set in response['results']: # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py index c2aaa861..e8c0575f 100755 --- a/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py @@ -36,7 +36,7 @@ def main(client, master_creative_id): while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_set in response['results']: # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/creative_set_service/update_creative_set.py b/examples/dfp/v201711/creative_set_service/update_creative_set.py index 44737177..6268f165 100755 --- a/examples/dfp/v201711/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201711/creative_set_service/update_creative_set.py @@ -48,7 +48,7 @@ def main(client, creative_set_id, companion_creative_id): response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_created_sets = [] for creative_set in response['results']: creative_set['companionCreativeIds'].append(companion_creative_id) diff --git a/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py index ed5f73f5..689a6785 100755 --- a/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_template in response['results']: # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py index a76a87fd..bc63707e 100755 --- a/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py @@ -34,7 +34,7 @@ def main(client): while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_template in response['results']: # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py index 7d560973..a6d3592c 100755 --- a/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py @@ -47,7 +47,7 @@ def main(client, label_id): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for creative_wrapper in response['results']: print ('Creative wrapper with ID "%s" applying to label "%s" with ' diff --git a/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py index 98f9f576..34024272 100755 --- a/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py @@ -34,7 +34,7 @@ def main(client): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_wrapper in response['results']: # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % diff --git a/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py index 30780139..6958acb4 100755 --- a/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_wrapper in response['results']: # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % diff --git a/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py index b4161728..00479c21 100755 --- a/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py @@ -48,7 +48,7 @@ def main(client, creative_wrapper_id): response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_creative_wrappers = [] for creative_wrapper in response['results']: creative_wrapper['ordering'] = 'OUTER' diff --git a/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py index ac1e29fa..df3c4335 100755 --- a/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -48,7 +48,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for custom_field in response['results']: print ('Custom field with ID "%s" and name "%s" will' diff --git a/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py index bd60ea4c..04f86b2e 100755 --- a/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py @@ -33,7 +33,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_field in response['results']: # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py index ba26fb6e..71f93cc8 100755 --- a/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py @@ -34,7 +34,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_field in response['results']: # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py index defeb67f..61907bbe 100755 --- a/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py @@ -48,7 +48,7 @@ def main(client, key_name): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) diff --git a/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py index 91c3fd9c..8ec72050 100755 --- a/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py @@ -54,7 +54,7 @@ def main(client, key_id): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} value_query = ('WHERE customTargetingKeyId = :keyId ' diff --git a/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 4559215e..666ed108 100755 --- a/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -34,7 +34,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( targeting_key_statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): all_keys.extend(response['results']) targeting_key_statement.offset += targeting_key_statement.limit else: @@ -51,7 +51,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_targeting_value in response['results']: # Print out some information for each custom targeting value. print('Custom targeting value with ID "%d", name "%s", display name ' diff --git a/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index d9f0f076..fde7822e 100755 --- a/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -36,7 +36,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( targeting_key_statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): all_keys.extend(response['results']) targeting_key_statement.offset += targeting_key_statement.limit else: @@ -53,7 +53,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_targeting_value in response['results']: # Print out some information for each custom targeting value. print('Custom targeting value with ID "%d", name "%s", display name ' diff --git a/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py index 0b6ebc81..b47e8843 100755 --- a/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py @@ -42,7 +42,7 @@ def main(client, key_id): statement.ToStatement()) # Update each local custom targeting key object by changing its display name. - if 'results' in response: + if 'results' in response and len(response['results']): updated_keys = [] for key in response['results']: if not key['displayName']: diff --git a/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py index edf52d61..bcb93a88 100755 --- a/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py @@ -42,7 +42,7 @@ def main(client, key_id): statement.ToStatement()) # Update each local custom targeting value object by changing its name. - if 'results' in response: + if 'results' in response and len(response['results']): updated_values = [] for value in response['results']: if not value['displayName']: diff --git a/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py index 5b9c8ae3..f9f1b1bd 100755 --- a/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py @@ -33,7 +33,7 @@ def main(client): while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for exchange_rate in response['results']: # Print out some information for each exchange rate. print( diff --git a/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py index 3b09f1dd..470934e9 100755 --- a/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -36,7 +36,7 @@ def main(client, currency_code): while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for exchange_rate in response['results']: # Print out some information for each exchange rate. print('Exchange rate with ID "%d", currency code "%s", and exchange ' diff --git a/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py index 61a3a46d..fc1733e4 100755 --- a/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py @@ -42,7 +42,7 @@ def main(client, exchange_rate_id): response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): exchange_rate = response['results'][0] # Update the exchange rate value to 1.5. diff --git a/examples/dfp/v201711/inventory_service/archive_ad_units.py b/examples/dfp/v201711/inventory_service/archive_ad_units.py index b7222ecf..cc152465 100755 --- a/examples/dfp/v201711/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201711/inventory_service/archive_ad_units.py @@ -49,7 +49,7 @@ def main(client, parent_id): while True: response = inventory_service.getAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: print ('Ad unit with ID "%s" and name "%s" will be archived.' % (ad_unit['id'], ad_unit['name'])) diff --git a/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py index 059e2af7..5d3c25f6 100755 --- a/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py @@ -66,7 +66,7 @@ def get_all_ad_units(inventory_service): found_ad_units = [] while keep_iterating: page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in page: + if 'results' in page and len(page['results']): total_results = page['totalResultSetSize'] found_ad_units.extend(page['results']) diff --git a/examples/dfp/v201711/inventory_service/get_all_ad_units.py b/examples/dfp/v201711/inventory_service/get_all_ad_units.py index 0b7f1585..8fa08cfd 100755 --- a/examples/dfp/v201711/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201711/inventory_service/get_all_ad_units.py @@ -31,7 +31,7 @@ def main(client): # through until all ad units have been retrieved. while True: response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py index 7e3a4200..c381d0d4 100755 --- a/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py @@ -40,7 +40,7 @@ def main(client): # through until all ad units have been retrieved. while True: response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/inventory_service/update_ad_units.py b/examples/dfp/v201711/inventory_service/update_ad_units.py index c1c3b0e0..a6a68b2f 100755 --- a/examples/dfp/v201711/inventory_service/update_ad_units.py +++ b/examples/dfp/v201711/inventory_service/update_ad_units.py @@ -56,7 +56,7 @@ def main(client, ad_unit_id): 'environmentType': 'BROWSER' } - if 'results' in response: + if 'results' in response and len(response['results']): updated_ad_units = [] for ad_unit in response['results']: if 'adUnitSizes' not in ad_unit: diff --git a/examples/dfp/v201711/label_service/deactivate_labels.py b/examples/dfp/v201711/label_service/deactivate_labels.py index 04227aff..e9bee27d 100755 --- a/examples/dfp/v201711/label_service/deactivate_labels.py +++ b/examples/dfp/v201711/label_service/deactivate_labels.py @@ -39,7 +39,7 @@ def main(client): # Get labels by statement. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: print ('Label with id "%s" and name "%s" will be ' 'deactivated.' % (label['id'], label['name'])) diff --git a/examples/dfp/v201711/label_service/get_active_labels.py b/examples/dfp/v201711/label_service/get_active_labels.py index 8e419288..7dcebbb8 100755 --- a/examples/dfp/v201711/label_service/get_active_labels.py +++ b/examples/dfp/v201711/label_service/get_active_labels.py @@ -32,7 +32,7 @@ def main(client): # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], diff --git a/examples/dfp/v201711/label_service/get_all_labels.py b/examples/dfp/v201711/label_service/get_all_labels.py index 2ac0531b..f47bdca4 100755 --- a/examples/dfp/v201711/label_service/get_all_labels.py +++ b/examples/dfp/v201711/label_service/get_all_labels.py @@ -31,7 +31,7 @@ def main(client): # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], diff --git a/examples/dfp/v201711/label_service/update_labels.py b/examples/dfp/v201711/label_service/update_labels.py index bebbe0d7..42461310 100755 --- a/examples/dfp/v201711/label_service/update_labels.py +++ b/examples/dfp/v201711/label_service/update_labels.py @@ -39,7 +39,7 @@ def main(client, label_id): # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local label object by changing the description. updated_labels = [] for label in response['results']: diff --git a/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py index 453cd6ef..b29b8d49 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py @@ -44,7 +44,7 @@ def main(client, line_item_id): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: print ('LICA with line item id "%s", creative id "%s", and status' ' "%s" will be deactivated.' % diff --git a/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py index 24b02c79..63005171 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py @@ -33,7 +33,7 @@ def main(client): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: diff --git a/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py index 0f6a4ea4..020da5a0 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py @@ -36,7 +36,7 @@ def main(client, line_item_id): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: diff --git a/examples/dfp/v201711/line_item_creative_association_service/update_licas.py b/examples/dfp/v201711/line_item_creative_association_service/update_licas.py index f52e4727..2a635d40 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201711/line_item_creative_association_service/update_licas.py @@ -38,7 +38,7 @@ def main(client): response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local LICA object by changing its destination URL. updated_licas = [] for lica in response['results']: diff --git a/examples/dfp/v201711/line_item_service/activate_line_items.py b/examples/dfp/v201711/line_item_service/activate_line_items.py index c8f08513..24dd5137 100755 --- a/examples/dfp/v201711/line_item_service/activate_line_items.py +++ b/examples/dfp/v201711/line_item_service/activate_line_items.py @@ -47,7 +47,7 @@ def main(client, order_id): while True: response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: print ('Line item with id "%s", belonging to order id "%s", and ' 'name "%s" will be activated.' % diff --git a/examples/dfp/v201711/line_item_service/get_all_line_items.py b/examples/dfp/v201711/line_item_service/get_all_line_items.py index 7f9b8b1a..240ad1b0 100755 --- a/examples/dfp/v201711/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201711/line_item_service/get_all_line_items.py @@ -32,7 +32,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py index 686e20b6..e1be9bf0 100755 --- a/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py @@ -33,7 +33,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py index 533e0bae..6d7e5959 100755 --- a/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py @@ -41,7 +41,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/line_item_service/pause_line_items.py b/examples/dfp/v201711/line_item_service/pause_line_items.py index d8261d8c..7fc4cbd5 100755 --- a/examples/dfp/v201711/line_item_service/pause_line_items.py +++ b/examples/dfp/v201711/line_item_service/pause_line_items.py @@ -44,7 +44,7 @@ def main(client): # Iterate over paged results from the statement. while should_continue: page = line_item_service.getLineItemsByStatement(statement.ToStatement()) - if 'results' in page: + if 'results' in page and len(page['results']): result_set_size = page['totalResultSetSize'] # Iterate over individual results in the page. for line_item in page['results']: diff --git a/examples/dfp/v201711/line_item_service/update_line_items.py b/examples/dfp/v201711/line_item_service/update_line_items.py index ba6e8ae1..78d0cad6 100755 --- a/examples/dfp/v201711/line_item_service/update_line_items.py +++ b/examples/dfp/v201711/line_item_service/update_line_items.py @@ -44,7 +44,7 @@ def main(client, order_id): response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local line item by changing its delivery rate type. updated_line_items = [] for line_item in response['results']: diff --git a/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py b/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py index 6074664b..a7c0e33b 100755 --- a/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py +++ b/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py @@ -42,7 +42,7 @@ def main(client, live_stream_event_id): while True: response = live_stream_event_service.getLiveStreamEventsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for live_stream_event in response['results']: print('live stream event with id "%s" and name "%s" will be activated.' % (live_stream_event['id'], live_stream_event['name'])) diff --git a/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py b/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py index 9154377a..4f3e6963 100755 --- a/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py @@ -34,7 +34,7 @@ def main(client): while True: response = live_stream_event_service.getLiveStreamEventsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for live_stream_event in response['results']: # Print out some information for each live stream event. print('live stream event with id "%d" and name "%s" was found.' % diff --git a/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py b/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py index 95653f6f..b74dfa26 100755 --- a/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py +++ b/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py @@ -44,7 +44,7 @@ def main(client, live_stream_event_id): # Set adTags to be updated. new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE'] - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local live stream event by changing its attributes. updated_live_stream_events = [] for live_stream_event in response['results']: diff --git a/examples/dfp/v201711/native_style_service/get_all_native_styles.py b/examples/dfp/v201711/native_style_service/get_all_native_styles.py index 419ea950..f75608dd 100755 --- a/examples/dfp/v201711/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201711/native_style_service/get_all_native_styles.py @@ -33,7 +33,7 @@ def main(client): while True: response = native_style_service.getNativeStylesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for native_style in response['results']: # Print out some information for each native style. print('Native style with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/order_service/approve_orders.py b/examples/dfp/v201711/order_service/approve_orders.py index 51f84adc..a117a7b5 100755 --- a/examples/dfp/v201711/order_service/approve_orders.py +++ b/examples/dfp/v201711/order_service/approve_orders.py @@ -41,7 +41,7 @@ def main(client): # Get orders by statement. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for order in response['results']: print ('Order with id "%s", name "%s", and status "%s" will be ' diff --git a/examples/dfp/v201711/order_service/get_all_orders.py b/examples/dfp/v201711/order_service/get_all_orders.py index 244b582a..75aa2252 100755 --- a/examples/dfp/v201711/order_service/get_all_orders.py +++ b/examples/dfp/v201711/order_service/get_all_orders.py @@ -31,7 +31,7 @@ def main(client): # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for order in response['results']: # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], diff --git a/examples/dfp/v201711/order_service/get_orders_starting_soon.py b/examples/dfp/v201711/order_service/get_orders_starting_soon.py index af8f7247..3712d2a0 100755 --- a/examples/dfp/v201711/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201711/order_service/get_orders_starting_soon.py @@ -42,7 +42,7 @@ def main(client): # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for order in response['results']: # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], diff --git a/examples/dfp/v201711/order_service/update_orders.py b/examples/dfp/v201711/order_service/update_orders.py index ee06522e..1f810499 100755 --- a/examples/dfp/v201711/order_service/update_orders.py +++ b/examples/dfp/v201711/order_service/update_orders.py @@ -39,7 +39,7 @@ def main(client, order_id): # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local order object by changing its notes. updated_orders = [] for order in response['results']: diff --git a/examples/dfp/v201711/package_service/get_all_packages.py b/examples/dfp/v201711/package_service/get_all_packages.py index a759e6e8..6820772e 100755 --- a/examples/dfp/v201711/package_service/get_all_packages.py +++ b/examples/dfp/v201711/package_service/get_all_packages.py @@ -31,7 +31,7 @@ def main(client): # through until all packages have been retrieved. while True: response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for pkg in response['results']: # Print out some information for each package. print( diff --git a/examples/dfp/v201711/package_service/get_in_progress_packages.py b/examples/dfp/v201711/package_service/get_in_progress_packages.py index 48ad8b79..0ec4fc65 100755 --- a/examples/dfp/v201711/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201711/package_service/get_in_progress_packages.py @@ -32,7 +32,7 @@ def main(client): # through until all packages have been retrieved. while True: response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for pkg in response['results']: # Print out some information for each package. print( diff --git a/examples/dfp/v201711/placement_service/create_placements.py b/examples/dfp/v201711/placement_service/create_placements.py index d974198e..24bf145e 100755 --- a/examples/dfp/v201711/placement_service/create_placements.py +++ b/examples/dfp/v201711/placement_service/create_placements.py @@ -61,7 +61,7 @@ def main(client): response = inventory_service.getAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Separate the ad units by size. for ad_unit in response['results']: if 'adUnitSizes' in ad_unit: diff --git a/examples/dfp/v201711/placement_service/get_active_placements.py b/examples/dfp/v201711/placement_service/get_active_placements.py index 816c1bb3..3704dcb5 100755 --- a/examples/dfp/v201711/placement_service/get_active_placements.py +++ b/examples/dfp/v201711/placement_service/get_active_placements.py @@ -33,7 +33,7 @@ def main(client): while True: response = placement_service.getPlacementsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for placement in response['results']: # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/placement_service/get_all_placements.py b/examples/dfp/v201711/placement_service/get_all_placements.py index 7fce181e..2a98cce2 100755 --- a/examples/dfp/v201711/placement_service/get_all_placements.py +++ b/examples/dfp/v201711/placement_service/get_all_placements.py @@ -32,7 +32,7 @@ def main(client): while True: response = placement_service.getPlacementsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for placement in response['results']: # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py index 67ae3b82..c55216ac 100755 --- a/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py @@ -33,7 +33,7 @@ def main(client): while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' diff --git a/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py index efd4e313..12a4a545 100755 --- a/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py @@ -36,7 +36,7 @@ def main(client, rate_card_id): while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' diff --git a/examples/dfp/v201711/premium_rate_service/update_premium_rates.py b/examples/dfp/v201711/premium_rate_service/update_premium_rates.py index 9cb338da..2239f7d8 100755 --- a/examples/dfp/v201711/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201711/premium_rate_service/update_premium_rates.py @@ -43,7 +43,7 @@ def main(client, premium_rate_id): response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_premium_rates = [] for premium_rate in response['results']: # Create a flat fee based premium rate value with a 10% increase. diff --git a/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py index 6cabd514..c5835440 100755 --- a/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_package_item_service.getProductPackageItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package_item in response['results']: # Print out some information for each product package item. print('Product package item with ID "%d", product id "%d", and product ' diff --git a/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py index b7d4900f..8d43e9b8 100755 --- a/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py @@ -36,7 +36,7 @@ def main(client, product_package_id): while True: response = product_package_item_service.getProductPackageItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package_item in response['results']: # Print out some information for each product package item. print('Product package item with ID "%d", product ID "%d", and product ' diff --git a/examples/dfp/v201711/product_package_service/get_active_product_packages.py b/examples/dfp/v201711/product_package_service/get_active_product_packages.py index b747a2a0..9f9b1fce 100755 --- a/examples/dfp/v201711/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201711/product_package_service/get_active_product_packages.py @@ -34,7 +34,7 @@ def main(client): while True: response = product_package_service.getProductPackagesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package in response['results']: # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/product_package_service/get_all_product_packages.py b/examples/dfp/v201711/product_package_service/get_all_product_packages.py index c1d566cb..0ef28edd 100755 --- a/examples/dfp/v201711/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201711/product_package_service/get_all_product_packages.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_package_service.getProductPackagesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package in response['results']: # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/product_service/get_all_products.py b/examples/dfp/v201711/product_service/get_all_products.py index 5b88012d..b3a66a1c 100755 --- a/examples/dfp/v201711/product_service/get_all_products.py +++ b/examples/dfp/v201711/product_service/get_all_products.py @@ -31,7 +31,7 @@ def main(client): # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product in response['results']: # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/product_service/get_products_for_product_template.py b/examples/dfp/v201711/product_service/get_products_for_product_template.py index 42ef9bdf..26b7c369 100755 --- a/examples/dfp/v201711/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201711/product_service/get_products_for_product_template.py @@ -35,7 +35,7 @@ def main(client, product_template_id): # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product in response['results']: # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/product_service/update_products.py b/examples/dfp/v201711/product_service/update_products.py index b1d37737..229fe819 100755 --- a/examples/dfp/v201711/product_service/update_products.py +++ b/examples/dfp/v201711/product_service/update_products.py @@ -40,7 +40,7 @@ def main(client, product_id): # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local product object by changing its notes. updated_products = [] for product in response['results']: diff --git a/examples/dfp/v201711/product_template_service/activate_product_templates.py b/examples/dfp/v201711/product_template_service/activate_product_templates.py index 87bae3ca..6676b7c2 100755 --- a/examples/dfp/v201711/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201711/product_template_service/activate_product_templates.py @@ -45,7 +45,7 @@ def main(client, product_template_id): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: print ('Product template with id "%s" and name "%s" will be ' 'activated.' % (product_template['id'], diff --git a/examples/dfp/v201711/product_template_service/get_all_product_templates.py b/examples/dfp/v201711/product_template_service/get_all_product_templates.py index 4d7f7680..9ca9a397 100755 --- a/examples/dfp/v201711/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201711/product_template_service/get_all_product_templates.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py index 9a6c9fc2..da31a375 100755 --- a/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py @@ -34,7 +34,7 @@ def main(client): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/product_template_service/update_product_templates.py b/examples/dfp/v201711/product_template_service/update_product_templates.py index 40bc6c41..3a58e9b1 100755 --- a/examples/dfp/v201711/product_template_service/update_product_templates.py +++ b/examples/dfp/v201711/product_template_service/update_product_templates.py @@ -43,7 +43,7 @@ def main(client, product_template_id): response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local product template object by appending a new geo-target. for product_template in response['results']: # Create geo-targeting for Canada to append. diff --git a/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py index 3001c92c..b178b4b8 100755 --- a/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py @@ -45,7 +45,7 @@ def main(client, proposal_line_item_id): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: print ('Proposal line item with id "%s", ' 'belonging to proposal id "%s", and ' diff --git a/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py index 9fb0218c..a7142e6f 100755 --- a/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py @@ -33,7 +33,7 @@ def main(client): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py index a82722d8..59c8dd5c 100755 --- a/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -36,7 +36,7 @@ def main(client, proposal_id): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py index 930fd72e..2f4b1c32 100755 --- a/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py @@ -44,7 +44,7 @@ def main(client, proposal_line_item_id): response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each the proposal line item's notes field. proposal_line_item = response['results'][0] proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.' diff --git a/examples/dfp/v201711/proposal_service/get_all_proposals.py b/examples/dfp/v201711/proposal_service/get_all_proposals.py index 10699516..7318822e 100755 --- a/examples/dfp/v201711/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201711/proposal_service/get_all_proposals.py @@ -31,7 +31,7 @@ def main(client): # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal in response['results']: # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py index dcf4fca4..cba14225 100755 --- a/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py @@ -32,7 +32,7 @@ def main(client): # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal in response['results']: # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py index 502d591a..4c61d9c8 100755 --- a/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py @@ -37,7 +37,7 @@ def main(client, proposal_id): # Get proposals by statement. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: print ('Programmatic proposal with id "%s", name "%s", and status ' diff --git a/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py index ecb8c5d1..b19ecdd4 100755 --- a/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py @@ -39,7 +39,7 @@ def main(client, proposal_id): # Get proposals by statement. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: print ('Proposal with id "%s", name "%s", and status "%s" will be' diff --git a/examples/dfp/v201711/proposal_service/update_proposals.py b/examples/dfp/v201711/proposal_service/update_proposals.py index 29339cca..06dbe9f6 100755 --- a/examples/dfp/v201711/proposal_service/update_proposals.py +++ b/examples/dfp/v201711/proposal_service/update_proposals.py @@ -40,7 +40,7 @@ def main(client, proposal_id): # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local proposal object by changing its notes. updated_proposals = [] for proposal in response['results']: diff --git a/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py index 2c0d78e4..e3284911 100755 --- a/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py @@ -32,7 +32,7 @@ def main(client): while True: response = rate_card_service.getRateCardsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for rate_card in response['results']: # Print out some information for each rate card. print('Rate card with ID "%d", name "%s", and currency code "%s" was ' diff --git a/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py index c3c213bb..833e526b 100755 --- a/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py @@ -34,7 +34,7 @@ def main(client): while True: response = rate_card_service.getRateCardsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for rate_card in response['results']: # Print out some information for each rate card. print( diff --git a/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index d669cb83..e2a4e2e7 100755 --- a/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -51,7 +51,7 @@ def main(client): page = (reconciliation_line_item_report_service .getReconciliationLineItemReportsByStatement( statement.ToStatement())) - if 'results' in page: + if 'results' in page and len(page['results']): result_set_size += page['totalResultSetSize'] # Iterate over individual results in the page. for line_item_report in page['results']: diff --git a/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 7e298979..3972269e 100755 --- a/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -39,7 +39,7 @@ def main(client, reconciliation_report_id): reconciliation_order_report_service .getReconciliationOrderReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_order_report in response['results']: # Print out some information for each reconciliation order report. print('Reconciliation order report with ID "%d" and status "%s" was ' diff --git a/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 9b414ea1..a0d975b6 100755 --- a/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -43,7 +43,7 @@ def main(client, reconciliation_report_id): reconciliation_report_row_service .getReconciliationReportRowsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report_row in response['results']: # Print out some information for each reconciliation report row. print('Reconciliation report row with ID "%d", reconciliation source ' diff --git a/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py index 15825fe0..90ec2152 100755 --- a/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py @@ -35,7 +35,7 @@ def main(client): reconciliation_report_service .getReconciliationReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report in response['results']: # Print out some information for each reconciliation report. print( diff --git a/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index c391ab1b..9b4ed1e2 100755 --- a/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -43,7 +43,7 @@ def main(client): reconciliation_report_service .getReconciliationReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report in response['results']: # Print out some information for each reconciliation report. print( diff --git a/examples/dfp/v201711/report_service/run_report_with_custom_fields.py b/examples/dfp/v201711/report_service/run_report_with_custom_fields.py index c302079c..208fbd0c 100755 --- a/examples/dfp/v201711/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201711/report_service/run_report_with_custom_fields.py @@ -44,7 +44,7 @@ def main(client, order_id): while True: response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Get custom field IDs from the line items of an order. for line_item in response['results']: if 'customFieldValues' in line_item: diff --git a/examples/dfp/v201711/report_service/run_saved_query.py b/examples/dfp/v201711/report_service/run_saved_query.py index 16ce73f3..027295cb 100755 --- a/examples/dfp/v201711/report_service/run_saved_query.py +++ b/examples/dfp/v201711/report_service/run_saved_query.py @@ -42,7 +42,7 @@ def main(client, saved_query_id): response = report_service.getSavedQueriesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): saved_query = response['results'][0] if saved_query['isCompatibleWithApiVersion']: diff --git a/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 9babe2de..b5812f0f 100755 --- a/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -49,7 +49,7 @@ def main(client): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: print ('Suggested ad unit with id "%s", and number of requests "%s"' diff --git a/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py index eecffd62..ef251fc6 100755 --- a/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -33,7 +33,7 @@ def main(client): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for suggested_ad_unit in response['results']: # Print out some information for each suggested ad unit. print( diff --git a/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 175f870c..2ca20b51 100755 --- a/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -36,7 +36,7 @@ def main(client, num_requests): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for suggested_ad_unit in response['results']: # Print out some information for each suggested ad unit. print( diff --git a/examples/dfp/v201711/team_service/get_all_teams.py b/examples/dfp/v201711/team_service/get_all_teams.py index 8a639323..d3d06b87 100755 --- a/examples/dfp/v201711/team_service/get_all_teams.py +++ b/examples/dfp/v201711/team_service/get_all_teams.py @@ -31,7 +31,7 @@ def main(client): # through until all teams have been retrieved. while True: response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for team in response['results']: # Print out some information for each team. print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], diff --git a/examples/dfp/v201711/team_service/update_teams.py b/examples/dfp/v201711/team_service/update_teams.py index 2f10953a..2f06f9fd 100755 --- a/examples/dfp/v201711/team_service/update_teams.py +++ b/examples/dfp/v201711/team_service/update_teams.py @@ -44,7 +44,7 @@ def main(client, team_id): # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_teams = [] # Update each local team object by changing its description. for team in response['results']: diff --git a/examples/dfp/v201711/user_service/get_all_users.py b/examples/dfp/v201711/user_service/get_all_users.py index 0c57a8d7..c846a6a3 100755 --- a/examples/dfp/v201711/user_service/get_all_users.py +++ b/examples/dfp/v201711/user_service/get_all_users.py @@ -31,7 +31,7 @@ def main(client): # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user in response['results']: # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], diff --git a/examples/dfp/v201711/user_service/get_user_by_email_address.py b/examples/dfp/v201711/user_service/get_user_by_email_address.py index 2d3ed8c8..f7fb6391 100755 --- a/examples/dfp/v201711/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201711/user_service/get_user_by_email_address.py @@ -34,7 +34,7 @@ def main(client, email_address): # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user in response['results']: # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], diff --git a/examples/dfp/v201711/user_service/update_users.py b/examples/dfp/v201711/user_service/update_users.py index 70a566c0..da906f31 100755 --- a/examples/dfp/v201711/user_service/update_users.py +++ b/examples/dfp/v201711/user_service/update_users.py @@ -38,7 +38,7 @@ def main(client, user_id): # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): users = response['results'] for user in users: user['name'] += ' Sr.' diff --git a/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py index 14783340..e2c171e1 100755 --- a/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py @@ -33,7 +33,7 @@ def main(client): while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user_team_association in response['results']: # Print out some information for each user team association. print('User team association with team id "%d" and user id "%d" was ' diff --git a/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py index c09c240c..d686c980 100755 --- a/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py @@ -36,7 +36,7 @@ def main(client, user_id): while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user_team_association in response['results']: # Print out some information for each user team association. print('User team association with user ID "%d" and team ID "%d" was ' diff --git a/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py index 43bc0e8d..1076ebb8 100755 --- a/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py @@ -48,7 +48,7 @@ def main(client, user_id): response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_user_team_associations = [] # Update each local user team association to read only access. for user_team_association in response['results']: diff --git a/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py index 0b176750..824c24f9 100755 --- a/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py @@ -46,7 +46,7 @@ def main(client, proposal_id): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for workflow_approval_request in response['results']: print ('Workflow approval request with id "%s" will be' diff --git a/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py index 5485408c..1c083cb6 100755 --- a/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py @@ -37,7 +37,7 @@ def main(client): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for workflow_request in response['results']: # Print out some information for each workflow request. print('Workflow request with ID "%d", entity type "%s", and entity ID ' diff --git a/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py index f098692f..9d257e7d 100755 --- a/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py @@ -37,7 +37,7 @@ def main(client): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for workflow_request in response['results']: # Print out some information for each workflow request. print('Workflow request with ID "%d", entity type "%s", and entity ID ' diff --git a/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py index 35624bcf..4b24ba54 100755 --- a/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -46,7 +46,7 @@ def main(client, proposal_id): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for workflow_request in response['results']: print ('Workflow external condition request with id "%s" for %s ' diff --git a/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py index c954ffbe..459660fd 100755 --- a/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py @@ -34,7 +34,7 @@ def main(client): while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for activity_group in response['results']: # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py index dd9a08e4..57789670 100755 --- a/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py @@ -33,7 +33,7 @@ def main(client): while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for activity_group in response['results']: # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/activity_group_service/update_activity_groups.py b/examples/dfp/v201802/activity_group_service/update_activity_groups.py index c25929a7..25c615fb 100755 --- a/examples/dfp/v201802/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201802/activity_group_service/update_activity_groups.py @@ -48,7 +48,7 @@ def main(client, activity_group_id, advertiser_company_id): # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_activity_groups = [] for activity_group in response['results']: activity_group['companyIds'].append(advertiser_company_id) diff --git a/examples/dfp/v201802/activity_service/get_active_activities.py b/examples/dfp/v201802/activity_service/get_active_activities.py index 5686aa52..906de34d 100755 --- a/examples/dfp/v201802/activity_service/get_active_activities.py +++ b/examples/dfp/v201802/activity_service/get_active_activities.py @@ -33,7 +33,7 @@ def main(client): while True: response = activity_service.getActivitiesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for activity in response['results']: # Print out some information for each activity. print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201802/activity_service/get_all_activities.py b/examples/dfp/v201802/activity_service/get_all_activities.py index d44eef63..d79b9590 100755 --- a/examples/dfp/v201802/activity_service/get_all_activities.py +++ b/examples/dfp/v201802/activity_service/get_all_activities.py @@ -32,7 +32,7 @@ def main(client): while True: response = activity_service.getActivitiesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for activity in response['results']: # Print out some information for each activity. print('Activity with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/activity_service/update_activities.py b/examples/dfp/v201802/activity_service/update_activities.py index 2225e1d4..fd3498b9 100755 --- a/examples/dfp/v201802/activity_service/update_activities.py +++ b/examples/dfp/v201802/activity_service/update_activities.py @@ -46,7 +46,7 @@ def main(client, activity_id): # Get activities by statement. response = activity_service.getActivitiesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_activities = [] for activity in response['results']: # Update the expected URL. diff --git a/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py index 07e9fa8c..d3a4ed75 100755 --- a/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py @@ -33,7 +33,7 @@ def main(client): while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for audience_segment in response['results']: # Print out some information for each audience segment. print('Audience segment with ID "%d", name "%s", and size "%d" was ' diff --git a/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py index 48aa0349..f47421b2 100755 --- a/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py @@ -34,7 +34,7 @@ def main(client): while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for audience_segment in response['results']: # Print out some information for each audience segment. print('Audience segment with ID "%d", name "%s", and size "%d" was ' diff --git a/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py index 0fa30e62..ac9216a7 100755 --- a/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py @@ -43,7 +43,7 @@ def main(client, audience_segment_id): response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): segments = response['results'] for segment in segments: diff --git a/examples/dfp/v201802/audience_segment_service/update_audience_segments.py b/examples/dfp/v201802/audience_segment_service/update_audience_segments.py index e0b559d1..1cc1d0b6 100755 --- a/examples/dfp/v201802/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201802/audience_segment_service/update_audience_segments.py @@ -43,7 +43,7 @@ def main(client, audience_segment_id): response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_audience_segments = [] for audience_segment in response['results']: print ('Audience segment with id "%s" and name "%s" will be updated.' diff --git a/examples/dfp/v201802/base_rate_service/get_all_base_rates.py b/examples/dfp/v201802/base_rate_service/get_all_base_rates.py index 743db7e5..1c8fd6e8 100755 --- a/examples/dfp/v201802/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/get_all_base_rates.py @@ -32,7 +32,7 @@ def main(client): while True: response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' diff --git a/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py index 2bc4555b..ee12f4cb 100755 --- a/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py @@ -35,7 +35,7 @@ def main(client, rate_card_id): while True: response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' diff --git a/examples/dfp/v201802/base_rate_service/update_base_rates.py b/examples/dfp/v201802/base_rate_service/update_base_rates.py index 48c74f3a..3cb98dfc 100755 --- a/examples/dfp/v201802/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201802/base_rate_service/update_base_rates.py @@ -42,7 +42,7 @@ def main(client, base_rate_id): response = base_rate_service.getBaseRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local base rate object by changing its value to $3 USD. new_rate = { 'currencyCode': 'USD', diff --git a/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py b/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py index 02e8b463..91df2a56 100755 --- a/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py @@ -36,7 +36,7 @@ def main(client): while True: response = (cdn_config_service .getCdnConfigurationsByStatement(statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for cdn in response['results']: # Print out some information for each company. print('Found CDN configuration with type "%s" and name "%s".' diff --git a/examples/dfp/v201802/company_service/get_advertisers.py b/examples/dfp/v201802/company_service/get_advertisers.py index ecb16c39..17f8b0a0 100755 --- a/examples/dfp/v201802/company_service/get_advertisers.py +++ b/examples/dfp/v201802/company_service/get_advertisers.py @@ -32,7 +32,7 @@ def main(client): # through until all companies have been retrieved. while True: response = company_service.getCompaniesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for company in response['results']: # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201802/company_service/get_all_companies.py b/examples/dfp/v201802/company_service/get_all_companies.py index cabe543b..b0d6e97f 100755 --- a/examples/dfp/v201802/company_service/get_all_companies.py +++ b/examples/dfp/v201802/company_service/get_all_companies.py @@ -31,7 +31,7 @@ def main(client): # through until all companies have been retrieved. while True: response = company_service.getCompaniesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for company in response['results']: # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201802/company_service/update_companies.py b/examples/dfp/v201802/company_service/update_companies.py index 65a71808..1bfe94bc 100755 --- a/examples/dfp/v201802/company_service/update_companies.py +++ b/examples/dfp/v201802/company_service/update_companies.py @@ -46,7 +46,7 @@ def main(client, company_id): # Get companies by statement. response = company_service.getCompaniesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_companies = [] for company in response['results']: company['comment'] += ' Updated.' diff --git a/examples/dfp/v201802/contact_service/get_all_contacts.py b/examples/dfp/v201802/contact_service/get_all_contacts.py index edde878e..32c02b93 100755 --- a/examples/dfp/v201802/contact_service/get_all_contacts.py +++ b/examples/dfp/v201802/contact_service/get_all_contacts.py @@ -31,7 +31,7 @@ def main(client): # through until all contacts have been retrieved. while True: response = contact_service.getContactsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for contact in response['results']: # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/contact_service/get_uninvited_contacts.py b/examples/dfp/v201802/contact_service/get_uninvited_contacts.py index 6063cad2..1f809524 100755 --- a/examples/dfp/v201802/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201802/contact_service/get_uninvited_contacts.py @@ -32,7 +32,7 @@ def main(client): # through until all contacts have been retrieved. while True: response = contact_service.getContactsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for contact in response['results']: # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/contact_service/update_contacts.py b/examples/dfp/v201802/contact_service/update_contacts.py index 4091cac3..0a1196c9 100755 --- a/examples/dfp/v201802/contact_service/update_contacts.py +++ b/examples/dfp/v201802/contact_service/update_contacts.py @@ -47,7 +47,7 @@ def main(client, contact_id): response = contact_service.getContactsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_contacts = [] for contact in response['results']: contact['address'] = '123 New Street, New York, NY, 10011' diff --git a/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index afe409a3..37d04a34 100755 --- a/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -36,7 +36,7 @@ def main(client): content_metadata_key_hierarchy_service .getContentMetadataKeyHierarchiesByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for content_metadata_key_hierarchy in response['results']: # Print out some information for each content metadata key hierarchy. print('Content metadata key hierarchy with ID "%d" and name "%s" was ' diff --git a/examples/dfp/v201802/content_service/get_all_content.py b/examples/dfp/v201802/content_service/get_all_content.py index 4eac419f..52f53c40 100755 --- a/examples/dfp/v201802/content_service/get_all_content.py +++ b/examples/dfp/v201802/content_service/get_all_content.py @@ -31,7 +31,7 @@ def main(client): # through until all content have been retrieved. while True: response = content_service.getContentByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for content in response['results']: # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/creative_service/get_all_creatives.py b/examples/dfp/v201802/creative_service/get_all_creatives.py index 63febc23..2c12848b 100755 --- a/examples/dfp/v201802/creative_service/get_all_creatives.py +++ b/examples/dfp/v201802/creative_service/get_all_creatives.py @@ -31,7 +31,7 @@ def main(client): # through until all creatives have been retrieved. while True: response = creative_service.getCreativesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative in response['results']: # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/creative_service/get_image_creatives.py b/examples/dfp/v201802/creative_service/get_image_creatives.py index f6099acd..294ed1cf 100755 --- a/examples/dfp/v201802/creative_service/get_image_creatives.py +++ b/examples/dfp/v201802/creative_service/get_image_creatives.py @@ -32,7 +32,7 @@ def main(client): # through until all creatives have been retrieved. while True: response = creative_service.getCreativesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative in response['results']: # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/creative_service/update_creatives.py b/examples/dfp/v201802/creative_service/update_creatives.py index 74726456..5bc84e6d 100755 --- a/examples/dfp/v201802/creative_service/update_creatives.py +++ b/examples/dfp/v201802/creative_service/update_creatives.py @@ -47,7 +47,7 @@ def main(client, image_creative_id): response = creative_service.getCreativesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local creative object by changing its destination URL. updated_creatives = [] for creative in response['results']: diff --git a/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py index b3c337f3..d39b99ef 100755 --- a/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_set in response['results']: # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py index ffd023d7..d13e615e 100755 --- a/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py @@ -36,7 +36,7 @@ def main(client, master_creative_id): while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_set in response['results']: # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/creative_set_service/update_creative_set.py b/examples/dfp/v201802/creative_set_service/update_creative_set.py index 36be393c..b23aa8f1 100755 --- a/examples/dfp/v201802/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201802/creative_set_service/update_creative_set.py @@ -48,7 +48,7 @@ def main(client, creative_set_id, companion_creative_id): response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_created_sets = [] for creative_set in response['results']: creative_set['companionCreativeIds'].append(companion_creative_id) diff --git a/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py index 2795bdd9..6df8e065 100755 --- a/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_template in response['results']: # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py index 202b14d1..ef613634 100755 --- a/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py @@ -34,7 +34,7 @@ def main(client): while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_template in response['results']: # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py index 3f46de24..8cd26e55 100755 --- a/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py @@ -47,7 +47,7 @@ def main(client, label_id): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for creative_wrapper in response['results']: print ('Creative wrapper with ID "%s" applying to label "%s" with ' diff --git a/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py index d2a29cd9..3fe60bd2 100755 --- a/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py @@ -34,7 +34,7 @@ def main(client): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_wrapper in response['results']: # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % diff --git a/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py index 1e2bd8b9..4b6ec0bf 100755 --- a/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_wrapper in response['results']: # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % diff --git a/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py index 75f7e964..27eb2e0b 100755 --- a/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py @@ -48,7 +48,7 @@ def main(client, creative_wrapper_id): response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_creative_wrappers = [] for creative_wrapper in response['results']: creative_wrapper['ordering'] = 'OUTER' diff --git a/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py index 16d45c12..295ce5d6 100755 --- a/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -48,7 +48,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for custom_field in response['results']: print ('Custom field with ID "%s" and name "%s" will' diff --git a/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py index afe4646c..4f4d0ba4 100755 --- a/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py @@ -33,7 +33,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_field in response['results']: # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py index 9a47c4f1..d1da9092 100755 --- a/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py @@ -34,7 +34,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_field in response['results']: # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py index d90b4079..733cdc25 100755 --- a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py @@ -48,7 +48,7 @@ def main(client, key_name): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} key_statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py index 2a46afba..14355137 100755 --- a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py @@ -48,7 +48,7 @@ def main(client, key_id): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} value_statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 8b378fca..57da81ae 100755 --- a/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -34,7 +34,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( targeting_key_statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): all_keys.extend(response['results']) targeting_key_statement.offset += targeting_key_statement.limit else: @@ -51,7 +51,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_targeting_value in response['results']: # Print out some information for each custom targeting value. print('Custom targeting value with ID "%d", name "%s", display name ' diff --git a/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 9c6a4660..317dd4f8 100755 --- a/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -36,7 +36,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( targeting_key_statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): all_keys.extend(response['results']) targeting_key_statement.offset += targeting_key_statement.limit else: @@ -53,7 +53,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_targeting_value in response['results']: # Print out some information for each custom targeting value. print('Custom targeting value with ID "%d", name "%s", display name ' diff --git a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py index 81ce3523..a9d34392 100755 --- a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py @@ -42,7 +42,7 @@ def main(client, key_id): statement.ToStatement()) # Update each local custom targeting key object by changing its display name. - if 'results' in response: + if 'results' in response and len(response['results']): updated_keys = [] for key in response['results']: if not key['displayName']: diff --git a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py index 5ce26863..d9a8a7e2 100755 --- a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py @@ -42,7 +42,7 @@ def main(client, key_id): statement.ToStatement()) # Update each local custom targeting value object by changing its name. - if 'results' in response: + if 'results' in response and len(response['results']): updated_values = [] for value in response['results']: if not value['displayName']: diff --git a/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py index 497f5630..e3165d30 100755 --- a/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py @@ -33,7 +33,7 @@ def main(client): while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for exchange_rate in response['results']: # Print out some information for each exchange rate. print( diff --git a/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py index dc7344e1..9c715fe3 100755 --- a/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -36,7 +36,7 @@ def main(client, currency_code): while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for exchange_rate in response['results']: # Print out some information for each exchange rate. print('Exchange rate with ID "%d", currency code "%s", and exchange ' diff --git a/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py index a95e076f..6e760ee5 100755 --- a/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py @@ -42,7 +42,7 @@ def main(client, exchange_rate_id): response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): exchange_rate = response['results'][0] # Update the exchange rate value to 1.5. diff --git a/examples/dfp/v201802/inventory_service/archive_ad_units.py b/examples/dfp/v201802/inventory_service/archive_ad_units.py index 6cfb83dc..0b1ec4e4 100755 --- a/examples/dfp/v201802/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201802/inventory_service/archive_ad_units.py @@ -49,7 +49,7 @@ def main(client, parent_id): while True: response = inventory_service.getAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: print ('Ad unit with ID "%s" and name "%s" will be archived.' % (ad_unit['id'], ad_unit['name'])) diff --git a/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py index e86eb93b..97a00c07 100755 --- a/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py @@ -66,7 +66,7 @@ def get_all_ad_units(inventory_service): found_ad_units = [] while keep_iterating: page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in page: + if 'results' in page and len(page['results']): total_results = page['totalResultSetSize'] found_ad_units.extend(page['results']) diff --git a/examples/dfp/v201802/inventory_service/get_all_ad_units.py b/examples/dfp/v201802/inventory_service/get_all_ad_units.py index c42ea962..a0593b64 100755 --- a/examples/dfp/v201802/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201802/inventory_service/get_all_ad_units.py @@ -31,7 +31,7 @@ def main(client): # through until all ad units have been retrieved. while True: response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py index f58ddeb5..afc75cf6 100755 --- a/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py @@ -40,7 +40,7 @@ def main(client): # through until all ad units have been retrieved. while True: response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/inventory_service/update_ad_units.py b/examples/dfp/v201802/inventory_service/update_ad_units.py index a7a4e217..2834c7f7 100755 --- a/examples/dfp/v201802/inventory_service/update_ad_units.py +++ b/examples/dfp/v201802/inventory_service/update_ad_units.py @@ -56,7 +56,7 @@ def main(client, ad_unit_id): 'environmentType': 'BROWSER' } - if 'results' in response: + if 'results' in response and len(response['results']): updated_ad_units = [] for ad_unit in response['results']: if 'adUnitSizes' not in ad_unit: diff --git a/examples/dfp/v201802/label_service/deactivate_labels.py b/examples/dfp/v201802/label_service/deactivate_labels.py index 14f1ea6a..a6a37d90 100755 --- a/examples/dfp/v201802/label_service/deactivate_labels.py +++ b/examples/dfp/v201802/label_service/deactivate_labels.py @@ -39,7 +39,7 @@ def main(client): # Get labels by statement. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: print ('Label with id "%s" and name "%s" will be ' 'deactivated.' % (label['id'], label['name'])) diff --git a/examples/dfp/v201802/label_service/get_active_labels.py b/examples/dfp/v201802/label_service/get_active_labels.py index d480c9a1..0d1085ee 100755 --- a/examples/dfp/v201802/label_service/get_active_labels.py +++ b/examples/dfp/v201802/label_service/get_active_labels.py @@ -32,7 +32,7 @@ def main(client): # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], diff --git a/examples/dfp/v201802/label_service/get_all_labels.py b/examples/dfp/v201802/label_service/get_all_labels.py index 7546eb12..2303e1a4 100755 --- a/examples/dfp/v201802/label_service/get_all_labels.py +++ b/examples/dfp/v201802/label_service/get_all_labels.py @@ -31,7 +31,7 @@ def main(client): # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], diff --git a/examples/dfp/v201802/label_service/update_labels.py b/examples/dfp/v201802/label_service/update_labels.py index 91b7d025..74c8783f 100755 --- a/examples/dfp/v201802/label_service/update_labels.py +++ b/examples/dfp/v201802/label_service/update_labels.py @@ -39,7 +39,7 @@ def main(client, label_id): # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local label object by changing the description. updated_labels = [] for label in response['results']: diff --git a/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py index fd01bc98..202b13a0 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py @@ -44,7 +44,7 @@ def main(client, line_item_id): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: print ('LICA with line item id "%s", creative id "%s", and status' ' "%s" will be deactivated.' % diff --git a/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py index a3e8cc11..a5e548d8 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py @@ -33,7 +33,7 @@ def main(client): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: diff --git a/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py index 81427789..5f799a2c 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py @@ -36,7 +36,7 @@ def main(client, line_item_id): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: diff --git a/examples/dfp/v201802/line_item_creative_association_service/update_licas.py b/examples/dfp/v201802/line_item_creative_association_service/update_licas.py index e5b6dc12..ab99185e 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201802/line_item_creative_association_service/update_licas.py @@ -38,7 +38,7 @@ def main(client): response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local LICA object by changing its destination URL. updated_licas = [] for lica in response['results']: diff --git a/examples/dfp/v201802/line_item_service/activate_line_items.py b/examples/dfp/v201802/line_item_service/activate_line_items.py index 20c52f69..edd95797 100755 --- a/examples/dfp/v201802/line_item_service/activate_line_items.py +++ b/examples/dfp/v201802/line_item_service/activate_line_items.py @@ -47,7 +47,7 @@ def main(client, order_id): while True: response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: print ('Line item with id "%s", belonging to order id "%s", and ' 'name "%s" will be activated.' % diff --git a/examples/dfp/v201802/line_item_service/get_all_line_items.py b/examples/dfp/v201802/line_item_service/get_all_line_items.py index 4e8ea547..33107257 100755 --- a/examples/dfp/v201802/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201802/line_item_service/get_all_line_items.py @@ -32,7 +32,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py index 3213cc3c..b8d89924 100755 --- a/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py @@ -33,7 +33,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py index be801307..5e6b2efa 100755 --- a/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py @@ -41,7 +41,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/line_item_service/pause_line_items.py b/examples/dfp/v201802/line_item_service/pause_line_items.py index 62481bf9..6090566b 100755 --- a/examples/dfp/v201802/line_item_service/pause_line_items.py +++ b/examples/dfp/v201802/line_item_service/pause_line_items.py @@ -44,7 +44,7 @@ def main(client): # Iterate over paged results from the statement. while should_continue: page = line_item_service.getLineItemsByStatement(statement.ToStatement()) - if 'results' in page: + if 'results' in page and len(page['results']): result_set_size = page['totalResultSetSize'] # Iterate over individual results in the page. for line_item in page['results']: diff --git a/examples/dfp/v201802/line_item_service/update_line_items.py b/examples/dfp/v201802/line_item_service/update_line_items.py index a98c03db..4499cbb9 100755 --- a/examples/dfp/v201802/line_item_service/update_line_items.py +++ b/examples/dfp/v201802/line_item_service/update_line_items.py @@ -44,7 +44,7 @@ def main(client, order_id): response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local line item by changing its delivery rate type. updated_line_items = [] for line_item in response['results']: diff --git a/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py b/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py index 04b5d933..5c15f78a 100755 --- a/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py +++ b/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py @@ -42,7 +42,7 @@ def main(client, live_stream_event_id): while True: response = live_stream_event_service.getLiveStreamEventsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for live_stream_event in response['results']: print('live stream event with id "%s" and name "%s" will be activated.' % (live_stream_event['id'], live_stream_event['name'])) diff --git a/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py b/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py index b8b4a57d..0bfc1bca 100755 --- a/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py @@ -34,7 +34,7 @@ def main(client): while True: response = live_stream_event_service.getLiveStreamEventsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for live_stream_event in response['results']: # Print out some information for each live stream event. print('live stream event with id "%d" and name "%s" was found.' % diff --git a/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py b/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py index 2023e9ae..4bc9cf2e 100755 --- a/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py +++ b/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py @@ -44,7 +44,7 @@ def main(client, live_stream_event_id): # Set adTags to be updated. new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE'] - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local live stream event by changing its attributes. updated_live_stream_events = [] for live_stream_event in response['results']: diff --git a/examples/dfp/v201802/native_style_service/get_all_native_styles.py b/examples/dfp/v201802/native_style_service/get_all_native_styles.py index f5a8cc41..4025475b 100755 --- a/examples/dfp/v201802/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201802/native_style_service/get_all_native_styles.py @@ -33,7 +33,7 @@ def main(client): while True: response = native_style_service.getNativeStylesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for native_style in response['results']: # Print out some information for each native style. print('Native style with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/order_service/approve_orders.py b/examples/dfp/v201802/order_service/approve_orders.py index 8d87302c..92b81b91 100755 --- a/examples/dfp/v201802/order_service/approve_orders.py +++ b/examples/dfp/v201802/order_service/approve_orders.py @@ -41,7 +41,7 @@ def main(client): # Get orders by statement. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for order in response['results']: print ('Order with id "%s", name "%s", and status "%s" will be ' diff --git a/examples/dfp/v201802/order_service/get_all_orders.py b/examples/dfp/v201802/order_service/get_all_orders.py index c2f7f0c1..13f2a568 100755 --- a/examples/dfp/v201802/order_service/get_all_orders.py +++ b/examples/dfp/v201802/order_service/get_all_orders.py @@ -31,7 +31,7 @@ def main(client): # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for order in response['results']: # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], diff --git a/examples/dfp/v201802/order_service/get_orders_starting_soon.py b/examples/dfp/v201802/order_service/get_orders_starting_soon.py index eefdb762..376b4214 100755 --- a/examples/dfp/v201802/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201802/order_service/get_orders_starting_soon.py @@ -42,7 +42,7 @@ def main(client): # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for order in response['results']: # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], diff --git a/examples/dfp/v201802/order_service/update_orders.py b/examples/dfp/v201802/order_service/update_orders.py index 761c8f47..aadfd1dd 100755 --- a/examples/dfp/v201802/order_service/update_orders.py +++ b/examples/dfp/v201802/order_service/update_orders.py @@ -39,7 +39,7 @@ def main(client, order_id): # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local order object by changing its notes. updated_orders = [] for order in response['results']: diff --git a/examples/dfp/v201802/package_service/get_all_packages.py b/examples/dfp/v201802/package_service/get_all_packages.py index f00ded0c..d8598da6 100755 --- a/examples/dfp/v201802/package_service/get_all_packages.py +++ b/examples/dfp/v201802/package_service/get_all_packages.py @@ -31,7 +31,7 @@ def main(client): # through until all packages have been retrieved. while True: response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for pkg in response['results']: # Print out some information for each package. print( diff --git a/examples/dfp/v201802/package_service/get_in_progress_packages.py b/examples/dfp/v201802/package_service/get_in_progress_packages.py index ed7c1af0..5adbd144 100755 --- a/examples/dfp/v201802/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201802/package_service/get_in_progress_packages.py @@ -32,7 +32,7 @@ def main(client): # through until all packages have been retrieved. while True: response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for pkg in response['results']: # Print out some information for each package. print( diff --git a/examples/dfp/v201802/placement_service/create_placements.py b/examples/dfp/v201802/placement_service/create_placements.py index cb1e5335..4d3a2c9c 100755 --- a/examples/dfp/v201802/placement_service/create_placements.py +++ b/examples/dfp/v201802/placement_service/create_placements.py @@ -61,7 +61,7 @@ def main(client): response = inventory_service.getAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Separate the ad units by size. for ad_unit in response['results']: if 'adUnitSizes' in ad_unit: diff --git a/examples/dfp/v201802/placement_service/get_active_placements.py b/examples/dfp/v201802/placement_service/get_active_placements.py index 5e9fa95a..296781aa 100755 --- a/examples/dfp/v201802/placement_service/get_active_placements.py +++ b/examples/dfp/v201802/placement_service/get_active_placements.py @@ -33,7 +33,7 @@ def main(client): while True: response = placement_service.getPlacementsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for placement in response['results']: # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/placement_service/get_all_placements.py b/examples/dfp/v201802/placement_service/get_all_placements.py index 2217dedf..10feefbe 100755 --- a/examples/dfp/v201802/placement_service/get_all_placements.py +++ b/examples/dfp/v201802/placement_service/get_all_placements.py @@ -32,7 +32,7 @@ def main(client): while True: response = placement_service.getPlacementsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for placement in response['results']: # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py index 134fb4b4..277b1ef7 100755 --- a/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py @@ -33,7 +33,7 @@ def main(client): while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' diff --git a/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py index caf5b5e6..88c7b942 100755 --- a/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py @@ -36,7 +36,7 @@ def main(client, rate_card_id): while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' diff --git a/examples/dfp/v201802/premium_rate_service/update_premium_rates.py b/examples/dfp/v201802/premium_rate_service/update_premium_rates.py index 05594e2f..48d70196 100755 --- a/examples/dfp/v201802/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201802/premium_rate_service/update_premium_rates.py @@ -43,7 +43,7 @@ def main(client, premium_rate_id): response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_premium_rates = [] for premium_rate in response['results']: # Create a flat fee based premium rate value with a 10% increase. diff --git a/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py index 78937795..23105a5f 100755 --- a/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_package_item_service.getProductPackageItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package_item in response['results']: # Print out some information for each product package item. print('Product package item with ID "%d", product id "%d", and product ' diff --git a/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py index 7d14808a..a74a5576 100755 --- a/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py @@ -36,7 +36,7 @@ def main(client, product_package_id): while True: response = product_package_item_service.getProductPackageItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package_item in response['results']: # Print out some information for each product package item. print('Product package item with ID "%d", product ID "%d", and product ' diff --git a/examples/dfp/v201802/product_package_service/get_active_product_packages.py b/examples/dfp/v201802/product_package_service/get_active_product_packages.py index 0782a636..978a69a6 100755 --- a/examples/dfp/v201802/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201802/product_package_service/get_active_product_packages.py @@ -34,7 +34,7 @@ def main(client): while True: response = product_package_service.getProductPackagesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package in response['results']: # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/product_package_service/get_all_product_packages.py b/examples/dfp/v201802/product_package_service/get_all_product_packages.py index 51227e64..5f80a5ff 100755 --- a/examples/dfp/v201802/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201802/product_package_service/get_all_product_packages.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_package_service.getProductPackagesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package in response['results']: # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/product_service/get_all_products.py b/examples/dfp/v201802/product_service/get_all_products.py index 9b9fc377..d51ecd13 100755 --- a/examples/dfp/v201802/product_service/get_all_products.py +++ b/examples/dfp/v201802/product_service/get_all_products.py @@ -31,7 +31,7 @@ def main(client): # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product in response['results']: # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/product_service/get_products_for_product_template.py b/examples/dfp/v201802/product_service/get_products_for_product_template.py index abb5c1ba..882c3a04 100755 --- a/examples/dfp/v201802/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201802/product_service/get_products_for_product_template.py @@ -35,7 +35,7 @@ def main(client, product_template_id): # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product in response['results']: # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/product_service/update_products.py b/examples/dfp/v201802/product_service/update_products.py index 8697a04c..3f25f4bd 100755 --- a/examples/dfp/v201802/product_service/update_products.py +++ b/examples/dfp/v201802/product_service/update_products.py @@ -40,7 +40,7 @@ def main(client, product_id): # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local product object by changing its notes. updated_products = [] for product in response['results']: diff --git a/examples/dfp/v201802/product_template_service/activate_product_templates.py b/examples/dfp/v201802/product_template_service/activate_product_templates.py index cf5dc6b0..2454c04e 100755 --- a/examples/dfp/v201802/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201802/product_template_service/activate_product_templates.py @@ -45,7 +45,7 @@ def main(client, product_template_id): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: print ('Product template with id "%s" and name "%s" will be ' 'activated.' % (product_template['id'], diff --git a/examples/dfp/v201802/product_template_service/get_all_product_templates.py b/examples/dfp/v201802/product_template_service/get_all_product_templates.py index 11f57816..2cbb9279 100755 --- a/examples/dfp/v201802/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201802/product_template_service/get_all_product_templates.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py index 97b5ef0f..48fcc5df 100755 --- a/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py @@ -34,7 +34,7 @@ def main(client): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/product_template_service/update_product_templates.py b/examples/dfp/v201802/product_template_service/update_product_templates.py index 36dda17f..c899305b 100755 --- a/examples/dfp/v201802/product_template_service/update_product_templates.py +++ b/examples/dfp/v201802/product_template_service/update_product_templates.py @@ -43,7 +43,7 @@ def main(client, product_template_id): response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local product template object by appending a new geo-target. for product_template in response['results']: # Create geo-targeting for Canada to append. diff --git a/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py index 7d0d0918..48568c1a 100755 --- a/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py @@ -45,7 +45,7 @@ def main(client, proposal_line_item_id): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: print ('Proposal line item with id "%s", ' 'belonging to proposal id "%s", and ' diff --git a/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py index a448e012..73442848 100755 --- a/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py @@ -33,7 +33,7 @@ def main(client): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 29df584f..3f63b344 100755 --- a/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -36,7 +36,7 @@ def main(client, proposal_id): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py index 4a559c5f..6ca41d6f 100755 --- a/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py @@ -44,7 +44,7 @@ def main(client, proposal_line_item_id): response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each the proposal line item's notes field. proposal_line_item = response['results'][0] proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.' diff --git a/examples/dfp/v201802/proposal_service/get_all_proposals.py b/examples/dfp/v201802/proposal_service/get_all_proposals.py index ee9a6082..30eebe62 100755 --- a/examples/dfp/v201802/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201802/proposal_service/get_all_proposals.py @@ -31,7 +31,7 @@ def main(client): # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal in response['results']: # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py index 19c3fa3d..eded3d02 100755 --- a/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py @@ -32,7 +32,7 @@ def main(client): # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal in response['results']: # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py index b68da967..428f4c83 100755 --- a/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py @@ -37,7 +37,7 @@ def main(client, proposal_id): # Get proposals by statement. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: print ('Programmatic proposal with id "%s", name "%s", and status ' diff --git a/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py index 600a5763..ee79183f 100755 --- a/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py @@ -39,7 +39,7 @@ def main(client, proposal_id): # Get proposals by statement. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: print ('Proposal with id "%s", name "%s", and status "%s" will be' diff --git a/examples/dfp/v201802/proposal_service/update_proposals.py b/examples/dfp/v201802/proposal_service/update_proposals.py index 3cbe6e7d..540cff7c 100755 --- a/examples/dfp/v201802/proposal_service/update_proposals.py +++ b/examples/dfp/v201802/proposal_service/update_proposals.py @@ -40,7 +40,7 @@ def main(client, proposal_id): # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local proposal object by changing its notes. updated_proposals = [] for proposal in response['results']: diff --git a/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py index c0fd27a7..4857906d 100755 --- a/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py @@ -32,7 +32,7 @@ def main(client): while True: response = rate_card_service.getRateCardsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for rate_card in response['results']: # Print out some information for each rate card. print('Rate card with ID "%d", name "%s", and currency code "%s" was ' diff --git a/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py index b413ebda..bd37d570 100755 --- a/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py @@ -34,7 +34,7 @@ def main(client): while True: response = rate_card_service.getRateCardsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for rate_card in response['results']: # Print out some information for each rate card. print( diff --git a/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index bbb62cd9..dac50e46 100755 --- a/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -51,7 +51,7 @@ def main(client): page = (reconciliation_line_item_report_service .getReconciliationLineItemReportsByStatement( statement.ToStatement())) - if 'results' in page: + if 'results' in page and len(page['results']): result_set_size += page['totalResultSetSize'] # Iterate over individual results in the page. for line_item_report in page['results']: diff --git a/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 5fd1484e..95c34b0d 100755 --- a/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -39,7 +39,7 @@ def main(client, reconciliation_report_id): reconciliation_order_report_service .getReconciliationOrderReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_order_report in response['results']: # Print out some information for each reconciliation order report. print('Reconciliation order report with ID "%d" and status "%s" was ' diff --git a/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 5efaa779..1557145b 100755 --- a/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -43,7 +43,7 @@ def main(client, reconciliation_report_id): reconciliation_report_row_service .getReconciliationReportRowsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report_row in response['results']: # Print out some information for each reconciliation report row. print('Reconciliation report row with ID "%d", reconciliation source ' diff --git a/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py index 7c465090..c42b0dd3 100755 --- a/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py @@ -35,7 +35,7 @@ def main(client): reconciliation_report_service .getReconciliationReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report in response['results']: # Print out some information for each reconciliation report. print( diff --git a/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index e6e12730..938ba4fa 100755 --- a/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -43,7 +43,7 @@ def main(client): reconciliation_report_service .getReconciliationReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report in response['results']: # Print out some information for each reconciliation report. print( diff --git a/examples/dfp/v201802/report_service/run_report_with_custom_fields.py b/examples/dfp/v201802/report_service/run_report_with_custom_fields.py index d1f76e9e..efdc3372 100755 --- a/examples/dfp/v201802/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201802/report_service/run_report_with_custom_fields.py @@ -44,7 +44,7 @@ def main(client, order_id): while True: response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Get custom field IDs from the line items of an order. for line_item in response['results']: if 'customFieldValues' in line_item: diff --git a/examples/dfp/v201802/report_service/run_saved_query.py b/examples/dfp/v201802/report_service/run_saved_query.py index ca0815df..a0fccfae 100755 --- a/examples/dfp/v201802/report_service/run_saved_query.py +++ b/examples/dfp/v201802/report_service/run_saved_query.py @@ -42,7 +42,7 @@ def main(client, saved_query_id): response = report_service.getSavedQueriesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): saved_query = response['results'][0] if saved_query['isCompatibleWithApiVersion']: diff --git a/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py index b850097f..656b4855 100755 --- a/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -41,7 +41,7 @@ def main(client): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: print ('Suggested ad unit with id "%s", and number of requests "%s"' diff --git a/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py index d8f8e923..3cabf8b5 100755 --- a/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -33,7 +33,7 @@ def main(client): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for suggested_ad_unit in response['results']: # Print out some information for each suggested ad unit. print( diff --git a/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 7c8fbdbe..c8d380a2 100755 --- a/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -36,7 +36,7 @@ def main(client, num_requests): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for suggested_ad_unit in response['results']: # Print out some information for each suggested ad unit. print( diff --git a/examples/dfp/v201802/team_service/get_all_teams.py b/examples/dfp/v201802/team_service/get_all_teams.py index 11e8653e..3c012fc5 100755 --- a/examples/dfp/v201802/team_service/get_all_teams.py +++ b/examples/dfp/v201802/team_service/get_all_teams.py @@ -31,7 +31,7 @@ def main(client): # through until all teams have been retrieved. while True: response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for team in response['results']: # Print out some information for each team. print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], diff --git a/examples/dfp/v201802/team_service/update_teams.py b/examples/dfp/v201802/team_service/update_teams.py index 2e6a8c45..6527f02a 100755 --- a/examples/dfp/v201802/team_service/update_teams.py +++ b/examples/dfp/v201802/team_service/update_teams.py @@ -44,7 +44,7 @@ def main(client, team_id): # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_teams = [] # Update each local team object by changing its description. for team in response['results']: diff --git a/examples/dfp/v201802/user_service/get_all_users.py b/examples/dfp/v201802/user_service/get_all_users.py index 36c26a79..5e043c1f 100755 --- a/examples/dfp/v201802/user_service/get_all_users.py +++ b/examples/dfp/v201802/user_service/get_all_users.py @@ -31,7 +31,7 @@ def main(client): # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user in response['results']: # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], diff --git a/examples/dfp/v201802/user_service/get_user_by_email_address.py b/examples/dfp/v201802/user_service/get_user_by_email_address.py index 0e492886..ddb8f015 100755 --- a/examples/dfp/v201802/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201802/user_service/get_user_by_email_address.py @@ -34,7 +34,7 @@ def main(client, email_address): # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user in response['results']: # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], diff --git a/examples/dfp/v201802/user_service/update_users.py b/examples/dfp/v201802/user_service/update_users.py index 2786043e..395bbf51 100755 --- a/examples/dfp/v201802/user_service/update_users.py +++ b/examples/dfp/v201802/user_service/update_users.py @@ -38,7 +38,7 @@ def main(client, user_id): # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): users = response['results'] for user in users: user['name'] += ' Sr.' diff --git a/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py index 631a9734..f867ce9f 100755 --- a/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py @@ -33,7 +33,7 @@ def main(client): while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user_team_association in response['results']: # Print out some information for each user team association. print('User team association with team id "%d" and user id "%d" was ' diff --git a/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py index 165a24e6..4f303dfb 100755 --- a/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py @@ -36,7 +36,7 @@ def main(client, user_id): while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user_team_association in response['results']: # Print out some information for each user team association. print('User team association with user ID "%d" and team ID "%d" was ' diff --git a/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py index 4f88e43f..e6e92014 100755 --- a/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py @@ -48,7 +48,7 @@ def main(client, user_id): response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_user_team_associations = [] # Update each local user team association to read only access. for user_team_association in response['results']: diff --git a/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py index e65fd9f8..a5d0d50f 100755 --- a/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py @@ -46,7 +46,7 @@ def main(client, proposal_id): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for workflow_approval_request in response['results']: print ('Workflow approval request with id "%s" will be' diff --git a/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py index 7dd04f12..08483be0 100755 --- a/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py @@ -37,7 +37,7 @@ def main(client): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for workflow_request in response['results']: # Print out some information for each workflow request. print('Workflow request with ID "%d", entity type "%s", and entity ID ' diff --git a/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py index 9ed72aac..2a4ea889 100755 --- a/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py @@ -37,7 +37,7 @@ def main(client): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for workflow_request in response['results']: # Print out some information for each workflow request. print('Workflow request with ID "%d", entity type "%s", and entity ID ' diff --git a/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py index d682dfdc..7d66ba4a 100755 --- a/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -46,7 +46,7 @@ def main(client, proposal_id): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for workflow_request in response['results']: print ('Workflow external condition request with id "%s" for %s ' diff --git a/examples/dfp/v201805/activity_group_service/get_active_activity_groups.py b/examples/dfp/v201805/activity_group_service/get_active_activity_groups.py index 39873e5b..077aa152 100755 --- a/examples/dfp/v201805/activity_group_service/get_active_activity_groups.py +++ b/examples/dfp/v201805/activity_group_service/get_active_activity_groups.py @@ -34,7 +34,7 @@ def main(client): while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for activity_group in response['results']: # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/activity_group_service/get_all_activity_groups.py b/examples/dfp/v201805/activity_group_service/get_all_activity_groups.py index 6e9a1947..3ce7d043 100755 --- a/examples/dfp/v201805/activity_group_service/get_all_activity_groups.py +++ b/examples/dfp/v201805/activity_group_service/get_all_activity_groups.py @@ -33,7 +33,7 @@ def main(client): while True: response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for activity_group in response['results']: # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/activity_group_service/update_activity_groups.py b/examples/dfp/v201805/activity_group_service/update_activity_groups.py index 0a5f87f9..62fe1f15 100755 --- a/examples/dfp/v201805/activity_group_service/update_activity_groups.py +++ b/examples/dfp/v201805/activity_group_service/update_activity_groups.py @@ -48,7 +48,7 @@ def main(client, activity_group_id, advertiser_company_id): # Get activity groups by statement. response = activity_group_service.getActivityGroupsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_activity_groups = [] for activity_group in response['results']: activity_group['companyIds'].append(advertiser_company_id) diff --git a/examples/dfp/v201805/activity_service/get_active_activities.py b/examples/dfp/v201805/activity_service/get_active_activities.py index 6de67205..dfb753e1 100755 --- a/examples/dfp/v201805/activity_service/get_active_activities.py +++ b/examples/dfp/v201805/activity_service/get_active_activities.py @@ -33,7 +33,7 @@ def main(client): while True: response = activity_service.getActivitiesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for activity in response['results']: # Print out some information for each activity. print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201805/activity_service/get_all_activities.py b/examples/dfp/v201805/activity_service/get_all_activities.py index 8cb0ffe1..84e91925 100755 --- a/examples/dfp/v201805/activity_service/get_all_activities.py +++ b/examples/dfp/v201805/activity_service/get_all_activities.py @@ -32,7 +32,7 @@ def main(client): while True: response = activity_service.getActivitiesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for activity in response['results']: # Print out some information for each activity. print('Activity with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/activity_service/update_activities.py b/examples/dfp/v201805/activity_service/update_activities.py index 95007511..c9344fc7 100755 --- a/examples/dfp/v201805/activity_service/update_activities.py +++ b/examples/dfp/v201805/activity_service/update_activities.py @@ -46,7 +46,7 @@ def main(client, activity_id): # Get activities by statement. response = activity_service.getActivitiesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_activities = [] for activity in response['results']: # Update the expected URL. diff --git a/examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py b/examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py index 412b91e2..22a2c302 100755 --- a/examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py @@ -33,7 +33,7 @@ def main(client): while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for audience_segment in response['results']: # Print out some information for each audience segment. print('Audience segment with ID "%d", name "%s", and size "%d" was ' diff --git a/examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py b/examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py index 6e68f588..2111ba3e 100755 --- a/examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py @@ -34,7 +34,7 @@ def main(client): while True: response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for audience_segment in response['results']: # Print out some information for each audience segment. print('Audience segment with ID "%d", name "%s", and size "%d" was ' diff --git a/examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py b/examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py index e0c2a855..58cb39a8 100755 --- a/examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py @@ -43,7 +43,7 @@ def main(client, audience_segment_id): response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): segments = response['results'] for segment in segments: diff --git a/examples/dfp/v201805/audience_segment_service/update_audience_segments.py b/examples/dfp/v201805/audience_segment_service/update_audience_segments.py index bf2e0980..2f0cef1d 100755 --- a/examples/dfp/v201805/audience_segment_service/update_audience_segments.py +++ b/examples/dfp/v201805/audience_segment_service/update_audience_segments.py @@ -43,7 +43,7 @@ def main(client, audience_segment_id): response = audience_segment_service.getAudienceSegmentsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_audience_segments = [] for audience_segment in response['results']: print ('Audience segment with id "%s" and name "%s" will be updated.' diff --git a/examples/dfp/v201805/base_rate_service/get_all_base_rates.py b/examples/dfp/v201805/base_rate_service/get_all_base_rates.py index 2835cbd5..390b3c89 100755 --- a/examples/dfp/v201805/base_rate_service/get_all_base_rates.py +++ b/examples/dfp/v201805/base_rate_service/get_all_base_rates.py @@ -32,7 +32,7 @@ def main(client): while True: response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' diff --git a/examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py b/examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py index 406a065d..278230e6 100755 --- a/examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py @@ -35,7 +35,7 @@ def main(client, rate_card_id): while True: response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' diff --git a/examples/dfp/v201805/base_rate_service/update_base_rates.py b/examples/dfp/v201805/base_rate_service/update_base_rates.py index 00cb642e..b95a6c81 100755 --- a/examples/dfp/v201805/base_rate_service/update_base_rates.py +++ b/examples/dfp/v201805/base_rate_service/update_base_rates.py @@ -42,7 +42,7 @@ def main(client, base_rate_id): response = base_rate_service.getBaseRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local base rate object by changing its value to $3 USD. new_rate = { 'currencyCode': 'USD', diff --git a/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py b/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py index d423e351..be37dcf9 100755 --- a/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py @@ -36,7 +36,7 @@ def main(client): while True: response = (cdn_config_service .getCdnConfigurationsByStatement(statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for cdn in response['results']: # Print out some information for each company. print('Found CDN configuration with type "%s" and name "%s".' diff --git a/examples/dfp/v201805/company_service/get_advertisers.py b/examples/dfp/v201805/company_service/get_advertisers.py index b046434d..b6a7ebee 100755 --- a/examples/dfp/v201805/company_service/get_advertisers.py +++ b/examples/dfp/v201805/company_service/get_advertisers.py @@ -32,7 +32,7 @@ def main(client): # through until all companies have been retrieved. while True: response = company_service.getCompaniesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for company in response['results']: # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201805/company_service/get_all_companies.py b/examples/dfp/v201805/company_service/get_all_companies.py index e089d9c2..0c97b344 100755 --- a/examples/dfp/v201805/company_service/get_all_companies.py +++ b/examples/dfp/v201805/company_service/get_all_companies.py @@ -31,7 +31,7 @@ def main(client): # through until all companies have been retrieved. while True: response = company_service.getCompaniesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for company in response['results']: # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % diff --git a/examples/dfp/v201805/company_service/update_companies.py b/examples/dfp/v201805/company_service/update_companies.py index 9fe4af37..cfeb2f8b 100755 --- a/examples/dfp/v201805/company_service/update_companies.py +++ b/examples/dfp/v201805/company_service/update_companies.py @@ -46,7 +46,7 @@ def main(client, company_id): # Get companies by statement. response = company_service.getCompaniesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_companies = [] for company in response['results']: company['comment'] += ' Updated.' diff --git a/examples/dfp/v201805/contact_service/get_all_contacts.py b/examples/dfp/v201805/contact_service/get_all_contacts.py index 780c4d2b..73232c59 100755 --- a/examples/dfp/v201805/contact_service/get_all_contacts.py +++ b/examples/dfp/v201805/contact_service/get_all_contacts.py @@ -31,7 +31,7 @@ def main(client): # through until all contacts have been retrieved. while True: response = contact_service.getContactsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for contact in response['results']: # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/contact_service/get_uninvited_contacts.py b/examples/dfp/v201805/contact_service/get_uninvited_contacts.py index 04d8f1e6..a1d228b7 100755 --- a/examples/dfp/v201805/contact_service/get_uninvited_contacts.py +++ b/examples/dfp/v201805/contact_service/get_uninvited_contacts.py @@ -32,7 +32,7 @@ def main(client): # through until all contacts have been retrieved. while True: response = contact_service.getContactsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for contact in response['results']: # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/contact_service/update_contacts.py b/examples/dfp/v201805/contact_service/update_contacts.py index ed8cfb8a..4c969cb3 100755 --- a/examples/dfp/v201805/contact_service/update_contacts.py +++ b/examples/dfp/v201805/contact_service/update_contacts.py @@ -47,7 +47,7 @@ def main(client, contact_id): response = contact_service.getContactsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_contacts = [] for contact in response['results']: contact['address'] = '123 New Street, New York, NY, 10011' diff --git a/examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 724b2128..b08afe1d 100755 --- a/examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -36,7 +36,7 @@ def main(client): content_metadata_key_hierarchy_service .getContentMetadataKeyHierarchiesByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for content_metadata_key_hierarchy in response['results']: # Print out some information for each content metadata key hierarchy. print('Content metadata key hierarchy with ID "%d" and name "%s" was ' diff --git a/examples/dfp/v201805/content_service/get_all_content.py b/examples/dfp/v201805/content_service/get_all_content.py index 996f9b9a..a80b8618 100755 --- a/examples/dfp/v201805/content_service/get_all_content.py +++ b/examples/dfp/v201805/content_service/get_all_content.py @@ -31,7 +31,7 @@ def main(client): # through until all content have been retrieved. while True: response = content_service.getContentByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for content in response['results']: # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/creative_service/get_all_creatives.py b/examples/dfp/v201805/creative_service/get_all_creatives.py index 20762dcb..6beec379 100755 --- a/examples/dfp/v201805/creative_service/get_all_creatives.py +++ b/examples/dfp/v201805/creative_service/get_all_creatives.py @@ -31,7 +31,7 @@ def main(client): # through until all creatives have been retrieved. while True: response = creative_service.getCreativesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative in response['results']: # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/creative_service/get_image_creatives.py b/examples/dfp/v201805/creative_service/get_image_creatives.py index 759bdd13..1620a908 100755 --- a/examples/dfp/v201805/creative_service/get_image_creatives.py +++ b/examples/dfp/v201805/creative_service/get_image_creatives.py @@ -32,7 +32,7 @@ def main(client): # through until all creatives have been retrieved. while True: response = creative_service.getCreativesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative in response['results']: # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/creative_service/update_creatives.py b/examples/dfp/v201805/creative_service/update_creatives.py index 580cba24..1817ca78 100755 --- a/examples/dfp/v201805/creative_service/update_creatives.py +++ b/examples/dfp/v201805/creative_service/update_creatives.py @@ -47,7 +47,7 @@ def main(client, image_creative_id): response = creative_service.getCreativesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local creative object by changing its destination URL. updated_creatives = [] for creative in response['results']: diff --git a/examples/dfp/v201805/creative_set_service/get_all_creative_sets.py b/examples/dfp/v201805/creative_set_service/get_all_creative_sets.py index 6a623305..e66b5b31 100755 --- a/examples/dfp/v201805/creative_set_service/get_all_creative_sets.py +++ b/examples/dfp/v201805/creative_set_service/get_all_creative_sets.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_set in response['results']: # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py b/examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py index ccf51553..7f4a9579 100755 --- a/examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py @@ -36,7 +36,7 @@ def main(client, master_creative_id): while True: response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_set in response['results']: # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/creative_set_service/update_creative_set.py b/examples/dfp/v201805/creative_set_service/update_creative_set.py index cd1ed1fc..1d3e1628 100755 --- a/examples/dfp/v201805/creative_set_service/update_creative_set.py +++ b/examples/dfp/v201805/creative_set_service/update_creative_set.py @@ -48,7 +48,7 @@ def main(client, creative_set_id, companion_creative_id): response = creative_set_service.getCreativeSetsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_created_sets = [] for creative_set in response['results']: creative_set['companionCreativeIds'].append(companion_creative_id) diff --git a/examples/dfp/v201805/creative_template_service/get_all_creative_templates.py b/examples/dfp/v201805/creative_template_service/get_all_creative_templates.py index bba87e16..cb6ba41d 100755 --- a/examples/dfp/v201805/creative_template_service/get_all_creative_templates.py +++ b/examples/dfp/v201805/creative_template_service/get_all_creative_templates.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_template in response['results']: # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py b/examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py index 8b77114b..8a307e75 100755 --- a/examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py @@ -34,7 +34,7 @@ def main(client): while True: response = creative_template_service.getCreativeTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_template in response['results']: # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py index 3a497e4b..e3248064 100755 --- a/examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py @@ -47,7 +47,7 @@ def main(client, label_id): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for creative_wrapper in response['results']: print ('Creative wrapper with ID "%s" applying to label "%s" with ' diff --git a/examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py b/examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py index 78c42a34..697538ee 100755 --- a/examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py @@ -34,7 +34,7 @@ def main(client): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_wrapper in response['results']: # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % diff --git a/examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py b/examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py index ed5bb88b..ea07926a 100755 --- a/examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py @@ -33,7 +33,7 @@ def main(client): while True: response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for creative_wrapper in response['results']: # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % diff --git a/examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py b/examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py index c291f687..d823635f 100755 --- a/examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py @@ -48,7 +48,7 @@ def main(client, creative_wrapper_id): response = creative_wrapper_service.getCreativeWrappersByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_creative_wrappers = [] for creative_wrapper in response['results']: creative_wrapper['ordering'] = 'OUTER' diff --git a/examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py index 14c46dcc..01dc372f 100755 --- a/examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -48,7 +48,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for custom_field in response['results']: print ('Custom field with ID "%s" and name "%s" will' diff --git a/examples/dfp/v201805/custom_field_service/get_all_custom_fields.py b/examples/dfp/v201805/custom_field_service/get_all_custom_fields.py index 080ac0e1..d753d9d9 100755 --- a/examples/dfp/v201805/custom_field_service/get_all_custom_fields.py +++ b/examples/dfp/v201805/custom_field_service/get_all_custom_fields.py @@ -33,7 +33,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_field in response['results']: # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py b/examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py index a01cca47..4534ab56 100755 --- a/examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py @@ -34,7 +34,7 @@ def main(client): while True: response = custom_field_service.getCustomFieldsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_field in response['results']: # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py b/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py index fb84fea0..c18198d4 100755 --- a/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py @@ -48,7 +48,7 @@ def main(client, key_name): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} key_statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py b/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py index e7d96621..00c44260 100755 --- a/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py @@ -48,7 +48,7 @@ def main(client, key_id): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} value_statement = (dfp.StatementBuilder() diff --git a/examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index d3dd5170..90745fca 100755 --- a/examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -34,7 +34,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( targeting_key_statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): all_keys.extend(response['results']) targeting_key_statement.offset += targeting_key_statement.limit else: @@ -51,7 +51,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_targeting_value in response['results']: # Print out some information for each custom targeting value. print('Custom targeting value with ID "%d", name "%s", display name ' diff --git a/examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 2c4a894b..39b7fc8d 100755 --- a/examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -36,7 +36,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingKeysByStatement( targeting_key_statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): all_keys.extend(response['results']) targeting_key_statement.offset += targeting_key_statement.limit else: @@ -53,7 +53,7 @@ def main(client): while True: response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for custom_targeting_value in response['results']: # Print out some information for each custom targeting value. print('Custom targeting value with ID "%d", name "%s", display name ' diff --git a/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py b/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py index 01a1eb3b..3e30b337 100755 --- a/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py @@ -42,7 +42,7 @@ def main(client, key_id): statement.ToStatement()) # Update each local custom targeting key object by changing its display name. - if 'results' in response: + if 'results' in response and len(response['results']): updated_keys = [] for key in response['results']: if not key['displayName']: diff --git a/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py b/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py index 074683e3..2c5074d1 100755 --- a/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py @@ -42,7 +42,7 @@ def main(client, key_id): statement.ToStatement()) # Update each local custom targeting value object by changing its name. - if 'results' in response: + if 'results' in response and len(response['results']): updated_values = [] for value in response['results']: if not value['displayName']: diff --git a/examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py b/examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py index d23410b5..abea1a8d 100755 --- a/examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py @@ -33,7 +33,7 @@ def main(client): while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for exchange_rate in response['results']: # Print out some information for each exchange rate. print( diff --git a/examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py index 152d1c77..1e434c83 100755 --- a/examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -36,7 +36,7 @@ def main(client, currency_code): while True: response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for exchange_rate in response['results']: # Print out some information for each exchange rate. print('Exchange rate with ID "%d", currency code "%s", and exchange ' diff --git a/examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py b/examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py index 270a48bc..dba98321 100755 --- a/examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py +++ b/examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py @@ -42,7 +42,7 @@ def main(client, exchange_rate_id): response = exchange_rate_service.getExchangeRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): exchange_rate = response['results'][0] # Update the exchange rate value to 1.5. diff --git a/examples/dfp/v201805/inventory_service/archive_ad_units.py b/examples/dfp/v201805/inventory_service/archive_ad_units.py index af33872a..fbe55bf6 100755 --- a/examples/dfp/v201805/inventory_service/archive_ad_units.py +++ b/examples/dfp/v201805/inventory_service/archive_ad_units.py @@ -49,7 +49,7 @@ def main(client, parent_id): while True: response = inventory_service.getAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: print ('Ad unit with ID "%s" and name "%s" will be archived.' % (ad_unit['id'], ad_unit['name'])) diff --git a/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py b/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py index bee36001..d424ebd8 100755 --- a/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py @@ -66,7 +66,7 @@ def get_all_ad_units(inventory_service): found_ad_units = [] while keep_iterating: page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in page: + if 'results' in page and len(page['results']): total_results = page['totalResultSetSize'] found_ad_units.extend(page['results']) diff --git a/examples/dfp/v201805/inventory_service/get_all_ad_units.py b/examples/dfp/v201805/inventory_service/get_all_ad_units.py index 06b7733e..702bc72f 100755 --- a/examples/dfp/v201805/inventory_service/get_all_ad_units.py +++ b/examples/dfp/v201805/inventory_service/get_all_ad_units.py @@ -31,7 +31,7 @@ def main(client): # through until all ad units have been retrieved. while True: response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py b/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py index 21678b0e..0d5fb79a 100755 --- a/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py +++ b/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py @@ -40,7 +40,7 @@ def main(client): # through until all ad units have been retrieved. while True: response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for ad_unit in response['results']: # Print out some information for each ad unit. print('Ad unit with ID "%s" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/inventory_service/update_ad_units.py b/examples/dfp/v201805/inventory_service/update_ad_units.py index 01e4514d..3adb7cf1 100755 --- a/examples/dfp/v201805/inventory_service/update_ad_units.py +++ b/examples/dfp/v201805/inventory_service/update_ad_units.py @@ -56,7 +56,7 @@ def main(client, ad_unit_id): 'environmentType': 'BROWSER' } - if 'results' in response: + if 'results' in response and len(response['results']): updated_ad_units = [] for ad_unit in response['results']: if 'adUnitSizes' not in ad_unit: diff --git a/examples/dfp/v201805/label_service/deactivate_labels.py b/examples/dfp/v201805/label_service/deactivate_labels.py index b2d025ba..5ab36860 100755 --- a/examples/dfp/v201805/label_service/deactivate_labels.py +++ b/examples/dfp/v201805/label_service/deactivate_labels.py @@ -39,7 +39,7 @@ def main(client): # Get labels by statement. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: print ('Label with id "%s" and name "%s" will be ' 'deactivated.' % (label['id'], label['name'])) diff --git a/examples/dfp/v201805/label_service/get_active_labels.py b/examples/dfp/v201805/label_service/get_active_labels.py index 41d7de6d..76827777 100755 --- a/examples/dfp/v201805/label_service/get_active_labels.py +++ b/examples/dfp/v201805/label_service/get_active_labels.py @@ -32,7 +32,7 @@ def main(client): # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], diff --git a/examples/dfp/v201805/label_service/get_all_labels.py b/examples/dfp/v201805/label_service/get_all_labels.py index f4c9ec1f..f5290edd 100755 --- a/examples/dfp/v201805/label_service/get_all_labels.py +++ b/examples/dfp/v201805/label_service/get_all_labels.py @@ -31,7 +31,7 @@ def main(client): # through until all labels have been retrieved. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for label in response['results']: # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], diff --git a/examples/dfp/v201805/label_service/update_labels.py b/examples/dfp/v201805/label_service/update_labels.py index 1430c929..b0718042 100755 --- a/examples/dfp/v201805/label_service/update_labels.py +++ b/examples/dfp/v201805/label_service/update_labels.py @@ -39,7 +39,7 @@ def main(client, label_id): # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local label object by changing the description. updated_labels = [] for label in response['results']: diff --git a/examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py b/examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py index 9db1f987..ca0b66ba 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py +++ b/examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py @@ -44,7 +44,7 @@ def main(client, line_item_id): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: print ('LICA with line item id "%s", creative id "%s", and status' ' "%s" will be deactivated.' % diff --git a/examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py b/examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py index 0d24a221..743a2a79 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py +++ b/examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py @@ -33,7 +33,7 @@ def main(client): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: diff --git a/examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py b/examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py index 2c8c83b8..920eeac1 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py @@ -36,7 +36,7 @@ def main(client, line_item_id): while True: response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for lica in response['results']: # Print out some information for each line item creative association. if 'creativeSetId' in lica: diff --git a/examples/dfp/v201805/line_item_creative_association_service/update_licas.py b/examples/dfp/v201805/line_item_creative_association_service/update_licas.py index a8498b4a..5aa84fa2 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/update_licas.py +++ b/examples/dfp/v201805/line_item_creative_association_service/update_licas.py @@ -38,7 +38,7 @@ def main(client): response = lica_service.getLineItemCreativeAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local LICA object by changing its destination URL. updated_licas = [] for lica in response['results']: diff --git a/examples/dfp/v201805/line_item_service/activate_line_items.py b/examples/dfp/v201805/line_item_service/activate_line_items.py index c8646a51..34c658cf 100755 --- a/examples/dfp/v201805/line_item_service/activate_line_items.py +++ b/examples/dfp/v201805/line_item_service/activate_line_items.py @@ -47,7 +47,7 @@ def main(client, order_id): while True: response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: print ('Line item with id "%s", belonging to order id "%s", and ' 'name "%s" will be activated.' % diff --git a/examples/dfp/v201805/line_item_service/get_all_line_items.py b/examples/dfp/v201805/line_item_service/get_all_line_items.py index f5a603c8..0b757e71 100755 --- a/examples/dfp/v201805/line_item_service/get_all_line_items.py +++ b/examples/dfp/v201805/line_item_service/get_all_line_items.py @@ -32,7 +32,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py b/examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py index b75ea1a8..905fd2c8 100755 --- a/examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py @@ -33,7 +33,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py b/examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py index 2d92cd8b..1ae113db 100755 --- a/examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py +++ b/examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py @@ -41,7 +41,7 @@ def main(client): while True: response = line_item_service.getLineItemsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for line_item in response['results']: # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/line_item_service/pause_line_items.py b/examples/dfp/v201805/line_item_service/pause_line_items.py index 40346fe2..c5085757 100755 --- a/examples/dfp/v201805/line_item_service/pause_line_items.py +++ b/examples/dfp/v201805/line_item_service/pause_line_items.py @@ -44,7 +44,7 @@ def main(client): # Iterate over paged results from the statement. while should_continue: page = line_item_service.getLineItemsByStatement(statement.ToStatement()) - if 'results' in page: + if 'results' in page and len(page['results']): result_set_size = page['totalResultSetSize'] # Iterate over individual results in the page. for line_item in page['results']: diff --git a/examples/dfp/v201805/line_item_service/update_line_items.py b/examples/dfp/v201805/line_item_service/update_line_items.py index 8386e7a2..6b2e0fd4 100755 --- a/examples/dfp/v201805/line_item_service/update_line_items.py +++ b/examples/dfp/v201805/line_item_service/update_line_items.py @@ -44,7 +44,7 @@ def main(client, order_id): response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local line item by changing its delivery rate type. updated_line_items = [] for line_item in response['results']: diff --git a/examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py b/examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py index 11c96a9a..b97b78cd 100755 --- a/examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py +++ b/examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py @@ -42,7 +42,7 @@ def main(client, live_stream_event_id): while True: response = live_stream_event_service.getLiveStreamEventsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for live_stream_event in response['results']: print('live stream event with id "%s" and name "%s" will be activated.' % (live_stream_event['id'], live_stream_event['name'])) diff --git a/examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py b/examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py index 5652fb1d..d2e7623f 100755 --- a/examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py @@ -34,7 +34,7 @@ def main(client): while True: response = live_stream_event_service.getLiveStreamEventsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for live_stream_event in response['results']: # Print out some information for each live stream event. print('live stream event with id "%d" and name "%s" was found.' % diff --git a/examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py b/examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py index b83ec6ca..382b879a 100755 --- a/examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py +++ b/examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py @@ -44,7 +44,7 @@ def main(client, live_stream_event_id): # Set adTags to be updated. new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE'] - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local live stream event by changing its attributes. updated_live_stream_events = [] for live_stream_event in response['results']: diff --git a/examples/dfp/v201805/native_style_service/get_all_native_styles.py b/examples/dfp/v201805/native_style_service/get_all_native_styles.py index a2908ad8..8f608773 100755 --- a/examples/dfp/v201805/native_style_service/get_all_native_styles.py +++ b/examples/dfp/v201805/native_style_service/get_all_native_styles.py @@ -33,7 +33,7 @@ def main(client): while True: response = native_style_service.getNativeStylesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for native_style in response['results']: # Print out some information for each native style. print('Native style with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/order_service/approve_orders.py b/examples/dfp/v201805/order_service/approve_orders.py index f3e667a8..6c47b89b 100755 --- a/examples/dfp/v201805/order_service/approve_orders.py +++ b/examples/dfp/v201805/order_service/approve_orders.py @@ -41,7 +41,7 @@ def main(client): # Get orders by statement. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for order in response['results']: print ('Order with id "%s", name "%s", and status "%s" will be ' diff --git a/examples/dfp/v201805/order_service/get_all_orders.py b/examples/dfp/v201805/order_service/get_all_orders.py index c376c2cc..d9424a63 100755 --- a/examples/dfp/v201805/order_service/get_all_orders.py +++ b/examples/dfp/v201805/order_service/get_all_orders.py @@ -31,7 +31,7 @@ def main(client): # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for order in response['results']: # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], diff --git a/examples/dfp/v201805/order_service/get_orders_starting_soon.py b/examples/dfp/v201805/order_service/get_orders_starting_soon.py index 1be982f8..ed9f4c32 100755 --- a/examples/dfp/v201805/order_service/get_orders_starting_soon.py +++ b/examples/dfp/v201805/order_service/get_orders_starting_soon.py @@ -42,7 +42,7 @@ def main(client): # through until all orders have been retrieved. while True: response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for order in response['results']: # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], diff --git a/examples/dfp/v201805/order_service/update_orders.py b/examples/dfp/v201805/order_service/update_orders.py index da67c9d1..cf3cb373 100755 --- a/examples/dfp/v201805/order_service/update_orders.py +++ b/examples/dfp/v201805/order_service/update_orders.py @@ -39,7 +39,7 @@ def main(client, order_id): # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local order object by changing its notes. updated_orders = [] for order in response['results']: diff --git a/examples/dfp/v201805/package_service/get_all_packages.py b/examples/dfp/v201805/package_service/get_all_packages.py index 0875b1c1..598a2efc 100755 --- a/examples/dfp/v201805/package_service/get_all_packages.py +++ b/examples/dfp/v201805/package_service/get_all_packages.py @@ -31,7 +31,7 @@ def main(client): # through until all packages have been retrieved. while True: response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for pkg in response['results']: # Print out some information for each package. print( diff --git a/examples/dfp/v201805/package_service/get_in_progress_packages.py b/examples/dfp/v201805/package_service/get_in_progress_packages.py index b0918e84..a3142c80 100755 --- a/examples/dfp/v201805/package_service/get_in_progress_packages.py +++ b/examples/dfp/v201805/package_service/get_in_progress_packages.py @@ -32,7 +32,7 @@ def main(client): # through until all packages have been retrieved. while True: response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for pkg in response['results']: # Print out some information for each package. print( diff --git a/examples/dfp/v201805/placement_service/create_placements.py b/examples/dfp/v201805/placement_service/create_placements.py index c37088f8..2a06f075 100755 --- a/examples/dfp/v201805/placement_service/create_placements.py +++ b/examples/dfp/v201805/placement_service/create_placements.py @@ -61,7 +61,7 @@ def main(client): response = inventory_service.getAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Separate the ad units by size. for ad_unit in response['results']: if 'adUnitSizes' in ad_unit: diff --git a/examples/dfp/v201805/placement_service/get_active_placements.py b/examples/dfp/v201805/placement_service/get_active_placements.py index 39999fd0..36d40ae8 100755 --- a/examples/dfp/v201805/placement_service/get_active_placements.py +++ b/examples/dfp/v201805/placement_service/get_active_placements.py @@ -33,7 +33,7 @@ def main(client): while True: response = placement_service.getPlacementsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for placement in response['results']: # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/placement_service/get_all_placements.py b/examples/dfp/v201805/placement_service/get_all_placements.py index 16561f3b..016b21c5 100755 --- a/examples/dfp/v201805/placement_service/get_all_placements.py +++ b/examples/dfp/v201805/placement_service/get_all_placements.py @@ -32,7 +32,7 @@ def main(client): while True: response = placement_service.getPlacementsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for placement in response['results']: # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py b/examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py index f88f70f6..47892106 100755 --- a/examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py +++ b/examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py @@ -33,7 +33,7 @@ def main(client): while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' diff --git a/examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py index 84fd6c4c..1d8e3df2 100755 --- a/examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py @@ -36,7 +36,7 @@ def main(client, rate_card_id): while True: response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' diff --git a/examples/dfp/v201805/premium_rate_service/update_premium_rates.py b/examples/dfp/v201805/premium_rate_service/update_premium_rates.py index bc1b97f8..f762c9bd 100755 --- a/examples/dfp/v201805/premium_rate_service/update_premium_rates.py +++ b/examples/dfp/v201805/premium_rate_service/update_premium_rates.py @@ -43,7 +43,7 @@ def main(client, premium_rate_id): response = premium_rate_service.getPremiumRatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_premium_rates = [] for premium_rate in response['results']: # Create a flat fee based premium rate value with a 10% increase. diff --git a/examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py b/examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py index bfee8248..a8b381be 100755 --- a/examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py +++ b/examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_package_item_service.getProductPackageItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package_item in response['results']: # Print out some information for each product package item. print('Product package item with ID "%d", product id "%d", and product ' diff --git a/examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py b/examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py index 68f18bc2..9e303462 100755 --- a/examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py @@ -36,7 +36,7 @@ def main(client, product_package_id): while True: response = product_package_item_service.getProductPackageItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package_item in response['results']: # Print out some information for each product package item. print('Product package item with ID "%d", product ID "%d", and product ' diff --git a/examples/dfp/v201805/product_package_service/get_active_product_packages.py b/examples/dfp/v201805/product_package_service/get_active_product_packages.py index ce6895bc..0eae55a9 100755 --- a/examples/dfp/v201805/product_package_service/get_active_product_packages.py +++ b/examples/dfp/v201805/product_package_service/get_active_product_packages.py @@ -34,7 +34,7 @@ def main(client): while True: response = product_package_service.getProductPackagesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package in response['results']: # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/product_package_service/get_all_product_packages.py b/examples/dfp/v201805/product_package_service/get_all_product_packages.py index 0284c676..4b948204 100755 --- a/examples/dfp/v201805/product_package_service/get_all_product_packages.py +++ b/examples/dfp/v201805/product_package_service/get_all_product_packages.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_package_service.getProductPackagesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_package in response['results']: # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/product_service/get_all_products.py b/examples/dfp/v201805/product_service/get_all_products.py index 5465d3af..b9045479 100755 --- a/examples/dfp/v201805/product_service/get_all_products.py +++ b/examples/dfp/v201805/product_service/get_all_products.py @@ -31,7 +31,7 @@ def main(client): # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product in response['results']: # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/product_service/get_products_for_product_template.py b/examples/dfp/v201805/product_service/get_products_for_product_template.py index d1e68df9..43b44cfe 100755 --- a/examples/dfp/v201805/product_service/get_products_for_product_template.py +++ b/examples/dfp/v201805/product_service/get_products_for_product_template.py @@ -35,7 +35,7 @@ def main(client, product_template_id): # through until all products have been retrieved. while True: response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product in response['results']: # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/product_service/update_products.py b/examples/dfp/v201805/product_service/update_products.py index 55797315..4b0f4036 100755 --- a/examples/dfp/v201805/product_service/update_products.py +++ b/examples/dfp/v201805/product_service/update_products.py @@ -40,7 +40,7 @@ def main(client, product_id): # Get products by statement. response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local product object by changing its notes. updated_products = [] for product in response['results']: diff --git a/examples/dfp/v201805/product_template_service/activate_product_templates.py b/examples/dfp/v201805/product_template_service/activate_product_templates.py index a6e68143..824e2ba1 100755 --- a/examples/dfp/v201805/product_template_service/activate_product_templates.py +++ b/examples/dfp/v201805/product_template_service/activate_product_templates.py @@ -45,7 +45,7 @@ def main(client, product_template_id): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: print ('Product template with id "%s" and name "%s" will be ' 'activated.' % (product_template['id'], diff --git a/examples/dfp/v201805/product_template_service/get_all_product_templates.py b/examples/dfp/v201805/product_template_service/get_all_product_templates.py index 4654b1a4..e82e198f 100755 --- a/examples/dfp/v201805/product_template_service/get_all_product_templates.py +++ b/examples/dfp/v201805/product_template_service/get_all_product_templates.py @@ -33,7 +33,7 @@ def main(client): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py b/examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py index 1df80e65..bb561a90 100755 --- a/examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py +++ b/examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py @@ -34,7 +34,7 @@ def main(client): while True: response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for product_template in response['results']: # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/product_template_service/update_product_templates.py b/examples/dfp/v201805/product_template_service/update_product_templates.py index 1533609d..29a137b6 100755 --- a/examples/dfp/v201805/product_template_service/update_product_templates.py +++ b/examples/dfp/v201805/product_template_service/update_product_templates.py @@ -43,7 +43,7 @@ def main(client, product_template_id): response = product_template_service.getProductTemplatesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local product template object by appending a new geo-target. for product_template in response['results']: # Create geo-targeting for Canada to append. diff --git a/examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py b/examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py index 9e6b738e..2d8495e8 100755 --- a/examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py @@ -45,7 +45,7 @@ def main(client, proposal_line_item_id): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: print ('Proposal line item with id "%s", ' 'belonging to proposal id "%s", and ' diff --git a/examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py b/examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py index 45bb7c33..c94464d0 100755 --- a/examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py @@ -33,7 +33,7 @@ def main(client): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py index e39257b6..8341ee11 100755 --- a/examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -36,7 +36,7 @@ def main(client, proposal_id): while True: response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal_line_item in response['results']: # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py b/examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py index ec2f4703..5f5fbb2c 100755 --- a/examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py @@ -44,7 +44,7 @@ def main(client, proposal_line_item_id): response = proposal_line_item_service.getProposalLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each the proposal line item's notes field. proposal_line_item = response['results'][0] proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.' diff --git a/examples/dfp/v201805/proposal_service/get_all_proposals.py b/examples/dfp/v201805/proposal_service/get_all_proposals.py index 9526dfd9..d527624c 100755 --- a/examples/dfp/v201805/proposal_service/get_all_proposals.py +++ b/examples/dfp/v201805/proposal_service/get_all_proposals.py @@ -31,7 +31,7 @@ def main(client): # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal in response['results']: # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py b/examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py index 04cfd9b3..823682b7 100755 --- a/examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py +++ b/examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py @@ -32,7 +32,7 @@ def main(client): # through until all proposals have been retrieved. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for proposal in response['results']: # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % diff --git a/examples/dfp/v201805/proposal_service/request_buyers_acceptance.py b/examples/dfp/v201805/proposal_service/request_buyers_acceptance.py index 70f8b1ae..3029f868 100755 --- a/examples/dfp/v201805/proposal_service/request_buyers_acceptance.py +++ b/examples/dfp/v201805/proposal_service/request_buyers_acceptance.py @@ -37,7 +37,7 @@ def main(client, proposal_id): # Get proposals by statement. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: print ('Programmatic proposal with id "%s", name "%s", and status ' diff --git a/examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py b/examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py index 09deb00b..1afca216 100755 --- a/examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py +++ b/examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py @@ -39,7 +39,7 @@ def main(client, proposal_id): # Get proposals by statement. while True: response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: print ('Proposal with id "%s", name "%s", and status "%s" will be' diff --git a/examples/dfp/v201805/proposal_service/update_proposals.py b/examples/dfp/v201805/proposal_service/update_proposals.py index 417fe19e..0223aff6 100755 --- a/examples/dfp/v201805/proposal_service/update_proposals.py +++ b/examples/dfp/v201805/proposal_service/update_proposals.py @@ -40,7 +40,7 @@ def main(client, proposal_id): # Get proposals by statement. response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Update each local proposal object by changing its notes. updated_proposals = [] for proposal in response['results']: diff --git a/examples/dfp/v201805/rate_card_service/get_all_rate_cards.py b/examples/dfp/v201805/rate_card_service/get_all_rate_cards.py index 8c5b7a71..929e8027 100755 --- a/examples/dfp/v201805/rate_card_service/get_all_rate_cards.py +++ b/examples/dfp/v201805/rate_card_service/get_all_rate_cards.py @@ -32,7 +32,7 @@ def main(client): while True: response = rate_card_service.getRateCardsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for rate_card in response['results']: # Print out some information for each rate card. print('Rate card with ID "%d", name "%s", and currency code "%s" was ' diff --git a/examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py b/examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py index e6f99eaa..0cc204a2 100755 --- a/examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py @@ -34,7 +34,7 @@ def main(client): while True: response = rate_card_service.getRateCardsByStatement(statement.ToStatement( )) - if 'results' in response: + if 'results' in response and len(response['results']): for rate_card in response['results']: # Print out some information for each rate card. print( diff --git a/examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 1c30a413..05138495 100755 --- a/examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -51,7 +51,7 @@ def main(client): page = (reconciliation_line_item_report_service .getReconciliationLineItemReportsByStatement( statement.ToStatement())) - if 'results' in page: + if 'results' in page and len(page['results']): result_set_size += page['totalResultSetSize'] # Iterate over individual results in the page. for line_item_report in page['results']: diff --git a/examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 4f40500d..6ecdb7b9 100755 --- a/examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -39,7 +39,7 @@ def main(client, reconciliation_report_id): reconciliation_order_report_service .getReconciliationOrderReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_order_report in response['results']: # Print out some information for each reconciliation order report. print('Reconciliation order report with ID "%d" and status "%s" was ' diff --git a/examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 9aa1e8f4..f0a9cdba 100755 --- a/examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -43,7 +43,7 @@ def main(client, reconciliation_report_id): reconciliation_report_row_service .getReconciliationReportRowsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report_row in response['results']: # Print out some information for each reconciliation report row. print('Reconciliation report row with ID "%d", reconciliation source ' diff --git a/examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py index 99ca0297..9e8745d3 100755 --- a/examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py @@ -35,7 +35,7 @@ def main(client): reconciliation_report_service .getReconciliationReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report in response['results']: # Print out some information for each reconciliation report. print( diff --git a/examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 5e24719b..9d80f156 100755 --- a/examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -43,7 +43,7 @@ def main(client): reconciliation_report_service .getReconciliationReportsByStatement( statement.ToStatement())) - if 'results' in response: + if 'results' in response and len(response['results']): for reconciliation_report in response['results']: # Print out some information for each reconciliation report. print( diff --git a/examples/dfp/v201805/report_service/run_report_with_custom_fields.py b/examples/dfp/v201805/report_service/run_report_with_custom_fields.py index b3db8e8b..0a80e0f9 100755 --- a/examples/dfp/v201805/report_service/run_report_with_custom_fields.py +++ b/examples/dfp/v201805/report_service/run_report_with_custom_fields.py @@ -44,7 +44,7 @@ def main(client, order_id): while True: response = line_item_service.getLineItemsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Get custom field IDs from the line items of an order. for line_item in response['results']: if 'customFieldValues' in line_item: diff --git a/examples/dfp/v201805/report_service/run_saved_query.py b/examples/dfp/v201805/report_service/run_saved_query.py index 03d0a556..7d098948 100755 --- a/examples/dfp/v201805/report_service/run_saved_query.py +++ b/examples/dfp/v201805/report_service/run_saved_query.py @@ -42,7 +42,7 @@ def main(client, saved_query_id): response = report_service.getSavedQueriesByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): saved_query = response['results'][0] if saved_query['isCompatibleWithApiVersion']: diff --git a/examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 385f20ee..9054bd60 100755 --- a/examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -41,7 +41,7 @@ def main(client): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: print ('Suggested ad unit with id "%s", and number of requests "%s"' diff --git a/examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py index 3e5b38b6..e27bde77 100755 --- a/examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -33,7 +33,7 @@ def main(client): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for suggested_ad_unit in response['results']: # Print out some information for each suggested ad unit. print( diff --git a/examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 639a2262..a9e4a499 100755 --- a/examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -36,7 +36,7 @@ def main(client, num_requests): while True: response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for suggested_ad_unit in response['results']: # Print out some information for each suggested ad unit. print( diff --git a/examples/dfp/v201805/team_service/get_all_teams.py b/examples/dfp/v201805/team_service/get_all_teams.py index aa9168b9..b4acc6f1 100755 --- a/examples/dfp/v201805/team_service/get_all_teams.py +++ b/examples/dfp/v201805/team_service/get_all_teams.py @@ -31,7 +31,7 @@ def main(client): # through until all teams have been retrieved. while True: response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for team in response['results']: # Print out some information for each team. print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], diff --git a/examples/dfp/v201805/team_service/update_teams.py b/examples/dfp/v201805/team_service/update_teams.py index 947534c5..9f16cd11 100755 --- a/examples/dfp/v201805/team_service/update_teams.py +++ b/examples/dfp/v201805/team_service/update_teams.py @@ -44,7 +44,7 @@ def main(client, team_id): # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_teams = [] # Update each local team object by changing its description. for team in response['results']: diff --git a/examples/dfp/v201805/user_service/get_all_users.py b/examples/dfp/v201805/user_service/get_all_users.py index 69f438b0..76444f71 100755 --- a/examples/dfp/v201805/user_service/get_all_users.py +++ b/examples/dfp/v201805/user_service/get_all_users.py @@ -31,7 +31,7 @@ def main(client): # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user in response['results']: # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], diff --git a/examples/dfp/v201805/user_service/get_user_by_email_address.py b/examples/dfp/v201805/user_service/get_user_by_email_address.py index 783cfdbb..45c993dc 100755 --- a/examples/dfp/v201805/user_service/get_user_by_email_address.py +++ b/examples/dfp/v201805/user_service/get_user_by_email_address.py @@ -34,7 +34,7 @@ def main(client, email_address): # through until all users have been retrieved. while True: response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user in response['results']: # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], diff --git a/examples/dfp/v201805/user_service/update_users.py b/examples/dfp/v201805/user_service/update_users.py index 289817f7..2a00295f 100755 --- a/examples/dfp/v201805/user_service/update_users.py +++ b/examples/dfp/v201805/user_service/update_users.py @@ -38,7 +38,7 @@ def main(client, user_id): # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): users = response['results'] for user in users: user['name'] += ' Sr.' diff --git a/examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py b/examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py index ff2d3b9c..d7b92bd2 100755 --- a/examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py +++ b/examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py @@ -33,7 +33,7 @@ def main(client): while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user_team_association in response['results']: # Print out some information for each user team association. print('User team association with team id "%d" and user id "%d" was ' diff --git a/examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py b/examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py index 30fd1bf5..81d4c05f 100755 --- a/examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py @@ -36,7 +36,7 @@ def main(client, user_id): while True: response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for user_team_association in response['results']: # Print out some information for each user team association. print('User team association with user ID "%d" and team ID "%d" was ' diff --git a/examples/dfp/v201805/user_team_association_service/update_user_team_associations.py b/examples/dfp/v201805/user_team_association_service/update_user_team_associations.py index b021ddaa..feb1d792 100755 --- a/examples/dfp/v201805/user_team_association_service/update_user_team_associations.py +++ b/examples/dfp/v201805/user_team_association_service/update_user_team_associations.py @@ -48,7 +48,7 @@ def main(client, user_id): response = user_team_association_service.getUserTeamAssociationsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): updated_user_team_associations = [] # Update each local user team association to read only access. for user_team_association in response['results']: diff --git a/examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py b/examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py index fb814d38..6ed95c5d 100755 --- a/examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py @@ -46,7 +46,7 @@ def main(client, proposal_id): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for workflow_approval_request in response['results']: print ('Workflow approval request with id "%s" will be' diff --git a/examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py b/examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py index 92b3bb63..9fbaccdc 100755 --- a/examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py @@ -37,7 +37,7 @@ def main(client): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for workflow_request in response['results']: # Print out some information for each workflow request. print('Workflow request with ID "%d", entity type "%s", and entity ID ' diff --git a/examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py b/examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py index ff657b8c..41c828e2 100755 --- a/examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py @@ -37,7 +37,7 @@ def main(client): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): for workflow_request in response['results']: # Print out some information for each workflow request. print('Workflow request with ID "%d", entity type "%s", and entity ID ' diff --git a/examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py index da7b8c1b..5fd72a9c 100755 --- a/examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -46,7 +46,7 @@ def main(client, proposal_id): while True: response = workflow_request_service.getWorkflowRequestsByStatement( statement.ToStatement()) - if 'results' in response: + if 'results' in response and len(response['results']): # Display results. for workflow_request in response['results']: print ('Workflow external condition request with id "%s" for %s ' From f9ce2a325b44759818fb833e743c11b05744a311 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 19 Jun 2018 10:42:05 -0400 Subject: [PATCH 113/180] Commiting latest changes. From 1258a35f1e975c1a5012252569b2218575d266ba Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Tue, 19 Jun 2018 11:00:00 -0400 Subject: [PATCH 114/180] Commiting latest changes. From e95a4c83ada087fda958f206296ae4551c2b8e6d Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Wed, 20 Jun 2018 09:53:16 -0400 Subject: [PATCH 115/180] Comitting latest changes. --- googleads/common.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googleads/common.py b/googleads/common.py index 61c15360..de5b2812 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '12.1.0' +VERSION = '12.2.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' From cd707dc897b93cf1bbb19355f7424e7834e7fb55 Mon Sep 17 00:00:00 2001 From: Gabe Rives-Corbett Date: Wed, 20 Jun 2018 09:55:20 -0400 Subject: [PATCH 116/180] Commiting latest changes. From 123dc01a1023f6719c644678181554ba406d5674 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 24 Jul 2018 15:37:23 -0400 Subject: [PATCH 117/180] AdWords v201710 sunset. --- ChangeLog | 3 + examples/adwords/v201710/__init__.py | 15 - .../v201710/account_management/__init__.py | 15 - .../account_management/accept_service_link.py | 62 --- .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 99 ---- .../get_account_hierarchy.py | 104 ---- .../v201710/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 226 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_click_to_download_ad.py | 125 ----- .../add_dynamic_page_feed.py | 295 ---------- .../add_dynamic_search_ads_campaign.py | 257 --------- ...add_expanded_text_ad_with_upgraded_urls.py | 113 ---- .../advanced_operations/add_html5_ad.py | 110 ---- .../add_responsive_display_ad.py | 158 ------ .../add_universal_app_campaign.py | 217 -------- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 171 ------ .../v201710/basic_operations/__init__.py | 15 - .../v201710/basic_operations/add_ad_groups.py | 115 ---- .../v201710/basic_operations/add_campaigns.py | 127 ----- .../basic_operations/add_expanded_text_ads.py | 74 --- .../v201710/basic_operations/add_keywords.py | 92 --- .../v201710/basic_operations/get_ad_groups.py | 76 --- .../v201710/basic_operations/get_campaigns.py | 68 --- .../get_campaigns_with_awql.py | 61 -- .../basic_operations/get_expanded_text_ads.py | 90 --- .../v201710/basic_operations/get_keywords.py | 87 --- .../v201710/basic_operations/pause_ad.py | 61 -- .../v201710/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 85 --- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201710/campaign_management/__init__.py | 15 - ...campaign_groups_and_performance_targets.py | 152 ----- .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 428 -------------- .../v201710/campaign_management/add_draft.py | 81 --- ...dd_keywords_using_incremental_batch_job.py | 257 --------- .../v201710/campaign_management/add_trial.py | 116 ---- .../get_all_disapproved_ads.py | 103 ---- .../get_all_disapproved_ads_with_awql.py | 88 --- .../get_campaigns_by_label.py | 83 --- .../campaign_management/graduate_trial.py | 79 --- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201710/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 131 ----- .../handle_policy_violation_error.py | 166 ------ .../adwords/v201710/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 156 ------ .../adwords/v201710/extensions/add_prices.py | 157 ------ .../v201710/extensions/add_site_links.py | 146 ----- .../extensions/add_site_links_using_feeds.py | 236 -------- .../adwords/v201710/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 526 ------------------ examples/adwords/v201710/misc/__init__.py | 15 - .../v201710/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201710/misc/upload_image.py | 65 --- .../v201710/misc/upload_media_bundle.py | 58 -- .../adwords/v201710/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 182 ------ ...aign_criterion_bid_modifier_simulations.py | 97 ---- .../get_keyword_bid_simulations.py | 99 ---- .../v201710/optimization/get_keyword_ideas.py | 113 ---- .../adwords/v201710/remarketing/__init__.py | 15 - .../v201710/remarketing/add_audience.py | 103 ---- .../remarketing/add_conversion_tracker.py | 66 --- .../remarketing/add_conversion_trackers.py | 103 ---- .../remarketing/add_crm_based_user_list.py | 101 ---- .../remarketing/add_rule_based_user_lists.py | 235 -------- .../upload_offline_call_conversions.py | 77 --- .../remarketing/upload_offline_conversions.py | 82 --- .../remarketing/upload_offline_data.py | 218 -------- .../adwords/v201710/reporting/__init__.py | 15 - ...oad_criteria_report_as_stream_with_awql.py | 79 --- ...criteria_report_as_stream_with_selector.py | 72 --- ...oad_criteria_report_as_string_with_awql.py | 58 -- ...criteria_report_as_string_with_selector.py | 55 -- .../download_criteria_report_with_awql.py | 58 -- .../download_criteria_report_with_selector.py | 56 -- .../v201710/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 244 -------- examples/adwords/v201710/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 279 ---------- .../v201710/shopping/add_product_scope.py | 104 ---- .../v201710/shopping/add_shopping_campaign.py | 172 ------ .../add_shopping_campaign_for_showcase_ads.py | 401 ------------- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201710/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 126 ----- .../add_customer_negative_criteria.py | 74 --- .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201710/targeting/lookup_location.py | 82 --- .../add_click_to_download_ad.py | 125 ----- .../add_click_to_download_ad.py | 125 ----- .../get_keyword_bid_simulations.py | 53 +- ...atic_proposals_for_non_sales_management.py | 14 +- .../get_geo_targets.py | 2 +- googleads/adwords.py | 58 +- googleads/common.py | 2 +- 110 files changed, 37 insertions(+), 11470 deletions(-) delete mode 100644 examples/adwords/v201710/__init__.py delete mode 100644 examples/adwords/v201710/account_management/__init__.py delete mode 100755 examples/adwords/v201710/account_management/accept_service_link.py delete mode 100755 examples/adwords/v201710/account_management/create_account.py delete mode 100755 examples/adwords/v201710/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201710/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201710/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py delete mode 100755 examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201710/basic_operations/__init__.py delete mode 100755 examples/adwords/v201710/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201710/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201710/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201710/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201710/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201710/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201710/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201710/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201710/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201710/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201710/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201710/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201710/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201710/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201710/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201710/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201710/campaign_management/__init__.py delete mode 100755 examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py delete mode 100755 examples/adwords/v201710/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201710/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201710/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201710/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201710/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201710/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201710/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201710/error_handling/__init__.py delete mode 100755 examples/adwords/v201710/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201710/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201710/extensions/__init__.py delete mode 100755 examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201710/extensions/add_prices.py delete mode 100755 examples/adwords/v201710/extensions/add_site_links.py delete mode 100755 examples/adwords/v201710/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201710/migration/__init__.py delete mode 100755 examples/adwords/v201710/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201710/misc/__init__.py delete mode 100755 examples/adwords/v201710/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201710/misc/upload_image.py delete mode 100755 examples/adwords/v201710/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201710/optimization/__init__.py delete mode 100755 examples/adwords/v201710/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201710/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201710/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201710/remarketing/__init__.py delete mode 100755 examples/adwords/v201710/remarketing/add_audience.py delete mode 100755 examples/adwords/v201710/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201710/remarketing/add_conversion_trackers.py delete mode 100755 examples/adwords/v201710/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201710/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201710/remarketing/upload_offline_call_conversions.py delete mode 100755 examples/adwords/v201710/remarketing/upload_offline_conversions.py delete mode 100755 examples/adwords/v201710/remarketing/upload_offline_data.py delete mode 100644 examples/adwords/v201710/reporting/__init__.py delete mode 100755 examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py delete mode 100755 examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py delete mode 100755 examples/adwords/v201710/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201710/reporting/download_criteria_report_with_selector.py delete mode 100755 examples/adwords/v201710/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201710/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201710/shopping/__init__.py delete mode 100755 examples/adwords/v201710/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201710/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201710/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py delete mode 100755 examples/adwords/v201710/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201710/targeting/__init__.py delete mode 100755 examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201710/targeting/add_customer_negative_criteria.py delete mode 100755 examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201710/targeting/lookup_location.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_click_to_download_ad.py diff --git a/ChangeLog b/ChangeLog index 9882eca8..b288b724 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +13.0.0 -- 07/25/18 +- Removed support for AdWords v201710. + 12.2.0 -- 06/18/18 - Fixed some DFP examples that would loop forever with Zeep. diff --git a/examples/adwords/v201710/__init__.py b/examples/adwords/v201710/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201710/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201710/account_management/__init__.py b/examples/adwords/v201710/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201710/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201710/account_management/accept_service_link.py b/examples/adwords/v201710/account_management/accept_service_link.py deleted file mode 100755 index 522f8305..00000000 --- a/examples/adwords/v201710/account_management/accept_service_link.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' - - -def main(client, service_link_id): - # Initialize appropriate service. - customer_service = client.GetService( - 'CustomerService', version='v201710') - - # Create the operation to set the status to ACTIVE. - operations = [{ - 'operator': 'SET', - 'operand': { - 'serviceLinkId': service_link_id, - 'serviceType': 'MERCHANT_CENTER', - 'linkStatus': 'ACTIVE', - } - }] - - # Update the service link. - mutated_service_links = customer_service.mutateServiceLinks(operations) - - # Display results. - for mutated_service_link in mutated_service_links: - print ('Service link with service link ID "%s", type "%s" was updated ' - 'to status: "%s".' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201710/account_management/create_account.py b/examples/adwords/v201710/account_management/create_account.py deleted file mode 100755 index 8daaceb5..00000000 --- a/examples/adwords/v201710/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201710') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID "%s" was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/account_management/get_account_changes.py b/examples/adwords/v201710/account_management/get_account_changes.py deleted file mode 100755 index 5bd8dfc2..00000000 --- a/examples/adwords/v201710/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201710') - campaign_service = client.GetService('CampaignService', version='v201710') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id "%s" has change status "%s".' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id "%s" has change status "%s".' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/account_management/get_account_hierarchy.py b/examples/adwords/v201710/account_management/get_account_hierarchy.py deleted file mode 100755 index 2c3727bd..00000000 --- a/examples/adwords/v201710/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201710') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/__init__.py b/examples/adwords/v201710/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201710/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201710/advanced_operations/add_ad_customizer.py b/examples/adwords/v201710/advanced_operations/add_ad_customizer.py deleted file mode 100755 index 48042172..00000000 --- a/examples/adwords/v201710/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates ExpandedTextAds that use ad customizations for specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no ExpandedTextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201710') - - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'headlinePart2': 'Only {=%s.Price}' % feed_name, - 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': expanded_text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID "%s", type "%s", and status "%s".' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201710') - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name "%s" and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201710') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - operation = { - 'operator': 'ADD', - 'operand': feed_item - } - - return operation - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index d48ba4bf..00000000 --- a/examples/adwords/v201710/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201710') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 2bd5158a..00000000 --- a/examples/adwords/v201710/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Optionally, you may specify a landscape image. - # Here we download a demo image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open('http://goo.gl/9JmyKk').read().decode('utf-8') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - }, - { - 'name': 'landscapeImage', - 'fieldMedia': { - 'xsi_type': 'Image', - 'data': image_data - }, - 'type': 'IMAGE' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py deleted file mode 100755 index a3fd7125..00000000 --- a/examples/adwords/v201710/advanced_operations/add_dynamic_page_feed.py +++ /dev/null @@ -1,295 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. - -To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -from collections import namedtuple -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - -# Used to keep track of DSA page feed details. -_DSAFeedDetails = namedtuple( - '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) -# ID that corresponds to the labels. -DSA_LABEL_FIELD_ID = 2 -# The criterion type to be used for DSA page feeds. -DSA_PAGE_FEED_CRITERION_TYPE = 61 -DSA_PAGE_URL_LABEL = 'discounts' -# ID that corresponds to the page URLs. -DSA_PAGE_URLS_FIELD_ID = 1 - - -def main(client, campaign_id, ad_group_id): - # Get the page feed details. This code example creates a new feed, but you can - # fetch and re-use an existing feed. - feed_details = _CreateFeed(client) - _CreateFeedMapping(client, feed_details) - _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) - - # Associate the page feed with the campaign. - _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) - - # Optional: Target web pages matching the feed's label in the ad group. - _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) - - print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id - - -def _CreateFeed(client): - """Creates the feed for DSA page URLs. - - Args: - client: an AdWordsClient instance. - - Returns: - A _DSAFeedDetails instance containing details about the created feed. - """ - # Get the FeedService. - feed_service = client.GetService('FeedService', version='v201710') - - # Create operation. - operation = { - # Create the feed. - 'operand': { - 'name': 'DSA Feed %s' % uuid.uuid4(), - # Create attributes. - 'attributes': [ - {'type': 'URL_LIST', 'name': 'Page URL'}, - {'type': 'STRING_LIST', 'name': 'Label'} - ], - 'origin': 'USER' - }, - 'operator': 'ADD' - } - - # Add the feed. - feed = feed_service.mutate([operation])['value'][0] - return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], - feed['attributes'][1]['id']) - - -def _CreateFeedMapping(client, feed_details): - """Creates the feed mapping for DSA page feeds. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - """ - # Get the FeedMappingService. - feed_mapping_service = client.GetService('FeedMappingService', - version='v201710') - - # Create the operation. - operation = { - # Create the feed mapping. - 'operand': { - 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, - 'feedId': feed_details.feed_id, - # Map the feedAttributeIds to the fieldId constants. - 'attributeFieldMappings': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'fieldId': DSA_PAGE_URLS_FIELD_ID - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'fieldId': DSA_LABEL_FIELD_ID - } - ] - }, - 'operator': 'ADD' - } - - # Add the feed mapping. - feed_mapping_service.mutate([operation]) - - -def _CreateFeedItems(client, feed_details, label_name): - """Creates the page URLs in the DSA page feed. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - label_name: a str containing the page feed URL label. - """ - # Get the FeedItemService. - feed_item_service = client.GetService('FeedItemService', version='v201710') - - # For page feed URL recommendations and rules, see: - # https://support.google.com/adwords/answer/7166527 - urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', - 'http://www.example.com/discounts/hotel-deals?id={feeditem}', - 'http://www.example.com/discounts/flight-deals?id={feeditem}') - - # Create the operation. - operations = [{ - # Create the feed item. - 'operand': { - 'feedId': feed_details.feed_id, - 'attributeValues': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'stringValues': [url] - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'stringValues': [label_name] - } - ] - }, - 'operator': 'ADD' - } for url in urls] - - # Add the feed item. - feed_item_service.mutate(operations) - - -def _UpdateCampaignDSASetting(client, campaign_id, feed_id): - """Updates the campaign DSA setting to DSA pagefeeds. - - Args: - client: an AdWordsClient instance. - campaign_id: a str Campaign ID. - feed_id: a str page Feed ID. - - Raises: - ValueError: If the given campaign is found not to be a dynamic search ad - campaign. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201710') - - selector = { - 'fields': ['Id', 'Settings'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [campaign_id] - }] - } - - response = campaign_service.get(selector) - - if response['totalNumEntries']: - campaign = response['entries'][0] - else: - raise ValueError('No campaign with ID "%d" exists.' % campaign_id) - - if not campaign['settings']: - raise ValueError('This is not a DSA campaign.') - - dsa_setting = None - - campaign_settings = campaign['settings'] - - for setting in campaign_settings: - if setting['Setting.Type'] == 'DynamicSearchAdsSetting': - dsa_setting = setting - break - - if dsa_setting is None: - raise ValueError('This is not a DSA campaign.') - - dsa_setting['pageFeed'] = { - 'feedIds': [feed_id] - } - - # Optional: Specify whether only the supplied URLs should be used with your - # Dynamic Search Ads. - dsa_setting['useSuppliedUrlsOnly'] = True - - operation = { - 'operand': { - 'id': campaign_id, - 'settings': campaign_settings - }, - 'operator': 'SET' - } - - campaign_service.mutate([operation]) - print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( - campaign_id, feed_id) - - -def _AddDSATargeting(client, ad_group_id, label_name): - """Set custom targeting for the page feed URLs based on a list of labels. - - Args: - client: an AdWordsClient instance. - ad_group_id: a str AdGroup ID. - label_name: a str label name. - - Returns: - A suds.sudsobject.Object representing the newly created webpage criterion. - """ - # Get the AdGroupCriterionService. - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201710') - - # Create the operation. - operation = { - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Test criterion', - # Add a condition for label=specified_label_name. - 'conditions': [{ - 'operand': 'CUSTOM_LABEL', - 'argument': label_name - }], - } - }, - # Set a custom bid for this criterion - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 1500000 - } - }] - } - }, - 'operator': 'ADD' - } - - criterion = ad_group_criterion_service.mutate([operation])['value'][0] - print 'Web page criterion with ID "%d" and status "%s" was created.' % ( - criterion['criterion']['id'], criterion['userStatus']) - return criterion - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py deleted file mode 100755 index ba304ce5..00000000 --- a/examples/adwords/v201710/advanced_operations/add_dynamic_search_ads_campaign.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Dynamic Search Ads campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - budget = _CreateBudget(client) - campaign_id = _CreateCampaign(client, budget) - ad_group_id = _CreateAdGroup(client, campaign_id) - _CreateExpandedDSA(client, ad_group_id) - _AddWebPageCriteria(client, ad_group_id) - - print 'Dynamic Search Ads campaign setup is complete.' - - -def _CreateBudget(client): - """Creates the budget. - - Args: - client: an AdWordsClient instance. - - Returns: - a suds.sudsobject.Object representation of the created budget. - """ - budget_service = client.GetService('BudgetService', version='v201710') - - # Create the campaign budget - operation = { - 'operand': { - 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), - 'deliveryMethod': 'STANDARD', - 'amount': { - 'microAmount': 500000 - } - }, - 'operator': 'ADD' - } - - budget = budget_service.mutate([operation])['value'][0] - - print 'Budget with ID "%d" and name "%s" was created.' % ( - budget['budgetId'], budget['name']) - - return budget - - -def _CreateCampaign(client, budget): - """Creates the campaign. - - Args: - client: an AdWordsClient instance. - budget: a suds.sudsobject.Object representation of a created budget. - - Returns: - An integer campaign ID. - """ - campaign_service = client.GetService('CampaignService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # prevent the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'budget': budget, - # Required: Set the campaign's Dynamic Search Ad settings. - 'settings': [{ - 'xsi_type': 'DynamicSearchAdsSetting', - # Required: Set the domain name and language. - 'domainName': 'example.com', - 'languageCode': 'en' - }], - # Optional: Set the start date. - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - # Optional: Set the end date. - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - }] - - campaign = campaign_service.mutate(operations)['value'][0] - campaign_id = campaign['id'] - - print 'Campaign with ID "%d" and name "%s" was added.' % ( - campaign_id, campaign['name']) - - return campaign_id - - -def _CreateAdGroup(client, campaign_id): - """Creates an ad group. - - Args: - client: an AdWordsClient instance. - campaign_id: an integer campaign ID. - - Returns: - An integer ad group ID. - """ - ad_group_service = client.GetService('AdGroupService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'adGroupType': 'SEARCH_DYNAMIC_ADS', - 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '3000000' - }, - }] - } - } - }] - - ad_group = ad_group_service.mutate(operations)['value'][0] - ad_group_id = ad_group['id'] - - print 'Ad group with ID "%d" and name "%s" was created.' % ( - ad_group_id, ad_group['name']) - - return ad_group_id - - -def _CreateExpandedDSA(client, ad_group_id): - """Creates the expanded Dynamic Search Ad. - - Args: - client: an AdwordsClient instance. - ad_group_id: an integer ID of the ad group in which the DSA is added. - """ - # Get the AdGroupAdService. - ad_group_ad_service = client.GetService('AdGroupAdService') - - # Create the operation - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - # Create the expanded dynamic search ad. This ad will have its - # headline and final URL auto-generated at serving time according to - # domain name specific information provided by DynamicSearchAdsSetting - # at the campaign level. - 'ad': { - 'xsi_type': 'ExpandedDynamicSearchAd', - # Set the ad description. - 'description': 'Buy your tickets now!' - }, - # Optional: Set the status. - 'status': 'PAUSED', - } - }] - - # Create the ad. - ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] - - # Display the results. - print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' - 'added' % (ad['id'], ad['description'])) - - -def _AddWebPageCriteria(client, ad_group_id): - """Adds a web page criterion to target Dynamic Search Ads. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID of the ad group the criteria is being added to. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201710') - - operations = [{ - 'operator': 'ADD', - # Create biddable ad group criterion. - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion for special offers for children. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Special offers for children.', - 'conditions': [ - { - 'operand': 'URL', - 'argument': '/marscruise/children' - }, - { - 'operand': 'PAGE_TITLE', - 'argument': 'Special Offer' - } - ] - } - }, - 'userStatus': 'PAUSED', - # Optional: set a custom bid. - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000L - } - }] - } - } - }] - - criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( - criterion['criterion']['id'], criterion['adGroupId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py deleted file mode 100755 index 16e68459..00000000 --- a/examples/adwords/v201710/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Create the expanded text ad - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - expanded_text_ad['trackingUrlTemplate'] = ( - 'http://tracker.example.com/?season={_season}&promocode={_promocode}' - '&u={lpurl}' - ) - - expanded_text_ad['urlCustomParameters'] = { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': expanded_text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_html5_ad.py b/examples/adwords/v201710/advanced_operations/add_html5_ad.py deleted file mode 100755 index 9133e386..00000000 --- a/examples/adwords/v201710/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Create HTML5 media. - html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return response.read().decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index ec102603..00000000 --- a/examples/adwords/v201710/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - media_service = client.GetService('MediaService', version='v201710') - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - - try: - # Create marketing image. - marketing_image = _CreateImage(media_service, opener, - 'https://goo.gl/3b9Wfh') - - # Create square marketing image. - square_marketing_image = _CreateImage(media_service, opener, - 'https://goo.gl/mtt54n') - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': marketing_image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'], - # Optional: Set a square marketing image to the ad. - 'squareMarketingImage': { - 'mediaId': square_marketing_image['mediaId'] - }, - # Optional: Set call-to-action text. - 'callToActionText': 'Shop Now', - # Optional: Set dynamic display ad settings, composed of - # landscape logo image, promotion text, and price prefix. - 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( - media_service, opener), - # Whitelisted accounts only: Set color settings using - # hexadecimal numbers. - # Set allowFlexibleColor to False if you want your ads to render - # by always using your colors strictly. - # 'mainColor': '#0000ff', - # 'accentColor': '#ffff00', - # 'allowFlexibleColor': False - # Whitelisted accounts only: Set the format setting that the ad - # will be served in. - # 'formatSetting': 'NON_NATIVE' - - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -def _CreateImage(media_service, opener, url): - """Creates an image and uploads it to the server. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - url: a str URL used to load image data. - - Returns: - The image that was successfully uploaded. - """ - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open(url).read().decode('utf-8') - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - return media_service.upload(image)[0] - - -def _CreateDynamicDisplayAdSettings(media_service, opener): - """Creates settings for dynamic display ad. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - - Returns: - The dynamic display ad settings. - """ - image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') - - logo = { - 'type': 'IMAGE', - 'mediaId': image['mediaId'], - 'xsi_type': 'Image' - } - - dynamic_settings = { - 'landscapeLogoImage': logo, - 'pricePrefix': 'as low as', - 'promoText': 'Free shipping!', - 'xsi_type': 'DynamicSettings', - } - - return dynamic_settings - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py deleted file mode 100755 index 27db64ed..00000000 --- a/examples/adwords/v201710/advanced_operations/add_universal_app_campaign.py +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Universal App campaign. - -To get campaigns, run get_campaigns.py. To upload image assets for this -campaign, run upload_image.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201710') - - budget_id = CreateBudget(client) - - # Create the Universal App campaign. - universal_app_campaign = { - 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'MULTI_CHANNEL', - 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', - # Set the campaign's bidding strategy. Universal app campaigns only - # support TARGET_CPA bidding strategy. - 'biddingStrategyConfiguration': { - # Set the target CPA to $1 / app install. - 'biddingScheme': { - 'xsi_type': 'TargetCpaBiddingScheme', - 'targetCpa': { - 'microAmount': '1000000' - } - }, - 'biddingStrategyType': 'TARGET_CPA' - }, - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - - universal_app_campaign['settings'] = [ - # Set the campaign's assets and ad text ideas. These values will - # be used to generate ads. - { - 'xsi_type': 'UniversalAppCampaignSetting', - 'appId': 'com.labpixies.colordrips', - 'description1': 'A cool puzzle game', - 'description2': 'Remove connected blocks', - 'description3': '3 difficulty levels', - 'description4': '4 colorful fun skins', - # Optional: You can set up to 20 image assets for your campaign. - # See upload_image.py for an example on how to upload images. - # - # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] - } - ] - - # Optimize this campaign for getting new users for your app. - universal_app_campaign_setting = universal_app_campaign['settings'][0] - universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( - 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') - - # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, - # then also specify your in-app conversion types so AdWords can focus your - # campaign on people who are most likely to complete the corresponding in-app - # actions. - # - # Conversions type IDs can be retrieved using ConversionTrackerService.get. - # universal_app_campaign['selectiveOptimization'] = { - # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] - # } - - # Optional: Set the campaign settings for Advanced location options. - universal_app_campaign['settings'].append({ - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - }) - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': universal_app_campaign - }] - - campaigns = campaign_service.mutate(operations)['value'] - - # Display results. - if campaigns: - for campaign in campaigns: - print ('Universal App Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - # Optional: Set the campaign's location and language targeting. No other - # targeting criteria can be used for Universal App campaigns. - SetCampaignTargetingCriteria(client, campaign) - else: - print 'No Universal App campaigns were added.' - - -def CreateBudget(client): - """Creates a budget and returns its budgetId. - - Args: - client: An AdWordsClient instance. - - Returns: - An int budgetId for the created Budget. - """ - budget_service = client.GetService('BudgetService', version='v201710') - - # Create a budget. - budget = { - 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': False - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Create the budget and return its ID. - budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - - return budget_id - - -def SetCampaignTargetingCriteria(client, campaign): - """Sets targeting criteria for the given campaign. - - Args: - client: An AdWordsClient instance. - campaign: A suds object representing the campaign we wish to attach - targeting criteria. - """ - campaign_criterion_service = client.GetService('CampaignCriterionService') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - criteria = [ - { - 'xsi_type': 'Location', - 'id': 21137 # California - }, - { - 'xsi_type': 'Location', - 'id': 2484 # Mexico - }, - { - 'xsi_type': 'Language', - 'id': 1000 # English - }, - { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - ] - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign['id'], - 'criterion': criterion - } - } for criterion in criteria] - - response = campaign_criterion_service.mutate(operations) - - if response and 'value' in response: - # Display the added campaign targets. - for criterion in response['value']: - print ('Campaign criteria of type "%s" and id "%s" was added.' - % (criterion['criterion']['type'], - criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index e510d813..00000000 --- a/examples/adwords/v201710/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201710') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201710') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201710') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index 34c27532..00000000 --- a/examples/adwords/v201710/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201710') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201710') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 5e65078a..00000000 --- a/examples/adwords/v201710/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201710') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index ab912ab5..00000000 --- a/examples/adwords/v201710/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201710') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201710') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201710') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201710/basic_operations/__init__.py b/examples/adwords/v201710/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201710/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201710/basic_operations/add_ad_groups.py b/examples/adwords/v201710/basic_operations/add_ad_groups.py deleted file mode 100755 index e38048e1..00000000 --- a/examples/adwords/v201710/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201710') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/basic_operations/add_campaigns.py b/examples/adwords/v201710/basic_operations/add_campaigns.py deleted file mode 100755 index 7789c2c1..00000000 --- a/examples/adwords/v201710/basic_operations/add_campaigns.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201710') - budget_service = client.GetService('BudgetService', version='v201710') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201710/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index d3394999..00000000 --- a/examples/adwords/v201710/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/add_keywords.py b/examples/adwords/v201710/basic_operations/add_keywords.py deleted file mode 100755 index 4b1b0cec..00000000 --- a/examples/adwords/v201710/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201710') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id "%s", criterion id ' - '"%s", text "%s", and match type "%s" was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/get_ad_groups.py b/examples/adwords/v201710/basic_operations/get_ad_groups.py deleted file mode 100755 index 719942e1..00000000 --- a/examples/adwords/v201710/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201710') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name "%s", id "%s" and status "%s" was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/basic_operations/get_campaigns.py b/examples/adwords/v201710/basic_operations/get_campaigns.py deleted file mode 100755 index 01c017d3..00000000 --- a/examples/adwords/v201710/basic_operations/get_campaigns.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201710') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 360d3d4a..00000000 --- a/examples/adwords/v201710/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201710') - - # Construct query and get all campaigns. - query = (adwords.ServiceQueryBuilder() - .Select('Id', 'Name', 'Status') - .Where('Status').EqualTo('ENABLED') - .OrderBy('Name') - .Limit(0, PAGE_SIZE) - .Build()) - - for page in query.Pager(campaign_service): - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201710/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index 77046b40..00000000 --- a/examples/adwords/v201710/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/get_keywords.py b/examples/adwords/v201710/basic_operations/get_keywords.py deleted file mode 100755 index 5feec2b1..00000000 --- a/examples/adwords/v201710/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201710') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID "%s", type "%s", text "%s", and match type ' - '"%s" was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/pause_ad.py b/examples/adwords/v201710/basic_operations/pause_ad.py deleted file mode 100755 index f51e1f90..00000000 --- a/examples/adwords/v201710/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id "%s" was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201710/basic_operations/remove_ad.py b/examples/adwords/v201710/basic_operations/remove_ad.py deleted file mode 100755 index 4ea3a4ec..00000000 --- a/examples/adwords/v201710/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id "%s" and type "%s" was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201710/basic_operations/remove_ad_group.py b/examples/adwords/v201710/basic_operations/remove_ad_group.py deleted file mode 100755 index 2a372bc8..00000000 --- a/examples/adwords/v201710/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201710') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name "%s" and id "%s" was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/basic_operations/remove_campaign.py b/examples/adwords/v201710/basic_operations/remove_campaign.py deleted file mode 100755 index 4e4e84f6..00000000 --- a/examples/adwords/v201710/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201710') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name "%s" and id "%s" was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/basic_operations/remove_keyword.py b/examples/adwords/v201710/basic_operations/remove_keyword.py deleted file mode 100755 index a5a13312..00000000 --- a/examples/adwords/v201710/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201710') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id "%s", criterion id "%s", ' - 'and type "%s" was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201710/basic_operations/update_ad_group.py b/examples/adwords/v201710/basic_operations/update_ad_group.py deleted file mode 100755 index eac1d446..00000000 --- a/examples/adwords/v201710/basic_operations/update_ad_group.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the CPC bid and status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' - - -def main(client, ad_group_id, bid_micro_amount=None): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201710') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - - if bid_micro_amount: - operations[0]['operand']['biddingStrategyConfiguration'] = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': bid_micro_amount, - } - }] - } - - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] - # Find the CpcBid in the bidding strategy configuration's bids collection. - cpc_bid_micros = None - - if bidding_strategy_configuration: - bids = bidding_strategy_configuration['bids'] - - if bids: - for bid in bids: - if bid['Bids.Type'] == 'CpcBid': - cpc_bid_micros = bid['bid']['microAmount'] - break - - print ('Ad group with name "%s", and id "%s" was updated to have status ' - '"%s" and CPC bid %d.' - % (ad_group['name'], ad_group['id'], ad_group['status'], - cpc_bid_micros)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201710/basic_operations/update_campaign.py b/examples/adwords/v201710/basic_operations/update_campaign.py deleted file mode 100755 index 9f0e4dc2..00000000 --- a/examples/adwords/v201710/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201710') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/basic_operations/update_keyword.py b/examples/adwords/v201710/basic_operations/update_keyword.py deleted file mode 100755 index b140a592..00000000 --- a/examples/adwords/v201710/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201710') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id "%s" and criterion id ' - '"%s" currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: "%s", value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201710/campaign_management/__init__.py b/examples/adwords/v201710/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201710/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py deleted file mode 100755 index 27cc2172..00000000 --- a/examples/adwords/v201710/campaign_management/add_campaign_groups_and_performance_targets.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a campaign group and sets a performance target for it. - -To get campaigns, run get_campaigns.py. To download reports, run -download_criteria_report_with_awql.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id1, campaign_id2): - campaign_group_id = _CreateCampaignGroup(client) - _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) - _CreatePerformanceTarget(client, campaign_group_id) - print 'Campaign group and its performance target were setup successfully.' - - -def _CreateCampaignGroup(client): - """Create a campaign group. - - Args: - client: an AdWordsClient instance. - - Returns: - The integer ID of the created campaign group. - """ - # Get the CampaignGroupService. - campaign_group_service = client.GetService('CampaignGroupService', - version='v201710') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the campaign group. - 'operand': { - 'name': 'Mars campaign group #%d' % uuid.uuid4() - } - }] - - campaign_group = campaign_group_service.mutate(operations)['value'][0] - campaign_group_id = campaign_group['id'] - - # Display the results. - print 'Campaign group with ID "%d" and name "%s" was created.' % ( - campaign_group_id, campaign_group['name']) - - return campaign_group_id - - -def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): - """Adds multiple campaigns to a campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - campaign_ids: a list of integer IDs for campaigns. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201710') - - # Create the operations. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'campaignGroupId': campaign_group_id - } - } for campaign_id in campaign_ids] - - campaign_service.mutate(operations) - - # Display the results. - print ('The following campaign IDs were added to the campaign group with ID ' - '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) - - -def _CreatePerformanceTarget(client, campaign_group_id): - """Creates a performance target for the campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - """ - # Get the CampaignGroupPerformanceTargetService. - cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', - version='v201710') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the performance target. - 'operand': { - 'campaignGroupId': campaign_group_id, - 'performanceTarget': { - # Keep the CPC for the campaigns < $3. - 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', - 'efficiencyTargetValue': 3000000, - # Keep the maximum spend under $50. - 'spendTargetType': 'MAXIMUM', - 'spendTarget': { - 'microAmount': 500000000 - }, - # Aim for at least 3000 clicks. - 'volumeGoalType': 'MAXIMIZE_CLICKS', - 'volumeTargetValue': 3000, - # Start the performance target today, and run it for the next 90 - # days. - 'startDate': datetime.datetime.now().strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(90)).strftime('%Y%m%d') - } - } - }] - - cgpt = cgpt_service.mutate(operations)['value'][0] - - # Display the results. - print ('Campaign performance target with ID "%d" was added for campaign ' - 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201710/campaign_management/add_campaign_labels.py b/examples/adwords/v201710/campaign_management/add_campaign_labels.py deleted file mode 100755 index ec7f1adc..00000000 --- a/examples/adwords/v201710/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201710') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index 1d00652b..00000000 --- a/examples/adwords/v201710/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,428 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201710') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201710') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding an ExpandedTextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new ExpandedTextAd for - each of the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once - # you've added targeting and the ads are ready to serve. - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201710') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201710/campaign_management/add_draft.py b/examples/adwords/v201710/campaign_management/add_draft.py deleted file mode 100755 index 4a63c846..00000000 --- a/examples/adwords/v201710/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201710') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201710') - - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index 1cb8bfe6..00000000 --- a/examples/adwords/v201710/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to incrementally upload keywords. - -Uses the BatchJobService and BatchJobHelper to incrementally upload operations. -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201710') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201710') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201710') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201710') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201710/campaign_management/add_trial.py b/examples/adwords/v201710/campaign_management/add_trial.py deleted file mode 100755 index 00382eef..00000000 --- a/examples/adwords/v201710/campaign_management/add_trial.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201710') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201710') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index b5e858b7..00000000 --- a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'PolicySummary'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CombinedApprovalStatus', - 'operator': 'EQUALS', - 'values': 'DISAPPROVED' - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - disapproved_count = 0 - - # Display results. - while more_pages: - page = ad_group_ad_service.get(selector) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % ad['ad']['id']) - # Display the policy topic entries related to the ad disapproval. - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName'], - policy_topic_entry['policyTopicHelpCenterUrl']) - # Display the attributes and values that triggered the policy topic. - policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] - if policy_topic_evidences: - for evidence in policy_topic_entry['policyTopicEvidences']: - print (' evidence type: %s' - % evidence['policyTopicEvidenceType']) - evidence_text_list = evidence['evidenceTextList'] - if evidence_text_list: - for index, evidence_text in enumerate(evidence_text_list): - print ' evidence text[%d]: %s' % (index, evidence_text) - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index c8d69dd6..00000000 --- a/examples/adwords/v201710/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', - version='v201710') - - # Construct query and get all ads for a given campaign. - query = (adwords.ServiceQueryBuilder() - .Select('Id', 'PolicySummary') - .Where('AdGroupId').EqualTo(ad_group_id) - .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') - .OrderBy('Id') - .Limit(0, PAGE_SIZE) - .Build()) - disapproved_count = 0 - - # Display results. - while True: - page = ad_group_ad_service.query(query) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % ad['ad']['id']) - # Display the policy topic entries related to the ad disapproval. - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName']) - # Display the attributes and values that triggered the policy topic. - if ('policyTopicEvidences' in policy_topic_entry - and policy_topic_entry['policyTopicEvidences']): - for evidence in policy_topic_entry['policyTopicEvidences']: - print (' evidence type: %s' - % evidence['policyTopicEvidenceType']) - evidence_text_list = evidence['evidenceTextList'] - if evidence_text_list: - for index, evidence_text in enumerate(evidence_text_list): - print ' evidence text[%d]: %s' % (index, evidence_text) - - if not query.HasNext(page): - break - query.NextPage() - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index e3ab0b1a..00000000 --- a/examples/adwords/v201710/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201710') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id "%s", name "%s", and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201710/campaign_management/graduate_trial.py b/examples/adwords/v201710/campaign_management/graduate_trial.py deleted file mode 100755 index c4f1945b..00000000 --- a/examples/adwords/v201710/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201710') - budget_service = client.GetService('BudgetService', version='v201710') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201710/campaign_management/set_ad_parameters.py b/examples/adwords/v201710/campaign_management/set_ad_parameters.py deleted file mode 100755 index e3a54c48..00000000 --- a/examples/adwords/v201710/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - ad_param_service = client.GetService('AdParamService', version='v201710') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id "%s" was successfully added to an ad group with ' - 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text "%s" was successfully set for criterion ' - 'with id "%s" and ad group id "%s".' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index e2a524d7..00000000 --- a/examples/adwords/v201710/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201710') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' - 'was updated with bid modifier "%s".' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201710/campaign_management/validate_text_ad.py b/examples/adwords/v201710/campaign_management/validate_text_ad.py deleted file mode 100755 index a11fb2fa..00000000 --- a/examples/adwords/v201710/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -No objects will be created, but exceptions will still be returned. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords -from googleads import errors - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Construct operations to add an expanded text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'] - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for all astronauts in orbit', - 'finalUrls': ['http://www.example.com'], - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except errors.GoogleAdsServerFault, e: - print 'Validation correctly failed with "%s".' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/error_handling/__init__.py b/examples/adwords/v201710/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201710/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201710/error_handling/handle_partial_failures.py b/examples/adwords/v201710/error_handling/handle_partial_failures.py deleted file mode 100755 index e9819dcf..00000000 --- a/examples/adwords/v201710/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201710') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id "%s", ' - 'criterion id "%s", text "%s", and match type "%s" was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - if (first_field_path_element and - first_field_path_element['field'] == 'operations' and - 'index' in first_field_path_element): - operation_index = first_field_path_element['index'] - - adgroup_criterion = operations[operation_index]['operand'] - - print('Ad group criterion with ad group ID %s and keyword "%s" triggered ' - 'a failure for the following reason: %s.' - % (adgroup_criterion['adGroupId'], - adgroup_criterion['criterion']['text'], - error['errorString'])) - else: - print ('A failure has occurred for the following reasons: %s\n' - % error['errorString']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/error_handling/handle_policy_violation_error.py b/examples/adwords/v201710/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 3e77917c..00000000 --- a/examples/adwords/v201710/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - - -from googleads import adwords -from googleads import errors - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201710') - - # Create expanded text ad that violates an exemptable policy. - exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise!!!', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - # Create text ad that violates a non-exemptable policy. - non_exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise with too long of a headline.', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - operations = [exemptable_expanded_text_ad_operation, - non_exemptable_expanded_text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except errors.GoogleAdsServerFault, e: - for error in e.fault.detail.ApiExceptionFault.errors: - # Get the index of the failed operation from the error's field path - # elements. - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - # If the operation index is not present on the first error field path - # element, then there's no way to determine which operation to remove, - # so simply throw the exception. - if (not (first_field_path_element - and first_field_path_element['field'] == 'operations' - and 'index' in first_field_path_element)): - raise e - - index = long(first_field_path_element['index']) - operation = operations[index] - if not HandleAPIError(error, operation): - # Set non-exemptable operation to None to mark for deletion. - print ('Removing operation with non-exemptable error at index %s.' - % index) - operations[index] = None - - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is "%s".' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -def HandleAPIError(error, operation): - """Makes an exemption for exemptable PolicyViolationErrors. - - Args: - error: the error associated with the given operation. - operation: the operation associated with the given error. - - Returns: - A boolean that is True if the given error was an exemptable - PolicyViolationError; otherwise, returns False. - """ - is_exemptable = False - - # Determine if the operation can be resubmitted with an exemption request. - if error['ApiError.Type'] == 'PolicyViolationError': - expanded_text_ad = operation['operand']['ad'] - is_exemptable = (error['isExemptable'] if 'isExemptable' in error else - False) - print ('Ad with headline "%s - %s" violated %s policy "%s".' % - (expanded_text_ad['headlinePart1'], - expanded_text_ad['headlinePart2'], - 'exemptable' if is_exemptable else 'non-exemptable', - error['externalPolicyName'])) - - if is_exemptable: - # Add exemption request to the operation. - print ('Adding exemption request for policy name "%s" on text "%s".' - % (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({'key': error['key']}) - - return is_exemptable - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/extensions/__init__.py b/examples/adwords/v201710/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201710/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 2c02dcce..00000000 --- a/examples/adwords/v201710/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201710').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201710') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except errors.GoogleAdsServerFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201710/extensions/add_prices.py b/examples/adwords/v201710/extensions/add_prices.py deleted file mode 100755 index b1856b3d..00000000 --- a/examples/adwords/v201710/extensions/add_prices.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a price extension and associates it with an account. - -Campaign targeting is also set usin the specified campaign ID. To get campaigns, -run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -MICROS_PER_DOLLAR = 1000000 - - -def main(client, campaign_id): - # Initialize appropriate service. - customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201710') - - # To create a price extension, at least three table rows are needed. - table_rows = [ - CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', - 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', - final_mobile_url='http://m.example.com/scrubs'), - CreatePriceTableRow('Hair Cuts', 'Once a month', - 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url='http://m.example.com/haircuts'), - CreatePriceTableRow('Skin Care Package', 'Four times a month', - 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url=( - 'http://m.example.com/skincarepackage')) - ] - - # Create the price extension feed item. - customer_extension_setting = { - 'extensionType': 'PRICE', - 'extensionSetting': { - 'extensions': [{ - 'priceExtensionType': 'SERVICES', - 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', - 'language': 'en', - 'campaignTargeting': { - 'TargetingCampaignId': campaign_id - }, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': 'SATURDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 22, - 'endMinute': 'ZERO' - }, - { - 'dayOfWeek': 'SUNDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 18, - 'endMinute': 'ZERO' - } - ] - }, - 'tableRows': table_rows, - # Price qualifier is optional. - 'priceQualifier': 'FROM', - 'xsi_type': 'PriceFeedItem' - }] - } - } - - # Create an operation to add the feed. - operations = [{ - 'operator': 'ADD', - 'operand': customer_extension_setting - }] - - # Add the price extension. - response = customer_extension_setting_service.mutate(operations) - - # Print the results. - if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit, final_mobile_url=None): - """Helper function to generate a single row of a price table. - - Args: - header: A str containing the header text of this row. - description: A str description of this row in the price table. - final_url: A str containing the final URL after all cross domain redirects. - price_in_micros: An int indicating the price of the given currency in - micros. - currency_code: A str indicating the currency code being used. - price_unit: A str enum indicating the price unit for this row. - final_mobile_url: A str containing the final mobile URL after all cross - domain redirects. - - Returns: - A dictionary containing the contents of the generated price table row. - """ - table_row = { - 'header': header, - 'description': description, - 'finalUrls': {'urls': [final_url]}, - 'price': { - 'money': { - 'microAmount': price_in_micros, - }, - 'currencyCode': currency_code - }, - 'priceUnit': price_unit, - 'xsi_type': 'PriceTableRow' - } - - if final_mobile_url: - table_row['finalMobileUrls'] = { - 'urls': [final_mobile_url] - } - - return table_row - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/extensions/add_site_links.py b/examples/adwords/v201710/extensions/add_site_links.py deleted file mode 100755 index 0405eef8..00000000 --- a/examples/adwords/v201710/extensions/add_site_links.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201710') - customer_service = client.GetService('CustomerService', version='v201710') - # Find the matching customer and its time zone. The getCustomers method will - # return a single Customer object corresponding to the configured - # clientCustomerId. - customer = customer_service.getCustomers()[0] - customer_tz = timezone(customer['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840}, - # Restrict targeting only to people physically within the United States. - # Otherwise, this could also show to people interested in the United - # States, but not physically located there. - 'geoTargetingRestriction': { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/extensions/add_site_links_using_feeds.py b/examples/adwords/v201710/extensions/add_site_links_using_feeds.py deleted file mode 100755 index a80525df..00000000 --- a/examples/adwords/v201710/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_2_TEXT = '3' -PLACEHOLDER_FIELD_LINE_3_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201710') - feed_item_service = client.GetService('FeedItemService', version='v201710') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201710') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201710') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 2 Description'}, - {'type': 'STRING', 'name': 'Line 3 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_2_feed_attribute_id = feed['attributes'][2]['id'] - line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name "%s" and ID "%s" was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - sitelinks_data['line3FeedId'] = line_3_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line2': 'Home line 2', 'line3': 'Home line 3'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line2': 'Support line 2', 'line3': 'Support line 3'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line2': 'Products line 2', 'line3': 'Products line 3'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'stringValue': item['line3'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - feed_item['geoTargetingRestriction'] = { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/migration/__init__.py b/examples/adwords/v201710/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201710/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201710/migration/migrate_to_extension_settings.py b/examples/adwords/v201710/migration/migrate_to_extension_settings.py deleted file mode 100755 index 8302525d..00000000 --- a/examples/adwords/v201710/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,526 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201710') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201710') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201710') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201710') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201710') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201710') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201710') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retreiving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/misc/__init__.py b/examples/adwords/v201710/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201710/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201710/misc/get_all_images_and_videos.py b/examples/adwords/v201710/misc/get_all_images_and_videos.py deleted file mode 100755 index 98a258aa..00000000 --- a/examples/adwords/v201710/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201710') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id "%s" was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/misc/upload_image.py b/examples/adwords/v201710/misc/upload_image.py deleted file mode 100755 index da63e423..00000000 --- a/examples/adwords/v201710/misc/upload_image.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201710') - - with open(image_filename, 'rb') as image_handle: - image_data = image_handle.read().decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201710/misc/upload_media_bundle.py b/examples/adwords/v201710/misc/upload_media_bundle.py deleted file mode 100755 index 0ba908a8..00000000 --- a/examples/adwords/v201710/misc/upload_media_bundle.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201710') - # Create HTML5 media. - html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return response.read().decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/optimization/__init__.py b/examples/adwords/v201710/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201710/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201710/optimization/estimate_keyword_traffic.py b/examples/adwords/v201710/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 5250262e..00000000 --- a/examples/adwords/v201710/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201710') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate - and min_estimate['averageCpc'] else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate - and min_estimate['averagePosition'] else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index 2139b135..00000000 --- a/examples/adwords/v201710/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201710') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page, - # NOT the number of entries (bid landscapes) in the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = num_landscape_points >= PAGE_SIZE - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201710/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index c25bf993..00000000 --- a/examples/adwords/v201710/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201710') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages: - num_landscape_points = 0 - page = data_service.getCriterionBidLandscape(selector) - - if page and 'entries' in page: - entries = page['entries'] - print 'Bid landscape(s) retrieved: %d.' % len(entries) - - for bid_landscape in entries: - print ('Retrieved keyword bid landscape with ad group ID "%d", ' - 'keyword ID "%d", start date "%s", end date "%s", ' - 'with landscape points:' % ( - bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - num_landscape_points += 1 - print (' bid: %s => clicks: %s, cost: %s, impressions: %s' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'])) - - # Need to increment by the total # of landscape points within the page, - # NOT the number of entries (bid landscapes) in the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = num_landscape_points >= PAGE_SIZE - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201710/optimization/get_keyword_ideas.py b/examples/adwords/v201710/optimization/get_keyword_ideas.py deleted file mode 100755 index a307aac8..00000000 --- a/examples/adwords/v201710/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id=None): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201710') - - # Construct selector object and retrieve related keywords. - selector = { - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS' - } - - selector['requestedAttributeTypes'] = [ - 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] - - offset = 0 - selector['paging'] = { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - - selector['searchParameters'] = [{ - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }] - - # Language setting (optional). - selector['searchParameters'].append({ - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }) - - # Network search parameter (optional) - selector['searchParameters'].append({ - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - }) - - # Use an existing ad group to generate ideas (optional) - if ad_group_id is not None: - selector['searchParameters'].append({ - 'xsi_type': 'SeedAdGroupIdSearchParameter', - 'adGroupId': ad_group_id - }) - - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr( - attribute['value'], 'value', '0') - print ('Keyword with "%s" text and average monthly search volume ' - '"%s" was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201710/remarketing/__init__.py b/examples/adwords/v201710/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201710/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201710/remarketing/add_audience.py b/examples/adwords/v201710/remarketing/add_audience.py deleted file mode 100755 index f9fd2d60..00000000 --- a/examples/adwords/v201710/remarketing/add_audience.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201710') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201710') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - result = user_list_service.mutate(operations) - - # Display results. - if 'value' in result: - conversion_ids = [] - for user_list in result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - selector = { - 'fields': ['Name', 'Status', 'Category'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': conversion_ids - }], - 'ordering': [{ - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }] - } - - pages = conversion_tracker_service.get(selector) - conversions_map = {} - if pages['entries']: - for conversion_tracker in pages['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in result['value']: - print ('User list with name "%s" and ID "%s" was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Conversion type code snippet associated to the list:\n%s\n' - % conversion_tracker['snippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/add_conversion_tracker.py b/examples/adwords/v201710/remarketing/add_conversion_tracker.py deleted file mode 100755 index 389d75d9..00000000 --- a/examples/adwords/v201710/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201710') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" \n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/add_conversion_trackers.py b/examples/adwords/v201710/remarketing/add_conversion_trackers.py deleted file mode 100755 index 1bf5ed31..00000000 --- a/examples/adwords/v201710/remarketing/add_conversion_trackers.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds AdWords conversion trackers. - -Adds an AdWords conversion tracker and an upload conversion tracker. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201710') - - # Create an AdWords conversion tracker. - adwords_conversion_tracker = { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'name': 'Upload Conversion #%s' % uuid.uuid4(), - # Optional fields. - # Set an appropriate category. This will be set to DEFAULT if not - # specified. - 'category': 'LEAD', - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90', - # Set the default currency code to use for conversions that do - # not specify a conversion currency. This must be an ISO 4217 3-character - # code such as "EUR" or "USD". - # If this field is not set, AdWords will use the account's currency. - 'defaultRevenueCurrencyCode': 'EUR', - # Set the default revenue value to use for conversions that do not specify - # a converison value. Note that this value should NOT be in micros. - 'defaultRevenueValue': '2.50', - # To upload fractional conversion credits, mark the upload conversion as - # externally attributed. To learn more about importing externally - # attributed conversions, see: - # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions - # 'isExternallyAttributed': 'true' - } - - # Construct operations. - operations = [{ - 'operator': 'ADD', - 'operand': conversion_tracker - } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] - - # Add the conversions. - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - if (conversion_tracker['ConversionTracker.Type'] - is 'AdWordsConversionTracker'): - print ('Conversion tracker with ID "%d", name "%s", status "%s" ' - 'and category "%s" and snippet \n"%s"\n was added.' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'], - conversion_tracker['snippet'])) - else: - print ('Conversion with ID "%d", name "%s", status "%s", and category ' - '"%s" was added.' - % (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/add_crm_based_user_list.py b/examples/adwords/v201710/remarketing/add_crm_based_user_list.py deleted file mode 100755 index faaf9c84..00000000 --- a/examples/adwords/v201710/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201710') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # Maximum lifespan is 180 days. - 'membershipLifeSpan': 180 - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - - emails = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] - - # Optional: AddressInfo is only accessible to whitelisted customers. - # If you are not on the whitelist, you should leave this code commented out. - # members.append({ - # 'addressInfo': { - # 'hashedFirstName': NormalizeAndSHA256('John'), - # 'hashedLastName': NormalizeAndSHA256('Doe'), - # 'countryCode': 'US', - # 'zipCode': '10001' - # } - # }) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'membersList': members - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def NormalizeAndSHA256(s): - """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. - - Args: - s: The string to perform this operation on. - - Returns: - A normalized and SHA-256 hashed string. - """ - return hashlib.sha256(s.strip().lower()).hexdigest() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201710/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 521d2cee..00000000 --- a/examples/adwords/v201710/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201710') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords knows how to apply the - # rules. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ], - # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF - # means 'at least one item in each rule item group must match', and DNF - # means 'at least one entire rule item group must match'. - # DateSpecificRuleUserList only supports DNF. You can also omit the rule - # type altogether to default to DNF. - 'ruleType': 'DNF' - } - - # Third and fourth rule item groups. - # Visitors of a page who visited another page. - site1_rule_item = { - 'StringRuleItem': { - 'key': {'name': 'url__'}, - 'op': 'EQUALS', - 'value': 'example.com/example1' - } - } - site2_rule_item = { - 'StringRuleItem': { - 'key': {'name': 'url__'}, - 'op': 'EQUALS', - 'value': 'example.com/example2' - } - } - - # Create two rules to show that a visitor browsed two sites. - user_visited_site1_rule = { - 'groups': [{ - 'items': [site1_rule_item] - }] - } - - user_visited_site2_rule = { - 'groups': [{ - 'items': [site2_rule_item] - }] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule, - # Optional: Set the populationStatus to REQUESTED to include past users in - # the user list. - 'prepopulationStatus': 'REQUESTED' - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create the user list for "Visitors of a page who did visit another page". - # To create a user list for "Visitors of a page who did not visit another - # page", change the ruleOperator from AND to AND_NOT. - combined_user_list = { - 'xsi_type': 'CombinedRuleUserList', - 'name': 'Combined rule user lst create at ${creation_time}', - 'description': 'Users who visited two sites.', - 'leftOperand': user_visited_site1_rule, - 'rightOperand': user_visited_site2_rule, - 'ruleOperator': 'AND' - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list, - combined_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201710/remarketing/upload_offline_call_conversions.py deleted file mode 100755 index 4bb6851b..00000000 --- a/examples/adwords/v201710/remarketing/upload_offline_call_conversions.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for calls related to ads in your account. - -To set up a conversion tracker, run the add_conversion_trackers.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CALLER_ID = 'INSERT_CALLER_ID_HERE' -# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats -# For time zones, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -CALL_START_TIME = 'INSERT_CALL_START_TIME' -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, caller_id, call_start_time, conversion_name, conversion_time, - conversion_value): - # Initialize appropriate services. - occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201710') - - # Associate offline call conversions with the existing named conversion - # tracker. If this tracker was newly created, it may be a few hours before it - # can accept conversions. - feed = { - 'callerId': caller_id, - 'callStartTime': call_start_time, - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - } - - occ_operations = [{'operator': 'ADD', 'operand': feed}] - - occ_response = occ_feed_service.mutate(occ_operations) - values = occ_response['value'] - - if values: - for occ_feed in values: - print ('Uploaded offline call conversion value of "%s" for caller ID ' - '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) - else: - print 'No offline call conversions were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, - CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201710/remarketing/upload_offline_conversions.py b/examples/adwords/v201710/remarketing/upload_offline_conversions.py deleted file mode 100755 index 7671c7b5..00000000 --- a/examples/adwords/v201710/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_trackers.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201710') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id, - # Optional: To upload fractional conversion credits, set the external - # attribution model and credit. To use this feature, your conversion - # tracker should be marked as externally attributed. To learn more about - # importing externally attributed conversins, see: - # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions - # 'externalAttributionCredit': 0.3, - # 'externalAttributionModel': 'Linear' - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of "%s" for Google Click ID ' - '"%s" to "%s".' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201710/remarketing/upload_offline_data.py b/examples/adwords/v201710/remarketing/upload_offline_data.py deleted file mode 100755 index 7004738f..00000000 --- a/examples/adwords/v201710/remarketing/upload_offline_data.py +++ /dev/null @@ -1,218 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 shows how to upload offline data for store sales transactions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import datetime -import hashlib - -from googleads import adwords -import pytz - - -_DT_FORMAT = '%Y%m%d %H%M%S' -# User identifier types whose values must be hashed. -_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', - 'HASHED_LAST_NAME', 'HASHED_PHONE') -# The timezone to be used in this example. For valid timezone IDs, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -_TIMEZONE = pytz.timezone('America/New_York') -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Insert email addresses below for creating user identifiers. -EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] -# The external upload ID can be any number that you use to keep track of your -# uploads. -EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' -# Store sales upload common metadata types -METADATA_TYPE_1P = 'FirstPartyUploadMetadata' -METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' -# Set the below constant to METADATA_TYPE_3P if uploading third-party data. -STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P -# The three constants below are needed when uploading third-party data. They -# are not used when uploading first-party data. -# Advertiser upload time to partner. -# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, -# see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' -# Indicates the version of the bridge map. -BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' -# The ID of the third party uploading the transaction feed. -PARTNER_ID = 'INSERT_PARTNER_ID_HERE' - - -def main(client, conversion_name, external_upload_id, - store_sales_upload_common_metadata_type, email_addresses, - advertiser_upload_time=None, bridge_map_version_id=None, - partner_id=None): - # Initialize appropriate services. - offline_data_upload_service = client.GetService( - 'OfflineDataUploadService', version='v201710') - - # Create the first offline data for upload. - # This transaction occurred 7 days ago with an amount of $200 USD. - transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - - datetime.timedelta(days=7)) - offline_data_1 = { - 'StoreSalesTransaction': { - 'userIdentifiers': [ - _CreateUserIdentifier(identifier_type='HASHED_EMAIL', - value=email_addresses[0]), - _CreateUserIdentifier(identifier_type='STATE', value='New York') - ], - 'transactionTime': _GetFormattedDateTime(transaction_time_1), - 'transactionAmount': { - 'currencyCode': 'USD', - 'money': { - 'microAmount': 200000000 - } - }, - 'conversionName': conversion_name - } - } - - # Create the second offline data for upload. - # This transaction occurred 14 days ago with amount of 450 EUR. - transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - - datetime.timedelta(days=14)) - offline_data_2 = { - 'StoreSalesTransaction': { - 'userIdentifiers': [ - _CreateUserIdentifier(identifier_type='HASHED_EMAIL', - value=email_addresses[1]), - _CreateUserIdentifier(identifier_type='STATE', value='California') - ], - 'transactionTime': _GetFormattedDateTime(transaction_time_2), - 'transactionAmount': { - 'currencyCode': 'EUR', - 'money': { - 'microAmount': 450000000 - } - }, - 'conversionName': conversion_name - } - } - - # Set the type and metadata of this upload. - upload_metadata = { - 'StoreSalesUploadCommonMetadata': { - 'xsi_type': store_sales_upload_common_metadata_type, - 'loyaltyRate': 1.0, - 'transactionUploadRate': 1.0, - } - } - - if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: - upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' - elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: - upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' - upload_metadata['StoreSalesUploadCommonMetadata'].update({ - 'advertiserUploadTime': advertiser_upload_time, - 'validTransactionRate': 1.0, - 'partnerMatchRate': 1.0, - 'partnerUploadRate': 1.0, - 'bridgeMapVersionId': bridge_map_version_id, - 'partnerId': partner_id - }) - else: - raise ValueError('Unknown metadata type.') - - # Create offline data upload - offline_data_upload = { - 'externalUploadId': external_upload_id, - 'offlineDataList': [offline_data_1, offline_data_2], - # Set the type of this upload. - 'uploadType': upload_type, - 'uploadMetadata': upload_metadata - } - - # Create an offline data upload operation. - operations = [{ - 'operator': 'ADD', - 'operand': offline_data_upload - }] - - # Upload offline data on the server and print the result. - result = offline_data_upload_service.mutate(operations) - offline_data_upload = result['value'][0] - - print ('Uploaded offline data with external upload ID "%d" and upload status ' - '"%s".' % (offline_data_upload['externalUploadId'], - offline_data_upload['uploadStatus'])) - - # Print any partial data errors from the response. The order of the partial - # data errors list is the same as the uploaded offline data list in the - # request. - for i, partial_data_error in enumerate( - offline_data_upload['partialDataErrors']): - # If a partial error occurred for this offline data, print the error. Note - # that non-errors for a given offline data would be set to None. - if partial_data_error: - print ('Found a partial error for offline data #%d with error string: %s' - % (i, partial_data_error['errorString'])) - - -def _CreateUserIdentifier(identifier_type=None, value=None): - """Creates a user identifier from the specified type and value. - - Args: - identifier_type: a str specifying the type of user identifier. - value: a str value of the identifier; to be hashed using SHA-256 if needed. - - Returns: - A dict specifying a user identifier, with a value hashed using SHA-256 if - needed. - """ - if identifier_type in _HASHED_IDENTIFIER_TYPES: - # If the user identifier type is a hashed type, normalize and hash the - # value. - value = hashlib.sha256(value.strip().lower()).hexdigest() - - user_identifier = { - 'userIdentifierType': identifier_type, - 'value': value - } - - return user_identifier - - -def _GetFormattedDateTime(dt): - """Formats the given datetime and timezone for use with AdWords. - - Args: - dt: a datetime instance. - - Returns: - A str representation of the datetime in the correct format for AdWords. - """ - return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, - STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, - ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201710/reporting/__init__.py b/examples/adwords/v201710/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201710/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index aa1294e9..00000000 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import StringIO -import sys - -from googleads import adwords - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201710') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py deleted file mode 100755 index f83a49c6..00000000 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_stream_with_selector.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import StringIO -import sys -from googleads import adwords - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201710') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index fcf87588..00000000 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201710') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py deleted file mode 100755 index b947dfb9..00000000 --- a/examples/adwords/v201710/reporting/download_criteria_report_as_string_with_selector.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201710') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 38bf210c..00000000 --- a/examples/adwords/v201710/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import sys -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201710') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - # You can provide a file object to write the output to. For this - # demonstration we use sys.stdout to write the report to the screen. - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', sys.stdout, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py deleted file mode 100755 index dfd83fec..00000000 --- a/examples/adwords/v201710/reporting/download_criteria_report_with_selector.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import sys -from googleads import adwords - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201710') - - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201710/reporting/get_report_fields.py b/examples/adwords/v201710/reporting/get_report_fields.py deleted file mode 100755 index 5d6b7fa9..00000000 --- a/examples/adwords/v201710/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201710') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type "%s" contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201710/reporting/parallel_report_download.py b/examples/adwords/v201710/reporting/parallel_report_download.py deleted file mode 100755 index 3734b53a..00000000 --- a/examples/adwords/v201710/reporting/parallel_report_download.py +++ /dev/null @@ -1,244 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import multiprocessing -import os -from Queue import Empty -import time - -import googleads.adwords -import googleads.errors - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def _DownloadReport(process_id, report_download_directory, customer_id, - report_definition): - """Helper function used by ReportWorker to download customer report. - - Note that multiprocessing differs between Windows / Unix environments. A - Process or its subclasses in Windows must be serializable with pickle, but - that is not possible for AdWordsClient or ReportDownloader. This top-level - function is used as a work-around for Windows support. - - Args: - process_id: The PID of the process downloading the report. - report_download_directory: A string indicating the directory where you - would like to download the reports. - customer_id: A str AdWords customer ID for which the report is being - downloaded. - report_definition: A dict containing the report definition to be used. - - Returns: - A tuple indicating a boolean success/failure status, and dict request - context. - """ - report_downloader = (googleads.adwords.AdWordsClient.LoadFromStorage() - .GetReportDownloader()) - - filepath = os.path.join(report_download_directory, - 'adgroup_%d.csv' % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (process_id, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - report_downloader.DownloadReport( - report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError as e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - def __init__(self, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = _DownloadReport(self.ident, self.report_download_directory, - customer_id, self.report_definition) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - Raises: - Exception: if no CustomerIds could be found. - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201710') - - offset = 0 - - # Get the account hierarchy for this account. - selector = { - 'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201710/shopping/__init__.py b/examples/adwords/v201710/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201710/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201710/shopping/add_product_partition_tree.py b/examples/adwords/v201710/shopping/add_product_partition_tree.py deleted file mode 100755 index 0897675e..00000000 --- a/examples/adwords/v201710/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,279 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201710') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201710/shopping/add_product_scope.py b/examples/adwords/v201710/shopping/add_product_scope.py deleted file mode 100755 index 65b384c7..00000000 --- a/examples/adwords/v201710/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201710') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201710/shopping/add_shopping_campaign.py b/examples/adwords/v201710/shopping/add_shopping_campaign.py deleted file mode 100755 index 81815a25..00000000 --- a/examples/adwords/v201710/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -# If set to true, a default partition will be created. If running the -# add_product_partition_tree.py example right after this example, make -# sure this stays set to false. -CREATE_DEFAULT_PARTITION = False -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id, create_default_partition): - campaign_service = client.GetService('CampaignService', version='v201710') - ad_group_service = client.GetService('AdGroupService', version='v201710') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201710') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - ad_group = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': ad_group - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] - ad_group_id = ad_group['id'] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (ad_group['name'], ad_group_id)) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': ad_group_id, - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - - if create_default_partition: - CreateDefaultPartition(client, ad_group_id) - - -def CreateDefaultPartition(client, ad_group_id): - """Creates a default partition. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID for an ad group. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201710') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Make sure that caseValue and parentCriterionId are left unspecified. - # This makes this partition as generic as possible to use as a - # fallback when others don't match. - 'criterion': { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - }, - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 500000 - } - }] - } - } - }] - - ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' - % (ad_group_criterion['criterion']['id'], - ad_group_criterion['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py deleted file mode 100755 index ba402775..00000000 --- a/examples/adwords/v201710/shopping/add_shopping_campaign_for_showcase_ads.py +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds a Shopping campaign for Showcase ads. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import uuid - -from googleads import adwords -from googleads import errors - - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' -COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - # Note: Showcase ads require either ManualCpc or EnhancedCpc in the - # campaign's BiddingStrategyConfiguration. - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, budget_id, merchant_id, expanded_image_filepath, - collapsed_image_filepath): - try: - # Create the Shopping Campaign - campaign = CreateShoppingCampaign(client, budget_id, merchant_id) - - # Create the AdGroup - adgroup = CreateAdGroup(client, campaign['id']) - - # Create a Showcase Ad - CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath) - - product_partition_tree = CreateProductPartition(client, adgroup['id']) - print 'Final tree:\n%s' % product_partition_tree - except errors.GoogleAdsServerFault: - print 'Failed to create shopping campaign for showcase ads.' - raise - - -def CreateShoppingCampaign(client, budget_id, merchant_id): - """Creates a shopping campaign with the given budget and merchant IDs. - - Args: - client: an AdWordsClient instance. - budget_id: the str ID of the budget to be associated with the shopping - campaign. - merchant_id: the str ID of the merchant account to be associated with the - shopping campaign. - - Returns: - The created Shopping Campaign as a sudsobject. - """ - campaign_service = client.GetService('CampaignService', 'v201710') - - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - return campaign - - -def CreateAdGroup(client, campaign_id): - """Creates an AdGroup for the given shopping campaign ID. - - Args: - client: an AdWordsClient instance. - campaign_id: the str ID of a shopping campaign. - - Returns: - The created AdGroup as a sudsobject. - """ - ad_group_service = client.GetService('AdGroupService', 'v201710') - - adgroup = { - # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS - 'adGroupType': 'SHOPPING_SHOWCASE_ADS', - 'campaignId': campaign_id, - 'name': 'AdGroup #%s' % uuid.uuid4(), - # REQUIRED: Set the ad group's bidding strategy configuration. - 'biddingStrategyConfiguration': { - # Showcase ads require either ManualCpc or EnhancedCpc. - 'biddingStrategyType': 'MANUAL_CPC', - # Optional: Set the bids - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 100000 - } - }] - } - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - return adgroup - - -def CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath): - """Creates a showcase add for the given AdGroup with the given images. - - Args: - client: an AdWordsClient instance. - adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. - expanded_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's expandedImage. - collapsed_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's collapsedImage. - - Returns: - The created Showcase Ad as a sudsobject. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201710') - - showcase_ad = { - 'adGroupId': adgroup['id'], - 'ad': { - 'xsi_type': 'ShowcaseAd', - 'Ad.Type': 'ShowcaseAd', - # Required: set the ad's name, final URLs, and display URL. - 'name': 'Showcase ad #%s' % uuid.uuid4(), - 'finalUrls': 'http://example.com/showcase', - 'displayUrl': 'example.com', - # Required: Set the ad's expanded image. - 'expandedImage': { - 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] - }, - # Optional: Set the collapsed image. - 'collapsedImage': { - 'mediaId': - UploadImage(client, collapsed_image_filepath)['mediaId'] - } - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': showcase_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] - - print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] - - return showcase_ad - - -def UploadImage(client, filepath): - """Uploads a .jpg image with the given filepath via the AdWords MediaService. - - Args: - client: an AdWordsClient instance. - filepath: a str filepath to the .jpg file to be uploaded. - - Returns: - The created Image as a sudsobject. - """ - media_service = client.GetService('MediaService', 'v201710') - - with open(filepath, 'rb') as image_handle: - image_data = image_handle.read().decode('utf-8') - - image = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - - image = media_service.upload(image)[0] - - return image - - -def CreateProductPartition(client, adgroup_id): - """Creates a ProductPartition tree for the given AdGroup ID. - - Args: - client: an AdWordsClient instance. - adgroup_id: a str AdGroup ID. - - Returns: - The ProductPartition tree as a sudsobject. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - 'v201710') - helper = ProductPartitionHelper(adgroup_id) - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition) - helper.CreateUnit(root, used_product_canonical_condition) - helper.CreateUnit(root, other_product_canonical_condition) - - result = ad_group_criterion_service.mutate(helper.operations) - return result['value'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, - COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201710/shopping/get_product_category_taxonomy.py b/examples/adwords/v201710/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 8a769c26..00000000 --- a/examples/adwords/v201710/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201710') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/targeting/__init__.py b/examples/adwords/v201710/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201710/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 1b464c56..00000000 --- a/examples/adwords/v201710/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201710') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s", criterion id "%s", ' - 'and type "%s" was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201710/targeting/add_customer_negative_criteria.py b/examples/adwords/v201710/targeting/add_customer_negative_criteria.py deleted file mode 100755 index 474b9430..00000000 --- a/examples/adwords/v201710/targeting/add_customer_negative_criteria.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds various types of negative criteria to a customer. - -These criteria will be applied to all campaigns for the customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_negative_criterion_service = client.GetService( - 'CustomerNegativeCriterionService', version='v201710') - - criteria = [ - # Exclude tragedy & conflict content. - { - 'xsi_type': 'ContentLabel', - 'contentLabelType': 'TRAGEDY' - }, - # Exclude a specific placement. - { - 'xsi_type': 'Placement', - 'url': 'http://www.example.com' - } - # Additional criteria types are available for this service. See the types - # listed under Criterion here: - # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion - ] - - # Create operations to add each of the criteria above. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'criterion': criterion - } - } for criterion in criteria] - - # Make the mutate request. - result = customer_negative_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for negative_criterion in result['value']: - print ('Customer negative criterion with criterion ID "%s", and type "%s" ' - 'was added.' % (negative_criterion['criterion']['id'], - negative_criterion['criterion']['type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index da284e19..00000000 --- a/examples/adwords/v201710/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201710') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type "%s" was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index a5fc78b7..00000000 --- a/examples/adwords/v201710/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201710') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index c874487d..00000000 --- a/examples/adwords/v201710/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201710') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name "%s" and ID "%s" was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name "%s", ID "%s", and country code "%s" was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201710/targeting/lookup_location.py b/examples/adwords/v201710/targeting/lookup_location.py deleted file mode 100755 index 4ba82ba7..00000000 --- a/examples/adwords/v201710/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201710') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term "%s" returned the location "%s" of type "%s"' - ' with parent locations "%s", reach "%s" and id "%s" (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index f34c33bd..00000000 --- a/examples/adwords/v201802/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Optionally, you may specify a landscape image. - # Here we download a demo image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open('http://goo.gl/9JmyKk').read().decode('utf-8') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - }, - { - 'name': 'landscapeImage', - 'fieldMedia': { - 'xsi_type': 'Image', - 'data': image_data - }, - 'type': 'IMAGE' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_click_to_download_ad.py b/examples/adwords/v201806/advanced_operations/add_click_to_download_ad.py deleted file mode 100755 index 8cf8c366..00000000 --- a/examples/adwords/v201806/advanced_operations/add_click_to_download_ad.py +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a click-to-download ad in a given ad group. - -This type of ad is also known as an app promotion ad. To list ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Optionally, you may specify a landscape image. - # Here we download a demo image. - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open('http://goo.gl/9JmyKk').read().decode('utf-8') - - # Create the template elements for the ad. You can refer to - # https://developers.google.com/adwords/api/docs/appendix/templateads - # for the list of available template fields. - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'headline', - 'fieldText': 'Enjoy your drive in Mars', - 'type': 'TEXT' - }, - { - 'name': 'description1', - 'fieldText': 'Realistic physics simulation', - 'type': 'TEXT' - }, - { - 'name': 'description2', - 'fieldText': 'Race against players online', - 'type': 'TEXT' - }, - { - 'name': 'appId', - 'fieldText': 'com.example.demogame', - 'type': 'TEXT' - }, - { - 'name': 'appStore', - 'fieldText': '2', - 'type': 'ENUM' - }, - { - 'name': 'landscapeImage', - 'fieldMedia': { - 'xsi_type': 'Image', - 'data': image_data - }, - 'type': 'IMAGE' - } - ] - } - - # Create click to download ad. - click_to_download_app_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for demo game', - 'templateId': '353', - 'finalUrls': [ - 'http://play.google.com/store/apps/details?id=com.example.demogame' - ], - 'displayUrl': 'play.google.com', - 'templateElements': [ad_data] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': click_to_download_app_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new click-to-download ad with ID "%s" and final URL "%s".' - % (ad['ad']['id'], ad['ad']['finalUrls'][0])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py index e57a5c27..79a8cf5c 100755 --- a/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py @@ -37,36 +37,20 @@ def main(client, ad_group_id, criterion_id): # Initialize appropriate service. data_service = client.GetService('DataService', version='v201806') - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'BiddableConversions', 'BiddableConversionsValue', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages: - num_landscape_points = 0 - page = data_service.getCriterionBidLandscape(selector) + # Create a query to select all keyword bid simulations for the specified + # ad group and criterion ID. + query = (adwords.ServiceQueryBuilder() + .Select( + 'AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'BiddableConversions', 'BiddableConversionsValue', 'LocalClicks', + 'LocalCost', 'LocalImpressions') + .Where('AdGroupId').EqualTo(ad_group_id) + .Where('CriterionId').EqualTo(criterion_id) + .Limit(0, PAGE_SIZE) + .Build()) + + while True: + page = data_service.queryCriterionBidLandscape(query) if page and 'entries' in page: entries = page['entries'] @@ -79,7 +63,6 @@ def main(client, ad_group_id, criterion_id): bid_landscape['adGroupId'], bid_landscape['criterionId'], bid_landscape['startDate'], bid_landscape['endDate'])) for bid_landscape_point in bid_landscape['landscapePoints']: - num_landscape_points += 1 print (' bid: %s => clicks: %s, cost: %s, impressions: %s, ' 'biddable conversions: %.2f, ' 'biddable conversions value: %.2f' @@ -90,11 +73,9 @@ def main(client, ad_group_id, criterion_id): bid_landscape_point['biddableConversions'], bid_landscape_point['biddableConversionsValue'])) - # Need to increment by the total # of landscape points within the page, - # NOT the number of entries (bid landscapes) in the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = num_landscape_points >= PAGE_SIZE + if not query.HasNext(page): + break + query.NextPage() if __name__ == '__main__': diff --git a/examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py index ba0cf308..f3a8e02f 100755 --- a/examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -25,10 +25,11 @@ PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' def main(client, programmatic_buyer_id, primary_salesperson_id, - primary_trafficker_id): + primary_trafficker_id, advertiser_id): proposal_service = client.GetService('ProposalService', version='v201805') proposal = { @@ -39,12 +40,17 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, }, # Set common required fields for proposals. 'name': 'Proposal #%s' % uuid.uuid4(), + # Set fields that are required before sending the proposal to the buyer. + 'primaryTraffickerId': primary_trafficker_id, + 'sellerContactIds': [primary_salesperson_id], 'primarySalesperson': { 'userId': primary_salesperson_id, 'split': '100000' }, - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', + 'advertiser': { + 'type': 'ADVERTISER', + 'companyId': advertiser_id + }, } proposals = proposal_service.createProposals([proposal]) @@ -59,4 +65,4 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID) + PRIMARY_TRAFFICKER_ID, ADVERTISER_ID) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py b/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py index 0948ced6..57393963 100755 --- a/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py +++ b/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py @@ -35,7 +35,7 @@ def main(client, geo_target_type): suffix='.csv', mode='w', delete=False) as geo_data_file: geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' - 'CountryCode ' + 'CountryCode, Type ' 'FROM Geo_Target ' 'WHERE Type = :type AND Targetable = true ' 'ORDER BY CountryCode ASC, Name ASC') diff --git a/googleads/adwords.py b/googleads/adwords.py index 222020cc..5204db1a 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -41,57 +41,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201710': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignBidModifierService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignGroupPerformanceTargetService': 'cm', - 'CampaignGroupService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerNegativeCriterionService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'FeedItemService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineCallConversionFeedService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'OfflineDataUploadService': 'rm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201802': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', @@ -2546,8 +2495,11 @@ def HasNext(self, page): # method of determining if there is still a page left. if (self._PAGE_TYPE in page and page[self._PAGE_TYPE] in self._BID_LANDSCAPE_PAGES): - total_landscape_points = sum([len(bid_landscape[self._LANDSCAPE_POINTS]) - for bid_landscape in page[self._ENTRIES]]) + if self._ENTRIES in page: + total_landscape_points = sum([len(bid_landscape[self._LANDSCAPE_POINTS]) + for bid_landscape in page[self._ENTRIES]]) + else: + total_landscape_points = 0 return total_landscape_points >= self._page_size if not self._total_num_entries: diff --git a/googleads/common.py b/googleads/common.py index de5b2812..00a2f807 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '12.2.0' +VERSION = '13.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' From ea5a264145849122d44a853487f2bb75e5a2394e Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 24 Jul 2018 15:39:38 -0400 Subject: [PATCH 118/180] Commiting latest changes. From cdafd0110c0ee6556959d1ac7ab9dd456fdfd269 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 21 Aug 2018 15:48:24 -0400 Subject: [PATCH 119/180] Google Ad Manager rebrand & v201808 release --- CONTRIBUTING.md | 3 +- ChangeLog | 6 + README.md | 15 +- ...te_ad_manager_client_with_access_token.py} | 15 +- ...e_ad_manager_client_with_refresh_token.py} | 13 +- ...ad_manager_client_with_service_account.py} | 13 +- .../authentication/generate_refresh_token.py | 6 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 6 +- .../get_active_activity_groups.py | 8 +- .../get_all_activity_groups.py | 8 +- .../update_activity_groups.py | 8 +- .../v201802}/activity_service/__init__.py | 0 .../activity_service/create_activities.py | 6 +- .../activity_service/get_active_activities.py | 8 +- .../activity_service/get_all_activities.py | 8 +- .../activity_service/update_activities.py | 8 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 6 +- .../get_all_audience_segments.py | 8 +- .../get_first_party_audience_segments.py | 8 +- .../populate_first_party_audience_segments.py | 8 +- .../update_audience_segments.py | 8 +- .../v201802}/base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 6 +- .../create_product_package_item_base_rates.py | 6 +- .../create_product_template_base_rates.py | 6 +- .../base_rate_service/get_all_base_rates.py | 11 +- .../get_base_rates_for_rate_card.py | 10 +- .../base_rate_service/update_base_rates.py | 10 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 6 +- .../get_all_cdn_configurations.py | 8 +- .../v201802}/company_service/__init__.py | 0 .../company_service/create_companies.py | 6 +- .../company_service/get_advertisers.py | 8 +- .../company_service/get_all_companies.py | 8 +- .../company_service/update_companies.py | 8 +- .../v201802}/contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 6 +- .../contact_service/get_all_contacts.py | 8 +- .../contact_service/get_uninvited_contacts.py | 8 +- .../contact_service/update_contacts.py | 8 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 9 +- ...delete_content_metadata_key_hierarchies.py | 10 +- ...et_all_content_metadata_key_hierarchies.py | 8 +- ...update_content_metadata_key_hierarchies.py | 11 +- .../v201802}/content_service/__init__.py | 0 .../content_service/get_all_content.py | 8 +- .../v201802}/creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 10 +- .../create_creative_from_template.py | 10 +- .../creative_service/create_creatives.py | 10 +- .../create_custom_creative.py | 12 +- .../create_native_creative.py | 6 +- .../creative_service/get_all_creatives.py | 8 +- .../creative_service/get_image_creatives.py | 8 +- .../creative_service/update_creatives.py | 8 +- .../v201802}/creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 6 +- .../create_creative_set.py | 6 +- .../get_all_creative_sets.py | 8 +- .../get_creative_sets_for_master_creative.py | 8 +- .../update_creative_set.py | 8 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 8 +- .../get_system_defined_creative_templates.py | 8 +- .../create_creative_wrappers.py | 6 +- .../deactivate_creative_wrapper.py | 8 +- .../get_active_creative_wrappers.py | 8 +- .../get_all_creative_wrappers.py | 8 +- .../update_creative_wrappers.py | 8 +- .../v201802}/custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 6 +- .../create_custom_fields.py | 6 +- .../deactivate_all_line_item_custom_fields.py | 8 +- .../get_all_custom_fields.py | 8 +- .../get_custom_fields_for_line_items.py | 8 +- .../set_line_item_custom_field_value.py | 16 +- .../update_custom_fields.py | 8 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 6 +- .../delete_custom_targeting_keys.py | 10 +- .../delete_custom_targeting_values.py | 10 +- ...et_all_custom_targeting_keys_and_values.py | 10 +- ...efined_custom_targeting_keys_and_values.py | 10 +- .../update_custom_targeting_keys.py | 8 +- .../update_custom_targeting_values.py | 8 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 6 +- .../get_all_exchange_rates.py | 8 +- .../get_exchange_rates_for_currency_code.py | 8 +- .../update_exchange_rates.py | 8 +- .../get_availability_forecast.py | 6 +- ...get_availability_forecast_for_line_item.py | 6 +- .../get_delivery_forecast_for_line_items.py | 6 +- .../v201802}/inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 8 +- .../inventory_service/create_ad_units.py | 6 +- .../get_ad_unit_hierarchy.py | 10 +- .../get_all_ad_unit_sizes.py | 8 +- .../inventory_service/get_all_ad_units.py | 8 +- .../get_top_level_ad_units.py | 8 +- .../inventory_service/update_ad_units.py | 8 +- .../v201802}/label_service/__init__.py | 0 .../v201802/label_service/create_labels.py | 8 +- .../label_service/deactivate_labels.py | 10 +- .../label_service/get_active_labels.py | 8 +- .../v201802/label_service/get_all_labels.py | 8 +- .../v201802/label_service/update_labels.py | 10 +- .../__init__.py | 0 .../create_licas.py | 6 +- .../deactivate_licas.py | 8 +- .../get_all_licas.py | 8 +- .../get_licas_for_line_item.py | 8 +- .../update_licas.py | 8 +- .../v201802}/line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 8 +- .../line_item_service/create_line_items.py | 6 +- .../create_video_line_item.py | 8 +- .../line_item_service/get_all_line_items.py | 8 +- .../get_line_items_that_need_creatives.py | 8 +- .../get_recently_updated_line_items.py | 8 +- .../line_item_service/pause_line_items.py | 8 +- .../target_custom_criteria.py | 8 +- .../line_item_service/update_line_items.py | 8 +- .../activate_live_stream_events.py | 10 +- .../create_live_stream_events.py | 6 +- .../get_all_live_stream_events.py | 8 +- .../register_sessions_for_monitoring.py | 6 +- .../update_live_stream_events.py | 8 +- .../v201802}/native_style_service/__init__.py | 0 .../create_native_styles.py | 8 +- .../get_all_native_styles.py | 8 +- .../v201802}/network_service/__init__.py | 0 .../network_service/get_all_networks.py | 6 +- .../network_service/get_current_network.py | 6 +- .../network_service/make_test_network.py | 20 +- .../v201802}/order_service/__init__.py | 0 .../v201802/order_service/approve_orders.py | 8 +- .../v201802/order_service/create_orders.py | 6 +- .../v201802/order_service/get_all_orders.py | 8 +- .../order_service/get_orders_starting_soon.py | 8 +- .../v201802/order_service/update_orders.py | 8 +- .../package_service/create_packages.py | 6 +- ...reate_proposal_line_items_from_packages.py | 8 +- .../package_service/get_all_packages.py | 8 +- .../get_in_progress_packages.py | 8 +- .../placement_service/create_placements.py | 8 +- .../deactivate_placements.py | 8 +- .../get_active_placements.py | 8 +- .../placement_service/get_all_placements.py | 8 +- .../placement_service/update_placements.py | 8 +- .../v201802}/premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 8 +- .../get_all_premium_rates.py | 15 +- .../get_premium_rates_for_rate_card.py | 8 +- .../update_premium_rates.py | 8 +- .../create_product_package_item.py | 6 +- .../get_all_product_package_items.py | 8 +- ...oduct_package_items_for_product_package.py | 8 +- .../create_product_packages.py | 6 +- .../get_active_product_packages.py | 8 +- .../get_all_product_packages.py | 8 +- .../v201802}/product_service/__init__.py | 0 .../product_service/get_all_products.py | 8 +- .../get_products_for_product_template.py | 8 +- .../product_service/update_products.py | 8 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 8 +- .../create_product_templates.py | 6 +- .../create_programmatic_product_templates.py | 6 +- .../get_all_product_templates.py | 8 +- .../get_sponsorship_product_templates.py | 8 +- .../update_product_templates.py | 8 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 8 +- ...create_programmatic_proposal_line_items.py | 6 +- ...sal_line_items_for_non_sales_management.py | 6 +- .../create_proposal_line_items.py | 6 +- .../get_all_proposal_line_items.py | 8 +- .../get_proposal_line_items_for_proposal.py | 8 +- .../update_proposal_line_items.py | 8 +- .../v201802}/proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 8 +- ...atic_proposals_for_non_sales_management.py | 6 +- .../proposal_service/create_proposals.py | 6 +- .../proposal_service/get_all_proposals.py | 8 +- .../get_marketplace_comments.py | 6 +- .../get_proposals_pending_approval.py | 8 +- .../request_buyers_acceptance.py | 8 +- .../submit_proposals_for_approval.py | 8 +- .../proposal_service/update_proposals.py | 8 +- .../__init__.py | 0 .../fetch_match_tables.py | 6 +- .../get_all_browsers.py | 6 +- .../get_all_programmatic_buyers.py | 6 +- .../get_geo_targets.py | 6 +- .../get_line_items_named_like.py | 6 +- .../get_recent_changes.py | 10 +- .../v201802}/rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 6 +- .../rate_card_service/get_all_rate_cards.py | 8 +- .../get_marketplace_rate_cards.py | 8 +- ..._item_reports_for_reconciliation_report.py | 8 +- ...update_reconciliation_line_item_reports.py | 10 +- ...order_reports_for_reconciliation_report.py | 8 +- .../submit_reconciliation_order_reports.py | 8 +- ...n_report_rows_for_reconciliation_report.py | 10 +- .../update_reconciliation_report_rows.py | 8 +- .../get_all_reconciliation_reports.py | 8 +- ...iliation_report_for_last_billing_period.py | 8 +- .../v201802}/report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 10 +- .../report_service/run_delivery_report.py | 12 +- .../report_service/run_inventory_report.py | 10 +- .../report_service/run_reach_report.py | 8 +- .../run_report_and_create_match_table.py | 8 +- .../run_report_with_custom_fields.py | 10 +- .../report_service/run_sales_report.py | 8 +- .../v201802/report_service/run_saved_query.py | 10 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 10 +- .../get_all_suggested_ad_units.py | 8 +- ...get_highly_requested_suggested_ad_units.py | 8 +- .../v201802}/team_service/__init__.py | 0 .../v201802/team_service/create_teams.py | 6 +- .../v201802/team_service/get_all_teams.py | 8 +- .../v201802/team_service/update_teams.py | 8 +- .../v201802}/user_service/__init__.py | 0 .../v201802/user_service/create_users.py | 6 +- .../v201802/user_service/deactivate_users.py | 8 +- .../v201802}/user_service/get_all_roles.py | 6 +- .../v201802/user_service/get_all_users.py | 8 +- .../v201802/user_service/get_current_user.py | 6 +- .../user_service/get_user_by_email_address.py | 8 +- .../v201802/user_service/update_users.py | 8 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 6 +- .../delete_user_team_associations.py | 8 +- .../get_all_user_team_associations.py | 8 +- .../get_user_team_associations_for_user.py | 8 +- .../update_user_team_associations.py | 8 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 8 +- .../get_workflow_approval_requests.py | 8 +- ...et_workflow_external_condition_requests.py | 8 +- ...er_workflow_external_condition_requests.py | 8 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 6 +- .../get_active_activity_groups.py | 8 +- .../get_all_activity_groups.py | 8 +- .../update_activity_groups.py | 8 +- .../v201805}/activity_service/__init__.py | 0 .../activity_service/create_activities.py | 6 +- .../activity_service/get_active_activities.py | 8 +- .../activity_service/get_all_activities.py | 8 +- .../activity_service/update_activities.py | 8 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 6 +- .../get_all_audience_segments.py | 8 +- .../get_first_party_audience_segments.py | 8 +- .../populate_first_party_audience_segments.py | 8 +- .../update_audience_segments.py | 8 +- .../v201805}/base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 6 +- .../create_product_package_item_base_rates.py | 6 +- .../create_product_template_base_rates.py | 6 +- .../base_rate_service/get_all_base_rates.py | 11 +- .../get_base_rates_for_rate_card.py | 10 +- .../base_rate_service/update_base_rates.py | 10 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 6 +- .../get_all_cdn_configurations.py | 8 +- .../v201805}/company_service/__init__.py | 0 .../company_service/create_companies.py | 6 +- .../company_service/get_advertisers.py | 8 +- .../company_service/get_all_companies.py | 8 +- .../company_service/update_companies.py | 8 +- .../v201805}/contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 6 +- .../contact_service/get_all_contacts.py | 8 +- .../contact_service/get_uninvited_contacts.py | 8 +- .../contact_service/update_contacts.py | 8 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 9 +- ...et_all_content_metadata_key_hierarchies.py | 8 +- ...update_content_metadata_key_hierarchies.py | 11 +- .../v201805}/content_service/__init__.py | 0 .../content_service/get_all_content.py | 8 +- .../v201805}/creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 10 +- .../create_creative_from_template.py | 10 +- .../creative_service/create_creatives.py | 10 +- .../create_custom_creative.py | 12 +- .../create_native_creative.py | 6 +- .../creative_service/get_all_creatives.py | 8 +- .../creative_service/get_image_creatives.py | 8 +- .../creative_service/update_creatives.py | 8 +- .../v201805}/creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 6 +- .../create_creative_set.py | 6 +- .../get_all_creative_sets.py | 8 +- .../get_creative_sets_for_master_creative.py | 8 +- .../update_creative_set.py | 8 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 8 +- .../get_system_defined_creative_templates.py | 8 +- .../create_creative_wrappers.py | 6 +- .../deactivate_creative_wrapper.py | 8 +- .../get_active_creative_wrappers.py | 8 +- .../get_all_creative_wrappers.py | 8 +- .../update_creative_wrappers.py | 8 +- .../v201805}/custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 6 +- .../create_custom_fields.py | 6 +- .../deactivate_all_line_item_custom_fields.py | 8 +- .../get_all_custom_fields.py | 8 +- .../get_custom_fields_for_line_items.py | 8 +- .../set_line_item_custom_field_value.py | 16 +- .../update_custom_fields.py | 8 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 6 +- .../delete_custom_targeting_keys.py | 10 +- .../delete_custom_targeting_values.py | 10 +- ...et_all_custom_targeting_keys_and_values.py | 10 +- ...efined_custom_targeting_keys_and_values.py | 10 +- .../update_custom_targeting_keys.py | 8 +- .../update_custom_targeting_values.py | 8 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 6 +- .../get_all_exchange_rates.py | 8 +- .../get_exchange_rates_for_currency_code.py | 8 +- .../update_exchange_rates.py | 8 +- .../get_availability_forecast.py | 6 +- ...get_availability_forecast_for_line_item.py | 6 +- .../get_delivery_forecast_for_line_items.py | 6 +- .../v201805}/inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 8 +- .../inventory_service/create_ad_units.py | 6 +- .../get_ad_unit_hierarchy.py | 10 +- .../get_all_ad_unit_sizes.py | 8 +- .../inventory_service/get_all_ad_units.py | 8 +- .../get_top_level_ad_units.py | 8 +- .../inventory_service/update_ad_units.py | 8 +- .../v201805}/label_service/__init__.py | 0 .../v201805/label_service/create_labels.py | 8 +- .../label_service/deactivate_labels.py | 10 +- .../label_service/get_active_labels.py | 8 +- .../v201805/label_service/get_all_labels.py | 8 +- .../v201805/label_service/update_labels.py | 10 +- .../__init__.py | 0 .../create_licas.py | 6 +- .../deactivate_licas.py | 8 +- .../get_all_licas.py | 8 +- .../get_licas_for_line_item.py | 8 +- .../update_licas.py | 8 +- .../v201805}/line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 8 +- .../line_item_service/create_line_items.py | 6 +- .../create_video_line_item.py | 8 +- .../line_item_service/get_all_line_items.py | 8 +- .../get_line_items_that_need_creatives.py | 8 +- .../get_recently_updated_line_items.py | 8 +- .../line_item_service/pause_line_items.py | 8 +- .../target_custom_criteria.py | 8 +- .../line_item_service/update_line_items.py | 8 +- .../activate_live_stream_events.py | 10 +- .../create_live_stream_events.py | 6 +- .../get_all_live_stream_events.py | 8 +- .../register_sessions_for_monitoring.py | 6 +- .../update_live_stream_events.py | 8 +- .../v201805}/native_style_service/__init__.py | 0 .../create_native_styles.py | 8 +- .../get_all_native_styles.py | 8 +- .../v201805}/network_service/__init__.py | 0 .../network_service/get_all_networks.py | 6 +- .../network_service/get_current_network.py | 6 +- .../network_service/make_test_network.py | 20 +- .../v201805}/order_service/__init__.py | 0 .../v201805/order_service/approve_orders.py | 8 +- .../v201805/order_service/create_orders.py | 6 +- .../v201805/order_service/get_all_orders.py | 8 +- .../order_service/get_orders_starting_soon.py | 8 +- .../v201805/order_service/update_orders.py | 8 +- .../package_service/create_packages.py | 6 +- ...reate_proposal_line_items_from_packages.py | 8 +- .../package_service/get_all_packages.py | 8 +- .../get_in_progress_packages.py | 8 +- .../placement_service/create_placements.py | 8 +- .../deactivate_placements.py | 8 +- .../get_active_placements.py | 8 +- .../placement_service/get_all_placements.py | 8 +- .../placement_service/update_placements.py | 8 +- .../v201805}/premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 8 +- .../get_all_premium_rates.py | 15 +- .../get_premium_rates_for_rate_card.py | 8 +- .../update_premium_rates.py | 8 +- .../create_product_package_item.py | 6 +- .../get_all_product_package_items.py | 8 +- ...oduct_package_items_for_product_package.py | 8 +- .../create_product_packages.py | 6 +- .../get_active_product_packages.py | 8 +- .../get_all_product_packages.py | 8 +- .../v201805}/product_service/__init__.py | 0 .../product_service/get_all_products.py | 8 +- .../get_products_for_product_template.py | 8 +- .../product_service/update_products.py | 8 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 8 +- .../create_product_templates.py | 6 +- .../create_programmatic_product_templates.py | 6 +- .../get_all_product_templates.py | 8 +- .../get_sponsorship_product_templates.py | 8 +- .../update_product_templates.py | 8 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 8 +- ...create_programmatic_proposal_line_items.py | 6 +- ...sal_line_items_for_non_sales_management.py | 6 +- .../create_proposal_line_items.py | 6 +- .../get_all_proposal_line_items.py | 8 +- .../get_proposal_line_items_for_proposal.py | 8 +- .../update_proposal_line_items.py | 8 +- .../v201805}/proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 8 +- ...atic_proposals_for_non_sales_management.py | 6 +- .../proposal_service/create_proposals.py | 6 +- .../proposal_service/get_all_proposals.py | 8 +- .../get_marketplace_comments.py | 6 +- .../get_proposals_pending_approval.py | 8 +- .../request_buyers_acceptance.py | 8 +- .../submit_proposals_for_approval.py | 8 +- .../proposal_service/update_proposals.py | 8 +- .../__init__.py | 0 .../fetch_match_tables.py | 6 +- .../get_all_browsers.py | 6 +- .../get_all_programmatic_buyers.py | 6 +- .../get_geo_targets.py | 6 +- .../get_line_items_named_like.py | 6 +- .../get_recent_changes.py | 10 +- .../v201805}/rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 6 +- .../rate_card_service/get_all_rate_cards.py | 8 +- .../get_marketplace_rate_cards.py | 8 +- ..._item_reports_for_reconciliation_report.py | 8 +- ...update_reconciliation_line_item_reports.py | 10 +- ...order_reports_for_reconciliation_report.py | 8 +- .../submit_reconciliation_order_reports.py | 8 +- ...n_report_rows_for_reconciliation_report.py | 10 +- .../update_reconciliation_report_rows.py | 8 +- .../get_all_reconciliation_reports.py | 8 +- ...iliation_report_for_last_billing_period.py | 8 +- .../v201805}/report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 10 +- .../report_service/run_delivery_report.py | 12 +- .../report_service/run_inventory_report.py | 10 +- .../report_service/run_reach_report.py | 8 +- .../run_report_and_create_match_table.py | 8 +- .../run_report_with_custom_fields.py | 10 +- .../report_service/run_sales_report.py | 8 +- .../v201805/report_service/run_saved_query.py | 10 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 10 +- .../get_all_suggested_ad_units.py | 8 +- ...get_highly_requested_suggested_ad_units.py | 8 +- .../v201805}/team_service/__init__.py | 0 .../v201805/team_service/create_teams.py | 6 +- .../v201805/team_service/get_all_teams.py | 8 +- .../v201805/team_service/update_teams.py | 8 +- .../v201805}/user_service/__init__.py | 0 .../v201805/user_service/create_users.py | 6 +- .../v201805/user_service/deactivate_users.py | 8 +- .../v201805}/user_service/get_all_roles.py | 6 +- .../v201805/user_service/get_all_users.py | 8 +- .../v201805/user_service/get_current_user.py | 6 +- .../user_service/get_user_by_email_address.py | 8 +- .../v201805/user_service/update_users.py | 8 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 6 +- .../delete_user_team_associations.py | 8 +- .../get_all_user_team_associations.py | 8 +- .../get_user_team_associations_for_user.py | 8 +- .../update_user_team_associations.py | 8 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 8 +- .../get_workflow_approval_requests.py | 8 +- ...et_workflow_external_condition_requests.py | 8 +- ...er_workflow_external_condition_requests.py | 8 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 8 +- .../get_active_activity_groups.py | 12 +- .../get_all_activity_groups.py | 10 +- .../update_activity_groups.py | 10 +- .../v201808}/activity_service/__init__.py | 0 .../activity_service/create_activities.py | 8 +- .../activity_service/get_active_activities.py | 12 +- .../activity_service/get_all_activities.py | 10 +- .../activity_service/update_activities.py | 10 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 10 +- .../get_all_audience_segments.py | 10 +- .../get_first_party_audience_segments.py | 12 +- .../populate_first_party_audience_segments.py | 10 +- .../update_audience_segments.py | 10 +- .../v201808}/base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 8 +- .../create_product_package_item_base_rates.py | 8 +- .../create_product_template_base_rates.py | 8 +- .../base_rate_service/get_all_base_rates.py | 13 +- .../get_base_rates_for_rate_card.py | 14 +- .../base_rate_service/update_base_rates.py | 12 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 8 +- .../get_all_cdn_configurations.py | 10 +- .../v201808}/company_service/__init__.py | 0 .../company_service/create_companies.py | 8 +- .../company_service/get_advertisers.py | 12 +- .../company_service/get_all_companies.py | 10 +- .../company_service/update_companies.py | 10 +- .../v201808}/contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 8 +- .../contact_service/get_all_contacts.py | 10 +- .../contact_service/get_uninvited_contacts.py | 12 +- .../contact_service/update_contacts.py | 10 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 11 +- ...et_all_content_metadata_key_hierarchies.py | 10 +- ...update_content_metadata_key_hierarchies.py | 13 +- .../v201808}/content_service/__init__.py | 0 .../content_service/get_all_content.py | 10 +- .../v201808}/creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 12 +- .../create_creative_from_template.py | 12 +- .../creative_service/create_creatives.py | 12 +- .../create_custom_creative.py | 14 +- .../create_native_creative.py | 8 +- .../creative_service/get_all_creatives.py | 10 +- .../creative_service/get_image_creatives.py | 12 +- .../creative_service/update_creatives.py | 12 +- .../v201808}/creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 8 +- .../create_creative_set.py | 8 +- .../get_all_creative_sets.py | 10 +- .../get_creative_sets_for_master_creative.py | 12 +- .../update_creative_set.py | 10 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 10 +- .../get_system_defined_creative_templates.py | 12 +- .../create_creative_wrappers.py | 8 +- .../deactivate_creative_wrapper.py | 12 +- .../get_active_creative_wrappers.py | 12 +- .../get_all_creative_wrappers.py | 10 +- .../update_creative_wrappers.py | 10 +- .../v201808}/custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 8 +- .../create_custom_fields.py | 8 +- .../deactivate_all_line_item_custom_fields.py | 12 +- .../get_all_custom_fields.py | 10 +- .../get_custom_fields_for_line_items.py | 12 +- .../set_line_item_custom_field_value.py | 57 ++-- .../update_custom_fields.py | 10 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 8 +- .../delete_custom_targeting_keys.py | 16 +- .../delete_custom_targeting_values.py | 29 +- ...et_all_custom_targeting_keys_and_values.py | 18 +- ...efined_custom_targeting_keys_and_values.py | 12 +- .../update_custom_targeting_keys.py | 10 +- .../update_custom_targeting_values.py | 12 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 8 +- .../get_all_exchange_rates.py | 10 +- .../get_exchange_rates_for_currency_code.py | 12 +- .../update_exchange_rates.py | 10 +- .../get_availability_forecast.py | 251 ++++++++++++++++++ ...get_availability_forecast_for_line_item.py | 9 +- .../get_delivery_forecast_for_line_items.py | 8 +- .../v201808}/inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 12 +- .../inventory_service/create_ad_units.py | 8 +- .../get_ad_unit_hierarchy.py | 14 +- .../get_all_ad_unit_sizes.py | 10 +- .../inventory_service/get_all_ad_units.py | 10 +- .../get_top_level_ad_units.py | 12 +- .../inventory_service/update_ad_units.py | 10 +- .../v201808}/label_service/__init__.py | 0 .../v201808}/label_service/create_labels.py | 10 +- .../label_service/deactivate_labels.py | 14 +- .../label_service/get_active_labels.py | 12 +- .../v201808}/label_service/get_all_labels.py | 10 +- .../v201808}/label_service/update_labels.py | 12 +- .../__init__.py | 0 .../create_licas.py | 8 +- .../deactivate_licas.py | 12 +- .../get_all_licas.py | 10 +- .../get_licas_for_line_item.py | 12 +- .../update_licas.py | 10 +- .../v201808}/line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 12 +- .../line_item_service/create_line_items.py | 8 +- .../create_video_line_item.py | 10 +- .../line_item_service/get_all_line_items.py | 10 +- .../get_line_items_that_need_creatives.py | 12 +- .../get_recently_updated_line_items.py | 12 +- .../line_item_service/pause_line_items.py | 10 +- .../target_custom_criteria.py | 10 +- .../line_item_service/update_line_items.py | 10 +- .../activate_live_stream_events.py | 12 +- .../create_live_stream_events.py | 8 +- .../get_all_live_stream_events.py | 10 +- .../register_sessions_for_monitoring.py | 8 +- .../update_live_stream_events.py | 10 +- .../v201808}/native_style_service/__init__.py | 0 .../create_native_styles.py | 10 +- .../get_all_native_styles.py | 10 +- .../v201808}/network_service/__init__.py | 0 .../network_service/get_all_networks.py | 8 +- .../network_service/get_current_network.py | 8 +- .../network_service/make_test_network.py | 22 +- .../v201808}/order_service/__init__.py | 0 .../v201808}/order_service/approve_orders.py | 12 +- .../v201808}/order_service/create_orders.py | 8 +- .../v201808}/order_service/get_all_orders.py | 10 +- .../order_service/get_orders_starting_soon.py | 12 +- .../v201808}/order_service/update_orders.py | 10 +- .../package_service/create_packages.py | 8 +- ...reate_proposal_line_items_from_packages.py | 10 +- .../package_service/get_all_packages.py | 10 +- .../get_in_progress_packages.py | 12 +- .../placement_service/create_placements.py | 12 +- .../deactivate_placements.py | 10 +- .../get_active_placements.py | 12 +- .../placement_service/get_all_placements.py | 10 +- .../placement_service/update_placements.py | 10 +- .../v201808}/premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 10 +- .../get_all_premium_rates.py | 17 +- .../get_premium_rates_for_rate_card.py | 12 +- .../update_premium_rates.py | 10 +- .../create_product_package_item.py | 8 +- .../get_all_product_package_items.py | 10 +- ...oduct_package_items_for_product_package.py | 12 +- .../create_product_packages.py | 8 +- .../get_active_product_packages.py | 12 +- .../get_all_product_packages.py | 10 +- .../v201808}/product_service/__init__.py | 0 .../product_service/get_all_products.py | 10 +- .../get_products_for_product_template.py | 12 +- .../product_service/update_products.py | 10 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 12 +- .../create_product_templates.py | 10 +- .../create_programmatic_product_templates.py | 10 +- .../get_all_product_templates.py | 10 +- .../get_sponsorship_product_templates.py | 12 +- .../update_product_templates.py | 10 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 12 +- ...create_programmatic_proposal_line_items.py | 10 +- ...sal_line_items_for_non_sales_management.py | 10 +- .../create_proposal_line_items.py | 10 +- .../get_all_proposal_line_items.py | 10 +- .../get_proposal_line_items_for_proposal.py | 12 +- .../update_proposal_line_items.py | 10 +- .../v201808}/proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 12 +- ...atic_proposals_for_non_sales_management.py | 8 +- .../proposal_service/create_proposals.py | 10 +- .../proposal_service/get_all_proposals.py | 10 +- .../get_marketplace_comments.py | 8 +- .../get_proposals_pending_approval.py | 12 +- .../request_buyers_acceptance.py | 12 +- .../submit_proposals_for_approval.py | 12 +- .../proposal_service/update_proposals.py | 10 +- .../__init__.py | 0 .../fetch_match_tables.py | 8 +- .../get_all_browsers.py | 8 +- .../get_all_programmatic_buyers.py | 8 +- .../get_geo_targets.py | 10 +- .../get_line_items_named_like.py | 8 +- .../get_recent_changes.py | 12 +- .../v201808}/rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 8 +- .../rate_card_service/get_all_rate_cards.py | 10 +- .../get_marketplace_rate_cards.py | 12 +- ..._item_reports_for_reconciliation_report.py | 10 +- ...update_reconciliation_line_item_reports.py | 12 +- ...order_reports_for_reconciliation_report.py | 12 +- .../submit_reconciliation_order_reports.py | 10 +- ...n_report_rows_for_reconciliation_report.py | 14 +- .../update_reconciliation_report_rows.py | 10 +- .../get_all_reconciliation_reports.py | 10 +- ...iliation_report_for_last_billing_period.py | 12 +- .../v201808}/report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 66 +++++ .../report_service/run_delivery_report.py | 14 +- .../report_service/run_inventory_report.py | 14 +- .../report_service/run_reach_report.py | 10 +- .../run_report_and_create_match_table.py | 10 +- .../run_report_with_custom_fields.py | 16 +- .../report_service/run_sales_report.py | 10 +- .../report_service/run_saved_query.py | 14 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 24 +- .../get_all_suggested_ad_units.py | 10 +- ...get_highly_requested_suggested_ad_units.py | 12 +- .../v201808}/team_service/__init__.py | 0 .../v201808}/team_service/create_teams.py | 8 +- .../v201808}/team_service/get_all_teams.py | 10 +- .../v201808}/team_service/update_teams.py | 10 +- .../v201808}/user_service/__init__.py | 0 .../v201808}/user_service/create_users.py | 8 +- .../v201808}/user_service/deactivate_users.py | 10 +- .../v201808}/user_service/get_all_roles.py | 6 +- .../v201808}/user_service/get_all_users.py | 10 +- .../v201808}/user_service/get_current_user.py | 8 +- .../user_service/get_user_by_email_address.py | 12 +- .../v201808}/user_service/update_users.py | 10 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 8 +- .../delete_user_team_associations.py | 10 +- .../get_all_user_team_associations.py | 10 +- .../get_user_team_associations_for_user.py | 12 +- .../update_user_team_associations.py | 10 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 12 +- .../get_workflow_approval_requests.py | 12 +- ...et_workflow_external_condition_requests.py | 12 +- ...er_workflow_external_condition_requests.py | 12 +- ...delete_content_metadata_key_hierarchies.py | 81 ------ .../get_availability_forecast.py | 130 --------- googleads.yaml | 4 +- googleads/__init__.py | 2 +- googleads/{dfp.py => ad_manager.py} | 184 ++++++------- googleads/common.py | 22 +- googleads/errors.py | 10 +- googleads/oauth2.py | 6 +- setup.py | 4 +- tests/{dfp_test.py => ad_manager_test.py} | 239 +++++++++-------- tests/common_test.py | 37 ++- tests/oauth2_test.py | 10 +- ...vice.xml => ad_manager_report_service.xml} | 0 tests/util_test.py | 38 +-- 745 files changed, 3401 insertions(+), 3261 deletions(-) rename examples/{dfp/authentication/create_dfp_client_with_access_token.py => ad_manager/authentication/create_ad_manager_client_with_access_token.py} (85%) rename examples/{dfp/authentication/create_dfp_client_with_refresh_token.py => ad_manager/authentication/create_ad_manager_client_with_refresh_token.py} (81%) rename examples/{dfp/authentication/create_dfp_client_with_service_account.py => ad_manager/authentication/create_ad_manager_client_with_service_account.py} (77%) rename examples/{dfp => ad_manager}/authentication/generate_refresh_token.py (96%) rename examples/{dfp/v201711 => ad_manager/v201802}/activity_group_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/activity_group_service/create_activity_groups.py (93%) rename examples/{dfp => ad_manager}/v201802/activity_group_service/get_active_activity_groups.py (91%) rename examples/{dfp => ad_manager}/v201802/activity_group_service/get_all_activity_groups.py (90%) rename examples/{dfp => ad_manager}/v201802/activity_group_service/update_activity_groups.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/activity_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/activity_service/create_activities.py (93%) rename examples/{dfp => ad_manager}/v201802/activity_service/get_active_activities.py (90%) rename examples/{dfp => ad_manager}/v201802/activity_service/get_all_activities.py (90%) rename examples/{dfp => ad_manager}/v201802/activity_service/update_activities.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/audience_segment_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/audience_segment_service/create_audience_segments.py (94%) rename examples/{dfp => ad_manager}/v201802/audience_segment_service/get_all_audience_segments.py (91%) rename examples/{dfp => ad_manager}/v201802/audience_segment_service/get_first_party_audience_segments.py (91%) rename examples/{dfp => ad_manager}/v201802/audience_segment_service/populate_first_party_audience_segments.py (91%) rename examples/{dfp => ad_manager}/v201802/audience_segment_service/update_audience_segments.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/base_rate_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/base_rate_service/create_product_base_rates.py (92%) rename examples/{dfp => ad_manager}/v201802/base_rate_service/create_product_package_item_base_rates.py (94%) rename examples/{dfp => ad_manager}/v201802/base_rate_service/create_product_template_base_rates.py (92%) rename examples/{dfp => ad_manager}/v201802/base_rate_service/get_all_base_rates.py (84%) rename examples/{dfp => ad_manager}/v201802/base_rate_service/get_base_rates_for_rate_card.py (87%) rename examples/{dfp => ad_manager}/v201802/base_rate_service/update_base_rates.py (90%) rename examples/{dfp/v201711 => ad_manager/v201802}/cdn_configuration_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/cdn_configuration_service/create_cdn_configurations.py (95%) rename examples/{dfp => ad_manager}/v201802/cdn_configuration_service/get_all_cdn_configurations.py (91%) rename examples/{dfp/v201711 => ad_manager/v201802}/company_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/company_service/create_companies.py (93%) rename examples/{dfp => ad_manager}/v201802/company_service/get_advertisers.py (90%) rename examples/{dfp => ad_manager}/v201802/company_service/get_all_companies.py (90%) rename examples/{dfp => ad_manager}/v201802/company_service/update_companies.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/contact_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/contact_service/create_contacts.py (92%) rename examples/{dfp => ad_manager}/v201802/contact_service/get_all_contacts.py (90%) rename examples/{dfp => ad_manager}/v201802/contact_service/get_uninvited_contacts.py (90%) rename examples/{dfp => ad_manager}/v201802/contact_service/update_contacts.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (91%) rename examples/{dfp => ad_manager}/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py (91%) rename examples/{dfp => ad_manager}/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (91%) rename examples/{dfp => ad_manager}/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (91%) rename examples/{dfp/v201711 => ad_manager/v201802}/content_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/content_service/get_all_content.py (90%) rename examples/{dfp/v201711 => ad_manager/v201802}/creative_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/creative_service/copy_image_creatives.py (88%) rename examples/{dfp => ad_manager}/v201802/creative_service/create_creative_from_template.py (92%) rename examples/{dfp => ad_manager}/v201802/creative_service/create_creatives.py (90%) rename examples/{dfp => ad_manager}/v201802/creative_service/create_custom_creative.py (89%) rename examples/{dfp => ad_manager}/v201802/creative_service/create_native_creative.py (97%) rename examples/{dfp => ad_manager}/v201802/creative_service/get_all_creatives.py (90%) rename examples/{dfp => ad_manager}/v201802/creative_service/get_image_creatives.py (90%) rename examples/{dfp => ad_manager}/v201802/creative_service/update_creatives.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/creative_set_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/creative_set_service/associate_creative_set_to_line_item.py (92%) rename examples/{dfp => ad_manager}/v201802/creative_set_service/create_creative_set.py (92%) rename examples/{dfp => ad_manager}/v201802/creative_set_service/get_all_creative_sets.py (90%) rename examples/{dfp => ad_manager}/v201802/creative_set_service/get_creative_sets_for_master_creative.py (90%) rename examples/{dfp => ad_manager}/v201802/creative_set_service/update_creative_set.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/creative_template_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/creative_template_service/get_all_creative_templates.py (90%) rename examples/{dfp => ad_manager}/v201802/creative_template_service/get_system_defined_creative_templates.py (91%) rename examples/{dfp => ad_manager}/v201802/creative_wrapper_service/create_creative_wrappers.py (94%) rename examples/{dfp => ad_manager}/v201802/creative_wrapper_service/deactivate_creative_wrapper.py (93%) rename examples/{dfp => ad_manager}/v201802/creative_wrapper_service/get_active_creative_wrappers.py (91%) rename examples/{dfp => ad_manager}/v201802/creative_wrapper_service/get_all_creative_wrappers.py (90%) rename examples/{dfp => ad_manager}/v201802/creative_wrapper_service/update_creative_wrappers.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/custom_field_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/custom_field_service/create_custom_field_options.py (93%) rename examples/{dfp => ad_manager}/v201802/custom_field_service/create_custom_fields.py (93%) rename examples/{dfp => ad_manager}/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py (93%) rename examples/{dfp => ad_manager}/v201802/custom_field_service/get_all_custom_fields.py (90%) rename examples/{dfp => ad_manager}/v201802/custom_field_service/get_custom_fields_for_line_items.py (91%) rename examples/{dfp => ad_manager}/v201802/custom_field_service/set_line_item_custom_field_value.py (91%) rename examples/{dfp => ad_manager}/v201802/custom_field_service/update_custom_fields.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/custom_targeting_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py (96%) rename examples/{dfp => ad_manager}/v201802/custom_targeting_service/delete_custom_targeting_keys.py (91%) rename examples/{dfp => ad_manager}/v201802/custom_targeting_service/delete_custom_targeting_values.py (91%) rename examples/{dfp => ad_manager}/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (91%) rename examples/{dfp => ad_manager}/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (92%) rename examples/{dfp => ad_manager}/v201802/custom_targeting_service/update_custom_targeting_keys.py (91%) rename examples/{dfp => ad_manager}/v201802/custom_targeting_service/update_custom_targeting_values.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/exchange_rate_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/exchange_rate_service/create_exchange_rates.py (93%) rename examples/{dfp => ad_manager}/v201802/exchange_rate_service/get_all_exchange_rates.py (91%) rename examples/{dfp => ad_manager}/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py (91%) rename examples/{dfp => ad_manager}/v201802/exchange_rate_service/update_exchange_rates.py (92%) rename examples/{dfp => ad_manager}/v201802/forecast_service/get_availability_forecast.py (96%) rename examples/{dfp => ad_manager}/v201802/forecast_service/get_availability_forecast_for_line_item.py (93%) rename examples/{dfp => ad_manager}/v201802/forecast_service/get_delivery_forecast_for_line_items.py (91%) rename examples/{dfp/v201711 => ad_manager/v201802}/inventory_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/inventory_service/archive_ad_units.py (92%) rename examples/{dfp => ad_manager}/v201802/inventory_service/create_ad_units.py (92%) rename examples/{dfp => ad_manager}/v201802/inventory_service/get_ad_unit_hierarchy.py (94%) rename examples/{dfp => ad_manager}/v201802/inventory_service/get_all_ad_unit_sizes.py (89%) rename examples/{dfp => ad_manager}/v201802/inventory_service/get_all_ad_units.py (90%) rename examples/{dfp => ad_manager}/v201802/inventory_service/get_top_level_ad_units.py (92%) rename examples/{dfp => ad_manager}/v201802/inventory_service/update_ad_units.py (93%) rename examples/{dfp/v201711 => ad_manager/v201802}/label_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/label_service/create_labels.py (89%) rename examples/{dfp => ad_manager}/v201802/label_service/deactivate_labels.py (89%) rename examples/{dfp => ad_manager}/v201802/label_service/get_active_labels.py (90%) rename examples/{dfp => ad_manager}/v201802/label_service/get_all_labels.py (90%) rename examples/{dfp => ad_manager}/v201802/label_service/update_labels.py (89%) rename examples/{dfp/v201711 => ad_manager/v201802}/line_item_creative_association_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/line_item_creative_association_service/create_licas.py (91%) rename examples/{dfp => ad_manager}/v201802/line_item_creative_association_service/deactivate_licas.py (92%) rename examples/{dfp => ad_manager}/v201802/line_item_creative_association_service/get_all_licas.py (92%) rename examples/{dfp => ad_manager}/v201802/line_item_creative_association_service/get_licas_for_line_item.py (92%) rename examples/{dfp => ad_manager}/v201802/line_item_creative_association_service/update_licas.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/line_item_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/line_item_service/activate_line_items.py (93%) rename examples/{dfp => ad_manager}/v201802/line_item_service/create_line_items.py (96%) rename examples/{dfp => ad_manager}/v201802/line_item_service/create_video_line_item.py (94%) rename examples/{dfp => ad_manager}/v201802/line_item_service/get_all_line_items.py (90%) rename examples/{dfp => ad_manager}/v201802/line_item_service/get_line_items_that_need_creatives.py (91%) rename examples/{dfp => ad_manager}/v201802/line_item_service/get_recently_updated_line_items.py (91%) rename examples/{dfp => ad_manager}/v201802/line_item_service/pause_line_items.py (93%) rename examples/{dfp => ad_manager}/v201802/line_item_service/target_custom_criteria.py (93%) rename examples/{dfp => ad_manager}/v201802/line_item_service/update_line_items.py (93%) rename examples/{dfp => ad_manager}/v201802/live_stream_event_service/activate_live_stream_events.py (90%) rename examples/{dfp => ad_manager}/v201802/live_stream_event_service/create_live_stream_events.py (93%) rename examples/{dfp => ad_manager}/v201802/live_stream_event_service/get_all_live_stream_events.py (90%) rename examples/{dfp => ad_manager}/v201802/live_stream_event_service/register_sessions_for_monitoring.py (91%) rename examples/{dfp => ad_manager}/v201802/live_stream_event_service/update_live_stream_events.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/native_style_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/native_style_service/create_native_styles.py (95%) rename examples/{dfp => ad_manager}/v201802/native_style_service/get_all_native_styles.py (90%) rename examples/{dfp/v201711 => ad_manager/v201802}/network_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/network_service/get_all_networks.py (90%) rename examples/{dfp => ad_manager}/v201802/network_service/get_current_network.py (89%) rename examples/{dfp => ad_manager}/v201802/network_service/make_test_network.py (68%) rename examples/{dfp/v201711 => ad_manager/v201802}/order_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/order_service/approve_orders.py (92%) rename examples/{dfp => ad_manager}/v201802/order_service/create_orders.py (90%) rename examples/{dfp => ad_manager}/v201802/order_service/get_all_orders.py (90%) rename examples/{dfp => ad_manager}/v201802/order_service/get_orders_starting_soon.py (92%) rename examples/{dfp => ad_manager}/v201802/order_service/update_orders.py (92%) rename examples/{dfp => ad_manager}/v201802/package_service/create_packages.py (93%) rename examples/{dfp => ad_manager}/v201802/package_service/create_proposal_line_items_from_packages.py (92%) rename examples/{dfp => ad_manager}/v201802/package_service/get_all_packages.py (90%) rename examples/{dfp => ad_manager}/v201802/package_service/get_in_progress_packages.py (90%) rename examples/{dfp => ad_manager}/v201802/placement_service/create_placements.py (95%) rename examples/{dfp => ad_manager}/v201802/placement_service/deactivate_placements.py (91%) rename examples/{dfp => ad_manager}/v201802/placement_service/get_active_placements.py (90%) rename examples/{dfp => ad_manager}/v201802/placement_service/get_all_placements.py (90%) rename examples/{dfp => ad_manager}/v201802/placement_service/update_placements.py (90%) rename examples/{dfp/v201711 => ad_manager/v201802}/premium_rate_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/premium_rate_service/create_premium_rates.py (92%) rename examples/{dfp => ad_manager}/v201802/premium_rate_service/get_all_premium_rates.py (81%) rename examples/{dfp => ad_manager}/v201802/premium_rate_service/get_premium_rates_for_rate_card.py (91%) rename examples/{dfp => ad_manager}/v201802/premium_rate_service/update_premium_rates.py (93%) rename examples/{dfp => ad_manager}/v201802/product_package_item_service/create_product_package_item.py (94%) rename examples/{dfp => ad_manager}/v201802/product_package_item_service/get_all_product_package_items.py (91%) rename examples/{dfp => ad_manager}/v201802/product_package_item_service/get_product_package_items_for_product_package.py (91%) rename examples/{dfp => ad_manager}/v201802/product_package_service/create_product_packages.py (92%) rename examples/{dfp => ad_manager}/v201802/product_package_service/get_active_product_packages.py (91%) rename examples/{dfp => ad_manager}/v201802/product_package_service/get_all_product_packages.py (90%) rename examples/{dfp/v201711 => ad_manager/v201802}/product_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/product_service/get_all_products.py (90%) rename examples/{dfp => ad_manager}/v201802/product_service/get_products_for_product_template.py (90%) rename examples/{dfp => ad_manager}/v201802/product_service/update_products.py (91%) rename examples/{dfp/v201711 => ad_manager/v201802}/product_template_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/product_template_service/activate_product_templates.py (92%) rename examples/{dfp => ad_manager}/v201802/product_template_service/create_product_templates.py (96%) rename examples/{dfp => ad_manager}/v201802/product_template_service/create_programmatic_product_templates.py (95%) rename examples/{dfp => ad_manager}/v201802/product_template_service/get_all_product_templates.py (90%) rename examples/{dfp => ad_manager}/v201802/product_template_service/get_sponsorship_product_templates.py (91%) rename examples/{dfp => ad_manager}/v201802/product_template_service/update_product_templates.py (93%) rename examples/{dfp/v201711 => ad_manager/v201802}/proposal_line_item_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/proposal_line_item_service/archive_proposal_line_items.py (92%) rename examples/{dfp => ad_manager}/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py (95%) rename examples/{dfp => ad_manager}/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (95%) rename examples/{dfp => ad_manager}/v201802/proposal_line_item_service/create_proposal_line_items.py (95%) rename examples/{dfp => ad_manager}/v201802/proposal_line_item_service/get_all_proposal_line_items.py (90%) rename examples/{dfp => ad_manager}/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py (91%) rename examples/{dfp => ad_manager}/v201802/proposal_line_item_service/update_proposal_line_items.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/proposal_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/proposal_service/create_programmatic_proposals.py (91%) rename examples/{dfp => ad_manager}/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py (91%) rename examples/{dfp => ad_manager}/v201802/proposal_service/create_proposals.py (93%) rename examples/{dfp => ad_manager}/v201802/proposal_service/get_all_proposals.py (90%) rename examples/{dfp => ad_manager}/v201802/proposal_service/get_marketplace_comments.py (93%) rename examples/{dfp => ad_manager}/v201802/proposal_service/get_proposals_pending_approval.py (90%) rename examples/{dfp => ad_manager}/v201802/proposal_service/request_buyers_acceptance.py (92%) rename examples/{dfp => ad_manager}/v201802/proposal_service/submit_proposals_for_approval.py (92%) rename examples/{dfp => ad_manager}/v201802/proposal_service/update_proposals.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/publisher_query_language_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/publisher_query_language_service/fetch_match_tables.py (93%) rename examples/{dfp => ad_manager}/v201802/publisher_query_language_service/get_all_browsers.py (93%) rename examples/{dfp => ad_manager}/v201802/publisher_query_language_service/get_all_programmatic_buyers.py (92%) rename examples/{dfp => ad_manager}/v201802/publisher_query_language_service/get_geo_targets.py (92%) rename examples/{dfp => ad_manager}/v201802/publisher_query_language_service/get_line_items_named_like.py (92%) rename examples/{dfp => ad_manager}/v201802/publisher_query_language_service/get_recent_changes.py (95%) rename examples/{dfp/v201711 => ad_manager/v201802}/rate_card_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/rate_card_service/create_rate_cards.py (93%) rename examples/{dfp => ad_manager}/v201802/rate_card_service/get_all_rate_cards.py (90%) rename examples/{dfp => ad_manager}/v201802/rate_card_service/get_marketplace_rate_cards.py (91%) rename examples/{dfp => ad_manager}/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (94%) rename examples/{dfp => ad_manager}/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (91%) rename examples/{dfp => ad_manager}/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (91%) rename examples/{dfp => ad_manager}/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py (93%) rename examples/{dfp => ad_manager}/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (89%) rename examples/{dfp => ad_manager}/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py (94%) rename examples/{dfp => ad_manager}/v201802/reconciliation_report_service/get_all_reconciliation_reports.py (91%) rename examples/{dfp => ad_manager}/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/report_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/report_service/run_ad_exchange_report.py (89%) rename examples/{dfp => ad_manager}/v201802/report_service/run_delivery_report.py (90%) rename examples/{dfp => ad_manager}/v201802/report_service/run_inventory_report.py (92%) rename examples/{dfp => ad_manager}/v201802/report_service/run_reach_report.py (91%) rename examples/{dfp => ad_manager}/v201802/report_service/run_report_and_create_match_table.py (94%) rename examples/{dfp => ad_manager}/v201802/report_service/run_report_with_custom_fields.py (93%) rename examples/{dfp => ad_manager}/v201802/report_service/run_sales_report.py (91%) rename examples/{dfp => ad_manager}/v201802/report_service/run_saved_query.py (91%) rename examples/{dfp/v201711 => ad_manager/v201802}/suggested_ad_unit_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py (90%) rename examples/{dfp => ad_manager}/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py (91%) rename examples/{dfp => ad_manager}/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (91%) rename examples/{dfp/v201711 => ad_manager/v201802}/team_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/team_service/create_teams.py (92%) rename examples/{dfp => ad_manager}/v201802/team_service/get_all_teams.py (90%) rename examples/{dfp => ad_manager}/v201802/team_service/update_teams.py (92%) rename examples/{dfp/v201711 => ad_manager/v201802}/user_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/user_service/create_users.py (90%) rename examples/{dfp => ad_manager}/v201802/user_service/deactivate_users.py (91%) rename examples/{dfp/v201805 => ad_manager/v201802}/user_service/get_all_roles.py (90%) rename examples/{dfp => ad_manager}/v201802/user_service/get_all_users.py (90%) rename examples/{dfp => ad_manager}/v201802/user_service/get_current_user.py (90%) rename examples/{dfp => ad_manager}/v201802/user_service/get_user_by_email_address.py (90%) rename examples/{dfp => ad_manager}/v201802/user_service/update_users.py (90%) rename examples/{dfp/v201711 => ad_manager/v201802}/user_team_association_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/user_team_association_service/create_user_team_associations.py (93%) rename examples/{dfp => ad_manager}/v201802/user_team_association_service/delete_user_team_associations.py (93%) rename examples/{dfp => ad_manager}/v201802/user_team_association_service/get_all_user_team_associations.py (91%) rename examples/{dfp => ad_manager}/v201802/user_team_association_service/get_user_team_associations_for_user.py (91%) rename examples/{dfp => ad_manager}/v201802/user_team_association_service/update_user_team_associations.py (93%) rename examples/{dfp/v201711 => ad_manager/v201802}/workflow_request_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201802/workflow_request_service/approve_workflow_approval_requests.py (93%) rename examples/{dfp => ad_manager}/v201802/workflow_request_service/get_workflow_approval_requests.py (92%) rename examples/{dfp => ad_manager}/v201802/workflow_request_service/get_workflow_external_condition_requests.py (92%) rename examples/{dfp => ad_manager}/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py (94%) rename examples/{dfp/v201802 => ad_manager/v201805}/activity_group_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/activity_group_service/create_activity_groups.py (93%) rename examples/{dfp => ad_manager}/v201805/activity_group_service/get_active_activity_groups.py (91%) rename examples/{dfp => ad_manager}/v201805/activity_group_service/get_all_activity_groups.py (90%) rename examples/{dfp => ad_manager}/v201805/activity_group_service/update_activity_groups.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/activity_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/activity_service/create_activities.py (93%) rename examples/{dfp => ad_manager}/v201805/activity_service/get_active_activities.py (90%) rename examples/{dfp => ad_manager}/v201805/activity_service/get_all_activities.py (90%) rename examples/{dfp => ad_manager}/v201805/activity_service/update_activities.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/audience_segment_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/audience_segment_service/create_audience_segments.py (94%) rename examples/{dfp => ad_manager}/v201805/audience_segment_service/get_all_audience_segments.py (91%) rename examples/{dfp => ad_manager}/v201805/audience_segment_service/get_first_party_audience_segments.py (91%) rename examples/{dfp => ad_manager}/v201805/audience_segment_service/populate_first_party_audience_segments.py (91%) rename examples/{dfp => ad_manager}/v201805/audience_segment_service/update_audience_segments.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/base_rate_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/base_rate_service/create_product_base_rates.py (92%) rename examples/{dfp => ad_manager}/v201805/base_rate_service/create_product_package_item_base_rates.py (94%) rename examples/{dfp => ad_manager}/v201805/base_rate_service/create_product_template_base_rates.py (92%) rename examples/{dfp => ad_manager}/v201805/base_rate_service/get_all_base_rates.py (84%) rename examples/{dfp => ad_manager}/v201805/base_rate_service/get_base_rates_for_rate_card.py (87%) rename examples/{dfp => ad_manager}/v201805/base_rate_service/update_base_rates.py (90%) rename examples/{dfp/v201802 => ad_manager/v201805}/cdn_configuration_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/cdn_configuration_service/create_cdn_configurations.py (95%) rename examples/{dfp => ad_manager}/v201805/cdn_configuration_service/get_all_cdn_configurations.py (91%) rename examples/{dfp/v201802 => ad_manager/v201805}/company_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/company_service/create_companies.py (93%) rename examples/{dfp => ad_manager}/v201805/company_service/get_advertisers.py (90%) rename examples/{dfp => ad_manager}/v201805/company_service/get_all_companies.py (90%) rename examples/{dfp => ad_manager}/v201805/company_service/update_companies.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/contact_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/contact_service/create_contacts.py (92%) rename examples/{dfp => ad_manager}/v201805/contact_service/get_all_contacts.py (90%) rename examples/{dfp => ad_manager}/v201805/contact_service/get_uninvited_contacts.py (90%) rename examples/{dfp => ad_manager}/v201805/contact_service/update_contacts.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (91%) rename examples/{dfp => ad_manager}/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (91%) rename examples/{dfp => ad_manager}/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (91%) rename examples/{dfp/v201802 => ad_manager/v201805}/content_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/content_service/get_all_content.py (90%) rename examples/{dfp/v201802 => ad_manager/v201805}/creative_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/creative_service/copy_image_creatives.py (88%) rename examples/{dfp => ad_manager}/v201805/creative_service/create_creative_from_template.py (92%) rename examples/{dfp => ad_manager}/v201805/creative_service/create_creatives.py (90%) rename examples/{dfp => ad_manager}/v201805/creative_service/create_custom_creative.py (89%) rename examples/{dfp => ad_manager}/v201805/creative_service/create_native_creative.py (97%) rename examples/{dfp => ad_manager}/v201805/creative_service/get_all_creatives.py (90%) rename examples/{dfp => ad_manager}/v201805/creative_service/get_image_creatives.py (90%) rename examples/{dfp => ad_manager}/v201805/creative_service/update_creatives.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/creative_set_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/creative_set_service/associate_creative_set_to_line_item.py (92%) rename examples/{dfp => ad_manager}/v201805/creative_set_service/create_creative_set.py (92%) rename examples/{dfp => ad_manager}/v201805/creative_set_service/get_all_creative_sets.py (90%) rename examples/{dfp => ad_manager}/v201805/creative_set_service/get_creative_sets_for_master_creative.py (90%) rename examples/{dfp => ad_manager}/v201805/creative_set_service/update_creative_set.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/creative_template_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/creative_template_service/get_all_creative_templates.py (90%) rename examples/{dfp => ad_manager}/v201805/creative_template_service/get_system_defined_creative_templates.py (91%) rename examples/{dfp => ad_manager}/v201805/creative_wrapper_service/create_creative_wrappers.py (94%) rename examples/{dfp => ad_manager}/v201805/creative_wrapper_service/deactivate_creative_wrapper.py (93%) rename examples/{dfp => ad_manager}/v201805/creative_wrapper_service/get_active_creative_wrappers.py (91%) rename examples/{dfp => ad_manager}/v201805/creative_wrapper_service/get_all_creative_wrappers.py (90%) rename examples/{dfp => ad_manager}/v201805/creative_wrapper_service/update_creative_wrappers.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/custom_field_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/custom_field_service/create_custom_field_options.py (93%) rename examples/{dfp => ad_manager}/v201805/custom_field_service/create_custom_fields.py (93%) rename examples/{dfp => ad_manager}/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py (93%) rename examples/{dfp => ad_manager}/v201805/custom_field_service/get_all_custom_fields.py (90%) rename examples/{dfp => ad_manager}/v201805/custom_field_service/get_custom_fields_for_line_items.py (91%) rename examples/{dfp => ad_manager}/v201805/custom_field_service/set_line_item_custom_field_value.py (91%) rename examples/{dfp => ad_manager}/v201805/custom_field_service/update_custom_fields.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/custom_targeting_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py (96%) rename examples/{dfp => ad_manager}/v201805/custom_targeting_service/delete_custom_targeting_keys.py (91%) rename examples/{dfp => ad_manager}/v201805/custom_targeting_service/delete_custom_targeting_values.py (91%) rename examples/{dfp => ad_manager}/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (91%) rename examples/{dfp => ad_manager}/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (92%) rename examples/{dfp => ad_manager}/v201805/custom_targeting_service/update_custom_targeting_keys.py (91%) rename examples/{dfp => ad_manager}/v201805/custom_targeting_service/update_custom_targeting_values.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/exchange_rate_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/exchange_rate_service/create_exchange_rates.py (93%) rename examples/{dfp => ad_manager}/v201805/exchange_rate_service/get_all_exchange_rates.py (91%) rename examples/{dfp => ad_manager}/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py (91%) rename examples/{dfp => ad_manager}/v201805/exchange_rate_service/update_exchange_rates.py (92%) rename examples/{dfp => ad_manager}/v201805/forecast_service/get_availability_forecast.py (96%) rename examples/{dfp => ad_manager}/v201805/forecast_service/get_availability_forecast_for_line_item.py (93%) rename examples/{dfp => ad_manager}/v201805/forecast_service/get_delivery_forecast_for_line_items.py (91%) rename examples/{dfp/v201802 => ad_manager/v201805}/inventory_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/inventory_service/archive_ad_units.py (92%) rename examples/{dfp => ad_manager}/v201805/inventory_service/create_ad_units.py (92%) rename examples/{dfp => ad_manager}/v201805/inventory_service/get_ad_unit_hierarchy.py (94%) rename examples/{dfp => ad_manager}/v201805/inventory_service/get_all_ad_unit_sizes.py (89%) rename examples/{dfp => ad_manager}/v201805/inventory_service/get_all_ad_units.py (90%) rename examples/{dfp => ad_manager}/v201805/inventory_service/get_top_level_ad_units.py (92%) rename examples/{dfp => ad_manager}/v201805/inventory_service/update_ad_units.py (93%) rename examples/{dfp/v201802 => ad_manager/v201805}/label_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/label_service/create_labels.py (89%) rename examples/{dfp => ad_manager}/v201805/label_service/deactivate_labels.py (89%) rename examples/{dfp => ad_manager}/v201805/label_service/get_active_labels.py (90%) rename examples/{dfp => ad_manager}/v201805/label_service/get_all_labels.py (90%) rename examples/{dfp => ad_manager}/v201805/label_service/update_labels.py (89%) rename examples/{dfp/v201802 => ad_manager/v201805}/line_item_creative_association_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/line_item_creative_association_service/create_licas.py (91%) rename examples/{dfp => ad_manager}/v201805/line_item_creative_association_service/deactivate_licas.py (92%) rename examples/{dfp => ad_manager}/v201805/line_item_creative_association_service/get_all_licas.py (92%) rename examples/{dfp => ad_manager}/v201805/line_item_creative_association_service/get_licas_for_line_item.py (92%) rename examples/{dfp => ad_manager}/v201805/line_item_creative_association_service/update_licas.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/line_item_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/line_item_service/activate_line_items.py (93%) rename examples/{dfp => ad_manager}/v201805/line_item_service/create_line_items.py (96%) rename examples/{dfp => ad_manager}/v201805/line_item_service/create_video_line_item.py (94%) rename examples/{dfp => ad_manager}/v201805/line_item_service/get_all_line_items.py (90%) rename examples/{dfp => ad_manager}/v201805/line_item_service/get_line_items_that_need_creatives.py (91%) rename examples/{dfp => ad_manager}/v201805/line_item_service/get_recently_updated_line_items.py (91%) rename examples/{dfp => ad_manager}/v201805/line_item_service/pause_line_items.py (93%) rename examples/{dfp => ad_manager}/v201805/line_item_service/target_custom_criteria.py (93%) rename examples/{dfp => ad_manager}/v201805/line_item_service/update_line_items.py (93%) rename examples/{dfp => ad_manager}/v201805/live_stream_event_service/activate_live_stream_events.py (90%) rename examples/{dfp => ad_manager}/v201805/live_stream_event_service/create_live_stream_events.py (93%) rename examples/{dfp => ad_manager}/v201805/live_stream_event_service/get_all_live_stream_events.py (90%) rename examples/{dfp => ad_manager}/v201805/live_stream_event_service/register_sessions_for_monitoring.py (91%) rename examples/{dfp => ad_manager}/v201805/live_stream_event_service/update_live_stream_events.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/native_style_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/native_style_service/create_native_styles.py (95%) rename examples/{dfp => ad_manager}/v201805/native_style_service/get_all_native_styles.py (90%) rename examples/{dfp/v201802 => ad_manager/v201805}/network_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/network_service/get_all_networks.py (90%) rename examples/{dfp => ad_manager}/v201805/network_service/get_current_network.py (89%) rename examples/{dfp => ad_manager}/v201805/network_service/make_test_network.py (68%) rename examples/{dfp/v201802 => ad_manager/v201805}/order_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/order_service/approve_orders.py (92%) rename examples/{dfp => ad_manager}/v201805/order_service/create_orders.py (90%) rename examples/{dfp => ad_manager}/v201805/order_service/get_all_orders.py (90%) rename examples/{dfp => ad_manager}/v201805/order_service/get_orders_starting_soon.py (92%) rename examples/{dfp => ad_manager}/v201805/order_service/update_orders.py (92%) rename examples/{dfp => ad_manager}/v201805/package_service/create_packages.py (93%) rename examples/{dfp => ad_manager}/v201805/package_service/create_proposal_line_items_from_packages.py (92%) rename examples/{dfp => ad_manager}/v201805/package_service/get_all_packages.py (90%) rename examples/{dfp => ad_manager}/v201805/package_service/get_in_progress_packages.py (90%) rename examples/{dfp => ad_manager}/v201805/placement_service/create_placements.py (95%) rename examples/{dfp => ad_manager}/v201805/placement_service/deactivate_placements.py (91%) rename examples/{dfp => ad_manager}/v201805/placement_service/get_active_placements.py (90%) rename examples/{dfp => ad_manager}/v201805/placement_service/get_all_placements.py (90%) rename examples/{dfp => ad_manager}/v201805/placement_service/update_placements.py (90%) rename examples/{dfp/v201802 => ad_manager/v201805}/premium_rate_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/premium_rate_service/create_premium_rates.py (92%) rename examples/{dfp => ad_manager}/v201805/premium_rate_service/get_all_premium_rates.py (81%) rename examples/{dfp => ad_manager}/v201805/premium_rate_service/get_premium_rates_for_rate_card.py (91%) rename examples/{dfp => ad_manager}/v201805/premium_rate_service/update_premium_rates.py (93%) rename examples/{dfp => ad_manager}/v201805/product_package_item_service/create_product_package_item.py (94%) rename examples/{dfp => ad_manager}/v201805/product_package_item_service/get_all_product_package_items.py (91%) rename examples/{dfp => ad_manager}/v201805/product_package_item_service/get_product_package_items_for_product_package.py (91%) rename examples/{dfp => ad_manager}/v201805/product_package_service/create_product_packages.py (92%) rename examples/{dfp => ad_manager}/v201805/product_package_service/get_active_product_packages.py (91%) rename examples/{dfp => ad_manager}/v201805/product_package_service/get_all_product_packages.py (90%) rename examples/{dfp/v201802 => ad_manager/v201805}/product_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/product_service/get_all_products.py (90%) rename examples/{dfp => ad_manager}/v201805/product_service/get_products_for_product_template.py (90%) rename examples/{dfp => ad_manager}/v201805/product_service/update_products.py (91%) rename examples/{dfp/v201802 => ad_manager/v201805}/product_template_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/product_template_service/activate_product_templates.py (92%) rename examples/{dfp => ad_manager}/v201805/product_template_service/create_product_templates.py (96%) rename examples/{dfp => ad_manager}/v201805/product_template_service/create_programmatic_product_templates.py (95%) rename examples/{dfp => ad_manager}/v201805/product_template_service/get_all_product_templates.py (90%) rename examples/{dfp => ad_manager}/v201805/product_template_service/get_sponsorship_product_templates.py (91%) rename examples/{dfp => ad_manager}/v201805/product_template_service/update_product_templates.py (93%) rename examples/{dfp/v201802 => ad_manager/v201805}/proposal_line_item_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/proposal_line_item_service/archive_proposal_line_items.py (92%) rename examples/{dfp => ad_manager}/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py (95%) rename examples/{dfp => ad_manager}/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (95%) rename examples/{dfp => ad_manager}/v201805/proposal_line_item_service/create_proposal_line_items.py (95%) rename examples/{dfp => ad_manager}/v201805/proposal_line_item_service/get_all_proposal_line_items.py (90%) rename examples/{dfp => ad_manager}/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py (91%) rename examples/{dfp => ad_manager}/v201805/proposal_line_item_service/update_proposal_line_items.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/proposal_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/proposal_service/create_programmatic_proposals.py (91%) rename examples/{dfp => ad_manager}/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py (92%) rename examples/{dfp => ad_manager}/v201805/proposal_service/create_proposals.py (93%) rename examples/{dfp => ad_manager}/v201805/proposal_service/get_all_proposals.py (90%) rename examples/{dfp => ad_manager}/v201805/proposal_service/get_marketplace_comments.py (93%) rename examples/{dfp => ad_manager}/v201805/proposal_service/get_proposals_pending_approval.py (90%) rename examples/{dfp => ad_manager}/v201805/proposal_service/request_buyers_acceptance.py (92%) rename examples/{dfp => ad_manager}/v201805/proposal_service/submit_proposals_for_approval.py (92%) rename examples/{dfp => ad_manager}/v201805/proposal_service/update_proposals.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/publisher_query_language_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/publisher_query_language_service/fetch_match_tables.py (93%) rename examples/{dfp => ad_manager}/v201805/publisher_query_language_service/get_all_browsers.py (93%) rename examples/{dfp => ad_manager}/v201805/publisher_query_language_service/get_all_programmatic_buyers.py (92%) rename examples/{dfp => ad_manager}/v201805/publisher_query_language_service/get_geo_targets.py (92%) rename examples/{dfp => ad_manager}/v201805/publisher_query_language_service/get_line_items_named_like.py (92%) rename examples/{dfp => ad_manager}/v201805/publisher_query_language_service/get_recent_changes.py (95%) rename examples/{dfp/v201802 => ad_manager/v201805}/rate_card_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/rate_card_service/create_rate_cards.py (93%) rename examples/{dfp => ad_manager}/v201805/rate_card_service/get_all_rate_cards.py (90%) rename examples/{dfp => ad_manager}/v201805/rate_card_service/get_marketplace_rate_cards.py (91%) rename examples/{dfp => ad_manager}/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (94%) rename examples/{dfp => ad_manager}/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (91%) rename examples/{dfp => ad_manager}/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (91%) rename examples/{dfp => ad_manager}/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py (93%) rename examples/{dfp => ad_manager}/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (89%) rename examples/{dfp => ad_manager}/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py (94%) rename examples/{dfp => ad_manager}/v201805/reconciliation_report_service/get_all_reconciliation_reports.py (91%) rename examples/{dfp => ad_manager}/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/report_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/report_service/run_ad_exchange_report.py (89%) rename examples/{dfp => ad_manager}/v201805/report_service/run_delivery_report.py (90%) rename examples/{dfp => ad_manager}/v201805/report_service/run_inventory_report.py (92%) rename examples/{dfp => ad_manager}/v201805/report_service/run_reach_report.py (91%) rename examples/{dfp => ad_manager}/v201805/report_service/run_report_and_create_match_table.py (94%) rename examples/{dfp => ad_manager}/v201805/report_service/run_report_with_custom_fields.py (93%) rename examples/{dfp => ad_manager}/v201805/report_service/run_sales_report.py (91%) rename examples/{dfp => ad_manager}/v201805/report_service/run_saved_query.py (91%) rename examples/{dfp/v201802 => ad_manager/v201805}/suggested_ad_unit_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py (90%) rename examples/{dfp => ad_manager}/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py (91%) rename examples/{dfp => ad_manager}/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (91%) rename examples/{dfp/v201802 => ad_manager/v201805}/team_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/team_service/create_teams.py (92%) rename examples/{dfp => ad_manager}/v201805/team_service/get_all_teams.py (90%) rename examples/{dfp => ad_manager}/v201805/team_service/update_teams.py (92%) rename examples/{dfp/v201802 => ad_manager/v201805}/user_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/user_service/create_users.py (90%) rename examples/{dfp => ad_manager}/v201805/user_service/deactivate_users.py (91%) rename examples/{dfp/v201802 => ad_manager/v201805}/user_service/get_all_roles.py (90%) rename examples/{dfp => ad_manager}/v201805/user_service/get_all_users.py (90%) rename examples/{dfp => ad_manager}/v201805/user_service/get_current_user.py (90%) rename examples/{dfp => ad_manager}/v201805/user_service/get_user_by_email_address.py (90%) rename examples/{dfp => ad_manager}/v201805/user_service/update_users.py (90%) rename examples/{dfp/v201802 => ad_manager/v201805}/user_team_association_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/user_team_association_service/create_user_team_associations.py (93%) rename examples/{dfp => ad_manager}/v201805/user_team_association_service/delete_user_team_associations.py (93%) rename examples/{dfp => ad_manager}/v201805/user_team_association_service/get_all_user_team_associations.py (91%) rename examples/{dfp => ad_manager}/v201805/user_team_association_service/get_user_team_associations_for_user.py (91%) rename examples/{dfp => ad_manager}/v201805/user_team_association_service/update_user_team_associations.py (93%) rename examples/{dfp/v201802 => ad_manager/v201805}/workflow_request_service/__init__.py (100%) rename examples/{dfp => ad_manager}/v201805/workflow_request_service/approve_workflow_approval_requests.py (93%) rename examples/{dfp => ad_manager}/v201805/workflow_request_service/get_workflow_approval_requests.py (92%) rename examples/{dfp => ad_manager}/v201805/workflow_request_service/get_workflow_external_condition_requests.py (92%) rename examples/{dfp => ad_manager}/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py (94%) rename examples/{dfp/v201805 => ad_manager/v201808}/activity_group_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/activity_group_service/create_activity_groups.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/activity_group_service/get_active_activity_groups.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/activity_group_service/get_all_activity_groups.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/activity_group_service/update_activity_groups.py (89%) rename examples/{dfp/v201805 => ad_manager/v201808}/activity_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/activity_service/create_activities.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/activity_service/get_active_activities.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/activity_service/get_all_activities.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/activity_service/update_activities.py (91%) rename examples/{dfp/v201805 => ad_manager/v201808}/audience_segment_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/audience_segment_service/create_audience_segments.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/audience_segment_service/get_all_audience_segments.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/audience_segment_service/get_first_party_audience_segments.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/audience_segment_service/populate_first_party_audience_segments.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/audience_segment_service/update_audience_segments.py (90%) rename examples/{dfp/v201805 => ad_manager/v201808}/base_rate_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/base_rate_service/create_product_base_rates.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/base_rate_service/create_product_package_item_base_rates.py (94%) rename examples/{dfp/v201711 => ad_manager/v201808}/base_rate_service/create_product_template_base_rates.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/base_rate_service/get_all_base_rates.py (84%) rename examples/{dfp/v201711 => ad_manager/v201808}/base_rate_service/get_base_rates_for_rate_card.py (84%) rename examples/{dfp/v201711 => ad_manager/v201808}/base_rate_service/update_base_rates.py (89%) rename examples/{dfp/v201805 => ad_manager/v201808}/cdn_configuration_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/cdn_configuration_service/create_cdn_configurations.py (93%) rename examples/{dfp/v201711 => ad_manager/v201808}/cdn_configuration_service/get_all_cdn_configurations.py (88%) rename examples/{dfp/v201805 => ad_manager/v201808}/company_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/company_service/create_companies.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/company_service/get_advertisers.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/company_service/get_all_companies.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/company_service/update_companies.py (91%) rename examples/{dfp/v201805 => ad_manager/v201808}/contact_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/contact_service/create_contacts.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/contact_service/get_all_contacts.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/contact_service/get_uninvited_contacts.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/contact_service/update_contacts.py (91%) rename examples/{dfp/v201805 => ad_manager/v201808}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (90%) rename examples/{dfp/v201805 => ad_manager/v201808}/content_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/content_service/get_all_content.py (89%) rename examples/{dfp/v201805 => ad_manager/v201808}/creative_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_service/copy_image_creatives.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_service/create_creative_from_template.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_service/create_creatives.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_service/create_custom_creative.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_service/create_native_creative.py (96%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_service/get_all_creatives.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_service/get_image_creatives.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_service/update_creatives.py (89%) rename examples/{dfp/v201805 => ad_manager/v201808}/creative_set_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_set_service/associate_creative_set_to_line_item.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_set_service/create_creative_set.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_set_service/get_all_creative_sets.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_set_service/get_creative_sets_for_master_creative.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_set_service/update_creative_set.py (90%) rename examples/{dfp/v201805 => ad_manager/v201808}/creative_template_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_template_service/get_all_creative_templates.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_template_service/get_system_defined_creative_templates.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_wrapper_service/create_creative_wrappers.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_wrapper_service/deactivate_creative_wrapper.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_wrapper_service/get_active_creative_wrappers.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_wrapper_service/get_all_creative_wrappers.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/creative_wrapper_service/update_creative_wrappers.py (90%) rename examples/{dfp/v201805 => ad_manager/v201808}/custom_field_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_field_service/create_custom_field_options.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_field_service/create_custom_fields.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_field_service/deactivate_all_line_item_custom_fields.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_field_service/get_all_custom_fields.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_field_service/get_custom_fields_for_line_items.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_field_service/set_line_item_custom_field_value.py (77%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_field_service/update_custom_fields.py (90%) rename examples/{dfp/v201805 => ad_manager/v201808}/custom_targeting_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_targeting_service/create_custom_targeting_keys_and_values.py (95%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_targeting_service/delete_custom_targeting_keys.py (85%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_targeting_service/delete_custom_targeting_values.py (77%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (83%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_targeting_service/update_custom_targeting_keys.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/custom_targeting_service/update_custom_targeting_values.py (88%) rename examples/{dfp/v201805 => ad_manager/v201808}/exchange_rate_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/exchange_rate_service/create_exchange_rates.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/exchange_rate_service/get_all_exchange_rates.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/exchange_rate_service/get_exchange_rates_for_currency_code.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/exchange_rate_service/update_exchange_rates.py (89%) create mode 100755 examples/ad_manager/v201808/forecast_service/get_availability_forecast.py rename examples/{dfp/v201711 => ad_manager/v201808}/forecast_service/get_availability_forecast_for_line_item.py (93%) rename examples/{dfp/v201711 => ad_manager/v201808}/forecast_service/get_delivery_forecast_for_line_items.py (91%) rename examples/{dfp/v201805 => ad_manager/v201808}/inventory_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/inventory_service/archive_ad_units.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/inventory_service/create_ad_units.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/inventory_service/get_ad_unit_hierarchy.py (93%) rename examples/{dfp/v201711 => ad_manager/v201808}/inventory_service/get_all_ad_unit_sizes.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/inventory_service/get_all_ad_units.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/inventory_service/get_top_level_ad_units.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/inventory_service/update_ad_units.py (92%) rename examples/{dfp/v201805 => ad_manager/v201808}/label_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/label_service/create_labels.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/label_service/deactivate_labels.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/label_service/get_active_labels.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/label_service/get_all_labels.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/label_service/update_labels.py (88%) rename examples/{dfp/v201805 => ad_manager/v201808}/line_item_creative_association_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_creative_association_service/create_licas.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_creative_association_service/deactivate_licas.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_creative_association_service/get_all_licas.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_creative_association_service/get_licas_for_line_item.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_creative_association_service/update_licas.py (89%) rename examples/{dfp/v201805 => ad_manager/v201808}/line_item_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/activate_line_items.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/create_line_items.py (96%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/create_video_line_item.py (94%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/get_all_line_items.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/get_line_items_that_need_creatives.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/get_recently_updated_line_items.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/pause_line_items.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/target_custom_criteria.py (93%) rename examples/{dfp/v201711 => ad_manager/v201808}/line_item_service/update_line_items.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/live_stream_event_service/activate_live_stream_events.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/live_stream_event_service/create_live_stream_events.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/live_stream_event_service/get_all_live_stream_events.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/live_stream_event_service/register_sessions_for_monitoring.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/live_stream_event_service/update_live_stream_events.py (90%) rename examples/{dfp/v201805 => ad_manager/v201808}/native_style_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/native_style_service/create_native_styles.py (94%) rename examples/{dfp/v201711 => ad_manager/v201808}/native_style_service/get_all_native_styles.py (87%) rename examples/{dfp/v201805 => ad_manager/v201808}/network_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/network_service/get_all_networks.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/network_service/get_current_network.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/network_service/make_test_network.py (68%) rename examples/{dfp/v201805 => ad_manager/v201808}/order_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/order_service/approve_orders.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/order_service/create_orders.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/order_service/get_all_orders.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/order_service/get_orders_starting_soon.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/order_service/update_orders.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/package_service/create_packages.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/package_service/create_proposal_line_items_from_packages.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/package_service/get_all_packages.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/package_service/get_in_progress_packages.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/placement_service/create_placements.py (94%) rename examples/{dfp/v201711 => ad_manager/v201808}/placement_service/deactivate_placements.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/placement_service/get_active_placements.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/placement_service/get_all_placements.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/placement_service/update_placements.py (89%) rename examples/{dfp/v201805 => ad_manager/v201808}/premium_rate_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/premium_rate_service/create_premium_rates.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/premium_rate_service/get_all_premium_rates.py (79%) rename examples/{dfp/v201711 => ad_manager/v201808}/premium_rate_service/get_premium_rates_for_rate_card.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/premium_rate_service/update_premium_rates.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_package_item_service/create_product_package_item.py (94%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_package_item_service/get_all_product_package_items.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_package_item_service/get_product_package_items_for_product_package.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_package_service/create_product_packages.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_package_service/get_active_product_packages.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_package_service/get_all_product_packages.py (88%) rename examples/{dfp/v201805 => ad_manager/v201808}/product_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_service/get_all_products.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_service/get_products_for_product_template.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_service/update_products.py (91%) rename examples/{dfp/v201805 => ad_manager/v201808}/product_template_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_template_service/activate_product_templates.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_template_service/create_product_templates.py (93%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_template_service/create_programmatic_product_templates.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_template_service/get_all_product_templates.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_template_service/get_sponsorship_product_templates.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/product_template_service/update_product_templates.py (92%) rename examples/{dfp/v201805 => ad_manager/v201808}/proposal_line_item_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_line_item_service/archive_proposal_line_items.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_line_item_service/create_programmatic_proposal_line_items.py (93%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (93%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_line_item_service/create_proposal_line_items.py (93%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_line_item_service/get_all_proposal_line_items.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_line_item_service/update_proposal_line_items.py (90%) rename examples/{dfp/v201805 => ad_manager/v201808}/proposal_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/create_programmatic_proposals.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/create_proposals.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/get_all_proposals.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/get_marketplace_comments.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/get_proposals_pending_approval.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/request_buyers_acceptance.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/submit_proposals_for_approval.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/proposal_service/update_proposals.py (91%) rename examples/{dfp/v201805 => ad_manager/v201808}/publisher_query_language_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/publisher_query_language_service/fetch_match_tables.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/publisher_query_language_service/get_all_browsers.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/publisher_query_language_service/get_all_programmatic_buyers.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/publisher_query_language_service/get_geo_targets.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/publisher_query_language_service/get_line_items_named_like.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/publisher_query_language_service/get_recent_changes.py (95%) rename examples/{dfp/v201805 => ad_manager/v201808}/rate_card_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/rate_card_service/create_rate_cards.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/rate_card_service/get_all_rate_cards.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/rate_card_service/get_marketplace_rate_cards.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/reconciliation_order_report_service/submit_reconciliation_order_reports.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (85%) rename examples/{dfp/v201711 => ad_manager/v201808}/reconciliation_report_row_service/update_reconciliation_report_rows.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/reconciliation_report_service/get_all_reconciliation_reports.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (88%) rename examples/{dfp/v201805 => ad_manager/v201808}/report_service/__init__.py (100%) create mode 100755 examples/ad_manager/v201808/report_service/run_ad_exchange_report.py rename examples/{dfp/v201711 => ad_manager/v201808}/report_service/run_delivery_report.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/report_service/run_inventory_report.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/report_service/run_reach_report.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/report_service/run_report_and_create_match_table.py (92%) rename examples/{dfp/v201711 => ad_manager/v201808}/report_service/run_report_with_custom_fields.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/report_service/run_sales_report.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/report_service/run_saved_query.py (88%) rename examples/{dfp/v201805 => ad_manager/v201808}/suggested_ad_unit_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (82%) rename examples/{dfp/v201711 => ad_manager/v201808}/suggested_ad_unit_service/get_all_suggested_ad_units.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (86%) rename examples/{dfp/v201805 => ad_manager/v201808}/team_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/team_service/create_teams.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/team_service/get_all_teams.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/team_service/update_teams.py (88%) rename examples/{dfp/v201805 => ad_manager/v201808}/user_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_service/create_users.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_service/deactivate_users.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_service/get_all_roles.py (90%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_service/get_all_users.py (86%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_service/get_current_user.py (84%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_service/get_user_by_email_address.py (84%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_service/update_users.py (86%) rename examples/{dfp/v201805 => ad_manager/v201808}/user_team_association_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_team_association_service/create_user_team_associations.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_team_association_service/delete_user_team_associations.py (91%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_team_association_service/get_all_user_team_associations.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_team_association_service/get_user_team_associations_for_user.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/user_team_association_service/update_user_team_associations.py (92%) rename examples/{dfp/v201805 => ad_manager/v201808}/workflow_request_service/__init__.py (100%) rename examples/{dfp/v201711 => ad_manager/v201808}/workflow_request_service/approve_workflow_approval_requests.py (89%) rename examples/{dfp/v201711 => ad_manager/v201808}/workflow_request_service/get_workflow_approval_requests.py (87%) rename examples/{dfp/v201711 => ad_manager/v201808}/workflow_request_service/get_workflow_external_condition_requests.py (88%) rename examples/{dfp/v201711 => ad_manager/v201808}/workflow_request_service/trigger_workflow_external_condition_requests.py (90%) delete mode 100755 examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py delete mode 100755 examples/dfp/v201711/forecast_service/get_availability_forecast.py rename googleads/{dfp.py => ad_manager.py} (85%) rename tests/{dfp_test.py => ad_manager_test.py} (81%) rename tests/test_data/{dfp_report_service.xml => ad_manager_report_service.xml} (100%) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cb8bc514..a6b0bd37 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,8 +13,7 @@ Follow either of the two links above to access the appropriate CLA and instructi - Sign a Contributor License Agreement (see above). - Join the appropriate product discussion forum. - AdWords API: https://developers.google.com/adwords/api/community/ - - DFP API: https://developers.google.com/doubleclick-publishers/community - - DFA API: https://developers.google.com/doubleclick-advertisers/reporting/community + - Ad Manager API: https://developers.google.com/ad-manager/community - Create an issue on the library issue tracker if there isn't one already. Use this issue to co-ordinate the changes with the library maintainer. - Fork the library, make the changes and send a [pull request](https://help.github.com/articles/using-pull-requests). - The library maintainer will work with you to review and apply the patch. diff --git a/ChangeLog b/ChangeLog index b288b724..44ee7e79 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +14.0.0 -- 08/21/18 +- DFP rebranded to Google Ad Manager. +- Google Ad Manager v201808 release. +- Removed support for DFP v201708. +- Removed examples for DFP v201711. + 13.0.0 -- 07/25/18 - Removed support for AdWords v201710. diff --git a/README.md b/README.md index 254ee506..070d8e61 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,8 @@ # The googleads Python client library +**Note:** DoubleClick for Publishers was recently renamed to Google Ad Manager, and this library +was modified to follow suit. Please see the [migration guide](https://github.com/googleads/googleads-python-lib/wiki/dfp-rebrand) +for more details. This client library simplifies accessing Google's SOAP Ads APIs - AdWords, and DoubleClick for Publishers. The library provides easy ways to store your @@ -40,19 +43,19 @@ code to help you get started integrating with our APIs. **If you're accessing an API using your own credentials...** * [Using AdWords](https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-(installed-application-flow)) - * [Using DFP](https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-(server-to-server-flow)) + * [Using Ad Manager](https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-(server-to-server-flow)) **If you're accessing an API on behalf of clients...** - * [Developing a web application (AdWords or DFP)](https://github.com/googleads/googleads-python-lib/wiki/API-access-on-behalf-of-your-clients-(web-flow)) + * [Developing a web application (AdWords or Ad Manager)](https://github.com/googleads/googleads-python-lib/wiki/API-access-on-behalf-of-your-clients-(web-flow)) #### Where can I find samples? -You can find code examples for the latest versions of AdWords or DFP on the +You can find code examples for the latest versions of AdWords or Ad Manager on the [releases](https://github.com/googleads/googleads-python-lib/releases) page. Alternatively, you can find [AdWords](https://github.com/googleads/googleads-python-lib/tree/master/examples/adwords) -or [DFP](https://github.com/googleads/googleads-python-lib/tree/master/examples/dfp) +or [Ad Manager](https://github.com/googleads/googleads-python-lib/tree/master/examples/ad_manager) samples in the examples directory of this repository. #### Where can I find the pydocs? @@ -73,7 +76,7 @@ contents. adwords_client = adwords.AdWordsClient.LoadFromStorage() # Alternatively, pass in the location of the file: -dfp_client = dfp.DfpClient.LoadFromStorage('C:\My\Directory\googleads.yaml') +ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage('C:\My\Directory\googleads.yaml') ``` #### How do I change the Client Customer Id at runtime? @@ -200,7 +203,7 @@ access a local file system that may not be available in certain hosting environments such as App Engine. You can pass an implementation of `suds.cache.Cache` or `zeep.cache.Base` to the `AdWordsClient` or -`DfpClient` initializer to modify the default caching behavior. +`AdManagerClient` initializer to modify the default caching behavior. For example, configuring a different location and duration of the cache file with zeep ```python diff --git a/examples/dfp/authentication/create_dfp_client_with_access_token.py b/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py similarity index 85% rename from examples/dfp/authentication/create_dfp_client_with_access_token.py rename to examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py index e24690c9..6d364692 100755 --- a/examples/dfp/authentication/create_dfp_client_with_access_token.py +++ b/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Initializes an DfpClient using GoogleAccessTokenClient. +"""Initializes an AdManagerClient using GoogleAccessTokenClient. Note that unlike clients initialized with GoogleRefreshTokenClient, those initialized with GoogleAccessTokenClient can't refresh. @@ -22,7 +22,7 @@ import argparse import datetime -from googleads import dfp +from googleads import ad_manager from googleads import oauth2 import httplib2 from oauth2client import client @@ -36,11 +36,11 @@ DEFAULT_CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' DEFAULT_REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE' -# DFP API information. +# Ad Manager API information. DEFAULT_APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE' parser = argparse.ArgumentParser( - description=('Creates an DfpClient using a GoogleAccessToken with an ' + description=('Creates an AdManagerClient using a GoogleAccessToken with an ' 'access token generated with the given credentials.')) parser.add_argument('--client_id', default=DEFAULT_CLIENT_ID, help='Client Id retrieved from the Developer\'s Console.') @@ -50,15 +50,16 @@ parser.add_argument('--refresh_token', default=DEFAULT_REFRESH_TOKEN, help='The refresh token used to generate an access token.') parser.add_argument('--application_name', default=DEFAULT_APPLICATION_NAME, - help='The application name for your DFP account.') + help='The application name for your Ad Manager account.') def main(access_token, token_expiry, application_name): oauth2_client = oauth2.GoogleAccessTokenClient(access_token, token_expiry) - dfp_client = dfp.DfpClient(oauth2_client, application_name) + ad_manager_client = ad_manager.AdManagerClient( + oauth2_client, application_name) - networks = dfp_client.GetService('NetworkService').getAllNetworks() + networks = ad_manager_client.GetService('NetworkService').getAllNetworks() for network in networks: print ('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) diff --git a/examples/dfp/authentication/create_dfp_client_with_refresh_token.py b/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py similarity index 81% rename from examples/dfp/authentication/create_dfp_client_with_refresh_token.py rename to examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py index 3024040b..52b456bb 100755 --- a/examples/dfp/authentication/create_dfp_client_with_refresh_token.py +++ b/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py @@ -14,16 +14,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Initializes a DfpClient without using yaml-cached credentials. +"""Initializes a AdManagerClient without using yaml-cached credentials. While our LoadFromStorage method provides a useful shortcut to instantiate a client if you regularly use just one set of credentials, production applications may need to swap out users. This example shows you how to create an OAuth2 -client and a DfpClient without relying on a yaml file. +client and a AdManagerClient without relying on a yaml file. """ -from googleads import dfp +from googleads import ad_manager from googleads import oauth2 # OAuth2 credential information. In a real application, you'd probably be @@ -32,7 +32,7 @@ CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE' REFRESH_TOKEN = 'INSERT_REFRESH_TOKEN_HERE' -# DFP API information. +# Ad Manager API information. APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE' @@ -40,9 +40,10 @@ def main(client_id, client_secret, refresh_token, application_name): oauth2_client = oauth2.GoogleRefreshTokenClient( client_id, client_secret, refresh_token) - dfp_client = dfp.DfpClient(oauth2_client, application_name) + ad_manager_client = ad_manager.AdManagerClient( + oauth2_client, application_name) - networks = dfp_client.GetService('NetworkService').getAllNetworks() + networks = ad_manager_client.GetService('NetworkService').getAllNetworks() for network in networks: print ('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) diff --git a/examples/dfp/authentication/create_dfp_client_with_service_account.py b/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py similarity index 77% rename from examples/dfp/authentication/create_dfp_client_with_service_account.py rename to examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py index f5081e32..a750b73e 100755 --- a/examples/dfp/authentication/create_dfp_client_with_service_account.py +++ b/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py @@ -14,27 +14,28 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Initializes a DfpClient using a Service Account.""" +"""Initializes a AdManagerClient using a Service Account.""" -from googleads import dfp +from googleads import ad_manager from googleads import oauth2 # OAuth2 credential information. In a real application, you'd probably be # pulling these values from a credential storage. KEY_FILE = 'INSERT_KEY_FILE_PATH' -# DFP API information. +# Ad Manager API information. APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE' def main(key_file, application_name): oauth2_client = oauth2.GoogleServiceAccountClient( - key_file, oauth2.GetAPIScope('dfp')) + key_file, oauth2.GetAPIScope('ad_manager')) - dfp_client = dfp.DfpClient(oauth2_client, application_name) + ad_manager_client = ad_manager.AdManagerClient( + oauth2_client, application_name) - networks = dfp_client.GetService('NetworkService').getAllNetworks() + networks = ad_manager_client.GetService('NetworkService').getAllNetworks() for network in networks: print ('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) diff --git a/examples/dfp/authentication/generate_refresh_token.py b/examples/ad_manager/authentication/generate_refresh_token.py similarity index 96% rename from examples/dfp/authentication/generate_refresh_token.py rename to examples/ad_manager/authentication/generate_refresh_token.py index 54e5f3c2..bfcc62e9 100755 --- a/examples/dfp/authentication/generate_refresh_token.py +++ b/examples/ad_manager/authentication/generate_refresh_token.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Generates a refresh token for use with DFP.""" +"""Generates a refresh token for use with Ad Manager.""" import argparse @@ -28,7 +28,7 @@ DEFAULT_CLIENT_ID = None DEFAULT_CLIENT_SECRET = None -# The DFP API OAuth2 scope. +# The Ad Manager API OAuth2 scope. SCOPE = u'https://www.googleapis.com/auth/dfp' # The redirect URI set for the given Client ID. The redirect URI for Client ID # generated for an installed application will always have this value. @@ -95,7 +95,7 @@ def main(client_id, client_secret, scopes): auth_url, _ = flow.authorization_url(prompt='consent') - print ('Log into the Google Account you use to access your DFP account' + print ('Log into the Google Account you use to access your Ad Manager account' 'and go to the following URL: \n%s\n' % (auth_url)) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() diff --git a/examples/dfp/v201711/activity_group_service/__init__.py b/examples/ad_manager/v201802/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201711/activity_group_service/__init__.py rename to examples/ad_manager/v201802/activity_group_service/__init__.py diff --git a/examples/dfp/v201802/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201802/activity_group_service/create_activity_groups.py similarity index 93% rename from examples/dfp/v201802/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v201802/activity_group_service/create_activity_groups.py index 0ab733fb..6932d052 100755 --- a/examples/dfp/v201802/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201802/activity_group_service/create_activity_groups.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the advertiser company this activity group is associated with. ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -67,5 +67,5 @@ def main(client, advertiser_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_COMPANY_ID) diff --git a/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201802/activity_group_service/get_active_activity_groups.py similarity index 91% rename from examples/dfp/v201802/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v201802/activity_group_service/get_active_activity_groups.py index 459660fd..9a75320e 100755 --- a/examples/dfp/v201802/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201802/activity_group_service/get_active_activity_groups.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): activity_group_service = client.GetService( 'ActivityGroupService', version='v201802') # Create a statement to select activity groups. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201802/activity_group_service/get_all_activity_groups.py similarity index 90% rename from examples/dfp/v201802/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v201802/activity_group_service/get_all_activity_groups.py index 57789670..14857362 100755 --- a/examples/dfp/v201802/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201802/activity_group_service/get_all_activity_groups.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ActivityGroupService', version='v201802') # Create a statement to select activity groups. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201802/activity_group_service/update_activity_groups.py similarity index 92% rename from examples/dfp/v201802/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v201802/activity_group_service/update_activity_groups.py index 25c615fb..4104eabf 100755 --- a/examples/dfp/v201802/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201802/activity_group_service/update_activity_groups.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity group and the company to update it with. ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' @@ -40,7 +40,7 @@ def main(client, activity_group_id, advertiser_company_id): version='v201802') # Create statement object to select a single activity groups by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', long(activity_group_id)) .Limit(1)) @@ -66,5 +66,5 @@ def main(client, activity_group_id, advertiser_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) diff --git a/examples/dfp/v201711/activity_service/__init__.py b/examples/ad_manager/v201802/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201711/activity_service/__init__.py rename to examples/ad_manager/v201802/activity_service/__init__.py diff --git a/examples/dfp/v201802/activity_service/create_activities.py b/examples/ad_manager/v201802/activity_service/create_activities.py similarity index 93% rename from examples/dfp/v201802/activity_service/create_activities.py rename to examples/ad_manager/v201802/activity_service/create_activities.py index 2277e7d3..3247775d 100755 --- a/examples/dfp/v201802/activity_service/create_activities.py +++ b/examples/ad_manager/v201802/activity_service/create_activities.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity group this activity is associated with. ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' @@ -64,5 +64,5 @@ def main(client, activity_group_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_GROUP_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_GROUP_ID) diff --git a/examples/dfp/v201802/activity_service/get_active_activities.py b/examples/ad_manager/v201802/activity_service/get_active_activities.py similarity index 90% rename from examples/dfp/v201802/activity_service/get_active_activities.py rename to examples/ad_manager/v201802/activity_service/get_active_activities.py index 906de34d..42f224b3 100755 --- a/examples/dfp/v201802/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201802/activity_service/get_active_activities.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. activity_service = client.GetService('ActivityService', version='v201802') # Create a statement to select activities. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/activity_service/get_all_activities.py b/examples/ad_manager/v201802/activity_service/get_all_activities.py similarity index 90% rename from examples/dfp/v201802/activity_service/get_all_activities.py rename to examples/ad_manager/v201802/activity_service/get_all_activities.py index d79b9590..9511a579 100755 --- a/examples/dfp/v201802/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201802/activity_service/get_all_activities.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): activity_service = client.GetService('ActivityService', version='v201802') # Create a statement to select activities. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/activity_service/update_activities.py b/examples/ad_manager/v201802/activity_service/update_activities.py similarity index 92% rename from examples/dfp/v201802/activity_service/update_activities.py rename to examples/ad_manager/v201802/activity_service/update_activities.py index fd3498b9..16446ff9 100755 --- a/examples/dfp/v201802/activity_service/update_activities.py +++ b/examples/ad_manager/v201802/activity_service/update_activities.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity to update. ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE' @@ -38,7 +38,7 @@ def main(client, activity_id): activity_service = client.GetService('ActivityService', version='v201802') # Create statement object to select one activity by ID to update. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :activityId') .WithBindVariable('activityId', long(activity_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, activity_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_ID) diff --git a/examples/dfp/v201711/audience_segment_service/__init__.py b/examples/ad_manager/v201802/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201711/audience_segment_service/__init__.py rename to examples/ad_manager/v201802/audience_segment_service/__init__.py diff --git a/examples/dfp/v201802/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201802/audience_segment_service/create_audience_segments.py similarity index 94% rename from examples/dfp/v201802/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v201802/audience_segment_service/create_audience_segments.py index 010d0124..4f883aad 100755 --- a/examples/dfp/v201802/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201802/audience_segment_service/create_audience_segments.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the IDs of the custom criteria to be used in the segment rule. CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -92,5 +92,5 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201802/audience_segment_service/get_all_audience_segments.py similarity index 91% rename from examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v201802/audience_segment_service/get_all_audience_segments.py index d3a4ed75..e664d6ab 100755 --- a/examples/dfp/v201802/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201802/audience_segment_service/get_all_audience_segments.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'AudienceSegmentService', version='v201802') # Create a statement to select audience segments. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201802/audience_segment_service/get_first_party_audience_segments.py similarity index 91% rename from examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v201802/audience_segment_service/get_first_party_audience_segments.py index f47421b2..f83d5370 100755 --- a/examples/dfp/v201802/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201802/audience_segment_service/get_first_party_audience_segments.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201802') # Create a statement to select audience segments. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) @@ -49,5 +49,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201802/audience_segment_service/populate_first_party_audience_segments.py similarity index 91% rename from examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v201802/audience_segment_service/populate_first_party_audience_segments.py index ac9216a7..2da62ba3 100755 --- a/examples/dfp/v201802/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201802/audience_segment_service/populate_first_party_audience_segments.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' @@ -33,7 +33,7 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201802') # Create statement object to get the specified first party audience segment. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) @@ -67,5 +67,5 @@ def main(client, audience_segment_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AUDIENCE_SEGMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/dfp/v201802/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201802/audience_segment_service/update_audience_segments.py similarity index 92% rename from examples/dfp/v201802/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v201802/audience_segment_service/update_audience_segments.py index 1cc1d0b6..b0a223e7 100755 --- a/examples/dfp/v201802/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201802/audience_segment_service/update_audience_segments.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' @@ -32,7 +32,7 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201802') # Create statement object to get the specified first party audience segment. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) @@ -64,5 +64,5 @@ def main(client, audience_segment_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AUDIENCE_SEGMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/dfp/v201711/base_rate_service/__init__.py b/examples/ad_manager/v201802/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201711/base_rate_service/__init__.py rename to examples/ad_manager/v201802/base_rate_service/__init__.py diff --git a/examples/dfp/v201802/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201802/base_rate_service/create_product_base_rates.py similarity index 92% rename from examples/dfp/v201802/base_rate_service/create_product_base_rates.py rename to examples/ad_manager/v201802/base_rate_service/create_product_base_rates.py index 54aa61a1..4be55317 100755 --- a/examples/dfp/v201802/base_rate_service/create_product_base_rates.py +++ b/examples/ad_manager/v201802/base_rate_service/create_product_base_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -61,5 +61,5 @@ def main(client, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201802/base_rate_service/create_product_package_item_base_rates.py similarity index 94% rename from examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py rename to examples/ad_manager/v201802/base_rate_service/create_product_package_item_base_rates.py index d7a50f50..3f1ad600 100755 --- a/examples/dfp/v201802/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/ad_manager/v201802/base_rate_service/create_product_package_item_base_rates.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the rate card ID to add the base rate to. RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201802/base_rate_service/create_product_template_base_rates.py similarity index 92% rename from examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py rename to examples/ad_manager/v201802/base_rate_service/create_product_template_base_rates.py index f259ca28..3e468c7b 100755 --- a/examples/dfp/v201802/base_rate_service/create_product_template_base_rates.py +++ b/examples/ad_manager/v201802/base_rate_service/create_product_template_base_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -61,5 +61,5 @@ def main(client, product_template_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201802/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201802/base_rate_service/get_all_base_rates.py similarity index 84% rename from examples/dfp/v201802/base_rate_service/get_all_base_rates.py rename to examples/ad_manager/v201802/base_rate_service/get_all_base_rates.py index 1c8fd6e8..4d52fb08 100755 --- a/examples/dfp/v201802/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201802/base_rate_service/get_all_base_rates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a statement to select base rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. @@ -36,7 +36,8 @@ def main(client): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), + 'found.\n' % (base_rate['id'], + ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) statement.offset += statement.limit else: @@ -47,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201802/base_rate_service/get_base_rates_for_rate_card.py similarity index 87% rename from examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py rename to examples/ad_manager/v201802/base_rate_service/get_base_rates_for_rate_card.py index ee12f4cb..3b30931e 100755 --- a/examples/dfp/v201802/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201802/base_rate_service/get_base_rates_for_rate_card.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -26,7 +26,7 @@ def main(client, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a statement to select base rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) @@ -40,7 +40,7 @@ def main(client, rate_card_id): # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' 'found.\n' % - (base_rate['id'], dfp.DfpClassType(base_rate), + (base_rate['id'], ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) statement.offset += statement.limit else: @@ -51,5 +51,5 @@ def main(client, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201802/base_rate_service/update_base_rates.py b/examples/ad_manager/v201802/base_rate_service/update_base_rates.py similarity index 90% rename from examples/dfp/v201802/base_rate_service/update_base_rates.py rename to examples/ad_manager/v201802/base_rate_service/update_base_rates.py index 3cb98dfc..76dbc7d5 100755 --- a/examples/dfp/v201802/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201802/base_rate_service/update_base_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' @@ -32,7 +32,7 @@ def main(client, base_rate_id): base_rate_service = client.GetService('BaseRateService', version='v201802') # Create a filter statement for base rates for a single rate card. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -63,7 +63,7 @@ def main(client, base_rate_id): print ('Base rate with ID "%s" and type "%s" belonging to ' 'rate card ID "%s" was updated.' % ( base_rate['id'], - dfp.DfpClassType(base_rate), + ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) else: print 'No base rates were updated.' @@ -73,5 +73,5 @@ def main(client, base_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, BASE_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, BASE_RATE_ID) diff --git a/examples/dfp/v201711/cdn_configuration_service/__init__.py b/examples/ad_manager/v201802/cdn_configuration_service/__init__.py similarity index 100% rename from examples/dfp/v201711/cdn_configuration_service/__init__.py rename to examples/ad_manager/v201802/cdn_configuration_service/__init__.py diff --git a/examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201802/cdn_configuration_service/create_cdn_configurations.py similarity index 95% rename from examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v201802/cdn_configuration_service/create_cdn_configurations.py index f0dfe4ce..2b8f33bd 100755 --- a/examples/dfp/v201802/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v201802/cdn_configuration_service/create_cdn_configurations.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -85,5 +85,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201802/cdn_configuration_service/get_all_cdn_configurations.py similarity index 91% rename from examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v201802/cdn_configuration_service/get_all_cdn_configurations.py index 91df2a56..98534c94 100755 --- a/examples/dfp/v201802/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201802/cdn_configuration_service/get_all_cdn_configurations.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -29,7 +29,7 @@ def main(client): version='v201802') # Create a statement to select cdn configurations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small number of configs at a time, paging # through until all have been retrieved. @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/company_service/__init__.py b/examples/ad_manager/v201802/company_service/__init__.py similarity index 100% rename from examples/dfp/v201711/company_service/__init__.py rename to examples/ad_manager/v201802/company_service/__init__.py diff --git a/examples/dfp/v201802/company_service/create_companies.py b/examples/ad_manager/v201802/company_service/create_companies.py similarity index 93% rename from examples/dfp/v201802/company_service/create_companies.py rename to examples/ad_manager/v201802/company_service/create_companies.py index 3106f133..66c36d80 100755 --- a/examples/dfp/v201802/company_service/create_companies.py +++ b/examples/ad_manager/v201802/company_service/create_companies.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -58,5 +58,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/company_service/get_advertisers.py b/examples/ad_manager/v201802/company_service/get_advertisers.py similarity index 90% rename from examples/dfp/v201802/company_service/get_advertisers.py rename to examples/ad_manager/v201802/company_service/get_advertisers.py index 17f8b0a0..423248a3 100755 --- a/examples/dfp/v201802/company_service/get_advertisers.py +++ b/examples/ad_manager/v201802/company_service/get_advertisers.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. company_service = client.GetService('CompanyService', version='v201802') # Create a statement to select companies. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/company_service/get_all_companies.py b/examples/ad_manager/v201802/company_service/get_all_companies.py similarity index 90% rename from examples/dfp/v201802/company_service/get_all_companies.py rename to examples/ad_manager/v201802/company_service/get_all_companies.py index b0d6e97f..46cfbcee 100755 --- a/examples/dfp/v201802/company_service/get_all_companies.py +++ b/examples/ad_manager/v201802/company_service/get_all_companies.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): company_service = client.GetService('CompanyService', version='v201802') # Create a statement to select companies. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/company_service/update_companies.py b/examples/ad_manager/v201802/company_service/update_companies.py similarity index 92% rename from examples/dfp/v201802/company_service/update_companies.py rename to examples/ad_manager/v201802/company_service/update_companies.py index 1bfe94bc..1d70bb9a 100755 --- a/examples/dfp/v201802/company_service/update_companies.py +++ b/examples/ad_manager/v201802/company_service/update_companies.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the company to update. COMPANY_ID = 'INSERT_COMPANY_ID_HERE' @@ -38,7 +38,7 @@ def main(client, company_id): company_service = client.GetService('CompanyService', version='v201802') # Create statement object to only select a single company by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(company_id)) .Limit(1)) @@ -66,5 +66,5 @@ def main(client, company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, COMPANY_ID) diff --git a/examples/dfp/v201711/contact_service/__init__.py b/examples/ad_manager/v201802/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201711/contact_service/__init__.py rename to examples/ad_manager/v201802/contact_service/__init__.py diff --git a/examples/dfp/v201802/contact_service/create_contacts.py b/examples/ad_manager/v201802/contact_service/create_contacts.py similarity index 92% rename from examples/dfp/v201802/contact_service/create_contacts.py rename to examples/ad_manager/v201802/contact_service/create_contacts.py index 80687d64..675cc03c 100755 --- a/examples/dfp/v201802/contact_service/create_contacts.py +++ b/examples/ad_manager/v201802/contact_service/create_contacts.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the advertiser company this contact is associated with. ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -67,5 +67,5 @@ def main(client, advertiser_company_id, agency_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) diff --git a/examples/dfp/v201802/contact_service/get_all_contacts.py b/examples/ad_manager/v201802/contact_service/get_all_contacts.py similarity index 90% rename from examples/dfp/v201802/contact_service/get_all_contacts.py rename to examples/ad_manager/v201802/contact_service/get_all_contacts.py index 32c02b93..2afe600c 100755 --- a/examples/dfp/v201802/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201802/contact_service/get_all_contacts.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): contact_service = client.GetService('ContactService', version='v201802') # Create a statement to select contacts. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201802/contact_service/get_uninvited_contacts.py similarity index 90% rename from examples/dfp/v201802/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v201802/contact_service/get_uninvited_contacts.py index 1f809524..4ee94a3d 100755 --- a/examples/dfp/v201802/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201802/contact_service/get_uninvited_contacts.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. contact_service = client.GetService('ContactService', version='v201802') # Create a statement to select contacts. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/contact_service/update_contacts.py b/examples/ad_manager/v201802/contact_service/update_contacts.py similarity index 92% rename from examples/dfp/v201802/contact_service/update_contacts.py rename to examples/ad_manager/v201802/contact_service/update_contacts.py index 0a1196c9..cc46f9d2 100755 --- a/examples/dfp/v201802/contact_service/update_contacts.py +++ b/examples/ad_manager/v201802/contact_service/update_contacts.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the contact to update. CONTACT_ID = 'INSERT_CONTACT_ID_HERE' @@ -38,7 +38,7 @@ def main(client, contact_id): contact_service = client.GetService('ContactService', version='v201802') # Create statement object to select the single contact by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(contact_id)) .Limit(1)) @@ -67,5 +67,5 @@ def main(client, contact_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTACT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTACT_ID) diff --git a/examples/dfp/v201711/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201711/content_metadata_key_hierarchy_service/__init__.py rename to examples/ad_manager/v201802/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 5b0c261e..cd5255e5 100755 --- a/examples/dfp/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -19,7 +19,7 @@ To determine which content metadata key hierarchies exist, run get_all_content_metadata_key_hierarchies.py. -This feature is only available to DFP video publishers. +This feature is only available to Video Solutions publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the IDs of the custom targeting keys for the hierarchy. HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' @@ -74,5 +74,6 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, HIERARCHY_LEVEL_ONE_KEY_ID, HIERARCHY_LEVEL_TWO_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, HIERARCHY_LEVEL_ONE_KEY_ID, + HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py index 24acd69a..e46667e6 100755 --- a/examples/dfp/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py @@ -19,7 +19,7 @@ To determine which content metadata key hierarchies exist, run get_all_content_metadata_key_hierarchies.py. -This feature is only available to DFP video publishers. +This feature is only available to Video Solutions publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,7 +30,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the content metadata key hierarchy to delete. CONTENT_METADATA_KEY_HIERARCHY_ID = ( @@ -44,7 +44,7 @@ def main(client, content_metadata_key_hierarchy_id): # Create a query to select a single content metadata key hierarchy. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) @@ -77,5 +77,5 @@ def main(client, content_metadata_key_hierarchy_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID) diff --git a/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 37d04a34..cae8df2b 100755 --- a/examples/dfp/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ContentMetadataKeyHierarchyService', version='v201802') # Create a statement to select content metadata key hierarchies. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index cbef227b..094441b9 100755 --- a/examples/dfp/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -19,7 +19,7 @@ To determine which content metadata key hierarchies exist, run get_all_content_metadata_key_hierarchies.py. -This feature is only available to DFP video publishers. +This feature is only available to Video Solutions publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,7 +30,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the content metadata key hierarchy to update. CONTENT_METADATA_KEY_HIERARCHY_ID = ( @@ -46,7 +46,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Create a query to select a single content metadata key hierarchy. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) @@ -89,5 +89,6 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID, + CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201711/content_service/__init__.py b/examples/ad_manager/v201802/content_service/__init__.py similarity index 100% rename from examples/dfp/v201711/content_service/__init__.py rename to examples/ad_manager/v201802/content_service/__init__.py diff --git a/examples/dfp/v201802/content_service/get_all_content.py b/examples/ad_manager/v201802/content_service/get_all_content.py similarity index 90% rename from examples/dfp/v201802/content_service/get_all_content.py rename to examples/ad_manager/v201802/content_service/get_all_content.py index 52f53c40..98fc5126 100755 --- a/examples/dfp/v201802/content_service/get_all_content.py +++ b/examples/ad_manager/v201802/content_service/get_all_content.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): content_service = client.GetService('ContentService', version='v201802') # Create a statement to select content. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_service/__init__.py b/examples/ad_manager/v201802/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201711/creative_service/__init__.py rename to examples/ad_manager/v201802/creative_service/__init__.py diff --git a/examples/dfp/v201802/creative_service/copy_image_creatives.py b/examples/ad_manager/v201802/creative_service/copy_image_creatives.py similarity index 88% rename from examples/dfp/v201802/creative_service/copy_image_creatives.py rename to examples/ad_manager/v201802/creative_service/copy_image_creatives.py index 9a5270da..c3b481be 100755 --- a/examples/dfp/v201802/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201802/creative_service/copy_image_creatives.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' @@ -31,7 +31,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to get the image creative. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) @@ -50,11 +50,11 @@ def main(client): print ('A creative with ID %d, name "%s", and type "%s" was created and ' 'can be previewed at: %s' % (result['id'], result['name'], - dfp.DfpClassType(result), + ad_manager.AdManagerClassType(result), result['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_service/create_creative_from_template.py b/examples/ad_manager/v201802/creative_service/create_creative_from_template.py similarity index 92% rename from examples/dfp/v201802/creative_service/create_creative_from_template.py rename to examples/ad_manager/v201802/creative_service/create_creative_from_template.py index 5c426783..874bec7b 100755 --- a/examples/dfp/v201802/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201802/creative_service/create_creative_from_template.py @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -102,10 +102,10 @@ def main(client, advertiser_id): # Display results. print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201802/creative_service/create_creatives.py b/examples/ad_manager/v201802/creative_service/create_creatives.py similarity index 90% rename from examples/dfp/v201802/creative_service/create_creatives.py rename to examples/ad_manager/v201802/creative_service/create_creatives.py index af9e329f..afda4e42 100755 --- a/examples/dfp/v201802/creative_service/create_creatives.py +++ b/examples/ad_manager/v201802/creative_service/create_creatives.py @@ -31,7 +31,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that all creatives will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -81,10 +81,10 @@ def main(client, advertiser_id): for creative in creatives: print ('Image creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201802/creative_service/create_custom_creative.py b/examples/ad_manager/v201802/creative_service/create_custom_creative.py similarity index 89% rename from examples/dfp/v201802/creative_service/create_custom_creative.py rename to examples/ad_manager/v201802/creative_service/create_custom_creative.py index de42ae87..c24c6640 100755 --- a/examples/dfp/v201802/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201802/creative_service/create_custom_creative.py @@ -16,7 +16,7 @@ """This example creates a custom creative for a given advertiser. -This feature is only available to DFP premium solution networks. To determine +This feature is only available to Ad Manager 360 solution networks. To determine which companies are advertisers, run get_advertisers.py. To determine which creative templates exist, run get_all_creative_templates.py. @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -79,10 +79,10 @@ def main(client, advertiser_id): creative = creatives[0] print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201802/creative_service/create_native_creative.py b/examples/ad_manager/v201802/creative_service/create_native_creative.py similarity index 97% rename from examples/dfp/v201802/creative_service/create_native_creative.py rename to examples/ad_manager/v201802/creative_service/create_native_creative.py index a52f3501..b7653eb5 100755 --- a/examples/dfp/v201802/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201802/creative_service/create_native_creative.py @@ -33,7 +33,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' @@ -128,5 +128,5 @@ def main(client, advertiser_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201802/creative_service/get_all_creatives.py b/examples/ad_manager/v201802/creative_service/get_all_creatives.py similarity index 90% rename from examples/dfp/v201802/creative_service/get_all_creatives.py rename to examples/ad_manager/v201802/creative_service/get_all_creatives.py index 2c12848b..4ae2ccb4 100755 --- a/examples/dfp/v201802/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201802/creative_service/get_all_creatives.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to select creatives. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_service/get_image_creatives.py b/examples/ad_manager/v201802/creative_service/get_image_creatives.py similarity index 90% rename from examples/dfp/v201802/creative_service/get_image_creatives.py rename to examples/ad_manager/v201802/creative_service/get_image_creatives.py index 294ed1cf..78956e3e 100755 --- a/examples/dfp/v201802/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201802/creative_service/get_image_creatives.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. creative_service = client.GetService('CreativeService', version='v201802') # Create a statement to select creatives. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_service/update_creatives.py b/examples/ad_manager/v201802/creative_service/update_creatives.py similarity index 92% rename from examples/dfp/v201802/creative_service/update_creatives.py rename to examples/ad_manager/v201802/creative_service/update_creatives.py index 5bc84e6d..1c482118 100755 --- a/examples/dfp/v201802/creative_service/update_creatives.py +++ b/examples/ad_manager/v201802/creative_service/update_creatives.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE' @@ -37,7 +37,7 @@ def main(client, image_creative_id): creative_service = client.GetService('CreativeService', version='v201802') # Create statement object to get the creative by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', long(image_creative_id)) @@ -67,5 +67,5 @@ def main(client, image_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, IMAGE_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, IMAGE_CREATIVE_ID) diff --git a/examples/dfp/v201711/creative_set_service/__init__.py b/examples/ad_manager/v201802/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201711/creative_set_service/__init__.py rename to examples/ad_manager/v201802/creative_set_service/__init__.py diff --git a/examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201802/creative_set_service/associate_creative_set_to_line_item.py similarity index 92% rename from examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v201802/creative_set_service/associate_creative_set_to_line_item.py index 339e5627..6440584c 100755 --- a/examples/dfp/v201802/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201802/creative_set_service/associate_creative_set_to_line_item.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -51,5 +51,5 @@ def main(client, creative_set_id, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_SET_ID, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_SET_ID, LINE_ITEM_ID) diff --git a/examples/dfp/v201802/creative_set_service/create_creative_set.py b/examples/ad_manager/v201802/creative_set_service/create_creative_set.py similarity index 92% rename from examples/dfp/v201802/creative_set_service/create_creative_set.py rename to examples/ad_manager/v201802/creative_set_service/create_creative_set.py index f3af2365..c3d58a6b 100755 --- a/examples/dfp/v201802/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201802/creative_set_service/create_creative_set.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' @@ -57,5 +57,5 @@ def main(client, master_creative_id, companion_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) diff --git a/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201802/creative_set_service/get_all_creative_sets.py similarity index 90% rename from examples/dfp/v201802/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v201802/creative_set_service/get_all_creative_sets.py index d39b99ef..5c9e865b 100755 --- a/examples/dfp/v201802/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201802/creative_set_service/get_all_creative_sets.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CreativeSetService', version='v201802') # Create a statement to select creative sets. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201802/creative_set_service/get_creative_sets_for_master_creative.py similarity index 90% rename from examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v201802/creative_set_service/get_creative_sets_for_master_creative.py index d13e615e..ba946129 100755 --- a/examples/dfp/v201802/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201802/creative_set_service/get_creative_sets_for_master_creative.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' @@ -27,7 +27,7 @@ def main(client, master_creative_id): creative_set_service = client.GetService( 'CreativeSetService', version='v201802') # Create a statement to select creative sets. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) @@ -50,5 +50,5 @@ def main(client, master_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, MASTER_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, MASTER_CREATIVE_ID) diff --git a/examples/dfp/v201802/creative_set_service/update_creative_set.py b/examples/ad_manager/v201802/creative_set_service/update_creative_set.py similarity index 92% rename from examples/dfp/v201802/creative_set_service/update_creative_set.py rename to examples/ad_manager/v201802/creative_set_service/update_creative_set.py index b23aa8f1..9182645e 100755 --- a/examples/dfp/v201802/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201802/creative_set_service/update_creative_set.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the creative set to update. CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' @@ -40,7 +40,7 @@ def main(client, creative_set_id, companion_creative_id): version='v201802') # Create statement to select a single creative set by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', long(creative_set_id))) @@ -69,5 +69,5 @@ def main(client, creative_set_id, companion_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) diff --git a/examples/dfp/v201711/creative_template_service/__init__.py b/examples/ad_manager/v201802/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201711/creative_template_service/__init__.py rename to examples/ad_manager/v201802/creative_template_service/__init__.py diff --git a/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201802/creative_template_service/get_all_creative_templates.py similarity index 90% rename from examples/dfp/v201802/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v201802/creative_template_service/get_all_creative_templates.py index 6df8e065..f7b75e72 100755 --- a/examples/dfp/v201802/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201802/creative_template_service/get_all_creative_templates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CreativeTemplateService', version='v201802') # Create a statement to select creative templates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201802/creative_template_service/get_system_defined_creative_templates.py similarity index 91% rename from examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v201802/creative_template_service/get_system_defined_creative_templates.py index ef613634..c93a7757 100755 --- a/examples/dfp/v201802/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201802/creative_template_service/get_system_defined_creative_templates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): creative_template_service = client.GetService( 'CreativeTemplateService', version='v201802') # Create a statement to select creative templates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201802/creative_wrapper_service/create_creative_wrappers.py similarity index 94% rename from examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v201802/creative_wrapper_service/create_creative_wrappers.py index 624413df..4202a22e 100755 --- a/examples/dfp/v201802/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201802/creative_wrapper_service/create_creative_wrappers.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE' @@ -59,5 +59,5 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201802/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 93% rename from examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v201802/creative_wrapper_service/deactivate_creative_wrapper.py index 8cd26e55..1326aac3 100755 --- a/examples/dfp/v201802/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201802/creative_wrapper_service/deactivate_creative_wrapper.py @@ -25,7 +25,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_LABEL_ID_HERE' @@ -36,7 +36,7 @@ def main(client, label_id): version='v201802') # Create a query to select the active creative wrappers for the given label. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', long(label_id))) @@ -74,5 +74,5 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201802/creative_wrapper_service/get_active_creative_wrappers.py similarity index 91% rename from examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v201802/creative_wrapper_service/get_active_creative_wrappers.py index 3fe60bd2..976a62b5 100755 --- a/examples/dfp/v201802/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201802/creative_wrapper_service/get_active_creative_wrappers.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): creative_wrapper_service = client.GetService( 'CreativeWrapperService', version='v201802') # Create a statement to select creative wrappers. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201802/creative_wrapper_service/get_all_creative_wrappers.py similarity index 90% rename from examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v201802/creative_wrapper_service/get_all_creative_wrappers.py index 4b6ec0bf..a2038391 100755 --- a/examples/dfp/v201802/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201802/creative_wrapper_service/get_all_creative_wrappers.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CreativeWrapperService', version='v201802') # Create a statement to select creative wrappers. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201802/creative_wrapper_service/update_creative_wrappers.py similarity index 92% rename from examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v201802/creative_wrapper_service/update_creative_wrappers.py index 27eb2e0b..e00f3c78 100755 --- a/examples/dfp/v201802/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201802/creative_wrapper_service/update_creative_wrappers.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the creative wrapper to update. CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE' @@ -39,7 +39,7 @@ def main(client, creative_wrapper_id): version='v201802') # Create statement to get a creative wrapper by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', long(creative_wrapper_id))) @@ -69,5 +69,5 @@ def main(client, creative_wrapper_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_WRAPPER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_WRAPPER_ID) diff --git a/examples/dfp/v201711/custom_field_service/__init__.py b/examples/ad_manager/v201802/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201711/custom_field_service/__init__.py rename to examples/ad_manager/v201802/custom_field_service/__init__.py diff --git a/examples/dfp/v201802/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201802/custom_field_service/create_custom_field_options.py similarity index 93% rename from examples/dfp/v201802/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v201802/custom_field_service/create_custom_field_options.py index 8129c823..97e58514 100755 --- a/examples/dfp/v201802/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201802/custom_field_service/create_custom_field_options.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the drop-down custom field to create options for. CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' @@ -63,5 +63,5 @@ def main(client, custom_field_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/dfp/v201802/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201802/custom_field_service/create_custom_fields.py similarity index 93% rename from examples/dfp/v201802/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v201802/custom_field_service/create_custom_fields.py index 1aaf1209..03a212ea 100755 --- a/examples/dfp/v201802/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201802/custom_field_service/create_custom_fields.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 93% rename from examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py index 295ce5d6..4c9f4582 100755 --- a/examples/dfp/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -37,7 +37,7 @@ def main(client): # Create statement to select only active custom fields that apply to # line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) @@ -69,5 +69,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201802/custom_field_service/get_all_custom_fields.py similarity index 90% rename from examples/dfp/v201802/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v201802/custom_field_service/get_all_custom_fields.py index 4f4d0ba4..96994073 100755 --- a/examples/dfp/v201802/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201802/custom_field_service/get_all_custom_fields.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CustomFieldService', version='v201802') # Create a statement to select custom fields. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201802/custom_field_service/get_custom_fields_for_line_items.py similarity index 91% rename from examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v201802/custom_field_service/get_custom_fields_for_line_items.py index d1da9092..2e5bcacc 100755 --- a/examples/dfp/v201802/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201802/custom_field_service/get_custom_fields_for_line_items.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): custom_field_service = client.GetService( 'CustomFieldService', version='v201802') # Create a statement to select custom fields. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201802/custom_field_service/set_line_item_custom_field_value.py similarity index 91% rename from examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v201802/custom_field_service/set_line_item_custom_field_value.py index 3553cb4e..586332e0 100755 --- a/examples/dfp/v201802/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201802/custom_field_service/set_line_item_custom_field_value.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the custom fields, custom field option, and line item. CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' @@ -47,7 +47,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, line_item_service = client.GetService('LineItemService', version='v201802') # Create statement to get a custom field. - custom_field_statement = (dfp.StatementBuilder() + custom_field_statement = (ad_manager.StatementBuilder() .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - dfp.StatementBuilder() + ad_manager.StatementBuilder() .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (dfp.StatementBuilder() + line_item_statement = (ad_manager.StatementBuilder() .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) @@ -118,11 +118,11 @@ def main(client, custom_field_id, drop_down_custom_field_id, for line_item in line_items: custom_field_value_strings = [] for value in line_item['customFieldValues']: - if dfp.DfpClassType(value) == 'CustomFieldValue': + if ad_manager.AdManagerClassType(value) == 'CustomFieldValue': custom_field_value_string = ( '{ID: "%s", value: "%s"}' % (value['customFieldId'], value['value']['value'])) - elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': + elif ad_manager.AdManagerClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) @@ -134,6 +134,6 @@ def main(client, custom_field_id, drop_down_custom_field_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID) diff --git a/examples/dfp/v201802/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201802/custom_field_service/update_custom_fields.py similarity index 92% rename from examples/dfp/v201802/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v201802/custom_field_service/update_custom_fields.py index cdebe296..1dc42beb 100755 --- a/examples/dfp/v201802/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201802/custom_field_service/update_custom_fields.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the custom field to update. CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' @@ -39,7 +39,7 @@ def main(client, custom_field_id): 'CustomFieldService', version='v201802') # Create statement to get a custom field. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :customFieldId') .WithBindVariable('customFieldId', long(custom_field_id))) @@ -66,5 +66,5 @@ def main(client, custom_field_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/dfp/v201711/custom_targeting_service/__init__.py b/examples/ad_manager/v201802/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201711/custom_targeting_service/__init__.py rename to examples/ad_manager/v201802/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 96% rename from examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py index 708a712a..2c4dc58e 100755 --- a/examples/dfp/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -128,5 +128,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_keys.py similarity index 91% rename from examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_keys.py index 733cdc25..dddca3e6 100755 --- a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_keys.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE' @@ -38,7 +38,7 @@ def main(client, key_name): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201802') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (dfp.StatementBuilder() + key_statement = (ad_manager.StatementBuilder() .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. @@ -73,5 +73,5 @@ def main(client, key_name): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, KEY_NAME) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, KEY_NAME) diff --git a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_values.py similarity index 91% rename from examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_values.py index 14355137..869c7c2e 100755 --- a/examples/dfp/v201802/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_values.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -38,7 +38,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201802') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (dfp.StatementBuilder() + value_statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) @@ -73,5 +73,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, KEY_ID) diff --git a/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 91% rename from examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 57da81ae..4771088a 100755 --- a/examples/dfp/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201802') # Create statement to get all targeting keys. - targeting_key_statement = dfp.StatementBuilder() + targeting_key_statement = ad_manager.StatementBuilder() all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) @@ -68,5 +68,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 92% rename from examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 317dd4f8..ef65c3f9 100755 --- a/examples/dfp/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201802') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (dfp.StatementBuilder() + targeting_key_statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) @@ -70,5 +70,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_keys.py similarity index 91% rename from examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_keys.py index a9d34392..be7f1a4c 100755 --- a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_keys.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -32,7 +32,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201802') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :keyId') .WithBindVariable('keyId', long(key_id)) .Limit(1)) @@ -63,5 +63,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_values.py similarity index 92% rename from examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_values.py index d9a8a7e2..6063ccd9 100755 --- a/examples/dfp/v201802/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_values.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -32,7 +32,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201802') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', long(key_id))) @@ -67,5 +67,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201711/exchange_rate_service/__init__.py b/examples/ad_manager/v201802/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201711/exchange_rate_service/__init__.py rename to examples/ad_manager/v201802/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201802/exchange_rate_service/create_exchange_rates.py similarity index 93% rename from examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py rename to examples/ad_manager/v201802/exchange_rate_service/create_exchange_rates.py index 66706137..5f717426 100755 --- a/examples/dfp/v201802/exchange_rate_service/create_exchange_rates.py +++ b/examples/ad_manager/v201802/exchange_rate_service/create_exchange_rates.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -54,5 +54,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201802/exchange_rate_service/get_all_exchange_rates.py similarity index 91% rename from examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py rename to examples/ad_manager/v201802/exchange_rate_service/get_all_exchange_rates.py index e3165d30..626499c6 100755 --- a/examples/dfp/v201802/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201802/exchange_rate_service/get_all_exchange_rates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ExchangeRateService', version='v201802') # Create a statement to select exchange rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 91% rename from examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/ad_manager/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py index 9c715fe3..0799cde2 100755 --- a/examples/dfp/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' @@ -27,7 +27,7 @@ def main(client, currency_code): exchange_rate_service = client.GetService( 'ExchangeRateService', version='v201802') # Create a statement to select exchange rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('currencyCode = :currencyCode') .WithBindVariable('currencyCode', currency_code)) @@ -52,5 +52,5 @@ def main(client, currency_code): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CURRENCY_CODE) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CURRENCY_CODE) diff --git a/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201802/exchange_rate_service/update_exchange_rates.py similarity index 92% rename from examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py rename to examples/ad_manager/v201802/exchange_rate_service/update_exchange_rates.py index 6e760ee5..f2de4bed 100755 --- a/examples/dfp/v201802/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201802/exchange_rate_service/update_exchange_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' @@ -33,7 +33,7 @@ def main(client, exchange_rate_id): version='v201802') # Create a statement to get an exchange rate by its ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(exchange_rate_id)) .Limit(1)) @@ -67,5 +67,5 @@ def main(client, exchange_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, EXCHANGE_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, EXCHANGE_RATE_ID) diff --git a/examples/dfp/v201802/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201802/forecast_service/get_availability_forecast.py similarity index 96% rename from examples/dfp/v201802/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v201802/forecast_service/get_availability_forecast.py index 29da19fc..ad2a9446 100755 --- a/examples/dfp/v201802/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v201802/forecast_service/get_availability_forecast.py @@ -27,7 +27,7 @@ import datetime # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set the ID of the advertiser (company) to forecast for. Setting an advertiser @@ -126,5 +126,5 @@ def main(client, advertiser_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201802/forecast_service/get_availability_forecast_for_line_item.py similarity index 93% rename from examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v201802/forecast_service/get_availability_forecast_for_line_item.py index f7914e26..38dec1ad 100755 --- a/examples/dfp/v201802/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201802/forecast_service/get_availability_forecast_for_line_item.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line item to get a forecast for. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -62,5 +62,5 @@ def main(client, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201802/forecast_service/get_delivery_forecast_for_line_items.py similarity index 91% rename from examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v201802/forecast_service/get_delivery_forecast_for_line_items.py index f6277566..911d9f1a 100755 --- a/examples/dfp/v201802/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201802/forecast_service/get_delivery_forecast_for_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line items to get forecasts for. LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' @@ -48,5 +48,5 @@ def main(client, line_item_id1, line_item_id2): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201711/inventory_service/__init__.py b/examples/ad_manager/v201802/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201711/inventory_service/__init__.py rename to examples/ad_manager/v201802/inventory_service/__init__.py diff --git a/examples/dfp/v201802/inventory_service/archive_ad_units.py b/examples/ad_manager/v201802/inventory_service/archive_ad_units.py similarity index 92% rename from examples/dfp/v201802/inventory_service/archive_ad_units.py rename to examples/ad_manager/v201802/inventory_service/archive_ad_units.py index 0b1ec4e4..27e4fabc 100755 --- a/examples/dfp/v201802/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201802/inventory_service/archive_ad_units.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' @@ -39,7 +39,7 @@ def main(client, parent_id): # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', long(parent_id))) @@ -71,5 +71,5 @@ def main(client, parent_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PARENT_AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/dfp/v201802/inventory_service/create_ad_units.py b/examples/ad_manager/v201802/inventory_service/create_ad_units.py similarity index 92% rename from examples/dfp/v201802/inventory_service/create_ad_units.py rename to examples/ad_manager/v201802/inventory_service/create_ad_units.py index 708709f9..0891613f 100755 --- a/examples/dfp/v201802/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201802/inventory_service/create_ad_units.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' @@ -66,5 +66,5 @@ def main(client, parent_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PARENT_AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201802/inventory_service/get_ad_unit_hierarchy.py similarity index 94% rename from examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v201802/inventory_service/get_ad_unit_hierarchy.py index 97a00c07..e8037b15 100755 --- a/examples/dfp/v201802/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201802/inventory_service/get_ad_unit_hierarchy.py @@ -19,7 +19,7 @@ # Import appropriate modules from the client library. import collections -from googleads import dfp +from googleads import ad_manager def main(client): @@ -32,7 +32,7 @@ def main(client): root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .OrderBy('id', ascending=True)) # Pull down all ad units into a list @@ -111,5 +111,5 @@ def display_hierarchy_helper(root, parent_id_to_children, depth): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201802/inventory_service/get_all_ad_unit_sizes.py similarity index 89% rename from examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v201802/inventory_service/get_all_ad_unit_sizes.py index 4858e6fc..07c08062 100755 --- a/examples/dfp/v201802/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201802/inventory_service/get_all_ad_unit_sizes.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'InventoryService', version='v201802') # Create a statement to select ad unit sizes. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. @@ -42,5 +42,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201802/inventory_service/get_all_ad_units.py similarity index 90% rename from examples/dfp/v201802/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v201802/inventory_service/get_all_ad_units.py index a0593b64..bbc6024c 100755 --- a/examples/dfp/v201802/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201802/inventory_service/get_all_ad_units.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): ad_unit_service = client.GetService('InventoryService', version='v201802') # Create a statement to select ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201802/inventory_service/get_top_level_ad_units.py similarity index 92% rename from examples/dfp/v201802/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v201802/inventory_service/get_top_level_ad_units.py index afc75cf6..ec2d411c 100755 --- a/examples/dfp/v201802/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201802/inventory_service/get_top_level_ad_units.py @@ -18,7 +18,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -31,7 +31,7 @@ def main(client): parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) @@ -54,5 +54,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/inventory_service/update_ad_units.py b/examples/ad_manager/v201802/inventory_service/update_ad_units.py similarity index 93% rename from examples/dfp/v201802/inventory_service/update_ad_units.py rename to examples/ad_manager/v201802/inventory_service/update_ad_units.py index 2834c7f7..b3386efd 100755 --- a/examples/dfp/v201802/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201802/inventory_service/update_ad_units.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the ad unit to get. @@ -39,7 +39,7 @@ def main(client, ad_unit_id): inventory_service = client.GetService('InventoryService', version='v201802') # Create a statement to select a single ad unit by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', ad_unit_id)) @@ -78,5 +78,5 @@ def main(client, ad_unit_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AD_UNIT_ID) diff --git a/examples/dfp/v201711/label_service/__init__.py b/examples/ad_manager/v201802/label_service/__init__.py similarity index 100% rename from examples/dfp/v201711/label_service/__init__.py rename to examples/ad_manager/v201802/label_service/__init__.py diff --git a/examples/dfp/v201802/label_service/create_labels.py b/examples/ad_manager/v201802/label_service/create_labels.py similarity index 89% rename from examples/dfp/v201802/label_service/create_labels.py rename to examples/ad_manager/v201802/label_service/create_labels.py index c6e3d203..31366328 100755 --- a/examples/dfp/v201802/label_service/create_labels.py +++ b/examples/ad_manager/v201802/label_service/create_labels.py @@ -17,14 +17,14 @@ """This code example creates new labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/label_service/deactivate_labels.py b/examples/ad_manager/v201802/label_service/deactivate_labels.py similarity index 89% rename from examples/dfp/v201802/label_service/deactivate_labels.py rename to examples/ad_manager/v201802/label_service/deactivate_labels.py index a6a37d90..22672fdd 100755 --- a/examples/dfp/v201802/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201802/label_service/deactivate_labels.py @@ -17,12 +17,12 @@ """This code example deactivates all active Labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -30,7 +30,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isActive = :isActive') .WithBindVariable('isActive', True)) @@ -61,5 +61,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/label_service/get_active_labels.py b/examples/ad_manager/v201802/label_service/get_active_labels.py similarity index 90% rename from examples/dfp/v201802/label_service/get_active_labels.py rename to examples/ad_manager/v201802/label_service/get_active_labels.py index 0d1085ee..a4b1e9d8 100755 --- a/examples/dfp/v201802/label_service/get_active_labels.py +++ b/examples/ad_manager/v201802/label_service/get_active_labels.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201802') # Create a statement to select labels. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isActive = :isActive') .WithBindVariable('isActive', True)) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/label_service/get_all_labels.py b/examples/ad_manager/v201802/label_service/get_all_labels.py similarity index 90% rename from examples/dfp/v201802/label_service/get_all_labels.py rename to examples/ad_manager/v201802/label_service/get_all_labels.py index 2303e1a4..a3fdbd14 100755 --- a/examples/dfp/v201802/label_service/get_all_labels.py +++ b/examples/ad_manager/v201802/label_service/get_all_labels.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201802') # Create a statement to select labels. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/label_service/update_labels.py b/examples/ad_manager/v201802/label_service/update_labels.py similarity index 89% rename from examples/dfp/v201802/label_service/update_labels.py rename to examples/ad_manager/v201802/label_service/update_labels.py index 74c8783f..485f43b2 100755 --- a/examples/dfp/v201802/label_service/update_labels.py +++ b/examples/ad_manager/v201802/label_service/update_labels.py @@ -17,12 +17,12 @@ """This code example updates the description of a single label. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_LABEL_ID_HERE' @@ -32,7 +32,7 @@ def main(client, label_id): label_service = client.GetService('LabelService', version='v201802') # Create a statement to select only active labels. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :labelId') .WithBindVariable('labelId', long(label_id))) @@ -58,6 +58,6 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201711/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201802/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201711/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v201802/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201802/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201802/line_item_creative_association_service/create_licas.py similarity index 91% rename from examples/dfp/v201802/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v201802/line_item_creative_association_service/create_licas.py index dcad9d0c..f881d6d7 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201802/line_item_creative_association_service/create_licas.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line item ID and creative IDs to associate. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -53,5 +53,5 @@ def main(client, line_item_id, creative_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID, CREATIVE_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, CREATIVE_IDS) diff --git a/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201802/line_item_creative_association_service/deactivate_licas.py similarity index 92% rename from examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v201802/line_item_creative_association_service/deactivate_licas.py index 202b13a0..cf9815c1 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201802/line_item_creative_association_service/deactivate_licas.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the line item in which to deactivate LICAs. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -33,7 +33,7 @@ def main(client, line_item_id): 'LineItemCreativeAssociationService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', long(line_item_id))) @@ -69,5 +69,5 @@ def main(client, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201802/line_item_creative_association_service/get_all_licas.py similarity index 92% rename from examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v201802/line_item_creative_association_service/get_all_licas.py index a5e548d8..9a5fb443 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201802/line_item_creative_association_service/get_all_licas.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201802') # Create a statement to select line item creative associations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201802/line_item_creative_association_service/get_licas_for_line_item.py similarity index 92% rename from examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v201802/line_item_creative_association_service/get_licas_for_line_item.py index 5f799a2c..c1a8bf72 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201802/line_item_creative_association_service/get_licas_for_line_item.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -27,7 +27,7 @@ def main(client, line_item_id): lica_service = client.GetService( 'LineItemCreativeAssociationService', version='v201802') # Create a statement to select line item creative associations. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) @@ -56,5 +56,5 @@ def main(client, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201802/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201802/line_item_creative_association_service/update_licas.py similarity index 92% rename from examples/dfp/v201802/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v201802/line_item_creative_association_service/update_licas.py index ab99185e..e4658ad6 100755 --- a/examples/dfp/v201802/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201802/line_item_creative_association_service/update_licas.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -31,7 +31,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201802') # Create statement object to get all LICAs. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() while True: # Get LICAs by statement. @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/line_item_service/__init__.py b/examples/ad_manager/v201802/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201711/line_item_service/__init__.py rename to examples/ad_manager/v201802/line_item_service/__init__.py diff --git a/examples/dfp/v201802/line_item_service/activate_line_items.py b/examples/ad_manager/v201802/line_item_service/activate_line_items.py similarity index 93% rename from examples/dfp/v201802/line_item_service/activate_line_items.py rename to examples/ad_manager/v201802/line_item_service/activate_line_items.py index edd95797..ec24ee04 100755 --- a/examples/dfp/v201802/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201802/line_item_service/activate_line_items.py @@ -25,7 +25,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the order to get line items from. ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -36,7 +36,7 @@ def main(client, order_id): line_item_service = client.GetService('LineItemService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', long(order_id))) @@ -71,5 +71,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201802/line_item_service/create_line_items.py b/examples/ad_manager/v201802/line_item_service/create_line_items.py similarity index 96% rename from examples/dfp/v201802/line_item_service/create_line_items.py rename to examples/ad_manager/v201802/line_item_service/create_line_items.py index 1e5af88b..2f9788f5 100755 --- a/examples/dfp/v201802/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201802/line_item_service/create_line_items.py @@ -26,7 +26,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set order that the created line item will belong to and add the id of a @@ -161,6 +161,6 @@ def main(client, order_id, targeted_placement_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID, TARGETED_PLACEMENT_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS) diff --git a/examples/dfp/v201802/line_item_service/create_video_line_item.py b/examples/ad_manager/v201802/line_item_service/create_video_line_item.py similarity index 94% rename from examples/dfp/v201802/line_item_service/create_video_line_item.py rename to examples/ad_manager/v201802/line_item_service/create_video_line_item.py index fcb84fec..19a7e3d7 100755 --- a/examples/dfp/v201802/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v201802/line_item_service/create_video_line_item.py @@ -16,7 +16,7 @@ """This code example creates a new line item to serve to video content. -This feature is only available to DFP premium solution networks. To determine +This feature is only available to Ad Manager 360 solution networks. To determine which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To create a video ad unit, run create_video_ad_unit.py. To create criteria for categories, run @@ -28,7 +28,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set order that all created line item will belong to and the video ad unit id @@ -130,6 +130,6 @@ def main(client, order_id, targeted_video_ad_unit_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201802/line_item_service/get_all_line_items.py b/examples/ad_manager/v201802/line_item_service/get_all_line_items.py similarity index 90% rename from examples/dfp/v201802/line_item_service/get_all_line_items.py rename to examples/ad_manager/v201802/line_item_service/get_all_line_items.py index 33107257..223484aa 100755 --- a/examples/dfp/v201802/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201802/line_item_service/get_all_line_items.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): line_item_service = client.GetService('LineItemService', version='v201802') # Create a statement to select line items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201802/line_item_service/get_line_items_that_need_creatives.py similarity index 91% rename from examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v201802/line_item_service/get_line_items_that_need_creatives.py index b8d89924..e309e0e4 100755 --- a/examples/dfp/v201802/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201802/line_item_service/get_line_items_that_need_creatives.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. line_item_service = client.GetService('LineItemService', version='v201802') # Create a statement to select line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201802/line_item_service/get_recently_updated_line_items.py similarity index 91% rename from examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v201802/line_item_service/get_recently_updated_line_items.py index 5e6b2efa..2d14225e 100755 --- a/examples/dfp/v201802/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201802/line_item_service/get_recently_updated_line_items.py @@ -20,7 +20,7 @@ from datetime import datetime from datetime import timedelta -from googleads import dfp +from googleads import ad_manager import pytz @@ -32,7 +32,7 @@ def main(client): - timedelta(days=1)) # Create a statement to select line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) @@ -55,5 +55,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/line_item_service/pause_line_items.py b/examples/ad_manager/v201802/line_item_service/pause_line_items.py similarity index 93% rename from examples/dfp/v201802/line_item_service/pause_line_items.py rename to examples/ad_manager/v201802/line_item_service/pause_line_items.py index 6090566b..f902871f 100755 --- a/examples/dfp/v201802/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201802/line_item_service/pause_line_items.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -33,7 +33,7 @@ def main(client): # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) @@ -70,5 +70,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201802/line_item_service/target_custom_criteria.py similarity index 93% rename from examples/dfp/v201802/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v201802/line_item_service/target_custom_criteria.py index 810372a2..16c2d087 100755 --- a/examples/dfp/v201802/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201802/line_item_service/target_custom_criteria.py @@ -25,7 +25,7 @@ import pprint # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE' @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :lineItemId') .WithBindVariable('lineItemId', long(line_item_id)) .Limit(1)) @@ -105,6 +105,6 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, VALUE_ID2, VALUE_ID3) diff --git a/examples/dfp/v201802/line_item_service/update_line_items.py b/examples/ad_manager/v201802/line_item_service/update_line_items.py similarity index 93% rename from examples/dfp/v201802/line_item_service/update_line_items.py rename to examples/ad_manager/v201802/line_item_service/update_line_items.py index 4499cbb9..578add23 100755 --- a/examples/dfp/v201802/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201802/line_item_service/update_line_items.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the order to get line items from. ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -33,7 +33,7 @@ def main(client, order_id): # Create statement object to only select line items with even delivery rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', long(order_id)) @@ -70,5 +70,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201802/live_stream_event_service/activate_live_stream_events.py similarity index 90% rename from examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v201802/live_stream_event_service/activate_live_stream_events.py index 5c15f78a..6961f7a1 100755 --- a/examples/dfp/v201802/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201802/live_stream_event_service/activate_live_stream_events.py @@ -17,7 +17,7 @@ """This code example activates paused live stream events.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the LiveStreamEvent to get live stream events from. LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' @@ -29,7 +29,7 @@ def main(client, live_stream_event_id): 'LiveStreamEventService', version='v201802') # Create query to find paused live stream events. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') @@ -53,7 +53,7 @@ def main(client, live_stream_event_id): }, statement.ToStatement()) if result and int(result['numChanges']) > 0: live_stream_events_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += ad_manager.SUGGESTED_PAGE_LIMIT else: break @@ -67,5 +67,5 @@ def main(client, live_stream_event_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LIVE_STREAM_EVENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201802/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201802/live_stream_event_service/create_live_stream_events.py similarity index 93% rename from examples/dfp/v201802/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v201802/live_stream_event_service/create_live_stream_events.py index 927fe5fa..d97066d8 100755 --- a/examples/dfp/v201802/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v201802/live_stream_event_service/create_live_stream_events.py @@ -24,7 +24,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set content urls and adTags to use @@ -64,5 +64,5 @@ def main(client, content_urls, ad_tags): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_URLS, AD_TAGS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_URLS, AD_TAGS) diff --git a/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201802/live_stream_event_service/get_all_live_stream_events.py similarity index 90% rename from examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v201802/live_stream_event_service/get_all_live_stream_events.py index 0bfc1bca..ebbeb937 100755 --- a/examples/dfp/v201802/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201802/live_stream_event_service/get_all_live_stream_events.py @@ -18,7 +18,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -27,7 +27,7 @@ def main(client): 'LiveStreamEventService', version='v201802') # Create a statement to select live stream events. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201802/live_stream_event_service/register_sessions_for_monitoring.py similarity index 91% rename from examples/dfp/v201802/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v201802/live_stream_event_service/register_sessions_for_monitoring.py index 9330bb0f..b9b49175 100755 --- a/examples/dfp/v201802/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201802/live_stream_event_service/register_sessions_for_monitoring.py @@ -17,7 +17,7 @@ """This example registers all live stream event-sessions ids for monitoring.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # List of session ids SESSION_IDS = ['INSERT_SESSION_IDS_HERE'] @@ -41,5 +41,5 @@ def main(client, session_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, SESSION_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, SESSION_IDS) diff --git a/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201802/live_stream_event_service/update_live_stream_events.py similarity index 92% rename from examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v201802/live_stream_event_service/update_live_stream_events.py index 4bc9cf2e..b4cd1d12 100755 --- a/examples/dfp/v201802/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201802/live_stream_event_service/update_live_stream_events.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set ID of the LiveStreamEvent to get live stream events from. LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' @@ -32,7 +32,7 @@ def main(client, live_stream_event_id): 'LiveStreamEventService', version='v201802') # Create statement object to only select matching live stream event. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('Id = :id')) .WithBindVariable('id', long(live_stream_event_id)) .Limit(500)) @@ -65,5 +65,5 @@ def main(client, live_stream_event_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LIVE_STREAM_EVENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201711/native_style_service/__init__.py b/examples/ad_manager/v201802/native_style_service/__init__.py similarity index 100% rename from examples/dfp/v201711/native_style_service/__init__.py rename to examples/ad_manager/v201802/native_style_service/__init__.py diff --git a/examples/dfp/v201802/native_style_service/create_native_styles.py b/examples/ad_manager/v201802/native_style_service/create_native_styles.py similarity index 95% rename from examples/dfp/v201802/native_style_service/create_native_styles.py rename to examples/ad_manager/v201802/native_style_service/create_native_styles.py index f71eff5a..4b923cc2 100755 --- a/examples/dfp/v201802/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201802/native_style_service/create_native_styles.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # This is the creative template ID for the system-defined native app install ad @@ -175,6 +175,6 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, WIDTH, - HEIGHT) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, + WIDTH, HEIGHT) diff --git a/examples/dfp/v201802/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201802/native_style_service/get_all_native_styles.py similarity index 90% rename from examples/dfp/v201802/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v201802/native_style_service/get_all_native_styles.py index 4025475b..3c2bb81b 100755 --- a/examples/dfp/v201802/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201802/native_style_service/get_all_native_styles.py @@ -17,7 +17,7 @@ """This example gets all native styles.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): version='v201802') # Create a statement to select native styles. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/network_service/__init__.py b/examples/ad_manager/v201802/network_service/__init__.py similarity index 100% rename from examples/dfp/v201711/network_service/__init__.py rename to examples/ad_manager/v201802/network_service/__init__.py diff --git a/examples/dfp/v201802/network_service/get_all_networks.py b/examples/ad_manager/v201802/network_service/get_all_networks.py similarity index 90% rename from examples/dfp/v201802/network_service/get_all_networks.py rename to examples/ad_manager/v201802/network_service/get_all_networks.py index df2354a6..cefa51da 100755 --- a/examples/dfp/v201802/network_service/get_all_networks.py +++ b/examples/ad_manager/v201802/network_service/get_all_networks.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -36,5 +36,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/network_service/get_current_network.py b/examples/ad_manager/v201802/network_service/get_current_network.py similarity index 89% rename from examples/dfp/v201802/network_service/get_current_network.py rename to examples/ad_manager/v201802/network_service/get_current_network.py index 58f87509..75497a1d 100755 --- a/examples/dfp/v201802/network_service/get_current_network.py +++ b/examples/ad_manager/v201802/network_service/get_current_network.py @@ -18,7 +18,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -33,5 +33,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/network_service/make_test_network.py b/examples/ad_manager/v201802/network_service/make_test_network.py similarity index 68% rename from examples/dfp/v201802/network_service/make_test_network.py rename to examples/ad_manager/v201802/network_service/make_test_network.py index b3e938fb..2bcf7f2b 100755 --- a/examples/dfp/v201802/network_service/make_test_network.py +++ b/examples/ad_manager/v201802/network_service/make_test_network.py @@ -16,11 +16,12 @@ """This example creates a test network. -You do not need to have a DFP account to run this example, but you do need to -have a Google account (created at http://www.google.com/accounts/newaccount -if you currently don't have one) that is not associated with any other DFP test -networks. Once this network is created, you can supply the network code in your -settings to make calls to other services. +You do not need to have an Ad Manager account to run this example, but you do +need to have a Google account (created at +http://www.google.com/accounts/newaccount if you currently don't have one) that +is not associated with any other Ad Manager test networks. Once this network is +created, you can supply the network code in your settings to make calls to +other services. Alternatively, if you do not wish to run this example, you can create a test network at: @@ -29,7 +30,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -42,10 +43,11 @@ def main(client): # Display results. print ('Test network with network code "%s" and display name "%s" ' 'created.' % (network['networkCode'], network['displayName'])) - print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s' + print ('You may now sign in at ' + 'http://www.google.com/admanager/main?networkCode=%s' % network['networkCode']) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/order_service/__init__.py b/examples/ad_manager/v201802/order_service/__init__.py similarity index 100% rename from examples/dfp/v201711/order_service/__init__.py rename to examples/ad_manager/v201802/order_service/__init__.py diff --git a/examples/dfp/v201802/order_service/approve_orders.py b/examples/ad_manager/v201802/order_service/approve_orders.py similarity index 92% rename from examples/dfp/v201802/order_service/approve_orders.py rename to examples/ad_manager/v201802/order_service/approve_orders.py index 92b81b91..a65b3123 100755 --- a/examples/dfp/v201802/order_service/approve_orders.py +++ b/examples/ad_manager/v201802/order_service/approve_orders.py @@ -23,7 +23,7 @@ import datetime # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -32,7 +32,7 @@ def main(client): # Create a filter statement. today = datetime.date.today() - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) @@ -63,5 +63,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/order_service/create_orders.py b/examples/ad_manager/v201802/order_service/create_orders.py similarity index 90% rename from examples/dfp/v201802/order_service/create_orders.py rename to examples/ad_manager/v201802/order_service/create_orders.py index 7fe46aae..b146b6ce 100755 --- a/examples/dfp/v201802/order_service/create_orders.py +++ b/examples/ad_manager/v201802/order_service/create_orders.py @@ -23,7 +23,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE' @@ -55,5 +55,5 @@ def main(client, company_id, salesperson_id, trafficker_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) diff --git a/examples/dfp/v201802/order_service/get_all_orders.py b/examples/ad_manager/v201802/order_service/get_all_orders.py similarity index 90% rename from examples/dfp/v201802/order_service/get_all_orders.py rename to examples/ad_manager/v201802/order_service/get_all_orders.py index 13f2a568..24a71b7a 100755 --- a/examples/dfp/v201802/order_service/get_all_orders.py +++ b/examples/ad_manager/v201802/order_service/get_all_orders.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): order_service = client.GetService('OrderService', version='v201802') # Create a statement to select orders. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201802/order_service/get_orders_starting_soon.py similarity index 92% rename from examples/dfp/v201802/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v201802/order_service/get_orders_starting_soon.py index 376b4214..ea98550a 100755 --- a/examples/dfp/v201802/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201802/order_service/get_orders_starting_soon.py @@ -20,7 +20,7 @@ from datetime import datetime from datetime import timedelta -from googleads import dfp +from googleads import ad_manager import pytz @@ -31,7 +31,7 @@ def main(client): soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/order_service/update_orders.py b/examples/ad_manager/v201802/order_service/update_orders.py similarity index 92% rename from examples/dfp/v201802/order_service/update_orders.py rename to examples/ad_manager/v201802/order_service/update_orders.py index aadfd1dd..d66a05e3 100755 --- a/examples/dfp/v201802/order_service/update_orders.py +++ b/examples/ad_manager/v201802/order_service/update_orders.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to select a single order by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :orderId') .WithBindVariable('orderId', long(order_id))) @@ -66,6 +66,6 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201802/package_service/create_packages.py b/examples/ad_manager/v201802/package_service/create_packages.py similarity index 93% rename from examples/dfp/v201802/package_service/create_packages.py rename to examples/ad_manager/v201802/package_service/create_packages.py index e3103d0a..ad27f86d 100755 --- a/examples/dfp/v201802/package_service/create_packages.py +++ b/examples/ad_manager/v201802/package_service/create_packages.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the ID of the product package to create the package from. PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -57,5 +57,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201802/package_service/create_proposal_line_items_from_packages.py similarity index 92% rename from examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py rename to examples/ad_manager/v201802/package_service/create_proposal_line_items_from_packages.py index a59ae877..562b65b1 100755 --- a/examples/dfp/v201802/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201802/package_service/create_proposal_line_items_from_packages.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' @@ -31,7 +31,7 @@ def main(client): package_service = client.GetService('PackageService', version='v201802') # Create a statement to select the single package. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -64,5 +64,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/package_service/get_all_packages.py b/examples/ad_manager/v201802/package_service/get_all_packages.py similarity index 90% rename from examples/dfp/v201802/package_service/get_all_packages.py rename to examples/ad_manager/v201802/package_service/get_all_packages.py index d8598da6..fdc7590d 100755 --- a/examples/dfp/v201802/package_service/get_all_packages.py +++ b/examples/ad_manager/v201802/package_service/get_all_packages.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): pkg_service = client.GetService('PackageService', version='v201802') # Create a statement to select packages. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/package_service/get_in_progress_packages.py b/examples/ad_manager/v201802/package_service/get_in_progress_packages.py similarity index 90% rename from examples/dfp/v201802/package_service/get_in_progress_packages.py rename to examples/ad_manager/v201802/package_service/get_in_progress_packages.py index 5adbd144..e2dfe4c1 100755 --- a/examples/dfp/v201802/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201802/package_service/get_in_progress_packages.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. pkg_service = client.GetService('PackageService', version='v201802') # Create a statement to select packages. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'IN_PROGRESS')) @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/placement_service/create_placements.py b/examples/ad_manager/v201802/placement_service/create_placements.py similarity index 95% rename from examples/dfp/v201802/placement_service/create_placements.py rename to examples/ad_manager/v201802/placement_service/create_placements.py index 4d3a2c9c..ffd3e841 100755 --- a/examples/dfp/v201802/placement_service/create_placements.py +++ b/examples/ad_manager/v201802/placement_service/create_placements.py @@ -23,7 +23,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() while True: response = inventory_service.getAdUnitsByStatement( @@ -104,5 +104,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/placement_service/deactivate_placements.py b/examples/ad_manager/v201802/placement_service/deactivate_placements.py similarity index 91% rename from examples/dfp/v201802/placement_service/deactivate_placements.py rename to examples/ad_manager/v201802/placement_service/deactivate_placements.py index cd9b2536..8105c398 100755 --- a/examples/dfp/v201802/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201802/placement_service/deactivate_placements.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' @@ -31,7 +31,7 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :placementId') .WithBindVariable('placementId', long(placement_id)) .Limit(1)) @@ -58,5 +58,5 @@ def main(client, placement_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PLACEMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/dfp/v201802/placement_service/get_active_placements.py b/examples/ad_manager/v201802/placement_service/get_active_placements.py similarity index 90% rename from examples/dfp/v201802/placement_service/get_active_placements.py rename to examples/ad_manager/v201802/placement_service/get_active_placements.py index 296781aa..ecbdef96 100755 --- a/examples/dfp/v201802/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201802/placement_service/get_active_placements.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. placement_service = client.GetService('PlacementService', version='v201802') # Create a statement to select placements. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/placement_service/get_all_placements.py b/examples/ad_manager/v201802/placement_service/get_all_placements.py similarity index 90% rename from examples/dfp/v201802/placement_service/get_all_placements.py rename to examples/ad_manager/v201802/placement_service/get_all_placements.py index 10feefbe..ed176304 100755 --- a/examples/dfp/v201802/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201802/placement_service/get_all_placements.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): placement_service = client.GetService('PlacementService', version='v201802') # Create a statement to select placements. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/placement_service/update_placements.py b/examples/ad_manager/v201802/placement_service/update_placements.py similarity index 90% rename from examples/dfp/v201802/placement_service/update_placements.py rename to examples/ad_manager/v201802/placement_service/update_placements.py index e629c072..b4c9249e 100755 --- a/examples/dfp/v201802/placement_service/update_placements.py +++ b/examples/ad_manager/v201802/placement_service/update_placements.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' @@ -31,7 +31,7 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -54,5 +54,5 @@ def main(client, placement_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PLACEMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/dfp/v201711/premium_rate_service/__init__.py b/examples/ad_manager/v201802/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201711/premium_rate_service/__init__.py rename to examples/ad_manager/v201802/premium_rate_service/__init__.py diff --git a/examples/dfp/v201802/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201802/premium_rate_service/create_premium_rates.py similarity index 92% rename from examples/dfp/v201802/premium_rate_service/create_premium_rates.py rename to examples/ad_manager/v201802/premium_rate_service/create_premium_rates.py index d9398c0e..0dfc45b5 100755 --- a/examples/dfp/v201802/premium_rate_service/create_premium_rates.py +++ b/examples/ad_manager/v201802/premium_rate_service/create_premium_rates.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -75,10 +75,10 @@ def main(client, rate_card_id): for premium_rate in premium_rates: print ('A premium rate for "%s" was added to the rate card with ID' ' of "%s".\n' - % (dfp.DfpClassType(premium_rate['premiumFeature']), + % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), premium_rate['id'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201802/premium_rate_service/get_all_premium_rates.py similarity index 81% rename from examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py rename to examples/ad_manager/v201802/premium_rate_service/get_all_premium_rates.py index 277b1ef7..fb9ab03a 100755 --- a/examples/dfp/v201802/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201802/premium_rate_service/get_all_premium_rates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'PremiumRateService', version='v201802') # Create a statement to select premium rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. @@ -37,9 +37,10 @@ def main(client): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'id "%d" was found.\n' % (premium_rate['id'], - dfp.DfpClassType(premium_rate), - premium_rate['rateCardId'])) + 'id "%d" was found.\n' % ( + premium_rate['id'], + ad_manager.AdManagerClassType(premium_rate), + premium_rate['rateCardId'])) statement.offset += statement.limit else: break @@ -49,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201802/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 91% rename from examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/ad_manager/v201802/premium_rate_service/get_premium_rates_for_rate_card.py index 88c7b942..30cb3ee4 100755 --- a/examples/dfp/v201802/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201802/premium_rate_service/get_premium_rates_for_rate_card.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -27,7 +27,7 @@ def main(client, rate_card_id): premium_rate_service = client.GetService( 'PremiumRateService', version='v201802') # Create a statement to select premium rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) @@ -52,5 +52,5 @@ def main(client, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201802/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201802/premium_rate_service/update_premium_rates.py similarity index 93% rename from examples/dfp/v201802/premium_rate_service/update_premium_rates.py rename to examples/ad_manager/v201802/premium_rate_service/update_premium_rates.py index 48d70196..50665428 100755 --- a/examples/dfp/v201802/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201802/premium_rate_service/update_premium_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' @@ -33,7 +33,7 @@ def main(client, premium_rate_id): version='v201802') # Create statement object to select a single proposal by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(premium_rate_id)) @@ -83,5 +83,5 @@ def main(client, premium_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PREMIUM_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PREMIUM_RATE_ID) diff --git a/examples/dfp/v201802/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201802/product_package_item_service/create_product_package_item.py similarity index 94% rename from examples/dfp/v201802/product_package_item_service/create_product_package_item.py rename to examples/ad_manager/v201802/product_package_item_service/create_product_package_item.py index e1647699..0264d6d1 100755 --- a/examples/dfp/v201802/product_package_item_service/create_product_package_item.py +++ b/examples/ad_manager/v201802/product_package_item_service/create_product_package_item.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the product package to add product package items to. PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -58,5 +58,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201802/product_package_item_service/get_all_product_package_items.py similarity index 91% rename from examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py rename to examples/ad_manager/v201802/product_package_item_service/get_all_product_package_items.py index 23105a5f..a9c920f3 100755 --- a/examples/dfp/v201802/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201802/product_package_item_service/get_all_product_package_items.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ProductPackageItemService', version='v201802') # Create a statement to select product package items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. @@ -49,5 +49,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201802/product_package_item_service/get_product_package_items_for_product_package.py similarity index 91% rename from examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/ad_manager/v201802/product_package_item_service/get_product_package_items_for_product_package.py index a74a5576..ceeef069 100755 --- a/examples/dfp/v201802/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201802/product_package_item_service/get_product_package_items_for_product_package.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -27,7 +27,7 @@ def main(client, product_package_id): product_package_item_service = client.GetService( 'ProductPackageItemService', version='v201802') # Create a statement to select product package items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('productPackageId = :productPackageId') .WithBindVariable('productPackageId', product_package_id)) @@ -52,5 +52,5 @@ def main(client, product_package_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_PACKAGE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_PACKAGE_ID) diff --git a/examples/dfp/v201802/product_package_service/create_product_packages.py b/examples/ad_manager/v201802/product_package_service/create_product_packages.py similarity index 92% rename from examples/dfp/v201802/product_package_service/create_product_packages.py rename to examples/ad_manager/v201802/product_package_service/create_product_packages.py index 36339471..7b938368 100755 --- a/examples/dfp/v201802/product_package_service/create_product_packages.py +++ b/examples/ad_manager/v201802/product_package_service/create_product_packages.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the ID of the rate card to associate with the product package. RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201802/product_package_service/get_active_product_packages.py similarity index 91% rename from examples/dfp/v201802/product_package_service/get_active_product_packages.py rename to examples/ad_manager/v201802/product_package_service/get_active_product_packages.py index 978a69a6..0cab6baa 100755 --- a/examples/dfp/v201802/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201802/product_package_service/get_active_product_packages.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): product_package_service = client.GetService( 'ProductPackageService', version='v201802') # Create a statement to select product packages. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201802/product_package_service/get_all_product_packages.py similarity index 90% rename from examples/dfp/v201802/product_package_service/get_all_product_packages.py rename to examples/ad_manager/v201802/product_package_service/get_all_product_packages.py index 5f80a5ff..2d95315a 100755 --- a/examples/dfp/v201802/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201802/product_package_service/get_all_product_packages.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ProductPackageService', version='v201802') # Create a statement to select product packages. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_service/__init__.py b/examples/ad_manager/v201802/product_service/__init__.py similarity index 100% rename from examples/dfp/v201711/product_service/__init__.py rename to examples/ad_manager/v201802/product_service/__init__.py diff --git a/examples/dfp/v201802/product_service/get_all_products.py b/examples/ad_manager/v201802/product_service/get_all_products.py similarity index 90% rename from examples/dfp/v201802/product_service/get_all_products.py rename to examples/ad_manager/v201802/product_service/get_all_products.py index d51ecd13..ae3dd122 100755 --- a/examples/dfp/v201802/product_service/get_all_products.py +++ b/examples/ad_manager/v201802/product_service/get_all_products.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): product_service = client.GetService('ProductService', version='v201802') # Create a statement to select products. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_service/get_products_for_product_template.py b/examples/ad_manager/v201802/product_service/get_products_for_product_template.py similarity index 90% rename from examples/dfp/v201802/product_service/get_products_for_product_template.py rename to examples/ad_manager/v201802/product_service/get_products_for_product_template.py index 882c3a04..51329df4 100755 --- a/examples/dfp/v201802/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201802/product_service/get_products_for_product_template.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' @@ -27,7 +27,7 @@ def main(client, product_template_id): product_service = client.GetService('ProductService', version='v201802') # Create a statement to select products. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('productTemplateId = :productTemplateId') .WithBindVariable('productTemplateId', product_template_id)) @@ -49,5 +49,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201802/product_service/update_products.py b/examples/ad_manager/v201802/product_service/update_products.py similarity index 91% rename from examples/dfp/v201802/product_service/update_products.py rename to examples/ad_manager/v201802/product_service/update_products.py index 3f25f4bd..8395aa3f 100755 --- a/examples/dfp/v201802/product_service/update_products.py +++ b/examples/ad_manager/v201802/product_service/update_products.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' @@ -32,7 +32,7 @@ def main(client, product_id): product_service = client.GetService('ProductService', version='v201802') # Create statement object to select a single product by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(product_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, product_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_ID) diff --git a/examples/dfp/v201711/product_template_service/__init__.py b/examples/ad_manager/v201802/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201711/product_template_service/__init__.py rename to examples/ad_manager/v201802/product_template_service/__init__.py diff --git a/examples/dfp/v201802/product_template_service/activate_product_templates.py b/examples/ad_manager/v201802/product_template_service/activate_product_templates.py similarity index 92% rename from examples/dfp/v201802/product_template_service/activate_product_templates.py rename to examples/ad_manager/v201802/product_template_service/activate_product_templates.py index 2454c04e..eee57805 100755 --- a/examples/dfp/v201802/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201802/product_template_service/activate_product_templates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the product template to activate. PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' @@ -34,7 +34,7 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(product_template_id)) .Limit(1)) @@ -70,5 +70,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201802/product_template_service/create_product_templates.py b/examples/ad_manager/v201802/product_template_service/create_product_templates.py similarity index 96% rename from examples/dfp/v201802/product_template_service/create_product_templates.py rename to examples/ad_manager/v201802/product_template_service/create_product_templates.py index d8cbf034..40e77754 100755 --- a/examples/dfp/v201802/product_template_service/create_product_templates.py +++ b/examples/ad_manager/v201802/product_template_service/create_product_templates.py @@ -22,7 +22,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -105,5 +105,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201802/product_template_service/create_programmatic_product_templates.py similarity index 95% rename from examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py rename to examples/ad_manager/v201802/product_template_service/create_programmatic_product_templates.py index 19b4d348..350bf69c 100755 --- a/examples/dfp/v201802/product_template_service/create_programmatic_product_templates.py +++ b/examples/ad_manager/v201802/product_template_service/create_programmatic_product_templates.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -87,5 +87,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201802/product_template_service/get_all_product_templates.py similarity index 90% rename from examples/dfp/v201802/product_template_service/get_all_product_templates.py rename to examples/ad_manager/v201802/product_template_service/get_all_product_templates.py index 2cbb9279..875e7f53 100755 --- a/examples/dfp/v201802/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201802/product_template_service/get_all_product_templates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ProductTemplateService', version='v201802') # Create a statement to select product templates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201802/product_template_service/get_sponsorship_product_templates.py similarity index 91% rename from examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py rename to examples/ad_manager/v201802/product_template_service/get_sponsorship_product_templates.py index 48fcc5df..beb74e34 100755 --- a/examples/dfp/v201802/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201802/product_template_service/get_sponsorship_product_templates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): product_template_service = client.GetService( 'ProductTemplateService', version='v201802') # Create a statement to select product templates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemType = :lineItemType') .WithBindVariable('lineItemType', 'SPONSORSHIP')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_template_service/update_product_templates.py b/examples/ad_manager/v201802/product_template_service/update_product_templates.py similarity index 93% rename from examples/dfp/v201802/product_template_service/update_product_templates.py rename to examples/ad_manager/v201802/product_template_service/update_product_templates.py index c899305b..fee07193 100755 --- a/examples/dfp/v201802/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201802/product_template_service/update_product_templates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' @@ -33,7 +33,7 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201802') # Create a statement to select a single product template by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(product_template_id)) @@ -90,5 +90,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201711/proposal_line_item_service/__init__.py b/examples/ad_manager/v201802/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201711/proposal_line_item_service/__init__.py rename to examples/ad_manager/v201802/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201802/proposal_line_item_service/archive_proposal_line_items.py similarity index 92% rename from examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v201802/proposal_line_item_service/archive_proposal_line_items.py index 48568c1a..30e4dc0b 100755 --- a/examples/dfp/v201802/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201802/proposal_line_item_service/archive_proposal_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the proposal line item to archive. PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' @@ -34,7 +34,7 @@ def main(client, proposal_line_item_id): 'ProposalLineItemService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) @@ -72,5 +72,5 @@ def main(client, proposal_line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 95% rename from examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py index ed61a734..d6d7bb10 100755 --- a/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -22,7 +22,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set the ID of the programmatic proposal that the proposal line item will @@ -99,6 +99,6 @@ def main(client, proposal_id, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 95% rename from examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index e49b1679..ebb54cf0 100755 --- a/examples/dfp/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -22,7 +22,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set proposal that the created proposal line item will belong to. @@ -105,6 +105,6 @@ def main(client, proposal_id, product_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID) diff --git a/examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201802/proposal_line_item_service/create_proposal_line_items.py similarity index 95% rename from examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v201802/proposal_line_item_service/create_proposal_line_items.py index 25106570..1abb2506 100755 --- a/examples/dfp/v201802/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201802/proposal_line_item_service/create_proposal_line_items.py @@ -26,7 +26,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set proposal that the created proposal line item will belong to. @@ -100,6 +100,6 @@ def main(client, proposal_id, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201802/proposal_line_item_service/get_all_proposal_line_items.py similarity index 90% rename from examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v201802/proposal_line_item_service/get_all_proposal_line_items.py index 73442848..a0223ab0 100755 --- a/examples/dfp/v201802/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201802/proposal_line_item_service/get_all_proposal_line_items.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ProposalLineItemService', version='v201802') # Create a statement to select proposal line items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 91% rename from examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 3f63b344..1a1874d8 100755 --- a/examples/dfp/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -27,7 +27,7 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( 'ProposalLineItemService', version='v201802') # Create a statement to select proposal line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) @@ -50,5 +50,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201802/proposal_line_item_service/update_proposal_line_items.py similarity index 92% rename from examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v201802/proposal_line_item_service/update_proposal_line_items.py index 6ca41d6f..333c63c5 100755 --- a/examples/dfp/v201802/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201802/proposal_line_item_service/update_proposal_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the proposal line item to update. PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' @@ -35,7 +35,7 @@ def main(client, proposal_line_item_id): # Create statement to select a proposal line item. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) @@ -68,5 +68,5 @@ def main(client, proposal_line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201711/proposal_service/__init__.py b/examples/ad_manager/v201802/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201711/proposal_service/__init__.py rename to examples/ad_manager/v201802/proposal_service/__init__.py diff --git a/examples/dfp/v201802/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201802/proposal_service/create_programmatic_proposals.py similarity index 91% rename from examples/dfp/v201802/proposal_service/create_programmatic_proposals.py rename to examples/ad_manager/v201802/proposal_service/create_programmatic_proposals.py index b367a445..0ecef57a 100755 --- a/examples/dfp/v201802/proposal_service/create_programmatic_proposals.py +++ b/examples/ad_manager/v201802/proposal_service/create_programmatic_proposals.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -66,6 +66,6 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID, - BUYER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID, BUYER_ID) diff --git a/examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 91% rename from examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/ad_manager/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 9021632a..dcfeae12 100755 --- a/examples/dfp/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/ad_manager/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -57,6 +57,6 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201802/proposal_service/create_proposals.py b/examples/ad_manager/v201802/proposal_service/create_proposals.py similarity index 93% rename from examples/dfp/v201802/proposal_service/create_proposals.py rename to examples/ad_manager/v201802/proposal_service/create_proposals.py index 5cfe3820..89f03352 100755 --- a/examples/dfp/v201802/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201802/proposal_service/create_proposals.py @@ -23,7 +23,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -72,6 +72,6 @@ def main(client, advertiser_id, primary_salesperson_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201802/proposal_service/get_all_proposals.py b/examples/ad_manager/v201802/proposal_service/get_all_proposals.py similarity index 90% rename from examples/dfp/v201802/proposal_service/get_all_proposals.py rename to examples/ad_manager/v201802/proposal_service/get_all_proposals.py index 30eebe62..ae5d62f8 100755 --- a/examples/dfp/v201802/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201802/proposal_service/get_all_proposals.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201802') # Create a statement to select proposals. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201802/proposal_service/get_marketplace_comments.py similarity index 93% rename from examples/dfp/v201802/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v201802/proposal_service/get_marketplace_comments.py index 63e4683b..84699e76 100755 --- a/examples/dfp/v201802/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201802/proposal_service/get_marketplace_comments.py @@ -19,7 +19,7 @@ # Import appropriate modules from the client library. from datetime import datetime -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -52,5 +52,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201802/proposal_service/get_proposals_pending_approval.py similarity index 90% rename from examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py rename to examples/ad_manager/v201802/proposal_service/get_proposals_pending_approval.py index eded3d02..6cca9940 100755 --- a/examples/dfp/v201802/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201802/proposal_service/get_proposals_pending_approval.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. proposal_service = client.GetService('ProposalService', version='v201802') # Create a statement to select proposals. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'PENDING_APPROVAL')) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201802/proposal_service/request_buyers_acceptance.py similarity index 92% rename from examples/dfp/v201802/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v201802/proposal_service/request_buyers_acceptance.py index 428f4c83..3a823d5a 100755 --- a/examples/dfp/v201802/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201802/proposal_service/request_buyers_acceptance.py @@ -19,7 +19,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -29,7 +29,7 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 @@ -63,5 +63,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201802/proposal_service/submit_proposals_for_approval.py similarity index 92% rename from examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py rename to examples/ad_manager/v201802/proposal_service/submit_proposals_for_approval.py index ee79183f..76ff57ed 100755 --- a/examples/dfp/v201802/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201802/proposal_service/submit_proposals_for_approval.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -31,7 +31,7 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 @@ -63,5 +63,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201802/proposal_service/update_proposals.py b/examples/ad_manager/v201802/proposal_service/update_proposals.py similarity index 92% rename from examples/dfp/v201802/proposal_service/update_proposals.py rename to examples/ad_manager/v201802/proposal_service/update_proposals.py index 540cff7c..fff7a52c 100755 --- a/examples/dfp/v201802/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201802/proposal_service/update_proposals.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -32,7 +32,7 @@ def main(client, proposal_id): # Create statement object to select a single proposal by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', long(proposal_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201711/publisher_query_language_service/__init__.py b/examples/ad_manager/v201802/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201711/publisher_query_language_service/__init__.py rename to examples/ad_manager/v201802/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201802/publisher_query_language_service/fetch_match_tables.py similarity index 93% rename from examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v201802/publisher_query_language_service/fetch_match_tables.py index 49c456d6..561db2db 100755 --- a/examples/dfp/v201802/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201802/publisher_query_language_service/fetch_match_tables.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201802/publisher_query_language_service/get_all_browsers.py similarity index 93% rename from examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v201802/publisher_query_language_service/get_all_browsers.py index e3c0ac25..bde91923 100755 --- a/examples/dfp/v201802/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201802/publisher_query_language_service/get_all_browsers.py @@ -27,7 +27,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201802/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 92% rename from examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v201802/publisher_query_language_service/get_all_programmatic_buyers.py index 51243ca7..68a344bb 100755 --- a/examples/dfp/v201802/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201802/publisher_query_language_service/get_all_programmatic_buyers.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201802/publisher_query_language_service/get_geo_targets.py similarity index 92% rename from examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v201802/publisher_query_language_service/get_geo_targets.py index 80183382..efb91f9a 100755 --- a/examples/dfp/v201802/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201802/publisher_query_language_service/get_geo_targets.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the type of geo target to query for. GEO_TARGET_TYPE = 'City' @@ -49,5 +49,5 @@ def main(client, geo_target_type): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, GEO_TARGET_TYPE) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, GEO_TARGET_TYPE) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201802/publisher_query_language_service/get_line_items_named_like.py similarity index 92% rename from examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v201802/publisher_query_language_service/get_line_items_named_like.py index 0d14cd53..f726ace4 100755 --- a/examples/dfp/v201802/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201802/publisher_query_language_service/get_line_items_named_like.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -44,5 +44,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201802/publisher_query_language_service/get_recent_changes.py similarity index 95% rename from examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v201802/publisher_query_language_service/get_recent_changes.py index 61f13440..926f3b20 100755 --- a/examples/dfp/v201802/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201802/publisher_query_language_service/get_recent_changes.py @@ -25,7 +25,7 @@ from datetime import timedelta # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') @@ -105,7 +105,7 @@ def ConvertValueForCsv(pql_value): return ','.join(['"%s"' % str(ConvertValueForCsv(single_field)) for single_field in field]) else: - class_type = dfp.DfpClassType(pql_value) + class_type = ad_manager.AdManagerClassType(pql_value) if class_type == 'TextValue': return field.replace('"', '""').encode('UTF8') @@ -152,5 +152,5 @@ def ConvertDateTimeToOffset(date_time_value): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/rate_card_service/__init__.py b/examples/ad_manager/v201802/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201711/rate_card_service/__init__.py rename to examples/ad_manager/v201802/rate_card_service/__init__.py diff --git a/examples/dfp/v201802/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201802/rate_card_service/create_rate_cards.py similarity index 93% rename from examples/dfp/v201802/rate_card_service/create_rate_cards.py rename to examples/ad_manager/v201802/rate_card_service/create_rate_cards.py index bbb198d0..20e4d06f 100755 --- a/examples/dfp/v201802/rate_card_service/create_rate_cards.py +++ b/examples/ad_manager/v201802/rate_card_service/create_rate_cards.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the IDs of the teams this rate card should be visible to. TEAM_IDS = ['INSERT_TEAM_ID_HERE'] @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201802/rate_card_service/get_all_rate_cards.py similarity index 90% rename from examples/dfp/v201802/rate_card_service/get_all_rate_cards.py rename to examples/ad_manager/v201802/rate_card_service/get_all_rate_cards.py index 4857906d..1a71ec6e 100755 --- a/examples/dfp/v201802/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201802/rate_card_service/get_all_rate_cards.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): rate_card_service = client.GetService('RateCardService', version='v201802') # Create a statement to select rate cards. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201802/rate_card_service/get_marketplace_rate_cards.py similarity index 91% rename from examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py rename to examples/ad_manager/v201802/rate_card_service/get_marketplace_rate_cards.py index bd37d570..a77f669a 100755 --- a/examples/dfp/v201802/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201802/rate_card_service/get_marketplace_rate_cards.py @@ -18,14 +18,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. rate_card_service = client.GetService('RateCardService', version='v201802') # Create a statement to select rate cards. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('forMarketplace = :forMarketplace') .WithBindVariable('forMarketplace', True)) @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 94% rename from examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/ad_manager/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index dac50e46..e8d0db92 100755 --- a/examples/dfp/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report to query. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -33,7 +33,7 @@ def main(client): 'ReconciliationLineItemReportService', version='v201802')) # Create a statement to select reconciliation line item reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('reconciliationReportId = :reconciliationReportId AND ' 'lineItemId != :lineItemId')) .OrderBy('lineItemId', ascending=True) @@ -71,5 +71,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 91% rename from examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/ad_manager/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index bdcd877e..3f839882 100755 --- a/examples/dfp/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation line item report to update. RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' @@ -33,7 +33,7 @@ def main(client): 'ReconciliationLineItemReportService', version='v201802')) # Create a statement to select a reconciliation line item report. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :lineItemReportId') .OrderBy('id', ascending=True) .Limit(1) @@ -47,7 +47,7 @@ def main(client): line_item_report = page['results'][0] # Set and use a manual volume for billing. This example splits the difference - # between DFP and the third party volume. + # between Ad Manager and the third party volume. line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + line_item_report['thirdPartyVolume']) / 2 line_item_report['reconciliationSource'] = 'MANUAL' @@ -63,5 +63,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 91% rename from examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/ad_manager/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 95c34b0d..10da1047 100755 --- a/examples/dfp/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -27,7 +27,7 @@ def main(client, reconciliation_report_id): reconciliation_order_report_service = client.GetService( 'ReconciliationOrderReportService', version='v201802') # Create a statement to select reconciliation order reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('reconciliationReportId = :reconciliationReportId') .WithBindVariable('reconciliationReportId', reconciliation_report_id)) @@ -54,5 +54,5 @@ def main(client, reconciliation_report_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 93% rename from examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/ad_manager/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 07b8c4f4..60272108 100755 --- a/examples/dfp/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation order report to submit. RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' @@ -33,7 +33,7 @@ def main(client): 'ReconciliationOrderReportService', version='v201802')) # Create a statement to select reconciliation order reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -67,5 +67,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 89% rename from examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/ad_manager/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 1557145b..408c82fd 100755 --- a/examples/dfp/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Gets a reconciliation report's rows for line items that served through DFP. +"""Gets a reconciliation report's rows for line items that Ad Manager served. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -30,7 +30,7 @@ def main(client, reconciliation_report_id): 'ReconciliationReportRowService', version='v201802') # Create a statement to select reconciliation report rows. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) @@ -60,5 +60,5 @@ def main(client, reconciliation_report_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 94% rename from examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/ad_manager/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py index fa7f2cc1..b4c6e083 100755 --- a/examples/dfp/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' @@ -36,7 +36,7 @@ def main(client): 'ReconciliationReportRowService', version='v201802')) # Create a statement to select reconciliation report rows. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('id = :reconciliationReportRowId AND ' 'reconciliationReportId = :reconciliationReportId')) .OrderBy('id', ascending=True) @@ -71,5 +71,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201802/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 91% rename from examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/ad_manager/v201802/reconciliation_report_service/get_all_reconciliation_reports.py index c42b0dd3..d4073a99 100755 --- a/examples/dfp/v201802/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201802/reconciliation_report_service/get_all_reconciliation_reports.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ReconciliationReportService', version='v201802') # Create a statement to select reconciliation reports. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. @@ -52,5 +52,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 92% rename from examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/ad_manager/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 938ba4fa..57f0f2d0 100755 --- a/examples/dfp/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -20,7 +20,7 @@ from datetime import date from datetime import timedelta -from googleads import dfp +from googleads import ad_manager def main(client): @@ -32,7 +32,7 @@ def main(client): last_month = first_of_the_month - timedelta(days=1) # Create a statement to select reconciliation reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('startDate = :startDate') .WithBindVariable('startDate', last_month)) @@ -59,5 +59,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/report_service/__init__.py b/examples/ad_manager/v201802/report_service/__init__.py similarity index 100% rename from examples/dfp/v201711/report_service/__init__.py rename to examples/ad_manager/v201802/report_service/__init__.py diff --git a/examples/dfp/v201802/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201802/report_service/run_ad_exchange_report.py similarity index 89% rename from examples/dfp/v201802/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v201802/report_service/run_ad_exchange_report.py index f6ebfee5..2d1c1d22 100755 --- a/examples/dfp/v201802/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201802/report_service/run_ad_exchange_report.py @@ -14,12 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report on Ad Exchange data via the DFP API.""" +"""Runs a report on Ad Exchange data via the Ad Manager API.""" import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors @@ -42,7 +42,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/report_service/run_delivery_report.py b/examples/ad_manager/v201802/report_service/run_delivery_report.py similarity index 90% rename from examples/dfp/v201802/report_service/run_delivery_report.py rename to examples/ad_manager/v201802/report_service/run_delivery_report.py index 48fa9bcf..a6c6b21b 100755 --- a/examples/dfp/v201802/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201802/report_service/run_delivery_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report similar to the "Orders report" on the DFP website. +"""Runs a report similar to the "Orders report" on the Ad Manager website. Includes additional attributes and can filter to include just one order. """ @@ -24,7 +24,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('ORDER_ID = :id') .WithBindVariable('id', long(order_id)) .Limit(None) # No limit or offset for reports @@ -64,7 +64,7 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -84,5 +84,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201802/report_service/run_inventory_report.py b/examples/ad_manager/v201802/report_service/run_inventory_report.py similarity index 92% rename from examples/dfp/v201802/report_service/run_inventory_report.py rename to examples/ad_manager/v201802/report_service/run_inventory_report.py index be8e2835..0d7af87f 100755 --- a/examples/dfp/v201802/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201802/report_service/run_inventory_report.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors @@ -34,7 +34,7 @@ def main(client): network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) .Limit(None) # No limit or offset for reports @@ -58,7 +58,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -78,5 +78,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/report_service/run_reach_report.py b/examples/ad_manager/v201802/report_service/run_reach_report.py similarity index 91% rename from examples/dfp/v201802/report_service/run_reach_report.py rename to examples/ad_manager/v201802/report_service/run_reach_report.py index 1f83a5ec..7682e63d 100755 --- a/examples/dfp/v201802/report_service/run_reach_report.py +++ b/examples/ad_manager/v201802/report_service/run_reach_report.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors @@ -39,7 +39,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -60,5 +60,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201802/report_service/run_report_and_create_match_table.py similarity index 94% rename from examples/dfp/v201802/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v201802/report_service/run_report_and_create_match_table.py index def767a9..36eecb4b 100755 --- a/examples/dfp/v201802/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201802/report_service/run_report_and_create_match_table.py @@ -26,7 +26,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors try: @@ -59,7 +59,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e with tempfile.NamedTemporaryFile( @@ -84,5 +84,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201802/report_service/run_report_with_custom_fields.py similarity index 93% rename from examples/dfp/v201802/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v201802/report_service/run_report_with_custom_fields.py index efdc3372..cbfb971b 100755 --- a/examples/dfp/v201802/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201802/report_service/run_report_with_custom_fields.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors # Set the ID of the order to get line items from. @@ -33,7 +33,7 @@ def main(client, order_id): report_downloader = client.GetDataDownloader(version='v201802') # Filter for line items of a given order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('orderId = :orderId') .WithBindVariable('orderId', long(order_id))) @@ -73,7 +73,7 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -93,5 +93,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201802/report_service/run_sales_report.py b/examples/ad_manager/v201802/report_service/run_sales_report.py similarity index 91% rename from examples/dfp/v201802/report_service/run_sales_report.py rename to examples/ad_manager/v201802/report_service/run_sales_report.py index d8411c93..78706ae1 100755 --- a/examples/dfp/v201802/report_service/run_sales_report.py +++ b/examples/ad_manager/v201802/report_service/run_sales_report.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors @@ -40,7 +40,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -60,5 +60,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/report_service/run_saved_query.py b/examples/ad_manager/v201802/report_service/run_saved_query.py similarity index 91% rename from examples/dfp/v201802/report_service/run_saved_query.py rename to examples/ad_manager/v201802/report_service/run_saved_query.py index a0fccfae..ac188a02 100755 --- a/examples/dfp/v201802/report_service/run_saved_query.py +++ b/examples/ad_manager/v201802/report_service/run_saved_query.py @@ -20,7 +20,7 @@ # Import appropriate modules from the client library. import tempfile -from googleads import dfp +from googleads import ad_manager from googleads import errors SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' @@ -34,7 +34,7 @@ def main(client, saved_query_id): report_downloader = client.GetDataDownloader(version='v201802') # Create statement object to filter for an order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(saved_query_id)) .Limit(1)) @@ -54,7 +54,7 @@ def main(client, saved_query_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -76,5 +76,5 @@ def main(client, saved_query_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, SAVED_QUERY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, SAVED_QUERY_ID) diff --git a/examples/dfp/v201711/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201802/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201711/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v201802/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 90% rename from examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 656b4855..f7b41d3a 100755 --- a/examples/dfp/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -16,12 +16,12 @@ """This code example approves all suggested ad units with 50 or more requests. -This feature is only available to DFP premium solution networks. +This feature is only available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager THRESHOLD_NUMBER_OF_REQUESTS = '50' @@ -32,7 +32,7 @@ def main(client): 'SuggestedAdUnitService', version='v201802') # Create a filter statement. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 @@ -65,6 +65,6 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 91% rename from examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py index 3cabf8b5..66c59755 100755 --- a/examples/dfp/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'SuggestedAdUnitService', version='v201802') # Create a statement to select suggested ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 91% rename from examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index c8d380a2..31defa2d 100755 --- a/examples/dfp/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE' @@ -27,7 +27,7 @@ def main(client, num_requests): suggested_ad_unit_service = client.GetService( 'SuggestedAdUnitService', version='v201802') # Create a statement to select suggested ad units. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', long(num_requests))) @@ -51,5 +51,5 @@ def main(client, num_requests): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, NUM_REQUESTS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, NUM_REQUESTS) diff --git a/examples/dfp/v201711/team_service/__init__.py b/examples/ad_manager/v201802/team_service/__init__.py similarity index 100% rename from examples/dfp/v201711/team_service/__init__.py rename to examples/ad_manager/v201802/team_service/__init__.py diff --git a/examples/dfp/v201802/team_service/create_teams.py b/examples/ad_manager/v201802/team_service/create_teams.py similarity index 92% rename from examples/dfp/v201802/team_service/create_teams.py rename to examples/ad_manager/v201802/team_service/create_teams.py index 5265d8d0..073abd55 100755 --- a/examples/dfp/v201802/team_service/create_teams.py +++ b/examples/ad_manager/v201802/team_service/create_teams.py @@ -28,7 +28,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/team_service/get_all_teams.py b/examples/ad_manager/v201802/team_service/get_all_teams.py similarity index 90% rename from examples/dfp/v201802/team_service/get_all_teams.py rename to examples/ad_manager/v201802/team_service/get_all_teams.py index 3c012fc5..1355d0d7 100755 --- a/examples/dfp/v201802/team_service/get_all_teams.py +++ b/examples/ad_manager/v201802/team_service/get_all_teams.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): team_service = client.GetService('TeamService', version='v201802') # Create a statement to select teams. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/team_service/update_teams.py b/examples/ad_manager/v201802/team_service/update_teams.py similarity index 92% rename from examples/dfp/v201802/team_service/update_teams.py rename to examples/ad_manager/v201802/team_service/update_teams.py index 6527f02a..3390ef28 100755 --- a/examples/dfp/v201802/team_service/update_teams.py +++ b/examples/ad_manager/v201802/team_service/update_teams.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager TEAM_ID = 'INSERT_TEAM_ID_HERE' @@ -37,7 +37,7 @@ def main(client, team_id): team_service = client.GetService('TeamService', version='v201802') # Create a filter statement to select a single team by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :teamId') .WithBindVariable('teamId', long(team_id))) @@ -64,5 +64,5 @@ def main(client, team_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TEAM_ID) diff --git a/examples/dfp/v201711/user_service/__init__.py b/examples/ad_manager/v201802/user_service/__init__.py similarity index 100% rename from examples/dfp/v201711/user_service/__init__.py rename to examples/ad_manager/v201802/user_service/__init__.py diff --git a/examples/dfp/v201802/user_service/create_users.py b/examples/ad_manager/v201802/user_service/create_users.py similarity index 90% rename from examples/dfp/v201802/user_service/create_users.py rename to examples/ad_manager/v201802/user_service/create_users.py index 021bb596..2d44649d 100755 --- a/examples/dfp/v201802/user_service/create_users.py +++ b/examples/ad_manager/v201802/user_service/create_users.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' NEW_USER_NAME = 'INSERT_NAME_HERE' @@ -53,5 +53,5 @@ def main(client, email, name): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) diff --git a/examples/dfp/v201802/user_service/deactivate_users.py b/examples/ad_manager/v201802/user_service/deactivate_users.py similarity index 91% rename from examples/dfp/v201802/user_service/deactivate_users.py rename to examples/ad_manager/v201802/user_service/deactivate_users.py index 771357d1..38c0eef9 100755 --- a/examples/dfp/v201802/user_service/deactivate_users.py +++ b/examples/ad_manager/v201802/user_service/deactivate_users.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE' @@ -33,7 +33,7 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :userId') .WithBindVariable('userId', long(user_id))) @@ -61,5 +61,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201805/user_service/get_all_roles.py b/examples/ad_manager/v201802/user_service/get_all_roles.py similarity index 90% rename from examples/dfp/v201805/user_service/get_all_roles.py rename to examples/ad_manager/v201802/user_service/get_all_roles.py index bb2bec62..442d35bd 100755 --- a/examples/dfp/v201805/user_service/get_all_roles.py +++ b/examples/ad_manager/v201802/user_service/get_all_roles.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -36,5 +36,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/user_service/get_all_users.py b/examples/ad_manager/v201802/user_service/get_all_users.py similarity index 90% rename from examples/dfp/v201802/user_service/get_all_users.py rename to examples/ad_manager/v201802/user_service/get_all_users.py index 5e043c1f..e319ae54 100755 --- a/examples/dfp/v201802/user_service/get_all_users.py +++ b/examples/ad_manager/v201802/user_service/get_all_users.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): user_service = client.GetService('UserService', version='v201802') # Create a statement to select users. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/user_service/get_current_user.py b/examples/ad_manager/v201802/user_service/get_current_user.py similarity index 90% rename from examples/dfp/v201802/user_service/get_current_user.py rename to examples/ad_manager/v201802/user_service/get_current_user.py index d04dcb56..534ccc07 100755 --- a/examples/dfp/v201802/user_service/get_current_user.py +++ b/examples/ad_manager/v201802/user_service/get_current_user.py @@ -17,7 +17,7 @@ """This example gets the current user.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -35,5 +35,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/user_service/get_user_by_email_address.py b/examples/ad_manager/v201802/user_service/get_user_by_email_address.py similarity index 90% rename from examples/dfp/v201802/user_service/get_user_by_email_address.py rename to examples/ad_manager/v201802/user_service/get_user_by_email_address.py index ddb8f015..9bce82d0 100755 --- a/examples/dfp/v201802/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201802/user_service/get_user_by_email_address.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' @@ -26,7 +26,7 @@ def main(client, email_address): # Initialize appropriate service. user_service = client.GetService('UserService', version='v201802') # Create a statement to select users. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('email = :email') .WithBindVariable('email', email_address)) @@ -48,5 +48,5 @@ def main(client, email_address): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, EMAIL_ADDRESS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, EMAIL_ADDRESS) diff --git a/examples/dfp/v201802/user_service/update_users.py b/examples/ad_manager/v201802/user_service/update_users.py similarity index 90% rename from examples/dfp/v201802/user_service/update_users.py rename to examples/ad_manager/v201802/user_service/update_users.py index 395bbf51..807b6fbe 100755 --- a/examples/dfp/v201802/user_service/update_users.py +++ b/examples/ad_manager/v201802/user_service/update_users.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' @@ -31,7 +31,7 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201802') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :userId') .WithBindVariable('userId', long(user_id))) @@ -54,5 +54,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201711/user_team_association_service/__init__.py b/examples/ad_manager/v201802/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201711/user_team_association_service/__init__.py rename to examples/ad_manager/v201802/user_team_association_service/__init__.py diff --git a/examples/dfp/v201802/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201802/user_team_association_service/create_user_team_associations.py similarity index 93% rename from examples/dfp/v201802/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v201802/user_team_association_service/create_user_team_associations.py index 6f55df77..576dddad 100755 --- a/examples/dfp/v201802/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201802/user_team_association_service/create_user_team_associations.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager TEAM_ID = 'INSERT_TEAM_ID_HERE' USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE'] @@ -63,5 +63,5 @@ def main(client, team_id, user_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID, USER_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TEAM_ID, USER_IDS) diff --git a/examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201802/user_team_association_service/delete_user_team_associations.py similarity index 93% rename from examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v201802/user_team_association_service/delete_user_team_associations.py index 85d04bc8..0e497cce 100755 --- a/examples/dfp/v201802/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201802/user_team_association_service/delete_user_team_associations.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_HERE' @@ -38,7 +38,7 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201802') # Create filter text to select user team associations by the user ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -73,5 +73,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201802/user_team_association_service/get_all_user_team_associations.py similarity index 91% rename from examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v201802/user_team_association_service/get_all_user_team_associations.py index f867ce9f..07e8c76e 100755 --- a/examples/dfp/v201802/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201802/user_team_association_service/get_all_user_team_associations.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'UserTeamAssociationService', version='v201802') # Create a statement to select user team associations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201802/user_team_association_service/get_user_team_associations_for_user.py similarity index 91% rename from examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v201802/user_team_association_service/get_user_team_associations_for_user.py index 4f303dfb..79809281 100755 --- a/examples/dfp/v201802/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201802/user_team_association_service/get_user_team_associations_for_user.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_HERE' @@ -27,7 +27,7 @@ def main(client, user_id): user_team_association_service = client.GetService( 'UserTeamAssociationService', version='v201802') # Create a statement to select user team associations. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -51,5 +51,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201802/user_team_association_service/update_user_team_associations.py similarity index 93% rename from examples/dfp/v201802/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v201802/user_team_association_service/update_user_team_associations.py index e6e92014..aa212b21 100755 --- a/examples/dfp/v201802/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201802/user_team_association_service/update_user_team_associations.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' @@ -40,7 +40,7 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201802') # Create filter text to select user team associations by the user ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -74,5 +74,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201711/workflow_request_service/__init__.py b/examples/ad_manager/v201802/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201711/workflow_request_service/__init__.py rename to examples/ad_manager/v201802/workflow_request_service/__init__.py diff --git a/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201802/workflow_request_service/approve_workflow_approval_requests.py similarity index 93% rename from examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py rename to examples/ad_manager/v201802/workflow_request_service/approve_workflow_approval_requests.py index a5d0d50f..2253dd99 100755 --- a/examples/dfp/v201802/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201802/workflow_request_service/approve_workflow_approval_requests.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -34,7 +34,7 @@ def main(client, proposal_id): version='v201802') # Create a filter statement. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) @@ -71,5 +71,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201802/workflow_request_service/get_workflow_approval_requests.py similarity index 92% rename from examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py rename to examples/ad_manager/v201802/workflow_request_service/get_workflow_approval_requests.py index 08483be0..38dd03a9 100755 --- a/examples/dfp/v201802/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201802/workflow_request_service/get_workflow_approval_requests.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -28,7 +28,7 @@ def main(client): workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201802') # Create a statement to select workflow requests. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201802/workflow_request_service/get_workflow_external_condition_requests.py similarity index 92% rename from examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/ad_manager/v201802/workflow_request_service/get_workflow_external_condition_requests.py index 2a4ea889..645d7efb 100755 --- a/examples/dfp/v201802/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201802/workflow_request_service/get_workflow_external_condition_requests.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -28,7 +28,7 @@ def main(client): workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201802') # Create a statement to select workflow requests. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 94% rename from examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/ad_manager/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py index 7d66ba4a..14deca1d 100755 --- a/examples/dfp/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -34,7 +34,7 @@ def main(client, proposal_id): version='v201802') # Create a filter statement. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) @@ -74,5 +74,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201802/activity_group_service/__init__.py b/examples/ad_manager/v201805/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201802/activity_group_service/__init__.py rename to examples/ad_manager/v201805/activity_group_service/__init__.py diff --git a/examples/dfp/v201805/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201805/activity_group_service/create_activity_groups.py similarity index 93% rename from examples/dfp/v201805/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v201805/activity_group_service/create_activity_groups.py index 022cd7c2..c2d3f9c8 100755 --- a/examples/dfp/v201805/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201805/activity_group_service/create_activity_groups.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the advertiser company this activity group is associated with. ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -67,5 +67,5 @@ def main(client, advertiser_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_COMPANY_ID) diff --git a/examples/dfp/v201805/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py similarity index 91% rename from examples/dfp/v201805/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py index 077aa152..a3d900a4 100755 --- a/examples/dfp/v201805/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): activity_group_service = client.GetService( 'ActivityGroupService', version='v201805') # Create a statement to select activity groups. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py similarity index 90% rename from examples/dfp/v201805/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py index 3ce7d043..16c4d419 100755 --- a/examples/dfp/v201805/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ActivityGroupService', version='v201805') # Create a statement to select activity groups. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201805/activity_group_service/update_activity_groups.py similarity index 92% rename from examples/dfp/v201805/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v201805/activity_group_service/update_activity_groups.py index 62fe1f15..84284c18 100755 --- a/examples/dfp/v201805/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201805/activity_group_service/update_activity_groups.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity group and the company to update it with. ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' @@ -40,7 +40,7 @@ def main(client, activity_group_id, advertiser_company_id): version='v201805') # Create statement object to select a single activity groups by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', long(activity_group_id)) .Limit(1)) @@ -66,5 +66,5 @@ def main(client, activity_group_id, advertiser_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) diff --git a/examples/dfp/v201802/activity_service/__init__.py b/examples/ad_manager/v201805/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201802/activity_service/__init__.py rename to examples/ad_manager/v201805/activity_service/__init__.py diff --git a/examples/dfp/v201805/activity_service/create_activities.py b/examples/ad_manager/v201805/activity_service/create_activities.py similarity index 93% rename from examples/dfp/v201805/activity_service/create_activities.py rename to examples/ad_manager/v201805/activity_service/create_activities.py index 8d16515e..b6339d1b 100755 --- a/examples/dfp/v201805/activity_service/create_activities.py +++ b/examples/ad_manager/v201805/activity_service/create_activities.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity group this activity is associated with. ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' @@ -64,5 +64,5 @@ def main(client, activity_group_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_GROUP_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_GROUP_ID) diff --git a/examples/dfp/v201805/activity_service/get_active_activities.py b/examples/ad_manager/v201805/activity_service/get_active_activities.py similarity index 90% rename from examples/dfp/v201805/activity_service/get_active_activities.py rename to examples/ad_manager/v201805/activity_service/get_active_activities.py index dfb753e1..0f30e0dd 100755 --- a/examples/dfp/v201805/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201805/activity_service/get_active_activities.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. activity_service = client.GetService('ActivityService', version='v201805') # Create a statement to select activities. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/activity_service/get_all_activities.py b/examples/ad_manager/v201805/activity_service/get_all_activities.py similarity index 90% rename from examples/dfp/v201805/activity_service/get_all_activities.py rename to examples/ad_manager/v201805/activity_service/get_all_activities.py index 84e91925..deff00c7 100755 --- a/examples/dfp/v201805/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201805/activity_service/get_all_activities.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): activity_service = client.GetService('ActivityService', version='v201805') # Create a statement to select activities. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/activity_service/update_activities.py b/examples/ad_manager/v201805/activity_service/update_activities.py similarity index 92% rename from examples/dfp/v201805/activity_service/update_activities.py rename to examples/ad_manager/v201805/activity_service/update_activities.py index c9344fc7..2f905724 100755 --- a/examples/dfp/v201805/activity_service/update_activities.py +++ b/examples/ad_manager/v201805/activity_service/update_activities.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity to update. ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE' @@ -38,7 +38,7 @@ def main(client, activity_id): activity_service = client.GetService('ActivityService', version='v201805') # Create statement object to select one activity by ID to update. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :activityId') .WithBindVariable('activityId', long(activity_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, activity_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_ID) diff --git a/examples/dfp/v201802/audience_segment_service/__init__.py b/examples/ad_manager/v201805/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201802/audience_segment_service/__init__.py rename to examples/ad_manager/v201805/audience_segment_service/__init__.py diff --git a/examples/dfp/v201805/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/create_audience_segments.py similarity index 94% rename from examples/dfp/v201805/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v201805/audience_segment_service/create_audience_segments.py index becf3ce0..1eea734e 100755 --- a/examples/dfp/v201805/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/create_audience_segments.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the IDs of the custom criteria to be used in the segment rule. CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -92,5 +92,5 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py similarity index 91% rename from examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py index 22a2c302..791c402d 100755 --- a/examples/dfp/v201805/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'AudienceSegmentService', version='v201805') # Create a statement to select audience segments. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py similarity index 91% rename from examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py index 2111ba3e..79d0c886 100755 --- a/examples/dfp/v201805/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201805') # Create a statement to select audience segments. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) @@ -49,5 +49,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py similarity index 91% rename from examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py index 58cb39a8..9a80a617 100755 --- a/examples/dfp/v201805/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' @@ -33,7 +33,7 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201805') # Create statement object to get the specified first party audience segment. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) @@ -67,5 +67,5 @@ def main(client, audience_segment_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AUDIENCE_SEGMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/dfp/v201805/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py similarity index 92% rename from examples/dfp/v201805/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py index 2f0cef1d..7401f4aa 100755 --- a/examples/dfp/v201805/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' @@ -32,7 +32,7 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201805') # Create statement object to get the specified first party audience segment. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) @@ -64,5 +64,5 @@ def main(client, audience_segment_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AUDIENCE_SEGMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/dfp/v201802/base_rate_service/__init__.py b/examples/ad_manager/v201805/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201802/base_rate_service/__init__.py rename to examples/ad_manager/v201805/base_rate_service/__init__.py diff --git a/examples/dfp/v201805/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201805/base_rate_service/create_product_base_rates.py similarity index 92% rename from examples/dfp/v201805/base_rate_service/create_product_base_rates.py rename to examples/ad_manager/v201805/base_rate_service/create_product_base_rates.py index 0948d09f..680710cd 100755 --- a/examples/dfp/v201805/base_rate_service/create_product_base_rates.py +++ b/examples/ad_manager/v201805/base_rate_service/create_product_base_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -61,5 +61,5 @@ def main(client, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201805/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201805/base_rate_service/create_product_package_item_base_rates.py similarity index 94% rename from examples/dfp/v201805/base_rate_service/create_product_package_item_base_rates.py rename to examples/ad_manager/v201805/base_rate_service/create_product_package_item_base_rates.py index 50532194..b449df56 100755 --- a/examples/dfp/v201805/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/ad_manager/v201805/base_rate_service/create_product_package_item_base_rates.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the rate card ID to add the base rate to. RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201805/base_rate_service/create_product_template_base_rates.py similarity index 92% rename from examples/dfp/v201805/base_rate_service/create_product_template_base_rates.py rename to examples/ad_manager/v201805/base_rate_service/create_product_template_base_rates.py index 4d6bbe06..cc3e25ce 100755 --- a/examples/dfp/v201805/base_rate_service/create_product_template_base_rates.py +++ b/examples/ad_manager/v201805/base_rate_service/create_product_template_base_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -61,5 +61,5 @@ def main(client, product_template_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201805/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py similarity index 84% rename from examples/dfp/v201805/base_rate_service/get_all_base_rates.py rename to examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py index 390b3c89..3e11527d 100755 --- a/examples/dfp/v201805/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a statement to select base rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. @@ -36,7 +36,8 @@ def main(client): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), + 'found.\n' % (base_rate['id'], + ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) statement.offset += statement.limit else: @@ -47,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py similarity index 87% rename from examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py rename to examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py index 278230e6..a127363c 100755 --- a/examples/dfp/v201805/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -26,7 +26,7 @@ def main(client, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a statement to select base rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) @@ -40,7 +40,7 @@ def main(client, rate_card_id): # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' 'found.\n' % - (base_rate['id'], dfp.DfpClassType(base_rate), + (base_rate['id'], ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) statement.offset += statement.limit else: @@ -51,5 +51,5 @@ def main(client, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201805/base_rate_service/update_base_rates.py b/examples/ad_manager/v201805/base_rate_service/update_base_rates.py similarity index 90% rename from examples/dfp/v201805/base_rate_service/update_base_rates.py rename to examples/ad_manager/v201805/base_rate_service/update_base_rates.py index b95a6c81..aa4dcb74 100755 --- a/examples/dfp/v201805/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201805/base_rate_service/update_base_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' @@ -32,7 +32,7 @@ def main(client, base_rate_id): base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a filter statement for base rates for a single rate card. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -63,7 +63,7 @@ def main(client, base_rate_id): print ('Base rate with ID "%s" and type "%s" belonging to ' 'rate card ID "%s" was updated.' % ( base_rate['id'], - dfp.DfpClassType(base_rate), + ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) else: print 'No base rates were updated.' @@ -73,5 +73,5 @@ def main(client, base_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, BASE_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, BASE_RATE_ID) diff --git a/examples/dfp/v201802/cdn_configuration_service/__init__.py b/examples/ad_manager/v201805/cdn_configuration_service/__init__.py similarity index 100% rename from examples/dfp/v201802/cdn_configuration_service/__init__.py rename to examples/ad_manager/v201805/cdn_configuration_service/__init__.py diff --git a/examples/dfp/v201805/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201805/cdn_configuration_service/create_cdn_configurations.py similarity index 95% rename from examples/dfp/v201805/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v201805/cdn_configuration_service/create_cdn_configurations.py index 3887620e..21a9459b 100755 --- a/examples/dfp/v201805/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v201805/cdn_configuration_service/create_cdn_configurations.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -85,5 +85,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py similarity index 91% rename from examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py index be37dcf9..fcc753f9 100755 --- a/examples/dfp/v201805/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -29,7 +29,7 @@ def main(client): version='v201805') # Create a statement to select cdn configurations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small number of configs at a time, paging # through until all have been retrieved. @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/company_service/__init__.py b/examples/ad_manager/v201805/company_service/__init__.py similarity index 100% rename from examples/dfp/v201802/company_service/__init__.py rename to examples/ad_manager/v201805/company_service/__init__.py diff --git a/examples/dfp/v201805/company_service/create_companies.py b/examples/ad_manager/v201805/company_service/create_companies.py similarity index 93% rename from examples/dfp/v201805/company_service/create_companies.py rename to examples/ad_manager/v201805/company_service/create_companies.py index a638349b..d7eccf64 100755 --- a/examples/dfp/v201805/company_service/create_companies.py +++ b/examples/ad_manager/v201805/company_service/create_companies.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -58,5 +58,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/company_service/get_advertisers.py b/examples/ad_manager/v201805/company_service/get_advertisers.py similarity index 90% rename from examples/dfp/v201805/company_service/get_advertisers.py rename to examples/ad_manager/v201805/company_service/get_advertisers.py index b6a7ebee..fd0510a2 100755 --- a/examples/dfp/v201805/company_service/get_advertisers.py +++ b/examples/ad_manager/v201805/company_service/get_advertisers.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. company_service = client.GetService('CompanyService', version='v201805') # Create a statement to select companies. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/company_service/get_all_companies.py b/examples/ad_manager/v201805/company_service/get_all_companies.py similarity index 90% rename from examples/dfp/v201805/company_service/get_all_companies.py rename to examples/ad_manager/v201805/company_service/get_all_companies.py index 0c97b344..df59fc3c 100755 --- a/examples/dfp/v201805/company_service/get_all_companies.py +++ b/examples/ad_manager/v201805/company_service/get_all_companies.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): company_service = client.GetService('CompanyService', version='v201805') # Create a statement to select companies. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/company_service/update_companies.py b/examples/ad_manager/v201805/company_service/update_companies.py similarity index 92% rename from examples/dfp/v201805/company_service/update_companies.py rename to examples/ad_manager/v201805/company_service/update_companies.py index cfeb2f8b..957dabad 100755 --- a/examples/dfp/v201805/company_service/update_companies.py +++ b/examples/ad_manager/v201805/company_service/update_companies.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the company to update. COMPANY_ID = 'INSERT_COMPANY_ID_HERE' @@ -38,7 +38,7 @@ def main(client, company_id): company_service = client.GetService('CompanyService', version='v201805') # Create statement object to only select a single company by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(company_id)) .Limit(1)) @@ -66,5 +66,5 @@ def main(client, company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, COMPANY_ID) diff --git a/examples/dfp/v201802/contact_service/__init__.py b/examples/ad_manager/v201805/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201802/contact_service/__init__.py rename to examples/ad_manager/v201805/contact_service/__init__.py diff --git a/examples/dfp/v201805/contact_service/create_contacts.py b/examples/ad_manager/v201805/contact_service/create_contacts.py similarity index 92% rename from examples/dfp/v201805/contact_service/create_contacts.py rename to examples/ad_manager/v201805/contact_service/create_contacts.py index e7bd1718..3d67169d 100755 --- a/examples/dfp/v201805/contact_service/create_contacts.py +++ b/examples/ad_manager/v201805/contact_service/create_contacts.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the advertiser company this contact is associated with. ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -67,5 +67,5 @@ def main(client, advertiser_company_id, agency_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) diff --git a/examples/dfp/v201805/contact_service/get_all_contacts.py b/examples/ad_manager/v201805/contact_service/get_all_contacts.py similarity index 90% rename from examples/dfp/v201805/contact_service/get_all_contacts.py rename to examples/ad_manager/v201805/contact_service/get_all_contacts.py index 73232c59..1c0d73de 100755 --- a/examples/dfp/v201805/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201805/contact_service/get_all_contacts.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): contact_service = client.GetService('ContactService', version='v201805') # Create a statement to select contacts. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py similarity index 90% rename from examples/dfp/v201805/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py index a1d228b7..2bcdb219 100755 --- a/examples/dfp/v201805/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. contact_service = client.GetService('ContactService', version='v201805') # Create a statement to select contacts. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/contact_service/update_contacts.py b/examples/ad_manager/v201805/contact_service/update_contacts.py similarity index 92% rename from examples/dfp/v201805/contact_service/update_contacts.py rename to examples/ad_manager/v201805/contact_service/update_contacts.py index 4c969cb3..5d3082af 100755 --- a/examples/dfp/v201805/contact_service/update_contacts.py +++ b/examples/ad_manager/v201805/contact_service/update_contacts.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the contact to update. CONTACT_ID = 'INSERT_CONTACT_ID_HERE' @@ -38,7 +38,7 @@ def main(client, contact_id): contact_service = client.GetService('ContactService', version='v201805') # Create statement object to select the single contact by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(contact_id)) .Limit(1)) @@ -67,5 +67,5 @@ def main(client, contact_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTACT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTACT_ID) diff --git a/examples/dfp/v201802/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201802/content_metadata_key_hierarchy_service/__init__.py rename to examples/ad_manager/v201805/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index d5287824..dc83bb63 100755 --- a/examples/dfp/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -19,7 +19,7 @@ To determine which content metadata key hierarchies exist, run get_all_content_metadata_key_hierarchies.py. -This feature is only available to DFP video publishers. +This feature is only available to Video Solutions publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the IDs of the custom targeting keys for the hierarchy. HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' @@ -74,5 +74,6 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, HIERARCHY_LEVEL_ONE_KEY_ID, HIERARCHY_LEVEL_TWO_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, HIERARCHY_LEVEL_ONE_KEY_ID, + HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index b08afe1d..e00064e8 100755 --- a/examples/dfp/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ContentMetadataKeyHierarchyService', version='v201805') # Create a statement to select content metadata key hierarchies. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 91% rename from examples/dfp/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 7b5bd910..5d085c9b 100755 --- a/examples/dfp/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -19,7 +19,7 @@ To determine which content metadata key hierarchies exist, run get_all_content_metadata_key_hierarchies.py. -This feature is only available to DFP video publishers. +This feature is only available to Video Solutions publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,7 +30,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the content metadata key hierarchy to update. CONTENT_METADATA_KEY_HIERARCHY_ID = ( @@ -46,7 +46,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Create a query to select a single content metadata key hierarchy. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) @@ -89,5 +89,6 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID, + CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201802/content_service/__init__.py b/examples/ad_manager/v201805/content_service/__init__.py similarity index 100% rename from examples/dfp/v201802/content_service/__init__.py rename to examples/ad_manager/v201805/content_service/__init__.py diff --git a/examples/dfp/v201805/content_service/get_all_content.py b/examples/ad_manager/v201805/content_service/get_all_content.py similarity index 90% rename from examples/dfp/v201805/content_service/get_all_content.py rename to examples/ad_manager/v201805/content_service/get_all_content.py index a80b8618..e8f11b2d 100755 --- a/examples/dfp/v201805/content_service/get_all_content.py +++ b/examples/ad_manager/v201805/content_service/get_all_content.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): content_service = client.GetService('ContentService', version='v201805') # Create a statement to select content. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/creative_service/__init__.py b/examples/ad_manager/v201805/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201802/creative_service/__init__.py rename to examples/ad_manager/v201805/creative_service/__init__.py diff --git a/examples/dfp/v201805/creative_service/copy_image_creatives.py b/examples/ad_manager/v201805/creative_service/copy_image_creatives.py similarity index 88% rename from examples/dfp/v201805/creative_service/copy_image_creatives.py rename to examples/ad_manager/v201805/creative_service/copy_image_creatives.py index b93d4a25..5ddf9440 100755 --- a/examples/dfp/v201805/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201805/creative_service/copy_image_creatives.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' @@ -31,7 +31,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to get the image creative. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) @@ -50,11 +50,11 @@ def main(client): print ('A creative with ID %d, name "%s", and type "%s" was created and ' 'can be previewed at: %s' % (result['id'], result['name'], - dfp.DfpClassType(result), + ad_manager.AdManagerClassType(result), result['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_service/create_creative_from_template.py b/examples/ad_manager/v201805/creative_service/create_creative_from_template.py similarity index 92% rename from examples/dfp/v201805/creative_service/create_creative_from_template.py rename to examples/ad_manager/v201805/creative_service/create_creative_from_template.py index 886b68e2..5a95694a 100755 --- a/examples/dfp/v201805/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201805/creative_service/create_creative_from_template.py @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -102,10 +102,10 @@ def main(client, advertiser_id): # Display results. print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201805/creative_service/create_creatives.py b/examples/ad_manager/v201805/creative_service/create_creatives.py similarity index 90% rename from examples/dfp/v201805/creative_service/create_creatives.py rename to examples/ad_manager/v201805/creative_service/create_creatives.py index 7db03fb4..93a142af 100755 --- a/examples/dfp/v201805/creative_service/create_creatives.py +++ b/examples/ad_manager/v201805/creative_service/create_creatives.py @@ -31,7 +31,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that all creatives will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -81,10 +81,10 @@ def main(client, advertiser_id): for creative in creatives: print ('Image creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201805/creative_service/create_custom_creative.py b/examples/ad_manager/v201805/creative_service/create_custom_creative.py similarity index 89% rename from examples/dfp/v201805/creative_service/create_custom_creative.py rename to examples/ad_manager/v201805/creative_service/create_custom_creative.py index be7a9b10..c616a98e 100755 --- a/examples/dfp/v201805/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201805/creative_service/create_custom_creative.py @@ -16,7 +16,7 @@ """This example creates a custom creative for a given advertiser. -This feature is only available to DFP premium solution networks. To determine +This feature is only available to Ad Manager 360 solution networks. To determine which companies are advertisers, run get_advertisers.py. To determine which creative templates exist, run get_all_creative_templates.py. @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -79,10 +79,10 @@ def main(client, advertiser_id): creative = creatives[0] print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201805/creative_service/create_native_creative.py b/examples/ad_manager/v201805/creative_service/create_native_creative.py similarity index 97% rename from examples/dfp/v201805/creative_service/create_native_creative.py rename to examples/ad_manager/v201805/creative_service/create_native_creative.py index 6a72df5d..5ce65334 100755 --- a/examples/dfp/v201805/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201805/creative_service/create_native_creative.py @@ -33,7 +33,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' @@ -128,5 +128,5 @@ def main(client, advertiser_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201805/creative_service/get_all_creatives.py b/examples/ad_manager/v201805/creative_service/get_all_creatives.py similarity index 90% rename from examples/dfp/v201805/creative_service/get_all_creatives.py rename to examples/ad_manager/v201805/creative_service/get_all_creatives.py index 6beec379..8aa94024 100755 --- a/examples/dfp/v201805/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201805/creative_service/get_all_creatives.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to select creatives. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_service/get_image_creatives.py b/examples/ad_manager/v201805/creative_service/get_image_creatives.py similarity index 90% rename from examples/dfp/v201805/creative_service/get_image_creatives.py rename to examples/ad_manager/v201805/creative_service/get_image_creatives.py index 1620a908..8be25a8f 100755 --- a/examples/dfp/v201805/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201805/creative_service/get_image_creatives.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to select creatives. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_service/update_creatives.py b/examples/ad_manager/v201805/creative_service/update_creatives.py similarity index 92% rename from examples/dfp/v201805/creative_service/update_creatives.py rename to examples/ad_manager/v201805/creative_service/update_creatives.py index 1817ca78..1f872e82 100755 --- a/examples/dfp/v201805/creative_service/update_creatives.py +++ b/examples/ad_manager/v201805/creative_service/update_creatives.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE' @@ -37,7 +37,7 @@ def main(client, image_creative_id): creative_service = client.GetService('CreativeService', version='v201805') # Create statement object to get the creative by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', long(image_creative_id)) @@ -67,5 +67,5 @@ def main(client, image_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, IMAGE_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, IMAGE_CREATIVE_ID) diff --git a/examples/dfp/v201802/creative_set_service/__init__.py b/examples/ad_manager/v201805/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201802/creative_set_service/__init__.py rename to examples/ad_manager/v201805/creative_set_service/__init__.py diff --git a/examples/dfp/v201805/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201805/creative_set_service/associate_creative_set_to_line_item.py similarity index 92% rename from examples/dfp/v201805/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v201805/creative_set_service/associate_creative_set_to_line_item.py index 83d523fc..6f457caa 100755 --- a/examples/dfp/v201805/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201805/creative_set_service/associate_creative_set_to_line_item.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -51,5 +51,5 @@ def main(client, creative_set_id, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_SET_ID, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_SET_ID, LINE_ITEM_ID) diff --git a/examples/dfp/v201805/creative_set_service/create_creative_set.py b/examples/ad_manager/v201805/creative_set_service/create_creative_set.py similarity index 92% rename from examples/dfp/v201805/creative_set_service/create_creative_set.py rename to examples/ad_manager/v201805/creative_set_service/create_creative_set.py index 056db8a0..d8511130 100755 --- a/examples/dfp/v201805/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201805/creative_set_service/create_creative_set.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' @@ -57,5 +57,5 @@ def main(client, master_creative_id, companion_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) diff --git a/examples/dfp/v201805/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py similarity index 90% rename from examples/dfp/v201805/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py index e66b5b31..d3be43e0 100755 --- a/examples/dfp/v201805/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CreativeSetService', version='v201805') # Create a statement to select creative sets. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py similarity index 90% rename from examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py index 7f4a9579..159a4e09 100755 --- a/examples/dfp/v201805/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' @@ -27,7 +27,7 @@ def main(client, master_creative_id): creative_set_service = client.GetService( 'CreativeSetService', version='v201805') # Create a statement to select creative sets. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) @@ -50,5 +50,5 @@ def main(client, master_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, MASTER_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, MASTER_CREATIVE_ID) diff --git a/examples/dfp/v201805/creative_set_service/update_creative_set.py b/examples/ad_manager/v201805/creative_set_service/update_creative_set.py similarity index 92% rename from examples/dfp/v201805/creative_set_service/update_creative_set.py rename to examples/ad_manager/v201805/creative_set_service/update_creative_set.py index 1d3e1628..9e7192fc 100755 --- a/examples/dfp/v201805/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201805/creative_set_service/update_creative_set.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the creative set to update. CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' @@ -40,7 +40,7 @@ def main(client, creative_set_id, companion_creative_id): version='v201805') # Create statement to select a single creative set by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', long(creative_set_id))) @@ -69,5 +69,5 @@ def main(client, creative_set_id, companion_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) diff --git a/examples/dfp/v201802/creative_template_service/__init__.py b/examples/ad_manager/v201805/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201802/creative_template_service/__init__.py rename to examples/ad_manager/v201805/creative_template_service/__init__.py diff --git a/examples/dfp/v201805/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py similarity index 90% rename from examples/dfp/v201805/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py index cb6ba41d..01b63822 100755 --- a/examples/dfp/v201805/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CreativeTemplateService', version='v201805') # Create a statement to select creative templates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py similarity index 91% rename from examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py index 8a307e75..fd9ee65c 100755 --- a/examples/dfp/v201805/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): creative_template_service = client.GetService( 'CreativeTemplateService', version='v201805') # Create a statement to select creative templates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201805/creative_wrapper_service/create_creative_wrappers.py similarity index 94% rename from examples/dfp/v201805/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v201805/creative_wrapper_service/create_creative_wrappers.py index c0db9688..b47efa06 100755 --- a/examples/dfp/v201805/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/create_creative_wrappers.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE' @@ -59,5 +59,5 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 93% rename from examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py index e3248064..65f25bb7 100755 --- a/examples/dfp/v201805/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py @@ -25,7 +25,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_LABEL_ID_HERE' @@ -36,7 +36,7 @@ def main(client, label_id): version='v201805') # Create a query to select the active creative wrappers for the given label. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', long(label_id))) @@ -74,5 +74,5 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py similarity index 91% rename from examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py index 697538ee..32f192a5 100755 --- a/examples/dfp/v201805/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): creative_wrapper_service = client.GetService( 'CreativeWrapperService', version='v201805') # Create a statement to select creative wrappers. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py similarity index 90% rename from examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py index ea07926a..b9a82dc5 100755 --- a/examples/dfp/v201805/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CreativeWrapperService', version='v201805') # Create a statement to select creative wrappers. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py similarity index 92% rename from examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py index d823635f..bb2d3da4 100755 --- a/examples/dfp/v201805/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the creative wrapper to update. CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE' @@ -39,7 +39,7 @@ def main(client, creative_wrapper_id): version='v201805') # Create statement to get a creative wrapper by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', long(creative_wrapper_id))) @@ -69,5 +69,5 @@ def main(client, creative_wrapper_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_WRAPPER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_WRAPPER_ID) diff --git a/examples/dfp/v201802/custom_field_service/__init__.py b/examples/ad_manager/v201805/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201802/custom_field_service/__init__.py rename to examples/ad_manager/v201805/custom_field_service/__init__.py diff --git a/examples/dfp/v201805/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201805/custom_field_service/create_custom_field_options.py similarity index 93% rename from examples/dfp/v201805/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v201805/custom_field_service/create_custom_field_options.py index 2ff33db3..a578a9c3 100755 --- a/examples/dfp/v201805/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201805/custom_field_service/create_custom_field_options.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the drop-down custom field to create options for. CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' @@ -63,5 +63,5 @@ def main(client, custom_field_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/dfp/v201805/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201805/custom_field_service/create_custom_fields.py similarity index 93% rename from examples/dfp/v201805/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v201805/custom_field_service/create_custom_fields.py index 4a0dde45..29985beb 100755 --- a/examples/dfp/v201805/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201805/custom_field_service/create_custom_fields.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 93% rename from examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py index 01dc372f..88218140 100755 --- a/examples/dfp/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -37,7 +37,7 @@ def main(client): # Create statement to select only active custom fields that apply to # line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) @@ -69,5 +69,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py similarity index 90% rename from examples/dfp/v201805/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py index d753d9d9..7d5c7abb 100755 --- a/examples/dfp/v201805/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CustomFieldService', version='v201805') # Create a statement to select custom fields. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py similarity index 91% rename from examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py index 4534ab56..85ca070e 100755 --- a/examples/dfp/v201805/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): custom_field_service = client.GetService( 'CustomFieldService', version='v201805') # Create a statement to select custom fields. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py similarity index 91% rename from examples/dfp/v201805/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py index 86b820ca..f6d8f158 100755 --- a/examples/dfp/v201805/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the custom fields, custom field option, and line item. CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' @@ -47,7 +47,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, line_item_service = client.GetService('LineItemService', version='v201805') # Create statement to get a custom field. - custom_field_statement = (dfp.StatementBuilder() + custom_field_statement = (ad_manager.StatementBuilder() .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - dfp.StatementBuilder() + ad_manager.StatementBuilder() .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (dfp.StatementBuilder() + line_item_statement = (ad_manager.StatementBuilder() .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) @@ -118,11 +118,11 @@ def main(client, custom_field_id, drop_down_custom_field_id, for line_item in line_items: custom_field_value_strings = [] for value in line_item['customFieldValues']: - if dfp.DfpClassType(value) == 'CustomFieldValue': + if ad_manager.AdManagerClassType(value) == 'CustomFieldValue': custom_field_value_string = ( '{ID: "%s", value: "%s"}' % (value['customFieldId'], value['value']['value'])) - elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': + elif ad_manager.AdManagerClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) @@ -134,6 +134,6 @@ def main(client, custom_field_id, drop_down_custom_field_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID) diff --git a/examples/dfp/v201805/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201805/custom_field_service/update_custom_fields.py similarity index 92% rename from examples/dfp/v201805/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v201805/custom_field_service/update_custom_fields.py index 59123218..b5859303 100755 --- a/examples/dfp/v201805/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201805/custom_field_service/update_custom_fields.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the custom field to update. CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' @@ -39,7 +39,7 @@ def main(client, custom_field_id): 'CustomFieldService', version='v201805') # Create statement to get a custom field. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :customFieldId') .WithBindVariable('customFieldId', long(custom_field_id))) @@ -66,5 +66,5 @@ def main(client, custom_field_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/dfp/v201802/custom_targeting_service/__init__.py b/examples/ad_manager/v201805/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201802/custom_targeting_service/__init__.py rename to examples/ad_manager/v201805/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 96% rename from examples/dfp/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py index 89b54bf1..b6ccf3a8 100755 --- a/examples/dfp/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -128,5 +128,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py similarity index 91% rename from examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py index c18198d4..a5d88ff2 100755 --- a/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE' @@ -38,7 +38,7 @@ def main(client, key_name): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201805') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (dfp.StatementBuilder() + key_statement = (ad_manager.StatementBuilder() .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. @@ -73,5 +73,5 @@ def main(client, key_name): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, KEY_NAME) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, KEY_NAME) diff --git a/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py similarity index 91% rename from examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py index 00c44260..a8819e90 100755 --- a/examples/dfp/v201805/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -38,7 +38,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201805') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (dfp.StatementBuilder() + value_statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) @@ -73,5 +73,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, KEY_ID) diff --git a/examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 91% rename from examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 90745fca..ba893e2c 100755 --- a/examples/dfp/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201805') # Create statement to get all targeting keys. - targeting_key_statement = dfp.StatementBuilder() + targeting_key_statement = ad_manager.StatementBuilder() all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) @@ -68,5 +68,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 92% rename from examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 39b7fc8d..f2e312ab 100755 --- a/examples/dfp/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201805') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (dfp.StatementBuilder() + targeting_key_statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) @@ -70,5 +70,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py similarity index 91% rename from examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py index 3e30b337..bc7f113a 100755 --- a/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -32,7 +32,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201805') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :keyId') .WithBindVariable('keyId', long(key_id)) .Limit(1)) @@ -63,5 +63,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py similarity index 92% rename from examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py index 2c5074d1..542c90bc 100755 --- a/examples/dfp/v201805/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -32,7 +32,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201805') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', long(key_id))) @@ -67,5 +67,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201802/exchange_rate_service/__init__.py b/examples/ad_manager/v201805/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201802/exchange_rate_service/__init__.py rename to examples/ad_manager/v201805/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201805/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201805/exchange_rate_service/create_exchange_rates.py similarity index 93% rename from examples/dfp/v201805/exchange_rate_service/create_exchange_rates.py rename to examples/ad_manager/v201805/exchange_rate_service/create_exchange_rates.py index df6307d3..3aad543f 100755 --- a/examples/dfp/v201805/exchange_rate_service/create_exchange_rates.py +++ b/examples/ad_manager/v201805/exchange_rate_service/create_exchange_rates.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -54,5 +54,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py similarity index 91% rename from examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py rename to examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py index abea1a8d..323f3c5c 100755 --- a/examples/dfp/v201805/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ExchangeRateService', version='v201805') # Create a statement to select exchange rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 91% rename from examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py index 1e434c83..b34d11c6 100755 --- a/examples/dfp/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' @@ -27,7 +27,7 @@ def main(client, currency_code): exchange_rate_service = client.GetService( 'ExchangeRateService', version='v201805') # Create a statement to select exchange rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('currencyCode = :currencyCode') .WithBindVariable('currencyCode', currency_code)) @@ -52,5 +52,5 @@ def main(client, currency_code): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CURRENCY_CODE) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CURRENCY_CODE) diff --git a/examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py similarity index 92% rename from examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py rename to examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py index dba98321..0462fd66 100755 --- a/examples/dfp/v201805/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' @@ -33,7 +33,7 @@ def main(client, exchange_rate_id): version='v201805') # Create a statement to get an exchange rate by its ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(exchange_rate_id)) .Limit(1)) @@ -67,5 +67,5 @@ def main(client, exchange_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, EXCHANGE_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, EXCHANGE_RATE_ID) diff --git a/examples/dfp/v201805/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201805/forecast_service/get_availability_forecast.py similarity index 96% rename from examples/dfp/v201805/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v201805/forecast_service/get_availability_forecast.py index a857a128..c1d25506 100755 --- a/examples/dfp/v201805/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v201805/forecast_service/get_availability_forecast.py @@ -27,7 +27,7 @@ import datetime # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set the ID of the advertiser (company) to forecast for. Setting an advertiser @@ -126,5 +126,5 @@ def main(client, advertiser_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201805/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201805/forecast_service/get_availability_forecast_for_line_item.py similarity index 93% rename from examples/dfp/v201805/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v201805/forecast_service/get_availability_forecast_for_line_item.py index 720da349..15eba4c5 100755 --- a/examples/dfp/v201805/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201805/forecast_service/get_availability_forecast_for_line_item.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line item to get a forecast for. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -62,5 +62,5 @@ def main(client, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201805/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201805/forecast_service/get_delivery_forecast_for_line_items.py similarity index 91% rename from examples/dfp/v201805/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v201805/forecast_service/get_delivery_forecast_for_line_items.py index f03d6025..98360a34 100755 --- a/examples/dfp/v201805/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201805/forecast_service/get_delivery_forecast_for_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line items to get forecasts for. LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' @@ -48,5 +48,5 @@ def main(client, line_item_id1, line_item_id2): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201802/inventory_service/__init__.py b/examples/ad_manager/v201805/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201802/inventory_service/__init__.py rename to examples/ad_manager/v201805/inventory_service/__init__.py diff --git a/examples/dfp/v201805/inventory_service/archive_ad_units.py b/examples/ad_manager/v201805/inventory_service/archive_ad_units.py similarity index 92% rename from examples/dfp/v201805/inventory_service/archive_ad_units.py rename to examples/ad_manager/v201805/inventory_service/archive_ad_units.py index fbe55bf6..337c2778 100755 --- a/examples/dfp/v201805/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/archive_ad_units.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' @@ -39,7 +39,7 @@ def main(client, parent_id): # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', long(parent_id))) @@ -71,5 +71,5 @@ def main(client, parent_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PARENT_AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/dfp/v201805/inventory_service/create_ad_units.py b/examples/ad_manager/v201805/inventory_service/create_ad_units.py similarity index 92% rename from examples/dfp/v201805/inventory_service/create_ad_units.py rename to examples/ad_manager/v201805/inventory_service/create_ad_units.py index f9b48c1b..b9d581fd 100755 --- a/examples/dfp/v201805/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/create_ad_units.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' @@ -66,5 +66,5 @@ def main(client, parent_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PARENT_AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py similarity index 94% rename from examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py index d424ebd8..0545e61f 100755 --- a/examples/dfp/v201805/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py @@ -19,7 +19,7 @@ # Import appropriate modules from the client library. import collections -from googleads import dfp +from googleads import ad_manager def main(client): @@ -32,7 +32,7 @@ def main(client): root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .OrderBy('id', ascending=True)) # Pull down all ad units into a list @@ -111,5 +111,5 @@ def display_hierarchy_helper(root, parent_id_to_children, depth): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py similarity index 89% rename from examples/dfp/v201805/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py index c5c55183..5b780c5b 100755 --- a/examples/dfp/v201805/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'InventoryService', version='v201805') # Create a statement to select ad unit sizes. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. @@ -42,5 +42,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201805/inventory_service/get_all_ad_units.py similarity index 90% rename from examples/dfp/v201805/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v201805/inventory_service/get_all_ad_units.py index 702bc72f..4e6bc325 100755 --- a/examples/dfp/v201805/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/get_all_ad_units.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): ad_unit_service = client.GetService('InventoryService', version='v201805') # Create a statement to select ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py similarity index 92% rename from examples/dfp/v201805/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py index 0d5fb79a..f9d22de4 100755 --- a/examples/dfp/v201805/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py @@ -18,7 +18,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -31,7 +31,7 @@ def main(client): parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) @@ -54,5 +54,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/inventory_service/update_ad_units.py b/examples/ad_manager/v201805/inventory_service/update_ad_units.py similarity index 93% rename from examples/dfp/v201805/inventory_service/update_ad_units.py rename to examples/ad_manager/v201805/inventory_service/update_ad_units.py index 3adb7cf1..5e0a3b7c 100755 --- a/examples/dfp/v201805/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/update_ad_units.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the ad unit to get. @@ -39,7 +39,7 @@ def main(client, ad_unit_id): inventory_service = client.GetService('InventoryService', version='v201805') # Create a statement to select a single ad unit by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', ad_unit_id)) @@ -78,5 +78,5 @@ def main(client, ad_unit_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AD_UNIT_ID) diff --git a/examples/dfp/v201802/label_service/__init__.py b/examples/ad_manager/v201805/label_service/__init__.py similarity index 100% rename from examples/dfp/v201802/label_service/__init__.py rename to examples/ad_manager/v201805/label_service/__init__.py diff --git a/examples/dfp/v201805/label_service/create_labels.py b/examples/ad_manager/v201805/label_service/create_labels.py similarity index 89% rename from examples/dfp/v201805/label_service/create_labels.py rename to examples/ad_manager/v201805/label_service/create_labels.py index 43c66f09..b20d152e 100755 --- a/examples/dfp/v201805/label_service/create_labels.py +++ b/examples/ad_manager/v201805/label_service/create_labels.py @@ -17,14 +17,14 @@ """This code example creates new labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/label_service/deactivate_labels.py b/examples/ad_manager/v201805/label_service/deactivate_labels.py similarity index 89% rename from examples/dfp/v201805/label_service/deactivate_labels.py rename to examples/ad_manager/v201805/label_service/deactivate_labels.py index 5ab36860..278c05b9 100755 --- a/examples/dfp/v201805/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201805/label_service/deactivate_labels.py @@ -17,12 +17,12 @@ """This code example deactivates all active Labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -30,7 +30,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isActive = :isActive') .WithBindVariable('isActive', True)) @@ -61,5 +61,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/label_service/get_active_labels.py b/examples/ad_manager/v201805/label_service/get_active_labels.py similarity index 90% rename from examples/dfp/v201805/label_service/get_active_labels.py rename to examples/ad_manager/v201805/label_service/get_active_labels.py index 76827777..57ee3bbf 100755 --- a/examples/dfp/v201805/label_service/get_active_labels.py +++ b/examples/ad_manager/v201805/label_service/get_active_labels.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201805') # Create a statement to select labels. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isActive = :isActive') .WithBindVariable('isActive', True)) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/label_service/get_all_labels.py b/examples/ad_manager/v201805/label_service/get_all_labels.py similarity index 90% rename from examples/dfp/v201805/label_service/get_all_labels.py rename to examples/ad_manager/v201805/label_service/get_all_labels.py index f5290edd..615234b7 100755 --- a/examples/dfp/v201805/label_service/get_all_labels.py +++ b/examples/ad_manager/v201805/label_service/get_all_labels.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201805') # Create a statement to select labels. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/label_service/update_labels.py b/examples/ad_manager/v201805/label_service/update_labels.py similarity index 89% rename from examples/dfp/v201805/label_service/update_labels.py rename to examples/ad_manager/v201805/label_service/update_labels.py index b0718042..643540e2 100755 --- a/examples/dfp/v201805/label_service/update_labels.py +++ b/examples/ad_manager/v201805/label_service/update_labels.py @@ -17,12 +17,12 @@ """This code example updates the description of a single label. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_LABEL_ID_HERE' @@ -32,7 +32,7 @@ def main(client, label_id): label_service = client.GetService('LabelService', version='v201805') # Create a statement to select only active labels. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :labelId') .WithBindVariable('labelId', long(label_id))) @@ -58,6 +58,6 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201802/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201805/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201802/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v201805/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201805/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201805/line_item_creative_association_service/create_licas.py similarity index 91% rename from examples/dfp/v201805/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v201805/line_item_creative_association_service/create_licas.py index 944e76ec..ca662ddb 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/create_licas.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line item ID and creative IDs to associate. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -53,5 +53,5 @@ def main(client, line_item_id, creative_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID, CREATIVE_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, CREATIVE_IDS) diff --git a/examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py similarity index 92% rename from examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py index ca0b66ba..7b9a12f6 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the line item in which to deactivate LICAs. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -33,7 +33,7 @@ def main(client, line_item_id): 'LineItemCreativeAssociationService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', long(line_item_id))) @@ -69,5 +69,5 @@ def main(client, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py similarity index 92% rename from examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py index 743a2a79..9915aa93 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201805') # Create a statement to select line item creative associations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py similarity index 92% rename from examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py index 920eeac1..838a4fe8 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -27,7 +27,7 @@ def main(client, line_item_id): lica_service = client.GetService( 'LineItemCreativeAssociationService', version='v201805') # Create a statement to select line item creative associations. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) @@ -56,5 +56,5 @@ def main(client, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201805/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py similarity index 92% rename from examples/dfp/v201805/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py index 5aa84fa2..8a07ab8d 100755 --- a/examples/dfp/v201805/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -31,7 +31,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201805') # Create statement object to get all LICAs. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() while True: # Get LICAs by statement. @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/line_item_service/__init__.py b/examples/ad_manager/v201805/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201802/line_item_service/__init__.py rename to examples/ad_manager/v201805/line_item_service/__init__.py diff --git a/examples/dfp/v201805/line_item_service/activate_line_items.py b/examples/ad_manager/v201805/line_item_service/activate_line_items.py similarity index 93% rename from examples/dfp/v201805/line_item_service/activate_line_items.py rename to examples/ad_manager/v201805/line_item_service/activate_line_items.py index 34c658cf..d7306953 100755 --- a/examples/dfp/v201805/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/activate_line_items.py @@ -25,7 +25,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the order to get line items from. ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -36,7 +36,7 @@ def main(client, order_id): line_item_service = client.GetService('LineItemService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', long(order_id))) @@ -71,5 +71,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201805/line_item_service/create_line_items.py b/examples/ad_manager/v201805/line_item_service/create_line_items.py similarity index 96% rename from examples/dfp/v201805/line_item_service/create_line_items.py rename to examples/ad_manager/v201805/line_item_service/create_line_items.py index 7f352b1d..369ce8e8 100755 --- a/examples/dfp/v201805/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/create_line_items.py @@ -26,7 +26,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set order that the created line item will belong to and add the id of a @@ -161,6 +161,6 @@ def main(client, order_id, targeted_placement_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID, TARGETED_PLACEMENT_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS) diff --git a/examples/dfp/v201805/line_item_service/create_video_line_item.py b/examples/ad_manager/v201805/line_item_service/create_video_line_item.py similarity index 94% rename from examples/dfp/v201805/line_item_service/create_video_line_item.py rename to examples/ad_manager/v201805/line_item_service/create_video_line_item.py index da6abd84..c43fd2d4 100755 --- a/examples/dfp/v201805/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v201805/line_item_service/create_video_line_item.py @@ -16,7 +16,7 @@ """This code example creates a new line item to serve to video content. -This feature is only available to DFP premium solution networks. To determine +This feature is only available to Ad Manager 360 solution networks. To determine which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To create a video ad unit, run create_video_ad_unit.py. To create criteria for categories, run @@ -28,7 +28,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set order that all created line item will belong to and the video ad unit id @@ -130,6 +130,6 @@ def main(client, order_id, targeted_video_ad_unit_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201805/line_item_service/get_all_line_items.py b/examples/ad_manager/v201805/line_item_service/get_all_line_items.py similarity index 90% rename from examples/dfp/v201805/line_item_service/get_all_line_items.py rename to examples/ad_manager/v201805/line_item_service/get_all_line_items.py index 0b757e71..1ac84fe7 100755 --- a/examples/dfp/v201805/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/get_all_line_items.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): line_item_service = client.GetService('LineItemService', version='v201805') # Create a statement to select line items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py similarity index 91% rename from examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py index 905fd2c8..172398a8 100755 --- a/examples/dfp/v201805/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. line_item_service = client.GetService('LineItemService', version='v201805') # Create a statement to select line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py similarity index 91% rename from examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py index 1ae113db..62d12cbb 100755 --- a/examples/dfp/v201805/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py @@ -20,7 +20,7 @@ from datetime import datetime from datetime import timedelta -from googleads import dfp +from googleads import ad_manager import pytz @@ -32,7 +32,7 @@ def main(client): - timedelta(days=1)) # Create a statement to select line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) @@ -55,5 +55,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/line_item_service/pause_line_items.py b/examples/ad_manager/v201805/line_item_service/pause_line_items.py similarity index 93% rename from examples/dfp/v201805/line_item_service/pause_line_items.py rename to examples/ad_manager/v201805/line_item_service/pause_line_items.py index c5085757..c6755cc5 100755 --- a/examples/dfp/v201805/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/pause_line_items.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -33,7 +33,7 @@ def main(client): # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) @@ -70,5 +70,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201805/line_item_service/target_custom_criteria.py similarity index 93% rename from examples/dfp/v201805/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v201805/line_item_service/target_custom_criteria.py index 7f64049f..7fdf5c5e 100755 --- a/examples/dfp/v201805/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201805/line_item_service/target_custom_criteria.py @@ -25,7 +25,7 @@ import pprint # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE' @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :lineItemId') .WithBindVariable('lineItemId', long(line_item_id)) .Limit(1)) @@ -105,6 +105,6 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, VALUE_ID2, VALUE_ID3) diff --git a/examples/dfp/v201805/line_item_service/update_line_items.py b/examples/ad_manager/v201805/line_item_service/update_line_items.py similarity index 93% rename from examples/dfp/v201805/line_item_service/update_line_items.py rename to examples/ad_manager/v201805/line_item_service/update_line_items.py index 6b2e0fd4..e01c07ac 100755 --- a/examples/dfp/v201805/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/update_line_items.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the order to get line items from. ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -33,7 +33,7 @@ def main(client, order_id): # Create statement object to only select line items with even delivery rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', long(order_id)) @@ -70,5 +70,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py similarity index 90% rename from examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py index b97b78cd..05844796 100755 --- a/examples/dfp/v201805/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py @@ -17,7 +17,7 @@ """This code example activates paused live stream events.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the LiveStreamEvent to get live stream events from. LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' @@ -29,7 +29,7 @@ def main(client, live_stream_event_id): 'LiveStreamEventService', version='v201805') # Create query to find paused live stream events. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') @@ -53,7 +53,7 @@ def main(client, live_stream_event_id): }, statement.ToStatement()) if result and int(result['numChanges']) > 0: live_stream_events_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += ad_manager.SUGGESTED_PAGE_LIMIT else: break @@ -67,5 +67,5 @@ def main(client, live_stream_event_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LIVE_STREAM_EVENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201805/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201805/live_stream_event_service/create_live_stream_events.py similarity index 93% rename from examples/dfp/v201805/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v201805/live_stream_event_service/create_live_stream_events.py index 3ddd62ed..553310d5 100755 --- a/examples/dfp/v201805/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v201805/live_stream_event_service/create_live_stream_events.py @@ -24,7 +24,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set content urls and adTags to use @@ -64,5 +64,5 @@ def main(client, content_urls, ad_tags): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_URLS, AD_TAGS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_URLS, AD_TAGS) diff --git a/examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py similarity index 90% rename from examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py index d2e7623f..f95f0934 100755 --- a/examples/dfp/v201805/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py @@ -18,7 +18,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -27,7 +27,7 @@ def main(client): 'LiveStreamEventService', version='v201805') # Create a statement to select live stream events. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201805/live_stream_event_service/register_sessions_for_monitoring.py similarity index 91% rename from examples/dfp/v201805/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v201805/live_stream_event_service/register_sessions_for_monitoring.py index b21c87d3..17329278 100755 --- a/examples/dfp/v201805/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201805/live_stream_event_service/register_sessions_for_monitoring.py @@ -17,7 +17,7 @@ """This example registers all live stream event-sessions ids for monitoring.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # List of session ids SESSION_IDS = ['INSERT_SESSION_IDS_HERE'] @@ -41,5 +41,5 @@ def main(client, session_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, SESSION_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, SESSION_IDS) diff --git a/examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py similarity index 92% rename from examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py index 382b879a..214a2e2f 100755 --- a/examples/dfp/v201805/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set ID of the LiveStreamEvent to get live stream events from. LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' @@ -32,7 +32,7 @@ def main(client, live_stream_event_id): 'LiveStreamEventService', version='v201805') # Create statement object to only select matching live stream event. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('Id = :id')) .WithBindVariable('id', long(live_stream_event_id)) .Limit(500)) @@ -65,5 +65,5 @@ def main(client, live_stream_event_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LIVE_STREAM_EVENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201802/native_style_service/__init__.py b/examples/ad_manager/v201805/native_style_service/__init__.py similarity index 100% rename from examples/dfp/v201802/native_style_service/__init__.py rename to examples/ad_manager/v201805/native_style_service/__init__.py diff --git a/examples/dfp/v201805/native_style_service/create_native_styles.py b/examples/ad_manager/v201805/native_style_service/create_native_styles.py similarity index 95% rename from examples/dfp/v201805/native_style_service/create_native_styles.py rename to examples/ad_manager/v201805/native_style_service/create_native_styles.py index a4b1838b..d3250bae 100755 --- a/examples/dfp/v201805/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201805/native_style_service/create_native_styles.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # This is the creative template ID for the system-defined native app install ad @@ -175,6 +175,6 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, WIDTH, - HEIGHT) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, + WIDTH, HEIGHT) diff --git a/examples/dfp/v201805/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201805/native_style_service/get_all_native_styles.py similarity index 90% rename from examples/dfp/v201805/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v201805/native_style_service/get_all_native_styles.py index 8f608773..e3f0bfc7 100755 --- a/examples/dfp/v201805/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201805/native_style_service/get_all_native_styles.py @@ -17,7 +17,7 @@ """This example gets all native styles.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): version='v201805') # Create a statement to select native styles. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/network_service/__init__.py b/examples/ad_manager/v201805/network_service/__init__.py similarity index 100% rename from examples/dfp/v201802/network_service/__init__.py rename to examples/ad_manager/v201805/network_service/__init__.py diff --git a/examples/dfp/v201805/network_service/get_all_networks.py b/examples/ad_manager/v201805/network_service/get_all_networks.py similarity index 90% rename from examples/dfp/v201805/network_service/get_all_networks.py rename to examples/ad_manager/v201805/network_service/get_all_networks.py index 5f7b854d..50753106 100755 --- a/examples/dfp/v201805/network_service/get_all_networks.py +++ b/examples/ad_manager/v201805/network_service/get_all_networks.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -36,5 +36,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/network_service/get_current_network.py b/examples/ad_manager/v201805/network_service/get_current_network.py similarity index 89% rename from examples/dfp/v201805/network_service/get_current_network.py rename to examples/ad_manager/v201805/network_service/get_current_network.py index 519e617d..552cdc4b 100755 --- a/examples/dfp/v201805/network_service/get_current_network.py +++ b/examples/ad_manager/v201805/network_service/get_current_network.py @@ -18,7 +18,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -33,5 +33,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/network_service/make_test_network.py b/examples/ad_manager/v201805/network_service/make_test_network.py similarity index 68% rename from examples/dfp/v201805/network_service/make_test_network.py rename to examples/ad_manager/v201805/network_service/make_test_network.py index df62a590..dae252d4 100755 --- a/examples/dfp/v201805/network_service/make_test_network.py +++ b/examples/ad_manager/v201805/network_service/make_test_network.py @@ -16,11 +16,12 @@ """This example creates a test network. -You do not need to have a DFP account to run this example, but you do need to -have a Google account (created at http://www.google.com/accounts/newaccount -if you currently don't have one) that is not associated with any other DFP test -networks. Once this network is created, you can supply the network code in your -settings to make calls to other services. +You do not need to have an Ad Manager account to run this example, but you do +need to have a Google account (created at +http://www.google.com/accounts/newaccount if you currently don't have one) that +is not associated with any other Ad Manager test networks. Once this network is +created, you can supply the network code in your settings to make calls to +other services. Alternatively, if you do not wish to run this example, you can create a test network at: @@ -29,7 +30,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -42,10 +43,11 @@ def main(client): # Display results. print ('Test network with network code "%s" and display name "%s" ' 'created.' % (network['networkCode'], network['displayName'])) - print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s' + print ('You may now sign in at ' + 'http://www.google.com/admanager/main?networkCode=%s' % network['networkCode']) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/order_service/__init__.py b/examples/ad_manager/v201805/order_service/__init__.py similarity index 100% rename from examples/dfp/v201802/order_service/__init__.py rename to examples/ad_manager/v201805/order_service/__init__.py diff --git a/examples/dfp/v201805/order_service/approve_orders.py b/examples/ad_manager/v201805/order_service/approve_orders.py similarity index 92% rename from examples/dfp/v201805/order_service/approve_orders.py rename to examples/ad_manager/v201805/order_service/approve_orders.py index 6c47b89b..4f10e7d8 100755 --- a/examples/dfp/v201805/order_service/approve_orders.py +++ b/examples/ad_manager/v201805/order_service/approve_orders.py @@ -23,7 +23,7 @@ import datetime # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -32,7 +32,7 @@ def main(client): # Create a filter statement. today = datetime.date.today() - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) @@ -63,5 +63,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/order_service/create_orders.py b/examples/ad_manager/v201805/order_service/create_orders.py similarity index 90% rename from examples/dfp/v201805/order_service/create_orders.py rename to examples/ad_manager/v201805/order_service/create_orders.py index 8afced0f..04ba75ea 100755 --- a/examples/dfp/v201805/order_service/create_orders.py +++ b/examples/ad_manager/v201805/order_service/create_orders.py @@ -23,7 +23,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE' @@ -55,5 +55,5 @@ def main(client, company_id, salesperson_id, trafficker_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) diff --git a/examples/dfp/v201805/order_service/get_all_orders.py b/examples/ad_manager/v201805/order_service/get_all_orders.py similarity index 90% rename from examples/dfp/v201805/order_service/get_all_orders.py rename to examples/ad_manager/v201805/order_service/get_all_orders.py index d9424a63..98acbc6e 100755 --- a/examples/dfp/v201805/order_service/get_all_orders.py +++ b/examples/ad_manager/v201805/order_service/get_all_orders.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): order_service = client.GetService('OrderService', version='v201805') # Create a statement to select orders. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201805/order_service/get_orders_starting_soon.py similarity index 92% rename from examples/dfp/v201805/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v201805/order_service/get_orders_starting_soon.py index ed9f4c32..d84a287c 100755 --- a/examples/dfp/v201805/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201805/order_service/get_orders_starting_soon.py @@ -20,7 +20,7 @@ from datetime import datetime from datetime import timedelta -from googleads import dfp +from googleads import ad_manager import pytz @@ -31,7 +31,7 @@ def main(client): soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/order_service/update_orders.py b/examples/ad_manager/v201805/order_service/update_orders.py similarity index 92% rename from examples/dfp/v201805/order_service/update_orders.py rename to examples/ad_manager/v201805/order_service/update_orders.py index cf3cb373..380fe155 100755 --- a/examples/dfp/v201805/order_service/update_orders.py +++ b/examples/ad_manager/v201805/order_service/update_orders.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to select a single order by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :orderId') .WithBindVariable('orderId', long(order_id))) @@ -66,6 +66,6 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201805/package_service/create_packages.py b/examples/ad_manager/v201805/package_service/create_packages.py similarity index 93% rename from examples/dfp/v201805/package_service/create_packages.py rename to examples/ad_manager/v201805/package_service/create_packages.py index dcbc8980..29c12353 100755 --- a/examples/dfp/v201805/package_service/create_packages.py +++ b/examples/ad_manager/v201805/package_service/create_packages.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the ID of the product package to create the package from. PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -57,5 +57,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py similarity index 92% rename from examples/dfp/v201805/package_service/create_proposal_line_items_from_packages.py rename to examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py index 47b5f785..33c4ce4b 100755 --- a/examples/dfp/v201805/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' @@ -31,7 +31,7 @@ def main(client): package_service = client.GetService('PackageService', version='v201805') # Create a statement to select the single package. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -64,5 +64,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/package_service/get_all_packages.py b/examples/ad_manager/v201805/package_service/get_all_packages.py similarity index 90% rename from examples/dfp/v201805/package_service/get_all_packages.py rename to examples/ad_manager/v201805/package_service/get_all_packages.py index 598a2efc..adcc425e 100755 --- a/examples/dfp/v201805/package_service/get_all_packages.py +++ b/examples/ad_manager/v201805/package_service/get_all_packages.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): pkg_service = client.GetService('PackageService', version='v201805') # Create a statement to select packages. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/package_service/get_in_progress_packages.py b/examples/ad_manager/v201805/package_service/get_in_progress_packages.py similarity index 90% rename from examples/dfp/v201805/package_service/get_in_progress_packages.py rename to examples/ad_manager/v201805/package_service/get_in_progress_packages.py index a3142c80..9dd55abe 100755 --- a/examples/dfp/v201805/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201805/package_service/get_in_progress_packages.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. pkg_service = client.GetService('PackageService', version='v201805') # Create a statement to select packages. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'IN_PROGRESS')) @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/placement_service/create_placements.py b/examples/ad_manager/v201805/placement_service/create_placements.py similarity index 95% rename from examples/dfp/v201805/placement_service/create_placements.py rename to examples/ad_manager/v201805/placement_service/create_placements.py index 2a06f075..512b9b98 100755 --- a/examples/dfp/v201805/placement_service/create_placements.py +++ b/examples/ad_manager/v201805/placement_service/create_placements.py @@ -23,7 +23,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() while True: response = inventory_service.getAdUnitsByStatement( @@ -104,5 +104,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/placement_service/deactivate_placements.py b/examples/ad_manager/v201805/placement_service/deactivate_placements.py similarity index 91% rename from examples/dfp/v201805/placement_service/deactivate_placements.py rename to examples/ad_manager/v201805/placement_service/deactivate_placements.py index d7b61e2e..4cce8607 100755 --- a/examples/dfp/v201805/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201805/placement_service/deactivate_placements.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' @@ -31,7 +31,7 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :placementId') .WithBindVariable('placementId', long(placement_id)) .Limit(1)) @@ -58,5 +58,5 @@ def main(client, placement_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PLACEMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/dfp/v201805/placement_service/get_active_placements.py b/examples/ad_manager/v201805/placement_service/get_active_placements.py similarity index 90% rename from examples/dfp/v201805/placement_service/get_active_placements.py rename to examples/ad_manager/v201805/placement_service/get_active_placements.py index 36d40ae8..e325526b 100755 --- a/examples/dfp/v201805/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201805/placement_service/get_active_placements.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. placement_service = client.GetService('PlacementService', version='v201805') # Create a statement to select placements. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/placement_service/get_all_placements.py b/examples/ad_manager/v201805/placement_service/get_all_placements.py similarity index 90% rename from examples/dfp/v201805/placement_service/get_all_placements.py rename to examples/ad_manager/v201805/placement_service/get_all_placements.py index 016b21c5..1667ef15 100755 --- a/examples/dfp/v201805/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201805/placement_service/get_all_placements.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): placement_service = client.GetService('PlacementService', version='v201805') # Create a statement to select placements. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/placement_service/update_placements.py b/examples/ad_manager/v201805/placement_service/update_placements.py similarity index 90% rename from examples/dfp/v201805/placement_service/update_placements.py rename to examples/ad_manager/v201805/placement_service/update_placements.py index aad1e1b8..3c2087e8 100755 --- a/examples/dfp/v201805/placement_service/update_placements.py +++ b/examples/ad_manager/v201805/placement_service/update_placements.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' @@ -31,7 +31,7 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -54,5 +54,5 @@ def main(client, placement_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PLACEMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/dfp/v201802/premium_rate_service/__init__.py b/examples/ad_manager/v201805/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201802/premium_rate_service/__init__.py rename to examples/ad_manager/v201805/premium_rate_service/__init__.py diff --git a/examples/dfp/v201805/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201805/premium_rate_service/create_premium_rates.py similarity index 92% rename from examples/dfp/v201805/premium_rate_service/create_premium_rates.py rename to examples/ad_manager/v201805/premium_rate_service/create_premium_rates.py index 31d11807..3ede39a6 100755 --- a/examples/dfp/v201805/premium_rate_service/create_premium_rates.py +++ b/examples/ad_manager/v201805/premium_rate_service/create_premium_rates.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -75,10 +75,10 @@ def main(client, rate_card_id): for premium_rate in premium_rates: print ('A premium rate for "%s" was added to the rate card with ID' ' of "%s".\n' - % (dfp.DfpClassType(premium_rate['premiumFeature']), + % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), premium_rate['id'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py similarity index 81% rename from examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py rename to examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py index 47892106..103e01b0 100755 --- a/examples/dfp/v201805/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'PremiumRateService', version='v201805') # Create a statement to select premium rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. @@ -37,9 +37,10 @@ def main(client): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'id "%d" was found.\n' % (premium_rate['id'], - dfp.DfpClassType(premium_rate), - premium_rate['rateCardId'])) + 'id "%d" was found.\n' % ( + premium_rate['id'], + ad_manager.AdManagerClassType(premium_rate), + premium_rate['rateCardId'])) statement.offset += statement.limit else: break @@ -49,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 91% rename from examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py index 1d8e3df2..447d0dc0 100755 --- a/examples/dfp/v201805/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -27,7 +27,7 @@ def main(client, rate_card_id): premium_rate_service = client.GetService( 'PremiumRateService', version='v201805') # Create a statement to select premium rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) @@ -52,5 +52,5 @@ def main(client, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201805/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py similarity index 93% rename from examples/dfp/v201805/premium_rate_service/update_premium_rates.py rename to examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py index f762c9bd..68c26b5e 100755 --- a/examples/dfp/v201805/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' @@ -33,7 +33,7 @@ def main(client, premium_rate_id): version='v201805') # Create statement object to select a single proposal by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(premium_rate_id)) @@ -83,5 +83,5 @@ def main(client, premium_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PREMIUM_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PREMIUM_RATE_ID) diff --git a/examples/dfp/v201805/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201805/product_package_item_service/create_product_package_item.py similarity index 94% rename from examples/dfp/v201805/product_package_item_service/create_product_package_item.py rename to examples/ad_manager/v201805/product_package_item_service/create_product_package_item.py index 9ff0f6a9..e7615951 100755 --- a/examples/dfp/v201805/product_package_item_service/create_product_package_item.py +++ b/examples/ad_manager/v201805/product_package_item_service/create_product_package_item.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the product package to add product package items to. PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -58,5 +58,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py similarity index 91% rename from examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py rename to examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py index a8b381be..dc729e92 100755 --- a/examples/dfp/v201805/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ProductPackageItemService', version='v201805') # Create a statement to select product package items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. @@ -49,5 +49,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py similarity index 91% rename from examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py index 9e303462..e813765c 100755 --- a/examples/dfp/v201805/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -27,7 +27,7 @@ def main(client, product_package_id): product_package_item_service = client.GetService( 'ProductPackageItemService', version='v201805') # Create a statement to select product package items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('productPackageId = :productPackageId') .WithBindVariable('productPackageId', product_package_id)) @@ -52,5 +52,5 @@ def main(client, product_package_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_PACKAGE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_PACKAGE_ID) diff --git a/examples/dfp/v201805/product_package_service/create_product_packages.py b/examples/ad_manager/v201805/product_package_service/create_product_packages.py similarity index 92% rename from examples/dfp/v201805/product_package_service/create_product_packages.py rename to examples/ad_manager/v201805/product_package_service/create_product_packages.py index 02418960..7470acbe 100755 --- a/examples/dfp/v201805/product_package_service/create_product_packages.py +++ b/examples/ad_manager/v201805/product_package_service/create_product_packages.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the ID of the rate card to associate with the product package. RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201805/product_package_service/get_active_product_packages.py similarity index 91% rename from examples/dfp/v201805/product_package_service/get_active_product_packages.py rename to examples/ad_manager/v201805/product_package_service/get_active_product_packages.py index 0eae55a9..d4bfabfa 100755 --- a/examples/dfp/v201805/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201805/product_package_service/get_active_product_packages.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): product_package_service = client.GetService( 'ProductPackageService', version='v201805') # Create a statement to select product packages. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201805/product_package_service/get_all_product_packages.py similarity index 90% rename from examples/dfp/v201805/product_package_service/get_all_product_packages.py rename to examples/ad_manager/v201805/product_package_service/get_all_product_packages.py index 4b948204..cdfb079a 100755 --- a/examples/dfp/v201805/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201805/product_package_service/get_all_product_packages.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ProductPackageService', version='v201805') # Create a statement to select product packages. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/product_service/__init__.py b/examples/ad_manager/v201805/product_service/__init__.py similarity index 100% rename from examples/dfp/v201802/product_service/__init__.py rename to examples/ad_manager/v201805/product_service/__init__.py diff --git a/examples/dfp/v201805/product_service/get_all_products.py b/examples/ad_manager/v201805/product_service/get_all_products.py similarity index 90% rename from examples/dfp/v201805/product_service/get_all_products.py rename to examples/ad_manager/v201805/product_service/get_all_products.py index b9045479..6a2c765b 100755 --- a/examples/dfp/v201805/product_service/get_all_products.py +++ b/examples/ad_manager/v201805/product_service/get_all_products.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): product_service = client.GetService('ProductService', version='v201805') # Create a statement to select products. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_service/get_products_for_product_template.py b/examples/ad_manager/v201805/product_service/get_products_for_product_template.py similarity index 90% rename from examples/dfp/v201805/product_service/get_products_for_product_template.py rename to examples/ad_manager/v201805/product_service/get_products_for_product_template.py index 43b44cfe..be88fe10 100755 --- a/examples/dfp/v201805/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201805/product_service/get_products_for_product_template.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' @@ -27,7 +27,7 @@ def main(client, product_template_id): product_service = client.GetService('ProductService', version='v201805') # Create a statement to select products. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('productTemplateId = :productTemplateId') .WithBindVariable('productTemplateId', product_template_id)) @@ -49,5 +49,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201805/product_service/update_products.py b/examples/ad_manager/v201805/product_service/update_products.py similarity index 91% rename from examples/dfp/v201805/product_service/update_products.py rename to examples/ad_manager/v201805/product_service/update_products.py index 4b0f4036..ecb757bc 100755 --- a/examples/dfp/v201805/product_service/update_products.py +++ b/examples/ad_manager/v201805/product_service/update_products.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' @@ -32,7 +32,7 @@ def main(client, product_id): product_service = client.GetService('ProductService', version='v201805') # Create statement object to select a single product by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(product_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, product_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_ID) diff --git a/examples/dfp/v201802/product_template_service/__init__.py b/examples/ad_manager/v201805/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201802/product_template_service/__init__.py rename to examples/ad_manager/v201805/product_template_service/__init__.py diff --git a/examples/dfp/v201805/product_template_service/activate_product_templates.py b/examples/ad_manager/v201805/product_template_service/activate_product_templates.py similarity index 92% rename from examples/dfp/v201805/product_template_service/activate_product_templates.py rename to examples/ad_manager/v201805/product_template_service/activate_product_templates.py index 824e2ba1..073b28b1 100755 --- a/examples/dfp/v201805/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/activate_product_templates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the product template to activate. PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' @@ -34,7 +34,7 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(product_template_id)) .Limit(1)) @@ -70,5 +70,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201805/product_template_service/create_product_templates.py b/examples/ad_manager/v201805/product_template_service/create_product_templates.py similarity index 96% rename from examples/dfp/v201805/product_template_service/create_product_templates.py rename to examples/ad_manager/v201805/product_template_service/create_product_templates.py index 180a9ed2..0ab720cc 100755 --- a/examples/dfp/v201805/product_template_service/create_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/create_product_templates.py @@ -22,7 +22,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -105,5 +105,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201805/product_template_service/create_programmatic_product_templates.py similarity index 95% rename from examples/dfp/v201805/product_template_service/create_programmatic_product_templates.py rename to examples/ad_manager/v201805/product_template_service/create_programmatic_product_templates.py index da6c8ac8..a52d0999 100755 --- a/examples/dfp/v201805/product_template_service/create_programmatic_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/create_programmatic_product_templates.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -87,5 +87,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201805/product_template_service/get_all_product_templates.py similarity index 90% rename from examples/dfp/v201805/product_template_service/get_all_product_templates.py rename to examples/ad_manager/v201805/product_template_service/get_all_product_templates.py index e82e198f..98ec8e8f 100755 --- a/examples/dfp/v201805/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/get_all_product_templates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ProductTemplateService', version='v201805') # Create a statement to select product templates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py similarity index 91% rename from examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py rename to examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py index bb561a90..be96c091 100755 --- a/examples/dfp/v201805/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): product_template_service = client.GetService( 'ProductTemplateService', version='v201805') # Create a statement to select product templates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemType = :lineItemType') .WithBindVariable('lineItemType', 'SPONSORSHIP')) @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_template_service/update_product_templates.py b/examples/ad_manager/v201805/product_template_service/update_product_templates.py similarity index 93% rename from examples/dfp/v201805/product_template_service/update_product_templates.py rename to examples/ad_manager/v201805/product_template_service/update_product_templates.py index 29a137b6..56109f0f 100755 --- a/examples/dfp/v201805/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/update_product_templates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' @@ -33,7 +33,7 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201805') # Create a statement to select a single product template by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(product_template_id)) @@ -90,5 +90,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201802/proposal_line_item_service/__init__.py b/examples/ad_manager/v201805/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201802/proposal_line_item_service/__init__.py rename to examples/ad_manager/v201805/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py similarity index 92% rename from examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py index 2d8495e8..0740b6c6 100755 --- a/examples/dfp/v201805/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the proposal line item to archive. PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' @@ -34,7 +34,7 @@ def main(client, proposal_line_item_id): 'ProposalLineItemService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) @@ -72,5 +72,5 @@ def main(client, proposal_line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 95% rename from examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py index a42f6dd1..85074dd9 100755 --- a/examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -22,7 +22,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set the ID of the programmatic proposal that the proposal line item will @@ -99,6 +99,6 @@ def main(client, proposal_id, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 95% rename from examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 23456dc5..ef3d2264 100755 --- a/examples/dfp/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -22,7 +22,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set proposal that the created proposal line item will belong to. @@ -105,6 +105,6 @@ def main(client, proposal_id, product_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID) diff --git a/examples/dfp/v201805/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201805/proposal_line_item_service/create_proposal_line_items.py similarity index 95% rename from examples/dfp/v201805/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v201805/proposal_line_item_service/create_proposal_line_items.py index 4ea8e9b4..29b2c63d 100755 --- a/examples/dfp/v201805/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/create_proposal_line_items.py @@ -26,7 +26,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set proposal that the created proposal line item will belong to. @@ -100,6 +100,6 @@ def main(client, proposal_id, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py similarity index 90% rename from examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py index c94464d0..25471ee2 100755 --- a/examples/dfp/v201805/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ProposalLineItemService', version='v201805') # Create a statement to select proposal line items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 91% rename from examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 8341ee11..771d0771 100755 --- a/examples/dfp/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -27,7 +27,7 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( 'ProposalLineItemService', version='v201805') # Create a statement to select proposal line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) @@ -50,5 +50,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py similarity index 92% rename from examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py index 5f5fbb2c..96839e50 100755 --- a/examples/dfp/v201805/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the proposal line item to update. PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' @@ -35,7 +35,7 @@ def main(client, proposal_line_item_id): # Create statement to select a proposal line item. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) @@ -68,5 +68,5 @@ def main(client, proposal_line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201802/proposal_service/__init__.py b/examples/ad_manager/v201805/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201802/proposal_service/__init__.py rename to examples/ad_manager/v201805/proposal_service/__init__.py diff --git a/examples/dfp/v201805/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201805/proposal_service/create_programmatic_proposals.py similarity index 91% rename from examples/dfp/v201805/proposal_service/create_programmatic_proposals.py rename to examples/ad_manager/v201805/proposal_service/create_programmatic_proposals.py index d72aafc6..94c5a19a 100755 --- a/examples/dfp/v201805/proposal_service/create_programmatic_proposals.py +++ b/examples/ad_manager/v201805/proposal_service/create_programmatic_proposals.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -66,6 +66,6 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID, - BUYER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID, BUYER_ID) diff --git a/examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 92% rename from examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/ad_manager/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py index f3a8e02f..6b0910b0 100755 --- a/examples/dfp/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/ad_manager/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -63,6 +63,6 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID, ADVERTISER_ID) diff --git a/examples/dfp/v201805/proposal_service/create_proposals.py b/examples/ad_manager/v201805/proposal_service/create_proposals.py similarity index 93% rename from examples/dfp/v201805/proposal_service/create_proposals.py rename to examples/ad_manager/v201805/proposal_service/create_proposals.py index 6cf119ac..a08d39c0 100755 --- a/examples/dfp/v201805/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201805/proposal_service/create_proposals.py @@ -23,7 +23,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -72,6 +72,6 @@ def main(client, advertiser_id, primary_salesperson_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201805/proposal_service/get_all_proposals.py b/examples/ad_manager/v201805/proposal_service/get_all_proposals.py similarity index 90% rename from examples/dfp/v201805/proposal_service/get_all_proposals.py rename to examples/ad_manager/v201805/proposal_service/get_all_proposals.py index d527624c..8a023971 100755 --- a/examples/dfp/v201805/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201805/proposal_service/get_all_proposals.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201805') # Create a statement to select proposals. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201805/proposal_service/get_marketplace_comments.py similarity index 93% rename from examples/dfp/v201805/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v201805/proposal_service/get_marketplace_comments.py index 72d835d4..24651638 100755 --- a/examples/dfp/v201805/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201805/proposal_service/get_marketplace_comments.py @@ -19,7 +19,7 @@ # Import appropriate modules from the client library. from datetime import datetime -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -52,5 +52,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py similarity index 90% rename from examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py rename to examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py index 823682b7..b28d04cf 100755 --- a/examples/dfp/v201805/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. proposal_service = client.GetService('ProposalService', version='v201805') # Create a statement to select proposals. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'PENDING_APPROVAL')) @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py similarity index 92% rename from examples/dfp/v201805/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py index 3029f868..9af78bce 100755 --- a/examples/dfp/v201805/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py @@ -19,7 +19,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -29,7 +29,7 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 @@ -63,5 +63,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py similarity index 92% rename from examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py rename to examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py index 1afca216..7b946b15 100755 --- a/examples/dfp/v201805/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -31,7 +31,7 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 @@ -63,5 +63,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201805/proposal_service/update_proposals.py b/examples/ad_manager/v201805/proposal_service/update_proposals.py similarity index 92% rename from examples/dfp/v201805/proposal_service/update_proposals.py rename to examples/ad_manager/v201805/proposal_service/update_proposals.py index 0223aff6..9dfdd4d5 100755 --- a/examples/dfp/v201805/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201805/proposal_service/update_proposals.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -32,7 +32,7 @@ def main(client, proposal_id): # Create statement object to select a single proposal by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', long(proposal_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201802/publisher_query_language_service/__init__.py b/examples/ad_manager/v201805/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201802/publisher_query_language_service/__init__.py rename to examples/ad_manager/v201805/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201805/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201805/publisher_query_language_service/fetch_match_tables.py similarity index 93% rename from examples/dfp/v201805/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v201805/publisher_query_language_service/fetch_match_tables.py index 9d1c1c42..aa4fee56 100755 --- a/examples/dfp/v201805/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201805/publisher_query_language_service/fetch_match_tables.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201805/publisher_query_language_service/get_all_browsers.py similarity index 93% rename from examples/dfp/v201805/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v201805/publisher_query_language_service/get_all_browsers.py index 794362d6..4f60f1ca 100755 --- a/examples/dfp/v201805/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201805/publisher_query_language_service/get_all_browsers.py @@ -27,7 +27,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201805/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 92% rename from examples/dfp/v201805/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v201805/publisher_query_language_service/get_all_programmatic_buyers.py index cf7d6e7d..d499f3a0 100755 --- a/examples/dfp/v201805/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201805/publisher_query_language_service/get_all_programmatic_buyers.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201805/publisher_query_language_service/get_geo_targets.py similarity index 92% rename from examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v201805/publisher_query_language_service/get_geo_targets.py index 57393963..ef29ba84 100755 --- a/examples/dfp/v201805/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201805/publisher_query_language_service/get_geo_targets.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the type of geo target to query for. GEO_TARGET_TYPE = 'City' @@ -49,5 +49,5 @@ def main(client, geo_target_type): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, GEO_TARGET_TYPE) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, GEO_TARGET_TYPE) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201805/publisher_query_language_service/get_line_items_named_like.py similarity index 92% rename from examples/dfp/v201805/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v201805/publisher_query_language_service/get_line_items_named_like.py index 6948300b..62d2f3bc 100755 --- a/examples/dfp/v201805/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201805/publisher_query_language_service/get_line_items_named_like.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -44,5 +44,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py similarity index 95% rename from examples/dfp/v201805/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py index a312739b..19239f2e 100755 --- a/examples/dfp/v201805/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py @@ -25,7 +25,7 @@ from datetime import timedelta # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') @@ -105,7 +105,7 @@ def ConvertValueForCsv(pql_value): return ','.join(['"%s"' % str(ConvertValueForCsv(single_field)) for single_field in field]) else: - class_type = dfp.DfpClassType(pql_value) + class_type = ad_manager.AdManagerClassType(pql_value) if class_type == 'TextValue': return field.replace('"', '""').encode('UTF8') @@ -152,5 +152,5 @@ def ConvertDateTimeToOffset(date_time_value): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/rate_card_service/__init__.py b/examples/ad_manager/v201805/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201802/rate_card_service/__init__.py rename to examples/ad_manager/v201805/rate_card_service/__init__.py diff --git a/examples/dfp/v201805/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201805/rate_card_service/create_rate_cards.py similarity index 93% rename from examples/dfp/v201805/rate_card_service/create_rate_cards.py rename to examples/ad_manager/v201805/rate_card_service/create_rate_cards.py index 1293a26b..8615af6a 100755 --- a/examples/dfp/v201805/rate_card_service/create_rate_cards.py +++ b/examples/ad_manager/v201805/rate_card_service/create_rate_cards.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the IDs of the teams this rate card should be visible to. TEAM_IDS = ['INSERT_TEAM_ID_HERE'] @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py similarity index 90% rename from examples/dfp/v201805/rate_card_service/get_all_rate_cards.py rename to examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py index 929e8027..271a03d4 100755 --- a/examples/dfp/v201805/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): rate_card_service = client.GetService('RateCardService', version='v201805') # Create a statement to select rate cards. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py similarity index 91% rename from examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py rename to examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py index 0cc204a2..0258ee75 100755 --- a/examples/dfp/v201805/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py @@ -18,14 +18,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. rate_card_service = client.GetService('RateCardService', version='v201805') # Create a statement to select rate cards. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('forMarketplace = :forMarketplace') .WithBindVariable('forMarketplace', True)) @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 94% rename from examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 05138495..a9a5d47f 100755 --- a/examples/dfp/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report to query. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -33,7 +33,7 @@ def main(client): 'ReconciliationLineItemReportService', version='v201805')) # Create a statement to select reconciliation line item reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('reconciliationReportId = :reconciliationReportId AND ' 'lineItemId != :lineItemId')) .OrderBy('lineItemId', ascending=True) @@ -71,5 +71,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 91% rename from examples/dfp/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 25eb176c..8b07cbdc 100755 --- a/examples/dfp/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation line item report to update. RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' @@ -33,7 +33,7 @@ def main(client): 'ReconciliationLineItemReportService', version='v201805')) # Create a statement to select a reconciliation line item report. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :lineItemReportId') .OrderBy('id', ascending=True) .Limit(1) @@ -47,7 +47,7 @@ def main(client): line_item_report = page['results'][0] # Set and use a manual volume for billing. This example splits the difference - # between DFP and the third party volume. + # between Ad Manager and the third party volume. line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + line_item_report['thirdPartyVolume']) / 2 line_item_report['reconciliationSource'] = 'MANUAL' @@ -63,5 +63,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 91% rename from examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 6ecdb7b9..bfbddf81 100755 --- a/examples/dfp/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -27,7 +27,7 @@ def main(client, reconciliation_report_id): reconciliation_order_report_service = client.GetService( 'ReconciliationOrderReportService', version='v201805') # Create a statement to select reconciliation order reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('reconciliationReportId = :reconciliationReportId') .WithBindVariable('reconciliationReportId', reconciliation_report_id)) @@ -54,5 +54,5 @@ def main(client, reconciliation_report_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 93% rename from examples/dfp/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 1ad5a015..711f4b90 100755 --- a/examples/dfp/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation order report to submit. RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' @@ -33,7 +33,7 @@ def main(client): 'ReconciliationOrderReportService', version='v201805')) # Create a statement to select reconciliation order reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -67,5 +67,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 89% rename from examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index f0a9cdba..22727432 100755 --- a/examples/dfp/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Gets a reconciliation report's rows for line items that served through DFP. +"""Gets a reconciliation report's rows for line items that Ad Manager served. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -30,7 +30,7 @@ def main(client, reconciliation_report_id): 'ReconciliationReportRowService', version='v201805') # Create a statement to select reconciliation report rows. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) @@ -60,5 +60,5 @@ def main(client, reconciliation_report_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 94% rename from examples/dfp/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py index 1afe7030..b67a6a27 100755 --- a/examples/dfp/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' @@ -36,7 +36,7 @@ def main(client): 'ReconciliationReportRowService', version='v201805')) # Create a statement to select reconciliation report rows. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('id = :reconciliationReportRowId AND ' 'reconciliationReportId = :reconciliationReportId')) .OrderBy('id', ascending=True) @@ -71,5 +71,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 91% rename from examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py index 9e8745d3..b23efe61 100755 --- a/examples/dfp/v201805/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'ReconciliationReportService', version='v201805') # Create a statement to select reconciliation reports. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. @@ -52,5 +52,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 92% rename from examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 9d80f156..8890b92f 100755 --- a/examples/dfp/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -20,7 +20,7 @@ from datetime import date from datetime import timedelta -from googleads import dfp +from googleads import ad_manager def main(client): @@ -32,7 +32,7 @@ def main(client): last_month = first_of_the_month - timedelta(days=1) # Create a statement to select reconciliation reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('startDate = :startDate') .WithBindVariable('startDate', last_month)) @@ -59,5 +59,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201802/report_service/__init__.py b/examples/ad_manager/v201805/report_service/__init__.py similarity index 100% rename from examples/dfp/v201802/report_service/__init__.py rename to examples/ad_manager/v201805/report_service/__init__.py diff --git a/examples/dfp/v201805/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201805/report_service/run_ad_exchange_report.py similarity index 89% rename from examples/dfp/v201805/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v201805/report_service/run_ad_exchange_report.py index e68a20ef..b66e6606 100755 --- a/examples/dfp/v201805/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201805/report_service/run_ad_exchange_report.py @@ -14,12 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report on Ad Exchange data via the DFP API.""" +"""Runs a report on Ad Exchange data via the Ad Manager API.""" import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors @@ -42,7 +42,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/report_service/run_delivery_report.py b/examples/ad_manager/v201805/report_service/run_delivery_report.py similarity index 90% rename from examples/dfp/v201805/report_service/run_delivery_report.py rename to examples/ad_manager/v201805/report_service/run_delivery_report.py index ae9857e8..5465a321 100755 --- a/examples/dfp/v201805/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201805/report_service/run_delivery_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report similar to the "Orders report" on the DFP website. +"""Runs a report similar to the "Orders report" on the Ad Manager website. Includes additional attributes and can filter to include just one order. """ @@ -24,7 +24,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('ORDER_ID = :id') .WithBindVariable('id', long(order_id)) .Limit(None) # No limit or offset for reports @@ -64,7 +64,7 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -84,5 +84,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201805/report_service/run_inventory_report.py b/examples/ad_manager/v201805/report_service/run_inventory_report.py similarity index 92% rename from examples/dfp/v201805/report_service/run_inventory_report.py rename to examples/ad_manager/v201805/report_service/run_inventory_report.py index 410f3392..34d23871 100755 --- a/examples/dfp/v201805/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201805/report_service/run_inventory_report.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors @@ -34,7 +34,7 @@ def main(client): network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) .Limit(None) # No limit or offset for reports @@ -58,7 +58,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -78,5 +78,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/report_service/run_reach_report.py b/examples/ad_manager/v201805/report_service/run_reach_report.py similarity index 91% rename from examples/dfp/v201805/report_service/run_reach_report.py rename to examples/ad_manager/v201805/report_service/run_reach_report.py index 8d0af11f..9b4b3836 100755 --- a/examples/dfp/v201805/report_service/run_reach_report.py +++ b/examples/ad_manager/v201805/report_service/run_reach_report.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors @@ -39,7 +39,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -60,5 +60,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201805/report_service/run_report_and_create_match_table.py similarity index 94% rename from examples/dfp/v201805/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v201805/report_service/run_report_and_create_match_table.py index cab552c7..d3d67281 100755 --- a/examples/dfp/v201805/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201805/report_service/run_report_and_create_match_table.py @@ -26,7 +26,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors try: @@ -59,7 +59,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e with tempfile.NamedTemporaryFile( @@ -84,5 +84,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py similarity index 93% rename from examples/dfp/v201805/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py index 0a80e0f9..c3e6a79a 100755 --- a/examples/dfp/v201805/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors # Set the ID of the order to get line items from. @@ -33,7 +33,7 @@ def main(client, order_id): report_downloader = client.GetDataDownloader(version='v201805') # Filter for line items of a given order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('orderId = :orderId') .WithBindVariable('orderId', long(order_id))) @@ -73,7 +73,7 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -93,5 +93,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201805/report_service/run_sales_report.py b/examples/ad_manager/v201805/report_service/run_sales_report.py similarity index 91% rename from examples/dfp/v201805/report_service/run_sales_report.py rename to examples/ad_manager/v201805/report_service/run_sales_report.py index 30587088..c46e55e8 100755 --- a/examples/dfp/v201805/report_service/run_sales_report.py +++ b/examples/ad_manager/v201805/report_service/run_sales_report.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors @@ -40,7 +40,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -60,5 +60,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/report_service/run_saved_query.py b/examples/ad_manager/v201805/report_service/run_saved_query.py similarity index 91% rename from examples/dfp/v201805/report_service/run_saved_query.py rename to examples/ad_manager/v201805/report_service/run_saved_query.py index 7d098948..0774d948 100755 --- a/examples/dfp/v201805/report_service/run_saved_query.py +++ b/examples/ad_manager/v201805/report_service/run_saved_query.py @@ -20,7 +20,7 @@ # Import appropriate modules from the client library. import tempfile -from googleads import dfp +from googleads import ad_manager from googleads import errors SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' @@ -34,7 +34,7 @@ def main(client, saved_query_id): report_downloader = client.GetDataDownloader(version='v201805') # Create statement object to filter for an order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(saved_query_id)) .Limit(1)) @@ -54,7 +54,7 @@ def main(client, saved_query_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -76,5 +76,5 @@ def main(client, saved_query_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, SAVED_QUERY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, SAVED_QUERY_ID) diff --git a/examples/dfp/v201802/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201805/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201802/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v201805/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 90% rename from examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 9054bd60..e2a9accd 100755 --- a/examples/dfp/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -16,12 +16,12 @@ """This code example approves all suggested ad units with 50 or more requests. -This feature is only available to DFP premium solution networks. +This feature is only available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager THRESHOLD_NUMBER_OF_REQUESTS = '50' @@ -32,7 +32,7 @@ def main(client): 'SuggestedAdUnitService', version='v201805') # Create a filter statement. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 @@ -65,6 +65,6 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 91% rename from examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py index e27bde77..006b9fa9 100755 --- a/examples/dfp/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'SuggestedAdUnitService', version='v201805') # Create a statement to select suggested ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 91% rename from examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index a9e4a499..d2c18ee3 100755 --- a/examples/dfp/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE' @@ -27,7 +27,7 @@ def main(client, num_requests): suggested_ad_unit_service = client.GetService( 'SuggestedAdUnitService', version='v201805') # Create a statement to select suggested ad units. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', long(num_requests))) @@ -51,5 +51,5 @@ def main(client, num_requests): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, NUM_REQUESTS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, NUM_REQUESTS) diff --git a/examples/dfp/v201802/team_service/__init__.py b/examples/ad_manager/v201805/team_service/__init__.py similarity index 100% rename from examples/dfp/v201802/team_service/__init__.py rename to examples/ad_manager/v201805/team_service/__init__.py diff --git a/examples/dfp/v201805/team_service/create_teams.py b/examples/ad_manager/v201805/team_service/create_teams.py similarity index 92% rename from examples/dfp/v201805/team_service/create_teams.py rename to examples/ad_manager/v201805/team_service/create_teams.py index 47f77d78..06cc7a9e 100755 --- a/examples/dfp/v201805/team_service/create_teams.py +++ b/examples/ad_manager/v201805/team_service/create_teams.py @@ -28,7 +28,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/team_service/get_all_teams.py b/examples/ad_manager/v201805/team_service/get_all_teams.py similarity index 90% rename from examples/dfp/v201805/team_service/get_all_teams.py rename to examples/ad_manager/v201805/team_service/get_all_teams.py index b4acc6f1..61e9dc6d 100755 --- a/examples/dfp/v201805/team_service/get_all_teams.py +++ b/examples/ad_manager/v201805/team_service/get_all_teams.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): team_service = client.GetService('TeamService', version='v201805') # Create a statement to select teams. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/team_service/update_teams.py b/examples/ad_manager/v201805/team_service/update_teams.py similarity index 92% rename from examples/dfp/v201805/team_service/update_teams.py rename to examples/ad_manager/v201805/team_service/update_teams.py index 9f16cd11..a5cc9678 100755 --- a/examples/dfp/v201805/team_service/update_teams.py +++ b/examples/ad_manager/v201805/team_service/update_teams.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager TEAM_ID = 'INSERT_TEAM_ID_HERE' @@ -37,7 +37,7 @@ def main(client, team_id): team_service = client.GetService('TeamService', version='v201805') # Create a filter statement to select a single team by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :teamId') .WithBindVariable('teamId', long(team_id))) @@ -64,5 +64,5 @@ def main(client, team_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TEAM_ID) diff --git a/examples/dfp/v201802/user_service/__init__.py b/examples/ad_manager/v201805/user_service/__init__.py similarity index 100% rename from examples/dfp/v201802/user_service/__init__.py rename to examples/ad_manager/v201805/user_service/__init__.py diff --git a/examples/dfp/v201805/user_service/create_users.py b/examples/ad_manager/v201805/user_service/create_users.py similarity index 90% rename from examples/dfp/v201805/user_service/create_users.py rename to examples/ad_manager/v201805/user_service/create_users.py index b84079c4..f0645906 100755 --- a/examples/dfp/v201805/user_service/create_users.py +++ b/examples/ad_manager/v201805/user_service/create_users.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' NEW_USER_NAME = 'INSERT_NAME_HERE' @@ -53,5 +53,5 @@ def main(client, email, name): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) diff --git a/examples/dfp/v201805/user_service/deactivate_users.py b/examples/ad_manager/v201805/user_service/deactivate_users.py similarity index 91% rename from examples/dfp/v201805/user_service/deactivate_users.py rename to examples/ad_manager/v201805/user_service/deactivate_users.py index 7b9ac397..e5c8dc03 100755 --- a/examples/dfp/v201805/user_service/deactivate_users.py +++ b/examples/ad_manager/v201805/user_service/deactivate_users.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE' @@ -33,7 +33,7 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :userId') .WithBindVariable('userId', long(user_id))) @@ -61,5 +61,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201802/user_service/get_all_roles.py b/examples/ad_manager/v201805/user_service/get_all_roles.py similarity index 90% rename from examples/dfp/v201802/user_service/get_all_roles.py rename to examples/ad_manager/v201805/user_service/get_all_roles.py index bb2bec62..442d35bd 100755 --- a/examples/dfp/v201802/user_service/get_all_roles.py +++ b/examples/ad_manager/v201805/user_service/get_all_roles.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -36,5 +36,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/user_service/get_all_users.py b/examples/ad_manager/v201805/user_service/get_all_users.py similarity index 90% rename from examples/dfp/v201805/user_service/get_all_users.py rename to examples/ad_manager/v201805/user_service/get_all_users.py index 76444f71..5b0f46ff 100755 --- a/examples/dfp/v201805/user_service/get_all_users.py +++ b/examples/ad_manager/v201805/user_service/get_all_users.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -25,7 +25,7 @@ def main(client): user_service = client.GetService('UserService', version='v201805') # Create a statement to select users. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/user_service/get_current_user.py b/examples/ad_manager/v201805/user_service/get_current_user.py similarity index 90% rename from examples/dfp/v201805/user_service/get_current_user.py rename to examples/ad_manager/v201805/user_service/get_current_user.py index 2eace62d..4b4f1907 100755 --- a/examples/dfp/v201805/user_service/get_current_user.py +++ b/examples/ad_manager/v201805/user_service/get_current_user.py @@ -17,7 +17,7 @@ """This example gets the current user.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -35,5 +35,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/user_service/get_user_by_email_address.py b/examples/ad_manager/v201805/user_service/get_user_by_email_address.py similarity index 90% rename from examples/dfp/v201805/user_service/get_user_by_email_address.py rename to examples/ad_manager/v201805/user_service/get_user_by_email_address.py index 45c993dc..040f59d1 100755 --- a/examples/dfp/v201805/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201805/user_service/get_user_by_email_address.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' @@ -26,7 +26,7 @@ def main(client, email_address): # Initialize appropriate service. user_service = client.GetService('UserService', version='v201805') # Create a statement to select users. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('email = :email') .WithBindVariable('email', email_address)) @@ -48,5 +48,5 @@ def main(client, email_address): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, EMAIL_ADDRESS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, EMAIL_ADDRESS) diff --git a/examples/dfp/v201805/user_service/update_users.py b/examples/ad_manager/v201805/user_service/update_users.py similarity index 90% rename from examples/dfp/v201805/user_service/update_users.py rename to examples/ad_manager/v201805/user_service/update_users.py index 2a00295f..e8482754 100755 --- a/examples/dfp/v201805/user_service/update_users.py +++ b/examples/ad_manager/v201805/user_service/update_users.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' @@ -31,7 +31,7 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201805') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :userId') .WithBindVariable('userId', long(user_id))) @@ -54,5 +54,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201802/user_team_association_service/__init__.py b/examples/ad_manager/v201805/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201802/user_team_association_service/__init__.py rename to examples/ad_manager/v201805/user_team_association_service/__init__.py diff --git a/examples/dfp/v201805/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201805/user_team_association_service/create_user_team_associations.py similarity index 93% rename from examples/dfp/v201805/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v201805/user_team_association_service/create_user_team_associations.py index 77f34cb4..dad08b20 100755 --- a/examples/dfp/v201805/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201805/user_team_association_service/create_user_team_associations.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager TEAM_ID = 'INSERT_TEAM_ID_HERE' USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE'] @@ -63,5 +63,5 @@ def main(client, team_id, user_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID, USER_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TEAM_ID, USER_IDS) diff --git a/examples/dfp/v201805/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py similarity index 93% rename from examples/dfp/v201805/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py index d591f5e9..c0503538 100755 --- a/examples/dfp/v201805/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_HERE' @@ -38,7 +38,7 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201805') # Create filter text to select user team associations by the user ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -73,5 +73,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py similarity index 91% rename from examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py index d7b92bd2..49f883c4 100755 --- a/examples/dfp/v201805/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -26,7 +26,7 @@ def main(client): 'UserTeamAssociationService', version='v201805') # Create a statement to select user team associations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py similarity index 91% rename from examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py index 81d4c05f..2d3c8e44 100755 --- a/examples/dfp/v201805/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_HERE' @@ -27,7 +27,7 @@ def main(client, user_id): user_team_association_service = client.GetService( 'UserTeamAssociationService', version='v201805') # Create a statement to select user team associations. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -51,5 +51,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201805/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py similarity index 93% rename from examples/dfp/v201805/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py index feb1d792..fe8886c8 100755 --- a/examples/dfp/v201805/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' @@ -40,7 +40,7 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201805') # Create filter text to select user team associations by the user ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -74,5 +74,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201802/workflow_request_service/__init__.py b/examples/ad_manager/v201805/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201802/workflow_request_service/__init__.py rename to examples/ad_manager/v201805/workflow_request_service/__init__.py diff --git a/examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py similarity index 93% rename from examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py rename to examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py index 6ed95c5d..46591dc7 100755 --- a/examples/dfp/v201805/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -34,7 +34,7 @@ def main(client, proposal_id): version='v201805') # Create a filter statement. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) @@ -71,5 +71,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py similarity index 92% rename from examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py rename to examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py index 9fbaccdc..239b6be3 100755 --- a/examples/dfp/v201805/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -28,7 +28,7 @@ def main(client): workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201805') # Create a statement to select workflow requests. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py similarity index 92% rename from examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py index 41c828e2..2566ffbd 100755 --- a/examples/dfp/v201805/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -28,7 +28,7 @@ def main(client): workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201805') # Create a statement to select workflow requests. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 94% rename from examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py index 5fd72a9c..f5c6d59d 100755 --- a/examples/dfp/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -34,7 +34,7 @@ def main(client, proposal_id): version='v201805') # Create a filter statement. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) @@ -74,5 +74,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201805/activity_group_service/__init__.py b/examples/ad_manager/v201808/activity_group_service/__init__.py similarity index 100% rename from examples/dfp/v201805/activity_group_service/__init__.py rename to examples/ad_manager/v201808/activity_group_service/__init__.py diff --git a/examples/dfp/v201711/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/create_activity_groups.py similarity index 91% rename from examples/dfp/v201711/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v201808/activity_group_service/create_activity_groups.py index cba5979e..195585f0 100755 --- a/examples/dfp/v201711/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201808/activity_group_service/create_activity_groups.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the advertiser company this activity group is associated with. ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201711') + version='v201808') # Create a short-term activity group. short_term_activity_group = { @@ -67,5 +67,5 @@ def main(client, advertiser_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_COMPANY_ID) diff --git a/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py similarity index 86% rename from examples/dfp/v201711/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py index 299400e3..671c98e9 100755 --- a/examples/dfp/v201711/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201711') + 'ActivityGroupService', version='v201808') # Create a statement to select activity groups. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -39,7 +39,7 @@ def main(client): # Print out some information for each activity group. print('Activity group with ID "%d" and name "%s" was found.\n' % (activity_group['id'], activity_group['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py similarity index 88% rename from examples/dfp/v201711/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py index 85724d16..a8292b86 100755 --- a/examples/dfp/v201711/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201711') + 'ActivityGroupService', version='v201808') # Create a statement to select activity groups. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py similarity index 89% rename from examples/dfp/v201711/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v201808/activity_group_service/update_activity_groups.py index 2eca7bac..88cb3bc8 100755 --- a/examples/dfp/v201711/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity group and the company to update it with. ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201711') + version='v201808') # Create statement object to select a single activity groups by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', long(activity_group_id)) .Limit(1)) @@ -66,5 +66,5 @@ def main(client, activity_group_id, advertiser_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) diff --git a/examples/dfp/v201805/activity_service/__init__.py b/examples/ad_manager/v201808/activity_service/__init__.py similarity index 100% rename from examples/dfp/v201805/activity_service/__init__.py rename to examples/ad_manager/v201808/activity_service/__init__.py diff --git a/examples/dfp/v201711/activity_service/create_activities.py b/examples/ad_manager/v201808/activity_service/create_activities.py similarity index 92% rename from examples/dfp/v201711/activity_service/create_activities.py rename to examples/ad_manager/v201808/activity_service/create_activities.py index 3926d5c0..ac07336c 100755 --- a/examples/dfp/v201711/activity_service/create_activities.py +++ b/examples/ad_manager/v201808/activity_service/create_activities.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity group this activity is associated with. ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201711') + activity_service = client.GetService('ActivityService', version='v201808') # Create a daily visits activity. daily_visits_activity = { @@ -64,5 +64,5 @@ def main(client, activity_group_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_GROUP_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_GROUP_ID) diff --git a/examples/dfp/v201711/activity_service/get_active_activities.py b/examples/ad_manager/v201808/activity_service/get_active_activities.py similarity index 88% rename from examples/dfp/v201711/activity_service/get_active_activities.py rename to examples/ad_manager/v201808/activity_service/get_active_activities.py index 388c45d3..5d78d3d0 100755 --- a/examples/dfp/v201711/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201808/activity_service/get_active_activities.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201711') + activity_service = client.GetService('ActivityService', version='v201808') # Create a statement to select activities. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -38,7 +38,7 @@ def main(client): # Print out some information for each activity. print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % (activity['id'], activity['name'], activity['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/activity_service/get_all_activities.py b/examples/ad_manager/v201808/activity_service/get_all_activities.py similarity index 89% rename from examples/dfp/v201711/activity_service/get_all_activities.py rename to examples/ad_manager/v201808/activity_service/get_all_activities.py index 8c110756..d949f570 100755 --- a/examples/dfp/v201711/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201808/activity_service/get_all_activities.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201711') + activity_service = client.GetService('ActivityService', version='v201808') # Create a statement to select activities. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/activity_service/update_activities.py b/examples/ad_manager/v201808/activity_service/update_activities.py similarity index 91% rename from examples/dfp/v201711/activity_service/update_activities.py rename to examples/ad_manager/v201808/activity_service/update_activities.py index 2a18d886..dc01b752 100755 --- a/examples/dfp/v201711/activity_service/update_activities.py +++ b/examples/ad_manager/v201808/activity_service/update_activities.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the activity to update. ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE' @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201711') + activity_service = client.GetService('ActivityService', version='v201808') # Create statement object to select one activity by ID to update. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :activityId') .WithBindVariable('activityId', long(activity_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, activity_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ACTIVITY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_ID) diff --git a/examples/dfp/v201805/audience_segment_service/__init__.py b/examples/ad_manager/v201808/audience_segment_service/__init__.py similarity index 100% rename from examples/dfp/v201805/audience_segment_service/__init__.py rename to examples/ad_manager/v201808/audience_segment_service/__init__.py diff --git a/examples/dfp/v201711/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/create_audience_segments.py similarity index 92% rename from examples/dfp/v201711/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v201808/audience_segment_service/create_audience_segments.py index 16b08496..5d31387b 100755 --- a/examples/dfp/v201711/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/create_audience_segments.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the IDs of the custom criteria to be used in the segment rule. CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201711') - network_service = client.GetService('NetworkService', version='v201711') + 'AudienceSegmentService', version='v201808') + network_service = client.GetService('NetworkService', version='v201808') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( @@ -92,5 +92,5 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py similarity index 88% rename from examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py index 9b67be8e..9bb8f5ee 100755 --- a/examples/dfp/v201711/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201711') + 'AudienceSegmentService', version='v201808') # Create a statement to select audience segments. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py similarity index 87% rename from examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py index 52cfba47..9dbe9254 100755 --- a/examples/dfp/v201711/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201711') + 'AudienceSegmentService', version='v201808') # Create a statement to select audience segments. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) @@ -40,7 +40,7 @@ def main(client): print('Audience segment with ID "%d", name "%s", and size "%d" was ' 'found.\n' % (audience_segment['id'], audience_segment['name'], audience_segment['size'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -49,5 +49,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py similarity index 89% rename from examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py index da8128dd..c1df3bfc 100755 --- a/examples/dfp/v201711/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201711') + 'AudienceSegmentService', version='v201808') # Create statement object to get the specified first party audience segment. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) @@ -67,5 +67,5 @@ def main(client, audience_segment_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AUDIENCE_SEGMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/dfp/v201711/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py similarity index 90% rename from examples/dfp/v201711/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py index fe640635..b7c24919 100755 --- a/examples/dfp/v201711/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201711') + 'AudienceSegmentService', version='v201808') # Create statement object to get the specified first party audience segment. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) @@ -64,5 +64,5 @@ def main(client, audience_segment_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AUDIENCE_SEGMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/dfp/v201805/base_rate_service/__init__.py b/examples/ad_manager/v201808/base_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201805/base_rate_service/__init__.py rename to examples/ad_manager/v201808/base_rate_service/__init__.py diff --git a/examples/dfp/v201711/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201808/base_rate_service/create_product_base_rates.py similarity index 90% rename from examples/dfp/v201711/base_rate_service/create_product_base_rates.py rename to examples/ad_manager/v201808/base_rate_service/create_product_base_rates.py index cc083cd8..1e7a4da9 100755 --- a/examples/dfp/v201711/base_rate_service/create_product_base_rates.py +++ b/examples/ad_manager/v201808/base_rate_service/create_product_base_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201711') + 'BaseRateService', version='v201808') # Create a product base rate. product_base_rate = { @@ -61,5 +61,5 @@ def main(client, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201808/base_rate_service/create_product_package_item_base_rates.py similarity index 94% rename from examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py rename to examples/ad_manager/v201808/base_rate_service/create_product_package_item_base_rates.py index 2a6ea9ac..72d074af 100755 --- a/examples/dfp/v201711/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/ad_manager/v201808/base_rate_service/create_product_package_item_base_rates.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the rate card ID to add the base rate to. RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201711') + base_rate_service = client.GetService('BaseRateService', version='v201808') # Create a base rate for a product package item. product_package_item_base_rate = { @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201808/base_rate_service/create_product_template_base_rates.py similarity index 90% rename from examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py rename to examples/ad_manager/v201808/base_rate_service/create_product_template_base_rates.py index 2f46ab9a..5d96a2b6 100755 --- a/examples/dfp/v201711/base_rate_service/create_product_template_base_rates.py +++ b/examples/ad_manager/v201808/base_rate_service/create_product_template_base_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201711') + 'BaseRateService', version='v201808') # Create a product template base rate. product_template_base_rate = { @@ -61,5 +61,5 @@ def main(client, product_template_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201711/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py similarity index 84% rename from examples/dfp/v201711/base_rate_service/get_all_base_rates.py rename to examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py index 497c7fc8..85eb737e 100755 --- a/examples/dfp/v201711/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201711') + base_rate_service = client.GetService('BaseRateService', version='v201808') # Create a statement to select base rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. @@ -36,7 +36,8 @@ def main(client): for base_rate in response['results']: # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate), + 'found.\n' % (base_rate['id'], + ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) statement.offset += statement.limit else: @@ -47,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py similarity index 84% rename from examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py rename to examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py index c0c5dbdb..ded1b04e 100755 --- a/examples/dfp/v201711/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201711') + base_rate_service = client.GetService('BaseRateService', version='v201808') # Create a statement to select base rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) @@ -40,9 +40,9 @@ def main(client, rate_card_id): # Print out some information for each base rate. print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' 'found.\n' % - (base_rate['id'], dfp.DfpClassType(base_rate), + (base_rate['id'], ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -51,5 +51,5 @@ def main(client, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201711/base_rate_service/update_base_rates.py b/examples/ad_manager/v201808/base_rate_service/update_base_rates.py similarity index 89% rename from examples/dfp/v201711/base_rate_service/update_base_rates.py rename to examples/ad_manager/v201808/base_rate_service/update_base_rates.py index 2f695c66..c0f59d39 100755 --- a/examples/dfp/v201711/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201808/base_rate_service/update_base_rates.py @@ -22,17 +22,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201711') + base_rate_service = client.GetService('BaseRateService', version='v201808') # Create a filter statement for base rates for a single rate card. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -63,7 +63,7 @@ def main(client, base_rate_id): print ('Base rate with ID "%s" and type "%s" belonging to ' 'rate card ID "%s" was updated.' % ( base_rate['id'], - dfp.DfpClassType(base_rate), + ad_manager.AdManagerClassType(base_rate), base_rate['rateCardId'])) else: print 'No base rates were updated.' @@ -73,5 +73,5 @@ def main(client, base_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, BASE_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, BASE_RATE_ID) diff --git a/examples/dfp/v201805/cdn_configuration_service/__init__.py b/examples/ad_manager/v201808/cdn_configuration_service/__init__.py similarity index 100% rename from examples/dfp/v201805/cdn_configuration_service/__init__.py rename to examples/ad_manager/v201808/cdn_configuration_service/__init__.py diff --git a/examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201808/cdn_configuration_service/create_cdn_configurations.py similarity index 93% rename from examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v201808/cdn_configuration_service/create_cdn_configurations.py index f646f7fc..7fcaef21 100755 --- a/examples/dfp/v201711/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v201808/cdn_configuration_service/create_cdn_configurations.py @@ -21,13 +21,13 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201711') + version='v201808') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. @@ -85,5 +85,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py similarity index 88% rename from examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py index a8b7332e..689a3eb6 100755 --- a/examples/dfp/v201711/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py @@ -20,16 +20,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201711') + version='v201808') # Create a statement to select cdn configurations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small number of configs at a time, paging # through until all have been retrieved. @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/company_service/__init__.py b/examples/ad_manager/v201808/company_service/__init__.py similarity index 100% rename from examples/dfp/v201805/company_service/__init__.py rename to examples/ad_manager/v201808/company_service/__init__.py diff --git a/examples/dfp/v201711/company_service/create_companies.py b/examples/ad_manager/v201808/company_service/create_companies.py similarity index 92% rename from examples/dfp/v201711/company_service/create_companies.py rename to examples/ad_manager/v201808/company_service/create_companies.py index 035983be..59acf80f 100755 --- a/examples/dfp/v201711/company_service/create_companies.py +++ b/examples/ad_manager/v201808/company_service/create_companies.py @@ -29,12 +29,12 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201711') + company_service = client.GetService('CompanyService', version='v201808') # Create company objects. companies = [ @@ -58,5 +58,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/company_service/get_advertisers.py b/examples/ad_manager/v201808/company_service/get_advertisers.py similarity index 88% rename from examples/dfp/v201711/company_service/get_advertisers.py rename to examples/ad_manager/v201808/company_service/get_advertisers.py index 80a3bf1b..fb32fd61 100755 --- a/examples/dfp/v201711/company_service/get_advertisers.py +++ b/examples/ad_manager/v201808/company_service/get_advertisers.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201711') + company_service = client.GetService('CompanyService', version='v201808') # Create a statement to select companies. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) @@ -37,7 +37,7 @@ def main(client): # Print out some information for each company. print('Company with ID "%d", name "%s", and type "%s" was found.\n' % (company['id'], company['name'], company['type'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/company_service/get_all_companies.py b/examples/ad_manager/v201808/company_service/get_all_companies.py similarity index 89% rename from examples/dfp/v201711/company_service/get_all_companies.py rename to examples/ad_manager/v201808/company_service/get_all_companies.py index 6854ff2a..176a892b 100755 --- a/examples/dfp/v201711/company_service/get_all_companies.py +++ b/examples/ad_manager/v201808/company_service/get_all_companies.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201711') + company_service = client.GetService('CompanyService', version='v201808') # Create a statement to select companies. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/company_service/update_companies.py b/examples/ad_manager/v201808/company_service/update_companies.py similarity index 91% rename from examples/dfp/v201711/company_service/update_companies.py rename to examples/ad_manager/v201808/company_service/update_companies.py index 35d735b6..39a712d9 100755 --- a/examples/dfp/v201711/company_service/update_companies.py +++ b/examples/ad_manager/v201808/company_service/update_companies.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the company to update. COMPANY_ID = 'INSERT_COMPANY_ID_HERE' @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201711') + company_service = client.GetService('CompanyService', version='v201808') # Create statement object to only select a single company by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(company_id)) .Limit(1)) @@ -66,5 +66,5 @@ def main(client, company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, COMPANY_ID) diff --git a/examples/dfp/v201805/contact_service/__init__.py b/examples/ad_manager/v201808/contact_service/__init__.py similarity index 100% rename from examples/dfp/v201805/contact_service/__init__.py rename to examples/ad_manager/v201808/contact_service/__init__.py diff --git a/examples/dfp/v201711/contact_service/create_contacts.py b/examples/ad_manager/v201808/contact_service/create_contacts.py similarity index 92% rename from examples/dfp/v201711/contact_service/create_contacts.py rename to examples/ad_manager/v201808/contact_service/create_contacts.py index 89872c6a..bb785104 100755 --- a/examples/dfp/v201711/contact_service/create_contacts.py +++ b/examples/ad_manager/v201808/contact_service/create_contacts.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the advertiser company this contact is associated with. ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201711') + contact_service = client.GetService('ContactService', version='v201808') # Create an advertiser contact. advertiser_contact = { @@ -67,5 +67,5 @@ def main(client, advertiser_company_id, agency_company_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) diff --git a/examples/dfp/v201711/contact_service/get_all_contacts.py b/examples/ad_manager/v201808/contact_service/get_all_contacts.py similarity index 89% rename from examples/dfp/v201711/contact_service/get_all_contacts.py rename to examples/ad_manager/v201808/contact_service/get_all_contacts.py index 8d5156c4..715aff51 100755 --- a/examples/dfp/v201711/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201808/contact_service/get_all_contacts.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201711') + contact_service = client.GetService('ContactService', version='v201808') # Create a statement to select contacts. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py similarity index 87% rename from examples/dfp/v201711/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py index 02135586..3945a19c 100755 --- a/examples/dfp/v201711/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201711') + contact_service = client.GetService('ContactService', version='v201808') # Create a statement to select contacts. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) @@ -37,7 +37,7 @@ def main(client): # Print out some information for each contact. print('Contact with ID "%d" and name "%s" was found.\n' % (contact['id'], contact['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/contact_service/update_contacts.py b/examples/ad_manager/v201808/contact_service/update_contacts.py similarity index 91% rename from examples/dfp/v201711/contact_service/update_contacts.py rename to examples/ad_manager/v201808/contact_service/update_contacts.py index 1bb70dd6..4062e0a2 100755 --- a/examples/dfp/v201711/contact_service/update_contacts.py +++ b/examples/ad_manager/v201808/contact_service/update_contacts.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the contact to update. CONTACT_ID = 'INSERT_CONTACT_ID_HERE' @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201711') + contact_service = client.GetService('ContactService', version='v201808') # Create statement object to select the single contact by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(contact_id)) .Limit(1)) @@ -67,5 +67,5 @@ def main(client, contact_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTACT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTACT_ID) diff --git a/examples/dfp/v201805/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/dfp/v201805/content_metadata_key_hierarchy_service/__init__.py rename to examples/ad_manager/v201808/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 88% rename from examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201808/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index 672b1efe..f17f68bb 100755 --- a/examples/dfp/v201711/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -19,7 +19,7 @@ To determine which content metadata key hierarchies exist, run get_all_content_metadata_key_hierarchies.py. -This feature is only available to DFP video publishers. +This feature is only available to Video Solutions publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the IDs of the custom targeting keys for the hierarchy. HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201711') + 'ContentMetadataKeyHierarchyService', version='v201808') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, @@ -74,5 +74,6 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, HIERARCHY_LEVEL_ONE_KEY_ID, HIERARCHY_LEVEL_TWO_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, HIERARCHY_LEVEL_ONE_KEY_ID, + HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 88% rename from examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index b80db960..443c686e 100755 --- a/examples/dfp/v201711/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201711') + 'ContentMetadataKeyHierarchyService', version='v201808') # Create a statement to select content metadata key hierarchies. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 90% rename from examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 81672538..428db239 100755 --- a/examples/dfp/v201711/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -19,7 +19,7 @@ To determine which content metadata key hierarchies exist, run get_all_content_metadata_key_hierarchies.py. -This feature is only available to DFP video publishers. +This feature is only available to Video Solutions publishers. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home @@ -30,7 +30,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the content metadata key hierarchy to update. CONTENT_METADATA_KEY_HIERARCHY_ID = ( @@ -42,11 +42,11 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201711') + 'ContentMetadataKeyHierarchyService', version='v201808') # Create a query to select a single content metadata key hierarchy. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) @@ -89,5 +89,6 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID, + CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201805/content_service/__init__.py b/examples/ad_manager/v201808/content_service/__init__.py similarity index 100% rename from examples/dfp/v201805/content_service/__init__.py rename to examples/ad_manager/v201808/content_service/__init__.py diff --git a/examples/dfp/v201711/content_service/get_all_content.py b/examples/ad_manager/v201808/content_service/get_all_content.py similarity index 89% rename from examples/dfp/v201711/content_service/get_all_content.py rename to examples/ad_manager/v201808/content_service/get_all_content.py index 95f17770..4b8e391d 100755 --- a/examples/dfp/v201711/content_service/get_all_content.py +++ b/examples/ad_manager/v201808/content_service/get_all_content.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201711') + content_service = client.GetService('ContentService', version='v201808') # Create a statement to select content. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/creative_service/__init__.py b/examples/ad_manager/v201808/creative_service/__init__.py similarity index 100% rename from examples/dfp/v201805/creative_service/__init__.py rename to examples/ad_manager/v201808/creative_service/__init__.py diff --git a/examples/dfp/v201711/creative_service/copy_image_creatives.py b/examples/ad_manager/v201808/creative_service/copy_image_creatives.py similarity index 87% rename from examples/dfp/v201711/creative_service/copy_image_creatives.py rename to examples/ad_manager/v201808/creative_service/copy_image_creatives.py index 6554acb1..49ae67bc 100755 --- a/examples/dfp/v201711/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201808/creative_service/copy_image_creatives.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201711') + creative_service = client.GetService('CreativeService', version='v201808') # Create a statement to get the image creative. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) @@ -50,11 +50,11 @@ def main(client): print ('A creative with ID %d, name "%s", and type "%s" was created and ' 'can be previewed at: %s' % (result['id'], result['name'], - dfp.DfpClassType(result), + ad_manager.AdManagerClassType(result), result['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_service/create_creative_from_template.py b/examples/ad_manager/v201808/creative_service/create_creative_from_template.py similarity index 92% rename from examples/dfp/v201711/creative_service/create_creative_from_template.py rename to examples/ad_manager/v201808/creative_service/create_creative_from_template.py index 129b9623..c83d1c12 100755 --- a/examples/dfp/v201711/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201808/creative_service/create_creative_from_template.py @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201711') + creative_service = client.GetService('CreativeService', version='v201808') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' @@ -102,10 +102,10 @@ def main(client, advertiser_id): # Display results. print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201711/creative_service/create_creatives.py b/examples/ad_manager/v201808/creative_service/create_creatives.py similarity index 90% rename from examples/dfp/v201711/creative_service/create_creatives.py rename to examples/ad_manager/v201808/creative_service/create_creatives.py index fac92a31..071c4a36 100755 --- a/examples/dfp/v201711/creative_service/create_creatives.py +++ b/examples/ad_manager/v201808/creative_service/create_creatives.py @@ -31,7 +31,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that all creatives will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201711') + creative_service = client.GetService('CreativeService', version='v201808') # Create creative objects. creatives = [] @@ -81,10 +81,10 @@ def main(client, advertiser_id): for creative in creatives: print ('Image creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201711/creative_service/create_custom_creative.py b/examples/ad_manager/v201808/creative_service/create_custom_creative.py similarity index 88% rename from examples/dfp/v201711/creative_service/create_custom_creative.py rename to examples/ad_manager/v201808/creative_service/create_custom_creative.py index 60a683eb..5bd8cbd4 100755 --- a/examples/dfp/v201711/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201808/creative_service/create_custom_creative.py @@ -16,7 +16,7 @@ """This example creates a custom creative for a given advertiser. -This feature is only available to DFP premium solution networks. To determine +This feature is only available to Ad Manager 360 solution networks. To determine which companies are advertisers, run get_advertisers.py. To determine which creative templates exist, run get_all_creative_templates.py. @@ -32,7 +32,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201711') + creative_service = client.GetService('CreativeService', version='v201808') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', @@ -79,10 +79,10 @@ def main(client, advertiser_id): creative = creatives[0] print ('Template creative with id "%s", name "%s", and type "%s" was ' 'created and can be previewed at %s.' - % (creative['id'], creative['name'], dfp.DfpClassType(creative), - creative['previewUrl'])) + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201711/creative_service/create_native_creative.py b/examples/ad_manager/v201808/creative_service/create_native_creative.py similarity index 96% rename from examples/dfp/v201711/creative_service/create_native_creative.py rename to examples/ad_manager/v201808/creative_service/create_native_creative.py index 75ebfa86..838e7708 100755 --- a/examples/dfp/v201711/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201808/creative_service/create_native_creative.py @@ -33,7 +33,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the advertiser (company) that the creative will be assigned to. ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201711') + creative_service = client.GetService('CreativeService', version='v201808') # Use the system defined native app install creative template. creative_template_id = '10004400' @@ -128,5 +128,5 @@ def main(client, advertiser_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201711/creative_service/get_all_creatives.py b/examples/ad_manager/v201808/creative_service/get_all_creatives.py similarity index 89% rename from examples/dfp/v201711/creative_service/get_all_creatives.py rename to examples/ad_manager/v201808/creative_service/get_all_creatives.py index 73a134c6..17135aa4 100755 --- a/examples/dfp/v201711/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201808/creative_service/get_all_creatives.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201711') + creative_service = client.GetService('CreativeService', version='v201808') # Create a statement to select creatives. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_service/get_image_creatives.py b/examples/ad_manager/v201808/creative_service/get_image_creatives.py similarity index 87% rename from examples/dfp/v201711/creative_service/get_image_creatives.py rename to examples/ad_manager/v201808/creative_service/get_image_creatives.py index 213ccd96..f9f735e5 100755 --- a/examples/dfp/v201711/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201808/creative_service/get_image_creatives.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201711') + creative_service = client.GetService('CreativeService', version='v201808') # Create a statement to select creatives. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) @@ -37,7 +37,7 @@ def main(client): # Print out some information for each creative. print('Creative with ID "%d" and name "%s" was found.\n' % (creative['id'], creative['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_service/update_creatives.py b/examples/ad_manager/v201808/creative_service/update_creatives.py similarity index 89% rename from examples/dfp/v201711/creative_service/update_creatives.py rename to examples/ad_manager/v201808/creative_service/update_creatives.py index f92fffb8..8929f0c1 100755 --- a/examples/dfp/v201711/creative_service/update_creatives.py +++ b/examples/ad_manager/v201808/creative_service/update_creatives.py @@ -27,17 +27,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE' def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201711') + creative_service = client.GetService('CreativeService', version='v201808') - # Create statement object to get all image creatives. - statement = (dfp.StatementBuilder() + # Create statement object to get the creative by ID. + statement = (ad_manager.StatementBuilder() .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', long(image_creative_id)) @@ -67,5 +67,5 @@ def main(client, image_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, IMAGE_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, IMAGE_CREATIVE_ID) diff --git a/examples/dfp/v201805/creative_set_service/__init__.py b/examples/ad_manager/v201808/creative_set_service/__init__.py similarity index 100% rename from examples/dfp/v201805/creative_set_service/__init__.py rename to examples/ad_manager/v201808/creative_set_service/__init__.py diff --git a/examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201808/creative_set_service/associate_creative_set_to_line_item.py similarity index 88% rename from examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v201808/creative_set_service/associate_creative_set_to_line_item.py index 579c7746..a104a70f 100755 --- a/examples/dfp/v201711/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201808/creative_set_service/associate_creative_set_to_line_item.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201711') + 'LineItemCreativeAssociationService', version='v201808') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} @@ -51,5 +51,5 @@ def main(client, creative_set_id, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_SET_ID, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_SET_ID, LINE_ITEM_ID) diff --git a/examples/dfp/v201711/creative_set_service/create_creative_set.py b/examples/ad_manager/v201808/creative_set_service/create_creative_set.py similarity index 89% rename from examples/dfp/v201711/creative_set_service/create_creative_set.py rename to examples/ad_manager/v201808/creative_set_service/create_creative_set.py index c734a6fd..fc8f5cb0 100755 --- a/examples/dfp/v201711/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201808/creative_set_service/create_creative_set.py @@ -29,7 +29,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201711') + version='v201808') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), @@ -57,5 +57,5 @@ def main(client, master_creative_id, companion_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) diff --git a/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py similarity index 88% rename from examples/dfp/v201711/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py index 1cabf48d..e56a8927 100755 --- a/examples/dfp/v201711/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201711') + 'CreativeSetService', version='v201808') # Create a statement to select creative sets. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py similarity index 86% rename from examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py index e8c0575f..c7e34212 100755 --- a/examples/dfp/v201711/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201711') + 'CreativeSetService', version='v201808') # Create a statement to select creative sets. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) @@ -41,7 +41,7 @@ def main(client, master_creative_id): # Print out some information for each creative set. print('Creative set with ID "%d" and name "%s" was found.\n' % (creative_set['id'], creative_set['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -50,5 +50,5 @@ def main(client, master_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, MASTER_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, MASTER_CREATIVE_ID) diff --git a/examples/dfp/v201711/creative_set_service/update_creative_set.py b/examples/ad_manager/v201808/creative_set_service/update_creative_set.py similarity index 90% rename from examples/dfp/v201711/creative_set_service/update_creative_set.py rename to examples/ad_manager/v201808/creative_set_service/update_creative_set.py index 6268f165..3ed696b5 100755 --- a/examples/dfp/v201711/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201808/creative_set_service/update_creative_set.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the creative set to update. CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201711') + version='v201808') # Create statement to select a single creative set by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', long(creative_set_id))) @@ -69,5 +69,5 @@ def main(client, creative_set_id, companion_creative_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) diff --git a/examples/dfp/v201805/creative_template_service/__init__.py b/examples/ad_manager/v201808/creative_template_service/__init__.py similarity index 100% rename from examples/dfp/v201805/creative_template_service/__init__.py rename to examples/ad_manager/v201808/creative_template_service/__init__.py diff --git a/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py similarity index 88% rename from examples/dfp/v201711/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py index 689a6785..d05bf5c2 100755 --- a/examples/dfp/v201711/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201711') + 'CreativeTemplateService', version='v201808') # Create a statement to select creative templates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py similarity index 86% rename from examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py index bc63707e..31f723e8 100755 --- a/examples/dfp/v201711/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201711') + 'CreativeTemplateService', version='v201808') # Create a statement to select creative templates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) @@ -39,7 +39,7 @@ def main(client): # Print out some information for each creative template. print('Creative template with ID "%d" and name "%s" was found.\n' % (creative_template['id'], creative_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/create_creative_wrappers.py similarity index 91% rename from examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v201808/creative_wrapper_service/create_creative_wrappers.py index ba0d2ca5..92261400 100755 --- a/examples/dfp/v201711/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/create_creative_wrappers.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE' @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201711') + version='v201808') # Create creative wrapper objects. creative_wrapper = { @@ -59,5 +59,5 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 90% rename from examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py index a6d3592c..a3087b9b 100755 --- a/examples/dfp/v201711/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py @@ -25,7 +25,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_LABEL_ID_HERE' @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201711') + version='v201808') # Create a query to select the active creative wrappers for the given label. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', long(label_id))) @@ -60,7 +60,7 @@ def main(client, label_id): {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: creative_wrappers_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -74,5 +74,5 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py similarity index 86% rename from examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py index 34024272..aa9b5278 100755 --- a/examples/dfp/v201711/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201711') + 'CreativeWrapperService', version='v201808') # Create a statement to select creative wrappers. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -39,7 +39,7 @@ def main(client): # Print out some information for each creative wrapper. print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py similarity index 88% rename from examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py index 6958acb4..ca10557d 100755 --- a/examples/dfp/v201711/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201711') + 'CreativeWrapperService', version='v201808') # Create a statement to select creative wrappers. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py similarity index 90% rename from examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py index 00479c21..7e21ee48 100755 --- a/examples/dfp/v201711/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the creative wrapper to update. CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE' @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201711') + version='v201808') # Create statement to get a creative wrapper by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', long(creative_wrapper_id))) @@ -69,5 +69,5 @@ def main(client, creative_wrapper_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CREATIVE_WRAPPER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_WRAPPER_ID) diff --git a/examples/dfp/v201805/custom_field_service/__init__.py b/examples/ad_manager/v201808/custom_field_service/__init__.py similarity index 100% rename from examples/dfp/v201805/custom_field_service/__init__.py rename to examples/ad_manager/v201808/custom_field_service/__init__.py diff --git a/examples/dfp/v201711/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201808/custom_field_service/create_custom_field_options.py similarity index 91% rename from examples/dfp/v201711/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v201808/custom_field_service/create_custom_field_options.py index 3c890017..20fddd59 100755 --- a/examples/dfp/v201711/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201808/custom_field_service/create_custom_field_options.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the drop-down custom field to create options for. CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201711') + 'CustomFieldService', version='v201808') # Create custom field options. custom_field_options = [ @@ -63,5 +63,5 @@ def main(client, custom_field_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/dfp/v201711/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/create_custom_fields.py similarity index 91% rename from examples/dfp/v201711/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v201808/custom_field_service/create_custom_fields.py index 58500da2..83d22be9 100755 --- a/examples/dfp/v201711/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201808/custom_field_service/create_custom_fields.py @@ -29,13 +29,13 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201711') + 'CustomFieldService', version='v201808') # Create custom field objects. custom_fields = [ @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 90% rename from examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py index df3c4335..788d1ce3 100755 --- a/examples/dfp/v201711/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -27,17 +27,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201711') + 'CustomFieldService', version='v201808') # Create statement to select only active custom fields that apply to # line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) @@ -57,7 +57,7 @@ def main(client): {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: custom_fields_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -69,5 +69,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py similarity index 88% rename from examples/dfp/v201711/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py index 04f86b2e..b185329d 100755 --- a/examples/dfp/v201711/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201711') + 'CustomFieldService', version='v201808') # Create a statement to select custom fields. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py similarity index 86% rename from examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py index 71f93cc8..da28601b 100755 --- a/examples/dfp/v201711/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201711') + 'CustomFieldService', version='v201808') # Create a statement to select custom fields. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) @@ -39,7 +39,7 @@ def main(client): # Print out some information for each custom field. print('Custom field with ID "%d" and name "%s" was found.\n' % (custom_field['id'], custom_field['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py similarity index 77% rename from examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py index 2c0c0ad1..2012369e 100755 --- a/examples/dfp/v201711/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the custom fields, custom field option, and line item. CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' @@ -42,53 +42,36 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201711') + 'CustomFieldService', version='v201808') - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') # Create statement to get a custom field. - custom_field_values = [{ - 'key': 'customFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': custom_field_id - } - }] - custom_field_query = 'WHERE id = :customFieldId' - custom_field_statement = dfp.FilterStatement( - custom_field_query, custom_field_values, 1) + custom_field_statement = (ad_manager.StatementBuilder() + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', custom_field_id) + .Limit(1)) # Get custom field. custom_field = custom_field_service.getCustomFieldsByStatement( custom_field_statement.ToStatement())['results'][0] # Create statement to get a drop down custom field. - drop_down_custom_field_values = [{ - 'key': 'dropDownCustomFieldId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': drop_down_custom_field_id - } - }] - drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId' - drop_down_custom_field_statement = dfp.FilterStatement( - drop_down_custom_field_query, drop_down_custom_field_values, 1) + drop_down_custom_field_statement = ( + ad_manager.StatementBuilder() + .Where('id = :dropDownCustomFieldId') + .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) + .Limit(1)) # Get drop-down custom field. drop_down_custom_field = custom_field_service.getCustomFieldsByStatement( drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_values = [{ - 'key': 'lineItemId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': line_item_id - } - }] - line_item_query = 'WHERE id = :lineItemId' - line_item_statement = dfp.FilterStatement( - line_item_query, line_item_values, 1) + line_item_statement = (ad_manager.StatementBuilder() + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', line_item_id) + .Limit(1)) # Get line item. line_item = line_item_service.getLineItemsByStatement( @@ -135,11 +118,11 @@ def main(client, custom_field_id, drop_down_custom_field_id, for line_item in line_items: custom_field_value_strings = [] for value in line_item['customFieldValues']: - if dfp.DfpClassType(value) == 'CustomFieldValue': + if ad_manager.AdManagerClassType(value) == 'CustomFieldValue': custom_field_value_string = ( '{ID: "%s", value: "%s"}' % (value['customFieldId'], value['value']['value'])) - elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue': + elif ad_manager.AdManagerClassType(value) == 'DropDownCustomFieldValue': custom_field_value_string = ( '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) @@ -151,6 +134,6 @@ def main(client, custom_field_id, drop_down_custom_field_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID) diff --git a/examples/dfp/v201711/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py similarity index 90% rename from examples/dfp/v201711/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v201808/custom_field_service/update_custom_fields.py index 1b6403c7..a3edfb16 100755 --- a/examples/dfp/v201711/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the custom field to update. CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201711') + 'CustomFieldService', version='v201808') # Create statement to get a custom field. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :customFieldId') .WithBindVariable('customFieldId', long(custom_field_id))) @@ -66,5 +66,5 @@ def main(client, custom_field_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_FIELD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/dfp/v201805/custom_targeting_service/__init__.py b/examples/ad_manager/v201808/custom_targeting_service/__init__.py similarity index 100% rename from examples/dfp/v201805/custom_targeting_service/__init__.py rename to examples/ad_manager/v201808/custom_targeting_service/__init__.py diff --git a/examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201808/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 95% rename from examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201808/custom_targeting_service/create_custom_targeting_keys_and_values.py index 0fd0c263..861be833 100755 --- a/examples/dfp/v201711/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -29,13 +29,13 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201711') + 'CustomTargetingService', version='v201808') # Create custom targeting key objects. keys = [ @@ -128,5 +128,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py similarity index 85% rename from examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py index 61907bbe..940a7b85 100755 --- a/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE' @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201711') + 'CustomTargetingService', version='v201808') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,8 +51,8 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_query = 'WHERE id IN (%s)' % ', '.join(key_ids) - key_statement = dfp.FilterStatement(key_query) + key_statement = (ad_manager.StatementBuilder() + .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. result = custom_targeting_service.performCustomTargetingKeyAction( @@ -60,7 +60,7 @@ def main(client, key_name): if result and int(result['numChanges']) > 0: deleted_custom_targeting_keys += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -73,5 +73,5 @@ def main(client, key_name): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, KEY_NAME) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, KEY_NAME) diff --git a/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py similarity index 77% rename from examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py index 8ec72050..bb1dcd07 100755 --- a/examples/dfp/v201711/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -36,17 +36,11 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201711') + 'CustomTargetingService', version='v201808') - filter_values = [{ - 'key': 'keyId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': key_id - } - }] - query = 'WHERE customTargetingKeyId = :keyId' - statement = dfp.FilterStatement(query, filter_values) + statement = (ad_manager.StatementBuilder() + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', key_id)) deleted_custom_targeting_values = 0 @@ -57,16 +51,17 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_query = ('WHERE customTargetingKeyId = :keyId ' - 'AND id IN (%s)' % ', '.join(value_ids)) - value_statement = dfp.FilterStatement(value_query, filter_values) + value_statement = (ad_manager.StatementBuilder() + .Where('customTargetingKeyId = :keyId ' + 'AND id IN (%s)' % ', '.join(value_ids)) + .WithBindVariable('keyId', key_id)) # Delete custom targeting values. result = custom_targeting_service.performCustomTargetingValueAction( action, value_statement.ToStatement()) if result and int(result['numChanges']) > 0: deleted_custom_targeting_values += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -78,5 +73,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, KEY_ID) diff --git a/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 83% rename from examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 666ed108..f2ff09bb 100755 --- a/examples/dfp/v201711/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201711') + 'CustomTargetingService', version='v201808') # Create statement to get all targeting keys. - targeting_key_statement = dfp.StatementBuilder() + targeting_key_statement = ad_manager.StatementBuilder() all_keys = [] @@ -42,9 +42,9 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - query = ('WHERE customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys])) - statement = dfp.FilterStatement(query) + statement = (ad_manager.StatementBuilder() + .Where('customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys]))) # Retrieve a small amount of custom targeting values at a time, paging # through until all custom targeting values have been retrieved. @@ -59,7 +59,7 @@ def main(client): (custom_targeting_value['id'], custom_targeting_value['name'], custom_targeting_value['displayName'], custom_targeting_value['customTargetingKeyId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -68,5 +68,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 90% rename from examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index fde7822e..eab04561 100755 --- a/examples/dfp/v201711/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201711') + 'CustomTargetingService', version='v201808') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (dfp.StatementBuilder() + targeting_key_statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) @@ -70,5 +70,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py similarity index 89% rename from examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py index b47e8843..71ebc154 100755 --- a/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201711') + 'CustomTargetingService', version='v201808') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :keyId') .WithBindVariable('keyId', long(key_id)) .Limit(1)) @@ -63,5 +63,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py similarity index 88% rename from examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py index bcb93a88..d6e1a72b 100755 --- a/examples/dfp/v201711/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201711') + 'CustomTargetingService', version='v201808') - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', long(key_id))) @@ -57,7 +57,7 @@ def main(client, key_id): print ('Custom targeting value with id "%s", name "%s", and display' ' name "%s" was updated.' % (value['id'], value['name'], value['displayName'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -67,5 +67,5 @@ def main(client, key_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CUSTOM_TARGETING_KEY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/dfp/v201805/exchange_rate_service/__init__.py b/examples/ad_manager/v201808/exchange_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201805/exchange_rate_service/__init__.py rename to examples/ad_manager/v201808/exchange_rate_service/__init__.py diff --git a/examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201808/exchange_rate_service/create_exchange_rates.py similarity index 90% rename from examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py rename to examples/ad_manager/v201808/exchange_rate_service/create_exchange_rates.py index 8be06ec7..eebb7f6e 100755 --- a/examples/dfp/v201711/exchange_rate_service/create_exchange_rates.py +++ b/examples/ad_manager/v201808/exchange_rate_service/create_exchange_rates.py @@ -23,13 +23,13 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201711') + version='v201808') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. @@ -54,5 +54,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py similarity index 88% rename from examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py rename to examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py index f9f1b1bd..ef5fffa1 100755 --- a/examples/dfp/v201711/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201711') + 'ExchangeRateService', version='v201808') # Create a statement to select exchange rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 87% rename from examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py index 470934e9..c75be3f6 100755 --- a/examples/dfp/v201711/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' @@ -25,9 +25,9 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201711') + 'ExchangeRateService', version='v201808') # Create a statement to select exchange rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('currencyCode = :currencyCode') .WithBindVariable('currencyCode', currency_code)) @@ -43,7 +43,7 @@ def main(client, currency_code): 'rate "%.2f" was found.\n' % (exchange_rate['id'], exchange_rate['currencyCode'], float(exchange_rate['exchangeRate'] / 1000000))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -52,5 +52,5 @@ def main(client, currency_code): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CURRENCY_CODE) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CURRENCY_CODE) diff --git a/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py similarity index 89% rename from examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py rename to examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py index fc1733e4..064df7a1 100755 --- a/examples/dfp/v201711/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' @@ -30,10 +30,10 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201711') + version='v201808') # Create a statement to get an exchange rate by its ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(exchange_rate_id)) .Limit(1)) @@ -67,5 +67,5 @@ def main(client, exchange_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, EXCHANGE_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, EXCHANGE_RATE_ID) diff --git a/examples/ad_manager/v201808/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201808/forecast_service/get_availability_forecast.py new file mode 100755 index 00000000..b7f3edd9 --- /dev/null +++ b/examples/ad_manager/v201808/forecast_service/get_availability_forecast.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 a forecast for a prospective line item. + +The prospective line item targets the entire network. The targeting can be +modified to determine forecasts for other criteria such as custom criteria +targeting (in addition to targeting the whole network). See +create_line_items.py for an example of how to create more complex targeting. + +""" + + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201808') + network_service = client.GetService('NetworkService', version='v201808') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + + now_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = now_datetime + datetime.timedelta(days=5) + + # Create prospective line item. + line_item = { + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + } + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + }, + 'isAmpOnly': True, + }, + { + 'size': { + 'width': '120', + 'height': '600' + } + } + ], + 'lineItemType': 'SPONSORSHIP', + 'startDateTimeType': 'IMMEDIATELY', + 'endDateTime': end_datetime, + 'costType': 'CPM', + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'primaryGoal': { + 'units': '50', + 'unitType': 'IMPRESSIONS', + 'goalType': 'DAILY' + }, + 'contractedUnitsBought': '100', + 'creativeRotationType': 'EVEN', + 'discountType': 'PERCENTAGE', + } + + prospective_line_item = { + 'lineItem': line_item, + 'advertiserId': advertiser_id + } + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + # The field includeTargetingCriteriaBreakdown can only be set if + # breakdowns are not manually specified. + # 'includeTargetingCriteriaBreakdown': True, + 'breakdown': { + 'timeWindows': [ + now_datetime, + now_datetime + datetime.timedelta(days=1), + now_datetime + datetime.timedelta(days=2), + now_datetime + datetime.timedelta(days=3), + now_datetime + datetime.timedelta(days=4), + end_datetime + ], + 'targets': [ + { + # Optional, the name field is only used to identify this + # breakdown in the response. + 'name': 'United States', + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '2840', + 'displayName': 'US' + } + ] + } + } + }, + { + # Optional, the name field is only used to identify this + # breakdown in the response. + 'name': 'Geneva', + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '20133', + 'displayName': 'Geneva' + } + ] + } + } + } + ] + } + } + + # Get forecast. + forecast = forecast_service.getAvailabilityForecast( + prospective_line_item, forecast_options) + matched = forecast['matchedUnits'] + available = forecast['availableUnits'] + possible = forecast['possibleUnits'] if 'possibleUnits' in forecast else None + unit_type = forecast['unitType'].lower() + + available_percent_overall, possible_percent_overall = CalculateForecastStats( + matched, available, possible) + + contending_line_items = getattr(forecast, 'contendingLineItems', []) + + # Display results. + print '%s %s matched overall.' % (matched, unit_type) + print '%s%% %s available overall.' % (available_percent_overall, unit_type) + print '%d contending line items overall.' % len(contending_line_items) + if possible: + print '%s%% %s possible overall.' % (possible_percent_overall, unit_type) + + if 'breakdowns' in forecast and len(forecast['breakdowns']): + for breakdown in forecast['breakdowns']: + print 'For breakdown time period %s - %s:' % ( + FormatSOAPDateTime(breakdown['startTime']), + FormatSOAPDateTime(breakdown['endTime'])) + for breakdown_entry in breakdown['breakdownEntries']: + matched = breakdown_entry['forecast']['matched'] + available = breakdown_entry['forecast']['available'] + possible = (breakdown_entry['forecast']['possible'] + if 'possible' in breakdown_entry['forecast'] else None) + name = breakdown_entry['name'] if 'name' in breakdown_entry else None + if name: + print '\tFor targeting breakdown named \'%s\'' % name + available_percent, possible_percent = CalculateForecastStats( + matched, available, possible) + print '\t\t%s %s matched.' % (matched, unit_type) + print '\t\t%s%% %s available.' % (available_percent, unit_type) + if possible: + print '\t\t%s%% %s possible.' % (possible_percent, unit_type) + + +def FormatSOAPDateTime(value): + """Format a SOAP DateTime object for printing. + + Args: + value: The DateTime object to format. + + Returns: + A string representing the value. + """ + value_date = value['date'] + return '%s-%s-%s %s:%s:%s (%s)' % ( + value_date['year'], value_date['month'], value_date['day'], + value['hour'], value['minute'], value['second'], value['timeZoneID']) + + +def CalculateForecastStats(matched, available, possible=None): + """Calculate forecast percentage stats. + + Args: + matched: The number of matched impressions. + available: The number of available impressions. + possible: The optional number of possible impressions. + + Returns: + The percentage of impressions that are available and possible. + """ + if matched > 0: + available_percent = (float(available) / matched) * 100. + else: + available_percent = 0 + + if possible is not None: + if matched > 0: + possible_percent = (possible/float(matched)) * 100. + else: + possible_percent = 0 + else: + possible_percent = None + + return available_percent, possible_percent + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201808/forecast_service/get_availability_forecast_for_line_item.py similarity index 93% rename from examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v201808/forecast_service/get_availability_forecast_for_line_item.py index 3820ae8f..35877319 100755 --- a/examples/dfp/v201711/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201808/forecast_service/get_availability_forecast_for_line_item.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line item to get a forecast for. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201711') + forecast_service = client.GetService('ForecastService', version='v201808') # Set forecasting options. forecast_options = { @@ -60,8 +60,7 @@ def main(client, line_item_id): possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201808/forecast_service/get_delivery_forecast_for_line_items.py similarity index 91% rename from examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v201808/forecast_service/get_delivery_forecast_for_line_items.py index 38f54050..01ea6e0b 100755 --- a/examples/dfp/v201711/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201808/forecast_service/get_delivery_forecast_for_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line items to get forecasts for. LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201711') + forecast_service = client.GetService('ForecastService', version='v201808') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( @@ -48,5 +48,5 @@ def main(client, line_item_id1, line_item_id2): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/dfp/v201805/inventory_service/__init__.py b/examples/ad_manager/v201808/inventory_service/__init__.py similarity index 100% rename from examples/dfp/v201805/inventory_service/__init__.py rename to examples/ad_manager/v201808/inventory_service/__init__.py diff --git a/examples/dfp/v201711/inventory_service/archive_ad_units.py b/examples/ad_manager/v201808/inventory_service/archive_ad_units.py similarity index 90% rename from examples/dfp/v201711/inventory_service/archive_ad_units.py rename to examples/ad_manager/v201808/inventory_service/archive_ad_units.py index cc152465..179c8e01 100755 --- a/examples/dfp/v201711/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/archive_ad_units.py @@ -28,18 +28,18 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201808') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', long(parent_id))) @@ -58,7 +58,7 @@ def main(client, parent_id): {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: ad_units_archived += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -71,5 +71,5 @@ def main(client, parent_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PARENT_AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/dfp/v201711/inventory_service/create_ad_units.py b/examples/ad_manager/v201808/inventory_service/create_ad_units.py similarity index 92% rename from examples/dfp/v201711/inventory_service/create_ad_units.py rename to examples/ad_manager/v201808/inventory_service/create_ad_units.py index b017e0dd..787aefe2 100755 --- a/examples/dfp/v201711/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/create_ad_units.py @@ -29,14 +29,14 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201808') # Create ad unit size. ad_unit_size = { @@ -66,5 +66,5 @@ def main(client, parent_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PARENT_AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py similarity index 93% rename from examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py index 5d3c25f6..dcd8aa57 100755 --- a/examples/dfp/v201711/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py @@ -19,20 +19,20 @@ # Import appropriate modules from the client library. import collections -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201711') - inventory_service = client.GetService('InventoryService', version='v201711') + network_service = client.GetService('NetworkService', version='v201808') + inventory_service = client.GetService('InventoryService', version='v201808') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .OrderBy('id', ascending=True)) # Pull down all ad units into a list @@ -111,5 +111,5 @@ def display_hierarchy_helper(root, parent_id_to_children, depth): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py similarity index 86% rename from examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py index aba7e9e5..8a973f02 100755 --- a/examples/dfp/v201711/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201711') + 'InventoryService', version='v201808') # Create a statement to select ad unit sizes. - statement = dfp.FilterStatement() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. @@ -42,5 +42,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py similarity index 89% rename from examples/dfp/v201711/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v201808/inventory_service/get_all_ad_units.py index 8fa08cfd..28972e48 100755 --- a/examples/dfp/v201711/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201711') + ad_unit_service = client.GetService('InventoryService', version='v201808') # Create a statement to select ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py similarity index 91% rename from examples/dfp/v201711/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py index c381d0d4..56d3d2b7 100755 --- a/examples/dfp/v201711/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py @@ -18,20 +18,20 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201711') - inventory_service = client.GetService('InventoryService', version='v201711') + network_service = client.GetService('NetworkService', version='v201808') + inventory_service = client.GetService('InventoryService', version='v201808') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) @@ -54,5 +54,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/inventory_service/update_ad_units.py b/examples/ad_manager/v201808/inventory_service/update_ad_units.py similarity index 92% rename from examples/dfp/v201711/inventory_service/update_ad_units.py rename to examples/ad_manager/v201808/inventory_service/update_ad_units.py index a6a68b2f..0b388101 100755 --- a/examples/dfp/v201711/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/update_ad_units.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the ad unit to get. @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201711') + inventory_service = client.GetService('InventoryService', version='v201808') # Create a statement to select a single ad unit by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', ad_unit_id)) @@ -78,5 +78,5 @@ def main(client, ad_unit_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, AD_UNIT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AD_UNIT_ID) diff --git a/examples/dfp/v201805/label_service/__init__.py b/examples/ad_manager/v201808/label_service/__init__.py similarity index 100% rename from examples/dfp/v201805/label_service/__init__.py rename to examples/ad_manager/v201808/label_service/__init__.py diff --git a/examples/dfp/v201711/label_service/create_labels.py b/examples/ad_manager/v201808/label_service/create_labels.py similarity index 89% rename from examples/dfp/v201711/label_service/create_labels.py rename to examples/ad_manager/v201808/label_service/create_labels.py index f4d95ddc..a794881f 100755 --- a/examples/dfp/v201711/label_service/create_labels.py +++ b/examples/ad_manager/v201808/label_service/create_labels.py @@ -17,19 +17,19 @@ """This code example creates new labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201711') + label_service = client.GetService('LabelService', version='v201808') # Create label objects. labels = [] @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/label_service/deactivate_labels.py b/examples/ad_manager/v201808/label_service/deactivate_labels.py similarity index 87% rename from examples/dfp/v201711/label_service/deactivate_labels.py rename to examples/ad_manager/v201808/label_service/deactivate_labels.py index e9bee27d..6baa079f 100755 --- a/examples/dfp/v201711/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201808/label_service/deactivate_labels.py @@ -17,20 +17,20 @@ """This code example deactivates all active Labels. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201711') + label_service = client.GetService('LabelService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isActive = :isActive') .WithBindVariable('isActive', True)) @@ -48,7 +48,7 @@ def main(client): {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: labels_deactivated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -61,5 +61,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/label_service/get_active_labels.py b/examples/ad_manager/v201808/label_service/get_active_labels.py similarity index 88% rename from examples/dfp/v201711/label_service/get_active_labels.py rename to examples/ad_manager/v201808/label_service/get_active_labels.py index 7dcebbb8..6a8c0ef1 100755 --- a/examples/dfp/v201711/label_service/get_active_labels.py +++ b/examples/ad_manager/v201808/label_service/get_active_labels.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201711') + label_service = client.GetService('LabelService', version='v201808') # Create a statement to select labels. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isActive = :isActive') .WithBindVariable('isActive', True)) @@ -37,7 +37,7 @@ def main(client): # Print out some information for each label. print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], label['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/label_service/get_all_labels.py b/examples/ad_manager/v201808/label_service/get_all_labels.py similarity index 89% rename from examples/dfp/v201711/label_service/get_all_labels.py rename to examples/ad_manager/v201808/label_service/get_all_labels.py index f47bdca4..5e93b328 100755 --- a/examples/dfp/v201711/label_service/get_all_labels.py +++ b/examples/ad_manager/v201808/label_service/get_all_labels.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201711') + label_service = client.GetService('LabelService', version='v201808') # Create a statement to select labels. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/label_service/update_labels.py b/examples/ad_manager/v201808/label_service/update_labels.py similarity index 88% rename from examples/dfp/v201711/label_service/update_labels.py rename to examples/ad_manager/v201808/label_service/update_labels.py index 42461310..f8e2b229 100755 --- a/examples/dfp/v201711/label_service/update_labels.py +++ b/examples/ad_manager/v201808/label_service/update_labels.py @@ -17,22 +17,22 @@ """This code example updates the description of a single label. To determine which labels exist, run get_all_labels.py. This feature is only -available to DFP premium solution networks. +available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LABEL_ID = 'INSERT_LABEL_ID_HERE' def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201711') + label_service = client.GetService('LabelService', version='v201808') # Create a statement to select only active labels. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :labelId') .WithBindVariable('labelId', long(label_id))) @@ -58,6 +58,6 @@ def main(client, label_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LABEL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/dfp/v201805/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201808/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/dfp/v201805/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v201808/line_item_creative_association_service/__init__.py diff --git a/examples/dfp/v201711/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/create_licas.py similarity index 88% rename from examples/dfp/v201711/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v201808/line_item_creative_association_service/create_licas.py index 7a6b7e1f..eb5f3566 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/create_licas.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the line item ID and creative IDs to associate. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201711') + 'LineItemCreativeAssociationService', version='v201808') licas = [] for creative_id in creative_ids: @@ -53,5 +53,5 @@ def main(client, line_item_id, creative_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID, CREATIVE_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, CREATIVE_IDS) diff --git a/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py similarity index 88% rename from examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py index b29b8d49..f69480e6 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the line item in which to deactivate LICAs. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201711') + 'LineItemCreativeAssociationService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', long(line_item_id))) @@ -56,7 +56,7 @@ def main(client, line_item_id): statement.ToStatement()) if result and int(result['numChanges']) > 0: num_deactivated_licas += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -69,5 +69,5 @@ def main(client, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py similarity index 89% rename from examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py index 63005171..70f4bf47 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201711') + 'LineItemCreativeAssociationService', version='v201808') # Create a statement to select line item creative associations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py similarity index 87% rename from examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py index 020da5a0..ef623efb 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201711') + 'LineItemCreativeAssociationService', version='v201808') # Create a statement to select line item creative associations. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) @@ -47,7 +47,7 @@ def main(client, line_item_id): print('Line item creative association with line item ID "%d" and ' 'creative ID "%d" was found.\n' % (lica['lineItemId'], lica['creativeId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -56,5 +56,5 @@ def main(client, line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/dfp/v201711/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py similarity index 89% rename from examples/dfp/v201711/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py index 2a635d40..e805fca3 100755 --- a/examples/dfp/v201711/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py @@ -22,16 +22,16 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201711') + 'LineItemCreativeAssociationService', version='v201808') # Create statement object to get all LICAs. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() while True: # Get LICAs by statement. @@ -62,5 +62,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/line_item_service/__init__.py b/examples/ad_manager/v201808/line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201805/line_item_service/__init__.py rename to examples/ad_manager/v201808/line_item_service/__init__.py diff --git a/examples/dfp/v201711/line_item_service/activate_line_items.py b/examples/ad_manager/v201808/line_item_service/activate_line_items.py similarity index 91% rename from examples/dfp/v201711/line_item_service/activate_line_items.py rename to examples/ad_manager/v201808/line_item_service/activate_line_items.py index 24dd5137..64f0bfe3 100755 --- a/examples/dfp/v201711/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/activate_line_items.py @@ -25,7 +25,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the order to get line items from. ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', long(order_id))) @@ -58,7 +58,7 @@ def main(client, order_id): {'xsi_type': 'ActivateLineItems'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: line_items_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -71,5 +71,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201711/line_item_service/create_line_items.py b/examples/ad_manager/v201808/line_item_service/create_line_items.py similarity index 96% rename from examples/dfp/v201711/line_item_service/create_line_items.py rename to examples/ad_manager/v201808/line_item_service/create_line_items.py index 71c64228..f0a98493 100755 --- a/examples/dfp/v201711/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/create_line_items.py @@ -26,7 +26,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set order that the created line item will belong to and add the id of a @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) @@ -161,6 +161,6 @@ def main(client, order_id, targeted_placement_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID, TARGETED_PLACEMENT_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS) diff --git a/examples/dfp/v201711/line_item_service/create_video_line_item.py b/examples/ad_manager/v201808/line_item_service/create_video_line_item.py similarity index 94% rename from examples/dfp/v201711/line_item_service/create_video_line_item.py rename to examples/ad_manager/v201808/line_item_service/create_video_line_item.py index 551c853c..707e8184 100755 --- a/examples/dfp/v201711/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v201808/line_item_service/create_video_line_item.py @@ -16,7 +16,7 @@ """This code example creates a new line item to serve to video content. -This feature is only available to DFP premium solution networks. To determine +This feature is only available to Ad Manager 360 solution networks. To determine which line items exist, run get_all_line_items.py. To determine which orders exist, run get_all_orders.py. To create a video ad unit, run create_video_ad_unit.py. To create criteria for categories, run @@ -28,7 +28,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set order that all created line item will belong to and the video ad unit id @@ -47,7 +47,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_custom_targeting_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) @@ -130,6 +130,6 @@ def main(client, order_id, targeted_video_ad_unit_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/dfp/v201711/line_item_service/get_all_line_items.py b/examples/ad_manager/v201808/line_item_service/get_all_line_items.py similarity index 89% rename from examples/dfp/v201711/line_item_service/get_all_line_items.py rename to examples/ad_manager/v201808/line_item_service/get_all_line_items.py index 240ad1b0..d89023a6 100755 --- a/examples/dfp/v201711/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/get_all_line_items.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') # Create a statement to select line items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py similarity index 88% rename from examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py index e1be9bf0..e23bdb74 100755 --- a/examples/dfp/v201711/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') # Create a statement to select line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) @@ -38,7 +38,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py similarity index 89% rename from examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py index 6d7e5959..92225e51 100755 --- a/examples/dfp/v201711/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py @@ -20,19 +20,19 @@ from datetime import datetime from datetime import timedelta -from googleads import dfp +from googleads import ad_manager import pytz def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) @@ -46,7 +46,7 @@ def main(client): # Print out some information for each line item. print('Line item with ID "%d" and name "%s" was found.\n' % (line_item['id'], line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -55,5 +55,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/line_item_service/pause_line_items.py b/examples/ad_manager/v201808/line_item_service/pause_line_items.py similarity index 92% rename from examples/dfp/v201711/line_item_service/pause_line_items.py rename to examples/ad_manager/v201808/line_item_service/pause_line_items.py index 7fc4cbd5..79ac603e 100755 --- a/examples/dfp/v201711/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/pause_line_items.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) @@ -70,5 +70,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py similarity index 93% rename from examples/dfp/v201711/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v201808/line_item_service/target_custom_criteria.py index 7299e656..8b877214 100755 --- a/examples/dfp/v201711/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py @@ -25,7 +25,7 @@ import pprint # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE' @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :lineItemId') .WithBindVariable('lineItemId', long(line_item_id)) .Limit(1)) @@ -105,6 +105,6 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, VALUE_ID2, VALUE_ID3) diff --git a/examples/dfp/v201711/line_item_service/update_line_items.py b/examples/ad_manager/v201808/line_item_service/update_line_items.py similarity index 92% rename from examples/dfp/v201711/line_item_service/update_line_items.py rename to examples/ad_manager/v201808/line_item_service/update_line_items.py index 78d0cad6..3d451888 100755 --- a/examples/dfp/v201711/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/update_line_items.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the order to get line items from. ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') # Create statement object to only select line items with even delivery rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', long(order_id)) @@ -70,5 +70,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py similarity index 88% rename from examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py index a7c0e33b..7add0880 100755 --- a/examples/dfp/v201711/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py @@ -17,7 +17,7 @@ """This code example activates paused live stream events.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the LiveStreamEvent to get live stream events from. LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201711') + 'LiveStreamEventService', version='v201808') # Create query to find paused live stream events. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') @@ -53,7 +53,7 @@ def main(client, live_stream_event_id): }, statement.ToStatement()) if result and int(result['numChanges']) > 0: live_stream_events_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += ad_manager.SUGGESTED_PAGE_LIMIT else: break @@ -67,5 +67,5 @@ def main(client, live_stream_event_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LIVE_STREAM_EVENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201711/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/create_live_stream_events.py similarity index 91% rename from examples/dfp/v201711/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v201808/live_stream_event_service/create_live_stream_events.py index d8769d38..1f6a04e8 100755 --- a/examples/dfp/v201711/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v201808/live_stream_event_service/create_live_stream_events.py @@ -24,7 +24,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set content urls and adTags to use @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201711') + 'LiveStreamEventService', version='v201808') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) @@ -64,5 +64,5 @@ def main(client, content_urls, ad_tags): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_URLS, AD_TAGS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_URLS, AD_TAGS) diff --git a/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py similarity index 88% rename from examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py index 4f3e6963..44eab75c 100755 --- a/examples/dfp/v201711/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py @@ -18,16 +18,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201711') + 'LiveStreamEventService', version='v201808') # Create a statement to select live stream events. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201808/live_stream_event_service/register_sessions_for_monitoring.py similarity index 88% rename from examples/dfp/v201711/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v201808/live_stream_event_service/register_sessions_for_monitoring.py index 7a155778..e3e8ce37 100755 --- a/examples/dfp/v201711/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201808/live_stream_event_service/register_sessions_for_monitoring.py @@ -17,7 +17,7 @@ """This example registers all live stream event-sessions ids for monitoring.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # List of session ids SESSION_IDS = ['INSERT_SESSION_IDS_HERE'] @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201711') + 'LiveStreamEventService', version='v201808') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( @@ -41,5 +41,5 @@ def main(client, session_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, SESSION_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, SESSION_IDS) diff --git a/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py similarity index 90% rename from examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py index b74dfa26..f22dad8d 100755 --- a/examples/dfp/v201711/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set ID of the LiveStreamEvent to get live stream events from. LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201711') + 'LiveStreamEventService', version='v201808') # Create statement object to only select matching live stream event. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('Id = :id')) .WithBindVariable('id', long(live_stream_event_id)) .Limit(500)) @@ -65,5 +65,5 @@ def main(client, live_stream_event_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, LIVE_STREAM_EVENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/dfp/v201805/native_style_service/__init__.py b/examples/ad_manager/v201808/native_style_service/__init__.py similarity index 100% rename from examples/dfp/v201805/native_style_service/__init__.py rename to examples/ad_manager/v201808/native_style_service/__init__.py diff --git a/examples/dfp/v201711/native_style_service/create_native_styles.py b/examples/ad_manager/v201808/native_style_service/create_native_styles.py similarity index 94% rename from examples/dfp/v201711/native_style_service/create_native_styles.py rename to examples/ad_manager/v201808/native_style_service/create_native_styles.py index 7923a081..a6d7d891 100755 --- a/examples/dfp/v201711/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201808/native_style_service/create_native_styles.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # This is the creative template ID for the system-defined native app install ad @@ -149,7 +149,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201711') + version='v201808') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), @@ -175,6 +175,6 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, WIDTH, - HEIGHT) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, + WIDTH, HEIGHT) diff --git a/examples/dfp/v201711/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py similarity index 87% rename from examples/dfp/v201711/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v201808/native_style_service/get_all_native_styles.py index f75608dd..dbbb8de5 100755 --- a/examples/dfp/v201711/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py @@ -17,16 +17,16 @@ """This example gets all native styles.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201711') + version='v201808') # Create a statement to select native styles. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/network_service/__init__.py b/examples/ad_manager/v201808/network_service/__init__.py similarity index 100% rename from examples/dfp/v201805/network_service/__init__.py rename to examples/ad_manager/v201808/network_service/__init__.py diff --git a/examples/dfp/v201711/network_service/get_all_networks.py b/examples/ad_manager/v201808/network_service/get_all_networks.py similarity index 89% rename from examples/dfp/v201711/network_service/get_all_networks.py rename to examples/ad_manager/v201808/network_service/get_all_networks.py index d040f75a..5f57da29 100755 --- a/examples/dfp/v201711/network_service/get_all_networks.py +++ b/examples/ad_manager/v201808/network_service/get_all_networks.py @@ -17,12 +17,12 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201711') + network_service = client.GetService('NetworkService', version='v201808') networks = network_service.getAllNetworks() @@ -36,5 +36,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/network_service/get_current_network.py b/examples/ad_manager/v201808/network_service/get_current_network.py similarity index 89% rename from examples/dfp/v201711/network_service/get_current_network.py rename to examples/ad_manager/v201808/network_service/get_current_network.py index e112d553..7278eb52 100755 --- a/examples/dfp/v201711/network_service/get_current_network.py +++ b/examples/ad_manager/v201808/network_service/get_current_network.py @@ -18,12 +18,12 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201711') + network_service = client.GetService('NetworkService', version='v201808') current_network = network_service.getCurrentNetwork() @@ -33,5 +33,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/network_service/make_test_network.py b/examples/ad_manager/v201808/network_service/make_test_network.py similarity index 68% rename from examples/dfp/v201711/network_service/make_test_network.py rename to examples/ad_manager/v201808/network_service/make_test_network.py index 8782a971..008e7193 100755 --- a/examples/dfp/v201711/network_service/make_test_network.py +++ b/examples/ad_manager/v201808/network_service/make_test_network.py @@ -16,11 +16,12 @@ """This example creates a test network. -You do not need to have a DFP account to run this example, but you do need to -have a Google account (created at http://www.google.com/accounts/newaccount -if you currently don't have one) that is not associated with any other DFP test -networks. Once this network is created, you can supply the network code in your -settings to make calls to other services. +You do not need to have an Ad Manager account to run this example, but you do +need to have a Google account (created at +http://www.google.com/accounts/newaccount if you currently don't have one) that +is not associated with any other Ad Manager test networks. Once this network is +created, you can supply the network code in your settings to make calls to +other services. Alternatively, if you do not wish to run this example, you can create a test network at: @@ -29,12 +30,12 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201711') + network_service = client.GetService('NetworkService', version='v201808') # Create a test network. network = network_service.makeTestNetwork() @@ -42,10 +43,11 @@ def main(client): # Display results. print ('Test network with network code "%s" and display name "%s" ' 'created.' % (network['networkCode'], network['displayName'])) - print ('You may now sign in at http://www.google.com/dfp/main?networkCode=%s' + print ('You may now sign in at ' + 'http://www.google.com/admanager/main?networkCode=%s' % network['networkCode']) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/order_service/__init__.py b/examples/ad_manager/v201808/order_service/__init__.py similarity index 100% rename from examples/dfp/v201805/order_service/__init__.py rename to examples/ad_manager/v201808/order_service/__init__.py diff --git a/examples/dfp/v201711/order_service/approve_orders.py b/examples/ad_manager/v201808/order_service/approve_orders.py similarity index 90% rename from examples/dfp/v201711/order_service/approve_orders.py rename to examples/ad_manager/v201808/order_service/approve_orders.py index a117a7b5..0b455bfb 100755 --- a/examples/dfp/v201711/order_service/approve_orders.py +++ b/examples/ad_manager/v201808/order_service/approve_orders.py @@ -23,16 +23,16 @@ import datetime # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201711') + order_service = client.GetService('OrderService', version='v201808') # Create a filter statement. today = datetime.date.today() - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) @@ -51,7 +51,7 @@ def main(client): {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: orders_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -63,5 +63,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/order_service/create_orders.py b/examples/ad_manager/v201808/order_service/create_orders.py similarity index 90% rename from examples/dfp/v201711/order_service/create_orders.py rename to examples/ad_manager/v201808/order_service/create_orders.py index f2b5628f..26203062 100755 --- a/examples/dfp/v201711/order_service/create_orders.py +++ b/examples/ad_manager/v201808/order_service/create_orders.py @@ -23,7 +23,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE' @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201711') + order_service = client.GetService('OrderService', version='v201808') # Create order objects. orders = [] @@ -55,5 +55,5 @@ def main(client, company_id, salesperson_id, trafficker_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) diff --git a/examples/dfp/v201711/order_service/get_all_orders.py b/examples/ad_manager/v201808/order_service/get_all_orders.py similarity index 89% rename from examples/dfp/v201711/order_service/get_all_orders.py rename to examples/ad_manager/v201808/order_service/get_all_orders.py index 75aa2252..958c79ca 100755 --- a/examples/dfp/v201711/order_service/get_all_orders.py +++ b/examples/ad_manager/v201808/order_service/get_all_orders.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201711') + order_service = client.GetService('OrderService', version='v201808') # Create a statement to select orders. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py similarity index 90% rename from examples/dfp/v201711/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v201808/order_service/get_orders_starting_soon.py index 3712d2a0..1fa0ee74 100755 --- a/examples/dfp/v201711/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py @@ -20,18 +20,18 @@ from datetime import datetime from datetime import timedelta -from googleads import dfp +from googleads import ad_manager import pytz def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201711') + order_service = client.GetService('OrderService', version='v201808') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') @@ -47,7 +47,7 @@ def main(client): # Print out some information for each order. print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], order['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/order_service/update_orders.py b/examples/ad_manager/v201808/order_service/update_orders.py similarity index 91% rename from examples/dfp/v201711/order_service/update_orders.py rename to examples/ad_manager/v201808/order_service/update_orders.py index 1f810499..163a31a7 100755 --- a/examples/dfp/v201711/order_service/update_orders.py +++ b/examples/ad_manager/v201808/order_service/update_orders.py @@ -21,18 +21,18 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ORDER_ID = 'INSERT_ORDER_ID_HERE' def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201711') + order_service = client.GetService('OrderService', version='v201808') # Create statement object to select a single order by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :orderId') .WithBindVariable('orderId', long(order_id))) @@ -66,6 +66,6 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201711/package_service/create_packages.py b/examples/ad_manager/v201808/package_service/create_packages.py similarity index 92% rename from examples/dfp/v201711/package_service/create_packages.py rename to examples/ad_manager/v201808/package_service/create_packages.py index cafb0c42..bcafa5fb 100755 --- a/examples/dfp/v201711/package_service/create_packages.py +++ b/examples/ad_manager/v201808/package_service/create_packages.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the ID of the product package to create the package from. PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201711') + package_service = client.GetService('PackageService', version='v201808') # Create local package. package = { @@ -57,5 +57,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py similarity index 91% rename from examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py rename to examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py index 4029c889..1e9717bf 100755 --- a/examples/dfp/v201711/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the line item to pause. PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201711') + package_service = client.GetService('PackageService', version='v201808') # Create a statement to select the single package. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -64,5 +64,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/package_service/get_all_packages.py b/examples/ad_manager/v201808/package_service/get_all_packages.py similarity index 89% rename from examples/dfp/v201711/package_service/get_all_packages.py rename to examples/ad_manager/v201808/package_service/get_all_packages.py index 6820772e..86cd16b3 100755 --- a/examples/dfp/v201711/package_service/get_all_packages.py +++ b/examples/ad_manager/v201808/package_service/get_all_packages.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201711') + pkg_service = client.GetService('PackageService', version='v201808') # Create a statement to select packages. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/package_service/get_in_progress_packages.py b/examples/ad_manager/v201808/package_service/get_in_progress_packages.py similarity index 88% rename from examples/dfp/v201711/package_service/get_in_progress_packages.py rename to examples/ad_manager/v201808/package_service/get_in_progress_packages.py index 0ec4fc65..fc486fd8 100755 --- a/examples/dfp/v201711/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201808/package_service/get_in_progress_packages.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201711') + pkg_service = client.GetService('PackageService', version='v201808') # Create a statement to select packages. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'IN_PROGRESS')) @@ -38,7 +38,7 @@ def main(client): print( 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/placement_service/create_placements.py b/examples/ad_manager/v201808/placement_service/create_placements.py similarity index 94% rename from examples/dfp/v201711/placement_service/create_placements.py rename to examples/ad_manager/v201808/placement_service/create_placements.py index 24bf145e..9918518d 100755 --- a/examples/dfp/v201711/placement_service/create_placements.py +++ b/examples/ad_manager/v201808/placement_service/create_placements.py @@ -23,13 +23,13 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201711') - inventory_service = client.GetService('InventoryService', version='v201711') + placement_service = client.GetService('PlacementService', version='v201808') + inventory_service = client.GetService('InventoryService', version='v201808') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() while True: response = inventory_service.getAdUnitsByStatement( @@ -104,5 +104,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/placement_service/deactivate_placements.py b/examples/ad_manager/v201808/placement_service/deactivate_placements.py similarity index 90% rename from examples/dfp/v201711/placement_service/deactivate_placements.py rename to examples/ad_manager/v201808/placement_service/deactivate_placements.py index 6d0bc0f8..a6e11916 100755 --- a/examples/dfp/v201711/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201808/placement_service/deactivate_placements.py @@ -21,17 +21,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201711') + placement_service = client.GetService('PlacementService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :placementId') .WithBindVariable('placementId', long(placement_id)) .Limit(1)) @@ -58,5 +58,5 @@ def main(client, placement_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PLACEMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/dfp/v201711/placement_service/get_active_placements.py b/examples/ad_manager/v201808/placement_service/get_active_placements.py similarity index 87% rename from examples/dfp/v201711/placement_service/get_active_placements.py rename to examples/ad_manager/v201808/placement_service/get_active_placements.py index 3704dcb5..dbed1123 100755 --- a/examples/dfp/v201711/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201808/placement_service/get_active_placements.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201711') + placement_service = client.GetService('PlacementService', version='v201808') # Create a statement to select placements. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -38,7 +38,7 @@ def main(client): # Print out some information for each placement. print('Placement with ID "%d" and name "%s" was found.\n' % (placement['id'], placement['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/placement_service/get_all_placements.py b/examples/ad_manager/v201808/placement_service/get_all_placements.py similarity index 89% rename from examples/dfp/v201711/placement_service/get_all_placements.py rename to examples/ad_manager/v201808/placement_service/get_all_placements.py index 2a98cce2..fbd52086 100755 --- a/examples/dfp/v201711/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201808/placement_service/get_all_placements.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201711') + placement_service = client.GetService('PlacementService', version='v201808') # Create a statement to select placements. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/placement_service/update_placements.py b/examples/ad_manager/v201808/placement_service/update_placements.py similarity index 89% rename from examples/dfp/v201711/placement_service/update_placements.py rename to examples/ad_manager/v201808/placement_service/update_placements.py index a2663891..9ad03779 100755 --- a/examples/dfp/v201711/placement_service/update_placements.py +++ b/examples/ad_manager/v201808/placement_service/update_placements.py @@ -21,17 +21,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201711') + placement_service = client.GetService('PlacementService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -54,5 +54,5 @@ def main(client, placement_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PLACEMENT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/dfp/v201805/premium_rate_service/__init__.py b/examples/ad_manager/v201808/premium_rate_service/__init__.py similarity index 100% rename from examples/dfp/v201805/premium_rate_service/__init__.py rename to examples/ad_manager/v201808/premium_rate_service/__init__.py diff --git a/examples/dfp/v201711/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201808/premium_rate_service/create_premium_rates.py similarity index 90% rename from examples/dfp/v201711/premium_rate_service/create_premium_rates.py rename to examples/ad_manager/v201808/premium_rate_service/create_premium_rates.py index 7d35fa92..69b506ed 100755 --- a/examples/dfp/v201711/premium_rate_service/create_premium_rates.py +++ b/examples/ad_manager/v201808/premium_rate_service/create_premium_rates.py @@ -20,7 +20,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201711') + version='v201808') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { @@ -75,10 +75,10 @@ def main(client, rate_card_id): for premium_rate in premium_rates: print ('A premium rate for "%s" was added to the rate card with ID' ' of "%s".\n' - % (dfp.DfpClassType(premium_rate['premiumFeature']), + % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), premium_rate['id'])) if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py similarity index 79% rename from examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py rename to examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py index c55216ac..44a26302 100755 --- a/examples/dfp/v201711/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201711') + 'PremiumRateService', version='v201808') # Create a statement to select premium rates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. @@ -37,9 +37,10 @@ def main(client): for premium_rate in response['results']: # Print out some information for each premium rate. print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'id "%d" was found.\n' % (premium_rate['id'], - dfp.DfpClassType(premium_rate), - premium_rate['rateCardId'])) + 'id "%d" was found.\n' % ( + premium_rate['id'], + ad_manager.AdManagerClassType(premium_rate), + premium_rate['rateCardId'])) statement.offset += statement.limit else: break @@ -49,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 87% rename from examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py index 12a4a545..5c824c01 100755 --- a/examples/dfp/v201711/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -25,9 +25,9 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201711') + 'PremiumRateService', version='v201808') # Create a statement to select premium rates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) @@ -43,7 +43,7 @@ def main(client, rate_card_id): 'ID "%d" was found.\n' % (premium_rate['id'], premium_rate['premium feature'], premium_rate['rateCardId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -52,5 +52,5 @@ def main(client, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/dfp/v201711/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py similarity index 91% rename from examples/dfp/v201711/premium_rate_service/update_premium_rates.py rename to examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py index 2239f7d8..6045d6f5 100755 --- a/examples/dfp/v201711/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' @@ -30,10 +30,10 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201711') + version='v201808') # Create statement object to select a single proposal by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(premium_rate_id)) @@ -83,5 +83,5 @@ def main(client, premium_rate_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PREMIUM_RATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PREMIUM_RATE_ID) diff --git a/examples/dfp/v201711/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201808/product_package_item_service/create_product_package_item.py similarity index 94% rename from examples/dfp/v201711/product_package_item_service/create_product_package_item.py rename to examples/ad_manager/v201808/product_package_item_service/create_product_package_item.py index be418ec4..e4a2b424 100755 --- a/examples/dfp/v201711/product_package_item_service/create_product_package_item.py +++ b/examples/ad_manager/v201808/product_package_item_service/create_product_package_item.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the product package to add product package items to. PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -32,7 +32,7 @@ def main(client): product_package_item_service = client.GetService('ProductPackageItemService', - version='v201711') + version='v201808') product_package_item = { # Set the product from which the product package item is created. @@ -58,5 +58,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py similarity index 88% rename from examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py rename to examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py index c5835440..8eb24f64 100755 --- a/examples/dfp/v201711/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201711') + 'ProductPackageItemService', version='v201808') # Create a statement to select product package items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. @@ -49,5 +49,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py similarity index 87% rename from examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py index 8d43e9b8..940a0fab 100755 --- a/examples/dfp/v201711/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' @@ -25,9 +25,9 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201711') + 'ProductPackageItemService', version='v201808') # Create a statement to select product package items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('productPackageId = :productPackageId') .WithBindVariable('productPackageId', product_package_id)) @@ -43,7 +43,7 @@ def main(client, product_package_id): 'package ID "%d" was found.\n' % (product_package_item['id'], product_package_item['productId'], product_package_item['productPackageId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -52,5 +52,5 @@ def main(client, product_package_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_PACKAGE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_PACKAGE_ID) diff --git a/examples/dfp/v201711/product_package_service/create_product_packages.py b/examples/ad_manager/v201808/product_package_service/create_product_packages.py similarity index 88% rename from examples/dfp/v201711/product_package_service/create_product_packages.py rename to examples/ad_manager/v201808/product_package_service/create_product_packages.py index 049ff271..0491c324 100755 --- a/examples/dfp/v201711/product_package_service/create_product_packages.py +++ b/examples/ad_manager/v201808/product_package_service/create_product_packages.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the ID of the rate card to associate with the product package. RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' @@ -30,7 +30,7 @@ def main(client): product_package_service = client.GetService('ProductPackageService', - version='v201711') + version='v201808') # Create a local product package. product_package = { @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py similarity index 86% rename from examples/dfp/v201711/product_package_service/get_active_product_packages.py rename to examples/ad_manager/v201808/product_package_service/get_active_product_packages.py index 9f9b1fce..bbe87d44 100755 --- a/examples/dfp/v201711/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201711') + 'ProductPackageService', version='v201808') # Create a statement to select product packages. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) @@ -39,7 +39,7 @@ def main(client): # Print out some information for each product package. print('Product package with ID "%d" and name "%s" was found.\n' % (product_package['id'], product_package['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py similarity index 88% rename from examples/dfp/v201711/product_package_service/get_all_product_packages.py rename to examples/ad_manager/v201808/product_package_service/get_all_product_packages.py index 0ef28edd..b29f1809 100755 --- a/examples/dfp/v201711/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201711') + 'ProductPackageService', version='v201808') # Create a statement to select product packages. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/product_service/__init__.py b/examples/ad_manager/v201808/product_service/__init__.py similarity index 100% rename from examples/dfp/v201805/product_service/__init__.py rename to examples/ad_manager/v201808/product_service/__init__.py diff --git a/examples/dfp/v201711/product_service/get_all_products.py b/examples/ad_manager/v201808/product_service/get_all_products.py similarity index 89% rename from examples/dfp/v201711/product_service/get_all_products.py rename to examples/ad_manager/v201808/product_service/get_all_products.py index b3a66a1c..19a4cc53 100755 --- a/examples/dfp/v201711/product_service/get_all_products.py +++ b/examples/ad_manager/v201808/product_service/get_all_products.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201711') + product_service = client.GetService('ProductService', version='v201808') # Create a statement to select products. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_service/get_products_for_product_template.py b/examples/ad_manager/v201808/product_service/get_products_for_product_template.py similarity index 87% rename from examples/dfp/v201711/product_service/get_products_for_product_template.py rename to examples/ad_manager/v201808/product_service/get_products_for_product_template.py index 26b7c369..783fd1ed 100755 --- a/examples/dfp/v201711/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201808/product_service/get_products_for_product_template.py @@ -17,17 +17,17 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201711') + product_service = client.GetService('ProductService', version='v201808') # Create a statement to select products. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('productTemplateId = :productTemplateId') .WithBindVariable('productTemplateId', product_template_id)) @@ -40,7 +40,7 @@ def main(client, product_template_id): # Print out some information for each product. print('Product with ID "%d" and name "%s" was found.\n' % (product['id'], product['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -49,5 +49,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201711/product_service/update_products.py b/examples/ad_manager/v201808/product_service/update_products.py similarity index 91% rename from examples/dfp/v201711/product_service/update_products.py rename to examples/ad_manager/v201808/product_service/update_products.py index 229fe819..242c512f 100755 --- a/examples/dfp/v201711/product_service/update_products.py +++ b/examples/ad_manager/v201808/product_service/update_products.py @@ -22,17 +22,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201711') + product_service = client.GetService('ProductService', version='v201808') # Create statement object to select a single product by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(product_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, product_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_ID) diff --git a/examples/dfp/v201805/product_template_service/__init__.py b/examples/ad_manager/v201808/product_template_service/__init__.py similarity index 100% rename from examples/dfp/v201805/product_template_service/__init__.py rename to examples/ad_manager/v201808/product_template_service/__init__.py diff --git a/examples/dfp/v201711/product_template_service/activate_product_templates.py b/examples/ad_manager/v201808/product_template_service/activate_product_templates.py similarity index 88% rename from examples/dfp/v201711/product_template_service/activate_product_templates.py rename to examples/ad_manager/v201808/product_template_service/activate_product_templates.py index 6676b7c2..7a7f8f96 100755 --- a/examples/dfp/v201711/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/activate_product_templates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the product template to activate. PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' @@ -31,10 +31,10 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201711') + 'ProductTemplateService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(product_template_id)) .Limit(1)) @@ -56,7 +56,7 @@ def main(client, product_template_id): {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: product_templates_activated += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -70,5 +70,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201711/product_template_service/create_product_templates.py b/examples/ad_manager/v201808/product_template_service/create_product_templates.py similarity index 93% rename from examples/dfp/v201711/product_template_service/create_product_templates.py rename to examples/ad_manager/v201808/product_template_service/create_product_templates.py index 2f7c2afb..8865e0b3 100755 --- a/examples/dfp/v201711/product_template_service/create_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/create_product_templates.py @@ -22,15 +22,15 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201711') + 'ProductTemplateService', version='v201808') network_service = client.GetService( - 'NetworkService', version='v201711') + 'NetworkService', version='v201808') # Create a product template. product_template = { @@ -105,5 +105,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201808/product_template_service/create_programmatic_product_templates.py similarity index 92% rename from examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py rename to examples/ad_manager/v201808/product_template_service/create_programmatic_product_templates.py index f7cc4b99..d32ccab3 100755 --- a/examples/dfp/v201711/product_template_service/create_programmatic_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/create_programmatic_product_templates.py @@ -20,14 +20,14 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201711') + 'ProductTemplateService', version='v201808') network_service = client.GetService( - 'NetworkService', version='v201711') + 'NetworkService', version='v201808') product_template = { # Setting required Marketplace information. @@ -87,5 +87,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py similarity index 88% rename from examples/dfp/v201711/product_template_service/get_all_product_templates.py rename to examples/ad_manager/v201808/product_template_service/get_all_product_templates.py index 9ca9a397..070f6e55 100755 --- a/examples/dfp/v201711/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201711') + 'ProductTemplateService', version='v201808') # Create a statement to select product templates. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py similarity index 86% rename from examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py rename to examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py index da31a375..3324a15b 100755 --- a/examples/dfp/v201711/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201711') + 'ProductTemplateService', version='v201808') # Create a statement to select product templates. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('lineItemType = :lineItemType') .WithBindVariable('lineItemType', 'SPONSORSHIP')) @@ -39,7 +39,7 @@ def main(client): # Print out some information for each product template. print('Product template with ID "%d" and name "%s" was found.\n' % (product_template['id'], product_template['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/product_template_service/update_product_templates.py b/examples/ad_manager/v201808/product_template_service/update_product_templates.py similarity index 92% rename from examples/dfp/v201711/product_template_service/update_product_templates.py rename to examples/ad_manager/v201808/product_template_service/update_product_templates.py index 3a58e9b1..18735440 100755 --- a/examples/dfp/v201711/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/update_product_templates.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' @@ -30,10 +30,10 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201711') + 'ProductTemplateService', version='v201808') # Create a statement to select a single product template by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(product_template_id)) @@ -90,5 +90,5 @@ def main(client, product_template_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PRODUCT_TEMPLATE_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/dfp/v201805/proposal_line_item_service/__init__.py b/examples/ad_manager/v201808/proposal_line_item_service/__init__.py similarity index 100% rename from examples/dfp/v201805/proposal_line_item_service/__init__.py rename to examples/ad_manager/v201808/proposal_line_item_service/__init__.py diff --git a/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py similarity index 89% rename from examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py index b178b4b8..a19b5739 100755 --- a/examples/dfp/v201711/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the id of the proposal line item to archive. PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201711') + 'ProposalLineItemService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, proposal_line_item_id): {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposal_line_items_archived += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -72,5 +72,5 @@ def main(client, proposal_line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 93% rename from examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items.py index 1654e9aa..0892fc58 100755 --- a/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -22,7 +22,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set the ID of the programmatic proposal that the proposal line item will @@ -40,8 +40,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201711') - network_service = client.GetService('NetworkService', version='v201711') + 'ProposalLineItemService', version='v201808') + network_service = client.GetService('NetworkService', version='v201808') # Get the root ad unit to target. root_ad_unit_id = ( @@ -99,6 +99,6 @@ def main(client, proposal_id, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 93% rename from examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index 0f204be9..f0728dd9 100755 --- a/examples/dfp/v201711/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -22,7 +22,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set proposal that the created proposal line item will belong to. @@ -34,8 +34,8 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201711') - network_service = client.GetService('NetworkService', version='v201711') + 'ProposalLineItemService', version='v201808') + network_service = client.GetService('NetworkService', version='v201808') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) @@ -105,6 +105,6 @@ def main(client, proposal_id, product_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID) diff --git a/examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/create_proposal_line_items.py similarity index 93% rename from examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v201808/proposal_line_item_service/create_proposal_line_items.py index 972bb150..4c479b74 100755 --- a/examples/dfp/v201711/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/create_proposal_line_items.py @@ -26,7 +26,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz # Set proposal that the created proposal line item will belong to. @@ -42,8 +42,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201711') - network_service = client.GetService('NetworkService', version='v201711') + 'ProposalLineItemService', version='v201808') + network_service = client.GetService('NetworkService', version='v201808') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) @@ -100,6 +100,6 @@ def main(client, proposal_id, product_id, rate_card_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py similarity index 88% rename from examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py index a7142e6f..9762b0cb 100755 --- a/examples/dfp/v201711/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201711') + 'ProposalLineItemService', version='v201808') # Create a statement to select proposal line items. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 86% rename from examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 59c8dd5c..1af67b0c 100755 --- a/examples/dfp/v201711/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201711') + 'ProposalLineItemService', version='v201808') # Create a statement to select proposal line items. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) @@ -41,7 +41,7 @@ def main(client, proposal_id): # Print out some information for each proposal line item. print('Proposal line item with ID "%d" and name "%s" was found.\n' % (proposal_line_item['id'], proposal_line_item['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -50,5 +50,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py similarity index 90% rename from examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py index 2f4b1c32..7293adb3 100755 --- a/examples/dfp/v201711/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set id of the proposal line item to update. PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201711') + 'ProposalLineItemService', version='v201808') # Create statement to select a proposal line item. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) @@ -68,5 +68,5 @@ def main(client, proposal_line_item_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_LINE_ITEM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/dfp/v201805/proposal_service/__init__.py b/examples/ad_manager/v201808/proposal_service/__init__.py similarity index 100% rename from examples/dfp/v201805/proposal_service/__init__.py rename to examples/ad_manager/v201808/proposal_service/__init__.py diff --git a/examples/dfp/v201711/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals.py similarity index 90% rename from examples/dfp/v201711/proposal_service/create_programmatic_proposals.py rename to examples/ad_manager/v201808/proposal_service/create_programmatic_proposals.py index 861f71b0..a913573a 100755 --- a/examples/dfp/v201711/proposal_service/create_programmatic_proposals.py +++ b/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201711') - network_service = client.GetService('NetworkService', version='v201711') + proposal_service = client.GetService('ProposalService', version='v201808') + network_service = client.GetService('NetworkService', version='v201808') proposal = { # Setting required Marketplace information. @@ -66,6 +66,6 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID, - BUYER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID, BUYER_ID) diff --git a/examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 91% rename from examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/ad_manager/v201808/proposal_service/create_programmatic_proposals_for_non_sales_management.py index fdef1830..a7b50ed0 100755 --- a/examples/dfp/v201711/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -20,7 +20,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201711') + proposal_service = client.GetService('ProposalService', version='v201808') proposal = { # Setting required Marketplace information. @@ -57,6 +57,6 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201711/proposal_service/create_proposals.py b/examples/ad_manager/v201808/proposal_service/create_proposals.py similarity index 92% rename from examples/dfp/v201711/proposal_service/create_proposals.py rename to examples/ad_manager/v201808/proposal_service/create_proposals.py index 0a800e90..a68b4e30 100755 --- a/examples/dfp/v201711/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201808/proposal_service/create_proposals.py @@ -23,7 +23,7 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201711') - network_service = client.GetService('NetworkService', version='v201711') + proposal_service = client.GetService('ProposalService', version='v201808') + network_service = client.GetService('NetworkService', version='v201808') # Create proposal objects. proposal = { @@ -72,6 +72,6 @@ def main(client, advertiser_id, primary_salesperson_id, if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/dfp/v201711/proposal_service/get_all_proposals.py b/examples/ad_manager/v201808/proposal_service/get_all_proposals.py similarity index 89% rename from examples/dfp/v201711/proposal_service/get_all_proposals.py rename to examples/ad_manager/v201808/proposal_service/get_all_proposals.py index 7318822e..3e1931d7 100755 --- a/examples/dfp/v201711/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201808/proposal_service/get_all_proposals.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201711') + proposal_service = client.GetService('ProposalService', version='v201808') # Create a statement to select proposals. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201808/proposal_service/get_marketplace_comments.py similarity index 91% rename from examples/dfp/v201711/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v201808/proposal_service/get_marketplace_comments.py index 08ae7a05..3dc4943f 100755 --- a/examples/dfp/v201711/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201808/proposal_service/get_marketplace_comments.py @@ -19,7 +19,7 @@ # Import appropriate modules from the client library. from datetime import datetime -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201711') + 'ProposalService', version='v201808') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} @@ -52,5 +52,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py similarity index 87% rename from examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py rename to examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py index cba14225..4fcaf11d 100755 --- a/examples/dfp/v201711/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py @@ -17,14 +17,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201711') + proposal_service = client.GetService('ProposalService', version='v201808') # Create a statement to select proposals. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('status = :status') .WithBindVariable('status', 'PENDING_APPROVAL')) @@ -37,7 +37,7 @@ def main(client): # Print out some information for each proposal. print('Proposal with ID "%d" and name "%s" was found.\n' % (proposal['id'], proposal['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -46,5 +46,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py similarity index 90% rename from examples/dfp/v201711/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py index 4c61d9c8..9d534ccf 100755 --- a/examples/dfp/v201711/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py @@ -19,17 +19,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201711') + proposal_service = client.GetService('ProposalService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 @@ -49,7 +49,7 @@ def main(client, proposal_id): {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposals_pushed_to_marketplace += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -63,5 +63,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py similarity index 89% rename from examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py rename to examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py index b19ecdd4..b2e9d33b 100755 --- a/examples/dfp/v201711/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py @@ -21,17 +21,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201711') + proposal_service = client.GetService('ProposalService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 @@ -50,7 +50,7 @@ def main(client, proposal_id): {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: proposals_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -63,5 +63,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201711/proposal_service/update_proposals.py b/examples/ad_manager/v201808/proposal_service/update_proposals.py similarity index 91% rename from examples/dfp/v201711/proposal_service/update_proposals.py rename to examples/ad_manager/v201808/proposal_service/update_proposals.py index 06dbe9f6..bfddcaae 100755 --- a/examples/dfp/v201711/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201808/proposal_service/update_proposals.py @@ -21,18 +21,18 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201711') + proposal_service = client.GetService('ProposalService', version='v201808') # Create statement object to select a single proposal by an ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :proposalId') .WithBindVariable('proposalId', long(proposal_id)) .Limit(1)) @@ -64,5 +64,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201805/publisher_query_language_service/__init__.py b/examples/ad_manager/v201808/publisher_query_language_service/__init__.py similarity index 100% rename from examples/dfp/v201805/publisher_query_language_service/__init__.py rename to examples/ad_manager/v201808/publisher_query_language_service/__init__.py diff --git a/examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201808/publisher_query_language_service/fetch_match_tables.py similarity index 90% rename from examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v201808/publisher_query_language_service/fetch_match_tables.py index 6f4c30fa..f1d1fe7f 100755 --- a/examples/dfp/v201711/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201808/publisher_query_language_service/fetch_match_tables.py @@ -20,12 +20,12 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201808/publisher_query_language_service/get_all_browsers.py similarity index 89% rename from examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v201808/publisher_query_language_service/get_all_browsers.py index 9c715c66..98b4867c 100755 --- a/examples/dfp/v201711/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201808/publisher_query_language_service/get_all_browsers.py @@ -27,12 +27,12 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') with tempfile.NamedTemporaryFile( prefix='browser_data_', @@ -51,5 +51,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201808/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 88% rename from examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v201808/publisher_query_language_service/get_all_programmatic_buyers.py index 1373e34c..68209369 100755 --- a/examples/dfp/v201711/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201808/publisher_query_language_service/get_all_programmatic_buyers.py @@ -20,12 +20,12 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201711') + data_downloader = client.GetDataDownloader(version='v201808') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201808/publisher_query_language_service/get_geo_targets.py similarity index 86% rename from examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v201808/publisher_query_language_service/get_geo_targets.py index ee80ecce..95c363ab 100755 --- a/examples/dfp/v201711/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201808/publisher_query_language_service/get_geo_targets.py @@ -20,7 +20,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the type of geo target to query for. GEO_TARGET_TYPE = 'City' @@ -28,14 +28,14 @@ def main(client, geo_target_type): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') with tempfile.NamedTemporaryFile( prefix='geo_data_', suffix='.csv', mode='w', delete=False) as geo_data_file: geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' - 'CountryCode ' + 'CountryCode, Type ' 'FROM Geo_Target ' 'WHERE Type = :type AND Targetable = true ' 'ORDER BY CountryCode ASC, Name ASC') @@ -49,5 +49,5 @@ def main(client, geo_target_type): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, GEO_TARGET_TYPE) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, GEO_TARGET_TYPE) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201808/publisher_query_language_service/get_line_items_named_like.py similarity index 88% rename from examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v201808/publisher_query_language_service/get_line_items_named_like.py index baba6a1d..c6a78875 100755 --- a/examples/dfp/v201711/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201808/publisher_query_language_service/get_line_items_named_like.py @@ -20,12 +20,12 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') with tempfile.NamedTemporaryFile( prefix='line_items_', @@ -44,5 +44,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py similarity index 95% rename from examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py index 41eb34c6..4452858c 100755 --- a/examples/dfp/v201711/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py @@ -25,13 +25,13 @@ from datetime import timedelta # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager import pytz def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201711') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201808') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') @@ -105,7 +105,7 @@ def ConvertValueForCsv(pql_value): return ','.join(['"%s"' % str(ConvertValueForCsv(single_field)) for single_field in field]) else: - class_type = dfp.DfpClassType(pql_value) + class_type = ad_manager.AdManagerClassType(pql_value) if class_type == 'TextValue': return field.replace('"', '""').encode('UTF8') @@ -152,5 +152,5 @@ def ConvertDateTimeToOffset(date_time_value): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/rate_card_service/__init__.py b/examples/ad_manager/v201808/rate_card_service/__init__.py similarity index 100% rename from examples/dfp/v201805/rate_card_service/__init__.py rename to examples/ad_manager/v201808/rate_card_service/__init__.py diff --git a/examples/dfp/v201711/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201808/rate_card_service/create_rate_cards.py similarity index 92% rename from examples/dfp/v201711/rate_card_service/create_rate_cards.py rename to examples/ad_manager/v201808/rate_card_service/create_rate_cards.py index d7acfcf9..09ee2ae9 100755 --- a/examples/dfp/v201711/rate_card_service/create_rate_cards.py +++ b/examples/ad_manager/v201808/rate_card_service/create_rate_cards.py @@ -22,7 +22,7 @@ # Import appropriate modules from the client library. import random -from googleads import dfp +from googleads import ad_manager # Set the IDs of the teams this rate card should be visible to. TEAM_IDS = ['INSERT_TEAM_ID_HERE'] @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201711') + rate_card_service = client.GetService('RateCardService', version='v201808') # Create a rate card. rate_card = { @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py similarity index 89% rename from examples/dfp/v201711/rate_card_service/get_all_rate_cards.py rename to examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py index e3284911..018787ee 100755 --- a/examples/dfp/v201711/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201711') + rate_card_service = client.GetService('RateCardService', version='v201808') # Create a statement to select rate cards. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. @@ -47,5 +47,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py similarity index 88% rename from examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py rename to examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py index 833e526b..e4d4f73d 100755 --- a/examples/dfp/v201711/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py @@ -18,14 +18,14 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201711') + rate_card_service = client.GetService('RateCardService', version='v201808') # Create a statement to select rate cards. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('forMarketplace = :forMarketplace') .WithBindVariable('forMarketplace', True)) @@ -41,7 +41,7 @@ def main(client): 'Rate card with ID "%d", name "%s", and currency code "%s" was ' 'found.\n' % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -50,5 +50,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 92% rename from examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index e2a4e2e7..cdde9f62 100755 --- a/examples/dfp/v201711/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report to query. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201711')) + 'ReconciliationLineItemReportService', version='v201808')) # Create a statement to select reconciliation line item reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('reconciliationReportId = :reconciliationReportId AND ' 'lineItemId != :lineItemId')) .OrderBy('lineItemId', ascending=True) @@ -71,5 +71,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 89% rename from examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index bdd94b5a..a8afd3d9 100755 --- a/examples/dfp/v201711/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation line item report to update. RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201711')) + 'ReconciliationLineItemReportService', version='v201808')) # Create a statement to select a reconciliation line item report. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :lineItemReportId') .OrderBy('id', ascending=True) .Limit(1) @@ -47,7 +47,7 @@ def main(client): line_item_report = page['results'][0] # Set and use a manual volume for billing. This example splits the difference - # between DFP and the third party volume. + # between Ad Manager and the third party volume. line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + line_item_report['thirdPartyVolume']) / 2 line_item_report['reconciliationSource'] = 'MANUAL' @@ -63,5 +63,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 87% rename from examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 3972269e..9d1d8503 100755 --- a/examples/dfp/v201711/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -25,9 +25,9 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201711') + 'ReconciliationOrderReportService', version='v201808') # Create a statement to select reconciliation order reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('reconciliationReportId = :reconciliationReportId') .WithBindVariable('reconciliationReportId', reconciliation_report_id)) @@ -45,7 +45,7 @@ def main(client, reconciliation_report_id): print('Reconciliation order report with ID "%d" and status "%s" was ' 'found.\n' % (reconciliation_order_report['id'], reconciliation_order_report['status'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -54,5 +54,5 @@ def main(client, reconciliation_report_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 90% rename from examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 4e3b4a82..c9d2475c 100755 --- a/examples/dfp/v201711/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation order report to submit. RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201711')) + 'ReconciliationOrderReportService', version='v201808')) # Create a statement to select reconciliation order reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -67,5 +67,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 85% rename from examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index a0d975b6..fb6f9ff3 100755 --- a/examples/dfp/v201711/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Gets a reconciliation report's rows for line items that served through DFP. +"""Gets a reconciliation report's rows for line items that Ad Manager served. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' @@ -27,10 +27,10 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201711') + 'ReconciliationReportRowService', version='v201808') # Create a statement to select reconciliation report rows. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) @@ -51,7 +51,7 @@ def main(client, reconciliation_report_id): (reconciliation_report_row['id'], reconciliation_report_row['reconciliationSource'], reconciliation_report_row['reconciledVolume'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -60,5 +60,5 @@ def main(client, reconciliation_report_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, RECONCILIATION_REPORT_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 92% rename from examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py index 99b28783..0dd3adfa 100755 --- a/examples/dfp/v201711/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -21,7 +21,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager # Set the ID of the reconciliation report row. RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' @@ -33,10 +33,10 @@ def main(client): # Initialize appropriate service. reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201711')) + 'ReconciliationReportRowService', version='v201808')) # Create a statement to select reconciliation report rows. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('id = :reconciliationReportRowId AND ' 'reconciliationReportId = :reconciliationReportId')) .OrderBy('id', ascending=True) @@ -71,5 +71,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 89% rename from examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py index 90ec2152..21d50ee6 100755 --- a/examples/dfp/v201711/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201711') + 'ReconciliationReportService', version='v201808') # Create a statement to select reconciliation reports. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. @@ -52,5 +52,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 88% rename from examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 9b4ed1e2..2dcfdb25 100755 --- a/examples/dfp/v201711/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -20,19 +20,19 @@ from datetime import date from datetime import timedelta -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201711') + 'ReconciliationReportService', version='v201808') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) # Create a statement to select reconciliation reports. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('startDate = :startDate') .WithBindVariable('startDate', last_month)) @@ -50,7 +50,7 @@ def main(client): 'Reconciliation report with ID "%d" and start date "%s" was found.' '\n' % (reconciliation_report['id'], last_month.strftime('%Y-%m-01'))) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -59,5 +59,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201805/report_service/__init__.py b/examples/ad_manager/v201808/report_service/__init__.py similarity index 100% rename from examples/dfp/v201805/report_service/__init__.py rename to examples/ad_manager/v201808/report_service/__init__.py diff --git a/examples/ad_manager/v201808/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201808/report_service/run_ad_exchange_report.py new file mode 100755 index 00000000..2d63b13f --- /dev/null +++ b/examples/ad_manager/v201808/report_service/run_ad_exchange_report.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Runs a report on Ad Exchange data via the Ad Manager API.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201808') + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'], + 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS', + 'AD_EXCHANGE_ESTIMATED_REVENUE'], + 'dateRangeType': 'LAST_WEEK', + 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time + 'adxReportCurrency': 'EUR' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/report_service/run_delivery_report.py b/examples/ad_manager/v201808/report_service/run_delivery_report.py similarity index 87% rename from examples/dfp/v201711/report_service/run_delivery_report.py rename to examples/ad_manager/v201808/report_service/run_delivery_report.py index 3bbc7c8f..4577f38a 100755 --- a/examples/dfp/v201711/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201808/report_service/run_delivery_report.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Runs a report similar to the "Orders report" on the DFP website. +"""Runs a report similar to the "Orders report" on the Ad Manager website. Includes additional attributes and can filter to include just one order. """ @@ -24,7 +24,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors ORDER_ID = 'INSERT_ORDER_ID_HERE' @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('ORDER_ID = :id') .WithBindVariable('id', long(order_id)) .Limit(None) # No limit or offset for reports @@ -59,12 +59,12 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -84,5 +84,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201711/report_service/run_inventory_report.py b/examples/ad_manager/v201808/report_service/run_inventory_report.py similarity index 89% rename from examples/dfp/v201711/report_service/run_inventory_report.py rename to examples/ad_manager/v201808/report_service/run_inventory_report.py index a7abcb2e..eedde178 100755 --- a/examples/dfp/v201711/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201808/report_service/run_inventory_report.py @@ -19,22 +19,22 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201711') + network_service = client.GetService('NetworkService', version='v201808') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) .Limit(None) # No limit or offset for reports @@ -58,7 +58,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -78,5 +78,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/report_service/run_reach_report.py b/examples/ad_manager/v201808/report_service/run_reach_report.py similarity index 88% rename from examples/dfp/v201711/report_service/run_reach_report.py rename to examples/ad_manager/v201808/report_service/run_reach_report.py index 53b8ab8f..df777ee5 100755 --- a/examples/dfp/v201711/report_service/run_reach_report.py +++ b/examples/ad_manager/v201808/report_service/run_reach_report.py @@ -19,13 +19,13 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') # Create report job. report_job = { @@ -39,7 +39,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -60,5 +60,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201808/report_service/run_report_and_create_match_table.py similarity index 92% rename from examples/dfp/v201711/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v201808/report_service/run_report_and_create_match_table.py index 777304d0..95a42819 100755 --- a/examples/dfp/v201711/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201808/report_service/run_report_and_create_match_table.py @@ -26,7 +26,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors try: @@ -54,12 +54,12 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e with tempfile.NamedTemporaryFile( @@ -84,5 +84,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py similarity index 89% rename from examples/dfp/v201711/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py index 208fbd0c..d5d37cc5 100755 --- a/examples/dfp/v201711/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py @@ -19,7 +19,7 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors # Set the ID of the order to get line items from. @@ -28,12 +28,12 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201711') + line_item_service = client.GetService('LineItemService', version='v201808') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') # Filter for line items of a given order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('orderId = :orderId') .WithBindVariable('orderId', long(order_id))) @@ -50,7 +50,7 @@ def main(client, order_id): if 'customFieldValues' in line_item: for custom_field_value in line_item['customFieldValues']: custom_field_ids.add(custom_field_value['customFieldId']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -73,7 +73,7 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -93,5 +93,5 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ORDER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/dfp/v201711/report_service/run_sales_report.py b/examples/ad_manager/v201808/report_service/run_sales_report.py similarity index 88% rename from examples/dfp/v201711/report_service/run_sales_report.py rename to examples/ad_manager/v201808/report_service/run_sales_report.py index e5b5663d..08009cb7 100755 --- a/examples/dfp/v201711/report_service/run_sales_report.py +++ b/examples/ad_manager/v201808/report_service/run_sales_report.py @@ -19,13 +19,13 @@ import tempfile # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager from googleads import errors def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') # Create report job. report_job = { @@ -40,7 +40,7 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. @@ -60,5 +60,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/report_service/run_saved_query.py b/examples/ad_manager/v201808/report_service/run_saved_query.py similarity index 88% rename from examples/dfp/v201711/report_service/run_saved_query.py rename to examples/ad_manager/v201808/report_service/run_saved_query.py index 027295cb..2ad90375 100755 --- a/examples/dfp/v201711/report_service/run_saved_query.py +++ b/examples/ad_manager/v201808/report_service/run_saved_query.py @@ -20,7 +20,7 @@ # Import appropriate modules from the client library. import tempfile -from googleads import dfp +from googleads import ad_manager from googleads import errors SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201711') + report_service = client.GetService('ReportService', version='v201808') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201711') + report_downloader = client.GetDataDownloader(version='v201808') # Create statement object to filter for an order. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :id') .WithBindVariable('id', long(saved_query_id)) .Limit(1)) @@ -54,7 +54,7 @@ def main(client, saved_query_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.DfpReportError, e: + except errors.AdManagerReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -76,5 +76,5 @@ def main(client, saved_query_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, SAVED_QUERY_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, SAVED_QUERY_ID) diff --git a/examples/dfp/v201805/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201808/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/dfp/v201805/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v201808/suggested_ad_unit_service/__init__.py diff --git a/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 82% rename from examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py index b5812f0f..04dfafb9 100755 --- a/examples/dfp/v201711/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -16,12 +16,12 @@ """This code example approves all suggested ad units with 50 or more requests. -This feature is only available to DFP premium solution networks. +This feature is only available to Ad Manager 360 solution networks. """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager THRESHOLD_NUMBER_OF_REQUESTS = '50' @@ -29,20 +29,12 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201711') - - values = [{ - 'key': 'numRequests', - 'value': { - 'xsi_type': 'NumberValue', - 'value': THRESHOLD_NUMBER_OF_REQUESTS - } - }] - - query = 'WHERE numRequests > :numRequests' + 'SuggestedAdUnitService', version='v201808') # Create a filter statement. - statement = dfp.FilterStatement(query, values) + statement = (ad_manager.StatementBuilder() + .Where('numRequests > :numRequests') + .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 # Get suggested ad units by statement. @@ -73,6 +65,6 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 88% rename from examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py index ef251fc6..1ec2ae9d 100755 --- a/examples/dfp/v201711/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201711') + 'SuggestedAdUnitService', version='v201808') # Create a statement to select suggested ad units. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 86% rename from examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 2ca20b51..b97550b0 100755 --- a/examples/dfp/v201711/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE' @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201711') + 'SuggestedAdUnitService', version='v201808') # Create a statement to select suggested ad units. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', long(num_requests))) @@ -42,7 +42,7 @@ def main(client, num_requests): print( 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -51,5 +51,5 @@ def main(client, num_requests): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, NUM_REQUESTS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, NUM_REQUESTS) diff --git a/examples/dfp/v201805/team_service/__init__.py b/examples/ad_manager/v201808/team_service/__init__.py similarity index 100% rename from examples/dfp/v201805/team_service/__init__.py rename to examples/ad_manager/v201808/team_service/__init__.py diff --git a/examples/dfp/v201711/team_service/create_teams.py b/examples/ad_manager/v201808/team_service/create_teams.py similarity index 89% rename from examples/dfp/v201711/team_service/create_teams.py rename to examples/ad_manager/v201808/team_service/create_teams.py index df551d17..f8044f8c 100755 --- a/examples/dfp/v201711/team_service/create_teams.py +++ b/examples/ad_manager/v201808/team_service/create_teams.py @@ -28,12 +28,12 @@ import uuid # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201711') + team_service = client.GetService('TeamService', version='v201808') # Create team objects. teams = [] @@ -56,5 +56,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/team_service/get_all_teams.py b/examples/ad_manager/v201808/team_service/get_all_teams.py similarity index 86% rename from examples/dfp/v201711/team_service/get_all_teams.py rename to examples/ad_manager/v201808/team_service/get_all_teams.py index d3d06b87..c5830cb4 100755 --- a/examples/dfp/v201711/team_service/get_all_teams.py +++ b/examples/ad_manager/v201808/team_service/get_all_teams.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201711') + team_service = client.GetService('TeamService', version='v201808') # Create a statement to select teams. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/team_service/update_teams.py b/examples/ad_manager/v201808/team_service/update_teams.py similarity index 88% rename from examples/dfp/v201711/team_service/update_teams.py rename to examples/ad_manager/v201808/team_service/update_teams.py index 2f06f9fd..c5d221dd 100755 --- a/examples/dfp/v201711/team_service/update_teams.py +++ b/examples/ad_manager/v201808/team_service/update_teams.py @@ -27,17 +27,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager TEAM_ID = 'INSERT_TEAM_ID_HERE' def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201711') + team_service = client.GetService('TeamService', version='v201808') # Create a filter statement to select a single team by ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :teamId') .WithBindVariable('teamId', long(team_id))) @@ -64,5 +64,5 @@ def main(client, team_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TEAM_ID) diff --git a/examples/dfp/v201805/user_service/__init__.py b/examples/ad_manager/v201808/user_service/__init__.py similarity index 100% rename from examples/dfp/v201805/user_service/__init__.py rename to examples/ad_manager/v201808/user_service/__init__.py diff --git a/examples/dfp/v201711/user_service/create_users.py b/examples/ad_manager/v201808/user_service/create_users.py similarity index 86% rename from examples/dfp/v201711/user_service/create_users.py rename to examples/ad_manager/v201808/user_service/create_users.py index cbdf701b..7cfd32d2 100755 --- a/examples/dfp/v201711/user_service/create_users.py +++ b/examples/ad_manager/v201808/user_service/create_users.py @@ -21,7 +21,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' NEW_USER_NAME = 'INSERT_NAME_HERE' @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201711') + user_service = client.GetService('UserService', version='v201808') # Create user objects. users = [ @@ -53,5 +53,5 @@ def main(client, email, name): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) diff --git a/examples/dfp/v201711/user_service/deactivate_users.py b/examples/ad_manager/v201808/user_service/deactivate_users.py similarity index 88% rename from examples/dfp/v201711/user_service/deactivate_users.py rename to examples/ad_manager/v201808/user_service/deactivate_users.py index 60cabd9a..97040aa9 100755 --- a/examples/dfp/v201711/user_service/deactivate_users.py +++ b/examples/ad_manager/v201808/user_service/deactivate_users.py @@ -23,17 +23,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE' def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201711') + user_service = client.GetService('UserService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :userId') .WithBindVariable('userId', long(user_id))) @@ -61,5 +61,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201711/user_service/get_all_roles.py b/examples/ad_manager/v201808/user_service/get_all_roles.py similarity index 90% rename from examples/dfp/v201711/user_service/get_all_roles.py rename to examples/ad_manager/v201808/user_service/get_all_roles.py index bb2bec62..442d35bd 100755 --- a/examples/dfp/v201711/user_service/get_all_roles.py +++ b/examples/ad_manager/v201808/user_service/get_all_roles.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): @@ -36,5 +36,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/user_service/get_all_users.py b/examples/ad_manager/v201808/user_service/get_all_users.py similarity index 86% rename from examples/dfp/v201711/user_service/get_all_users.py rename to examples/ad_manager/v201808/user_service/get_all_users.py index c846a6a3..aa05b4fc 100755 --- a/examples/dfp/v201711/user_service/get_all_users.py +++ b/examples/ad_manager/v201808/user_service/get_all_users.py @@ -17,15 +17,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201711') + user_service = client.GetService('UserService', version='v201808') # Create a statement to select users. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. @@ -45,5 +45,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/user_service/get_current_user.py b/examples/ad_manager/v201808/user_service/get_current_user.py similarity index 84% rename from examples/dfp/v201711/user_service/get_current_user.py rename to examples/ad_manager/v201808/user_service/get_current_user.py index c1f43169..94d55e55 100755 --- a/examples/dfp/v201711/user_service/get_current_user.py +++ b/examples/ad_manager/v201808/user_service/get_current_user.py @@ -17,12 +17,12 @@ """This example gets the current user.""" # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201711') + user_service = client.GetService('UserService', version='v201808') # Get current user. user = user_service.getCurrentUser() @@ -35,5 +35,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/user_service/get_user_by_email_address.py b/examples/ad_manager/v201808/user_service/get_user_by_email_address.py similarity index 84% rename from examples/dfp/v201711/user_service/get_user_by_email_address.py rename to examples/ad_manager/v201808/user_service/get_user_by_email_address.py index f7fb6391..93a933b0 100755 --- a/examples/dfp/v201711/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201808/user_service/get_user_by_email_address.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201711') + user_service = client.GetService('UserService', version='v201808') # Create a statement to select users. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('email = :email') .WithBindVariable('email', email_address)) @@ -39,7 +39,7 @@ def main(client, email_address): # Print out some information for each user. print('User with ID "%d" and name "%s" was found.\n' % (user['id'], user['name'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -48,5 +48,5 @@ def main(client, email_address): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, EMAIL_ADDRESS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, EMAIL_ADDRESS) diff --git a/examples/dfp/v201711/user_service/update_users.py b/examples/ad_manager/v201808/user_service/update_users.py similarity index 86% rename from examples/dfp/v201711/user_service/update_users.py rename to examples/ad_manager/v201808/user_service/update_users.py index da906f31..eff3a2c1 100755 --- a/examples/dfp/v201711/user_service/update_users.py +++ b/examples/ad_manager/v201808/user_service/update_users.py @@ -21,17 +21,17 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201711') + user_service = client.GetService('UserService', version='v201808') # Create query. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('id = :userId') .WithBindVariable('userId', long(user_id))) @@ -54,5 +54,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201805/user_team_association_service/__init__.py b/examples/ad_manager/v201808/user_team_association_service/__init__.py similarity index 100% rename from examples/dfp/v201805/user_team_association_service/__init__.py rename to examples/ad_manager/v201808/user_team_association_service/__init__.py diff --git a/examples/dfp/v201711/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/create_user_team_associations.py similarity index 91% rename from examples/dfp/v201711/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v201808/user_team_association_service/create_user_team_associations.py index 5a8ee9cd..c37f417d 100755 --- a/examples/dfp/v201711/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201808/user_team_association_service/create_user_team_associations.py @@ -28,7 +28,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager TEAM_ID = 'INSERT_TEAM_ID_HERE' USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE'] @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201711') + 'UserTeamAssociationService', version='v201808') user_team_associations = [] for user_id in user_ids: @@ -63,5 +63,5 @@ def main(client, team_id, user_ids): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, TEAM_ID, USER_IDS) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TEAM_ID, USER_IDS) diff --git a/examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py similarity index 91% rename from examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py index b0dd9259..8bf6fc90 100755 --- a/examples/dfp/v201711/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py @@ -27,7 +27,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_HERE' @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201711') + 'UserTeamAssociationService', version='v201808') # Create filter text to select user team associations by the user ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -73,5 +73,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py similarity index 88% rename from examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py index e2c171e1..43f481b8 100755 --- a/examples/dfp/v201711/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py @@ -17,16 +17,16 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201711') + 'UserTeamAssociationService', version='v201808') # Create a statement to select user team associations. - statement = dfp.StatementBuilder() + statement = ad_manager.StatementBuilder() # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -48,5 +48,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py similarity index 87% rename from examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py index d686c980..b73f043d 100755 --- a/examples/dfp/v201711/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py @@ -17,7 +17,7 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_HERE' @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201711') + 'UserTeamAssociationService', version='v201808') # Create a statement to select user team associations. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -42,7 +42,7 @@ def main(client, user_id): print('User team association with user ID "%d" and team ID "%d" was ' 'found.\n' % (user_team_association['userId'], user_team_association['teamId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -51,5 +51,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py similarity index 92% rename from examples/dfp/v201711/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py index 1076ebb8..4fac863d 100755 --- a/examples/dfp/v201711/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py @@ -29,7 +29,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201711') + 'UserTeamAssociationService', version='v201808') # Create filter text to select user team associations by the user ID. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) @@ -74,5 +74,5 @@ def main(client, user_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, USER_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/dfp/v201805/workflow_request_service/__init__.py b/examples/ad_manager/v201808/workflow_request_service/__init__.py similarity index 100% rename from examples/dfp/v201805/workflow_request_service/__init__.py rename to examples/ad_manager/v201808/workflow_request_service/__init__.py diff --git a/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py similarity index 89% rename from examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py rename to examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py index 824c24f9..c970542e 100755 --- a/examples/dfp/v201711/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -31,10 +31,10 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201711') + version='v201808') # Create a filter statement. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) @@ -58,7 +58,7 @@ def main(client, proposal_id): statement.ToStatement()) if result and int(result['numChanges']) > 0: workflow_approval_requests_approved += int(result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -71,5 +71,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py similarity index 87% rename from examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py rename to examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py index 1c083cb6..cf2f07b5 100755 --- a/examples/dfp/v201711/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py @@ -20,15 +20,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201711') + 'WorkflowRequestService', version='v201808') # Create a statement to select workflow requests. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) @@ -44,7 +44,7 @@ def main(client): '"%d" was found.\n' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py similarity index 88% rename from examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py index 9d257e7d..91f85bf0 100755 --- a/examples/dfp/v201711/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py @@ -20,15 +20,15 @@ """ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201711') + 'WorkflowRequestService', version='v201808') # Create a statement to select workflow requests. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) @@ -44,7 +44,7 @@ def main(client): '"%d" was found.\n' % (workflow_request['id'], workflow_request['entityType'], workflow_request['entityId'])) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -53,5 +53,5 @@ def main(client): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 90% rename from examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py index 4b24ba54..2728d725 100755 --- a/examples/dfp/v201711/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -23,7 +23,7 @@ # Import appropriate modules from the client library. -from googleads import dfp +from googleads import ad_manager PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' @@ -31,10 +31,10 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201711') + version='v201808') # Create a filter statement. - statement = (dfp.StatementBuilder() + statement = (ad_manager.StatementBuilder() .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) @@ -61,7 +61,7 @@ def main(client, proposal_id): if result and int(result['numChanges']) > 0: workflow_external_condition_requests_triggered += int( result['numChanges']) - statement.offset += dfp.SUGGESTED_PAGE_LIMIT + statement.offset += statement.limit else: break @@ -74,5 +74,5 @@ def main(client, proposal_id): if __name__ == '__main__': # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, PROPOSAL_ID) + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py deleted file mode 100755 index 30327029..00000000 --- a/examples/dfp/v201711/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example deletes content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to DFP video publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import dfp - -# Set the ID of the content metadata key hierarchy to delete. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') - - -def main(client, content_metadata_key_hierarchy_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201711') - - # Create a query to select a single content metadata key hierarchy. - - statement = (dfp.StatementBuilder() - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) - .Limit(1)) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())[0]) - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - # Display results. - if content_metadata_key_hierarchies: - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with ID "%s" and name "%s" ' - 'will be deleted.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - # Perform action. - result = (content_metadata_key_hierarchy_service - .performContentMetadataKeyHierarchyAction( - {'type': 'DeleteContentMetadataKeyHierarchies'}, - statement.ToStatement()))[0] - - # Display results. - print ('Number of content metadata key hierarchies deleted: %s' % - result['numChanges']) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, CONTENT_METADATA_KEY_HIERARCHY_ID) diff --git a/examples/dfp/v201711/forecast_service/get_availability_forecast.py b/examples/dfp/v201711/forecast_service/get_availability_forecast.py deleted file mode 100755 index 24916d0b..00000000 --- a/examples/dfp/v201711/forecast_service/get_availability_forecast.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 a forecast for a prospective line item. - -The prospective line item targets the entire network. The targeting can be -modified to determine forecasts for other criteria such as custom criteria -targeting (in addition to targeting the whole network). See -create_line_items.py for an example of how to create more complex targeting. - -""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import dfp -import pytz - -# Set the ID of the advertiser (company) to forecast for. Setting an advertiser -# will cause the forecast to apply the appropriate unified blocking rules. -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201711') - network_service = client.GetService('NetworkService', version='v201711') - - # get the root ad unit ID to target the entire network. - root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime += datetime.timedelta(days=30) - - # Create prospective line item. - line_item = { - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': [ - { - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id, - } - ] - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '300', - 'height': '250' - } - }, - { - 'size': { - 'width': '120', - 'height': '600' - } - } - ], - 'lineItemType': 'SPONSORSHIP', - 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': end_datetime, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'DAILY' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'EVEN', - 'discountType': 'PERCENTAGE', - } - - prospective_line_item = { - 'lineItem': line_item, - 'advertiserId': advertiser_id - } - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - 'includeTargetingCriteriaBreakdown': True, - } - - # Get forecast. - forecast = forecast_service.getAvailabilityForecast( - prospective_line_item, forecast_options) - matched = long(forecast['matchedUnits']) - available_units = long(forecast['availableUnits']) - - if matched > 0: - available_percent = (float(available_units) / matched) * 100. - else: - available_percent = 0 - - contending_line_items = getattr(forecast, 'contentingLineItems', []) - - # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) - - if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - - -if __name__ == '__main__': - # Initialize client object. - dfp_client = dfp.DfpClient.LoadFromStorage() - main(dfp_client, ADVERTISER_ID) diff --git a/googleads.yaml b/googleads.yaml index 7e31c359..202bd0ae 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -37,8 +37,8 @@ adwords: # use_raw_enum_values: False -# DfpClient configurations -dfp: +# AdManagerClient configurations +ad_manager: ############################################################################# # Required Fields # ############################################################################# diff --git a/googleads/__init__.py b/googleads/__init__.py index 1f5e6526..63f5b65d 100644 --- a/googleads/__init__.py +++ b/googleads/__init__.py @@ -14,5 +14,5 @@ """A client library for Google's SOAP Ads APIs.""" +from ad_manager import AdManagerClient from adwords import AdWordsClient -from dfp import DfpClient diff --git a/googleads/dfp.py b/googleads/ad_manager.py similarity index 85% rename from googleads/dfp.py rename to googleads/ad_manager.py index 9d69b44f..4b70cda2 100644 --- a/googleads/dfp.py +++ b/googleads/ad_manager.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Client library for the DoubleClick for Publishers API.""" +"""Client library for the Ad Manager API.""" import csv @@ -30,7 +30,7 @@ # The default application name. DEFAULT_APPLICATION_NAME = 'INSERT_APPLICATION_NAME_HERE' -# The endpoint server for DFP. +# The endpoint server for Ad Manager. DEFAULT_ENDPOINT = 'https://ads.google.com' # The suggested page limit per page fetched from the API. SUGGESTED_PAGE_LIMIT = 500 @@ -42,17 +42,17 @@ '%s.%s' % (__name__, 'data_downloader')) -# A giant dictionary of DFP versions and the services they support. +# A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201708': + 'v201711': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentMetadataKeyHierarchyService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'ExchangeRateService', 'ForecastService', - 'InventoryService', 'LabelService', + 'CdnConfigurationService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentMetadataKeyHierarchyService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', @@ -66,7 +66,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201711': + 'v201802': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', @@ -88,14 +88,15 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201802': + 'v201805': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', 'ContentBundleService', 'ContentMetadataKeyHierarchyService', 'ContentService', 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'ExchangeRateService', 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', @@ -110,7 +111,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201805': + 'v201808': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', @@ -136,7 +137,7 @@ } -class DfpClient(googleads.common.CommonClient): +class AdManagerClient(googleads.common.CommonClient): """A central location to set headers and create web service clients. Attributes: @@ -149,11 +150,11 @@ class DfpClient(googleads.common.CommonClient): this header to be set. """ - # The key in the storage yaml which contains DFP data. - _YAML_KEY = 'dfp' - # A list of values which must be provided to use DFP. + # The key in the storage yaml which contains Ad Manager data. + _YAML_KEY = 'ad_manager' + # A list of values which must be provided to use Ad Manager. _REQUIRED_INIT_VALUES = ('application_name',) - # A list of values which may optionally be provided when using DFP. + # A list of values which may optionally be provided when using Ad Manager. _OPTIONAL_INIT_VALUES = ( 'network_code', googleads.common.ENABLE_COMPRESSION_KEY) # The format of SOAP service WSDLs. A server, version, and service name need @@ -162,13 +163,13 @@ class DfpClient(googleads.common.CommonClient): @classmethod def LoadFromString(cls, yaml_doc): - """Creates a DfpClient with information stored in a yaml string. + """Creates a AdManagerClient with information stored in a yaml string. Args: - yaml_doc: The yaml string containing the cached DFP data. + yaml_doc: The yaml string containing the cached Ad Manager data. Returns: - A DfpClient initialized with the values cached in the yaml string. + A AdManagerClient initialized with the values cached in the yaml string. Raises: A GoogleAdsValueError if the given yaml string does not contain the @@ -181,14 +182,14 @@ def LoadFromString(cls, yaml_doc): @classmethod def LoadFromStorage(cls, path=None): - """Creates a DfpClient with information stored in a yaml file. + """Creates a AdManagerClient with information stored in a yaml file. Args: [optional] - path: str The path to the file containing cached DFP data. + path: str The path to the file containing cached Ad Manager data. Returns: - A DfpClient initialized with the values cached in the file. + A AdManagerClient initialized with the values cached in the file. Raises: A GoogleAdsValueError if the given yaml file does not contain the @@ -206,10 +207,10 @@ def __init__(self, oauth2_client, application_name, network_code=None, cache=None, proxy_config=None, soap_impl='zeep', timeout=3600, custom_http_headers=None, enable_compression=False): - """Initializes a DfpClient. + """Initializes a AdManagerClient. For more information on these arguments, see our SOAP headers guide: - https://developers.google.com/doubleclick-publishers/docs/soap_xml + https://developers.google.com/ad-manager/docs/soap_xml Args: oauth2_client: A googleads.oauth2.GoogleOAuth2Client used to authorize @@ -227,14 +228,14 @@ def __init__(self, oauth2_client, application_name, network_code=None, isn't being used. soap_impl: A string identifying which SOAP implementation to use. The options are 'zeep' or 'suds'. - timeout: An integer timeout in MS for connections made to DFP. + timeout: An integer timeout in MS for connections made to Ad Manager. custom_http_headers: A dictionary with HTTP headers to add to outgoing requests. enable_compression: A boolean indicating if you want to enable compression of the SOAP response. If True, the SOAP response will use gzip compression, and will be decompressed for you automatically. """ - super(DfpClient, self).__init__() + super(AdManagerClient, self).__init__() if not application_name or (DEFAULT_APPLICATION_NAME in application_name): raise googleads.errors.GoogleAdsValueError( @@ -246,7 +247,7 @@ def __init__(self, oauth2_client, application_name, network_code=None, self.network_code = network_code self.cache = cache self.custom_http_headers = custom_http_headers - self._header_handler = _DfpHeaderHandler( + self._header_handler = _AdManagerHeaderHandler( self, enable_compression, custom_http_headers) self.proxy_config = (proxy_config if proxy_config else googleads.common.ProxyConfig()) @@ -263,13 +264,14 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], """Creates a service client for the given service. Args: - service_name: A string identifying which DFP service to create a service - client for. + service_name: A string identifying which Ad Manager service to create a + service client for. [optional] - version: A string identifying the DFP version to connect to. This defaults - to what is currently the latest version. This will be updated in - future releases to point to what is then the latest version. - server: A string identifying the webserver hosting the DFP API. + version: A string identifying the Ad Manager version to connect to. This + defaults to what is currently the latest version. This will be + updated in future releases to point to what is then the + latest version. + server: A string identifying the webserver hosting the Ad Manager API. Returns: A googleads.common.GoogleSoapService instance which has the headers @@ -287,7 +289,7 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], service = googleads.common.GetServiceClassForLibrary(self.soap_impl)( self._SOAP_SERVICE_FORMAT % (server, version, service_name), self._header_handler, - _DfpPacker, + _AdManagerPacker, self.proxy_config, self.timeout, cache=self.cache) @@ -299,30 +301,31 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], raise else: raise googleads.errors.GoogleAdsValueError( - 'Unrecognized service for the DFP API. Service given: %s ' + 'Unrecognized service for the Ad Manager API. Service given: %s ' 'Supported services: %s' % (service_name, _SERVICE_MAP[version])) else: raise googleads.errors.GoogleAdsValueError( - 'Unrecognized version of the DFP API. Version given: %s Supported ' - 'versions: %s' % (version, _SERVICE_MAP.keys())) + 'Unrecognized version of the Ad Manager API. Version given: %s ' + 'Supported versions: %s' % (version, _SERVICE_MAP.keys())) def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): - """Creates a downloader for DFP reports and PQL result sets. + """Creates a downloader for Ad Manager reports and PQL result sets. This is a convenience method. It is functionally identical to calling - DataDownloader(dfp_client, version, server) + DataDownloader(ad_manager_client, version, server) Args: [optional] - version: A string identifying the DFP version to connect to. This defaults - to what is currently the latest version. This will be updated in - future releases to point to what is then the latest version. - server: A string identifying the webserver hosting the DFP API. + version: A string identifying the Ad Manager version to connect to. + This defaults to what is currently the latest version. This will be + updated in future releases to point to what is then the + latest version. + server: A string identifying the webserver hosting the Ad Manager API. Returns: - A DataDownloader tied to this DfpClient, ready to download reports. + A DataDownloader tied to this AdManagerClient, ready to download reports. """ if not server: server = DEFAULT_ENDPOINT @@ -330,28 +333,30 @@ def GetDataDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], return DataDownloader(self, version, server) -class _DfpHeaderHandler(googleads.common.HeaderHandler): - """Handler which sets the headers for a DFP SOAP call.""" +class _AdManagerHeaderHandler(googleads.common.HeaderHandler): + """Handler which sets the headers for an Ad Manager SOAP call.""" - # The library signature for DFP, to be appended to all application_names. + # The library signature for Ad Manager, to be appended to all + # application_names. _PRODUCT_SIG = 'DfpApi-Python' # The name of the WSDL-defined SOAP Header class used in all requests. _SOAP_HEADER_CLASS = 'ns0:SoapRequestHeader' - def __init__(self, dfp_client, enable_compression, custom_http_headers=None): - """Initializes a DfpHeaderHandler. + def __init__( + self, ad_manager_client, enable_compression, custom_http_headers=None): + """Initializes an AdManagerHeaderHandler. Args: - dfp_client: The DfpClient whose data will be used to fill in the headers. - We retain a reference to this object so that the header handler picks - up changes to the client. + ad_manager_client: The AdManagerClient whose data will be used to fill + in the headers. We retain a reference to this object so that the + header handler picks up changes to the client. enable_compression: A boolean indicating if you want to enable compression of the SOAP response. If True, the SOAP response will use gzip compression, and will be decompressed for you automatically. custom_http_headers: A dictionary of custom HTTP headers to send with all requests. """ - self._dfp_client = dfp_client + self._ad_manager_client = ad_manager_client self.enable_compression = enable_compression self.custom_http_headers = custom_http_headers or {} @@ -366,9 +371,9 @@ def GetSOAPHeaders(self, create_method): A SOAP object containing the headers. """ header = create_method(self._SOAP_HEADER_CLASS) - header.networkCode = self._dfp_client.network_code + header.networkCode = self._ad_manager_client.network_code header.applicationName = ''.join([ - self._dfp_client.application_name, + self._ad_manager_client.application_name, googleads.common.GenerateLibSig(self._PRODUCT_SIG)]) return header @@ -378,7 +383,7 @@ def GetHTTPHeaders(self): Returns: A dictionary containing the required headers. """ - http_headers = self._dfp_client.oauth2_client.CreateHttpHeader() + http_headers = self._ad_manager_client.oauth2_client.CreateHttpHeader() if self.enable_compression: http_headers['accept-encoding'] = 'gzip' @@ -387,34 +392,34 @@ def GetHTTPHeaders(self): return http_headers -class _DfpPacker(googleads.common.SoapPacker): - """A utility applying customized packing logic for DFP.""" +class _AdManagerPacker(googleads.common.SoapPacker): + """A utility applying customized packing logic for Ad Manager.""" @classmethod def Pack(cls, obj): - """Pack the given object using DFP-specific logic. + """Pack the given object using Ad Manager-specific logic. Args: - obj: an object to be packed for SOAP using DFP-specific logic, if + obj: an object to be packed for SOAP using Ad Manager-specific logic, if applicable. Returns: - The given object packed with DFP-specific logic for SOAP, if applicable. - Otherwise, returns the given object unmodified. + The given object packed with Ad Manager-specific logic for SOAP, + if applicable. Otherwise, returns the given object unmodified. """ if isinstance(obj, (datetime.datetime, datetime.date)): - return cls.DfpDateTimePacker(obj) + return cls.AdManagerDateTimePacker(obj) return obj @classmethod - def DfpDateTimePacker(cls, value): - """Returns dicts formatted for DFP SOAP based on date/datetime. + def AdManagerDateTimePacker(cls, value): + """Returns dicts formatted for Ad Manager SOAP based on date/datetime. Args: value: A date or datetime object to be converted. Returns: - The value object correctly represented for DFP SOAP. + The value object correctly represented for Ad Manager SOAP. """ if isinstance(value, datetime.datetime): @@ -424,7 +429,7 @@ def DfpDateTimePacker(cls, value): ) return { - 'date': cls.DfpDateTimePacker(value.date()), + 'date': cls.AdManagerDateTimePacker(value.date()), 'hour': value.hour, 'minute': value.minute, 'second': value.second, @@ -709,7 +714,7 @@ def __init__(self, where_clause='', values=None, limit=SUGGESTED_PAGE_LIMIT, self.offset = offset def ToStatement(self): - """Returns this statement object in the format DFP requires.""" + """Returns this statement object in the format Ad Manager requires.""" return {'query': ('%s LIMIT %d OFFSET %d' % (self.where_clause, self.limit, self.offset)), 'values': self.values} @@ -718,46 +723,47 @@ def ToStatement(self): class DataDownloader(object): """A utility that can be used to download reports and PQL result sets.""" - def __init__(self, dfp_client, version=sorted(_SERVICE_MAP.keys())[-1], + def __init__(self, ad_manager_client, version=sorted(_SERVICE_MAP.keys())[-1], server=None): """Initializes a DataDownloader. Args: - dfp_client: The DfpClient whose attributes will be used to authorize your - report download and PQL query requests. + ad_manager_client: The AdManagerClient whose attributes will be used to + authorize your report download and PQL query requests. [optional] - version: A string identifying the DFP version to connect to. This defaults - to what is currently the latest version. This will be updated in - future releases to point to what is then the latest version. - server: A string identifying the webserver hosting the DFP API. + version: A string identifying the Ad Manager version to connect to. + This defaults to what is currently the latest version. This will be + updated in future releases to point to what is then the + latest version. + server: A string identifying the webserver hosting the Ad Manager API. """ if not server: server = DEFAULT_ENDPOINT if server[-1] == '/': server = server[:-1] - self._dfp_client = dfp_client + self._ad_manager_client = ad_manager_client self._version = version self._server = server self._report_service = None self._pql_service = None - self.proxy_config = self._dfp_client.proxy_config + self.proxy_config = self._ad_manager_client.proxy_config handlers = self.proxy_config.GetHandlers() self.url_opener = urllib2.build_opener(*handlers) - if self._dfp_client.custom_http_headers: + if self._ad_manager_client.custom_http_headers: self.url_opener.addheaders.extend( - self._dfp_client.custom_http_headers.items()) + self._ad_manager_client.custom_http_headers.items()) def _GetReportService(self): """Lazily initializes a report service client.""" if not self._report_service: - self._report_service = self._dfp_client.GetService( + self._report_service = self._ad_manager_client.GetService( 'ReportService', self._version, self._server) return self._report_service def _GetPqlService(self): """Lazily initializes a PQL service client.""" if not self._pql_service: - self._pql_service = self._dfp_client.GetService( + self._pql_service = self._ad_manager_client.GetService( 'PublisherQueryLanguageService', self._version, self._server) return self._pql_service @@ -772,7 +778,7 @@ def WaitForReport(self, report_job): The completed report job's ID as a string. Raises: - A DfpReportError if the report job fails to complete. + An AdManagerReportError if the report job fails to complete. """ service = self._GetReportService() report_job_id = service.runReportJob(report_job)['id'] @@ -791,7 +797,7 @@ def WaitForReport(self, report_job): status = service.getReportJob(report_job_id)['reportJobStatus'] if status == 'FAILED': - raise googleads.errors.DfpReportError(report_job_id) + raise googleads.errors.AdManagerReportError(report_job_id) else: _data_downloader_logger.debug('Report has completed successfully') return report_job_id @@ -890,7 +896,7 @@ def _ConvertValueForCsv(self, pql_value): if field: if isinstance(field, list): - if all(DfpClassType(single_field) == DfpClassType(field[0]) + if all(AdManagerClassType(single_field) == AdManagerClassType(field[0]) for single_field in field): return ','.join([ '"%s"' % str(self._ConvertValueForCsv(single_field)) @@ -899,7 +905,7 @@ def _ConvertValueForCsv(self, pql_value): raise googleads.errors.GoogleAdsValueError( 'The set value returned contains unsupported mix value types') - class_type = DfpClassType(pql_value) + class_type = AdManagerClassType(pql_value) if class_type == 'TextValue': s = field.replace('"', '""') @@ -991,7 +997,7 @@ def _ConvertDateTimeToOffset(self, date_time_value): return date_time_str -def DfpClassType(value): +def AdManagerClassType(value): """Returns the class type for the Suds object. Args: diff --git a/googleads/common.py b/googleads/common.py index 00a2f807..dad772e3 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '13.0.0' +VERSION = '14.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' @@ -136,7 +136,7 @@ def GenerateLibSig(short_name): class CommonClient(object): - """Contains shared startup code between DFP and AdWords clients.""" + """Contains shared startup code between Ad Manager and AdWords clients.""" def __init__(self): # Warn users on deprecated Python versions on initialization. @@ -184,6 +184,11 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, """ data = yaml.safe_load(yaml_doc) or {} + if 'dfp' in data: + raise googleads.errors.GoogleAdsValueError( + 'Please replace the "dfp" key in the configuration YAML string with' + '"ad_manager" to fix this issue.') + logging_config = data.get(_LOGGING_KEY) if logging_config: logging.config.dictConfig(logging_config) @@ -415,11 +420,12 @@ def _PackForSuds(obj, factory, packer=None): # packed into a suds.null() object. for param, _ in new_obj: # Another problem is that the suds.mx.appender.ObjectAppender won't - # serialize object types with no fields set, but both AdWords and DFP - # rely on sending objects with just the xsi:type set. The below "if" - # statement is an ugly hack that gets this to work in all(?) situations - # by taking advantage of the fact that these classes generally all have - # a type field. The only other option is to monkey patch ObjectAppender. + # serialize object types with no fields set, but both AdWords and Ad + # Manager rely on sending objects with just the xsi:type set. The + # below "if" statement is an ugly hack that gets this to work in all(?) + # situations by taking advantage of the fact that these classes + # generally all have a type field. The only other option is to monkey + # patch ObjectAppender. if param.endswith('.Type'): setattr(new_obj, param, obj['xsi_type']) else: @@ -1437,7 +1443,7 @@ def _ExtractRequestSummaryFields(document): if client_customer_id is not None: summary_fields['clientCustomerId'] = client_customer_id.text - # Extract DFP-specific fields if they exist. + # Extract Ad Manager-specific fields if they exist. # Note: We need to check if None because this will always evaluate False. network_code = headers.getChild('networkCode') if network_code is not None: diff --git a/googleads/errors.py b/googleads/errors.py index 3aec1374..b6770ce1 100644 --- a/googleads/errors.py +++ b/googleads/errors.py @@ -108,20 +108,20 @@ class AdWordsBatchJobServiceInvalidOperationError(GoogleAdsError): pass -class DfpReportError(GoogleAdsError): - """Error indicating that a DFP report download request failed. +class AdManagerReportError(GoogleAdsError): + """Error indicating that an Ad Manager report download request failed. Attributes: report_job_id: The ID of the report job which failed. """ def __init__(self, report_job_id): - """Initializes a DfpReportError. + """Initializes a AdManagerReportError. Args: report_job_id: The ID of the report job which failed. """ - super(DfpReportError, self).__init__( - 'DFP report job failed. The ID of the failed report is: %s' + super(AdManagerReportError, self).__init__( + 'Ad Manager report job failed. The ID of the failed report is: %s' % report_job_id) self.report_job_id = report_job_id diff --git a/googleads/oauth2.py b/googleads/oauth2.py index 7bb76540..322eb32d 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -32,7 +32,7 @@ # The scopes used for authorizing with the APIs supported by this library. SCOPES = {'adwords': 'https://www.googleapis.com/auth/adwords', - 'dfp': 'https://www.googleapis.com/auth/dfp'} + 'ad_manager': 'https://www.googleapis.com/auth/dfp'} def GetAPIScope(api_name): @@ -46,8 +46,8 @@ def GetAPIScope(api_name): A string that is the scope for the given API name. Raises: - GoogleAdsValueError: If the given api_name is invalid; accepted valus are - "adwords" and "dfp". + GoogleAdsValueError: If the given api_name is invalid; accepted values are + "adwords" and "ad_manager". """ try: return SCOPES[api_name] diff --git a/setup.py b/setup.py index 5ffa6319..b80cdc9a 100755 --- a/setup.py +++ b/setup.py @@ -64,7 +64,7 @@ def GetVersion(): The googleads Python Client Libraries support the following products: * AdWords API -* DoubleClick for Publishers API +* Google Ad Manager API You can find more information about the Google Ads Python Client Libraries `here `_. @@ -119,7 +119,7 @@ def GetVersion(): long_description=long_description, packages=PACKAGES, platforms='any', - keywords='adwords dfp google', + keywords='adwords dfp admanager google', classifiers=CLASSIFIERS, install_requires=DEPENDENCIES, tests_require=TEST_DEPENDENCIES, diff --git a/tests/dfp_test.py b/tests/ad_manager_test.py similarity index 81% rename from tests/dfp_test.py rename to tests/ad_manager_test.py index c987e152..9a0541f6 100644 --- a/tests/dfp_test.py +++ b/tests/ad_manager_test.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Unit tests to cover the dfp module.""" +"""Unit tests to cover the ad_manager module.""" import datetime @@ -22,7 +22,7 @@ import mock import pytz import six -import googleads.dfp +import googleads.ad_manager import googleads.common import googleads.errors from . import testing @@ -107,15 +107,15 @@ def DecideValue(original_object): return BooleanValue(original_object) -class DfpHeaderHandlerTest(testing.CleanUtilityRegistryTestCase): - """Tests for the googleads.dfp._DfpHeaderHandler class.""" +class AdManagerHeaderHandlerTest(testing.CleanUtilityRegistryTestCase): + """Tests for the googleads.ad_manager._AdManagerHeaderHandler class.""" def setUp(self): - self.dfp_client = mock.Mock() + self.ad_manager_client = mock.Mock() self.enable_compression = False self.custom_headers = () - self.header_handler = googleads.dfp._DfpHeaderHandler( - self.dfp_client, self.enable_compression, self.custom_headers) + self.header_handler = googleads.ad_manager._AdManagerHeaderHandler( + self.ad_manager_client, self.enable_compression, self.custom_headers) self.utility_name = 'TestUtility' self.default_sig_template = ' (%s, %s, %s)' self.util_sig_template = ' (%s, %s, %s, %s)' @@ -132,7 +132,7 @@ def Test(self): self.test_utility = TestUtility() def testGetHTTPHeaders(self): - self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( + self.ad_manager_client.oauth2_client.CreateHttpHeader.return_value = ( self.oauth_header) header_result = self.header_handler.GetHTTPHeaders() @@ -141,7 +141,7 @@ def testGetHTTPHeaders(self): self.assertEqual(header_result, self.oauth_header) def testGetHTTPHeadersWithCustomHeaders(self): - self.dfp_client.oauth2_client.CreateHttpHeader.return_value = ( + self.ad_manager_client.oauth2_client.CreateHttpHeader.return_value = ( self.oauth_header) self.header_handler.custom_http_headers = {'X-My-Header': 'abc'} @@ -152,8 +152,8 @@ def testGetHTTPHeadersWithCustomHeaders(self): def testGetSOAPHeaders(self): create_method = mock.Mock() - self.dfp_client.network_code = self.network_code - self.dfp_client.application_name = self.app_name + self.ad_manager_client.network_code = self.network_code + self.ad_manager_client.application_name = self.app_name header_result = self.header_handler.GetSOAPHeaders(create_method) @@ -164,32 +164,33 @@ def testGetSOAPHeaders(self): ''.join([ self.app_name, googleads.common.GenerateLibSig( - googleads.dfp._DfpHeaderHandler._PRODUCT_SIG)]), + googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG)]), header_result.applicationName) def testGetSOAPHeadersUserAgentWithUtility(self): create_method = mock.Mock() - self.dfp_client.network_code = self.network_code - self.dfp_client.application_name = self.app_name + self.ad_manager_client.network_code = self.network_code + self.ad_manager_client.application_name = self.app_name with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: self.test_utility.Test() # This will register TestUtility. soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( - ''.join([self.app_name, - self.util_sig_template % ( - googleads.dfp._DfpHeaderHandler._PRODUCT_SIG, - mock_common_sig, - mock_py_ver, - self.utility_name)]), + ''.join([ + self.app_name, + self.util_sig_template % ( + googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name)]), soap_header.applicationName) def testGetHeadersUserAgentWithAndWithoutUtility(self): create_method = mock.Mock() - self.dfp_client.network_code = self.network_code - self.dfp_client.application_name = self.app_name + self.ad_manager_client.network_code = self.network_code + self.ad_manager_client.application_name = self.app_name with mock.patch('googleads.common._COMMON_LIB_SIG') as mock_common_sig: with mock.patch('googleads.common._PYTHON_VERSION') as mock_py_ver: @@ -197,40 +198,43 @@ def testGetHeadersUserAgentWithAndWithoutUtility(self): self.test_utility.Test() # This will register TestUtility. soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( - ''.join([self.app_name, - self.util_sig_template % ( - googleads.dfp._DfpHeaderHandler._PRODUCT_SIG, - mock_common_sig, - mock_py_ver, - self.utility_name)]), + ''.join([ + self.app_name, + self.util_sig_template % ( + googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name)]), soap_header.applicationName) # Check headers when no utility should be registered. soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( - ''.join([self.app_name, - self.default_sig_template % ( - googleads.dfp._DfpHeaderHandler._PRODUCT_SIG, - mock_common_sig, - mock_py_ver)]), + ''.join([ + self.app_name, + self.default_sig_template % ( + googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver)]), soap_header.applicationName) # Verify that utility is registered in subsequent uses. self.test_utility.Test() # This will register TestUtility. soap_header = self.header_handler.GetSOAPHeaders(create_method) self.assertEqual( - ''.join([self.app_name, - self.util_sig_template % ( - googleads.dfp._DfpHeaderHandler._PRODUCT_SIG, - mock_common_sig, - mock_py_ver, - self.utility_name)]), + ''.join([ + self.app_name, + self.util_sig_template % ( + googleads.ad_manager._AdManagerHeaderHandler._PRODUCT_SIG, + mock_common_sig, + mock_py_ver, + self.utility_name)]), soap_header.applicationName) -class DfpClientTest(unittest.TestCase): - """Tests for the googleads.dfp.DfpClient class.""" +class AdManagerClientTest(unittest.TestCase): + """Tests for the googleads.ad_manager.AdManagerClient class.""" def setUp(self): self.network_code = '12345' @@ -243,16 +247,16 @@ def setUp(self): self.proxy_config = googleads.common.ProxyConfig( https_proxy=self.https_proxy) self.cache = None - self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1] + self.version = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1] - def CreateDfpClient(self, **kwargs): + def CreateAdManagerClient(self, **kwargs): if 'proxy_config' not in kwargs: kwargs['proxy_config'] = self.proxy_config if 'cache' not in kwargs: kwargs['cache'] = self.cache - return googleads.dfp.DfpClient( + return googleads.ad_manager.AdManagerClient( self.oauth2_client, self.application_name, self.network_code, **kwargs) @@ -263,8 +267,9 @@ def testLoadFromString(self): 'oauth2_client': True, 'application_name': 'unit testing' } - self.assertIsInstance(googleads.dfp.DfpClient.LoadFromString(''), - googleads.dfp.DfpClient) + self.assertIsInstance( + googleads.ad_manager.AdManagerClient.LoadFromString(''), + googleads.ad_manager.AdManagerClient) def testLoadFromStorage(self): with mock.patch('googleads.common.LoadFromStorage') as mock_load: @@ -273,8 +278,9 @@ def testLoadFromStorage(self): 'oauth2_client': True, 'application_name': 'unit testing' } - self.assertIsInstance(googleads.dfp.DfpClient.LoadFromStorage(), - googleads.dfp.DfpClient) + self.assertIsInstance( + googleads.ad_manager.AdManagerClient.LoadFromStorage(), + googleads.ad_manager.AdManagerClient) def testLoadFromStorageWithCompressionEnabled(self): enable_compression = True @@ -283,7 +289,7 @@ def testLoadFromStorageWithCompressionEnabled(self): custom_headers = {'X-My-Header': 'abc'} with mock.patch('googleads.common.LoadFromStorage') as mock_load: - with mock.patch('googleads.dfp._DfpHeaderHandler') as mock_h: + with mock.patch('googleads.ad_manager._AdManagerHeaderHandler') as mock_h: mock_load.return_value = { 'network_code': 'abcdEFghIjkLMOpqRs', 'oauth2_client': True, @@ -291,33 +297,33 @@ def testLoadFromStorageWithCompressionEnabled(self): 'enable_compression': enable_compression, 'custom_http_headers': custom_headers } - dfp_client = googleads.dfp.DfpClient.LoadFromStorage() + ad_manager = googleads.ad_manager.AdManagerClient.LoadFromStorage() self.assertEqual( application_name_gzip_template % default_app_name, - dfp_client.application_name) + ad_manager.application_name) mock_h.assert_called_once_with( - dfp_client, enable_compression, custom_headers) + ad_manager, enable_compression, custom_headers) def testInitializeWithDefaultApplicationName(self): self.application_name = 'INSERT_APPLICATION_NAME_HERE' self.assertRaises( - googleads.errors.GoogleAdsValueError, googleads.dfp.DfpClient, - self.oauth2_client, self.application_name, self.network_code, - self.https_proxy, self.cache) + googleads.errors.GoogleAdsValueError, + googleads.ad_manager.AdManagerClient, self.oauth2_client, + self.application_name, self.network_code, self.https_proxy, self.cache) def testInitializeWithUselessApplicationName(self): self.application_name = 'try_to_trick_me_INSERT_APPLICATION_NAME_HERE' self.assertRaises( - googleads.errors.GoogleAdsValueError, googleads.dfp.DfpClient, - self.oauth2_client, self.application_name, self.network_code, - self.https_proxy, self.cache) + googleads.errors.GoogleAdsValueError, + googleads.ad_manager.AdManagerClient, self.oauth2_client, + self.application_name, self.network_code, self.https_proxy, self.cache) def testGetService_success(self): - dfp_client = self.CreateDfpClient( + ad_manager = self.CreateAdManagerClient( cache='cache', proxy_config='proxy', timeout='timeout') - service_name = googleads.dfp._SERVICE_MAP[self.version][0] + service_name = googleads.ad_manager._SERVICE_MAP[self.version][0] # Use a custom server. Also test what happens if the server ends with a # trailing slash @@ -329,52 +335,52 @@ def testGetService_success(self): impl.return_value = mock_service mock_get_service.return_value = impl - service = dfp_client.GetService(service_name, self.version, server) + service = ad_manager.GetService(service_name, self.version, server) impl.assert_called_once_with( 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' - % (self.version, service_name), dfp_client._header_handler, - googleads.dfp._DfpPacker, 'proxy', 'timeout', + % (self.version, service_name), ad_manager._header_handler, + googleads.ad_manager._AdManagerPacker, 'proxy', 'timeout', cache='cache') self.assertEqual(service, mock_service) def testGetService_badService(self): - dfp_client = self.CreateDfpClient() + ad_manager = self.CreateAdManagerClient() with mock.patch('googleads.common.' 'GetServiceClassForLibrary') as mock_get_service: mock_get_service.side_effect = ( googleads.errors.GoogleAdsSoapTransportError('', '')) self.assertRaises( - googleads.errors.GoogleAdsValueError, dfp_client.GetService, + googleads.errors.GoogleAdsValueError, ad_manager.GetService, 'GYIVyievfyiovslf', self.version) def testGetService_badVersion(self): - dfp_client = self.CreateDfpClient() + ad_manager = self.CreateAdManagerClient() with mock.patch('googleads.common.' 'GetServiceClassForLibrary') as mock_get_service: mock_get_service.side_effect = ( googleads.errors.GoogleAdsSoapTransportError('', '')) self.assertRaises( - googleads.errors.GoogleAdsValueError, dfp_client.GetService, + googleads.errors.GoogleAdsValueError, ad_manager.GetService, 'CampaignService', '11111') def testGetService_transportError(self): - service = googleads.dfp._SERVICE_MAP[self.version][0] - dfp_client = self.CreateDfpClient() + service = googleads.ad_manager._SERVICE_MAP[self.version][0] + ad_manager = self.CreateAdManagerClient() with mock.patch('googleads.common.' 'GetServiceClassForLibrary') as mock_get_service: mock_get_service.side_effect = ( googleads.errors.GoogleAdsSoapTransportError('', '')) self.assertRaises(googleads.errors.GoogleAdsSoapTransportError, - dfp_client.GetService, service, self.version) + ad_manager.GetService, service, self.version) -class DfpPackerTest(unittest.TestCase): - """Tests for the googleads.dfp._DfpPacker class.""" +class AdManagerPackerTest(unittest.TestCase): + """Tests for the googleads.ad_manager._AdManagerPacker class.""" def setUp(self): - self.packer = googleads.dfp._DfpPacker + self.packer = googleads.ad_manager._AdManagerPacker def testPackDate(self): input_date = datetime.date(2017, 1, 2) @@ -396,21 +402,21 @@ def testPackDateTimeNeedsTimeZone(self): def testPackUnsupportedObjectType(self): obj = object() - self.assertEqual(googleads.dfp._DfpPacker.Pack(obj), obj) + self.assertEqual(googleads.ad_manager._AdManagerPacker.Pack(obj), obj) class DataDownloaderTest(unittest.TestCase): - """Tests for the googleads.dfp.DfpClient class.""" + """Tests for the googleads.ad_manager.AdManagerClient class.""" def setUp(self): network_code = '12345' application_name = 'application name' oauth2_client = 'unused' self.https_proxy = 'myproxy.com:443' - self.dfp_client = googleads.dfp.DfpClient( + self.ad_manager = googleads.ad_manager.AdManagerClient( oauth2_client, application_name, network_code, self.https_proxy) - self.version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1] - self.report_downloader = self.dfp_client.GetDataDownloader() + self.version = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1] + self.report_downloader = self.ad_manager.GetDataDownloader() self.pql_service = mock.Mock() self.report_service = mock.Mock() self.report_downloader._pql_service = self.pql_service @@ -654,7 +660,7 @@ def testWaitForReport_failure(self): self.report_service.runReportJob.return_value = {'id': '782yt97r2'} self.assertRaises( - googleads.errors.DfpReportError, + googleads.errors.AdManagerReportError, self.report_downloader.WaitForReport, {'id': 'obj'}) def testDownloadReportToFile(self): @@ -691,23 +697,25 @@ def testDownloadReportToFile(self): self.assertEqual(report_data, outfile.getvalue()) def testGetReportService(self): - self.report_downloader._dfp_client = mock.Mock() + self.report_downloader._ad_manager_client = mock.Mock() self.report_downloader._report_service = None self.report_downloader._GetReportService() - self.report_downloader._dfp_client.GetService.assert_called_once_with( + client = self.report_downloader._ad_manager_client + client.GetService.assert_called_once_with( 'ReportService', self.version, 'https://ads.google.com') def testGetPqlService(self): - self.report_downloader._dfp_client = mock.Mock() + self.report_downloader._ad_manager_client = mock.Mock() self.report_downloader._pql_service = None self.report_downloader._GetPqlService() - self.report_downloader._dfp_client.GetService.assert_called_once_with( + client = self.report_downloader._ad_manager_client + client.GetService.assert_called_once_with( 'PublisherQueryLanguageService', self.version, 'https://ads.google.com') def testDownloadHasCustomHeaders(self): - self.dfp_client.custom_http_headers = {'X-My-Headers': 'abc'} + self.ad_manager.custom_http_headers = {'X-My-Headers': 'abc'} class MyOpener(object): addheaders = [('a', 'b')] @@ -716,7 +724,7 @@ class MyOpener(object): with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mock_build_opener: mock_build_opener.return_value = opener - self.dfp_client.GetDataDownloader() + self.ad_manager.GetDataDownloader() self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Headers', 'abc')]) @@ -724,7 +732,7 @@ class StatementBuilderTest(testing.CleanUtilityRegistryTestCase): """Tests for the StatementBuilder class.""" def testBuildBasicSelectFrom(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() select_call_result = test_statement.Select('Id') from_call_result = test_statement.From('Line_Item') @@ -732,11 +740,11 @@ def testBuildBasicSelectFrom(self): self.assertEqual(from_call_result, test_statement) self.assertEqual(test_statement.ToStatement(), {'query': ('SELECT Id FROM Line_Item LIMIT %s OFFSET 0' % - googleads.dfp.SUGGESTED_PAGE_LIMIT), + googleads.ad_manager.SUGGESTED_PAGE_LIMIT), 'values': None}) def testLimitClause(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() limit_call_result = (test_statement .Select('Id') .From('Line_Item') @@ -753,7 +761,7 @@ def testLimitClause(self): 'values': None}) def testOffsetClause(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() offset_call_result = ( test_statement .Select('Id') @@ -764,11 +772,11 @@ def testOffsetClause(self): self.assertEqual(offset_call_result, test_statement) self.assertEqual(test_statement.ToStatement(), {'query': ('SELECT Id FROM Line_Item LIMIT %s OFFSET 100' % - googleads.dfp.SUGGESTED_PAGE_LIMIT), + googleads.ad_manager.SUGGESTED_PAGE_LIMIT), 'values': None}) def testOrderByClause(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() order_call_result = ( test_statement .Select('Id') @@ -781,7 +789,7 @@ def testOrderByClause(self): {'query': ('SELECT Id FROM Line_Item ' 'ORDER BY Id ASC ' 'LIMIT %s OFFSET 0' % - googleads.dfp.SUGGESTED_PAGE_LIMIT), + googleads.ad_manager.SUGGESTED_PAGE_LIMIT), 'values': None}) test_statement.OrderBy('Id', ascending=False) @@ -789,26 +797,24 @@ def testOrderByClause(self): {'query': ('SELECT Id FROM Line_Item ' 'ORDER BY Id DESC ' 'LIMIT %s OFFSET 0' % - googleads.dfp.SUGGESTED_PAGE_LIMIT), + googleads.ad_manager.SUGGESTED_PAGE_LIMIT), 'values': None}) def testConstructorArgs(self): - test_statement = googleads.dfp.StatementBuilder(select_columns='Id', - from_table='Line_Item', - where='abc = 123', - order_by='Id', - order_ascending=False,) + test_statement = googleads.ad_manager.StatementBuilder( + select_columns='Id', from_table='Line_Item', where='abc = 123', + order_by='Id', order_ascending=False) self.assertEqual(test_statement.ToStatement(), {'query': ('SELECT Id FROM Line_Item ' 'WHERE abc = 123 ' 'ORDER BY Id DESC ' 'LIMIT %s OFFSET 0' % - googleads.dfp.SUGGESTED_PAGE_LIMIT), + googleads.ad_manager.SUGGESTED_PAGE_LIMIT), 'values': None}) def testWhereWithStringVariable(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() where_call_result = ( test_statement .Select('Id') @@ -826,16 +832,17 @@ def testWhereWithStringVariable(self): }] self.assertEqual(where_call_result, test_statement) self.assertEqual(bind_call_result, test_statement) - self.assertEqual(test_statement.ToStatement(), - {'query': ( - 'SELECT Id FROM Line_Item ' - 'WHERE key = :test_key ' - 'LIMIT %s ' - 'OFFSET 0' % googleads.dfp.SUGGESTED_PAGE_LIMIT), - 'values': target_values}) + self.assertEqual( + test_statement.ToStatement(), + {'query': ( + 'SELECT Id FROM Line_Item ' + 'WHERE key = :test_key ' + 'LIMIT %s ' + 'OFFSET 0' % googleads.ad_manager.SUGGESTED_PAGE_LIMIT), + 'values': target_values}) def testWhereWithOtherTypes(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() test_statement.Where(( 'bool_key = :test_bool_key ' 'AND number_key = :test_number_key ' @@ -912,7 +919,7 @@ def testWhereWithOtherTypes(self): 'AND datetime_key = :test_datetime_key ' 'AND set_key = :test_set_key ' 'LIMIT %s ' - 'OFFSET 0' % googleads.dfp.SUGGESTED_PAGE_LIMIT + 'OFFSET 0' % googleads.ad_manager.SUGGESTED_PAGE_LIMIT )) # The output order doesn't matter, and it's stored internally as a dict @@ -923,7 +930,7 @@ def testWhereWithOtherTypes(self): ) def testBreakWithSetOfMultipleTypes(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() test_statement.Where('key = :test_key') self.assertRaises( @@ -933,7 +940,7 @@ def testBreakWithSetOfMultipleTypes(self): ) def testMutateVar(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() test_statement.Where('key = :test_key') test_statement.WithBindVariable('key', 'abc') test_statement.WithBindVariable('key', '123') @@ -943,7 +950,7 @@ def testMutateVar(self): self.assertEqual(statement_result['values'][0]['value']['value'], '123') def testBreakWithNoTZ(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() test_statement.Where('key = :test_key') self.assertRaises( @@ -953,7 +960,7 @@ def testBreakWithNoTZ(self): ) def testBreakWithUnknownType(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() test_statement.Where('key = :test_key') class RandomType(object): @@ -966,7 +973,7 @@ class RandomType(object): ) def testBreakWithBadSelectFrom(self): - test_statement = googleads.dfp.StatementBuilder() + test_statement = googleads.ad_manager.StatementBuilder() test_statement.Select('Id') self.assertRaises(googleads.errors.GoogleAdsError, @@ -989,7 +996,7 @@ def testFilterStatement(self): 'value': 'test_value' } }] - test_statement = googleads.dfp.FilterStatement() + test_statement = googleads.ad_manager.FilterStatement() self.assertEqual(test_statement.ToStatement(), {'query': ' LIMIT 500 OFFSET 0', 'values': None}) test_statement.offset += 30 @@ -999,7 +1006,7 @@ def testFilterStatement(self): test_statement.limit = 5 self.assertEqual(test_statement.ToStatement(), {'query': ' LIMIT 5 OFFSET 123', 'values': None}) - test_statement = googleads.dfp.FilterStatement( + test_statement = googleads.ad_manager.FilterStatement( 'SELECT Id FROM Line_Item WHERE key = :test_key', limit=300, offset=20, values=values) self.assertEqual(test_statement.ToStatement(), diff --git a/tests/common_test.py b/tests/common_test.py index 279fcccc..95955898 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -250,7 +250,7 @@ def testExtractRequestSummaryFieldsForAdWords(self): self.assertEqual(expected_result, googleads.common._ExtractRequestSummaryFields(root)) - def testExtractRequestSummaryFieldsForDfp(self): + def testExtractRequestSummaryFieldsForAdManager(self): root = suds.sax.element.Element('root', parent=None) network_code = '111111111' nc_element = suds.sax.element.Element('networkCode', parent=None) @@ -608,6 +608,17 @@ def testLoadFromString_missingRequiredKeys(self): googleads.common.LoadFromString, yaml_doc, 'three', ['needed', 'keys'], []) + def testLoadFromString_migrateToAdManager(self): + with mock.patch('googleads.common.open', self.fake_open, create=True): + # Both keys are missing. + yaml_doc = self._CreateYamlDoc({ + 'dfp': {} + }, 'dfp', self._OAUTH_INSTALLED_APP_DICT) + with self.assertRaises(googleads.errors.GoogleAdsValueError) as ctx: + googleads.common.LoadFromString(yaml_doc, 'two', ['ad_manager'], []) + + self.assertIn('Please replace', str(ctx.exception)) + def testLoadFromString(self): # No optional keys present. yaml_doc = self._CreateYamlDoc({ @@ -659,24 +670,26 @@ def testLoadFromString(self): self.assertTrue(googleads.common._utility_registry._enabled) def testLoadFromString_serviceAccount(self): - dfp_scope = googleads.oauth2.GetAPIScope('dfp') + ad_manager_scope = googleads.oauth2.GetAPIScope('ad_manager') # No optional keys present. yaml_doc = self._CreateYamlDoc( - {'dfp': {'needed': 'd', 'keys': 'e'}}, - insert_oauth2_key='dfp', oauth_dict=self._OAUTH_SERVICE_ACCT_DICT) + {'ad_manager': {'needed': 'd', 'keys': 'e'}}, + insert_oauth2_key='ad_manager', + oauth_dict=self._OAUTH_SERVICE_ACCT_DICT) with mock.patch( 'googleads.oauth2.GoogleServiceAccountClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() rval = googleads.common.LoadFromString( - yaml_doc, 'dfp', ['needed', 'keys'], ['other']) + yaml_doc, 'ad_manager', ['needed', 'keys'], ['other']) proxy_config.assert_called_once_with( http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( - '/test/test.json', dfp_scope, sub='delegated_account@example.com', + '/test/test.json', ad_manager_scope, + sub='delegated_account@example.com', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, @@ -687,21 +700,22 @@ def testLoadFromString_serviceAccount(self): # The optional key is present. yaml_doc = self._CreateYamlDoc( - {'dfp': {'needed': 'd', 'keys': 'e', 'other': 'f'}}, 'dfp', - self._OAUTH_SERVICE_ACCT_DICT) + {'ad_manager': {'needed': 'd', 'keys': 'e', 'other': 'f'}}, + 'ad_manager', self._OAUTH_SERVICE_ACCT_DICT) with mock.patch( 'googleads.oauth2.GoogleServiceAccountClient') as mock_client: with mock.patch('googleads.common.open', self.fake_open, create=True): with mock.patch('googleads.common.ProxyConfig') as proxy_config: proxy_config.return_value = mock.Mock() rval = googleads.common.LoadFromString( - yaml_doc, 'dfp', ['needed', 'keys'], ['other']) + yaml_doc, 'ad_manager', ['needed', 'keys'], ['other']) proxy_config.assert_called_once_with( http_proxy=None, https_proxy=None, cafile=None, disable_certificate_validation=False) mock_client.assert_called_once_with( - '/test/test.json', dfp_scope, sub='delegated_account@example.com', + '/test/test.json', ad_manager_scope, + sub='delegated_account@example.com', proxy_config=proxy_config.return_value) self.assertEqual({'oauth2_client': mock_client.return_value, 'proxy_config': proxy_config.return_value, @@ -1096,7 +1110,8 @@ class TestZeepArgumentPacking(unittest.TestCase): def setUp(self): header_handler = mock.Mock() - wsdl_path = os.path.join(TEST_DIR, 'test_data/dfp_report_service.xml') + wsdl_path = os.path.join( + TEST_DIR, 'test_data/ad_manager_report_service.xml') self.zeep_client = googleads.common.ZeepServiceProxy( wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100) diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index eca30dce..56cf9dd2 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -38,9 +38,9 @@ class GetAPIScopeTest(unittest.TestCase): def setUp(self): self.api_name_adwords = 'adwords' - self.api_name_dfp = 'dfp' + self.api_name_ad_manager = 'ad_manager' self.scope_adwords = 'https://www.googleapis.com/auth/adwords' - self.scope_dfp = 'https://www.googleapis.com/auth/dfp' + self.scope_ad_manager = 'https://www.googleapis.com/auth/dfp' def testGetAPIScope_adwords(self): self.assertEquals(googleads.oauth2.GetAPIScope(self.api_name_adwords), @@ -50,9 +50,9 @@ def testGetAPIScope_badKey(self): self.assertRaises(googleads.errors.GoogleAdsValueError, googleads.oauth2.GetAPIScope, 'fake_api_name') - def testGetAPIScope_dfp(self): - self.assertEquals(googleads.oauth2.GetAPIScope(self.api_name_dfp), - self.scope_dfp) + def testGetAPIScope_ad_manager(self): + self.assertEqual(googleads.oauth2.GetAPIScope(self.api_name_ad_manager), + self.scope_ad_manager) class GoogleOAuth2ClientTest(unittest.TestCase): diff --git a/tests/test_data/dfp_report_service.xml b/tests/test_data/ad_manager_report_service.xml similarity index 100% rename from tests/test_data/dfp_report_service.xml rename to tests/test_data/ad_manager_report_service.xml diff --git a/tests/util_test.py b/tests/util_test.py index 393ab815..276b60ef 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -19,8 +19,8 @@ import os import unittest +import googleads.ad_manager import googleads.adwords -import googleads.dfp import googleads.errors import googleads.util from lxml import etree @@ -61,16 +61,17 @@ def setUp(self, soap_impl): self.adwords_namespace_partial = ( 'https://adwords.google.com/api/adwords/%s/' + self.adwords_version) - # DfpClient setup + # AdManagerClient setup network_code = '12345' application_name = 'application name' - self.dfp_client = googleads.dfp.DfpClient( + self.ad_manager_client = googleads.ad_manager.AdManagerClient( oauth2_client, application_name, network_code, soap_impl=soap_impl) - self.dfp_version = sorted(googleads.dfp._SERVICE_MAP.keys())[-1] - self.dfp_namespace = ( + self.ad_manager_version = sorted( + googleads.ad_manager._SERVICE_MAP.keys())[-1] + self.ad_manager_namespace = ( 'https://www.google.com/apis/ads/publisher/%s' - % self.dfp_version) + % self.ad_manager_version) def testPatchedSudsJurkoAppender(self): """Tests to confirm that the appender no longer removes empty objects.""" @@ -90,16 +91,16 @@ def testPatchedSudsJurkoAppender(self): } }] query = 'WHERE orderId = :orderId AND status = :status' - statement = googleads.dfp.FilterStatement(query, values) + statement = googleads.ad_manager.FilterStatement(query, values) - line_item_service = self.dfp_client.GetService('LineItemService') + line_item_service = self.ad_manager_client.GetService('LineItemService') line_item_action = {'xsi_type': 'ActivateLineItems'} request = line_item_service.GetRequestXML( 'performLineItemAction', line_item_action, statement.ToStatement()) line_item_action = request.find( - './/{%s}lineItemAction' % self.dfp_namespace) + './/{%s}lineItemAction' % self.ad_manager_namespace) # Assert that the request includes the action. self.assertIsNotNone(line_item_action) @@ -233,12 +234,12 @@ def mock_fault_response(self, response_file, version): def testSingleErrorListIssue90(self): """Verifies that issue 90 has been resolved with the patch.""" query = 'WHERE 1 = 0' - statement = googleads.dfp.FilterStatement(query) - line_item_service = self.dfp_client.GetService('LineItemService') + statement = googleads.ad_manager.FilterStatement(query) + line_item_service = self.ad_manager_client.GetService('LineItemService') line_item_action = {'xsi_type': 'ActivateLineItems'} st = statement.ToStatement() with self.mock_fault_response( - 'test_data/fault_response_envelope.txt', self.dfp_version): + 'test_data/fault_response_envelope.txt', self.ad_manager_version): try: line_item_service.performLineItemAction(line_item_action, st) except googleads.errors.GoogleAdsServerFault as e: @@ -247,13 +248,13 @@ def testSingleErrorListIssue90(self): def testSingleErrorListIssue90_emptyErrors(self): """Verifies that issue 90 has been resolved with the patch.""" query = 'WHERE 1 = 0' - statement = googleads.dfp.FilterStatement(query) - line_item_service = self.dfp_client.GetService('LineItemService') + statement = googleads.ad_manager.FilterStatement(query) + line_item_service = self.ad_manager_client.GetService('LineItemService') line_item_action = {'xsi_type': 'ActivateLineItems'} st = statement.ToStatement() with self.mock_fault_response( - 'test_data/empty_fault_response_envelope.txt', self.dfp_version): + 'test_data/empty_fault_response_envelope.txt', self.ad_manager_version): try: line_item_service.performLineItemAction(line_item_action, st) except googleads.errors.GoogleAdsServerFault as e: @@ -262,13 +263,14 @@ def testSingleErrorListIssue90_emptyErrors(self): def testSingleErrorListIssue90_multipleErrors(self): """Verifies that issue 90 has been resolved with the patch.""" query = 'WHERE 1 = 0' - statement = googleads.dfp.FilterStatement(query) - line_item_service = self.dfp_client.GetService('LineItemService') + statement = googleads.ad_manager.FilterStatement(query) + line_item_service = self.ad_manager_client.GetService('LineItemService') line_item_action = {'xsi_type': 'ActivateLineItems'} st = statement.ToStatement() with self.mock_fault_response( - 'test_data/multi_errors_fault_response_envelope.txt', self.dfp_version): + 'test_data/multi_errors_fault_response_envelope.txt', + self.ad_manager_version): try: line_item_service.performLineItemAction(line_item_action, st) except googleads.errors.GoogleAdsServerFault as e: From d281383e00421d4400eb4f4995fe10b2c8e44c4a Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 21 Aug 2018 15:51:21 -0400 Subject: [PATCH 120/180] Commiting latest changes. From 11a6b8582c97ee645cc2edb0241d8803ec885202 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 21 Sep 2018 16:27:52 -0400 Subject: [PATCH 121/180] AdWords v201809 release. --- ChangeLog | 17 +- README.md | 7 +- .../account_management/create_account.py | 8 +- .../account_management/create_account.py | 8 +- examples/adwords/v201809/__init__.py | 15 + .../v201809/account_management/__init__.py | 15 + .../account_management/accept_service_link.py | 62 ++ .../account_management/create_account.py | 63 ++ .../account_management/get_account_changes.py | 99 ++ .../get_account_hierarchy.py | 104 ++ .../v201809/advanced_operations/__init__.py | 15 + .../advanced_operations/add_ad_customizer.py | 257 +++++ .../add_ad_group_bid_modifier.py | 75 ++ .../add_dynamic_page_feed.py | 295 ++++++ .../add_dynamic_search_ads_campaign.py | 259 +++++ ...add_expanded_text_ad_with_upgraded_urls.py | 113 ++ .../advanced_operations/add_gmail_ad.py | 115 +++ .../advanced_operations/add_html5_ad.py | 110 ++ .../add_multi_asset_responsive_display_ad.py | 177 ++++ .../add_responsive_display_ad.py | 158 +++ ...d_shopping_dynamic_remarketing_campaign.py | 301 ++++++ .../add_universal_app_campaign.py | 218 ++++ .../create_and_attach_shared_keyword_set.py | 128 +++ ...ind_and_remove_criteria_from_shared_set.py | 155 +++ .../get_ad_group_bid_modifier.py | 73 ++ .../use_shared_bidding_strategy.py | 171 ++++ .../v201809/basic_operations/__init__.py | 15 + .../v201809/basic_operations/add_ad_groups.py | 115 +++ .../v201809/basic_operations/add_campaigns.py | 127 +++ .../basic_operations/add_expanded_text_ads.py | 77 ++ .../v201809/basic_operations/add_keywords.py | 92 ++ .../add_responsive_search_ad.py | 112 ++ .../v201809/basic_operations/get_ad_groups.py | 76 ++ .../v201809/basic_operations/get_campaigns.py | 68 ++ .../get_campaigns_with_awql.py | 61 ++ .../basic_operations/get_expanded_text_ads.py | 90 ++ .../v201809/basic_operations/get_keywords.py | 87 ++ .../get_responsive_search_ads.py | 100 ++ .../v201809/basic_operations/pause_ad.py | 61 ++ .../v201809/basic_operations/remove_ad.py | 62 ++ .../basic_operations/remove_ad_group.py | 58 ++ .../basic_operations/remove_campaign.py | 58 ++ .../basic_operations/remove_keyword.py | 67 ++ .../basic_operations/update_ad_group.py | 85 ++ .../basic_operations/update_campaign.py | 58 ++ .../update_expanded_text_ad.py | 74 ++ .../basic_operations/update_keyword.py | 82 ++ .../v201809/campaign_management/__init__.py | 15 + ...campaign_groups_and_performance_targets.py | 152 +++ .../add_campaign_labels.py | 67 ++ .../add_complete_campaigns_using_batch_job.py | 428 ++++++++ .../v201809/campaign_management/add_draft.py | 81 ++ ...dd_keywords_using_incremental_batch_job.py | 257 +++++ .../v201809/campaign_management/add_trial.py | 117 +++ .../get_all_disapproved_ads.py | 103 ++ .../get_all_disapproved_ads_with_awql.py | 88 ++ .../get_campaigns_by_label.py | 83 ++ .../campaign_management/graduate_trial.py | 79 ++ .../campaign_management/set_ad_parameters.py | 100 ++ .../set_criterion_bid_modifier.py | 77 ++ .../campaign_management/validate_text_ad.py | 84 ++ .../v201809/error_handling/__init__.py | 15 + .../error_handling/handle_partial_failures.py | 131 +++ .../adwords/v201809/extensions/__init__.py | 15 + ..._google_my_business_location_extensions.py | 156 +++ .../adwords/v201809/extensions/add_prices.py | 157 +++ .../v201809/extensions/add_site_links.py | 146 +++ .../extensions/add_site_links_using_feeds.py | 303 ++++++ .../adwords/v201809/migration/__init__.py | 15 + .../migrate_to_extension_settings.py | 526 ++++++++++ examples/adwords/v201809/misc/__init__.py | 15 + .../v201809/misc/get_all_image_assets.py | 78 ++ .../v201809/misc/get_all_images_and_videos.py | 85 ++ examples/adwords/v201809/misc/upload_image.py | 65 ++ .../v201809/misc/upload_image_asset.py | 71 ++ .../v201809/misc/upload_media_bundle.py | 58 ++ .../adwords/v201809/optimization/__init__.py | 15 + .../optimization/estimate_keyword_traffic.py | 182 ++++ ...aign_criterion_bid_modifier_simulations.py | 97 ++ .../get_keyword_bid_simulations.py | 85 ++ .../v201809/optimization/get_keyword_ideas.py | 113 ++ .../adwords/v201809/remarketing/__init__.py | 15 + .../v201809/remarketing/add_audience.py | 104 ++ .../remarketing/add_conversion_tracker.py | 66 ++ .../remarketing/add_conversion_trackers.py | 101 ++ .../remarketing/add_crm_based_user_list.py | 104 ++ .../remarketing/add_rule_based_user_lists.py | 235 +++++ .../upload_conversion_adjustments.py | 73 ++ .../upload_offline_call_conversions.py | 77 ++ .../remarketing/upload_offline_conversions.py | 82 ++ .../remarketing/upload_offline_data.py | 259 +++++ .../adwords/v201809/reporting/__init__.py | 15 + ...oad_criteria_report_as_stream_with_awql.py | 79 ++ ...criteria_report_as_stream_with_selector.py | 72 ++ ...oad_criteria_report_as_string_with_awql.py | 58 ++ ...criteria_report_as_string_with_selector.py | 55 + .../download_criteria_report_with_awql.py | 58 ++ .../download_criteria_report_with_selector.py | 56 + .../v201809/reporting/get_report_fields.py | 52 + .../reporting/parallel_report_download.py | 244 +++++ .../stream_criteria_report_results.py | 70 ++ examples/adwords/v201809/shopping/__init__.py | 15 + .../shopping/add_product_partition_tree.py | 279 +++++ .../v201809/shopping/add_product_scope.py | 104 ++ .../v201809/shopping/add_shopping_campaign.py | 172 ++++ .../add_shopping_campaign_for_showcase_ads.py | 401 ++++++++ .../shopping/get_product_category_taxonomy.py | 96 ++ .../adwords/v201809/targeting/__init__.py | 15 + .../add_campaign_targeting_criteria.py | 126 +++ .../add_customer_negative_criteria.py | 74 ++ .../add_demographic_targeting_criteria.py | 96 ++ .../get_campaign_targeting_criteria.py | 85 ++ .../get_targetable_languages_and_carriers.py | 57 ++ .../v201809/targeting/lookup_location.py | 82 ++ googleads/adwords.py | 122 ++- googleads/common.py | 2 +- tests/adwords_test.py | 64 +- tests/test_data/unicode_test_data.txt | 965 ++++++++++++++++++ 118 files changed, 13262 insertions(+), 70 deletions(-) create mode 100644 examples/adwords/v201809/__init__.py create mode 100644 examples/adwords/v201809/account_management/__init__.py create mode 100755 examples/adwords/v201809/account_management/accept_service_link.py create mode 100755 examples/adwords/v201809/account_management/create_account.py create mode 100755 examples/adwords/v201809/account_management/get_account_changes.py create mode 100755 examples/adwords/v201809/account_management/get_account_hierarchy.py create mode 100644 examples/adwords/v201809/advanced_operations/__init__.py create mode 100755 examples/adwords/v201809/advanced_operations/add_ad_customizer.py create mode 100755 examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py create mode 100755 examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py create mode 100755 examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py create mode 100755 examples/adwords/v201809/advanced_operations/add_gmail_ad.py create mode 100755 examples/adwords/v201809/advanced_operations/add_html5_ad.py create mode 100755 examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py create mode 100755 examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py create mode 100755 examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py create mode 100755 examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py create mode 100755 examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py create mode 100755 examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py create mode 100755 examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py create mode 100755 examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py create mode 100644 examples/adwords/v201809/basic_operations/__init__.py create mode 100755 examples/adwords/v201809/basic_operations/add_ad_groups.py create mode 100755 examples/adwords/v201809/basic_operations/add_campaigns.py create mode 100755 examples/adwords/v201809/basic_operations/add_expanded_text_ads.py create mode 100755 examples/adwords/v201809/basic_operations/add_keywords.py create mode 100755 examples/adwords/v201809/basic_operations/add_responsive_search_ad.py create mode 100755 examples/adwords/v201809/basic_operations/get_ad_groups.py create mode 100755 examples/adwords/v201809/basic_operations/get_campaigns.py create mode 100755 examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py create mode 100755 examples/adwords/v201809/basic_operations/get_expanded_text_ads.py create mode 100755 examples/adwords/v201809/basic_operations/get_keywords.py create mode 100755 examples/adwords/v201809/basic_operations/get_responsive_search_ads.py create mode 100755 examples/adwords/v201809/basic_operations/pause_ad.py create mode 100755 examples/adwords/v201809/basic_operations/remove_ad.py create mode 100755 examples/adwords/v201809/basic_operations/remove_ad_group.py create mode 100755 examples/adwords/v201809/basic_operations/remove_campaign.py create mode 100755 examples/adwords/v201809/basic_operations/remove_keyword.py create mode 100755 examples/adwords/v201809/basic_operations/update_ad_group.py create mode 100755 examples/adwords/v201809/basic_operations/update_campaign.py create mode 100755 examples/adwords/v201809/basic_operations/update_expanded_text_ad.py create mode 100755 examples/adwords/v201809/basic_operations/update_keyword.py create mode 100644 examples/adwords/v201809/campaign_management/__init__.py create mode 100755 examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py create mode 100755 examples/adwords/v201809/campaign_management/add_campaign_labels.py create mode 100755 examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py create mode 100755 examples/adwords/v201809/campaign_management/add_draft.py create mode 100755 examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py create mode 100755 examples/adwords/v201809/campaign_management/add_trial.py create mode 100755 examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py create mode 100755 examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py create mode 100755 examples/adwords/v201809/campaign_management/get_campaigns_by_label.py create mode 100755 examples/adwords/v201809/campaign_management/graduate_trial.py create mode 100755 examples/adwords/v201809/campaign_management/set_ad_parameters.py create mode 100755 examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py create mode 100755 examples/adwords/v201809/campaign_management/validate_text_ad.py create mode 100644 examples/adwords/v201809/error_handling/__init__.py create mode 100755 examples/adwords/v201809/error_handling/handle_partial_failures.py create mode 100644 examples/adwords/v201809/extensions/__init__.py create mode 100755 examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py create mode 100755 examples/adwords/v201809/extensions/add_prices.py create mode 100755 examples/adwords/v201809/extensions/add_site_links.py create mode 100755 examples/adwords/v201809/extensions/add_site_links_using_feeds.py create mode 100644 examples/adwords/v201809/migration/__init__.py create mode 100755 examples/adwords/v201809/migration/migrate_to_extension_settings.py create mode 100644 examples/adwords/v201809/misc/__init__.py create mode 100755 examples/adwords/v201809/misc/get_all_image_assets.py create mode 100755 examples/adwords/v201809/misc/get_all_images_and_videos.py create mode 100755 examples/adwords/v201809/misc/upload_image.py create mode 100755 examples/adwords/v201809/misc/upload_image_asset.py create mode 100755 examples/adwords/v201809/misc/upload_media_bundle.py create mode 100644 examples/adwords/v201809/optimization/__init__.py create mode 100755 examples/adwords/v201809/optimization/estimate_keyword_traffic.py create mode 100755 examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py create mode 100755 examples/adwords/v201809/optimization/get_keyword_bid_simulations.py create mode 100755 examples/adwords/v201809/optimization/get_keyword_ideas.py create mode 100644 examples/adwords/v201809/remarketing/__init__.py create mode 100755 examples/adwords/v201809/remarketing/add_audience.py create mode 100755 examples/adwords/v201809/remarketing/add_conversion_tracker.py create mode 100755 examples/adwords/v201809/remarketing/add_conversion_trackers.py create mode 100755 examples/adwords/v201809/remarketing/add_crm_based_user_list.py create mode 100755 examples/adwords/v201809/remarketing/add_rule_based_user_lists.py create mode 100755 examples/adwords/v201809/remarketing/upload_conversion_adjustments.py create mode 100755 examples/adwords/v201809/remarketing/upload_offline_call_conversions.py create mode 100755 examples/adwords/v201809/remarketing/upload_offline_conversions.py create mode 100755 examples/adwords/v201809/remarketing/upload_offline_data.py create mode 100644 examples/adwords/v201809/reporting/__init__.py create mode 100755 examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py create mode 100755 examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py create mode 100755 examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py create mode 100755 examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py create mode 100755 examples/adwords/v201809/reporting/download_criteria_report_with_awql.py create mode 100755 examples/adwords/v201809/reporting/download_criteria_report_with_selector.py create mode 100755 examples/adwords/v201809/reporting/get_report_fields.py create mode 100755 examples/adwords/v201809/reporting/parallel_report_download.py create mode 100755 examples/adwords/v201809/reporting/stream_criteria_report_results.py create mode 100644 examples/adwords/v201809/shopping/__init__.py create mode 100755 examples/adwords/v201809/shopping/add_product_partition_tree.py create mode 100755 examples/adwords/v201809/shopping/add_product_scope.py create mode 100755 examples/adwords/v201809/shopping/add_shopping_campaign.py create mode 100755 examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py create mode 100755 examples/adwords/v201809/shopping/get_product_category_taxonomy.py create mode 100644 examples/adwords/v201809/targeting/__init__.py create mode 100755 examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201809/targeting/add_customer_negative_criteria.py create mode 100755 examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py create mode 100755 examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py create mode 100755 examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py create mode 100755 examples/adwords/v201809/targeting/lookup_location.py create mode 100644 tests/test_data/unicode_test_data.txt diff --git a/ChangeLog b/ChangeLog index 44ee7e79..25c13437 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,14 +1,19 @@ +14.1.0 -- 09/21/18 +* Added support and examples for AdWords v201809. +* Resolved issues: +- Issue 281: https://github.com/googleads/googleads-python-lib/issues/281 + 14.0.0 -- 08/21/18 -- DFP rebranded to Google Ad Manager. -- Google Ad Manager v201808 release. -- Removed support for DFP v201708. -- Removed examples for DFP v201711. +* DFP rebranded to Google Ad Manager. +* Google Ad Manager v201808 release. +* Removed support for DFP v201708. +* Removed examples for DFP v201711. 13.0.0 -- 07/25/18 -- Removed support for AdWords v201710. +* Removed support for AdWords v201710. 12.2.0 -- 06/18/18 -- Fixed some DFP examples that would loop forever with Zeep. +* Fixed some DFP examples that would loop forever with Zeep. 12.1.0 -- 06/06/18 * Added support and examples for AdWords v201806. diff --git a/README.md b/README.md index 070d8e61..f40cc90e 100644 --- a/README.md +++ b/README.md @@ -94,13 +94,10 @@ If you have issues directly related to the client library, use the [issue tracker](https://github.com/googleads/googleads-python-lib/issues). -If you have issues pertaining to a specific product, use the product support forums: +If you have issues pertaining to a specific API, use the product support forums: * [AdWords](https://groups.google.com/forum/#!forum/adwords-api) -* [DoubleClick for Publishers](https://groups.google.com/forum/#!forum/google-doubleclick-for-publishers-api) - -Make sure to subscribe to our [Google Plus page](https://plus.google.com/+GoogleAdsDevelopers) -for API change announcements and other news. +* [Ad Manager](https://groups.google.com/forum/#!forum/google-doubleclick-for-publishers-api) ## How do I log SOAP interactions? diff --git a/examples/adwords/v201802/account_management/create_account.py b/examples/adwords/v201802/account_management/create_account.py index c345e9da..4d305c37 100755 --- a/examples/adwords/v201802/account_management/create_account.py +++ b/examples/adwords/v201802/account_management/create_account.py @@ -44,13 +44,7 @@ def main(client): 'name': 'Account created with ManagedCustomerService on %s' % today, 'currencyCode': 'EUR', 'dateTimeZone': 'Europe/London', - }, - # For whitelisted users only, uncomment the inviteeEmail and inviteeRole - # attributes to invite a user to have access to an account on an ADD. An - # email will be sent inviting the user to have access to the newly created - # account. - # 'inviteeEmail': 'invited_user1@example.com', - # 'inviteeRole': 'ADMINISTRATIVE' + } }] # Create the account. It is possible to create multiple accounts with one diff --git a/examples/adwords/v201806/account_management/create_account.py b/examples/adwords/v201806/account_management/create_account.py index 1fe81d49..e4de5452 100755 --- a/examples/adwords/v201806/account_management/create_account.py +++ b/examples/adwords/v201806/account_management/create_account.py @@ -44,13 +44,7 @@ def main(client): 'name': 'Account created with ManagedCustomerService on %s' % today, 'currencyCode': 'EUR', 'dateTimeZone': 'Europe/London', - }, - # For whitelisted users only, uncomment the inviteeEmail and inviteeRole - # attributes to invite a user to have access to an account on an ADD. An - # email will be sent inviting the user to have access to the newly created - # account. - # 'inviteeEmail': 'invited_user1@example.com', - # 'inviteeRole': 'ADMINISTRATIVE' + } }] # Create the account. It is possible to create multiple accounts with one diff --git a/examples/adwords/v201809/__init__.py b/examples/adwords/v201809/__init__.py new file mode 100644 index 00000000..16ff256a --- /dev/null +++ b/examples/adwords/v201809/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Examples for AdWords.""" diff --git a/examples/adwords/v201809/account_management/__init__.py b/examples/adwords/v201809/account_management/__init__.py new file mode 100644 index 00000000..94b5520f --- /dev/null +++ b/examples/adwords/v201809/account_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Account management examples.""" diff --git a/examples/adwords/v201809/account_management/accept_service_link.py b/examples/adwords/v201809/account_management/accept_service_link.py new file mode 100755 index 00000000..7087fc40 --- /dev/null +++ b/examples/adwords/v201809/account_management/accept_service_link.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' + + +def main(client, service_link_id): + # Initialize appropriate service. + customer_service = client.GetService( + 'CustomerService', version='v201809') + + # Create the operation to set the status to ACTIVE. + operations = [{ + 'operator': 'SET', + 'operand': { + 'serviceLinkId': service_link_id, + 'serviceType': 'MERCHANT_CENTER', + 'linkStatus': 'ACTIVE', + } + }] + + # Update the service link. + mutated_service_links = customer_service.mutateServiceLinks(operations) + + # Display results. + for mutated_service_link in mutated_service_links: + print ('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201809/account_management/create_account.py b/examples/adwords/v201809/account_management/create_account.py new file mode 100755 index 00000000..7655a1b2 --- /dev/null +++ b/examples/adwords/v201809/account_management/create_account.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to create an account. + +Note by default this account will only be accessible via its parent AdWords +manager account.. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201809') + + today = datetime.today().strftime('%Y%m%d %H:%M:%S') + # Construct operations and add campaign. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Account created with ManagedCustomerService on %s' % today, + 'currencyCode': 'EUR', + 'dateTimeZone': 'Europe/London', + } + }] + + # Create the account. It is possible to create multiple accounts with one + # request by sending an array of operations. + accounts = managed_customer_service.mutate(operations) + + # Display results. + for account in accounts['value']: + print ('Account with customer ID "%s" was successfully created.' + % account['customerId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/account_management/get_account_changes.py b/examples/adwords/v201809/account_management/get_account_changes.py new file mode 100755 index 00000000..84300fa6 --- /dev/null +++ b/examples/adwords/v201809/account_management/get_account_changes.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the changes in the account during the last 24 hours. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_sync_service = client.GetService( + 'CustomerSyncService', version='v201809') + campaign_service = client.GetService('CampaignService', version='v201809') + + # Construct selector and get all campaigns. + selector = { + 'fields': ['Id', 'Name', 'Status'] + } + campaigns = campaign_service.get(selector) + campaign_ids = [] + if 'entries' in campaigns: + for campaign in campaigns['entries']: + campaign_ids.append(campaign['id']) + else: + print 'No campaigns were found.' + return + + # Construct selector and get all changes. + today = datetime.datetime.today() + yesterday = today - datetime.timedelta(1) + selector = { + 'dateTimeRange': { + 'min': yesterday.strftime('%Y%m%d %H%M%S'), + 'max': today.strftime('%Y%m%d %H%M%S') + }, + 'campaignIds': campaign_ids + } + account_changes = customer_sync_service.get(selector) + + # Display results. + if account_changes: + if 'lastChangeTimestamp' in account_changes: + print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + if account_changes['changedCampaigns']: + for data in account_changes['changedCampaigns']: + print ('Campaign with id "%s" has change status "%s".' + % (data['campaignId'], data['campaignChangeStatus'])) + if (data['campaignChangeStatus'] != 'NEW' and + data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): + if 'addedCampaignCriteria' in data: + print (' Added campaign criteria: %s' % + data['addedCampaignCriteria']) + if 'removedCampaignCriteria' in data: + print (' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) + if 'changedAdGroups' in data: + for ad_group_data in data['changedAdGroups']: + print (' Ad group with id "%s" has change status "%s".' + % (ad_group_data['adGroupId'], + ad_group_data['adGroupChangeStatus'])) + if ad_group_data['adGroupChangeStatus'] != 'NEW': + if 'changedAds' in ad_group_data: + print ' Changed ads: %s' % ad_group_data['changedAds'] + if 'changedCriteria' in ad_group_data: + print (' Changed criteria: %s' % + ad_group_data['changedCriteria']) + if 'removedCriteria' in ad_group_data: + print (' Removed criteria: %s' % + ad_group_data['removedCriteria']) + else: + print 'No changes were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/account_management/get_account_hierarchy.py b/examples/adwords/v201809/account_management/get_account_hierarchy.py new file mode 100755 index 00000000..121872e2 --- /dev/null +++ b/examples/adwords/v201809/account_management/get_account_hierarchy.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the account hierarchy under the current account. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +PAGE_SIZE = 500 + + +def DisplayAccountTree(account, accounts, links, depth=0): + """Displays an account tree. + + Args: + account: dict The account to display. + accounts: dict Map from customerId to account. + links: dict Map from customerId to child links. + depth: int Depth of the current account in the tree. + """ + prefix = '-' * depth * 2 + print '%s%s, %s' % (prefix, account['customerId'], account['name']) + if account['customerId'] in links: + for child_link in links[account['customerId']]: + child_account = accounts[child_link['clientCustomerId']] + DisplayAccountTree(child_account, accounts, links, depth + 1) + + +def main(client): + # Initialize appropriate service. + managed_customer_service = client.GetService( + 'ManagedCustomerService', version='v201809') + + # Construct selector to get all accounts. + offset = 0 + selector = { + 'fields': ['CustomerId', 'Name'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + accounts = {} + child_links = {} + parent_links = {} + root_account = None + + while more_pages: + # Get serviced account graph. + page = managed_customer_service.get(selector) + if 'entries' in page and page['entries']: + # Create map from customerId to parent and child links. + if 'links' in page: + for link in page['links']: + if link['managerCustomerId'] not in child_links: + child_links[link['managerCustomerId']] = [] + child_links[link['managerCustomerId']].append(link) + if link['clientCustomerId'] not in parent_links: + parent_links[link['clientCustomerId']] = [] + parent_links[link['clientCustomerId']].append(link) + # Map from customerID to account. + for account in page['entries']: + accounts[account['customerId']] = account + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + # Find the root account. + for customer_id in accounts: + if customer_id not in parent_links: + root_account = accounts[customer_id] + + # Display account tree. + if root_account: + print 'CustomerId, Name' + DisplayAccountTree(root_account, accounts, child_links, 0) + else: + print 'Unable to determine a root account' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/advanced_operations/__init__.py b/examples/adwords/v201809/advanced_operations/__init__.py new file mode 100644 index 00000000..dc91ba79 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Advanced operations examples.""" diff --git a/examples/adwords/v201809/advanced_operations/add_ad_customizer.py b/examples/adwords/v201809/advanced_operations/add_ad_customizer.py new file mode 100755 index 00000000..4b7c8de6 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_ad_customizer.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad customizer feed. + +Associates the feed with customer and adds an ad that uses the feed to populate +dynamic data. + +""" + + +from datetime import datetime +from uuid import uuid4 + +# Import appropriate classes from the client library. +from googleads import adwords +from googleads import errors + + +FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() +ADGROUPS = [ + 'INSERT_ADGROUP_ID_1_HERE', + 'INSERT_ADGROUP_ID_2_HERE' +] + + +def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): + """Creates ExpandedTextAds that use ad customizations for specified AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. + feed_name: the name of the feed used to apply customizations. + + Raises: + GoogleAdsError: if no ExpandedTextAds were added. + """ + # Get the AdGroupAdService + adgroup_ad_service = client.GetService('AdGroupAdService', 'v201809') + + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, + 'headlinePart2': 'Only {=%s.Price}' % feed_name, + 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, + 'finalUrls': ['http://www.example.com'], + } + + # We add the same ad to both ad groups. When they serve, they will show + # different values, since they match different feed items. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'adGroupId': adgroup, + 'ad': expanded_text_ad + } + } for adgroup in adgroup_ids] + + response = adgroup_ad_service.mutate(operations) + + if response and 'value' in response: + for ad in response['value']: + print ('Created an ad with ID "%s", type "%s", and status "%s".' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + else: + raise errors.GoogleAdsError('No ads were added.') + + +def CreateCustomizerFeed(client, feed_name): + """Creates a new AdCustomizerFeed. + + Args: + client: an AdWordsClient instance. + feed_name: the name for the new AdCustomizerFeed. + + Returns: + The new AdCustomizerFeed. + """ + # Get the AdCustomizerFeedService + ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', + 'v201809') + customizer_feed = { + 'feedName': feed_name, + 'feedAttributes': [ + {'type': 'STRING', 'name': 'Name'}, + {'type': 'STRING', 'name': 'Price'}, + {'type': 'DATE_TIME', 'name': 'Date'} + ] + } + + feed_service_operation = { + 'operator': 'ADD', + 'operand': customizer_feed + } + + response = ad_customizer_feed_service.mutate([feed_service_operation]) + + if response and 'value' in response: + feed = response['value'][0] + feed_data = { + 'feedId': feed['feedId'], + 'nameId': feed['feedAttributes'][0]['id'], + 'priceId': feed['feedAttributes'][1]['id'], + 'dateId': feed['feedAttributes'][2]['id'] + } + print ('Feed with name "%s" and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) + return feed + else: + raise errors.GoogleAdsError('No feeds were added') + + +def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id): + """Restricts the feed item to an ad group. + + Args: + client: an AdWordsClient instance. + feed_item: The feed item. + adgroup_id: The ad group ID. + """ + # Get the FeedItemTargetService + feed_item_target_service = client.GetService( + 'FeedItemTargetService', 'v201809') + + # Optional: Restrict the first feed item to only serve with ads for the + # specified ad group ID. + ad_group_target = { + 'xsi_type': 'FeedItemAdGroupTarget', + 'feedId': feed_item['feedId'], + 'feedItemId': feed_item['feedItemId'], + 'adGroupId': adgroup_id + } + + operation = {'operator': 'ADD', 'operand': ad_group_target} + + response = feed_item_target_service.mutate([operation]) + new_ad_group_target = response['value'][0] + + print('Feed item target for feed ID %s and feed item ID %s was created to ' + 'restrict serving to ad group ID %s' % + (new_ad_group_target['feedId'], + new_ad_group_target['feedItemId'], + new_ad_group_target['adGroupId'])) + + +def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): + """Creates FeedItems for the specified AdGroups. + + These FeedItems contain values to use in ad customizations for the AdGroups. + + Args: + client: an AdWordsClient instance. + adgroup_ids: a list containing two AdGroup Ids. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Raises: + GoogleAdsError: if no FeedItems were added. + """ + # Get the FeedItemService + feed_item_service = client.GetService('FeedItemService', 'v201809') + now = datetime.now() + mars_date = datetime(now.year, now.month, 1, 0, 0) + venus_date = datetime(now.year, now.month, 15, 0, 0) + time_format = '%Y%m%d %H%M%S' + + feed_item_operations = [ + CreateFeedItemAddOperation( + 'Mars', '$1234.56', mars_date.strftime(time_format), + ad_customizer_feed), + CreateFeedItemAddOperation( + 'Venus', '$1450.00', venus_date.strftime(time_format), + ad_customizer_feed) + ] + + response = feed_item_service.mutate(feed_item_operations) + + if 'value' in response: + for feed_item in response['value']: + print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + else: + raise errors.GoogleAdsError('No FeedItems were added.') + + for feed_item, adgroup_id in zip(response['value'], adgroup_ids): + RestrictFeedItemToAdGroup(client, feed_item, adgroup_id) + + +def CreateFeedItemAddOperation(name, price, date, ad_customizer_feed): + """Creates a FeedItemOperation. + + The generated FeedItemOperation will create a FeedItem with the specified + values when sent to FeedItemService.mutate. + + Args: + name: the value for the name attribute of the FeedItem. + price: the value for the price attribute of the FeedItem. + date: the value for the date attribute of the FeedItem. + ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems + with. + + Returns: + A new FeedItemOperation for adding a FeedItem. + """ + feed_item = { + 'feedId': ad_customizer_feed['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], + 'stringValue': name + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], + 'stringValue': price + }, + { + 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], + 'stringValue': date + } + ] + } + + operation = { + 'operator': 'ADD', + 'operand': feed_item + } + + return operation + + +def main(client, adgroup_ids, feed_name=FEED_NAME): + # Create a customizer feed. One feed per account can be used for all ads. + ad_customizer_feed = CreateCustomizerFeed(client, feed_name) + # Add feed items containing the values we'd like to place in ads. + CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) + # All set! We can now create ads with customizations. + CreateAdsWithCustomizations(client, adgroup_ids, feed_name) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py new file mode 100755 index 00000000..4a6a9d8f --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds an ad group level mobile bid modifier override for a campaign. + +To get your ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' + + +def main(client, ad_group_id, bid_modifier): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201809') + + # Mobile criterion ID. + criterion_id = '30001' + + # Prepare to add an ad group level override. + operation = { + # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A + # modifier can be removed with the 'REMOVE' operator. + 'operator': 'ADD', + 'operand': { + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Platform', + 'id': criterion_id + }, + 'bidModifier': bid_modifier + } + } + + # Add ad group level mobile bid modifier. + response = ad_group_bid_modifier_service.mutate([operation]) + if response and response['value']: + modifier = response['value'][0] + value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + else: + print 'No modifiers were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py new file mode 100755 index 00000000..ac988fbf --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. + +To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +from collections import namedtuple +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + +# Used to keep track of DSA page feed details. +_DSAFeedDetails = namedtuple( + '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) +# ID that corresponds to the labels. +DSA_LABEL_FIELD_ID = 2 +# The criterion type to be used for DSA page feeds. +DSA_PAGE_FEED_CRITERION_TYPE = 61 +DSA_PAGE_URL_LABEL = 'discounts' +# ID that corresponds to the page URLs. +DSA_PAGE_URLS_FIELD_ID = 1 + + +def main(client, campaign_id, ad_group_id): + # Get the page feed details. This code example creates a new feed, but you can + # fetch and re-use an existing feed. + feed_details = _CreateFeed(client) + _CreateFeedMapping(client, feed_details) + _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) + + # Associate the page feed with the campaign. + _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) + + # Optional: Target web pages matching the feed's label in the ad group. + _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) + + print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + + +def _CreateFeed(client): + """Creates the feed for DSA page URLs. + + Args: + client: an AdWordsClient instance. + + Returns: + A _DSAFeedDetails instance containing details about the created feed. + """ + # Get the FeedService. + feed_service = client.GetService('FeedService', version='v201809') + + # Create operation. + operation = { + # Create the feed. + 'operand': { + 'name': 'DSA Feed %s' % uuid.uuid4(), + # Create attributes. + 'attributes': [ + {'type': 'URL_LIST', 'name': 'Page URL'}, + {'type': 'STRING_LIST', 'name': 'Label'} + ], + 'origin': 'USER' + }, + 'operator': 'ADD' + } + + # Add the feed. + feed = feed_service.mutate([operation])['value'][0] + return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], + feed['attributes'][1]['id']) + + +def _CreateFeedMapping(client, feed_details): + """Creates the feed mapping for DSA page feeds. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + """ + # Get the FeedMappingService. + feed_mapping_service = client.GetService('FeedMappingService', + version='v201809') + + # Create the operation. + operation = { + # Create the feed mapping. + 'operand': { + 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, + 'feedId': feed_details.feed_id, + # Map the feedAttributeIds to the fieldId constants. + 'attributeFieldMappings': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'fieldId': DSA_PAGE_URLS_FIELD_ID + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'fieldId': DSA_LABEL_FIELD_ID + } + ] + }, + 'operator': 'ADD' + } + + # Add the feed mapping. + feed_mapping_service.mutate([operation]) + + +def _CreateFeedItems(client, feed_details, label_name): + """Creates the page URLs in the DSA page feed. + + Args: + client: an AdWordsClient instance. + feed_details: a _DSAFeedDetails instance. + label_name: a str containing the page feed URL label. + """ + # Get the FeedItemService. + feed_item_service = client.GetService('FeedItemService', version='v201809') + + # For page feed URL recommendations and rules, see: + # https://support.google.com/adwords/answer/7166527 + urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', + 'http://www.example.com/discounts/hotel-deals?id={feeditem}', + 'http://www.example.com/discounts/flight-deals?id={feeditem}') + + # Create the operation. + operations = [{ + # Create the feed item. + 'operand': { + 'feedId': feed_details.feed_id, + 'attributeValues': [ + { + 'feedAttributeId': feed_details.url_attribute_id, + 'stringValues': [url] + }, + { + 'feedAttributeId': feed_details.label_attribute_id, + 'stringValues': [label_name] + } + ] + }, + 'operator': 'ADD' + } for url in urls] + + # Add the feed item. + feed_item_service.mutate(operations) + + +def _UpdateCampaignDSASetting(client, campaign_id, feed_id): + """Updates the campaign DSA setting to DSA pagefeeds. + + Args: + client: an AdWordsClient instance. + campaign_id: a str Campaign ID. + feed_id: a str page Feed ID. + + Raises: + ValueError: If the given campaign is found not to be a dynamic search ad + campaign. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201809') + + selector = { + 'fields': ['Id', 'Settings'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [campaign_id] + }] + } + + response = campaign_service.get(selector) + + if response['totalNumEntries']: + campaign = response['entries'][0] + else: + raise ValueError('No campaign with ID "%d" exists.' % campaign_id) + + if not campaign['settings']: + raise ValueError('This is not a DSA campaign.') + + dsa_setting = None + + campaign_settings = campaign['settings'] + + for setting in campaign_settings: + if setting['Setting.Type'] == 'DynamicSearchAdsSetting': + dsa_setting = setting + break + + if dsa_setting is None: + raise ValueError('This is not a DSA campaign.') + + dsa_setting['pageFeed'] = { + 'feedIds': [feed_id] + } + + # Optional: Specify whether only the supplied URLs should be used with your + # Dynamic Search Ads. + dsa_setting['useSuppliedUrlsOnly'] = True + + operation = { + 'operand': { + 'id': campaign_id, + 'settings': campaign_settings + }, + 'operator': 'SET' + } + + campaign_service.mutate([operation]) + print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id) + + +def _AddDSATargeting(client, ad_group_id, label_name): + """Set custom targeting for the page feed URLs based on a list of labels. + + Args: + client: an AdWordsClient instance. + ad_group_id: a str AdGroup ID. + label_name: a str label name. + + Returns: + A suds.sudsobject.Object representing the newly created webpage criterion. + """ + # Get the AdGroupCriterionService. + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201809') + + # Create the operation. + operation = { + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Test criterion', + # Add a condition for label=specified_label_name. + 'conditions': [{ + 'operand': 'CUSTOM_LABEL', + 'argument': label_name + }], + } + }, + # Set a custom bid for this criterion + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 1500000 + } + }] + } + }, + 'operator': 'ADD' + } + + criterion = ad_group_criterion_service.mutate([operation])['value'][0] + print 'Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus']) + return criterion + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py new file mode 100755 index 00000000..7a2246f2 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Dynamic Search Ads campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + budget = _CreateBudget(client) + campaign_id = _CreateCampaign(client, budget) + ad_group_id = _CreateAdGroup(client, campaign_id) + _CreateExpandedDSA(client, ad_group_id) + _AddWebPageCriteria(client, ad_group_id) + + print 'Dynamic Search Ads campaign setup is complete.' + + +def _CreateBudget(client): + """Creates the budget. + + Args: + client: an AdWordsClient instance. + + Returns: + a suds.sudsobject.Object representation of the created budget. + """ + budget_service = client.GetService('BudgetService', version='v201809') + + # Create the campaign budget + operation = { + 'operand': { + 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), + 'deliveryMethod': 'STANDARD', + 'amount': { + 'microAmount': 500000 + } + }, + 'operator': 'ADD' + } + + budget = budget_service.mutate([operation])['value'][0] + + print 'Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name']) + + return budget + + +def _CreateCampaign(client, budget): + """Creates the campaign. + + Args: + client: an AdWordsClient instance. + budget: a suds.sudsobject.Object representation of a created budget. + + Returns: + An integer campaign ID. + """ + campaign_service = client.GetService('CampaignService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # prevent the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'budget': budget, + # Required: Set the campaign's Dynamic Search Ad settings. + 'settings': [{ + 'xsi_type': 'DynamicSearchAdsSetting', + # Required: Set the domain name and language. + 'domainName': 'example.com', + 'languageCode': 'en' + }], + # Optional: Set the start date. + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + # Optional: Set the end date. + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + }] + + campaign = campaign_service.mutate(operations)['value'][0] + campaign_id = campaign['id'] + + print 'Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name']) + + return campaign_id + + +def _CreateAdGroup(client, campaign_id): + """Creates an ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: an integer campaign ID. + + Returns: + An integer ad group ID. + """ + ad_group_service = client.GetService('AdGroupService') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'adGroupType': 'SEARCH_DYNAMIC_ADS', + 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '3000000' + }, + }] + } + } + }] + + ad_group = ad_group_service.mutate(operations)['value'][0] + ad_group_id = ad_group['id'] + + print 'Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name']) + + return ad_group_id + + +def _CreateExpandedDSA(client, ad_group_id): + """Creates the expanded Dynamic Search Ad. + + Args: + client: an AdwordsClient instance. + ad_group_id: an integer ID of the ad group in which the DSA is added. + """ + # Get the AdGroupAdService. + ad_group_ad_service = client.GetService('AdGroupAdService') + + # Create the operation + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + # Create the expanded dynamic search ad. This ad will have its + # headline and final URL auto-generated at serving time according to + # domain name specific information provided by DynamicSearchAdsSetting + # at the campaign level. + 'ad': { + 'xsi_type': 'ExpandedDynamicSearchAd', + # Set the ad description. + 'description': 'Buy your tickets now!', + 'description2': 'Discount ends soon' + }, + # Optional: Set the status. + 'status': 'PAUSED', + } + }] + + # Create the ad. + ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] + + # Display the results. + print ('Expanded dynamic search ad with ID "%d", description "%s", and ' + 'description 2 "%s" was added' + % (ad['id'], ad['description'], ad['description2'])) + + +def _AddWebPageCriteria(client, ad_group_id): + """Adds a web page criterion to target Dynamic Search Ads. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID of the ad group the criteria is being added to. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201809') + + operations = [{ + 'operator': 'ADD', + # Create biddable ad group criterion. + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Create a webpage criterion for special offers for children. + 'criterion': { + 'xsi_type': 'Webpage', + 'parameter': { + 'criterionName': 'Special offers for children.', + 'conditions': [ + { + 'operand': 'URL', + 'argument': '/marscruise/children' + }, + { + 'operand': 'PAGE_TITLE', + 'argument': 'Special Offer' + } + ] + } + }, + 'userStatus': 'PAUSED', + # Optional: set a custom bid. + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000L + } + }] + } + } + }] + + criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py new file mode 100755 index 00000000..968f7bcf --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + adgroup_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Create the expanded text ad + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + # Specify a list of final URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalUrls': [ + 'http://www.example.com/cruise/space/', + 'http://www.example.com/locations/mars/' + ], + # Specify a list of final mobile URLs. This field cannot be set if URL + # field is set, or finalUrls is unset. This may be specified at ad, + # criterion, and feed item levels. + 'finalMobileUrls': [ + 'http://mobile.example.com/cruise/space/', + 'http://mobile.example.com/locations/mars/' + ] + } + + # Specify a tracking URL for 3rd party tracking provider. You may specify + # one at customer, campaign, ad group, ad, criterion or feed item levels. + expanded_text_ad['trackingUrlTemplate'] = ( + 'http://tracker.example.com/?season={_season}&promocode={_promocode}' + '&u={lpurl}' + ) + + expanded_text_ad['urlCustomParameters'] = { + 'parameters': [ + # Since your tracking URL has two custom parameters, provide + # their values too. This can be provided at campaign, ad group, + # ad, criterion, or feed item levels. + { + 'key': 'season', + 'value': 'christmas' + }, + { + 'key': 'promocode', + 'value': 'NYC123' + } + ] + } + + text_adgroup_ad = { + 'adGroupId': adgroup_id, + 'ad': expanded_text_ad, + # Optional: Set the status. + 'status': 'PAUSED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': text_adgroup_ad + }] + + response = adgroup_ad_service.mutate(operations) + + if 'value' in response: + for adgroup_ad in response['value']: + print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print 'Upgraded URL properties:' + print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] + print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] + print ('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + else: + raise errors.GoogleAdsError('Failed to create AdGroupAd.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201809/advanced_operations/add_gmail_ad.py b/examples/adwords/v201809/advanced_operations/add_gmail_ad.py new file mode 100755 index 00000000..a5c386f0 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_gmail_ad.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example adds a Gmail ad to a given ad group. + +The ad group's campaign needs to have an AdvertisingChannelType of DISPLAY and +AdvertisingChannelSubType of DISPLAY_GMAIL_AD. + +To get your ad groups, run get_ad_groups.py. +""" + + +# Import appropriate classes from the client library. +from googleads import adwords + + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + media_service = client.GetService('MediaService', 'v201809') + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809') + opener = client.proxy_config.BuildOpener() + + try: + # This ad format doesn't allow the creation of an image using the Image.data + # field. An image must first be created using the MediaService, and an + # Image.mediaId must be populated when creating the ad. + uploaded_logo_image = _CreateImage( + media_service, opener, 'https://goo.gl/mtt54n') + uploaded_marketing_image = _CreateImage( + media_service, opener, 'http://goo.gl/3b9Wfh') + + teaser = { + 'headline': 'Dream', + 'description': 'Create your own adventure', + 'businessName': 'Interplanetary Ships', + 'logoImage': uploaded_logo_image + } + + # Creates a Gmail ad. + gmail_ad = { + 'xsi_type': 'GmailAd', + 'teaser': teaser, + 'marketingImage': uploaded_marketing_image, + 'marketingImageHeadline': 'Travel', + 'marketingImageDescription': 'Take to the skies!', + 'finalUrls': ['http://wwww.example.com'] + } + + # Creates ad group ad for the Gmail ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': gmail_ad, + # Optional: Set additional settings. + 'status': 'PAUSED' + } + + # Creates ad group ad operations. + operations = [{ + 'operator': 'ADD', + 'operand': ad_group_ad + }] + + # Adds a Gmail ad. + ad_group_ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad_group_ad in ad_group_ads['value']: + print ('A Gmail ad with id "%d" and short headline "%s" was ' + 'added.' % (ad_group_ad['ad']['id'], + ad_group_ad['ad']['teaser']['headline'])) + except Exception as e: + raise Exception('Failed to create Gmail ad: %s' % e) + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = opener.open(url).read().decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201809/advanced_operations/add_html5_ad.py b/examples/adwords/v201809/advanced_operations/add_html5_ad.py new file mode 100755 index 00000000..2c54d843 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_html5_ad.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import urllib2 +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Create HTML5 media. + html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media_bundle = { + 'xsi_type': 'MediaBundle', + 'data': html5_zip, + 'entryPoint': 'carousel/index.html', + 'type': 'MEDIA_BUNDLE' + } + + ad_data = { + 'uniqueName': 'adData', + 'fields': [ + { + 'name': 'Custom_layout', + 'fieldMedia': media_bundle, + 'type': 'MEDIA_BUNDLE' + }, + { + 'name': 'layout', + 'fieldText': 'Custom', + 'type': 'ENUM' + } + ] + } + + html5_ad = { + 'xsi_type': 'TemplateAd', + 'name': 'Ad for HTML5', + 'templateId': 419, + 'finalUrls': ['https://www.google.com'], + 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', + 'dimensions': { + 'width': '300', + 'height': '250' + }, + 'templateElements': [ad_data] + } + + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': html5_ad, + 'status': 'PAUSED' + } + + operations = [ + { + 'operator': 'ADD', + 'operand': ad_group_ad + } + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) + + +def GetHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return response.read().decode('utf-8') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py b/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py new file mode 100755 index 00000000..777da5a1 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 adds a responsive display ad to an ad group. + +Image assets are uploaded using AssetService. To get ad groups, run +get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords +import requests + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def UploadImageAsset(client, url): + """Uploads the image from the specified url. + + Args: + client: An AdWordsClient instance. + url: The image URL. + + Returns: + The ID of the uploaded image. + """ + # Initialize appropriate service. + asset_service = client.GetService('AssetService', version='v201809') + + # Download the image. + image_request = requests.get(url) + + # Create the image asset. + image_asset = { + 'xsi_type': 'ImageAsset', + 'imageData': image_request.content, + # This field is optional, and if provided should be unique. + # 'assetName': 'Image asset ' + str(uuid.uuid4()), + } + + # Create the operation. + operation = { + 'operator': 'ADD', + 'operand': image_asset + } + + # Create the asset and return the ID. + result = asset_service.mutate([operation]) + + return result['value'][0]['assetId'] + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Create the ad. + multi_asset_responsive_display_ad = { + 'xsi_type': 'MultiAssetResponsiveDisplayAd', + 'headlines': [{ + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Travel to Mars' + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Travel to Jupiter', + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Travel to Pluto' + } + }], + 'descriptions': [{ + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Visit the planet in a luxury spaceship.', + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'See the planet in style.', + } + }], + 'businessName': 'Galactic Luxury Cruises', + 'longHeadline': { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Visit the planet in a luxury spaceship.', + } + }, + # This ad format does not allow the creation of an image asset by setting + # the asset.imageData field. An image asset must first be created using + # the AssetService, and asset.assetId must be populated when creating + # the ad. + 'marketingImages': [{ + 'asset': { + 'xsi_type': 'ImageAsset', + 'assetId': UploadImageAsset(client, 'https://goo.gl/3b9Wfh') + } + }], + 'squareMarketingImages': [{ + 'asset': { + 'xsi_type': 'ImageAsset', + 'assetId': UploadImageAsset(client, 'https://goo.gl/mtt54n') + } + }], + # Optional values + 'finalUrls': ['http://www.example.com'], + 'callToActionText': 'Shop Now', + # Set color settings using hexadecimal values. Set allowFlexibleColor to + # false if you want your ads to render by always using your colors + # strictly. + 'mainColor': '#0000ff', + 'accentColor': '#ffff00', + 'allowFlexibleColor': False, + 'formatSetting': 'NON_NATIVE', + # Set dynamic display ad settings, composed of landscape logo image, + # promotion text, and price prefix. + 'dynamicSettingsPricePrefix': 'as low as', + 'dynamicSettingsPromoText': 'Free shipping!', + 'logoImages': [{ + 'asset': { + 'xsi_type': 'ImageAsset', + 'assetId': UploadImageAsset(client, 'https://goo.gl/mtt54n') + } + }] + } + + # Create ad group ad. + ad_group_ad = { + 'adGroupId': ad_group_id, + 'ad': multi_asset_responsive_display_ad, + # Optional. + 'status': 'PAUSED' + } + + # Add ad. + ads = ad_group_ad_service.mutate([ + {'operator': 'ADD', 'operand': ad_group_ad} + ]) + # Display results. + if 'value' in ads: + for ad in ads['value']: + print ('Added new responsive display ad ad with ID "%d" ' + 'and long headline "%s".' + % (ad['ad']['id'], ad['ad']['longHeadline']['asset']['assetText'])) + else: + print 'No ads were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py new file mode 100755 index 00000000..bbb77aa9 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a responsive display ad to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import urllib2 + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate services. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + media_service = client.GetService('MediaService', version='v201809') + opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + + try: + # Create marketing image. + marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/3b9Wfh') + + # Create square marketing image. + square_marketing_image = _CreateImage(media_service, opener, + 'https://goo.gl/mtt54n') + + # Create a responsive display ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveDisplayAd', + 'marketingImage': {'mediaId': marketing_image['mediaId']}, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://www.example.com'], + # Optional: Set a square marketing image to the ad. + 'squareMarketingImage': { + 'mediaId': square_marketing_image['mediaId'] + }, + # Optional: Set call-to-action text. + 'callToActionText': 'Shop Now', + # Optional: Set dynamic display ad settings, composed of + # landscape logo image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( + media_service, opener), + # Whitelisted accounts only: Set color settings using + # hexadecimal numbers. + # Set allowFlexibleColor to False if you want your ads to render + # by always using your colors strictly. + # 'mainColor': '#0000ff', + # 'accentColor': '#ffff00', + # 'allowFlexibleColor': False + # Whitelisted accounts only: Set the format setting that the ad + # will be served in. + # 'formatSetting': 'NON_NATIVE' + + }, + # Optional fields. + 'status': 'PAUSED' + } + }] + + # Make the mutate request. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + + except: + raise Exception('Failed to create responsive display ad.') + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = opener.open(url).read().decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +def _CreateDynamicDisplayAdSettings(media_service, opener): + """Creates settings for dynamic display ad. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + + Returns: + The dynamic display ad settings. + """ + image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + + logo = { + 'type': 'IMAGE', + 'mediaId': image['mediaId'], + 'xsi_type': 'Image' + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!', + 'xsi_type': 'DynamicSettings', + } + + return dynamic_settings + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py new file mode 100755 index 00000000..6b983688 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Adds a Shopping dynamic remarketing campaign for the Display Network. + +This example steps through the following: +* Creates a new Display Network campaign. +* Links the campaign with Merchant Center. +* Links the user list to the ad group. +* Creates a responsive display ad to render the dynamic text. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import uuid + +from googleads import adwords + + +MERCHANT_ID = 'INSERT_MERCHANT_CENTER_ID_HERE' +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +USER_LIST_ID = 'INSERT_USER_LIST_ID_HERE' + + +def main(client, merchant_id, budget_id, user_list_id): + opener = client.proxy_config.BuildOpener() + + campaign = CreateCampaign(client, merchant_id, budget_id) + campaign_id = campaign['id'] + print 'Campaign with name "%s" and ID "%d" was added.' % ( + campaign['name'], campaign_id) + + ad_group = CreateAdGroup(client, campaign_id) + ad_group_id = ad_group['id'] + print 'Ad group with name "%s" and ID "%d" was added.' % ( + ad_group['name'], ad_group_id) + + ad_group_ad = CreateAd(client, opener, ad_group_id) + print 'Responsive display ad with ID "%d" was added.' % ( + ad_group_ad['ad']['id']) + + AttachUserList(client, ad_group_id, user_list_id) + print 'User list with ID "%d" was attached to ad group with ID "%d".' % ( + user_list_id, ad_group_id) + + +def CreateCampaign(client, merchant_id, budget_id): + """Creates a new Display Network campaign. + + Args: + client: an AdWordsClient instance. + merchant_id: a int merchant center ID. + budget_id: a int budget ID. + + Returns: + The campaign that was successfully created. + """ + campaign_service = client.GetService('CampaignService', 'v201809') + + campaign = { + 'name': 'Shopping campaign #%d' % uuid.uuid4(), + # Dynamic remarketing campaigns are only available on the Google Display + # Network. + 'advertisingChannelType': 'DISPLAY', + 'status': 'PAUSED', + 'budget': { + 'budgetId': budget_id + }, + # This example uses a Manual CPC bidding strategy, but you should select + # the strategy that best aligns with your sales goals. More details here: + # https://support.google.com/adwords/answer/2472725 + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [{ + 'xsi_type': 'ShoppingSetting', + # Campaigns with numerically higher priorities take precedence over + # those with lower priorities. + 'campaignPriority': 0, + 'merchantId': merchant_id, + # Display network campaigns do not support partition by country. The + # only supported value is "ZZ". This signals that products from all + # countries are available in this campaign. The actual products which + # serve are based on the products tagged in the user list entry. + 'salesCountry': 'ZZ', + # Optional: Enable local inventory ads (items for sale in physical + # stores.) + 'enableLocal': True, + }] + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + return campaign_service.mutate(operations)['value'][0] + + +def CreateAdGroup(client, campaign_id): + """Creates a dynamic remarketing campaign. + + Args: + client: an AdWordsClient instance. + campaign_id: an int campaign ID. + + Returns: + The ad group that was successfully created. + """ + ad_group_service = client.GetService('AdGroupService', 'v201809') + + ad_group = { + 'name': 'Dynamic remarketing ad group', + 'campaignId': campaign_id, + 'status': 'ENABLED' + } + + operations = [{ + 'operator': 'ADD', + 'operand': ad_group + }] + + return ad_group_service.mutate(operations)['value'][0] + + +def CreateAd(client, opener, ad_group_id): + """Creates a ResponsiveDisplayAd. + + Args: + client: an AdWordsClient instance. + opener: an OpenerDirector instance. + ad_group_id: an int ad group ID. + + Returns: + The ad group ad that was successfully created. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809') + media_service = client.GetService('MediaService', 'v201809') + + marketing_image_id = _CreateImage( + media_service, opener, 'https://goo.gl/3b9Wfh') + logo_image_id = _CreateImage(media_service, opener, 'https://goo.gl/mtt54n') + + ad = { + 'xsi_type': 'ResponsiveDisplayAd', + # This ad format doesn't allow the creation of an image using the + # Image.data field. An image must first be created using the MediaService, + # and Image.mediaId must be populated when creating the ad. + 'marketingImage': { + 'xsi_type': 'Image', + 'mediaId': marketing_image_id + }, + 'shortHeadline': 'Travel', + 'longHeadline': 'Travel the World', + 'description': 'Take to the air!', + 'businessName': 'Interplanetary Cruises', + 'finalUrls': ['http://wwww.example.com'], + # Optional: Call to action text. + # Valid texts: https://support.google.com/adwords/answer/7005917 + 'callToActionText': 'Apply Now', + # Optional: Set dynamic display ad settings, composed of landscape logo + # image, promotion text, and price prefix. + 'dynamicDisplayAdSettings': CreateDynamicDisplayAdSettings( + client, opener), + # Optional: Create a logo image and set it to the ad. + 'logoImage': { + 'xsi_type': 'Image', + 'mediaId': logo_image_id + }, + # Optional: Create a square marketing image and set it to the ad. + 'squareMarketingImage': { + 'xsi_type': 'Image', + 'mediaId': logo_image_id + }, + # Whitelisted accounts only: Set color settings using hexadecimal values. + # Set allowFlexibleColor to False if you want your ads to render by always + # using your colors strictly. + # 'mainColor': '#000fff', + # 'accentColor': '#fff000', + # 'allowFlexibleColor': False, + # Whitelisted accounts only: Set the format setting that the ad will be + # served in. + # 'formatSetting': 'NON_NATIVE' + } + + ad_group_ad = { + 'ad': ad, + 'adGroupId': ad_group_id + } + + operations = [{ + 'operation': 'ADD', + 'operand': ad_group_ad + }] + + return ad_group_ad_service.mutate(operations)['value'][0] + + +def AttachUserList(client, ad_group_id, user_list_id): + """Links the provided ad group and user list. + + Args: + client: an AdWordsClient instance. + ad_group_id: an int ad group ID. + user_list_id: an int user list ID. + + Returns: + The ad group criterion that was successfully created. + """ + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', 'v201809') + + user_list = { + 'xsi_type': 'CriterionUserList', + 'userListId': user_list_id + } + + ad_group_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'criterion': user_list, + 'adGroupId': ad_group_id + } + + operations = [{ + 'operator': 'ADD', + 'operand': ad_group_criterion + }] + + return ad_group_criterion_service.mutate(operations)['value'][0] + + +def CreateDynamicDisplayAdSettings(client, opener): + """Creates dynamic display ad settings. + + Args: + client: an AdWordsClient instance. + opener: an OpenerDirector instance. + + Returns: + A dict containing the dynamic display ad settings. + """ + media_service = client.GetService('MediaService', 'v201809') + + logo = { + 'xsi_type': 'Image', + 'mediaId': _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') + } + + dynamic_settings = { + 'landscapeLogoImage': logo, + 'pricePrefix': 'as low as', + 'promoText': 'Free shipping!' + } + + return dynamic_settings + + +def _CreateImage(media_service, opener, url): + """Creates an image and uploads it to the server. + + Args: + media_service: a SudsServiceProxy instance for AdWords's MediaService. + opener: an OpenerDirector instance. + url: a str URL used to load image data. + + Returns: + The image that was successfully uploaded. + """ + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + image_data = opener.open(url).read().decode('utf-8') + image = { + 'type': 'IMAGE', + 'data': image_data, + 'xsi_type': 'Image' + } + + return media_service.upload(image)[0] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, MERCHANT_ID, BUDGET_ID, USER_LIST_ID) diff --git a/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py new file mode 100755 index 00000000..28e4f609 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Universal App campaign. + +To get campaigns, run get_campaigns.py. To upload image assets for this +campaign, run upload_image.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201809') + + budget_id = CreateBudget(client) + + # Create the Universal App campaign. + universal_app_campaign = { + 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'MULTI_CHANNEL', + 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', + # Set the campaign's bidding strategy. Universal app campaigns only + # support TARGET_CPA bidding strategy. + 'biddingStrategyConfiguration': { + # Set the target CPA to $1 / app install. + 'biddingScheme': { + 'xsi_type': 'TargetCpaBiddingScheme', + 'targetCpa': { + 'microAmount': '1000000' + } + }, + 'biddingStrategyType': 'TARGET_CPA' + }, + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + } + + universal_app_campaign['settings'] = [ + # Set the campaign's assets and ad text ideas. These values will + # be used to generate ads. + { + 'xsi_type': 'UniversalAppCampaignSetting', + 'appId': 'com.labpixies.colordrips', + 'appVendor': 'VENDOR_GOOGLE_MARKET', + 'description1': 'A cool puzzle game', + 'description2': 'Remove connected blocks', + 'description3': '3 difficulty levels', + 'description4': '4 colorful fun skins', + # Optional: You can set up to 20 image assets for your campaign. + # See upload_image.py for an example on how to upload images. + # + # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] + } + ] + + # Optimize this campaign for getting new users for your app. + universal_app_campaign_setting = universal_app_campaign['settings'][0] + universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( + 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') + + # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, + # then also specify your in-app conversion types so AdWords can focus your + # campaign on people who are most likely to complete the corresponding in-app + # actions. + # + # Conversions type IDs can be retrieved using ConversionTrackerService.get. + # universal_app_campaign['selectiveOptimization'] = { + # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] + # } + + # Optional: Set the campaign settings for Advanced location options. + universal_app_campaign['settings'].append({ + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + }) + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': universal_app_campaign + }] + + campaigns = campaign_service.mutate(operations)['value'] + + # Display results. + if campaigns: + for campaign in campaigns: + print ('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + # Optional: Set the campaign's location and language targeting. No other + # targeting criteria can be used for Universal App campaigns. + SetCampaignTargetingCriteria(client, campaign) + else: + print 'No Universal App campaigns were added.' + + +def CreateBudget(client): + """Creates a budget and returns its budgetId. + + Args: + client: An AdWordsClient instance. + + Returns: + An int budgetId for the created Budget. + """ + budget_service = client.GetService('BudgetService', version='v201809') + + # Create a budget. + budget = { + 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Create the budget and return its ID. + budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] + + return budget_id + + +def SetCampaignTargetingCriteria(client, campaign): + """Sets targeting criteria for the given campaign. + + Args: + client: An AdWordsClient instance. + campaign: A suds object representing the campaign we wish to attach + targeting criteria. + """ + campaign_criterion_service = client.GetService('CampaignCriterionService') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + criteria = [ + { + 'xsi_type': 'Location', + 'id': 21137 # California + }, + { + 'xsi_type': 'Location', + 'id': 2484 # Mexico + }, + { + 'xsi_type': 'Language', + 'id': 1000 # English + }, + { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + ] + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign['id'], + 'criterion': criterion + } + } for criterion in criteria] + + response = campaign_criterion_service.mutate(operations) + + if response and 'value' in response: + # Display the added campaign targets. + for criterion in response['value']: + print ('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], + criterion['criterion']['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py new file mode 100755 index 00000000..d5e20932 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Attaches a new shared list of negative broad match keywords to a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_set_service = client.GetService('SharedSetService', version='v201809') + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201809') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201809') + + # Keywords to create a shared set of. + keywords = ['mars cruise', 'mars hotels'] + # Create shared negative keyword set. + shared_set = { + 'name': 'API Negative keyword list - %d' % uuid.uuid4(), + 'type': 'NEGATIVE_KEYWORDS' + } + + # Add shared set. + operations = [{ + 'operator': 'ADD', + 'operand': shared_set + }] + + response = shared_set_service.mutate(operations) + + if response and response['value']: + shared_set = response['value'][0] + shared_set_id = shared_set['sharedSetId'] + + print 'Shared set with ID %d and name "%s" was successfully added.' % ( + shared_set_id, shared_set['name'] + ) + else: + raise errors.GoogleAdsError('No shared set was added.') + + # Add negative keywords to shared set. + shared_criteria = [ + { + 'criterion': { + 'xsi_type': 'Keyword', + 'text': keyword, + 'matchType': 'BROAD' + }, + 'negative': True, + 'sharedSetId': shared_set_id + } for keyword in keywords + ] + + operations = [ + { + 'operator': 'ADD', + 'operand': criterion + } for criterion in shared_criteria + ] + + response = shared_criterion_service.mutate(operations) + + if 'value' in response: + for shared_criteria in response['value']: + print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + shared_criteria['criterion']['id'], + shared_criteria['criterion']['text'], + shared_criteria['sharedSetId'] + ) + else: + raise errors.GoogleAdsError('No shared keyword was added.') + + # Attach the articles to the campaign. + campaign_set = { + 'campaignId': campaign_id, + 'sharedSetId': shared_set_id + } + + operations = [ + { + 'operator': 'ADD', + 'operand': campaign_set + } + ] + + response = campaign_shared_set_service.mutate(operations) + + if 'value' in response: + print 'Shared set ID %d was attached to campaign ID %d' % ( + response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] + ) + else: + raise errors.GoogleAdsError('No campaign shared set was added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py new file mode 100755 index 00000000..4dfa6728 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Demonstrates how to find and remove shared sets/shared set criterions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 500 + + +def main(client, campaign_id): + # Initialize appropriate services. + shared_criterion_service = client.GetService('SharedCriterionService', + version='v201809') + campaign_shared_set_service = client.GetService('CampaignSharedSetService', + version='v201809') + + shared_set_ids = [] + criterion_ids = [] + + # First, retrieve all shared sets associated with the campaign. + + # Create selector for shared sets to: + # - filter by campaign ID, + # - filter by shared set type. + selector = { + 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', + 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + }, + { + 'field': 'SharedSetType', + 'operator': 'IN', + 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = campaign_shared_set_service.get(selector) + if 'entries' in page: + for shared_set in page['entries']: + print 'Campaign shared set ID %d and name "%s"' % ( + shared_set['sharedSetId'], shared_set['sharedSetName'] + ) + shared_set_ids.append(shared_set['sharedSetId']) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Next, retrieve criterion IDs for all found shared sets. + selector = { + 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', + 'PlacementUrl'], + 'predicates': [ + { + 'field': 'SharedSetId', + 'operator': 'IN', + 'values': shared_set_ids + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + # Set initial values: + offset = 0 + page = {'totalNumEntries': 1} + + while page['totalNumEntries'] > offset: + page = shared_criterion_service.get(selector) + if 'entries' in page: + for shared_criterion in page['entries']: + if shared_criterion['criterion']['type'] == 'KEYWORD': + print ('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) + elif shared_criterion['criterion']['type'] == 'PLACEMENT': + print ('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) + else: + print 'Shared criterion with ID %d was found.' % ( + shared_criterion['criterion']['id'], + ) + criterion_ids.append({ + 'sharedSetId': shared_criterion['sharedSetId'], + 'criterionId': shared_criterion['criterion']['id'] + }) + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = offset + + # Finally, remove the criteria. + if criterion_ids: + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'criterion': {'id': criterion['criterionId']}, + 'sharedSetId': criterion['sharedSetId'] + } + } for criterion in criterion_ids + ] + + response = shared_criterion_service.mutate(operations) + if 'value' in response: + for criterion in response['value']: + print ('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + else: + print 'No shared criteria were removed.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py new file mode 100755 index 00000000..fe830c0a --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the ad group level bid modifiers for a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + ad_group_bid_modifier_service = client.GetService( + 'AdGroupBidModifierService', version='v201809') + + # Get all ad group bid modifiers for the campaign. + selector = { + 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], + 'paging': { + 'startIndex': '0', + 'numberResults': str(PAGE_SIZE) + } + } + + # Set initial values. + offset, page = 0, {} + more_results = True + + while more_results: + page = ad_group_bid_modifier_service.get(selector) + if page['entries']: + for modifier in page['entries']: + value = (modifier['bidModifier'] if 'bidModifier' in modifier + else 'unset') + print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) + + # Increment values to request the next page. + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + else: + print 'No ad group bid modifiers returned.' + more_results = int(page['totalNumEntries']) > offset + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py new file mode 100755 index 00000000..c5fb8010 --- /dev/null +++ b/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds a Shared Bidding Strategy and uses it to construct a campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +# Enter a shared budget ID to re-use an existing budget or leave as None to +# create a new one. +BUDGET_ID = None + + +def main(client, budget_id): + bidding_strategy = CreateBiddingStrategy(client) + + if budget_id is None: + budget = CreateSharedBudget(client) + budget_id = budget['budgetId'] + + CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) + + +def CreateBiddingStrategy(client): + """Creates a bidding strategy object. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a bidding strategy. + """ + # Initialize appropriate service. + bidding_strategy_service = client.GetService( + 'BiddingStrategyService', version='v201809') + + # Create a shared bidding strategy. + shared_bidding_strategy = { + 'name': 'Maximize Clicks %s' % uuid.uuid4(), + 'biddingScheme': { + 'xsi_type': 'TargetSpendBiddingScheme', + # Optionally set additional bidding scheme parameters. + 'bidCeiling': { + 'microAmount': '2000000' + } + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': shared_bidding_strategy + } + + response = bidding_strategy_service.mutate([operation]) + new_bidding_strategy = response['value'][0] + + print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + + return new_bidding_strategy + + +def CreateSharedBudget(client): + """Creates an explicit budget to be used only to create the Campaign. + + Args: + client: AdWordsClient the client to run the example with. + + Returns: + dict An object representing a shared budget. + """ + # Initialize appropriate service. + budget_service = client.GetService('BudgetService', version='v201809') + + # Create a shared budget + budget = { + 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '2000000' + }, + 'deliveryMethod': 'STANDARD', + 'isExplicitlyShared': 'true' + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': budget + } + + response = budget_service.mutate([operation]) + return response['value'][0] + + +def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): + """Create a Campaign with a Shared Bidding Strategy. + + Args: + client: AdWordsClient the client to run the example with. + bidding_strategy_id: string the bidding strategy ID to use. + budget_id: string the shared budget ID to use. + + Returns: + dict An object representing a campaign. + """ + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201809') + + # Create campaign. + campaign = { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyId': bidding_strategy_id + }, + 'advertisingChannelType': 'SEARCH', + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'true' + } + } + + # Create operation. + operation = { + 'operator': 'ADD', + 'operand': campaign + } + + response = campaign_service.mutate([operation]) + new_campaign = response['value'][0] + + print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + + return new_campaign + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201809/basic_operations/__init__.py b/examples/adwords/v201809/basic_operations/__init__.py new file mode 100644 index 00000000..1a2bc84a --- /dev/null +++ b/examples/adwords/v201809/basic_operations/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Basic operations examples.""" diff --git a/examples/adwords/v201809/basic_operations/add_ad_groups.py b/examples/adwords/v201809/basic_operations/add_ad_groups.py new file mode 100755 index 00000000..8451644e --- /dev/null +++ b/examples/adwords/v201809/basic_operations/add_ad_groups.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad groups to a given campaign. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201809') + + # Construct operations and add ad groups. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + }, + } + ] + }, + 'settings': [ + { + # Targeting restriction settings. Depending on the + # criterionTypeGroup value, most TargetingSettingDetail only + # affect Display campaigns. However, the + # USER_INTEREST_AND_LIST value works for RLSA campaigns - + # Search campaigns targeting using a remarketing list. + 'xsi_type': 'TargetingSetting', + 'details': [ + # Restricting to serve ads that match your ad group + # placements. This is equivalent to choosing + # "Target and bid" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'PLACEMENT', + 'targetAll': 'false', + }, + # Using your ad group verticals only for bidding. This is + # equivalent to choosing "Bid only" in the UI. + { + 'xsi_type': 'TargetingSettingDetail', + 'criterionTypeGroup': 'VERTICAL', + 'targetAll': 'true', + }, + ] + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), + 'status': 'ENABLED', + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + print ('Ad group with name "%s" and id "%s" was added.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/basic_operations/add_campaigns.py b/examples/adwords/v201809/basic_operations/add_campaigns.py new file mode 100755 index 00000000..1420734c --- /dev/null +++ b/examples/adwords/v201809/basic_operations/add_campaigns.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds campaigns. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import datetime +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + campaign_service = client.GetService('CampaignService', version='v201809') + budget_service = client.GetService('BudgetService', version='v201809') + + # Create a budget, which can be shared by multiple campaigns. + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + # Construct operations and add campaigns. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once you've + # added targeting and the ads are ready to serve. + 'status': 'PAUSED', + 'advertisingChannelType': 'SEARCH', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC', + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'networkSetting': { + 'targetGoogleSearch': 'true', + 'targetSearchNetwork': 'true', + 'targetContentNetwork': 'false', + 'targetPartnerSearchNetwork': 'false' + }, + # Optional fields + 'startDate': (datetime.datetime.now() + + datetime.timedelta(1)).strftime('%Y%m%d'), + 'frequencyCap': { + 'impressions': '5', + 'timeUnit': 'DAY', + 'level': 'ADGROUP' + }, + 'settings': [ + { + 'xsi_type': 'GeoTargetTypeSetting', + 'positiveGeoTargetType': 'DONT_CARE', + 'negativeGeoTargetType': 'DONT_CARE' + } + ] + } + }, { + 'operator': 'ADD', + 'operand': { + 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), + 'status': 'PAUSED', + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'endDate': (datetime.datetime.now() + + datetime.timedelta(365)).strftime('%Y%m%d'), + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'advertisingChannelType': 'DISPLAY' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py new file mode 100755 index 00000000..7d0cb187 --- /dev/null +++ b/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds expanded text ads to a given ad group. + +To get ad_group_id, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': ('Cruise #%s to Mars' + % str(uuid.uuid4())[:8]), + 'headlinePart2': 'Best Space Cruise Line', + 'headlinePart3': 'For Your Loved Ones', + 'description': 'Buy your tickets now!', + 'description2': 'Discount ends soon', + 'finalUrls': ['http://www.example.com/%s' % i], + }, + # Optional fields. + 'status': 'PAUSED' + } + } for i in range(NUMBER_OF_ADS) + ] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print ('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s\n\theadlinePart3: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['headlinePart3'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/basic_operations/add_keywords.py b/examples/adwords/v201809/basic_operations/add_keywords.py new file mode 100755 index 00000000..47fb127f --- /dev/null +++ b/examples/adwords/v201809/basic_operations/add_keywords.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds ad group criteria to an ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201809') + + # Construct keyword ad group criterion object. + keyword1 = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars' + }, + # These fields are optional. + 'userStatus': 'PAUSED', + 'finalUrls': { + 'urls': ['http://example.com/mars'] + } + } + + keyword2 = { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'EXACT', + 'text': 'pluto' + } + } + + # Construct operations and add ad group criteria. + operations = [ + { + 'operator': 'ADD', + 'operand': keyword1 + }, + { + 'operator': 'ADD', + 'operand': keyword2 + } + ] + ad_group_criteria = ad_group_criterion_service.mutate( + operations)['value'] + + # Display results. + for criterion in ad_group_criteria: + print ('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py b/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py new file mode 100755 index 00000000..0e7dd0f2 --- /dev/null +++ b/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 adds a responsive search ad to a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +NUMBER_OF_ADS = 5 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + responsive_search_ad = { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ResponsiveSearchAd', + 'finalUrls': ['http://www.example.com/cruise'], + 'path1': 'all-inclusive', + 'path2': 'deals', + 'headlines': [{ + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Cruise to Mars # ' + str(uuid.uuid4())[:8] + }, + 'pinnedField': 'HEADLINE_1' + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Best Space Cruise Line', + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Experience the Stars' + } + }], + 'descriptions': [{ + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Buy your tickets now.' + } + }, { + 'asset': { + 'xsi_type': 'TextAsset', + 'assetText': 'Visit the Red Planet', + } + }], + }, + # Optional fields. + 'status': 'PAUSED' + } + + # Create the operations. + operations = [{ + 'operator': 'ADD', + 'operand': responsive_search_ad + }] + + # Create the ad on the server. + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + ad = ad['ad'] + print ('Ad of type "%s" with id "%d" was added.\n' + 'Headlines:\n%s\n' + 'Descriptions:\n%s' + % (ad['Ad.Type'], ad['id'], + '\n'.join(['\t%s (pinned to %s)' % + (headline['asset']['assetText'], + headline['pinnedField']) + for headline in ad['headlines']]), + '\n'.join(['\t%s (pinned to %s)' % + (headline['asset']['assetText'], + headline['pinnedField']) + for headline in ad['descriptions']]))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/basic_operations/get_ad_groups.py b/examples/adwords/v201809/basic_operations/get_ad_groups.py new file mode 100755 index 00000000..29db6bef --- /dev/null +++ b/examples/adwords/v201809/basic_operations/get_ad_groups.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 groups for a given campaign. + +To add an ad group, run add_ad_group.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201809') + + # Construct selector and get all ad groups. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'predicates': [ + { + 'field': 'CampaignId', + 'operator': 'EQUALS', + 'values': [campaign_id] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = ad_group_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group in page['entries']: + print ('Ad group with name "%s", id "%s" and status "%s" was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) + else: + print 'No ad groups were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/basic_operations/get_campaigns.py b/examples/adwords/v201809/basic_operations/get_campaigns.py new file mode 100755 index 00000000..4c1de220 --- /dev/null +++ b/examples/adwords/v201809/basic_operations/get_campaigns.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201809') + + # Construct selector and get all campaigns. + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Status'], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py new file mode 100755 index 00000000..0bcab324 --- /dev/null +++ b/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with AWQL. + +To add a campaign, run add_campaign.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201809') + + # Construct query and get all campaigns. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'Name', 'Status') + .Where('Status').EqualTo('ENABLED') + .OrderBy('Name') + .Limit(0, PAGE_SIZE) + .Build()) + + for page in query.Pager(campaign_service): + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) + else: + print 'No campaigns were found.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py new file mode 100755 index 00000000..2c75b20c --- /dev/null +++ b/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 expanded text ads for a given ad group. + +To add an expanded text ad, run add_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', + 'Description'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['EXPANDED_TEXT_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad in page['entries']: + print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/basic_operations/get_keywords.py b/examples/adwords/v201809/basic_operations/get_keywords.py new file mode 100755 index 00000000..9bc3085c --- /dev/null +++ b/examples/adwords/v201809/basic_operations/get_keywords.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 group criteria in an account. + +To add keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' + + +def main(client, adgroup_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201809') + + # Construct selector and get all ad group criteria. + offset = 0 + selector = { + 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [adgroup_id] + }, + { + 'field': 'CriteriaType', + 'operator': 'EQUALS', + 'values': ['KEYWORD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] + } + more_pages = True + while more_pages: + page = ad_group_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for keyword in page['entries']: + print ('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) + else: + print 'No keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py b/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py new file mode 100755 index 00000000..f449281f --- /dev/null +++ b/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 non-removed responsive search ads in a specified ad group. + +To add responsive search ads, run add_responsive_search_ad.py. To get ad groups, +run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'Status', 'ResponsiveSearchAdHeadlines', + 'ResponsiveSearchAdDescriptions'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'AdType', + 'operator': 'EQUALS', + 'values': ['RESPONSIVE_SEARCH_AD'] + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'ordering': [ + { + 'field': 'Id', + 'sortOrder': 'ASCENDING' + } + ] + } + + more_pages = True + while more_pages: + page = ad_group_ad_service.get(selector) + + # Display results. + if 'entries' in page: + for ad_group_ad in page['entries']: + ad = ad_group_ad['ad'] + print ('Responsive search ad with status %s and id "%d" was found.\n' + 'Headlines:\n%s\n' + 'Descriptions:\n%s' + % (ad_group_ad['status'], ad['id'], + '\n'.join(['\t%s (pinned to %s)' % + (headline['asset']['assetText'], + headline['pinnedField']) + for headline in ad['headlines']]), + '\n'.join(['\t%s (pinned to %s)' % + (headline['asset']['assetText'], + headline['pinnedField']) + for headline in ad['descriptions']]))) + else: + print 'No ads were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/basic_operations/pause_ad.py b/examples/adwords/v201809/basic_operations/pause_ad.py new file mode 100755 index 00000000..a495cb3d --- /dev/null +++ b/examples/adwords/v201809/basic_operations/pause_ad.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates status for a given ad. + +To get ads, run get_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Construct operations and update an ad. + operations = [{ + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id, + }, + 'status': 'PAUSED' + } + }] + ads = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in ads['value']: + print 'Ad with id "%s" was updated.'% ad['ad']['id'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201809/basic_operations/remove_ad.py b/examples/adwords/v201809/basic_operations/remove_ad.py new file mode 100755 index 00000000..3c238576 --- /dev/null +++ b/examples/adwords/v201809/basic_operations/remove_ad.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. + +To get ads, run get_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_group_id, ad_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Construct operations and delete ad. + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'id': ad_id + } + } + }] + result = ad_group_ad_service.mutate(operations) + + # Display results. + for ad in result['value']: + print ('Ad with id "%s" and type "%s" was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201809/basic_operations/remove_ad_group.py b/examples/adwords/v201809/basic_operations/remove_ad_group.py new file mode 100755 index 00000000..b09b9cd2 --- /dev/null +++ b/examples/adwords/v201809/basic_operations/remove_ad_group.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201809') + + # Construct operations and delete ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'REMOVED' + } + }] + result = ad_group_service.mutate(operations) + + # Display results. + for ad_group in result['value']: + print ('Ad group with name "%s" and id "%s" was deleted.' + % (ad_group['name'], ad_group['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/basic_operations/remove_campaign.py b/examples/adwords/v201809/basic_operations/remove_campaign.py new file mode 100755 index 00000000..d919860c --- /dev/null +++ b/examples/adwords/v201809/basic_operations/remove_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201809') + + # Construct operations and delete campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'REMOVED' + } + }] + result = campaign_service.mutate(operations) + + # Display results. + for campaign in result['value']: + print ('Campaign with name "%s" and id "%s" was deleted.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/basic_operations/remove_keyword.py b/examples/adwords/v201809/basic_operations/remove_keyword.py new file mode 100755 index 00000000..0d08ecbc --- /dev/null +++ b/examples/adwords/v201809/basic_operations/remove_keyword.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. + +To get ad group criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201809') + + # Construct operations and delete ad group criteria. + operations = [ + { + 'operator': 'REMOVE', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id + } + } + } + ] + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + print ('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['Criterion.Type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201809/basic_operations/update_ad_group.py b/examples/adwords/v201809/basic_operations/update_ad_group.py new file mode 100755 index 00000000..1385903f --- /dev/null +++ b/examples/adwords/v201809/basic_operations/update_ad_group.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the CPC bid and status for a given ad group. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' + + +def main(client, ad_group_id, bid_micro_amount=None): + # Initialize appropriate service. + ad_group_service = client.GetService('AdGroupService', version='v201809') + + # Construct operations and update an ad group. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': ad_group_id, + 'status': 'PAUSED' + } + }] + + if bid_micro_amount: + operations[0]['operand']['biddingStrategyConfiguration'] = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': bid_micro_amount, + } + }] + } + + ad_groups = ad_group_service.mutate(operations) + + # Display results. + for ad_group in ad_groups['value']: + bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] + # Find the CpcBid in the bidding strategy configuration's bids collection. + cpc_bid_micros = None + + if bidding_strategy_configuration: + bids = bidding_strategy_configuration['bids'] + + if bids: + for bid in bids: + if bid['Bids.Type'] == 'CpcBid': + cpc_bid_micros = bid['bid']['microAmount'] + break + + print ('Ad group with name "%s", and id "%s" was updated to have status ' + '"%s" and CPC bid %d.' + % (ad_group['name'], ad_group['id'], ad_group['status'], + cpc_bid_micros)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201809/basic_operations/update_campaign.py b/examples/adwords/v201809/basic_operations/update_campaign.py new file mode 100755 index 00000000..fa9ae36c --- /dev/null +++ b/examples/adwords/v201809/basic_operations/update_campaign.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates a campaign by setting its status to PAUSED. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201809') + + # Construct operations and update campaign. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'status': 'PAUSED' + } + }] + campaigns = campaign_service.mutate(operations) + + # Display results. + for campaign in campaigns['value']: + print ('Campaign with name "%s" and id "%s" was updated.' + % (campaign['name'], campaign['id'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py b/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py new file mode 100755 index 00000000..38753fc0 --- /dev/null +++ b/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 updates an expanded text ad. + +To get expanded text ads, run get_expanded_text_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import uuid +from googleads import adwords + + +AD_ID = 'INSERT_AD_ID_HERE' + + +def main(client, ad_id): + # Initialize appropriate service. + ad_service = client.GetService('AdService', version='v201809') + + # Create an expanded text ad using the provided ad ID. + expanded_text_ad = { + 'xsi_type': 'ExpandedTextAd', + 'id': ad_id, + 'headlinePart1': 'Cruise to Pluto #' + str(uuid.uuid4())[:8], + 'headlinePart2': 'Tickets on sale now', + 'description': 'Best space cruise ever.', + 'finalUrls': ['http://www.example.com'], + 'finalMobileUrls': ['http://www.example.com/mobile'] + } + + # Create ad group ad operation. + operations = [{ + 'operator': 'SET', + 'operand': expanded_text_ad + }] + + # Updates the ad on ther server. + result = ad_service.mutate(operations) + updated_ad = result['value'][0] + + print 'Expanded text ad with ID %s was updated.' % updated_ad['id'] + print ('\tHeadline part 1: %s\nHeadline part 2: %s\nDescription: %s\n' + 'Final URL: %s\nFinal mobile URL: %s' % + (updated_ad['headlinePart1'], + updated_ad['headlinePart2'], + updated_ad['description'], + updated_ad['finalUrls'][0], + updated_ad['finalMobileUrls'][0])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_ID) diff --git a/examples/adwords/v201809/basic_operations/update_keyword.py b/examples/adwords/v201809/basic_operations/update_keyword.py new file mode 100755 index 00000000..fa956ea4 --- /dev/null +++ b/examples/adwords/v201809/basic_operations/update_keyword.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 updates the bid of a keyword. + +To add a keyword, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201809') + + # Construct operations and update bids. + + operations = [{ + 'operator': 'SET', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'id': criterion_id, + }, + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': '1000000' + } + } + ] + } + } + }] + ad_group_criteria = ad_group_criterion_service.mutate(operations) + + # Display results. + if 'value' in ad_group_criteria: + for criterion in ad_group_criteria['value']: + if criterion['criterion']['Criterion.Type'] == 'Keyword': + print ('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) + for bid in criterion['biddingStrategyConfiguration']['bids']: + print '\tType: "%s", value: %s' % (bid['Bids.Type'], + bid['bid']['microAmount']) + else: + print 'No ad group criteria were updated.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201809/campaign_management/__init__.py b/examples/adwords/v201809/campaign_management/__init__.py new file mode 100644 index 00000000..afa503f3 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Campaign management examples.""" diff --git a/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py new file mode 100755 index 00000000..31cfdf32 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a campaign group and sets a performance target for it. + +To get campaigns, run get_campaigns.py. To download reports, run +download_criteria_report_with_awql.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import datetime +import uuid +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id1, campaign_id2): + campaign_group_id = _CreateCampaignGroup(client) + _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) + _CreatePerformanceTarget(client, campaign_group_id) + print 'Campaign group and its performance target were setup successfully.' + + +def _CreateCampaignGroup(client): + """Create a campaign group. + + Args: + client: an AdWordsClient instance. + + Returns: + The integer ID of the created campaign group. + """ + # Get the CampaignGroupService. + campaign_group_service = client.GetService('CampaignGroupService', + version='v201809') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the campaign group. + 'operand': { + 'name': 'Mars campaign group #%d' % uuid.uuid4() + } + }] + + campaign_group = campaign_group_service.mutate(operations)['value'][0] + campaign_group_id = campaign_group['id'] + + # Display the results. + print 'Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name']) + + return campaign_group_id + + +def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): + """Adds multiple campaigns to a campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + campaign_ids: a list of integer IDs for campaigns. + """ + # Get the CampaignService. + campaign_service = client.GetService('CampaignService', version='v201809') + + # Create the operations. + operations = [{ + 'operator': 'SET', + 'operand': { + 'id': campaign_id, + 'campaignGroupId': campaign_group_id + } + } for campaign_id in campaign_ids] + + campaign_service.mutate(operations) + + # Display the results. + print ('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + + +def _CreatePerformanceTarget(client, campaign_group_id): + """Creates a performance target for the campaign group. + + Args: + client: an AdWordsClient instance. + campaign_group_id: an integer ID for the campaign group. + """ + # Get the CampaignGroupPerformanceTargetService. + cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', + version='v201809') + + # Create the operation. + operations = [{ + 'operator': 'ADD', + # Create the performance target. + 'operand': { + 'campaignGroupId': campaign_group_id, + 'performanceTarget': { + # Keep the CPC for the campaigns < $3. + 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', + 'efficiencyTargetValue': 3000000, + # Keep the maximum spend under $50. + 'spendTargetType': 'MAXIMUM', + 'spendTarget': { + 'microAmount': 500000000 + }, + # Aim for at least 3000 clicks. + 'volumeGoalType': 'MAXIMIZE_CLICKS', + 'volumeTargetValue': 3000, + # Start the performance target today, and run it for the next 90 + # days. + 'startDate': datetime.datetime.now().strftime('%Y%m%d'), + 'endDate': (datetime.datetime.now() + + datetime.timedelta(90)).strftime('%Y%m%d') + } + } + }] + + cgpt = cgpt_service.mutate(operations)['value'][0] + + # Display the results. + print ('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201809/campaign_management/add_campaign_labels.py b/examples/adwords/v201809/campaign_management/add_campaign_labels.py new file mode 100755 index 00000000..0ac06b90 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/add_campaign_labels.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a label to multiple campaigns. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' +CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, campaign_id1, campaign_id2, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201809') + + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id1, + 'labelId': label_id, + } + }, + { + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id2, + 'labelId': label_id, + } + } + ] + + result = campaign_service.mutateLabel(operations) + + # Display results. + for label in result['value']: + print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' + % (label['campaignId'], label['labelId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py new file mode 100755 index 00000000..cb8602be --- /dev/null +++ b/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. + +The complete Campaign created by this example also includes AdGroups and +KeyWords. + +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +NUMBER_OF_CAMPAIGNS_TO_ADD = 2 +NUMBER_OF_ADGROUPS_TO_ADD = 2 +NUMBER_OF_KEYWORDS_TO_ADD = 5 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201809') + + # Create a BatchJob. + batch_job = AddBatchJob(client) + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Generate operations to upload. + budget_operations = BuildBudgetOperations(batch_job_helper) + campaign_operations = BuildCampaignOperations( + batch_job_helper, budget_operations, number_of_campaigns) + campaign_criterion_operations = BuildCampaignCriterionOperations( + campaign_operations) + adgroup_operations = BuildAdGroupOperations( + batch_job_helper, campaign_operations, number_of_adgroups) + adgroup_criterion_operations = BuildAdGroupCriterionOperations( + adgroup_operations, number_of_keywords) + adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) + + # Upload operations. + batch_job_helper.UploadOperations( + upload_url, budget_operations, campaign_operations, + campaign_criterion_operations, adgroup_operations, + adgroup_criterion_operations, adgroup_ad_operations) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201809') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupAdOperations(adgroup_operations): + """Builds the operations adding an ExpandedTextAd to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + + Returns: + a list containing the operations that will create a new ExpandedTextAd for + each of the provided AdGroups. + """ + adgroup_ad_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupAdOperation', + 'operand': { + 'adGroupId': adgroup_operation['operand']['id'], + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com/1'] + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations] + + return adgroup_ad_operations + + +def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_operations: a list containing the operations that will add AdGroups. + number_of_keywords: an int defining the number of Keywords to be created. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + # Make 50% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for adgroup_operation in adgroup_operations + for i in range(number_of_keywords)] + + return criterion_operations + + +def BuildAdGroupOperations(batch_job_helper, + campaign_operations, number_of_adgroups=1): + """Builds the operations adding desired number of AdGroups to given Campaigns. + + Note: When the AdGroups are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + campaign_operations: a list containing the operations that will add + Campaigns. + number_of_adgroups: an int defining the number of AdGroups to be created per + Campaign. + + Returns: + a list containing the operations that will add the desired number of + AdGroups to each of the provided Campaigns. + """ + adgroup_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'AdGroupOperation', + 'operand': { + 'campaignId': campaign_operation['operand']['id'], + 'id': batch_job_helper.GetId(), + 'name': 'Batch Ad Group #%s' % uuid.uuid4(), + 'biddingStrategyConfiguration': { + 'bids': [ + { + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 10000000 + } + } + ] + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations + for _ in range(number_of_adgroups)] + + return adgroup_operations + + +def BuildBudgetOperations(batch_job_helper): + """Builds the operations needed to create a new Budget. + + Note: When the Budget is created, it will have a different Id than the one + generated here as a temporary Id. This is just used to identify it in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + + Returns: + a list containing the operation that will create a new Budget. + """ + # A list of operations creating a Budget. + budget_operations = [{ + # The xsi_type of the operation can usually be guessed by the API because + # a given service only handles one type of operation. However, batch jobs + # process operations of different types, so the xsi_type must always be + # explicitly defined for these operations. + 'xsi_type': 'BudgetOperation', + 'operand': { + 'name': 'Batch budget #%s' % uuid.uuid4(), + # This is a temporary Id used by the BatchJobService to identify the + # Budget for operations that require a budgetId. + 'budgetId': batch_job_helper.GetId(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD' + }, + 'operator': 'ADD' + }] + + return budget_operations + + +def BuildCampaignCriterionOperations(campaign_operations): + """Builds the operations needed to create Negative Campaign Criterion. + + Args: + campaign_operations: a list containing the operations that will add + Campaigns. + + Returns: + a list containing the operations that will create a new Negative Campaign + Criterion associated with each provided Campaign. + """ + criterion_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignCriterionOperation', + 'operand': { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_operation['operand']['id'], + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus' + } + }, + 'operator': 'ADD' + } + for campaign_operation in campaign_operations] + + return criterion_operations + + +def BuildCampaignOperations(batch_job_helper, + budget_operations, number_of_campaigns=1): + """Builds the operations needed to create a new Campaign. + + Note: When the Campaigns are created, they will have a different Id than those + generated here as a temporary Id. This is just used to identify them in the + BatchJobService. + + Args: + batch_job_helper: a BatchJobHelper instance. + budget_operations: a list containing the operation that will add the budget + used by these Campaigns. + number_of_campaigns: an int number defining the number of campaigns to be + created. + + Returns: + a list containing the operations to create the desired number of Campaigns. + """ + # Grab the temporary budgetId to associate with the new Campaigns. + budget_id = budget_operations[0]['operand']['budgetId'] + + campaign_operations = [ + { + # The xsi_type of the operation can usually be guessed by the API + # because a given service only handles one type of operation. + # However, batch jobs process operations of different types, so + # the xsi_type must always be explicitly defined for these + # operations. + 'xsi_type': 'CampaignOperation', + 'operand': { + 'name': 'Batch Campaign #%s' % uuid.uuid4(), + # Recommendation: Set the campaign to PAUSED when creating it to + # stop the ads from immediately serving. Set to ENABLED once + # you've added targeting and the ads are ready to serve. + 'status': 'PAUSED', + # This is a temporary Id used by the BatchJobService to identify + # the Campaigns for operations that require a campaignId. + 'id': batch_job_helper.GetId(), + 'advertisingChannelType': 'SEARCH', + # Note that only the budgetId is required + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + } + }, + 'operator': 'ADD' + } + for _ in range(number_of_campaigns)] + + return campaign_operations + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201809') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt = 0 + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + raise Exception('Batch Job not finished downloading. Try checking later.') + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, + NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201809/campaign_management/add_draft.py b/examples/adwords/v201809/campaign_management/add_draft.py new file mode 100755 index 00000000..0be2a990 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/add_draft.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a draft and accesses its associated draft campaign. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' + + +def main(client, base_campaign_id): + draft_service = client.GetService('DraftService', version='v201809') + + draft = { + 'baseCampaignId': base_campaign_id, + 'draftName': 'Test Draft #%s' % uuid.uuid4() + } + + draft_operation = {'operator': 'ADD', 'operand': draft} + draft = draft_service.mutate([draft_operation])['value'][0] + draft_campaign_id = draft['draftCampaignId'] + + # Once the draft is created, you can modify the draft campaign as if it were a + # real campaign. For example, you may add criteria, adjust bids, or even + # include additional ads. Adding a criteria is shown here. + campaign_criterion_service = client.GetService('CampaignCriterionService', + version='v201809') + + criterion = { + 'xsi_type': 'Language', + 'id': 1003 # Spanish + } + + criterion_operation = { + # Make sure to use the draftCampaignId when modifying the virtual draft + # campaign. + 'operator': 'ADD', + 'operand': { + 'campaignId': draft_campaign_id, + 'criterion': criterion + } + } + + criterion = campaign_criterion_service.mutate([criterion_operation])[ + 'value'][0] + + print ('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py new file mode 100755 index 00000000..2c5603a0 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to incrementally upload keywords. + +Uses the BatchJobService and BatchJobHelper to incrementally upload operations. +""" + +import random +import time +import urllib2 +import uuid + +from googleads import adwords + + +ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' +KEYWORD_COUNT = 100 +MAX_POLL_ATTEMPTS = 5 +PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') + + +def main(client, adgroup_id): + # Initialize BatchJobHelper. + batch_job_helper = client.GetBatchJobHelper(version='v201809') + # Create a BatchJob. + batch_job = AddBatchJob(client) + + # Retrieve the URL used to upload the BatchJob operations. + upload_url = batch_job['uploadUrl']['url'] + batch_job_id = batch_job['id'] + print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url) + + # Initialize IncrementalUploadHelper. + incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) + + # Generate and upload first set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload second set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations]) + # Generate and upload third and final set of operations. + adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) + incremental_uploader.UploadOperations( + [adgroup_criterion_operations], is_last=True) + + # Download and display results. + download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) + response = urllib2.urlopen(download_url).read() + PrintResponse(batch_job_helper, response) + + +def AddBatchJob(client): + """Add a new BatchJob to upload operations to. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + + Returns: + The new BatchJob created by the request. + """ + # Initialize appropriate service. + batch_job_service = client.GetService('BatchJobService', version='v201809') + # Create a BatchJob. + batch_job_operations = [{ + 'operand': {}, + 'operator': 'ADD' + }] + return batch_job_service.mutate(batch_job_operations)['value'][0] + + +def BuildAdGroupCriterionOperations(adgroup_id): + """Builds the operations adding a Keyword Criterion to each AdGroup. + + Args: + adgroup_id: an integer identifying an AdGroup to associate the keywords + with. + + Returns: + a list containing the operations that will create a new Keyword Criterion + associated with each provided AdGroup. + """ + criterion_operations = [ + { + # You must specify the xsi_type of operations run by the + # BatchJobService. + 'xsi_type': 'AdGroupCriterionOperation', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': adgroup_id, + 'criterion': { + 'xsi_type': 'Keyword', + # Make 10% of keywords invalid to demonstrate error handling. + 'text': 'mars%s%s' % (uuid.uuid4(), + '!!!' if i % 10 == 0 else ''), + 'matchType': 'BROAD' + } + }, + 'operator': 'ADD' + } + for i in range(KEYWORD_COUNT)] + + return criterion_operations + + +def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): + """Cancels the given BatchJob. + + Args: + client: an instantiated AdWordsClient used to cancel the BatchJob. + batch_job: a BatchJob to be canceled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has been canceled. + """ + batch_job_service = client.GetService('BatchJobService', 'v201809') + batch_job['status'] = 'CANCELING' + + operation = { + 'operator': 'SET', + 'operand': batch_job + } + + batch_job_service.mutate([operation]) + + # Verify that the Batch Job cancels. + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] != 'CANCELED'): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print ('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job['id']) + poll_attempt += 1 + + if batch_job['status'] == 'CANCELED': + print ('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) + else: + print ('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) + + +def GetBatchJob(client, batch_job_id): + """Retrieves the BatchJob with the given id. + + Args: + client: an instantiated AdWordsClient used to retrieve the BatchJob. + batch_job_id: a long identifying the BatchJob to be retrieved. + Returns: + The BatchJob associated with the given id. + """ + batch_job_service = client.GetService('BatchJobService', 'v201809') + + selector = { + 'fields': ['Id', 'Status', 'DownloadUrl'], + 'predicates': [ + { + 'field': 'Id', + 'operator': 'EQUALS', + 'values': [batch_job_id] + } + ] + } + + return batch_job_service.get(selector)['entries'][0] + + +def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, + max_poll_attempts=MAX_POLL_ATTEMPTS): + """Retrieves the downloadUrl when the BatchJob is complete. + + Args: + client: an instantiated AdWordsClient used to poll the BatchJob. + batch_job_id: a long identifying the BatchJob to be polled. + max_poll_attempts: an int defining the number of times the BatchJob will be + checked to determine whether it has completed. + + Returns: + A str containing the downloadUrl of the completed BatchJob. + + Raises: + Exception: If the BatchJob hasn't finished after the maximum poll attempts + have been made. + """ + batch_job = GetBatchJob(client, batch_job_id) + if batch_job['status'] == 'CANCELED': + raise Exception('Batch Job with ID "%s" was canceled before completing.' + % batch_job_id) + + poll_attempt = 0 + + while (poll_attempt in range(max_poll_attempts) and + batch_job['status'] in PENDING_STATUSES): + sleep_interval = (30 * (2 ** poll_attempt) + + (random.randint(0, 10000) / 1000)) + print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + time.sleep(sleep_interval) + batch_job = GetBatchJob(client, batch_job_id) + poll_attempt += 1 + + if 'downloadUrl' in batch_job: + url = batch_job['downloadUrl']['url'] + print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) + return url + + print ('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + CancelBatchJob(client, batch_job) + + +def PrintResponse(batch_job_helper, response_xml): + """Prints the BatchJobService response. + + Args: + batch_job_helper: a BatchJobHelper instance. + response_xml: a string containing a response from the BatchJobService. + """ + response = batch_job_helper.ParseResponse(response_xml) + + if 'rval' in response['mutateResponse']: + for data in response['mutateResponse']['rval']: + if 'errorList' in data: + print 'Operation %s - FAILURE:' % data['index'] + print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] + print '\ttrigger=%s' % data['errorList']['errors']['trigger'] + print '\terrorString=%s' % data['errorList']['errors']['errorString'] + print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] + print '\treason=%s' % data['errorList']['errors']['reason'] + if 'result' in data: + print 'Operation %s - SUCCESS.' % data['index'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201809/campaign_management/add_trial.py b/examples/adwords/v201809/campaign_management/add_trial.py new file mode 100755 index 00000000..d7588a83 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/add_trial.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a trial and waits for it to complete. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid +from googleads import adwords + + +BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' +DRAFT_ID = 'INSERT_DRAFT_ID_HERE' +MAX_POLL_ATTEMPTS = 6 + + +def main(client, base_campaign_id, draft_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201809') + trial_async_error_service = client.GetService('TrialAsyncErrorService', + version='v201809') + + trial = { + 'draftId': draft_id, + 'baseCampaignId': base_campaign_id, + 'name': 'Test Trial #%d' % uuid.uuid4(), + 'trafficSplitPercent': 50, + 'trafficSplitType': 'RANDOM_QUERY' + } + + trial_operation = {'operator': 'ADD', 'operand': trial} + trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] + selector = { + 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], + 'predicates': [{ + 'field': 'Id', + 'operator': 'IN', + 'values': [trial_id] + }] + } + + # Since creating a trial is asynchronous, we have to poll it to wait for it to + # finish. + poll_attempts = 0 + is_pending = True + trial = None + + while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: + trial = trial_service.get(selector)['entries'][0] + print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + poll_attempts += 1 + is_pending = trial['status'] == 'CREATING' + + if is_pending: + sleep_seconds = 30 * (2 ** poll_attempts) + print 'Sleeping for %d seconds.' % sleep_seconds + time.sleep(sleep_seconds) + + if trial['status'] == 'ACTIVE': + # The trial creation was successful. + print 'Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId']) + elif trial['status'] == 'CREATION_FAILED': + # The trial creation failed, and errors can be fetched from the + # TrialAsyncErrorService. + selector = { + 'fields': ['TrialId', 'AsyncError'], + 'predicates': [{ + 'field': 'TrialId', + 'operator': 'IN', + 'values': [trial['id']] + }] + } + + errors = trial_async_error_service.get(selector)['entries'] + + if not errors: + print 'Could not retrieve errors for trial %d' % trial['id'] + else: + print 'Could not create trial due to the following errors:' + for error in errors: + print 'Error: %s' % error['asyncError'] + else: + # Most likely, the trial is still being created. You can continue polling, + # but we have limited the number of attempts in the example. + print ('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py new file mode 100755 index 00000000..5a0acf3d --- /dev/null +++ b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Construct selector and get all ads for a given ad group. + offset = 0 + selector = { + 'fields': ['Id', 'PolicySummary'], + 'predicates': [ + { + 'field': 'AdGroupId', + 'operator': 'EQUALS', + 'values': [ad_group_id] + }, + { + 'field': 'CombinedApprovalStatus', + 'operator': 'EQUALS', + 'values': 'DISAPPROVED' + } + ], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + more_pages = True + disapproved_count = 0 + + # Display results. + while more_pages: + page = ad_group_ad_service.get(selector) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName'], + policy_topic_entry['policyTopicHelpCenterUrl']) + # Display the attributes and values that triggered the policy topic. + policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] + if policy_topic_evidences: + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py new file mode 100755 index 00000000..a8fb9c6c --- /dev/null +++ b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 disapproved ads for a given campaign with AWQL. + +To add an ad, run add_ads.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', + version='v201809') + + # Construct query and get all ads for a given campaign. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'PolicySummary') + .Where('AdGroupId').EqualTo(ad_group_id) + .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') + .OrderBy('Id') + .Limit(0, PAGE_SIZE) + .Build()) + disapproved_count = 0 + + # Display results. + while True: + page = ad_group_ad_service.query(query) + + if 'entries' in page: + for ad in page['entries']: + disapproved_count += 1 + policy_summary = ad['policySummary'] + + print ('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) + # Display the policy topic entries related to the ad disapproval. + for policy_topic_entry in policy_summary['policyTopicEntries']: + print ' topic ID: %s, topic name: %s' % ( + policy_topic_entry['policyTopicId'], + policy_topic_entry['policyTopicName']) + # Display the attributes and values that triggered the policy topic. + if ('policyTopicEvidences' in policy_topic_entry + and policy_topic_entry['policyTopicEvidences']): + for evidence in policy_topic_entry['policyTopicEvidences']: + print (' evidence type: %s' + % evidence['policyTopicEvidenceType']) + evidence_text_list = evidence['evidenceTextList'] + if evidence_text_list: + for index, evidence_text in enumerate(evidence_text_list): + print ' evidence text[%d]: %s' % (index, evidence_text) + + if not query.HasNext(page): + break + query.NextPage() + + print '%d disapproved ads were found.' % disapproved_count + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py new file mode 100755 index 00000000..d509ee24 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 campaigns with a specific label. + +To add a label to campaigns, run add_campaign_labels.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +LABEL_ID = 'INSERT_LABEL_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, label_id): + # Initialize appropriate service. + campaign_service = client.GetService('CampaignService', version='v201809') + + offset = 0 + selector = { + 'fields': ['Id', 'Name', 'Labels'], + # Labels filtering is performed by ID. You can use CONTAINS_ANY to select + # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns + # with all of the label IDs, or CONTAINS_NONE to select campaigns with + # none of the label IDs. + 'ordering': { + 'field': 'Name', + 'sortOrder': 'ASCENDING' + }, + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + }, + 'predicates': { + 'field': 'Labels', + 'operator': 'CONTAINS_ANY', + 'values': [label_id] + } + } + + more_pages = True + while more_pages: + page = campaign_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign in page['entries']: + print ('Campaign found with Id "%s", name "%s", and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) + else: + print 'No campaigns were found.' + + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201809/campaign_management/graduate_trial.py b/examples/adwords/v201809/campaign_management/graduate_trial.py new file mode 100755 index 00000000..0491ddd4 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/graduate_trial.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Illustrates how to graduate a trial. + +See the Campaign Drafts and Experiments guide for more information: +https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +TRIAL_ID = 'INSERT_TRIAL_ID_HERE' + + +def main(client, trial_id): + # Initialize appropriate services. + trial_service = client.GetService('TrialService', version='v201809') + budget_service = client.GetService('BudgetService', version='v201809') + + # To graduate a trial, you must specify a different budget from the base + # campaign. The base campaign (in order to have had a trial based on it) must + # have a non-shared budget, so it cannot be shared with the new independent + # campaign created by graduation. + budget = { + 'name': 'Budget #%d' % uuid.uuid4(), + 'amount': {'microAmount': 50000000}, + 'deliveryMethod': 'STANDARD' + } + + budget_operation = {'operator': 'ADD', 'operand': budget} + # Add budget + budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] + + trial = { + 'id': trial_id, + 'budgetId': budget_id, + 'status': 'GRADUATED' + } + + trial_operation = {'operator': 'SET', 'operand': trial} + + # Update the trial. + trial = trial_service.mutate([trial_operation])['value'][0] + + # Graduation is a synchronous operation, so the campaign is already ready. If + # you promote instead, make sure to see the polling scheme demonstrated in + # add_trial.py to wait for the asynchronous operation to finish. + print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201809/campaign_management/set_ad_parameters.py b/examples/adwords/v201809/campaign_management/set_ad_parameters.py new file mode 100755 index 00000000..2f2ffff1 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/set_ad_parameters.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2016 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 adds a text ad with ad parameters. + +To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + ad_param_service = client.GetService('AdParamService', version='v201809') + + # Construct operations for adding text ad object and add to an ad group. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'TextAd', + 'finalUrls': ['http://www.example.com'], + 'displayUrl': 'example.com', + 'description1': 'Low-gravity fun for {param1:cheap}.', + 'description2': 'Only {param2:a few} seats left!', + 'headline': 'Luxury Mars Cruises' + }, + 'status': 'ENABLED' + } + }] + ads = ad_group_ad_service.mutate(operations)['value'] + + # Display results. + for ad in ads: + print ('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) + + # Construct operations for setting ad parameters. + operations = [ + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': u'£100', + 'paramIndex': '1' + } + }, + { + 'operator': 'SET', + 'operand': { + 'adGroupId': ad_group_id, + 'criterionId': criterion_id, + 'insertionText': '50', + 'paramIndex': '2' + } + } + ] + ad_params = ad_param_service.mutate(operations) + + # Display results. + for ad_param in ad_params: + print ('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' + % (ad_param['insertionText'], ad_param['criterionId'], + ad_param['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py new file mode 100755 index 00000000..e25e9ed7 --- /dev/null +++ b/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +BID_MODIFIER = '1.5' + + +def main(client, campaign_id, bid_modifier): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201809') + + # Create mobile platform.The ID can be found in the documentation. + # https://developers.google.com/adwords/api/docs/appendix/platforms + mobile = { + 'xsi_type': 'Platform', + 'id': '30001' + } + + # Create campaign criterion with modified bid. + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': mobile, + 'bidModifier': bid_modifier + } + + # Create operations. + operations = [ + { + 'operator': 'SET', + 'operand': campaign_criterion + } + ] + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['bidModifier'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201809/campaign_management/validate_text_ad.py b/examples/adwords/v201809/campaign_management/validate_text_ad.py new file mode 100755 index 00000000..9ba36eaf --- /dev/null +++ b/examples/adwords/v201809/campaign_management/validate_text_ad.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 shows how to use validateOnly SOAP header. + +No objects will be created, but exceptions will still be returned. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords +from googleads import errors + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service with validate only flag enabled. + client.validate_only = True + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Construct operations to add an expanded text ad. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for everyone!', + 'finalUrls': ['http://www.example.com'] + } + } + }] + ad_group_ad_service.mutate(operations) + # No error means the request is valid. + + # Now let's check an invalid ad using a very long line to trigger an error. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdGroupAd', + 'adGroupId': ad_group_id, + 'ad': { + 'xsi_type': 'ExpandedTextAd', + 'headlinePart1': 'Luxury Cruise to Mars', + 'headlinePart2': 'Visit the Red Planet in style.', + 'description': 'Low-gravity fun for all astronauts in orbit', + 'finalUrls': ['http://www.example.com'], + } + } + }] + try: + ad_group_ad_service.mutate(operations) + except errors.GoogleAdsServerFault, e: + print 'Validation correctly failed with "%s".' % str(e) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/error_handling/__init__.py b/examples/adwords/v201809/error_handling/__init__.py new file mode 100644 index 00000000..7b767e05 --- /dev/null +++ b/examples/adwords/v201809/error_handling/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Error handling examples.""" diff --git a/examples/adwords/v201809/error_handling/handle_partial_failures.py b/examples/adwords/v201809/error_handling/handle_partial_failures.py new file mode 100755 index 00000000..03b8468a --- /dev/null +++ b/examples/adwords/v201809/error_handling/handle_partial_failures.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 demonstrates how to handle partial failures. + +To get ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Enable partial failure. + client.partial_failure = True + + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201809') + + # Construct keyword ad group criteria objects. + keywords = [ + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'mars cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'inv\@lid cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'venus cruise' + } + }, + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': r'b\(a\)d keyword cruise' + } + } + ] + + # Construct operations and add ad group criteria. + operations = [] + for keyword in keywords: + operations.append( + { + 'operator': 'ADD', + 'operand': keyword + }) + result = ad_group_criterion_service.mutate(operations) + + # Display results. + for criterion in result['value']: + if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': + print ('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], + criterion['criterion']['text'], + criterion['criterion']['matchType'])) + + for error in result['partialFailureErrors']: + field_path_elements = error['fieldPathElements'] + first_field_path_element = None + + if field_path_elements: + first_field_path_element = field_path_elements[0] + + if (first_field_path_element and + first_field_path_element['field'] == 'operations' and + 'index' in first_field_path_element): + operation_index = first_field_path_element['index'] + + adgroup_criterion = operations[operation_index]['operand'] + + print('Ad group criterion with ad group ID %s and keyword "%s" triggered ' + 'a failure for the following reason: %s.' + % (adgroup_criterion['adGroupId'], + adgroup_criterion['criterion']['text'], + error['errorString'])) + else: + print ('A failure has occurred for the following reasons: %s\n' + % error['errorString']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/extensions/__init__.py b/examples/adwords/v201809/extensions/__init__.py new file mode 100644 index 00000000..594717b1 --- /dev/null +++ b/examples/adwords/v201809/extensions/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Extension examples.""" diff --git a/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py new file mode 100755 index 00000000..3d9e944c --- /dev/null +++ b/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a feed that syncs feed items from a Google My Business (GMB) account. + +This example associates the feed with a customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import time +import uuid + +from googleads import adwords +from googleads import errors + +GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' + +# If the gmb_email_address above is for a GMB manager instead of +# the GMB account owner, then set business_account_identifier to the +# +Page ID of a location for which the manager has access. See the +# location extensions guide at +# https://developers.google.com/adwords/api/docs/guides/feed-services-locations +# for details. +BUSINESS_ACCOUNT_IDENTIFIER = None + +# The placeholder type for location extensions. +# See the Placeholder reference page for a list of all the placeholder types +# and fields: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_LOCATION = 7 + +# The maximum number of CustomerFeed ADD operation attempts to make before +# throwing an exception. +MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 + + +def main(client, gmb_email_address, gmb_access_token, + business_account_identifier=None): + # Create a feed that will sync to the Google Places account specified by + # gmb_email_address. Do not add FeedAttributes to this object, + # as AdWords will add them automatically because this will be a + # system generated feed. + feed = { + 'name': 'GMB feed #%s' % uuid.uuid4(), + 'systemFeedGenerationData': { + 'xsi_type': 'PlacesLocationFeedData', + 'oAuthInfo': { + 'httpMethod': 'GET', + 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', + 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token + }, + 'emailAddress': gmb_email_address, + }, + # Since this feed's feed items will be managed by AdWords, you must set + # its origin to ADWORDS. + 'origin': 'ADWORDS' + } + + # Only include the business_account_identifier if it's specified. + if business_account_identifier: + feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( + business_account_identifier + ) + + # Create an operation to add the feed. + gmb_operations = [{ + 'operator': 'ADD', + 'operand': feed + }] + + gmb_response = client.GetService('FeedService', version='v201809').mutate( + gmb_operations) + added_feed = gmb_response['value'][0] + print 'Added GMB feed with ID: %d\n' % added_feed['id'] + + # Add a CustomerFeed that associates the feed with this customer for the + # LOCATION placeholder type. + customer_feed = { + 'feedId': added_feed['id'], + 'placeholderTypes': [PLACEHOLDER_LOCATION], + # Create a matching function that will always evaluate to True. + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': { + 'xsi_type': 'ConstantOperand', + 'type': 'BOOLEAN', + 'booleanValue': True + } + } + } + + customer_feed_operation = { + 'xsi_type': 'CustomerFeedOperation', + 'operator': 'ADD', + 'operand': customer_feed + } + + customer_feed_service = client.GetService( + 'CustomerFeedService', version='v201809') + added_customer_feed = None + + i = 0 + while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: + try: + added_customer_feed = customer_feed_service.mutate([ + customer_feed_operation])['value'][0] + except errors.GoogleAdsServerFault: + # Wait using exponential backoff policy + sleep_seconds = 2 ** i + print ('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + + time.sleep(sleep_seconds) + i += 1 + + if added_customer_feed is None: + raise errors.GoogleAdsError( + 'Could not create the CustomerFeed after %s attempts. Please retry the ' + 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) + + print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your + # AdWords API refresh token, leave the assignment below unchanged. Otherwise, + # to obtain an access token for your GMB account, you can run the + # generate_refresh_token.py example after manually replacing the scope with + # "https://www.google.com/local/add". + GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token + + main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, + BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201809/extensions/add_prices.py b/examples/adwords/v201809/extensions/add_prices.py new file mode 100755 index 00000000..e852819b --- /dev/null +++ b/examples/adwords/v201809/extensions/add_prices.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a price extension and associates it with an account. + +Campaign targeting is also set usin the specified campaign ID. To get campaigns, +run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +from googleads import errors + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +MICROS_PER_DOLLAR = 1000000 + + +def main(client, campaign_id): + # Initialize appropriate service. + customer_extension_setting_service = client.GetService( + 'CustomerExtensionSettingService', 'v201809') + + # To create a price extension, at least three table rows are needed. + table_rows = [ + CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', + 'https://www.example.com/scrubs', + 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', + final_mobile_url='http://m.example.com/scrubs'), + CreatePriceTableRow('Hair Cuts', 'Once a month', + 'https://www.example.com/haircuts', + 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url='http://m.example.com/haircuts'), + CreatePriceTableRow('Skin Care Package', 'Four times a month', + 'https://www.examples.com/skincarepackage', + 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', + final_mobile_url=( + 'http://m.example.com/skincarepackage')) + ] + + # Create the price extension feed item. + customer_extension_setting = { + 'extensionType': 'PRICE', + 'extensionSetting': { + 'extensions': [{ + 'priceExtensionType': 'SERVICES', + 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', + 'language': 'en', + 'campaignTargeting': { + 'TargetingCampaignId': campaign_id + }, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': 'SATURDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 22, + 'endMinute': 'ZERO' + }, + { + 'dayOfWeek': 'SUNDAY', + 'startHour': 10, + 'startMinute': 'ZERO', + 'endHour': 18, + 'endMinute': 'ZERO' + } + ] + }, + 'tableRows': table_rows, + # Price qualifier is optional. + 'priceQualifier': 'FROM', + 'xsi_type': 'PriceFeedItem' + }] + } + } + + # Create an operation to add the feed. + operations = [{ + 'operator': 'ADD', + 'operand': customer_extension_setting + }] + + # Add the price extension. + response = customer_extension_setting_service.mutate(operations) + + # Print the results. + if 'value' in response: + print ('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +def CreatePriceTableRow(header, description, final_url, price_in_micros, + currency_code, price_unit, final_mobile_url=None): + """Helper function to generate a single row of a price table. + + Args: + header: A str containing the header text of this row. + description: A str description of this row in the price table. + final_url: A str containing the final URL after all cross domain redirects. + price_in_micros: An int indicating the price of the given currency in + micros. + currency_code: A str indicating the currency code being used. + price_unit: A str enum indicating the price unit for this row. + final_mobile_url: A str containing the final mobile URL after all cross + domain redirects. + + Returns: + A dictionary containing the contents of the generated price table row. + """ + table_row = { + 'header': header, + 'description': description, + 'finalUrls': {'urls': [final_url]}, + 'price': { + 'money': { + 'microAmount': price_in_micros, + }, + 'currencyCode': currency_code + }, + 'priceUnit': price_unit, + 'xsi_type': 'PriceTableRow' + } + + if final_mobile_url: + table_row['finalMobileUrls'] = { + 'urls': [final_mobile_url] + } + + return table_row + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/extensions/add_site_links.py b/examples/adwords/v201809/extensions/add_site_links.py new file mode 100755 index 00000000..05f89d0f --- /dev/null +++ b/examples/adwords/v201809/extensions/add_site_links.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from datetime import datetime + +from googleads import adwords +from googleads import errors +from pytz import timezone + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + # Initialize appropriate services. + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', version='v201809') + customer_service = client.GetService('CustomerService', version='v201809') + # Find the matching customer and its time zone. The getCustomers method will + # return a single Customer object corresponding to the configured + # clientCustomerId. + customer = customer_service.getCustomers()[0] + customer_tz = timezone(customer['dateTimeZone']) + time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) + + print ('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) + + # Create the sitelinks + sitelink1 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Store Hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} + } + + # Show the Thanksgiving specials link only from 20 - 27 Nov. + sitelink2 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Thanksgiving Specials', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, + # The time zone of the start and end date/times must match the time zone + # of the customer. + 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, + customer_tz).strftime(time_fmt), + 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, + customer_tz).strftime(time_fmt), + # Target this sitelink for United States only. For valid geolocation + # codes, see: + # https://developers.google.com/adwords/api/docs/appendix/geotargeting + 'geoTargeting': {'id': 2840}, + # Restrict targeting only to people physically within the United States. + # Otherwise, this could also show to people interested in the United + # States, but not physically located there. + 'geoTargetingRestriction': { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + } + + # Show the wifi details primarily for high end mobile users. + sitelink3 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Wifi Available', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, + # See https://developers.google.com/adwords/api/docs/appendix/platforms + # for device criteria IDs. + 'devicePreference': {'devicePreference': '30001'}, + # Target this sitelink only when the ad is triggered by the keyword + # "free wifi." + 'keywordTargeting': { + 'text': 'free wifi', + 'matchType': 'BROAD' + } + } + + # Show the happy hours link only during Mon - Fri 6PM to 9PM. + sitelink4 = { + 'xsi_type': 'SitelinkFeedItem', + 'sitelinkText': 'Happy hours', + 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, + 'scheduling': { + 'feedItemSchedules': [ + { + 'dayOfWeek': day, + 'startHour': '18', + 'startMinute': 'ZERO', + 'endHour': '21', + 'endMinute': 'ZERO' + } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', + 'FRIDAY'] + ] + } + } + + # Create your Campaign Extension Settings. This associates the sitelinks + # to your campaign. + campaign_extension_setting = { + 'campaignId': campaign_id, + 'extensionType': 'SITELINK', + 'extensionSetting': { + 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] + } + } + + operation = { + 'operator': 'ADD', + 'operand': campaign_extension_setting + } + + # Add the extensions. + response = campaign_extension_setting_service.mutate([operation]) + + if 'value' in response: + print ('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) + else: + raise errors.GoogleAdsError('No extension settings were added.') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/extensions/add_site_links_using_feeds.py b/examples/adwords/v201809/extensions/add_site_links_using_feeds.py new file mode 100755 index 00000000..86e70851 --- /dev/null +++ b/examples/adwords/v201809/extensions/add_site_links_using_feeds.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. + +To add sitelinks using the simpler ExtensionSetting services, see: +add_sitelinks.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import re +import uuid +from googleads import adwords +from googleads import errors + +# See the Placeholder reference page for a list of all the placeholder types and +# fields. +# https://developers.google.com/adwords/api/docs/appendix/placeholders.html +PLACEHOLDER_SITELINKS = '1' +PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' +PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' +PLACEHOLDER_FIELD_LINE_2_TEXT = '3' +PLACEHOLDER_FIELD_LINE_3_TEXT = '4' + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Optional: Ad group to restrict targeting to. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def RestrictFeedItemToGeoTarget(client, feed_item, location_id): + """Restrict a feed item to a geo target location. + + Args: + client: An AdWordsClient instance. + feed_item: A FeedItem. + location_id: The Id of the location to restrict to. + """ + # Retrieve the FeedItemTargetService + feed_item_target_service = client.GetService( + 'FeedItemTargetService', version='v201809') + + # Optional: Restrict the first feed item to only serve with ads for the + # specified geo target. + criterion_target = { + 'xsi_type': 'FeedItemCriterionTarget', + 'feedId': feed_item['feedId'], + 'feedItemId': feed_item['feedItemId'], + # These IDs can be found in the documentation or retrieved with the + # LocationCriterionService. + 'criterion': { + 'xsi_type': 'Location', + 'id': location_id + } + } + + operation = {'operator': 'ADD', 'operand': criterion_target} + + response = feed_item_target_service.mutate([operation]) + new_location_target = response['value'][0] + print('Feed item target for feed ID %d and feed item ID %d was created to ' + 'restrict serving to location ID %d.' % + (new_location_target['feedId'], + new_location_target['feedItemId'], + new_location_target['criterion']['id'])) + + +def main(client, campaign_id, ad_group_id=None): + # Initialize appropriate service. + feed_service = client.GetService('FeedService', version='v201809') + feed_item_service = client.GetService('FeedItemService', version='v201809') + feed_item_target_service = client.GetService('FeedItemTargetService', + version='v201809') + feed_mapping_service = client.GetService( + 'FeedMappingService', version='v201809') + campaign_feed_service = client.GetService( + 'CampaignFeedService', version='v201809') + + sitelinks_data = {} + + # Create site links feed first. + site_links_feed = { + 'name': 'Feed For Site Links #%s' % uuid.uuid4(), + 'attributes': [ + {'type': 'STRING', 'name': 'Link Text'}, + {'type': 'URL_LIST', 'name': 'Link Final URLs'}, + {'type': 'STRING', 'name': 'Line 2 Description'}, + {'type': 'STRING', 'name': 'Line 3 Description'} + ] + } + + response = feed_service.mutate([ + {'operator': 'ADD', 'operand': site_links_feed} + ]) + + if 'value' in response: + feed = response['value'][0] + link_text_feed_attribute_id = feed['attributes'][0]['id'] + final_url_feed_attribute_id = feed['attributes'][1]['id'] + line_2_feed_attribute_id = feed['attributes'][2]['id'] + line_3_feed_attribute_id = feed['attributes'][3]['id'] + print ('Feed with name "%s" and ID "%d" was added with' % + (feed['name'], feed['id'])) + print ('\tText attribute ID "%d" and Final URL attribute ID "%d".' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print ('\tLine 2 attribute ID "%d" and Line 3 attribute ID "%d".' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) + sitelinks_data['feedId'] = feed['id'] + sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id + sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id + sitelinks_data['line2FeedId'] = line_2_feed_attribute_id + sitelinks_data['line3FeedId'] = line_3_feed_attribute_id + else: + raise errors.GoogleAdsError('No feeds were added.') + + # Create site links feed items. + items_data = [ + {'text': 'Home', 'finalUrls': 'http://www.example.com', + 'line2': 'Home line 2', 'line3': 'Home line 3'}, + {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', + 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, + {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', + 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, + {'text': 'Support', 'finalUrls': 'http://www.example.com/support', + 'line2': 'Support line 2', 'line3': 'Support line 3'}, + {'text': 'Products', 'finalUrls': 'http://www.example.com/products', + 'line2': 'Products line 2', 'line3': 'Products line 3'}, + {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', + 'line2': 'About line 2', 'line3': 'About line 3', 'locationTarget': True} + ] + + feed_items = [] + for item in items_data: + feed_item = { + 'feedId': sitelinks_data['feedId'], + 'attributeValues': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'stringValue': item['text'] + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'stringValues': [item['finalUrls']] + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'stringValue': item['line2'] + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'stringValue': item['line3'] + } + ], + # Optional: use the 'startTime' and 'endTime' keys to specify the time + # period for the feed to deliver. The example below will make the feed + # start now and stop in one month. + # Make sure you specify the datetime in the customer's time zone. You + # can retrieve this from customer['dateTimeZone']. + # + # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') + # ['endTime']: (datetime.datetime.now() + + # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') + } + + # Optional: Restrict targeting only to people physically within + # the location. + if 'locationTarget' in item: + item['geoTargetingRestriction'] = { + 'geoRestriction': 'LOCATION_OF_PRESENCE' + } + + feed_items.append(feed_item) + + feed_items_operations = [{'operator': 'ADD', 'operand': item} for item + in feed_items] + + response = feed_item_service.mutate(feed_items_operations) + if 'value' in response: + sitelinks_data['feedItemIds'] = [] + for feed_item in response['value']: + print 'Feed item with ID %d was added.' % feed_item['feedItemId'] + sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) + else: + raise errors.GoogleAdsError('No feed items were added.') + + # Target the "aboutUs" sitelink to geographically target California. + # See https://developers.google.com/adwords/api/docs/appendix/geotargeting for + # location criteria for supported locations. + RestrictFeedItemToGeoTarget(client, response['value'][5], 21137) + + # Create site links feed mapping. + + feed_mapping = { + 'placeholderType': PLACEHOLDER_SITELINKS, + 'feedId': sitelinks_data['feedId'], + 'attributeFieldMappings': [ + { + 'feedAttributeId': sitelinks_data['linkTextFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT + }, + { + 'feedAttributeId': sitelinks_data['finalUrlFeedId'], + 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS + }, + { + 'feedAttributeId': sitelinks_data['line2FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT + }, + { + 'feedAttributeId': sitelinks_data['line3FeedId'], + 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT + } + ] + } + + response = feed_mapping_service.mutate([ + {'operator': 'ADD', 'operand': feed_mapping} + ]) + if 'value' in response: + feed_mapping = response['value'][0] + print ('Feed mapping with ID %d and placeholder type %s was saved for feed' + ' with ID %d.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) + else: + raise errors.GoogleAdsError('No feed mappings were added.') + + # Construct a matching function that associates the sitelink feeditems to the + # campaign, and set the device preference to Mobile. For more details, see the + # matching function guide: + # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions + matching_function_string = ( + 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % + re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) + + campaign_feed = { + 'feedId': sitelinks_data['feedId'], + 'campaignId': campaign_id, + 'matchingFunction': {'functionString': matching_function_string}, + # Specifying placeholder types on the CampaignFeed allows the same feed + # to be used for different placeholders in different Campaigns. + 'placeholderTypes': [PLACEHOLDER_SITELINKS] + } + + response = campaign_feed_service.mutate([ + {'operator': 'ADD', 'operand': campaign_feed} + ]) + if 'value' in response: + campaign_feed = response['value'][0] + print ('Campaign with ID %d was associated with feed with ID %d.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) + else: + raise errors.GoogleAdsError('No campaign feeds were added.') + + # Optional: Restrict the first feed item to only serve with ads for the + # specified ad group ID. + if ad_group_id: + feed_item_target = { + 'xsi_type': 'FeedItemAdGroupTarget', + 'feedId': sitelinks_data['feedId'], + 'feedItemId': sitelinks_data['feedItemIds'][0], + 'adGroupId': ad_group_id + } + + operations = [{ + 'operator': 'ADD', + 'operand': feed_item_target + }] + + response = feed_item_target_service.mutate(operations) + + if 'value' in response: + print ('Feed item target for feed ID "%d" and feed item ID "%d" was ' + 'created to restrict serving to ad group ID "%d".' + % (feed_item_target['feedId'], feed_item_target['feedItemId'], + feed_item_target['adGroupId'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + if AD_GROUP_ID == 'INSERT_AD_GROUP_ID_HERE': + main(adwords_client, CAMPAIGN_ID) + else: + main(adwords_client, CAMPAIGN_ID, ad_group_id=AD_GROUP_ID) diff --git a/examples/adwords/v201809/migration/__init__.py b/examples/adwords/v201809/migration/__init__.py new file mode 100644 index 00000000..09996b99 --- /dev/null +++ b/examples/adwords/v201809/migration/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Migration examples.""" diff --git a/examples/adwords/v201809/migration/migrate_to_extension_settings.py b/examples/adwords/v201809/migration/migrate_to_extension_settings.py new file mode 100755 index 00000000..c9c888b9 --- /dev/null +++ b/examples/adwords/v201809/migration/migrate_to_extension_settings.py @@ -0,0 +1,526 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Migrates Feed-based sitelinks at Campaign level to use extension settings. + +To learn more about extensionsettings, see: +https://developers.google.com/adwords/api/docs/guides/extension-settings. + +To learn more about migrating Feed-based extensions to extension settings, see: +https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings + +This code example doesn't migrate scheduling or feeditem-level campaign, +adgroup, keyword, or geo targeting settings. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +# The placeholder type for sitelinks. For the list of all supported placeholder +# types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +PLACEHOLDER_TYPE_SITELINKS = 1 + + +# The placeholder field IDs for sitelinks. For the list of all supported +# placeholder types, see: +# https://developers.google.com/adwords/api/docs/appendix/placeholders +SITE_LINK_FIELDS = { + 'TEXT': 1, + 'URL': 2, + 'LINE2': 3, + 'LINE3': 4, + 'FINAL_URLS': 5, + 'FINAL_MOBILE_URLS': 6, + 'TRACKING_URL_TEMPLATE': 7 +} + +PAGE_SIZE = 500 + + +def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions=None): + """Creates the extension setting for a list of Feed Items. + + Args: + client: an AdWordsClient instance. + feed_items: the list of all Feed Items. + campaign_feed: the original Campaign Feed. + feed_item_ids: the Ids of the feed items for which extension settings should + be created. + platform_restrictions: an optional Platform Restriction for the Feed items. + """ + campaign_extension_setting_service = client.GetService( + 'CampaignExtensionSettingService', 'v201809') + + extension_feed_items = [{ + CreateSitelinkFeedItem(feed_items, feed_item_id) + } for feed_item_id in feed_item_ids] + + extension_setting = { + 'extensions': extension_feed_items + } + + if platform_restrictions: + extension_setting['platformRestrictions'] = platform_restrictions + + campaign_extension_setting = { + 'campaignId': campaign_feed['campaignId'], + 'extensionType': 'SITELINK', + 'extensionSetting': extension_setting + } + + operation = { + 'operand': campaign_extension_setting, + 'operator': 'ADD' + } + + campaign_extension_setting_service.mutate([operation]) + + +def CreateSitelinkFeedItem(feed_items, feed_item_id): + """Creates a Sitelink Feed Item. + + Args: + feed_items: a list of all Feed Items. + feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item + should be created. + + Returns: + The new Sitelink Feed Item. + """ + site_link_from_feed = feed_items[feed_item_id] + site_link_feed_item = { + 'sitelinkText': site_link_from_feed['text'], + 'sitelinkLine2': site_link_from_feed['line2'], + 'sitelinkLine3': site_link_from_feed['line3'], + } + + if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: + site_link_feed_item['sitelinkFinalUrls'] = { + 'urls': site_link_from_feed['finalUrls'] + } + + if 'finalMobileUrls' in site_link_from_feed: + site_link_feed_item['sitelinkFinalMobileUrls'] = { + 'urls': site_link_from_feed['finalMobileUrls'] + } + + site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( + site_link_from_feed['trackingUrlTemplate']) + else: + site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] + + return site_link_feed_item + + +def DeleteCampaignFeed(client, campaign_feed): + """Deletes a campaign feed. + + Args: + client: an AdWordsClient instance. + campaign_feed: the campaign feed to delete. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201809') + + operation = { + 'operand': campaign_feed, + 'operator': 'REMOVE' + } + + campaign_feed_service.mutate([operation]) + + +def DeleteOldFeedItems(client, feed_item_ids, feed): + """Deletes the old feed items for which extension settings have been created. + + Args: + client: an AdWordsClient instance. + feed_item_ids: a list of Feed Item Ids. + feed: the Feed containing the given Feed Item Ids. + """ + if not feed_item_ids: + return + + feed_item_service = client.GetService('FeedItemService', 'v201809') + + operations = [{ + 'operator': 'REMOVE', + 'operand': { + 'feedId': feed['id'], + 'feedItemId': feed_item_id + } + } for feed_item_id in feed_item_ids] + + feed_item_service.mutate(operations) + + +def GetCampaignFeeds(client, feed, placeholder_type): + """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. + + Args: + client: an AdWordsClient instance. + feed: a Campaign Feed. + placeholder_type: the Placeholder Type. + + Returns: + A list of Feed Item Ids. + """ + campaign_feed_service = client.GetService('CampaignFeedService', 'v201809') + + campaign_feeds = [] + more_pages = True + + selector = { + 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderTypes', + 'operator': 'CONTAINS_ANY', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = campaign_feed_service.get(selector) + + if 'entries' in page: + campaign_feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return campaign_feeds + + +def GetFeeds(client): + """Returns a list of all enabled Feeds. + + Args: + client: an AdWordsClient instance. + + Returns: + A list containing all enabled Feeds. + """ + feed_service = client.GetService('FeedService', 'v201809') + + feeds = [] + more_pages = True + + selector = { + 'fields': ['Id', 'Name', 'Attributes'], + 'predicates': [ + { + 'field': 'Origin', + 'operator': 'EQUALS', + 'values': ['USER'] + }, + { + 'field': 'FeedStatus', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_service.get(selector) + + if 'entries' in page: + feeds.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feeds + + +def GetFeedItems(client, feed): + """Returns the Feed Items for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving Feed Items from. + + Returns: + The Feed Items associated with the given Feed. + """ + feed_item_service = client.GetService('FeedItemService', 'v201809') + + feed_items = [] + more_pages = True + + selector = { + 'fields': ['FeedItemId', 'AttributeValues'], + 'predicates': [ + { + 'field': 'Status', + 'operator': 'EQUALS', + 'values': ['ENABLED'] + }, + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_item_service.get(selector) + + if 'entries' in page: + feed_items.extend(page['entries']) + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return feed_items + + +def GetFeedItemIdsForCampaign(campaign_feed): + """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. + + Returns: + A list of Feed Item IDs. + """ + feed_item_ids = set() + + try: + lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] + except KeyError: + lhs_operand = None + + if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == + 'RequestContextOperand'): + request_context_operand = lhs_operand[0] + + if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and + campaign_feed['matchingFunction']['operator'] == 'IN'): + for argument in campaign_feed['matchingFunction']['rhsOperand']: + if argument['xsi_type'] == 'ConstantOperand': + feed_item_ids.add(argument['longValue']) + + return feed_item_ids + + +def GetFeedMapping(client, feed, placeholder_type): + """Gets the Feed Mapping for a given Feed. + + Args: + client: an AdWordsClient instance. + feed: the Feed we are retrieving the Feed Mapping for. + placeholder_type: the Placeholder Type we are looking for. + Returns: + A dictionary containing the Feed Mapping. + """ + feed_mapping_service = client.GetService('FeedMappingService', 'v201809') + + attribute_mappings = {} + more_pages = True + + selector = { + 'fields': ['FeedMappingId', 'AttributeFieldMappings'], + 'predicates': [ + { + 'field': 'FeedId', + 'operator': 'EQUALS', + 'values': [feed['id']] + }, + { + 'field': 'PlaceholderType', + 'operator': 'EQUALS', + 'values': [placeholder_type] + } + ], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + } + } + + while more_pages: + page = feed_mapping_service.get(selector) + + if 'entries' in page: + # Normally, a feed attribute is mapped only to one field. However, you may + # map it to more than one field if needed. + for feed_mapping in page['entries']: + for attribute_mapping in feed_mapping['attributeFieldMappings']: + # Since attribute mappings can have multiple values for each key, + # we use a list to store the values. + if attribute_mapping['feedAttributeId'] in attribute_mappings: + attribute_mappings[attribute_mapping['feedAttributeId']].append( + attribute_mapping['fieldId']) + else: + attribute_mappings[attribute_mapping['feedAttributeId']] = [ + attribute_mapping['fieldId']] + + selector['paging']['startIndex'] += PAGE_SIZE + more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) + + return attribute_mappings + + +def GetPlatformRestrictions(campaign_feed): + """Get the Platform Restrictions for a given Campaign Feed. + + Args: + campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for. + + Returns: + The Platform Restrictions for the given feed. + """ + platform_restrictions = None + + if campaign_feed['matchingFunction']['operator'] == 'AND': + for argument in campaign_feed['matchingFunction']['lhsOperand']: + # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') + if argument['value']['operator'] == 'EQUALS': + request_context_operand = argument['value']['lhsOperand'][0] + + if (request_context_operand and + request_context_operand == 'DEVICE_PLATFORM'): + # This needs to be capitalized for ExtensionSettingPlatform. + platform_restrictions = argument['value']['rhsOperand'][0].upper() + + return platform_restrictions + + +def GetSitelinksFromFeed(client, feed): + """Gets the sitelinks from a feed. + + Args: + client: an AdWordsClient instance. + feed: the feed used to retrieve sitelinks. + + Returns: + A dictionary mapping the feed item ID to SiteLinkFromFeed. + """ + # Retrieve the feed's attribute mapping. + feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + feed_items = {} + + for feed_item in GetFeedItems(client, feed): + site_link_from_feed = {} + + for attribute_value in feed_item['attributeValues']: + if attribute_value['feedAttributeId'] in feed_mappings: + for field_id in feed_mappings[attribute_value['feedAttributeId']]: + if field_id == SITE_LINK_FIELDS['TEXT']: + site_link_from_feed['text'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['URL']: + site_link_from_feed['url'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: + site_link_from_feed['finalUrls'] = attribute_value['stringValues'] + elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: + site_link_from_feed['finalMobileUrls'] = attribute_value[ + 'stringValues'] + elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: + site_link_from_feed['trackingUrlTemplate'] = attribute_value[ + 'stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE2']: + site_link_from_feed['line2'] = attribute_value['stringValue'] + elif field_id == SITE_LINK_FIELDS['LINE3']: + site_link_from_feed['line3'] = attribute_value['stringValue'] + else: + print 'No applicable Site Link Field found for Id: %s' % field_id + + feed_items[feed_item['feedItemId']] = site_link_from_feed + + return feed_items + + +def main(client): + # Get all of the feeds for the current user. + feeds = GetFeeds(client) + + for feed in feeds: + # Retrieve all the sitelinks from the current feed. + feed_items = GetSitelinksFromFeed(client, feed) + + # Get all the instances where a sitelink from this feed has been added to a + # campaign. + campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) + + all_feed_items_to_delete = [] + for campaign_feed in campaign_feeds: + # Retrieve the sitelinks that have been associated with this Campaign. + feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) + + if feed_item_ids == 0: + print ('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + continue + + platform_restrictions = GetPlatformRestrictions(campaign_feed) + + # Delete the campaign feed that associates the sitelinks from the feed to + # the Campaign. + DeleteCampaignFeed(client, campaign_feed) + + # Create extension settings instead of sitelinks. + CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, + platform_restrictions) + + # Mark the sitelinks from the feed for deletion. + all_feed_items_to_delete.extend(feed_item_ids) + + # Delete all the sitelinks from the feed. + DeleteOldFeedItems(client, all_feed_items_to_delete, feed) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/misc/__init__.py b/examples/adwords/v201809/misc/__init__.py new file mode 100644 index 00000000..1c53bcd3 --- /dev/null +++ b/examples/adwords/v201809/misc/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Miscellaneous examples.""" diff --git a/examples/adwords/v201809/misc/get_all_image_assets.py b/examples/adwords/v201809/misc/get_all_image_assets.py new file mode 100755 index 00000000..d10694a2 --- /dev/null +++ b/examples/adwords/v201809/misc/get_all_image_assets.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 image assets. + +To upload an image asset, run upload_image_asset.py + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + asset_service = client.GetService('AssetService', version='v201809') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['AssetName', 'AssetStatus', 'ImageFileSize', 'ImageWidth', + 'ImageHeight', 'ImageFullSizeUrl'], + 'predicates': [{ + 'field': 'AssetSubtype', + 'operator': 'IN', + 'values': ['IMAGE'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = asset_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + print ('Image asset with id %s, name "%s", and status %s was found.\n' + '\tSize is %sx%s and asset URL is %s.' % + (image['assetId'], image['assetName'], image['assetStatus'], + image['fullSizeInfo']['imageWidth'], + image['fullSizeInfo']['imageHeight'], + image['fullSizeInfo']['imageUrl'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/misc/get_all_images_and_videos.py b/examples/adwords/v201809/misc/get_all_images_and_videos.py new file mode 100755 index 00000000..3b60d6ed --- /dev/null +++ b/examples/adwords/v201809/misc/get_all_images_and_videos.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 images and videos. + +To upload an image, run upload_image.py. To upload video, see: +http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201809') + + # Construct selector and get all images. + offset = 0 + selector = { + 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], + 'predicates': [{ + 'field': 'Type', + 'operator': 'IN', + 'values': ['IMAGE', 'VIDEO'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = media_service.get(selector) + + # Display results. + if 'entries' in page: + for image in page['entries']: + try: + dimensions = dict([(entry['key'], entry['value']) + for entry in image['dimensions']]) + except AttributeError: + dimensions = {'FULL': {'height': 0, 'width': 0}} + if image['type'] == 'IMAGE': + print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) + elif image['type'] == 'VIDEO': + print ('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) + else: + print 'No images/videos were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/misc/upload_image.py b/examples/adwords/v201809/misc/upload_image.py new file mode 100755 index 00000000..72f97c7e --- /dev/null +++ b/examples/adwords/v201809/misc/upload_image.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an image. + +To get images, run get_all_images.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' + + +def main(client, image_filename): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201809') + + with open(image_filename, 'rb') as image_handle: + image_data = image_handle.read().decode('utf-8') + + # Construct media and upload image. + media = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + media = media_service.upload(media)[0] + + # Display results. + if media: + dimensions = dict([(entry['key'], entry['value']) + for entry in media['dimensions']]) + print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201809/misc/upload_image_asset.py b/examples/adwords/v201809/misc/upload_image_asset.py new file mode 100755 index 00000000..70a89954 --- /dev/null +++ b/examples/adwords/v201809/misc/upload_image_asset.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 uploads an image asset. + +To get image assets, run get_all_image_assets.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords +import requests + + +def main(client): + # Initialize appropriate service. + asset_service = client.GetService('AssetService', version='v201809') + + image_request = requests.get('https://goo.gl/3b9Wfh') + image_data = image_request.content + + # Construct media and upload image asset. + image_asset = { + 'xsi_type': 'ImageAsset', + # Optional: Provide a unique friendly name to identify your asset. If you + # specify the assetName field, then both the asset name and the image + # being uploaded should be unique, and should not match another ACTIVE + # asset in this customer account. + # 'assetName': 'Jupiter Trip #' + str(uuid.uuid4())[:8], + 'imageData': image_data, + + } + + operation = {'operator': 'ADD', 'operand': image_asset} + + asset = asset_service.mutate([operation])['value'][0] + + # Display results. + if asset: + print ('Image asset with id %s, name "%s", and status %s was created.\n' + '\tSize is %sx%s and asset URL is %s.' % + (asset['assetId'], asset['assetName'], asset['assetStatus'], + asset['fullSizeInfo']['imageWidth'], + asset['fullSizeInfo']['imageHeight'], + asset['fullSizeInfo']['imageUrl'])) + else: + print 'No images were uploaded.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/misc/upload_media_bundle.py b/examples/adwords/v201809/misc/upload_media_bundle.py new file mode 100755 index 00000000..4ae8f69a --- /dev/null +++ b/examples/adwords/v201809/misc/upload_media_bundle.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 uploads an HTML5 zip file. + +""" + +import urllib2 +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + media_service = client.GetService('MediaService', version='v201809') + # Create HTML5 media. + html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') + # Create a media bundle containing the zip file with all the HTML5 components. + media = [{ + 'xsi_type': 'MediaBundle', + 'data': html5_zip, + 'type': 'MEDIA_BUNDLE' + }] + # Upload HTML5 zip. + response = media_service.upload(media) + + if response: + for media in response: + print( + 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' + 'uploaded successfully.' % + (media['mediaId'], media['dimensions'][0]['value']['width'], + media['dimensions'][0]['value']['height'], media['mimeType'])) + + +def GetHTML5ZipFromUrl(url): + """Retrieve zip file from the given URL.""" + response = urllib2.urlopen(url) + # Note: The utf-8 decode is for 2to3 Python 3 compatibility. + return response.read().decode('utf-8') + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/optimization/__init__.py b/examples/adwords/v201809/optimization/__init__.py new file mode 100644 index 00000000..34ee7f4b --- /dev/null +++ b/examples/adwords/v201809/optimization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Optimization examples.""" diff --git a/examples/adwords/v201809/optimization/estimate_keyword_traffic.py b/examples/adwords/v201809/optimization/estimate_keyword_traffic.py new file mode 100755 index 00000000..ca399db2 --- /dev/null +++ b/examples/adwords/v201809/optimization/estimate_keyword_traffic.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keyword traffic estimates. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + traffic_estimator_service = client.GetService( + 'TrafficEstimatorService', version='v201809') + + # Construct selector object and retrieve traffic estimates. + keywords = [ + {'text': 'mars cruise', 'matchType': 'BROAD'}, + {'text': 'cheap cruise', 'matchType': 'PHRASE'}, + {'text': 'cruise', 'matchType': 'EXACT'} + ] + negative_keywords = [ + {'text': 'moon walk', 'matchType': 'BROAD'} + ] + keyword_estimate_requests = [] + for keyword in keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + } + }) + + for keyword in negative_keywords: + keyword_estimate_requests.append({ + 'keyword': { + 'xsi_type': 'Keyword', + 'matchType': keyword['matchType'], + 'text': keyword['text'] + }, + 'isNegative': 'true' + }) + + # Create ad group estimate requests. + adgroup_estimate_requests = [{ + 'keywordEstimateRequests': keyword_estimate_requests, + 'maxCpc': { + 'xsi_type': 'Money', + 'microAmount': '1000000' + } + }] + + # Create campaign estimate requests. + campaign_estimate_requests = [{ + 'adGroupEstimateRequests': adgroup_estimate_requests, + 'criteria': [ + { + 'xsi_type': 'Location', + 'id': '2840' # United States. + }, + { + 'xsi_type': 'Language', + 'id': '1000' # English. + } + ], + }] + + # Create the selector. + selector = { + 'campaignEstimateRequests': campaign_estimate_requests, + } + + # Optional: Request a list of campaign-level estimates segmented by + # platform. + selector['platformEstimateRequested'] = True + + # Get traffic estimates. + estimates = traffic_estimator_service.get(selector) + + campaign_estimate = estimates['campaignEstimates'][0] + + # Display the campaign level estimates segmented by platform. + if 'platformEstimates' in campaign_estimate: + platform_template = ('Results for the platform with ID: "%d" and name: ' + '"%s".') + for platform_estimate in campaign_estimate['platformEstimates']: + platform = platform_estimate['platform'] + DisplayEstimate(platform_template % (platform['id'], + platform['platformName']), + platform_estimate['minEstimate'], + platform_estimate['maxEstimate']) + + # Display the keyword estimates. + if 'adGroupEstimates' in campaign_estimate: + ad_group_estimate = campaign_estimate['adGroupEstimates'][0] + if 'keywordEstimates' in ad_group_estimate: + keyword_estimates = ad_group_estimate['keywordEstimates'] + keyword_template = ('Results for the keyword with text "%s" and match ' + 'type "%s":') + + keyword_estimates_and_requests = zip(keyword_estimates, + keyword_estimate_requests) + + for keyword_tuple in keyword_estimates_and_requests: + if keyword_tuple[1].get('isNegative', False): + continue + keyword = keyword_tuple[1]['keyword'] + keyword_estimate = keyword_tuple[0] + DisplayEstimate(keyword_template % (keyword['text'], + keyword['matchType']), + keyword_estimate['min'], keyword_estimate['max']) + + +def _CalculateMean(min_est, max_est): + if min_est and max_est: + return (float(min_est) + float(max_est)) / 2.0 + else: + return None + + +def _FormatMean(mean): + if mean: + return '%.2f' % mean + else: + return 'N/A' + + +def DisplayEstimate(message, min_estimate, max_estimate): + """Displays mean average cpc, position, clicks, and total cost for estimate. + + Args: + message: str message to display for the given estimate. + min_estimate: sudsobject containing a minimum estimate from the + TrafficEstimatorService response. + max_estimate: sudsobject containing a maximum estimate from the + TrafficEstimatorService response. + """ + # Find the mean of the min and max values. + mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], + max_estimate['averageCpc']['microAmount']) + if 'averageCpc' in min_estimate + and min_estimate['averageCpc'] else None) + mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], + max_estimate['averagePosition']) + if 'averagePosition' in min_estimate + and min_estimate['averagePosition'] else None) + mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], + max_estimate['clicksPerDay']) + mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], + max_estimate['totalCost']['microAmount']) + + print message + print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) + print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) + print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) + print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py new file mode 100755 index 00000000..0830076c --- /dev/null +++ b/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Gets all available campaign criterion bid modifier landscapes for a campaign. + +To get campaigns, run basic_operations/get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, campaign_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201809') + + # Get all the campaigns for this account. + selector = { + 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', + 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', + 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', + 'RequiredBudget'], + 'paging': { + 'startIndex': 0, + 'numberResults': PAGE_SIZE + }, + 'predicates': [{ + 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] + }] + } + + # Set initial values. + offset = 0 + more_pages = True + + while more_pages is True: + num_landscape_points = 0 + page = data_service.getCampaignCriterionBidLandscape(selector) + + # Display results. + if 'entries' in page: + for bid_modifier_landscape in page['entries']: + num_landscape_points = 0 + print ('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) + for landscape_point in bid_modifier_landscape['landscapePoints']: + num_landscape_points += 1 + print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) + else: + print 'No bid modifier landscapes found.' + + # Need to increment by the total # of landscape points within the page, + # NOT the number of entries (bid landscapes) in the page. + offset += num_landscape_points + selector['paging']['startIndex'] = str(offset) + more_pages = num_landscape_points >= PAGE_SIZE + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py new file mode 100755 index 00000000..a92bb69d --- /dev/null +++ b/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 a bid landscape for an ad group and a criterion. + +To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +CRITERION_ID = 'INSERT_CRITERION_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id, criterion_id): + # Initialize appropriate service. + data_service = client.GetService('DataService', version='v201809') + + # Create a query to select all keyword bid simulations for the specified + # ad group and criterion ID. + query = (adwords.ServiceQueryBuilder() + .Select( + 'AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', + 'BiddableConversions', 'BiddableConversionsValue', 'LocalClicks', + 'LocalCost', 'LocalImpressions') + .Where('AdGroupId').EqualTo(ad_group_id) + .Where('CriterionId').EqualTo(criterion_id) + .Limit(0, PAGE_SIZE) + .Build()) + + while True: + page = data_service.queryCriterionBidLandscape(query) + + if page and 'entries' in page: + entries = page['entries'] + print 'Bid landscape(s) retrieved: %d.' % len(entries) + + for bid_landscape in entries: + print ('Retrieved keyword bid landscape with ad group ID "%d", ' + 'keyword ID "%d", start date "%s", end date "%s", ' + 'with landscape points:' % ( + bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) + for bid_landscape_point in bid_landscape['landscapePoints']: + print (' bid: %s => clicks: %s, cost: %s, impressions: %s, ' + 'biddable conversions: %.2f, ' + 'biddable conversions value: %.2f' + % (bid_landscape_point['bid']['microAmount'], + bid_landscape_point['clicks'], + bid_landscape_point['cost']['microAmount'], + bid_landscape_point['impressions'], + bid_landscape_point['biddableConversions'], + bid_landscape_point['biddableConversionsValue'])) + + if not query.HasNext(page): + break + query.NextPage() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201809/optimization/get_keyword_ideas.py b/examples/adwords/v201809/optimization/get_keyword_ideas.py new file mode 100755 index 00000000..38463669 --- /dev/null +++ b/examples/adwords/v201809/optimization/get_keyword_ideas.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 keywords that are related to a given keyword. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' +PAGE_SIZE = 100 + + +def main(client, ad_group_id=None): + # Initialize appropriate service. + targeting_idea_service = client.GetService( + 'TargetingIdeaService', version='v201809') + + # Construct selector object and retrieve related keywords. + selector = { + 'ideaType': 'KEYWORD', + 'requestType': 'IDEAS' + } + + selector['requestedAttributeTypes'] = [ + 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] + + offset = 0 + selector['paging'] = { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + + selector['searchParameters'] = [{ + 'xsi_type': 'RelatedToQuerySearchParameter', + 'queries': ['space cruise'] + }] + + # Language setting (optional). + selector['searchParameters'].append({ + # The ID can be found in the documentation: + # https://developers.google.com/adwords/api/docs/appendix/languagecodes + 'xsi_type': 'LanguageSearchParameter', + 'languages': [{'id': '1000'}] + }) + + # Network search parameter (optional) + selector['searchParameters'].append({ + 'xsi_type': 'NetworkSearchParameter', + 'networkSetting': { + 'targetGoogleSearch': True, + 'targetSearchNetwork': False, + 'targetContentNetwork': False, + 'targetPartnerSearchNetwork': False + } + }) + + # Use an existing ad group to generate ideas (optional) + if ad_group_id is not None: + selector['searchParameters'].append({ + 'xsi_type': 'SeedAdGroupIdSearchParameter', + 'adGroupId': ad_group_id + }) + + more_pages = True + while more_pages: + page = targeting_idea_service.get(selector) + + # Display results. + if 'entries' in page: + for result in page['entries']: + attributes = {} + for attribute in result['data']: + attributes[attribute['key']] = getattr( + attribute['value'], 'value', '0') + print ('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], + attributes['SEARCH_VOLUME'], + attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) + print + else: + print 'No related keywords were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201809/remarketing/__init__.py b/examples/adwords/v201809/remarketing/__init__.py new file mode 100644 index 00000000..c4912fc8 --- /dev/null +++ b/examples/adwords/v201809/remarketing/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Remarketing examples.""" diff --git a/examples/adwords/v201809/remarketing/add_audience.py b/examples/adwords/v201809/remarketing/add_audience.py new file mode 100755 index 00000000..faf20976 --- /dev/null +++ b/examples/adwords/v201809/remarketing/add_audience.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +PAGE_SIZE = 100 + + +def main(client): + # Initialize appropriate service. + user_list_service = client.GetService( + 'AdwordsUserListService', version='v201809') + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201809') + + # Construct operations and add a user list. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BasicUserList', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'description': 'A list of mars cruise customers in the last year', + 'membershipLifeSpan': '365', + 'conversionTypes': [ + { + 'name': ('Mars cruise customers #%s' + % uuid.uuid4()) + } + ], + # Optional field. + 'status': 'OPEN', + } + } + ] + user_list_result = user_list_service.mutate(operations) + + # Capture the ID(s) of the conversion. + if 'value' in user_list_result: + conversion_ids = [] + for user_list in user_list_result['value']: + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_ids.append(conversion_type['id']) + + # Create query. + query = (adwords.ServiceQueryBuilder() + .Select('Id', 'GoogleGlobalSiteTag', 'GoogleEventSnippet') + .Where('Id').In(*conversion_ids) + .Limit(0, PAGE_SIZE) + .Build()) + + conversions_map = {} + + # Get all conversion trackers. + for page in query.Pager(conversion_tracker_service): + if 'entries' in page: + for conversion_tracker in page['entries']: + conversions_map[conversion_tracker['id']] = conversion_tracker + + for user_list in user_list_result['value']: + print ('User list with name "%s" and ID "%s" was added.' + % (user_list['name'], user_list['id'])) + if user_list['conversionTypes']: + for conversion_type in user_list['conversionTypes']: + conversion_tracker = conversions_map[conversion_type['id']] + print ('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print ('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) + else: + print 'No user lists were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/remarketing/add_conversion_tracker.py b/examples/adwords/v201809/remarketing/add_conversion_tracker.py new file mode 100755 index 00000000..60918dc0 --- /dev/null +++ b/examples/adwords/v201809/remarketing/add_conversion_tracker.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds an AdWords conversion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201809') + + # Construct operations and add conversion_tracker. + operations = [ + { + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Mars cruise customers #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + } + ] + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/remarketing/add_conversion_trackers.py b/examples/adwords/v201809/remarketing/add_conversion_trackers.py new file mode 100755 index 00000000..2f72ea41 --- /dev/null +++ b/examples/adwords/v201809/remarketing/add_conversion_trackers.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds AdWords conversion trackers. + +Adds an AdWords conversion tracker and an upload conversion tracker. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + conversion_tracker_service = client.GetService( + 'ConversionTrackerService', version='v201809') + + # Create an AdWords conversion tracker. + adwords_conversion_tracker = { + 'xsi_type': 'AdWordsConversionTracker', + 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), + 'category': 'DEFAULT', + # Optional fields. + 'status': 'ENABLED', + 'viewthroughLookbackWindow': '15', + 'defaultRevenueValue': '23.41', + 'alwaysUseDefaultRevenueValue': 'true' + } + + upload_conversion = { + 'xsi_type': 'UploadConversion', + 'name': 'Upload Conversion #%s' % uuid.uuid4(), + # Optional fields. + # Set an appropriate category. This will be set to DEFAULT if not + # specified. + 'category': 'LEAD', + 'viewthroughLookbackWindow': '30', + 'ctcLookbackWindow': '90', + # Set the default currency code to use for conversions that do + # not specify a conversion currency. This must be an ISO 4217 3-character + # code such as "EUR" or "USD". + # If this field is not set, AdWords will use the account's currency. + 'defaultRevenueCurrencyCode': 'EUR', + # Set the default revenue value to use for conversions that do not specify + # a converison value. Note that this value should NOT be in micros. + 'defaultRevenueValue': '2.50', + # To upload fractional conversion credits, mark the upload conversion as + # externally attributed. To learn more about importing externally + # attributed conversions, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'isExternallyAttributed': 'true' + } + + # Construct operations. + operations = [{ + 'operator': 'ADD', + 'operand': conversion_tracker + } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] + + # Add the conversions. + conversion_trackers = conversion_tracker_service.mutate(operations) + + # Display results. + for conversion_tracker in conversion_trackers['value']: + print ('Conversion with ID "%d", name "%s", status "%s", and category ' + '"%s" was added.' + % (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) + if (conversion_tracker['ConversionTracker.Type'] + == 'AdWordsConversionTracker'): + print ('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print ('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/remarketing/add_crm_based_user_list.py b/examples/adwords/v201809/remarketing/add_crm_based_user_list.py new file mode 100755 index 00000000..6e3dc05b --- /dev/null +++ b/examples/adwords/v201809/remarketing/add_crm_based_user_list.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + + +"""Adds a user list and populates it with hashed email addresses. + +Note: It may take several hours for the list to be populated with members. Email +addresses must be associated with a Google account. For privacy purposes, the +user list size will show as zero until the list has at least 1000 members. After +that, the size will be rounded to the two most significant digits. +""" + + +import hashlib +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + # Initialize appropriate services. + user_list_service = client.GetService('AdwordsUserListService', 'v201809') + + user_list = { + 'xsi_type': 'CrmBasedUserList', + 'name': 'Customer relationship management list #%d' % uuid.uuid4(), + 'description': 'A list of customers that originated from email addresses', + # CRM-based user lists can use a membershipLifeSpan of 10000 to indicate + # unlimited; otherwise normal values apply. + 'membershipLifeSpan': 30, + 'uploadKeyType': 'CONTACT_INFO' + } + + # Create an operation to add the user list. + operations = [{ + 'operator': 'ADD', + 'operand': user_list + }] + + result = user_list_service.mutate(operations) + user_list_id = result['value'][0]['id'] + + emails = ['customer1@example.com', 'customer2@example.com', + ' Customer3@example.com '] + members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] + + # Add address info. + members.append({ + 'addressInfo': { + # First and last name must be normalized and hashed. + 'hashedFirstName': NormalizeAndSHA256('John'), + 'hashedLastName': NormalizeAndSHA256('Doe'), + # Country code and zip code are sent in plaintext. + 'countryCode': 'US', + 'zipCode': '10001' + } + }) + + mutate_members_operation = { + 'operand': { + 'userListId': user_list_id, + 'membersList': members + }, + 'operator': 'ADD' + } + + response = user_list_service.mutateMembers([mutate_members_operation]) + + if 'userLists' in response: + for user_list in response['userLists']: + print ('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) + + +def NormalizeAndSHA256(s): + """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. + + Args: + s: The string to perform this operation on. + + Returns: + A normalized and SHA-256 hashed string. + """ + return hashlib.sha256(s.strip().lower()).hexdigest() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py new file mode 100755 index 00000000..eb8ba3be --- /dev/null +++ b/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds two rule-based remarketing user lists. + +Adds two rule-based remarketing user lists; one with no site visit date +restrictions and another that will only include users who visit your site in +the next six months. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import calendar +from datetime import date +from datetime import datetime +from datetime import timedelta +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + adwords_user_list_service = client.GetService( + 'AdwordsUserListService', version='v201809') + + # First rule item group - users who visited the checkout page and had more + # than one item in their shopping cart. + checkout_rule_item = { + 'StringRuleItem': { + 'key': { + 'name': 'ecomm_pagetype' + }, + 'op': 'EQUALS', + 'value': 'checkout' + } + } + + cart_size_rule_item = { + 'NumberRuleItem': { + 'key': { + 'name': 'cartsize' + }, + 'op': 'GREATER_THAN', + 'value': '1.0' + } + } + + # Combine the two rule items into a RuleItemGroup so AdWords will logically + # AND the rules together. + checkout_multiple_item_group = { + 'items': [checkout_rule_item, cart_size_rule_item] + } + + # Second rule item group - users who checked out within the next 3 months. + today = date.today() + start_date_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'AFTER', + 'value': today.strftime('%Y%m%d') + } + } + + three_months_later = AddMonths(today, 3) + + three_months_later_rule_item = { + 'DateRuleItem': { + 'key': { + 'name': 'checkoutdate' + }, + 'op': 'BEFORE', + 'value': three_months_later.strftime('%Y%m%d') + } + } + + # Combine the date rule items into a RuleItemGroup + checked_out_date_range_item_group = { + 'items': [start_date_rule_item, three_months_later_rule_item] + } + + # Combine the rule item groups into a Rule so AdWords knows how to apply the + # rules. + rule = { + 'groups': [ + checkout_multiple_item_group, + checked_out_date_range_item_group + ], + # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF + # means 'at least one item in each rule item group must match', and DNF + # means 'at least one entire rule item group must match'. + # DateSpecificRuleUserList only supports DNF. You can also omit the rule + # type altogether to default to DNF. + 'ruleType': 'DNF' + } + + # Third and fourth rule item groups. + # Visitors of a page who visited another page. + site1_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example1' + } + } + site2_rule_item = { + 'StringRuleItem': { + 'key': {'name': 'url__'}, + 'op': 'EQUALS', + 'value': 'example.com/example2' + } + } + + # Create two rules to show that a visitor browsed two sites. + user_visited_site1_rule = { + 'groups': [{ + 'items': [site1_rule_item] + }] + } + + user_visited_site2_rule = { + 'groups': [{ + 'items': [site2_rule_item] + }] + } + + # Create the user list with no restrictions on site visit date. + expression_user_list = { + 'xsi_type': 'ExpressionRuleUserList', + 'name': 'Expression-based user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who checked out in three month window OR visited' + ' the checkout page with more than one item in their' + ' cart.', + 'rule': rule, + # Optional: Set the populationStatus to REQUESTED to include past users in + # the user list. + 'prepopulationStatus': 'REQUESTED' + } + + # Create the user list restricted to users who visit your site within the next + # six months. + end_date = AddMonths(today, 6) + + date_user_list = { + 'xsi_type': 'DateSpecificRuleUserList', + 'name': 'Date rule user list created at %s' + % datetime.today().strftime('%Y%m%d %H:%M:%S'), + 'description': 'Users who visited the site between %s and %s and checked' + ' out in three month window OR visited the checkout page' + ' with more than one item in their cart.' + % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), + 'rule': rule, + 'startDate': today.strftime('%Y%m%d'), + 'endDate': end_date.strftime('%Y%m%d') + } + + # Create the user list for "Visitors of a page who did visit another page". + # To create a user list for "Visitors of a page who did not visit another + # page", change the ruleOperator from AND to AND_NOT. + combined_user_list = { + 'xsi_type': 'CombinedRuleUserList', + 'name': 'Combined rule user lst create at ${creation_time}', + 'description': 'Users who visited two sites.', + 'leftOperand': user_visited_site1_rule, + 'rightOperand': user_visited_site2_rule, + 'ruleOperator': 'AND' + } + + # Create operations to add the user lists. + operations = [ + { + 'operand': user_list, + 'operator': 'ADD', + } for user_list in [expression_user_list, date_user_list, + combined_user_list] + ] + + # Submit the operations. + user_lists = adwords_user_list_service.mutate(operations) + + # Display results. + for user_list in user_lists['value']: + print (('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) + + +def AddMonths(start_date, months): + """A simple convenience utility for adding months to a given start date. + + This increments the months by adding the number of days in the current month + to the current month, for each month. + + Args: + start_date: date The date months are being added to. + months: int The number of months to add. + + Returns: + A date equal to the start date incremented by the given number of months. + """ + current_date = start_date + i = 0 + while i < months: + month_days = calendar.monthrange(current_date.year, current_date.month)[1] + current_date += timedelta(days=month_days) + i += 1 + return current_date + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py b/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py new file mode 100755 index 00000000..dd695cb4 --- /dev/null +++ b/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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. + +"""Imports conversion adjustments for conversions that already exist. + +To set up a conversion tracker, run the add_conversion_tracker.py example. + +""" + +from googleads import adwords + + +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' + +GCLID = 'INSERT_GCLID_HERE' + +ADJUSTMENT_TYPE = 'INSERT_ADJUSTMENT_TYPE_HERE' + +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' + +ADJUSTMENT_TIME = 'INSERT_ADJUSTMENT_TIME_HERE' + +ADJUSTED_VALUE = 'INSERT_ADJUST_VALUE_HERE' + + +def main(client, conversion_name, gclid, adjustment_type, conversion_time, + adjustment_time, adjusted_value): + # Initialize appropriate services. + offline_conversion_service = client.GetService( + 'OfflineConversionAdjustmentFeedService', version='v201809') + + # Associate conversion adjustments with the existing named conversion tracker. + # The GCLID should have been uploaded before with a conversion. + feed = { + 'xsi_type': 'GclidOfflineConversionAdjustmentFeed', + 'conversionName': conversion_name, + 'googleClickId': gclid, + 'conversionTime': conversion_time, + 'adjustmentType': adjustment_type, + 'adjustmentTime': adjustment_time, + 'adjustedValue': adjusted_value + } + + offline_conversion_operation = {'operator': 'ADD', 'operand': feed} + + offline_conversion_response = offline_conversion_service.mutate( + [offline_conversion_operation]) + + new_feed = offline_conversion_response['value'][0] + + print ('Uploaded offline conversion adjustment value of "%s" for Google ' + 'Click ID "%s"' % (new_feed['adjustedValue'], + new_feed['googleClickId'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, GCLID, ADJUSTMENT_TYPE, CONVERSION_TIME, + ADJUSTMENT_TIME, ADJUSTED_VALUE) diff --git a/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py new file mode 100755 index 00000000..b0b148df --- /dev/null +++ b/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for calls related to ads in your account. + +To set up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CALLER_ID = 'INSERT_CALLER_ID_HERE' +# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats +# For time zones, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +CALL_START_TIME = 'INSERT_CALL_START_TIME' +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, caller_id, call_start_time, conversion_name, conversion_time, + conversion_value): + # Initialize appropriate services. + occ_feed_service = client.GetService( + 'OfflineCallConversionFeedService', version='v201809') + + # Associate offline call conversions with the existing named conversion + # tracker. If this tracker was newly created, it may be a few hours before it + # can accept conversions. + feed = { + 'callerId': caller_id, + 'callStartTime': call_start_time, + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + } + + occ_operations = [{'operator': 'ADD', 'operand': feed}] + + occ_response = occ_feed_service.mutate(occ_operations) + values = occ_response['value'] + + if values: + for occ_feed in values: + print ('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + else: + print 'No offline call conversions were added.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, + CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201809/remarketing/upload_offline_conversions.py b/examples/adwords/v201809/remarketing/upload_offline_conversions.py new file mode 100755 index 00000000..0c1b3e3f --- /dev/null +++ b/examples/adwords/v201809/remarketing/upload_offline_conversions.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Imports offline conversion values for specific clicks into your account. + +To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set +up a conversion tracker, run the add_conversion_trackers.py example. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Your click ID must be less than 30 days old. +CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' +# The conversion time must be more recent than the time of the click. +CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' +CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' + + +def main(client, conversion_name, click_id, conversion_time, conversion_value): + # Initialize appropriate services. + offline_conversion_feed_service = client.GetService( + 'OfflineConversionFeedService', version='v201809') + + # Associate offline conversions with the existing named conversion tracker. If + # this tracker was newly created, it may be a few hours before it can accept + # conversions. + feed = { + 'conversionName': conversion_name, + 'conversionTime': conversion_time, + 'conversionValue': conversion_value, + 'googleClickId': click_id, + # Optional: To upload fractional conversion credits, set the external + # attribution model and credit. To use this feature, your conversion + # tracker should be marked as externally attributed. To learn more about + # importing externally attributed conversins, see: + # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions + # 'externalAttributionCredit': 0.3, + # 'externalAttributionModel': 'Linear' + } + + offline_conversion_operation = { + 'operator': 'ADD', + 'operand': feed + } + + offline_conversion_response = offline_conversion_feed_service.mutate( + [offline_conversion_operation]) + new_feed = offline_conversion_response['value'] + + print ('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, + CONVERSION_VALUE) diff --git a/examples/adwords/v201809/remarketing/upload_offline_data.py b/examples/adwords/v201809/remarketing/upload_offline_data.py new file mode 100755 index 00000000..b09584bb --- /dev/null +++ b/examples/adwords/v201809/remarketing/upload_offline_data.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 shows how to upload offline data for store sales transactions. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import datetime +import hashlib + +from googleads import adwords +import pytz + + +_DT_FORMAT = '%Y%m%d %H%M%S' +# User identifier types whose values must be hashed. +_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', + 'HASHED_LAST_NAME', 'HASHED_PHONE') +# The timezone to be used in this example. For valid timezone IDs, see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +_TIMEZONE = pytz.timezone('America/New_York') +# Name of the conversion tracker to upload to. +CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' +# Insert email addresses below for creating user identifiers. +EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] +# The external upload ID can be any number that you use to keep track of your +# uploads. +EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' +# Store sales upload common metadata types +METADATA_TYPE_1P = 'FirstPartyUploadMetadata' +METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' +# Set the below constant to METADATA_TYPE_3P if uploading third-party data. +STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P +# The three constants below are needed when uploading third-party data. They +# are not used when uploading first-party data. +# Advertiser upload time to partner. +# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, +# see: +# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids +ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' +# Indicates the version of the bridge map. +BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' +# The ID of the third party uploading the transaction feed. +PARTNER_ID = 'INSERT_PARTNER_ID_HERE' + + +def main(client, conversion_name, external_upload_id, + store_sales_upload_common_metadata_type, email_addresses, + advertiser_upload_time=None, bridge_map_version_id=None, + partner_id=None): + # Set partial failure to True since this example demonstrates how to handle + # partial errors. + client.partial_failure = True + # Initialize appropriate services. + offline_data_upload_service = client.GetService( + 'OfflineDataUploadService', version='v201809') + + # Create the first offline data for upload. + # This transaction occurred 7 days ago with an amount of $200 USD. + transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=7)) + offline_data_1 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[0]), + _CreateUserIdentifier(identifier_type='STATE', value='New York') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_1), + 'transactionAmount': { + 'currencyCode': 'USD', + 'money': { + 'microAmount': 200000000 + } + }, + 'conversionName': conversion_name + } + } + + # Create the second offline data for upload. + # This transaction occurred 14 days ago with amount of 450 EUR. + transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - + datetime.timedelta(days=14)) + offline_data_2 = { + 'StoreSalesTransaction': { + 'userIdentifiers': [ + _CreateUserIdentifier(identifier_type='HASHED_EMAIL', + value=email_addresses[1]), + _CreateUserIdentifier(identifier_type='STATE', value='California') + ], + 'transactionTime': _GetFormattedDateTime(transaction_time_2), + 'transactionAmount': { + 'currencyCode': 'EUR', + 'money': { + 'microAmount': 450000000 + } + }, + 'conversionName': conversion_name + } + } + + # Set the type and metadata of this upload. + upload_metadata = { + 'StoreSalesUploadCommonMetadata': { + 'xsi_type': store_sales_upload_common_metadata_type, + 'loyaltyRate': 1.0, + 'transactionUploadRate': 1.0, + } + } + + if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: + upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' + elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: + upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' + upload_metadata['StoreSalesUploadCommonMetadata'].update({ + 'advertiserUploadTime': advertiser_upload_time, + 'validTransactionRate': 1.0, + 'partnerMatchRate': 1.0, + 'partnerUploadRate': 1.0, + 'bridgeMapVersionId': bridge_map_version_id, + 'partnerId': partner_id + }) + else: + raise ValueError('Unknown metadata type.') + + # Create offline data upload + offline_data_upload = { + 'externalUploadId': external_upload_id, + 'offlineDataList': [offline_data_1, offline_data_2], + # Set the type of this upload. + 'uploadType': upload_type, + 'uploadMetadata': upload_metadata + } + + # Create an offline data upload operation. + operations = [{ + 'operator': 'ADD', + 'operand': offline_data_upload + }] + + # Upload offline data on the server and print the result. + result = offline_data_upload_service.mutate(operations) + offline_data_upload = result['value'][0] + + print ('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) + + # Print any partial data errors from the response. + if result['partialFailureErrors']: + for api_error in result['partialFailureErrors']: + # Get the index of the failed operation from the error's field path + # elements. + operation_index = _GetFieldPathElementIndex(api_error, 'operations') + + if operation_index: + failed_offline_data_upload = operations[operation_index]['operand'] + # Get the index of the entry in the offline data list from the error's + # field path elements. + offline_data_list_index = _GetFieldPathElementIndex( + api_error, 'offlineDataList') + print ('Offline data list entry "%d" in operation "%d" with external ' + 'upload ID "%d" and type "%s" has triggered failure for the ' + 'following reason: "%s"' % ( + offline_data_list_index, operation_index, + failed_offline_data_upload['externalUploadId'], + failed_offline_data_upload['uploadType'], + api_error['errorString'])) + else: + print ('A failure has occurred for the following reason: "%s".' % ( + api_error['errorString'])) + + +def _CreateUserIdentifier(identifier_type=None, value=None): + """Creates a user identifier from the specified type and value. + + Args: + identifier_type: a str specifying the type of user identifier. + value: a str value of the identifier; to be hashed using SHA-256 if needed. + + Returns: + A dict specifying a user identifier, with a value hashed using SHA-256 if + needed. + """ + if identifier_type in _HASHED_IDENTIFIER_TYPES: + # If the user identifier type is a hashed type, normalize and hash the + # value. + value = hashlib.sha256(value.strip().lower()).hexdigest() + + user_identifier = { + 'userIdentifierType': identifier_type, + 'value': value + } + + return user_identifier + + +def _GetFieldPathElementIndex(api_error, field): + """Retrieve the index of a given field in the api_error's fieldPathElements. + + Args: + api_error: a dict containing a partialFailureError returned from the AdWords + API. + field: a str field for which this determines the index in the api_error's + fieldPathElements. + + Returns: + An int index of the field path element, or None if the specified field can't + be found in the api_error. + """ + field_path_elements = api_error['fieldPathElements'] + + if field_path_elements: + found_index = [field_path_element['index'] + for field_path_element in field_path_elements + if field_path_element['field'] == field] + if found_index: + return found_index + + return None + + +def _GetFormattedDateTime(dt): + """Formats the given datetime and timezone for use with AdWords. + + Args: + dt: a datetime instance. + + Returns: + A str representation of the datetime in the correct format for AdWords. + """ + return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, + STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, + ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201809/reporting/__init__.py b/examples/adwords/v201809/reporting/__init__.py new file mode 100644 index 00000000..8f94f28b --- /dev/null +++ b/examples/adwords/v201809/reporting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Reporting examples.""" diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py new file mode 100755 index 00000000..69cf0739 --- /dev/null +++ b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import StringIO +import sys + +from googleads import adwords + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201809') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, + 'CSV') + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py new file mode 100755 index 00000000..0536e597 --- /dev/null +++ b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the report download stream. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import StringIO +import sys +from googleads import adwords + +# The chunk size used for the report download. +CHUNK_SIZE = 16 * 1024 + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201809') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Retrieve the report stream and print it out + report_data = StringIO.StringIO() + stream_data = report_downloader.DownloadReportAsStream( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + try: + while True: + chunk = stream_data.read(CHUNK_SIZE) + if not chunk: break + report_data.write(chunk.decode() if sys.version_info[0] == 3 + and getattr(report_data, 'mode', 'w') == 'w' else chunk) + print report_data.getvalue() + finally: + report_data.close() + stream_data.close() + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py new file mode 100755 index 00000000..c997f27f --- /dev/null +++ b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +# Specify where to download the file here. +PATH = '/tmp/report_download.csv' + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201809') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + print report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py new file mode 100755 index 00000000..72fd54e2 --- /dev/null +++ b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report as a string. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +from googleads import adwords + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201809') + + # Create report definition. + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # Print out the report as a string + print report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201809/reporting/download_criteria_report_with_awql.py new file mode 100755 index 00000000..7e2ca12f --- /dev/null +++ b/examples/adwords/v201809/reporting/download_criteria_report_with_awql.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report with AWQL. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +import sys +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201809') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', + 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', + 'Cost') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + # You can provide a file object to write the output to. For this + # demonstration we use sys.stdout to write the report to the screen. + report_downloader.DownloadReportWithAwql( + report_query, 'CSV', sys.stdout, skip_report_header=False, + skip_column_header=False, skip_report_summary=False, + include_zero_impressions=True) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201809/reporting/download_criteria_report_with_selector.py new file mode 100755 index 00000000..5027e841 --- /dev/null +++ b/examples/adwords/v201809/reporting/download_criteria_report_with_selector.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads a criteria performance report. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import sys +from googleads import adwords + + +def main(client): + report_downloader = client.GetReportDownloader(version='v201809') + + report = { + 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'CRITERIA_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', + 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] + } + } + + # You can provide a file object to write the output to. For this demonstration + # we use sys.stdout to write the report to the screen. + report_downloader.DownloadReport( + report, sys.stdout, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True) + + +if __name__ == '__main__': + adwords_client = adwords.AdWordsClient.LoadFromStorage() + main(adwords_client) diff --git a/examples/adwords/v201809/reporting/get_report_fields.py b/examples/adwords/v201809/reporting/get_report_fields.py new file mode 100755 index 00000000..209826c7 --- /dev/null +++ b/examples/adwords/v201809/reporting/get_report_fields.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 report fields. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' + + +def main(client, report_type): + # Initialize appropriate service. + report_definition_service = client.GetService( + 'ReportDefinitionService', version='v201809') + + # Get report fields. + fields = report_definition_service.getReportFields(report_type) + + # Display results. + print 'Report type "%s" contains the following fields:' % report_type + for field in fields: + print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + if 'enumValues' in field: + print ' := [%s]' % ', '.join(field['enumValues']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201809/reporting/parallel_report_download.py b/examples/adwords/v201809/reporting/parallel_report_download.py new file mode 100755 index 00000000..e9193f98 --- /dev/null +++ b/examples/adwords/v201809/reporting/parallel_report_download.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 downloads an adgroup performance report for all child accounts. + +To get report fields, run get_report_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import multiprocessing +import os +from Queue import Empty +import time + +import googleads.adwords +import googleads.errors + +# Timeout between retries in seconds. +BACKOFF_FACTOR = 5 +# Maximum number of processes to spawn. +MAX_PROCESSES = multiprocessing.cpu_count() +# Maximum number of retries for 500 errors. +MAX_RETRIES = 5 +# Maximum number of items to be sent in a single API response. +PAGE_SIZE = 100 +# Directory to download the reports to. +REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' + + +def _DownloadReport(process_id, report_download_directory, customer_id, + report_definition): + """Helper function used by ReportWorker to download customer report. + + Note that multiprocessing differs between Windows / Unix environments. A + Process or its subclasses in Windows must be serializable with pickle, but + that is not possible for AdWordsClient or ReportDownloader. This top-level + function is used as a work-around for Windows support. + + Args: + process_id: The PID of the process downloading the report. + report_download_directory: A string indicating the directory where you + would like to download the reports. + customer_id: A str AdWords customer ID for which the report is being + downloaded. + report_definition: A dict containing the report definition to be used. + + Returns: + A tuple indicating a boolean success/failure status, and dict request + context. + """ + report_downloader = (googleads.adwords.AdWordsClient.LoadFromStorage() + .GetReportDownloader()) + + filepath = os.path.join(report_download_directory, + 'adgroup_%d.csv' % customer_id) + retry_count = 0 + + while True: + print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (process_id, retry_count, customer_id, filepath)) + try: + with open(filepath, 'wb') as handler: + report_downloader.DownloadReport( + report_definition, output=handler, + client_customer_id=customer_id) + return (True, {'customerId': customer_id}) + except googleads.errors.AdWordsReportError as e: + if e.code == 500 and retry_count < MAX_RETRIES: + time.sleep(retry_count * BACKOFF_FACTOR) + else: + print ('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) + return (False, {'customerId': customer_id, 'code': e.code, + 'message': e.message}) + + +class ReportWorker(multiprocessing.Process): + """A worker Process used to download reports for a set of customer IDs.""" + + def __init__(self, report_download_directory, report_definition, + input_queue, success_queue, failure_queue): + """Initializes a ReportWorker. + + Args: + report_download_directory: A string indicating the directory where you + would like to download the reports. + report_definition: A dict containing the report definition that you would + like to run against all customer IDs in the input_queue. + input_queue: A Queue instance containing all of the customer IDs that + the report_definition will be run against. + success_queue: A Queue instance that the details of successful report + downloads will be saved to. + failure_queue: A Queue instance that the details of failed report + downloads will be saved to. + """ + super(ReportWorker, self).__init__() + self.report_download_directory = report_download_directory + self.report_definition = report_definition + self.input_queue = input_queue + self.success_queue = success_queue + self.failure_queue = failure_queue + + def run(self): + while True: + try: + customer_id = self.input_queue.get(timeout=0.01) + except Empty: + break + result = _DownloadReport(self.ident, self.report_download_directory, + customer_id, self.report_definition) + (self.success_queue if result[0] else self.failure_queue).put(result[1]) + + +def GetCustomerIDs(client): + """Retrieves all CustomerIds in the account hierarchy. + + Note that your configuration file must specify a client_customer_id belonging + to an AdWords manager account. + + Args: + client: an AdWordsClient instance. + Raises: + Exception: if no CustomerIds could be found. + Returns: + A Queue instance containing all CustomerIds in the account hierarchy. + """ + # For this example, we will use ManagedCustomerService to get all IDs in + # hierarchy that do not belong to MCC accounts. + managed_customer_service = client.GetService('ManagedCustomerService', + version='v201809') + + offset = 0 + + # Get the account hierarchy for this account. + selector = { + 'fields': ['CustomerId'], + 'predicates': [{ + 'field': 'CanManageClients', + 'operator': 'EQUALS', + 'values': [False] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + + # Using Queue to balance load between processes. + queue = multiprocessing.Queue() + more_pages = True + + while more_pages: + page = managed_customer_service.get(selector) + + if page and 'entries' in page and page['entries']: + for entry in page['entries']: + queue.put(entry['customerId']) + else: + raise Exception('Can\'t retrieve any customer ID.') + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + return queue + + +def main(client, report_download_directory): + # Determine list of customer IDs to retrieve report for. + input_queue = GetCustomerIDs(client) + reports_succeeded = multiprocessing.Queue() + reports_failed = multiprocessing.Queue() + + # Create report definition. + report_definition = { + 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', + 'dateRangeType': 'LAST_7_DAYS', + 'reportType': 'ADGROUP_PERFORMANCE_REPORT', + 'downloadFormat': 'CSV', + 'selector': { + 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', + 'Cost'], + # Predicates are optional. + 'predicates': { + 'field': 'AdGroupStatus', + 'operator': 'IN', + 'values': ['ENABLED', 'PAUSED'] + } + }, + } + + queue_size = input_queue.qsize() + num_processes = min(queue_size, MAX_PROCESSES) + print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + + # Start all the processes. + processes = [ReportWorker(report_download_directory, + report_definition, input_queue, reports_succeeded, + reports_failed) + for _ in range(num_processes)] + + for process in processes: + process.start() + + for process in processes: + process.join() + + print 'Finished downloading reports with the following results:' + while True: + try: + success = reports_succeeded.get(timeout=0.01) + except Empty: + break + print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + + while True: + try: + failure = reports_failed.get(timeout=0.01) + except Empty: + break + print ('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) + + +if __name__ == '__main__': + adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() + main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201809/reporting/stream_criteria_report_results.py b/examples/adwords/v201809/reporting/stream_criteria_report_results.py new file mode 100755 index 00000000..3884cbaf --- /dev/null +++ b/examples/adwords/v201809/reporting/stream_criteria_report_results.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 streams the results of an ad hoc report. + +Collects total impressions by campaign from each line. Demonstrates how you can +extract data from a large report without holding the entire result set in +memory or using files. +""" + +import collections + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + report_downloader = client.GetReportDownloader(version='v201809') + + # Create report query. + report_query = (adwords.ReportQueryBuilder() + .Select('Id', 'AdNetworkType1', 'Impressions') + .From('CRITERIA_PERFORMANCE_REPORT') + .Where('Status').In('ENABLED', 'PAUSED') + .During('LAST_7_DAYS') + .Build()) + + # Retrieve the report stream. + stream = report_downloader.DownloadReportAsStreamWithAwql( + report_query, 'CSV', skip_report_header=True, skip_column_header=True, + skip_report_summary=True, include_zero_impressions=True) + + ad_network_map = collections.defaultdict(int) + + try: + while True: + line = stream.readline() + if not line: break + process_line(line, ad_network_map=ad_network_map) + finally: + stream.close() + + print 'Total impressions by ad network type 1:' + for ad_network_type, impressions in sorted(ad_network_map.iteritems()): + print '%s: %s' % (ad_network_type, impressions) + + +def process_line(line, ad_network_map): + _, ad_network_type_1, impressions = line.split(',') + ad_network_map[ad_network_type_1] += int(impressions) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/shopping/__init__.py b/examples/adwords/v201809/shopping/__init__.py new file mode 100644 index 00000000..be510830 --- /dev/null +++ b/examples/adwords/v201809/shopping/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Shopping examples.""" diff --git a/examples/adwords/v201809/shopping/add_product_partition_tree.py b/examples/adwords/v201809/shopping/add_product_partition_tree.py new file mode 100755 index 00000000..d66f135f --- /dev/null +++ b/examples/adwords/v201809/shopping/add_product_partition_tree.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creates a ProductPartition tree. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, adgroup_id): + """Runs the example.""" + adgroup_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201809') + + helper = ProductPartitionHelper(adgroup_id) + + # The most trivial partition tree has only a unit node as the root, e.g.: + # helper.CreateUnit(bid_amount=100000) + + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition, 200000) + helper.CreateUnit(root, used_product_canonical_condition, 100000) + other_condition = helper.CreateSubdivision( + root, other_product_canonical_condition) + + cool_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CoolBrand' + } + + cheap_product_brand = { + 'xsi_type': 'ProductBrand', + 'value': 'CheapBrand' + } + + other_product_brand = { + 'xsi_type': 'ProductBrand', + } + + helper.CreateUnit(other_condition, cool_product_brand, 900000) + helper.CreateUnit(other_condition, cheap_product_brand, 10000) + other_brand = helper.CreateSubdivision(other_condition, other_product_brand) + + # The value for the bidding category is a fixed ID for the 'Luggage & Bags' + # category. You can retrieve IDs for categories from the ConstantDataService. + # See the 'GetProductTaxonomy' example for more details. + luggage_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + + generic_category = { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + } + + helper.CreateUnit(other_brand, luggage_category, 750000) + helper.CreateUnit(other_brand, generic_category, 110000) + + # Make the mutate request + result = adgroup_criterion_service.mutate(helper.GetOperations()) + + children = {} + + root_node = None + + # For each criterion, make an array containing each of its children. + # We always create the parent before the child, so we can rely on that here. + for adgroup_criterion in result['value']: + children[adgroup_criterion['criterion']['id']] = [] + + if 'parentCriterionId' in adgroup_criterion['criterion']: + children[adgroup_criterion['criterion']['parentCriterionId']].append( + adgroup_criterion['criterion']) + else: + root_node = adgroup_criterion['criterion'] + + # Show the tree + DisplayTree(root_node, children) + + +def DisplayTree(node, children, level=0): + """Recursively display a node and each of its children. + + Args: + node: The node we're displaying the children of. + children: Children of the parent node. + level: How deep in the tree we are. + """ + value = '' + node_type = '' + + if 'caseValue' in node: + case_value = node['caseValue'] + node_type = case_value['ProductDimension.Type'] + + if node_type == 'ProductCanonicalCondition': + value = (case_value['condition'] if 'condition' in case_value + else 'OTHER') + elif node_type == 'ProductBiddingCategory': + value = '%s(%s)' % (case_value['type'], case_value['value'] + if 'value' in case_value else 'OTHER') + else: + value = (case_value['value'] if 'value' in case_value else 'OTHER') + + print ('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) + + for child_node in children[node['id']]: + DisplayTree(child_node, children, level + 1) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201809/shopping/add_product_scope.py b/examples/adwords/v201809/shopping/add_product_scope.py new file mode 100755 index 00000000..9065d558 --- /dev/null +++ b/examples/adwords/v201809/shopping/add_product_scope.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Restricts products that will be included in a campaign with a ProductScope. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' + + +def main(client, campaign_id): + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201809') + + product_scope = { + 'xsi_type': 'ProductScope', + # This set of dimensions is for demonstration purposes only. It would be + # extremely unlikely that you want to include so many dimensions in your + # product scope. + 'dimensions': [ + { + 'xsi_type': 'ProductBrand', + 'value': 'Nexus' + }, + { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + }, + { + 'xsi_type': 'ProductCustomAttribute', + 'type': 'CUSTOM_ATTRIBUTE_0', + 'value': 'my attribute value' + }, + { + 'xsi_type': 'ProductOfferId', + 'value': 'book1' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L1', + 'value': 'Media' + }, + { + 'xsi_type': 'ProductType', + 'type': 'PRODUCT_TYPE_L2', + 'value': 'Books' + }, + # The value for the bidding category is a fixed ID for the "Luggage + # & Bags" category. You can retrieve IDs for categories from the + # ConstantDataService. See the "GetProductCategoryTaxonomy" example + # for more details. + { + 'xsi_type': 'ProductBiddingCategory', + 'type': 'BIDDING_CATEGORY_L1', + 'value': '-5914235892932915235' + } + ] + } + + campaign_criterion = { + 'campaignId': campaign_id, + 'criterion': product_scope + } + + operations = [{ + 'operator': 'ADD', + 'operand': campaign_criterion + }] + + # Make the request + result = campaign_criterion_service.mutate(operations) + + for criterion in result['value']: + print ('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201809/shopping/add_shopping_campaign.py b/examples/adwords/v201809/shopping/add_shopping_campaign.py new file mode 100755 index 00000000..b6e6afe1 --- /dev/null +++ b/examples/adwords/v201809/shopping/add_shopping_campaign.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds a Shopping campaign. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +# If set to true, a default partition will be created. If running the +# add_product_partition_tree.py example right after this example, make +# sure this stays set to false. +CREATE_DEFAULT_PARTITION = False +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, budget_id, merchant_id, create_default_partition): + campaign_service = client.GetService('CampaignService', version='v201809') + ad_group_service = client.GetService('AdGroupService', version='v201809') + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + + # Create campaign + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations) + + for campaign in result['value']: + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + # Create the AdGroup + ad_group = { + 'campaignId': campaign['id'], + 'name': 'AdGroup #%s' % uuid.uuid4() + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': ad_group + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) + + # Create an AdGroup Ad + adgroup_ad = { + 'adGroupId': ad_group_id, + # Create ProductAd + 'ad': { + 'xsi_type': 'ProductAd', + 'Ad.Type': 'ProductAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201809') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + }, + 'biddingStrategyConfiguration': { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 500000 + } + }] + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py new file mode 100755 index 00000000..0f1f88f8 --- /dev/null +++ b/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py @@ -0,0 +1,401 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds a Shopping campaign for Showcase ads. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import uuid + +from googleads import adwords +from googleads import errors + + +BUDGET_ID = 'INSERT_BUDGET_ID_HERE' +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' +EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' +COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' + + +class ProductPartitionHelper(object): + """A helper for creating ProductPartition trees.""" + + def __init__(self, adgroup_id): + """Initializer. + + Args: + adgroup_id: The ID of the AdGroup that we wish to attach the partition + tree to. + """ + # The next temporary criterion ID to be used. + # When creating our tree we need to specify the parent-child relationships + # between nodes. However, until a criterion has been created on the server + # we do not have a criterion ID with which to refer to it. + # Instead we can specify temporary IDs that are specific to a single mutate + # request. Once the criteria have been created they are assigned an ID as + # normal and the temporary ID will no longer refer to it. + # A valid temporary ID is any negative integer. + self.next_id = -1 + # The set of mutate operations needed to create the current tree. + self.operations = [] + self.adgroup_id = adgroup_id + + def CreateSubdivision(self, parent=None, value=None): + """Creates a subdivision node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + Returns: + A new subdivision node. + """ + division = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'SUBDIVISION', + 'id': str(self.next_id) + } + + # The root has neither a parent nor a value. + if parent is not None: + division['parentCriterionId'] = parent['id'] + division['caseValue'] = value + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': self.adgroup_id, + 'criterion': division + } + + self.CreateAddOperation(adgroup_criterion) + self.next_id -= 1 + + return division + + def CreateUnit(self, parent=None, value=None, bid_amount=None): + """Creates a unit node. + + Args: + parent: The node that should be this node's parent. + value: The value being partitioned on. + bid_amount: The amount to bid for matching products, in micros. + Returns: + A new unit node. + """ + unit = { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + + # The root node has neither a parent nor a value. + if parent is not None: + unit['parentCriterionId'] = parent['id'] + unit['caseValue'] = value + + if bid_amount is not None and bid_amount > 0: + # Note: Showcase ads require that the campaign has a ManualCpc + # BiddingStrategyConfiguration. + bidding_strategy_configuration = { + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'xsi_type': 'Money', + 'microAmount': str(bid_amount) + } + }] + } + + adgroup_criterion = { + 'xsi_type': 'BiddableAdGroupCriterion', + 'biddingStrategyConfiguration': bidding_strategy_configuration + } + else: + adgroup_criterion = { + 'xsi_type': 'NegativeAdGroupCriterion' + } + + adgroup_criterion['adGroupId'] = self.adgroup_id + adgroup_criterion['criterion'] = unit + + self.CreateAddOperation(adgroup_criterion) + + return unit + + def GetOperations(self): + """Returns the set of mutate operations needed to create the current tree. + + Returns: + The set of operations + """ + return self.operations + + def CreateAddOperation(self, criterion): + """Creates an AdGroupCriterionOperation for the given criterion. + + Args: + criterion: The criterion we want to add. + """ + operation = { + 'operator': 'ADD', + 'operand': criterion + } + + self.operations.append(operation) + + +def main(client, budget_id, merchant_id, expanded_image_filepath, + collapsed_image_filepath): + try: + # Create the Shopping Campaign + campaign = CreateShoppingCampaign(client, budget_id, merchant_id) + + # Create the AdGroup + adgroup = CreateAdGroup(client, campaign['id']) + + # Create a Showcase Ad + CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath) + + product_partition_tree = CreateProductPartition(client, adgroup['id']) + print 'Final tree:\n%s' % product_partition_tree + except errors.GoogleAdsServerFault: + print 'Failed to create shopping campaign for showcase ads.' + raise + + +def CreateShoppingCampaign(client, budget_id, merchant_id): + """Creates a shopping campaign with the given budget and merchant IDs. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + shopping campaign. + + Returns: + The created Shopping Campaign as a sudsobject. + """ + campaign_service = client.GetService('CampaignService', 'v201809') + + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a shopping campaign + 'advertisingChannelType': 'SHOPPING', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required) + 'budget': { + 'budgetId': budget_id + }, + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MANUAL_CPC' + }, + 'settings': [ + # All shopping campaigns need a ShoppingSetting + { + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'campaignPriority': '0', + 'merchantId': merchant_id, + # Set to "True" to enable Local Inventory Ads in your campaign. + 'enableLocal': True + } + ] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + campaign = campaign_service.mutate(campaign_operations)['value'][0] + print ('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) + + return campaign + + +def CreateAdGroup(client, campaign_id): + """Creates an AdGroup for the given shopping campaign ID. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a shopping campaign. + + Returns: + The created AdGroup as a sudsobject. + """ + ad_group_service = client.GetService('AdGroupService', 'v201809') + + adgroup = { + # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS + 'adGroupType': 'SHOPPING_SHOWCASE_ADS', + 'campaignId': campaign_id, + 'name': 'AdGroup #%s' % uuid.uuid4(), + # REQUIRED: Set the ad group's bidding strategy configuration. + 'biddingStrategyConfiguration': { + # Showcase ads require either ManualCpc or EnhancedCpc. + 'biddingStrategyType': 'MANUAL_CPC', + # Optional: Set the bids + 'bids': [{ + 'xsi_type': 'CpcBid', + 'bid': { + 'microAmount': 100000 + } + }] + } + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': adgroup + } + + # Make the mutate request to add the AdGroup to the Shopping Campaign + adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) + + return adgroup + + +def CreateShowcaseAd(client, adgroup, expanded_image_filepath, + collapsed_image_filepath): + """Creates a showcase add for the given AdGroup with the given images. + + Args: + client: an AdWordsClient instance. + adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + expanded_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's expandedImage. + collapsed_image_filepath: a str filepath to a .jpg file that will be used as + the Showcase Ad's collapsedImage. + + Returns: + The created Showcase Ad as a sudsobject. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809') + + showcase_ad = { + 'adGroupId': adgroup['id'], + 'ad': { + 'xsi_type': 'ShowcaseAd', + 'Ad.Type': 'ShowcaseAd', + # Required: set the ad's name, final URLs, and display URL. + 'name': 'Showcase ad #%s' % uuid.uuid4(), + 'finalUrls': 'http://example.com/showcase', + 'displayUrl': 'example.com', + # Required: Set the ad's expanded image. + 'expandedImage': { + 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] + }, + # Optional: Set the collapsed image. + 'collapsedImage': { + 'mediaId': + UploadImage(client, collapsed_image_filepath)['mediaId'] + } + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': showcase_ad + } + + # Make the mutate request to add the ProductAd to the AdGroup + showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] + + print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + + return showcase_ad + + +def UploadImage(client, filepath): + """Uploads a .jpg image with the given filepath via the AdWords MediaService. + + Args: + client: an AdWordsClient instance. + filepath: a str filepath to the .jpg file to be uploaded. + + Returns: + The created Image as a sudsobject. + """ + media_service = client.GetService('MediaService', 'v201809') + + with open(filepath, 'rb') as image_handle: + image_data = image_handle.read().decode('utf-8') + + image = [{ + 'xsi_type': 'Image', + 'data': image_data, + 'type': 'IMAGE' + }] + + image = media_service.upload(image)[0] + + return image + + +def CreateProductPartition(client, adgroup_id): + """Creates a ProductPartition tree for the given AdGroup ID. + + Args: + client: an AdWordsClient instance. + adgroup_id: a str AdGroup ID. + + Returns: + The ProductPartition tree as a sudsobject. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + 'v201809') + helper = ProductPartitionHelper(adgroup_id) + root = helper.CreateSubdivision() + + new_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'NEW' + } + + used_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + 'condition': 'USED' + } + + other_product_canonical_condition = { + 'xsi_type': 'ProductCanonicalCondition', + } + + helper.CreateUnit(root, new_product_canonical_condition) + helper.CreateUnit(root, used_product_canonical_condition) + helper.CreateUnit(root, other_product_canonical_condition) + + result = ad_group_criterion_service.mutate(helper.operations) + return result['value'] + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, + COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201809/shopping/get_product_category_taxonomy.py b/examples/adwords/v201809/shopping/get_product_category_taxonomy.py new file mode 100755 index 00000000..f6922afe --- /dev/null +++ b/examples/adwords/v201809/shopping/get_product_category_taxonomy.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import adwords + + +def main(client): + service = client.GetService('ConstantDataService', version='v201809') + + selector = { + 'predicates': [ + { + 'field': 'Country', + 'operator': 'IN', + 'values': ['US'] + } + ] + } + + result = service.getProductBiddingCategoryData(selector) + + bidding_categories = {} + root_categories = [] + + for product_bidding_category in result: + category_id = product_bidding_category['dimensionValue']['value'] + parent_id = None + name = product_bidding_category['displayValue'][0]['value'] + + # Note: There may be cases where there isn't a value. + if ('parentDimensionValue' in product_bidding_category and + 'value' in product_bidding_category['parentDimensionValue']): + parent_id = product_bidding_category['parentDimensionValue']['value'] + + if category_id not in bidding_categories: + bidding_categories[category_id] = {} + + category = bidding_categories[category_id] + + if parent_id is not None: + if parent_id not in bidding_categories: + bidding_categories[parent_id] = {} + + parent = bidding_categories[parent_id] + + if 'children' not in parent: + parent['children'] = [] + + parent['children'].append(category) + else: + root_categories.append(category) + + category['id'] = category_id + category['name'] = name + + DisplayCategories(root_categories) + + +def DisplayCategories(categories, prefix=''): + for category in categories: + print '%s%s [%s]' % (prefix, category['name'], category['id']) + + if 'children' in category: + DisplayCategories(category['children'], '%s%s > ' % (prefix, + category['name'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/targeting/__init__.py b/examples/adwords/v201809/targeting/__init__.py new file mode 100644 index 00000000..f5595299 --- /dev/null +++ b/examples/adwords/v201809/targeting/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2016 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. + +"""Targeting examples.""" diff --git a/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py new file mode 100755 index 00000000..0a125bdd --- /dev/null +++ b/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds various types of targeting criteria to a given campaign. + +To get campaigns, run get_campaigns.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' +# Replace the value below with the ID of a feed that has been configured for +# location targeting, meaning it has an ENABLED FeedMapping with criterionType +# of 77. Feeds linked to a GMB account automatically have this FeedMapping. +# If you don't have such a feed, set this value to None. +LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' + + +def main(client, campaign_id, location_feed_id=None): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201809') + + # Create locations. The IDs can be found in the documentation or retrieved + # with the LocationCriterionService. + california = { + 'xsi_type': 'Location', + 'id': '21137' + } + mexico = { + 'xsi_type': 'Location', + 'id': '2484' + } + + # Create languages. The IDs can be found in the documentation or retrieved + # with the ConstantDataService. + english = { + 'xsi_type': 'Language', + 'id': '1000' + } + spanish = { + 'xsi_type': 'Language', + 'id': '1003' + } + + # Create a negative campaign criterion operation. + negative_campaign_criterion_operand = { + 'xsi_type': 'NegativeCampaignCriterion', + 'campaignId': campaign_id, + 'criterion': { + 'xsi_type': 'Keyword', + 'matchType': 'BROAD', + 'text': 'jupiter cruise' + } + } + criteria = [california, mexico, english, spanish] + if location_feed_id: + # Distance targeting. Area of 10 miles around targets above. + criteria.append({ + 'xsi_type': 'LocationGroups', + 'feedId': location_feed_id, + 'matchingFunction': { + 'operator': 'IDENTITY', + 'lhsOperand': [{ + 'xsi_type': 'LocationExtensionOperand', + 'radius': { + 'xsi_type': 'ConstantOperand', + 'type': 'DOUBLE', + 'unit': 'MILES', + 'doubleValue': 10 + } + }] + } + }) + # Create operations + operations = [] + for criterion in criteria: + operations.append({ + 'operator': 'ADD', + 'operand': { + 'campaignId': campaign_id, + 'criterion': criterion + } + }) + # Add the negative campaign criterion. + operations.append({ + 'operator': 'ADD', + 'operand': negative_campaign_criterion_operand + }) + + # Make the mutate request. + result = campaign_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for campaign_criterion in result['value']: + print ('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' + % (campaign_criterion['campaignId'], + campaign_criterion['criterion']['id'], + campaign_criterion['criterion']['type'])) + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201809/targeting/add_customer_negative_criteria.py b/examples/adwords/v201809/targeting/add_customer_negative_criteria.py new file mode 100755 index 00000000..17636501 --- /dev/null +++ b/examples/adwords/v201809/targeting/add_customer_negative_criteria.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 adds various types of negative criteria to a customer. + +These criteria will be applied to all campaigns for the customer. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + customer_negative_criterion_service = client.GetService( + 'CustomerNegativeCriterionService', version='v201809') + + criteria = [ + # Exclude tragedy & conflict content. + { + 'xsi_type': 'ContentLabel', + 'contentLabelType': 'TRAGEDY' + }, + # Exclude a specific placement. + { + 'xsi_type': 'Placement', + 'url': 'http://www.example.com' + } + # Additional criteria types are available for this service. See the types + # listed under Criterion here: + # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion + ] + + # Create operations to add each of the criteria above. + operations = [{ + 'operator': 'ADD', + 'operand': { + 'criterion': criterion + } + } for criterion in criteria] + + # Make the mutate request. + result = customer_negative_criterion_service.mutate(operations) + + # Display the resulting campaign criteria. + for negative_criterion in result['value']: + print ('Customer negative criterion with criterion ID "%s", and type "%s" ' + 'was added.' % (negative_criterion['criterion']['id'], + negative_criterion['criterion']['type'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py new file mode 100755 index 00000000..d3abdfa2 --- /dev/null +++ b/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 adds demographic criteria to an ad group. + +To get a list of ad groups, run get_ad_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +GENDER_MALE = '10' +AGE_RANGE_UNDETERMINED = '503999' + +AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' + + +def main(client, ad_group_id): + # Initialize appropriate service. + ad_group_criterion_service = client.GetService( + 'AdGroupCriterionService', version='v201809') + + # Create the ad group criteria. + ad_group_criteria = [ + # Targeting criterion. + { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'Gender', + # Create gender criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/genders. + 'id': GENDER_MALE + } + }, + # Exclusion criterion. + { + 'xsi_type': 'NegativeAdGroupCriterion', + 'adGroupId': ad_group_id, + 'criterion': { + 'xsi_type': 'AgeRange', + # Create age range criteria. The IDs can be found in the + # documentation: + # https://developers.google.com/adwords/api/docs/appendix/ages. + 'id': AGE_RANGE_UNDETERMINED + } + } + ] + + # Create operations. + operations = [] + for criterion in ad_group_criteria: + operations.append({ + 'operator': 'ADD', + 'operand': criterion + }) + + response = ad_group_criterion_service.mutate(operations) + + if response and response['value']: + criteria = response['value'] + for ad_group_criterion in criteria: + criterion = ad_group_criterion['criterion'] + print ('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type "%s" was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) + else: + print 'No criteria were returned.' + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py new file mode 100755 index 00000000..0c19811c --- /dev/null +++ b/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 illustrates how to retrieve all the campaign targets. + +To set campaign targets, run add_campaign_targeting_criteria.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +PAGE_SIZE = 500 + + +def main(client): + # Initialize appropriate service. + campaign_criterion_service = client.GetService( + 'CampaignCriterionService', version='v201809') + + # Construct selector and get all campaign targets. + offset = 0 + selector = { + 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', + 'LanguageName', 'LocationName', 'KeywordText'], + 'predicates': [{ + 'field': 'CriteriaType', + 'operator': 'IN', + 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] + }], + 'paging': { + 'startIndex': str(offset), + 'numberResults': str(PAGE_SIZE) + } + } + more_pages = True + while more_pages: + page = campaign_criterion_service.get(selector) + + # Display results. + if 'entries' in page: + for campaign_criterion in page['entries']: + negative = '' + if (campaign_criterion['CampaignCriterion.Type'] + == 'NegativeCampaignCriterion'): + negative = 'Negative ' + criterion = campaign_criterion['criterion'] + criteria = (criterion['text'] if 'text' in criterion else + criterion['platformName'] if 'platformName' in criterion + else criterion['name'] if 'name' in criterion else + criterion['locationName'] if 'locationName' in criterion + else None) + print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) + else: + print 'No campaign targets were found.' + offset += PAGE_SIZE + selector['paging']['startIndex'] = str(offset) + more_pages = offset < int(page['totalNumEntries']) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py new file mode 100755 index 00000000..7bd17fcf --- /dev/null +++ b/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 all languages and carriers available for targeting. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def main(client): + # Initialize appropriate service. + constant_data_service = client.GetService( + 'ConstantDataService', version='v201809') + + # Get all languages. + languages = constant_data_service.getLanguageCriterion() + + # Display results. + for language in languages: + print ('Language with name "%s" and ID "%s" was found.' + % (language['name'], language['id'])) + + # Get all carriers. + carriers = constant_data_service.getCarrierCriterion() + + # Display results. + for carrier in carriers: + print ('Carrier with name "%s", ID "%s", and country code "%s" was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/examples/adwords/v201809/targeting/lookup_location.py b/examples/adwords/v201809/targeting/lookup_location.py new file mode 100755 index 00000000..10ba7211 --- /dev/null +++ b/examples/adwords/v201809/targeting/lookup_location.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 LocationCriterion. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + +from googleads import adwords + + +def GetLocationString(location): + return '%s (%s)' % (location['locationName'], location['displayType'] + if 'displayType' in location else None) + + +def main(client): + # Initialize appropriate service. + location_criterion_service = client.GetService( + 'LocationCriterionService', version='v201809') + + location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + + # Create the selector. + selector = { + 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', + 'ParentLocations', 'Reach', 'TargetingStatus'], + 'predicates': [{ + 'field': 'LocationName', + 'operator': 'IN', + 'values': location_names + }, { + 'field': 'Locale', + 'operator': 'EQUALS', + 'values': ['en'] + }] + } + + # Make the get request. + location_criteria = location_criterion_service.get(selector) + + # Display the resulting location criteria. + for location_criterion in location_criteria: + parent_string = '' + if ('parentLocations' in location_criterion['location'] + and location_criterion['location']['parentLocations']): + parent_string = ', '.join([GetLocationString(parent)for parent in + location_criterion['location'] + ['parentLocations']]) + print ('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' + % (location_criterion['searchTerm'], + location_criterion['location']['locationName'], + location_criterion['location']['displayType'], parent_string, + location_criterion['reach'] + if 'reach' in location_criterion else None, + location_criterion['location']['id'], + location_criterion['location']['targetingStatus'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client) diff --git a/googleads/adwords.py b/googleads/adwords.py index 5204db1a..f04f0350 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -15,9 +15,9 @@ """Client library for the AdWords API.""" import abc +import codecs from collections import namedtuple import datetime -import io import logging import os import re @@ -26,10 +26,11 @@ import urllib2 from xml.etree import ElementTree -import xmltodict -import yaml import googleads.common import googleads.errors +import six +import xmltodict +import yaml _report_logger = logging.getLogger('%s.%s' % (__name__, 'report_downloader')) @@ -148,6 +149,62 @@ 'TrafficEstimatorService': 'o', 'TrialAsyncErrorService': 'cm', 'TrialService': 'cm' + }, + 'v201809': { + 'AccountLabelService': 'mcm', + 'AdCustomizerFeedService': 'cm', + 'AdGroupAdService': 'cm', + 'AdGroupBidModifierService': 'cm', + 'AdGroupCriterionService': 'cm', + 'AdGroupExtensionSettingService': 'cm', + 'AdGroupFeedService': 'cm', + 'AdGroupService': 'cm', + 'AdParamService': 'cm', + 'AdService': 'cm', + 'AdwordsUserListService': 'rm', + 'AssetService': 'cm', + 'BatchJobService': 'cm', + 'BiddingStrategyService': 'cm', + 'BudgetOrderService': 'billing', + 'BudgetService': 'cm', + 'CampaignBidModifierService': 'cm', + 'CampaignCriterionService': 'cm', + 'CampaignExtensionSettingService': 'cm', + 'CampaignFeedService': 'cm', + 'CampaignGroupPerformanceTargetService': 'cm', + 'CampaignGroupService': 'cm', + 'CampaignService': 'cm', + 'CampaignSharedSetService': 'cm', + 'ConstantDataService': 'cm', + 'ConversionTrackerService': 'cm', + 'CustomAffinityService': 'rm', + 'CustomerExtensionSettingService': 'cm', + 'CustomerFeedService': 'cm', + 'CustomerNegativeCriterionService': 'cm', + 'CustomerService': 'mcm', + 'CustomerSyncService': 'ch', + 'DataService': 'cm', + 'DraftAsyncErrorService': 'cm', + 'DraftService': 'cm', + 'FeedItemService': 'cm', + 'FeedItemTargetService': 'cm', + 'FeedMappingService': 'cm', + 'FeedService': 'cm', + 'LabelService': 'cm', + 'LocationCriterionService': 'cm', + 'ManagedCustomerService': 'mcm', + 'MediaService': 'cm', + 'OfflineCallConversionFeedService': 'cm', + 'OfflineConversionAdjustmentFeedService': 'cm', + 'OfflineConversionFeedService': 'cm', + 'OfflineDataUploadService': 'rm', + 'ReportDefinitionService': 'cm', + 'SharedCriterionService': 'cm', + 'SharedSetService': 'cm', + 'TargetingIdeaService': 'o', + 'TrafficEstimatorService': 'o', + 'TrialAsyncErrorService': 'cm', + 'TrialService': 'cm' } } @@ -1266,13 +1323,28 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], self.proxy_config, self._namespace, self._adwords_client.cache) def _DownloadReportCheckFormat(self, file_format, output): - mode = getattr(output, 'mode', 'w') - is_valid_gzip_mode = 'b' in mode and ('+' in mode or 'w' in mode) - - if (file_format.startswith('GZIPPED_') - and not (is_valid_gzip_mode or isinstance(output, io.BytesIO))): - raise googleads.errors.GoogleAdsValueError('Need to specify a binary' - ' output for GZIPPED formats.') + """Verifies file format compatibility with given output.""" + encoding = getattr(output, 'encoding', None) + + # In Python 2 binary file encoding will be set to None, and StringIO / + # BytesIO instances will not have an encoding attribute. In Python 3, + # binary files don't have an encoding attribute, StringIO instances have an + # encoding set to None, and BytesIO instances lack an encoding attribute. + # As a result, if encoding is ever set, it indicates that the specified + # output is incompatible with GZIPPED formats. + if encoding and file_format.startswith('GZIPPED_'): + raise googleads.errors.GoogleAdsValueError( + 'Need to specify a binary output for GZIPPED formats.') + + # Because Python 3 StringIO instances always have encoding set to None, + # it's necessary to verify that StringIO instances aren't used with GZIPPED + # formats. In Python 2, this wouldn't matter because StringIO instances + # store bytes (appropriate for GZIPPED formats) rather than unicode data. + if six.PY3: + if (file_format.startswith('GZIPPED_') + and isinstance(output, six.StringIO)): + raise googleads.errors.GoogleAdsValueError( + 'Need to specify a binary output for GZIPPED formats.') def DownloadReport(self, report_definition, output=sys.stdout, **kwargs): """Downloads an AdWords report using a report definition. @@ -1552,6 +1624,9 @@ def DownloadReportWithAwql(self, query, file_format, output=sys.stdout, def _DownloadReport(self, post_body, output, **kwargs): """Downloads an AdWords report, writing the contents to the given file. + This will attempt to determine the encoding of the specified output and + read the report with the appropriate StreamReader. + Args: post_body: The contents of the POST request's body as a URL encoded string. @@ -1586,21 +1661,36 @@ def _DownloadReport(self, post_body, output, **kwargs): """ response = None try: - # New response = self._DownloadReportAsStream(post_body, **kwargs) + + # Determine encoding of provided output. + if six.PY3 and isinstance(output, six.StringIO): + encoding = 'utf-8' + else: + encoding = getattr(output, 'encoding', None) + + # If any encoding is found, apply the appropriate StreamReader to the + # response. When reading in chunks, this prevents truncation of multi-byte + # characters; e.g. utf-8. For more details, see: + # https://github.com/googleads/googleads-python-lib/issues/281 + if encoding: + stream_reader = codecs.getreader(encoding) + response = stream_reader(response) + while True: chunk = response.read(_CHUNK_SIZE) if not chunk: break - output.write(chunk.decode('utf-8') if sys.version_info[0] == 3 - and (getattr(output, 'mode', 'w') == 'w' - and not isinstance(output, io.BytesIO)) - else chunk) + output.write(chunk) finally: if response: response.close() def _DownloadReportAsStream(self, post_body, **kwargs): - """Downloads an AdWords report, returning a stream. + """Downloads an AdWords report, returning a stream-like object. + + In Python 2, this will return a urllib2.addinfourl instance. In Python 3, + this will return a http.client.HTTPResponse instance. In either case, + reading from the stream-like object will return binary data. Args: post_body: The contents of the POST request's body as a URL encoded diff --git a/googleads/common.py b/googleads/common.py index dad772e3..e5cda946 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '14.0.0' +VERSION = '14.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 72e764f1..9c893995 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -1784,6 +1784,11 @@ def setUp(self): self.report_downloader = self.GetReportDownloader() self.report_downloader.url_opener = self.opener + test_dir = os.path.dirname(__file__) + with open(os.path.join( + test_dir, 'test_data/unicode_test_data.txt')) as handler: + self.budget_template = handler.read() + def testSetsCustomHeaders(self): class MyOpener(object): @@ -1853,6 +1858,26 @@ def testDownloadReportAsStringWithAwql(self): self.header_handler.GetReportDownloadHeaders.assert_called_once_with( include_zero_impressions=True, use_raw_enum_values=False) + def testDownloadReportWithUnicodeReportDataIssue281(self): + """This test verifies that issue #281 has been resolved. + + https://github.com/googleads/googleads-python-lib/issues/281 + + Intentionally reads in a lot of unicode data with small chunk size to + replicate issue where chunked data read in _DownloadReport on Python 3 + would cause a UnicodeDecodeError if multi-byte character were truncated. + """ + test_dir = os.path.dirname(__file__) + googleads.adwords._CHUNK_SIZE = 10 # Small chunk size used to replicate. + + with mock.patch.object(self.report_downloader, + '_DownloadReportAsStream') as stream: + stream.return_value = open(os.path.join( + test_dir, 'test_data/unicode_test_data.txt'), 'rb') + report_definition = {'downloadFormat': 'CSV'} + s = six.StringIO() + self.report_downloader.DownloadReport(report_definition, output=s) + def testDownloadReportCheckFormat_CSVStringSuccess(self): output_file = six.StringIO() @@ -1863,16 +1888,17 @@ def testDownloadReportCheckFormat_CSVStringSuccess(self): 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDBinaryFileSuccess(self): - output_file = six.StringIO() + output_file = tempfile.TemporaryFile(mode='wb') try: - self.report_downloader._DownloadReportCheckFormat('CSV', output_file) + self.report_downloader._DownloadReportCheckFormat( + 'GZIPPED_CSV', output_file) except googleads.errors.GoogleAdsValueError: self.fail('_DownloadReportCheckFormat raised GoogleAdsValueError' 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDBytesIOSuccess(self): - output_file = tempfile.TemporaryFile(mode='wb') + output_file = six.BytesIO() try: self.report_downloader._DownloadReportCheckFormat('GZIPPED_CSV', @@ -1882,31 +1908,13 @@ def testDownloadReportCheckFormat_GZIPPEDBytesIOSuccess(self): 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDStringFailure(self): - output_file = six.StringIO() - - self.assertRaises(googleads.errors.GoogleAdsValueError, - self.report_downloader._DownloadReportCheckFormat, - 'GZIPPED_CSV', output_file) - - def testDownloadReportCheckFormat_Issue152(self): - output_file = six.StringIO() - output_file.mode = 'w+b' # Verify writing and reading works. - - try: - self.report_downloader._DownloadReportCheckFormat( - 'GZIPPED_CSV', output_file) - except googleads.errors.GoogleAdsValueError: - self.fail('_DownloadReportCheckFormat raised GoogleAdsValueError' - 'unexpectedly!') - - output_file.mode = 'r+b' # Verify reading and writing works. - - try: - self.report_downloader._DownloadReportCheckFormat( - 'GZIPPED_CSV', output_file) - except googleads.errors.GoogleAdsValueError: - self.fail('_DownloadReportCheckFormat raised GoogleAdsValueError' - 'unexpectedly!') + # This would only fail in Python 3, where StringIO is unicode rather than + # bytes. + if six.PY3: + output_file = six.StringIO() + self.assertRaises(googleads.errors.GoogleAdsValueError, + self.report_downloader._DownloadReportCheckFormat, + 'GZIPPED_CSV', output_file) def testDownloadReport_failure(self): output_file = six.StringIO() diff --git a/tests/test_data/unicode_test_data.txt b/tests/test_data/unicode_test_data.txt new file mode 100644 index 00000000..1c1638de --- /dev/null +++ b/tests/test_data/unicode_test_data.txt @@ -0,0 +1,965 @@ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +けけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけけ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿❗ᚖ❗けけけ¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿けけけ¿α¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ω¿ +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +⺎⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺏⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻⺐⸻⸮᠁៷ᚸᚸᚸᚔ¿αἈ¡អĕŀŀⲟ❗ᚖ❗ឃōᚱƚᚦ¡ωᾨ¿ᚔᚸ ᚸᚸ៷᠁⸮⸻ +あいうえおくくくどれみふぁちどけけけすしかかか +¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿¿α¡ĤĕŀŀőŴōřƚƌ¡ω¿ +あいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかかあいうえおくくくどれみふぁちどけけけすしかかか From 1e882141b8eb663b55dd582ce0f4fbf3cd2f672d Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Fri, 21 Sep 2018 16:30:21 -0400 Subject: [PATCH 122/180] Commiting latest changes. From 9592c1680a41ba0a8e52865588640df37a64a6bf Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 15 Nov 2018 15:46:21 -0500 Subject: [PATCH 123/180] googleads Python Client Library v15.0.0 -- 11/14/2018 --- ChangeLog | 11 + ...delete_content_metadata_key_hierarchies.py | 81 ------ .../get_availability_forecast.py | 130 --------- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 2 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 2 +- .../get_all_cdn_configurations.py | 2 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/get_all_content.py | 2 +- .../creative_service/copy_image_creatives.py | 2 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../update_creative_set.py | 2 +- .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 2 +- .../set_line_item_custom_field_value.py | 6 +- .../update_custom_fields.py | 2 +- .../delete_custom_targeting_keys.py | 4 +- .../delete_custom_targeting_values.py | 4 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- ...efined_custom_targeting_keys_and_values.py | 4 +- .../update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../update_exchange_rates.py | 2 +- .../inventory_service/archive_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 4 +- .../get_all_ad_unit_sizes.py | 2 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../label_service/get_active_labels.py | 2 +- .../v201805/label_service/get_all_labels.py | 2 +- .../v201805/label_service/update_labels.py | 2 +- .../deactivate_licas.py | 2 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../update_licas.py | 2 +- .../line_item_service/activate_line_items.py | 2 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 2 +- .../activate_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 2 +- .../update_live_stream_events.py | 2 +- .../get_all_native_styles.py | 2 +- .../v201805/order_service/approve_orders.py | 2 +- .../v201805/order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 2 +- .../v201805/order_service/update_orders.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 2 +- .../placement_service/create_placements.py | 2 +- .../deactivate_placements.py | 2 +- .../get_active_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 2 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 2 +- .../update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 2 +- .../get_active_product_packages.py | 2 +- .../get_all_product_packages.py | 2 +- .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- .../product_service/update_products.py | 2 +- .../activate_product_templates.py | 2 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 2 +- .../archive_proposal_line_items.py | 2 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 2 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_proposals_pending_approval.py | 2 +- .../request_buyers_acceptance.py | 2 +- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 2 +- .../get_recent_changes.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 2 +- ...update_reconciliation_line_item_reports.py | 2 +- ...order_reports_for_reconciliation_report.py | 2 +- .../submit_reconciliation_order_reports.py | 2 +- ...n_report_rows_for_reconciliation_report.py | 2 +- .../update_reconciliation_report_rows.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 2 +- .../report_service/run_delivery_report.py | 2 +- .../report_service/run_inventory_report.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../v201805/report_service/run_saved_query.py | 2 +- .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 2 +- .../v201805/team_service/get_all_teams.py | 2 +- .../v201805/team_service/update_teams.py | 2 +- .../v201805/user_service/deactivate_users.py | 2 +- .../v201805/user_service/get_all_users.py | 2 +- .../user_service/get_user_by_email_address.py | 2 +- .../v201805/user_service/update_users.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py | 2 +- ...et_workflow_external_condition_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 2 +- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 2 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 2 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 2 +- .../update_audience_segments.py | 2 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 2 +- .../get_all_cdn_configurations.py | 2 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 2 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 2 +- ...update_content_metadata_key_hierarchies.py | 2 +- .../content_service/get_all_content.py | 2 +- .../creative_service/copy_image_creatives.py | 2 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../creative_service/update_creatives.py | 2 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../update_creative_set.py | 2 +- .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../deactivate_creative_wrapper.py | 2 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 2 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 2 +- .../set_line_item_custom_field_value.py | 6 +- .../update_custom_fields.py | 2 +- .../delete_custom_targeting_keys.py | 4 +- .../delete_custom_targeting_values.py | 4 +- ...et_all_custom_targeting_keys_and_values.py | 4 +- ...efined_custom_targeting_keys_and_values.py | 4 +- .../update_custom_targeting_keys.py | 2 +- .../update_custom_targeting_values.py | 2 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../update_exchange_rates.py | 2 +- .../inventory_service/archive_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 4 +- .../get_all_ad_unit_sizes.py | 2 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 2 +- .../label_service/deactivate_labels.py | 2 +- .../label_service/get_active_labels.py | 2 +- .../v201808/label_service/get_all_labels.py | 2 +- .../v201808/label_service/update_labels.py | 2 +- .../deactivate_licas.py | 2 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../update_licas.py | 2 +- .../line_item_service/activate_line_items.py | 2 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../line_item_service/pause_line_items.py | 2 +- .../target_custom_criteria.py | 2 +- .../line_item_service/update_line_items.py | 2 +- .../activate_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 2 +- .../update_live_stream_events.py | 2 +- .../get_all_native_styles.py | 2 +- .../v201808/order_service/approve_orders.py | 2 +- .../v201808/order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 2 +- .../v201808/order_service/update_orders.py | 2 +- ...reate_proposal_line_items_from_packages.py | 2 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 2 +- .../placement_service/create_placements.py | 2 +- .../deactivate_placements.py | 2 +- .../get_active_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 2 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 2 +- .../update_premium_rates.py | 2 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 2 +- .../get_active_product_packages.py | 2 +- .../get_all_product_packages.py | 2 +- .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- .../product_service/update_products.py | 2 +- .../activate_product_templates.py | 2 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 2 +- .../archive_proposal_line_items.py | 2 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 2 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_proposals_pending_approval.py | 2 +- .../request_buyers_acceptance.py | 2 +- .../submit_proposals_for_approval.py | 2 +- .../proposal_service/update_proposals.py | 2 +- .../get_recent_changes.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 2 +- ...update_reconciliation_line_item_reports.py | 2 +- ...order_reports_for_reconciliation_report.py | 2 +- .../submit_reconciliation_order_reports.py | 2 +- ...n_report_rows_for_reconciliation_report.py | 2 +- .../update_reconciliation_report_rows.py | 2 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 2 +- .../report_service/run_delivery_report.py | 2 +- .../report_service/run_inventory_report.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../v201808/report_service/run_saved_query.py | 2 +- .../approve_all_suggested_ad_units.py | 2 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 2 +- .../v201808/team_service/get_all_teams.py | 2 +- .../v201808/team_service/update_teams.py | 2 +- .../v201808/user_service/deactivate_users.py | 2 +- .../v201808/user_service/get_all_users.py | 2 +- .../user_service/get_user_by_email_address.py | 2 +- .../v201808/user_service/update_users.py | 2 +- .../delete_user_team_associations.py | 2 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 2 +- .../update_user_team_associations.py | 2 +- .../approve_workflow_approval_requests.py | 2 +- .../get_workflow_approval_requests.py | 2 +- ...et_workflow_external_condition_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 2 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_package_item_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 4 +- .../get_base_rates_for_rate_card.py | 4 +- .../base_rate_service/update_base_rates.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 4 +- ...update_content_metadata_key_hierarchies.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 4 +- .../get_exchange_rates_for_currency_code.py | 4 +- .../update_exchange_rates.py | 4 +- .../get_availability_forecast.py | 251 ++++++++++++++++++ ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 38 ++- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 8 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 4 +- .../package_service/get_all_packages.py | 4 +- .../get_in_progress_packages.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 4 +- .../get_premium_rates_for_rate_card.py | 4 +- .../update_premium_rates.py | 4 +- .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 4 +- ...oduct_package_items_for_product_package.py | 4 +- .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 4 +- .../get_all_product_packages.py | 4 +- .../product_service/__init__.py | 0 .../product_service/get_all_products.py | 4 +- .../get_products_for_product_template.py | 4 +- .../product_service/update_products.py | 4 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 4 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 4 +- .../get_sponsorship_product_templates.py | 4 +- .../update_product_templates.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- ...create_programmatic_proposal_line_items.py | 4 +- ...sal_line_items_for_non_sales_management.py | 15 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 2 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../submit_proposals_for_approval.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 4 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 6 +- .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 4 +- .../get_marketplace_rate_cards.py | 4 +- ..._item_reports_for_reconciliation_report.py | 4 +- ...update_reconciliation_line_item_reports.py | 4 +- ...order_reports_for_reconciliation_report.py | 4 +- .../submit_reconciliation_order_reports.py | 4 +- ...n_report_rows_for_reconciliation_report.py | 4 +- .../update_reconciliation_report_rows.py | 4 +- .../get_all_reconciliation_reports.py | 4 +- ...iliation_report_for_last_billing_period.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 6 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 6 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 4 +- .../get_workflow_approval_requests.py | 4 +- ...et_workflow_external_condition_requests.py | 4 +- ...er_workflow_external_condition_requests.py | 4 +- .../v201802/targeting/lookup_location.py | 2 +- .../v201806/targeting/lookup_location.py | 2 +- .../v201809/targeting/lookup_location.py | 2 +- googleads/ad_manager.py | 91 ++++--- googleads/adwords.py | 4 +- googleads/common.py | 23 +- tests/ad_manager_test.py | 173 +++++++++++- tests/adwords_test.py | 6 +- tests/common_test.py | 56 ++-- 537 files changed, 1240 insertions(+), 981 deletions(-) delete mode 100755 examples/ad_manager/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201802/forecast_service/get_availability_forecast.py rename examples/ad_manager/{v201802 => v201811}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v201802 => v201811}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v201802 => v201811}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v201802 => v201811}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v201802 => v201811}/activity_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v201802 => v201811}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v201802 => v201811}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v201802 => v201811}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v201802 => v201811}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v201802 => v201811}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v201802 => v201811}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v201802 => v201811}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v201802 => v201811}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v201802 => v201811}/base_rate_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/base_rate_service/create_product_base_rates.py (97%) rename examples/ad_manager/{v201802 => v201811}/base_rate_service/create_product_package_item_base_rates.py (99%) rename examples/ad_manager/{v201802 => v201811}/base_rate_service/create_product_template_base_rates.py (98%) rename examples/ad_manager/{v201802 => v201811}/base_rate_service/get_all_base_rates.py (96%) rename examples/ad_manager/{v201802 => v201811}/base_rate_service/get_base_rates_for_rate_card.py (96%) rename examples/ad_manager/{v201802 => v201811}/base_rate_service/update_base_rates.py (96%) rename examples/ad_manager/{v201802 => v201811}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v201802 => v201811}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v201802 => v201811}/company_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/company_service/create_companies.py (99%) rename examples/ad_manager/{v201802 => v201811}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v201802 => v201811}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v201802 => v201811}/company_service/update_companies.py (96%) rename examples/ad_manager/{v201802 => v201811}/contact_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v201802 => v201811}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v201802 => v201811}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v201802 => v201811}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v201802 => v201811}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/ad_manager/{v201802 => v201811}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (94%) rename examples/ad_manager/{v201802 => v201811}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (96%) rename examples/ad_manager/{v201802 => v201811}/content_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/content_service/get_all_content.py (95%) rename examples/ad_manager/{v201802 => v201811}/creative_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v201802 => v201811}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v201802 => v201811}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v201802 => v201811}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v201802 => v201811}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v201802 => v201811}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v201802 => v201811}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v201802 => v201811}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v201802 => v201811}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v201802 => v201811}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v201802 => v201811}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v201802 => v201811}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v201802 => v201811}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v201802 => v201811}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v201802 => v201811}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v201802 => v201811}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v201802 => v201811}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v201802 => v201811}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v201802 => v201811}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v201802 => v201811}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v201802 => v201811}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v201802 => v201811}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v201802 => v201811}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v201802 => v201811}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v201802 => v201811}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v201802 => v201811}/custom_field_service/set_line_item_custom_field_value.py (95%) rename examples/ad_manager/{v201802 => v201811}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v201802 => v201811}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v201802 => v201811}/custom_targeting_service/delete_custom_targeting_keys.py (93%) rename examples/ad_manager/{v201802 => v201811}/custom_targeting_service/delete_custom_targeting_values.py (93%) rename examples/ad_manager/{v201802 => v201811}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (93%) rename examples/ad_manager/{v201802 => v201811}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (93%) rename examples/ad_manager/{v201802 => v201811}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201802 => v201811}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v201802 => v201811}/exchange_rate_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/ad_manager/{v201802 => v201811}/exchange_rate_service/get_all_exchange_rates.py (94%) rename examples/ad_manager/{v201802 => v201811}/exchange_rate_service/get_exchange_rates_for_currency_code.py (94%) rename examples/ad_manager/{v201802 => v201811}/exchange_rate_service/update_exchange_rates.py (95%) create mode 100755 examples/ad_manager/v201811/forecast_service/get_availability_forecast.py rename examples/ad_manager/{v201802 => v201811}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v201802 => v201811}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v201802 => v201811}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v201802 => v201811}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v201802 => v201811}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v201802 => v201811}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v201802 => v201811}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v201802 => v201811}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v201802 => v201811}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v201802 => v201811}/label_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/label_service/create_labels.py (99%) rename examples/ad_manager/{v201802 => v201811}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v201802 => v201811}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v201802 => v201811}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v201802 => v201811}/label_service/update_labels.py (96%) rename examples/ad_manager/{v201802 => v201811}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v201802 => v201811}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v201802 => v201811}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v201802 => v201811}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v201802 => v201811}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/create_video_line_item.py (76%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v201802 => v201811}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v201802 => v201811}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v201802 => v201811}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v201802 => v201811}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v201802 => v201811}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v201802 => v201811}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v201802 => v201811}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/native_style_service/create_native_styles.py (97%) rename examples/ad_manager/{v201802 => v201811}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v201802 => v201811}/network_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v201802 => v201811}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v201802 => v201811}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v201802 => v201811}/order_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v201802 => v201811}/order_service/create_orders.py (99%) rename examples/ad_manager/{v201802 => v201811}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v201802 => v201811}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v201802 => v201811}/order_service/update_orders.py (97%) rename examples/ad_manager/{v201802 => v201811}/package_service/create_packages.py (99%) rename examples/ad_manager/{v201802 => v201811}/package_service/create_proposal_line_items_from_packages.py (96%) rename examples/ad_manager/{v201802 => v201811}/package_service/get_all_packages.py (96%) rename examples/ad_manager/{v201802 => v201811}/package_service/get_in_progress_packages.py (96%) rename examples/ad_manager/{v201802 => v201811}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v201802 => v201811}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v201802 => v201811}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v201802 => v201811}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v201802 => v201811}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v201802 => v201811}/premium_rate_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/premium_rate_service/create_premium_rates.py (97%) rename examples/ad_manager/{v201802 => v201811}/premium_rate_service/get_all_premium_rates.py (94%) rename examples/ad_manager/{v201802 => v201811}/premium_rate_service/get_premium_rates_for_rate_card.py (95%) rename examples/ad_manager/{v201802 => v201811}/premium_rate_service/update_premium_rates.py (95%) rename examples/ad_manager/{v201802 => v201811}/product_package_item_service/create_product_package_item.py (99%) rename examples/ad_manager/{v201802 => v201811}/product_package_item_service/get_all_product_package_items.py (94%) rename examples/ad_manager/{v201802 => v201811}/product_package_item_service/get_product_package_items_for_product_package.py (94%) rename examples/ad_manager/{v201802 => v201811}/product_package_service/create_product_packages.py (96%) rename examples/ad_manager/{v201802 => v201811}/product_package_service/get_active_product_packages.py (94%) rename examples/ad_manager/{v201802 => v201811}/product_package_service/get_all_product_packages.py (94%) rename examples/ad_manager/{v201802 => v201811}/product_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/product_service/get_all_products.py (95%) rename examples/ad_manager/{v201802 => v201811}/product_service/get_products_for_product_template.py (96%) rename examples/ad_manager/{v201802 => v201811}/product_service/update_products.py (96%) rename examples/ad_manager/{v201802 => v201811}/product_template_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/product_template_service/activate_product_templates.py (95%) rename examples/ad_manager/{v201802 => v201811}/product_template_service/create_product_templates.py (97%) rename examples/ad_manager/{v201802 => v201811}/product_template_service/create_programmatic_product_templates.py (96%) rename examples/ad_manager/{v201802 => v201811}/product_template_service/get_all_product_templates.py (94%) rename examples/ad_manager/{v201802 => v201811}/product_template_service/get_sponsorship_product_templates.py (94%) rename examples/ad_manager/{v201802 => v201811}/product_template_service/update_product_templates.py (96%) rename examples/ad_manager/{v201802 => v201811}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v201802 => v201811}/proposal_line_item_service/create_programmatic_proposal_line_items.py (98%) rename examples/ad_manager/{v201802 => v201811}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (88%) rename examples/ad_manager/{v201802 => v201811}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v201802 => v201811}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v201802 => v201811}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v201802 => v201811}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/create_programmatic_proposals.py (99%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (99%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/get_proposals_pending_approval.py (96%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/submit_proposals_for_approval.py (96%) rename examples/ad_manager/{v201802 => v201811}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v201802 => v201811}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v201802 => v201811}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v201802 => v201811}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v201802 => v201811}/publisher_query_language_service/get_geo_targets.py (94%) rename examples/ad_manager/{v201802 => v201811}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v201802 => v201811}/publisher_query_language_service/get_recent_changes.py (97%) rename examples/ad_manager/{v201802 => v201811}/rate_card_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/rate_card_service/create_rate_cards.py (99%) rename examples/ad_manager/{v201802 => v201811}/rate_card_service/get_all_rate_cards.py (95%) rename examples/ad_manager/{v201802 => v201811}/rate_card_service/get_marketplace_rate_cards.py (96%) rename examples/ad_manager/{v201802 => v201811}/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (95%) rename examples/ad_manager/{v201802 => v201811}/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (95%) rename examples/ad_manager/{v201802 => v201811}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (94%) rename examples/ad_manager/{v201802 => v201811}/reconciliation_order_report_service/submit_reconciliation_order_reports.py (95%) rename examples/ad_manager/{v201802 => v201811}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (95%) rename examples/ad_manager/{v201802 => v201811}/reconciliation_report_row_service/update_reconciliation_report_rows.py (95%) rename examples/ad_manager/{v201802 => v201811}/reconciliation_report_service/get_all_reconciliation_reports.py (94%) rename examples/ad_manager/{v201802 => v201811}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (94%) rename examples/ad_manager/{v201802 => v201811}/report_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v201802 => v201811}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v201802 => v201811}/report_service/run_inventory_report.py (95%) rename examples/ad_manager/{v201802 => v201811}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v201802 => v201811}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v201802 => v201811}/report_service/run_report_with_custom_fields.py (95%) rename examples/ad_manager/{v201802 => v201811}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v201802 => v201811}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v201802 => v201811}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v201802 => v201811}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v201802 => v201811}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v201802 => v201811}/team_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/team_service/create_teams.py (99%) rename examples/ad_manager/{v201802 => v201811}/team_service/get_all_teams.py (96%) rename examples/ad_manager/{v201802 => v201811}/team_service/update_teams.py (97%) rename examples/ad_manager/{v201802 => v201811}/user_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/user_service/create_users.py (99%) rename examples/ad_manager/{v201802 => v201811}/user_service/deactivate_users.py (97%) rename examples/ad_manager/{v201802 => v201811}/user_service/get_all_roles.py (100%) rename examples/ad_manager/{v201802 => v201811}/user_service/get_all_users.py (96%) rename examples/ad_manager/{v201802 => v201811}/user_service/get_current_user.py (99%) rename examples/ad_manager/{v201802 => v201811}/user_service/get_user_by_email_address.py (96%) rename examples/ad_manager/{v201802 => v201811}/user_service/update_users.py (96%) rename examples/ad_manager/{v201802 => v201811}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v201802 => v201811}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v201802 => v201811}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v201802 => v201811}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v201802 => v201811}/user_team_association_service/update_user_team_associations.py (96%) rename examples/ad_manager/{v201802 => v201811}/workflow_request_service/__init__.py (100%) rename examples/ad_manager/{v201802 => v201811}/workflow_request_service/approve_workflow_approval_requests.py (95%) rename examples/ad_manager/{v201802 => v201811}/workflow_request_service/get_workflow_approval_requests.py (94%) rename examples/ad_manager/{v201802 => v201811}/workflow_request_service/get_workflow_external_condition_requests.py (94%) rename examples/ad_manager/{v201802 => v201811}/workflow_request_service/trigger_workflow_external_condition_requests.py (95%) diff --git a/ChangeLog b/ChangeLog index 25c13437..4f79c5e5 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,14 @@ +15.0.0 -- 11/14/2018 +* Added support for v201811. +* Removed support for v201711. +* Removed examples for v201802. +* Remove ContentMetadataKeyHierarchyService +* Added version parameter to PQL utilities to account for statement + differences among API versions. This parameter defaults to the most recent + API version. If you update your Python client library but don't plan on + migrating to the newest API version, you might need to explicitly declare the + version for the PQL utility to use. + 14.1.0 -- 09/21/18 * Added support and examples for AdWords v201809. * Resolved issues: diff --git a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py b/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py deleted file mode 100755 index e46667e6..00000000 --- a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/delete_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example deletes content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the content metadata key hierarchy to delete. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') - - -def main(client, content_metadata_key_hierarchy_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201802') - - # Create a query to select a single content metadata key hierarchy. - - statement = (ad_manager.StatementBuilder() - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) - .Limit(1)) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())[0]) - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - # Display results. - if content_metadata_key_hierarchies: - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with ID "%s" and name "%s" ' - 'will be deleted.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - # Perform action. - result = (content_metadata_key_hierarchy_service - .performContentMetadataKeyHierarchyAction( - {'type': 'DeleteContentMetadataKeyHierarchies'}, - statement.ToStatement()))[0] - - # Display results. - print ('Number of content metadata key hierarchies deleted: %s' % - result['numChanges']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID) diff --git a/examples/ad_manager/v201802/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201802/forecast_service/get_availability_forecast.py deleted file mode 100755 index ad2a9446..00000000 --- a/examples/ad_manager/v201802/forecast_service/get_availability_forecast.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 a forecast for a prospective line item. - -The prospective line item targets the entire network. The targeting can be -modified to determine forecasts for other criteria such as custom criteria -targeting (in addition to targeting the whole network). See -create_line_items.py for an example of how to create more complex targeting. - -""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set the ID of the advertiser (company) to forecast for. Setting an advertiser -# will cause the forecast to apply the appropriate unified blocking rules. -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201802') - network_service = client.GetService('NetworkService', version='v201802') - - # get the root ad unit ID to target the entire network. - root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime += datetime.timedelta(days=30) - - # Create prospective line item. - line_item = { - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': [ - { - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id, - } - ] - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '300', - 'height': '250' - } - }, - { - 'size': { - 'width': '120', - 'height': '600' - } - } - ], - 'lineItemType': 'SPONSORSHIP', - 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': end_datetime, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'DAILY' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'EVEN', - 'discountType': 'PERCENTAGE', - } - - prospective_line_item = { - 'lineItem': line_item, - 'advertiserId': advertiser_id - } - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - 'includeTargetingCriteriaBreakdown': True, - } - - # Get forecast. - forecast = forecast_service.getAvailabilityForecast( - prospective_line_item, forecast_options) - matched = long(forecast['matchedUnits']) - available_units = long(forecast['availableUnits']) - - if matched > 0: - available_percent = (float(available_units) / matched) * 100. - else: - available_percent = 0 - - contending_line_items = getattr(forecast, 'contentingLineItems', []) - - # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) - - if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py index a3d900a4..5bae3c98 100755 --- a/examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py @@ -25,7 +25,7 @@ def main(client): activity_group_service = client.GetService( 'ActivityGroupService', version='v201805') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py index 16c4d419..37155c24 100755 --- a/examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py @@ -26,7 +26,7 @@ def main(client): 'ActivityGroupService', version='v201805') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201805/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201805/activity_group_service/update_activity_groups.py index 84284c18..3d38ce60 100755 --- a/examples/ad_manager/v201805/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201805/activity_group_service/update_activity_groups.py @@ -40,7 +40,7 @@ def main(client, activity_group_id, advertiser_company_id): version='v201805') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', long(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/activity_service/get_active_activities.py b/examples/ad_manager/v201805/activity_service/get_active_activities.py index 0f30e0dd..6d2e25a7 100755 --- a/examples/ad_manager/v201805/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201805/activity_service/get_active_activities.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. activity_service = client.GetService('ActivityService', version='v201805') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/activity_service/get_all_activities.py b/examples/ad_manager/v201805/activity_service/get_all_activities.py index deff00c7..e22d1a25 100755 --- a/examples/ad_manager/v201805/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201805/activity_service/get_all_activities.py @@ -25,7 +25,7 @@ def main(client): activity_service = client.GetService('ActivityService', version='v201805') # Create a statement to select activities. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201805/activity_service/update_activities.py b/examples/ad_manager/v201805/activity_service/update_activities.py index 2f905724..d953e14e 100755 --- a/examples/ad_manager/v201805/activity_service/update_activities.py +++ b/examples/ad_manager/v201805/activity_service/update_activities.py @@ -38,7 +38,7 @@ def main(client, activity_id): activity_service = client.GetService('ActivityService', version='v201805') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :activityId') .WithBindVariable('activityId', long(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py index 791c402d..70d8b9a1 100755 --- a/examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py @@ -26,7 +26,7 @@ def main(client): 'AudienceSegmentService', version='v201805') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py index 79d0c886..96373dd5 100755 --- a/examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py @@ -25,7 +25,7 @@ def main(client): audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201805') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py index 9a80a617..91144dbb 100755 --- a/examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py @@ -33,7 +33,7 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201805') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) diff --git a/examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py index 7401f4aa..8aba8fd6 100755 --- a/examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py @@ -32,7 +32,7 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201805') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) diff --git a/examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py index 3e11527d..8d50840d 100755 --- a/examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py @@ -25,7 +25,7 @@ def main(client): base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a statement to select base rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py index a127363c..ee04c0cb 100755 --- a/examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py @@ -26,7 +26,7 @@ def main(client, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a statement to select base rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) diff --git a/examples/ad_manager/v201805/base_rate_service/update_base_rates.py b/examples/ad_manager/v201805/base_rate_service/update_base_rates.py index aa4dcb74..db4d943b 100755 --- a/examples/ad_manager/v201805/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201805/base_rate_service/update_base_rates.py @@ -32,7 +32,7 @@ def main(client, base_rate_id): base_rate_service = client.GetService('BaseRateService', version='v201805') # Create a filter statement for base rates for a single rate card. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py index fcc753f9..949bd7bd 100755 --- a/examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py @@ -29,7 +29,7 @@ def main(client): version='v201805') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v201805/company_service/get_advertisers.py b/examples/ad_manager/v201805/company_service/get_advertisers.py index fd0510a2..8411ae72 100755 --- a/examples/ad_manager/v201805/company_service/get_advertisers.py +++ b/examples/ad_manager/v201805/company_service/get_advertisers.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. company_service = client.GetService('CompanyService', version='v201805') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201805/company_service/get_all_companies.py b/examples/ad_manager/v201805/company_service/get_all_companies.py index df59fc3c..9a12a342 100755 --- a/examples/ad_manager/v201805/company_service/get_all_companies.py +++ b/examples/ad_manager/v201805/company_service/get_all_companies.py @@ -25,7 +25,7 @@ def main(client): company_service = client.GetService('CompanyService', version='v201805') # Create a statement to select companies. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201805/company_service/update_companies.py b/examples/ad_manager/v201805/company_service/update_companies.py index 957dabad..b67834af 100755 --- a/examples/ad_manager/v201805/company_service/update_companies.py +++ b/examples/ad_manager/v201805/company_service/update_companies.py @@ -38,7 +38,7 @@ def main(client, company_id): company_service = client.GetService('CompanyService', version='v201805') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', long(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/contact_service/get_all_contacts.py b/examples/ad_manager/v201805/contact_service/get_all_contacts.py index 1c0d73de..6f182040 100755 --- a/examples/ad_manager/v201805/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201805/contact_service/get_all_contacts.py @@ -25,7 +25,7 @@ def main(client): contact_service = client.GetService('ContactService', version='v201805') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py index 2bcdb219..e7fa5388 100755 --- a/examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. contact_service = client.GetService('ContactService', version='v201805') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201805/contact_service/update_contacts.py b/examples/ad_manager/v201805/contact_service/update_contacts.py index 5d3082af..4cbb1513 100755 --- a/examples/ad_manager/v201805/contact_service/update_contacts.py +++ b/examples/ad_manager/v201805/contact_service/update_contacts.py @@ -38,7 +38,7 @@ def main(client, contact_id): contact_service = client.GetService('ContactService', version='v201805') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', long(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index e00064e8..d28d0838 100755 --- a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -26,7 +26,7 @@ def main(client): 'ContentMetadataKeyHierarchyService', version='v201805') # Create a statement to select content metadata key hierarchies. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been diff --git a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 5d085c9b..6f99f097 100755 --- a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -46,7 +46,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Create a query to select a single content metadata key hierarchy. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) diff --git a/examples/ad_manager/v201805/content_service/get_all_content.py b/examples/ad_manager/v201805/content_service/get_all_content.py index e8f11b2d..d2cfc740 100755 --- a/examples/ad_manager/v201805/content_service/get_all_content.py +++ b/examples/ad_manager/v201805/content_service/get_all_content.py @@ -25,7 +25,7 @@ def main(client): content_service = client.GetService('ContentService', version='v201805') # Create a statement to select content. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v201805/creative_service/copy_image_creatives.py b/examples/ad_manager/v201805/creative_service/copy_image_creatives.py index 5ddf9440..fdc9d1ca 100755 --- a/examples/ad_manager/v201805/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201805/creative_service/copy_image_creatives.py @@ -31,7 +31,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201805/creative_service/get_all_creatives.py b/examples/ad_manager/v201805/creative_service/get_all_creatives.py index 8aa94024..61f95466 100755 --- a/examples/ad_manager/v201805/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201805/creative_service/get_all_creatives.py @@ -25,7 +25,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201805/creative_service/get_image_creatives.py b/examples/ad_manager/v201805/creative_service/get_image_creatives.py index 8be25a8f..79ecfd06 100755 --- a/examples/ad_manager/v201805/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201805/creative_service/get_image_creatives.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. creative_service = client.GetService('CreativeService', version='v201805') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201805/creative_service/update_creatives.py b/examples/ad_manager/v201805/creative_service/update_creatives.py index 1f872e82..690f81b0 100755 --- a/examples/ad_manager/v201805/creative_service/update_creatives.py +++ b/examples/ad_manager/v201805/creative_service/update_creatives.py @@ -37,7 +37,7 @@ def main(client, image_creative_id): creative_service = client.GetService('CreativeService', version='v201805') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', long(image_creative_id)) diff --git a/examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py index d3be43e0..74a63a41 100755 --- a/examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py @@ -26,7 +26,7 @@ def main(client): 'CreativeSetService', version='v201805') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py index 159a4e09..2c06b55a 100755 --- a/examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py @@ -27,7 +27,7 @@ def main(client, master_creative_id): creative_set_service = client.GetService( 'CreativeSetService', version='v201805') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201805/creative_set_service/update_creative_set.py b/examples/ad_manager/v201805/creative_set_service/update_creative_set.py index 9e7192fc..3235512f 100755 --- a/examples/ad_manager/v201805/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201805/creative_set_service/update_creative_set.py @@ -40,7 +40,7 @@ def main(client, creative_set_id, companion_creative_id): version='v201805') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', long(creative_set_id))) diff --git a/examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py index 01b63822..444946db 100755 --- a/examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py @@ -26,7 +26,7 @@ def main(client): 'CreativeTemplateService', version='v201805') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py index fd9ee65c..ac4b59d1 100755 --- a/examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py @@ -25,7 +25,7 @@ def main(client): creative_template_service = client.GetService( 'CreativeTemplateService', version='v201805') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py index 65f25bb7..6681de03 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py @@ -36,7 +36,7 @@ def main(client, label_id): version='v201805') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', long(label_id))) diff --git a/examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py index 32f192a5..c0c01a29 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py @@ -25,7 +25,7 @@ def main(client): creative_wrapper_service = client.GetService( 'CreativeWrapperService', version='v201805') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py index b9a82dc5..cc2388e7 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py @@ -26,7 +26,7 @@ def main(client): 'CreativeWrapperService', version='v201805') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py index bb2d3da4..d05997d2 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py @@ -39,7 +39,7 @@ def main(client, creative_wrapper_id): version='v201805') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', long(creative_wrapper_id))) diff --git a/examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py index 88218140..5840d059 100755 --- a/examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -37,7 +37,7 @@ def main(client): # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py index 7d5c7abb..61592434 100755 --- a/examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py @@ -26,7 +26,7 @@ def main(client): 'CustomFieldService', version='v201805') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py index 85ca070e..ef066a48 100755 --- a/examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py @@ -25,7 +25,7 @@ def main(client): custom_field_service = client.GetService( 'CustomFieldService', version='v201805') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py index f6d8f158..b391912b 100755 --- a/examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py @@ -47,7 +47,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, line_item_service = client.GetService('LineItemService', version='v201805') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder() + custom_field_statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder() + ad_manager.StatementBuilder(version='v201805') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder() + line_item_statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201805/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201805/custom_field_service/update_custom_fields.py index b5859303..6063a673 100755 --- a/examples/ad_manager/v201805/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201805/custom_field_service/update_custom_fields.py @@ -39,7 +39,7 @@ def main(client, custom_field_id): 'CustomFieldService', version='v201805') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :customFieldId') .WithBindVariable('customFieldId', long(custom_field_id))) diff --git a/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py index a5d88ff2..2710e977 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py @@ -38,7 +38,7 @@ def main(client, key_name): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201805') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder() + key_statement = (ad_manager.StatementBuilder(version='v201805') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py index a8819e90..c2bc4526 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py @@ -38,7 +38,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201805') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder() + value_statement = (ad_manager.StatementBuilder(version='v201805') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index ba893e2c..9b7e0504 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201805') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder() + targeting_key_statement = ad_manager.StatementBuilder(version='v201805') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index f2e312ab..4bae3542 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201805') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder() + targeting_key_statement = (ad_manager.StatementBuilder(version='v201805') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py index bc7f113a..3fd9c256 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py @@ -32,7 +32,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201805') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :keyId') .WithBindVariable('keyId', long(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py index 542c90bc..e5858db8 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py @@ -32,7 +32,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201805') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', long(key_id))) diff --git a/examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py index 323f3c5c..92b95a39 100755 --- a/examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py @@ -26,7 +26,7 @@ def main(client): 'ExchangeRateService', version='v201805') # Create a statement to select exchange rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py index b34d11c6..5e10e96f 100755 --- a/examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -27,7 +27,7 @@ def main(client, currency_code): exchange_rate_service = client.GetService( 'ExchangeRateService', version='v201805') # Create a statement to select exchange rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('currencyCode = :currencyCode') .WithBindVariable('currencyCode', currency_code)) diff --git a/examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py index 0462fd66..71eb35a8 100755 --- a/examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py @@ -33,7 +33,7 @@ def main(client, exchange_rate_id): version='v201805') # Create a statement to get an exchange rate by its ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', long(exchange_rate_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/inventory_service/archive_ad_units.py b/examples/ad_manager/v201805/inventory_service/archive_ad_units.py index 337c2778..a02e530e 100755 --- a/examples/ad_manager/v201805/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/archive_ad_units.py @@ -39,7 +39,7 @@ def main(client, parent_id): # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', long(parent_id))) diff --git a/examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py index 0545e61f..b32d9731 100755 --- a/examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py @@ -32,7 +32,7 @@ def main(client): root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py index 5b780c5b..ab6b3f21 100755 --- a/examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py @@ -26,7 +26,7 @@ def main(client): 'InventoryService', version='v201805') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201805/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201805/inventory_service/get_all_ad_units.py index 4e6bc325..ae462b25 100755 --- a/examples/ad_manager/v201805/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/get_all_ad_units.py @@ -25,7 +25,7 @@ def main(client): ad_unit_service = client.GetService('InventoryService', version='v201805') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py index f9d22de4..37f23fea 100755 --- a/examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py @@ -31,7 +31,7 @@ def main(client): parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201805/inventory_service/update_ad_units.py b/examples/ad_manager/v201805/inventory_service/update_ad_units.py index 5e0a3b7c..81ad312b 100755 --- a/examples/ad_manager/v201805/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201805/inventory_service/update_ad_units.py @@ -39,7 +39,7 @@ def main(client, ad_unit_id): inventory_service = client.GetService('InventoryService', version='v201805') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201805/label_service/deactivate_labels.py b/examples/ad_manager/v201805/label_service/deactivate_labels.py index 278c05b9..57fdacad 100755 --- a/examples/ad_manager/v201805/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201805/label_service/deactivate_labels.py @@ -30,7 +30,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201805/label_service/get_active_labels.py b/examples/ad_manager/v201805/label_service/get_active_labels.py index 57ee3bbf..ea5b51dd 100755 --- a/examples/ad_manager/v201805/label_service/get_active_labels.py +++ b/examples/ad_manager/v201805/label_service/get_active_labels.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201805') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201805/label_service/get_all_labels.py b/examples/ad_manager/v201805/label_service/get_all_labels.py index 615234b7..9d04ace1 100755 --- a/examples/ad_manager/v201805/label_service/get_all_labels.py +++ b/examples/ad_manager/v201805/label_service/get_all_labels.py @@ -25,7 +25,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201805') # Create a statement to select labels. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201805/label_service/update_labels.py b/examples/ad_manager/v201805/label_service/update_labels.py index 643540e2..aa6f4243 100755 --- a/examples/ad_manager/v201805/label_service/update_labels.py +++ b/examples/ad_manager/v201805/label_service/update_labels.py @@ -32,7 +32,7 @@ def main(client, label_id): label_service = client.GetService('LabelService', version='v201805') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :labelId') .WithBindVariable('labelId', long(label_id))) diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py index 7b9a12f6..efbafe02 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py @@ -33,7 +33,7 @@ def main(client, line_item_id): 'LineItemCreativeAssociationService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', long(line_item_id))) diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py index 9915aa93..17dfd485 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py @@ -26,7 +26,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201805') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py index 838a4fe8..187383b0 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py @@ -27,7 +27,7 @@ def main(client, line_item_id): lica_service = client.GetService( 'LineItemCreativeAssociationService', version='v201805') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py index 8a07ab8d..cd82fc0b 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py @@ -31,7 +31,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201805') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201805/line_item_service/activate_line_items.py b/examples/ad_manager/v201805/line_item_service/activate_line_items.py index d7306953..dcb9f64f 100755 --- a/examples/ad_manager/v201805/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/activate_line_items.py @@ -36,7 +36,7 @@ def main(client, order_id): line_item_service = client.GetService('LineItemService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201805/line_item_service/get_all_line_items.py b/examples/ad_manager/v201805/line_item_service/get_all_line_items.py index 1ac84fe7..981681a3 100755 --- a/examples/ad_manager/v201805/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/get_all_line_items.py @@ -25,7 +25,7 @@ def main(client): line_item_service = client.GetService('LineItemService', version='v201805') # Create a statement to select line items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py index 172398a8..c269080f 100755 --- a/examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. line_item_service = client.GetService('LineItemService', version='v201805') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py index 62d12cbb..d941e768 100755 --- a/examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py @@ -32,7 +32,7 @@ def main(client): - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201805/line_item_service/pause_line_items.py b/examples/ad_manager/v201805/line_item_service/pause_line_items.py index c6755cc5..468e5f0a 100755 --- a/examples/ad_manager/v201805/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/pause_line_items.py @@ -33,7 +33,7 @@ def main(client): # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201805/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201805/line_item_service/target_custom_criteria.py index 7fdf5c5e..4cded881 100755 --- a/examples/ad_manager/v201805/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201805/line_item_service/target_custom_criteria.py @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :lineItemId') .WithBindVariable('lineItemId', long(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/line_item_service/update_line_items.py b/examples/ad_manager/v201805/line_item_service/update_line_items.py index e01c07ac..6f36b5c8 100755 --- a/examples/ad_manager/v201805/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201805/line_item_service/update_line_items.py @@ -33,7 +33,7 @@ def main(client, order_id): # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', long(order_id)) diff --git a/examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py index 05844796..08e8cffc 100755 --- a/examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py @@ -29,7 +29,7 @@ def main(client, live_stream_event_id): 'LiveStreamEventService', version='v201805') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py index f95f0934..90272a90 100755 --- a/examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py @@ -27,7 +27,7 @@ def main(client): 'LiveStreamEventService', version='v201805') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py index 214a2e2f..6e33f326 100755 --- a/examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py @@ -32,7 +32,7 @@ def main(client, live_stream_event_id): 'LiveStreamEventService', version='v201805') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('Id = :id')) .WithBindVariable('id', long(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201805/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201805/native_style_service/get_all_native_styles.py index e3f0bfc7..5ff6624b 100755 --- a/examples/ad_manager/v201805/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201805/native_style_service/get_all_native_styles.py @@ -26,7 +26,7 @@ def main(client): version='v201805') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201805/order_service/approve_orders.py b/examples/ad_manager/v201805/order_service/approve_orders.py index 4f10e7d8..b173e3d8 100755 --- a/examples/ad_manager/v201805/order_service/approve_orders.py +++ b/examples/ad_manager/v201805/order_service/approve_orders.py @@ -32,7 +32,7 @@ def main(client): # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201805/order_service/get_all_orders.py b/examples/ad_manager/v201805/order_service/get_all_orders.py index 98acbc6e..24290f92 100755 --- a/examples/ad_manager/v201805/order_service/get_all_orders.py +++ b/examples/ad_manager/v201805/order_service/get_all_orders.py @@ -25,7 +25,7 @@ def main(client): order_service = client.GetService('OrderService', version='v201805') # Create a statement to select orders. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201805/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201805/order_service/get_orders_starting_soon.py index d84a287c..af135d41 100755 --- a/examples/ad_manager/v201805/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201805/order_service/get_orders_starting_soon.py @@ -31,7 +31,7 @@ def main(client): soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201805/order_service/update_orders.py b/examples/ad_manager/v201805/order_service/update_orders.py index 380fe155..f7e4d1d6 100755 --- a/examples/ad_manager/v201805/order_service/update_orders.py +++ b/examples/ad_manager/v201805/order_service/update_orders.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :orderId') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py index 33c4ce4b..6356c1c6 100755 --- a/examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py @@ -31,7 +31,7 @@ def main(client): package_service = client.GetService('PackageService', version='v201805') # Create a statement to select the single package. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/package_service/get_all_packages.py b/examples/ad_manager/v201805/package_service/get_all_packages.py index adcc425e..947bbf71 100755 --- a/examples/ad_manager/v201805/package_service/get_all_packages.py +++ b/examples/ad_manager/v201805/package_service/get_all_packages.py @@ -25,7 +25,7 @@ def main(client): pkg_service = client.GetService('PackageService', version='v201805') # Create a statement to select packages. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/ad_manager/v201805/package_service/get_in_progress_packages.py b/examples/ad_manager/v201805/package_service/get_in_progress_packages.py index 9dd55abe..1093281b 100755 --- a/examples/ad_manager/v201805/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201805/package_service/get_in_progress_packages.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. pkg_service = client.GetService('PackageService', version='v201805') # Create a statement to select packages. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status') .WithBindVariable('status', 'IN_PROGRESS')) diff --git a/examples/ad_manager/v201805/placement_service/create_placements.py b/examples/ad_manager/v201805/placement_service/create_placements.py index 512b9b98..4940aed9 100755 --- a/examples/ad_manager/v201805/placement_service/create_placements.py +++ b/examples/ad_manager/v201805/placement_service/create_placements.py @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201805/placement_service/deactivate_placements.py b/examples/ad_manager/v201805/placement_service/deactivate_placements.py index 4cce8607..7b031b54 100755 --- a/examples/ad_manager/v201805/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201805/placement_service/deactivate_placements.py @@ -31,7 +31,7 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :placementId') .WithBindVariable('placementId', long(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/placement_service/get_active_placements.py b/examples/ad_manager/v201805/placement_service/get_active_placements.py index e325526b..15c8fa98 100755 --- a/examples/ad_manager/v201805/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201805/placement_service/get_active_placements.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. placement_service = client.GetService('PlacementService', version='v201805') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/placement_service/get_all_placements.py b/examples/ad_manager/v201805/placement_service/get_all_placements.py index 1667ef15..99785473 100755 --- a/examples/ad_manager/v201805/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201805/placement_service/get_all_placements.py @@ -25,7 +25,7 @@ def main(client): placement_service = client.GetService('PlacementService', version='v201805') # Create a statement to select placements. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201805/placement_service/update_placements.py b/examples/ad_manager/v201805/placement_service/update_placements.py index 3c2087e8..c66a8f8b 100755 --- a/examples/ad_manager/v201805/placement_service/update_placements.py +++ b/examples/ad_manager/v201805/placement_service/update_placements.py @@ -31,7 +31,7 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py index 103e01b0..d4c6a8ed 100755 --- a/examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py @@ -26,7 +26,7 @@ def main(client): 'PremiumRateService', version='v201805') # Create a statement to select premium rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py index 447d0dc0..fd67b3c0 100755 --- a/examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py @@ -27,7 +27,7 @@ def main(client, rate_card_id): premium_rate_service = client.GetService( 'PremiumRateService', version='v201805') # Create a statement to select premium rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) diff --git a/examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py index 68c26b5e..5180551f 100755 --- a/examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py @@ -33,7 +33,7 @@ def main(client, premium_rate_id): version='v201805') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(premium_rate_id)) diff --git a/examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py index dc729e92..f74613d0 100755 --- a/examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageItemService', version='v201805') # Create a statement to select product package items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py index e813765c..a694e7fd 100755 --- a/examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py @@ -27,7 +27,7 @@ def main(client, product_package_id): product_package_item_service = client.GetService( 'ProductPackageItemService', version='v201805') # Create a statement to select product package items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('productPackageId = :productPackageId') .WithBindVariable('productPackageId', product_package_id)) diff --git a/examples/ad_manager/v201805/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201805/product_package_service/get_active_product_packages.py index d4bfabfa..c252ea98 100755 --- a/examples/ad_manager/v201805/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201805/product_package_service/get_active_product_packages.py @@ -25,7 +25,7 @@ def main(client): product_package_service = client.GetService( 'ProductPackageService', version='v201805') # Create a statement to select product packages. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201805/product_package_service/get_all_product_packages.py index cdfb079a..7f550a79 100755 --- a/examples/ad_manager/v201805/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201805/product_package_service/get_all_product_packages.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageService', version='v201805') # Create a statement to select product packages. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/ad_manager/v201805/product_service/get_all_products.py b/examples/ad_manager/v201805/product_service/get_all_products.py index 6a2c765b..bf38d449 100755 --- a/examples/ad_manager/v201805/product_service/get_all_products.py +++ b/examples/ad_manager/v201805/product_service/get_all_products.py @@ -25,7 +25,7 @@ def main(client): product_service = client.GetService('ProductService', version='v201805') # Create a statement to select products. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/ad_manager/v201805/product_service/get_products_for_product_template.py b/examples/ad_manager/v201805/product_service/get_products_for_product_template.py index be88fe10..4b2c7773 100755 --- a/examples/ad_manager/v201805/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201805/product_service/get_products_for_product_template.py @@ -27,7 +27,7 @@ def main(client, product_template_id): product_service = client.GetService('ProductService', version='v201805') # Create a statement to select products. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('productTemplateId = :productTemplateId') .WithBindVariable('productTemplateId', product_template_id)) diff --git a/examples/ad_manager/v201805/product_service/update_products.py b/examples/ad_manager/v201805/product_service/update_products.py index ecb757bc..9d8b257a 100755 --- a/examples/ad_manager/v201805/product_service/update_products.py +++ b/examples/ad_manager/v201805/product_service/update_products.py @@ -32,7 +32,7 @@ def main(client, product_id): product_service = client.GetService('ProductService', version='v201805') # Create statement object to select a single product by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', long(product_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/product_template_service/activate_product_templates.py b/examples/ad_manager/v201805/product_template_service/activate_product_templates.py index 073b28b1..658be073 100755 --- a/examples/ad_manager/v201805/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/activate_product_templates.py @@ -34,7 +34,7 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', long(product_template_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201805/product_template_service/get_all_product_templates.py index 98ec8e8f..e1c968d4 100755 --- a/examples/ad_manager/v201805/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/get_all_product_templates.py @@ -26,7 +26,7 @@ def main(client): 'ProductTemplateService', version='v201805') # Create a statement to select product templates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py index be96c091..bce68e6f 100755 --- a/examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py @@ -25,7 +25,7 @@ def main(client): product_template_service = client.GetService( 'ProductTemplateService', version='v201805') # Create a statement to select product templates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('lineItemType = :lineItemType') .WithBindVariable('lineItemType', 'SPONSORSHIP')) diff --git a/examples/ad_manager/v201805/product_template_service/update_product_templates.py b/examples/ad_manager/v201805/product_template_service/update_product_templates.py index 56109f0f..b79cbcef 100755 --- a/examples/ad_manager/v201805/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201805/product_template_service/update_product_templates.py @@ -33,7 +33,7 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201805') # Create a statement to select a single product template by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(product_template_id)) diff --git a/examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py index 0740b6c6..1566c1da 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py @@ -34,7 +34,7 @@ def main(client, proposal_line_item_id): 'ProposalLineItemService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py index 25471ee2..28cf4be5 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py @@ -26,7 +26,7 @@ def main(client): 'ProposalLineItemService', version='v201805') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 771d0771..319c1fc4 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -27,7 +27,7 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( 'ProposalLineItemService', version='v201805') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py index 96839e50..46390d4f 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py @@ -35,7 +35,7 @@ def main(client, proposal_line_item_id): # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/proposal_service/get_all_proposals.py b/examples/ad_manager/v201805/proposal_service/get_all_proposals.py index 8a023971..0f235db4 100755 --- a/examples/ad_manager/v201805/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201805/proposal_service/get_all_proposals.py @@ -25,7 +25,7 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201805') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py index b28d04cf..8b378510 100755 --- a/examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. proposal_service = client.GetService('ProposalService', version='v201805') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('status = :status') .WithBindVariable('status', 'PENDING_APPROVAL')) diff --git a/examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py index 9af78bce..9462df80 100755 --- a/examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py @@ -29,7 +29,7 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py index 7b946b15..98305b25 100755 --- a/examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py @@ -31,7 +31,7 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 diff --git a/examples/ad_manager/v201805/proposal_service/update_proposals.py b/examples/ad_manager/v201805/proposal_service/update_proposals.py index 9dfdd4d5..9c2cc804 100755 --- a/examples/ad_manager/v201805/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201805/proposal_service/update_proposals.py @@ -32,7 +32,7 @@ def main(client, proposal_id): # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :proposalId') .WithBindVariable('proposalId', long(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py index 19239f2e..71ef6235 100755 --- a/examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py index 271a03d4..c344d746 100755 --- a/examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py @@ -25,7 +25,7 @@ def main(client): rate_card_service = client.GetService('RateCardService', version='v201805') # Create a statement to select rate cards. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py index 0258ee75..971cbc0b 100755 --- a/examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. rate_card_service = client.GetService('RateCardService', version='v201805') # Create a statement to select rate cards. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('forMarketplace = :forMarketplace') .WithBindVariable('forMarketplace', True)) diff --git a/examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index a9a5d47f..7cf68312 100755 --- a/examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -33,7 +33,7 @@ def main(client): 'ReconciliationLineItemReportService', version='v201805')) # Create a statement to select reconciliation line item reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('reconciliationReportId = :reconciliationReportId AND ' 'lineItemId != :lineItemId')) .OrderBy('lineItemId', ascending=True) diff --git a/examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 8b07cbdc..88e67bf9 100755 --- a/examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -33,7 +33,7 @@ def main(client): 'ReconciliationLineItemReportService', version='v201805')) # Create a statement to select a reconciliation line item report. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :lineItemReportId') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index bfbddf81..0f80ca96 100755 --- a/examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -27,7 +27,7 @@ def main(client, reconciliation_report_id): reconciliation_order_report_service = client.GetService( 'ReconciliationOrderReportService', version='v201805') # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('reconciliationReportId = :reconciliationReportId') .WithBindVariable('reconciliationReportId', reconciliation_report_id)) diff --git a/examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 711f4b90..623acce9 100755 --- a/examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -33,7 +33,7 @@ def main(client): 'ReconciliationOrderReportService', version='v201805')) # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 22727432..19383c97 100755 --- a/examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -30,7 +30,7 @@ def main(client, reconciliation_report_id): 'ReconciliationReportRowService', version='v201805') # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) diff --git a/examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py index b67a6a27..c9219ca9 100755 --- a/examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -36,7 +36,7 @@ def main(client): 'ReconciliationReportRowService', version='v201805')) # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('id = :reconciliationReportRowId AND ' 'reconciliationReportId = :reconciliationReportId')) .OrderBy('id', ascending=True) diff --git a/examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py index b23efe61..9cbfd6c6 100755 --- a/examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py @@ -26,7 +26,7 @@ def main(client): 'ReconciliationReportService', version='v201805') # Create a statement to select reconciliation reports. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. diff --git a/examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 8890b92f..ca25f470 100755 --- a/examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -32,7 +32,7 @@ def main(client): last_month = first_of_the_month - timedelta(days=1) # Create a statement to select reconciliation reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('startDate = :startDate') .WithBindVariable('startDate', last_month)) diff --git a/examples/ad_manager/v201805/report_service/run_delivery_report.py b/examples/ad_manager/v201805/report_service/run_delivery_report.py index 5465a321..f7795ebb 100755 --- a/examples/ad_manager/v201805/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201805/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('ORDER_ID = :id') .WithBindVariable('id', long(order_id)) .Limit(None) # No limit or offset for reports diff --git a/examples/ad_manager/v201805/report_service/run_inventory_report.py b/examples/ad_manager/v201805/report_service/run_inventory_report.py index 34d23871..f329a544 100755 --- a/examples/ad_manager/v201805/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201805/report_service/run_inventory_report.py @@ -34,7 +34,7 @@ def main(client): network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) .Limit(None) # No limit or offset for reports diff --git a/examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py index c3e6a79a..773468d8 100755 --- a/examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py @@ -33,7 +33,7 @@ def main(client, order_id): report_downloader = client.GetDataDownloader(version='v201805') # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('orderId = :orderId') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201805/report_service/run_saved_query.py b/examples/ad_manager/v201805/report_service/run_saved_query.py index 0774d948..098e5cff 100755 --- a/examples/ad_manager/v201805/report_service/run_saved_query.py +++ b/examples/ad_manager/v201805/report_service/run_saved_query.py @@ -34,7 +34,7 @@ def main(client, saved_query_id): report_downloader = client.GetDataDownloader(version='v201805') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :id') .WithBindVariable('id', long(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py index e2a9accd..1d49ee41 100755 --- a/examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -32,7 +32,7 @@ def main(client): 'SuggestedAdUnitService', version='v201805') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py index 006b9fa9..d1e08a7b 100755 --- a/examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -26,7 +26,7 @@ def main(client): 'SuggestedAdUnitService', version='v201805') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index d2c18ee3..24b213f7 100755 --- a/examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -27,7 +27,7 @@ def main(client, num_requests): suggested_ad_unit_service = client.GetService( 'SuggestedAdUnitService', version='v201805') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', long(num_requests))) diff --git a/examples/ad_manager/v201805/team_service/get_all_teams.py b/examples/ad_manager/v201805/team_service/get_all_teams.py index 61e9dc6d..0fd00499 100755 --- a/examples/ad_manager/v201805/team_service/get_all_teams.py +++ b/examples/ad_manager/v201805/team_service/get_all_teams.py @@ -25,7 +25,7 @@ def main(client): team_service = client.GetService('TeamService', version='v201805') # Create a statement to select teams. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201805/team_service/update_teams.py b/examples/ad_manager/v201805/team_service/update_teams.py index a5cc9678..3b493662 100755 --- a/examples/ad_manager/v201805/team_service/update_teams.py +++ b/examples/ad_manager/v201805/team_service/update_teams.py @@ -37,7 +37,7 @@ def main(client, team_id): team_service = client.GetService('TeamService', version='v201805') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :teamId') .WithBindVariable('teamId', long(team_id))) diff --git a/examples/ad_manager/v201805/user_service/deactivate_users.py b/examples/ad_manager/v201805/user_service/deactivate_users.py index e5c8dc03..1dc7c63d 100755 --- a/examples/ad_manager/v201805/user_service/deactivate_users.py +++ b/examples/ad_manager/v201805/user_service/deactivate_users.py @@ -33,7 +33,7 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/user_service/get_all_users.py b/examples/ad_manager/v201805/user_service/get_all_users.py index 5b0f46ff..81c83592 100755 --- a/examples/ad_manager/v201805/user_service/get_all_users.py +++ b/examples/ad_manager/v201805/user_service/get_all_users.py @@ -25,7 +25,7 @@ def main(client): user_service = client.GetService('UserService', version='v201805') # Create a statement to select users. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201805/user_service/get_user_by_email_address.py b/examples/ad_manager/v201805/user_service/get_user_by_email_address.py index 040f59d1..a32515c6 100755 --- a/examples/ad_manager/v201805/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201805/user_service/get_user_by_email_address.py @@ -26,7 +26,7 @@ def main(client, email_address): # Initialize appropriate service. user_service = client.GetService('UserService', version='v201805') # Create a statement to select users. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201805/user_service/update_users.py b/examples/ad_manager/v201805/user_service/update_users.py index e8482754..4b3076d3 100755 --- a/examples/ad_manager/v201805/user_service/update_users.py +++ b/examples/ad_manager/v201805/user_service/update_users.py @@ -31,7 +31,7 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201805') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('id = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py index c0503538..5dad19c3 100755 --- a/examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py @@ -38,7 +38,7 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201805') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py index 49f883c4..6609392a 100755 --- a/examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py @@ -26,7 +26,7 @@ def main(client): 'UserTeamAssociationService', version='v201805') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201805') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py index 2d3c8e44..d24e0dc9 100755 --- a/examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py @@ -27,7 +27,7 @@ def main(client, user_id): user_team_association_service = client.GetService( 'UserTeamAssociationService', version='v201805') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py index fe8886c8..419925d0 100755 --- a/examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py @@ -40,7 +40,7 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201805') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py index 46591dc7..ea172937 100755 --- a/examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py @@ -34,7 +34,7 @@ def main(client, proposal_id): version='v201805') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) diff --git a/examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py index 239b6be3..308be1bf 100755 --- a/examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py @@ -28,7 +28,7 @@ def main(client): workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201805') # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) diff --git a/examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py index 2566ffbd..33fadd30 100755 --- a/examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py @@ -28,7 +28,7 @@ def main(client): workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201805') # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) diff --git a/examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py index f5c6d59d..20673048 100755 --- a/examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -34,7 +34,7 @@ def main(client, proposal_id): version='v201805') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201805') .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) diff --git a/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py index 671c98e9..43e5e90d 100755 --- a/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py @@ -25,7 +25,7 @@ def main(client): activity_group_service = client.GetService( 'ActivityGroupService', version='v201808') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py index a8292b86..598284a2 100755 --- a/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py @@ -26,7 +26,7 @@ def main(client): 'ActivityGroupService', version='v201808') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py index 88cb3bc8..df0b7da9 100755 --- a/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py @@ -40,7 +40,7 @@ def main(client, activity_group_id, advertiser_company_id): version='v201808') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', long(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/activity_service/get_active_activities.py b/examples/ad_manager/v201808/activity_service/get_active_activities.py index 5d78d3d0..04453053 100755 --- a/examples/ad_manager/v201808/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201808/activity_service/get_active_activities.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. activity_service = client.GetService('ActivityService', version='v201808') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201808/activity_service/get_all_activities.py b/examples/ad_manager/v201808/activity_service/get_all_activities.py index d949f570..28501e28 100755 --- a/examples/ad_manager/v201808/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201808/activity_service/get_all_activities.py @@ -25,7 +25,7 @@ def main(client): activity_service = client.GetService('ActivityService', version='v201808') # Create a statement to select activities. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201808/activity_service/update_activities.py b/examples/ad_manager/v201808/activity_service/update_activities.py index dc01b752..66b3b8ce 100755 --- a/examples/ad_manager/v201808/activity_service/update_activities.py +++ b/examples/ad_manager/v201808/activity_service/update_activities.py @@ -38,7 +38,7 @@ def main(client, activity_id): activity_service = client.GetService('ActivityService', version='v201808') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :activityId') .WithBindVariable('activityId', long(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py index 9bb8f5ee..3fb0fbcf 100755 --- a/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py @@ -26,7 +26,7 @@ def main(client): 'AudienceSegmentService', version='v201808') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py index 9dbe9254..8a7855cc 100755 --- a/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py @@ -25,7 +25,7 @@ def main(client): audience_segment_service = client.GetService( 'AudienceSegmentService', version='v201808') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py index c1df3bfc..dd971e3e 100755 --- a/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py @@ -33,7 +33,7 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201808') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) diff --git a/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py index b7c24919..4c51e00d 100755 --- a/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py @@ -32,7 +32,7 @@ def main(client, audience_segment_id): 'AudienceSegmentService', version='v201808') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) diff --git a/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py index 85eb737e..ceba2083 100755 --- a/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py @@ -25,7 +25,7 @@ def main(client): base_rate_service = client.GetService('BaseRateService', version='v201808') # Create a statement to select base rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py index ded1b04e..6e7148b6 100755 --- a/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py @@ -26,7 +26,7 @@ def main(client, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService('BaseRateService', version='v201808') # Create a statement to select base rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) diff --git a/examples/ad_manager/v201808/base_rate_service/update_base_rates.py b/examples/ad_manager/v201808/base_rate_service/update_base_rates.py index c0f59d39..022da6ca 100755 --- a/examples/ad_manager/v201808/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201808/base_rate_service/update_base_rates.py @@ -32,7 +32,7 @@ def main(client, base_rate_id): base_rate_service = client.GetService('BaseRateService', version='v201808') # Create a filter statement for base rates for a single rate card. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py index 689a3eb6..b2c0c821 100755 --- a/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py @@ -29,7 +29,7 @@ def main(client): version='v201808') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v201808/company_service/get_advertisers.py b/examples/ad_manager/v201808/company_service/get_advertisers.py index fb32fd61..778a6c7e 100755 --- a/examples/ad_manager/v201808/company_service/get_advertisers.py +++ b/examples/ad_manager/v201808/company_service/get_advertisers.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. company_service = client.GetService('CompanyService', version='v201808') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201808/company_service/get_all_companies.py b/examples/ad_manager/v201808/company_service/get_all_companies.py index 176a892b..82e793c8 100755 --- a/examples/ad_manager/v201808/company_service/get_all_companies.py +++ b/examples/ad_manager/v201808/company_service/get_all_companies.py @@ -25,7 +25,7 @@ def main(client): company_service = client.GetService('CompanyService', version='v201808') # Create a statement to select companies. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201808/company_service/update_companies.py b/examples/ad_manager/v201808/company_service/update_companies.py index 39a712d9..e447415f 100755 --- a/examples/ad_manager/v201808/company_service/update_companies.py +++ b/examples/ad_manager/v201808/company_service/update_companies.py @@ -38,7 +38,7 @@ def main(client, company_id): company_service = client.GetService('CompanyService', version='v201808') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', long(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/contact_service/get_all_contacts.py b/examples/ad_manager/v201808/contact_service/get_all_contacts.py index 715aff51..52b87af0 100755 --- a/examples/ad_manager/v201808/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201808/contact_service/get_all_contacts.py @@ -25,7 +25,7 @@ def main(client): contact_service = client.GetService('ContactService', version='v201808') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py index 3945a19c..ee05f1e9 100755 --- a/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. contact_service = client.GetService('ContactService', version='v201808') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201808/contact_service/update_contacts.py b/examples/ad_manager/v201808/contact_service/update_contacts.py index 4062e0a2..01032620 100755 --- a/examples/ad_manager/v201808/contact_service/update_contacts.py +++ b/examples/ad_manager/v201808/contact_service/update_contacts.py @@ -38,7 +38,7 @@ def main(client, contact_id): contact_service = client.GetService('ContactService', version='v201808') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', long(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index 443c686e..842856f7 100755 --- a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -26,7 +26,7 @@ def main(client): 'ContentMetadataKeyHierarchyService', version='v201808') # Create a statement to select content metadata key hierarchies. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been diff --git a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 428db239..e966ba99 100755 --- a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -46,7 +46,7 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Create a query to select a single content metadata key hierarchy. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) diff --git a/examples/ad_manager/v201808/content_service/get_all_content.py b/examples/ad_manager/v201808/content_service/get_all_content.py index 4b8e391d..d4c120ca 100755 --- a/examples/ad_manager/v201808/content_service/get_all_content.py +++ b/examples/ad_manager/v201808/content_service/get_all_content.py @@ -25,7 +25,7 @@ def main(client): content_service = client.GetService('ContentService', version='v201808') # Create a statement to select content. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v201808/creative_service/copy_image_creatives.py b/examples/ad_manager/v201808/creative_service/copy_image_creatives.py index 49ae67bc..24740e02 100755 --- a/examples/ad_manager/v201808/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201808/creative_service/copy_image_creatives.py @@ -31,7 +31,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201808') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201808/creative_service/get_all_creatives.py b/examples/ad_manager/v201808/creative_service/get_all_creatives.py index 17135aa4..6a440f6d 100755 --- a/examples/ad_manager/v201808/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201808/creative_service/get_all_creatives.py @@ -25,7 +25,7 @@ def main(client): creative_service = client.GetService('CreativeService', version='v201808') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201808/creative_service/get_image_creatives.py b/examples/ad_manager/v201808/creative_service/get_image_creatives.py index f9f735e5..1e532578 100755 --- a/examples/ad_manager/v201808/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201808/creative_service/get_image_creatives.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. creative_service = client.GetService('CreativeService', version='v201808') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201808/creative_service/update_creatives.py b/examples/ad_manager/v201808/creative_service/update_creatives.py index 8929f0c1..5ab70081 100755 --- a/examples/ad_manager/v201808/creative_service/update_creatives.py +++ b/examples/ad_manager/v201808/creative_service/update_creatives.py @@ -37,7 +37,7 @@ def main(client, image_creative_id): creative_service = client.GetService('CreativeService', version='v201808') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', long(image_creative_id)) diff --git a/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py index e56a8927..d32e9d35 100755 --- a/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py @@ -26,7 +26,7 @@ def main(client): 'CreativeSetService', version='v201808') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py index c7e34212..2646ea85 100755 --- a/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py @@ -27,7 +27,7 @@ def main(client, master_creative_id): creative_set_service = client.GetService( 'CreativeSetService', version='v201808') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201808/creative_set_service/update_creative_set.py b/examples/ad_manager/v201808/creative_set_service/update_creative_set.py index 3ed696b5..1a333f43 100755 --- a/examples/ad_manager/v201808/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201808/creative_set_service/update_creative_set.py @@ -40,7 +40,7 @@ def main(client, creative_set_id, companion_creative_id): version='v201808') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', long(creative_set_id))) diff --git a/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py index d05bf5c2..67a95fad 100755 --- a/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py @@ -26,7 +26,7 @@ def main(client): 'CreativeTemplateService', version='v201808') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py index 31f723e8..8630e84d 100755 --- a/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py @@ -25,7 +25,7 @@ def main(client): creative_template_service = client.GetService( 'CreativeTemplateService', version='v201808') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py index a3087b9b..313f2bb5 100755 --- a/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py @@ -36,7 +36,7 @@ def main(client, label_id): version='v201808') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', long(label_id))) diff --git a/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py index aa9b5278..1e9e9095 100755 --- a/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py @@ -25,7 +25,7 @@ def main(client): creative_wrapper_service = client.GetService( 'CreativeWrapperService', version='v201808') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py index ca10557d..87f4a745 100755 --- a/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py @@ -26,7 +26,7 @@ def main(client): 'CreativeWrapperService', version='v201808') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py index 7e21ee48..86c38a62 100755 --- a/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py @@ -39,7 +39,7 @@ def main(client, creative_wrapper_id): version='v201808') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', long(creative_wrapper_id))) diff --git a/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py index 788d1ce3..3f2848b4 100755 --- a/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -37,7 +37,7 @@ def main(client): # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py index b185329d..ab3dd0cb 100755 --- a/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py @@ -26,7 +26,7 @@ def main(client): 'CustomFieldService', version='v201808') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py index da28601b..3144f460 100755 --- a/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py @@ -25,7 +25,7 @@ def main(client): custom_field_service = client.GetService( 'CustomFieldService', version='v201808') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py index 2012369e..e6487aeb 100755 --- a/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py @@ -47,7 +47,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, line_item_service = client.GetService('LineItemService', version='v201808') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder() + custom_field_statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder() + ad_manager.StatementBuilder(version='v201808') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder() + line_item_statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py index a3edfb16..524b01d5 100755 --- a/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py @@ -39,7 +39,7 @@ def main(client, custom_field_id): 'CustomFieldService', version='v201808') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :customFieldId') .WithBindVariable('customFieldId', long(custom_field_id))) diff --git a/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py index 940a7b85..5b5524f0 100755 --- a/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py @@ -38,7 +38,7 @@ def main(client, key_name): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201808') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder() + key_statement = (ad_manager.StatementBuilder(version='v201808') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py index bb1dcd07..6ca118f1 100755 --- a/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py @@ -38,7 +38,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201808') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder() + value_statement = (ad_manager.StatementBuilder(version='v201808') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index f2ff09bb..b33e8898 100755 --- a/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201808') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder() + targeting_key_statement = ad_manager.StatementBuilder(version='v201808') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index eab04561..51e6a12b 100755 --- a/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -26,7 +26,7 @@ def main(client): 'CustomTargetingService', version='v201808') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder() + targeting_key_statement = (ad_manager.StatementBuilder(version='v201808') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py index 71ebc154..65c97e12 100755 --- a/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py @@ -32,7 +32,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201808') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :keyId') .WithBindVariable('keyId', long(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py index d6e1a72b..2929da9d 100755 --- a/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py @@ -32,7 +32,7 @@ def main(client, key_id): custom_targeting_service = client.GetService( 'CustomTargetingService', version='v201808') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', long(key_id))) diff --git a/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py index ef5fffa1..0cc20b9f 100755 --- a/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py @@ -26,7 +26,7 @@ def main(client): 'ExchangeRateService', version='v201808') # Create a statement to select exchange rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py index c75be3f6..25704dfc 100755 --- a/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -27,7 +27,7 @@ def main(client, currency_code): exchange_rate_service = client.GetService( 'ExchangeRateService', version='v201808') # Create a statement to select exchange rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('currencyCode = :currencyCode') .WithBindVariable('currencyCode', currency_code)) diff --git a/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py index 064df7a1..af8090fb 100755 --- a/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py @@ -33,7 +33,7 @@ def main(client, exchange_rate_id): version='v201808') # Create a statement to get an exchange rate by its ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', long(exchange_rate_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/inventory_service/archive_ad_units.py b/examples/ad_manager/v201808/inventory_service/archive_ad_units.py index 179c8e01..cfa8e179 100755 --- a/examples/ad_manager/v201808/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/archive_ad_units.py @@ -39,7 +39,7 @@ def main(client, parent_id): # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', long(parent_id))) diff --git a/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py index dcd8aa57..ac13076e 100755 --- a/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py @@ -32,7 +32,7 @@ def main(client): root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py index 8a973f02..eabc01e1 100755 --- a/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py @@ -26,7 +26,7 @@ def main(client): 'InventoryService', version='v201808') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py index 28972e48..c5c854f6 100755 --- a/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py @@ -25,7 +25,7 @@ def main(client): ad_unit_service = client.GetService('InventoryService', version='v201808') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py index 56d3d2b7..87a75e26 100755 --- a/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py @@ -31,7 +31,7 @@ def main(client): parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201808/inventory_service/update_ad_units.py b/examples/ad_manager/v201808/inventory_service/update_ad_units.py index 0b388101..5bdca610 100755 --- a/examples/ad_manager/v201808/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201808/inventory_service/update_ad_units.py @@ -39,7 +39,7 @@ def main(client, ad_unit_id): inventory_service = client.GetService('InventoryService', version='v201808') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201808/label_service/deactivate_labels.py b/examples/ad_manager/v201808/label_service/deactivate_labels.py index 6baa079f..70d7be9e 100755 --- a/examples/ad_manager/v201808/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201808/label_service/deactivate_labels.py @@ -30,7 +30,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201808/label_service/get_active_labels.py b/examples/ad_manager/v201808/label_service/get_active_labels.py index 6a8c0ef1..39065efc 100755 --- a/examples/ad_manager/v201808/label_service/get_active_labels.py +++ b/examples/ad_manager/v201808/label_service/get_active_labels.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201808') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201808/label_service/get_all_labels.py b/examples/ad_manager/v201808/label_service/get_all_labels.py index 5e93b328..a1feeb2f 100755 --- a/examples/ad_manager/v201808/label_service/get_all_labels.py +++ b/examples/ad_manager/v201808/label_service/get_all_labels.py @@ -25,7 +25,7 @@ def main(client): label_service = client.GetService('LabelService', version='v201808') # Create a statement to select labels. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201808/label_service/update_labels.py b/examples/ad_manager/v201808/label_service/update_labels.py index f8e2b229..fdf33d9c 100755 --- a/examples/ad_manager/v201808/label_service/update_labels.py +++ b/examples/ad_manager/v201808/label_service/update_labels.py @@ -32,7 +32,7 @@ def main(client, label_id): label_service = client.GetService('LabelService', version='v201808') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :labelId') .WithBindVariable('labelId', long(label_id))) diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py index f69480e6..c2f4f3e2 100755 --- a/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py @@ -33,7 +33,7 @@ def main(client, line_item_id): 'LineItemCreativeAssociationService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', long(line_item_id))) diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py index 70f4bf47..f1acf180 100755 --- a/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py @@ -26,7 +26,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201808') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py index ef623efb..b43fea0d 100755 --- a/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py @@ -27,7 +27,7 @@ def main(client, line_item_id): lica_service = client.GetService( 'LineItemCreativeAssociationService', version='v201808') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py index e805fca3..130c80b8 100755 --- a/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py @@ -31,7 +31,7 @@ def main(client): 'LineItemCreativeAssociationService', version='v201808') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201808/line_item_service/activate_line_items.py b/examples/ad_manager/v201808/line_item_service/activate_line_items.py index 64f0bfe3..6de6be2e 100755 --- a/examples/ad_manager/v201808/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/activate_line_items.py @@ -36,7 +36,7 @@ def main(client, order_id): line_item_service = client.GetService('LineItemService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201808/line_item_service/get_all_line_items.py b/examples/ad_manager/v201808/line_item_service/get_all_line_items.py index d89023a6..7699daa1 100755 --- a/examples/ad_manager/v201808/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/get_all_line_items.py @@ -25,7 +25,7 @@ def main(client): line_item_service = client.GetService('LineItemService', version='v201808') # Create a statement to select line items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py index e23bdb74..8dc1c1fb 100755 --- a/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. line_item_service = client.GetService('LineItemService', version='v201808') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py index 92225e51..d2e664b9 100755 --- a/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py @@ -32,7 +32,7 @@ def main(client): - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201808/line_item_service/pause_line_items.py b/examples/ad_manager/v201808/line_item_service/pause_line_items.py index 79ac603e..5a5a3873 100755 --- a/examples/ad_manager/v201808/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/pause_line_items.py @@ -33,7 +33,7 @@ def main(client): # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py index 8b877214..c9628e41 100755 --- a/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :lineItemId') .WithBindVariable('lineItemId', long(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/line_item_service/update_line_items.py b/examples/ad_manager/v201808/line_item_service/update_line_items.py index 3d451888..54cd59ff 100755 --- a/examples/ad_manager/v201808/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201808/line_item_service/update_line_items.py @@ -33,7 +33,7 @@ def main(client, order_id): # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', long(order_id)) diff --git a/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py index 7add0880..f2d72c71 100755 --- a/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py @@ -29,7 +29,7 @@ def main(client, live_stream_event_id): 'LiveStreamEventService', version='v201808') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py index 44eab75c..1954ca37 100755 --- a/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py @@ -27,7 +27,7 @@ def main(client): 'LiveStreamEventService', version='v201808') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py index f22dad8d..34e48cc5 100755 --- a/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py @@ -32,7 +32,7 @@ def main(client, live_stream_event_id): 'LiveStreamEventService', version='v201808') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('Id = :id')) .WithBindVariable('id', long(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py index dbbb8de5..3bb2f92b 100755 --- a/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py @@ -26,7 +26,7 @@ def main(client): version='v201808') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201808/order_service/approve_orders.py b/examples/ad_manager/v201808/order_service/approve_orders.py index 0b455bfb..f1bce5b9 100755 --- a/examples/ad_manager/v201808/order_service/approve_orders.py +++ b/examples/ad_manager/v201808/order_service/approve_orders.py @@ -32,7 +32,7 @@ def main(client): # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201808/order_service/get_all_orders.py b/examples/ad_manager/v201808/order_service/get_all_orders.py index 958c79ca..53cc23f5 100755 --- a/examples/ad_manager/v201808/order_service/get_all_orders.py +++ b/examples/ad_manager/v201808/order_service/get_all_orders.py @@ -25,7 +25,7 @@ def main(client): order_service = client.GetService('OrderService', version='v201808') # Create a statement to select orders. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py index 1fa0ee74..d6ae2a91 100755 --- a/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py @@ -31,7 +31,7 @@ def main(client): soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201808/order_service/update_orders.py b/examples/ad_manager/v201808/order_service/update_orders.py index 163a31a7..1d69813b 100755 --- a/examples/ad_manager/v201808/order_service/update_orders.py +++ b/examples/ad_manager/v201808/order_service/update_orders.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :orderId') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py index 1e9717bf..1c2b4938 100755 --- a/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py @@ -31,7 +31,7 @@ def main(client): package_service = client.GetService('PackageService', version='v201808') # Create a statement to select the single package. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201808/package_service/get_all_packages.py b/examples/ad_manager/v201808/package_service/get_all_packages.py index 86cd16b3..bfffe92c 100755 --- a/examples/ad_manager/v201808/package_service/get_all_packages.py +++ b/examples/ad_manager/v201808/package_service/get_all_packages.py @@ -25,7 +25,7 @@ def main(client): pkg_service = client.GetService('PackageService', version='v201808') # Create a statement to select packages. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/ad_manager/v201808/package_service/get_in_progress_packages.py b/examples/ad_manager/v201808/package_service/get_in_progress_packages.py index fc486fd8..100a3505 100755 --- a/examples/ad_manager/v201808/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201808/package_service/get_in_progress_packages.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. pkg_service = client.GetService('PackageService', version='v201808') # Create a statement to select packages. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status') .WithBindVariable('status', 'IN_PROGRESS')) diff --git a/examples/ad_manager/v201808/placement_service/create_placements.py b/examples/ad_manager/v201808/placement_service/create_placements.py index 9918518d..d9a16f6e 100755 --- a/examples/ad_manager/v201808/placement_service/create_placements.py +++ b/examples/ad_manager/v201808/placement_service/create_placements.py @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201808/placement_service/deactivate_placements.py b/examples/ad_manager/v201808/placement_service/deactivate_placements.py index a6e11916..74feabd3 100755 --- a/examples/ad_manager/v201808/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201808/placement_service/deactivate_placements.py @@ -31,7 +31,7 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :placementId') .WithBindVariable('placementId', long(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/placement_service/get_active_placements.py b/examples/ad_manager/v201808/placement_service/get_active_placements.py index dbed1123..1d5dea47 100755 --- a/examples/ad_manager/v201808/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201808/placement_service/get_active_placements.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. placement_service = client.GetService('PlacementService', version='v201808') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201808/placement_service/get_all_placements.py b/examples/ad_manager/v201808/placement_service/get_all_placements.py index fbd52086..908d1924 100755 --- a/examples/ad_manager/v201808/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201808/placement_service/get_all_placements.py @@ -25,7 +25,7 @@ def main(client): placement_service = client.GetService('PlacementService', version='v201808') # Create a statement to select placements. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201808/placement_service/update_placements.py b/examples/ad_manager/v201808/placement_service/update_placements.py index 9ad03779..4768ba9e 100755 --- a/examples/ad_manager/v201808/placement_service/update_placements.py +++ b/examples/ad_manager/v201808/placement_service/update_placements.py @@ -31,7 +31,7 @@ def main(client, placement_id): placement_service = client.GetService('PlacementService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py index 44a26302..6afd5635 100755 --- a/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py @@ -26,7 +26,7 @@ def main(client): 'PremiumRateService', version='v201808') # Create a statement to select premium rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py index 5c824c01..2068c033 100755 --- a/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py @@ -27,7 +27,7 @@ def main(client, rate_card_id): premium_rate_service = client.GetService( 'PremiumRateService', version='v201808') # Create a statement to select premium rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) diff --git a/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py index 6045d6f5..a3efb98f 100755 --- a/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py @@ -33,7 +33,7 @@ def main(client, premium_rate_id): version='v201808') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(premium_rate_id)) diff --git a/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py index 8eb24f64..d5d39056 100755 --- a/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageItemService', version='v201808') # Create a statement to select product package items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py index 940a0fab..e768b725 100755 --- a/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py @@ -27,7 +27,7 @@ def main(client, product_package_id): product_package_item_service = client.GetService( 'ProductPackageItemService', version='v201808') # Create a statement to select product package items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('productPackageId = :productPackageId') .WithBindVariable('productPackageId', product_package_id)) diff --git a/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py index bbe87d44..24df6745 100755 --- a/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py @@ -25,7 +25,7 @@ def main(client): product_package_service = client.GetService( 'ProductPackageService', version='v201808') # Create a statement to select product packages. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py index b29f1809..333087ed 100755 --- a/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py @@ -26,7 +26,7 @@ def main(client): 'ProductPackageService', version='v201808') # Create a statement to select product packages. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/ad_manager/v201808/product_service/get_all_products.py b/examples/ad_manager/v201808/product_service/get_all_products.py index 19a4cc53..329dc856 100755 --- a/examples/ad_manager/v201808/product_service/get_all_products.py +++ b/examples/ad_manager/v201808/product_service/get_all_products.py @@ -25,7 +25,7 @@ def main(client): product_service = client.GetService('ProductService', version='v201808') # Create a statement to select products. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/ad_manager/v201808/product_service/get_products_for_product_template.py b/examples/ad_manager/v201808/product_service/get_products_for_product_template.py index 783fd1ed..51160ca4 100755 --- a/examples/ad_manager/v201808/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201808/product_service/get_products_for_product_template.py @@ -27,7 +27,7 @@ def main(client, product_template_id): product_service = client.GetService('ProductService', version='v201808') # Create a statement to select products. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('productTemplateId = :productTemplateId') .WithBindVariable('productTemplateId', product_template_id)) diff --git a/examples/ad_manager/v201808/product_service/update_products.py b/examples/ad_manager/v201808/product_service/update_products.py index 242c512f..93471235 100755 --- a/examples/ad_manager/v201808/product_service/update_products.py +++ b/examples/ad_manager/v201808/product_service/update_products.py @@ -32,7 +32,7 @@ def main(client, product_id): product_service = client.GetService('ProductService', version='v201808') # Create statement object to select a single product by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', long(product_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/product_template_service/activate_product_templates.py b/examples/ad_manager/v201808/product_template_service/activate_product_templates.py index 7a7f8f96..2d649f69 100755 --- a/examples/ad_manager/v201808/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/activate_product_templates.py @@ -34,7 +34,7 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', long(product_template_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py index 070f6e55..868e1518 100755 --- a/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py @@ -26,7 +26,7 @@ def main(client): 'ProductTemplateService', version='v201808') # Create a statement to select product templates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py index 3324a15b..22cfd0c3 100755 --- a/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py @@ -25,7 +25,7 @@ def main(client): product_template_service = client.GetService( 'ProductTemplateService', version='v201808') # Create a statement to select product templates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('lineItemType = :lineItemType') .WithBindVariable('lineItemType', 'SPONSORSHIP')) diff --git a/examples/ad_manager/v201808/product_template_service/update_product_templates.py b/examples/ad_manager/v201808/product_template_service/update_product_templates.py index 18735440..990f2f91 100755 --- a/examples/ad_manager/v201808/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201808/product_template_service/update_product_templates.py @@ -33,7 +33,7 @@ def main(client, product_template_id): 'ProductTemplateService', version='v201808') # Create a statement to select a single product template by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(product_template_id)) diff --git a/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py index a19b5739..65f353ea 100755 --- a/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py @@ -34,7 +34,7 @@ def main(client, proposal_line_item_id): 'ProposalLineItemService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py index 9762b0cb..66d87c8d 100755 --- a/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py @@ -26,7 +26,7 @@ def main(client): 'ProposalLineItemService', version='v201808') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 1af67b0c..74bafccf 100755 --- a/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -27,7 +27,7 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( 'ProposalLineItemService', version='v201808') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py index 7293adb3..146b20f5 100755 --- a/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py @@ -35,7 +35,7 @@ def main(client, proposal_line_item_id): # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/proposal_service/get_all_proposals.py b/examples/ad_manager/v201808/proposal_service/get_all_proposals.py index 3e1931d7..78067812 100755 --- a/examples/ad_manager/v201808/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201808/proposal_service/get_all_proposals.py @@ -25,7 +25,7 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201808') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py index 4fcaf11d..9b7ce9d5 100755 --- a/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py @@ -24,7 +24,7 @@ def main(client): # Initialize appropriate service. proposal_service = client.GetService('ProposalService', version='v201808') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('status = :status') .WithBindVariable('status', 'PENDING_APPROVAL')) diff --git a/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py index 9d534ccf..b352217e 100755 --- a/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py @@ -29,7 +29,7 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py index b2e9d33b..77d4b206 100755 --- a/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py @@ -31,7 +31,7 @@ def main(client, proposal_id): proposal_service = client.GetService('ProposalService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 diff --git a/examples/ad_manager/v201808/proposal_service/update_proposals.py b/examples/ad_manager/v201808/proposal_service/update_proposals.py index bfddcaae..c4f2cd54 100755 --- a/examples/ad_manager/v201808/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201808/proposal_service/update_proposals.py @@ -32,7 +32,7 @@ def main(client, proposal_id): # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :proposalId') .WithBindVariable('proposalId', long(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py index 4452858c..c43eeb5e 100755 --- a/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py index 018787ee..42723673 100755 --- a/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py @@ -25,7 +25,7 @@ def main(client): rate_card_service = client.GetService('RateCardService', version='v201808') # Create a statement to select rate cards. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py index e4d4f73d..a9863f9b 100755 --- a/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py @@ -25,7 +25,7 @@ def main(client): # Initialize appropriate service. rate_card_service = client.GetService('RateCardService', version='v201808') # Create a statement to select rate cards. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('forMarketplace = :forMarketplace') .WithBindVariable('forMarketplace', True)) diff --git a/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index cdde9f62..c82b0443 100755 --- a/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -33,7 +33,7 @@ def main(client): 'ReconciliationLineItemReportService', version='v201808')) # Create a statement to select reconciliation line item reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('reconciliationReportId = :reconciliationReportId AND ' 'lineItemId != :lineItemId')) .OrderBy('lineItemId', ascending=True) diff --git a/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index a8afd3d9..d3c55cee 100755 --- a/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -33,7 +33,7 @@ def main(client): 'ReconciliationLineItemReportService', version='v201808')) # Create a statement to select a reconciliation line item report. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :lineItemReportId') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 9d1d8503..87b475b0 100755 --- a/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -27,7 +27,7 @@ def main(client, reconciliation_report_id): reconciliation_order_report_service = client.GetService( 'ReconciliationOrderReportService', version='v201808') # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('reconciliationReportId = :reconciliationReportId') .WithBindVariable('reconciliationReportId', reconciliation_report_id)) diff --git a/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py index c9d2475c..6d3cf243 100755 --- a/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -33,7 +33,7 @@ def main(client): 'ReconciliationOrderReportService', version='v201808')) # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index fb6f9ff3..5caa60de 100755 --- a/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -30,7 +30,7 @@ def main(client, reconciliation_report_id): 'ReconciliationReportRowService', version='v201808') # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) diff --git a/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py index 0dd3adfa..064b3c8c 100755 --- a/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -36,7 +36,7 @@ def main(client): 'ReconciliationReportRowService', version='v201808')) # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('id = :reconciliationReportRowId AND ' 'reconciliationReportId = :reconciliationReportId')) .OrderBy('id', ascending=True) diff --git a/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py index 21d50ee6..aff3d512 100755 --- a/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py @@ -26,7 +26,7 @@ def main(client): 'ReconciliationReportService', version='v201808') # Create a statement to select reconciliation reports. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. diff --git a/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 2dcfdb25..b648d800 100755 --- a/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -32,7 +32,7 @@ def main(client): last_month = first_of_the_month - timedelta(days=1) # Create a statement to select reconciliation reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('startDate = :startDate') .WithBindVariable('startDate', last_month)) diff --git a/examples/ad_manager/v201808/report_service/run_delivery_report.py b/examples/ad_manager/v201808/report_service/run_delivery_report.py index 4577f38a..4ac27a34 100755 --- a/examples/ad_manager/v201808/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201808/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('ORDER_ID = :id') .WithBindVariable('id', long(order_id)) .Limit(None) # No limit or offset for reports diff --git a/examples/ad_manager/v201808/report_service/run_inventory_report.py b/examples/ad_manager/v201808/report_service/run_inventory_report.py index eedde178..95cabda3 100755 --- a/examples/ad_manager/v201808/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201808/report_service/run_inventory_report.py @@ -34,7 +34,7 @@ def main(client): network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) .Limit(None) # No limit or offset for reports diff --git a/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py index d5d37cc5..7d6093ee 100755 --- a/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py @@ -33,7 +33,7 @@ def main(client, order_id): report_downloader = client.GetDataDownloader(version='v201808') # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('orderId = :orderId') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201808/report_service/run_saved_query.py b/examples/ad_manager/v201808/report_service/run_saved_query.py index 2ad90375..c1d3ef64 100755 --- a/examples/ad_manager/v201808/report_service/run_saved_query.py +++ b/examples/ad_manager/v201808/report_service/run_saved_query.py @@ -34,7 +34,7 @@ def main(client, saved_query_id): report_downloader = client.GetDataDownloader(version='v201808') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :id') .WithBindVariable('id', long(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 04dfafb9..8eed7f1c 100755 --- a/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -32,7 +32,7 @@ def main(client): 'SuggestedAdUnitService', version='v201808') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py index 1ec2ae9d..b844f281 100755 --- a/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -26,7 +26,7 @@ def main(client): 'SuggestedAdUnitService', version='v201808') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index b97550b0..842dcd9d 100755 --- a/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -27,7 +27,7 @@ def main(client, num_requests): suggested_ad_unit_service = client.GetService( 'SuggestedAdUnitService', version='v201808') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', long(num_requests))) diff --git a/examples/ad_manager/v201808/team_service/get_all_teams.py b/examples/ad_manager/v201808/team_service/get_all_teams.py index c5830cb4..ecf3978a 100755 --- a/examples/ad_manager/v201808/team_service/get_all_teams.py +++ b/examples/ad_manager/v201808/team_service/get_all_teams.py @@ -25,7 +25,7 @@ def main(client): team_service = client.GetService('TeamService', version='v201808') # Create a statement to select teams. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201808/team_service/update_teams.py b/examples/ad_manager/v201808/team_service/update_teams.py index c5d221dd..d33e859e 100755 --- a/examples/ad_manager/v201808/team_service/update_teams.py +++ b/examples/ad_manager/v201808/team_service/update_teams.py @@ -37,7 +37,7 @@ def main(client, team_id): team_service = client.GetService('TeamService', version='v201808') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :teamId') .WithBindVariable('teamId', long(team_id))) diff --git a/examples/ad_manager/v201808/user_service/deactivate_users.py b/examples/ad_manager/v201808/user_service/deactivate_users.py index 97040aa9..4315b88c 100755 --- a/examples/ad_manager/v201808/user_service/deactivate_users.py +++ b/examples/ad_manager/v201808/user_service/deactivate_users.py @@ -33,7 +33,7 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201808/user_service/get_all_users.py b/examples/ad_manager/v201808/user_service/get_all_users.py index aa05b4fc..caa0951b 100755 --- a/examples/ad_manager/v201808/user_service/get_all_users.py +++ b/examples/ad_manager/v201808/user_service/get_all_users.py @@ -25,7 +25,7 @@ def main(client): user_service = client.GetService('UserService', version='v201808') # Create a statement to select users. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201808/user_service/get_user_by_email_address.py b/examples/ad_manager/v201808/user_service/get_user_by_email_address.py index 93a933b0..e15adb37 100755 --- a/examples/ad_manager/v201808/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201808/user_service/get_user_by_email_address.py @@ -26,7 +26,7 @@ def main(client, email_address): # Initialize appropriate service. user_service = client.GetService('UserService', version='v201808') # Create a statement to select users. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201808/user_service/update_users.py b/examples/ad_manager/v201808/user_service/update_users.py index eff3a2c1..5e5df575 100755 --- a/examples/ad_manager/v201808/user_service/update_users.py +++ b/examples/ad_manager/v201808/user_service/update_users.py @@ -31,7 +31,7 @@ def main(client, user_id): user_service = client.GetService('UserService', version='v201808') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('id = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py index 8bf6fc90..4655d73a 100755 --- a/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py @@ -38,7 +38,7 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201808') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py index 43f481b8..746a386a 100755 --- a/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py @@ -26,7 +26,7 @@ def main(client): 'UserTeamAssociationService', version='v201808') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201808') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py index b73f043d..32019038 100755 --- a/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py @@ -27,7 +27,7 @@ def main(client, user_id): user_team_association_service = client.GetService( 'UserTeamAssociationService', version='v201808') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py index 4fac863d..0644eaaf 100755 --- a/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py @@ -40,7 +40,7 @@ def main(client, user_id): 'UserTeamAssociationService', version='v201808') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py index c970542e..a5468cba 100755 --- a/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py @@ -34,7 +34,7 @@ def main(client, proposal_id): version='v201808') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) diff --git a/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py index cf2f07b5..0244aabd 100755 --- a/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py @@ -28,7 +28,7 @@ def main(client): workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201808') # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) diff --git a/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py index 91f85bf0..a81f0f5b 100755 --- a/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py @@ -28,7 +28,7 @@ def main(client): workflow_request_service = client.GetService( 'WorkflowRequestService', version='v201808') # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) diff --git a/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py index 2728d725..167e4dbe 100755 --- a/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -34,7 +34,7 @@ def main(client, proposal_id): version='v201808') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201808') .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) diff --git a/examples/ad_manager/v201802/activity_group_service/__init__.py b/examples/ad_manager/v201811/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/activity_group_service/__init__.py rename to examples/ad_manager/v201811/activity_group_service/__init__.py diff --git a/examples/ad_manager/v201802/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201811/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v201802/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v201811/activity_group_service/create_activity_groups.py index 6932d052..fb7d9d51 100755 --- a/examples/ad_manager/v201802/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201811/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201802') + version='v201811') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v201802/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v201802/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py index 9a75320e..b0ad5466 100755 --- a/examples/ad_manager/v201802/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201802') + 'ActivityGroupService', version='v201811') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201802/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v201802/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py index 14857362..157800e3 100755 --- a/examples/ad_manager/v201802/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201802') + 'ActivityGroupService', version='v201811') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201802/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201811/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v201802/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v201811/activity_group_service/update_activity_groups.py index 4104eabf..79229770 100755 --- a/examples/ad_manager/v201802/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201811/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201802') + version='v201811') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', long(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/activity_service/__init__.py b/examples/ad_manager/v201811/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/activity_service/__init__.py rename to examples/ad_manager/v201811/activity_service/__init__.py diff --git a/examples/ad_manager/v201802/activity_service/create_activities.py b/examples/ad_manager/v201811/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v201802/activity_service/create_activities.py rename to examples/ad_manager/v201811/activity_service/create_activities.py index 3247775d..5ac6dd12 100755 --- a/examples/ad_manager/v201802/activity_service/create_activities.py +++ b/examples/ad_manager/v201811/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201802') + activity_service = client.GetService('ActivityService', version='v201811') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v201802/activity_service/get_active_activities.py b/examples/ad_manager/v201811/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v201802/activity_service/get_active_activities.py rename to examples/ad_manager/v201811/activity_service/get_active_activities.py index 42f224b3..5ffd0865 100755 --- a/examples/ad_manager/v201802/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201811/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201802') + activity_service = client.GetService('ActivityService', version='v201811') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201802/activity_service/get_all_activities.py b/examples/ad_manager/v201811/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v201802/activity_service/get_all_activities.py rename to examples/ad_manager/v201811/activity_service/get_all_activities.py index 9511a579..790d42b2 100755 --- a/examples/ad_manager/v201802/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201811/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201802') + activity_service = client.GetService('ActivityService', version='v201811') # Create a statement to select activities. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201802/activity_service/update_activities.py b/examples/ad_manager/v201811/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v201802/activity_service/update_activities.py rename to examples/ad_manager/v201811/activity_service/update_activities.py index 16446ff9..688c5204 100755 --- a/examples/ad_manager/v201802/activity_service/update_activities.py +++ b/examples/ad_manager/v201811/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201802') + activity_service = client.GetService('ActivityService', version='v201811') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :activityId') .WithBindVariable('activityId', long(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/audience_segment_service/__init__.py b/examples/ad_manager/v201811/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/audience_segment_service/__init__.py rename to examples/ad_manager/v201811/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v201802/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v201802/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py index 4f883aad..68cddff4 100755 --- a/examples/ad_manager/v201802/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201802') - network_service = client.GetService('NetworkService', version='v201802') + 'AudienceSegmentService', version='v201811') + network_service = client.GetService('NetworkService', version='v201811') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201802/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v201802/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py index e664d6ab..c9adf99c 100755 --- a/examples/ad_manager/v201802/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201802') + 'AudienceSegmentService', version='v201811') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201802/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v201802/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py index f83d5370..7e3208d2 100755 --- a/examples/ad_manager/v201802/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201802') + 'AudienceSegmentService', version='v201811') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201802/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v201802/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py index 2da62ba3..26c671e8 100755 --- a/examples/ad_manager/v201802/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201802') + 'AudienceSegmentService', version='v201811') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) diff --git a/examples/ad_manager/v201802/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v201802/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py index b0a223e7..4256d856 100755 --- a/examples/ad_manager/v201802/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201802') + 'AudienceSegmentService', version='v201811') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) diff --git a/examples/ad_manager/v201802/base_rate_service/__init__.py b/examples/ad_manager/v201811/base_rate_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/base_rate_service/__init__.py rename to examples/ad_manager/v201811/base_rate_service/__init__.py diff --git a/examples/ad_manager/v201802/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/ad_manager/v201802/base_rate_service/create_product_base_rates.py rename to examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py index 4be55317..96c38e73 100755 --- a/examples/ad_manager/v201802/base_rate_service/create_product_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201802') + 'BaseRateService', version='v201811') # Create a product base rate. product_base_rate = { diff --git a/examples/ad_manager/v201802/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py similarity index 99% rename from examples/ad_manager/v201802/base_rate_service/create_product_package_item_base_rates.py rename to examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py index 3f1ad600..859a1bba 100755 --- a/examples/ad_manager/v201802/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201802') + base_rate_service = client.GetService('BaseRateService', version='v201811') # Create a base rate for a product package item. product_package_item_base_rate = { diff --git a/examples/ad_manager/v201802/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py similarity index 98% rename from examples/ad_manager/v201802/base_rate_service/create_product_template_base_rates.py rename to examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py index 3e468c7b..08201601 100755 --- a/examples/ad_manager/v201802/base_rate_service/create_product_template_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201802') + 'BaseRateService', version='v201811') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/ad_manager/v201802/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py similarity index 96% rename from examples/ad_manager/v201802/base_rate_service/get_all_base_rates.py rename to examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py index 4d52fb08..8edb7d58 100755 --- a/examples/ad_manager/v201802/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201802') + base_rate_service = client.GetService('BaseRateService', version='v201811') # Create a statement to select base rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/ad_manager/v201802/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py similarity index 96% rename from examples/ad_manager/v201802/base_rate_service/get_base_rates_for_rate_card.py rename to examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py index 3b30931e..83a7351d 100755 --- a/examples/ad_manager/v201802/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py @@ -24,9 +24,9 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201802') + base_rate_service = client.GetService('BaseRateService', version='v201811') # Create a statement to select base rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) diff --git a/examples/ad_manager/v201802/base_rate_service/update_base_rates.py b/examples/ad_manager/v201811/base_rate_service/update_base_rates.py similarity index 96% rename from examples/ad_manager/v201802/base_rate_service/update_base_rates.py rename to examples/ad_manager/v201811/base_rate_service/update_base_rates.py index 76dbc7d5..35aa22d8 100755 --- a/examples/ad_manager/v201802/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/update_base_rates.py @@ -29,10 +29,10 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201802') + base_rate_service = client.GetService('BaseRateService', version='v201811') # Create a filter statement for base rates for a single rate card. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201802/cdn_configuration_service/__init__.py b/examples/ad_manager/v201811/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/cdn_configuration_service/__init__.py rename to examples/ad_manager/v201811/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v201802/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201811/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v201802/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v201811/cdn_configuration_service/create_cdn_configurations.py index 2b8f33bd..946ee564 100755 --- a/examples/ad_manager/v201802/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v201811/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201802') + version='v201811') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v201802/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v201802/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py index 98534c94..9aa41520 100755 --- a/examples/ad_manager/v201802/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201802') + version='v201811') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v201802/company_service/__init__.py b/examples/ad_manager/v201811/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/company_service/__init__.py rename to examples/ad_manager/v201811/company_service/__init__.py diff --git a/examples/ad_manager/v201802/company_service/create_companies.py b/examples/ad_manager/v201811/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v201802/company_service/create_companies.py rename to examples/ad_manager/v201811/company_service/create_companies.py index 66c36d80..6f1d5de1 100755 --- a/examples/ad_manager/v201802/company_service/create_companies.py +++ b/examples/ad_manager/v201811/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201802') + company_service = client.GetService('CompanyService', version='v201811') # Create company objects. companies = [ diff --git a/examples/ad_manager/v201802/company_service/get_advertisers.py b/examples/ad_manager/v201811/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v201802/company_service/get_advertisers.py rename to examples/ad_manager/v201811/company_service/get_advertisers.py index 423248a3..edfd6091 100755 --- a/examples/ad_manager/v201802/company_service/get_advertisers.py +++ b/examples/ad_manager/v201811/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201802') + company_service = client.GetService('CompanyService', version='v201811') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201802/company_service/get_all_companies.py b/examples/ad_manager/v201811/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v201802/company_service/get_all_companies.py rename to examples/ad_manager/v201811/company_service/get_all_companies.py index 46cfbcee..d45cc748 100755 --- a/examples/ad_manager/v201802/company_service/get_all_companies.py +++ b/examples/ad_manager/v201811/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201802') + company_service = client.GetService('CompanyService', version='v201811') # Create a statement to select companies. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201802/company_service/update_companies.py b/examples/ad_manager/v201811/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v201802/company_service/update_companies.py rename to examples/ad_manager/v201811/company_service/update_companies.py index 1d70bb9a..631b6024 100755 --- a/examples/ad_manager/v201802/company_service/update_companies.py +++ b/examples/ad_manager/v201811/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201802') + company_service = client.GetService('CompanyService', version='v201811') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', long(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/contact_service/__init__.py b/examples/ad_manager/v201811/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/contact_service/__init__.py rename to examples/ad_manager/v201811/contact_service/__init__.py diff --git a/examples/ad_manager/v201802/contact_service/create_contacts.py b/examples/ad_manager/v201811/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v201802/contact_service/create_contacts.py rename to examples/ad_manager/v201811/contact_service/create_contacts.py index 675cc03c..d805ea92 100755 --- a/examples/ad_manager/v201802/contact_service/create_contacts.py +++ b/examples/ad_manager/v201811/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201802') + contact_service = client.GetService('ContactService', version='v201811') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v201802/contact_service/get_all_contacts.py b/examples/ad_manager/v201811/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v201802/contact_service/get_all_contacts.py rename to examples/ad_manager/v201811/contact_service/get_all_contacts.py index 2afe600c..8df2e0ea 100755 --- a/examples/ad_manager/v201802/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201811/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201802') + contact_service = client.GetService('ContactService', version='v201811') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201802/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v201802/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py index 4ee94a3d..a2f97fad 100755 --- a/examples/ad_manager/v201802/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201802') + contact_service = client.GetService('ContactService', version='v201811') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201802/contact_service/update_contacts.py b/examples/ad_manager/v201811/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v201802/contact_service/update_contacts.py rename to examples/ad_manager/v201811/contact_service/update_contacts.py index cc46f9d2..d568d80e 100755 --- a/examples/ad_manager/v201802/contact_service/update_contacts.py +++ b/examples/ad_manager/v201811/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201802') + contact_service = client.GetService('ContactService', version='v201811') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', long(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/content_metadata_key_hierarchy_service/__init__.py rename to examples/ad_manager/v201811/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/ad_manager/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201811/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index cd5255e5..1f0452b6 100755 --- a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201802') + 'ContentMetadataKeyHierarchyService', version='v201811') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 94% rename from examples/ad_manager/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201811/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index cae8df2b..4da6014a 100755 --- a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201802') + 'ContentMetadataKeyHierarchyService', version='v201811') # Create a statement to select content metadata key hierarchies. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been diff --git a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 96% rename from examples/ad_manager/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201811/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 094441b9..96f131ac 100755 --- a/examples/ad_manager/v201802/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,11 +42,11 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201802') + 'ContentMetadataKeyHierarchyService', version='v201811') # Create a query to select a single content metadata key hierarchy. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) diff --git a/examples/ad_manager/v201802/content_service/__init__.py b/examples/ad_manager/v201811/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/content_service/__init__.py rename to examples/ad_manager/v201811/content_service/__init__.py diff --git a/examples/ad_manager/v201802/content_service/get_all_content.py b/examples/ad_manager/v201811/content_service/get_all_content.py similarity index 95% rename from examples/ad_manager/v201802/content_service/get_all_content.py rename to examples/ad_manager/v201811/content_service/get_all_content.py index 98fc5126..1d0561d8 100755 --- a/examples/ad_manager/v201802/content_service/get_all_content.py +++ b/examples/ad_manager/v201811/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201802') + content_service = client.GetService('ContentService', version='v201811') # Create a statement to select content. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v201802/creative_service/__init__.py b/examples/ad_manager/v201811/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/creative_service/__init__.py rename to examples/ad_manager/v201811/creative_service/__init__.py diff --git a/examples/ad_manager/v201802/creative_service/copy_image_creatives.py b/examples/ad_manager/v201811/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v201802/creative_service/copy_image_creatives.py rename to examples/ad_manager/v201811/creative_service/copy_image_creatives.py index c3b481be..9847fd68 100755 --- a/examples/ad_manager/v201802/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201811/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201802') + creative_service = client.GetService('CreativeService', version='v201811') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201802/creative_service/create_creative_from_template.py b/examples/ad_manager/v201811/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v201802/creative_service/create_creative_from_template.py rename to examples/ad_manager/v201811/creative_service/create_creative_from_template.py index 874bec7b..0d41b549 100755 --- a/examples/ad_manager/v201802/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201811/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201802') + creative_service = client.GetService('CreativeService', version='v201811') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v201802/creative_service/create_creatives.py b/examples/ad_manager/v201811/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v201802/creative_service/create_creatives.py rename to examples/ad_manager/v201811/creative_service/create_creatives.py index afda4e42..29c8281d 100755 --- a/examples/ad_manager/v201802/creative_service/create_creatives.py +++ b/examples/ad_manager/v201811/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201802') + creative_service = client.GetService('CreativeService', version='v201811') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v201802/creative_service/create_custom_creative.py b/examples/ad_manager/v201811/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v201802/creative_service/create_custom_creative.py rename to examples/ad_manager/v201811/creative_service/create_custom_creative.py index c24c6640..21dac3a4 100755 --- a/examples/ad_manager/v201802/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201811/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201802') + creative_service = client.GetService('CreativeService', version='v201811') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v201802/creative_service/create_native_creative.py b/examples/ad_manager/v201811/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v201802/creative_service/create_native_creative.py rename to examples/ad_manager/v201811/creative_service/create_native_creative.py index b7653eb5..62198290 100755 --- a/examples/ad_manager/v201802/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201811/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201802') + creative_service = client.GetService('CreativeService', version='v201811') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v201802/creative_service/get_all_creatives.py b/examples/ad_manager/v201811/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v201802/creative_service/get_all_creatives.py rename to examples/ad_manager/v201811/creative_service/get_all_creatives.py index 4ae2ccb4..d1aa3ccc 100755 --- a/examples/ad_manager/v201802/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201811/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201802') + creative_service = client.GetService('CreativeService', version='v201811') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201802/creative_service/get_image_creatives.py b/examples/ad_manager/v201811/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v201802/creative_service/get_image_creatives.py rename to examples/ad_manager/v201811/creative_service/get_image_creatives.py index 78956e3e..a3032af8 100755 --- a/examples/ad_manager/v201802/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201811/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201802') + creative_service = client.GetService('CreativeService', version='v201811') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201802/creative_service/update_creatives.py b/examples/ad_manager/v201811/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v201802/creative_service/update_creatives.py rename to examples/ad_manager/v201811/creative_service/update_creatives.py index 1c482118..9a995e01 100755 --- a/examples/ad_manager/v201802/creative_service/update_creatives.py +++ b/examples/ad_manager/v201811/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201802') + creative_service = client.GetService('CreativeService', version='v201811') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', long(image_creative_id)) diff --git a/examples/ad_manager/v201802/creative_set_service/__init__.py b/examples/ad_manager/v201811/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/creative_set_service/__init__.py rename to examples/ad_manager/v201811/creative_set_service/__init__.py diff --git a/examples/ad_manager/v201802/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v201802/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py index 6440584c..5237b11a 100755 --- a/examples/ad_manager/v201802/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201802') + 'LineItemCreativeAssociationService', version='v201811') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v201802/creative_set_service/create_creative_set.py b/examples/ad_manager/v201811/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v201802/creative_set_service/create_creative_set.py rename to examples/ad_manager/v201811/creative_set_service/create_creative_set.py index c3d58a6b..b4911012 100755 --- a/examples/ad_manager/v201802/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201811/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201802') + version='v201811') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v201802/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v201802/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py index 5c9e865b..51bdb6c2 100755 --- a/examples/ad_manager/v201802/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201802') + 'CreativeSetService', version='v201811') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201802/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v201802/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py index ba946129..0f815e34 100755 --- a/examples/ad_manager/v201802/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201802') + 'CreativeSetService', version='v201811') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201802/creative_set_service/update_creative_set.py b/examples/ad_manager/v201811/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v201802/creative_set_service/update_creative_set.py rename to examples/ad_manager/v201811/creative_set_service/update_creative_set.py index 9182645e..56bb53ca 100755 --- a/examples/ad_manager/v201802/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201811/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201802') + version='v201811') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', long(creative_set_id))) diff --git a/examples/ad_manager/v201802/creative_template_service/__init__.py b/examples/ad_manager/v201811/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/creative_template_service/__init__.py rename to examples/ad_manager/v201811/creative_template_service/__init__.py diff --git a/examples/ad_manager/v201802/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v201802/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py index f7b75e72..0947f151 100755 --- a/examples/ad_manager/v201802/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201802') + 'CreativeTemplateService', version='v201811') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201802/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v201802/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py index c93a7757..1e3a7d9f 100755 --- a/examples/ad_manager/v201802/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201802') + 'CreativeTemplateService', version='v201811') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201802/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v201802/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py index 4202a22e..695a1394 100755 --- a/examples/ad_manager/v201802/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201802') + version='v201811') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v201802/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v201802/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py index 1326aac3..d6a21e51 100755 --- a/examples/ad_manager/v201802/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201802') + version='v201811') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', long(label_id))) diff --git a/examples/ad_manager/v201802/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201802/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py index 976a62b5..57ef0f75 100755 --- a/examples/ad_manager/v201802/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201802') + 'CreativeWrapperService', version='v201811') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201802/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201802/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py index a2038391..1fc76c2c 100755 --- a/examples/ad_manager/v201802/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201802') + 'CreativeWrapperService', version='v201811') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201802/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v201802/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py index e00f3c78..3e69db75 100755 --- a/examples/ad_manager/v201802/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201802') + version='v201811') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', long(creative_wrapper_id))) diff --git a/examples/ad_manager/v201802/custom_field_service/__init__.py b/examples/ad_manager/v201811/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/custom_field_service/__init__.py rename to examples/ad_manager/v201811/custom_field_service/__init__.py diff --git a/examples/ad_manager/v201802/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v201802/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py index 97e58514..15d56b00 100755 --- a/examples/ad_manager/v201802/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201802') + 'CustomFieldService', version='v201811') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v201802/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201811/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v201802/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v201811/custom_field_service/create_custom_fields.py index 03a212ea..eac70950 100755 --- a/examples/ad_manager/v201802/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201811/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201802') + 'CustomFieldService', version='v201811') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py index 4c9f4582..c5c0dec2 100755 --- a/examples/ad_manager/v201802/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201802') + 'CustomFieldService', version='v201811') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201802/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v201802/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py index 96994073..8cfe0088 100755 --- a/examples/ad_manager/v201802/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201802') + 'CustomFieldService', version='v201811') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201802/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v201802/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py index 2e5bcacc..c0f107bb 100755 --- a/examples/ad_manager/v201802/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201802') + 'CustomFieldService', version='v201811') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201802/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py similarity index 95% rename from examples/ad_manager/v201802/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py index 586332e0..4d1f28bb 100755 --- a/examples/ad_manager/v201802/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201802') + 'CustomFieldService', version='v201811') - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder() + custom_field_statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder() + ad_manager.StatementBuilder(version='v201811') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder() + line_item_statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201802/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201811/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v201802/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v201811/custom_field_service/update_custom_fields.py index 1dc42beb..fd89034b 100755 --- a/examples/ad_manager/v201802/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201811/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201802') + 'CustomFieldService', version='v201811') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :customFieldId') .WithBindVariable('customFieldId', long(custom_field_id))) diff --git a/examples/ad_manager/v201802/custom_targeting_service/__init__.py b/examples/ad_manager/v201811/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/custom_targeting_service/__init__.py rename to examples/ad_manager/v201811/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py index 2c4dc58e..0aad2f4d 100755 --- a/examples/ad_manager/v201802/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201802') + 'CustomTargetingService', version='v201811') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py similarity index 93% rename from examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py index dddca3e6..facf35a1 100755 --- a/examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201802') + 'CustomTargetingService', version='v201811') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder() + key_statement = (ad_manager.StatementBuilder(version='v201811') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py similarity index 93% rename from examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py index 869c7c2e..5585346b 100755 --- a/examples/ad_manager/v201802/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201802') + 'CustomTargetingService', version='v201811') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder() + value_statement = (ad_manager.StatementBuilder(version='v201811') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 93% rename from examples/ad_manager/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 4771088a..121b234a 100755 --- a/examples/ad_manager/v201802/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201802') + 'CustomTargetingService', version='v201811') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder() + targeting_key_statement = ad_manager.StatementBuilder(version='v201811') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 93% rename from examples/ad_manager/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index ef65c3f9..a56c0b4e 100755 --- a/examples/ad_manager/v201802/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201802') + 'CustomTargetingService', version='v201811') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder() + targeting_key_statement = (ad_manager.StatementBuilder(version='v201811') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py index be7f1a4c..977ffcca 100755 --- a/examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201802') + 'CustomTargetingService', version='v201811') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :keyId') .WithBindVariable('keyId', long(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py index 6063ccd9..496e1be2 100755 --- a/examples/ad_manager/v201802/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201802') + 'CustomTargetingService', version='v201811') - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', long(key_id))) diff --git a/examples/ad_manager/v201802/exchange_rate_service/__init__.py b/examples/ad_manager/v201811/exchange_rate_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/exchange_rate_service/__init__.py rename to examples/ad_manager/v201811/exchange_rate_service/__init__.py diff --git a/examples/ad_manager/v201802/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/ad_manager/v201802/exchange_rate_service/create_exchange_rates.py rename to examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py index 5f717426..47860fb1 100755 --- a/examples/ad_manager/v201802/exchange_rate_service/create_exchange_rates.py +++ b/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201802') + version='v201811') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/ad_manager/v201802/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py similarity index 94% rename from examples/ad_manager/v201802/exchange_rate_service/get_all_exchange_rates.py rename to examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py index 626499c6..af9fc376 100755 --- a/examples/ad_manager/v201802/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201802') + 'ExchangeRateService', version='v201811') # Create a statement to select exchange rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/ad_manager/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 94% rename from examples/ad_manager/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py index 0799cde2..d1830859 100755 --- a/examples/ad_manager/v201802/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,9 +25,9 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201802') + 'ExchangeRateService', version='v201811') # Create a statement to select exchange rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('currencyCode = :currencyCode') .WithBindVariable('currencyCode', currency_code)) diff --git a/examples/ad_manager/v201802/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py similarity index 95% rename from examples/ad_manager/v201802/exchange_rate_service/update_exchange_rates.py rename to examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py index f2de4bed..59cace62 100755 --- a/examples/ad_manager/v201802/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py @@ -30,10 +30,10 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201802') + version='v201811') # Create a statement to get an exchange rate by its ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', long(exchange_rate_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py new file mode 100755 index 00000000..96980310 --- /dev/null +++ b/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 a forecast for a prospective line item. + +The prospective line item targets the entire network. The targeting can be +modified to determine forecasts for other criteria such as custom criteria +targeting (in addition to targeting the whole network). See +create_line_items.py for an example of how to create more complex targeting. + +""" + + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201811') + network_service = client.GetService('NetworkService', version='v201811') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + + now_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = now_datetime + datetime.timedelta(days=5) + + # Create prospective line item. + line_item = { + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + } + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + }, + 'isAmpOnly': True, + }, + { + 'size': { + 'width': '120', + 'height': '600' + } + } + ], + 'lineItemType': 'SPONSORSHIP', + 'startDateTimeType': 'IMMEDIATELY', + 'endDateTime': end_datetime, + 'costType': 'CPM', + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'primaryGoal': { + 'units': '50', + 'unitType': 'IMPRESSIONS', + 'goalType': 'DAILY' + }, + 'contractedUnitsBought': '100', + 'creativeRotationType': 'EVEN', + 'discountType': 'PERCENTAGE', + } + + prospective_line_item = { + 'lineItem': line_item, + 'advertiserId': advertiser_id + } + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + # The field includeTargetingCriteriaBreakdown can only be set if + # breakdowns are not manually specified. + # 'includeTargetingCriteriaBreakdown': True, + 'breakdown': { + 'timeWindows': [ + now_datetime, + now_datetime + datetime.timedelta(days=1), + now_datetime + datetime.timedelta(days=2), + now_datetime + datetime.timedelta(days=3), + now_datetime + datetime.timedelta(days=4), + end_datetime + ], + 'targets': [ + { + # Optional, the name field is only used to identify this + # breakdown in the response. + 'name': 'United States', + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '2840', + 'displayName': 'US' + } + ] + } + } + }, + { + # Optional, the name field is only used to identify this + # breakdown in the response. + 'name': 'Geneva', + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '20133', + 'displayName': 'Geneva' + } + ] + } + } + } + ] + } + } + + # Get forecast. + forecast = forecast_service.getAvailabilityForecast( + prospective_line_item, forecast_options) + matched = forecast['matchedUnits'] + available = forecast['availableUnits'] + possible = forecast['possibleUnits'] if 'possibleUnits' in forecast else None + unit_type = forecast['unitType'].lower() + + available_percent_overall, possible_percent_overall = CalculateForecastStats( + matched, available, possible) + + contending_line_items = getattr(forecast, 'contendingLineItems', []) + + # Display results. + print '%s %s matched overall.' % (matched, unit_type) + print '%s%% %s available overall.' % (available_percent_overall, unit_type) + print '%d contending line items overall.' % len(contending_line_items) + if possible: + print '%s%% %s possible overall.' % (possible_percent_overall, unit_type) + + if 'breakdowns' in forecast and len(forecast['breakdowns']): + for breakdown in forecast['breakdowns']: + print 'For breakdown time period %s - %s:' % ( + FormatSOAPDateTime(breakdown['startTime']), + FormatSOAPDateTime(breakdown['endTime'])) + for breakdown_entry in breakdown['breakdownEntries']: + matched = breakdown_entry['forecast']['matched'] + available = breakdown_entry['forecast']['available'] + possible = (breakdown_entry['forecast']['possible'] + if 'possible' in breakdown_entry['forecast'] else None) + name = breakdown_entry['name'] if 'name' in breakdown_entry else None + if name: + print '\tFor targeting breakdown named \'%s\'' % name + available_percent, possible_percent = CalculateForecastStats( + matched, available, possible) + print '\t\t%s %s matched.' % (matched, unit_type) + print '\t\t%s%% %s available.' % (available_percent, unit_type) + if possible: + print '\t\t%s%% %s possible.' % (possible_percent, unit_type) + + +def FormatSOAPDateTime(value): + """Format a SOAP DateTime object for printing. + + Args: + value: The DateTime object to format. + + Returns: + A string representing the value. + """ + value_date = value['date'] + return '%s-%s-%s %s:%s:%s (%s)' % ( + value_date['year'], value_date['month'], value_date['day'], + value['hour'], value['minute'], value['second'], value['timeZoneId']) + + +def CalculateForecastStats(matched, available, possible=None): + """Calculate forecast percentage stats. + + Args: + matched: The number of matched impressions. + available: The number of available impressions. + possible: The optional number of possible impressions. + + Returns: + The percentage of impressions that are available and possible. + """ + if matched > 0: + available_percent = (float(available) / matched) * 100. + else: + available_percent = 0 + + if possible is not None: + if matched > 0: + possible_percent = (possible/float(matched)) * 100. + else: + possible_percent = 0 + else: + possible_percent = None + + return available_percent, possible_percent + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201802/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v201802/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py index 38dec1ad..ef58d378 100755 --- a/examples/ad_manager/v201802/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201802') + forecast_service = client.GetService('ForecastService', version='v201811') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v201802/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v201802/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py index 911d9f1a..2404c016 100755 --- a/examples/ad_manager/v201802/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201802') + forecast_service = client.GetService('ForecastService', version='v201811') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v201802/inventory_service/__init__.py b/examples/ad_manager/v201811/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/inventory_service/__init__.py rename to examples/ad_manager/v201811/inventory_service/__init__.py diff --git a/examples/ad_manager/v201802/inventory_service/archive_ad_units.py b/examples/ad_manager/v201811/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v201802/inventory_service/archive_ad_units.py rename to examples/ad_manager/v201811/inventory_service/archive_ad_units.py index 27e4fabc..1b8c147e 100755 --- a/examples/ad_manager/v201802/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201811') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', long(parent_id))) diff --git a/examples/ad_manager/v201802/inventory_service/create_ad_units.py b/examples/ad_manager/v201811/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v201802/inventory_service/create_ad_units.py rename to examples/ad_manager/v201811/inventory_service/create_ad_units.py index 0891613f..5e895033 100755 --- a/examples/ad_manager/v201802/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201811') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v201802/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v201802/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py index e8037b15..6c762676 100755 --- a/examples/ad_manager/v201802/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201802') - inventory_service = client.GetService('InventoryService', version='v201802') + network_service = client.GetService('NetworkService', version='v201811') + inventory_service = client.GetService('InventoryService', version='v201811') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201802/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201811/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v201802/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v201811/inventory_service/get_all_ad_unit_sizes.py index 07c08062..15a46a52 100755 --- a/examples/ad_manager/v201802/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201811/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201802') + 'InventoryService', version='v201811') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201802/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201811/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v201802/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v201811/inventory_service/get_all_ad_units.py index bbc6024c..74a6e595 100755 --- a/examples/ad_manager/v201802/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201802') + ad_unit_service = client.GetService('InventoryService', version='v201811') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201802/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v201802/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py index ec2d411c..1be9801e 100755 --- a/examples/ad_manager/v201802/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201802') - inventory_service = client.GetService('InventoryService', version='v201802') + network_service = client.GetService('NetworkService', version='v201811') + inventory_service = client.GetService('InventoryService', version='v201811') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201802/inventory_service/update_ad_units.py b/examples/ad_manager/v201811/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v201802/inventory_service/update_ad_units.py rename to examples/ad_manager/v201811/inventory_service/update_ad_units.py index b3386efd..e491dfe7 100755 --- a/examples/ad_manager/v201802/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201802') + inventory_service = client.GetService('InventoryService', version='v201811') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201802/label_service/__init__.py b/examples/ad_manager/v201811/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/label_service/__init__.py rename to examples/ad_manager/v201811/label_service/__init__.py diff --git a/examples/ad_manager/v201802/label_service/create_labels.py b/examples/ad_manager/v201811/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v201802/label_service/create_labels.py rename to examples/ad_manager/v201811/label_service/create_labels.py index 31366328..bc23bcbe 100755 --- a/examples/ad_manager/v201802/label_service/create_labels.py +++ b/examples/ad_manager/v201811/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201802') + label_service = client.GetService('LabelService', version='v201811') # Create label objects. labels = [] diff --git a/examples/ad_manager/v201802/label_service/deactivate_labels.py b/examples/ad_manager/v201811/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v201802/label_service/deactivate_labels.py rename to examples/ad_manager/v201811/label_service/deactivate_labels.py index 22672fdd..a13891c2 100755 --- a/examples/ad_manager/v201802/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201811/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201802') + label_service = client.GetService('LabelService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201802/label_service/get_active_labels.py b/examples/ad_manager/v201811/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v201802/label_service/get_active_labels.py rename to examples/ad_manager/v201811/label_service/get_active_labels.py index a4b1e9d8..e98c0204 100755 --- a/examples/ad_manager/v201802/label_service/get_active_labels.py +++ b/examples/ad_manager/v201811/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201802') + label_service = client.GetService('LabelService', version='v201811') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201802/label_service/get_all_labels.py b/examples/ad_manager/v201811/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v201802/label_service/get_all_labels.py rename to examples/ad_manager/v201811/label_service/get_all_labels.py index a3fdbd14..a14f966a 100755 --- a/examples/ad_manager/v201802/label_service/get_all_labels.py +++ b/examples/ad_manager/v201811/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201802') + label_service = client.GetService('LabelService', version='v201811') # Create a statement to select labels. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201802/label_service/update_labels.py b/examples/ad_manager/v201811/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v201802/label_service/update_labels.py rename to examples/ad_manager/v201811/label_service/update_labels.py index 485f43b2..ef17d615 100755 --- a/examples/ad_manager/v201802/label_service/update_labels.py +++ b/examples/ad_manager/v201811/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201802') + label_service = client.GetService('LabelService', version='v201811') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :labelId') .WithBindVariable('labelId', long(label_id))) diff --git a/examples/ad_manager/v201802/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201811/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v201811/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v201802/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v201802/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py index f881d6d7..4ceebff4 100755 --- a/examples/ad_manager/v201802/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201802') + 'LineItemCreativeAssociationService', version='v201811') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v201802/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v201802/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py index cf9815c1..631b0609 100755 --- a/examples/ad_manager/v201802/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201802') + 'LineItemCreativeAssociationService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', long(line_item_id))) diff --git a/examples/ad_manager/v201802/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v201802/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py index 9a5fb443..60fafdf2 100755 --- a/examples/ad_manager/v201802/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201802') + 'LineItemCreativeAssociationService', version='v201811') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201802/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v201802/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py index c1a8bf72..34d13685 100755 --- a/examples/ad_manager/v201802/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201802') + 'LineItemCreativeAssociationService', version='v201811') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201802/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v201802/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py index e4658ad6..6bedb97d 100755 --- a/examples/ad_manager/v201802/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201802') + 'LineItemCreativeAssociationService', version='v201811') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201802/line_item_service/__init__.py b/examples/ad_manager/v201811/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/line_item_service/__init__.py rename to examples/ad_manager/v201811/line_item_service/__init__.py diff --git a/examples/ad_manager/v201802/line_item_service/activate_line_items.py b/examples/ad_manager/v201811/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v201802/line_item_service/activate_line_items.py rename to examples/ad_manager/v201811/line_item_service/activate_line_items.py index ec24ee04..07c8713e 100755 --- a/examples/ad_manager/v201802/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201802/line_item_service/create_line_items.py b/examples/ad_manager/v201811/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v201802/line_item_service/create_line_items.py rename to examples/ad_manager/v201811/line_item_service/create_line_items.py index 2f9788f5..c7e47097 100755 --- a/examples/ad_manager/v201802/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201802/line_item_service/create_video_line_item.py b/examples/ad_manager/v201811/line_item_service/create_video_line_item.py similarity index 76% rename from examples/ad_manager/v201802/line_item_service/create_video_line_item.py rename to examples/ad_manager/v201811/line_item_service/create_video_line_item.py index 19a7e3d7..cc04d6c8 100755 --- a/examples/ad_manager/v201802/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v201811/line_item_service/create_video_line_item.py @@ -16,11 +16,7 @@ """This code example creates a new line item to serve to video content. -This feature is only available to Ad Manager 360 solution networks. To determine -which line items exist, run get_all_line_items.py. To determine which orders -exist, run get_all_orders.py. To create a video ad unit, run -create_video_ad_unit.py. To create criteria for categories, run -create_custom_targeting_keys_and_values.py. +This feature is only available to Ad Manager 360 solution networks. """ @@ -36,32 +32,30 @@ ORDER_ID = 'INSERT_ORDER_ID_HERE' TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE' -# Set the custom targeting value ID representing the metadata -# on the content to target. This would typically be from a key representing -# a "genre" and the value representing something like "comedy". The value -# must be from a key in a content metadata key hierarchy. -CONTENT_CUSTOM_TARGETING_VALUE_ID = ( - 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE') +# Set the video content to target. +CONTENT_ID = 'INSERT_CONTENT_ID_HERE' +# Set the video content bundle to target. +CONTENT_BUNDLE_ID = 'INSERT_CONTENT_BUNDLE_ID_HERE' -def main(client, order_id, targeted_video_ad_unit_id, - content_custom_targeting_value_id): +def main(client, order_id, targeted_video_ad_unit_id, content_id, + content_bundle_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) # Create line item object. line_item = { - 'name': 'Line item #%s' % uuid.uuid4(), - 'orderId': order_id, + 'name': + 'Line item #%s' % uuid.uuid4(), + 'orderId': + order_id, 'targeting': { 'contentTargeting': { - 'targetedContentMetadata': [ - {'customTargetingValueIds': [ - content_custom_targeting_value_id]} - ] + 'targetedContentIds': [content_id], + 'targetedContentBundleIds': [content_bundle_id] }, 'inventoryTargeting': { 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id, @@ -131,5 +125,5 @@ def main(client, order_id, targeted_video_ad_unit_id, if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, - CONTENT_CUSTOM_TARGETING_VALUE_ID) + main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_ID, + CONTENT_BUNDLE_ID) diff --git a/examples/ad_manager/v201802/line_item_service/get_all_line_items.py b/examples/ad_manager/v201811/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v201802/line_item_service/get_all_line_items.py rename to examples/ad_manager/v201811/line_item_service/get_all_line_items.py index 223484aa..767e4837 100755 --- a/examples/ad_manager/v201802/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') # Create a statement to select line items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201802/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v201802/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py index e309e0e4..6334f9f1 100755 --- a/examples/ad_manager/v201802/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201802/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v201802/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py index 2d14225e..f2b6b9b7 100755 --- a/examples/ad_manager/v201802/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201802/line_item_service/pause_line_items.py b/examples/ad_manager/v201811/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v201802/line_item_service/pause_line_items.py rename to examples/ad_manager/v201811/line_item_service/pause_line_items.py index f902871f..7ff28685 100755 --- a/examples/ad_manager/v201802/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201802/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201811/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v201802/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v201811/line_item_service/target_custom_criteria.py index 16c2d087..44d1b8be 100755 --- a/examples/ad_manager/v201802/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201811/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :lineItemId') .WithBindVariable('lineItemId', long(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/line_item_service/update_line_items.py b/examples/ad_manager/v201811/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v201802/line_item_service/update_line_items.py rename to examples/ad_manager/v201811/line_item_service/update_line_items.py index 578add23..cdde787a 100755 --- a/examples/ad_manager/v201802/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', long(order_id)) diff --git a/examples/ad_manager/v201802/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201802/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py index 6961f7a1..8ea6729e 100755 --- a/examples/ad_manager/v201802/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201802') + 'LiveStreamEventService', version='v201811') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201802/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201811/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v201802/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v201811/live_stream_event_service/create_live_stream_events.py index d97066d8..1045916d 100755 --- a/examples/ad_manager/v201802/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v201811/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201802') + 'LiveStreamEventService', version='v201811') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v201802/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v201802/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py index ebbeb937..0c81200b 100755 --- a/examples/ad_manager/v201802/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201802') + 'LiveStreamEventService', version='v201811') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201802/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v201802/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py index b9b49175..a3e1a13d 100755 --- a/examples/ad_manager/v201802/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201802') + 'LiveStreamEventService', version='v201811') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v201802/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201802/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py index b4cd1d12..eb179188 100755 --- a/examples/ad_manager/v201802/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201802') + 'LiveStreamEventService', version='v201811') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('Id = :id')) .WithBindVariable('id', long(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201802/native_style_service/__init__.py b/examples/ad_manager/v201811/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/native_style_service/__init__.py rename to examples/ad_manager/v201811/native_style_service/__init__.py diff --git a/examples/ad_manager/v201802/native_style_service/create_native_styles.py b/examples/ad_manager/v201811/native_style_service/create_native_styles.py similarity index 97% rename from examples/ad_manager/v201802/native_style_service/create_native_styles.py rename to examples/ad_manager/v201811/native_style_service/create_native_styles.py index 4b923cc2..9780d39b 100755 --- a/examples/ad_manager/v201802/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201811/native_style_service/create_native_styles.py @@ -99,15 +99,13 @@ width: 100%; border-radius: 20%; } -.title, -.promo-headline { +.title { font-weight: bold; font-size: 14px; line-height: 20px; margin: 8px 8px 4px 8px; } -.title a, -.promo-headline { +.title a { color: rgba(112, 112, 112, 1); text-decoration: none; } @@ -149,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201802') + version='v201811') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v201802/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201811/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v201802/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v201811/native_style_service/get_all_native_styles.py index 3c2bb81b..1900c486 100755 --- a/examples/ad_manager/v201802/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201811/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201802') + version='v201811') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201802/network_service/__init__.py b/examples/ad_manager/v201811/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/network_service/__init__.py rename to examples/ad_manager/v201811/network_service/__init__.py diff --git a/examples/ad_manager/v201802/network_service/get_all_networks.py b/examples/ad_manager/v201811/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v201802/network_service/get_all_networks.py rename to examples/ad_manager/v201811/network_service/get_all_networks.py index cefa51da..6442bac6 100755 --- a/examples/ad_manager/v201802/network_service/get_all_networks.py +++ b/examples/ad_manager/v201811/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201802') + network_service = client.GetService('NetworkService', version='v201811') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v201802/network_service/get_current_network.py b/examples/ad_manager/v201811/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v201802/network_service/get_current_network.py rename to examples/ad_manager/v201811/network_service/get_current_network.py index 75497a1d..0c9eb594 100755 --- a/examples/ad_manager/v201802/network_service/get_current_network.py +++ b/examples/ad_manager/v201811/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201802') + network_service = client.GetService('NetworkService', version='v201811') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201802/network_service/make_test_network.py b/examples/ad_manager/v201811/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v201802/network_service/make_test_network.py rename to examples/ad_manager/v201811/network_service/make_test_network.py index 2bcf7f2b..a85aa508 100755 --- a/examples/ad_manager/v201802/network_service/make_test_network.py +++ b/examples/ad_manager/v201811/network_service/make_test_network.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201802') + network_service = client.GetService('NetworkService', version='v201811') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v201802/order_service/__init__.py b/examples/ad_manager/v201811/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/order_service/__init__.py rename to examples/ad_manager/v201811/order_service/__init__.py diff --git a/examples/ad_manager/v201802/order_service/approve_orders.py b/examples/ad_manager/v201811/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v201802/order_service/approve_orders.py rename to examples/ad_manager/v201811/order_service/approve_orders.py index a65b3123..edc36d5d 100755 --- a/examples/ad_manager/v201802/order_service/approve_orders.py +++ b/examples/ad_manager/v201811/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201802') + order_service = client.GetService('OrderService', version='v201811') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201802/order_service/create_orders.py b/examples/ad_manager/v201811/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v201802/order_service/create_orders.py rename to examples/ad_manager/v201811/order_service/create_orders.py index b146b6ce..49facb27 100755 --- a/examples/ad_manager/v201802/order_service/create_orders.py +++ b/examples/ad_manager/v201811/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201802') + order_service = client.GetService('OrderService', version='v201811') # Create order objects. orders = [] diff --git a/examples/ad_manager/v201802/order_service/get_all_orders.py b/examples/ad_manager/v201811/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v201802/order_service/get_all_orders.py rename to examples/ad_manager/v201811/order_service/get_all_orders.py index 24a71b7a..03a15c6c 100755 --- a/examples/ad_manager/v201802/order_service/get_all_orders.py +++ b/examples/ad_manager/v201811/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201802') + order_service = client.GetService('OrderService', version='v201811') # Create a statement to select orders. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201802/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201811/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v201802/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v201811/order_service/get_orders_starting_soon.py index ea98550a..7fee3aae 100755 --- a/examples/ad_manager/v201802/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201811/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201802') + order_service = client.GetService('OrderService', version='v201811') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201802/order_service/update_orders.py b/examples/ad_manager/v201811/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v201802/order_service/update_orders.py rename to examples/ad_manager/v201811/order_service/update_orders.py index d66a05e3..6fb03b32 100755 --- a/examples/ad_manager/v201802/order_service/update_orders.py +++ b/examples/ad_manager/v201811/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201802') + order_service = client.GetService('OrderService', version='v201811') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :orderId') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201802/package_service/create_packages.py b/examples/ad_manager/v201811/package_service/create_packages.py similarity index 99% rename from examples/ad_manager/v201802/package_service/create_packages.py rename to examples/ad_manager/v201811/package_service/create_packages.py index ad27f86d..097c8d68 100755 --- a/examples/ad_manager/v201802/package_service/create_packages.py +++ b/examples/ad_manager/v201811/package_service/create_packages.py @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201802') + package_service = client.GetService('PackageService', version='v201811') # Create local package. package = { diff --git a/examples/ad_manager/v201802/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py similarity index 96% rename from examples/ad_manager/v201802/package_service/create_proposal_line_items_from_packages.py rename to examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py index 562b65b1..c8eee245 100755 --- a/examples/ad_manager/v201802/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201802') + package_service = client.GetService('PackageService', version='v201811') # Create a statement to select the single package. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201802/package_service/get_all_packages.py b/examples/ad_manager/v201811/package_service/get_all_packages.py similarity index 96% rename from examples/ad_manager/v201802/package_service/get_all_packages.py rename to examples/ad_manager/v201811/package_service/get_all_packages.py index fdc7590d..6d8b0c25 100755 --- a/examples/ad_manager/v201802/package_service/get_all_packages.py +++ b/examples/ad_manager/v201811/package_service/get_all_packages.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201802') + pkg_service = client.GetService('PackageService', version='v201811') # Create a statement to select packages. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/ad_manager/v201802/package_service/get_in_progress_packages.py b/examples/ad_manager/v201811/package_service/get_in_progress_packages.py similarity index 96% rename from examples/ad_manager/v201802/package_service/get_in_progress_packages.py rename to examples/ad_manager/v201811/package_service/get_in_progress_packages.py index e2dfe4c1..98f737ce 100755 --- a/examples/ad_manager/v201802/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201811/package_service/get_in_progress_packages.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201802') + pkg_service = client.GetService('PackageService', version='v201811') # Create a statement to select packages. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status') .WithBindVariable('status', 'IN_PROGRESS')) diff --git a/examples/ad_manager/v201802/placement_service/create_placements.py b/examples/ad_manager/v201811/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v201802/placement_service/create_placements.py rename to examples/ad_manager/v201811/placement_service/create_placements.py index ffd3e841..682b8d77 100755 --- a/examples/ad_manager/v201802/placement_service/create_placements.py +++ b/examples/ad_manager/v201811/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201802') - inventory_service = client.GetService('InventoryService', version='v201802') + placement_service = client.GetService('PlacementService', version='v201811') + inventory_service = client.GetService('InventoryService', version='v201811') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201802/placement_service/deactivate_placements.py b/examples/ad_manager/v201811/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v201802/placement_service/deactivate_placements.py rename to examples/ad_manager/v201811/placement_service/deactivate_placements.py index 8105c398..37f98910 100755 --- a/examples/ad_manager/v201802/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201811/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201802') + placement_service = client.GetService('PlacementService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :placementId') .WithBindVariable('placementId', long(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/placement_service/get_active_placements.py b/examples/ad_manager/v201811/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v201802/placement_service/get_active_placements.py rename to examples/ad_manager/v201811/placement_service/get_active_placements.py index ecbdef96..0c97afa8 100755 --- a/examples/ad_manager/v201802/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201811/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201802') + placement_service = client.GetService('PlacementService', version='v201811') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201802/placement_service/get_all_placements.py b/examples/ad_manager/v201811/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v201802/placement_service/get_all_placements.py rename to examples/ad_manager/v201811/placement_service/get_all_placements.py index ed176304..7e214177 100755 --- a/examples/ad_manager/v201802/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201811/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201802') + placement_service = client.GetService('PlacementService', version='v201811') # Create a statement to select placements. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201802/placement_service/update_placements.py b/examples/ad_manager/v201811/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v201802/placement_service/update_placements.py rename to examples/ad_manager/v201811/placement_service/update_placements.py index b4c9249e..72b0e564 100755 --- a/examples/ad_manager/v201802/placement_service/update_placements.py +++ b/examples/ad_manager/v201811/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201802') + placement_service = client.GetService('PlacementService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201802/premium_rate_service/__init__.py b/examples/ad_manager/v201811/premium_rate_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/premium_rate_service/__init__.py rename to examples/ad_manager/v201811/premium_rate_service/__init__.py diff --git a/examples/ad_manager/v201802/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/ad_manager/v201802/premium_rate_service/create_premium_rates.py rename to examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py index 0dfc45b5..ef6f0b74 100755 --- a/examples/ad_manager/v201802/premium_rate_service/create_premium_rates.py +++ b/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201802') + version='v201811') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/ad_manager/v201802/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py similarity index 94% rename from examples/ad_manager/v201802/premium_rate_service/get_all_premium_rates.py rename to examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py index fb9ab03a..07dc9f1c 100755 --- a/examples/ad_manager/v201802/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201802') + 'PremiumRateService', version='v201811') # Create a statement to select premium rates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/ad_manager/v201802/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 95% rename from examples/ad_manager/v201802/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py index 30cb3ee4..41ab9292 100755 --- a/examples/ad_manager/v201802/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,9 +25,9 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201802') + 'PremiumRateService', version='v201811') # Create a statement to select premium rates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) diff --git a/examples/ad_manager/v201802/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py similarity index 95% rename from examples/ad_manager/v201802/premium_rate_service/update_premium_rates.py rename to examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py index 50665428..d35c09b6 100755 --- a/examples/ad_manager/v201802/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py @@ -30,10 +30,10 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201802') + version='v201811') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(premium_rate_id)) diff --git a/examples/ad_manager/v201802/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py similarity index 99% rename from examples/ad_manager/v201802/product_package_item_service/create_product_package_item.py rename to examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py index 0264d6d1..315128a8 100755 --- a/examples/ad_manager/v201802/product_package_item_service/create_product_package_item.py +++ b/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py @@ -32,7 +32,7 @@ def main(client): product_package_item_service = client.GetService('ProductPackageItemService', - version='v201802') + version='v201811') product_package_item = { # Set the product from which the product package item is created. diff --git a/examples/ad_manager/v201802/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py similarity index 94% rename from examples/ad_manager/v201802/product_package_item_service/get_all_product_package_items.py rename to examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py index a9c920f3..702454b6 100755 --- a/examples/ad_manager/v201802/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201802') + 'ProductPackageItemService', version='v201811') # Create a statement to select product package items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/ad_manager/v201802/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py similarity index 94% rename from examples/ad_manager/v201802/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py index ceeef069..ebb28eff 100755 --- a/examples/ad_manager/v201802/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,9 +25,9 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201802') + 'ProductPackageItemService', version='v201811') # Create a statement to select product package items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('productPackageId = :productPackageId') .WithBindVariable('productPackageId', product_package_id)) diff --git a/examples/ad_manager/v201802/product_package_service/create_product_packages.py b/examples/ad_manager/v201811/product_package_service/create_product_packages.py similarity index 96% rename from examples/ad_manager/v201802/product_package_service/create_product_packages.py rename to examples/ad_manager/v201811/product_package_service/create_product_packages.py index 7b938368..3937bc7f 100755 --- a/examples/ad_manager/v201802/product_package_service/create_product_packages.py +++ b/examples/ad_manager/v201811/product_package_service/create_product_packages.py @@ -30,7 +30,7 @@ def main(client): product_package_service = client.GetService('ProductPackageService', - version='v201802') + version='v201811') # Create a local product package. product_package = { diff --git a/examples/ad_manager/v201802/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py similarity index 94% rename from examples/ad_manager/v201802/product_package_service/get_active_product_packages.py rename to examples/ad_manager/v201811/product_package_service/get_active_product_packages.py index 0cab6baa..f3309bf7 100755 --- a/examples/ad_manager/v201802/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201802') + 'ProductPackageService', version='v201811') # Create a statement to select product packages. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201802/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201811/product_package_service/get_all_product_packages.py similarity index 94% rename from examples/ad_manager/v201802/product_package_service/get_all_product_packages.py rename to examples/ad_manager/v201811/product_package_service/get_all_product_packages.py index 2d95315a..f899dee0 100755 --- a/examples/ad_manager/v201802/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201811/product_package_service/get_all_product_packages.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201802') + 'ProductPackageService', version='v201811') # Create a statement to select product packages. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/ad_manager/v201802/product_service/__init__.py b/examples/ad_manager/v201811/product_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/product_service/__init__.py rename to examples/ad_manager/v201811/product_service/__init__.py diff --git a/examples/ad_manager/v201802/product_service/get_all_products.py b/examples/ad_manager/v201811/product_service/get_all_products.py similarity index 95% rename from examples/ad_manager/v201802/product_service/get_all_products.py rename to examples/ad_manager/v201811/product_service/get_all_products.py index ae3dd122..3812027f 100755 --- a/examples/ad_manager/v201802/product_service/get_all_products.py +++ b/examples/ad_manager/v201811/product_service/get_all_products.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201802') + product_service = client.GetService('ProductService', version='v201811') # Create a statement to select products. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/ad_manager/v201802/product_service/get_products_for_product_template.py b/examples/ad_manager/v201811/product_service/get_products_for_product_template.py similarity index 96% rename from examples/ad_manager/v201802/product_service/get_products_for_product_template.py rename to examples/ad_manager/v201811/product_service/get_products_for_product_template.py index 51329df4..b4abe0e3 100755 --- a/examples/ad_manager/v201802/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201811/product_service/get_products_for_product_template.py @@ -24,10 +24,10 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201802') + product_service = client.GetService('ProductService', version='v201811') # Create a statement to select products. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('productTemplateId = :productTemplateId') .WithBindVariable('productTemplateId', product_template_id)) diff --git a/examples/ad_manager/v201802/product_service/update_products.py b/examples/ad_manager/v201811/product_service/update_products.py similarity index 96% rename from examples/ad_manager/v201802/product_service/update_products.py rename to examples/ad_manager/v201811/product_service/update_products.py index 8395aa3f..03348c33 100755 --- a/examples/ad_manager/v201802/product_service/update_products.py +++ b/examples/ad_manager/v201811/product_service/update_products.py @@ -29,10 +29,10 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201802') + product_service = client.GetService('ProductService', version='v201811') # Create statement object to select a single product by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', long(product_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/product_template_service/__init__.py b/examples/ad_manager/v201811/product_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/product_template_service/__init__.py rename to examples/ad_manager/v201811/product_template_service/__init__.py diff --git a/examples/ad_manager/v201802/product_template_service/activate_product_templates.py b/examples/ad_manager/v201811/product_template_service/activate_product_templates.py similarity index 95% rename from examples/ad_manager/v201802/product_template_service/activate_product_templates.py rename to examples/ad_manager/v201811/product_template_service/activate_product_templates.py index eee57805..3487dd9e 100755 --- a/examples/ad_manager/v201802/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/activate_product_templates.py @@ -31,10 +31,10 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201802') + 'ProductTemplateService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', long(product_template_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/product_template_service/create_product_templates.py b/examples/ad_manager/v201811/product_template_service/create_product_templates.py similarity index 97% rename from examples/ad_manager/v201802/product_template_service/create_product_templates.py rename to examples/ad_manager/v201811/product_template_service/create_product_templates.py index 40e77754..82c742bb 100755 --- a/examples/ad_manager/v201802/product_template_service/create_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201802') + 'ProductTemplateService', version='v201811') network_service = client.GetService( - 'NetworkService', version='v201802') + 'NetworkService', version='v201811') # Create a product template. product_template = { diff --git a/examples/ad_manager/v201802/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py similarity index 96% rename from examples/ad_manager/v201802/product_template_service/create_programmatic_product_templates.py rename to examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py index 350bf69c..85b16406 100755 --- a/examples/ad_manager/v201802/product_template_service/create_programmatic_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201802') + 'ProductTemplateService', version='v201811') network_service = client.GetService( - 'NetworkService', version='v201802') + 'NetworkService', version='v201811') product_template = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201802/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201811/product_template_service/get_all_product_templates.py similarity index 94% rename from examples/ad_manager/v201802/product_template_service/get_all_product_templates.py rename to examples/ad_manager/v201811/product_template_service/get_all_product_templates.py index 875e7f53..9193f01b 100755 --- a/examples/ad_manager/v201802/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/get_all_product_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201802') + 'ProductTemplateService', version='v201811') # Create a statement to select product templates. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/ad_manager/v201802/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py similarity index 94% rename from examples/ad_manager/v201802/product_template_service/get_sponsorship_product_templates.py rename to examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py index beb74e34..1ee08d56 100755 --- a/examples/ad_manager/v201802/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201802') + 'ProductTemplateService', version='v201811') # Create a statement to select product templates. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('lineItemType = :lineItemType') .WithBindVariable('lineItemType', 'SPONSORSHIP')) diff --git a/examples/ad_manager/v201802/product_template_service/update_product_templates.py b/examples/ad_manager/v201811/product_template_service/update_product_templates.py similarity index 96% rename from examples/ad_manager/v201802/product_template_service/update_product_templates.py rename to examples/ad_manager/v201811/product_template_service/update_product_templates.py index fee07193..ad342535 100755 --- a/examples/ad_manager/v201802/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/update_product_templates.py @@ -30,10 +30,10 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201802') + 'ProductTemplateService', version='v201811') # Create a statement to select a single product template by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(product_template_id)) diff --git a/examples/ad_manager/v201802/proposal_line_item_service/__init__.py b/examples/ad_manager/v201811/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/proposal_line_item_service/__init__.py rename to examples/ad_manager/v201811/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v201802/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201802/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py index 30e4dc0b..c9ad1de1 100755 --- a/examples/ad_manager/v201802/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201802') + 'ProposalLineItemService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py index d6d7bb10..e9746071 100755 --- a/examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -40,8 +40,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201802') - network_service = client.GetService('NetworkService', version='v201802') + 'ProposalLineItemService', version='v201811') + network_service = client.GetService('NetworkService', version='v201811') # Get the root ad unit to target. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 88% rename from examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index ebb54cf0..db94be97 100755 --- a/examples/ad_manager/v201802/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -34,8 +34,8 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201802') - network_service = client.GetService('NetworkService', version='v201802') + 'ProposalLineItemService', version='v201811') + network_service = client.GetService('NetworkService', version='v201811') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) @@ -60,6 +60,13 @@ def main(client, proposal_id, product_id): 'targetedAdUnits': { 'adUnitId': root_ad_unit_id } + }, + # Target Display environment by excluding Mobile Apps. + # DeviceCapabilities can be obtained though the Device_Capability PQL + # table: + # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService + 'technologyTargeting': { + 'deviceCapabilityTargeting': [{'id': 5005}] } }, 'startDateTime': start_datetime, @@ -79,10 +86,6 @@ def main(client, proposal_id, product_id): 'units': '1000', 'unitType': 'IMPRESSIONS', }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, 'netRate': { 'currencyCode': 'USD', 'microAmount': '2000000' diff --git a/examples/ad_manager/v201802/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v201802/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py index 1abb2506..58fd44ba 100755 --- a/examples/ad_manager/v201802/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py @@ -42,8 +42,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201802') - network_service = client.GetService('NetworkService', version='v201802') + 'ProposalLineItemService', version='v201811') + network_service = client.GetService('NetworkService', version='v201811') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201802/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v201802/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py index a0223ab0..523cc7ac 100755 --- a/examples/ad_manager/v201802/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201802') + 'ProposalLineItemService', version='v201811') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 1a1874d8..97d5c2f4 100755 --- a/examples/ad_manager/v201802/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201802') + 'ProposalLineItemService', version='v201811') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201802/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201802/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py index 333c63c5..90be64cd 100755 --- a/examples/ad_manager/v201802/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201802') + 'ProposalLineItemService', version='v201811') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/proposal_service/__init__.py b/examples/ad_manager/v201811/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/proposal_service/__init__.py rename to examples/ad_manager/v201811/proposal_service/__init__.py diff --git a/examples/ad_manager/v201802/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals.py similarity index 99% rename from examples/ad_manager/v201802/proposal_service/create_programmatic_proposals.py rename to examples/ad_manager/v201811/proposal_service/create_programmatic_proposals.py index 0ecef57a..dc41ac6b 100755 --- a/examples/ad_manager/v201802/proposal_service/create_programmatic_proposals.py +++ b/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201802') - network_service = client.GetService('NetworkService', version='v201802') + proposal_service = client.GetService('ProposalService', version='v201811') + network_service = client.GetService('NetworkService', version='v201811') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 99% rename from examples/ad_manager/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/ad_manager/v201811/proposal_service/create_programmatic_proposals_for_non_sales_management.py index dcfeae12..05e1a521 100755 --- a/examples/ad_manager/v201802/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -29,7 +29,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201802') + proposal_service = client.GetService('ProposalService', version='v201811') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201802/proposal_service/create_proposals.py b/examples/ad_manager/v201811/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v201802/proposal_service/create_proposals.py rename to examples/ad_manager/v201811/proposal_service/create_proposals.py index 89f03352..af63f22a 100755 --- a/examples/ad_manager/v201802/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201811/proposal_service/create_proposals.py @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201802') - network_service = client.GetService('NetworkService', version='v201802') + proposal_service = client.GetService('ProposalService', version='v201811') + network_service = client.GetService('NetworkService', version='v201811') # Create proposal objects. proposal = { diff --git a/examples/ad_manager/v201802/proposal_service/get_all_proposals.py b/examples/ad_manager/v201811/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v201802/proposal_service/get_all_proposals.py rename to examples/ad_manager/v201811/proposal_service/get_all_proposals.py index ae5d62f8..a899376a 100755 --- a/examples/ad_manager/v201802/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201811/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201802') + proposal_service = client.GetService('ProposalService', version='v201811') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201802/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v201802/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py index 84699e76..c5bf17ba 100755 --- a/examples/ad_manager/v201802/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201802') + 'ProposalService', version='v201811') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v201802/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py similarity index 96% rename from examples/ad_manager/v201802/proposal_service/get_proposals_pending_approval.py rename to examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py index 6cca9940..9ac8741c 100755 --- a/examples/ad_manager/v201802/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201802') + proposal_service = client.GetService('ProposalService', version='v201811') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status') .WithBindVariable('status', 'PENDING_APPROVAL')) diff --git a/examples/ad_manager/v201802/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v201802/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py index 3a823d5a..f315a70f 100755 --- a/examples/ad_manager/v201802/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201802') + proposal_service = client.GetService('ProposalService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201802/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py similarity index 96% rename from examples/ad_manager/v201802/proposal_service/submit_proposals_for_approval.py rename to examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py index 76ff57ed..3bcdc28d 100755 --- a/examples/ad_manager/v201802/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py @@ -28,10 +28,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201802') + proposal_service = client.GetService('ProposalService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 diff --git a/examples/ad_manager/v201802/proposal_service/update_proposals.py b/examples/ad_manager/v201811/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v201802/proposal_service/update_proposals.py rename to examples/ad_manager/v201811/proposal_service/update_proposals.py index fff7a52c..e1495fb5 100755 --- a/examples/ad_manager/v201802/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201811/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201802') + proposal_service = client.GetService('ProposalService', version='v201811') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :proposalId') .WithBindVariable('proposalId', long(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/publisher_query_language_service/__init__.py b/examples/ad_manager/v201811/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/publisher_query_language_service/__init__.py rename to examples/ad_manager/v201811/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v201802/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v201802/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py index 561db2db..8fc54914 100755 --- a/examples/ad_manager/v201802/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201802/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v201802/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py index bde91923..5a0c7edd 100755 --- a/examples/ad_manager/v201802/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v201802/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v201802/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py index 68a344bb..c5e82130 100755 --- a/examples/ad_manager/v201802/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201802') + data_downloader = client.GetDataDownloader(version='v201811') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201802/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py similarity index 94% rename from examples/ad_manager/v201802/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py index efb91f9a..79cd8688 100755 --- a/examples/ad_manager/v201802/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py @@ -28,14 +28,14 @@ def main(client, geo_target_type): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') with tempfile.NamedTemporaryFile( prefix='geo_data_', suffix='.csv', mode='w', delete=False) as geo_data_file: geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' - 'CountryCode ' + 'CountryCode, Type ' 'FROM Geo_Target ' 'WHERE Type = :type AND Targetable = true ' 'ORDER BY CountryCode ASC, Name ASC') diff --git a/examples/ad_manager/v201802/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v201802/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py index f726ace4..8dc51f66 100755 --- a/examples/ad_manager/v201802/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v201802/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py similarity index 97% rename from examples/ad_manager/v201802/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py index 926f3b20..5f13eb9d 100755 --- a/examples/ad_manager/v201802/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201802') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201811') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') @@ -142,7 +142,7 @@ def ConvertDateTimeToOffset(date_time_value): int(date_time_value['minute']), int(date_time_value['second'])) date_time_str = pytz.timezone( - date_time_value['timeZoneID']).localize(date_time_obj).isoformat() + date_time_value['timeZoneId']).localize(date_time_obj).isoformat() if date_time_str[-5:] == '00:00': return date_time_str[:-6] + 'Z' diff --git a/examples/ad_manager/v201802/rate_card_service/__init__.py b/examples/ad_manager/v201811/rate_card_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/rate_card_service/__init__.py rename to examples/ad_manager/v201811/rate_card_service/__init__.py diff --git a/examples/ad_manager/v201802/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py similarity index 99% rename from examples/ad_manager/v201802/rate_card_service/create_rate_cards.py rename to examples/ad_manager/v201811/rate_card_service/create_rate_cards.py index 20e4d06f..2f40323f 100755 --- a/examples/ad_manager/v201802/rate_card_service/create_rate_cards.py +++ b/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201802') + rate_card_service = client.GetService('RateCardService', version='v201811') # Create a rate card. rate_card = { diff --git a/examples/ad_manager/v201802/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py similarity index 95% rename from examples/ad_manager/v201802/rate_card_service/get_all_rate_cards.py rename to examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py index 1a71ec6e..5d528b2a 100755 --- a/examples/ad_manager/v201802/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201802') + rate_card_service = client.GetService('RateCardService', version='v201811') # Create a statement to select rate cards. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/ad_manager/v201802/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py similarity index 96% rename from examples/ad_manager/v201802/rate_card_service/get_marketplace_rate_cards.py rename to examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py index a77f669a..53727cad 100755 --- a/examples/ad_manager/v201802/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201802') + rate_card_service = client.GetService('RateCardService', version='v201811') # Create a statement to select rate cards. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('forMarketplace = :forMarketplace') .WithBindVariable('forMarketplace', True)) diff --git a/examples/ad_manager/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 95% rename from examples/ad_manager/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index e8d0db92..02d8f420 100755 --- a/examples/ad_manager/v201802/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201802')) + 'ReconciliationLineItemReportService', version='v201811')) # Create a statement to select reconciliation line item reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('reconciliationReportId = :reconciliationReportId AND ' 'lineItemId != :lineItemId')) .OrderBy('lineItemId', ascending=True) diff --git a/examples/ad_manager/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 95% rename from examples/ad_manager/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 3f839882..9669f8ac 100755 --- a/examples/ad_manager/v201802/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201802')) + 'ReconciliationLineItemReportService', version='v201811')) # Create a statement to select a reconciliation line item report. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :lineItemReportId') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 94% rename from examples/ad_manager/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 10da1047..d8794192 100755 --- a/examples/ad_manager/v201802/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,9 +25,9 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201802') + 'ReconciliationOrderReportService', version='v201811') # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('reconciliationReportId = :reconciliationReportId') .WithBindVariable('reconciliationReportId', reconciliation_report_id)) diff --git a/examples/ad_manager/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 95% rename from examples/ad_manager/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 60272108..fcd69a5e 100755 --- a/examples/ad_manager/v201802/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201802')) + 'ReconciliationOrderReportService', version='v201811')) # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 95% rename from examples/ad_manager/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 408c82fd..29359781 100755 --- a/examples/ad_manager/v201802/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -27,10 +27,10 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201802') + 'ReconciliationReportRowService', version='v201811') # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) diff --git a/examples/ad_manager/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 95% rename from examples/ad_manager/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py index b4c6e083..a4963d7f 100755 --- a/examples/ad_manager/v201802/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -33,10 +33,10 @@ def main(client): # Initialize appropriate service. reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201802')) + 'ReconciliationReportRowService', version='v201811')) # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('id = :reconciliationReportRowId AND ' 'reconciliationReportId = :reconciliationReportId')) .OrderBy('id', ascending=True) diff --git a/examples/ad_manager/v201802/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 94% rename from examples/ad_manager/v201802/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py index d4073a99..522ad220 100755 --- a/examples/ad_manager/v201802/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201802') + 'ReconciliationReportService', version='v201811') # Create a statement to select reconciliation reports. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. diff --git a/examples/ad_manager/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 94% rename from examples/ad_manager/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 57f0f2d0..bf450695 100755 --- a/examples/ad_manager/v201802/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201802') + 'ReconciliationReportService', version='v201811') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) # Create a statement to select reconciliation reports. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('startDate = :startDate') .WithBindVariable('startDate', last_month)) diff --git a/examples/ad_manager/v201802/report_service/__init__.py b/examples/ad_manager/v201811/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/report_service/__init__.py rename to examples/ad_manager/v201811/report_service/__init__.py diff --git a/examples/ad_manager/v201802/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201811/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v201802/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v201811/report_service/run_ad_exchange_report.py index 2d1c1d22..fa543dab 100755 --- a/examples/ad_manager/v201802/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201811/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') # Create report job. report_job = { diff --git a/examples/ad_manager/v201802/report_service/run_delivery_report.py b/examples/ad_manager/v201811/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v201802/report_service/run_delivery_report.py rename to examples/ad_manager/v201811/report_service/run_delivery_report.py index a6c6b21b..d19e34df 100755 --- a/examples/ad_manager/v201802/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201811/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('ORDER_ID = :id') .WithBindVariable('id', long(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201802/report_service/run_inventory_report.py b/examples/ad_manager/v201811/report_service/run_inventory_report.py similarity index 95% rename from examples/ad_manager/v201802/report_service/run_inventory_report.py rename to examples/ad_manager/v201811/report_service/run_inventory_report.py index 0d7af87f..d4a8bebc 100755 --- a/examples/ad_manager/v201802/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201811/report_service/run_inventory_report.py @@ -25,16 +25,16 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201802') + network_service = client.GetService('NetworkService', version='v201811') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) .Limit(None) # No limit or offset for reports diff --git a/examples/ad_manager/v201802/report_service/run_reach_report.py b/examples/ad_manager/v201811/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v201802/report_service/run_reach_report.py rename to examples/ad_manager/v201811/report_service/run_reach_report.py index 7682e63d..fa7e834d 100755 --- a/examples/ad_manager/v201802/report_service/run_reach_report.py +++ b/examples/ad_manager/v201811/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') # Create report job. report_job = { diff --git a/examples/ad_manager/v201802/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v201802/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py index 36eecb4b..e5370573 100755 --- a/examples/ad_manager/v201802/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201802/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py similarity index 95% rename from examples/ad_manager/v201802/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py index cbfb971b..d5bfb86d 100755 --- a/examples/ad_manager/v201802/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py @@ -28,12 +28,12 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201802') + line_item_service = client.GetService('LineItemService', version='v201811') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('orderId = :orderId') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201802/report_service/run_sales_report.py b/examples/ad_manager/v201811/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v201802/report_service/run_sales_report.py rename to examples/ad_manager/v201811/report_service/run_sales_report.py index 78706ae1..47feee9b 100755 --- a/examples/ad_manager/v201802/report_service/run_sales_report.py +++ b/examples/ad_manager/v201811/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') # Create report job. report_job = { diff --git a/examples/ad_manager/v201802/report_service/run_saved_query.py b/examples/ad_manager/v201811/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v201802/report_service/run_saved_query.py rename to examples/ad_manager/v201811/report_service/run_saved_query.py index ac188a02..3a7f6f00 100755 --- a/examples/ad_manager/v201802/report_service/run_saved_query.py +++ b/examples/ad_manager/v201811/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201802') + report_service = client.GetService('ReportService', version='v201811') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201802') + report_downloader = client.GetDataDownloader(version='v201811') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .WithBindVariable('id', long(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v201802/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201811/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v201811/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py index f7b41d3a..2da09a35 100755 --- a/examples/ad_manager/v201802/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201802') + 'SuggestedAdUnitService', version='v201811') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py index 66c59755..b2bb3b38 100755 --- a/examples/ad_manager/v201802/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201802') + 'SuggestedAdUnitService', version='v201811') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 31defa2d..ef252c65 100755 --- a/examples/ad_manager/v201802/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201802') + 'SuggestedAdUnitService', version='v201811') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', long(num_requests))) diff --git a/examples/ad_manager/v201802/team_service/__init__.py b/examples/ad_manager/v201811/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/team_service/__init__.py rename to examples/ad_manager/v201811/team_service/__init__.py diff --git a/examples/ad_manager/v201802/team_service/create_teams.py b/examples/ad_manager/v201811/team_service/create_teams.py similarity index 99% rename from examples/ad_manager/v201802/team_service/create_teams.py rename to examples/ad_manager/v201811/team_service/create_teams.py index 073abd55..7c6d7740 100755 --- a/examples/ad_manager/v201802/team_service/create_teams.py +++ b/examples/ad_manager/v201811/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201802') + team_service = client.GetService('TeamService', version='v201811') # Create team objects. teams = [] diff --git a/examples/ad_manager/v201802/team_service/get_all_teams.py b/examples/ad_manager/v201811/team_service/get_all_teams.py similarity index 96% rename from examples/ad_manager/v201802/team_service/get_all_teams.py rename to examples/ad_manager/v201811/team_service/get_all_teams.py index 1355d0d7..dc19a046 100755 --- a/examples/ad_manager/v201802/team_service/get_all_teams.py +++ b/examples/ad_manager/v201811/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201802') + team_service = client.GetService('TeamService', version='v201811') # Create a statement to select teams. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201802/team_service/update_teams.py b/examples/ad_manager/v201811/team_service/update_teams.py similarity index 97% rename from examples/ad_manager/v201802/team_service/update_teams.py rename to examples/ad_manager/v201811/team_service/update_teams.py index 3390ef28..dbd6260c 100755 --- a/examples/ad_manager/v201802/team_service/update_teams.py +++ b/examples/ad_manager/v201811/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201802') + team_service = client.GetService('TeamService', version='v201811') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :teamId') .WithBindVariable('teamId', long(team_id))) diff --git a/examples/ad_manager/v201802/user_service/__init__.py b/examples/ad_manager/v201811/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/user_service/__init__.py rename to examples/ad_manager/v201811/user_service/__init__.py diff --git a/examples/ad_manager/v201802/user_service/create_users.py b/examples/ad_manager/v201811/user_service/create_users.py similarity index 99% rename from examples/ad_manager/v201802/user_service/create_users.py rename to examples/ad_manager/v201811/user_service/create_users.py index 2d44649d..0734e568 100755 --- a/examples/ad_manager/v201802/user_service/create_users.py +++ b/examples/ad_manager/v201811/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201802') + user_service = client.GetService('UserService', version='v201811') # Create user objects. users = [ diff --git a/examples/ad_manager/v201802/user_service/deactivate_users.py b/examples/ad_manager/v201811/user_service/deactivate_users.py similarity index 97% rename from examples/ad_manager/v201802/user_service/deactivate_users.py rename to examples/ad_manager/v201811/user_service/deactivate_users.py index 38c0eef9..4fa1926a 100755 --- a/examples/ad_manager/v201802/user_service/deactivate_users.py +++ b/examples/ad_manager/v201811/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201802') + user_service = client.GetService('UserService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201802/user_service/get_all_roles.py b/examples/ad_manager/v201811/user_service/get_all_roles.py similarity index 100% rename from examples/ad_manager/v201802/user_service/get_all_roles.py rename to examples/ad_manager/v201811/user_service/get_all_roles.py diff --git a/examples/ad_manager/v201802/user_service/get_all_users.py b/examples/ad_manager/v201811/user_service/get_all_users.py similarity index 96% rename from examples/ad_manager/v201802/user_service/get_all_users.py rename to examples/ad_manager/v201811/user_service/get_all_users.py index e319ae54..620e4e8e 100755 --- a/examples/ad_manager/v201802/user_service/get_all_users.py +++ b/examples/ad_manager/v201811/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201802') + user_service = client.GetService('UserService', version='v201811') # Create a statement to select users. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201802/user_service/get_current_user.py b/examples/ad_manager/v201811/user_service/get_current_user.py similarity index 99% rename from examples/ad_manager/v201802/user_service/get_current_user.py rename to examples/ad_manager/v201811/user_service/get_current_user.py index 534ccc07..78e227ab 100755 --- a/examples/ad_manager/v201802/user_service/get_current_user.py +++ b/examples/ad_manager/v201811/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201802') + user_service = client.GetService('UserService', version='v201811') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v201802/user_service/get_user_by_email_address.py b/examples/ad_manager/v201811/user_service/get_user_by_email_address.py similarity index 96% rename from examples/ad_manager/v201802/user_service/get_user_by_email_address.py rename to examples/ad_manager/v201811/user_service/get_user_by_email_address.py index 9bce82d0..0017162b 100755 --- a/examples/ad_manager/v201802/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201811/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201802') + user_service = client.GetService('UserService', version='v201811') # Create a statement to select users. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201802/user_service/update_users.py b/examples/ad_manager/v201811/user_service/update_users.py similarity index 96% rename from examples/ad_manager/v201802/user_service/update_users.py rename to examples/ad_manager/v201811/user_service/update_users.py index 807b6fbe..04c8d979 100755 --- a/examples/ad_manager/v201802/user_service/update_users.py +++ b/examples/ad_manager/v201811/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201802') + user_service = client.GetService('UserService', version='v201811') # Create query. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201802/user_team_association_service/__init__.py b/examples/ad_manager/v201811/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/user_team_association_service/__init__.py rename to examples/ad_manager/v201811/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v201802/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v201802/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py index 576dddad..f9bfab18 100755 --- a/examples/ad_manager/v201802/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201802') + 'UserTeamAssociationService', version='v201811') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v201802/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v201802/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py index 0e497cce..c9fcb114 100755 --- a/examples/ad_manager/v201802/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201802') + 'UserTeamAssociationService', version='v201811') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201802/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v201802/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py index 07e8c76e..d20bf893 100755 --- a/examples/ad_manager/v201802/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201802') + 'UserTeamAssociationService', version='v201811') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder() + statement = ad_manager.StatementBuilder(version='v201811') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201802/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v201802/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py index 79809281..15596c51 100755 --- a/examples/ad_manager/v201802/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201802') + 'UserTeamAssociationService', version='v201811') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201802/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v201802/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py index aa212b21..c8b53d70 100755 --- a/examples/ad_manager/v201802/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201802') + 'UserTeamAssociationService', version='v201811') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201802/workflow_request_service/__init__.py b/examples/ad_manager/v201811/workflow_request_service/__init__.py similarity index 100% rename from examples/ad_manager/v201802/workflow_request_service/__init__.py rename to examples/ad_manager/v201811/workflow_request_service/__init__.py diff --git a/examples/ad_manager/v201802/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py similarity index 95% rename from examples/ad_manager/v201802/workflow_request_service/approve_workflow_approval_requests.py rename to examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py index 2253dd99..ac2673b8 100755 --- a/examples/ad_manager/v201802/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py @@ -31,10 +31,10 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201802') + version='v201811') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) diff --git a/examples/ad_manager/v201802/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py similarity index 94% rename from examples/ad_manager/v201802/workflow_request_service/get_workflow_approval_requests.py rename to examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py index 38dd03a9..cd77e7fb 100755 --- a/examples/ad_manager/v201802/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py @@ -26,9 +26,9 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201802') + 'WorkflowRequestService', version='v201811') # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) diff --git a/examples/ad_manager/v201802/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py similarity index 94% rename from examples/ad_manager/v201802/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py index 645d7efb..e01dba41 100755 --- a/examples/ad_manager/v201802/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,9 +26,9 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201802') + 'WorkflowRequestService', version='v201811') # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) diff --git a/examples/ad_manager/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 95% rename from examples/ad_manager/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py index 14deca1d..cc6803a8 100755 --- a/examples/ad_manager/v201802/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,10 +31,10 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201802') + version='v201811') # Create a filter statement. - statement = (ad_manager.StatementBuilder() + statement = (ad_manager.StatementBuilder(version='v201811') .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) diff --git a/examples/adwords/v201802/targeting/lookup_location.py b/examples/adwords/v201802/targeting/lookup_location.py index ad885dd4..b6062267 100755 --- a/examples/adwords/v201802/targeting/lookup_location.py +++ b/examples/adwords/v201802/targeting/lookup_location.py @@ -36,7 +36,7 @@ def main(client): location_criterion_service = client.GetService( 'LocationCriterionService', version='v201802') - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + location_names = ['Paris', 'Quebec', 'Spain', 'Deutschland'] # Create the selector. selector = { diff --git a/examples/adwords/v201806/targeting/lookup_location.py b/examples/adwords/v201806/targeting/lookup_location.py index decb4f35..38a1fa31 100755 --- a/examples/adwords/v201806/targeting/lookup_location.py +++ b/examples/adwords/v201806/targeting/lookup_location.py @@ -36,7 +36,7 @@ def main(client): location_criterion_service = client.GetService( 'LocationCriterionService', version='v201806') - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + location_names = ['Paris', 'Quebec', 'Spain', 'Deutschland'] # Create the selector. selector = { diff --git a/examples/adwords/v201809/targeting/lookup_location.py b/examples/adwords/v201809/targeting/lookup_location.py index 10ba7211..046c1612 100755 --- a/examples/adwords/v201809/targeting/lookup_location.py +++ b/examples/adwords/v201809/targeting/lookup_location.py @@ -36,7 +36,7 @@ def main(client): location_criterion_service = client.GetService( 'LocationCriterionService', version='v201809') - location_names = ['Paris', 'Quebec', 'Spain', 'Deutchland'] + location_names = ['Paris', 'Quebec', 'Spain', 'Deutschland'] # Create the selector. selector = { diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 4b70cda2..8b629fec 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,7 +44,7 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201711': + 'v201802': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', @@ -66,14 +66,15 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201802': + 'v201805': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', 'ContentBundleService', 'ContentMetadataKeyHierarchyService', 'ContentService', 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'ExchangeRateService', 'ForecastService', 'InventoryService', 'LabelService', 'LineItemCreativeAssociationService', 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', @@ -88,7 +89,7 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201805': + 'v201808': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', @@ -111,18 +112,17 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), - 'v201808': + 'v201811': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', 'CdnConfigurationService', 'CompanyService', 'ContactService', - 'ContentBundleService', 'ContentMetadataKeyHierarchyService', - 'ContentService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'ExchangeRateService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', + 'ContentBundleService', 'ContentService', 'CreativeService', + 'CreativeSetService', 'CreativeTemplateService', + 'CreativeWrapperService', 'CustomFieldService', + 'CustomTargetingService', 'DaiAuthenticationKeyService', + 'ExchangeRateService', 'ForecastService', 'InventoryService', + 'LabelService', 'LineItemCreativeAssociationService', + 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', 'OrderService', 'PackageService', 'PlacementService', 'PremiumRateService', 'ProductService', 'ProductPackageService', @@ -292,6 +292,7 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], _AdManagerPacker, self.proxy_config, self.timeout, + version, cache=self.cache) return service @@ -396,27 +397,29 @@ class _AdManagerPacker(googleads.common.SoapPacker): """A utility applying customized packing logic for Ad Manager.""" @classmethod - def Pack(cls, obj): + def Pack(cls, obj, version): """Pack the given object using Ad Manager-specific logic. Args: obj: an object to be packed for SOAP using Ad Manager-specific logic, if applicable. + version: the version of the current API, e.g. 'v201811' Returns: The given object packed with Ad Manager-specific logic for SOAP, if applicable. Otherwise, returns the given object unmodified. """ if isinstance(obj, (datetime.datetime, datetime.date)): - return cls.AdManagerDateTimePacker(obj) + return cls.AdManagerDateTimePacker(obj, version) return obj @classmethod - def AdManagerDateTimePacker(cls, value): + def AdManagerDateTimePacker(cls, value, version): """Returns dicts formatted for Ad Manager SOAP based on date/datetime. Args: value: A date or datetime object to be converted. + version: the version of the current API, e.g. 'v201811' Returns: The value object correctly represented for Ad Manager SOAP. @@ -427,13 +430,14 @@ def AdManagerDateTimePacker(cls, value): raise googleads.errors.GoogleAdsValueError( 'Datetime %s is not timezone aware.' % value ) - return { - 'date': cls.AdManagerDateTimePacker(value.date()), + 'date': cls.AdManagerDateTimePacker(value.date(), version), 'hour': value.hour, 'minute': value.minute, 'second': value.second, - 'timeZoneID': value.tzinfo.zone, + # As of V201811, timeZoneID was renamed timeZoneId + 'timeZoneId' if version >= 'v201811' else 'timeZoneID': + value.tzinfo.zone, } elif isinstance(value, datetime.date): return {'year': value.year, 'month': value.month, 'day': value.day} @@ -468,7 +472,8 @@ def __repr__(self): def __init__(self, select_columns=None, from_table=None, where=None, order_by=None, order_ascending=True, - limit=SUGGESTED_PAGE_LIMIT, offset=0): + limit=SUGGESTED_PAGE_LIMIT, offset=0, + version=sorted(_SERVICE_MAP.keys())[-1]): """Initializes StatementBuilder. Args: @@ -479,12 +484,17 @@ def __init__(self, select_columns=None, from_table=None, where=None, order_ascending: a boolean specifying sort order ascending or descending. limit: an integer with the limit clause. offset: an integer with the offset clause. + version: A string identifying the Ad Manager version this statement is + compatible with. This defaults to what is currently the latest + version. This will be updated in future releases to point to what is + then the latest version. """ self._select = select_columns self._from_ = from_table self._where = where self.limit = limit self.offset = offset + self._version = version if order_by: self._order_by = self._OrderByPair(column=order_by, ascending=order_ascending) @@ -523,8 +533,8 @@ def ToStatement(self): query.append(self._OFFSET_PART % self.offset) return {'query': ' '.join(query), - 'values': (PQLHelper.GetQueryValuesFromDict(self._values) - if self._values else None)} + 'values': (PQLHelper.GetQueryValuesFromDict( + self._values, self._version) if self._values else None)} def Select(self, columns): """Adds a SELECT clause. @@ -612,7 +622,7 @@ def WithBindVariable(self, key, value): """ # Make this call to throw the exception here if there is a problem - PQLHelper.GetValueRepresentation(value) + PQLHelper.GetValueRepresentation(value, self._version) self._values[key] = value return self @@ -622,29 +632,40 @@ class PQLHelper(object): """Utility class for PQL.""" @classmethod - def GetQueryValuesFromDict(cls, d): + def GetQueryValuesFromDict(cls, d, version=sorted(_SERVICE_MAP.keys())[-1]): """Converts a dict of python types into a list of PQL types. Args: d: A dictionary of variable names to python types. + version: A string identifying the Ad Manager version the values object + is compatible with. This defaults to what is currently the latest + version. This will be updated in future releases to point to what is + then the latest version. Returns: - A list of variables formatted for PQL statements. + A list of variables formatted for PQL statements which are compatible with + a particular API version. """ return [{ 'key': key, - 'value': cls.GetValueRepresentation(value) + 'value': cls.GetValueRepresentation(value, version) } for key, value in d.iteritems()] @classmethod - def GetValueRepresentation(cls, value): + def GetValueRepresentation(cls, value, + version=sorted(_SERVICE_MAP.keys())[-1]): """Converts a single python value to its PQL representation. Args: value: A python value. + version: A string identifying the Ad Manager version the value object + is compatible with. This defaults to what is currently the latest + version. This will be updated in future releases to point to what is + then the latest version. Returns: - The value formatted for PQL statements. + The value formatted for PQL statements which are compatible with a + particular API version. """ if isinstance(value, str) or isinstance(value, unicode): return {'value': value, 'xsi_type': 'TextValue'} @@ -671,7 +692,8 @@ def GetValueRepresentation(cls, value): 'hour': value.hour, 'minute': value.minute, 'second': value.second, - 'timeZoneID': value.tzinfo.zone, + 'timeZoneId' if version >= 'v201811' else 'timeZoneID': + value.tzinfo.zone, } } elif isinstance(value, datetime.date): @@ -690,7 +712,7 @@ def GetValueRepresentation(cls, value): return { 'xsi_type': 'SetValue', - 'values': [cls.GetValueRepresentation(v) for v in value] + 'values': [cls.GetValueRepresentation(v, version) for v in value] } else: raise googleads.errors.GoogleAdsValueError( @@ -939,7 +961,7 @@ def _PageThroughPqlSet(self, pql_query, output_function, values): to the pql_query. """ if isinstance(values, dict): - values = PQLHelper.GetQueryValuesFromDict(values) + values = PQLHelper.GetQueryValuesFromDict(values, self._version) pql_service = self._GetPqlService() current_offset = 0 @@ -988,8 +1010,13 @@ def _ConvertDateTimeToOffset(self, date_time_value): int(date_time_value['hour']), int(date_time_value['minute']), int(date_time_value['second'])) + # v201808 is the last Ad Manager version to use timeZoneID. + if self._version > 'v201808': + time_zone_str = 'timeZoneId' + else: + time_zone_str = 'timeZoneID' date_time_str = pytz.timezone( - date_time_value['timeZoneID']).localize(date_time_obj).isoformat() + date_time_value[time_zone_str]).localize(date_time_obj).isoformat() if date_time_str[-5:] == '00:00': return date_time_str[:-6] + 'Z' diff --git a/googleads/adwords.py b/googleads/adwords.py index f04f0350..1ae05fe0 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -424,6 +424,7 @@ def GetService(self, service_name, version=None, server=None): _AdWordsPacker, self.proxy_config, self.timeout, + version, cache=self.cache) return service @@ -616,12 +617,13 @@ class _AdWordsPacker(googleads.common.SoapPacker): """A utility applying customized packing logic for AdWords.""" @classmethod - def Pack(cls, obj): + def Pack(cls, obj, version): """Pack the given object using AdWords-specific logic. Args: obj: an object to be packed for SOAP using AdWords-specific logic, if applicable. + version: the version of the current API, e.g. 'v201809' Returns: The given object packed with AdWords-specific logic for SOAP, if diff --git a/googleads/common.py b/googleads/common.py index e5cda946..64419dbc 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '14.1.0' +VERSION = '15.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' @@ -376,7 +376,7 @@ def _ExtractProxyConfig(product_yaml_key, proxy_config_data): return proxy_config -def _PackForSuds(obj, factory, packer=None): +def _PackForSuds(obj, factory, packer=None, version=None): """Packs SOAP input into the format we want for suds. The main goal here is to pack dictionaries with an 'xsi_type' key into @@ -393,6 +393,7 @@ def _PackForSuds(obj, factory, packer=None): classes generated from the WSDL. packer: An optional subclass of googleads.common.SoapPacker that provides customized packing logic. + version: the version of the current API, e.g. 'v201811' Returns: If the given obj was a dictionary that contained the 'xsi_type' key, this @@ -400,7 +401,7 @@ def _PackForSuds(obj, factory, packer=None): be the same data type as the input obj was. """ if packer: - obj = packer.Pack(obj) + obj = packer.Pack(obj, version) if obj in ({}, None): # Force suds to serialize empty objects. There are legitimate use cases for @@ -859,7 +860,7 @@ class GoogleSoapService(object): """ __metaclass__ = abc.ABCMeta - def __init__(self, header_handler, packer): + def __init__(self, header_handler, packer, version): """Initializes a SOAP service. Args: @@ -867,9 +868,11 @@ def __init__(self, header_handler, packer): SOAP and HTTP headers. packer: A googleads.common.SoapPacker instance used to transform entities. + version: the version of the current API, e.g. 'v201811' """ self._header_handler = header_handler self._packer = packer + self._version = version self._method_proxies = {} @@ -943,7 +946,7 @@ class SudsServiceProxy(GoogleSoapService): """ def __init__(self, endpoint, header_handler, packer, proxy_config, - timeout, cache=None): + timeout, version, cache=None): """Initializes a suds service proxy. Args: @@ -954,13 +957,14 @@ def __init__(self, endpoint, header_handler, packer, proxy_config, customized packing logic. proxy_config: A ProxyConfig that represents proxy settings. timeout: An integer to set the connection timeout. + version: the current version of the library, e.g. 'v201811' cache: A suds.cache.Cache instance to pass to the underlying SOAP library for caching. Raises: GoogleAdsValueError: The wrong type was given for caching. """ - super(SudsServiceProxy, self).__init__(header_handler, packer) + super(SudsServiceProxy, self).__init__(header_handler, packer, version) if cache and not isinstance(cache, suds.cache.Cache): raise googleads.errors.GoogleAdsValueError( @@ -1124,7 +1128,7 @@ class ZeepServiceProxy(GoogleSoapService): NO_CACHE = 'zeep_no_cache' def __init__(self, endpoint, header_handler, packer, - proxy_config, timeout, cache=None): + proxy_config, timeout, version, cache=None): """Initializes a zeep service proxy. Args: @@ -1135,6 +1139,7 @@ def __init__(self, endpoint, header_handler, packer, customized packing logic. proxy_config: A ProxyConfig that represents proxy settings. timeout: An integer to set the connection timeout. + version: the version of the current API, e.g. 'v201811' cache: An instance of zeep.cache.Base to pass to the underlying SOAP library for caching. A file cache by default. To disable, pass googleads.common.ZeepServiceProxy.NO_CACHE. @@ -1142,7 +1147,7 @@ def __init__(self, endpoint, header_handler, packer, Raises: GoogleAdsValueError: The wrong type was given for caching. """ - super(ZeepServiceProxy, self).__init__(header_handler, packer) + super(ZeepServiceProxy, self).__init__(header_handler, packer, version) if cache and not (isinstance(cache, zeep.cache.Base) or cache == self.NO_CACHE): @@ -1264,7 +1269,7 @@ def _PackArgumentsHelper(self, elem, data, set_type_attrs): An instance of type 'elem'. """ if self._packer: - data = self._packer.Pack(data) + data = self._packer.Pack(data, self._version) if isinstance(data, dict): # Instantiate from simple Python dict # See if there is a manually specified derived type. diff --git a/tests/ad_manager_test.py b/tests/ad_manager_test.py index 9a0541f6..19e49082 100644 --- a/tests/ad_manager_test.py +++ b/tests/ad_manager_test.py @@ -29,6 +29,7 @@ URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' +CURRENT_VERSION = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1] class BaseValue(object): @@ -341,7 +342,7 @@ def testGetService_success(self): 'https://testing.test.com/apis/ads/publisher/%s/%s?wsdl' % (self.version, service_name), ad_manager._header_handler, googleads.ad_manager._AdManagerPacker, 'proxy', 'timeout', - cache='cache') + self.version, cache='cache') self.assertEqual(service, mock_service) @@ -384,25 +385,34 @@ def setUp(self): def testPackDate(self): input_date = datetime.date(2017, 1, 2) - result = self.packer.Pack(input_date) + result = self.packer.Pack(input_date, CURRENT_VERSION) self.assertEqual(result, {'year': 2017, 'month': 1, 'day': 2}) - def testPackDateTime(self): + def testPackDateTimePreV201811(self): input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) input_date = pytz.timezone('America/New_York').localize(input_date) - result = self.packer.Pack(input_date) + result = self.packer.Pack(input_date, 'v201808') self.assertEqual(result, {'date': {'year': 2017, 'month': 1, 'day': 2}, 'hour': 3, 'minute': 4, 'second': 5, 'timeZoneID': 'America/New_York'}) + def testPackDateTimePostV201811(self): + input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) + input_date = pytz.timezone('America/New_York').localize(input_date) + result = self.packer.Pack(input_date, CURRENT_VERSION) + self.assertEqual(result, {'date': {'year': 2017, 'month': 1, 'day': 2}, + 'hour': 3, 'minute': 4, 'second': 5, + 'timeZoneId': 'America/New_York'}) + def testPackDateTimeNeedsTimeZone(self): input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) self.assertRaises(googleads.errors.GoogleAdsValueError, - self.packer.Pack, input_date) + self.packer.Pack, input_date, CURRENT_VERSION) def testPackUnsupportedObjectType(self): obj = object() - self.assertEqual(googleads.ad_manager._AdManagerPacker.Pack(obj), obj) + self.assertEqual(googleads.ad_manager._AdManagerPacker. + Pack(obj, CURRENT_VERSION), obj) class DataDownloaderTest(unittest.TestCase): @@ -417,10 +427,14 @@ def setUp(self): oauth2_client, application_name, network_code, self.https_proxy) self.version = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1] self.report_downloader = self.ad_manager.GetDataDownloader() + self.report_downloader_201808 = self.ad_manager.GetDataDownloader( + version='v201808') self.pql_service = mock.Mock() self.report_service = mock.Mock() self.report_downloader._pql_service = self.pql_service self.report_downloader._report_service = self.report_service + self.report_downloader_201808._pql_service = self.pql_service + self.report_downloader_201808._report_service = self.report_service self.generic_header = [{'labelName': 'Some random header...'}, {'labelName': 'Another header...'}] @@ -443,6 +457,20 @@ def setUp(self): } row1_field4 = { + 'value': { + 'date': { + 'year': '2012', + 'month': '11', + 'day': '05' + }, + 'hour': '12', + 'minute': '12', + 'second': '12', + 'timeZoneId': 'PST8PDT'}, + 'xsi_type': 'DateTimeValue' + } + + row1_field4_201808 = { 'value': { 'date': { 'year': '2012', @@ -494,6 +522,21 @@ def setUp(self): } row2_field4 = { + 'value': { + 'date': { + 'year': '2013', + 'month': '01', + 'day': '03' + }, + 'hour': '02', + 'minute': '02', + 'second': '02', + 'timeZoneId': 'GMT' + }, + 'xsi_type': 'DateTimeValue' + } + + row2_field4_201808 = { 'value': { 'date': { 'year': '2013', @@ -529,12 +572,23 @@ def setUp(self): row2 = [row2_field1, row2_field2, row2_field3, row2_field4, row2_field5, row2_field6] + row1_201808 = [row1_field1, row1_field2, row1_field3, row1_field4_201808, + row1_field5, row1_field6] + row2_201808 = [row2_field1, row2_field2, row2_field3, row2_field4_201808, + row2_field5, row2_field6] + self.generic_rval = [{ 'values': [DecideValue(value) for value in row1] }, { 'values': [DecideValue(value) for value in row2] }] + self.generic_rval_201808 = [{ + 'values': [DecideValue(value) for value in row1_201808] + }, { + 'values': [DecideValue(value) for value in row2_201808] + }] + def testDownloadPqlResultSetToCsv(self): csv_file = six.StringIO() @@ -587,6 +641,25 @@ def testDownloadPqlResultToList(self): self.generic_header[1]['labelName']], row1, row2], result_set) + def testDownloadPqlResultToList_201808(self): + self.pql_service.select.return_value = {'rows': self.generic_rval_201808, + 'columnTypes': self.generic_header} + + result_set = self.report_downloader_201808.DownloadPqlResultToList( + 'SELECT Id, Name FROM Line_Item') + + row1 = [self.report_downloader_201808._ConvertValueForCsv(field) + for field in self.generic_rval_201808[0]['values']] + row2 = [self.report_downloader_201808._ConvertValueForCsv(field) + for field in self.generic_rval_201808[1]['values']] + + self.pql_service.select.assert_called_once_with( + {'values': None, + 'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')}) + self.assertEqual([[self.generic_header[0]['labelName'], + self.generic_header[1]['labelName']], + row1, row2], result_set) + def testDownloadPqlResultToListWithOldValuesList(self): self.pql_service.select.return_value = {'rows': self.generic_rval, 'columnTypes': self.generic_header} @@ -861,6 +934,94 @@ def testWhereWithOtherTypes(self): test_statement.WithBindVariable('test_datetime_key', test_dt) test_statement.WithBindVariable('test_set_key', [1, 2]) + target_values = [{ + 'key': 'test_bool_key', + 'value': { + 'xsi_type': 'BooleanValue', + 'value': True, + } + }, { + 'key': 'test_number_key', + 'value': { + 'xsi_type': 'NumberValue', + 'value': 5, + } + }, { + 'key': 'test_date_key', + 'value': { + 'xsi_type': 'DateValue', + 'value': { + 'year': 2017, + 'month': 1, + 'day': 2, + }, + } + }, { + 'key': 'test_datetime_key', + 'value': { + 'xsi_type': 'DateTimeValue', + 'value': { + 'date': { + 'year': 2017, + 'month': 1, + 'day': 2, + }, + 'hour': 3, + 'minute': 4, + 'second': 5, + 'timeZoneId': 'America/New_York' + }, + } + }, { + 'key': 'test_set_key', + 'value': { + 'xsi_type': 'SetValue', + 'values': [ + {'xsi_type': 'NumberValue', 'value': 1}, + {'xsi_type': 'NumberValue', 'value': 2}, + ], + } + }] + target_values.sort(key=lambda v: v['key']) + + statement_result = test_statement.ToStatement() + self.assertEqual(statement_result['query'], + ('WHERE bool_key = :test_bool_key ' + 'AND number_key = :test_number_key ' + 'AND date_key = :test_date_key ' + 'AND datetime_key = :test_datetime_key ' + 'AND set_key = :test_set_key ' + 'LIMIT %s ' + 'OFFSET 0' % googleads.ad_manager.SUGGESTED_PAGE_LIMIT + )) + + # The output order doesn't matter, and it's stored internally as a dict + # until rendered, which is fine, but we need to lock it down for this test. + self.assertEqual( + sorted(statement_result['values'], key=lambda v: v['key']), + target_values + ) + + def testWhereWithOtherTypes_201808(self): + test_statement = googleads.ad_manager.StatementBuilder(version='v201808') + test_statement.Where(( + 'bool_key = :test_bool_key ' + 'AND number_key = :test_number_key ' + 'AND date_key = :test_date_key ' + 'AND datetime_key = :test_datetime_key ' + 'AND set_key = :test_set_key' + )) + + test_statement.WithBindVariable('test_bool_key', True) + test_statement.WithBindVariable('test_number_key', 5) + test_statement.WithBindVariable('test_date_key', datetime.date(2017, 1, 2)) + test_dt = datetime.datetime(2017, 1, 2, + hour=3, minute=4, second=5, + ) + test_dt = pytz.timezone('America/New_York').localize(test_dt) + test_statement.WithBindVariable('test_datetime_key', test_dt) + test_statement.WithBindVariable('test_set_key', [1, 2]) + target_values = [{ 'key': 'test_bool_key', 'value': { diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 9c893995..1575e130 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -430,6 +430,7 @@ def testGetService_success(self): googleads.adwords._AdWordsPacker, 'proxy_config', 'timeout', + CURRENT_VERSION, cache='cache') self.assertEqual(service, mock_service) @@ -504,11 +505,12 @@ def testAdWordsPackerForServiceQuery(self): query_regex = (r'SELECT (.*) WHERE Status = "ENABLED"' r' ORDER BY Name ASC LIMIT 0,100') - self.assertRegexpMatches(self.packer.Pack(query), query_regex) + self.assertRegexpMatches(self.packer.Pack(query, CURRENT_VERSION), + query_regex) def testAdWordsPackerForUnsupportedObjectType(self): obj = object() - self.assertEqual(self.packer.Pack(obj), obj) + self.assertEqual(self.packer.Pack(obj, CURRENT_VERSION), obj) class BatchJobHelperTest(testing.CleanUtilityRegistryTestCase): diff --git a/tests/common_test.py b/tests/common_test.py index 95955898..2e653f48 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -41,6 +41,7 @@ URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' TEST_DIR = os.path.dirname(__file__) +CURRENT_VERSION = 'v201811' class CommonTest(testing.CleanUtilityRegistryTestCase): @@ -64,7 +65,7 @@ def setUp(self): self.test1_name = 'Test1' self.test2_name = 'Test2' self.test2_version = 'testing' - + self.fake_version = 'ignored' locale_patcher = mock.patch('googleads.common.locale.getdefaultlocale', return_value=('en_us', 'UTF-8')) self.locale_patcher = locale_patcher.start() @@ -897,7 +898,7 @@ def testPackForSuds(self): def testPackForSuds_applyCustomPacker(self): class CustomPacker(googleads.common.SoapPacker): @classmethod - def Pack(cls, obj): + def Pack(cls, obj, version): if isinstance(obj, numbers.Number): return {'xsi_type': 'Integer', 'value': str(int(obj))} return obj @@ -908,7 +909,8 @@ def Pack(cls, obj): [('Number.Type', 0), ('value', 1)]) number = 3.14159265358979323846264 - rval = googleads.common._PackForSuds(number, factory, CustomPacker) + rval = googleads.common._PackForSuds(number, factory, CustomPacker, + CURRENT_VERSION) self.assertEqual('Integer', getattr(rval, 'Number.Type')) self.assertEqual('3', rval.value) @@ -945,6 +947,7 @@ def setUp(self): self.empty_proxy_config = googleads.common.ProxyConfig() self.timeout_100 = 100 + self.fake_version = 'ignored' def testCreateZeepClient(self): header_handler = mock.Mock() @@ -959,7 +962,8 @@ class MyCache(zeep.cache.Base): mock.patch('googleads.common._ZeepProxyTransport') as zeep_transport, \ mock.patch('googleads.util.ZeepLogger') as zeep_logger: zeep_wrapper = googleads.common.ZeepServiceProxy( - 'http://abc', header_handler, packer, 'proxy', 'timeout', cache) + 'http://abc', header_handler, packer, 'proxy', 'timeout', + self.fake_version, cache) zeep_auth.assert_called_once_with(header_handler) plugins = [zeep_auth.return_value, zeep_logger.return_value] @@ -976,7 +980,7 @@ def testCreateSoapElementForType(self): with mock_zeep_client(): zeep_wrapper = googleads.common.ZeepServiceProxy( 'http://abc', header_handler, packer, - self.empty_proxy_config, self.timeout_100) + self.empty_proxy_config, self.timeout_100, self.fake_version) type_mock = mock.Mock() zeep_wrapper.zeep_client.get_type.return_value = type_mock @@ -991,7 +995,7 @@ def testWsdlHasMethod(self): with mock_zeep_client(): zeep_wrapper = googleads.common.ZeepServiceProxy( 'http://abc', header_handler, packer, - self.empty_proxy_config, self.timeout_100) + self.empty_proxy_config, self.timeout_100, self.fake_version) with mock.patch.object(zeep_wrapper, '_method_bindings') as mock_bindings: get_method = mock_bindings.get @@ -1007,7 +1011,8 @@ def testZeepErrorRaisesGoogleError(self): with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError): googleads.common.ZeepServiceProxy( - 'http://abc', None, None, self.empty_proxy_config, self.timeout_100) + 'http://abc', None, None, self.empty_proxy_config, self.timeout_100, + self.fake_version) @mock.patch('googleads.common._ZeepProxyTransport') def testSchemaHelperRaisesGoogleError(self, mock_transport_class): @@ -1024,7 +1029,7 @@ def testGetRequestXML(self): with mock_zeep_client(): zeep_wrapper = googleads.common.ZeepServiceProxy( 'http://abc', header_handler, packer, - self.empty_proxy_config, self.timeout_100) + self.empty_proxy_config, self.timeout_100, self.fake_version) mock_create = zeep_wrapper.zeep_client.create_message @@ -1051,7 +1056,8 @@ def testBadCacheType(self): self.assertRaises(googleads.errors.GoogleAdsValueError): googleads.common.ZeepServiceProxy( 'http://abc', header_handler, packer, - self.empty_proxy_config, self.timeout_100, cache='not_a_zeep_cache') + self.empty_proxy_config, self.timeout_100, self.fake_version, + cache='not_a_zeep_cache') def testSchemaHelperBadCacheType(self): with self.assertRaises(googleads.errors.GoogleAdsValueError): @@ -1065,7 +1071,7 @@ def testAllowsNoCache(self): mock.patch('googleads.common._ZeepProxyTransport') as zeep_transport: googleads.common.ZeepServiceProxy( 'http://abc', header_handler, packer, - self.empty_proxy_config, self.timeout_100, + self.empty_proxy_config, self.timeout_100, self.fake_version, cache=googleads.common.ZeepServiceProxy.NO_CACHE) zeep_transport.assert_called_once_with( @@ -1081,7 +1087,7 @@ def testFaultWithErrors(self): with mock_zeep_client(): zeep_wrapper = googleads.common.ZeepServiceProxy( 'http://abc', header_handler, packer, - googleads.common.ProxyConfig(), 100) + googleads.common.ProxyConfig(), 100, self.fake_version) zeep_wrapper.zeep_client.service['mymethod'].side_effect = fault zeep_wrapper._GetBindingNamespace = mock.Mock() @@ -1109,11 +1115,12 @@ class TestZeepArgumentPacking(unittest.TestCase): def setUp(self): header_handler = mock.Mock() - + self.fake_version = 'ignored' wsdl_path = os.path.join( TEST_DIR, 'test_data/ad_manager_report_service.xml') self.zeep_client = googleads.common.ZeepServiceProxy( - wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100) + wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100, + self.fake_version) def testPackArgumentsPrimitivesOnly(self): result = self.zeep_client._PackArguments('getReportJobStatus', [5]) @@ -1174,8 +1181,11 @@ def testPackArgumentsLooksThroughSoapElements(self): def testPackArgumentsWithCustomPacker(self): class CustomPacker(googleads.common.SoapPacker): + def __init__(self): + self._version = CURRENT_VERSION + @classmethod - def Pack(cls, obj): + def Pack(cls, obj, version): if isinstance(obj, numbers.Number): return '50' return obj @@ -1199,7 +1209,8 @@ def testPackArgumentsMultipleSchemas(self): wsdl_path = os.path.join( TEST_DIR, 'test_data/traffic_estimator_service.xml') zeep_client = googleads.common.ZeepServiceProxy( - wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100) + wsdl_path, header_handler, None, googleads.common.ProxyConfig(), 100, + self.fake_version) element = zeep_client.zeep_client.get_type('ns0:Criterion') data = {'xsi_type': 'Location', 'id': '2840'} @@ -1217,6 +1228,9 @@ def testPackArgumentsBadType(self): class SudsServiceProxyTest(unittest.TestCase): """Tests for the googleads.common.SudsServiceProxy class.""" + def setUp(self): + self.fake_version = 'ignored' + def testCreateSudsClient(self): class MyCache(suds.cache.Cache): pass @@ -1238,7 +1252,7 @@ class MyCache(suds.cache.Cache): suds_wrapper = googleads.common.SudsServiceProxy( 'https://endpoint', header_handler, packer, proxy_config, - 1000, cache) + 1000, self.fake_version, cache) mock_transport.assert_called_once_with(1000, proxy_config) mock_suds_client.assert_called_once_with( @@ -1277,7 +1291,8 @@ def testGetMethod(self): mock_suds_client_class.return_value = mock_suds_client suds_wrapper = googleads.common.SudsServiceProxy( - 'https://endpoint', header_handler, None, None, 1000, None + 'https://endpoint', header_handler, None, None, 1000, + self.fake_version, None ) with mock.patch.object(suds_wrapper, '_CreateMethod') as mock_create: @@ -1387,7 +1402,7 @@ def testGetRequestXML(self): def testCreateSoapElementForType(self): with self.mock_suds_api(): suds_wrapper = googleads.common.SudsServiceProxy( - 'https://endpoint', None, None, None, 1000, None) + 'https://endpoint', None, None, None, 1000, self.fake_version, None) suds_wrapper.suds_client.factory.create.return_value = 'result' result = suds_wrapper.CreateSoapElementForType('MyType') @@ -1396,7 +1411,7 @@ def testCreateSoapElementForType(self): def testSetHeaders(self): with self.mock_suds_api(): suds_wrapper = googleads.common.SudsServiceProxy( - 'https://endpoint', None, None, None, 1000, None) + 'https://endpoint', None, None, None, 1000, self.fake_version, None) suds_wrapper.SetHeaders('soap', 'http') suds_wrapper.suds_client.set_options.assert_called_once_with( @@ -1406,7 +1421,8 @@ def testBadCache(self): with self.mock_suds_api(), \ self.assertRaises(googleads.errors.GoogleAdsValueError): googleads.common.SudsServiceProxy( - 'https://endpoint', None, None, None, 1000, 'not_a_suds_cache') + 'https://endpoint', None, None, None, 1000, 'not_a_suds_cache', + self.fake_version) def testSchemaHelperBadCache(self): with self.assertRaises(googleads.errors.GoogleAdsValueError): From e731aa5dc3079cf9dd4a1cd24625343bf3107a09 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 15 Nov 2018 15:48:43 -0500 Subject: [PATCH 124/180] Commiting latest changes. From cf2e9082423aee8c77df7c8e88fbd97200b664c5 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Mon, 26 Nov 2018 15:53:27 -0500 Subject: [PATCH 125/180] Updating documentation for 15.0.1 --- ChangeLog | 3 + .../v201809/shopping/add_smart_shopping_ad.py | 230 ++++++++++++++++++ googleads/common.py | 2 +- 3 files changed, 234 insertions(+), 1 deletion(-) create mode 100755 examples/adwords/v201809/shopping/add_smart_shopping_ad.py diff --git a/ChangeLog b/ChangeLog index 4f79c5e5..f1981c13 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +15.0.1 -- 11/16/2018 +* Added Smart Shopping ad example (v201809) + 15.0.0 -- 11/14/2018 * Added support for v201811. * Removed support for v201711. diff --git a/examples/adwords/v201809/shopping/add_smart_shopping_ad.py b/examples/adwords/v201809/shopping/add_smart_shopping_ad.py new file mode 100755 index 00000000..4272699c --- /dev/null +++ b/examples/adwords/v201809/shopping/add_smart_shopping_ad.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC +# +# 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 adds a Smart Shopping campaign with an ad group and ad group ad. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import adwords + +# If set to true, a default partition will be created. +# Set it to false if you plan to run the add_product_partition_tree.py +# example right after this example. +CREATE_DEFAULT_PARTITION = False +MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' + + +def main(client, merchant_id, create_default_partition): + budget_id = CreateBudget(client) + campaign_id = CreateSmartCampaign(client, budget_id, merchant_id) + ad_group_id = CreateSmartShoppingAdGroup(client, campaign_id) + CreateSmartShoppingAd(client, ad_group_id) + + if create_default_partition: + CreateDefaultPartition(client, ad_group_id) + + +def CreateBudget(client): + """Adds a new budget. + + Args: + client: an AdWordsClient instance. + Returns: + A budget ID. + """ + budget_service = client.GetService('BudgetService', version='v201809') + + budget = { + 'name': 'Interplanetary budget #%s' % uuid.uuid4(), + 'amount': { + 'microAmount': '50000000' + }, + 'deliveryMethod': 'STANDARD', + # Non-shared budgets are required for Smart Shopping campaigns. + 'isExplicitlyShared': False + } + + budget_operations = [{ + 'operator': 'ADD', + 'operand': budget + }] + + # Add the budget. + budget_id = budget_service.mutate(budget_operations)['value'][0][ + 'budgetId'] + + return budget_id + + +def CreateSmartCampaign(client, budget_id, merchant_id): + """Adds a new Smart Shopping campaign. + + Args: + client: an AdWordsClient instance. + budget_id: the str ID of the budget to be associated with the Shopping + campaign. + merchant_id: the str ID of the merchant account to be associated with the + Shopping campaign. + Returns: + A campaign ID. + """ + campaign_service = client.GetService('CampaignService', version='v201809') + # Create campaign with required and optional settings. + campaign = { + 'name': 'Shopping campaign #%s' % uuid.uuid4(), + # The advertisingChannelType is what makes this a Shopping campaign. + 'advertisingChannelType': 'SHOPPING', + # Sets the advertisingChannelSubType to SHOPPING_GOAL_OPTIMIZED_ADS to + # make this a Smart Shopping campaign. + 'advertisingChannelSubType': 'SHOPPING_GOAL_OPTIMIZED_ADS', + # Recommendation: Set the campaign to PAUSED when creating it to stop the + # ads from immediately serving. Set to ENABLED once you've added targeting + # and the ads are ready to serve. + 'status': 'PAUSED', + # Set portfolio budget (required). + 'budget': {'budgetId': budget_id}, + # Set a bidding strategy. Only MAXIMIZE_CONVERSION_VALUE is supported. + 'biddingStrategyConfiguration': { + 'biddingStrategyType': 'MAXIMIZE_CONVERSION_VALUE' + }, + 'settings': [{ + # All Shopping campaigns need a ShoppingSetting. + 'xsi_type': 'ShoppingSetting', + 'salesCountry': 'US', + 'merchantId': merchant_id + }] + } + + campaign_operations = [{ + 'operator': 'ADD', + 'operand': campaign + }] + + result = campaign_service.mutate(campaign_operations)['value'][0] + + print ('Smart Shopping campaign with name "%s" and ID "%s" was added.' + % (result['name'], result['id'])) + + return result['id'] + + +def CreateSmartShoppingAdGroup(client, campaign_id): + """Adds a new Smart Shopping ad group. + + Args: + client: an AdWordsClient instance. + campaign_id: the str ID of a Smart Shopping campaign. + Returns: + An ad group ID. + """ + ad_group_service = client.GetService('AdGroupService', version='v201809') + # Create the ad group. + ad_group = { + 'campaignId': campaign_id, + 'name': 'Smart Shopping ad group #%s' % uuid.uuid4(), + # Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS. + 'adGroupType': 'SHOPPING_GOAL_OPTIMIZED_ADS' + } + + adgroup_operations = { + 'operator': 'ADD', + 'operand': ad_group + } + + # Make the mutate request to add the AdGroup to the Smart Shopping campaign. + ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] + ad_group_id = ad_group['id'] + + print ('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) + + return ad_group_id + + +def CreateSmartShoppingAd(client, ad_group_id): + """Adds a new Smart Shopping ad. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') + # Create an AdGroup Ad. + adgroup_ad = { + 'adGroupId': ad_group_id, + # Create a Smart Shopping ad (Goal-optimized Shopping ad). + 'ad': { + 'xsi_type': 'GoalOptimizedShoppingAd' + } + } + + ad_operation = { + 'operator': 'ADD', + 'operand': adgroup_ad + } + + # Make the mutate request to add the Smart Shopping ad to the AdGroup. + ad_result = ad_group_ad_service.mutate([ad_operation]) + + for adgroup_ad in ad_result['value']: + print 'Smart Shopping ad with ID "%s" was added.' % adgroup_ad['ad']['id'] + + +def CreateDefaultPartition(client, ad_group_id): + """Creates a default partition. + + Args: + client: an AdWordsClient instance. + ad_group_id: an integer ID for an ad group. + """ + ad_group_criterion_service = client.GetService('AdGroupCriterionService', + version='v201809') + + operations = [{ + 'operator': 'ADD', + 'operand': { + 'xsi_type': 'BiddableAdGroupCriterion', + 'adGroupId': ad_group_id, + # Make sure that caseValue and parentCriterionId are left unspecified. + # This makes this partition as generic as possible to use as a + # fallback when others don't match. + 'criterion': { + 'xsi_type': 'ProductPartition', + 'partitionType': 'UNIT' + } + } + }] + + ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] + + print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], + ad_group_criterion['adGroupId'])) + + +if __name__ == '__main__': + # Initialize client object. + adwords_client = adwords.AdWordsClient.LoadFromStorage() + + main(adwords_client, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/googleads/common.py b/googleads/common.py index 64419dbc..77d4ab8f 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '15.0.0' +VERSION = '15.0.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' From fe86335c416e0571328c0a481c4b0cff863c01d9 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Mon, 26 Nov 2018 15:55:34 -0500 Subject: [PATCH 126/180] Commiting latest changes. From 01cd7356119ad75e5b277fe066208a5585ace4d1 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Wed, 9 Jan 2019 10:21:42 -0500 Subject: [PATCH 127/180] Updating PyYaml dependency to resolve security flaw --- ChangeLog | 3 +++ README.md | 2 ++ googleads/common.py | 2 +- setup.py | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index f1981c13..967145d8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +15.0.2 -- 01/08/2019 +* Updated PyYAML dependencies to >=4.2b1 for https://nvd.nist.gov/vuln/detail/CVE-2017-18342 + 15.0.1 -- 11/16/2018 * Added Smart Shopping ad example (v201809) diff --git a/README.md b/README.md index f40cc90e..00ad1b9e 100644 --- a/README.md +++ b/README.md @@ -259,3 +259,5 @@ have Python 2.7.9 (or higher) or Python 3.4 (or higher) installed. ## Authors: Mark Saniscalchi + David Wihl + Ben Karl diff --git a/googleads/common.py b/googleads/common.py index 77d4ab8f..5424190f 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '15.0.1' +VERSION = '15.0.2' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/setup.py b/setup.py index b80cdc9a..e0a26b55 100755 --- a/setup.py +++ b/setup.py @@ -26,7 +26,7 @@ DEPENDENCIES = ['google-auth>=1.0.0,<2.0.0', 'google-auth-oauthlib>=0.0.1,<1.0.0', 'pytz>=2015.7', - 'PyYAML>=3.11,<4.0', 'requests>=2.0.0,<3.0.0', + 'PyYAML>=4.2b1, <5.0', 'requests>=2.0.0,<3.0.0', 'suds-jurko>=0.6,<0.7', 'xmltodict>=0.9.2,<1.0.0', 'zeep>=2.5.0'] From 20abf4d034f0557958ecd70db5a4bb41b7ade30b Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Wed, 9 Jan 2019 10:23:47 -0500 Subject: [PATCH 128/180] Commiting latest changes. From ab8b32612a7a10e28be2fd956022b230d3996bf3 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Fri, 1 Feb 2019 12:42:13 -0500 Subject: [PATCH 129/180] Removing support for AdWords v201802 --- ChangeLog | 3 + examples/adwords/v201802/__init__.py | 15 - .../v201802/account_management/__init__.py | 15 - .../account_management/accept_service_link.py | 62 --- .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 99 ---- .../get_account_hierarchy.py | 104 ---- .../v201802/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 226 -------- .../add_ad_group_bid_modifier.py | 75 --- .../add_dynamic_page_feed.py | 295 ---------- .../add_dynamic_search_ads_campaign.py | 257 --------- ...add_expanded_text_ad_with_upgraded_urls.py | 113 ---- .../advanced_operations/add_gmail_ad.py | 115 ---- .../advanced_operations/add_html5_ad.py | 110 ---- .../add_responsive_display_ad.py | 158 ------ ...d_shopping_dynamic_remarketing_campaign.py | 304 ---------- .../add_universal_app_campaign.py | 218 -------- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 171 ------ .../v201802/basic_operations/__init__.py | 15 - .../v201802/basic_operations/add_ad_groups.py | 115 ---- .../v201802/basic_operations/add_campaigns.py | 127 ----- .../basic_operations/add_expanded_text_ads.py | 74 --- .../v201802/basic_operations/add_keywords.py | 92 --- .../v201802/basic_operations/get_ad_groups.py | 76 --- .../v201802/basic_operations/get_campaigns.py | 68 --- .../get_campaigns_with_awql.py | 61 -- .../basic_operations/get_expanded_text_ads.py | 90 --- .../v201802/basic_operations/get_keywords.py | 87 --- .../v201802/basic_operations/pause_ad.py | 61 -- .../v201802/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 85 --- .../basic_operations/update_campaign.py | 58 -- .../basic_operations/update_keyword.py | 82 --- .../v201802/campaign_management/__init__.py | 15 - ...campaign_groups_and_performance_targets.py | 152 ----- .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 428 -------------- .../v201802/campaign_management/add_draft.py | 81 --- ...dd_keywords_using_incremental_batch_job.py | 257 --------- .../v201802/campaign_management/add_trial.py | 116 ---- .../get_all_disapproved_ads.py | 103 ---- .../get_all_disapproved_ads_with_awql.py | 88 --- .../get_campaigns_by_label.py | 83 --- .../campaign_management/graduate_trial.py | 79 --- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201802/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 131 ----- .../handle_policy_violation_error.py | 166 ------ .../adwords/v201802/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 156 ------ .../adwords/v201802/extensions/add_prices.py | 157 ------ .../v201802/extensions/add_site_links.py | 146 ----- .../extensions/add_site_links_using_feeds.py | 265 --------- .../adwords/v201802/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 526 ------------------ examples/adwords/v201802/misc/__init__.py | 15 - .../v201802/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201802/misc/upload_image.py | 65 --- .../v201802/misc/upload_media_bundle.py | 58 -- .../adwords/v201802/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 182 ------ ...aign_criterion_bid_modifier_simulations.py | 97 ---- .../get_keyword_bid_simulations.py | 104 ---- .../v201802/optimization/get_keyword_ideas.py | 113 ---- .../adwords/v201802/remarketing/__init__.py | 15 - .../v201802/remarketing/add_audience.py | 104 ---- .../remarketing/add_conversion_tracker.py | 66 --- .../remarketing/add_conversion_trackers.py | 101 ---- .../remarketing/add_crm_based_user_list.py | 104 ---- .../remarketing/add_rule_based_user_lists.py | 235 -------- .../upload_offline_call_conversions.py | 77 --- .../remarketing/upload_offline_conversions.py | 82 --- .../remarketing/upload_offline_data.py | 259 --------- .../adwords/v201802/reporting/__init__.py | 15 - ...oad_criteria_report_as_stream_with_awql.py | 79 --- ...criteria_report_as_stream_with_selector.py | 72 --- ...oad_criteria_report_as_string_with_awql.py | 58 -- ...criteria_report_as_string_with_selector.py | 55 -- .../download_criteria_report_with_awql.py | 58 -- .../download_criteria_report_with_selector.py | 56 -- .../v201802/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 244 -------- examples/adwords/v201802/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 279 ---------- .../v201802/shopping/add_product_scope.py | 104 ---- .../v201802/shopping/add_shopping_campaign.py | 172 ------ .../add_shopping_campaign_for_showcase_ads.py | 401 ------------- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201802/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 126 ----- .../add_customer_negative_criteria.py | 74 --- .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201802/targeting/lookup_location.py | 82 --- googleads/adwords.py | 52 -- googleads/common.py | 2 +- tests/test_data/traffic_estimator_service.xml | 64 ++- 107 files changed, 51 insertions(+), 11567 deletions(-) delete mode 100644 examples/adwords/v201802/__init__.py delete mode 100644 examples/adwords/v201802/account_management/__init__.py delete mode 100755 examples/adwords/v201802/account_management/accept_service_link.py delete mode 100755 examples/adwords/v201802/account_management/create_account.py delete mode 100755 examples/adwords/v201802/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201802/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201802/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_gmail_ad.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py delete mode 100755 examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py delete mode 100755 examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201802/basic_operations/__init__.py delete mode 100755 examples/adwords/v201802/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201802/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201802/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201802/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201802/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201802/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201802/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201802/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201802/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201802/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201802/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201802/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201802/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201802/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201802/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201802/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201802/campaign_management/__init__.py delete mode 100755 examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py delete mode 100755 examples/adwords/v201802/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201802/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201802/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201802/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201802/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201802/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201802/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201802/error_handling/__init__.py delete mode 100755 examples/adwords/v201802/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201802/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201802/extensions/__init__.py delete mode 100755 examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201802/extensions/add_prices.py delete mode 100755 examples/adwords/v201802/extensions/add_site_links.py delete mode 100755 examples/adwords/v201802/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201802/migration/__init__.py delete mode 100755 examples/adwords/v201802/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201802/misc/__init__.py delete mode 100755 examples/adwords/v201802/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201802/misc/upload_image.py delete mode 100755 examples/adwords/v201802/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201802/optimization/__init__.py delete mode 100755 examples/adwords/v201802/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201802/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201802/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201802/remarketing/__init__.py delete mode 100755 examples/adwords/v201802/remarketing/add_audience.py delete mode 100755 examples/adwords/v201802/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201802/remarketing/add_conversion_trackers.py delete mode 100755 examples/adwords/v201802/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201802/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201802/remarketing/upload_offline_call_conversions.py delete mode 100755 examples/adwords/v201802/remarketing/upload_offline_conversions.py delete mode 100755 examples/adwords/v201802/remarketing/upload_offline_data.py delete mode 100644 examples/adwords/v201802/reporting/__init__.py delete mode 100755 examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py delete mode 100755 examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py delete mode 100755 examples/adwords/v201802/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201802/reporting/download_criteria_report_with_selector.py delete mode 100755 examples/adwords/v201802/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201802/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201802/shopping/__init__.py delete mode 100755 examples/adwords/v201802/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201802/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201802/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py delete mode 100755 examples/adwords/v201802/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201802/targeting/__init__.py delete mode 100755 examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201802/targeting/add_customer_negative_criteria.py delete mode 100755 examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201802/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 967145d8..409c6eb6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +16.0.0 -- 01/29/2019 +* Removed support for AdWords v201802 + 15.0.2 -- 01/08/2019 * Updated PyYAML dependencies to >=4.2b1 for https://nvd.nist.gov/vuln/detail/CVE-2017-18342 diff --git a/examples/adwords/v201802/__init__.py b/examples/adwords/v201802/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201802/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201802/account_management/__init__.py b/examples/adwords/v201802/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201802/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201802/account_management/accept_service_link.py b/examples/adwords/v201802/account_management/accept_service_link.py deleted file mode 100755 index b01f7180..00000000 --- a/examples/adwords/v201802/account_management/accept_service_link.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' - - -def main(client, service_link_id): - # Initialize appropriate service. - customer_service = client.GetService( - 'CustomerService', version='v201802') - - # Create the operation to set the status to ACTIVE. - operations = [{ - 'operator': 'SET', - 'operand': { - 'serviceLinkId': service_link_id, - 'serviceType': 'MERCHANT_CENTER', - 'linkStatus': 'ACTIVE', - } - }] - - # Update the service link. - mutated_service_links = customer_service.mutateServiceLinks(operations) - - # Display results. - for mutated_service_link in mutated_service_links: - print ('Service link with service link ID "%s", type "%s" was updated ' - 'to status: "%s".' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201802/account_management/create_account.py b/examples/adwords/v201802/account_management/create_account.py deleted file mode 100755 index 4d305c37..00000000 --- a/examples/adwords/v201802/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201802') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID "%s" was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/account_management/get_account_changes.py b/examples/adwords/v201802/account_management/get_account_changes.py deleted file mode 100755 index 659a4606..00000000 --- a/examples/adwords/v201802/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201802') - campaign_service = client.GetService('CampaignService', version='v201802') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id "%s" has change status "%s".' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id "%s" has change status "%s".' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/account_management/get_account_hierarchy.py b/examples/adwords/v201802/account_management/get_account_hierarchy.py deleted file mode 100755 index 4cffedc7..00000000 --- a/examples/adwords/v201802/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201802') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/__init__.py b/examples/adwords/v201802/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201802/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201802/advanced_operations/add_ad_customizer.py b/examples/adwords/v201802/advanced_operations/add_ad_customizer.py deleted file mode 100755 index adff3d83..00000000 --- a/examples/adwords/v201802/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates ExpandedTextAds that use ad customizations for specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no ExpandedTextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201802') - - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'headlinePart2': 'Only {=%s.Price}' % feed_name, - 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': expanded_text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID "%s", type "%s", and status "%s".' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201802') - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name "%s" and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201802') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0], - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - adgroup_ids[1], ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - -def CreateFeedItemAddOperation(name, price, date, adgroup_id, - ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values and AdGroupTargeting when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - adgroup_id: the ID of the ad_group to target with the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'adGroupTargeting': { - 'TargetingAdGroupId': adgroup_id - }, - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - operation = { - 'operator': 'ADD', - 'operand': feed_item - } - - return operation - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index e09b1d5a..00000000 --- a/examples/adwords/v201802/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201802') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py deleted file mode 100755 index 8ea1a2e4..00000000 --- a/examples/adwords/v201802/advanced_operations/add_dynamic_page_feed.py +++ /dev/null @@ -1,295 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. - -To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -from collections import namedtuple -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - -# Used to keep track of DSA page feed details. -_DSAFeedDetails = namedtuple( - '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) -# ID that corresponds to the labels. -DSA_LABEL_FIELD_ID = 2 -# The criterion type to be used for DSA page feeds. -DSA_PAGE_FEED_CRITERION_TYPE = 61 -DSA_PAGE_URL_LABEL = 'discounts' -# ID that corresponds to the page URLs. -DSA_PAGE_URLS_FIELD_ID = 1 - - -def main(client, campaign_id, ad_group_id): - # Get the page feed details. This code example creates a new feed, but you can - # fetch and re-use an existing feed. - feed_details = _CreateFeed(client) - _CreateFeedMapping(client, feed_details) - _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) - - # Associate the page feed with the campaign. - _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) - - # Optional: Target web pages matching the feed's label in the ad group. - _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) - - print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id - - -def _CreateFeed(client): - """Creates the feed for DSA page URLs. - - Args: - client: an AdWordsClient instance. - - Returns: - A _DSAFeedDetails instance containing details about the created feed. - """ - # Get the FeedService. - feed_service = client.GetService('FeedService', version='v201802') - - # Create operation. - operation = { - # Create the feed. - 'operand': { - 'name': 'DSA Feed %s' % uuid.uuid4(), - # Create attributes. - 'attributes': [ - {'type': 'URL_LIST', 'name': 'Page URL'}, - {'type': 'STRING_LIST', 'name': 'Label'} - ], - 'origin': 'USER' - }, - 'operator': 'ADD' - } - - # Add the feed. - feed = feed_service.mutate([operation])['value'][0] - return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], - feed['attributes'][1]['id']) - - -def _CreateFeedMapping(client, feed_details): - """Creates the feed mapping for DSA page feeds. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - """ - # Get the FeedMappingService. - feed_mapping_service = client.GetService('FeedMappingService', - version='v201802') - - # Create the operation. - operation = { - # Create the feed mapping. - 'operand': { - 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, - 'feedId': feed_details.feed_id, - # Map the feedAttributeIds to the fieldId constants. - 'attributeFieldMappings': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'fieldId': DSA_PAGE_URLS_FIELD_ID - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'fieldId': DSA_LABEL_FIELD_ID - } - ] - }, - 'operator': 'ADD' - } - - # Add the feed mapping. - feed_mapping_service.mutate([operation]) - - -def _CreateFeedItems(client, feed_details, label_name): - """Creates the page URLs in the DSA page feed. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - label_name: a str containing the page feed URL label. - """ - # Get the FeedItemService. - feed_item_service = client.GetService('FeedItemService', version='v201802') - - # For page feed URL recommendations and rules, see: - # https://support.google.com/adwords/answer/7166527 - urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', - 'http://www.example.com/discounts/hotel-deals?id={feeditem}', - 'http://www.example.com/discounts/flight-deals?id={feeditem}') - - # Create the operation. - operations = [{ - # Create the feed item. - 'operand': { - 'feedId': feed_details.feed_id, - 'attributeValues': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'stringValues': [url] - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'stringValues': [label_name] - } - ] - }, - 'operator': 'ADD' - } for url in urls] - - # Add the feed item. - feed_item_service.mutate(operations) - - -def _UpdateCampaignDSASetting(client, campaign_id, feed_id): - """Updates the campaign DSA setting to DSA pagefeeds. - - Args: - client: an AdWordsClient instance. - campaign_id: a str Campaign ID. - feed_id: a str page Feed ID. - - Raises: - ValueError: If the given campaign is found not to be a dynamic search ad - campaign. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201802') - - selector = { - 'fields': ['Id', 'Settings'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [campaign_id] - }] - } - - response = campaign_service.get(selector) - - if response['totalNumEntries']: - campaign = response['entries'][0] - else: - raise ValueError('No campaign with ID "%d" exists.' % campaign_id) - - if not campaign['settings']: - raise ValueError('This is not a DSA campaign.') - - dsa_setting = None - - campaign_settings = campaign['settings'] - - for setting in campaign_settings: - if setting['Setting.Type'] == 'DynamicSearchAdsSetting': - dsa_setting = setting - break - - if dsa_setting is None: - raise ValueError('This is not a DSA campaign.') - - dsa_setting['pageFeed'] = { - 'feedIds': [feed_id] - } - - # Optional: Specify whether only the supplied URLs should be used with your - # Dynamic Search Ads. - dsa_setting['useSuppliedUrlsOnly'] = True - - operation = { - 'operand': { - 'id': campaign_id, - 'settings': campaign_settings - }, - 'operator': 'SET' - } - - campaign_service.mutate([operation]) - print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( - campaign_id, feed_id) - - -def _AddDSATargeting(client, ad_group_id, label_name): - """Set custom targeting for the page feed URLs based on a list of labels. - - Args: - client: an AdWordsClient instance. - ad_group_id: a str AdGroup ID. - label_name: a str label name. - - Returns: - A suds.sudsobject.Object representing the newly created webpage criterion. - """ - # Get the AdGroupCriterionService. - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201802') - - # Create the operation. - operation = { - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Test criterion', - # Add a condition for label=specified_label_name. - 'conditions': [{ - 'operand': 'CUSTOM_LABEL', - 'argument': label_name - }], - } - }, - # Set a custom bid for this criterion - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 1500000 - } - }] - } - }, - 'operator': 'ADD' - } - - criterion = ad_group_criterion_service.mutate([operation])['value'][0] - print 'Web page criterion with ID "%d" and status "%s" was created.' % ( - criterion['criterion']['id'], criterion['userStatus']) - return criterion - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py deleted file mode 100755 index 439c7ba7..00000000 --- a/examples/adwords/v201802/advanced_operations/add_dynamic_search_ads_campaign.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Dynamic Search Ads campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - budget = _CreateBudget(client) - campaign_id = _CreateCampaign(client, budget) - ad_group_id = _CreateAdGroup(client, campaign_id) - _CreateExpandedDSA(client, ad_group_id) - _AddWebPageCriteria(client, ad_group_id) - - print 'Dynamic Search Ads campaign setup is complete.' - - -def _CreateBudget(client): - """Creates the budget. - - Args: - client: an AdWordsClient instance. - - Returns: - a suds.sudsobject.Object representation of the created budget. - """ - budget_service = client.GetService('BudgetService', version='v201802') - - # Create the campaign budget - operation = { - 'operand': { - 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), - 'deliveryMethod': 'STANDARD', - 'amount': { - 'microAmount': 500000 - } - }, - 'operator': 'ADD' - } - - budget = budget_service.mutate([operation])['value'][0] - - print 'Budget with ID "%d" and name "%s" was created.' % ( - budget['budgetId'], budget['name']) - - return budget - - -def _CreateCampaign(client, budget): - """Creates the campaign. - - Args: - client: an AdWordsClient instance. - budget: a suds.sudsobject.Object representation of a created budget. - - Returns: - An integer campaign ID. - """ - campaign_service = client.GetService('CampaignService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # prevent the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'budget': budget, - # Required: Set the campaign's Dynamic Search Ad settings. - 'settings': [{ - 'xsi_type': 'DynamicSearchAdsSetting', - # Required: Set the domain name and language. - 'domainName': 'example.com', - 'languageCode': 'en' - }], - # Optional: Set the start date. - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - # Optional: Set the end date. - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - }] - - campaign = campaign_service.mutate(operations)['value'][0] - campaign_id = campaign['id'] - - print 'Campaign with ID "%d" and name "%s" was added.' % ( - campaign_id, campaign['name']) - - return campaign_id - - -def _CreateAdGroup(client, campaign_id): - """Creates an ad group. - - Args: - client: an AdWordsClient instance. - campaign_id: an integer campaign ID. - - Returns: - An integer ad group ID. - """ - ad_group_service = client.GetService('AdGroupService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'adGroupType': 'SEARCH_DYNAMIC_ADS', - 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '3000000' - }, - }] - } - } - }] - - ad_group = ad_group_service.mutate(operations)['value'][0] - ad_group_id = ad_group['id'] - - print 'Ad group with ID "%d" and name "%s" was created.' % ( - ad_group_id, ad_group['name']) - - return ad_group_id - - -def _CreateExpandedDSA(client, ad_group_id): - """Creates the expanded Dynamic Search Ad. - - Args: - client: an AdwordsClient instance. - ad_group_id: an integer ID of the ad group in which the DSA is added. - """ - # Get the AdGroupAdService. - ad_group_ad_service = client.GetService('AdGroupAdService') - - # Create the operation - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - # Create the expanded dynamic search ad. This ad will have its - # headline and final URL auto-generated at serving time according to - # domain name specific information provided by DynamicSearchAdsSetting - # at the campaign level. - 'ad': { - 'xsi_type': 'ExpandedDynamicSearchAd', - # Set the ad description. - 'description': 'Buy your tickets now!' - }, - # Optional: Set the status. - 'status': 'PAUSED', - } - }] - - # Create the ad. - ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] - - # Display the results. - print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' - 'added' % (ad['id'], ad['description'])) - - -def _AddWebPageCriteria(client, ad_group_id): - """Adds a web page criterion to target Dynamic Search Ads. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID of the ad group the criteria is being added to. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201802') - - operations = [{ - 'operator': 'ADD', - # Create biddable ad group criterion. - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion for special offers for children. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Special offers for children.', - 'conditions': [ - { - 'operand': 'URL', - 'argument': '/marscruise/children' - }, - { - 'operand': 'PAGE_TITLE', - 'argument': 'Special Offer' - } - ] - } - }, - 'userStatus': 'PAUSED', - # Optional: set a custom bid. - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000L - } - }] - } - } - }] - - criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( - criterion['criterion']['id'], criterion['adGroupId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py deleted file mode 100755 index 55bc2357..00000000 --- a/examples/adwords/v201802/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Create the expanded text ad - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - expanded_text_ad['trackingUrlTemplate'] = ( - 'http://tracker.example.com/?season={_season}&promocode={_promocode}' - '&u={lpurl}' - ) - - expanded_text_ad['urlCustomParameters'] = { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': expanded_text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_gmail_ad.py b/examples/adwords/v201802/advanced_operations/add_gmail_ad.py deleted file mode 100755 index daa400de..00000000 --- a/examples/adwords/v201802/advanced_operations/add_gmail_ad.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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 code example adds a Gmail ad to a given ad group. - -The ad group's campaign needs to have an AdvertisingChannelType of DISPLAY and -AdvertisingChannelSubType of DISPLAY_GMAIL_AD. - -To get your ad groups, run get_ad_groups.py. -""" - - -# Import appropriate classes from the client library. -from googleads import adwords - - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - media_service = client.GetService('MediaService', 'v201802') - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') - opener = client.proxy_config.BuildOpener() - - try: - # This ad format doesn't allow the creation of an image using the Image.data - # field. An image must first be created using the MediaService, and an - # Image.mediaId must be populated when creating the ad. - uploaded_logo_image = _CreateImage( - media_service, opener, 'https://goo.gl/mtt54n') - uploaded_marketing_image = _CreateImage( - media_service, opener, 'http://goo.gl/3b9Wfh') - - teaser = { - 'headline': 'Dream', - 'description': 'Create your own adventure', - 'businessName': 'Interplanetary Ships', - 'logoImage': uploaded_logo_image - } - - # Creates a Gmail ad. - gmail_ad = { - 'xsi_type': 'GmailAd', - 'teaser': teaser, - 'marketingImage': uploaded_marketing_image, - 'marketingImageHeadline': 'Travel', - 'marketingImageDescription': 'Take to the skies!', - 'finalUrls': ['http://wwww.example.com'] - } - - # Creates ad group ad for the Gmail ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': gmail_ad, - # Optional: Set additional settings. - 'status': 'PAUSED' - } - - # Creates ad group ad operations. - operations = [{ - 'operator': 'ADD', - 'operand': ad_group_ad - }] - - # Adds a Gmail ad. - ad_group_ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad_group_ad in ad_group_ads['value']: - print ('A Gmail ad with id "%d" and short headline "%s" was ' - 'added.' % (ad_group_ad['ad']['id'], - ad_group_ad['ad']['teaser']['headline'])) - except Exception as e: - raise Exception('Failed to create Gmail ad: %s' % e) - - -def _CreateImage(media_service, opener, url): - """Creates an image and uploads it to the server. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - url: a str URL used to load image data. - - Returns: - The image that was successfully uploaded. - """ - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open(url).read().decode('utf-8') - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - return media_service.upload(image)[0] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_html5_ad.py b/examples/adwords/v201802/advanced_operations/add_html5_ad.py deleted file mode 100755 index d0f2810f..00000000 --- a/examples/adwords/v201802/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Create HTML5 media. - html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return response.read().decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index 1eadade0..00000000 --- a/examples/adwords/v201802/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - media_service = client.GetService('MediaService', version='v201802') - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - - try: - # Create marketing image. - marketing_image = _CreateImage(media_service, opener, - 'https://goo.gl/3b9Wfh') - - # Create square marketing image. - square_marketing_image = _CreateImage(media_service, opener, - 'https://goo.gl/mtt54n') - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': marketing_image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'], - # Optional: Set a square marketing image to the ad. - 'squareMarketingImage': { - 'mediaId': square_marketing_image['mediaId'] - }, - # Optional: Set call-to-action text. - 'callToActionText': 'Shop Now', - # Optional: Set dynamic display ad settings, composed of - # landscape logo image, promotion text, and price prefix. - 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( - media_service, opener), - # Whitelisted accounts only: Set color settings using - # hexadecimal numbers. - # Set allowFlexibleColor to False if you want your ads to render - # by always using your colors strictly. - # 'mainColor': '#0000ff', - # 'accentColor': '#ffff00', - # 'allowFlexibleColor': False - # Whitelisted accounts only: Set the format setting that the ad - # will be served in. - # 'formatSetting': 'NON_NATIVE' - - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -def _CreateImage(media_service, opener, url): - """Creates an image and uploads it to the server. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - url: a str URL used to load image data. - - Returns: - The image that was successfully uploaded. - """ - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open(url).read().decode('utf-8') - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - return media_service.upload(image)[0] - - -def _CreateDynamicDisplayAdSettings(media_service, opener): - """Creates settings for dynamic display ad. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - - Returns: - The dynamic display ad settings. - """ - image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') - - logo = { - 'type': 'IMAGE', - 'mediaId': image['mediaId'], - 'xsi_type': 'Image' - } - - dynamic_settings = { - 'landscapeLogoImage': logo, - 'pricePrefix': 'as low as', - 'promoText': 'Free shipping!', - 'xsi_type': 'DynamicSettings', - } - - return dynamic_settings - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py deleted file mode 100755 index 19b90065..00000000 --- a/examples/adwords/v201802/advanced_operations/add_shopping_dynamic_remarketing_campaign.py +++ /dev/null @@ -1,304 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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. - -"""Adds a Shopping dynamic remarketing campaign for the Display Network. - -This example steps through the following: -* Creates a new Display Network campaign. -* Links the campaign with Merchant Center. -* Links the user list to the ad group. -* Creates a responsive display ad to render the dynamic text. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - - -import uuid - -from googleads import adwords - - -MERCHANT_ID = 'INSERT_MERCHANT_CENTER_ID_HERE' -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -USER_LIST_ID = 'INSERT_USER_LIST_ID_HERE' - - -def main(client, merchant_id, budget_id, user_list_id): - opener = client.proxy_config.BuildOpener() - - campaign = CreateCampaign(client, merchant_id, budget_id) - campaign_id = campaign['id'] - print 'Campaign with name "%s" and ID "%d" was added.' % ( - campaign['name'], campaign_id) - - ad_group = CreateAdGroup(client, campaign_id) - ad_group_id = ad_group['id'] - print 'Ad group with name "%s" and ID "%d" was added.' % ( - ad_group['name'], ad_group_id) - - ad_group_ad = CreateAd(client, opener, ad_group_id) - print 'Responsive display ad with ID "%d" was added.' % ( - ad_group_ad['ad']['id']) - - AttachUserList(client, ad_group_id, user_list_id) - print 'User list with ID "%d" was attached to ad group with ID "%d".' % ( - user_list_id, ad_group_id) - - -def CreateCampaign(client, merchant_id, budget_id): - """Creates a new Display Network campaign. - - Args: - client: an AdWordsClient instance. - merchant_id: a int merchant center ID. - budget_id: a int budget ID. - - Returns: - The campaign that was successfully created. - """ - campaign_service = client.GetService('CampaignService', 'v201802') - - campaign = { - 'name': 'Shopping campaign #%d' % uuid.uuid4(), - # Dynamic remarketing campaigns are only available on the Google Display - # Network. - 'advertisingChannelType': 'DISPLAY', - 'status': 'PAUSED', - 'budget': { - 'budgetId': budget_id - }, - # This example uses a Manual CPC bidding strategy, but you should select - # the strategy that best aligns with your sales goals. More details here: - # https://support.google.com/adwords/answer/2472725 - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [{ - 'xsi_type': 'ShoppingSetting', - # Campaigns with numerically higher priorities take precedence over - # those with lower priorities. - 'campaignPriority': 0, - 'merchantId': merchant_id, - # Display network campaigns do not support partition by country. The - # only supported value is "ZZ". This signals that products from all - # countries are available in this campaign. The actual products which - # serve are based on the products tagged in the user list entry. - 'salesCountry': 'ZZ', - # Optional: Enable local inventory ads (items for sale in physical - # stores.) - 'enableLocal': True, - # Optional: Declare whether purchases are only made on the merchant - # store, or completed on Google. - 'purchasePlatform': 'MERCHANT' - }] - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - return campaign_service.mutate(operations)['value'][0] - - -def CreateAdGroup(client, campaign_id): - """Creates a dynamic remarketing campaign. - - Args: - client: an AdWordsClient instance. - campaign_id: an int campaign ID. - - Returns: - The ad group that was successfully created. - """ - ad_group_service = client.GetService('AdGroupService', 'v201802') - - ad_group = { - 'name': 'Dynamic remarketing ad group', - 'campaignId': campaign_id, - 'status': 'ENABLED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': ad_group - }] - - return ad_group_service.mutate(operations)['value'][0] - - -def CreateAd(client, opener, ad_group_id): - """Creates a ResponsiveDisplayAd. - - Args: - client: an AdWordsClient instance. - opener: an OpenerDirector instance. - ad_group_id: an int ad group ID. - - Returns: - The ad group ad that was successfully created. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') - media_service = client.GetService('MediaService', 'v201802') - - marketing_image_id = _CreateImage( - media_service, opener, 'https://goo.gl/3b9Wfh') - logo_image_id = _CreateImage(media_service, opener, 'https://goo.gl/mtt54n') - - ad = { - 'xsi_type': 'ResponsiveDisplayAd', - # This ad format doesn't allow the creation of an image using the - # Image.data field. An image must first be created using the MediaService, - # and Image.mediaId must be populated when creating the ad. - 'marketingImage': { - 'xsi_type': 'Image', - 'mediaId': marketing_image_id - }, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://wwww.example.com'], - # Optional: Call to action text. - # Valid texts: https://support.google.com/adwords/answer/7005917 - 'callToActionText': 'Apply Now', - # Optional: Set dynamic display ad settings, composed of landscape logo - # image, promotion text, and price prefix. - 'dynamicDisplayAdSettings': CreateDynamicDisplayAdSettings( - client, opener), - # Optional: Create a logo image and set it to the ad. - 'logoImage': { - 'xsi_type': 'Image', - 'mediaId': logo_image_id - }, - # Optional: Create a square marketing image and set it to the ad. - 'squareMarketingImage': { - 'xsi_type': 'Image', - 'mediaId': logo_image_id - }, - # Whitelisted accounts only: Set color settings using hexadecimal values. - # Set allowFlexibleColor to False if you want your ads to render by always - # using your colors strictly. - # 'mainColor': '#000fff', - # 'accentColor': '#fff000', - # 'allowFlexibleColor': False, - # Whitelisted accounts only: Set the format setting that the ad will be - # served in. - # 'formatSetting': 'NON_NATIVE' - } - - ad_group_ad = { - 'ad': ad, - 'adGroupId': ad_group_id - } - - operations = [{ - 'operation': 'ADD', - 'operand': ad_group_ad - }] - - return ad_group_ad_service.mutate(operations)['value'][0] - - -def AttachUserList(client, ad_group_id, user_list_id): - """Links the provided ad group and user list. - - Args: - client: an AdWordsClient instance. - ad_group_id: an int ad group ID. - user_list_id: an int user list ID. - - Returns: - The ad group criterion that was successfully created. - """ - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', 'v201802') - - user_list = { - 'xsi_type': 'CriterionUserList', - 'userListId': user_list_id - } - - ad_group_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'criterion': user_list, - 'adGroupId': ad_group_id - } - - operations = [{ - 'operator': 'ADD', - 'operand': ad_group_criterion - }] - - return ad_group_criterion_service.mutate(operations)['value'][0] - - -def CreateDynamicDisplayAdSettings(client, opener): - """Creates dynamic display ad settings. - - Args: - client: an AdWordsClient instance. - opener: an OpenerDirector instance. - - Returns: - A dict containing the dynamic display ad settings. - """ - media_service = client.GetService('MediaService', 'v201802') - - logo = { - 'xsi_type': 'Image', - 'mediaId': _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') - } - - dynamic_settings = { - 'landscapeLogoImage': logo, - 'pricePrefix': 'as low as', - 'promoText': 'Free shipping!' - } - - return dynamic_settings - - -def _CreateImage(media_service, opener, url): - """Creates an image and uploads it to the server. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - url: a str URL used to load image data. - - Returns: - The image that was successfully uploaded. - """ - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open(url).read().decode('utf-8') - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - return media_service.upload(image)[0] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, MERCHANT_ID, BUDGET_ID, USER_LIST_ID) diff --git a/examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py deleted file mode 100755 index e992b18c..00000000 --- a/examples/adwords/v201802/advanced_operations/add_universal_app_campaign.py +++ /dev/null @@ -1,218 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Universal App campaign. - -To get campaigns, run get_campaigns.py. To upload image assets for this -campaign, run upload_image.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201802') - - budget_id = CreateBudget(client) - - # Create the Universal App campaign. - universal_app_campaign = { - 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'MULTI_CHANNEL', - 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', - # Set the campaign's bidding strategy. Universal app campaigns only - # support TARGET_CPA bidding strategy. - 'biddingStrategyConfiguration': { - # Set the target CPA to $1 / app install. - 'biddingScheme': { - 'xsi_type': 'TargetCpaBiddingScheme', - 'targetCpa': { - 'microAmount': '1000000' - } - }, - 'biddingStrategyType': 'TARGET_CPA' - }, - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - - universal_app_campaign['settings'] = [ - # Set the campaign's assets and ad text ideas. These values will - # be used to generate ads. - { - 'xsi_type': 'UniversalAppCampaignSetting', - 'appId': 'com.labpixies.colordrips', - 'appVendor': 'VENDOR_GOOGLE_MARKET', - 'description1': 'A cool puzzle game', - 'description2': 'Remove connected blocks', - 'description3': '3 difficulty levels', - 'description4': '4 colorful fun skins', - # Optional: You can set up to 20 image assets for your campaign. - # See upload_image.py for an example on how to upload images. - # - # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] - } - ] - - # Optimize this campaign for getting new users for your app. - universal_app_campaign_setting = universal_app_campaign['settings'][0] - universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( - 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') - - # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, - # then also specify your in-app conversion types so AdWords can focus your - # campaign on people who are most likely to complete the corresponding in-app - # actions. - # - # Conversions type IDs can be retrieved using ConversionTrackerService.get. - # universal_app_campaign['selectiveOptimization'] = { - # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] - # } - - # Optional: Set the campaign settings for Advanced location options. - universal_app_campaign['settings'].append({ - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - }) - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': universal_app_campaign - }] - - campaigns = campaign_service.mutate(operations)['value'] - - # Display results. - if campaigns: - for campaign in campaigns: - print ('Universal App Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - # Optional: Set the campaign's location and language targeting. No other - # targeting criteria can be used for Universal App campaigns. - SetCampaignTargetingCriteria(client, campaign) - else: - print 'No Universal App campaigns were added.' - - -def CreateBudget(client): - """Creates a budget and returns its budgetId. - - Args: - client: An AdWordsClient instance. - - Returns: - An int budgetId for the created Budget. - """ - budget_service = client.GetService('BudgetService', version='v201802') - - # Create a budget. - budget = { - 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': False - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Create the budget and return its ID. - budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - - return budget_id - - -def SetCampaignTargetingCriteria(client, campaign): - """Sets targeting criteria for the given campaign. - - Args: - client: An AdWordsClient instance. - campaign: A suds object representing the campaign we wish to attach - targeting criteria. - """ - campaign_criterion_service = client.GetService('CampaignCriterionService') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - criteria = [ - { - 'xsi_type': 'Location', - 'id': 21137 # California - }, - { - 'xsi_type': 'Location', - 'id': 2484 # Mexico - }, - { - 'xsi_type': 'Language', - 'id': 1000 # English - }, - { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - ] - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign['id'], - 'criterion': criterion - } - } for criterion in criteria] - - response = campaign_criterion_service.mutate(operations) - - if response and 'value' in response: - # Display the added campaign targets. - for criterion in response['value']: - print ('Campaign criteria of type "%s" and id "%s" was added.' - % (criterion['criterion']['type'], - criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 7efcf236..00000000 --- a/examples/adwords/v201802/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201802') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201802') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201802') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index 7a91a4df..00000000 --- a/examples/adwords/v201802/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201802') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201802') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 10bca1ce..00000000 --- a/examples/adwords/v201802/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201802') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 47639262..00000000 --- a/examples/adwords/v201802/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201802') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201802') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201802') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201802/basic_operations/__init__.py b/examples/adwords/v201802/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201802/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201802/basic_operations/add_ad_groups.py b/examples/adwords/v201802/basic_operations/add_ad_groups.py deleted file mode 100755 index a56ec582..00000000 --- a/examples/adwords/v201802/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201802') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/basic_operations/add_campaigns.py b/examples/adwords/v201802/basic_operations/add_campaigns.py deleted file mode 100755 index 929d2657..00000000 --- a/examples/adwords/v201802/basic_operations/add_campaigns.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201802') - budget_service = client.GetService('BudgetService', version='v201802') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201802/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index e8963345..00000000 --- a/examples/adwords/v201802/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/add_keywords.py b/examples/adwords/v201802/basic_operations/add_keywords.py deleted file mode 100755 index 1e46a98a..00000000 --- a/examples/adwords/v201802/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201802') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id "%s", criterion id ' - '"%s", text "%s", and match type "%s" was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/get_ad_groups.py b/examples/adwords/v201802/basic_operations/get_ad_groups.py deleted file mode 100755 index f2fda1ba..00000000 --- a/examples/adwords/v201802/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201802') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name "%s", id "%s" and status "%s" was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/basic_operations/get_campaigns.py b/examples/adwords/v201802/basic_operations/get_campaigns.py deleted file mode 100755 index a4169de6..00000000 --- a/examples/adwords/v201802/basic_operations/get_campaigns.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201802') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 7220e6f0..00000000 --- a/examples/adwords/v201802/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201802') - - # Construct query and get all campaigns. - query = (adwords.ServiceQueryBuilder() - .Select('Id', 'Name', 'Status') - .Where('Status').EqualTo('ENABLED') - .OrderBy('Name') - .Limit(0, PAGE_SIZE) - .Build()) - - for page in query.Pager(campaign_service): - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201802/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index 64e656d5..00000000 --- a/examples/adwords/v201802/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/get_keywords.py b/examples/adwords/v201802/basic_operations/get_keywords.py deleted file mode 100755 index 012ab9c3..00000000 --- a/examples/adwords/v201802/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201802') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID "%s", type "%s", text "%s", and match type ' - '"%s" was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/pause_ad.py b/examples/adwords/v201802/basic_operations/pause_ad.py deleted file mode 100755 index d9c00409..00000000 --- a/examples/adwords/v201802/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id "%s" was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201802/basic_operations/remove_ad.py b/examples/adwords/v201802/basic_operations/remove_ad.py deleted file mode 100755 index 7eb35a05..00000000 --- a/examples/adwords/v201802/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id "%s" and type "%s" was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201802/basic_operations/remove_ad_group.py b/examples/adwords/v201802/basic_operations/remove_ad_group.py deleted file mode 100755 index 7d82f4ef..00000000 --- a/examples/adwords/v201802/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201802') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name "%s" and id "%s" was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/basic_operations/remove_campaign.py b/examples/adwords/v201802/basic_operations/remove_campaign.py deleted file mode 100755 index b4a55598..00000000 --- a/examples/adwords/v201802/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201802') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name "%s" and id "%s" was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/basic_operations/remove_keyword.py b/examples/adwords/v201802/basic_operations/remove_keyword.py deleted file mode 100755 index 63ee1239..00000000 --- a/examples/adwords/v201802/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201802') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id "%s", criterion id "%s", ' - 'and type "%s" was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201802/basic_operations/update_ad_group.py b/examples/adwords/v201802/basic_operations/update_ad_group.py deleted file mode 100755 index 7f06c46c..00000000 --- a/examples/adwords/v201802/basic_operations/update_ad_group.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the CPC bid and status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' - - -def main(client, ad_group_id, bid_micro_amount=None): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201802') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - - if bid_micro_amount: - operations[0]['operand']['biddingStrategyConfiguration'] = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': bid_micro_amount, - } - }] - } - - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] - # Find the CpcBid in the bidding strategy configuration's bids collection. - cpc_bid_micros = None - - if bidding_strategy_configuration: - bids = bidding_strategy_configuration['bids'] - - if bids: - for bid in bids: - if bid['Bids.Type'] == 'CpcBid': - cpc_bid_micros = bid['bid']['microAmount'] - break - - print ('Ad group with name "%s", and id "%s" was updated to have status ' - '"%s" and CPC bid %d.' - % (ad_group['name'], ad_group['id'], ad_group['status'], - cpc_bid_micros)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201802/basic_operations/update_campaign.py b/examples/adwords/v201802/basic_operations/update_campaign.py deleted file mode 100755 index 70bd4546..00000000 --- a/examples/adwords/v201802/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201802') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/basic_operations/update_keyword.py b/examples/adwords/v201802/basic_operations/update_keyword.py deleted file mode 100755 index fd0527bb..00000000 --- a/examples/adwords/v201802/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201802') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id "%s" and criterion id ' - '"%s" currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: "%s", value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201802/campaign_management/__init__.py b/examples/adwords/v201802/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201802/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py deleted file mode 100755 index 9576a872..00000000 --- a/examples/adwords/v201802/campaign_management/add_campaign_groups_and_performance_targets.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a campaign group and sets a performance target for it. - -To get campaigns, run get_campaigns.py. To download reports, run -download_criteria_report_with_awql.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id1, campaign_id2): - campaign_group_id = _CreateCampaignGroup(client) - _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) - _CreatePerformanceTarget(client, campaign_group_id) - print 'Campaign group and its performance target were setup successfully.' - - -def _CreateCampaignGroup(client): - """Create a campaign group. - - Args: - client: an AdWordsClient instance. - - Returns: - The integer ID of the created campaign group. - """ - # Get the CampaignGroupService. - campaign_group_service = client.GetService('CampaignGroupService', - version='v201802') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the campaign group. - 'operand': { - 'name': 'Mars campaign group #%d' % uuid.uuid4() - } - }] - - campaign_group = campaign_group_service.mutate(operations)['value'][0] - campaign_group_id = campaign_group['id'] - - # Display the results. - print 'Campaign group with ID "%d" and name "%s" was created.' % ( - campaign_group_id, campaign_group['name']) - - return campaign_group_id - - -def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): - """Adds multiple campaigns to a campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - campaign_ids: a list of integer IDs for campaigns. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201802') - - # Create the operations. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'campaignGroupId': campaign_group_id - } - } for campaign_id in campaign_ids] - - campaign_service.mutate(operations) - - # Display the results. - print ('The following campaign IDs were added to the campaign group with ID ' - '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) - - -def _CreatePerformanceTarget(client, campaign_group_id): - """Creates a performance target for the campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - """ - # Get the CampaignGroupPerformanceTargetService. - cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', - version='v201802') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the performance target. - 'operand': { - 'campaignGroupId': campaign_group_id, - 'performanceTarget': { - # Keep the CPC for the campaigns < $3. - 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', - 'efficiencyTargetValue': 3000000, - # Keep the maximum spend under $50. - 'spendTargetType': 'MAXIMUM', - 'spendTarget': { - 'microAmount': 500000000 - }, - # Aim for at least 3000 clicks. - 'volumeGoalType': 'MAXIMIZE_CLICKS', - 'volumeTargetValue': 3000, - # Start the performance target today, and run it for the next 90 - # days. - 'startDate': datetime.datetime.now().strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(90)).strftime('%Y%m%d') - } - } - }] - - cgpt = cgpt_service.mutate(operations)['value'][0] - - # Display the results. - print ('Campaign performance target with ID "%d" was added for campaign ' - 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201802/campaign_management/add_campaign_labels.py b/examples/adwords/v201802/campaign_management/add_campaign_labels.py deleted file mode 100755 index 0b59df85..00000000 --- a/examples/adwords/v201802/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201802') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index 0cc20483..00000000 --- a/examples/adwords/v201802/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,428 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201802') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201802') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding an ExpandedTextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new ExpandedTextAd for - each of the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once - # you've added targeting and the ads are ready to serve. - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201802') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201802/campaign_management/add_draft.py b/examples/adwords/v201802/campaign_management/add_draft.py deleted file mode 100755 index afeef760..00000000 --- a/examples/adwords/v201802/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201802') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201802') - - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index 6e8eb880..00000000 --- a/examples/adwords/v201802/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to incrementally upload keywords. - -Uses the BatchJobService and BatchJobHelper to incrementally upload operations. -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201802') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201802') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201802') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201802') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/campaign_management/add_trial.py b/examples/adwords/v201802/campaign_management/add_trial.py deleted file mode 100755 index 931a66ee..00000000 --- a/examples/adwords/v201802/campaign_management/add_trial.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201802') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201802') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index cfb8ef3f..00000000 --- a/examples/adwords/v201802/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'PolicySummary'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CombinedApprovalStatus', - 'operator': 'EQUALS', - 'values': 'DISAPPROVED' - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - disapproved_count = 0 - - # Display results. - while more_pages: - page = ad_group_ad_service.get(selector) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % ad['ad']['id']) - # Display the policy topic entries related to the ad disapproval. - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName'], - policy_topic_entry['policyTopicHelpCenterUrl']) - # Display the attributes and values that triggered the policy topic. - policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] - if policy_topic_evidences: - for evidence in policy_topic_entry['policyTopicEvidences']: - print (' evidence type: %s' - % evidence['policyTopicEvidenceType']) - evidence_text_list = evidence['evidenceTextList'] - if evidence_text_list: - for index, evidence_text in enumerate(evidence_text_list): - print ' evidence text[%d]: %s' % (index, evidence_text) - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index ba8ab982..00000000 --- a/examples/adwords/v201802/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', - version='v201802') - - # Construct query and get all ads for a given campaign. - query = (adwords.ServiceQueryBuilder() - .Select('Id', 'PolicySummary') - .Where('AdGroupId').EqualTo(ad_group_id) - .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') - .OrderBy('Id') - .Limit(0, PAGE_SIZE) - .Build()) - disapproved_count = 0 - - # Display results. - while True: - page = ad_group_ad_service.query(query) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % ad['ad']['id']) - # Display the policy topic entries related to the ad disapproval. - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName']) - # Display the attributes and values that triggered the policy topic. - if ('policyTopicEvidences' in policy_topic_entry - and policy_topic_entry['policyTopicEvidences']): - for evidence in policy_topic_entry['policyTopicEvidences']: - print (' evidence type: %s' - % evidence['policyTopicEvidenceType']) - evidence_text_list = evidence['evidenceTextList'] - if evidence_text_list: - for index, evidence_text in enumerate(evidence_text_list): - print ' evidence text[%d]: %s' % (index, evidence_text) - - if not query.HasNext(page): - break - query.NextPage() - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201802/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 37deb3d7..00000000 --- a/examples/adwords/v201802/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201802') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id "%s", name "%s", and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201802/campaign_management/graduate_trial.py b/examples/adwords/v201802/campaign_management/graduate_trial.py deleted file mode 100755 index 970eaf3e..00000000 --- a/examples/adwords/v201802/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201802') - budget_service = client.GetService('BudgetService', version='v201802') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201802/campaign_management/set_ad_parameters.py b/examples/adwords/v201802/campaign_management/set_ad_parameters.py deleted file mode 100755 index 4c44ff29..00000000 --- a/examples/adwords/v201802/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - ad_param_service = client.GetService('AdParamService', version='v201802') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id "%s" was successfully added to an ad group with ' - 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text "%s" was successfully set for criterion ' - 'with id "%s" and ad group id "%s".' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index 0fb52250..00000000 --- a/examples/adwords/v201802/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201802') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' - 'was updated with bid modifier "%s".' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201802/campaign_management/validate_text_ad.py b/examples/adwords/v201802/campaign_management/validate_text_ad.py deleted file mode 100755 index 904392e8..00000000 --- a/examples/adwords/v201802/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -No objects will be created, but exceptions will still be returned. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords -from googleads import errors - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Construct operations to add an expanded text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'] - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for all astronauts in orbit', - 'finalUrls': ['http://www.example.com'], - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except errors.GoogleAdsServerFault, e: - print 'Validation correctly failed with "%s".' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/error_handling/__init__.py b/examples/adwords/v201802/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201802/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201802/error_handling/handle_partial_failures.py b/examples/adwords/v201802/error_handling/handle_partial_failures.py deleted file mode 100755 index cdcad6b6..00000000 --- a/examples/adwords/v201802/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201802') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id "%s", ' - 'criterion id "%s", text "%s", and match type "%s" was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - if (first_field_path_element and - first_field_path_element['field'] == 'operations' and - 'index' in first_field_path_element): - operation_index = first_field_path_element['index'] - - adgroup_criterion = operations[operation_index]['operand'] - - print('Ad group criterion with ad group ID %s and keyword "%s" triggered ' - 'a failure for the following reason: %s.' - % (adgroup_criterion['adGroupId'], - adgroup_criterion['criterion']['text'], - error['errorString'])) - else: - print ('A failure has occurred for the following reasons: %s\n' - % error['errorString']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/error_handling/handle_policy_violation_error.py b/examples/adwords/v201802/error_handling/handle_policy_violation_error.py deleted file mode 100755 index b13a2263..00000000 --- a/examples/adwords/v201802/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - - -from googleads import adwords -from googleads import errors - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') - - # Create expanded text ad that violates an exemptable policy. - exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise!!!', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - # Create text ad that violates a non-exemptable policy. - non_exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise with too long of a headline.', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - operations = [exemptable_expanded_text_ad_operation, - non_exemptable_expanded_text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except errors.GoogleAdsServerFault, e: - for error in e.errors: - # Get the index of the failed operation from the error's field path - # elements. - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - # If the operation index is not present on the first error field path - # element, then there's no way to determine which operation to remove, - # so simply throw the exception. - if (not (first_field_path_element - and first_field_path_element['field'] == 'operations' - and 'index' in first_field_path_element)): - raise e - - index = long(first_field_path_element['index']) - operation = operations[index] - if not HandleAPIError(error, operation): - # Set non-exemptable operation to None to mark for deletion. - print ('Removing operation with non-exemptable error at index %s.' - % index) - operations[index] = None - - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is "%s".' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -def HandleAPIError(error, operation): - """Makes an exemption for exemptable PolicyViolationErrors. - - Args: - error: the error associated with the given operation. - operation: the operation associated with the given error. - - Returns: - A boolean that is True if the given error was an exemptable - PolicyViolationError; otherwise, returns False. - """ - is_exemptable = False - - # Determine if the operation can be resubmitted with an exemption request. - if error['ApiError.Type'] == 'PolicyViolationError': - expanded_text_ad = operation['operand']['ad'] - is_exemptable = (error['isExemptable'] if 'isExemptable' in error else - False) - print ('Ad with headline "%s - %s" violated %s policy "%s".' % - (expanded_text_ad['headlinePart1'], - expanded_text_ad['headlinePart2'], - 'exemptable' if is_exemptable else 'non-exemptable', - error['externalPolicyName'])) - - if is_exemptable: - # Add exemption request to the operation. - print ('Adding exemption request for policy name "%s" on text "%s".' - % (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({'key': error['key']}) - - return is_exemptable - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/extensions/__init__.py b/examples/adwords/v201802/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201802/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index c152f6da..00000000 --- a/examples/adwords/v201802/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201802').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201802') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except errors.GoogleAdsServerFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201802/extensions/add_prices.py b/examples/adwords/v201802/extensions/add_prices.py deleted file mode 100755 index 9d77294d..00000000 --- a/examples/adwords/v201802/extensions/add_prices.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a price extension and associates it with an account. - -Campaign targeting is also set usin the specified campaign ID. To get campaigns, -run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -MICROS_PER_DOLLAR = 1000000 - - -def main(client, campaign_id): - # Initialize appropriate service. - customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201802') - - # To create a price extension, at least three table rows are needed. - table_rows = [ - CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', - 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', - final_mobile_url='http://m.example.com/scrubs'), - CreatePriceTableRow('Hair Cuts', 'Once a month', - 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url='http://m.example.com/haircuts'), - CreatePriceTableRow('Skin Care Package', 'Four times a month', - 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url=( - 'http://m.example.com/skincarepackage')) - ] - - # Create the price extension feed item. - customer_extension_setting = { - 'extensionType': 'PRICE', - 'extensionSetting': { - 'extensions': [{ - 'priceExtensionType': 'SERVICES', - 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', - 'language': 'en', - 'campaignTargeting': { - 'TargetingCampaignId': campaign_id - }, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': 'SATURDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 22, - 'endMinute': 'ZERO' - }, - { - 'dayOfWeek': 'SUNDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 18, - 'endMinute': 'ZERO' - } - ] - }, - 'tableRows': table_rows, - # Price qualifier is optional. - 'priceQualifier': 'FROM', - 'xsi_type': 'PriceFeedItem' - }] - } - } - - # Create an operation to add the feed. - operations = [{ - 'operator': 'ADD', - 'operand': customer_extension_setting - }] - - # Add the price extension. - response = customer_extension_setting_service.mutate(operations) - - # Print the results. - if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit, final_mobile_url=None): - """Helper function to generate a single row of a price table. - - Args: - header: A str containing the header text of this row. - description: A str description of this row in the price table. - final_url: A str containing the final URL after all cross domain redirects. - price_in_micros: An int indicating the price of the given currency in - micros. - currency_code: A str indicating the currency code being used. - price_unit: A str enum indicating the price unit for this row. - final_mobile_url: A str containing the final mobile URL after all cross - domain redirects. - - Returns: - A dictionary containing the contents of the generated price table row. - """ - table_row = { - 'header': header, - 'description': description, - 'finalUrls': {'urls': [final_url]}, - 'price': { - 'money': { - 'microAmount': price_in_micros, - }, - 'currencyCode': currency_code - }, - 'priceUnit': price_unit, - 'xsi_type': 'PriceTableRow' - } - - if final_mobile_url: - table_row['finalMobileUrls'] = { - 'urls': [final_mobile_url] - } - - return table_row - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/extensions/add_site_links.py b/examples/adwords/v201802/extensions/add_site_links.py deleted file mode 100755 index 2a13cbcb..00000000 --- a/examples/adwords/v201802/extensions/add_site_links.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201802') - customer_service = client.GetService('CustomerService', version='v201802') - # Find the matching customer and its time zone. The getCustomers method will - # return a single Customer object corresponding to the configured - # clientCustomerId. - customer = customer_service.getCustomers()[0] - customer_tz = timezone(customer['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840}, - # Restrict targeting only to people physically within the United States. - # Otherwise, this could also show to people interested in the United - # States, but not physically located there. - 'geoTargetingRestriction': { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/extensions/add_site_links_using_feeds.py b/examples/adwords/v201802/extensions/add_site_links_using_feeds.py deleted file mode 100755 index b4d07fdd..00000000 --- a/examples/adwords/v201802/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,265 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_2_TEXT = '3' -PLACEHOLDER_FIELD_LINE_3_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Optional: Ad group to restrict targeting to. -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, campaign_id, ad_group_id=None): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201802') - feed_item_service = client.GetService('FeedItemService', version='v201802') - feed_item_target_service = client.GetService('FeedItemTargetService', - version='v201802') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201802') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201802') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 2 Description'}, - {'type': 'STRING', 'name': 'Line 3 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_2_feed_attribute_id = feed['attributes'][2]['id'] - line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name "%s" and ID "%s" was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID "%s" and Final URL attribute ID "%s".' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID "%s" and Line 3 attribute ID "%s".' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - sitelinks_data['line3FeedId'] = line_3_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line2': 'Home line 2', 'line3': 'Home line 3'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line2': 'Support line 2', 'line3': 'Support line 3'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line2': 'Products line 2', 'line3': 'Products line 3'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line2': 'About line 2', 'line3': 'About line 3', 'locationId': '21137'} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'stringValue': item['line3'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Use geographical targeting on a feed. - # The IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - if 'locationId' in item: - feed_item['geoTargeting'] = { - 'id': item['locationId'] - } - feed_item['geoTargetingRestriction'] = { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %s was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %s and placeholder type %s was saved for feed' - ' with ID %s.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %s was associated with feed with ID %s.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - # Optional: Restrict the first feed item to only serve with ads for the - # specified ad group ID. - if ad_group_id: - feed_item_target = { - 'xsi_type': 'FeedItemAdGroupTarget', - 'feedId': sitelinks_data['feedId'], - 'feedItemId': sitelinks_data['feedItemIds'][0], - 'adGroupId': ad_group_id - } - - operations = [{ - 'operator': 'ADD', - 'operand': feed_item_target - }] - - response = feed_item_target_service.mutate(operations) - - if 'value' in response: - print ('Feed item target for feed ID "%d" and feed item ID "%d" was ' - 'created to restrict serving to ad group ID "%d".' - % (feed_item_target['feedId'], feed_item_target['feedItemId'], - feed_item_target['adGroupId'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - if AD_GROUP_ID == 'INSERT_AD_GROUP_ID_HERE': - main(adwords_client, CAMPAIGN_ID) - else: - main(adwords_client, CAMPAIGN_ID, ad_group_id=AD_GROUP_ID) diff --git a/examples/adwords/v201802/migration/__init__.py b/examples/adwords/v201802/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201802/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201802/migration/migrate_to_extension_settings.py b/examples/adwords/v201802/migration/migrate_to_extension_settings.py deleted file mode 100755 index 3dbb69ff..00000000 --- a/examples/adwords/v201802/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,526 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201802') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - 'scheduling': site_link_from_feed['scheduling'] - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201802') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201802') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201802') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201802') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201802') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues', 'Scheduling'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201802') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - if 'scheduling' in feed_item: - site_link_from_feed['scheduling'] = feed_item['scheduling'] - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/misc/__init__.py b/examples/adwords/v201802/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201802/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201802/misc/get_all_images_and_videos.py b/examples/adwords/v201802/misc/get_all_images_and_videos.py deleted file mode 100755 index 294477ef..00000000 --- a/examples/adwords/v201802/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201802') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id "%s" was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/misc/upload_image.py b/examples/adwords/v201802/misc/upload_image.py deleted file mode 100755 index afbdc996..00000000 --- a/examples/adwords/v201802/misc/upload_image.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201802') - - with open(image_filename, 'rb') as image_handle: - image_data = image_handle.read().decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201802/misc/upload_media_bundle.py b/examples/adwords/v201802/misc/upload_media_bundle.py deleted file mode 100755 index 74ec7032..00000000 --- a/examples/adwords/v201802/misc/upload_media_bundle.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201802') - # Create HTML5 media. - html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return response.read().decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/optimization/__init__.py b/examples/adwords/v201802/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201802/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201802/optimization/estimate_keyword_traffic.py b/examples/adwords/v201802/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 1d9575ac..00000000 --- a/examples/adwords/v201802/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201802') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate - and min_estimate['averageCpc'] else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate - and min_estimate['averagePosition'] else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index ec07bb79..00000000 --- a/examples/adwords/v201802/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201802') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page, - # NOT the number of entries (bid landscapes) in the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = num_landscape_points >= PAGE_SIZE - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201802/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index edc2c8f3..00000000 --- a/examples/adwords/v201802/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201802') - - # Construct bid landscape selector object and retrieve bid landscape. - selector = { - 'fields': ['AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'BiddableConversions', 'BiddableConversionsValue', - 'LocalClicks', 'LocalCost', 'LocalImpressions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CriterionId', - 'operator': 'EQUALS', - 'values': [criterion_id] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages: - num_landscape_points = 0 - page = data_service.getCriterionBidLandscape(selector) - - if page and 'entries' in page: - entries = page['entries'] - print 'Bid landscape(s) retrieved: %d.' % len(entries) - - for bid_landscape in entries: - print ('Retrieved keyword bid landscape with ad group ID "%d", ' - 'keyword ID "%d", start date "%s", end date "%s", ' - 'with landscape points:' % ( - bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - num_landscape_points += 1 - print (' bid: %s => clicks: %s, cost: %s, impressions: %s, ' - 'biddable conversions: %.2f, ' - 'biddable conversions value: %.2f' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'], - bid_landscape_point['biddableConversions'], - bid_landscape_point['biddableConversionsValue'])) - - # Need to increment by the total # of landscape points within the page, - # NOT the number of entries (bid landscapes) in the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = num_landscape_points >= PAGE_SIZE - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201802/optimization/get_keyword_ideas.py b/examples/adwords/v201802/optimization/get_keyword_ideas.py deleted file mode 100755 index d2e42701..00000000 --- a/examples/adwords/v201802/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id=None): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201802') - - # Construct selector object and retrieve related keywords. - selector = { - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS' - } - - selector['requestedAttributeTypes'] = [ - 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] - - offset = 0 - selector['paging'] = { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - - selector['searchParameters'] = [{ - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }] - - # Language setting (optional). - selector['searchParameters'].append({ - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }) - - # Network search parameter (optional) - selector['searchParameters'].append({ - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - }) - - # Use an existing ad group to generate ideas (optional) - if ad_group_id is not None: - selector['searchParameters'].append({ - 'xsi_type': 'SeedAdGroupIdSearchParameter', - 'adGroupId': ad_group_id - }) - - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr( - attribute['value'], 'value', '0') - print ('Keyword with "%s" text and average monthly search volume ' - '"%s" was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201802/remarketing/__init__.py b/examples/adwords/v201802/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201802/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201802/remarketing/add_audience.py b/examples/adwords/v201802/remarketing/add_audience.py deleted file mode 100755 index 2d5de75e..00000000 --- a/examples/adwords/v201802/remarketing/add_audience.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201802') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201802') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - user_list_result = user_list_service.mutate(operations) - - # Capture the ID(s) of the conversion. - if 'value' in user_list_result: - conversion_ids = [] - for user_list in user_list_result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - # Create query. - query = (adwords.ServiceQueryBuilder() - .Select('Id', 'GoogleGlobalSiteTag', 'GoogleEventSnippet') - .Where('Id').In(*conversion_ids) - .Limit(0, PAGE_SIZE) - .Build()) - - conversions_map = {} - - # Get all conversion trackers. - for page in query.Pager(conversion_tracker_service): - if 'entries' in page: - for conversion_tracker in page['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in user_list_result['value']: - print ('User list with name "%s" and ID "%s" was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Google global site tag:\n%s\n\n' - % conversion_tracker['googleGlobalSiteTag']) - print ('Google event snippet:\n%s\n\n' - % conversion_tracker['googleEventSnippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/add_conversion_tracker.py b/examples/adwords/v201802/remarketing/add_conversion_tracker.py deleted file mode 100755 index a15199c6..00000000 --- a/examples/adwords/v201802/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201802') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s"\n was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/add_conversion_trackers.py b/examples/adwords/v201802/remarketing/add_conversion_trackers.py deleted file mode 100755 index 5e96e8c8..00000000 --- a/examples/adwords/v201802/remarketing/add_conversion_trackers.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds AdWords conversion trackers. - -Adds an AdWords conversion tracker and an upload conversion tracker. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201802') - - # Create an AdWords conversion tracker. - adwords_conversion_tracker = { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'name': 'Upload Conversion #%s' % uuid.uuid4(), - # Optional fields. - # Set an appropriate category. This will be set to DEFAULT if not - # specified. - 'category': 'LEAD', - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90', - # Set the default currency code to use for conversions that do - # not specify a conversion currency. This must be an ISO 4217 3-character - # code such as "EUR" or "USD". - # If this field is not set, AdWords will use the account's currency. - 'defaultRevenueCurrencyCode': 'EUR', - # Set the default revenue value to use for conversions that do not specify - # a converison value. Note that this value should NOT be in micros. - 'defaultRevenueValue': '2.50', - # To upload fractional conversion credits, mark the upload conversion as - # externally attributed. To learn more about importing externally - # attributed conversions, see: - # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions - # 'isExternallyAttributed': 'true' - } - - # Construct operations. - operations = [{ - 'operator': 'ADD', - 'operand': conversion_tracker - } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] - - # Add the conversions. - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion with ID "%d", name "%s", status "%s", and category ' - '"%s" was added.' - % (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'])) - if (conversion_tracker['ConversionTracker.Type'] - == 'AdWordsConversionTracker'): - print ('Google global site tag:\n%s\n\n' - % conversion_tracker['googleGlobalSiteTag']) - print ('Google event snippet:\n%s\n\n' - % conversion_tracker['googleEventSnippet']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/add_crm_based_user_list.py b/examples/adwords/v201802/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 4ca088c6..00000000 --- a/examples/adwords/v201802/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201802') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # CRM-based user lists can use a membershipLifeSpan of 10000 to indicate - # unlimited; otherwise normal values apply. - 'membershipLifeSpan': 30, - 'uploadKeyType': 'CONTACT_INFO' - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - - emails = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] - - # Add address info. - members.append({ - 'addressInfo': { - # First and last name must be normalized and hashed. - 'hashedFirstName': NormalizeAndSHA256('John'), - 'hashedLastName': NormalizeAndSHA256('Doe'), - # Country code and zip code are sent in plaintext. - 'countryCode': 'US', - 'zipCode': '10001' - } - }) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'membersList': members - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def NormalizeAndSHA256(s): - """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. - - Args: - s: The string to perform this operation on. - - Returns: - A normalized and SHA-256 hashed string. - """ - return hashlib.sha256(s.strip().lower()).hexdigest() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201802/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index d291310e..00000000 --- a/examples/adwords/v201802/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201802') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords knows how to apply the - # rules. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ], - # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF - # means 'at least one item in each rule item group must match', and DNF - # means 'at least one entire rule item group must match'. - # DateSpecificRuleUserList only supports DNF. You can also omit the rule - # type altogether to default to DNF. - 'ruleType': 'DNF' - } - - # Third and fourth rule item groups. - # Visitors of a page who visited another page. - site1_rule_item = { - 'StringRuleItem': { - 'key': {'name': 'url__'}, - 'op': 'EQUALS', - 'value': 'example.com/example1' - } - } - site2_rule_item = { - 'StringRuleItem': { - 'key': {'name': 'url__'}, - 'op': 'EQUALS', - 'value': 'example.com/example2' - } - } - - # Create two rules to show that a visitor browsed two sites. - user_visited_site1_rule = { - 'groups': [{ - 'items': [site1_rule_item] - }] - } - - user_visited_site2_rule = { - 'groups': [{ - 'items': [site2_rule_item] - }] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule, - # Optional: Set the populationStatus to REQUESTED to include past users in - # the user list. - 'prepopulationStatus': 'REQUESTED' - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create the user list for "Visitors of a page who did visit another page". - # To create a user list for "Visitors of a page who did not visit another - # page", change the ruleOperator from AND to AND_NOT. - combined_user_list = { - 'xsi_type': 'CombinedRuleUserList', - 'name': 'Combined rule user lst create at ${creation_time}', - 'description': 'Users who visited two sites.', - 'leftOperand': user_visited_site1_rule, - 'rightOperand': user_visited_site2_rule, - 'ruleOperator': 'AND' - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list, - combined_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201802/remarketing/upload_offline_call_conversions.py deleted file mode 100755 index 4321e895..00000000 --- a/examples/adwords/v201802/remarketing/upload_offline_call_conversions.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for calls related to ads in your account. - -To set up a conversion tracker, run the add_conversion_trackers.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CALLER_ID = 'INSERT_CALLER_ID_HERE' -# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats -# For time zones, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -CALL_START_TIME = 'INSERT_CALL_START_TIME' -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, caller_id, call_start_time, conversion_name, conversion_time, - conversion_value): - # Initialize appropriate services. - occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201802') - - # Associate offline call conversions with the existing named conversion - # tracker. If this tracker was newly created, it may be a few hours before it - # can accept conversions. - feed = { - 'callerId': caller_id, - 'callStartTime': call_start_time, - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - } - - occ_operations = [{'operator': 'ADD', 'operand': feed}] - - occ_response = occ_feed_service.mutate(occ_operations) - values = occ_response['value'] - - if values: - for occ_feed in values: - print ('Uploaded offline call conversion value of "%s" for caller ID ' - '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) - else: - print 'No offline call conversions were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, - CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201802/remarketing/upload_offline_conversions.py b/examples/adwords/v201802/remarketing/upload_offline_conversions.py deleted file mode 100755 index 3d84c0c4..00000000 --- a/examples/adwords/v201802/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_trackers.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201802') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id, - # Optional: To upload fractional conversion credits, set the external - # attribution model and credit. To use this feature, your conversion - # tracker should be marked as externally attributed. To learn more about - # importing externally attributed conversins, see: - # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions - # 'externalAttributionCredit': 0.3, - # 'externalAttributionModel': 'Linear' - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of "%s" for Google Click ID ' - '"%s" to "%s".' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201802/remarketing/upload_offline_data.py b/examples/adwords/v201802/remarketing/upload_offline_data.py deleted file mode 100755 index 6f834e3e..00000000 --- a/examples/adwords/v201802/remarketing/upload_offline_data.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 shows how to upload offline data for store sales transactions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import datetime -import hashlib - -from googleads import adwords -import pytz - - -_DT_FORMAT = '%Y%m%d %H%M%S' -# User identifier types whose values must be hashed. -_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', - 'HASHED_LAST_NAME', 'HASHED_PHONE') -# The timezone to be used in this example. For valid timezone IDs, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -_TIMEZONE = pytz.timezone('America/New_York') -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Insert email addresses below for creating user identifiers. -EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] -# The external upload ID can be any number that you use to keep track of your -# uploads. -EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' -# Store sales upload common metadata types -METADATA_TYPE_1P = 'FirstPartyUploadMetadata' -METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' -# Set the below constant to METADATA_TYPE_3P if uploading third-party data. -STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P -# The three constants below are needed when uploading third-party data. They -# are not used when uploading first-party data. -# Advertiser upload time to partner. -# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, -# see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' -# Indicates the version of the bridge map. -BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' -# The ID of the third party uploading the transaction feed. -PARTNER_ID = 'INSERT_PARTNER_ID_HERE' - - -def main(client, conversion_name, external_upload_id, - store_sales_upload_common_metadata_type, email_addresses, - advertiser_upload_time=None, bridge_map_version_id=None, - partner_id=None): - # Set partial failure to True since this example demonstrates how to handle - # partial errors. - client.partial_failure = True - # Initialize appropriate services. - offline_data_upload_service = client.GetService( - 'OfflineDataUploadService', version='v201802') - - # Create the first offline data for upload. - # This transaction occurred 7 days ago with an amount of $200 USD. - transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - - datetime.timedelta(days=7)) - offline_data_1 = { - 'StoreSalesTransaction': { - 'userIdentifiers': [ - _CreateUserIdentifier(identifier_type='HASHED_EMAIL', - value=email_addresses[0]), - _CreateUserIdentifier(identifier_type='STATE', value='New York') - ], - 'transactionTime': _GetFormattedDateTime(transaction_time_1), - 'transactionAmount': { - 'currencyCode': 'USD', - 'money': { - 'microAmount': 200000000 - } - }, - 'conversionName': conversion_name - } - } - - # Create the second offline data for upload. - # This transaction occurred 14 days ago with amount of 450 EUR. - transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - - datetime.timedelta(days=14)) - offline_data_2 = { - 'StoreSalesTransaction': { - 'userIdentifiers': [ - _CreateUserIdentifier(identifier_type='HASHED_EMAIL', - value=email_addresses[1]), - _CreateUserIdentifier(identifier_type='STATE', value='California') - ], - 'transactionTime': _GetFormattedDateTime(transaction_time_2), - 'transactionAmount': { - 'currencyCode': 'EUR', - 'money': { - 'microAmount': 450000000 - } - }, - 'conversionName': conversion_name - } - } - - # Set the type and metadata of this upload. - upload_metadata = { - 'StoreSalesUploadCommonMetadata': { - 'xsi_type': store_sales_upload_common_metadata_type, - 'loyaltyRate': 1.0, - 'transactionUploadRate': 1.0, - } - } - - if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: - upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' - elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: - upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' - upload_metadata['StoreSalesUploadCommonMetadata'].update({ - 'advertiserUploadTime': advertiser_upload_time, - 'validTransactionRate': 1.0, - 'partnerMatchRate': 1.0, - 'partnerUploadRate': 1.0, - 'bridgeMapVersionId': bridge_map_version_id, - 'partnerId': partner_id - }) - else: - raise ValueError('Unknown metadata type.') - - # Create offline data upload - offline_data_upload = { - 'externalUploadId': external_upload_id, - 'offlineDataList': [offline_data_1, offline_data_2], - # Set the type of this upload. - 'uploadType': upload_type, - 'uploadMetadata': upload_metadata - } - - # Create an offline data upload operation. - operations = [{ - 'operator': 'ADD', - 'operand': offline_data_upload - }] - - # Upload offline data on the server and print the result. - result = offline_data_upload_service.mutate(operations) - offline_data_upload = result['value'][0] - - print ('Uploaded offline data with external upload ID "%d" and upload status ' - '"%s".' % (offline_data_upload['externalUploadId'], - offline_data_upload['uploadStatus'])) - - # Print any partial data errors from the response. - if result['partialFailureErrors']: - for api_error in result['partialFailureErrors']: - # Get the index of the failed operation from the error's field path - # elements. - operation_index = _GetFieldPathElementIndex(api_error, 'operations') - - if operation_index: - failed_offline_data_upload = operations[operation_index]['operand'] - # Get the index of the entry in the offline data list from the error's - # field path elements. - offline_data_list_index = _GetFieldPathElementIndex( - api_error, 'offlineDataList') - print ('Offline data list entry "%d" in operation "%d" with external ' - 'upload ID "%d" and type "%s" has triggered failure for the ' - 'following reason: "%s"' % ( - offline_data_list_index, operation_index, - failed_offline_data_upload['externalUploadId'], - failed_offline_data_upload['uploadType'], - api_error['errorString'])) - else: - print ('A failure has occurred for the following reason: "%s".' % ( - api_error['errorString'])) - - -def _CreateUserIdentifier(identifier_type=None, value=None): - """Creates a user identifier from the specified type and value. - - Args: - identifier_type: a str specifying the type of user identifier. - value: a str value of the identifier; to be hashed using SHA-256 if needed. - - Returns: - A dict specifying a user identifier, with a value hashed using SHA-256 if - needed. - """ - if identifier_type in _HASHED_IDENTIFIER_TYPES: - # If the user identifier type is a hashed type, normalize and hash the - # value. - value = hashlib.sha256(value.strip().lower()).hexdigest() - - user_identifier = { - 'userIdentifierType': identifier_type, - 'value': value - } - - return user_identifier - - -def _GetFieldPathElementIndex(api_error, field): - """Retrieve the index of a given field in the api_error's fieldPathElements. - - Args: - api_error: a dict containing a partialFailureError returned from the AdWords - API. - field: a str field for which this determines the index in the api_error's - fieldPathElements. - - Returns: - An int index of the field path element, or None if the specified field can't - be found in the api_error. - """ - field_path_elements = api_error['fieldPathElements'] - - if field_path_elements: - found_index = [field_path_element['index'] - for field_path_element in field_path_elements - if field_path_element['field'] == field] - if found_index: - return found_index - - return None - - -def _GetFormattedDateTime(dt): - """Formats the given datetime and timezone for use with AdWords. - - Args: - dt: a datetime instance. - - Returns: - A str representation of the datetime in the correct format for AdWords. - """ - return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, - STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, - ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201802/reporting/__init__.py b/examples/adwords/v201802/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201802/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index fce40cd5..00000000 --- a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import StringIO -import sys - -from googleads import adwords - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201802') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py deleted file mode 100755 index 80276d22..00000000 --- a/examples/adwords/v201802/reporting/download_criteria_report_as_stream_with_selector.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import StringIO -import sys -from googleads import adwords - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201802') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 561e0d96..00000000 --- a/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201802') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py deleted file mode 100755 index 47f71143..00000000 --- a/examples/adwords/v201802/reporting/download_criteria_report_as_string_with_selector.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201802') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201802/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index baeaa32b..00000000 --- a/examples/adwords/v201802/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import sys -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201802') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - # You can provide a file object to write the output to. For this - # demonstration we use sys.stdout to write the report to the screen. - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', sys.stdout, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py deleted file mode 100755 index b457899e..00000000 --- a/examples/adwords/v201802/reporting/download_criteria_report_with_selector.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import sys -from googleads import adwords - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201802') - - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201802/reporting/get_report_fields.py b/examples/adwords/v201802/reporting/get_report_fields.py deleted file mode 100755 index 87fa380c..00000000 --- a/examples/adwords/v201802/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201802') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type "%s" contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201802/reporting/parallel_report_download.py b/examples/adwords/v201802/reporting/parallel_report_download.py deleted file mode 100755 index f34b2f31..00000000 --- a/examples/adwords/v201802/reporting/parallel_report_download.py +++ /dev/null @@ -1,244 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import multiprocessing -import os -from Queue import Empty -import time - -import googleads.adwords -import googleads.errors - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def _DownloadReport(process_id, report_download_directory, customer_id, - report_definition): - """Helper function used by ReportWorker to download customer report. - - Note that multiprocessing differs between Windows / Unix environments. A - Process or its subclasses in Windows must be serializable with pickle, but - that is not possible for AdWordsClient or ReportDownloader. This top-level - function is used as a work-around for Windows support. - - Args: - process_id: The PID of the process downloading the report. - report_download_directory: A string indicating the directory where you - would like to download the reports. - customer_id: A str AdWords customer ID for which the report is being - downloaded. - report_definition: A dict containing the report definition to be used. - - Returns: - A tuple indicating a boolean success/failure status, and dict request - context. - """ - report_downloader = (googleads.adwords.AdWordsClient.LoadFromStorage() - .GetReportDownloader()) - - filepath = os.path.join(report_download_directory, - 'adgroup_%d.csv' % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (process_id, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - report_downloader.DownloadReport( - report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError as e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - def __init__(self, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = _DownloadReport(self.ident, self.report_download_directory, - customer_id, self.report_definition) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - Raises: - Exception: if no CustomerIds could be found. - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201802') - - offset = 0 - - # Get the account hierarchy for this account. - selector = { - 'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201802/shopping/__init__.py b/examples/adwords/v201802/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201802/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201802/shopping/add_product_partition_tree.py b/examples/adwords/v201802/shopping/add_product_partition_tree.py deleted file mode 100755 index 7c4dd3d5..00000000 --- a/examples/adwords/v201802/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,279 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201802') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201802/shopping/add_product_scope.py b/examples/adwords/v201802/shopping/add_product_scope.py deleted file mode 100755 index c8a893ed..00000000 --- a/examples/adwords/v201802/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201802') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201802/shopping/add_shopping_campaign.py b/examples/adwords/v201802/shopping/add_shopping_campaign.py deleted file mode 100755 index eab1d0d8..00000000 --- a/examples/adwords/v201802/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -# If set to true, a default partition will be created. If running the -# add_product_partition_tree.py example right after this example, make -# sure this stays set to false. -CREATE_DEFAULT_PARTITION = False -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id, create_default_partition): - campaign_service = client.GetService('CampaignService', version='v201802') - ad_group_service = client.GetService('AdGroupService', version='v201802') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201802') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - ad_group = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': ad_group - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] - ad_group_id = ad_group['id'] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (ad_group['name'], ad_group_id)) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': ad_group_id, - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - - if create_default_partition: - CreateDefaultPartition(client, ad_group_id) - - -def CreateDefaultPartition(client, ad_group_id): - """Creates a default partition. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID for an ad group. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201802') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Make sure that caseValue and parentCriterionId are left unspecified. - # This makes this partition as generic as possible to use as a - # fallback when others don't match. - 'criterion': { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - }, - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 500000 - } - }] - } - } - }] - - ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' - % (ad_group_criterion['criterion']['id'], - ad_group_criterion['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py deleted file mode 100755 index 6e6d14b4..00000000 --- a/examples/adwords/v201802/shopping/add_shopping_campaign_for_showcase_ads.py +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds a Shopping campaign for Showcase ads. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import uuid - -from googleads import adwords -from googleads import errors - - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' -COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - # Note: Showcase ads require either ManualCpc or EnhancedCpc in the - # campaign's BiddingStrategyConfiguration. - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, budget_id, merchant_id, expanded_image_filepath, - collapsed_image_filepath): - try: - # Create the Shopping Campaign - campaign = CreateShoppingCampaign(client, budget_id, merchant_id) - - # Create the AdGroup - adgroup = CreateAdGroup(client, campaign['id']) - - # Create a Showcase Ad - CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath) - - product_partition_tree = CreateProductPartition(client, adgroup['id']) - print 'Final tree:\n%s' % product_partition_tree - except errors.GoogleAdsServerFault: - print 'Failed to create shopping campaign for showcase ads.' - raise - - -def CreateShoppingCampaign(client, budget_id, merchant_id): - """Creates a shopping campaign with the given budget and merchant IDs. - - Args: - client: an AdWordsClient instance. - budget_id: the str ID of the budget to be associated with the shopping - campaign. - merchant_id: the str ID of the merchant account to be associated with the - shopping campaign. - - Returns: - The created Shopping Campaign as a sudsobject. - """ - campaign_service = client.GetService('CampaignService', 'v201802') - - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - return campaign - - -def CreateAdGroup(client, campaign_id): - """Creates an AdGroup for the given shopping campaign ID. - - Args: - client: an AdWordsClient instance. - campaign_id: the str ID of a shopping campaign. - - Returns: - The created AdGroup as a sudsobject. - """ - ad_group_service = client.GetService('AdGroupService', 'v201802') - - adgroup = { - # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS - 'adGroupType': 'SHOPPING_SHOWCASE_ADS', - 'campaignId': campaign_id, - 'name': 'AdGroup #%s' % uuid.uuid4(), - # REQUIRED: Set the ad group's bidding strategy configuration. - 'biddingStrategyConfiguration': { - # Showcase ads require either ManualCpc or EnhancedCpc. - 'biddingStrategyType': 'MANUAL_CPC', - # Optional: Set the bids - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 100000 - } - }] - } - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - return adgroup - - -def CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath): - """Creates a showcase add for the given AdGroup with the given images. - - Args: - client: an AdWordsClient instance. - adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. - expanded_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's expandedImage. - collapsed_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's collapsedImage. - - Returns: - The created Showcase Ad as a sudsobject. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201802') - - showcase_ad = { - 'adGroupId': adgroup['id'], - 'ad': { - 'xsi_type': 'ShowcaseAd', - 'Ad.Type': 'ShowcaseAd', - # Required: set the ad's name, final URLs, and display URL. - 'name': 'Showcase ad #%s' % uuid.uuid4(), - 'finalUrls': 'http://example.com/showcase', - 'displayUrl': 'example.com', - # Required: Set the ad's expanded image. - 'expandedImage': { - 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] - }, - # Optional: Set the collapsed image. - 'collapsedImage': { - 'mediaId': - UploadImage(client, collapsed_image_filepath)['mediaId'] - } - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': showcase_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] - - print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] - - return showcase_ad - - -def UploadImage(client, filepath): - """Uploads a .jpg image with the given filepath via the AdWords MediaService. - - Args: - client: an AdWordsClient instance. - filepath: a str filepath to the .jpg file to be uploaded. - - Returns: - The created Image as a sudsobject. - """ - media_service = client.GetService('MediaService', 'v201802') - - with open(filepath, 'rb') as image_handle: - image_data = image_handle.read().decode('utf-8') - - image = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - - image = media_service.upload(image)[0] - - return image - - -def CreateProductPartition(client, adgroup_id): - """Creates a ProductPartition tree for the given AdGroup ID. - - Args: - client: an AdWordsClient instance. - adgroup_id: a str AdGroup ID. - - Returns: - The ProductPartition tree as a sudsobject. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - 'v201802') - helper = ProductPartitionHelper(adgroup_id) - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition) - helper.CreateUnit(root, used_product_canonical_condition) - helper.CreateUnit(root, other_product_canonical_condition) - - result = ad_group_criterion_service.mutate(helper.operations) - return result['value'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, - COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201802/shopping/get_product_category_taxonomy.py b/examples/adwords/v201802/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 59b8a20c..00000000 --- a/examples/adwords/v201802/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201802') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/targeting/__init__.py b/examples/adwords/v201802/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201802/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index ca6bc2fd..00000000 --- a/examples/adwords/v201802/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201802') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s", criterion id "%s", ' - 'and type "%s" was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201802/targeting/add_customer_negative_criteria.py b/examples/adwords/v201802/targeting/add_customer_negative_criteria.py deleted file mode 100755 index 772ebeb1..00000000 --- a/examples/adwords/v201802/targeting/add_customer_negative_criteria.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds various types of negative criteria to a customer. - -These criteria will be applied to all campaigns for the customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_negative_criterion_service = client.GetService( - 'CustomerNegativeCriterionService', version='v201802') - - criteria = [ - # Exclude tragedy & conflict content. - { - 'xsi_type': 'ContentLabel', - 'contentLabelType': 'TRAGEDY' - }, - # Exclude a specific placement. - { - 'xsi_type': 'Placement', - 'url': 'http://www.example.com' - } - # Additional criteria types are available for this service. See the types - # listed under Criterion here: - # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion - ] - - # Create operations to add each of the criteria above. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'criterion': criterion - } - } for criterion in criteria] - - # Make the mutate request. - result = customer_negative_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for negative_criterion in result['value']: - print ('Customer negative criterion with criterion ID "%s", and type "%s" ' - 'was added.' % (negative_criterion['criterion']['id'], - negative_criterion['criterion']['type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index c53b5d3b..00000000 --- a/examples/adwords/v201802/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201802') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type "%s" was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index ec37619b..00000000 --- a/examples/adwords/v201802/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201802') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index a14ac2df..00000000 --- a/examples/adwords/v201802/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201802') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name "%s" and ID "%s" was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name "%s", ID "%s", and country code "%s" was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201802/targeting/lookup_location.py b/examples/adwords/v201802/targeting/lookup_location.py deleted file mode 100755 index b6062267..00000000 --- a/examples/adwords/v201802/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201802') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutschland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term "%s" returned the location "%s" of type "%s"' - ' with parent locations "%s", reach "%s" and id "%s" (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/googleads/adwords.py b/googleads/adwords.py index 1ae05fe0..b1173e58 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -42,58 +42,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201802': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdwordsUserListService': 'rm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignBidModifierService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignGroupPerformanceTargetService': 'cm', - 'CampaignGroupService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerNegativeCriterionService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'FeedItemService': 'cm', - 'FeedItemTargetService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineCallConversionFeedService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'OfflineDataUploadService': 'rm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201806': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', diff --git a/googleads/common.py b/googleads/common.py index 5424190f..6fb82e71 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '15.0.2' +VERSION = '16.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/test_data/traffic_estimator_service.xml b/tests/test_data/traffic_estimator_service.xml index 23c762c4..da37e8c0 100644 --- a/tests/test_data/traffic_estimator_service.xml +++ b/tests/test_data/traffic_estimator_service.xml @@ -1,16 +1,16 @@ - + + xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:tns="https://adwords.google.com/api/adwords/cm/v201809"> @@ -690,9 +690,9 @@ Ads will be served with Google.com search results. <span class="constraint AdxEnabled">This is disabled for AdX.</span> <span class="constraint CampaignType">This field may only be set to true for campaign channel type SEARCH.</span> -<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel type MULTI_CHANNEL.</span> <span class="constraint CampaignType">This field may only be set to false for campaign channel type DISPLAY.</span> -<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_UNIVERSAL_ADS.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_GOAL_OPTIMIZED_ADS.</span> @@ -703,8 +703,8 @@ Ads will be served on partner sites in the Google Search Network (requires {@code GOOGLE_SEARCH}). <span class="constraint AdxEnabled">This is disabled for AdX.</span> - <span class="constraint CampaignType">This field may only be set to true for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span> -<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_UNIVERSAL_ADS.</span> + <span class="constraint CampaignType">This field may only be set to true for campaign channel type MULTI_CHANNEL.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_GOAL_OPTIMIZED_ADS.</span> @@ -714,9 +714,10 @@ Ads will be served on specified placements in the Google Display Network. Placements are specified using {@code Placement} criteria. - <span class="constraint CampaignType">This field may only be set to true for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span> + <span class="constraint CampaignType">This field may only be set to true for campaign channel type MULTI_CHANNEL.</span> <span class="constraint CampaignType">This field may only be set to false for campaign channel subtype SEARCH_MOBILE_APP.</span> -<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_UNIVERSAL_ADS.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel type DISPLAY with campaign channel subtype DISPLAY_SMART_CAMPAIGN.</span> +<span class="constraint CampaignType">This field may only be set to true for campaign channel subtype SHOPPING_GOAL_OPTIMIZED_ADS.</span> @@ -727,7 +728,7 @@ Ads will be served on the Google Partner Network. This is available to only some specific Google partner accounts. <span class="constraint AdxEnabled">This is disabled for AdX.</span> - <span class="constraint CampaignType">This field may only be set to false for campaign channel subtype UNIVERSAL_APP_CAMPAIGN.</span> + <span class="constraint CampaignType">This field may only be set to false for campaign channel type MULTI_CHANNEL.</span> @@ -1577,6 +1578,21 @@ + + + + The customer has a policy to enforce 2-Step Verification, but the user is not enrolled. + + + + + + + The customer has a policy to enforce enrollment in the Advanced Protection Program, but + the user is not enrolled. + + + @@ -1791,6 +1807,20 @@ + + + + Custom Affinity, a criterion used for custom audience targeting. + + + + + + + Custom Intent, a criterion used for custom audience targeting. + + + @@ -2520,11 +2550,11 @@ - + xmlns:cm="https://adwords.google.com/api/adwords/cm/v201809" + xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:tns="https://adwords.google.com/api/adwords/o/v201809"> + @@ -3307,7 +3337,7 @@ - + From 6039d08e2d85850a46a70f24359d362ffde2f7ed Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Fri, 1 Feb 2019 12:44:13 -0500 Subject: [PATCH 130/180] Commiting latest changes. From 120278ba7d154fe470530649e1aa97d61f6a5646 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Tue, 12 Feb 2019 14:50:43 -0500 Subject: [PATCH 131/180] Ad Manager: removing support for v201802, removing v201805 examples, adding support for v201902 --- ChangeLog | 5 + .../get_availability_forecast.py | 130 --------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_traffic_adjustments.py | 143 ++++++++++ .../get_all_traffic_adjustments.py | 53 ++++ .../update_traffic_adjustments.py | 88 ++++++ .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../base_rate_service/__init__.py | 0 .../create_product_base_rates.py | 2 +- .../create_product_package_item_base_rates.py | 2 +- .../create_product_template_base_rates.py | 2 +- .../base_rate_service/get_all_base_rates.py | 4 +- .../get_base_rates_for_rate_card.py | 4 +- .../base_rate_service/update_base_rates.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../get_all_cms_metadata_keys.py | 52 ++++ .../get_all_cms_metadata_values.py | 55 ++++ .../get_cms_metadata_values_for_key.py | 60 +++++ .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../__init__.py | 0 ...create_content_metadata_key_hierarchies.py | 2 +- ...et_all_content_metadata_key_hierarchies.py | 4 +- ...update_content_metadata_key_hierarchies.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../exchange_rate_service/__init__.py | 0 .../create_exchange_rates.py | 2 +- .../get_all_exchange_rates.py | 4 +- .../get_exchange_rates_for_currency_code.py | 4 +- .../update_exchange_rates.py | 4 +- .../get_availability_forecast.py | 251 ++++++++++++++++++ ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 105 ++++---- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 8 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../package_service/create_packages.py | 2 +- ...reate_proposal_line_items_from_packages.py | 4 +- .../package_service/get_all_packages.py | 4 +- .../get_in_progress_packages.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../premium_rate_service/__init__.py | 0 .../create_premium_rates.py | 2 +- .../get_all_premium_rates.py | 4 +- .../get_premium_rates_for_rate_card.py | 4 +- .../update_premium_rates.py | 4 +- .../create_product_package_item.py | 2 +- .../get_all_product_package_items.py | 4 +- ...oduct_package_items_for_product_package.py | 4 +- .../create_product_packages.py | 2 +- .../get_active_product_packages.py | 4 +- .../get_all_product_packages.py | 4 +- .../product_service/__init__.py | 0 .../product_service/get_all_products.py | 4 +- .../get_products_for_product_template.py | 4 +- .../product_service/update_products.py | 4 +- .../product_template_service/__init__.py | 0 .../activate_product_templates.py | 4 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 4 +- .../get_all_product_templates.py | 4 +- .../get_sponsorship_product_templates.py | 4 +- .../update_product_templates.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- ...create_programmatic_proposal_line_items.py | 4 +- ...sal_line_items_for_non_sales_management.py | 15 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../create_programmatic_proposals.py | 4 +- ...atic_proposals_for_non_sales_management.py | 16 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../submit_proposals_for_approval.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 6 +- .../rate_card_service/__init__.py | 0 .../rate_card_service/create_rate_cards.py | 2 +- .../rate_card_service/get_all_rate_cards.py | 4 +- .../get_marketplace_rate_cards.py | 4 +- ..._item_reports_for_reconciliation_report.py | 4 +- ...update_reconciliation_line_item_reports.py | 4 +- ...order_reports_for_reconciliation_report.py | 4 +- .../submit_reconciliation_order_reports.py | 4 +- ...n_report_rows_for_reconciliation_report.py | 4 +- .../update_reconciliation_report_rows.py | 4 +- .../get_all_reconciliation_reports.py | 4 +- ...iliation_report_for_last_billing_period.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 14 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 6 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 0 .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- .../workflow_request_service/__init__.py | 0 .../approve_workflow_approval_requests.py | 4 +- .../get_workflow_approval_requests.py | 4 +- ...et_workflow_external_condition_requests.py | 4 +- ...er_workflow_external_condition_requests.py | 4 +- googleads/ad_manager.py | 45 ++-- googleads/common.py | 2 +- tests/common_test.py | 2 +- 252 files changed, 1169 insertions(+), 597 deletions(-) delete mode 100755 examples/ad_manager/v201805/forecast_service/get_availability_forecast.py rename examples/ad_manager/{v201805 => v201902}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v201805 => v201902}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v201805 => v201902}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v201805 => v201902}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v201805 => v201902}/activity_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v201805 => v201902}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v201805 => v201902}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v201805 => v201902}/activity_service/update_activities.py (96%) create mode 100755 examples/ad_manager/v201902/adjustment_service/create_traffic_adjustments.py create mode 100755 examples/ad_manager/v201902/adjustment_service/get_all_traffic_adjustments.py create mode 100755 examples/ad_manager/v201902/adjustment_service/update_traffic_adjustments.py rename examples/ad_manager/{v201805 => v201902}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v201805 => v201902}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v201805 => v201902}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v201805 => v201902}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v201805 => v201902}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v201805 => v201902}/base_rate_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/base_rate_service/create_product_base_rates.py (97%) rename examples/ad_manager/{v201805 => v201902}/base_rate_service/create_product_package_item_base_rates.py (99%) rename examples/ad_manager/{v201805 => v201902}/base_rate_service/create_product_template_base_rates.py (98%) rename examples/ad_manager/{v201805 => v201902}/base_rate_service/get_all_base_rates.py (96%) rename examples/ad_manager/{v201805 => v201902}/base_rate_service/get_base_rates_for_rate_card.py (96%) rename examples/ad_manager/{v201805 => v201902}/base_rate_service/update_base_rates.py (96%) rename examples/ad_manager/{v201805 => v201902}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v201805 => v201902}/cdn_configuration_service/get_all_cdn_configurations.py (93%) create mode 100755 examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_keys.py create mode 100755 examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_values.py create mode 100755 examples/ad_manager/v201902/cms_metadata_service/get_cms_metadata_values_for_key.py rename examples/ad_manager/{v201805 => v201902}/company_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/company_service/create_companies.py (99%) rename examples/ad_manager/{v201805 => v201902}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v201805 => v201902}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v201805 => v201902}/company_service/update_companies.py (96%) rename examples/ad_manager/{v201805 => v201902}/contact_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v201805 => v201902}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v201805 => v201902}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v201805 => v201902}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v201805 => v201902}/content_metadata_key_hierarchy_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py (97%) rename examples/ad_manager/{v201805 => v201902}/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py (94%) rename examples/ad_manager/{v201805 => v201902}/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py (96%) rename examples/ad_manager/{v201805 => v201902}/content_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/content_service/get_all_content.py (95%) rename examples/ad_manager/{v201805 => v201902}/creative_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v201805 => v201902}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v201805 => v201902}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v201805 => v201902}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v201805 => v201902}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v201805 => v201902}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v201805 => v201902}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v201805 => v201902}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v201805 => v201902}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v201805 => v201902}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v201805 => v201902}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v201805 => v201902}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v201805 => v201902}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v201805 => v201902}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v201805 => v201902}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v201805 => v201902}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v201805 => v201902}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v201805 => v201902}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v201805 => v201902}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v201805 => v201902}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v201805 => v201902}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v201805 => v201902}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v201805 => v201902}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v201805 => v201902}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v201805 => v201902}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v201805 => v201902}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v201805 => v201902}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v201805 => v201902}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v201805 => v201902}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201805 => v201902}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v201805 => v201902}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201805 => v201902}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201805 => v201902}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201805 => v201902}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v201805 => v201902}/exchange_rate_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/exchange_rate_service/create_exchange_rates.py (96%) rename examples/ad_manager/{v201805 => v201902}/exchange_rate_service/get_all_exchange_rates.py (94%) rename examples/ad_manager/{v201805 => v201902}/exchange_rate_service/get_exchange_rates_for_currency_code.py (94%) rename examples/ad_manager/{v201805 => v201902}/exchange_rate_service/update_exchange_rates.py (95%) create mode 100755 examples/ad_manager/v201902/forecast_service/get_availability_forecast.py rename examples/ad_manager/{v201805 => v201902}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v201805 => v201902}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v201805 => v201902}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v201805 => v201902}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v201805 => v201902}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v201805 => v201902}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v201805 => v201902}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v201805 => v201902}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v201805 => v201902}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v201805 => v201902}/label_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/label_service/create_labels.py (99%) rename examples/ad_manager/{v201805 => v201902}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v201805 => v201902}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v201805 => v201902}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v201805 => v201902}/label_service/update_labels.py (96%) rename examples/ad_manager/{v201805 => v201902}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v201805 => v201902}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v201805 => v201902}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v201805 => v201902}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v201805 => v201902}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/create_video_line_item.py (53%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v201805 => v201902}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v201805 => v201902}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v201805 => v201902}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v201805 => v201902}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v201805 => v201902}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v201805 => v201902}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v201805 => v201902}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/native_style_service/create_native_styles.py (97%) rename examples/ad_manager/{v201805 => v201902}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v201805 => v201902}/network_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v201805 => v201902}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v201805 => v201902}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v201805 => v201902}/order_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v201805 => v201902}/order_service/create_orders.py (99%) rename examples/ad_manager/{v201805 => v201902}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v201805 => v201902}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v201805 => v201902}/order_service/update_orders.py (97%) rename examples/ad_manager/{v201805 => v201902}/package_service/create_packages.py (99%) rename examples/ad_manager/{v201805 => v201902}/package_service/create_proposal_line_items_from_packages.py (96%) rename examples/ad_manager/{v201805 => v201902}/package_service/get_all_packages.py (96%) rename examples/ad_manager/{v201805 => v201902}/package_service/get_in_progress_packages.py (96%) rename examples/ad_manager/{v201805 => v201902}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v201805 => v201902}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v201805 => v201902}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v201805 => v201902}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v201805 => v201902}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v201805 => v201902}/premium_rate_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/premium_rate_service/create_premium_rates.py (97%) rename examples/ad_manager/{v201805 => v201902}/premium_rate_service/get_all_premium_rates.py (94%) rename examples/ad_manager/{v201805 => v201902}/premium_rate_service/get_premium_rates_for_rate_card.py (95%) rename examples/ad_manager/{v201805 => v201902}/premium_rate_service/update_premium_rates.py (95%) rename examples/ad_manager/{v201805 => v201902}/product_package_item_service/create_product_package_item.py (99%) rename examples/ad_manager/{v201805 => v201902}/product_package_item_service/get_all_product_package_items.py (94%) rename examples/ad_manager/{v201805 => v201902}/product_package_item_service/get_product_package_items_for_product_package.py (94%) rename examples/ad_manager/{v201805 => v201902}/product_package_service/create_product_packages.py (96%) rename examples/ad_manager/{v201805 => v201902}/product_package_service/get_active_product_packages.py (94%) rename examples/ad_manager/{v201805 => v201902}/product_package_service/get_all_product_packages.py (94%) rename examples/ad_manager/{v201805 => v201902}/product_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/product_service/get_all_products.py (95%) rename examples/ad_manager/{v201805 => v201902}/product_service/get_products_for_product_template.py (96%) rename examples/ad_manager/{v201805 => v201902}/product_service/update_products.py (96%) rename examples/ad_manager/{v201805 => v201902}/product_template_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/product_template_service/activate_product_templates.py (95%) rename examples/ad_manager/{v201805 => v201902}/product_template_service/create_product_templates.py (97%) rename examples/ad_manager/{v201805 => v201902}/product_template_service/create_programmatic_product_templates.py (96%) rename examples/ad_manager/{v201805 => v201902}/product_template_service/get_all_product_templates.py (94%) rename examples/ad_manager/{v201805 => v201902}/product_template_service/get_sponsorship_product_templates.py (94%) rename examples/ad_manager/{v201805 => v201902}/product_template_service/update_product_templates.py (96%) rename examples/ad_manager/{v201805 => v201902}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v201805 => v201902}/proposal_line_item_service/create_programmatic_proposal_line_items.py (98%) rename examples/ad_manager/{v201805 => v201902}/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py (88%) rename examples/ad_manager/{v201805 => v201902}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v201805 => v201902}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v201805 => v201902}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v201805 => v201902}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/create_programmatic_proposals.py (99%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/create_programmatic_proposals_for_non_sales_management.py (83%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/get_proposals_pending_approval.py (96%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/submit_proposals_for_approval.py (96%) rename examples/ad_manager/{v201805 => v201902}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v201805 => v201902}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v201805 => v201902}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v201805 => v201902}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v201805 => v201902}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v201805 => v201902}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v201805 => v201902}/publisher_query_language_service/get_recent_changes.py (97%) rename examples/ad_manager/{v201805 => v201902}/rate_card_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/rate_card_service/create_rate_cards.py (99%) rename examples/ad_manager/{v201805 => v201902}/rate_card_service/get_all_rate_cards.py (95%) rename examples/ad_manager/{v201805 => v201902}/rate_card_service/get_marketplace_rate_cards.py (96%) rename examples/ad_manager/{v201805 => v201902}/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py (95%) rename examples/ad_manager/{v201805 => v201902}/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py (95%) rename examples/ad_manager/{v201805 => v201902}/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py (94%) rename examples/ad_manager/{v201805 => v201902}/reconciliation_order_report_service/submit_reconciliation_order_reports.py (95%) rename examples/ad_manager/{v201805 => v201902}/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py (95%) rename examples/ad_manager/{v201805 => v201902}/reconciliation_report_row_service/update_reconciliation_report_rows.py (95%) rename examples/ad_manager/{v201805 => v201902}/reconciliation_report_service/get_all_reconciliation_reports.py (94%) rename examples/ad_manager/{v201805 => v201902}/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py (94%) rename examples/ad_manager/{v201805 => v201902}/report_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v201805 => v201902}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v201805 => v201902}/report_service/run_inventory_report.py (86%) rename examples/ad_manager/{v201805 => v201902}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v201805 => v201902}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v201805 => v201902}/report_service/run_report_with_custom_fields.py (95%) rename examples/ad_manager/{v201805 => v201902}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v201805 => v201902}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v201805 => v201902}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v201805 => v201902}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v201805 => v201902}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v201805 => v201902}/team_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/team_service/create_teams.py (96%) rename examples/ad_manager/{v201805 => v201902}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v201805 => v201902}/team_service/update_teams.py (94%) rename examples/ad_manager/{v201805 => v201902}/user_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/user_service/create_users.py (96%) rename examples/ad_manager/{v201805 => v201902}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v201805 => v201902}/user_service/get_all_roles.py (100%) rename examples/ad_manager/{v201805 => v201902}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v201805 => v201902}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v201805 => v201902}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v201805 => v201902}/user_service/update_users.py (92%) rename examples/ad_manager/{v201805 => v201902}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v201805 => v201902}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v201805 => v201902}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v201805 => v201902}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v201805 => v201902}/user_team_association_service/update_user_team_associations.py (96%) rename examples/ad_manager/{v201805 => v201902}/workflow_request_service/__init__.py (100%) rename examples/ad_manager/{v201805 => v201902}/workflow_request_service/approve_workflow_approval_requests.py (95%) rename examples/ad_manager/{v201805 => v201902}/workflow_request_service/get_workflow_approval_requests.py (94%) rename examples/ad_manager/{v201805 => v201902}/workflow_request_service/get_workflow_external_condition_requests.py (94%) rename examples/ad_manager/{v201805 => v201902}/workflow_request_service/trigger_workflow_external_condition_requests.py (95%) diff --git a/ChangeLog b/ChangeLog index 409c6eb6..1a7707ab 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +17.0.0 -- 02/12/2019 +* Added support for Ad Manager v201902. +* Removed support for Ad Manager v201802. +* Removed examples for Ad Manager v201805. + 16.0.0 -- 01/29/2019 * Removed support for AdWords v201802 diff --git a/examples/ad_manager/v201805/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201805/forecast_service/get_availability_forecast.py deleted file mode 100755 index c1d25506..00000000 --- a/examples/ad_manager/v201805/forecast_service/get_availability_forecast.py +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 a forecast for a prospective line item. - -The prospective line item targets the entire network. The targeting can be -modified to determine forecasts for other criteria such as custom criteria -targeting (in addition to targeting the whole network). See -create_line_items.py for an example of how to create more complex targeting. - -""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set the ID of the advertiser (company) to forecast for. Setting an advertiser -# will cause the forecast to apply the appropriate unified blocking rules. -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201805') - network_service = client.GetService('NetworkService', version='v201805') - - # get the root ad unit ID to target the entire network. - root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime += datetime.timedelta(days=30) - - # Create prospective line item. - line_item = { - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': [ - { - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id, - } - ] - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '300', - 'height': '250' - } - }, - { - 'size': { - 'width': '120', - 'height': '600' - } - } - ], - 'lineItemType': 'SPONSORSHIP', - 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': end_datetime, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'DAILY' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'EVEN', - 'discountType': 'PERCENTAGE', - } - - prospective_line_item = { - 'lineItem': line_item, - 'advertiserId': advertiser_id - } - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - 'includeTargetingCriteriaBreakdown': True, - } - - # Get forecast. - forecast = forecast_service.getAvailabilityForecast( - prospective_line_item, forecast_options) - matched = long(forecast['matchedUnits']) - available_units = long(forecast['availableUnits']) - - if matched > 0: - available_percent = (float(available_units) / matched) * 100. - else: - available_percent = 0 - - contending_line_items = getattr(forecast, 'contentingLineItems', []) - - # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) - - if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201805/activity_group_service/__init__.py b/examples/ad_manager/v201902/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/activity_group_service/__init__.py rename to examples/ad_manager/v201902/activity_group_service/__init__.py diff --git a/examples/ad_manager/v201805/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201902/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v201805/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v201902/activity_group_service/create_activity_groups.py index c2d3f9c8..55075af0 100755 --- a/examples/ad_manager/v201805/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201902/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201805') + version='v201902') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py index 5bae3c98..da31eefe 100755 --- a/examples/ad_manager/v201805/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201805') + 'ActivityGroupService', version='v201902') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py index 37155c24..c77ec1c5 100755 --- a/examples/ad_manager/v201805/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201805') + 'ActivityGroupService', version='v201902') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201805/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201902/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v201805/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v201902/activity_group_service/update_activity_groups.py index 3d38ce60..7f7bd747 100755 --- a/examples/ad_manager/v201805/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201902/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201805') + version='v201902') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', long(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/activity_service/__init__.py b/examples/ad_manager/v201902/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/activity_service/__init__.py rename to examples/ad_manager/v201902/activity_service/__init__.py diff --git a/examples/ad_manager/v201805/activity_service/create_activities.py b/examples/ad_manager/v201902/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v201805/activity_service/create_activities.py rename to examples/ad_manager/v201902/activity_service/create_activities.py index b6339d1b..d2baa78c 100755 --- a/examples/ad_manager/v201805/activity_service/create_activities.py +++ b/examples/ad_manager/v201902/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201805') + activity_service = client.GetService('ActivityService', version='v201902') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v201805/activity_service/get_active_activities.py b/examples/ad_manager/v201902/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v201805/activity_service/get_active_activities.py rename to examples/ad_manager/v201902/activity_service/get_active_activities.py index 6d2e25a7..b65358c3 100755 --- a/examples/ad_manager/v201805/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201902/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201805') + activity_service = client.GetService('ActivityService', version='v201902') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/activity_service/get_all_activities.py b/examples/ad_manager/v201902/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v201805/activity_service/get_all_activities.py rename to examples/ad_manager/v201902/activity_service/get_all_activities.py index e22d1a25..de891c36 100755 --- a/examples/ad_manager/v201805/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201902/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201805') + activity_service = client.GetService('ActivityService', version='v201902') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201805/activity_service/update_activities.py b/examples/ad_manager/v201902/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v201805/activity_service/update_activities.py rename to examples/ad_manager/v201902/activity_service/update_activities.py index d953e14e..3a5c27db 100755 --- a/examples/ad_manager/v201805/activity_service/update_activities.py +++ b/examples/ad_manager/v201902/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201805') + activity_service = client.GetService('ActivityService', version='v201902') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :activityId') .WithBindVariable('activityId', long(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/adjustment_service/create_traffic_adjustments.py b/examples/ad_manager/v201902/adjustment_service/create_traffic_adjustments.py new file mode 100755 index 00000000..22a57577 --- /dev/null +++ b/examples/ad_manager/v201902/adjustment_service/create_traffic_adjustments.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 adds or replaces a forecast adjustment. + +The adjustment will affect 1920x1080 video traffic in the United States. +""" + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service and the network service. + adjustment_service = client.GetService('AdjustmentService', version='v201902') + network_service = client.GetService('NetworkService', version='v201902') + + # Get the root ad unit id to target the whole site. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create inventory targeting. + inventory_targeting = { + 'targetedAdUnits': [{ + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id + }] + } + + # Create geo targeting. When using geo targeting with the adjustment service, + # only locations of type COUNTRY are supported. You can download the latest + # geo targets at https://developers.google.com/ad-manager/api/geotargets. + geo_targeting = { + 'targetedLocations': [{ + 'id': 2840 + }] # USA. + } + + # Create ad unit size to define the slice of inventory affected by the + # traffic adjustment. + ad_unit_size = { + 'size': { + 'width': 1920, + 'height': 1080 + }, + 'environmentType': 'VIDEO_PLAYER' + } + + # Create a new historical adjustment targeting next year's January with 105% + # of the traffic of this year's January. + this_january = { + 'startDate': datetime.date(datetime.date.today().year, 1, 1), + 'endDate': datetime.date(datetime.date.today().year, 1, 31) + } + next_january = { + 'startDate': datetime.date(datetime.date.today().year + 1, 1, 1), + 'endDate': datetime.date(datetime.date.today().year + 1, 1, 31) + } + + january_segment = { + 'basisType': 'HISTORICAL', + 'historicalAdjustment': { + 'targetDateRange': next_january, + 'referenceDateRange': this_january, + 'milliPercentMultiplier': 105000 + } + } + + # Create a new absolute adjustment of 500,000 ad opportunities for Christmas + # and 1,000,000 opportunities for Boxing Day of next year. + christmas_day = datetime.date(datetime.date.today().year + 1, 12, 25) + boxing_day = christmas_day + datetime.timedelta(days=1) + holiday_range = {'startDate': christmas_day, 'endDate': boxing_day} + + holiday_segment = { + 'basisType': 'ABSOLUTE', + 'adjustmentTimeSeries': { + 'timeSeriesDateRange': holiday_range, + 'timeSeriesValues': [500000, 1000000], # xsd:long[] + 'valuePeriodType': 'DAILY' + } + } + + # Create a new absolute adjustment of 900,000 ad opportunities for the first + # week of September of next year. + first_week_of_september = { + 'startDate': datetime.date(datetime.date.today().year + 1, 9, 1), + 'endDate': datetime.date(datetime.date.today().year + 1, 9, 7) + } + + september_segment = { + 'basisType': 'ABSOLUTE', + 'adjustmentTimeSeries': { + 'timeSeriesDateRange': first_week_of_september, + 'timeSeriesValues': [900000], + 'valuePeriodType': 'CUSTOM' + } + } + + # Create traffic forecast adjustment object. + adjustment_segments = [january_segment, holiday_segment, september_segment] + adjustment = { + 'filterCriteria': { + 'targeting': { + 'inventoryTargeting': inventory_targeting, + 'geoTargeting': geo_targeting + }, + 'adUnitSizes': [ad_unit_size] + }, + 'forecastAdjustmentSegments': adjustment_segments + } + + # Create or update the traffic adjustment for the given filter criteria on + # the server. + updated_adjustments = adjustment_service.updateTrafficAdjustments( + [adjustment]) + + # Display the results. + for updated_adjustment in updated_adjustments: + print('Traffic forecast adjustment with id %d and %d segments was ' + 'created.' % (updated_adjustment['id'], + len(updated_adjustment['forecastAdjustmentSegments']))) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201902/adjustment_service/get_all_traffic_adjustments.py b/examples/ad_manager/v201902/adjustment_service/get_all_traffic_adjustments.py new file mode 100755 index 00000000..cabc767d --- /dev/null +++ b/examples/ad_manager/v201902/adjustment_service/get_all_traffic_adjustments.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 traffic adjustments.""" + +from __future__ import print_function + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v201902') + + # Create a statement to get all forecast traffic adjustments. + statement = ad_manager.StatementBuilder(version='v201902') + + # Retrieve a small number of traffic adjustments at a time, paging + # through until all traffic adjustments have been retrieved. + while True: + response = adjustment_service.getTrafficAdjustmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for adjustment in response['results']: + # Print out some information for each traffic adjustment. + print('Traffic forecast adjustment with id %d and %d segments was ' + 'found.' % (adjustment['id'], + len(adjustment['forecastAdjustmentSegments']))) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201902/adjustment_service/update_traffic_adjustments.py b/examples/ad_manager/v201902/adjustment_service/update_traffic_adjustments.py new file mode 100755 index 00000000..60a54bd2 --- /dev/null +++ b/examples/ad_manager/v201902/adjustment_service/update_traffic_adjustments.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 adds a historical adjustment of 110% for New Years Day traffic. +""" + +from __future__ import print_function +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' + + +def main(client, adjustment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v201902') + + # Create a statement to select a single traffic forecast adjustment by id. + statement = ( + ad_manager.StatementBuilder( + version='v201902').Where('id = :id').WithBindVariable( + 'id', adjustment_id)) + + # Get the forecast traffic adjustment. + response = adjustment_service.getTrafficAdjustmentsByStatement( + statement.ToStatement()) + + # Create a new historical adjustment segment for New Year's Day. + this_new_years = datetime.date(datetime.date.today().year, 12, 31) + next_new_years = datetime.date(datetime.date.today().year + 1, 12, 31) + + new_years_segment = { + 'basisType': 'HISTORICAL', + 'historicalAdjustment': { + 'targetDateRange': { + 'startDate': next_new_years, + 'endDate': next_new_years + }, + 'referenceDateRange': { + 'startDate': this_new_years, + 'endDate': this_new_years + }, + 'milliPercentMultiplier': 110000 + } + } + + if 'results' in response and len(response['results']): + # Update each local traffic adjustment. + updated_adjustments = [] + for adjustment in response['results']: + adjustment['forecastAdjustmentSegments'].append(new_years_segment) + updated_adjustments.append(adjustment) + + # Update traffic adjustments remotely. + adjustments = adjustment_service.updateTrafficAdjustments( + updated_adjustments) + + # Display the results. + if adjustments: + for adjustment in adjustments: + print('Traffic forecast adjustment with id %d and %d segments was ' + 'created.' % (adjustment['id'], + len(adjustment['forecastAdjustmentSegments']))) + else: + print('No traffic adjustments were updated.') + else: + print('No traffic adjustments found to update.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v201805/audience_segment_service/__init__.py b/examples/ad_manager/v201902/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/audience_segment_service/__init__.py rename to examples/ad_manager/v201902/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v201805/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v201805/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py index 1eea734e..b1e9bcec 100755 --- a/examples/ad_manager/v201805/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201805') - network_service = client.GetService('NetworkService', version='v201805') + 'AudienceSegmentService', version='v201902') + network_service = client.GetService('NetworkService', version='v201902') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py index 70d8b9a1..5f0e6ea2 100755 --- a/examples/ad_manager/v201805/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201805') + 'AudienceSegmentService', version='v201902') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py index 96373dd5..9354b883 100755 --- a/examples/ad_manager/v201805/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201805') + 'AudienceSegmentService', version='v201902') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py index 91144dbb..5b567d35 100755 --- a/examples/ad_manager/v201805/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201805') + 'AudienceSegmentService', version='v201902') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) diff --git a/examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py index 8aba8fd6..ae0509ae 100755 --- a/examples/ad_manager/v201805/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201805') + 'AudienceSegmentService', version='v201902') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', long(audience_segment_id)) diff --git a/examples/ad_manager/v201805/base_rate_service/__init__.py b/examples/ad_manager/v201902/base_rate_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/base_rate_service/__init__.py rename to examples/ad_manager/v201902/base_rate_service/__init__.py diff --git a/examples/ad_manager/v201805/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py similarity index 97% rename from examples/ad_manager/v201805/base_rate_service/create_product_base_rates.py rename to examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py index 680710cd..65b79f4f 100755 --- a/examples/ad_manager/v201805/base_rate_service/create_product_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201805') + 'BaseRateService', version='v201902') # Create a product base rate. product_base_rate = { diff --git a/examples/ad_manager/v201805/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py similarity index 99% rename from examples/ad_manager/v201805/base_rate_service/create_product_package_item_base_rates.py rename to examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py index b449df56..a4b219cf 100755 --- a/examples/ad_manager/v201805/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201805') + base_rate_service = client.GetService('BaseRateService', version='v201902') # Create a base rate for a product package item. product_package_item_base_rate = { diff --git a/examples/ad_manager/v201805/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py similarity index 98% rename from examples/ad_manager/v201805/base_rate_service/create_product_template_base_rates.py rename to examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py index cc3e25ce..0e1c7b9d 100755 --- a/examples/ad_manager/v201805/base_rate_service/create_product_template_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py @@ -31,7 +31,7 @@ def main(client, product_template_id, rate_card_id): # Initialize appropriate service. base_rate_service = client.GetService( - 'BaseRateService', version='v201805') + 'BaseRateService', version='v201902') # Create a product template base rate. product_template_base_rate = { diff --git a/examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py similarity index 96% rename from examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py rename to examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py index 8d50840d..2ec2bbce 100755 --- a/examples/ad_manager/v201805/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201805') + base_rate_service = client.GetService('BaseRateService', version='v201902') # Create a statement to select base rates. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of base rates at a time, paging # through until all base rates have been retrieved. diff --git a/examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py similarity index 96% rename from examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py rename to examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py index ee04c0cb..3e6deb9a 100755 --- a/examples/ad_manager/v201805/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py @@ -24,9 +24,9 @@ def main(client, rate_card_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201805') + base_rate_service = client.GetService('BaseRateService', version='v201902') # Create a statement to select base rates. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) diff --git a/examples/ad_manager/v201805/base_rate_service/update_base_rates.py b/examples/ad_manager/v201902/base_rate_service/update_base_rates.py similarity index 96% rename from examples/ad_manager/v201805/base_rate_service/update_base_rates.py rename to examples/ad_manager/v201902/base_rate_service/update_base_rates.py index db4d943b..a7155c07 100755 --- a/examples/ad_manager/v201805/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/update_base_rates.py @@ -29,10 +29,10 @@ def main(client, base_rate_id): # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201805') + base_rate_service = client.GetService('BaseRateService', version='v201902') # Create a filter statement for base rates for a single rate card. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/cdn_configuration_service/__init__.py b/examples/ad_manager/v201902/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/cdn_configuration_service/__init__.py rename to examples/ad_manager/v201902/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v201805/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201902/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v201805/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v201902/cdn_configuration_service/create_cdn_configurations.py index 21a9459b..22304b45 100755 --- a/examples/ad_manager/v201805/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v201902/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201805') + version='v201902') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py index 949bd7bd..9f262ec5 100755 --- a/examples/ad_manager/v201805/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201805') + version='v201902') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_keys.py new file mode 100755 index 00000000..4f233607 --- /dev/null +++ b/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_keys.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 CmsMetadataKeys.""" + +# Import appropriate modules from the client library. +from __future__ import print_function +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201902') + + # Create a statement to select CmsMetadataKeys. + statement = ad_manager.StatementBuilder(version='v201902') + + # Retrieve a small amount of keys at a time, paging + # through until all keys have been retrieved. + while True: + response = cms_metadata_service.getCmsMetadataKeysByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_key in response['results']: + # Print out some information for each key. + print('CMS metadata key with Id %d and name "%s" was found.\n' % + (cms_metadata_key['id'], cms_metadata_key['name'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_values.py new file mode 100755 index 00000000..e7808283 --- /dev/null +++ b/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_values.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 CmsMetadataValues.""" + +# Import appropriate modules from the client library. +from __future__ import print_function +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201902') + + # Create a statement to select CmsMetadataValues. + statement = ad_manager.StatementBuilder(version='v201902') + + # Retrieve a small amount of values at a time, paging + # through until all values have been retrieved. + while True: + response = cms_metadata_service.getCmsMetadataValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_value in response['results']: + # Print out some information for each value. + print(('CMS metadata value with Id %d and name "%s", associated with ' + 'the CmsMetadataKey with id %d and name "%s", was found.\n') % + (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'], cms_metadata_value['key']['id'], + cms_metadata_value['key']['name'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201902/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v201902/cms_metadata_service/get_cms_metadata_values_for_key.py new file mode 100755 index 00000000..075b1879 --- /dev/null +++ b/examples/ad_manager/v201902/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 CmsMetadataValues for a particular CmsMetadataKey.""" + +# Import appropriate modules from the client library. +from __future__ import print_function +from googleads import ad_manager + +CMS_METADATA_KEY_NAME = 'INSERT_CMS_METADATA_KEY_NAME_HERE' + + +def main(client, cms_metadata_key_name): + # Initialize appropriate service. + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201902') + + # Create a statement to select CmsMetadataValues for a particular key. + statement = ( + ad_manager.StatementBuilder(version='v201902').Where( + 'cmsKey = :cmsMetadataKeyName').WithBindVariable( + 'cmsMetadataKeyName', cms_metadata_key_name)) + + # Retrieve a small amount of values at a time, paging + # through until all values have been retrieved. + while True: + response = cms_metadata_service.getCmsMetadataValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_value in response['results']: + # Print out some information for each value. + print(('CMS metadata value with Id %d and name "%s", associated with ' + 'the CmsMetadataKey with id %d and name "%s", was found.\n') % + (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'], cms_metadata_value['key']['id'], + cms_metadata_value['key']['name'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CMS_METADATA_KEY_NAME) diff --git a/examples/ad_manager/v201805/company_service/__init__.py b/examples/ad_manager/v201902/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/company_service/__init__.py rename to examples/ad_manager/v201902/company_service/__init__.py diff --git a/examples/ad_manager/v201805/company_service/create_companies.py b/examples/ad_manager/v201902/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v201805/company_service/create_companies.py rename to examples/ad_manager/v201902/company_service/create_companies.py index d7eccf64..8b37ee46 100755 --- a/examples/ad_manager/v201805/company_service/create_companies.py +++ b/examples/ad_manager/v201902/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201805') + company_service = client.GetService('CompanyService', version='v201902') # Create company objects. companies = [ diff --git a/examples/ad_manager/v201805/company_service/get_advertisers.py b/examples/ad_manager/v201902/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v201805/company_service/get_advertisers.py rename to examples/ad_manager/v201902/company_service/get_advertisers.py index 8411ae72..1b38f940 100755 --- a/examples/ad_manager/v201805/company_service/get_advertisers.py +++ b/examples/ad_manager/v201902/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201805') + company_service = client.GetService('CompanyService', version='v201902') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201805/company_service/get_all_companies.py b/examples/ad_manager/v201902/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v201805/company_service/get_all_companies.py rename to examples/ad_manager/v201902/company_service/get_all_companies.py index 9a12a342..60f73ad5 100755 --- a/examples/ad_manager/v201805/company_service/get_all_companies.py +++ b/examples/ad_manager/v201902/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201805') + company_service = client.GetService('CompanyService', version='v201902') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201805/company_service/update_companies.py b/examples/ad_manager/v201902/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v201805/company_service/update_companies.py rename to examples/ad_manager/v201902/company_service/update_companies.py index b67834af..42339553 100755 --- a/examples/ad_manager/v201805/company_service/update_companies.py +++ b/examples/ad_manager/v201902/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201805') + company_service = client.GetService('CompanyService', version='v201902') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', long(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/contact_service/__init__.py b/examples/ad_manager/v201902/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/contact_service/__init__.py rename to examples/ad_manager/v201902/contact_service/__init__.py diff --git a/examples/ad_manager/v201805/contact_service/create_contacts.py b/examples/ad_manager/v201902/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v201805/contact_service/create_contacts.py rename to examples/ad_manager/v201902/contact_service/create_contacts.py index 3d67169d..ea14866f 100755 --- a/examples/ad_manager/v201805/contact_service/create_contacts.py +++ b/examples/ad_manager/v201902/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201805') + contact_service = client.GetService('ContactService', version='v201902') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v201805/contact_service/get_all_contacts.py b/examples/ad_manager/v201902/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v201805/contact_service/get_all_contacts.py rename to examples/ad_manager/v201902/contact_service/get_all_contacts.py index 6f182040..65fbde5d 100755 --- a/examples/ad_manager/v201805/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201902/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201805') + contact_service = client.GetService('ContactService', version='v201902') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py index e7fa5388..aed4d4d1 100755 --- a/examples/ad_manager/v201805/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201805') + contact_service = client.GetService('ContactService', version='v201902') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201805/contact_service/update_contacts.py b/examples/ad_manager/v201902/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v201805/contact_service/update_contacts.py rename to examples/ad_manager/v201902/contact_service/update_contacts.py index 4cbb1513..ee3e868a 100755 --- a/examples/ad_manager/v201805/contact_service/update_contacts.py +++ b/examples/ad_manager/v201902/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201805') + contact_service = client.GetService('ContactService', version='v201902') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', long(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/content_metadata_key_hierarchy_service/__init__.py rename to examples/ad_manager/v201902/content_metadata_key_hierarchy_service/__init__.py diff --git a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py similarity index 97% rename from examples/ad_manager/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201902/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py index dc83bb63..e93ff004 100755 --- a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -42,7 +42,7 @@ def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201805') + 'ContentMetadataKeyHierarchyService', version='v201902') hierarchy_level_1 = { 'customTargetingKeyId': hierarchy_level_one_key_id, diff --git a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py similarity index 94% rename from examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201902/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py index d28d0838..9ea30768 100755 --- a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201805') + 'ContentMetadataKeyHierarchyService', version='v201902') # Create a statement to select content metadata key hierarchies. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of content metadata key hierarchies at a time, # paging through until all content metadata key hierarchies have been diff --git a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py similarity index 96% rename from examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py rename to examples/ad_manager/v201902/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py index 6f99f097..eccfce7d 100755 --- a/examples/ad_manager/v201805/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -42,11 +42,11 @@ def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): # Initialize appropriate service. content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201805') + 'ContentMetadataKeyHierarchyService', version='v201902') # Create a query to select a single content metadata key hierarchy. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) diff --git a/examples/ad_manager/v201805/content_service/__init__.py b/examples/ad_manager/v201902/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/content_service/__init__.py rename to examples/ad_manager/v201902/content_service/__init__.py diff --git a/examples/ad_manager/v201805/content_service/get_all_content.py b/examples/ad_manager/v201902/content_service/get_all_content.py similarity index 95% rename from examples/ad_manager/v201805/content_service/get_all_content.py rename to examples/ad_manager/v201902/content_service/get_all_content.py index d2cfc740..db6c8e39 100755 --- a/examples/ad_manager/v201805/content_service/get_all_content.py +++ b/examples/ad_manager/v201902/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201805') + content_service = client.GetService('ContentService', version='v201902') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v201805/creative_service/__init__.py b/examples/ad_manager/v201902/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/creative_service/__init__.py rename to examples/ad_manager/v201902/creative_service/__init__.py diff --git a/examples/ad_manager/v201805/creative_service/copy_image_creatives.py b/examples/ad_manager/v201902/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v201805/creative_service/copy_image_creatives.py rename to examples/ad_manager/v201902/creative_service/copy_image_creatives.py index fdc9d1ca..5f1cb376 100755 --- a/examples/ad_manager/v201805/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201902/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201805') + creative_service = client.GetService('CreativeService', version='v201902') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201805/creative_service/create_creative_from_template.py b/examples/ad_manager/v201902/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v201805/creative_service/create_creative_from_template.py rename to examples/ad_manager/v201902/creative_service/create_creative_from_template.py index 5a95694a..f3dca2ca 100755 --- a/examples/ad_manager/v201805/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201902/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201805') + creative_service = client.GetService('CreativeService', version='v201902') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v201805/creative_service/create_creatives.py b/examples/ad_manager/v201902/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v201805/creative_service/create_creatives.py rename to examples/ad_manager/v201902/creative_service/create_creatives.py index 93a142af..720383ff 100755 --- a/examples/ad_manager/v201805/creative_service/create_creatives.py +++ b/examples/ad_manager/v201902/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201805') + creative_service = client.GetService('CreativeService', version='v201902') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v201805/creative_service/create_custom_creative.py b/examples/ad_manager/v201902/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v201805/creative_service/create_custom_creative.py rename to examples/ad_manager/v201902/creative_service/create_custom_creative.py index c616a98e..2af78804 100755 --- a/examples/ad_manager/v201805/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201902/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201805') + creative_service = client.GetService('CreativeService', version='v201902') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v201805/creative_service/create_native_creative.py b/examples/ad_manager/v201902/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v201805/creative_service/create_native_creative.py rename to examples/ad_manager/v201902/creative_service/create_native_creative.py index 5ce65334..71386088 100755 --- a/examples/ad_manager/v201805/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201902/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201805') + creative_service = client.GetService('CreativeService', version='v201902') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v201805/creative_service/get_all_creatives.py b/examples/ad_manager/v201902/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v201805/creative_service/get_all_creatives.py rename to examples/ad_manager/v201902/creative_service/get_all_creatives.py index 61f95466..87b9665e 100755 --- a/examples/ad_manager/v201805/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201902/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201805') + creative_service = client.GetService('CreativeService', version='v201902') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201805/creative_service/get_image_creatives.py b/examples/ad_manager/v201902/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v201805/creative_service/get_image_creatives.py rename to examples/ad_manager/v201902/creative_service/get_image_creatives.py index 79ecfd06..0e5a610b 100755 --- a/examples/ad_manager/v201805/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201902/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201805') + creative_service = client.GetService('CreativeService', version='v201902') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201805/creative_service/update_creatives.py b/examples/ad_manager/v201902/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v201805/creative_service/update_creatives.py rename to examples/ad_manager/v201902/creative_service/update_creatives.py index 690f81b0..5c41d77c 100755 --- a/examples/ad_manager/v201805/creative_service/update_creatives.py +++ b/examples/ad_manager/v201902/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201805') + creative_service = client.GetService('CreativeService', version='v201902') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', long(image_creative_id)) diff --git a/examples/ad_manager/v201805/creative_set_service/__init__.py b/examples/ad_manager/v201902/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/creative_set_service/__init__.py rename to examples/ad_manager/v201902/creative_set_service/__init__.py diff --git a/examples/ad_manager/v201805/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v201805/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py index 6f457caa..fe1bae85 100755 --- a/examples/ad_manager/v201805/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201805') + 'LineItemCreativeAssociationService', version='v201902') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v201805/creative_set_service/create_creative_set.py b/examples/ad_manager/v201902/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v201805/creative_set_service/create_creative_set.py rename to examples/ad_manager/v201902/creative_set_service/create_creative_set.py index d8511130..bd576d69 100755 --- a/examples/ad_manager/v201805/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201902/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201805') + version='v201902') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py index 74a63a41..15102e7c 100755 --- a/examples/ad_manager/v201805/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201805') + 'CreativeSetService', version='v201902') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py index 2c06b55a..c964c417 100755 --- a/examples/ad_manager/v201805/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201805') + 'CreativeSetService', version='v201902') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201805/creative_set_service/update_creative_set.py b/examples/ad_manager/v201902/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v201805/creative_set_service/update_creative_set.py rename to examples/ad_manager/v201902/creative_set_service/update_creative_set.py index 3235512f..bb2943d9 100755 --- a/examples/ad_manager/v201805/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201902/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201805') + version='v201902') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', long(creative_set_id))) diff --git a/examples/ad_manager/v201805/creative_template_service/__init__.py b/examples/ad_manager/v201902/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/creative_template_service/__init__.py rename to examples/ad_manager/v201902/creative_template_service/__init__.py diff --git a/examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py index 444946db..7a8e57ec 100755 --- a/examples/ad_manager/v201805/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201805') + 'CreativeTemplateService', version='v201902') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py index ac4b59d1..7ef20636 100755 --- a/examples/ad_manager/v201805/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201805') + 'CreativeTemplateService', version='v201902') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201805/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v201805/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py index b47efa06..89bd2944 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201805') + version='v201902') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py index 6681de03..99f3f5e2 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201805') + version='v201902') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', long(label_id))) diff --git a/examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py index c0c01a29..b7d06f01 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201805') + 'CreativeWrapperService', version='v201902') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py index cc2388e7..a97c5d49 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201805') + 'CreativeWrapperService', version='v201902') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py index d05997d2..815704c4 100755 --- a/examples/ad_manager/v201805/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201805') + version='v201902') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', long(creative_wrapper_id))) diff --git a/examples/ad_manager/v201805/custom_field_service/__init__.py b/examples/ad_manager/v201902/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/custom_field_service/__init__.py rename to examples/ad_manager/v201902/custom_field_service/__init__.py diff --git a/examples/ad_manager/v201805/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v201805/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py index a578a9c3..30f2d7a4 100755 --- a/examples/ad_manager/v201805/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201805') + 'CustomFieldService', version='v201902') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v201805/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201902/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v201805/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v201902/custom_field_service/create_custom_fields.py index 29985beb..17429827 100755 --- a/examples/ad_manager/v201805/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201902/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201805') + 'CustomFieldService', version='v201902') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py index 5840d059..cae10f75 100755 --- a/examples/ad_manager/v201805/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201805') + 'CustomFieldService', version='v201902') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py index 61592434..955f84eb 100755 --- a/examples/ad_manager/v201805/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201805') + 'CustomFieldService', version='v201902') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py index ef066a48..0b2fb463 100755 --- a/examples/ad_manager/v201805/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201805') + 'CustomFieldService', version='v201902') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py index b391912b..396156b1 100755 --- a/examples/ad_manager/v201805/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201805') + 'CustomFieldService', version='v201902') - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v201805') + custom_field_statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v201805') + ad_manager.StatementBuilder(version='v201902') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v201805') + line_item_statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201805/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201902/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v201805/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v201902/custom_field_service/update_custom_fields.py index 6063a673..1570f5c0 100755 --- a/examples/ad_manager/v201805/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201902/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201805') + 'CustomFieldService', version='v201902') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :customFieldId') .WithBindVariable('customFieldId', long(custom_field_id))) diff --git a/examples/ad_manager/v201805/custom_targeting_service/__init__.py b/examples/ad_manager/v201902/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/custom_targeting_service/__init__.py rename to examples/ad_manager/v201902/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py index b6ccf3a8..61ce431d 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201805') + 'CustomTargetingService', version='v201902') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py index 2710e977..fb0a1f76 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201805') + 'CustomTargetingService', version='v201902') - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v201805') + key_statement = (ad_manager.StatementBuilder(version='v201902') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py index c2bc4526..2d5b5abb 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201805') + 'CustomTargetingService', version='v201902') - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v201805') + value_statement = (ad_manager.StatementBuilder(version='v201902') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 9b7e0504..b8682e07 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201805') + 'CustomTargetingService', version='v201902') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v201805') + targeting_key_statement = ad_manager.StatementBuilder(version='v201902') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 4bae3542..0efc5e8a 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201805') + 'CustomTargetingService', version='v201902') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v201805') + targeting_key_statement = (ad_manager.StatementBuilder(version='v201902') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py index 3fd9c256..07e59658 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201805') + 'CustomTargetingService', version='v201902') - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :keyId') .WithBindVariable('keyId', long(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py index e5858db8..fece8762 100755 --- a/examples/ad_manager/v201805/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201805') + 'CustomTargetingService', version='v201902') - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', long(key_id))) diff --git a/examples/ad_manager/v201805/exchange_rate_service/__init__.py b/examples/ad_manager/v201902/exchange_rate_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/exchange_rate_service/__init__.py rename to examples/ad_manager/v201902/exchange_rate_service/__init__.py diff --git a/examples/ad_manager/v201805/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py similarity index 96% rename from examples/ad_manager/v201805/exchange_rate_service/create_exchange_rates.py rename to examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py index 3aad543f..7db3116a 100755 --- a/examples/ad_manager/v201805/exchange_rate_service/create_exchange_rates.py +++ b/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201805') + version='v201902') # Create a new fixed exchange rate with currency code 'AUD', with direction # FROM_NETWORK with a value of 1.5. diff --git a/examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py similarity index 94% rename from examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py rename to examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py index 92b95a39..46a916e9 100755 --- a/examples/ad_manager/v201805/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201805') + 'ExchangeRateService', version='v201902') # Create a statement to select exchange rates. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of exchange rates at a time, paging # through until all exchange rates have been retrieved. diff --git a/examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py similarity index 94% rename from examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py rename to examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py index 5e10e96f..f7760c29 100755 --- a/examples/ad_manager/v201805/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -25,9 +25,9 @@ def main(client, currency_code): # Initialize appropriate service. exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201805') + 'ExchangeRateService', version='v201902') # Create a statement to select exchange rates. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('currencyCode = :currencyCode') .WithBindVariable('currencyCode', currency_code)) diff --git a/examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py similarity index 95% rename from examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py rename to examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py index 71eb35a8..da41e186 100755 --- a/examples/ad_manager/v201805/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py @@ -30,10 +30,10 @@ def main(client, exchange_rate_id): # Initialize appropriate service. exchange_rate_service = client.GetService('ExchangeRateService', - version='v201805') + version='v201902') # Create a statement to get an exchange rate by its ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', long(exchange_rate_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py new file mode 100755 index 00000000..a97a7fac --- /dev/null +++ b/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 a forecast for a prospective line item. + +The prospective line item targets the entire network. The targeting can be +modified to determine forecasts for other criteria such as custom criteria +targeting (in addition to targeting the whole network). See +create_line_items.py for an example of how to create more complex targeting. + +""" + + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201902') + network_service = client.GetService('NetworkService', version='v201902') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + + now_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = now_datetime + datetime.timedelta(days=5) + + # Create prospective line item. + line_item = { + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + } + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + }, + 'isAmpOnly': True, + }, + { + 'size': { + 'width': '120', + 'height': '600' + } + } + ], + 'lineItemType': 'SPONSORSHIP', + 'startDateTimeType': 'IMMEDIATELY', + 'endDateTime': end_datetime, + 'costType': 'CPM', + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'primaryGoal': { + 'units': '50', + 'unitType': 'IMPRESSIONS', + 'goalType': 'DAILY' + }, + 'contractedUnitsBought': '100', + 'creativeRotationType': 'EVEN', + 'discountType': 'PERCENTAGE', + } + + prospective_line_item = { + 'lineItem': line_item, + 'advertiserId': advertiser_id + } + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + # The field includeTargetingCriteriaBreakdown can only be set if + # breakdowns are not manually specified. + # 'includeTargetingCriteriaBreakdown': True, + 'breakdown': { + 'timeWindows': [ + now_datetime, + now_datetime + datetime.timedelta(days=1), + now_datetime + datetime.timedelta(days=2), + now_datetime + datetime.timedelta(days=3), + now_datetime + datetime.timedelta(days=4), + end_datetime + ], + 'targets': [ + { + # Optional, the name field is only used to identify this + # breakdown in the response. + 'name': 'United States', + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '2840', + 'displayName': 'US' + } + ] + } + } + }, + { + # Optional, the name field is only used to identify this + # breakdown in the response. + 'name': 'Geneva', + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '20133', + 'displayName': 'Geneva' + } + ] + } + } + } + ] + } + } + + # Get forecast. + forecast = forecast_service.getAvailabilityForecast( + prospective_line_item, forecast_options) + matched = forecast['matchedUnits'] + available = forecast['availableUnits'] + possible = forecast['possibleUnits'] if 'possibleUnits' in forecast else None + unit_type = forecast['unitType'].lower() + + available_percent_overall, possible_percent_overall = CalculateForecastStats( + matched, available, possible) + + contending_line_items = getattr(forecast, 'contendingLineItems', []) + + # Display results. + print '%s %s matched overall.' % (matched, unit_type) + print '%s%% %s available overall.' % (available_percent_overall, unit_type) + print '%d contending line items overall.' % len(contending_line_items) + if possible: + print '%s%% %s possible overall.' % (possible_percent_overall, unit_type) + + if 'breakdowns' in forecast and len(forecast['breakdowns']): + for breakdown in forecast['breakdowns']: + print 'For breakdown time period %s - %s:' % ( + FormatSOAPDateTime(breakdown['startTime']), + FormatSOAPDateTime(breakdown['endTime'])) + for breakdown_entry in breakdown['breakdownEntries']: + matched = breakdown_entry['forecast']['matched'] + available = breakdown_entry['forecast']['available'] + possible = (breakdown_entry['forecast']['possible'] + if 'possible' in breakdown_entry['forecast'] else None) + name = breakdown_entry['name'] if 'name' in breakdown_entry else None + if name: + print '\tFor targeting breakdown named \'%s\'' % name + available_percent, possible_percent = CalculateForecastStats( + matched, available, possible) + print '\t\t%s %s matched.' % (matched, unit_type) + print '\t\t%s%% %s available.' % (available_percent, unit_type) + if possible: + print '\t\t%s%% %s possible.' % (possible_percent, unit_type) + + +def FormatSOAPDateTime(value): + """Format a SOAP DateTime object for printing. + + Args: + value: The DateTime object to format. + + Returns: + A string representing the value. + """ + value_date = value['date'] + return '%s-%s-%s %s:%s:%s (%s)' % ( + value_date['year'], value_date['month'], value_date['day'], + value['hour'], value['minute'], value['second'], value['timeZoneId']) + + +def CalculateForecastStats(matched, available, possible=None): + """Calculate forecast percentage stats. + + Args: + matched: The number of matched impressions. + available: The number of available impressions. + possible: The optional number of possible impressions. + + Returns: + The percentage of impressions that are available and possible. + """ + if matched > 0: + available_percent = (float(available) / matched) * 100. + else: + available_percent = 0 + + if possible is not None: + if matched > 0: + possible_percent = (possible/float(matched)) * 100. + else: + possible_percent = 0 + else: + possible_percent = None + + return available_percent, possible_percent + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201805/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v201805/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py index 15eba4c5..8fceb1c9 100755 --- a/examples/ad_manager/v201805/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201805') + forecast_service = client.GetService('ForecastService', version='v201902') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v201805/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v201805/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py index 98360a34..438b3b86 100755 --- a/examples/ad_manager/v201805/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201805') + forecast_service = client.GetService('ForecastService', version='v201902') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v201805/inventory_service/__init__.py b/examples/ad_manager/v201902/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/inventory_service/__init__.py rename to examples/ad_manager/v201902/inventory_service/__init__.py diff --git a/examples/ad_manager/v201805/inventory_service/archive_ad_units.py b/examples/ad_manager/v201902/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v201805/inventory_service/archive_ad_units.py rename to examples/ad_manager/v201902/inventory_service/archive_ad_units.py index a02e530e..d1fbf0ec 100755 --- a/examples/ad_manager/v201805/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201805') + inventory_service = client.GetService('InventoryService', version='v201902') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', long(parent_id))) diff --git a/examples/ad_manager/v201805/inventory_service/create_ad_units.py b/examples/ad_manager/v201902/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v201805/inventory_service/create_ad_units.py rename to examples/ad_manager/v201902/inventory_service/create_ad_units.py index b9d581fd..93867bcc 100755 --- a/examples/ad_manager/v201805/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201805') + inventory_service = client.GetService('InventoryService', version='v201902') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py index b32d9731..b3b7e7c7 100755 --- a/examples/ad_manager/v201805/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201805') - inventory_service = client.GetService('InventoryService', version='v201805') + network_service = client.GetService('NetworkService', version='v201902') + inventory_service = client.GetService('InventoryService', version='v201902') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201902/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v201902/inventory_service/get_all_ad_unit_sizes.py index ab6b3f21..6405df08 100755 --- a/examples/ad_manager/v201805/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201902/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201805') + 'InventoryService', version='v201902') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201805/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201902/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v201805/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v201902/inventory_service/get_all_ad_units.py index ae462b25..93470f03 100755 --- a/examples/ad_manager/v201805/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201805') + ad_unit_service = client.GetService('InventoryService', version='v201902') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py index 37f23fea..76e772d8 100755 --- a/examples/ad_manager/v201805/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201805') - inventory_service = client.GetService('InventoryService', version='v201805') + network_service = client.GetService('NetworkService', version='v201902') + inventory_service = client.GetService('InventoryService', version='v201902') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201805/inventory_service/update_ad_units.py b/examples/ad_manager/v201902/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v201805/inventory_service/update_ad_units.py rename to examples/ad_manager/v201902/inventory_service/update_ad_units.py index 81ad312b..3ae7463c 100755 --- a/examples/ad_manager/v201805/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201805') + inventory_service = client.GetService('InventoryService', version='v201902') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201805/label_service/__init__.py b/examples/ad_manager/v201902/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/label_service/__init__.py rename to examples/ad_manager/v201902/label_service/__init__.py diff --git a/examples/ad_manager/v201805/label_service/create_labels.py b/examples/ad_manager/v201902/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v201805/label_service/create_labels.py rename to examples/ad_manager/v201902/label_service/create_labels.py index b20d152e..33506d7c 100755 --- a/examples/ad_manager/v201805/label_service/create_labels.py +++ b/examples/ad_manager/v201902/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201805') + label_service = client.GetService('LabelService', version='v201902') # Create label objects. labels = [] diff --git a/examples/ad_manager/v201805/label_service/deactivate_labels.py b/examples/ad_manager/v201902/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v201805/label_service/deactivate_labels.py rename to examples/ad_manager/v201902/label_service/deactivate_labels.py index 57fdacad..8cd7e7ca 100755 --- a/examples/ad_manager/v201805/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201902/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201805') + label_service = client.GetService('LabelService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201805/label_service/get_active_labels.py b/examples/ad_manager/v201902/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v201805/label_service/get_active_labels.py rename to examples/ad_manager/v201902/label_service/get_active_labels.py index ea5b51dd..2d9edc7a 100755 --- a/examples/ad_manager/v201805/label_service/get_active_labels.py +++ b/examples/ad_manager/v201902/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201805') + label_service = client.GetService('LabelService', version='v201902') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201805/label_service/get_all_labels.py b/examples/ad_manager/v201902/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v201805/label_service/get_all_labels.py rename to examples/ad_manager/v201902/label_service/get_all_labels.py index 9d04ace1..fa622592 100755 --- a/examples/ad_manager/v201805/label_service/get_all_labels.py +++ b/examples/ad_manager/v201902/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201805') + label_service = client.GetService('LabelService', version='v201902') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201805/label_service/update_labels.py b/examples/ad_manager/v201902/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v201805/label_service/update_labels.py rename to examples/ad_manager/v201902/label_service/update_labels.py index aa6f4243..a45f310f 100755 --- a/examples/ad_manager/v201805/label_service/update_labels.py +++ b/examples/ad_manager/v201902/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201805') + label_service = client.GetService('LabelService', version='v201902') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :labelId') .WithBindVariable('labelId', long(label_id))) diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201902/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v201902/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v201805/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py index ca662ddb..808db1ae 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201805') + 'LineItemCreativeAssociationService', version='v201902') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py index efbafe02..2b473f41 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201805') + 'LineItemCreativeAssociationService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', long(line_item_id))) diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py index 17dfd485..b112d047 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201805') + 'LineItemCreativeAssociationService', version='v201902') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py index 187383b0..01d0005d 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201805') + 'LineItemCreativeAssociationService', version='v201902') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py index cd82fc0b..ecc5a621 100755 --- a/examples/ad_manager/v201805/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201805') + 'LineItemCreativeAssociationService', version='v201902') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201805/line_item_service/__init__.py b/examples/ad_manager/v201902/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/line_item_service/__init__.py rename to examples/ad_manager/v201902/line_item_service/__init__.py diff --git a/examples/ad_manager/v201805/line_item_service/activate_line_items.py b/examples/ad_manager/v201902/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v201805/line_item_service/activate_line_items.py rename to examples/ad_manager/v201902/line_item_service/activate_line_items.py index dcb9f64f..bf6870ba 100755 --- a/examples/ad_manager/v201805/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201805/line_item_service/create_line_items.py b/examples/ad_manager/v201902/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v201805/line_item_service/create_line_items.py rename to examples/ad_manager/v201902/line_item_service/create_line_items.py index 369ce8e8..7dbcfca4 100755 --- a/examples/ad_manager/v201805/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201805/line_item_service/create_video_line_item.py b/examples/ad_manager/v201902/line_item_service/create_video_line_item.py similarity index 53% rename from examples/ad_manager/v201805/line_item_service/create_video_line_item.py rename to examples/ad_manager/v201902/line_item_service/create_video_line_item.py index c43fd2d4..b599884a 100755 --- a/examples/ad_manager/v201805/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v201902/line_item_service/create_video_line_item.py @@ -16,14 +16,9 @@ """This code example creates a new line item to serve to video content. -This feature is only available to Ad Manager 360 solution networks. To determine -which line items exist, run get_all_line_items.py. To determine which orders -exist, run get_all_orders.py. To create a video ad unit, run -create_video_ad_unit.py. To create criteria for categories, run -create_custom_targeting_keys_and_values.py. +This feature is only available to Ad Manager 360 solution networks. """ - import datetime import uuid @@ -36,18 +31,18 @@ ORDER_ID = 'INSERT_ORDER_ID_HERE' TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE' -# Set the custom targeting value ID representing the metadata -# on the content to target. This would typically be from a key representing -# a "genre" and the value representing something like "comedy". The value -# must be from a key in a content metadata key hierarchy. -CONTENT_CUSTOM_TARGETING_VALUE_ID = ( - 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE') +# Set the video content to target. +CONTENT_ID = 'INSERT_CONTENT_ID_HERE' +# Set the video content bundle to target. +CONTENT_BUNDLE_ID = 'INSERT_CONTENT_BUNDLE_ID_HERE' +# Set the CMS metadata value to target. +CMS_METADATA_VALUE_ID = 'INSERT_CMS_METADATA_VALUE_ID_HERE' -def main(client, order_id, targeted_video_ad_unit_id, - content_custom_targeting_value_id): +def main(client, order_id, targeted_video_ad_unit_id, content_id, + content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) @@ -58,47 +53,51 @@ def main(client, order_id, targeted_video_ad_unit_id, 'orderId': order_id, 'targeting': { 'contentTargeting': { - 'targetedContentMetadata': [ - {'customTargetingValueIds': [ - content_custom_targeting_value_id]} - ] + 'targetedContentIds': [content_id], + 'targetedVideoContentBundleIds': [content_bundle_id] + }, + 'customTargeting': { + 'logicalOperator': 'AND', + 'children': [{ + 'xsi_type': 'CmsMetadataCriteria', + 'cmsMetadataValueIds': [cms_metadata_value_id], + 'operator': 'EQUALS' + }] }, 'inventoryTargeting': { - 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id, - 'includeDescendants': 'true'}] + 'targetedAdUnits': [{ + 'adUnitId': targeted_video_ad_unit_id, + 'includeDescendants': 'true' + }] + }, + 'requestPlatformTargeting': { + 'targetedRequestPlatforms': ['VIDEO_PLAYER'] }, 'videoPositionTargeting': { - 'targetedPositions': [ - { - 'videoPosition': { - 'positionType': 'PREROLL' - } + 'targetedPositions': [{ + 'videoPosition': { + 'positionType': 'PREROLL' } - ] + }] } }, - 'creativePlaceholders': [ - { + 'creativePlaceholders': [{ + 'size': { + 'width': '400', + 'height': '300' + }, + 'companions': [{ 'size': { - 'width': '400', - 'height': '300' + 'width': '300', + 'height': '250' }, - 'companions': [ - { - 'size': { - 'width': '300', - 'height': '250' - }, - }, - { - 'size': { - 'width': '728', - 'height': '90' - }, - } - ] - } - ], + }, { + 'size': { + 'width': '728', + 'height': '90' + }, + }] + }], 'environmentType': 'VIDEO_PLAYER', 'companionDeliveryOption': 'OPTIONAL', 'startDateTimeType': 'IMMEDIATELY', @@ -121,15 +120,15 @@ def main(client, order_id, targeted_video_ad_unit_id, } # Add line item. - line_item = line_item_service.createLineItem(line_item) + line_item = line_item_service.createLineItems([line_item])[0] # Display results. - print ('Video line item with id "%s", belonging to order id "%s", and ' - 'named "%s" was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print('Video line item with id "%s", belonging to order id "%s", and ' + 'named "%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, - CONTENT_CUSTOM_TARGETING_VALUE_ID) + main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_ID, + CONTENT_BUNDLE_ID, CMS_METADATA_VALUE_ID) diff --git a/examples/ad_manager/v201805/line_item_service/get_all_line_items.py b/examples/ad_manager/v201902/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v201805/line_item_service/get_all_line_items.py rename to examples/ad_manager/v201902/line_item_service/get_all_line_items.py index 981681a3..9d09535b 100755 --- a/examples/ad_manager/v201805/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py index c269080f..f11ca551 100755 --- a/examples/ad_manager/v201805/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py index d941e768..90ad184c 100755 --- a/examples/ad_manager/v201805/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201805/line_item_service/pause_line_items.py b/examples/ad_manager/v201902/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v201805/line_item_service/pause_line_items.py rename to examples/ad_manager/v201902/line_item_service/pause_line_items.py index 468e5f0a..e39a4bc2 100755 --- a/examples/ad_manager/v201805/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201805/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201902/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v201805/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v201902/line_item_service/target_custom_criteria.py index 4cded881..ae925a76 100755 --- a/examples/ad_manager/v201805/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201902/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :lineItemId') .WithBindVariable('lineItemId', long(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/line_item_service/update_line_items.py b/examples/ad_manager/v201902/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v201805/line_item_service/update_line_items.py rename to examples/ad_manager/v201902/line_item_service/update_line_items.py index 6f36b5c8..ee6a5429 100755 --- a/examples/ad_manager/v201805/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', long(order_id)) diff --git a/examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py index 08e8cffc..a4eaa02c 100755 --- a/examples/ad_manager/v201805/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201805') + 'LiveStreamEventService', version='v201902') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201805/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201902/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v201805/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v201902/live_stream_event_service/create_live_stream_events.py index 553310d5..fe485e81 100755 --- a/examples/ad_manager/v201805/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v201902/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201805') + 'LiveStreamEventService', version='v201902') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py index 90272a90..9a833cd2 100755 --- a/examples/ad_manager/v201805/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201805') + 'LiveStreamEventService', version='v201902') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201805/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v201805/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py index 17329278..e066d33f 100755 --- a/examples/ad_manager/v201805/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201805') + 'LiveStreamEventService', version='v201902') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py index 6e33f326..60aa03e4 100755 --- a/examples/ad_manager/v201805/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201805') + 'LiveStreamEventService', version='v201902') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('Id = :id')) .WithBindVariable('id', long(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201805/native_style_service/__init__.py b/examples/ad_manager/v201902/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/native_style_service/__init__.py rename to examples/ad_manager/v201902/native_style_service/__init__.py diff --git a/examples/ad_manager/v201805/native_style_service/create_native_styles.py b/examples/ad_manager/v201902/native_style_service/create_native_styles.py similarity index 97% rename from examples/ad_manager/v201805/native_style_service/create_native_styles.py rename to examples/ad_manager/v201902/native_style_service/create_native_styles.py index d3250bae..810a35bb 100755 --- a/examples/ad_manager/v201805/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201902/native_style_service/create_native_styles.py @@ -99,15 +99,13 @@ width: 100%; border-radius: 20%; } -.title, -.promo-headline { +.title { font-weight: bold; font-size: 14px; line-height: 20px; margin: 8px 8px 4px 8px; } -.title a, -.promo-headline { +.title a { color: rgba(112, 112, 112, 1); text-decoration: none; } @@ -149,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201805') + version='v201902') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v201805/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201902/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v201805/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v201902/native_style_service/get_all_native_styles.py index 5ff6624b..637d72fc 100755 --- a/examples/ad_manager/v201805/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201902/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201805') + version='v201902') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201805/network_service/__init__.py b/examples/ad_manager/v201902/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/network_service/__init__.py rename to examples/ad_manager/v201902/network_service/__init__.py diff --git a/examples/ad_manager/v201805/network_service/get_all_networks.py b/examples/ad_manager/v201902/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v201805/network_service/get_all_networks.py rename to examples/ad_manager/v201902/network_service/get_all_networks.py index 50753106..1be117aa 100755 --- a/examples/ad_manager/v201805/network_service/get_all_networks.py +++ b/examples/ad_manager/v201902/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201805') + network_service = client.GetService('NetworkService', version='v201902') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v201805/network_service/get_current_network.py b/examples/ad_manager/v201902/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v201805/network_service/get_current_network.py rename to examples/ad_manager/v201902/network_service/get_current_network.py index 552cdc4b..7cdb6e98 100755 --- a/examples/ad_manager/v201805/network_service/get_current_network.py +++ b/examples/ad_manager/v201902/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201805') + network_service = client.GetService('NetworkService', version='v201902') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201805/network_service/make_test_network.py b/examples/ad_manager/v201902/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v201805/network_service/make_test_network.py rename to examples/ad_manager/v201902/network_service/make_test_network.py index dae252d4..ceb088fd 100755 --- a/examples/ad_manager/v201805/network_service/make_test_network.py +++ b/examples/ad_manager/v201902/network_service/make_test_network.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201805') + network_service = client.GetService('NetworkService', version='v201902') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v201805/order_service/__init__.py b/examples/ad_manager/v201902/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/order_service/__init__.py rename to examples/ad_manager/v201902/order_service/__init__.py diff --git a/examples/ad_manager/v201805/order_service/approve_orders.py b/examples/ad_manager/v201902/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v201805/order_service/approve_orders.py rename to examples/ad_manager/v201902/order_service/approve_orders.py index b173e3d8..e0e09d5a 100755 --- a/examples/ad_manager/v201805/order_service/approve_orders.py +++ b/examples/ad_manager/v201902/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201805') + order_service = client.GetService('OrderService', version='v201902') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201805/order_service/create_orders.py b/examples/ad_manager/v201902/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v201805/order_service/create_orders.py rename to examples/ad_manager/v201902/order_service/create_orders.py index 04ba75ea..76325017 100755 --- a/examples/ad_manager/v201805/order_service/create_orders.py +++ b/examples/ad_manager/v201902/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201805') + order_service = client.GetService('OrderService', version='v201902') # Create order objects. orders = [] diff --git a/examples/ad_manager/v201805/order_service/get_all_orders.py b/examples/ad_manager/v201902/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v201805/order_service/get_all_orders.py rename to examples/ad_manager/v201902/order_service/get_all_orders.py index 24290f92..454d17d3 100755 --- a/examples/ad_manager/v201805/order_service/get_all_orders.py +++ b/examples/ad_manager/v201902/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201805') + order_service = client.GetService('OrderService', version='v201902') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201805/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201902/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v201805/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v201902/order_service/get_orders_starting_soon.py index af135d41..3af80f10 100755 --- a/examples/ad_manager/v201805/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201902/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201805') + order_service = client.GetService('OrderService', version='v201902') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201805/order_service/update_orders.py b/examples/ad_manager/v201902/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v201805/order_service/update_orders.py rename to examples/ad_manager/v201902/order_service/update_orders.py index f7e4d1d6..af844b09 100755 --- a/examples/ad_manager/v201805/order_service/update_orders.py +++ b/examples/ad_manager/v201902/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201805') + order_service = client.GetService('OrderService', version='v201902') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :orderId') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201805/package_service/create_packages.py b/examples/ad_manager/v201902/package_service/create_packages.py similarity index 99% rename from examples/ad_manager/v201805/package_service/create_packages.py rename to examples/ad_manager/v201902/package_service/create_packages.py index 29c12353..2264039f 100755 --- a/examples/ad_manager/v201805/package_service/create_packages.py +++ b/examples/ad_manager/v201902/package_service/create_packages.py @@ -37,7 +37,7 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201805') + package_service = client.GetService('PackageService', version='v201902') # Create local package. package = { diff --git a/examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py similarity index 96% rename from examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py rename to examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py index 6356c1c6..905a2546 100755 --- a/examples/ad_manager/v201805/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201805') + package_service = client.GetService('PackageService', version='v201902') # Create a statement to select the single package. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/package_service/get_all_packages.py b/examples/ad_manager/v201902/package_service/get_all_packages.py similarity index 96% rename from examples/ad_manager/v201805/package_service/get_all_packages.py rename to examples/ad_manager/v201902/package_service/get_all_packages.py index 947bbf71..4a470442 100755 --- a/examples/ad_manager/v201805/package_service/get_all_packages.py +++ b/examples/ad_manager/v201902/package_service/get_all_packages.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201805') + pkg_service = client.GetService('PackageService', version='v201902') # Create a statement to select packages. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of packages at a time, paging # through until all packages have been retrieved. diff --git a/examples/ad_manager/v201805/package_service/get_in_progress_packages.py b/examples/ad_manager/v201902/package_service/get_in_progress_packages.py similarity index 96% rename from examples/ad_manager/v201805/package_service/get_in_progress_packages.py rename to examples/ad_manager/v201902/package_service/get_in_progress_packages.py index 1093281b..80c32207 100755 --- a/examples/ad_manager/v201805/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201902/package_service/get_in_progress_packages.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201805') + pkg_service = client.GetService('PackageService', version='v201902') # Create a statement to select packages. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status') .WithBindVariable('status', 'IN_PROGRESS')) diff --git a/examples/ad_manager/v201805/placement_service/create_placements.py b/examples/ad_manager/v201902/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v201805/placement_service/create_placements.py rename to examples/ad_manager/v201902/placement_service/create_placements.py index 4940aed9..08820a6f 100755 --- a/examples/ad_manager/v201805/placement_service/create_placements.py +++ b/examples/ad_manager/v201902/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201805') - inventory_service = client.GetService('InventoryService', version='v201805') + placement_service = client.GetService('PlacementService', version='v201902') + inventory_service = client.GetService('InventoryService', version='v201902') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201805/placement_service/deactivate_placements.py b/examples/ad_manager/v201902/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v201805/placement_service/deactivate_placements.py rename to examples/ad_manager/v201902/placement_service/deactivate_placements.py index 7b031b54..110f4a45 100755 --- a/examples/ad_manager/v201805/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201902/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201805') + placement_service = client.GetService('PlacementService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :placementId') .WithBindVariable('placementId', long(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/placement_service/get_active_placements.py b/examples/ad_manager/v201902/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v201805/placement_service/get_active_placements.py rename to examples/ad_manager/v201902/placement_service/get_active_placements.py index 15c8fa98..59deef1e 100755 --- a/examples/ad_manager/v201805/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201902/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201805') + placement_service = client.GetService('PlacementService', version='v201902') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/placement_service/get_all_placements.py b/examples/ad_manager/v201902/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v201805/placement_service/get_all_placements.py rename to examples/ad_manager/v201902/placement_service/get_all_placements.py index 99785473..8fb62438 100755 --- a/examples/ad_manager/v201805/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201902/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201805') + placement_service = client.GetService('PlacementService', version='v201902') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201805/placement_service/update_placements.py b/examples/ad_manager/v201902/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v201805/placement_service/update_placements.py rename to examples/ad_manager/v201902/placement_service/update_placements.py index c66a8f8b..df203ffc 100755 --- a/examples/ad_manager/v201805/placement_service/update_placements.py +++ b/examples/ad_manager/v201902/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201805') + placement_service = client.GetService('PlacementService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/premium_rate_service/__init__.py b/examples/ad_manager/v201902/premium_rate_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/premium_rate_service/__init__.py rename to examples/ad_manager/v201902/premium_rate_service/__init__.py diff --git a/examples/ad_manager/v201805/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py similarity index 97% rename from examples/ad_manager/v201805/premium_rate_service/create_premium_rates.py rename to examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py index 3ede39a6..032ca707 100755 --- a/examples/ad_manager/v201805/premium_rate_service/create_premium_rates.py +++ b/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py @@ -28,7 +28,7 @@ def main(client, rate_card_id): # Initialize appropriate services. premium_rate_service = client.GetService('PremiumRateService', - version='v201805') + version='v201902') # Create an ad unit premium to apply to the rate card. ad_unit_premium_feature = { diff --git a/examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py similarity index 94% rename from examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py rename to examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py index d4c6a8ed..752a7866 100755 --- a/examples/ad_manager/v201805/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201805') + 'PremiumRateService', version='v201902') # Create a statement to select premium rates. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of premium rates at a time, paging # through until all premium rates have been retrieved. diff --git a/examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py similarity index 95% rename from examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py rename to examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py index fd67b3c0..7148e347 100755 --- a/examples/ad_manager/v201805/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py @@ -25,9 +25,9 @@ def main(client, rate_card_id): # Initialize appropriate service. premium_rate_service = client.GetService( - 'PremiumRateService', version='v201805') + 'PremiumRateService', version='v201902') # Create a statement to select premium rates. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('rateCardId = :rateCardId') .WithBindVariable('rateCardId', rate_card_id)) diff --git a/examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py similarity index 95% rename from examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py rename to examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py index 5180551f..8cf63bad 100755 --- a/examples/ad_manager/v201805/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py @@ -30,10 +30,10 @@ def main(client, premium_rate_id): # Initialize appropriate service. premium_rate_service = client.GetService('PremiumRateService', - version='v201805') + version='v201902') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(premium_rate_id)) diff --git a/examples/ad_manager/v201805/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py similarity index 99% rename from examples/ad_manager/v201805/product_package_item_service/create_product_package_item.py rename to examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py index e7615951..1a950077 100755 --- a/examples/ad_manager/v201805/product_package_item_service/create_product_package_item.py +++ b/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py @@ -32,7 +32,7 @@ def main(client): product_package_item_service = client.GetService('ProductPackageItemService', - version='v201805') + version='v201902') product_package_item = { # Set the product from which the product package item is created. diff --git a/examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py similarity index 94% rename from examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py rename to examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py index f74613d0..31a6055a 100755 --- a/examples/ad_manager/v201805/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201805') + 'ProductPackageItemService', version='v201902') # Create a statement to select product package items. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of product package items at a time, paging # through until all product package items have been retrieved. diff --git a/examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py similarity index 94% rename from examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py rename to examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py index a694e7fd..1dfeaad6 100755 --- a/examples/ad_manager/v201805/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py @@ -25,9 +25,9 @@ def main(client, product_package_id): # Initialize appropriate service. product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201805') + 'ProductPackageItemService', version='v201902') # Create a statement to select product package items. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('productPackageId = :productPackageId') .WithBindVariable('productPackageId', product_package_id)) diff --git a/examples/ad_manager/v201805/product_package_service/create_product_packages.py b/examples/ad_manager/v201902/product_package_service/create_product_packages.py similarity index 96% rename from examples/ad_manager/v201805/product_package_service/create_product_packages.py rename to examples/ad_manager/v201902/product_package_service/create_product_packages.py index 7470acbe..bc297c78 100755 --- a/examples/ad_manager/v201805/product_package_service/create_product_packages.py +++ b/examples/ad_manager/v201902/product_package_service/create_product_packages.py @@ -30,7 +30,7 @@ def main(client): product_package_service = client.GetService('ProductPackageService', - version='v201805') + version='v201902') # Create a local product package. product_package = { diff --git a/examples/ad_manager/v201805/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py similarity index 94% rename from examples/ad_manager/v201805/product_package_service/get_active_product_packages.py rename to examples/ad_manager/v201902/product_package_service/get_active_product_packages.py index c252ea98..b93b1d41 100755 --- a/examples/ad_manager/v201805/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201805') + 'ProductPackageService', version='v201902') # Create a statement to select product packages. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201805/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py similarity index 94% rename from examples/ad_manager/v201805/product_package_service/get_all_product_packages.py rename to examples/ad_manager/v201902/product_package_service/get_all_product_packages.py index 7f550a79..513280a6 100755 --- a/examples/ad_manager/v201805/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. product_package_service = client.GetService( - 'ProductPackageService', version='v201805') + 'ProductPackageService', version='v201902') # Create a statement to select product packages. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of product packages at a time, paging # through until all product packages have been retrieved. diff --git a/examples/ad_manager/v201805/product_service/__init__.py b/examples/ad_manager/v201902/product_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/product_service/__init__.py rename to examples/ad_manager/v201902/product_service/__init__.py diff --git a/examples/ad_manager/v201805/product_service/get_all_products.py b/examples/ad_manager/v201902/product_service/get_all_products.py similarity index 95% rename from examples/ad_manager/v201805/product_service/get_all_products.py rename to examples/ad_manager/v201902/product_service/get_all_products.py index bf38d449..d8e67253 100755 --- a/examples/ad_manager/v201805/product_service/get_all_products.py +++ b/examples/ad_manager/v201902/product_service/get_all_products.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201805') + product_service = client.GetService('ProductService', version='v201902') # Create a statement to select products. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of products at a time, paging # through until all products have been retrieved. diff --git a/examples/ad_manager/v201805/product_service/get_products_for_product_template.py b/examples/ad_manager/v201902/product_service/get_products_for_product_template.py similarity index 96% rename from examples/ad_manager/v201805/product_service/get_products_for_product_template.py rename to examples/ad_manager/v201902/product_service/get_products_for_product_template.py index 4b2c7773..70fea594 100755 --- a/examples/ad_manager/v201805/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201902/product_service/get_products_for_product_template.py @@ -24,10 +24,10 @@ def main(client, product_template_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201805') + product_service = client.GetService('ProductService', version='v201902') # Create a statement to select products. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('productTemplateId = :productTemplateId') .WithBindVariable('productTemplateId', product_template_id)) diff --git a/examples/ad_manager/v201805/product_service/update_products.py b/examples/ad_manager/v201902/product_service/update_products.py similarity index 96% rename from examples/ad_manager/v201805/product_service/update_products.py rename to examples/ad_manager/v201902/product_service/update_products.py index 9d8b257a..501491c0 100755 --- a/examples/ad_manager/v201805/product_service/update_products.py +++ b/examples/ad_manager/v201902/product_service/update_products.py @@ -29,10 +29,10 @@ def main(client, product_id): # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201805') + product_service = client.GetService('ProductService', version='v201902') # Create statement object to select a single product by an ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', long(product_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/product_template_service/__init__.py b/examples/ad_manager/v201902/product_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/product_template_service/__init__.py rename to examples/ad_manager/v201902/product_template_service/__init__.py diff --git a/examples/ad_manager/v201805/product_template_service/activate_product_templates.py b/examples/ad_manager/v201902/product_template_service/activate_product_templates.py similarity index 95% rename from examples/ad_manager/v201805/product_template_service/activate_product_templates.py rename to examples/ad_manager/v201902/product_template_service/activate_product_templates.py index 658be073..89a5a5c8 100755 --- a/examples/ad_manager/v201805/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/activate_product_templates.py @@ -31,10 +31,10 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201805') + 'ProductTemplateService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', long(product_template_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/product_template_service/create_product_templates.py b/examples/ad_manager/v201902/product_template_service/create_product_templates.py similarity index 97% rename from examples/ad_manager/v201805/product_template_service/create_product_templates.py rename to examples/ad_manager/v201902/product_template_service/create_product_templates.py index 0ab720cc..575c7d44 100755 --- a/examples/ad_manager/v201805/product_template_service/create_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/create_product_templates.py @@ -28,9 +28,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201805') + 'ProductTemplateService', version='v201902') network_service = client.GetService( - 'NetworkService', version='v201805') + 'NetworkService', version='v201902') # Create a product template. product_template = { diff --git a/examples/ad_manager/v201805/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py similarity index 96% rename from examples/ad_manager/v201805/product_template_service/create_programmatic_product_templates.py rename to examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py index a52d0999..11ab2fbf 100755 --- a/examples/ad_manager/v201805/product_template_service/create_programmatic_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py @@ -25,9 +25,9 @@ def main(client): product_template_service = client.GetService( - 'ProductTemplateService', version='v201805') + 'ProductTemplateService', version='v201902') network_service = client.GetService( - 'NetworkService', version='v201805') + 'NetworkService', version='v201902') product_template = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201805/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201902/product_template_service/get_all_product_templates.py similarity index 94% rename from examples/ad_manager/v201805/product_template_service/get_all_product_templates.py rename to examples/ad_manager/v201902/product_template_service/get_all_product_templates.py index e1c968d4..88bbfb8e 100755 --- a/examples/ad_manager/v201805/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/get_all_product_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201805') + 'ProductTemplateService', version='v201902') # Create a statement to select product templates. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of product templates at a time, paging # through until all product templates have been retrieved. diff --git a/examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py similarity index 94% rename from examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py rename to examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py index bce68e6f..01f171f4 100755 --- a/examples/ad_manager/v201805/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201805') + 'ProductTemplateService', version='v201902') # Create a statement to select product templates. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('lineItemType = :lineItemType') .WithBindVariable('lineItemType', 'SPONSORSHIP')) diff --git a/examples/ad_manager/v201805/product_template_service/update_product_templates.py b/examples/ad_manager/v201902/product_template_service/update_product_templates.py similarity index 96% rename from examples/ad_manager/v201805/product_template_service/update_product_templates.py rename to examples/ad_manager/v201902/product_template_service/update_product_templates.py index b79cbcef..a4d9f342 100755 --- a/examples/ad_manager/v201805/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/update_product_templates.py @@ -30,10 +30,10 @@ def main(client, product_template_id): # Initialize appropriate service. product_template_service = client.GetService( - 'ProductTemplateService', version='v201805') + 'ProductTemplateService', version='v201902') # Create a statement to select a single product template by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', long(product_template_id)) diff --git a/examples/ad_manager/v201805/proposal_line_item_service/__init__.py b/examples/ad_manager/v201902/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/proposal_line_item_service/__init__.py rename to examples/ad_manager/v201902/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py index 1566c1da..82c64c49 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201805') + 'ProposalLineItemService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py rename to examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py index 85074dd9..2ab6c859 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -40,8 +40,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201805') - network_service = client.GetService('NetworkService', version='v201805') + 'ProposalLineItemService', version='v201902') + network_service = client.GetService('NetworkService', version='v201902') # Get the root ad unit to target. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py similarity index 88% rename from examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index ef3d2264..d6bc8219 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -34,8 +34,8 @@ def main(client, proposal_id, product_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201805') - network_service = client.GetService('NetworkService', version='v201805') + 'ProposalLineItemService', version='v201902') + network_service = client.GetService('NetworkService', version='v201902') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) @@ -60,6 +60,13 @@ def main(client, proposal_id, product_id): 'targetedAdUnits': { 'adUnitId': root_ad_unit_id } + }, + # Target Display environment by excluding Mobile Apps. + # DeviceCapabilities can be obtained though the Device_Capability PQL + # table: + # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService + 'technologyTargeting': { + 'deviceCapabilityTargeting': [{'id': 5005}] } }, 'startDateTime': start_datetime, @@ -79,10 +86,6 @@ def main(client, proposal_id, product_id): 'units': '1000', 'unitType': 'IMPRESSIONS', }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, 'netRate': { 'currencyCode': 'USD', 'microAmount': '2000000' diff --git a/examples/ad_manager/v201805/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v201805/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py index 29b2c63d..6d72e8a5 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py @@ -42,8 +42,8 @@ def main(client, proposal_id, product_id, rate_card_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201805') - network_service = client.GetService('NetworkService', version='v201805') + 'ProposalLineItemService', version='v201902') + network_service = client.GetService('NetworkService', version='v201902') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py index 28cf4be5..8df2e2dc 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201805') + 'ProposalLineItemService', version='v201902') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 319c1fc4..8fd23187 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201805') + 'ProposalLineItemService', version='v201902') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py index 46390d4f..68c70045 100755 --- a/examples/ad_manager/v201805/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201805') + 'ProposalLineItemService', version='v201902') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', long(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/proposal_service/__init__.py b/examples/ad_manager/v201902/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/proposal_service/__init__.py rename to examples/ad_manager/v201902/proposal_service/__init__.py diff --git a/examples/ad_manager/v201805/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals.py similarity index 99% rename from examples/ad_manager/v201805/proposal_service/create_programmatic_proposals.py rename to examples/ad_manager/v201902/proposal_service/create_programmatic_proposals.py index 94c5a19a..da97b45f 100755 --- a/examples/ad_manager/v201805/proposal_service/create_programmatic_proposals.py +++ b/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals.py @@ -30,8 +30,8 @@ def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, buyer_id): - proposal_service = client.GetService('ProposalService', version='v201805') - network_service = client.GetService('NetworkService', version='v201805') + proposal_service = client.GetService('ProposalService', version='v201902') + network_service = client.GetService('NetworkService', version='v201902') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals_for_non_sales_management.py similarity index 83% rename from examples/ad_manager/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/ad_manager/v201902/proposal_service/create_programmatic_proposals_for_non_sales_management.py index 6b0910b0..a568913b 100755 --- a/examples/ad_manager/v201805/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -25,12 +25,11 @@ PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' def main(client, programmatic_buyer_id, primary_salesperson_id, - primary_trafficker_id, advertiser_id): - proposal_service = client.GetService('ProposalService', version='v201805') + primary_trafficker_id): + proposal_service = client.GetService('ProposalService', version='v201902') proposal = { # Setting required Marketplace information. @@ -40,17 +39,12 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, }, # Set common required fields for proposals. 'name': 'Proposal #%s' % uuid.uuid4(), - # Set fields that are required before sending the proposal to the buyer. - 'primaryTraffickerId': primary_trafficker_id, - 'sellerContactIds': [primary_salesperson_id], 'primarySalesperson': { 'userId': primary_salesperson_id, 'split': '100000' }, - 'advertiser': { - 'type': 'ADVERTISER', - 'companyId': advertiser_id - }, + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', } proposals = proposal_service.createProposals([proposal]) @@ -65,4 +59,4 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID, ADVERTISER_ID) + PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201805/proposal_service/create_proposals.py b/examples/ad_manager/v201902/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v201805/proposal_service/create_proposals.py rename to examples/ad_manager/v201902/proposal_service/create_proposals.py index a08d39c0..f8b980d8 100755 --- a/examples/ad_manager/v201805/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201902/proposal_service/create_proposals.py @@ -34,8 +34,8 @@ def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201805') - network_service = client.GetService('NetworkService', version='v201805') + proposal_service = client.GetService('ProposalService', version='v201902') + network_service = client.GetService('NetworkService', version='v201902') # Create proposal objects. proposal = { diff --git a/examples/ad_manager/v201805/proposal_service/get_all_proposals.py b/examples/ad_manager/v201902/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v201805/proposal_service/get_all_proposals.py rename to examples/ad_manager/v201902/proposal_service/get_all_proposals.py index 0f235db4..3dd1190f 100755 --- a/examples/ad_manager/v201805/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201902/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201805') + proposal_service = client.GetService('ProposalService', version='v201902') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201805/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v201805/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py index 24651638..bfca57c3 100755 --- a/examples/ad_manager/v201805/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201805') + 'ProposalService', version='v201902') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py similarity index 96% rename from examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py rename to examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py index 8b378510..d7a21239 100755 --- a/examples/ad_manager/v201805/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201805') + proposal_service = client.GetService('ProposalService', version='v201902') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status') .WithBindVariable('status', 'PENDING_APPROVAL')) diff --git a/examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py index 9462df80..4fbd173c 100755 --- a/examples/ad_manager/v201805/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201805') + proposal_service = client.GetService('ProposalService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py similarity index 96% rename from examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py rename to examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py index 98305b25..743bca8e 100755 --- a/examples/ad_manager/v201805/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py @@ -28,10 +28,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201805') + proposal_service = client.GetService('ProposalService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_approved = 0 diff --git a/examples/ad_manager/v201805/proposal_service/update_proposals.py b/examples/ad_manager/v201902/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v201805/proposal_service/update_proposals.py rename to examples/ad_manager/v201902/proposal_service/update_proposals.py index 9c2cc804..a63804f5 100755 --- a/examples/ad_manager/v201805/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201902/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201805') + proposal_service = client.GetService('ProposalService', version='v201902') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :proposalId') .WithBindVariable('proposalId', long(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/publisher_query_language_service/__init__.py b/examples/ad_manager/v201902/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/publisher_query_language_service/__init__.py rename to examples/ad_manager/v201902/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v201805/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v201805/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py index aa4fee56..0314eb63 100755 --- a/examples/ad_manager/v201805/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201805/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v201805/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py index 4f60f1ca..c4761b9b 100755 --- a/examples/ad_manager/v201805/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v201805/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v201805/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py index d499f3a0..e3e9d842 100755 --- a/examples/ad_manager/v201805/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201805') + data_downloader = client.GetDataDownloader(version='v201902') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201805/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v201805/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py index ef29ba84..0abb46b4 100755 --- a/examples/ad_manager/v201805/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client, geo_target_type): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v201805/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v201805/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py index 62d2f3bc..5e8d8607 100755 --- a/examples/ad_manager/v201805/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py similarity index 97% rename from examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py index 71ef6235..b5243323 100755 --- a/examples/ad_manager/v201805/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201805') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201902') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') @@ -142,7 +142,7 @@ def ConvertDateTimeToOffset(date_time_value): int(date_time_value['minute']), int(date_time_value['second'])) date_time_str = pytz.timezone( - date_time_value['timeZoneID']).localize(date_time_obj).isoformat() + date_time_value['timeZoneId']).localize(date_time_obj).isoformat() if date_time_str[-5:] == '00:00': return date_time_str[:-6] + 'Z' diff --git a/examples/ad_manager/v201805/rate_card_service/__init__.py b/examples/ad_manager/v201902/rate_card_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/rate_card_service/__init__.py rename to examples/ad_manager/v201902/rate_card_service/__init__.py diff --git a/examples/ad_manager/v201805/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py similarity index 99% rename from examples/ad_manager/v201805/rate_card_service/create_rate_cards.py rename to examples/ad_manager/v201902/rate_card_service/create_rate_cards.py index 8615af6a..7f528af2 100755 --- a/examples/ad_manager/v201805/rate_card_service/create_rate_cards.py +++ b/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201805') + rate_card_service = client.GetService('RateCardService', version='v201902') # Create a rate card. rate_card = { diff --git a/examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py similarity index 95% rename from examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py rename to examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py index c344d746..8f73fed3 100755 --- a/examples/ad_manager/v201805/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201805') + rate_card_service = client.GetService('RateCardService', version='v201902') # Create a statement to select rate cards. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of rate cards at a time, paging # through until all rate cards have been retrieved. diff --git a/examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py similarity index 96% rename from examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py rename to examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py index 971cbc0b..7a48f1ed 100755 --- a/examples/ad_manager/v201805/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201805') + rate_card_service = client.GetService('RateCardService', version='v201902') # Create a statement to select rate cards. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('forMarketplace = :forMarketplace') .WithBindVariable('forMarketplace', True)) diff --git a/examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py similarity index 95% rename from examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py rename to examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 7cf68312..ad7620e0 100755 --- a/examples/ad_manager/v201805/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201805')) + 'ReconciliationLineItemReportService', version='v201902')) # Create a statement to select reconciliation line item reports. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('reconciliationReportId = :reconciliationReportId AND ' 'lineItemId != :lineItemId')) .OrderBy('lineItemId', ascending=True) diff --git a/examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py similarity index 95% rename from examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py rename to examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 88e67bf9..5923eb8e 100755 --- a/examples/ad_manager/v201805/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201805')) + 'ReconciliationLineItemReportService', version='v201902')) # Create a statement to select a reconciliation line item report. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :lineItemReportId') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py similarity index 94% rename from examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py rename to examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 0f80ca96..4ef8f0d5 100755 --- a/examples/ad_manager/v201805/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -25,9 +25,9 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201805') + 'ReconciliationOrderReportService', version='v201902') # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('reconciliationReportId = :reconciliationReportId') .WithBindVariable('reconciliationReportId', reconciliation_report_id)) diff --git a/examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py similarity index 95% rename from examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py rename to examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 623acce9..69850233 100755 --- a/examples/ad_manager/v201805/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -30,10 +30,10 @@ def main(client): # Initialize appropriate service. reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201805')) + 'ReconciliationOrderReportService', version='v201902')) # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py similarity index 95% rename from examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py rename to examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 19383c97..4df9fcb7 100755 --- a/examples/ad_manager/v201805/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -27,10 +27,10 @@ def main(client, reconciliation_report_id): # Initialize appropriate service. reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201805') + 'ReconciliationReportRowService', version='v201902') # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) diff --git a/examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py similarity index 95% rename from examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py rename to examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py index c9219ca9..8e0e4ffa 100755 --- a/examples/ad_manager/v201805/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -33,10 +33,10 @@ def main(client): # Initialize appropriate service. reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201805')) + 'ReconciliationReportRowService', version='v201902')) # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('id = :reconciliationReportRowId AND ' 'reconciliationReportId = :reconciliationReportId')) .OrderBy('id', ascending=True) diff --git a/examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py similarity index 94% rename from examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py rename to examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py index 9cbfd6c6..d4b2c76c 100755 --- a/examples/ad_manager/v201805/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201805') + 'ReconciliationReportService', version='v201902') # Create a statement to select reconciliation reports. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of reconciliation reports at a time, paging # through until all reconciliation reports have been retrieved. diff --git a/examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py similarity index 94% rename from examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py rename to examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index ca25f470..889ed713 100755 --- a/examples/ad_manager/v201805/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201805') + 'ReconciliationReportService', version='v201902') first_of_the_month = date.today().replace(day=1) last_month = first_of_the_month - timedelta(days=1) # Create a statement to select reconciliation reports. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('startDate = :startDate') .WithBindVariable('startDate', last_month)) diff --git a/examples/ad_manager/v201805/report_service/__init__.py b/examples/ad_manager/v201902/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/report_service/__init__.py rename to examples/ad_manager/v201902/report_service/__init__.py diff --git a/examples/ad_manager/v201805/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201902/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v201805/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v201902/report_service/run_ad_exchange_report.py index b66e6606..2d27cc9c 100755 --- a/examples/ad_manager/v201805/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201902/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') # Create report job. report_job = { diff --git a/examples/ad_manager/v201805/report_service/run_delivery_report.py b/examples/ad_manager/v201902/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v201805/report_service/run_delivery_report.py rename to examples/ad_manager/v201902/report_service/run_delivery_report.py index f7795ebb..76f89bb4 100755 --- a/examples/ad_manager/v201805/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201902/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('ORDER_ID = :id') .WithBindVariable('id', long(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201805/report_service/run_inventory_report.py b/examples/ad_manager/v201902/report_service/run_inventory_report.py similarity index 86% rename from examples/ad_manager/v201805/report_service/run_inventory_report.py rename to examples/ad_manager/v201902/report_service/run_inventory_report.py index f329a544..07d5de3d 100755 --- a/examples/ad_manager/v201805/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201902/report_service/run_inventory_report.py @@ -25,16 +25,16 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201805') + network_service = client.GetService('NetworkService', version='v201902') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) .Limit(None) # No limit or offset for reports @@ -46,10 +46,10 @@ def main(client): 'dimensions': ['DATE', 'AD_UNIT_NAME'], 'adUnitView': 'HIERARCHICAL', 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS', - 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS', - 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', - 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], + 'ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS', + 'ADSENSE_LINE_ITEM_LEVEL_CLICKS', + 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', + 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', 'statement': statement.ToStatement() } diff --git a/examples/ad_manager/v201805/report_service/run_reach_report.py b/examples/ad_manager/v201902/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v201805/report_service/run_reach_report.py rename to examples/ad_manager/v201902/report_service/run_reach_report.py index 9b4b3836..f7370148 100755 --- a/examples/ad_manager/v201805/report_service/run_reach_report.py +++ b/examples/ad_manager/v201902/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') # Create report job. report_job = { diff --git a/examples/ad_manager/v201805/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v201805/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py index d3d67281..0d223538 100755 --- a/examples/ad_manager/v201805/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py similarity index 95% rename from examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py index 773468d8..4fc16765 100755 --- a/examples/ad_manager/v201805/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py @@ -28,12 +28,12 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201805') + line_item_service = client.GetService('LineItemService', version='v201902') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('orderId = :orderId') .WithBindVariable('orderId', long(order_id))) diff --git a/examples/ad_manager/v201805/report_service/run_sales_report.py b/examples/ad_manager/v201902/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v201805/report_service/run_sales_report.py rename to examples/ad_manager/v201902/report_service/run_sales_report.py index c46e55e8..d34bac17 100755 --- a/examples/ad_manager/v201805/report_service/run_sales_report.py +++ b/examples/ad_manager/v201902/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') # Create report job. report_job = { diff --git a/examples/ad_manager/v201805/report_service/run_saved_query.py b/examples/ad_manager/v201902/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v201805/report_service/run_saved_query.py rename to examples/ad_manager/v201902/report_service/run_saved_query.py index 098e5cff..13f5e283 100755 --- a/examples/ad_manager/v201805/report_service/run_saved_query.py +++ b/examples/ad_manager/v201902/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201805') + report_service = client.GetService('ReportService', version='v201902') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201805') + report_downloader = client.GetDataDownloader(version='v201902') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .WithBindVariable('id', long(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v201805/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201902/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v201902/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 1d49ee41..8c4f4434 100755 --- a/examples/ad_manager/v201805/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201805') + 'SuggestedAdUnitService', version='v201902') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py index d1e08a7b..76f5245f 100755 --- a/examples/ad_manager/v201805/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201805') + 'SuggestedAdUnitService', version='v201902') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 24b213f7..62289682 100755 --- a/examples/ad_manager/v201805/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201805') + 'SuggestedAdUnitService', version='v201902') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', long(num_requests))) diff --git a/examples/ad_manager/v201805/team_service/__init__.py b/examples/ad_manager/v201902/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/team_service/__init__.py rename to examples/ad_manager/v201902/team_service/__init__.py diff --git a/examples/ad_manager/v201805/team_service/create_teams.py b/examples/ad_manager/v201902/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v201805/team_service/create_teams.py rename to examples/ad_manager/v201902/team_service/create_teams.py index 06cc7a9e..4b574a46 100755 --- a/examples/ad_manager/v201805/team_service/create_teams.py +++ b/examples/ad_manager/v201902/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201805') + team_service = client.GetService('TeamService', version='v201902') # Create team objects. teams = [] diff --git a/examples/ad_manager/v201805/team_service/get_all_teams.py b/examples/ad_manager/v201902/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v201805/team_service/get_all_teams.py rename to examples/ad_manager/v201902/team_service/get_all_teams.py index 0fd00499..3ff51034 100755 --- a/examples/ad_manager/v201805/team_service/get_all_teams.py +++ b/examples/ad_manager/v201902/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201805') + team_service = client.GetService('TeamService', version='v201902') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201805/team_service/update_teams.py b/examples/ad_manager/v201902/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v201805/team_service/update_teams.py rename to examples/ad_manager/v201902/team_service/update_teams.py index 3b493662..32e6aa70 100755 --- a/examples/ad_manager/v201805/team_service/update_teams.py +++ b/examples/ad_manager/v201902/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201805') + team_service = client.GetService('TeamService', version='v201902') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :teamId') .WithBindVariable('teamId', long(team_id))) diff --git a/examples/ad_manager/v201805/user_service/__init__.py b/examples/ad_manager/v201902/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/user_service/__init__.py rename to examples/ad_manager/v201902/user_service/__init__.py diff --git a/examples/ad_manager/v201805/user_service/create_users.py b/examples/ad_manager/v201902/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v201805/user_service/create_users.py rename to examples/ad_manager/v201902/user_service/create_users.py index f0645906..9b51ee18 100755 --- a/examples/ad_manager/v201805/user_service/create_users.py +++ b/examples/ad_manager/v201902/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201805') + user_service = client.GetService('UserService', version='v201902') # Create user objects. users = [ diff --git a/examples/ad_manager/v201805/user_service/deactivate_users.py b/examples/ad_manager/v201902/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v201805/user_service/deactivate_users.py rename to examples/ad_manager/v201902/user_service/deactivate_users.py index 1dc7c63d..9eada7ab 100755 --- a/examples/ad_manager/v201805/user_service/deactivate_users.py +++ b/examples/ad_manager/v201902/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201805') + user_service = client.GetService('UserService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/user_service/get_all_roles.py b/examples/ad_manager/v201902/user_service/get_all_roles.py similarity index 100% rename from examples/ad_manager/v201805/user_service/get_all_roles.py rename to examples/ad_manager/v201902/user_service/get_all_roles.py diff --git a/examples/ad_manager/v201805/user_service/get_all_users.py b/examples/ad_manager/v201902/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v201805/user_service/get_all_users.py rename to examples/ad_manager/v201902/user_service/get_all_users.py index 81c83592..74f424ce 100755 --- a/examples/ad_manager/v201805/user_service/get_all_users.py +++ b/examples/ad_manager/v201902/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201805') + user_service = client.GetService('UserService', version='v201902') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201805/user_service/get_current_user.py b/examples/ad_manager/v201902/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v201805/user_service/get_current_user.py rename to examples/ad_manager/v201902/user_service/get_current_user.py index 4b4f1907..012221fb 100755 --- a/examples/ad_manager/v201805/user_service/get_current_user.py +++ b/examples/ad_manager/v201902/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201805') + user_service = client.GetService('UserService', version='v201902') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v201805/user_service/get_user_by_email_address.py b/examples/ad_manager/v201902/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v201805/user_service/get_user_by_email_address.py rename to examples/ad_manager/v201902/user_service/get_user_by_email_address.py index a32515c6..8350c7c5 100755 --- a/examples/ad_manager/v201805/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201902/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201805') + user_service = client.GetService('UserService', version='v201902') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201805/user_service/update_users.py b/examples/ad_manager/v201902/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v201805/user_service/update_users.py rename to examples/ad_manager/v201902/user_service/update_users.py index 4b3076d3..0aba54e4 100755 --- a/examples/ad_manager/v201805/user_service/update_users.py +++ b/examples/ad_manager/v201902/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201805') + user_service = client.GetService('UserService', version='v201902') # Create query. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/user_team_association_service/__init__.py b/examples/ad_manager/v201902/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/user_team_association_service/__init__.py rename to examples/ad_manager/v201902/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v201805/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v201805/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py index dad08b20..143799de 100755 --- a/examples/ad_manager/v201805/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201805') + 'UserTeamAssociationService', version='v201902') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py index 5dad19c3..26f307a4 100755 --- a/examples/ad_manager/v201805/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201805') + 'UserTeamAssociationService', version='v201902') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py index 6609392a..0134b3da 100755 --- a/examples/ad_manager/v201805/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201805') + 'UserTeamAssociationService', version='v201902') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v201805') + statement = ad_manager.StatementBuilder(version='v201902') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py index d24e0dc9..3cf60498 100755 --- a/examples/ad_manager/v201805/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201805') + 'UserTeamAssociationService', version='v201902') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py index 419925d0..71365e24 100755 --- a/examples/ad_manager/v201805/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201805') + 'UserTeamAssociationService', version='v201902') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('userId = :userId') .WithBindVariable('userId', long(user_id))) diff --git a/examples/ad_manager/v201805/workflow_request_service/__init__.py b/examples/ad_manager/v201902/workflow_request_service/__init__.py similarity index 100% rename from examples/ad_manager/v201805/workflow_request_service/__init__.py rename to examples/ad_manager/v201902/workflow_request_service/__init__.py diff --git a/examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py similarity index 95% rename from examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py rename to examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py index ea172937..5fd48ba5 100755 --- a/examples/ad_manager/v201805/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py @@ -31,10 +31,10 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201805') + version='v201902') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) diff --git a/examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py similarity index 94% rename from examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py rename to examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py index 308be1bf..6dd80263 100755 --- a/examples/ad_manager/v201805/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py @@ -26,9 +26,9 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201805') + 'WorkflowRequestService', version='v201902') # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) diff --git a/examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py similarity index 94% rename from examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py rename to examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py index 33fadd30..d0233fa9 100755 --- a/examples/ad_manager/v201805/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py @@ -26,9 +26,9 @@ def main(client): # Initialize appropriate service. workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201805') + 'WorkflowRequestService', version='v201902') # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where('type = :type') .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) diff --git a/examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py similarity index 95% rename from examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py rename to examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py index 20673048..c3ada98c 100755 --- a/examples/ad_manager/v201805/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -31,10 +31,10 @@ def main(client, proposal_id): # Initialize appropriate service. workflow_request_service = client.GetService('WorkflowRequestService', - version='v201805') + version='v201902') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201805') + statement = (ad_manager.StatementBuilder(version='v201902') .Where(('entityId = :entityId and entityType = :entityType ' 'and type = :type')) .WithBindVariable('entityId', proposal_id) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 8b629fec..d9d8d6ac 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,28 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201802': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CdnConfigurationService', 'CompanyService', 'ContactService', - 'ContentBundleService', 'ContentMetadataKeyHierarchyService', - 'ContentService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', 'ExchangeRateService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardService', - 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'UserService', - 'UserTeamAssociationService', 'WorkflowRequestService'), 'v201805': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', @@ -134,6 +112,29 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), + 'v201902': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'BaseRateService', 'CdnConfigurationService', 'CmsMetadataService', + 'CompanyService', 'ContactService', 'ContentBundleService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'ExchangeRateService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'RateCardService', + 'ReconciliationOrderReportService', 'ReconciliationReportRowService', + 'ReconciliationLineItemReportService', + 'ReconciliationReportService', 'ReportService', + 'SuggestedAdUnitService', 'TeamService', 'UserService', + 'UserTeamAssociationService', 'WorkflowRequestService'), } diff --git a/googleads/common.py b/googleads/common.py index 6fb82e71..1a5380fb 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '16.0.0' +VERSION = '17.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 2e653f48..42c2bd4f 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -41,7 +41,7 @@ URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v201811' +CURRENT_VERSION = 'v201902' class CommonTest(testing.CleanUtilityRegistryTestCase): From 8f7bd7f987498c4651c969a7dc73e1d5fc965be2 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Tue, 12 Feb 2019 14:53:02 -0500 Subject: [PATCH 132/180] Commiting latest changes. From 63f0867e73f79fb2d4c2aaf4bd1b61cfca7e913b Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Thu, 28 Mar 2019 10:31:45 -0400 Subject: [PATCH 133/180] Removing support for AdWords v201806 --- ChangeLog | 3 + examples/adwords/v201806/__init__.py | 15 - .../v201806/account_management/__init__.py | 15 - .../account_management/accept_service_link.py | 62 --- .../account_management/create_account.py | 63 --- .../account_management/get_account_changes.py | 99 ---- .../get_account_hierarchy.py | 104 ---- .../v201806/advanced_operations/__init__.py | 15 - .../advanced_operations/add_ad_customizer.py | 257 --------- .../add_ad_group_bid_modifier.py | 75 --- .../add_dynamic_page_feed.py | 295 ---------- .../add_dynamic_search_ads_campaign.py | 257 --------- ...add_expanded_text_ad_with_upgraded_urls.py | 113 ---- .../advanced_operations/add_gmail_ad.py | 115 ---- .../advanced_operations/add_html5_ad.py | 110 ---- .../add_multi_asset_responsive_display_ad.py | 177 ------ .../add_responsive_display_ad.py | 158 ------ ...d_shopping_dynamic_remarketing_campaign.py | 301 ---------- .../add_universal_app_campaign.py | 218 -------- .../create_and_attach_shared_keyword_set.py | 128 ----- ...ind_and_remove_criteria_from_shared_set.py | 155 ------ .../get_ad_group_bid_modifier.py | 73 --- .../use_shared_bidding_strategy.py | 171 ------ .../v201806/basic_operations/__init__.py | 15 - .../v201806/basic_operations/add_ad_groups.py | 115 ---- .../v201806/basic_operations/add_campaigns.py | 127 ----- .../basic_operations/add_expanded_text_ads.py | 74 --- .../v201806/basic_operations/add_keywords.py | 92 --- .../add_responsive_search_ad.py | 112 ---- .../v201806/basic_operations/get_ad_groups.py | 76 --- .../v201806/basic_operations/get_campaigns.py | 68 --- .../get_campaigns_with_awql.py | 61 -- .../basic_operations/get_expanded_text_ads.py | 90 --- .../v201806/basic_operations/get_keywords.py | 87 --- .../get_responsive_search_ads.py | 100 ---- .../v201806/basic_operations/pause_ad.py | 61 -- .../v201806/basic_operations/remove_ad.py | 62 --- .../basic_operations/remove_ad_group.py | 58 -- .../basic_operations/remove_campaign.py | 58 -- .../basic_operations/remove_keyword.py | 67 --- .../basic_operations/update_ad_group.py | 85 --- .../basic_operations/update_campaign.py | 58 -- .../update_expanded_text_ad.py | 74 --- .../basic_operations/update_keyword.py | 82 --- .../v201806/campaign_management/__init__.py | 15 - ...campaign_groups_and_performance_targets.py | 152 ----- .../add_campaign_labels.py | 67 --- .../add_complete_campaigns_using_batch_job.py | 428 -------------- .../v201806/campaign_management/add_draft.py | 81 --- ...dd_keywords_using_incremental_batch_job.py | 257 --------- .../v201806/campaign_management/add_trial.py | 116 ---- .../get_all_disapproved_ads.py | 103 ---- .../get_all_disapproved_ads_with_awql.py | 88 --- .../get_campaigns_by_label.py | 83 --- .../campaign_management/graduate_trial.py | 79 --- .../campaign_management/set_ad_parameters.py | 100 ---- .../set_criterion_bid_modifier.py | 77 --- .../campaign_management/validate_text_ad.py | 84 --- .../v201806/error_handling/__init__.py | 15 - .../error_handling/handle_partial_failures.py | 131 ----- .../handle_policy_violation_error.py | 166 ------ .../adwords/v201806/extensions/__init__.py | 15 - ..._google_my_business_location_extensions.py | 156 ------ .../adwords/v201806/extensions/add_prices.py | 157 ------ .../v201806/extensions/add_site_links.py | 146 ----- .../extensions/add_site_links_using_feeds.py | 303 ---------- .../adwords/v201806/migration/__init__.py | 15 - .../migrate_to_extension_settings.py | 526 ------------------ examples/adwords/v201806/misc/__init__.py | 15 - .../v201806/misc/get_all_image_assets.py | 78 --- .../v201806/misc/get_all_images_and_videos.py | 85 --- examples/adwords/v201806/misc/upload_image.py | 65 --- .../v201806/misc/upload_image_asset.py | 71 --- .../v201806/misc/upload_media_bundle.py | 58 -- .../adwords/v201806/optimization/__init__.py | 15 - .../optimization/estimate_keyword_traffic.py | 182 ------ ...aign_criterion_bid_modifier_simulations.py | 97 ---- .../get_keyword_bid_simulations.py | 85 --- .../v201806/optimization/get_keyword_ideas.py | 113 ---- .../adwords/v201806/remarketing/__init__.py | 15 - .../v201806/remarketing/add_audience.py | 104 ---- .../remarketing/add_conversion_tracker.py | 66 --- .../remarketing/add_conversion_trackers.py | 101 ---- .../remarketing/add_crm_based_user_list.py | 104 ---- .../remarketing/add_rule_based_user_lists.py | 235 -------- .../upload_conversion_adjustments.py | 73 --- .../upload_offline_call_conversions.py | 77 --- .../remarketing/upload_offline_conversions.py | 82 --- .../remarketing/upload_offline_data.py | 259 --------- .../adwords/v201806/reporting/__init__.py | 15 - ...oad_criteria_report_as_stream_with_awql.py | 79 --- ...criteria_report_as_stream_with_selector.py | 72 --- ...oad_criteria_report_as_string_with_awql.py | 58 -- ...criteria_report_as_string_with_selector.py | 55 -- .../download_criteria_report_with_awql.py | 58 -- .../download_criteria_report_with_selector.py | 56 -- .../v201806/reporting/get_report_fields.py | 52 -- .../reporting/parallel_report_download.py | 244 -------- examples/adwords/v201806/shopping/__init__.py | 15 - .../shopping/add_product_partition_tree.py | 279 ---------- .../v201806/shopping/add_product_scope.py | 104 ---- .../v201806/shopping/add_shopping_campaign.py | 172 ------ .../add_shopping_campaign_for_showcase_ads.py | 401 ------------- .../shopping/get_product_category_taxonomy.py | 96 ---- .../adwords/v201806/targeting/__init__.py | 15 - .../add_campaign_targeting_criteria.py | 126 ----- .../add_customer_negative_criteria.py | 74 --- .../add_demographic_targeting_criteria.py | 96 ---- .../get_campaign_targeting_criteria.py | 85 --- .../get_targetable_languages_and_carriers.py | 57 -- .../v201806/targeting/lookup_location.py | 82 --- googleads/adwords.py | 56 -- googleads/common.py | 2 +- 113 files changed, 4 insertions(+), 12286 deletions(-) delete mode 100644 examples/adwords/v201806/__init__.py delete mode 100644 examples/adwords/v201806/account_management/__init__.py delete mode 100755 examples/adwords/v201806/account_management/accept_service_link.py delete mode 100755 examples/adwords/v201806/account_management/create_account.py delete mode 100755 examples/adwords/v201806/account_management/get_account_changes.py delete mode 100755 examples/adwords/v201806/account_management/get_account_hierarchy.py delete mode 100644 examples/adwords/v201806/advanced_operations/__init__.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_ad_customizer.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_dynamic_page_feed.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_dynamic_search_ads_campaign.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_gmail_ad.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_html5_ad.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_multi_asset_responsive_display_ad.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_responsive_display_ad.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_shopping_dynamic_remarketing_campaign.py delete mode 100755 examples/adwords/v201806/advanced_operations/add_universal_app_campaign.py delete mode 100755 examples/adwords/v201806/advanced_operations/create_and_attach_shared_keyword_set.py delete mode 100755 examples/adwords/v201806/advanced_operations/find_and_remove_criteria_from_shared_set.py delete mode 100755 examples/adwords/v201806/advanced_operations/get_ad_group_bid_modifier.py delete mode 100755 examples/adwords/v201806/advanced_operations/use_shared_bidding_strategy.py delete mode 100644 examples/adwords/v201806/basic_operations/__init__.py delete mode 100755 examples/adwords/v201806/basic_operations/add_ad_groups.py delete mode 100755 examples/adwords/v201806/basic_operations/add_campaigns.py delete mode 100755 examples/adwords/v201806/basic_operations/add_expanded_text_ads.py delete mode 100755 examples/adwords/v201806/basic_operations/add_keywords.py delete mode 100755 examples/adwords/v201806/basic_operations/add_responsive_search_ad.py delete mode 100755 examples/adwords/v201806/basic_operations/get_ad_groups.py delete mode 100755 examples/adwords/v201806/basic_operations/get_campaigns.py delete mode 100755 examples/adwords/v201806/basic_operations/get_campaigns_with_awql.py delete mode 100755 examples/adwords/v201806/basic_operations/get_expanded_text_ads.py delete mode 100755 examples/adwords/v201806/basic_operations/get_keywords.py delete mode 100755 examples/adwords/v201806/basic_operations/get_responsive_search_ads.py delete mode 100755 examples/adwords/v201806/basic_operations/pause_ad.py delete mode 100755 examples/adwords/v201806/basic_operations/remove_ad.py delete mode 100755 examples/adwords/v201806/basic_operations/remove_ad_group.py delete mode 100755 examples/adwords/v201806/basic_operations/remove_campaign.py delete mode 100755 examples/adwords/v201806/basic_operations/remove_keyword.py delete mode 100755 examples/adwords/v201806/basic_operations/update_ad_group.py delete mode 100755 examples/adwords/v201806/basic_operations/update_campaign.py delete mode 100755 examples/adwords/v201806/basic_operations/update_expanded_text_ad.py delete mode 100755 examples/adwords/v201806/basic_operations/update_keyword.py delete mode 100644 examples/adwords/v201806/campaign_management/__init__.py delete mode 100755 examples/adwords/v201806/campaign_management/add_campaign_groups_and_performance_targets.py delete mode 100755 examples/adwords/v201806/campaign_management/add_campaign_labels.py delete mode 100755 examples/adwords/v201806/campaign_management/add_complete_campaigns_using_batch_job.py delete mode 100755 examples/adwords/v201806/campaign_management/add_draft.py delete mode 100755 examples/adwords/v201806/campaign_management/add_keywords_using_incremental_batch_job.py delete mode 100755 examples/adwords/v201806/campaign_management/add_trial.py delete mode 100755 examples/adwords/v201806/campaign_management/get_all_disapproved_ads.py delete mode 100755 examples/adwords/v201806/campaign_management/get_all_disapproved_ads_with_awql.py delete mode 100755 examples/adwords/v201806/campaign_management/get_campaigns_by_label.py delete mode 100755 examples/adwords/v201806/campaign_management/graduate_trial.py delete mode 100755 examples/adwords/v201806/campaign_management/set_ad_parameters.py delete mode 100755 examples/adwords/v201806/campaign_management/set_criterion_bid_modifier.py delete mode 100755 examples/adwords/v201806/campaign_management/validate_text_ad.py delete mode 100644 examples/adwords/v201806/error_handling/__init__.py delete mode 100755 examples/adwords/v201806/error_handling/handle_partial_failures.py delete mode 100755 examples/adwords/v201806/error_handling/handle_policy_violation_error.py delete mode 100644 examples/adwords/v201806/extensions/__init__.py delete mode 100755 examples/adwords/v201806/extensions/add_google_my_business_location_extensions.py delete mode 100755 examples/adwords/v201806/extensions/add_prices.py delete mode 100755 examples/adwords/v201806/extensions/add_site_links.py delete mode 100755 examples/adwords/v201806/extensions/add_site_links_using_feeds.py delete mode 100644 examples/adwords/v201806/migration/__init__.py delete mode 100755 examples/adwords/v201806/migration/migrate_to_extension_settings.py delete mode 100644 examples/adwords/v201806/misc/__init__.py delete mode 100755 examples/adwords/v201806/misc/get_all_image_assets.py delete mode 100755 examples/adwords/v201806/misc/get_all_images_and_videos.py delete mode 100755 examples/adwords/v201806/misc/upload_image.py delete mode 100755 examples/adwords/v201806/misc/upload_image_asset.py delete mode 100755 examples/adwords/v201806/misc/upload_media_bundle.py delete mode 100644 examples/adwords/v201806/optimization/__init__.py delete mode 100755 examples/adwords/v201806/optimization/estimate_keyword_traffic.py delete mode 100755 examples/adwords/v201806/optimization/get_campaign_criterion_bid_modifier_simulations.py delete mode 100755 examples/adwords/v201806/optimization/get_keyword_bid_simulations.py delete mode 100755 examples/adwords/v201806/optimization/get_keyword_ideas.py delete mode 100644 examples/adwords/v201806/remarketing/__init__.py delete mode 100755 examples/adwords/v201806/remarketing/add_audience.py delete mode 100755 examples/adwords/v201806/remarketing/add_conversion_tracker.py delete mode 100755 examples/adwords/v201806/remarketing/add_conversion_trackers.py delete mode 100755 examples/adwords/v201806/remarketing/add_crm_based_user_list.py delete mode 100755 examples/adwords/v201806/remarketing/add_rule_based_user_lists.py delete mode 100755 examples/adwords/v201806/remarketing/upload_conversion_adjustments.py delete mode 100755 examples/adwords/v201806/remarketing/upload_offline_call_conversions.py delete mode 100755 examples/adwords/v201806/remarketing/upload_offline_conversions.py delete mode 100755 examples/adwords/v201806/remarketing/upload_offline_data.py delete mode 100644 examples/adwords/v201806/reporting/__init__.py delete mode 100755 examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_awql.py delete mode 100755 examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_selector.py delete mode 100755 examples/adwords/v201806/reporting/download_criteria_report_as_string_with_awql.py delete mode 100755 examples/adwords/v201806/reporting/download_criteria_report_as_string_with_selector.py delete mode 100755 examples/adwords/v201806/reporting/download_criteria_report_with_awql.py delete mode 100755 examples/adwords/v201806/reporting/download_criteria_report_with_selector.py delete mode 100755 examples/adwords/v201806/reporting/get_report_fields.py delete mode 100755 examples/adwords/v201806/reporting/parallel_report_download.py delete mode 100644 examples/adwords/v201806/shopping/__init__.py delete mode 100755 examples/adwords/v201806/shopping/add_product_partition_tree.py delete mode 100755 examples/adwords/v201806/shopping/add_product_scope.py delete mode 100755 examples/adwords/v201806/shopping/add_shopping_campaign.py delete mode 100755 examples/adwords/v201806/shopping/add_shopping_campaign_for_showcase_ads.py delete mode 100755 examples/adwords/v201806/shopping/get_product_category_taxonomy.py delete mode 100644 examples/adwords/v201806/targeting/__init__.py delete mode 100755 examples/adwords/v201806/targeting/add_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201806/targeting/add_customer_negative_criteria.py delete mode 100755 examples/adwords/v201806/targeting/add_demographic_targeting_criteria.py delete mode 100755 examples/adwords/v201806/targeting/get_campaign_targeting_criteria.py delete mode 100755 examples/adwords/v201806/targeting/get_targetable_languages_and_carriers.py delete mode 100755 examples/adwords/v201806/targeting/lookup_location.py diff --git a/ChangeLog b/ChangeLog index 1a7707ab..bf97eea4 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +18.0.0 -- 03/28/2019 +* Removed support for AdWords v201806 + 17.0.0 -- 02/12/2019 * Added support for Ad Manager v201902. * Removed support for Ad Manager v201802. diff --git a/examples/adwords/v201806/__init__.py b/examples/adwords/v201806/__init__.py deleted file mode 100644 index 16ff256a..00000000 --- a/examples/adwords/v201806/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Examples for AdWords.""" diff --git a/examples/adwords/v201806/account_management/__init__.py b/examples/adwords/v201806/account_management/__init__.py deleted file mode 100644 index 94b5520f..00000000 --- a/examples/adwords/v201806/account_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Account management examples.""" diff --git a/examples/adwords/v201806/account_management/accept_service_link.py b/examples/adwords/v201806/account_management/accept_service_link.py deleted file mode 100755 index 9e227b10..00000000 --- a/examples/adwords/v201806/account_management/accept_service_link.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 accepts a pending Google Merchant Center invitation link. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -SERVICE_LINK_ID = 'INSERT_SERVICE_LINK_ID_HERE' - - -def main(client, service_link_id): - # Initialize appropriate service. - customer_service = client.GetService( - 'CustomerService', version='v201806') - - # Create the operation to set the status to ACTIVE. - operations = [{ - 'operator': 'SET', - 'operand': { - 'serviceLinkId': service_link_id, - 'serviceType': 'MERCHANT_CENTER', - 'linkStatus': 'ACTIVE', - } - }] - - # Update the service link. - mutated_service_links = customer_service.mutateServiceLinks(operations) - - # Display results. - for mutated_service_link in mutated_service_links: - print ('Service link with service link ID "%s", type "%s" was updated ' - 'to status: "%s".' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, SERVICE_LINK_ID) diff --git a/examples/adwords/v201806/account_management/create_account.py b/examples/adwords/v201806/account_management/create_account.py deleted file mode 100755 index e4de5452..00000000 --- a/examples/adwords/v201806/account_management/create_account.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to create an account. - -Note by default this account will only be accessible via its parent AdWords -manager account.. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201806') - - today = datetime.today().strftime('%Y%m%d %H:%M:%S') - # Construct operations and add campaign. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Account created with ManagedCustomerService on %s' % today, - 'currencyCode': 'EUR', - 'dateTimeZone': 'Europe/London', - } - }] - - # Create the account. It is possible to create multiple accounts with one - # request by sending an array of operations. - accounts = managed_customer_service.mutate(operations) - - # Display results. - for account in accounts['value']: - print ('Account with customer ID "%s" was successfully created.' - % account['customerId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/account_management/get_account_changes.py b/examples/adwords/v201806/account_management/get_account_changes.py deleted file mode 100755 index 645ecfa1..00000000 --- a/examples/adwords/v201806/account_management/get_account_changes.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the changes in the account during the last 24 hours. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_sync_service = client.GetService( - 'CustomerSyncService', version='v201806') - campaign_service = client.GetService('CampaignService', version='v201806') - - # Construct selector and get all campaigns. - selector = { - 'fields': ['Id', 'Name', 'Status'] - } - campaigns = campaign_service.get(selector) - campaign_ids = [] - if 'entries' in campaigns: - for campaign in campaigns['entries']: - campaign_ids.append(campaign['id']) - else: - print 'No campaigns were found.' - return - - # Construct selector and get all changes. - today = datetime.datetime.today() - yesterday = today - datetime.timedelta(1) - selector = { - 'dateTimeRange': { - 'min': yesterday.strftime('%Y%m%d %H%M%S'), - 'max': today.strftime('%Y%m%d %H%M%S') - }, - 'campaignIds': campaign_ids - } - account_changes = customer_sync_service.get(selector) - - # Display results. - if account_changes: - if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] - if account_changes['changedCampaigns']: - for data in account_changes['changedCampaigns']: - print ('Campaign with id "%s" has change status "%s".' - % (data['campaignId'], data['campaignChangeStatus'])) - if (data['campaignChangeStatus'] != 'NEW' and - data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): - if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) - if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) - if 'changedAdGroups' in data: - for ad_group_data in data['changedAdGroups']: - print (' Ad group with id "%s" has change status "%s".' - % (ad_group_data['adGroupId'], - ad_group_data['adGroupChangeStatus'])) - if ad_group_data['adGroupChangeStatus'] != 'NEW': - if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] - if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) - if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) - else: - print 'No changes were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/account_management/get_account_hierarchy.py b/examples/adwords/v201806/account_management/get_account_hierarchy.py deleted file mode 100755 index 01a10e01..00000000 --- a/examples/adwords/v201806/account_management/get_account_hierarchy.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the account hierarchy under the current account. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -PAGE_SIZE = 500 - - -def DisplayAccountTree(account, accounts, links, depth=0): - """Displays an account tree. - - Args: - account: dict The account to display. - accounts: dict Map from customerId to account. - links: dict Map from customerId to child links. - depth: int Depth of the current account in the tree. - """ - prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) - if account['customerId'] in links: - for child_link in links[account['customerId']]: - child_account = accounts[child_link['clientCustomerId']] - DisplayAccountTree(child_account, accounts, links, depth + 1) - - -def main(client): - # Initialize appropriate service. - managed_customer_service = client.GetService( - 'ManagedCustomerService', version='v201806') - - # Construct selector to get all accounts. - offset = 0 - selector = { - 'fields': ['CustomerId', 'Name'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - accounts = {} - child_links = {} - parent_links = {} - root_account = None - - while more_pages: - # Get serviced account graph. - page = managed_customer_service.get(selector) - if 'entries' in page and page['entries']: - # Create map from customerId to parent and child links. - if 'links' in page: - for link in page['links']: - if link['managerCustomerId'] not in child_links: - child_links[link['managerCustomerId']] = [] - child_links[link['managerCustomerId']].append(link) - if link['clientCustomerId'] not in parent_links: - parent_links[link['clientCustomerId']] = [] - parent_links[link['clientCustomerId']].append(link) - # Map from customerID to account. - for account in page['entries']: - accounts[account['customerId']] = account - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - # Find the root account. - for customer_id in accounts: - if customer_id not in parent_links: - root_account = accounts[customer_id] - - # Display account tree. - if root_account: - print 'CustomerId, Name' - DisplayAccountTree(root_account, accounts, child_links, 0) - else: - print 'Unable to determine a root account' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/advanced_operations/__init__.py b/examples/adwords/v201806/advanced_operations/__init__.py deleted file mode 100644 index dc91ba79..00000000 --- a/examples/adwords/v201806/advanced_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Advanced operations examples.""" diff --git a/examples/adwords/v201806/advanced_operations/add_ad_customizer.py b/examples/adwords/v201806/advanced_operations/add_ad_customizer.py deleted file mode 100755 index a983f15c..00000000 --- a/examples/adwords/v201806/advanced_operations/add_ad_customizer.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad customizer feed. - -Associates the feed with customer and adds an ad that uses the feed to populate -dynamic data. - -""" - - -from datetime import datetime -from uuid import uuid4 - -# Import appropriate classes from the client library. -from googleads import adwords -from googleads import errors - - -FEED_NAME = 'Interplanetary Feed Name %s' % uuid4() -ADGROUPS = [ - 'INSERT_ADGROUP_ID_1_HERE', - 'INSERT_ADGROUP_ID_2_HERE' -] - - -def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): - """Creates ExpandedTextAds that use ad customizations for specified AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. - feed_name: the name of the feed used to apply customizations. - - Raises: - GoogleAdsError: if no ExpandedTextAds were added. - """ - # Get the AdGroupAdService - adgroup_ad_service = client.GetService('AdGroupAdService', 'v201806') - - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name, - 'headlinePart2': 'Only {=%s.Price}' % feed_name, - 'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name, - 'finalUrls': ['http://www.example.com'], - } - - # We add the same ad to both ad groups. When they serve, they will show - # different values, since they match different feed items. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'adGroupId': adgroup, - 'ad': expanded_text_ad - } - } for adgroup in adgroup_ids] - - response = adgroup_ad_service.mutate(operations) - - if response and 'value' in response: - for ad in response['value']: - print ('Created an ad with ID "%s", type "%s", and status "%s".' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - raise errors.GoogleAdsError('No ads were added.') - - -def CreateCustomizerFeed(client, feed_name): - """Creates a new AdCustomizerFeed. - - Args: - client: an AdWordsClient instance. - feed_name: the name for the new AdCustomizerFeed. - - Returns: - The new AdCustomizerFeed. - """ - # Get the AdCustomizerFeedService - ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', - 'v201806') - customizer_feed = { - 'feedName': feed_name, - 'feedAttributes': [ - {'type': 'STRING', 'name': 'Name'}, - {'type': 'STRING', 'name': 'Price'}, - {'type': 'DATE_TIME', 'name': 'Date'} - ] - } - - feed_service_operation = { - 'operator': 'ADD', - 'operand': customizer_feed - } - - response = ad_customizer_feed_service.mutate([feed_service_operation]) - - if response and 'value' in response: - feed = response['value'][0] - feed_data = { - 'feedId': feed['feedId'], - 'nameId': feed['feedAttributes'][0]['id'], - 'priceId': feed['feedAttributes'][1]['id'], - 'dateId': feed['feedAttributes'][2]['id'] - } - print ('Feed with name "%s" and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) - return feed - else: - raise errors.GoogleAdsError('No feeds were added') - - -def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id): - """Restricts the feed item to an ad group. - - Args: - client: an AdWordsClient instance. - feed_item: The feed item. - adgroup_id: The ad group ID. - """ - # Get the FeedItemTargetService - feed_item_target_service = client.GetService( - 'FeedItemTargetService', 'v201806') - - # Optional: Restrict the first feed item to only serve with ads for the - # specified ad group ID. - ad_group_target = { - 'xsi_type': 'FeedItemAdGroupTarget', - 'feedId': feed_item['feedId'], - 'feedItemId': feed_item['feedItemId'], - 'adGroupId': adgroup_id - } - - operation = {'operator': 'ADD', 'operand': ad_group_target} - - response = feed_item_target_service.mutate([operation]) - new_ad_group_target = response['value'][0] - - print('Feed item target for feed ID %s and feed item ID %s was created to ' - 'restrict serving to ad group ID %s' % - (new_ad_group_target['feedId'], - new_ad_group_target['feedItemId'], - new_ad_group_target['adGroupId'])) - - -def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): - """Creates FeedItems for the specified AdGroups. - - These FeedItems contain values to use in ad customizations for the AdGroups. - - Args: - client: an AdWordsClient instance. - adgroup_ids: a list containing two AdGroup Ids. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Raises: - GoogleAdsError: if no FeedItems were added. - """ - # Get the FeedItemService - feed_item_service = client.GetService('FeedItemService', 'v201806') - now = datetime.now() - mars_date = datetime(now.year, now.month, 1, 0, 0) - venus_date = datetime(now.year, now.month, 15, 0, 0) - time_format = '%Y%m%d %H%M%S' - - feed_item_operations = [ - CreateFeedItemAddOperation( - 'Mars', '$1234.56', mars_date.strftime(time_format), - ad_customizer_feed), - CreateFeedItemAddOperation( - 'Venus', '$1450.00', venus_date.strftime(time_format), - ad_customizer_feed) - ] - - response = feed_item_service.mutate(feed_item_operations) - - if 'value' in response: - for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] - else: - raise errors.GoogleAdsError('No FeedItems were added.') - - for feed_item, adgroup_id in zip(response['value'], adgroup_ids): - RestrictFeedItemToAdGroup(client, feed_item, adgroup_id) - - -def CreateFeedItemAddOperation(name, price, date, ad_customizer_feed): - """Creates a FeedItemOperation. - - The generated FeedItemOperation will create a FeedItem with the specified - values when sent to FeedItemService.mutate. - - Args: - name: the value for the name attribute of the FeedItem. - price: the value for the price attribute of the FeedItem. - date: the value for the date attribute of the FeedItem. - ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems - with. - - Returns: - A new FeedItemOperation for adding a FeedItem. - """ - feed_item = { - 'feedId': ad_customizer_feed['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'], - 'stringValue': name - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'], - 'stringValue': price - }, - { - 'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'], - 'stringValue': date - } - ] - } - - operation = { - 'operator': 'ADD', - 'operand': feed_item - } - - return operation - - -def main(client, adgroup_ids, feed_name=FEED_NAME): - # Create a customizer feed. One feed per account can be used for all ads. - ad_customizer_feed = CreateCustomizerFeed(client, feed_name) - # Add feed items containing the values we'd like to place in ads. - CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed) - # All set! We can now create ads with customizations. - CreateAdsWithCustomizations(client, adgroup_ids, feed_name) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUPS) diff --git a/examples/adwords/v201806/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201806/advanced_operations/add_ad_group_bid_modifier.py deleted file mode 100755 index 3c65fbdf..00000000 --- a/examples/adwords/v201806/advanced_operations/add_ad_group_bid_modifier.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds an ad group level mobile bid modifier override for a campaign. - -To get your ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -BID_MODIFIER = 'INSERT_BID_MODIFIER_HERE' - - -def main(client, ad_group_id, bid_modifier): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201806') - - # Mobile criterion ID. - criterion_id = '30001' - - # Prepare to add an ad group level override. - operation = { - # Use 'ADD' to add a new modifier and 'SET' to update an existing one. A - # modifier can be removed with the 'REMOVE' operator. - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Platform', - 'id': criterion_id - }, - 'bidModifier': bid_modifier - } - } - - # Add ad group level mobile bid modifier. - response = ad_group_bid_modifier_service.mutate([operation]) - if response and response['value']: - modifier = response['value'][0] - value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - else: - print 'No modifiers were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, BID_MODIFIER) diff --git a/examples/adwords/v201806/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201806/advanced_operations/add_dynamic_page_feed.py deleted file mode 100755 index cdb2b89b..00000000 --- a/examples/adwords/v201806/advanced_operations/add_dynamic_page_feed.py +++ /dev/null @@ -1,295 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds page feed to specify URLs to use with your Dynamic Search Ads campaign. - -To create a Dynamic Search Ads campaign, run add_dynamic_search_ad_campaign.py. -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -from collections import namedtuple -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - -# Used to keep track of DSA page feed details. -_DSAFeedDetails = namedtuple( - '_DSAFeedDetails', ['feed_id', 'url_attribute_id', 'label_attribute_id']) -# ID that corresponds to the labels. -DSA_LABEL_FIELD_ID = 2 -# The criterion type to be used for DSA page feeds. -DSA_PAGE_FEED_CRITERION_TYPE = 61 -DSA_PAGE_URL_LABEL = 'discounts' -# ID that corresponds to the page URLs. -DSA_PAGE_URLS_FIELD_ID = 1 - - -def main(client, campaign_id, ad_group_id): - # Get the page feed details. This code example creates a new feed, but you can - # fetch and re-use an existing feed. - feed_details = _CreateFeed(client) - _CreateFeedMapping(client, feed_details) - _CreateFeedItems(client, feed_details, DSA_PAGE_URL_LABEL) - - # Associate the page feed with the campaign. - _UpdateCampaignDSASetting(client, campaign_id, feed_details.feed_id) - - # Optional: Target web pages matching the feed's label in the ad group. - _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) - - print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id - - -def _CreateFeed(client): - """Creates the feed for DSA page URLs. - - Args: - client: an AdWordsClient instance. - - Returns: - A _DSAFeedDetails instance containing details about the created feed. - """ - # Get the FeedService. - feed_service = client.GetService('FeedService', version='v201806') - - # Create operation. - operation = { - # Create the feed. - 'operand': { - 'name': 'DSA Feed %s' % uuid.uuid4(), - # Create attributes. - 'attributes': [ - {'type': 'URL_LIST', 'name': 'Page URL'}, - {'type': 'STRING_LIST', 'name': 'Label'} - ], - 'origin': 'USER' - }, - 'operator': 'ADD' - } - - # Add the feed. - feed = feed_service.mutate([operation])['value'][0] - return _DSAFeedDetails(feed['id'], feed['attributes'][0]['id'], - feed['attributes'][1]['id']) - - -def _CreateFeedMapping(client, feed_details): - """Creates the feed mapping for DSA page feeds. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - """ - # Get the FeedMappingService. - feed_mapping_service = client.GetService('FeedMappingService', - version='v201806') - - # Create the operation. - operation = { - # Create the feed mapping. - 'operand': { - 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE, - 'feedId': feed_details.feed_id, - # Map the feedAttributeIds to the fieldId constants. - 'attributeFieldMappings': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'fieldId': DSA_PAGE_URLS_FIELD_ID - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'fieldId': DSA_LABEL_FIELD_ID - } - ] - }, - 'operator': 'ADD' - } - - # Add the feed mapping. - feed_mapping_service.mutate([operation]) - - -def _CreateFeedItems(client, feed_details, label_name): - """Creates the page URLs in the DSA page feed. - - Args: - client: an AdWordsClient instance. - feed_details: a _DSAFeedDetails instance. - label_name: a str containing the page feed URL label. - """ - # Get the FeedItemService. - feed_item_service = client.GetService('FeedItemService', version='v201806') - - # For page feed URL recommendations and rules, see: - # https://support.google.com/adwords/answer/7166527 - urls = ('http://www.example.com/discounts/rental-cars?id={feeditem}', - 'http://www.example.com/discounts/hotel-deals?id={feeditem}', - 'http://www.example.com/discounts/flight-deals?id={feeditem}') - - # Create the operation. - operations = [{ - # Create the feed item. - 'operand': { - 'feedId': feed_details.feed_id, - 'attributeValues': [ - { - 'feedAttributeId': feed_details.url_attribute_id, - 'stringValues': [url] - }, - { - 'feedAttributeId': feed_details.label_attribute_id, - 'stringValues': [label_name] - } - ] - }, - 'operator': 'ADD' - } for url in urls] - - # Add the feed item. - feed_item_service.mutate(operations) - - -def _UpdateCampaignDSASetting(client, campaign_id, feed_id): - """Updates the campaign DSA setting to DSA pagefeeds. - - Args: - client: an AdWordsClient instance. - campaign_id: a str Campaign ID. - feed_id: a str page Feed ID. - - Raises: - ValueError: If the given campaign is found not to be a dynamic search ad - campaign. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201806') - - selector = { - 'fields': ['Id', 'Settings'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [campaign_id] - }] - } - - response = campaign_service.get(selector) - - if response['totalNumEntries']: - campaign = response['entries'][0] - else: - raise ValueError('No campaign with ID "%d" exists.' % campaign_id) - - if not campaign['settings']: - raise ValueError('This is not a DSA campaign.') - - dsa_setting = None - - campaign_settings = campaign['settings'] - - for setting in campaign_settings: - if setting['Setting.Type'] == 'DynamicSearchAdsSetting': - dsa_setting = setting - break - - if dsa_setting is None: - raise ValueError('This is not a DSA campaign.') - - dsa_setting['pageFeed'] = { - 'feedIds': [feed_id] - } - - # Optional: Specify whether only the supplied URLs should be used with your - # Dynamic Search Ads. - dsa_setting['useSuppliedUrlsOnly'] = True - - operation = { - 'operand': { - 'id': campaign_id, - 'settings': campaign_settings - }, - 'operator': 'SET' - } - - campaign_service.mutate([operation]) - print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( - campaign_id, feed_id) - - -def _AddDSATargeting(client, ad_group_id, label_name): - """Set custom targeting for the page feed URLs based on a list of labels. - - Args: - client: an AdWordsClient instance. - ad_group_id: a str AdGroup ID. - label_name: a str label name. - - Returns: - A suds.sudsobject.Object representing the newly created webpage criterion. - """ - # Get the AdGroupCriterionService. - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201806') - - # Create the operation. - operation = { - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Test criterion', - # Add a condition for label=specified_label_name. - 'conditions': [{ - 'operand': 'CUSTOM_LABEL', - 'argument': label_name - }], - } - }, - # Set a custom bid for this criterion - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 1500000 - } - }] - } - }, - 'operator': 'ADD' - } - - criterion = ad_group_criterion_service.mutate([operation])['value'][0] - print 'Web page criterion with ID "%d" and status "%s" was created.' % ( - criterion['criterion']['id'], criterion['userStatus']) - return criterion - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201806/advanced_operations/add_dynamic_search_ads_campaign.py deleted file mode 100755 index 4c51ac69..00000000 --- a/examples/adwords/v201806/advanced_operations/add_dynamic_search_ads_campaign.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Dynamic Search Ads campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - budget = _CreateBudget(client) - campaign_id = _CreateCampaign(client, budget) - ad_group_id = _CreateAdGroup(client, campaign_id) - _CreateExpandedDSA(client, ad_group_id) - _AddWebPageCriteria(client, ad_group_id) - - print 'Dynamic Search Ads campaign setup is complete.' - - -def _CreateBudget(client): - """Creates the budget. - - Args: - client: an AdWordsClient instance. - - Returns: - a suds.sudsobject.Object representation of the created budget. - """ - budget_service = client.GetService('BudgetService', version='v201806') - - # Create the campaign budget - operation = { - 'operand': { - 'name': 'Interplanetary Cruise Budget #%d' % uuid.uuid4(), - 'deliveryMethod': 'STANDARD', - 'amount': { - 'microAmount': 500000 - } - }, - 'operator': 'ADD' - } - - budget = budget_service.mutate([operation])['value'][0] - - print 'Budget with ID "%d" and name "%s" was created.' % ( - budget['budgetId'], budget['name']) - - return budget - - -def _CreateCampaign(client, budget): - """Creates the campaign. - - Args: - client: an AdWordsClient instance. - budget: a suds.sudsobject.Object representation of a created budget. - - Returns: - An integer campaign ID. - """ - campaign_service = client.GetService('CampaignService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%d' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # prevent the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'budget': budget, - # Required: Set the campaign's Dynamic Search Ad settings. - 'settings': [{ - 'xsi_type': 'DynamicSearchAdsSetting', - # Required: Set the domain name and language. - 'domainName': 'example.com', - 'languageCode': 'en' - }], - # Optional: Set the start date. - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - # Optional: Set the end date. - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - }] - - campaign = campaign_service.mutate(operations)['value'][0] - campaign_id = campaign['id'] - - print 'Campaign with ID "%d" and name "%s" was added.' % ( - campaign_id, campaign['name']) - - return campaign_id - - -def _CreateAdGroup(client, campaign_id): - """Creates an ad group. - - Args: - client: an AdWordsClient instance. - campaign_id: an integer campaign ID. - - Returns: - An integer ad group ID. - """ - ad_group_service = client.GetService('AdGroupService') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'adGroupType': 'SEARCH_DYNAMIC_ADS', - 'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '3000000' - }, - }] - } - } - }] - - ad_group = ad_group_service.mutate(operations)['value'][0] - ad_group_id = ad_group['id'] - - print 'Ad group with ID "%d" and name "%s" was created.' % ( - ad_group_id, ad_group['name']) - - return ad_group_id - - -def _CreateExpandedDSA(client, ad_group_id): - """Creates the expanded Dynamic Search Ad. - - Args: - client: an AdwordsClient instance. - ad_group_id: an integer ID of the ad group in which the DSA is added. - """ - # Get the AdGroupAdService. - ad_group_ad_service = client.GetService('AdGroupAdService') - - # Create the operation - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - # Create the expanded dynamic search ad. This ad will have its - # headline and final URL auto-generated at serving time according to - # domain name specific information provided by DynamicSearchAdsSetting - # at the campaign level. - 'ad': { - 'xsi_type': 'ExpandedDynamicSearchAd', - # Set the ad description. - 'description': 'Buy your tickets now!' - }, - # Optional: Set the status. - 'status': 'PAUSED', - } - }] - - # Create the ad. - ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] - - # Display the results. - print ('Expanded dynamic search ad with ID "%d" and description "%s" was ' - 'added' % (ad['id'], ad['description'])) - - -def _AddWebPageCriteria(client, ad_group_id): - """Adds a web page criterion to target Dynamic Search Ads. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID of the ad group the criteria is being added to. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201806') - - operations = [{ - 'operator': 'ADD', - # Create biddable ad group criterion. - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Create a webpage criterion for special offers for children. - 'criterion': { - 'xsi_type': 'Webpage', - 'parameter': { - 'criterionName': 'Special offers for children.', - 'conditions': [ - { - 'operand': 'URL', - 'argument': '/marscruise/children' - }, - { - 'operand': 'PAGE_TITLE', - 'argument': 'Special Offer' - } - ] - } - }, - 'userStatus': 'PAUSED', - # Optional: set a custom bid. - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000L - } - }] - } - } - }] - - criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( - criterion['criterion']['id'], criterion['adGroupId']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201806/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py deleted file mode 100755 index 1cb4a046..00000000 --- a/examples/adwords/v201806/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an expanded text ad that uses upgraded URLS. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - adgroup_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Create the expanded text ad - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - # Specify a list of final URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalUrls': [ - 'http://www.example.com/cruise/space/', - 'http://www.example.com/locations/mars/' - ], - # Specify a list of final mobile URLs. This field cannot be set if URL - # field is set, or finalUrls is unset. This may be specified at ad, - # criterion, and feed item levels. - 'finalMobileUrls': [ - 'http://mobile.example.com/cruise/space/', - 'http://mobile.example.com/locations/mars/' - ] - } - - # Specify a tracking URL for 3rd party tracking provider. You may specify - # one at customer, campaign, ad group, ad, criterion or feed item levels. - expanded_text_ad['trackingUrlTemplate'] = ( - 'http://tracker.example.com/?season={_season}&promocode={_promocode}' - '&u={lpurl}' - ) - - expanded_text_ad['urlCustomParameters'] = { - 'parameters': [ - # Since your tracking URL has two custom parameters, provide - # their values too. This can be provided at campaign, ad group, - # ad, criterion, or feed item levels. - { - 'key': 'season', - 'value': 'christmas' - }, - { - 'key': 'promocode', - 'value': 'NYC123' - } - ] - } - - text_adgroup_ad = { - 'adGroupId': adgroup_id, - 'ad': expanded_text_ad, - # Optional: Set the status. - 'status': 'PAUSED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': text_adgroup_ad - }] - - response = adgroup_ad_service.mutate(operations) - - if 'value' in response: - for adgroup_ad in response['value']: - print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] - else: - raise errors.GoogleAdsError('Failed to create AdGroupAd.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_gmail_ad.py b/examples/adwords/v201806/advanced_operations/add_gmail_ad.py deleted file mode 100755 index d7cf578c..00000000 --- a/examples/adwords/v201806/advanced_operations/add_gmail_ad.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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 code example adds a Gmail ad to a given ad group. - -The ad group's campaign needs to have an AdvertisingChannelType of DISPLAY and -AdvertisingChannelSubType of DISPLAY_GMAIL_AD. - -To get your ad groups, run get_ad_groups.py. -""" - - -# Import appropriate classes from the client library. -from googleads import adwords - - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - media_service = client.GetService('MediaService', 'v201806') - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201806') - opener = client.proxy_config.BuildOpener() - - try: - # This ad format doesn't allow the creation of an image using the Image.data - # field. An image must first be created using the MediaService, and an - # Image.mediaId must be populated when creating the ad. - uploaded_logo_image = _CreateImage( - media_service, opener, 'https://goo.gl/mtt54n') - uploaded_marketing_image = _CreateImage( - media_service, opener, 'http://goo.gl/3b9Wfh') - - teaser = { - 'headline': 'Dream', - 'description': 'Create your own adventure', - 'businessName': 'Interplanetary Ships', - 'logoImage': uploaded_logo_image - } - - # Creates a Gmail ad. - gmail_ad = { - 'xsi_type': 'GmailAd', - 'teaser': teaser, - 'marketingImage': uploaded_marketing_image, - 'marketingImageHeadline': 'Travel', - 'marketingImageDescription': 'Take to the skies!', - 'finalUrls': ['http://wwww.example.com'] - } - - # Creates ad group ad for the Gmail ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': gmail_ad, - # Optional: Set additional settings. - 'status': 'PAUSED' - } - - # Creates ad group ad operations. - operations = [{ - 'operator': 'ADD', - 'operand': ad_group_ad - }] - - # Adds a Gmail ad. - ad_group_ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad_group_ad in ad_group_ads['value']: - print ('A Gmail ad with id "%d" and short headline "%s" was ' - 'added.' % (ad_group_ad['ad']['id'], - ad_group_ad['ad']['teaser']['headline'])) - except Exception as e: - raise Exception('Failed to create Gmail ad: %s' % e) - - -def _CreateImage(media_service, opener, url): - """Creates an image and uploads it to the server. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - url: a str URL used to load image data. - - Returns: - The image that was successfully uploaded. - """ - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open(url).read().decode('utf-8') - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - return media_service.upload(image)[0] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_html5_ad.py b/examples/adwords/v201806/advanced_operations/add_html5_ad.py deleted file mode 100755 index 343ae2c2..00000000 --- a/examples/adwords/v201806/advanced_operations/add_html5_ad.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an HTML5 ad to a given AdGroup. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import urllib2 -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Create HTML5 media. - html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media_bundle = { - 'xsi_type': 'MediaBundle', - 'data': html5_zip, - 'entryPoint': 'carousel/index.html', - 'type': 'MEDIA_BUNDLE' - } - - ad_data = { - 'uniqueName': 'adData', - 'fields': [ - { - 'name': 'Custom_layout', - 'fieldMedia': media_bundle, - 'type': 'MEDIA_BUNDLE' - }, - { - 'name': 'layout', - 'fieldText': 'Custom', - 'type': 'ENUM' - } - ] - } - - html5_ad = { - 'xsi_type': 'TemplateAd', - 'name': 'Ad for HTML5', - 'templateId': 419, - 'finalUrls': ['https://www.google.com'], - 'displayUrl': 'www.google.com?tip=ENTER_YOUR_OWN_FINAL_AND_DISPLAY_URLS', - 'dimensions': { - 'width': '300', - 'height': '250' - }, - 'templateElements': [ad_data] - } - - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': html5_ad, - 'status': 'PAUSED' - } - - operations = [ - { - 'operator': 'ADD', - 'operand': ad_group_ad - } - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) - - -def GetHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return response.read().decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_multi_asset_responsive_display_ad.py b/examples/adwords/v201806/advanced_operations/add_multi_asset_responsive_display_ad.py deleted file mode 100755 index c6c5273f..00000000 --- a/examples/adwords/v201806/advanced_operations/add_multi_asset_responsive_display_ad.py +++ /dev/null @@ -1,177 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 Google LLC -# -# 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 -# -# https://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 adds a responsive display ad to an ad group. - -Image assets are uploaded using AssetService. To get ad groups, run -get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords -import requests - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def UploadImageAsset(client, url): - """Uploads the image from the specified url. - - Args: - client: An AdWordsClient instance. - url: The image URL. - - Returns: - The ID of the uploaded image. - """ - # Initialize appropriate service. - asset_service = client.GetService('AssetService', version='v201806') - - # Download the image. - image_request = requests.get(url) - - # Create the image asset. - image_asset = { - 'xsi_type': 'ImageAsset', - 'imageData': image_request.content, - # This field is optional, and if provided should be unique. - # 'assetName': 'Image asset ' + str(uuid.uuid4()), - } - - # Create the operation. - operation = { - 'operator': 'ADD', - 'operand': image_asset - } - - # Create the asset and return the ID. - result = asset_service.mutate([operation]) - - return result['value'][0]['assetId'] - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Create the ad. - multi_asset_responsive_display_ad = { - 'xsi_type': 'MultiAssetResponsiveDisplayAd', - 'headlines': [{ - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Travel to Mars' - } - }, { - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Travel to Jupiter', - } - }, { - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Travel to Pluto' - } - }], - 'descriptions': [{ - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Visit the planet in a luxury spaceship.', - } - }, { - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'See the planet in style.', - } - }], - 'businessName': 'Galactic Luxury Cruises', - 'longHeadline': { - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Visit the planet in a luxury spaceship.', - } - }, - # This ad format does not allow the creation of an image asset by setting - # the asset.imageData field. An image asset must first be created using - # the AssetService, and asset.assetId must be populated when creating - # the ad. - 'marketingImages': [{ - 'asset': { - 'xsi_type': 'ImageAsset', - 'assetId': UploadImageAsset(client, 'https://goo.gl/3b9Wfh') - } - }], - 'squareMarketingImages': [{ - 'asset': { - 'xsi_type': 'ImageAsset', - 'assetId': UploadImageAsset(client, 'https://goo.gl/mtt54n') - } - }], - # Optional values - 'finalUrls': ['http://www.example.com'], - 'callToActionText': 'Shop Now', - # Set color settings using hexadecimal values. Set allowFlexibleColor to - # false if you want your ads to render by always using your colors - # strictly. - 'mainColor': '#0000ff', - 'accentColor': '#ffff00', - 'allowFlexibleColor': False, - 'formatSetting': 'NON_NATIVE', - # Set dynamic display ad settings, composed of landscape logo image, - # promotion text, and price prefix. - 'dynamicSettingsPricePrefix': 'as low as', - 'dynamicSettingsPromoText': 'Free shipping!', - 'logoImages': [{ - 'asset': { - 'xsi_type': 'ImageAsset', - 'assetId': UploadImageAsset(client, 'https://goo.gl/mtt54n') - } - }] - } - - # Create ad group ad. - ad_group_ad = { - 'adGroupId': ad_group_id, - 'ad': multi_asset_responsive_display_ad, - # Optional. - 'status': 'PAUSED' - } - - # Add ad. - ads = ad_group_ad_service.mutate([ - {'operator': 'ADD', 'operand': ad_group_ad} - ]) - # Display results. - if 'value' in ads: - for ad in ads['value']: - print ('Added new responsive display ad ad with ID "%d" ' - 'and long headline "%s".' - % (ad['ad']['id'], ad['ad']['longHeadline']['asset']['assetText'])) - else: - print 'No ads were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201806/advanced_operations/add_responsive_display_ad.py deleted file mode 100755 index 104c3e09..00000000 --- a/examples/adwords/v201806/advanced_operations/add_responsive_display_ad.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a responsive display ad to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import urllib2 - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate services. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - media_service = client.GetService('MediaService', version='v201806') - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) - - try: - # Create marketing image. - marketing_image = _CreateImage(media_service, opener, - 'https://goo.gl/3b9Wfh') - - # Create square marketing image. - square_marketing_image = _CreateImage(media_service, opener, - 'https://goo.gl/mtt54n') - - # Create a responsive display ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveDisplayAd', - 'marketingImage': {'mediaId': marketing_image['mediaId']}, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://www.example.com'], - # Optional: Set a square marketing image to the ad. - 'squareMarketingImage': { - 'mediaId': square_marketing_image['mediaId'] - }, - # Optional: Set call-to-action text. - 'callToActionText': 'Shop Now', - # Optional: Set dynamic display ad settings, composed of - # landscape logo image, promotion text, and price prefix. - 'dynamicDisplayAdSettings': _CreateDynamicDisplayAdSettings( - media_service, opener), - # Whitelisted accounts only: Set color settings using - # hexadecimal numbers. - # Set allowFlexibleColor to False if you want your ads to render - # by always using your colors strictly. - # 'mainColor': '#0000ff', - # 'accentColor': '#ffff00', - # 'allowFlexibleColor': False - # Whitelisted accounts only: Set the format setting that the ad - # will be served in. - # 'formatSetting': 'NON_NATIVE' - - }, - # Optional fields. - 'status': 'PAUSED' - } - }] - - # Make the mutate request. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) - - except: - raise Exception('Failed to create responsive display ad.') - - -def _CreateImage(media_service, opener, url): - """Creates an image and uploads it to the server. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - url: a str URL used to load image data. - - Returns: - The image that was successfully uploaded. - """ - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open(url).read().decode('utf-8') - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - return media_service.upload(image)[0] - - -def _CreateDynamicDisplayAdSettings(media_service, opener): - """Creates settings for dynamic display ad. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - - Returns: - The dynamic display ad settings. - """ - image = _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') - - logo = { - 'type': 'IMAGE', - 'mediaId': image['mediaId'], - 'xsi_type': 'Image' - } - - dynamic_settings = { - 'landscapeLogoImage': logo, - 'pricePrefix': 'as low as', - 'promoText': 'Free shipping!', - 'xsi_type': 'DynamicSettings', - } - - return dynamic_settings - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201806/advanced_operations/add_shopping_dynamic_remarketing_campaign.py deleted file mode 100755 index 1f36a5fe..00000000 --- a/examples/adwords/v201806/advanced_operations/add_shopping_dynamic_remarketing_campaign.py +++ /dev/null @@ -1,301 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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. - -"""Adds a Shopping dynamic remarketing campaign for the Display Network. - -This example steps through the following: -* Creates a new Display Network campaign. -* Links the campaign with Merchant Center. -* Links the user list to the ad group. -* Creates a responsive display ad to render the dynamic text. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - - -import uuid - -from googleads import adwords - - -MERCHANT_ID = 'INSERT_MERCHANT_CENTER_ID_HERE' -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -USER_LIST_ID = 'INSERT_USER_LIST_ID_HERE' - - -def main(client, merchant_id, budget_id, user_list_id): - opener = client.proxy_config.BuildOpener() - - campaign = CreateCampaign(client, merchant_id, budget_id) - campaign_id = campaign['id'] - print 'Campaign with name "%s" and ID "%d" was added.' % ( - campaign['name'], campaign_id) - - ad_group = CreateAdGroup(client, campaign_id) - ad_group_id = ad_group['id'] - print 'Ad group with name "%s" and ID "%d" was added.' % ( - ad_group['name'], ad_group_id) - - ad_group_ad = CreateAd(client, opener, ad_group_id) - print 'Responsive display ad with ID "%d" was added.' % ( - ad_group_ad['ad']['id']) - - AttachUserList(client, ad_group_id, user_list_id) - print 'User list with ID "%d" was attached to ad group with ID "%d".' % ( - user_list_id, ad_group_id) - - -def CreateCampaign(client, merchant_id, budget_id): - """Creates a new Display Network campaign. - - Args: - client: an AdWordsClient instance. - merchant_id: a int merchant center ID. - budget_id: a int budget ID. - - Returns: - The campaign that was successfully created. - """ - campaign_service = client.GetService('CampaignService', 'v201806') - - campaign = { - 'name': 'Shopping campaign #%d' % uuid.uuid4(), - # Dynamic remarketing campaigns are only available on the Google Display - # Network. - 'advertisingChannelType': 'DISPLAY', - 'status': 'PAUSED', - 'budget': { - 'budgetId': budget_id - }, - # This example uses a Manual CPC bidding strategy, but you should select - # the strategy that best aligns with your sales goals. More details here: - # https://support.google.com/adwords/answer/2472725 - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [{ - 'xsi_type': 'ShoppingSetting', - # Campaigns with numerically higher priorities take precedence over - # those with lower priorities. - 'campaignPriority': 0, - 'merchantId': merchant_id, - # Display network campaigns do not support partition by country. The - # only supported value is "ZZ". This signals that products from all - # countries are available in this campaign. The actual products which - # serve are based on the products tagged in the user list entry. - 'salesCountry': 'ZZ', - # Optional: Enable local inventory ads (items for sale in physical - # stores.) - 'enableLocal': True, - }] - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - return campaign_service.mutate(operations)['value'][0] - - -def CreateAdGroup(client, campaign_id): - """Creates a dynamic remarketing campaign. - - Args: - client: an AdWordsClient instance. - campaign_id: an int campaign ID. - - Returns: - The ad group that was successfully created. - """ - ad_group_service = client.GetService('AdGroupService', 'v201806') - - ad_group = { - 'name': 'Dynamic remarketing ad group', - 'campaignId': campaign_id, - 'status': 'ENABLED' - } - - operations = [{ - 'operator': 'ADD', - 'operand': ad_group - }] - - return ad_group_service.mutate(operations)['value'][0] - - -def CreateAd(client, opener, ad_group_id): - """Creates a ResponsiveDisplayAd. - - Args: - client: an AdWordsClient instance. - opener: an OpenerDirector instance. - ad_group_id: an int ad group ID. - - Returns: - The ad group ad that was successfully created. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201806') - media_service = client.GetService('MediaService', 'v201806') - - marketing_image_id = _CreateImage( - media_service, opener, 'https://goo.gl/3b9Wfh') - logo_image_id = _CreateImage(media_service, opener, 'https://goo.gl/mtt54n') - - ad = { - 'xsi_type': 'ResponsiveDisplayAd', - # This ad format doesn't allow the creation of an image using the - # Image.data field. An image must first be created using the MediaService, - # and Image.mediaId must be populated when creating the ad. - 'marketingImage': { - 'xsi_type': 'Image', - 'mediaId': marketing_image_id - }, - 'shortHeadline': 'Travel', - 'longHeadline': 'Travel the World', - 'description': 'Take to the air!', - 'businessName': 'Interplanetary Cruises', - 'finalUrls': ['http://wwww.example.com'], - # Optional: Call to action text. - # Valid texts: https://support.google.com/adwords/answer/7005917 - 'callToActionText': 'Apply Now', - # Optional: Set dynamic display ad settings, composed of landscape logo - # image, promotion text, and price prefix. - 'dynamicDisplayAdSettings': CreateDynamicDisplayAdSettings( - client, opener), - # Optional: Create a logo image and set it to the ad. - 'logoImage': { - 'xsi_type': 'Image', - 'mediaId': logo_image_id - }, - # Optional: Create a square marketing image and set it to the ad. - 'squareMarketingImage': { - 'xsi_type': 'Image', - 'mediaId': logo_image_id - }, - # Whitelisted accounts only: Set color settings using hexadecimal values. - # Set allowFlexibleColor to False if you want your ads to render by always - # using your colors strictly. - # 'mainColor': '#000fff', - # 'accentColor': '#fff000', - # 'allowFlexibleColor': False, - # Whitelisted accounts only: Set the format setting that the ad will be - # served in. - # 'formatSetting': 'NON_NATIVE' - } - - ad_group_ad = { - 'ad': ad, - 'adGroupId': ad_group_id - } - - operations = [{ - 'operation': 'ADD', - 'operand': ad_group_ad - }] - - return ad_group_ad_service.mutate(operations)['value'][0] - - -def AttachUserList(client, ad_group_id, user_list_id): - """Links the provided ad group and user list. - - Args: - client: an AdWordsClient instance. - ad_group_id: an int ad group ID. - user_list_id: an int user list ID. - - Returns: - The ad group criterion that was successfully created. - """ - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', 'v201806') - - user_list = { - 'xsi_type': 'CriterionUserList', - 'userListId': user_list_id - } - - ad_group_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'criterion': user_list, - 'adGroupId': ad_group_id - } - - operations = [{ - 'operator': 'ADD', - 'operand': ad_group_criterion - }] - - return ad_group_criterion_service.mutate(operations)['value'][0] - - -def CreateDynamicDisplayAdSettings(client, opener): - """Creates dynamic display ad settings. - - Args: - client: an AdWordsClient instance. - opener: an OpenerDirector instance. - - Returns: - A dict containing the dynamic display ad settings. - """ - media_service = client.GetService('MediaService', 'v201806') - - logo = { - 'xsi_type': 'Image', - 'mediaId': _CreateImage(media_service, opener, 'https://goo.gl/dEvQeF') - } - - dynamic_settings = { - 'landscapeLogoImage': logo, - 'pricePrefix': 'as low as', - 'promoText': 'Free shipping!' - } - - return dynamic_settings - - -def _CreateImage(media_service, opener, url): - """Creates an image and uploads it to the server. - - Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. - opener: an OpenerDirector instance. - url: a str URL used to load image data. - - Returns: - The image that was successfully uploaded. - """ - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - image_data = opener.open(url).read().decode('utf-8') - image = { - 'type': 'IMAGE', - 'data': image_data, - 'xsi_type': 'Image' - } - - return media_service.upload(image)[0] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, MERCHANT_ID, BUDGET_ID, USER_LIST_ID) diff --git a/examples/adwords/v201806/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201806/advanced_operations/add_universal_app_campaign.py deleted file mode 100755 index 3149fb47..00000000 --- a/examples/adwords/v201806/advanced_operations/add_universal_app_campaign.py +++ /dev/null @@ -1,218 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Universal App campaign. - -To get campaigns, run get_campaigns.py. To upload image assets for this -campaign, run upload_image.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201806') - - budget_id = CreateBudget(client) - - # Create the Universal App campaign. - universal_app_campaign = { - 'name': 'Interplanetary Cruise App #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'MULTI_CHANNEL', - 'advertisingChannelSubType': 'UNIVERSAL_APP_CAMPAIGN', - # Set the campaign's bidding strategy. Universal app campaigns only - # support TARGET_CPA bidding strategy. - 'biddingStrategyConfiguration': { - # Set the target CPA to $1 / app install. - 'biddingScheme': { - 'xsi_type': 'TargetCpaBiddingScheme', - 'targetCpa': { - 'microAmount': '1000000' - } - }, - 'biddingStrategyType': 'TARGET_CPA' - }, - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - } - - universal_app_campaign['settings'] = [ - # Set the campaign's assets and ad text ideas. These values will - # be used to generate ads. - { - 'xsi_type': 'UniversalAppCampaignSetting', - 'appId': 'com.labpixies.colordrips', - 'appVendor': 'VENDOR_GOOGLE_MARKET', - 'description1': 'A cool puzzle game', - 'description2': 'Remove connected blocks', - 'description3': '3 difficulty levels', - 'description4': '4 colorful fun skins', - # Optional: You can set up to 20 image assets for your campaign. - # See upload_image.py for an example on how to upload images. - # - # 'imageMediaIds': [INSERT_IMAGE_MEDIA_ID(s)_HERE] - } - ] - - # Optimize this campaign for getting new users for your app. - universal_app_campaign_setting = universal_app_campaign['settings'][0] - universal_app_campaign_setting['universalAppBiddingStrategyGoalType'] = ( - 'OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME') - - # Optional: If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, - # then also specify your in-app conversion types so AdWords can focus your - # campaign on people who are most likely to complete the corresponding in-app - # actions. - # - # Conversions type IDs can be retrieved using ConversionTrackerService.get. - # universal_app_campaign['selectiveOptimization'] = { - # 'conversionTypeIds': [INSERT_CONVERSION_TYPE_ID(s)_HERE] - # } - - # Optional: Set the campaign settings for Advanced location options. - universal_app_campaign['settings'].append({ - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - }) - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': universal_app_campaign - }] - - campaigns = campaign_service.mutate(operations)['value'] - - # Display results. - if campaigns: - for campaign in campaigns: - print ('Universal App Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - # Optional: Set the campaign's location and language targeting. No other - # targeting criteria can be used for Universal App campaigns. - SetCampaignTargetingCriteria(client, campaign) - else: - print 'No Universal App campaigns were added.' - - -def CreateBudget(client): - """Creates a budget and returns its budgetId. - - Args: - client: An AdWordsClient instance. - - Returns: - An int budgetId for the created Budget. - """ - budget_service = client.GetService('BudgetService', version='v201806') - - # Create a budget. - budget = { - 'name': 'Interplanetary Cruise App Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': False - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Create the budget and return its ID. - budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId'] - - return budget_id - - -def SetCampaignTargetingCriteria(client, campaign): - """Sets targeting criteria for the given campaign. - - Args: - client: An AdWordsClient instance. - campaign: A suds object representing the campaign we wish to attach - targeting criteria. - """ - campaign_criterion_service = client.GetService('CampaignCriterionService') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - criteria = [ - { - 'xsi_type': 'Location', - 'id': 21137 # California - }, - { - 'xsi_type': 'Location', - 'id': 2484 # Mexico - }, - { - 'xsi_type': 'Language', - 'id': 1000 # English - }, - { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - ] - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign['id'], - 'criterion': criterion - } - } for criterion in criteria] - - response = campaign_criterion_service.mutate(operations) - - if response and 'value' in response: - # Display the added campaign targets. - for criterion in response['value']: - print ('Campaign criteria of type "%s" and id "%s" was added.' - % (criterion['criterion']['type'], - criterion['criterion']['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201806/advanced_operations/create_and_attach_shared_keyword_set.py deleted file mode 100755 index 0bd0a11f..00000000 --- a/examples/adwords/v201806/advanced_operations/create_and_attach_shared_keyword_set.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Attaches a new shared list of negative broad match keywords to a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_set_service = client.GetService('SharedSetService', version='v201806') - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201806') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201806') - - # Keywords to create a shared set of. - keywords = ['mars cruise', 'mars hotels'] - # Create shared negative keyword set. - shared_set = { - 'name': 'API Negative keyword list - %d' % uuid.uuid4(), - 'type': 'NEGATIVE_KEYWORDS' - } - - # Add shared set. - operations = [{ - 'operator': 'ADD', - 'operand': shared_set - }] - - response = shared_set_service.mutate(operations) - - if response and response['value']: - shared_set = response['value'][0] - shared_set_id = shared_set['sharedSetId'] - - print 'Shared set with ID %d and name "%s" was successfully added.' % ( - shared_set_id, shared_set['name'] - ) - else: - raise errors.GoogleAdsError('No shared set was added.') - - # Add negative keywords to shared set. - shared_criteria = [ - { - 'criterion': { - 'xsi_type': 'Keyword', - 'text': keyword, - 'matchType': 'BROAD' - }, - 'negative': True, - 'sharedSetId': shared_set_id - } for keyword in keywords - ] - - operations = [ - { - 'operator': 'ADD', - 'operand': criterion - } for criterion in shared_criteria - ] - - response = shared_criterion_service.mutate(operations) - - if 'value' in response: - for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( - shared_criteria['criterion']['id'], - shared_criteria['criterion']['text'], - shared_criteria['sharedSetId'] - ) - else: - raise errors.GoogleAdsError('No shared keyword was added.') - - # Attach the articles to the campaign. - campaign_set = { - 'campaignId': campaign_id, - 'sharedSetId': shared_set_id - } - - operations = [ - { - 'operator': 'ADD', - 'operand': campaign_set - } - ] - - response = campaign_shared_set_service.mutate(operations) - - if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( - response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) - else: - raise errors.GoogleAdsError('No campaign shared set was added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201806/advanced_operations/find_and_remove_criteria_from_shared_set.py deleted file mode 100755 index 0d6356c1..00000000 --- a/examples/adwords/v201806/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Demonstrates how to find and remove shared sets/shared set criterions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 500 - - -def main(client, campaign_id): - # Initialize appropriate services. - shared_criterion_service = client.GetService('SharedCriterionService', - version='v201806') - campaign_shared_set_service = client.GetService('CampaignSharedSetService', - version='v201806') - - shared_set_ids = [] - criterion_ids = [] - - # First, retrieve all shared sets associated with the campaign. - - # Create selector for shared sets to: - # - filter by campaign ID, - # - filter by shared set type. - selector = { - 'fields': ['SharedSetId', 'CampaignId', 'SharedSetName', 'SharedSetType', - 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - }, - { - 'field': 'SharedSetType', - 'operator': 'IN', - 'values': ['NEGATIVE_KEYWORDS', 'NEGATIVE_PLACEMENTS'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = campaign_shared_set_service.get(selector) - if 'entries' in page: - for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( - shared_set['sharedSetId'], shared_set['sharedSetName'] - ) - shared_set_ids.append(shared_set['sharedSetId']) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Next, retrieve criterion IDs for all found shared sets. - selector = { - 'fields': ['SharedSetId', 'Id', 'KeywordText', 'KeywordMatchType', - 'PlacementUrl'], - 'predicates': [ - { - 'field': 'SharedSetId', - 'operator': 'IN', - 'values': shared_set_ids - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - # Set initial values: - offset = 0 - page = {'totalNumEntries': 1} - - while page['totalNumEntries'] > offset: - page = shared_criterion_service.get(selector) - if 'entries' in page: - for shared_criterion in page['entries']: - if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) - elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) - else: - print 'Shared criterion with ID %d was found.' % ( - shared_criterion['criterion']['id'], - ) - criterion_ids.append({ - 'sharedSetId': shared_criterion['sharedSetId'], - 'criterionId': shared_criterion['criterion']['id'] - }) - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = offset - - # Finally, remove the criteria. - if criterion_ids: - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'criterion': {'id': criterion['criterionId']}, - 'sharedSetId': criterion['sharedSetId'] - } - } for criterion in criterion_ids - ] - - response = shared_criterion_service.mutate(operations) - if 'value' in response: - for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) - else: - print 'No shared criteria were removed.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201806/advanced_operations/get_ad_group_bid_modifier.py deleted file mode 100755 index 4b470490..00000000 --- a/examples/adwords/v201806/advanced_operations/get_ad_group_bid_modifier.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the ad group level bid modifiers for a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - ad_group_bid_modifier_service = client.GetService( - 'AdGroupBidModifierService', version='v201806') - - # Get all ad group bid modifiers for the campaign. - selector = { - 'fields': ['CampaignId', 'AdGroupId', 'BidModifier', 'Id'], - 'paging': { - 'startIndex': '0', - 'numberResults': str(PAGE_SIZE) - } - } - - # Set initial values. - offset, page = 0, {} - more_results = True - - while more_results: - page = ad_group_bid_modifier_service.get(selector) - if page['entries']: - for modifier in page['entries']: - value = (modifier['bidModifier'] if 'bidModifier' in modifier - else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) - - # Increment values to request the next page. - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - else: - print 'No ad group bid modifiers returned.' - more_results = int(page['totalNumEntries']) > offset - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201806/advanced_operations/use_shared_bidding_strategy.py deleted file mode 100755 index 0f3138da..00000000 --- a/examples/adwords/v201806/advanced_operations/use_shared_bidding_strategy.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds a Shared Bidding Strategy and uses it to construct a campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -# Enter a shared budget ID to re-use an existing budget or leave as None to -# create a new one. -BUDGET_ID = None - - -def main(client, budget_id): - bidding_strategy = CreateBiddingStrategy(client) - - if budget_id is None: - budget = CreateSharedBudget(client) - budget_id = budget['budgetId'] - - CreateCampaignWithBiddingStrategy(client, bidding_strategy['id'], budget_id) - - -def CreateBiddingStrategy(client): - """Creates a bidding strategy object. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a bidding strategy. - """ - # Initialize appropriate service. - bidding_strategy_service = client.GetService( - 'BiddingStrategyService', version='v201806') - - # Create a shared bidding strategy. - shared_bidding_strategy = { - 'name': 'Maximize Clicks %s' % uuid.uuid4(), - 'biddingScheme': { - 'xsi_type': 'TargetSpendBiddingScheme', - # Optionally set additional bidding scheme parameters. - 'bidCeiling': { - 'microAmount': '2000000' - } - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': shared_bidding_strategy - } - - response = bidding_strategy_service.mutate([operation]) - new_bidding_strategy = response['value'][0] - - print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) - - return new_bidding_strategy - - -def CreateSharedBudget(client): - """Creates an explicit budget to be used only to create the Campaign. - - Args: - client: AdWordsClient the client to run the example with. - - Returns: - dict An object representing a shared budget. - """ - # Initialize appropriate service. - budget_service = client.GetService('BudgetService', version='v201806') - - # Create a shared budget - budget = { - 'name': 'Shared Interplanetary Budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '2000000' - }, - 'deliveryMethod': 'STANDARD', - 'isExplicitlyShared': 'true' - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': budget - } - - response = budget_service.mutate([operation]) - return response['value'][0] - - -def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): - """Create a Campaign with a Shared Bidding Strategy. - - Args: - client: AdWordsClient the client to run the example with. - bidding_strategy_id: string the bidding strategy ID to use. - budget_id: string the shared budget ID to use. - - Returns: - dict An object representing a campaign. - """ - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201806') - - # Create campaign. - campaign = { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyId': bidding_strategy_id - }, - 'advertisingChannelType': 'SEARCH', - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'true' - } - } - - # Create operation. - operation = { - 'operator': 'ADD', - 'operand': campaign - } - - response = campaign_service.mutate([operation]) - new_campaign = response['value'][0] - - print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) - - return new_campaign - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, BUDGET_ID) diff --git a/examples/adwords/v201806/basic_operations/__init__.py b/examples/adwords/v201806/basic_operations/__init__.py deleted file mode 100644 index 1a2bc84a..00000000 --- a/examples/adwords/v201806/basic_operations/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Basic operations examples.""" diff --git a/examples/adwords/v201806/basic_operations/add_ad_groups.py b/examples/adwords/v201806/basic_operations/add_ad_groups.py deleted file mode 100755 index c3d54ca0..00000000 --- a/examples/adwords/v201806/basic_operations/add_ad_groups.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad groups to a given campaign. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201806') - - # Construct operations and add ad groups. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Mars Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - }, - } - ] - }, - 'settings': [ - { - # Targeting restriction settings. Depending on the - # criterionTypeGroup value, most TargetingSettingDetail only - # affect Display campaigns. However, the - # USER_INTEREST_AND_LIST value works for RLSA campaigns - - # Search campaigns targeting using a remarketing list. - 'xsi_type': 'TargetingSetting', - 'details': [ - # Restricting to serve ads that match your ad group - # placements. This is equivalent to choosing - # "Target and bid" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'PLACEMENT', - 'targetAll': 'false', - }, - # Using your ad group verticals only for bidding. This is - # equivalent to choosing "Bid only" in the UI. - { - 'xsi_type': 'TargetingSettingDetail', - 'criterionTypeGroup': 'VERTICAL', - 'targetAll': 'true', - }, - ] - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'name': 'Earth to Venus Cruises #%s' % uuid.uuid4(), - 'status': 'ENABLED', - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was added.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/basic_operations/add_campaigns.py b/examples/adwords/v201806/basic_operations/add_campaigns.py deleted file mode 100755 index d7b6104b..00000000 --- a/examples/adwords/v201806/basic_operations/add_campaigns.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds campaigns. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import datetime -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - campaign_service = client.GetService('CampaignService', version='v201806') - budget_service = client.GetService('BudgetService', version='v201806') - - # Create a budget, which can be shared by multiple campaigns. - budget = { - 'name': 'Interplanetary budget #%s' % uuid.uuid4(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - } - - budget_operations = [{ - 'operator': 'ADD', - 'operand': budget - }] - - # Add the budget. - budget_id = budget_service.mutate(budget_operations)['value'][0][ - 'budgetId'] - - # Construct operations and add campaigns. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once you've - # added targeting and the ads are ready to serve. - 'status': 'PAUSED', - 'advertisingChannelType': 'SEARCH', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC', - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'networkSetting': { - 'targetGoogleSearch': 'true', - 'targetSearchNetwork': 'true', - 'targetContentNetwork': 'false', - 'targetPartnerSearchNetwork': 'false' - }, - # Optional fields - 'startDate': (datetime.datetime.now() + - datetime.timedelta(1)).strftime('%Y%m%d'), - 'frequencyCap': { - 'impressions': '5', - 'timeUnit': 'DAY', - 'level': 'ADGROUP' - }, - 'settings': [ - { - 'xsi_type': 'GeoTargetTypeSetting', - 'positiveGeoTargetType': 'DONT_CARE', - 'negativeGeoTargetType': 'DONT_CARE' - } - ] - } - }, { - 'operator': 'ADD', - 'operand': { - 'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(), - 'status': 'PAUSED', - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'endDate': (datetime.datetime.now() + - datetime.timedelta(365)).strftime('%Y%m%d'), - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'advertisingChannelType': 'DISPLAY' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201806/basic_operations/add_expanded_text_ads.py deleted file mode 100755 index 77459ca7..00000000 --- a/examples/adwords/v201806/basic_operations/add_expanded_text_ads.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds expanded text ads to a given ad group. - -To get ad_group_id, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': ('Cruise #%s to Mars' - % str(uuid.uuid4())[:8]), - 'headlinePart2': 'Best Space Cruise Line', - 'description': 'Buy your tickets now!', - 'finalUrls': ['http://www.example.com/%s' % i], - }, - # Optional fields. - 'status': 'PAUSED' - } - } for i in range(NUMBER_OF_ADS) - ] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/add_keywords.py b/examples/adwords/v201806/basic_operations/add_keywords.py deleted file mode 100755 index 510f1982..00000000 --- a/examples/adwords/v201806/basic_operations/add_keywords.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds ad group criteria to an ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201806') - - # Construct keyword ad group criterion object. - keyword1 = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars' - }, - # These fields are optional. - 'userStatus': 'PAUSED', - 'finalUrls': { - 'urls': ['http://example.com/mars'] - } - } - - keyword2 = { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'EXACT', - 'text': 'pluto' - } - } - - # Construct operations and add ad group criteria. - operations = [ - { - 'operator': 'ADD', - 'operand': keyword1 - }, - { - 'operator': 'ADD', - 'operand': keyword2 - } - ] - ad_group_criteria = ad_group_criterion_service.mutate( - operations)['value'] - - # Display results. - for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id "%s", criterion id ' - '"%s", text "%s", and match type "%s" was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/add_responsive_search_ad.py b/examples/adwords/v201806/basic_operations/add_responsive_search_ad.py deleted file mode 100755 index e633f505..00000000 --- a/examples/adwords/v201806/basic_operations/add_responsive_search_ad.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 Google LLC -# -# 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 -# -# https://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 adds a responsive search ad to a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -NUMBER_OF_ADS = 5 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - responsive_search_ad = { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ResponsiveSearchAd', - 'finalUrls': ['http://www.example.com/cruise'], - 'path1': 'all-inclusive', - 'path2': 'deals', - 'headlines': [{ - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Cruise to Mars # ' + str(uuid.uuid4())[:8] - }, - 'pinnedField': 'HEADLINE_1' - }, { - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Best Space Cruise Line', - } - }, { - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Experience the Stars' - } - }], - 'descriptions': [{ - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Buy your tickets now.' - } - }, { - 'asset': { - 'xsi_type': 'TextAsset', - 'assetText': 'Visit the Red Planet', - } - }], - }, - # Optional fields. - 'status': 'PAUSED' - } - - # Create the operations. - operations = [{ - 'operator': 'ADD', - 'operand': responsive_search_ad - }] - - # Create the ad on the server. - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - ad = ad['ad'] - print ('Ad of type "%s" with id "%d" was added.\n' - 'Headlines:\n%s\n' - 'Descriptions:\n%s' - % (ad['Ad.Type'], ad['id'], - '\n'.join(['\t%s (pinned to %s)' % - (headline['asset']['assetText'], - headline['pinnedField']) - for headline in ad['headlines']]), - '\n'.join(['\t%s (pinned to %s)' % - (headline['asset']['assetText'], - headline['pinnedField']) - for headline in ad['descriptions']]))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/get_ad_groups.py b/examples/adwords/v201806/basic_operations/get_ad_groups.py deleted file mode 100755 index 57909335..00000000 --- a/examples/adwords/v201806/basic_operations/get_ad_groups.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 groups for a given campaign. - -To add an ad group, run add_ad_group.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201806') - - # Construct selector and get all ad groups. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'predicates': [ - { - 'field': 'CampaignId', - 'operator': 'EQUALS', - 'values': [campaign_id] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = ad_group_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group in page['entries']: - print ('Ad group with name "%s", id "%s" and status "%s" was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) - else: - print 'No ad groups were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/basic_operations/get_campaigns.py b/examples/adwords/v201806/basic_operations/get_campaigns.py deleted file mode 100755 index a79a81cc..00000000 --- a/examples/adwords/v201806/basic_operations/get_campaigns.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201806') - - # Construct selector and get all campaigns. - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Status'], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201806/basic_operations/get_campaigns_with_awql.py deleted file mode 100755 index 5d1964d2..00000000 --- a/examples/adwords/v201806/basic_operations/get_campaigns_with_awql.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with AWQL. - -To add a campaign, run add_campaign.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201806') - - # Construct query and get all campaigns. - query = (adwords.ServiceQueryBuilder() - .Select('Id', 'Name', 'Status') - .Where('Status').EqualTo('ENABLED') - .OrderBy('Name') - .Limit(0, PAGE_SIZE) - .Build()) - - for page in query.Pager(campaign_service): - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) - else: - print 'No campaigns were found.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201806/basic_operations/get_expanded_text_ads.py deleted file mode 100755 index 0e552503..00000000 --- a/examples/adwords/v201806/basic_operations/get_expanded_text_ads.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 expanded text ads for a given ad group. - -To add an expanded text ad, run add_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'AdGroupId', 'Status', 'HeadlinePart1', 'HeadlinePart2', - 'Description'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['EXPANDED_TEXT_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/get_keywords.py b/examples/adwords/v201806/basic_operations/get_keywords.py deleted file mode 100755 index d302dcb0..00000000 --- a/examples/adwords/v201806/basic_operations/get_keywords.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 group criteria in an account. - -To add keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' - - -def main(client, adgroup_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201806') - - # Construct selector and get all ad group criteria. - offset = 0 - selector = { - 'fields': ['Id', 'CriteriaType', 'KeywordMatchType', 'KeywordText'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [adgroup_id] - }, - { - 'field': 'CriteriaType', - 'operator': 'EQUALS', - 'values': ['KEYWORD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [{'field': 'KeywordText', 'sortOrder': 'ASCENDING'}] - } - more_pages = True - while more_pages: - page = ad_group_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for keyword in page['entries']: - print ('Keyword ID "%s", type "%s", text "%s", and match type ' - '"%s" was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) - else: - print 'No keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/get_responsive_search_ads.py b/examples/adwords/v201806/basic_operations/get_responsive_search_ads.py deleted file mode 100755 index 16f5fbbc..00000000 --- a/examples/adwords/v201806/basic_operations/get_responsive_search_ads.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 Google LLC -# -# 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 -# -# https://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 non-removed responsive search ads in a specified ad group. - -To add responsive search ads, run add_responsive_search_ad.py. To get ad groups, -run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'Status', 'ResponsiveSearchAdHeadlines', - 'ResponsiveSearchAdDescriptions'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'AdType', - 'operator': 'EQUALS', - 'values': ['RESPONSIVE_SEARCH_AD'] - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'ordering': [ - { - 'field': 'Id', - 'sortOrder': 'ASCENDING' - } - ] - } - - more_pages = True - while more_pages: - page = ad_group_ad_service.get(selector) - - # Display results. - if 'entries' in page: - for ad_group_ad in page['entries']: - ad = ad_group_ad['ad'] - print ('Responsive search ad with status %s and id "%d" was found.\n' - 'Headlines:\n%s\n' - 'Descriptions:\n%s' - % (ad_group_ad['status'], ad['id'], - '\n'.join(['\t%s (pinned to %s)' % - (headline['asset']['assetText'], - headline['pinnedField']) - for headline in ad['headlines']]), - '\n'.join(['\t%s (pinned to %s)' % - (headline['asset']['assetText'], - headline['pinnedField']) - for headline in ad['descriptions']]))) - else: - print 'No ads were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/pause_ad.py b/examples/adwords/v201806/basic_operations/pause_ad.py deleted file mode 100755 index be54b6ac..00000000 --- a/examples/adwords/v201806/basic_operations/pause_ad.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates status for a given ad. - -To get ads, run get_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Construct operations and update an ad. - operations = [{ - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id, - }, - 'status': 'PAUSED' - } - }] - ads = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in ads['value']: - print 'Ad with id "%s" was updated.'% ad['ad']['id'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201806/basic_operations/remove_ad.py b/examples/adwords/v201806/basic_operations/remove_ad.py deleted file mode 100755 index 4ebcb023..00000000 --- a/examples/adwords/v201806/basic_operations/remove_ad.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad using the 'REMOVE' operator. - -To get ads, run get_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_group_id, ad_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Construct operations and delete ad. - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'id': ad_id - } - } - }] - result = ad_group_ad_service.mutate(operations) - - # Display results. - for ad in result['value']: - print ('Ad with id "%s" and type "%s" was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, AD_ID) diff --git a/examples/adwords/v201806/basic_operations/remove_ad_group.py b/examples/adwords/v201806/basic_operations/remove_ad_group.py deleted file mode 100755 index 45790fd6..00000000 --- a/examples/adwords/v201806/basic_operations/remove_ad_group.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group by setting the status to 'REMOVED'. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201806') - - # Construct operations and delete ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'REMOVED' - } - }] - result = ad_group_service.mutate(operations) - - # Display results. - for ad_group in result['value']: - print ('Ad group with name "%s" and id "%s" was deleted.' - % (ad_group['name'], ad_group['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/basic_operations/remove_campaign.py b/examples/adwords/v201806/basic_operations/remove_campaign.py deleted file mode 100755 index 9c9cae62..00000000 --- a/examples/adwords/v201806/basic_operations/remove_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes a campaign by setting the status to 'REMOVED'. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201806') - - # Construct operations and delete campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'REMOVED' - } - }] - result = campaign_service.mutate(operations) - - # Display results. - for campaign in result['value']: - print ('Campaign with name "%s" and id "%s" was deleted.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/basic_operations/remove_keyword.py b/examples/adwords/v201806/basic_operations/remove_keyword.py deleted file mode 100755 index 4a15a2cb..00000000 --- a/examples/adwords/v201806/basic_operations/remove_keyword.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 deletes an ad group criterion using the 'REMOVE' operator. - -To get ad group criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201806') - - # Construct operations and delete ad group criteria. - operations = [ - { - 'operator': 'REMOVE', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id - } - } - } - ] - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - print ('Ad group criterion with ad group id "%s", criterion id "%s", ' - 'and type "%s" was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['Criterion.Type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201806/basic_operations/update_ad_group.py b/examples/adwords/v201806/basic_operations/update_ad_group.py deleted file mode 100755 index 879c7334..00000000 --- a/examples/adwords/v201806/basic_operations/update_ad_group.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the CPC bid and status for a given ad group. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CPC_BID_MICRO_AMOUNT = 'INSERT_CPC_BID_MICRO_AMOUNT_HERE' - - -def main(client, ad_group_id, bid_micro_amount=None): - # Initialize appropriate service. - ad_group_service = client.GetService('AdGroupService', version='v201806') - - # Construct operations and update an ad group. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': ad_group_id, - 'status': 'PAUSED' - } - }] - - if bid_micro_amount: - operations[0]['operand']['biddingStrategyConfiguration'] = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': bid_micro_amount, - } - }] - } - - ad_groups = ad_group_service.mutate(operations) - - # Display results. - for ad_group in ad_groups['value']: - bidding_strategy_configuration = ad_group['biddingStrategyConfiguration'] - # Find the CpcBid in the bidding strategy configuration's bids collection. - cpc_bid_micros = None - - if bidding_strategy_configuration: - bids = bidding_strategy_configuration['bids'] - - if bids: - for bid in bids: - if bid['Bids.Type'] == 'CpcBid': - cpc_bid_micros = bid['bid']['microAmount'] - break - - print ('Ad group with name "%s", and id "%s" was updated to have status ' - '"%s" and CPC bid %d.' - % (ad_group['name'], ad_group['id'], ad_group['status'], - cpc_bid_micros)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CPC_BID_MICRO_AMOUNT) diff --git a/examples/adwords/v201806/basic_operations/update_campaign.py b/examples/adwords/v201806/basic_operations/update_campaign.py deleted file mode 100755 index 39f999d9..00000000 --- a/examples/adwords/v201806/basic_operations/update_campaign.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates a campaign by setting its status to PAUSED. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201806') - - # Construct operations and update campaign. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'status': 'PAUSED' - } - }] - campaigns = campaign_service.mutate(operations) - - # Display results. - for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was updated.' - % (campaign['name'], campaign['id'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/basic_operations/update_expanded_text_ad.py b/examples/adwords/v201806/basic_operations/update_expanded_text_ad.py deleted file mode 100755 index 20da1137..00000000 --- a/examples/adwords/v201806/basic_operations/update_expanded_text_ad.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 Google LLC -# -# 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 -# -# https://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 updates an expanded text ad. - -To get expanded text ads, run get_expanded_text_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import uuid -from googleads import adwords - - -AD_ID = 'INSERT_AD_ID_HERE' - - -def main(client, ad_id): - # Initialize appropriate service. - ad_service = client.GetService('AdService', version='v201806') - - # Create an expanded text ad using the provided ad ID. - expanded_text_ad = { - 'xsi_type': 'ExpandedTextAd', - 'id': ad_id, - 'headlinePart1': 'Cruise to Pluto #' + str(uuid.uuid4())[:8], - 'headlinePart2': 'Tickets on sale now', - 'description': 'Best space cruise ever.', - 'finalUrls': ['http://www.example.com'], - 'finalMobileUrls': ['http://www.example.com/mobile'] - } - - # Create ad group ad operation. - operations = [{ - 'operator': 'SET', - 'operand': expanded_text_ad - }] - - # Updates the ad on ther server. - result = ad_service.mutate(operations) - updated_ad = result['value'][0] - - print 'Expanded text ad with ID %s was updated.' % updated_ad['id'] - print ('\tHeadline part 1: %s\nHeadline part 2: %s\nDescription: %s\n' - 'Final URL: %s\nFinal mobile URL: %s' % - (updated_ad['headlinePart1'], - updated_ad['headlinePart2'], - updated_ad['description'], - updated_ad['finalUrls'][0], - updated_ad['finalMobileUrls'][0])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_ID) diff --git a/examples/adwords/v201806/basic_operations/update_keyword.py b/examples/adwords/v201806/basic_operations/update_keyword.py deleted file mode 100755 index ba612d58..00000000 --- a/examples/adwords/v201806/basic_operations/update_keyword.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 updates the bid of a keyword. - -To add a keyword, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201806') - - # Construct operations and update bids. - - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'id': criterion_id, - }, - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': '1000000' - } - } - ] - } - } - }] - ad_group_criteria = ad_group_criterion_service.mutate(operations) - - # Display results. - if 'value' in ad_group_criteria: - for criterion in ad_group_criteria['value']: - if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id "%s" and criterion id ' - '"%s" currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) - for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: "%s", value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) - else: - print 'No ad group criteria were updated.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201806/campaign_management/__init__.py b/examples/adwords/v201806/campaign_management/__init__.py deleted file mode 100644 index afa503f3..00000000 --- a/examples/adwords/v201806/campaign_management/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Campaign management examples.""" diff --git a/examples/adwords/v201806/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201806/campaign_management/add_campaign_groups_and_performance_targets.py deleted file mode 100755 index 56ea182a..00000000 --- a/examples/adwords/v201806/campaign_management/add_campaign_groups_and_performance_targets.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a campaign group and sets a performance target for it. - -To get campaigns, run get_campaigns.py. To download reports, run -download_criteria_report_with_awql.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import datetime -import uuid -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id1, campaign_id2): - campaign_group_id = _CreateCampaignGroup(client) - _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) - _CreatePerformanceTarget(client, campaign_group_id) - print 'Campaign group and its performance target were setup successfully.' - - -def _CreateCampaignGroup(client): - """Create a campaign group. - - Args: - client: an AdWordsClient instance. - - Returns: - The integer ID of the created campaign group. - """ - # Get the CampaignGroupService. - campaign_group_service = client.GetService('CampaignGroupService', - version='v201806') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the campaign group. - 'operand': { - 'name': 'Mars campaign group #%d' % uuid.uuid4() - } - }] - - campaign_group = campaign_group_service.mutate(operations)['value'][0] - campaign_group_id = campaign_group['id'] - - # Display the results. - print 'Campaign group with ID "%d" and name "%s" was created.' % ( - campaign_group_id, campaign_group['name']) - - return campaign_group_id - - -def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): - """Adds multiple campaigns to a campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - campaign_ids: a list of integer IDs for campaigns. - """ - # Get the CampaignService. - campaign_service = client.GetService('CampaignService', version='v201806') - - # Create the operations. - operations = [{ - 'operator': 'SET', - 'operand': { - 'id': campaign_id, - 'campaignGroupId': campaign_group_id - } - } for campaign_id in campaign_ids] - - campaign_service.mutate(operations) - - # Display the results. - print ('The following campaign IDs were added to the campaign group with ID ' - '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) - - -def _CreatePerformanceTarget(client, campaign_group_id): - """Creates a performance target for the campaign group. - - Args: - client: an AdWordsClient instance. - campaign_group_id: an integer ID for the campaign group. - """ - # Get the CampaignGroupPerformanceTargetService. - cgpt_service = client.GetService('CampaignGroupPerformanceTargetService', - version='v201806') - - # Create the operation. - operations = [{ - 'operator': 'ADD', - # Create the performance target. - 'operand': { - 'campaignGroupId': campaign_group_id, - 'performanceTarget': { - # Keep the CPC for the campaigns < $3. - 'efficiencyTargetType': 'CPC_LESS_THAN_OR_EQUAL_TO', - 'efficiencyTargetValue': 3000000, - # Keep the maximum spend under $50. - 'spendTargetType': 'MAXIMUM', - 'spendTarget': { - 'microAmount': 500000000 - }, - # Aim for at least 3000 clicks. - 'volumeGoalType': 'MAXIMIZE_CLICKS', - 'volumeTargetValue': 3000, - # Start the performance target today, and run it for the next 90 - # days. - 'startDate': datetime.datetime.now().strftime('%Y%m%d'), - 'endDate': (datetime.datetime.now() + - datetime.timedelta(90)).strftime('%Y%m%d') - } - } - }] - - cgpt = cgpt_service.mutate(operations)['value'][0] - - # Display the results. - print ('Campaign performance target with ID "%d" was added for campaign ' - 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2) diff --git a/examples/adwords/v201806/campaign_management/add_campaign_labels.py b/examples/adwords/v201806/campaign_management/add_campaign_labels.py deleted file mode 100755 index 4e8625d0..00000000 --- a/examples/adwords/v201806/campaign_management/add_campaign_labels.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a label to multiple campaigns. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID1 = 'INSERT_FIRST_CAMPAIGN_ID_HERE' -CAMPAIGN_ID2 = 'INSERT_SECOND_CAMPAIGN_ID_HERE' -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, campaign_id1, campaign_id2, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201806') - - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id1, - 'labelId': label_id, - } - }, - { - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id2, - 'labelId': label_id, - } - } - ] - - result = campaign_service.mutateLabel(operations) - - # Display results. - for label in result['value']: - print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' - % (label['campaignId'], label['labelId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID1, CAMPAIGN_ID2, LABEL_ID) diff --git a/examples/adwords/v201806/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201806/campaign_management/add_complete_campaigns_using_batch_job.py deleted file mode 100755 index a1ea42f1..00000000 --- a/examples/adwords/v201806/campaign_management/add_complete_campaigns_using_batch_job.py +++ /dev/null @@ -1,428 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uses the BatchJobService to create a complete Campaign. - -The complete Campaign created by this example also includes AdGroups and -KeyWords. - -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -NUMBER_OF_CAMPAIGNS_TO_ADD = 2 -NUMBER_OF_ADGROUPS_TO_ADD = 2 -NUMBER_OF_KEYWORDS_TO_ADD = 5 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201806') - - # Create a BatchJob. - batch_job = AddBatchJob(client) - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Generate operations to upload. - budget_operations = BuildBudgetOperations(batch_job_helper) - campaign_operations = BuildCampaignOperations( - batch_job_helper, budget_operations, number_of_campaigns) - campaign_criterion_operations = BuildCampaignCriterionOperations( - campaign_operations) - adgroup_operations = BuildAdGroupOperations( - batch_job_helper, campaign_operations, number_of_adgroups) - adgroup_criterion_operations = BuildAdGroupCriterionOperations( - adgroup_operations, number_of_keywords) - adgroup_ad_operations = BuildAdGroupAdOperations(adgroup_operations) - - # Upload operations. - batch_job_helper.UploadOperations( - upload_url, budget_operations, campaign_operations, - campaign_criterion_operations, adgroup_operations, - adgroup_criterion_operations, adgroup_ad_operations) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201806') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupAdOperations(adgroup_operations): - """Builds the operations adding an ExpandedTextAd to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - - Returns: - a list containing the operations that will create a new ExpandedTextAd for - each of the provided AdGroups. - """ - adgroup_ad_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupAdOperation', - 'operand': { - 'adGroupId': adgroup_operation['operand']['id'], - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com/1'] - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations] - - return adgroup_ad_operations - - -def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_operations: a list containing the operations that will add AdGroups. - number_of_keywords: an int defining the number of Keywords to be created. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - # Make 50% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (i, '!!!' if i % 2 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for adgroup_operation in adgroup_operations - for i in range(number_of_keywords)] - - return criterion_operations - - -def BuildAdGroupOperations(batch_job_helper, - campaign_operations, number_of_adgroups=1): - """Builds the operations adding desired number of AdGroups to given Campaigns. - - Note: When the AdGroups are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - campaign_operations: a list containing the operations that will add - Campaigns. - number_of_adgroups: an int defining the number of AdGroups to be created per - Campaign. - - Returns: - a list containing the operations that will add the desired number of - AdGroups to each of the provided Campaigns. - """ - adgroup_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'AdGroupOperation', - 'operand': { - 'campaignId': campaign_operation['operand']['id'], - 'id': batch_job_helper.GetId(), - 'name': 'Batch Ad Group #%s' % uuid.uuid4(), - 'biddingStrategyConfiguration': { - 'bids': [ - { - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 10000000 - } - } - ] - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations - for _ in range(number_of_adgroups)] - - return adgroup_operations - - -def BuildBudgetOperations(batch_job_helper): - """Builds the operations needed to create a new Budget. - - Note: When the Budget is created, it will have a different Id than the one - generated here as a temporary Id. This is just used to identify it in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - - Returns: - a list containing the operation that will create a new Budget. - """ - # A list of operations creating a Budget. - budget_operations = [{ - # The xsi_type of the operation can usually be guessed by the API because - # a given service only handles one type of operation. However, batch jobs - # process operations of different types, so the xsi_type must always be - # explicitly defined for these operations. - 'xsi_type': 'BudgetOperation', - 'operand': { - 'name': 'Batch budget #%s' % uuid.uuid4(), - # This is a temporary Id used by the BatchJobService to identify the - # Budget for operations that require a budgetId. - 'budgetId': batch_job_helper.GetId(), - 'amount': { - 'microAmount': '50000000' - }, - 'deliveryMethod': 'STANDARD' - }, - 'operator': 'ADD' - }] - - return budget_operations - - -def BuildCampaignCriterionOperations(campaign_operations): - """Builds the operations needed to create Negative Campaign Criterion. - - Args: - campaign_operations: a list containing the operations that will add - Campaigns. - - Returns: - a list containing the operations that will create a new Negative Campaign - Criterion associated with each provided Campaign. - """ - criterion_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignCriterionOperation', - 'operand': { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_operation['operand']['id'], - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus' - } - }, - 'operator': 'ADD' - } - for campaign_operation in campaign_operations] - - return criterion_operations - - -def BuildCampaignOperations(batch_job_helper, - budget_operations, number_of_campaigns=1): - """Builds the operations needed to create a new Campaign. - - Note: When the Campaigns are created, they will have a different Id than those - generated here as a temporary Id. This is just used to identify them in the - BatchJobService. - - Args: - batch_job_helper: a BatchJobHelper instance. - budget_operations: a list containing the operation that will add the budget - used by these Campaigns. - number_of_campaigns: an int number defining the number of campaigns to be - created. - - Returns: - a list containing the operations to create the desired number of Campaigns. - """ - # Grab the temporary budgetId to associate with the new Campaigns. - budget_id = budget_operations[0]['operand']['budgetId'] - - campaign_operations = [ - { - # The xsi_type of the operation can usually be guessed by the API - # because a given service only handles one type of operation. - # However, batch jobs process operations of different types, so - # the xsi_type must always be explicitly defined for these - # operations. - 'xsi_type': 'CampaignOperation', - 'operand': { - 'name': 'Batch Campaign #%s' % uuid.uuid4(), - # Recommendation: Set the campaign to PAUSED when creating it to - # stop the ads from immediately serving. Set to ENABLED once - # you've added targeting and the ads are ready to serve. - 'status': 'PAUSED', - # This is a temporary Id used by the BatchJobService to identify - # the Campaigns for operations that require a campaignId. - 'id': batch_job_helper.GetId(), - 'advertisingChannelType': 'SEARCH', - # Note that only the budgetId is required - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - } - }, - 'operator': 'ADD' - } - for _ in range(number_of_campaigns)] - - return campaign_operations - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201806') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt = 0 - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - raise Exception('Batch Job not finished downloading. Try checking later.') - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, NUMBER_OF_CAMPAIGNS_TO_ADD, NUMBER_OF_ADGROUPS_TO_ADD, - NUMBER_OF_KEYWORDS_TO_ADD) diff --git a/examples/adwords/v201806/campaign_management/add_draft.py b/examples/adwords/v201806/campaign_management/add_draft.py deleted file mode 100755 index cd33973d..00000000 --- a/examples/adwords/v201806/campaign_management/add_draft.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a draft and accesses its associated draft campaign. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' - - -def main(client, base_campaign_id): - draft_service = client.GetService('DraftService', version='v201806') - - draft = { - 'baseCampaignId': base_campaign_id, - 'draftName': 'Test Draft #%s' % uuid.uuid4() - } - - draft_operation = {'operator': 'ADD', 'operand': draft} - draft = draft_service.mutate([draft_operation])['value'][0] - draft_campaign_id = draft['draftCampaignId'] - - # Once the draft is created, you can modify the draft campaign as if it were a - # real campaign. For example, you may add criteria, adjust bids, or even - # include additional ads. Adding a criteria is shown here. - campaign_criterion_service = client.GetService('CampaignCriterionService', - version='v201806') - - criterion = { - 'xsi_type': 'Language', - 'id': 1003 # Spanish - } - - criterion_operation = { - # Make sure to use the draftCampaignId when modifying the virtual draft - # campaign. - 'operator': 'ADD', - 'operand': { - 'campaignId': draft_campaign_id, - 'criterion': criterion - } - } - - criterion = campaign_criterion_service.mutate([criterion_operation])[ - 'value'][0] - - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID) diff --git a/examples/adwords/v201806/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201806/campaign_management/add_keywords_using_incremental_batch_job.py deleted file mode 100755 index bb37351e..00000000 --- a/examples/adwords/v201806/campaign_management/add_keywords_using_incremental_batch_job.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to incrementally upload keywords. - -Uses the BatchJobService and BatchJobHelper to incrementally upload operations. -""" - -import random -import time -import urllib2 -import uuid - -from googleads import adwords - - -ADGROUP_ID = 'INSERT_ADGROUP_ID_HERE' -KEYWORD_COUNT = 100 -MAX_POLL_ATTEMPTS = 5 -PENDING_STATUSES = ('ACTIVE', 'AWAITING_FILE', 'CANCELING') - - -def main(client, adgroup_id): - # Initialize BatchJobHelper. - batch_job_helper = client.GetBatchJobHelper(version='v201806') - # Create a BatchJob. - batch_job = AddBatchJob(client) - - # Retrieve the URL used to upload the BatchJob operations. - upload_url = batch_job['uploadUrl']['url'] - batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) - - # Initialize IncrementalUploadHelper. - incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) - - # Generate and upload first set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload second set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations]) - # Generate and upload third and final set of operations. - adgroup_criterion_operations = BuildAdGroupCriterionOperations(adgroup_id) - incremental_uploader.UploadOperations( - [adgroup_criterion_operations], is_last=True) - - # Download and display results. - download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() - PrintResponse(batch_job_helper, response) - - -def AddBatchJob(client): - """Add a new BatchJob to upload operations to. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - - Returns: - The new BatchJob created by the request. - """ - # Initialize appropriate service. - batch_job_service = client.GetService('BatchJobService', version='v201806') - # Create a BatchJob. - batch_job_operations = [{ - 'operand': {}, - 'operator': 'ADD' - }] - return batch_job_service.mutate(batch_job_operations)['value'][0] - - -def BuildAdGroupCriterionOperations(adgroup_id): - """Builds the operations adding a Keyword Criterion to each AdGroup. - - Args: - adgroup_id: an integer identifying an AdGroup to associate the keywords - with. - - Returns: - a list containing the operations that will create a new Keyword Criterion - associated with each provided AdGroup. - """ - criterion_operations = [ - { - # You must specify the xsi_type of operations run by the - # BatchJobService. - 'xsi_type': 'AdGroupCriterionOperation', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': adgroup_id, - 'criterion': { - 'xsi_type': 'Keyword', - # Make 10% of keywords invalid to demonstrate error handling. - 'text': 'mars%s%s' % (uuid.uuid4(), - '!!!' if i % 10 == 0 else ''), - 'matchType': 'BROAD' - } - }, - 'operator': 'ADD' - } - for i in range(KEYWORD_COUNT)] - - return criterion_operations - - -def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): - """Cancels the given BatchJob. - - Args: - client: an instantiated AdWordsClient used to cancel the BatchJob. - batch_job: a BatchJob to be canceled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has been canceled. - """ - batch_job_service = client.GetService('BatchJobService', 'v201806') - batch_job['status'] = 'CANCELING' - - operation = { - 'operator': 'SET', - 'operand': batch_job - } - - batch_job_service.mutate([operation]) - - # Verify that the Batch Job cancels. - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] != 'CANCELED'): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job['id']) - poll_attempt += 1 - - if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) - else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) - - -def GetBatchJob(client, batch_job_id): - """Retrieves the BatchJob with the given id. - - Args: - client: an instantiated AdWordsClient used to retrieve the BatchJob. - batch_job_id: a long identifying the BatchJob to be retrieved. - Returns: - The BatchJob associated with the given id. - """ - batch_job_service = client.GetService('BatchJobService', 'v201806') - - selector = { - 'fields': ['Id', 'Status', 'DownloadUrl'], - 'predicates': [ - { - 'field': 'Id', - 'operator': 'EQUALS', - 'values': [batch_job_id] - } - ] - } - - return batch_job_service.get(selector)['entries'][0] - - -def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, - max_poll_attempts=MAX_POLL_ATTEMPTS): - """Retrieves the downloadUrl when the BatchJob is complete. - - Args: - client: an instantiated AdWordsClient used to poll the BatchJob. - batch_job_id: a long identifying the BatchJob to be polled. - max_poll_attempts: an int defining the number of times the BatchJob will be - checked to determine whether it has completed. - - Returns: - A str containing the downloadUrl of the completed BatchJob. - - Raises: - Exception: If the BatchJob hasn't finished after the maximum poll attempts - have been made. - """ - batch_job = GetBatchJob(client, batch_job_id) - if batch_job['status'] == 'CANCELED': - raise Exception('Batch Job with ID "%s" was canceled before completing.' - % batch_job_id) - - poll_attempt = 0 - - while (poll_attempt in range(max_poll_attempts) and - batch_job['status'] in PENDING_STATUSES): - sleep_interval = (30 * (2 ** poll_attempt) + - (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval - time.sleep(sleep_interval) - batch_job = GetBatchJob(client, batch_job_id) - poll_attempt += 1 - - if 'downloadUrl' in batch_job: - url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) - return url - - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) - CancelBatchJob(client, batch_job) - - -def PrintResponse(batch_job_helper, response_xml): - """Prints the BatchJobService response. - - Args: - batch_job_helper: a BatchJobHelper instance. - response_xml: a string containing a response from the BatchJobService. - """ - response = batch_job_helper.ParseResponse(response_xml) - - if 'rval' in response['mutateResponse']: - for data in response['mutateResponse']['rval']: - if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] - if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/campaign_management/add_trial.py b/examples/adwords/v201806/campaign_management/add_trial.py deleted file mode 100755 index 568b9d21..00000000 --- a/examples/adwords/v201806/campaign_management/add_trial.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a trial and waits for it to complete. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid -from googleads import adwords - - -BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE' -DRAFT_ID = 'INSERT_DRAFT_ID_HERE' -MAX_POLL_ATTEMPTS = 6 - - -def main(client, base_campaign_id, draft_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201806') - trial_async_error_service = client.GetService('TrialAsyncErrorService', - version='v201806') - - trial = { - 'draftId': draft_id, - 'baseCampaignId': base_campaign_id, - 'name': 'Test Trial #%d' % uuid.uuid4(), - 'trafficSplitPercent': 50 - } - - trial_operation = {'operator': 'ADD', 'operand': trial} - trial_id = trial_service.mutate([trial_operation])['value'][0]['id'] - selector = { - 'fields': ['Id', 'Status', 'BaseCampaignId', 'TrialCampaignId'], - 'predicates': [{ - 'field': 'Id', - 'operator': 'IN', - 'values': [trial_id] - }] - } - - # Since creating a trial is asynchronous, we have to poll it to wait for it to - # finish. - poll_attempts = 0 - is_pending = True - trial = None - - while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: - trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) - poll_attempts += 1 - is_pending = trial['status'] == 'CREATING' - - if is_pending: - sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds - time.sleep(sleep_seconds) - - if trial['status'] == 'ACTIVE': - # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) - elif trial['status'] == 'CREATION_FAILED': - # The trial creation failed, and errors can be fetched from the - # TrialAsyncErrorService. - selector = { - 'fields': ['TrialId', 'AsyncError'], - 'predicates': [{ - 'field': 'TrialId', - 'operator': 'IN', - 'values': [trial['id']] - }] - } - - errors = trial_async_error_service.get(selector)['entries'] - - if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] - else: - print 'Could not create trial due to the following errors:' - for error in errors: - print 'Error: %s' % error['asyncError'] - else: - # Most likely, the trial is still being created. You can continue polling, - # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BASE_CAMPAIGN_ID, DRAFT_ID) diff --git a/examples/adwords/v201806/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201806/campaign_management/get_all_disapproved_ads.py deleted file mode 100755 index a9fbc258..00000000 --- a/examples/adwords/v201806/campaign_management/get_all_disapproved_ads.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Construct selector and get all ads for a given ad group. - offset = 0 - selector = { - 'fields': ['Id', 'PolicySummary'], - 'predicates': [ - { - 'field': 'AdGroupId', - 'operator': 'EQUALS', - 'values': [ad_group_id] - }, - { - 'field': 'CombinedApprovalStatus', - 'operator': 'EQUALS', - 'values': 'DISAPPROVED' - } - ], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - more_pages = True - disapproved_count = 0 - - # Display results. - while more_pages: - page = ad_group_ad_service.get(selector) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % ad['ad']['id']) - # Display the policy topic entries related to the ad disapproval. - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName'], - policy_topic_entry['policyTopicHelpCenterUrl']) - # Display the attributes and values that triggered the policy topic. - policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] - if policy_topic_evidences: - for evidence in policy_topic_entry['policyTopicEvidences']: - print (' evidence type: %s' - % evidence['policyTopicEvidenceType']) - evidence_text_list = evidence['evidenceTextList'] - if evidence_text_list: - for index, evidence_text in enumerate(evidence_text_list): - print ' evidence text[%d]: %s' % (index, evidence_text) - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201806/campaign_management/get_all_disapproved_ads_with_awql.py deleted file mode 100755 index 8fe617a8..00000000 --- a/examples/adwords/v201806/campaign_management/get_all_disapproved_ads_with_awql.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 disapproved ads for a given campaign with AWQL. - -To add an ad, run add_ads.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', - version='v201806') - - # Construct query and get all ads for a given campaign. - query = (adwords.ServiceQueryBuilder() - .Select('Id', 'PolicySummary') - .Where('AdGroupId').EqualTo(ad_group_id) - .Where('CombinedApprovalStatus').EqualTo('DISAPPROVED') - .OrderBy('Id') - .Limit(0, PAGE_SIZE) - .Build()) - disapproved_count = 0 - - # Display results. - while True: - page = ad_group_ad_service.query(query) - - if 'entries' in page: - for ad in page['entries']: - disapproved_count += 1 - policy_summary = ad['policySummary'] - - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % ad['ad']['id']) - # Display the policy topic entries related to the ad disapproval. - for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s' % ( - policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName']) - # Display the attributes and values that triggered the policy topic. - if ('policyTopicEvidences' in policy_topic_entry - and policy_topic_entry['policyTopicEvidences']): - for evidence in policy_topic_entry['policyTopicEvidences']: - print (' evidence type: %s' - % evidence['policyTopicEvidenceType']) - evidence_text_list = evidence['evidenceTextList'] - if evidence_text_list: - for index, evidence_text in enumerate(evidence_text_list): - print ' evidence text[%d]: %s' % (index, evidence_text) - - if not query.HasNext(page): - break - query.NextPage() - - print '%d disapproved ads were found.' % disapproved_count - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201806/campaign_management/get_campaigns_by_label.py deleted file mode 100755 index 4fcdbc14..00000000 --- a/examples/adwords/v201806/campaign_management/get_campaigns_by_label.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 campaigns with a specific label. - -To add a label to campaigns, run add_campaign_labels.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -LABEL_ID = 'INSERT_LABEL_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, label_id): - # Initialize appropriate service. - campaign_service = client.GetService('CampaignService', version='v201806') - - offset = 0 - selector = { - 'fields': ['Id', 'Name', 'Labels'], - # Labels filtering is performed by ID. You can use CONTAINS_ANY to select - # campaigns with any of the label IDs, CONTAINS_ALL to select campaigns - # with all of the label IDs, or CONTAINS_NONE to select campaigns with - # none of the label IDs. - 'ordering': { - 'field': 'Name', - 'sortOrder': 'ASCENDING' - }, - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - }, - 'predicates': { - 'field': 'Labels', - 'operator': 'CONTAINS_ANY', - 'values': [label_id] - } - } - - more_pages = True - while more_pages: - page = campaign_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign in page['entries']: - print ('Campaign found with Id "%s", name "%s", and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) - else: - print 'No campaigns were found.' - - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, LABEL_ID) diff --git a/examples/adwords/v201806/campaign_management/graduate_trial.py b/examples/adwords/v201806/campaign_management/graduate_trial.py deleted file mode 100755 index cb5a2700..00000000 --- a/examples/adwords/v201806/campaign_management/graduate_trial.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Illustrates how to graduate a trial. - -See the Campaign Drafts and Experiments guide for more information: -https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -TRIAL_ID = 'INSERT_TRIAL_ID_HERE' - - -def main(client, trial_id): - # Initialize appropriate services. - trial_service = client.GetService('TrialService', version='v201806') - budget_service = client.GetService('BudgetService', version='v201806') - - # To graduate a trial, you must specify a different budget from the base - # campaign. The base campaign (in order to have had a trial based on it) must - # have a non-shared budget, so it cannot be shared with the new independent - # campaign created by graduation. - budget = { - 'name': 'Budget #%d' % uuid.uuid4(), - 'amount': {'microAmount': 50000000}, - 'deliveryMethod': 'STANDARD' - } - - budget_operation = {'operator': 'ADD', 'operand': budget} - # Add budget - budget_id = budget_service.mutate([budget_operation])['value'][0]['budgetId'] - - trial = { - 'id': trial_id, - 'budgetId': budget_id, - 'status': 'GRADUATED' - } - - trial_operation = {'operator': 'SET', 'operand': trial} - - # Update the trial. - trial = trial_service.mutate([trial_operation])['value'][0] - - # Graduation is a synchronous operation, so the campaign is already ready. If - # you promote instead, make sure to see the polling scheme demonstrated in - # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, TRIAL_ID) diff --git a/examples/adwords/v201806/campaign_management/set_ad_parameters.py b/examples/adwords/v201806/campaign_management/set_ad_parameters.py deleted file mode 100755 index a3d0d09f..00000000 --- a/examples/adwords/v201806/campaign_management/set_ad_parameters.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Copyright 2016 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 adds a text ad with ad parameters. - -To get ad groups, run get_ad_groups.py. To get keywords, run add_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_KEYWORD_CRITERION_ID_HERE' - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - ad_param_service = client.GetService('AdParamService', version='v201806') - - # Construct operations for adding text ad object and add to an ad group. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'TextAd', - 'finalUrls': ['http://www.example.com'], - 'displayUrl': 'example.com', - 'description1': 'Low-gravity fun for {param1:cheap}.', - 'description2': 'Only {param2:a few} seats left!', - 'headline': 'Luxury Mars Cruises' - }, - 'status': 'ENABLED' - } - }] - ads = ad_group_ad_service.mutate(operations)['value'] - - # Display results. - for ad in ads: - print ('Text ad with id "%s" was successfully added to an ad group with ' - 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) - - # Construct operations for setting ad parameters. - operations = [ - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': u'£100', - 'paramIndex': '1' - } - }, - { - 'operator': 'SET', - 'operand': { - 'adGroupId': ad_group_id, - 'criterionId': criterion_id, - 'insertionText': '50', - 'paramIndex': '2' - } - } - ] - ad_params = ad_param_service.mutate(operations) - - # Display results. - for ad_param in ad_params: - print ('Ad parameter with text "%s" was successfully set for criterion ' - 'with id "%s" and ad group id "%s".' - % (ad_param['insertionText'], ad_param['criterionId'], - ad_param['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201806/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201806/campaign_management/set_criterion_bid_modifier.py deleted file mode 100755 index 83cfb697..00000000 --- a/examples/adwords/v201806/campaign_management/set_criterion_bid_modifier.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sets a bid modifier for the mobile platform on given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -BID_MODIFIER = '1.5' - - -def main(client, campaign_id, bid_modifier): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201806') - - # Create mobile platform.The ID can be found in the documentation. - # https://developers.google.com/adwords/api/docs/appendix/platforms - mobile = { - 'xsi_type': 'Platform', - 'id': '30001' - } - - # Create campaign criterion with modified bid. - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': mobile, - 'bidModifier': bid_modifier - } - - # Create operations. - operations = [ - { - 'operator': 'SET', - 'operand': campaign_criterion - } - ] - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' - 'was updated with bid modifier "%s".' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['bidModifier'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, BID_MODIFIER) diff --git a/examples/adwords/v201806/campaign_management/validate_text_ad.py b/examples/adwords/v201806/campaign_management/validate_text_ad.py deleted file mode 100755 index b0f58439..00000000 --- a/examples/adwords/v201806/campaign_management/validate_text_ad.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 shows how to use validateOnly SOAP header. - -No objects will be created, but exceptions will still be returned. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords -from googleads import errors - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service with validate only flag enabled. - client.validate_only = True - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Construct operations to add an expanded text ad. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for everyone!', - 'finalUrls': ['http://www.example.com'] - } - } - }] - ad_group_ad_service.mutate(operations) - # No error means the request is valid. - - # Now let's check an invalid ad using a very long line to trigger an error. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdGroupAd', - 'adGroupId': ad_group_id, - 'ad': { - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Luxury Cruise to Mars', - 'headlinePart2': 'Visit the Red Planet in style.', - 'description': 'Low-gravity fun for all astronauts in orbit', - 'finalUrls': ['http://www.example.com'], - } - } - }] - try: - ad_group_ad_service.mutate(operations) - except errors.GoogleAdsServerFault, e: - print 'Validation correctly failed with "%s".' % str(e) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/error_handling/__init__.py b/examples/adwords/v201806/error_handling/__init__.py deleted file mode 100644 index 7b767e05..00000000 --- a/examples/adwords/v201806/error_handling/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Error handling examples.""" diff --git a/examples/adwords/v201806/error_handling/handle_partial_failures.py b/examples/adwords/v201806/error_handling/handle_partial_failures.py deleted file mode 100755 index 1c65cfea..00000000 --- a/examples/adwords/v201806/error_handling/handle_partial_failures.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle partial failures. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Enable partial failure. - client.partial_failure = True - - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201806') - - # Construct keyword ad group criteria objects. - keywords = [ - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'mars cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'inv\@lid cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'venus cruise' - } - }, - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': r'b\(a\)d keyword cruise' - } - } - ] - - # Construct operations and add ad group criteria. - operations = [] - for keyword in keywords: - operations.append( - { - 'operator': 'ADD', - 'operand': keyword - }) - result = ad_group_criterion_service.mutate(operations) - - # Display results. - for criterion in result['value']: - if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id "%s", ' - 'criterion id "%s", text "%s", and match type "%s" was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], - criterion['criterion']['text'], - criterion['criterion']['matchType'])) - - for error in result['partialFailureErrors']: - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - if (first_field_path_element and - first_field_path_element['field'] == 'operations' and - 'index' in first_field_path_element): - operation_index = first_field_path_element['index'] - - adgroup_criterion = operations[operation_index]['operand'] - - print('Ad group criterion with ad group ID %s and keyword "%s" triggered ' - 'a failure for the following reason: %s.' - % (adgroup_criterion['adGroupId'], - adgroup_criterion['criterion']['text'], - error['errorString'])) - else: - print ('A failure has occurred for the following reasons: %s\n' - % error['errorString']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/error_handling/handle_policy_violation_error.py b/examples/adwords/v201806/error_handling/handle_policy_violation_error.py deleted file mode 100755 index 976648b3..00000000 --- a/examples/adwords/v201806/error_handling/handle_policy_violation_error.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 demonstrates how to handle policy violation errors. - -To get ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - - -from googleads import adwords -from googleads import errors - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201806') - - # Create expanded text ad that violates an exemptable policy. - exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise!!!', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - # Create text ad that violates a non-exemptable policy. - non_exemptable_expanded_text_ad_operation = { - 'operator': 'ADD', - 'operand': { - 'adGroupId': ad_group_id, - 'ad': { - # The 'xsi_type' field allows you to specify the xsi:type of the - # object being created. It's only necessary when you must provide - # an explicit type that the client library can't infer. - 'xsi_type': 'ExpandedTextAd', - 'headlinePart1': 'Mars Cruise with too long of a headline.', - 'headlinePart2': 'Best space cruise line.', - 'description': 'Visit the Red Planet in style.', - 'finalUrls': ['http://www.example.com'] - } - } - } - - operations = [exemptable_expanded_text_ad_operation, - non_exemptable_expanded_text_ad_operation] - - # Validate the ad. - try: - # Enable "validate only" to check for errors. - client.validate_only = True - ad_group_ad_service.mutate(operations) - print 'Validation successful, no errors returned.' - except errors.GoogleAdsServerFault, e: - for error in e.errors: - # Get the index of the failed operation from the error's field path - # elements. - field_path_elements = error['fieldPathElements'] - first_field_path_element = None - - if field_path_elements: - first_field_path_element = field_path_elements[0] - - # If the operation index is not present on the first error field path - # element, then there's no way to determine which operation to remove, - # so simply throw the exception. - if (not (first_field_path_element - and first_field_path_element['field'] == 'operations' - and 'index' in first_field_path_element)): - raise e - - index = long(first_field_path_element['index']) - operation = operations[index] - if not HandleAPIError(error, operation): - # Set non-exemptable operation to None to mark for deletion. - print ('Removing operation with non-exemptable error at index %s.' - % index) - operations[index] = None - - # Remove the non-exemptable operations. - operations = [op for op in operations if op is not None] - - # Add these ads. Disable "validate only" so the ads will get created. - client.validate_only = False - if operations: - response = ad_group_ad_service.mutate(operations) - if response and response['value']: - ads = response['value'] - print 'Added %s ad(s) to ad group %s.' % (len(ads), ad_group_id) - for ad in ads: - print (' Ad id is %s, type is %s and status is "%s".' % - (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) - else: - print 'No ads were added.' - - -def HandleAPIError(error, operation): - """Makes an exemption for exemptable PolicyViolationErrors. - - Args: - error: the error associated with the given operation. - operation: the operation associated with the given error. - - Returns: - A boolean that is True if the given error was an exemptable - PolicyViolationError; otherwise, returns False. - """ - is_exemptable = False - - # Determine if the operation can be resubmitted with an exemption request. - if error['ApiError.Type'] == 'PolicyViolationError': - expanded_text_ad = operation['operand']['ad'] - is_exemptable = (error['isExemptable'] if 'isExemptable' in error else - False) - print ('Ad with headline "%s - %s" violated %s policy "%s".' % - (expanded_text_ad['headlinePart1'], - expanded_text_ad['headlinePart2'], - 'exemptable' if is_exemptable else 'non-exemptable', - error['externalPolicyName'])) - - if is_exemptable: - # Add exemption request to the operation. - print ('Adding exemption request for policy name "%s" on text "%s".' - % (error['key']['policyName'], error['key']['violatingText'])) - if 'exemptionRequests' not in operation: - operation['exemptionRequests'] = [] - operation['exemptionRequests'].append({'key': error['key']}) - - return is_exemptable - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/extensions/__init__.py b/examples/adwords/v201806/extensions/__init__.py deleted file mode 100644 index 594717b1..00000000 --- a/examples/adwords/v201806/extensions/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Extension examples.""" diff --git a/examples/adwords/v201806/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201806/extensions/add_google_my_business_location_extensions.py deleted file mode 100755 index 8f719027..00000000 --- a/examples/adwords/v201806/extensions/add_google_my_business_location_extensions.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a feed that syncs feed items from a Google My Business (GMB) account. - -This example associates the feed with a customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import time -import uuid - -from googleads import adwords -from googleads import errors - -GMB_EMAIL_ADDRESS = 'INSERT_GMB_EMAIL_ADDRESS_HERE' - -# If the gmb_email_address above is for a GMB manager instead of -# the GMB account owner, then set business_account_identifier to the -# +Page ID of a location for which the manager has access. See the -# location extensions guide at -# https://developers.google.com/adwords/api/docs/guides/feed-services-locations -# for details. -BUSINESS_ACCOUNT_IDENTIFIER = None - -# The placeholder type for location extensions. -# See the Placeholder reference page for a list of all the placeholder types -# and fields: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_LOCATION = 7 - -# The maximum number of CustomerFeed ADD operation attempts to make before -# throwing an exception. -MAX_CUSTOMER_FEED_ADD_ATTEMPTS = 10 - - -def main(client, gmb_email_address, gmb_access_token, - business_account_identifier=None): - # Create a feed that will sync to the Google Places account specified by - # gmb_email_address. Do not add FeedAttributes to this object, - # as AdWords will add them automatically because this will be a - # system generated feed. - feed = { - 'name': 'GMB feed #%s' % uuid.uuid4(), - 'systemFeedGenerationData': { - 'xsi_type': 'PlacesLocationFeedData', - 'oAuthInfo': { - 'httpMethod': 'GET', - 'httpRequestUrl': 'https://www.googleapis.com/auth/adwords', - 'httpAuthorizationHeader': 'Bearer %s' % gmb_access_token - }, - 'emailAddress': gmb_email_address, - }, - # Since this feed's feed items will be managed by AdWords, you must set - # its origin to ADWORDS. - 'origin': 'ADWORDS' - } - - # Only include the business_account_identifier if it's specified. - if business_account_identifier: - feed['systemFeedGenerationData']['businessAccountIdentifier'] = ( - business_account_identifier - ) - - # Create an operation to add the feed. - gmb_operations = [{ - 'operator': 'ADD', - 'operand': feed - }] - - gmb_response = client.GetService('FeedService', version='v201806').mutate( - gmb_operations) - added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] - - # Add a CustomerFeed that associates the feed with this customer for the - # LOCATION placeholder type. - customer_feed = { - 'feedId': added_feed['id'], - 'placeholderTypes': [PLACEHOLDER_LOCATION], - # Create a matching function that will always evaluate to True. - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': { - 'xsi_type': 'ConstantOperand', - 'type': 'BOOLEAN', - 'booleanValue': True - } - } - } - - customer_feed_operation = { - 'xsi_type': 'CustomerFeedOperation', - 'operator': 'ADD', - 'operand': customer_feed - } - - customer_feed_service = client.GetService( - 'CustomerFeedService', version='v201806') - added_customer_feed = None - - i = 0 - while i < MAX_CUSTOMER_FEED_ADD_ATTEMPTS and added_customer_feed is None: - try: - added_customer_feed = customer_feed_service.mutate([ - customer_feed_operation])['value'][0] - except errors.GoogleAdsServerFault: - # Wait using exponential backoff policy - sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) - - time.sleep(sleep_seconds) - i += 1 - - if added_customer_feed is None: - raise errors.GoogleAdsError( - 'Could not create the CustomerFeed after %s attempts. Please retry the ' - 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - # If the GMB_EMAIL_ADDRESS above is the same user you used to generate your - # AdWords API refresh token, leave the assignment below unchanged. Otherwise, - # to obtain an access token for your GMB account, you can run the - # generate_refresh_token.py example after manually replacing the scope with - # "https://www.google.com/local/add". - GMB_ACCESS_TOKEN = adwords_client.oauth2_client.oauth2credentials.access_token - - main(adwords_client, GMB_EMAIL_ADDRESS, GMB_ACCESS_TOKEN, - BUSINESS_ACCOUNT_IDENTIFIER) diff --git a/examples/adwords/v201806/extensions/add_prices.py b/examples/adwords/v201806/extensions/add_prices.py deleted file mode 100755 index 1963ccd6..00000000 --- a/examples/adwords/v201806/extensions/add_prices.py +++ /dev/null @@ -1,157 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a price extension and associates it with an account. - -Campaign targeting is also set usin the specified campaign ID. To get campaigns, -run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -from googleads import errors - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -MICROS_PER_DOLLAR = 1000000 - - -def main(client, campaign_id): - # Initialize appropriate service. - customer_extension_setting_service = client.GetService( - 'CustomerExtensionSettingService', 'v201806') - - # To create a price extension, at least three table rows are needed. - table_rows = [ - CreatePriceTableRow('Scrubs', 'Body Scrub, Salt Scrub', - 'https://www.example.com/scrubs', - 60 * MICROS_PER_DOLLAR, 'USD', 'PER_HOUR', - final_mobile_url='http://m.example.com/scrubs'), - CreatePriceTableRow('Hair Cuts', 'Once a month', - 'https://www.example.com/haircuts', - 75 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url='http://m.example.com/haircuts'), - CreatePriceTableRow('Skin Care Package', 'Four times a month', - 'https://www.examples.com/skincarepackage', - 250 * MICROS_PER_DOLLAR, 'USD', 'PER_MONTH', - final_mobile_url=( - 'http://m.example.com/skincarepackage')) - ] - - # Create the price extension feed item. - customer_extension_setting = { - 'extensionType': 'PRICE', - 'extensionSetting': { - 'extensions': [{ - 'priceExtensionType': 'SERVICES', - 'trackingUrlTemplate': 'http://tracker.example.com/?u={lpurl}', - 'language': 'en', - 'campaignTargeting': { - 'TargetingCampaignId': campaign_id - }, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': 'SATURDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 22, - 'endMinute': 'ZERO' - }, - { - 'dayOfWeek': 'SUNDAY', - 'startHour': 10, - 'startMinute': 'ZERO', - 'endHour': 18, - 'endMinute': 'ZERO' - } - ] - }, - 'tableRows': table_rows, - # Price qualifier is optional. - 'priceQualifier': 'FROM', - 'xsi_type': 'PriceFeedItem' - }] - } - } - - # Create an operation to add the feed. - operations = [{ - 'operator': 'ADD', - 'operand': customer_extension_setting - }] - - # Add the price extension. - response = customer_extension_setting_service.mutate(operations) - - # Print the results. - if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -def CreatePriceTableRow(header, description, final_url, price_in_micros, - currency_code, price_unit, final_mobile_url=None): - """Helper function to generate a single row of a price table. - - Args: - header: A str containing the header text of this row. - description: A str description of this row in the price table. - final_url: A str containing the final URL after all cross domain redirects. - price_in_micros: An int indicating the price of the given currency in - micros. - currency_code: A str indicating the currency code being used. - price_unit: A str enum indicating the price unit for this row. - final_mobile_url: A str containing the final mobile URL after all cross - domain redirects. - - Returns: - A dictionary containing the contents of the generated price table row. - """ - table_row = { - 'header': header, - 'description': description, - 'finalUrls': {'urls': [final_url]}, - 'price': { - 'money': { - 'microAmount': price_in_micros, - }, - 'currencyCode': currency_code - }, - 'priceUnit': price_unit, - 'xsi_type': 'PriceTableRow' - } - - if final_mobile_url: - table_row['finalMobileUrls'] = { - 'urls': [final_mobile_url] - } - - return table_row - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/extensions/add_site_links.py b/examples/adwords/v201806/extensions/add_site_links.py deleted file mode 100755 index fac3a6fb..00000000 --- a/examples/adwords/v201806/extensions/add_site_links.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Adds sitelinks to a campaign using the CampaignExtensionSettingService. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from datetime import datetime - -from googleads import adwords -from googleads import errors -from pytz import timezone - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - # Initialize appropriate services. - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', version='v201806') - customer_service = client.GetService('CustomerService', version='v201806') - # Find the matching customer and its time zone. The getCustomers method will - # return a single Customer object corresponding to the configured - # clientCustomerId. - customer = customer_service.getCustomers()[0] - customer_tz = timezone(customer['dateTimeZone']) - time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) - - # Create the sitelinks - sitelink1 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Store Hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/storehours']} - } - - # Show the Thanksgiving specials link only from 20 - 27 Nov. - sitelink2 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Thanksgiving Specials', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/thanksgiving']}, - # The time zone of the start and end date/times must match the time zone - # of the customer. - 'startTime': datetime(datetime.now().year, 11, 20, 0, 0, 0, 0, - customer_tz).strftime(time_fmt), - 'endTime': datetime(datetime.now().year, 11, 27, 23, 59, 59, 59, - customer_tz).strftime(time_fmt), - # Target this sitelink for United States only. For valid geolocation - # codes, see: - # https://developers.google.com/adwords/api/docs/appendix/geotargeting - 'geoTargeting': {'id': 2840}, - # Restrict targeting only to people physically within the United States. - # Otherwise, this could also show to people interested in the United - # States, but not physically located there. - 'geoTargetingRestriction': { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - } - - # Show the wifi details primarily for high end mobile users. - sitelink3 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Wifi Available', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/mobile/wifi']}, - # See https://developers.google.com/adwords/api/docs/appendix/platforms - # for device criteria IDs. - 'devicePreference': {'devicePreference': '30001'}, - # Target this sitelink only when the ad is triggered by the keyword - # "free wifi." - 'keywordTargeting': { - 'text': 'free wifi', - 'matchType': 'BROAD' - } - } - - # Show the happy hours link only during Mon - Fri 6PM to 9PM. - sitelink4 = { - 'xsi_type': 'SitelinkFeedItem', - 'sitelinkText': 'Happy hours', - 'sitelinkFinalUrls': {'urls': ['http://www.example.com/happyhours']}, - 'scheduling': { - 'feedItemSchedules': [ - { - 'dayOfWeek': day, - 'startHour': '18', - 'startMinute': 'ZERO', - 'endHour': '21', - 'endMinute': 'ZERO' - } for day in ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', - 'FRIDAY'] - ] - } - } - - # Create your Campaign Extension Settings. This associates the sitelinks - # to your campaign. - campaign_extension_setting = { - 'campaignId': campaign_id, - 'extensionType': 'SITELINK', - 'extensionSetting': { - 'extensions': [sitelink1, sitelink2, sitelink3, sitelink4] - } - } - - operation = { - 'operator': 'ADD', - 'operand': campaign_extension_setting - } - - # Add the extensions. - response = campaign_extension_setting_service.mutate([operation]) - - if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) - else: - raise errors.GoogleAdsError('No extension settings were added.') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/extensions/add_site_links_using_feeds.py b/examples/adwords/v201806/extensions/add_site_links_using_feeds.py deleted file mode 100755 index 08086673..00000000 --- a/examples/adwords/v201806/extensions/add_site_links_using_feeds.py +++ /dev/null @@ -1,303 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a sitelinks feed and associates it with a campaign. - -To add sitelinks using the simpler ExtensionSetting services, see: -add_sitelinks.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import re -import uuid -from googleads import adwords -from googleads import errors - -# See the Placeholder reference page for a list of all the placeholder types and -# fields. -# https://developers.google.com/adwords/api/docs/appendix/placeholders.html -PLACEHOLDER_SITELINKS = '1' -PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = '1' -PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = '5' -PLACEHOLDER_FIELD_LINE_2_TEXT = '3' -PLACEHOLDER_FIELD_LINE_3_TEXT = '4' - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Optional: Ad group to restrict targeting to. -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def RestrictFeedItemToGeoTarget(client, feed_item, location_id): - """Restrict a feed item to a geo target location. - - Args: - client: An AdWordsClient instance. - feed_item: A FeedItem. - location_id: The Id of the location to restrict to. - """ - # Retrieve the FeedItemTargetService - feed_item_target_service = client.GetService( - 'FeedItemTargetService', version='v201806') - - # Optional: Restrict the first feed item to only serve with ads for the - # specified geo target. - criterion_target = { - 'xsi_type': 'FeedItemCriterionTarget', - 'feedId': feed_item['feedId'], - 'feedItemId': feed_item['feedItemId'], - # These IDs can be found in the documentation or retrieved with the - # LocationCriterionService. - 'criterion': { - 'xsi_type': 'Location', - 'id': location_id - } - } - - operation = {'operator': 'ADD', 'operand': criterion_target} - - response = feed_item_target_service.mutate([operation]) - new_location_target = response['value'][0] - print('Feed item target for feed ID %d and feed item ID %d was created to ' - 'restrict serving to location ID %d.' % - (new_location_target['feedId'], - new_location_target['feedItemId'], - new_location_target['criterion']['id'])) - - -def main(client, campaign_id, ad_group_id=None): - # Initialize appropriate service. - feed_service = client.GetService('FeedService', version='v201806') - feed_item_service = client.GetService('FeedItemService', version='v201806') - feed_item_target_service = client.GetService('FeedItemTargetService', - version='v201806') - feed_mapping_service = client.GetService( - 'FeedMappingService', version='v201806') - campaign_feed_service = client.GetService( - 'CampaignFeedService', version='v201806') - - sitelinks_data = {} - - # Create site links feed first. - site_links_feed = { - 'name': 'Feed For Site Links #%s' % uuid.uuid4(), - 'attributes': [ - {'type': 'STRING', 'name': 'Link Text'}, - {'type': 'URL_LIST', 'name': 'Link Final URLs'}, - {'type': 'STRING', 'name': 'Line 2 Description'}, - {'type': 'STRING', 'name': 'Line 3 Description'} - ] - } - - response = feed_service.mutate([ - {'operator': 'ADD', 'operand': site_links_feed} - ]) - - if 'value' in response: - feed = response['value'][0] - link_text_feed_attribute_id = feed['attributes'][0]['id'] - final_url_feed_attribute_id = feed['attributes'][1]['id'] - line_2_feed_attribute_id = feed['attributes'][2]['id'] - line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name "%s" and ID "%d" was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID "%d" and Final URL attribute ID "%d".' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID "%d" and Line 3 attribute ID "%d".' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) - sitelinks_data['feedId'] = feed['id'] - sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id - sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id - sitelinks_data['line2FeedId'] = line_2_feed_attribute_id - sitelinks_data['line3FeedId'] = line_3_feed_attribute_id - else: - raise errors.GoogleAdsError('No feeds were added.') - - # Create site links feed items. - items_data = [ - {'text': 'Home', 'finalUrls': 'http://www.example.com', - 'line2': 'Home line 2', 'line3': 'Home line 3'}, - {'text': 'Stores', 'finalUrls': 'http://www.example.com/stores', - 'line2': 'Stores line 2', 'line3': 'Stores line 3'}, - {'text': 'On Sale', 'finalUrls': 'http://www.example.com/sale', - 'line2': 'On Sale line 2', 'line3': 'On Sale line 3'}, - {'text': 'Support', 'finalUrls': 'http://www.example.com/support', - 'line2': 'Support line 2', 'line3': 'Support line 3'}, - {'text': 'Products', 'finalUrls': 'http://www.example.com/products', - 'line2': 'Products line 2', 'line3': 'Products line 3'}, - {'text': 'About Us', 'finalUrls': 'http://www.example.com/about', - 'line2': 'About line 2', 'line3': 'About line 3', 'locationTarget': True} - ] - - feed_items = [] - for item in items_data: - feed_item = { - 'feedId': sitelinks_data['feedId'], - 'attributeValues': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'stringValue': item['text'] - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'stringValues': [item['finalUrls']] - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'stringValue': item['line2'] - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'stringValue': item['line3'] - } - ], - # Optional: use the 'startTime' and 'endTime' keys to specify the time - # period for the feed to deliver. The example below will make the feed - # start now and stop in one month. - # Make sure you specify the datetime in the customer's time zone. You - # can retrieve this from customer['dateTimeZone']. - # - # ['startTime']: datetime.datetime.now().strftime('%Y%m%d %H%M%S') - # ['endTime']: (datetime.datetime.now() + - # relativedelta(months=1)).strftime('%Y%m%d %H%M%S') - } - - # Optional: Restrict targeting only to people physically within - # the location. - if 'locationTarget' in item: - item['geoTargetingRestriction'] = { - 'geoRestriction': 'LOCATION_OF_PRESENCE' - } - - feed_items.append(feed_item) - - feed_items_operations = [{'operator': 'ADD', 'operand': item} for item - in feed_items] - - response = feed_item_service.mutate(feed_items_operations) - if 'value' in response: - sitelinks_data['feedItemIds'] = [] - for feed_item in response['value']: - print 'Feed item with ID %d was added.' % feed_item['feedItemId'] - sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) - else: - raise errors.GoogleAdsError('No feed items were added.') - - # Target the "aboutUs" sitelink to geographically target California. - # See https://developers.google.com/adwords/api/docs/appendix/geotargeting for - # location criteria for supported locations. - RestrictFeedItemToGeoTarget(client, response['value'][5], 21137) - - # Create site links feed mapping. - - feed_mapping = { - 'placeholderType': PLACEHOLDER_SITELINKS, - 'feedId': sitelinks_data['feedId'], - 'attributeFieldMappings': [ - { - 'feedAttributeId': sitelinks_data['linkTextFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_LINK_TEXT - }, - { - 'feedAttributeId': sitelinks_data['finalUrlFeedId'], - 'fieldId': PLACEHOLDER_FIELD_SITELINK_FINAL_URLS - }, - { - 'feedAttributeId': sitelinks_data['line2FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_2_TEXT - }, - { - 'feedAttributeId': sitelinks_data['line3FeedId'], - 'fieldId': PLACEHOLDER_FIELD_LINE_3_TEXT - } - ] - } - - response = feed_mapping_service.mutate([ - {'operator': 'ADD', 'operand': feed_mapping} - ]) - if 'value' in response: - feed_mapping = response['value'][0] - print ('Feed mapping with ID %d and placeholder type %s was saved for feed' - ' with ID %d.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) - else: - raise errors.GoogleAdsError('No feed mappings were added.') - - # Construct a matching function that associates the sitelink feeditems to the - # campaign, and set the device preference to Mobile. For more details, see the - # matching function guide: - # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions - matching_function_string = ( - 'AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \'Mobile\'))' % - re.sub(r'\[|\]|L', '', str(sitelinks_data['feedItemIds']))) - - campaign_feed = { - 'feedId': sitelinks_data['feedId'], - 'campaignId': campaign_id, - 'matchingFunction': {'functionString': matching_function_string}, - # Specifying placeholder types on the CampaignFeed allows the same feed - # to be used for different placeholders in different Campaigns. - 'placeholderTypes': [PLACEHOLDER_SITELINKS] - } - - response = campaign_feed_service.mutate([ - {'operator': 'ADD', 'operand': campaign_feed} - ]) - if 'value' in response: - campaign_feed = response['value'][0] - print ('Campaign with ID %d was associated with feed with ID %d.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) - else: - raise errors.GoogleAdsError('No campaign feeds were added.') - - # Optional: Restrict the first feed item to only serve with ads for the - # specified ad group ID. - if ad_group_id: - feed_item_target = { - 'xsi_type': 'FeedItemAdGroupTarget', - 'feedId': sitelinks_data['feedId'], - 'feedItemId': sitelinks_data['feedItemIds'][0], - 'adGroupId': ad_group_id - } - - operations = [{ - 'operator': 'ADD', - 'operand': feed_item_target - }] - - response = feed_item_target_service.mutate(operations) - - if 'value' in response: - print ('Feed item target for feed ID "%d" and feed item ID "%d" was ' - 'created to restrict serving to ad group ID "%d".' - % (feed_item_target['feedId'], feed_item_target['feedItemId'], - feed_item_target['adGroupId'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - if AD_GROUP_ID == 'INSERT_AD_GROUP_ID_HERE': - main(adwords_client, CAMPAIGN_ID) - else: - main(adwords_client, CAMPAIGN_ID, ad_group_id=AD_GROUP_ID) diff --git a/examples/adwords/v201806/migration/__init__.py b/examples/adwords/v201806/migration/__init__.py deleted file mode 100644 index 09996b99..00000000 --- a/examples/adwords/v201806/migration/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Migration examples.""" diff --git a/examples/adwords/v201806/migration/migrate_to_extension_settings.py b/examples/adwords/v201806/migration/migrate_to_extension_settings.py deleted file mode 100755 index fcdfd777..00000000 --- a/examples/adwords/v201806/migration/migrate_to_extension_settings.py +++ /dev/null @@ -1,526 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Migrates Feed-based sitelinks at Campaign level to use extension settings. - -To learn more about extensionsettings, see: -https://developers.google.com/adwords/api/docs/guides/extension-settings. - -To learn more about migrating Feed-based extensions to extension settings, see: -https://developers.google.com/adwords/api/docs/guides/migrate-to-extension-settings - -This code example doesn't migrate scheduling or feeditem-level campaign, -adgroup, keyword, or geo targeting settings. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -# The placeholder type for sitelinks. For the list of all supported placeholder -# types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -PLACEHOLDER_TYPE_SITELINKS = 1 - - -# The placeholder field IDs for sitelinks. For the list of all supported -# placeholder types, see: -# https://developers.google.com/adwords/api/docs/appendix/placeholders -SITE_LINK_FIELDS = { - 'TEXT': 1, - 'URL': 2, - 'LINE2': 3, - 'LINE3': 4, - 'FINAL_URLS': 5, - 'FINAL_MOBILE_URLS': 6, - 'TRACKING_URL_TEMPLATE': 7 -} - -PAGE_SIZE = 500 - - -def CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions=None): - """Creates the extension setting for a list of Feed Items. - - Args: - client: an AdWordsClient instance. - feed_items: the list of all Feed Items. - campaign_feed: the original Campaign Feed. - feed_item_ids: the Ids of the feed items for which extension settings should - be created. - platform_restrictions: an optional Platform Restriction for the Feed items. - """ - campaign_extension_setting_service = client.GetService( - 'CampaignExtensionSettingService', 'v201806') - - extension_feed_items = [{ - CreateSitelinkFeedItem(feed_items, feed_item_id) - } for feed_item_id in feed_item_ids] - - extension_setting = { - 'extensions': extension_feed_items - } - - if platform_restrictions: - extension_setting['platformRestrictions'] = platform_restrictions - - campaign_extension_setting = { - 'campaignId': campaign_feed['campaignId'], - 'extensionType': 'SITELINK', - 'extensionSetting': extension_setting - } - - operation = { - 'operand': campaign_extension_setting, - 'operator': 'ADD' - } - - campaign_extension_setting_service.mutate([operation]) - - -def CreateSitelinkFeedItem(feed_items, feed_item_id): - """Creates a Sitelink Feed Item. - - Args: - feed_items: a list of all Feed Items. - feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item - should be created. - - Returns: - The new Sitelink Feed Item. - """ - site_link_from_feed = feed_items[feed_item_id] - site_link_feed_item = { - 'sitelinkText': site_link_from_feed['text'], - 'sitelinkLine2': site_link_from_feed['line2'], - 'sitelinkLine3': site_link_from_feed['line3'], - } - - if 'finalUrls' in site_link_from_feed and site_link_from_feed['finalUrls']: - site_link_feed_item['sitelinkFinalUrls'] = { - 'urls': site_link_from_feed['finalUrls'] - } - - if 'finalMobileUrls' in site_link_from_feed: - site_link_feed_item['sitelinkFinalMobileUrls'] = { - 'urls': site_link_from_feed['finalMobileUrls'] - } - - site_link_feed_item['sitelinkTrackingUrlTemplate'] = ( - site_link_from_feed['trackingUrlTemplate']) - else: - site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url'] - - return site_link_feed_item - - -def DeleteCampaignFeed(client, campaign_feed): - """Deletes a campaign feed. - - Args: - client: an AdWordsClient instance. - campaign_feed: the campaign feed to delete. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201806') - - operation = { - 'operand': campaign_feed, - 'operator': 'REMOVE' - } - - campaign_feed_service.mutate([operation]) - - -def DeleteOldFeedItems(client, feed_item_ids, feed): - """Deletes the old feed items for which extension settings have been created. - - Args: - client: an AdWordsClient instance. - feed_item_ids: a list of Feed Item Ids. - feed: the Feed containing the given Feed Item Ids. - """ - if not feed_item_ids: - return - - feed_item_service = client.GetService('FeedItemService', 'v201806') - - operations = [{ - 'operator': 'REMOVE', - 'operand': { - 'feedId': feed['id'], - 'feedItemId': feed_item_id - } - } for feed_item_id in feed_item_ids] - - feed_item_service.mutate(operations) - - -def GetCampaignFeeds(client, feed, placeholder_type): - """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed. - - Args: - client: an AdWordsClient instance. - feed: a Campaign Feed. - placeholder_type: the Placeholder Type. - - Returns: - A list of Feed Item Ids. - """ - campaign_feed_service = client.GetService('CampaignFeedService', 'v201806') - - campaign_feeds = [] - more_pages = True - - selector = { - 'fields': ['CampaignId', 'MatchingFunction', 'PlaceholderTypes'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderTypes', - 'operator': 'CONTAINS_ANY', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = campaign_feed_service.get(selector) - - if 'entries' in page: - campaign_feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return campaign_feeds - - -def GetFeeds(client): - """Returns a list of all enabled Feeds. - - Args: - client: an AdWordsClient instance. - - Returns: - A list containing all enabled Feeds. - """ - feed_service = client.GetService('FeedService', 'v201806') - - feeds = [] - more_pages = True - - selector = { - 'fields': ['Id', 'Name', 'Attributes'], - 'predicates': [ - { - 'field': 'Origin', - 'operator': 'EQUALS', - 'values': ['USER'] - }, - { - 'field': 'FeedStatus', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_service.get(selector) - - if 'entries' in page: - feeds.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feeds - - -def GetFeedItems(client, feed): - """Returns the Feed Items for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving Feed Items from. - - Returns: - The Feed Items associated with the given Feed. - """ - feed_item_service = client.GetService('FeedItemService', 'v201806') - - feed_items = [] - more_pages = True - - selector = { - 'fields': ['FeedItemId', 'AttributeValues'], - 'predicates': [ - { - 'field': 'Status', - 'operator': 'EQUALS', - 'values': ['ENABLED'] - }, - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_item_service.get(selector) - - if 'entries' in page: - feed_items.extend(page['entries']) - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return feed_items - - -def GetFeedItemIdsForCampaign(campaign_feed): - """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. - - Returns: - A list of Feed Item IDs. - """ - feed_item_ids = set() - - try: - lhs_operand = campaign_feed['matchingFunction']['lhsOperand'] - except KeyError: - lhs_operand = None - - if (lhs_operand and lhs_operand[0]['FunctionArgumentOperand.Type'] == - 'RequestContextOperand'): - request_context_operand = lhs_operand[0] - - if (request_context_operand['contextType'] == 'FEED_ITEM_ID' and - campaign_feed['matchingFunction']['operator'] == 'IN'): - for argument in campaign_feed['matchingFunction']['rhsOperand']: - if argument['xsi_type'] == 'ConstantOperand': - feed_item_ids.add(argument['longValue']) - - return feed_item_ids - - -def GetFeedMapping(client, feed, placeholder_type): - """Gets the Feed Mapping for a given Feed. - - Args: - client: an AdWordsClient instance. - feed: the Feed we are retrieving the Feed Mapping for. - placeholder_type: the Placeholder Type we are looking for. - Returns: - A dictionary containing the Feed Mapping. - """ - feed_mapping_service = client.GetService('FeedMappingService', 'v201806') - - attribute_mappings = {} - more_pages = True - - selector = { - 'fields': ['FeedMappingId', 'AttributeFieldMappings'], - 'predicates': [ - { - 'field': 'FeedId', - 'operator': 'EQUALS', - 'values': [feed['id']] - }, - { - 'field': 'PlaceholderType', - 'operator': 'EQUALS', - 'values': [placeholder_type] - } - ], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - } - } - - while more_pages: - page = feed_mapping_service.get(selector) - - if 'entries' in page: - # Normally, a feed attribute is mapped only to one field. However, you may - # map it to more than one field if needed. - for feed_mapping in page['entries']: - for attribute_mapping in feed_mapping['attributeFieldMappings']: - # Since attribute mappings can have multiple values for each key, - # we use a list to store the values. - if attribute_mapping['feedAttributeId'] in attribute_mappings: - attribute_mappings[attribute_mapping['feedAttributeId']].append( - attribute_mapping['fieldId']) - else: - attribute_mappings[attribute_mapping['feedAttributeId']] = [ - attribute_mapping['fieldId']] - - selector['paging']['startIndex'] += PAGE_SIZE - more_pages = selector['paging']['startIndex'] < int(page['totalNumEntries']) - - return attribute_mappings - - -def GetPlatformRestrictions(campaign_feed): - """Get the Platform Restrictions for a given Campaign Feed. - - Args: - campaign_feed: the Campaign Feed we are retrieving Platform Restrictons for. - - Returns: - The Platform Restrictions for the given feed. - """ - platform_restrictions = None - - if campaign_feed['matchingFunction']['operator'] == 'AND': - for argument in campaign_feed['matchingFunction']['lhsOperand']: - # Check if matchingFunction is EQUALS(CONTEXT.DEVICE, 'Mobile') - if argument['value']['operator'] == 'EQUALS': - request_context_operand = argument['value']['lhsOperand'][0] - - if (request_context_operand and - request_context_operand == 'DEVICE_PLATFORM'): - # This needs to be capitalized for ExtensionSettingPlatform. - platform_restrictions = argument['value']['rhsOperand'][0].upper() - - return platform_restrictions - - -def GetSitelinksFromFeed(client, feed): - """Gets the sitelinks from a feed. - - Args: - client: an AdWordsClient instance. - feed: the feed used to retrieve sitelinks. - - Returns: - A dictionary mapping the feed item ID to SiteLinkFromFeed. - """ - # Retrieve the feed's attribute mapping. - feed_mappings = GetFeedMapping(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - feed_items = {} - - for feed_item in GetFeedItems(client, feed): - site_link_from_feed = {} - - for attribute_value in feed_item['attributeValues']: - if attribute_value['feedAttributeId'] in feed_mappings: - for field_id in feed_mappings[attribute_value['feedAttributeId']]: - if field_id == SITE_LINK_FIELDS['TEXT']: - site_link_from_feed['text'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['URL']: - site_link_from_feed['url'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['FINAL_URLS']: - site_link_from_feed['finalUrls'] = attribute_value['stringValues'] - elif field_id == SITE_LINK_FIELDS['FINAL_MOBILE_URLS']: - site_link_from_feed['finalMobileUrls'] = attribute_value[ - 'stringValues'] - elif field_id == SITE_LINK_FIELDS['TRACKING_URL_TEMPLATE']: - site_link_from_feed['trackingUrlTemplate'] = attribute_value[ - 'stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE2']: - site_link_from_feed['line2'] = attribute_value['stringValue'] - elif field_id == SITE_LINK_FIELDS['LINE3']: - site_link_from_feed['line3'] = attribute_value['stringValue'] - else: - print 'No applicable Site Link Field found for Id: %s' % field_id - - feed_items[feed_item['feedItemId']] = site_link_from_feed - - return feed_items - - -def main(client): - # Get all of the feeds for the current user. - feeds = GetFeeds(client) - - for feed in feeds: - # Retrieve all the sitelinks from the current feed. - feed_items = GetSitelinksFromFeed(client, feed) - - # Get all the instances where a sitelink from this feed has been added to a - # campaign. - campaign_feeds = GetCampaignFeeds(client, feed, PLACEHOLDER_TYPE_SITELINKS) - - all_feed_items_to_delete = [] - for campaign_feed in campaign_feeds: - # Retrieve the sitelinks that have been associated with this Campaign. - feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) - - if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) - continue - - platform_restrictions = GetPlatformRestrictions(campaign_feed) - - # Delete the campaign feed that associates the sitelinks from the feed to - # the Campaign. - DeleteCampaignFeed(client, campaign_feed) - - # Create extension settings instead of sitelinks. - CreateExtensionSetting(client, feed_items, campaign_feed, feed_item_ids, - platform_restrictions) - - # Mark the sitelinks from the feed for deletion. - all_feed_items_to_delete.extend(feed_item_ids) - - # Delete all the sitelinks from the feed. - DeleteOldFeedItems(client, all_feed_items_to_delete, feed) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/misc/__init__.py b/examples/adwords/v201806/misc/__init__.py deleted file mode 100644 index 1c53bcd3..00000000 --- a/examples/adwords/v201806/misc/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Miscellaneous examples.""" diff --git a/examples/adwords/v201806/misc/get_all_image_assets.py b/examples/adwords/v201806/misc/get_all_image_assets.py deleted file mode 100755 index a29bbf91..00000000 --- a/examples/adwords/v201806/misc/get_all_image_assets.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 Google LLC -# -# 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 -# -# https://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 image assets. - -To upload an image asset, run upload_image_asset.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - asset_service = client.GetService('AssetService', version='v201806') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['AssetName', 'AssetStatus', 'ImageFileSize', 'ImageWidth', - 'ImageHeight', 'ImageFullSizeUrl'], - 'predicates': [{ - 'field': 'AssetSubtype', - 'operator': 'IN', - 'values': ['IMAGE'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = asset_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - print ('Image asset with id %s, name "%s", and status %s was found.\n' - '\tSize is %sx%s and asset URL is %s.' % - (image['assetId'], image['assetName'], image['assetStatus'], - image['fullSizeInfo']['imageWidth'], - image['fullSizeInfo']['imageHeight'], - image['fullSizeInfo']['imageUrl'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/misc/get_all_images_and_videos.py b/examples/adwords/v201806/misc/get_all_images_and_videos.py deleted file mode 100755 index 218173e0..00000000 --- a/examples/adwords/v201806/misc/get_all_images_and_videos.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 images and videos. - -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201806') - - # Construct selector and get all images. - offset = 0 - selector = { - 'fields': ['MediaId', 'Type', 'Width', 'Height', 'MimeType'], - 'predicates': [{ - 'field': 'Type', - 'operator': 'IN', - 'values': ['IMAGE', 'VIDEO'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = media_service.get(selector) - - # Display results. - if 'entries' in page: - for image in page['entries']: - try: - dimensions = dict([(entry['key'], entry['value']) - for entry in image['dimensions']]) - except AttributeError: - dimensions = {'FULL': {'height': 0, 'width': 0}} - if image['type'] == 'IMAGE': - print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) - elif image['type'] == 'VIDEO': - print ('%s with id "%s" was found.' % (image['type'], - image['mediaId'])) - else: - print 'No images/videos were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/misc/upload_image.py b/examples/adwords/v201806/misc/upload_image.py deleted file mode 100755 index 75563e6c..00000000 --- a/examples/adwords/v201806/misc/upload_image.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an image. - -To get images, run get_all_images.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -IMAGE_FILENAME = 'INSERT_IMAGE_PATH_HERE' - - -def main(client, image_filename): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201806') - - with open(image_filename, 'rb') as image_handle: - image_data = image_handle.read().decode('utf-8') - - # Construct media and upload image. - media = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - media = media_service.upload(media)[0] - - # Display results. - if media: - dimensions = dict([(entry['key'], entry['value']) - for entry in media['dimensions']]) - print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, IMAGE_FILENAME) diff --git a/examples/adwords/v201806/misc/upload_image_asset.py b/examples/adwords/v201806/misc/upload_image_asset.py deleted file mode 100755 index cfafe6ce..00000000 --- a/examples/adwords/v201806/misc/upload_image_asset.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 Google LLC -# -# 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 -# -# https://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 uploads an image asset. - -To get image assets, run get_all_image_assets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords -import requests - - -def main(client): - # Initialize appropriate service. - asset_service = client.GetService('AssetService', version='v201806') - - image_request = requests.get('https://goo.gl/3b9Wfh') - image_data = image_request.content - - # Construct media and upload image asset. - image_asset = { - 'xsi_type': 'ImageAsset', - # Optional: Provide a unique friendly name to identify your asset. If you - # specify the assetName field, then both the asset name and the image - # being uploaded should be unique, and should not match another ACTIVE - # asset in this customer account. - # 'assetName': 'Jupiter Trip #' + str(uuid.uuid4())[:8], - 'imageData': image_data, - - } - - operation = {'operator': 'ADD', 'operand': image_asset} - - asset = asset_service.mutate([operation])['value'][0] - - # Display results. - if asset: - print ('Image asset with id %s, name "%s", and status %s was created.\n' - '\tSize is %sx%s and asset URL is %s.' % - (asset['assetId'], asset['assetName'], asset['assetStatus'], - asset['fullSizeInfo']['imageWidth'], - asset['fullSizeInfo']['imageHeight'], - asset['fullSizeInfo']['imageUrl'])) - else: - print 'No images were uploaded.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/misc/upload_media_bundle.py b/examples/adwords/v201806/misc/upload_media_bundle.py deleted file mode 100755 index 83ecb649..00000000 --- a/examples/adwords/v201806/misc/upload_media_bundle.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 uploads an HTML5 zip file. - -""" - -import urllib2 -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - media_service = client.GetService('MediaService', version='v201806') - # Create HTML5 media. - html5_zip = GetHTML5ZipFromUrl('https://goo.gl/9Y7qI2') - # Create a media bundle containing the zip file with all the HTML5 components. - media = [{ - 'xsi_type': 'MediaBundle', - 'data': html5_zip, - 'type': 'MEDIA_BUNDLE' - }] - # Upload HTML5 zip. - response = media_service.upload(media) - - if response: - for media in response: - print( - 'HTML5 media with ID %d, dimensions %dx%d, and MIME type "%s" ' - 'uploaded successfully.' % - (media['mediaId'], media['dimensions'][0]['value']['width'], - media['dimensions'][0]['value']['height'], media['mimeType'])) - - -def GetHTML5ZipFromUrl(url): - """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) - # Note: The utf-8 decode is for 2to3 Python 3 compatibility. - return response.read().decode('utf-8') - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/optimization/__init__.py b/examples/adwords/v201806/optimization/__init__.py deleted file mode 100644 index 34ee7f4b..00000000 --- a/examples/adwords/v201806/optimization/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Optimization examples.""" diff --git a/examples/adwords/v201806/optimization/estimate_keyword_traffic.py b/examples/adwords/v201806/optimization/estimate_keyword_traffic.py deleted file mode 100755 index 3a4e81bf..00000000 --- a/examples/adwords/v201806/optimization/estimate_keyword_traffic.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keyword traffic estimates. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - traffic_estimator_service = client.GetService( - 'TrafficEstimatorService', version='v201806') - - # Construct selector object and retrieve traffic estimates. - keywords = [ - {'text': 'mars cruise', 'matchType': 'BROAD'}, - {'text': 'cheap cruise', 'matchType': 'PHRASE'}, - {'text': 'cruise', 'matchType': 'EXACT'} - ] - negative_keywords = [ - {'text': 'moon walk', 'matchType': 'BROAD'} - ] - keyword_estimate_requests = [] - for keyword in keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - } - }) - - for keyword in negative_keywords: - keyword_estimate_requests.append({ - 'keyword': { - 'xsi_type': 'Keyword', - 'matchType': keyword['matchType'], - 'text': keyword['text'] - }, - 'isNegative': 'true' - }) - - # Create ad group estimate requests. - adgroup_estimate_requests = [{ - 'keywordEstimateRequests': keyword_estimate_requests, - 'maxCpc': { - 'xsi_type': 'Money', - 'microAmount': '1000000' - } - }] - - # Create campaign estimate requests. - campaign_estimate_requests = [{ - 'adGroupEstimateRequests': adgroup_estimate_requests, - 'criteria': [ - { - 'xsi_type': 'Location', - 'id': '2840' # United States. - }, - { - 'xsi_type': 'Language', - 'id': '1000' # English. - } - ], - }] - - # Create the selector. - selector = { - 'campaignEstimateRequests': campaign_estimate_requests, - } - - # Optional: Request a list of campaign-level estimates segmented by - # platform. - selector['platformEstimateRequested'] = True - - # Get traffic estimates. - estimates = traffic_estimator_service.get(selector) - - campaign_estimate = estimates['campaignEstimates'][0] - - # Display the campaign level estimates segmented by platform. - if 'platformEstimates' in campaign_estimate: - platform_template = ('Results for the platform with ID: "%d" and name: ' - '"%s".') - for platform_estimate in campaign_estimate['platformEstimates']: - platform = platform_estimate['platform'] - DisplayEstimate(platform_template % (platform['id'], - platform['platformName']), - platform_estimate['minEstimate'], - platform_estimate['maxEstimate']) - - # Display the keyword estimates. - if 'adGroupEstimates' in campaign_estimate: - ad_group_estimate = campaign_estimate['adGroupEstimates'][0] - if 'keywordEstimates' in ad_group_estimate: - keyword_estimates = ad_group_estimate['keywordEstimates'] - keyword_template = ('Results for the keyword with text "%s" and match ' - 'type "%s":') - - keyword_estimates_and_requests = zip(keyword_estimates, - keyword_estimate_requests) - - for keyword_tuple in keyword_estimates_and_requests: - if keyword_tuple[1].get('isNegative', False): - continue - keyword = keyword_tuple[1]['keyword'] - keyword_estimate = keyword_tuple[0] - DisplayEstimate(keyword_template % (keyword['text'], - keyword['matchType']), - keyword_estimate['min'], keyword_estimate['max']) - - -def _CalculateMean(min_est, max_est): - if min_est and max_est: - return (float(min_est) + float(max_est)) / 2.0 - else: - return None - - -def _FormatMean(mean): - if mean: - return '%.2f' % mean - else: - return 'N/A' - - -def DisplayEstimate(message, min_estimate, max_estimate): - """Displays mean average cpc, position, clicks, and total cost for estimate. - - Args: - message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the - TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the - TrafficEstimatorService response. - """ - # Find the mean of the min and max values. - mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], - max_estimate['averageCpc']['microAmount']) - if 'averageCpc' in min_estimate - and min_estimate['averageCpc'] else None) - mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], - max_estimate['averagePosition']) - if 'averagePosition' in min_estimate - and min_estimate['averagePosition'] else None) - mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], - max_estimate['clicksPerDay']) - mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], - max_estimate['totalCost']['microAmount']) - - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201806/optimization/get_campaign_criterion_bid_modifier_simulations.py deleted file mode 100755 index 13cce825..00000000 --- a/examples/adwords/v201806/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets all available campaign criterion bid modifier landscapes for a campaign. - -To get campaigns, run basic_operations/get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, campaign_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201806') - - # Get all the campaigns for this account. - selector = { - 'fields': ['CampaignId', 'CriterionId', 'StartDate', 'EndDate', - 'BidModifier', 'LocalClicks', 'LocalCost', 'LocalImpressions', - 'TotalLocalClicks', 'TotalLocalCost', 'TotalLocalImpressions', - 'RequiredBudget'], - 'paging': { - 'startIndex': 0, - 'numberResults': PAGE_SIZE - }, - 'predicates': [{ - 'field': 'CampaignId', 'operator': 'IN', 'values': [campaign_id] - }] - } - - # Set initial values. - offset = 0 - more_pages = True - - while more_pages is True: - num_landscape_points = 0 - page = data_service.getCampaignCriterionBidLandscape(selector) - - # Display results. - if 'entries' in page: - for bid_modifier_landscape in page['entries']: - num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) - for landscape_point in bid_modifier_landscape['landscapePoints']: - num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) - else: - print 'No bid modifier landscapes found.' - - # Need to increment by the total # of landscape points within the page, - # NOT the number of entries (bid landscapes) in the page. - offset += num_landscape_points - selector['paging']['startIndex'] = str(offset) - more_pages = num_landscape_points >= PAGE_SIZE - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py deleted file mode 100755 index 79a8cf5c..00000000 --- a/examples/adwords/v201806/optimization/get_keyword_bid_simulations.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 a bid landscape for an ad group and a criterion. - -To get ad groups, run get_ad_groups.py. To get criteria, run get_keywords.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -CRITERION_ID = 'INSERT_CRITERION_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id, criterion_id): - # Initialize appropriate service. - data_service = client.GetService('DataService', version='v201806') - - # Create a query to select all keyword bid simulations for the specified - # ad group and criterion ID. - query = (adwords.ServiceQueryBuilder() - .Select( - 'AdGroupId', 'CriterionId', 'StartDate', 'EndDate', 'Bid', - 'BiddableConversions', 'BiddableConversionsValue', 'LocalClicks', - 'LocalCost', 'LocalImpressions') - .Where('AdGroupId').EqualTo(ad_group_id) - .Where('CriterionId').EqualTo(criterion_id) - .Limit(0, PAGE_SIZE) - .Build()) - - while True: - page = data_service.queryCriterionBidLandscape(query) - - if page and 'entries' in page: - entries = page['entries'] - print 'Bid landscape(s) retrieved: %d.' % len(entries) - - for bid_landscape in entries: - print ('Retrieved keyword bid landscape with ad group ID "%d", ' - 'keyword ID "%d", start date "%s", end date "%s", ' - 'with landscape points:' % ( - bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) - for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s, ' - 'biddable conversions: %.2f, ' - 'biddable conversions value: %.2f' - % (bid_landscape_point['bid']['microAmount'], - bid_landscape_point['clicks'], - bid_landscape_point['cost']['microAmount'], - bid_landscape_point['impressions'], - bid_landscape_point['biddableConversions'], - bid_landscape_point['biddableConversionsValue'])) - - if not query.HasNext(page): - break - query.NextPage() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID, CRITERION_ID) diff --git a/examples/adwords/v201806/optimization/get_keyword_ideas.py b/examples/adwords/v201806/optimization/get_keyword_ideas.py deleted file mode 100755 index c397aa79..00000000 --- a/examples/adwords/v201806/optimization/get_keyword_ideas.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 keywords that are related to a given keyword. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Optional AdGroup ID used to set a SearchAdGroupIdSearchParameter. -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' -PAGE_SIZE = 100 - - -def main(client, ad_group_id=None): - # Initialize appropriate service. - targeting_idea_service = client.GetService( - 'TargetingIdeaService', version='v201806') - - # Construct selector object and retrieve related keywords. - selector = { - 'ideaType': 'KEYWORD', - 'requestType': 'IDEAS' - } - - selector['requestedAttributeTypes'] = [ - 'KEYWORD_TEXT', 'SEARCH_VOLUME', 'CATEGORY_PRODUCTS_AND_SERVICES'] - - offset = 0 - selector['paging'] = { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - - selector['searchParameters'] = [{ - 'xsi_type': 'RelatedToQuerySearchParameter', - 'queries': ['space cruise'] - }] - - # Language setting (optional). - selector['searchParameters'].append({ - # The ID can be found in the documentation: - # https://developers.google.com/adwords/api/docs/appendix/languagecodes - 'xsi_type': 'LanguageSearchParameter', - 'languages': [{'id': '1000'}] - }) - - # Network search parameter (optional) - selector['searchParameters'].append({ - 'xsi_type': 'NetworkSearchParameter', - 'networkSetting': { - 'targetGoogleSearch': True, - 'targetSearchNetwork': False, - 'targetContentNetwork': False, - 'targetPartnerSearchNetwork': False - } - }) - - # Use an existing ad group to generate ideas (optional) - if ad_group_id is not None: - selector['searchParameters'].append({ - 'xsi_type': 'SeedAdGroupIdSearchParameter', - 'adGroupId': ad_group_id - }) - - more_pages = True - while more_pages: - page = targeting_idea_service.get(selector) - - # Display results. - if 'entries' in page: - for result in page['entries']: - attributes = {} - for attribute in result['data']: - attributes[attribute['key']] = getattr( - attribute['value'], 'value', '0') - print ('Keyword with "%s" text and average monthly search volume ' - '"%s" was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], - attributes['SEARCH_VOLUME'], - attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) - print - else: - print 'No related keywords were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, int(AD_GROUP_ID) if AD_GROUP_ID.isdigit() else None) diff --git a/examples/adwords/v201806/remarketing/__init__.py b/examples/adwords/v201806/remarketing/__init__.py deleted file mode 100644 index c4912fc8..00000000 --- a/examples/adwords/v201806/remarketing/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Remarketing examples.""" diff --git a/examples/adwords/v201806/remarketing/add_audience.py b/examples/adwords/v201806/remarketing/add_audience.py deleted file mode 100755 index ba6be197..00000000 --- a/examples/adwords/v201806/remarketing/add_audience.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a remarketing user list (a.k.a. audience). - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -PAGE_SIZE = 100 - - -def main(client): - # Initialize appropriate service. - user_list_service = client.GetService( - 'AdwordsUserListService', version='v201806') - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201806') - - # Construct operations and add a user list. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BasicUserList', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'description': 'A list of mars cruise customers in the last year', - 'membershipLifeSpan': '365', - 'conversionTypes': [ - { - 'name': ('Mars cruise customers #%s' - % uuid.uuid4()) - } - ], - # Optional field. - 'status': 'OPEN', - } - } - ] - user_list_result = user_list_service.mutate(operations) - - # Capture the ID(s) of the conversion. - if 'value' in user_list_result: - conversion_ids = [] - for user_list in user_list_result['value']: - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_ids.append(conversion_type['id']) - - # Create query. - query = (adwords.ServiceQueryBuilder() - .Select('Id', 'GoogleGlobalSiteTag', 'GoogleEventSnippet') - .Where('Id').In(*conversion_ids) - .Limit(0, PAGE_SIZE) - .Build()) - - conversions_map = {} - - # Get all conversion trackers. - for page in query.Pager(conversion_tracker_service): - if 'entries' in page: - for conversion_tracker in page['entries']: - conversions_map[conversion_tracker['id']] = conversion_tracker - - for user_list in user_list_result['value']: - print ('User list with name "%s" and ID "%s" was added.' - % (user_list['name'], user_list['id'])) - if user_list['conversionTypes']: - for conversion_type in user_list['conversionTypes']: - conversion_tracker = conversions_map[conversion_type['id']] - print ('Google global site tag:\n%s\n\n' - % conversion_tracker['googleGlobalSiteTag']) - print ('Google event snippet:\n%s\n\n' - % conversion_tracker['googleEventSnippet']) - else: - print 'No user lists were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/add_conversion_tracker.py b/examples/adwords/v201806/remarketing/add_conversion_tracker.py deleted file mode 100755 index 83e4e38d..00000000 --- a/examples/adwords/v201806/remarketing/add_conversion_tracker.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds an AdWords conversion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201806') - - # Construct operations and add conversion_tracker. - operations = [ - { - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Mars cruise customers #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - } - ] - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/add_conversion_trackers.py b/examples/adwords/v201806/remarketing/add_conversion_trackers.py deleted file mode 100755 index c66a29a7..00000000 --- a/examples/adwords/v201806/remarketing/add_conversion_trackers.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds AdWords conversion trackers. - -Adds an AdWords conversion tracker and an upload conversion tracker. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - conversion_tracker_service = client.GetService( - 'ConversionTrackerService', version='v201806') - - # Create an AdWords conversion tracker. - adwords_conversion_tracker = { - 'xsi_type': 'AdWordsConversionTracker', - 'name': 'Earth to Mars Cruises Conversion #%s' % uuid.uuid4(), - 'category': 'DEFAULT', - # Optional fields. - 'status': 'ENABLED', - 'viewthroughLookbackWindow': '15', - 'defaultRevenueValue': '23.41', - 'alwaysUseDefaultRevenueValue': 'true' - } - - upload_conversion = { - 'xsi_type': 'UploadConversion', - 'name': 'Upload Conversion #%s' % uuid.uuid4(), - # Optional fields. - # Set an appropriate category. This will be set to DEFAULT if not - # specified. - 'category': 'LEAD', - 'viewthroughLookbackWindow': '30', - 'ctcLookbackWindow': '90', - # Set the default currency code to use for conversions that do - # not specify a conversion currency. This must be an ISO 4217 3-character - # code such as "EUR" or "USD". - # If this field is not set, AdWords will use the account's currency. - 'defaultRevenueCurrencyCode': 'EUR', - # Set the default revenue value to use for conversions that do not specify - # a converison value. Note that this value should NOT be in micros. - 'defaultRevenueValue': '2.50', - # To upload fractional conversion credits, mark the upload conversion as - # externally attributed. To learn more about importing externally - # attributed conversions, see: - # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions - # 'isExternallyAttributed': 'true' - } - - # Construct operations. - operations = [{ - 'operator': 'ADD', - 'operand': conversion_tracker - } for conversion_tracker in [adwords_conversion_tracker, upload_conversion]] - - # Add the conversions. - conversion_trackers = conversion_tracker_service.mutate(operations) - - # Display results. - for conversion_tracker in conversion_trackers['value']: - print ('Conversion with ID "%d", name "%s", status "%s", and category ' - '"%s" was added.' - % (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'])) - if (conversion_tracker['ConversionTracker.Type'] - == 'AdWordsConversionTracker'): - print ('Google global site tag:\n%s\n\n' - % conversion_tracker['googleGlobalSiteTag']) - print ('Google event snippet:\n%s\n\n' - % conversion_tracker['googleEventSnippet']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/add_crm_based_user_list.py b/examples/adwords/v201806/remarketing/add_crm_based_user_list.py deleted file mode 100755 index 6569c528..00000000 --- a/examples/adwords/v201806/remarketing/add_crm_based_user_list.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - - -"""Adds a user list and populates it with hashed email addresses. - -Note: It may take several hours for the list to be populated with members. Email -addresses must be associated with a Google account. For privacy purposes, the -user list size will show as zero until the list has at least 1000 members. After -that, the size will be rounded to the two most significant digits. -""" - - -import hashlib -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - # Initialize appropriate services. - user_list_service = client.GetService('AdwordsUserListService', 'v201806') - - user_list = { - 'xsi_type': 'CrmBasedUserList', - 'name': 'Customer relationship management list #%d' % uuid.uuid4(), - 'description': 'A list of customers that originated from email addresses', - # CRM-based user lists can use a membershipLifeSpan of 10000 to indicate - # unlimited; otherwise normal values apply. - 'membershipLifeSpan': 30, - 'uploadKeyType': 'CONTACT_INFO' - } - - # Create an operation to add the user list. - operations = [{ - 'operator': 'ADD', - 'operand': user_list - }] - - result = user_list_service.mutate(operations) - user_list_id = result['value'][0]['id'] - - emails = ['customer1@example.com', 'customer2@example.com', - ' Customer3@example.com '] - members = [{'hashedEmail': NormalizeAndSHA256(email)} for email in emails] - - # Add address info. - members.append({ - 'addressInfo': { - # First and last name must be normalized and hashed. - 'hashedFirstName': NormalizeAndSHA256('John'), - 'hashedLastName': NormalizeAndSHA256('Doe'), - # Country code and zip code are sent in plaintext. - 'countryCode': 'US', - 'zipCode': '10001' - } - }) - - mutate_members_operation = { - 'operand': { - 'userListId': user_list_id, - 'membersList': members - }, - 'operator': 'ADD' - } - - response = user_list_service.mutateMembers([mutate_members_operation]) - - if 'userLists' in response: - for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) - - -def NormalizeAndSHA256(s): - """Normalizes (lowercase, remove whitespace) and hashes a string with SHA-256. - - Args: - s: The string to perform this operation on. - - Returns: - A normalized and SHA-256 hashed string. - """ - return hashlib.sha256(s.strip().lower()).hexdigest() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201806/remarketing/add_rule_based_user_lists.py deleted file mode 100755 index 8efdfbe4..00000000 --- a/examples/adwords/v201806/remarketing/add_rule_based_user_lists.py +++ /dev/null @@ -1,235 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds two rule-based remarketing user lists. - -Adds two rule-based remarketing user lists; one with no site visit date -restrictions and another that will only include users who visit your site in -the next six months. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import calendar -from datetime import date -from datetime import datetime -from datetime import timedelta -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - adwords_user_list_service = client.GetService( - 'AdwordsUserListService', version='v201806') - - # First rule item group - users who visited the checkout page and had more - # than one item in their shopping cart. - checkout_rule_item = { - 'StringRuleItem': { - 'key': { - 'name': 'ecomm_pagetype' - }, - 'op': 'EQUALS', - 'value': 'checkout' - } - } - - cart_size_rule_item = { - 'NumberRuleItem': { - 'key': { - 'name': 'cartsize' - }, - 'op': 'GREATER_THAN', - 'value': '1.0' - } - } - - # Combine the two rule items into a RuleItemGroup so AdWords will logically - # AND the rules together. - checkout_multiple_item_group = { - 'items': [checkout_rule_item, cart_size_rule_item] - } - - # Second rule item group - users who checked out within the next 3 months. - today = date.today() - start_date_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'AFTER', - 'value': today.strftime('%Y%m%d') - } - } - - three_months_later = AddMonths(today, 3) - - three_months_later_rule_item = { - 'DateRuleItem': { - 'key': { - 'name': 'checkoutdate' - }, - 'op': 'BEFORE', - 'value': three_months_later.strftime('%Y%m%d') - } - } - - # Combine the date rule items into a RuleItemGroup - checked_out_date_range_item_group = { - 'items': [start_date_rule_item, three_months_later_rule_item] - } - - # Combine the rule item groups into a Rule so AdWords knows how to apply the - # rules. - rule = { - 'groups': [ - checkout_multiple_item_group, - checked_out_date_range_item_group - ], - # ExpressionRuleUserLists can use either CNF or DNF for matching. CNF - # means 'at least one item in each rule item group must match', and DNF - # means 'at least one entire rule item group must match'. - # DateSpecificRuleUserList only supports DNF. You can also omit the rule - # type altogether to default to DNF. - 'ruleType': 'DNF' - } - - # Third and fourth rule item groups. - # Visitors of a page who visited another page. - site1_rule_item = { - 'StringRuleItem': { - 'key': {'name': 'url__'}, - 'op': 'EQUALS', - 'value': 'example.com/example1' - } - } - site2_rule_item = { - 'StringRuleItem': { - 'key': {'name': 'url__'}, - 'op': 'EQUALS', - 'value': 'example.com/example2' - } - } - - # Create two rules to show that a visitor browsed two sites. - user_visited_site1_rule = { - 'groups': [{ - 'items': [site1_rule_item] - }] - } - - user_visited_site2_rule = { - 'groups': [{ - 'items': [site2_rule_item] - }] - } - - # Create the user list with no restrictions on site visit date. - expression_user_list = { - 'xsi_type': 'ExpressionRuleUserList', - 'name': 'Expression-based user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who checked out in three month window OR visited' - ' the checkout page with more than one item in their' - ' cart.', - 'rule': rule, - # Optional: Set the populationStatus to REQUESTED to include past users in - # the user list. - 'prepopulationStatus': 'REQUESTED' - } - - # Create the user list restricted to users who visit your site within the next - # six months. - end_date = AddMonths(today, 6) - - date_user_list = { - 'xsi_type': 'DateSpecificRuleUserList', - 'name': 'Date rule user list created at %s' - % datetime.today().strftime('%Y%m%d %H:%M:%S'), - 'description': 'Users who visited the site between %s and %s and checked' - ' out in three month window OR visited the checkout page' - ' with more than one item in their cart.' - % (today.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')), - 'rule': rule, - 'startDate': today.strftime('%Y%m%d'), - 'endDate': end_date.strftime('%Y%m%d') - } - - # Create the user list for "Visitors of a page who did visit another page". - # To create a user list for "Visitors of a page who did not visit another - # page", change the ruleOperator from AND to AND_NOT. - combined_user_list = { - 'xsi_type': 'CombinedRuleUserList', - 'name': 'Combined rule user lst create at ${creation_time}', - 'description': 'Users who visited two sites.', - 'leftOperand': user_visited_site1_rule, - 'rightOperand': user_visited_site2_rule, - 'ruleOperator': 'AND' - } - - # Create operations to add the user lists. - operations = [ - { - 'operand': user_list, - 'operator': 'ADD', - } for user_list in [expression_user_list, date_user_list, - combined_user_list] - ] - - # Submit the operations. - user_lists = adwords_user_list_service.mutate(operations) - - # Display results. - for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) - - -def AddMonths(start_date, months): - """A simple convenience utility for adding months to a given start date. - - This increments the months by adding the number of days in the current month - to the current month, for each month. - - Args: - start_date: date The date months are being added to. - months: int The number of months to add. - - Returns: - A date equal to the start date incremented by the given number of months. - """ - current_date = start_date - i = 0 - while i < months: - month_days = calendar.monthrange(current_date.year, current_date.month)[1] - current_date += timedelta(days=month_days) - i += 1 - return current_date - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/remarketing/upload_conversion_adjustments.py b/examples/adwords/v201806/remarketing/upload_conversion_adjustments.py deleted file mode 100755 index a33e8d17..00000000 --- a/examples/adwords/v201806/remarketing/upload_conversion_adjustments.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 Google LLC -# -# 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 -# -# https://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. - -"""Imports conversion adjustments for conversions that already exist. - -To set up a conversion tracker, run the add_conversion_tracker.py example. - -""" - -from googleads import adwords - - -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' - -GCLID = 'INSERT_GCLID_HERE' - -ADJUSTMENT_TYPE = 'INSERT_ADJUSTMENT_TYPE_HERE' - -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' - -ADJUSTMENT_TIME = 'INSERT_ADJUSTMENT_TIME_HERE' - -ADJUSTED_VALUE = 'INSERT_ADJUST_VALUE_HERE' - - -def main(client, conversion_name, gclid, adjustment_type, conversion_time, - adjustment_time, adjusted_value): - # Initialize appropriate services. - offline_conversion_service = client.GetService( - 'OfflineConversionAdjustmentFeedService', version='v201806') - - # Associate conversion adjustments with the existing named conversion tracker. - # The GCLID should have been uploaded before with a conversion. - feed = { - 'xsi_type': 'GclidOfflineConversionAdjustmentFeed', - 'conversionName': conversion_name, - 'googleClickId': gclid, - 'conversionTime': conversion_time, - 'adjustmentType': adjustment_type, - 'adjustmentTime': adjustment_time, - 'adjustedValue': adjusted_value - } - - offline_conversion_operation = {'operator': 'ADD', 'operand': feed} - - offline_conversion_response = offline_conversion_service.mutate( - [offline_conversion_operation]) - - new_feed = offline_conversion_response['value'][0] - - print ('Uploaded offline conversion adjustment value of "%s" for Google ' - 'Click ID "%s"' % (new_feed['adjustedValue'], - new_feed['googleClickId'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, GCLID, ADJUSTMENT_TYPE, CONVERSION_TIME, - ADJUSTMENT_TIME, ADJUSTED_VALUE) diff --git a/examples/adwords/v201806/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201806/remarketing/upload_offline_call_conversions.py deleted file mode 100755 index a35ba52c..00000000 --- a/examples/adwords/v201806/remarketing/upload_offline_call_conversions.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for calls related to ads in your account. - -To set up a conversion tracker, run the add_conversion_trackers.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CALLER_ID = 'INSERT_CALLER_ID_HERE' -# For times use the format yyyyMMdd HHmmss tz. For more details on formats, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats -# For time zones, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -CALL_START_TIME = 'INSERT_CALL_START_TIME' -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' # Name of conversion tracker. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, caller_id, call_start_time, conversion_name, conversion_time, - conversion_value): - # Initialize appropriate services. - occ_feed_service = client.GetService( - 'OfflineCallConversionFeedService', version='v201806') - - # Associate offline call conversions with the existing named conversion - # tracker. If this tracker was newly created, it may be a few hours before it - # can accept conversions. - feed = { - 'callerId': caller_id, - 'callStartTime': call_start_time, - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - } - - occ_operations = [{'operator': 'ADD', 'operand': feed}] - - occ_response = occ_feed_service.mutate(occ_operations) - values = occ_response['value'] - - if values: - for occ_feed in values: - print ('Uploaded offline call conversion value of "%s" for caller ID ' - '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) - else: - print 'No offline call conversions were added.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CALLER_ID, CALL_START_TIME, CONVERSION_NAME, - CONVERSION_TIME, CONVERSION_VALUE) diff --git a/examples/adwords/v201806/remarketing/upload_offline_conversions.py b/examples/adwords/v201806/remarketing/upload_offline_conversions.py deleted file mode 100755 index 71a5ba5a..00000000 --- a/examples/adwords/v201806/remarketing/upload_offline_conversions.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Imports offline conversion values for specific clicks into your account. - -To get the Google Click ID for a click, run a CLICK_PERFORMANCE_REPORT. To set -up a conversion tracker, run the add_conversion_trackers.py example. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Your click ID must be less than 30 days old. -CLICK_ID = 'INSERT_GOOGLE_CLICK_ID_HERE' -# The conversion time must be more recent than the time of the click. -CONVERSION_TIME = 'INSERT_CONVERSION_TIME_HERE' -CONVERSION_VALUE = 'INSERT_CONVERSION_VALUE_HERE' - - -def main(client, conversion_name, click_id, conversion_time, conversion_value): - # Initialize appropriate services. - offline_conversion_feed_service = client.GetService( - 'OfflineConversionFeedService', version='v201806') - - # Associate offline conversions with the existing named conversion tracker. If - # this tracker was newly created, it may be a few hours before it can accept - # conversions. - feed = { - 'conversionName': conversion_name, - 'conversionTime': conversion_time, - 'conversionValue': conversion_value, - 'googleClickId': click_id, - # Optional: To upload fractional conversion credits, set the external - # attribution model and credit. To use this feature, your conversion - # tracker should be marked as externally attributed. To learn more about - # importing externally attributed conversins, see: - # https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions - # 'externalAttributionCredit': 0.3, - # 'externalAttributionModel': 'Linear' - } - - offline_conversion_operation = { - 'operator': 'ADD', - 'operand': feed - } - - offline_conversion_response = offline_conversion_feed_service.mutate( - [offline_conversion_operation]) - new_feed = offline_conversion_response['value'] - - print ('Uploaded offline conversion value of "%s" for Google Click ID ' - '"%s" to "%s".' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, CLICK_ID, CONVERSION_TIME, - CONVERSION_VALUE) diff --git a/examples/adwords/v201806/remarketing/upload_offline_data.py b/examples/adwords/v201806/remarketing/upload_offline_data.py deleted file mode 100755 index 549fecc5..00000000 --- a/examples/adwords/v201806/remarketing/upload_offline_data.py +++ /dev/null @@ -1,259 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 shows how to upload offline data for store sales transactions. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import datetime -import hashlib - -from googleads import adwords -import pytz - - -_DT_FORMAT = '%Y%m%d %H%M%S' -# User identifier types whose values must be hashed. -_HASHED_IDENTIFIER_TYPES = ('HASHED_EMAIL', 'HASHED_FIRST_NAME', - 'HASHED_LAST_NAME', 'HASHED_PHONE') -# The timezone to be used in this example. For valid timezone IDs, see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -_TIMEZONE = pytz.timezone('America/New_York') -# Name of the conversion tracker to upload to. -CONVERSION_NAME = 'INSERT_CONVERSION_NAME_HERE' -# Insert email addresses below for creating user identifiers. -EMAIL_ADDRESSES = ['EMAIL_ADDRESS_1', 'EMAIL_ADDRESS_2'] -# The external upload ID can be any number that you use to keep track of your -# uploads. -EXTERNAL_UPLOAD_ID = 'INSERT_EXTERNAL_UPLOAD_ID' -# Store sales upload common metadata types -METADATA_TYPE_1P = 'FirstPartyUploadMetadata' -METADATA_TYPE_3P = 'ThirdPartyUploadMetadata' -# Set the below constant to METADATA_TYPE_3P if uploading third-party data. -STORE_SALES_UPLOAD_COMMON_METADATA_TYPE = METADATA_TYPE_1P -# The three constants below are needed when uploading third-party data. They -# are not used when uploading first-party data. -# Advertiser upload time to partner. -# For times, use the format yyyyMMdd HHmmss tz. For more details on formats, -# see: -# https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids -ADVERTISER_UPLOAD_TIME = 'INSERT_ADVERTISER_UPLOAD_TIME_HERE' -# Indicates the version of the bridge map. -BRIDGE_MAP_VERSION_ID = 'INSERT_BRIDGE_MAP_VERSION_ID_HERE' -# The ID of the third party uploading the transaction feed. -PARTNER_ID = 'INSERT_PARTNER_ID_HERE' - - -def main(client, conversion_name, external_upload_id, - store_sales_upload_common_metadata_type, email_addresses, - advertiser_upload_time=None, bridge_map_version_id=None, - partner_id=None): - # Set partial failure to True since this example demonstrates how to handle - # partial errors. - client.partial_failure = True - # Initialize appropriate services. - offline_data_upload_service = client.GetService( - 'OfflineDataUploadService', version='v201806') - - # Create the first offline data for upload. - # This transaction occurred 7 days ago with an amount of $200 USD. - transaction_time_1 = (datetime.datetime.now(tz=_TIMEZONE) - - datetime.timedelta(days=7)) - offline_data_1 = { - 'StoreSalesTransaction': { - 'userIdentifiers': [ - _CreateUserIdentifier(identifier_type='HASHED_EMAIL', - value=email_addresses[0]), - _CreateUserIdentifier(identifier_type='STATE', value='New York') - ], - 'transactionTime': _GetFormattedDateTime(transaction_time_1), - 'transactionAmount': { - 'currencyCode': 'USD', - 'money': { - 'microAmount': 200000000 - } - }, - 'conversionName': conversion_name - } - } - - # Create the second offline data for upload. - # This transaction occurred 14 days ago with amount of 450 EUR. - transaction_time_2 = (datetime.datetime.now(tz=_TIMEZONE) - - datetime.timedelta(days=14)) - offline_data_2 = { - 'StoreSalesTransaction': { - 'userIdentifiers': [ - _CreateUserIdentifier(identifier_type='HASHED_EMAIL', - value=email_addresses[1]), - _CreateUserIdentifier(identifier_type='STATE', value='California') - ], - 'transactionTime': _GetFormattedDateTime(transaction_time_2), - 'transactionAmount': { - 'currencyCode': 'EUR', - 'money': { - 'microAmount': 450000000 - } - }, - 'conversionName': conversion_name - } - } - - # Set the type and metadata of this upload. - upload_metadata = { - 'StoreSalesUploadCommonMetadata': { - 'xsi_type': store_sales_upload_common_metadata_type, - 'loyaltyRate': 1.0, - 'transactionUploadRate': 1.0, - } - } - - if store_sales_upload_common_metadata_type == METADATA_TYPE_1P: - upload_type = 'STORE_SALES_UPLOAD_FIRST_PARTY' - elif store_sales_upload_common_metadata_type == METADATA_TYPE_3P: - upload_type = 'STORE_SALES_UPLOAD_THIRD_PARTY' - upload_metadata['StoreSalesUploadCommonMetadata'].update({ - 'advertiserUploadTime': advertiser_upload_time, - 'validTransactionRate': 1.0, - 'partnerMatchRate': 1.0, - 'partnerUploadRate': 1.0, - 'bridgeMapVersionId': bridge_map_version_id, - 'partnerId': partner_id - }) - else: - raise ValueError('Unknown metadata type.') - - # Create offline data upload - offline_data_upload = { - 'externalUploadId': external_upload_id, - 'offlineDataList': [offline_data_1, offline_data_2], - # Set the type of this upload. - 'uploadType': upload_type, - 'uploadMetadata': upload_metadata - } - - # Create an offline data upload operation. - operations = [{ - 'operator': 'ADD', - 'operand': offline_data_upload - }] - - # Upload offline data on the server and print the result. - result = offline_data_upload_service.mutate(operations) - offline_data_upload = result['value'][0] - - print ('Uploaded offline data with external upload ID "%d" and upload status ' - '"%s".' % (offline_data_upload['externalUploadId'], - offline_data_upload['uploadStatus'])) - - # Print any partial data errors from the response. - if result['partialFailureErrors']: - for api_error in result['partialFailureErrors']: - # Get the index of the failed operation from the error's field path - # elements. - operation_index = _GetFieldPathElementIndex(api_error, 'operations') - - if operation_index: - failed_offline_data_upload = operations[operation_index]['operand'] - # Get the index of the entry in the offline data list from the error's - # field path elements. - offline_data_list_index = _GetFieldPathElementIndex( - api_error, 'offlineDataList') - print ('Offline data list entry "%d" in operation "%d" with external ' - 'upload ID "%d" and type "%s" has triggered failure for the ' - 'following reason: "%s"' % ( - offline_data_list_index, operation_index, - failed_offline_data_upload['externalUploadId'], - failed_offline_data_upload['uploadType'], - api_error['errorString'])) - else: - print ('A failure has occurred for the following reason: "%s".' % ( - api_error['errorString'])) - - -def _CreateUserIdentifier(identifier_type=None, value=None): - """Creates a user identifier from the specified type and value. - - Args: - identifier_type: a str specifying the type of user identifier. - value: a str value of the identifier; to be hashed using SHA-256 if needed. - - Returns: - A dict specifying a user identifier, with a value hashed using SHA-256 if - needed. - """ - if identifier_type in _HASHED_IDENTIFIER_TYPES: - # If the user identifier type is a hashed type, normalize and hash the - # value. - value = hashlib.sha256(value.strip().lower()).hexdigest() - - user_identifier = { - 'userIdentifierType': identifier_type, - 'value': value - } - - return user_identifier - - -def _GetFieldPathElementIndex(api_error, field): - """Retrieve the index of a given field in the api_error's fieldPathElements. - - Args: - api_error: a dict containing a partialFailureError returned from the AdWords - API. - field: a str field for which this determines the index in the api_error's - fieldPathElements. - - Returns: - An int index of the field path element, or None if the specified field can't - be found in the api_error. - """ - field_path_elements = api_error['fieldPathElements'] - - if field_path_elements: - found_index = [field_path_element['index'] - for field_path_element in field_path_elements - if field_path_element['field'] == field] - if found_index: - return found_index - - return None - - -def _GetFormattedDateTime(dt): - """Formats the given datetime and timezone for use with AdWords. - - Args: - dt: a datetime instance. - - Returns: - A str representation of the datetime in the correct format for AdWords. - """ - return '%s %s' % (datetime.datetime.strftime(dt, _DT_FORMAT), _TIMEZONE.zone) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CONVERSION_NAME, EXTERNAL_UPLOAD_ID, - STORE_SALES_UPLOAD_COMMON_METADATA_TYPE, EMAIL_ADDRESSES, - ADVERTISER_UPLOAD_TIME, BRIDGE_MAP_VERSION_ID, PARTNER_ID) diff --git a/examples/adwords/v201806/reporting/__init__.py b/examples/adwords/v201806/reporting/__init__.py deleted file mode 100644 index 8f94f28b..00000000 --- a/examples/adwords/v201806/reporting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Reporting examples.""" diff --git a/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_awql.py deleted file mode 100755 index 6969c22a..00000000 --- a/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_awql.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a stream with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import StringIO -import sys - -from googleads import adwords - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201806') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, - 'CSV') - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_selector.py deleted file mode 100755 index 5232bbbc..00000000 --- a/examples/adwords/v201806/reporting/download_criteria_report_as_stream_with_selector.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the report download stream. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import StringIO -import sys -from googleads import adwords - -# The chunk size used for the report download. -CHUNK_SIZE = 16 * 1024 - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201806') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Retrieve the report stream and print it out - report_data = StringIO.StringIO() - stream_data = report_downloader.DownloadReportAsStream( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - try: - while True: - chunk = stream_data.read(CHUNK_SIZE) - if not chunk: break - report_data.write(chunk.decode() if sys.version_info[0] == 3 - and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() - finally: - report_data.close() - stream_data.close() - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_awql.py deleted file mode 100755 index 3082b800..00000000 --- a/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -# Specify where to download the file here. -PATH = '/tmp/report_download.csv' - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201806') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_selector.py deleted file mode 100755 index 1650fe9b..00000000 --- a/examples/adwords/v201806/reporting/download_criteria_report_as_string_with_selector.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report as a string. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -from googleads import adwords - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201806') - - # Create report definition. - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_with_awql.py b/examples/adwords/v201806/reporting/download_criteria_report_with_awql.py deleted file mode 100755 index 14eed254..00000000 --- a/examples/adwords/v201806/reporting/download_criteria_report_with_awql.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report with AWQL. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -import sys -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - report_downloader = client.GetReportDownloader(version='v201806') - - # Create report query. - report_query = (adwords.ReportQueryBuilder() - .Select('CampaignId', 'AdGroupId', 'Id', 'Criteria', - 'CriteriaType', 'FinalUrls', 'Impressions', 'Clicks', - 'Cost') - .From('CRITERIA_PERFORMANCE_REPORT') - .Where('Status').In('ENABLED', 'PAUSED') - .During('LAST_7_DAYS') - .Build()) - - # You can provide a file object to write the output to. For this - # demonstration we use sys.stdout to write the report to the screen. - report_downloader.DownloadReportWithAwql( - report_query, 'CSV', sys.stdout, skip_report_header=False, - skip_column_header=False, skip_report_summary=False, - include_zero_impressions=True) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/reporting/download_criteria_report_with_selector.py b/examples/adwords/v201806/reporting/download_criteria_report_with_selector.py deleted file mode 100755 index 17a8ecbc..00000000 --- a/examples/adwords/v201806/reporting/download_criteria_report_with_selector.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads a criteria performance report. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import sys -from googleads import adwords - - -def main(client): - report_downloader = client.GetReportDownloader(version='v201806') - - report = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - # You can provide a file object to write the output to. For this demonstration - # we use sys.stdout to write the report to the screen. - report_downloader.DownloadReport( - report, sys.stdout, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) - - -if __name__ == '__main__': - adwords_client = adwords.AdWordsClient.LoadFromStorage() - main(adwords_client) diff --git a/examples/adwords/v201806/reporting/get_report_fields.py b/examples/adwords/v201806/reporting/get_report_fields.py deleted file mode 100755 index 121144ed..00000000 --- a/examples/adwords/v201806/reporting/get_report_fields.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 report fields. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -REPORT_TYPE = 'INSERT_REPORT_TYPE_HERE' - - -def main(client, report_type): - # Initialize appropriate service. - report_definition_service = client.GetService( - 'ReportDefinitionService', version='v201806') - - # Get report fields. - fields = report_definition_service.getReportFields(report_type) - - # Display results. - print 'Report type "%s" contains the following fields:' % report_type - for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) - if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, REPORT_TYPE) diff --git a/examples/adwords/v201806/reporting/parallel_report_download.py b/examples/adwords/v201806/reporting/parallel_report_download.py deleted file mode 100755 index a4d3fbad..00000000 --- a/examples/adwords/v201806/reporting/parallel_report_download.py +++ /dev/null @@ -1,244 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 downloads an adgroup performance report for all child accounts. - -To get report fields, run get_report_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import multiprocessing -import os -from Queue import Empty -import time - -import googleads.adwords -import googleads.errors - -# Timeout between retries in seconds. -BACKOFF_FACTOR = 5 -# Maximum number of processes to spawn. -MAX_PROCESSES = multiprocessing.cpu_count() -# Maximum number of retries for 500 errors. -MAX_RETRIES = 5 -# Maximum number of items to be sent in a single API response. -PAGE_SIZE = 100 -# Directory to download the reports to. -REPORT_DOWNLOAD_DIRECTORY = 'INSERT_REPORT_DOWNLOAD_DIRECTORY' - - -def _DownloadReport(process_id, report_download_directory, customer_id, - report_definition): - """Helper function used by ReportWorker to download customer report. - - Note that multiprocessing differs between Windows / Unix environments. A - Process or its subclasses in Windows must be serializable with pickle, but - that is not possible for AdWordsClient or ReportDownloader. This top-level - function is used as a work-around for Windows support. - - Args: - process_id: The PID of the process downloading the report. - report_download_directory: A string indicating the directory where you - would like to download the reports. - customer_id: A str AdWords customer ID for which the report is being - downloaded. - report_definition: A dict containing the report definition to be used. - - Returns: - A tuple indicating a boolean success/failure status, and dict request - context. - """ - report_downloader = (googleads.adwords.AdWordsClient.LoadFromStorage() - .GetReportDownloader()) - - filepath = os.path.join(report_download_directory, - 'adgroup_%d.csv' % customer_id) - retry_count = 0 - - while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (process_id, retry_count, customer_id, filepath)) - try: - with open(filepath, 'wb') as handler: - report_downloader.DownloadReport( - report_definition, output=handler, - client_customer_id=customer_id) - return (True, {'customerId': customer_id}) - except googleads.errors.AdWordsReportError as e: - if e.code == 500 and retry_count < MAX_RETRIES: - time.sleep(retry_count * BACKOFF_FACTOR) - else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) - return (False, {'customerId': customer_id, 'code': e.code, - 'message': e.message}) - - -class ReportWorker(multiprocessing.Process): - """A worker Process used to download reports for a set of customer IDs.""" - - def __init__(self, report_download_directory, report_definition, - input_queue, success_queue, failure_queue): - """Initializes a ReportWorker. - - Args: - report_download_directory: A string indicating the directory where you - would like to download the reports. - report_definition: A dict containing the report definition that you would - like to run against all customer IDs in the input_queue. - input_queue: A Queue instance containing all of the customer IDs that - the report_definition will be run against. - success_queue: A Queue instance that the details of successful report - downloads will be saved to. - failure_queue: A Queue instance that the details of failed report - downloads will be saved to. - """ - super(ReportWorker, self).__init__() - self.report_download_directory = report_download_directory - self.report_definition = report_definition - self.input_queue = input_queue - self.success_queue = success_queue - self.failure_queue = failure_queue - - def run(self): - while True: - try: - customer_id = self.input_queue.get(timeout=0.01) - except Empty: - break - result = _DownloadReport(self.ident, self.report_download_directory, - customer_id, self.report_definition) - (self.success_queue if result[0] else self.failure_queue).put(result[1]) - - -def GetCustomerIDs(client): - """Retrieves all CustomerIds in the account hierarchy. - - Note that your configuration file must specify a client_customer_id belonging - to an AdWords manager account. - - Args: - client: an AdWordsClient instance. - Raises: - Exception: if no CustomerIds could be found. - Returns: - A Queue instance containing all CustomerIds in the account hierarchy. - """ - # For this example, we will use ManagedCustomerService to get all IDs in - # hierarchy that do not belong to MCC accounts. - managed_customer_service = client.GetService('ManagedCustomerService', - version='v201806') - - offset = 0 - - # Get the account hierarchy for this account. - selector = { - 'fields': ['CustomerId'], - 'predicates': [{ - 'field': 'CanManageClients', - 'operator': 'EQUALS', - 'values': [False] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - - # Using Queue to balance load between processes. - queue = multiprocessing.Queue() - more_pages = True - - while more_pages: - page = managed_customer_service.get(selector) - - if page and 'entries' in page and page['entries']: - for entry in page['entries']: - queue.put(entry['customerId']) - else: - raise Exception('Can\'t retrieve any customer ID.') - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - return queue - - -def main(client, report_download_directory): - # Determine list of customer IDs to retrieve report for. - input_queue = GetCustomerIDs(client) - reports_succeeded = multiprocessing.Queue() - reports_failed = multiprocessing.Queue() - - # Create report definition. - report_definition = { - 'reportName': 'Custom ADGROUP_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'ADGROUP_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Impressions', 'Clicks', - 'Cost'], - # Predicates are optional. - 'predicates': { - 'field': 'AdGroupStatus', - 'operator': 'IN', - 'values': ['ENABLED', 'PAUSED'] - } - }, - } - - queue_size = input_queue.qsize() - num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) - - # Start all the processes. - processes = [ReportWorker(report_download_directory, - report_definition, input_queue, reports_succeeded, - reports_failed) - for _ in range(num_processes)] - - for process in processes: - process.start() - - for process in processes: - process.join() - - print 'Finished downloading reports with the following results:' - while True: - try: - success = reports_succeeded.get(timeout=0.01) - except Empty: - break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] - - while True: - try: - failure = reports_failed.get(timeout=0.01) - except Empty: - break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) - - -if __name__ == '__main__': - adwords_client = googleads.adwords.AdWordsClient.LoadFromStorage() - main(adwords_client, REPORT_DOWNLOAD_DIRECTORY) diff --git a/examples/adwords/v201806/shopping/__init__.py b/examples/adwords/v201806/shopping/__init__.py deleted file mode 100644 index be510830..00000000 --- a/examples/adwords/v201806/shopping/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Shopping examples.""" diff --git a/examples/adwords/v201806/shopping/add_product_partition_tree.py b/examples/adwords/v201806/shopping/add_product_partition_tree.py deleted file mode 100755 index 918bbce1..00000000 --- a/examples/adwords/v201806/shopping/add_product_partition_tree.py +++ /dev/null @@ -1,279 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a ProductPartition tree. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -ADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, adgroup_id): - """Runs the example.""" - adgroup_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201806') - - helper = ProductPartitionHelper(adgroup_id) - - # The most trivial partition tree has only a unit node as the root, e.g.: - # helper.CreateUnit(bid_amount=100000) - - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition, 200000) - helper.CreateUnit(root, used_product_canonical_condition, 100000) - other_condition = helper.CreateSubdivision( - root, other_product_canonical_condition) - - cool_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CoolBrand' - } - - cheap_product_brand = { - 'xsi_type': 'ProductBrand', - 'value': 'CheapBrand' - } - - other_product_brand = { - 'xsi_type': 'ProductBrand', - } - - helper.CreateUnit(other_condition, cool_product_brand, 900000) - helper.CreateUnit(other_condition, cheap_product_brand, 10000) - other_brand = helper.CreateSubdivision(other_condition, other_product_brand) - - # The value for the bidding category is a fixed ID for the 'Luggage & Bags' - # category. You can retrieve IDs for categories from the ConstantDataService. - # See the 'GetProductTaxonomy' example for more details. - luggage_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - - generic_category = { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - } - - helper.CreateUnit(other_brand, luggage_category, 750000) - helper.CreateUnit(other_brand, generic_category, 110000) - - # Make the mutate request - result = adgroup_criterion_service.mutate(helper.GetOperations()) - - children = {} - - root_node = None - - # For each criterion, make an array containing each of its children. - # We always create the parent before the child, so we can rely on that here. - for adgroup_criterion in result['value']: - children[adgroup_criterion['criterion']['id']] = [] - - if 'parentCriterionId' in adgroup_criterion['criterion']: - children[adgroup_criterion['criterion']['parentCriterionId']].append( - adgroup_criterion['criterion']) - else: - root_node = adgroup_criterion['criterion'] - - # Show the tree - DisplayTree(root_node, children) - - -def DisplayTree(node, children, level=0): - """Recursively display a node and each of its children. - - Args: - node: The node we're displaying the children of. - children: Children of the parent node. - level: How deep in the tree we are. - """ - value = '' - node_type = '' - - if 'caseValue' in node: - case_value = node['caseValue'] - node_type = case_value['ProductDimension.Type'] - - if node_type == 'ProductCanonicalCondition': - value = (case_value['condition'] if 'condition' in case_value - else 'OTHER') - elif node_type == 'ProductBiddingCategory': - value = '%s(%s)' % (case_value['type'], case_value['value'] - if 'value' in case_value else 'OTHER') - else: - value = (case_value['value'] if 'value' in case_value else 'OTHER') - - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) - - for child_node in children[node['id']]: - DisplayTree(child_node, children, level + 1) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, ADGROUP_ID) diff --git a/examples/adwords/v201806/shopping/add_product_scope.py b/examples/adwords/v201806/shopping/add_product_scope.py deleted file mode 100755 index 17da9cdc..00000000 --- a/examples/adwords/v201806/shopping/add_product_scope.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Restricts products that will be included in a campaign with a ProductScope. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' - - -def main(client, campaign_id): - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201806') - - product_scope = { - 'xsi_type': 'ProductScope', - # This set of dimensions is for demonstration purposes only. It would be - # extremely unlikely that you want to include so many dimensions in your - # product scope. - 'dimensions': [ - { - 'xsi_type': 'ProductBrand', - 'value': 'Nexus' - }, - { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - }, - { - 'xsi_type': 'ProductCustomAttribute', - 'type': 'CUSTOM_ATTRIBUTE_0', - 'value': 'my attribute value' - }, - { - 'xsi_type': 'ProductOfferId', - 'value': 'book1' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L1', - 'value': 'Media' - }, - { - 'xsi_type': 'ProductType', - 'type': 'PRODUCT_TYPE_L2', - 'value': 'Books' - }, - # The value for the bidding category is a fixed ID for the "Luggage - # & Bags" category. You can retrieve IDs for categories from the - # ConstantDataService. See the "GetProductCategoryTaxonomy" example - # for more details. - { - 'xsi_type': 'ProductBiddingCategory', - 'type': 'BIDDING_CATEGORY_L1', - 'value': '-5914235892932915235' - } - ] - } - - campaign_criterion = { - 'campaignId': campaign_id, - 'criterion': product_scope - } - - operations = [{ - 'operator': 'ADD', - 'operand': campaign_criterion - }] - - # Make the request - result = campaign_criterion_service.mutate(operations) - - for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID) diff --git a/examples/adwords/v201806/shopping/add_shopping_campaign.py b/examples/adwords/v201806/shopping/add_shopping_campaign.py deleted file mode 100755 index 602e5e5f..00000000 --- a/examples/adwords/v201806/shopping/add_shopping_campaign.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds a Shopping campaign. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import adwords - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -# If set to true, a default partition will be created. If running the -# add_product_partition_tree.py example right after this example, make -# sure this stays set to false. -CREATE_DEFAULT_PARTITION = False -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' - - -def main(client, budget_id, merchant_id, create_default_partition): - campaign_service = client.GetService('CampaignService', version='v201806') - ad_group_service = client.GetService('AdGroupService', version='v201806') - ad_group_ad_service = client.GetService('AdGroupAdService', version='v201806') - - # Create campaign - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - result = campaign_service.mutate(campaign_operations) - - for campaign in result['value']: - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - # Create the AdGroup - ad_group = { - 'campaignId': campaign['id'], - 'name': 'AdGroup #%s' % uuid.uuid4() - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': ad_group - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] - ad_group_id = ad_group['id'] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (ad_group['name'], ad_group_id)) - - # Create an AdGroup Ad - adgroup_ad = { - 'adGroupId': ad_group_id, - # Create ProductAd - 'ad': { - 'xsi_type': 'ProductAd', - 'Ad.Type': 'ProductAd' - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': adgroup_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - ad_result = ad_group_ad_service.mutate([ad_operation]) - - for adgroup_ad in ad_result['value']: - print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - - if create_default_partition: - CreateDefaultPartition(client, ad_group_id) - - -def CreateDefaultPartition(client, ad_group_id): - """Creates a default partition. - - Args: - client: an AdWordsClient instance. - ad_group_id: an integer ID for an ad group. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - version='v201806') - - operations = [{ - 'operator': 'ADD', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - # Make sure that caseValue and parentCriterionId are left unspecified. - # This makes this partition as generic as possible to use as a - # fallback when others don't match. - 'criterion': { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - }, - 'biddingStrategyConfiguration': { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 500000 - } - }] - } - } - }] - - ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] - - print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' - % (ad_group_criterion['criterion']['id'], - ad_group_criterion['adGroupId'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, CREATE_DEFAULT_PARTITION) diff --git a/examples/adwords/v201806/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201806/shopping/add_shopping_campaign_for_showcase_ads.py deleted file mode 100755 index 52aaaeb8..00000000 --- a/examples/adwords/v201806/shopping/add_shopping_campaign_for_showcase_ads.py +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds a Shopping campaign for Showcase ads. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import uuid - -from googleads import adwords -from googleads import errors - - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' -COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - # Note: Showcase ads require that the campaign has a ManualCpc - # BiddingStrategyConfiguration. - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, budget_id, merchant_id, expanded_image_filepath, - collapsed_image_filepath): - try: - # Create the Shopping Campaign - campaign = CreateShoppingCampaign(client, budget_id, merchant_id) - - # Create the AdGroup - adgroup = CreateAdGroup(client, campaign['id']) - - # Create a Showcase Ad - CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath) - - product_partition_tree = CreateProductPartition(client, adgroup['id']) - print 'Final tree:\n%s' % product_partition_tree - except errors.GoogleAdsServerFault: - print 'Failed to create shopping campaign for showcase ads.' - raise - - -def CreateShoppingCampaign(client, budget_id, merchant_id): - """Creates a shopping campaign with the given budget and merchant IDs. - - Args: - client: an AdWordsClient instance. - budget_id: the str ID of the budget to be associated with the shopping - campaign. - merchant_id: the str ID of the merchant account to be associated with the - shopping campaign. - - Returns: - The created Shopping Campaign as a sudsobject. - """ - campaign_service = client.GetService('CampaignService', 'v201806') - - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - return campaign - - -def CreateAdGroup(client, campaign_id): - """Creates an AdGroup for the given shopping campaign ID. - - Args: - client: an AdWordsClient instance. - campaign_id: the str ID of a shopping campaign. - - Returns: - The created AdGroup as a sudsobject. - """ - ad_group_service = client.GetService('AdGroupService', 'v201806') - - adgroup = { - # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS - 'adGroupType': 'SHOPPING_SHOWCASE_ADS', - 'campaignId': campaign_id, - 'name': 'AdGroup #%s' % uuid.uuid4(), - # REQUIRED: Set the ad group's bidding strategy configuration. - 'biddingStrategyConfiguration': { - # Showcase ads require either ManualCpc or EnhancedCpc. - 'biddingStrategyType': 'MANUAL_CPC', - # Optional: Set the bids - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 100000 - } - }] - } - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] - - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - return adgroup - - -def CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath): - """Creates a showcase add for the given AdGroup with the given images. - - Args: - client: an AdWordsClient instance. - adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. - expanded_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's expandedImage. - collapsed_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's collapsedImage. - - Returns: - The created Showcase Ad as a sudsobject. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201806') - - showcase_ad = { - 'adGroupId': adgroup['id'], - 'ad': { - 'xsi_type': 'ShowcaseAd', - 'Ad.Type': 'ShowcaseAd', - # Required: set the ad's name, final URLs, and display URL. - 'name': 'Showcase ad #%s' % uuid.uuid4(), - 'finalUrls': 'http://example.com/showcase', - 'displayUrl': 'example.com', - # Required: Set the ad's expanded image. - 'expandedImage': { - 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] - }, - # Optional: Set the collapsed image. - 'collapsedImage': { - 'mediaId': - UploadImage(client, collapsed_image_filepath)['mediaId'] - } - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': showcase_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] - - print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] - - return showcase_ad - - -def UploadImage(client, filepath): - """Uploads a .jpg image with the given filepath via the AdWords MediaService. - - Args: - client: an AdWordsClient instance. - filepath: a str filepath to the .jpg file to be uploaded. - - Returns: - The created Image as a sudsobject. - """ - media_service = client.GetService('MediaService', 'v201806') - - with open(filepath, 'rb') as image_handle: - image_data = image_handle.read().decode('utf-8') - - image = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - - image = media_service.upload(image)[0] - - return image - - -def CreateProductPartition(client, adgroup_id): - """Creates a ProductPartition tree for the given AdGroup ID. - - Args: - client: an AdWordsClient instance. - adgroup_id: a str AdGroup ID. - - Returns: - The ProductPartition tree as a sudsobject. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - 'v201806') - helper = ProductPartitionHelper(adgroup_id) - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition) - helper.CreateUnit(root, used_product_canonical_condition) - helper.CreateUnit(root, other_product_canonical_condition) - - result = ad_group_criterion_service.mutate(helper.operations) - return result['value'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, - COLLAPSED_IMAGE_FILEPATH) diff --git a/examples/adwords/v201806/shopping/get_product_category_taxonomy.py b/examples/adwords/v201806/shopping/get_product_category_taxonomy.py deleted file mode 100755 index 1f456086..00000000 --- a/examples/adwords/v201806/shopping/get_product_category_taxonomy.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fetches the set of valid ProductBiddingCategories. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import adwords - - -def main(client): - service = client.GetService('ConstantDataService', version='v201806') - - selector = { - 'predicates': [ - { - 'field': 'Country', - 'operator': 'IN', - 'values': ['US'] - } - ] - } - - result = service.getProductBiddingCategoryData(selector) - - bidding_categories = {} - root_categories = [] - - for product_bidding_category in result: - category_id = product_bidding_category['dimensionValue']['value'] - parent_id = None - name = product_bidding_category['displayValue'][0]['value'] - - # Note: There may be cases where there isn't a value. - if ('parentDimensionValue' in product_bidding_category and - 'value' in product_bidding_category['parentDimensionValue']): - parent_id = product_bidding_category['parentDimensionValue']['value'] - - if category_id not in bidding_categories: - bidding_categories[category_id] = {} - - category = bidding_categories[category_id] - - if parent_id is not None: - if parent_id not in bidding_categories: - bidding_categories[parent_id] = {} - - parent = bidding_categories[parent_id] - - if 'children' not in parent: - parent['children'] = [] - - parent['children'].append(category) - else: - root_categories.append(category) - - category['id'] = category_id - category['name'] = name - - DisplayCategories(root_categories) - - -def DisplayCategories(categories, prefix=''): - for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) - - if 'children' in category: - DisplayCategories(category['children'], '%s%s > ' % (prefix, - category['name'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/targeting/__init__.py b/examples/adwords/v201806/targeting/__init__.py deleted file mode 100644 index f5595299..00000000 --- a/examples/adwords/v201806/targeting/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2016 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. - -"""Targeting examples.""" diff --git a/examples/adwords/v201806/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201806/targeting/add_campaign_targeting_criteria.py deleted file mode 100755 index 969b36ff..00000000 --- a/examples/adwords/v201806/targeting/add_campaign_targeting_criteria.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds various types of targeting criteria to a given campaign. - -To get campaigns, run get_campaigns.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE' -# Replace the value below with the ID of a feed that has been configured for -# location targeting, meaning it has an ENABLED FeedMapping with criterionType -# of 77. Feeds linked to a GMB account automatically have this FeedMapping. -# If you don't have such a feed, set this value to None. -LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE' - - -def main(client, campaign_id, location_feed_id=None): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201806') - - # Create locations. The IDs can be found in the documentation or retrieved - # with the LocationCriterionService. - california = { - 'xsi_type': 'Location', - 'id': '21137' - } - mexico = { - 'xsi_type': 'Location', - 'id': '2484' - } - - # Create languages. The IDs can be found in the documentation or retrieved - # with the ConstantDataService. - english = { - 'xsi_type': 'Language', - 'id': '1000' - } - spanish = { - 'xsi_type': 'Language', - 'id': '1003' - } - - # Create a negative campaign criterion operation. - negative_campaign_criterion_operand = { - 'xsi_type': 'NegativeCampaignCriterion', - 'campaignId': campaign_id, - 'criterion': { - 'xsi_type': 'Keyword', - 'matchType': 'BROAD', - 'text': 'jupiter cruise' - } - } - criteria = [california, mexico, english, spanish] - if location_feed_id: - # Distance targeting. Area of 10 miles around targets above. - criteria.append({ - 'xsi_type': 'LocationGroups', - 'feedId': location_feed_id, - 'matchingFunction': { - 'operator': 'IDENTITY', - 'lhsOperand': [{ - 'xsi_type': 'LocationExtensionOperand', - 'radius': { - 'xsi_type': 'ConstantOperand', - 'type': 'DOUBLE', - 'unit': 'MILES', - 'doubleValue': 10 - } - }] - } - }) - # Create operations - operations = [] - for criterion in criteria: - operations.append({ - 'operator': 'ADD', - 'operand': { - 'campaignId': campaign_id, - 'criterion': criterion - } - }) - # Add the negative campaign criterion. - operations.append({ - 'operator': 'ADD', - 'operand': negative_campaign_criterion_operand - }) - - # Make the mutate request. - result = campaign_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s", criterion id "%s", ' - 'and type "%s" was added.' - % (campaign_criterion['campaignId'], - campaign_criterion['criterion']['id'], - campaign_criterion['criterion']['type'])) - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, CAMPAIGN_ID, LOCATION_FEED_ID) diff --git a/examples/adwords/v201806/targeting/add_customer_negative_criteria.py b/examples/adwords/v201806/targeting/add_customer_negative_criteria.py deleted file mode 100755 index b7325473..00000000 --- a/examples/adwords/v201806/targeting/add_customer_negative_criteria.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds various types of negative criteria to a customer. - -These criteria will be applied to all campaigns for the customer. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - customer_negative_criterion_service = client.GetService( - 'CustomerNegativeCriterionService', version='v201806') - - criteria = [ - # Exclude tragedy & conflict content. - { - 'xsi_type': 'ContentLabel', - 'contentLabelType': 'TRAGEDY' - }, - # Exclude a specific placement. - { - 'xsi_type': 'Placement', - 'url': 'http://www.example.com' - } - # Additional criteria types are available for this service. See the types - # listed under Criterion here: - # https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion - ] - - # Create operations to add each of the criteria above. - operations = [{ - 'operator': 'ADD', - 'operand': { - 'criterion': criterion - } - } for criterion in criteria] - - # Make the mutate request. - result = customer_negative_criterion_service.mutate(operations) - - # Display the resulting campaign criteria. - for negative_criterion in result['value']: - print ('Customer negative criterion with criterion ID "%s", and type "%s" ' - 'was added.' % (negative_criterion['criterion']['id'], - negative_criterion['criterion']['type'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201806/targeting/add_demographic_targeting_criteria.py deleted file mode 100755 index 64da5eab..00000000 --- a/examples/adwords/v201806/targeting/add_demographic_targeting_criteria.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 adds demographic criteria to an ad group. - -To get a list of ad groups, run get_ad_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -GENDER_MALE = '10' -AGE_RANGE_UNDETERMINED = '503999' - -AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' - - -def main(client, ad_group_id): - # Initialize appropriate service. - ad_group_criterion_service = client.GetService( - 'AdGroupCriterionService', version='v201806') - - # Create the ad group criteria. - ad_group_criteria = [ - # Targeting criterion. - { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'Gender', - # Create gender criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/genders. - 'id': GENDER_MALE - } - }, - # Exclusion criterion. - { - 'xsi_type': 'NegativeAdGroupCriterion', - 'adGroupId': ad_group_id, - 'criterion': { - 'xsi_type': 'AgeRange', - # Create age range criteria. The IDs can be found in the - # documentation: - # https://developers.google.com/adwords/api/docs/appendix/ages. - 'id': AGE_RANGE_UNDETERMINED - } - } - ] - - # Create operations. - operations = [] - for criterion in ad_group_criteria: - operations.append({ - 'operator': 'ADD', - 'operand': criterion - }) - - response = ad_group_criterion_service.mutate(operations) - - if response and response['value']: - criteria = response['value'] - for ad_group_criterion in criteria: - criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type "%s" was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) - else: - print 'No criteria were returned.' - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, AD_GROUP_ID) diff --git a/examples/adwords/v201806/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201806/targeting/get_campaign_targeting_criteria.py deleted file mode 100755 index 85cbc6d3..00000000 --- a/examples/adwords/v201806/targeting/get_campaign_targeting_criteria.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 illustrates how to retrieve all the campaign targets. - -To set campaign targets, run add_campaign_targeting_criteria.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -PAGE_SIZE = 500 - - -def main(client): - # Initialize appropriate service. - campaign_criterion_service = client.GetService( - 'CampaignCriterionService', version='v201806') - - # Construct selector and get all campaign targets. - offset = 0 - selector = { - 'fields': ['CampaignId', 'Id', 'CriteriaType', 'PlatformName', - 'LanguageName', 'LocationName', 'KeywordText'], - 'predicates': [{ - 'field': 'CriteriaType', - 'operator': 'IN', - 'values': ['KEYWORD', 'LANGUAGE', 'LOCATION', 'PLATFORM'] - }], - 'paging': { - 'startIndex': str(offset), - 'numberResults': str(PAGE_SIZE) - } - } - more_pages = True - while more_pages: - page = campaign_criterion_service.get(selector) - - # Display results. - if 'entries' in page: - for campaign_criterion in page['entries']: - negative = '' - if (campaign_criterion['CampaignCriterion.Type'] - == 'NegativeCampaignCriterion'): - negative = 'Negative ' - criterion = campaign_criterion['criterion'] - criteria = (criterion['text'] if 'text' in criterion else - criterion['platformName'] if 'platformName' in criterion - else criterion['name'] if 'name' in criterion else - criterion['locationName'] if 'locationName' in criterion - else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) - else: - print 'No campaign targets were found.' - offset += PAGE_SIZE - selector['paging']['startIndex'] = str(offset) - more_pages = offset < int(page['totalNumEntries']) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201806/targeting/get_targetable_languages_and_carriers.py deleted file mode 100755 index 6d626eaa..00000000 --- a/examples/adwords/v201806/targeting/get_targetable_languages_and_carriers.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 all languages and carriers available for targeting. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def main(client): - # Initialize appropriate service. - constant_data_service = client.GetService( - 'ConstantDataService', version='v201806') - - # Get all languages. - languages = constant_data_service.getLanguageCriterion() - - # Display results. - for language in languages: - print ('Language with name "%s" and ID "%s" was found.' - % (language['name'], language['id'])) - - # Get all carriers. - carriers = constant_data_service.getCarrierCriterion() - - # Display results. - for carrier in carriers: - print ('Carrier with name "%s", ID "%s", and country code "%s" was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/examples/adwords/v201806/targeting/lookup_location.py b/examples/adwords/v201806/targeting/lookup_location.py deleted file mode 100755 index 38a1fa31..00000000 --- a/examples/adwords/v201806/targeting/lookup_location.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 LocationCriterion. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - -from googleads import adwords - - -def GetLocationString(location): - return '%s (%s)' % (location['locationName'], location['displayType'] - if 'displayType' in location else None) - - -def main(client): - # Initialize appropriate service. - location_criterion_service = client.GetService( - 'LocationCriterionService', version='v201806') - - location_names = ['Paris', 'Quebec', 'Spain', 'Deutschland'] - - # Create the selector. - selector = { - 'fields': ['Id', 'LocationName', 'DisplayType', 'CanonicalName', - 'ParentLocations', 'Reach', 'TargetingStatus'], - 'predicates': [{ - 'field': 'LocationName', - 'operator': 'IN', - 'values': location_names - }, { - 'field': 'Locale', - 'operator': 'EQUALS', - 'values': ['en'] - }] - } - - # Make the get request. - location_criteria = location_criterion_service.get(selector) - - # Display the resulting location criteria. - for location_criterion in location_criteria: - parent_string = '' - if ('parentLocations' in location_criterion['location'] - and location_criterion['location']['parentLocations']): - parent_string = ', '.join([GetLocationString(parent)for parent in - location_criterion['location'] - ['parentLocations']]) - print ('The search term "%s" returned the location "%s" of type "%s"' - ' with parent locations "%s", reach "%s" and id "%s" (%s)' - % (location_criterion['searchTerm'], - location_criterion['location']['locationName'], - location_criterion['location']['displayType'], parent_string, - location_criterion['reach'] - if 'reach' in location_criterion else None, - location_criterion['location']['id'], - location_criterion['location']['targetingStatus'])) - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client) diff --git a/googleads/adwords.py b/googleads/adwords.py index b1173e58..04df0daf 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -42,62 +42,6 @@ # A giant dictionary of AdWords versions, the services they support, and which # namespace those services are in. _SERVICE_MAP = { - 'v201806': { - 'AccountLabelService': 'mcm', - 'AdCustomizerFeedService': 'cm', - 'AdGroupAdService': 'cm', - 'AdGroupBidModifierService': 'cm', - 'AdGroupCriterionService': 'cm', - 'AdGroupExtensionSettingService': 'cm', - 'AdGroupFeedService': 'cm', - 'AdGroupService': 'cm', - 'AdParamService': 'cm', - 'AdService': 'cm', - 'AdwordsUserListService': 'rm', - 'AssetService': 'cm', - 'BatchJobService': 'cm', - 'BiddingStrategyService': 'cm', - 'BudgetOrderService': 'billing', - 'BudgetService': 'cm', - 'CampaignBidModifierService': 'cm', - 'CampaignCriterionService': 'cm', - 'CampaignExtensionSettingService': 'cm', - 'CampaignFeedService': 'cm', - 'CampaignGroupPerformanceTargetService': 'cm', - 'CampaignGroupService': 'cm', - 'CampaignService': 'cm', - 'CampaignSharedSetService': 'cm', - 'ConstantDataService': 'cm', - 'ConversionTrackerService': 'cm', - 'CustomAffinityService': 'rm', - 'CustomerExtensionSettingService': 'cm', - 'CustomerFeedService': 'cm', - 'CustomerNegativeCriterionService': 'cm', - 'CustomerService': 'mcm', - 'CustomerSyncService': 'ch', - 'DataService': 'cm', - 'DraftAsyncErrorService': 'cm', - 'DraftService': 'cm', - 'FeedItemService': 'cm', - 'FeedItemTargetService': 'cm', - 'FeedMappingService': 'cm', - 'FeedService': 'cm', - 'LabelService': 'cm', - 'LocationCriterionService': 'cm', - 'ManagedCustomerService': 'mcm', - 'MediaService': 'cm', - 'OfflineCallConversionFeedService': 'cm', - 'OfflineConversionAdjustmentFeedService': 'cm', - 'OfflineConversionFeedService': 'cm', - 'OfflineDataUploadService': 'rm', - 'ReportDefinitionService': 'cm', - 'SharedCriterionService': 'cm', - 'SharedSetService': 'cm', - 'TargetingIdeaService': 'o', - 'TrafficEstimatorService': 'o', - 'TrialAsyncErrorService': 'cm', - 'TrialService': 'cm' - }, 'v201809': { 'AccountLabelService': 'mcm', 'AdCustomizerFeedService': 'cm', diff --git a/googleads/common.py b/googleads/common.py index 1a5380fb..dd0a6a39 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '17.0.0' +VERSION = '18.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' From 188785c7003c03d8b408e48ef891e3a15ec1e1b1 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Thu, 28 Mar 2019 10:33:37 -0400 Subject: [PATCH 134/180] Commiting latest changes. From edb46f6c6b666e1713320a2fd892293d298ec18e Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Wed, 3 Apr 2019 08:39:09 -0400 Subject: [PATCH 135/180] Update comment in get_all_images_and_videos example --- examples/adwords/v201809/misc/get_all_images_and_videos.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/adwords/v201809/misc/get_all_images_and_videos.py b/examples/adwords/v201809/misc/get_all_images_and_videos.py index 3b60d6ed..b8f0b7e4 100755 --- a/examples/adwords/v201809/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201809/misc/get_all_images_and_videos.py @@ -16,8 +16,8 @@ """This example gets all images and videos. -To upload an image, run upload_image.py. To upload video, see: -http://adwords.google.com/support/aw/bin/answer.py?hl=en&answer=39454. +To upload an image, run upload_image.py. Use the Google Ads website to upload +new videos. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home From 8faf55a6db11a3a01176a37b759124fc2ad06621 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Thu, 4 Apr 2019 11:52:30 -0400 Subject: [PATCH 136/180] Releasing v18.1.0 --- ChangeLog | 4 ++++ googleads/common.py | 2 +- setup.py | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index bf97eea4..5450352a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +18.1.0 -- 04/03/2018 +* Upgrade PyYAML to 5.1 >= 6.0 +* Update comment in get_all_images_and_videos examples + 18.0.0 -- 03/28/2019 * Removed support for AdWords v201806 diff --git a/googleads/common.py b/googleads/common.py index dd0a6a39..7ef683e9 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '18.0.0' +VERSION = '18.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/setup.py b/setup.py index e0a26b55..2b557fcd 100755 --- a/setup.py +++ b/setup.py @@ -26,7 +26,7 @@ DEPENDENCIES = ['google-auth>=1.0.0,<2.0.0', 'google-auth-oauthlib>=0.0.1,<1.0.0', 'pytz>=2015.7', - 'PyYAML>=4.2b1, <5.0', 'requests>=2.0.0,<3.0.0', + 'PyYAML>=5.1, <6.0', 'requests>=2.0.0,<3.0.0', 'suds-jurko>=0.6,<0.7', 'xmltodict>=0.9.2,<1.0.0', 'zeep>=2.5.0'] From aa3b1b474b0f9789ca55ca46f4b2b57aeae38874 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Thu, 4 Apr 2019 11:54:16 -0400 Subject: [PATCH 137/180] Commiting latest changes. From 6e3edd5fd8e8e90f8533182069017295a9823843 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 16 May 2019 14:34:50 -0400 Subject: [PATCH 138/180] Releasing v19.0.0 --- ChangeLog | 5 + .../activity_group_service/__init__.py | 15 ++ .../create_activity_groups.py | 71 +++++ .../get_active_activity_groups.py | 52 ++++ .../get_all_activity_groups.py | 51 ++++ .../update_activity_groups.py | 70 +++++ .../v201905/activity_service/__init__.py | 15 ++ .../activity_service/create_activities.py | 68 +++++ .../activity_service/get_active_activities.py | 51 ++++ .../activity_service/get_all_activities.py | 50 ++++ .../activity_service/update_activities.py | 68 +++++ .../create_traffic_adjustments.py | 143 ++++++++++ .../get_all_traffic_adjustments.py | 53 ++++ .../update_traffic_adjustments.py | 88 ++++++ .../audience_segment_service/__init__.py | 15 ++ .../create_audience_segments.py | 96 +++++++ .../get_all_audience_segments.py | 52 ++++ .../get_first_party_audience_segments.py | 53 ++++ .../populate_first_party_audience_segments.py | 71 +++++ .../update_audience_segments.py | 68 +++++ .../v201905/base_rate_service/__init__.py | 15 ++ .../create_product_base_rates.py | 65 +++++ .../create_product_package_item_base_rates.py | 66 +++++ .../create_product_template_base_rates.py | 65 +++++ .../base_rate_service/get_all_base_rates.py | 52 ++++ .../get_base_rates_for_rate_card.py | 55 ++++ .../base_rate_service/update_base_rates.py | 77 ++++++ .../cdn_configuration_service/__init__.py | 15 ++ .../create_cdn_configurations.py | 89 +++++++ .../get_all_cdn_configurations.py | 54 ++++ .../get_all_cms_metadata_keys.py | 52 ++++ .../get_all_cms_metadata_values.py | 55 ++++ .../get_cms_metadata_values_for_key.py | 60 +++++ .../v201905/company_service/__init__.py | 15 ++ .../company_service/create_companies.py | 62 +++++ .../company_service/get_advertisers.py | 50 ++++ .../company_service/get_all_companies.py | 49 ++++ .../company_service/update_companies.py | 70 +++++ .../v201905/contact_service/__init__.py | 15 ++ .../contact_service/create_contacts.py | 71 +++++ .../contact_service/get_all_contacts.py | 49 ++++ .../contact_service/get_uninvited_contacts.py | 50 ++++ .../contact_service/update_contacts.py | 71 +++++ .../__init__.py | 15 ++ ...create_content_metadata_key_hierarchies.py | 79 ++++++ ...et_all_content_metadata_key_hierarchies.py | 55 ++++ ...update_content_metadata_key_hierarchies.py | 94 +++++++ .../v201905/content_service/__init__.py | 15 ++ .../content_service/get_all_content.py | 49 ++++ .../v201905/creative_service/__init__.py | 15 ++ .../creative_service/copy_image_creatives.py | 60 +++++ .../create_creative_from_template.py | 111 ++++++++ .../creative_service/create_creatives.py | 90 +++++++ .../create_custom_creative.py | 88 ++++++ .../create_native_creative.py | 132 +++++++++ .../creative_service/get_all_creatives.py | 49 ++++ .../creative_service/get_image_creatives.py | 50 ++++ .../creative_service/update_creatives.py | 71 +++++ .../v201905/creative_set_service/__init__.py | 15 ++ .../associate_creative_set_to_line_item.py | 55 ++++ .../create_creative_set.py | 61 +++++ .../get_all_creative_sets.py | 51 ++++ .../get_creative_sets_for_master_creative.py | 54 ++++ .../update_creative_set.py | 73 +++++ .../creative_template_service/__init__.py | 15 ++ .../get_all_creative_templates.py | 51 ++++ .../get_system_defined_creative_templates.py | 52 ++++ .../create_creative_wrappers.py | 63 +++++ .../deactivate_creative_wrapper.py | 78 ++++++ .../get_active_creative_wrappers.py | 52 ++++ .../get_all_creative_wrappers.py | 51 ++++ .../update_creative_wrappers.py | 73 +++++ .../v201905/custom_field_service/__init__.py | 15 ++ .../create_custom_field_options.py | 67 +++++ .../create_custom_fields.py | 66 +++++ .../deactivate_all_line_item_custom_fields.py | 73 +++++ .../get_all_custom_fields.py | 51 ++++ .../get_custom_fields_for_line_items.py | 52 ++++ .../set_line_item_custom_field_value.py | 139 ++++++++++ .../update_custom_fields.py | 70 +++++ .../custom_targeting_service/__init__.py | 15 ++ ...create_custom_targeting_keys_and_values.py | 132 +++++++++ .../delete_custom_targeting_keys.py | 77 ++++++ .../delete_custom_targeting_values.py | 77 ++++++ ...et_all_custom_targeting_keys_and_values.py | 72 +++++ ...efined_custom_targeting_keys_and_values.py | 74 ++++++ .../update_custom_targeting_keys.py | 67 +++++ .../update_custom_targeting_values.py | 71 +++++ .../v201905/exchange_rate_service/__init__.py | 15 ++ .../create_exchange_rates.py | 58 ++++ .../get_all_exchange_rates.py | 54 ++++ .../get_exchange_rates_for_currency_code.py | 56 ++++ .../update_exchange_rates.py | 71 +++++ .../get_availability_forecast.py | 251 ++++++++++++++++++ ...get_availability_forecast_for_line_item.py | 66 +++++ .../get_delivery_forecast_for_line_items.py | 52 ++++ .../v201905/inventory_service/__init__.py | 15 ++ .../inventory_service/archive_ad_units.py | 75 ++++++ .../inventory_service/create_ad_units.py | 70 +++++ .../get_ad_unit_hierarchy.py | 115 ++++++++ .../get_all_ad_unit_sizes.py | 46 ++++ .../inventory_service/get_all_ad_units.py | 49 ++++ .../get_top_level_ad_units.py | 58 ++++ .../inventory_service/update_ad_units.py | 82 ++++++ .../v201905/label_service/__init__.py | 15 ++ .../v201905/label_service/create_labels.py | 55 ++++ .../label_service/deactivate_labels.py | 65 +++++ .../label_service/get_active_labels.py | 50 ++++ .../v201905/label_service/get_all_labels.py | 49 ++++ .../v201905/label_service/update_labels.py | 63 +++++ .../__init__.py | 15 ++ .../create_licas.py | 57 ++++ .../deactivate_licas.py | 73 +++++ .../get_all_licas.py | 57 ++++ .../get_licas_for_line_item.py | 60 +++++ .../update_licas.py | 66 +++++ .../v201905/line_item_service/__init__.py | 15 ++ .../line_item_service/activate_line_items.py | 75 ++++++ .../line_item_service/create_line_items.py | 166 ++++++++++++ .../create_video_line_item.py | 134 ++++++++++ .../line_item_service/get_all_line_items.py | 50 ++++ .../get_line_items_that_need_creatives.py | 51 ++++ .../get_recently_updated_line_items.py | 59 ++++ .../line_item_service/pause_line_items.py | 74 ++++++ .../target_custom_criteria.py | 110 ++++++++ .../line_item_service/update_line_items.py | 74 ++++++ .../activate_live_stream_events.py | 71 +++++ .../create_live_stream_events.py | 68 +++++ .../get_all_live_stream_events.py | 52 ++++ .../register_sessions_for_monitoring.py | 45 ++++ .../update_live_stream_events.py | 69 +++++ .../v201905/native_style_service/__init__.py | 15 ++ .../create_native_styles.py | 178 +++++++++++++ .../get_all_native_styles.py | 51 ++++ .../v201905/network_service/__init__.py | 15 ++ .../network_service/get_all_networks.py | 40 +++ .../network_service/get_current_network.py | 37 +++ .../network_service/make_test_network.py | 53 ++++ .../v201905/order_service/__init__.py | 15 ++ .../v201905/order_service/approve_orders.py | 67 +++++ .../v201905/order_service/create_orders.py | 59 ++++ .../v201905/order_service/get_all_orders.py | 49 ++++ .../order_service/get_orders_starting_soon.py | 60 +++++ .../v201905/order_service/update_orders.py | 71 +++++ .../package_service/create_packages.py | 61 +++++ ...reate_proposal_line_items_from_packages.py | 68 +++++ .../package_service/get_all_packages.py | 50 ++++ .../get_in_progress_packages.py | 51 ++++ .../placement_service/create_placements.py | 108 ++++++++ .../deactivate_placements.py | 62 +++++ .../get_active_placements.py | 51 ++++ .../placement_service/get_all_placements.py | 50 ++++ .../placement_service/update_placements.py | 58 ++++ .../v201905/premium_rate_service/__init__.py | 15 ++ .../create_premium_rates.py | 84 ++++++ .../get_all_premium_rates.py | 54 ++++ .../get_premium_rates_for_rate_card.py | 56 ++++ .../update_premium_rates.py | 87 ++++++ .../create_product_package_item.py | 62 +++++ .../get_all_product_package_items.py | 53 ++++ ...oduct_package_items_for_product_package.py | 56 ++++ .../create_product_packages.py | 51 ++++ .../get_active_product_packages.py | 52 ++++ .../get_all_product_packages.py | 51 ++++ .../v201905/product_service/__init__.py | 15 ++ .../product_service/get_all_products.py | 49 ++++ .../get_products_for_product_template.py | 53 ++++ .../product_service/update_products.py | 68 +++++ .../product_template_service/__init__.py | 15 ++ .../activate_product_templates.py | 74 ++++++ .../create_product_templates.py | 109 ++++++++ .../create_programmatic_product_templates.py | 91 +++++++ .../get_all_product_templates.py | 51 ++++ .../get_sponsorship_product_templates.py | 52 ++++ .../update_product_templates.py | 94 +++++++ .../proposal_line_item_service/__init__.py | 15 ++ .../archive_proposal_line_items.py | 76 ++++++ ...create_programmatic_proposal_line_items.py | 104 ++++++++ ...sal_line_items_for_non_sales_management.py | 113 ++++++++ .../create_proposal_line_items.py | 105 ++++++++ .../get_all_proposal_line_items.py | 51 ++++ .../get_proposal_line_items_for_proposal.py | 54 ++++ .../update_proposal_line_items.py | 72 +++++ .../v201905/proposal_service/__init__.py | 15 ++ .../create_programmatic_proposals.py | 71 +++++ ...atic_proposals_for_non_sales_management.py | 62 +++++ .../proposal_service/create_proposals.py | 77 ++++++ .../proposal_service/get_all_proposals.py | 49 ++++ .../get_marketplace_comments.py | 56 ++++ .../get_proposals_pending_approval.py | 50 ++++ .../request_buyers_acceptance.py | 67 +++++ .../submit_proposals_for_approval.py | 67 +++++ .../proposal_service/update_proposals.py | 68 +++++ .../__init__.py | 15 ++ .../fetch_match_tables.py | 55 ++++ .../get_all_browsers.py | 55 ++++ .../get_all_programmatic_buyers.py | 49 ++++ .../get_geo_targets.py | 53 ++++ .../get_line_items_named_like.py | 48 ++++ .../get_recent_changes.py | 156 +++++++++++ .../v201905/rate_card_service/__init__.py | 15 ++ .../rate_card_service/create_rate_cards.py | 60 +++++ .../rate_card_service/get_all_rate_cards.py | 51 ++++ .../get_marketplace_rate_cards.py | 54 ++++ ..._item_reports_for_reconciliation_report.py | 75 ++++++ ...update_reconciliation_line_item_reports.py | 67 +++++ ...order_reports_for_reconciliation_report.py | 58 ++++ .../submit_reconciliation_order_reports.py | 71 +++++ ...n_report_rows_for_reconciliation_report.py | 64 +++++ .../update_reconciliation_report_rows.py | 75 ++++++ .../get_all_reconciliation_reports.py | 56 ++++ ...iliation_report_for_last_billing_period.py | 63 +++++ .../v201905/report_service/__init__.py | 15 ++ .../report_service/run_ad_exchange_report.py | 66 +++++ .../report_service/run_delivery_report.py | 88 ++++++ .../report_service/run_inventory_report.py | 82 ++++++ .../report_service/run_reach_report.py | 64 +++++ .../run_report_and_create_match_table.py | 88 ++++++ .../run_report_with_custom_fields.py | 97 +++++++ .../report_service/run_sales_report.py | 64 +++++ .../v201905/report_service/run_saved_query.py | 80 ++++++ .../suggested_ad_unit_service/__init__.py | 15 ++ .../approve_all_suggested_ad_units.py | 70 +++++ .../get_all_suggested_ad_units.py | 52 ++++ ...get_highly_requested_suggested_ad_units.py | 55 ++++ .../targeting_preset_service/__init__.py | 15 ++ .../get_all_targeting_presets.py | 52 ++++ .../v201905/team_service/__init__.py | 15 ++ .../v201905/team_service/create_teams.py | 60 +++++ .../v201905/team_service/get_all_teams.py | 49 ++++ .../v201905/team_service/update_teams.py | 68 +++++ .../v201905/user_service/__init__.py | 15 ++ .../v201905/user_service/create_users.py | 57 ++++ .../v201905/user_service/deactivate_users.py | 65 +++++ .../v201905/user_service/get_all_roles.py | 40 +++ .../v201905/user_service/get_all_users.py | 49 ++++ .../v201905/user_service/get_current_user.py | 39 +++ .../user_service/get_user_by_email_address.py | 52 ++++ .../v201905/user_service/update_users.py | 58 ++++ .../user_team_association_service/__init__.py | 15 ++ .../create_user_team_associations.py | 67 +++++ .../delete_user_team_associations.py | 77 ++++++ .../get_all_user_team_associations.py | 52 ++++ .../get_user_team_associations_for_user.py | 55 ++++ .../update_user_team_associations.py | 78 ++++++ .../workflow_request_service/__init__.py | 15 ++ .../approve_workflow_approval_requests.py | 75 ++++++ .../get_workflow_approval_requests.py | 57 ++++ ...et_workflow_external_condition_requests.py | 57 ++++ ...er_workflow_external_condition_requests.py | 78 ++++++ googleads/ad_manager.py | 46 ++-- googleads/common.py | 2 +- 252 files changed, 15076 insertions(+), 24 deletions(-) create mode 100755 examples/ad_manager/v201905/activity_group_service/__init__.py create mode 100755 examples/ad_manager/v201905/activity_group_service/create_activity_groups.py create mode 100755 examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py create mode 100755 examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py create mode 100755 examples/ad_manager/v201905/activity_group_service/update_activity_groups.py create mode 100755 examples/ad_manager/v201905/activity_service/__init__.py create mode 100755 examples/ad_manager/v201905/activity_service/create_activities.py create mode 100755 examples/ad_manager/v201905/activity_service/get_active_activities.py create mode 100755 examples/ad_manager/v201905/activity_service/get_all_activities.py create mode 100755 examples/ad_manager/v201905/activity_service/update_activities.py create mode 100755 examples/ad_manager/v201905/adjustment_service/create_traffic_adjustments.py create mode 100755 examples/ad_manager/v201905/adjustment_service/get_all_traffic_adjustments.py create mode 100755 examples/ad_manager/v201905/adjustment_service/update_traffic_adjustments.py create mode 100755 examples/ad_manager/v201905/audience_segment_service/__init__.py create mode 100755 examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py create mode 100755 examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py create mode 100755 examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py create mode 100755 examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py create mode 100755 examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py create mode 100755 examples/ad_manager/v201905/base_rate_service/__init__.py create mode 100755 examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py create mode 100755 examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py create mode 100755 examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py create mode 100755 examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py create mode 100755 examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py create mode 100755 examples/ad_manager/v201905/base_rate_service/update_base_rates.py create mode 100755 examples/ad_manager/v201905/cdn_configuration_service/__init__.py create mode 100755 examples/ad_manager/v201905/cdn_configuration_service/create_cdn_configurations.py create mode 100755 examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py create mode 100755 examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_keys.py create mode 100755 examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_values.py create mode 100755 examples/ad_manager/v201905/cms_metadata_service/get_cms_metadata_values_for_key.py create mode 100755 examples/ad_manager/v201905/company_service/__init__.py create mode 100755 examples/ad_manager/v201905/company_service/create_companies.py create mode 100755 examples/ad_manager/v201905/company_service/get_advertisers.py create mode 100755 examples/ad_manager/v201905/company_service/get_all_companies.py create mode 100755 examples/ad_manager/v201905/company_service/update_companies.py create mode 100755 examples/ad_manager/v201905/contact_service/__init__.py create mode 100755 examples/ad_manager/v201905/contact_service/create_contacts.py create mode 100755 examples/ad_manager/v201905/contact_service/get_all_contacts.py create mode 100755 examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py create mode 100755 examples/ad_manager/v201905/contact_service/update_contacts.py create mode 100755 examples/ad_manager/v201905/content_metadata_key_hierarchy_service/__init__.py create mode 100755 examples/ad_manager/v201905/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py create mode 100755 examples/ad_manager/v201905/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py create mode 100755 examples/ad_manager/v201905/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py create mode 100755 examples/ad_manager/v201905/content_service/__init__.py create mode 100755 examples/ad_manager/v201905/content_service/get_all_content.py create mode 100755 examples/ad_manager/v201905/creative_service/__init__.py create mode 100755 examples/ad_manager/v201905/creative_service/copy_image_creatives.py create mode 100755 examples/ad_manager/v201905/creative_service/create_creative_from_template.py create mode 100755 examples/ad_manager/v201905/creative_service/create_creatives.py create mode 100755 examples/ad_manager/v201905/creative_service/create_custom_creative.py create mode 100755 examples/ad_manager/v201905/creative_service/create_native_creative.py create mode 100755 examples/ad_manager/v201905/creative_service/get_all_creatives.py create mode 100755 examples/ad_manager/v201905/creative_service/get_image_creatives.py create mode 100755 examples/ad_manager/v201905/creative_service/update_creatives.py create mode 100755 examples/ad_manager/v201905/creative_set_service/__init__.py create mode 100755 examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py create mode 100755 examples/ad_manager/v201905/creative_set_service/create_creative_set.py create mode 100755 examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py create mode 100755 examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py create mode 100755 examples/ad_manager/v201905/creative_set_service/update_creative_set.py create mode 100755 examples/ad_manager/v201905/creative_template_service/__init__.py create mode 100755 examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py create mode 100755 examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py create mode 100755 examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py create mode 100755 examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py create mode 100755 examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py create mode 100755 examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py create mode 100755 examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py create mode 100755 examples/ad_manager/v201905/custom_field_service/__init__.py create mode 100755 examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py create mode 100755 examples/ad_manager/v201905/custom_field_service/create_custom_fields.py create mode 100755 examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py create mode 100755 examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py create mode 100755 examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py create mode 100755 examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py create mode 100755 examples/ad_manager/v201905/custom_field_service/update_custom_fields.py create mode 100755 examples/ad_manager/v201905/custom_targeting_service/__init__.py create mode 100755 examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py create mode 100755 examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py create mode 100755 examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py create mode 100755 examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py create mode 100755 examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py create mode 100755 examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py create mode 100755 examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py create mode 100755 examples/ad_manager/v201905/exchange_rate_service/__init__.py create mode 100755 examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py create mode 100755 examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py create mode 100755 examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py create mode 100755 examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py create mode 100755 examples/ad_manager/v201905/forecast_service/get_availability_forecast.py create mode 100755 examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py create mode 100755 examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py create mode 100755 examples/ad_manager/v201905/inventory_service/__init__.py create mode 100755 examples/ad_manager/v201905/inventory_service/archive_ad_units.py create mode 100755 examples/ad_manager/v201905/inventory_service/create_ad_units.py create mode 100755 examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py create mode 100755 examples/ad_manager/v201905/inventory_service/get_all_ad_unit_sizes.py create mode 100755 examples/ad_manager/v201905/inventory_service/get_all_ad_units.py create mode 100755 examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py create mode 100755 examples/ad_manager/v201905/inventory_service/update_ad_units.py create mode 100755 examples/ad_manager/v201905/label_service/__init__.py create mode 100755 examples/ad_manager/v201905/label_service/create_labels.py create mode 100755 examples/ad_manager/v201905/label_service/deactivate_labels.py create mode 100755 examples/ad_manager/v201905/label_service/get_active_labels.py create mode 100755 examples/ad_manager/v201905/label_service/get_all_labels.py create mode 100755 examples/ad_manager/v201905/label_service/update_labels.py create mode 100755 examples/ad_manager/v201905/line_item_creative_association_service/__init__.py create mode 100755 examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py create mode 100755 examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py create mode 100755 examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py create mode 100755 examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py create mode 100755 examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py create mode 100755 examples/ad_manager/v201905/line_item_service/__init__.py create mode 100755 examples/ad_manager/v201905/line_item_service/activate_line_items.py create mode 100755 examples/ad_manager/v201905/line_item_service/create_line_items.py create mode 100755 examples/ad_manager/v201905/line_item_service/create_video_line_item.py create mode 100755 examples/ad_manager/v201905/line_item_service/get_all_line_items.py create mode 100755 examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py create mode 100755 examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py create mode 100755 examples/ad_manager/v201905/line_item_service/pause_line_items.py create mode 100755 examples/ad_manager/v201905/line_item_service/target_custom_criteria.py create mode 100755 examples/ad_manager/v201905/line_item_service/update_line_items.py create mode 100755 examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py create mode 100755 examples/ad_manager/v201905/live_stream_event_service/create_live_stream_events.py create mode 100755 examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py create mode 100755 examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py create mode 100755 examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py create mode 100755 examples/ad_manager/v201905/native_style_service/__init__.py create mode 100755 examples/ad_manager/v201905/native_style_service/create_native_styles.py create mode 100755 examples/ad_manager/v201905/native_style_service/get_all_native_styles.py create mode 100755 examples/ad_manager/v201905/network_service/__init__.py create mode 100755 examples/ad_manager/v201905/network_service/get_all_networks.py create mode 100755 examples/ad_manager/v201905/network_service/get_current_network.py create mode 100755 examples/ad_manager/v201905/network_service/make_test_network.py create mode 100755 examples/ad_manager/v201905/order_service/__init__.py create mode 100755 examples/ad_manager/v201905/order_service/approve_orders.py create mode 100755 examples/ad_manager/v201905/order_service/create_orders.py create mode 100755 examples/ad_manager/v201905/order_service/get_all_orders.py create mode 100755 examples/ad_manager/v201905/order_service/get_orders_starting_soon.py create mode 100755 examples/ad_manager/v201905/order_service/update_orders.py create mode 100755 examples/ad_manager/v201905/package_service/create_packages.py create mode 100755 examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py create mode 100755 examples/ad_manager/v201905/package_service/get_all_packages.py create mode 100755 examples/ad_manager/v201905/package_service/get_in_progress_packages.py create mode 100755 examples/ad_manager/v201905/placement_service/create_placements.py create mode 100755 examples/ad_manager/v201905/placement_service/deactivate_placements.py create mode 100755 examples/ad_manager/v201905/placement_service/get_active_placements.py create mode 100755 examples/ad_manager/v201905/placement_service/get_all_placements.py create mode 100755 examples/ad_manager/v201905/placement_service/update_placements.py create mode 100755 examples/ad_manager/v201905/premium_rate_service/__init__.py create mode 100755 examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py create mode 100755 examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py create mode 100755 examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py create mode 100755 examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py create mode 100755 examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py create mode 100755 examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py create mode 100755 examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py create mode 100755 examples/ad_manager/v201905/product_package_service/create_product_packages.py create mode 100755 examples/ad_manager/v201905/product_package_service/get_active_product_packages.py create mode 100755 examples/ad_manager/v201905/product_package_service/get_all_product_packages.py create mode 100755 examples/ad_manager/v201905/product_service/__init__.py create mode 100755 examples/ad_manager/v201905/product_service/get_all_products.py create mode 100755 examples/ad_manager/v201905/product_service/get_products_for_product_template.py create mode 100755 examples/ad_manager/v201905/product_service/update_products.py create mode 100755 examples/ad_manager/v201905/product_template_service/__init__.py create mode 100755 examples/ad_manager/v201905/product_template_service/activate_product_templates.py create mode 100755 examples/ad_manager/v201905/product_template_service/create_product_templates.py create mode 100755 examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py create mode 100755 examples/ad_manager/v201905/product_template_service/get_all_product_templates.py create mode 100755 examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py create mode 100755 examples/ad_manager/v201905/product_template_service/update_product_templates.py create mode 100755 examples/ad_manager/v201905/proposal_line_item_service/__init__.py create mode 100755 examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py create mode 100755 examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py create mode 100755 examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py create mode 100755 examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py create mode 100755 examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py create mode 100755 examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py create mode 100755 examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py create mode 100755 examples/ad_manager/v201905/proposal_service/__init__.py create mode 100755 examples/ad_manager/v201905/proposal_service/create_programmatic_proposals.py create mode 100755 examples/ad_manager/v201905/proposal_service/create_programmatic_proposals_for_non_sales_management.py create mode 100755 examples/ad_manager/v201905/proposal_service/create_proposals.py create mode 100755 examples/ad_manager/v201905/proposal_service/get_all_proposals.py create mode 100755 examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py create mode 100755 examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py create mode 100755 examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py create mode 100755 examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py create mode 100755 examples/ad_manager/v201905/proposal_service/update_proposals.py create mode 100755 examples/ad_manager/v201905/publisher_query_language_service/__init__.py create mode 100755 examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py create mode 100755 examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py create mode 100755 examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py create mode 100755 examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py create mode 100755 examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py create mode 100755 examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py create mode 100755 examples/ad_manager/v201905/rate_card_service/__init__.py create mode 100755 examples/ad_manager/v201905/rate_card_service/create_rate_cards.py create mode 100755 examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py create mode 100755 examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py create mode 100755 examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py create mode 100755 examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py create mode 100755 examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py create mode 100755 examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py create mode 100755 examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py create mode 100755 examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py create mode 100755 examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py create mode 100755 examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py create mode 100755 examples/ad_manager/v201905/report_service/__init__.py create mode 100755 examples/ad_manager/v201905/report_service/run_ad_exchange_report.py create mode 100755 examples/ad_manager/v201905/report_service/run_delivery_report.py create mode 100755 examples/ad_manager/v201905/report_service/run_inventory_report.py create mode 100755 examples/ad_manager/v201905/report_service/run_reach_report.py create mode 100755 examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py create mode 100755 examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py create mode 100755 examples/ad_manager/v201905/report_service/run_sales_report.py create mode 100755 examples/ad_manager/v201905/report_service/run_saved_query.py create mode 100755 examples/ad_manager/v201905/suggested_ad_unit_service/__init__.py create mode 100755 examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py create mode 100755 examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py create mode 100755 examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py create mode 100755 examples/ad_manager/v201905/targeting_preset_service/__init__.py create mode 100755 examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py create mode 100755 examples/ad_manager/v201905/team_service/__init__.py create mode 100755 examples/ad_manager/v201905/team_service/create_teams.py create mode 100755 examples/ad_manager/v201905/team_service/get_all_teams.py create mode 100755 examples/ad_manager/v201905/team_service/update_teams.py create mode 100755 examples/ad_manager/v201905/user_service/__init__.py create mode 100755 examples/ad_manager/v201905/user_service/create_users.py create mode 100755 examples/ad_manager/v201905/user_service/deactivate_users.py create mode 100755 examples/ad_manager/v201905/user_service/get_all_roles.py create mode 100755 examples/ad_manager/v201905/user_service/get_all_users.py create mode 100755 examples/ad_manager/v201905/user_service/get_current_user.py create mode 100755 examples/ad_manager/v201905/user_service/get_user_by_email_address.py create mode 100755 examples/ad_manager/v201905/user_service/update_users.py create mode 100755 examples/ad_manager/v201905/user_team_association_service/__init__.py create mode 100755 examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py create mode 100755 examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py create mode 100755 examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py create mode 100755 examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py create mode 100755 examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py create mode 100755 examples/ad_manager/v201905/workflow_request_service/__init__.py create mode 100755 examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py create mode 100755 examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py create mode 100755 examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py create mode 100755 examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py diff --git a/ChangeLog b/ChangeLog index 5450352a..68f4088b 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +19.0.0 -- 05/09/2019 +* Added support for Ad Manager v201905 +* Removed support for Ad Manager v201805 +* Removed examples for Ad Manager v201808 + 18.1.0 -- 04/03/2018 * Upgrade PyYAML to 5.1 >= 6.0 * Update comment in get_all_images_and_videos examples diff --git a/examples/ad_manager/v201905/activity_group_service/__init__.py b/examples/ad_manager/v201905/activity_group_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/activity_group_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py new file mode 100755 index 00000000..256d9e94 --- /dev/null +++ b/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new activity groups. + +To determine which activity groups exist, run get_all_activity_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the advertiser company this activity group is associated with. +ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' + + +def main(client, advertiser_company_id): + # Initialize appropriate service. + activity_group_service = client.GetService('ActivityGroupService', + version='v201905') + + # Create a short-term activity group. + short_term_activity_group = { + 'name': 'Short-term activity group #%s' % uuid.uuid4(), + 'companyIds': [advertiser_company_id], + 'clicksLookback': '1', + 'impressionsLookback': '1' + } + + # Create a long-term activity group. + long_term_activity_group = { + 'name': 'Long-term activity group #%s' % uuid.uuid4(), + 'companyIds': [advertiser_company_id], + 'clicksLookback': '30', + 'impressionsLookback': '30' + } + + # Create the activity groups on the server. + activity_groups = activity_group_service.createActivityGroups([ + short_term_activity_group, long_term_activity_group]) + + # Display results. + for activity_group in activity_groups: + print ('Activity group with ID "%s" and name "%s" was created.' + % (activity_group['id'], activity_group['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_COMPANY_ID) diff --git a/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py new file mode 100755 index 00000000..1137ccde --- /dev/null +++ b/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 active activity groups. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + activity_group_service = client.GetService( + 'ActivityGroupService', version='v201905') + # Create a statement to select activity groups. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) + + # Retrieve a small amount of activity groups at a time, paging + # through until all activity groups have been retrieved. + while True: + response = activity_group_service.getActivityGroupsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for activity_group in response['results']: + # Print out some information for each activity group. + print('Activity group with ID "%d" and name "%s" was found.\n' % + (activity_group['id'], activity_group['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py new file mode 100755 index 00000000..7e5c4041 --- /dev/null +++ b/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 activity groups. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + activity_group_service = client.GetService( + 'ActivityGroupService', version='v201905') + + # Create a statement to select activity groups. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of activity groups at a time, paging + # through until all activity groups have been retrieved. + while True: + response = activity_group_service.getActivityGroupsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for activity_group in response['results']: + # Print out some information for each activity group. + print('Activity group with ID "%d" and name "%s" was found.\n' % + (activity_group['id'], activity_group['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py new file mode 100755 index 00000000..9fa21fc2 --- /dev/null +++ b/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates activity groups. + +To determine which activity groups exist, run get_all_activity_groups.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the activity group and the company to update it with. +ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' +ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' + + +def main(client, activity_group_id, advertiser_company_id): + # Initialize appropriate service. + activity_group_service = client.GetService('ActivityGroupService', + version='v201905') + + # Create statement object to select a single activity groups by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :activityGroupId') + .WithBindVariable('activityGroupId', long(activity_group_id)) + .Limit(1)) + + # Get activity groups by statement. + response = activity_group_service.getActivityGroupsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + updated_activity_groups = [] + for activity_group in response['results']: + activity_group['companyIds'].append(advertiser_company_id) + updated_activity_groups.append(activity_group) + # Update the activity groups on the server. + activity_groups = activity_group_service.updateActivityGroups( + updated_activity_groups) + + for activity_group in activity_groups: + print (('Activity group with ID "%s" and name "%s" was updated.') + % (activity_group['id'], activity_group['name'])) + else: + print 'No activity groups found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) diff --git a/examples/ad_manager/v201905/activity_service/__init__.py b/examples/ad_manager/v201905/activity_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/activity_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/activity_service/create_activities.py b/examples/ad_manager/v201905/activity_service/create_activities.py new file mode 100755 index 00000000..58767280 --- /dev/null +++ b/examples/ad_manager/v201905/activity_service/create_activities.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new activities. + +To determine which activities groups exist, run get_all_activities.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the activity group this activity is associated with. +ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' + + +def main(client, activity_group_id): + # Initialize appropriate service. + activity_service = client.GetService('ActivityService', version='v201905') + + # Create a daily visits activity. + daily_visits_activity = { + 'name': 'Activity #%s' % uuid.uuid4(), + 'activityGroupId': activity_group_id, + 'type': 'DAILY_VISITS' + } + + # Create a custom activity. + custom_activity = { + 'name': 'Activity #%s' % uuid.uuid4(), + 'activityGroupId': activity_group_id, + 'type': 'CUSTOM' + } + + # Create the activities on the server. + activities = activity_service.createActivities([ + daily_visits_activity, custom_activity]) + + # Display results. + for activity in activities: + print ('An activity with ID "%s", name "%s", and type "%s" was ' + 'created.' % (activity['id'], activity['name'], activity['type'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_GROUP_ID) diff --git a/examples/ad_manager/v201905/activity_service/get_active_activities.py b/examples/ad_manager/v201905/activity_service/get_active_activities.py new file mode 100755 index 00000000..0fd55cf4 --- /dev/null +++ b/examples/ad_manager/v201905/activity_service/get_active_activities.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 active activities. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + activity_service = client.GetService('ActivityService', version='v201905') + # Create a statement to select activities. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) + + # Retrieve a small amount of activities at a time, paging + # through until all activities have been retrieved. + while True: + response = activity_service.getActivitiesByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for activity in response['results']: + # Print out some information for each activity. + print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % + (activity['id'], activity['name'], activity['type'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/activity_service/get_all_activities.py b/examples/ad_manager/v201905/activity_service/get_all_activities.py new file mode 100755 index 00000000..d06ef0e8 --- /dev/null +++ b/examples/ad_manager/v201905/activity_service/get_all_activities.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 activities. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + activity_service = client.GetService('ActivityService', version='v201905') + + # Create a statement to select activities. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of activities at a time, paging + # through until all activities have been retrieved. + while True: + response = activity_service.getActivitiesByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for activity in response['results']: + # Print out some information for each activity. + print('Activity with ID "%d" and name "%s" was found.\n' % + (activity['id'], activity['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/activity_service/update_activities.py b/examples/ad_manager/v201905/activity_service/update_activities.py new file mode 100755 index 00000000..7fe4a3ed --- /dev/null +++ b/examples/ad_manager/v201905/activity_service/update_activities.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates activities. + +To determine which activities exist, run get_all_activities.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the activity to update. +ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE' + + +def main(client, activity_id): + # Initialize appropriate service. + activity_service = client.GetService('ActivityService', version='v201905') + + # Create statement object to select one activity by ID to update. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :activityId') + .WithBindVariable('activityId', long(activity_id)) + .Limit(1)) + + # Get activities by statement. + response = activity_service.getActivitiesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + updated_activities = [] + for activity in response['results']: + # Update the expected URL. + activity['expectedURL'] = 'https://google.com' + updated_activities.append(activity) + # Update the activity on the server. + activities = activity_service.updateActivities(updated_activities) + + for updated_activity in activities: + print (('Activity with ID "%s" and name "%s" was updated.') + % (updated_activity['id'], updated_activity['name'])) + else: + print 'No activities found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ACTIVITY_ID) diff --git a/examples/ad_manager/v201905/adjustment_service/create_traffic_adjustments.py b/examples/ad_manager/v201905/adjustment_service/create_traffic_adjustments.py new file mode 100755 index 00000000..fbf9df5b --- /dev/null +++ b/examples/ad_manager/v201905/adjustment_service/create_traffic_adjustments.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 adds or replaces a forecast adjustment. + +The adjustment will affect 1920x1080 video traffic in the United States. +""" + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service and the network service. + adjustment_service = client.GetService('AdjustmentService', version='v201905') + network_service = client.GetService('NetworkService', version='v201905') + + # Get the root ad unit id to target the whole site. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create inventory targeting. + inventory_targeting = { + 'targetedAdUnits': [{ + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id + }] + } + + # Create geo targeting. When using geo targeting with the adjustment service, + # only locations of type COUNTRY are supported. You can download the latest + # geo targets at https://developers.google.com/ad-manager/api/geotargets. + geo_targeting = { + 'targetedLocations': [{ + 'id': 2840 + }] # USA. + } + + # Create ad unit size to define the slice of inventory affected by the + # traffic adjustment. + ad_unit_size = { + 'size': { + 'width': 1920, + 'height': 1080 + }, + 'environmentType': 'VIDEO_PLAYER' + } + + # Create a new historical adjustment targeting next year's January with 105% + # of the traffic of this year's January. + this_january = { + 'startDate': datetime.date(datetime.date.today().year, 1, 1), + 'endDate': datetime.date(datetime.date.today().year, 1, 31) + } + next_january = { + 'startDate': datetime.date(datetime.date.today().year + 1, 1, 1), + 'endDate': datetime.date(datetime.date.today().year + 1, 1, 31) + } + + january_segment = { + 'basisType': 'HISTORICAL', + 'historicalAdjustment': { + 'targetDateRange': next_january, + 'referenceDateRange': this_january, + 'milliPercentMultiplier': 105000 + } + } + + # Create a new absolute adjustment of 500,000 ad opportunities for Christmas + # and 1,000,000 opportunities for Boxing Day of next year. + christmas_day = datetime.date(datetime.date.today().year + 1, 12, 25) + boxing_day = christmas_day + datetime.timedelta(days=1) + holiday_range = {'startDate': christmas_day, 'endDate': boxing_day} + + holiday_segment = { + 'basisType': 'ABSOLUTE', + 'adjustmentTimeSeries': { + 'timeSeriesDateRange': holiday_range, + 'timeSeriesValues': [500000, 1000000], # xsd:long[] + 'valuePeriodType': 'DAILY' + } + } + + # Create a new absolute adjustment of 900,000 ad opportunities for the first + # week of September of next year. + first_week_of_september = { + 'startDate': datetime.date(datetime.date.today().year + 1, 9, 1), + 'endDate': datetime.date(datetime.date.today().year + 1, 9, 7) + } + + september_segment = { + 'basisType': 'ABSOLUTE', + 'adjustmentTimeSeries': { + 'timeSeriesDateRange': first_week_of_september, + 'timeSeriesValues': [900000], + 'valuePeriodType': 'CUSTOM' + } + } + + # Create traffic forecast adjustment object. + adjustment_segments = [january_segment, holiday_segment, september_segment] + adjustment = { + 'filterCriteria': { + 'targeting': { + 'inventoryTargeting': inventory_targeting, + 'geoTargeting': geo_targeting + }, + 'adUnitSizes': [ad_unit_size] + }, + 'forecastAdjustmentSegments': adjustment_segments + } + + # Create or update the traffic adjustment for the given filter criteria on + # the server. + updated_adjustments = adjustment_service.updateTrafficAdjustments( + [adjustment]) + + # Display the results. + for updated_adjustment in updated_adjustments: + print('Traffic forecast adjustment with id %d and %d segments was ' + 'created.' % (updated_adjustment['id'], + len(updated_adjustment['forecastAdjustmentSegments']))) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/adjustment_service/get_all_traffic_adjustments.py b/examples/ad_manager/v201905/adjustment_service/get_all_traffic_adjustments.py new file mode 100755 index 00000000..a2340cef --- /dev/null +++ b/examples/ad_manager/v201905/adjustment_service/get_all_traffic_adjustments.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 traffic adjustments.""" + +from __future__ import print_function + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v201905') + + # Create a statement to get all forecast traffic adjustments. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small number of traffic adjustments at a time, paging + # through until all traffic adjustments have been retrieved. + while True: + response = adjustment_service.getTrafficAdjustmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for adjustment in response['results']: + # Print out some information for each traffic adjustment. + print('Traffic forecast adjustment with id %d and %d segments was ' + 'found.' % (adjustment['id'], + len(adjustment['forecastAdjustmentSegments']))) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/adjustment_service/update_traffic_adjustments.py b/examples/ad_manager/v201905/adjustment_service/update_traffic_adjustments.py new file mode 100755 index 00000000..d59b2e2d --- /dev/null +++ b/examples/ad_manager/v201905/adjustment_service/update_traffic_adjustments.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 adds a historical adjustment of 110% for New Years Day traffic. +""" + +from __future__ import print_function +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' + + +def main(client, adjustment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v201905') + + # Create a statement to select a single traffic forecast adjustment by id. + statement = ( + ad_manager.StatementBuilder( + version='v201905').Where('id = :id').WithBindVariable( + 'id', adjustment_id)) + + # Get the forecast traffic adjustment. + response = adjustment_service.getTrafficAdjustmentsByStatement( + statement.ToStatement()) + + # Create a new historical adjustment segment for New Year's Day. + this_new_years = datetime.date(datetime.date.today().year, 12, 31) + next_new_years = datetime.date(datetime.date.today().year + 1, 12, 31) + + new_years_segment = { + 'basisType': 'HISTORICAL', + 'historicalAdjustment': { + 'targetDateRange': { + 'startDate': next_new_years, + 'endDate': next_new_years + }, + 'referenceDateRange': { + 'startDate': this_new_years, + 'endDate': this_new_years + }, + 'milliPercentMultiplier': 110000 + } + } + + if 'results' in response and len(response['results']): + # Update each local traffic adjustment. + updated_adjustments = [] + for adjustment in response['results']: + adjustment['forecastAdjustmentSegments'].append(new_years_segment) + updated_adjustments.append(adjustment) + + # Update traffic adjustments remotely. + adjustments = adjustment_service.updateTrafficAdjustments( + updated_adjustments) + + # Display the results. + if adjustments: + for adjustment in adjustments: + print('Traffic forecast adjustment with id %d and %d segments was ' + 'created.' % (adjustment['id'], + len(adjustment['forecastAdjustmentSegments']))) + else: + print('No traffic adjustments were updated.') + else: + print('No traffic adjustments found to update.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v201905/audience_segment_service/__init__.py b/examples/ad_manager/v201905/audience_segment_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/audience_segment_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py new file mode 100755 index 00000000..fc2cf720 --- /dev/null +++ b/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates a new rule based first party audience segment.""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the IDs of the custom criteria to be used in the segment rule. +CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' +CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' + + +def main(client, custom_targeting_key_id, custom_targeting_value_id): + # Initialize appropriate services. + audience_segment_service = client.GetService( + 'AudienceSegmentService', version='v201905') + network_service = client.GetService('NetworkService', version='v201905') + + # Get the root ad unit ID used to target the entire network. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create inventory targeting (pointed at root ad unit i.e. the whole network) + inventory_targeting = { + 'targetedAdUnits': [ + {'adUnitId': root_ad_unit_id} + ] + } + + # Create custom criteria. + custom_criteria = [ + { + 'xsi_type': 'CustomCriteria', + 'keyId': custom_targeting_key_id, + 'valueIds': [custom_targeting_value_id], + 'operator': 'IS' + } + ] + + # Create the custom criteria set. + top_custom_criteria_set = { + 'logicalOperator': 'AND', + 'children': custom_criteria + } + + # Create the audience segment rule. + rule = { + 'inventoryRule': inventory_targeting, + 'customCriteriaRule': top_custom_criteria_set + } + + # Create an audience segment. + audience_segment = [ + { + 'xsi_type': 'RuleBasedFirstPartyAudienceSegment', + 'name': ('Sports enthusiasts audience segment %s' % + uuid.uuid4()), + 'description': 'Sports enthusiasts between the ages of 20 and 30', + 'pageViews': '6', + 'recencyDays': '6', + 'membershipExpirationDays': '88', + 'rule': rule + } + ] + + audience_segments = ( + audience_segment_service.createAudienceSegments(audience_segment)) + + for created_audience_segment in audience_segments: + print ('An audience segment with ID "%s", name "%s", and type "%s" ' + 'was created.' % (created_audience_segment['id'], + created_audience_segment['name'], + created_audience_segment['type'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py new file mode 100755 index 00000000..b1ac0da8 --- /dev/null +++ b/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 audience segments. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + audience_segment_service = client.GetService( + 'AudienceSegmentService', version='v201905') + + # Create a statement to select audience segments. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of audience segments at a time, paging + # through until all audience segments have been retrieved. + while True: + response = audience_segment_service.getAudienceSegmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for audience_segment in response['results']: + # Print out some information for each audience segment. + print('Audience segment with ID "%d", name "%s", and size "%d" was ' + 'found.\n' % (audience_segment['id'], audience_segment['name'], + audience_segment['size'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py new file mode 100755 index 00000000..a495a37e --- /dev/null +++ b/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 first party audience segments. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + audience_segment_service = client.GetService( + 'AudienceSegmentService', version='v201905') + # Create a statement to select audience segments. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('type = :type') + .WithBindVariable('type', 'FIRST_PARTY')) + + # Retrieve a small amount of audience segments at a time, paging + # through until all audience segments have been retrieved. + while True: + response = audience_segment_service.getAudienceSegmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for audience_segment in response['results']: + # Print out some information for each audience segment. + print('Audience segment with ID "%d", name "%s", and size "%d" was ' + 'found.\n' % (audience_segment['id'], audience_segment['name'], + audience_segment['size'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py new file mode 100755 index 00000000..374f5819 --- /dev/null +++ b/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 populates a specific first party audience segment. + +To determine which first party audience segments exist, run +get_first_party_audience_segments.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' + + +def main(client, audience_segment_id): + # Initialize appropriate service. + audience_segment_service = client.GetService( + 'AudienceSegmentService', version='v201905') + + # Create statement object to get the specified first party audience segment. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) + + response = audience_segment_service.getAudienceSegmentsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + segments = response['results'] + + for segment in segments: + print ( + 'Audience segment with id "%s" and name "%s" will be populated.' + % (segment['id'], segment['name'])) + + action = { + 'xsi_type': 'PopulateAudienceSegments' + } + + populated_audience_segments = ( + audience_segment_service.performAudienceSegmentAction( + action, statement.ToStatement())) + + print ('%s audience segment populated' % + populated_audience_segments['numChanges']) + else: + print 'No Results Found' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py new file mode 100755 index 00000000..15a94347 --- /dev/null +++ b/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates rule based first party audience segments. + +To determine which audience segments exist, run get_all_audience_segments.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' + + +def main(client, audience_segment_id): + # Initialize appropriate service. + audience_segment_service = client.GetService( + 'AudienceSegmentService', version='v201905') + + # Create statement object to get the specified first party audience segment. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('Type = :type AND Id = :audience_segment_id') + .WithBindVariable('audience_segment_id', + long(audience_segment_id)) + .WithBindVariable('type', 'FIRST_PARTY') + .Limit(1)) + + # Get audience segments by statement. + response = audience_segment_service.getAudienceSegmentsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + updated_audience_segments = [] + for audience_segment in response['results']: + print ('Audience segment with id "%s" and name "%s" will be updated.' + % (audience_segment['id'], audience_segment['name'])) + + audience_segment['membershipExpirationDays'] = '180' + updated_audience_segments.append(audience_segment) + + audience_segments = audience_segment_service.updateAudienceSegments( + updated_audience_segments) + + for audience_segment in audience_segments: + print ('Audience segment with id "%s" and name "%s" was updated' % + (audience_segment['id'], audience_segment['name'])) + else: + print 'No audience segment found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/ad_manager/v201905/base_rate_service/__init__.py b/examples/ad_manager/v201905/base_rate_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/base_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py new file mode 100755 index 00000000..24fe9bb0 --- /dev/null +++ b/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates a product base rate. + +To determine which base rates exist, run get_all_base_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, product_id, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService( + 'BaseRateService', version='v201905') + + # Create a product base rate. + product_base_rate = { + 'xsi_type': 'ProductBaseRate', + # Set the rate card ID that the product base rate belongs to. + 'rateCardId': rate_card_id, + # Set the product id the base rate will be applied to. + 'productId': product_id, + # Set the rate to be $2. + 'rate': { + 'currencyCode': 'USD', + 'microAmount': 2000000 + } + } + + # Create the product base rate on the server. + base_rates = base_rate_service.createBaseRates( + [product_base_rate]) + + if base_rates: + for base_rate in base_rates: + print ('A product base rate with ID "%s" and rate \'%.2f\' %s was ' + 'created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py new file mode 100755 index 00000000..14bddffe --- /dev/null +++ b/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a product package item base rate. + +To determine which base rates exist, run get_all_base_rates.py +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the rate card ID to add the base rate to. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + +# Set the product package item to apply this base rate to. +PRODUCT_PACKAGE_ITEM_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201905') + + # Create a base rate for a product package item. + product_package_item_base_rate = { + 'xsi_type': 'ProductPackageItemBaseRate', + # Set the rate card ID that the product package item base rate + # belongs to. + 'rateCardId': RATE_CARD_ID, + # Set the product package item the base rate will be applied to. + 'productPackageItemId': PRODUCT_PACKAGE_ITEM_ID, + # Create a rate worth $2 USD and set that on the product package item + # base rate. + 'rate': { + 'xsi_type': 'Money', + 'currencyCode': 'USD', + 'microAmount': 2000000, + } + } + + # Create the product package item base rate on the server. + result = base_rate_service.createBaseRates([product_package_item_base_rate]) + + for new_base_rate in result: + print ('A product package item base rate with ID %d and rate %f %s ' + 'was created.' % (new_base_rate['id'], + new_base_rate['microAmount'], + new_base_rate['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py new file mode 100755 index 00000000..6a38d9b9 --- /dev/null +++ b/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates a product template base rate. + +To determine which base rates exist, run get_all_base_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, product_template_id, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService( + 'BaseRateService', version='v201905') + + # Create a product template base rate. + product_template_base_rate = { + 'xsi_type': 'ProductTemplateBaseRate', + # Set the rate card ID that the product template base rate belongs to. + 'rateCardId': rate_card_id, + # Set the product template the base rate will be applied to. + 'productTemplateId': product_template_id, + # Set the rate to be $2. + 'rate': { + 'currencyCode': 'USD', + 'microAmount': 2000000 + } + } + + # Create the product template item base rate on the server. + base_rates = base_rate_service.createBaseRates( + [product_template_base_rate]) + + if base_rates: + for base_rate in base_rates: + print ('A product template base rate with ID "%s" and rate \'%.2f\' %s' + ' was created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py new file mode 100755 index 00000000..b92350b8 --- /dev/null +++ b/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 base rates. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201905') + + # Create a statement to select base rates. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of base rates at a time, paging + # through until all base rates have been retrieved. + while True: + response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for base_rate in response['results']: + # Print out some information for each base rate. + print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' + 'found.\n' % (base_rate['id'], + ad_manager.AdManagerClassType(base_rate), + base_rate['rateCardId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py new file mode 100755 index 00000000..dfa06842 --- /dev/null +++ b/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 base rates belonging to a rate card. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201905') + # Create a statement to select base rates. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) + + # Retrieve a small amount of base rates at a time, paging + # through until all base rates have been retrieved. + while True: + response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for base_rate in response['results']: + # Print out some information for each base rate. + print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' + 'found.\n' % + (base_rate['id'], ad_manager.AdManagerClassType(base_rate), + base_rate['rateCardId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/base_rate_service/update_base_rates.py b/examples/ad_manager/v201905/base_rate_service/update_base_rates.py new file mode 100755 index 00000000..60c4b9a3 --- /dev/null +++ b/examples/ad_manager/v201905/base_rate_service/update_base_rates.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates a base rate's value. + +To determine which base rates exist, run get_all_base_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' + + +def main(client, base_rate_id): + # Initialize appropriate service. + base_rate_service = client.GetService('BaseRateService', version='v201905') + + # Create a filter statement for base rates for a single rate card. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', long(base_rate_id))) + + # Get single base rate by statement. + response = base_rate_service.getBaseRatesByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local base rate object by changing its value to $3 USD. + new_rate = { + 'currencyCode': 'USD', + 'microAmount': 3000000 + } + + updated_base_rates = [] + for base_rate in response['results']: + base_rate['rate'] = new_rate + updated_base_rates.append(base_rate) + + # Update base rates remotely. + base_rates = base_rate_service.updateBaseRates(updated_base_rates) + + # Display results. + if base_rates: + for base_rate in base_rates: + print ('Base rate with ID "%s" and type "%s" belonging to ' + 'rate card ID "%s" was updated.' % ( + base_rate['id'], + ad_manager.AdManagerClassType(base_rate), + base_rate['rateCardId'])) + else: + print 'No base rates were updated.' + else: + print 'No base rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, BASE_RATE_ID) diff --git a/examples/ad_manager/v201905/cdn_configuration_service/__init__.py b/examples/ad_manager/v201905/cdn_configuration_service/__init__.py new file mode 100755 index 00000000..473ddba1 --- /dev/null +++ b/examples/ad_manager/v201905/cdn_configuration_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. diff --git a/examples/ad_manager/v201905/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201905/cdn_configuration_service/create_cdn_configurations.py new file mode 100755 index 00000000..51ae1a9d --- /dev/null +++ b/examples/ad_manager/v201905/cdn_configuration_service/create_cdn_configurations.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 code example creates new cdn configurations. + +To determine which configurations exist, run get_all_cdn_configurations.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201905') + + # Create cdn config objects. + # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. + configs = [{ + # Basic example with no security policies. + 'name': 'ApiConfig1', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'NONE' + } + } + } + }, { + # Complex example with security policies. + 'name': 'ApiConfig2', + 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', + 'sourceContentConfiguration': { + 'ingestSettings': { + 'urlPrefix': 'ingest1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': False, + 'tokenAuthenticationKey': 'abc123', + } + }, + 'defaultDeliverySettings': { + 'urlPrefix': 'delivery1.com', + 'securityPolicy': { + 'securityPolicyType': 'AKAMAI', + 'disableServerSideUrlSigning': True, + 'originForwardingType': 'CONVENTIONAL', + 'originPathPrefix': '/path/to/my/origin' + } + } + } + }] + + # Add configs. + configs = cdn_config_service.createCdnConfigurations(configs) + + # Display results. + for config in configs: + print('Created CDN configuration with type "%s" and name "%s".' + % (config['cdnConfigurationType'], config['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py new file mode 100755 index 00000000..ae318610 --- /dev/null +++ b/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 CDN configuration objects. + +Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be +returned. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + cdn_config_service = client.GetService('CdnConfigurationService', + version='v201905') + + # Create a statement to select cdn configurations. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small number of configs at a time, paging + # through until all have been retrieved. + while True: + response = (cdn_config_service + .getCdnConfigurationsByStatement(statement.ToStatement())) + if 'results' in response and len(response['results']): + for cdn in response['results']: + # Print out some information for each company. + print('Found CDN configuration with type "%s" and name "%s".' + % (cdn['cdnConfigurationType'], cdn['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_keys.py new file mode 100755 index 00000000..3eaf651b --- /dev/null +++ b/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_keys.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 CmsMetadataKeys.""" + +# Import appropriate modules from the client library. +from __future__ import print_function +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201905') + + # Create a statement to select CmsMetadataKeys. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of keys at a time, paging + # through until all keys have been retrieved. + while True: + response = cms_metadata_service.getCmsMetadataKeysByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_key in response['results']: + # Print out some information for each key. + print('CMS metadata key with Id %d and name "%s" was found.\n' % + (cms_metadata_key['id'], cms_metadata_key['name'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_values.py new file mode 100755 index 00000000..80f3d495 --- /dev/null +++ b/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_values.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 CmsMetadataValues.""" + +# Import appropriate modules from the client library. +from __future__ import print_function +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201905') + + # Create a statement to select CmsMetadataValues. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of values at a time, paging + # through until all values have been retrieved. + while True: + response = cms_metadata_service.getCmsMetadataValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_value in response['results']: + # Print out some information for each value. + print(('CMS metadata value with Id %d and name "%s", associated with ' + 'the CmsMetadataKey with id %d and name "%s", was found.\n') % + (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'], cms_metadata_value['key']['id'], + cms_metadata_value['key']['name'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v201905/cms_metadata_service/get_cms_metadata_values_for_key.py new file mode 100755 index 00000000..6c831917 --- /dev/null +++ b/examples/ad_manager/v201905/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 CmsMetadataValues for a particular CmsMetadataKey.""" + +# Import appropriate modules from the client library. +from __future__ import print_function +from googleads import ad_manager + +CMS_METADATA_KEY_NAME = 'INSERT_CMS_METADATA_KEY_NAME_HERE' + + +def main(client, cms_metadata_key_name): + # Initialize appropriate service. + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201905') + + # Create a statement to select CmsMetadataValues for a particular key. + statement = ( + ad_manager.StatementBuilder(version='v201905').Where( + 'cmsKey = :cmsMetadataKeyName').WithBindVariable( + 'cmsMetadataKeyName', cms_metadata_key_name)) + + # Retrieve a small amount of values at a time, paging + # through until all values have been retrieved. + while True: + response = cms_metadata_service.getCmsMetadataValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_value in response['results']: + # Print out some information for each value. + print(('CMS metadata value with Id %d and name "%s", associated with ' + 'the CmsMetadataKey with id %d and name "%s", was found.\n') % + (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'], cms_metadata_value['key']['id'], + cms_metadata_value['key']['name'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CMS_METADATA_KEY_NAME) diff --git a/examples/ad_manager/v201905/company_service/__init__.py b/examples/ad_manager/v201905/company_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/company_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/company_service/create_companies.py b/examples/ad_manager/v201905/company_service/create_companies.py new file mode 100755 index 00000000..df7217d5 --- /dev/null +++ b/examples/ad_manager/v201905/company_service/create_companies.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new companies. + +To determine which companies exist, run get_all_companies.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + company_service = client.GetService('CompanyService', version='v201905') + + # Create company objects. + companies = [ + { + 'name': 'Advertiser #%s' % uuid.uuid4(), + 'type': 'ADVERTISER' + }, + { + 'name': 'Agency #%s' % uuid.uuid4(), + 'type': 'AGENCY' + } + ] + + # Add companies. + companies = company_service.createCompanies(companies) + + # Display results. + for company in companies: + print ('Company with ID "%s", name "%s", and type "%s" was created.' + % (company['id'], company['name'], company['type'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/company_service/get_advertisers.py b/examples/ad_manager/v201905/company_service/get_advertisers.py new file mode 100755 index 00000000..d0d096f4 --- /dev/null +++ b/examples/ad_manager/v201905/company_service/get_advertisers.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 companies that are advertisers. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + company_service = client.GetService('CompanyService', version='v201905') + # Create a statement to select companies. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('type = :type') + .WithBindVariable('type', 'ADVERTISER')) + + # Retrieve a small amount of companies at a time, paging + # through until all companies have been retrieved. + while True: + response = company_service.getCompaniesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for company in response['results']: + # Print out some information for each company. + print('Company with ID "%d", name "%s", and type "%s" was found.\n' % + (company['id'], company['name'], company['type'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/company_service/get_all_companies.py b/examples/ad_manager/v201905/company_service/get_all_companies.py new file mode 100755 index 00000000..22d8529d --- /dev/null +++ b/examples/ad_manager/v201905/company_service/get_all_companies.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 companies. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + company_service = client.GetService('CompanyService', version='v201905') + + # Create a statement to select companies. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of companies at a time, paging + # through until all companies have been retrieved. + while True: + response = company_service.getCompaniesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for company in response['results']: + # Print out some information for each company. + print('Company with ID "%d", name "%s", and type "%s" was found.\n' % + (company['id'], company['name'], company['type'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/company_service/update_companies.py b/examples/ad_manager/v201905/company_service/update_companies.py new file mode 100755 index 00000000..a1bf8d15 --- /dev/null +++ b/examples/ad_manager/v201905/company_service/update_companies.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates company comments. + +To determine which companies exist, run get_all_companies.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the company to update. +COMPANY_ID = 'INSERT_COMPANY_ID_HERE' + + +def main(client, company_id): + # Initialize appropriate service. + company_service = client.GetService('CompanyService', version='v201905') + + # Create statement object to only select a single company by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', long(company_id)) + .Limit(1)) + + # Get companies by statement. + response = company_service.getCompaniesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + updated_companies = [] + for company in response['results']: + company['comment'] += ' Updated.' + updated_companies.append(company) + + # Update the companies on the server. + companies = company_service.updateCompanies(updated_companies) + + # Display results. + for company in companies: + print (('Company with ID "%s", name "%s", and comment "%s"' + ' was updated.') + % (company['id'], company['name'], company['comment'])) + else: + print 'No companies found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, COMPANY_ID) diff --git a/examples/ad_manager/v201905/contact_service/__init__.py b/examples/ad_manager/v201905/contact_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/contact_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/contact_service/create_contacts.py b/examples/ad_manager/v201905/contact_service/create_contacts.py new file mode 100755 index 00000000..03ee90c2 --- /dev/null +++ b/examples/ad_manager/v201905/contact_service/create_contacts.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new contacts. + +To determine which contacts exist, run get_all_contacts.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the advertiser company this contact is associated with. +ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' + +# Set the ID of the agency company this contact is associated with. +AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE' + + +def main(client, advertiser_company_id, agency_company_id): + # Initialize appropriate service. + contact_service = client.GetService('ContactService', version='v201905') + + # Create an advertiser contact. + advertiser_contact = { + 'name': 'Mr. Advertiser #%s' % uuid.uuid4(), + 'email': 'advertiser@advertising.com', + 'companyId': advertiser_company_id + } + + # Create an agency contact. + agency_contact = { + 'name': 'Ms. Agency #%s' % uuid.uuid4(), + 'email': 'agency@agencies.com', + 'companyId': agency_company_id + } + + # Create the contacts on the server. + contacts = contact_service.createContacts([advertiser_contact, + agency_contact]) + + # Display results. + for contact in contacts: + print ('Contact with ID "%s" name "%s" was created.' + % (contact['id'], contact['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) diff --git a/examples/ad_manager/v201905/contact_service/get_all_contacts.py b/examples/ad_manager/v201905/contact_service/get_all_contacts.py new file mode 100755 index 00000000..5fc123fc --- /dev/null +++ b/examples/ad_manager/v201905/contact_service/get_all_contacts.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 contacts. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + contact_service = client.GetService('ContactService', version='v201905') + + # Create a statement to select contacts. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of contacts at a time, paging + # through until all contacts have been retrieved. + while True: + response = contact_service.getContactsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for contact in response['results']: + # Print out some information for each contact. + print('Contact with ID "%d" and name "%s" was found.\n' % + (contact['id'], contact['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py new file mode 100755 index 00000000..9542484d --- /dev/null +++ b/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 contacts that aren't invited yet. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + contact_service = client.GetService('ContactService', version='v201905') + # Create a statement to select contacts. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status') + .WithBindVariable('status', 'UNINVITED')) + + # Retrieve a small amount of contacts at a time, paging + # through until all contacts have been retrieved. + while True: + response = contact_service.getContactsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for contact in response['results']: + # Print out some information for each contact. + print('Contact with ID "%d" and name "%s" was found.\n' % + (contact['id'], contact['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/contact_service/update_contacts.py b/examples/ad_manager/v201905/contact_service/update_contacts.py new file mode 100755 index 00000000..4b5c97c4 --- /dev/null +++ b/examples/ad_manager/v201905/contact_service/update_contacts.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates contact addresses. + +To determine which contacts exist, run get_all_contacts.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the contact to update. +CONTACT_ID = 'INSERT_CONTACT_ID_HERE' + + +def main(client, contact_id): + # Initialize appropriate service. + contact_service = client.GetService('ContactService', version='v201905') + + # Create statement object to select the single contact by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', long(contact_id)) + .Limit(1)) + + # Get contacts by statement. + response = contact_service.getContactsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + updated_contacts = [] + for contact in response['results']: + contact['address'] = '123 New Street, New York, NY, 10011' + updated_contacts.append(contact) + + # Update the contact on the server. + contacts = contact_service.updateContacts(updated_contacts) + + # Display results. + for contact in contacts: + print (('Contact with ID "%s", name "%s", and address "%s" ' + 'was updated.') + % (contact['id'], contact['name'], contact['address'])) + else: + print 'No contacts found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTACT_ID) diff --git a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py new file mode 100755 index 00000000..23ec1a46 --- /dev/null +++ b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new content metadata key hierarchies. + +To determine which content metadata key hierarchies exist, run +get_all_content_metadata_key_hierarchies.py. + +This feature is only available to Video Solutions publishers. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the IDs of the custom targeting keys for the hierarchy. +HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' +HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE' + + +def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): + # Initialize appropriate service. + content_metadata_key_hierarchy_service = client.GetService( + 'ContentMetadataKeyHierarchyService', version='v201905') + + hierarchy_level_1 = { + 'customTargetingKeyId': hierarchy_level_one_key_id, + 'hierarchyLevel': '1' + } + + hierarchy_level_2 = { + 'customTargetingKeyId': hierarchy_level_two_key_id, + 'hierarchyLevel': '2' + } + + hierarchy_levels = [hierarchy_level_1, hierarchy_level_2] + + # Create content metadata key hierarchy object. + content_metadata_key_hierarchy = { + 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(), + 'hierarchyLevels': hierarchy_levels + } + + content_metadata_key_hierarchies = ( + content_metadata_key_hierarchy_service + .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy])) + + # Display results. + for content_metadata_key_hierarchy in content_metadata_key_hierarchies: + print ('Content metadata key hierarchy with id "%s" and name "%s"' + ' was created.' % (content_metadata_key_hierarchy['id'], + content_metadata_key_hierarchy['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, HIERARCHY_LEVEL_ONE_KEY_ID, + HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py new file mode 100755 index 00000000..44d31e6f --- /dev/null +++ b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 content metadata key hierarchies. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + content_metadata_key_hierarchy_service = client.GetService( + 'ContentMetadataKeyHierarchyService', version='v201905') + + # Create a statement to select content metadata key hierarchies. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of content metadata key hierarchies at a time, + # paging through until all content metadata key hierarchies have been + # retrieved. + while True: + response = ( + content_metadata_key_hierarchy_service + .getContentMetadataKeyHierarchiesByStatement( + statement.ToStatement())) + if 'results' in response and len(response['results']): + for content_metadata_key_hierarchy in response['results']: + # Print out some information for each content metadata key hierarchy. + print('Content metadata key hierarchy with ID "%d" and name "%s" was ' + 'found.\n' % (content_metadata_key_hierarchy['id'], + content_metadata_key_hierarchy['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py new file mode 100755 index 00000000..95eaa050 --- /dev/null +++ b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates content metadata key hierarchies. + +To determine which content metadata key hierarchies exist, run +get_all_content_metadata_key_hierarchies.py. + +This feature is only available to Video Solutions publishers. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the content metadata key hierarchy to update. +CONTENT_METADATA_KEY_HIERARCHY_ID = ( + 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') +# Set the ID of the custom targeting key to be added as a hierarchy level. +CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' + + +def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): + # Initialize appropriate service. + content_metadata_key_hierarchy_service = client.GetService( + 'ContentMetadataKeyHierarchyService', version='v201905') + + # Create a query to select a single content metadata key hierarchy. + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) + .Limit(1)) + + # Get a single content metadata key hierarchy by statement. + response = (content_metadata_key_hierarchy_service + .getContentMetadataKeyHierarchiesByStatement( + statement.ToStatement()))[0] + content_metadata_key_hierarchies = (response['results'] + if 'results' in response else None) + + if content_metadata_key_hierarchies: + content_metadata_key_hierarchy = content_metadata_key_hierarchies[0] + + # Update the content metadata key hierarchy by adding a hierarchy level. + hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels'] + + hierarchy_level = { + 'customTargetingKeyId': custom_targeting_key_id, + 'hierarchyLevel': str(len(hierarchy_levels) + 1) + } + + content_metadata_key_hierarchy['hierarchyLevels'] = ( + hierarchy_levels.append(hierarchy_level)) + + content_metadata_key_hierarchies = ( + content_metadata_key_hierarchy_service + .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies)) + + # Display results. + for content_metadata_key_hierarchy in content_metadata_key_hierarchies: + print ('Content metadata key hierarchy with id "%s" and name "%s"' + ' was updated.' % (content_metadata_key_hierarchy['id'], + content_metadata_key_hierarchy['name'])) + + else: + print 'No content metadata key hierarchies were found' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID, + CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201905/content_service/__init__.py b/examples/ad_manager/v201905/content_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/content_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/content_service/get_all_content.py b/examples/ad_manager/v201905/content_service/get_all_content.py new file mode 100755 index 00000000..48114111 --- /dev/null +++ b/examples/ad_manager/v201905/content_service/get_all_content.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 content. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + content_service = client.GetService('ContentService', version='v201905') + + # Create a statement to select content. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of content at a time, paging + # through until all content have been retrieved. + while True: + response = content_service.getContentByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for content in response['results']: + # Print out some information for each content. + print('Content with ID "%d" and name "%s" was found.\n' % + (content['id'], content['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_service/__init__.py b/examples/ad_manager/v201905/creative_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/creative_service/copy_image_creatives.py b/examples/ad_manager/v201905/creative_service/copy_image_creatives.py new file mode 100755 index 00000000..10f61ff5 --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/copy_image_creatives.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a copy of an image creative. + +To determine which image creatives exist, run get_image_creatives.py +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the line item to pause. +CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201905') + + # Create a statement to get the image creative. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', CREATIVE_ID)) + + # Get the creative. + query_result = creative_service.getCreativesByStatement( + statement.ToStatement()) + + image_creative = query_result['results'][0] + + # Build the new creative, set id to None to create a copy. + image_creative['id'] = None + image_creative['name'] = 'Copy of %s' % image_creative['name'] + + result = creative_service.createCreatives([image_creative])[0] + print ('A creative with ID %d, name "%s", and type "%s" was created and ' + 'can be previewed at: %s' % (result['id'], + result['name'], + ad_manager.AdManagerClassType(result), + result['previewUrl'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_service/create_creative_from_template.py b/examples/ad_manager/v201905/creative_service/create_creative_from_template.py new file mode 100755 index 00000000..e032be95 --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/create_creative_from_template.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates a new template creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. +To determine which creative templates exist, run +get_all_creative_templates.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import os +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201905') + + # Use the image banner with optional third party tracking template. + creative_template_id = '10000680' + + # Create image asset. + file_name = 'image%s.jpg' % uuid.uuid4() + image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', + 'medium_rectangle.jpg'), 'r').read() + size = { + 'width': '300', + 'height': '250' + } + asset = { + 'xsi_type': 'CreativeAsset', + 'fileName': file_name, + 'assetByteArray': image_data, + 'size': size + } + + # Create creative from templates. + creative = { + 'xsi_type': 'TemplateCreative', + 'name': 'Template Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': size, + 'creativeTemplateId': creative_template_id, + 'creativeTemplateVariableValues': [ + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Imagefile', + 'asset': asset + }, + { + 'xsi_type': 'LongCreativeTemplateVariableValue', + 'uniqueName': 'Imagewidth', + 'value': '300' + }, + { + 'xsi_type': 'LongCreativeTemplateVariableValue', + 'uniqueName': 'Imageheight', + 'value': '250' + }, + { + 'xsi_type': 'UrlCreativeTemplateVariableValue', + 'uniqueName': 'ClickthroughURL', + 'value': 'www.google.com' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Targetwindow', + 'value': '_blank' + } + ] + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print ('Template creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201905/creative_service/create_creatives.py b/examples/ad_manager/v201905/creative_service/create_creatives.py new file mode 100755 index 00000000..a6a94207 --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/create_creatives.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new image creatives for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. +To determine which creatives already exist, run get_all_creatives.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import os +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the advertiser (company) that all creatives will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201905') + + # Create creative objects. + creatives = [] + with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', + 'medium_rectangle.jpg'), 'r') as image: + image_data = image.read() + + for _ in xrange(5): + # Create creative size. + size = { + 'width': '300', + 'height': '250' + } + + # Create image asset. + creative_asset = { + 'xsi_type': 'CreativeAsset', + 'fileName': 'image.jpg', + 'assetByteArray': image_data, + 'size': size + } + + # Create an image creative. + creative = { + 'xsi_type': 'ImageCreative', + 'name': 'Image Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'destinationUrl': 'http://google.com', + 'size': size, + 'primaryImageAsset': creative_asset + } + + creatives.append(creative) + + # Add creatives. + creatives = creative_service.createCreatives(creatives) + + # Display results. + for creative in creatives: + print ('Image creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201905/creative_service/create_custom_creative.py b/examples/ad_manager/v201905/creative_service/create_custom_creative.py new file mode 100755 index 00000000..a057b2ca --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/create_custom_creative.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates a custom creative for a given advertiser. + +This feature is only available to Ad Manager 360 solution networks. To determine +which companies are advertisers, run get_advertisers.py. To determine +which creative templates exist, run get_all_creative_templates.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import os +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201905') + + # Get the image data for the creative. + image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', + 'medium_rectangle.jpg'), 'r').read() + + # Create the HTML snippet used in the custom creative. + html_snippet = ('
Click above for ' + 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%', + '%%FILE:IMAGE_ASSET%%') + + # Create custom creative. + creative = { + 'xsi_type': 'CustomCreative', + 'name': 'Custom Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '300', 'height': '250'}, + 'destinationUrl': 'http://google.com', + 'customCreativeAssets': [ + { + 'xsi_type': 'CustomCreativeAsset', + 'macroName': 'IMAGE_ASSET', + 'asset': { + 'assetByteArray': image_data, + 'fileName': 'image%s.jpg' % uuid.uuid4() + } + } + ], + 'htmlSnippet': html_snippet + } + + # Call service to create the creative. + creatives = creative_service.createCreatives([creative]) + + # Display results. + if creatives: + creative = creatives[0] + print ('Template creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201905/creative_service/create_native_creative.py b/examples/ad_manager/v201905/creative_service/create_native_creative.py new file mode 100755 index 00000000..a18e635b --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/create_native_creative.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates a new native creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. + +The code in this example will use app data from the Google sample app +'Pie Noon': + +https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import urllib2 +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO' + 'PYnTdOQGaSpGSEZflIFs0iw=h300') +APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp' + 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300') + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201905') + + # Use the system defined native app install creative template. + creative_template_id = '10004400' + + image_data = urllib2.urlopen(ICON_URL).read() + + app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() + + # Create creative from templates. + creative = { + 'xsi_type': 'TemplateCreative', + 'name': 'Native Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '1', 'height': '1', 'isAspectRatio': False}, + 'creativeTemplateId': creative_template_id, + 'destinationUrl': ('https://play.google.com/store/apps/details?id=' + 'com.google.fpl.pie_noon'), + 'creativeTemplateVariableValues': [ + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Image', + 'asset': { + 'assetByteArray': image_data, + 'fileName': 'file%s.png' % uuid.uuid4() + } + }, + { + 'xsi_type': 'AssetCreativeTemplateVariableValue', + 'uniqueName': 'Appicon', + 'asset': { + 'assetByteArray': app_icon_data, + 'fileName': 'appicon%s.png' % uuid.uuid4() + } + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Price', + 'value': 'Free' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Calltoaction', + 'value': 'Install' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Starrating', + 'value': '4' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Store', + 'value': 'Google Play' + }, + { + 'xsi_type': 'UrlCreativeTemplateVariableValue', + 'uniqueName': 'DeeplinkclickactionURL', + 'value': 'market://details?id=com.google.fpl.pie_noon' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Body', + 'value': 'Try multi-screen mode!' + }, + { + 'xsi_type': 'StringCreativeTemplateVariableValue', + 'uniqueName': 'Headline', + 'value': 'Pie Noon' + } + ] + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print ('Native creative with id "%s" and name "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], creative['previewUrl'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201905/creative_service/get_all_creatives.py b/examples/ad_manager/v201905/creative_service/get_all_creatives.py new file mode 100755 index 00000000..42faf3e3 --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/get_all_creatives.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creatives. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201905') + + # Create a statement to select creatives. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of creatives at a time, paging + # through until all creatives have been retrieved. + while True: + response = creative_service.getCreativesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for creative in response['results']: + # Print out some information for each creative. + print('Creative with ID "%d" and name "%s" was found.\n' % + (creative['id'], creative['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_service/get_image_creatives.py b/examples/ad_manager/v201905/creative_service/get_image_creatives.py new file mode 100755 index 00000000..b78e8c94 --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/get_image_creatives.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 image creatives. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201905') + # Create a statement to select creatives. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('creativeType = :creativeType') + .WithBindVariable('creativeType', 'ImageCreative')) + + # Retrieve a small amount of creatives at a time, paging + # through until all creatives have been retrieved. + while True: + response = creative_service.getCreativesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for creative in response['results']: + # Print out some information for each creative. + print('Creative with ID "%d" and name "%s" was found.\n' % + (creative['id'], creative['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_service/update_creatives.py b/examples/ad_manager/v201905/creative_service/update_creatives.py new file mode 100755 index 00000000..6e24b483 --- /dev/null +++ b/examples/ad_manager/v201905/creative_service/update_creatives.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates the destination URL of a single image creative. + +To determine which image creatives exist, run get_all_creatives.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE' + + +def main(client, image_creative_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v201905') + + # Create statement object to get the creative by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('creativeType = :type AND id = :id') + .WithBindVariable('type', 'ImageCreative') + .WithBindVariable('id', long(image_creative_id)) + .Limit(1)) + + # Get creatives by statement. + response = creative_service.getCreativesByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local creative object by changing its destination URL. + updated_creatives = [] + for creative in response['results']: + creative['destinationUrl'] = 'http://news.google.com' + updated_creatives.append(creative) + + # Update creatives remotely. + creatives = creative_service.updateCreatives(updated_creatives) + + # Display results. + for creative in creatives: + print ('Image creative with id "%s" and destination URL "%s" was ' + 'updated.' % (creative['id'], creative['destinationUrl'])) + else: + print 'No creatives found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, IMAGE_CREATIVE_ID) diff --git a/examples/ad_manager/v201905/creative_set_service/__init__.py b/examples/ad_manager/v201905/creative_set_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/creative_set_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py new file mode 100755 index 00000000..5152137d --- /dev/null +++ b/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. + +"""Creates a line item creative association for a creative set. + +To create creative sets, run create_creative_set.py. To create creatives, run +create_creatives.py. To determine which LICAs exist, run get_all_licas.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client, creative_set_id, line_item_id): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v201905') + + # Create LICA for a creative set. + lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} + + # Add LICA. + lica = lica_service.createLineItemCreativeAssociations([lica]) + + # Display results. + print (('LICA with line item ID "%s" and creative set ID "%s" was ' + 'created.') % (lica['lineItemId'], lica['creativeSetId'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_SET_ID, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201905/creative_set_service/create_creative_set.py b/examples/ad_manager/v201905/creative_set_service/create_creative_set.py new file mode 100755 index 00000000..5d07e01d --- /dev/null +++ b/examples/ad_manager/v201905/creative_set_service/create_creative_set.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new creative sets. + +To determine which creative sets exist, run get_all_creative_sets.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' +COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' + + +def main(client, master_creative_id, companion_creative_id): + # Initialize appropriate service. + creative_set_service = client.GetService('CreativeSetService', + version='v201905') + + # Create creative set objects. + creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), + 'masterCreativeId': master_creative_id, + 'companionCreativeIds': [companion_creative_id]} + + # Add creative sets. + creative_set = creative_set_service.createCreativeSet(creative_set) + + # Display results. + if creative_set: + print (('Creative set with ID "%s", master creative ID "%s", and ' + 'companion creative IDs {%s} was created.') + % (creative_set['id'], creative_set['masterCreativeId'], + ','.join(creative_set['companionCreativeIds']))) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) diff --git a/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py new file mode 100755 index 00000000..90ea61c7 --- /dev/null +++ b/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creative sets. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + creative_set_service = client.GetService( + 'CreativeSetService', version='v201905') + + # Create a statement to select creative sets. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of creative sets at a time, paging + # through until all creative sets have been retrieved. + while True: + response = creative_set_service.getCreativeSetsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for creative_set in response['results']: + # Print out some information for each creative set. + print('Creative set with ID "%d" and name "%s" was found.\n' % + (creative_set['id'], creative_set['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py new file mode 100755 index 00000000..1a933ead --- /dev/null +++ b/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creative sets for a master creative. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' + + +def main(client, master_creative_id): + # Initialize appropriate service. + creative_set_service = client.GetService( + 'CreativeSetService', version='v201905') + # Create a statement to select creative sets. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('masterCreativeId = :masterCreativeId') + .WithBindVariable('masterCreativeId', master_creative_id)) + + # Retrieve a small amount of creative sets at a time, paging + # through until all creative sets have been retrieved. + while True: + response = creative_set_service.getCreativeSetsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for creative_set in response['results']: + # Print out some information for each creative set. + print('Creative set with ID "%d" and name "%s" was found.\n' % + (creative_set['id'], creative_set['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, MASTER_CREATIVE_ID) diff --git a/examples/ad_manager/v201905/creative_set_service/update_creative_set.py b/examples/ad_manager/v201905/creative_set_service/update_creative_set.py new file mode 100755 index 00000000..496da05f --- /dev/null +++ b/examples/ad_manager/v201905/creative_set_service/update_creative_set.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates a creative set by adding a companion creative. + +To determine which creative sets exist, run get_all_creative_sets.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the creative set to update. +CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' +COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' + + +def main(client, creative_set_id, companion_creative_id): + # Initialize appropriate service. + creative_set_service = client.GetService('CreativeSetService', + version='v201905') + + # Create statement to select a single creative set by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :creativeSetId') + .WithBindVariable('creativeSetId', long(creative_set_id))) + + # Get creative set. + response = creative_set_service.getCreativeSetsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + updated_created_sets = [] + for creative_set in response['results']: + creative_set['companionCreativeIds'].append(companion_creative_id) + updated_created_sets.append(creative_set) + + # Update the creative sets on the server. + creative_sets = creative_set_service.updateCreativeSet(updated_created_sets) + + # Display results. + for creative_set in creative_sets: + print (('Creative set with ID "%s", master creative ID "%s", and ' + 'companion creative IDs {%s} was updated.') + % (creative_set['id'], creative_set['masterCreativeId'], + ','.join(creative_set['companionCreativeIds']))) + else: + print 'No creative sets found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) diff --git a/examples/ad_manager/v201905/creative_template_service/__init__.py b/examples/ad_manager/v201905/creative_template_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/creative_template_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py new file mode 100755 index 00000000..7dc1d16b --- /dev/null +++ b/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creative templates. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + creative_template_service = client.GetService( + 'CreativeTemplateService', version='v201905') + + # Create a statement to select creative templates. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of creative templates at a time, paging + # through until all creative templates have been retrieved. + while True: + response = creative_template_service.getCreativeTemplatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for creative_template in response['results']: + # Print out some information for each creative template. + print('Creative template with ID "%d" and name "%s" was found.\n' % + (creative_template['id'], creative_template['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py new file mode 100755 index 00000000..a6dc1392 --- /dev/null +++ b/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 system defined creative templates. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + creative_template_service = client.GetService( + 'CreativeTemplateService', version='v201905') + # Create a statement to select creative templates. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('type = :type') + .WithBindVariable('type', 'SYSTEM_DEFINED')) + + # Retrieve a small amount of creative templates at a time, paging + # through until all creative templates have been retrieved. + while True: + response = creative_template_service.getCreativeTemplatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for creative_template in response['results']: + # Print out some information for each creative template. + print('Creative template with ID "%d" and name "%s" was found.\n' % + (creative_template['id'], creative_template['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py new file mode 100755 index 00000000..7cdae657 --- /dev/null +++ b/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates a new creative wrapper. + +Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and +applied to ad units by AdUnit.appliedLabels. To determine which creative +wrappers exist, run get_all_creative_wrappers.py + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE' + + +def main(client, label_id): + # Initialize appropriate service. + creative_wrapper_service = client.GetService('CreativeWrapperService', + version='v201905') + + # Create creative wrapper objects. + creative_wrapper = { + # A label can only be associated with one creative wrapper. + 'labelId': label_id, + 'ordering': 'INNER', + 'htmlHeader': 'My creative wrapper header', + 'htmlFooter': 'My creative wrapper footer' + } + + # Add creative wrapper. + creative_wrappers = creative_wrapper_service.createCreativeWrappers( + [creative_wrapper]) + + # Display results. + for creative_wrapper in creative_wrappers: + print ('Creative wrapper with ID "%s" applying to label "%s" was ' + 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py new file mode 100755 index 00000000..6b67424f --- /dev/null +++ b/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example deactivates a creative wrapper belonging to a label. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, label_id): + # Initialize appropriate service. + creative_wrapper_service = client.GetService('CreativeWrapperService', + version='v201905') + + # Create a query to select the active creative wrappers for the given label. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status AND labelId = :labelId') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('labelId', long(label_id))) + + creative_wrappers_deactivated = 0 + + # Get creative wrappers by statement. + while True: + response = creative_wrapper_service.getCreativeWrappersByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + # Display results. + for creative_wrapper in response['results']: + print ('Creative wrapper with ID "%s" applying to label "%s" with ' + 'status "%s" will be deactivated.' % + (creative_wrapper['id'], + creative_wrapper['labelId'], + creative_wrapper['status'])) + # Perform action. + result = creative_wrapper_service.performCreativeWrapperAction( + {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + creative_wrappers_deactivated += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if creative_wrappers_deactivated > 0: + print ('Number of creative wrappers deactivated: %s' % + creative_wrappers_deactivated) + else: + print 'No creative wrappers were deactivated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) diff --git a/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py new file mode 100755 index 00000000..632cdd46 --- /dev/null +++ b/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 active creative wrappers. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + creative_wrapper_service = client.GetService( + 'CreativeWrapperService', version='v201905') + # Create a statement to select creative wrappers. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) + + # Retrieve a small amount of creative wrappers at a time, paging + # through until all creative wrappers have been retrieved. + while True: + response = creative_wrapper_service.getCreativeWrappersByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for creative_wrapper in response['results']: + # Print out some information for each creative wrapper. + print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % + (creative_wrapper['id'], creative_wrapper['labelId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py new file mode 100755 index 00000000..6a79e769 --- /dev/null +++ b/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creative wrappers. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + creative_wrapper_service = client.GetService( + 'CreativeWrapperService', version='v201905') + + # Create a statement to select creative wrappers. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of creative wrappers at a time, paging + # through until all creative wrappers have been retrieved. + while True: + response = creative_wrapper_service.getCreativeWrappersByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for creative_wrapper in response['results']: + # Print out some information for each creative wrapper. + print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % + (creative_wrapper['id'], creative_wrapper['labelId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py new file mode 100755 index 00000000..254cc98e --- /dev/null +++ b/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates a creative wrapper to the 'OUTER' wrapping order. + +To determine which creative wrappers exist, run get_all_creative_wrappers.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the creative wrapper to update. +CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE' + + +def main(client, creative_wrapper_id): + # Initialize appropriate service. + creative_wrapper_service = client.GetService('CreativeWrapperService', + version='v201905') + + # Create statement to get a creative wrapper by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :creativeWrapperId') + .WithBindVariable('creativeWrapperId', + long(creative_wrapper_id))) + + # Get creative wrappers. + response = creative_wrapper_service.getCreativeWrappersByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + updated_creative_wrappers = [] + for creative_wrapper in response['results']: + creative_wrapper['ordering'] = 'OUTER' + updated_creative_wrappers.append(creative_wrapper) + + # Update the creative wrappers on the server. + creative_wrappers = creative_wrapper_service.updateCreativeWrappers( + updated_creative_wrappers) + + # Display results. + for creative_wrapper in creative_wrappers: + print (('Creative wrapper with ID "%s" and wrapping order "%s" ' + 'was updated.') % (creative_wrapper['id'], + creative_wrapper['ordering'])) + else: + print 'No creative wrappers found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CREATIVE_WRAPPER_ID) diff --git a/examples/ad_manager/v201905/custom_field_service/__init__.py b/examples/ad_manager/v201905/custom_field_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/custom_field_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py new file mode 100755 index 00000000..268f6bac --- /dev/null +++ b/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates custom field options for a drop-down custom field. + +Once created, custom field options can be found under the options fields of the +drop-down custom field and they cannot be deleted. To determine which custom +fields exist, run get_all_custom_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the drop-down custom field to create options for. +CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' + + +def main(client, custom_field_id): + # Initialize appropriate service. + custom_field_service = client.GetService( + 'CustomFieldService', version='v201905') + + # Create custom field options. + custom_field_options = [ + { + 'displayName': 'Approved', + 'customFieldId': custom_field_id + }, + { + 'displayName': 'Unapproved', + 'customFieldId': custom_field_id + } + ] + + # Add custom field options. + custom_field_options = custom_field_service.createCustomFieldOptions( + custom_field_options) + + # Display results. + for custom_field_option in custom_field_options: + print ('Custom field option with ID "%s" and name "%s" was created.' + % (custom_field_option['id'], custom_field_option['displayName'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py new file mode 100755 index 00000000..3fea59d7 --- /dev/null +++ b/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates custom fields. + +To determine which custom fields exist, run get_all_custom_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + custom_field_service = client.GetService( + 'CustomFieldService', version='v201905') + + # Create custom field objects. + custom_fields = [ + { + 'name': 'Customer comments #%s' % uuid.uuid4(), + 'entityType': 'LINE_ITEM', + 'dataType': 'STRING', + 'visibility': 'FULL' + }, { + 'name': 'Internal approval status #%s' % uuid.uuid4(), + 'entityType': 'LINE_ITEM', + 'dataType': 'DROP_DOWN', + 'visibility': 'FULL' + } + ] + + # Add custom fields. + custom_fields = custom_field_service.createCustomFields(custom_fields) + + # Display results. + for custom_field in custom_fields: + print ('Custom field with ID "%s" and name "%s" was created.' + % (custom_field['id'], custom_field['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py new file mode 100755 index 00000000..c3a1b579 --- /dev/null +++ b/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 deactivates all active line items custom fields. + +To determine which custom fields exist, run get_all_custom_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + custom_field_service = client.GetService( + 'CustomFieldService', version='v201905') + + # Create statement to select only active custom fields that apply to + # line items. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('entityType = :entityType and isActive = :isActive') + .WithBindVariable('entityType', 'LINE_ITEM') + .WithBindVariable('isActive', True)) + + custom_fields_deactivated = 0 + + # Get custom fields by statement. + while True: + response = custom_field_service.getCustomFieldsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + # Display results. + for custom_field in response['results']: + print ('Custom field with ID "%s" and name "%s" will' + ' be deactivated.' % (custom_field['id'], custom_field['name'])) + result = custom_field_service.performCustomFieldAction( + {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + custom_fields_deactivated += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + if custom_fields_deactivated > 0: + print 'Number of custom fields deactivated: %s' % custom_fields_deactivated + else: + print 'No custom fields were deactivated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py new file mode 100755 index 00000000..54cd336c --- /dev/null +++ b/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 fields. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + custom_field_service = client.GetService( + 'CustomFieldService', version='v201905') + + # Create a statement to select custom fields. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of custom fields at a time, paging + # through until all custom fields have been retrieved. + while True: + response = custom_field_service.getCustomFieldsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for custom_field in response['results']: + # Print out some information for each custom field. + print('Custom field with ID "%d" and name "%s" was found.\n' % + (custom_field['id'], custom_field['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py new file mode 100755 index 00000000..babb1efd --- /dev/null +++ b/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 fields that can be applied to line items. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + custom_field_service = client.GetService( + 'CustomFieldService', version='v201905') + # Create a statement to select custom fields. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('entityType = :entityType') + .WithBindVariable('entityType', 'LINE_ITEM')) + + # Retrieve a small amount of custom fields at a time, paging + # through until all custom fields have been retrieved. + while True: + response = custom_field_service.getCustomFieldsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for custom_field in response['results']: + # Print out some information for each custom field. + print('Custom field with ID "%d" and name "%s" was found.\n' % + (custom_field['id'], custom_field['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py new file mode 100755 index 00000000..b996819d --- /dev/null +++ b/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 sets custom field values on a line item. + +To determine which custom fields exist, run get_all_custom_fields.py. +To determine which line item exist, run get_all_line_items.py. +To create custom field options, run create_custom_field_options.py + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the custom fields, custom field option, and line item. +CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' +DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' +CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE' +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client, custom_field_id, drop_down_custom_field_id, + custom_field_option_id, line_item_id): + # Initialize appropriate services. + custom_field_service = client.GetService( + 'CustomFieldService', version='v201905') + + line_item_service = client.GetService('LineItemService', version='v201905') + + # Create statement to get a custom field. + custom_field_statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', custom_field_id) + .Limit(1)) + + # Get custom field. + custom_field = custom_field_service.getCustomFieldsByStatement( + custom_field_statement.ToStatement())['results'][0] + + # Create statement to get a drop down custom field. + drop_down_custom_field_statement = ( + ad_manager.StatementBuilder(version='v201905') + .Where('id = :dropDownCustomFieldId') + .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) + .Limit(1)) + + # Get drop-down custom field. + drop_down_custom_field = custom_field_service.getCustomFieldsByStatement( + drop_down_custom_field_statement.ToStatement())['results'][0] + + # Create statement to get a line item. + line_item_statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', line_item_id) + .Limit(1)) + + # Get line item. + line_item = line_item_service.getLineItemsByStatement( + line_item_statement.ToStatement())['results'][0] + + if custom_field and line_item: + # Create custom field values. + custom_field_value = { + 'customFieldId': custom_field['id'], + 'xsi_type': 'CustomFieldValue', + 'value': { + 'xsi_type': 'TextValue', + 'value': 'Custom field value' + } + } + + drop_down_custom_field_value = { + 'customFieldId': drop_down_custom_field['id'], + 'xsi_type': 'DropDownCustomFieldValue', + 'customFieldOptionId': custom_field_option_id, + } + + custom_field_values = [custom_field_value, drop_down_custom_field_value] + + old_custom_field_values = [] + if 'customFieldValues' in line_item: + old_custom_field_values = line_item['customFieldValues'] + + # Only add existing custom field values for different custom fields than the + # ones you are setting. + for old_custom_field_value in old_custom_field_values: + if (old_custom_field_value['customFieldId'] != + custom_field_value['customFieldId'] + and old_custom_field_value['customFieldId'] != + drop_down_custom_field_value['customFieldId']): + custom_field_values.append(old_custom_field_value) + + line_item['customFieldValues'] = custom_field_values + + # Update the line item on the server. + line_items = line_item_service.updateLineItems([line_item]) + + # Display results. + for line_item in line_items: + custom_field_value_strings = [] + for value in line_item['customFieldValues']: + if ad_manager.AdManagerClassType(value) == 'CustomFieldValue': + custom_field_value_string = ( + '{ID: "%s", value: "%s"}' + % (value['customFieldId'], value['value']['value'])) + elif ad_manager.AdManagerClassType(value) == 'DropDownCustomFieldValue': + custom_field_value_string = ( + '{ID: "%s", custom field option ID: "%s"}' + % (value['customFieldId'], value['customFieldOptionId'])) + custom_field_value_strings.append(custom_field_value_string) + print ('Line item with ID "%s" set with custom field values %s.' + % (line_item['id'], ','.join(custom_field_value_strings))) + else: + print 'Line item or custom field not found.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, + CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py new file mode 100755 index 00000000..7cfb3b88 --- /dev/null +++ b/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates custom field descriptions. + +To determine which custom fields exist, run get_all_custom_fields.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the custom field to update. +CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' + + +def main(client, custom_field_id): + # Initialize appropriate service. + custom_field_service = client.GetService( + 'CustomFieldService', version='v201905') + + # Create statement to get a custom field. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :customFieldId') + .WithBindVariable('customFieldId', long(custom_field_id))) + + # Get custom field. + custom_fields = custom_field_service.getCustomsFieldByStatement( + statement.ToStatement()) + + if custom_fields: + for custom_field in custom_fields: + custom_field['description'] += ' Updated.' + + # Update the custom field on the server. + custom_fields = custom_field_service.updateCustomFields(custom_fields) + + # Display results. + for custom_field in custom_fields: + print (('Custom field with ID "%s", name "%s", and ' + 'description "%s" was updated.') + % (custom_field['id'], custom_field['name'], + custom_field['description'])) + else: + print 'No custom fields found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/ad_manager/v201905/custom_targeting_service/__init__.py b/examples/ad_manager/v201905/custom_targeting_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/custom_targeting_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..9c1fb171 --- /dev/null +++ b/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates new custom targeting keys and values. + +To determine which custom targeting keys and values exist, run +get_all_custom_targeting_keys_and_values.py. To target these custom targeting +keys and values, run target_custom_criteria_example.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201905') + + # Create custom targeting key objects. + keys = [ + { + 'displayName': 'gender', + 'name': 'g', + 'type': 'PREDEFINED' + }, + { + 'displayName': 'car model', + 'name': 'c', + 'type': 'FREEFORM' + }, + # Add predefined key that may be use for content targeting. + { + 'displayName': 'genre', + 'name': 'genre', + 'type': 'PREDEFINED' + } + ] + + # Add custom targeting keys. + keys = custom_targeting_service.createCustomTargetingKeys(keys) + + # Display results. + if keys: + for key in keys: + print ('A custom targeting key with id "%s", name "%s", and display ' + 'name "%s" was created.' % (key['id'], key['name'], + key['displayName'])) + else: + print 'No keys were created.' + + # Create custom targeting value objects. + values = [ + { + 'customTargetingKeyId': keys[0]['id'], + 'displayName': 'male', + # Name is set to 1 so that the actual name can be hidden from website + # users. + 'name': '1', + 'matchType': 'EXACT' + }, + { + 'customTargetingKeyId': keys[0]['id'], + 'displayName': 'female', + # Name is set to 2 so that the actual name can be hidden from website + # users. + 'name': '2', + 'matchType': 'EXACT' + }, + { + 'customTargetingKeyId': keys[1]['id'], + 'displayName': 'honda civic', + 'name': 'honda civic', + 'matchType': 'EXACT' + }, + { + 'customTargetingKeyId': keys[1]['id'], + 'displayName': 'toyota', + 'name': 'toyota', + 'matchType': 'EXACT' + }, + { + 'customTargetingKeyId': keys[2]['id'], + 'displayName': 'comedy', + 'name': 'comedy', + 'matchType': 'EXACT' + }, + { + 'customTargetingKeyId': keys[2]['id'], + 'displayName': 'drama', + 'name': 'drama', + 'matchType': 'EXACT' + } + ] + + # Add custom targeting values. + values = custom_targeting_service.createCustomTargetingValues(values) + + # Display results. + if values: + for value in values: + print ('A custom targeting value with id "%s", belonging to key with id' + ' "%s", name "%s", and display name "%s" was created.' + % (value['id'], value['customTargetingKeyId'], value['name'], + value['displayName'])) + else: + print 'No values were created.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py new file mode 100755 index 00000000..8d4df693 --- /dev/null +++ b/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 deletes a custom targeting key by its name. + +To determine which custom targeting keys exist, run +get_all_custom_targeting_keys_and_values.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE' + + +def main(client, key_name): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201905') + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('name = :name') + .WithBindVariable('name', key_name)) + + deleted_custom_targeting_keys = 0 + + # Get custom targeting keys. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + key_ids = [str(key['id']) for key in response['results']] + action = {'xsi_type': 'DeleteCustomTargetingKeys'} + key_statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id IN (%s)' % ', '.join(key_ids))) + + # Delete custom targeting keys. + result = custom_targeting_service.performCustomTargetingKeyAction( + action, key_statement.ToStatement()) + + if result and int(result['numChanges']) > 0: + deleted_custom_targeting_keys += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + if deleted_custom_targeting_keys > 0: + print ('Number of custom targeting keys deleted: %s' + % deleted_custom_targeting_keys) + else: + print 'No custom targeting keys were deleted.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, KEY_NAME) diff --git a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py new file mode 100755 index 00000000..b543ac7c --- /dev/null +++ b/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. + +"""Deletes custom targeting values for a given custom targeting key. + +To determine which custom targeting keys and values exist, run +get_all_custom_targeting_keys_and_values.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' + + +def main(client, key_id): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201905') + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', key_id)) + + deleted_custom_targeting_values = 0 + + # Get custom targeting values. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + value_ids = [value['id'] for value in response['results']] + action = {'xsi_type': 'DeleteCustomTargetingValues'} + value_statement = (ad_manager.StatementBuilder(version='v201905') + .Where('customTargetingKeyId = :keyId ' + 'AND id IN (%s)' % ', '.join(value_ids)) + .WithBindVariable('keyId', key_id)) + + # Delete custom targeting values. + result = custom_targeting_service.performCustomTargetingValueAction( + action, value_statement.ToStatement()) + if result and int(result['numChanges']) > 0: + deleted_custom_targeting_values += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + if deleted_custom_targeting_values > 0: + print ('Number of custom targeting values deleted: %s' + % deleted_custom_targeting_values) + else: + print 'No custom targeting values were deleted.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, KEY_ID) diff --git a/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..cb2d440b --- /dev/null +++ b/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 targeting keys and values. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201905') + + # Create statement to get all targeting keys. + targeting_key_statement = ad_manager.StatementBuilder(version='v201905') + + all_keys = [] + + # Get custom targeting keys by statement. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + targeting_key_statement.ToStatement()) + if 'results' in response and len(response['results']): + all_keys.extend(response['results']) + targeting_key_statement.offset += targeting_key_statement.limit + else: + break + + if all_keys: + # Create a statement to select custom targeting values. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('customTargetingKeyId IN (%s)' % + ', '.join([str(key['id']) for key in all_keys]))) + + # Retrieve a small amount of custom targeting values at a time, paging + # through until all custom targeting values have been retrieved. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for custom_targeting_value in response['results']: + # Print out some information for each custom targeting value. + print('Custom targeting value with ID "%d", name "%s", display name ' + '"%s", and custom targeting key ID "%d" was found.\n' % + (custom_targeting_value['id'], custom_targeting_value['name'], + custom_targeting_value['displayName'], + custom_targeting_value['customTargetingKeyId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py new file mode 100755 index 00000000..202e4d85 --- /dev/null +++ b/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 targeting keys and values. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201905') + + # Create statement to get targeting keys for predefined values. + targeting_key_statement = (ad_manager.StatementBuilder(version='v201905') + .Where('type = :type') + .WithBindVariable('type', 'PREDEFINED')) + + all_keys = [] + + # Get custom targeting keys by statement. + while True: + response = custom_targeting_service.getCustomTargetingKeysByStatement( + targeting_key_statement.ToStatement()) + if 'results' in response and len(response['results']): + all_keys.extend(response['results']) + targeting_key_statement.offset += targeting_key_statement.limit + else: + break + + if all_keys: + # Create a statement to select custom targeting values. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('customTargetingKeyId IN (:ids)') + .WithBindVariable('ids', [key['id'] for key in all_keys])) + + # Retrieve a small amount of custom targeting values at a time, paging + # through until all custom targeting values have been retrieved. + while True: + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for custom_targeting_value in response['results']: + # Print out some information for each custom targeting value. + print('Custom targeting value with ID "%d", name "%s", display name ' + '"%s", and custom targeting key ID "%d" was found.\n' % + (custom_targeting_value['id'], custom_targeting_value['name'], + custom_targeting_value['displayName'], + custom_targeting_value['customTargetingKeyId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py new file mode 100755 index 00000000..08f63dc5 --- /dev/null +++ b/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates the display name of a single custom targeting key. + +To determine which custom targeting keys exist, run +get_all_custom_targeting_keys_and_values.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' + + +def main(client, key_id): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201905') + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :keyId') + .WithBindVariable('keyId', long(key_id)) + .Limit(1)) + + # Get custom targeting keys by statement. + response = custom_targeting_service.getCustomTargetingKeysByStatement( + statement.ToStatement()) + + # Update each local custom targeting key object by changing its display name. + if 'results' in response and len(response['results']): + updated_keys = [] + for key in response['results']: + if not key['displayName']: + key['displayName'] = key['name'] + key['displayName'] += ' (Deprecated)' + updated_keys.append(key) + keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys) + + # Display results. + if keys: + for key in keys: + print ('Custom targeting key with id "%s", name "%s", display name ' + '"%s", and type "%s" was updated.' + % (key['id'], key['name'], key['displayName'], key['type'])) + else: + print 'No custom targeting keys were found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py new file mode 100755 index 00000000..53f95599 --- /dev/null +++ b/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. + +"""Updates name of custom targeting values belonging to a custom targeting key. + +To determine which custom targeting keys exist, run +get_all_custom_targeting_keys_and_values.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' + + +def main(client, key_id): + # Initialize appropriate service. + custom_targeting_service = client.GetService( + 'CustomTargetingService', version='v201905') + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('customTargetingKeyId = :keyId') + .WithBindVariable('keyId', long(key_id))) + + while True: + # Get custom targeting values by statement. + response = custom_targeting_service.getCustomTargetingValuesByStatement( + statement.ToStatement()) + + # Update each local custom targeting value object by changing its name. + if 'results' in response and len(response['results']): + updated_values = [] + for value in response['results']: + if not value['displayName']: + value['displayName'] = value['name'] + value['displayName'] += ' (Deprecated)' + updated_values.append(value) + values = custom_targeting_service.updateCustomTargetingValues( + updated_values) + + # Display results. + for value in values: + print ('Custom targeting value with id "%s", name "%s", and display' + ' name "%s" was updated.' + % (value['id'], value['name'], value['displayName'])) + statement.offset += statement.limit + else: + break + + if response['totalResultSetSize'] == 0: + print 'No custom targeting values were updated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201905/exchange_rate_service/__init__.py b/examples/ad_manager/v201905/exchange_rate_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/exchange_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py new file mode 100755 index 00000000..cdc43a10 --- /dev/null +++ b/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates an exchange rate. + +To determine which exchange rates exist, run get_all_exchange_rates.py. + + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201905') + + # Create a new fixed exchange rate with currency code 'AUD', with direction + # FROM_NETWORK with a value of 1.5. + exchange_rate = { + 'currencyCode': 'AUD', + 'direction': 'FROM_NETWORK', + 'exchangeRate': long(15000000000), + 'refreshRate': 'FIXED' + } + + created_exchange_rate = exchange_rate_service.createExchangeRates( + [exchange_rate])[0] + + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was created.' % (created_exchange_rate['id'], + created_exchange_rate['currencyCode'], + created_exchange_rate['direction'], + (float(created_exchange_rate['exchangeRate']) / + 10000000000))) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py new file mode 100755 index 00000000..870df735 --- /dev/null +++ b/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 exchange rates. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + exchange_rate_service = client.GetService( + 'ExchangeRateService', version='v201905') + + # Create a statement to select exchange rates. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of exchange rates at a time, paging + # through until all exchange rates have been retrieved. + while True: + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for exchange_rate in response['results']: + # Print out some information for each exchange rate. + print( + 'Exchange rate with ID "%d", currency code "%s", direction "%s", ' + 'and exchange rate "%d" was found.\n' % + (exchange_rate['id'], exchange_rate['currencyCode'], + exchange_rate['direction'], exchange_rate['exchangeRate'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py new file mode 100755 index 00000000..3591b4a3 --- /dev/null +++ b/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the exchange rate for a specific currency code. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' + + +def main(client, currency_code): + # Initialize appropriate service. + exchange_rate_service = client.GetService( + 'ExchangeRateService', version='v201905') + # Create a statement to select exchange rates. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('currencyCode = :currencyCode') + .WithBindVariable('currencyCode', currency_code)) + + # Retrieve a small amount of exchange rates at a time, paging + # through until all exchange rates have been retrieved. + while True: + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for exchange_rate in response['results']: + # Print out some information for each exchange rate. + print('Exchange rate with ID "%d", currency code "%s", and exchange ' + 'rate "%.2f" was found.\n' % + (exchange_rate['id'], exchange_rate['currencyCode'], + float(exchange_rate['exchangeRate'] / 1000000))) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CURRENCY_CODE) diff --git a/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py new file mode 100755 index 00000000..8132155a --- /dev/null +++ b/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates the value of an exchange rate. + +To create exchange rates, run create_exchange_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' + + +def main(client, exchange_rate_id): + # Initialize appropriate service. + exchange_rate_service = client.GetService('ExchangeRateService', + version='v201905') + + # Create a statement to get an exchange rate by its ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', long(exchange_rate_id)) + .Limit(1)) + + # Get rate cards by statement. + response = exchange_rate_service.getExchangeRatesByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + exchange_rate = response['results'][0] + + # Update the exchange rate value to 1.5. + exchange_rate['exchangeRate'] = long(15000000000) + + exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) + + if exchange_rates: + for exchange_rate in exchange_rates: + print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was updated.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) + else: + print 'No exchange rates were updated.' + else: + print 'No exchange rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, EXCHANGE_RATE_ID) diff --git a/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py new file mode 100755 index 00000000..88fc8ae8 --- /dev/null +++ b/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 a forecast for a prospective line item. + +The prospective line item targets the entire network. The targeting can be +modified to determine forecasts for other criteria such as custom criteria +targeting (in addition to targeting the whole network). See +create_line_items.py for an example of how to create more complex targeting. + +""" + + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set the ID of the advertiser (company) to forecast for. Setting an advertiser +# will cause the forecast to apply the appropriate unified blocking rules. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201905') + network_service = client.GetService('NetworkService', version='v201905') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + + now_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = now_datetime + datetime.timedelta(days=5) + + # Create prospective line item. + line_item = { + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + } + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + }, + 'isAmpOnly': True, + }, + { + 'size': { + 'width': '120', + 'height': '600' + } + } + ], + 'lineItemType': 'SPONSORSHIP', + 'startDateTimeType': 'IMMEDIATELY', + 'endDateTime': end_datetime, + 'costType': 'CPM', + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'primaryGoal': { + 'units': '50', + 'unitType': 'IMPRESSIONS', + 'goalType': 'DAILY' + }, + 'contractedUnitsBought': '100', + 'creativeRotationType': 'EVEN', + 'discountType': 'PERCENTAGE', + } + + prospective_line_item = { + 'lineItem': line_item, + 'advertiserId': advertiser_id + } + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + # The field includeTargetingCriteriaBreakdown can only be set if + # breakdowns are not manually specified. + # 'includeTargetingCriteriaBreakdown': True, + 'breakdown': { + 'timeWindows': [ + now_datetime, + now_datetime + datetime.timedelta(days=1), + now_datetime + datetime.timedelta(days=2), + now_datetime + datetime.timedelta(days=3), + now_datetime + datetime.timedelta(days=4), + end_datetime + ], + 'targets': [ + { + # Optional, the name field is only used to identify this + # breakdown in the response. + 'name': 'United States', + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '2840', + 'displayName': 'US' + } + ] + } + } + }, + { + # Optional, the name field is only used to identify this + # breakdown in the response. + 'name': 'Geneva', + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '20133', + 'displayName': 'Geneva' + } + ] + } + } + } + ] + } + } + + # Get forecast. + forecast = forecast_service.getAvailabilityForecast( + prospective_line_item, forecast_options) + matched = forecast['matchedUnits'] + available = forecast['availableUnits'] + possible = forecast['possibleUnits'] if 'possibleUnits' in forecast else None + unit_type = forecast['unitType'].lower() + + available_percent_overall, possible_percent_overall = CalculateForecastStats( + matched, available, possible) + + contending_line_items = getattr(forecast, 'contendingLineItems', []) + + # Display results. + print '%s %s matched overall.' % (matched, unit_type) + print '%s%% %s available overall.' % (available_percent_overall, unit_type) + print '%d contending line items overall.' % len(contending_line_items) + if possible: + print '%s%% %s possible overall.' % (possible_percent_overall, unit_type) + + if 'breakdowns' in forecast and len(forecast['breakdowns']): + for breakdown in forecast['breakdowns']: + print 'For breakdown time period %s - %s:' % ( + FormatSOAPDateTime(breakdown['startTime']), + FormatSOAPDateTime(breakdown['endTime'])) + for breakdown_entry in breakdown['breakdownEntries']: + matched = breakdown_entry['forecast']['matched'] + available = breakdown_entry['forecast']['available'] + possible = (breakdown_entry['forecast']['possible'] + if 'possible' in breakdown_entry['forecast'] else None) + name = breakdown_entry['name'] if 'name' in breakdown_entry else None + if name: + print '\tFor targeting breakdown named \'%s\'' % name + available_percent, possible_percent = CalculateForecastStats( + matched, available, possible) + print '\t\t%s %s matched.' % (matched, unit_type) + print '\t\t%s%% %s available.' % (available_percent, unit_type) + if possible: + print '\t\t%s%% %s possible.' % (possible_percent, unit_type) + + +def FormatSOAPDateTime(value): + """Format a SOAP DateTime object for printing. + + Args: + value: The DateTime object to format. + + Returns: + A string representing the value. + """ + value_date = value['date'] + return '%s-%s-%s %s:%s:%s (%s)' % ( + value_date['year'], value_date['month'], value_date['day'], + value['hour'], value['minute'], value['second'], value['timeZoneId']) + + +def CalculateForecastStats(matched, available, possible=None): + """Calculate forecast percentage stats. + + Args: + matched: The number of matched impressions. + available: The number of available impressions. + possible: The optional number of possible impressions. + + Returns: + The percentage of impressions that are available and possible. + """ + if matched > 0: + available_percent = (float(available) / matched) * 100. + else: + available_percent = 0 + + if possible is not None: + if matched > 0: + possible_percent = (possible/float(matched)) * 100. + else: + possible_percent = 0 + else: + possible_percent = None + + return available_percent, possible_percent + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py new file mode 100755 index 00000000..c90e8cdc --- /dev/null +++ b/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example gets an availability forecast for an existing line item. + +To determine which line items exist, run get_all_line_items.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the line item to get a forecast for. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client, line_item_id): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201905') + + # Set forecasting options. + forecast_options = { + 'includeContendingLineItems': True, + 'includeTargetingCriteriaBreakdown': True, + } + + # Get forecast for line item. + forecast = forecast_service.getAvailabilityForecastById( + line_item_id, forecast_options) + matched = long(forecast['matchedUnits']) + available_units = long(forecast['availableUnits']) + + if matched > 0: + available_percent = (float(available_units) / matched) * 100. + else: + available_percent = 0 + + contending_line_items = getattr(forecast, 'contentingLineItems', []) + + # Display results. + print '%s %s matched.' % (matched, forecast['unitType'].lower()) + print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) + print '%d contending line items.' % len(contending_line_items) + + if 'possibleUnits' in forecast and matched: + possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. + print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py new file mode 100755 index 00000000..00020008 --- /dev/null +++ b/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example gets a delivery forecast for two existing line items. + +To determine which line items exist, run get_all_line_items.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the line items to get forecasts for. +LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' +LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE' + + +def main(client, line_item_id1, line_item_id2): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v201905') + + # Get forecast for line item. + forecast = forecast_service.getDeliveryForecastByIds( + [line_item_id1, line_item_id2], None) + + for single_forecast in forecast['lineItemDeliveryForecasts']: + unit_type = single_forecast['unitType'] + print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( + single_forecast['lineItemId'], single_forecast['matchedUnits'], + unit_type, single_forecast['deliveredUnits'], unit_type, + single_forecast['predictedDeliveryUnits'], unit_type)) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/ad_manager/v201905/inventory_service/__init__.py b/examples/ad_manager/v201905/inventory_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/inventory_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/inventory_service/archive_ad_units.py b/examples/ad_manager/v201905/inventory_service/archive_ad_units.py new file mode 100755 index 00000000..dd1e4893 --- /dev/null +++ b/examples/ad_manager/v201905/inventory_service/archive_ad_units.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example archives ad units. + +The parent ad unit and all ad units underneath it will be archived. To create ad +units, run create_ad_units.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' + + +def main(client, parent_id): + # Initialize appropriate service. + inventory_service = client.GetService('InventoryService', version='v201905') + + # Create a query to select ad units under the parent ad unit and the parent ad + # unit. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('parentId = :parentId or id = :parentId') + .WithBindVariable('parentId', long(parent_id))) + + ad_units_archived = 0 + + # Get ad units by statement. + while True: + response = inventory_service.getAdUnitsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for ad_unit in response['results']: + print ('Ad unit with ID "%s" and name "%s" will be archived.' + % (ad_unit['id'], ad_unit['name'])) + # Perform action. + result = inventory_service.performAdUnitAction( + {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + ad_units_archived += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if ad_units_archived > 0: + print 'Number of ad units archived: %s' % ad_units_archived + else: + print 'No ad units were archived.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/ad_manager/v201905/inventory_service/create_ad_units.py b/examples/ad_manager/v201905/inventory_service/create_ad_units.py new file mode 100755 index 00000000..80d56035 --- /dev/null +++ b/examples/ad_manager/v201905/inventory_service/create_ad_units.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new ad units. + +To determine which ad units exist, run get_all_ad_units.py + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' + + +def main(client, parent_id): + # Initialize appropriate service. + inventory_service = client.GetService('InventoryService', version='v201905') + + # Create ad unit size. + ad_unit_size = { + 'size': { + 'width': '300', + 'height': '250' + }, + 'environmentType': 'BROWSER' + } + + # Create ad unit objects. + ad_unit = { + 'name': 'Ad_unit_%s' % uuid.uuid4(), + 'parentId': parent_id, + 'description': 'Ad unit description.', + 'targetWindow': 'BLANK', + 'adUnitSizes': [ad_unit_size] + } + + # Add ad units. + ad_units = inventory_service.createAdUnits([ad_unit]) + + # Display results. + for ad_unit in ad_units: + print ('Ad unit with ID "%s" and name "%s" was created.' + % (ad_unit['id'], ad_unit['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py new file mode 100755 index 00000000..41d2f83c --- /dev/null +++ b/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 prints all ad unit names as a tree.""" + + +# Import appropriate modules from the client library. +import collections +from googleads import ad_manager + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201905') + inventory_service = client.GetService('InventoryService', version='v201905') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select only the root ad unit by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', root_ad_unit_id)) + + # Make a request for the root ad unit + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + root_ad_unit = response['results'][0] + + all_ad_units = get_all_ad_units(inventory_service) + + display_hierarchy(root_ad_unit, all_ad_units) + + +def get_all_ad_units(inventory_service): + """Download all ad units. + + Args: + inventory_service: An instance of the InventoryService. + + Returns: + A list containing all ad units. + """ + # Create a statement to get all ad units. + statement = (ad_manager.StatementBuilder(version='v201905') + .OrderBy('id', ascending=True)) + + # Pull down all ad units into a list + keep_iterating = True + total_results = 0 + found_ad_units = [] + while keep_iterating: + page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in page and len(page['results']): + total_results = page['totalResultSetSize'] + found_ad_units.extend(page['results']) + + statement.offset += statement.limit + keep_iterating = statement.offset < total_results + + return found_ad_units + + +def display_hierarchy(root_ad_unit, all_ad_units): + """Display the ad units as a tree. + + Args: + root_ad_unit: The root ad unit to begin from. + all_ad_units: A list containing all ad units. + """ + # Create a dict mapping the ids of parents to lists of their children. + parent_id_to_children = collections.defaultdict(list) + for ad_unit in all_ad_units: + if 'parentId' in ad_unit: + parent_id_to_children[ad_unit['parentId']].append(ad_unit) + parent_id_to_children = dict(parent_id_to_children) + + display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0) + + +def display_hierarchy_helper(root, parent_id_to_children, depth): + """Recursive helper for displaying the hierarchy. + + Args: + root: The current root ad unit. + parent_id_to_children: The overall map of parent ids to children. + depth: The current depth. + """ + print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id']) + + # Recurse for each child of this root that has children. + for child in parent_id_to_children.get(root['id'], []): + display_hierarchy_helper(child, parent_id_to_children, depth + 1) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201905/inventory_service/get_all_ad_unit_sizes.py new file mode 100755 index 00000000..22266555 --- /dev/null +++ b/examples/ad_manager/v201905/inventory_service/get_all_ad_unit_sizes.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 unit sizes. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + ad_unit_size_service = client.GetService( + 'InventoryService', version='v201905') + + # Create a statement to select ad unit sizes. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of ad unit sizes at a time, paging + # through until all ad unit sizes have been retrieved. + response = ad_unit_size_service.getAdUnitSizesByStatement( + statement.ToStatement()) + if response: + for ad_unit_size in response: + # Print out some information for each ad unit size. + if 'fullDisplayString' in ad_unit_size: + print('Ad unit size with dimensions "%s" was found.\n' % + (ad_unit_size['fullDisplayString'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py new file mode 100755 index 00000000..a1ea5a80 --- /dev/null +++ b/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + ad_unit_service = client.GetService('InventoryService', version='v201905') + + # Create a statement to select ad units. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py new file mode 100755 index 00000000..211d0af4 --- /dev/null +++ b/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 child ad units of the effective root ad unit.""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v201905') + inventory_service = client.GetService('InventoryService', version='v201905') + + # Set the parent ad unit's ID for all children ad units to be fetched from. + current_network = network_service.getCurrentNetwork() + parent_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create a statement to select ad units under the parent ad unit. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('parentId = :parentId') + .OrderBy('id', ascending=True) + .WithBindVariable('parentId', parent_ad_unit_id)) + + # Retrieve a small amount of ad units at a time, paging + # through until all ad units have been retrieved. + while True: + response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for ad_unit in response['results']: + # Print out some information for each ad unit. + print('Ad unit with ID "%s" and name "%s" was found.\n' % + (ad_unit['id'], ad_unit['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/inventory_service/update_ad_units.py b/examples/ad_manager/v201905/inventory_service/update_ad_units.py new file mode 100755 index 00000000..c8178607 --- /dev/null +++ b/examples/ad_manager/v201905/inventory_service/update_ad_units.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates ad unit sizes by adding a banner ad size. + +To determine which ad units exist, run get_all_ad_units.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +# Set the ID of the ad unit to get. +AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' + + +def main(client, ad_unit_id): + # Initialize appropriate service. + inventory_service = client.GetService('InventoryService', version='v201905') + + # Create a statement to select a single ad unit by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', ad_unit_id)) + + # Get ad units by statement. + response = inventory_service.getAdUnitsByStatement( + statement.ToStatement()) + + # Add the size 468x60 to the ad unit. + ad_unit_size = { + 'size': { + 'width': '468', + 'height': '60' + }, + 'environmentType': 'BROWSER' + } + + if 'results' in response and len(response['results']): + updated_ad_units = [] + for ad_unit in response['results']: + if 'adUnitSizes' not in ad_unit: + ad_unit['adUnitSizes'] = [] + ad_unit['adUnitSizes'].append(ad_unit_size) + updated_ad_units.append(ad_unit) + + # Update ad unit on the server. + ad_units = inventory_service.updateAdUnits(updated_ad_units) + + # Display results. + for ad_unit in ad_units: + ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], + size['size']['height']) + for size in ad_unit['adUnitSizes']] + print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' + % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, AD_UNIT_ID) diff --git a/examples/ad_manager/v201905/label_service/__init__.py b/examples/ad_manager/v201905/label_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/label_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/label_service/create_labels.py b/examples/ad_manager/v201905/label_service/create_labels.py new file mode 100755 index 00000000..ce09719d --- /dev/null +++ b/examples/ad_manager/v201905/label_service/create_labels.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new labels. + +To determine which labels exist, run get_all_labels.py. This feature is only +available to Ad Manager 360 solution networks. +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + label_service = client.GetService('LabelService', version='v201905') + + # Create label objects. + labels = [] + for _ in xrange(5): + label = { + 'name': 'Label #%s' % uuid.uuid4(), + 'isActive': 'true', + 'types': ['COMPETITIVE_EXCLUSION'] + } + labels.append(label) + + # Add Labels. + labels = label_service.createLabels(labels) + + # Display results. + for label in labels: + print ('Label with id "%s", name "%s", and types {%s} was found.' + % (label['id'], label['name'], ','.join(label['types']))) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/label_service/deactivate_labels.py b/examples/ad_manager/v201905/label_service/deactivate_labels.py new file mode 100755 index 00000000..4d0ceacc --- /dev/null +++ b/examples/ad_manager/v201905/label_service/deactivate_labels.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example deactivates all active Labels. + +To determine which labels exist, run get_all_labels.py. This feature is only +available to Ad Manager 360 solution networks. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + label_service = client.GetService('LabelService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) + + labels_deactivated = 0 + + # Get labels by statement. + while True: + response = label_service.getLabelsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for label in response['results']: + print ('Label with id "%s" and name "%s" will be ' + 'deactivated.' % (label['id'], label['name'])) + # Perform action. + result = label_service.performLabelAction( + {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + labels_deactivated += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if labels_deactivated > 0: + print 'Number of labels deactivated: %s' % labels_deactivated + else: + print 'No labels were deactivated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/label_service/get_active_labels.py b/examples/ad_manager/v201905/label_service/get_active_labels.py new file mode 100755 index 00000000..8da4ac00 --- /dev/null +++ b/examples/ad_manager/v201905/label_service/get_active_labels.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 active labels. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + label_service = client.GetService('LabelService', version='v201905') + # Create a statement to select labels. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('isActive = :isActive') + .WithBindVariable('isActive', True)) + + # Retrieve a small amount of labels at a time, paging + # through until all labels have been retrieved. + while True: + response = label_service.getLabelsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for label in response['results']: + # Print out some information for each label. + print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], + label['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/label_service/get_all_labels.py b/examples/ad_manager/v201905/label_service/get_all_labels.py new file mode 100755 index 00000000..551ab193 --- /dev/null +++ b/examples/ad_manager/v201905/label_service/get_all_labels.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 labels. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + label_service = client.GetService('LabelService', version='v201905') + + # Create a statement to select labels. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of labels at a time, paging + # through until all labels have been retrieved. + while True: + response = label_service.getLabelsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for label in response['results']: + # Print out some information for each label. + print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], + label['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/label_service/update_labels.py b/examples/ad_manager/v201905/label_service/update_labels.py new file mode 100755 index 00000000..6ae3b127 --- /dev/null +++ b/examples/ad_manager/v201905/label_service/update_labels.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates the description of a single label. + +To determine which labels exist, run get_all_labels.py. This feature is only +available to Ad Manager 360 solution networks. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +LABEL_ID = 'INSERT_LABEL_ID_HERE' + + +def main(client, label_id): + # Initialize appropriate service. + label_service = client.GetService('LabelService', version='v201905') + + # Create a statement to select only active labels. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :labelId') + .WithBindVariable('labelId', long(label_id))) + + # Get labels by filter. + response = label_service.getLabelsByStatement(statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local label object by changing the description. + updated_labels = [] + for label in response['results']: + label['description'] = 'These labels are updated.' + updated_labels.append(label) + + # Update labels remotely. + labels = label_service.updateLabels(updated_labels) + + for label in labels: + print ('Label with id "%s" and name "%s" was updated.' + % (label['id'], label['name'])) + else: + print 'No labels found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LABEL_ID) + diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201905/line_item_creative_association_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_creative_association_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py new file mode 100755 index 00000000..ff7215e1 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new line item creative associations (LICAs) for an +existing line item and a set of creative ids. + +To determine which LICAs exist, run get_all_licas.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the line item ID and creative IDs to associate. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' +CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE'] + + +def main(client, line_item_id, creative_ids): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v201905') + + licas = [] + for creative_id in creative_ids: + licas.append({'creativeId': creative_id, + 'lineItemId': line_item_id}) + + # Create the LICAs remotely. + licas = lica_service.createLineItemCreativeAssociations(licas) + + # Display results. + if licas: + for lica in licas: + print ('LICA with line item id "%s", creative id "%s", and ' + 'status "%s" was created.' % + (lica['lineItemId'], lica['creativeId'], lica['status'])) + else: + print 'No LICAs created.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, CREATIVE_IDS) diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py new file mode 100755 index 00000000..7df185c1 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example deactivates all LICAs for the line item. + +To determine which LICAs exist, run get_all_licas.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the line item in which to deactivate LICAs. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client, line_item_id): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('lineItemId = :lineItemId AND status = :status') + .WithBindVariable('status', 'ACTIVE') + .WithBindVariable('lineItemId', long(line_item_id))) + + num_deactivated_licas = 0 + + # Get LICAs by statement. + while True: + response = lica_service.getLineItemCreativeAssociationsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for lica in response['results']: + print ('LICA with line item id "%s", creative id "%s", and status' + ' "%s" will be deactivated.' % + (lica['lineItemId'], lica['creativeId'], lica['status'])) + + # Perform action. + result = lica_service.performLineItemCreativeAssociationAction( + {'xsi_type': 'DeactivateLineItemCreativeAssociations'}, + statement.ToStatement()) + if result and int(result['numChanges']) > 0: + num_deactivated_licas += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if num_deactivated_licas > 0: + print 'Number of LICAs deactivated: %s' % num_deactivated_licas + else: + print 'No LICAs were deactivated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py new file mode 100755 index 00000000..37c66e48 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 line item creative associations. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v201905') + + # Create a statement to select line item creative associations. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of line item creative associations at a time, paging + # through until all line item creative associations have been retrieved. + while True: + response = lica_service.getLineItemCreativeAssociationsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for lica in response['results']: + # Print out some information for each line item creative association. + if 'creativeSetId' in lica: + print('LICA with line item ID "%s", creative set ID "%s", and ' + 'status "%s" was found.' % + (lica['lineItemId'], lica['creativeSetId'], lica['status'])) + else: + print('Line item creative association with line item ID "%d" and ' + 'creative ID "%d" was found.\n' % + (lica['lineItemId'], lica['creativeId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py new file mode 100755 index 00000000..cd8f0ee0 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 line item creative associations for a given line item. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client, line_item_id): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v201905') + # Create a statement to select line item creative associations. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('lineItemId = :lineItemId') + .WithBindVariable('lineItemId', line_item_id)) + + # Retrieve a small amount of line item creative associations at a time, paging + # through until all line item creative associations have been retrieved. + while True: + response = lica_service.getLineItemCreativeAssociationsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for lica in response['results']: + # Print out some information for each line item creative association. + if 'creativeSetId' in lica: + print('LICA with line item ID "%s", creative set ID "%s", and ' + 'status "%s" was found.' % + (lica['lineItemId'], lica['creativeSetId'], lica['status'])) + else: + print('Line item creative association with line item ID "%d" and ' + 'creative ID "%d" was found.\n' % + (lica['lineItemId'], lica['creativeId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py new file mode 100755 index 00000000..18737a41 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates the destination URL of all line item creative +associations (LICA). + +To determine which LICAs exist, run get_all_licas.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v201905') + + # Create statement object to get all LICAs. + statement = ad_manager.StatementBuilder(version='v201905') + + while True: + # Get LICAs by statement. + response = lica_service.getLineItemCreativeAssociationsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local LICA object by changing its destination URL. + updated_licas = [] + for lica in response['results']: + lica['destinationUrl'] = 'http://news.google.com' + updated_licas.append(lica) + + # Update LICAs remotely. + licas = lica_service.updateLineItemCreativeAssociations(updated_licas) + + # Display results. + for lica in licas: + print ('LICA with line item id "%s", creative id "%s", and status ' + '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], + lica['status'])) + statement.offset += statement.limit + else: + break + + if response['totalResultSetSize'] == 0: + print 'No LICAs found to update.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/line_item_service/__init__.py b/examples/ad_manager/v201905/line_item_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/line_item_service/activate_line_items.py b/examples/ad_manager/v201905/line_item_service/activate_line_items.py new file mode 100755 index 00000000..ba254ad2 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/activate_line_items.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example activates all line items for the given order. + +To be activated, line items need to be in the approved state and have at least +one creative associated with them. To approve line items, approve the order to +which they belong by running approve_orders.py. To create LICAs, run +create_licas.py. To determine which line items exist, run +get_all_line_items.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the order to get line items from. +ORDER_ID = 'INSERT_ORDER_ID_HERE' + + +def main(client, order_id): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('orderId = :orderId AND status = :status') + .WithBindVariable('status', 'NEEDS_CREATIVES') + .WithBindVariable('orderId', long(order_id))) + + line_items_activated = 0 + + # Get line items by statement. + while True: + response = line_item_service.getLineItemsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for line_item in response['results']: + print ('Line item with id "%s", belonging to order id "%s", and ' + 'name "%s" will be activated.' % + (line_item['id'], line_item['orderId'], line_item['name'])) + + # Perform action. + result = line_item_service.performLineItemAction( + {'xsi_type': 'ActivateLineItems'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + line_items_activated += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if line_items_activated > 0: + print 'Number of line items activated: %s' % line_items_activated + else: + print 'No line items were activated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/ad_manager/v201905/line_item_service/create_line_items.py b/examples/ad_manager/v201905/line_item_service/create_line_items.py new file mode 100755 index 00000000..32179684 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/create_line_items.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new line items. + +To determine which line items exist, run get_all_line_items.py. To determine +which orders exist, run get_all_orders.py. To determine which placements exist, +run get_all_placements.py. +""" + + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set order that the created line item will belong to and add the id of a +# placement containing ad units to target. +ORDER_ID = 'INSERT_ORDER_ID_HERE' +TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE'] + + +def main(client, order_id, targeted_placement_ids): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) + + # Create line item objects. + line_items = [] + for _ in xrange(5): + line_item = { + 'name': 'Line item #%s' % uuid.uuid4(), + 'orderId': order_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedPlacementIds': targeted_placement_ids + }, + 'geoTargeting': { + 'targetedLocations': [ + { + 'id': '2840', + 'displayName': 'US' + }, + { + 'id': '20133', + 'displayName': 'Geneva' + }, + { + 'id': '9000093', + 'displayName': 'B3P', + } + ], + 'excludedLocations': [ + { + 'id': '1016367', + 'displayName': 'Chicago', + }, + { + 'id': '200501', + 'displayName': 'New York NY' + } + ] + }, + 'dayPartTargeting': { + 'dayParts': [ + { + 'dayOfWeek': 'SATURDAY', + 'startTime': { + 'hour': '0', + 'minute': 'ZERO' + }, + 'endTime': { + 'hour': '24', + 'minute': 'ZERO' + } + }, + { + 'dayOfWeek': 'SUNDAY', + 'startTime': { + 'hour': '0', + 'minute': 'ZERO' + }, + 'endTime': { + 'hour': '24', + 'minute': 'ZERO' + } + } + ], + 'timeZone': 'BROWSER' + }, + 'userDomainTargeting': { + 'domains': ['usa.gov'], + 'targeted': 'false' + }, + 'technologyTargeting': { + 'browserTargeting': { + 'browsers': [{'id': '500072'}], + 'isTargeted': 'true' + } + } + }, + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + } + }, + { + 'size': { + 'width': '120', + 'height': '600' + } + } + ], + 'startDateTimeType': 'IMMEDIATELY', + 'lineItemType': 'STANDARD', + 'endDateTime': end_datetime, + 'costType': 'CPM', + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'primaryGoal': { + 'units': '50', + 'unitType': 'IMPRESSIONS', + 'goalType': 'LIFETIME' + }, + 'contractedUnitsBought': '100', + 'creativeRotationType': 'EVEN', + 'discountType': 'PERCENTAGE', + 'allowOverbook': 'true' + } + line_items.append(line_item) + + # Add line items. + line_items = line_item_service.createLineItems(line_items) + + # Display results. + for line_item in line_items: + print ('Line item with id "%s", belonging to order id "%s", and named ' + '"%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS) + diff --git a/examples/ad_manager/v201905/line_item_service/create_video_line_item.py b/examples/ad_manager/v201905/line_item_service/create_video_line_item.py new file mode 100755 index 00000000..4af42345 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/create_video_line_item.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates a new line item to serve to video content. + +This feature is only available to Ad Manager 360 solution networks. +""" + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set order that all created line item will belong to and the video ad unit id +# to target. +ORDER_ID = 'INSERT_ORDER_ID_HERE' +TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE' + +# Set the video content to target. +CONTENT_ID = 'INSERT_CONTENT_ID_HERE' +# Set the video content bundle to target. +CONTENT_BUNDLE_ID = 'INSERT_CONTENT_BUNDLE_ID_HERE' +# Set the CMS metadata value to target. +CMS_METADATA_VALUE_ID = 'INSERT_CMS_METADATA_VALUE_ID_HERE' + + +def main(client, order_id, targeted_video_ad_unit_id, content_id, + content_bundle_id, cms_metadata_value_id): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + + end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime += datetime.timedelta(days=365) + + # Create line item object. + line_item = { + 'name': 'Line item #%s' % uuid.uuid4(), + 'orderId': order_id, + 'targeting': { + 'contentTargeting': { + 'targetedContentIds': [content_id], + 'targetedVideoContentBundleIds': [content_bundle_id] + }, + 'customTargeting': { + 'logicalOperator': 'AND', + 'children': [{ + 'xsi_type': 'CmsMetadataCriteria', + 'cmsMetadataValueIds': [cms_metadata_value_id], + 'operator': 'EQUALS' + }] + }, + 'inventoryTargeting': { + 'targetedAdUnits': [{ + 'adUnitId': targeted_video_ad_unit_id, + 'includeDescendants': 'true' + }] + }, + 'requestPlatformTargeting': { + 'targetedRequestPlatforms': ['VIDEO_PLAYER'] + }, + 'videoPositionTargeting': { + 'targetedPositions': [{ + 'videoPosition': { + 'positionType': 'PREROLL' + } + }] + } + }, + 'creativePlaceholders': [{ + 'size': { + 'width': '400', + 'height': '300' + }, + 'companions': [{ + 'size': { + 'width': '300', + 'height': '250' + }, + }, { + 'size': { + 'width': '728', + 'height': '90' + }, + }] + }], + 'environmentType': 'VIDEO_PLAYER', + 'companionDeliveryOption': 'OPTIONAL', + 'startDateTimeType': 'IMMEDIATELY', + 'lineItemType': 'SPONSORSHIP', + 'endDateTime': end_datetime, + 'costType': 'CPM', + 'costPerUnit': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'primaryGoal': { + 'units': '50', + 'unitType': 'IMPRESSIONS', + 'goalType': 'DAILY' + }, + 'contractedUnitsBought': '100', + 'creativeRotationType': 'OPTIMIZED', + 'discountType': 'PERCENTAGE', + 'allowOverbook': 'true' + } + + # Add line item. + line_item = line_item_service.createLineItems([line_item])[0] + + # Display results. + print('Video line item with id "%s", belonging to order id "%s", and ' + 'named "%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_ID, + CONTENT_BUNDLE_ID, CMS_METADATA_VALUE_ID) diff --git a/examples/ad_manager/v201905/line_item_service/get_all_line_items.py b/examples/ad_manager/v201905/line_item_service/get_all_line_items.py new file mode 100755 index 00000000..9b2e1d72 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/get_all_line_items.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 line items. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + + # Create a statement to select line items. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py new file mode 100755 index 00000000..78c7b9d5 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 line items that are missing creatives. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + # Create a statement to select line items. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('isMissingCreatives = :isMissingCreatives') + .WithBindVariable('isMissingCreatives', True)) + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py new file mode 100755 index 00000000..6a19b3a6 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 only recently updated line items. +""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import ad_manager +import pytz + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + + # Create a statement to select line items. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) + + # Retrieve a small amount of line items at a time, paging + # through until all line items have been retrieved. + while True: + response = line_item_service.getLineItemsByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for line_item in response['results']: + # Print out some information for each line item. + print('Line item with ID "%d" and name "%s" was found.\n' % + (line_item['id'], line_item['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/line_item_service/pause_line_items.py b/examples/ad_manager/v201905/line_item_service/pause_line_items.py new file mode 100755 index 00000000..c622373d --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/pause_line_items.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 pauses a line item. + +Line items must be paused before they can be updated. To determine which line +items exist, run get_all_line_items.py +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the line item to pause. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' + + +def main(client): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + + # Create a statement to select the line item. + # Change this to operate on more than one Line Item. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', LINE_ITEM_ID)) + + result_set_size = 0 + should_continue = True + + # Iterate over paged results from the statement. + while should_continue: + page = line_item_service.getLineItemsByStatement(statement.ToStatement()) + if 'results' in page and len(page['results']): + result_set_size = page['totalResultSetSize'] + # Iterate over individual results in the page. + for line_item in page['results']: + print 'Pausing line item with ID %d' % line_item['id'] + # Update statement for next page. + statement.offset += statement.limit + should_continue = statement.offset < result_set_size + + print 'Pausing %d line item(s)' % result_set_size + + if result_set_size > 0: + statement.offset = None + statement.limit = None + + # Perform Pause action on all Line Items that match the statement. + update_result = line_item_service.performLineItemAction( + {'xsi_type': 'PauseLineItems'}, statement.ToStatement()) + + if update_result and update_result['numChanges'] > 0: + print 'Updated %d line item(s)' % update_result['numChanges'] + else: + print 'No line items were paused' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py new file mode 100755 index 00000000..c2bb7177 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates a line item to add custom criteria targeting. + +To determine which line items exist, run get_all_line_items.py. To determine +which custom targeting keys and values exist, run +get_all_custom_targeting_keys_and_values.py. +""" + + +import pprint + +# Import appropriate modules from the client library. +from googleads import ad_manager + +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' +KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE' +KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE' +KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE' + +VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE' +VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE' +VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE' + + +def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, + value_id3): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + + # create custom criterias + custom_criteria1 = { + 'xsi_type': 'CustomCriteria', + 'keyId': key_id1, + 'valueIds': [value_id1], + 'operator': 'IS' + } + + custom_criteria2 = { + 'xsi_type': 'CustomCriteria', + 'keyId': key_id2, + 'valueIds': [value_id2], + 'operator': 'IS_NOT' + } + + custom_criteria3 = { + 'xsi_type': 'CustomCriteria', + 'keyId': key_id3, + 'valueIds': [value_id3], + 'operator': 'IS' + } + + # Create the custom criteria set that will resemble: + # (custom_criteria1.key == custom_criteria1.value OR + # (custom_criteria2.key != custom_criteria2.value AND + # custom_criteria13.key == custom_criteria3.value)) + sub_set = { + 'xsi_type': 'CustomCriteriaSet', + 'logicalOperator': 'AND', + 'children': [custom_criteria2, custom_criteria3] + } + + top_set = { + 'xsi_type': 'CustomCriteriaSet', + 'logicalOperator': 'OR', + 'children': [custom_criteria1, sub_set] + } + + # Create statement to get the line item + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :lineItemId') + .WithBindVariable('lineItemId', long(line_item_id)) + .Limit(1)) + + # Set custom criteria targeting on the line item. + line_item = line_item_service.getLineItemsByStatement( + statement.ToStatement())['results'][0] + line_item['targeting']['customTargeting'] = top_set + + # Update line item. + line_item = line_item_service.updateLineItems([line_item])[0] + + # Display results. + if line_item: + print ('Line item with id "%s" updated with custom criteria targeting:' + % line_item['id']) + pprint.pprint(line_item['targeting']['customTargeting']) + else: + print 'No line items were updated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, + VALUE_ID2, VALUE_ID3) diff --git a/examples/ad_manager/v201905/line_item_service/update_line_items.py b/examples/ad_manager/v201905/line_item_service/update_line_items.py new file mode 100755 index 00000000..19966bd3 --- /dev/null +++ b/examples/ad_manager/v201905/line_item_service/update_line_items.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates the delivery rate of all line items in an order. + +To determine which line items exist, run get_all_line_items.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the order to get line items from. +ORDER_ID = 'INSERT_ORDER_ID_HERE' + + +def main(client, order_id): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + + # Create statement object to only select line items with even delivery rates. + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('deliveryRateType = :deliveryRateType AND ' + 'orderId = :orderId')) + .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('deliveryRateType', 'EVENLY') + .Limit(500)) + + # Get line items by statement. + response = line_item_service.getLineItemsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local line item by changing its delivery rate type. + updated_line_items = [] + for line_item in response['results']: + if not line_item['isArchived']: + line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE' + updated_line_items.append(line_item) + + # Update line items remotely. + line_items = line_item_service.updateLineItems(updated_line_items) + + # Display results. + if line_items: + for line_item in line_items: + print ('Line item with id "%s", belonging to order id "%s", named ' + '"%s", and delivery rate "%s" was updated.' + % (line_item['id'], line_item['orderId'], line_item['name'], + line_item['deliveryRateType'])) + else: + print 'No line items were updated.' + else: + print 'No line items found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py new file mode 100755 index 00000000..0a3cb053 --- /dev/null +++ b/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example activates paused live stream events.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the LiveStreamEvent to get live stream events from. +LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' + + +def main(client, live_stream_event_id): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201905') + + # Create query to find paused live stream events. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('id = :id AND ' + 'status = :status')) + .WithBindVariable('status', 'PAUSED') + .WithBindVariable('id', long(live_stream_event_id)) + .Limit(500)) + + live_stream_events_activated = 0 + + # Get live stream events by statement. + while True: + response = live_stream_event_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for live_stream_event in response['results']: + print('live stream event with id "%s" and name "%s" will be activated.' + % (live_stream_event['id'], live_stream_event['name'])) + + # Perform action. + result = live_stream_event_service.performLiveStreamEventAction({ + 'xsi_type': 'ActivateLiveStreamEvents' + }, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + live_stream_events_activated += int(result['numChanges']) + statement.offset += ad_manager.SUGGESTED_PAGE_LIMIT + else: + break + + # Display results. + if live_stream_events_activated > 0: + print '# of live stream events activated: %s' % ( + live_stream_events_activated) + else: + print 'No live stream events were activated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/ad_manager/v201905/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201905/live_stream_event_service/create_live_stream_events.py new file mode 100755 index 00000000..3e35ea6b --- /dev/null +++ b/examples/ad_manager/v201905/live_stream_event_service/create_live_stream_events.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example creates new live stream events. + +To determine which live stream events exist, run get_all_live_stream_events.py. +To determine which cdn configurations exist, run get_cdn_configurations.py. +""" + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set content urls and adTags to use +CONTENT_URLS = ['INSERT_CONTENT_URLS_HERE'] +AD_TAGS = ['INSERT_AD_TAGS_HERE'] + + +def main(client, content_urls, ad_tags): + # Initialize appropriate services. + live_events_service = client.GetService( + 'LiveStreamEventService', version='v201905') + + # Stream will play for 365 days + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + + # Create live stream event objects + live_stream_events = [{ + 'name': 'Live Stream Event #%s' % uuid.uuid4(), + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, + 'contentUrls': content_urls, + 'adTags': ad_tags + }] + + # Add live stream events. + live_stream_events = live_events_service.createLiveStreamEvents( + live_stream_events) + + # Display results. + for live_stream_event in live_stream_events: + print( + 'Live stream event with id "%s", named "%s" and status %s was created.' + % (live_stream_event['id'], live_stream_event['name'], + live_stream_event['status'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CONTENT_URLS, AD_TAGS) diff --git a/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py new file mode 100755 index 00000000..7d45acdf --- /dev/null +++ b/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 live stream events. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201905') + + # Create a statement to select live stream events. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of live stream events at a time, paging + # through until all live stream events have been retrieved. + while True: + response = live_stream_event_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for live_stream_event in response['results']: + # Print out some information for each live stream event. + print('live stream event with id "%d" and name "%s" was found.' % + (live_stream_event['id'], live_stream_event['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py new file mode 100755 index 00000000..37d5a3d2 --- /dev/null +++ b/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 registers all live stream event-sessions ids for monitoring.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# List of session ids +SESSION_IDS = ['INSERT_SESSION_IDS_HERE'] + + +def main(client, session_ids): + # Initialize appropriate service. + live_stream_event_service = client.GetService( + 'LiveStreamEventService', version='v201905') + + # Retrieve all sessions id that are being monitored + session_ids = live_stream_event_service.registerSessionsForMonitoring( + session_ids) + if session_ids: + for session_id in session_ids: + # Print out some information for each live stream event. + print 'Session with ID "%s" registered for monitoring.' % (session_id) + + print '\nNumber of results found: %s' % session_ids.size + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, SESSION_IDS) diff --git a/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py new file mode 100755 index 00000000..2c0665d4 --- /dev/null +++ b/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2018 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 code example updates live stream events. + +To determine which live stream events exist, run get_all_live_stream_events.py. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set ID of the LiveStreamEvent to get live stream events from. +LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' + + +def main(client, live_stream_event_id): + # Initialize appropriate services. + live_stream_events_service = client.GetService( + 'LiveStreamEventService', version='v201905') + + # Create statement object to only select matching live stream event. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('Id = :id')) + .WithBindVariable('id', long(live_stream_event_id)) + .Limit(500)) + + # Get live stream events by statement. + response = live_stream_events_service.getLiveStreamEventsByStatement( + statement.ToStatement()) + + # Set adTags to be updated. + new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE'] + + if 'results' in response and len(response['results']): + # Update each local live stream event by changing its attributes. + updated_live_stream_events = [] + for live_stream_event in response['results']: + live_stream_event['startDateTimeType'] = 'IMMEDIATELY' + live_stream_event['adTags'] = new_ad_tags + updated_live_stream_events.append(live_stream_event) + + # Update live stream events. + live_stream_events = live_stream_events_service.updateLiveStreamEvents( + updated_live_stream_events) + + # Display results. + for live_stream_event in live_stream_events: + print('Live stream event with id "%s", named "%s" and status %s was ' + 'updated.' % (live_stream_event['id'], live_stream_event['name'], + live_stream_event['status'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/ad_manager/v201905/native_style_service/__init__.py b/examples/ad_manager/v201905/native_style_service/__init__.py new file mode 100755 index 00000000..473ddba1 --- /dev/null +++ b/examples/ad_manager/v201905/native_style_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. diff --git a/examples/ad_manager/v201905/native_style_service/create_native_styles.py b/examples/ad_manager/v201905/native_style_service/create_native_styles.py new file mode 100755 index 00000000..48f0d1b5 --- /dev/null +++ b/examples/ad_manager/v201905/native_style_service/create_native_styles.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Creates a native app install ad.""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +# This is the creative template ID for the system-defined native app install ad +# format, which we will create the native style from. Use +# CreativeTemplateService.getCreativeTemplateByStatement() and +# CreativeTemplate.isNativeEligible() to get other native ad formats available +# in your network. +CREATIVE_TEMPLATE_ID = 10004400 +WIDTH = 300 +HEIGHT = 345 + +HTML_SNIPPET = """
+ +
Ad
+
+ + + +
+
+ +
+
+ [%Body%] +
+
[%Price%]
+ +
+""" + +CSS_SNIPPET = """body { + background-color: rgba(255, 255, 255, 1); + font-family: "Roboto-Regular", sans-serif; + font-weight: normal; + font-size: 12px; + line-height: 14px; +} +.attribution { + background-color: rgba(236, 182, 0, 1); + color: rgba(255, 255, 255, 1); + font-size: 13px; + display: table; + margin: 4px 8px; + padding: 0 3px; + border-radius: 2px; +} +.image { + text-align: center; + margin: 8px; +} +.image img, +.image-link { + width: 100%; +} +.app-icon { + float: left; + margin: 0 8px 4px 8px; + height: 40px; + width: 40px; + background-color: transparent; +} +.app-icon img { + height: 100%; + width: 100%; + border-radius: 20%; +} +.title { + font-weight: bold; + font-size: 14px; + line-height: 20px; + margin: 8px 8px 4px 8px; +} +.title a { + color: rgba(112, 112, 112, 1); + text-decoration: none; +} +.reviews { + float: left; +} +.reviews svg { + fill: rgba(0, 0, 0, 0.7); +} +.body { + clear: left; + margin: 8px; +} +.body a { + color: rgba(110, 110, 110, 1); + text-decoration: none; +} +.price { + display: none; +} +.button { + font-size: 14px; + font-weight: bold; + float: right; + margin: 0px 16px 16px 0px; + white-space: nowrap; +} +.button a { + color: #2196F3; + text-decoration: none; +} +.button svg { + display: none; +} +""" + + +def main(client, html_snippet, css_snippet, creative_template_id, width, + height): + # Initialize appropriate service. + native_style_service = client.GetService('NativeStyleService', + version='v201905') + + native_style = { + 'name': 'Native style #%d' % uuid.uuid4(), + 'htmlSnippet': html_snippet, + 'cssSnippet': css_snippet, + 'creativeTemplateId': creative_template_id, + 'size': { + 'width': width, + 'height': height, + 'isAspectRatio': False + } + } + + # Create the native style on the server. + native_styles = native_style_service.createNativeStyles([native_style]) + + # Display results. + for native_style in native_styles: + print ('A Native style with ID "%s", name "%s", and creative template ID' + '"%d" was created.' % (native_style['id'], native_style['name'], + native_style['creativeTemplateId'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, + WIDTH, HEIGHT) diff --git a/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py new file mode 100755 index 00000000..1a8a98c9 --- /dev/null +++ b/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 native styles.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + native_style_service = client.GetService('NativeStyleService', + version='v201905') + + # Create a statement to select native styles. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of native styles at a time, paging + # through until all native styles have been retrieved. + while True: + response = native_style_service.getNativeStylesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for native_style in response['results']: + # Print out some information for each native style. + print('Native style with ID "%d" and name "%s" was found.\n' % + (native_style['id'], native_style['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/network_service/__init__.py b/examples/ad_manager/v201905/network_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/network_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/network_service/get_all_networks.py b/examples/ad_manager/v201905/network_service/get_all_networks.py new file mode 100755 index 00000000..504c35ce --- /dev/null +++ b/examples/ad_manager/v201905/network_service/get_all_networks.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 networks. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201905') + + networks = network_service.getAllNetworks() + + # Print out some information for each network. + for network in networks: + print('Network with network code "%s" and display name "%s" was found.' + % (network['networkCode'], network['displayName'])) + + print '\nNumber of results found: %s' % len(networks) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/network_service/get_current_network.py b/examples/ad_manager/v201905/network_service/get_current_network.py new file mode 100755 index 00000000..fbcb7a55 --- /dev/null +++ b/examples/ad_manager/v201905/network_service/get_current_network.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 the current network.""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201905') + + current_network = network_service.getCurrentNetwork() + + print ("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/network_service/make_test_network.py b/examples/ad_manager/v201905/network_service/make_test_network.py new file mode 100755 index 00000000..f3b2babc --- /dev/null +++ b/examples/ad_manager/v201905/network_service/make_test_network.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates a test network. + +You do not need to have an Ad Manager account to run this example, but you do +need to have a Google account (created at +http://www.google.com/accounts/newaccount if you currently don't have one) that +is not associated with any other Ad Manager test networks. Once this network is +created, you can supply the network code in your settings to make calls to +other services. + +Alternatively, if you do not wish to run this example, you can create a test +network at: +https://dfp-playground.appspot.com +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201905') + + # Create a test network. + network = network_service.makeTestNetwork() + + # Display results. + print ('Test network with network code "%s" and display name "%s" ' + 'created.' % (network['networkCode'], network['displayName'])) + print ('You may now sign in at ' + 'http://www.google.com/admanager/main?networkCode=%s' + % network['networkCode']) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/order_service/__init__.py b/examples/ad_manager/v201905/order_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/order_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/order_service/approve_orders.py b/examples/ad_manager/v201905/order_service/approve_orders.py new file mode 100755 index 00000000..c21389d8 --- /dev/null +++ b/examples/ad_manager/v201905/order_service/approve_orders.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example approves all eligible draft and pending orders. + +To determine which orders exist, run get_all_orders.py. +""" + + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + order_service = client.GetService('OrderService', version='v201905') + + # Create a filter statement. + today = datetime.date.today() + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' + 'AND endDateTime >= :today AND isArchived = FALSE')) + .WithBindVariable('today', today)) + orders_approved = 0 + + # Get orders by statement. + while True: + response = order_service.getOrdersByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + # Display results. + for order in response['results']: + print ('Order with id "%s", name "%s", and status "%s" will be ' + 'approved.' % (order['id'], order['name'], order['status'])) + # Perform action. + result = order_service.performOrderAction( + {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + orders_approved += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if orders_approved > 0: + print 'Number of orders approved: %s' % orders_approved + else: + print 'No orders were approved.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/order_service/create_orders.py b/examples/ad_manager/v201905/order_service/create_orders.py new file mode 100755 index 00000000..09faf1bb --- /dev/null +++ b/examples/ad_manager/v201905/order_service/create_orders.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new orders. + +To determine which orders exist, run get_all_orders.py. +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' +SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE' +TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE' + + +def main(client, company_id, salesperson_id, trafficker_id): + # Initialize appropriate service. + order_service = client.GetService('OrderService', version='v201905') + + # Create order objects. + orders = [] + for _ in xrange(5): + order = { + 'name': 'Order #%s' % uuid.uuid4(), + 'advertiserId': company_id, + 'salespersonId': salesperson_id, + 'traffickerId': trafficker_id + } + orders.append(order) + + # Add orders. + orders = order_service.createOrders(orders) + + # Display results. + for order in orders: + print ('Order with id "%s" and name "%s" was created.' + % (order['id'], order['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) diff --git a/examples/ad_manager/v201905/order_service/get_all_orders.py b/examples/ad_manager/v201905/order_service/get_all_orders.py new file mode 100755 index 00000000..c594c0d3 --- /dev/null +++ b/examples/ad_manager/v201905/order_service/get_all_orders.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 orders. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + order_service = client.GetService('OrderService', version='v201905') + + # Create a statement to select orders. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of orders at a time, paging + # through until all orders have been retrieved. + while True: + response = order_service.getOrdersByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for order in response['results']: + # Print out some information for each order. + print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], + order['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py new file mode 100755 index 00000000..8d1bc708 --- /dev/null +++ b/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 orders that are starting soon. +""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import ad_manager +import pytz + + +def main(client): + # Initialize appropriate service. + order_service = client.GetService('OrderService', version='v201905') + now = datetime.now(tz=pytz.timezone('America/New_York')) + soon = now + timedelta(days=5) + + # Create a statement to select orders. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('status = :status AND startDateTime >= :now ' + 'AND startDateTime <= :soon')) + .WithBindVariable('status', 'APPROVED') + .WithBindVariable('now', now) + .WithBindVariable('soon', soon)) + + # Retrieve a small amount of orders at a time, paging + # through until all orders have been retrieved. + while True: + response = order_service.getOrdersByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for order in response['results']: + # Print out some information for each order. + print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], + order['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/order_service/update_orders.py b/examples/ad_manager/v201905/order_service/update_orders.py new file mode 100755 index 00000000..2ffc375d --- /dev/null +++ b/examples/ad_manager/v201905/order_service/update_orders.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates the notes of a single order specified by ID. + +To determine which orders exist, run get_all_orders.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ORDER_ID = 'INSERT_ORDER_ID_HERE' + + +def main(client, order_id): + # Initialize appropriate service. + order_service = client.GetService('OrderService', version='v201905') + + # Create statement object to select a single order by an ID. + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :orderId') + .WithBindVariable('orderId', long(order_id))) + + # Get orders by statement. + response = order_service.getOrdersByStatement(statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local order object by changing its notes. + updated_orders = [] + for order in response['results']: + # Archived orders cannot be updated. + if not order['isArchived']: + order['notes'] = 'Spoke to advertiser. All is well.' + updated_orders.append(order) + + # Update orders remotely. + orders = order_service.updateOrders(updated_orders) + + # Display results. + if orders: + for order in orders: + print ('Order with id "%s", name "%s", advertiser id "%s", and ' + 'notes "%s" was updated.' + % (order['id'], order['name'], order['advertiserId'], + order['notes'])) + else: + print 'No orders were updated.' + else: + print 'No orders found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) + diff --git a/examples/ad_manager/v201905/package_service/create_packages.py b/examples/ad_manager/v201905/package_service/create_packages.py new file mode 100755 index 00000000..16cbea3c --- /dev/null +++ b/examples/ad_manager/v201905/package_service/create_packages.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a package. + +To determine which packages exist, run get_all_packages.py. +""" + +# Import appropriate modules from the client library. +import random + +from googleads import ad_manager + +# Set the ID of the product package to create the package from. +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + +# Set the ID of the proposal to create proposal line items under. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the rate card the proposal line items belonging to the product +# package are priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client): + # Initialize appropriate service. + package_service = client.GetService('PackageService', version='v201905') + + # Create local package. + package = { + 'name': 'Package #%d' % random.randint(0, 1000000), + 'proposalId': PROPOSAL_ID, + 'productPackageId': PRODUCT_PACKAGE_ID, + 'rateCardId': RATE_CARD_ID, + } + + # Create the package on the server. + result = package_service.createPackages([package]) + + for new_package in result: + print ('A package with ID %d and name "%s" was created' % + (new_package['id'], new_package['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py new file mode 100755 index 00000000..cfc5c1f5 --- /dev/null +++ b/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a copy of an image creative. + +To determine which image creatives exist, run get_image_creatives.py +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the line item to pause. +PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + package_service = client.GetService('PackageService', version='v201905') + + # Create a statement to select the single package. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', PACKAGE_ID)) + + # Get the package. + query_result = package_service.getPackagesByStatement(statement.ToStatement()) + + package = query_result['results'][0] + + print ('Package with ID %d will create proposal line items using product ' + 'package with ID %d.' % (package['id'], + package['productPackageId'])) + + # Remove limit and offset from statement. + statement.limit = None + statement.offset = None + + # Perform update packages action. + result = package_service.performPackageAction( + {'xsi_type': 'CreateProposalLineItemsFromPackages'}, + statement.ToStatement()) + + if result and result['numChanges'] > 0: + print ('Number of packages that proposal line items were created for: %d' % + result['numChanges']) + else: + print 'No proposal line items were created.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/package_service/get_all_packages.py b/examples/ad_manager/v201905/package_service/get_all_packages.py new file mode 100755 index 00000000..7cbf6d67 --- /dev/null +++ b/examples/ad_manager/v201905/package_service/get_all_packages.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 packages. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + pkg_service = client.GetService('PackageService', version='v201905') + + # Create a statement to select packages. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of packages at a time, paging + # through until all packages have been retrieved. + while True: + response = pkg_service.getPackagesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for pkg in response['results']: + # Print out some information for each package. + print( + 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' + % (pkg['id'], pkg['name'], pkg['proposalId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/package_service/get_in_progress_packages.py b/examples/ad_manager/v201905/package_service/get_in_progress_packages.py new file mode 100755 index 00000000..0df5ab35 --- /dev/null +++ b/examples/ad_manager/v201905/package_service/get_in_progress_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 packages in progress. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + pkg_service = client.GetService('PackageService', version='v201905') + # Create a statement to select packages. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status') + .WithBindVariable('status', 'IN_PROGRESS')) + + # Retrieve a small amount of packages at a time, paging + # through until all packages have been retrieved. + while True: + response = pkg_service.getPackagesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for pkg in response['results']: + # Print out some information for each package. + print( + 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' + % (pkg['id'], pkg['name'], pkg['proposalId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/placement_service/create_placements.py b/examples/ad_manager/v201905/placement_service/create_placements.py new file mode 100755 index 00000000..8fb2f4a7 --- /dev/null +++ b/examples/ad_manager/v201905/placement_service/create_placements.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new placements for various ad unit sizes. + +To determine which placements exist, run get_all_placements.py. +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + placement_service = client.GetService('PlacementService', version='v201905') + inventory_service = client.GetService('InventoryService', version='v201905') + + # Create placement object to store medium rectangle ad units. + medium_rectangle_ad_unit_placement = { + 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(), + 'description': 'Contains ad units that hold creatives of size 300x250', + 'targetedAdUnitIds': [] + } + + # Create placement object to store skyscraper ad units. + skyscraper_ad_unit_placement = { + 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(), + 'description': 'Contains ad units that hold creatives of size 120x600', + 'targetedAdUnitIds': [] + } + + # Create placement object to store banner ad units. + banner_ad_unit_placement = { + 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(), + 'description': 'Contains ad units that hold creatives of size 468x60', + 'targetedAdUnitIds': [] + } + + placement_list = [] + + # Create statement to get all the ad units. + statement = ad_manager.StatementBuilder(version='v201905') + + while True: + response = inventory_service.getAdUnitsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Separate the ad units by size. + for ad_unit in response['results']: + if 'adUnitSizes' in ad_unit: + for ad_unit_size in ad_unit['adUnitSizes']: + size = ad_unit_size['size'] + if size['width'] == '300' and size['height'] == '250': + medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append( + ad_unit['id']) + elif size['width'] == '120' and size['height'] == '600': + skyscraper_ad_unit_placement['targetedAdUnitIds'].append( + ad_unit['id']) + elif size['width'] == '468' and size['height'] == '60': + banner_ad_unit_placement['targetedAdUnitIds'].append( + ad_unit['id']) + statement.offset += statement.limit + else: + break + + # Only create placements with one or more ad unit. + if medium_rectangle_ad_unit_placement['targetedAdUnitIds']: + placement_list.append(medium_rectangle_ad_unit_placement) + + if skyscraper_ad_unit_placement['targetedAdUnitIds']: + placement_list.append(skyscraper_ad_unit_placement) + + if banner_ad_unit_placement['targetedAdUnitIds']: + placement_list.append(banner_ad_unit_placement) + + # Add placements. + placements = placement_service.createPlacements(placement_list) + + # Display results. + for placement in placements: + ad_unit_ids = '' + if 'targetedAdUnitIds' in placement: + ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) + print ('A Placement with ID "%s", name "%s", and containing ad units ' + '{%s} was created.' % (placement['id'], placement['name'], + ad_unit_ids)) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/placement_service/deactivate_placements.py b/examples/ad_manager/v201905/placement_service/deactivate_placements.py new file mode 100755 index 00000000..706cab7c --- /dev/null +++ b/examples/ad_manager/v201905/placement_service/deactivate_placements.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example deactivates all active placements. + +To determine which placements exist, run get_all_placements.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' + + +def main(client, placement_id): + # Initialize appropriate service. + placement_service = client.GetService('PlacementService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :placementId') + .WithBindVariable('placementId', long(placement_id)) + .Limit(1)) + + # Get placements by statement. + placements = placement_service.getPlacementsByStatement( + statement.ToStatement()) + + for placement in placements: + print ('Placement with id "%s", name "%s", and status "%s" will be ' + 'deactivated.' % (placement['id'], placement['name'], + placement['status'])) + + # Perform action. + result = placement_service.performPlacementAction( + {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement()) + + # Display results. + if result and int(result['numChanges']) > 0: + print 'Number of placements deactivated: %s' % result['numChanges'] + else: + print 'No placements were deactivated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/ad_manager/v201905/placement_service/get_active_placements.py b/examples/ad_manager/v201905/placement_service/get_active_placements.py new file mode 100755 index 00000000..db59202b --- /dev/null +++ b/examples/ad_manager/v201905/placement_service/get_active_placements.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 active placements. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + placement_service = client.GetService('PlacementService', version='v201905') + # Create a statement to select placements. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) + + # Retrieve a small amount of placements at a time, paging + # through until all placements have been retrieved. + while True: + response = placement_service.getPlacementsByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for placement in response['results']: + # Print out some information for each placement. + print('Placement with ID "%d" and name "%s" was found.\n' % + (placement['id'], placement['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/placement_service/get_all_placements.py b/examples/ad_manager/v201905/placement_service/get_all_placements.py new file mode 100755 index 00000000..3a5f21d8 --- /dev/null +++ b/examples/ad_manager/v201905/placement_service/get_all_placements.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 placements. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + placement_service = client.GetService('PlacementService', version='v201905') + + # Create a statement to select placements. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of placements at a time, paging + # through until all placements have been retrieved. + while True: + response = placement_service.getPlacementsByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for placement in response['results']: + # Print out some information for each placement. + print('Placement with ID "%d" and name "%s" was found.\n' % + (placement['id'], placement['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/placement_service/update_placements.py b/examples/ad_manager/v201905/placement_service/update_placements.py new file mode 100755 index 00000000..23df13d4 --- /dev/null +++ b/examples/ad_manager/v201905/placement_service/update_placements.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates a single placement to allow for AdSense targeting. + +To determine which placements exist, run get_all_placements.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' + + +def main(client, placement_id): + # Initialize appropriate service. + placement_service = client.GetService('PlacementService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', placement_id)) + + # Get placements by statement. + page = placement_service.getPlacementsByStatement( + statement.ToStatement()) + + placement = page['results'][0] + + placement['description'] = 'This placement contains all leaderboards.' + + # Update placements remotely. + updated_placements = placement_service.updatePlacements([placement]) + + for placement in updated_placements: + print ('Placement with id "%s" and name "%s" was updated.' + % (placement['id'], placement['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/ad_manager/v201905/premium_rate_service/__init__.py b/examples/ad_manager/v201905/premium_rate_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/premium_rate_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py new file mode 100755 index 00000000..ca0e69f2 --- /dev/null +++ b/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new premium_rates. + +To determine which premium_rates exist, run get_all_premium_rates.py. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate services. + premium_rate_service = client.GetService('PremiumRateService', + version='v201905') + + # Create an ad unit premium to apply to the rate card. + ad_unit_premium_feature = { + 'xsi_type': 'AdUnitPremiumFeature' + } + + # Create a CPC based premium rate value with adjustments in milli amounts. + # This will adjust a CPC priced proposal line item that has + # inventory targeting specified by 10% of the cost associated with the rate + # card (this comes from a percentage adjustment). + cpc_premium_rate_value = { + 'premiumFeature': ad_unit_premium_feature, + 'rateType': 'CPC', + 'adjustmentSize': 10000, + 'adjustmentType': 'PERCENTAGE' + } + + # Create a CPM based premium rate value with adjustments in micro amounts. + # This will adjust a CPM priced proposal line item that has + # inventory targeting specified by 2 units of the currency associated with + # the rate card (this comes from absolute value adjustment). + cpm_premium_rate_value = { + 'premiumFeature': ad_unit_premium_feature, + 'rateType': 'CPM', + 'adjustmentSize': 2000000, + 'adjustmentType': 'ABSOLUTE_VALUE' + } + + # Create premium rate. + # Associate premium rate with the rate card and set premium information. + # This premium will apply for proposal line items targeting 'any' ad unit + # for both CPM and CPC rate types. + premium_rate = { + 'rateCardId': rate_card_id, + 'pricingMethod': 'ANY_VALUE', + 'premiumFeature': ad_unit_premium_feature, + 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value] + } + + # Add premium_rates. + premium_rates = premium_rate_service.createPremiumRates([premium_rate]) + + # Display results. + for premium_rate in premium_rates: + print ('A premium rate for "%s" was added to the rate card with ID' + ' of "%s".\n' + % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), + premium_rate['id'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py new file mode 100755 index 00000000..ab90ec52 --- /dev/null +++ b/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 premium rates. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + premium_rate_service = client.GetService( + 'PremiumRateService', version='v201905') + + # Create a statement to select premium rates. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of premium rates at a time, paging + # through until all premium rates have been retrieved. + while True: + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for premium_rate in response['results']: + # Print out some information for each premium rate. + print('Premium rate with ID "%d", premium feature "%s", and rate card ' + 'id "%d" was found.\n' % ( + premium_rate['id'], + ad_manager.AdManagerClassType(premium_rate), + premium_rate['rateCardId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py new file mode 100755 index 00000000..2f01430b --- /dev/null +++ b/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 premium rates on a specific rate card. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, rate_card_id): + # Initialize appropriate service. + premium_rate_service = client.GetService( + 'PremiumRateService', version='v201905') + # Create a statement to select premium rates. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('rateCardId = :rateCardId') + .WithBindVariable('rateCardId', rate_card_id)) + + # Retrieve a small amount of premium rates at a time, paging + # through until all premium rates have been retrieved. + while True: + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for premium_rate in response['results']: + # Print out some information for each premium rate. + print('Premium rate with ID "%d", premium feature "%s", and rate card ' + 'ID "%d" was found.\n' % (premium_rate['id'], + premium_rate['premium feature'], + premium_rate['rateCardId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py new file mode 100755 index 00000000..7fd99849 --- /dev/null +++ b/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates a premium rate to add a flat fee to an existing feature. + +To determine which premium rates exist, run get_all_premium_rates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' + + +def main(client, premium_rate_id): + # Initialize appropriate service. + premium_rate_service = client.GetService('PremiumRateService', + version='v201905') + + # Create statement object to select a single proposal by an ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(premium_rate_id)) + .Limit(1)) + + # Get the premium rate. + response = premium_rate_service.getPremiumRatesByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + updated_premium_rates = [] + for premium_rate in response['results']: + # Create a flat fee based premium rate value with a 10% increase. + new_flat_fee_rate = { + 'premiumFeature': premium_rate['premiumFeature'], + 'rateType': 'CPM', + 'adjustmentSize': 10000, + 'adjustmentType': 'PERCENTAGE' + } + + # Update the premium rate's premiumRateValues to include a flat fee + # premium rate. + + existing_premium_rate_value = ( + [] if 'premiumRateValues' not in premium_rate else + premium_rate['premiumRateValues']) + existing_premium_rate_value.append(new_flat_fee_rate) + premium_rate['premiumRateValues'] = existing_premium_rate_value + + updated_premium_rates.append(premium_rate) + + # Update products remotely. + premium_rates = premium_rate_service.updatePremiumRates( + updated_premium_rates) + + # Display results. + if premium_rates: + for premium_rate in premium_rates: + print ('Premium rate with ID "%s", associated with rate card id' + ' "%s" was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) + else: + print 'No premium rates were updated.' + else: + print 'No premium rates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PREMIUM_RATE_ID) diff --git a/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py new file mode 100755 index 00000000..b9fa1a4c --- /dev/null +++ b/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a product package item. + +To determine which product package items exist, run +get_all_product_package_items.py +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the product package to add product package items to. +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + +# Set the ID of the product to generate a product package item from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client): + product_package_item_service = client.GetService('ProductPackageItemService', + version='v201905') + + product_package_item = { + # Set the product from which the product package item is created. + 'productId': PRODUCT_ID, + # Set the product package that the product package item belongs to. + 'productPackageId': PRODUCT_PACKAGE_ID, + # Specify if the product package item is required for this + # product package. + 'isMandatory': True + } + + # Create the product package item on the server. + result = product_package_item_service.createProductPackageItems( + [product_package_item]) + + for new_product_package_item in result: + print ('A product package with ID %d created from product ID %d ' + 'belonging to product package with ID %d was created.' % + (new_product_package_item['id'], + new_product_package_item['productId'], + new_product_package_item['productPackageId'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py new file mode 100755 index 00000000..e677a43b --- /dev/null +++ b/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 product package items. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + product_package_item_service = client.GetService( + 'ProductPackageItemService', version='v201905') + + # Create a statement to select product package items. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of product package items at a time, paging + # through until all product package items have been retrieved. + while True: + response = product_package_item_service.getProductPackageItemsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for product_package_item in response['results']: + # Print out some information for each product package item. + print('Product package item with ID "%d", product id "%d", and product ' + 'package id "%d" was found.\n' % + (product_package_item['id'], product_package_item['productId'], + product_package_item['productPackageId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py new file mode 100755 index 00000000..8ba5ad20 --- /dev/null +++ b/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 product package items belonging to a product package. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' + + +def main(client, product_package_id): + # Initialize appropriate service. + product_package_item_service = client.GetService( + 'ProductPackageItemService', version='v201905') + # Create a statement to select product package items. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('productPackageId = :productPackageId') + .WithBindVariable('productPackageId', product_package_id)) + + # Retrieve a small amount of product package items at a time, paging + # through until all product package items have been retrieved. + while True: + response = product_package_item_service.getProductPackageItemsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for product_package_item in response['results']: + # Print out some information for each product package item. + print('Product package item with ID "%d", product ID "%d", and product ' + 'package ID "%d" was found.\n' % + (product_package_item['id'], product_package_item['productId'], + product_package_item['productPackageId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_PACKAGE_ID) diff --git a/examples/ad_manager/v201905/product_package_service/create_product_packages.py b/examples/ad_manager/v201905/product_package_service/create_product_packages.py new file mode 100755 index 00000000..43f2e6f6 --- /dev/null +++ b/examples/ad_manager/v201905/product_package_service/create_product_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a product package. + +To determine which product packages exist, run get_all_product_packages.py +""" + +# Import appropriate modules from the client library. +import random + +from googleads import ad_manager + +# Set the ID of the rate card to associate with the product package. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client): + product_package_service = client.GetService('ProductPackageService', + version='v201905') + + # Create a local product package. + product_package = { + 'name': 'Product Package #%d' % random.randint(0, 100000000), + 'rateCardIds': [RATE_CARD_ID] + } + + result = product_package_service.createProductPackages([product_package]) + + for new_product_package in result: + print ('A product package with ID %d and name "%s" was created.' % + (new_product_package['id'], new_product_package['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py new file mode 100755 index 00000000..139c1ed1 --- /dev/null +++ b/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 active product packages. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + product_package_service = client.GetService( + 'ProductPackageService', version='v201905') + # Create a statement to select product packages. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status') + .WithBindVariable('status', 'ACTIVE')) + + # Retrieve a small amount of product packages at a time, paging + # through until all product packages have been retrieved. + while True: + response = product_package_service.getProductPackagesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for product_package in response['results']: + # Print out some information for each product package. + print('Product package with ID "%d" and name "%s" was found.\n' % + (product_package['id'], product_package['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py new file mode 100755 index 00000000..e50f40e4 --- /dev/null +++ b/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 product packages. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + product_package_service = client.GetService( + 'ProductPackageService', version='v201905') + + # Create a statement to select product packages. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of product packages at a time, paging + # through until all product packages have been retrieved. + while True: + response = product_package_service.getProductPackagesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for product_package in response['results']: + # Print out some information for each product package. + print('Product package with ID "%d" and name "%s" was found.\n' % + (product_package['id'], product_package['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_service/__init__.py b/examples/ad_manager/v201905/product_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/product_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/product_service/get_all_products.py b/examples/ad_manager/v201905/product_service/get_all_products.py new file mode 100755 index 00000000..3a6a2561 --- /dev/null +++ b/examples/ad_manager/v201905/product_service/get_all_products.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 products. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201905') + + # Create a statement to select products. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of products at a time, paging + # through until all products have been retrieved. + while True: + response = product_service.getProductsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for product in response['results']: + # Print out some information for each product. + print('Product with ID "%d" and name "%s" was found.\n' % + (product['id'], product['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_service/get_products_for_product_template.py b/examples/ad_manager/v201905/product_service/get_products_for_product_template.py new file mode 100755 index 00000000..51b58500 --- /dev/null +++ b/examples/ad_manager/v201905/product_service/get_products_for_product_template.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 products created from a product template. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201905') + + # Create a statement to select products. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('productTemplateId = :productTemplateId') + .WithBindVariable('productTemplateId', product_template_id)) + + # Retrieve a small amount of products at a time, paging + # through until all products have been retrieved. + while True: + response = product_service.getProductsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for product in response['results']: + # Print out some information for each product. + print('Product with ID "%d" and name "%s" was found.\n' % + (product['id'], product['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201905/product_service/update_products.py b/examples/ad_manager/v201905/product_service/update_products.py new file mode 100755 index 00000000..75905cbc --- /dev/null +++ b/examples/ad_manager/v201905/product_service/update_products.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates a product's notes. + +To determine which products exist, run get_all_products.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, product_id): + # Initialize appropriate service. + product_service = client.GetService('ProductService', version='v201905') + + # Create statement object to select a single product by an ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', long(product_id)) + .Limit(1)) + + # Get products by statement. + response = product_service.getProductsByStatement(statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local product object by changing its notes. + updated_products = [] + for product in response['results']: + product['notes'] = 'Product needs further review before activation.' + updated_products.append(product) + + # Update products remotely. + products = product_service.updateProducts(updated_products) + + # Display results. + if products: + for product in products: + print ('Product with id "%s", name "%s", and ' + 'notes "%s" was updated.' + % (product['id'], product['name'], product['notes'])) + else: + print 'No products were updated.' + else: + print 'No products found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_ID) diff --git a/examples/ad_manager/v201905/product_template_service/__init__.py b/examples/ad_manager/v201905/product_template_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/product_template_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/product_template_service/activate_product_templates.py b/examples/ad_manager/v201905/product_template_service/activate_product_templates.py new file mode 100755 index 00000000..eb087342 --- /dev/null +++ b/examples/ad_manager/v201905/product_template_service/activate_product_templates.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example activates a product template. + +To determine which product templates exist, run get_all_product_templates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the product template to activate. +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) + + product_templates_activated = 0 + + # Get product_templates by statement. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for product_template in response['results']: + print ('Product template with id "%s" and name "%s" will be ' + 'activated.' % (product_template['id'], + product_template['name'])) + + # Perform action. + result = product_template_service.performProductTemplateAction( + {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + product_templates_activated += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if product_templates_activated > 0: + print ('Number of product templates ' + 'activated: %s' % product_templates_activated) + else: + print 'No product templates were activated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201905/product_template_service/create_product_templates.py b/examples/ad_manager/v201905/product_template_service/create_product_templates.py new file mode 100755 index 00000000..bad5121e --- /dev/null +++ b/examples/ad_manager/v201905/product_template_service/create_product_templates.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates a product template. + +To determine which product templates exist, run get_all_product_templates.py. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201905') + network_service = client.GetService( + 'NetworkService', version='v201905') + + # Create a product template. + product_template = { + 'name': ('Product template #%d' % uuid.uuid4()), + 'description': ('This product template creates standard proposal line ' + 'items targeting Chrome browsers with product ' + 'segmentation on ad units and geo targeting.'), + 'nameMacro': (' - - ' + ' - '), + 'productType': 'DFP', + 'rateType': 'CPM', + 'roadblockingType': 'ONE_OR_MORE', + 'deliveryRateType': 'AS_FAST_AS_POSSIBLE', + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'lineItemType': 'STANDARD', + 'customizableAttributes': { + 'allowPlacementTargetingCustomization': True, + }, + 'builtInTargeting': { + 'technologyTargeting': { + # Set browser targeting to Chrome. + 'browserTargeting': { + { + 'browsers': [ + { + 'id': '500072' + } + ] + } + } + } + }, + 'productSegmentation': { + 'geoSegment': { + 'targetedLocations': [ + {'id': '2840', + 'displayName': 'US'}, + {'id': '2344', + 'displayName': 'Hong Kong'} + ] + }, + 'adUnitSegments': [{ + 'adUnitId': (network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId']), + 'includeDescendants': 'true' + }] + } + } + + # Create product templates on the server. + product_templates = product_template_service.createProductTemplates( + [product_template]) + + if product_templates: + for product_template in product_templates: + print ('A product template with ID "%s" and name "%s" was ' + 'created.' % (product_template['id'], product_template['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py new file mode 100755 index 00000000..866b241c --- /dev/null +++ b/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 creates a programmatic product template. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + product_template_service = client.GetService( + 'ProductTemplateService', version='v201905') + network_service = client.GetService( + 'NetworkService', version='v201905') + + product_template = { + # Setting required Marketplace information. + 'productTemplateMarketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + # Setting common required fields for product templates. + 'name': ('Product template #%d' % uuid.uuid4()), + 'description': ('This product template creates standard programmatic' + 'proposal line items targeting all ad units with' + 'product segmentation on geo targeting.'), + 'nameMacro': (' - - ' + ' - '), + 'productType': 'DFP', + 'rateType': 'CPM', + 'creativePlaceholders': [ + { + 'size': { + 'width': '728', + 'height': '90' + } + }, + { + 'size': { + 'width': '300', + 'height': '250' + } + } + ], + 'lineItemType': 'STANDARD', + 'productSegmentation': { + 'geoSegment': { + 'targetedLocations': [ + {'id': '2840', + 'displayName': 'US'}, + {'id': '2344', + 'displayName': 'Hong Kong'} + ] + }, + 'adUnitSegments': [{ + 'adUnitId': (network_service.getCurrentNetwork()[ + 'effectiveRootAdUnitId']), + 'includeDescendants': 'true' + }] + } + } + + product_templates = product_template_service.createProductTemplates( + [product_template]) + + if product_templates: + for product_template in product_templates: + print ('A programmatic product template with ID "%s" and name "%s" ' + 'was created.' % (product_template['id'], + product_template['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py new file mode 100755 index 00000000..c3f4e639 --- /dev/null +++ b/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 product templates. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201905') + + # Create a statement to select product templates. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of product templates at a time, paging + # through until all product templates have been retrieved. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for product_template in response['results']: + # Print out some information for each product template. + print('Product template with ID "%d" and name "%s" was found.\n' % + (product_template['id'], product_template['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py new file mode 100755 index 00000000..d5eadf3d --- /dev/null +++ b/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 sponsorship product templates. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201905') + # Create a statement to select product templates. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('lineItemType = :lineItemType') + .WithBindVariable('lineItemType', 'SPONSORSHIP')) + + # Retrieve a small amount of product templates at a time, paging + # through until all product templates have been retrieved. + while True: + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for product_template in response['results']: + # Print out some information for each product template. + print('Product template with ID "%d" and name "%s" was found.\n' % + (product_template['id'], product_template['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_template_service/update_product_templates.py b/examples/ad_manager/v201905/product_template_service/update_product_templates.py new file mode 100755 index 00000000..aa313ecc --- /dev/null +++ b/examples/ad_manager/v201905/product_template_service/update_product_templates.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates a product template's GeoTargeting. + +To determine which product templates exist, run get_all_product_templates.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' + + +def main(client, product_template_id): + # Initialize appropriate service. + product_template_service = client.GetService( + 'ProductTemplateService', version='v201905') + + # Create a statement to select a single product template by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .WithBindVariable('id', long(product_template_id)) + .Limit(1)) + + # Get product templates by statement. + response = product_template_service.getProductTemplatesByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local product template object by appending a new geo-target. + for product_template in response['results']: + # Create geo-targeting for Canada to append. + location = { + 'id': '2124', + 'displayName': 'Canada' + } + + try: + targeting = product_template['builtInTargeting'] + + if 'geoTargeting' in targeting: + geo_targeting = targeting['geoTargeting'] + + if 'targetedLocations' in geo_targeting: + geo_targeting['targetedLocations'].append(location) + else: + geo_targeting['targetedLocations'] = [location] + else: + targeting['geoTargeting'] = { + 'targetedLocations': [location] + } + except KeyError: + product_template['builtInTargeting'] = { + 'geoTargeting': { + 'targetedLocations': [location] + } + } + + # Update products remotely. + product_templates = product_template_service.updateProductTemplates( + [product_template]) + + # Display results. + if product_templates: + for product_template in product_templates: + print ('Product template with id "%s" and name "%s" was ' + 'updated.' % (product_template['id'], product_template['name'])) + else: + print 'No product templates were updated.' + else: + print 'No product templates found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201905/proposal_line_item_service/__init__.py b/examples/ad_manager/v201905/proposal_line_item_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_line_item_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py new file mode 100755 index 00000000..f2c91dad --- /dev/null +++ b/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example archives a proposal line item. + +To determine which proposal line items exist, run +get_all_proposal_line_items.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the proposal line item to archive. +PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' + + +def main(client, proposal_line_item_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) + + proposal_line_items_archived = 0 + + # Get proposal line items by statement. + while True: + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for proposal_line_item in response['results']: + print ('Proposal line item with id "%s", ' + 'belonging to proposal id "%s", and ' + 'name "%s" will be archived.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + # Perform action. + result = proposal_line_item_service.performProposalLineItemAction( + {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposal_line_items_archived += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if proposal_line_items_archived > 0: + print ('Number of proposal line items ' + 'archived: %s' % proposal_line_items_archived) + else: + print 'No proposal line items were archived.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py new file mode 100755 index 00000000..4db1b897 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 code example creates a new programmatic proposal line item. +""" + + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set the ID of the programmatic proposal that the proposal line item will +# belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + +# Set the ID of the Marketplace rate card the proposal line items should be +# priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, proposal_id, product_id, rate_card_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201905') + network_service = client.GetService('NetworkService', version='v201905') + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + + # Create a single programmatic proposal line item. + proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + # Setting common required fields for proposal line items. + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'rateCardId': rate_card_id, + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'netCost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'netRate': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add programmatic proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Programmatic proposal line item with id "%s", belonging to ' + 'proposal id "%s", and named "%s" was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py new file mode 100755 index 00000000..f0384e66 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a programmatic proposal line item for non-sales management. +""" + + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set proposal that the created proposal line item will belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + + +def main(client, proposal_id, product_id): + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201905') + network_service = client.GetService('NetworkService', version='v201905') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single programmatic proposal line item. + proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for proposal line items. + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + }, + # Target Display environment by excluding Mobile Apps. + # DeviceCapabilities can be obtained though the Device_Capability PQL + # table: + # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService + 'technologyTargeting': { + 'deviceCapabilityTargeting': [{'id': 5005}] + } + }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, + 'creativePlaceholders': [{ + 'size': { + 'width': '300', + 'height': '250' + } + }, { + 'size': { + 'width': '120', + 'height': '600' + } + }], + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'netRate': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Programmatic proposal line item for non-sales management with id ' + '"%s", belonging to proposal id "%s", and named "%s" ' + 'was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID) + diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py new file mode 100755 index 00000000..a0ec6c3e --- /dev/null +++ b/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates a new run-of-network proposal line item. + +To determine which proposal line items exist, run +get_all_proposal_line_items.py. To determine which proposals exist, run +get_all_proposals.py. +""" + + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + +# Set proposal that the created proposal line item will belong to. +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + +# Set the ID of the product that the proposal line items should be created from. +PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' + +# Set the ID of the rate card the proposal line items should be priced from. +RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' + + +def main(client, proposal_id, product_id, rate_card_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201905') + network_service = client.GetService('NetworkService', version='v201905') + + start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) + end_datetime = start_datetime + datetime.timedelta(days=365) + + # Get the root ad unit to target. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Create a single proposal line item. + proposal_line_item = { + 'name': 'Proposal line item #%s' % uuid.uuid4(), + 'rateCardId': rate_card_id, + 'productId': product_id, + 'proposalId': proposal_id, + 'targeting': { + 'inventoryTargeting': { + 'targetedAdUnits': { + 'adUnitId': root_ad_unit_id + } + } + }, + 'startDateTime': start_datetime, + 'endDateTime': end_datetime, + 'deliveryRateType': 'EVENLY', + 'creativeRotationType': 'OPTIMIZED', + 'billingCap': 'CAPPED_CUMULATIVE', + 'billingSource': 'THIRD_PARTY_VOLUME', + 'goal': { + 'units': '1000', + 'unitType': 'IMPRESSIONS', + }, + 'netCost': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'netRate': { + 'currencyCode': 'USD', + 'microAmount': '2000000' + }, + 'rateType': 'CPM', + } + + # Add proposal line items. + proposal_line_items = proposal_line_item_service.createProposalLineItems( + [proposal_line_item]) + + # Display results. + for proposal_line_item in proposal_line_items: + print ('Proposal line item with id "%s", belonging to proposal id "%s"' + ', and named "%s" was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + diff --git a/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py new file mode 100755 index 00000000..f5aa3104 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 proposal line items. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201905') + + # Create a statement to select proposal line items. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of proposal line items at a time, paging + # through until all proposal line items have been retrieved. + while True: + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for proposal_line_item in response['results']: + # Print out some information for each proposal line item. + print('Proposal line item with ID "%d" and name "%s" was found.\n' % + (proposal_line_item['id'], proposal_line_item['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py new file mode 100755 index 00000000..e4be6d25 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 proposal line items belonging to a specific proposal. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201905') + # Create a statement to select proposal line items. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('proposalId = :proposalId') + .WithBindVariable('proposalId', proposal_id)) + + # Retrieve a small amount of proposal line items at a time, paging + # through until all proposal line items have been retrieved. + while True: + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for proposal_line_item in response['results']: + # Print out some information for each proposal line item. + print('Proposal line item with ID "%d" and name "%s" was found.\n' % + (proposal_line_item['id'], proposal_line_item['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py new file mode 100755 index 00000000..39aec9da --- /dev/null +++ b/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates a proposal line item's notes. + +To determine which proposal line items exist, +run get_all_proposal_line_items.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the proposal line item to update. +PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' + + +def main(client, proposal_line_item_id): + # Initialize appropriate service. + proposal_line_item_service = client.GetService( + 'ProposalLineItemService', version='v201905') + + # Create statement to select a proposal line item. + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', long(proposal_line_item_id)) + .Limit(1)) + + # Get proposal line items by statement. + response = proposal_line_item_service.getProposalLineItemsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each the proposal line item's notes field. + proposal_line_item = response['results'][0] + proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.' + + # Update proposal line items remotely. + proposal_line_items = proposal_line_item_service.updateProposalLineItems( + [proposal_line_item]) + + # Display results. + if proposal_line_items: + for proposal_line_item in proposal_line_items: + print ('Line item with id "%s", belonging to proposal id "%s" and,' + ' named "%s" was updated.' % ( + proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) + else: + print 'No proposal line items were updated.' + else: + print 'No proposal line items found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/ad_manager/v201905/proposal_service/__init__.py b/examples/ad_manager/v201905/proposal_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals.py new file mode 100755 index 00000000..cd98aaa7 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 code example creates new programmatic proposals. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' +BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' + + +def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, + buyer_id): + proposal_service = client.GetService('ProposalService', version='v201905') + network_service = client.GetService('NetworkService', version='v201905') + + proposal = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'buyerAccountId': buyer_id + }, + 'isProgrammatic': True, + # Setting required common fields for Proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), + 'advertiser': { + 'companyId': advertiser_id, + 'type': 'ADVERTISER' + }, + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '100000' + }, + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + 'budget': { + 'microAmount': '100000000', + 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] + }, + } + proposals = proposal_service.createProposals([proposal]) + + # Display results. + for proposal in proposals: + print('Programmatic proposal with id "%s" and name "%s" was created.' % + (proposal['id'], proposal['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID, BUYER_ID) diff --git a/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals_for_non_sales_management.py new file mode 100755 index 00000000..a2068a47 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals_for_non_sales_management.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Creates a programmatic proposal for networks not using sales management. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' + + +def main(client, programmatic_buyer_id, primary_salesperson_id, + primary_trafficker_id): + proposal_service = client.GetService('ProposalService', version='v201905') + + proposal = { + # Setting required Marketplace information. + 'isProgrammatic': 'true', + 'marketplaceInfo': { + 'buyerAccountId': programmatic_buyer_id, + }, + # Set common required fields for proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '100000' + }, + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + } + + proposals = proposal_service.createProposals([proposal]) + + # Display results. + for proposal in proposals: + print('Programmatic proposal with id "%s" and name "%s" was created.' % + (proposal['id'], proposal['name'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201905/proposal_service/create_proposals.py b/examples/ad_manager/v201905/proposal_service/create_proposals.py new file mode 100755 index 00000000..12437bea --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/create_proposals.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new proposals. + +To determine which proposals exist, run get_all_proposals.py. +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' +SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' +PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' + + +def main(client, advertiser_id, primary_salesperson_id, + secondary_salesperson_id, primary_trafficker_id): + # Initialize appropriate services. + proposal_service = client.GetService('ProposalService', version='v201905') + network_service = client.GetService('NetworkService', version='v201905') + + # Create proposal objects. + proposal = { + 'name': 'Proposal #%s' % uuid.uuid4(), + 'advertiser': { + 'companyId': advertiser_id, + 'type': 'ADVERTISER' + }, + 'primarySalesperson': { + 'userId': primary_salesperson_id, + 'split': '75000' + }, + 'secondarySalespeople': [{ + 'userId': secondary_salesperson_id, + 'split': '25000' + }], + 'primaryTraffickerId': primary_trafficker_id, + 'probabilityOfClose': '100000', + 'budget': { + 'microAmount': '100000000', + 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] + }, + 'billingCap': 'CAPPED_CUMULATIVE', + 'billingSource': 'DFP_VOLUME' + } + + # Add proposals. + proposals = proposal_service.createProposals([proposal]) + + # Display results. + for proposal in proposals: + print ('Proposal with id "%s" and name "%s" was created.' + % (proposal['id'], proposal['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, + SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201905/proposal_service/get_all_proposals.py b/examples/ad_manager/v201905/proposal_service/get_all_proposals.py new file mode 100755 index 00000000..ffd23d4f --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/get_all_proposals.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 proposals. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201905') + + # Create a statement to select proposals. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of proposals at a time, paging + # through until all proposals have been retrieved. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for proposal in response['results']: + # Print out some information for each proposal. + print('Proposal with ID "%d" and name "%s" was found.\n' % + (proposal['id'], proposal['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py new file mode 100755 index 00000000..f601235b --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the Marketplace comments for a programmatic proposal.""" + +# Import appropriate modules from the client library. +from datetime import datetime + +from googleads import ad_manager + + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + marketplace_comment_service = client.GetService( + 'ProposalService', version='v201905') + query = 'WHERE proposalId = %s' % proposal_id + # Create a statement to select marketplace comments. + statement = {'query': query} + + response = marketplace_comment_service.getMarketplaceCommentsByStatement( + statement) + + # Print out some information for each marketplace comment. + for marketplace_comment in response['results']: + date_time = marketplace_comment['creationTime'] + date_time_string = datetime(date_time['date']['year'], + date_time['date']['month'], + date_time['date']['day'], date_time['hour'], + date_time['minute'], + date_time['second']).isoformat() + print('Marketplace comment with creation time "%s"and comment "%s" was ' + 'found.\n' % (date_time_string, marketplace_comment['comment'])) + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py new file mode 100755 index 00000000..2d6dccb2 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 proposals pending approval. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201905') + # Create a statement to select proposals. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('status = :status') + .WithBindVariable('status', 'PENDING_APPROVAL')) + + # Retrieve a small amount of proposals at a time, paging + # through until all proposals have been retrieved. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for proposal in response['results']: + # Print out some information for each proposal. + print('Proposal with ID "%d" and name "%s" was found.\n' % + (proposal['id'], proposal['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py new file mode 100755 index 00000000..22b09c42 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 code example requests buyer acceptance for a single proposal. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) + proposals_pushed_to_marketplace = 0 + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + # Display results. + for proposal in response['results']: + print ('Programmatic proposal with id "%s", name "%s", and status ' + '"%s" will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) + # Perform action. + result = proposal_service.performProposalAction( + {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposals_pushed_to_marketplace += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if proposals_pushed_to_marketplace > 0: + print ('\nNumber of programmatic proposals pushed to Marketplace: %s' + % proposals_pushed_to_marketplace) + else: + print '\nNo programmatic proposals were pushed to Marketplace.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py new file mode 100755 index 00000000..8e3de01b --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example approves a single proposal. + +To determine which proposals exist, run get_all_proposals.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :proposalId') + .WithBindVariable('proposalId', proposal_id)) + proposals_approved = 0 + + # Get proposals by statement. + while True: + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + # Display results. + for proposal in response['results']: + print ('Proposal with id "%s", name "%s", and status "%s" will be' + ' approved.' % (proposal['id'], proposal['name'], + proposal['status'])) + # Perform action. + result = proposal_service.performProposalAction( + {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + proposals_approved += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if proposals_approved > 0: + print '\nNumber of proposals approved: %s' % proposals_approved + else: + print '\nNo proposals were approved.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/proposal_service/update_proposals.py b/examples/ad_manager/v201905/proposal_service/update_proposals.py new file mode 100755 index 00000000..65a32176 --- /dev/null +++ b/examples/ad_manager/v201905/proposal_service/update_proposals.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates the notes of a single proposal specified by ID. + +To determine which proposals exist, run get_all_proposals.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + proposal_service = client.GetService('ProposalService', version='v201905') + + # Create statement object to select a single proposal by an ID. + + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :proposalId') + .WithBindVariable('proposalId', long(proposal_id)) + .Limit(1)) + + # Get proposals by statement. + response = proposal_service.getProposalsByStatement(statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local proposal object by changing its notes. + updated_proposals = [] + for proposal in response['results']: + proposal['internalNotes'] = 'Proposal needs review before approval.' + updated_proposals.append(proposal) + + # Update proposals remotely. + proposals = proposal_service.updateProposals(updated_proposals) + + # Display results. + if proposals: + for proposal in proposals: + print ('Proposal with id "%s", name "%s", and ' + 'notes "%s" was updated.' + % (proposal['id'], proposal['name'], proposal['internalNotes'])) + else: + print 'No proposals were updated.' + else: + print 'No proposals found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/__init__.py b/examples/ad_manager/v201905/publisher_query_language_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/publisher_query_language_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py new file mode 100755 index 00000000..79e9d467 --- /dev/null +++ b/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 fetches data from PQL tables and creates match table files.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201905') + + line_items_file = tempfile.NamedTemporaryFile( + prefix='line_items_', suffix='.csv', mode='w', delete=False) + ad_units_file = tempfile.NamedTemporaryFile( + prefix='ad_units_', suffix='.csv', mode='w', delete=False) + + line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id ' + 'ASC') + ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC' + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + line_items_pql_query, line_items_file) + report_downloader.DownloadPqlResultToCsv( + ad_units_pql_query, ad_units_file) + + line_items_file.close() + ad_units_file.close() + + print 'Saved line items to... %s' % line_items_file.name + print 'Saved ad units to... %s' % ad_units_file.name + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py new file mode 100755 index 00000000..eaf42c4b --- /dev/null +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 browsers available to target from the Browser table. + +Other tables include 'Bandwidth_Group', 'Browser_Language', +'Device_Capability', 'Operating_System', etc... + +A full list of available criteria tables can be found at +https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService +""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201905') + + with tempfile.NamedTemporaryFile( + prefix='browser_data_', + suffix='.csv', mode='w', delete=False) as browser_data_file: + + browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion ' + 'FROM Browser ' + 'ORDER BY BrowserName ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + browser_pql_query, browser_data_file) + + print 'Saved browser data to... %s' % browser_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py new file mode 100755 index 00000000..b9343f44 --- /dev/null +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 fetches programmatic buyer information from the PQL table.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize a report downloader. + data_downloader = client.GetDataDownloader(version='v201905') + + programmatic_buyers_file = tempfile.NamedTemporaryFile( + prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) + + programmatic_buyers_query = ('SELECT BuyerAccountId, Name ' + 'FROM Programmatic_Buyer ' + 'ORDER BY BuyerAccountId ASC') + + # Downloads the response from PQL select statement to the specified file + data_downloader.DownloadPqlResultToCsv( + programmatic_buyers_query, programmatic_buyers_file) + + programmatic_buyers_file.close() + + print 'Saved programmatic buyers to... %s' % programmatic_buyers_file.name + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py new file mode 100755 index 00000000..0648bbf6 --- /dev/null +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 downloads geo targeting constants using PQL.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the type of geo target to query for. +GEO_TARGET_TYPE = 'City' + + +def main(client, geo_target_type): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201905') + + with tempfile.NamedTemporaryFile( + prefix='geo_data_', + suffix='.csv', mode='w', delete=False) as geo_data_file: + + geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' + 'CountryCode, Type ' + 'FROM Geo_Target ' + 'WHERE Type = :type AND Targetable = true ' + 'ORDER BY CountryCode ASC, Name ASC') + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + geo_pql_query, geo_data_file, {'type': geo_target_type}) + + print 'Saved geo data to... %s' % geo_data_file.name + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, GEO_TARGET_TYPE) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py new file mode 100755 index 00000000..2dec29a2 --- /dev/null +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 fetches line items from the pql table with a LIKE clause.""" + + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize a report downloader. + report_downloader = client.GetDataDownloader(version='v201905') + + with tempfile.NamedTemporaryFile( + prefix='line_items_', + suffix='.csv', mode='w', delete=False) as line_items_file: + + line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item " + "WHERE Name LIKE 'line item%' " + "ORDER BY Id ASC") + + # Downloads the response from PQL select statement to the specified file + report_downloader.DownloadPqlResultToCsv( + line_items_pql_query, line_items_file) + + print 'Saved line items to... %s' % line_items_file.name + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py new file mode 100755 index 00000000..fa025b0d --- /dev/null +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Gets recent changes in your network using the Change_History table. + +A full list of available tables can be found at: +https://developers.google.com/doubleclick-publishers/docs/reference/latest/PublisherQueryLanguageService +""" + +from datetime import date +from datetime import datetime +from datetime import timedelta + +# Import appropriate modules from the client library. +from googleads import ad_manager +import pytz + + +def main(client): + # Initialize appropriate service. + pql_service = client.GetService('PublisherQueryLanguageService', 'v201905') + + end_date = datetime.now(tz=pytz.timezone('America/New_York')) + start_date = end_date - timedelta(days=1) + initial_query = ('ChangeDateTime > :startDateTime ' + 'AND ChangeDateTime < :endDateTime') + pagination_query = 'Id < :id AND ' + initial_query + + statement = (ad_manager.StatementBuilder(version='v201905') + .Select(('Id, ChangeDateTime, EntityId, EntityType, ' + 'Operation, UserId')) + .From('Change_History') + .Where(initial_query) + .OrderBy('ChangeDateTime', ascending=False) + .WithBindVariable('startDateTime', start_date) + .WithBindVariable('endDateTime', end_date)) + + keep_iterating = True + i = 0 + total_rows = [] + + while keep_iterating: + response = pql_service.select(statement.ToStatement()) + column_types = ([column_type['labelName'] + for column_type in response['columnTypes']]) + rows = response['rows'] + rows_length = len(rows) + total_rows.extend(rows) + + if rows and rows_length > 0: + # Get the earliest change ID in the result set. + last_row = rows[-1] + last_id = last_row['values'][0]['value'] + i += 1 + + # Update the statement using the earliest row in the previous result. + statement.Where(pagination_query) + statement.WithBindVariable('id', last_id) + + print ('%d) %d changes prior to ID "%s" were found.\n' + % (i, rows_length, last_id)) + + keep_iterating = rows and len(rows) == statement.limit + + # Print out columns header + print ','.join(column_types) + + # Print out every row + for row in total_rows: + print ConvertValueForCsv(row) + + +def ConvertValueForCsv(pql_value): + """Sanitizes a field value from a Value object to a CSV suitable format. + + Args: + pql_value: dict a dictionary containing the data for a single field of an + entity. + + Returns: + str a CSV writer friendly value formatted by Value.Type. + """ + if 'value' in pql_value: + field = pql_value['value'] + elif 'values' in pql_value: + field = pql_value['values'] + else: + field = None + + if field: + if isinstance(field, list): + return ','.join(['"%s"' % str(ConvertValueForCsv(single_field)) + for single_field in field]) + else: + class_type = ad_manager.AdManagerClassType(pql_value) + + if class_type == 'TextValue': + return field.replace('"', '""').encode('UTF8') + elif class_type == 'NumberValue': + return float(field) if '.' in field else int(field) + elif class_type == 'DateTimeValue': + return ConvertDateTimeToOffset(field) + elif class_type == 'DateValue': + return date(int(field['date']['year']), + int(field['date']['month']), + int(field['date']['day'])).isoformat() + else: + return field + else: + return '-' + + +def ConvertDateTimeToOffset(date_time_value): + """Converts the PQL formatted response for a dateTime object. + + Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.' + + Args: + date_time_value: dict The date time value from the PQL response. + + Returns: + str: A string representation of the date time value uniform to + ReportService. + """ + date_time_obj = datetime(int(date_time_value['date']['year']), + int(date_time_value['date']['month']), + int(date_time_value['date']['day']), + int(date_time_value['hour']), + int(date_time_value['minute']), + int(date_time_value['second'])) + date_time_str = pytz.timezone( + date_time_value['timeZoneId']).localize(date_time_obj).isoformat() + + if date_time_str[-5:] == '00:00': + return date_time_str[:-6] + 'Z' + else: + return date_time_str + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/rate_card_service/__init__.py b/examples/ad_manager/v201905/rate_card_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/rate_card_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py new file mode 100755 index 00000000..5639ddae --- /dev/null +++ b/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 creates a new rate card. + +To determine which rate cards exist, run get_all_rate_cards.py. +""" + +# Import appropriate modules from the client library. +import random + +from googleads import ad_manager + +# Set the IDs of the teams this rate card should be visible to. +TEAM_IDS = ['INSERT_TEAM_ID_HERE'] + +# Set the currency code to create the rate card with. +CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201905') + + # Create a rate card. + rate_card = { + 'name': 'RateCard #%d' % random.randint(0, 100000000), + 'currencyCode': CURRENCY_CODE, + 'pricingModel': 'NET', + } + + # This field is optional. + rate_card['appliedTeamIds'] = TEAM_IDS + + result = rate_card_service.createRateCards([rate_card]) + + for new_rate_card in result: + print ('A rate card with ID %s, name "%s", and currency code "%s" ' + 'was created.' % (new_rate_card['id'], + new_rate_card['name'], + new_rate_card['currencyCode'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py new file mode 100755 index 00000000..ca48f700 --- /dev/null +++ b/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 rate cards. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201905') + + # Create a statement to select rate cards. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of rate cards at a time, paging + # through until all rate cards have been retrieved. + while True: + response = rate_card_service.getRateCardsByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for rate_card in response['results']: + # Print out some information for each rate card. + print('Rate card with ID "%d", name "%s", and currency code "%s" was ' + 'found.\n' % + (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py new file mode 100755 index 00000000..4f209b67 --- /dev/null +++ b/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 rate cards that can be used for Marketplace products. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + rate_card_service = client.GetService('RateCardService', version='v201905') + # Create a statement to select rate cards. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('forMarketplace = :forMarketplace') + .WithBindVariable('forMarketplace', True)) + + # Retrieve a small amount of rate cards at a time, paging + # through until all rate cards have been retrieved. + while True: + response = rate_card_service.getRateCardsByStatement(statement.ToStatement( + )) + if 'results' in response and len(response['results']): + for rate_card in response['results']: + # Print out some information for each rate card. + print( + 'Rate card with ID "%d", name "%s", and currency code "%s" was ' + 'found.\n' + % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py new file mode 100755 index 00000000..57430710 --- /dev/null +++ b/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 line item reports for a given reconciliation report. + +To determine how many reconciliation reports exist, +run get_all_reconciliation_reports.py. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the reconciliation report to query. +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_line_item_report_service = (client.GetService( + 'ReconciliationLineItemReportService', version='v201905')) + + # Create a statement to select reconciliation line item reports. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('reconciliationReportId = :reconciliationReportId AND ' + 'lineItemId != :lineItemId')) + .OrderBy('lineItemId', ascending=True) + .WithBindVariable('reconciliationReportId', + RECONCILIATION_REPORT_ID) + .WithBindVariable('lineItemId', 0)) + + # Retrieve a small amount of reconciliation line item reports at a time, + # paging through until all reconciliation line item reports have been + # retrieved. + result_set_size = 0 + should_continue = True + + while should_continue: + page = (reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement( + statement.ToStatement())) + if 'results' in page and len(page['results']): + result_set_size += page['totalResultSetSize'] + # Iterate over individual results in the page. + for line_item_report in page['results']: + print ('Reconciliation line item report with ID %d, line item ID %d, ' + 'reconciliation source "%s", and reconciled volume %d was ' + 'found.' % (line_item_report['id'], + line_item_report['lineItemId'], + line_item_report['reconciliationSource'], + (line_item_report['reconciledVolume'] + if 'reconciledVolume' in line_item_report else 0))) + # Update statement for next page. + statement.offset += statement.limit + should_continue = statement.offset < result_set_size + + print 'Number of results found: %d' % result_set_size + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py new file mode 100755 index 00000000..ecdfacf7 --- /dev/null +++ b/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 updates a reconciliation line item report. + +To get reconciliation line item reports for a reconciliation report, run +get_reconciliation_line_item_reports_for_reconciliation_report.py +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the reconciliation line item report to update. +RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_line_item_report_service = (client.GetService( + 'ReconciliationLineItemReportService', version='v201905')) + + # Create a statement to select a reconciliation line item report. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :lineItemReportId') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('lineItemReportId', + RECONCILIATION_LINE_ITEM_REPORT_ID)) + + # Get reconciliation line item reports by statement. + page = (reconciliation_line_item_report_service + .getReconciliationLineItemReportsByStatement(statement.ToStatement())) + + line_item_report = page['results'][0] + + # Set and use a manual volume for billing. This example splits the difference + # between Ad Manager and the third party volume. + line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + + line_item_report['thirdPartyVolume']) / 2 + line_item_report['reconciliationSource'] = 'MANUAL' + + result = (reconciliation_line_item_report_service + .updateReconciliationLineItemReports([line_item_report])) + + for updated_report in result: + print ('Reconciliation line item report with ID %d for line item ID %d was ' + 'updated, with manual volume %d' % (updated_report['id'], + updated_report['lineItemId'], + updated_report['manualVolume'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py new file mode 100755 index 00000000..f013e3a6 --- /dev/null +++ b/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. +"""Gets all reconciliation order reports for a given reconciliation report. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_order_report_service = client.GetService( + 'ReconciliationOrderReportService', version='v201905') + # Create a statement to select reconciliation order reports. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('reconciliationReportId = :reconciliationReportId') + .WithBindVariable('reconciliationReportId', + reconciliation_report_id)) + + # Retrieve a small amount of reconciliation order reports at a time, paging + # through until all reconciliation order reports have been retrieved. + while True: + response = ( + reconciliation_order_report_service + .getReconciliationOrderReportsByStatement( + statement.ToStatement())) + if 'results' in response and len(response['results']): + for reconciliation_order_report in response['results']: + # Print out some information for each reconciliation order report. + print('Reconciliation order report with ID "%d" and status "%s" was ' + 'found.\n' % (reconciliation_order_report['id'], + reconciliation_order_report['status'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py new file mode 100755 index 00000000..2b09b47c --- /dev/null +++ b/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 submits a reconciliation order report. + +To get all reconciliation order reports for a reconciliation report, +run get get_reconciliation_order_reports_for_reconciliation_report.py. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the reconciliation order report to submit. +RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_order_report_service = (client.GetService( + 'ReconciliationOrderReportService', version='v201905')) + + # Create a statement to select reconciliation order reports. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .OrderBy('id', ascending=True) + .Limit(1) + .WithBindVariable('id', RECONCILIATION_ORDER_REPORT_ID)) + + # Get reconciliation order reports by statement. + page = (reconciliation_order_report_service + .getReconciliationOrderReportsByStatement(statement.ToStatement())) + + report = page['results'][0] + + print ('Reconciliation order report with ID %d will be submitted.' % + report['id']) + + # Remove limit and offset from statement. + statement.limit = None + statement.offset = None + + # Perform action. + result = (reconciliation_order_report_service + .performReconciliationOrderReportAction( + {'xsi_type': 'SubmitReconciliationOrderReports'}, + statement.ToStatement())) + + if result and result['numChanges'] > 0: + print ('Number of reconciliation order reports submitted: %d' % + result['numChanges']) + else: + print 'No reconciliation order reports were submitted.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py new file mode 100755 index 00000000..20e3f822 --- /dev/null +++ b/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2016 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. + +"""Gets a reconciliation report's rows for line items that Ad Manager served. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the reconciliation report row. +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client, reconciliation_report_id): + # Initialize appropriate service. + reconciliation_report_row_service = client.GetService( + 'ReconciliationReportRowService', version='v201905') + + # Create a statement to select reconciliation report rows. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('reconciliationReportId = :reportId ' + 'AND lineItemId != :lineItemId')) + .WithBindVariable('lineItemId', 0) + .WithBindVariable('reportId', long(reconciliation_report_id))) + + # Retrieve a small amount of reconciliation report rows at a time, paging + # through until all reconciliation report rows have been retrieved. + while True: + response = ( + reconciliation_report_row_service + .getReconciliationReportRowsByStatement( + statement.ToStatement())) + if 'results' in response and len(response['results']): + for reconciliation_report_row in response['results']: + # Print out some information for each reconciliation report row. + print('Reconciliation report row with ID "%d", reconciliation source ' + '"%s", and reconciled volume "%d" was found.\n' % + (reconciliation_report_row['id'], + reconciliation_report_row['reconciliationSource'], + reconciliation_report_row['reconciledVolume'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py new file mode 100755 index 00000000..9bbcb882 --- /dev/null +++ b/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 updates a reconciliation report row. + +To determine which reconciliation report rows exist, +run get_reconciliation_report_rows_for_reconciliation_report.py +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the ID of the reconciliation report row. +RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' + +# Set the ID of the reconciliation report. +RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' + + +def main(client): + # Initialize appropriate service. + reconciliation_report_row_service = (client.GetService( + 'ReconciliationReportRowService', version='v201905')) + + # Create a statement to select reconciliation report rows. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('id = :reconciliationReportRowId AND ' + 'reconciliationReportId = :reconciliationReportId')) + .OrderBy('id', ascending=True) + .WithBindVariable('reconciliationReportRowId', + RECONCILIATION_REPORT_ROW_ID) + .WithBindVariable('reconciliationReportId', + RECONCILIATION_REPORT_ID)) + + # Get reconciliation report rows by statement. + page = (reconciliation_report_row_service + .getReconciliationReportRowsByStatement(statement.ToStatement())) + + row = page['results'][0] + + # Set a comment on the reconciliation report row. + row['comments'] = ('Third part volume didn\'t match DFP - we agreed to split ' + 'the difference') + + # Set and use a manual volume for billing. + row['manualVolume'] = (row['dfpVolume'] + row['thirdPartyVolume']) / 2 + row['reconciliationSource'] = 'MANUAL' + + updated_rows = (reconciliation_report_row_service + .updateReconciliationReportRows([row])) + + for updated_row in updated_rows: + print ('Reconciliation report row for line item ID %d and creative ID %d ' + 'was updated, with manual volume %d' % (updated_row['lineItemId'], + updated_row['creativeId'], + updated_row['manualVolume'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py new file mode 100755 index 00000000..4696745a --- /dev/null +++ b/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 reconciliation reports. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + reconciliation_report_service = client.GetService( + 'ReconciliationReportService', version='v201905') + + # Create a statement to select reconciliation reports. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of reconciliation reports at a time, paging + # through until all reconciliation reports have been retrieved. + while True: + response = ( + reconciliation_report_service + .getReconciliationReportsByStatement( + statement.ToStatement())) + if 'results' in response and len(response['results']): + for reconciliation_report in response['results']: + # Print out some information for each reconciliation report. + print( + 'Reconciliation report with ID "%d", month "%d", and year "%d" was' + ' found.\n' % (reconciliation_report['id'], + reconciliation_report['startDate']['month'], + reconciliation_report['startDate']['year'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py new file mode 100755 index 00000000..bcfb4210 --- /dev/null +++ b/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 the previous billing period's reconciliation report. +""" + +# Import appropriate modules from the client library. +from datetime import date +from datetime import timedelta + +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + reconciliation_report_service = client.GetService( + 'ReconciliationReportService', version='v201905') + + first_of_the_month = date.today().replace(day=1) + last_month = first_of_the_month - timedelta(days=1) + + # Create a statement to select reconciliation reports. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('startDate = :startDate') + .WithBindVariable('startDate', last_month)) + + # Retrieve a small amount of reconciliation reports at a time, paging + # through until all reconciliation reports have been retrieved. + while True: + response = ( + reconciliation_report_service + .getReconciliationReportsByStatement( + statement.ToStatement())) + if 'results' in response and len(response['results']): + for reconciliation_report in response['results']: + # Print out some information for each reconciliation report. + print( + 'Reconciliation report with ID "%d" and start date "%s" was found.' + '\n' % (reconciliation_report['id'], + last_month.strftime('%Y-%m-01'))) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/report_service/__init__.py b/examples/ad_manager/v201905/report_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/report_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py new file mode 100755 index 00000000..7ad98b1f --- /dev/null +++ b/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2018 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. + +"""Runs a report on Ad Exchange data via the Ad Manager API.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201905') + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'], + 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS', + 'AD_EXCHANGE_ESTIMATED_REVENUE'], + 'dateRangeType': 'LAST_WEEK', + 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time + 'adxReportCurrency': 'EUR' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/report_service/run_delivery_report.py b/examples/ad_manager/v201905/report_service/run_delivery_report.py new file mode 100755 index 00000000..7bf193d1 --- /dev/null +++ b/examples/ad_manager/v201905/report_service/run_delivery_report.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. + +"""Runs a report similar to the "Orders report" on the Ad Manager website. + +Includes additional attributes and can filter to include just one order. +""" + +from datetime import datetime +from datetime import timedelta +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + +ORDER_ID = 'INSERT_ORDER_ID_HERE' + + +def main(client, order_id): + # Create statement object to filter for an order. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('ORDER_ID = :id') + .WithBindVariable('id', long(order_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) + + # Set the start and end dates of the report to run (past 8 days). + end_date = datetime.now().date() + start_date = end_date - timedelta(days=8) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['ORDER_ID', 'ORDER_NAME'], + 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', + 'ORDER_END_DATE_TIME'], + 'statement': statement.ToStatement(), + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': start_date, + 'endDate': end_date + } + } + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201905') + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/ad_manager/v201905/report_service/run_inventory_report.py b/examples/ad_manager/v201905/report_service/run_inventory_report.py new file mode 100755 index 00000000..1becffc6 --- /dev/null +++ b/examples/ad_manager/v201905/report_service/run_inventory_report.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 runs a typical daily inventory report.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + + +def main(client): + # Initialize appropriate service. + network_service = client.GetService('NetworkService', version='v201905') + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201905') + + # Get root ad unit id for network. + root_ad_unit_id = ( + network_service.getCurrentNetwork()['effectiveRootAdUnitId']) + + # Set filter statement and bind value for reportQuery. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') + .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .Limit(None) # No limit or offset for reports + .Offset(None)) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['DATE', 'AD_UNIT_NAME'], + 'adUnitView': 'HIERARCHICAL', + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS', + 'ADSENSE_LINE_ITEM_LEVEL_CLICKS', + 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', + 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'], + 'dateRangeType': 'LAST_WEEK', + 'statement': statement.ToStatement() + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/report_service/run_reach_report.py b/examples/ad_manager/v201905/report_service/run_reach_report.py new file mode 100755 index 00000000..8cc78626 --- /dev/null +++ b/examples/ad_manager/v201905/report_service/run_reach_report.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example runs a reach report.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201905') + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'], + 'dateRangeType': 'REACH_LIFETIME' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py new file mode 100755 index 00000000..9d72cb5e --- /dev/null +++ b/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2017 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. + +"""Runs a report for LineItems with additional data from a PQL table. + +Fetches a basic report over a network's LineItems and then adds some +extra columns which might be useful for future analysis, such as +LineItemType, from the PQL Line_Item table, creating a match table. +""" + +from datetime import date +from datetime import timedelta +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + +try: + import pandas +except ImportError: + raise ImportError('This example requires the pandas library to be installed.') + + +def main(client): + # Set the start and end dates of the report to run (past 8 days). + end_date = date.today() + start_date = end_date - timedelta(days=8) + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', + 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'CUSTOM_DATE', + 'startDate': start_date, + 'endDate': end_date + } + } + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201905') + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + + with tempfile.NamedTemporaryFile( + suffix='.csv.gz', mode='wb', delete=False) as report_file: + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, 'CSV_DUMP', report_file) + + # Create a PQL query to fetch the line item data + line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem') + + # Download the response from PQL select statement + line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) + + # Use pandas to join the two csv files into a match table + report = pandas.read_csv(report_file.name) + line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0]) + merged_result = pandas.merge(report, line_items, + left_on='Dimension.LINE_ITEM_ID', right_on='id') + merged_result.to_csv('~/complete_line_items_report.csv', index=False) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py new file mode 100755 index 00000000..6f351771 --- /dev/null +++ b/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. + +"""Runs a report with custom fields found in the line items of an order.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + +# Set the ID of the order to get line items from. +ORDER_ID = 'INSERT_ORDER_ID_HERE' + + +def main(client, order_id): + # Initialize appropriate service. + line_item_service = client.GetService('LineItemService', version='v201905') + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201905') + + # Filter for line items of a given order. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('orderId = :orderId') + .WithBindVariable('orderId', long(order_id))) + + # Collect all line item custom field IDs for an order. + custom_field_ids = set() + + # Get users by statement. + while True: + response = line_item_service.getLineItemsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + # Get custom field IDs from the line items of an order. + for line_item in response['results']: + if 'customFieldValues' in line_item: + for custom_field_value in line_item['customFieldValues']: + custom_field_ids.add(custom_field_value['customFieldId']) + statement.offset += statement.limit + else: + break + + # Modify statement for reports + statement.limit = None + statement.offset = None + statement.Where('ORDER_ID = :orderId') + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'statement': statement.ToStatement(), + 'columns': ['AD_SERVER_IMPRESSIONS'], + 'dateRangeType': 'LAST_MONTH', + 'customFieldIds': list(custom_field_ids) + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ORDER_ID) diff --git a/examples/ad_manager/v201905/report_service/run_sales_report.py b/examples/ad_manager/v201905/report_service/run_sales_report.py new file mode 100755 index 00000000..28b1c714 --- /dev/null +++ b/examples/ad_manager/v201905/report_service/run_sales_report.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. + +"""Runs a report equal to the 'Sales by salespersons report'.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201905') + + # Create report job. + report_job = { + 'reportQuery': { + 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'], + 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE', + 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], + 'dateRangeType': 'LAST_MONTH' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/report_service/run_saved_query.py b/examples/ad_manager/v201905/report_service/run_saved_query.py new file mode 100755 index 00000000..f19dbae8 --- /dev/null +++ b/examples/ad_manager/v201905/report_service/run_saved_query.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 runs a report from a saved query. +""" + +# Import appropriate modules from the client library. +import tempfile + +from googleads import ad_manager +from googleads import errors + +SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' + + +def main(client, saved_query_id): + # Initialize appropriate service. + report_service = client.GetService('ReportService', version='v201905') + + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v201905') + + # Create statement object to filter for an order. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :id') + .WithBindVariable('id', long(saved_query_id)) + .Limit(1)) + + response = report_service.getSavedQueriesByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + saved_query = response['results'][0] + + if saved_query['isCompatibleWithApiVersion']: + report_job = {} + + # Set report query and optionally modify it. + report_job['reportQuery'] = saved_query['reportQuery'] + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError, e: + print 'Failed to generate report. Error was: %s' % e + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print 'Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name) + else: + print 'The query specified is not compatible with the API version.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, SAVED_QUERY_ID) diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201905/suggested_ad_unit_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/suggested_ad_unit_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py new file mode 100755 index 00000000..88da4959 --- /dev/null +++ b/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example approves all suggested ad units with 50 or more requests. + +This feature is only available to Ad Manager 360 solution networks. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +THRESHOLD_NUMBER_OF_REQUESTS = '50' + + +def main(client): + # Initialize appropriate service. + suggested_ad_unit_service = client.GetService( + 'SuggestedAdUnitService', version='v201905') + + # Create a filter statement. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('numRequests > :numRequests') + .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) + num_approved_suggested_ad_units = 0 + + # Get suggested ad units by statement. + while True: + response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + # Print suggested ad units that will be approved. + for suggested_ad_unit in response['results']: + print ('Suggested ad unit with id "%s", and number of requests "%s"' + ' will be approved.' % (suggested_ad_unit['id'], + suggested_ad_unit['numRequests'])) + + # Approve suggested ad units. + result = suggested_ad_unit_service.performSuggestedAdUnitAction( + {'xsi_type': 'ApproveSuggestedAdUnits'}, + statement.ToStatement()) + if result and int(result['numChanges']) > 0: + num_approved_suggested_ad_units += int(result['numChanges']) + else: + break + + if num_approved_suggested_ad_units > 0: + print ('Number of suggested ad units approved: %s' % + num_approved_suggested_ad_units) + else: + print 'No suggested ad units were approved.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) + diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py new file mode 100755 index 00000000..aa279f00 --- /dev/null +++ b/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 suggested ad units. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + suggested_ad_unit_service = client.GetService( + 'SuggestedAdUnitService', version='v201905') + + # Create a statement to select suggested ad units. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of suggested ad units at a time, paging + # through until all suggested ad units have been retrieved. + while True: + response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for suggested_ad_unit in response['results']: + # Print out some information for each suggested ad unit. + print( + 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' + % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py new file mode 100755 index 00000000..6372772d --- /dev/null +++ b/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 highly requested suggested ad units. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE' + + +def main(client, num_requests): + # Initialize appropriate service. + suggested_ad_unit_service = client.GetService( + 'SuggestedAdUnitService', version='v201905') + # Create a statement to select suggested ad units. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('numRequests >= :numRequests') + .WithBindVariable('numRequests', long(num_requests))) + + # Retrieve a small amount of suggested ad units at a time, paging + # through until all suggested ad units have been retrieved. + while True: + response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for suggested_ad_unit in response['results']: + # Print out some information for each suggested ad unit. + print( + 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' + % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, NUM_REQUESTS) diff --git a/examples/ad_manager/v201905/targeting_preset_service/__init__.py b/examples/ad_manager/v201905/targeting_preset_service/__init__.py new file mode 100755 index 00000000..6d126cce --- /dev/null +++ b/examples/ad_manager/v201905/targeting_preset_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2019 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. diff --git a/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py new file mode 100755 index 00000000..a3cb3a61 --- /dev/null +++ b/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2019 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 targeting presets. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + targeting_preset_service = client.GetService( + 'TargetingPresetService', version='v201905') + + # Create a statement to select suggested ad units. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small number of targeting presets at a time, paging + # through until all targeting presets have been retrieved. + while True: + response = targeting_preset_service.getTargetingPresetsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for targeting_preset in response['results']: + # Print out some information for each targeting preset. + print( + 'Targeting preset with ID "%s" and name "%d" was found.\n' + % (targeting_preset['id'], targeting_preset['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/team_service/__init__.py b/examples/ad_manager/v201905/team_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/team_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/team_service/create_teams.py b/examples/ad_manager/v201905/team_service/create_teams.py new file mode 100755 index 00000000..bcfaa628 --- /dev/null +++ b/examples/ad_manager/v201905/team_service/create_teams.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 creates new teams. + +To determine which teams exist, run get_all_teams.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + team_service = client.GetService('TeamService', version='v201905') + + # Create team objects. + teams = [] + for _ in xrange(5): + team = { + 'name': 'Team %s' % uuid.uuid4(), + 'hasAllCompanies': 'false', + 'hasAllInventory': 'false', + 'teamAccessType': 'READ_WRITE' + } + teams.append(team) + + # Add Teams. + teams = team_service.createTeams(teams) + + # Display results. + for team in teams: + print ('Team with ID "%s" and name "%s" was created.' + % (team['id'], team['name'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/team_service/get_all_teams.py b/examples/ad_manager/v201905/team_service/get_all_teams.py new file mode 100755 index 00000000..73d71ac7 --- /dev/null +++ b/examples/ad_manager/v201905/team_service/get_all_teams.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 teams. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + team_service = client.GetService('TeamService', version='v201905') + + # Create a statement to select teams. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of teams at a time, paging + # through until all teams have been retrieved. + while True: + response = team_service.getTeamsByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for team in response['results']: + # Print out some information for each team. + print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], + team['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/team_service/update_teams.py b/examples/ad_manager/v201905/team_service/update_teams.py new file mode 100755 index 00000000..26b6aa4b --- /dev/null +++ b/examples/ad_manager/v201905/team_service/update_teams.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates teams by changing its description. + +To determine which teams exist, run get_all_teams.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +TEAM_ID = 'INSERT_TEAM_ID_HERE' + + +def main(client, team_id): + # Initialize appropriate service. + team_service = client.GetService('TeamService', version='v201905') + + # Create a filter statement to select a single team by ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :teamId') + .WithBindVariable('teamId', long(team_id))) + + # Get teams by statement. + response = team_service.getTeamsByStatement(statement.ToStatement()) + + if 'results' in response and len(response['results']): + updated_teams = [] + # Update each local team object by changing its description. + for team in response['results']: + team['description'] = 'this team is great!' + updated_teams.append(team) + + # Update teams on the server. + teams = team_service.updateTeams(updated_teams) + + # Display results. + for team in teams: + print ('Team with id "%s" and name "%s" was updated.' + % (team['id'], team['name'])) + else: + print 'No teams found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TEAM_ID) diff --git a/examples/ad_manager/v201905/user_service/__init__.py b/examples/ad_manager/v201905/user_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/user_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/user_service/create_users.py b/examples/ad_manager/v201905/user_service/create_users.py new file mode 100755 index 00000000..8264c249 --- /dev/null +++ b/examples/ad_manager/v201905/user_service/create_users.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates new users. + +To determine which users exist, run get_all_users.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' +NEW_USER_NAME = 'INSERT_NAME_HERE' + + +def main(client, email, name): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201905') + + # Create user objects. + users = [ + { + 'email': email, + 'name': name, + } + ] + for user in users: + # Set the system defined ID of the trafficker role. + # To determine what other roles exist, run get_all_roles.py. + user['roleId'] = '-7' + + # Add users. + users = user_service.createUsers(users) + + # Display results. + for user in users: + print ('User with id "%s", email "%s", and role "%s" was created.' + % (user['id'], user['email'], user['roleName'])) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) diff --git a/examples/ad_manager/v201905/user_service/deactivate_users.py b/examples/ad_manager/v201905/user_service/deactivate_users.py new file mode 100755 index 00000000..099e00a0 --- /dev/null +++ b/examples/ad_manager/v201905/user_service/deactivate_users.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example deactivates a user. + +Deactivated users can no longer make requests to the API. The user making the +request cannot deactivate itself. To determine which users exist, run +get_all_users.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE' + + +def main(client, user_id): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) + + # Get users by statement. + response = user_service.getUsersByStatement(statement.ToStatement()) + users = response['results'] if 'results' in response else [] + + for user in users: + print ('User with id "%s", email "%s", and status "%s" will be ' + 'deactivated.' + % (user['id'], user['email'], + {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) + print 'Number of users to be deactivated: %s' % len(users) + + # Perform action. + result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'}, + statement.ToStatement()) + + # Display results. + if result and int(result['numChanges']) > 0: + print 'Number of users deactivated: %s' % result['numChanges'] + else: + print 'No users were deactivated.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201905/user_service/get_all_roles.py b/examples/ad_manager/v201905/user_service/get_all_roles.py new file mode 100755 index 00000000..442d35bd --- /dev/null +++ b/examples/ad_manager/v201905/user_service/get_all_roles.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 roles. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201605') + + roles = user_service.getAllRoles() + + # Print out some information for each role. + for role in roles: + print('Role with id "%s" and name "%s" was found.' % + (role['id'], role['name'])) + + print '\nNumber of results found: %s' % len(roles) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/user_service/get_all_users.py b/examples/ad_manager/v201905/user_service/get_all_users.py new file mode 100755 index 00000000..17a5cac4 --- /dev/null +++ b/examples/ad_manager/v201905/user_service/get_all_users.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 users. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201905') + + # Create a statement to select users. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of users at a time, paging + # through until all users have been retrieved. + while True: + response = user_service.getUsersByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for user in response['results']: + # Print out some information for each user. + print('User with ID "%d" and name "%s" was found.\n' % (user['id'], + user['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/user_service/get_current_user.py b/examples/ad_manager/v201905/user_service/get_current_user.py new file mode 100755 index 00000000..d3b17848 --- /dev/null +++ b/examples/ad_manager/v201905/user_service/get_current_user.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# +# Copyright 2017 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 the current user.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201905') + + # Get current user. + user = user_service.getCurrentUser() + + print ('User with ID %d, name "%s", email "%s", and role "%s" ' + 'is the current user.' % ( + user.id, user.name, user.email, user.roleName + )) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/user_service/get_user_by_email_address.py b/examples/ad_manager/v201905/user_service/get_user_by_email_address.py new file mode 100755 index 00000000..4c98d485 --- /dev/null +++ b/examples/ad_manager/v201905/user_service/get_user_by_email_address.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 users by email. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' + + +def main(client, email_address): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201905') + # Create a statement to select users. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('email = :email') + .WithBindVariable('email', email_address)) + + # Retrieve a small amount of users at a time, paging + # through until all users have been retrieved. + while True: + response = user_service.getUsersByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for user in response['results']: + # Print out some information for each user. + print('User with ID "%d" and name "%s" was found.\n' % (user['id'], + user['name'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, EMAIL_ADDRESS) diff --git a/examples/ad_manager/v201905/user_service/update_users.py b/examples/ad_manager/v201905/user_service/update_users.py new file mode 100755 index 00000000..a4f3ae3a --- /dev/null +++ b/examples/ad_manager/v201905/user_service/update_users.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example updates a user by adding " Sr." to the end of their name. + +To determine which users exist, run get_all_users.py. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' + + +def main(client, user_id): + # Initialize appropriate service. + user_service = client.GetService('UserService', version='v201905') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('id = :userId') + .WithBindVariable('userId', long(user_id))) + + # Get users by statement. + response = user_service.getUsersByStatement(statement.ToStatement()) + + if 'results' in response and len(response['results']): + users = response['results'] + for user in users: + user['name'] += ' Sr.' + + # Update users on server. + users = user_service.updateUsers(users) + for user in users: + print ('User with id "%s" and name "%s" was updated.' + % (user['id'], user['name'])) + else: + print 'No users found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201905/user_team_association_service/__init__.py b/examples/ad_manager/v201905/user_team_association_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/user_team_association_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py new file mode 100755 index 00000000..09d71d1b --- /dev/null +++ b/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 adds a user to a team by creating an association between them. + +To determine which teams exists, run get_all_teams.py. To determine which +users exist, run get_all_users.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +TEAM_ID = 'INSERT_TEAM_ID_HERE' +USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE'] + + +def main(client, team_id, user_ids): + # Initialize appropriate service. + user_team_association_service = client.GetService( + 'UserTeamAssociationService', version='v201905') + + user_team_associations = [] + for user_id in user_ids: + user_team_associations.append( + { + 'teamId': team_id, + 'userId': user_id + }) + + # Create the user team association on the server. + user_team_associations = ( + user_team_association_service.createUserTeamAssociations( + user_team_associations)) + + # Display results. + if user_team_associations: + for user_team_association in user_team_associations: + print ('A user team association between user with ID "%s" and team with' + ' ID "%s"was created.' % (user_team_association['userId'], + user_team_association['teamId'])) + else: + print 'No user team associations created.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TEAM_ID, USER_IDS) diff --git a/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py new file mode 100755 index 00000000..a7b8e7e6 --- /dev/null +++ b/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 removes the user from all its teams. + +To determine which users exist, run get_all_users.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +USER_ID = 'INSERT_USER_ID_HERE' + + +def main(client, user_id): + # Initialize appropriate service. + user_team_association_service = client.GetService( + 'UserTeamAssociationService', version='v201905') + + # Create filter text to select user team associations by the user ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) + + # Get user team associations by statement. + response = user_team_association_service.getUserTeamAssociationsByStatement( + statement.ToStatement()) + user_team_associations = response['results'] if 'results' in response else [] + + for user_team_association in user_team_associations: + print ('User team association between user with ID "%s" and team with ' + 'ID "%s" will be deleted.' % (user_team_association['userId'], + user_team_association['teamId'])) + print ('Number of teams that the user will be removed from: %s' % + len(user_team_associations)) + + # Action doesn't require limit/offset + statement.limit = None + statement.offset = None + + # Perform action. + result = user_team_association_service.performUserTeamAssociationAction( + {'xsi_type': 'DeleteUserTeamAssociations'}, + statement.ToStatement()) + + # Display results. + if result and int(result['numChanges']) > 0: + print ('Number of teams that the user was removed from: %s' + % result['numChanges']) + else: + print 'No user team associations were deleted.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py new file mode 100755 index 00000000..85024b2e --- /dev/null +++ b/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 user team associations. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + user_team_association_service = client.GetService( + 'UserTeamAssociationService', version='v201905') + + # Create a statement to select user team associations. + statement = ad_manager.StatementBuilder(version='v201905') + + # Retrieve a small amount of user team associations at a time, paging + # through until all user team associations have been retrieved. + while True: + response = user_team_association_service.getUserTeamAssociationsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for user_team_association in response['results']: + # Print out some information for each user team association. + print('User team association with team id "%d" and user id "%d" was ' + 'found.\n' % (user_team_association['teamId'], + user_team_association['userId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py new file mode 100755 index 00000000..fa43ae3e --- /dev/null +++ b/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 user team associations (i.e. teams) for a given user. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +USER_ID = 'INSERT_USER_ID_HERE' + + +def main(client, user_id): + # Initialize appropriate service. + user_team_association_service = client.GetService( + 'UserTeamAssociationService', version='v201905') + # Create a statement to select user team associations. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) + + # Retrieve a small amount of user team associations at a time, paging + # through until all user team associations have been retrieved. + while True: + response = user_team_association_service.getUserTeamAssociationsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for user_team_association in response['results']: + # Print out some information for each user team association. + print('User team association with user ID "%d" and team ID "%d" was ' + 'found.\n' % (user_team_association['userId'], + user_team_association['teamId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py new file mode 100755 index 00000000..a86ee932 --- /dev/null +++ b/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 updates user team associations. + +It updates a user team association by setting the overridden access type to read +only for all teams that the user belongs to. To determine which users exists, +run get_all_users.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' + + +def main(client, user_id): + # Initialize appropriate service. + user_team_association_service = client.GetService( + 'UserTeamAssociationService', version='v201905') + + # Create filter text to select user team associations by the user ID. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('userId = :userId') + .WithBindVariable('userId', long(user_id))) + + # Get user team associations by statement. + response = user_team_association_service.getUserTeamAssociationsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + updated_user_team_associations = [] + # Update each local user team association to read only access. + for user_team_association in response['results']: + user_team_association['overriddenTeamAccessType'] = 'READ_ONLY' + updated_user_team_associations.append(user_team_association) + + # Update user team associations on the server. + user_team_associations = ( + user_team_association_service.updateUserTeamAssociations( + updated_user_team_associations)) + + # Display results. + if user_team_associations: + for user_team_association in user_team_associations: + print ('User team association between user with ID "%s" and team with' + ' ID "%s" was updated.' % (user_team_association['userId'], + user_team_association['teamId'])) + else: + print 'No user team associations were updated.' + else: + print 'No user team associations found to update.' + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201905/workflow_request_service/__init__.py b/examples/ad_manager/v201905/workflow_request_service/__init__.py new file mode 100755 index 00000000..3746cd33 --- /dev/null +++ b/examples/ad_manager/v201905/workflow_request_service/__init__.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +# +# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py new file mode 100755 index 00000000..63e6cbe6 --- /dev/null +++ b/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 approves all workflow approval requests belonging to a proposal. + +To determine which workflow approval requests exist, run +get_all_workflow_approval_requests.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201905') + + # Create a filter statement. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) + workflow_approval_requests_approved = 0 + + # Get workflow approval requests by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + # Display results. + for workflow_approval_request in response['results']: + print ('Workflow approval request with id "%s" will be' + ' approved.' % workflow_approval_request['id']) + # Perform action. + result = workflow_request_service.performWorkflowRequestAction( + {'xsi_type': 'ApproveWorkflowApprovalRequests', + 'comment': 'This workflow has now been approved for submission.'}, + statement.ToStatement()) + if result and int(result['numChanges']) > 0: + workflow_approval_requests_approved += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if workflow_approval_requests_approved > 0: + print ('\nNumber of workflow approval requests approved: %s' % + workflow_approval_requests_approved) + else: + print '\nNo workflow approval requests were approved.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py new file mode 100755 index 00000000..c7e78791 --- /dev/null +++ b/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 workflow approval requests. + +Workflow approval requests must be approved or rejected for a workflow to +finish. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + workflow_request_service = client.GetService( + 'WorkflowRequestService', version='v201905') + # Create a statement to select workflow requests. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) + + # Retrieve a small amount of workflow requests at a time, paging + # through until all workflow requests have been retrieved. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for workflow_request in response['results']: + # Print out some information for each workflow request. + print('Workflow request with ID "%d", entity type "%s", and entity ID ' + '"%d" was found.\n' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py new file mode 100755 index 00000000..4c971d94 --- /dev/null +++ b/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 workflow external condition requests. + +Workflow external condition requests must be triggered or skipped for a +workflow to finish. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + workflow_request_service = client.GetService( + 'WorkflowRequestService', version='v201905') + # Create a statement to select workflow requests. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where('type = :type') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) + + # Retrieve a small amount of workflow requests at a time, paging + # through until all workflow requests have been retrieved. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for workflow_request in response['results']: + # Print out some information for each workflow request. + print('Workflow request with ID "%d", entity type "%s", and entity ID ' + '"%d" was found.\n' % (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + statement.offset += statement.limit + else: + break + + print '\nNumber of results found: %s' % response['totalResultSetSize'] + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py new file mode 100755 index 00000000..947fe23b --- /dev/null +++ b/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 triggers all workflow external condition requests for a proposal. + +Workflow external condition requests must be triggered or skipped for a workflow +to finish. To determine which proposals exist, run get_all_proposals.py. + +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' + + +def main(client, proposal_id): + # Initialize appropriate service. + workflow_request_service = client.GetService('WorkflowRequestService', + version='v201905') + + # Create a filter statement. + statement = (ad_manager.StatementBuilder(version='v201905') + .Where(('entityId = :entityId and entityType = :entityType ' + 'and type = :type')) + .WithBindVariable('entityId', proposal_id) + .WithBindVariable('entityType', 'PROPOSAL') + .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) + workflow_external_condition_requests_triggered = 0 + + # Get workflow external condition requests by statement. + while True: + response = workflow_request_service.getWorkflowRequestsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + # Display results. + for workflow_request in response['results']: + print ('Workflow external condition request with id "%s" for %s ' + 'with id "%s" will be triggered.' % + (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) + # Perform action. + result = workflow_request_service.performWorkflowRequestAction( + {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, + statement.ToStatement()) + if result and int(result['numChanges']) > 0: + workflow_external_condition_requests_triggered += int( + result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if workflow_external_condition_requests_triggered > 0: + print ('\nNumber of workflow external condition requests triggered: %s' % + workflow_external_condition_requests_triggered) + else: + print '\nNo workflow external condition requests were triggered.' + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, PROPOSAL_ID) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index d9d8d6ac..d1516b37 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,29 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201805': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CdnConfigurationService', 'CompanyService', 'ContactService', - 'ContentBundleService', 'ContentMetadataKeyHierarchyService', - 'ContentService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'ExchangeRateService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardService', - 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'UserService', - 'UserTeamAssociationService', 'WorkflowRequestService'), 'v201808': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', @@ -135,6 +112,29 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), + 'v201905': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'BaseRateService', 'CdnConfigurationService', 'CmsMetadataService', + 'CompanyService', 'ContactService', 'ContentBundleService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'ExchangeRateService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PackageService', 'PlacementService', + 'PremiumRateService', 'ProductService', 'ProductPackageService', + 'ProductPackageItemService', 'ProductTemplateService', + 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'RateCardService', + 'ReconciliationOrderReportService', 'ReconciliationReportRowService', + 'ReconciliationLineItemReportService', + 'ReconciliationReportService', 'ReportService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), } diff --git a/googleads/common.py b/googleads/common.py index 7ef683e9..e810eb07 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '18.1.0' +VERSION = '19.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' From 964298a95b354f0352f2cc1c2d229049f3642d0a Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 16 May 2019 21:36:22 +0300 Subject: [PATCH 139/180] Commiting latest changes. From c46b30d3c6cdb5eae499e35d89e33947e6ef7381 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Wed, 22 May 2019 10:56:06 -0400 Subject: [PATCH 140/180] Releasing v19.0.1 (removing v201808 samples) --- ChangeLog | 3 + .../activity_group_service/__init__.py | 15 -- .../create_activity_groups.py | 71 ----- .../get_active_activity_groups.py | 52 ---- .../get_all_activity_groups.py | 51 ---- .../update_activity_groups.py | 70 ----- .../v201808/activity_service/__init__.py | 15 -- .../activity_service/create_activities.py | 68 ----- .../activity_service/get_active_activities.py | 51 ---- .../activity_service/get_all_activities.py | 50 ---- .../activity_service/update_activities.py | 68 ----- .../audience_segment_service/__init__.py | 15 -- .../create_audience_segments.py | 96 ------- .../get_all_audience_segments.py | 52 ---- .../get_first_party_audience_segments.py | 53 ---- .../populate_first_party_audience_segments.py | 71 ----- .../update_audience_segments.py | 68 ----- .../v201808/base_rate_service/__init__.py | 15 -- .../create_product_base_rates.py | 65 ----- .../create_product_package_item_base_rates.py | 66 ----- .../create_product_template_base_rates.py | 65 ----- .../base_rate_service/get_all_base_rates.py | 52 ---- .../get_base_rates_for_rate_card.py | 55 ---- .../base_rate_service/update_base_rates.py | 77 ------ .../cdn_configuration_service/__init__.py | 15 -- .../create_cdn_configurations.py | 89 ------- .../get_all_cdn_configurations.py | 54 ---- .../v201808/company_service/__init__.py | 15 -- .../company_service/create_companies.py | 62 ----- .../company_service/get_advertisers.py | 50 ---- .../company_service/get_all_companies.py | 49 ---- .../company_service/update_companies.py | 70 ----- .../v201808/contact_service/__init__.py | 15 -- .../contact_service/create_contacts.py | 71 ----- .../contact_service/get_all_contacts.py | 49 ---- .../contact_service/get_uninvited_contacts.py | 50 ---- .../contact_service/update_contacts.py | 71 ----- .../__init__.py | 15 -- ...create_content_metadata_key_hierarchies.py | 79 ------ ...et_all_content_metadata_key_hierarchies.py | 55 ---- ...update_content_metadata_key_hierarchies.py | 94 ------- .../v201808/content_service/__init__.py | 15 -- .../content_service/get_all_content.py | 49 ---- .../v201808/creative_service/__init__.py | 15 -- .../creative_service/copy_image_creatives.py | 60 ----- .../create_creative_from_template.py | 111 -------- .../creative_service/create_creatives.py | 90 ------- .../create_custom_creative.py | 88 ------ .../create_native_creative.py | 132 --------- .../creative_service/get_all_creatives.py | 49 ---- .../creative_service/get_image_creatives.py | 50 ---- .../creative_service/update_creatives.py | 71 ----- .../v201808/creative_set_service/__init__.py | 15 -- .../associate_creative_set_to_line_item.py | 55 ---- .../create_creative_set.py | 61 ----- .../get_all_creative_sets.py | 51 ---- .../get_creative_sets_for_master_creative.py | 54 ---- .../update_creative_set.py | 73 ----- .../creative_template_service/__init__.py | 15 -- .../get_all_creative_templates.py | 51 ---- .../get_system_defined_creative_templates.py | 52 ---- .../create_creative_wrappers.py | 63 ----- .../deactivate_creative_wrapper.py | 78 ------ .../get_active_creative_wrappers.py | 52 ---- .../get_all_creative_wrappers.py | 51 ---- .../update_creative_wrappers.py | 73 ----- .../v201808/custom_field_service/__init__.py | 15 -- .../create_custom_field_options.py | 67 ----- .../create_custom_fields.py | 66 ----- .../deactivate_all_line_item_custom_fields.py | 73 ----- .../get_all_custom_fields.py | 51 ---- .../get_custom_fields_for_line_items.py | 52 ---- .../set_line_item_custom_field_value.py | 139 ---------- .../update_custom_fields.py | 70 ----- .../custom_targeting_service/__init__.py | 15 -- ...create_custom_targeting_keys_and_values.py | 132 --------- .../delete_custom_targeting_keys.py | 77 ------ .../delete_custom_targeting_values.py | 77 ------ ...et_all_custom_targeting_keys_and_values.py | 72 ----- ...efined_custom_targeting_keys_and_values.py | 74 ------ .../update_custom_targeting_keys.py | 67 ----- .../update_custom_targeting_values.py | 71 ----- .../v201808/exchange_rate_service/__init__.py | 15 -- .../create_exchange_rates.py | 58 ---- .../get_all_exchange_rates.py | 54 ---- .../get_exchange_rates_for_currency_code.py | 56 ---- .../update_exchange_rates.py | 71 ----- .../get_availability_forecast.py | 251 ------------------ ...get_availability_forecast_for_line_item.py | 66 ----- .../get_delivery_forecast_for_line_items.py | 52 ---- .../v201808/inventory_service/__init__.py | 15 -- .../inventory_service/archive_ad_units.py | 75 ------ .../inventory_service/create_ad_units.py | 70 ----- .../get_ad_unit_hierarchy.py | 115 -------- .../get_all_ad_unit_sizes.py | 46 ---- .../inventory_service/get_all_ad_units.py | 49 ---- .../get_top_level_ad_units.py | 58 ---- .../inventory_service/update_ad_units.py | 82 ------ .../v201808/label_service/__init__.py | 15 -- .../v201808/label_service/create_labels.py | 55 ---- .../label_service/deactivate_labels.py | 65 ----- .../label_service/get_active_labels.py | 50 ---- .../v201808/label_service/get_all_labels.py | 49 ---- .../v201808/label_service/update_labels.py | 63 ----- .../__init__.py | 15 -- .../create_licas.py | 57 ---- .../deactivate_licas.py | 73 ----- .../get_all_licas.py | 57 ---- .../get_licas_for_line_item.py | 60 ----- .../update_licas.py | 66 ----- .../v201808/line_item_service/__init__.py | 15 -- .../line_item_service/activate_line_items.py | 75 ------ .../line_item_service/create_line_items.py | 166 ------------ .../create_video_line_item.py | 135 ---------- .../line_item_service/get_all_line_items.py | 50 ---- .../get_line_items_that_need_creatives.py | 51 ---- .../get_recently_updated_line_items.py | 59 ---- .../line_item_service/pause_line_items.py | 74 ------ .../target_custom_criteria.py | 110 -------- .../line_item_service/update_line_items.py | 74 ------ .../activate_live_stream_events.py | 71 ----- .../create_live_stream_events.py | 68 ----- .../get_all_live_stream_events.py | 52 ---- .../register_sessions_for_monitoring.py | 45 ---- .../update_live_stream_events.py | 69 ----- .../v201808/native_style_service/__init__.py | 15 -- .../create_native_styles.py | 180 ------------- .../get_all_native_styles.py | 51 ---- .../v201808/network_service/__init__.py | 15 -- .../network_service/get_all_networks.py | 40 --- .../network_service/get_current_network.py | 37 --- .../network_service/make_test_network.py | 53 ---- .../v201808/order_service/__init__.py | 15 -- .../v201808/order_service/approve_orders.py | 67 ----- .../v201808/order_service/create_orders.py | 59 ---- .../v201808/order_service/get_all_orders.py | 49 ---- .../order_service/get_orders_starting_soon.py | 60 ----- .../v201808/order_service/update_orders.py | 71 ----- .../package_service/create_packages.py | 61 ----- ...reate_proposal_line_items_from_packages.py | 68 ----- .../package_service/get_all_packages.py | 50 ---- .../get_in_progress_packages.py | 51 ---- .../placement_service/create_placements.py | 108 -------- .../deactivate_placements.py | 62 ----- .../get_active_placements.py | 51 ---- .../placement_service/get_all_placements.py | 50 ---- .../placement_service/update_placements.py | 58 ---- .../v201808/premium_rate_service/__init__.py | 15 -- .../create_premium_rates.py | 84 ------ .../get_all_premium_rates.py | 54 ---- .../get_premium_rates_for_rate_card.py | 56 ---- .../update_premium_rates.py | 87 ------ .../create_product_package_item.py | 62 ----- .../get_all_product_package_items.py | 53 ---- ...oduct_package_items_for_product_package.py | 56 ---- .../create_product_packages.py | 51 ---- .../get_active_product_packages.py | 52 ---- .../get_all_product_packages.py | 51 ---- .../v201808/product_service/__init__.py | 15 -- .../product_service/get_all_products.py | 49 ---- .../get_products_for_product_template.py | 53 ---- .../product_service/update_products.py | 68 ----- .../product_template_service/__init__.py | 15 -- .../activate_product_templates.py | 74 ------ .../create_product_templates.py | 109 -------- .../create_programmatic_product_templates.py | 91 ------- .../get_all_product_templates.py | 51 ---- .../get_sponsorship_product_templates.py | 52 ---- .../update_product_templates.py | 94 ------- .../proposal_line_item_service/__init__.py | 15 -- .../archive_proposal_line_items.py | 76 ------ ...create_programmatic_proposal_line_items.py | 104 -------- ...sal_line_items_for_non_sales_management.py | 110 -------- .../create_proposal_line_items.py | 105 -------- .../get_all_proposal_line_items.py | 51 ---- .../get_proposal_line_items_for_proposal.py | 54 ---- .../update_proposal_line_items.py | 72 ----- .../v201808/proposal_service/__init__.py | 15 -- .../create_programmatic_proposals.py | 71 ----- ...atic_proposals_for_non_sales_management.py | 62 ----- .../proposal_service/create_proposals.py | 77 ------ .../proposal_service/get_all_proposals.py | 49 ---- .../get_marketplace_comments.py | 56 ---- .../get_proposals_pending_approval.py | 50 ---- .../request_buyers_acceptance.py | 67 ----- .../submit_proposals_for_approval.py | 67 ----- .../proposal_service/update_proposals.py | 68 ----- .../__init__.py | 15 -- .../fetch_match_tables.py | 55 ---- .../get_all_browsers.py | 55 ---- .../get_all_programmatic_buyers.py | 49 ---- .../get_geo_targets.py | 53 ---- .../get_line_items_named_like.py | 48 ---- .../get_recent_changes.py | 156 ----------- .../v201808/rate_card_service/__init__.py | 15 -- .../rate_card_service/create_rate_cards.py | 60 ----- .../rate_card_service/get_all_rate_cards.py | 51 ---- .../get_marketplace_rate_cards.py | 54 ---- ..._item_reports_for_reconciliation_report.py | 75 ------ ...update_reconciliation_line_item_reports.py | 67 ----- ...order_reports_for_reconciliation_report.py | 58 ---- .../submit_reconciliation_order_reports.py | 71 ----- ...n_report_rows_for_reconciliation_report.py | 64 ----- .../update_reconciliation_report_rows.py | 75 ------ .../get_all_reconciliation_reports.py | 56 ---- ...iliation_report_for_last_billing_period.py | 63 ----- .../v201808/report_service/__init__.py | 15 -- .../report_service/run_ad_exchange_report.py | 66 ----- .../report_service/run_delivery_report.py | 88 ------ .../report_service/run_inventory_report.py | 82 ------ .../report_service/run_reach_report.py | 64 ----- .../run_report_and_create_match_table.py | 88 ------ .../run_report_with_custom_fields.py | 97 ------- .../report_service/run_sales_report.py | 64 ----- .../v201808/report_service/run_saved_query.py | 80 ------ .../suggested_ad_unit_service/__init__.py | 15 -- .../approve_all_suggested_ad_units.py | 70 ----- .../get_all_suggested_ad_units.py | 52 ---- ...get_highly_requested_suggested_ad_units.py | 55 ---- .../v201808/team_service/__init__.py | 15 -- .../v201808/team_service/create_teams.py | 60 ----- .../v201808/team_service/get_all_teams.py | 49 ---- .../v201808/team_service/update_teams.py | 68 ----- .../v201808/user_service/__init__.py | 15 -- .../v201808/user_service/create_users.py | 57 ---- .../v201808/user_service/deactivate_users.py | 65 ----- .../v201808/user_service/get_all_roles.py | 40 --- .../v201808/user_service/get_all_users.py | 49 ---- .../v201808/user_service/get_current_user.py | 39 --- .../user_service/get_user_by_email_address.py | 52 ---- .../v201808/user_service/update_users.py | 58 ---- .../user_team_association_service/__init__.py | 15 -- .../create_user_team_associations.py | 67 ----- .../delete_user_team_associations.py | 77 ------ .../get_all_user_team_associations.py | 52 ---- .../get_user_team_associations_for_user.py | 55 ---- .../update_user_team_associations.py | 78 ------ .../workflow_request_service/__init__.py | 15 -- .../approve_workflow_approval_requests.py | 75 ------ .../get_workflow_approval_requests.py | 57 ---- ...et_workflow_external_condition_requests.py | 57 ---- ...er_workflow_external_condition_requests.py | 78 ------ googleads/common.py | 2 +- 243 files changed, 4 insertions(+), 14530 deletions(-) delete mode 100755 examples/ad_manager/v201808/activity_group_service/__init__.py delete mode 100755 examples/ad_manager/v201808/activity_group_service/create_activity_groups.py delete mode 100755 examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py delete mode 100755 examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py delete mode 100755 examples/ad_manager/v201808/activity_group_service/update_activity_groups.py delete mode 100755 examples/ad_manager/v201808/activity_service/__init__.py delete mode 100755 examples/ad_manager/v201808/activity_service/create_activities.py delete mode 100755 examples/ad_manager/v201808/activity_service/get_active_activities.py delete mode 100755 examples/ad_manager/v201808/activity_service/get_all_activities.py delete mode 100755 examples/ad_manager/v201808/activity_service/update_activities.py delete mode 100755 examples/ad_manager/v201808/audience_segment_service/__init__.py delete mode 100755 examples/ad_manager/v201808/audience_segment_service/create_audience_segments.py delete mode 100755 examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py delete mode 100755 examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py delete mode 100755 examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py delete mode 100755 examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py delete mode 100755 examples/ad_manager/v201808/base_rate_service/__init__.py delete mode 100755 examples/ad_manager/v201808/base_rate_service/create_product_base_rates.py delete mode 100755 examples/ad_manager/v201808/base_rate_service/create_product_package_item_base_rates.py delete mode 100755 examples/ad_manager/v201808/base_rate_service/create_product_template_base_rates.py delete mode 100755 examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py delete mode 100755 examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py delete mode 100755 examples/ad_manager/v201808/base_rate_service/update_base_rates.py delete mode 100755 examples/ad_manager/v201808/cdn_configuration_service/__init__.py delete mode 100755 examples/ad_manager/v201808/cdn_configuration_service/create_cdn_configurations.py delete mode 100755 examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py delete mode 100755 examples/ad_manager/v201808/company_service/__init__.py delete mode 100755 examples/ad_manager/v201808/company_service/create_companies.py delete mode 100755 examples/ad_manager/v201808/company_service/get_advertisers.py delete mode 100755 examples/ad_manager/v201808/company_service/get_all_companies.py delete mode 100755 examples/ad_manager/v201808/company_service/update_companies.py delete mode 100755 examples/ad_manager/v201808/contact_service/__init__.py delete mode 100755 examples/ad_manager/v201808/contact_service/create_contacts.py delete mode 100755 examples/ad_manager/v201808/contact_service/get_all_contacts.py delete mode 100755 examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py delete mode 100755 examples/ad_manager/v201808/contact_service/update_contacts.py delete mode 100755 examples/ad_manager/v201808/content_metadata_key_hierarchy_service/__init__.py delete mode 100755 examples/ad_manager/v201808/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201808/content_service/__init__.py delete mode 100755 examples/ad_manager/v201808/content_service/get_all_content.py delete mode 100755 examples/ad_manager/v201808/creative_service/__init__.py delete mode 100755 examples/ad_manager/v201808/creative_service/copy_image_creatives.py delete mode 100755 examples/ad_manager/v201808/creative_service/create_creative_from_template.py delete mode 100755 examples/ad_manager/v201808/creative_service/create_creatives.py delete mode 100755 examples/ad_manager/v201808/creative_service/create_custom_creative.py delete mode 100755 examples/ad_manager/v201808/creative_service/create_native_creative.py delete mode 100755 examples/ad_manager/v201808/creative_service/get_all_creatives.py delete mode 100755 examples/ad_manager/v201808/creative_service/get_image_creatives.py delete mode 100755 examples/ad_manager/v201808/creative_service/update_creatives.py delete mode 100755 examples/ad_manager/v201808/creative_set_service/__init__.py delete mode 100755 examples/ad_manager/v201808/creative_set_service/associate_creative_set_to_line_item.py delete mode 100755 examples/ad_manager/v201808/creative_set_service/create_creative_set.py delete mode 100755 examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py delete mode 100755 examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py delete mode 100755 examples/ad_manager/v201808/creative_set_service/update_creative_set.py delete mode 100755 examples/ad_manager/v201808/creative_template_service/__init__.py delete mode 100755 examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py delete mode 100755 examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py delete mode 100755 examples/ad_manager/v201808/creative_wrapper_service/create_creative_wrappers.py delete mode 100755 examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py delete mode 100755 examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py delete mode 100755 examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py delete mode 100755 examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py delete mode 100755 examples/ad_manager/v201808/custom_field_service/__init__.py delete mode 100755 examples/ad_manager/v201808/custom_field_service/create_custom_field_options.py delete mode 100755 examples/ad_manager/v201808/custom_field_service/create_custom_fields.py delete mode 100755 examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py delete mode 100755 examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py delete mode 100755 examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py delete mode 100755 examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py delete mode 100755 examples/ad_manager/v201808/custom_field_service/update_custom_fields.py delete mode 100755 examples/ad_manager/v201808/custom_targeting_service/__init__.py delete mode 100755 examples/ad_manager/v201808/custom_targeting_service/create_custom_targeting_keys_and_values.py delete mode 100755 examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py delete mode 100755 examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py delete mode 100755 examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py delete mode 100755 examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py delete mode 100755 examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py delete mode 100755 examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py delete mode 100755 examples/ad_manager/v201808/exchange_rate_service/__init__.py delete mode 100755 examples/ad_manager/v201808/exchange_rate_service/create_exchange_rates.py delete mode 100755 examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py delete mode 100755 examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py delete mode 100755 examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py delete mode 100755 examples/ad_manager/v201808/forecast_service/get_availability_forecast.py delete mode 100755 examples/ad_manager/v201808/forecast_service/get_availability_forecast_for_line_item.py delete mode 100755 examples/ad_manager/v201808/forecast_service/get_delivery_forecast_for_line_items.py delete mode 100755 examples/ad_manager/v201808/inventory_service/__init__.py delete mode 100755 examples/ad_manager/v201808/inventory_service/archive_ad_units.py delete mode 100755 examples/ad_manager/v201808/inventory_service/create_ad_units.py delete mode 100755 examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py delete mode 100755 examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py delete mode 100755 examples/ad_manager/v201808/inventory_service/get_all_ad_units.py delete mode 100755 examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py delete mode 100755 examples/ad_manager/v201808/inventory_service/update_ad_units.py delete mode 100755 examples/ad_manager/v201808/label_service/__init__.py delete mode 100755 examples/ad_manager/v201808/label_service/create_labels.py delete mode 100755 examples/ad_manager/v201808/label_service/deactivate_labels.py delete mode 100755 examples/ad_manager/v201808/label_service/get_active_labels.py delete mode 100755 examples/ad_manager/v201808/label_service/get_all_labels.py delete mode 100755 examples/ad_manager/v201808/label_service/update_labels.py delete mode 100755 examples/ad_manager/v201808/line_item_creative_association_service/__init__.py delete mode 100755 examples/ad_manager/v201808/line_item_creative_association_service/create_licas.py delete mode 100755 examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py delete mode 100755 examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py delete mode 100755 examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py delete mode 100755 examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py delete mode 100755 examples/ad_manager/v201808/line_item_service/__init__.py delete mode 100755 examples/ad_manager/v201808/line_item_service/activate_line_items.py delete mode 100755 examples/ad_manager/v201808/line_item_service/create_line_items.py delete mode 100755 examples/ad_manager/v201808/line_item_service/create_video_line_item.py delete mode 100755 examples/ad_manager/v201808/line_item_service/get_all_line_items.py delete mode 100755 examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py delete mode 100755 examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py delete mode 100755 examples/ad_manager/v201808/line_item_service/pause_line_items.py delete mode 100755 examples/ad_manager/v201808/line_item_service/target_custom_criteria.py delete mode 100755 examples/ad_manager/v201808/line_item_service/update_line_items.py delete mode 100755 examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py delete mode 100755 examples/ad_manager/v201808/live_stream_event_service/create_live_stream_events.py delete mode 100755 examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py delete mode 100755 examples/ad_manager/v201808/live_stream_event_service/register_sessions_for_monitoring.py delete mode 100755 examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py delete mode 100755 examples/ad_manager/v201808/native_style_service/__init__.py delete mode 100755 examples/ad_manager/v201808/native_style_service/create_native_styles.py delete mode 100755 examples/ad_manager/v201808/native_style_service/get_all_native_styles.py delete mode 100755 examples/ad_manager/v201808/network_service/__init__.py delete mode 100755 examples/ad_manager/v201808/network_service/get_all_networks.py delete mode 100755 examples/ad_manager/v201808/network_service/get_current_network.py delete mode 100755 examples/ad_manager/v201808/network_service/make_test_network.py delete mode 100755 examples/ad_manager/v201808/order_service/__init__.py delete mode 100755 examples/ad_manager/v201808/order_service/approve_orders.py delete mode 100755 examples/ad_manager/v201808/order_service/create_orders.py delete mode 100755 examples/ad_manager/v201808/order_service/get_all_orders.py delete mode 100755 examples/ad_manager/v201808/order_service/get_orders_starting_soon.py delete mode 100755 examples/ad_manager/v201808/order_service/update_orders.py delete mode 100755 examples/ad_manager/v201808/package_service/create_packages.py delete mode 100755 examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py delete mode 100755 examples/ad_manager/v201808/package_service/get_all_packages.py delete mode 100755 examples/ad_manager/v201808/package_service/get_in_progress_packages.py delete mode 100755 examples/ad_manager/v201808/placement_service/create_placements.py delete mode 100755 examples/ad_manager/v201808/placement_service/deactivate_placements.py delete mode 100755 examples/ad_manager/v201808/placement_service/get_active_placements.py delete mode 100755 examples/ad_manager/v201808/placement_service/get_all_placements.py delete mode 100755 examples/ad_manager/v201808/placement_service/update_placements.py delete mode 100755 examples/ad_manager/v201808/premium_rate_service/__init__.py delete mode 100755 examples/ad_manager/v201808/premium_rate_service/create_premium_rates.py delete mode 100755 examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py delete mode 100755 examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py delete mode 100755 examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py delete mode 100755 examples/ad_manager/v201808/product_package_item_service/create_product_package_item.py delete mode 100755 examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py delete mode 100755 examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py delete mode 100755 examples/ad_manager/v201808/product_package_service/create_product_packages.py delete mode 100755 examples/ad_manager/v201808/product_package_service/get_active_product_packages.py delete mode 100755 examples/ad_manager/v201808/product_package_service/get_all_product_packages.py delete mode 100755 examples/ad_manager/v201808/product_service/__init__.py delete mode 100755 examples/ad_manager/v201808/product_service/get_all_products.py delete mode 100755 examples/ad_manager/v201808/product_service/get_products_for_product_template.py delete mode 100755 examples/ad_manager/v201808/product_service/update_products.py delete mode 100755 examples/ad_manager/v201808/product_template_service/__init__.py delete mode 100755 examples/ad_manager/v201808/product_template_service/activate_product_templates.py delete mode 100755 examples/ad_manager/v201808/product_template_service/create_product_templates.py delete mode 100755 examples/ad_manager/v201808/product_template_service/create_programmatic_product_templates.py delete mode 100755 examples/ad_manager/v201808/product_template_service/get_all_product_templates.py delete mode 100755 examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py delete mode 100755 examples/ad_manager/v201808/product_template_service/update_product_templates.py delete mode 100755 examples/ad_manager/v201808/proposal_line_item_service/__init__.py delete mode 100755 examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py delete mode 100755 examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items.py delete mode 100755 examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py delete mode 100755 examples/ad_manager/v201808/proposal_line_item_service/create_proposal_line_items.py delete mode 100755 examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py delete mode 100755 examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py delete mode 100755 examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py delete mode 100755 examples/ad_manager/v201808/proposal_service/__init__.py delete mode 100755 examples/ad_manager/v201808/proposal_service/create_programmatic_proposals.py delete mode 100755 examples/ad_manager/v201808/proposal_service/create_programmatic_proposals_for_non_sales_management.py delete mode 100755 examples/ad_manager/v201808/proposal_service/create_proposals.py delete mode 100755 examples/ad_manager/v201808/proposal_service/get_all_proposals.py delete mode 100755 examples/ad_manager/v201808/proposal_service/get_marketplace_comments.py delete mode 100755 examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py delete mode 100755 examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py delete mode 100755 examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py delete mode 100755 examples/ad_manager/v201808/proposal_service/update_proposals.py delete mode 100755 examples/ad_manager/v201808/publisher_query_language_service/__init__.py delete mode 100755 examples/ad_manager/v201808/publisher_query_language_service/fetch_match_tables.py delete mode 100755 examples/ad_manager/v201808/publisher_query_language_service/get_all_browsers.py delete mode 100755 examples/ad_manager/v201808/publisher_query_language_service/get_all_programmatic_buyers.py delete mode 100755 examples/ad_manager/v201808/publisher_query_language_service/get_geo_targets.py delete mode 100755 examples/ad_manager/v201808/publisher_query_language_service/get_line_items_named_like.py delete mode 100755 examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py delete mode 100755 examples/ad_manager/v201808/rate_card_service/__init__.py delete mode 100755 examples/ad_manager/v201808/rate_card_service/create_rate_cards.py delete mode 100755 examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py delete mode 100755 examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py delete mode 100755 examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py delete mode 100755 examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py delete mode 100755 examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py delete mode 100755 examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py delete mode 100755 examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py delete mode 100755 examples/ad_manager/v201808/report_service/__init__.py delete mode 100755 examples/ad_manager/v201808/report_service/run_ad_exchange_report.py delete mode 100755 examples/ad_manager/v201808/report_service/run_delivery_report.py delete mode 100755 examples/ad_manager/v201808/report_service/run_inventory_report.py delete mode 100755 examples/ad_manager/v201808/report_service/run_reach_report.py delete mode 100755 examples/ad_manager/v201808/report_service/run_report_and_create_match_table.py delete mode 100755 examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py delete mode 100755 examples/ad_manager/v201808/report_service/run_sales_report.py delete mode 100755 examples/ad_manager/v201808/report_service/run_saved_query.py delete mode 100755 examples/ad_manager/v201808/suggested_ad_unit_service/__init__.py delete mode 100755 examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py delete mode 100755 examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py delete mode 100755 examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py delete mode 100755 examples/ad_manager/v201808/team_service/__init__.py delete mode 100755 examples/ad_manager/v201808/team_service/create_teams.py delete mode 100755 examples/ad_manager/v201808/team_service/get_all_teams.py delete mode 100755 examples/ad_manager/v201808/team_service/update_teams.py delete mode 100755 examples/ad_manager/v201808/user_service/__init__.py delete mode 100755 examples/ad_manager/v201808/user_service/create_users.py delete mode 100755 examples/ad_manager/v201808/user_service/deactivate_users.py delete mode 100755 examples/ad_manager/v201808/user_service/get_all_roles.py delete mode 100755 examples/ad_manager/v201808/user_service/get_all_users.py delete mode 100755 examples/ad_manager/v201808/user_service/get_current_user.py delete mode 100755 examples/ad_manager/v201808/user_service/get_user_by_email_address.py delete mode 100755 examples/ad_manager/v201808/user_service/update_users.py delete mode 100755 examples/ad_manager/v201808/user_team_association_service/__init__.py delete mode 100755 examples/ad_manager/v201808/user_team_association_service/create_user_team_associations.py delete mode 100755 examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py delete mode 100755 examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py delete mode 100755 examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py delete mode 100755 examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py delete mode 100755 examples/ad_manager/v201808/workflow_request_service/__init__.py delete mode 100755 examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py delete mode 100755 examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py delete mode 100755 examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py delete mode 100755 examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py diff --git a/ChangeLog b/ChangeLog index 68f4088b..ab841fd4 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +19.0.1 -- 05/22/2019 +* Really removed examples for Ad Manager v201808 + 19.0.0 -- 05/09/2019 * Added support for Ad Manager v201905 * Removed support for Ad Manager v201805 diff --git a/examples/ad_manager/v201808/activity_group_service/__init__.py b/examples/ad_manager/v201808/activity_group_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/activity_group_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/create_activity_groups.py deleted file mode 100755 index 195585f0..00000000 --- a/examples/ad_manager/v201808/activity_group_service/create_activity_groups.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new activity groups. - -To determine which activity groups exist, run get_all_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the advertiser company this activity group is associated with. -ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, advertiser_company_id): - # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201808') - - # Create a short-term activity group. - short_term_activity_group = { - 'name': 'Short-term activity group #%s' % uuid.uuid4(), - 'companyIds': [advertiser_company_id], - 'clicksLookback': '1', - 'impressionsLookback': '1' - } - - # Create a long-term activity group. - long_term_activity_group = { - 'name': 'Long-term activity group #%s' % uuid.uuid4(), - 'companyIds': [advertiser_company_id], - 'clicksLookback': '30', - 'impressionsLookback': '30' - } - - # Create the activity groups on the server. - activity_groups = activity_group_service.createActivityGroups([ - short_term_activity_group, long_term_activity_group]) - - # Display results. - for activity_group in activity_groups: - print ('Activity group with ID "%s" and name "%s" was created.' - % (activity_group['id'], activity_group['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_COMPANY_ID) diff --git a/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py deleted file mode 100755 index 43e5e90d..00000000 --- a/examples/ad_manager/v201808/activity_group_service/get_active_activity_groups.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active activity groups. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - activity_group_service = client.GetService( - 'ActivityGroupService', version='v201808') - # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status') - .WithBindVariable('status', 'ACTIVE')) - - # Retrieve a small amount of activity groups at a time, paging - # through until all activity groups have been retrieved. - while True: - response = activity_group_service.getActivityGroupsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for activity_group in response['results']: - # Print out some information for each activity group. - print('Activity group with ID "%d" and name "%s" was found.\n' % - (activity_group['id'], activity_group['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py deleted file mode 100755 index 598284a2..00000000 --- a/examples/ad_manager/v201808/activity_group_service/get_all_activity_groups.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 activity groups. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - activity_group_service = client.GetService( - 'ActivityGroupService', version='v201808') - - # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of activity groups at a time, paging - # through until all activity groups have been retrieved. - while True: - response = activity_group_service.getActivityGroupsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for activity_group in response['results']: - # Print out some information for each activity group. - print('Activity group with ID "%d" and name "%s" was found.\n' % - (activity_group['id'], activity_group['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py deleted file mode 100755 index df0b7da9..00000000 --- a/examples/ad_manager/v201808/activity_group_service/update_activity_groups.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates activity groups. - -To determine which activity groups exist, run get_all_activity_groups.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the activity group and the company to update it with. -ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' -ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, activity_group_id, advertiser_company_id): - # Initialize appropriate service. - activity_group_service = client.GetService('ActivityGroupService', - version='v201808') - - # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :activityGroupId') - .WithBindVariable('activityGroupId', long(activity_group_id)) - .Limit(1)) - - # Get activity groups by statement. - response = activity_group_service.getActivityGroupsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - updated_activity_groups = [] - for activity_group in response['results']: - activity_group['companyIds'].append(advertiser_company_id) - updated_activity_groups.append(activity_group) - # Update the activity groups on the server. - activity_groups = activity_group_service.updateActivityGroups( - updated_activity_groups) - - for activity_group in activity_groups: - print (('Activity group with ID "%s" and name "%s" was updated.') - % (activity_group['id'], activity_group['name'])) - else: - print 'No activity groups found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ACTIVITY_GROUP_ID, ADVERTISER_COMPANY_ID) diff --git a/examples/ad_manager/v201808/activity_service/__init__.py b/examples/ad_manager/v201808/activity_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/activity_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/activity_service/create_activities.py b/examples/ad_manager/v201808/activity_service/create_activities.py deleted file mode 100755 index ac07336c..00000000 --- a/examples/ad_manager/v201808/activity_service/create_activities.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new activities. - -To determine which activities groups exist, run get_all_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the activity group this activity is associated with. -ACTIVITY_GROUP_ID = 'INSERT_ACTIVITY_GROUP_ID_HERE' - - -def main(client, activity_group_id): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201808') - - # Create a daily visits activity. - daily_visits_activity = { - 'name': 'Activity #%s' % uuid.uuid4(), - 'activityGroupId': activity_group_id, - 'type': 'DAILY_VISITS' - } - - # Create a custom activity. - custom_activity = { - 'name': 'Activity #%s' % uuid.uuid4(), - 'activityGroupId': activity_group_id, - 'type': 'CUSTOM' - } - - # Create the activities on the server. - activities = activity_service.createActivities([ - daily_visits_activity, custom_activity]) - - # Display results. - for activity in activities: - print ('An activity with ID "%s", name "%s", and type "%s" was ' - 'created.' % (activity['id'], activity['name'], activity['type'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ACTIVITY_GROUP_ID) diff --git a/examples/ad_manager/v201808/activity_service/get_active_activities.py b/examples/ad_manager/v201808/activity_service/get_active_activities.py deleted file mode 100755 index 04453053..00000000 --- a/examples/ad_manager/v201808/activity_service/get_active_activities.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active activities. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201808') - # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status') - .WithBindVariable('status', 'ACTIVE')) - - # Retrieve a small amount of activities at a time, paging - # through until all activities have been retrieved. - while True: - response = activity_service.getActivitiesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for activity in response['results']: - # Print out some information for each activity. - print('Activity with ID "%d", name "%s", and type "%s" was found.\n' % - (activity['id'], activity['name'], activity['type'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/activity_service/get_all_activities.py b/examples/ad_manager/v201808/activity_service/get_all_activities.py deleted file mode 100755 index 28501e28..00000000 --- a/examples/ad_manager/v201808/activity_service/get_all_activities.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 activities. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201808') - - # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of activities at a time, paging - # through until all activities have been retrieved. - while True: - response = activity_service.getActivitiesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for activity in response['results']: - # Print out some information for each activity. - print('Activity with ID "%d" and name "%s" was found.\n' % - (activity['id'], activity['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/activity_service/update_activities.py b/examples/ad_manager/v201808/activity_service/update_activities.py deleted file mode 100755 index 66b3b8ce..00000000 --- a/examples/ad_manager/v201808/activity_service/update_activities.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates activities. - -To determine which activities exist, run get_all_activities.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the activity to update. -ACTIVITY_ID = 'INSERT_ACTIVITY_ID_HERE' - - -def main(client, activity_id): - # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201808') - - # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :activityId') - .WithBindVariable('activityId', long(activity_id)) - .Limit(1)) - - # Get activities by statement. - response = activity_service.getActivitiesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - updated_activities = [] - for activity in response['results']: - # Update the expected URL. - activity['expectedURL'] = 'https://google.com' - updated_activities.append(activity) - # Update the activity on the server. - activities = activity_service.updateActivities(updated_activities) - - for updated_activity in activities: - print (('Activity with ID "%s" and name "%s" was updated.') - % (updated_activity['id'], updated_activity['name'])) - else: - print 'No activities found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ACTIVITY_ID) diff --git a/examples/ad_manager/v201808/audience_segment_service/__init__.py b/examples/ad_manager/v201808/audience_segment_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/audience_segment_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/create_audience_segments.py deleted file mode 100755 index 5d31387b..00000000 --- a/examples/ad_manager/v201808/audience_segment_service/create_audience_segments.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a new rule based first party audience segment.""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the IDs of the custom criteria to be used in the segment rule. -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' -CUSTOM_TARGETING_VALUE_ID = 'INSERT_CUSTOM_TARGETING_VALUE_ID_HERE' - - -def main(client, custom_targeting_key_id, custom_targeting_value_id): - # Initialize appropriate services. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201808') - network_service = client.GetService('NetworkService', version='v201808') - - # Get the root ad unit ID used to target the entire network. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Create inventory targeting (pointed at root ad unit i.e. the whole network) - inventory_targeting = { - 'targetedAdUnits': [ - {'adUnitId': root_ad_unit_id} - ] - } - - # Create custom criteria. - custom_criteria = [ - { - 'xsi_type': 'CustomCriteria', - 'keyId': custom_targeting_key_id, - 'valueIds': [custom_targeting_value_id], - 'operator': 'IS' - } - ] - - # Create the custom criteria set. - top_custom_criteria_set = { - 'logicalOperator': 'AND', - 'children': custom_criteria - } - - # Create the audience segment rule. - rule = { - 'inventoryRule': inventory_targeting, - 'customCriteriaRule': top_custom_criteria_set - } - - # Create an audience segment. - audience_segment = [ - { - 'xsi_type': 'RuleBasedFirstPartyAudienceSegment', - 'name': ('Sports enthusiasts audience segment %s' % - uuid.uuid4()), - 'description': 'Sports enthusiasts between the ages of 20 and 30', - 'pageViews': '6', - 'recencyDays': '6', - 'membershipExpirationDays': '88', - 'rule': rule - } - ] - - audience_segments = ( - audience_segment_service.createAudienceSegments(audience_segment)) - - for created_audience_segment in audience_segments: - print ('An audience segment with ID "%s", name "%s", and type "%s" ' - 'was created.' % (created_audience_segment['id'], - created_audience_segment['name'], - created_audience_segment['type'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CUSTOM_TARGETING_KEY_ID, CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py deleted file mode 100755 index 3fb0fbcf..00000000 --- a/examples/ad_manager/v201808/audience_segment_service/get_all_audience_segments.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 audience segments. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201808') - - # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of audience segments at a time, paging - # through until all audience segments have been retrieved. - while True: - response = audience_segment_service.getAudienceSegmentsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for audience_segment in response['results']: - # Print out some information for each audience segment. - print('Audience segment with ID "%d", name "%s", and size "%d" was ' - 'found.\n' % (audience_segment['id'], audience_segment['name'], - audience_segment['size'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py deleted file mode 100755 index 8a7855cc..00000000 --- a/examples/ad_manager/v201808/audience_segment_service/get_first_party_audience_segments.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 first party audience segments. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201808') - # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('type = :type') - .WithBindVariable('type', 'FIRST_PARTY')) - - # Retrieve a small amount of audience segments at a time, paging - # through until all audience segments have been retrieved. - while True: - response = audience_segment_service.getAudienceSegmentsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for audience_segment in response['results']: - # Print out some information for each audience segment. - print('Audience segment with ID "%d", name "%s", and size "%d" was ' - 'found.\n' % (audience_segment['id'], audience_segment['name'], - audience_segment['size'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py deleted file mode 100755 index dd971e3e..00000000 --- a/examples/ad_manager/v201808/audience_segment_service/populate_first_party_audience_segments.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 populates a specific first party audience segment. - -To determine which first party audience segments exist, run -get_first_party_audience_segments.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' - - -def main(client, audience_segment_id): - # Initialize appropriate service. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201808') - - # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('Type = :type AND Id = :audience_segment_id') - .WithBindVariable('audience_segment_id', - long(audience_segment_id)) - .WithBindVariable('type', 'FIRST_PARTY') - .Limit(1)) - - response = audience_segment_service.getAudienceSegmentsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - segments = response['results'] - - for segment in segments: - print ( - 'Audience segment with id "%s" and name "%s" will be populated.' - % (segment['id'], segment['name'])) - - action = { - 'xsi_type': 'PopulateAudienceSegments' - } - - populated_audience_segments = ( - audience_segment_service.performAudienceSegmentAction( - action, statement.ToStatement())) - - print ('%s audience segment populated' % - populated_audience_segments['numChanges']) - else: - print 'No Results Found' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py deleted file mode 100755 index 4c51e00d..00000000 --- a/examples/ad_manager/v201808/audience_segment_service/update_audience_segments.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates rule based first party audience segments. - -To determine which audience segments exist, run get_all_audience_segments.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE' - - -def main(client, audience_segment_id): - # Initialize appropriate service. - audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201808') - - # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('Type = :type AND Id = :audience_segment_id') - .WithBindVariable('audience_segment_id', - long(audience_segment_id)) - .WithBindVariable('type', 'FIRST_PARTY') - .Limit(1)) - - # Get audience segments by statement. - response = audience_segment_service.getAudienceSegmentsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_audience_segments = [] - for audience_segment in response['results']: - print ('Audience segment with id "%s" and name "%s" will be updated.' - % (audience_segment['id'], audience_segment['name'])) - - audience_segment['membershipExpirationDays'] = '180' - updated_audience_segments.append(audience_segment) - - audience_segments = audience_segment_service.updateAudienceSegments( - updated_audience_segments) - - for audience_segment in audience_segments: - print ('Audience segment with id "%s" and name "%s" was updated' % - (audience_segment['id'], audience_segment['name'])) - else: - print 'No audience segment found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, AUDIENCE_SEGMENT_ID) diff --git a/examples/ad_manager/v201808/base_rate_service/__init__.py b/examples/ad_manager/v201808/base_rate_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/base_rate_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201808/base_rate_service/create_product_base_rates.py deleted file mode 100755 index 1e7a4da9..00000000 --- a/examples/ad_manager/v201808/base_rate_service/create_product_base_rates.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201808') - - # Create a product base rate. - product_base_rate = { - 'xsi_type': 'ProductBaseRate', - # Set the rate card ID that the product base rate belongs to. - 'rateCardId': rate_card_id, - # Set the product id the base rate will be applied to. - 'productId': product_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create the product base rate on the server. - base_rates = base_rate_service.createBaseRates( - [product_base_rate]) - - if base_rates: - for base_rate in base_rates: - print ('A product base rate with ID "%s" and rate \'%.2f\' %s was ' - 'created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201808/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201808/base_rate_service/create_product_package_item_base_rates.py deleted file mode 100755 index 72d074af..00000000 --- a/examples/ad_manager/v201808/base_rate_service/create_product_package_item_base_rates.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package item base rate. - -To determine which base rates exist, run get_all_base_rates.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the rate card ID to add the base rate to. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - -# Set the product package item to apply this base rate to. -PRODUCT_PACKAGE_ITEM_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201808') - - # Create a base rate for a product package item. - product_package_item_base_rate = { - 'xsi_type': 'ProductPackageItemBaseRate', - # Set the rate card ID that the product package item base rate - # belongs to. - 'rateCardId': RATE_CARD_ID, - # Set the product package item the base rate will be applied to. - 'productPackageItemId': PRODUCT_PACKAGE_ITEM_ID, - # Create a rate worth $2 USD and set that on the product package item - # base rate. - 'rate': { - 'xsi_type': 'Money', - 'currencyCode': 'USD', - 'microAmount': 2000000, - } - } - - # Create the product package item base rate on the server. - result = base_rate_service.createBaseRates([product_package_item_base_rate]) - - for new_base_rate in result: - print ('A product package item base rate with ID %d and rate %f %s ' - 'was created.' % (new_base_rate['id'], - new_base_rate['microAmount'], - new_base_rate['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201808/base_rate_service/create_product_template_base_rates.py deleted file mode 100755 index 5d96a2b6..00000000 --- a/examples/ad_manager/v201808/base_rate_service/create_product_template_base_rates.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product template base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_template_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201808') - - # Create a product template base rate. - product_template_base_rate = { - 'xsi_type': 'ProductTemplateBaseRate', - # Set the rate card ID that the product template base rate belongs to. - 'rateCardId': rate_card_id, - # Set the product template the base rate will be applied to. - 'productTemplateId': product_template_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create the product template item base rate on the server. - base_rates = base_rate_service.createBaseRates( - [product_template_base_rate]) - - if base_rates: - for base_rate in base_rates: - print ('A product template base rate with ID "%s" and rate \'%.2f\' %s' - ' was created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py deleted file mode 100755 index ceba2083..00000000 --- a/examples/ad_manager/v201808/base_rate_service/get_all_base_rates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 base rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201808') - - # Create a statement to select base rates. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of base rates at a time, paging - # through until all base rates have been retrieved. - while True: - response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for base_rate in response['results']: - # Print out some information for each base rate. - print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % (base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py deleted file mode 100755 index 6e7148b6..00000000 --- a/examples/ad_manager/v201808/base_rate_service/get_base_rates_for_rate_card.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 base rates belonging to a rate card. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201808') - # Create a statement to select base rates. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('rateCardId = :rateCardId') - .WithBindVariable('rateCardId', rate_card_id)) - - # Retrieve a small amount of base rates at a time, paging - # through until all base rates have been retrieved. - while True: - response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for base_rate in response['results']: - # Print out some information for each base rate. - print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % - (base_rate['id'], ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201808/base_rate_service/update_base_rates.py b/examples/ad_manager/v201808/base_rate_service/update_base_rates.py deleted file mode 100755 index 022da6ca..00000000 --- a/examples/ad_manager/v201808/base_rate_service/update_base_rates.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a base rate's value. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' - - -def main(client, base_rate_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201808') - - # Create a filter statement for base rates for a single rate card. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', long(base_rate_id))) - - # Get single base rate by statement. - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local base rate object by changing its value to $3 USD. - new_rate = { - 'currencyCode': 'USD', - 'microAmount': 3000000 - } - - updated_base_rates = [] - for base_rate in response['results']: - base_rate['rate'] = new_rate - updated_base_rates.append(base_rate) - - # Update base rates remotely. - base_rates = base_rate_service.updateBaseRates(updated_base_rates) - - # Display results. - if base_rates: - for base_rate in base_rates: - print ('Base rate with ID "%s" and type "%s" belonging to ' - 'rate card ID "%s" was updated.' % ( - base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - else: - print 'No base rates were updated.' - else: - print 'No base rates found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, BASE_RATE_ID) diff --git a/examples/ad_manager/v201808/cdn_configuration_service/__init__.py b/examples/ad_manager/v201808/cdn_configuration_service/__init__.py deleted file mode 100755 index 473ddba1..00000000 --- a/examples/ad_manager/v201808/cdn_configuration_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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. diff --git a/examples/ad_manager/v201808/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201808/cdn_configuration_service/create_cdn_configurations.py deleted file mode 100755 index 7fcaef21..00000000 --- a/examples/ad_manager/v201808/cdn_configuration_service/create_cdn_configurations.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 code example creates new cdn configurations. - -To determine which configurations exist, run get_all_cdn_configurations.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - cdn_config_service = client.GetService('CdnConfigurationService', - version='v201808') - - # Create cdn config objects. - # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. - configs = [{ - # Basic example with no security policies. - 'name': 'ApiConfig1', - 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', - 'sourceContentConfiguration': { - 'ingestSettings': { - 'urlPrefix': 'ingest1.com', - 'securityPolicy': { - 'securityPolicyType': 'NONE' - } - }, - 'defaultDeliverySettings': { - 'urlPrefix': 'delivery1.com', - 'securityPolicy': { - 'securityPolicyType': 'NONE' - } - } - } - }, { - # Complex example with security policies. - 'name': 'ApiConfig2', - 'cdnConfigurationType': 'LIVE_STREAM_SOURCE_CONTENT', - 'sourceContentConfiguration': { - 'ingestSettings': { - 'urlPrefix': 'ingest1.com', - 'securityPolicy': { - 'securityPolicyType': 'AKAMAI', - 'disableServerSideUrlSigning': False, - 'tokenAuthenticationKey': 'abc123', - } - }, - 'defaultDeliverySettings': { - 'urlPrefix': 'delivery1.com', - 'securityPolicy': { - 'securityPolicyType': 'AKAMAI', - 'disableServerSideUrlSigning': True, - 'originForwardingType': 'CONVENTIONAL', - 'originPathPrefix': '/path/to/my/origin' - } - } - } - }] - - # Add configs. - configs = cdn_config_service.createCdnConfigurations(configs) - - # Display results. - for config in configs: - print('Created CDN configuration with type "%s" and name "%s".' - % (config['cdnConfigurationType'], config['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py deleted file mode 100755 index b2c0c821..00000000 --- a/examples/ad_manager/v201808/cdn_configuration_service/get_all_cdn_configurations.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 CDN configuration objects. - -Currently only configurations of type LIVE_STREAM_SOURCE_CONTENT will be -returned. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - cdn_config_service = client.GetService('CdnConfigurationService', - version='v201808') - - # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small number of configs at a time, paging - # through until all have been retrieved. - while True: - response = (cdn_config_service - .getCdnConfigurationsByStatement(statement.ToStatement())) - if 'results' in response and len(response['results']): - for cdn in response['results']: - # Print out some information for each company. - print('Found CDN configuration with type "%s" and name "%s".' - % (cdn['cdnConfigurationType'], cdn['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/company_service/__init__.py b/examples/ad_manager/v201808/company_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/company_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/company_service/create_companies.py b/examples/ad_manager/v201808/company_service/create_companies.py deleted file mode 100755 index 59acf80f..00000000 --- a/examples/ad_manager/v201808/company_service/create_companies.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new companies. - -To determine which companies exist, run get_all_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201808') - - # Create company objects. - companies = [ - { - 'name': 'Advertiser #%s' % uuid.uuid4(), - 'type': 'ADVERTISER' - }, - { - 'name': 'Agency #%s' % uuid.uuid4(), - 'type': 'AGENCY' - } - ] - - # Add companies. - companies = company_service.createCompanies(companies) - - # Display results. - for company in companies: - print ('Company with ID "%s", name "%s", and type "%s" was created.' - % (company['id'], company['name'], company['type'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/company_service/get_advertisers.py b/examples/ad_manager/v201808/company_service/get_advertisers.py deleted file mode 100755 index 778a6c7e..00000000 --- a/examples/ad_manager/v201808/company_service/get_advertisers.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 companies that are advertisers. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201808') - # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('type = :type') - .WithBindVariable('type', 'ADVERTISER')) - - # Retrieve a small amount of companies at a time, paging - # through until all companies have been retrieved. - while True: - response = company_service.getCompaniesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for company in response['results']: - # Print out some information for each company. - print('Company with ID "%d", name "%s", and type "%s" was found.\n' % - (company['id'], company['name'], company['type'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/company_service/get_all_companies.py b/examples/ad_manager/v201808/company_service/get_all_companies.py deleted file mode 100755 index 82e793c8..00000000 --- a/examples/ad_manager/v201808/company_service/get_all_companies.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 companies. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201808') - - # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of companies at a time, paging - # through until all companies have been retrieved. - while True: - response = company_service.getCompaniesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for company in response['results']: - # Print out some information for each company. - print('Company with ID "%d", name "%s", and type "%s" was found.\n' % - (company['id'], company['name'], company['type'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/company_service/update_companies.py b/examples/ad_manager/v201808/company_service/update_companies.py deleted file mode 100755 index e447415f..00000000 --- a/examples/ad_manager/v201808/company_service/update_companies.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates company comments. - -To determine which companies exist, run get_all_companies.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the company to update. -COMPANY_ID = 'INSERT_COMPANY_ID_HERE' - - -def main(client, company_id): - # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201808') - - # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', long(company_id)) - .Limit(1)) - - # Get companies by statement. - response = company_service.getCompaniesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - updated_companies = [] - for company in response['results']: - company['comment'] += ' Updated.' - updated_companies.append(company) - - # Update the companies on the server. - companies = company_service.updateCompanies(updated_companies) - - # Display results. - for company in companies: - print (('Company with ID "%s", name "%s", and comment "%s"' - ' was updated.') - % (company['id'], company['name'], company['comment'])) - else: - print 'No companies found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, COMPANY_ID) diff --git a/examples/ad_manager/v201808/contact_service/__init__.py b/examples/ad_manager/v201808/contact_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/contact_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/contact_service/create_contacts.py b/examples/ad_manager/v201808/contact_service/create_contacts.py deleted file mode 100755 index bb785104..00000000 --- a/examples/ad_manager/v201808/contact_service/create_contacts.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new contacts. - -To determine which contacts exist, run get_all_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the advertiser company this contact is associated with. -ADVERTISER_COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - -# Set the ID of the agency company this contact is associated with. -AGENCY_COMPANY_ID = 'INSERT_AGENCY_COMPANY_ID_HERE' - - -def main(client, advertiser_company_id, agency_company_id): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201808') - - # Create an advertiser contact. - advertiser_contact = { - 'name': 'Mr. Advertiser #%s' % uuid.uuid4(), - 'email': 'advertiser@advertising.com', - 'companyId': advertiser_company_id - } - - # Create an agency contact. - agency_contact = { - 'name': 'Ms. Agency #%s' % uuid.uuid4(), - 'email': 'agency@agencies.com', - 'companyId': agency_company_id - } - - # Create the contacts on the server. - contacts = contact_service.createContacts([advertiser_contact, - agency_contact]) - - # Display results. - for contact in contacts: - print ('Contact with ID "%s" name "%s" was created.' - % (contact['id'], contact['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_COMPANY_ID, AGENCY_COMPANY_ID) diff --git a/examples/ad_manager/v201808/contact_service/get_all_contacts.py b/examples/ad_manager/v201808/contact_service/get_all_contacts.py deleted file mode 100755 index 52b87af0..00000000 --- a/examples/ad_manager/v201808/contact_service/get_all_contacts.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 contacts. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201808') - - # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of contacts at a time, paging - # through until all contacts have been retrieved. - while True: - response = contact_service.getContactsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for contact in response['results']: - # Print out some information for each contact. - print('Contact with ID "%d" and name "%s" was found.\n' % - (contact['id'], contact['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py deleted file mode 100755 index ee05f1e9..00000000 --- a/examples/ad_manager/v201808/contact_service/get_uninvited_contacts.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 contacts that aren't invited yet. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201808') - # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status') - .WithBindVariable('status', 'UNINVITED')) - - # Retrieve a small amount of contacts at a time, paging - # through until all contacts have been retrieved. - while True: - response = contact_service.getContactsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for contact in response['results']: - # Print out some information for each contact. - print('Contact with ID "%d" and name "%s" was found.\n' % - (contact['id'], contact['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/contact_service/update_contacts.py b/examples/ad_manager/v201808/contact_service/update_contacts.py deleted file mode 100755 index 01032620..00000000 --- a/examples/ad_manager/v201808/contact_service/update_contacts.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates contact addresses. - -To determine which contacts exist, run get_all_contacts.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the contact to update. -CONTACT_ID = 'INSERT_CONTACT_ID_HERE' - - -def main(client, contact_id): - # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201808') - - # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', long(contact_id)) - .Limit(1)) - - # Get contacts by statement. - response = contact_service.getContactsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_contacts = [] - for contact in response['results']: - contact['address'] = '123 New Street, New York, NY, 10011' - updated_contacts.append(contact) - - # Update the contact on the server. - contacts = contact_service.updateContacts(updated_contacts) - - # Display results. - for contact in contacts: - print (('Contact with ID "%s", name "%s", and address "%s" ' - 'was updated.') - % (contact['id'], contact['name'], contact['address'])) - else: - print 'No contacts found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CONTACT_ID) diff --git a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py deleted file mode 100755 index f17f68bb..00000000 --- a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the IDs of the custom targeting keys for the hierarchy. -HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' -HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201808') - - hierarchy_level_1 = { - 'customTargetingKeyId': hierarchy_level_one_key_id, - 'hierarchyLevel': '1' - } - - hierarchy_level_2 = { - 'customTargetingKeyId': hierarchy_level_two_key_id, - 'hierarchyLevel': '2' - } - - hierarchy_levels = [hierarchy_level_1, hierarchy_level_2] - - # Create content metadata key hierarchy object. - content_metadata_key_hierarchy = { - 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(), - 'hierarchyLevels': hierarchy_levels - } - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy])) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id "%s" and name "%s"' - ' was created.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, HIERARCHY_LEVEL_ONE_KEY_ID, - HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py deleted file mode 100755 index 842856f7..00000000 --- a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 content metadata key hierarchies. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201808') - - # Create a statement to select content metadata key hierarchies. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of content metadata key hierarchies at a time, - # paging through until all content metadata key hierarchies have been - # retrieved. - while True: - response = ( - content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for content_metadata_key_hierarchy in response['results']: - # Print out some information for each content metadata key hierarchy. - print('Content metadata key hierarchy with ID "%d" and name "%s" was ' - 'found.\n' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py deleted file mode 100755 index e966ba99..00000000 --- a/examples/ad_manager/v201808/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the content metadata key hierarchy to update. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') -# Set the ID of the custom targeting key to be added as a hierarchy level. -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201808') - - # Create a query to select a single content metadata key hierarchy. - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) - .Limit(1)) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement()))[0] - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - if content_metadata_key_hierarchies: - content_metadata_key_hierarchy = content_metadata_key_hierarchies[0] - - # Update the content metadata key hierarchy by adding a hierarchy level. - hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels'] - - hierarchy_level = { - 'customTargetingKeyId': custom_targeting_key_id, - 'hierarchyLevel': str(len(hierarchy_levels) + 1) - } - - content_metadata_key_hierarchy['hierarchyLevels'] = ( - hierarchy_levels.append(hierarchy_level)) - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies)) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id "%s" and name "%s"' - ' was updated.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - else: - print 'No content metadata key hierarchies were found' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID, - CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201808/content_service/__init__.py b/examples/ad_manager/v201808/content_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/content_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/content_service/get_all_content.py b/examples/ad_manager/v201808/content_service/get_all_content.py deleted file mode 100755 index d4c120ca..00000000 --- a/examples/ad_manager/v201808/content_service/get_all_content.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 content. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201808') - - # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of content at a time, paging - # through until all content have been retrieved. - while True: - response = content_service.getContentByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for content in response['results']: - # Print out some information for each content. - print('Content with ID "%d" and name "%s" was found.\n' % - (content['id'], content['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_service/__init__.py b/examples/ad_manager/v201808/creative_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/creative_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/creative_service/copy_image_creatives.py b/examples/ad_manager/v201808/creative_service/copy_image_creatives.py deleted file mode 100755 index 24740e02..00000000 --- a/examples/ad_manager/v201808/creative_service/copy_image_creatives.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a copy of an image creative. - -To determine which image creatives exist, run get_image_creatives.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the line item to pause. -CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201808') - - # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', CREATIVE_ID)) - - # Get the creative. - query_result = creative_service.getCreativesByStatement( - statement.ToStatement()) - - image_creative = query_result['results'][0] - - # Build the new creative, set id to None to create a copy. - image_creative['id'] = None - image_creative['name'] = 'Copy of %s' % image_creative['name'] - - result = creative_service.createCreatives([image_creative])[0] - print ('A creative with ID %d, name "%s", and type "%s" was created and ' - 'can be previewed at: %s' % (result['id'], - result['name'], - ad_manager.AdManagerClassType(result), - result['previewUrl'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_service/create_creative_from_template.py b/examples/ad_manager/v201808/creative_service/create_creative_from_template.py deleted file mode 100755 index c83d1c12..00000000 --- a/examples/ad_manager/v201808/creative_service/create_creative_from_template.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates a new template creative for a given advertiser. - -To determine which companies are advertisers, run get_advertisers.py. -To determine which creative templates exist, run -get_all_creative_templates.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import os -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set id of the advertiser (company) that the creative will be assigned to. -ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201808') - - # Use the image banner with optional third party tracking template. - creative_template_id = '10000680' - - # Create image asset. - file_name = 'image%s.jpg' % uuid.uuid4() - image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r').read() - size = { - 'width': '300', - 'height': '250' - } - asset = { - 'xsi_type': 'CreativeAsset', - 'fileName': file_name, - 'assetByteArray': image_data, - 'size': size - } - - # Create creative from templates. - creative = { - 'xsi_type': 'TemplateCreative', - 'name': 'Template Creative #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'size': size, - 'creativeTemplateId': creative_template_id, - 'creativeTemplateVariableValues': [ - { - 'xsi_type': 'AssetCreativeTemplateVariableValue', - 'uniqueName': 'Imagefile', - 'asset': asset - }, - { - 'xsi_type': 'LongCreativeTemplateVariableValue', - 'uniqueName': 'Imagewidth', - 'value': '300' - }, - { - 'xsi_type': 'LongCreativeTemplateVariableValue', - 'uniqueName': 'Imageheight', - 'value': '250' - }, - { - 'xsi_type': 'UrlCreativeTemplateVariableValue', - 'uniqueName': 'ClickthroughURL', - 'value': 'www.google.com' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Targetwindow', - 'value': '_blank' - } - ] - } - - # Call service to create the creative. - creative = creative_service.createCreatives([creative])[0] - - # Display results. - print ('Template creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], - ad_manager.AdManagerClassType(creative), creative['previewUrl'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201808/creative_service/create_creatives.py b/examples/ad_manager/v201808/creative_service/create_creatives.py deleted file mode 100755 index 071c4a36..00000000 --- a/examples/ad_manager/v201808/creative_service/create_creatives.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new image creatives for a given advertiser. - -To determine which companies are advertisers, run get_advertisers.py. -To determine which creatives already exist, run get_all_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import os -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set id of the advertiser (company) that all creatives will be assigned to. -ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201808') - - # Create creative objects. - creatives = [] - with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r') as image: - image_data = image.read() - - for _ in xrange(5): - # Create creative size. - size = { - 'width': '300', - 'height': '250' - } - - # Create image asset. - creative_asset = { - 'xsi_type': 'CreativeAsset', - 'fileName': 'image.jpg', - 'assetByteArray': image_data, - 'size': size - } - - # Create an image creative. - creative = { - 'xsi_type': 'ImageCreative', - 'name': 'Image Creative #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'destinationUrl': 'http://google.com', - 'size': size, - 'primaryImageAsset': creative_asset - } - - creatives.append(creative) - - # Add creatives. - creatives = creative_service.createCreatives(creatives) - - # Display results. - for creative in creatives: - print ('Image creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], - ad_manager.AdManagerClassType(creative), creative['previewUrl'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201808/creative_service/create_custom_creative.py b/examples/ad_manager/v201808/creative_service/create_custom_creative.py deleted file mode 100755 index 5bd8cbd4..00000000 --- a/examples/ad_manager/v201808/creative_service/create_custom_creative.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a custom creative for a given advertiser. - -This feature is only available to Ad Manager 360 solution networks. To determine -which companies are advertisers, run get_advertisers.py. To determine -which creative templates exist, run get_all_creative_templates.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import os -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set id of the advertiser (company) that the creative will be assigned to. -ADVERTISER_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201808') - - # Get the image data for the creative. - image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r').read() - - # Create the HTML snippet used in the custom creative. - html_snippet = ('
Click above for ' - 'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%', - '%%FILE:IMAGE_ASSET%%') - - # Create custom creative. - creative = { - 'xsi_type': 'CustomCreative', - 'name': 'Custom Creative #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'size': {'width': '300', 'height': '250'}, - 'destinationUrl': 'http://google.com', - 'customCreativeAssets': [ - { - 'xsi_type': 'CustomCreativeAsset', - 'macroName': 'IMAGE_ASSET', - 'asset': { - 'assetByteArray': image_data, - 'fileName': 'image%s.jpg' % uuid.uuid4() - } - } - ], - 'htmlSnippet': html_snippet - } - - # Call service to create the creative. - creatives = creative_service.createCreatives([creative]) - - # Display results. - if creatives: - creative = creatives[0] - print ('Template creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], - ad_manager.AdManagerClassType(creative), creative['previewUrl'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201808/creative_service/create_native_creative.py b/examples/ad_manager/v201808/creative_service/create_native_creative.py deleted file mode 100755 index 838e7708..00000000 --- a/examples/ad_manager/v201808/creative_service/create_native_creative.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates a new native creative for a given advertiser. - -To determine which companies are advertisers, run get_advertisers.py. - -The code in this example will use app data from the Google sample app -'Pie Noon': - -https://play.google.com/store/apps/details?id=com.google.fpl.pie_noon&hl=en - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import urllib2 -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set id of the advertiser (company) that the creative will be assigned to. -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -ICON_URL = ('https://lh4.ggpht.com/GIGNKdGHMEHFDw6TM2bgAUDKPQQRIReKZPqEpMeEhZO' - 'PYnTdOQGaSpGSEZflIFs0iw=h300') -APP_ICON_SMALL = ('https://lh6.ggpht.com/Jzvjne5CLs6fJ1MHF-XeuUfpABzl0YNMlp4Rp' - 'HnvPRCIj4--eTDwtyouwUDzVVekXw=w300') - - -def main(client, advertiser_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201808') - - # Use the system defined native app install creative template. - creative_template_id = '10004400' - - image_data = urllib2.urlopen(ICON_URL).read() - - app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() - - # Create creative from templates. - creative = { - 'xsi_type': 'TemplateCreative', - 'name': 'Native Creative #%s' % uuid.uuid4(), - 'advertiserId': advertiser_id, - 'size': {'width': '1', 'height': '1', 'isAspectRatio': False}, - 'creativeTemplateId': creative_template_id, - 'destinationUrl': ('https://play.google.com/store/apps/details?id=' - 'com.google.fpl.pie_noon'), - 'creativeTemplateVariableValues': [ - { - 'xsi_type': 'AssetCreativeTemplateVariableValue', - 'uniqueName': 'Image', - 'asset': { - 'assetByteArray': image_data, - 'fileName': 'file%s.png' % uuid.uuid4() - } - }, - { - 'xsi_type': 'AssetCreativeTemplateVariableValue', - 'uniqueName': 'Appicon', - 'asset': { - 'assetByteArray': app_icon_data, - 'fileName': 'appicon%s.png' % uuid.uuid4() - } - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Price', - 'value': 'Free' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Calltoaction', - 'value': 'Install' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Starrating', - 'value': '4' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Store', - 'value': 'Google Play' - }, - { - 'xsi_type': 'UrlCreativeTemplateVariableValue', - 'uniqueName': 'DeeplinkclickactionURL', - 'value': 'market://details?id=com.google.fpl.pie_noon' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Body', - 'value': 'Try multi-screen mode!' - }, - { - 'xsi_type': 'StringCreativeTemplateVariableValue', - 'uniqueName': 'Headline', - 'value': 'Pie Noon' - } - ] - } - - # Call service to create the creative. - creative = creative_service.createCreatives([creative])[0] - - # Display results. - print ('Native creative with id "%s" and name "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['previewUrl'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201808/creative_service/get_all_creatives.py b/examples/ad_manager/v201808/creative_service/get_all_creatives.py deleted file mode 100755 index 6a440f6d..00000000 --- a/examples/ad_manager/v201808/creative_service/get_all_creatives.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creatives. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201808') - - # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of creatives at a time, paging - # through until all creatives have been retrieved. - while True: - response = creative_service.getCreativesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for creative in response['results']: - # Print out some information for each creative. - print('Creative with ID "%d" and name "%s" was found.\n' % - (creative['id'], creative['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_service/get_image_creatives.py b/examples/ad_manager/v201808/creative_service/get_image_creatives.py deleted file mode 100755 index 1e532578..00000000 --- a/examples/ad_manager/v201808/creative_service/get_image_creatives.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 image creatives. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201808') - # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('creativeType = :creativeType') - .WithBindVariable('creativeType', 'ImageCreative')) - - # Retrieve a small amount of creatives at a time, paging - # through until all creatives have been retrieved. - while True: - response = creative_service.getCreativesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for creative in response['results']: - # Print out some information for each creative. - print('Creative with ID "%d" and name "%s" was found.\n' % - (creative['id'], creative['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_service/update_creatives.py b/examples/ad_manager/v201808/creative_service/update_creatives.py deleted file mode 100755 index 5ab70081..00000000 --- a/examples/ad_manager/v201808/creative_service/update_creatives.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates the destination URL of a single image creative. - -To determine which image creatives exist, run get_all_creatives.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -IMAGE_CREATIVE_ID = 'INSERT_IMAGE_CREATIVE_ID_HERE' - - -def main(client, image_creative_id): - # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201808') - - # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('creativeType = :type AND id = :id') - .WithBindVariable('type', 'ImageCreative') - .WithBindVariable('id', long(image_creative_id)) - .Limit(1)) - - # Get creatives by statement. - response = creative_service.getCreativesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local creative object by changing its destination URL. - updated_creatives = [] - for creative in response['results']: - creative['destinationUrl'] = 'http://news.google.com' - updated_creatives.append(creative) - - # Update creatives remotely. - creatives = creative_service.updateCreatives(updated_creatives) - - # Display results. - for creative in creatives: - print ('Image creative with id "%s" and destination URL "%s" was ' - 'updated.' % (creative['id'], creative['destinationUrl'])) - else: - print 'No creatives found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, IMAGE_CREATIVE_ID) diff --git a/examples/ad_manager/v201808/creative_set_service/__init__.py b/examples/ad_manager/v201808/creative_set_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/creative_set_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201808/creative_set_service/associate_creative_set_to_line_item.py deleted file mode 100755 index a104a70f..00000000 --- a/examples/ad_manager/v201808/creative_set_service/associate_creative_set_to_line_item.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. - -"""Creates a line item creative association for a creative set. - -To create creative sets, run create_creative_set.py. To create creatives, run -create_creatives.py. To determine which LICAs exist, run get_all_licas.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, creative_set_id, line_item_id): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201808') - - # Create LICA for a creative set. - lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} - - # Add LICA. - lica = lica_service.createLineItemCreativeAssociations([lica]) - - # Display results. - print (('LICA with line item ID "%s" and creative set ID "%s" was ' - 'created.') % (lica['lineItemId'], lica['creativeSetId'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CREATIVE_SET_ID, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201808/creative_set_service/create_creative_set.py b/examples/ad_manager/v201808/creative_set_service/create_creative_set.py deleted file mode 100755 index fc8f5cb0..00000000 --- a/examples/ad_manager/v201808/creative_set_service/create_creative_set.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new creative sets. - -To determine which creative sets exist, run get_all_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' -COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' - - -def main(client, master_creative_id, companion_creative_id): - # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201808') - - # Create creative set objects. - creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), - 'masterCreativeId': master_creative_id, - 'companionCreativeIds': [companion_creative_id]} - - # Add creative sets. - creative_set = creative_set_service.createCreativeSet(creative_set) - - # Display results. - if creative_set: - print (('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was created.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, MASTER_CREATIVE_ID, COMPANION_CREATIVE_ID) diff --git a/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py deleted file mode 100755 index d32e9d35..00000000 --- a/examples/ad_manager/v201808/creative_set_service/get_all_creative_sets.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creative sets. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - creative_set_service = client.GetService( - 'CreativeSetService', version='v201808') - - # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of creative sets at a time, paging - # through until all creative sets have been retrieved. - while True: - response = creative_set_service.getCreativeSetsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for creative_set in response['results']: - # Print out some information for each creative set. - print('Creative set with ID "%d" and name "%s" was found.\n' % - (creative_set['id'], creative_set['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py deleted file mode 100755 index 2646ea85..00000000 --- a/examples/ad_manager/v201808/creative_set_service/get_creative_sets_for_master_creative.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creative sets for a master creative. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -MASTER_CREATIVE_ID = 'INSERT_MASTER_CREATIVE_ID_HERE' - - -def main(client, master_creative_id): - # Initialize appropriate service. - creative_set_service = client.GetService( - 'CreativeSetService', version='v201808') - # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('masterCreativeId = :masterCreativeId') - .WithBindVariable('masterCreativeId', master_creative_id)) - - # Retrieve a small amount of creative sets at a time, paging - # through until all creative sets have been retrieved. - while True: - response = creative_set_service.getCreativeSetsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for creative_set in response['results']: - # Print out some information for each creative set. - print('Creative set with ID "%d" and name "%s" was found.\n' % - (creative_set['id'], creative_set['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, MASTER_CREATIVE_ID) diff --git a/examples/ad_manager/v201808/creative_set_service/update_creative_set.py b/examples/ad_manager/v201808/creative_set_service/update_creative_set.py deleted file mode 100755 index 1a333f43..00000000 --- a/examples/ad_manager/v201808/creative_set_service/update_creative_set.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates a creative set by adding a companion creative. - -To determine which creative sets exist, run get_all_creative_sets.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the creative set to update. -CREATIVE_SET_ID = 'INSERT_CREATIVE_SET_ID_HERE' -COMPANION_CREATIVE_ID = 'INSERT_COMPANION_CREATIVE_ID_HERE' - - -def main(client, creative_set_id, companion_creative_id): - # Initialize appropriate service. - creative_set_service = client.GetService('CreativeSetService', - version='v201808') - - # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :creativeSetId') - .WithBindVariable('creativeSetId', long(creative_set_id))) - - # Get creative set. - response = creative_set_service.getCreativeSetsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_created_sets = [] - for creative_set in response['results']: - creative_set['companionCreativeIds'].append(companion_creative_id) - updated_created_sets.append(creative_set) - - # Update the creative sets on the server. - creative_sets = creative_set_service.updateCreativeSet(updated_created_sets) - - # Display results. - for creative_set in creative_sets: - print (('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was updated.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) - else: - print 'No creative sets found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CREATIVE_SET_ID, COMPANION_CREATIVE_ID) diff --git a/examples/ad_manager/v201808/creative_template_service/__init__.py b/examples/ad_manager/v201808/creative_template_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/creative_template_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py deleted file mode 100755 index 67a95fad..00000000 --- a/examples/ad_manager/v201808/creative_template_service/get_all_creative_templates.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creative templates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201808') - - # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of creative templates at a time, paging - # through until all creative templates have been retrieved. - while True: - response = creative_template_service.getCreativeTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for creative_template in response['results']: - # Print out some information for each creative template. - print('Creative template with ID "%d" and name "%s" was found.\n' % - (creative_template['id'], creative_template['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py deleted file mode 100755 index 8630e84d..00000000 --- a/examples/ad_manager/v201808/creative_template_service/get_system_defined_creative_templates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 system defined creative templates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201808') - # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('type = :type') - .WithBindVariable('type', 'SYSTEM_DEFINED')) - - # Retrieve a small amount of creative templates at a time, paging - # through until all creative templates have been retrieved. - while True: - response = creative_template_service.getCreativeTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for creative_template in response['results']: - # Print out some information for each creative template. - print('Creative template with ID "%d" and name "%s" was found.\n' % - (creative_template['id'], creative_template['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/create_creative_wrappers.py deleted file mode 100755 index 92261400..00000000 --- a/examples/ad_manager/v201808/creative_wrapper_service/create_creative_wrappers.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates a new creative wrapper. - -Creative wrappers must be associated with a LabelType.CREATIVE_WRAPPER label and -applied to ad units by AdUnit.appliedLabels. To determine which creative -wrappers exist, run get_all_creative_wrappers.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -LABEL_ID = 'INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE' - - -def main(client, label_id): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201808') - - # Create creative wrapper objects. - creative_wrapper = { - # A label can only be associated with one creative wrapper. - 'labelId': label_id, - 'ordering': 'INNER', - 'htmlHeader': 'My creative wrapper header', - 'htmlFooter': 'My creative wrapper footer' - } - - # Add creative wrapper. - creative_wrappers = creative_wrapper_service.createCreativeWrappers( - [creative_wrapper]) - - # Display results. - for creative_wrapper in creative_wrappers: - print ('Creative wrapper with ID "%s" applying to label "%s" was ' - 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LABEL_ID) diff --git a/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py deleted file mode 100755 index 313f2bb5..00000000 --- a/examples/ad_manager/v201808/creative_wrapper_service/deactivate_creative_wrapper.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example deactivates a creative wrapper belonging to a label. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, label_id): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201808') - - # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status AND labelId = :labelId') - .WithBindVariable('status', 'ACTIVE') - .WithBindVariable('labelId', long(label_id))) - - creative_wrappers_deactivated = 0 - - # Get creative wrappers by statement. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for creative_wrapper in response['results']: - print ('Creative wrapper with ID "%s" applying to label "%s" with ' - 'status "%s" will be deactivated.' % - (creative_wrapper['id'], - creative_wrapper['labelId'], - creative_wrapper['status'])) - # Perform action. - result = creative_wrapper_service.performCreativeWrapperAction( - {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - creative_wrappers_deactivated += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if creative_wrappers_deactivated > 0: - print ('Number of creative wrappers deactivated: %s' % - creative_wrappers_deactivated) - else: - print 'No creative wrappers were deactivated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LABEL_ID) diff --git a/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py deleted file mode 100755 index 1e9e9095..00000000 --- a/examples/ad_manager/v201808/creative_wrapper_service/get_active_creative_wrappers.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active creative wrappers. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201808') - # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status') - .WithBindVariable('status', 'ACTIVE')) - - # Retrieve a small amount of creative wrappers at a time, paging - # through until all creative wrappers have been retrieved. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for creative_wrapper in response['results']: - # Print out some information for each creative wrapper. - print('Creative wrapper with ID "%d" and label ID "%d" was found.\n' % - (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py deleted file mode 100755 index 87f4a745..00000000 --- a/examples/ad_manager/v201808/creative_wrapper_service/get_all_creative_wrappers.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creative wrappers. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201808') - - # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of creative wrappers at a time, paging - # through until all creative wrappers have been retrieved. - while True: - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for creative_wrapper in response['results']: - # Print out some information for each creative wrapper. - print('Creative wrapper with ID "%d" and label id "%d" was found.\n' % - (creative_wrapper['id'], creative_wrapper['labelId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py deleted file mode 100755 index 86c38a62..00000000 --- a/examples/ad_manager/v201808/creative_wrapper_service/update_creative_wrappers.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates a creative wrapper to the 'OUTER' wrapping order. - -To determine which creative wrappers exist, run get_all_creative_wrappers.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the creative wrapper to update. -CREATIVE_WRAPPER_ID = 'INSERT_CREATIVE_WRAPPER_ID_HERE' - - -def main(client, creative_wrapper_id): - # Initialize appropriate service. - creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201808') - - # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :creativeWrapperId') - .WithBindVariable('creativeWrapperId', - long(creative_wrapper_id))) - - # Get creative wrappers. - response = creative_wrapper_service.getCreativeWrappersByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_creative_wrappers = [] - for creative_wrapper in response['results']: - creative_wrapper['ordering'] = 'OUTER' - updated_creative_wrappers.append(creative_wrapper) - - # Update the creative wrappers on the server. - creative_wrappers = creative_wrapper_service.updateCreativeWrappers( - updated_creative_wrappers) - - # Display results. - for creative_wrapper in creative_wrappers: - print (('Creative wrapper with ID "%s" and wrapping order "%s" ' - 'was updated.') % (creative_wrapper['id'], - creative_wrapper['ordering'])) - else: - print 'No creative wrappers found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CREATIVE_WRAPPER_ID) diff --git a/examples/ad_manager/v201808/custom_field_service/__init__.py b/examples/ad_manager/v201808/custom_field_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/custom_field_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201808/custom_field_service/create_custom_field_options.py deleted file mode 100755 index 20fddd59..00000000 --- a/examples/ad_manager/v201808/custom_field_service/create_custom_field_options.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates custom field options for a drop-down custom field. - -Once created, custom field options can be found under the options fields of the -drop-down custom field and they cannot be deleted. To determine which custom -fields exist, run get_all_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the drop-down custom field to create options for. -CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' - - -def main(client, custom_field_id): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201808') - - # Create custom field options. - custom_field_options = [ - { - 'displayName': 'Approved', - 'customFieldId': custom_field_id - }, - { - 'displayName': 'Unapproved', - 'customFieldId': custom_field_id - } - ] - - # Add custom field options. - custom_field_options = custom_field_service.createCustomFieldOptions( - custom_field_options) - - # Display results. - for custom_field_option in custom_field_options: - print ('Custom field option with ID "%s" and name "%s" was created.' - % (custom_field_option['id'], custom_field_option['displayName'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/ad_manager/v201808/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/create_custom_fields.py deleted file mode 100755 index 83d22be9..00000000 --- a/examples/ad_manager/v201808/custom_field_service/create_custom_fields.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates custom fields. - -To determine which custom fields exist, run get_all_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201808') - - # Create custom field objects. - custom_fields = [ - { - 'name': 'Customer comments #%s' % uuid.uuid4(), - 'entityType': 'LINE_ITEM', - 'dataType': 'STRING', - 'visibility': 'FULL' - }, { - 'name': 'Internal approval status #%s' % uuid.uuid4(), - 'entityType': 'LINE_ITEM', - 'dataType': 'DROP_DOWN', - 'visibility': 'FULL' - } - ] - - # Add custom fields. - custom_fields = custom_field_service.createCustomFields(custom_fields) - - # Display results. - for custom_field in custom_fields: - print ('Custom field with ID "%s" and name "%s" was created.' - % (custom_field['id'], custom_field['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py deleted file mode 100755 index 3f2848b4..00000000 --- a/examples/ad_manager/v201808/custom_field_service/deactivate_all_line_item_custom_fields.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 deactivates all active line items custom fields. - -To determine which custom fields exist, run get_all_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201808') - - # Create statement to select only active custom fields that apply to - # line items. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('entityType = :entityType and isActive = :isActive') - .WithBindVariable('entityType', 'LINE_ITEM') - .WithBindVariable('isActive', True)) - - custom_fields_deactivated = 0 - - # Get custom fields by statement. - while True: - response = custom_field_service.getCustomFieldsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for custom_field in response['results']: - print ('Custom field with ID "%s" and name "%s" will' - ' be deactivated.' % (custom_field['id'], custom_field['name'])) - result = custom_field_service.performCustomFieldAction( - {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - custom_fields_deactivated += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - if custom_fields_deactivated > 0: - print 'Number of custom fields deactivated: %s' % custom_fields_deactivated - else: - print 'No custom fields were deactivated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py deleted file mode 100755 index ab3dd0cb..00000000 --- a/examples/ad_manager/v201808/custom_field_service/get_all_custom_fields.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fields. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201808') - - # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of custom fields at a time, paging - # through until all custom fields have been retrieved. - while True: - response = custom_field_service.getCustomFieldsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for custom_field in response['results']: - # Print out some information for each custom field. - print('Custom field with ID "%d" and name "%s" was found.\n' % - (custom_field['id'], custom_field['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py deleted file mode 100755 index 3144f460..00000000 --- a/examples/ad_manager/v201808/custom_field_service/get_custom_fields_for_line_items.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 fields that can be applied to line items. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201808') - # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('entityType = :entityType') - .WithBindVariable('entityType', 'LINE_ITEM')) - - # Retrieve a small amount of custom fields at a time, paging - # through until all custom fields have been retrieved. - while True: - response = custom_field_service.getCustomFieldsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for custom_field in response['results']: - # Print out some information for each custom field. - print('Custom field with ID "%d" and name "%s" was found.\n' % - (custom_field['id'], custom_field['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py deleted file mode 100755 index e6487aeb..00000000 --- a/examples/ad_manager/v201808/custom_field_service/set_line_item_custom_field_value.py +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 sets custom field values on a line item. - -To determine which custom fields exist, run get_all_custom_fields.py. -To determine which line item exist, run get_all_line_items.py. -To create custom field options, run create_custom_field_options.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the custom fields, custom field option, and line item. -CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' -DROP_DOWN_CUSTOM_FIELD_ID = 'INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE' -CUSTOM_FIELD_OPTION_ID = 'INSERT_CUSTOM_FIELD_OPTION_ID_HERE' -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, custom_field_id, drop_down_custom_field_id, - custom_field_option_id, line_item_id): - # Initialize appropriate services. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201808') - - line_item_service = client.GetService('LineItemService', version='v201808') - - # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :customFieldId') - .WithBindVariable('customFieldId', custom_field_id) - .Limit(1)) - - # Get custom field. - custom_field = custom_field_service.getCustomFieldsByStatement( - custom_field_statement.ToStatement())['results'][0] - - # Create statement to get a drop down custom field. - drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v201808') - .Where('id = :dropDownCustomFieldId') - .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) - .Limit(1)) - - # Get drop-down custom field. - drop_down_custom_field = custom_field_service.getCustomFieldsByStatement( - drop_down_custom_field_statement.ToStatement())['results'][0] - - # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :lineItemId') - .WithBindVariable('lineItemId', line_item_id) - .Limit(1)) - - # Get line item. - line_item = line_item_service.getLineItemsByStatement( - line_item_statement.ToStatement())['results'][0] - - if custom_field and line_item: - # Create custom field values. - custom_field_value = { - 'customFieldId': custom_field['id'], - 'xsi_type': 'CustomFieldValue', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'Custom field value' - } - } - - drop_down_custom_field_value = { - 'customFieldId': drop_down_custom_field['id'], - 'xsi_type': 'DropDownCustomFieldValue', - 'customFieldOptionId': custom_field_option_id, - } - - custom_field_values = [custom_field_value, drop_down_custom_field_value] - - old_custom_field_values = [] - if 'customFieldValues' in line_item: - old_custom_field_values = line_item['customFieldValues'] - - # Only add existing custom field values for different custom fields than the - # ones you are setting. - for old_custom_field_value in old_custom_field_values: - if (old_custom_field_value['customFieldId'] != - custom_field_value['customFieldId'] - and old_custom_field_value['customFieldId'] != - drop_down_custom_field_value['customFieldId']): - custom_field_values.append(old_custom_field_value) - - line_item['customFieldValues'] = custom_field_values - - # Update the line item on the server. - line_items = line_item_service.updateLineItems([line_item]) - - # Display results. - for line_item in line_items: - custom_field_value_strings = [] - for value in line_item['customFieldValues']: - if ad_manager.AdManagerClassType(value) == 'CustomFieldValue': - custom_field_value_string = ( - '{ID: "%s", value: "%s"}' - % (value['customFieldId'], value['value']['value'])) - elif ad_manager.AdManagerClassType(value) == 'DropDownCustomFieldValue': - custom_field_value_string = ( - '{ID: "%s", custom field option ID: "%s"}' - % (value['customFieldId'], value['customFieldOptionId'])) - custom_field_value_strings.append(custom_field_value_string) - print ('Line item with ID "%s" set with custom field values %s.' - % (line_item['id'], ','.join(custom_field_value_strings))) - else: - print 'Line item or custom field not found.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CUSTOM_FIELD_ID, DROP_DOWN_CUSTOM_FIELD_ID, - CUSTOM_FIELD_OPTION_ID, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py deleted file mode 100755 index 524b01d5..00000000 --- a/examples/ad_manager/v201808/custom_field_service/update_custom_fields.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates custom field descriptions. - -To determine which custom fields exist, run get_all_custom_fields.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the custom field to update. -CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID_HERE' - - -def main(client, custom_field_id): - # Initialize appropriate service. - custom_field_service = client.GetService( - 'CustomFieldService', version='v201808') - - # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :customFieldId') - .WithBindVariable('customFieldId', long(custom_field_id))) - - # Get custom field. - custom_fields = custom_field_service.getCustomsFieldByStatement( - statement.ToStatement()) - - if custom_fields: - for custom_field in custom_fields: - custom_field['description'] += ' Updated.' - - # Update the custom field on the server. - custom_fields = custom_field_service.updateCustomFields(custom_fields) - - # Display results. - for custom_field in custom_fields: - print (('Custom field with ID "%s", name "%s", and ' - 'description "%s" was updated.') - % (custom_field['id'], custom_field['name'], - custom_field['description'])) - else: - print 'No custom fields found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CUSTOM_FIELD_ID) diff --git a/examples/ad_manager/v201808/custom_targeting_service/__init__.py b/examples/ad_manager/v201808/custom_targeting_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/custom_targeting_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201808/custom_targeting_service/create_custom_targeting_keys_and_values.py deleted file mode 100755 index 861be833..00000000 --- a/examples/ad_manager/v201808/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates new custom targeting keys and values. - -To determine which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py. To target these custom targeting -keys and values, run target_custom_criteria_example.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201808') - - # Create custom targeting key objects. - keys = [ - { - 'displayName': 'gender', - 'name': 'g', - 'type': 'PREDEFINED' - }, - { - 'displayName': 'car model', - 'name': 'c', - 'type': 'FREEFORM' - }, - # Add predefined key that may be use for content targeting. - { - 'displayName': 'genre', - 'name': 'genre', - 'type': 'PREDEFINED' - } - ] - - # Add custom targeting keys. - keys = custom_targeting_service.createCustomTargetingKeys(keys) - - # Display results. - if keys: - for key in keys: - print ('A custom targeting key with id "%s", name "%s", and display ' - 'name "%s" was created.' % (key['id'], key['name'], - key['displayName'])) - else: - print 'No keys were created.' - - # Create custom targeting value objects. - values = [ - { - 'customTargetingKeyId': keys[0]['id'], - 'displayName': 'male', - # Name is set to 1 so that the actual name can be hidden from website - # users. - 'name': '1', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[0]['id'], - 'displayName': 'female', - # Name is set to 2 so that the actual name can be hidden from website - # users. - 'name': '2', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[1]['id'], - 'displayName': 'honda civic', - 'name': 'honda civic', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[1]['id'], - 'displayName': 'toyota', - 'name': 'toyota', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[2]['id'], - 'displayName': 'comedy', - 'name': 'comedy', - 'matchType': 'EXACT' - }, - { - 'customTargetingKeyId': keys[2]['id'], - 'displayName': 'drama', - 'name': 'drama', - 'matchType': 'EXACT' - } - ] - - # Add custom targeting values. - values = custom_targeting_service.createCustomTargetingValues(values) - - # Display results. - if values: - for value in values: - print ('A custom targeting value with id "%s", belonging to key with id' - ' "%s", name "%s", and display name "%s" was created.' - % (value['id'], value['customTargetingKeyId'], value['name'], - value['displayName'])) - else: - print 'No values were created.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py deleted file mode 100755 index 5b5524f0..00000000 --- a/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_keys.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 deletes a custom targeting key by its name. - -To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -KEY_NAME = 'INSERT_CUSTOM_TARGETING_KEY_NAME_HERE' - - -def main(client, key_name): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201808') - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('name = :name') - .WithBindVariable('name', key_name)) - - deleted_custom_targeting_keys = 0 - - # Get custom targeting keys. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - key_ids = [str(key['id']) for key in response['results']] - action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id IN (%s)' % ', '.join(key_ids))) - - # Delete custom targeting keys. - result = custom_targeting_service.performCustomTargetingKeyAction( - action, key_statement.ToStatement()) - - if result and int(result['numChanges']) > 0: - deleted_custom_targeting_keys += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - if deleted_custom_targeting_keys > 0: - print ('Number of custom targeting keys deleted: %s' - % deleted_custom_targeting_keys) - else: - print 'No custom targeting keys were deleted.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, KEY_NAME) diff --git a/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py deleted file mode 100755 index 6ca118f1..00000000 --- a/examples/ad_manager/v201808/custom_targeting_service/delete_custom_targeting_values.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. - -"""Deletes custom targeting values for a given custom targeting key. - -To determine which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201808') - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('customTargetingKeyId = :keyId') - .WithBindVariable('keyId', key_id)) - - deleted_custom_targeting_values = 0 - - # Get custom targeting values. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - value_ids = [value['id'] for value in response['results']] - action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v201808') - .Where('customTargetingKeyId = :keyId ' - 'AND id IN (%s)' % ', '.join(value_ids)) - .WithBindVariable('keyId', key_id)) - - # Delete custom targeting values. - result = custom_targeting_service.performCustomTargetingValueAction( - action, value_statement.ToStatement()) - if result and int(result['numChanges']) > 0: - deleted_custom_targeting_values += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - if deleted_custom_targeting_values > 0: - print ('Number of custom targeting values deleted: %s' - % deleted_custom_targeting_values) - else: - print 'No custom targeting values were deleted.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, KEY_ID) diff --git a/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py deleted file mode 100755 index b33e8898..00000000 --- a/examples/ad_manager/v201808/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 targeting keys and values. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201808') - - # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v201808') - - all_keys = [] - - # Get custom targeting keys by statement. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - targeting_key_statement.ToStatement()) - if 'results' in response and len(response['results']): - all_keys.extend(response['results']) - targeting_key_statement.offset += targeting_key_statement.limit - else: - break - - if all_keys: - # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('customTargetingKeyId IN (%s)' % - ', '.join([str(key['id']) for key in all_keys]))) - - # Retrieve a small amount of custom targeting values at a time, paging - # through until all custom targeting values have been retrieved. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for custom_targeting_value in response['results']: - # Print out some information for each custom targeting value. - print('Custom targeting value with ID "%d", name "%s", display name ' - '"%s", and custom targeting key ID "%d" was found.\n' % - (custom_targeting_value['id'], custom_targeting_value['name'], - custom_targeting_value['displayName'], - custom_targeting_value['customTargetingKeyId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py deleted file mode 100755 index 51e6a12b..00000000 --- a/examples/ad_manager/v201808/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 targeting keys and values. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201808') - - # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v201808') - .Where('type = :type') - .WithBindVariable('type', 'PREDEFINED')) - - all_keys = [] - - # Get custom targeting keys by statement. - while True: - response = custom_targeting_service.getCustomTargetingKeysByStatement( - targeting_key_statement.ToStatement()) - if 'results' in response and len(response['results']): - all_keys.extend(response['results']) - targeting_key_statement.offset += targeting_key_statement.limit - else: - break - - if all_keys: - # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('customTargetingKeyId IN (:ids)') - .WithBindVariable('ids', [key['id'] for key in all_keys])) - - # Retrieve a small amount of custom targeting values at a time, paging - # through until all custom targeting values have been retrieved. - while True: - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for custom_targeting_value in response['results']: - # Print out some information for each custom targeting value. - print('Custom targeting value with ID "%d", name "%s", display name ' - '"%s", and custom targeting key ID "%d" was found.\n' % - (custom_targeting_value['id'], custom_targeting_value['name'], - custom_targeting_value['displayName'], - custom_targeting_value['customTargetingKeyId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py deleted file mode 100755 index 65c97e12..00000000 --- a/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_keys.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates the display name of a single custom targeting key. - -To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201808') - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :keyId') - .WithBindVariable('keyId', long(key_id)) - .Limit(1)) - - # Get custom targeting keys by statement. - response = custom_targeting_service.getCustomTargetingKeysByStatement( - statement.ToStatement()) - - # Update each local custom targeting key object by changing its display name. - if 'results' in response and len(response['results']): - updated_keys = [] - for key in response['results']: - if not key['displayName']: - key['displayName'] = key['name'] - key['displayName'] += ' (Deprecated)' - updated_keys.append(key) - keys = custom_targeting_service.updateCustomTargetingKeys(updated_keys) - - # Display results. - if keys: - for key in keys: - print ('Custom targeting key with id "%s", name "%s", display name ' - '"%s", and type "%s" was updated.' - % (key['id'], key['name'], key['displayName'], key['type'])) - else: - print 'No custom targeting keys were found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py deleted file mode 100755 index 2929da9d..00000000 --- a/examples/ad_manager/v201808/custom_targeting_service/update_custom_targeting_values.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. - -"""Updates name of custom targeting values belonging to a custom targeting key. - -To determine which custom targeting keys exist, run -get_all_custom_targeting_keys_and_values.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, key_id): - # Initialize appropriate service. - custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201808') - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('customTargetingKeyId = :keyId') - .WithBindVariable('keyId', long(key_id))) - - while True: - # Get custom targeting values by statement. - response = custom_targeting_service.getCustomTargetingValuesByStatement( - statement.ToStatement()) - - # Update each local custom targeting value object by changing its name. - if 'results' in response and len(response['results']): - updated_values = [] - for value in response['results']: - if not value['displayName']: - value['displayName'] = value['name'] - value['displayName'] += ' (Deprecated)' - updated_values.append(value) - values = custom_targeting_service.updateCustomTargetingValues( - updated_values) - - # Display results. - for value in values: - print ('Custom targeting value with id "%s", name "%s", and display' - ' name "%s" was updated.' - % (value['id'], value['name'], value['displayName'])) - statement.offset += statement.limit - else: - break - - if response['totalResultSetSize'] == 0: - print 'No custom targeting values were updated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201808/exchange_rate_service/__init__.py b/examples/ad_manager/v201808/exchange_rate_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/exchange_rate_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201808/exchange_rate_service/create_exchange_rates.py deleted file mode 100755 index eebb7f6e..00000000 --- a/examples/ad_manager/v201808/exchange_rate_service/create_exchange_rates.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates an exchange rate. - -To determine which exchange rates exist, run get_all_exchange_rates.py. - - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201808') - - # Create a new fixed exchange rate with currency code 'AUD', with direction - # FROM_NETWORK with a value of 1.5. - exchange_rate = { - 'currencyCode': 'AUD', - 'direction': 'FROM_NETWORK', - 'exchangeRate': long(15000000000), - 'refreshRate': 'FIXED' - } - - created_exchange_rate = exchange_rate_service.createExchangeRates( - [exchange_rate])[0] - - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was created.' % (created_exchange_rate['id'], - created_exchange_rate['currencyCode'], - created_exchange_rate['direction'], - (float(created_exchange_rate['exchangeRate']) / - 10000000000))) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py deleted file mode 100755 index 0cc20b9f..00000000 --- a/examples/ad_manager/v201808/exchange_rate_service/get_all_exchange_rates.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 exchange rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201808') - - # Create a statement to select exchange rates. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of exchange rates at a time, paging - # through until all exchange rates have been retrieved. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for exchange_rate in response['results']: - # Print out some information for each exchange rate. - print( - 'Exchange rate with ID "%d", currency code "%s", direction "%s", ' - 'and exchange rate "%d" was found.\n' % - (exchange_rate['id'], exchange_rate['currencyCode'], - exchange_rate['direction'], exchange_rate['exchangeRate'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py deleted file mode 100755 index 25704dfc..00000000 --- a/examples/ad_manager/v201808/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the exchange rate for a specific currency code. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client, currency_code): - # Initialize appropriate service. - exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201808') - # Create a statement to select exchange rates. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('currencyCode = :currencyCode') - .WithBindVariable('currencyCode', currency_code)) - - # Retrieve a small amount of exchange rates at a time, paging - # through until all exchange rates have been retrieved. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for exchange_rate in response['results']: - # Print out some information for each exchange rate. - print('Exchange rate with ID "%d", currency code "%s", and exchange ' - 'rate "%.2f" was found.\n' % - (exchange_rate['id'], exchange_rate['currencyCode'], - float(exchange_rate['exchangeRate'] / 1000000))) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CURRENCY_CODE) diff --git a/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py deleted file mode 100755 index af8090fb..00000000 --- a/examples/ad_manager/v201808/exchange_rate_service/update_exchange_rates.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates the value of an exchange rate. - -To create exchange rates, run create_exchange_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' - - -def main(client, exchange_rate_id): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201808') - - # Create a statement to get an exchange rate by its ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', long(exchange_rate_id)) - .Limit(1)) - - # Get rate cards by statement. - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - exchange_rate = response['results'][0] - - # Update the exchange rate value to 1.5. - exchange_rate['exchangeRate'] = long(15000000000) - - exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) - - if exchange_rates: - for exchange_rate in exchange_rates: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was updated.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) - else: - print 'No exchange rates were updated.' - else: - print 'No exchange rates found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, EXCHANGE_RATE_ID) diff --git a/examples/ad_manager/v201808/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201808/forecast_service/get_availability_forecast.py deleted file mode 100755 index b7f3edd9..00000000 --- a/examples/ad_manager/v201808/forecast_service/get_availability_forecast.py +++ /dev/null @@ -1,251 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 a forecast for a prospective line item. - -The prospective line item targets the entire network. The targeting can be -modified to determine forecasts for other criteria such as custom criteria -targeting (in addition to targeting the whole network). See -create_line_items.py for an example of how to create more complex targeting. - -""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set the ID of the advertiser (company) to forecast for. Setting an advertiser -# will cause the forecast to apply the appropriate unified blocking rules. -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' - - -def main(client, advertiser_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201808') - network_service = client.GetService('NetworkService', version='v201808') - - # get the root ad unit ID to target the entire network. - root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] - - now_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = now_datetime + datetime.timedelta(days=5) - - # Create prospective line item. - line_item = { - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': [ - { - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id, - } - ] - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '300', - 'height': '250' - }, - 'isAmpOnly': True, - }, - { - 'size': { - 'width': '120', - 'height': '600' - } - } - ], - 'lineItemType': 'SPONSORSHIP', - 'startDateTimeType': 'IMMEDIATELY', - 'endDateTime': end_datetime, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'DAILY' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'EVEN', - 'discountType': 'PERCENTAGE', - } - - prospective_line_item = { - 'lineItem': line_item, - 'advertiserId': advertiser_id - } - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - # The field includeTargetingCriteriaBreakdown can only be set if - # breakdowns are not manually specified. - # 'includeTargetingCriteriaBreakdown': True, - 'breakdown': { - 'timeWindows': [ - now_datetime, - now_datetime + datetime.timedelta(days=1), - now_datetime + datetime.timedelta(days=2), - now_datetime + datetime.timedelta(days=3), - now_datetime + datetime.timedelta(days=4), - end_datetime - ], - 'targets': [ - { - # Optional, the name field is only used to identify this - # breakdown in the response. - 'name': 'United States', - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': [ - { - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id, - } - ] - }, - 'geoTargeting': { - 'targetedLocations': [ - { - 'id': '2840', - 'displayName': 'US' - } - ] - } - } - }, - { - # Optional, the name field is only used to identify this - # breakdown in the response. - 'name': 'Geneva', - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': [ - { - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id, - } - ] - }, - 'geoTargeting': { - 'targetedLocations': [ - { - 'id': '20133', - 'displayName': 'Geneva' - } - ] - } - } - } - ] - } - } - - # Get forecast. - forecast = forecast_service.getAvailabilityForecast( - prospective_line_item, forecast_options) - matched = forecast['matchedUnits'] - available = forecast['availableUnits'] - possible = forecast['possibleUnits'] if 'possibleUnits' in forecast else None - unit_type = forecast['unitType'].lower() - - available_percent_overall, possible_percent_overall = CalculateForecastStats( - matched, available, possible) - - contending_line_items = getattr(forecast, 'contendingLineItems', []) - - # Display results. - print '%s %s matched overall.' % (matched, unit_type) - print '%s%% %s available overall.' % (available_percent_overall, unit_type) - print '%d contending line items overall.' % len(contending_line_items) - if possible: - print '%s%% %s possible overall.' % (possible_percent_overall, unit_type) - - if 'breakdowns' in forecast and len(forecast['breakdowns']): - for breakdown in forecast['breakdowns']: - print 'For breakdown time period %s - %s:' % ( - FormatSOAPDateTime(breakdown['startTime']), - FormatSOAPDateTime(breakdown['endTime'])) - for breakdown_entry in breakdown['breakdownEntries']: - matched = breakdown_entry['forecast']['matched'] - available = breakdown_entry['forecast']['available'] - possible = (breakdown_entry['forecast']['possible'] - if 'possible' in breakdown_entry['forecast'] else None) - name = breakdown_entry['name'] if 'name' in breakdown_entry else None - if name: - print '\tFor targeting breakdown named \'%s\'' % name - available_percent, possible_percent = CalculateForecastStats( - matched, available, possible) - print '\t\t%s %s matched.' % (matched, unit_type) - print '\t\t%s%% %s available.' % (available_percent, unit_type) - if possible: - print '\t\t%s%% %s possible.' % (possible_percent, unit_type) - - -def FormatSOAPDateTime(value): - """Format a SOAP DateTime object for printing. - - Args: - value: The DateTime object to format. - - Returns: - A string representing the value. - """ - value_date = value['date'] - return '%s-%s-%s %s:%s:%s (%s)' % ( - value_date['year'], value_date['month'], value_date['day'], - value['hour'], value['minute'], value['second'], value['timeZoneID']) - - -def CalculateForecastStats(matched, available, possible=None): - """Calculate forecast percentage stats. - - Args: - matched: The number of matched impressions. - available: The number of available impressions. - possible: The optional number of possible impressions. - - Returns: - The percentage of impressions that are available and possible. - """ - if matched > 0: - available_percent = (float(available) / matched) * 100. - else: - available_percent = 0 - - if possible is not None: - if matched > 0: - possible_percent = (possible/float(matched)) * 100. - else: - possible_percent = 0 - else: - possible_percent = None - - return available_percent, possible_percent - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v201808/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201808/forecast_service/get_availability_forecast_for_line_item.py deleted file mode 100755 index 35877319..00000000 --- a/examples/ad_manager/v201808/forecast_service/get_availability_forecast_for_line_item.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example gets an availability forecast for an existing line item. - -To determine which line items exist, run get_all_line_items.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the line item to get a forecast for. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, line_item_id): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201808') - - # Set forecasting options. - forecast_options = { - 'includeContendingLineItems': True, - 'includeTargetingCriteriaBreakdown': True, - } - - # Get forecast for line item. - forecast = forecast_service.getAvailabilityForecastById( - line_item_id, forecast_options) - matched = long(forecast['matchedUnits']) - available_units = long(forecast['availableUnits']) - - if matched > 0: - available_percent = (float(available_units) / matched) * 100. - else: - available_percent = 0 - - contending_line_items = getattr(forecast, 'contentingLineItems', []) - - # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) - - if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201808/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201808/forecast_service/get_delivery_forecast_for_line_items.py deleted file mode 100755 index 01ea6e0b..00000000 --- a/examples/ad_manager/v201808/forecast_service/get_delivery_forecast_for_line_items.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example gets a delivery forecast for two existing line items. - -To determine which line items exist, run get_all_line_items.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the line items to get forecasts for. -LINE_ITEM_ID_1 = 'INSERT_LINE_ITEM_1_ID_HERE' -LINE_ITEM_ID_2 = 'INSERT_LINE_ITEM_2_ID_HERE' - - -def main(client, line_item_id1, line_item_id2): - # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201808') - - # Get forecast for line item. - forecast = forecast_service.getDeliveryForecastByIds( - [line_item_id1, line_item_id2], None) - - for single_forecast in forecast['lineItemDeliveryForecasts']: - unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' - '%d %s predicted\n' % ( - single_forecast['lineItemId'], single_forecast['matchedUnits'], - unit_type, single_forecast['deliveredUnits'], unit_type, - single_forecast['predictedDeliveryUnits'], unit_type)) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LINE_ITEM_ID_1, LINE_ITEM_ID_2) diff --git a/examples/ad_manager/v201808/inventory_service/__init__.py b/examples/ad_manager/v201808/inventory_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/inventory_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/inventory_service/archive_ad_units.py b/examples/ad_manager/v201808/inventory_service/archive_ad_units.py deleted file mode 100755 index cfa8e179..00000000 --- a/examples/ad_manager/v201808/inventory_service/archive_ad_units.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example archives ad units. - -The parent ad unit and all ad units underneath it will be archived. To create ad -units, run create_ad_units.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' - - -def main(client, parent_id): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201808') - - # Create a query to select ad units under the parent ad unit and the parent ad - # unit. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('parentId = :parentId or id = :parentId') - .WithBindVariable('parentId', long(parent_id))) - - ad_units_archived = 0 - - # Get ad units by statement. - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for ad_unit in response['results']: - print ('Ad unit with ID "%s" and name "%s" will be archived.' - % (ad_unit['id'], ad_unit['name'])) - # Perform action. - result = inventory_service.performAdUnitAction( - {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - ad_units_archived += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if ad_units_archived > 0: - print 'Number of ad units archived: %s' % ad_units_archived - else: - print 'No ad units were archived.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/ad_manager/v201808/inventory_service/create_ad_units.py b/examples/ad_manager/v201808/inventory_service/create_ad_units.py deleted file mode 100755 index 787aefe2..00000000 --- a/examples/ad_manager/v201808/inventory_service/create_ad_units.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new ad units. - -To determine which ad units exist, run get_all_ad_units.py - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PARENT_AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' - - -def main(client, parent_id): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201808') - - # Create ad unit size. - ad_unit_size = { - 'size': { - 'width': '300', - 'height': '250' - }, - 'environmentType': 'BROWSER' - } - - # Create ad unit objects. - ad_unit = { - 'name': 'Ad_unit_%s' % uuid.uuid4(), - 'parentId': parent_id, - 'description': 'Ad unit description.', - 'targetWindow': 'BLANK', - 'adUnitSizes': [ad_unit_size] - } - - # Add ad units. - ad_units = inventory_service.createAdUnits([ad_unit]) - - # Display results. - for ad_unit in ad_units: - print ('Ad unit with ID "%s" and name "%s" was created.' - % (ad_unit['id'], ad_unit['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PARENT_AD_UNIT_ID) diff --git a/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py deleted file mode 100755 index ac13076e..00000000 --- a/examples/ad_manager/v201808/inventory_service/get_ad_unit_hierarchy.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 prints all ad unit names as a tree.""" - - -# Import appropriate modules from the client library. -import collections -from googleads import ad_manager - - -def main(client): - # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201808') - inventory_service = client.GetService('InventoryService', version='v201808') - - # Set the parent ad unit's ID for all children ad units to be fetched from. - current_network = network_service.getCurrentNetwork() - root_ad_unit_id = current_network['effectiveRootAdUnitId'] - - # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', root_ad_unit_id)) - - # Make a request for the root ad unit - response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - root_ad_unit = response['results'][0] - - all_ad_units = get_all_ad_units(inventory_service) - - display_hierarchy(root_ad_unit, all_ad_units) - - -def get_all_ad_units(inventory_service): - """Download all ad units. - - Args: - inventory_service: An instance of the InventoryService. - - Returns: - A list containing all ad units. - """ - # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v201808') - .OrderBy('id', ascending=True)) - - # Pull down all ad units into a list - keep_iterating = True - total_results = 0 - found_ad_units = [] - while keep_iterating: - page = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in page and len(page['results']): - total_results = page['totalResultSetSize'] - found_ad_units.extend(page['results']) - - statement.offset += statement.limit - keep_iterating = statement.offset < total_results - - return found_ad_units - - -def display_hierarchy(root_ad_unit, all_ad_units): - """Display the ad units as a tree. - - Args: - root_ad_unit: The root ad unit to begin from. - all_ad_units: A list containing all ad units. - """ - # Create a dict mapping the ids of parents to lists of their children. - parent_id_to_children = collections.defaultdict(list) - for ad_unit in all_ad_units: - if 'parentId' in ad_unit: - parent_id_to_children[ad_unit['parentId']].append(ad_unit) - parent_id_to_children = dict(parent_id_to_children) - - display_hierarchy_helper(root_ad_unit, parent_id_to_children, 0) - - -def display_hierarchy_helper(root, parent_id_to_children, depth): - """Recursive helper for displaying the hierarchy. - - Args: - root: The current root ad unit. - parent_id_to_children: The overall map of parent ids to children. - depth: The current depth. - """ - print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), - root['name'], root['id']) - - # Recurse for each child of this root that has children. - for child in parent_id_to_children.get(root['id'], []): - display_hierarchy_helper(child, parent_id_to_children, depth + 1) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py deleted file mode 100755 index eabc01e1..00000000 --- a/examples/ad_manager/v201808/inventory_service/get_all_ad_unit_sizes.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 unit sizes. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - ad_unit_size_service = client.GetService( - 'InventoryService', version='v201808') - - # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of ad unit sizes at a time, paging - # through until all ad unit sizes have been retrieved. - response = ad_unit_size_service.getAdUnitSizesByStatement( - statement.ToStatement()) - if response: - for ad_unit_size in response: - # Print out some information for each ad unit size. - if 'fullDisplayString' in ad_unit_size: - print('Ad unit size with dimensions "%s" was found.\n' % - (ad_unit_size['fullDisplayString'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py deleted file mode 100755 index c5c854f6..00000000 --- a/examples/ad_manager/v201808/inventory_service/get_all_ad_units.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201808') - - # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of ad units at a time, paging - # through until all ad units have been retrieved. - while True: - response = ad_unit_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for ad_unit in response['results']: - # Print out some information for each ad unit. - print('Ad unit with ID "%s" and name "%s" was found.\n' % - (ad_unit['id'], ad_unit['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py deleted file mode 100755 index 87a75e26..00000000 --- a/examples/ad_manager/v201808/inventory_service/get_top_level_ad_units.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 child ad units of the effective root ad unit.""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201808') - inventory_service = client.GetService('InventoryService', version='v201808') - - # Set the parent ad unit's ID for all children ad units to be fetched from. - current_network = network_service.getCurrentNetwork() - parent_ad_unit_id = current_network['effectiveRootAdUnitId'] - - # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('parentId = :parentId') - .OrderBy('id', ascending=True) - .WithBindVariable('parentId', parent_ad_unit_id)) - - # Retrieve a small amount of ad units at a time, paging - # through until all ad units have been retrieved. - while True: - response = inventory_service.getAdUnitsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for ad_unit in response['results']: - # Print out some information for each ad unit. - print('Ad unit with ID "%s" and name "%s" was found.\n' % - (ad_unit['id'], ad_unit['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/inventory_service/update_ad_units.py b/examples/ad_manager/v201808/inventory_service/update_ad_units.py deleted file mode 100755 index 5bdca610..00000000 --- a/examples/ad_manager/v201808/inventory_service/update_ad_units.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates ad unit sizes by adding a banner ad size. - -To determine which ad units exist, run get_all_ad_units.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -# Set the ID of the ad unit to get. -AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' - - -def main(client, ad_unit_id): - # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201808') - - # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', ad_unit_id)) - - # Get ad units by statement. - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - - # Add the size 468x60 to the ad unit. - ad_unit_size = { - 'size': { - 'width': '468', - 'height': '60' - }, - 'environmentType': 'BROWSER' - } - - if 'results' in response and len(response['results']): - updated_ad_units = [] - for ad_unit in response['results']: - if 'adUnitSizes' not in ad_unit: - ad_unit['adUnitSizes'] = [] - ad_unit['adUnitSizes'].append(ad_unit_size) - updated_ad_units.append(ad_unit) - - # Update ad unit on the server. - ad_units = inventory_service.updateAdUnits(updated_ad_units) - - # Display results. - for ad_unit in ad_units: - ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], - size['size']['height']) - for size in ad_unit['adUnitSizes']] - print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' - % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, AD_UNIT_ID) diff --git a/examples/ad_manager/v201808/label_service/__init__.py b/examples/ad_manager/v201808/label_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/label_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/label_service/create_labels.py b/examples/ad_manager/v201808/label_service/create_labels.py deleted file mode 100755 index a794881f..00000000 --- a/examples/ad_manager/v201808/label_service/create_labels.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new labels. - -To determine which labels exist, run get_all_labels.py. This feature is only -available to Ad Manager 360 solution networks. -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201808') - - # Create label objects. - labels = [] - for _ in xrange(5): - label = { - 'name': 'Label #%s' % uuid.uuid4(), - 'isActive': 'true', - 'types': ['COMPETITIVE_EXCLUSION'] - } - labels.append(label) - - # Add Labels. - labels = label_service.createLabels(labels) - - # Display results. - for label in labels: - print ('Label with id "%s", name "%s", and types {%s} was found.' - % (label['id'], label['name'], ','.join(label['types']))) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/label_service/deactivate_labels.py b/examples/ad_manager/v201808/label_service/deactivate_labels.py deleted file mode 100755 index 70d7be9e..00000000 --- a/examples/ad_manager/v201808/label_service/deactivate_labels.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example deactivates all active Labels. - -To determine which labels exist, run get_all_labels.py. This feature is only -available to Ad Manager 360 solution networks. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('isActive = :isActive') - .WithBindVariable('isActive', True)) - - labels_deactivated = 0 - - # Get labels by statement. - while True: - response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for label in response['results']: - print ('Label with id "%s" and name "%s" will be ' - 'deactivated.' % (label['id'], label['name'])) - # Perform action. - result = label_service.performLabelAction( - {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - labels_deactivated += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if labels_deactivated > 0: - print 'Number of labels deactivated: %s' % labels_deactivated - else: - print 'No labels were deactivated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/label_service/get_active_labels.py b/examples/ad_manager/v201808/label_service/get_active_labels.py deleted file mode 100755 index 39065efc..00000000 --- a/examples/ad_manager/v201808/label_service/get_active_labels.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active labels. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201808') - # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('isActive = :isActive') - .WithBindVariable('isActive', True)) - - # Retrieve a small amount of labels at a time, paging - # through until all labels have been retrieved. - while True: - response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for label in response['results']: - # Print out some information for each label. - print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], - label['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/label_service/get_all_labels.py b/examples/ad_manager/v201808/label_service/get_all_labels.py deleted file mode 100755 index a1feeb2f..00000000 --- a/examples/ad_manager/v201808/label_service/get_all_labels.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 labels. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201808') - - # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of labels at a time, paging - # through until all labels have been retrieved. - while True: - response = label_service.getLabelsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for label in response['results']: - # Print out some information for each label. - print('Label with ID "%d" and name "%s" was found.\n' % (label['id'], - label['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/label_service/update_labels.py b/examples/ad_manager/v201808/label_service/update_labels.py deleted file mode 100755 index fdf33d9c..00000000 --- a/examples/ad_manager/v201808/label_service/update_labels.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates the description of a single label. - -To determine which labels exist, run get_all_labels.py. This feature is only -available to Ad Manager 360 solution networks. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -LABEL_ID = 'INSERT_LABEL_ID_HERE' - - -def main(client, label_id): - # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201808') - - # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :labelId') - .WithBindVariable('labelId', long(label_id))) - - # Get labels by filter. - response = label_service.getLabelsByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local label object by changing the description. - updated_labels = [] - for label in response['results']: - label['description'] = 'These labels are updated.' - updated_labels.append(label) - - # Update labels remotely. - labels = label_service.updateLabels(updated_labels) - - for label in labels: - print ('Label with id "%s" and name "%s" was updated.' - % (label['id'], label['name'])) - else: - print 'No labels found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LABEL_ID) - diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201808/line_item_creative_association_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/line_item_creative_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/create_licas.py deleted file mode 100755 index eb5f3566..00000000 --- a/examples/ad_manager/v201808/line_item_creative_association_service/create_licas.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new line item creative associations (LICAs) for an -existing line item and a set of creative ids. - -To determine which LICAs exist, run get_all_licas.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the line item ID and creative IDs to associate. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' -CREATIVE_IDS = ['INSERT_CREATIVE_IDS_HERE'] - - -def main(client, line_item_id, creative_ids): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201808') - - licas = [] - for creative_id in creative_ids: - licas.append({'creativeId': creative_id, - 'lineItemId': line_item_id}) - - # Create the LICAs remotely. - licas = lica_service.createLineItemCreativeAssociations(licas) - - # Display results. - if licas: - for lica in licas: - print ('LICA with line item id "%s", creative id "%s", and ' - 'status "%s" was created.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) - else: - print 'No LICAs created.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LINE_ITEM_ID, CREATIVE_IDS) diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py deleted file mode 100755 index c2f4f3e2..00000000 --- a/examples/ad_manager/v201808/line_item_creative_association_service/deactivate_licas.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example deactivates all LICAs for the line item. - -To determine which LICAs exist, run get_all_licas.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the id of the line item in which to deactivate LICAs. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, line_item_id): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('lineItemId = :lineItemId AND status = :status') - .WithBindVariable('status', 'ACTIVE') - .WithBindVariable('lineItemId', long(line_item_id))) - - num_deactivated_licas = 0 - - # Get LICAs by statement. - while True: - response = lica_service.getLineItemCreativeAssociationsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for lica in response['results']: - print ('LICA with line item id "%s", creative id "%s", and status' - ' "%s" will be deactivated.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) - - # Perform action. - result = lica_service.performLineItemCreativeAssociationAction( - {'xsi_type': 'DeactivateLineItemCreativeAssociations'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - num_deactivated_licas += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if num_deactivated_licas > 0: - print 'Number of LICAs deactivated: %s' % num_deactivated_licas - else: - print 'No LICAs were deactivated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py deleted file mode 100755 index f1acf180..00000000 --- a/examples/ad_manager/v201808/line_item_creative_association_service/get_all_licas.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 line item creative associations. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201808') - - # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of line item creative associations at a time, paging - # through until all line item creative associations have been retrieved. - while True: - response = lica_service.getLineItemCreativeAssociationsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for lica in response['results']: - # Print out some information for each line item creative association. - if 'creativeSetId' in lica: - print('LICA with line item ID "%s", creative set ID "%s", and ' - 'status "%s" was found.' % - (lica['lineItemId'], lica['creativeSetId'], lica['status'])) - else: - print('Line item creative association with line item ID "%d" and ' - 'creative ID "%d" was found.\n' % - (lica['lineItemId'], lica['creativeId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py deleted file mode 100755 index b43fea0d..00000000 --- a/examples/ad_manager/v201808/line_item_creative_association_service/get_licas_for_line_item.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 line item creative associations for a given line item. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client, line_item_id): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201808') - # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('lineItemId = :lineItemId') - .WithBindVariable('lineItemId', line_item_id)) - - # Retrieve a small amount of line item creative associations at a time, paging - # through until all line item creative associations have been retrieved. - while True: - response = lica_service.getLineItemCreativeAssociationsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for lica in response['results']: - # Print out some information for each line item creative association. - if 'creativeSetId' in lica: - print('LICA with line item ID "%s", creative set ID "%s", and ' - 'status "%s" was found.' % - (lica['lineItemId'], lica['creativeSetId'], lica['status'])) - else: - print('Line item creative association with line item ID "%d" and ' - 'creative ID "%d" was found.\n' % - (lica['lineItemId'], lica['creativeId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LINE_ITEM_ID) diff --git a/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py deleted file mode 100755 index 130c80b8..00000000 --- a/examples/ad_manager/v201808/line_item_creative_association_service/update_licas.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates the destination URL of all line item creative -associations (LICA). - -To determine which LICAs exist, run get_all_licas.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201808') - - # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v201808') - - while True: - # Get LICAs by statement. - response = lica_service.getLineItemCreativeAssociationsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local LICA object by changing its destination URL. - updated_licas = [] - for lica in response['results']: - lica['destinationUrl'] = 'http://news.google.com' - updated_licas.append(lica) - - # Update LICAs remotely. - licas = lica_service.updateLineItemCreativeAssociations(updated_licas) - - # Display results. - for lica in licas: - print ('LICA with line item id "%s", creative id "%s", and status ' - '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) - statement.offset += statement.limit - else: - break - - if response['totalResultSetSize'] == 0: - print 'No LICAs found to update.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/line_item_service/__init__.py b/examples/ad_manager/v201808/line_item_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/line_item_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/line_item_service/activate_line_items.py b/examples/ad_manager/v201808/line_item_service/activate_line_items.py deleted file mode 100755 index 6de6be2e..00000000 --- a/examples/ad_manager/v201808/line_item_service/activate_line_items.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example activates all line items for the given order. - -To be activated, line items need to be in the approved state and have at least -one creative associated with them. To approve line items, approve the order to -which they belong by running approve_orders.py. To create LICAs, run -create_licas.py. To determine which line items exist, run -get_all_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the id of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('orderId = :orderId AND status = :status') - .WithBindVariable('status', 'NEEDS_CREATIVES') - .WithBindVariable('orderId', long(order_id))) - - line_items_activated = 0 - - # Get line items by statement. - while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for line_item in response['results']: - print ('Line item with id "%s", belonging to order id "%s", and ' - 'name "%s" will be activated.' % - (line_item['id'], line_item['orderId'], line_item['name'])) - - # Perform action. - result = line_item_service.performLineItemAction( - {'xsi_type': 'ActivateLineItems'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - line_items_activated += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if line_items_activated > 0: - print 'Number of line items activated: %s' % line_items_activated - else: - print 'No line items were activated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID) diff --git a/examples/ad_manager/v201808/line_item_service/create_line_items.py b/examples/ad_manager/v201808/line_item_service/create_line_items.py deleted file mode 100755 index f0a98493..00000000 --- a/examples/ad_manager/v201808/line_item_service/create_line_items.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new line items. - -To determine which line items exist, run get_all_line_items.py. To determine -which orders exist, run get_all_orders.py. To determine which placements exist, -run get_all_placements.py. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set order that the created line item will belong to and add the id of a -# placement containing ad units to target. -ORDER_ID = 'INSERT_ORDER_ID_HERE' -TARGETED_PLACEMENT_IDS = ['INSERT_PLACEMENT_IDS_HERE'] - - -def main(client, order_id, targeted_placement_ids): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - - end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime += datetime.timedelta(days=365) - - # Create line item objects. - line_items = [] - for _ in xrange(5): - line_item = { - 'name': 'Line item #%s' % uuid.uuid4(), - 'orderId': order_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedPlacementIds': targeted_placement_ids - }, - 'geoTargeting': { - 'targetedLocations': [ - { - 'id': '2840', - 'displayName': 'US' - }, - { - 'id': '20133', - 'displayName': 'Geneva' - }, - { - 'id': '9000093', - 'displayName': 'B3P', - } - ], - 'excludedLocations': [ - { - 'id': '1016367', - 'displayName': 'Chicago', - }, - { - 'id': '200501', - 'displayName': 'New York NY' - } - ] - }, - 'dayPartTargeting': { - 'dayParts': [ - { - 'dayOfWeek': 'SATURDAY', - 'startTime': { - 'hour': '0', - 'minute': 'ZERO' - }, - 'endTime': { - 'hour': '24', - 'minute': 'ZERO' - } - }, - { - 'dayOfWeek': 'SUNDAY', - 'startTime': { - 'hour': '0', - 'minute': 'ZERO' - }, - 'endTime': { - 'hour': '24', - 'minute': 'ZERO' - } - } - ], - 'timeZone': 'BROWSER' - }, - 'userDomainTargeting': { - 'domains': ['usa.gov'], - 'targeted': 'false' - }, - 'technologyTargeting': { - 'browserTargeting': { - 'browsers': [{'id': '500072'}], - 'isTargeted': 'true' - } - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '300', - 'height': '250' - } - }, - { - 'size': { - 'width': '120', - 'height': '600' - } - } - ], - 'startDateTimeType': 'IMMEDIATELY', - 'lineItemType': 'STANDARD', - 'endDateTime': end_datetime, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'LIFETIME' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'EVEN', - 'discountType': 'PERCENTAGE', - 'allowOverbook': 'true' - } - line_items.append(line_item) - - # Add line items. - line_items = line_item_service.createLineItems(line_items) - - # Display results. - for line_item in line_items: - print ('Line item with id "%s", belonging to order id "%s", and named ' - '"%s" was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS) - diff --git a/examples/ad_manager/v201808/line_item_service/create_video_line_item.py b/examples/ad_manager/v201808/line_item_service/create_video_line_item.py deleted file mode 100755 index 707e8184..00000000 --- a/examples/ad_manager/v201808/line_item_service/create_video_line_item.py +++ /dev/null @@ -1,135 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates a new line item to serve to video content. - -This feature is only available to Ad Manager 360 solution networks. To determine -which line items exist, run get_all_line_items.py. To determine which orders -exist, run get_all_orders.py. To create a video ad unit, run -create_video_ad_unit.py. To create criteria for categories, run -create_custom_targeting_keys_and_values.py. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set order that all created line item will belong to and the video ad unit id -# to target. -ORDER_ID = 'INSERT_ORDER_ID_HERE' -TARGETED_VIDEO_AD_UNIT_ID = 'INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE' - -# Set the custom targeting value ID representing the metadata -# on the content to target. This would typically be from a key representing -# a "genre" and the value representing something like "comedy". The value -# must be from a key in a content metadata key hierarchy. -CONTENT_CUSTOM_TARGETING_VALUE_ID = ( - 'INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE') - - -def main(client, order_id, targeted_video_ad_unit_id, - content_custom_targeting_value_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - - end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime += datetime.timedelta(days=365) - - # Create line item object. - line_item = { - 'name': 'Line item #%s' % uuid.uuid4(), - 'orderId': order_id, - 'targeting': { - 'contentTargeting': { - 'targetedContentMetadata': [ - {'customTargetingValueIds': [ - content_custom_targeting_value_id]} - ] - }, - 'inventoryTargeting': { - 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id, - 'includeDescendants': 'true'}] - }, - 'videoPositionTargeting': { - 'targetedPositions': [ - { - 'videoPosition': { - 'positionType': 'PREROLL' - } - } - ] - } - }, - 'creativePlaceholders': [ - { - 'size': { - 'width': '400', - 'height': '300' - }, - 'companions': [ - { - 'size': { - 'width': '300', - 'height': '250' - }, - }, - { - 'size': { - 'width': '728', - 'height': '90' - }, - } - ] - } - ], - 'environmentType': 'VIDEO_PLAYER', - 'companionDeliveryOption': 'OPTIONAL', - 'startDateTimeType': 'IMMEDIATELY', - 'lineItemType': 'SPONSORSHIP', - 'endDateTime': end_datetime, - 'costType': 'CPM', - 'costPerUnit': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'primaryGoal': { - 'units': '50', - 'unitType': 'IMPRESSIONS', - 'goalType': 'DAILY' - }, - 'contractedUnitsBought': '100', - 'creativeRotationType': 'OPTIMIZED', - 'discountType': 'PERCENTAGE', - 'allowOverbook': 'true' - } - - # Add line item. - line_item = line_item_service.createLineItem(line_item) - - # Display results. - print ('Video line item with id "%s", belonging to order id "%s", and ' - 'named "%s" was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, - CONTENT_CUSTOM_TARGETING_VALUE_ID) diff --git a/examples/ad_manager/v201808/line_item_service/get_all_line_items.py b/examples/ad_manager/v201808/line_item_service/get_all_line_items.py deleted file mode 100755 index 7699daa1..00000000 --- a/examples/ad_manager/v201808/line_item_service/get_all_line_items.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 line items. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - - # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of line items at a time, paging - # through until all line items have been retrieved. - while True: - response = line_item_service.getLineItemsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for line_item in response['results']: - # Print out some information for each line item. - print('Line item with ID "%d" and name "%s" was found.\n' % - (line_item['id'], line_item['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py deleted file mode 100755 index 8dc1c1fb..00000000 --- a/examples/ad_manager/v201808/line_item_service/get_line_items_that_need_creatives.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 line items that are missing creatives. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('isMissingCreatives = :isMissingCreatives') - .WithBindVariable('isMissingCreatives', True)) - - # Retrieve a small amount of line items at a time, paging - # through until all line items have been retrieved. - while True: - response = line_item_service.getLineItemsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for line_item in response['results']: - # Print out some information for each line item. - print('Line item with ID "%d" and name "%s" was found.\n' % - (line_item['id'], line_item['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py deleted file mode 100755 index d2e664b9..00000000 --- a/examples/ad_manager/v201808/line_item_service/get_recently_updated_line_items.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 only recently updated line items. -""" - -# Import appropriate modules from the client library. -from datetime import datetime -from datetime import timedelta - -from googleads import ad_manager -import pytz - - -def main(client): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - - last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - - timedelta(days=1)) - - # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('lastModifiedDateTime >= :lastModifiedDateTime') - .WithBindVariable('lastModifiedDateTime', last_modified)) - - # Retrieve a small amount of line items at a time, paging - # through until all line items have been retrieved. - while True: - response = line_item_service.getLineItemsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for line_item in response['results']: - # Print out some information for each line item. - print('Line item with ID "%d" and name "%s" was found.\n' % - (line_item['id'], line_item['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/line_item_service/pause_line_items.py b/examples/ad_manager/v201808/line_item_service/pause_line_items.py deleted file mode 100755 index 5a5a3873..00000000 --- a/examples/ad_manager/v201808/line_item_service/pause_line_items.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 pauses a line item. - -Line items must be paused before they can be updated. To determine which line -items exist, run get_all_line_items.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the line item to pause. -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' - - -def main(client): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - - # Create a statement to select the line item. - # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', LINE_ITEM_ID)) - - result_set_size = 0 - should_continue = True - - # Iterate over paged results from the statement. - while should_continue: - page = line_item_service.getLineItemsByStatement(statement.ToStatement()) - if 'results' in page and len(page['results']): - result_set_size = page['totalResultSetSize'] - # Iterate over individual results in the page. - for line_item in page['results']: - print 'Pausing line item with ID %d' % line_item['id'] - # Update statement for next page. - statement.offset += statement.limit - should_continue = statement.offset < result_set_size - - print 'Pausing %d line item(s)' % result_set_size - - if result_set_size > 0: - statement.offset = None - statement.limit = None - - # Perform Pause action on all Line Items that match the statement. - update_result = line_item_service.performLineItemAction( - {'xsi_type': 'PauseLineItems'}, statement.ToStatement()) - - if update_result and update_result['numChanges'] > 0: - print 'Updated %d line item(s)' % update_result['numChanges'] - else: - print 'No line items were paused' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py deleted file mode 100755 index c9628e41..00000000 --- a/examples/ad_manager/v201808/line_item_service/target_custom_criteria.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a line item to add custom criteria targeting. - -To determine which line items exist, run get_all_line_items.py. To determine -which custom targeting keys and values exist, run -get_all_custom_targeting_keys_and_values.py. -""" - - -import pprint - -# Import appropriate modules from the client library. -from googleads import ad_manager - -LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' -KEY_ID1 = 'INSERT_TARGETING_KEY_ID_HERE' -KEY_ID2 = 'INSERT_TARGETING_KEY_ID_HERE' -KEY_ID3 = 'INSERT_TARGETING_KEY_ID_HERE' - -VALUE_ID1 = 'INSERT_TARGETING_VALUE_ID_HERE' -VALUE_ID2 = 'INSERT_TARGETING_VALUE_ID_HERE' -VALUE_ID3 = 'INSERT_TARGETING_VALUE_ID_HERE' - - -def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, - value_id3): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - - # create custom criterias - custom_criteria1 = { - 'xsi_type': 'CustomCriteria', - 'keyId': key_id1, - 'valueIds': [value_id1], - 'operator': 'IS' - } - - custom_criteria2 = { - 'xsi_type': 'CustomCriteria', - 'keyId': key_id2, - 'valueIds': [value_id2], - 'operator': 'IS_NOT' - } - - custom_criteria3 = { - 'xsi_type': 'CustomCriteria', - 'keyId': key_id3, - 'valueIds': [value_id3], - 'operator': 'IS' - } - - # Create the custom criteria set that will resemble: - # (custom_criteria1.key == custom_criteria1.value OR - # (custom_criteria2.key != custom_criteria2.value AND - # custom_criteria13.key == custom_criteria3.value)) - sub_set = { - 'xsi_type': 'CustomCriteriaSet', - 'logicalOperator': 'AND', - 'children': [custom_criteria2, custom_criteria3] - } - - top_set = { - 'xsi_type': 'CustomCriteriaSet', - 'logicalOperator': 'OR', - 'children': [custom_criteria1, sub_set] - } - - # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :lineItemId') - .WithBindVariable('lineItemId', long(line_item_id)) - .Limit(1)) - - # Set custom criteria targeting on the line item. - line_item = line_item_service.getLineItemsByStatement( - statement.ToStatement())['results'][0] - line_item['targeting']['customTargeting'] = top_set - - # Update line item. - line_item = line_item_service.updateLineItems([line_item])[0] - - # Display results. - if line_item: - print ('Line item with id "%s" updated with custom criteria targeting:' - % line_item['id']) - pprint.pprint(line_item['targeting']['customTargeting']) - else: - print 'No line items were updated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LINE_ITEM_ID, KEY_ID1, KEY_ID2, KEY_ID3, VALUE_ID1, - VALUE_ID2, VALUE_ID3) diff --git a/examples/ad_manager/v201808/line_item_service/update_line_items.py b/examples/ad_manager/v201808/line_item_service/update_line_items.py deleted file mode 100755 index 54cd59ff..00000000 --- a/examples/ad_manager/v201808/line_item_service/update_line_items.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates the delivery rate of all line items in an order. - -To determine which line items exist, run get_all_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set id of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - - # Create statement object to only select line items with even delivery rates. - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('deliveryRateType = :deliveryRateType AND ' - 'orderId = :orderId')) - .WithBindVariable('orderId', long(order_id)) - .WithBindVariable('deliveryRateType', 'EVENLY') - .Limit(500)) - - # Get line items by statement. - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local line item by changing its delivery rate type. - updated_line_items = [] - for line_item in response['results']: - if not line_item['isArchived']: - line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE' - updated_line_items.append(line_item) - - # Update line items remotely. - line_items = line_item_service.updateLineItems(updated_line_items) - - # Display results. - if line_items: - for line_item in line_items: - print ('Line item with id "%s", belonging to order id "%s", named ' - '"%s", and delivery rate "%s" was updated.' - % (line_item['id'], line_item['orderId'], line_item['name'], - line_item['deliveryRateType'])) - else: - print 'No line items were updated.' - else: - print 'No line items found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID) diff --git a/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py deleted file mode 100755 index f2d72c71..00000000 --- a/examples/ad_manager/v201808/live_stream_event_service/activate_live_stream_events.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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 code example activates paused live stream events.""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the id of the LiveStreamEvent to get live stream events from. -LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' - - -def main(client, live_stream_event_id): - # Initialize appropriate service. - live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201808') - - # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('id = :id AND ' - 'status = :status')) - .WithBindVariable('status', 'PAUSED') - .WithBindVariable('id', long(live_stream_event_id)) - .Limit(500)) - - live_stream_events_activated = 0 - - # Get live stream events by statement. - while True: - response = live_stream_event_service.getLiveStreamEventsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for live_stream_event in response['results']: - print('live stream event with id "%s" and name "%s" will be activated.' - % (live_stream_event['id'], live_stream_event['name'])) - - # Perform action. - result = live_stream_event_service.performLiveStreamEventAction({ - 'xsi_type': 'ActivateLiveStreamEvents' - }, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - live_stream_events_activated += int(result['numChanges']) - statement.offset += ad_manager.SUGGESTED_PAGE_LIMIT - else: - break - - # Display results. - if live_stream_events_activated > 0: - print '# of live stream events activated: %s' % ( - live_stream_events_activated) - else: - print 'No live stream events were activated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/ad_manager/v201808/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/create_live_stream_events.py deleted file mode 100755 index 1f6a04e8..00000000 --- a/examples/ad_manager/v201808/live_stream_event_service/create_live_stream_events.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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 code example creates new live stream events. - -To determine which live stream events exist, run get_all_live_stream_events.py. -To determine which cdn configurations exist, run get_cdn_configurations.py. -""" - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set content urls and adTags to use -CONTENT_URLS = ['INSERT_CONTENT_URLS_HERE'] -AD_TAGS = ['INSERT_AD_TAGS_HERE'] - - -def main(client, content_urls, ad_tags): - # Initialize appropriate services. - live_events_service = client.GetService( - 'LiveStreamEventService', version='v201808') - - # Stream will play for 365 days - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Create live stream event objects - live_stream_events = [{ - 'name': 'Live Stream Event #%s' % uuid.uuid4(), - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'contentUrls': content_urls, - 'adTags': ad_tags - }] - - # Add live stream events. - live_stream_events = live_events_service.createLiveStreamEvents( - live_stream_events) - - # Display results. - for live_stream_event in live_stream_events: - print( - 'Live stream event with id "%s", named "%s" and status %s was created.' - % (live_stream_event['id'], live_stream_event['name'], - live_stream_event['status'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CONTENT_URLS, AD_TAGS) diff --git a/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py deleted file mode 100755 index 1954ca37..00000000 --- a/examples/ad_manager/v201808/live_stream_event_service/get_all_live_stream_events.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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 live stream events. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201808') - - # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of live stream events at a time, paging - # through until all live stream events have been retrieved. - while True: - response = live_stream_event_service.getLiveStreamEventsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for live_stream_event in response['results']: - # Print out some information for each live stream event. - print('live stream event with id "%d" and name "%s" was found.' % - (live_stream_event['id'], live_stream_event['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201808/live_stream_event_service/register_sessions_for_monitoring.py deleted file mode 100755 index e3e8ce37..00000000 --- a/examples/ad_manager/v201808/live_stream_event_service/register_sessions_for_monitoring.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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 registers all live stream event-sessions ids for monitoring.""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# List of session ids -SESSION_IDS = ['INSERT_SESSION_IDS_HERE'] - - -def main(client, session_ids): - # Initialize appropriate service. - live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201808') - - # Retrieve all sessions id that are being monitored - session_ids = live_stream_event_service.registerSessionsForMonitoring( - session_ids) - if session_ids: - for session_id in session_ids: - # Print out some information for each live stream event. - print 'Session with ID "%s" registered for monitoring.' % (session_id) - - print '\nNumber of results found: %s' % session_ids.size - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, SESSION_IDS) diff --git a/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py deleted file mode 100755 index 34e48cc5..00000000 --- a/examples/ad_manager/v201808/live_stream_event_service/update_live_stream_events.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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 code example updates live stream events. - -To determine which live stream events exist, run get_all_live_stream_events.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set ID of the LiveStreamEvent to get live stream events from. -LIVE_STREAM_EVENT_ID = 'INSERT_LIVE_STREAM_EVENT_ID_HERE' - - -def main(client, live_stream_event_id): - # Initialize appropriate services. - live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201808') - - # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('Id = :id')) - .WithBindVariable('id', long(live_stream_event_id)) - .Limit(500)) - - # Get live stream events by statement. - response = live_stream_events_service.getLiveStreamEventsByStatement( - statement.ToStatement()) - - # Set adTags to be updated. - new_ad_tags = ['INSERT_NEW_AD_TAGS_HERE'] - - if 'results' in response and len(response['results']): - # Update each local live stream event by changing its attributes. - updated_live_stream_events = [] - for live_stream_event in response['results']: - live_stream_event['startDateTimeType'] = 'IMMEDIATELY' - live_stream_event['adTags'] = new_ad_tags - updated_live_stream_events.append(live_stream_event) - - # Update live stream events. - live_stream_events = live_stream_events_service.updateLiveStreamEvents( - updated_live_stream_events) - - # Display results. - for live_stream_event in live_stream_events: - print('Live stream event with id "%s", named "%s" and status %s was ' - 'updated.' % (live_stream_event['id'], live_stream_event['name'], - live_stream_event['status'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, LIVE_STREAM_EVENT_ID) diff --git a/examples/ad_manager/v201808/native_style_service/__init__.py b/examples/ad_manager/v201808/native_style_service/__init__.py deleted file mode 100755 index 473ddba1..00000000 --- a/examples/ad_manager/v201808/native_style_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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. diff --git a/examples/ad_manager/v201808/native_style_service/create_native_styles.py b/examples/ad_manager/v201808/native_style_service/create_native_styles.py deleted file mode 100755 index a6d7d891..00000000 --- a/examples/ad_manager/v201808/native_style_service/create_native_styles.py +++ /dev/null @@ -1,180 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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. - -"""Creates a native app install ad.""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -# This is the creative template ID for the system-defined native app install ad -# format, which we will create the native style from. Use -# CreativeTemplateService.getCreativeTemplateByStatement() and -# CreativeTemplate.isNativeEligible() to get other native ad formats available -# in your network. -CREATIVE_TEMPLATE_ID = 10004400 -WIDTH = 300 -HEIGHT = 345 - -HTML_SNIPPET = """
- -
Ad
-
- - - -
-
- -
-
- [%Body%] -
-
[%Price%]
- -
-""" - -CSS_SNIPPET = """body { - background-color: rgba(255, 255, 255, 1); - font-family: "Roboto-Regular", sans-serif; - font-weight: normal; - font-size: 12px; - line-height: 14px; -} -.attribution { - background-color: rgba(236, 182, 0, 1); - color: rgba(255, 255, 255, 1); - font-size: 13px; - display: table; - margin: 4px 8px; - padding: 0 3px; - border-radius: 2px; -} -.image { - text-align: center; - margin: 8px; -} -.image img, -.image-link { - width: 100%; -} -.app-icon { - float: left; - margin: 0 8px 4px 8px; - height: 40px; - width: 40px; - background-color: transparent; -} -.app-icon img { - height: 100%; - width: 100%; - border-radius: 20%; -} -.title, -.promo-headline { - font-weight: bold; - font-size: 14px; - line-height: 20px; - margin: 8px 8px 4px 8px; -} -.title a, -.promo-headline { - color: rgba(112, 112, 112, 1); - text-decoration: none; -} -.reviews { - float: left; -} -.reviews svg { - fill: rgba(0, 0, 0, 0.7); -} -.body { - clear: left; - margin: 8px; -} -.body a { - color: rgba(110, 110, 110, 1); - text-decoration: none; -} -.price { - display: none; -} -.button { - font-size: 14px; - font-weight: bold; - float: right; - margin: 0px 16px 16px 0px; - white-space: nowrap; -} -.button a { - color: #2196F3; - text-decoration: none; -} -.button svg { - display: none; -} -""" - - -def main(client, html_snippet, css_snippet, creative_template_id, width, - height): - # Initialize appropriate service. - native_style_service = client.GetService('NativeStyleService', - version='v201808') - - native_style = { - 'name': 'Native style #%d' % uuid.uuid4(), - 'htmlSnippet': html_snippet, - 'cssSnippet': css_snippet, - 'creativeTemplateId': creative_template_id, - 'size': { - 'width': width, - 'height': height, - 'isAspectRatio': False - } - } - - # Create the native style on the server. - native_styles = native_style_service.createNativeStyles([native_style]) - - # Display results. - for native_style in native_styles: - print ('A Native style with ID "%s", name "%s", and creative template ID' - '"%d" was created.' % (native_style['id'], native_style['name'], - native_style['creativeTemplateId'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, HTML_SNIPPET, CSS_SNIPPET, CREATIVE_TEMPLATE_ID, - WIDTH, HEIGHT) diff --git a/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py deleted file mode 100755 index 3bb2f92b..00000000 --- a/examples/ad_manager/v201808/native_style_service/get_all_native_styles.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 native styles.""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - native_style_service = client.GetService('NativeStyleService', - version='v201808') - - # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of native styles at a time, paging - # through until all native styles have been retrieved. - while True: - response = native_style_service.getNativeStylesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for native_style in response['results']: - # Print out some information for each native style. - print('Native style with ID "%d" and name "%s" was found.\n' % - (native_style['id'], native_style['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/network_service/__init__.py b/examples/ad_manager/v201808/network_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/network_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/network_service/get_all_networks.py b/examples/ad_manager/v201808/network_service/get_all_networks.py deleted file mode 100755 index 5f57da29..00000000 --- a/examples/ad_manager/v201808/network_service/get_all_networks.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 networks. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201808') - - networks = network_service.getAllNetworks() - - # Print out some information for each network. - for network in networks: - print('Network with network code "%s" and display name "%s" was found.' - % (network['networkCode'], network['displayName'])) - - print '\nNumber of results found: %s' % len(networks) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/network_service/get_current_network.py b/examples/ad_manager/v201808/network_service/get_current_network.py deleted file mode 100755 index 7278eb52..00000000 --- a/examples/ad_manager/v201808/network_service/get_current_network.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 the current network.""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201808') - - current_network = network_service.getCurrentNetwork() - - print ("Current network has network code '%s' and display name '%s'." % - (current_network['networkCode'], current_network['displayName'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/network_service/make_test_network.py b/examples/ad_manager/v201808/network_service/make_test_network.py deleted file mode 100755 index 008e7193..00000000 --- a/examples/ad_manager/v201808/network_service/make_test_network.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a test network. - -You do not need to have an Ad Manager account to run this example, but you do -need to have a Google account (created at -http://www.google.com/accounts/newaccount if you currently don't have one) that -is not associated with any other Ad Manager test networks. Once this network is -created, you can supply the network code in your settings to make calls to -other services. - -Alternatively, if you do not wish to run this example, you can create a test -network at: -https://dfp-playground.appspot.com -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201808') - - # Create a test network. - network = network_service.makeTestNetwork() - - # Display results. - print ('Test network with network code "%s" and display name "%s" ' - 'created.' % (network['networkCode'], network['displayName'])) - print ('You may now sign in at ' - 'http://www.google.com/admanager/main?networkCode=%s' - % network['networkCode']) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/order_service/__init__.py b/examples/ad_manager/v201808/order_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/order_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/order_service/approve_orders.py b/examples/ad_manager/v201808/order_service/approve_orders.py deleted file mode 100755 index f1bce5b9..00000000 --- a/examples/ad_manager/v201808/order_service/approve_orders.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example approves all eligible draft and pending orders. - -To determine which orders exist, run get_all_orders.py. -""" - - -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201808') - - # Create a filter statement. - today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' - 'AND endDateTime >= :today AND isArchived = FALSE')) - .WithBindVariable('today', today)) - orders_approved = 0 - - # Get orders by statement. - while True: - response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for order in response['results']: - print ('Order with id "%s", name "%s", and status "%s" will be ' - 'approved.' % (order['id'], order['name'], order['status'])) - # Perform action. - result = order_service.performOrderAction( - {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - orders_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if orders_approved > 0: - print 'Number of orders approved: %s' % orders_approved - else: - print 'No orders were approved.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/order_service/create_orders.py b/examples/ad_manager/v201808/order_service/create_orders.py deleted file mode 100755 index 26203062..00000000 --- a/examples/ad_manager/v201808/order_service/create_orders.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new orders. - -To determine which orders exist, run get_all_orders.py. -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -COMPANY_ID = 'INSERT_ADVERTISER_COMPANY_ID_HERE' -SALESPERSON_ID = 'INSERT_SALESPERSON_ID_HERE' -TRAFFICKER_ID = 'INSERT_TRAFFICKER_ID_HERE' - - -def main(client, company_id, salesperson_id, trafficker_id): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201808') - - # Create order objects. - orders = [] - for _ in xrange(5): - order = { - 'name': 'Order #%s' % uuid.uuid4(), - 'advertiserId': company_id, - 'salespersonId': salesperson_id, - 'traffickerId': trafficker_id - } - orders.append(order) - - # Add orders. - orders = order_service.createOrders(orders) - - # Display results. - for order in orders: - print ('Order with id "%s" and name "%s" was created.' - % (order['id'], order['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, COMPANY_ID, SALESPERSON_ID, TRAFFICKER_ID) diff --git a/examples/ad_manager/v201808/order_service/get_all_orders.py b/examples/ad_manager/v201808/order_service/get_all_orders.py deleted file mode 100755 index 53cc23f5..00000000 --- a/examples/ad_manager/v201808/order_service/get_all_orders.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 orders. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201808') - - # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of orders at a time, paging - # through until all orders have been retrieved. - while True: - response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for order in response['results']: - # Print out some information for each order. - print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], - order['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py deleted file mode 100755 index d6ae2a91..00000000 --- a/examples/ad_manager/v201808/order_service/get_orders_starting_soon.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 orders that are starting soon. -""" - -# Import appropriate modules from the client library. -from datetime import datetime -from datetime import timedelta - -from googleads import ad_manager -import pytz - - -def main(client): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201808') - now = datetime.now(tz=pytz.timezone('America/New_York')) - soon = now + timedelta(days=5) - - # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('status = :status AND startDateTime >= :now ' - 'AND startDateTime <= :soon')) - .WithBindVariable('status', 'APPROVED') - .WithBindVariable('now', now) - .WithBindVariable('soon', soon)) - - # Retrieve a small amount of orders at a time, paging - # through until all orders have been retrieved. - while True: - response = order_service.getOrdersByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for order in response['results']: - # Print out some information for each order. - print('Order with ID "%d" and name "%s" was found.\n' % (order['id'], - order['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/order_service/update_orders.py b/examples/ad_manager/v201808/order_service/update_orders.py deleted file mode 100755 index 1d69813b..00000000 --- a/examples/ad_manager/v201808/order_service/update_orders.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates the notes of a single order specified by ID. - -To determine which orders exist, run get_all_orders.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201808') - - # Create statement object to select a single order by an ID. - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :orderId') - .WithBindVariable('orderId', long(order_id))) - - # Get orders by statement. - response = order_service.getOrdersByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local order object by changing its notes. - updated_orders = [] - for order in response['results']: - # Archived orders cannot be updated. - if not order['isArchived']: - order['notes'] = 'Spoke to advertiser. All is well.' - updated_orders.append(order) - - # Update orders remotely. - orders = order_service.updateOrders(updated_orders) - - # Display results. - if orders: - for order in orders: - print ('Order with id "%s", name "%s", advertiser id "%s", and ' - 'notes "%s" was updated.' - % (order['id'], order['name'], order['advertiserId'], - order['notes'])) - else: - print 'No orders were updated.' - else: - print 'No orders found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID) - diff --git a/examples/ad_manager/v201808/package_service/create_packages.py b/examples/ad_manager/v201808/package_service/create_packages.py deleted file mode 100755 index bcafa5fb..00000000 --- a/examples/ad_manager/v201808/package_service/create_packages.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a package. - -To determine which packages exist, run get_all_packages.py. -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the ID of the product package to create the package from. -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - -# Set the ID of the proposal to create proposal line items under. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the rate card the proposal line items belonging to the product -# package are priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client): - # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201808') - - # Create local package. - package = { - 'name': 'Package #%d' % random.randint(0, 1000000), - 'proposalId': PROPOSAL_ID, - 'productPackageId': PRODUCT_PACKAGE_ID, - 'rateCardId': RATE_CARD_ID, - } - - # Create the package on the server. - result = package_service.createPackages([package]) - - for new_package in result: - print ('A package with ID %d and name "%s" was created' % - (new_package['id'], new_package['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py deleted file mode 100755 index 1c2b4938..00000000 --- a/examples/ad_manager/v201808/package_service/create_proposal_line_items_from_packages.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a copy of an image creative. - -To determine which image creatives exist, run get_image_creatives.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the line item to pause. -PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201808') - - # Create a statement to select the single package. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', PACKAGE_ID)) - - # Get the package. - query_result = package_service.getPackagesByStatement(statement.ToStatement()) - - package = query_result['results'][0] - - print ('Package with ID %d will create proposal line items using product ' - 'package with ID %d.' % (package['id'], - package['productPackageId'])) - - # Remove limit and offset from statement. - statement.limit = None - statement.offset = None - - # Perform update packages action. - result = package_service.performPackageAction( - {'xsi_type': 'CreateProposalLineItemsFromPackages'}, - statement.ToStatement()) - - if result and result['numChanges'] > 0: - print ('Number of packages that proposal line items were created for: %d' % - result['numChanges']) - else: - print 'No proposal line items were created.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/package_service/get_all_packages.py b/examples/ad_manager/v201808/package_service/get_all_packages.py deleted file mode 100755 index bfffe92c..00000000 --- a/examples/ad_manager/v201808/package_service/get_all_packages.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201808') - - # Create a statement to select packages. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of packages at a time, paging - # through until all packages have been retrieved. - while True: - response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for pkg in response['results']: - # Print out some information for each package. - print( - 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' - % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/package_service/get_in_progress_packages.py b/examples/ad_manager/v201808/package_service/get_in_progress_packages.py deleted file mode 100755 index 100a3505..00000000 --- a/examples/ad_manager/v201808/package_service/get_in_progress_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 packages in progress. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201808') - # Create a statement to select packages. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status') - .WithBindVariable('status', 'IN_PROGRESS')) - - # Retrieve a small amount of packages at a time, paging - # through until all packages have been retrieved. - while True: - response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for pkg in response['results']: - # Print out some information for each package. - print( - 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' - % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/placement_service/create_placements.py b/examples/ad_manager/v201808/placement_service/create_placements.py deleted file mode 100755 index d9a16f6e..00000000 --- a/examples/ad_manager/v201808/placement_service/create_placements.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new placements for various ad unit sizes. - -To determine which placements exist, run get_all_placements.py. -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201808') - inventory_service = client.GetService('InventoryService', version='v201808') - - # Create placement object to store medium rectangle ad units. - medium_rectangle_ad_unit_placement = { - 'name': 'Medium rectangle AdUnit Placement #%s' % uuid.uuid4(), - 'description': 'Contains ad units that hold creatives of size 300x250', - 'targetedAdUnitIds': [] - } - - # Create placement object to store skyscraper ad units. - skyscraper_ad_unit_placement = { - 'name': 'Skyscraper AdUnit Placement #%s' % uuid.uuid4(), - 'description': 'Contains ad units that hold creatives of size 120x600', - 'targetedAdUnitIds': [] - } - - # Create placement object to store banner ad units. - banner_ad_unit_placement = { - 'name': 'Banner AdUnit Placement #%s' % uuid.uuid4(), - 'description': 'Contains ad units that hold creatives of size 468x60', - 'targetedAdUnitIds': [] - } - - placement_list = [] - - # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v201808') - - while True: - response = inventory_service.getAdUnitsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Separate the ad units by size. - for ad_unit in response['results']: - if 'adUnitSizes' in ad_unit: - for ad_unit_size in ad_unit['adUnitSizes']: - size = ad_unit_size['size'] - if size['width'] == '300' and size['height'] == '250': - medium_rectangle_ad_unit_placement['targetedAdUnitIds'].append( - ad_unit['id']) - elif size['width'] == '120' and size['height'] == '600': - skyscraper_ad_unit_placement['targetedAdUnitIds'].append( - ad_unit['id']) - elif size['width'] == '468' and size['height'] == '60': - banner_ad_unit_placement['targetedAdUnitIds'].append( - ad_unit['id']) - statement.offset += statement.limit - else: - break - - # Only create placements with one or more ad unit. - if medium_rectangle_ad_unit_placement['targetedAdUnitIds']: - placement_list.append(medium_rectangle_ad_unit_placement) - - if skyscraper_ad_unit_placement['targetedAdUnitIds']: - placement_list.append(skyscraper_ad_unit_placement) - - if banner_ad_unit_placement['targetedAdUnitIds']: - placement_list.append(banner_ad_unit_placement) - - # Add placements. - placements = placement_service.createPlacements(placement_list) - - # Display results. - for placement in placements: - ad_unit_ids = '' - if 'targetedAdUnitIds' in placement: - ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) - print ('A Placement with ID "%s", name "%s", and containing ad units ' - '{%s} was created.' % (placement['id'], placement['name'], - ad_unit_ids)) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/placement_service/deactivate_placements.py b/examples/ad_manager/v201808/placement_service/deactivate_placements.py deleted file mode 100755 index 74feabd3..00000000 --- a/examples/ad_manager/v201808/placement_service/deactivate_placements.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example deactivates all active placements. - -To determine which placements exist, run get_all_placements.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' - - -def main(client, placement_id): - # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :placementId') - .WithBindVariable('placementId', long(placement_id)) - .Limit(1)) - - # Get placements by statement. - placements = placement_service.getPlacementsByStatement( - statement.ToStatement()) - - for placement in placements: - print ('Placement with id "%s", name "%s", and status "%s" will be ' - 'deactivated.' % (placement['id'], placement['name'], - placement['status'])) - - # Perform action. - result = placement_service.performPlacementAction( - {'xsi_type': 'DeactivatePlacements'}, statement.ToStatement()) - - # Display results. - if result and int(result['numChanges']) > 0: - print 'Number of placements deactivated: %s' % result['numChanges'] - else: - print 'No placements were deactivated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/ad_manager/v201808/placement_service/get_active_placements.py b/examples/ad_manager/v201808/placement_service/get_active_placements.py deleted file mode 100755 index 1d5dea47..00000000 --- a/examples/ad_manager/v201808/placement_service/get_active_placements.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active placements. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201808') - # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status') - .WithBindVariable('status', 'ACTIVE')) - - # Retrieve a small amount of placements at a time, paging - # through until all placements have been retrieved. - while True: - response = placement_service.getPlacementsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for placement in response['results']: - # Print out some information for each placement. - print('Placement with ID "%d" and name "%s" was found.\n' % - (placement['id'], placement['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/placement_service/get_all_placements.py b/examples/ad_manager/v201808/placement_service/get_all_placements.py deleted file mode 100755 index 908d1924..00000000 --- a/examples/ad_manager/v201808/placement_service/get_all_placements.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 placements. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201808') - - # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of placements at a time, paging - # through until all placements have been retrieved. - while True: - response = placement_service.getPlacementsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for placement in response['results']: - # Print out some information for each placement. - print('Placement with ID "%d" and name "%s" was found.\n' % - (placement['id'], placement['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/placement_service/update_placements.py b/examples/ad_manager/v201808/placement_service/update_placements.py deleted file mode 100755 index 4768ba9e..00000000 --- a/examples/ad_manager/v201808/placement_service/update_placements.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates a single placement to allow for AdSense targeting. - -To determine which placements exist, run get_all_placements.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PLACEMENT_ID = 'INSERT_PLACEMENT_ID_HERE' - - -def main(client, placement_id): - # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', placement_id)) - - # Get placements by statement. - page = placement_service.getPlacementsByStatement( - statement.ToStatement()) - - placement = page['results'][0] - - placement['description'] = 'This placement contains all leaderboards.' - - # Update placements remotely. - updated_placements = placement_service.updatePlacements([placement]) - - for placement in updated_placements: - print ('Placement with id "%s" and name "%s" was updated.' - % (placement['id'], placement['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PLACEMENT_ID) diff --git a/examples/ad_manager/v201808/premium_rate_service/__init__.py b/examples/ad_manager/v201808/premium_rate_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/premium_rate_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201808/premium_rate_service/create_premium_rates.py deleted file mode 100755 index 69b506ed..00000000 --- a/examples/ad_manager/v201808/premium_rate_service/create_premium_rates.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new premium_rates. - -To determine which premium_rates exist, run get_all_premium_rates.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate services. - premium_rate_service = client.GetService('PremiumRateService', - version='v201808') - - # Create an ad unit premium to apply to the rate card. - ad_unit_premium_feature = { - 'xsi_type': 'AdUnitPremiumFeature' - } - - # Create a CPC based premium rate value with adjustments in milli amounts. - # This will adjust a CPC priced proposal line item that has - # inventory targeting specified by 10% of the cost associated with the rate - # card (this comes from a percentage adjustment). - cpc_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPC', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Create a CPM based premium rate value with adjustments in micro amounts. - # This will adjust a CPM priced proposal line item that has - # inventory targeting specified by 2 units of the currency associated with - # the rate card (this comes from absolute value adjustment). - cpm_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPM', - 'adjustmentSize': 2000000, - 'adjustmentType': 'ABSOLUTE_VALUE' - } - - # Create premium rate. - # Associate premium rate with the rate card and set premium information. - # This premium will apply for proposal line items targeting 'any' ad unit - # for both CPM and CPC rate types. - premium_rate = { - 'rateCardId': rate_card_id, - 'pricingMethod': 'ANY_VALUE', - 'premiumFeature': ad_unit_premium_feature, - 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value] - } - - # Add premium_rates. - premium_rates = premium_rate_service.createPremiumRates([premium_rate]) - - # Display results. - for premium_rate in premium_rates: - print ('A premium rate for "%s" was added to the rate card with ID' - ' of "%s".\n' - % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), - premium_rate['id'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py deleted file mode 100755 index 6afd5635..00000000 --- a/examples/ad_manager/v201808/premium_rate_service/get_all_premium_rates.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 premium rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - premium_rate_service = client.GetService( - 'PremiumRateService', version='v201808') - - # Create a statement to select premium rates. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of premium rates at a time, paging - # through until all premium rates have been retrieved. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for premium_rate in response['results']: - # Print out some information for each premium rate. - print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'id "%d" was found.\n' % ( - premium_rate['id'], - ad_manager.AdManagerClassType(premium_rate), - premium_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py deleted file mode 100755 index 2068c033..00000000 --- a/examples/ad_manager/v201808/premium_rate_service/get_premium_rates_for_rate_card.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 premium rates on a specific rate card. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - premium_rate_service = client.GetService( - 'PremiumRateService', version='v201808') - # Create a statement to select premium rates. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('rateCardId = :rateCardId') - .WithBindVariable('rateCardId', rate_card_id)) - - # Retrieve a small amount of premium rates at a time, paging - # through until all premium rates have been retrieved. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for premium_rate in response['results']: - # Print out some information for each premium rate. - print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'ID "%d" was found.\n' % (premium_rate['id'], - premium_rate['premium feature'], - premium_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py deleted file mode 100755 index a3efb98f..00000000 --- a/examples/ad_manager/v201808/premium_rate_service/update_premium_rates.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a premium rate to add a flat fee to an existing feature. - -To determine which premium rates exist, run get_all_premium_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' - - -def main(client, premium_rate_id): - # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201808') - - # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(premium_rate_id)) - .Limit(1)) - - # Get the premium rate. - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_premium_rates = [] - for premium_rate in response['results']: - # Create a flat fee based premium rate value with a 10% increase. - new_flat_fee_rate = { - 'premiumFeature': premium_rate['premiumFeature'], - 'rateType': 'CPM', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Update the premium rate's premiumRateValues to include a flat fee - # premium rate. - - existing_premium_rate_value = ( - [] if 'premiumRateValues' not in premium_rate else - premium_rate['premiumRateValues']) - existing_premium_rate_value.append(new_flat_fee_rate) - premium_rate['premiumRateValues'] = existing_premium_rate_value - - updated_premium_rates.append(premium_rate) - - # Update products remotely. - premium_rates = premium_rate_service.updatePremiumRates( - updated_premium_rates) - - # Display results. - if premium_rates: - for premium_rate in premium_rates: - print ('Premium rate with ID "%s", associated with rate card id' - ' "%s" was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) - else: - print 'No premium rates were updated.' - else: - print 'No premium rates found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PREMIUM_RATE_ID) diff --git a/examples/ad_manager/v201808/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201808/product_package_item_service/create_product_package_item.py deleted file mode 100755 index e4a2b424..00000000 --- a/examples/ad_manager/v201808/product_package_item_service/create_product_package_item.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package item. - -To determine which product package items exist, run -get_all_product_package_items.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the product package to add product package items to. -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - -# Set the ID of the product to generate a product package item from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client): - product_package_item_service = client.GetService('ProductPackageItemService', - version='v201808') - - product_package_item = { - # Set the product from which the product package item is created. - 'productId': PRODUCT_ID, - # Set the product package that the product package item belongs to. - 'productPackageId': PRODUCT_PACKAGE_ID, - # Specify if the product package item is required for this - # product package. - 'isMandatory': True - } - - # Create the product package item on the server. - result = product_package_item_service.createProductPackageItems( - [product_package_item]) - - for new_product_package_item in result: - print ('A product package with ID %d created from product ID %d ' - 'belonging to product package with ID %d was created.' % - (new_product_package_item['id'], - new_product_package_item['productId'], - new_product_package_item['productPackageId'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py deleted file mode 100755 index d5d39056..00000000 --- a/examples/ad_manager/v201808/product_package_item_service/get_all_product_package_items.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product package items. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201808') - - # Create a statement to select product package items. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of product package items at a time, paging - # through until all product package items have been retrieved. - while True: - response = product_package_item_service.getProductPackageItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package_item in response['results']: - # Print out some information for each product package item. - print('Product package item with ID "%d", product id "%d", and product ' - 'package id "%d" was found.\n' % - (product_package_item['id'], product_package_item['productId'], - product_package_item['productPackageId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py deleted file mode 100755 index e768b725..00000000 --- a/examples/ad_manager/v201808/product_package_item_service/get_product_package_items_for_product_package.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product package items belonging to a product package. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - - -def main(client, product_package_id): - # Initialize appropriate service. - product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201808') - # Create a statement to select product package items. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('productPackageId = :productPackageId') - .WithBindVariable('productPackageId', product_package_id)) - - # Retrieve a small amount of product package items at a time, paging - # through until all product package items have been retrieved. - while True: - response = product_package_item_service.getProductPackageItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package_item in response['results']: - # Print out some information for each product package item. - print('Product package item with ID "%d", product ID "%d", and product ' - 'package ID "%d" was found.\n' % - (product_package_item['id'], product_package_item['productId'], - product_package_item['productPackageId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_PACKAGE_ID) diff --git a/examples/ad_manager/v201808/product_package_service/create_product_packages.py b/examples/ad_manager/v201808/product_package_service/create_product_packages.py deleted file mode 100755 index 0491c324..00000000 --- a/examples/ad_manager/v201808/product_package_service/create_product_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package. - -To determine which product packages exist, run get_all_product_packages.py -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the ID of the rate card to associate with the product package. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client): - product_package_service = client.GetService('ProductPackageService', - version='v201808') - - # Create a local product package. - product_package = { - 'name': 'Product Package #%d' % random.randint(0, 100000000), - 'rateCardIds': [RATE_CARD_ID] - } - - result = product_package_service.createProductPackages([product_package]) - - for new_product_package in result: - print ('A product package with ID %d and name "%s" was created.' % - (new_product_package['id'], new_product_package['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py deleted file mode 100755 index 24df6745..00000000 --- a/examples/ad_manager/v201808/product_package_service/get_active_product_packages.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active product packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_service = client.GetService( - 'ProductPackageService', version='v201808') - # Create a statement to select product packages. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status') - .WithBindVariable('status', 'ACTIVE')) - - # Retrieve a small amount of product packages at a time, paging - # through until all product packages have been retrieved. - while True: - response = product_package_service.getProductPackagesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package in response['results']: - # Print out some information for each product package. - print('Product package with ID "%d" and name "%s" was found.\n' % - (product_package['id'], product_package['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py deleted file mode 100755 index 333087ed..00000000 --- a/examples/ad_manager/v201808/product_package_service/get_all_product_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_service = client.GetService( - 'ProductPackageService', version='v201808') - - # Create a statement to select product packages. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of product packages at a time, paging - # through until all product packages have been retrieved. - while True: - response = product_package_service.getProductPackagesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package in response['results']: - # Print out some information for each product package. - print('Product package with ID "%d" and name "%s" was found.\n' % - (product_package['id'], product_package['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_service/__init__.py b/examples/ad_manager/v201808/product_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/product_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/product_service/get_all_products.py b/examples/ad_manager/v201808/product_service/get_all_products.py deleted file mode 100755 index 329dc856..00000000 --- a/examples/ad_manager/v201808/product_service/get_all_products.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 products. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201808') - - # Create a statement to select products. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of products at a time, paging - # through until all products have been retrieved. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for product in response['results']: - # Print out some information for each product. - print('Product with ID "%d" and name "%s" was found.\n' % - (product['id'], product['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_service/get_products_for_product_template.py b/examples/ad_manager/v201808/product_service/get_products_for_product_template.py deleted file mode 100755 index 51160ca4..00000000 --- a/examples/ad_manager/v201808/product_service/get_products_for_product_template.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 products created from a product template. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201808') - - # Create a statement to select products. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('productTemplateId = :productTemplateId') - .WithBindVariable('productTemplateId', product_template_id)) - - # Retrieve a small amount of products at a time, paging - # through until all products have been retrieved. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for product in response['results']: - # Print out some information for each product. - print('Product with ID "%d" and name "%s" was found.\n' % - (product['id'], product['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201808/product_service/update_products.py b/examples/ad_manager/v201808/product_service/update_products.py deleted file mode 100755 index 93471235..00000000 --- a/examples/ad_manager/v201808/product_service/update_products.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a product's notes. - -To determine which products exist, run get_all_products.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201808') - - # Create statement object to select a single product by an ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', long(product_id)) - .Limit(1)) - - # Get products by statement. - response = product_service.getProductsByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local product object by changing its notes. - updated_products = [] - for product in response['results']: - product['notes'] = 'Product needs further review before activation.' - updated_products.append(product) - - # Update products remotely. - products = product_service.updateProducts(updated_products) - - # Display results. - if products: - for product in products: - print ('Product with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (product['id'], product['name'], product['notes'])) - else: - print 'No products were updated.' - else: - print 'No products found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_ID) diff --git a/examples/ad_manager/v201808/product_template_service/__init__.py b/examples/ad_manager/v201808/product_template_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/product_template_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/product_template_service/activate_product_templates.py b/examples/ad_manager/v201808/product_template_service/activate_product_templates.py deleted file mode 100755 index 2d649f69..00000000 --- a/examples/ad_manager/v201808/product_template_service/activate_product_templates.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example activates a product template. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the id of the product template to activate. -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', long(product_template_id)) - .Limit(1)) - - product_templates_activated = 0 - - # Get product_templates by statement. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - print ('Product template with id "%s" and name "%s" will be ' - 'activated.' % (product_template['id'], - product_template['name'])) - - # Perform action. - result = product_template_service.performProductTemplateAction( - {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - product_templates_activated += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if product_templates_activated > 0: - print ('Number of product templates ' - 'activated: %s' % product_templates_activated) - else: - print 'No product templates were activated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201808/product_template_service/create_product_templates.py b/examples/ad_manager/v201808/product_template_service/create_product_templates.py deleted file mode 100755 index 8865e0b3..00000000 --- a/examples/ad_manager/v201808/product_template_service/create_product_templates.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product template. - -To determine which product templates exist, run get_all_product_templates.py. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201808') - network_service = client.GetService( - 'NetworkService', version='v201808') - - # Create a product template. - product_template = { - 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard proposal line ' - 'items targeting Chrome browsers with product ' - 'segmentation on ad units and geo targeting.'), - 'nameMacro': (' - - ' - ' - '), - 'productType': 'DFP', - 'rateType': 'CPM', - 'roadblockingType': 'ONE_OR_MORE', - 'deliveryRateType': 'AS_FAST_AS_POSSIBLE', - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'lineItemType': 'STANDARD', - 'customizableAttributes': { - 'allowPlacementTargetingCustomization': True, - }, - 'builtInTargeting': { - 'technologyTargeting': { - # Set browser targeting to Chrome. - 'browserTargeting': { - { - 'browsers': [ - { - 'id': '500072' - } - ] - } - } - } - }, - 'productSegmentation': { - 'geoSegment': { - 'targetedLocations': [ - {'id': '2840', - 'displayName': 'US'}, - {'id': '2344', - 'displayName': 'Hong Kong'} - ] - }, - 'adUnitSegments': [{ - 'adUnitId': (network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId']), - 'includeDescendants': 'true' - }] - } - } - - # Create product templates on the server. - product_templates = product_template_service.createProductTemplates( - [product_template]) - - if product_templates: - for product_template in product_templates: - print ('A product template with ID "%s" and name "%s" was ' - 'created.' % (product_template['id'], product_template['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201808/product_template_service/create_programmatic_product_templates.py deleted file mode 100755 index d32ccab3..00000000 --- a/examples/ad_manager/v201808/product_template_service/create_programmatic_product_templates.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product template. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - product_template_service = client.GetService( - 'ProductTemplateService', version='v201808') - network_service = client.GetService( - 'NetworkService', version='v201808') - - product_template = { - # Setting required Marketplace information. - 'productTemplateMarketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for product templates. - 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard programmatic' - 'proposal line items targeting all ad units with' - 'product segmentation on geo targeting.'), - 'nameMacro': (' - - ' - ' - '), - 'productType': 'DFP', - 'rateType': 'CPM', - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'lineItemType': 'STANDARD', - 'productSegmentation': { - 'geoSegment': { - 'targetedLocations': [ - {'id': '2840', - 'displayName': 'US'}, - {'id': '2344', - 'displayName': 'Hong Kong'} - ] - }, - 'adUnitSegments': [{ - 'adUnitId': (network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId']), - 'includeDescendants': 'true' - }] - } - } - - product_templates = product_template_service.createProductTemplates( - [product_template]) - - if product_templates: - for product_template in product_templates: - print ('A programmatic product template with ID "%s" and name "%s" ' - 'was created.' % (product_template['id'], - product_template['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py deleted file mode 100755 index 868e1518..00000000 --- a/examples/ad_manager/v201808/product_template_service/get_all_product_templates.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product templates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201808') - - # Create a statement to select product templates. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of product templates at a time, paging - # through until all product templates have been retrieved. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - # Print out some information for each product template. - print('Product template with ID "%d" and name "%s" was found.\n' % - (product_template['id'], product_template['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py deleted file mode 100755 index 22cfd0c3..00000000 --- a/examples/ad_manager/v201808/product_template_service/get_sponsorship_product_templates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sponsorship product templates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201808') - # Create a statement to select product templates. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('lineItemType = :lineItemType') - .WithBindVariable('lineItemType', 'SPONSORSHIP')) - - # Retrieve a small amount of product templates at a time, paging - # through until all product templates have been retrieved. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - # Print out some information for each product template. - print('Product template with ID "%d" and name "%s" was found.\n' % - (product_template['id'], product_template['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/product_template_service/update_product_templates.py b/examples/ad_manager/v201808/product_template_service/update_product_templates.py deleted file mode 100755 index 990f2f91..00000000 --- a/examples/ad_manager/v201808/product_template_service/update_product_templates.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a product template's GeoTargeting. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201808') - - # Create a statement to select a single product template by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(product_template_id)) - .Limit(1)) - - # Get product templates by statement. - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local product template object by appending a new geo-target. - for product_template in response['results']: - # Create geo-targeting for Canada to append. - location = { - 'id': '2124', - 'displayName': 'Canada' - } - - try: - targeting = product_template['builtInTargeting'] - - if 'geoTargeting' in targeting: - geo_targeting = targeting['geoTargeting'] - - if 'targetedLocations' in geo_targeting: - geo_targeting['targetedLocations'].append(location) - else: - geo_targeting['targetedLocations'] = [location] - else: - targeting['geoTargeting'] = { - 'targetedLocations': [location] - } - except KeyError: - product_template['builtInTargeting'] = { - 'geoTargeting': { - 'targetedLocations': [location] - } - } - - # Update products remotely. - product_templates = product_template_service.updateProductTemplates( - [product_template]) - - # Display results. - if product_templates: - for product_template in product_templates: - print ('Product template with id "%s" and name "%s" was ' - 'updated.' % (product_template['id'], product_template['name'])) - else: - print 'No product templates were updated.' - else: - print 'No product templates found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201808/proposal_line_item_service/__init__.py b/examples/ad_manager/v201808/proposal_line_item_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/proposal_line_item_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py deleted file mode 100755 index 65f353ea..00000000 --- a/examples/ad_manager/v201808/proposal_line_item_service/archive_proposal_line_items.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example archives a proposal line item. - -To determine which proposal line items exist, run -get_all_proposal_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the id of the proposal line item to archive. -PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' - - -def main(client, proposal_line_item_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', long(proposal_line_item_id)) - .Limit(1)) - - proposal_line_items_archived = 0 - - # Get proposal line items by statement. - while True: - response = proposal_line_item_service.getProposalLineItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for proposal_line_item in response['results']: - print ('Proposal line item with id "%s", ' - 'belonging to proposal id "%s", and ' - 'name "%s" will be archived.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - - # Perform action. - result = proposal_line_item_service.performProposalLineItemAction( - {'xsi_type': 'ArchiveProposalLineItems'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - proposal_line_items_archived += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if proposal_line_items_archived > 0: - print ('Number of proposal line items ' - 'archived: %s' % proposal_line_items_archived) - else: - print 'No proposal line items were archived.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items.py deleted file mode 100755 index 0892fc58..00000000 --- a/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a new programmatic proposal line item. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set the ID of the programmatic proposal that the proposal line item will -# belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -# Set the ID of the Marketplace rate card the proposal line items should be -# priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, proposal_id, product_id, rate_card_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201808') - network_service = client.GetService('NetworkService', version='v201808') - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Create a single programmatic proposal line item. - proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for proposal line items. - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'rateCardId': rate_card_id, - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add programmatic proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item with id "%s", belonging to ' - 'proposal id "%s", and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) - diff --git a/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py deleted file mode 100755 index f0728dd9..00000000 --- a/examples/ad_manager/v201808/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a programmatic proposal line item for non-sales management. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set proposal that the created proposal line item will belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, proposal_id, product_id): - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201808') - network_service = client.GetService('NetworkService', version='v201808') - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Create a single programmatic proposal line item. - proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for proposal line items. - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'creativePlaceholders': [{ - 'size': { - 'width': '300', - 'height': '250' - } - }, { - 'size': { - 'width': '120', - 'height': '600' - } - }], - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item for non-sales management with id ' - '"%s", belonging to proposal id "%s", and named "%s" ' - 'was created.' % (proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID) - diff --git a/examples/ad_manager/v201808/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/create_proposal_line_items.py deleted file mode 100755 index 4c479b74..00000000 --- a/examples/ad_manager/v201808/proposal_line_item_service/create_proposal_line_items.py +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates a new run-of-network proposal line item. - -To determine which proposal line items exist, run -get_all_proposal_line_items.py. To determine which proposals exist, run -get_all_proposals.py. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set proposal that the created proposal line item will belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -# Set the ID of the rate card the proposal line items should be priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, proposal_id, product_id, rate_card_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201808') - network_service = client.GetService('NetworkService', version='v201808') - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Create a single proposal line item. - proposal_line_item = { - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'rateCardId': rate_card_id, - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'deliveryRateType': 'EVENLY', - 'creativeRotationType': 'OPTIMIZED', - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'THIRD_PARTY_VOLUME', - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print ('Proposal line item with id "%s", belonging to proposal id "%s"' - ', and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) - diff --git a/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py deleted file mode 100755 index 66d87c8d..00000000 --- a/examples/ad_manager/v201808/proposal_line_item_service/get_all_proposal_line_items.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 proposal line items. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201808') - - # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of proposal line items at a time, paging - # through until all proposal line items have been retrieved. - while True: - response = proposal_line_item_service.getProposalLineItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for proposal_line_item in response['results']: - # Print out some information for each proposal line item. - print('Proposal line item with ID "%d" and name "%s" was found.\n' % - (proposal_line_item['id'], proposal_line_item['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py deleted file mode 100755 index 74bafccf..00000000 --- a/examples/ad_manager/v201808/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 proposal line items belonging to a specific proposal. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201808') - # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('proposalId = :proposalId') - .WithBindVariable('proposalId', proposal_id)) - - # Retrieve a small amount of proposal line items at a time, paging - # through until all proposal line items have been retrieved. - while True: - response = proposal_line_item_service.getProposalLineItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for proposal_line_item in response['results']: - # Print out some information for each proposal line item. - print('Proposal line item with ID "%d" and name "%s" was found.\n' % - (proposal_line_item['id'], proposal_line_item['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py deleted file mode 100755 index 146b20f5..00000000 --- a/examples/ad_manager/v201808/proposal_line_item_service/update_proposal_line_items.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates a proposal line item's notes. - -To determine which proposal line items exist, -run get_all_proposal_line_items.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set id of the proposal line item to update. -PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_ITEM_ID_HERE' - - -def main(client, proposal_line_item_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201808') - - # Create statement to select a proposal line item. - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', long(proposal_line_item_id)) - .Limit(1)) - - # Get proposal line items by statement. - response = proposal_line_item_service.getProposalLineItemsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each the proposal line item's notes field. - proposal_line_item = response['results'][0] - proposal_line_item['internalNotes'] = 'Proposal line is ready to submit.' - - # Update proposal line items remotely. - proposal_line_items = proposal_line_item_service.updateProposalLineItems( - [proposal_line_item]) - - # Display results. - if proposal_line_items: - for proposal_line_item in proposal_line_items: - print ('Line item with id "%s", belonging to proposal id "%s" and,' - ' named "%s" was updated.' % ( - proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - else: - print 'No proposal line items were updated.' - else: - print 'No proposal line items found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_LINE_ITEM_ID) diff --git a/examples/ad_manager/v201808/proposal_service/__init__.py b/examples/ad_manager/v201808/proposal_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/proposal_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals.py deleted file mode 100755 index a913573a..00000000 --- a/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates new programmatic proposals. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' -BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' - - -def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, - buyer_id): - proposal_service = client.GetService('ProposalService', version='v201808') - network_service = client.GetService('NetworkService', version='v201808') - - proposal = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'buyerAccountId': buyer_id - }, - 'isProgrammatic': True, - # Setting required common fields for Proposals. - 'name': 'Proposal #%s' % uuid.uuid4(), - 'advertiser': { - 'companyId': advertiser_id, - 'type': 'ADVERTISER' - }, - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '100000' - }, - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - 'budget': { - 'microAmount': '100000000', - 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] - }, - } - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print('Programmatic proposal with id "%s" and name "%s" was created.' % - (proposal['id'], proposal['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID, BUYER_ID) diff --git a/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals_for_non_sales_management.py deleted file mode 100755 index a7b50ed0..00000000 --- a/examples/ad_manager/v201808/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a programmatic proposal for networks not using sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' - - -def main(client, programmatic_buyer_id, primary_salesperson_id, - primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201808') - - proposal = { - # Setting required Marketplace information. - 'isProgrammatic': 'true', - 'marketplaceInfo': { - 'buyerAccountId': programmatic_buyer_id, - }, - # Set common required fields for proposals. - 'name': 'Proposal #%s' % uuid.uuid4(), - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '100000' - }, - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - } - - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print('Programmatic proposal with id "%s" and name "%s" was created.' % - (proposal['id'], proposal['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201808/proposal_service/create_proposals.py b/examples/ad_manager/v201808/proposal_service/create_proposals.py deleted file mode 100755 index a68b4e30..00000000 --- a/examples/ad_manager/v201808/proposal_service/create_proposals.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new proposals. - -To determine which proposals exist, run get_all_proposals.py. -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' - - -def main(client, advertiser_id, primary_salesperson_id, - secondary_salesperson_id, primary_trafficker_id): - # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201808') - network_service = client.GetService('NetworkService', version='v201808') - - # Create proposal objects. - proposal = { - 'name': 'Proposal #%s' % uuid.uuid4(), - 'advertiser': { - 'companyId': advertiser_id, - 'type': 'ADVERTISER' - }, - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '75000' - }, - 'secondarySalespeople': [{ - 'userId': secondary_salesperson_id, - 'split': '25000' - }], - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - 'budget': { - 'microAmount': '100000000', - 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] - }, - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'DFP_VOLUME' - } - - # Add proposals. - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print ('Proposal with id "%s" and name "%s" was created.' - % (proposal['id'], proposal['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201808/proposal_service/get_all_proposals.py b/examples/ad_manager/v201808/proposal_service/get_all_proposals.py deleted file mode 100755 index 78067812..00000000 --- a/examples/ad_manager/v201808/proposal_service/get_all_proposals.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 proposals. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201808') - - # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of proposals at a time, paging - # through until all proposals have been retrieved. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for proposal in response['results']: - # Print out some information for each proposal. - print('Proposal with ID "%d" and name "%s" was found.\n' % - (proposal['id'], proposal['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201808/proposal_service/get_marketplace_comments.py deleted file mode 100755 index 3dc4943f..00000000 --- a/examples/ad_manager/v201808/proposal_service/get_marketplace_comments.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the Marketplace comments for a programmatic proposal.""" - -# Import appropriate modules from the client library. -from datetime import datetime - -from googleads import ad_manager - - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - marketplace_comment_service = client.GetService( - 'ProposalService', version='v201808') - query = 'WHERE proposalId = %s' % proposal_id - # Create a statement to select marketplace comments. - statement = {'query': query} - - response = marketplace_comment_service.getMarketplaceCommentsByStatement( - statement) - - # Print out some information for each marketplace comment. - for marketplace_comment in response['results']: - date_time = marketplace_comment['creationTime'] - date_time_string = datetime(date_time['date']['year'], - date_time['date']['month'], - date_time['date']['day'], date_time['hour'], - date_time['minute'], - date_time['second']).isoformat() - print('Marketplace comment with creation time "%s"and comment "%s" was ' - 'found.\n' % (date_time_string, marketplace_comment['comment'])) - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py deleted file mode 100755 index 9b7ce9d5..00000000 --- a/examples/ad_manager/v201808/proposal_service/get_proposals_pending_approval.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 proposals pending approval. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201808') - # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('status = :status') - .WithBindVariable('status', 'PENDING_APPROVAL')) - - # Retrieve a small amount of proposals at a time, paging - # through until all proposals have been retrieved. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for proposal in response['results']: - # Print out some information for each proposal. - print('Proposal with ID "%d" and name "%s" was found.\n' % - (proposal['id'], proposal['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py deleted file mode 100755 index b352217e..00000000 --- a/examples/ad_manager/v201808/proposal_service/request_buyers_acceptance.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example requests buyer acceptance for a single proposal. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :proposalId') - .WithBindVariable('proposalId', proposal_id)) - proposals_pushed_to_marketplace = 0 - - # Get proposals by statement. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for proposal in response['results']: - print ('Programmatic proposal with id "%s", name "%s", and status ' - '"%s" will be pushed to Marketplace.' % (proposal['id'], - proposal['name'], - proposal['status'])) - # Perform action. - result = proposal_service.performProposalAction( - {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - proposals_pushed_to_marketplace += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if proposals_pushed_to_marketplace > 0: - print ('\nNumber of programmatic proposals pushed to Marketplace: %s' - % proposals_pushed_to_marketplace) - else: - print '\nNo programmatic proposals were pushed to Marketplace.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py deleted file mode 100755 index 77d4b206..00000000 --- a/examples/ad_manager/v201808/proposal_service/submit_proposals_for_approval.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example approves a single proposal. - -To determine which proposals exist, run get_all_proposals.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :proposalId') - .WithBindVariable('proposalId', proposal_id)) - proposals_approved = 0 - - # Get proposals by statement. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for proposal in response['results']: - print ('Proposal with id "%s", name "%s", and status "%s" will be' - ' approved.' % (proposal['id'], proposal['name'], - proposal['status'])) - # Perform action. - result = proposal_service.performProposalAction( - {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - proposals_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if proposals_approved > 0: - print '\nNumber of proposals approved: %s' % proposals_approved - else: - print '\nNo proposals were approved.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201808/proposal_service/update_proposals.py b/examples/ad_manager/v201808/proposal_service/update_proposals.py deleted file mode 100755 index c4f2cd54..00000000 --- a/examples/ad_manager/v201808/proposal_service/update_proposals.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates the notes of a single proposal specified by ID. - -To determine which proposals exist, run get_all_proposals.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201808') - - # Create statement object to select a single proposal by an ID. - - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :proposalId') - .WithBindVariable('proposalId', long(proposal_id)) - .Limit(1)) - - # Get proposals by statement. - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local proposal object by changing its notes. - updated_proposals = [] - for proposal in response['results']: - proposal['internalNotes'] = 'Proposal needs review before approval.' - updated_proposals.append(proposal) - - # Update proposals remotely. - proposals = proposal_service.updateProposals(updated_proposals) - - # Display results. - if proposals: - for proposal in proposals: - print ('Proposal with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (proposal['id'], proposal['name'], proposal['internalNotes'])) - else: - print 'No proposals were updated.' - else: - print 'No proposals found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201808/publisher_query_language_service/__init__.py b/examples/ad_manager/v201808/publisher_query_language_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/publisher_query_language_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201808/publisher_query_language_service/fetch_match_tables.py deleted file mode 100755 index f1d1fe7f..00000000 --- a/examples/ad_manager/v201808/publisher_query_language_service/fetch_match_tables.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 fetches data from PQL tables and creates match table files.""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201808') - - line_items_file = tempfile.NamedTemporaryFile( - prefix='line_items_', suffix='.csv', mode='w', delete=False) - ad_units_file = tempfile.NamedTemporaryFile( - prefix='ad_units_', suffix='.csv', mode='w', delete=False) - - line_items_pql_query = ('SELECT Name, Id, Status FROM Line_Item ORDER BY Id ' - 'ASC') - ad_units_pql_query = 'SELECT Name, Id FROM Ad_Unit ORDER BY Id ASC' - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - line_items_pql_query, line_items_file) - report_downloader.DownloadPqlResultToCsv( - ad_units_pql_query, ad_units_file) - - line_items_file.close() - ad_units_file.close() - - print 'Saved line items to... %s' % line_items_file.name - print 'Saved ad units to... %s' % ad_units_file.name - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201808/publisher_query_language_service/get_all_browsers.py deleted file mode 100755 index 98b4867c..00000000 --- a/examples/ad_manager/v201808/publisher_query_language_service/get_all_browsers.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 browsers available to target from the Browser table. - -Other tables include 'Bandwidth_Group', 'Browser_Language', -'Device_Capability', 'Operating_System', etc... - -A full list of available criteria tables can be found at -https://developers.google.com/doubleclick-publishers/docs/reference/v201708/PublisherQueryLanguageService -""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201808') - - with tempfile.NamedTemporaryFile( - prefix='browser_data_', - suffix='.csv', mode='w', delete=False) as browser_data_file: - - browser_pql_query = ('SELECT Id, BrowserName, MajorVersion, MinorVersion ' - 'FROM Browser ' - 'ORDER BY BrowserName ASC') - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - browser_pql_query, browser_data_file) - - print 'Saved browser data to... %s' % browser_data_file.name - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201808/publisher_query_language_service/get_all_programmatic_buyers.py deleted file mode 100755 index 68209369..00000000 --- a/examples/ad_manager/v201808/publisher_query_language_service/get_all_programmatic_buyers.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 fetches programmatic buyer information from the PQL table.""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201808') - - programmatic_buyers_file = tempfile.NamedTemporaryFile( - prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) - - programmatic_buyers_query = ('SELECT BuyerAccountId, Name ' - 'FROM Programmatic_Buyer ' - 'ORDER BY BuyerAccountId ASC') - - # Downloads the response from PQL select statement to the specified file - data_downloader.DownloadPqlResultToCsv( - programmatic_buyers_query, programmatic_buyers_file) - - programmatic_buyers_file.close() - - print 'Saved programmatic buyers to... %s' % programmatic_buyers_file.name - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201808/publisher_query_language_service/get_geo_targets.py deleted file mode 100755 index 95c363ab..00000000 --- a/examples/ad_manager/v201808/publisher_query_language_service/get_geo_targets.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 downloads geo targeting constants using PQL.""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the type of geo target to query for. -GEO_TARGET_TYPE = 'City' - - -def main(client, geo_target_type): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201808') - - with tempfile.NamedTemporaryFile( - prefix='geo_data_', - suffix='.csv', mode='w', delete=False) as geo_data_file: - - geo_pql_query = ('SELECT Id, Name, CanonicalParentId, ParentIds, ' - 'CountryCode, Type ' - 'FROM Geo_Target ' - 'WHERE Type = :type AND Targetable = true ' - 'ORDER BY CountryCode ASC, Name ASC') - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - geo_pql_query, geo_data_file, {'type': geo_target_type}) - - print 'Saved geo data to... %s' % geo_data_file.name - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, GEO_TARGET_TYPE) diff --git a/examples/ad_manager/v201808/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201808/publisher_query_language_service/get_line_items_named_like.py deleted file mode 100755 index c6a78875..00000000 --- a/examples/ad_manager/v201808/publisher_query_language_service/get_line_items_named_like.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 fetches line items from the pql table with a LIKE clause.""" - - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201808') - - with tempfile.NamedTemporaryFile( - prefix='line_items_', - suffix='.csv', mode='w', delete=False) as line_items_file: - - line_items_pql_query = ("SELECT Id, Name, Status FROM Line_Item " - "WHERE Name LIKE 'line item%' " - "ORDER BY Id ASC") - - # Downloads the response from PQL select statement to the specified file - report_downloader.DownloadPqlResultToCsv( - line_items_pql_query, line_items_file) - - print 'Saved line items to... %s' % line_items_file.name - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py deleted file mode 100755 index c43eeb5e..00000000 --- a/examples/ad_manager/v201808/publisher_query_language_service/get_recent_changes.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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. - -"""Gets recent changes in your network using the Change_History table. - -A full list of available tables can be found at: -https://developers.google.com/doubleclick-publishers/docs/reference/latest/PublisherQueryLanguageService -""" - -from datetime import date -from datetime import datetime -from datetime import timedelta - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - - -def main(client): - # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201808') - - end_date = datetime.now(tz=pytz.timezone('America/New_York')) - start_date = end_date - timedelta(days=1) - initial_query = ('ChangeDateTime > :startDateTime ' - 'AND ChangeDateTime < :endDateTime') - pagination_query = 'Id < :id AND ' + initial_query - - statement = (ad_manager.StatementBuilder(version='v201808') - .Select(('Id, ChangeDateTime, EntityId, EntityType, ' - 'Operation, UserId')) - .From('Change_History') - .Where(initial_query) - .OrderBy('ChangeDateTime', ascending=False) - .WithBindVariable('startDateTime', start_date) - .WithBindVariable('endDateTime', end_date)) - - keep_iterating = True - i = 0 - total_rows = [] - - while keep_iterating: - response = pql_service.select(statement.ToStatement()) - column_types = ([column_type['labelName'] - for column_type in response['columnTypes']]) - rows = response['rows'] - rows_length = len(rows) - total_rows.extend(rows) - - if rows and rows_length > 0: - # Get the earliest change ID in the result set. - last_row = rows[-1] - last_id = last_row['values'][0]['value'] - i += 1 - - # Update the statement using the earliest row in the previous result. - statement.Where(pagination_query) - statement.WithBindVariable('id', last_id) - - print ('%d) %d changes prior to ID "%s" were found.\n' - % (i, rows_length, last_id)) - - keep_iterating = rows and len(rows) == statement.limit - - # Print out columns header - print ','.join(column_types) - - # Print out every row - for row in total_rows: - print ConvertValueForCsv(row) - - -def ConvertValueForCsv(pql_value): - """Sanitizes a field value from a Value object to a CSV suitable format. - - Args: - pql_value: dict a dictionary containing the data for a single field of an - entity. - - Returns: - str a CSV writer friendly value formatted by Value.Type. - """ - if 'value' in pql_value: - field = pql_value['value'] - elif 'values' in pql_value: - field = pql_value['values'] - else: - field = None - - if field: - if isinstance(field, list): - return ','.join(['"%s"' % str(ConvertValueForCsv(single_field)) - for single_field in field]) - else: - class_type = ad_manager.AdManagerClassType(pql_value) - - if class_type == 'TextValue': - return field.replace('"', '""').encode('UTF8') - elif class_type == 'NumberValue': - return float(field) if '.' in field else int(field) - elif class_type == 'DateTimeValue': - return ConvertDateTimeToOffset(field) - elif class_type == 'DateValue': - return date(int(field['date']['year']), - int(field['date']['month']), - int(field['date']['day'])).isoformat() - else: - return field - else: - return '-' - - -def ConvertDateTimeToOffset(date_time_value): - """Converts the PQL formatted response for a dateTime object. - - Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.' - - Args: - date_time_value: dict The date time value from the PQL response. - - Returns: - str: A string representation of the date time value uniform to - ReportService. - """ - date_time_obj = datetime(int(date_time_value['date']['year']), - int(date_time_value['date']['month']), - int(date_time_value['date']['day']), - int(date_time_value['hour']), - int(date_time_value['minute']), - int(date_time_value['second'])) - date_time_str = pytz.timezone( - date_time_value['timeZoneID']).localize(date_time_obj).isoformat() - - if date_time_str[-5:] == '00:00': - return date_time_str[:-6] + 'Z' - else: - return date_time_str - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/rate_card_service/__init__.py b/examples/ad_manager/v201808/rate_card_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/rate_card_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201808/rate_card_service/create_rate_cards.py deleted file mode 100755 index 09ee2ae9..00000000 --- a/examples/ad_manager/v201808/rate_card_service/create_rate_cards.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a new rate card. - -To determine which rate cards exist, run get_all_rate_cards.py. -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the IDs of the teams this rate card should be visible to. -TEAM_IDS = ['INSERT_TEAM_ID_HERE'] - -# Set the currency code to create the rate card with. -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201808') - - # Create a rate card. - rate_card = { - 'name': 'RateCard #%d' % random.randint(0, 100000000), - 'currencyCode': CURRENCY_CODE, - 'pricingModel': 'NET', - } - - # This field is optional. - rate_card['appliedTeamIds'] = TEAM_IDS - - result = rate_card_service.createRateCards([rate_card]) - - for new_rate_card in result: - print ('A rate card with ID %s, name "%s", and currency code "%s" ' - 'was created.' % (new_rate_card['id'], - new_rate_card['name'], - new_rate_card['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py deleted file mode 100755 index 42723673..00000000 --- a/examples/ad_manager/v201808/rate_card_service/get_all_rate_cards.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 rate cards. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201808') - - # Create a statement to select rate cards. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of rate cards at a time, paging - # through until all rate cards have been retrieved. - while True: - response = rate_card_service.getRateCardsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for rate_card in response['results']: - # Print out some information for each rate card. - print('Rate card with ID "%d", name "%s", and currency code "%s" was ' - 'found.\n' % - (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py deleted file mode 100755 index a9863f9b..00000000 --- a/examples/ad_manager/v201808/rate_card_service/get_marketplace_rate_cards.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 rate cards that can be used for Marketplace products. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201808') - # Create a statement to select rate cards. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('forMarketplace = :forMarketplace') - .WithBindVariable('forMarketplace', True)) - - # Retrieve a small amount of rate cards at a time, paging - # through until all rate cards have been retrieved. - while True: - response = rate_card_service.getRateCardsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for rate_card in response['results']: - # Print out some information for each rate card. - print( - 'Rate card with ID "%d", name "%s", and currency code "%s" was ' - 'found.\n' - % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py deleted file mode 100755 index c82b0443..00000000 --- a/examples/ad_manager/v201808/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 line item reports for a given reconciliation report. - -To determine how many reconciliation reports exist, -run get_all_reconciliation_reports.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report to query. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201808')) - - # Create a statement to select reconciliation line item reports. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('reconciliationReportId = :reconciliationReportId AND ' - 'lineItemId != :lineItemId')) - .OrderBy('lineItemId', ascending=True) - .WithBindVariable('reconciliationReportId', - RECONCILIATION_REPORT_ID) - .WithBindVariable('lineItemId', 0)) - - # Retrieve a small amount of reconciliation line item reports at a time, - # paging through until all reconciliation line item reports have been - # retrieved. - result_set_size = 0 - should_continue = True - - while should_continue: - page = (reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement( - statement.ToStatement())) - if 'results' in page and len(page['results']): - result_set_size += page['totalResultSetSize'] - # Iterate over individual results in the page. - for line_item_report in page['results']: - print ('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source "%s", and reconciled volume %d was ' - 'found.' % (line_item_report['id'], - line_item_report['lineItemId'], - line_item_report['reconciliationSource'], - (line_item_report['reconciledVolume'] - if 'reconciledVolume' in line_item_report else 0))) - # Update statement for next page. - statement.offset += statement.limit - should_continue = statement.offset < result_set_size - - print 'Number of results found: %d' % result_set_size - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py deleted file mode 100755 index d3c55cee..00000000 --- a/examples/ad_manager/v201808/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 updates a reconciliation line item report. - -To get reconciliation line item reports for a reconciliation report, run -get_reconciliation_line_item_reports_for_reconciliation_report.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation line item report to update. -RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201808')) - - # Create a statement to select a reconciliation line item report. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :lineItemReportId') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('lineItemReportId', - RECONCILIATION_LINE_ITEM_REPORT_ID)) - - # Get reconciliation line item reports by statement. - page = (reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement(statement.ToStatement())) - - line_item_report = page['results'][0] - - # Set and use a manual volume for billing. This example splits the difference - # between Ad Manager and the third party volume. - line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + - line_item_report['thirdPartyVolume']) / 2 - line_item_report['reconciliationSource'] = 'MANUAL' - - result = (reconciliation_line_item_report_service - .updateReconciliationLineItemReports([line_item_report])) - - for updated_report in result: - print ('Reconciliation line item report with ID %d for line item ID %d was ' - 'updated, with manual volume %d' % (updated_report['id'], - updated_report['lineItemId'], - updated_report['manualVolume'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py deleted file mode 100755 index 87b475b0..00000000 --- a/examples/ad_manager/v201808/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. -"""Gets all reconciliation order reports for a given reconciliation report. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201808') - # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('reconciliationReportId = :reconciliationReportId') - .WithBindVariable('reconciliationReportId', - reconciliation_report_id)) - - # Retrieve a small amount of reconciliation order reports at a time, paging - # through until all reconciliation order reports have been retrieved. - while True: - response = ( - reconciliation_order_report_service - .getReconciliationOrderReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_order_report in response['results']: - # Print out some information for each reconciliation order report. - print('Reconciliation order report with ID "%d" and status "%s" was ' - 'found.\n' % (reconciliation_order_report['id'], - reconciliation_order_report['status'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py deleted file mode 100755 index 6d3cf243..00000000 --- a/examples/ad_manager/v201808/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 submits a reconciliation order report. - -To get all reconciliation order reports for a reconciliation report, -run get get_reconciliation_order_reports_for_reconciliation_report.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation order report to submit. -RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201808')) - - # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', RECONCILIATION_ORDER_REPORT_ID)) - - # Get reconciliation order reports by statement. - page = (reconciliation_order_report_service - .getReconciliationOrderReportsByStatement(statement.ToStatement())) - - report = page['results'][0] - - print ('Reconciliation order report with ID %d will be submitted.' % - report['id']) - - # Remove limit and offset from statement. - statement.limit = None - statement.offset = None - - # Perform action. - result = (reconciliation_order_report_service - .performReconciliationOrderReportAction( - {'xsi_type': 'SubmitReconciliationOrderReports'}, - statement.ToStatement())) - - if result and result['numChanges'] > 0: - print ('Number of reconciliation order reports submitted: %d' % - result['numChanges']) - else: - print 'No reconciliation order reports were submitted.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py deleted file mode 100755 index 5caa60de..00000000 --- a/examples/ad_manager/v201808/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets a reconciliation report's rows for line items that Ad Manager served. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report row. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201808') - - # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('reconciliationReportId = :reportId ' - 'AND lineItemId != :lineItemId')) - .WithBindVariable('lineItemId', 0) - .WithBindVariable('reportId', long(reconciliation_report_id))) - - # Retrieve a small amount of reconciliation report rows at a time, paging - # through until all reconciliation report rows have been retrieved. - while True: - response = ( - reconciliation_report_row_service - .getReconciliationReportRowsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report_row in response['results']: - # Print out some information for each reconciliation report row. - print('Reconciliation report row with ID "%d", reconciliation source ' - '"%s", and reconciled volume "%d" was found.\n' % - (reconciliation_report_row['id'], - reconciliation_report_row['reconciliationSource'], - reconciliation_report_row['reconciledVolume'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py deleted file mode 100755 index 064b3c8c..00000000 --- a/examples/ad_manager/v201808/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 updates a reconciliation report row. - -To determine which reconciliation report rows exist, -run get_reconciliation_report_rows_for_reconciliation_report.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report row. -RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' - -# Set the ID of the reconciliation report. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201808')) - - # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('id = :reconciliationReportRowId AND ' - 'reconciliationReportId = :reconciliationReportId')) - .OrderBy('id', ascending=True) - .WithBindVariable('reconciliationReportRowId', - RECONCILIATION_REPORT_ROW_ID) - .WithBindVariable('reconciliationReportId', - RECONCILIATION_REPORT_ID)) - - # Get reconciliation report rows by statement. - page = (reconciliation_report_row_service - .getReconciliationReportRowsByStatement(statement.ToStatement())) - - row = page['results'][0] - - # Set a comment on the reconciliation report row. - row['comments'] = ('Third part volume didn\'t match DFP - we agreed to split ' - 'the difference') - - # Set and use a manual volume for billing. - row['manualVolume'] = (row['dfpVolume'] + row['thirdPartyVolume']) / 2 - row['reconciliationSource'] = 'MANUAL' - - updated_rows = (reconciliation_report_row_service - .updateReconciliationReportRows([row])) - - for updated_row in updated_rows: - print ('Reconciliation report row for line item ID %d and creative ID %d ' - 'was updated, with manual volume %d' % (updated_row['lineItemId'], - updated_row['creativeId'], - updated_row['manualVolume'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py deleted file mode 100755 index aff3d512..00000000 --- a/examples/ad_manager/v201808/reconciliation_report_service/get_all_reconciliation_reports.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 reconciliation reports. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201808') - - # Create a statement to select reconciliation reports. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of reconciliation reports at a time, paging - # through until all reconciliation reports have been retrieved. - while True: - response = ( - reconciliation_report_service - .getReconciliationReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report in response['results']: - # Print out some information for each reconciliation report. - print( - 'Reconciliation report with ID "%d", month "%d", and year "%d" was' - ' found.\n' % (reconciliation_report['id'], - reconciliation_report['startDate']['month'], - reconciliation_report['startDate']['year'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py deleted file mode 100755 index b648d800..00000000 --- a/examples/ad_manager/v201808/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the previous billing period's reconciliation report. -""" - -# Import appropriate modules from the client library. -from datetime import date -from datetime import timedelta - -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201808') - - first_of_the_month = date.today().replace(day=1) - last_month = first_of_the_month - timedelta(days=1) - - # Create a statement to select reconciliation reports. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('startDate = :startDate') - .WithBindVariable('startDate', last_month)) - - # Retrieve a small amount of reconciliation reports at a time, paging - # through until all reconciliation reports have been retrieved. - while True: - response = ( - reconciliation_report_service - .getReconciliationReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report in response['results']: - # Print out some information for each reconciliation report. - print( - 'Reconciliation report with ID "%d" and start date "%s" was found.' - '\n' % (reconciliation_report['id'], - last_month.strftime('%Y-%m-01'))) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/report_service/__init__.py b/examples/ad_manager/v201808/report_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/report_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201808/report_service/run_ad_exchange_report.py deleted file mode 100755 index 2d63b13f..00000000 --- a/examples/ad_manager/v201808/report_service/run_ad_exchange_report.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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. - -"""Runs a report on Ad Exchange data via the Ad Manager API.""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - - -def main(client): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201808') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'], - 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS', - 'AD_EXCHANGE_ESTIMATED_REVENUE'], - 'dateRangeType': 'LAST_WEEK', - 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time - 'adxReportCurrency': 'EUR' - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/report_service/run_delivery_report.py b/examples/ad_manager/v201808/report_service/run_delivery_report.py deleted file mode 100755 index 4ac27a34..00000000 --- a/examples/ad_manager/v201808/report_service/run_delivery_report.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. - -"""Runs a report similar to the "Orders report" on the Ad Manager website. - -Includes additional attributes and can filter to include just one order. -""" - -from datetime import datetime -from datetime import timedelta -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('ORDER_ID = :id') - .WithBindVariable('id', long(order_id)) - .Limit(None) # No limit or offset for reports - .Offset(None)) - - # Set the start and end dates of the report to run (past 8 days). - end_date = datetime.now().date() - start_date = end_date - timedelta(days=8) - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['ORDER_ID', 'ORDER_NAME'], - 'dimensionAttributes': ['ORDER_TRAFFICKER', 'ORDER_START_DATE_TIME', - 'ORDER_END_DATE_TIME'], - 'statement': statement.ToStatement(), - 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', - 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'CUSTOM_DATE', - 'startDate': start_date, - 'endDate': end_date - } - } - - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201808') - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID) diff --git a/examples/ad_manager/v201808/report_service/run_inventory_report.py b/examples/ad_manager/v201808/report_service/run_inventory_report.py deleted file mode 100755 index 95cabda3..00000000 --- a/examples/ad_manager/v201808/report_service/run_inventory_report.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 runs a typical daily inventory report.""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - - -def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201808') - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201808') - - # Get root ad unit id for network. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') - .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) - .Limit(None) # No limit or offset for reports - .Offset(None)) - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['DATE', 'AD_UNIT_NAME'], - 'adUnitView': 'HIERARCHICAL', - 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS', - 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS', - 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', - 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], - 'dateRangeType': 'LAST_WEEK', - 'statement': statement.ToStatement() - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/report_service/run_reach_report.py b/examples/ad_manager/v201808/report_service/run_reach_report.py deleted file mode 100755 index df777ee5..00000000 --- a/examples/ad_manager/v201808/report_service/run_reach_report.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example runs a reach report.""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - - -def main(client): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201808') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'], - 'dateRangeType': 'REACH_LIFETIME' - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201808/report_service/run_report_and_create_match_table.py deleted file mode 100755 index 95a42819..00000000 --- a/examples/ad_manager/v201808/report_service/run_report_and_create_match_table.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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. - -"""Runs a report for LineItems with additional data from a PQL table. - -Fetches a basic report over a network's LineItems and then adds some -extra columns which might be useful for future analysis, such as -LineItemType, from the PQL Line_Item table, creating a match table. -""" - -from datetime import date -from datetime import timedelta -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - -try: - import pandas -except ImportError: - raise ImportError('This example requires the pandas library to be installed.') - - -def main(client): - # Set the start and end dates of the report to run (past 8 days). - end_date = date.today() - start_date = end_date - timedelta(days=8) - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'AD_SERVER_CTR', 'AD_SERVER_CPM_AND_CPC_REVENUE', - 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'CUSTOM_DATE', - 'startDate': start_date, - 'endDate': end_date - } - } - - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201808') - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e - - with tempfile.NamedTemporaryFile( - suffix='.csv.gz', mode='wb', delete=False) as report_file: - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, 'CSV_DUMP', report_file) - - # Create a PQL query to fetch the line item data - line_items_pql_query = ('SELECT Id, LineItemType, Status FROM LineItem') - - # Download the response from PQL select statement - line_items = report_downloader.DownloadPqlResultToList(line_items_pql_query) - - # Use pandas to join the two csv files into a match table - report = pandas.read_csv(report_file.name) - line_items = pandas.DataFrame(data=line_items[1:], columns=line_items[0]) - merged_result = pandas.merge(report, line_items, - left_on='Dimension.LINE_ITEM_ID', right_on='id') - merged_result.to_csv('~/complete_line_items_report.csv', index=False) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py deleted file mode 100755 index 7d6093ee..00000000 --- a/examples/ad_manager/v201808/report_service/run_report_with_custom_fields.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. - -"""Runs a report with custom fields found in the line items of an order.""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - -# Set the ID of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' - - -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201808') - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201808') - - # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('orderId = :orderId') - .WithBindVariable('orderId', long(order_id))) - - # Collect all line item custom field IDs for an order. - custom_field_ids = set() - - # Get users by statement. - while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Get custom field IDs from the line items of an order. - for line_item in response['results']: - if 'customFieldValues' in line_item: - for custom_field_value in line_item['customFieldValues']: - custom_field_ids.add(custom_field_value['customFieldId']) - statement.offset += statement.limit - else: - break - - # Modify statement for reports - statement.limit = None - statement.offset = None - statement.Where('ORDER_ID = :orderId') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': statement.ToStatement(), - 'columns': ['AD_SERVER_IMPRESSIONS'], - 'dateRangeType': 'LAST_MONTH', - 'customFieldIds': list(custom_field_ids) - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID) diff --git a/examples/ad_manager/v201808/report_service/run_sales_report.py b/examples/ad_manager/v201808/report_service/run_sales_report.py deleted file mode 100755 index 08009cb7..00000000 --- a/examples/ad_manager/v201808/report_service/run_sales_report.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. - -"""Runs a report equal to the 'Sales by salespersons report'.""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - - -def main(client): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201808') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['SALESPERSON_ID', 'SALESPERSON_NAME'], - 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CPM_AND_CPC_REVENUE', - 'AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM'], - 'dateRangeType': 'LAST_MONTH' - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/report_service/run_saved_query.py b/examples/ad_manager/v201808/report_service/run_saved_query.py deleted file mode 100755 index c1d3ef64..00000000 --- a/examples/ad_manager/v201808/report_service/run_saved_query.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 runs a report from a saved query. -""" - -# Import appropriate modules from the client library. -import tempfile - -from googleads import ad_manager -from googleads import errors - -SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' - - -def main(client, saved_query_id): - # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201808') - - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201808') - - # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :id') - .WithBindVariable('id', long(saved_query_id)) - .Limit(1)) - - response = report_service.getSavedQueriesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - saved_query = response['results'][0] - - if saved_query['isCompatibleWithApiVersion']: - report_job = {} - - # Set report query and optionally modify it. - report_job['reportQuery'] = saved_query['reportQuery'] - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) - else: - print 'The query specified is not compatible with the API version.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, SAVED_QUERY_ID) diff --git a/examples/ad_manager/v201808/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201808/suggested_ad_unit_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/suggested_ad_unit_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py deleted file mode 100755 index 8eed7f1c..00000000 --- a/examples/ad_manager/v201808/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example approves all suggested ad units with 50 or more requests. - -This feature is only available to Ad Manager 360 solution networks. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -THRESHOLD_NUMBER_OF_REQUESTS = '50' - - -def main(client): - # Initialize appropriate service. - suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201808') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('numRequests > :numRequests') - .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) - num_approved_suggested_ad_units = 0 - - # Get suggested ad units by statement. - while True: - response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Print suggested ad units that will be approved. - for suggested_ad_unit in response['results']: - print ('Suggested ad unit with id "%s", and number of requests "%s"' - ' will be approved.' % (suggested_ad_unit['id'], - suggested_ad_unit['numRequests'])) - - # Approve suggested ad units. - result = suggested_ad_unit_service.performSuggestedAdUnitAction( - {'xsi_type': 'ApproveSuggestedAdUnits'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - num_approved_suggested_ad_units += int(result['numChanges']) - else: - break - - if num_approved_suggested_ad_units > 0: - print ('Number of suggested ad units approved: %s' % - num_approved_suggested_ad_units) - else: - print 'No suggested ad units were approved.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) - diff --git a/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py deleted file mode 100755 index b844f281..00000000 --- a/examples/ad_manager/v201808/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 suggested ad units. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201808') - - # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of suggested ad units at a time, paging - # through until all suggested ad units have been retrieved. - while True: - response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for suggested_ad_unit in response['results']: - # Print out some information for each suggested ad unit. - print( - 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py deleted file mode 100755 index 842dcd9d..00000000 --- a/examples/ad_manager/v201808/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 highly requested suggested ad units. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -NUM_REQUESTS = 'INSERT_NUM_REQUESTS_HERE' - - -def main(client, num_requests): - # Initialize appropriate service. - suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201808') - # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('numRequests >= :numRequests') - .WithBindVariable('numRequests', long(num_requests))) - - # Retrieve a small amount of suggested ad units at a time, paging - # through until all suggested ad units have been retrieved. - while True: - response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for suggested_ad_unit in response['results']: - # Print out some information for each suggested ad unit. - print( - 'Suggested ad unit with ID "%s" and num requests "%d" was found.\n' - % (suggested_ad_unit['id'], suggested_ad_unit['numRequests'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, NUM_REQUESTS) diff --git a/examples/ad_manager/v201808/team_service/__init__.py b/examples/ad_manager/v201808/team_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/team_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/team_service/create_teams.py b/examples/ad_manager/v201808/team_service/create_teams.py deleted file mode 100755 index f8044f8c..00000000 --- a/examples/ad_manager/v201808/team_service/create_teams.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates new teams. - -To determine which teams exist, run get_all_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201808') - - # Create team objects. - teams = [] - for _ in xrange(5): - team = { - 'name': 'Team %s' % uuid.uuid4(), - 'hasAllCompanies': 'false', - 'hasAllInventory': 'false', - 'teamAccessType': 'READ_WRITE' - } - teams.append(team) - - # Add Teams. - teams = team_service.createTeams(teams) - - # Display results. - for team in teams: - print ('Team with ID "%s" and name "%s" was created.' - % (team['id'], team['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/team_service/get_all_teams.py b/examples/ad_manager/v201808/team_service/get_all_teams.py deleted file mode 100755 index ecf3978a..00000000 --- a/examples/ad_manager/v201808/team_service/get_all_teams.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 teams. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201808') - - # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of teams at a time, paging - # through until all teams have been retrieved. - while True: - response = team_service.getTeamsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for team in response['results']: - # Print out some information for each team. - print('Team with ID "%d" and name "%s" was found.\n' % (team['id'], - team['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/team_service/update_teams.py b/examples/ad_manager/v201808/team_service/update_teams.py deleted file mode 100755 index d33e859e..00000000 --- a/examples/ad_manager/v201808/team_service/update_teams.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates teams by changing its description. - -To determine which teams exist, run get_all_teams.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -TEAM_ID = 'INSERT_TEAM_ID_HERE' - - -def main(client, team_id): - # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201808') - - # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :teamId') - .WithBindVariable('teamId', long(team_id))) - - # Get teams by statement. - response = team_service.getTeamsByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_teams = [] - # Update each local team object by changing its description. - for team in response['results']: - team['description'] = 'this team is great!' - updated_teams.append(team) - - # Update teams on the server. - teams = team_service.updateTeams(updated_teams) - - # Display results. - for team in teams: - print ('Team with id "%s" and name "%s" was updated.' - % (team['id'], team['name'])) - else: - print 'No teams found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, TEAM_ID) diff --git a/examples/ad_manager/v201808/user_service/__init__.py b/examples/ad_manager/v201808/user_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/user_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/user_service/create_users.py b/examples/ad_manager/v201808/user_service/create_users.py deleted file mode 100755 index 7cfd32d2..00000000 --- a/examples/ad_manager/v201808/user_service/create_users.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new users. - -To determine which users exist, run get_all_users.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -NEW_USER_EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' -NEW_USER_NAME = 'INSERT_NAME_HERE' - - -def main(client, email, name): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201808') - - # Create user objects. - users = [ - { - 'email': email, - 'name': name, - } - ] - for user in users: - # Set the system defined ID of the trafficker role. - # To determine what other roles exist, run get_all_roles.py. - user['roleId'] = '-7' - - # Add users. - users = user_service.createUsers(users) - - # Display results. - for user in users: - print ('User with id "%s", email "%s", and role "%s" was created.' - % (user['id'], user['email'], user['roleName'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, NEW_USER_EMAIL_ADDRESS, NEW_USER_NAME) diff --git a/examples/ad_manager/v201808/user_service/deactivate_users.py b/examples/ad_manager/v201808/user_service/deactivate_users.py deleted file mode 100755 index 4315b88c..00000000 --- a/examples/ad_manager/v201808/user_service/deactivate_users.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example deactivates a user. - -Deactivated users can no longer make requests to the API. The user making the -request cannot deactivate itself. To determine which users exist, run -get_all_users.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -USER_ID = 'INSERT_USER_ID_TO_DEACTIVATE_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :userId') - .WithBindVariable('userId', long(user_id))) - - # Get users by statement. - response = user_service.getUsersByStatement(statement.ToStatement()) - users = response['results'] if 'results' in response else [] - - for user in users: - print ('User with id "%s", email "%s", and status "%s" will be ' - 'deactivated.' - % (user['id'], user['email'], - {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) - print 'Number of users to be deactivated: %s' % len(users) - - # Perform action. - result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'}, - statement.ToStatement()) - - # Display results. - if result and int(result['numChanges']) > 0: - print 'Number of users deactivated: %s' % result['numChanges'] - else: - print 'No users were deactivated.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201808/user_service/get_all_roles.py b/examples/ad_manager/v201808/user_service/get_all_roles.py deleted file mode 100755 index 442d35bd..00000000 --- a/examples/ad_manager/v201808/user_service/get_all_roles.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 roles. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') - - roles = user_service.getAllRoles() - - # Print out some information for each role. - for role in roles: - print('Role with id "%s" and name "%s" was found.' % - (role['id'], role['name'])) - - print '\nNumber of results found: %s' % len(roles) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/user_service/get_all_users.py b/examples/ad_manager/v201808/user_service/get_all_users.py deleted file mode 100755 index caa0951b..00000000 --- a/examples/ad_manager/v201808/user_service/get_all_users.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 users. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201808') - - # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of users at a time, paging - # through until all users have been retrieved. - while True: - response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for user in response['results']: - # Print out some information for each user. - print('User with ID "%d" and name "%s" was found.\n' % (user['id'], - user['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/user_service/get_current_user.py b/examples/ad_manager/v201808/user_service/get_current_user.py deleted file mode 100755 index 94d55e55..00000000 --- a/examples/ad_manager/v201808/user_service/get_current_user.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 the current user.""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201808') - - # Get current user. - user = user_service.getCurrentUser() - - print ('User with ID %d, name "%s", email "%s", and role "%s" ' - 'is the current user.' % ( - user.id, user.name, user.email, user.roleName - )) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/user_service/get_user_by_email_address.py b/examples/ad_manager/v201808/user_service/get_user_by_email_address.py deleted file mode 100755 index e15adb37..00000000 --- a/examples/ad_manager/v201808/user_service/get_user_by_email_address.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 users by email. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE' - - -def main(client, email_address): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201808') - # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('email = :email') - .WithBindVariable('email', email_address)) - - # Retrieve a small amount of users at a time, paging - # through until all users have been retrieved. - while True: - response = user_service.getUsersByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for user in response['results']: - # Print out some information for each user. - print('User with ID "%d" and name "%s" was found.\n' % (user['id'], - user['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, EMAIL_ADDRESS) diff --git a/examples/ad_manager/v201808/user_service/update_users.py b/examples/ad_manager/v201808/user_service/update_users.py deleted file mode 100755 index 5e5df575..00000000 --- a/examples/ad_manager/v201808/user_service/update_users.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates a user by adding " Sr." to the end of their name. - -To determine which users exist, run get_all_users.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201808') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('id = :userId') - .WithBindVariable('userId', long(user_id))) - - # Get users by statement. - response = user_service.getUsersByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - users = response['results'] - for user in users: - user['name'] += ' Sr.' - - # Update users on server. - users = user_service.updateUsers(users) - for user in users: - print ('User with id "%s" and name "%s" was updated.' - % (user['id'], user['name'])) - else: - print 'No users found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201808/user_team_association_service/__init__.py b/examples/ad_manager/v201808/user_team_association_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/user_team_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/create_user_team_associations.py deleted file mode 100755 index c37f417d..00000000 --- a/examples/ad_manager/v201808/user_team_association_service/create_user_team_associations.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 adds a user to a team by creating an association between them. - -To determine which teams exists, run get_all_teams.py. To determine which -users exist, run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -TEAM_ID = 'INSERT_TEAM_ID_HERE' -USER_IDS = ['INSERT_USER_IDS_TO_ASSOCIATE_TO_TEAM_HERE'] - - -def main(client, team_id, user_ids): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201808') - - user_team_associations = [] - for user_id in user_ids: - user_team_associations.append( - { - 'teamId': team_id, - 'userId': user_id - }) - - # Create the user team association on the server. - user_team_associations = ( - user_team_association_service.createUserTeamAssociations( - user_team_associations)) - - # Display results. - if user_team_associations: - for user_team_association in user_team_associations: - print ('A user team association between user with ID "%s" and team with' - ' ID "%s"was created.' % (user_team_association['userId'], - user_team_association['teamId'])) - else: - print 'No user team associations created.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, TEAM_ID, USER_IDS) diff --git a/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py deleted file mode 100755 index 4655d73a..00000000 --- a/examples/ad_manager/v201808/user_team_association_service/delete_user_team_associations.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 removes the user from all its teams. - -To determine which users exist, run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -USER_ID = 'INSERT_USER_ID_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201808') - - # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) - - # Get user team associations by statement. - response = user_team_association_service.getUserTeamAssociationsByStatement( - statement.ToStatement()) - user_team_associations = response['results'] if 'results' in response else [] - - for user_team_association in user_team_associations: - print ('User team association between user with ID "%s" and team with ' - 'ID "%s" will be deleted.' % (user_team_association['userId'], - user_team_association['teamId'])) - print ('Number of teams that the user will be removed from: %s' % - len(user_team_associations)) - - # Action doesn't require limit/offset - statement.limit = None - statement.offset = None - - # Perform action. - result = user_team_association_service.performUserTeamAssociationAction( - {'xsi_type': 'DeleteUserTeamAssociations'}, - statement.ToStatement()) - - # Display results. - if result and int(result['numChanges']) > 0: - print ('Number of teams that the user was removed from: %s' - % result['numChanges']) - else: - print 'No user team associations were deleted.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py deleted file mode 100755 index 746a386a..00000000 --- a/examples/ad_manager/v201808/user_team_association_service/get_all_user_team_associations.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 user team associations. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201808') - - # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v201808') - - # Retrieve a small amount of user team associations at a time, paging - # through until all user team associations have been retrieved. - while True: - response = user_team_association_service.getUserTeamAssociationsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for user_team_association in response['results']: - # Print out some information for each user team association. - print('User team association with team id "%d" and user id "%d" was ' - 'found.\n' % (user_team_association['teamId'], - user_team_association['userId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py deleted file mode 100755 index 32019038..00000000 --- a/examples/ad_manager/v201808/user_team_association_service/get_user_team_associations_for_user.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 user team associations (i.e. teams) for a given user. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -USER_ID = 'INSERT_USER_ID_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201808') - # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) - - # Retrieve a small amount of user team associations at a time, paging - # through until all user team associations have been retrieved. - while True: - response = user_team_association_service.getUserTeamAssociationsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for user_team_association in response['results']: - # Print out some information for each user team association. - print('User team association with user ID "%d" and team ID "%d" was ' - 'found.\n' % (user_team_association['userId'], - user_team_association['teamId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py deleted file mode 100755 index 0644eaaf..00000000 --- a/examples/ad_manager/v201808/user_team_association_service/update_user_team_associations.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates user team associations. - -It updates a user team association by setting the overridden access type to read -only for all teams that the user belongs to. To determine which users exists, -run get_all_users.py. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -USER_ID = 'INSERT_USER_ID_TO_UPDATE_HERE' - - -def main(client, user_id): - # Initialize appropriate service. - user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201808') - - # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) - - # Get user team associations by statement. - response = user_team_association_service.getUserTeamAssociationsByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_user_team_associations = [] - # Update each local user team association to read only access. - for user_team_association in response['results']: - user_team_association['overriddenTeamAccessType'] = 'READ_ONLY' - updated_user_team_associations.append(user_team_association) - - # Update user team associations on the server. - user_team_associations = ( - user_team_association_service.updateUserTeamAssociations( - updated_user_team_associations)) - - # Display results. - if user_team_associations: - for user_team_association in user_team_associations: - print ('User team association between user with ID "%s" and team with' - ' ID "%s" was updated.' % (user_team_association['userId'], - user_team_association['teamId'])) - else: - print 'No user team associations were updated.' - else: - print 'No user team associations found to update.' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, USER_ID) diff --git a/examples/ad_manager/v201808/workflow_request_service/__init__.py b/examples/ad_manager/v201808/workflow_request_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201808/workflow_request_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py deleted file mode 100755 index a5468cba..00000000 --- a/examples/ad_manager/v201808/workflow_request_service/approve_workflow_approval_requests.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 approves all workflow approval requests belonging to a proposal. - -To determine which workflow approval requests exist, run -get_all_workflow_approval_requests.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201808') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('entityId = :entityId and entityType = :entityType ' - 'and type = :type')) - .WithBindVariable('entityId', proposal_id) - .WithBindVariable('entityType', 'PROPOSAL') - .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) - workflow_approval_requests_approved = 0 - - # Get workflow approval requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for workflow_approval_request in response['results']: - print ('Workflow approval request with id "%s" will be' - ' approved.' % workflow_approval_request['id']) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'ApproveWorkflowApprovalRequests', - 'comment': 'This workflow has now been approved for submission.'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_approval_requests_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if workflow_approval_requests_approved > 0: - print ('\nNumber of workflow approval requests approved: %s' % - workflow_approval_requests_approved) - else: - print '\nNo workflow approval requests were approved.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py deleted file mode 100755 index 0244aabd..00000000 --- a/examples/ad_manager/v201808/workflow_request_service/get_workflow_approval_requests.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 workflow approval requests. - -Workflow approval requests must be approved or rejected for a workflow to -finish. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201808') - # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('type = :type') - .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) - - # Retrieve a small amount of workflow requests at a time, paging - # through until all workflow requests have been retrieved. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for workflow_request in response['results']: - # Print out some information for each workflow request. - print('Workflow request with ID "%d", entity type "%s", and entity ID ' - '"%d" was found.\n' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py deleted file mode 100755 index a81f0f5b..00000000 --- a/examples/ad_manager/v201808/workflow_request_service/get_workflow_external_condition_requests.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 workflow external condition requests. - -Workflow external condition requests must be triggered or skipped for a -workflow to finish. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201808') - # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where('type = :type') - .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) - - # Retrieve a small amount of workflow requests at a time, paging - # through until all workflow requests have been retrieved. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for workflow_request in response['results']: - # Print out some information for each workflow request. - print('Workflow request with ID "%d", entity type "%s", and entity ID ' - '"%d" was found.\n' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py deleted file mode 100755 index 167e4dbe..00000000 --- a/examples/ad_manager/v201808/workflow_request_service/trigger_workflow_external_condition_requests.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 triggers all workflow external condition requests for a proposal. - -Workflow external condition requests must be triggered or skipped for a workflow -to finish. To determine which proposals exist, run get_all_proposals.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201808') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201808') - .Where(('entityId = :entityId and entityType = :entityType ' - 'and type = :type')) - .WithBindVariable('entityId', proposal_id) - .WithBindVariable('entityType', 'PROPOSAL') - .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) - workflow_external_condition_requests_triggered = 0 - - # Get workflow external condition requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for workflow_request in response['results']: - print ('Workflow external condition request with id "%s" for %s ' - 'with id "%s" will be triggered.' % - (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_external_condition_requests_triggered += int( - result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if workflow_external_condition_requests_triggered > 0: - print ('\nNumber of workflow external condition requests triggered: %s' % - workflow_external_condition_requests_triggered) - else: - print '\nNo workflow external condition requests were triggered.' - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/googleads/common.py b/googleads/common.py index e810eb07..59a67550 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -78,7 +78,7 @@ 'compatibility with this library, upgrade to Python 2.7.9 or higher.') -VERSION = '19.0.0' +VERSION = '19.0.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' From 81742dc3571c9413196cfceb57f761c79db6857a Mon Sep 17 00:00:00 2001 From: David Wihl Date: Wed, 22 May 2019 17:57:29 +0300 Subject: [PATCH 141/180] Commiting latest changes. From 370455cdfd66375eafdabcac5819b0040d9d8ab5 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Tue, 11 Jun 2019 16:07:53 -0400 Subject: [PATCH 142/180] Releasing v20.0.0 --- ChangeLog | 4 + README.md | 85 +-- ...ate_ad_manager_client_with_access_token.py | 4 +- ...te_ad_manager_client_with_refresh_token.py | 4 +- ..._ad_manager_client_with_service_account.py | 4 +- .../authentication/generate_refresh_token.py | 12 +- .../create_activity_groups.py | 4 +- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 8 +- .../activity_service/create_activities.py | 4 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 8 +- .../create_audience_segments.py | 8 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 10 +- .../update_audience_segments.py | 12 +- .../create_product_base_rates.py | 8 +- .../create_product_package_item_base_rates.py | 8 +- .../create_product_template_base_rates.py | 8 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 16 +- .../get_all_cdn_configurations.py | 2 +- .../company_service/create_companies.py | 4 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 10 +- .../contact_service/create_contacts.py | 4 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 10 +- .../__init__.py | 15 - ...create_content_metadata_key_hierarchies.py | 79 --- ...et_all_content_metadata_key_hierarchies.py | 55 -- ...update_content_metadata_key_hierarchies.py | 94 --- .../content_service/get_all_content.py | 4 +- .../creative_service/copy_image_creatives.py | 10 +- .../create_creative_from_template.py | 6 +- .../creative_service/create_creatives.py | 6 +- .../create_custom_creative.py | 6 +- .../create_native_creative.py | 12 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../creative_service/update_creatives.py | 8 +- .../associate_creative_set_to_line_item.py | 4 +- .../create_creative_set.py | 6 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../update_creative_set.py | 10 +- .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../create_creative_wrappers.py | 4 +- .../deactivate_creative_wrapper.py | 18 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 10 +- .../create_custom_field_options.py | 4 +- .../create_custom_fields.py | 4 +- .../deactivate_all_line_item_custom_fields.py | 8 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 2 +- .../set_line_item_custom_field_value.py | 6 +- .../update_custom_fields.py | 10 +- ...create_custom_targeting_keys_and_values.py | 16 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- ...efined_custom_targeting_keys_and_values.py | 2 +- .../update_custom_targeting_keys.py | 10 +- .../update_custom_targeting_values.py | 10 +- .../create_exchange_rates.py | 16 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../update_exchange_rates.py | 22 +- .../get_availability_forecast.py | 20 +- ...get_availability_forecast_for_line_item.py | 15 +- .../get_delivery_forecast_for_line_items.py | 12 +- .../inventory_service/archive_ad_units.py | 10 +- .../inventory_service/create_ad_units.py | 4 +- .../get_ad_unit_hierarchy.py | 4 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 4 +- .../v201811/label_service/create_labels.py | 4 +- .../label_service/deactivate_labels.py | 8 +- .../label_service/get_active_labels.py | 2 +- .../v201811/label_service/get_all_labels.py | 2 +- .../v201811/label_service/update_labels.py | 8 +- .../create_licas.py | 8 +- .../deactivate_licas.py | 12 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../update_licas.py | 8 +- .../line_item_service/activate_line_items.py | 12 +- .../line_item_service/create_line_items.py | 6 +- .../create_video_line_item.py | 6 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../line_item_service/pause_line_items.py | 8 +- .../target_custom_criteria.py | 8 +- .../line_item_service/update_line_items.py | 12 +- .../activate_live_stream_events.py | 8 +- .../get_all_live_stream_events.py | 2 +- .../register_sessions_for_monitoring.py | 4 +- .../update_live_stream_events.py | 2 +- .../create_native_styles.py | 6 +- .../get_all_native_styles.py | 2 +- .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 4 +- .../network_service/make_test_network.py | 10 +- .../v201811/order_service/approve_orders.py | 8 +- .../v201811/order_service/create_orders.py | 4 +- .../v201811/order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 2 +- .../v201811/order_service/update_orders.py | 12 +- .../package_service/create_packages.py | 4 +- ...reate_proposal_line_items_from_packages.py | 12 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 2 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 12 +- .../get_active_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 4 +- .../create_premium_rates.py | 6 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 2 +- .../update_premium_rates.py | 12 +- .../create_product_package_item.py | 10 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 2 +- .../create_product_packages.py | 4 +- .../get_active_product_packages.py | 2 +- .../get_all_product_packages.py | 2 +- .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- .../product_service/update_products.py | 12 +- .../activate_product_templates.py | 14 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 6 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 10 +- .../archive_proposal_line_items.py | 18 +- ...create_programmatic_proposal_line_items.py | 8 +- ...sal_line_items_for_non_sales_management.py | 10 +- .../create_proposal_line_items.py | 8 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 14 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 2 +- .../request_buyers_acceptance.py | 14 +- .../submit_proposals_for_approval.py | 10 +- .../proposal_service/update_proposals.py | 12 +- .../fetch_match_tables.py | 4 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 4 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 8 +- .../rate_card_service/create_rate_cards.py | 8 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 16 +- ...update_reconciliation_line_item_reports.py | 8 +- ...order_reports_for_reconciliation_report.py | 2 +- .../submit_reconciliation_order_reports.py | 10 +- ...n_report_rows_for_reconciliation_report.py | 4 +- .../update_reconciliation_report_rows.py | 8 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 2 +- .../report_service/run_ad_exchange_report.py | 8 +- .../report_service/run_delivery_report.py | 10 +- .../report_service/run_inventory_report.py | 10 +- .../report_service/run_reach_report.py | 8 +- .../run_report_and_create_match_table.py | 4 +- .../run_report_with_custom_fields.py | 10 +- .../report_service/run_sales_report.py | 8 +- .../v201811/report_service/run_saved_query.py | 12 +- .../approve_all_suggested_ad_units.py | 12 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../v201811/team_service/create_teams.py | 4 +- .../v201811/team_service/get_all_teams.py | 2 +- .../v201811/team_service/update_teams.py | 8 +- .../v201811/user_service/create_users.py | 4 +- .../v201811/user_service/deactivate_users.py | 14 +- .../v201811/user_service/get_all_roles.py | 4 +- .../v201811/user_service/get_all_users.py | 2 +- .../v201811/user_service/get_current_user.py | 7 +- .../user_service/get_user_by_email_address.py | 2 +- .../v201811/user_service/update_users.py | 8 +- .../create_user_team_associations.py | 8 +- .../delete_user_team_associations.py | 18 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 12 +- .../approve_workflow_approval_requests.py | 10 +- .../get_workflow_approval_requests.py | 2 +- ...et_workflow_external_condition_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 16 +- .../create_activity_groups.py | 4 +- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 8 +- .../activity_service/create_activities.py | 4 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 8 +- .../create_audience_segments.py | 8 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 10 +- .../update_audience_segments.py | 12 +- .../create_product_base_rates.py | 8 +- .../create_product_package_item_base_rates.py | 8 +- .../create_product_template_base_rates.py | 8 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 16 +- .../get_all_cdn_configurations.py | 2 +- .../company_service/create_companies.py | 4 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 10 +- .../contact_service/create_contacts.py | 4 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 10 +- .../__init__.py | 15 - ...create_content_metadata_key_hierarchies.py | 79 --- ...et_all_content_metadata_key_hierarchies.py | 55 -- ...update_content_metadata_key_hierarchies.py | 94 --- .../content_service/get_all_content.py | 4 +- .../creative_service/copy_image_creatives.py | 10 +- .../create_creative_from_template.py | 6 +- .../creative_service/create_creatives.py | 6 +- .../create_custom_creative.py | 6 +- .../create_native_creative.py | 12 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../creative_service/update_creatives.py | 8 +- .../associate_creative_set_to_line_item.py | 4 +- .../create_creative_set.py | 6 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../update_creative_set.py | 10 +- .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../create_creative_wrappers.py | 4 +- .../deactivate_creative_wrapper.py | 18 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 10 +- .../create_custom_field_options.py | 4 +- .../create_custom_fields.py | 4 +- .../deactivate_all_line_item_custom_fields.py | 8 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 2 +- .../set_line_item_custom_field_value.py | 6 +- .../update_custom_fields.py | 10 +- ...create_custom_targeting_keys_and_values.py | 16 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- ...efined_custom_targeting_keys_and_values.py | 2 +- .../update_custom_targeting_keys.py | 10 +- .../update_custom_targeting_values.py | 10 +- .../create_exchange_rates.py | 16 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../update_exchange_rates.py | 22 +- .../get_availability_forecast.py | 20 +- ...get_availability_forecast_for_line_item.py | 15 +- .../get_delivery_forecast_for_line_items.py | 12 +- .../inventory_service/archive_ad_units.py | 10 +- .../inventory_service/create_ad_units.py | 4 +- .../get_ad_unit_hierarchy.py | 4 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 4 +- .../v201902/label_service/create_labels.py | 4 +- .../label_service/deactivate_labels.py | 8 +- .../label_service/get_active_labels.py | 2 +- .../v201902/label_service/get_all_labels.py | 2 +- .../v201902/label_service/update_labels.py | 8 +- .../create_licas.py | 8 +- .../deactivate_licas.py | 12 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../update_licas.py | 8 +- .../line_item_service/activate_line_items.py | 12 +- .../line_item_service/create_line_items.py | 6 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../line_item_service/pause_line_items.py | 8 +- .../target_custom_criteria.py | 8 +- .../line_item_service/update_line_items.py | 12 +- .../activate_live_stream_events.py | 8 +- .../get_all_live_stream_events.py | 2 +- .../register_sessions_for_monitoring.py | 4 +- .../update_live_stream_events.py | 2 +- .../create_native_styles.py | 6 +- .../get_all_native_styles.py | 2 +- .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 4 +- .../network_service/make_test_network.py | 10 +- .../v201902/order_service/approve_orders.py | 8 +- .../v201902/order_service/create_orders.py | 4 +- .../v201902/order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 2 +- .../v201902/order_service/update_orders.py | 12 +- .../package_service/create_packages.py | 4 +- ...reate_proposal_line_items_from_packages.py | 12 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 2 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 12 +- .../get_active_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 4 +- .../create_premium_rates.py | 6 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 2 +- .../update_premium_rates.py | 12 +- .../create_product_package_item.py | 10 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 2 +- .../create_product_packages.py | 4 +- .../get_active_product_packages.py | 2 +- .../get_all_product_packages.py | 2 +- .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- .../product_service/update_products.py | 12 +- .../activate_product_templates.py | 14 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 6 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 10 +- .../archive_proposal_line_items.py | 18 +- ...create_programmatic_proposal_line_items.py | 8 +- ...sal_line_items_for_non_sales_management.py | 10 +- .../create_proposal_line_items.py | 8 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 14 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 2 +- .../request_buyers_acceptance.py | 14 +- .../submit_proposals_for_approval.py | 10 +- .../proposal_service/update_proposals.py | 12 +- .../fetch_match_tables.py | 4 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 4 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 8 +- .../rate_card_service/create_rate_cards.py | 8 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 16 +- ...update_reconciliation_line_item_reports.py | 8 +- ...order_reports_for_reconciliation_report.py | 2 +- .../submit_reconciliation_order_reports.py | 10 +- ...n_report_rows_for_reconciliation_report.py | 4 +- .../update_reconciliation_report_rows.py | 8 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 2 +- .../report_service/run_ad_exchange_report.py | 8 +- .../report_service/run_delivery_report.py | 10 +- .../report_service/run_inventory_report.py | 10 +- .../report_service/run_reach_report.py | 8 +- .../run_report_and_create_match_table.py | 4 +- .../run_report_with_custom_fields.py | 10 +- .../report_service/run_sales_report.py | 8 +- .../v201902/report_service/run_saved_query.py | 12 +- .../approve_all_suggested_ad_units.py | 12 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../v201902/team_service/create_teams.py | 4 +- .../v201902/team_service/get_all_teams.py | 2 +- .../v201902/team_service/update_teams.py | 8 +- .../v201902/user_service/create_users.py | 4 +- .../v201902/user_service/deactivate_users.py | 14 +- .../v201902/user_service/get_all_roles.py | 4 +- .../v201902/user_service/get_all_users.py | 2 +- .../v201902/user_service/get_current_user.py | 7 +- .../user_service/get_user_by_email_address.py | 2 +- .../v201902/user_service/update_users.py | 8 +- .../create_user_team_associations.py | 8 +- .../delete_user_team_associations.py | 18 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 12 +- .../approve_workflow_approval_requests.py | 10 +- .../get_workflow_approval_requests.py | 2 +- ...et_workflow_external_condition_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 16 +- .../create_activity_groups.py | 4 +- .../get_active_activity_groups.py | 2 +- .../get_all_activity_groups.py | 2 +- .../update_activity_groups.py | 8 +- .../activity_service/create_activities.py | 4 +- .../activity_service/get_active_activities.py | 2 +- .../activity_service/get_all_activities.py | 2 +- .../activity_service/update_activities.py | 8 +- .../create_audience_segments.py | 8 +- .../get_all_audience_segments.py | 2 +- .../get_first_party_audience_segments.py | 2 +- .../populate_first_party_audience_segments.py | 10 +- .../update_audience_segments.py | 12 +- .../create_product_base_rates.py | 8 +- .../create_product_package_item_base_rates.py | 8 +- .../create_product_template_base_rates.py | 8 +- .../base_rate_service/get_all_base_rates.py | 2 +- .../get_base_rates_for_rate_card.py | 2 +- .../base_rate_service/update_base_rates.py | 16 +- .../get_all_cdn_configurations.py | 2 +- .../company_service/create_companies.py | 4 +- .../company_service/get_advertisers.py | 2 +- .../company_service/get_all_companies.py | 2 +- .../company_service/update_companies.py | 10 +- .../contact_service/create_contacts.py | 4 +- .../contact_service/get_all_contacts.py | 2 +- .../contact_service/get_uninvited_contacts.py | 2 +- .../contact_service/update_contacts.py | 10 +- .../__init__.py | 15 - ...create_content_metadata_key_hierarchies.py | 79 --- ...et_all_content_metadata_key_hierarchies.py | 55 -- ...update_content_metadata_key_hierarchies.py | 94 --- .../content_service/get_all_content.py | 4 +- .../creative_service/copy_image_creatives.py | 10 +- .../create_creative_from_template.py | 6 +- .../creative_service/create_creatives.py | 6 +- .../create_custom_creative.py | 6 +- .../create_native_creative.py | 12 +- .../creative_service/get_all_creatives.py | 2 +- .../creative_service/get_image_creatives.py | 2 +- .../creative_service/update_creatives.py | 8 +- .../associate_creative_set_to_line_item.py | 4 +- .../create_creative_set.py | 6 +- .../get_all_creative_sets.py | 2 +- .../get_creative_sets_for_master_creative.py | 2 +- .../update_creative_set.py | 10 +- .../get_all_creative_templates.py | 2 +- .../get_system_defined_creative_templates.py | 2 +- .../create_creative_wrappers.py | 4 +- .../deactivate_creative_wrapper.py | 18 +- .../get_active_creative_wrappers.py | 2 +- .../get_all_creative_wrappers.py | 2 +- .../update_creative_wrappers.py | 10 +- .../create_custom_field_options.py | 4 +- .../create_custom_fields.py | 4 +- .../deactivate_all_line_item_custom_fields.py | 8 +- .../get_all_custom_fields.py | 2 +- .../get_custom_fields_for_line_items.py | 2 +- .../set_line_item_custom_field_value.py | 6 +- .../update_custom_fields.py | 10 +- ...create_custom_targeting_keys_and_values.py | 16 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 2 +- ...efined_custom_targeting_keys_and_values.py | 2 +- .../update_custom_targeting_keys.py | 10 +- .../update_custom_targeting_values.py | 10 +- .../create_exchange_rates.py | 16 +- .../get_all_exchange_rates.py | 2 +- .../get_exchange_rates_for_currency_code.py | 2 +- .../update_exchange_rates.py | 22 +- .../get_availability_forecast.py | 20 +- ...get_availability_forecast_for_line_item.py | 15 +- .../get_delivery_forecast_for_line_items.py | 12 +- .../inventory_service/archive_ad_units.py | 10 +- .../inventory_service/create_ad_units.py | 4 +- .../get_ad_unit_hierarchy.py | 4 +- .../inventory_service/get_all_ad_units.py | 2 +- .../get_top_level_ad_units.py | 2 +- .../inventory_service/update_ad_units.py | 4 +- .../v201905/label_service/create_labels.py | 4 +- .../label_service/deactivate_labels.py | 8 +- .../label_service/get_active_labels.py | 2 +- .../v201905/label_service/get_all_labels.py | 2 +- .../v201905/label_service/update_labels.py | 8 +- .../create_licas.py | 8 +- .../deactivate_licas.py | 12 +- .../get_all_licas.py | 2 +- .../get_licas_for_line_item.py | 2 +- .../update_licas.py | 8 +- .../line_item_service/activate_line_items.py | 12 +- .../line_item_service/create_line_items.py | 6 +- .../line_item_service/get_all_line_items.py | 2 +- .../get_line_items_that_need_creatives.py | 2 +- .../get_recently_updated_line_items.py | 2 +- .../line_item_service/pause_line_items.py | 8 +- .../target_custom_criteria.py | 8 +- .../line_item_service/update_line_items.py | 12 +- .../activate_live_stream_events.py | 8 +- .../get_all_live_stream_events.py | 2 +- .../register_sessions_for_monitoring.py | 4 +- .../update_live_stream_events.py | 2 +- .../create_native_styles.py | 6 +- .../get_all_native_styles.py | 2 +- .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 4 +- .../network_service/make_test_network.py | 10 +- .../v201905/order_service/approve_orders.py | 8 +- .../v201905/order_service/create_orders.py | 4 +- .../v201905/order_service/get_all_orders.py | 2 +- .../order_service/get_orders_starting_soon.py | 2 +- .../v201905/order_service/update_orders.py | 12 +- .../package_service/create_packages.py | 4 +- ...reate_proposal_line_items_from_packages.py | 12 +- .../package_service/get_all_packages.py | 2 +- .../get_in_progress_packages.py | 2 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 12 +- .../get_active_placements.py | 2 +- .../placement_service/get_all_placements.py | 2 +- .../placement_service/update_placements.py | 4 +- .../create_premium_rates.py | 6 +- .../get_all_premium_rates.py | 2 +- .../get_premium_rates_for_rate_card.py | 2 +- .../update_premium_rates.py | 12 +- .../create_product_package_item.py | 10 +- .../get_all_product_package_items.py | 2 +- ...oduct_package_items_for_product_package.py | 2 +- .../create_product_packages.py | 4 +- .../get_active_product_packages.py | 2 +- .../get_all_product_packages.py | 2 +- .../product_service/get_all_products.py | 2 +- .../get_products_for_product_template.py | 2 +- .../product_service/update_products.py | 12 +- .../activate_product_templates.py | 14 +- .../create_product_templates.py | 4 +- .../create_programmatic_product_templates.py | 6 +- .../get_all_product_templates.py | 2 +- .../get_sponsorship_product_templates.py | 2 +- .../update_product_templates.py | 10 +- .../archive_proposal_line_items.py | 18 +- ...create_programmatic_proposal_line_items.py | 8 +- ...sal_line_items_for_non_sales_management.py | 10 +- .../create_proposal_line_items.py | 8 +- .../get_all_proposal_line_items.py | 2 +- .../get_proposal_line_items_for_proposal.py | 2 +- .../update_proposal_line_items.py | 14 +- .../proposal_service/create_proposals.py | 4 +- .../proposal_service/get_all_proposals.py | 2 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_pending_approval.py | 2 +- .../request_buyers_acceptance.py | 14 +- .../submit_proposals_for_approval.py | 10 +- .../proposal_service/update_proposals.py | 12 +- .../fetch_match_tables.py | 4 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 4 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 8 +- .../rate_card_service/create_rate_cards.py | 8 +- .../rate_card_service/get_all_rate_cards.py | 2 +- .../get_marketplace_rate_cards.py | 2 +- ..._item_reports_for_reconciliation_report.py | 16 +- ...update_reconciliation_line_item_reports.py | 8 +- ...order_reports_for_reconciliation_report.py | 2 +- .../submit_reconciliation_order_reports.py | 10 +- ...n_report_rows_for_reconciliation_report.py | 4 +- .../update_reconciliation_report_rows.py | 8 +- .../get_all_reconciliation_reports.py | 2 +- ...iliation_report_for_last_billing_period.py | 2 +- .../report_service/run_ad_exchange_report.py | 8 +- .../report_service/run_delivery_report.py | 10 +- .../report_service/run_inventory_report.py | 10 +- .../report_service/run_reach_report.py | 8 +- .../run_report_and_create_match_table.py | 4 +- .../run_report_with_custom_fields.py | 10 +- .../report_service/run_sales_report.py | 8 +- .../v201905/report_service/run_saved_query.py | 12 +- .../approve_all_suggested_ad_units.py | 12 +- .../get_all_suggested_ad_units.py | 2 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../get_all_targeting_presets.py | 2 +- .../v201905/team_service/create_teams.py | 4 +- .../v201905/team_service/get_all_teams.py | 2 +- .../v201905/team_service/update_teams.py | 8 +- .../v201905/user_service/create_users.py | 4 +- .../v201905/user_service/deactivate_users.py | 14 +- .../v201905/user_service/get_all_roles.py | 4 +- .../v201905/user_service/get_all_users.py | 2 +- .../v201905/user_service/get_current_user.py | 7 +- .../user_service/get_user_by_email_address.py | 2 +- .../v201905/user_service/update_users.py | 8 +- .../create_user_team_associations.py | 8 +- .../delete_user_team_associations.py | 18 +- .../get_all_user_team_associations.py | 2 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 12 +- .../approve_workflow_approval_requests.py | 10 +- .../get_workflow_approval_requests.py | 2 +- ...et_workflow_external_condition_requests.py | 2 +- ...er_workflow_external_condition_requests.py | 16 +- .../adwords/adwords_appengine_demo/README.md | 5 +- .../handlers/api_handler.py | 2 +- .../views/add_adgroup_view.py | 2 +- .../views/add_campaign_view.py | 2 +- .../adwords_appengine_demo/views/init_view.py | 2 +- .../views/show_accounts_view.py | 2 +- .../views/show_adgroups_view.py | 2 +- .../views/show_budget_view.py | 2 +- .../views/show_campaigns_view.py | 2 +- .../views/show_credentials_view.py | 2 +- .../views/update_budget_view.py | 2 +- .../views/update_credentials_view.py | 2 +- ...create_adwords_client_with_access_token.py | 2 +- ...reate_adwords_client_with_refresh_token.py | 4 +- ...ate_adwords_client_with_service_account.py | 4 +- .../authentication/generate_refresh_token.py | 12 +- .../account_management/accept_service_link.py | 8 +- .../account_management/create_account.py | 4 +- .../account_management/get_account_changes.py | 32 +- .../get_account_hierarchy.py | 6 +- .../advanced_operations/add_ad_customizer.py | 14 +- .../add_ad_group_bid_modifier.py | 10 +- .../add_dynamic_page_feed.py | 13 +- .../add_dynamic_search_ads_campaign.py | 28 +- ...add_expanded_text_ad_with_upgraded_urls.py | 14 +- .../advanced_operations/add_gmail_ad.py | 8 +- .../advanced_operations/add_html5_ad.py | 9 +- .../add_multi_asset_responsive_display_ad.py | 8 +- .../add_responsive_display_ad.py | 12 +- ...d_shopping_dynamic_remarketing_campaign.py | 18 +- .../add_universal_app_campaign.py | 12 +- .../create_and_attach_shared_keyword_set.py | 12 +- ...ind_and_remove_criteria_from_shared_set.py | 26 +- .../get_ad_group_bid_modifier.py | 10 +- .../use_shared_bidding_strategy.py | 16 +- .../v201809/basic_operations/add_ad_groups.py | 4 +- .../v201809/basic_operations/add_campaigns.py | 4 +- .../basic_operations/add_expanded_text_ads.py | 6 +- .../v201809/basic_operations/add_keywords.py | 6 +- .../add_responsive_search_ad.py | 8 +- .../v201809/basic_operations/get_ad_groups.py | 8 +- .../v201809/basic_operations/get_campaigns.py | 8 +- .../get_campaigns_with_awql.py | 8 +- .../basic_operations/get_expanded_text_ads.py | 12 +- .../v201809/basic_operations/get_keywords.py | 14 +- .../get_responsive_search_ads.py | 10 +- .../v201809/basic_operations/pause_ad.py | 2 +- .../v201809/basic_operations/remove_ad.py | 4 +- .../basic_operations/remove_ad_group.py | 4 +- .../basic_operations/remove_campaign.py | 4 +- .../basic_operations/remove_keyword.py | 6 +- .../basic_operations/update_ad_group.py | 6 +- .../basic_operations/update_campaign.py | 4 +- .../update_expanded_text_ad.py | 16 +- .../basic_operations/update_keyword.py | 12 +- ...campaign_groups_and_performance_targets.py | 14 +- .../add_campaign_labels.py | 4 +- .../add_complete_campaigns_using_batch_job.py | 28 +- .../v201809/campaign_management/add_draft.py | 4 +- ...dd_keywords_using_incremental_batch_job.py | 44 +- .../v201809/campaign_management/add_trial.py | 18 +- .../get_all_disapproved_ads.py | 16 +- .../get_all_disapproved_ads_with_awql.py | 16 +- .../get_campaigns_by_label.py | 6 +- .../campaign_management/graduate_trial.py | 6 +- .../campaign_management/set_ad_parameters.py | 10 +- .../set_criterion_bid_modifier.py | 6 +- .../campaign_management/validate_text_ad.py | 4 +- .../error_handling/handle_partial_failures.py | 12 +- ..._google_my_business_location_extensions.py | 10 +- .../adwords/v201809/extensions/add_prices.py | 4 +- .../v201809/extensions/add_site_links.py | 10 +- .../extensions/add_site_links_using_feeds.py | 32 +- .../migrate_to_extension_settings.py | 10 +- .../v201809/misc/get_all_image_assets.py | 14 +- .../v201809/misc/get_all_images_and_videos.py | 16 +- examples/adwords/v201809/misc/upload_image.py | 8 +- .../v201809/misc/upload_image_asset.py | 14 +- .../v201809/misc/upload_media_bundle.py | 5 +- .../optimization/estimate_keyword_traffic.py | 14 +- ...aign_criterion_bid_modifier_simulations.py | 32 +- .../get_keyword_bid_simulations.py | 20 +- .../v201809/optimization/get_keyword_ideas.py | 8 +- .../v201809/remarketing/add_audience.py | 14 +- .../remarketing/add_conversion_tracker.py | 8 +- .../remarketing/add_conversion_trackers.py | 14 +- .../remarketing/add_crm_based_user_list.py | 4 +- .../remarketing/add_rule_based_user_lists.py | 10 +- .../upload_conversion_adjustments.py | 6 +- .../upload_offline_call_conversions.py | 6 +- .../remarketing/upload_offline_conversions.py | 8 +- .../remarketing/upload_offline_data.py | 24 +- ...oad_criteria_report_as_stream_with_awql.py | 10 +- ...criteria_report_as_stream_with_selector.py | 4 +- ...oad_criteria_report_as_string_with_awql.py | 6 +- ...criteria_report_as_string_with_selector.py | 6 +- .../v201809/reporting/get_report_fields.py | 6 +- .../reporting/parallel_report_download.py | 20 +- .../stream_criteria_report_results.py | 4 +- .../shopping/add_product_partition_tree.py | 4 +- .../v201809/shopping/add_product_scope.py | 4 +- .../v201809/shopping/add_shopping_campaign.py | 14 +- .../add_shopping_campaign_for_showcase_ads.py | 26 +- .../v201809/shopping/add_smart_shopping_ad.py | 14 +- .../shopping/get_product_category_taxonomy.py | 2 +- .../add_campaign_targeting_criteria.py | 6 +- .../add_customer_negative_criteria.py | 6 +- .../add_demographic_targeting_criteria.py | 10 +- .../get_campaign_targeting_criteria.py | 8 +- .../get_targetable_languages_and_carriers.py | 12 +- .../v201809/targeting/lookup_location.py | 6 +- googleads.yaml | 7 - googleads/__init__.py | 4 +- googleads/ad_manager.py | 26 +- googleads/adwords.py | 128 ++-- googleads/common.py | 538 +-------------- googleads/util.py | 256 +------ setup.py | 21 +- tests/ad_manager_test.py | 15 +- tests/adwords_test.py | 334 +++------- tests/common_test.py | 629 +----------------- tests/oauth2_test.py | 6 +- .../batch_job_util_raw_request_template.txt | 2 +- tests/testing.py | 38 -- tests/util_test.py | 429 +----------- 736 files changed, 2601 insertions(+), 5390 deletions(-) delete mode 100755 examples/ad_manager/v201811/content_metadata_key_hierarchy_service/__init__.py delete mode 100755 examples/ad_manager/v201811/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201811/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201811/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201902/content_metadata_key_hierarchy_service/__init__.py delete mode 100755 examples/ad_manager/v201902/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201902/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201902/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201905/content_metadata_key_hierarchy_service/__init__.py delete mode 100755 examples/ad_manager/v201905/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201905/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py delete mode 100755 examples/ad_manager/v201905/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py diff --git a/ChangeLog b/ChangeLog index ab841fd4..d9339d7d 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +20.0.0 -- 06/11/2019 +* Updated examples to be Python 3 compatible +* Removed suds dependency leaving zeep as the only supported SOAP client + 19.0.1 -- 05/22/2019 * Really removed examples for Ad Manager v201808 diff --git a/README.md b/README.md index 00ad1b9e..d018669c 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,9 @@ and DoubleClick for Publishers. The library provides easy ways to store your authentication and create SOAP web service clients. It also contains example code to help you get started integrating with our APIs. +**NOTE**: As of v20.0.0 this library is _not_ compatible with Python versions less than Python 3.6. +Also `suds` is no longer supported in this library, `zeep` is now the only supported SOAP client. + ## Getting started 1. Download and install the library @@ -112,12 +115,6 @@ can do the following: logging.basicConfig(level=logging.INFO, format=googleads.util.LOGGER_FORMAT) logging.getLogger('googleads.soap').setLevel(logging.DEBUG) ``` - -If you are using suds, you can achieve the same like this: -```python -logging.basicConfig(level=logging.INFO, format=googleads.util.LOGGER_FORMAT) -logging.getLogger('suds.transport').setLevel(logging.DEBUG) -``` If you wish to log to a file, you'll need to attach a log handler to this source which is configured to write the output to a file. @@ -138,60 +135,6 @@ class DangerousZeepLogger(zeep.Plugin): adwords_client.zeep_client.plugins.append(DangerousZeepLogger()) ``` -When using suds, this library will apply log filters to the `googleads.common`, -`suds.client`, and `suds.transport` loggers in order to omit sensitive data. If -you need to see this data in your logs, you can disable the filters with the -following: -```python -logging.getLogger('googleads.common').removeFilter( - googleads.util.GetGoogleAdsCommonFilter()) -logging.getLogger('suds.client').removeFilter( - googleads.util.GetSudsClientFilter()) -logging.getLogger('suds.mx.core').removeFilter( - googleads.util.GetSudsMXCoreFilter()) -logging.getLogger('suds.mx.literal').removeFilter( - googleads.util.GetSudsMXLiteralFilter()) -logging.getLogger('suds.transport').removeFilter( - googleads.util.GetSudsTransportFilter()) -``` - - -## I'm familiar with suds/zeep. Can I use those features in the library? -Yes, you can. The services returned by the `client.GetService()` functions all -have a reference to the underlying client stored in the `zeep_client` or `suds_client` -attributes. You can retrieve the client and use it in familiar ways: -```python -client = AdWordsClient.LoadFromStorage() -campaign_service = client.GetService('CampaignService') -suds_client = campaign_service.suds_client - -campaign = suds_client.factory.create('Campaign') -# Set any attributes on the campaign object which you need. -campaign.name = 'My Campaign' -campaign.status = 'PAUSED' - -operation = suds_client.factory.create('CampaignOperation') -operation.operator = 'ADD' -operation.operand = campaign - -# The service object returned from the client.GetService() call accepts suds -# objects and will set the SOAP and HTTP headers for you. -campaign_service.mutate([operation]) - -# Alternatively, if you wish to set the headers yourself, you can use the -# suds_client.service directly. -soap_header = suds_client.factory.create('SoapHeader') -soap_header.clientCustomerId = client.client_customer_id -soap_header.developerToken = client.developer_token -soap_header.userAgent = client.user_agent - -suds_client.set_options( - soapheaders=soap_header, - headers=client.oauth2_client.CreateHttpHeader()) - -suds_client.service.mutate([operation]) -``` - ## How can I configure or disable caching? By default, clients are cached because reading and digesting the WSDL @@ -199,7 +142,7 @@ can be expensive. However, the default caching method requires permission to access a local file system that may not be available in certain hosting environments such as App Engine. -You can pass an implementation of `suds.cache.Cache` or `zeep.cache.Base` to the `AdWordsClient` or +You can pass an implementation of `zeep.cache.Base` to the `AdWordsClient` or `AdManagerClient` initializer to modify the default caching behavior. For example, configuring a different location and duration of the cache file with zeep @@ -210,14 +153,6 @@ adwords_client = adwords.AdWordsClient( client_customer_id=client_customer_id, cache=doc_cache) ``` -And with suds: -```python -doc_cache = suds.cache.DocumentCache(location=cache_path, days=2) -adwords_client = adwords.AdWordsClient( - developer_token, oauth2_client, user_agent, - client_customer_id=client_customer_id, cache=doc_cache) -``` - You can also disable caching in similar fashion with zeep ```python adwords_client = adwords.AdWordsClient( @@ -226,26 +161,16 @@ adwords_client = adwords.AdWordsClient( cache=googleads.common.ZeepServiceProxy.NO_CACHE) ``` -And with suds: -```python -adwords_client = adwords.AdWordsClient( - developer_token, oauth2_client, user_agent, - client_customer_id=client_customer_id, cache=suds.cache.NoCache()) -``` - - ## Requirements ### Python Versions -This library supports both Python 2 and 3. To use this library, you will need to -have Python 2.7.9 (or higher) or Python 3.4 (or higher) installed. +This library only supports Python 3.6+. ### External Dependencies: - httplib2 -- https://pypi.python.org/pypi/httplib2/ - oauth2client -- https://pypi.python.org/pypi/oauth2client/ - - suds-jurko -- https://pypi.python.org/pypi/suds-jurko/ - pysocks -- https://pypi.python.org/pypi/PySocks/ - pytz -- https://pypi.python.org/pypi/pytz - pyYAML -- https://pypi.python.org/pypi/pyYAML/ diff --git a/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py b/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py index 6d364692..74ecb010 100755 --- a/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py +++ b/examples/ad_manager/authentication/create_ad_manager_client_with_access_token.py @@ -61,8 +61,8 @@ def main(access_token, token_expiry, application_name): networks = ad_manager_client.GetService('NetworkService').getAllNetworks() for network in networks: - print ('Network with network code "%s" and display name "%s" was found.' - % (network['networkCode'], network['displayName'])) + print('Network with network code "%s" and display name "%s" was found.' + % (network['networkCode'], network['displayName'])) if __name__ == '__main__': diff --git a/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py b/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py index 52b456bb..5c3d0e10 100755 --- a/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py +++ b/examples/ad_manager/authentication/create_ad_manager_client_with_refresh_token.py @@ -45,8 +45,8 @@ def main(client_id, client_secret, refresh_token, application_name): networks = ad_manager_client.GetService('NetworkService').getAllNetworks() for network in networks: - print ('Network with network code "%s" and display name "%s" was found.' - % (network['networkCode'], network['displayName'])) + print('Network with network code "%s" and display name "%s" was found.' + % (network['networkCode'], network['displayName'])) if __name__ == '__main__': diff --git a/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py b/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py index a750b73e..de909fc3 100755 --- a/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py +++ b/examples/ad_manager/authentication/create_ad_manager_client_with_service_account.py @@ -37,8 +37,8 @@ def main(key_file, application_name): networks = ad_manager_client.GetService('NetworkService').getAllNetworks() for network in networks: - print ('Network with network code "%s" and display name "%s" was found.' - % (network['networkCode'], network['displayName'])) + print('Network with network code "%s" and display name "%s" was found.' + % (network['networkCode'], network['displayName'])) if __name__ == '__main__': diff --git a/examples/ad_manager/authentication/generate_refresh_token.py b/examples/ad_manager/authentication/generate_refresh_token.py index bfcc62e9..c0034a91 100755 --- a/examples/ad_manager/authentication/generate_refresh_token.py +++ b/examples/ad_manager/authentication/generate_refresh_token.py @@ -95,19 +95,19 @@ def main(client_id, client_secret, scopes): auth_url, _ = flow.authorization_url(prompt='consent') - print ('Log into the Google Account you use to access your Ad Manager account' - 'and go to the following URL: \n%s\n' % (auth_url)) - print 'After approving the token enter the verification code (if specified).' + print('Log into the Google Account you use to access your Ad Manager account' + 'and go to the following URL: \n%s\n' % (auth_url)) + print('After approving the token enter the verification code (if specified).') code = raw_input('Code: ').strip() try: flow.fetch_token(code=code) except InvalidGrantError as ex: - print 'Authentication has failed: %s' % ex + print('Authentication has failed: %s' % ex) sys.exit(1) - print 'Access token: %s' % flow.credentials.token - print 'Refresh token: %s' % flow.credentials.refresh_token + print('Access token: %s' % flow.credentials.token) + print('Refresh token: %s' % flow.credentials.refresh_token) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201811/activity_group_service/create_activity_groups.py index fb7d9d51..409824a5 100755 --- a/examples/ad_manager/v201811/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201811/activity_group_service/create_activity_groups.py @@ -62,8 +62,8 @@ def main(client, advertiser_company_id): # Display results. for activity_group in activity_groups: - print ('Activity group with ID "%s" and name "%s" was created.' - % (activity_group['id'], activity_group['name'])) + print('Activity group with ID "%s" and name "%s" was created.' + % (activity_group['id'], activity_group['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py index b0ad5466..7c7bc582 100755 --- a/examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py index 157800e3..37a5cb79 100755 --- a/examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201811/activity_group_service/update_activity_groups.py index 79229770..e85b1d86 100755 --- a/examples/ad_manager/v201811/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201811/activity_group_service/update_activity_groups.py @@ -42,7 +42,7 @@ def main(client, activity_group_id, advertiser_company_id): # Create statement object to select a single activity groups by ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :activityGroupId') - .WithBindVariable('activityGroupId', long(activity_group_id)) + .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) # Get activity groups by statement. @@ -58,10 +58,10 @@ def main(client, activity_group_id, advertiser_company_id): updated_activity_groups) for activity_group in activity_groups: - print (('Activity group with ID "%s" and name "%s" was updated.') - % (activity_group['id'], activity_group['name'])) + print(('Activity group with ID "%s" and name "%s" was updated.') + % (activity_group['id'], activity_group['name'])) else: - print 'No activity groups found to update.' + print('No activity groups found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/activity_service/create_activities.py b/examples/ad_manager/v201811/activity_service/create_activities.py index 5ac6dd12..89d0db2f 100755 --- a/examples/ad_manager/v201811/activity_service/create_activities.py +++ b/examples/ad_manager/v201811/activity_service/create_activities.py @@ -59,8 +59,8 @@ def main(client, activity_group_id): # Display results. for activity in activities: - print ('An activity with ID "%s", name "%s", and type "%s" was ' - 'created.' % (activity['id'], activity['name'], activity['type'])) + print('An activity with ID "%s", name "%s", and type "%s" was ' + 'created.' % (activity['id'], activity['name'], activity['type'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/activity_service/get_active_activities.py b/examples/ad_manager/v201811/activity_service/get_active_activities.py index 5ffd0865..4db61a64 100755 --- a/examples/ad_manager/v201811/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201811/activity_service/get_active_activities.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/activity_service/get_all_activities.py b/examples/ad_manager/v201811/activity_service/get_all_activities.py index 790d42b2..d4d99954 100755 --- a/examples/ad_manager/v201811/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201811/activity_service/get_all_activities.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/activity_service/update_activities.py b/examples/ad_manager/v201811/activity_service/update_activities.py index 688c5204..b2e73b72 100755 --- a/examples/ad_manager/v201811/activity_service/update_activities.py +++ b/examples/ad_manager/v201811/activity_service/update_activities.py @@ -40,7 +40,7 @@ def main(client, activity_id): # Create statement object to select one activity by ID to update. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :activityId') - .WithBindVariable('activityId', long(activity_id)) + .WithBindVariable('activityId', int(activity_id)) .Limit(1)) # Get activities by statement. @@ -56,10 +56,10 @@ def main(client, activity_id): activities = activity_service.updateActivities(updated_activities) for updated_activity in activities: - print (('Activity with ID "%s" and name "%s" was updated.') - % (updated_activity['id'], updated_activity['name'])) + print(('Activity with ID "%s" and name "%s" was updated.') + % (updated_activity['id'], updated_activity['name'])) else: - print 'No activities found to update.' + print('No activities found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py index 68cddff4..f7eff0f3 100755 --- a/examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py @@ -84,10 +84,10 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): audience_segment_service.createAudienceSegments(audience_segment)) for created_audience_segment in audience_segments: - print ('An audience segment with ID "%s", name "%s", and type "%s" ' - 'was created.' % (created_audience_segment['id'], - created_audience_segment['name'], - created_audience_segment['type'])) + print('An audience segment with ID "%s", name "%s", and type "%s" ' + 'was created.' % (created_audience_segment['id'], + created_audience_segment['name'], + created_audience_segment['type'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py index c9adf99c..4e3c5682 100755 --- a/examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py index 7e3208d2..2410fe09 100755 --- a/examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py @@ -44,7 +44,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py index 26c671e8..be95fc71 100755 --- a/examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py @@ -36,7 +36,7 @@ def main(client, audience_segment_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', - long(audience_segment_id)) + int(audience_segment_id)) .WithBindVariable('type', 'FIRST_PARTY') .Limit(1)) @@ -47,7 +47,7 @@ def main(client, audience_segment_id): segments = response['results'] for segment in segments: - print ( + print( 'Audience segment with id "%s" and name "%s" will be populated.' % (segment['id'], segment['name'])) @@ -59,10 +59,10 @@ def main(client, audience_segment_id): audience_segment_service.performAudienceSegmentAction( action, statement.ToStatement())) - print ('%s audience segment populated' % - populated_audience_segments['numChanges']) + print('%s audience segment populated' % + populated_audience_segments['numChanges']) else: - print 'No Results Found' + print('No Results Found') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py index 4256d856..8d707f49 100755 --- a/examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py @@ -35,7 +35,7 @@ def main(client, audience_segment_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', - long(audience_segment_id)) + int(audience_segment_id)) .WithBindVariable('type', 'FIRST_PARTY') .Limit(1)) @@ -46,8 +46,8 @@ def main(client, audience_segment_id): if 'results' in response and len(response['results']): updated_audience_segments = [] for audience_segment in response['results']: - print ('Audience segment with id "%s" and name "%s" will be updated.' - % (audience_segment['id'], audience_segment['name'])) + print('Audience segment with id "%s" and name "%s" will be updated.' + % (audience_segment['id'], audience_segment['name'])) audience_segment['membershipExpirationDays'] = '180' updated_audience_segments.append(audience_segment) @@ -56,10 +56,10 @@ def main(client, audience_segment_id): updated_audience_segments) for audience_segment in audience_segments: - print ('Audience segment with id "%s" and name "%s" was updated' % - (audience_segment['id'], audience_segment['name'])) + print('Audience segment with id "%s" and name "%s" was updated' % + (audience_segment['id'], audience_segment['name'])) else: - print 'No audience segment found to update.' + print('No audience segment found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py index 96c38e73..9fad367c 100755 --- a/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py @@ -53,10 +53,10 @@ def main(client, product_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product base rate with ID "%s" and rate \'%.2f\' %s was ' - 'created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) + print('A product base rate with ID "%s" and rate \'%.2f\' %s was ' + 'created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py index 859a1bba..799b1dbe 100755 --- a/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py @@ -54,10 +54,10 @@ def main(client): result = base_rate_service.createBaseRates([product_package_item_base_rate]) for new_base_rate in result: - print ('A product package item base rate with ID %d and rate %f %s ' - 'was created.' % (new_base_rate['id'], - new_base_rate['microAmount'], - new_base_rate['currencyCode'])) + print('A product package item base rate with ID %d and rate %f %s ' + 'was created.' % (new_base_rate['id'], + new_base_rate['microAmount'], + new_base_rate['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py index 08201601..770ff107 100755 --- a/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py @@ -53,10 +53,10 @@ def main(client, product_template_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product template base rate with ID "%s" and rate \'%.2f\' %s' - ' was created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) + print('A product template base rate with ID "%s" and rate \'%.2f\' %s' + ' was created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py index 8edb7d58..b9368058 100755 --- a/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py index 83a7351d..211ff434 100755 --- a/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py @@ -46,7 +46,7 @@ def main(client, rate_card_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/base_rate_service/update_base_rates.py b/examples/ad_manager/v201811/base_rate_service/update_base_rates.py index 35aa22d8..44aea9b5 100755 --- a/examples/ad_manager/v201811/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201811/base_rate_service/update_base_rates.py @@ -36,7 +36,7 @@ def main(client, base_rate_id): .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) - .WithBindVariable('id', long(base_rate_id))) + .WithBindVariable('id', int(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( @@ -60,15 +60,15 @@ def main(client, base_rate_id): # Display results. if base_rates: for base_rate in base_rates: - print ('Base rate with ID "%s" and type "%s" belonging to ' - 'rate card ID "%s" was updated.' % ( - base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) + print('Base rate with ID "%s" and type "%s" belonging to ' + 'rate card ID "%s" was updated.' % ( + base_rate['id'], + ad_manager.AdManagerClassType(base_rate), + base_rate['rateCardId'])) else: - print 'No base rates were updated.' + print('No base rates were updated.') else: - print 'No base rates found to update.' + print('No base rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py index 9aa41520..c7116db6 100755 --- a/examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/company_service/create_companies.py b/examples/ad_manager/v201811/company_service/create_companies.py index 6f1d5de1..83ccc417 100755 --- a/examples/ad_manager/v201811/company_service/create_companies.py +++ b/examples/ad_manager/v201811/company_service/create_companies.py @@ -53,8 +53,8 @@ def main(client): # Display results. for company in companies: - print ('Company with ID "%s", name "%s", and type "%s" was created.' - % (company['id'], company['name'], company['type'])) + print('Company with ID "%s", name "%s", and type "%s" was created.' + % (company['id'], company['name'], company['type'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/company_service/get_advertisers.py b/examples/ad_manager/v201811/company_service/get_advertisers.py index edfd6091..d7cee10d 100755 --- a/examples/ad_manager/v201811/company_service/get_advertisers.py +++ b/examples/ad_manager/v201811/company_service/get_advertisers.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/company_service/get_all_companies.py b/examples/ad_manager/v201811/company_service/get_all_companies.py index d45cc748..54dff40a 100755 --- a/examples/ad_manager/v201811/company_service/get_all_companies.py +++ b/examples/ad_manager/v201811/company_service/get_all_companies.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/company_service/update_companies.py b/examples/ad_manager/v201811/company_service/update_companies.py index 631b6024..0372a3ad 100755 --- a/examples/ad_manager/v201811/company_service/update_companies.py +++ b/examples/ad_manager/v201811/company_service/update_companies.py @@ -40,7 +40,7 @@ def main(client, company_id): # Create statement object to only select a single company by ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') - .WithBindVariable('id', long(company_id)) + .WithBindVariable('id', int(company_id)) .Limit(1)) # Get companies by statement. @@ -57,11 +57,11 @@ def main(client, company_id): # Display results. for company in companies: - print (('Company with ID "%s", name "%s", and comment "%s"' - ' was updated.') - % (company['id'], company['name'], company['comment'])) + print(('Company with ID "%s", name "%s", and comment "%s"' + ' was updated.') + % (company['id'], company['name'], company['comment'])) else: - print 'No companies found to update.' + print('No companies found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/contact_service/create_contacts.py b/examples/ad_manager/v201811/contact_service/create_contacts.py index d805ea92..16457695 100755 --- a/examples/ad_manager/v201811/contact_service/create_contacts.py +++ b/examples/ad_manager/v201811/contact_service/create_contacts.py @@ -62,8 +62,8 @@ def main(client, advertiser_company_id, agency_company_id): # Display results. for contact in contacts: - print ('Contact with ID "%s" name "%s" was created.' - % (contact['id'], contact['name'])) + print('Contact with ID "%s" name "%s" was created.' + % (contact['id'], contact['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/contact_service/get_all_contacts.py b/examples/ad_manager/v201811/contact_service/get_all_contacts.py index 8df2e0ea..f9dea551 100755 --- a/examples/ad_manager/v201811/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201811/contact_service/get_all_contacts.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py index a2f97fad..fdf9d459 100755 --- a/examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/contact_service/update_contacts.py b/examples/ad_manager/v201811/contact_service/update_contacts.py index d568d80e..5e3b13d4 100755 --- a/examples/ad_manager/v201811/contact_service/update_contacts.py +++ b/examples/ad_manager/v201811/contact_service/update_contacts.py @@ -40,7 +40,7 @@ def main(client, contact_id): # Create statement object to select the single contact by ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') - .WithBindVariable('id', long(contact_id)) + .WithBindVariable('id', int(contact_id)) .Limit(1)) # Get contacts by statement. @@ -58,11 +58,11 @@ def main(client, contact_id): # Display results. for contact in contacts: - print (('Contact with ID "%s", name "%s", and address "%s" ' - 'was updated.') - % (contact['id'], contact['name'], contact['address'])) + print(('Contact with ID "%s", name "%s", and address "%s" ' + 'was updated.') + % (contact['id'], contact['name'], contact['address'])) else: - print 'No contacts found to update.' + print('No contacts found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py deleted file mode 100755 index 1f0452b6..00000000 --- a/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the IDs of the custom targeting keys for the hierarchy. -HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' -HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201811') - - hierarchy_level_1 = { - 'customTargetingKeyId': hierarchy_level_one_key_id, - 'hierarchyLevel': '1' - } - - hierarchy_level_2 = { - 'customTargetingKeyId': hierarchy_level_two_key_id, - 'hierarchyLevel': '2' - } - - hierarchy_levels = [hierarchy_level_1, hierarchy_level_2] - - # Create content metadata key hierarchy object. - content_metadata_key_hierarchy = { - 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(), - 'hierarchyLevels': hierarchy_levels - } - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy])) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id "%s" and name "%s"' - ' was created.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, HIERARCHY_LEVEL_ONE_KEY_ID, - HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py deleted file mode 100755 index 4da6014a..00000000 --- a/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 content metadata key hierarchies. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201811') - - # Create a statement to select content metadata key hierarchies. - statement = ad_manager.StatementBuilder(version='v201811') - - # Retrieve a small amount of content metadata key hierarchies at a time, - # paging through until all content metadata key hierarchies have been - # retrieved. - while True: - response = ( - content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for content_metadata_key_hierarchy in response['results']: - # Print out some information for each content metadata key hierarchy. - print('Content metadata key hierarchy with ID "%d" and name "%s" was ' - 'found.\n' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py deleted file mode 100755 index 96f131ac..00000000 --- a/examples/ad_manager/v201811/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the content metadata key hierarchy to update. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') -# Set the ID of the custom targeting key to be added as a hierarchy level. -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201811') - - # Create a query to select a single content metadata key hierarchy. - - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) - .Limit(1)) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement()))[0] - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - if content_metadata_key_hierarchies: - content_metadata_key_hierarchy = content_metadata_key_hierarchies[0] - - # Update the content metadata key hierarchy by adding a hierarchy level. - hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels'] - - hierarchy_level = { - 'customTargetingKeyId': custom_targeting_key_id, - 'hierarchyLevel': str(len(hierarchy_levels) + 1) - } - - content_metadata_key_hierarchy['hierarchyLevels'] = ( - hierarchy_levels.append(hierarchy_level)) - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies)) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id "%s" and name "%s"' - ' was updated.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - else: - print 'No content metadata key hierarchies were found' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID, - CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201811/content_service/get_all_content.py b/examples/ad_manager/v201811/content_service/get_all_content.py index 1d0561d8..ad8e4fcc 100755 --- a/examples/ad_manager/v201811/content_service/get_all_content.py +++ b/examples/ad_manager/v201811/content_service/get_all_content.py @@ -35,12 +35,12 @@ def main(client): for content in response['results']: # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % - (content['id'], content['name'])) + (content['id'], content['name'].encode('utf-8'))) statement.offset += statement.limit else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_service/copy_image_creatives.py b/examples/ad_manager/v201811/creative_service/copy_image_creatives.py index 9847fd68..b1e0df83 100755 --- a/examples/ad_manager/v201811/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201811/creative_service/copy_image_creatives.py @@ -47,11 +47,11 @@ def main(client): image_creative['name'] = 'Copy of %s' % image_creative['name'] result = creative_service.createCreatives([image_creative])[0] - print ('A creative with ID %d, name "%s", and type "%s" was created and ' - 'can be previewed at: %s' % (result['id'], - result['name'], - ad_manager.AdManagerClassType(result), - result['previewUrl'])) + print('A creative with ID %d, name "%s", and type "%s" was created and ' + 'can be previewed at: %s' % (result['id'], + result['name'], + ad_manager.AdManagerClassType(result), + result['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_service/create_creative_from_template.py b/examples/ad_manager/v201811/creative_service/create_creative_from_template.py index 0d41b549..a812dceb 100755 --- a/examples/ad_manager/v201811/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201811/creative_service/create_creative_from_template.py @@ -100,9 +100,9 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Template creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Template creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_service/create_creatives.py b/examples/ad_manager/v201811/creative_service/create_creatives.py index 29c8281d..3d5beb72 100755 --- a/examples/ad_manager/v201811/creative_service/create_creatives.py +++ b/examples/ad_manager/v201811/creative_service/create_creatives.py @@ -79,9 +79,9 @@ def main(client, advertiser_id): # Display results. for creative in creatives: - print ('Image creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Image creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_service/create_custom_creative.py b/examples/ad_manager/v201811/creative_service/create_custom_creative.py index 21dac3a4..fa6385f3 100755 --- a/examples/ad_manager/v201811/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201811/creative_service/create_custom_creative.py @@ -77,9 +77,9 @@ def main(client, advertiser_id): # Display results. if creatives: creative = creatives[0] - print ('Template creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Template creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_service/create_native_creative.py b/examples/ad_manager/v201811/creative_service/create_native_creative.py index 62198290..bdc83a08 100755 --- a/examples/ad_manager/v201811/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201811/creative_service/create_native_creative.py @@ -29,8 +29,8 @@ section of our README. """ -import urllib2 import uuid +from urllib.request import urlopen # Import appropriate modules from the client library. from googleads import ad_manager @@ -50,9 +50,9 @@ def main(client, advertiser_id): # Use the system defined native app install creative template. creative_template_id = '10004400' - image_data = urllib2.urlopen(ICON_URL).read() + image_data = urlopen(ICON_URL).read() - app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() + app_icon_data = urlopen(APP_ICON_SMALL).read() # Create creative from templates. creative = { @@ -122,9 +122,9 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Native creative with id "%s" and name "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['previewUrl'])) + print('Native creative with id "%s" and name "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/creative_service/get_all_creatives.py b/examples/ad_manager/v201811/creative_service/get_all_creatives.py index d1aa3ccc..0038fb66 100755 --- a/examples/ad_manager/v201811/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201811/creative_service/get_all_creatives.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_service/get_image_creatives.py b/examples/ad_manager/v201811/creative_service/get_image_creatives.py index a3032af8..5c0971ff 100755 --- a/examples/ad_manager/v201811/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201811/creative_service/get_image_creatives.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_service/update_creatives.py b/examples/ad_manager/v201811/creative_service/update_creatives.py index 9a995e01..29a5985c 100755 --- a/examples/ad_manager/v201811/creative_service/update_creatives.py +++ b/examples/ad_manager/v201811/creative_service/update_creatives.py @@ -40,7 +40,7 @@ def main(client, image_creative_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') - .WithBindVariable('id', long(image_creative_id)) + .WithBindVariable('id', int(image_creative_id)) .Limit(1)) # Get creatives by statement. @@ -59,10 +59,10 @@ def main(client, image_creative_id): # Display results. for creative in creatives: - print ('Image creative with id "%s" and destination URL "%s" was ' - 'updated.' % (creative['id'], creative['destinationUrl'])) + print('Image creative with id "%s" and destination URL "%s" was ' + 'updated.' % (creative['id'], creative['destinationUrl'])) else: - print 'No creatives found to update.' + print('No creatives found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py index 5237b11a..cfc54536 100755 --- a/examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py @@ -46,8 +46,8 @@ def main(client, creative_set_id, line_item_id): lica = lica_service.createLineItemCreativeAssociations([lica]) # Display results. - print (('LICA with line item ID "%s" and creative set ID "%s" was ' - 'created.') % (lica['lineItemId'], lica['creativeSetId'])) + print(('LICA with line item ID "%s" and creative set ID "%s" was ' + 'created.') % (lica['lineItemId'], lica['creativeSetId'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/creative_set_service/create_creative_set.py b/examples/ad_manager/v201811/creative_set_service/create_creative_set.py index b4911012..db2b15af 100755 --- a/examples/ad_manager/v201811/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201811/creative_set_service/create_creative_set.py @@ -50,9 +50,9 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: - print (('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was created.') - % (creative_set['id'], creative_set['masterCreativeId'], + print(('Creative set with ID "%s", master creative ID "%s", and ' + 'companion creative IDs {%s} was created.') + % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py index 51bdb6c2..0221291b 100755 --- a/examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py index 0f815e34..cc6ed2d3 100755 --- a/examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py @@ -45,7 +45,7 @@ def main(client, master_creative_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_set_service/update_creative_set.py b/examples/ad_manager/v201811/creative_set_service/update_creative_set.py index 56bb53ca..18557638 100755 --- a/examples/ad_manager/v201811/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201811/creative_set_service/update_creative_set.py @@ -42,7 +42,7 @@ def main(client, creative_set_id, companion_creative_id): # Create statement to select a single creative set by ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :creativeSetId') - .WithBindVariable('creativeSetId', long(creative_set_id))) + .WithBindVariable('creativeSetId', int(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -59,12 +59,12 @@ def main(client, creative_set_id, companion_creative_id): # Display results. for creative_set in creative_sets: - print (('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was updated.') - % (creative_set['id'], creative_set['masterCreativeId'], + print(('Creative set with ID "%s", master creative ID "%s", and ' + 'companion creative IDs {%s} was updated.') + % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) else: - print 'No creative sets found to update.' + print('No creative sets found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py index 0947f151..17a1ff03 100755 --- a/examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py index 1e3a7d9f..31c2beaa 100755 --- a/examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py index 695a1394..c2d064d2 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py @@ -54,8 +54,8 @@ def main(client, label_id): # Display results. for creative_wrapper in creative_wrappers: - print ('Creative wrapper with ID "%s" applying to label "%s" was ' - 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) + print('Creative wrapper with ID "%s" applying to label "%s" was ' + 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py index d6a21e51..8fb0ae2a 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py @@ -39,7 +39,7 @@ def main(client, label_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') - .WithBindVariable('labelId', long(label_id))) + .WithBindVariable('labelId', int(label_id))) creative_wrappers_deactivated = 0 @@ -50,11 +50,11 @@ def main(client, label_id): if 'results' in response and len(response['results']): # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID "%s" applying to label "%s" with ' - 'status "%s" will be deactivated.' % - (creative_wrapper['id'], - creative_wrapper['labelId'], - creative_wrapper['status'])) + print('Creative wrapper with ID "%s" applying to label "%s" with ' + 'status "%s" will be deactivated.' % + (creative_wrapper['id'], + creative_wrapper['labelId'], + creative_wrapper['status'])) # Perform action. result = creative_wrapper_service.performCreativeWrapperAction( {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) @@ -66,10 +66,10 @@ def main(client, label_id): # Display results. if creative_wrappers_deactivated > 0: - print ('Number of creative wrappers deactivated: %s' % - creative_wrappers_deactivated) + print('Number of creative wrappers deactivated: %s' % + creative_wrappers_deactivated) else: - print 'No creative wrappers were deactivated.' + print('No creative wrappers were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py index 57ef0f75..f581577d 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py index 1fc76c2c..752122e7 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py index 3e69db75..2aae91ca 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py @@ -42,7 +42,7 @@ def main(client, creative_wrapper_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', - long(creative_wrapper_id))) + int(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -60,11 +60,11 @@ def main(client, creative_wrapper_id): # Display results. for creative_wrapper in creative_wrappers: - print (('Creative wrapper with ID "%s" and wrapping order "%s" ' - 'was updated.') % (creative_wrapper['id'], - creative_wrapper['ordering'])) + print(('Creative wrapper with ID "%s" and wrapping order "%s" ' + 'was updated.') % (creative_wrapper['id'], + creative_wrapper['ordering'])) else: - print 'No creative wrappers found to update.' + print('No creative wrappers found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py index 15d56b00..5aaa0531 100755 --- a/examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py @@ -58,8 +58,8 @@ def main(client, custom_field_id): # Display results. for custom_field_option in custom_field_options: - print ('Custom field option with ID "%s" and name "%s" was created.' - % (custom_field_option['id'], custom_field_option['displayName'])) + print('Custom field option with ID "%s" and name "%s" was created.' + % (custom_field_option['id'], custom_field_option['displayName'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201811/custom_field_service/create_custom_fields.py index eac70950..6a826a29 100755 --- a/examples/ad_manager/v201811/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201811/custom_field_service/create_custom_fields.py @@ -57,8 +57,8 @@ def main(client): # Display results. for custom_field in custom_fields: - print ('Custom field with ID "%s" and name "%s" was created.' - % (custom_field['id'], custom_field['name'])) + print('Custom field with ID "%s" and name "%s" was created.' + % (custom_field['id'], custom_field['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py index c5c0dec2..61e2b342 100755 --- a/examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -51,8 +51,8 @@ def main(client): if 'results' in response and len(response['results']): # Display results. for custom_field in response['results']: - print ('Custom field with ID "%s" and name "%s" will' - ' be deactivated.' % (custom_field['id'], custom_field['name'])) + print('Custom field with ID "%s" and name "%s" will' + ' be deactivated.' % (custom_field['id'], custom_field['name'])) result = custom_field_service.performCustomFieldAction( {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: @@ -62,9 +62,9 @@ def main(client): break if custom_fields_deactivated > 0: - print 'Number of custom fields deactivated: %s' % custom_fields_deactivated + print('Number of custom fields deactivated: %s' % custom_fields_deactivated) else: - print 'No custom fields were deactivated.' + print('No custom fields were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py index 8cfe0088..2fb8a8ce 100755 --- a/examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py index c0f107bb..01cbc8f6 100755 --- a/examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py index 4d1f28bb..f45af2f5 100755 --- a/examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py @@ -127,10 +127,10 @@ def main(client, custom_field_id, drop_down_custom_field_id, '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) custom_field_value_strings.append(custom_field_value_string) - print ('Line item with ID "%s" set with custom field values %s.' - % (line_item['id'], ','.join(custom_field_value_strings))) + print('Line item with ID "%s" set with custom field values %s.' + % (line_item['id'], ','.join(custom_field_value_strings))) else: - print 'Line item or custom field not found.' + print('Line item or custom field not found.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201811/custom_field_service/update_custom_fields.py index fd89034b..419aca99 100755 --- a/examples/ad_manager/v201811/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201811/custom_field_service/update_custom_fields.py @@ -41,7 +41,7 @@ def main(client, custom_field_id): # Create statement to get a custom field. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :customFieldId') - .WithBindVariable('customFieldId', long(custom_field_id))) + .WithBindVariable('customFieldId', int(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -56,12 +56,12 @@ def main(client, custom_field_id): # Display results. for custom_field in custom_fields: - print (('Custom field with ID "%s", name "%s", and ' - 'description "%s" was updated.') - % (custom_field['id'], custom_field['name'], + print(('Custom field with ID "%s", name "%s", and ' + 'description "%s" was updated.') + % (custom_field['id'], custom_field['name'], custom_field['description'])) else: - print 'No custom fields found to update.' + print('No custom fields found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py index 0aad2f4d..020d6ed0 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -63,11 +63,11 @@ def main(client): # Display results. if keys: for key in keys: - print ('A custom targeting key with id "%s", name "%s", and display ' - 'name "%s" was created.' % (key['id'], key['name'], - key['displayName'])) + print('A custom targeting key with id "%s", name "%s", and display ' + 'name "%s" was created.' % (key['id'], key['name'], + key['displayName'])) else: - print 'No keys were created.' + print('No keys were created.') # Create custom targeting value objects. values = [ @@ -119,12 +119,12 @@ def main(client): # Display results. if values: for value in values: - print ('A custom targeting value with id "%s", belonging to key with id' - ' "%s", name "%s", and display name "%s" was created.' - % (value['id'], value['customTargetingKeyId'], value['name'], + print('A custom targeting value with id "%s", belonging to key with id' + ' "%s", name "%s", and display name "%s" was created.' + % (value['id'], value['customTargetingKeyId'], value['name'], value['displayName'])) else: - print 'No values were created.' + print('No values were created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py index facf35a1..771cc288 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py @@ -65,10 +65,10 @@ def main(client, key_name): break if deleted_custom_targeting_keys > 0: - print ('Number of custom targeting keys deleted: %s' - % deleted_custom_targeting_keys) + print('Number of custom targeting keys deleted: %s' + % deleted_custom_targeting_keys) else: - print 'No custom targeting keys were deleted.' + print('No custom targeting keys were deleted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py index 5585346b..4550b2eb 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py @@ -66,10 +66,10 @@ def main(client, key_id): break if deleted_custom_targeting_values > 0: - print ('Number of custom targeting values deleted: %s' - % deleted_custom_targeting_values) + print('Number of custom targeting values deleted: %s' + % deleted_custom_targeting_values) else: - print 'No custom targeting values were deleted.' + print('No custom targeting values were deleted.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 121b234a..fb8290c3 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -63,7 +63,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index a56c0b4e..906dbc68 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -65,7 +65,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py index 977ffcca..cc11ceec 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py @@ -34,7 +34,7 @@ def main(client, key_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :keyId') - .WithBindVariable('keyId', long(key_id)) + .WithBindVariable('keyId', int(key_id)) .Limit(1)) # Get custom targeting keys by statement. @@ -54,11 +54,11 @@ def main(client, key_id): # Display results. if keys: for key in keys: - print ('Custom targeting key with id "%s", name "%s", display name ' - '"%s", and type "%s" was updated.' - % (key['id'], key['name'], key['displayName'], key['type'])) + print('Custom targeting key with id "%s", name "%s", display name ' + '"%s", and type "%s" was updated.' + % (key['id'], key['name'], key['displayName'], key['type'])) else: - print 'No custom targeting keys were found to update.' + print('No custom targeting keys were found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py index 496e1be2..2a31f92c 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py @@ -34,7 +34,7 @@ def main(client, key_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('customTargetingKeyId = :keyId') - .WithBindVariable('keyId', long(key_id))) + .WithBindVariable('keyId', int(key_id))) while True: # Get custom targeting values by statement. @@ -54,15 +54,15 @@ def main(client, key_id): # Display results. for value in values: - print ('Custom targeting value with id "%s", name "%s", and display' - ' name "%s" was updated.' - % (value['id'], value['name'], value['displayName'])) + print('Custom targeting value with id "%s", name "%s", and display' + ' name "%s" was updated.' + % (value['id'], value['name'], value['displayName'])) statement.offset += statement.limit else: break if response['totalResultSetSize'] == 0: - print 'No custom targeting values were updated.' + print('No custom targeting values were updated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py index 47860fb1..26361f19 100755 --- a/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py +++ b/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py @@ -36,20 +36,20 @@ def main(client): exchange_rate = { 'currencyCode': 'AUD', 'direction': 'FROM_NETWORK', - 'exchangeRate': long(15000000000), + 'exchangeRate': int(15000000000), 'refreshRate': 'FIXED' } created_exchange_rate = exchange_rate_service.createExchangeRates( [exchange_rate])[0] - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was created.' % (created_exchange_rate['id'], - created_exchange_rate['currencyCode'], - created_exchange_rate['direction'], - (float(created_exchange_rate['exchangeRate']) / - 10000000000))) + print('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was created.' % (created_exchange_rate['id'], + created_exchange_rate['currencyCode'], + created_exchange_rate['direction'], + (float(created_exchange_rate['exchangeRate']) / + 10000000000))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py index af9fc376..bd5d641d 100755 --- a/examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py index d1830859..2351a26e 100755 --- a/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -47,7 +47,7 @@ def main(client, currency_code): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py index 59cace62..aa2a6d42 100755 --- a/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py @@ -35,7 +35,7 @@ def main(client, exchange_rate_id): # Create a statement to get an exchange rate by its ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') - .WithBindVariable('id', long(exchange_rate_id)) + .WithBindVariable('id', int(exchange_rate_id)) .Limit(1)) # Get rate cards by statement. @@ -46,23 +46,23 @@ def main(client, exchange_rate_id): exchange_rate = response['results'][0] # Update the exchange rate value to 1.5. - exchange_rate['exchangeRate'] = long(15000000000) + exchange_rate['exchangeRate'] = int(15000000000) exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) if exchange_rates: for exchange_rate in exchange_rates: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was updated.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + print('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was updated.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) else: - print 'No exchange rates were updated.' + print('No exchange rates were updated.') else: - print 'No exchange rates found to update.' + print('No exchange rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py index 96980310..bd8823a0 100755 --- a/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py @@ -176,17 +176,17 @@ def main(client, advertiser_id): contending_line_items = getattr(forecast, 'contendingLineItems', []) # Display results. - print '%s %s matched overall.' % (matched, unit_type) - print '%s%% %s available overall.' % (available_percent_overall, unit_type) - print '%d contending line items overall.' % len(contending_line_items) + print('%s %s matched overall.' % (matched, unit_type)) + print('%s%% %s available overall.' % (available_percent_overall, unit_type)) + print('%d contending line items overall.' % len(contending_line_items)) if possible: - print '%s%% %s possible overall.' % (possible_percent_overall, unit_type) + print('%s%% %s possible overall.' % (possible_percent_overall, unit_type)) if 'breakdowns' in forecast and len(forecast['breakdowns']): for breakdown in forecast['breakdowns']: - print 'For breakdown time period %s - %s:' % ( + print('For breakdown time period %s - %s:' % ( FormatSOAPDateTime(breakdown['startTime']), - FormatSOAPDateTime(breakdown['endTime'])) + FormatSOAPDateTime(breakdown['endTime']))) for breakdown_entry in breakdown['breakdownEntries']: matched = breakdown_entry['forecast']['matched'] available = breakdown_entry['forecast']['available'] @@ -194,13 +194,13 @@ def main(client, advertiser_id): if 'possible' in breakdown_entry['forecast'] else None) name = breakdown_entry['name'] if 'name' in breakdown_entry else None if name: - print '\tFor targeting breakdown named \'%s\'' % name + print('\tFor targeting breakdown named \'%s\'' % name) available_percent, possible_percent = CalculateForecastStats( matched, available, possible) - print '\t\t%s %s matched.' % (matched, unit_type) - print '\t\t%s%% %s available.' % (available_percent, unit_type) + print('\t\t%s %s matched.' % (matched, unit_type)) + print('\t\t%s%% %s available.' % (available_percent, unit_type)) if possible: - print '\t\t%s%% %s possible.' % (possible_percent, unit_type) + print('\t\t%s%% %s possible.' % (possible_percent, unit_type)) def FormatSOAPDateTime(value): diff --git a/examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py index ef58d378..89abd1f8 100755 --- a/examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py @@ -41,8 +41,8 @@ def main(client, line_item_id): # Get forecast for line item. forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) - matched = long(forecast['matchedUnits']) - available_units = long(forecast['availableUnits']) + matched = int(forecast['matchedUnits']) + available_units = int(forecast['availableUnits']) if matched > 0: available_percent = (float(available_units) / matched) * 100. @@ -52,13 +52,14 @@ def main(client, line_item_id): contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) + print('%s %s matched.' % (matched, forecast['unitType'].lower())) + print('%s%% %s available.' % ( + available_percent, forecast['unitType'].lower())) + print('%d contending line items.' % len(contending_line_items)) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + possible_percent = (int(forecast['possibleUnits'])/float(matched)) * 100. + print('%s%% %s possible' % (possible_percent, forecast['unitType'].lower())) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py index 2404c016..8d28987b 100755 --- a/examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py @@ -35,15 +35,15 @@ def main(client, line_item_id1, line_item_id2): # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( - [line_item_id1, line_item_id2], None) + [line_item_id1, line_item_id2], {'ignoredLineItemIds': []}) for single_forecast in forecast['lineItemDeliveryForecasts']: unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' - '%d %s predicted\n' % ( - single_forecast['lineItemId'], single_forecast['matchedUnits'], - unit_type, single_forecast['deliveredUnits'], unit_type, - single_forecast['predictedDeliveryUnits'], unit_type)) + print('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( + single_forecast['lineItemId'], single_forecast['matchedUnits'], + unit_type, single_forecast['deliveredUnits'], unit_type, + single_forecast['predictedDeliveryUnits'], unit_type)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/inventory_service/archive_ad_units.py b/examples/ad_manager/v201811/inventory_service/archive_ad_units.py index 1b8c147e..20306421 100755 --- a/examples/ad_manager/v201811/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/archive_ad_units.py @@ -41,7 +41,7 @@ def main(client, parent_id): # unit. statement = (ad_manager.StatementBuilder(version='v201811') .Where('parentId = :parentId or id = :parentId') - .WithBindVariable('parentId', long(parent_id))) + .WithBindVariable('parentId', int(parent_id))) ad_units_archived = 0 @@ -51,8 +51,8 @@ def main(client, parent_id): statement.ToStatement()) if 'results' in response and len(response['results']): for ad_unit in response['results']: - print ('Ad unit with ID "%s" and name "%s" will be archived.' - % (ad_unit['id'], ad_unit['name'])) + print('Ad unit with ID "%s" and name "%s" will be archived.' + % (ad_unit['id'], ad_unit['name'])) # Perform action. result = inventory_service.performAdUnitAction( {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) @@ -64,9 +64,9 @@ def main(client, parent_id): # Display results. if ad_units_archived > 0: - print 'Number of ad units archived: %s' % ad_units_archived + print('Number of ad units archived: %s' % ad_units_archived) else: - print 'No ad units were archived.' + print('No ad units were archived.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/inventory_service/create_ad_units.py b/examples/ad_manager/v201811/inventory_service/create_ad_units.py index 5e895033..37234564 100755 --- a/examples/ad_manager/v201811/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/create_ad_units.py @@ -61,8 +61,8 @@ def main(client, parent_id): # Display results. for ad_unit in ad_units: - print ('Ad unit with ID "%s" and name "%s" was created.' - % (ad_unit['id'], ad_unit['name'])) + print('Ad unit with ID "%s" and name "%s" was created.' + % (ad_unit['id'], ad_unit['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py index 6c762676..a018637f 100755 --- a/examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py @@ -101,8 +101,8 @@ def display_hierarchy_helper(root, parent_id_to_children, depth): parent_id_to_children: The overall map of parent ids to children. depth: The current depth. """ - print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), - root['name'], root['id']) + print('%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id'])) # Recurse for each child of this root that has children. for child in parent_id_to_children.get(root['id'], []): diff --git a/examples/ad_manager/v201811/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201811/inventory_service/get_all_ad_units.py index 74a6e595..9258d35d 100755 --- a/examples/ad_manager/v201811/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/get_all_ad_units.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py index 1be9801e..1201f131 100755 --- a/examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py @@ -49,7 +49,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/inventory_service/update_ad_units.py b/examples/ad_manager/v201811/inventory_service/update_ad_units.py index e491dfe7..187f197a 100755 --- a/examples/ad_manager/v201811/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201811/inventory_service/update_ad_units.py @@ -72,8 +72,8 @@ def main(client, ad_unit_id): ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], size['size']['height']) for size in ad_unit['adUnitSizes']] - print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' - % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + print('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' + % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/label_service/create_labels.py b/examples/ad_manager/v201811/label_service/create_labels.py index bc23bcbe..f863ba7a 100755 --- a/examples/ad_manager/v201811/label_service/create_labels.py +++ b/examples/ad_manager/v201811/label_service/create_labels.py @@ -46,8 +46,8 @@ def main(client): # Display results. for label in labels: - print ('Label with id "%s", name "%s", and types {%s} was found.' - % (label['id'], label['name'], ','.join(label['types']))) + print('Label with id "%s", name "%s", and types {%s} was found.' + % (label['id'], label['name'], ','.join(label['types']))) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/label_service/deactivate_labels.py b/examples/ad_manager/v201811/label_service/deactivate_labels.py index a13891c2..2035fbda 100755 --- a/examples/ad_manager/v201811/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201811/label_service/deactivate_labels.py @@ -41,8 +41,8 @@ def main(client): response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response and len(response['results']): for label in response['results']: - print ('Label with id "%s" and name "%s" will be ' - 'deactivated.' % (label['id'], label['name'])) + print('Label with id "%s" and name "%s" will be ' + 'deactivated.' % (label['id'], label['name'])) # Perform action. result = label_service.performLabelAction( {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) @@ -54,9 +54,9 @@ def main(client): # Display results. if labels_deactivated > 0: - print 'Number of labels deactivated: %s' % labels_deactivated + print('Number of labels deactivated: %s' % labels_deactivated) else: - print 'No labels were deactivated.' + print('No labels were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/label_service/get_active_labels.py b/examples/ad_manager/v201811/label_service/get_active_labels.py index e98c0204..60808671 100755 --- a/examples/ad_manager/v201811/label_service/get_active_labels.py +++ b/examples/ad_manager/v201811/label_service/get_active_labels.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/label_service/get_all_labels.py b/examples/ad_manager/v201811/label_service/get_all_labels.py index a14f966a..d8e0544c 100755 --- a/examples/ad_manager/v201811/label_service/get_all_labels.py +++ b/examples/ad_manager/v201811/label_service/get_all_labels.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/label_service/update_labels.py b/examples/ad_manager/v201811/label_service/update_labels.py index ef17d615..18f52663 100755 --- a/examples/ad_manager/v201811/label_service/update_labels.py +++ b/examples/ad_manager/v201811/label_service/update_labels.py @@ -34,7 +34,7 @@ def main(client, label_id): # Create a statement to select only active labels. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :labelId') - .WithBindVariable('labelId', long(label_id))) + .WithBindVariable('labelId', int(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -50,10 +50,10 @@ def main(client, label_id): labels = label_service.updateLabels(updated_labels) for label in labels: - print ('Label with id "%s" and name "%s" was updated.' - % (label['id'], label['name'])) + print('Label with id "%s" and name "%s" was updated.' + % (label['id'], label['name'])) else: - print 'No labels found to update.' + print('No labels found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py index 4ceebff4..ee40debf 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py @@ -45,11 +45,11 @@ def main(client, line_item_id, creative_ids): # Display results. if licas: for lica in licas: - print ('LICA with line item id "%s", creative id "%s", and ' - 'status "%s" was created.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) + print('LICA with line item id "%s", creative id "%s", and ' + 'status "%s" was created.' % + (lica['lineItemId'], lica['creativeId'], lica['status'])) else: - print 'No LICAs created.' + print('No LICAs created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py index 631b0609..ca558875 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py @@ -36,7 +36,7 @@ def main(client, line_item_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') - .WithBindVariable('lineItemId', long(line_item_id))) + .WithBindVariable('lineItemId', int(line_item_id))) num_deactivated_licas = 0 @@ -46,9 +46,9 @@ def main(client, line_item_id): statement.ToStatement()) if 'results' in response and len(response['results']): for lica in response['results']: - print ('LICA with line item id "%s", creative id "%s", and status' - ' "%s" will be deactivated.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) + print('LICA with line item id "%s", creative id "%s", and status' + ' "%s" will be deactivated.' % + (lica['lineItemId'], lica['creativeId'], lica['status'])) # Perform action. result = lica_service.performLineItemCreativeAssociationAction( @@ -62,9 +62,9 @@ def main(client, line_item_id): # Display results. if num_deactivated_licas > 0: - print 'Number of LICAs deactivated: %s' % num_deactivated_licas + print('Number of LICAs deactivated: %s' % num_deactivated_licas) else: - print 'No LICAs were deactivated.' + print('No LICAs were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py index 60fafdf2..8108c15d 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py index 34d13685..551ad705 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py @@ -51,7 +51,7 @@ def main(client, line_item_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py index 6bedb97d..82b0ed09 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py @@ -50,15 +50,15 @@ def main(client): # Display results. for lica in licas: - print ('LICA with line item id "%s", creative id "%s", and status ' - '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print('LICA with line item id "%s", creative id "%s", and status ' + '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], + lica['status'])) statement.offset += statement.limit else: break if response['totalResultSetSize'] == 0: - print 'No LICAs found to update.' + print('No LICAs found to update.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/line_item_service/activate_line_items.py b/examples/ad_manager/v201811/line_item_service/activate_line_items.py index 07c8713e..df2b50d6 100755 --- a/examples/ad_manager/v201811/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/activate_line_items.py @@ -39,7 +39,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) line_items_activated = 0 @@ -49,9 +49,9 @@ def main(client, order_id): statement.ToStatement()) if 'results' in response and len(response['results']): for line_item in response['results']: - print ('Line item with id "%s", belonging to order id "%s", and ' - 'name "%s" will be activated.' % - (line_item['id'], line_item['orderId'], line_item['name'])) + print('Line item with id "%s", belonging to order id "%s", and ' + 'name "%s" will be activated.' % + (line_item['id'], line_item['orderId'], line_item['name'])) # Perform action. result = line_item_service.performLineItemAction( @@ -64,9 +64,9 @@ def main(client, order_id): # Display results. if line_items_activated > 0: - print 'Number of line items activated: %s' % line_items_activated + print('Number of line items activated: %s' % line_items_activated) else: - print 'No line items were activated.' + print('No line items were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_service/create_line_items.py b/examples/ad_manager/v201811/line_item_service/create_line_items.py index c7e47097..bda701c9 100755 --- a/examples/ad_manager/v201811/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/create_line_items.py @@ -155,9 +155,9 @@ def main(client, order_id, targeted_placement_ids): # Display results. for line_item in line_items: - print ('Line item with id "%s", belonging to order id "%s", and named ' - '"%s" was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print('Line item with id "%s", belonging to order id "%s", and named ' + '"%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/line_item_service/create_video_line_item.py b/examples/ad_manager/v201811/line_item_service/create_video_line_item.py index cc04d6c8..97909aac 100755 --- a/examples/ad_manager/v201811/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v201811/line_item_service/create_video_line_item.py @@ -118,9 +118,9 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, line_item = line_item_service.createLineItem(line_item) # Display results. - print ('Video line item with id "%s", belonging to order id "%s", and ' - 'named "%s" was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print('Video line item with id "%s", belonging to order id "%s", and ' + 'named "%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/line_item_service/get_all_line_items.py b/examples/ad_manager/v201811/line_item_service/get_all_line_items.py index 767e4837..058eb99c 100755 --- a/examples/ad_manager/v201811/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/get_all_line_items.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py index 6334f9f1..3756b1f0 100755 --- a/examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py index f2b6b9b7..15792ebe 100755 --- a/examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py @@ -50,7 +50,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_service/pause_line_items.py b/examples/ad_manager/v201811/line_item_service/pause_line_items.py index 7ff28685..efa02d80 100755 --- a/examples/ad_manager/v201811/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/pause_line_items.py @@ -48,12 +48,12 @@ def main(client): result_set_size = page['totalResultSetSize'] # Iterate over individual results in the page. for line_item in page['results']: - print 'Pausing line item with ID %d' % line_item['id'] + print('Pausing line item with ID %d' % line_item['id']) # Update statement for next page. statement.offset += statement.limit should_continue = statement.offset < result_set_size - print 'Pausing %d line item(s)' % result_set_size + print('Pausing %d line item(s)' % result_set_size) if result_set_size > 0: statement.offset = None @@ -64,9 +64,9 @@ def main(client): {'xsi_type': 'PauseLineItems'}, statement.ToStatement()) if update_result and update_result['numChanges'] > 0: - print 'Updated %d line item(s)' % update_result['numChanges'] + print('Updated %d line item(s)' % update_result['numChanges']) else: - print 'No line items were paused' + print('No line items were paused') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201811/line_item_service/target_custom_criteria.py index 44d1b8be..84e6f570 100755 --- a/examples/ad_manager/v201811/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201811/line_item_service/target_custom_criteria.py @@ -83,7 +83,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Create statement to get the line item statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :lineItemId') - .WithBindVariable('lineItemId', long(line_item_id)) + .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) # Set custom criteria targeting on the line item. @@ -96,11 +96,11 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Display results. if line_item: - print ('Line item with id "%s" updated with custom criteria targeting:' - % line_item['id']) + print('Line item with id "%s" updated with custom criteria targeting:' + % line_item['id']) pprint.pprint(line_item['targeting']['customTargeting']) else: - print 'No line items were updated.' + print('No line items were updated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/line_item_service/update_line_items.py b/examples/ad_manager/v201811/line_item_service/update_line_items.py index cdde787a..2f06c8dd 100755 --- a/examples/ad_manager/v201811/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201811/line_item_service/update_line_items.py @@ -36,7 +36,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) - .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('orderId', int(order_id)) .WithBindVariable('deliveryRateType', 'EVENLY') .Limit(500)) @@ -58,14 +58,14 @@ def main(client, order_id): # Display results. if line_items: for line_item in line_items: - print ('Line item with id "%s", belonging to order id "%s", named ' - '"%s", and delivery rate "%s" was updated.' - % (line_item['id'], line_item['orderId'], line_item['name'], + print('Line item with id "%s", belonging to order id "%s", named ' + '"%s", and delivery rate "%s" was updated.' + % (line_item['id'], line_item['orderId'], line_item['name'], line_item['deliveryRateType'])) else: - print 'No line items were updated.' + print('No line items were updated.') else: - print 'No line items found to update.' + print('No line items found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py index 8ea6729e..5335d4f0 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py @@ -33,7 +33,7 @@ def main(client, live_stream_event_id): .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') - .WithBindVariable('id', long(live_stream_event_id)) + .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) live_stream_events_activated = 0 @@ -59,10 +59,10 @@ def main(client, live_stream_event_id): # Display results. if live_stream_events_activated > 0: - print '# of live stream events activated: %s' % ( - live_stream_events_activated) + print('# of live stream events activated: %s' % ( + live_stream_events_activated)) else: - print 'No live stream events were activated.' + print('No live stream events were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py index 0c81200b..553d38d2 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py index a3e1a13d..a12ce208 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py @@ -34,9 +34,9 @@ def main(client, session_ids): if session_ids: for session_id in session_ids: # Print out some information for each live stream event. - print 'Session with ID "%s" registered for monitoring.' % (session_id) + print('Session with ID "%s" registered for monitoring.' % (session_id)) - print '\nNumber of results found: %s' % session_ids.size + print('\nNumber of results found: %s' % session_ids.size) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py index eb179188..7722ee67 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py @@ -34,7 +34,7 @@ def main(client, live_stream_event_id): # Create statement object to only select matching live stream event. statement = (ad_manager.StatementBuilder(version='v201811') .Where(('Id = :id')) - .WithBindVariable('id', long(live_stream_event_id)) + .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) # Get live stream events by statement. diff --git a/examples/ad_manager/v201811/native_style_service/create_native_styles.py b/examples/ad_manager/v201811/native_style_service/create_native_styles.py index 9780d39b..7a3407e3 100755 --- a/examples/ad_manager/v201811/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201811/native_style_service/create_native_styles.py @@ -166,9 +166,9 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, # Display results. for native_style in native_styles: - print ('A Native style with ID "%s", name "%s", and creative template ID' - '"%d" was created.' % (native_style['id'], native_style['name'], - native_style['creativeTemplateId'])) + print('A Native style with ID "%s", name "%s", and creative template ID' + '"%d" was created.' % (native_style['id'], native_style['name'], + native_style['creativeTemplateId'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201811/native_style_service/get_all_native_styles.py index 1900c486..a037c34f 100755 --- a/examples/ad_manager/v201811/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201811/native_style_service/get_all_native_styles.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/network_service/get_all_networks.py b/examples/ad_manager/v201811/network_service/get_all_networks.py index 6442bac6..f431845e 100755 --- a/examples/ad_manager/v201811/network_service/get_all_networks.py +++ b/examples/ad_manager/v201811/network_service/get_all_networks.py @@ -31,7 +31,7 @@ def main(client): print('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) - print '\nNumber of results found: %s' % len(networks) + print('\nNumber of results found: %s' % len(networks)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/network_service/get_current_network.py b/examples/ad_manager/v201811/network_service/get_current_network.py index 0c9eb594..1bc7e9f0 100755 --- a/examples/ad_manager/v201811/network_service/get_current_network.py +++ b/examples/ad_manager/v201811/network_service/get_current_network.py @@ -27,8 +27,8 @@ def main(client): current_network = network_service.getCurrentNetwork() - print ("Current network has network code '%s' and display name '%s'." % - (current_network['networkCode'], current_network['displayName'])) + print("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/network_service/make_test_network.py b/examples/ad_manager/v201811/network_service/make_test_network.py index a85aa508..30398331 100755 --- a/examples/ad_manager/v201811/network_service/make_test_network.py +++ b/examples/ad_manager/v201811/network_service/make_test_network.py @@ -41,11 +41,11 @@ def main(client): network = network_service.makeTestNetwork() # Display results. - print ('Test network with network code "%s" and display name "%s" ' - 'created.' % (network['networkCode'], network['displayName'])) - print ('You may now sign in at ' - 'http://www.google.com/admanager/main?networkCode=%s' - % network['networkCode']) + print('Test network with network code "%s" and display name "%s" ' + 'created.' % (network['networkCode'], network['displayName'])) + print('You may now sign in at ' + 'http://www.google.com/admanager/main?networkCode=%s' + % network['networkCode']) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/order_service/approve_orders.py b/examples/ad_manager/v201811/order_service/approve_orders.py index edc36d5d..564c08ed 100755 --- a/examples/ad_manager/v201811/order_service/approve_orders.py +++ b/examples/ad_manager/v201811/order_service/approve_orders.py @@ -44,8 +44,8 @@ def main(client): if 'results' in response and len(response['results']): # Display results. for order in response['results']: - print ('Order with id "%s", name "%s", and status "%s" will be ' - 'approved.' % (order['id'], order['name'], order['status'])) + print('Order with id "%s", name "%s", and status "%s" will be ' + 'approved.' % (order['id'], order['name'], order['status'])) # Perform action. result = order_service.performOrderAction( {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) @@ -57,9 +57,9 @@ def main(client): # Display results. if orders_approved > 0: - print 'Number of orders approved: %s' % orders_approved + print('Number of orders approved: %s' % orders_approved) else: - print 'No orders were approved.' + print('No orders were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/order_service/create_orders.py b/examples/ad_manager/v201811/order_service/create_orders.py index 49facb27..f0eb3ee0 100755 --- a/examples/ad_manager/v201811/order_service/create_orders.py +++ b/examples/ad_manager/v201811/order_service/create_orders.py @@ -50,8 +50,8 @@ def main(client, company_id, salesperson_id, trafficker_id): # Display results. for order in orders: - print ('Order with id "%s" and name "%s" was created.' - % (order['id'], order['name'])) + print('Order with id "%s" and name "%s" was created.' + % (order['id'], order['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/order_service/get_all_orders.py b/examples/ad_manager/v201811/order_service/get_all_orders.py index 03a15c6c..b250b17c 100755 --- a/examples/ad_manager/v201811/order_service/get_all_orders.py +++ b/examples/ad_manager/v201811/order_service/get_all_orders.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201811/order_service/get_orders_starting_soon.py index 7fee3aae..d6915cb0 100755 --- a/examples/ad_manager/v201811/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201811/order_service/get_orders_starting_soon.py @@ -51,7 +51,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/order_service/update_orders.py b/examples/ad_manager/v201811/order_service/update_orders.py index 6fb03b32..51fd8548 100755 --- a/examples/ad_manager/v201811/order_service/update_orders.py +++ b/examples/ad_manager/v201811/order_service/update_orders.py @@ -34,7 +34,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :orderId') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -54,14 +54,14 @@ def main(client, order_id): # Display results. if orders: for order in orders: - print ('Order with id "%s", name "%s", advertiser id "%s", and ' - 'notes "%s" was updated.' - % (order['id'], order['name'], order['advertiserId'], + print('Order with id "%s", name "%s", advertiser id "%s", and ' + 'notes "%s" was updated.' + % (order['id'], order['name'], order['advertiserId'], order['notes'])) else: - print 'No orders were updated.' + print('No orders were updated.') else: - print 'No orders found to update.' + print('No orders found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/package_service/create_packages.py b/examples/ad_manager/v201811/package_service/create_packages.py index 097c8d68..6fa041de 100755 --- a/examples/ad_manager/v201811/package_service/create_packages.py +++ b/examples/ad_manager/v201811/package_service/create_packages.py @@ -51,8 +51,8 @@ def main(client): result = package_service.createPackages([package]) for new_package in result: - print ('A package with ID %d and name "%s" was created' % - (new_package['id'], new_package['name'])) + print('A package with ID %d and name "%s" was created' % + (new_package['id'], new_package['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py index c8eee245..f27c631b 100755 --- a/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py @@ -42,9 +42,9 @@ def main(client): package = query_result['results'][0] - print ('Package with ID %d will create proposal line items using product ' - 'package with ID %d.' % (package['id'], - package['productPackageId'])) + print('Package with ID %d will create proposal line items using product ' + 'package with ID %d.' % (package['id'], + package['productPackageId'])) # Remove limit and offset from statement. statement.limit = None @@ -56,10 +56,10 @@ def main(client): statement.ToStatement()) if result and result['numChanges'] > 0: - print ('Number of packages that proposal line items were created for: %d' % - result['numChanges']) + print('Number of packages that proposal line items were created for: %d' % + result['numChanges']) else: - print 'No proposal line items were created.' + print('No proposal line items were created.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/package_service/get_all_packages.py b/examples/ad_manager/v201811/package_service/get_all_packages.py index 6d8b0c25..1f58e38b 100755 --- a/examples/ad_manager/v201811/package_service/get_all_packages.py +++ b/examples/ad_manager/v201811/package_service/get_all_packages.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/package_service/get_in_progress_packages.py b/examples/ad_manager/v201811/package_service/get_in_progress_packages.py index 98f737ce..230b6e1c 100755 --- a/examples/ad_manager/v201811/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201811/package_service/get_in_progress_packages.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/placement_service/create_placements.py b/examples/ad_manager/v201811/placement_service/create_placements.py index 682b8d77..e0d6ad17 100755 --- a/examples/ad_manager/v201811/placement_service/create_placements.py +++ b/examples/ad_manager/v201811/placement_service/create_placements.py @@ -98,9 +98,9 @@ def main(client): ad_unit_ids = '' if 'targetedAdUnitIds' in placement: ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) - print ('A Placement with ID "%s", name "%s", and containing ad units ' - '{%s} was created.' % (placement['id'], placement['name'], - ad_unit_ids)) + print('A Placement with ID "%s", name "%s", and containing ad units ' + '{%s} was created.' % (placement['id'], placement['name'], + ad_unit_ids)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/placement_service/deactivate_placements.py b/examples/ad_manager/v201811/placement_service/deactivate_placements.py index 37f98910..4204fc4d 100755 --- a/examples/ad_manager/v201811/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201811/placement_service/deactivate_placements.py @@ -33,7 +33,7 @@ def main(client, placement_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :placementId') - .WithBindVariable('placementId', long(placement_id)) + .WithBindVariable('placementId', int(placement_id)) .Limit(1)) # Get placements by statement. @@ -41,9 +41,9 @@ def main(client, placement_id): statement.ToStatement()) for placement in placements: - print ('Placement with id "%s", name "%s", and status "%s" will be ' - 'deactivated.' % (placement['id'], placement['name'], - placement['status'])) + print('Placement with id "%s", name "%s", and status "%s" will be ' + 'deactivated.' % (placement['id'], placement['name'], + placement['status'])) # Perform action. result = placement_service.performPlacementAction( @@ -51,9 +51,9 @@ def main(client, placement_id): # Display results. if result and int(result['numChanges']) > 0: - print 'Number of placements deactivated: %s' % result['numChanges'] + print('Number of placements deactivated: %s' % result['numChanges']) else: - print 'No placements were deactivated.' + print('No placements were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/placement_service/get_active_placements.py b/examples/ad_manager/v201811/placement_service/get_active_placements.py index 0c97afa8..a98859b4 100755 --- a/examples/ad_manager/v201811/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201811/placement_service/get_active_placements.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/placement_service/get_all_placements.py b/examples/ad_manager/v201811/placement_service/get_all_placements.py index 7e214177..2c902f29 100755 --- a/examples/ad_manager/v201811/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201811/placement_service/get_all_placements.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/placement_service/update_placements.py b/examples/ad_manager/v201811/placement_service/update_placements.py index 72b0e564..772220a5 100755 --- a/examples/ad_manager/v201811/placement_service/update_placements.py +++ b/examples/ad_manager/v201811/placement_service/update_placements.py @@ -49,8 +49,8 @@ def main(client, placement_id): updated_placements = placement_service.updatePlacements([placement]) for placement in updated_placements: - print ('Placement with id "%s" and name "%s" was updated.' - % (placement['id'], placement['name'])) + print('Placement with id "%s" and name "%s" was updated.' + % (placement['id'], placement['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py index ef6f0b74..33f8e27f 100755 --- a/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py +++ b/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py @@ -73,9 +73,9 @@ def main(client, rate_card_id): # Display results. for premium_rate in premium_rates: - print ('A premium rate for "%s" was added to the rate card with ID' - ' of "%s".\n' - % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), + print('A premium rate for "%s" was added to the rate card with ID' + ' of "%s".\n' + % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), premium_rate['id'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py index 07dc9f1c..c41b0612 100755 --- a/examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py index 41ab9292..4a881d52 100755 --- a/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py @@ -47,7 +47,7 @@ def main(client, rate_card_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py index d35c09b6..b0b0875a 100755 --- a/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py @@ -36,7 +36,7 @@ def main(client, premium_rate_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) - .WithBindVariable('id', long(premium_rate_id)) + .WithBindVariable('id', int(premium_rate_id)) .Limit(1)) # Get the premium rate. @@ -72,13 +72,13 @@ def main(client, premium_rate_id): # Display results. if premium_rates: for premium_rate in premium_rates: - print ('Premium rate with ID "%s", associated with rate card id' - ' "%s" was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) + print('Premium rate with ID "%s", associated with rate card id' + ' "%s" was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) else: - print 'No premium rates were updated.' + print('No premium rates were updated.') else: - print 'No premium rates found to update.' + print('No premium rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py index 315128a8..469f4488 100755 --- a/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py +++ b/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py @@ -49,11 +49,11 @@ def main(client): [product_package_item]) for new_product_package_item in result: - print ('A product package with ID %d created from product ID %d ' - 'belonging to product package with ID %d was created.' % - (new_product_package_item['id'], - new_product_package_item['productId'], - new_product_package_item['productPackageId'])) + print('A product package with ID %d created from product ID %d ' + 'belonging to product package with ID %d was created.' % + (new_product_package_item['id'], + new_product_package_item['productId'], + new_product_package_item['productPackageId'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py index 702454b6..1930d17e 100755 --- a/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py @@ -44,7 +44,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py index ebb28eff..eb0f6dd0 100755 --- a/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py @@ -47,7 +47,7 @@ def main(client, product_package_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_package_service/create_product_packages.py b/examples/ad_manager/v201811/product_package_service/create_product_packages.py index 3937bc7f..d1c0e113 100755 --- a/examples/ad_manager/v201811/product_package_service/create_product_packages.py +++ b/examples/ad_manager/v201811/product_package_service/create_product_packages.py @@ -41,8 +41,8 @@ def main(client): result = product_package_service.createProductPackages([product_package]) for new_product_package in result: - print ('A product package with ID %d and name "%s" was created.' % - (new_product_package['id'], new_product_package['name'])) + print('A product package with ID %d and name "%s" was created.' % + (new_product_package['id'], new_product_package['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py index f3309bf7..74fdb0c4 100755 --- a/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201811/product_package_service/get_all_product_packages.py index f899dee0..205bce6a 100755 --- a/examples/ad_manager/v201811/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201811/product_package_service/get_all_product_packages.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_service/get_all_products.py b/examples/ad_manager/v201811/product_service/get_all_products.py index 3812027f..05ab107d 100755 --- a/examples/ad_manager/v201811/product_service/get_all_products.py +++ b/examples/ad_manager/v201811/product_service/get_all_products.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_service/get_products_for_product_template.py b/examples/ad_manager/v201811/product_service/get_products_for_product_template.py index b4abe0e3..e4a2735c 100755 --- a/examples/ad_manager/v201811/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201811/product_service/get_products_for_product_template.py @@ -44,7 +44,7 @@ def main(client, product_template_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_service/update_products.py b/examples/ad_manager/v201811/product_service/update_products.py index 03348c33..639c2268 100755 --- a/examples/ad_manager/v201811/product_service/update_products.py +++ b/examples/ad_manager/v201811/product_service/update_products.py @@ -34,7 +34,7 @@ def main(client, product_id): # Create statement object to select a single product by an ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') - .WithBindVariable('id', long(product_id)) + .WithBindVariable('id', int(product_id)) .Limit(1)) # Get products by statement. @@ -53,13 +53,13 @@ def main(client, product_id): # Display results. if products: for product in products: - print ('Product with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (product['id'], product['name'], product['notes'])) + print('Product with id "%s", name "%s", and ' + 'notes "%s" was updated.' + % (product['id'], product['name'], product['notes'])) else: - print 'No products were updated.' + print('No products were updated.') else: - print 'No products found to update.' + print('No products found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_template_service/activate_product_templates.py b/examples/ad_manager/v201811/product_template_service/activate_product_templates.py index 3487dd9e..39ea36da 100755 --- a/examples/ad_manager/v201811/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/activate_product_templates.py @@ -36,7 +36,7 @@ def main(client, product_template_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') - .WithBindVariable('id', long(product_template_id)) + .WithBindVariable('id', int(product_template_id)) .Limit(1)) product_templates_activated = 0 @@ -47,9 +47,9 @@ def main(client, product_template_id): statement.ToStatement()) if 'results' in response and len(response['results']): for product_template in response['results']: - print ('Product template with id "%s" and name "%s" will be ' - 'activated.' % (product_template['id'], - product_template['name'])) + print('Product template with id "%s" and name "%s" will be ' + 'activated.' % (product_template['id'], + product_template['name'])) # Perform action. result = product_template_service.performProductTemplateAction( @@ -62,10 +62,10 @@ def main(client, product_template_id): # Display results. if product_templates_activated > 0: - print ('Number of product templates ' - 'activated: %s' % product_templates_activated) + print('Number of product templates ' + 'activated: %s' % product_templates_activated) else: - print 'No product templates were activated.' + print('No product templates were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_template_service/create_product_templates.py b/examples/ad_manager/v201811/product_template_service/create_product_templates.py index 82c742bb..4cc43eba 100755 --- a/examples/ad_manager/v201811/product_template_service/create_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/create_product_templates.py @@ -99,8 +99,8 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A product template with ID "%s" and name "%s" was ' - 'created.' % (product_template['id'], product_template['name'])) + print('A product template with ID "%s" and name "%s" was ' + 'created.' % (product_template['id'], product_template['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py index 85b16406..8d2a791b 100755 --- a/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py @@ -80,9 +80,9 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A programmatic product template with ID "%s" and name "%s" ' - 'was created.' % (product_template['id'], - product_template['name'])) + print('A programmatic product template with ID "%s" and name "%s" ' + 'was created.' % (product_template['id'], + product_template['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201811/product_template_service/get_all_product_templates.py index 9193f01b..b7b42abe 100755 --- a/examples/ad_manager/v201811/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/get_all_product_templates.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py index 1ee08d56..d86efd38 100755 --- a/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/product_template_service/update_product_templates.py b/examples/ad_manager/v201811/product_template_service/update_product_templates.py index ad342535..5f9a16bb 100755 --- a/examples/ad_manager/v201811/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201811/product_template_service/update_product_templates.py @@ -36,7 +36,7 @@ def main(client, product_template_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') .OrderBy('id', ascending=True) - .WithBindVariable('id', long(product_template_id)) + .WithBindVariable('id', int(product_template_id)) .Limit(1)) # Get product templates by statement. @@ -80,12 +80,12 @@ def main(client, product_template_id): # Display results. if product_templates: for product_template in product_templates: - print ('Product template with id "%s" and name "%s" was ' - 'updated.' % (product_template['id'], product_template['name'])) + print('Product template with id "%s" and name "%s" was ' + 'updated.' % (product_template['id'], product_template['name'])) else: - print 'No product templates were updated.' + print('No product templates were updated.') else: - print 'No product templates found to update.' + print('No product templates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py index c9ad1de1..6e802668 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py @@ -36,7 +36,7 @@ def main(client, proposal_line_item_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') - .WithBindVariable('id', long(proposal_line_item_id)) + .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) proposal_line_items_archived = 0 @@ -47,11 +47,11 @@ def main(client, proposal_line_item_id): statement.ToStatement()) if 'results' in response and len(response['results']): for proposal_line_item in response['results']: - print ('Proposal line item with id "%s", ' - 'belonging to proposal id "%s", and ' - 'name "%s" will be archived.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", ' + 'belonging to proposal id "%s", and ' + 'name "%s" will be archived.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) # Perform action. result = proposal_line_item_service.performProposalLineItemAction( @@ -64,10 +64,10 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items_archived > 0: - print ('Number of proposal line items ' - 'archived: %s' % proposal_line_items_archived) + print('Number of proposal line items ' + 'archived: %s' % proposal_line_items_archived) else: - print 'No proposal line items were archived.' + print('No proposal line items were archived.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py index e9746071..29ed6054 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -91,10 +91,10 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item with id "%s", belonging to ' - 'proposal id "%s", and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Programmatic proposal line item with id "%s", belonging to ' + 'proposal id "%s", and named "%s" was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index db94be97..ebe2725c 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -99,11 +99,11 @@ def main(client, proposal_id, product_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item for non-sales management with id ' - '"%s", belonging to proposal id "%s", and named "%s" ' - 'was created.' % (proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Programmatic proposal line item for non-sales management with id ' + '"%s", belonging to proposal id "%s", and named "%s" ' + 'was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py index 58fd44ba..7a69ade4 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py @@ -92,10 +92,10 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Proposal line item with id "%s", belonging to proposal id "%s"' - ', and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", belonging to proposal id "%s"' + ', and named "%s" was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py index 523cc7ac..53f983bc 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 97d5c2f4..118e8ab1 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -45,7 +45,7 @@ def main(client, proposal_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py index 90be64cd..5206930d 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py @@ -37,7 +37,7 @@ def main(client, proposal_line_item_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') - .WithBindVariable('id', long(proposal_line_item_id)) + .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) # Get proposal line items by statement. @@ -56,14 +56,14 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items: for proposal_line_item in proposal_line_items: - print ('Line item with id "%s", belonging to proposal id "%s" and,' - ' named "%s" was updated.' % ( - proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Line item with id "%s", belonging to proposal id "%s" and,' + ' named "%s" was updated.' % ( + proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) else: - print 'No proposal line items were updated.' + print('No proposal line items were updated.') else: - print 'No proposal line items found to update.' + print('No proposal line items found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_service/create_proposals.py b/examples/ad_manager/v201811/proposal_service/create_proposals.py index af63f22a..c411d010 100755 --- a/examples/ad_manager/v201811/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201811/proposal_service/create_proposals.py @@ -67,8 +67,8 @@ def main(client, advertiser_id, primary_salesperson_id, # Display results. for proposal in proposals: - print ('Proposal with id "%s" and name "%s" was created.' - % (proposal['id'], proposal['name'])) + print('Proposal with id "%s" and name "%s" was created.' + % (proposal['id'], proposal['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/proposal_service/get_all_proposals.py b/examples/ad_manager/v201811/proposal_service/get_all_proposals.py index a899376a..aa4c1bd3 100755 --- a/examples/ad_manager/v201811/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201811/proposal_service/get_all_proposals.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py index c5bf17ba..76049d1c 100755 --- a/examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py @@ -47,7 +47,7 @@ def main(client, proposal_id): print('Marketplace comment with creation time "%s"and comment "%s" was ' 'found.\n' % (date_time_string, marketplace_comment['comment'])) - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py index 9ac8741c..9577e54c 100755 --- a/examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py index f315a70f..b318ef75 100755 --- a/examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py @@ -40,10 +40,10 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: - print ('Programmatic proposal with id "%s", name "%s", and status ' - '"%s" will be pushed to Marketplace.' % (proposal['id'], - proposal['name'], - proposal['status'])) + print('Programmatic proposal with id "%s", name "%s", and status ' + '"%s" will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) @@ -55,10 +55,10 @@ def main(client, proposal_id): # Display results. if proposals_pushed_to_marketplace > 0: - print ('\nNumber of programmatic proposals pushed to Marketplace: %s' - % proposals_pushed_to_marketplace) + print('\nNumber of programmatic proposals pushed to Marketplace: %s' + % proposals_pushed_to_marketplace) else: - print '\nNo programmatic proposals were pushed to Marketplace.' + print('\nNo programmatic proposals were pushed to Marketplace.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py index 3bcdc28d..59bab7c1 100755 --- a/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py @@ -42,9 +42,9 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: - print ('Proposal with id "%s", name "%s", and status "%s" will be' - ' approved.' % (proposal['id'], proposal['name'], - proposal['status'])) + print('Proposal with id "%s", name "%s", and status "%s" will be' + ' approved.' % (proposal['id'], proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) @@ -56,9 +56,9 @@ def main(client, proposal_id): # Display results. if proposals_approved > 0: - print '\nNumber of proposals approved: %s' % proposals_approved + print('\nNumber of proposals approved: %s' % proposals_approved) else: - print '\nNo proposals were approved.' + print('\nNo proposals were approved.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/proposal_service/update_proposals.py b/examples/ad_manager/v201811/proposal_service/update_proposals.py index e1495fb5..11fe2cf0 100755 --- a/examples/ad_manager/v201811/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201811/proposal_service/update_proposals.py @@ -34,7 +34,7 @@ def main(client, proposal_id): statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :proposalId') - .WithBindVariable('proposalId', long(proposal_id)) + .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) # Get proposals by statement. @@ -53,13 +53,13 @@ def main(client, proposal_id): # Display results. if proposals: for proposal in proposals: - print ('Proposal with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (proposal['id'], proposal['name'], proposal['internalNotes'])) + print('Proposal with id "%s", name "%s", and ' + 'notes "%s" was updated.' + % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: - print 'No proposals were updated.' + print('No proposals were updated.') else: - print 'No proposals found to update.' + print('No proposals found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py index 8fc54914..1267cd20 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py @@ -45,8 +45,8 @@ def main(client): line_items_file.close() ad_units_file.close() - print 'Saved line items to... %s' % line_items_file.name - print 'Saved ad units to... %s' % ad_units_file.name + print('Saved line items to... %s' % line_items_file.name) + print('Saved ad units to... %s' % ad_units_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py index 5a0c7edd..af6258a5 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py @@ -46,7 +46,7 @@ def main(client): report_downloader.DownloadPqlResultToCsv( browser_pql_query, browser_data_file) - print 'Saved browser data to... %s' % browser_data_file.name + print('Saved browser data to... %s' % browser_data_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py index c5e82130..64ec2d12 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py @@ -40,7 +40,7 @@ def main(client): programmatic_buyers_file.close() - print 'Saved programmatic buyers to... %s' % programmatic_buyers_file.name + print('Saved programmatic buyers to... %s' % programmatic_buyers_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py index 79cd8688..28395d20 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py @@ -26,7 +26,7 @@ GEO_TARGET_TYPE = 'City' -def main(client, geo_target_type): +def main(client): # Initialize a report downloader. report_downloader = client.GetDataDownloader(version='v201811') @@ -44,7 +44,7 @@ def main(client, geo_target_type): report_downloader.DownloadPqlResultToCsv( geo_pql_query, geo_data_file, {'type': geo_target_type}) - print 'Saved geo data to... %s' % geo_data_file.name + print('Saved geo data to... %s' % geo_data_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py index 8dc51f66..77001901 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py @@ -39,7 +39,7 @@ def main(client): report_downloader.DownloadPqlResultToCsv( line_items_pql_query, line_items_file) - print 'Saved line items to... %s' % line_items_file.name + print('Saved line items to... %s' % line_items_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py index 5f13eb9d..7aeab7e9 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py @@ -70,17 +70,17 @@ def main(client): statement.Where(pagination_query) statement.WithBindVariable('id', last_id) - print ('%d) %d changes prior to ID "%s" were found.\n' - % (i, rows_length, last_id)) + print('%d) %d changes prior to ID "%s" were found.\n' + % (i, rows_length, last_id)) keep_iterating = rows and len(rows) == statement.limit # Print out columns header - print ','.join(column_types) + print(','.join(column_types)) # Print out every row for row in total_rows: - print ConvertValueForCsv(row) + print(ConvertValueForCsv(row)) def ConvertValueForCsv(pql_value): diff --git a/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py index 2f40323f..955e9806 100755 --- a/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py +++ b/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py @@ -48,10 +48,10 @@ def main(client): result = rate_card_service.createRateCards([rate_card]) for new_rate_card in result: - print ('A rate card with ID %s, name "%s", and currency code "%s" ' - 'was created.' % (new_rate_card['id'], - new_rate_card['name'], - new_rate_card['currencyCode'])) + print('A rate card with ID %s, name "%s", and currency code "%s" ' + 'was created.' % (new_rate_card['id'], + new_rate_card['name'], + new_rate_card['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py index 5d528b2a..30352dc9 100755 --- a/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py index 53727cad..00d67c27 100755 --- a/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 02d8f420..38ee9f7a 100755 --- a/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -55,18 +55,18 @@ def main(client): result_set_size += page['totalResultSetSize'] # Iterate over individual results in the page. for line_item_report in page['results']: - print ('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source "%s", and reconciled volume %d was ' - 'found.' % (line_item_report['id'], - line_item_report['lineItemId'], - line_item_report['reconciliationSource'], - (line_item_report['reconciledVolume'] - if 'reconciledVolume' in line_item_report else 0))) + print('Reconciliation line item report with ID %d, line item ID %d, ' + 'reconciliation source "%s", and reconciled volume %d was ' + 'found.' % (line_item_report['id'], + line_item_report['lineItemId'], + line_item_report['reconciliationSource'], + (line_item_report['reconciledVolume'] + if 'reconciledVolume' in line_item_report else 0))) # Update statement for next page. statement.offset += statement.limit should_continue = statement.offset < result_set_size - print 'Number of results found: %d' % result_set_size + print('Number of results found: %d' % result_set_size) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 9669f8ac..729fb214 100755 --- a/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -56,10 +56,10 @@ def main(client): .updateReconciliationLineItemReports([line_item_report])) for updated_report in result: - print ('Reconciliation line item report with ID %d for line item ID %d was ' - 'updated, with manual volume %d' % (updated_report['id'], - updated_report['lineItemId'], - updated_report['manualVolume'])) + print('Reconciliation line item report with ID %d for line item ID %d was ' + 'updated, with manual volume %d' % (updated_report['id'], + updated_report['lineItemId'], + updated_report['manualVolume'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index d8794192..e15d03d2 100755 --- a/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -49,7 +49,7 @@ def main(client, reconciliation_report_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py index fcd69a5e..8859b7e2 100755 --- a/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -45,8 +45,8 @@ def main(client): report = page['results'][0] - print ('Reconciliation order report with ID %d will be submitted.' % - report['id']) + print('Reconciliation order report with ID %d will be submitted.' % + report['id']) # Remove limit and offset from statement. statement.limit = None @@ -59,10 +59,10 @@ def main(client): statement.ToStatement())) if result and result['numChanges'] > 0: - print ('Number of reconciliation order reports submitted: %d' % - result['numChanges']) + print('Number of reconciliation order reports submitted: %d' % + result['numChanges']) else: - print 'No reconciliation order reports were submitted.' + print('No reconciliation order reports were submitted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 29359781..9ad5a924 100755 --- a/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -34,7 +34,7 @@ def main(client, reconciliation_report_id): .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) - .WithBindVariable('reportId', long(reconciliation_report_id))) + .WithBindVariable('reportId', int(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. @@ -55,7 +55,7 @@ def main(client, reconciliation_report_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py index a4963d7f..ebdd112f 100755 --- a/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -63,10 +63,10 @@ def main(client): .updateReconciliationReportRows([row])) for updated_row in updated_rows: - print ('Reconciliation report row for line item ID %d and creative ID %d ' - 'was updated, with manual volume %d' % (updated_row['lineItemId'], - updated_row['creativeId'], - updated_row['manualVolume'])) + print('Reconciliation report row for line item ID %d and creative ID %d ' + 'was updated, with manual volume %d' % (updated_row['lineItemId'], + updated_row['creativeId'], + updated_row['manualVolume'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py index 522ad220..8a674ed2 100755 --- a/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py @@ -47,7 +47,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index bf450695..cbced6af 100755 --- a/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -54,7 +54,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201811/report_service/run_ad_exchange_report.py index fa543dab..aa1873c6 100755 --- a/examples/ad_manager/v201811/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201811/report_service/run_ad_exchange_report.py @@ -42,8 +42,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -57,8 +57,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/report_service/run_delivery_report.py b/examples/ad_manager/v201811/report_service/run_delivery_report.py index d19e34df..8e5d648a 100755 --- a/examples/ad_manager/v201811/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201811/report_service/run_delivery_report.py @@ -34,7 +34,7 @@ def main(client, order_id): # Create statement object to filter for an order. statement = (ad_manager.StatementBuilder(version='v201811') .Where('ORDER_ID = :id') - .WithBindVariable('id', long(order_id)) + .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports .Offset(None)) @@ -64,8 +64,8 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -79,8 +79,8 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/report_service/run_inventory_report.py b/examples/ad_manager/v201811/report_service/run_inventory_report.py index d4a8bebc..1cd8a119 100755 --- a/examples/ad_manager/v201811/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201811/report_service/run_inventory_report.py @@ -36,7 +36,7 @@ def main(client): # Set filter statement and bind value for reportQuery. statement = (ad_manager.StatementBuilder(version='v201811') .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') - .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .WithBindVariable('parentAdUnitId', int(root_ad_unit_id)) .Limit(None) # No limit or offset for reports .Offset(None)) @@ -58,8 +58,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -73,8 +73,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/report_service/run_reach_report.py b/examples/ad_manager/v201811/report_service/run_reach_report.py index fa7e834d..27a5aa16 100755 --- a/examples/ad_manager/v201811/report_service/run_reach_report.py +++ b/examples/ad_manager/v201811/report_service/run_reach_report.py @@ -39,8 +39,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -54,8 +54,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py index e5370573..26008980 100755 --- a/examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py @@ -59,8 +59,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) with tempfile.NamedTemporaryFile( suffix='.csv.gz', mode='wb', delete=False) as report_file: diff --git a/examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py index d5bfb86d..d2358865 100755 --- a/examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py @@ -35,7 +35,7 @@ def main(client, order_id): # Filter for line items of a given order. statement = (ad_manager.StatementBuilder(version='v201811') .Where('orderId = :orderId') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -73,8 +73,8 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -88,8 +88,8 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/report_service/run_sales_report.py b/examples/ad_manager/v201811/report_service/run_sales_report.py index 47feee9b..cce63190 100755 --- a/examples/ad_manager/v201811/report_service/run_sales_report.py +++ b/examples/ad_manager/v201811/report_service/run_sales_report.py @@ -40,8 +40,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -55,8 +55,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/report_service/run_saved_query.py b/examples/ad_manager/v201811/report_service/run_saved_query.py index 3a7f6f00..cf28e175 100755 --- a/examples/ad_manager/v201811/report_service/run_saved_query.py +++ b/examples/ad_manager/v201811/report_service/run_saved_query.py @@ -36,7 +36,7 @@ def main(client, saved_query_id): # Create statement object to filter for an order. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :id') - .WithBindVariable('id', long(saved_query_id)) + .WithBindVariable('id', int(saved_query_id)) .Limit(1)) response = report_service.getSavedQueriesByStatement( @@ -54,8 +54,8 @@ def main(client, saved_query_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -68,10 +68,10 @@ def main(client, saved_query_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) else: - print 'The query specified is not compatible with the API version.' + print('The query specified is not compatible with the API version.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 2da09a35..866fc7e8 100755 --- a/examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -44,9 +44,9 @@ def main(client): if 'results' in response and len(response['results']): # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: - print ('Suggested ad unit with id "%s", and number of requests "%s"' - ' will be approved.' % (suggested_ad_unit['id'], - suggested_ad_unit['numRequests'])) + print('Suggested ad unit with id "%s", and number of requests "%s"' + ' will be approved.' % (suggested_ad_unit['id'], + suggested_ad_unit['numRequests'])) # Approve suggested ad units. result = suggested_ad_unit_service.performSuggestedAdUnitAction( @@ -58,10 +58,10 @@ def main(client): break if num_approved_suggested_ad_units > 0: - print ('Number of suggested ad units approved: %s' % - num_approved_suggested_ad_units) + print('Number of suggested ad units approved: %s' % + num_approved_suggested_ad_units) else: - print 'No suggested ad units were approved.' + print('No suggested ad units were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py index b2bb3b38..9f5b82cd 100755 --- a/examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index ef252c65..04d0b40f 100755 --- a/examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client, num_requests): # Create a statement to select suggested ad units. statement = (ad_manager.StatementBuilder(version='v201811') .Where('numRequests >= :numRequests') - .WithBindVariable('numRequests', long(num_requests))) + .WithBindVariable('numRequests', int(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -46,7 +46,7 @@ def main(client, num_requests): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/team_service/create_teams.py b/examples/ad_manager/v201811/team_service/create_teams.py index 7c6d7740..c4d94003 100755 --- a/examples/ad_manager/v201811/team_service/create_teams.py +++ b/examples/ad_manager/v201811/team_service/create_teams.py @@ -51,8 +51,8 @@ def main(client): # Display results. for team in teams: - print ('Team with ID "%s" and name "%s" was created.' - % (team['id'], team['name'])) + print('Team with ID "%s" and name "%s" was created.' + % (team['id'], team['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/team_service/get_all_teams.py b/examples/ad_manager/v201811/team_service/get_all_teams.py index dc19a046..a22e0f79 100755 --- a/examples/ad_manager/v201811/team_service/get_all_teams.py +++ b/examples/ad_manager/v201811/team_service/get_all_teams.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/team_service/update_teams.py b/examples/ad_manager/v201811/team_service/update_teams.py index dbd6260c..b398cef3 100755 --- a/examples/ad_manager/v201811/team_service/update_teams.py +++ b/examples/ad_manager/v201811/team_service/update_teams.py @@ -39,7 +39,7 @@ def main(client, team_id): # Create a filter statement to select a single team by ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :teamId') - .WithBindVariable('teamId', long(team_id))) + .WithBindVariable('teamId', int(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -56,10 +56,10 @@ def main(client, team_id): # Display results. for team in teams: - print ('Team with id "%s" and name "%s" was updated.' - % (team['id'], team['name'])) + print('Team with id "%s" and name "%s" was updated.' + % (team['id'], team['name'])) else: - print 'No teams found to update.' + print('No teams found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_service/create_users.py b/examples/ad_manager/v201811/user_service/create_users.py index 0734e568..549c49ae 100755 --- a/examples/ad_manager/v201811/user_service/create_users.py +++ b/examples/ad_manager/v201811/user_service/create_users.py @@ -48,8 +48,8 @@ def main(client, email, name): # Display results. for user in users: - print ('User with id "%s", email "%s", and role "%s" was created.' - % (user['id'], user['email'], user['roleName'])) + print('User with id "%s", email "%s", and role "%s" was created.' + % (user['id'], user['email'], user['roleName'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/user_service/deactivate_users.py b/examples/ad_manager/v201811/user_service/deactivate_users.py index 4fa1926a..2876e1d3 100755 --- a/examples/ad_manager/v201811/user_service/deactivate_users.py +++ b/examples/ad_manager/v201811/user_service/deactivate_users.py @@ -35,18 +35,18 @@ def main(client, user_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) users = response['results'] if 'results' in response else [] for user in users: - print ('User with id "%s", email "%s", and status "%s" will be ' - 'deactivated.' - % (user['id'], user['email'], + print('User with id "%s", email "%s", and status "%s" will be ' + 'deactivated.' + % (user['id'], user['email'], {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) - print 'Number of users to be deactivated: %s' % len(users) + print('Number of users to be deactivated: %s' % len(users)) # Perform action. result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'}, @@ -54,9 +54,9 @@ def main(client, user_id): # Display results. if result and int(result['numChanges']) > 0: - print 'Number of users deactivated: %s' % result['numChanges'] + print('Number of users deactivated: %s' % result['numChanges']) else: - print 'No users were deactivated.' + print('No users were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_service/get_all_roles.py b/examples/ad_manager/v201811/user_service/get_all_roles.py index 442d35bd..38cfc420 100755 --- a/examples/ad_manager/v201811/user_service/get_all_roles.py +++ b/examples/ad_manager/v201811/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') + user_service = client.GetService('UserService', version='v201905') roles = user_service.getAllRoles() @@ -31,7 +31,7 @@ def main(client): print('Role with id "%s" and name "%s" was found.' % (role['id'], role['name'])) - print '\nNumber of results found: %s' % len(roles) + print('\nNumber of results found: %s' % len(roles)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_service/get_all_users.py b/examples/ad_manager/v201811/user_service/get_all_users.py index 620e4e8e..367eaf38 100755 --- a/examples/ad_manager/v201811/user_service/get_all_users.py +++ b/examples/ad_manager/v201811/user_service/get_all_users.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_service/get_current_user.py b/examples/ad_manager/v201811/user_service/get_current_user.py index 78e227ab..fa8163c4 100755 --- a/examples/ad_manager/v201811/user_service/get_current_user.py +++ b/examples/ad_manager/v201811/user_service/get_current_user.py @@ -27,10 +27,9 @@ def main(client): # Get current user. user = user_service.getCurrentUser() - print ('User with ID %d, name "%s", email "%s", and role "%s" ' - 'is the current user.' % ( - user.id, user.name, user.email, user.roleName - )) + print('User with ID %d, name "%s", email "%s", and role "%s" ' + 'is the current user.' % ( + user.id, user.name, user.email, user.roleName)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_service/get_user_by_email_address.py b/examples/ad_manager/v201811/user_service/get_user_by_email_address.py index 0017162b..f5fba570 100755 --- a/examples/ad_manager/v201811/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201811/user_service/get_user_by_email_address.py @@ -43,7 +43,7 @@ def main(client, email_address): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_service/update_users.py b/examples/ad_manager/v201811/user_service/update_users.py index 04c8d979..04a8fe1a 100755 --- a/examples/ad_manager/v201811/user_service/update_users.py +++ b/examples/ad_manager/v201811/user_service/update_users.py @@ -33,7 +33,7 @@ def main(client, user_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201811') .Where('id = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -46,10 +46,10 @@ def main(client, user_id): # Update users on server. users = user_service.updateUsers(users) for user in users: - print ('User with id "%s" and name "%s" was updated.' - % (user['id'], user['name'])) + print('User with id "%s" and name "%s" was updated.' + % (user['id'], user['name'])) else: - print 'No users found to update.' + print('No users found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py index f9bfab18..d4afaf0c 100755 --- a/examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py @@ -55,11 +55,11 @@ def main(client, team_id, user_ids): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('A user team association between user with ID "%s" and team with' - ' ID "%s"was created.' % (user_team_association['userId'], - user_team_association['teamId'])) + print('A user team association between user with ID "%s" and team with' + ' ID "%s"was created.' % (user_team_association['userId'], + user_team_association['teamId'])) else: - print 'No user team associations created.' + print('No user team associations created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py index c9fcb114..26f8c6fe 100755 --- a/examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py @@ -40,7 +40,7 @@ def main(client, user_id): # Create filter text to select user team associations by the user ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -48,11 +48,11 @@ def main(client, user_id): user_team_associations = response['results'] if 'results' in response else [] for user_team_association in user_team_associations: - print ('User team association between user with ID "%s" and team with ' - 'ID "%s" will be deleted.' % (user_team_association['userId'], - user_team_association['teamId'])) - print ('Number of teams that the user will be removed from: %s' % - len(user_team_associations)) + print('User team association between user with ID "%s" and team with ' + 'ID "%s" will be deleted.' % (user_team_association['userId'], + user_team_association['teamId'])) + print('Number of teams that the user will be removed from: %s' % + len(user_team_associations)) # Action doesn't require limit/offset statement.limit = None @@ -65,10 +65,10 @@ def main(client, user_id): # Display results. if result and int(result['numChanges']) > 0: - print ('Number of teams that the user was removed from: %s' - % result['numChanges']) + print('Number of teams that the user was removed from: %s' + % result['numChanges']) else: - print 'No user team associations were deleted.' + print('No user team associations were deleted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py index d20bf893..eb050f93 100755 --- a/examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py index 15596c51..9f251771 100755 --- a/examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py @@ -29,7 +29,7 @@ def main(client, user_id): # Create a statement to select user team associations. statement = (ad_manager.StatementBuilder(version='v201811') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -46,7 +46,7 @@ def main(client, user_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py index c8b53d70..d9ff8bd2 100755 --- a/examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py @@ -42,7 +42,7 @@ def main(client, user_id): # Create filter text to select user team associations by the user ID. statement = (ad_manager.StatementBuilder(version='v201811') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -63,13 +63,13 @@ def main(client, user_id): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('User team association between user with ID "%s" and team with' - ' ID "%s" was updated.' % (user_team_association['userId'], - user_team_association['teamId'])) + print('User team association between user with ID "%s" and team with' + ' ID "%s" was updated.' % (user_team_association['userId'], + user_team_association['teamId'])) else: - print 'No user team associations were updated.' + print('No user team associations were updated.') else: - print 'No user team associations found to update.' + print('No user team associations found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py index ac2673b8..3de7266b 100755 --- a/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py @@ -49,8 +49,8 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for workflow_approval_request in response['results']: - print ('Workflow approval request with id "%s" will be' - ' approved.' % workflow_approval_request['id']) + print('Workflow approval request with id "%s" will be' + ' approved.' % workflow_approval_request['id']) # Perform action. result = workflow_request_service.performWorkflowRequestAction( {'xsi_type': 'ApproveWorkflowApprovalRequests', @@ -64,10 +64,10 @@ def main(client, proposal_id): # Display results. if workflow_approval_requests_approved > 0: - print ('\nNumber of workflow approval requests approved: %s' % - workflow_approval_requests_approved) + print('\nNumber of workflow approval requests approved: %s' % + workflow_approval_requests_approved) else: - print '\nNo workflow approval requests were approved.' + print('\nNo workflow approval requests were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py index cd77e7fb..ee4ca81d 100755 --- a/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py index e01dba41..a007a631 100755 --- a/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py index cc6803a8..fdc12922 100755 --- a/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -49,11 +49,11 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id "%s" for %s ' - 'with id "%s" will be triggered.' % - (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + print('Workflow external condition request with id "%s" for %s ' + 'with id "%s" will be triggered.' % + (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) # Perform action. result = workflow_request_service.performWorkflowRequestAction( {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, @@ -67,10 +67,10 @@ def main(client, proposal_id): # Display results. if workflow_external_condition_requests_triggered > 0: - print ('\nNumber of workflow external condition requests triggered: %s' % - workflow_external_condition_requests_triggered) + print('\nNumber of workflow external condition requests triggered: %s' % + workflow_external_condition_requests_triggered) else: - print '\nNo workflow external condition requests were triggered.' + print('\nNo workflow external condition requests were triggered.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201902/activity_group_service/create_activity_groups.py index 55075af0..242ea9e5 100755 --- a/examples/ad_manager/v201902/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201902/activity_group_service/create_activity_groups.py @@ -62,8 +62,8 @@ def main(client, advertiser_company_id): # Display results. for activity_group in activity_groups: - print ('Activity group with ID "%s" and name "%s" was created.' - % (activity_group['id'], activity_group['name'])) + print('Activity group with ID "%s" and name "%s" was created.' + % (activity_group['id'], activity_group['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py index da31eefe..c438b46d 100755 --- a/examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py index c77ec1c5..dd6539d3 100755 --- a/examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201902/activity_group_service/update_activity_groups.py index 7f7bd747..bc2c6e3b 100755 --- a/examples/ad_manager/v201902/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201902/activity_group_service/update_activity_groups.py @@ -42,7 +42,7 @@ def main(client, activity_group_id, advertiser_company_id): # Create statement object to select a single activity groups by ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :activityGroupId') - .WithBindVariable('activityGroupId', long(activity_group_id)) + .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) # Get activity groups by statement. @@ -58,10 +58,10 @@ def main(client, activity_group_id, advertiser_company_id): updated_activity_groups) for activity_group in activity_groups: - print (('Activity group with ID "%s" and name "%s" was updated.') - % (activity_group['id'], activity_group['name'])) + print(('Activity group with ID "%s" and name "%s" was updated.') + % (activity_group['id'], activity_group['name'])) else: - print 'No activity groups found to update.' + print('No activity groups found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/activity_service/create_activities.py b/examples/ad_manager/v201902/activity_service/create_activities.py index d2baa78c..514a5763 100755 --- a/examples/ad_manager/v201902/activity_service/create_activities.py +++ b/examples/ad_manager/v201902/activity_service/create_activities.py @@ -59,8 +59,8 @@ def main(client, activity_group_id): # Display results. for activity in activities: - print ('An activity with ID "%s", name "%s", and type "%s" was ' - 'created.' % (activity['id'], activity['name'], activity['type'])) + print('An activity with ID "%s", name "%s", and type "%s" was ' + 'created.' % (activity['id'], activity['name'], activity['type'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/activity_service/get_active_activities.py b/examples/ad_manager/v201902/activity_service/get_active_activities.py index b65358c3..676b02d3 100755 --- a/examples/ad_manager/v201902/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201902/activity_service/get_active_activities.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/activity_service/get_all_activities.py b/examples/ad_manager/v201902/activity_service/get_all_activities.py index de891c36..d5210098 100755 --- a/examples/ad_manager/v201902/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201902/activity_service/get_all_activities.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/activity_service/update_activities.py b/examples/ad_manager/v201902/activity_service/update_activities.py index 3a5c27db..a6087812 100755 --- a/examples/ad_manager/v201902/activity_service/update_activities.py +++ b/examples/ad_manager/v201902/activity_service/update_activities.py @@ -40,7 +40,7 @@ def main(client, activity_id): # Create statement object to select one activity by ID to update. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :activityId') - .WithBindVariable('activityId', long(activity_id)) + .WithBindVariable('activityId', int(activity_id)) .Limit(1)) # Get activities by statement. @@ -56,10 +56,10 @@ def main(client, activity_id): activities = activity_service.updateActivities(updated_activities) for updated_activity in activities: - print (('Activity with ID "%s" and name "%s" was updated.') - % (updated_activity['id'], updated_activity['name'])) + print(('Activity with ID "%s" and name "%s" was updated.') + % (updated_activity['id'], updated_activity['name'])) else: - print 'No activities found to update.' + print('No activities found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py index b1e9bcec..3628df37 100755 --- a/examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py @@ -84,10 +84,10 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): audience_segment_service.createAudienceSegments(audience_segment)) for created_audience_segment in audience_segments: - print ('An audience segment with ID "%s", name "%s", and type "%s" ' - 'was created.' % (created_audience_segment['id'], - created_audience_segment['name'], - created_audience_segment['type'])) + print('An audience segment with ID "%s", name "%s", and type "%s" ' + 'was created.' % (created_audience_segment['id'], + created_audience_segment['name'], + created_audience_segment['type'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py index 5f0e6ea2..e5e09663 100755 --- a/examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py index 9354b883..36fad0cb 100755 --- a/examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py @@ -44,7 +44,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py index 5b567d35..9c4da083 100755 --- a/examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py @@ -36,7 +36,7 @@ def main(client, audience_segment_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', - long(audience_segment_id)) + int(audience_segment_id)) .WithBindVariable('type', 'FIRST_PARTY') .Limit(1)) @@ -47,7 +47,7 @@ def main(client, audience_segment_id): segments = response['results'] for segment in segments: - print ( + print( 'Audience segment with id "%s" and name "%s" will be populated.' % (segment['id'], segment['name'])) @@ -59,10 +59,10 @@ def main(client, audience_segment_id): audience_segment_service.performAudienceSegmentAction( action, statement.ToStatement())) - print ('%s audience segment populated' % - populated_audience_segments['numChanges']) + print('%s audience segment populated' % + populated_audience_segments['numChanges']) else: - print 'No Results Found' + print('No Results Found') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py index ae0509ae..de7b4383 100755 --- a/examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py @@ -35,7 +35,7 @@ def main(client, audience_segment_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', - long(audience_segment_id)) + int(audience_segment_id)) .WithBindVariable('type', 'FIRST_PARTY') .Limit(1)) @@ -46,8 +46,8 @@ def main(client, audience_segment_id): if 'results' in response and len(response['results']): updated_audience_segments = [] for audience_segment in response['results']: - print ('Audience segment with id "%s" and name "%s" will be updated.' - % (audience_segment['id'], audience_segment['name'])) + print('Audience segment with id "%s" and name "%s" will be updated.' + % (audience_segment['id'], audience_segment['name'])) audience_segment['membershipExpirationDays'] = '180' updated_audience_segments.append(audience_segment) @@ -56,10 +56,10 @@ def main(client, audience_segment_id): updated_audience_segments) for audience_segment in audience_segments: - print ('Audience segment with id "%s" and name "%s" was updated' % - (audience_segment['id'], audience_segment['name'])) + print('Audience segment with id "%s" and name "%s" was updated' % + (audience_segment['id'], audience_segment['name'])) else: - print 'No audience segment found to update.' + print('No audience segment found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py index 65b79f4f..c96a7680 100755 --- a/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py @@ -53,10 +53,10 @@ def main(client, product_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product base rate with ID "%s" and rate \'%.2f\' %s was ' - 'created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) + print('A product base rate with ID "%s" and rate \'%.2f\' %s was ' + 'created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py index a4b219cf..7aeaeec3 100755 --- a/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py @@ -54,10 +54,10 @@ def main(client): result = base_rate_service.createBaseRates([product_package_item_base_rate]) for new_base_rate in result: - print ('A product package item base rate with ID %d and rate %f %s ' - 'was created.' % (new_base_rate['id'], - new_base_rate['microAmount'], - new_base_rate['currencyCode'])) + print('A product package item base rate with ID %d and rate %f %s ' + 'was created.' % (new_base_rate['id'], + new_base_rate['microAmount'], + new_base_rate['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py index 0e1c7b9d..bbe9fee2 100755 --- a/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py @@ -53,10 +53,10 @@ def main(client, product_template_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product template base rate with ID "%s" and rate \'%.2f\' %s' - ' was created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) + print('A product template base rate with ID "%s" and rate \'%.2f\' %s' + ' was created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py index 2ec2bbce..24e0eb23 100755 --- a/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py index 3e6deb9a..a86bdce0 100755 --- a/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py @@ -46,7 +46,7 @@ def main(client, rate_card_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/base_rate_service/update_base_rates.py b/examples/ad_manager/v201902/base_rate_service/update_base_rates.py index a7155c07..ad594629 100755 --- a/examples/ad_manager/v201902/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201902/base_rate_service/update_base_rates.py @@ -36,7 +36,7 @@ def main(client, base_rate_id): .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) - .WithBindVariable('id', long(base_rate_id))) + .WithBindVariable('id', int(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( @@ -60,15 +60,15 @@ def main(client, base_rate_id): # Display results. if base_rates: for base_rate in base_rates: - print ('Base rate with ID "%s" and type "%s" belonging to ' - 'rate card ID "%s" was updated.' % ( - base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) + print('Base rate with ID "%s" and type "%s" belonging to ' + 'rate card ID "%s" was updated.' % ( + base_rate['id'], + ad_manager.AdManagerClassType(base_rate), + base_rate['rateCardId'])) else: - print 'No base rates were updated.' + print('No base rates were updated.') else: - print 'No base rates found to update.' + print('No base rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py index 9f262ec5..2debaeb6 100755 --- a/examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/company_service/create_companies.py b/examples/ad_manager/v201902/company_service/create_companies.py index 8b37ee46..831c6ec0 100755 --- a/examples/ad_manager/v201902/company_service/create_companies.py +++ b/examples/ad_manager/v201902/company_service/create_companies.py @@ -53,8 +53,8 @@ def main(client): # Display results. for company in companies: - print ('Company with ID "%s", name "%s", and type "%s" was created.' - % (company['id'], company['name'], company['type'])) + print('Company with ID "%s", name "%s", and type "%s" was created.' + % (company['id'], company['name'], company['type'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/company_service/get_advertisers.py b/examples/ad_manager/v201902/company_service/get_advertisers.py index 1b38f940..c9f5a166 100755 --- a/examples/ad_manager/v201902/company_service/get_advertisers.py +++ b/examples/ad_manager/v201902/company_service/get_advertisers.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/company_service/get_all_companies.py b/examples/ad_manager/v201902/company_service/get_all_companies.py index 60f73ad5..83f439ea 100755 --- a/examples/ad_manager/v201902/company_service/get_all_companies.py +++ b/examples/ad_manager/v201902/company_service/get_all_companies.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/company_service/update_companies.py b/examples/ad_manager/v201902/company_service/update_companies.py index 42339553..293c0a58 100755 --- a/examples/ad_manager/v201902/company_service/update_companies.py +++ b/examples/ad_manager/v201902/company_service/update_companies.py @@ -40,7 +40,7 @@ def main(client, company_id): # Create statement object to only select a single company by ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') - .WithBindVariable('id', long(company_id)) + .WithBindVariable('id', int(company_id)) .Limit(1)) # Get companies by statement. @@ -57,11 +57,11 @@ def main(client, company_id): # Display results. for company in companies: - print (('Company with ID "%s", name "%s", and comment "%s"' - ' was updated.') - % (company['id'], company['name'], company['comment'])) + print(('Company with ID "%s", name "%s", and comment "%s"' + ' was updated.') + % (company['id'], company['name'], company['comment'])) else: - print 'No companies found to update.' + print('No companies found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/contact_service/create_contacts.py b/examples/ad_manager/v201902/contact_service/create_contacts.py index ea14866f..1b9357cb 100755 --- a/examples/ad_manager/v201902/contact_service/create_contacts.py +++ b/examples/ad_manager/v201902/contact_service/create_contacts.py @@ -62,8 +62,8 @@ def main(client, advertiser_company_id, agency_company_id): # Display results. for contact in contacts: - print ('Contact with ID "%s" name "%s" was created.' - % (contact['id'], contact['name'])) + print('Contact with ID "%s" name "%s" was created.' + % (contact['id'], contact['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/contact_service/get_all_contacts.py b/examples/ad_manager/v201902/contact_service/get_all_contacts.py index 65fbde5d..da3266d6 100755 --- a/examples/ad_manager/v201902/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201902/contact_service/get_all_contacts.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py index aed4d4d1..db4ccd50 100755 --- a/examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/contact_service/update_contacts.py b/examples/ad_manager/v201902/contact_service/update_contacts.py index ee3e868a..ff8f5bb9 100755 --- a/examples/ad_manager/v201902/contact_service/update_contacts.py +++ b/examples/ad_manager/v201902/contact_service/update_contacts.py @@ -40,7 +40,7 @@ def main(client, contact_id): # Create statement object to select the single contact by ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') - .WithBindVariable('id', long(contact_id)) + .WithBindVariable('id', int(contact_id)) .Limit(1)) # Get contacts by statement. @@ -58,11 +58,11 @@ def main(client, contact_id): # Display results. for contact in contacts: - print (('Contact with ID "%s", name "%s", and address "%s" ' - 'was updated.') - % (contact['id'], contact['name'], contact['address'])) + print(('Contact with ID "%s", name "%s", and address "%s" ' + 'was updated.') + % (contact['id'], contact['name'], contact['address'])) else: - print 'No contacts found to update.' + print('No contacts found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py deleted file mode 100755 index e93ff004..00000000 --- a/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the IDs of the custom targeting keys for the hierarchy. -HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' -HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201902') - - hierarchy_level_1 = { - 'customTargetingKeyId': hierarchy_level_one_key_id, - 'hierarchyLevel': '1' - } - - hierarchy_level_2 = { - 'customTargetingKeyId': hierarchy_level_two_key_id, - 'hierarchyLevel': '2' - } - - hierarchy_levels = [hierarchy_level_1, hierarchy_level_2] - - # Create content metadata key hierarchy object. - content_metadata_key_hierarchy = { - 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(), - 'hierarchyLevels': hierarchy_levels - } - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy])) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id "%s" and name "%s"' - ' was created.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, HIERARCHY_LEVEL_ONE_KEY_ID, - HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py deleted file mode 100755 index 9ea30768..00000000 --- a/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 content metadata key hierarchies. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201902') - - # Create a statement to select content metadata key hierarchies. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of content metadata key hierarchies at a time, - # paging through until all content metadata key hierarchies have been - # retrieved. - while True: - response = ( - content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for content_metadata_key_hierarchy in response['results']: - # Print out some information for each content metadata key hierarchy. - print('Content metadata key hierarchy with ID "%d" and name "%s" was ' - 'found.\n' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py deleted file mode 100755 index eccfce7d..00000000 --- a/examples/ad_manager/v201902/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the content metadata key hierarchy to update. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') -# Set the ID of the custom targeting key to be added as a hierarchy level. -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201902') - - # Create a query to select a single content metadata key hierarchy. - - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) - .Limit(1)) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement()))[0] - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - if content_metadata_key_hierarchies: - content_metadata_key_hierarchy = content_metadata_key_hierarchies[0] - - # Update the content metadata key hierarchy by adding a hierarchy level. - hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels'] - - hierarchy_level = { - 'customTargetingKeyId': custom_targeting_key_id, - 'hierarchyLevel': str(len(hierarchy_levels) + 1) - } - - content_metadata_key_hierarchy['hierarchyLevels'] = ( - hierarchy_levels.append(hierarchy_level)) - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies)) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id "%s" and name "%s"' - ' was updated.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - else: - print 'No content metadata key hierarchies were found' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID, - CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201902/content_service/get_all_content.py b/examples/ad_manager/v201902/content_service/get_all_content.py index db6c8e39..259da022 100755 --- a/examples/ad_manager/v201902/content_service/get_all_content.py +++ b/examples/ad_manager/v201902/content_service/get_all_content.py @@ -35,12 +35,12 @@ def main(client): for content in response['results']: # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % - (content['id'], content['name'])) + (content['id'], content['name'].encode('utf-8'))) statement.offset += statement.limit else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_service/copy_image_creatives.py b/examples/ad_manager/v201902/creative_service/copy_image_creatives.py index 5f1cb376..73fbf01b 100755 --- a/examples/ad_manager/v201902/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201902/creative_service/copy_image_creatives.py @@ -47,11 +47,11 @@ def main(client): image_creative['name'] = 'Copy of %s' % image_creative['name'] result = creative_service.createCreatives([image_creative])[0] - print ('A creative with ID %d, name "%s", and type "%s" was created and ' - 'can be previewed at: %s' % (result['id'], - result['name'], - ad_manager.AdManagerClassType(result), - result['previewUrl'])) + print('A creative with ID %d, name "%s", and type "%s" was created and ' + 'can be previewed at: %s' % (result['id'], + result['name'], + ad_manager.AdManagerClassType(result), + result['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_service/create_creative_from_template.py b/examples/ad_manager/v201902/creative_service/create_creative_from_template.py index f3dca2ca..0796ce2e 100755 --- a/examples/ad_manager/v201902/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201902/creative_service/create_creative_from_template.py @@ -100,9 +100,9 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Template creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Template creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_service/create_creatives.py b/examples/ad_manager/v201902/creative_service/create_creatives.py index 720383ff..0c8685ad 100755 --- a/examples/ad_manager/v201902/creative_service/create_creatives.py +++ b/examples/ad_manager/v201902/creative_service/create_creatives.py @@ -79,9 +79,9 @@ def main(client, advertiser_id): # Display results. for creative in creatives: - print ('Image creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Image creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_service/create_custom_creative.py b/examples/ad_manager/v201902/creative_service/create_custom_creative.py index 2af78804..e04c072f 100755 --- a/examples/ad_manager/v201902/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201902/creative_service/create_custom_creative.py @@ -77,9 +77,9 @@ def main(client, advertiser_id): # Display results. if creatives: creative = creatives[0] - print ('Template creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Template creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_service/create_native_creative.py b/examples/ad_manager/v201902/creative_service/create_native_creative.py index 71386088..8eeadbd7 100755 --- a/examples/ad_manager/v201902/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201902/creative_service/create_native_creative.py @@ -29,8 +29,8 @@ section of our README. """ -import urllib2 import uuid +from urllib.request import urlopen # Import appropriate modules from the client library. from googleads import ad_manager @@ -50,9 +50,9 @@ def main(client, advertiser_id): # Use the system defined native app install creative template. creative_template_id = '10004400' - image_data = urllib2.urlopen(ICON_URL).read() + image_data = urlopen(ICON_URL).read() - app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() + app_icon_data = urlopen(APP_ICON_SMALL).read() # Create creative from templates. creative = { @@ -122,9 +122,9 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Native creative with id "%s" and name "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['previewUrl'])) + print('Native creative with id "%s" and name "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/creative_service/get_all_creatives.py b/examples/ad_manager/v201902/creative_service/get_all_creatives.py index 87b9665e..9e2a7d34 100755 --- a/examples/ad_manager/v201902/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201902/creative_service/get_all_creatives.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_service/get_image_creatives.py b/examples/ad_manager/v201902/creative_service/get_image_creatives.py index 0e5a610b..49eb1342 100755 --- a/examples/ad_manager/v201902/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201902/creative_service/get_image_creatives.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_service/update_creatives.py b/examples/ad_manager/v201902/creative_service/update_creatives.py index 5c41d77c..ac8182bc 100755 --- a/examples/ad_manager/v201902/creative_service/update_creatives.py +++ b/examples/ad_manager/v201902/creative_service/update_creatives.py @@ -40,7 +40,7 @@ def main(client, image_creative_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') - .WithBindVariable('id', long(image_creative_id)) + .WithBindVariable('id', int(image_creative_id)) .Limit(1)) # Get creatives by statement. @@ -59,10 +59,10 @@ def main(client, image_creative_id): # Display results. for creative in creatives: - print ('Image creative with id "%s" and destination URL "%s" was ' - 'updated.' % (creative['id'], creative['destinationUrl'])) + print('Image creative with id "%s" and destination URL "%s" was ' + 'updated.' % (creative['id'], creative['destinationUrl'])) else: - print 'No creatives found to update.' + print('No creatives found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py index fe1bae85..752eb61c 100755 --- a/examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py @@ -46,8 +46,8 @@ def main(client, creative_set_id, line_item_id): lica = lica_service.createLineItemCreativeAssociations([lica]) # Display results. - print (('LICA with line item ID "%s" and creative set ID "%s" was ' - 'created.') % (lica['lineItemId'], lica['creativeSetId'])) + print(('LICA with line item ID "%s" and creative set ID "%s" was ' + 'created.') % (lica['lineItemId'], lica['creativeSetId'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/creative_set_service/create_creative_set.py b/examples/ad_manager/v201902/creative_set_service/create_creative_set.py index bd576d69..db8a7eb5 100755 --- a/examples/ad_manager/v201902/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201902/creative_set_service/create_creative_set.py @@ -50,9 +50,9 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: - print (('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was created.') - % (creative_set['id'], creative_set['masterCreativeId'], + print(('Creative set with ID "%s", master creative ID "%s", and ' + 'companion creative IDs {%s} was created.') + % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py index 15102e7c..f636f81b 100755 --- a/examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py index c964c417..80b8bbee 100755 --- a/examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py @@ -45,7 +45,7 @@ def main(client, master_creative_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_set_service/update_creative_set.py b/examples/ad_manager/v201902/creative_set_service/update_creative_set.py index bb2943d9..266aeb27 100755 --- a/examples/ad_manager/v201902/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201902/creative_set_service/update_creative_set.py @@ -42,7 +42,7 @@ def main(client, creative_set_id, companion_creative_id): # Create statement to select a single creative set by ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :creativeSetId') - .WithBindVariable('creativeSetId', long(creative_set_id))) + .WithBindVariable('creativeSetId', int(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -59,12 +59,12 @@ def main(client, creative_set_id, companion_creative_id): # Display results. for creative_set in creative_sets: - print (('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was updated.') - % (creative_set['id'], creative_set['masterCreativeId'], + print(('Creative set with ID "%s", master creative ID "%s", and ' + 'companion creative IDs {%s} was updated.') + % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) else: - print 'No creative sets found to update.' + print('No creative sets found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py index 7a8e57ec..63325fab 100755 --- a/examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py index 7ef20636..c99ab207 100755 --- a/examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py index 89bd2944..e9a2da47 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py @@ -54,8 +54,8 @@ def main(client, label_id): # Display results. for creative_wrapper in creative_wrappers: - print ('Creative wrapper with ID "%s" applying to label "%s" was ' - 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) + print('Creative wrapper with ID "%s" applying to label "%s" was ' + 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py index 99f3f5e2..129682e9 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py @@ -39,7 +39,7 @@ def main(client, label_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') - .WithBindVariable('labelId', long(label_id))) + .WithBindVariable('labelId', int(label_id))) creative_wrappers_deactivated = 0 @@ -50,11 +50,11 @@ def main(client, label_id): if 'results' in response and len(response['results']): # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID "%s" applying to label "%s" with ' - 'status "%s" will be deactivated.' % - (creative_wrapper['id'], - creative_wrapper['labelId'], - creative_wrapper['status'])) + print('Creative wrapper with ID "%s" applying to label "%s" with ' + 'status "%s" will be deactivated.' % + (creative_wrapper['id'], + creative_wrapper['labelId'], + creative_wrapper['status'])) # Perform action. result = creative_wrapper_service.performCreativeWrapperAction( {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) @@ -66,10 +66,10 @@ def main(client, label_id): # Display results. if creative_wrappers_deactivated > 0: - print ('Number of creative wrappers deactivated: %s' % - creative_wrappers_deactivated) + print('Number of creative wrappers deactivated: %s' % + creative_wrappers_deactivated) else: - print 'No creative wrappers were deactivated.' + print('No creative wrappers were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py index b7d06f01..dfc51eae 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py index a97c5d49..5e3434f5 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py index 815704c4..3f340f79 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py @@ -42,7 +42,7 @@ def main(client, creative_wrapper_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', - long(creative_wrapper_id))) + int(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -60,11 +60,11 @@ def main(client, creative_wrapper_id): # Display results. for creative_wrapper in creative_wrappers: - print (('Creative wrapper with ID "%s" and wrapping order "%s" ' - 'was updated.') % (creative_wrapper['id'], - creative_wrapper['ordering'])) + print(('Creative wrapper with ID "%s" and wrapping order "%s" ' + 'was updated.') % (creative_wrapper['id'], + creative_wrapper['ordering'])) else: - print 'No creative wrappers found to update.' + print('No creative wrappers found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py index 30f2d7a4..f9295c51 100755 --- a/examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py @@ -58,8 +58,8 @@ def main(client, custom_field_id): # Display results. for custom_field_option in custom_field_options: - print ('Custom field option with ID "%s" and name "%s" was created.' - % (custom_field_option['id'], custom_field_option['displayName'])) + print('Custom field option with ID "%s" and name "%s" was created.' + % (custom_field_option['id'], custom_field_option['displayName'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201902/custom_field_service/create_custom_fields.py index 17429827..5c88fa9b 100755 --- a/examples/ad_manager/v201902/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201902/custom_field_service/create_custom_fields.py @@ -57,8 +57,8 @@ def main(client): # Display results. for custom_field in custom_fields: - print ('Custom field with ID "%s" and name "%s" was created.' - % (custom_field['id'], custom_field['name'])) + print('Custom field with ID "%s" and name "%s" was created.' + % (custom_field['id'], custom_field['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py index cae10f75..452e3719 100755 --- a/examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -51,8 +51,8 @@ def main(client): if 'results' in response and len(response['results']): # Display results. for custom_field in response['results']: - print ('Custom field with ID "%s" and name "%s" will' - ' be deactivated.' % (custom_field['id'], custom_field['name'])) + print('Custom field with ID "%s" and name "%s" will' + ' be deactivated.' % (custom_field['id'], custom_field['name'])) result = custom_field_service.performCustomFieldAction( {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: @@ -62,9 +62,9 @@ def main(client): break if custom_fields_deactivated > 0: - print 'Number of custom fields deactivated: %s' % custom_fields_deactivated + print('Number of custom fields deactivated: %s' % custom_fields_deactivated) else: - print 'No custom fields were deactivated.' + print('No custom fields were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py index 955f84eb..83a59bf1 100755 --- a/examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py index 0b2fb463..d989d9e6 100755 --- a/examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py index 396156b1..4efbfad4 100755 --- a/examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py @@ -127,10 +127,10 @@ def main(client, custom_field_id, drop_down_custom_field_id, '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) custom_field_value_strings.append(custom_field_value_string) - print ('Line item with ID "%s" set with custom field values %s.' - % (line_item['id'], ','.join(custom_field_value_strings))) + print('Line item with ID "%s" set with custom field values %s.' + % (line_item['id'], ','.join(custom_field_value_strings))) else: - print 'Line item or custom field not found.' + print('Line item or custom field not found.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201902/custom_field_service/update_custom_fields.py index 1570f5c0..9f84b724 100755 --- a/examples/ad_manager/v201902/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201902/custom_field_service/update_custom_fields.py @@ -41,7 +41,7 @@ def main(client, custom_field_id): # Create statement to get a custom field. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :customFieldId') - .WithBindVariable('customFieldId', long(custom_field_id))) + .WithBindVariable('customFieldId', int(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -56,12 +56,12 @@ def main(client, custom_field_id): # Display results. for custom_field in custom_fields: - print (('Custom field with ID "%s", name "%s", and ' - 'description "%s" was updated.') - % (custom_field['id'], custom_field['name'], + print(('Custom field with ID "%s", name "%s", and ' + 'description "%s" was updated.') + % (custom_field['id'], custom_field['name'], custom_field['description'])) else: - print 'No custom fields found to update.' + print('No custom fields found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py index 61ce431d..1a5f86c7 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -63,11 +63,11 @@ def main(client): # Display results. if keys: for key in keys: - print ('A custom targeting key with id "%s", name "%s", and display ' - 'name "%s" was created.' % (key['id'], key['name'], - key['displayName'])) + print('A custom targeting key with id "%s", name "%s", and display ' + 'name "%s" was created.' % (key['id'], key['name'], + key['displayName'])) else: - print 'No keys were created.' + print('No keys were created.') # Create custom targeting value objects. values = [ @@ -119,12 +119,12 @@ def main(client): # Display results. if values: for value in values: - print ('A custom targeting value with id "%s", belonging to key with id' - ' "%s", name "%s", and display name "%s" was created.' - % (value['id'], value['customTargetingKeyId'], value['name'], + print('A custom targeting value with id "%s", belonging to key with id' + ' "%s", name "%s", and display name "%s" was created.' + % (value['id'], value['customTargetingKeyId'], value['name'], value['displayName'])) else: - print 'No values were created.' + print('No values were created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py index fb0a1f76..d30a19d0 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py @@ -65,10 +65,10 @@ def main(client, key_name): break if deleted_custom_targeting_keys > 0: - print ('Number of custom targeting keys deleted: %s' - % deleted_custom_targeting_keys) + print('Number of custom targeting keys deleted: %s' + % deleted_custom_targeting_keys) else: - print 'No custom targeting keys were deleted.' + print('No custom targeting keys were deleted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py index 2d5b5abb..82c14c38 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py @@ -66,10 +66,10 @@ def main(client, key_id): break if deleted_custom_targeting_values > 0: - print ('Number of custom targeting values deleted: %s' - % deleted_custom_targeting_values) + print('Number of custom targeting values deleted: %s' + % deleted_custom_targeting_values) else: - print 'No custom targeting values were deleted.' + print('No custom targeting values were deleted.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index b8682e07..a4818d01 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -63,7 +63,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 0efc5e8a..19af06c1 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -65,7 +65,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py index 07e59658..8578015c 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py @@ -34,7 +34,7 @@ def main(client, key_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :keyId') - .WithBindVariable('keyId', long(key_id)) + .WithBindVariable('keyId', int(key_id)) .Limit(1)) # Get custom targeting keys by statement. @@ -54,11 +54,11 @@ def main(client, key_id): # Display results. if keys: for key in keys: - print ('Custom targeting key with id "%s", name "%s", display name ' - '"%s", and type "%s" was updated.' - % (key['id'], key['name'], key['displayName'], key['type'])) + print('Custom targeting key with id "%s", name "%s", display name ' + '"%s", and type "%s" was updated.' + % (key['id'], key['name'], key['displayName'], key['type'])) else: - print 'No custom targeting keys were found to update.' + print('No custom targeting keys were found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py index fece8762..8ab23c0f 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py @@ -34,7 +34,7 @@ def main(client, key_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('customTargetingKeyId = :keyId') - .WithBindVariable('keyId', long(key_id))) + .WithBindVariable('keyId', int(key_id))) while True: # Get custom targeting values by statement. @@ -54,15 +54,15 @@ def main(client, key_id): # Display results. for value in values: - print ('Custom targeting value with id "%s", name "%s", and display' - ' name "%s" was updated.' - % (value['id'], value['name'], value['displayName'])) + print('Custom targeting value with id "%s", name "%s", and display' + ' name "%s" was updated.' + % (value['id'], value['name'], value['displayName'])) statement.offset += statement.limit else: break if response['totalResultSetSize'] == 0: - print 'No custom targeting values were updated.' + print('No custom targeting values were updated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py index 7db3116a..b5d94fa3 100755 --- a/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py +++ b/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py @@ -36,20 +36,20 @@ def main(client): exchange_rate = { 'currencyCode': 'AUD', 'direction': 'FROM_NETWORK', - 'exchangeRate': long(15000000000), + 'exchangeRate': int(15000000000), 'refreshRate': 'FIXED' } created_exchange_rate = exchange_rate_service.createExchangeRates( [exchange_rate])[0] - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was created.' % (created_exchange_rate['id'], - created_exchange_rate['currencyCode'], - created_exchange_rate['direction'], - (float(created_exchange_rate['exchangeRate']) / - 10000000000))) + print('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was created.' % (created_exchange_rate['id'], + created_exchange_rate['currencyCode'], + created_exchange_rate['direction'], + (float(created_exchange_rate['exchangeRate']) / + 10000000000))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py index 46a916e9..df06ec84 100755 --- a/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py index f7760c29..f8bc7733 100755 --- a/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -47,7 +47,7 @@ def main(client, currency_code): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py index da41e186..623916dc 100755 --- a/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py @@ -35,7 +35,7 @@ def main(client, exchange_rate_id): # Create a statement to get an exchange rate by its ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') - .WithBindVariable('id', long(exchange_rate_id)) + .WithBindVariable('id', int(exchange_rate_id)) .Limit(1)) # Get rate cards by statement. @@ -46,23 +46,23 @@ def main(client, exchange_rate_id): exchange_rate = response['results'][0] # Update the exchange rate value to 1.5. - exchange_rate['exchangeRate'] = long(15000000000) + exchange_rate['exchangeRate'] = int(15000000000) exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) if exchange_rates: for exchange_rate in exchange_rates: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was updated.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + print('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was updated.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) else: - print 'No exchange rates were updated.' + print('No exchange rates were updated.') else: - print 'No exchange rates found to update.' + print('No exchange rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py index a97a7fac..e5095213 100755 --- a/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py @@ -176,17 +176,17 @@ def main(client, advertiser_id): contending_line_items = getattr(forecast, 'contendingLineItems', []) # Display results. - print '%s %s matched overall.' % (matched, unit_type) - print '%s%% %s available overall.' % (available_percent_overall, unit_type) - print '%d contending line items overall.' % len(contending_line_items) + print('%s %s matched overall.' % (matched, unit_type)) + print('%s%% %s available overall.' % (available_percent_overall, unit_type)) + print('%d contending line items overall.' % len(contending_line_items)) if possible: - print '%s%% %s possible overall.' % (possible_percent_overall, unit_type) + print('%s%% %s possible overall.' % (possible_percent_overall, unit_type)) if 'breakdowns' in forecast and len(forecast['breakdowns']): for breakdown in forecast['breakdowns']: - print 'For breakdown time period %s - %s:' % ( + print('For breakdown time period %s - %s:' % ( FormatSOAPDateTime(breakdown['startTime']), - FormatSOAPDateTime(breakdown['endTime'])) + FormatSOAPDateTime(breakdown['endTime']))) for breakdown_entry in breakdown['breakdownEntries']: matched = breakdown_entry['forecast']['matched'] available = breakdown_entry['forecast']['available'] @@ -194,13 +194,13 @@ def main(client, advertiser_id): if 'possible' in breakdown_entry['forecast'] else None) name = breakdown_entry['name'] if 'name' in breakdown_entry else None if name: - print '\tFor targeting breakdown named \'%s\'' % name + print('\tFor targeting breakdown named \'%s\'' % name) available_percent, possible_percent = CalculateForecastStats( matched, available, possible) - print '\t\t%s %s matched.' % (matched, unit_type) - print '\t\t%s%% %s available.' % (available_percent, unit_type) + print('\t\t%s %s matched.' % (matched, unit_type)) + print('\t\t%s%% %s available.' % (available_percent, unit_type)) if possible: - print '\t\t%s%% %s possible.' % (possible_percent, unit_type) + print('\t\t%s%% %s possible.' % (possible_percent, unit_type)) def FormatSOAPDateTime(value): diff --git a/examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py index 8fceb1c9..2f124d57 100755 --- a/examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py @@ -41,8 +41,8 @@ def main(client, line_item_id): # Get forecast for line item. forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) - matched = long(forecast['matchedUnits']) - available_units = long(forecast['availableUnits']) + matched = int(forecast['matchedUnits']) + available_units = int(forecast['availableUnits']) if matched > 0: available_percent = (float(available_units) / matched) * 100. @@ -52,13 +52,14 @@ def main(client, line_item_id): contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) + print('%s %s matched.' % (matched, forecast['unitType'].lower())) + print('%s%% %s available.' % ( + available_percent, forecast['unitType'].lower())) + print('%d contending line items.' % len(contending_line_items)) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + possible_percent = (int(forecast['possibleUnits'])/float(matched)) * 100. + print('%s%% %s possible' % (possible_percent, forecast['unitType'].lower())) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py index 438b3b86..0ab4fde2 100755 --- a/examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py @@ -35,15 +35,15 @@ def main(client, line_item_id1, line_item_id2): # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( - [line_item_id1, line_item_id2], None) + [line_item_id1, line_item_id2], {'ignoredLineItemIds': []}) for single_forecast in forecast['lineItemDeliveryForecasts']: unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' - '%d %s predicted\n' % ( - single_forecast['lineItemId'], single_forecast['matchedUnits'], - unit_type, single_forecast['deliveredUnits'], unit_type, - single_forecast['predictedDeliveryUnits'], unit_type)) + print('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( + single_forecast['lineItemId'], single_forecast['matchedUnits'], + unit_type, single_forecast['deliveredUnits'], unit_type, + single_forecast['predictedDeliveryUnits'], unit_type)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/inventory_service/archive_ad_units.py b/examples/ad_manager/v201902/inventory_service/archive_ad_units.py index d1fbf0ec..6388f13a 100755 --- a/examples/ad_manager/v201902/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/archive_ad_units.py @@ -41,7 +41,7 @@ def main(client, parent_id): # unit. statement = (ad_manager.StatementBuilder(version='v201902') .Where('parentId = :parentId or id = :parentId') - .WithBindVariable('parentId', long(parent_id))) + .WithBindVariable('parentId', int(parent_id))) ad_units_archived = 0 @@ -51,8 +51,8 @@ def main(client, parent_id): statement.ToStatement()) if 'results' in response and len(response['results']): for ad_unit in response['results']: - print ('Ad unit with ID "%s" and name "%s" will be archived.' - % (ad_unit['id'], ad_unit['name'])) + print('Ad unit with ID "%s" and name "%s" will be archived.' + % (ad_unit['id'], ad_unit['name'])) # Perform action. result = inventory_service.performAdUnitAction( {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) @@ -64,9 +64,9 @@ def main(client, parent_id): # Display results. if ad_units_archived > 0: - print 'Number of ad units archived: %s' % ad_units_archived + print('Number of ad units archived: %s' % ad_units_archived) else: - print 'No ad units were archived.' + print('No ad units were archived.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/inventory_service/create_ad_units.py b/examples/ad_manager/v201902/inventory_service/create_ad_units.py index 93867bcc..7b2bb36a 100755 --- a/examples/ad_manager/v201902/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/create_ad_units.py @@ -61,8 +61,8 @@ def main(client, parent_id): # Display results. for ad_unit in ad_units: - print ('Ad unit with ID "%s" and name "%s" was created.' - % (ad_unit['id'], ad_unit['name'])) + print('Ad unit with ID "%s" and name "%s" was created.' + % (ad_unit['id'], ad_unit['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py index b3b7e7c7..5f06a8cf 100755 --- a/examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py @@ -101,8 +101,8 @@ def display_hierarchy_helper(root, parent_id_to_children, depth): parent_id_to_children: The overall map of parent ids to children. depth: The current depth. """ - print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), - root['name'], root['id']) + print('%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id'])) # Recurse for each child of this root that has children. for child in parent_id_to_children.get(root['id'], []): diff --git a/examples/ad_manager/v201902/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201902/inventory_service/get_all_ad_units.py index 93470f03..308e38e7 100755 --- a/examples/ad_manager/v201902/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/get_all_ad_units.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py index 76e772d8..98243add 100755 --- a/examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py @@ -49,7 +49,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/inventory_service/update_ad_units.py b/examples/ad_manager/v201902/inventory_service/update_ad_units.py index 3ae7463c..f1829b07 100755 --- a/examples/ad_manager/v201902/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201902/inventory_service/update_ad_units.py @@ -72,8 +72,8 @@ def main(client, ad_unit_id): ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], size['size']['height']) for size in ad_unit['adUnitSizes']] - print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' - % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + print('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' + % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/label_service/create_labels.py b/examples/ad_manager/v201902/label_service/create_labels.py index 33506d7c..00e50da0 100755 --- a/examples/ad_manager/v201902/label_service/create_labels.py +++ b/examples/ad_manager/v201902/label_service/create_labels.py @@ -46,8 +46,8 @@ def main(client): # Display results. for label in labels: - print ('Label with id "%s", name "%s", and types {%s} was found.' - % (label['id'], label['name'], ','.join(label['types']))) + print('Label with id "%s", name "%s", and types {%s} was found.' + % (label['id'], label['name'], ','.join(label['types']))) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/label_service/deactivate_labels.py b/examples/ad_manager/v201902/label_service/deactivate_labels.py index 8cd7e7ca..a97cb136 100755 --- a/examples/ad_manager/v201902/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201902/label_service/deactivate_labels.py @@ -41,8 +41,8 @@ def main(client): response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response and len(response['results']): for label in response['results']: - print ('Label with id "%s" and name "%s" will be ' - 'deactivated.' % (label['id'], label['name'])) + print('Label with id "%s" and name "%s" will be ' + 'deactivated.' % (label['id'], label['name'])) # Perform action. result = label_service.performLabelAction( {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) @@ -54,9 +54,9 @@ def main(client): # Display results. if labels_deactivated > 0: - print 'Number of labels deactivated: %s' % labels_deactivated + print('Number of labels deactivated: %s' % labels_deactivated) else: - print 'No labels were deactivated.' + print('No labels were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/label_service/get_active_labels.py b/examples/ad_manager/v201902/label_service/get_active_labels.py index 2d9edc7a..02aab6b4 100755 --- a/examples/ad_manager/v201902/label_service/get_active_labels.py +++ b/examples/ad_manager/v201902/label_service/get_active_labels.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/label_service/get_all_labels.py b/examples/ad_manager/v201902/label_service/get_all_labels.py index fa622592..0e944fba 100755 --- a/examples/ad_manager/v201902/label_service/get_all_labels.py +++ b/examples/ad_manager/v201902/label_service/get_all_labels.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/label_service/update_labels.py b/examples/ad_manager/v201902/label_service/update_labels.py index a45f310f..2f19fba5 100755 --- a/examples/ad_manager/v201902/label_service/update_labels.py +++ b/examples/ad_manager/v201902/label_service/update_labels.py @@ -34,7 +34,7 @@ def main(client, label_id): # Create a statement to select only active labels. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :labelId') - .WithBindVariable('labelId', long(label_id))) + .WithBindVariable('labelId', int(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -50,10 +50,10 @@ def main(client, label_id): labels = label_service.updateLabels(updated_labels) for label in labels: - print ('Label with id "%s" and name "%s" was updated.' - % (label['id'], label['name'])) + print('Label with id "%s" and name "%s" was updated.' + % (label['id'], label['name'])) else: - print 'No labels found to update.' + print('No labels found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py index 808db1ae..9aa8b810 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py @@ -45,11 +45,11 @@ def main(client, line_item_id, creative_ids): # Display results. if licas: for lica in licas: - print ('LICA with line item id "%s", creative id "%s", and ' - 'status "%s" was created.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) + print('LICA with line item id "%s", creative id "%s", and ' + 'status "%s" was created.' % + (lica['lineItemId'], lica['creativeId'], lica['status'])) else: - print 'No LICAs created.' + print('No LICAs created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py index 2b473f41..390a2818 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py @@ -36,7 +36,7 @@ def main(client, line_item_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') - .WithBindVariable('lineItemId', long(line_item_id))) + .WithBindVariable('lineItemId', int(line_item_id))) num_deactivated_licas = 0 @@ -46,9 +46,9 @@ def main(client, line_item_id): statement.ToStatement()) if 'results' in response and len(response['results']): for lica in response['results']: - print ('LICA with line item id "%s", creative id "%s", and status' - ' "%s" will be deactivated.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) + print('LICA with line item id "%s", creative id "%s", and status' + ' "%s" will be deactivated.' % + (lica['lineItemId'], lica['creativeId'], lica['status'])) # Perform action. result = lica_service.performLineItemCreativeAssociationAction( @@ -62,9 +62,9 @@ def main(client, line_item_id): # Display results. if num_deactivated_licas > 0: - print 'Number of LICAs deactivated: %s' % num_deactivated_licas + print('Number of LICAs deactivated: %s' % num_deactivated_licas) else: - print 'No LICAs were deactivated.' + print('No LICAs were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py index b112d047..7ea54471 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py index 01d0005d..d9351f25 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py @@ -51,7 +51,7 @@ def main(client, line_item_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py index ecc5a621..0bc348e6 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py @@ -50,15 +50,15 @@ def main(client): # Display results. for lica in licas: - print ('LICA with line item id "%s", creative id "%s", and status ' - '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print('LICA with line item id "%s", creative id "%s", and status ' + '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], + lica['status'])) statement.offset += statement.limit else: break if response['totalResultSetSize'] == 0: - print 'No LICAs found to update.' + print('No LICAs found to update.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/line_item_service/activate_line_items.py b/examples/ad_manager/v201902/line_item_service/activate_line_items.py index bf6870ba..3db3c90a 100755 --- a/examples/ad_manager/v201902/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/activate_line_items.py @@ -39,7 +39,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) line_items_activated = 0 @@ -49,9 +49,9 @@ def main(client, order_id): statement.ToStatement()) if 'results' in response and len(response['results']): for line_item in response['results']: - print ('Line item with id "%s", belonging to order id "%s", and ' - 'name "%s" will be activated.' % - (line_item['id'], line_item['orderId'], line_item['name'])) + print('Line item with id "%s", belonging to order id "%s", and ' + 'name "%s" will be activated.' % + (line_item['id'], line_item['orderId'], line_item['name'])) # Perform action. result = line_item_service.performLineItemAction( @@ -64,9 +64,9 @@ def main(client, order_id): # Display results. if line_items_activated > 0: - print 'Number of line items activated: %s' % line_items_activated + print('Number of line items activated: %s' % line_items_activated) else: - print 'No line items were activated.' + print('No line items were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_service/create_line_items.py b/examples/ad_manager/v201902/line_item_service/create_line_items.py index 7dbcfca4..67334dbb 100755 --- a/examples/ad_manager/v201902/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/create_line_items.py @@ -155,9 +155,9 @@ def main(client, order_id, targeted_placement_ids): # Display results. for line_item in line_items: - print ('Line item with id "%s", belonging to order id "%s", and named ' - '"%s" was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print('Line item with id "%s", belonging to order id "%s", and named ' + '"%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/line_item_service/get_all_line_items.py b/examples/ad_manager/v201902/line_item_service/get_all_line_items.py index 9d09535b..48f5ff96 100755 --- a/examples/ad_manager/v201902/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/get_all_line_items.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py index f11ca551..56eb70f4 100755 --- a/examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py index 90ad184c..e184d334 100755 --- a/examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py @@ -50,7 +50,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_service/pause_line_items.py b/examples/ad_manager/v201902/line_item_service/pause_line_items.py index e39a4bc2..be12973f 100755 --- a/examples/ad_manager/v201902/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/pause_line_items.py @@ -48,12 +48,12 @@ def main(client): result_set_size = page['totalResultSetSize'] # Iterate over individual results in the page. for line_item in page['results']: - print 'Pausing line item with ID %d' % line_item['id'] + print('Pausing line item with ID %d' % line_item['id']) # Update statement for next page. statement.offset += statement.limit should_continue = statement.offset < result_set_size - print 'Pausing %d line item(s)' % result_set_size + print('Pausing %d line item(s)' % result_set_size) if result_set_size > 0: statement.offset = None @@ -64,9 +64,9 @@ def main(client): {'xsi_type': 'PauseLineItems'}, statement.ToStatement()) if update_result and update_result['numChanges'] > 0: - print 'Updated %d line item(s)' % update_result['numChanges'] + print('Updated %d line item(s)' % update_result['numChanges']) else: - print 'No line items were paused' + print('No line items were paused') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201902/line_item_service/target_custom_criteria.py index ae925a76..a2c7d0ab 100755 --- a/examples/ad_manager/v201902/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201902/line_item_service/target_custom_criteria.py @@ -83,7 +83,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Create statement to get the line item statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :lineItemId') - .WithBindVariable('lineItemId', long(line_item_id)) + .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) # Set custom criteria targeting on the line item. @@ -96,11 +96,11 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Display results. if line_item: - print ('Line item with id "%s" updated with custom criteria targeting:' - % line_item['id']) + print('Line item with id "%s" updated with custom criteria targeting:' + % line_item['id']) pprint.pprint(line_item['targeting']['customTargeting']) else: - print 'No line items were updated.' + print('No line items were updated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/line_item_service/update_line_items.py b/examples/ad_manager/v201902/line_item_service/update_line_items.py index ee6a5429..114afd02 100755 --- a/examples/ad_manager/v201902/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201902/line_item_service/update_line_items.py @@ -36,7 +36,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) - .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('orderId', int(order_id)) .WithBindVariable('deliveryRateType', 'EVENLY') .Limit(500)) @@ -58,14 +58,14 @@ def main(client, order_id): # Display results. if line_items: for line_item in line_items: - print ('Line item with id "%s", belonging to order id "%s", named ' - '"%s", and delivery rate "%s" was updated.' - % (line_item['id'], line_item['orderId'], line_item['name'], + print('Line item with id "%s", belonging to order id "%s", named ' + '"%s", and delivery rate "%s" was updated.' + % (line_item['id'], line_item['orderId'], line_item['name'], line_item['deliveryRateType'])) else: - print 'No line items were updated.' + print('No line items were updated.') else: - print 'No line items found to update.' + print('No line items found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py index a4eaa02c..734feff0 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py @@ -33,7 +33,7 @@ def main(client, live_stream_event_id): .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') - .WithBindVariable('id', long(live_stream_event_id)) + .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) live_stream_events_activated = 0 @@ -59,10 +59,10 @@ def main(client, live_stream_event_id): # Display results. if live_stream_events_activated > 0: - print '# of live stream events activated: %s' % ( - live_stream_events_activated) + print('# of live stream events activated: %s' % ( + live_stream_events_activated)) else: - print 'No live stream events were activated.' + print('No live stream events were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py index 9a833cd2..7402f578 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py index e066d33f..11af75d0 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py @@ -34,9 +34,9 @@ def main(client, session_ids): if session_ids: for session_id in session_ids: # Print out some information for each live stream event. - print 'Session with ID "%s" registered for monitoring.' % (session_id) + print('Session with ID "%s" registered for monitoring.' % (session_id)) - print '\nNumber of results found: %s' % session_ids.size + print('\nNumber of results found: %s' % session_ids.size) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py index 60aa03e4..a40ac261 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py @@ -34,7 +34,7 @@ def main(client, live_stream_event_id): # Create statement object to only select matching live stream event. statement = (ad_manager.StatementBuilder(version='v201902') .Where(('Id = :id')) - .WithBindVariable('id', long(live_stream_event_id)) + .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) # Get live stream events by statement. diff --git a/examples/ad_manager/v201902/native_style_service/create_native_styles.py b/examples/ad_manager/v201902/native_style_service/create_native_styles.py index 810a35bb..9edb16d7 100755 --- a/examples/ad_manager/v201902/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201902/native_style_service/create_native_styles.py @@ -166,9 +166,9 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, # Display results. for native_style in native_styles: - print ('A Native style with ID "%s", name "%s", and creative template ID' - '"%d" was created.' % (native_style['id'], native_style['name'], - native_style['creativeTemplateId'])) + print('A Native style with ID "%s", name "%s", and creative template ID' + '"%d" was created.' % (native_style['id'], native_style['name'], + native_style['creativeTemplateId'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201902/native_style_service/get_all_native_styles.py index 637d72fc..2301b0ba 100755 --- a/examples/ad_manager/v201902/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201902/native_style_service/get_all_native_styles.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/network_service/get_all_networks.py b/examples/ad_manager/v201902/network_service/get_all_networks.py index 1be117aa..3c6aebff 100755 --- a/examples/ad_manager/v201902/network_service/get_all_networks.py +++ b/examples/ad_manager/v201902/network_service/get_all_networks.py @@ -31,7 +31,7 @@ def main(client): print('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) - print '\nNumber of results found: %s' % len(networks) + print('\nNumber of results found: %s' % len(networks)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/network_service/get_current_network.py b/examples/ad_manager/v201902/network_service/get_current_network.py index 7cdb6e98..e8d960dd 100755 --- a/examples/ad_manager/v201902/network_service/get_current_network.py +++ b/examples/ad_manager/v201902/network_service/get_current_network.py @@ -27,8 +27,8 @@ def main(client): current_network = network_service.getCurrentNetwork() - print ("Current network has network code '%s' and display name '%s'." % - (current_network['networkCode'], current_network['displayName'])) + print("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/network_service/make_test_network.py b/examples/ad_manager/v201902/network_service/make_test_network.py index ceb088fd..0e4240cc 100755 --- a/examples/ad_manager/v201902/network_service/make_test_network.py +++ b/examples/ad_manager/v201902/network_service/make_test_network.py @@ -41,11 +41,11 @@ def main(client): network = network_service.makeTestNetwork() # Display results. - print ('Test network with network code "%s" and display name "%s" ' - 'created.' % (network['networkCode'], network['displayName'])) - print ('You may now sign in at ' - 'http://www.google.com/admanager/main?networkCode=%s' - % network['networkCode']) + print('Test network with network code "%s" and display name "%s" ' + 'created.' % (network['networkCode'], network['displayName'])) + print('You may now sign in at ' + 'http://www.google.com/admanager/main?networkCode=%s' + % network['networkCode']) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/order_service/approve_orders.py b/examples/ad_manager/v201902/order_service/approve_orders.py index e0e09d5a..16b6acbc 100755 --- a/examples/ad_manager/v201902/order_service/approve_orders.py +++ b/examples/ad_manager/v201902/order_service/approve_orders.py @@ -44,8 +44,8 @@ def main(client): if 'results' in response and len(response['results']): # Display results. for order in response['results']: - print ('Order with id "%s", name "%s", and status "%s" will be ' - 'approved.' % (order['id'], order['name'], order['status'])) + print('Order with id "%s", name "%s", and status "%s" will be ' + 'approved.' % (order['id'], order['name'], order['status'])) # Perform action. result = order_service.performOrderAction( {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) @@ -57,9 +57,9 @@ def main(client): # Display results. if orders_approved > 0: - print 'Number of orders approved: %s' % orders_approved + print('Number of orders approved: %s' % orders_approved) else: - print 'No orders were approved.' + print('No orders were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/order_service/create_orders.py b/examples/ad_manager/v201902/order_service/create_orders.py index 76325017..6ba93011 100755 --- a/examples/ad_manager/v201902/order_service/create_orders.py +++ b/examples/ad_manager/v201902/order_service/create_orders.py @@ -50,8 +50,8 @@ def main(client, company_id, salesperson_id, trafficker_id): # Display results. for order in orders: - print ('Order with id "%s" and name "%s" was created.' - % (order['id'], order['name'])) + print('Order with id "%s" and name "%s" was created.' + % (order['id'], order['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/order_service/get_all_orders.py b/examples/ad_manager/v201902/order_service/get_all_orders.py index 454d17d3..3390d61e 100755 --- a/examples/ad_manager/v201902/order_service/get_all_orders.py +++ b/examples/ad_manager/v201902/order_service/get_all_orders.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201902/order_service/get_orders_starting_soon.py index 3af80f10..344da809 100755 --- a/examples/ad_manager/v201902/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201902/order_service/get_orders_starting_soon.py @@ -51,7 +51,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/order_service/update_orders.py b/examples/ad_manager/v201902/order_service/update_orders.py index af844b09..4ed63a8d 100755 --- a/examples/ad_manager/v201902/order_service/update_orders.py +++ b/examples/ad_manager/v201902/order_service/update_orders.py @@ -34,7 +34,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :orderId') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -54,14 +54,14 @@ def main(client, order_id): # Display results. if orders: for order in orders: - print ('Order with id "%s", name "%s", advertiser id "%s", and ' - 'notes "%s" was updated.' - % (order['id'], order['name'], order['advertiserId'], + print('Order with id "%s", name "%s", advertiser id "%s", and ' + 'notes "%s" was updated.' + % (order['id'], order['name'], order['advertiserId'], order['notes'])) else: - print 'No orders were updated.' + print('No orders were updated.') else: - print 'No orders found to update.' + print('No orders found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/package_service/create_packages.py b/examples/ad_manager/v201902/package_service/create_packages.py index 2264039f..eca0c302 100755 --- a/examples/ad_manager/v201902/package_service/create_packages.py +++ b/examples/ad_manager/v201902/package_service/create_packages.py @@ -51,8 +51,8 @@ def main(client): result = package_service.createPackages([package]) for new_package in result: - print ('A package with ID %d and name "%s" was created' % - (new_package['id'], new_package['name'])) + print('A package with ID %d and name "%s" was created' % + (new_package['id'], new_package['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py index 905a2546..dc103934 100755 --- a/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py @@ -42,9 +42,9 @@ def main(client): package = query_result['results'][0] - print ('Package with ID %d will create proposal line items using product ' - 'package with ID %d.' % (package['id'], - package['productPackageId'])) + print('Package with ID %d will create proposal line items using product ' + 'package with ID %d.' % (package['id'], + package['productPackageId'])) # Remove limit and offset from statement. statement.limit = None @@ -56,10 +56,10 @@ def main(client): statement.ToStatement()) if result and result['numChanges'] > 0: - print ('Number of packages that proposal line items were created for: %d' % - result['numChanges']) + print('Number of packages that proposal line items were created for: %d' % + result['numChanges']) else: - print 'No proposal line items were created.' + print('No proposal line items were created.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/package_service/get_all_packages.py b/examples/ad_manager/v201902/package_service/get_all_packages.py index 4a470442..0925f67f 100755 --- a/examples/ad_manager/v201902/package_service/get_all_packages.py +++ b/examples/ad_manager/v201902/package_service/get_all_packages.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/package_service/get_in_progress_packages.py b/examples/ad_manager/v201902/package_service/get_in_progress_packages.py index 80c32207..289aefde 100755 --- a/examples/ad_manager/v201902/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201902/package_service/get_in_progress_packages.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/placement_service/create_placements.py b/examples/ad_manager/v201902/placement_service/create_placements.py index 08820a6f..f8757ca3 100755 --- a/examples/ad_manager/v201902/placement_service/create_placements.py +++ b/examples/ad_manager/v201902/placement_service/create_placements.py @@ -98,9 +98,9 @@ def main(client): ad_unit_ids = '' if 'targetedAdUnitIds' in placement: ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) - print ('A Placement with ID "%s", name "%s", and containing ad units ' - '{%s} was created.' % (placement['id'], placement['name'], - ad_unit_ids)) + print('A Placement with ID "%s", name "%s", and containing ad units ' + '{%s} was created.' % (placement['id'], placement['name'], + ad_unit_ids)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/placement_service/deactivate_placements.py b/examples/ad_manager/v201902/placement_service/deactivate_placements.py index 110f4a45..20ab2fa3 100755 --- a/examples/ad_manager/v201902/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201902/placement_service/deactivate_placements.py @@ -33,7 +33,7 @@ def main(client, placement_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :placementId') - .WithBindVariable('placementId', long(placement_id)) + .WithBindVariable('placementId', int(placement_id)) .Limit(1)) # Get placements by statement. @@ -41,9 +41,9 @@ def main(client, placement_id): statement.ToStatement()) for placement in placements: - print ('Placement with id "%s", name "%s", and status "%s" will be ' - 'deactivated.' % (placement['id'], placement['name'], - placement['status'])) + print('Placement with id "%s", name "%s", and status "%s" will be ' + 'deactivated.' % (placement['id'], placement['name'], + placement['status'])) # Perform action. result = placement_service.performPlacementAction( @@ -51,9 +51,9 @@ def main(client, placement_id): # Display results. if result and int(result['numChanges']) > 0: - print 'Number of placements deactivated: %s' % result['numChanges'] + print('Number of placements deactivated: %s' % result['numChanges']) else: - print 'No placements were deactivated.' + print('No placements were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/placement_service/get_active_placements.py b/examples/ad_manager/v201902/placement_service/get_active_placements.py index 59deef1e..3786b708 100755 --- a/examples/ad_manager/v201902/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201902/placement_service/get_active_placements.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/placement_service/get_all_placements.py b/examples/ad_manager/v201902/placement_service/get_all_placements.py index 8fb62438..d2846654 100755 --- a/examples/ad_manager/v201902/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201902/placement_service/get_all_placements.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/placement_service/update_placements.py b/examples/ad_manager/v201902/placement_service/update_placements.py index df203ffc..66a2fdbb 100755 --- a/examples/ad_manager/v201902/placement_service/update_placements.py +++ b/examples/ad_manager/v201902/placement_service/update_placements.py @@ -49,8 +49,8 @@ def main(client, placement_id): updated_placements = placement_service.updatePlacements([placement]) for placement in updated_placements: - print ('Placement with id "%s" and name "%s" was updated.' - % (placement['id'], placement['name'])) + print('Placement with id "%s" and name "%s" was updated.' + % (placement['id'], placement['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py index 032ca707..f9b85b20 100755 --- a/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py +++ b/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py @@ -73,9 +73,9 @@ def main(client, rate_card_id): # Display results. for premium_rate in premium_rates: - print ('A premium rate for "%s" was added to the rate card with ID' - ' of "%s".\n' - % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), + print('A premium rate for "%s" was added to the rate card with ID' + ' of "%s".\n' + % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), premium_rate['id'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py index 752a7866..b575807d 100755 --- a/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py index 7148e347..0af039ad 100755 --- a/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py @@ -47,7 +47,7 @@ def main(client, rate_card_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py index 8cf63bad..a55cbe68 100755 --- a/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py @@ -36,7 +36,7 @@ def main(client, premium_rate_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) - .WithBindVariable('id', long(premium_rate_id)) + .WithBindVariable('id', int(premium_rate_id)) .Limit(1)) # Get the premium rate. @@ -72,13 +72,13 @@ def main(client, premium_rate_id): # Display results. if premium_rates: for premium_rate in premium_rates: - print ('Premium rate with ID "%s", associated with rate card id' - ' "%s" was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) + print('Premium rate with ID "%s", associated with rate card id' + ' "%s" was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) else: - print 'No premium rates were updated.' + print('No premium rates were updated.') else: - print 'No premium rates found to update.' + print('No premium rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py index 1a950077..7c27e7f6 100755 --- a/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py +++ b/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py @@ -49,11 +49,11 @@ def main(client): [product_package_item]) for new_product_package_item in result: - print ('A product package with ID %d created from product ID %d ' - 'belonging to product package with ID %d was created.' % - (new_product_package_item['id'], - new_product_package_item['productId'], - new_product_package_item['productPackageId'])) + print('A product package with ID %d created from product ID %d ' + 'belonging to product package with ID %d was created.' % + (new_product_package_item['id'], + new_product_package_item['productId'], + new_product_package_item['productPackageId'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py index 31a6055a..78d2684d 100755 --- a/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py @@ -44,7 +44,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py index 1dfeaad6..58142e5a 100755 --- a/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py @@ -47,7 +47,7 @@ def main(client, product_package_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_package_service/create_product_packages.py b/examples/ad_manager/v201902/product_package_service/create_product_packages.py index bc297c78..360a75cf 100755 --- a/examples/ad_manager/v201902/product_package_service/create_product_packages.py +++ b/examples/ad_manager/v201902/product_package_service/create_product_packages.py @@ -41,8 +41,8 @@ def main(client): result = product_package_service.createProductPackages([product_package]) for new_product_package in result: - print ('A product package with ID %d and name "%s" was created.' % - (new_product_package['id'], new_product_package['name'])) + print('A product package with ID %d and name "%s" was created.' % + (new_product_package['id'], new_product_package['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py index b93b1d41..ef45ded7 100755 --- a/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py index 513280a6..7b7020a0 100755 --- a/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_service/get_all_products.py b/examples/ad_manager/v201902/product_service/get_all_products.py index d8e67253..a8d30ed0 100755 --- a/examples/ad_manager/v201902/product_service/get_all_products.py +++ b/examples/ad_manager/v201902/product_service/get_all_products.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_service/get_products_for_product_template.py b/examples/ad_manager/v201902/product_service/get_products_for_product_template.py index 70fea594..f3f9e01f 100755 --- a/examples/ad_manager/v201902/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201902/product_service/get_products_for_product_template.py @@ -44,7 +44,7 @@ def main(client, product_template_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_service/update_products.py b/examples/ad_manager/v201902/product_service/update_products.py index 501491c0..9a52fb16 100755 --- a/examples/ad_manager/v201902/product_service/update_products.py +++ b/examples/ad_manager/v201902/product_service/update_products.py @@ -34,7 +34,7 @@ def main(client, product_id): # Create statement object to select a single product by an ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') - .WithBindVariable('id', long(product_id)) + .WithBindVariable('id', int(product_id)) .Limit(1)) # Get products by statement. @@ -53,13 +53,13 @@ def main(client, product_id): # Display results. if products: for product in products: - print ('Product with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (product['id'], product['name'], product['notes'])) + print('Product with id "%s", name "%s", and ' + 'notes "%s" was updated.' + % (product['id'], product['name'], product['notes'])) else: - print 'No products were updated.' + print('No products were updated.') else: - print 'No products found to update.' + print('No products found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_template_service/activate_product_templates.py b/examples/ad_manager/v201902/product_template_service/activate_product_templates.py index 89a5a5c8..4ce4b3e2 100755 --- a/examples/ad_manager/v201902/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/activate_product_templates.py @@ -36,7 +36,7 @@ def main(client, product_template_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') - .WithBindVariable('id', long(product_template_id)) + .WithBindVariable('id', int(product_template_id)) .Limit(1)) product_templates_activated = 0 @@ -47,9 +47,9 @@ def main(client, product_template_id): statement.ToStatement()) if 'results' in response and len(response['results']): for product_template in response['results']: - print ('Product template with id "%s" and name "%s" will be ' - 'activated.' % (product_template['id'], - product_template['name'])) + print('Product template with id "%s" and name "%s" will be ' + 'activated.' % (product_template['id'], + product_template['name'])) # Perform action. result = product_template_service.performProductTemplateAction( @@ -62,10 +62,10 @@ def main(client, product_template_id): # Display results. if product_templates_activated > 0: - print ('Number of product templates ' - 'activated: %s' % product_templates_activated) + print('Number of product templates ' + 'activated: %s' % product_templates_activated) else: - print 'No product templates were activated.' + print('No product templates were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_template_service/create_product_templates.py b/examples/ad_manager/v201902/product_template_service/create_product_templates.py index 575c7d44..fe97dfb7 100755 --- a/examples/ad_manager/v201902/product_template_service/create_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/create_product_templates.py @@ -99,8 +99,8 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A product template with ID "%s" and name "%s" was ' - 'created.' % (product_template['id'], product_template['name'])) + print('A product template with ID "%s" and name "%s" was ' + 'created.' % (product_template['id'], product_template['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py index 11ab2fbf..db150180 100755 --- a/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py @@ -80,9 +80,9 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A programmatic product template with ID "%s" and name "%s" ' - 'was created.' % (product_template['id'], - product_template['name'])) + print('A programmatic product template with ID "%s" and name "%s" ' + 'was created.' % (product_template['id'], + product_template['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201902/product_template_service/get_all_product_templates.py index 88bbfb8e..3084af7b 100755 --- a/examples/ad_manager/v201902/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/get_all_product_templates.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py index 01f171f4..8c7e3859 100755 --- a/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/product_template_service/update_product_templates.py b/examples/ad_manager/v201902/product_template_service/update_product_templates.py index a4d9f342..fe507bdd 100755 --- a/examples/ad_manager/v201902/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201902/product_template_service/update_product_templates.py @@ -36,7 +36,7 @@ def main(client, product_template_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') .OrderBy('id', ascending=True) - .WithBindVariable('id', long(product_template_id)) + .WithBindVariable('id', int(product_template_id)) .Limit(1)) # Get product templates by statement. @@ -80,12 +80,12 @@ def main(client, product_template_id): # Display results. if product_templates: for product_template in product_templates: - print ('Product template with id "%s" and name "%s" was ' - 'updated.' % (product_template['id'], product_template['name'])) + print('Product template with id "%s" and name "%s" was ' + 'updated.' % (product_template['id'], product_template['name'])) else: - print 'No product templates were updated.' + print('No product templates were updated.') else: - print 'No product templates found to update.' + print('No product templates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py index 82c64c49..9bb2b5bf 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py @@ -36,7 +36,7 @@ def main(client, proposal_line_item_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') - .WithBindVariable('id', long(proposal_line_item_id)) + .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) proposal_line_items_archived = 0 @@ -47,11 +47,11 @@ def main(client, proposal_line_item_id): statement.ToStatement()) if 'results' in response and len(response['results']): for proposal_line_item in response['results']: - print ('Proposal line item with id "%s", ' - 'belonging to proposal id "%s", and ' - 'name "%s" will be archived.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", ' + 'belonging to proposal id "%s", and ' + 'name "%s" will be archived.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) # Perform action. result = proposal_line_item_service.performProposalLineItemAction( @@ -64,10 +64,10 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items_archived > 0: - print ('Number of proposal line items ' - 'archived: %s' % proposal_line_items_archived) + print('Number of proposal line items ' + 'archived: %s' % proposal_line_items_archived) else: - print 'No proposal line items were archived.' + print('No proposal line items were archived.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py index 2ab6c859..34340533 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -91,10 +91,10 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item with id "%s", belonging to ' - 'proposal id "%s", and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Programmatic proposal line item with id "%s", belonging to ' + 'proposal id "%s", and named "%s" was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index d6bc8219..91b615ef 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -99,11 +99,11 @@ def main(client, proposal_id, product_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item for non-sales management with id ' - '"%s", belonging to proposal id "%s", and named "%s" ' - 'was created.' % (proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Programmatic proposal line item for non-sales management with id ' + '"%s", belonging to proposal id "%s", and named "%s" ' + 'was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py index 6d72e8a5..d7295960 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py @@ -92,10 +92,10 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Proposal line item with id "%s", belonging to proposal id "%s"' - ', and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", belonging to proposal id "%s"' + ', and named "%s" was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py index 8df2e2dc..b9410478 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 8fd23187..5a3b046c 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -45,7 +45,7 @@ def main(client, proposal_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py index 68c70045..e1f956d0 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py @@ -37,7 +37,7 @@ def main(client, proposal_line_item_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') - .WithBindVariable('id', long(proposal_line_item_id)) + .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) # Get proposal line items by statement. @@ -56,14 +56,14 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items: for proposal_line_item in proposal_line_items: - print ('Line item with id "%s", belonging to proposal id "%s" and,' - ' named "%s" was updated.' % ( - proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Line item with id "%s", belonging to proposal id "%s" and,' + ' named "%s" was updated.' % ( + proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) else: - print 'No proposal line items were updated.' + print('No proposal line items were updated.') else: - print 'No proposal line items found to update.' + print('No proposal line items found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_service/create_proposals.py b/examples/ad_manager/v201902/proposal_service/create_proposals.py index f8b980d8..d373d891 100755 --- a/examples/ad_manager/v201902/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201902/proposal_service/create_proposals.py @@ -67,8 +67,8 @@ def main(client, advertiser_id, primary_salesperson_id, # Display results. for proposal in proposals: - print ('Proposal with id "%s" and name "%s" was created.' - % (proposal['id'], proposal['name'])) + print('Proposal with id "%s" and name "%s" was created.' + % (proposal['id'], proposal['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/proposal_service/get_all_proposals.py b/examples/ad_manager/v201902/proposal_service/get_all_proposals.py index 3dd1190f..de978527 100755 --- a/examples/ad_manager/v201902/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201902/proposal_service/get_all_proposals.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py index bfca57c3..f0cbb405 100755 --- a/examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py @@ -47,7 +47,7 @@ def main(client, proposal_id): print('Marketplace comment with creation time "%s"and comment "%s" was ' 'found.\n' % (date_time_string, marketplace_comment['comment'])) - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py index d7a21239..6ea9deee 100755 --- a/examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py index 4fbd173c..ad893e5a 100755 --- a/examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py @@ -40,10 +40,10 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: - print ('Programmatic proposal with id "%s", name "%s", and status ' - '"%s" will be pushed to Marketplace.' % (proposal['id'], - proposal['name'], - proposal['status'])) + print('Programmatic proposal with id "%s", name "%s", and status ' + '"%s" will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) @@ -55,10 +55,10 @@ def main(client, proposal_id): # Display results. if proposals_pushed_to_marketplace > 0: - print ('\nNumber of programmatic proposals pushed to Marketplace: %s' - % proposals_pushed_to_marketplace) + print('\nNumber of programmatic proposals pushed to Marketplace: %s' + % proposals_pushed_to_marketplace) else: - print '\nNo programmatic proposals were pushed to Marketplace.' + print('\nNo programmatic proposals were pushed to Marketplace.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py index 743bca8e..2922015e 100755 --- a/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py @@ -42,9 +42,9 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: - print ('Proposal with id "%s", name "%s", and status "%s" will be' - ' approved.' % (proposal['id'], proposal['name'], - proposal['status'])) + print('Proposal with id "%s", name "%s", and status "%s" will be' + ' approved.' % (proposal['id'], proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) @@ -56,9 +56,9 @@ def main(client, proposal_id): # Display results. if proposals_approved > 0: - print '\nNumber of proposals approved: %s' % proposals_approved + print('\nNumber of proposals approved: %s' % proposals_approved) else: - print '\nNo proposals were approved.' + print('\nNo proposals were approved.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/proposal_service/update_proposals.py b/examples/ad_manager/v201902/proposal_service/update_proposals.py index a63804f5..9596c08d 100755 --- a/examples/ad_manager/v201902/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201902/proposal_service/update_proposals.py @@ -34,7 +34,7 @@ def main(client, proposal_id): statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :proposalId') - .WithBindVariable('proposalId', long(proposal_id)) + .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) # Get proposals by statement. @@ -53,13 +53,13 @@ def main(client, proposal_id): # Display results. if proposals: for proposal in proposals: - print ('Proposal with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (proposal['id'], proposal['name'], proposal['internalNotes'])) + print('Proposal with id "%s", name "%s", and ' + 'notes "%s" was updated.' + % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: - print 'No proposals were updated.' + print('No proposals were updated.') else: - print 'No proposals found to update.' + print('No proposals found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py index 0314eb63..9179f0c4 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py @@ -45,8 +45,8 @@ def main(client): line_items_file.close() ad_units_file.close() - print 'Saved line items to... %s' % line_items_file.name - print 'Saved ad units to... %s' % ad_units_file.name + print('Saved line items to... %s' % line_items_file.name) + print('Saved ad units to... %s' % ad_units_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py index c4761b9b..8cecbc29 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py @@ -46,7 +46,7 @@ def main(client): report_downloader.DownloadPqlResultToCsv( browser_pql_query, browser_data_file) - print 'Saved browser data to... %s' % browser_data_file.name + print('Saved browser data to... %s' % browser_data_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py index e3e9d842..b84c4266 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py @@ -40,7 +40,7 @@ def main(client): programmatic_buyers_file.close() - print 'Saved programmatic buyers to... %s' % programmatic_buyers_file.name + print('Saved programmatic buyers to... %s' % programmatic_buyers_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py index 0abb46b4..5a38a8bc 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py @@ -26,7 +26,7 @@ GEO_TARGET_TYPE = 'City' -def main(client, geo_target_type): +def main(client): # Initialize a report downloader. report_downloader = client.GetDataDownloader(version='v201902') @@ -44,7 +44,7 @@ def main(client, geo_target_type): report_downloader.DownloadPqlResultToCsv( geo_pql_query, geo_data_file, {'type': geo_target_type}) - print 'Saved geo data to... %s' % geo_data_file.name + print('Saved geo data to... %s' % geo_data_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py index 5e8d8607..65b9d769 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py @@ -39,7 +39,7 @@ def main(client): report_downloader.DownloadPqlResultToCsv( line_items_pql_query, line_items_file) - print 'Saved line items to... %s' % line_items_file.name + print('Saved line items to... %s' % line_items_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py index b5243323..37457e79 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py @@ -70,17 +70,17 @@ def main(client): statement.Where(pagination_query) statement.WithBindVariable('id', last_id) - print ('%d) %d changes prior to ID "%s" were found.\n' - % (i, rows_length, last_id)) + print('%d) %d changes prior to ID "%s" were found.\n' + % (i, rows_length, last_id)) keep_iterating = rows and len(rows) == statement.limit # Print out columns header - print ','.join(column_types) + print(','.join(column_types)) # Print out every row for row in total_rows: - print ConvertValueForCsv(row) + print(ConvertValueForCsv(row)) def ConvertValueForCsv(pql_value): diff --git a/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py index 7f528af2..fb6f130c 100755 --- a/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py +++ b/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py @@ -48,10 +48,10 @@ def main(client): result = rate_card_service.createRateCards([rate_card]) for new_rate_card in result: - print ('A rate card with ID %s, name "%s", and currency code "%s" ' - 'was created.' % (new_rate_card['id'], - new_rate_card['name'], - new_rate_card['currencyCode'])) + print('A rate card with ID %s, name "%s", and currency code "%s" ' + 'was created.' % (new_rate_card['id'], + new_rate_card['name'], + new_rate_card['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py index 8f73fed3..dffd4225 100755 --- a/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py index 7a48f1ed..05e33199 100755 --- a/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index ad7620e0..c9929cab 100755 --- a/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -55,18 +55,18 @@ def main(client): result_set_size += page['totalResultSetSize'] # Iterate over individual results in the page. for line_item_report in page['results']: - print ('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source "%s", and reconciled volume %d was ' - 'found.' % (line_item_report['id'], - line_item_report['lineItemId'], - line_item_report['reconciliationSource'], - (line_item_report['reconciledVolume'] - if 'reconciledVolume' in line_item_report else 0))) + print('Reconciliation line item report with ID %d, line item ID %d, ' + 'reconciliation source "%s", and reconciled volume %d was ' + 'found.' % (line_item_report['id'], + line_item_report['lineItemId'], + line_item_report['reconciliationSource'], + (line_item_report['reconciledVolume'] + if 'reconciledVolume' in line_item_report else 0))) # Update statement for next page. statement.offset += statement.limit should_continue = statement.offset < result_set_size - print 'Number of results found: %d' % result_set_size + print('Number of results found: %d' % result_set_size) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index 5923eb8e..91842a41 100755 --- a/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -56,10 +56,10 @@ def main(client): .updateReconciliationLineItemReports([line_item_report])) for updated_report in result: - print ('Reconciliation line item report with ID %d for line item ID %d was ' - 'updated, with manual volume %d' % (updated_report['id'], - updated_report['lineItemId'], - updated_report['manualVolume'])) + print('Reconciliation line item report with ID %d for line item ID %d was ' + 'updated, with manual volume %d' % (updated_report['id'], + updated_report['lineItemId'], + updated_report['manualVolume'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index 4ef8f0d5..ced1d2ac 100755 --- a/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -49,7 +49,7 @@ def main(client, reconciliation_report_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 69850233..80152dbe 100755 --- a/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -45,8 +45,8 @@ def main(client): report = page['results'][0] - print ('Reconciliation order report with ID %d will be submitted.' % - report['id']) + print('Reconciliation order report with ID %d will be submitted.' % + report['id']) # Remove limit and offset from statement. statement.limit = None @@ -59,10 +59,10 @@ def main(client): statement.ToStatement())) if result and result['numChanges'] > 0: - print ('Number of reconciliation order reports submitted: %d' % - result['numChanges']) + print('Number of reconciliation order reports submitted: %d' % + result['numChanges']) else: - print 'No reconciliation order reports were submitted.' + print('No reconciliation order reports were submitted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 4df9fcb7..f156867e 100755 --- a/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -34,7 +34,7 @@ def main(client, reconciliation_report_id): .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) - .WithBindVariable('reportId', long(reconciliation_report_id))) + .WithBindVariable('reportId', int(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. @@ -55,7 +55,7 @@ def main(client, reconciliation_report_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py index 8e0e4ffa..44252a28 100755 --- a/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -63,10 +63,10 @@ def main(client): .updateReconciliationReportRows([row])) for updated_row in updated_rows: - print ('Reconciliation report row for line item ID %d and creative ID %d ' - 'was updated, with manual volume %d' % (updated_row['lineItemId'], - updated_row['creativeId'], - updated_row['manualVolume'])) + print('Reconciliation report row for line item ID %d and creative ID %d ' + 'was updated, with manual volume %d' % (updated_row['lineItemId'], + updated_row['creativeId'], + updated_row['manualVolume'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py index d4b2c76c..71d1578d 100755 --- a/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py @@ -47,7 +47,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index 889ed713..33df990a 100755 --- a/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -54,7 +54,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201902/report_service/run_ad_exchange_report.py index 2d27cc9c..8025139c 100755 --- a/examples/ad_manager/v201902/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201902/report_service/run_ad_exchange_report.py @@ -42,8 +42,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -57,8 +57,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/report_service/run_delivery_report.py b/examples/ad_manager/v201902/report_service/run_delivery_report.py index 76f89bb4..5db8cf28 100755 --- a/examples/ad_manager/v201902/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201902/report_service/run_delivery_report.py @@ -34,7 +34,7 @@ def main(client, order_id): # Create statement object to filter for an order. statement = (ad_manager.StatementBuilder(version='v201902') .Where('ORDER_ID = :id') - .WithBindVariable('id', long(order_id)) + .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports .Offset(None)) @@ -64,8 +64,8 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -79,8 +79,8 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/report_service/run_inventory_report.py b/examples/ad_manager/v201902/report_service/run_inventory_report.py index 07d5de3d..5c4e06c0 100755 --- a/examples/ad_manager/v201902/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201902/report_service/run_inventory_report.py @@ -36,7 +36,7 @@ def main(client): # Set filter statement and bind value for reportQuery. statement = (ad_manager.StatementBuilder(version='v201902') .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') - .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .WithBindVariable('parentAdUnitId', int(root_ad_unit_id)) .Limit(None) # No limit or offset for reports .Offset(None)) @@ -58,8 +58,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -73,8 +73,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/report_service/run_reach_report.py b/examples/ad_manager/v201902/report_service/run_reach_report.py index f7370148..dd5f4036 100755 --- a/examples/ad_manager/v201902/report_service/run_reach_report.py +++ b/examples/ad_manager/v201902/report_service/run_reach_report.py @@ -39,8 +39,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -54,8 +54,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py index 0d223538..ef9d4916 100755 --- a/examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py @@ -59,8 +59,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) with tempfile.NamedTemporaryFile( suffix='.csv.gz', mode='wb', delete=False) as report_file: diff --git a/examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py index 4fc16765..4af9c240 100755 --- a/examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py @@ -35,7 +35,7 @@ def main(client, order_id): # Filter for line items of a given order. statement = (ad_manager.StatementBuilder(version='v201902') .Where('orderId = :orderId') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -73,8 +73,8 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -88,8 +88,8 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/report_service/run_sales_report.py b/examples/ad_manager/v201902/report_service/run_sales_report.py index d34bac17..76379106 100755 --- a/examples/ad_manager/v201902/report_service/run_sales_report.py +++ b/examples/ad_manager/v201902/report_service/run_sales_report.py @@ -40,8 +40,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -55,8 +55,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/report_service/run_saved_query.py b/examples/ad_manager/v201902/report_service/run_saved_query.py index 13f5e283..0f217acc 100755 --- a/examples/ad_manager/v201902/report_service/run_saved_query.py +++ b/examples/ad_manager/v201902/report_service/run_saved_query.py @@ -36,7 +36,7 @@ def main(client, saved_query_id): # Create statement object to filter for an order. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :id') - .WithBindVariable('id', long(saved_query_id)) + .WithBindVariable('id', int(saved_query_id)) .Limit(1)) response = report_service.getSavedQueriesByStatement( @@ -54,8 +54,8 @@ def main(client, saved_query_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -68,10 +68,10 @@ def main(client, saved_query_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) else: - print 'The query specified is not compatible with the API version.' + print('The query specified is not compatible with the API version.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 8c4f4434..19d48551 100755 --- a/examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -44,9 +44,9 @@ def main(client): if 'results' in response and len(response['results']): # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: - print ('Suggested ad unit with id "%s", and number of requests "%s"' - ' will be approved.' % (suggested_ad_unit['id'], - suggested_ad_unit['numRequests'])) + print('Suggested ad unit with id "%s", and number of requests "%s"' + ' will be approved.' % (suggested_ad_unit['id'], + suggested_ad_unit['numRequests'])) # Approve suggested ad units. result = suggested_ad_unit_service.performSuggestedAdUnitAction( @@ -58,10 +58,10 @@ def main(client): break if num_approved_suggested_ad_units > 0: - print ('Number of suggested ad units approved: %s' % - num_approved_suggested_ad_units) + print('Number of suggested ad units approved: %s' % + num_approved_suggested_ad_units) else: - print 'No suggested ad units were approved.' + print('No suggested ad units were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py index 76f5245f..2cb50683 100755 --- a/examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 62289682..141e92a5 100755 --- a/examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client, num_requests): # Create a statement to select suggested ad units. statement = (ad_manager.StatementBuilder(version='v201902') .Where('numRequests >= :numRequests') - .WithBindVariable('numRequests', long(num_requests))) + .WithBindVariable('numRequests', int(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -46,7 +46,7 @@ def main(client, num_requests): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/team_service/create_teams.py b/examples/ad_manager/v201902/team_service/create_teams.py index 4b574a46..3d9772f1 100755 --- a/examples/ad_manager/v201902/team_service/create_teams.py +++ b/examples/ad_manager/v201902/team_service/create_teams.py @@ -51,8 +51,8 @@ def main(client): # Display results. for team in teams: - print ('Team with ID "%s" and name "%s" was created.' - % (team['id'], team['name'])) + print('Team with ID "%s" and name "%s" was created.' + % (team['id'], team['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/team_service/get_all_teams.py b/examples/ad_manager/v201902/team_service/get_all_teams.py index 3ff51034..ab31e99b 100755 --- a/examples/ad_manager/v201902/team_service/get_all_teams.py +++ b/examples/ad_manager/v201902/team_service/get_all_teams.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/team_service/update_teams.py b/examples/ad_manager/v201902/team_service/update_teams.py index 32e6aa70..8910b8df 100755 --- a/examples/ad_manager/v201902/team_service/update_teams.py +++ b/examples/ad_manager/v201902/team_service/update_teams.py @@ -39,7 +39,7 @@ def main(client, team_id): # Create a filter statement to select a single team by ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :teamId') - .WithBindVariable('teamId', long(team_id))) + .WithBindVariable('teamId', int(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -56,10 +56,10 @@ def main(client, team_id): # Display results. for team in teams: - print ('Team with id "%s" and name "%s" was updated.' - % (team['id'], team['name'])) + print('Team with id "%s" and name "%s" was updated.' + % (team['id'], team['name'])) else: - print 'No teams found to update.' + print('No teams found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_service/create_users.py b/examples/ad_manager/v201902/user_service/create_users.py index 9b51ee18..144bd087 100755 --- a/examples/ad_manager/v201902/user_service/create_users.py +++ b/examples/ad_manager/v201902/user_service/create_users.py @@ -48,8 +48,8 @@ def main(client, email, name): # Display results. for user in users: - print ('User with id "%s", email "%s", and role "%s" was created.' - % (user['id'], user['email'], user['roleName'])) + print('User with id "%s", email "%s", and role "%s" was created.' + % (user['id'], user['email'], user['roleName'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/user_service/deactivate_users.py b/examples/ad_manager/v201902/user_service/deactivate_users.py index 9eada7ab..66f2c592 100755 --- a/examples/ad_manager/v201902/user_service/deactivate_users.py +++ b/examples/ad_manager/v201902/user_service/deactivate_users.py @@ -35,18 +35,18 @@ def main(client, user_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) users = response['results'] if 'results' in response else [] for user in users: - print ('User with id "%s", email "%s", and status "%s" will be ' - 'deactivated.' - % (user['id'], user['email'], + print('User with id "%s", email "%s", and status "%s" will be ' + 'deactivated.' + % (user['id'], user['email'], {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) - print 'Number of users to be deactivated: %s' % len(users) + print('Number of users to be deactivated: %s' % len(users)) # Perform action. result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'}, @@ -54,9 +54,9 @@ def main(client, user_id): # Display results. if result and int(result['numChanges']) > 0: - print 'Number of users deactivated: %s' % result['numChanges'] + print('Number of users deactivated: %s' % result['numChanges']) else: - print 'No users were deactivated.' + print('No users were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_service/get_all_roles.py b/examples/ad_manager/v201902/user_service/get_all_roles.py index 442d35bd..38cfc420 100755 --- a/examples/ad_manager/v201902/user_service/get_all_roles.py +++ b/examples/ad_manager/v201902/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') + user_service = client.GetService('UserService', version='v201905') roles = user_service.getAllRoles() @@ -31,7 +31,7 @@ def main(client): print('Role with id "%s" and name "%s" was found.' % (role['id'], role['name'])) - print '\nNumber of results found: %s' % len(roles) + print('\nNumber of results found: %s' % len(roles)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_service/get_all_users.py b/examples/ad_manager/v201902/user_service/get_all_users.py index 74f424ce..e4b2602d 100755 --- a/examples/ad_manager/v201902/user_service/get_all_users.py +++ b/examples/ad_manager/v201902/user_service/get_all_users.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_service/get_current_user.py b/examples/ad_manager/v201902/user_service/get_current_user.py index 012221fb..55b0c090 100755 --- a/examples/ad_manager/v201902/user_service/get_current_user.py +++ b/examples/ad_manager/v201902/user_service/get_current_user.py @@ -27,10 +27,9 @@ def main(client): # Get current user. user = user_service.getCurrentUser() - print ('User with ID %d, name "%s", email "%s", and role "%s" ' - 'is the current user.' % ( - user.id, user.name, user.email, user.roleName - )) + print('User with ID %d, name "%s", email "%s", and role "%s" ' + 'is the current user.' % ( + user.id, user.name, user.email, user.roleName)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_service/get_user_by_email_address.py b/examples/ad_manager/v201902/user_service/get_user_by_email_address.py index 8350c7c5..3ea58d08 100755 --- a/examples/ad_manager/v201902/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201902/user_service/get_user_by_email_address.py @@ -43,7 +43,7 @@ def main(client, email_address): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_service/update_users.py b/examples/ad_manager/v201902/user_service/update_users.py index 0aba54e4..3663abbf 100755 --- a/examples/ad_manager/v201902/user_service/update_users.py +++ b/examples/ad_manager/v201902/user_service/update_users.py @@ -33,7 +33,7 @@ def main(client, user_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201902') .Where('id = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -46,10 +46,10 @@ def main(client, user_id): # Update users on server. users = user_service.updateUsers(users) for user in users: - print ('User with id "%s" and name "%s" was updated.' - % (user['id'], user['name'])) + print('User with id "%s" and name "%s" was updated.' + % (user['id'], user['name'])) else: - print 'No users found to update.' + print('No users found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py index 143799de..ae07570f 100755 --- a/examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py @@ -55,11 +55,11 @@ def main(client, team_id, user_ids): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('A user team association between user with ID "%s" and team with' - ' ID "%s"was created.' % (user_team_association['userId'], - user_team_association['teamId'])) + print('A user team association between user with ID "%s" and team with' + ' ID "%s"was created.' % (user_team_association['userId'], + user_team_association['teamId'])) else: - print 'No user team associations created.' + print('No user team associations created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py index 26f307a4..f53edcff 100755 --- a/examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py @@ -40,7 +40,7 @@ def main(client, user_id): # Create filter text to select user team associations by the user ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -48,11 +48,11 @@ def main(client, user_id): user_team_associations = response['results'] if 'results' in response else [] for user_team_association in user_team_associations: - print ('User team association between user with ID "%s" and team with ' - 'ID "%s" will be deleted.' % (user_team_association['userId'], - user_team_association['teamId'])) - print ('Number of teams that the user will be removed from: %s' % - len(user_team_associations)) + print('User team association between user with ID "%s" and team with ' + 'ID "%s" will be deleted.' % (user_team_association['userId'], + user_team_association['teamId'])) + print('Number of teams that the user will be removed from: %s' % + len(user_team_associations)) # Action doesn't require limit/offset statement.limit = None @@ -65,10 +65,10 @@ def main(client, user_id): # Display results. if result and int(result['numChanges']) > 0: - print ('Number of teams that the user was removed from: %s' - % result['numChanges']) + print('Number of teams that the user was removed from: %s' + % result['numChanges']) else: - print 'No user team associations were deleted.' + print('No user team associations were deleted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py index 0134b3da..77a40895 100755 --- a/examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py index 3cf60498..a472f12c 100755 --- a/examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py @@ -29,7 +29,7 @@ def main(client, user_id): # Create a statement to select user team associations. statement = (ad_manager.StatementBuilder(version='v201902') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -46,7 +46,7 @@ def main(client, user_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py index 71365e24..ce7cbdd8 100755 --- a/examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py @@ -42,7 +42,7 @@ def main(client, user_id): # Create filter text to select user team associations by the user ID. statement = (ad_manager.StatementBuilder(version='v201902') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -63,13 +63,13 @@ def main(client, user_id): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('User team association between user with ID "%s" and team with' - ' ID "%s" was updated.' % (user_team_association['userId'], - user_team_association['teamId'])) + print('User team association between user with ID "%s" and team with' + ' ID "%s" was updated.' % (user_team_association['userId'], + user_team_association['teamId'])) else: - print 'No user team associations were updated.' + print('No user team associations were updated.') else: - print 'No user team associations found to update.' + print('No user team associations found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py index 5fd48ba5..0631cd69 100755 --- a/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py @@ -49,8 +49,8 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for workflow_approval_request in response['results']: - print ('Workflow approval request with id "%s" will be' - ' approved.' % workflow_approval_request['id']) + print('Workflow approval request with id "%s" will be' + ' approved.' % workflow_approval_request['id']) # Perform action. result = workflow_request_service.performWorkflowRequestAction( {'xsi_type': 'ApproveWorkflowApprovalRequests', @@ -64,10 +64,10 @@ def main(client, proposal_id): # Display results. if workflow_approval_requests_approved > 0: - print ('\nNumber of workflow approval requests approved: %s' % - workflow_approval_requests_approved) + print('\nNumber of workflow approval requests approved: %s' % + workflow_approval_requests_approved) else: - print '\nNo workflow approval requests were approved.' + print('\nNo workflow approval requests were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py index 6dd80263..cdac48ba 100755 --- a/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py index d0233fa9..73fdb595 100755 --- a/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py index c3ada98c..56fc4ef3 100755 --- a/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -49,11 +49,11 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id "%s" for %s ' - 'with id "%s" will be triggered.' % - (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + print('Workflow external condition request with id "%s" for %s ' + 'with id "%s" will be triggered.' % + (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) # Perform action. result = workflow_request_service.performWorkflowRequestAction( {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, @@ -67,10 +67,10 @@ def main(client, proposal_id): # Display results. if workflow_external_condition_requests_triggered > 0: - print ('\nNumber of workflow external condition requests triggered: %s' % - workflow_external_condition_requests_triggered) + print('\nNumber of workflow external condition requests triggered: %s' % + workflow_external_condition_requests_triggered) else: - print '\nNo workflow external condition requests were triggered.' + print('\nNo workflow external condition requests were triggered.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py index 256d9e94..f7fc003c 100755 --- a/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py @@ -62,8 +62,8 @@ def main(client, advertiser_company_id): # Display results. for activity_group in activity_groups: - print ('Activity group with ID "%s" and name "%s" was created.' - % (activity_group['id'], activity_group['name'])) + print('Activity group with ID "%s" and name "%s" was created.' + % (activity_group['id'], activity_group['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py index 1137ccde..c79463de 100755 --- a/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py index 7e5c4041..1afd9b18 100755 --- a/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py index 9fa21fc2..a730afb9 100755 --- a/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py @@ -42,7 +42,7 @@ def main(client, activity_group_id, advertiser_company_id): # Create statement object to select a single activity groups by ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :activityGroupId') - .WithBindVariable('activityGroupId', long(activity_group_id)) + .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) # Get activity groups by statement. @@ -58,10 +58,10 @@ def main(client, activity_group_id, advertiser_company_id): updated_activity_groups) for activity_group in activity_groups: - print (('Activity group with ID "%s" and name "%s" was updated.') - % (activity_group['id'], activity_group['name'])) + print(('Activity group with ID "%s" and name "%s" was updated.') + % (activity_group['id'], activity_group['name'])) else: - print 'No activity groups found to update.' + print('No activity groups found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/activity_service/create_activities.py b/examples/ad_manager/v201905/activity_service/create_activities.py index 58767280..09bb98df 100755 --- a/examples/ad_manager/v201905/activity_service/create_activities.py +++ b/examples/ad_manager/v201905/activity_service/create_activities.py @@ -59,8 +59,8 @@ def main(client, activity_group_id): # Display results. for activity in activities: - print ('An activity with ID "%s", name "%s", and type "%s" was ' - 'created.' % (activity['id'], activity['name'], activity['type'])) + print('An activity with ID "%s", name "%s", and type "%s" was ' + 'created.' % (activity['id'], activity['name'], activity['type'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/activity_service/get_active_activities.py b/examples/ad_manager/v201905/activity_service/get_active_activities.py index 0fd55cf4..76564315 100755 --- a/examples/ad_manager/v201905/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201905/activity_service/get_active_activities.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/activity_service/get_all_activities.py b/examples/ad_manager/v201905/activity_service/get_all_activities.py index d06ef0e8..64e75b13 100755 --- a/examples/ad_manager/v201905/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201905/activity_service/get_all_activities.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/activity_service/update_activities.py b/examples/ad_manager/v201905/activity_service/update_activities.py index 7fe4a3ed..a4ff885e 100755 --- a/examples/ad_manager/v201905/activity_service/update_activities.py +++ b/examples/ad_manager/v201905/activity_service/update_activities.py @@ -40,7 +40,7 @@ def main(client, activity_id): # Create statement object to select one activity by ID to update. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :activityId') - .WithBindVariable('activityId', long(activity_id)) + .WithBindVariable('activityId', int(activity_id)) .Limit(1)) # Get activities by statement. @@ -56,10 +56,10 @@ def main(client, activity_id): activities = activity_service.updateActivities(updated_activities) for updated_activity in activities: - print (('Activity with ID "%s" and name "%s" was updated.') - % (updated_activity['id'], updated_activity['name'])) + print(('Activity with ID "%s" and name "%s" was updated.') + % (updated_activity['id'], updated_activity['name'])) else: - print 'No activities found to update.' + print('No activities found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py index fc2cf720..63387692 100755 --- a/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py @@ -84,10 +84,10 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): audience_segment_service.createAudienceSegments(audience_segment)) for created_audience_segment in audience_segments: - print ('An audience segment with ID "%s", name "%s", and type "%s" ' - 'was created.' % (created_audience_segment['id'], - created_audience_segment['name'], - created_audience_segment['type'])) + print('An audience segment with ID "%s", name "%s", and type "%s" ' + 'was created.' % (created_audience_segment['id'], + created_audience_segment['name'], + created_audience_segment['type'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py index b1ac0da8..241c21c6 100755 --- a/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py index a495a37e..f81ad480 100755 --- a/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py @@ -44,7 +44,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py index 374f5819..7ff56aa8 100755 --- a/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py @@ -36,7 +36,7 @@ def main(client, audience_segment_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', - long(audience_segment_id)) + int(audience_segment_id)) .WithBindVariable('type', 'FIRST_PARTY') .Limit(1)) @@ -47,7 +47,7 @@ def main(client, audience_segment_id): segments = response['results'] for segment in segments: - print ( + print( 'Audience segment with id "%s" and name "%s" will be populated.' % (segment['id'], segment['name'])) @@ -59,10 +59,10 @@ def main(client, audience_segment_id): audience_segment_service.performAudienceSegmentAction( action, statement.ToStatement())) - print ('%s audience segment populated' % - populated_audience_segments['numChanges']) + print('%s audience segment populated' % + populated_audience_segments['numChanges']) else: - print 'No Results Found' + print('No Results Found') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py index 15a94347..40eb0a24 100755 --- a/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py @@ -35,7 +35,7 @@ def main(client, audience_segment_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', - long(audience_segment_id)) + int(audience_segment_id)) .WithBindVariable('type', 'FIRST_PARTY') .Limit(1)) @@ -46,8 +46,8 @@ def main(client, audience_segment_id): if 'results' in response and len(response['results']): updated_audience_segments = [] for audience_segment in response['results']: - print ('Audience segment with id "%s" and name "%s" will be updated.' - % (audience_segment['id'], audience_segment['name'])) + print('Audience segment with id "%s" and name "%s" will be updated.' + % (audience_segment['id'], audience_segment['name'])) audience_segment['membershipExpirationDays'] = '180' updated_audience_segments.append(audience_segment) @@ -56,10 +56,10 @@ def main(client, audience_segment_id): updated_audience_segments) for audience_segment in audience_segments: - print ('Audience segment with id "%s" and name "%s" was updated' % - (audience_segment['id'], audience_segment['name'])) + print('Audience segment with id "%s" and name "%s" was updated' % + (audience_segment['id'], audience_segment['name'])) else: - print 'No audience segment found to update.' + print('No audience segment found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py index 24fe9bb0..44b2f6ea 100755 --- a/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py +++ b/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py @@ -53,10 +53,10 @@ def main(client, product_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product base rate with ID "%s" and rate \'%.2f\' %s was ' - 'created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) + print('A product base rate with ID "%s" and rate \'%.2f\' %s was ' + 'created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py index 14bddffe..ddd9a51d 100755 --- a/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py +++ b/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py @@ -54,10 +54,10 @@ def main(client): result = base_rate_service.createBaseRates([product_package_item_base_rate]) for new_base_rate in result: - print ('A product package item base rate with ID %d and rate %f %s ' - 'was created.' % (new_base_rate['id'], - new_base_rate['microAmount'], - new_base_rate['currencyCode'])) + print('A product package item base rate with ID %d and rate %f %s ' + 'was created.' % (new_base_rate['id'], + new_base_rate['microAmount'], + new_base_rate['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py index 6a38d9b9..d56c7463 100755 --- a/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py +++ b/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py @@ -53,10 +53,10 @@ def main(client, product_template_id, rate_card_id): if base_rates: for base_rate in base_rates: - print ('A product template base rate with ID "%s" and rate \'%.2f\' %s' - ' was created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) + print('A product template base rate with ID "%s" and rate \'%.2f\' %s' + ' was created.' % (base_rate['id'], + base_rate['rate']['microAmount'], + base_rate['rate']['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py index b92350b8..e463e1c8 100755 --- a/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py +++ b/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py index dfa06842..3f875a35 100755 --- a/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py +++ b/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py @@ -46,7 +46,7 @@ def main(client, rate_card_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/base_rate_service/update_base_rates.py b/examples/ad_manager/v201905/base_rate_service/update_base_rates.py index 60c4b9a3..3f271a2c 100755 --- a/examples/ad_manager/v201905/base_rate_service/update_base_rates.py +++ b/examples/ad_manager/v201905/base_rate_service/update_base_rates.py @@ -36,7 +36,7 @@ def main(client, base_rate_id): .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) - .WithBindVariable('id', long(base_rate_id))) + .WithBindVariable('id', int(base_rate_id))) # Get single base rate by statement. response = base_rate_service.getBaseRatesByStatement( @@ -60,15 +60,15 @@ def main(client, base_rate_id): # Display results. if base_rates: for base_rate in base_rates: - print ('Base rate with ID "%s" and type "%s" belonging to ' - 'rate card ID "%s" was updated.' % ( - base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) + print('Base rate with ID "%s" and type "%s" belonging to ' + 'rate card ID "%s" was updated.' % ( + base_rate['id'], + ad_manager.AdManagerClassType(base_rate), + base_rate['rateCardId'])) else: - print 'No base rates were updated.' + print('No base rates were updated.') else: - print 'No base rates found to update.' + print('No base rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py index ae318610..4583fcf2 100755 --- a/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/company_service/create_companies.py b/examples/ad_manager/v201905/company_service/create_companies.py index df7217d5..164f76a4 100755 --- a/examples/ad_manager/v201905/company_service/create_companies.py +++ b/examples/ad_manager/v201905/company_service/create_companies.py @@ -53,8 +53,8 @@ def main(client): # Display results. for company in companies: - print ('Company with ID "%s", name "%s", and type "%s" was created.' - % (company['id'], company['name'], company['type'])) + print('Company with ID "%s", name "%s", and type "%s" was created.' + % (company['id'], company['name'], company['type'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/company_service/get_advertisers.py b/examples/ad_manager/v201905/company_service/get_advertisers.py index d0d096f4..aa4debac 100755 --- a/examples/ad_manager/v201905/company_service/get_advertisers.py +++ b/examples/ad_manager/v201905/company_service/get_advertisers.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/company_service/get_all_companies.py b/examples/ad_manager/v201905/company_service/get_all_companies.py index 22d8529d..96957d13 100755 --- a/examples/ad_manager/v201905/company_service/get_all_companies.py +++ b/examples/ad_manager/v201905/company_service/get_all_companies.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/company_service/update_companies.py b/examples/ad_manager/v201905/company_service/update_companies.py index a1bf8d15..5fb90287 100755 --- a/examples/ad_manager/v201905/company_service/update_companies.py +++ b/examples/ad_manager/v201905/company_service/update_companies.py @@ -40,7 +40,7 @@ def main(client, company_id): # Create statement object to only select a single company by ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') - .WithBindVariable('id', long(company_id)) + .WithBindVariable('id', int(company_id)) .Limit(1)) # Get companies by statement. @@ -57,11 +57,11 @@ def main(client, company_id): # Display results. for company in companies: - print (('Company with ID "%s", name "%s", and comment "%s"' - ' was updated.') - % (company['id'], company['name'], company['comment'])) + print(('Company with ID "%s", name "%s", and comment "%s"' + ' was updated.') + % (company['id'], company['name'], company['comment'])) else: - print 'No companies found to update.' + print('No companies found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/contact_service/create_contacts.py b/examples/ad_manager/v201905/contact_service/create_contacts.py index 03ee90c2..1f9ffcdc 100755 --- a/examples/ad_manager/v201905/contact_service/create_contacts.py +++ b/examples/ad_manager/v201905/contact_service/create_contacts.py @@ -62,8 +62,8 @@ def main(client, advertiser_company_id, agency_company_id): # Display results. for contact in contacts: - print ('Contact with ID "%s" name "%s" was created.' - % (contact['id'], contact['name'])) + print('Contact with ID "%s" name "%s" was created.' + % (contact['id'], contact['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/contact_service/get_all_contacts.py b/examples/ad_manager/v201905/contact_service/get_all_contacts.py index 5fc123fc..10a04a34 100755 --- a/examples/ad_manager/v201905/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201905/contact_service/get_all_contacts.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py index 9542484d..0daf28f9 100755 --- a/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/contact_service/update_contacts.py b/examples/ad_manager/v201905/contact_service/update_contacts.py index 4b5c97c4..309187c7 100755 --- a/examples/ad_manager/v201905/contact_service/update_contacts.py +++ b/examples/ad_manager/v201905/contact_service/update_contacts.py @@ -40,7 +40,7 @@ def main(client, contact_id): # Create statement object to select the single contact by ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') - .WithBindVariable('id', long(contact_id)) + .WithBindVariable('id', int(contact_id)) .Limit(1)) # Get contacts by statement. @@ -58,11 +58,11 @@ def main(client, contact_id): # Display results. for contact in contacts: - print (('Contact with ID "%s", name "%s", and address "%s" ' - 'was updated.') - % (contact['id'], contact['name'], contact['address'])) + print(('Contact with ID "%s", name "%s", and address "%s" ' + 'was updated.') + % (contact['id'], contact['name'], contact['address'])) else: - print 'No contacts found to update.' + print('No contacts found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/__init__.py b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py deleted file mode 100755 index 23ec1a46..00000000 --- a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/create_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the IDs of the custom targeting keys for the hierarchy. -HIERARCHY_LEVEL_ONE_KEY_ID = 'INSERT_LEVEL_ONE_CUSTOM_TARGETING_KEY_ID_HERE' -HIERARCHY_LEVEL_TWO_KEY_ID = 'INSERT_LEVEL_TWO_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, hierarchy_level_one_key_id, hierarchy_level_two_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201905') - - hierarchy_level_1 = { - 'customTargetingKeyId': hierarchy_level_one_key_id, - 'hierarchyLevel': '1' - } - - hierarchy_level_2 = { - 'customTargetingKeyId': hierarchy_level_two_key_id, - 'hierarchyLevel': '2' - } - - hierarchy_levels = [hierarchy_level_1, hierarchy_level_2] - - # Create content metadata key hierarchy object. - content_metadata_key_hierarchy = { - 'name': 'Content Metadata Key Hierarchy #%s' % uuid.uuid4(), - 'hierarchyLevels': hierarchy_levels - } - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .createContentMetadataKeyHierarchies([content_metadata_key_hierarchy])) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id "%s" and name "%s"' - ' was created.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, HIERARCHY_LEVEL_ONE_KEY_ID, - HIERARCHY_LEVEL_TWO_KEY_ID) diff --git a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py deleted file mode 100755 index 44d31e6f..00000000 --- a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/get_all_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 content metadata key hierarchies. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201905') - - # Create a statement to select content metadata key hierarchies. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of content metadata key hierarchies at a time, - # paging through until all content metadata key hierarchies have been - # retrieved. - while True: - response = ( - content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for content_metadata_key_hierarchy in response['results']: - # Print out some information for each content metadata key hierarchy. - print('Content metadata key hierarchy with ID "%d" and name "%s" was ' - 'found.\n' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - statement.offset += statement.limit - else: - break - - print '\nNumber of results found: %s' % response['totalResultSetSize'] - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py b/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py deleted file mode 100755 index 95eaa050..00000000 --- a/examples/ad_manager/v201905/content_metadata_key_hierarchy_service/update_content_metadata_key_hierarchies.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example updates content metadata key hierarchies. - -To determine which content metadata key hierarchies exist, run -get_all_content_metadata_key_hierarchies.py. - -This feature is only available to Video Solutions publishers. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the content metadata key hierarchy to update. -CONTENT_METADATA_KEY_HIERARCHY_ID = ( - 'INSERT_CONTENT_METADATA_KEY_HIERARCHY_ID_HERE') -# Set the ID of the custom targeting key to be added as a hierarchy level. -CUSTOM_TARGETING_KEY_ID = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE' - - -def main(client, content_metadata_key_hierarchy_id, custom_targeting_key_id): - # Initialize appropriate service. - content_metadata_key_hierarchy_service = client.GetService( - 'ContentMetadataKeyHierarchyService', version='v201905') - - # Create a query to select a single content metadata key hierarchy. - - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', long(content_metadata_key_hierarchy_id)) - .Limit(1)) - - # Get a single content metadata key hierarchy by statement. - response = (content_metadata_key_hierarchy_service - .getContentMetadataKeyHierarchiesByStatement( - statement.ToStatement()))[0] - content_metadata_key_hierarchies = (response['results'] - if 'results' in response else None) - - if content_metadata_key_hierarchies: - content_metadata_key_hierarchy = content_metadata_key_hierarchies[0] - - # Update the content metadata key hierarchy by adding a hierarchy level. - hierarchy_levels = content_metadata_key_hierarchy['hierarchyLevels'] - - hierarchy_level = { - 'customTargetingKeyId': custom_targeting_key_id, - 'hierarchyLevel': str(len(hierarchy_levels) + 1) - } - - content_metadata_key_hierarchy['hierarchyLevels'] = ( - hierarchy_levels.append(hierarchy_level)) - - content_metadata_key_hierarchies = ( - content_metadata_key_hierarchy_service - .updateContentMetadataKeyHierarchies(content_metadata_key_hierarchies)) - - # Display results. - for content_metadata_key_hierarchy in content_metadata_key_hierarchies: - print ('Content metadata key hierarchy with id "%s" and name "%s"' - ' was updated.' % (content_metadata_key_hierarchy['id'], - content_metadata_key_hierarchy['name'])) - - else: - print 'No content metadata key hierarchies were found' - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CONTENT_METADATA_KEY_HIERARCHY_ID, - CUSTOM_TARGETING_KEY_ID) diff --git a/examples/ad_manager/v201905/content_service/get_all_content.py b/examples/ad_manager/v201905/content_service/get_all_content.py index 48114111..bcc07cae 100755 --- a/examples/ad_manager/v201905/content_service/get_all_content.py +++ b/examples/ad_manager/v201905/content_service/get_all_content.py @@ -35,12 +35,12 @@ def main(client): for content in response['results']: # Print out some information for each content. print('Content with ID "%d" and name "%s" was found.\n' % - (content['id'], content['name'])) + (content['id'], content['name'].encode('utf-8'))) statement.offset += statement.limit else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_service/copy_image_creatives.py b/examples/ad_manager/v201905/creative_service/copy_image_creatives.py index 10f61ff5..c2632691 100755 --- a/examples/ad_manager/v201905/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201905/creative_service/copy_image_creatives.py @@ -47,11 +47,11 @@ def main(client): image_creative['name'] = 'Copy of %s' % image_creative['name'] result = creative_service.createCreatives([image_creative])[0] - print ('A creative with ID %d, name "%s", and type "%s" was created and ' - 'can be previewed at: %s' % (result['id'], - result['name'], - ad_manager.AdManagerClassType(result), - result['previewUrl'])) + print('A creative with ID %d, name "%s", and type "%s" was created and ' + 'can be previewed at: %s' % (result['id'], + result['name'], + ad_manager.AdManagerClassType(result), + result['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_service/create_creative_from_template.py b/examples/ad_manager/v201905/creative_service/create_creative_from_template.py index e032be95..1f4ec854 100755 --- a/examples/ad_manager/v201905/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201905/creative_service/create_creative_from_template.py @@ -100,9 +100,9 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Template creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Template creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_service/create_creatives.py b/examples/ad_manager/v201905/creative_service/create_creatives.py index a6a94207..15846afd 100755 --- a/examples/ad_manager/v201905/creative_service/create_creatives.py +++ b/examples/ad_manager/v201905/creative_service/create_creatives.py @@ -79,9 +79,9 @@ def main(client, advertiser_id): # Display results. for creative in creatives: - print ('Image creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Image creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_service/create_custom_creative.py b/examples/ad_manager/v201905/creative_service/create_custom_creative.py index a057b2ca..3c7d24e6 100755 --- a/examples/ad_manager/v201905/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201905/creative_service/create_custom_creative.py @@ -77,9 +77,9 @@ def main(client, advertiser_id): # Display results. if creatives: creative = creatives[0] - print ('Template creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], + print('Template creative with id "%s", name "%s", and type "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], ad_manager.AdManagerClassType(creative), creative['previewUrl'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_service/create_native_creative.py b/examples/ad_manager/v201905/creative_service/create_native_creative.py index a18e635b..e9686e61 100755 --- a/examples/ad_manager/v201905/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201905/creative_service/create_native_creative.py @@ -29,8 +29,8 @@ section of our README. """ -import urllib2 import uuid +from urllib.request import urlopen # Import appropriate modules from the client library. from googleads import ad_manager @@ -50,9 +50,9 @@ def main(client, advertiser_id): # Use the system defined native app install creative template. creative_template_id = '10004400' - image_data = urllib2.urlopen(ICON_URL).read() + image_data = urlopen(ICON_URL).read() - app_icon_data = urllib2.urlopen(APP_ICON_SMALL).read() + app_icon_data = urlopen(APP_ICON_SMALL).read() # Create creative from templates. creative = { @@ -122,9 +122,9 @@ def main(client, advertiser_id): creative = creative_service.createCreatives([creative])[0] # Display results. - print ('Native creative with id "%s" and name "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], creative['previewUrl'])) + print('Native creative with id "%s" and name "%s" was ' + 'created and can be previewed at %s.' + % (creative['id'], creative['name'], creative['previewUrl'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/creative_service/get_all_creatives.py b/examples/ad_manager/v201905/creative_service/get_all_creatives.py index 42faf3e3..3556f670 100755 --- a/examples/ad_manager/v201905/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201905/creative_service/get_all_creatives.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_service/get_image_creatives.py b/examples/ad_manager/v201905/creative_service/get_image_creatives.py index b78e8c94..2da94eaa 100755 --- a/examples/ad_manager/v201905/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201905/creative_service/get_image_creatives.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_service/update_creatives.py b/examples/ad_manager/v201905/creative_service/update_creatives.py index 6e24b483..16ac522d 100755 --- a/examples/ad_manager/v201905/creative_service/update_creatives.py +++ b/examples/ad_manager/v201905/creative_service/update_creatives.py @@ -40,7 +40,7 @@ def main(client, image_creative_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') - .WithBindVariable('id', long(image_creative_id)) + .WithBindVariable('id', int(image_creative_id)) .Limit(1)) # Get creatives by statement. @@ -59,10 +59,10 @@ def main(client, image_creative_id): # Display results. for creative in creatives: - print ('Image creative with id "%s" and destination URL "%s" was ' - 'updated.' % (creative['id'], creative['destinationUrl'])) + print('Image creative with id "%s" and destination URL "%s" was ' + 'updated.' % (creative['id'], creative['destinationUrl'])) else: - print 'No creatives found to update.' + print('No creatives found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py index 5152137d..cf629306 100755 --- a/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py @@ -46,8 +46,8 @@ def main(client, creative_set_id, line_item_id): lica = lica_service.createLineItemCreativeAssociations([lica]) # Display results. - print (('LICA with line item ID "%s" and creative set ID "%s" was ' - 'created.') % (lica['lineItemId'], lica['creativeSetId'])) + print(('LICA with line item ID "%s" and creative set ID "%s" was ' + 'created.') % (lica['lineItemId'], lica['creativeSetId'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/creative_set_service/create_creative_set.py b/examples/ad_manager/v201905/creative_set_service/create_creative_set.py index 5d07e01d..731e3353 100755 --- a/examples/ad_manager/v201905/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201905/creative_set_service/create_creative_set.py @@ -50,9 +50,9 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: - print (('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was created.') - % (creative_set['id'], creative_set['masterCreativeId'], + print(('Creative set with ID "%s", master creative ID "%s", and ' + 'companion creative IDs {%s} was created.') + % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py index 90ea61c7..1a7afa26 100755 --- a/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py index 1a933ead..a2b576fd 100755 --- a/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py @@ -45,7 +45,7 @@ def main(client, master_creative_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_set_service/update_creative_set.py b/examples/ad_manager/v201905/creative_set_service/update_creative_set.py index 496da05f..68f9b35e 100755 --- a/examples/ad_manager/v201905/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201905/creative_set_service/update_creative_set.py @@ -42,7 +42,7 @@ def main(client, creative_set_id, companion_creative_id): # Create statement to select a single creative set by ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :creativeSetId') - .WithBindVariable('creativeSetId', long(creative_set_id))) + .WithBindVariable('creativeSetId', int(creative_set_id))) # Get creative set. response = creative_set_service.getCreativeSetsByStatement( @@ -59,12 +59,12 @@ def main(client, creative_set_id, companion_creative_id): # Display results. for creative_set in creative_sets: - print (('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was updated.') - % (creative_set['id'], creative_set['masterCreativeId'], + print(('Creative set with ID "%s", master creative ID "%s", and ' + 'companion creative IDs {%s} was updated.') + % (creative_set['id'], creative_set['masterCreativeId'], ','.join(creative_set['companionCreativeIds']))) else: - print 'No creative sets found to update.' + print('No creative sets found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py index 7dc1d16b..5c26c5fd 100755 --- a/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py index a6dc1392..6e637cee 100755 --- a/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py index 7cdae657..50ec10f8 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py @@ -54,8 +54,8 @@ def main(client, label_id): # Display results. for creative_wrapper in creative_wrappers: - print ('Creative wrapper with ID "%s" applying to label "%s" was ' - 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) + print('Creative wrapper with ID "%s" applying to label "%s" was ' + 'created.' % (creative_wrapper['id'], creative_wrapper['labelId'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py index 6b67424f..87d6c5cf 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py @@ -39,7 +39,7 @@ def main(client, label_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') - .WithBindVariable('labelId', long(label_id))) + .WithBindVariable('labelId', int(label_id))) creative_wrappers_deactivated = 0 @@ -50,11 +50,11 @@ def main(client, label_id): if 'results' in response and len(response['results']): # Display results. for creative_wrapper in response['results']: - print ('Creative wrapper with ID "%s" applying to label "%s" with ' - 'status "%s" will be deactivated.' % - (creative_wrapper['id'], - creative_wrapper['labelId'], - creative_wrapper['status'])) + print('Creative wrapper with ID "%s" applying to label "%s" with ' + 'status "%s" will be deactivated.' % + (creative_wrapper['id'], + creative_wrapper['labelId'], + creative_wrapper['status'])) # Perform action. result = creative_wrapper_service.performCreativeWrapperAction( {'xsi_type': 'DeactivateCreativeWrappers'}, statement.ToStatement()) @@ -66,10 +66,10 @@ def main(client, label_id): # Display results. if creative_wrappers_deactivated > 0: - print ('Number of creative wrappers deactivated: %s' % - creative_wrappers_deactivated) + print('Number of creative wrappers deactivated: %s' % + creative_wrappers_deactivated) else: - print 'No creative wrappers were deactivated.' + print('No creative wrappers were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py index 632cdd46..5ede2feb 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py index 6a79e769..729d4e23 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py index 254cc98e..6e6fc56d 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py @@ -42,7 +42,7 @@ def main(client, creative_wrapper_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', - long(creative_wrapper_id))) + int(creative_wrapper_id))) # Get creative wrappers. response = creative_wrapper_service.getCreativeWrappersByStatement( @@ -60,11 +60,11 @@ def main(client, creative_wrapper_id): # Display results. for creative_wrapper in creative_wrappers: - print (('Creative wrapper with ID "%s" and wrapping order "%s" ' - 'was updated.') % (creative_wrapper['id'], - creative_wrapper['ordering'])) + print(('Creative wrapper with ID "%s" and wrapping order "%s" ' + 'was updated.') % (creative_wrapper['id'], + creative_wrapper['ordering'])) else: - print 'No creative wrappers found to update.' + print('No creative wrappers found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py index 268f6bac..930d0e6e 100755 --- a/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py @@ -58,8 +58,8 @@ def main(client, custom_field_id): # Display results. for custom_field_option in custom_field_options: - print ('Custom field option with ID "%s" and name "%s" was created.' - % (custom_field_option['id'], custom_field_option['displayName'])) + print('Custom field option with ID "%s" and name "%s" was created.' + % (custom_field_option['id'], custom_field_option['displayName'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py index 3fea59d7..54f65d27 100755 --- a/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py @@ -57,8 +57,8 @@ def main(client): # Display results. for custom_field in custom_fields: - print ('Custom field with ID "%s" and name "%s" was created.' - % (custom_field['id'], custom_field['name'])) + print('Custom field with ID "%s" and name "%s" was created.' + % (custom_field['id'], custom_field['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py index c3a1b579..956d5adf 100755 --- a/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -51,8 +51,8 @@ def main(client): if 'results' in response and len(response['results']): # Display results. for custom_field in response['results']: - print ('Custom field with ID "%s" and name "%s" will' - ' be deactivated.' % (custom_field['id'], custom_field['name'])) + print('Custom field with ID "%s" and name "%s" will' + ' be deactivated.' % (custom_field['id'], custom_field['name'])) result = custom_field_service.performCustomFieldAction( {'xsi_type': 'DeactivateCustomFields'}, statement.ToStatement()) if result and int(result['numChanges']) > 0: @@ -62,9 +62,9 @@ def main(client): break if custom_fields_deactivated > 0: - print 'Number of custom fields deactivated: %s' % custom_fields_deactivated + print('Number of custom fields deactivated: %s' % custom_fields_deactivated) else: - print 'No custom fields were deactivated.' + print('No custom fields were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py index 54cd336c..4a4e7935 100755 --- a/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py index babb1efd..fb07534b 100755 --- a/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py index b996819d..0c95fb98 100755 --- a/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py @@ -127,10 +127,10 @@ def main(client, custom_field_id, drop_down_custom_field_id, '{ID: "%s", custom field option ID: "%s"}' % (value['customFieldId'], value['customFieldOptionId'])) custom_field_value_strings.append(custom_field_value_string) - print ('Line item with ID "%s" set with custom field values %s.' - % (line_item['id'], ','.join(custom_field_value_strings))) + print('Line item with ID "%s" set with custom field values %s.' + % (line_item['id'], ','.join(custom_field_value_strings))) else: - print 'Line item or custom field not found.' + print('Line item or custom field not found.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py index 7cfb3b88..a37a71f1 100755 --- a/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py @@ -41,7 +41,7 @@ def main(client, custom_field_id): # Create statement to get a custom field. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :customFieldId') - .WithBindVariable('customFieldId', long(custom_field_id))) + .WithBindVariable('customFieldId', int(custom_field_id))) # Get custom field. custom_fields = custom_field_service.getCustomsFieldByStatement( @@ -56,12 +56,12 @@ def main(client, custom_field_id): # Display results. for custom_field in custom_fields: - print (('Custom field with ID "%s", name "%s", and ' - 'description "%s" was updated.') - % (custom_field['id'], custom_field['name'], + print(('Custom field with ID "%s", name "%s", and ' + 'description "%s" was updated.') + % (custom_field['id'], custom_field['name'], custom_field['description'])) else: - print 'No custom fields found to update.' + print('No custom fields found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py index 9c1fb171..e2e20793 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -63,11 +63,11 @@ def main(client): # Display results. if keys: for key in keys: - print ('A custom targeting key with id "%s", name "%s", and display ' - 'name "%s" was created.' % (key['id'], key['name'], - key['displayName'])) + print('A custom targeting key with id "%s", name "%s", and display ' + 'name "%s" was created.' % (key['id'], key['name'], + key['displayName'])) else: - print 'No keys were created.' + print('No keys were created.') # Create custom targeting value objects. values = [ @@ -119,12 +119,12 @@ def main(client): # Display results. if values: for value in values: - print ('A custom targeting value with id "%s", belonging to key with id' - ' "%s", name "%s", and display name "%s" was created.' - % (value['id'], value['customTargetingKeyId'], value['name'], + print('A custom targeting value with id "%s", belonging to key with id' + ' "%s", name "%s", and display name "%s" was created.' + % (value['id'], value['customTargetingKeyId'], value['name'], value['displayName'])) else: - print 'No values were created.' + print('No values were created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py index 8d4df693..946d8140 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py @@ -65,10 +65,10 @@ def main(client, key_name): break if deleted_custom_targeting_keys > 0: - print ('Number of custom targeting keys deleted: %s' - % deleted_custom_targeting_keys) + print('Number of custom targeting keys deleted: %s' + % deleted_custom_targeting_keys) else: - print 'No custom targeting keys were deleted.' + print('No custom targeting keys were deleted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py index b543ac7c..3bd945e2 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py @@ -66,10 +66,10 @@ def main(client, key_id): break if deleted_custom_targeting_values > 0: - print ('Number of custom targeting values deleted: %s' - % deleted_custom_targeting_values) + print('Number of custom targeting values deleted: %s' + % deleted_custom_targeting_values) else: - print 'No custom targeting values were deleted.' + print('No custom targeting values were deleted.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index cb2d440b..8f66776c 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -63,7 +63,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 202e4d85..2a4e3c6b 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -65,7 +65,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py index 08f63dc5..d2e94d82 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py @@ -34,7 +34,7 @@ def main(client, key_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :keyId') - .WithBindVariable('keyId', long(key_id)) + .WithBindVariable('keyId', int(key_id)) .Limit(1)) # Get custom targeting keys by statement. @@ -54,11 +54,11 @@ def main(client, key_id): # Display results. if keys: for key in keys: - print ('Custom targeting key with id "%s", name "%s", display name ' - '"%s", and type "%s" was updated.' - % (key['id'], key['name'], key['displayName'], key['type'])) + print('Custom targeting key with id "%s", name "%s", display name ' + '"%s", and type "%s" was updated.' + % (key['id'], key['name'], key['displayName'], key['type'])) else: - print 'No custom targeting keys were found to update.' + print('No custom targeting keys were found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py index 53f95599..1798a0da 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py @@ -34,7 +34,7 @@ def main(client, key_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('customTargetingKeyId = :keyId') - .WithBindVariable('keyId', long(key_id))) + .WithBindVariable('keyId', int(key_id))) while True: # Get custom targeting values by statement. @@ -54,15 +54,15 @@ def main(client, key_id): # Display results. for value in values: - print ('Custom targeting value with id "%s", name "%s", and display' - ' name "%s" was updated.' - % (value['id'], value['name'], value['displayName'])) + print('Custom targeting value with id "%s", name "%s", and display' + ' name "%s" was updated.' + % (value['id'], value['name'], value['displayName'])) statement.offset += statement.limit else: break if response['totalResultSetSize'] == 0: - print 'No custom targeting values were updated.' + print('No custom targeting values were updated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py index cdc43a10..eb20f767 100755 --- a/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py +++ b/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py @@ -36,20 +36,20 @@ def main(client): exchange_rate = { 'currencyCode': 'AUD', 'direction': 'FROM_NETWORK', - 'exchangeRate': long(15000000000), + 'exchangeRate': int(15000000000), 'refreshRate': 'FIXED' } created_exchange_rate = exchange_rate_service.createExchangeRates( [exchange_rate])[0] - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was created.' % (created_exchange_rate['id'], - created_exchange_rate['currencyCode'], - created_exchange_rate['direction'], - (float(created_exchange_rate['exchangeRate']) / - 10000000000))) + print('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was created.' % (created_exchange_rate['id'], + created_exchange_rate['currencyCode'], + created_exchange_rate['direction'], + (float(created_exchange_rate['exchangeRate']) / + 10000000000))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py index 870df735..74833d08 100755 --- a/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py index 3591b4a3..dc4e41fc 100755 --- a/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ b/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py @@ -47,7 +47,7 @@ def main(client, currency_code): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py index 8132155a..4543a5f5 100755 --- a/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py +++ b/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py @@ -35,7 +35,7 @@ def main(client, exchange_rate_id): # Create a statement to get an exchange rate by its ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') - .WithBindVariable('id', long(exchange_rate_id)) + .WithBindVariable('id', int(exchange_rate_id)) .Limit(1)) # Get rate cards by statement. @@ -46,23 +46,23 @@ def main(client, exchange_rate_id): exchange_rate = response['results'][0] # Update the exchange rate value to 1.5. - exchange_rate['exchangeRate'] = long(15000000000) + exchange_rate['exchangeRate'] = int(15000000000) exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) if exchange_rates: for exchange_rate in exchange_rates: - print ('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was updated.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) + print('Exchange rate with id \'%s,\' currency code \'%s,\' ' + 'direction \'%s,\' and exchange rate \'%.2f\' ' + 'was updated.' % (exchange_rate['id'], + exchange_rate['currencyCode'], + exchange_rate['direction'], + (float(exchange_rate['exchangeRate']) / + 10000000000))) else: - print 'No exchange rates were updated.' + print('No exchange rates were updated.') else: - print 'No exchange rates found to update.' + print('No exchange rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py index 88fc8ae8..6e5ce768 100755 --- a/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py @@ -176,17 +176,17 @@ def main(client, advertiser_id): contending_line_items = getattr(forecast, 'contendingLineItems', []) # Display results. - print '%s %s matched overall.' % (matched, unit_type) - print '%s%% %s available overall.' % (available_percent_overall, unit_type) - print '%d contending line items overall.' % len(contending_line_items) + print('%s %s matched overall.' % (matched, unit_type)) + print('%s%% %s available overall.' % (available_percent_overall, unit_type)) + print('%d contending line items overall.' % len(contending_line_items)) if possible: - print '%s%% %s possible overall.' % (possible_percent_overall, unit_type) + print('%s%% %s possible overall.' % (possible_percent_overall, unit_type)) if 'breakdowns' in forecast and len(forecast['breakdowns']): for breakdown in forecast['breakdowns']: - print 'For breakdown time period %s - %s:' % ( + print('For breakdown time period %s - %s:' % ( FormatSOAPDateTime(breakdown['startTime']), - FormatSOAPDateTime(breakdown['endTime'])) + FormatSOAPDateTime(breakdown['endTime']))) for breakdown_entry in breakdown['breakdownEntries']: matched = breakdown_entry['forecast']['matched'] available = breakdown_entry['forecast']['available'] @@ -194,13 +194,13 @@ def main(client, advertiser_id): if 'possible' in breakdown_entry['forecast'] else None) name = breakdown_entry['name'] if 'name' in breakdown_entry else None if name: - print '\tFor targeting breakdown named \'%s\'' % name + print('\tFor targeting breakdown named \'%s\'' % name) available_percent, possible_percent = CalculateForecastStats( matched, available, possible) - print '\t\t%s %s matched.' % (matched, unit_type) - print '\t\t%s%% %s available.' % (available_percent, unit_type) + print('\t\t%s %s matched.' % (matched, unit_type)) + print('\t\t%s%% %s available.' % (available_percent, unit_type)) if possible: - print '\t\t%s%% %s possible.' % (possible_percent, unit_type) + print('\t\t%s%% %s possible.' % (possible_percent, unit_type)) def FormatSOAPDateTime(value): diff --git a/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py index c90e8cdc..75736005 100755 --- a/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py @@ -41,8 +41,8 @@ def main(client, line_item_id): # Get forecast for line item. forecast = forecast_service.getAvailabilityForecastById( line_item_id, forecast_options) - matched = long(forecast['matchedUnits']) - available_units = long(forecast['availableUnits']) + matched = int(forecast['matchedUnits']) + available_units = int(forecast['availableUnits']) if matched > 0: available_percent = (float(available_units) / matched) * 100. @@ -52,13 +52,14 @@ def main(client, line_item_id): contending_line_items = getattr(forecast, 'contentingLineItems', []) # Display results. - print '%s %s matched.' % (matched, forecast['unitType'].lower()) - print '%s%% %s available.' % (available_percent, forecast['unitType'].lower()) - print '%d contending line items.' % len(contending_line_items) + print('%s %s matched.' % (matched, forecast['unitType'].lower())) + print('%s%% %s available.' % ( + available_percent, forecast['unitType'].lower())) + print('%d contending line items.' % len(contending_line_items)) if 'possibleUnits' in forecast and matched: - possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100. - print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower()) + possible_percent = (int(forecast['possibleUnits'])/float(matched)) * 100. + print('%s%% %s possible' % (possible_percent, forecast['unitType'].lower())) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py index 00020008..1c6f7546 100755 --- a/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py @@ -35,15 +35,15 @@ def main(client, line_item_id1, line_item_id2): # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( - [line_item_id1, line_item_id2], None) + [line_item_id1, line_item_id2], {'ignoredLineItemIds': []}) for single_forecast in forecast['lineItemDeliveryForecasts']: unit_type = single_forecast['unitType'] - print ('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' - '%d %s predicted\n' % ( - single_forecast['lineItemId'], single_forecast['matchedUnits'], - unit_type, single_forecast['deliveredUnits'], unit_type, - single_forecast['predictedDeliveryUnits'], unit_type)) + print('Forecast for line item %d:\n\t%d %s matched\n\t%d %s delivered\n\t' + '%d %s predicted\n' % ( + single_forecast['lineItemId'], single_forecast['matchedUnits'], + unit_type, single_forecast['deliveredUnits'], unit_type, + single_forecast['predictedDeliveryUnits'], unit_type)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/inventory_service/archive_ad_units.py b/examples/ad_manager/v201905/inventory_service/archive_ad_units.py index dd1e4893..eff00728 100755 --- a/examples/ad_manager/v201905/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201905/inventory_service/archive_ad_units.py @@ -41,7 +41,7 @@ def main(client, parent_id): # unit. statement = (ad_manager.StatementBuilder(version='v201905') .Where('parentId = :parentId or id = :parentId') - .WithBindVariable('parentId', long(parent_id))) + .WithBindVariable('parentId', int(parent_id))) ad_units_archived = 0 @@ -51,8 +51,8 @@ def main(client, parent_id): statement.ToStatement()) if 'results' in response and len(response['results']): for ad_unit in response['results']: - print ('Ad unit with ID "%s" and name "%s" will be archived.' - % (ad_unit['id'], ad_unit['name'])) + print('Ad unit with ID "%s" and name "%s" will be archived.' + % (ad_unit['id'], ad_unit['name'])) # Perform action. result = inventory_service.performAdUnitAction( {'xsi_type': 'ArchiveAdUnits'}, statement.ToStatement()) @@ -64,9 +64,9 @@ def main(client, parent_id): # Display results. if ad_units_archived > 0: - print 'Number of ad units archived: %s' % ad_units_archived + print('Number of ad units archived: %s' % ad_units_archived) else: - print 'No ad units were archived.' + print('No ad units were archived.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/inventory_service/create_ad_units.py b/examples/ad_manager/v201905/inventory_service/create_ad_units.py index 80d56035..bef24f34 100755 --- a/examples/ad_manager/v201905/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201905/inventory_service/create_ad_units.py @@ -61,8 +61,8 @@ def main(client, parent_id): # Display results. for ad_unit in ad_units: - print ('Ad unit with ID "%s" and name "%s" was created.' - % (ad_unit['id'], ad_unit['name'])) + print('Ad unit with ID "%s" and name "%s" was created.' + % (ad_unit['id'], ad_unit['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py index 41d2f83c..a273d85b 100755 --- a/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py @@ -101,8 +101,8 @@ def display_hierarchy_helper(root, parent_id_to_children, depth): parent_id_to_children: The overall map of parent ids to children. depth: The current depth. """ - print '%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), - root['name'], root['id']) + print('%s%s (%s)' % ('%s+--' % ('|'.join([' '] * depth)), + root['name'], root['id'])) # Recurse for each child of this root that has children. for child in parent_id_to_children.get(root['id'], []): diff --git a/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py index a1ea5a80..092188d8 100755 --- a/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py index 211d0af4..b0721ece 100755 --- a/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py @@ -49,7 +49,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/inventory_service/update_ad_units.py b/examples/ad_manager/v201905/inventory_service/update_ad_units.py index c8178607..ef0fc2ba 100755 --- a/examples/ad_manager/v201905/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201905/inventory_service/update_ad_units.py @@ -72,8 +72,8 @@ def main(client, ad_unit_id): ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], size['size']['height']) for size in ad_unit['adUnitSizes']] - print ('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' - % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) + print('Ad unit with ID "%s", name "%s", and sizes [%s] was updated' + % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/label_service/create_labels.py b/examples/ad_manager/v201905/label_service/create_labels.py index ce09719d..67752860 100755 --- a/examples/ad_manager/v201905/label_service/create_labels.py +++ b/examples/ad_manager/v201905/label_service/create_labels.py @@ -46,8 +46,8 @@ def main(client): # Display results. for label in labels: - print ('Label with id "%s", name "%s", and types {%s} was found.' - % (label['id'], label['name'], ','.join(label['types']))) + print('Label with id "%s", name "%s", and types {%s} was found.' + % (label['id'], label['name'], ','.join(label['types']))) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/label_service/deactivate_labels.py b/examples/ad_manager/v201905/label_service/deactivate_labels.py index 4d0ceacc..8734115c 100755 --- a/examples/ad_manager/v201905/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201905/label_service/deactivate_labels.py @@ -41,8 +41,8 @@ def main(client): response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response and len(response['results']): for label in response['results']: - print ('Label with id "%s" and name "%s" will be ' - 'deactivated.' % (label['id'], label['name'])) + print('Label with id "%s" and name "%s" will be ' + 'deactivated.' % (label['id'], label['name'])) # Perform action. result = label_service.performLabelAction( {'xsi_type': 'DeactivateLabels'}, statement.ToStatement()) @@ -54,9 +54,9 @@ def main(client): # Display results. if labels_deactivated > 0: - print 'Number of labels deactivated: %s' % labels_deactivated + print('Number of labels deactivated: %s' % labels_deactivated) else: - print 'No labels were deactivated.' + print('No labels were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/label_service/get_active_labels.py b/examples/ad_manager/v201905/label_service/get_active_labels.py index 8da4ac00..28b308ef 100755 --- a/examples/ad_manager/v201905/label_service/get_active_labels.py +++ b/examples/ad_manager/v201905/label_service/get_active_labels.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/label_service/get_all_labels.py b/examples/ad_manager/v201905/label_service/get_all_labels.py index 551ab193..e93d2a71 100755 --- a/examples/ad_manager/v201905/label_service/get_all_labels.py +++ b/examples/ad_manager/v201905/label_service/get_all_labels.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/label_service/update_labels.py b/examples/ad_manager/v201905/label_service/update_labels.py index 6ae3b127..33a30358 100755 --- a/examples/ad_manager/v201905/label_service/update_labels.py +++ b/examples/ad_manager/v201905/label_service/update_labels.py @@ -34,7 +34,7 @@ def main(client, label_id): # Create a statement to select only active labels. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :labelId') - .WithBindVariable('labelId', long(label_id))) + .WithBindVariable('labelId', int(label_id))) # Get labels by filter. response = label_service.getLabelsByStatement(statement.ToStatement()) @@ -50,10 +50,10 @@ def main(client, label_id): labels = label_service.updateLabels(updated_labels) for label in labels: - print ('Label with id "%s" and name "%s" was updated.' - % (label['id'], label['name'])) + print('Label with id "%s" and name "%s" was updated.' + % (label['id'], label['name'])) else: - print 'No labels found to update.' + print('No labels found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py index ff7215e1..0b092f00 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py @@ -45,11 +45,11 @@ def main(client, line_item_id, creative_ids): # Display results. if licas: for lica in licas: - print ('LICA with line item id "%s", creative id "%s", and ' - 'status "%s" was created.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) + print('LICA with line item id "%s", creative id "%s", and ' + 'status "%s" was created.' % + (lica['lineItemId'], lica['creativeId'], lica['status'])) else: - print 'No LICAs created.' + print('No LICAs created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py index 7df185c1..984ee9ab 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py @@ -36,7 +36,7 @@ def main(client, line_item_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') - .WithBindVariable('lineItemId', long(line_item_id))) + .WithBindVariable('lineItemId', int(line_item_id))) num_deactivated_licas = 0 @@ -46,9 +46,9 @@ def main(client, line_item_id): statement.ToStatement()) if 'results' in response and len(response['results']): for lica in response['results']: - print ('LICA with line item id "%s", creative id "%s", and status' - ' "%s" will be deactivated.' % - (lica['lineItemId'], lica['creativeId'], lica['status'])) + print('LICA with line item id "%s", creative id "%s", and status' + ' "%s" will be deactivated.' % + (lica['lineItemId'], lica['creativeId'], lica['status'])) # Perform action. result = lica_service.performLineItemCreativeAssociationAction( @@ -62,9 +62,9 @@ def main(client, line_item_id): # Display results. if num_deactivated_licas > 0: - print 'Number of LICAs deactivated: %s' % num_deactivated_licas + print('Number of LICAs deactivated: %s' % num_deactivated_licas) else: - print 'No LICAs were deactivated.' + print('No LICAs were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py index 37c66e48..6920c2c8 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py index cd8f0ee0..894048c6 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py @@ -51,7 +51,7 @@ def main(client, line_item_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py index 18737a41..95254f4e 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py @@ -50,15 +50,15 @@ def main(client): # Display results. for lica in licas: - print ('LICA with line item id "%s", creative id "%s", and status ' - '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], - lica['status'])) + print('LICA with line item id "%s", creative id "%s", and status ' + '"%s" was updated.' % (lica['lineItemId'], lica['creativeId'], + lica['status'])) statement.offset += statement.limit else: break if response['totalResultSetSize'] == 0: - print 'No LICAs found to update.' + print('No LICAs found to update.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/line_item_service/activate_line_items.py b/examples/ad_manager/v201905/line_item_service/activate_line_items.py index ba254ad2..9c6017d3 100755 --- a/examples/ad_manager/v201905/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201905/line_item_service/activate_line_items.py @@ -39,7 +39,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) line_items_activated = 0 @@ -49,9 +49,9 @@ def main(client, order_id): statement.ToStatement()) if 'results' in response and len(response['results']): for line_item in response['results']: - print ('Line item with id "%s", belonging to order id "%s", and ' - 'name "%s" will be activated.' % - (line_item['id'], line_item['orderId'], line_item['name'])) + print('Line item with id "%s", belonging to order id "%s", and ' + 'name "%s" will be activated.' % + (line_item['id'], line_item['orderId'], line_item['name'])) # Perform action. result = line_item_service.performLineItemAction( @@ -64,9 +64,9 @@ def main(client, order_id): # Display results. if line_items_activated > 0: - print 'Number of line items activated: %s' % line_items_activated + print('Number of line items activated: %s' % line_items_activated) else: - print 'No line items were activated.' + print('No line items were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_service/create_line_items.py b/examples/ad_manager/v201905/line_item_service/create_line_items.py index 32179684..9fbecedb 100755 --- a/examples/ad_manager/v201905/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201905/line_item_service/create_line_items.py @@ -155,9 +155,9 @@ def main(client, order_id, targeted_placement_ids): # Display results. for line_item in line_items: - print ('Line item with id "%s", belonging to order id "%s", and named ' - '"%s" was created.' % (line_item['id'], line_item['orderId'], - line_item['name'])) + print('Line item with id "%s", belonging to order id "%s", and named ' + '"%s" was created.' % (line_item['id'], line_item['orderId'], + line_item['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/line_item_service/get_all_line_items.py b/examples/ad_manager/v201905/line_item_service/get_all_line_items.py index 9b2e1d72..b5e4d5c2 100755 --- a/examples/ad_manager/v201905/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201905/line_item_service/get_all_line_items.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py index 78c7b9d5..6c983f95 100755 --- a/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py index 6a19b3a6..3b19d5fc 100755 --- a/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py @@ -50,7 +50,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_service/pause_line_items.py b/examples/ad_manager/v201905/line_item_service/pause_line_items.py index c622373d..83a023b3 100755 --- a/examples/ad_manager/v201905/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201905/line_item_service/pause_line_items.py @@ -48,12 +48,12 @@ def main(client): result_set_size = page['totalResultSetSize'] # Iterate over individual results in the page. for line_item in page['results']: - print 'Pausing line item with ID %d' % line_item['id'] + print('Pausing line item with ID %d' % line_item['id']) # Update statement for next page. statement.offset += statement.limit should_continue = statement.offset < result_set_size - print 'Pausing %d line item(s)' % result_set_size + print('Pausing %d line item(s)' % result_set_size) if result_set_size > 0: statement.offset = None @@ -64,9 +64,9 @@ def main(client): {'xsi_type': 'PauseLineItems'}, statement.ToStatement()) if update_result and update_result['numChanges'] > 0: - print 'Updated %d line item(s)' % update_result['numChanges'] + print('Updated %d line item(s)' % update_result['numChanges']) else: - print 'No line items were paused' + print('No line items were paused') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py index c2bb7177..41659293 100755 --- a/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py @@ -83,7 +83,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Create statement to get the line item statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :lineItemId') - .WithBindVariable('lineItemId', long(line_item_id)) + .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) # Set custom criteria targeting on the line item. @@ -96,11 +96,11 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, # Display results. if line_item: - print ('Line item with id "%s" updated with custom criteria targeting:' - % line_item['id']) + print('Line item with id "%s" updated with custom criteria targeting:' + % line_item['id']) pprint.pprint(line_item['targeting']['customTargeting']) else: - print 'No line items were updated.' + print('No line items were updated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/line_item_service/update_line_items.py b/examples/ad_manager/v201905/line_item_service/update_line_items.py index 19966bd3..d89d0e8c 100755 --- a/examples/ad_manager/v201905/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201905/line_item_service/update_line_items.py @@ -36,7 +36,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) - .WithBindVariable('orderId', long(order_id)) + .WithBindVariable('orderId', int(order_id)) .WithBindVariable('deliveryRateType', 'EVENLY') .Limit(500)) @@ -58,14 +58,14 @@ def main(client, order_id): # Display results. if line_items: for line_item in line_items: - print ('Line item with id "%s", belonging to order id "%s", named ' - '"%s", and delivery rate "%s" was updated.' - % (line_item['id'], line_item['orderId'], line_item['name'], + print('Line item with id "%s", belonging to order id "%s", named ' + '"%s", and delivery rate "%s" was updated.' + % (line_item['id'], line_item['orderId'], line_item['name'], line_item['deliveryRateType'])) else: - print 'No line items were updated.' + print('No line items were updated.') else: - print 'No line items found to update.' + print('No line items found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py index 0a3cb053..e9f564e4 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py @@ -33,7 +33,7 @@ def main(client, live_stream_event_id): .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') - .WithBindVariable('id', long(live_stream_event_id)) + .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) live_stream_events_activated = 0 @@ -59,10 +59,10 @@ def main(client, live_stream_event_id): # Display results. if live_stream_events_activated > 0: - print '# of live stream events activated: %s' % ( - live_stream_events_activated) + print('# of live stream events activated: %s' % ( + live_stream_events_activated)) else: - print 'No live stream events were activated.' + print('No live stream events were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py index 7d45acdf..d43833b3 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py index 37d5a3d2..f3a11d93 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py @@ -34,9 +34,9 @@ def main(client, session_ids): if session_ids: for session_id in session_ids: # Print out some information for each live stream event. - print 'Session with ID "%s" registered for monitoring.' % (session_id) + print('Session with ID "%s" registered for monitoring.' % (session_id)) - print '\nNumber of results found: %s' % session_ids.size + print('\nNumber of results found: %s' % session_ids.size) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py index 2c0665d4..d2159231 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py @@ -34,7 +34,7 @@ def main(client, live_stream_event_id): # Create statement object to only select matching live stream event. statement = (ad_manager.StatementBuilder(version='v201905') .Where(('Id = :id')) - .WithBindVariable('id', long(live_stream_event_id)) + .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) # Get live stream events by statement. diff --git a/examples/ad_manager/v201905/native_style_service/create_native_styles.py b/examples/ad_manager/v201905/native_style_service/create_native_styles.py index 48f0d1b5..81c5f804 100755 --- a/examples/ad_manager/v201905/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201905/native_style_service/create_native_styles.py @@ -166,9 +166,9 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, # Display results. for native_style in native_styles: - print ('A Native style with ID "%s", name "%s", and creative template ID' - '"%d" was created.' % (native_style['id'], native_style['name'], - native_style['creativeTemplateId'])) + print('A Native style with ID "%s", name "%s", and creative template ID' + '"%d" was created.' % (native_style['id'], native_style['name'], + native_style['creativeTemplateId'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py index 1a8a98c9..4f0f2956 100755 --- a/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/network_service/get_all_networks.py b/examples/ad_manager/v201905/network_service/get_all_networks.py index 504c35ce..79d9750b 100755 --- a/examples/ad_manager/v201905/network_service/get_all_networks.py +++ b/examples/ad_manager/v201905/network_service/get_all_networks.py @@ -31,7 +31,7 @@ def main(client): print('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['displayName'])) - print '\nNumber of results found: %s' % len(networks) + print('\nNumber of results found: %s' % len(networks)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/network_service/get_current_network.py b/examples/ad_manager/v201905/network_service/get_current_network.py index fbcb7a55..99d190e0 100755 --- a/examples/ad_manager/v201905/network_service/get_current_network.py +++ b/examples/ad_manager/v201905/network_service/get_current_network.py @@ -27,8 +27,8 @@ def main(client): current_network = network_service.getCurrentNetwork() - print ("Current network has network code '%s' and display name '%s'." % - (current_network['networkCode'], current_network['displayName'])) + print("Current network has network code '%s' and display name '%s'." % + (current_network['networkCode'], current_network['displayName'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/network_service/make_test_network.py b/examples/ad_manager/v201905/network_service/make_test_network.py index f3b2babc..f754b4df 100755 --- a/examples/ad_manager/v201905/network_service/make_test_network.py +++ b/examples/ad_manager/v201905/network_service/make_test_network.py @@ -41,11 +41,11 @@ def main(client): network = network_service.makeTestNetwork() # Display results. - print ('Test network with network code "%s" and display name "%s" ' - 'created.' % (network['networkCode'], network['displayName'])) - print ('You may now sign in at ' - 'http://www.google.com/admanager/main?networkCode=%s' - % network['networkCode']) + print('Test network with network code "%s" and display name "%s" ' + 'created.' % (network['networkCode'], network['displayName'])) + print('You may now sign in at ' + 'http://www.google.com/admanager/main?networkCode=%s' + % network['networkCode']) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/order_service/approve_orders.py b/examples/ad_manager/v201905/order_service/approve_orders.py index c21389d8..2c53d896 100755 --- a/examples/ad_manager/v201905/order_service/approve_orders.py +++ b/examples/ad_manager/v201905/order_service/approve_orders.py @@ -44,8 +44,8 @@ def main(client): if 'results' in response and len(response['results']): # Display results. for order in response['results']: - print ('Order with id "%s", name "%s", and status "%s" will be ' - 'approved.' % (order['id'], order['name'], order['status'])) + print('Order with id "%s", name "%s", and status "%s" will be ' + 'approved.' % (order['id'], order['name'], order['status'])) # Perform action. result = order_service.performOrderAction( {'xsi_type': 'ApproveOrders'}, statement.ToStatement()) @@ -57,9 +57,9 @@ def main(client): # Display results. if orders_approved > 0: - print 'Number of orders approved: %s' % orders_approved + print('Number of orders approved: %s' % orders_approved) else: - print 'No orders were approved.' + print('No orders were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/order_service/create_orders.py b/examples/ad_manager/v201905/order_service/create_orders.py index 09faf1bb..6cf1a59e 100755 --- a/examples/ad_manager/v201905/order_service/create_orders.py +++ b/examples/ad_manager/v201905/order_service/create_orders.py @@ -50,8 +50,8 @@ def main(client, company_id, salesperson_id, trafficker_id): # Display results. for order in orders: - print ('Order with id "%s" and name "%s" was created.' - % (order['id'], order['name'])) + print('Order with id "%s" and name "%s" was created.' + % (order['id'], order['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/order_service/get_all_orders.py b/examples/ad_manager/v201905/order_service/get_all_orders.py index c594c0d3..d44761de 100755 --- a/examples/ad_manager/v201905/order_service/get_all_orders.py +++ b/examples/ad_manager/v201905/order_service/get_all_orders.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py index 8d1bc708..37dac560 100755 --- a/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py @@ -51,7 +51,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/order_service/update_orders.py b/examples/ad_manager/v201905/order_service/update_orders.py index 2ffc375d..f3554405 100755 --- a/examples/ad_manager/v201905/order_service/update_orders.py +++ b/examples/ad_manager/v201905/order_service/update_orders.py @@ -34,7 +34,7 @@ def main(client, order_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :orderId') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) # Get orders by statement. response = order_service.getOrdersByStatement(statement.ToStatement()) @@ -54,14 +54,14 @@ def main(client, order_id): # Display results. if orders: for order in orders: - print ('Order with id "%s", name "%s", advertiser id "%s", and ' - 'notes "%s" was updated.' - % (order['id'], order['name'], order['advertiserId'], + print('Order with id "%s", name "%s", advertiser id "%s", and ' + 'notes "%s" was updated.' + % (order['id'], order['name'], order['advertiserId'], order['notes'])) else: - print 'No orders were updated.' + print('No orders were updated.') else: - print 'No orders found to update.' + print('No orders found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/package_service/create_packages.py b/examples/ad_manager/v201905/package_service/create_packages.py index 16cbea3c..cea0e81e 100755 --- a/examples/ad_manager/v201905/package_service/create_packages.py +++ b/examples/ad_manager/v201905/package_service/create_packages.py @@ -51,8 +51,8 @@ def main(client): result = package_service.createPackages([package]) for new_package in result: - print ('A package with ID %d and name "%s" was created' % - (new_package['id'], new_package['name'])) + print('A package with ID %d and name "%s" was created' % + (new_package['id'], new_package['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py index cfc5c1f5..db8b32ae 100755 --- a/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py +++ b/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py @@ -42,9 +42,9 @@ def main(client): package = query_result['results'][0] - print ('Package with ID %d will create proposal line items using product ' - 'package with ID %d.' % (package['id'], - package['productPackageId'])) + print('Package with ID %d will create proposal line items using product ' + 'package with ID %d.' % (package['id'], + package['productPackageId'])) # Remove limit and offset from statement. statement.limit = None @@ -56,10 +56,10 @@ def main(client): statement.ToStatement()) if result and result['numChanges'] > 0: - print ('Number of packages that proposal line items were created for: %d' % - result['numChanges']) + print('Number of packages that proposal line items were created for: %d' % + result['numChanges']) else: - print 'No proposal line items were created.' + print('No proposal line items were created.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/package_service/get_all_packages.py b/examples/ad_manager/v201905/package_service/get_all_packages.py index 7cbf6d67..fd515a65 100755 --- a/examples/ad_manager/v201905/package_service/get_all_packages.py +++ b/examples/ad_manager/v201905/package_service/get_all_packages.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/package_service/get_in_progress_packages.py b/examples/ad_manager/v201905/package_service/get_in_progress_packages.py index 0df5ab35..e7e4ea20 100755 --- a/examples/ad_manager/v201905/package_service/get_in_progress_packages.py +++ b/examples/ad_manager/v201905/package_service/get_in_progress_packages.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/placement_service/create_placements.py b/examples/ad_manager/v201905/placement_service/create_placements.py index 8fb2f4a7..25987a82 100755 --- a/examples/ad_manager/v201905/placement_service/create_placements.py +++ b/examples/ad_manager/v201905/placement_service/create_placements.py @@ -98,9 +98,9 @@ def main(client): ad_unit_ids = '' if 'targetedAdUnitIds' in placement: ad_unit_ids = ', '.join(placement['targetedAdUnitIds']) - print ('A Placement with ID "%s", name "%s", and containing ad units ' - '{%s} was created.' % (placement['id'], placement['name'], - ad_unit_ids)) + print('A Placement with ID "%s", name "%s", and containing ad units ' + '{%s} was created.' % (placement['id'], placement['name'], + ad_unit_ids)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/placement_service/deactivate_placements.py b/examples/ad_manager/v201905/placement_service/deactivate_placements.py index 706cab7c..e0c5869b 100755 --- a/examples/ad_manager/v201905/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201905/placement_service/deactivate_placements.py @@ -33,7 +33,7 @@ def main(client, placement_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :placementId') - .WithBindVariable('placementId', long(placement_id)) + .WithBindVariable('placementId', int(placement_id)) .Limit(1)) # Get placements by statement. @@ -41,9 +41,9 @@ def main(client, placement_id): statement.ToStatement()) for placement in placements: - print ('Placement with id "%s", name "%s", and status "%s" will be ' - 'deactivated.' % (placement['id'], placement['name'], - placement['status'])) + print('Placement with id "%s", name "%s", and status "%s" will be ' + 'deactivated.' % (placement['id'], placement['name'], + placement['status'])) # Perform action. result = placement_service.performPlacementAction( @@ -51,9 +51,9 @@ def main(client, placement_id): # Display results. if result and int(result['numChanges']) > 0: - print 'Number of placements deactivated: %s' % result['numChanges'] + print('Number of placements deactivated: %s' % result['numChanges']) else: - print 'No placements were deactivated.' + print('No placements were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/placement_service/get_active_placements.py b/examples/ad_manager/v201905/placement_service/get_active_placements.py index db59202b..5373373b 100755 --- a/examples/ad_manager/v201905/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201905/placement_service/get_active_placements.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/placement_service/get_all_placements.py b/examples/ad_manager/v201905/placement_service/get_all_placements.py index 3a5f21d8..7652add1 100755 --- a/examples/ad_manager/v201905/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201905/placement_service/get_all_placements.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/placement_service/update_placements.py b/examples/ad_manager/v201905/placement_service/update_placements.py index 23df13d4..a3f4aa7f 100755 --- a/examples/ad_manager/v201905/placement_service/update_placements.py +++ b/examples/ad_manager/v201905/placement_service/update_placements.py @@ -49,8 +49,8 @@ def main(client, placement_id): updated_placements = placement_service.updatePlacements([placement]) for placement in updated_placements: - print ('Placement with id "%s" and name "%s" was updated.' - % (placement['id'], placement['name'])) + print('Placement with id "%s" and name "%s" was updated.' + % (placement['id'], placement['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py index ca0e69f2..4cf8efc8 100755 --- a/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py +++ b/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py @@ -73,9 +73,9 @@ def main(client, rate_card_id): # Display results. for premium_rate in premium_rates: - print ('A premium rate for "%s" was added to the rate card with ID' - ' of "%s".\n' - % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), + print('A premium rate for "%s" was added to the rate card with ID' + ' of "%s".\n' + % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), premium_rate['id'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py index ab90ec52..5b85a494 100755 --- a/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py index 2f01430b..a7aef244 100755 --- a/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py +++ b/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py @@ -47,7 +47,7 @@ def main(client, rate_card_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py index 7fd99849..b56cde27 100755 --- a/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py +++ b/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py @@ -36,7 +36,7 @@ def main(client, premium_rate_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') .OrderBy('id', ascending=True) - .WithBindVariable('id', long(premium_rate_id)) + .WithBindVariable('id', int(premium_rate_id)) .Limit(1)) # Get the premium rate. @@ -72,13 +72,13 @@ def main(client, premium_rate_id): # Display results. if premium_rates: for premium_rate in premium_rates: - print ('Premium rate with ID "%s", associated with rate card id' - ' "%s" was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) + print('Premium rate with ID "%s", associated with rate card id' + ' "%s" was updated.' % (premium_rate['id'], + premium_rate['rateCardId'])) else: - print 'No premium rates were updated.' + print('No premium rates were updated.') else: - print 'No premium rates found to update.' + print('No premium rates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py index b9fa1a4c..b60ed465 100755 --- a/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py +++ b/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py @@ -49,11 +49,11 @@ def main(client): [product_package_item]) for new_product_package_item in result: - print ('A product package with ID %d created from product ID %d ' - 'belonging to product package with ID %d was created.' % - (new_product_package_item['id'], - new_product_package_item['productId'], - new_product_package_item['productPackageId'])) + print('A product package with ID %d created from product ID %d ' + 'belonging to product package with ID %d was created.' % + (new_product_package_item['id'], + new_product_package_item['productId'], + new_product_package_item['productPackageId'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py index e677a43b..40656642 100755 --- a/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py +++ b/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py @@ -44,7 +44,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py index 8ba5ad20..8726e3bc 100755 --- a/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py +++ b/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py @@ -47,7 +47,7 @@ def main(client, product_package_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_package_service/create_product_packages.py b/examples/ad_manager/v201905/product_package_service/create_product_packages.py index 43f2e6f6..685c4bfb 100755 --- a/examples/ad_manager/v201905/product_package_service/create_product_packages.py +++ b/examples/ad_manager/v201905/product_package_service/create_product_packages.py @@ -41,8 +41,8 @@ def main(client): result = product_package_service.createProductPackages([product_package]) for new_product_package in result: - print ('A product package with ID %d and name "%s" was created.' % - (new_product_package['id'], new_product_package['name'])) + print('A product package with ID %d and name "%s" was created.' % + (new_product_package['id'], new_product_package['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py index 139c1ed1..606fe4b6 100755 --- a/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py +++ b/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py index e50f40e4..ef5a723c 100755 --- a/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_service/get_all_products.py b/examples/ad_manager/v201905/product_service/get_all_products.py index 3a6a2561..6a4ca8ef 100755 --- a/examples/ad_manager/v201905/product_service/get_all_products.py +++ b/examples/ad_manager/v201905/product_service/get_all_products.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_service/get_products_for_product_template.py b/examples/ad_manager/v201905/product_service/get_products_for_product_template.py index 51b58500..48adf096 100755 --- a/examples/ad_manager/v201905/product_service/get_products_for_product_template.py +++ b/examples/ad_manager/v201905/product_service/get_products_for_product_template.py @@ -44,7 +44,7 @@ def main(client, product_template_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_service/update_products.py b/examples/ad_manager/v201905/product_service/update_products.py index 75905cbc..d2c571ac 100755 --- a/examples/ad_manager/v201905/product_service/update_products.py +++ b/examples/ad_manager/v201905/product_service/update_products.py @@ -34,7 +34,7 @@ def main(client, product_id): # Create statement object to select a single product by an ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') - .WithBindVariable('id', long(product_id)) + .WithBindVariable('id', int(product_id)) .Limit(1)) # Get products by statement. @@ -53,13 +53,13 @@ def main(client, product_id): # Display results. if products: for product in products: - print ('Product with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (product['id'], product['name'], product['notes'])) + print('Product with id "%s", name "%s", and ' + 'notes "%s" was updated.' + % (product['id'], product['name'], product['notes'])) else: - print 'No products were updated.' + print('No products were updated.') else: - print 'No products found to update.' + print('No products found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_template_service/activate_product_templates.py b/examples/ad_manager/v201905/product_template_service/activate_product_templates.py index eb087342..dba227c0 100755 --- a/examples/ad_manager/v201905/product_template_service/activate_product_templates.py +++ b/examples/ad_manager/v201905/product_template_service/activate_product_templates.py @@ -36,7 +36,7 @@ def main(client, product_template_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') - .WithBindVariable('id', long(product_template_id)) + .WithBindVariable('id', int(product_template_id)) .Limit(1)) product_templates_activated = 0 @@ -47,9 +47,9 @@ def main(client, product_template_id): statement.ToStatement()) if 'results' in response and len(response['results']): for product_template in response['results']: - print ('Product template with id "%s" and name "%s" will be ' - 'activated.' % (product_template['id'], - product_template['name'])) + print('Product template with id "%s" and name "%s" will be ' + 'activated.' % (product_template['id'], + product_template['name'])) # Perform action. result = product_template_service.performProductTemplateAction( @@ -62,10 +62,10 @@ def main(client, product_template_id): # Display results. if product_templates_activated > 0: - print ('Number of product templates ' - 'activated: %s' % product_templates_activated) + print('Number of product templates ' + 'activated: %s' % product_templates_activated) else: - print 'No product templates were activated.' + print('No product templates were activated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_template_service/create_product_templates.py b/examples/ad_manager/v201905/product_template_service/create_product_templates.py index bad5121e..99b51466 100755 --- a/examples/ad_manager/v201905/product_template_service/create_product_templates.py +++ b/examples/ad_manager/v201905/product_template_service/create_product_templates.py @@ -99,8 +99,8 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A product template with ID "%s" and name "%s" was ' - 'created.' % (product_template['id'], product_template['name'])) + print('A product template with ID "%s" and name "%s" was ' + 'created.' % (product_template['id'], product_template['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py index 866b241c..1c7fcdf1 100755 --- a/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py +++ b/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py @@ -80,9 +80,9 @@ def main(client): if product_templates: for product_template in product_templates: - print ('A programmatic product template with ID "%s" and name "%s" ' - 'was created.' % (product_template['id'], - product_template['name'])) + print('A programmatic product template with ID "%s" and name "%s" ' + 'was created.' % (product_template['id'], + product_template['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py index c3f4e639..c354925f 100755 --- a/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py index d5eadf3d..8364ceeb 100755 --- a/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py +++ b/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/product_template_service/update_product_templates.py b/examples/ad_manager/v201905/product_template_service/update_product_templates.py index aa313ecc..8ac48f78 100755 --- a/examples/ad_manager/v201905/product_template_service/update_product_templates.py +++ b/examples/ad_manager/v201905/product_template_service/update_product_templates.py @@ -36,7 +36,7 @@ def main(client, product_template_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') .OrderBy('id', ascending=True) - .WithBindVariable('id', long(product_template_id)) + .WithBindVariable('id', int(product_template_id)) .Limit(1)) # Get product templates by statement. @@ -80,12 +80,12 @@ def main(client, product_template_id): # Display results. if product_templates: for product_template in product_templates: - print ('Product template with id "%s" and name "%s" was ' - 'updated.' % (product_template['id'], product_template['name'])) + print('Product template with id "%s" and name "%s" was ' + 'updated.' % (product_template['id'], product_template['name'])) else: - print 'No product templates were updated.' + print('No product templates were updated.') else: - print 'No product templates found to update.' + print('No product templates found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py index f2c91dad..9ce652bf 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py @@ -36,7 +36,7 @@ def main(client, proposal_line_item_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') - .WithBindVariable('id', long(proposal_line_item_id)) + .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) proposal_line_items_archived = 0 @@ -47,11 +47,11 @@ def main(client, proposal_line_item_id): statement.ToStatement()) if 'results' in response and len(response['results']): for proposal_line_item in response['results']: - print ('Proposal line item with id "%s", ' - 'belonging to proposal id "%s", and ' - 'name "%s" will be archived.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", ' + 'belonging to proposal id "%s", and ' + 'name "%s" will be archived.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) # Perform action. result = proposal_line_item_service.performProposalLineItemAction( @@ -64,10 +64,10 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items_archived > 0: - print ('Number of proposal line items ' - 'archived: %s' % proposal_line_items_archived) + print('Number of proposal line items ' + 'archived: %s' % proposal_line_items_archived) else: - print 'No proposal line items were archived.' + print('No proposal line items were archived.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py index 4db1b897..dfd61a15 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py @@ -91,10 +91,10 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item with id "%s", belonging to ' - 'proposal id "%s", and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Programmatic proposal line item with id "%s", belonging to ' + 'proposal id "%s", and named "%s" was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py index f0384e66..a8bfefdc 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py @@ -99,11 +99,11 @@ def main(client, proposal_id, product_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Programmatic proposal line item for non-sales management with id ' - '"%s", belonging to proposal id "%s", and named "%s" ' - 'was created.' % (proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Programmatic proposal line item for non-sales management with id ' + '"%s", belonging to proposal id "%s", and named "%s" ' + 'was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py index a0ec6c3e..51bb7d79 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py @@ -92,10 +92,10 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print ('Proposal line item with id "%s", belonging to proposal id "%s"' - ', and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", belonging to proposal id "%s"' + ', and named "%s" was created.' % + (proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py index f5aa3104..68d23ed9 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py index e4be6d25..1e3168bc 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -45,7 +45,7 @@ def main(client, proposal_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py index 39aec9da..f1114575 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py @@ -37,7 +37,7 @@ def main(client, proposal_line_item_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') - .WithBindVariable('id', long(proposal_line_item_id)) + .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) # Get proposal line items by statement. @@ -56,14 +56,14 @@ def main(client, proposal_line_item_id): # Display results. if proposal_line_items: for proposal_line_item in proposal_line_items: - print ('Line item with id "%s", belonging to proposal id "%s" and,' - ' named "%s" was updated.' % ( - proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Line item with id "%s", belonging to proposal id "%s" and,' + ' named "%s" was updated.' % ( + proposal_line_item['id'], proposal_line_item['proposalId'], + proposal_line_item['name'])) else: - print 'No proposal line items were updated.' + print('No proposal line items were updated.') else: - print 'No proposal line items found to update.' + print('No proposal line items found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_service/create_proposals.py b/examples/ad_manager/v201905/proposal_service/create_proposals.py index 12437bea..1d51eafc 100755 --- a/examples/ad_manager/v201905/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201905/proposal_service/create_proposals.py @@ -67,8 +67,8 @@ def main(client, advertiser_id, primary_salesperson_id, # Display results. for proposal in proposals: - print ('Proposal with id "%s" and name "%s" was created.' - % (proposal['id'], proposal['name'])) + print('Proposal with id "%s" and name "%s" was created.' + % (proposal['id'], proposal['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/proposal_service/get_all_proposals.py b/examples/ad_manager/v201905/proposal_service/get_all_proposals.py index ffd23d4f..f891d591 100755 --- a/examples/ad_manager/v201905/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201905/proposal_service/get_all_proposals.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py index f601235b..93194a1d 100755 --- a/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py @@ -47,7 +47,7 @@ def main(client, proposal_id): print('Marketplace comment with creation time "%s"and comment "%s" was ' 'found.\n' % (date_time_string, marketplace_comment['comment'])) - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py index 2d6dccb2..c2575eeb 100755 --- a/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py @@ -41,7 +41,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py index 22b09c42..b7de144a 100755 --- a/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py @@ -40,10 +40,10 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: - print ('Programmatic proposal with id "%s", name "%s", and status ' - '"%s" will be pushed to Marketplace.' % (proposal['id'], - proposal['name'], - proposal['status'])) + print('Programmatic proposal with id "%s", name "%s", and status ' + '"%s" will be pushed to Marketplace.' % (proposal['id'], + proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'RequestBuyerAcceptance'}, statement.ToStatement()) @@ -55,10 +55,10 @@ def main(client, proposal_id): # Display results. if proposals_pushed_to_marketplace > 0: - print ('\nNumber of programmatic proposals pushed to Marketplace: %s' - % proposals_pushed_to_marketplace) + print('\nNumber of programmatic proposals pushed to Marketplace: %s' + % proposals_pushed_to_marketplace) else: - print '\nNo programmatic proposals were pushed to Marketplace.' + print('\nNo programmatic proposals were pushed to Marketplace.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py index 8e3de01b..2e5cb8a1 100755 --- a/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py +++ b/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py @@ -42,9 +42,9 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for proposal in response['results']: - print ('Proposal with id "%s", name "%s", and status "%s" will be' - ' approved.' % (proposal['id'], proposal['name'], - proposal['status'])) + print('Proposal with id "%s", name "%s", and status "%s" will be' + ' approved.' % (proposal['id'], proposal['name'], + proposal['status'])) # Perform action. result = proposal_service.performProposalAction( {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) @@ -56,9 +56,9 @@ def main(client, proposal_id): # Display results. if proposals_approved > 0: - print '\nNumber of proposals approved: %s' % proposals_approved + print('\nNumber of proposals approved: %s' % proposals_approved) else: - print '\nNo proposals were approved.' + print('\nNo proposals were approved.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/proposal_service/update_proposals.py b/examples/ad_manager/v201905/proposal_service/update_proposals.py index 65a32176..48701056 100755 --- a/examples/ad_manager/v201905/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201905/proposal_service/update_proposals.py @@ -34,7 +34,7 @@ def main(client, proposal_id): statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :proposalId') - .WithBindVariable('proposalId', long(proposal_id)) + .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) # Get proposals by statement. @@ -53,13 +53,13 @@ def main(client, proposal_id): # Display results. if proposals: for proposal in proposals: - print ('Proposal with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (proposal['id'], proposal['name'], proposal['internalNotes'])) + print('Proposal with id "%s", name "%s", and ' + 'notes "%s" was updated.' + % (proposal['id'], proposal['name'], proposal['internalNotes'])) else: - print 'No proposals were updated.' + print('No proposals were updated.') else: - print 'No proposals found to update.' + print('No proposals found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py index 79e9d467..68c6707a 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py @@ -45,8 +45,8 @@ def main(client): line_items_file.close() ad_units_file.close() - print 'Saved line items to... %s' % line_items_file.name - print 'Saved ad units to... %s' % ad_units_file.name + print('Saved line items to... %s' % line_items_file.name) + print('Saved ad units to... %s' % ad_units_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py index eaf42c4b..23f51b7e 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py @@ -46,7 +46,7 @@ def main(client): report_downloader.DownloadPqlResultToCsv( browser_pql_query, browser_data_file) - print 'Saved browser data to... %s' % browser_data_file.name + print('Saved browser data to... %s' % browser_data_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py index b9343f44..2e70aa63 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py @@ -40,7 +40,7 @@ def main(client): programmatic_buyers_file.close() - print 'Saved programmatic buyers to... %s' % programmatic_buyers_file.name + print('Saved programmatic buyers to... %s' % programmatic_buyers_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py index 0648bbf6..3b5a9df0 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py @@ -26,7 +26,7 @@ GEO_TARGET_TYPE = 'City' -def main(client, geo_target_type): +def main(client): # Initialize a report downloader. report_downloader = client.GetDataDownloader(version='v201905') @@ -44,7 +44,7 @@ def main(client, geo_target_type): report_downloader.DownloadPqlResultToCsv( geo_pql_query, geo_data_file, {'type': geo_target_type}) - print 'Saved geo data to... %s' % geo_data_file.name + print('Saved geo data to... %s' % geo_data_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py index 2dec29a2..fdec7c7c 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py @@ -39,7 +39,7 @@ def main(client): report_downloader.DownloadPqlResultToCsv( line_items_pql_query, line_items_file) - print 'Saved line items to... %s' % line_items_file.name + print('Saved line items to... %s' % line_items_file.name) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py index fa025b0d..2f442c08 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py @@ -70,17 +70,17 @@ def main(client): statement.Where(pagination_query) statement.WithBindVariable('id', last_id) - print ('%d) %d changes prior to ID "%s" were found.\n' - % (i, rows_length, last_id)) + print('%d) %d changes prior to ID "%s" were found.\n' + % (i, rows_length, last_id)) keep_iterating = rows and len(rows) == statement.limit # Print out columns header - print ','.join(column_types) + print(','.join(column_types)) # Print out every row for row in total_rows: - print ConvertValueForCsv(row) + print(ConvertValueForCsv(row)) def ConvertValueForCsv(pql_value): diff --git a/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py index 5639ddae..cd10de46 100755 --- a/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py +++ b/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py @@ -48,10 +48,10 @@ def main(client): result = rate_card_service.createRateCards([rate_card]) for new_rate_card in result: - print ('A rate card with ID %s, name "%s", and currency code "%s" ' - 'was created.' % (new_rate_card['id'], - new_rate_card['name'], - new_rate_card['currencyCode'])) + print('A rate card with ID %s, name "%s", and currency code "%s" ' + 'was created.' % (new_rate_card['id'], + new_rate_card['name'], + new_rate_card['currencyCode'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py index ca48f700..04a80438 100755 --- a/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py +++ b/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py @@ -42,7 +42,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py index 4f209b67..c4020d69 100755 --- a/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py +++ b/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py @@ -45,7 +45,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py index 57430710..1d003163 100755 --- a/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py @@ -55,18 +55,18 @@ def main(client): result_set_size += page['totalResultSetSize'] # Iterate over individual results in the page. for line_item_report in page['results']: - print ('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source "%s", and reconciled volume %d was ' - 'found.' % (line_item_report['id'], - line_item_report['lineItemId'], - line_item_report['reconciliationSource'], - (line_item_report['reconciledVolume'] - if 'reconciledVolume' in line_item_report else 0))) + print('Reconciliation line item report with ID %d, line item ID %d, ' + 'reconciliation source "%s", and reconciled volume %d was ' + 'found.' % (line_item_report['id'], + line_item_report['lineItemId'], + line_item_report['reconciliationSource'], + (line_item_report['reconciledVolume'] + if 'reconciledVolume' in line_item_report else 0))) # Update statement for next page. statement.offset += statement.limit should_continue = statement.offset < result_set_size - print 'Number of results found: %d' % result_set_size + print('Number of results found: %d' % result_set_size) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py index ecdfacf7..925cdbc6 100755 --- a/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ b/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py @@ -56,10 +56,10 @@ def main(client): .updateReconciliationLineItemReports([line_item_report])) for updated_report in result: - print ('Reconciliation line item report with ID %d for line item ID %d was ' - 'updated, with manual volume %d' % (updated_report['id'], - updated_report['lineItemId'], - updated_report['manualVolume'])) + print('Reconciliation line item report with ID %d for line item ID %d was ' + 'updated, with manual volume %d' % (updated_report['id'], + updated_report['lineItemId'], + updated_report['manualVolume'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py index f013e3a6..37494b6f 100755 --- a/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ b/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py @@ -49,7 +49,7 @@ def main(client, reconciliation_report_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py index 2b09b47c..7c46cb83 100755 --- a/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ b/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py @@ -45,8 +45,8 @@ def main(client): report = page['results'][0] - print ('Reconciliation order report with ID %d will be submitted.' % - report['id']) + print('Reconciliation order report with ID %d will be submitted.' % + report['id']) # Remove limit and offset from statement. statement.limit = None @@ -59,10 +59,10 @@ def main(client): statement.ToStatement())) if result and result['numChanges'] > 0: - print ('Number of reconciliation order reports submitted: %d' % - result['numChanges']) + print('Number of reconciliation order reports submitted: %d' % + result['numChanges']) else: - print 'No reconciliation order reports were submitted.' + print('No reconciliation order reports were submitted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py index 20e3f822..3eabadf2 100755 --- a/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ b/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py @@ -34,7 +34,7 @@ def main(client, reconciliation_report_id): .Where(('reconciliationReportId = :reportId ' 'AND lineItemId != :lineItemId')) .WithBindVariable('lineItemId', 0) - .WithBindVariable('reportId', long(reconciliation_report_id))) + .WithBindVariable('reportId', int(reconciliation_report_id))) # Retrieve a small amount of reconciliation report rows at a time, paging # through until all reconciliation report rows have been retrieved. @@ -55,7 +55,7 @@ def main(client, reconciliation_report_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py index 9bbcb882..545d13d4 100755 --- a/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ b/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py @@ -63,10 +63,10 @@ def main(client): .updateReconciliationReportRows([row])) for updated_row in updated_rows: - print ('Reconciliation report row for line item ID %d and creative ID %d ' - 'was updated, with manual volume %d' % (updated_row['lineItemId'], - updated_row['creativeId'], - updated_row['manualVolume'])) + print('Reconciliation report row for line item ID %d and creative ID %d ' + 'was updated, with manual volume %d' % (updated_row['lineItemId'], + updated_row['creativeId'], + updated_row['manualVolume'])) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py index 4696745a..eb1e8d5e 100755 --- a/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py +++ b/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py @@ -47,7 +47,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py index bcfb4210..d9bf4efd 100755 --- a/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ b/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py @@ -54,7 +54,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py index 7ad98b1f..64704452 100755 --- a/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py @@ -42,8 +42,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -57,8 +57,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/report_service/run_delivery_report.py b/examples/ad_manager/v201905/report_service/run_delivery_report.py index 7bf193d1..dd6d6d88 100755 --- a/examples/ad_manager/v201905/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201905/report_service/run_delivery_report.py @@ -34,7 +34,7 @@ def main(client, order_id): # Create statement object to filter for an order. statement = (ad_manager.StatementBuilder(version='v201905') .Where('ORDER_ID = :id') - .WithBindVariable('id', long(order_id)) + .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports .Offset(None)) @@ -64,8 +64,8 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -79,8 +79,8 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/report_service/run_inventory_report.py b/examples/ad_manager/v201905/report_service/run_inventory_report.py index 1becffc6..046f7c19 100755 --- a/examples/ad_manager/v201905/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201905/report_service/run_inventory_report.py @@ -36,7 +36,7 @@ def main(client): # Set filter statement and bind value for reportQuery. statement = (ad_manager.StatementBuilder(version='v201905') .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') - .WithBindVariable('parentAdUnitId', long(root_ad_unit_id)) + .WithBindVariable('parentAdUnitId', int(root_ad_unit_id)) .Limit(None) # No limit or offset for reports .Offset(None)) @@ -58,8 +58,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -73,8 +73,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/report_service/run_reach_report.py b/examples/ad_manager/v201905/report_service/run_reach_report.py index 8cc78626..a5bebcdc 100755 --- a/examples/ad_manager/v201905/report_service/run_reach_report.py +++ b/examples/ad_manager/v201905/report_service/run_reach_report.py @@ -39,8 +39,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -54,8 +54,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py index 9d72cb5e..5b8ee8e2 100755 --- a/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py @@ -59,8 +59,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) with tempfile.NamedTemporaryFile( suffix='.csv.gz', mode='wb', delete=False) as report_file: diff --git a/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py index 6f351771..0c04a6ac 100755 --- a/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py @@ -35,7 +35,7 @@ def main(client, order_id): # Filter for line items of a given order. statement = (ad_manager.StatementBuilder(version='v201905') .Where('orderId = :orderId') - .WithBindVariable('orderId', long(order_id))) + .WithBindVariable('orderId', int(order_id))) # Collect all line item custom field IDs for an order. custom_field_ids = set() @@ -73,8 +73,8 @@ def main(client, order_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -88,8 +88,8 @@ def main(client, order_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/report_service/run_sales_report.py b/examples/ad_manager/v201905/report_service/run_sales_report.py index 28b1c714..c5a1f92d 100755 --- a/examples/ad_manager/v201905/report_service/run_sales_report.py +++ b/examples/ad_manager/v201905/report_service/run_sales_report.py @@ -40,8 +40,8 @@ def main(client): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -55,8 +55,8 @@ def main(client): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/report_service/run_saved_query.py b/examples/ad_manager/v201905/report_service/run_saved_query.py index f19dbae8..5887e589 100755 --- a/examples/ad_manager/v201905/report_service/run_saved_query.py +++ b/examples/ad_manager/v201905/report_service/run_saved_query.py @@ -36,7 +36,7 @@ def main(client, saved_query_id): # Create statement object to filter for an order. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :id') - .WithBindVariable('id', long(saved_query_id)) + .WithBindVariable('id', int(saved_query_id)) .Limit(1)) response = report_service.getSavedQueriesByStatement( @@ -54,8 +54,8 @@ def main(client, saved_query_id): try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError, e: - print 'Failed to generate report. Error was: %s' % e + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) # Change to your preferred export format. export_format = 'CSV_DUMP' @@ -68,10 +68,10 @@ def main(client, saved_query_id): report_file.close() # Display results. - print 'Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name) + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) else: - print 'The query specified is not compatible with the API version.' + print('The query specified is not compatible with the API version.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 88da4959..dbd02daa 100755 --- a/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -44,9 +44,9 @@ def main(client): if 'results' in response and len(response['results']): # Print suggested ad units that will be approved. for suggested_ad_unit in response['results']: - print ('Suggested ad unit with id "%s", and number of requests "%s"' - ' will be approved.' % (suggested_ad_unit['id'], - suggested_ad_unit['numRequests'])) + print('Suggested ad unit with id "%s", and number of requests "%s"' + ' will be approved.' % (suggested_ad_unit['id'], + suggested_ad_unit['numRequests'])) # Approve suggested ad units. result = suggested_ad_unit_service.performSuggestedAdUnitAction( @@ -58,10 +58,10 @@ def main(client): break if num_approved_suggested_ad_units > 0: - print ('Number of suggested ad units approved: %s' % - num_approved_suggested_ad_units) + print('Number of suggested ad units approved: %s' % + num_approved_suggested_ad_units) else: - print 'No suggested ad units were approved.' + print('No suggested ad units were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py index aa279f00..fb32e663 100755 --- a/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 6372772d..b45342a0 100755 --- a/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -29,7 +29,7 @@ def main(client, num_requests): # Create a statement to select suggested ad units. statement = (ad_manager.StatementBuilder(version='v201905') .Where('numRequests >= :numRequests') - .WithBindVariable('numRequests', long(num_requests))) + .WithBindVariable('numRequests', int(num_requests))) # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. @@ -46,7 +46,7 @@ def main(client, num_requests): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py index a3cb3a61..8aa78dc3 100755 --- a/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/team_service/create_teams.py b/examples/ad_manager/v201905/team_service/create_teams.py index bcfaa628..b13a4a01 100755 --- a/examples/ad_manager/v201905/team_service/create_teams.py +++ b/examples/ad_manager/v201905/team_service/create_teams.py @@ -51,8 +51,8 @@ def main(client): # Display results. for team in teams: - print ('Team with ID "%s" and name "%s" was created.' - % (team['id'], team['name'])) + print('Team with ID "%s" and name "%s" was created.' + % (team['id'], team['name'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/team_service/get_all_teams.py b/examples/ad_manager/v201905/team_service/get_all_teams.py index 73d71ac7..04f664f5 100755 --- a/examples/ad_manager/v201905/team_service/get_all_teams.py +++ b/examples/ad_manager/v201905/team_service/get_all_teams.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/team_service/update_teams.py b/examples/ad_manager/v201905/team_service/update_teams.py index 26b6aa4b..6874c209 100755 --- a/examples/ad_manager/v201905/team_service/update_teams.py +++ b/examples/ad_manager/v201905/team_service/update_teams.py @@ -39,7 +39,7 @@ def main(client, team_id): # Create a filter statement to select a single team by ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :teamId') - .WithBindVariable('teamId', long(team_id))) + .WithBindVariable('teamId', int(team_id))) # Get teams by statement. response = team_service.getTeamsByStatement(statement.ToStatement()) @@ -56,10 +56,10 @@ def main(client, team_id): # Display results. for team in teams: - print ('Team with id "%s" and name "%s" was updated.' - % (team['id'], team['name'])) + print('Team with id "%s" and name "%s" was updated.' + % (team['id'], team['name'])) else: - print 'No teams found to update.' + print('No teams found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_service/create_users.py b/examples/ad_manager/v201905/user_service/create_users.py index 8264c249..fc3a8abe 100755 --- a/examples/ad_manager/v201905/user_service/create_users.py +++ b/examples/ad_manager/v201905/user_service/create_users.py @@ -48,8 +48,8 @@ def main(client, email, name): # Display results. for user in users: - print ('User with id "%s", email "%s", and role "%s" was created.' - % (user['id'], user['email'], user['roleName'])) + print('User with id "%s", email "%s", and role "%s" was created.' + % (user['id'], user['email'], user['roleName'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/user_service/deactivate_users.py b/examples/ad_manager/v201905/user_service/deactivate_users.py index 099e00a0..e0dee995 100755 --- a/examples/ad_manager/v201905/user_service/deactivate_users.py +++ b/examples/ad_manager/v201905/user_service/deactivate_users.py @@ -35,18 +35,18 @@ def main(client, user_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) users = response['results'] if 'results' in response else [] for user in users: - print ('User with id "%s", email "%s", and status "%s" will be ' - 'deactivated.' - % (user['id'], user['email'], + print('User with id "%s", email "%s", and status "%s" will be ' + 'deactivated.' + % (user['id'], user['email'], {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']])) - print 'Number of users to be deactivated: %s' % len(users) + print('Number of users to be deactivated: %s' % len(users)) # Perform action. result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'}, @@ -54,9 +54,9 @@ def main(client, user_id): # Display results. if result and int(result['numChanges']) > 0: - print 'Number of users deactivated: %s' % result['numChanges'] + print('Number of users deactivated: %s' % result['numChanges']) else: - print 'No users were deactivated.' + print('No users were deactivated.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_service/get_all_roles.py b/examples/ad_manager/v201905/user_service/get_all_roles.py index 442d35bd..38cfc420 100755 --- a/examples/ad_manager/v201905/user_service/get_all_roles.py +++ b/examples/ad_manager/v201905/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201605') + user_service = client.GetService('UserService', version='v201905') roles = user_service.getAllRoles() @@ -31,7 +31,7 @@ def main(client): print('Role with id "%s" and name "%s" was found.' % (role['id'], role['name'])) - print '\nNumber of results found: %s' % len(roles) + print('\nNumber of results found: %s' % len(roles)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_service/get_all_users.py b/examples/ad_manager/v201905/user_service/get_all_users.py index 17a5cac4..e7f6f731 100755 --- a/examples/ad_manager/v201905/user_service/get_all_users.py +++ b/examples/ad_manager/v201905/user_service/get_all_users.py @@ -40,7 +40,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_service/get_current_user.py b/examples/ad_manager/v201905/user_service/get_current_user.py index d3b17848..e9683c7a 100755 --- a/examples/ad_manager/v201905/user_service/get_current_user.py +++ b/examples/ad_manager/v201905/user_service/get_current_user.py @@ -27,10 +27,9 @@ def main(client): # Get current user. user = user_service.getCurrentUser() - print ('User with ID %d, name "%s", email "%s", and role "%s" ' - 'is the current user.' % ( - user.id, user.name, user.email, user.roleName - )) + print('User with ID %d, name "%s", email "%s", and role "%s" ' + 'is the current user.' % ( + user.id, user.name, user.email, user.roleName)) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_service/get_user_by_email_address.py b/examples/ad_manager/v201905/user_service/get_user_by_email_address.py index 4c98d485..60be4a0a 100755 --- a/examples/ad_manager/v201905/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201905/user_service/get_user_by_email_address.py @@ -43,7 +43,7 @@ def main(client, email_address): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_service/update_users.py b/examples/ad_manager/v201905/user_service/update_users.py index a4f3ae3a..4f9096af 100755 --- a/examples/ad_manager/v201905/user_service/update_users.py +++ b/examples/ad_manager/v201905/user_service/update_users.py @@ -33,7 +33,7 @@ def main(client, user_id): # Create query. statement = (ad_manager.StatementBuilder(version='v201905') .Where('id = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get users by statement. response = user_service.getUsersByStatement(statement.ToStatement()) @@ -46,10 +46,10 @@ def main(client, user_id): # Update users on server. users = user_service.updateUsers(users) for user in users: - print ('User with id "%s" and name "%s" was updated.' - % (user['id'], user['name'])) + print('User with id "%s" and name "%s" was updated.' + % (user['id'], user['name'])) else: - print 'No users found to update.' + print('No users found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py index 09d71d1b..ebb8bea4 100755 --- a/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py @@ -55,11 +55,11 @@ def main(client, team_id, user_ids): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('A user team association between user with ID "%s" and team with' - ' ID "%s"was created.' % (user_team_association['userId'], - user_team_association['teamId'])) + print('A user team association between user with ID "%s" and team with' + ' ID "%s"was created.' % (user_team_association['userId'], + user_team_association['teamId'])) else: - print 'No user team associations created.' + print('No user team associations created.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py index a7b8e7e6..51c42213 100755 --- a/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py @@ -40,7 +40,7 @@ def main(client, user_id): # Create filter text to select user team associations by the user ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -48,11 +48,11 @@ def main(client, user_id): user_team_associations = response['results'] if 'results' in response else [] for user_team_association in user_team_associations: - print ('User team association between user with ID "%s" and team with ' - 'ID "%s" will be deleted.' % (user_team_association['userId'], - user_team_association['teamId'])) - print ('Number of teams that the user will be removed from: %s' % - len(user_team_associations)) + print('User team association between user with ID "%s" and team with ' + 'ID "%s" will be deleted.' % (user_team_association['userId'], + user_team_association['teamId'])) + print('Number of teams that the user will be removed from: %s' % + len(user_team_associations)) # Action doesn't require limit/offset statement.limit = None @@ -65,10 +65,10 @@ def main(client, user_id): # Display results. if result and int(result['numChanges']) > 0: - print ('Number of teams that the user was removed from: %s' - % result['numChanges']) + print('Number of teams that the user was removed from: %s' + % result['numChanges']) else: - print 'No user team associations were deleted.' + print('No user team associations were deleted.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py index 85024b2e..cd3f6d52 100755 --- a/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py @@ -43,7 +43,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py index fa43ae3e..96919d90 100755 --- a/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py @@ -29,7 +29,7 @@ def main(client, user_id): # Create a statement to select user team associations. statement = (ad_manager.StatementBuilder(version='v201905') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. @@ -46,7 +46,7 @@ def main(client, user_id): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py index a86ee932..ea5416c7 100755 --- a/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py @@ -42,7 +42,7 @@ def main(client, user_id): # Create filter text to select user team associations by the user ID. statement = (ad_manager.StatementBuilder(version='v201905') .Where('userId = :userId') - .WithBindVariable('userId', long(user_id))) + .WithBindVariable('userId', int(user_id))) # Get user team associations by statement. response = user_team_association_service.getUserTeamAssociationsByStatement( @@ -63,13 +63,13 @@ def main(client, user_id): # Display results. if user_team_associations: for user_team_association in user_team_associations: - print ('User team association between user with ID "%s" and team with' - ' ID "%s" was updated.' % (user_team_association['userId'], - user_team_association['teamId'])) + print('User team association between user with ID "%s" and team with' + ' ID "%s" was updated.' % (user_team_association['userId'], + user_team_association['teamId'])) else: - print 'No user team associations were updated.' + print('No user team associations were updated.') else: - print 'No user team associations found to update.' + print('No user team associations found to update.') if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py index 63e6cbe6..d7a474e3 100755 --- a/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py +++ b/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py @@ -49,8 +49,8 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for workflow_approval_request in response['results']: - print ('Workflow approval request with id "%s" will be' - ' approved.' % workflow_approval_request['id']) + print('Workflow approval request with id "%s" will be' + ' approved.' % workflow_approval_request['id']) # Perform action. result = workflow_request_service.performWorkflowRequestAction( {'xsi_type': 'ApproveWorkflowApprovalRequests', @@ -64,10 +64,10 @@ def main(client, proposal_id): # Display results. if workflow_approval_requests_approved > 0: - print ('\nNumber of workflow approval requests approved: %s' % - workflow_approval_requests_approved) + print('\nNumber of workflow approval requests approved: %s' % + workflow_approval_requests_approved) else: - print '\nNo workflow approval requests were approved.' + print('\nNo workflow approval requests were approved.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py index c7e78791..e20948b7 100755 --- a/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py +++ b/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py index 4c971d94..96d99976 100755 --- a/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py @@ -48,7 +48,7 @@ def main(client): else: break - print '\nNumber of results found: %s' % response['totalResultSetSize'] + print('\nNumber of results found: %s' % response['totalResultSetSize']) if __name__ == '__main__': diff --git a/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py index 947fe23b..5a259bc7 100755 --- a/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py +++ b/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py @@ -49,11 +49,11 @@ def main(client, proposal_id): if 'results' in response and len(response['results']): # Display results. for workflow_request in response['results']: - print ('Workflow external condition request with id "%s" for %s ' - 'with id "%s" will be triggered.' % - (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) + print('Workflow external condition request with id "%s" for %s ' + 'with id "%s" will be triggered.' % + (workflow_request['id'], + workflow_request['entityType'], + workflow_request['entityId'])) # Perform action. result = workflow_request_service.performWorkflowRequestAction( {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, @@ -67,10 +67,10 @@ def main(client, proposal_id): # Display results. if workflow_external_condition_requests_triggered > 0: - print ('\nNumber of workflow external condition requests triggered: %s' % - workflow_external_condition_requests_triggered) + print('\nNumber of workflow external condition requests triggered: %s' % + workflow_external_condition_requests_triggered) else: - print '\nNo workflow external condition requests were triggered.' + print('\nNo workflow external condition requests were triggered.') if __name__ == '__main__': # Initialize client object. diff --git a/examples/adwords/adwords_appengine_demo/README.md b/examples/adwords/adwords_appengine_demo/README.md index b43b39ba..fd25c97e 100644 --- a/examples/adwords/adwords_appengine_demo/README.md +++ b/examples/adwords/adwords_appengine_demo/README.md @@ -33,7 +33,7 @@ Task Queue API to handle requests asynchronously. You can read more about this This guide assumes that you have already set up your AdWords account and have prepared your OAuth2 Credentials via the Google Developers Console. -1. Install Python v2.7.9 or higher, which you can get +1. Install Python v3.6 or higher, which you can get [here](https://www.python.org/downloads). 1. Install [pip](http://pip.readthedocs.org/en/latest/installing.html), @@ -90,13 +90,12 @@ Submit bug reports or feature requests to our ## External Dependencies: -* [Python v2.7.9+](https://www.python.org/downloads/) +* [Python v3.6+](https://www.python.org/downloads/) * [httplib2 v0.9+](https://pypi.python.org/pypi/httplib2) * [oauth2client v4.0.0+](https://pypi.python.org/pypi/oauth2client/) * [pysocks v1.5.0+](https://pypi.python.org/pypi/PySocks/) * [pytz 2014.7+](https://pypi.python.org/pypi/pytz) * [PyYAML 3.11+](https://pypi.python.org/pypi/PyYAML) -* [suds-jurko 0.6+](https://pypi.python.org/pypi/suds-jurko) * [xmltodict 0.9.2+](https://pypi.python.org/pypi/xmltodict) * [App Engine SDK v1.9.11+](https://developers.google.com/appengine/downloads) * [Google Ads Python Client Library v10.1.0+](https://github.com/googleads/googleads-python-lib) diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index 29e86706..167b4b29 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -246,7 +246,7 @@ def GetCampaigns(self, client_customer_id): return campaigns['entries'] else: return None - except Exception, e: + except Exception as e: if i == max_tries: raise GoogleAdsError(e) continue diff --git a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py index 48bb14c5..7660cb0e 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_adgroup_view.py @@ -58,7 +58,7 @@ def post(self): self.redirect('/showAdGroups?clientCustomerId=%s&campaignId=%s' % (client_customer_id, campaign_id)) - except Exception, e: + except Exception as e: template_values['error'] = str(e) # Use template to write output to the page. path = os.path.join(os.path.dirname(__file__), diff --git a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py index 25297d20..72e442ed 100755 --- a/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py +++ b/examples/adwords/adwords_appengine_demo/views/add_campaign_view.py @@ -57,7 +57,7 @@ def post(self): ad_channel_type, budget) self.redirect('/showCampaigns?clientCustomerId=%s' % client_customer_id) - except Exception, e: + except Exception as e: template_values['error'] = str(e) # Use template to write output to the page. path = os.path.join(os.path.dirname(__file__), diff --git a/examples/adwords/adwords_appengine_demo/views/init_view.py b/examples/adwords/adwords_appengine_demo/views/init_view.py index e6215956..9f4038c1 100755 --- a/examples/adwords/adwords_appengine_demo/views/init_view.py +++ b/examples/adwords/adwords_appengine_demo/views/init_view.py @@ -37,5 +37,5 @@ def get(self): self.redirect('/showAccounts') else: self.redirect('/showCredentials') - except Exception, e: + except Exception as e: logging.debug(str(e)) diff --git a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py index e3bdbf1d..debc0a0d 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_accounts_view.py @@ -51,7 +51,7 @@ def get(self): # Fetch account info for each client account and place in template. template_values['accounts'] = handler.GetAccounts() - except Exception, e: + except Exception as e: template_values['error'] = str(e) finally: # Use template to write output to the page. diff --git a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py index 9722cad9..fa9397b8 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_adgroups_view.py @@ -56,7 +56,7 @@ def get(self): adgroups = handler.GetAdGroups(client_customer_id, campaign_id) # Use template to write output to the page. template_values['adgroups'] = adgroups - except Exception, e: + except Exception as e: template_values['error'] = str(e) finally: path = os.path.join(os.path.dirname(__file__), diff --git a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py index 758f832d..543fdbc9 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_budget_view.py @@ -58,7 +58,7 @@ def get(self): budget = handler.GetBudget(client_customer_id, budget_id) # Use template to write output to the page. template_values['budget'] = budget - except Exception, e: + except Exception as e: template_values['error'] = str(e) finally: path = os.path.join(os.path.dirname(__file__), diff --git a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py index 9c74eeaa..1101c2f1 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_campaigns_view.py @@ -54,7 +54,7 @@ def get(self): app_user.developer_token) campaigns = handler.GetCampaigns(client_customer_id) - except Exception, e: + except Exception as e: template_values['error'] = str(e) finally: # Use template to write output to the page. diff --git a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py index bcc709c3..e2fbf543 100755 --- a/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/show_credentials_view.py @@ -52,7 +52,7 @@ def get(self): ) template_values['dev_token'] = (app_user.developer_token if app_user.developer_token else '') - except Exception, e: + except Exception as e: template_values['error'] = str(e) finally: # Use template to write output to the page. diff --git a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py index bbfe5d96..51c8db7c 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_budget_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_budget_view.py @@ -59,7 +59,7 @@ def post(self): self.redirect('/showBudget?clientCustomerId=%s&budgetId=%s' % (client_customer_id, budget_id)) - except Exception, e: + except Exception as e: # Use template to write output to the page. template_values['error'] = str(e) path = os.path.join(os.path.dirname(__file__), diff --git a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py index 844b7cd4..4b2a4af5 100755 --- a/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py +++ b/examples/adwords/adwords_appengine_demo/views/update_credentials_view.py @@ -44,7 +44,7 @@ def post(self): self.request.get('adwords_manager_cid'), self.request.get('dev_token')) self.redirect('/showCredentials') - except Exception, e: + except Exception as e: template_values['error'] = str(e) # Use template to write output to the page. path = os.path.join(os.path.dirname(__file__), diff --git a/examples/adwords/authentication/create_adwords_client_with_access_token.py b/examples/adwords/authentication/create_adwords_client_with_access_token.py index 95eea9e8..53b61d66 100755 --- a/examples/adwords/authentication/create_adwords_client_with_access_token.py +++ b/examples/adwords/authentication/create_adwords_client_with_access_token.py @@ -66,7 +66,7 @@ def main(access_token, token_expiry, client_customer_id, developer_token, client_customer_id=client_customer_id) customer = adwords_client.GetService('CustomerService').getCustomers()[0] - print 'You are logged in as customer: %s' % customer['customerId'] + print('You are logged in as customer: %s' % customer['customerId']) if __name__ == '__main__': diff --git a/examples/adwords/authentication/create_adwords_client_with_refresh_token.py b/examples/adwords/authentication/create_adwords_client_with_refresh_token.py index b79c69ab..17bdeead 100755 --- a/examples/adwords/authentication/create_adwords_client_with_refresh_token.py +++ b/examples/adwords/authentication/create_adwords_client_with_refresh_token.py @@ -51,10 +51,10 @@ def main(client_id, client_secret, refresh_token, developer_token, user_agent, version='v201702') customers = customer_service.getCustomers() - print 'You are logged in as a user with access to the following customers:' + print('You are logged in as a user with access to the following customers:') for customer in customers: - print '\t%s' % customer['customerId'] + print('\t%s' % customer['customerId']) if __name__ == '__main__': diff --git a/examples/adwords/authentication/create_adwords_client_with_service_account.py b/examples/adwords/authentication/create_adwords_client_with_service_account.py index 2a171b43..ef481b1f 100755 --- a/examples/adwords/authentication/create_adwords_client_with_service_account.py +++ b/examples/adwords/authentication/create_adwords_client_with_service_account.py @@ -44,10 +44,10 @@ def main(key_file, service_account_user, developer_token, user_agent, version='v201702') customers = customer_service.getCustomers() - print 'You are logged in as a user with access to the following customers:' + print('You are logged in as a user with access to the following customers:') for customer in customers: - print '\t%s' % customer['customerId'] + print('\t%s' % customer['customerId']) if __name__ == '__main__': diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index ed879c45..1aca6d43 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -95,19 +95,19 @@ def main(client_id, client_secret, scopes): auth_url, _ = flow.authorization_url(prompt='consent') - print ('Log into the Google Account you use to access your AdWords account ' - 'and go to the following URL: \n%s\n' % auth_url) - print 'After approving the token enter the verification code (if specified).' + print('Log into the Google Account you use to access your AdWords account ' + 'and go to the following URL: \n%s\n' % auth_url) + print('After approving the token enter the verification code (if specified).') code = raw_input('Code: ').strip() try: flow.fetch_token(code=code) except InvalidGrantError as ex: - print 'Authentication has failed: %s' % ex + print('Authentication has failed: %s' % ex) sys.exit(1) - print 'Access token: %s' % flow.credentials.token - print 'Refresh token: %s' % flow.credentials.refresh_token + print('Access token: %s' % flow.credentials.token) + print('Refresh token: %s' % flow.credentials.refresh_token) if __name__ == '__main__': diff --git a/examples/adwords/v201809/account_management/accept_service_link.py b/examples/adwords/v201809/account_management/accept_service_link.py index 7087fc40..354f87e0 100755 --- a/examples/adwords/v201809/account_management/accept_service_link.py +++ b/examples/adwords/v201809/account_management/accept_service_link.py @@ -50,10 +50,10 @@ def main(client, service_link_id): # Display results. for mutated_service_link in mutated_service_links: - print ('Service link with service link ID "%s", type "%s" was updated ' - 'to status: "%s".' % (mutated_service_link['serviceLinkId'], - mutated_service_link['serviceType'], - mutated_service_link['linkStatus'])) + print('Service link with service link ID "%s", type "%s" was updated ' + 'to status: "%s".' % (mutated_service_link['serviceLinkId'], + mutated_service_link['serviceType'], + mutated_service_link['linkStatus'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/account_management/create_account.py b/examples/adwords/v201809/account_management/create_account.py index 7655a1b2..8932714e 100755 --- a/examples/adwords/v201809/account_management/create_account.py +++ b/examples/adwords/v201809/account_management/create_account.py @@ -53,8 +53,8 @@ def main(client): # Display results. for account in accounts['value']: - print ('Account with customer ID "%s" was successfully created.' - % account['customerId']) + print('Account with customer ID "%s" was successfully created.' + % account['customerId']) if __name__ == '__main__': diff --git a/examples/adwords/v201809/account_management/get_account_changes.py b/examples/adwords/v201809/account_management/get_account_changes.py index 84300fa6..65430f46 100755 --- a/examples/adwords/v201809/account_management/get_account_changes.py +++ b/examples/adwords/v201809/account_management/get_account_changes.py @@ -44,7 +44,7 @@ def main(client): for campaign in campaigns['entries']: campaign_ids.append(campaign['id']) else: - print 'No campaigns were found.' + print('No campaigns were found.') return # Construct selector and get all changes. @@ -62,35 +62,35 @@ def main(client): # Display results. if account_changes: if 'lastChangeTimestamp' in account_changes: - print 'Most recent changes: %s' % account_changes['lastChangeTimestamp'] + print('Most recent changes: %s' % account_changes['lastChangeTimestamp']) if account_changes['changedCampaigns']: for data in account_changes['changedCampaigns']: - print ('Campaign with id "%s" has change status "%s".' - % (data['campaignId'], data['campaignChangeStatus'])) + print('Campaign with id "%s" has change status "%s".' + % (data['campaignId'], data['campaignChangeStatus'])) if (data['campaignChangeStatus'] != 'NEW' and data['campaignChangeStatus'] != 'FIELDS_UNCHANGED'): if 'addedCampaignCriteria' in data: - print (' Added campaign criteria: %s' % - data['addedCampaignCriteria']) + print(' Added campaign criteria: %s' % + data['addedCampaignCriteria']) if 'removedCampaignCriteria' in data: - print (' Removed campaign criteria: %s' % - data['removedCampaignCriteria']) + print(' Removed campaign criteria: %s' % + data['removedCampaignCriteria']) if 'changedAdGroups' in data: for ad_group_data in data['changedAdGroups']: - print (' Ad group with id "%s" has change status "%s".' - % (ad_group_data['adGroupId'], + print(' Ad group with id "%s" has change status "%s".' + % (ad_group_data['adGroupId'], ad_group_data['adGroupChangeStatus'])) if ad_group_data['adGroupChangeStatus'] != 'NEW': if 'changedAds' in ad_group_data: - print ' Changed ads: %s' % ad_group_data['changedAds'] + print(' Changed ads: %s' % ad_group_data['changedAds']) if 'changedCriteria' in ad_group_data: - print (' Changed criteria: %s' % - ad_group_data['changedCriteria']) + print(' Changed criteria: %s' % + ad_group_data['changedCriteria']) if 'removedCriteria' in ad_group_data: - print (' Removed criteria: %s' % - ad_group_data['removedCriteria']) + print(' Removed criteria: %s' % + ad_group_data['removedCriteria']) else: - print 'No changes were found.' + print('No changes were found.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/account_management/get_account_hierarchy.py b/examples/adwords/v201809/account_management/get_account_hierarchy.py index 121872e2..d6a7cb84 100755 --- a/examples/adwords/v201809/account_management/get_account_hierarchy.py +++ b/examples/adwords/v201809/account_management/get_account_hierarchy.py @@ -38,7 +38,7 @@ def DisplayAccountTree(account, accounts, links, depth=0): depth: int Depth of the current account in the tree. """ prefix = '-' * depth * 2 - print '%s%s, %s' % (prefix, account['customerId'], account['name']) + print('%s%s, %s' % (prefix, account['customerId'], account['name'])) if account['customerId'] in links: for child_link in links[account['customerId']]: child_account = accounts[child_link['clientCustomerId']] @@ -92,10 +92,10 @@ def main(client): # Display account tree. if root_account: - print 'CustomerId, Name' + print('CustomerId, Name') DisplayAccountTree(root_account, accounts, child_links, 0) else: - print 'Unable to determine a root account' + print('Unable to determine a root account') if __name__ == '__main__': diff --git a/examples/adwords/v201809/advanced_operations/add_ad_customizer.py b/examples/adwords/v201809/advanced_operations/add_ad_customizer.py index 4b7c8de6..9fa43c1d 100755 --- a/examples/adwords/v201809/advanced_operations/add_ad_customizer.py +++ b/examples/adwords/v201809/advanced_operations/add_ad_customizer.py @@ -73,8 +73,8 @@ def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): if response and 'value' in response: for ad in response['value']: - print ('Created an ad with ID "%s", type "%s", and status "%s".' - % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) + print('Created an ad with ID "%s", type "%s", and status "%s".' + % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status'])) else: raise errors.GoogleAdsError('No ads were added.') @@ -116,10 +116,10 @@ def CreateCustomizerFeed(client, feed_name): 'priceId': feed['feedAttributes'][1]['id'], 'dateId': feed['feedAttributes'][2]['id'] } - print ('Feed with name "%s" and ID %s was added with:\n' - '\tName attribute ID %s and price attribute ID %s and date attribute' - 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], - feed_data['priceId'], feed_data['dateId']) + print('Feed with name "%s" and ID %s was added with:\n' + '\tName attribute ID %s and price attribute ID %s and date attribute' + 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], + feed_data['priceId'], feed_data['dateId']) return feed else: raise errors.GoogleAdsError('No feeds were added') @@ -192,7 +192,7 @@ def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): if 'value' in response: for feed_item in response['value']: - print 'Added FeedItem with ID %d.' % feed_item['feedItemId'] + print('Added FeedItem with ID %d.' % feed_item['feedItemId']) else: raise errors.GoogleAdsError('No FeedItems were added.') diff --git a/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py b/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py index 4a6a9d8f..5ff880cf 100755 --- a/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py +++ b/examples/adwords/v201809/advanced_operations/add_ad_group_bid_modifier.py @@ -60,12 +60,12 @@ def main(client, ad_group_id, bid_modifier): if response and response['value']: modifier = response['value'][0] value = modifier['bidModifier'] if 'bidModifier' in modifier else 'unset' - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' - 'ad group level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) + print('Campaign ID %s, AdGroup ID %s, Criterion ID %s was updated with ' + 'ad group level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) else: - print 'No modifiers were added.' + print('No modifiers were added.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py b/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py index ac988fbf..34b461d2 100755 --- a/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py +++ b/examples/adwords/v201809/advanced_operations/add_dynamic_page_feed.py @@ -59,7 +59,7 @@ def main(client, campaign_id, ad_group_id): # Optional: Target web pages matching the feed's label in the ad group. _AddDSATargeting(client, ad_group_id, DSA_PAGE_URL_LABEL) - print 'Dynamic page feed setup complete for campaign ID "%d".' % campaign_id + print('Dynamic page feed setup complete for campaign ID "%d".' % campaign_id) def _CreateFeed(client): @@ -234,8 +234,8 @@ def _UpdateCampaignDSASetting(client, campaign_id, feed_id): } campaign_service.mutate([operation]) - print 'DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( - campaign_id, feed_id) + print('DSA page feed for campaign ID "%d" was updated with feed ID "%d".' % ( + campaign_id, feed_id)) def _AddDSATargeting(client, ad_group_id, label_name): @@ -247,7 +247,8 @@ def _AddDSATargeting(client, ad_group_id, label_name): label_name: a str label name. Returns: - A suds.sudsobject.Object representing the newly created webpage criterion. + A zeep.objects.BiddableAdGroupCriterion representing the newly created + webpage criterion. """ # Get the AdGroupCriterionService. ad_group_criterion_service = client.GetService('AdGroupCriterionService', @@ -284,8 +285,8 @@ def _AddDSATargeting(client, ad_group_id, label_name): } criterion = ad_group_criterion_service.mutate([operation])['value'][0] - print 'Web page criterion with ID "%d" and status "%s" was created.' % ( - criterion['criterion']['id'], criterion['userStatus']) + print('Web page criterion with ID "%d" and status "%s" was created.' % ( + criterion['criterion']['id'], criterion['userStatus'])) return criterion diff --git a/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py b/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py index 7a2246f2..2f154e36 100755 --- a/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py +++ b/examples/adwords/v201809/advanced_operations/add_dynamic_search_ads_campaign.py @@ -37,7 +37,7 @@ def main(client): _CreateExpandedDSA(client, ad_group_id) _AddWebPageCriteria(client, ad_group_id) - print 'Dynamic Search Ads campaign setup is complete.' + print('Dynamic Search Ads campaign setup is complete.') def _CreateBudget(client): @@ -47,7 +47,7 @@ def _CreateBudget(client): client: an AdWordsClient instance. Returns: - a suds.sudsobject.Object representation of the created budget. + a zeep.objects.Budget representation of the created budget. """ budget_service = client.GetService('BudgetService', version='v201809') @@ -65,8 +65,8 @@ def _CreateBudget(client): budget = budget_service.mutate([operation])['value'][0] - print 'Budget with ID "%d" and name "%s" was created.' % ( - budget['budgetId'], budget['name']) + print('Budget with ID "%d" and name "%s" was created.' % ( + budget['budgetId'], budget['name'])) return budget @@ -76,7 +76,7 @@ def _CreateCampaign(client, budget): Args: client: an AdWordsClient instance. - budget: a suds.sudsobject.Object representation of a created budget. + budget: a zeep.objects.Budget representation of a created budget. Returns: An integer campaign ID. @@ -115,8 +115,8 @@ def _CreateCampaign(client, budget): campaign = campaign_service.mutate(operations)['value'][0] campaign_id = campaign['id'] - print 'Campaign with ID "%d" and name "%s" was added.' % ( - campaign_id, campaign['name']) + print('Campaign with ID "%d" and name "%s" was added.' % ( + campaign_id, campaign['name'])) return campaign_id @@ -154,8 +154,8 @@ def _CreateAdGroup(client, campaign_id): ad_group = ad_group_service.mutate(operations)['value'][0] ad_group_id = ad_group['id'] - print 'Ad group with ID "%d" and name "%s" was created.' % ( - ad_group_id, ad_group['name']) + print('Ad group with ID "%d" and name "%s" was created.' % ( + ad_group_id, ad_group['name'])) return ad_group_id @@ -195,9 +195,9 @@ def _CreateExpandedDSA(client, ad_group_id): ad = ad_group_ad_service.mutate(operations)['value'][0]['ad'] # Display the results. - print ('Expanded dynamic search ad with ID "%d", description "%s", and ' - 'description 2 "%s" was added' - % (ad['id'], ad['description'], ad['description2'])) + print('Expanded dynamic search ad with ID "%d", description "%s", and ' + 'description 2 "%s" was added' + % (ad['id'], ad['description'], ad['description2'])) def _AddWebPageCriteria(client, ad_group_id): @@ -248,8 +248,8 @@ def _AddWebPageCriteria(client, ad_group_id): criterion = ad_group_criterion_service.mutate(operations)['value'][0] - print 'Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( - criterion['criterion']['id'], criterion['adGroupId']) + print('Webpage criterion with ID "%d" was added to ad group ID "%d".' % ( + criterion['criterion']['id'], criterion['adGroupId'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py b/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py index 968f7bcf..b2ae7c4e 100755 --- a/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py +++ b/examples/adwords/v201809/advanced_operations/add_expanded_text_ad_with_upgraded_urls.py @@ -95,13 +95,13 @@ def main(client, adgroup_id): if 'value' in response: for adgroup_ad in response['value']: - print 'AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id'] - print 'Upgraded URL properties:' - print 'Final Urls: %s' % adgroup_ad['ad']['finalUrls'] - print 'Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls'] - print ('Tracking URL template: %s' - % adgroup_ad['ad']['trackingUrlTemplate']) - print 'Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters'] + print('AdGroupAd with ID "%s" was added.' % adgroup_ad['ad']['id']) + print('Upgraded URL properties:') + print('Final Urls: %s' % adgroup_ad['ad']['finalUrls']) + print('Final Mobile URLs: %s' % adgroup_ad['ad']['finalMobileUrls']) + print('Tracking URL template: %s' + % adgroup_ad['ad']['trackingUrlTemplate']) + print('Custom parameters: %s' % adgroup_ad['ad']['urlCustomParameters']) else: raise errors.GoogleAdsError('Failed to create AdGroupAd.') diff --git a/examples/adwords/v201809/advanced_operations/add_gmail_ad.py b/examples/adwords/v201809/advanced_operations/add_gmail_ad.py index a5c386f0..683136f3 100755 --- a/examples/adwords/v201809/advanced_operations/add_gmail_ad.py +++ b/examples/adwords/v201809/advanced_operations/add_gmail_ad.py @@ -80,9 +80,9 @@ def main(client, ad_group_id): # Display results. for ad_group_ad in ad_group_ads['value']: - print ('A Gmail ad with id "%d" and short headline "%s" was ' - 'added.' % (ad_group_ad['ad']['id'], - ad_group_ad['ad']['teaser']['headline'])) + print('A Gmail ad with id "%d" and short headline "%s" was ' + 'added.' % (ad_group_ad['ad']['id'], + ad_group_ad['ad']['teaser']['headline'])) except Exception as e: raise Exception('Failed to create Gmail ad: %s' % e) @@ -91,7 +91,7 @@ def _CreateImage(media_service, opener, url): """Creates an image and uploads it to the server. Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. + media_service: a ZeepServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. url: a str URL used to load image data. diff --git a/examples/adwords/v201809/advanced_operations/add_html5_ad.py b/examples/adwords/v201809/advanced_operations/add_html5_ad.py index 2c54d843..2fde31f9 100755 --- a/examples/adwords/v201809/advanced_operations/add_html5_ad.py +++ b/examples/adwords/v201809/advanced_operations/add_html5_ad.py @@ -26,7 +26,8 @@ """ -import urllib2 +from urllib.request import urlopen + from googleads import adwords @@ -92,13 +93,13 @@ def main(client, ad_group_id): # Display results. for ad in ads['value']: - print ('New HTML5 Ad with id "%s" and of display url "%s" was added.' - % (ad['ad']['id'], ad['ad']['displayUrl'])) + print('New HTML5 Ad with id "%s" and of display url "%s" was added.' + % (ad['ad']['id'], ad['ad']['displayUrl'])) def GetHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) + response = urlopen(url) # Note: The utf-8 decode is for 2to3 Python 3 compatibility. return response.read().decode('utf-8') diff --git a/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py b/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py index 777da5a1..71213023 100755 --- a/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py +++ b/examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py @@ -164,11 +164,11 @@ def main(client, ad_group_id): # Display results. if 'value' in ads: for ad in ads['value']: - print ('Added new responsive display ad ad with ID "%d" ' - 'and long headline "%s".' - % (ad['ad']['id'], ad['ad']['longHeadline']['asset']['assetText'])) + print('Added new responsive display ad ad with ID "%d" ' + 'and long headline "%s".' + % (ad['ad']['id'], ad['ad']['longHeadline']['asset']['assetText'])) else: - print 'No ads were added.' + print('No ads were added.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py b/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py index bbb77aa9..e4e0002a 100755 --- a/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py +++ b/examples/adwords/v201809/advanced_operations/add_responsive_display_ad.py @@ -25,7 +25,7 @@ """ -import urllib2 +from urllib.request import build_opener from googleads import adwords @@ -37,7 +37,7 @@ def main(client, ad_group_id): # Initialize appropriate services. ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') media_service = client.GetService('MediaService', version='v201809') - opener = urllib2.build_opener(*client.proxy_config.GetHandlers()) + opener = build_opener(*client.proxy_config.GetHandlers()) try: # Create marketing image. @@ -94,8 +94,8 @@ def main(client, ad_group_id): # Display results. for ad in ads['value']: - print ('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' - 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) + print('ResponsiveDisplayAd with id "%d" and short headline "%s" was ' + 'added.' % (ad['ad']['id'], ad['ad']['shortHeadline'])) except: raise Exception('Failed to create responsive display ad.') @@ -105,7 +105,7 @@ def _CreateImage(media_service, opener, url): """Creates an image and uploads it to the server. Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. + media_service: a ZeepServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. url: a str URL used to load image data. @@ -127,7 +127,7 @@ def _CreateDynamicDisplayAdSettings(media_service, opener): """Creates settings for dynamic display ad. Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. + media_service: a ZeepServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. Returns: diff --git a/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py b/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py index 6b983688..62f724c1 100755 --- a/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py +++ b/examples/adwords/v201809/advanced_operations/add_shopping_dynamic_remarketing_campaign.py @@ -44,21 +44,21 @@ def main(client, merchant_id, budget_id, user_list_id): campaign = CreateCampaign(client, merchant_id, budget_id) campaign_id = campaign['id'] - print 'Campaign with name "%s" and ID "%d" was added.' % ( - campaign['name'], campaign_id) + print('Campaign with name "%s" and ID "%d" was added.' % ( + campaign['name'], campaign_id)) ad_group = CreateAdGroup(client, campaign_id) ad_group_id = ad_group['id'] - print 'Ad group with name "%s" and ID "%d" was added.' % ( - ad_group['name'], ad_group_id) + print('Ad group with name "%s" and ID "%d" was added.' % ( + ad_group['name'], ad_group_id)) ad_group_ad = CreateAd(client, opener, ad_group_id) - print 'Responsive display ad with ID "%d" was added.' % ( - ad_group_ad['ad']['id']) + print('Responsive display ad with ID "%d" was added.' % ( + ad_group_ad['ad']['id'])) AttachUserList(client, ad_group_id, user_list_id) - print 'User list with ID "%d" was attached to ad group with ID "%d".' % ( - user_list_id, ad_group_id) + print('User list with ID "%d" was attached to ad group with ID "%d".' % ( + user_list_id, ad_group_id)) def CreateCampaign(client, merchant_id, budget_id): @@ -276,7 +276,7 @@ def _CreateImage(media_service, opener, url): """Creates an image and uploads it to the server. Args: - media_service: a SudsServiceProxy instance for AdWords's MediaService. + media_service: a ZeepServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. url: a str URL used to load image data. diff --git a/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py b/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py index 28e4f609..6ae29105 100755 --- a/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py +++ b/examples/adwords/v201809/advanced_operations/add_universal_app_campaign.py @@ -121,13 +121,13 @@ def main(client): # Display results. if campaigns: for campaign in campaigns: - print ('Universal App Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) + print('Universal App Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) # Optional: Set the campaign's location and language targeting. No other # targeting criteria can be used for Universal App campaigns. SetCampaignTargetingCriteria(client, campaign) else: - print 'No Universal App campaigns were added.' + print('No Universal App campaigns were added.') def CreateBudget(client): @@ -167,7 +167,7 @@ def SetCampaignTargetingCriteria(client, campaign): Args: client: An AdWordsClient instance. - campaign: A suds object representing the campaign we wish to attach + campaign: A zeep.objects.Campaign representing the campaign we wish to attach targeting criteria. """ campaign_criterion_service = client.GetService('CampaignCriterionService') @@ -206,8 +206,8 @@ def SetCampaignTargetingCriteria(client, campaign): if response and 'value' in response: # Display the added campaign targets. for criterion in response['value']: - print ('Campaign criteria of type "%s" and id "%s" was added.' - % (criterion['criterion']['type'], + print('Campaign criteria of type "%s" and id "%s" was added.' + % (criterion['criterion']['type'], criterion['criterion']['id'])) diff --git a/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py b/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py index d5e20932..4d3a3800 100755 --- a/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py +++ b/examples/adwords/v201809/advanced_operations/create_and_attach_shared_keyword_set.py @@ -60,9 +60,9 @@ def main(client, campaign_id): shared_set = response['value'][0] shared_set_id = shared_set['sharedSetId'] - print 'Shared set with ID %d and name "%s" was successfully added.' % ( + print('Shared set with ID %d and name "%s" was successfully added.' % ( shared_set_id, shared_set['name'] - ) + )) else: raise errors.GoogleAdsError('No shared set was added.') @@ -90,11 +90,11 @@ def main(client, campaign_id): if 'value' in response: for shared_criteria in response['value']: - print 'Added shared criterion ID %d "%s" to shared set with ID %d.' % ( + print('Added shared criterion ID %d "%s" to shared set with ID %d.' % ( shared_criteria['criterion']['id'], shared_criteria['criterion']['text'], shared_criteria['sharedSetId'] - ) + )) else: raise errors.GoogleAdsError('No shared keyword was added.') @@ -114,9 +114,9 @@ def main(client, campaign_id): response = campaign_shared_set_service.mutate(operations) if 'value' in response: - print 'Shared set ID %d was attached to campaign ID %d' % ( + print('Shared set ID %d was attached to campaign ID %d' % ( response['value'][0]['sharedSetId'], response['value'][0]['campaignId'] - ) + )) else: raise errors.GoogleAdsError('No campaign shared set was added.') diff --git a/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py b/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py index 4dfa6728..916a04ee 100755 --- a/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py +++ b/examples/adwords/v201809/advanced_operations/find_and_remove_criteria_from_shared_set.py @@ -74,9 +74,9 @@ def main(client, campaign_id): page = campaign_shared_set_service.get(selector) if 'entries' in page: for shared_set in page['entries']: - print 'Campaign shared set ID %d and name "%s"' % ( + print('Campaign shared set ID %d and name "%s"' % ( shared_set['sharedSetId'], shared_set['sharedSetName'] - ) + )) shared_set_ids.append(shared_set['sharedSetId']) # Increment values to request the next page. offset += PAGE_SIZE @@ -108,17 +108,17 @@ def main(client, campaign_id): if 'entries' in page: for shared_criterion in page['entries']: if shared_criterion['criterion']['type'] == 'KEYWORD': - print ('Shared negative keyword with ID %d and text "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['text'])) + print('Shared negative keyword with ID %d and text "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['text'])) elif shared_criterion['criterion']['type'] == 'PLACEMENT': - print ('Shared negative placement with ID %d and url "%s" was' - 'found.' % (shared_criterion['criterion']['id'], - shared_criterion['criterion']['url'])) + print('Shared negative placement with ID %d and url "%s" was' + 'found.' % (shared_criterion['criterion']['id'], + shared_criterion['criterion']['url'])) else: - print 'Shared criterion with ID %d was found.' % ( + print('Shared criterion with ID %d was found.' % ( shared_criterion['criterion']['id'], - ) + )) criterion_ids.append({ 'sharedSetId': shared_criterion['sharedSetId'], 'criterionId': shared_criterion['criterion']['id'] @@ -142,10 +142,10 @@ def main(client, campaign_id): response = shared_criterion_service.mutate(operations) if 'value' in response: for criterion in response['value']: - print ('Criterion ID %d was successfully removed from shared set ID' - '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) + print('Criterion ID %d was successfully removed from shared set ID' + '%d.' % (criterion['criterion']['id'], criterion['sharedSetId'])) else: - print 'No shared criteria were removed.' + print('No shared criteria were removed.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py b/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py index fe830c0a..c5880795 100755 --- a/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py +++ b/examples/adwords/v201809/advanced_operations/get_ad_group_bid_modifier.py @@ -53,16 +53,16 @@ def main(client): for modifier in page['entries']: value = (modifier['bidModifier'] if 'bidModifier' in modifier else 'unset') - print ('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' - 'level modifier: %s' % - (modifier['campaignId'], modifier['adGroupId'], - modifier['criterion']['id'], value)) + print('Campaign ID %s, AdGroup ID %s, Criterion ID %s has ad group ' + 'level modifier: %s' % + (modifier['campaignId'], modifier['adGroupId'], + modifier['criterion']['id'], value)) # Increment values to request the next page. offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) else: - print 'No ad group bid modifiers returned.' + print('No ad group bid modifiers returned.') more_results = int(page['totalNumEntries']) > offset diff --git a/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py b/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py index c5fb8010..3ede5fae 100755 --- a/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py +++ b/examples/adwords/v201809/advanced_operations/use_shared_bidding_strategy.py @@ -77,10 +77,10 @@ def CreateBiddingStrategy(client): response = bidding_strategy_service.mutate([operation]) new_bidding_strategy = response['value'][0] - print ('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' - 'was created.' % - (new_bidding_strategy['name'], new_bidding_strategy['id'], - new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) + print('Shared bidding strategy with name "%s" and ID "%s" of type "%s"' + 'was created.' % + (new_bidding_strategy['name'], new_bidding_strategy['id'], + new_bidding_strategy['biddingScheme']['BiddingScheme.Type'])) return new_bidding_strategy @@ -157,10 +157,10 @@ def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id): response = campaign_service.mutate([operation]) new_campaign = response['value'][0] - print ('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' - 'was created.' % - (new_campaign['name'], new_campaign['id'], - new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) + print('Campaign with name "%s", ID "%s" and bidding scheme ID "%s" ' + 'was created.' % + (new_campaign['name'], new_campaign['id'], + new_campaign['biddingStrategyConfiguration']['biddingStrategyId'])) return new_campaign diff --git a/examples/adwords/v201809/basic_operations/add_ad_groups.py b/examples/adwords/v201809/basic_operations/add_ad_groups.py index 8451644e..52ef7c65 100755 --- a/examples/adwords/v201809/basic_operations/add_ad_groups.py +++ b/examples/adwords/v201809/basic_operations/add_ad_groups.py @@ -104,8 +104,8 @@ def main(client, campaign_id): # Display results. for ad_group in ad_groups['value']: - print ('Ad group with name "%s" and id "%s" was added.' - % (ad_group['name'], ad_group['id'])) + print('Ad group with name "%s" and id "%s" was added.' + % (ad_group['name'], ad_group['id'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/add_campaigns.py b/examples/adwords/v201809/basic_operations/add_campaigns.py index 1420734c..f0e91d67 100755 --- a/examples/adwords/v201809/basic_operations/add_campaigns.py +++ b/examples/adwords/v201809/basic_operations/add_campaigns.py @@ -116,8 +116,8 @@ def main(client): # Display results. for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was added.' - % (campaign['name'], campaign['id'])) + print('Campaign with name "%s" and id "%s" was added.' + % (campaign['name'], campaign['id'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py b/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py index 7d0cb187..60c99731 100755 --- a/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py +++ b/examples/adwords/v201809/basic_operations/add_expanded_text_ads.py @@ -63,9 +63,9 @@ def main(client, ad_group_id): # Display results. for ad in ads['value']: - print ('Ad of type "%s" with id "%d" was added.' - '\n\theadlinePart1: %s\n\theadlinePart2: %s\n\theadlinePart3: %s' - % (ad['ad']['Ad.Type'], ad['ad']['id'], + print('Ad of type "%s" with id "%d" was added.' + '\n\theadlinePart1: %s\n\theadlinePart2: %s\n\theadlinePart3: %s' + % (ad['ad']['Ad.Type'], ad['ad']['id'], ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], ad['ad']['headlinePart3'])) diff --git a/examples/adwords/v201809/basic_operations/add_keywords.py b/examples/adwords/v201809/basic_operations/add_keywords.py index 47fb127f..dc6fbd3f 100755 --- a/examples/adwords/v201809/basic_operations/add_keywords.py +++ b/examples/adwords/v201809/basic_operations/add_keywords.py @@ -78,9 +78,9 @@ def main(client, ad_group_id): # Display results. for criterion in ad_group_criteria: - print ('Keyword ad group criterion with ad group id "%s", criterion id ' - '"%s", text "%s", and match type "%s" was added.' - % (criterion['adGroupId'], criterion['criterion']['id'], + print('Keyword ad group criterion with ad group id "%s", criterion id ' + '"%s", text "%s", and match type "%s" was added.' + % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['text'], criterion['criterion']['matchType'])) diff --git a/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py b/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py index 0e7dd0f2..038ce20a 100755 --- a/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py +++ b/examples/adwords/v201809/basic_operations/add_responsive_search_ad.py @@ -91,10 +91,10 @@ def main(client, ad_group_id): # Display results. for ad in ads['value']: ad = ad['ad'] - print ('Ad of type "%s" with id "%d" was added.\n' - 'Headlines:\n%s\n' - 'Descriptions:\n%s' - % (ad['Ad.Type'], ad['id'], + print('Ad of type "%s" with id "%d" was added.\n' + 'Headlines:\n%s\n' + 'Descriptions:\n%s' + % (ad['Ad.Type'], ad['id'], '\n'.join(['\t%s (pinned to %s)' % (headline['asset']['assetText'], headline['pinnedField']) diff --git a/examples/adwords/v201809/basic_operations/get_ad_groups.py b/examples/adwords/v201809/basic_operations/get_ad_groups.py index 29db6bef..3c23b6aa 100755 --- a/examples/adwords/v201809/basic_operations/get_ad_groups.py +++ b/examples/adwords/v201809/basic_operations/get_ad_groups.py @@ -59,11 +59,11 @@ def main(client, campaign_id): # Display results. if 'entries' in page: for ad_group in page['entries']: - print ('Ad group with name "%s", id "%s" and status "%s" was ' - 'found.' % (ad_group['name'], ad_group['id'], - ad_group['status'])) + print('Ad group with name "%s", id "%s" and status "%s" was ' + 'found.' % (ad_group['name'], ad_group['id'], + ad_group['status'])) else: - print 'No ad groups were found.' + print('No ad groups were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/basic_operations/get_campaigns.py b/examples/adwords/v201809/basic_operations/get_campaigns.py index 4c1de220..c8ae3cb9 100755 --- a/examples/adwords/v201809/basic_operations/get_campaigns.py +++ b/examples/adwords/v201809/basic_operations/get_campaigns.py @@ -53,11 +53,11 @@ def main(client): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) + print('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) else: - print 'No campaigns were found.' + print('No campaigns were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py b/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py index 0bcab324..f5e511a2 100755 --- a/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py +++ b/examples/adwords/v201809/basic_operations/get_campaigns_with_awql.py @@ -48,11 +48,11 @@ def main(client): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign with id "%s", name "%s", and status "%s" was ' - 'found.' % (campaign['id'], campaign['name'], - campaign['status'])) + print('Campaign with id "%s", name "%s", and status "%s" was ' + 'found.' % (campaign['id'], campaign['name'], + campaign['status'])) else: - print 'No campaigns were found.' + print('No campaigns were found.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py b/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py index 2c75b20c..99d409b1 100755 --- a/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py +++ b/examples/adwords/v201809/basic_operations/get_expanded_text_ads.py @@ -71,13 +71,13 @@ def main(client, ad_group_id): # Display results. if 'entries' in page: for ad in page['entries']: - print ('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' - 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' - 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], - ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], - ad['ad']['description'])) + print('ExpandedTextAd with id "%d", AdGroupId "%d", status "%s", ' + 'headlinePart1 "%s", headlinePart2 "%s", description "%s" was ' + 'found.' % (ad['ad']['id'], ad['adGroupId'], ad['status'], + ad['ad']['headlinePart1'], ad['ad']['headlinePart2'], + ad['ad']['description'])) else: - print 'No ads were found.' + print('No ads were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/basic_operations/get_keywords.py b/examples/adwords/v201809/basic_operations/get_keywords.py index 9bc3085c..c0a7da95 100755 --- a/examples/adwords/v201809/basic_operations/get_keywords.py +++ b/examples/adwords/v201809/basic_operations/get_keywords.py @@ -67,14 +67,14 @@ def main(client, adgroup_id): # Display results. if 'entries' in page: for keyword in page['entries']: - print ('Keyword ID "%s", type "%s", text "%s", and match type ' - '"%s" was found.' % ( - keyword['criterion']['id'], - keyword['criterion']['type'], - keyword['criterion']['text'], - keyword['criterion']['matchType'])) + print('Keyword ID "%s", type "%s", text "%s", and match type ' + '"%s" was found.' % ( + keyword['criterion']['id'], + keyword['criterion']['type'], + keyword['criterion']['text'], + keyword['criterion']['matchType'])) else: - print 'No keywords were found.' + print('No keywords were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py b/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py index f449281f..42c6be89 100755 --- a/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py +++ b/examples/adwords/v201809/basic_operations/get_responsive_search_ads.py @@ -74,10 +74,10 @@ def main(client, ad_group_id): if 'entries' in page: for ad_group_ad in page['entries']: ad = ad_group_ad['ad'] - print ('Responsive search ad with status %s and id "%d" was found.\n' - 'Headlines:\n%s\n' - 'Descriptions:\n%s' - % (ad_group_ad['status'], ad['id'], + print('Responsive search ad with status %s and id "%d" was found.\n' + 'Headlines:\n%s\n' + 'Descriptions:\n%s' + % (ad_group_ad['status'], ad['id'], '\n'.join(['\t%s (pinned to %s)' % (headline['asset']['assetText'], headline['pinnedField']) @@ -87,7 +87,7 @@ def main(client, ad_group_id): headline['pinnedField']) for headline in ad['descriptions']]))) else: - print 'No ads were found.' + print('No ads were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/basic_operations/pause_ad.py b/examples/adwords/v201809/basic_operations/pause_ad.py index a495cb3d..1e5f9733 100755 --- a/examples/adwords/v201809/basic_operations/pause_ad.py +++ b/examples/adwords/v201809/basic_operations/pause_ad.py @@ -51,7 +51,7 @@ def main(client, ad_group_id, ad_id): # Display results. for ad in ads['value']: - print 'Ad with id "%s" was updated.'% ad['ad']['id'] + print('Ad with id "%s" was updated.'% ad['ad']['id']) if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/remove_ad.py b/examples/adwords/v201809/basic_operations/remove_ad.py index 3c238576..1f0753f6 100755 --- a/examples/adwords/v201809/basic_operations/remove_ad.py +++ b/examples/adwords/v201809/basic_operations/remove_ad.py @@ -51,8 +51,8 @@ def main(client, ad_group_id, ad_id): # Display results. for ad in result['value']: - print ('Ad with id "%s" and type "%s" was deleted.' - % (ad['ad']['id'], ad['ad']['Ad.Type'])) + print('Ad with id "%s" and type "%s" was deleted.' + % (ad['ad']['id'], ad['ad']['Ad.Type'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/remove_ad_group.py b/examples/adwords/v201809/basic_operations/remove_ad_group.py index b09b9cd2..b35c356a 100755 --- a/examples/adwords/v201809/basic_operations/remove_ad_group.py +++ b/examples/adwords/v201809/basic_operations/remove_ad_group.py @@ -47,8 +47,8 @@ def main(client, ad_group_id): # Display results. for ad_group in result['value']: - print ('Ad group with name "%s" and id "%s" was deleted.' - % (ad_group['name'], ad_group['id'])) + print('Ad group with name "%s" and id "%s" was deleted.' + % (ad_group['name'], ad_group['id'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/remove_campaign.py b/examples/adwords/v201809/basic_operations/remove_campaign.py index d919860c..778f9dc6 100755 --- a/examples/adwords/v201809/basic_operations/remove_campaign.py +++ b/examples/adwords/v201809/basic_operations/remove_campaign.py @@ -47,8 +47,8 @@ def main(client, campaign_id): # Display results. for campaign in result['value']: - print ('Campaign with name "%s" and id "%s" was deleted.' - % (campaign['name'], campaign['id'])) + print('Campaign with name "%s" and id "%s" was deleted.' + % (campaign['name'], campaign['id'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/remove_keyword.py b/examples/adwords/v201809/basic_operations/remove_keyword.py index 0d08ecbc..f75a6547 100755 --- a/examples/adwords/v201809/basic_operations/remove_keyword.py +++ b/examples/adwords/v201809/basic_operations/remove_keyword.py @@ -54,9 +54,9 @@ def main(client, ad_group_id, criterion_id): # Display results. for criterion in result['value']: - print ('Ad group criterion with ad group id "%s", criterion id "%s", ' - 'and type "%s" was deleted.' - % (criterion['adGroupId'], criterion['criterion']['id'], + print('Ad group criterion with ad group id "%s", criterion id "%s", ' + 'and type "%s" was deleted.' + % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['Criterion.Type'])) diff --git a/examples/adwords/v201809/basic_operations/update_ad_group.py b/examples/adwords/v201809/basic_operations/update_ad_group.py index 1385903f..be3bad7c 100755 --- a/examples/adwords/v201809/basic_operations/update_ad_group.py +++ b/examples/adwords/v201809/basic_operations/update_ad_group.py @@ -72,9 +72,9 @@ def main(client, ad_group_id, bid_micro_amount=None): cpc_bid_micros = bid['bid']['microAmount'] break - print ('Ad group with name "%s", and id "%s" was updated to have status ' - '"%s" and CPC bid %d.' - % (ad_group['name'], ad_group['id'], ad_group['status'], + print('Ad group with name "%s", and id "%s" was updated to have status ' + '"%s" and CPC bid %d.' + % (ad_group['name'], ad_group['id'], ad_group['status'], cpc_bid_micros)) diff --git a/examples/adwords/v201809/basic_operations/update_campaign.py b/examples/adwords/v201809/basic_operations/update_campaign.py index fa9ae36c..ecd19f1f 100755 --- a/examples/adwords/v201809/basic_operations/update_campaign.py +++ b/examples/adwords/v201809/basic_operations/update_campaign.py @@ -47,8 +47,8 @@ def main(client, campaign_id): # Display results. for campaign in campaigns['value']: - print ('Campaign with name "%s" and id "%s" was updated.' - % (campaign['name'], campaign['id'])) + print('Campaign with name "%s" and id "%s" was updated.' + % (campaign['name'], campaign['id'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py b/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py index 38753fc0..ba35d9a6 100755 --- a/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py +++ b/examples/adwords/v201809/basic_operations/update_expanded_text_ad.py @@ -57,14 +57,14 @@ def main(client, ad_id): result = ad_service.mutate(operations) updated_ad = result['value'][0] - print 'Expanded text ad with ID %s was updated.' % updated_ad['id'] - print ('\tHeadline part 1: %s\nHeadline part 2: %s\nDescription: %s\n' - 'Final URL: %s\nFinal mobile URL: %s' % - (updated_ad['headlinePart1'], - updated_ad['headlinePart2'], - updated_ad['description'], - updated_ad['finalUrls'][0], - updated_ad['finalMobileUrls'][0])) + print('Expanded text ad with ID %s was updated.' % updated_ad['id']) + print('\tHeadline part 1: %s\nHeadline part 2: %s\nDescription: %s\n' + 'Final URL: %s\nFinal mobile URL: %s' % + (updated_ad['headlinePart1'], + updated_ad['headlinePart2'], + updated_ad['description'], + updated_ad['finalUrls'][0], + updated_ad['finalMobileUrls'][0])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/basic_operations/update_keyword.py b/examples/adwords/v201809/basic_operations/update_keyword.py index fa956ea4..6078d6a2 100755 --- a/examples/adwords/v201809/basic_operations/update_keyword.py +++ b/examples/adwords/v201809/basic_operations/update_keyword.py @@ -65,14 +65,14 @@ def main(client, ad_group_id, criterion_id): if 'value' in ad_group_criteria: for criterion in ad_group_criteria['value']: if criterion['criterion']['Criterion.Type'] == 'Keyword': - print ('Ad group criterion with ad group id "%s" and criterion id ' - '"%s" currently has bids:' - % (criterion['adGroupId'], criterion['criterion']['id'])) + print('Ad group criterion with ad group id "%s" and criterion id ' + '"%s" currently has bids:' + % (criterion['adGroupId'], criterion['criterion']['id'])) for bid in criterion['biddingStrategyConfiguration']['bids']: - print '\tType: "%s", value: %s' % (bid['Bids.Type'], - bid['bid']['microAmount']) + print('\tType: "%s", value: %s' % (bid['Bids.Type'],) + bid['bid']['microAmount']) else: - print 'No ad group criteria were updated.' + print('No ad group criteria were updated.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py b/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py index 31cfdf32..58aa128c 100755 --- a/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py +++ b/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py @@ -38,7 +38,7 @@ def main(client, campaign_id1, campaign_id2): campaign_group_id = _CreateCampaignGroup(client) _AddCampaignsToGroup(client, campaign_group_id, [campaign_id1, campaign_id2]) _CreatePerformanceTarget(client, campaign_group_id) - print 'Campaign group and its performance target were setup successfully.' + print('Campaign group and its performance target were setup successfully.') def _CreateCampaignGroup(client): @@ -67,8 +67,8 @@ def _CreateCampaignGroup(client): campaign_group_id = campaign_group['id'] # Display the results. - print 'Campaign group with ID "%d" and name "%s" was created.' % ( - campaign_group_id, campaign_group['name']) + print('Campaign group with ID "%d" and name "%s" was created.' % ( + campaign_group_id, campaign_group['name'])) return campaign_group_id @@ -96,8 +96,8 @@ def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): campaign_service.mutate(operations) # Display the results. - print ('The following campaign IDs were added to the campaign group with ID ' - '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) + print('The following campaign IDs were added to the campaign group with ID ' + '"%d":\n\t%s' % (campaign_group_id, campaign_ids)) def _CreatePerformanceTarget(client, campaign_group_id): @@ -141,8 +141,8 @@ def _CreatePerformanceTarget(client, campaign_group_id): cgpt = cgpt_service.mutate(operations)['value'][0] # Display the results. - print ('Campaign performance target with ID "%d" was added for campaign ' - 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) + print('Campaign performance target with ID "%d" was added for campaign ' + 'group ID "%d".' % (cgpt['id'], cgpt['campaignGroupId'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/add_campaign_labels.py b/examples/adwords/v201809/campaign_management/add_campaign_labels.py index 0ac06b90..138c5dc3 100755 --- a/examples/adwords/v201809/campaign_management/add_campaign_labels.py +++ b/examples/adwords/v201809/campaign_management/add_campaign_labels.py @@ -56,8 +56,8 @@ def main(client, campaign_id1, campaign_id2, label_id): # Display results. for label in result['value']: - print ('CampaignLabel with campaignId "%s" and labelId "%s" was added.' - % (label['campaignId'], label['labelId'])) + print('CampaignLabel with campaignId "%s" and labelId "%s" was added.' + % (label['campaignId'], label['labelId'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py b/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py index cb8602be..dc18b4f4 100755 --- a/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py +++ b/examples/adwords/v201809/campaign_management/add_complete_campaigns_using_batch_job.py @@ -23,8 +23,8 @@ import random import time -import urllib2 import uuid +from urllib.request import urlopen from googleads import adwords @@ -45,8 +45,8 @@ def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): # Retrieve the URL used to upload the BatchJob operations. upload_url = batch_job['uploadUrl']['url'] batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) + print('Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url)) # Generate operations to upload. budget_operations = BuildBudgetOperations(batch_job_helper) @@ -68,7 +68,7 @@ def main(client, number_of_campaigns, number_of_adgroups, number_of_keywords): # Download and display results. download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() + response = urlopen(download_url).read() PrintResponse(batch_job_helper, response) @@ -386,15 +386,15 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, batch_job['status'] in PENDING_STATUSES): sleep_interval = (30 * (2 ** poll_attempt) + (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + print('Batch Job not ready, sleeping for %s seconds.' % sleep_interval) time.sleep(sleep_interval) batch_job = GetBatchJob(client, batch_job_id) poll_attempt += 1 if 'downloadUrl' in batch_job: url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) + print('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) return url raise Exception('Batch Job not finished downloading. Try checking later.') @@ -411,14 +411,14 @@ def PrintResponse(batch_job_helper, response_xml): if 'rval' in response['mutateResponse']: for data in response['mutateResponse']['rval']: if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] + print('Operation %s - FAILURE:' % data['index']) + print('\terrorType=%s' % data['errorList']['errors']['ApiError.Type']) + print('\ttrigger=%s' % data['errorList']['errors']['trigger']) + print('\terrorString=%s' % data['errorList']['errors']['errorString']) + print('\tfieldPath=%s' % data['errorList']['errors']['fieldPath']) + print('\treason=%s' % data['errorList']['errors']['reason']) if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] + print('Operation %s - SUCCESS.' % data['index']) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/add_draft.py b/examples/adwords/v201809/campaign_management/add_draft.py index 0be2a990..c2c5b8ca 100755 --- a/examples/adwords/v201809/campaign_management/add_draft.py +++ b/examples/adwords/v201809/campaign_management/add_draft.py @@ -70,8 +70,8 @@ def main(client, base_campaign_id): criterion = campaign_criterion_service.mutate([criterion_operation])[ 'value'][0] - print ('Draft updated to include criteria in campaign with ID %d' % - draft_campaign_id) + print('Draft updated to include criteria in campaign with ID %d' % + draft_campaign_id) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py b/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py index 2c5603a0..6fabf0da 100755 --- a/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py +++ b/examples/adwords/v201809/campaign_management/add_keywords_using_incremental_batch_job.py @@ -21,8 +21,8 @@ import random import time -import urllib2 import uuid +from urllib.request import urlopen from googleads import adwords @@ -42,8 +42,8 @@ def main(client, adgroup_id): # Retrieve the URL used to upload the BatchJob operations. upload_url = batch_job['uploadUrl']['url'] batch_job_id = batch_job['id'] - print 'Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( - batch_job['id'], batch_job['status'], upload_url) + print('Created BatchJob with ID "%d", status "%s", and upload URL "%s"' % ( + batch_job['id'], batch_job['status'], upload_url)) # Initialize IncrementalUploadHelper. incremental_uploader = batch_job_helper.GetIncrementalUploadHelper(upload_url) @@ -63,7 +63,7 @@ def main(client, adgroup_id): # Download and display results. download_url = GetBatchJobDownloadUrlWhenReady(client, batch_job_id) - response = urllib2.urlopen(download_url).read() + response = urlopen(download_url).read() PrintResponse(batch_job_helper, response) @@ -146,18 +146,18 @@ def CancelBatchJob(client, batch_job, max_poll_attempts=MAX_POLL_ATTEMPTS): batch_job['status'] != 'CANCELED'): sleep_interval = (30 * (2 ** poll_attempt) + (random.randint(0, 10000) / 1000)) - print ('Batch Job not finished canceling, sleeping for %s seconds.' - % sleep_interval) + print('Batch Job not finished canceling, sleeping for %s seconds.' + % sleep_interval) time.sleep(sleep_interval) batch_job = GetBatchJob(client, batch_job['id']) poll_attempt += 1 if batch_job['status'] == 'CANCELED': - print ('Batch Job with ID "%d" has been successfully canceled.' % - batch_job['id']) + print('Batch Job with ID "%d" has been successfully canceled.' % + batch_job['id']) else: - print ('Batch Job with ID "%d" failed to cancel after polling %d times.' - % (batch_job['id'], max_poll_attempts)) + print('Batch Job with ID "%d" failed to cancel after polling %d times.' + % (batch_job['id'], max_poll_attempts)) def GetBatchJob(client, batch_job_id): @@ -213,19 +213,19 @@ def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, batch_job['status'] in PENDING_STATUSES): sleep_interval = (30 * (2 ** poll_attempt) + (random.randint(0, 10000) / 1000)) - print 'Batch Job not ready, sleeping for %s seconds.' % sleep_interval + print('Batch Job not ready, sleeping for %s seconds.' % sleep_interval) time.sleep(sleep_interval) batch_job = GetBatchJob(client, batch_job_id) poll_attempt += 1 if 'downloadUrl' in batch_job: url = batch_job['downloadUrl']['url'] - print ('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' - % (batch_job['id'], batch_job['status'], url)) + print('Batch Job with Id "%s", Status "%s", and DownloadUrl "%s" ready.' + % (batch_job['id'], batch_job['status'], url)) return url - print ('BatchJob with ID "%s" is being canceled because it was in a pending ' - 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) + print('BatchJob with ID "%s" is being canceled because it was in a pending ' + 'state after polling %d times.' % (batch_job_id, max_poll_attempts)) CancelBatchJob(client, batch_job) @@ -241,14 +241,14 @@ def PrintResponse(batch_job_helper, response_xml): if 'rval' in response['mutateResponse']: for data in response['mutateResponse']['rval']: if 'errorList' in data: - print 'Operation %s - FAILURE:' % data['index'] - print '\terrorType=%s' % data['errorList']['errors']['ApiError.Type'] - print '\ttrigger=%s' % data['errorList']['errors']['trigger'] - print '\terrorString=%s' % data['errorList']['errors']['errorString'] - print '\tfieldPath=%s' % data['errorList']['errors']['fieldPath'] - print '\treason=%s' % data['errorList']['errors']['reason'] + print('Operation %s - FAILURE:' % data['index']) + print('\terrorType=%s' % data['errorList']['errors']['ApiError.Type']) + print('\ttrigger=%s' % data['errorList']['errors']['trigger']) + print('\terrorString=%s' % data['errorList']['errors']['errorString']) + print('\tfieldPath=%s' % data['errorList']['errors']['fieldPath']) + print('\treason=%s' % data['errorList']['errors']['reason']) if 'result' in data: - print 'Operation %s - SUCCESS.' % data['index'] + print('Operation %s - SUCCESS.' % data['index']) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/add_trial.py b/examples/adwords/v201809/campaign_management/add_trial.py index d7588a83..3237d432 100755 --- a/examples/adwords/v201809/campaign_management/add_trial.py +++ b/examples/adwords/v201809/campaign_management/add_trial.py @@ -70,19 +70,19 @@ def main(client, base_campaign_id, draft_id): while is_pending and poll_attempts < MAX_POLL_ATTEMPTS: trial = trial_service.get(selector)['entries'][0] - print 'Trial ID %d has status "%s"' % (trial['id'], trial['status']) + print('Trial ID %d has status "%s"' % (trial['id'], trial['status'])) poll_attempts += 1 is_pending = trial['status'] == 'CREATING' if is_pending: sleep_seconds = 30 * (2 ** poll_attempts) - print 'Sleeping for %d seconds.' % sleep_seconds + print('Sleeping for %d seconds.' % sleep_seconds) time.sleep(sleep_seconds) if trial['status'] == 'ACTIVE': # The trial creation was successful. - print 'Trial created with ID %d and trial campaign ID %d' % ( - trial['id'], trial['trialCampaignId']) + print('Trial created with ID %d and trial campaign ID %d' % ( + trial['id'], trial['trialCampaignId'])) elif trial['status'] == 'CREATION_FAILED': # The trial creation failed, and errors can be fetched from the # TrialAsyncErrorService. @@ -98,16 +98,16 @@ def main(client, base_campaign_id, draft_id): errors = trial_async_error_service.get(selector)['entries'] if not errors: - print 'Could not retrieve errors for trial %d' % trial['id'] + print('Could not retrieve errors for trial %d' % trial['id']) else: - print 'Could not create trial due to the following errors:' + print('Could not create trial due to the following errors:') for error in errors: - print 'Error: %s' % error['asyncError'] + print('Error: %s' % error['asyncError']) else: # Most likely, the trial is still being created. You can continue polling, # but we have limited the number of attempts in the example. - print ('Timed out waiting to create trial from draft %d with base campaign ' - '%d' % (draft_id, base_campaign_id)) + print('Timed out waiting to create trial from draft %d with base campaign ' + '%d' % (draft_id, base_campaign_id)) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py index 5a0acf3d..c7afeb7b 100755 --- a/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py +++ b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads.py @@ -70,30 +70,30 @@ def main(client, ad_group_id): disapproved_count += 1 policy_summary = ad['policySummary'] - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % ad['ad']['id']) + print('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) # Display the policy topic entries related to the ad disapproval. for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s, Help Center URL: %s' % ( + print(' topic ID: %s, topic name: %s, Help Center URL: %s' % ( policy_topic_entry['policyTopicId'], policy_topic_entry['policyTopicName'], - policy_topic_entry['policyTopicHelpCenterUrl']) + policy_topic_entry['policyTopicHelpCenterUrl'])) # Display the attributes and values that triggered the policy topic. policy_topic_evidences = policy_topic_entry['policyTopicEvidences'] if policy_topic_evidences: for evidence in policy_topic_entry['policyTopicEvidences']: - print (' evidence type: %s' - % evidence['policyTopicEvidenceType']) + print(' evidence type: %s' + % evidence['policyTopicEvidenceType']) evidence_text_list = evidence['evidenceTextList'] if evidence_text_list: for index, evidence_text in enumerate(evidence_text_list): - print ' evidence text[%d]: %s' % (index, evidence_text) + print(' evidence text[%d]: %s' % (index, evidence_text)) offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) - print '%d disapproved ads were found.' % disapproved_count + print('%d disapproved ads were found.' % disapproved_count) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py index a8fb9c6c..f4f890cf 100755 --- a/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py +++ b/examples/adwords/v201809/campaign_management/get_all_disapproved_ads_with_awql.py @@ -56,29 +56,29 @@ def main(client, ad_group_id): disapproved_count += 1 policy_summary = ad['policySummary'] - print ('Ad with id "%s" was disapproved with the following policy ' - 'topic entries:' % ad['ad']['id']) + print('Ad with id "%s" was disapproved with the following policy ' + 'topic entries:' % ad['ad']['id']) # Display the policy topic entries related to the ad disapproval. for policy_topic_entry in policy_summary['policyTopicEntries']: - print ' topic ID: %s, topic name: %s' % ( + print(' topic ID: %s, topic name: %s' % ( policy_topic_entry['policyTopicId'], - policy_topic_entry['policyTopicName']) + policy_topic_entry['policyTopicName'])) # Display the attributes and values that triggered the policy topic. if ('policyTopicEvidences' in policy_topic_entry and policy_topic_entry['policyTopicEvidences']): for evidence in policy_topic_entry['policyTopicEvidences']: - print (' evidence type: %s' - % evidence['policyTopicEvidenceType']) + print(' evidence type: %s' + % evidence['policyTopicEvidenceType']) evidence_text_list = evidence['evidenceTextList'] if evidence_text_list: for index, evidence_text in enumerate(evidence_text_list): - print ' evidence text[%d]: %s' % (index, evidence_text) + print(' evidence text[%d]: %s' % (index, evidence_text)) if not query.HasNext(page): break query.NextPage() - print '%d disapproved ads were found.' % disapproved_count + print('%d disapproved ads were found.' % disapproved_count) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py b/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py index d509ee24..6a401529 100755 --- a/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py +++ b/examples/adwords/v201809/campaign_management/get_campaigns_by_label.py @@ -66,10 +66,10 @@ def main(client, label_id): # Display results. if 'entries' in page: for campaign in page['entries']: - print ('Campaign found with Id "%s", name "%s", and labels: %s' - % (campaign['id'], campaign['name'], campaign['labels'])) + print('Campaign found with Id "%s", name "%s", and labels: %s' + % (campaign['id'], campaign['name'], campaign['labels'])) else: - print 'No campaigns were found.' + print('No campaigns were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) diff --git a/examples/adwords/v201809/campaign_management/graduate_trial.py b/examples/adwords/v201809/campaign_management/graduate_trial.py index 0491ddd4..73e24f12 100755 --- a/examples/adwords/v201809/campaign_management/graduate_trial.py +++ b/examples/adwords/v201809/campaign_management/graduate_trial.py @@ -67,9 +67,9 @@ def main(client, trial_id): # Graduation is a synchronous operation, so the campaign is already ready. If # you promote instead, make sure to see the polling scheme demonstrated in # add_trial.py to wait for the asynchronous operation to finish. - print ('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' - 'is no longer dependent on this trial.' % ( - trial['id'], trial['trialCampaignId'], budget_id)) + print('Trial ID %d graduated. Campaign %d was given a new budget ID %d and ' + 'is no longer dependent on this trial.' % ( + trial['id'], trial['trialCampaignId'], budget_id)) if __name__ == '__main__': diff --git a/examples/adwords/v201809/campaign_management/set_ad_parameters.py b/examples/adwords/v201809/campaign_management/set_ad_parameters.py index 2f2ffff1..bab7186f 100755 --- a/examples/adwords/v201809/campaign_management/set_ad_parameters.py +++ b/examples/adwords/v201809/campaign_management/set_ad_parameters.py @@ -59,8 +59,8 @@ def main(client, ad_group_id, criterion_id): # Display results. for ad in ads: - print ('Text ad with id "%s" was successfully added to an ad group with ' - 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) + print('Text ad with id "%s" was successfully added to an ad group with ' + 'id "%s".' % (ad['adGroupId'], ad['ad']['id'])) # Construct operations for setting ad parameters. operations = [ @@ -87,9 +87,9 @@ def main(client, ad_group_id, criterion_id): # Display results. for ad_param in ad_params: - print ('Ad parameter with text "%s" was successfully set for criterion ' - 'with id "%s" and ad group id "%s".' - % (ad_param['insertionText'], ad_param['criterionId'], + print('Ad parameter with text "%s" was successfully set for criterion ' + 'with id "%s" and ad group id "%s".' + % (ad_param['insertionText'], ad_param['criterionId'], ad_param['adGroupId'])) diff --git a/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py b/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py index e25e9ed7..9c7a869c 100755 --- a/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py +++ b/examples/adwords/v201809/campaign_management/set_criterion_bid_modifier.py @@ -63,9 +63,9 @@ def main(client, campaign_id, bid_modifier): # Display the resulting campaign criteria. for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s" and criterion id "%s" ' - 'was updated with bid modifier "%s".' - % (campaign_criterion['campaignId'], + print('Campaign criterion with campaign id "%s" and criterion id "%s" ' + 'was updated with bid modifier "%s".' + % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['bidModifier'])) diff --git a/examples/adwords/v201809/campaign_management/validate_text_ad.py b/examples/adwords/v201809/campaign_management/validate_text_ad.py index 9ba36eaf..ea1035d9 100755 --- a/examples/adwords/v201809/campaign_management/validate_text_ad.py +++ b/examples/adwords/v201809/campaign_management/validate_text_ad.py @@ -73,8 +73,8 @@ def main(client, ad_group_id): }] try: ad_group_ad_service.mutate(operations) - except errors.GoogleAdsServerFault, e: - print 'Validation correctly failed with "%s".' % str(e) + except errors.GoogleAdsServerFault as e: + print('Validation correctly failed with "%s".' % str(e)) if __name__ == '__main__': diff --git a/examples/adwords/v201809/error_handling/handle_partial_failures.py b/examples/adwords/v201809/error_handling/handle_partial_failures.py index 03b8468a..fc4c703d 100755 --- a/examples/adwords/v201809/error_handling/handle_partial_failures.py +++ b/examples/adwords/v201809/error_handling/handle_partial_failures.py @@ -93,10 +93,10 @@ def main(client, ad_group_id): # Display results. for criterion in result['value']: if criterion['AdGroupCriterion.Type'] == 'BiddableAdGroupCriterion': - print ('Added keyword ad group criterion with ad group id "%s", ' - 'criterion id "%s", text "%s", and match type "%s" was ' - 'added.' - % (criterion['adGroupId'], criterion['criterion']['id'], + print('Added keyword ad group criterion with ad group id "%s", ' + 'criterion id "%s", text "%s", and match type "%s" was ' + 'added.' + % (criterion['adGroupId'], criterion['criterion']['id'], criterion['criterion']['text'], criterion['criterion']['matchType'])) @@ -120,8 +120,8 @@ def main(client, ad_group_id): adgroup_criterion['criterion']['text'], error['errorString'])) else: - print ('A failure has occurred for the following reasons: %s\n' - % error['errorString']) + print('A failure has occurred for the following reasons: %s\n' + % error['errorString']) if __name__ == '__main__': diff --git a/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py b/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py index 3d9e944c..0a467e25 100755 --- a/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py +++ b/examples/adwords/v201809/extensions/add_google_my_business_location_extensions.py @@ -91,7 +91,7 @@ def main(client, gmb_email_address, gmb_access_token, gmb_response = client.GetService('FeedService', version='v201809').mutate( gmb_operations) added_feed = gmb_response['value'][0] - print 'Added GMB feed with ID: %d\n' % added_feed['id'] + print('Added GMB feed with ID: %d\n' % added_feed['id']) # Add a CustomerFeed that associates the feed with this customer for the # LOCATION placeholder type. @@ -127,8 +127,8 @@ def main(client, gmb_email_address, gmb_access_token, except errors.GoogleAdsServerFault: # Wait using exponential backoff policy sleep_seconds = 2 ** i - print ('Attempt %d to add the CustomerFeed was not successful.' - 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) + print('Attempt %d to add the CustomerFeed was not successful.' + 'Waiting %d seconds before trying again.\n' % (i, sleep_seconds)) time.sleep(sleep_seconds) i += 1 @@ -138,8 +138,8 @@ def main(client, gmb_email_address, gmb_access_token, 'Could not create the CustomerFeed after %s attempts. Please retry the ' 'CustomerFeed ADD operation later.' % MAX_CUSTOMER_FEED_ADD_ATTEMPTS) - print ('Added CustomerFeed for feed ID %d and placeholder type %d\n' - % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) + print('Added CustomerFeed for feed ID %d and placeholder type %d\n' + % (added_customer_feed['id'], added_customer_feed['placeholderTypes'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/adwords/v201809/extensions/add_prices.py b/examples/adwords/v201809/extensions/add_prices.py index e852819b..fbfa40db 100755 --- a/examples/adwords/v201809/extensions/add_prices.py +++ b/examples/adwords/v201809/extensions/add_prices.py @@ -105,8 +105,8 @@ def main(client, campaign_id): # Print the results. if 'value' in response: - print ('Extension setting with type "%s" was added to your account.' - % response['value'][0]['extensionType']) + print('Extension setting with type "%s" was added to your account.' + % response['value'][0]['extensionType']) else: raise errors.GoogleAdsError('No extension settings were added.') diff --git a/examples/adwords/v201809/extensions/add_site_links.py b/examples/adwords/v201809/extensions/add_site_links.py index 05f89d0f..f9b68717 100755 --- a/examples/adwords/v201809/extensions/add_site_links.py +++ b/examples/adwords/v201809/extensions/add_site_links.py @@ -45,8 +45,8 @@ def main(client, campaign_id): customer_tz = timezone(customer['dateTimeZone']) time_fmt = '%s %s' % ('%Y%m%d %H%M%S', customer_tz) - print ('Found customer ID %d with time zone "%s".' - % (customer['customerId'], customer['dateTimeZone'])) + print('Found customer ID %d with time zone "%s".' + % (customer['customerId'], customer['dateTimeZone'])) # Create the sitelinks sitelink1 = { @@ -132,9 +132,9 @@ def main(client, campaign_id): response = campaign_extension_setting_service.mutate([operation]) if 'value' in response: - print ('Extension setting with type "%s" was added to campaignId "%d".' % - (response['value'][0]['extensionType'], - response['value'][0]['campaignId'])) + print('Extension setting with type "%s" was added to campaignId "%d".' % + (response['value'][0]['extensionType'], + response['value'][0]['campaignId'])) else: raise errors.GoogleAdsError('No extension settings were added.') diff --git a/examples/adwords/v201809/extensions/add_site_links_using_feeds.py b/examples/adwords/v201809/extensions/add_site_links_using_feeds.py index 86e70851..3b3a004e 100755 --- a/examples/adwords/v201809/extensions/add_site_links_using_feeds.py +++ b/examples/adwords/v201809/extensions/add_site_links_using_feeds.py @@ -117,12 +117,12 @@ def main(client, campaign_id, ad_group_id=None): final_url_feed_attribute_id = feed['attributes'][1]['id'] line_2_feed_attribute_id = feed['attributes'][2]['id'] line_3_feed_attribute_id = feed['attributes'][3]['id'] - print ('Feed with name "%s" and ID "%d" was added with' % - (feed['name'], feed['id'])) - print ('\tText attribute ID "%d" and Final URL attribute ID "%d".' % - (link_text_feed_attribute_id, final_url_feed_attribute_id)) - print ('\tLine 2 attribute ID "%d" and Line 3 attribute ID "%d".' % - (line_2_feed_attribute_id, line_3_feed_attribute_id)) + print('Feed with name "%s" and ID "%d" was added with' % + (feed['name'], feed['id'])) + print('\tText attribute ID "%d" and Final URL attribute ID "%d".' % + (link_text_feed_attribute_id, final_url_feed_attribute_id)) + print('\tLine 2 attribute ID "%d" and Line 3 attribute ID "%d".' % + (line_2_feed_attribute_id, line_3_feed_attribute_id)) sitelinks_data['feedId'] = feed['id'] sitelinks_data['linkTextFeedId'] = link_text_feed_attribute_id sitelinks_data['finalUrlFeedId'] = final_url_feed_attribute_id @@ -196,7 +196,7 @@ def main(client, campaign_id, ad_group_id=None): if 'value' in response: sitelinks_data['feedItemIds'] = [] for feed_item in response['value']: - print 'Feed item with ID %d was added.' % feed_item['feedItemId'] + print('Feed item with ID %d was added.' % feed_item['feedItemId']) sitelinks_data['feedItemIds'].append(feed_item['feedItemId']) else: raise errors.GoogleAdsError('No feed items were added.') @@ -236,10 +236,10 @@ def main(client, campaign_id, ad_group_id=None): ]) if 'value' in response: feed_mapping = response['value'][0] - print ('Feed mapping with ID %d and placeholder type %s was saved for feed' - ' with ID %d.' % - (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], - feed_mapping['feedId'])) + print('Feed mapping with ID %d and placeholder type %s was saved for feed' + ' with ID %d.' % + (feed_mapping['feedMappingId'], feed_mapping['placeholderType'], + feed_mapping['feedId'])) else: raise errors.GoogleAdsError('No feed mappings were added.') @@ -265,8 +265,8 @@ def main(client, campaign_id, ad_group_id=None): ]) if 'value' in response: campaign_feed = response['value'][0] - print ('Campaign with ID %d was associated with feed with ID %d.' % - (campaign_feed['campaignId'], campaign_feed['feedId'])) + print('Campaign with ID %d was associated with feed with ID %d.' % + (campaign_feed['campaignId'], campaign_feed['feedId'])) else: raise errors.GoogleAdsError('No campaign feeds were added.') @@ -288,9 +288,9 @@ def main(client, campaign_id, ad_group_id=None): response = feed_item_target_service.mutate(operations) if 'value' in response: - print ('Feed item target for feed ID "%d" and feed item ID "%d" was ' - 'created to restrict serving to ad group ID "%d".' - % (feed_item_target['feedId'], feed_item_target['feedItemId'], + print('Feed item target for feed ID "%d" and feed item ID "%d" was ' + 'created to restrict serving to ad group ID "%d".' + % (feed_item_target['feedId'], feed_item_target['feedItemId'], feed_item_target['adGroupId'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/migration/migrate_to_extension_settings.py b/examples/adwords/v201809/migration/migrate_to_extension_settings.py index c9c888b9..59b87e48 100755 --- a/examples/adwords/v201809/migration/migrate_to_extension_settings.py +++ b/examples/adwords/v201809/migration/migrate_to_extension_settings.py @@ -471,7 +471,7 @@ def GetSitelinksFromFeed(client, feed): elif field_id == SITE_LINK_FIELDS['LINE3']: site_link_from_feed['line3'] = attribute_value['stringValue'] else: - print 'No applicable Site Link Field found for Id: %s' % field_id + print('No applicable Site Link Field found for Id: %s' % field_id) feed_items[feed_item['feedItemId']] = site_link_from_feed @@ -496,10 +496,10 @@ def main(client): feed_item_ids = GetFeedItemIdsForCampaign(campaign_feed) if feed_item_ids == 0: - print ('Migration skipped for campaign feed with campaign ID %d ' - 'and feed ID %d because no mapped feed item IDs were found in ' - 'the campaign feed\'s matching function.' - % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) + print('Migration skipped for campaign feed with campaign ID %d ' + 'and feed ID %d because no mapped feed item IDs were found in ' + 'the campaign feed\'s matching function.' + % (campaign_feed['campaign_id'], campaign_feed['feed_id'])) continue platform_restrictions = GetPlatformRestrictions(campaign_feed) diff --git a/examples/adwords/v201809/misc/get_all_image_assets.py b/examples/adwords/v201809/misc/get_all_image_assets.py index d10694a2..32881373 100755 --- a/examples/adwords/v201809/misc/get_all_image_assets.py +++ b/examples/adwords/v201809/misc/get_all_image_assets.py @@ -57,14 +57,14 @@ def main(client): # Display results. if 'entries' in page: for image in page['entries']: - print ('Image asset with id %s, name "%s", and status %s was found.\n' - '\tSize is %sx%s and asset URL is %s.' % - (image['assetId'], image['assetName'], image['assetStatus'], - image['fullSizeInfo']['imageWidth'], - image['fullSizeInfo']['imageHeight'], - image['fullSizeInfo']['imageUrl'])) + print('Image asset with id %s, name "%s", and status %s was found.\n' + '\tSize is %sx%s and asset URL is %s.' % + (image['assetId'], image['assetName'], image['assetStatus'], + image['fullSizeInfo']['imageWidth'], + image['fullSizeInfo']['imageHeight'], + image['fullSizeInfo']['imageUrl'])) else: - print 'No images/videos were found.' + print('No images/videos were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/misc/get_all_images_and_videos.py b/examples/adwords/v201809/misc/get_all_images_and_videos.py index b8f0b7e4..dcafecb8 100755 --- a/examples/adwords/v201809/misc/get_all_images_and_videos.py +++ b/examples/adwords/v201809/misc/get_all_images_and_videos.py @@ -63,16 +63,16 @@ def main(client): except AttributeError: dimensions = {'FULL': {'height': 0, 'width': 0}} if image['type'] == 'IMAGE': - print ('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' - ' was found.' % (image['type'], image['mediaId'], - dimensions['FULL']['height'], - dimensions['FULL']['width'], - image['mimeType'])) + print('%s with id "%s", dimensions \'%sx%s\', and MimeType "%s"' + ' was found.' % (image['type'], image['mediaId'], + dimensions['FULL']['height'], + dimensions['FULL']['width'], + image['mimeType'])) elif image['type'] == 'VIDEO': - print ('%s with id "%s" was found.' % (image['type'], - image['mediaId'])) + print('%s with id "%s" was found.' % (image['type'], + image['mediaId'])) else: - print 'No images/videos were found.' + print('No images/videos were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/misc/upload_image.py b/examples/adwords/v201809/misc/upload_image.py index 72f97c7e..efa8991e 100755 --- a/examples/adwords/v201809/misc/upload_image.py +++ b/examples/adwords/v201809/misc/upload_image.py @@ -51,11 +51,11 @@ def main(client, image_filename): if media: dimensions = dict([(entry['key'], entry['value']) for entry in media['dimensions']]) - print ('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' - ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], - dimensions['FULL']['width'], media['mimeType'])) + print('Image with id "%s", dimensions \'%sx%s\', and MimeType "%s" was' + ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'], + dimensions['FULL']['width'], media['mimeType'])) else: - print 'No images were uploaded.' + print('No images were uploaded.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/misc/upload_image_asset.py b/examples/adwords/v201809/misc/upload_image_asset.py index 70a89954..f3bd0b2f 100755 --- a/examples/adwords/v201809/misc/upload_image_asset.py +++ b/examples/adwords/v201809/misc/upload_image_asset.py @@ -54,14 +54,14 @@ def main(client): # Display results. if asset: - print ('Image asset with id %s, name "%s", and status %s was created.\n' - '\tSize is %sx%s and asset URL is %s.' % - (asset['assetId'], asset['assetName'], asset['assetStatus'], - asset['fullSizeInfo']['imageWidth'], - asset['fullSizeInfo']['imageHeight'], - asset['fullSizeInfo']['imageUrl'])) + print('Image asset with id %s, name "%s", and status %s was created.\n' + '\tSize is %sx%s and asset URL is %s.' % + (asset['assetId'], asset['assetName'], asset['assetStatus'], + asset['fullSizeInfo']['imageWidth'], + asset['fullSizeInfo']['imageHeight'], + asset['fullSizeInfo']['imageUrl'])) else: - print 'No images were uploaded.' + print('No images were uploaded.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/misc/upload_media_bundle.py b/examples/adwords/v201809/misc/upload_media_bundle.py index 4ae8f69a..e0bb8fe3 100755 --- a/examples/adwords/v201809/misc/upload_media_bundle.py +++ b/examples/adwords/v201809/misc/upload_media_bundle.py @@ -18,7 +18,8 @@ """ -import urllib2 +from urllib.request import urlopen + from googleads import adwords @@ -47,7 +48,7 @@ def main(client): def GetHTML5ZipFromUrl(url): """Retrieve zip file from the given URL.""" - response = urllib2.urlopen(url) + response = urlopen(url) # Note: The utf-8 decode is for 2to3 Python 3 compatibility. return response.read().decode('utf-8') diff --git a/examples/adwords/v201809/optimization/estimate_keyword_traffic.py b/examples/adwords/v201809/optimization/estimate_keyword_traffic.py index ca399db2..81cff0cb 100755 --- a/examples/adwords/v201809/optimization/estimate_keyword_traffic.py +++ b/examples/adwords/v201809/optimization/estimate_keyword_traffic.py @@ -149,9 +149,9 @@ def DisplayEstimate(message, min_estimate, max_estimate): Args: message: str message to display for the given estimate. - min_estimate: sudsobject containing a minimum estimate from the + min_estimate: zeep.objects.StatsEstimate containing a minimum estimate from the TrafficEstimatorService response. - max_estimate: sudsobject containing a maximum estimate from the + max_estimate: zeep.objects.StatsEstimate containing a maximum estimate from the TrafficEstimatorService response. """ # Find the mean of the min and max values. @@ -168,11 +168,11 @@ def DisplayEstimate(message, min_estimate, max_estimate): mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], max_estimate['totalCost']['microAmount']) - print message - print ' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc) - print ' Estimated ad position: %s' % _FormatMean(mean_avg_pos) - print ' Estimated daily clicks: %s' % _FormatMean(mean_clicks) - print ' Estimated daily cost: %s' % _FormatMean(mean_total_cost) + print(message) + print(' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc)) + print(' Estimated ad position: %s' % _FormatMean(mean_avg_pos)) + print(' Estimated daily clicks: %s' % _FormatMean(mean_clicks)) + print(' Estimated daily cost: %s' % _FormatMean(mean_total_cost)) if __name__ == '__main__': diff --git a/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py b/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py index 0830076c..b8ae8328 100755 --- a/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py +++ b/examples/adwords/v201809/optimization/get_campaign_criterion_bid_modifier_simulations.py @@ -63,25 +63,25 @@ def main(client, campaign_id): if 'entries' in page: for bid_modifier_landscape in page['entries']: num_landscape_points = 0 - print ('Found campaign-level criterion bid modifier landscapes for ' - 'criterion with ID "%d", start date "%s", end date "%s", and ' - 'landscape points:') % (bid_modifier_landscape['criterionId'], - bid_modifier_landscape['startDate'], - bid_modifier_landscape['endDate']) + print('Found campaign-level criterion bid modifier landscapes for ' + 'criterion with ID "%d", start date "%s", end date "%s", and ' + 'landscape points:') % (bid_modifier_landscape['criterionId'], + bid_modifier_landscape['startDate'], + bid_modifier_landscape['endDate']) for landscape_point in bid_modifier_landscape['landscapePoints']: num_landscape_points += 1 - print ('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' - 'total clicks: %d, total cost: %d, total impressions: %d, ' - 'and required budget: %f') % ( - landscape_point['bidModifier'], landscape_point['clicks'], - landscape_point['cost']['microAmount'], - landscape_point['impressions'], - landscape_point['totalLocalClicks'], - landscape_point['totalLocalCost']['microAmount'], - landscape_point['totalLocalImpressions'], - landscape_point['requiredBudget']['microAmount']) + print('\tbid modifier: %f, clicks: %d, cost: %d, impressions: %d, ' + 'total clicks: %d, total cost: %d, total impressions: %d, ' + 'and required budget: %f') % ( + landscape_point['bidModifier'], landscape_point['clicks'], + landscape_point['cost']['microAmount'], + landscape_point['impressions'], + landscape_point['totalLocalClicks'], + landscape_point['totalLocalCost']['microAmount'], + landscape_point['totalLocalImpressions'], + landscape_point['requiredBudget']['microAmount']) else: - print 'No bid modifier landscapes found.' + print('No bid modifier landscapes found.') # Need to increment by the total # of landscape points within the page, # NOT the number of entries (bid landscapes) in the page. diff --git a/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py b/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py index a92bb69d..a61f7e97 100755 --- a/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py +++ b/examples/adwords/v201809/optimization/get_keyword_bid_simulations.py @@ -54,19 +54,19 @@ def main(client, ad_group_id, criterion_id): if page and 'entries' in page: entries = page['entries'] - print 'Bid landscape(s) retrieved: %d.' % len(entries) + print('Bid landscape(s) retrieved: %d.' % len(entries)) for bid_landscape in entries: - print ('Retrieved keyword bid landscape with ad group ID "%d", ' - 'keyword ID "%d", start date "%s", end date "%s", ' - 'with landscape points:' % ( - bid_landscape['adGroupId'], bid_landscape['criterionId'], - bid_landscape['startDate'], bid_landscape['endDate'])) + print('Retrieved keyword bid landscape with ad group ID "%d", ' + 'keyword ID "%d", start date "%s", end date "%s", ' + 'with landscape points:' % ( + bid_landscape['adGroupId'], bid_landscape['criterionId'], + bid_landscape['startDate'], bid_landscape['endDate'])) for bid_landscape_point in bid_landscape['landscapePoints']: - print (' bid: %s => clicks: %s, cost: %s, impressions: %s, ' - 'biddable conversions: %.2f, ' - 'biddable conversions value: %.2f' - % (bid_landscape_point['bid']['microAmount'], + print(' bid: %s => clicks: %s, cost: %s, impressions: %s, ' + 'biddable conversions: %.2f, ' + 'biddable conversions value: %.2f' + % (bid_landscape_point['bid']['microAmount'], bid_landscape_point['clicks'], bid_landscape_point['cost']['microAmount'], bid_landscape_point['impressions'], diff --git a/examples/adwords/v201809/optimization/get_keyword_ideas.py b/examples/adwords/v201809/optimization/get_keyword_ideas.py index 38463669..a2294a3b 100755 --- a/examples/adwords/v201809/optimization/get_keyword_ideas.py +++ b/examples/adwords/v201809/optimization/get_keyword_ideas.py @@ -93,14 +93,14 @@ def main(client, ad_group_id=None): for attribute in result['data']: attributes[attribute['key']] = getattr( attribute['value'], 'value', '0') - print ('Keyword with "%s" text and average monthly search volume ' - '"%s" was found with Products and Services categories: %s.' - % (attributes['KEYWORD_TEXT'], + print('Keyword with "%s" text and average monthly search volume ' + '"%s" was found with Products and Services categories: %s.' + % (attributes['KEYWORD_TEXT'], attributes['SEARCH_VOLUME'], attributes['CATEGORY_PRODUCTS_AND_SERVICES'])) print else: - print 'No related keywords were found.' + print('No related keywords were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/remarketing/add_audience.py b/examples/adwords/v201809/remarketing/add_audience.py index faf20976..df986e15 100755 --- a/examples/adwords/v201809/remarketing/add_audience.py +++ b/examples/adwords/v201809/remarketing/add_audience.py @@ -84,17 +84,17 @@ def main(client): conversions_map[conversion_tracker['id']] = conversion_tracker for user_list in user_list_result['value']: - print ('User list with name "%s" and ID "%s" was added.' - % (user_list['name'], user_list['id'])) + print('User list with name "%s" and ID "%s" was added.' + % (user_list['name'], user_list['id'])) if user_list['conversionTypes']: for conversion_type in user_list['conversionTypes']: conversion_tracker = conversions_map[conversion_type['id']] - print ('Google global site tag:\n%s\n\n' - % conversion_tracker['googleGlobalSiteTag']) - print ('Google event snippet:\n%s\n\n' - % conversion_tracker['googleEventSnippet']) + print('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) else: - print 'No user lists were added.' + print('No user lists were added.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/remarketing/add_conversion_tracker.py b/examples/adwords/v201809/remarketing/add_conversion_tracker.py index 60918dc0..5dd177b0 100755 --- a/examples/adwords/v201809/remarketing/add_conversion_tracker.py +++ b/examples/adwords/v201809/remarketing/add_conversion_tracker.py @@ -53,10 +53,10 @@ def main(client): # Display results. for conversion_tracker in conversion_trackers['value']: - print ('Conversion tracker with id "%s", name "%s", status "%s" ' - 'and category "%s" was added.\n' % - (conversion_tracker['id'], conversion_tracker['name'], - conversion_tracker['status'], conversion_tracker['category'])) + print('Conversion tracker with id "%s", name "%s", status "%s" ' + 'and category "%s" was added.\n' % + (conversion_tracker['id'], conversion_tracker['name'], + conversion_tracker['status'], conversion_tracker['category'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/remarketing/add_conversion_trackers.py b/examples/adwords/v201809/remarketing/add_conversion_trackers.py index 2f72ea41..892de60d 100755 --- a/examples/adwords/v201809/remarketing/add_conversion_trackers.py +++ b/examples/adwords/v201809/remarketing/add_conversion_trackers.py @@ -82,16 +82,16 @@ def main(client): # Display results. for conversion_tracker in conversion_trackers['value']: - print ('Conversion with ID "%d", name "%s", status "%s", and category ' - '"%s" was added.' - % (conversion_tracker['id'], conversion_tracker['name'], + print('Conversion with ID "%d", name "%s", status "%s", and category ' + '"%s" was added.' + % (conversion_tracker['id'], conversion_tracker['name'], conversion_tracker['status'], conversion_tracker['category'])) if (conversion_tracker['ConversionTracker.Type'] == 'AdWordsConversionTracker'): - print ('Google global site tag:\n%s\n\n' - % conversion_tracker['googleGlobalSiteTag']) - print ('Google event snippet:\n%s\n\n' - % conversion_tracker['googleEventSnippet']) + print('Google global site tag:\n%s\n\n' + % conversion_tracker['googleGlobalSiteTag']) + print('Google event snippet:\n%s\n\n' + % conversion_tracker['googleEventSnippet']) if __name__ == '__main__': diff --git a/examples/adwords/v201809/remarketing/add_crm_based_user_list.py b/examples/adwords/v201809/remarketing/add_crm_based_user_list.py index 6e3dc05b..69ff41ae 100755 --- a/examples/adwords/v201809/remarketing/add_crm_based_user_list.py +++ b/examples/adwords/v201809/remarketing/add_crm_based_user_list.py @@ -82,8 +82,8 @@ def main(client): if 'userLists' in response: for user_list in response['userLists']: - print ('User list with name "%s" and ID "%d" was added.' - % (user_list['name'], user_list['id'])) + print('User list with name "%s" and ID "%d" was added.' + % (user_list['name'], user_list['id'])) def NormalizeAndSHA256(s): diff --git a/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py b/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py index eb8ba3be..3de34401 100755 --- a/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py +++ b/examples/adwords/v201809/remarketing/add_rule_based_user_lists.py @@ -199,11 +199,11 @@ def main(client): # Display results. for user_list in user_lists['value']: - print (('User list added with ID %d, name "%s", status "%s", list type' - ' "%s", accountUserListStatus "%s", description "%s".') % - (user_list['id'], user_list['name'], - user_list['status'], user_list['listType'], - user_list['accountUserListStatus'], user_list['description'])) + print(('User list added with ID %d, name "%s", status "%s", list type' + ' "%s", accountUserListStatus "%s", description "%s".') % + (user_list['id'], user_list['name'], + user_list['status'], user_list['listType'], + user_list['accountUserListStatus'], user_list['description'])) def AddMonths(start_date, months): diff --git a/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py b/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py index dd695cb4..90200f70 100755 --- a/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py +++ b/examples/adwords/v201809/remarketing/upload_conversion_adjustments.py @@ -61,9 +61,9 @@ def main(client, conversion_name, gclid, adjustment_type, conversion_time, new_feed = offline_conversion_response['value'][0] - print ('Uploaded offline conversion adjustment value of "%s" for Google ' - 'Click ID "%s"' % (new_feed['adjustedValue'], - new_feed['googleClickId'])) + print('Uploaded offline conversion adjustment value of "%s" for Google ' + 'Click ID "%s"' % (new_feed['adjustedValue'], + new_feed['googleClickId'])) if __name__ == '__main__': # Initialize client object. diff --git a/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py b/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py index b0b148df..695f91f8 100755 --- a/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py +++ b/examples/adwords/v201809/remarketing/upload_offline_call_conversions.py @@ -63,10 +63,10 @@ def main(client, caller_id, call_start_time, conversion_name, conversion_time, if values: for occ_feed in values: - print ('Uploaded offline call conversion value of "%s" for caller ID ' - '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) + print('Uploaded offline call conversion value of "%s" for caller ID ' + '"%s".\n' % (occ_feed['conversionName'], occ_feed['callerId'])) else: - print 'No offline call conversions were added.' + print('No offline call conversions were added.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/remarketing/upload_offline_conversions.py b/examples/adwords/v201809/remarketing/upload_offline_conversions.py index 0c1b3e3f..cb12d45b 100755 --- a/examples/adwords/v201809/remarketing/upload_offline_conversions.py +++ b/examples/adwords/v201809/remarketing/upload_offline_conversions.py @@ -68,10 +68,10 @@ def main(client, conversion_name, click_id, conversion_time, conversion_value): [offline_conversion_operation]) new_feed = offline_conversion_response['value'] - print ('Uploaded offline conversion value of "%s" for Google Click ID ' - '"%s" to "%s".' % (new_feed['conversionValue'], - new_feed['googleClickId'], - new_feed['conversionName'])) + print('Uploaded offline conversion value of "%s" for Google Click ID ' + '"%s" to "%s".' % (new_feed['conversionValue'], + new_feed['googleClickId'], + new_feed['conversionName'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/remarketing/upload_offline_data.py b/examples/adwords/v201809/remarketing/upload_offline_data.py index b09584bb..ad8522d0 100755 --- a/examples/adwords/v201809/remarketing/upload_offline_data.py +++ b/examples/adwords/v201809/remarketing/upload_offline_data.py @@ -156,13 +156,13 @@ def main(client, conversion_name, external_upload_id, 'operand': offline_data_upload }] - # Upload offline data on the server and print the result. + # Upload offline data on the server and print(the result.) result = offline_data_upload_service.mutate(operations) offline_data_upload = result['value'][0] - print ('Uploaded offline data with external upload ID "%d" and upload status ' - '"%s".' % (offline_data_upload['externalUploadId'], - offline_data_upload['uploadStatus'])) + print('Uploaded offline data with external upload ID "%d" and upload status ' + '"%s".' % (offline_data_upload['externalUploadId'], + offline_data_upload['uploadStatus'])) # Print any partial data errors from the response. if result['partialFailureErrors']: @@ -177,15 +177,15 @@ def main(client, conversion_name, external_upload_id, # field path elements. offline_data_list_index = _GetFieldPathElementIndex( api_error, 'offlineDataList') - print ('Offline data list entry "%d" in operation "%d" with external ' - 'upload ID "%d" and type "%s" has triggered failure for the ' - 'following reason: "%s"' % ( - offline_data_list_index, operation_index, - failed_offline_data_upload['externalUploadId'], - failed_offline_data_upload['uploadType'], - api_error['errorString'])) + print('Offline data list entry "%d" in operation "%d" with external ' + 'upload ID "%d" and type "%s" has triggered failure for the ' + 'following reason: "%s"' % ( + offline_data_list_index, operation_index, + failed_offline_data_upload['externalUploadId'], + failed_offline_data_upload['uploadType'], + api_error['errorString'])) else: - print ('A failure has occurred for the following reason: "%s".' % ( + print('A failure has occurred for the following reason: "%s".' % ( api_error['errorString'])) diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py index 69cf0739..55848c9d 100755 --- a/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py +++ b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_awql.py @@ -51,11 +51,11 @@ def main(client): .During('LAST_7_DAYS') .Build()) - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) + print(report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True)) - # Retrieve the report stream and print it out + # Retrieve the report stream and print(it out) report_data = StringIO.StringIO() stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, 'CSV') @@ -66,7 +66,7 @@ def main(client): if not chunk: break report_data.write(chunk.decode() if sys.version_info[0] == 3 and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() + print(report_data.getvalue()) finally: report_data.close() stream_data.close() diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py index 0536e597..a68b931c 100755 --- a/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py +++ b/examples/adwords/v201809/reporting/download_criteria_report_as_stream_with_selector.py @@ -49,7 +49,7 @@ def main(client): } } - # Retrieve the report stream and print it out + # Retrieve the report stream and print(it out) report_data = StringIO.StringIO() stream_data = report_downloader.DownloadReportAsStream( report, skip_report_header=False, skip_column_header=False, @@ -61,7 +61,7 @@ def main(client): if not chunk: break report_data.write(chunk.decode() if sys.version_info[0] == 3 and getattr(report_data, 'mode', 'w') == 'w' else chunk) - print report_data.getvalue() + print(report_data.getvalue()) finally: report_data.close() stream_data.close() diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py index c997f27f..d32508db 100755 --- a/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py +++ b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_awql.py @@ -46,9 +46,9 @@ def main(client): .During('LAST_7_DAYS') .Build()) - print report_downloader.DownloadReportAsStringWithAwql( - report_query, 'CSV', skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) + print(report_downloader.DownloadReportAsStringWithAwql( + report_query, 'CSV', skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True)) if __name__ == '__main__': diff --git a/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py index 72fd54e2..8a23d63a 100755 --- a/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py +++ b/examples/adwords/v201809/reporting/download_criteria_report_as_string_with_selector.py @@ -45,9 +45,9 @@ def main(client): } # Print out the report as a string - print report_downloader.DownloadReportAsString( - report, skip_report_header=False, skip_column_header=False, - skip_report_summary=False, include_zero_impressions=True) + print(report_downloader.DownloadReportAsString( + report, skip_report_header=False, skip_column_header=False, + skip_report_summary=False, include_zero_impressions=True)) if __name__ == '__main__': diff --git a/examples/adwords/v201809/reporting/get_report_fields.py b/examples/adwords/v201809/reporting/get_report_fields.py index 209826c7..2356af46 100755 --- a/examples/adwords/v201809/reporting/get_report_fields.py +++ b/examples/adwords/v201809/reporting/get_report_fields.py @@ -38,11 +38,11 @@ def main(client, report_type): fields = report_definition_service.getReportFields(report_type) # Display results. - print 'Report type "%s" contains the following fields:' % report_type + print('Report type "%s" contains the following fields:' % report_type) for field in fields: - print ' - %s (%s)' % (field['fieldName'], field['fieldType']) + print(' - %s (%s)' % (field['fieldName'], field['fieldType'])) if 'enumValues' in field: - print ' := [%s]' % ', '.join(field['enumValues']) + print(' := [%s]' % ', '.join(field['enumValues'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/reporting/parallel_report_download.py b/examples/adwords/v201809/reporting/parallel_report_download.py index e9193f98..4b28e930 100755 --- a/examples/adwords/v201809/reporting/parallel_report_download.py +++ b/examples/adwords/v201809/reporting/parallel_report_download.py @@ -73,8 +73,8 @@ def _DownloadReport(process_id, report_download_directory, customer_id, retry_count = 0 while True: - print ('[%d/%d] Loading report for customer ID "%s" into "%s"...' - % (process_id, retry_count, customer_id, filepath)) + print('[%d/%d] Loading report for customer ID "%s" into "%s"...' + % (process_id, retry_count, customer_id, filepath)) try: with open(filepath, 'wb') as handler: report_downloader.DownloadReport( @@ -85,8 +85,8 @@ def _DownloadReport(process_id, report_download_directory, customer_id, if e.code == 500 and retry_count < MAX_RETRIES: time.sleep(retry_count * BACKOFF_FACTOR) else: - print ('Report failed for customer ID "%s" with code "%d" after "%d" ' - 'retries.' % (customer_id, e.code, retry_count+1)) + print('Report failed for customer ID "%s" with code "%d" after "%d" ' + 'retries.' % (customer_id, e.code, retry_count+1)) return (False, {'customerId': customer_id, 'code': e.code, 'message': e.message}) @@ -207,7 +207,7 @@ def main(client, report_download_directory): queue_size = input_queue.qsize() num_processes = min(queue_size, MAX_PROCESSES) - print 'Retrieving %d reports with %d processes:' % (queue_size, num_processes) + print('Retrieving %d reports with %d processes:' % (queue_size, num_processes)) # Start all the processes. processes = [ReportWorker(report_download_directory, @@ -221,22 +221,22 @@ def main(client, report_download_directory): for process in processes: process.join() - print 'Finished downloading reports with the following results:' + print('Finished downloading reports with the following results:') while True: try: success = reports_succeeded.get(timeout=0.01) except Empty: break - print '\tReport for CustomerId "%d" succeeded.' % success['customerId'] + print('\tReport for CustomerId "%d" succeeded.' % success['customerId']) while True: try: failure = reports_failed.get(timeout=0.01) except Empty: break - print ('\tReport for CustomerId "%d" failed with error code "%s" and ' - 'message: %s.' % (failure['customerId'], failure['code'], - failure['message'])) + print('\tReport for CustomerId "%d" failed with error code "%s" and ' + 'message: %s.' % (failure['customerId'], failure['code'], + failure['message'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/reporting/stream_criteria_report_results.py b/examples/adwords/v201809/reporting/stream_criteria_report_results.py index 3884cbaf..a6186b10 100755 --- a/examples/adwords/v201809/reporting/stream_criteria_report_results.py +++ b/examples/adwords/v201809/reporting/stream_criteria_report_results.py @@ -53,9 +53,9 @@ def main(client): finally: stream.close() - print 'Total impressions by ad network type 1:' + print('Total impressions by ad network type 1:') for ad_network_type, impressions in sorted(ad_network_map.iteritems()): - print '%s: %s' % (ad_network_type, impressions) + print('%s: %s' % (ad_network_type, impressions)) def process_line(line, ad_network_map): diff --git a/examples/adwords/v201809/shopping/add_product_partition_tree.py b/examples/adwords/v201809/shopping/add_product_partition_tree.py index d66f135f..f377911f 100755 --- a/examples/adwords/v201809/shopping/add_product_partition_tree.py +++ b/examples/adwords/v201809/shopping/add_product_partition_tree.py @@ -265,8 +265,8 @@ def DisplayTree(node, children, level=0): else: value = (case_value['value'] if 'value' in case_value else 'OTHER') - print ('%sid: %s, node_type: %s, value: %s\n' - % (' ' * level, node['id'], node_type, value)) + print('%sid: %s, node_type: %s, value: %s\n' + % (' ' * level, node['id'], node_type, value)) for child_node in children[node['id']]: DisplayTree(child_node, children, level + 1) diff --git a/examples/adwords/v201809/shopping/add_product_scope.py b/examples/adwords/v201809/shopping/add_product_scope.py index 9065d558..fb496782 100755 --- a/examples/adwords/v201809/shopping/add_product_scope.py +++ b/examples/adwords/v201809/shopping/add_product_scope.py @@ -93,8 +93,8 @@ def main(client, campaign_id): result = campaign_criterion_service.mutate(operations) for criterion in result['value']: - print ('Created a ProductScope criterion with Id: %s' - % criterion['criterion']['id']) + print('Created a ProductScope criterion with Id: %s' + % criterion['criterion']['id']) if __name__ == '__main__': diff --git a/examples/adwords/v201809/shopping/add_shopping_campaign.py b/examples/adwords/v201809/shopping/add_shopping_campaign.py index b6e6afe1..eb01867c 100755 --- a/examples/adwords/v201809/shopping/add_shopping_campaign.py +++ b/examples/adwords/v201809/shopping/add_shopping_campaign.py @@ -79,8 +79,8 @@ def main(client, budget_id, merchant_id, create_default_partition): result = campaign_service.mutate(campaign_operations) for campaign in result['value']: - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) + print('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) # Create the AdGroup ad_group = { @@ -97,8 +97,8 @@ def main(client, budget_id, merchant_id, create_default_partition): ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] ad_group_id = ad_group['id'] - print ('AdGroup with name "%s" and ID "%s" was added.' - % (ad_group['name'], ad_group_id)) + print('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) # Create an AdGroup Ad adgroup_ad = { @@ -119,7 +119,7 @@ def main(client, budget_id, merchant_id, create_default_partition): ad_result = ad_group_ad_service.mutate([ad_operation]) for adgroup_ad in ad_result['value']: - print 'ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id'] + print('ProductAd with ID "%s" was added.' % adgroup_ad['ad']['id']) if create_default_partition: CreateDefaultPartition(client, ad_group_id) @@ -160,8 +160,8 @@ def CreateDefaultPartition(client, ad_group_id): ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] - print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' - % (ad_group_criterion['criterion']['id'], + print('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], ad_group_criterion['adGroupId'])) diff --git a/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py index 0f1f88f8..9875c72d 100755 --- a/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py +++ b/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py @@ -173,9 +173,9 @@ def main(client, budget_id, merchant_id, expanded_image_filepath, collapsed_image_filepath) product_partition_tree = CreateProductPartition(client, adgroup['id']) - print 'Final tree:\n%s' % product_partition_tree + print('Final tree:\n%s' % product_partition_tree) except errors.GoogleAdsServerFault: - print 'Failed to create shopping campaign for showcase ads.' + print('Failed to create shopping campaign for showcase ads.') raise @@ -190,7 +190,7 @@ def CreateShoppingCampaign(client, budget_id, merchant_id): shopping campaign. Returns: - The created Shopping Campaign as a sudsobject. + The created Shopping Campaign as a zeep.objects.Campaign. """ campaign_service = client.GetService('CampaignService', 'v201809') @@ -228,8 +228,8 @@ def CreateShoppingCampaign(client, budget_id, merchant_id): }] campaign = campaign_service.mutate(campaign_operations)['value'][0] - print ('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) + print('Campaign with name "%s" and ID "%s" was added.' + % (campaign['name'], campaign['id'])) return campaign @@ -242,7 +242,7 @@ def CreateAdGroup(client, campaign_id): campaign_id: the str ID of a shopping campaign. Returns: - The created AdGroup as a sudsobject. + The created AdGroup as a zeep.objects.AdGroup. """ ad_group_service = client.GetService('AdGroupService', 'v201809') @@ -273,8 +273,8 @@ def CreateAdGroup(client, campaign_id): # Make the mutate request to add the AdGroup to the Shopping Campaign adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] - print ('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) + print('AdGroup with name "%s" and ID "%s" was added.' + % (adgroup['name'], adgroup['id'])) return adgroup @@ -285,14 +285,14 @@ def CreateShowcaseAd(client, adgroup, expanded_image_filepath, Args: client: an AdWordsClient instance. - adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. + adgroup: a dict or zeep object defining an AdGroup for a Shopping Campaign. expanded_image_filepath: a str filepath to a .jpg file that will be used as the Showcase Ad's expandedImage. collapsed_image_filepath: a str filepath to a .jpg file that will be used as the Showcase Ad's collapsedImage. Returns: - The created Showcase Ad as a sudsobject. + The created Showcase Ad as a zeep.objects.Ad. """ ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809') @@ -325,7 +325,7 @@ def CreateShowcaseAd(client, adgroup, expanded_image_filepath, # Make the mutate request to add the ProductAd to the AdGroup showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] - print 'ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id'] + print('ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id']) return showcase_ad @@ -338,7 +338,7 @@ def UploadImage(client, filepath): filepath: a str filepath to the .jpg file to be uploaded. Returns: - The created Image as a sudsobject. + The created Image as a zeep.objects.Image. """ media_service = client.GetService('MediaService', 'v201809') @@ -364,7 +364,7 @@ def CreateProductPartition(client, adgroup_id): adgroup_id: a str AdGroup ID. Returns: - The ProductPartition tree as a sudsobject. + The ProductPartition tree as a zeep.objects.ProductPartition. """ ad_group_criterion_service = client.GetService('AdGroupCriterionService', 'v201809') diff --git a/examples/adwords/v201809/shopping/add_smart_shopping_ad.py b/examples/adwords/v201809/shopping/add_smart_shopping_ad.py index 4272699c..ee740c77 100755 --- a/examples/adwords/v201809/shopping/add_smart_shopping_ad.py +++ b/examples/adwords/v201809/shopping/add_smart_shopping_ad.py @@ -123,8 +123,8 @@ def CreateSmartCampaign(client, budget_id, merchant_id): result = campaign_service.mutate(campaign_operations)['value'][0] - print ('Smart Shopping campaign with name "%s" and ID "%s" was added.' - % (result['name'], result['id'])) + print('Smart Shopping campaign with name "%s" and ID "%s" was added.' + % (result['name'], result['id'])) return result['id'] @@ -156,8 +156,8 @@ def CreateSmartShoppingAdGroup(client, campaign_id): ad_group = ad_group_service.mutate(adgroup_operations)['value'][0] ad_group_id = ad_group['id'] - print ('AdGroup with name "%s" and ID "%s" was added.' - % (ad_group['name'], ad_group_id)) + print('AdGroup with name "%s" and ID "%s" was added.' + % (ad_group['name'], ad_group_id)) return ad_group_id @@ -188,7 +188,7 @@ def CreateSmartShoppingAd(client, ad_group_id): ad_result = ad_group_ad_service.mutate([ad_operation]) for adgroup_ad in ad_result['value']: - print 'Smart Shopping ad with ID "%s" was added.' % adgroup_ad['ad']['id'] + print('Smart Shopping ad with ID "%s" was added.' % adgroup_ad['ad']['id']) def CreateDefaultPartition(client, ad_group_id): @@ -218,8 +218,8 @@ def CreateDefaultPartition(client, ad_group_id): ad_group_criterion = ad_group_criterion_service.mutate(operations)['value'][0] - print ('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' - % (ad_group_criterion['criterion']['id'], + print('Ad group criterion with ID "%d" in ad group with ID "%d" was added.' + % (ad_group_criterion['criterion']['id'], ad_group_criterion['adGroupId'])) diff --git a/examples/adwords/v201809/shopping/get_product_category_taxonomy.py b/examples/adwords/v201809/shopping/get_product_category_taxonomy.py index f6922afe..72269e34 100755 --- a/examples/adwords/v201809/shopping/get_product_category_taxonomy.py +++ b/examples/adwords/v201809/shopping/get_product_category_taxonomy.py @@ -82,7 +82,7 @@ def main(client): def DisplayCategories(categories, prefix=''): for category in categories: - print '%s%s [%s]' % (prefix, category['name'], category['id']) + print('%s%s [%s]' % (prefix, category['name'], category['id'])) if 'children' in category: DisplayCategories(category['children'], '%s%s > ' % (prefix, diff --git a/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py b/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py index 0a125bdd..1a6bf2ae 100755 --- a/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py +++ b/examples/adwords/v201809/targeting/add_campaign_targeting_criteria.py @@ -113,9 +113,9 @@ def main(client, campaign_id, location_feed_id=None): # Display the resulting campaign criteria. for campaign_criterion in result['value']: - print ('Campaign criterion with campaign id "%s", criterion id "%s", ' - 'and type "%s" was added.' - % (campaign_criterion['campaignId'], + print('Campaign criterion with campaign id "%s", criterion id "%s", ' + 'and type "%s" was added.' + % (campaign_criterion['campaignId'], campaign_criterion['criterion']['id'], campaign_criterion['criterion']['type'])) diff --git a/examples/adwords/v201809/targeting/add_customer_negative_criteria.py b/examples/adwords/v201809/targeting/add_customer_negative_criteria.py index 17636501..b69d71c8 100755 --- a/examples/adwords/v201809/targeting/add_customer_negative_criteria.py +++ b/examples/adwords/v201809/targeting/add_customer_negative_criteria.py @@ -62,9 +62,9 @@ def main(client): # Display the resulting campaign criteria. for negative_criterion in result['value']: - print ('Customer negative criterion with criterion ID "%s", and type "%s" ' - 'was added.' % (negative_criterion['criterion']['id'], - negative_criterion['criterion']['type'])) + print('Customer negative criterion with criterion ID "%s", and type "%s" ' + 'was added.' % (negative_criterion['criterion']['id'], + negative_criterion['criterion']['type'])) if __name__ == '__main__': diff --git a/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py b/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py index d3abdfa2..101495e7 100755 --- a/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py +++ b/examples/adwords/v201809/targeting/add_demographic_targeting_criteria.py @@ -81,12 +81,12 @@ def main(client, ad_group_id): criteria = response['value'] for ad_group_criterion in criteria: criterion = ad_group_criterion['criterion'] - print ('Ad group criterion with ad group ID %s, criterion ID %s and ' - 'type "%s" was added.' % - (ad_group_criterion['adGroupId'], criterion['id'], - criterion['type'])) + print('Ad group criterion with ad group ID %s, criterion ID %s and ' + 'type "%s" was added.' % + (ad_group_criterion['adGroupId'], criterion['id'], + criterion['type'])) else: - print 'No criteria were returned.' + print('No criteria were returned.') if __name__ == '__main__': diff --git a/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py b/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py index 0c19811c..0e80b412 100755 --- a/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py +++ b/examples/adwords/v201809/targeting/get_campaign_targeting_criteria.py @@ -68,11 +68,11 @@ def main(client): else criterion['name'] if 'name' in criterion else criterion['locationName'] if 'locationName' in criterion else None) - print ('%sCampaign Criterion found for Campaign ID %s with type %s and ' - 'criteria "%s".' % (negative, campaign_criterion['campaignId'], - criterion['type'], criteria)) + print('%sCampaign Criterion found for Campaign ID %s with type %s and ' + 'criteria "%s".' % (negative, campaign_criterion['campaignId'], + criterion['type'], criteria)) else: - print 'No campaign targets were found.' + print('No campaign targets were found.') offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) diff --git a/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py b/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py index 7bd17fcf..f5f7c519 100755 --- a/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py +++ b/examples/adwords/v201809/targeting/get_targetable_languages_and_carriers.py @@ -36,18 +36,18 @@ def main(client): # Display results. for language in languages: - print ('Language with name "%s" and ID "%s" was found.' - % (language['name'], language['id'])) + print('Language with name "%s" and ID "%s" was found.' + % (language['name'], language['id'])) # Get all carriers. carriers = constant_data_service.getCarrierCriterion() # Display results. for carrier in carriers: - print ('Carrier with name "%s", ID "%s", and country code "%s" was ' - 'found.' % ( - carrier['name'], carrier['id'], - getattr(carrier, 'countryCode', 'N/A'))) + print('Carrier with name "%s", ID "%s", and country code "%s" was ' + 'found.' % ( + carrier['name'], carrier['id'], + getattr(carrier, 'countryCode', 'N/A'))) if __name__ == '__main__': diff --git a/examples/adwords/v201809/targeting/lookup_location.py b/examples/adwords/v201809/targeting/lookup_location.py index 046c1612..0270526d 100755 --- a/examples/adwords/v201809/targeting/lookup_location.py +++ b/examples/adwords/v201809/targeting/lookup_location.py @@ -64,9 +64,9 @@ def main(client): parent_string = ', '.join([GetLocationString(parent)for parent in location_criterion['location'] ['parentLocations']]) - print ('The search term "%s" returned the location "%s" of type "%s"' - ' with parent locations "%s", reach "%s" and id "%s" (%s)' - % (location_criterion['searchTerm'], + print('The search term "%s" returned the location "%s" of type "%s"' + ' with parent locations "%s", reach "%s" and id "%s" (%s)' + % (location_criterion['searchTerm'], location_criterion['location']['locationName'], location_criterion['location']['displayType'], parent_string, location_criterion['reach'] diff --git a/googleads.yaml b/googleads.yaml index 202bd0ae..62f60c44 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -116,13 +116,6 @@ ad_manager: ################################################################################ # include_utilities_in_user_agent: True ################################################################################ -# SOAP implementation (optional) # -# Specify which SOAP implementation to use. This library currently supports # -# suds and zeep. Zeep is more modern, and is the default, if you have any # -# issues please report them and fall back to suds. # -################################################################################ -# soap_impl: zeep -################################################################################ # Custom HTTP headers (optional) # # Specify one or more custom headers to pass along with all requests to # # the API. # diff --git a/googleads/__init__.py b/googleads/__init__.py index 63f5b65d..78b5fa78 100644 --- a/googleads/__init__.py +++ b/googleads/__init__.py @@ -14,5 +14,5 @@ """A client library for Google's SOAP Ads APIs.""" -from ad_manager import AdManagerClient -from adwords import AdWordsClient +from .ad_manager import AdManagerClient +from .adwords import AdWordsClient diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index d1516b37..56666d53 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -22,7 +22,7 @@ import os import sys import time -import urllib2 +from urllib.request import build_opener import pytz import googleads.common @@ -205,7 +205,7 @@ def LoadFromStorage(cls, path=None): cls._OPTIONAL_INIT_VALUES)) def __init__(self, oauth2_client, application_name, network_code=None, - cache=None, proxy_config=None, soap_impl='zeep', timeout=3600, + cache=None, proxy_config=None, timeout=3600, custom_http_headers=None, enable_compression=False): """Initializes a AdManagerClient. @@ -222,13 +222,11 @@ def __init__(self, oauth2_client, application_name, network_code=None, network_code: A string identifying the network code of the network you are accessing. All requests other than getAllNetworks require this header to be set. - cache: A subclass of zeep.cache.Base or suds.cache.Cache. If not set, + cache: A subclass of zeep.cache.Base. If not set, this will default to a basic file cache. To disable caching for Zeep, pass googleads.common.ZeepServiceProxy.NO_CACHE. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. - soap_impl: A string identifying which SOAP implementation to use. The - options are 'zeep' or 'suds'. timeout: An integer timeout in MS for connections made to Ad Manager. custom_http_headers: A dictionary with HTTP headers to add to outgoing requests. @@ -256,7 +254,6 @@ def __init__(self, oauth2_client, application_name, network_code=None, if enable_compression: self.application_name = '%s (gzip)' % self.application_name - self.soap_impl = soap_impl self.timeout = timeout @@ -287,7 +284,7 @@ def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server = server[:-1] if server[-1] == '/' else server try: - service = googleads.common.GetServiceClassForLibrary(self.soap_impl)( + service = googleads.common.GetServiceClassForLibrary()( self._SOAP_SERVICE_FORMAT % (server, version, service_name), self._header_handler, _AdManagerPacker, @@ -650,7 +647,7 @@ def GetQueryValuesFromDict(cls, d, version=sorted(_SERVICE_MAP.keys())[-1]): return [{ 'key': key, 'value': cls.GetValueRepresentation(value, version) - } for key, value in d.iteritems()] + } for key, value in d.items()] @classmethod def GetValueRepresentation(cls, value, @@ -668,7 +665,7 @@ def GetValueRepresentation(cls, value, The value formatted for PQL statements which are compatible with a particular API version. """ - if isinstance(value, str) or isinstance(value, unicode): + if isinstance(value, str): return {'value': value, 'xsi_type': 'TextValue'} elif isinstance(value, bool): return {'value': value, 'xsi_type': 'BooleanValue'} @@ -763,7 +760,9 @@ def __init__(self, ad_manager_client, version=sorted(_SERVICE_MAP.keys())[-1], if not server: server = DEFAULT_ENDPOINT - if server[-1] == '/': server = server[:-1] + if server[-1] == '/': + server = server[:-1] + self._ad_manager_client = ad_manager_client self._version = version self._server = server @@ -771,7 +770,8 @@ def __init__(self, ad_manager_client, version=sorted(_SERVICE_MAP.keys())[-1], self._pql_service = None self.proxy_config = self._ad_manager_client.proxy_config handlers = self.proxy_config.GetHandlers() - self.url_opener = urllib2.build_opener(*handlers) + self.url_opener = build_opener(*handlers) + if self._ad_manager_client.custom_http_headers: self.url_opener.addheaders.extend( self._ad_manager_client.custom_http_headers.items()) @@ -1026,10 +1026,10 @@ def _ConvertDateTimeToOffset(self, date_time_value): def AdManagerClassType(value): - """Returns the class type for the Suds object. + """Returns the class type for an object. Args: - value: generic Suds object to return type for. + value: generic object to return type for. Returns: str: A string representation of the value response type. diff --git a/googleads/adwords.py b/googleads/adwords.py index 04df0daf..415bdec4 100644 --- a/googleads/adwords.py +++ b/googleads/adwords.py @@ -22,13 +22,14 @@ import os import re import sys -import urllib -import urllib2 +import io +from urllib.request import Request, build_opener +from urllib.parse import urlencode +from urllib.error import HTTPError from xml.etree import ElementTree import googleads.common import googleads.errors -import six import xmltodict import yaml @@ -192,8 +193,7 @@ def LoadFromStorage(cls, path=None): cls._OPTIONAL_INIT_VALUES)) def __init__(self, developer_token, oauth2_client, - user_agent=_DEFAULT_USER_AGENT, soap_impl='zeep', - timeout=3600, **kwargs): + user_agent=_DEFAULT_USER_AGENT, timeout=3600, **kwargs): """Initializes an AdWordsClient. For more information on these arguments, see our SOAP headers guide: @@ -206,8 +206,6 @@ def __init__(self, developer_token, oauth2_client, user_agent: An arbitrary string containing only ASCII characters that will be used to identify your application. If not set, this will default to the string value "unknown". - soap_impl: A string identifying which SOAP implementation to use. The - options are 'zeep' or 'suds'. timeout: An integer time in MS to time out connections to AdWords. **kwargs: Optional keyword arguments. @@ -223,9 +221,9 @@ def __init__(self, developer_token, oauth2_client, succeed, to result in a complete failure with no changes made or a partial failure with some changes made. Only certain services respect this header. - cache: A subclass of zeep.cache.Base or suds.cache.Cache. If not set, - this will default to a basic file cache. To disable caching for Zeep, - pass googleads.common.ZeepServiceProxy.NO_CACHE. + cache: A subclass of zeep.cache.Base. If not set, this will default to a + basic file cache. To disable caching for Zeep, pass + googleads.common.ZeepServiceProxy.NO_CACHE. proxy_config: A googleads.common.ProxyConfig instance or None if a proxy isn't being used. report_downloader_headers: A dict containing optional headers to be used @@ -244,11 +242,9 @@ def __init__(self, developer_token, oauth2_client, self.oauth2_client = oauth2_client self.client_customer_id = kwargs.get('client_customer_id') self.user_agent = user_agent - self.soap_impl = soap_impl self.custom_http_headers = kwargs.get('custom_http_headers') - # Verify that the provided user_agent contains only ASCII characters. In - # both Python 2 and Python 3, a UnicodeEncodeError will be raised if it - # contains a non-ASCII character. + # Verify that the provided user_agent contains only ASCII characters. A + # UnicodeEncodeError will be raised if it contains a non-ASCII character. try: self.user_agent.encode('ascii') except UnicodeEncodeError: @@ -267,7 +263,6 @@ def __init__(self, developer_token, oauth2_client, if self.enable_compression: self.user_agent = '%s (gzip)' % self.user_agent - self.message_plugin = googleads.common.LoggingMessagePlugin() self.timeout = timeout def GetService(self, service_name, version=None, server=None): @@ -308,7 +303,7 @@ def GetService(self, service_name, version=None, server=None): raise googleads.errors.GoogleAdsValueError( msg_fmt % ('version', version, _SERVICE_MAP.keys())) - service = googleads.common.GetServiceClassForLibrary(self.soap_impl)( + service = googleads.common.GetServiceClassForLibrary()( self._SOAP_SERVICE_FORMAT % ( server, version_service_mapping, version, service_name), _AdWordsHeaderHandler( @@ -575,7 +570,7 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): **kwargs: optional keyword arguments. Returns: - A urllib2.Request instance with the correct method, headers, and + A urllib.request.Request instance with the correct method, headers, and padding (if required) for the batch job upload. """ @@ -693,7 +688,7 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): incremental upload. Returns: - A urllib2.Request instance with the correct method, headers, and + A urllib.request.Request instance with the correct method, headers, and padding (if required) for the batch job upload. """ current_content_length = kwargs.get('current_content_length', 0) @@ -703,7 +698,7 @@ def BuildUploadRequest(self, upload_url, operations, **kwargs): operations, has_prefix=current_content_length == 0, has_suffix=is_last) - req = urllib2.Request(upload_url) + req = Request(upload_url) req.add_header('Content-Type', 'application/xml') # Determine length of this message and the required padding. new_content_length = current_content_length @@ -786,9 +781,7 @@ def _ExtractOperations(self, full_soap_xml): # Ensure operations are formatted correctly for BatchJobService. for operations in method: self._FormatForBatchJobService(operations) - # Extract the operation type, ensure xsi:type is set for - # BatchJobService. Even if xsi_type is set earlier, suds will end up - # removing it when it sets Operation.Type. + # Extract the operation type, ensure xsi:type is set for BatchJobService. operation_type = operations.find('Operation.Type') if operation_type is None: raise googleads.errors.GoogleAdsValueError('No xsi_type specified ' @@ -796,18 +789,14 @@ def _ExtractOperations(self, full_soap_xml): operations.attrib[self.XSI_TYPE_STRING] = operation_type.text operations_xml = ''.join([ElementTree.tostring(operation).decode('utf-8') for operation in method]) - # Force removal of this line, which suds produces. - operations_xml = operations_xml.replace( - 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"', '') return operations_xml def _FormatForBatchJobService(self, element): """Formats contents of all operations for use with the BatchJobService. - This will recursively remove unnecessary namespaces generated by suds that - would prevent the operations from executing via the BatchJobService. It - will also remove namespaces appended to the xsi:type in some cases that - also cause issues for the BatchJobService. + This will recursively remove unnecessary namespaces that would prevent the + operations from executing via the BatchJobService. It will also remove namespaces + appended to the xsi:type in some cases that also cause issues for the BatchJobService. Args: element: a starting Element to be modified to the correct format. @@ -932,9 +921,9 @@ def GetResponseParser(cls, *args, **kwargs): return cls._XMLToDictResponseParser(*args, **kwargs) def ParseResponse(self, batch_job_response): - """Parses a Batch Job Service response and returns it as a suds object. + """Parses a Batch Job Service response and returns it as a zeep object. - Note: Unlike suds objects generated via an API call with suds, type + Note: Unlike zeep objects generated via an API call with zeep, type information will be lost. All values are strings. Args: @@ -942,7 +931,7 @@ def ParseResponse(self, batch_job_response): BatchJobService. Returns: - A suds object response generated from the provided batch_job_response. + A zeep object response generated from the provided batch_job_response. """ return self._response_parser.ParseResponse(batch_job_response) @@ -1026,7 +1015,7 @@ def __init__(self, request_builder, upload_url, current_content_length=0, 'Current content length %s is < 0.' % current_content_length) self._current_content_length = current_content_length self._is_last = is_last - self._url_opener = urllib2.build_opener( + self._url_opener = build_opener( *self._request_builder.client.proxy_config.GetHandlers()) if self._request_builder.client.custom_http_headers: self._url_opener.addheaders.extend( @@ -1057,7 +1046,7 @@ def _InitializeURL(self, upload_url, current_content_length): } # Send an HTTP POST request to the given upload_url - req = urllib2.Request(upload_url, data={}, headers=headers) + req = Request(upload_url, data={}, headers=headers) resp = self._url_opener.open(req) return resp.headers['location'] @@ -1106,8 +1095,8 @@ def UploadOperations(self, operations, is_last=False): req = self._request_builder.BuildUploadRequest( self._upload_url, operations, current_content_length=self._current_content_length, is_last=is_last) - # Make the request, ignoring the urllib2.HTTPError raised due to HTTP status - # code 308 (for resumable uploads). + # Make the request, ignoring the urllib.error.HTTPError raised due to HTTP + # status code 308 (for resumable uploads). try: _batch_job_logger.debug('Outgoing request: %s %s %s', req.get_full_url(), req.headers, req.data) @@ -1117,7 +1106,7 @@ def UploadOperations(self, operations, is_last=False): if _batch_job_logger.isEnabledFor(logging.INFO): _batch_job_logger.info('Request summary: %s', self._ExtractRequestSummaryFields(req)) - except urllib2.HTTPError as e: + except HTTPError as e: if e.code != 308: if _batch_job_logger.isEnabledFor(logging.WARNING): _batch_job_logger.warning( @@ -1132,9 +1121,9 @@ def _ExtractRequestSummaryFields(self, request, error=None): """Extract fields used in the summary logs. Args: - request: a urllib2.Request instance configured to make the request. + request: a urllib.request.Request instance configured to make the request. [optional] - error: a urllib2.HttpError instance used to retrieve error details. + error: a urllib.error.HttpError instance used to retrieve error details. Returns: A dict containing the fields to be output in the summary logs. @@ -1204,14 +1193,13 @@ def __init__(self, adwords_client, version=sorted(_SERVICE_MAP.keys())[-1], self._adwords_client.custom_http_headers) self.proxy_config = self._adwords_client.proxy_config handlers = self.proxy_config.GetHandlers() - self.url_opener = urllib2.build_opener(*handlers) + self.url_opener = build_opener(*handlers) if self._adwords_client.custom_http_headers: self.url_opener.addheaders.extend( adwords_client.custom_http_headers.items()) schema_url = self._SCHEMA_FORMAT % (server, version) - service_class = (googleads.common - .GetSchemaHelperForLibrary(adwords_client.soap_impl)) + service_class = googleads.common.GetSchemaHelperForLibrary() self.schema_helper = service_class( schema_url, self._adwords_client.timeout, self.proxy_config, self._namespace, self._adwords_client.cache) @@ -1220,25 +1208,20 @@ def _DownloadReportCheckFormat(self, file_format, output): """Verifies file format compatibility with given output.""" encoding = getattr(output, 'encoding', None) - # In Python 2 binary file encoding will be set to None, and StringIO / - # BytesIO instances will not have an encoding attribute. In Python 3, - # binary files don't have an encoding attribute, StringIO instances have an - # encoding set to None, and BytesIO instances lack an encoding attribute. - # As a result, if encoding is ever set, it indicates that the specified - # output is incompatible with GZIPPED formats. + # StringIO instances have an encoding set to None, and BytesIO instances + # lack an encoding attribute. As a result, if encoding is ever set, it + # indicates that the specified output is incompatible with GZIPPED formats. if encoding and file_format.startswith('GZIPPED_'): raise googleads.errors.GoogleAdsValueError( 'Need to specify a binary output for GZIPPED formats.') - # Because Python 3 StringIO instances always have encoding set to None, - # it's necessary to verify that StringIO instances aren't used with GZIPPED - # formats. In Python 2, this wouldn't matter because StringIO instances - # store bytes (appropriate for GZIPPED formats) rather than unicode data. - if six.PY3: - if (file_format.startswith('GZIPPED_') - and isinstance(output, six.StringIO)): - raise googleads.errors.GoogleAdsValueError( - 'Need to specify a binary output for GZIPPED formats.') + # Because StringIO instances always have encoding set to None, it's + # necessary to verify that StringIO instances aren't used with GZIPPED + # formats. + if (file_format.startswith('GZIPPED_') + and isinstance(output, io.StringIO)): + raise googleads.errors.GoogleAdsValueError( + 'Need to specify a binary output for GZIPPED formats.') def DownloadReport(self, report_definition, output=sys.stdout, **kwargs): """Downloads an AdWords report using a report definition. @@ -1548,8 +1531,7 @@ def _DownloadReport(self, post_body, output, **kwargs): Raises: AdWordsReportBadRequestError: if the report download fails due to improper input. In the event of certain other failures, a - urllib2.URLError (Python 2) or urllib.error.URLError (Python 3) will be - raised. + urllib.error.URLError will be raised. AdWordsReportError: if the request fails for any other reason; e.g. a network error. """ @@ -1558,7 +1540,7 @@ def _DownloadReport(self, post_body, output, **kwargs): response = self._DownloadReportAsStream(post_body, **kwargs) # Determine encoding of provided output. - if six.PY3 and isinstance(output, six.StringIO): + if isinstance(output, io.StringIO): encoding = 'utf-8' else: encoding = getattr(output, 'encoding', None) @@ -1582,9 +1564,8 @@ def _DownloadReport(self, post_body, output, **kwargs): def _DownloadReportAsStream(self, post_body, **kwargs): """Downloads an AdWords report, returning a stream-like object. - In Python 2, this will return a urllib2.addinfourl instance. In Python 3, - this will return a http.client.HTTPResponse instance. In either case, - reading from the stream-like object will return binary data. + This will return a http.client.HTTPResponse instance, reading from which + will return binary data. Args: post_body: The contents of the POST request's body as a URL encoded @@ -1614,15 +1595,14 @@ def _DownloadReportAsStream(self, post_body, **kwargs): Raises: AdWordsReportBadRequestError: if the report download fails due to improper input. In the event of certain other failures, a - urllib2.URLError (Python 2) or urllib.error.URLError (Python 3) will be - raised. + urllib.error.URLError will be raised. AdWordsReportError: if the request fails for any other reason; e.g. a network error. """ if sys.version_info[0] == 3: post_body = bytes(post_body, 'utf8') - request = urllib2.Request( + request = Request( self._end_point, post_body, self._header_handler.GetReportDownloadHeaders(**kwargs)) try: @@ -1642,7 +1622,7 @@ def _DownloadReportAsStream(self, post_body, **kwargs): self._ExtractResponseHeaders(response.headers), response.code, response.msg) return response - except urllib2.HTTPError as e: + except HTTPError as e: error = self._ExtractError(e) if _report_logger.isEnabledFor(logging.WARNING): _report_logger.warning( @@ -1689,7 +1669,7 @@ def _ExtractRequestSummaryFields(self, request, error=None): """Extract fields used in the summary logs. Args: - request: a urllib2.Request instance. + request: a urllib.request.Request instance. [optional] error: a googleads.errors.AdWordsReportError instance or subclass used to retrieve error details. This should only be present when an error @@ -1732,7 +1712,7 @@ def _SerializeAwql(self, query, file_format): The given query and format URL encoded into the format needed for an AdWords report request as a string. This is intended to be a POST body. """ - return urllib.urlencode({'__fmt': file_format, '__rdquery': str(query)}) + return urlencode({'__fmt': file_format, '__rdquery': str(query)}) def _SerializeReportDefinition(self, report_definition): """Serializes a report definition for transport. @@ -1746,7 +1726,7 @@ def _SerializeReportDefinition(self, report_definition): the format needed for an AdWords report request as a string. This is intended to be a POST body. """ - return urllib.urlencode( + return urlencode( {'__rdxml': self.schema_helper.GetSoapXMLForComplexType( self._REPORT_DEFINITION_NAME, report_definition)}) @@ -1754,7 +1734,7 @@ def _ExtractError(self, error): """Attempts to extract information from a report download error XML message. Args: - error: A urllib2.HTTPError describing the report download failure. + error: A urllib.error.HTTPError describing the report download failure. Returns: An error that should be raised. If the content was an XML error message, @@ -2069,14 +2049,14 @@ def Build(self): def _CreateSingleValueCondition(self, value, operator): """Creates a single-value condition with the provided value and operator.""" - if isinstance(value, str) or isinstance(value, unicode): + if isinstance(value, str): value = '"%s"' % value return '%s %s %s' % (self._field, operator, value) def _CreateMultipleValuesCondition(self, values, operator): """Creates a condition with the provided list of values and operator.""" - values = ['"%s"' % value if isinstance(value, str) or - isinstance(value, unicode) else str(value) for value in values] + values = ['"%s"' % value if isinstance(value, str) else + str(value) for value in values] return '%s %s [%s]' % (self._field, operator, ', '.join(values)) diff --git a/googleads/common.py b/googleads/common.py index 59a67550..78c66c56 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -19,7 +19,6 @@ import binascii from functools import wraps import inspect -from itertools import izip import locale import logging import logging.config @@ -27,19 +26,12 @@ import ssl import sys import threading -import urllib2 import warnings +from urllib.request import HTTPSHandler, ProxyHandler, build_opener import lxml.builder import lxml.etree import requests.exceptions -import suds -import suds.cache -import suds.client -import suds.mx.literal -import suds.plugin -import suds.transport.http -import suds.xsd.doctor import yaml import zeep import zeep.cache @@ -51,22 +43,7 @@ import googleads.oauth2 import googleads.util -try: - import urllib2.HTTPSHandler -except ImportError: - # Python versions below 2.7.9 / 3.4 won't have this. In order to offer legacy - # support (for now) we will work around this gracefully, but users will - # not have certificate validation performed until they update. - pass - - -logging.getLogger('suds.client').addFilter(googleads.util.GetSudsClientFilter()) -logging.getLogger('suds.mx.core').addFilter( - googleads.util.GetSudsMXCoreFilter()) -logging.getLogger('suds.mx.literal').addFilter( - googleads.util.GetSudsMXLiteralFilter()) -logging.getLogger('suds.transport.http').addFilter( - googleads.util.GetSudsTransportFilter()) + _logger = logging.getLogger(__name__) _PY_VERSION_MAJOR = sys.version_info.major @@ -75,10 +52,10 @@ _DEPRECATED_VERSION_TEMPLATE = ( 'This library is being run by an unsupported Python version (%s.%s.%s). In ' 'order to benefit from important security improvements and ensure ' - 'compatibility with this library, upgrade to Python 2.7.9 or higher.') + 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '19.0.1' +VERSION = '20.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' @@ -103,17 +80,11 @@ # A key used to configure the client to send arbitrary headers in SOAP requests. CUSTOM_HEADERS_KEY = 'custom_http_headers' -# A key used to specify the SOAP implementation to use. -SOAP_IMPLEMENTATION_KEY = 'soap_impl' - # Global variables used to enable and store utility usage stats. _utility_registry = googleads.util.UtilityRegistry() _UTILITY_REGISTER_YAML_KEY = 'include_utilities_in_user_agent' _UTILITY_LOCK = threading.Lock() -# Apply any necessary patches to dependency libraries. -googleads.util.PatchHelper().Apply() - def GenerateLibSig(short_name): """Generates a library signature suitable for a user agent field. @@ -140,13 +111,9 @@ class CommonClient(object): def __init__(self): # Warn users on deprecated Python versions on initialization. - if _PY_VERSION_MAJOR == 2: - if _PY_VERSION_MINOR == 7 and _PY_VERSION_MICRO < 9: - _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, - _PY_VERSION_MINOR, _PY_VERSION_MICRO) - elif _PY_VERSION_MINOR < 7: - _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, - _PY_VERSION_MINOR, _PY_VERSION_MICRO) + if _PY_VERSION_MAJOR == 3 and _PY_VERSION_MINOR < 6: + _logger.warning(_DEPRECATED_VERSION_TEMPLATE, _PY_VERSION_MAJOR, + _PY_VERSION_MINOR, _PY_VERSION_MICRO) # Warn users about using non-utf8 encoding _, encoding = locale.getdefaultlocale() @@ -230,9 +197,6 @@ def LoadFromString(yaml_doc, product_yaml_key, required_client_values, client_kwargs[CUSTOM_HEADERS_KEY] = data.get(CUSTOM_HEADERS_KEY, None) - if SOAP_IMPLEMENTATION_KEY in data: - client_kwargs[SOAP_IMPLEMENTATION_KEY] = data[SOAP_IMPLEMENTATION_KEY] - for value in optional_product_values: if value in product_data: client_kwargs[value] = product_data[value] @@ -376,108 +340,6 @@ def _ExtractProxyConfig(product_yaml_key, proxy_config_data): return proxy_config -def _PackForSuds(obj, factory, packer=None, version=None): - """Packs SOAP input into the format we want for suds. - - The main goal here is to pack dictionaries with an 'xsi_type' key into - objects. This allows dictionary syntax to be used even with complex types - extending other complex types. The contents of dictionaries and lists/tuples - are recursively packed. Mutable types are copied - we don't mutate the input. - - Args: - obj: A parameter for a SOAP request which will be packed. If this is - a dictionary or list, the contents will recursively be packed. If this - is not a dictionary or list, the contents will be recursively searched - for instances of unpacked dictionaries or lists. - factory: The suds.client.Factory object which can create instances of the - classes generated from the WSDL. - packer: An optional subclass of googleads.common.SoapPacker that provides - customized packing logic. - version: the version of the current API, e.g. 'v201811' - - Returns: - If the given obj was a dictionary that contained the 'xsi_type' key, this - will be an instance of a class generated from the WSDL. Otherwise, this will - be the same data type as the input obj was. - """ - if packer: - obj = packer.Pack(obj, version) - - if obj in ({}, None): - # Force suds to serialize empty objects. There are legitimate use cases for - # this, for example passing in an empty SearchCriteria object to a DFA - # search method in order to select everything. - return suds.null() - elif isinstance(obj, dict): - if 'xsi_type' in obj: - try: - new_obj = factory.create(obj['xsi_type']) - except suds.TypeNotFound: - new_obj = factory.create(':'.join(['ns0', obj['xsi_type']])) - # Suds sends an empty XML element for enum types which are not set. None - # of Google's Ads APIs will accept this. Initializing all of the fields in - # a suds object to None will ensure that they don't get serialized at all - # unless the user sets a value. User values explicitly set to None will be - # packed into a suds.null() object. - for param, _ in new_obj: - # Another problem is that the suds.mx.appender.ObjectAppender won't - # serialize object types with no fields set, but both AdWords and Ad - # Manager rely on sending objects with just the xsi:type set. The - # below "if" statement is an ugly hack that gets this to work in all(?) - # situations by taking advantage of the fact that these classes - # generally all have a type field. The only other option is to monkey - # patch ObjectAppender. - if param.endswith('.Type'): - setattr(new_obj, param, obj['xsi_type']) - else: - setattr(new_obj, param, None) - for key in obj: - if key == 'xsi_type': continue - setattr(new_obj, key, _PackForSuds(obj[key], factory, - packer=packer)) - else: - new_obj = {} - for key in obj: - new_obj[key] = _PackForSuds(obj[key], factory, - packer=packer) - return new_obj - elif isinstance(obj, (list, tuple)): - return [_PackForSuds(item, factory, - packer=packer) for item in obj] - else: - _RecurseOverObject(obj, factory) - return obj - - -def _RecurseOverObject(obj, factory, parent=None): - """Recurses over a nested structure to look for changes in Suds objects. - - Args: - obj: A parameter for a SOAP request field which is to be inspected and - will be packed for Suds if an xsi_type is specified, otherwise will be - left unaltered. - factory: The suds.client.Factory object which can create instances of the - classes generated from the WSDL. - parent: The parent object that contains the obj parameter to be inspected. - """ - if _IsSudsIterable(obj): - # Since in-place modification of the Suds object is taking place, the - # iterator should be done over a frozen copy of the unpacked fields. - copy_of_obj = tuple(obj) - for item in copy_of_obj: - if _IsSudsIterable(item): - if 'xsi_type' in item: - if isinstance(obj, tuple): - parent[obj[0]] = _PackForSuds(obj[1], factory) - else: - obj.remove(item) - obj.append(_PackForSuds(item, factory)) - _RecurseOverObject(item, factory, obj) - - -def _IsSudsIterable(obj): - """A short helper method to determine if a field is iterable for Suds.""" - return obj and not isinstance(obj, basestring) and hasattr(obj, '__iter__') def IncludeUtilitiesInUserAgent(value): @@ -574,8 +436,7 @@ def __init__(self, http_proxy=None, https_proxy=None, cafile=None, self.disable_certificate_validation = disable_certificate_validation self.cafile = None if disable_certificate_validation else cafile - # Initialize the context used to generate the urllib2.HTTPSHandler (in - # Python 2.7.9+ and 3.4+) used by suds and urllib2. + # Initialize the context used to generate the HTTPSHandler. self.ssl_context = self._InitSSLContext( self.cafile, self.disable_certificate_validation) @@ -594,8 +455,6 @@ def _InitSSLContext(self, cafile=None, An ssl.SSLContext instance, or None if the version of Python being used doesn't support it. """ - # Attempt to create a context; this should succeed in Python 2 versions - # 2.7.9+ and Python 3 versions 3.4+. try: if disable_ssl_certificate_validation: ssl._create_default_https_context = ssl._create_unverified_context @@ -614,44 +473,31 @@ def _InitSSLContext(self, cafile=None, def BuildOpener(self): """Builds an OpenerDirector instance using the ProxyConfig settings. - In Python 2, this will return a urllib2.OpenerDirector instance. In Python - 3, this will return a urllib.request.OpenerDirector instance. + This will return a urllib2.request.OpenerDirector instance. Returns: An OpenerDirector instance instantiated with settings defined in the ProxyConfig instance. """ - return urllib2.build_opener(*self.GetHandlers()) + return build_opener(*self.GetHandlers()) def GetHandlers(self): - """Retrieve the appropriate urllib2 handlers for the given configuration. + """Retrieve the appropriate urllib handlers for the given configuration. Returns: - A list of urllib2.BaseHandler subclasses to be used when making calls - with proxy. + A list of urllib.request.BaseHandler subclasses to be used when making + calls with proxy. """ handlers = [] if self.ssl_context: - handlers.append(urllib2.HTTPSHandler(context=self.ssl_context)) + handlers.append(HTTPSHandler(context=self.ssl_context)) if self.proxies: - handlers.append(urllib2.ProxyHandler(self.proxies)) + handlers.append(ProxyHandler(self.proxies)) return handlers - def GetSudsProxyTransport(self): - """Retrieve a suds.transport.http.HttpTransport to be used with suds. - - This will apply all handlers relevant to the usage of the proxy - configuration automatically. - - Returns: - A _SudsProxyTransport instance used to make requests with suds using the - configured proxy. - """ - return self._SudsProxyTransport(self.GetHandlers()) - class _ZeepProxyTransport(zeep.transports.Transport): """A Zeep transport which configures caching, proxy support, and timeouts.""" @@ -674,31 +520,6 @@ def __init__(self, timeout, proxy_config, cache): self.session.proxies = proxy_config.proxies -class _SudsProxyTransport(suds.transport.http.HttpTransport): - """A transport that applies the given handlers for usage with a proxy.""" - - def __init__(self, timeout, proxy_config): - """Initializes SudsHTTPSTransport. - - Args: - timeout: An integer for the connection timeout time. - proxy_config: A ProxyConfig instance representing proxy settings. - """ - suds.transport.http.HttpTransport.__init__(self, timeout=timeout) - self.handlers = proxy_config.GetHandlers() - - def u2handlers(self): - """Get a collection of urllib2 handlers to be installed in the opener. - - Returns: - A list of handlers to be installed to the OpenerDirector used by suds. - """ - # Start with the default set of handlers. - return_handlers = suds.transport.http.HttpTransport.u2handlers(self) - return_handlers.extend(self.handlers) - - return return_handlers - class SoapPacker(object): """A utility class to be passed to argument packing functions. @@ -711,11 +532,10 @@ class SoapPacker(object): def Pack(cls, obj): raise NotImplementedError('You must subclass SoapPacker.') -def GetSchemaHelperForLibrary(lib_name): - if lib_name == 'suds': - return SudsSchemaHelper - elif lib_name == 'zeep': - return ZeepSchemaHelper + +def GetSchemaHelperForLibrary(): + return ZeepSchemaHelper + class GoogleSchemaHelper(object): """Base class for type to xml conversion. @@ -738,61 +558,6 @@ def GetSoapXMLForComplexType(self, type_name, value): """ return -class SudsSchemaHelper(GoogleSchemaHelper): - """Suds schema helper implementation.""" - def __init__(self, endpoint, timeout, - proxy_config, namespace_override, cache): - """Initializes a SudsSchemaHelper. - - Args: - endpoint: A string representing the URL to connect to. - timeout: An integer timeout in MS used to determine connection timeouts. - proxy_config: A googleads.common.ProxyConfig instance which represents - the proxy settings needed. - namespace_override: A string to doctor the WSDL namespace with. - cache: An instance of suds.cache.Cache to use for caching. - - Raises: - GoogleAdsValueError: The wrong type was given for caching. - """ - - if cache and not isinstance(cache, suds.cache.Cache): - raise googleads.errors.GoogleAdsValueError( - 'Must use a proper suds cache with suds.') - - transport = _SudsProxyTransport(timeout, proxy_config) - try: - doctor = suds.xsd.doctor.ImportDoctor( - suds.xsd.doctor.Import( - namespace_override, endpoint)) - self.suds_client = suds.client.Client( - endpoint, - transport=transport, - plugins=[LoggingMessagePlugin()], - cache=cache, - doctor=doctor) - self._namespace_override = namespace_override - except suds.transport.TransportError as e: - raise googleads.errors.GoogleAdsSoapTransportError(str(e)) - - def GetSoapXMLForComplexType(self, type_name, value): - """Return an XML string representing a SOAP complex type. - - Args: - type_name: The name of the type with namespace prefix if necessary. - value: A python dictionary to hydrate the type instance with. - - Returns: - A string containing the SOAP XML for the type. - """ - schema = self.suds_client.wsdl.schema - definition_type = schema.elements[(type_name, self._namespace_override)] - marshaller = suds.mx.literal.Literal(schema) - content = suds.mx.Content( - tag=type_name, value=value, - name=type_name, type=definition_type) - data = marshaller.process(content) - return data class ZeepSchemaHelper(GoogleSchemaHelper): """Zeep schema helper implementation.""" @@ -846,11 +611,9 @@ def GetSoapXMLForComplexType(self, type_name, value): data = lxml.etree.tostring(result_element).strip() return data -def GetServiceClassForLibrary(lib_name): - if lib_name == 'suds': - return SudsServiceProxy - elif lib_name == 'zeep': - return ZeepServiceProxy + +def GetServiceClassForLibrary(): + return ZeepServiceProxy class GoogleSoapService(object): @@ -931,157 +694,6 @@ def __getattr__(self, attr): raise googleads.errors.GoogleAdsValueError('Service %s not found' % attr) -class SudsServiceProxy(GoogleSoapService): - """Wraps a suds service object, allowing custom logic to be injected. - - This class is responsible for refreshing the HTTP and SOAP headers, so changes - to the client object will be reflected in future SOAP calls, and for - transforming SOAP call input parameters, allowing dictionary syntax to be used - with all SOAP complex types. - - Attributes: - suds_client: The suds.client.Client this service belongs to. If you are - familiar with suds and want to use autogenerated classes, you can access - the client and its factory, - """ - - def __init__(self, endpoint, header_handler, packer, proxy_config, - timeout, version, cache=None): - """Initializes a suds service proxy. - - Args: - endpoint: A URL for the service. - header_handler: A HeaderHandler responsible for setting the SOAP and HTTP - headers on the service client. - packer: An optional subclass of googleads.common.SoapPacker that provides - customized packing logic. - proxy_config: A ProxyConfig that represents proxy settings. - timeout: An integer to set the connection timeout. - version: the current version of the library, e.g. 'v201811' - cache: A suds.cache.Cache instance to pass to the underlying SOAP - library for caching. - - Raises: - GoogleAdsValueError: The wrong type was given for caching. - """ - super(SudsServiceProxy, self).__init__(header_handler, packer, version) - - if cache and not isinstance(cache, suds.cache.Cache): - raise googleads.errors.GoogleAdsValueError( - 'Must use a proper suds cache with suds.') - - transport = _SudsProxyTransport(timeout, proxy_config) - self._method_proxies = {} - try: - self.suds_client = suds.client.Client( - endpoint, - timeout=timeout, - cache=cache, - transport=transport, - plugins=[LoggingMessagePlugin()]) - except suds.transport.TransportError as e: - raise googleads.errors.GoogleAdsSoapTransportError(str(e)) - - - def GetRequestXML(self, method, *args): - """Get the raw SOAP XML for a request. - - Args: - method: The method name. - *args: A list of arguments to be passed to the method. - - Returns: - An element containing the raw XML that would be sent as the request. - """ - self.suds_client.set_options(nosend=True) - service_request = (getattr(self, method))(*args).envelope - self.suds_client.set_options(nosend=False) - return lxml.etree.fromstring(service_request) - - def CreateSoapElementForType(self, type_name): - """Create an instance of a SOAP type. - - Args: - type_name: The name of the type. - - Returns: - An instance of type type_name. - """ - return self.suds_client.factory.create(type_name) - - def SetHeaders(self, soap_headers, http_headers): - """Set the headers for the underlying client. - - Args: - soap_headers: A SOAP element for the SOAP headers. - http_headers: A dictionary for the http headers. - """ - self.suds_client.set_options(soapheaders=soap_headers, headers=http_headers) - - def _WsdlHasMethod(self, method_name): - """Determine if the wsdl contains a method. - - Args: - method_name: The name of the method to search. - - Returns: - True if the method is in the WSDL, otherwise False. - """ - return method_name in self.suds_client.wsdl.services[0].ports[0].methods - - def _CreateMethod(self, method_name): - """Create a method wrapping an invocation to the SOAP service. - - Args: - method_name: A string identifying the name of the SOAP method to call. - - Returns: - A callable that can be used to make the desired SOAP request. - """ - soap_service_method = getattr(self.suds_client.service, method_name) - - def MakeSoapRequest(*args): - """Perform a SOAP call.""" - AddToUtilityRegistry('suds') - self.SetHeaders( - self._header_handler.GetSOAPHeaders(self.CreateSoapElementForType), - self._header_handler.GetHTTPHeaders()) - - try: - return soap_service_method( - *[_PackForSuds(arg, self.suds_client.factory, - self._packer) for arg in args]) - except suds.WebFault as e: - if _logger.isEnabledFor(logging.WARNING): - _logger.warning('Response summary - %s', - _ExtractResponseSummaryFields(e.document)) - - _logger.debug('SOAP response:\n%s', e.document.str()) - - if not hasattr(e.fault, 'detail'): - exc = (googleads.errors. - GoogleAdsServerFault(e.document, message=e.fault.faultstring)) - raise exc # Done this way for 2to3 - - # Before re-throwing the WebFault exception, an error object needs to be - # wrapped in a list for safe iteration. - fault = e.fault.detail.ApiExceptionFault - if not hasattr(fault, 'errors') or fault.errors is None: - exc = (googleads.errors. - GoogleAdsServerFault(e.document, message=e.fault.faultstring)) - raise exc # Done this way for 2to3 - - obj = fault.errors - if not isinstance(obj, list): - fault.errors = [obj] - - exc = googleads.errors.GoogleAdsServerFault(e.document, fault.errors, - message=e.fault.faultstring) - raise exc # Done this way for 2to3 - - return MakeSoapRequest - - class _ZeepAuthHeaderPlugin(zeep.Plugin): """A zeep plugin responsible for setting our custom HTTP headers.""" @@ -1163,8 +775,8 @@ def __init__(self, endpoint, header_handler, packer, except requests.exceptions.HTTPError as e: raise googleads.errors.GoogleAdsSoapTransportError(str(e)) - first_service = list(self.zeep_client.wsdl.services.itervalues())[0] - first_port = list(first_service.ports.itervalues())[0] + first_service = list(self.zeep_client.wsdl.services.values())[0] + first_port = list(first_service.ports.values())[0] self._method_bindings = first_port.binding @@ -1212,7 +824,7 @@ def _WsdlHasMethod(self, method_name): def _GetBindingNamespace(self): """Return a string with the namespace of the service binding in the WSDL.""" - return (list(self.zeep_client.wsdl.bindings.itervalues())[0] + return (list(self.zeep_client.wsdl.bindings.values())[0] .port_name.namespace) def _PackArguments(self, method_name, args, set_type_attrs=False): @@ -1236,7 +848,7 @@ def _PackArguments(self, method_name, args, set_type_attrs=False): op_params = self.zeep_client.get_element( '{%s}%s' % (self._GetBindingNamespace(), method_name)).type.elements result = [self._PackArgumentsHelper(param, param_data, set_type_attrs) - for ((_, param), param_data) in izip(op_params, args)] + for ((_, param), param_data) in zip(op_params, args)] return result @classmethod @@ -1279,7 +891,7 @@ def _PackArgumentsHelper(self, elem, data, set_type_attrs): else: elem_type = elem.type - data_formatted = data.iteritems() + data_formatted = data.items() packed_result = self._CreateComplexTypeFromData( elem_type, type_override is not None, data_formatted, set_type_attrs) elif isinstance(data, zeep.xsd.CompoundValue): @@ -1293,10 +905,6 @@ def _PackArgumentsHelper(self, elem, data, set_type_attrs): packed_result = [self._PackArgumentsHelper(elem, item, set_type_attrs) for item in data] else: - if elem.type.name == 'base64Binary' and self._IsBase64(data): - _logger.warn('Passing data to base64 field %s that may ' - 'already be encoded. Do not pre-encode base64 ' - 'fields with zeep.', elem.name) packed_result = data return packed_result @@ -1409,95 +1017,3 @@ def GetSOAPHeaders(self, create_method): @abc.abstractmethod def GetHTTPHeaders(self): """Returns the required HTTP headers.""" - - - -class LoggingMessagePlugin(suds.plugin.MessagePlugin): - """A MessagePlugin used to log request summaries.""" - - def marshalled(self, context): - if _logger.isEnabledFor(logging.INFO): - _logger.info('Request summary - %s', - _ExtractRequestSummaryFields(context.envelope)) - - def parsed(self, context): - if _logger.isEnabledFor(logging.INFO): - _logger.info('Response summary - %s', - _ExtractResponseSummaryFields(context.reply)) - - -def _ExtractRequestSummaryFields(document): - """Extract logging fields from the request's suds.sax.element.Element. - - Args: - document: A suds.sax.element.Element instance containing the API request. - - Returns: - A dict mapping logging field names to their corresponding value. - """ - headers = document.childAtPath('Header/RequestHeader') - body = document.childAtPath('Body') - - summary_fields = { - 'methodName': body.getChildren()[0].name - } - - # Extract AdWords-specific fields if they exist. - # Note: We need to check if None because this will always evaluate False. - client_customer_id = headers.getChild('clientCustomerId') - if client_customer_id is not None: - summary_fields['clientCustomerId'] = client_customer_id.text - - # Extract Ad Manager-specific fields if they exist. - # Note: We need to check if None because this will always evaluate False. - network_code = headers.getChild('networkCode') - if network_code is not None: - summary_fields['networkCode'] = network_code.text - - return summary_fields - - -def _ExtractResponseSummaryFields(document): - """Extract logging fields from the response's suds.sax.document.Document. - - Args: - document: A suds.sax.document.Document instance containing the parsed - API response for a given API request. - - Returns: - A dict mapping logging field names to their corresponding value. - """ - headers = document.childAtPath('Envelope/Header/ResponseHeader') - body = document.childAtPath('Envelope/Body') - summary_fields = {} - - if headers is not None: - summary_fields['requestId'] = headers.getChild('requestId').text - summary_fields['responseTime'] = headers.getChild('responseTime').text - - # Extract AdWords-specific summary fields if they are present. - # Note: We need to check if None because this will always evaluate False. - service_name = headers.getChild('serviceName') - if service_name is not None: - summary_fields['serviceName'] = service_name.text - - method_name = headers.getChild('methodName') - if method_name is not None: - summary_fields['methodName'] = method_name.text - - operations = headers.getChild('operations') - if operations is not None: - summary_fields['operations'] = operations.text - - if body is not None: - # Extract fault if it exists. - fault = body.getChild('Fault') - if fault is not None: - summary_fields['isFault'] = True - # Cap length of faultstring to 16k characters for summary. - summary_fields['faultMessage'] = fault.getChild( - 'faultstring').text[:16000] - else: - summary_fields['isFault'] = False - - return summary_fields diff --git a/googleads/util.py b/googleads/util.py index 83158969..b539c21c 100644 --- a/googleads/util.py +++ b/googleads/util.py @@ -14,27 +14,16 @@ """Utilities used by the client library.""" -import gzip -import io import logging import re -import sys import threading -import urllib2 from lxml import etree -import suds -import suds.mx -import suds.mx.appender import zeep _COMMON_FILTER = None -_SUDS_CLIENT_FILTER = None -_SUDS_MX_CORE_FILTER = None -_SUDS_MX_LITERAL_FILTER = None -_SUDS_TRANSPORT_FILTER = None LOGGER_FORMAT = '[%(asctime)s - %(name)s - %(levelname)s] %(message)s' @@ -45,114 +34,6 @@ def GetGoogleAdsCommonFilter(): return _COMMON_FILTER -def GetSudsClientFilter(): - global _SUDS_CLIENT_FILTER - if not _SUDS_CLIENT_FILTER: - _SUDS_CLIENT_FILTER = _SudsClientFilter() - return _SUDS_CLIENT_FILTER - - -def GetSudsMXCoreFilter(): - global _SUDS_MX_CORE_FILTER - if not _SUDS_MX_CORE_FILTER: - _SUDS_MX_CORE_FILTER = _SudsMXCoreFilter() - return _SUDS_MX_CORE_FILTER - - -def GetSudsMXLiteralFilter(): - global _SUDS_MX_LITERAL_FILTER - if not _SUDS_MX_LITERAL_FILTER: - _SUDS_MX_LITERAL_FILTER = _SudsMXLiteralFilter() - return _SUDS_MX_LITERAL_FILTER - - -def GetSudsTransportFilter(): - global _SUDS_TRANSPORT_FILTER - if not _SUDS_TRANSPORT_FILTER: - _SUDS_TRANSPORT_FILTER = _SudsTransportFilter() - return _SUDS_TRANSPORT_FILTER - - -class PatchHelper(object): - """Utility that applies patches on behalf of the Google Ads Client Library.""" - - def Apply(self): - """Apply patches used by the Google Ads Client Library.""" - self._ApplySudsJurkoAppenderPatch() - self._ApplySudsJurkoSendPatch() - - def _ApplySudsJurkoAppenderPatch(self): - """Appends a Monkey Patch to the suds.mx.appender module. - - This resolves an issue where empty objects are ignored and stripped from the - request output. More details can be found on the suds-jurko issue tracker: - https://goo.gl/uyYw0C - """ - def PatchedAppend(self, parent, content): - obj = content.value - child = self.node(content) - parent.append(child) - for item in obj: - cont = suds.mx.Content(tag=item[0], value=item[1]) - suds.mx.appender.Appender.append(self, child, cont) - - suds.mx.appender.ObjectAppender.append = PatchedAppend - - def _ApplySudsJurkoSendPatch(self): - """Appends a Monkey Patch to the suds.transport.http module. - - This allows the suds library to decompress the SOAP body when compression is - enabled. For more details on SOAP Compression, see: - https://developers.google.com/adwords/api/docs/guides/bestpractices?hl=en#use_compression - """ - def GetInflateStream(msg): - stream = io.BytesIO() - stream.write(msg) - stream.flush() - stream.seek(0) - return gzip.GzipFile(fileobj=stream, mode='rb') - - def PatchedHttpTransportSend(self, request): - """Patch for HttpTransport.send to enable gzip compression.""" - msg = request.message - http_transport = suds.transport.http.HttpTransport - url = http_transport._HttpTransport__get_request_url(request) - headers = request.headers - u2request = urllib2.Request(url, msg, headers) - self.addcookies(u2request) - self.proxy = self.options.proxy - request.headers.update(u2request.headers) - suds.transport.http.log.debug('sending:\n%s', request) - try: - fp = self.u2open(u2request) - except urllib2.HTTPError, e: - if e.code in (202, 204): - return None - else: - if e.headers.get('content-encoding') == 'gzip': - # If gzip encoding is used, decompress here. - # Need to read and recreate a stream because urllib result objects - # don't fully implement the file-like API - e.fp = GetInflateStream(e.fp.read()) - - raise suds.transport.TransportError(e.msg, e.code, e.fp) - - self.getcookies(fp, u2request) - # Note: Python 2 returns httplib.HTTPMessage, and Python 3 returns - # http.client.HTTPMessage, which differ slightly. - headers = (fp.headers.dict if sys.version_info < (3, 0) else fp.headers) - result = suds.transport.Reply(200, headers, fp.read()) - - if result.headers.get('content-encoding') == 'gzip': - # If gzip encoding is used, decompress here. - result.message = GetInflateStream(result.message).read() - - suds.transport.http.log.debug('received:\n%s', result) - return result - - suds.transport.http.HttpTransport.send = PatchedHttpTransportSend - - class _AbstractDevTokenSOAPFilter(logging.Filter): """Interface for sanitizing logs containing SOAP request/response data.""" @@ -178,137 +59,6 @@ def filter(self, record): return True -class _SudsClientFilter(_AbstractDevTokenSOAPFilter): - """Removes sensitive data from logs generated by suds.client.""" - _SUDS_CLIENT_SOAP_MSG = 'sending to (%s)\nmessage:\n%s' - _SUDS_CLIENT_HEADERS_MSG = 'headers = %s' - - def filter(self, record): - args = record.args - if record.msg == self._SUDS_CLIENT_SOAP_MSG: - # If the original suds.sax.document.Document is modified, that will also - # modify the request itself. Instead, replace it with its sanitized text. - record.args = (args[0], self._DEVELOPER_TOKEN_SUB.sub( - self._REDACTED, args[1].str())) - elif record.msg == self._SUDS_CLIENT_HEADERS_MSG: - sanitized_headers = record.args.copy() - if self._AUTHORIZATION_HEADER in sanitized_headers: - sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED - sanitized_headers.pop(self._AUTHORIZATION_HEADER.capitalize(), None) - record.args = sanitized_headers - return True - - -class _SudsMXCoreFilter(_AbstractDevTokenSOAPFilter): - """Removes sensitive data from logs generated by suds.mx.core.""" - - _DEVELOPER_TOKEN = 'developerToken' - _REQUEST_HEADER = 'RequestHeader' - - def filter(self, record): - for i in range(len(record.args)): - arg = record.args[i] - - if isinstance(arg, suds.mx.Content): - if arg.tag == self._REQUEST_HEADER: - # Rather than modifying the argument directly, sets args to a modified - # copy so that we don't overwrite the headers to be sent in the actual - # request. - d = dict(arg.value) - if self._DEVELOPER_TOKEN in d: - d[self._DEVELOPER_TOKEN] = self._REDACTED - record.args = list(record.args) - record.args[i] = suds.mx.Content(tag=self._REQUEST_HEADER, value=d) - break - if arg.tag == self._DEVELOPER_TOKEN: - # Rather than modifying the argument directly, sets args to a modified - # copy so that we don't overwrite the headers to be sent in the actual - # request. - record.args = list(record.args) - record.args[i] = suds.mx.Content( - tag=self._DEVELOPER_TOKEN, value=self._REDACTED) - break - elif isinstance(arg, suds.sax.element.Element): - if arg.name == self._REQUEST_HEADER: - # Only produce a modified copy of the RequestHeader element if it - # contains a developer token. - if arg.getChild(self._DEVELOPER_TOKEN) is not None: - request_header = suds.sax.element.Element( - arg.name, parent=arg.parent) - - for child in arg.getChildren(): - copied_child = suds.sax.element.Element( - child.name, parent=request_header) - - if child.name == self._DEVELOPER_TOKEN: - copied_child.text = suds.sax.text.Text(self._REDACTED) - else: - copied_child.text = child.text - - request_header.append(copied_child) - - # Rather than modifying the argument directly, sets args to a - # modified copy so that we don't overwrite the headers to be sent in - # the actual request. - record.args = list(record.args) - record.args[i] = request_header - break - - return True - - -class _SudsMXLiteralFilter(_AbstractDevTokenSOAPFilter): - """Removes sensitive data from logs generated by suds.mx.literal.""" - - _DEVELOPER_TOKEN = 'developerToken' - _REQUEST_HEADER = 'RequestHeader' - - def filter(self, record): - for i in range(len(record.args)): - arg = record.args[i] - - if isinstance(arg, suds.mx.Content): - if arg.tag == self._REQUEST_HEADER: - # Rather than modifying the argument directly, sets args to a modified - # copy so that we don't overwrite the headers to be sent in the actual - # request. - d = dict(arg.value) - if self._DEVELOPER_TOKEN in d: - d[self._DEVELOPER_TOKEN] = self._REDACTED - record.args = list(record.args) - record.args[i] = suds.mx.Content(tag=self._REQUEST_HEADER, value=d) - break - if arg.tag == self._DEVELOPER_TOKEN: - # Rather than modifying the argument directly, sets args to a modified - # copy so that we don't overwrite the headers to be sent in the actual - # request. - record.args = list(record.args) - record.args[i] = suds.mx.Content(tag=self._DEVELOPER_TOKEN, - value=self._REDACTED) - break - - return True - - -class _SudsTransportFilter(_AbstractDevTokenSOAPFilter): - """Removes sensitive data from logs generated by suds.transport.""" - - def filter(self, record): - if record.args: - arg = record.args[0] - if isinstance(arg, suds.transport.Request): - new_arg = suds.transport.Request(arg.url) - sanitized_headers = arg.headers.copy() - if self._AUTHORIZATION_HEADER in sanitized_headers: - sanitized_headers[self._AUTHORIZATION_HEADER] = self._REDACTED - sanitized_headers.pop(self._AUTHORIZATION_HEADER.capitalize(), None) - new_arg.headers = sanitized_headers - new_arg.message = self._DEVELOPER_TOKEN_SUB.sub( - self._REDACTED, arg.message.decode('utf-8')) - record.args = (new_arg,) - - return True - _RESPONSE_XML_LOG_LINE = 'Incoming response: \n%s' _REQUEST_LOG_LINE = 'Request made: Service: "%s" Method: "%s" URL: "%s"' _REQUEST_XML_LOG_LINE = 'Outgoing request: %s\n%s' @@ -355,7 +105,8 @@ def ingress(self, envelope, http_headers, operation): warn_data.update(header_data) if 'serviceName' not in warn_data: - warn_data['serviceName'] = operation.binding.wsdl.services.keys()[0] + warn_service_name = operation.binding.wsdl.services.keys() + warn_data['serviceName'] = list(warn_service_name)[0] if 'methodName' not in warn_data: warn_data['methodName'] = operation.name @@ -377,7 +128,8 @@ def egress(self, envelope, http_headers, operation, binding_options): A tuple of the envelope and headers. """ if self._logger.isEnabledFor(logging.INFO): - service_name = operation.binding.wsdl.services.keys()[0] + service_keys = operation.binding.wsdl.services.keys() + service_name = list(service_keys)[0] self._logger.info(_REQUEST_LOG_LINE, service_name, operation.name, binding_options['address']) diff --git a/setup.py b/setup.py index 2b557fcd..0038f1d9 100755 --- a/setup.py +++ b/setup.py @@ -27,18 +27,15 @@ DEPENDENCIES = ['google-auth>=1.0.0,<2.0.0', 'google-auth-oauthlib>=0.0.1,<1.0.0', 'pytz>=2015.7', 'PyYAML>=5.1, <6.0', 'requests>=2.0.0,<3.0.0', - 'suds-jurko>=0.6,<0.7', 'xmltodict>=0.9.2,<1.0.0', - 'zeep>=2.5.0'] + 'xmltodict>=0.9.2,<1.0.0', 'zeep>=2.5.0'] # Note: Breaking change introduced in pyfakefs 3.3. -TEST_DEPENDENCIES = ['mock>=2.0.0,<3.0.0', 'pyfakefs>=3.2,<3.3', - 'six>=1.11.0,<2.0.0'] +TEST_DEPENDENCIES = ['mock>=2.0.0,<3.0.0', 'pyfakefs>=3.2,<3.3'] CLASSIFIERS = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.4' + 'Programming Language :: Python :: 3.6' ] @@ -72,10 +69,7 @@ def GetVersion(): Supported Python Versions ========================= -This library is supported for Python 2 and 3, for versions 2.7+ and 3.4+ -respectively. It is recommended that Python 2 users use python 2.7.9+ to take -advantage of the SSL Certificate Validation feature that is not included in -earlier versions. +This library is supported for Python 3.6+. Installation ============ @@ -105,10 +99,6 @@ def GetVersion(): `issue tracker `_. """ -extra_params = {} -if sys.version_info[0] == 3: - extra_params['use_2to3'] = True - setup(name='googleads', version=GetVersion(), description='Google Ads Python Client Library', @@ -123,5 +113,4 @@ def GetVersion(): classifiers=CLASSIFIERS, install_requires=DEPENDENCIES, tests_require=TEST_DEPENDENCIES, - test_suite='tests', - **extra_params) + test_suite='tests') diff --git a/tests/ad_manager_test.py b/tests/ad_manager_test.py index 19e49082..b795c6b3 100644 --- a/tests/ad_manager_test.py +++ b/tests/ad_manager_test.py @@ -16,19 +16,17 @@ import datetime -import sys import unittest import mock import pytz -import six +import io import googleads.ad_manager import googleads.common import googleads.errors from . import testing -URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' CURRENT_VERSION = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1] @@ -590,7 +588,7 @@ def setUp(self): }] def testDownloadPqlResultSetToCsv(self): - csv_file = six.StringIO() + csv_file = io.StringIO() self.pql_service.select.return_value = {'rows': self.generic_rval, 'columnTypes': self.generic_header} @@ -741,20 +739,19 @@ def testDownloadReportToFile(self): report_job_id = 't68t3278y429' report_download_url = 'http://google.com/something' report_data = 'THIS IS YOUR REPORT!' - report_contents = six.StringIO() + report_contents = io.StringIO() report_contents.write(report_data) report_contents.seek(0) fake_response = mock.Mock() fake_response.read = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - outfile = six.StringIO() + outfile = io.StringIO() download_func = self.report_service.getReportDownloadUrlWithOptions download_func.return_value = report_download_url - with mock.patch('urllib2.OpenerDirector.open' if sys.version_info[0] == 2 - else 'urllib.request.OpenerDirector.open') as mock_open: + with mock.patch('urllib.request.OpenerDirector.open') as mock_open: mock_open.return_value = fake_response self.report_downloader.DownloadReportToFile( @@ -794,7 +791,7 @@ class MyOpener(object): addheaders = [('a', 'b')] opener = MyOpener() - with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mock_build_opener: + with mock.patch('googleads.ad_manager.build_opener') as mock_build_opener: mock_build_opener.return_value = opener self.ad_manager.GetDataDownloader() diff --git a/tests/adwords_test.py b/tests/adwords_test.py index 1575e130..e3f7b18b 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -22,38 +22,29 @@ import re import tempfile import unittest +from urllib.error import HTTPError +from urllib.parse import urlencode +from urllib.request import urlopen from xml.etree import ElementTree import googleads.adwords import googleads.common import googleads.errors +from . import testing import lxml.etree import mock -import six -import suds -import yaml import yaml import zeep.transports -from . import testing -try: - import urllib2 -except ImportError: - import urllib.request as urllib2 # For Py3 CURRENT_VERSION = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] TEST_DIR = os.path.dirname(__file__) -URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' -def GetAdWordsClient(soap_impl, **kwargs): +def GetAdWordsClient(**kwargs): """Returns an initialized AdwordsClient for use in testing. If not specified, the keyword arguments will be set to default test values. - Args: - soap_impl: The SOAP implementation to pass to the client. - **kwargs: Optional keyword arguments that can be provided to customize the - generated AdWordsClient. Keyword Arguments: ccid: A str value for the AdWordsClient's client_customer_id. dev_token: A str value for the AdWordsClient's developer_token. @@ -90,8 +81,7 @@ def GetAdWordsClient(soap_impl, **kwargs): cache=kwargs.get('cache'), proxy_config=kwargs.get('proxy_config'), validate_only=validate_only, partial_failure=partial_failure, - report_downloader_headers=report_downloader_headers, - soap_impl=soap_impl, timeout=timeout) + report_downloader_headers=report_downloader_headers, timeout=timeout) return client @@ -137,7 +127,7 @@ def setUp(self): self.default_sig_template = ' (%s, %s, %s)' self.util_sig_template = ' (%s, %s, %s, %s)' self.aw_client = GetAdWordsClient( - 'zeep', ccid=self.ccid, dev_token=self.dev_token, + ccid=self.ccid, dev_token=self.dev_token, user_agent=self.user_agent, oauth2_client=self.oauth2_client, validate_only=self.validate_only, partial_failure=self.partial_failure, report_downloader_headers=self.report_downloader_headers) @@ -348,10 +338,8 @@ def setUp(self): os.path.dirname(__file__), 'test_data/adwords_googleads.yaml') self.https_proxy_uri = 'http://myproxy:443' self.proxy_config = GetProxyConfig(https_proxy_uri=self.https_proxy_uri) - self.file_cache = suds.cache.FileCache - self.no_cache = suds.cache.NoCache() - self.adwords_client = GetAdWordsClient('zeep') - self.aw_client = GetAdWordsClient('zeep', proxy_config=self.proxy_config) + self.adwords_client = GetAdWordsClient() + self.aw_client = GetAdWordsClient(proxy_config=self.proxy_config) self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.adwords_client, CURRENT_VERSION, False, None) @@ -400,7 +388,7 @@ def testLoadFromStorageWithNoUserAgent(self): def testGetService_success(self): client = GetAdWordsClient( - 'zeep', timeout='timeout', cache='cache', proxy_config='proxy_config') + timeout='timeout', cache='cache', proxy_config='proxy_config') client.enable_compression = True service_name = list(googleads.adwords._SERVICE_MAP[CURRENT_VERSION])[0] @@ -481,8 +469,8 @@ def testServiceMap(self): for service, mapping in services.items(): wsdl_url = wsdl_url_template % (server, mapping, version, service) try: - six.moves.urllib.request.urlopen(wsdl_url) - except six.moves.urllib.error.HTTPError: + urlopen(wsdl_url) + except HTTPError: raise ValueError('AdWords API %s does not contain "%s" with mapping ' '"%s". The generated WSDL URL does not exist:\n%s' % (version, service, mapping, wsdl_url)) @@ -519,7 +507,7 @@ class BatchJobHelperTest(testing.CleanUtilityRegistryTestCase): def setUp(self): """Prepare tests.""" - self.client = GetAdWordsClient('zeep') + self.client = GetAdWordsClient() self.batch_job_helper = self.client.GetBatchJobHelper() def testGetId(self): @@ -539,21 +527,20 @@ def testUploadOperations(self): with mock.patch('googleads.adwords.IncrementalUploadHelper' '._InitializeURL') as mock_init: mock_init.return_value = 'https://www.google.com' - with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: + with mock.patch('urllib.request.OpenerDirector.open') as mock_open: self.batch_job_helper.UploadOperations([[]]) mock_open.assert_called_with(mock_request) -@testing.MultiBackendTest class BatchJobUploadRequestBuilderTest(testing.CleanUtilityRegistryTestCase): """Test suite for the BatchJobUploadRequestBuilder.""" ENVELOPE_NS = 'http://schemas.xmlsoap.org/soap/envelope/' - def setUp(self, soap_impl): + def setUp(self): """Prepare tests.""" - self.client = GetAdWordsClient(soap_impl) + self.client = GetAdWordsClient() self.request_builder = self.client.GetBatchJobHelper()._request_builder self.version = self.request_builder._version self.upload_url = 'https://goo.gl/IaQQsJ' @@ -738,8 +725,7 @@ def GenerateValidRequest(self, operation_type, num_operations=1): request = self.RAW_API_REQUEST_TEMPLATE % ( self.version, self.version, method, ops_xml, method) - if six.PY3: - request = bytes(request, 'utf-8') + request = bytes(request, 'utf-8') request = lxml.etree.fromstring(request) return (ops, request) @@ -1324,13 +1310,13 @@ class IncrementalUploadHelperTest(testing.CleanUtilityRegistryTestCase): """Test suite for the IncrementalUploadHelper.""" def GetIncrementalUploadHelper(self): - with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: + with mock.patch('urllib.request.OpenerDirector.open') as mock_open: mock_open.return_value.headers = {'location': self.initialized_url} return self.batch_job_helper.GetIncrementalUploadHelper(self.original_url) def setUp(self): """Prepare tests.""" - self.client = GetAdWordsClient('zeep') + self.client = GetAdWordsClient() self.server = 'https://test.com' self.version = 'test_version' self.batch_job_helper = self.client.GetBatchJobHelper( @@ -1357,9 +1343,9 @@ def testDump(self): self.assertEqual(expected, dump_data) def testLoad(self): - s = six.StringIO(self.incremental_uploader_dump) + s = io.StringIO(self.incremental_uploader_dump) - with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: + with mock.patch('urllib.request.OpenerDirector.open') as mock_open: mock_open.return_value.headers = { 'location': self.initialized_url } @@ -1386,7 +1372,7 @@ def testUploadOperations(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: + with mock.patch('urllib.request.OpenerDirector.open') as mock_open: self.incremental_uploader.UploadOperations([[]], True) mock_open.assert_called_with(mock_request) @@ -1395,7 +1381,7 @@ def testUploadOperationsWithError(self): error_code = '404' error_message = 'I AM ERROR' error_headers = {} - http_error = six.moves.urllib.error.HTTPError( + http_error = HTTPError( error_url, error_code, error_message, error_headers, None) with mock.patch('googleads.adwords.BatchJobHelper.' @@ -1403,10 +1389,10 @@ def testUploadOperationsWithError(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch.object(urllib2.OpenerDirector, 'open') as mock_open: + with mock.patch('urllib.request.OpenerDirector.open') as mock_open: mock_open.side_effect = http_error self.assertRaises( - six.moves.urllib.error.HTTPError, + HTTPError, self.incremental_uploader.UploadOperations, [[]], True) mock_open.assert_called_with(mock_request) @@ -1416,7 +1402,7 @@ def testUploadOperationsAfterFinished(self): 'BuildUploadRequest') as mock_build_request: mock_request = mock.MagicMock() mock_build_request.return_value = mock_request - with mock.patch.object(urllib2.OpenerDirector, 'open'): + with mock.patch('urllib.request.OpenerDirector.open'): self.incremental_uploader.UploadOperations([[]], True) self.assertRaises( googleads.errors.AdWordsBatchJobServiceInvalidOperationError, @@ -1427,7 +1413,7 @@ class MyOpener(object): addheaders = [('a', 'b')] opener = MyOpener() - with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mock_build_opener,\ + with mock.patch('googleads.adwords.build_opener') as mock_build_opener,\ mock.patch('googleads.adwords.IncrementalUploadHelper._InitializeURL'): mock_build_opener.return_value = opener self.client.custom_http_headers = {'X-My-Headers': 'abc'} @@ -1442,7 +1428,7 @@ class ResponseParserTest(testing.CleanUtilityRegistryTestCase): def setUp(self): """Prepare tests.""" - self.client = GetAdWordsClient('zeep') + self.client = GetAdWordsClient() self.response_parser = googleads.adwords.BatchJobHelper.GetResponseParser() @classmethod @@ -1525,10 +1511,7 @@ def GetVersionedXSD(version): with open(report_xsd, 'rb') as f: data = f.read() - if six.PY3: - return data.replace(b'{VERSION}', bytes(version, 'utf-8')) - else: - return data.replace('{VERSION}', version) + return data.replace(b'{VERSION}', bytes(version, 'utf-8')) class ReportDownloaderZeepTest(testing.CleanUtilityRegistryTestCase): @@ -1538,14 +1521,10 @@ def setUp(self): self.opener = mock.Mock() self.adwords_client = mock.Mock() self.adwords_client.proxy_config = GetProxyConfig() - self.adwords_client.soap_impl = 'zeep' self.adwords_client.cache = googleads.common.ZeepServiceProxy.NO_CACHE self.adwords_client.custom_http_headers = False self.header_handler = mock.Mock() - # It's unfortunate that the target output is different between suds and - # zeep. The reason is because suds pretty prints its xml in a very hardcoded - # hack way, and zeep does not. Not doing it is better. post_body_path = os.path.join( TEST_DIR, 'test_data/adwords_report_post_body_no_formatting.txt') with open(post_body_path, 'r') as f: @@ -1563,112 +1542,16 @@ def load(self, url): with mock.patch('googleads.common._ZeepProxyTransport') as mock_transport: mock_transport.return_value = XSDTransport() - self.adwords_client.soap_impl = 'zeep' self.report_downloader = googleads.adwords.ReportDownloader( self.adwords_client, self.version ) self.report_downloader.url_opener = self.opener @mock.patch('googleads.adwords._report_logger') - @mock.patch.object(urllib2, 'Request') + @mock.patch.object(googleads.adwords, 'Request') def testDownloadReportWithZeep(self, mock_request, mock_logger): mock_logger.isEnabledFor.return_value = True - output_file = six.StringIO() - report_definition = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - with mock.patch.object(self.report_downloader, - '_header_handler') as mock_header_handler, \ - (mock.patch.object( - self.report_downloader, - '_ExtractRequestSummaryFields')) as mock_extract_request_summary, \ - (mock.patch.object( - self.report_downloader, - '_ExtractResponseHeaders')) as mock_extract_response_headers: - response_data = u'ABC 广告客户' - response_fp = six.BytesIO() - response_fp.write(response_data if six.PY2 else bytes(response_data, - 'utf-8')) - response_fp.seek(0) - mock_response = mock.Mock() - mock_response.read.side_effect = response_fp.read - mock_response.code = '200' - self.opener.open.return_value = mock_response - - self.report_downloader.DownloadReport(report_definition, output_file, - skip_report_header=True, - use_raw_enum_values=False) - - mock_request.assert_called_once_with( - self.report_downloader._end_point, - (self.post_body_data if six.PY2 - else bytes(self.post_body_data, 'utf-8')), - mock_header_handler.GetReportDownloadHeaders.return_value) - - output_file.seek(0) - self.assertEqual(output_file.read(), response_data) - mock_extract_request_summary.assert_called_once_with( - mock_request.return_value) - mock_extract_response_headers.assert_called_once_with( - mock_response.headers) - - -class ReportDownloaderSudsTest(testing.CleanUtilityRegistryTestCase): - """Reporting integration tests for suds.""" - - def setUp(self): - self.version = CURRENT_VERSION - self.marshaller = mock.Mock() - self.header_handler = mock.Mock() - self.adwords_client = mock.Mock() - self.adwords_client.proxy_config = GetProxyConfig() - self.adwords_client.cache = suds.cache.NoCache() - self.adwords_client.custom_http_headers = False - self.opener = mock.Mock() - - post_body_path = os.path.join(TEST_DIR, - 'test_data/adwords_report_post_body.txt') - with open(post_body_path, 'r') as f: - self.post_body_data = f.read().replace('{VERSION}', self.version) - - class XSDTransport(suds.transport.Transport): - - def __init__(self): - suds.transport.Transport.__init__(self) - self.handlers = [] - - def open(self, request): - fp = io.BytesIO() - fp.write(GetVersionedXSD(CURRENT_VERSION)) - fp.seek(0) - return fp - - with mock.patch( - 'googleads.adwords._AdWordsHeaderHandler') as mock_handler: - mock_handler.return_value = self.header_handler - - with mock.patch('googleads.common._SudsProxyTransport') as mock_transport: - mock_transport.return_value = XSDTransport() - - self.adwords_client.soap_impl = 'suds' - self.report_downloader = googleads.adwords.ReportDownloader( - self.adwords_client, self.version - ) - self.report_downloader.url_opener = self.opener - - @mock.patch('googleads.adwords._report_logger') - @mock.patch.object(urllib2, 'Request') - def testDownloadReportWithSuds(self, mock_request, mock_logger): - mock_logger.isEnabledFor.return_value = True - output_file = six.StringIO() + output_file = io.StringIO() report_definition = { 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', 'dateRangeType': 'LAST_7_DAYS', @@ -1689,9 +1572,8 @@ def testDownloadReportWithSuds(self, mock_request, mock_logger): self.report_downloader, '_ExtractResponseHeaders')) as mock_extract_response_headers: response_data = u'ABC 广告客户' - response_fp = six.BytesIO() - response_fp.write(response_data if six.PY2 else bytes(response_data, - 'utf-8')) + response_fp = io.BytesIO() + response_fp.write(bytes(response_data, 'utf-8')) response_fp.seek(0) mock_response = mock.Mock() mock_response.read.side_effect = response_fp.read @@ -1704,8 +1586,7 @@ def testDownloadReportWithSuds(self, mock_request, mock_logger): mock_request.assert_called_once_with( self.report_downloader._end_point, - (self.post_body_data if six.PY2 - else bytes(self.post_body_data, 'utf-8')), + (bytes(self.post_body_data, 'utf-8')), mock_header_handler.GetReportDownloadHeaders.return_value) output_file.seek(0) @@ -1715,50 +1596,6 @@ def testDownloadReportWithSuds(self, mock_request, mock_logger): mock_extract_response_headers.assert_called_once_with( mock_response.headers) - @mock.patch.object(urllib2, 'Request') - def testDownloadReportWithBytesIO(self, mock_request): - output_file = six.BytesIO() - report_definition = { - 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', - 'dateRangeType': 'LAST_7_DAYS', - 'reportType': 'CRITERIA_PERFORMANCE_REPORT', - 'downloadFormat': 'CSV', - 'selector': { - 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', - 'Criteria', 'FinalUrls', 'Impressions', 'Clicks', 'Cost'] - } - } - - with mock.patch.object(self.report_downloader, - '_header_handler') as mock_header_handler, \ - (mock.patch.object(self.report_downloader, - '_ExtractRequestSummaryFields')), \ - (mock.patch.object(self.report_downloader, - '_ExtractResponseHeaders')): - response_data = u'CONTENT STRING 广告客户' - response_fp = six.BytesIO() - response_fp.write(response_data.encode('utf-8')) - response_fp.seek(0) - mock_response = mock.Mock() - mock_response.read.side_effect = response_fp.read - mock_response.code = '200' - self.opener.open.return_value = mock_response - - self.report_downloader.DownloadReport(report_definition, - output_file, - skip_report_header=True, - use_raw_enum_values=False) - - mock_request.assert_called_once_with( - self.report_downloader._end_point, - (self.post_body_data if six.PY2 - else bytes(self.post_body_data, 'utf-8')), - mock_header_handler.GetReportDownloadHeaders.return_value) - - output_file.seek(0) - self.assertEqual(output_file.read().decode('utf-8'), response_data) - - class ReportDownloaderTest(testing.CleanUtilityRegistryTestCase): """Tests for the googleads.adwords.ReportDownloader class.""" @@ -1779,7 +1616,7 @@ def setUp(self): self.header_handler = mock.Mock() self.adwords_client = mock.Mock() self.adwords_client.proxy_config = GetProxyConfig() - self.adwords_client.cache = suds.cache.NoCache() + self.adwords_client.cache = googleads.common.ZeepServiceProxy.NO_CACHE self.adwords_client.custom_http_headers = False self.opener = mock.Mock() @@ -1787,8 +1624,8 @@ def setUp(self): self.report_downloader.url_opener = self.opener test_dir = os.path.dirname(__file__) - with open(os.path.join( - test_dir, 'test_data/unicode_test_data.txt')) as handler: + test_data_path = os.path.join(test_dir, 'test_data/unicode_test_data.txt') + with open(test_data_path, encoding='utf-8') as handler: self.budget_template = handler.read() def testSetsCustomHeaders(self): @@ -1798,13 +1635,13 @@ class MyOpener(object): opener = MyOpener() self.adwords_client.custom_http_headers = {'X-My-Header': 'abc'} - with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mock_build_opener: + with mock.patch('googleads.adwords.build_opener') as mock_build_opener: mock_build_opener.return_value = opener self.GetReportDownloader() self.assertEqual(opener.addheaders, [('a', 'b'), ('X-My-Header', 'abc')]) - @mock.patch.object(urllib2.OpenerDirector, 'open') + @mock.patch('urllib.request.OpenerDirector.open') def testDownloadReportAsString(self, mock_request): serialize_response = mock.Mock() with mock.patch.object( @@ -1827,23 +1664,21 @@ def testDownloadReportAsString(self, mock_request): def testDownloadReportAsStringWithAwql(self): query = 'SELECT Id FROM Campaign WHERE NAME LIKE \'%Test%\'' file_format = 'CSV' - post_body = six.moves.urllib.parse.urlencode({'__fmt': file_format, + post_body = urlencode({'__fmt': file_format, '__rdquery': query}) - if six.PY3: - post_body = bytes(post_body, 'utf-8') + post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING アングリーバード' report_contents = io.BytesIO() - report_contents.write(report_data.encode('utf-8') if six.PY2 - else bytes(report_data, 'utf-8')) + report_contents.write(bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() fake_response.read.side_effect = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - with mock.patch.object(urllib2, 'Request') as mock_request: + with mock.patch.object(googleads.adwords, 'Request') as mock_request: mock_request_instance = mock.Mock() mock_request.return_value = mock_request_instance mock_request_instance.get_full_url.return_value = 'https://google.com/' @@ -1877,11 +1712,11 @@ def testDownloadReportWithUnicodeReportDataIssue281(self): stream.return_value = open(os.path.join( test_dir, 'test_data/unicode_test_data.txt'), 'rb') report_definition = {'downloadFormat': 'CSV'} - s = six.StringIO() + s = io.StringIO() self.report_downloader.DownloadReport(report_definition, output=s) def testDownloadReportCheckFormat_CSVStringSuccess(self): - output_file = six.StringIO() + output_file = io.StringIO() try: self.report_downloader._DownloadReportCheckFormat('CSV', output_file) @@ -1900,7 +1735,7 @@ def testDownloadReportCheckFormat_GZIPPEDBinaryFileSuccess(self): 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDBytesIOSuccess(self): - output_file = six.BytesIO() + output_file = io.BytesIO() try: self.report_downloader._DownloadReportCheckFormat('GZIPPED_CSV', @@ -1910,16 +1745,13 @@ def testDownloadReportCheckFormat_GZIPPEDBytesIOSuccess(self): 'unexpectedly!') def testDownloadReportCheckFormat_GZIPPEDStringFailure(self): - # This would only fail in Python 3, where StringIO is unicode rather than - # bytes. - if six.PY3: - output_file = six.StringIO() - self.assertRaises(googleads.errors.GoogleAdsValueError, - self.report_downloader._DownloadReportCheckFormat, - 'GZIPPED_CSV', output_file) + output_file = io.StringIO() + self.assertRaises(googleads.errors.GoogleAdsValueError, + self.report_downloader._DownloadReportCheckFormat, + 'GZIPPED_CSV', output_file) def testDownloadReport_failure(self): - output_file = six.StringIO() + output_file = io.StringIO() report_definition = { 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', 'dateRangeType': 'LAST_7_DAYS', @@ -1934,12 +1766,11 @@ def testDownloadReport_failure(self): with mock.patch.object(self.report_downloader.url_opener, 'open') as mock_open: response_data = 'bad stuff happened' - response_fp = six.BytesIO() - response_fp.write(response_data if six.PY2 else bytes( - response_data, 'utf-8')) + response_fp = io.BytesIO() + response_fp.write(bytes(response_data, 'utf-8')) response_fp.seek(0) - mock_open.side_effect = six.moves.urllib.error.HTTPError( + mock_open.side_effect = HTTPError( 'http://abc', '500', 'whoops!', {}, response_fp) with mock.patch.object(self.report_downloader, '_header_handler'): with self.assertRaises(googleads.errors.AdWordsReportError): @@ -1948,29 +1779,27 @@ def testDownloadReport_failure(self): use_raw_enum_values=False) def testDownloadReportWithAwql(self): - output_file = six.StringIO() + output_file = io.StringIO() query = (googleads.adwords.ReportQueryBuilder() .Select('CampaignId').From('CAMPAIGN_PERFORMANCE_REPORT') .Where('CampaignStatus').EqualTo('ENABLED') .Build()) file_format = 'CSV' - post_body = six.moves.urllib.parse.urlencode({'__fmt': file_format, + post_body = urlencode({'__fmt': file_format, '__rdquery': query}) - if six.PY3: - post_body = bytes(post_body, 'utf-8') + post_body = bytes(post_body, 'utf-8') headers = {'Authorization': 'ya29.something'} self.header_handler.GetReportDownloadHeaders.return_value = headers report_data = u'CONTENT STRING 广告客户' - report_contents = six.StringIO() if six.PY2 else io.BytesIO() - report_contents.write(report_data if six.PY2 - else bytes(report_data, 'utf-8')) + report_contents = io.BytesIO() + report_contents.write(bytes(report_data, 'utf-8')) report_contents.seek(0) fake_response = mock.Mock() fake_response.read.side_effect = report_contents.read fake_response.msg = 'fake message' fake_response.code = '200' - with mock.patch.object(urllib2, 'Request') as mock_request: + with mock.patch.object(googleads.adwords, 'Request') as mock_request: mock_request_instance = mock.Mock() mock_request.return_value = mock_request_instance mock_request_instance.get_full_url.return_value = 'https://google.com/' @@ -1998,9 +1827,8 @@ def testExtractError_badRequest(self): '%s%s' '%s') response_data = error_template % (type_, trigger, field_path) - response_fp = six.BytesIO() - response_fp.write(response_data if six.PY2 - else bytes(response_data, 'utf-8')) + response_fp = io.BytesIO() + response_fp.write(bytes(response_data, 'utf-8')) response_fp.seek(0) response.read.side_effect = response_fp.read @@ -2015,9 +1843,8 @@ def testExtractError_badRequest(self): # Check that if the XML fields are empty, this still functions. response_data = error_template % ('', '', '') - response_fp = six.BytesIO() - response_fp.write(response_data if six.PY2 - else bytes(response_data, 'utf-8')) + response_fp = io.BytesIO() + response_fp.write(bytes(response_data, 'utf-8')) response_fp.seek(0) response.read.side_effect = response_fp.read rval = self.report_downloader._ExtractError(response) @@ -2032,9 +1859,8 @@ def testExtractError_malformedBadRequest(self): '1234' '5678' '') - response_fp = six.BytesIO() - response_fp.write(response_data if six.PY2 - else bytes(response_data, 'utf-8')) + response_fp = io.BytesIO() + response_fp.write(bytes(response_data, 'utf-8')) response_fp.seek(0) response.read.side_effect = response_fp.read @@ -2048,8 +1874,7 @@ def testExtractError_notBadRequest(self): response = mock.Mock() response.code = 400 content = 'Page not found!' - response.read.return_value = (content if six.PY2 - else bytes(content, 'utf-8')) + response.read.return_value = (bytes(content, 'utf-8')) rval = self.report_downloader._ExtractError(response) self.assertEqual(response.code, rval.code) @@ -2311,9 +2136,8 @@ def testCopyConstructor(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause can show fields listed in any orders. - six.assertCountEqual( - self, selected_fields, - [field.strip() for field in match.group(1).split(',')]) + self.assertCountEqual(selected_fields, + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testFailUsingCopyConstructor(self): @@ -2332,9 +2156,8 @@ def testBuild(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause can show fields listed in any orders. - six.assertCountEqual( - self, selected_fields, - [field.strip() for field in match.group(1).split(',')]) + self.assertCountEqual(selected_fields, + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testBuild_duplicateSelectedFieldsRetainOnlyUnique(self): @@ -2347,9 +2170,8 @@ def testBuild_duplicateSelectedFieldsRetainOnlyUnique(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause retains only unique fields. - six.assertCountEqual( - self, set(selected_fields), - [field.strip() for field in match.group(1).split(',')]) + self.assertCountEqual(set(selected_fields), + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testBuild_whereConditions(self): @@ -2369,9 +2191,8 @@ def testBuild_whereConditions(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause can show fields listed in any orders. - six.assertCountEqual( - self, selected_fields, - [field.strip() for field in match.group(1).split(',')]) + self.assertCountEqual(selected_fields, + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testBuild_orderByDesc(self): @@ -2387,9 +2208,8 @@ def testBuild_orderByDesc(self): match = re.match(awql_regex, str(actual_query)) # The SELECT clause can show fields listed in any orders. - six.assertCountEqual( - self, selected_fields, - [field.strip() for field in match.group(1).split(',')]) + self.assertCountEqual(selected_fields, + [field.strip() for field in match.group(1).split(',')]) self.assertRegexpMatches(str(actual_query), awql_regex) def testBuild_selectIsNone(self): diff --git a/tests/common_test.py b/tests/common_test.py index 42c2bd4f..0b3cf350 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -26,9 +26,6 @@ from pyfakefs import fake_tempfile import mock import requests.exceptions -import six -import suds -import suds.cache import yaml import zeep.cache @@ -39,7 +36,6 @@ import zeep.exceptions -URL_REQUEST_PATH = 'urllib2' if six.PY2 else 'urllib.request' TEST_DIR = os.path.dirname(__file__) CURRENT_VERSION = 'v201902' @@ -167,7 +163,6 @@ def testLoadFromStorage(self): yaml_fname = self._CreateYamlFile( {'one': {'needed': 'd', 'keys': 'e', 'other': 'f'}, googleads.common._LOGGING_KEY: logging_config, - googleads.common.SOAP_IMPLEMENTATION_KEY: 'suds', googleads.common.CUSTOM_HEADERS_KEY: {'X-My-Header': 'abc'}}, 'one', self._OAUTH_INSTALLED_APP_DICT) with mock.patch('googleads.oauth2.GoogleRefreshTokenClient') as mock_client: @@ -187,7 +182,6 @@ def testLoadFromStorage(self): 'needed': 'd', 'keys': 'e', 'other': 'f', 'proxy_config': proxy_config.return_value, googleads.common.ENABLE_COMPRESSION_KEY: False, - googleads.common.SOAP_IMPLEMENTATION_KEY: 'suds', googleads.common.CUSTOM_HEADERS_KEY: { 'X-My-Header': 'abc'}}, rval) @@ -228,164 +222,10 @@ def _CreateYamlDoc(self, data, insert_oauth2_key=None, oauth_dict=None): data[key].update(oauth_dict) return yaml.dump(data) - def testExtractRequestSummaryFieldsForAdWords(self): - root = suds.sax.element.Element('root', parent=None) - client_customer_id = '111-222-3333' - ccid_element = suds.sax.element.Element('clientCustomerId', parent=None) - ccid_element.text = client_customer_id - request_header_element = suds.sax.element.Element('RequestHeader', - parent=None) - header_element = suds.sax.element.Element('Header', parent=None) - method_name = 'someMethodName' - method_element = suds.sax.element.Element(method_name) - body = suds.sax.element.Element('Body', parent=None) - request_header_element.append(ccid_element) - header_element.append(request_header_element) - body.append(method_element) - root.append((header_element, body)) - expected_result = { - 'methodName': method_name, - 'clientCustomerId': client_customer_id - } - - self.assertEqual(expected_result, - googleads.common._ExtractRequestSummaryFields(root)) - - def testExtractRequestSummaryFieldsForAdManager(self): - root = suds.sax.element.Element('root', parent=None) - network_code = '111111111' - nc_element = suds.sax.element.Element('networkCode', parent=None) - nc_element.text = network_code - request_header_element = suds.sax.element.Element('RequestHeader', - parent=None) - header_element = suds.sax.element.Element('Header', parent=None) - method_name = 'someMethodName' - method_element = suds.sax.element.Element(method_name) - body = suds.sax.element.Element('Body', parent=None) - request_header_element.append(nc_element) - header_element.append(request_header_element) - body.append(method_element) - root.append((header_element, body)) - expected_result = { - 'methodName': method_name, - 'networkCode': network_code - } - - self.assertEqual(expected_result, - googleads.common._ExtractRequestSummaryFields(root)) - - def testExtractResponseSummaryFieldsWithAdWordsFields(self): - root = suds.sax.element.Element('Envelope', parent=None) - doc = suds.sax.document.Document(root=root) - request_id = '0' - response_time = '1000' - service_name = 'SomeService' - method_name = 'someMethodName' - operations = '0' - rid_element = suds.sax.element.Element('requestId', parent=None) - rid_element.text = request_id - rt_element = suds.sax.element.Element('responseTime', parent=None) - rt_element.text = response_time - service_element = suds.sax.element.Element('serviceName', parent=None) - service_element.text = service_name - method_element = suds.sax.element.Element('methodName', parent=None) - method_element.text = method_name - ops_element = suds.sax.element.Element('operations', parent=None) - ops_element.text = operations - response_header_element = suds.sax.element.Element('ResponseHeader', - parent=None) - header_element = suds.sax.element.Element('Header', parent=None) - body = suds.sax.element.Element('Body', parent=None) - response_header_element.append((rid_element, rt_element, service_element, - method_element, ops_element)) - header_element.append(response_header_element) - root.append((header_element, body)) - expected_result = { - 'requestId': request_id, - 'responseTime': response_time, - 'isFault': False, - 'serviceName': service_name, - 'methodName': method_name, - 'operations': operations - } - - self.assertEqual(expected_result, - googleads.common._ExtractResponseSummaryFields(doc)) - - def testExtractResponseSummaryFieldsWithFault(self): - root = suds.sax.element.Element('Envelope', parent=None) - doc = suds.sax.document.Document(root=root) - request_id = '0' - response_time = '1000' - fault_string = 'I AM ERROR' - rid_element = suds.sax.element.Element('requestId', parent=None) - rid_element.text = suds.sax.text.Text(request_id) - rt_element = suds.sax.element.Element('responseTime', parent=None) - rt_element.text = suds.sax.text.Text(response_time) - response_header_element = suds.sax.element.Element('ResponseHeader', - parent=None) - header_element = suds.sax.element.Element('Header', parent=None) - response_header_element.append((rid_element, rt_element)) - header_element.append(response_header_element) - fault_element = suds.sax.element.Element('Fault', parent=None) - fault_string_element = suds.sax.element.Element('faultstring', parent=None) - fault_string_element.text = suds.sax.text.Text(fault_string) - body = suds.sax.element.Element('Body', parent=None) - fault_element.append(fault_string_element) - body.append(fault_element) - root.append((header_element, body)) - expected_result = { - 'requestId': request_id, - 'responseTime': response_time, - 'isFault': True, - 'faultMessage': fault_string - } - - self.assertEqual(expected_result, - googleads.common._ExtractResponseSummaryFields(doc)) - - def testExtractResponseSummaryFieldsWithoutFault(self): - root = suds.sax.element.Element('Envelope', parent=None) - doc = suds.sax.document.Document(root=root) - request_id = '0' - response_time = '1000' - rid_element = suds.sax.element.Element('requestId', parent=None) - rid_element.text = request_id - rt_element = suds.sax.element.Element('responseTime', parent=None) - rt_element.text = response_time - response_header_element = suds.sax.element.Element('ResponseHeader', - parent=None) - header_element = suds.sax.element.Element('Header', parent=None) - body = suds.sax.element.Element('Body', parent=None) - response_header_element.append((rid_element, rt_element)) - header_element.append(response_header_element) - root.append((header_element, body)) - expected_result = { - 'requestId': request_id, - 'responseTime': response_time, - 'isFault': False - } - - self.assertEqual(expected_result, - googleads.common._ExtractResponseSummaryFields(doc)) - - def testCommonClient_deprecatedWarningLoggerByMicroValue(self): - test_major_value = 2 - test_minor_value = 7 - test_micro_value = 6 - with mock.patch('googleads.common._PY_VERSION_MAJOR', test_major_value): - with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): - with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): - with mock.patch('googleads.common._logger') as mock_logger: - googleads.common.CommonClient() - mock_logger.warning.assert_called_once_with( - googleads.common._DEPRECATED_VERSION_TEMPLATE, - test_major_value, test_minor_value, test_micro_value) - def testLoadFromString_deprecatedWarningLoggerByMinorValue(self): - test_major_value = 2 - test_minor_value = 6 - test_micro_value = 9 + test_major_value = 3 + test_minor_value = 4 + test_micro_value = 5 with mock.patch('googleads.common._PY_VERSION_MAJOR', test_major_value): with mock.patch('googleads.common._PY_VERSION_MINOR', test_minor_value): with mock.patch('googleads.common._PY_VERSION_MICRO', test_micro_value): @@ -492,13 +332,6 @@ def testLoadFromString_passesWithHTTPAndHTTPSProxy(self): googleads.common.ENABLE_COMPRESSION_KEY: False, googleads.common.CUSTOM_HEADERS_KEY: None}, rval) - def testHTTPSProxyExtendsSSLSockTimeout(self): - proxy_config = mock.MagicMock() - with mock.patch('suds.transport.http.' - 'HttpTransport.__init__') as mock_transport: - googleads.common._SudsProxyTransport(1000, proxy_config) - self.assertEqual(mock_transport.call_args_list[0][1]['timeout'], 1000) - def testLoadFromString_passesWithHTTPProxy(self): yaml_doc = self._CreateYamlDoc( {'adwords': {}, @@ -834,95 +667,6 @@ def testGenerateLibSigWithUtilitiesDisabled(self): googleads.common._PYTHON_VERSION), googleads.common.GenerateLibSig(my_name)) - def testPackForSuds(self): - factory = mock.Mock() - - # Test that anything other than list, tuple, and dict pass right through. - self.assertEqual('input', googleads.common._PackForSuds('input', factory)) - self.assertEqual(set([1]), - googleads.common._PackForSuds(set([1]), factory)) - - # Test that lists not containing dicts with xsi types return the same - # values, and test that the input list was not modified. - input_list = ['1', set([3]), {'moo': 'cow'}] - self.assertEqual(['1', set([3]), {'moo': 'cow'}], - googleads.common._PackForSuds(input_list, factory)) - self.assertEqual(['1', set([3]), {'moo': 'cow'}], input_list) - - # Test that dicts without xsi types return the same values, and test that - # the input dict was not modified - input_dict = {'1': 'moo', frozenset([2]): ['val']} - self.assertEqual({'1': 'moo', frozenset([2]): ['val']}, - googleads.common._PackForSuds(input_dict, factory)) - self.assertEqual({'1': 'moo', frozenset([2]): ['val']}, input_dict) - - # Now it gets interesting... Test that a dictionary with xsi type gets - # changed into an object. Test that the input dict is unmodified. - input_dict = {'xsi_type': 'EliteCampaign', 'name': 'Sales', 'id': 123456, - 'metadata': {'a': 'b'}} - factory.create.return_value = mock.MagicMock() - factory.create.return_value.__iter__.return_value = iter( - [('id', 0), ('name', 1), ('metadata', 2), ('Campaign.Type', 3), - ('status', 4)]) - - rval = googleads.common._PackForSuds(input_dict, factory) - factory.create.assert_called_once_with('EliteCampaign') - self.assertEqual('Sales', rval.name) - self.assertEqual(123456, rval.id) - self.assertEqual({'a': 'b'}, rval.metadata) - self.assertEqual('EliteCampaign', getattr(rval, 'Campaign.Type')) - self.assertEqual(None, rval.status) - self.assertEqual({'xsi_type': 'EliteCampaign', 'name': 'Sales', - 'id': 123456, 'metadata': {'a': 'b'}}, input_dict) - - # Test that this all works recursively. Nest dictionaries in dictionaries in - # lists in classes. - factory = mock.Mock() - factory.create.side_effect = [mock.MagicMock(), mock.MagicMock()] - input_list = [{'xsi_type': 'EliteCampaign', 'name': 'Sales', 'id': None, - 'metadata': {'xsi_type': 'metadata', 'a': {'b': 'c'}}}, - {'i do not have': 'a type'}] - rval = googleads.common._PackForSuds(input_list, factory) - factory.create.assert_any_call('EliteCampaign') - factory.create.assert_any_call('metadata') - self.assertEqual(len(rval), 2) - self.assertEqual('Sales', rval[0].name) - self.assertIsInstance(rval[0].id, suds.null) - self.assertEqual({'b': 'c'}, rval[0].metadata.a) - self.assertEqual({'i do not have': 'a type'}, rval[1]) - self.assertEqual( - [{'xsi_type': 'EliteCampaign', 'name': 'Sales', 'id': None, - 'metadata': {'xsi_type': 'metadata', 'a': {'b': 'c'}}}, - {'i do not have': 'a type'}], input_list) - - def testPackForSuds_applyCustomPacker(self): - class CustomPacker(googleads.common.SoapPacker): - @classmethod - def Pack(cls, obj, version): - if isinstance(obj, numbers.Number): - return {'xsi_type': 'Integer', 'value': str(int(obj))} - return obj - - factory = mock.Mock() - factory.create.return_value = mock.MagicMock() - factory.create.return_value.__iter__.return_value = iter( - [('Number.Type', 0), ('value', 1)]) - number = 3.14159265358979323846264 - - rval = googleads.common._PackForSuds(number, factory, CustomPacker, - CURRENT_VERSION) - self.assertEqual('Integer', getattr(rval, 'Number.Type')) - self.assertEqual('3', rval.value) - - def testPackForSuds_secondNamespace(self): - factory = mock.Mock() - factory.create.side_effect = [suds.TypeNotFound(''), mock.MagicMock()] - input_list = {'xsi_type': 'EliteCampaign', 'name': 'Sales'} - rval = googleads.common._PackForSuds(input_list, factory) - factory.create.assert_any_call('EliteCampaign') - factory.create.assert_any_call('ns0:EliteCampaign') - self.assertEqual('Sales', rval.name) - @contextmanager def mock_zeep_client(): @@ -1124,7 +868,7 @@ def setUp(self): def testPackArgumentsPrimitivesOnly(self): result = self.zeep_client._PackArguments('getReportJobStatus', [5]) - six.assertCountEqual(self, result, [5]) + self.assertCountEqual(result, [5]) def testPackArgumentsWithSimpleDict(self): opts = { @@ -1201,7 +945,6 @@ def testPackArgumentsBase64Warning(self): with mock.patch('googleads.common._logger'): self.zeep_client._PackArgumentsHelper(b64_type, data, False) - self.assertTrue(len(googleads.common._logger.warn.mock_calls)) def testPackArgumentsMultipleSchemas(self): header_handler = mock.Mock() @@ -1225,241 +968,6 @@ def testPackArgumentsBadType(self): self.zeep_client._PackArgumentsHelper(element, data, False) -class SudsServiceProxyTest(unittest.TestCase): - """Tests for the googleads.common.SudsServiceProxy class.""" - - def setUp(self): - self.fake_version = 'ignored' - - def testCreateSudsClient(self): - class MyCache(suds.cache.Cache): - pass - - cache = MyCache() - header_handler = mock.Mock() - packer = mock.Mock() - proxy_config = mock.Mock() - - with mock.patch('googleads.common.suds.client.Client') as mock_suds_client: - mock_suds_client.return_value = 'suds_client' - - with mock.patch('googleads.common.LoggingMessagePlugin') as mock_logging: - mock_logging.return_value = 'logging' - - with mock.patch('googleads.common' - '._SudsProxyTransport') as mock_transport: - mock_transport.return_value = 'transport' - - suds_wrapper = googleads.common.SudsServiceProxy( - 'https://endpoint', header_handler, packer, proxy_config, - 1000, self.fake_version, cache) - - mock_transport.assert_called_once_with(1000, proxy_config) - mock_suds_client.assert_called_once_with( - 'https://endpoint', timeout=1000, cache=cache, - transport='transport', plugins=['logging']) - self.assertEqual(suds_wrapper.suds_client, 'suds_client') - - @contextmanager - def mock_suds_api(self): - with mock.patch('googleads.common._SudsProxyTransport'), \ - mock.patch('googleads.common.suds.client.Client') as mock_suds_client: - yield mock_suds_client - - def testSudsErrorRaisesGoogleError(self): - with self.mock_suds_api() as mock_suds_client: - mock_suds_client.side_effect = suds.transport.TransportError(None, None) - with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError): - googleads.common.SudsServiceProxy( - 'https://endpoint', None, None, None, 1000, None) - - def testSchemaHelperRaisesGoogleError(self): - with self.mock_suds_api() as mock_suds_client: - mock_suds_client.side_effect = suds.transport.TransportError(None, None) - - with self.assertRaises(googleads.errors.GoogleAdsSoapTransportError): - googleads.common.SudsSchemaHelper(None, None, None, 100, None) - - - def testGetMethod(self): - header_handler = mock.Mock() - wrapped_method = mock.Mock() - wrapped_method.return_value = 'wrap_result' - - with self.mock_suds_api() as mock_suds_client_class: - mock_suds_client = mock.MagicMock() - mock_suds_client_class.return_value = mock_suds_client - - suds_wrapper = googleads.common.SudsServiceProxy( - 'https://endpoint', header_handler, None, None, 1000, - self.fake_version, None - ) - - with mock.patch.object(suds_wrapper, '_CreateMethod') as mock_create: - mock_create.return_value = wrapped_method - - services_dict = {'method1': True} - suds_contains_method = (mock_suds_client.wsdl.services[0].ports[0] - .methods.__contains__) - suds_contains_method.side_effect = services_dict.__contains__ - result = suds_wrapper.method1() - self.assertEqual(result, 'wrap_result') - - @contextmanager - def get_suds_api_with_mocked_method(self, mock_method): - header_handler = mock.Mock() - with self.mock_suds_api() as mock_suds_client_class: - mock_suds_client = mock.MagicMock() - mock_suds_client_class.return_value = mock_suds_client - - suds_wrapper = googleads.common.SudsServiceProxy( - 'https://endpoint', header_handler, None, None, 1000, None - ) - with mock.patch('googleads.common._ExtractResponseSummaryFields'): - with mock.patch.object(suds_wrapper, - '_WsdlHasMethod') as mock_has_method: - mock_has_method.return_value = True - - suds_wrapper.suds_client.service.method1 = mock_method - suds_wrapper._method_proxies['method1'] = ( - suds_wrapper._CreateMethod('method1')) - - yield suds_wrapper - - def testNoDetailError(self): - mock_method = mock.Mock() - mock_document = mock.Mock() - - class MockFault(object): - faultstring = 'abc' - - mock_method.side_effect = suds.WebFault(MockFault(), mock_document) - - with self.get_suds_api_with_mocked_method(mock_method) as suds_wrapper: - with self.assertRaises(googleads.errors.GoogleAdsServerFault) as e: - suds_wrapper.method1() - - self.assertEqual(len(e.exception.errors), 0) - self.assertEqual(e.exception.document, mock_document) - self.assertIn('abc', str(e.exception)) - - def testEmptyListError(self): - mock_method = mock.Mock() - mock_document = mock.Mock() - - class MockFault(object): - faultstring = 'abc' - detail = mock.Mock() - - def __init__(self): - self.detail.ApiExceptionFault.errors = None - - mock_fault = MockFault() - - mock_method.side_effect = suds.WebFault(mock_fault, mock_document) - - with self.get_suds_api_with_mocked_method(mock_method) as suds_wrapper: - with self.assertRaises(googleads.errors.GoogleAdsServerFault) as e: - suds_wrapper.method1() - self.assertEqual(len(e.exception.errors), 0) - self.assertEqual(e.exception.document, mock_document) - self.assertIn('abc', str(e.exception)) - - def testFaultWithErrors(self): - mock_method = mock.Mock() - mock_document = mock.Mock() - - class MockFault(object): - faultstring = 'abc' - detail = mock.Mock() - - def __init__(self): - self.detail.ApiExceptionFault.errors = ['1', '2', '3'] - - mock_fault = MockFault() - - mock_method.side_effect = suds.WebFault(mock_fault, mock_document) - - with self.get_suds_api_with_mocked_method(mock_method) as suds_wrapper: - with self.assertRaises(googleads.errors.GoogleAdsServerFault) as e: - suds_wrapper.method1() - six.assertCountEqual(self, e.exception.errors, ['1', '2', '3']) - self.assertEqual(e.exception.document, mock_document) - self.assertIn('abc', str(e.exception)) - - def testGetRequestXML(self): - mock_method = mock.Mock() - mock_method.return_value.envelope = '' - - with self.get_suds_api_with_mocked_method(mock_method) as suds_wrapper, \ - mock.patch.object(suds_wrapper, 'SetHeaders'): - ops = ['abc', '123'] - result = suds_wrapper.GetRequestXML('method1', ops) - toggle_calls = [mock.call(nosend=True), mock.call(nosend=False)] - suds_wrapper.suds_client.set_options.assert_has_calls(toggle_calls) - self.assertEqual(result.tag, 'a') - - def testCreateSoapElementForType(self): - with self.mock_suds_api(): - suds_wrapper = googleads.common.SudsServiceProxy( - 'https://endpoint', None, None, None, 1000, self.fake_version, None) - suds_wrapper.suds_client.factory.create.return_value = 'result' - - result = suds_wrapper.CreateSoapElementForType('MyType') - self.assertEqual(result, 'result') - - def testSetHeaders(self): - with self.mock_suds_api(): - suds_wrapper = googleads.common.SudsServiceProxy( - 'https://endpoint', None, None, None, 1000, self.fake_version, None) - - suds_wrapper.SetHeaders('soap', 'http') - suds_wrapper.suds_client.set_options.assert_called_once_with( - soapheaders='soap', headers='http') - - def testBadCache(self): - with self.mock_suds_api(), \ - self.assertRaises(googleads.errors.GoogleAdsValueError): - googleads.common.SudsServiceProxy( - 'https://endpoint', None, None, None, 1000, 'not_a_suds_cache', - self.fake_version) - - def testSchemaHelperBadCache(self): - with self.assertRaises(googleads.errors.GoogleAdsValueError): - googleads.common.SudsSchemaHelper(None, None, None, None, 'not_cache') - - -class LoggingMessagePluginTest(unittest.TestCase): - """Tests for the googleads.common.LoggingMessagePlugin class.""" - - def setUp(self): - self.logging_message_plugin = googleads.common.LoggingMessagePlugin() - - def testMarshalled(self): - envelope = 'envelope' - marshalled_context = mock.Mock() - marshalled_context.envelope = envelope - - with mock.patch('googleads.common._logger') as mock_logger: - mock_logger.isEnabledFor.return_value = True - with mock.patch( - 'googleads.common._ExtractRequestSummaryFields') as mk_ext: - self.logging_message_plugin.marshalled(marshalled_context) - mk_ext.assert_called_once_with(envelope) - - def testParsed(self): - reply = 'reply' - parsed_context = mock.Mock() - parsed_context.reply = reply - - with mock.patch('googleads.common._logger') as mock_logger: - mock_logger.isEnabledFor.return_value = True - with mock.patch( - 'googleads.common._ExtractResponseSummaryFields') as mk_ext: - self.logging_message_plugin.parsed(parsed_context) - mk_ext.assert_called_once_with(reply) - - class ProxyConfigTest(unittest.TestCase): """Tests for the googleads.common.ProxyConfig class.""" @@ -1472,71 +980,27 @@ def testBuildOpenerWithConfig(self): proxy_config = googleads.common.ProxyConfig( https_proxy=self.proxy_no_credentials) - with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mck_build_opener: - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as mck_https_hndlr: - with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as mck_prxy_hndlr: - mck_https_hndlr_instance = mock.Mock() - mck_https_hndlr.return_value = mck_https_hndlr_instance - mck_prxy_hndlr_instance = mock.Mock() - mck_prxy_hndlr.return_value = mck_prxy_hndlr_instance - proxy_config.BuildOpener() - mck_build_opener.assert_called_once_with( - *[mck_https_hndlr_instance, mck_prxy_hndlr_instance]) + with mock.patch('googleads.common.build_opener') as mck_build_opener, \ + mock.patch('googleads.common.HTTPSHandler') as mck_https_hndlr, \ + mock.patch('googleads.common.ProxyHandler') as mck_prxy_hndlr: + mck_https_hndlr_instance = mock.Mock() + mck_https_hndlr.return_value = mck_https_hndlr_instance + mck_prxy_hndlr_instance = mock.Mock() + mck_prxy_hndlr.return_value = mck_prxy_hndlr_instance + proxy_config.BuildOpener() + mck_build_opener.assert_called_once_with( + *[mck_https_hndlr_instance, mck_prxy_hndlr_instance]) def testBuildOpenerWithDefaultConfig(self): proxy_config = googleads.common.ProxyConfig() - with mock.patch('%s.build_opener' % URL_REQUEST_PATH) as mck_build_opener: - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as mock_https_hndlr: + with mock.patch('googleads.common.build_opener') as mck_build_opener, \ + mock.patch('googleads.common.HTTPSHandler') as mock_https_hndlr: mock_https_hndlr_instance = mock.Mock mock_https_hndlr.return_value = mock_https_hndlr_instance proxy_config.BuildOpener() mck_build_opener.assert_called_once_with(*[mock_https_hndlr_instance]) - def testProxyConfigGetHandlersWithNoProxyOrSSLContext(self): - proxy_config = googleads.common.ProxyConfig() - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: - https_handler_instance = mock.Mock() - https_handler.return_value = https_handler_instance - - transport = googleads.common._SudsProxyTransport(0, proxy_config) - self.assertIn(https_handler_instance, transport.handlers) - - def testProxyConfigGetHandlersWithProxy(self): - with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: - proxy_handler_instance = mock.Mock() - proxy_handler.return_value = proxy_handler_instance - proxy_config = googleads.common.ProxyConfig( - http_proxy=self.proxy_no_credentials) - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: - https_handler_instance = mock.Mock() - https_handler.return_value = https_handler_instance - - transport = googleads.common._SudsProxyTransport(0, proxy_config) - self.assertEqual(transport.handlers, - [https_handler_instance, proxy_handler_instance]) - proxy_handler.assert_called_once_with( - {'http': self.proxy_no_credentials}) - - def testProxyConfigGetHandlersWithProxyAndSLLContext(self): - with mock.patch('googleads.common.ProxyConfig._InitSSLContext') as ssl_ctxt: - ssl_ctxt.return_value = 'CONTEXT' - with mock.patch('%s.ProxyHandler' % URL_REQUEST_PATH) as proxy_handler: - proxy_handler.return_value = mock.Mock() - with mock.patch('%s.HTTPSHandler' % URL_REQUEST_PATH) as https_handler: - https_handler.return_value = mock.Mock() - - proxy_config = googleads.common.ProxyConfig( - https_proxy=self.proxy_no_credentials) - transport = googleads.common._SudsProxyTransport(0, proxy_config) - self.assertEqual(transport.handlers, - [https_handler.return_value, - proxy_handler.return_value]) - proxy_handler.assert_called_once_with( - {'https': self.proxy_no_credentials}) - https_handler.assert_called_once_with( - context=ssl_ctxt.return_value) - def testProxyConfigWithNoProxy(self): proxy_config = googleads.common.ProxyConfig() self.assertEqual(proxy_config.proxies, {}) @@ -1575,66 +1039,5 @@ def testProxyConfigWithHTTPAndHTTPSProxy(self): self.assertEqual(proxy_config.disable_certificate_validation, True) -class MockHeaders(object): - - def __init__(self, d): - self.dict = d - - # If testing on Python 3, add get method to better mimic the - # http.client.HTTPMessage behavior. - if six.PY3: - def py3_get(s): - return self.dict.get(s) - self.get = py3_get - - -class TestSudsRequestPatcher(unittest.TestCase): - - def testInflateSuccessfulRequestIfGzipped(self): - with mock.patch('suds.transport.http.HttpTransport.getcookies'): - with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: - with mock.patch('gzip.GzipFile.read') as mock_read: - resp_fp = six.BytesIO() - resp_fp.write(b'abc') - resp_fp.flush() - resp_fp.seek(0) - resp = six.moves.urllib.response.addinfourl( - resp_fp, MockHeaders({'content-encoding': 'gzip'}), - 'https://example.com', code=200) - mock_open.return_value = resp - - req = suds.transport.Request('https://example.com', - message='hello world') - suds.transport.http.HttpTransport().send(req) - mock_read.assert_called_once() - - def testInflateFailedRequestIfGzipped(self): - - with mock.patch('suds.transport.http.HttpTransport.getcookies'): - with mock.patch('%s.OpenerDirector.open' % URL_REQUEST_PATH) as mock_open: - with mock.patch('gzip.GzipFile') as mock_gzip: - gzip_instance_mock = mock.MagicMock - mock_gzip.return_value = gzip_instance_mock - resp_fp = six.BytesIO() - resp_fp.write(b'abc') - resp_fp.flush() - resp_fp.seek(0) - resp = six.moves.urllib.response.addinfourl( - resp_fp, MockHeaders({'content-encoding': 'gzip'}), - 'https://example.com', code=200) - - def fail_to_open(*args, **kwargs): - raise six.moves.urllib.error.HTTPError( - 'https://example.com', 500, 'oops!', - {'content-encoding': 'gzip'}, resp) - mock_open.side_effect = fail_to_open - - req = suds.transport.Request('https://example.com', - message='hello world') - with self.assertRaises(suds.transport.TransportError) as exc: - suds.transport.http.HttpTransport().send(req) - self.assertEqual(exc.exception.fp, gzip_instance_mock) - - if __name__ == '__main__': unittest.main() diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index 56cf9dd2..c6dd5fa8 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -19,7 +19,6 @@ import unittest import mock -import six import googleads.common import googleads.errors import googleads.oauth2 @@ -30,9 +29,6 @@ from google.oauth2.credentials import Credentials -_BUILTIN_PATH = '__builtin__' if six.PY2 else 'builtins' - - class GetAPIScopeTest(unittest.TestCase): """Tests for the googleads.oauth2.GetAPIScope function.""" @@ -250,7 +246,7 @@ def refresh(request): self.mock_credentials_instance.apply = mock.Mock(side_effect=apply) self.mock_credentials_instance.refresh = mock.Mock(side_effect=refresh) - with mock.patch('%s.open' % _BUILTIN_PATH, self.fake_open): + with mock.patch('builtins.open', self.fake_open): with mock.patch('google.oauth2.service_account.Credentials', self.mock_credentials): self.sa_client = googleads.oauth2.GoogleServiceAccountClient( diff --git a/tests/test_data/batch_job_util_raw_request_template.txt b/tests/test_data/batch_job_util_raw_request_template.txt index fd7e0e6f..56a88638 100644 --- a/tests/test_data/batch_job_util_raw_request_template.txt +++ b/tests/test_data/batch_job_util_raw_request_template.txt @@ -4,7 +4,7 @@ 000-000-0000 xxxxxxxxxxxxxxxxxxxx - notarealemail@fake.com (AwApi-Python, googleads/3.8.0, Python/2.7.6) + notarealemail@fake.com (AwApi-Python, googleads/3.8.0, Python/3.6.7) false false diff --git a/tests/testing.py b/tests/testing.py index 2757a64e..71d23912 100644 --- a/tests/testing.py +++ b/tests/testing.py @@ -31,41 +31,3 @@ class CleanUtilityRegistryTestCase(unittest.TestCase): def tearDown(self): """Ensures that the UtilityRegistry is cleared between tests.""" googleads.common._utility_registry.Clear() - -_SOAP_BACKENDS = ['suds', 'zeep'] - - -def _CreatePatchedSetUp(func): - """Create a setUp function that includes the SOAP implementation. - - Args: - func: A reference to the original setUp function. - - Returns: - The result of func called with soap_impl. - """ - @functools.wraps(func) - def SetUp(self): - soap_impl = 'suds' if '_suds' in str(self) else 'zeep' - return func(self, soap_impl) - return SetUp - - -def MultiBackendTest(cls): - """A decorator that patches a test suite to test with zeep and suds. - - Args: - cls: The test suite to patch - - Returns: - The patched suite. - """ - for name, func in list(cls.__dict__.items()): - if name.startswith('test'): - for backend in _SOAP_BACKENDS: - # Create a new test with _suds and _zeep - setattr(cls, '%s_%s' % (name, backend), func) - # Delete the original test - delattr(cls, name) - cls.setUp = _CreatePatchedSetUp(cls.setUp) - return cls diff --git a/tests/util_test.py b/tests/util_test.py index 276b60ef..93dcada0 100644 --- a/tests/util_test.py +++ b/tests/util_test.py @@ -25,22 +25,12 @@ import googleads.util from lxml import etree import mock -import six -import suds -import suds.transport -from . import testing -_HTTP_CLIENT_PATH = 'httplib' if six.PY2 else 'http.client' - - -@testing.MultiBackendTest class PatchesTest(unittest.TestCase): """Tests for the PatchHelper utility.""" - def setUp(self, soap_impl): - self.soap_impl = soap_impl - + def setUp(self): oauth_header = {'Authorization': 'header'} oauth2_client = mock.Mock() oauth2_client.CreateHttpHeader.return_value = dict(oauth_header) @@ -51,12 +41,12 @@ def setUp(self, soap_impl): user_agent = '4M153rAb13p1l30F53CR37s' self.adwords_client = googleads.adwords.AdWordsClient( dev_token, oauth2_client, user_agent, - client_customer_id=client_customer_id, soap_impl=soap_impl) + client_customer_id=client_customer_id) # AdWordsClient setup (compression enabled) self.adwords_client_with_compression = googleads.adwords.AdWordsClient( dev_token, oauth2_client, user_agent, client_customer_id=client_customer_id, - enable_compression=True, soap_impl=soap_impl) + enable_compression=True) self.adwords_version = sorted(googleads.adwords._SERVICE_MAP.keys())[-1] self.adwords_namespace_partial = ( 'https://adwords.google.com/api/adwords/%s/' + self.adwords_version) @@ -65,7 +55,7 @@ def setUp(self, soap_impl): network_code = '12345' application_name = 'application name' self.ad_manager_client = googleads.ad_manager.AdManagerClient( - oauth2_client, application_name, network_code, soap_impl=soap_impl) + oauth2_client, application_name, network_code) self.ad_manager_version = sorted( googleads.ad_manager._SERVICE_MAP.keys())[-1] @@ -73,163 +63,20 @@ def setUp(self, soap_impl): 'https://www.google.com/apis/ads/publisher/%s' % self.ad_manager_version) - def testPatchedSudsJurkoAppender(self): - """Tests to confirm that the appender no longer removes empty objects.""" - # Create a fake query & statement - order_id = 1 - values = [{ - 'key': 'orderId', - 'value': { - 'xsi_type': 'NumberValue', - 'value': order_id - } - }, { - 'key': 'status', - 'value': { - 'xsi_type': 'TextValue', - 'value': 'NEEDS_CREATIVES' - } - }] - query = 'WHERE orderId = :orderId AND status = :status' - statement = googleads.ad_manager.FilterStatement(query, values) - - line_item_service = self.ad_manager_client.GetService('LineItemService') - - line_item_action = {'xsi_type': 'ActivateLineItems'} - request = line_item_service.GetRequestXML( - 'performLineItemAction', line_item_action, statement.ToStatement()) - - line_item_action = request.find( - './/{%s}lineItemAction' % self.ad_manager_namespace) - - # Assert that the request includes the action. - self.assertIsNotNone(line_item_action) - - def testPatchedSudsJurkoAppenderIssue63(self): - """Verifies that issue 63 has been resolved with the patch.""" - # Create a fake operation to set a Keyword's finalMobileUrls and finalUrls - # to a blank value. In the bug, these fields would be excluded from the - # output. - operations = [{ - 'operator': 'SET', - 'operand': { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': 1, - 'criterion': { - 'id': 123456, - 'xsi_type': 'Keyword', - 'type': 'KEYWORD', - 'matchType': 'BROAD', - 'text': 'I AM ERROR', - }, - # These two fields should appear in the request. - 'finalMobileUrls': {'urls': []}, - 'finalUrls': {'urls': []} - } - }] - adgroup_criterion_service = self.adwords_client.GetService( - 'AdGroupCriterionService') - request = adgroup_criterion_service.GetRequestXML('mutate', operations) - final_mobile_urls = request.find('.//{%s}finalMobileUrls' % - self.adwords_namespace_partial % 'cm') - final_urls = request.find('.//{%s}finalUrls' % - self.adwords_namespace_partial % 'cm') - # Assert that the request includes the empty urls. - self.assertIsNotNone(final_mobile_urls) - self.assertIsNotNone(final_urls) - - def testPatchedSudsJurkoAppenderIssue78(self): - """Verifies that issue 78 has been resolved with the patch.""" - # Create a fake customer that contains only an empty value for the - # trackingUrl template. In the bug, this would be excluded from the output. - customer = {'trackingUrlTemplate': '', 'xsi_type': 'Customer'} - customer_service = self.adwords_client.GetService('CustomerService') - request = customer_service.GetRequestXML('mutate', customer) - tracking_url_template = request.find( - './/{%s}trackingUrlTemplate' % self.adwords_namespace_partial % 'mcm') - # Assert that the request includes the empty trackingUrlTemplate. - self.assertIsNotNone(tracking_url_template) - - def testSudsJurkoSendWithCompression(self): - """Verifies that the patched HttpTransport.send can decode gzip response.""" - # Not applicable to zeep - if self.soap_impl == 'zeep': - return - - test_dir = os.path.dirname(__file__) - cs = self.adwords_client_with_compression.GetService('CampaignService') - - with mock.patch('suds.transport.http.HttpTransport.u2open'): - with mock.patch('suds.transport.Reply') as mock_reply: - with open(os.path.join( - test_dir, 'test_data/gzip_response.bin'), 'rb') as handler: - # Use a fake reply containing a gzipped SOAP response. - reply_instance = mock.Mock() - reply_instance.code = 200 - reply_instance.headers = {'content-encoding': 'gzip'} - reply_instance.message = handler.read() - mock_reply.return_value = reply_instance - # The send method would ordinarily fail to decompress the gzip SOAP - # message without the patch, resulting in an exception being raised. - cs.get() - - def testSudsJurkoSendWithException(self): - """Verifies that the patched HttpTransport.send can escalate HTTPError.""" - # Not applicable to zeep - if self.soap_impl == 'zeep': - return - - test_dir = os.path.dirname(__file__) - cs = self.adwords_client_with_compression.GetService('CampaignService') - - with mock.patch('suds.transport.http.HttpTransport.u2open') as mock_u2open: - with mock.patch('%s.HTTPMessage' % _HTTP_CLIENT_PATH) as mock_headers: - mock_headers.get.return_value = None - with open(os.path.join( - test_dir, 'test_data/compact_fault_response_envelope.txt'), 'rb' - ) as handler: - url = 'https://ads.google.com' - code = 500 - msg = '' - hdrs = mock_headers - mock_u2open.side_effect = six.moves.urllib.error.HTTPError( - url, code, msg, hdrs, handler) - try: - cs.get() - except googleads.errors.GoogleAdsServerFault as e: - self.assertEqual( - 'Unmarshalling Error: For input string: ' - '"INSERT_ADVERTISER_COMPANY_ID_HERE" ', - str(e)) - @contextmanager def mock_fault_response(self, response_file, version): test_dir = os.path.dirname(__file__) with open(os.path.join(test_dir, response_file), 'rb') as handler: response_data = handler.read() - if six.PY3: - response_data = response_data.replace( - b'{VERSION}', bytes(version, 'utf-8')) - else: - response_data = response_data.replace('{VERSION}', version) - - if self.soap_impl == 'suds': - with mock.patch('suds.transport.http.HttpTransport.send') as mock_send: - # Use a fake reply containing a fault SOAP response. - reply_instance = mock.Mock() - reply_instance.code = 500 - reply_instance.headers = {} - reply_instance.message = response_data - mock_send.return_value = reply_instance - yield - else: - with mock.patch('zeep.transports.Transport.post') as mock_post: - reply_instance = mock.Mock() - reply_instance.status_code = 500 - reply_instance.headers = {} - reply_instance.content = response_data - mock_post.return_value = reply_instance - yield + response_data = response_data.replace(b'{VERSION}', bytes(version, 'utf-8')) + + with mock.patch('zeep.transports.Transport.post') as mock_post: + reply_instance = mock.Mock() + reply_instance.status_code = 500 + reply_instance.headers = {} + reply_instance.content = response_data + mock_post.return_value = reply_instance + yield def testSingleErrorListIssue90(self): """Verifies that issue 90 has been resolved with the patch.""" @@ -291,7 +138,6 @@ def testGetGoogleAdsCommonFilter(self): def testFilterAtInfoLevel(self): record = mock.Mock() record.levelno = logging.INFO - doc = mock.Mock() doc.str.return_value = self.dev_token_template % 'test' @@ -309,245 +155,6 @@ def testFilterAtUnfilteredLevel(self): self.assertEqual(record.args, expected_args) -class SudsClientFilterTest(unittest.TestCase): - """Tests for the SudsClientFilter utility.""" - - def setUp(self): - self.filter = googleads.util.GetSudsClientFilter() - self.redacted_text = 'REDACTED' - self.dev_token_template = 'DevToken' - self.location = 'https://www.google.com' - test_dir = os.path.dirname(__file__) - with open(os.path.join( - test_dir, 'test_data/request_envelope_template.txt'), 'r') as handler: - self.test_request_envelope_template = handler.read() - - def testGetSudsClientFilter(self): - self.assertIs(self.filter, googleads.util.GetSudsClientFilter()) - - def testFilterWithSudsClientSOAPMessage(self): - record = mock.Mock() - soapenv = mock.Mock() - soapenv.str.return_value = (self.test_request_envelope_template - % self.dev_token_template) - record.msg = 'sending to (%s)\nmessage:\n%s' - record.args = [self.location, soapenv] - self.filter.filter(record) - self.assertEqual(record.args, (self.location, - (self.test_request_envelope_template - % self.redacted_text))) - - def testFilterWithSudsClientHeadersMessage(self): - record = mock.Mock() - record.msg = 'headers = %s' - record.args = {'Content-Type': 'text/xml; charset=utf-8', - 'authorization': 'Bearer abc123doremi'} - expected_args = {'Content-Type': 'text/xml; charset=utf-8', - 'authorization': self.redacted_text} - self.filter.filter(record) - self.assertEqual(record.args, expected_args) - - -class SudsMXCoreFilterTest(unittest.TestCase): - """Tests for the SudsMXCoreFilter utility.""" - - _DEVELOPER_TOKEN = 'developerToken' - _REQUEST_HEADER = 'RequestHeader' - - def setUp(self): - self.filter = googleads.util.GetSudsMXCoreFilter() - self.redacted_text = 'REDACTED' - self.developer_token_value = 'abc123doremi' - - def testGetSudsMXCoreFilter(self): - self.assertIs(self.filter, googleads.util.GetSudsMXCoreFilter()) - - def testFilterWithContentDeveloperToken(self): - content = suds.mx.Content(tag=self._DEVELOPER_TOKEN, - value=self.developer_token_value) - - record = mock.Mock() - record.args = [content] - - self.filter.filter(record) - # Verify that the original copy wasn't modified. - self.assertEqual(content.value, self.developer_token_value) - # Verify that the args were modified. - self.assertEqual(record.args[0].value, self.redacted_text) - - def testFilterWithContentRequestHeader(self): - request_header_value = { - self._DEVELOPER_TOKEN: self.developer_token_value - } - expected_filtered_value = { - self._DEVELOPER_TOKEN: self.redacted_text - } - content = suds.mx.Content(tag=self._REQUEST_HEADER, - value=request_header_value) - - record = mock.Mock() - record.args = [content] - - self.filter.filter(record) - # Verify that the original copy wasn't modified. - self.assertEqual(request_header_value[self._DEVELOPER_TOKEN], - self.developer_token_value) - # Verify that the args were modified. - self.assertEqual(record.args[0].value, expected_filtered_value) - - def testFilterWithElementRequestHeader(self): - request_header_element = suds.sax.element.Element( - self._REQUEST_HEADER, parent=None) - child = suds.sax.element.Element(self._DEVELOPER_TOKEN, parent=None) - child.text = suds.sax.text.Text(self.developer_token_value) - request_header_element.append(child) - - record = mock.Mock() - record.args = [request_header_element] - - self.filter.filter(record) - # Verify that the original copy wasn't modified. - self.assertEqual(child.text, suds.sax.text.Text(self.developer_token_value)) - # Verify that the args were modified. - self.assertEqual(record.args[0].getChild(self._DEVELOPER_TOKEN).text, - suds.sax.text.Text(self.redacted_text)) - - def testFilterWithNoArgs(self): - record = mock.Mock() - record.args = [] - self.filter.filter(record) - - def testFilterWithNoRequestHeader(self): - foo_value = 'bar' - lorem_value = 'ipsum' - potayto_value = 'potahto' - request_header_value = { - 'foo': foo_value, - 'lorem': lorem_value, - 'potayto': potayto_value - } - content = suds.mx.Content(tag=self._REQUEST_HEADER, - value=request_header_value) - - record = mock.Mock() - record.args = [content] - - self.filter.filter(record) - # Verify that the original copy wasn't modified. - self.assertEqual(request_header_value['foo'], foo_value) - self.assertEqual(request_header_value['lorem'], lorem_value) - self.assertEqual(request_header_value['potayto'], potayto_value) - # Verify that the args weren't modified. - self.assertEqual(record.args[0].value, request_header_value) - - -class SudsMXLiteralFilterTest(unittest.TestCase): - """Tests for the SudsMXLiteralFilter utility.""" - - _DEVELOPER_TOKEN = 'developerToken' - _REQUEST_HEADER = 'RequestHeader' - - def setUp(self): - self.filter = googleads.util.GetSudsMXLiteralFilter() - self.redacted_text = 'REDACTED' - self.developer_token_value = 'abc123doremi' - - def testGetSudsMXLiteralFilter(self): - self.assertIs(self.filter, googleads.util.GetSudsMXLiteralFilter()) - - def testFilterWithContentDeveloperToken(self): - content = suds.mx.Content(tag=self._DEVELOPER_TOKEN, - value=self.developer_token_value) - - record = mock.Mock() - record.args = [content] - - self.filter.filter(record) - # Verify that the original copy wasn't modified. - self.assertEqual(content.value, self.developer_token_value) - # Verify that the args were modified. - self.assertEqual(record.args[0].value, self.redacted_text) - - def testFilterWithContentRequestHeader(self): - request_header_value = { - self._DEVELOPER_TOKEN: self.developer_token_value - } - expected_filtered_value = { - self._DEVELOPER_TOKEN: self.redacted_text - } - content = suds.mx.Content(tag=self._REQUEST_HEADER, - value=request_header_value) - - record = mock.Mock() - record.args = [content] - - self.filter.filter(record) - # Verify that the original copy wasn't modified. - self.assertEqual(request_header_value[self._DEVELOPER_TOKEN], - self.developer_token_value) - # Verify that the args were modified. - self.assertEqual(record.args[0].value, expected_filtered_value) - - def testFilterWithNoArgs(self): - record = mock.Mock() - record.args = [] - self.filter.filter(record) - - def testFilterWithNoRequestHeader(self): - foo_value = 'bar' - lorem_value = 'ipsum' - potayto_value = 'potahto' - request_header_value = { - 'foo': foo_value, - 'lorem': lorem_value, - 'potayto': potayto_value - } - content = suds.mx.Content(tag=self._REQUEST_HEADER, - value=request_header_value) - - record = mock.Mock() - record.args = [content] - - self.filter.filter(record) - # Verify that the original copy wasn't modified. - self.assertEqual(request_header_value['foo'], foo_value) - self.assertEqual(request_header_value['lorem'], lorem_value) - self.assertEqual(request_header_value['potayto'], potayto_value) - # Verify that the args weren't modified. - self.assertEqual(record.args[0].value, request_header_value) - - -class SudsTransportFilterTest(unittest.TestCase): - """Tests for the SudsTransportFilter utility.""" - - def setUp(self): - self.filter = googleads.util.GetSudsTransportFilter() - self.redacted_text = 'REDACTED' - self.dev_token_template = 'DevToken' - self.location = 'https://www.google.com' - test_dir = os.path.dirname(__file__) - with open(os.path.join( - test_dir, 'test_data/request_envelope_template.txt'), 'r') as handler: - self.test_request_envelope_template = handler.read() - - def testGetSudsTransportFilter(self): - self.assertIs(self.filter, googleads.util.GetSudsTransportFilter()) - - def testFilterSudsTransportRequest(self): - request_instance = suds.transport.Request('https://www.google.com') - request_instance.headers = {'User-Agent': 'user-agent', - 'authorization': 'abc123doremi'} - request_instance.message = (self.test_request_envelope_template % - self.dev_token_template).encode('utf-8') - expected_headers = {'User-Agent': 'user-agent', - 'authorization': self.redacted_text} - record = mock.Mock() - record.args = (request_instance,) - self.filter.filter(record) - self.assertEqual(record.args[0].headers, expected_headers) - self.assertEqual(record.args[0].message, - self.test_request_envelope_template % self.redacted_text) - XML_WITH_DEV_TOKEN = ( '' 'a token' @@ -558,8 +165,7 @@ def testFilterSudsTransportRequest(self): XML_WITH_DEV_TOKEN = etree.fromstring(XML_WITH_DEV_TOKEN) XML_PRETTY = etree.tostring(XML_WITH_DEV_TOKEN, pretty_print=True) XML_PRETTY_SAFE = etree.tostring(XML_WITH_DEV_TOKEN_SAFE, pretty_print=True) -if six.PY3: - XML_PRETTY_SAFE = XML_PRETTY_SAFE.decode('utf-8') +XML_PRETTY_SAFE = XML_PRETTY_SAFE.decode('utf-8') XML_WITH_FAULT = etree.fromstring( '' '' @@ -584,11 +190,7 @@ def setUp(self): self.zeep_logger._logger = self.logger self.operation = mock.Mock() self.operation.name = 'opname' - if six.PY2: - self.operation.binding.wsdl.services.keys.return_value = ['service_name'] - else: - self.operation.binding.wsdl.services.keys.return_value = ( - iter(['service_name'])) + self.operation.binding.wsdl.services.keys.return_value = ['service_name'] def enable_log_levels(self, *levels): self.logger.isEnabledFor.side_effect = lambda lvl: lvl in levels @@ -664,7 +266,6 @@ def testEgressDebugLogging(self): googleads.util._REQUEST_XML_LOG_LINE, ZEEP_HEADER_SAFE, XML_PRETTY_SAFE) def testEgressInfoLogging(self): - self.enable_log_levels(logging.INFO) self.zeep_logger.egress( XML_WITH_DEV_TOKEN, ZEEP_HEADER, self.operation, BINDING_OPTIONS) From 94855e288ddf252586983a880aad247ceb9e1b90 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Tue, 11 Jun 2019 16:09:58 -0400 Subject: [PATCH 143/180] Commiting latest changes. From f070075a081cf2b32fd3d3b1b34b3e3770858c52 Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Tue, 13 Aug 2019 15:14:11 -0400 Subject: [PATCH 144/180] Ad Manager v201908 release. --- ChangeLog | 6 + .../create_product_base_rates.py | 65 ------- .../create_product_package_item_base_rates.py | 66 ------- .../create_product_template_base_rates.py | 65 ------- .../base_rate_service/get_all_base_rates.py | 52 ------ .../get_base_rates_for_rate_card.py | 55 ------ .../base_rate_service/update_base_rates.py | 77 --------- .../create_exchange_rates.py | 58 ------- .../get_exchange_rates_for_currency_code.py | 56 ------ .../update_exchange_rates.py | 71 -------- .../package_service/create_packages.py | 61 ------- ...reate_proposal_line_items_from_packages.py | 68 -------- .../package_service/get_all_packages.py | 50 ------ .../get_in_progress_packages.py | 51 ------ .../create_premium_rates.py | 84 --------- .../get_premium_rates_for_rate_card.py | 56 ------ .../update_premium_rates.py | 87 ---------- .../create_product_package_item.py | 62 ------- .../get_all_product_package_items.py | 53 ------ ...oduct_package_items_for_product_package.py | 56 ------ .../create_product_packages.py | 51 ------ .../get_active_product_packages.py | 52 ------ .../product_service/get_all_products.py | 49 ------ .../get_products_for_product_template.py | 53 ------ .../product_service/update_products.py | 68 -------- .../activate_product_templates.py | 74 -------- .../create_product_templates.py | 109 ------------ .../create_programmatic_product_templates.py | 91 ---------- .../get_sponsorship_product_templates.py | 52 ------ .../update_product_templates.py | 94 ---------- ...create_programmatic_proposal_line_items.py | 104 ----------- ...sal_line_items_for_non_sales_management.py | 113 ------------ .../create_proposal_line_items.py | 105 ------------ .../create_programmatic_proposals.py | 71 -------- .../proposal_service/create_proposals.py | 77 --------- .../submit_proposals_for_approval.py | 67 -------- .../rate_card_service/create_rate_cards.py | 60 ------- .../rate_card_service/get_all_rate_cards.py | 51 ------ .../get_marketplace_rate_cards.py | 54 ------ ..._item_reports_for_reconciliation_report.py | 75 -------- ...update_reconciliation_line_item_reports.py | 67 -------- ...order_reports_for_reconciliation_report.py | 58 ------- .../submit_reconciliation_order_reports.py | 71 -------- ...n_report_rows_for_reconciliation_report.py | 64 ------- .../update_reconciliation_report_rows.py | 75 -------- .../get_all_reconciliation_reports.py | 56 ------ ...iliation_report_for_last_billing_period.py | 63 ------- .../v201811/report_service/__init__.py | 15 -- .../suggested_ad_unit_service/__init__.py | 15 -- .../v201811/team_service/__init__.py | 15 -- .../v201811/user_service/__init__.py | 15 -- .../user_team_association_service/__init__.py | 15 -- .../workflow_request_service/__init__.py | 15 -- .../approve_workflow_approval_requests.py | 75 -------- .../get_workflow_approval_requests.py | 57 ------- ...et_workflow_external_condition_requests.py | 57 ------- ...er_workflow_external_condition_requests.py | 78 --------- ...create_programmatic_proposal_line_items.py | 104 ----------- .../create_proposal_line_items.py | 67 ++++---- .../create_programmatic_proposals.py | 71 -------- ...atic_proposals_for_non_sales_management.py | 62 ------- .../proposal_service/create_proposals.py | 50 ++---- ...> get_proposals_awaiting_seller_review.py} | 7 +- .../submit_proposals_for_approval.py | 67 -------- ...create_programmatic_proposal_line_items.py | 104 ----------- ...sal_line_items_for_non_sales_management.py | 113 ------------ .../create_proposal_line_items.py | 67 ++++---- .../create_programmatic_proposals.py | 71 -------- ...atic_proposals_for_non_sales_management.py | 62 ------- .../proposal_service/create_proposals.py | 50 ++---- ...> get_proposals_awaiting_seller_review.py} | 7 +- .../submit_proposals_for_approval.py | 67 -------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_traffic_adjustments.py | 143 ++++++++++++++++ .../get_all_traffic_adjustments.py} | 35 ++-- .../update_traffic_adjustments.py | 88 ++++++++++ .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../get_all_cms_metadata_keys.py} | 29 ++-- .../get_all_cms_metadata_values.py} | 35 ++-- .../get_cms_metadata_values_for_key.py | 60 +++++++ .../company_service}/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service}/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service}/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../creative_service}/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service}/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service}/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service}/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service}/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service}/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service}/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service}/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 81 ++++----- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service}/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service}/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service}/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py} | 47 +++-- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service}/__init__.py | 0 .../proposal_service/create_proposals.py} | 7 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py} | 11 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service}/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 14 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 6 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../suggested_ad_unit_service}/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service}/__init__.py | 2 +- .../get_all_targeting_presets.py} | 27 +-- .../team_service}/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service}/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- .../account_management/get_account_changes.py | 2 +- googleads/ad_manager.py | 53 +++--- googleads/common.py | 2 +- tests/ad_manager_test.py | 161 +----------------- tests/common_test.py | 2 +- 262 files changed, 837 insertions(+), 4931 deletions(-) delete mode 100755 examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py delete mode 100755 examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py delete mode 100755 examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py delete mode 100755 examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py delete mode 100755 examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py delete mode 100755 examples/ad_manager/v201811/base_rate_service/update_base_rates.py delete mode 100755 examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py delete mode 100755 examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py delete mode 100755 examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py delete mode 100755 examples/ad_manager/v201811/package_service/create_packages.py delete mode 100755 examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py delete mode 100755 examples/ad_manager/v201811/package_service/get_all_packages.py delete mode 100755 examples/ad_manager/v201811/package_service/get_in_progress_packages.py delete mode 100755 examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py delete mode 100755 examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py delete mode 100755 examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py delete mode 100755 examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py delete mode 100755 examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py delete mode 100755 examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py delete mode 100755 examples/ad_manager/v201811/product_package_service/create_product_packages.py delete mode 100755 examples/ad_manager/v201811/product_package_service/get_active_product_packages.py delete mode 100755 examples/ad_manager/v201811/product_service/get_all_products.py delete mode 100755 examples/ad_manager/v201811/product_service/get_products_for_product_template.py delete mode 100755 examples/ad_manager/v201811/product_service/update_products.py delete mode 100755 examples/ad_manager/v201811/product_template_service/activate_product_templates.py delete mode 100755 examples/ad_manager/v201811/product_template_service/create_product_templates.py delete mode 100755 examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py delete mode 100755 examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py delete mode 100755 examples/ad_manager/v201811/product_template_service/update_product_templates.py delete mode 100755 examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py delete mode 100755 examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py delete mode 100755 examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py delete mode 100755 examples/ad_manager/v201811/proposal_service/create_programmatic_proposals.py delete mode 100755 examples/ad_manager/v201811/proposal_service/create_proposals.py delete mode 100755 examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py delete mode 100755 examples/ad_manager/v201811/rate_card_service/create_rate_cards.py delete mode 100755 examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py delete mode 100755 examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py delete mode 100755 examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py delete mode 100755 examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py delete mode 100755 examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py delete mode 100755 examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py delete mode 100755 examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py delete mode 100755 examples/ad_manager/v201811/report_service/__init__.py delete mode 100755 examples/ad_manager/v201811/suggested_ad_unit_service/__init__.py delete mode 100755 examples/ad_manager/v201811/team_service/__init__.py delete mode 100755 examples/ad_manager/v201811/user_service/__init__.py delete mode 100755 examples/ad_manager/v201811/user_team_association_service/__init__.py delete mode 100755 examples/ad_manager/v201811/workflow_request_service/__init__.py delete mode 100755 examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py delete mode 100755 examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py delete mode 100755 examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py delete mode 100755 examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py delete mode 100755 examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py delete mode 100755 examples/ad_manager/v201902/proposal_service/create_programmatic_proposals.py delete mode 100755 examples/ad_manager/v201902/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename examples/ad_manager/v201902/proposal_service/{get_proposals_pending_approval.py => get_proposals_awaiting_seller_review.py} (89%) delete mode 100755 examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py delete mode 100755 examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py delete mode 100755 examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py delete mode 100755 examples/ad_manager/v201905/proposal_service/create_programmatic_proposals.py delete mode 100755 examples/ad_manager/v201905/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename examples/ad_manager/v201905/proposal_service/{get_proposals_pending_approval.py => get_proposals_awaiting_seller_review.py} (89%) delete mode 100755 examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py rename examples/ad_manager/{v201811 => v201908}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v201811 => v201908}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v201811 => v201908}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v201811 => v201908}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v201811 => v201908}/activity_service/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v201811 => v201908}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v201811 => v201908}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v201811 => v201908}/activity_service/update_activities.py (96%) create mode 100755 examples/ad_manager/v201908/adjustment_service/create_traffic_adjustments.py rename examples/ad_manager/{v201811/premium_rate_service/get_all_premium_rates.py => v201908/adjustment_service/get_all_traffic_adjustments.py} (54%) create mode 100755 examples/ad_manager/v201908/adjustment_service/update_traffic_adjustments.py rename examples/ad_manager/{v201811 => v201908}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v201811 => v201908}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v201811 => v201908}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v201811 => v201908}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v201811 => v201908}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v201811 => v201908}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v201811 => v201908}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v201811/product_package_service/get_all_product_packages.py => v201908/cms_metadata_service/get_all_cms_metadata_keys.py} (59%) rename examples/ad_manager/{v201811/exchange_rate_service/get_all_exchange_rates.py => v201908/cms_metadata_service/get_all_cms_metadata_values.py} (54%) create mode 100755 examples/ad_manager/v201908/cms_metadata_service/get_cms_metadata_values_for_key.py rename examples/ad_manager/{v201811/base_rate_service => v201908/company_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/company_service/create_companies.py (99%) rename examples/ad_manager/{v201811 => v201908}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v201811 => v201908}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v201811 => v201908}/company_service/update_companies.py (96%) rename examples/ad_manager/{v201811/company_service => v201908/contact_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v201811 => v201908}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v201811 => v201908}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v201811 => v201908}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v201811/contact_service => v201908/content_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/content_service/get_all_content.py (95%) rename examples/ad_manager/{v201811/content_service => v201908/creative_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v201811 => v201908}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v201811 => v201908}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v201811 => v201908}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v201811 => v201908}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v201811 => v201908}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v201811 => v201908}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v201811 => v201908}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v201811/creative_service => v201908/creative_set_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v201811 => v201908}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v201811 => v201908}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v201811 => v201908}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v201811 => v201908}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v201811/creative_set_service => v201908/creative_template_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v201811 => v201908}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v201811 => v201908}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v201811 => v201908}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v201811 => v201908}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v201811 => v201908}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v201811 => v201908}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v201811/creative_template_service => v201908/custom_field_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v201811 => v201908}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v201811 => v201908}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v201811 => v201908}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v201811 => v201908}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v201811 => v201908}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v201811 => v201908}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v201811/custom_field_service => v201908/custom_targeting_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v201811 => v201908}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201811 => v201908}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v201811 => v201908}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201811 => v201908}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201811 => v201908}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201811 => v201908}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v201811 => v201908}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v201811 => v201908}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v201811 => v201908}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v201811/custom_targeting_service => v201908/inventory_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v201811 => v201908}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v201811 => v201908}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v201811 => v201908}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v201811 => v201908}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v201811 => v201908}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v201811 => v201908}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v201811/exchange_rate_service => v201908/label_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/label_service/create_labels.py (99%) rename examples/ad_manager/{v201811 => v201908}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v201811 => v201908}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v201811 => v201908}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v201811 => v201908}/label_service/update_labels.py (96%) rename examples/ad_manager/{v201811/inventory_service => v201908/line_item_creative_association_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v201811 => v201908}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v201811 => v201908}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v201811 => v201908}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v201811 => v201908}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v201811/label_service => v201908/line_item_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/create_video_line_item.py (66%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v201811 => v201908}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v201811 => v201908}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v201811 => v201908}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v201811 => v201908}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v201811 => v201908}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v201811 => v201908}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v201811 => v201908}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v201811 => v201908}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v201811/line_item_creative_association_service => v201908/network_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v201811 => v201908}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v201811 => v201908}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v201811/line_item_service => v201908/order_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v201811 => v201908}/order_service/create_orders.py (99%) rename examples/ad_manager/{v201811 => v201908}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v201811 => v201908}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v201811 => v201908}/order_service/update_orders.py (97%) rename examples/ad_manager/{v201811 => v201908}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v201811 => v201908}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v201811 => v201908}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v201811 => v201908}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v201811 => v201908}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v201811/network_service => v201908/proposal_line_item_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py => v201908/proposal_line_item_service/create_proposal_line_items.py} (75%) rename examples/ad_manager/{v201811 => v201908}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v201811 => v201908}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v201811 => v201908}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v201811/order_service => v201908/proposal_service}/__init__.py (100%) rename examples/ad_manager/{v201811/proposal_service/create_programmatic_proposals_for_non_sales_management.py => v201908/proposal_service/create_proposals.py} (91%) rename examples/ad_manager/{v201811 => v201908}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v201811 => v201908}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v201811/proposal_service/get_proposals_pending_approval.py => v201908/proposal_service/get_proposals_awaiting_seller_review.py} (85%) rename examples/ad_manager/{v201811 => v201908}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v201811 => v201908}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v201811/premium_rate_service => v201908/publisher_query_language_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v201811 => v201908}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v201811 => v201908}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v201811 => v201908}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v201811 => v201908}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v201811 => v201908}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v201811/product_service => v201908/report_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v201811 => v201908}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v201811 => v201908}/report_service/run_inventory_report.py (86%) rename examples/ad_manager/{v201811 => v201908}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v201811 => v201908}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v201811 => v201908}/report_service/run_report_with_custom_fields.py (95%) rename examples/ad_manager/{v201811 => v201908}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v201811 => v201908}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v201811/product_template_service => v201908/suggested_ad_unit_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v201811 => v201908}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v201811 => v201908}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v201811/rate_card_service => v201908/targeting_preset_service}/__init__.py (91%) rename examples/ad_manager/{v201811/product_template_service/get_all_product_templates.py => v201908/targeting_preset_service/get_all_targeting_presets.py} (59%) rename examples/ad_manager/{v201811/proposal_line_item_service => v201908/team_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/team_service/create_teams.py (96%) rename examples/ad_manager/{v201811 => v201908}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v201811 => v201908}/team_service/update_teams.py (94%) rename examples/ad_manager/{v201811/proposal_service => v201908/user_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/user_service/create_users.py (96%) rename examples/ad_manager/{v201811 => v201908}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v201811 => v201908}/user_service/get_all_roles.py (99%) rename examples/ad_manager/{v201811 => v201908}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v201811 => v201908}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v201811 => v201908}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v201811 => v201908}/user_service/update_users.py (92%) rename examples/ad_manager/{v201811/publisher_query_language_service => v201908/user_team_association_service}/__init__.py (100%) rename examples/ad_manager/{v201811 => v201908}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v201811 => v201908}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v201811 => v201908}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v201811 => v201908}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v201811 => v201908}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index d9339d7d..e3e00deb 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +21.0.0 -- 08/14/2019 +* Added support for Ad Manager v201908 +* Removed support for Ad Manager v201808 +* Removed examples for Ad Manager v201811 +* Updated all Ad Manager examples to reflect Sales Manager sunset + 20.0.0 -- 06/11/2019 * Updated examples to be Python 3 compatible * Removed suds dependency leaving zeep as the only supported SOAP client diff --git a/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py deleted file mode 100755 index 9fad367c..00000000 --- a/examples/ad_manager/v201811/base_rate_service/create_product_base_rates.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201811') - - # Create a product base rate. - product_base_rate = { - 'xsi_type': 'ProductBaseRate', - # Set the rate card ID that the product base rate belongs to. - 'rateCardId': rate_card_id, - # Set the product id the base rate will be applied to. - 'productId': product_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create the product base rate on the server. - base_rates = base_rate_service.createBaseRates( - [product_base_rate]) - - if base_rates: - for base_rate in base_rates: - print('A product base rate with ID "%s" and rate \'%.2f\' %s was ' - 'created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py deleted file mode 100755 index 799b1dbe..00000000 --- a/examples/ad_manager/v201811/base_rate_service/create_product_package_item_base_rates.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package item base rate. - -To determine which base rates exist, run get_all_base_rates.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the rate card ID to add the base rate to. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - -# Set the product package item to apply this base rate to. -PRODUCT_PACKAGE_ITEM_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201811') - - # Create a base rate for a product package item. - product_package_item_base_rate = { - 'xsi_type': 'ProductPackageItemBaseRate', - # Set the rate card ID that the product package item base rate - # belongs to. - 'rateCardId': RATE_CARD_ID, - # Set the product package item the base rate will be applied to. - 'productPackageItemId': PRODUCT_PACKAGE_ITEM_ID, - # Create a rate worth $2 USD and set that on the product package item - # base rate. - 'rate': { - 'xsi_type': 'Money', - 'currencyCode': 'USD', - 'microAmount': 2000000, - } - } - - # Create the product package item base rate on the server. - result = base_rate_service.createBaseRates([product_package_item_base_rate]) - - for new_base_rate in result: - print('A product package item base rate with ID %d and rate %f %s ' - 'was created.' % (new_base_rate['id'], - new_base_rate['microAmount'], - new_base_rate['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py deleted file mode 100755 index 770ff107..00000000 --- a/examples/ad_manager/v201811/base_rate_service/create_product_template_base_rates.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product template base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_template_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201811') - - # Create a product template base rate. - product_template_base_rate = { - 'xsi_type': 'ProductTemplateBaseRate', - # Set the rate card ID that the product template base rate belongs to. - 'rateCardId': rate_card_id, - # Set the product template the base rate will be applied to. - 'productTemplateId': product_template_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create the product template item base rate on the server. - base_rates = base_rate_service.createBaseRates( - [product_template_base_rate]) - - if base_rates: - for base_rate in base_rates: - print('A product template base rate with ID "%s" and rate \'%.2f\' %s' - ' was created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py deleted file mode 100755 index b9368058..00000000 --- a/examples/ad_manager/v201811/base_rate_service/get_all_base_rates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 base rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201811') - - # Create a statement to select base rates. - statement = ad_manager.StatementBuilder(version='v201811') - - # Retrieve a small amount of base rates at a time, paging - # through until all base rates have been retrieved. - while True: - response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for base_rate in response['results']: - # Print out some information for each base rate. - print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % (base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py deleted file mode 100755 index 211ff434..00000000 --- a/examples/ad_manager/v201811/base_rate_service/get_base_rates_for_rate_card.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 base rates belonging to a rate card. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201811') - # Create a statement to select base rates. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('rateCardId = :rateCardId') - .WithBindVariable('rateCardId', rate_card_id)) - - # Retrieve a small amount of base rates at a time, paging - # through until all base rates have been retrieved. - while True: - response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for base_rate in response['results']: - # Print out some information for each base rate. - print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % - (base_rate['id'], ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201811/base_rate_service/update_base_rates.py b/examples/ad_manager/v201811/base_rate_service/update_base_rates.py deleted file mode 100755 index 44aea9b5..00000000 --- a/examples/ad_manager/v201811/base_rate_service/update_base_rates.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a base rate's value. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' - - -def main(client, base_rate_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201811') - - # Create a filter statement for base rates for a single rate card. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', int(base_rate_id))) - - # Get single base rate by statement. - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local base rate object by changing its value to $3 USD. - new_rate = { - 'currencyCode': 'USD', - 'microAmount': 3000000 - } - - updated_base_rates = [] - for base_rate in response['results']: - base_rate['rate'] = new_rate - updated_base_rates.append(base_rate) - - # Update base rates remotely. - base_rates = base_rate_service.updateBaseRates(updated_base_rates) - - # Display results. - if base_rates: - for base_rate in base_rates: - print('Base rate with ID "%s" and type "%s" belonging to ' - 'rate card ID "%s" was updated.' % ( - base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - else: - print('No base rates were updated.') - else: - print('No base rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, BASE_RATE_ID) diff --git a/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py deleted file mode 100755 index 26361f19..00000000 --- a/examples/ad_manager/v201811/exchange_rate_service/create_exchange_rates.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates an exchange rate. - -To determine which exchange rates exist, run get_all_exchange_rates.py. - - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201811') - - # Create a new fixed exchange rate with currency code 'AUD', with direction - # FROM_NETWORK with a value of 1.5. - exchange_rate = { - 'currencyCode': 'AUD', - 'direction': 'FROM_NETWORK', - 'exchangeRate': int(15000000000), - 'refreshRate': 'FIXED' - } - - created_exchange_rate = exchange_rate_service.createExchangeRates( - [exchange_rate])[0] - - print('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was created.' % (created_exchange_rate['id'], - created_exchange_rate['currencyCode'], - created_exchange_rate['direction'], - (float(created_exchange_rate['exchangeRate']) / - 10000000000))) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py deleted file mode 100755 index 2351a26e..00000000 --- a/examples/ad_manager/v201811/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the exchange rate for a specific currency code. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client, currency_code): - # Initialize appropriate service. - exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201811') - # Create a statement to select exchange rates. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('currencyCode = :currencyCode') - .WithBindVariable('currencyCode', currency_code)) - - # Retrieve a small amount of exchange rates at a time, paging - # through until all exchange rates have been retrieved. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for exchange_rate in response['results']: - # Print out some information for each exchange rate. - print('Exchange rate with ID "%d", currency code "%s", and exchange ' - 'rate "%.2f" was found.\n' % - (exchange_rate['id'], exchange_rate['currencyCode'], - float(exchange_rate['exchangeRate'] / 1000000))) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CURRENCY_CODE) diff --git a/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py deleted file mode 100755 index aa2a6d42..00000000 --- a/examples/ad_manager/v201811/exchange_rate_service/update_exchange_rates.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates the value of an exchange rate. - -To create exchange rates, run create_exchange_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' - - -def main(client, exchange_rate_id): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201811') - - # Create a statement to get an exchange rate by its ID. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .WithBindVariable('id', int(exchange_rate_id)) - .Limit(1)) - - # Get rate cards by statement. - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - exchange_rate = response['results'][0] - - # Update the exchange rate value to 1.5. - exchange_rate['exchangeRate'] = int(15000000000) - - exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) - - if exchange_rates: - for exchange_rate in exchange_rates: - print('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was updated.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) - else: - print('No exchange rates were updated.') - else: - print('No exchange rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, EXCHANGE_RATE_ID) diff --git a/examples/ad_manager/v201811/package_service/create_packages.py b/examples/ad_manager/v201811/package_service/create_packages.py deleted file mode 100755 index 6fa041de..00000000 --- a/examples/ad_manager/v201811/package_service/create_packages.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a package. - -To determine which packages exist, run get_all_packages.py. -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the ID of the product package to create the package from. -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - -# Set the ID of the proposal to create proposal line items under. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the rate card the proposal line items belonging to the product -# package are priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client): - # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201811') - - # Create local package. - package = { - 'name': 'Package #%d' % random.randint(0, 1000000), - 'proposalId': PROPOSAL_ID, - 'productPackageId': PRODUCT_PACKAGE_ID, - 'rateCardId': RATE_CARD_ID, - } - - # Create the package on the server. - result = package_service.createPackages([package]) - - for new_package in result: - print('A package with ID %d and name "%s" was created' % - (new_package['id'], new_package['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py deleted file mode 100755 index f27c631b..00000000 --- a/examples/ad_manager/v201811/package_service/create_proposal_line_items_from_packages.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a copy of an image creative. - -To determine which image creatives exist, run get_image_creatives.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the line item to pause. -PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201811') - - # Create a statement to select the single package. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', PACKAGE_ID)) - - # Get the package. - query_result = package_service.getPackagesByStatement(statement.ToStatement()) - - package = query_result['results'][0] - - print('Package with ID %d will create proposal line items using product ' - 'package with ID %d.' % (package['id'], - package['productPackageId'])) - - # Remove limit and offset from statement. - statement.limit = None - statement.offset = None - - # Perform update packages action. - result = package_service.performPackageAction( - {'xsi_type': 'CreateProposalLineItemsFromPackages'}, - statement.ToStatement()) - - if result and result['numChanges'] > 0: - print('Number of packages that proposal line items were created for: %d' % - result['numChanges']) - else: - print('No proposal line items were created.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/package_service/get_all_packages.py b/examples/ad_manager/v201811/package_service/get_all_packages.py deleted file mode 100755 index 1f58e38b..00000000 --- a/examples/ad_manager/v201811/package_service/get_all_packages.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201811') - - # Create a statement to select packages. - statement = ad_manager.StatementBuilder(version='v201811') - - # Retrieve a small amount of packages at a time, paging - # through until all packages have been retrieved. - while True: - response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for pkg in response['results']: - # Print out some information for each package. - print( - 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' - % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/package_service/get_in_progress_packages.py b/examples/ad_manager/v201811/package_service/get_in_progress_packages.py deleted file mode 100755 index 230b6e1c..00000000 --- a/examples/ad_manager/v201811/package_service/get_in_progress_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 packages in progress. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201811') - # Create a statement to select packages. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('status = :status') - .WithBindVariable('status', 'IN_PROGRESS')) - - # Retrieve a small amount of packages at a time, paging - # through until all packages have been retrieved. - while True: - response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for pkg in response['results']: - # Print out some information for each package. - print( - 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' - % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py deleted file mode 100755 index 33f8e27f..00000000 --- a/examples/ad_manager/v201811/premium_rate_service/create_premium_rates.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new premium_rates. - -To determine which premium_rates exist, run get_all_premium_rates.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate services. - premium_rate_service = client.GetService('PremiumRateService', - version='v201811') - - # Create an ad unit premium to apply to the rate card. - ad_unit_premium_feature = { - 'xsi_type': 'AdUnitPremiumFeature' - } - - # Create a CPC based premium rate value with adjustments in milli amounts. - # This will adjust a CPC priced proposal line item that has - # inventory targeting specified by 10% of the cost associated with the rate - # card (this comes from a percentage adjustment). - cpc_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPC', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Create a CPM based premium rate value with adjustments in micro amounts. - # This will adjust a CPM priced proposal line item that has - # inventory targeting specified by 2 units of the currency associated with - # the rate card (this comes from absolute value adjustment). - cpm_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPM', - 'adjustmentSize': 2000000, - 'adjustmentType': 'ABSOLUTE_VALUE' - } - - # Create premium rate. - # Associate premium rate with the rate card and set premium information. - # This premium will apply for proposal line items targeting 'any' ad unit - # for both CPM and CPC rate types. - premium_rate = { - 'rateCardId': rate_card_id, - 'pricingMethod': 'ANY_VALUE', - 'premiumFeature': ad_unit_premium_feature, - 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value] - } - - # Add premium_rates. - premium_rates = premium_rate_service.createPremiumRates([premium_rate]) - - # Display results. - for premium_rate in premium_rates: - print('A premium rate for "%s" was added to the rate card with ID' - ' of "%s".\n' - % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), - premium_rate['id'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py deleted file mode 100755 index 4a881d52..00000000 --- a/examples/ad_manager/v201811/premium_rate_service/get_premium_rates_for_rate_card.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 premium rates on a specific rate card. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - premium_rate_service = client.GetService( - 'PremiumRateService', version='v201811') - # Create a statement to select premium rates. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('rateCardId = :rateCardId') - .WithBindVariable('rateCardId', rate_card_id)) - - # Retrieve a small amount of premium rates at a time, paging - # through until all premium rates have been retrieved. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for premium_rate in response['results']: - # Print out some information for each premium rate. - print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'ID "%d" was found.\n' % (premium_rate['id'], - premium_rate['premium feature'], - premium_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py deleted file mode 100755 index b0b0875a..00000000 --- a/examples/ad_manager/v201811/premium_rate_service/update_premium_rates.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a premium rate to add a flat fee to an existing feature. - -To determine which premium rates exist, run get_all_premium_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' - - -def main(client, premium_rate_id): - # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201811') - - # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', int(premium_rate_id)) - .Limit(1)) - - # Get the premium rate. - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_premium_rates = [] - for premium_rate in response['results']: - # Create a flat fee based premium rate value with a 10% increase. - new_flat_fee_rate = { - 'premiumFeature': premium_rate['premiumFeature'], - 'rateType': 'CPM', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Update the premium rate's premiumRateValues to include a flat fee - # premium rate. - - existing_premium_rate_value = ( - [] if 'premiumRateValues' not in premium_rate else - premium_rate['premiumRateValues']) - existing_premium_rate_value.append(new_flat_fee_rate) - premium_rate['premiumRateValues'] = existing_premium_rate_value - - updated_premium_rates.append(premium_rate) - - # Update products remotely. - premium_rates = premium_rate_service.updatePremiumRates( - updated_premium_rates) - - # Display results. - if premium_rates: - for premium_rate in premium_rates: - print('Premium rate with ID "%s", associated with rate card id' - ' "%s" was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) - else: - print('No premium rates were updated.') - else: - print('No premium rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PREMIUM_RATE_ID) diff --git a/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py deleted file mode 100755 index 469f4488..00000000 --- a/examples/ad_manager/v201811/product_package_item_service/create_product_package_item.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package item. - -To determine which product package items exist, run -get_all_product_package_items.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the product package to add product package items to. -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - -# Set the ID of the product to generate a product package item from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client): - product_package_item_service = client.GetService('ProductPackageItemService', - version='v201811') - - product_package_item = { - # Set the product from which the product package item is created. - 'productId': PRODUCT_ID, - # Set the product package that the product package item belongs to. - 'productPackageId': PRODUCT_PACKAGE_ID, - # Specify if the product package item is required for this - # product package. - 'isMandatory': True - } - - # Create the product package item on the server. - result = product_package_item_service.createProductPackageItems( - [product_package_item]) - - for new_product_package_item in result: - print('A product package with ID %d created from product ID %d ' - 'belonging to product package with ID %d was created.' % - (new_product_package_item['id'], - new_product_package_item['productId'], - new_product_package_item['productPackageId'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py deleted file mode 100755 index 1930d17e..00000000 --- a/examples/ad_manager/v201811/product_package_item_service/get_all_product_package_items.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product package items. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201811') - - # Create a statement to select product package items. - statement = ad_manager.StatementBuilder(version='v201811') - - # Retrieve a small amount of product package items at a time, paging - # through until all product package items have been retrieved. - while True: - response = product_package_item_service.getProductPackageItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package_item in response['results']: - # Print out some information for each product package item. - print('Product package item with ID "%d", product id "%d", and product ' - 'package id "%d" was found.\n' % - (product_package_item['id'], product_package_item['productId'], - product_package_item['productPackageId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py deleted file mode 100755 index eb0f6dd0..00000000 --- a/examples/ad_manager/v201811/product_package_item_service/get_product_package_items_for_product_package.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product package items belonging to a product package. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - - -def main(client, product_package_id): - # Initialize appropriate service. - product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201811') - # Create a statement to select product package items. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('productPackageId = :productPackageId') - .WithBindVariable('productPackageId', product_package_id)) - - # Retrieve a small amount of product package items at a time, paging - # through until all product package items have been retrieved. - while True: - response = product_package_item_service.getProductPackageItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package_item in response['results']: - # Print out some information for each product package item. - print('Product package item with ID "%d", product ID "%d", and product ' - 'package ID "%d" was found.\n' % - (product_package_item['id'], product_package_item['productId'], - product_package_item['productPackageId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_PACKAGE_ID) diff --git a/examples/ad_manager/v201811/product_package_service/create_product_packages.py b/examples/ad_manager/v201811/product_package_service/create_product_packages.py deleted file mode 100755 index d1c0e113..00000000 --- a/examples/ad_manager/v201811/product_package_service/create_product_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package. - -To determine which product packages exist, run get_all_product_packages.py -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the ID of the rate card to associate with the product package. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client): - product_package_service = client.GetService('ProductPackageService', - version='v201811') - - # Create a local product package. - product_package = { - 'name': 'Product Package #%d' % random.randint(0, 100000000), - 'rateCardIds': [RATE_CARD_ID] - } - - result = product_package_service.createProductPackages([product_package]) - - for new_product_package in result: - print('A product package with ID %d and name "%s" was created.' % - (new_product_package['id'], new_product_package['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py deleted file mode 100755 index 74fdb0c4..00000000 --- a/examples/ad_manager/v201811/product_package_service/get_active_product_packages.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active product packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_service = client.GetService( - 'ProductPackageService', version='v201811') - # Create a statement to select product packages. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('status = :status') - .WithBindVariable('status', 'ACTIVE')) - - # Retrieve a small amount of product packages at a time, paging - # through until all product packages have been retrieved. - while True: - response = product_package_service.getProductPackagesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package in response['results']: - # Print out some information for each product package. - print('Product package with ID "%d" and name "%s" was found.\n' % - (product_package['id'], product_package['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/product_service/get_all_products.py b/examples/ad_manager/v201811/product_service/get_all_products.py deleted file mode 100755 index 05ab107d..00000000 --- a/examples/ad_manager/v201811/product_service/get_all_products.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 products. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201811') - - # Create a statement to select products. - statement = ad_manager.StatementBuilder(version='v201811') - - # Retrieve a small amount of products at a time, paging - # through until all products have been retrieved. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for product in response['results']: - # Print out some information for each product. - print('Product with ID "%d" and name "%s" was found.\n' % - (product['id'], product['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/product_service/get_products_for_product_template.py b/examples/ad_manager/v201811/product_service/get_products_for_product_template.py deleted file mode 100755 index e4a2735c..00000000 --- a/examples/ad_manager/v201811/product_service/get_products_for_product_template.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 products created from a product template. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201811') - - # Create a statement to select products. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('productTemplateId = :productTemplateId') - .WithBindVariable('productTemplateId', product_template_id)) - - # Retrieve a small amount of products at a time, paging - # through until all products have been retrieved. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for product in response['results']: - # Print out some information for each product. - print('Product with ID "%d" and name "%s" was found.\n' % - (product['id'], product['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201811/product_service/update_products.py b/examples/ad_manager/v201811/product_service/update_products.py deleted file mode 100755 index 639c2268..00000000 --- a/examples/ad_manager/v201811/product_service/update_products.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a product's notes. - -To determine which products exist, run get_all_products.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201811') - - # Create statement object to select a single product by an ID. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .WithBindVariable('id', int(product_id)) - .Limit(1)) - - # Get products by statement. - response = product_service.getProductsByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local product object by changing its notes. - updated_products = [] - for product in response['results']: - product['notes'] = 'Product needs further review before activation.' - updated_products.append(product) - - # Update products remotely. - products = product_service.updateProducts(updated_products) - - # Display results. - if products: - for product in products: - print('Product with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (product['id'], product['name'], product['notes'])) - else: - print('No products were updated.') - else: - print('No products found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_ID) diff --git a/examples/ad_manager/v201811/product_template_service/activate_product_templates.py b/examples/ad_manager/v201811/product_template_service/activate_product_templates.py deleted file mode 100755 index 39ea36da..00000000 --- a/examples/ad_manager/v201811/product_template_service/activate_product_templates.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example activates a product template. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the id of the product template to activate. -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201811') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .WithBindVariable('id', int(product_template_id)) - .Limit(1)) - - product_templates_activated = 0 - - # Get product_templates by statement. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - print('Product template with id "%s" and name "%s" will be ' - 'activated.' % (product_template['id'], - product_template['name'])) - - # Perform action. - result = product_template_service.performProductTemplateAction( - {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - product_templates_activated += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if product_templates_activated > 0: - print('Number of product templates ' - 'activated: %s' % product_templates_activated) - else: - print('No product templates were activated.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201811/product_template_service/create_product_templates.py b/examples/ad_manager/v201811/product_template_service/create_product_templates.py deleted file mode 100755 index 4cc43eba..00000000 --- a/examples/ad_manager/v201811/product_template_service/create_product_templates.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product template. - -To determine which product templates exist, run get_all_product_templates.py. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201811') - network_service = client.GetService( - 'NetworkService', version='v201811') - - # Create a product template. - product_template = { - 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard proposal line ' - 'items targeting Chrome browsers with product ' - 'segmentation on ad units and geo targeting.'), - 'nameMacro': (' - - ' - ' - '), - 'productType': 'DFP', - 'rateType': 'CPM', - 'roadblockingType': 'ONE_OR_MORE', - 'deliveryRateType': 'AS_FAST_AS_POSSIBLE', - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'lineItemType': 'STANDARD', - 'customizableAttributes': { - 'allowPlacementTargetingCustomization': True, - }, - 'builtInTargeting': { - 'technologyTargeting': { - # Set browser targeting to Chrome. - 'browserTargeting': { - { - 'browsers': [ - { - 'id': '500072' - } - ] - } - } - } - }, - 'productSegmentation': { - 'geoSegment': { - 'targetedLocations': [ - {'id': '2840', - 'displayName': 'US'}, - {'id': '2344', - 'displayName': 'Hong Kong'} - ] - }, - 'adUnitSegments': [{ - 'adUnitId': (network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId']), - 'includeDescendants': 'true' - }] - } - } - - # Create product templates on the server. - product_templates = product_template_service.createProductTemplates( - [product_template]) - - if product_templates: - for product_template in product_templates: - print('A product template with ID "%s" and name "%s" was ' - 'created.' % (product_template['id'], product_template['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py deleted file mode 100755 index 8d2a791b..00000000 --- a/examples/ad_manager/v201811/product_template_service/create_programmatic_product_templates.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product template. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - product_template_service = client.GetService( - 'ProductTemplateService', version='v201811') - network_service = client.GetService( - 'NetworkService', version='v201811') - - product_template = { - # Setting required Marketplace information. - 'productTemplateMarketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for product templates. - 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard programmatic' - 'proposal line items targeting all ad units with' - 'product segmentation on geo targeting.'), - 'nameMacro': (' - - ' - ' - '), - 'productType': 'DFP', - 'rateType': 'CPM', - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'lineItemType': 'STANDARD', - 'productSegmentation': { - 'geoSegment': { - 'targetedLocations': [ - {'id': '2840', - 'displayName': 'US'}, - {'id': '2344', - 'displayName': 'Hong Kong'} - ] - }, - 'adUnitSegments': [{ - 'adUnitId': (network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId']), - 'includeDescendants': 'true' - }] - } - } - - product_templates = product_template_service.createProductTemplates( - [product_template]) - - if product_templates: - for product_template in product_templates: - print('A programmatic product template with ID "%s" and name "%s" ' - 'was created.' % (product_template['id'], - product_template['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py deleted file mode 100755 index d86efd38..00000000 --- a/examples/ad_manager/v201811/product_template_service/get_sponsorship_product_templates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sponsorship product templates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201811') - # Create a statement to select product templates. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('lineItemType = :lineItemType') - .WithBindVariable('lineItemType', 'SPONSORSHIP')) - - # Retrieve a small amount of product templates at a time, paging - # through until all product templates have been retrieved. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - # Print out some information for each product template. - print('Product template with ID "%d" and name "%s" was found.\n' % - (product_template['id'], product_template['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/product_template_service/update_product_templates.py b/examples/ad_manager/v201811/product_template_service/update_product_templates.py deleted file mode 100755 index 5f9a16bb..00000000 --- a/examples/ad_manager/v201811/product_template_service/update_product_templates.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a product template's GeoTargeting. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201811') - - # Create a statement to select a single product template by ID. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', int(product_template_id)) - .Limit(1)) - - # Get product templates by statement. - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local product template object by appending a new geo-target. - for product_template in response['results']: - # Create geo-targeting for Canada to append. - location = { - 'id': '2124', - 'displayName': 'Canada' - } - - try: - targeting = product_template['builtInTargeting'] - - if 'geoTargeting' in targeting: - geo_targeting = targeting['geoTargeting'] - - if 'targetedLocations' in geo_targeting: - geo_targeting['targetedLocations'].append(location) - else: - geo_targeting['targetedLocations'] = [location] - else: - targeting['geoTargeting'] = { - 'targetedLocations': [location] - } - except KeyError: - product_template['builtInTargeting'] = { - 'geoTargeting': { - 'targetedLocations': [location] - } - } - - # Update products remotely. - product_templates = product_template_service.updateProductTemplates( - [product_template]) - - # Display results. - if product_templates: - for product_template in product_templates: - print('Product template with id "%s" and name "%s" was ' - 'updated.' % (product_template['id'], product_template['name'])) - else: - print('No product templates were updated.') - else: - print('No product templates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py deleted file mode 100755 index 29ed6054..00000000 --- a/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a new programmatic proposal line item. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set the ID of the programmatic proposal that the proposal line item will -# belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -# Set the ID of the Marketplace rate card the proposal line items should be -# priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, proposal_id, product_id, rate_card_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201811') - network_service = client.GetService('NetworkService', version='v201811') - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Create a single programmatic proposal line item. - proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for proposal line items. - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'rateCardId': rate_card_id, - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add programmatic proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print('Programmatic proposal line item with id "%s", belonging to ' - 'proposal id "%s", and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) - diff --git a/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py deleted file mode 100755 index ebe2725c..00000000 --- a/examples/ad_manager/v201811/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a programmatic proposal line item for non-sales management. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set proposal that the created proposal line item will belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, proposal_id, product_id): - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201811') - network_service = client.GetService('NetworkService', version='v201811') - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Create a single programmatic proposal line item. - proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for proposal line items. - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - }, - # Target Display environment by excluding Mobile Apps. - # DeviceCapabilities can be obtained though the Device_Capability PQL - # table: - # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService - 'technologyTargeting': { - 'deviceCapabilityTargeting': [{'id': 5005}] - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'creativePlaceholders': [{ - 'size': { - 'width': '300', - 'height': '250' - } - }, { - 'size': { - 'width': '120', - 'height': '600' - } - }], - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print('Programmatic proposal line item for non-sales management with id ' - '"%s", belonging to proposal id "%s", and named "%s" ' - 'was created.' % (proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID) - diff --git a/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py deleted file mode 100755 index 7a69ade4..00000000 --- a/examples/ad_manager/v201811/proposal_line_item_service/create_proposal_line_items.py +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates a new run-of-network proposal line item. - -To determine which proposal line items exist, run -get_all_proposal_line_items.py. To determine which proposals exist, run -get_all_proposals.py. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set proposal that the created proposal line item will belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -# Set the ID of the rate card the proposal line items should be priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, proposal_id, product_id, rate_card_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201811') - network_service = client.GetService('NetworkService', version='v201811') - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Create a single proposal line item. - proposal_line_item = { - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'rateCardId': rate_card_id, - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'deliveryRateType': 'EVENLY', - 'creativeRotationType': 'OPTIMIZED', - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'THIRD_PARTY_VOLUME', - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print('Proposal line item with id "%s", belonging to proposal id "%s"' - ', and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) - diff --git a/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals.py deleted file mode 100755 index dc41ac6b..00000000 --- a/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates new programmatic proposals. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' -BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' - - -def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, - buyer_id): - proposal_service = client.GetService('ProposalService', version='v201811') - network_service = client.GetService('NetworkService', version='v201811') - - proposal = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'buyerAccountId': buyer_id - }, - 'isProgrammatic': True, - # Setting required common fields for Proposals. - 'name': 'Proposal #%s' % uuid.uuid4(), - 'advertiser': { - 'companyId': advertiser_id, - 'type': 'ADVERTISER' - }, - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '100000' - }, - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - 'budget': { - 'microAmount': '100000000', - 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] - }, - } - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print('Programmatic proposal with id "%s" and name "%s" was created.' % - (proposal['id'], proposal['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID, BUYER_ID) diff --git a/examples/ad_manager/v201811/proposal_service/create_proposals.py b/examples/ad_manager/v201811/proposal_service/create_proposals.py deleted file mode 100755 index c411d010..00000000 --- a/examples/ad_manager/v201811/proposal_service/create_proposals.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new proposals. - -To determine which proposals exist, run get_all_proposals.py. -""" - - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' - - -def main(client, advertiser_id, primary_salesperson_id, - secondary_salesperson_id, primary_trafficker_id): - # Initialize appropriate services. - proposal_service = client.GetService('ProposalService', version='v201811') - network_service = client.GetService('NetworkService', version='v201811') - - # Create proposal objects. - proposal = { - 'name': 'Proposal #%s' % uuid.uuid4(), - 'advertiser': { - 'companyId': advertiser_id, - 'type': 'ADVERTISER' - }, - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '75000' - }, - 'secondarySalespeople': [{ - 'userId': secondary_salesperson_id, - 'split': '25000' - }], - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - 'budget': { - 'microAmount': '100000000', - 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] - }, - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'DFP_VOLUME' - } - - # Add proposals. - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print('Proposal with id "%s" and name "%s" was created.' - % (proposal['id'], proposal['name'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py deleted file mode 100755 index 59bab7c1..00000000 --- a/examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example approves a single proposal. - -To determine which proposals exist, run get_all_proposals.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201811') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :proposalId') - .WithBindVariable('proposalId', proposal_id)) - proposals_approved = 0 - - # Get proposals by statement. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for proposal in response['results']: - print('Proposal with id "%s", name "%s", and status "%s" will be' - ' approved.' % (proposal['id'], proposal['name'], - proposal['status'])) - # Perform action. - result = proposal_service.performProposalAction( - {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - proposals_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if proposals_approved > 0: - print('\nNumber of proposals approved: %s' % proposals_approved) - else: - print('\nNo proposals were approved.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py deleted file mode 100755 index 955e9806..00000000 --- a/examples/ad_manager/v201811/rate_card_service/create_rate_cards.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a new rate card. - -To determine which rate cards exist, run get_all_rate_cards.py. -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the IDs of the teams this rate card should be visible to. -TEAM_IDS = ['INSERT_TEAM_ID_HERE'] - -# Set the currency code to create the rate card with. -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201811') - - # Create a rate card. - rate_card = { - 'name': 'RateCard #%d' % random.randint(0, 100000000), - 'currencyCode': CURRENCY_CODE, - 'pricingModel': 'NET', - } - - # This field is optional. - rate_card['appliedTeamIds'] = TEAM_IDS - - result = rate_card_service.createRateCards([rate_card]) - - for new_rate_card in result: - print('A rate card with ID %s, name "%s", and currency code "%s" ' - 'was created.' % (new_rate_card['id'], - new_rate_card['name'], - new_rate_card['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py deleted file mode 100755 index 30352dc9..00000000 --- a/examples/ad_manager/v201811/rate_card_service/get_all_rate_cards.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 rate cards. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201811') - - # Create a statement to select rate cards. - statement = ad_manager.StatementBuilder(version='v201811') - - # Retrieve a small amount of rate cards at a time, paging - # through until all rate cards have been retrieved. - while True: - response = rate_card_service.getRateCardsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for rate_card in response['results']: - # Print out some information for each rate card. - print('Rate card with ID "%d", name "%s", and currency code "%s" was ' - 'found.\n' % - (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py deleted file mode 100755 index 00d67c27..00000000 --- a/examples/ad_manager/v201811/rate_card_service/get_marketplace_rate_cards.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 rate cards that can be used for Marketplace products. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201811') - # Create a statement to select rate cards. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('forMarketplace = :forMarketplace') - .WithBindVariable('forMarketplace', True)) - - # Retrieve a small amount of rate cards at a time, paging - # through until all rate cards have been retrieved. - while True: - response = rate_card_service.getRateCardsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for rate_card in response['results']: - # Print out some information for each rate card. - print( - 'Rate card with ID "%d", name "%s", and currency code "%s" was ' - 'found.\n' - % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py deleted file mode 100755 index 38ee9f7a..00000000 --- a/examples/ad_manager/v201811/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 line item reports for a given reconciliation report. - -To determine how many reconciliation reports exist, -run get_all_reconciliation_reports.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report to query. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201811')) - - # Create a statement to select reconciliation line item reports. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where(('reconciliationReportId = :reconciliationReportId AND ' - 'lineItemId != :lineItemId')) - .OrderBy('lineItemId', ascending=True) - .WithBindVariable('reconciliationReportId', - RECONCILIATION_REPORT_ID) - .WithBindVariable('lineItemId', 0)) - - # Retrieve a small amount of reconciliation line item reports at a time, - # paging through until all reconciliation line item reports have been - # retrieved. - result_set_size = 0 - should_continue = True - - while should_continue: - page = (reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement( - statement.ToStatement())) - if 'results' in page and len(page['results']): - result_set_size += page['totalResultSetSize'] - # Iterate over individual results in the page. - for line_item_report in page['results']: - print('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source "%s", and reconciled volume %d was ' - 'found.' % (line_item_report['id'], - line_item_report['lineItemId'], - line_item_report['reconciliationSource'], - (line_item_report['reconciledVolume'] - if 'reconciledVolume' in line_item_report else 0))) - # Update statement for next page. - statement.offset += statement.limit - should_continue = statement.offset < result_set_size - - print('Number of results found: %d' % result_set_size) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py deleted file mode 100755 index 729fb214..00000000 --- a/examples/ad_manager/v201811/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 updates a reconciliation line item report. - -To get reconciliation line item reports for a reconciliation report, run -get_reconciliation_line_item_reports_for_reconciliation_report.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation line item report to update. -RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201811')) - - # Create a statement to select a reconciliation line item report. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :lineItemReportId') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('lineItemReportId', - RECONCILIATION_LINE_ITEM_REPORT_ID)) - - # Get reconciliation line item reports by statement. - page = (reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement(statement.ToStatement())) - - line_item_report = page['results'][0] - - # Set and use a manual volume for billing. This example splits the difference - # between Ad Manager and the third party volume. - line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + - line_item_report['thirdPartyVolume']) / 2 - line_item_report['reconciliationSource'] = 'MANUAL' - - result = (reconciliation_line_item_report_service - .updateReconciliationLineItemReports([line_item_report])) - - for updated_report in result: - print('Reconciliation line item report with ID %d for line item ID %d was ' - 'updated, with manual volume %d' % (updated_report['id'], - updated_report['lineItemId'], - updated_report['manualVolume'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py deleted file mode 100755 index e15d03d2..00000000 --- a/examples/ad_manager/v201811/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. -"""Gets all reconciliation order reports for a given reconciliation report. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201811') - # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('reconciliationReportId = :reconciliationReportId') - .WithBindVariable('reconciliationReportId', - reconciliation_report_id)) - - # Retrieve a small amount of reconciliation order reports at a time, paging - # through until all reconciliation order reports have been retrieved. - while True: - response = ( - reconciliation_order_report_service - .getReconciliationOrderReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_order_report in response['results']: - # Print out some information for each reconciliation order report. - print('Reconciliation order report with ID "%d" and status "%s" was ' - 'found.\n' % (reconciliation_order_report['id'], - reconciliation_order_report['status'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py deleted file mode 100755 index 8859b7e2..00000000 --- a/examples/ad_manager/v201811/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 submits a reconciliation order report. - -To get all reconciliation order reports for a reconciliation report, -run get get_reconciliation_order_reports_for_reconciliation_report.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation order report to submit. -RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201811')) - - # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', RECONCILIATION_ORDER_REPORT_ID)) - - # Get reconciliation order reports by statement. - page = (reconciliation_order_report_service - .getReconciliationOrderReportsByStatement(statement.ToStatement())) - - report = page['results'][0] - - print('Reconciliation order report with ID %d will be submitted.' % - report['id']) - - # Remove limit and offset from statement. - statement.limit = None - statement.offset = None - - # Perform action. - result = (reconciliation_order_report_service - .performReconciliationOrderReportAction( - {'xsi_type': 'SubmitReconciliationOrderReports'}, - statement.ToStatement())) - - if result and result['numChanges'] > 0: - print('Number of reconciliation order reports submitted: %d' % - result['numChanges']) - else: - print('No reconciliation order reports were submitted.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py deleted file mode 100755 index 9ad5a924..00000000 --- a/examples/ad_manager/v201811/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets a reconciliation report's rows for line items that Ad Manager served. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report row. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201811') - - # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where(('reconciliationReportId = :reportId ' - 'AND lineItemId != :lineItemId')) - .WithBindVariable('lineItemId', 0) - .WithBindVariable('reportId', int(reconciliation_report_id))) - - # Retrieve a small amount of reconciliation report rows at a time, paging - # through until all reconciliation report rows have been retrieved. - while True: - response = ( - reconciliation_report_row_service - .getReconciliationReportRowsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report_row in response['results']: - # Print out some information for each reconciliation report row. - print('Reconciliation report row with ID "%d", reconciliation source ' - '"%s", and reconciled volume "%d" was found.\n' % - (reconciliation_report_row['id'], - reconciliation_report_row['reconciliationSource'], - reconciliation_report_row['reconciledVolume'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py deleted file mode 100755 index ebdd112f..00000000 --- a/examples/ad_manager/v201811/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 updates a reconciliation report row. - -To determine which reconciliation report rows exist, -run get_reconciliation_report_rows_for_reconciliation_report.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report row. -RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' - -# Set the ID of the reconciliation report. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201811')) - - # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where(('id = :reconciliationReportRowId AND ' - 'reconciliationReportId = :reconciliationReportId')) - .OrderBy('id', ascending=True) - .WithBindVariable('reconciliationReportRowId', - RECONCILIATION_REPORT_ROW_ID) - .WithBindVariable('reconciliationReportId', - RECONCILIATION_REPORT_ID)) - - # Get reconciliation report rows by statement. - page = (reconciliation_report_row_service - .getReconciliationReportRowsByStatement(statement.ToStatement())) - - row = page['results'][0] - - # Set a comment on the reconciliation report row. - row['comments'] = ('Third part volume didn\'t match DFP - we agreed to split ' - 'the difference') - - # Set and use a manual volume for billing. - row['manualVolume'] = (row['dfpVolume'] + row['thirdPartyVolume']) / 2 - row['reconciliationSource'] = 'MANUAL' - - updated_rows = (reconciliation_report_row_service - .updateReconciliationReportRows([row])) - - for updated_row in updated_rows: - print('Reconciliation report row for line item ID %d and creative ID %d ' - 'was updated, with manual volume %d' % (updated_row['lineItemId'], - updated_row['creativeId'], - updated_row['manualVolume'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py deleted file mode 100755 index 8a674ed2..00000000 --- a/examples/ad_manager/v201811/reconciliation_report_service/get_all_reconciliation_reports.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 reconciliation reports. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201811') - - # Create a statement to select reconciliation reports. - statement = ad_manager.StatementBuilder(version='v201811') - - # Retrieve a small amount of reconciliation reports at a time, paging - # through until all reconciliation reports have been retrieved. - while True: - response = ( - reconciliation_report_service - .getReconciliationReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report in response['results']: - # Print out some information for each reconciliation report. - print( - 'Reconciliation report with ID "%d", month "%d", and year "%d" was' - ' found.\n' % (reconciliation_report['id'], - reconciliation_report['startDate']['month'], - reconciliation_report['startDate']['year'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py deleted file mode 100755 index cbced6af..00000000 --- a/examples/ad_manager/v201811/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the previous billing period's reconciliation report. -""" - -# Import appropriate modules from the client library. -from datetime import date -from datetime import timedelta - -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201811') - - first_of_the_month = date.today().replace(day=1) - last_month = first_of_the_month - timedelta(days=1) - - # Create a statement to select reconciliation reports. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('startDate = :startDate') - .WithBindVariable('startDate', last_month)) - - # Retrieve a small amount of reconciliation reports at a time, paging - # through until all reconciliation reports have been retrieved. - while True: - response = ( - reconciliation_report_service - .getReconciliationReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report in response['results']: - # Print out some information for each reconciliation report. - print( - 'Reconciliation report with ID "%d" and start date "%s" was found.' - '\n' % (reconciliation_report['id'], - last_month.strftime('%Y-%m-01'))) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/report_service/__init__.py b/examples/ad_manager/v201811/report_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201811/report_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201811/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201811/suggested_ad_unit_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201811/suggested_ad_unit_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201811/team_service/__init__.py b/examples/ad_manager/v201811/team_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201811/team_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201811/user_service/__init__.py b/examples/ad_manager/v201811/user_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201811/user_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201811/user_team_association_service/__init__.py b/examples/ad_manager/v201811/user_team_association_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201811/user_team_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201811/workflow_request_service/__init__.py b/examples/ad_manager/v201811/workflow_request_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201811/workflow_request_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py deleted file mode 100755 index 3de7266b..00000000 --- a/examples/ad_manager/v201811/workflow_request_service/approve_workflow_approval_requests.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 approves all workflow approval requests belonging to a proposal. - -To determine which workflow approval requests exist, run -get_all_workflow_approval_requests.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201811') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where(('entityId = :entityId and entityType = :entityType ' - 'and type = :type')) - .WithBindVariable('entityId', proposal_id) - .WithBindVariable('entityType', 'PROPOSAL') - .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) - workflow_approval_requests_approved = 0 - - # Get workflow approval requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for workflow_approval_request in response['results']: - print('Workflow approval request with id "%s" will be' - ' approved.' % workflow_approval_request['id']) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'ApproveWorkflowApprovalRequests', - 'comment': 'This workflow has now been approved for submission.'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_approval_requests_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if workflow_approval_requests_approved > 0: - print('\nNumber of workflow approval requests approved: %s' % - workflow_approval_requests_approved) - else: - print('\nNo workflow approval requests were approved.') - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py deleted file mode 100755 index ee4ca81d..00000000 --- a/examples/ad_manager/v201811/workflow_request_service/get_workflow_approval_requests.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 workflow approval requests. - -Workflow approval requests must be approved or rejected for a workflow to -finish. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201811') - # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('type = :type') - .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) - - # Retrieve a small amount of workflow requests at a time, paging - # through until all workflow requests have been retrieved. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for workflow_request in response['results']: - # Print out some information for each workflow request. - print('Workflow request with ID "%d", entity type "%s", and entity ID ' - '"%d" was found.\n' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py deleted file mode 100755 index a007a631..00000000 --- a/examples/ad_manager/v201811/workflow_request_service/get_workflow_external_condition_requests.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 workflow external condition requests. - -Workflow external condition requests must be triggered or skipped for a -workflow to finish. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201811') - # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('type = :type') - .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) - - # Retrieve a small amount of workflow requests at a time, paging - # through until all workflow requests have been retrieved. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for workflow_request in response['results']: - # Print out some information for each workflow request. - print('Workflow request with ID "%d", entity type "%s", and entity ID ' - '"%d" was found.\n' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py deleted file mode 100755 index fdc12922..00000000 --- a/examples/ad_manager/v201811/workflow_request_service/trigger_workflow_external_condition_requests.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 triggers all workflow external condition requests for a proposal. - -Workflow external condition requests must be triggered or skipped for a workflow -to finish. To determine which proposals exist, run get_all_proposals.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201811') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where(('entityId = :entityId and entityType = :entityType ' - 'and type = :type')) - .WithBindVariable('entityId', proposal_id) - .WithBindVariable('entityType', 'PROPOSAL') - .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) - workflow_external_condition_requests_triggered = 0 - - # Get workflow external condition requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for workflow_request in response['results']: - print('Workflow external condition request with id "%s" for %s ' - 'with id "%s" will be triggered.' % - (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_external_condition_requests_triggered += int( - result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if workflow_external_condition_requests_triggered > 0: - print('\nNumber of workflow external condition requests triggered: %s' % - workflow_external_condition_requests_triggered) - else: - print('\nNo workflow external condition requests were triggered.') - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py deleted file mode 100755 index 34340533..00000000 --- a/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a new programmatic proposal line item. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set the ID of the programmatic proposal that the proposal line item will -# belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -# Set the ID of the Marketplace rate card the proposal line items should be -# priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, proposal_id, product_id, rate_card_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201902') - network_service = client.GetService('NetworkService', version='v201902') - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Create a single programmatic proposal line item. - proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for proposal line items. - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'rateCardId': rate_card_id, - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add programmatic proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print('Programmatic proposal line item with id "%s", belonging to ' - 'proposal id "%s", and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) - diff --git a/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py index d7295960..0f0bff70 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,12 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates a new run-of-network proposal line item. - -To determine which proposal line items exist, run -get_all_proposal_line_items.py. To determine which proposals exist, run -get_all_proposals.py. -""" +"""Creates a proposal line item.""" import datetime @@ -32,15 +27,8 @@ # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -# Set the ID of the rate card the proposal line items should be priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - -def main(client, proposal_id, product_id, rate_card_id): - # Initialize appropriate service. +def main(client, proposal_id): proposal_line_item_service = client.GetService( 'ProposalLineItemService', version='v201902') network_service = client.GetService('NetworkService', version='v201902') @@ -52,33 +40,50 @@ def main(client, proposal_id, product_id, rate_card_id): root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - # Create a single proposal line item. + # Create a single programmatic proposal line item. proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for proposal line items. 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'rateCardId': rate_card_id, - 'productId': product_id, 'proposalId': proposal_id, 'targeting': { 'inventoryTargeting': { 'targetedAdUnits': { 'adUnitId': root_ad_unit_id } + }, + # Target Display environment by excluding Mobile Apps. + # DeviceCapabilities can be obtained though the Device_Capability PQL + # table: + # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService + 'technologyTargeting': { + 'deviceCapabilityTargeting': [{'id': 5005}] } }, 'startDateTime': start_datetime, 'endDateTime': end_datetime, - 'deliveryRateType': 'EVENLY', - 'creativeRotationType': 'OPTIMIZED', - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'THIRD_PARTY_VOLUME', + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + } + }, + { + 'size': { + 'width': '120', + 'height': '600' + } + } + ], 'goal': { 'units': '1000', 'unitType': 'IMPRESSIONS', }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, 'netRate': { 'currencyCode': 'USD', 'microAmount': '2000000' @@ -92,14 +97,14 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print('Proposal line item with id "%s", belonging to proposal id "%s"' - ', and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", belonging to proposal with id "%s",' + ' and named "%s" was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals.py deleted file mode 100755 index da97b45f..00000000 --- a/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates new programmatic proposals. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' -BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' - - -def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, - buyer_id): - proposal_service = client.GetService('ProposalService', version='v201902') - network_service = client.GetService('NetworkService', version='v201902') - - proposal = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'buyerAccountId': buyer_id - }, - 'isProgrammatic': True, - # Setting required common fields for Proposals. - 'name': 'Proposal #%s' % uuid.uuid4(), - 'advertiser': { - 'companyId': advertiser_id, - 'type': 'ADVERTISER' - }, - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '100000' - }, - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - 'budget': { - 'microAmount': '100000000', - 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] - }, - } - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print('Programmatic proposal with id "%s" and name "%s" was created.' % - (proposal['id'], proposal['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID, BUYER_ID) diff --git a/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals_for_non_sales_management.py deleted file mode 100755 index a568913b..00000000 --- a/examples/ad_manager/v201902/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a programmatic proposal for networks not using sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' - - -def main(client, programmatic_buyer_id, primary_salesperson_id, - primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201902') - - proposal = { - # Setting required Marketplace information. - 'isProgrammatic': 'true', - 'marketplaceInfo': { - 'buyerAccountId': programmatic_buyer_id, - }, - # Set common required fields for proposals. - 'name': 'Proposal #%s' % uuid.uuid4(), - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '100000' - }, - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - } - - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print('Programmatic proposal with id "%s" and name "%s" was created.' % - (proposal['id'], proposal['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201902/proposal_service/create_proposals.py b/examples/ad_manager/v201902/proposal_service/create_proposals.py index d373d891..f8030b14 100755 --- a/examples/ad_manager/v201902/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201902/proposal_service/create_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,64 +14,48 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates new proposals. - -To determine which proposals exist, run get_all_proposals.py. -""" - +"""This example creates a proposal.""" import uuid # Import appropriate modules from the client library. from googleads import ad_manager -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' -def main(client, advertiser_id, primary_salesperson_id, - secondary_salesperson_id, primary_trafficker_id): - # Initialize appropriate services. +def main(client, programmatic_buyer_id, primary_salesperson_id, + primary_trafficker_id): proposal_service = client.GetService('ProposalService', version='v201902') - network_service = client.GetService('NetworkService', version='v201902') - # Create proposal objects. proposal = { - 'name': 'Proposal #%s' % uuid.uuid4(), - 'advertiser': { - 'companyId': advertiser_id, - 'type': 'ADVERTISER' + # Setting required Marketplace information. + 'isProgrammatic': 'true', + 'marketplaceInfo': { + 'buyerAccountId': programmatic_buyer_id, }, + # Set common required fields for proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), 'primarySalesperson': { 'userId': primary_salesperson_id, - 'split': '75000' + 'split': '100000' }, - 'secondarySalespeople': [{ - 'userId': secondary_salesperson_id, - 'split': '25000' - }], 'primaryTraffickerId': primary_trafficker_id, 'probabilityOfClose': '100000', - 'budget': { - 'microAmount': '100000000', - 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] - }, - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'DFP_VOLUME' } - # Add proposals. proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: - print('Proposal with id "%s" and name "%s" was created.' - % (proposal['id'], proposal['name'])) + print('Proposal with id "%s" and name "%s" was created.' % + (proposal['id'], proposal['name'])) + if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) + main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201902/proposal_service/get_proposals_awaiting_seller_review.py similarity index 89% rename from examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py rename to examples/ad_manager/v201902/proposal_service/get_proposals_awaiting_seller_review.py index 6ea9deee..8e3d1ac0 100755 --- a/examples/ad_manager/v201902/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201902/proposal_service/get_proposals_awaiting_seller_review.py @@ -13,8 +13,7 @@ # 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 proposals pending approval. -""" +"""This example gets all proposals awaiting seller review.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -25,8 +24,8 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201902') # Create a statement to select proposals. statement = (ad_manager.StatementBuilder(version='v201902') - .Where('status = :status') - .WithBindVariable('status', 'PENDING_APPROVAL')) + .Where('negotiationStatus = :negotiationStatus') + .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py deleted file mode 100755 index 2922015e..00000000 --- a/examples/ad_manager/v201902/proposal_service/submit_proposals_for_approval.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example approves a single proposal. - -To determine which proposals exist, run get_all_proposals.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201902') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :proposalId') - .WithBindVariable('proposalId', proposal_id)) - proposals_approved = 0 - - # Get proposals by statement. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for proposal in response['results']: - print('Proposal with id "%s", name "%s", and status "%s" will be' - ' approved.' % (proposal['id'], proposal['name'], - proposal['status'])) - # Perform action. - result = proposal_service.performProposalAction( - {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - proposals_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if proposals_approved > 0: - print('\nNumber of proposals approved: %s' % proposals_approved) - else: - print('\nNo proposals were approved.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py deleted file mode 100755 index dfd61a15..00000000 --- a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates a new programmatic proposal line item. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set the ID of the programmatic proposal that the proposal line item will -# belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -# Set the ID of the Marketplace rate card the proposal line items should be -# priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, proposal_id, product_id, rate_card_id): - # Initialize appropriate service. - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201905') - network_service = client.GetService('NetworkService', version='v201905') - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Create a single programmatic proposal line item. - proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for proposal line items. - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'rateCardId': rate_card_id, - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add programmatic proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print('Programmatic proposal line item with id "%s", belonging to ' - 'proposal id "%s", and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) - diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py deleted file mode 100755 index a8bfefdc..00000000 --- a/examples/ad_manager/v201905/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a programmatic proposal line item for non-sales management. -""" - - -import datetime -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager -import pytz - -# Set proposal that the created proposal line item will belong to. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, proposal_id, product_id): - proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201905') - network_service = client.GetService('NetworkService', version='v201905') - - start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) - end_datetime = start_datetime + datetime.timedelta(days=365) - - # Get the root ad unit to target. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Create a single programmatic proposal line item. - proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - - # Setting common required fields for proposal line items. - 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'productId': product_id, - 'proposalId': proposal_id, - 'targeting': { - 'inventoryTargeting': { - 'targetedAdUnits': { - 'adUnitId': root_ad_unit_id - } - }, - # Target Display environment by excluding Mobile Apps. - # DeviceCapabilities can be obtained though the Device_Capability PQL - # table: - # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService - 'technologyTargeting': { - 'deviceCapabilityTargeting': [{'id': 5005}] - } - }, - 'startDateTime': start_datetime, - 'endDateTime': end_datetime, - 'creativePlaceholders': [{ - 'size': { - 'width': '300', - 'height': '250' - } - }, { - 'size': { - 'width': '120', - 'height': '600' - } - }], - 'goal': { - 'units': '1000', - 'unitType': 'IMPRESSIONS', - }, - 'netRate': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, - 'rateType': 'CPM', - } - - # Add proposal line items. - proposal_line_items = proposal_line_item_service.createProposalLineItems( - [proposal_line_item]) - - # Display results. - for proposal_line_item in proposal_line_items: - print('Programmatic proposal line item for non-sales management with id ' - '"%s", belonging to proposal id "%s", and named "%s" ' - 'was created.' % (proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID) - diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py index 51bb7d79..3a92b420 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,12 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates a new run-of-network proposal line item. - -To determine which proposal line items exist, run -get_all_proposal_line_items.py. To determine which proposals exist, run -get_all_proposals.py. -""" +"""Creates a proposal line item.""" import datetime @@ -32,15 +27,8 @@ # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -# Set the ID of the rate card the proposal line items should be priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - -def main(client, proposal_id, product_id, rate_card_id): - # Initialize appropriate service. +def main(client, proposal_id): proposal_line_item_service = client.GetService( 'ProposalLineItemService', version='v201905') network_service = client.GetService('NetworkService', version='v201905') @@ -52,33 +40,50 @@ def main(client, proposal_id, product_id, rate_card_id): root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - # Create a single proposal line item. + # Create a single programmatic proposal line item. proposal_line_item = { + # Setting required Marketplace information. + 'marketplaceInfo': { + 'adExchangeEnvironment': 'DISPLAY' + }, + + # Setting common required fields for proposal line items. 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'rateCardId': rate_card_id, - 'productId': product_id, 'proposalId': proposal_id, 'targeting': { 'inventoryTargeting': { 'targetedAdUnits': { 'adUnitId': root_ad_unit_id } + }, + # Target Display environment by excluding Mobile Apps. + # DeviceCapabilities can be obtained though the Device_Capability PQL + # table: + # https://developers.google.com/ad-manager/api/reference/latest/PublisherQueryLanguageService + 'technologyTargeting': { + 'deviceCapabilityTargeting': [{'id': 5005}] } }, 'startDateTime': start_datetime, 'endDateTime': end_datetime, - 'deliveryRateType': 'EVENLY', - 'creativeRotationType': 'OPTIMIZED', - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'THIRD_PARTY_VOLUME', + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + } + }, + { + 'size': { + 'width': '120', + 'height': '600' + } + } + ], 'goal': { 'units': '1000', 'unitType': 'IMPRESSIONS', }, - 'netCost': { - 'currencyCode': 'USD', - 'microAmount': '2000000' - }, 'netRate': { 'currencyCode': 'USD', 'microAmount': '2000000' @@ -92,14 +97,14 @@ def main(client, proposal_id, product_id, rate_card_id): # Display results. for proposal_line_item in proposal_line_items: - print('Proposal line item with id "%s", belonging to proposal id "%s"' - ', and named "%s" was created.' % - (proposal_line_item['id'], proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", belonging to proposal with id "%s",' + ' and named "%s" was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID, RATE_CARD_ID) + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals.py b/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals.py deleted file mode 100755 index cd98aaa7..00000000 --- a/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 code example creates new programmatic proposals. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' -BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' - - -def main(client, advertiser_id, primary_salesperson_id, primary_trafficker_id, - buyer_id): - proposal_service = client.GetService('ProposalService', version='v201905') - network_service = client.GetService('NetworkService', version='v201905') - - proposal = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'buyerAccountId': buyer_id - }, - 'isProgrammatic': True, - # Setting required common fields for Proposals. - 'name': 'Proposal #%s' % uuid.uuid4(), - 'advertiser': { - 'companyId': advertiser_id, - 'type': 'ADVERTISER' - }, - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '100000' - }, - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - 'budget': { - 'microAmount': '100000000', - 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] - }, - } - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print('Programmatic proposal with id "%s" and name "%s" was created.' % - (proposal['id'], proposal['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID, BUYER_ID) diff --git a/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals_for_non_sales_management.py deleted file mode 100755 index a2068a47..00000000 --- a/examples/ad_manager/v201905/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Creates a programmatic proposal for networks not using sales management. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' -PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' - - -def main(client, programmatic_buyer_id, primary_salesperson_id, - primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201905') - - proposal = { - # Setting required Marketplace information. - 'isProgrammatic': 'true', - 'marketplaceInfo': { - 'buyerAccountId': programmatic_buyer_id, - }, - # Set common required fields for proposals. - 'name': 'Proposal #%s' % uuid.uuid4(), - 'primarySalesperson': { - 'userId': primary_salesperson_id, - 'split': '100000' - }, - 'primaryTraffickerId': primary_trafficker_id, - 'probabilityOfClose': '100000', - } - - proposals = proposal_service.createProposals([proposal]) - - # Display results. - for proposal in proposals: - print('Programmatic proposal with id "%s" and name "%s" was created.' % - (proposal['id'], proposal['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, - PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201905/proposal_service/create_proposals.py b/examples/ad_manager/v201905/proposal_service/create_proposals.py index 1d51eafc..1b8b5e0d 100755 --- a/examples/ad_manager/v201905/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201905/proposal_service/create_proposals.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2016 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. @@ -14,64 +14,48 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This code example creates new proposals. - -To determine which proposals exist, run get_all_proposals.py. -""" - +"""This example creates a proposal.""" import uuid # Import appropriate modules from the client library. from googleads import ad_manager -ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' +PROGRAMMATIC_BUYER_ID = 'INSERT_BUYER_ID_FROM_PQL_TABLE_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' -SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' -def main(client, advertiser_id, primary_salesperson_id, - secondary_salesperson_id, primary_trafficker_id): - # Initialize appropriate services. +def main(client, programmatic_buyer_id, primary_salesperson_id, + primary_trafficker_id): proposal_service = client.GetService('ProposalService', version='v201905') - network_service = client.GetService('NetworkService', version='v201905') - # Create proposal objects. proposal = { - 'name': 'Proposal #%s' % uuid.uuid4(), - 'advertiser': { - 'companyId': advertiser_id, - 'type': 'ADVERTISER' + # Setting required Marketplace information. + 'isProgrammatic': 'true', + 'marketplaceInfo': { + 'buyerAccountId': programmatic_buyer_id, }, + # Set common required fields for proposals. + 'name': 'Proposal #%s' % uuid.uuid4(), 'primarySalesperson': { 'userId': primary_salesperson_id, - 'split': '75000' + 'split': '100000' }, - 'secondarySalespeople': [{ - 'userId': secondary_salesperson_id, - 'split': '25000' - }], 'primaryTraffickerId': primary_trafficker_id, 'probabilityOfClose': '100000', - 'budget': { - 'microAmount': '100000000', - 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] - }, - 'billingCap': 'CAPPED_CUMULATIVE', - 'billingSource': 'DFP_VOLUME' } - # Add proposals. proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: - print('Proposal with id "%s" and name "%s" was created.' - % (proposal['id'], proposal['name'])) + print('Proposal with id "%s" and name "%s" was created.' % + (proposal['id'], proposal['name'])) + if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, - SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) + main(ad_manager_client, PROGRAMMATIC_BUYER_ID, PRIMARY_SALESPERSON_ID, + PRIMARY_TRAFFICKER_ID) diff --git a/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201905/proposal_service/get_proposals_awaiting_seller_review.py similarity index 89% rename from examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py rename to examples/ad_manager/v201905/proposal_service/get_proposals_awaiting_seller_review.py index c2575eeb..8f096ad1 100755 --- a/examples/ad_manager/v201905/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201905/proposal_service/get_proposals_awaiting_seller_review.py @@ -13,8 +13,7 @@ # 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 proposals pending approval. -""" +"""This example gets all proposals awaiting seller review.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -25,8 +24,8 @@ def main(client): proposal_service = client.GetService('ProposalService', version='v201905') # Create a statement to select proposals. statement = (ad_manager.StatementBuilder(version='v201905') - .Where('status = :status') - .WithBindVariable('status', 'PENDING_APPROVAL')) + .Where('negotiationStatus = :negotiationStatus') + .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py b/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py deleted file mode 100755 index 2e5cb8a1..00000000 --- a/examples/ad_manager/v201905/proposal_service/submit_proposals_for_approval.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example approves a single proposal. - -To determine which proposals exist, run get_all_proposals.py. -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201905') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :proposalId') - .WithBindVariable('proposalId', proposal_id)) - proposals_approved = 0 - - # Get proposals by statement. - while True: - response = proposal_service.getProposalsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for proposal in response['results']: - print('Proposal with id "%s", name "%s", and status "%s" will be' - ' approved.' % (proposal['id'], proposal['name'], - proposal['status'])) - # Perform action. - result = proposal_service.performProposalAction( - {'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - proposals_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if proposals_approved > 0: - print('\nNumber of proposals approved: %s' % proposals_approved) - else: - print('\nNo proposals were approved.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201811/activity_group_service/__init__.py b/examples/ad_manager/v201908/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/activity_group_service/__init__.py rename to examples/ad_manager/v201908/activity_group_service/__init__.py diff --git a/examples/ad_manager/v201811/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201908/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v201811/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v201908/activity_group_service/create_activity_groups.py index 409824a5..18bb07c5 100755 --- a/examples/ad_manager/v201811/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201908/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201811') + version='v201908') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201908/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v201908/activity_group_service/get_active_activity_groups.py index 7c7bc582..d0b7f3e5 100755 --- a/examples/ad_manager/v201811/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201908/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201811') + 'ActivityGroupService', version='v201908') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201908/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v201908/activity_group_service/get_all_activity_groups.py index 37a5cb79..40b701b9 100755 --- a/examples/ad_manager/v201811/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201908/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201811') + 'ActivityGroupService', version='v201908') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201811/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201908/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v201811/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v201908/activity_group_service/update_activity_groups.py index e85b1d86..87fbb707 100755 --- a/examples/ad_manager/v201811/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201908/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201811') + version='v201908') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/activity_service/__init__.py b/examples/ad_manager/v201908/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/activity_service/__init__.py rename to examples/ad_manager/v201908/activity_service/__init__.py diff --git a/examples/ad_manager/v201811/activity_service/create_activities.py b/examples/ad_manager/v201908/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v201811/activity_service/create_activities.py rename to examples/ad_manager/v201908/activity_service/create_activities.py index 89d0db2f..3c112186 100755 --- a/examples/ad_manager/v201811/activity_service/create_activities.py +++ b/examples/ad_manager/v201908/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201811') + activity_service = client.GetService('ActivityService', version='v201908') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v201811/activity_service/get_active_activities.py b/examples/ad_manager/v201908/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v201811/activity_service/get_active_activities.py rename to examples/ad_manager/v201908/activity_service/get_active_activities.py index 4db61a64..1d78348d 100755 --- a/examples/ad_manager/v201811/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201908/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201811') + activity_service = client.GetService('ActivityService', version='v201908') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201811/activity_service/get_all_activities.py b/examples/ad_manager/v201908/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v201811/activity_service/get_all_activities.py rename to examples/ad_manager/v201908/activity_service/get_all_activities.py index d4d99954..a98418f1 100755 --- a/examples/ad_manager/v201811/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201908/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201811') + activity_service = client.GetService('ActivityService', version='v201908') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201811/activity_service/update_activities.py b/examples/ad_manager/v201908/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v201811/activity_service/update_activities.py rename to examples/ad_manager/v201908/activity_service/update_activities.py index b2e73b72..92f5dcb2 100755 --- a/examples/ad_manager/v201811/activity_service/update_activities.py +++ b/examples/ad_manager/v201908/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201811') + activity_service = client.GetService('ActivityService', version='v201908') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/adjustment_service/create_traffic_adjustments.py b/examples/ad_manager/v201908/adjustment_service/create_traffic_adjustments.py new file mode 100755 index 00000000..3d17a011 --- /dev/null +++ b/examples/ad_manager/v201908/adjustment_service/create_traffic_adjustments.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 adds or replaces a forecast adjustment. + +The adjustment will affect 1920x1080 video traffic in the United States. +""" + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service and the network service. + adjustment_service = client.GetService('AdjustmentService', version='v201908') + network_service = client.GetService('NetworkService', version='v201908') + + # Get the root ad unit id to target the whole site. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create inventory targeting. + inventory_targeting = { + 'targetedAdUnits': [{ + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id + }] + } + + # Create geo targeting. When using geo targeting with the adjustment service, + # only locations of type COUNTRY are supported. You can download the latest + # geo targets at https://developers.google.com/ad-manager/api/geotargets. + geo_targeting = { + 'targetedLocations': [{ + 'id': 2840 + }] # USA. + } + + # Create ad unit size to define the slice of inventory affected by the + # traffic adjustment. + ad_unit_size = { + 'size': { + 'width': 1920, + 'height': 1080 + }, + 'environmentType': 'VIDEO_PLAYER' + } + + # Create a new historical adjustment targeting next year's January with 105% + # of the traffic of this year's January. + this_january = { + 'startDate': datetime.date(datetime.date.today().year, 1, 1), + 'endDate': datetime.date(datetime.date.today().year, 1, 31) + } + next_january = { + 'startDate': datetime.date(datetime.date.today().year + 1, 1, 1), + 'endDate': datetime.date(datetime.date.today().year + 1, 1, 31) + } + + january_segment = { + 'basisType': 'HISTORICAL', + 'historicalAdjustment': { + 'targetDateRange': next_january, + 'referenceDateRange': this_january, + 'milliPercentMultiplier': 105000 + } + } + + # Create a new absolute adjustment of 500,000 ad opportunities for Christmas + # and 1,000,000 opportunities for Boxing Day of next year. + christmas_day = datetime.date(datetime.date.today().year + 1, 12, 25) + boxing_day = christmas_day + datetime.timedelta(days=1) + holiday_range = {'startDate': christmas_day, 'endDate': boxing_day} + + holiday_segment = { + 'basisType': 'ABSOLUTE', + 'adjustmentTimeSeries': { + 'timeSeriesDateRange': holiday_range, + 'timeSeriesValues': [500000, 1000000], # xsd:long[] + 'valuePeriodType': 'DAILY' + } + } + + # Create a new absolute adjustment of 900,000 ad opportunities for the first + # week of September of next year. + first_week_of_september = { + 'startDate': datetime.date(datetime.date.today().year + 1, 9, 1), + 'endDate': datetime.date(datetime.date.today().year + 1, 9, 7) + } + + september_segment = { + 'basisType': 'ABSOLUTE', + 'adjustmentTimeSeries': { + 'timeSeriesDateRange': first_week_of_september, + 'timeSeriesValues': [900000], + 'valuePeriodType': 'CUSTOM' + } + } + + # Create traffic forecast adjustment object. + adjustment_segments = [january_segment, holiday_segment, september_segment] + adjustment = { + 'filterCriteria': { + 'targeting': { + 'inventoryTargeting': inventory_targeting, + 'geoTargeting': geo_targeting + }, + 'adUnitSizes': [ad_unit_size] + }, + 'forecastAdjustmentSegments': adjustment_segments + } + + # Create or update the traffic adjustment for the given filter criteria on + # the server. + updated_adjustments = adjustment_service.updateTrafficAdjustments( + [adjustment]) + + # Display the results. + for updated_adjustment in updated_adjustments: + print('Traffic forecast adjustment with id %d and %d segments was ' + 'created.' % (updated_adjustment['id'], + len(updated_adjustment['forecastAdjustmentSegments']))) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201908/adjustment_service/get_all_traffic_adjustments.py similarity index 54% rename from examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py rename to examples/ad_manager/v201908/adjustment_service/get_all_traffic_adjustments.py index c41b0612..8f8ac6a1 100755 --- a/examples/ad_manager/v201811/premium_rate_service/get_all_premium_rates.py +++ b/examples/ad_manager/v201908/adjustment_service/get_all_traffic_adjustments.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2016 Google Inc. All Rights Reserved. +# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,34 +13,33 @@ # 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 premium rates. -""" + +"""This example gets all traffic adjustments.""" + +from __future__ import print_function # Import appropriate modules from the client library. from googleads import ad_manager def main(client): - # Initialize appropriate service. - premium_rate_service = client.GetService( - 'PremiumRateService', version='v201811') + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v201908') - # Create a statement to select premium rates. - statement = ad_manager.StatementBuilder(version='v201811') + # Create a statement to get all forecast traffic adjustments. + statement = ad_manager.StatementBuilder(version='v201908') - # Retrieve a small amount of premium rates at a time, paging - # through until all premium rates have been retrieved. + # Retrieve a small number of traffic adjustments at a time, paging + # through until all traffic adjustments have been retrieved. while True: - response = premium_rate_service.getPremiumRatesByStatement( + response = adjustment_service.getTrafficAdjustmentsByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): - for premium_rate in response['results']: - # Print out some information for each premium rate. - print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'id "%d" was found.\n' % ( - premium_rate['id'], - ad_manager.AdManagerClassType(premium_rate), - premium_rate['rateCardId'])) + for adjustment in response['results']: + # Print out some information for each traffic adjustment. + print('Traffic forecast adjustment with id %d and %d segments was ' + 'found.' % (adjustment['id'], + len(adjustment['forecastAdjustmentSegments']))) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v201908/adjustment_service/update_traffic_adjustments.py b/examples/ad_manager/v201908/adjustment_service/update_traffic_adjustments.py new file mode 100755 index 00000000..eb6bb694 --- /dev/null +++ b/examples/ad_manager/v201908/adjustment_service/update_traffic_adjustments.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 adds a historical adjustment of 110% for New Years Day traffic. +""" + +from __future__ import print_function +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' + + +def main(client, adjustment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v201908') + + # Create a statement to select a single traffic forecast adjustment by id. + statement = ( + ad_manager.StatementBuilder( + version='v201908').Where('id = :id').WithBindVariable( + 'id', adjustment_id)) + + # Get the forecast traffic adjustment. + response = adjustment_service.getTrafficAdjustmentsByStatement( + statement.ToStatement()) + + # Create a new historical adjustment segment for New Year's Day. + this_new_years = datetime.date(datetime.date.today().year, 12, 31) + next_new_years = datetime.date(datetime.date.today().year + 1, 12, 31) + + new_years_segment = { + 'basisType': 'HISTORICAL', + 'historicalAdjustment': { + 'targetDateRange': { + 'startDate': next_new_years, + 'endDate': next_new_years + }, + 'referenceDateRange': { + 'startDate': this_new_years, + 'endDate': this_new_years + }, + 'milliPercentMultiplier': 110000 + } + } + + if 'results' in response and len(response['results']): + # Update each local traffic adjustment. + updated_adjustments = [] + for adjustment in response['results']: + adjustment['forecastAdjustmentSegments'].append(new_years_segment) + updated_adjustments.append(adjustment) + + # Update traffic adjustments remotely. + adjustments = adjustment_service.updateTrafficAdjustments( + updated_adjustments) + + # Display the results. + if adjustments: + for adjustment in adjustments: + print('Traffic forecast adjustment with id %d and %d segments was ' + 'created.' % (adjustment['id'], + len(adjustment['forecastAdjustmentSegments']))) + else: + print('No traffic adjustments were updated.') + else: + print('No traffic adjustments found to update.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v201811/audience_segment_service/__init__.py b/examples/ad_manager/v201908/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/audience_segment_service/__init__.py rename to examples/ad_manager/v201908/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201908/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v201908/audience_segment_service/create_audience_segments.py index f7eff0f3..9ece5256 100755 --- a/examples/ad_manager/v201811/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201908/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201811') - network_service = client.GetService('NetworkService', version='v201811') + 'AudienceSegmentService', version='v201908') + network_service = client.GetService('NetworkService', version='v201908') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201908/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v201908/audience_segment_service/get_all_audience_segments.py index 4e3c5682..f5f19393 100755 --- a/examples/ad_manager/v201811/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201908/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201811') + 'AudienceSegmentService', version='v201908') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201908/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v201908/audience_segment_service/get_first_party_audience_segments.py index 2410fe09..7f5cb482 100755 --- a/examples/ad_manager/v201811/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201908/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201811') + 'AudienceSegmentService', version='v201908') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201908/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v201908/audience_segment_service/populate_first_party_audience_segments.py index be95fc71..b381f866 100755 --- a/examples/ad_manager/v201811/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201908/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201811') + 'AudienceSegmentService', version='v201908') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201908/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v201908/audience_segment_service/update_audience_segments.py index 8d707f49..ae61d631 100755 --- a/examples/ad_manager/v201811/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201908/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201811') + 'AudienceSegmentService', version='v201908') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201811/cdn_configuration_service/__init__.py b/examples/ad_manager/v201908/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/cdn_configuration_service/__init__.py rename to examples/ad_manager/v201908/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v201811/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201908/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v201811/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v201908/cdn_configuration_service/create_cdn_configurations.py index 946ee564..635e42cd 100755 --- a/examples/ad_manager/v201811/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v201908/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201811') + version='v201908') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201908/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v201908/cdn_configuration_service/get_all_cdn_configurations.py index c7116db6..745933a9 100755 --- a/examples/ad_manager/v201811/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201908/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201811') + version='v201908') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v201811/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 59% rename from examples/ad_manager/v201811/product_package_service/get_all_product_packages.py rename to examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_keys.py index 205bce6a..ea456f49 100755 --- a/examples/ad_manager/v201811/product_package_service/get_all_product_packages.py +++ b/examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_keys.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2016 Google Inc. All Rights Reserved. +# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,31 +13,32 @@ # 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 product packages. -""" + +"""This example gets all CmsMetadataKeys.""" # Import appropriate modules from the client library. +from __future__ import print_function from googleads import ad_manager def main(client): # Initialize appropriate service. - product_package_service = client.GetService( - 'ProductPackageService', version='v201811') + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201908') - # Create a statement to select product packages. - statement = ad_manager.StatementBuilder(version='v201811') + # Create a statement to select CmsMetadataKeys. + statement = ad_manager.StatementBuilder(version='v201908') - # Retrieve a small amount of product packages at a time, paging - # through until all product packages have been retrieved. + # Retrieve a small amount of keys at a time, paging + # through until all keys have been retrieved. while True: - response = product_package_service.getProductPackagesByStatement( + response = cms_metadata_service.getCmsMetadataKeysByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): - for product_package in response['results']: - # Print out some information for each product package. - print('Product package with ID "%d" and name "%s" was found.\n' % - (product_package['id'], product_package['name'])) + for cms_metadata_key in response['results']: + # Print out some information for each key. + print('CMS metadata key with Id %d and name "%s" was found.\n' % + (cms_metadata_key['id'], cms_metadata_key['name'])) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_values.py similarity index 54% rename from examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py rename to examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_values.py index bd5d641d..8e006616 100755 --- a/examples/ad_manager/v201811/exchange_rate_service/get_all_exchange_rates.py +++ b/examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_values.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2016 Google Inc. All Rights Reserved. +# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,34 +13,35 @@ # 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 exchange rates. -""" + +"""This example gets all CmsMetadataValues.""" # Import appropriate modules from the client library. +from __future__ import print_function from googleads import ad_manager def main(client): # Initialize appropriate service. - exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201811') + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201908') - # Create a statement to select exchange rates. - statement = ad_manager.StatementBuilder(version='v201811') + # Create a statement to select CmsMetadataValues. + statement = ad_manager.StatementBuilder(version='v201908') - # Retrieve a small amount of exchange rates at a time, paging - # through until all exchange rates have been retrieved. + # Retrieve a small amount of values at a time, paging + # through until all values have been retrieved. while True: - response = exchange_rate_service.getExchangeRatesByStatement( + response = cms_metadata_service.getCmsMetadataValuesByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): - for exchange_rate in response['results']: - # Print out some information for each exchange rate. - print( - 'Exchange rate with ID "%d", currency code "%s", direction "%s", ' - 'and exchange rate "%d" was found.\n' % - (exchange_rate['id'], exchange_rate['currencyCode'], - exchange_rate['direction'], exchange_rate['exchangeRate'])) + for cms_metadata_value in response['results']: + # Print out some information for each value. + print(('CMS metadata value with Id %d and name "%s", associated with ' + 'the CmsMetadataKey with id %d and name "%s", was found.\n') % + (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'], cms_metadata_value['key']['id'], + cms_metadata_value['key']['name'])) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v201908/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v201908/cms_metadata_service/get_cms_metadata_values_for_key.py new file mode 100755 index 00000000..1831894c --- /dev/null +++ b/examples/ad_manager/v201908/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +# +# Copyright 2019 Google LLC +# +# 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 CmsMetadataValues for a particular CmsMetadataKey.""" + +# Import appropriate modules from the client library. +from __future__ import print_function +from googleads import ad_manager + +CMS_METADATA_KEY_NAME = 'INSERT_CMS_METADATA_KEY_NAME_HERE' + + +def main(client, cms_metadata_key_name): + # Initialize appropriate service. + cms_metadata_service = client.GetService( + 'CmsMetadataService', version='v201908') + + # Create a statement to select CmsMetadataValues for a particular key. + statement = ( + ad_manager.StatementBuilder(version='v201908').Where( + 'cmsKey = :cmsMetadataKeyName').WithBindVariable( + 'cmsMetadataKeyName', cms_metadata_key_name)) + + # Retrieve a small amount of values at a time, paging + # through until all values have been retrieved. + while True: + response = cms_metadata_service.getCmsMetadataValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_value in response['results']: + # Print out some information for each value. + print(('CMS metadata value with Id %d and name "%s", associated with ' + 'the CmsMetadataKey with id %d and name "%s", was found.\n') % + (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'], cms_metadata_value['key']['id'], + cms_metadata_value['key']['name'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CMS_METADATA_KEY_NAME) diff --git a/examples/ad_manager/v201811/base_rate_service/__init__.py b/examples/ad_manager/v201908/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/base_rate_service/__init__.py rename to examples/ad_manager/v201908/company_service/__init__.py diff --git a/examples/ad_manager/v201811/company_service/create_companies.py b/examples/ad_manager/v201908/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v201811/company_service/create_companies.py rename to examples/ad_manager/v201908/company_service/create_companies.py index 83ccc417..dd6033fa 100755 --- a/examples/ad_manager/v201811/company_service/create_companies.py +++ b/examples/ad_manager/v201908/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201811') + company_service = client.GetService('CompanyService', version='v201908') # Create company objects. companies = [ diff --git a/examples/ad_manager/v201811/company_service/get_advertisers.py b/examples/ad_manager/v201908/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v201811/company_service/get_advertisers.py rename to examples/ad_manager/v201908/company_service/get_advertisers.py index d7cee10d..243e30cc 100755 --- a/examples/ad_manager/v201811/company_service/get_advertisers.py +++ b/examples/ad_manager/v201908/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201811') + company_service = client.GetService('CompanyService', version='v201908') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201811/company_service/get_all_companies.py b/examples/ad_manager/v201908/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v201811/company_service/get_all_companies.py rename to examples/ad_manager/v201908/company_service/get_all_companies.py index 54dff40a..91311ed2 100755 --- a/examples/ad_manager/v201811/company_service/get_all_companies.py +++ b/examples/ad_manager/v201908/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201811') + company_service = client.GetService('CompanyService', version='v201908') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201811/company_service/update_companies.py b/examples/ad_manager/v201908/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v201811/company_service/update_companies.py rename to examples/ad_manager/v201908/company_service/update_companies.py index 0372a3ad..5b485e11 100755 --- a/examples/ad_manager/v201811/company_service/update_companies.py +++ b/examples/ad_manager/v201908/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201811') + company_service = client.GetService('CompanyService', version='v201908') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/company_service/__init__.py b/examples/ad_manager/v201908/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/company_service/__init__.py rename to examples/ad_manager/v201908/contact_service/__init__.py diff --git a/examples/ad_manager/v201811/contact_service/create_contacts.py b/examples/ad_manager/v201908/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v201811/contact_service/create_contacts.py rename to examples/ad_manager/v201908/contact_service/create_contacts.py index 16457695..b9ffc2e2 100755 --- a/examples/ad_manager/v201811/contact_service/create_contacts.py +++ b/examples/ad_manager/v201908/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201811') + contact_service = client.GetService('ContactService', version='v201908') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v201811/contact_service/get_all_contacts.py b/examples/ad_manager/v201908/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v201811/contact_service/get_all_contacts.py rename to examples/ad_manager/v201908/contact_service/get_all_contacts.py index f9dea551..1867a5df 100755 --- a/examples/ad_manager/v201811/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201908/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201811') + contact_service = client.GetService('ContactService', version='v201908') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201908/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v201908/contact_service/get_uninvited_contacts.py index fdf9d459..f67b7b58 100755 --- a/examples/ad_manager/v201811/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201908/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201811') + contact_service = client.GetService('ContactService', version='v201908') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201811/contact_service/update_contacts.py b/examples/ad_manager/v201908/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v201811/contact_service/update_contacts.py rename to examples/ad_manager/v201908/contact_service/update_contacts.py index 5e3b13d4..d90e9914 100755 --- a/examples/ad_manager/v201811/contact_service/update_contacts.py +++ b/examples/ad_manager/v201908/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201811') + contact_service = client.GetService('ContactService', version='v201908') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/contact_service/__init__.py b/examples/ad_manager/v201908/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/contact_service/__init__.py rename to examples/ad_manager/v201908/content_service/__init__.py diff --git a/examples/ad_manager/v201811/content_service/get_all_content.py b/examples/ad_manager/v201908/content_service/get_all_content.py similarity index 95% rename from examples/ad_manager/v201811/content_service/get_all_content.py rename to examples/ad_manager/v201908/content_service/get_all_content.py index ad8e4fcc..70d0738e 100755 --- a/examples/ad_manager/v201811/content_service/get_all_content.py +++ b/examples/ad_manager/v201908/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201811') + content_service = client.GetService('ContentService', version='v201908') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v201811/content_service/__init__.py b/examples/ad_manager/v201908/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/content_service/__init__.py rename to examples/ad_manager/v201908/creative_service/__init__.py diff --git a/examples/ad_manager/v201811/creative_service/copy_image_creatives.py b/examples/ad_manager/v201908/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v201811/creative_service/copy_image_creatives.py rename to examples/ad_manager/v201908/creative_service/copy_image_creatives.py index b1e0df83..3c28ef42 100755 --- a/examples/ad_manager/v201811/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201908/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201811') + creative_service = client.GetService('CreativeService', version='v201908') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201811/creative_service/create_creative_from_template.py b/examples/ad_manager/v201908/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v201811/creative_service/create_creative_from_template.py rename to examples/ad_manager/v201908/creative_service/create_creative_from_template.py index a812dceb..04346c59 100755 --- a/examples/ad_manager/v201811/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201908/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201811') + creative_service = client.GetService('CreativeService', version='v201908') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v201811/creative_service/create_creatives.py b/examples/ad_manager/v201908/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v201811/creative_service/create_creatives.py rename to examples/ad_manager/v201908/creative_service/create_creatives.py index 3d5beb72..f2c4a2d1 100755 --- a/examples/ad_manager/v201811/creative_service/create_creatives.py +++ b/examples/ad_manager/v201908/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201811') + creative_service = client.GetService('CreativeService', version='v201908') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v201811/creative_service/create_custom_creative.py b/examples/ad_manager/v201908/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v201811/creative_service/create_custom_creative.py rename to examples/ad_manager/v201908/creative_service/create_custom_creative.py index fa6385f3..9a4ee533 100755 --- a/examples/ad_manager/v201811/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201908/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201811') + creative_service = client.GetService('CreativeService', version='v201908') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v201811/creative_service/create_native_creative.py b/examples/ad_manager/v201908/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v201811/creative_service/create_native_creative.py rename to examples/ad_manager/v201908/creative_service/create_native_creative.py index bdc83a08..87482aa1 100755 --- a/examples/ad_manager/v201811/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201908/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201811') + creative_service = client.GetService('CreativeService', version='v201908') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v201811/creative_service/get_all_creatives.py b/examples/ad_manager/v201908/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v201811/creative_service/get_all_creatives.py rename to examples/ad_manager/v201908/creative_service/get_all_creatives.py index 0038fb66..c4c6a3eb 100755 --- a/examples/ad_manager/v201811/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201908/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201811') + creative_service = client.GetService('CreativeService', version='v201908') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201811/creative_service/get_image_creatives.py b/examples/ad_manager/v201908/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v201811/creative_service/get_image_creatives.py rename to examples/ad_manager/v201908/creative_service/get_image_creatives.py index 5c0971ff..e9e96a24 100755 --- a/examples/ad_manager/v201811/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201908/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201811') + creative_service = client.GetService('CreativeService', version='v201908') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201811/creative_service/update_creatives.py b/examples/ad_manager/v201908/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v201811/creative_service/update_creatives.py rename to examples/ad_manager/v201908/creative_service/update_creatives.py index 29a5985c..7eee0216 100755 --- a/examples/ad_manager/v201811/creative_service/update_creatives.py +++ b/examples/ad_manager/v201908/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201811') + creative_service = client.GetService('CreativeService', version='v201908') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v201811/creative_service/__init__.py b/examples/ad_manager/v201908/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/creative_service/__init__.py rename to examples/ad_manager/v201908/creative_set_service/__init__.py diff --git a/examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201908/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v201908/creative_set_service/associate_creative_set_to_line_item.py index cfc54536..beac079a 100755 --- a/examples/ad_manager/v201811/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201908/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201811') + 'LineItemCreativeAssociationService', version='v201908') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v201811/creative_set_service/create_creative_set.py b/examples/ad_manager/v201908/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v201811/creative_set_service/create_creative_set.py rename to examples/ad_manager/v201908/creative_set_service/create_creative_set.py index db2b15af..794414b1 100755 --- a/examples/ad_manager/v201811/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201908/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201811') + version='v201908') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201908/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v201908/creative_set_service/get_all_creative_sets.py index 0221291b..3cc0ca07 100755 --- a/examples/ad_manager/v201811/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201908/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201811') + 'CreativeSetService', version='v201908') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201908/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v201908/creative_set_service/get_creative_sets_for_master_creative.py index cc6ed2d3..70716293 100755 --- a/examples/ad_manager/v201811/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201908/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201811') + 'CreativeSetService', version='v201908') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201811/creative_set_service/update_creative_set.py b/examples/ad_manager/v201908/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v201811/creative_set_service/update_creative_set.py rename to examples/ad_manager/v201908/creative_set_service/update_creative_set.py index 18557638..cda2f52a 100755 --- a/examples/ad_manager/v201811/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201908/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201811') + version='v201908') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v201811/creative_set_service/__init__.py b/examples/ad_manager/v201908/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/creative_set_service/__init__.py rename to examples/ad_manager/v201908/creative_template_service/__init__.py diff --git a/examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201908/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v201908/creative_template_service/get_all_creative_templates.py index 17a1ff03..cc688f2c 100755 --- a/examples/ad_manager/v201811/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201908/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201811') + 'CreativeTemplateService', version='v201908') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201908/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v201908/creative_template_service/get_system_defined_creative_templates.py index 31c2beaa..a15d5c40 100755 --- a/examples/ad_manager/v201811/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201908/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201811') + 'CreativeTemplateService', version='v201908') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201908/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v201908/creative_wrapper_service/create_creative_wrappers.py index c2d064d2..08503298 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201908/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201811') + version='v201908') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201908/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v201908/creative_wrapper_service/deactivate_creative_wrapper.py index 8fb0ae2a..d556fcce 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201908/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201811') + version='v201908') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201908/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v201908/creative_wrapper_service/get_active_creative_wrappers.py index f581577d..b703f94c 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201908/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201811') + 'CreativeWrapperService', version='v201908') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201908/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v201908/creative_wrapper_service/get_all_creative_wrappers.py index 752122e7..30d5c38e 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201908/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201811') + 'CreativeWrapperService', version='v201908') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201908/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v201908/creative_wrapper_service/update_creative_wrappers.py index 2aae91ca..00fc4fed 100755 --- a/examples/ad_manager/v201811/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201908/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201811') + version='v201908') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v201811/creative_template_service/__init__.py b/examples/ad_manager/v201908/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/creative_template_service/__init__.py rename to examples/ad_manager/v201908/custom_field_service/__init__.py diff --git a/examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201908/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v201908/custom_field_service/create_custom_field_options.py index 5aaa0531..48185467 100755 --- a/examples/ad_manager/v201811/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201908/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201811') + 'CustomFieldService', version='v201908') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v201811/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201908/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v201811/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v201908/custom_field_service/create_custom_fields.py index 6a826a29..d32e4340 100755 --- a/examples/ad_manager/v201811/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201908/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201811') + 'CustomFieldService', version='v201908') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201908/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v201908/custom_field_service/deactivate_all_line_item_custom_fields.py index 61e2b342..100cd53e 100755 --- a/examples/ad_manager/v201811/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201908/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201811') + 'CustomFieldService', version='v201908') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201908/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v201908/custom_field_service/get_all_custom_fields.py index 2fb8a8ce..9efaacbd 100755 --- a/examples/ad_manager/v201811/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201908/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201811') + 'CustomFieldService', version='v201908') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201908/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v201908/custom_field_service/get_custom_fields_for_line_items.py index 01cbc8f6..98ff74c8 100755 --- a/examples/ad_manager/v201811/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201908/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201811') + 'CustomFieldService', version='v201908') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201908/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v201908/custom_field_service/set_line_item_custom_field_value.py index f45af2f5..5ca21a23 100755 --- a/examples/ad_manager/v201811/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201908/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201811') + 'CustomFieldService', version='v201908') - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v201811') + custom_field_statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v201811') + ad_manager.StatementBuilder(version='v201908') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v201811') + line_item_statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201811/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201908/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v201811/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v201908/custom_field_service/update_custom_fields.py index 419aca99..87071178 100755 --- a/examples/ad_manager/v201811/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201908/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201811') + 'CustomFieldService', version='v201908') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v201811/custom_field_service/__init__.py b/examples/ad_manager/v201908/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/custom_field_service/__init__.py rename to examples/ad_manager/v201908/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201908/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201908/custom_targeting_service/create_custom_targeting_keys_and_values.py index 020d6ed0..383f9bdc 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201908/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201811') + 'CustomTargetingService', version='v201908') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_keys.py index 771cc288..7842fd42 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201811') + 'CustomTargetingService', version='v201908') - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v201811') + key_statement = (ad_manager.StatementBuilder(version='v201908') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_values.py index 4550b2eb..e9a16725 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201811') + 'CustomTargetingService', version='v201908') - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v201811') + value_statement = (ad_manager.StatementBuilder(version='v201908') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201908/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201908/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index fb8290c3..58a5f152 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201908/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201811') + 'CustomTargetingService', version='v201908') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v201811') + targeting_key_statement = ad_manager.StatementBuilder(version='v201908') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201908/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201908/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 906dbc68..3239dab6 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201908/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201811') + 'CustomTargetingService', version='v201908') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v201811') + targeting_key_statement = (ad_manager.StatementBuilder(version='v201908') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_keys.py index cc11ceec..de6c7575 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201811') + 'CustomTargetingService', version='v201908') - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_values.py index 2a31f92c..dc79104c 100755 --- a/examples/ad_manager/v201811/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201811') + 'CustomTargetingService', version='v201908') - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201908/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v201811/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v201908/forecast_service/get_availability_forecast.py index bd8823a0..7ccdd6e9 100755 --- a/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v201908/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201811') - network_service = client.GetService('NetworkService', version='v201811') + forecast_service = client.GetService('ForecastService', version='v201908') + network_service = client.GetService('NetworkService', version='v201908') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201908/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v201908/forecast_service/get_availability_forecast_for_line_item.py index 89abd1f8..999566ba 100755 --- a/examples/ad_manager/v201811/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201908/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201811') + forecast_service = client.GetService('ForecastService', version='v201908') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201908/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v201908/forecast_service/get_delivery_forecast_for_line_items.py index 8d28987b..05c698b4 100755 --- a/examples/ad_manager/v201811/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201908/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201811') + forecast_service = client.GetService('ForecastService', version='v201908') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v201811/custom_targeting_service/__init__.py b/examples/ad_manager/v201908/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/custom_targeting_service/__init__.py rename to examples/ad_manager/v201908/inventory_service/__init__.py diff --git a/examples/ad_manager/v201811/inventory_service/archive_ad_units.py b/examples/ad_manager/v201908/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v201811/inventory_service/archive_ad_units.py rename to examples/ad_manager/v201908/inventory_service/archive_ad_units.py index 20306421..7cbdbc8c 100755 --- a/examples/ad_manager/v201811/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201908/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201811') + inventory_service = client.GetService('InventoryService', version='v201908') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v201811/inventory_service/create_ad_units.py b/examples/ad_manager/v201908/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v201811/inventory_service/create_ad_units.py rename to examples/ad_manager/v201908/inventory_service/create_ad_units.py index 37234564..2d8e97b6 100755 --- a/examples/ad_manager/v201811/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201908/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201811') + inventory_service = client.GetService('InventoryService', version='v201908') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201908/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v201908/inventory_service/get_ad_unit_hierarchy.py index a018637f..51a96c37 100755 --- a/examples/ad_manager/v201811/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201908/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201811') - inventory_service = client.GetService('InventoryService', version='v201811') + network_service = client.GetService('NetworkService', version='v201908') + inventory_service = client.GetService('InventoryService', version='v201908') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201811/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201908/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v201811/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v201908/inventory_service/get_all_ad_unit_sizes.py index 15a46a52..96538d76 100755 --- a/examples/ad_manager/v201811/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201908/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201811') + 'InventoryService', version='v201908') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201811/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201908/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v201811/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v201908/inventory_service/get_all_ad_units.py index 9258d35d..dbaea8d6 100755 --- a/examples/ad_manager/v201811/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201908/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201811') + ad_unit_service = client.GetService('InventoryService', version='v201908') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201908/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v201908/inventory_service/get_top_level_ad_units.py index 1201f131..28084dd9 100755 --- a/examples/ad_manager/v201811/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201908/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201811') - inventory_service = client.GetService('InventoryService', version='v201811') + network_service = client.GetService('NetworkService', version='v201908') + inventory_service = client.GetService('InventoryService', version='v201908') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201811/inventory_service/update_ad_units.py b/examples/ad_manager/v201908/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v201811/inventory_service/update_ad_units.py rename to examples/ad_manager/v201908/inventory_service/update_ad_units.py index 187f197a..901040d7 100755 --- a/examples/ad_manager/v201811/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201908/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201811') + inventory_service = client.GetService('InventoryService', version='v201908') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201811/exchange_rate_service/__init__.py b/examples/ad_manager/v201908/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/exchange_rate_service/__init__.py rename to examples/ad_manager/v201908/label_service/__init__.py diff --git a/examples/ad_manager/v201811/label_service/create_labels.py b/examples/ad_manager/v201908/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v201811/label_service/create_labels.py rename to examples/ad_manager/v201908/label_service/create_labels.py index f863ba7a..27b54906 100755 --- a/examples/ad_manager/v201811/label_service/create_labels.py +++ b/examples/ad_manager/v201908/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201811') + label_service = client.GetService('LabelService', version='v201908') # Create label objects. labels = [] diff --git a/examples/ad_manager/v201811/label_service/deactivate_labels.py b/examples/ad_manager/v201908/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v201811/label_service/deactivate_labels.py rename to examples/ad_manager/v201908/label_service/deactivate_labels.py index 2035fbda..45d42733 100755 --- a/examples/ad_manager/v201811/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201908/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201811') + label_service = client.GetService('LabelService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201811/label_service/get_active_labels.py b/examples/ad_manager/v201908/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v201811/label_service/get_active_labels.py rename to examples/ad_manager/v201908/label_service/get_active_labels.py index 60808671..5953ea39 100755 --- a/examples/ad_manager/v201811/label_service/get_active_labels.py +++ b/examples/ad_manager/v201908/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201811') + label_service = client.GetService('LabelService', version='v201908') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201811/label_service/get_all_labels.py b/examples/ad_manager/v201908/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v201811/label_service/get_all_labels.py rename to examples/ad_manager/v201908/label_service/get_all_labels.py index d8e0544c..1e7ffbbb 100755 --- a/examples/ad_manager/v201811/label_service/get_all_labels.py +++ b/examples/ad_manager/v201908/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201811') + label_service = client.GetService('LabelService', version='v201908') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201811/label_service/update_labels.py b/examples/ad_manager/v201908/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v201811/label_service/update_labels.py rename to examples/ad_manager/v201908/label_service/update_labels.py index 18f52663..354d8a68 100755 --- a/examples/ad_manager/v201811/label_service/update_labels.py +++ b/examples/ad_manager/v201908/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201811') + label_service = client.GetService('LabelService', version='v201908') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201811/inventory_service/__init__.py b/examples/ad_manager/v201908/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/inventory_service/__init__.py rename to examples/ad_manager/v201908/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201908/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v201908/line_item_creative_association_service/create_licas.py index ee40debf..ea62da96 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201908/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201811') + 'LineItemCreativeAssociationService', version='v201908') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201908/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v201908/line_item_creative_association_service/deactivate_licas.py index ca558875..29c06fb8 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201908/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201811') + 'LineItemCreativeAssociationService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201908/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v201908/line_item_creative_association_service/get_all_licas.py index 8108c15d..288784e7 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201908/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201811') + 'LineItemCreativeAssociationService', version='v201908') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201908/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v201908/line_item_creative_association_service/get_licas_for_line_item.py index 551ad705..5ed2efa7 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201908/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201811') + 'LineItemCreativeAssociationService', version='v201908') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201908/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v201908/line_item_creative_association_service/update_licas.py index 82b0ed09..e8a28266 100755 --- a/examples/ad_manager/v201811/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201908/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201811') + 'LineItemCreativeAssociationService', version='v201908') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201811/label_service/__init__.py b/examples/ad_manager/v201908/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/label_service/__init__.py rename to examples/ad_manager/v201908/line_item_service/__init__.py diff --git a/examples/ad_manager/v201811/line_item_service/activate_line_items.py b/examples/ad_manager/v201908/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v201811/line_item_service/activate_line_items.py rename to examples/ad_manager/v201908/line_item_service/activate_line_items.py index df2b50d6..00d1264b 100755 --- a/examples/ad_manager/v201811/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201908/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201811/line_item_service/create_line_items.py b/examples/ad_manager/v201908/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v201811/line_item_service/create_line_items.py rename to examples/ad_manager/v201908/line_item_service/create_line_items.py index bda701c9..51b1e5e7 100755 --- a/examples/ad_manager/v201811/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201908/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201811/line_item_service/create_video_line_item.py b/examples/ad_manager/v201908/line_item_service/create_video_line_item.py similarity index 66% rename from examples/ad_manager/v201811/line_item_service/create_video_line_item.py rename to examples/ad_manager/v201908/line_item_service/create_video_line_item.py index 97909aac..4856cbe5 100755 --- a/examples/ad_manager/v201811/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v201908/line_item_service/create_video_line_item.py @@ -19,7 +19,6 @@ This feature is only available to Ad Manager 360 solution networks. """ - import datetime import uuid @@ -36,63 +35,69 @@ CONTENT_ID = 'INSERT_CONTENT_ID_HERE' # Set the video content bundle to target. CONTENT_BUNDLE_ID = 'INSERT_CONTENT_BUNDLE_ID_HERE' +# Set the CMS metadata value to target. +CMS_METADATA_VALUE_ID = 'INSERT_CMS_METADATA_VALUE_ID_HERE' def main(client, order_id, targeted_video_ad_unit_id, content_id, - content_bundle_id): + content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) # Create line item object. line_item = { - 'name': - 'Line item #%s' % uuid.uuid4(), - 'orderId': - order_id, + 'name': 'Line item #%s' % uuid.uuid4(), + 'orderId': order_id, 'targeting': { 'contentTargeting': { 'targetedContentIds': [content_id], - 'targetedContentBundleIds': [content_bundle_id] + 'targetedVideoContentBundleIds': [content_bundle_id] + }, + 'customTargeting': { + 'logicalOperator': 'AND', + 'children': [{ + 'xsi_type': 'CmsMetadataCriteria', + 'cmsMetadataValueIds': [cms_metadata_value_id], + 'operator': 'EQUALS' + }] }, 'inventoryTargeting': { - 'targetedAdUnits': [{'adUnitId': targeted_video_ad_unit_id, - 'includeDescendants': 'true'}] + 'targetedAdUnits': [{ + 'adUnitId': targeted_video_ad_unit_id, + 'includeDescendants': 'true' + }] + }, + 'requestPlatformTargeting': { + 'targetedRequestPlatforms': ['VIDEO_PLAYER'] }, 'videoPositionTargeting': { - 'targetedPositions': [ - { - 'videoPosition': { - 'positionType': 'PREROLL' - } + 'targetedPositions': [{ + 'videoPosition': { + 'positionType': 'PREROLL' } - ] + }] } }, - 'creativePlaceholders': [ - { + 'creativePlaceholders': [{ + 'size': { + 'width': '400', + 'height': '300' + }, + 'companions': [{ 'size': { - 'width': '400', - 'height': '300' + 'width': '300', + 'height': '250' }, - 'companions': [ - { - 'size': { - 'width': '300', - 'height': '250' - }, - }, - { - 'size': { - 'width': '728', - 'height': '90' - }, - } - ] - } - ], + }, { + 'size': { + 'width': '728', + 'height': '90' + }, + }] + }], 'environmentType': 'VIDEO_PLAYER', 'companionDeliveryOption': 'OPTIONAL', 'startDateTimeType': 'IMMEDIATELY', @@ -115,7 +120,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, } # Add line item. - line_item = line_item_service.createLineItem(line_item) + line_item = line_item_service.createLineItems([line_item])[0] # Display results. print('Video line item with id "%s", belonging to order id "%s", and ' @@ -126,4 +131,4 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, ORDER_ID, TARGETED_VIDEO_AD_UNIT_ID, CONTENT_ID, - CONTENT_BUNDLE_ID) + CONTENT_BUNDLE_ID, CMS_METADATA_VALUE_ID) diff --git a/examples/ad_manager/v201811/line_item_service/get_all_line_items.py b/examples/ad_manager/v201908/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v201811/line_item_service/get_all_line_items.py rename to examples/ad_manager/v201908/line_item_service/get_all_line_items.py index 058eb99c..2c606b43 100755 --- a/examples/ad_manager/v201811/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201908/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201908/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v201908/line_item_service/get_line_items_that_need_creatives.py index 3756b1f0..f678232e 100755 --- a/examples/ad_manager/v201811/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201908/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201908/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v201908/line_item_service/get_recently_updated_line_items.py index 15792ebe..61ee1c24 100755 --- a/examples/ad_manager/v201811/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201908/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201811/line_item_service/pause_line_items.py b/examples/ad_manager/v201908/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v201811/line_item_service/pause_line_items.py rename to examples/ad_manager/v201908/line_item_service/pause_line_items.py index efa02d80..41549b64 100755 --- a/examples/ad_manager/v201811/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201908/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201811/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201908/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v201811/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v201908/line_item_service/target_custom_criteria.py index 84e6f570..d8248b4f 100755 --- a/examples/ad_manager/v201811/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201908/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/line_item_service/update_line_items.py b/examples/ad_manager/v201908/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v201811/line_item_service/update_line_items.py rename to examples/ad_manager/v201908/line_item_service/update_line_items.py index 2f06c8dd..95ed5978 100755 --- a/examples/ad_manager/v201811/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201908/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201908/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v201908/live_stream_event_service/activate_live_stream_events.py index 5335d4f0..99e1994e 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201908/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201811') + 'LiveStreamEventService', version='v201908') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201811/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201908/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v201811/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v201908/live_stream_event_service/create_live_stream_events.py index 1045916d..4c68af61 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v201908/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201811') + 'LiveStreamEventService', version='v201908') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201908/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v201908/live_stream_event_service/get_all_live_stream_events.py index 553d38d2..0591ef13 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201908/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201811') + 'LiveStreamEventService', version='v201908') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201908/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v201908/live_stream_event_service/register_sessions_for_monitoring.py index a12ce208..030d141c 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201908/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201811') + 'LiveStreamEventService', version='v201908') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201908/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v201908/live_stream_event_service/update_live_stream_events.py index 7722ee67..d81b50fe 100755 --- a/examples/ad_manager/v201811/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201908/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201811') + 'LiveStreamEventService', version='v201908') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201811/native_style_service/__init__.py b/examples/ad_manager/v201908/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/native_style_service/__init__.py rename to examples/ad_manager/v201908/native_style_service/__init__.py diff --git a/examples/ad_manager/v201811/native_style_service/create_native_styles.py b/examples/ad_manager/v201908/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v201811/native_style_service/create_native_styles.py rename to examples/ad_manager/v201908/native_style_service/create_native_styles.py index 7a3407e3..64d8096f 100755 --- a/examples/ad_manager/v201811/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201908/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201811') + version='v201908') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v201811/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201908/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v201811/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v201908/native_style_service/get_all_native_styles.py index a037c34f..f5050723 100755 --- a/examples/ad_manager/v201811/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201908/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201811') + version='v201908') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201811/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201908/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v201908/network_service/__init__.py diff --git a/examples/ad_manager/v201811/network_service/get_all_networks.py b/examples/ad_manager/v201908/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v201811/network_service/get_all_networks.py rename to examples/ad_manager/v201908/network_service/get_all_networks.py index f431845e..2cbc9724 100755 --- a/examples/ad_manager/v201811/network_service/get_all_networks.py +++ b/examples/ad_manager/v201908/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201811') + network_service = client.GetService('NetworkService', version='v201908') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v201811/network_service/get_current_network.py b/examples/ad_manager/v201908/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v201811/network_service/get_current_network.py rename to examples/ad_manager/v201908/network_service/get_current_network.py index 1bc7e9f0..fd385837 100755 --- a/examples/ad_manager/v201811/network_service/get_current_network.py +++ b/examples/ad_manager/v201908/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201811') + network_service = client.GetService('NetworkService', version='v201908') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201811/network_service/make_test_network.py b/examples/ad_manager/v201908/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v201811/network_service/make_test_network.py rename to examples/ad_manager/v201908/network_service/make_test_network.py index 30398331..c631fb1e 100755 --- a/examples/ad_manager/v201811/network_service/make_test_network.py +++ b/examples/ad_manager/v201908/network_service/make_test_network.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201811') + network_service = client.GetService('NetworkService', version='v201908') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v201811/line_item_service/__init__.py b/examples/ad_manager/v201908/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/line_item_service/__init__.py rename to examples/ad_manager/v201908/order_service/__init__.py diff --git a/examples/ad_manager/v201811/order_service/approve_orders.py b/examples/ad_manager/v201908/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v201811/order_service/approve_orders.py rename to examples/ad_manager/v201908/order_service/approve_orders.py index 564c08ed..5d2e9c46 100755 --- a/examples/ad_manager/v201811/order_service/approve_orders.py +++ b/examples/ad_manager/v201908/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201811') + order_service = client.GetService('OrderService', version='v201908') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201811/order_service/create_orders.py b/examples/ad_manager/v201908/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v201811/order_service/create_orders.py rename to examples/ad_manager/v201908/order_service/create_orders.py index f0eb3ee0..6ca3fe39 100755 --- a/examples/ad_manager/v201811/order_service/create_orders.py +++ b/examples/ad_manager/v201908/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201811') + order_service = client.GetService('OrderService', version='v201908') # Create order objects. orders = [] diff --git a/examples/ad_manager/v201811/order_service/get_all_orders.py b/examples/ad_manager/v201908/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v201811/order_service/get_all_orders.py rename to examples/ad_manager/v201908/order_service/get_all_orders.py index b250b17c..f1a82dcd 100755 --- a/examples/ad_manager/v201811/order_service/get_all_orders.py +++ b/examples/ad_manager/v201908/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201811') + order_service = client.GetService('OrderService', version='v201908') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201811/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201908/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v201811/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v201908/order_service/get_orders_starting_soon.py index d6915cb0..8a204a57 100755 --- a/examples/ad_manager/v201811/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201908/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201811') + order_service = client.GetService('OrderService', version='v201908') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201811/order_service/update_orders.py b/examples/ad_manager/v201908/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v201811/order_service/update_orders.py rename to examples/ad_manager/v201908/order_service/update_orders.py index 51fd8548..94c109ea 100755 --- a/examples/ad_manager/v201811/order_service/update_orders.py +++ b/examples/ad_manager/v201908/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201811') + order_service = client.GetService('OrderService', version='v201908') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201811/placement_service/create_placements.py b/examples/ad_manager/v201908/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v201811/placement_service/create_placements.py rename to examples/ad_manager/v201908/placement_service/create_placements.py index e0d6ad17..8267f71e 100755 --- a/examples/ad_manager/v201811/placement_service/create_placements.py +++ b/examples/ad_manager/v201908/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201811') - inventory_service = client.GetService('InventoryService', version='v201811') + placement_service = client.GetService('PlacementService', version='v201908') + inventory_service = client.GetService('InventoryService', version='v201908') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201811/placement_service/deactivate_placements.py b/examples/ad_manager/v201908/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v201811/placement_service/deactivate_placements.py rename to examples/ad_manager/v201908/placement_service/deactivate_placements.py index 4204fc4d..27db4a01 100755 --- a/examples/ad_manager/v201811/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201908/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201811') + placement_service = client.GetService('PlacementService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/placement_service/get_active_placements.py b/examples/ad_manager/v201908/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v201811/placement_service/get_active_placements.py rename to examples/ad_manager/v201908/placement_service/get_active_placements.py index a98859b4..63fdf126 100755 --- a/examples/ad_manager/v201811/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201908/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201811') + placement_service = client.GetService('PlacementService', version='v201908') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201811/placement_service/get_all_placements.py b/examples/ad_manager/v201908/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v201811/placement_service/get_all_placements.py rename to examples/ad_manager/v201908/placement_service/get_all_placements.py index 2c902f29..52a422a9 100755 --- a/examples/ad_manager/v201811/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201908/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201811') + placement_service = client.GetService('PlacementService', version='v201908') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201811/placement_service/update_placements.py b/examples/ad_manager/v201908/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v201811/placement_service/update_placements.py rename to examples/ad_manager/v201908/placement_service/update_placements.py index 772220a5..8dc283e2 100755 --- a/examples/ad_manager/v201811/placement_service/update_placements.py +++ b/examples/ad_manager/v201908/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201811') + placement_service = client.GetService('PlacementService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201811/network_service/__init__.py b/examples/ad_manager/v201908/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/network_service/__init__.py rename to examples/ad_manager/v201908/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201908/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v201908/proposal_line_item_service/archive_proposal_line_items.py index 6e802668..9f9c7325 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201908/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201811') + 'ProposalLineItemService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py b/examples/ad_manager/v201908/proposal_line_item_service/create_proposal_line_items.py similarity index 75% rename from examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py rename to examples/ad_manager/v201908/proposal_line_item_service/create_proposal_line_items.py index 91b615ef..cc9ee05c 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/create_programmatic_proposal_line_items_for_non_sales_management.py +++ b/examples/ad_manager/v201908/proposal_line_item_service/create_proposal_line_items.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Creates a programmatic proposal line item for non-sales management. -""" +"""Creates a proposal line item.""" import datetime @@ -28,14 +27,11 @@ # Set proposal that the created proposal line item will belong to. PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' -# Set the ID of the product that the proposal line items should be created from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - -def main(client, proposal_id, product_id): +def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201902') - network_service = client.GetService('NetworkService', version='v201902') + 'ProposalLineItemService', version='v201908') + network_service = client.GetService('NetworkService', version='v201908') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) @@ -53,7 +49,6 @@ def main(client, proposal_id, product_id): # Setting common required fields for proposal line items. 'name': 'Proposal line item #%s' % uuid.uuid4(), - 'productId': product_id, 'proposalId': proposal_id, 'targeting': { 'inventoryTargeting': { @@ -71,17 +66,20 @@ def main(client, proposal_id, product_id): }, 'startDateTime': start_datetime, 'endDateTime': end_datetime, - 'creativePlaceholders': [{ - 'size': { - 'width': '300', - 'height': '250' - } - }, { - 'size': { - 'width': '120', - 'height': '600' + 'creativePlaceholders': [ + { + 'size': { + 'width': '300', + 'height': '250' + } + }, + { + 'size': { + 'width': '120', + 'height': '600' + } } - }], + ], 'goal': { 'units': '1000', 'unitType': 'IMPRESSIONS', @@ -99,15 +97,14 @@ def main(client, proposal_id, product_id): # Display results. for proposal_line_item in proposal_line_items: - print('Programmatic proposal line item for non-sales management with id ' - '"%s", belonging to proposal id "%s", and named "%s" ' - 'was created.' % (proposal_line_item['id'], - proposal_line_item['proposalId'], - proposal_line_item['name'])) + print('Proposal line item with id "%s", belonging to proposal with id "%s",' + ' and named "%s" was created.' % (proposal_line_item['id'], + proposal_line_item['proposalId'], + proposal_line_item['name'])) if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID, PRODUCT_ID) + main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201908/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v201908/proposal_line_item_service/get_all_proposal_line_items.py index 53f983bc..8effa384 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201908/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201811') + 'ProposalLineItemService', version='v201908') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201908/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v201908/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 118e8ab1..c35c00c4 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201908/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201811') + 'ProposalLineItemService', version='v201908') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201908/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v201908/proposal_line_item_service/update_proposal_line_items.py index 5206930d..901bda63 100755 --- a/examples/ad_manager/v201811/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201908/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201811') + 'ProposalLineItemService', version='v201908') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/order_service/__init__.py b/examples/ad_manager/v201908/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/order_service/__init__.py rename to examples/ad_manager/v201908/proposal_service/__init__.py diff --git a/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals_for_non_sales_management.py b/examples/ad_manager/v201908/proposal_service/create_proposals.py similarity index 91% rename from examples/ad_manager/v201811/proposal_service/create_programmatic_proposals_for_non_sales_management.py rename to examples/ad_manager/v201908/proposal_service/create_proposals.py index 05e1a521..4d3007b3 100755 --- a/examples/ad_manager/v201811/proposal_service/create_programmatic_proposals_for_non_sales_management.py +++ b/examples/ad_manager/v201908/proposal_service/create_proposals.py @@ -14,8 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Creates a programmatic proposal for networks not using sales management. -""" +"""This example creates a proposal.""" import uuid @@ -29,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201811') + proposal_service = client.GetService('ProposalService', version='v201908') proposal = { # Setting required Marketplace information. @@ -51,7 +50,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, # Display results. for proposal in proposals: - print('Programmatic proposal with id "%s" and name "%s" was created.' % + print('Proposal with id "%s" and name "%s" was created.' % (proposal['id'], proposal['name'])) diff --git a/examples/ad_manager/v201811/proposal_service/get_all_proposals.py b/examples/ad_manager/v201908/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v201811/proposal_service/get_all_proposals.py rename to examples/ad_manager/v201908/proposal_service/get_all_proposals.py index aa4c1bd3..06468378 100755 --- a/examples/ad_manager/v201811/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201908/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201811') + proposal_service = client.GetService('ProposalService', version='v201908') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201908/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v201908/proposal_service/get_marketplace_comments.py index 76049d1c..f7a0868a 100755 --- a/examples/ad_manager/v201811/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201908/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201811') + 'ProposalService', version='v201908') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py b/examples/ad_manager/v201908/proposal_service/get_proposals_awaiting_seller_review.py similarity index 85% rename from examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py rename to examples/ad_manager/v201908/proposal_service/get_proposals_awaiting_seller_review.py index 9577e54c..14a3c141 100755 --- a/examples/ad_manager/v201811/proposal_service/get_proposals_pending_approval.py +++ b/examples/ad_manager/v201908/proposal_service/get_proposals_awaiting_seller_review.py @@ -13,8 +13,7 @@ # 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 proposals pending approval. -""" +"""This example gets all proposals awaiting seller review.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -22,11 +21,11 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201811') + proposal_service = client.GetService('ProposalService', version='v201908') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v201811') - .Where('status = :status') - .WithBindVariable('status', 'PENDING_APPROVAL')) + statement = (ad_manager.StatementBuilder(version='v201908') + .Where('negotiationStatus = :negotiationStatus') + .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201908/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v201908/proposal_service/request_buyers_acceptance.py index b318ef75..41aa7746 100755 --- a/examples/ad_manager/v201811/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201908/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201811') + proposal_service = client.GetService('ProposalService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201811/proposal_service/update_proposals.py b/examples/ad_manager/v201908/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v201811/proposal_service/update_proposals.py rename to examples/ad_manager/v201908/proposal_service/update_proposals.py index 11fe2cf0..95849d5f 100755 --- a/examples/ad_manager/v201811/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201908/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201811') + proposal_service = client.GetService('ProposalService', version='v201908') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/premium_rate_service/__init__.py b/examples/ad_manager/v201908/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/premium_rate_service/__init__.py rename to examples/ad_manager/v201908/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201908/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v201908/publisher_query_language_service/fetch_match_tables.py index 1267cd20..34e54c73 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201908/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201908/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v201908/publisher_query_language_service/get_all_browsers.py index af6258a5..c31237b1 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201908/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201908/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v201908/publisher_query_language_service/get_all_programmatic_buyers.py index 64ec2d12..a7267574 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201908/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201811') + data_downloader = client.GetDataDownloader(version='v201908') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201908/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v201908/publisher_query_language_service/get_geo_targets.py index 28395d20..561abcbf 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201908/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201908/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v201908/publisher_query_language_service/get_line_items_named_like.py index 77001901..8a10c24c 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201908/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201908/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v201908/publisher_query_language_service/get_recent_changes.py index 7aeab7e9..0bd025c1 100755 --- a/examples/ad_manager/v201811/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201908/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201811') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201908') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v201811/product_service/__init__.py b/examples/ad_manager/v201908/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/product_service/__init__.py rename to examples/ad_manager/v201908/report_service/__init__.py diff --git a/examples/ad_manager/v201811/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201908/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v201811/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v201908/report_service/run_ad_exchange_report.py index aa1873c6..4f431eea 100755 --- a/examples/ad_manager/v201811/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201908/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') # Create report job. report_job = { diff --git a/examples/ad_manager/v201811/report_service/run_delivery_report.py b/examples/ad_manager/v201908/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v201811/report_service/run_delivery_report.py rename to examples/ad_manager/v201908/report_service/run_delivery_report.py index 8e5d648a..2cec8565 100755 --- a/examples/ad_manager/v201811/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201908/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201811/report_service/run_inventory_report.py b/examples/ad_manager/v201908/report_service/run_inventory_report.py similarity index 86% rename from examples/ad_manager/v201811/report_service/run_inventory_report.py rename to examples/ad_manager/v201908/report_service/run_inventory_report.py index 1cd8a119..caa5bb77 100755 --- a/examples/ad_manager/v201811/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201908/report_service/run_inventory_report.py @@ -25,16 +25,16 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201811') + network_service = client.GetService('NetworkService', version='v201908') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') .WithBindVariable('parentAdUnitId', int(root_ad_unit_id)) .Limit(None) # No limit or offset for reports @@ -46,10 +46,10 @@ def main(client): 'dimensions': ['DATE', 'AD_UNIT_NAME'], 'adUnitView': 'HIERARCHICAL', 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS', - 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS', - 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', - 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], + 'ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS', + 'ADSENSE_LINE_ITEM_LEVEL_CLICKS', + 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', + 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', 'statement': statement.ToStatement() } diff --git a/examples/ad_manager/v201811/report_service/run_reach_report.py b/examples/ad_manager/v201908/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v201811/report_service/run_reach_report.py rename to examples/ad_manager/v201908/report_service/run_reach_report.py index 27a5aa16..9cc56de4 100755 --- a/examples/ad_manager/v201811/report_service/run_reach_report.py +++ b/examples/ad_manager/v201908/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') # Create report job. report_job = { diff --git a/examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201908/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v201908/report_service/run_report_and_create_match_table.py index 26008980..23c5ed47 100755 --- a/examples/ad_manager/v201811/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201908/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201908/report_service/run_report_with_custom_fields.py similarity index 95% rename from examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v201908/report_service/run_report_with_custom_fields.py index d2358865..0af5875d 100755 --- a/examples/ad_manager/v201811/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201908/report_service/run_report_with_custom_fields.py @@ -28,12 +28,12 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201811') + line_item_service = client.GetService('LineItemService', version='v201908') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('orderId = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201811/report_service/run_sales_report.py b/examples/ad_manager/v201908/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v201811/report_service/run_sales_report.py rename to examples/ad_manager/v201908/report_service/run_sales_report.py index cce63190..cc075ba9 100755 --- a/examples/ad_manager/v201811/report_service/run_sales_report.py +++ b/examples/ad_manager/v201908/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') # Create report job. report_job = { diff --git a/examples/ad_manager/v201811/report_service/run_saved_query.py b/examples/ad_manager/v201908/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v201811/report_service/run_saved_query.py rename to examples/ad_manager/v201908/report_service/run_saved_query.py index cf28e175..92fd3bae 100755 --- a/examples/ad_manager/v201811/report_service/run_saved_query.py +++ b/examples/ad_manager/v201908/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201811') + report_service = client.GetService('ReportService', version='v201908') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201811') + report_downloader = client.GetDataDownloader(version='v201908') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v201811/product_template_service/__init__.py b/examples/ad_manager/v201908/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/product_template_service/__init__.py rename to examples/ad_manager/v201908/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201908/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v201908/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 866fc7e8..2893eb1d 100755 --- a/examples/ad_manager/v201811/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201908/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201811') + 'SuggestedAdUnitService', version='v201908') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201908/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v201908/suggested_ad_unit_service/get_all_suggested_ad_units.py index 9f5b82cd..fc87af6a 100755 --- a/examples/ad_manager/v201811/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201908/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201811') + 'SuggestedAdUnitService', version='v201908') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201908/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v201908/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 04d0b40f..f5d97d89 100755 --- a/examples/ad_manager/v201811/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201908/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201811') + 'SuggestedAdUnitService', version='v201908') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v201811/rate_card_service/__init__.py b/examples/ad_manager/v201908/targeting_preset_service/__init__.py similarity index 91% rename from examples/ad_manager/v201811/rate_card_service/__init__.py rename to examples/ad_manager/v201908/targeting_preset_service/__init__.py index 3746cd33..6d126cce 100755 --- a/examples/ad_manager/v201811/rate_card_service/__init__.py +++ b/examples/ad_manager/v201908/targeting_preset_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2019 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. diff --git a/examples/ad_manager/v201811/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py similarity index 59% rename from examples/ad_manager/v201811/product_template_service/get_all_product_templates.py rename to examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py index b7b42abe..62379383 100755 --- a/examples/ad_manager/v201811/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2016 Google Inc. All Rights Reserved. +# Copyright 2019 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. @@ -13,7 +13,7 @@ # 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 product templates. +"""This example gets all targeting presets. """ # Import appropriate modules from the client library. @@ -22,22 +22,23 @@ def main(client): # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201811') + targeting_preset_service = client.GetService( + 'TargetingPresetService', version='v201908') - # Create a statement to select product templates. - statement = ad_manager.StatementBuilder(version='v201811') + # Create a statement to select suggested ad units. + statement = ad_manager.StatementBuilder(version='v201908') - # Retrieve a small amount of product templates at a time, paging - # through until all product templates have been retrieved. + # Retrieve a small number of targeting presets at a time, paging + # through until all targeting presets have been retrieved. while True: - response = product_template_service.getProductTemplatesByStatement( + response = targeting_preset_service.getTargetingPresetsByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): - for product_template in response['results']: - # Print out some information for each product template. - print('Product template with ID "%d" and name "%s" was found.\n' % - (product_template['id'], product_template['name'])) + for targeting_preset in response['results']: + # Print out some information for each targeting preset. + print( + 'Targeting preset with ID "%s" and name "%d" was found.\n' + % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v201811/proposal_line_item_service/__init__.py b/examples/ad_manager/v201908/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/proposal_line_item_service/__init__.py rename to examples/ad_manager/v201908/team_service/__init__.py diff --git a/examples/ad_manager/v201811/team_service/create_teams.py b/examples/ad_manager/v201908/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v201811/team_service/create_teams.py rename to examples/ad_manager/v201908/team_service/create_teams.py index c4d94003..dc9922ae 100755 --- a/examples/ad_manager/v201811/team_service/create_teams.py +++ b/examples/ad_manager/v201908/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201811') + team_service = client.GetService('TeamService', version='v201908') # Create team objects. teams = [] diff --git a/examples/ad_manager/v201811/team_service/get_all_teams.py b/examples/ad_manager/v201908/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v201811/team_service/get_all_teams.py rename to examples/ad_manager/v201908/team_service/get_all_teams.py index a22e0f79..f6daffae 100755 --- a/examples/ad_manager/v201811/team_service/get_all_teams.py +++ b/examples/ad_manager/v201908/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201811') + team_service = client.GetService('TeamService', version='v201908') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201811/team_service/update_teams.py b/examples/ad_manager/v201908/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v201811/team_service/update_teams.py rename to examples/ad_manager/v201908/team_service/update_teams.py index b398cef3..fe154a74 100755 --- a/examples/ad_manager/v201811/team_service/update_teams.py +++ b/examples/ad_manager/v201908/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201811') + team_service = client.GetService('TeamService', version='v201908') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v201811/proposal_service/__init__.py b/examples/ad_manager/v201908/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/proposal_service/__init__.py rename to examples/ad_manager/v201908/user_service/__init__.py diff --git a/examples/ad_manager/v201811/user_service/create_users.py b/examples/ad_manager/v201908/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v201811/user_service/create_users.py rename to examples/ad_manager/v201908/user_service/create_users.py index 549c49ae..2060ffe2 100755 --- a/examples/ad_manager/v201811/user_service/create_users.py +++ b/examples/ad_manager/v201908/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201811') + user_service = client.GetService('UserService', version='v201908') # Create user objects. users = [ diff --git a/examples/ad_manager/v201811/user_service/deactivate_users.py b/examples/ad_manager/v201908/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v201811/user_service/deactivate_users.py rename to examples/ad_manager/v201908/user_service/deactivate_users.py index 2876e1d3..212b9019 100755 --- a/examples/ad_manager/v201811/user_service/deactivate_users.py +++ b/examples/ad_manager/v201908/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201811') + user_service = client.GetService('UserService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201811/user_service/get_all_roles.py b/examples/ad_manager/v201908/user_service/get_all_roles.py similarity index 99% rename from examples/ad_manager/v201811/user_service/get_all_roles.py rename to examples/ad_manager/v201908/user_service/get_all_roles.py index 38cfc420..01d181dc 100755 --- a/examples/ad_manager/v201811/user_service/get_all_roles.py +++ b/examples/ad_manager/v201908/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v201908') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v201811/user_service/get_all_users.py b/examples/ad_manager/v201908/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v201811/user_service/get_all_users.py rename to examples/ad_manager/v201908/user_service/get_all_users.py index 367eaf38..9484bb16 100755 --- a/examples/ad_manager/v201811/user_service/get_all_users.py +++ b/examples/ad_manager/v201908/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201811') + user_service = client.GetService('UserService', version='v201908') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201811/user_service/get_current_user.py b/examples/ad_manager/v201908/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v201811/user_service/get_current_user.py rename to examples/ad_manager/v201908/user_service/get_current_user.py index fa8163c4..c66e04a5 100755 --- a/examples/ad_manager/v201811/user_service/get_current_user.py +++ b/examples/ad_manager/v201908/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201811') + user_service = client.GetService('UserService', version='v201908') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v201811/user_service/get_user_by_email_address.py b/examples/ad_manager/v201908/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v201811/user_service/get_user_by_email_address.py rename to examples/ad_manager/v201908/user_service/get_user_by_email_address.py index f5fba570..b75c5226 100755 --- a/examples/ad_manager/v201811/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201908/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201811') + user_service = client.GetService('UserService', version='v201908') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201811/user_service/update_users.py b/examples/ad_manager/v201908/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v201811/user_service/update_users.py rename to examples/ad_manager/v201908/user_service/update_users.py index 04a8fe1a..d282fdfb 100755 --- a/examples/ad_manager/v201811/user_service/update_users.py +++ b/examples/ad_manager/v201908/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201811') + user_service = client.GetService('UserService', version='v201908') # Create query. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201811/publisher_query_language_service/__init__.py b/examples/ad_manager/v201908/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201811/publisher_query_language_service/__init__.py rename to examples/ad_manager/v201908/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201908/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v201908/user_team_association_service/create_user_team_associations.py index d4afaf0c..775c3237 100755 --- a/examples/ad_manager/v201811/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201908/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201811') + 'UserTeamAssociationService', version='v201908') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201908/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v201908/user_team_association_service/delete_user_team_associations.py index 26f8c6fe..64836e4f 100755 --- a/examples/ad_manager/v201811/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201908/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201811') + 'UserTeamAssociationService', version='v201908') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201908/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v201908/user_team_association_service/get_all_user_team_associations.py index eb050f93..eb948d76 100755 --- a/examples/ad_manager/v201811/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201908/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201811') + 'UserTeamAssociationService', version='v201908') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v201811') + statement = ad_manager.StatementBuilder(version='v201908') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201908/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v201908/user_team_association_service/get_user_team_associations_for_user.py index 9f251771..7d982ba5 100755 --- a/examples/ad_manager/v201811/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201908/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201811') + 'UserTeamAssociationService', version='v201908') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201908/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v201908/user_team_association_service/update_user_team_associations.py index d9ff8bd2..accebf0c 100755 --- a/examples/ad_manager/v201811/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201908/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201811') + 'UserTeamAssociationService', version='v201908') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201811') + statement = (ad_manager.StatementBuilder(version='v201908') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/adwords/v201809/account_management/get_account_changes.py b/examples/adwords/v201809/account_management/get_account_changes.py index 65430f46..9bbed1c7 100755 --- a/examples/adwords/v201809/account_management/get_account_changes.py +++ b/examples/adwords/v201809/account_management/get_account_changes.py @@ -40,7 +40,7 @@ def main(client): } campaigns = campaign_service.get(selector) campaign_ids = [] - if 'entries' in campaigns: + if 'totalNumEntries' in campaigns and campaigns['totalNumEntries'] > 0: for campaign in campaigns['entries']: campaign_ids.append(campaign['id']) else: diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 56666d53..25b8c7cc 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,29 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201808': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CdnConfigurationService', 'CompanyService', 'ContactService', - 'ContentBundleService', 'ContentMetadataKeyHierarchyService', - 'ContentService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'ExchangeRateService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardService', - 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'UserService', - 'UserTeamAssociationService', 'WorkflowRequestService'), 'v201811': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', @@ -135,6 +112,22 @@ 'ReconciliationReportService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), + 'v201908': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', + 'ContactService', 'ContentBundleService', 'ContentService', + 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', + 'CreativeWrapperService', 'CustomFieldService', + 'CustomTargetingService', 'DaiAuthenticationKeyService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PlacementService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService'), } @@ -433,9 +426,7 @@ def AdManagerDateTimePacker(cls, value, version): 'hour': value.hour, 'minute': value.minute, 'second': value.second, - # As of V201811, timeZoneID was renamed timeZoneId - 'timeZoneId' if version >= 'v201811' else 'timeZoneID': - value.tzinfo.zone, + 'timeZoneId': value.tzinfo.zone, } elif isinstance(value, datetime.date): return {'year': value.year, 'month': value.month, 'day': value.day} @@ -690,8 +681,7 @@ def GetValueRepresentation(cls, value, 'hour': value.hour, 'minute': value.minute, 'second': value.second, - 'timeZoneId' if version >= 'v201811' else 'timeZoneID': - value.tzinfo.zone, + 'timeZoneId': value.tzinfo.zone, } } elif isinstance(value, datetime.date): @@ -1011,13 +1001,8 @@ def _ConvertDateTimeToOffset(self, date_time_value): int(date_time_value['hour']), int(date_time_value['minute']), int(date_time_value['second'])) - # v201808 is the last Ad Manager version to use timeZoneID. - if self._version > 'v201808': - time_zone_str = 'timeZoneId' - else: - time_zone_str = 'timeZoneID' date_time_str = pytz.timezone( - date_time_value[time_zone_str]).localize(date_time_obj).isoformat() + date_time_value['timeZoneId']).localize(date_time_obj).isoformat() if date_time_str[-5:] == '00:00': return date_time_str[:-6] + 'Z' diff --git a/googleads/common.py b/googleads/common.py index 78c66c56..7cff7ac0 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '20.0.0' +VERSION = '21.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/ad_manager_test.py b/tests/ad_manager_test.py index b795c6b3..bb137e0b 100644 --- a/tests/ad_manager_test.py +++ b/tests/ad_manager_test.py @@ -386,15 +386,7 @@ def testPackDate(self): result = self.packer.Pack(input_date, CURRENT_VERSION) self.assertEqual(result, {'year': 2017, 'month': 1, 'day': 2}) - def testPackDateTimePreV201811(self): - input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) - input_date = pytz.timezone('America/New_York').localize(input_date) - result = self.packer.Pack(input_date, 'v201808') - self.assertEqual(result, {'date': {'year': 2017, 'month': 1, 'day': 2}, - 'hour': 3, 'minute': 4, 'second': 5, - 'timeZoneID': 'America/New_York'}) - - def testPackDateTimePostV201811(self): + def testPackDateTime(self): input_date = datetime.datetime(2017, 1, 2, 3, 4, 5) input_date = pytz.timezone('America/New_York').localize(input_date) result = self.packer.Pack(input_date, CURRENT_VERSION) @@ -425,14 +417,10 @@ def setUp(self): oauth2_client, application_name, network_code, self.https_proxy) self.version = sorted(googleads.ad_manager._SERVICE_MAP.keys())[-1] self.report_downloader = self.ad_manager.GetDataDownloader() - self.report_downloader_201808 = self.ad_manager.GetDataDownloader( - version='v201808') self.pql_service = mock.Mock() self.report_service = mock.Mock() self.report_downloader._pql_service = self.pql_service self.report_downloader._report_service = self.report_service - self.report_downloader_201808._pql_service = self.pql_service - self.report_downloader_201808._report_service = self.report_service self.generic_header = [{'labelName': 'Some random header...'}, {'labelName': 'Another header...'}] @@ -468,20 +456,6 @@ def setUp(self): 'xsi_type': 'DateTimeValue' } - row1_field4_201808 = { - 'value': { - 'date': { - 'year': '2012', - 'month': '11', - 'day': '05' - }, - 'hour': '12', - 'minute': '12', - 'second': '12', - 'timeZoneID': 'PST8PDT'}, - 'xsi_type': 'DateTimeValue' - } - row1_field5 = { 'value': None, 'xsi_type': 'NumberValue' @@ -534,21 +508,6 @@ def setUp(self): 'xsi_type': 'DateTimeValue' } - row2_field4_201808 = { - 'value': { - 'date': { - 'year': '2013', - 'month': '01', - 'day': '03' - }, - 'hour': '02', - 'minute': '02', - 'second': '02', - 'timeZoneID': 'GMT' - }, - 'xsi_type': 'DateTimeValue' - } - row2_field5 = { 'value': '123456', 'xsi_type': 'NumberValue' @@ -570,23 +529,12 @@ def setUp(self): row2 = [row2_field1, row2_field2, row2_field3, row2_field4, row2_field5, row2_field6] - row1_201808 = [row1_field1, row1_field2, row1_field3, row1_field4_201808, - row1_field5, row1_field6] - row2_201808 = [row2_field1, row2_field2, row2_field3, row2_field4_201808, - row2_field5, row2_field6] - self.generic_rval = [{ 'values': [DecideValue(value) for value in row1] }, { 'values': [DecideValue(value) for value in row2] }] - self.generic_rval_201808 = [{ - 'values': [DecideValue(value) for value in row1_201808] - }, { - 'values': [DecideValue(value) for value in row2_201808] - }] - def testDownloadPqlResultSetToCsv(self): csv_file = io.StringIO() @@ -639,25 +587,6 @@ def testDownloadPqlResultToList(self): self.generic_header[1]['labelName']], row1, row2], result_set) - def testDownloadPqlResultToList_201808(self): - self.pql_service.select.return_value = {'rows': self.generic_rval_201808, - 'columnTypes': self.generic_header} - - result_set = self.report_downloader_201808.DownloadPqlResultToList( - 'SELECT Id, Name FROM Line_Item') - - row1 = [self.report_downloader_201808._ConvertValueForCsv(field) - for field in self.generic_rval_201808[0]['values']] - row2 = [self.report_downloader_201808._ConvertValueForCsv(field) - for field in self.generic_rval_201808[1]['values']] - - self.pql_service.select.assert_called_once_with( - {'values': None, - 'query': ('SELECT Id, Name FROM Line_Item LIMIT 500 OFFSET 0')}) - self.assertEqual([[self.generic_header[0]['labelName'], - self.generic_header[1]['labelName']], - row1, row2], result_set) - def testDownloadPqlResultToListWithOldValuesList(self): self.pql_service.select.return_value = {'rows': self.generic_rval, 'columnTypes': self.generic_header} @@ -999,94 +928,6 @@ def testWhereWithOtherTypes(self): target_values ) - def testWhereWithOtherTypes_201808(self): - test_statement = googleads.ad_manager.StatementBuilder(version='v201808') - test_statement.Where(( - 'bool_key = :test_bool_key ' - 'AND number_key = :test_number_key ' - 'AND date_key = :test_date_key ' - 'AND datetime_key = :test_datetime_key ' - 'AND set_key = :test_set_key' - )) - - test_statement.WithBindVariable('test_bool_key', True) - test_statement.WithBindVariable('test_number_key', 5) - test_statement.WithBindVariable('test_date_key', datetime.date(2017, 1, 2)) - test_dt = datetime.datetime(2017, 1, 2, - hour=3, minute=4, second=5, - ) - test_dt = pytz.timezone('America/New_York').localize(test_dt) - test_statement.WithBindVariable('test_datetime_key', test_dt) - test_statement.WithBindVariable('test_set_key', [1, 2]) - - target_values = [{ - 'key': 'test_bool_key', - 'value': { - 'xsi_type': 'BooleanValue', - 'value': True, - } - }, { - 'key': 'test_number_key', - 'value': { - 'xsi_type': 'NumberValue', - 'value': 5, - } - }, { - 'key': 'test_date_key', - 'value': { - 'xsi_type': 'DateValue', - 'value': { - 'year': 2017, - 'month': 1, - 'day': 2, - }, - } - }, { - 'key': 'test_datetime_key', - 'value': { - 'xsi_type': 'DateTimeValue', - 'value': { - 'date': { - 'year': 2017, - 'month': 1, - 'day': 2, - }, - 'hour': 3, - 'minute': 4, - 'second': 5, - 'timeZoneID': 'America/New_York' - }, - } - }, { - 'key': 'test_set_key', - 'value': { - 'xsi_type': 'SetValue', - 'values': [ - {'xsi_type': 'NumberValue', 'value': 1}, - {'xsi_type': 'NumberValue', 'value': 2}, - ], - } - }] - target_values.sort(key=lambda v: v['key']) - - statement_result = test_statement.ToStatement() - self.assertEqual(statement_result['query'], - ('WHERE bool_key = :test_bool_key ' - 'AND number_key = :test_number_key ' - 'AND date_key = :test_date_key ' - 'AND datetime_key = :test_datetime_key ' - 'AND set_key = :test_set_key ' - 'LIMIT %s ' - 'OFFSET 0' % googleads.ad_manager.SUGGESTED_PAGE_LIMIT - )) - - # The output order doesn't matter, and it's stored internally as a dict - # until rendered, which is fine, but we need to lock it down for this test. - self.assertEqual( - sorted(statement_result['values'], key=lambda v: v['key']), - target_values - ) - def testBreakWithSetOfMultipleTypes(self): test_statement = googleads.ad_manager.StatementBuilder() test_statement.Where('key = :test_key') diff --git a/tests/common_test.py b/tests/common_test.py index 0b3cf350..86079a22 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v201902' +CURRENT_VERSION = 'v201908' class CommonTest(testing.CleanUtilityRegistryTestCase): From 497a2e806f9e038cae4aa485f8521b0ddeaec70e Mon Sep 17 00:00:00 2001 From: Ben Karl Date: Tue, 13 Aug 2019 15:16:20 -0400 Subject: [PATCH 145/180] Commiting latest changes. From d32cd6301b1d64c19711e597dba5a02a77a0334f Mon Sep 17 00:00:00 2001 From: Jonathas Reuel <32553694+jonathasreuel@users.noreply.github.com> Date: Wed, 18 Sep 2019 12:26:09 -0300 Subject: [PATCH 146/180] Undeclared Variable Removal (#431) The variable raw_input have no declaration, this was replaced by input. --- examples/adwords/authentication/generate_refresh_token.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/adwords/authentication/generate_refresh_token.py b/examples/adwords/authentication/generate_refresh_token.py index 1aca6d43..027dc59f 100755 --- a/examples/adwords/authentication/generate_refresh_token.py +++ b/examples/adwords/authentication/generate_refresh_token.py @@ -98,7 +98,7 @@ def main(client_id, client_secret, scopes): print('Log into the Google Account you use to access your AdWords account ' 'and go to the following URL: \n%s\n' % auth_url) print('After approving the token enter the verification code (if specified).') - code = raw_input('Code: ').strip() + code = input('Code: ').strip() try: flow.fetch_token(code=code) From 5612f19327658f0bd72a3e8737369fb321b923bb Mon Sep 17 00:00:00 2001 From: Luis Date: Fri, 20 Sep 2019 15:41:13 -0400 Subject: [PATCH 147/180] raw_input() is now input() as of Python3 (#432) --- examples/ad_manager/authentication/generate_refresh_token.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/ad_manager/authentication/generate_refresh_token.py b/examples/ad_manager/authentication/generate_refresh_token.py index c0034a91..243f2410 100755 --- a/examples/ad_manager/authentication/generate_refresh_token.py +++ b/examples/ad_manager/authentication/generate_refresh_token.py @@ -98,7 +98,7 @@ def main(client_id, client_secret, scopes): print('Log into the Google Account you use to access your Ad Manager account' 'and go to the following URL: \n%s\n' % (auth_url)) print('After approving the token enter the verification code (if specified).') - code = raw_input('Code: ').strip() + code = input('Code: ').strip() try: flow.fetch_token(code=code) From 4f22d79ed35b19fe625995e53de9d4a02c7c3b01 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Tue, 5 Nov 2019 15:30:56 -0500 Subject: [PATCH 148/180] Ad Manager v201911 release. --- ChangeLog | 5 + .../create_product_base_rates.py | 65 ----------- .../create_product_package_item_base_rates.py | 66 ----------- .../create_product_template_base_rates.py | 65 ----------- .../base_rate_service/get_all_base_rates.py | 52 --------- .../get_base_rates_for_rate_card.py | 55 --------- .../base_rate_service/update_base_rates.py | 77 ------------- .../create_exchange_rates.py | 58 ---------- .../get_all_exchange_rates.py | 54 --------- .../get_exchange_rates_for_currency_code.py | 56 --------- .../update_exchange_rates.py | 71 ------------ .../package_service/create_packages.py | 61 ---------- ...reate_proposal_line_items_from_packages.py | 68 ----------- .../package_service/get_all_packages.py | 50 -------- .../get_in_progress_packages.py | 51 -------- .../create_premium_rates.py | 84 -------------- .../get_all_premium_rates.py | 54 --------- .../get_premium_rates_for_rate_card.py | 56 --------- .../update_premium_rates.py | 87 -------------- .../create_product_package_item.py | 62 ---------- .../get_all_product_package_items.py | 53 --------- ...oduct_package_items_for_product_package.py | 56 --------- .../create_product_packages.py | 51 -------- .../get_active_product_packages.py | 52 --------- .../get_all_product_packages.py | 51 -------- .../product_service/get_all_products.py | 49 -------- .../get_products_for_product_template.py | 53 --------- .../product_service/update_products.py | 68 ----------- .../activate_product_templates.py | 74 ------------ .../create_product_templates.py | 109 ------------------ .../create_programmatic_product_templates.py | 91 --------------- .../get_sponsorship_product_templates.py | 52 --------- .../update_product_templates.py | 94 --------------- .../rate_card_service/create_rate_cards.py | 60 ---------- .../rate_card_service/get_all_rate_cards.py | 51 -------- .../get_marketplace_rate_cards.py | 54 --------- ..._item_reports_for_reconciliation_report.py | 75 ------------ ...update_reconciliation_line_item_reports.py | 67 ----------- ...order_reports_for_reconciliation_report.py | 58 ---------- .../submit_reconciliation_order_reports.py | 71 ------------ ...n_report_rows_for_reconciliation_report.py | 64 ---------- .../update_reconciliation_report_rows.py | 75 ------------ .../get_all_reconciliation_reports.py | 56 --------- ...iliation_report_for_last_billing_period.py | 63 ---------- .../v201902/report_service/__init__.py | 15 --- .../suggested_ad_unit_service/__init__.py | 15 --- .../v201902/team_service/__init__.py | 15 --- .../v201902/user_service/__init__.py | 15 --- .../user_team_association_service/__init__.py | 15 --- .../workflow_request_service/__init__.py | 15 --- .../approve_workflow_approval_requests.py | 75 ------------ .../get_workflow_approval_requests.py | 57 --------- ...et_workflow_external_condition_requests.py | 57 --------- ...er_workflow_external_condition_requests.py | 78 ------------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_traffic_adjustments.py | 4 +- .../get_all_traffic_adjustments.py | 4 +- .../update_traffic_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service}/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service}/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service}/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../creative_service}/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service}/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service}/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service}/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service}/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service}/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service}/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service}/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service}/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service}/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service}/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service}/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service}/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 18 +-- .../report_service/run_reach_report.py | 7 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 45 ++------ .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../suggested_ad_unit_service}/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service}/__init__.py | 2 +- .../get_all_targeting_presets.py} | 27 ++--- .../team_service}/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service}/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 38 +++--- googleads/common.py | 2 +- tests/common_test.py | 2 +- 242 files changed, 326 insertions(+), 3464 deletions(-) delete mode 100755 examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py delete mode 100755 examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py delete mode 100755 examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py delete mode 100755 examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py delete mode 100755 examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py delete mode 100755 examples/ad_manager/v201902/base_rate_service/update_base_rates.py delete mode 100755 examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py delete mode 100755 examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py delete mode 100755 examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py delete mode 100755 examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py delete mode 100755 examples/ad_manager/v201902/package_service/create_packages.py delete mode 100755 examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py delete mode 100755 examples/ad_manager/v201902/package_service/get_all_packages.py delete mode 100755 examples/ad_manager/v201902/package_service/get_in_progress_packages.py delete mode 100755 examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py delete mode 100755 examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py delete mode 100755 examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py delete mode 100755 examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py delete mode 100755 examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py delete mode 100755 examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py delete mode 100755 examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py delete mode 100755 examples/ad_manager/v201902/product_package_service/create_product_packages.py delete mode 100755 examples/ad_manager/v201902/product_package_service/get_active_product_packages.py delete mode 100755 examples/ad_manager/v201902/product_package_service/get_all_product_packages.py delete mode 100755 examples/ad_manager/v201902/product_service/get_all_products.py delete mode 100755 examples/ad_manager/v201902/product_service/get_products_for_product_template.py delete mode 100755 examples/ad_manager/v201902/product_service/update_products.py delete mode 100755 examples/ad_manager/v201902/product_template_service/activate_product_templates.py delete mode 100755 examples/ad_manager/v201902/product_template_service/create_product_templates.py delete mode 100755 examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py delete mode 100755 examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py delete mode 100755 examples/ad_manager/v201902/product_template_service/update_product_templates.py delete mode 100755 examples/ad_manager/v201902/rate_card_service/create_rate_cards.py delete mode 100755 examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py delete mode 100755 examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py delete mode 100755 examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py delete mode 100755 examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py delete mode 100755 examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py delete mode 100755 examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py delete mode 100755 examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py delete mode 100755 examples/ad_manager/v201902/report_service/__init__.py delete mode 100755 examples/ad_manager/v201902/suggested_ad_unit_service/__init__.py delete mode 100755 examples/ad_manager/v201902/team_service/__init__.py delete mode 100755 examples/ad_manager/v201902/user_service/__init__.py delete mode 100755 examples/ad_manager/v201902/user_team_association_service/__init__.py delete mode 100755 examples/ad_manager/v201902/workflow_request_service/__init__.py delete mode 100755 examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py delete mode 100755 examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py delete mode 100755 examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py delete mode 100755 examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py rename examples/ad_manager/{v201902 => v201911}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v201902 => v201911}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v201902 => v201911}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v201902 => v201911}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v201902 => v201911}/activity_service/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v201902 => v201911}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v201902 => v201911}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v201902 => v201911}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v201902 => v201911}/adjustment_service/create_traffic_adjustments.py (99%) rename examples/ad_manager/{v201902 => v201911}/adjustment_service/get_all_traffic_adjustments.py (95%) rename examples/ad_manager/{v201902 => v201911}/adjustment_service/update_traffic_adjustments.py (97%) rename examples/ad_manager/{v201902 => v201911}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v201902 => v201911}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v201902 => v201911}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v201902 => v201911}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v201902 => v201911}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v201902 => v201911}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v201902 => v201911}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v201902 => v201911}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v201902 => v201911}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v201902 => v201911}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v201902/base_rate_service => v201911/company_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/company_service/create_companies.py (99%) rename examples/ad_manager/{v201902 => v201911}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v201902 => v201911}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v201902 => v201911}/company_service/update_companies.py (96%) rename examples/ad_manager/{v201902/company_service => v201911/contact_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v201902 => v201911}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v201902 => v201911}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v201902 => v201911}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v201902/contact_service => v201911/content_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/content_service/get_all_content.py (95%) rename examples/ad_manager/{v201902/content_service => v201911/creative_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v201902 => v201911}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v201902 => v201911}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v201902 => v201911}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v201902 => v201911}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v201902 => v201911}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v201902 => v201911}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v201902 => v201911}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v201902/creative_service => v201911/creative_set_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v201902 => v201911}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v201902 => v201911}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v201902 => v201911}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v201902 => v201911}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v201902/creative_set_service => v201911/creative_template_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v201902 => v201911}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v201902 => v201911}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v201902 => v201911}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v201902 => v201911}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v201902 => v201911}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v201902 => v201911}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v201902/creative_template_service => v201911/custom_field_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v201902 => v201911}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v201902 => v201911}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v201902 => v201911}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v201902 => v201911}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v201902 => v201911}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v201902 => v201911}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v201902/custom_field_service => v201911/custom_targeting_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v201902 => v201911}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201902 => v201911}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v201902 => v201911}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201902 => v201911}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201902 => v201911}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201902 => v201911}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v201902 => v201911}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v201902 => v201911}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v201902 => v201911}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v201902/custom_targeting_service => v201911/inventory_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v201902 => v201911}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v201902 => v201911}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v201902 => v201911}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v201902 => v201911}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v201902 => v201911}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v201902 => v201911}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v201902/exchange_rate_service => v201911/label_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/label_service/create_labels.py (99%) rename examples/ad_manager/{v201902 => v201911}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v201902 => v201911}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v201902 => v201911}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v201902 => v201911}/label_service/update_labels.py (96%) rename examples/ad_manager/{v201902/inventory_service => v201911/line_item_creative_association_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v201902 => v201911}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v201902 => v201911}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v201902 => v201911}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v201902 => v201911}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v201902/label_service => v201911/line_item_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v201902 => v201911}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v201902 => v201911}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v201902 => v201911}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v201902 => v201911}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v201902 => v201911}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v201902 => v201911}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v201902 => v201911}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v201902 => v201911}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v201902/line_item_creative_association_service => v201911/network_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v201902 => v201911}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v201902 => v201911}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v201902/line_item_service => v201911/order_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v201902 => v201911}/order_service/create_orders.py (99%) rename examples/ad_manager/{v201902 => v201911}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v201902 => v201911}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v201902 => v201911}/order_service/update_orders.py (97%) rename examples/ad_manager/{v201902 => v201911}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v201902 => v201911}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v201902 => v201911}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v201902 => v201911}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v201902 => v201911}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v201902/network_service => v201911/proposal_line_item_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v201902 => v201911}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v201902 => v201911}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v201902 => v201911}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v201902 => v201911}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v201902/order_service => v201911/proposal_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v201902 => v201911}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v201902 => v201911}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v201902 => v201911}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v201902 => v201911}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v201902 => v201911}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v201902/premium_rate_service => v201911/publisher_query_language_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v201902 => v201911}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v201902 => v201911}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v201902 => v201911}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v201902 => v201911}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v201902 => v201911}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v201902/product_service => v201911/report_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v201902 => v201911}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v201902 => v201911}/report_service/run_inventory_report.py (74%) rename examples/ad_manager/{v201902 => v201911}/report_service/run_reach_report.py (87%) rename examples/ad_manager/{v201902 => v201911}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v201902 => v201911}/report_service/run_report_with_custom_fields.py (55%) rename examples/ad_manager/{v201902 => v201911}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v201902 => v201911}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v201902/product_template_service => v201911/suggested_ad_unit_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v201902 => v201911}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v201902 => v201911}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v201902/rate_card_service => v201911/targeting_preset_service}/__init__.py (91%) rename examples/ad_manager/{v201902/product_template_service/get_all_product_templates.py => v201911/targeting_preset_service/get_all_targeting_presets.py} (59%) rename examples/ad_manager/{v201902/proposal_line_item_service => v201911/team_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/team_service/create_teams.py (99%) rename examples/ad_manager/{v201902 => v201911}/team_service/get_all_teams.py (96%) rename examples/ad_manager/{v201902 => v201911}/team_service/update_teams.py (97%) rename examples/ad_manager/{v201902/proposal_service => v201911/user_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/user_service/create_users.py (99%) rename examples/ad_manager/{v201902 => v201911}/user_service/deactivate_users.py (97%) rename examples/ad_manager/{v201902 => v201911}/user_service/get_all_roles.py (99%) rename examples/ad_manager/{v201902 => v201911}/user_service/get_all_users.py (96%) rename examples/ad_manager/{v201902 => v201911}/user_service/get_current_user.py (99%) rename examples/ad_manager/{v201902 => v201911}/user_service/get_user_by_email_address.py (96%) rename examples/ad_manager/{v201902 => v201911}/user_service/update_users.py (96%) rename examples/ad_manager/{v201902/publisher_query_language_service => v201911/user_team_association_service}/__init__.py (100%) rename examples/ad_manager/{v201902 => v201911}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v201902 => v201911}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v201902 => v201911}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v201902 => v201911}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v201902 => v201911}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index e3e00deb..7494d249 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +22.0.0 -- 11/05/2019 +* Added support for Ad Manager v201911. +* Removed support for Ad Manager v201811. +* Removed examples for Ad Manager v201902. + 21.0.0 -- 08/14/2019 * Added support for Ad Manager v201908 * Removed support for Ad Manager v201808 diff --git a/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py deleted file mode 100755 index c96a7680..00000000 --- a/examples/ad_manager/v201902/base_rate_service/create_product_base_rates.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201902') - - # Create a product base rate. - product_base_rate = { - 'xsi_type': 'ProductBaseRate', - # Set the rate card ID that the product base rate belongs to. - 'rateCardId': rate_card_id, - # Set the product id the base rate will be applied to. - 'productId': product_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create the product base rate on the server. - base_rates = base_rate_service.createBaseRates( - [product_base_rate]) - - if base_rates: - for base_rate in base_rates: - print('A product base rate with ID "%s" and rate \'%.2f\' %s was ' - 'created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py deleted file mode 100755 index 7aeaeec3..00000000 --- a/examples/ad_manager/v201902/base_rate_service/create_product_package_item_base_rates.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package item base rate. - -To determine which base rates exist, run get_all_base_rates.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the rate card ID to add the base rate to. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - -# Set the product package item to apply this base rate to. -PRODUCT_PACKAGE_ITEM_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201902') - - # Create a base rate for a product package item. - product_package_item_base_rate = { - 'xsi_type': 'ProductPackageItemBaseRate', - # Set the rate card ID that the product package item base rate - # belongs to. - 'rateCardId': RATE_CARD_ID, - # Set the product package item the base rate will be applied to. - 'productPackageItemId': PRODUCT_PACKAGE_ITEM_ID, - # Create a rate worth $2 USD and set that on the product package item - # base rate. - 'rate': { - 'xsi_type': 'Money', - 'currencyCode': 'USD', - 'microAmount': 2000000, - } - } - - # Create the product package item base rate on the server. - result = base_rate_service.createBaseRates([product_package_item_base_rate]) - - for new_base_rate in result: - print('A product package item base rate with ID %d and rate %f %s ' - 'was created.' % (new_base_rate['id'], - new_base_rate['microAmount'], - new_base_rate['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py deleted file mode 100755 index bbe9fee2..00000000 --- a/examples/ad_manager/v201902/base_rate_service/create_product_template_base_rates.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product template base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_template_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201902') - - # Create a product template base rate. - product_template_base_rate = { - 'xsi_type': 'ProductTemplateBaseRate', - # Set the rate card ID that the product template base rate belongs to. - 'rateCardId': rate_card_id, - # Set the product template the base rate will be applied to. - 'productTemplateId': product_template_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create the product template item base rate on the server. - base_rates = base_rate_service.createBaseRates( - [product_template_base_rate]) - - if base_rates: - for base_rate in base_rates: - print('A product template base rate with ID "%s" and rate \'%.2f\' %s' - ' was created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py deleted file mode 100755 index 24e0eb23..00000000 --- a/examples/ad_manager/v201902/base_rate_service/get_all_base_rates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 base rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201902') - - # Create a statement to select base rates. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of base rates at a time, paging - # through until all base rates have been retrieved. - while True: - response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for base_rate in response['results']: - # Print out some information for each base rate. - print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % (base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py deleted file mode 100755 index a86bdce0..00000000 --- a/examples/ad_manager/v201902/base_rate_service/get_base_rates_for_rate_card.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 base rates belonging to a rate card. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201902') - # Create a statement to select base rates. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('rateCardId = :rateCardId') - .WithBindVariable('rateCardId', rate_card_id)) - - # Retrieve a small amount of base rates at a time, paging - # through until all base rates have been retrieved. - while True: - response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for base_rate in response['results']: - # Print out some information for each base rate. - print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % - (base_rate['id'], ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201902/base_rate_service/update_base_rates.py b/examples/ad_manager/v201902/base_rate_service/update_base_rates.py deleted file mode 100755 index ad594629..00000000 --- a/examples/ad_manager/v201902/base_rate_service/update_base_rates.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a base rate's value. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' - - -def main(client, base_rate_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201902') - - # Create a filter statement for base rates for a single rate card. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', int(base_rate_id))) - - # Get single base rate by statement. - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local base rate object by changing its value to $3 USD. - new_rate = { - 'currencyCode': 'USD', - 'microAmount': 3000000 - } - - updated_base_rates = [] - for base_rate in response['results']: - base_rate['rate'] = new_rate - updated_base_rates.append(base_rate) - - # Update base rates remotely. - base_rates = base_rate_service.updateBaseRates(updated_base_rates) - - # Display results. - if base_rates: - for base_rate in base_rates: - print('Base rate with ID "%s" and type "%s" belonging to ' - 'rate card ID "%s" was updated.' % ( - base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - else: - print('No base rates were updated.') - else: - print('No base rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, BASE_RATE_ID) diff --git a/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py deleted file mode 100755 index b5d94fa3..00000000 --- a/examples/ad_manager/v201902/exchange_rate_service/create_exchange_rates.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates an exchange rate. - -To determine which exchange rates exist, run get_all_exchange_rates.py. - - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201902') - - # Create a new fixed exchange rate with currency code 'AUD', with direction - # FROM_NETWORK with a value of 1.5. - exchange_rate = { - 'currencyCode': 'AUD', - 'direction': 'FROM_NETWORK', - 'exchangeRate': int(15000000000), - 'refreshRate': 'FIXED' - } - - created_exchange_rate = exchange_rate_service.createExchangeRates( - [exchange_rate])[0] - - print('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was created.' % (created_exchange_rate['id'], - created_exchange_rate['currencyCode'], - created_exchange_rate['direction'], - (float(created_exchange_rate['exchangeRate']) / - 10000000000))) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py deleted file mode 100755 index df06ec84..00000000 --- a/examples/ad_manager/v201902/exchange_rate_service/get_all_exchange_rates.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 exchange rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201902') - - # Create a statement to select exchange rates. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of exchange rates at a time, paging - # through until all exchange rates have been retrieved. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for exchange_rate in response['results']: - # Print out some information for each exchange rate. - print( - 'Exchange rate with ID "%d", currency code "%s", direction "%s", ' - 'and exchange rate "%d" was found.\n' % - (exchange_rate['id'], exchange_rate['currencyCode'], - exchange_rate['direction'], exchange_rate['exchangeRate'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py deleted file mode 100755 index f8bc7733..00000000 --- a/examples/ad_manager/v201902/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the exchange rate for a specific currency code. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client, currency_code): - # Initialize appropriate service. - exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201902') - # Create a statement to select exchange rates. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('currencyCode = :currencyCode') - .WithBindVariable('currencyCode', currency_code)) - - # Retrieve a small amount of exchange rates at a time, paging - # through until all exchange rates have been retrieved. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for exchange_rate in response['results']: - # Print out some information for each exchange rate. - print('Exchange rate with ID "%d", currency code "%s", and exchange ' - 'rate "%.2f" was found.\n' % - (exchange_rate['id'], exchange_rate['currencyCode'], - float(exchange_rate['exchangeRate'] / 1000000))) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CURRENCY_CODE) diff --git a/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py deleted file mode 100755 index 623916dc..00000000 --- a/examples/ad_manager/v201902/exchange_rate_service/update_exchange_rates.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates the value of an exchange rate. - -To create exchange rates, run create_exchange_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' - - -def main(client, exchange_rate_id): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201902') - - # Create a statement to get an exchange rate by its ID. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .WithBindVariable('id', int(exchange_rate_id)) - .Limit(1)) - - # Get rate cards by statement. - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - exchange_rate = response['results'][0] - - # Update the exchange rate value to 1.5. - exchange_rate['exchangeRate'] = int(15000000000) - - exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) - - if exchange_rates: - for exchange_rate in exchange_rates: - print('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was updated.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) - else: - print('No exchange rates were updated.') - else: - print('No exchange rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, EXCHANGE_RATE_ID) diff --git a/examples/ad_manager/v201902/package_service/create_packages.py b/examples/ad_manager/v201902/package_service/create_packages.py deleted file mode 100755 index eca0c302..00000000 --- a/examples/ad_manager/v201902/package_service/create_packages.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a package. - -To determine which packages exist, run get_all_packages.py. -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the ID of the product package to create the package from. -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - -# Set the ID of the proposal to create proposal line items under. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the rate card the proposal line items belonging to the product -# package are priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client): - # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201902') - - # Create local package. - package = { - 'name': 'Package #%d' % random.randint(0, 1000000), - 'proposalId': PROPOSAL_ID, - 'productPackageId': PRODUCT_PACKAGE_ID, - 'rateCardId': RATE_CARD_ID, - } - - # Create the package on the server. - result = package_service.createPackages([package]) - - for new_package in result: - print('A package with ID %d and name "%s" was created' % - (new_package['id'], new_package['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py deleted file mode 100755 index dc103934..00000000 --- a/examples/ad_manager/v201902/package_service/create_proposal_line_items_from_packages.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a copy of an image creative. - -To determine which image creatives exist, run get_image_creatives.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the line item to pause. -PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201902') - - # Create a statement to select the single package. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', PACKAGE_ID)) - - # Get the package. - query_result = package_service.getPackagesByStatement(statement.ToStatement()) - - package = query_result['results'][0] - - print('Package with ID %d will create proposal line items using product ' - 'package with ID %d.' % (package['id'], - package['productPackageId'])) - - # Remove limit and offset from statement. - statement.limit = None - statement.offset = None - - # Perform update packages action. - result = package_service.performPackageAction( - {'xsi_type': 'CreateProposalLineItemsFromPackages'}, - statement.ToStatement()) - - if result and result['numChanges'] > 0: - print('Number of packages that proposal line items were created for: %d' % - result['numChanges']) - else: - print('No proposal line items were created.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/package_service/get_all_packages.py b/examples/ad_manager/v201902/package_service/get_all_packages.py deleted file mode 100755 index 0925f67f..00000000 --- a/examples/ad_manager/v201902/package_service/get_all_packages.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201902') - - # Create a statement to select packages. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of packages at a time, paging - # through until all packages have been retrieved. - while True: - response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for pkg in response['results']: - # Print out some information for each package. - print( - 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' - % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/package_service/get_in_progress_packages.py b/examples/ad_manager/v201902/package_service/get_in_progress_packages.py deleted file mode 100755 index 289aefde..00000000 --- a/examples/ad_manager/v201902/package_service/get_in_progress_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 packages in progress. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201902') - # Create a statement to select packages. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('status = :status') - .WithBindVariable('status', 'IN_PROGRESS')) - - # Retrieve a small amount of packages at a time, paging - # through until all packages have been retrieved. - while True: - response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for pkg in response['results']: - # Print out some information for each package. - print( - 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' - % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py deleted file mode 100755 index f9b85b20..00000000 --- a/examples/ad_manager/v201902/premium_rate_service/create_premium_rates.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new premium_rates. - -To determine which premium_rates exist, run get_all_premium_rates.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate services. - premium_rate_service = client.GetService('PremiumRateService', - version='v201902') - - # Create an ad unit premium to apply to the rate card. - ad_unit_premium_feature = { - 'xsi_type': 'AdUnitPremiumFeature' - } - - # Create a CPC based premium rate value with adjustments in milli amounts. - # This will adjust a CPC priced proposal line item that has - # inventory targeting specified by 10% of the cost associated with the rate - # card (this comes from a percentage adjustment). - cpc_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPC', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Create a CPM based premium rate value with adjustments in micro amounts. - # This will adjust a CPM priced proposal line item that has - # inventory targeting specified by 2 units of the currency associated with - # the rate card (this comes from absolute value adjustment). - cpm_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPM', - 'adjustmentSize': 2000000, - 'adjustmentType': 'ABSOLUTE_VALUE' - } - - # Create premium rate. - # Associate premium rate with the rate card and set premium information. - # This premium will apply for proposal line items targeting 'any' ad unit - # for both CPM and CPC rate types. - premium_rate = { - 'rateCardId': rate_card_id, - 'pricingMethod': 'ANY_VALUE', - 'premiumFeature': ad_unit_premium_feature, - 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value] - } - - # Add premium_rates. - premium_rates = premium_rate_service.createPremiumRates([premium_rate]) - - # Display results. - for premium_rate in premium_rates: - print('A premium rate for "%s" was added to the rate card with ID' - ' of "%s".\n' - % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), - premium_rate['id'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py deleted file mode 100755 index b575807d..00000000 --- a/examples/ad_manager/v201902/premium_rate_service/get_all_premium_rates.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 premium rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - premium_rate_service = client.GetService( - 'PremiumRateService', version='v201902') - - # Create a statement to select premium rates. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of premium rates at a time, paging - # through until all premium rates have been retrieved. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for premium_rate in response['results']: - # Print out some information for each premium rate. - print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'id "%d" was found.\n' % ( - premium_rate['id'], - ad_manager.AdManagerClassType(premium_rate), - premium_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py deleted file mode 100755 index 0af039ad..00000000 --- a/examples/ad_manager/v201902/premium_rate_service/get_premium_rates_for_rate_card.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 premium rates on a specific rate card. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - premium_rate_service = client.GetService( - 'PremiumRateService', version='v201902') - # Create a statement to select premium rates. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('rateCardId = :rateCardId') - .WithBindVariable('rateCardId', rate_card_id)) - - # Retrieve a small amount of premium rates at a time, paging - # through until all premium rates have been retrieved. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for premium_rate in response['results']: - # Print out some information for each premium rate. - print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'ID "%d" was found.\n' % (premium_rate['id'], - premium_rate['premium feature'], - premium_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py deleted file mode 100755 index a55cbe68..00000000 --- a/examples/ad_manager/v201902/premium_rate_service/update_premium_rates.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a premium rate to add a flat fee to an existing feature. - -To determine which premium rates exist, run get_all_premium_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' - - -def main(client, premium_rate_id): - # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201902') - - # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', int(premium_rate_id)) - .Limit(1)) - - # Get the premium rate. - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_premium_rates = [] - for premium_rate in response['results']: - # Create a flat fee based premium rate value with a 10% increase. - new_flat_fee_rate = { - 'premiumFeature': premium_rate['premiumFeature'], - 'rateType': 'CPM', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Update the premium rate's premiumRateValues to include a flat fee - # premium rate. - - existing_premium_rate_value = ( - [] if 'premiumRateValues' not in premium_rate else - premium_rate['premiumRateValues']) - existing_premium_rate_value.append(new_flat_fee_rate) - premium_rate['premiumRateValues'] = existing_premium_rate_value - - updated_premium_rates.append(premium_rate) - - # Update products remotely. - premium_rates = premium_rate_service.updatePremiumRates( - updated_premium_rates) - - # Display results. - if premium_rates: - for premium_rate in premium_rates: - print('Premium rate with ID "%s", associated with rate card id' - ' "%s" was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) - else: - print('No premium rates were updated.') - else: - print('No premium rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PREMIUM_RATE_ID) diff --git a/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py deleted file mode 100755 index 7c27e7f6..00000000 --- a/examples/ad_manager/v201902/product_package_item_service/create_product_package_item.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package item. - -To determine which product package items exist, run -get_all_product_package_items.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the product package to add product package items to. -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - -# Set the ID of the product to generate a product package item from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client): - product_package_item_service = client.GetService('ProductPackageItemService', - version='v201902') - - product_package_item = { - # Set the product from which the product package item is created. - 'productId': PRODUCT_ID, - # Set the product package that the product package item belongs to. - 'productPackageId': PRODUCT_PACKAGE_ID, - # Specify if the product package item is required for this - # product package. - 'isMandatory': True - } - - # Create the product package item on the server. - result = product_package_item_service.createProductPackageItems( - [product_package_item]) - - for new_product_package_item in result: - print('A product package with ID %d created from product ID %d ' - 'belonging to product package with ID %d was created.' % - (new_product_package_item['id'], - new_product_package_item['productId'], - new_product_package_item['productPackageId'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py deleted file mode 100755 index 78d2684d..00000000 --- a/examples/ad_manager/v201902/product_package_item_service/get_all_product_package_items.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product package items. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201902') - - # Create a statement to select product package items. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of product package items at a time, paging - # through until all product package items have been retrieved. - while True: - response = product_package_item_service.getProductPackageItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package_item in response['results']: - # Print out some information for each product package item. - print('Product package item with ID "%d", product id "%d", and product ' - 'package id "%d" was found.\n' % - (product_package_item['id'], product_package_item['productId'], - product_package_item['productPackageId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py deleted file mode 100755 index 58142e5a..00000000 --- a/examples/ad_manager/v201902/product_package_item_service/get_product_package_items_for_product_package.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product package items belonging to a product package. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - - -def main(client, product_package_id): - # Initialize appropriate service. - product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201902') - # Create a statement to select product package items. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('productPackageId = :productPackageId') - .WithBindVariable('productPackageId', product_package_id)) - - # Retrieve a small amount of product package items at a time, paging - # through until all product package items have been retrieved. - while True: - response = product_package_item_service.getProductPackageItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package_item in response['results']: - # Print out some information for each product package item. - print('Product package item with ID "%d", product ID "%d", and product ' - 'package ID "%d" was found.\n' % - (product_package_item['id'], product_package_item['productId'], - product_package_item['productPackageId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_PACKAGE_ID) diff --git a/examples/ad_manager/v201902/product_package_service/create_product_packages.py b/examples/ad_manager/v201902/product_package_service/create_product_packages.py deleted file mode 100755 index 360a75cf..00000000 --- a/examples/ad_manager/v201902/product_package_service/create_product_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package. - -To determine which product packages exist, run get_all_product_packages.py -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the ID of the rate card to associate with the product package. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client): - product_package_service = client.GetService('ProductPackageService', - version='v201902') - - # Create a local product package. - product_package = { - 'name': 'Product Package #%d' % random.randint(0, 100000000), - 'rateCardIds': [RATE_CARD_ID] - } - - result = product_package_service.createProductPackages([product_package]) - - for new_product_package in result: - print('A product package with ID %d and name "%s" was created.' % - (new_product_package['id'], new_product_package['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py deleted file mode 100755 index ef45ded7..00000000 --- a/examples/ad_manager/v201902/product_package_service/get_active_product_packages.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active product packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_service = client.GetService( - 'ProductPackageService', version='v201902') - # Create a statement to select product packages. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('status = :status') - .WithBindVariable('status', 'ACTIVE')) - - # Retrieve a small amount of product packages at a time, paging - # through until all product packages have been retrieved. - while True: - response = product_package_service.getProductPackagesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package in response['results']: - # Print out some information for each product package. - print('Product package with ID "%d" and name "%s" was found.\n' % - (product_package['id'], product_package['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py deleted file mode 100755 index 7b7020a0..00000000 --- a/examples/ad_manager/v201902/product_package_service/get_all_product_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_service = client.GetService( - 'ProductPackageService', version='v201902') - - # Create a statement to select product packages. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of product packages at a time, paging - # through until all product packages have been retrieved. - while True: - response = product_package_service.getProductPackagesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package in response['results']: - # Print out some information for each product package. - print('Product package with ID "%d" and name "%s" was found.\n' % - (product_package['id'], product_package['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_service/get_all_products.py b/examples/ad_manager/v201902/product_service/get_all_products.py deleted file mode 100755 index a8d30ed0..00000000 --- a/examples/ad_manager/v201902/product_service/get_all_products.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 products. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201902') - - # Create a statement to select products. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of products at a time, paging - # through until all products have been retrieved. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for product in response['results']: - # Print out some information for each product. - print('Product with ID "%d" and name "%s" was found.\n' % - (product['id'], product['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_service/get_products_for_product_template.py b/examples/ad_manager/v201902/product_service/get_products_for_product_template.py deleted file mode 100755 index f3f9e01f..00000000 --- a/examples/ad_manager/v201902/product_service/get_products_for_product_template.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 products created from a product template. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201902') - - # Create a statement to select products. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('productTemplateId = :productTemplateId') - .WithBindVariable('productTemplateId', product_template_id)) - - # Retrieve a small amount of products at a time, paging - # through until all products have been retrieved. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for product in response['results']: - # Print out some information for each product. - print('Product with ID "%d" and name "%s" was found.\n' % - (product['id'], product['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201902/product_service/update_products.py b/examples/ad_manager/v201902/product_service/update_products.py deleted file mode 100755 index 9a52fb16..00000000 --- a/examples/ad_manager/v201902/product_service/update_products.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a product's notes. - -To determine which products exist, run get_all_products.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201902') - - # Create statement object to select a single product by an ID. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .WithBindVariable('id', int(product_id)) - .Limit(1)) - - # Get products by statement. - response = product_service.getProductsByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local product object by changing its notes. - updated_products = [] - for product in response['results']: - product['notes'] = 'Product needs further review before activation.' - updated_products.append(product) - - # Update products remotely. - products = product_service.updateProducts(updated_products) - - # Display results. - if products: - for product in products: - print('Product with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (product['id'], product['name'], product['notes'])) - else: - print('No products were updated.') - else: - print('No products found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_ID) diff --git a/examples/ad_manager/v201902/product_template_service/activate_product_templates.py b/examples/ad_manager/v201902/product_template_service/activate_product_templates.py deleted file mode 100755 index 4ce4b3e2..00000000 --- a/examples/ad_manager/v201902/product_template_service/activate_product_templates.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example activates a product template. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the id of the product template to activate. -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201902') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .WithBindVariable('id', int(product_template_id)) - .Limit(1)) - - product_templates_activated = 0 - - # Get product_templates by statement. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - print('Product template with id "%s" and name "%s" will be ' - 'activated.' % (product_template['id'], - product_template['name'])) - - # Perform action. - result = product_template_service.performProductTemplateAction( - {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - product_templates_activated += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if product_templates_activated > 0: - print('Number of product templates ' - 'activated: %s' % product_templates_activated) - else: - print('No product templates were activated.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201902/product_template_service/create_product_templates.py b/examples/ad_manager/v201902/product_template_service/create_product_templates.py deleted file mode 100755 index fe97dfb7..00000000 --- a/examples/ad_manager/v201902/product_template_service/create_product_templates.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product template. - -To determine which product templates exist, run get_all_product_templates.py. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201902') - network_service = client.GetService( - 'NetworkService', version='v201902') - - # Create a product template. - product_template = { - 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard proposal line ' - 'items targeting Chrome browsers with product ' - 'segmentation on ad units and geo targeting.'), - 'nameMacro': (' - - ' - ' - '), - 'productType': 'DFP', - 'rateType': 'CPM', - 'roadblockingType': 'ONE_OR_MORE', - 'deliveryRateType': 'AS_FAST_AS_POSSIBLE', - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'lineItemType': 'STANDARD', - 'customizableAttributes': { - 'allowPlacementTargetingCustomization': True, - }, - 'builtInTargeting': { - 'technologyTargeting': { - # Set browser targeting to Chrome. - 'browserTargeting': { - { - 'browsers': [ - { - 'id': '500072' - } - ] - } - } - } - }, - 'productSegmentation': { - 'geoSegment': { - 'targetedLocations': [ - {'id': '2840', - 'displayName': 'US'}, - {'id': '2344', - 'displayName': 'Hong Kong'} - ] - }, - 'adUnitSegments': [{ - 'adUnitId': (network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId']), - 'includeDescendants': 'true' - }] - } - } - - # Create product templates on the server. - product_templates = product_template_service.createProductTemplates( - [product_template]) - - if product_templates: - for product_template in product_templates: - print('A product template with ID "%s" and name "%s" was ' - 'created.' % (product_template['id'], product_template['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py deleted file mode 100755 index db150180..00000000 --- a/examples/ad_manager/v201902/product_template_service/create_programmatic_product_templates.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product template. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - product_template_service = client.GetService( - 'ProductTemplateService', version='v201902') - network_service = client.GetService( - 'NetworkService', version='v201902') - - product_template = { - # Setting required Marketplace information. - 'productTemplateMarketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for product templates. - 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard programmatic' - 'proposal line items targeting all ad units with' - 'product segmentation on geo targeting.'), - 'nameMacro': (' - - ' - ' - '), - 'productType': 'DFP', - 'rateType': 'CPM', - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'lineItemType': 'STANDARD', - 'productSegmentation': { - 'geoSegment': { - 'targetedLocations': [ - {'id': '2840', - 'displayName': 'US'}, - {'id': '2344', - 'displayName': 'Hong Kong'} - ] - }, - 'adUnitSegments': [{ - 'adUnitId': (network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId']), - 'includeDescendants': 'true' - }] - } - } - - product_templates = product_template_service.createProductTemplates( - [product_template]) - - if product_templates: - for product_template in product_templates: - print('A programmatic product template with ID "%s" and name "%s" ' - 'was created.' % (product_template['id'], - product_template['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py deleted file mode 100755 index 8c7e3859..00000000 --- a/examples/ad_manager/v201902/product_template_service/get_sponsorship_product_templates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sponsorship product templates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201902') - # Create a statement to select product templates. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('lineItemType = :lineItemType') - .WithBindVariable('lineItemType', 'SPONSORSHIP')) - - # Retrieve a small amount of product templates at a time, paging - # through until all product templates have been retrieved. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - # Print out some information for each product template. - print('Product template with ID "%d" and name "%s" was found.\n' % - (product_template['id'], product_template['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/product_template_service/update_product_templates.py b/examples/ad_manager/v201902/product_template_service/update_product_templates.py deleted file mode 100755 index fe507bdd..00000000 --- a/examples/ad_manager/v201902/product_template_service/update_product_templates.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a product template's GeoTargeting. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201902') - - # Create a statement to select a single product template by ID. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', int(product_template_id)) - .Limit(1)) - - # Get product templates by statement. - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local product template object by appending a new geo-target. - for product_template in response['results']: - # Create geo-targeting for Canada to append. - location = { - 'id': '2124', - 'displayName': 'Canada' - } - - try: - targeting = product_template['builtInTargeting'] - - if 'geoTargeting' in targeting: - geo_targeting = targeting['geoTargeting'] - - if 'targetedLocations' in geo_targeting: - geo_targeting['targetedLocations'].append(location) - else: - geo_targeting['targetedLocations'] = [location] - else: - targeting['geoTargeting'] = { - 'targetedLocations': [location] - } - except KeyError: - product_template['builtInTargeting'] = { - 'geoTargeting': { - 'targetedLocations': [location] - } - } - - # Update products remotely. - product_templates = product_template_service.updateProductTemplates( - [product_template]) - - # Display results. - if product_templates: - for product_template in product_templates: - print('Product template with id "%s" and name "%s" was ' - 'updated.' % (product_template['id'], product_template['name'])) - else: - print('No product templates were updated.') - else: - print('No product templates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py deleted file mode 100755 index fb6f130c..00000000 --- a/examples/ad_manager/v201902/rate_card_service/create_rate_cards.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a new rate card. - -To determine which rate cards exist, run get_all_rate_cards.py. -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the IDs of the teams this rate card should be visible to. -TEAM_IDS = ['INSERT_TEAM_ID_HERE'] - -# Set the currency code to create the rate card with. -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201902') - - # Create a rate card. - rate_card = { - 'name': 'RateCard #%d' % random.randint(0, 100000000), - 'currencyCode': CURRENCY_CODE, - 'pricingModel': 'NET', - } - - # This field is optional. - rate_card['appliedTeamIds'] = TEAM_IDS - - result = rate_card_service.createRateCards([rate_card]) - - for new_rate_card in result: - print('A rate card with ID %s, name "%s", and currency code "%s" ' - 'was created.' % (new_rate_card['id'], - new_rate_card['name'], - new_rate_card['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py deleted file mode 100755 index dffd4225..00000000 --- a/examples/ad_manager/v201902/rate_card_service/get_all_rate_cards.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 rate cards. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201902') - - # Create a statement to select rate cards. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of rate cards at a time, paging - # through until all rate cards have been retrieved. - while True: - response = rate_card_service.getRateCardsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for rate_card in response['results']: - # Print out some information for each rate card. - print('Rate card with ID "%d", name "%s", and currency code "%s" was ' - 'found.\n' % - (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py deleted file mode 100755 index 05e33199..00000000 --- a/examples/ad_manager/v201902/rate_card_service/get_marketplace_rate_cards.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 rate cards that can be used for Marketplace products. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201902') - # Create a statement to select rate cards. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('forMarketplace = :forMarketplace') - .WithBindVariable('forMarketplace', True)) - - # Retrieve a small amount of rate cards at a time, paging - # through until all rate cards have been retrieved. - while True: - response = rate_card_service.getRateCardsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for rate_card in response['results']: - # Print out some information for each rate card. - print( - 'Rate card with ID "%d", name "%s", and currency code "%s" was ' - 'found.\n' - % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py deleted file mode 100755 index c9929cab..00000000 --- a/examples/ad_manager/v201902/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 line item reports for a given reconciliation report. - -To determine how many reconciliation reports exist, -run get_all_reconciliation_reports.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report to query. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201902')) - - # Create a statement to select reconciliation line item reports. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where(('reconciliationReportId = :reconciliationReportId AND ' - 'lineItemId != :lineItemId')) - .OrderBy('lineItemId', ascending=True) - .WithBindVariable('reconciliationReportId', - RECONCILIATION_REPORT_ID) - .WithBindVariable('lineItemId', 0)) - - # Retrieve a small amount of reconciliation line item reports at a time, - # paging through until all reconciliation line item reports have been - # retrieved. - result_set_size = 0 - should_continue = True - - while should_continue: - page = (reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement( - statement.ToStatement())) - if 'results' in page and len(page['results']): - result_set_size += page['totalResultSetSize'] - # Iterate over individual results in the page. - for line_item_report in page['results']: - print('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source "%s", and reconciled volume %d was ' - 'found.' % (line_item_report['id'], - line_item_report['lineItemId'], - line_item_report['reconciliationSource'], - (line_item_report['reconciledVolume'] - if 'reconciledVolume' in line_item_report else 0))) - # Update statement for next page. - statement.offset += statement.limit - should_continue = statement.offset < result_set_size - - print('Number of results found: %d' % result_set_size) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py deleted file mode 100755 index 91842a41..00000000 --- a/examples/ad_manager/v201902/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 updates a reconciliation line item report. - -To get reconciliation line item reports for a reconciliation report, run -get_reconciliation_line_item_reports_for_reconciliation_report.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation line item report to update. -RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201902')) - - # Create a statement to select a reconciliation line item report. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :lineItemReportId') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('lineItemReportId', - RECONCILIATION_LINE_ITEM_REPORT_ID)) - - # Get reconciliation line item reports by statement. - page = (reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement(statement.ToStatement())) - - line_item_report = page['results'][0] - - # Set and use a manual volume for billing. This example splits the difference - # between Ad Manager and the third party volume. - line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + - line_item_report['thirdPartyVolume']) / 2 - line_item_report['reconciliationSource'] = 'MANUAL' - - result = (reconciliation_line_item_report_service - .updateReconciliationLineItemReports([line_item_report])) - - for updated_report in result: - print('Reconciliation line item report with ID %d for line item ID %d was ' - 'updated, with manual volume %d' % (updated_report['id'], - updated_report['lineItemId'], - updated_report['manualVolume'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py deleted file mode 100755 index ced1d2ac..00000000 --- a/examples/ad_manager/v201902/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. -"""Gets all reconciliation order reports for a given reconciliation report. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201902') - # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('reconciliationReportId = :reconciliationReportId') - .WithBindVariable('reconciliationReportId', - reconciliation_report_id)) - - # Retrieve a small amount of reconciliation order reports at a time, paging - # through until all reconciliation order reports have been retrieved. - while True: - response = ( - reconciliation_order_report_service - .getReconciliationOrderReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_order_report in response['results']: - # Print out some information for each reconciliation order report. - print('Reconciliation order report with ID "%d" and status "%s" was ' - 'found.\n' % (reconciliation_order_report['id'], - reconciliation_order_report['status'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py deleted file mode 100755 index 80152dbe..00000000 --- a/examples/ad_manager/v201902/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 submits a reconciliation order report. - -To get all reconciliation order reports for a reconciliation report, -run get get_reconciliation_order_reports_for_reconciliation_report.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation order report to submit. -RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201902')) - - # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', RECONCILIATION_ORDER_REPORT_ID)) - - # Get reconciliation order reports by statement. - page = (reconciliation_order_report_service - .getReconciliationOrderReportsByStatement(statement.ToStatement())) - - report = page['results'][0] - - print('Reconciliation order report with ID %d will be submitted.' % - report['id']) - - # Remove limit and offset from statement. - statement.limit = None - statement.offset = None - - # Perform action. - result = (reconciliation_order_report_service - .performReconciliationOrderReportAction( - {'xsi_type': 'SubmitReconciliationOrderReports'}, - statement.ToStatement())) - - if result and result['numChanges'] > 0: - print('Number of reconciliation order reports submitted: %d' % - result['numChanges']) - else: - print('No reconciliation order reports were submitted.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py deleted file mode 100755 index f156867e..00000000 --- a/examples/ad_manager/v201902/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets a reconciliation report's rows for line items that Ad Manager served. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report row. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201902') - - # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where(('reconciliationReportId = :reportId ' - 'AND lineItemId != :lineItemId')) - .WithBindVariable('lineItemId', 0) - .WithBindVariable('reportId', int(reconciliation_report_id))) - - # Retrieve a small amount of reconciliation report rows at a time, paging - # through until all reconciliation report rows have been retrieved. - while True: - response = ( - reconciliation_report_row_service - .getReconciliationReportRowsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report_row in response['results']: - # Print out some information for each reconciliation report row. - print('Reconciliation report row with ID "%d", reconciliation source ' - '"%s", and reconciled volume "%d" was found.\n' % - (reconciliation_report_row['id'], - reconciliation_report_row['reconciliationSource'], - reconciliation_report_row['reconciledVolume'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py deleted file mode 100755 index 44252a28..00000000 --- a/examples/ad_manager/v201902/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 updates a reconciliation report row. - -To determine which reconciliation report rows exist, -run get_reconciliation_report_rows_for_reconciliation_report.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report row. -RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' - -# Set the ID of the reconciliation report. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201902')) - - # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where(('id = :reconciliationReportRowId AND ' - 'reconciliationReportId = :reconciliationReportId')) - .OrderBy('id', ascending=True) - .WithBindVariable('reconciliationReportRowId', - RECONCILIATION_REPORT_ROW_ID) - .WithBindVariable('reconciliationReportId', - RECONCILIATION_REPORT_ID)) - - # Get reconciliation report rows by statement. - page = (reconciliation_report_row_service - .getReconciliationReportRowsByStatement(statement.ToStatement())) - - row = page['results'][0] - - # Set a comment on the reconciliation report row. - row['comments'] = ('Third part volume didn\'t match DFP - we agreed to split ' - 'the difference') - - # Set and use a manual volume for billing. - row['manualVolume'] = (row['dfpVolume'] + row['thirdPartyVolume']) / 2 - row['reconciliationSource'] = 'MANUAL' - - updated_rows = (reconciliation_report_row_service - .updateReconciliationReportRows([row])) - - for updated_row in updated_rows: - print('Reconciliation report row for line item ID %d and creative ID %d ' - 'was updated, with manual volume %d' % (updated_row['lineItemId'], - updated_row['creativeId'], - updated_row['manualVolume'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py deleted file mode 100755 index 71d1578d..00000000 --- a/examples/ad_manager/v201902/reconciliation_report_service/get_all_reconciliation_reports.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 reconciliation reports. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201902') - - # Create a statement to select reconciliation reports. - statement = ad_manager.StatementBuilder(version='v201902') - - # Retrieve a small amount of reconciliation reports at a time, paging - # through until all reconciliation reports have been retrieved. - while True: - response = ( - reconciliation_report_service - .getReconciliationReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report in response['results']: - # Print out some information for each reconciliation report. - print( - 'Reconciliation report with ID "%d", month "%d", and year "%d" was' - ' found.\n' % (reconciliation_report['id'], - reconciliation_report['startDate']['month'], - reconciliation_report['startDate']['year'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py deleted file mode 100755 index 33df990a..00000000 --- a/examples/ad_manager/v201902/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the previous billing period's reconciliation report. -""" - -# Import appropriate modules from the client library. -from datetime import date -from datetime import timedelta - -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201902') - - first_of_the_month = date.today().replace(day=1) - last_month = first_of_the_month - timedelta(days=1) - - # Create a statement to select reconciliation reports. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('startDate = :startDate') - .WithBindVariable('startDate', last_month)) - - # Retrieve a small amount of reconciliation reports at a time, paging - # through until all reconciliation reports have been retrieved. - while True: - response = ( - reconciliation_report_service - .getReconciliationReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report in response['results']: - # Print out some information for each reconciliation report. - print( - 'Reconciliation report with ID "%d" and start date "%s" was found.' - '\n' % (reconciliation_report['id'], - last_month.strftime('%Y-%m-01'))) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/report_service/__init__.py b/examples/ad_manager/v201902/report_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201902/report_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201902/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201902/suggested_ad_unit_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201902/suggested_ad_unit_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201902/team_service/__init__.py b/examples/ad_manager/v201902/team_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201902/team_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201902/user_service/__init__.py b/examples/ad_manager/v201902/user_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201902/user_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201902/user_team_association_service/__init__.py b/examples/ad_manager/v201902/user_team_association_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201902/user_team_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201902/workflow_request_service/__init__.py b/examples/ad_manager/v201902/workflow_request_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201902/workflow_request_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py deleted file mode 100755 index 0631cd69..00000000 --- a/examples/ad_manager/v201902/workflow_request_service/approve_workflow_approval_requests.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 approves all workflow approval requests belonging to a proposal. - -To determine which workflow approval requests exist, run -get_all_workflow_approval_requests.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201902') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where(('entityId = :entityId and entityType = :entityType ' - 'and type = :type')) - .WithBindVariable('entityId', proposal_id) - .WithBindVariable('entityType', 'PROPOSAL') - .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) - workflow_approval_requests_approved = 0 - - # Get workflow approval requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for workflow_approval_request in response['results']: - print('Workflow approval request with id "%s" will be' - ' approved.' % workflow_approval_request['id']) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'ApproveWorkflowApprovalRequests', - 'comment': 'This workflow has now been approved for submission.'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_approval_requests_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if workflow_approval_requests_approved > 0: - print('\nNumber of workflow approval requests approved: %s' % - workflow_approval_requests_approved) - else: - print('\nNo workflow approval requests were approved.') - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py deleted file mode 100755 index cdac48ba..00000000 --- a/examples/ad_manager/v201902/workflow_request_service/get_workflow_approval_requests.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 workflow approval requests. - -Workflow approval requests must be approved or rejected for a workflow to -finish. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201902') - # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('type = :type') - .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) - - # Retrieve a small amount of workflow requests at a time, paging - # through until all workflow requests have been retrieved. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for workflow_request in response['results']: - # Print out some information for each workflow request. - print('Workflow request with ID "%d", entity type "%s", and entity ID ' - '"%d" was found.\n' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py deleted file mode 100755 index 73fdb595..00000000 --- a/examples/ad_manager/v201902/workflow_request_service/get_workflow_external_condition_requests.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 workflow external condition requests. - -Workflow external condition requests must be triggered or skipped for a -workflow to finish. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201902') - # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('type = :type') - .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) - - # Retrieve a small amount of workflow requests at a time, paging - # through until all workflow requests have been retrieved. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for workflow_request in response['results']: - # Print out some information for each workflow request. - print('Workflow request with ID "%d", entity type "%s", and entity ID ' - '"%d" was found.\n' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py deleted file mode 100755 index 56fc4ef3..00000000 --- a/examples/ad_manager/v201902/workflow_request_service/trigger_workflow_external_condition_requests.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 triggers all workflow external condition requests for a proposal. - -Workflow external condition requests must be triggered or skipped for a workflow -to finish. To determine which proposals exist, run get_all_proposals.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201902') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where(('entityId = :entityId and entityType = :entityType ' - 'and type = :type')) - .WithBindVariable('entityId', proposal_id) - .WithBindVariable('entityType', 'PROPOSAL') - .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) - workflow_external_condition_requests_triggered = 0 - - # Get workflow external condition requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for workflow_request in response['results']: - print('Workflow external condition request with id "%s" for %s ' - 'with id "%s" will be triggered.' % - (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_external_condition_requests_triggered += int( - result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if workflow_external_condition_requests_triggered > 0: - print('\nNumber of workflow external condition requests triggered: %s' % - workflow_external_condition_requests_triggered) - else: - print('\nNo workflow external condition requests were triggered.') - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201902/activity_group_service/__init__.py b/examples/ad_manager/v201911/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/activity_group_service/__init__.py rename to examples/ad_manager/v201911/activity_group_service/__init__.py diff --git a/examples/ad_manager/v201902/activity_group_service/create_activity_groups.py b/examples/ad_manager/v201911/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v201902/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v201911/activity_group_service/create_activity_groups.py index 242ea9e5..2a5c55ae 100755 --- a/examples/ad_manager/v201902/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v201911/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201902') + version='v201911') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v201911/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v201911/activity_group_service/get_active_activity_groups.py index c438b46d..e6463e3b 100755 --- a/examples/ad_manager/v201902/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v201911/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201902') + 'ActivityGroupService', version='v201911') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v201911/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v201911/activity_group_service/get_all_activity_groups.py index dd6539d3..914989bd 100755 --- a/examples/ad_manager/v201902/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v201911/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201902') + 'ActivityGroupService', version='v201911') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201902/activity_group_service/update_activity_groups.py b/examples/ad_manager/v201911/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v201902/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v201911/activity_group_service/update_activity_groups.py index bc2c6e3b..59f5ae55 100755 --- a/examples/ad_manager/v201902/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v201911/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201902') + version='v201911') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/activity_service/__init__.py b/examples/ad_manager/v201911/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/activity_service/__init__.py rename to examples/ad_manager/v201911/activity_service/__init__.py diff --git a/examples/ad_manager/v201902/activity_service/create_activities.py b/examples/ad_manager/v201911/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v201902/activity_service/create_activities.py rename to examples/ad_manager/v201911/activity_service/create_activities.py index 514a5763..2a3213da 100755 --- a/examples/ad_manager/v201902/activity_service/create_activities.py +++ b/examples/ad_manager/v201911/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201902') + activity_service = client.GetService('ActivityService', version='v201911') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v201902/activity_service/get_active_activities.py b/examples/ad_manager/v201911/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v201902/activity_service/get_active_activities.py rename to examples/ad_manager/v201911/activity_service/get_active_activities.py index 676b02d3..b5653747 100755 --- a/examples/ad_manager/v201902/activity_service/get_active_activities.py +++ b/examples/ad_manager/v201911/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201902') + activity_service = client.GetService('ActivityService', version='v201911') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201902/activity_service/get_all_activities.py b/examples/ad_manager/v201911/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v201902/activity_service/get_all_activities.py rename to examples/ad_manager/v201911/activity_service/get_all_activities.py index d5210098..155735f8 100755 --- a/examples/ad_manager/v201902/activity_service/get_all_activities.py +++ b/examples/ad_manager/v201911/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201902') + activity_service = client.GetService('ActivityService', version='v201911') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201902/activity_service/update_activities.py b/examples/ad_manager/v201911/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v201902/activity_service/update_activities.py rename to examples/ad_manager/v201911/activity_service/update_activities.py index a6087812..ffe8c629 100755 --- a/examples/ad_manager/v201902/activity_service/update_activities.py +++ b/examples/ad_manager/v201911/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201902') + activity_service = client.GetService('ActivityService', version='v201911') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/adjustment_service/create_traffic_adjustments.py b/examples/ad_manager/v201911/adjustment_service/create_traffic_adjustments.py similarity index 99% rename from examples/ad_manager/v201902/adjustment_service/create_traffic_adjustments.py rename to examples/ad_manager/v201911/adjustment_service/create_traffic_adjustments.py index 22a57577..6fcece38 100755 --- a/examples/ad_manager/v201902/adjustment_service/create_traffic_adjustments.py +++ b/examples/ad_manager/v201911/adjustment_service/create_traffic_adjustments.py @@ -27,8 +27,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v201902') - network_service = client.GetService('NetworkService', version='v201902') + adjustment_service = client.GetService('AdjustmentService', version='v201911') + network_service = client.GetService('NetworkService', version='v201911') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201902/adjustment_service/get_all_traffic_adjustments.py b/examples/ad_manager/v201911/adjustment_service/get_all_traffic_adjustments.py similarity index 95% rename from examples/ad_manager/v201902/adjustment_service/get_all_traffic_adjustments.py rename to examples/ad_manager/v201911/adjustment_service/get_all_traffic_adjustments.py index cabc767d..6f9b7fe7 100755 --- a/examples/ad_manager/v201902/adjustment_service/get_all_traffic_adjustments.py +++ b/examples/ad_manager/v201911/adjustment_service/get_all_traffic_adjustments.py @@ -24,10 +24,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v201902') + adjustment_service = client.GetService('AdjustmentService', version='v201911') # Create a statement to get all forecast traffic adjustments. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small number of traffic adjustments at a time, paging # through until all traffic adjustments have been retrieved. diff --git a/examples/ad_manager/v201902/adjustment_service/update_traffic_adjustments.py b/examples/ad_manager/v201911/adjustment_service/update_traffic_adjustments.py similarity index 97% rename from examples/ad_manager/v201902/adjustment_service/update_traffic_adjustments.py rename to examples/ad_manager/v201911/adjustment_service/update_traffic_adjustments.py index 60a54bd2..475a9dd1 100755 --- a/examples/ad_manager/v201902/adjustment_service/update_traffic_adjustments.py +++ b/examples/ad_manager/v201911/adjustment_service/update_traffic_adjustments.py @@ -28,12 +28,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v201902') + adjustment_service = client.GetService('AdjustmentService', version='v201911') # Create a statement to select a single traffic forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v201902').Where('id = :id').WithBindVariable( + version='v201911').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast traffic adjustment. diff --git a/examples/ad_manager/v201902/audience_segment_service/__init__.py b/examples/ad_manager/v201911/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/audience_segment_service/__init__.py rename to examples/ad_manager/v201911/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v201911/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v201911/audience_segment_service/create_audience_segments.py index 3628df37..ade57d67 100755 --- a/examples/ad_manager/v201902/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v201911/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201902') - network_service = client.GetService('NetworkService', version='v201902') + 'AudienceSegmentService', version='v201911') + network_service = client.GetService('NetworkService', version='v201911') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v201911/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v201911/audience_segment_service/get_all_audience_segments.py index e5e09663..999bdd0a 100755 --- a/examples/ad_manager/v201902/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v201911/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201902') + 'AudienceSegmentService', version='v201911') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v201911/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v201911/audience_segment_service/get_first_party_audience_segments.py index 36fad0cb..0da69f84 100755 --- a/examples/ad_manager/v201902/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v201911/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201902') + 'AudienceSegmentService', version='v201911') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v201911/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v201911/audience_segment_service/populate_first_party_audience_segments.py index 9c4da083..573dc49d 100755 --- a/examples/ad_manager/v201902/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v201911/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201902') + 'AudienceSegmentService', version='v201911') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v201911/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v201911/audience_segment_service/update_audience_segments.py index de7b4383..283a6ce9 100755 --- a/examples/ad_manager/v201902/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v201911/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201902') + 'AudienceSegmentService', version='v201911') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201902/cdn_configuration_service/__init__.py b/examples/ad_manager/v201911/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/cdn_configuration_service/__init__.py rename to examples/ad_manager/v201911/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v201902/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v201911/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v201902/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v201911/cdn_configuration_service/create_cdn_configurations.py index 22304b45..48472749 100755 --- a/examples/ad_manager/v201902/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v201911/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201902') + version='v201911') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v201911/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v201911/cdn_configuration_service/get_all_cdn_configurations.py index 2debaeb6..3eabcadd 100755 --- a/examples/ad_manager/v201902/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v201911/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201902') + version='v201911') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_keys.py index 4f233607..9789b858 100755 --- a/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201902') + 'CmsMetadataService', version='v201911') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_values.py index e7808283..686c45b4 100755 --- a/examples/ad_manager/v201902/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201902') + 'CmsMetadataService', version='v201911') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v201902/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v201911/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v201902/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v201911/cms_metadata_service/get_cms_metadata_values_for_key.py index 075b1879..0f3ac26b 100755 --- a/examples/ad_manager/v201902/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v201911/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201902') + 'CmsMetadataService', version='v201911') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v201902').Where( + ad_manager.StatementBuilder(version='v201911').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v201902/base_rate_service/__init__.py b/examples/ad_manager/v201911/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/base_rate_service/__init__.py rename to examples/ad_manager/v201911/company_service/__init__.py diff --git a/examples/ad_manager/v201902/company_service/create_companies.py b/examples/ad_manager/v201911/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v201902/company_service/create_companies.py rename to examples/ad_manager/v201911/company_service/create_companies.py index 831c6ec0..922225a0 100755 --- a/examples/ad_manager/v201902/company_service/create_companies.py +++ b/examples/ad_manager/v201911/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201902') + company_service = client.GetService('CompanyService', version='v201911') # Create company objects. companies = [ diff --git a/examples/ad_manager/v201902/company_service/get_advertisers.py b/examples/ad_manager/v201911/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v201902/company_service/get_advertisers.py rename to examples/ad_manager/v201911/company_service/get_advertisers.py index c9f5a166..85d6f902 100755 --- a/examples/ad_manager/v201902/company_service/get_advertisers.py +++ b/examples/ad_manager/v201911/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201902') + company_service = client.GetService('CompanyService', version='v201911') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201902/company_service/get_all_companies.py b/examples/ad_manager/v201911/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v201902/company_service/get_all_companies.py rename to examples/ad_manager/v201911/company_service/get_all_companies.py index 83f439ea..b4b955e8 100755 --- a/examples/ad_manager/v201902/company_service/get_all_companies.py +++ b/examples/ad_manager/v201911/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201902') + company_service = client.GetService('CompanyService', version='v201911') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201902/company_service/update_companies.py b/examples/ad_manager/v201911/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v201902/company_service/update_companies.py rename to examples/ad_manager/v201911/company_service/update_companies.py index 293c0a58..f4797e7f 100755 --- a/examples/ad_manager/v201902/company_service/update_companies.py +++ b/examples/ad_manager/v201911/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201902') + company_service = client.GetService('CompanyService', version='v201911') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/company_service/__init__.py b/examples/ad_manager/v201911/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/company_service/__init__.py rename to examples/ad_manager/v201911/contact_service/__init__.py diff --git a/examples/ad_manager/v201902/contact_service/create_contacts.py b/examples/ad_manager/v201911/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v201902/contact_service/create_contacts.py rename to examples/ad_manager/v201911/contact_service/create_contacts.py index 1b9357cb..e11e5b1b 100755 --- a/examples/ad_manager/v201902/contact_service/create_contacts.py +++ b/examples/ad_manager/v201911/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201902') + contact_service = client.GetService('ContactService', version='v201911') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v201902/contact_service/get_all_contacts.py b/examples/ad_manager/v201911/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v201902/contact_service/get_all_contacts.py rename to examples/ad_manager/v201911/contact_service/get_all_contacts.py index da3266d6..65cedd76 100755 --- a/examples/ad_manager/v201902/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v201911/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201902') + contact_service = client.GetService('ContactService', version='v201911') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v201911/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v201911/contact_service/get_uninvited_contacts.py index db4ccd50..c6367670 100755 --- a/examples/ad_manager/v201902/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v201911/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201902') + contact_service = client.GetService('ContactService', version='v201911') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201902/contact_service/update_contacts.py b/examples/ad_manager/v201911/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v201902/contact_service/update_contacts.py rename to examples/ad_manager/v201911/contact_service/update_contacts.py index ff8f5bb9..589d3687 100755 --- a/examples/ad_manager/v201902/contact_service/update_contacts.py +++ b/examples/ad_manager/v201911/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201902') + contact_service = client.GetService('ContactService', version='v201911') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/contact_service/__init__.py b/examples/ad_manager/v201911/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/contact_service/__init__.py rename to examples/ad_manager/v201911/content_service/__init__.py diff --git a/examples/ad_manager/v201902/content_service/get_all_content.py b/examples/ad_manager/v201911/content_service/get_all_content.py similarity index 95% rename from examples/ad_manager/v201902/content_service/get_all_content.py rename to examples/ad_manager/v201911/content_service/get_all_content.py index 259da022..7ca2c6a3 100755 --- a/examples/ad_manager/v201902/content_service/get_all_content.py +++ b/examples/ad_manager/v201911/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201902') + content_service = client.GetService('ContentService', version='v201911') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v201902/content_service/__init__.py b/examples/ad_manager/v201911/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/content_service/__init__.py rename to examples/ad_manager/v201911/creative_service/__init__.py diff --git a/examples/ad_manager/v201902/creative_service/copy_image_creatives.py b/examples/ad_manager/v201911/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v201902/creative_service/copy_image_creatives.py rename to examples/ad_manager/v201911/creative_service/copy_image_creatives.py index 73fbf01b..a8d65e6e 100755 --- a/examples/ad_manager/v201902/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v201911/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201902') + creative_service = client.GetService('CreativeService', version='v201911') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201902/creative_service/create_creative_from_template.py b/examples/ad_manager/v201911/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v201902/creative_service/create_creative_from_template.py rename to examples/ad_manager/v201911/creative_service/create_creative_from_template.py index 0796ce2e..9bb7a8fa 100755 --- a/examples/ad_manager/v201902/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v201911/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201902') + creative_service = client.GetService('CreativeService', version='v201911') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v201902/creative_service/create_creatives.py b/examples/ad_manager/v201911/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v201902/creative_service/create_creatives.py rename to examples/ad_manager/v201911/creative_service/create_creatives.py index 0c8685ad..69423a67 100755 --- a/examples/ad_manager/v201902/creative_service/create_creatives.py +++ b/examples/ad_manager/v201911/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201902') + creative_service = client.GetService('CreativeService', version='v201911') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v201902/creative_service/create_custom_creative.py b/examples/ad_manager/v201911/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v201902/creative_service/create_custom_creative.py rename to examples/ad_manager/v201911/creative_service/create_custom_creative.py index e04c072f..539ef47e 100755 --- a/examples/ad_manager/v201902/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v201911/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201902') + creative_service = client.GetService('CreativeService', version='v201911') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v201902/creative_service/create_native_creative.py b/examples/ad_manager/v201911/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v201902/creative_service/create_native_creative.py rename to examples/ad_manager/v201911/creative_service/create_native_creative.py index 8eeadbd7..c1082ecf 100755 --- a/examples/ad_manager/v201902/creative_service/create_native_creative.py +++ b/examples/ad_manager/v201911/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201902') + creative_service = client.GetService('CreativeService', version='v201911') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v201902/creative_service/get_all_creatives.py b/examples/ad_manager/v201911/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v201902/creative_service/get_all_creatives.py rename to examples/ad_manager/v201911/creative_service/get_all_creatives.py index 9e2a7d34..6d65a061 100755 --- a/examples/ad_manager/v201902/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v201911/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201902') + creative_service = client.GetService('CreativeService', version='v201911') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201902/creative_service/get_image_creatives.py b/examples/ad_manager/v201911/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v201902/creative_service/get_image_creatives.py rename to examples/ad_manager/v201911/creative_service/get_image_creatives.py index 49eb1342..fa2a16e0 100755 --- a/examples/ad_manager/v201902/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v201911/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201902') + creative_service = client.GetService('CreativeService', version='v201911') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201902/creative_service/update_creatives.py b/examples/ad_manager/v201911/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v201902/creative_service/update_creatives.py rename to examples/ad_manager/v201911/creative_service/update_creatives.py index ac8182bc..d3eb4817 100755 --- a/examples/ad_manager/v201902/creative_service/update_creatives.py +++ b/examples/ad_manager/v201911/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201902') + creative_service = client.GetService('CreativeService', version='v201911') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v201902/creative_service/__init__.py b/examples/ad_manager/v201911/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/creative_service/__init__.py rename to examples/ad_manager/v201911/creative_set_service/__init__.py diff --git a/examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v201911/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v201911/creative_set_service/associate_creative_set_to_line_item.py index 752eb61c..d134ca04 100755 --- a/examples/ad_manager/v201902/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v201911/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201902') + 'LineItemCreativeAssociationService', version='v201911') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v201902/creative_set_service/create_creative_set.py b/examples/ad_manager/v201911/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v201902/creative_set_service/create_creative_set.py rename to examples/ad_manager/v201911/creative_set_service/create_creative_set.py index db8a7eb5..36c46bc6 100755 --- a/examples/ad_manager/v201902/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v201911/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201902') + version='v201911') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v201911/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v201911/creative_set_service/get_all_creative_sets.py index f636f81b..6441d610 100755 --- a/examples/ad_manager/v201902/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v201911/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201902') + 'CreativeSetService', version='v201911') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v201911/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v201911/creative_set_service/get_creative_sets_for_master_creative.py index 80b8bbee..47600b95 100755 --- a/examples/ad_manager/v201902/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v201911/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201902') + 'CreativeSetService', version='v201911') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201902/creative_set_service/update_creative_set.py b/examples/ad_manager/v201911/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v201902/creative_set_service/update_creative_set.py rename to examples/ad_manager/v201911/creative_set_service/update_creative_set.py index 266aeb27..fb3f2c9f 100755 --- a/examples/ad_manager/v201902/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v201911/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201902') + version='v201911') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v201902/creative_set_service/__init__.py b/examples/ad_manager/v201911/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/creative_set_service/__init__.py rename to examples/ad_manager/v201911/creative_template_service/__init__.py diff --git a/examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v201911/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v201911/creative_template_service/get_all_creative_templates.py index 63325fab..1cdef040 100755 --- a/examples/ad_manager/v201902/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v201911/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201902') + 'CreativeTemplateService', version='v201911') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v201911/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v201911/creative_template_service/get_system_defined_creative_templates.py index c99ab207..f2ffd2a7 100755 --- a/examples/ad_manager/v201902/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v201911/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201902') + 'CreativeTemplateService', version='v201911') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v201911/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v201911/creative_wrapper_service/create_creative_wrappers.py index e9a2da47..a7e1d7e0 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v201911/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201902') + version='v201911') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v201911/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v201911/creative_wrapper_service/deactivate_creative_wrapper.py index 129682e9..050a56a6 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v201911/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201902') + version='v201911') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v201911/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v201911/creative_wrapper_service/get_active_creative_wrappers.py index dfc51eae..8fe3a701 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v201911/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201902') + 'CreativeWrapperService', version='v201911') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v201911/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v201911/creative_wrapper_service/get_all_creative_wrappers.py index 5e3434f5..41d43849 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v201911/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201902') + 'CreativeWrapperService', version='v201911') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v201911/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v201911/creative_wrapper_service/update_creative_wrappers.py index 3f340f79..8edcd07e 100755 --- a/examples/ad_manager/v201902/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v201911/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201902') + version='v201911') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v201902/creative_template_service/__init__.py b/examples/ad_manager/v201911/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/creative_template_service/__init__.py rename to examples/ad_manager/v201911/custom_field_service/__init__.py diff --git a/examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v201911/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v201911/custom_field_service/create_custom_field_options.py index f9295c51..d7f0f511 100755 --- a/examples/ad_manager/v201902/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v201911/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201902') + 'CustomFieldService', version='v201911') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v201902/custom_field_service/create_custom_fields.py b/examples/ad_manager/v201911/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v201902/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v201911/custom_field_service/create_custom_fields.py index 5c88fa9b..b3b78240 100755 --- a/examples/ad_manager/v201902/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v201911/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201902') + 'CustomFieldService', version='v201911') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v201911/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v201911/custom_field_service/deactivate_all_line_item_custom_fields.py index 452e3719..a6a7ac51 100755 --- a/examples/ad_manager/v201902/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v201911/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201902') + 'CustomFieldService', version='v201911') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v201911/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v201911/custom_field_service/get_all_custom_fields.py index 83a59bf1..d6933693 100755 --- a/examples/ad_manager/v201902/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v201911/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201902') + 'CustomFieldService', version='v201911') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v201911/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v201911/custom_field_service/get_custom_fields_for_line_items.py index d989d9e6..10f0e004 100755 --- a/examples/ad_manager/v201902/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v201911/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201902') + 'CustomFieldService', version='v201911') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v201911/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v201911/custom_field_service/set_line_item_custom_field_value.py index 4efbfad4..c168149f 100755 --- a/examples/ad_manager/v201902/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v201911/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201902') + 'CustomFieldService', version='v201911') - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v201902') + custom_field_statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v201902') + ad_manager.StatementBuilder(version='v201911') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v201902') + line_item_statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201902/custom_field_service/update_custom_fields.py b/examples/ad_manager/v201911/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v201902/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v201911/custom_field_service/update_custom_fields.py index 9f84b724..933dcdc9 100755 --- a/examples/ad_manager/v201902/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v201911/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201902') + 'CustomFieldService', version='v201911') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v201902/custom_field_service/__init__.py b/examples/ad_manager/v201911/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/custom_field_service/__init__.py rename to examples/ad_manager/v201911/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v201911/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201911/custom_targeting_service/create_custom_targeting_keys_and_values.py index 1a5f86c7..e55df15d 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201911/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201902') + 'CustomTargetingService', version='v201911') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_keys.py index d30a19d0..41ddbd56 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201902') + 'CustomTargetingService', version='v201911') - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v201902') + key_statement = (ad_manager.StatementBuilder(version='v201911') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_values.py index 82c14c38..da495b9e 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201902') + 'CustomTargetingService', version='v201911') - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v201902') + value_statement = (ad_manager.StatementBuilder(version='v201911') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v201911/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201911/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index a4818d01..478f87d8 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201911/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201902') + 'CustomTargetingService', version='v201911') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v201902') + targeting_key_statement = ad_manager.StatementBuilder(version='v201911') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v201911/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v201911/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 19af06c1..c1fb91af 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v201911/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201902') + 'CustomTargetingService', version='v201911') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v201902') + targeting_key_statement = (ad_manager.StatementBuilder(version='v201911') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_keys.py index 8578015c..291e4ead 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201902') + 'CustomTargetingService', version='v201911') - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_values.py index 8ab23c0f..52855cf0 100755 --- a/examples/ad_manager/v201902/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201902') + 'CustomTargetingService', version='v201911') - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py b/examples/ad_manager/v201911/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v201902/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v201911/forecast_service/get_availability_forecast.py index e5095213..4b226c9a 100755 --- a/examples/ad_manager/v201902/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v201911/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201902') - network_service = client.GetService('NetworkService', version='v201902') + forecast_service = client.GetService('ForecastService', version='v201911') + network_service = client.GetService('NetworkService', version='v201911') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v201911/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v201911/forecast_service/get_availability_forecast_for_line_item.py index 2f124d57..de0a2f81 100755 --- a/examples/ad_manager/v201902/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v201911/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201902') + forecast_service = client.GetService('ForecastService', version='v201911') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v201911/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v201911/forecast_service/get_delivery_forecast_for_line_items.py index 0ab4fde2..76c1de8e 100755 --- a/examples/ad_manager/v201902/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v201911/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201902') + forecast_service = client.GetService('ForecastService', version='v201911') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v201902/custom_targeting_service/__init__.py b/examples/ad_manager/v201911/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/custom_targeting_service/__init__.py rename to examples/ad_manager/v201911/inventory_service/__init__.py diff --git a/examples/ad_manager/v201902/inventory_service/archive_ad_units.py b/examples/ad_manager/v201911/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v201902/inventory_service/archive_ad_units.py rename to examples/ad_manager/v201911/inventory_service/archive_ad_units.py index 6388f13a..514317f9 100755 --- a/examples/ad_manager/v201902/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v201911/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201902') + inventory_service = client.GetService('InventoryService', version='v201911') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v201902/inventory_service/create_ad_units.py b/examples/ad_manager/v201911/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v201902/inventory_service/create_ad_units.py rename to examples/ad_manager/v201911/inventory_service/create_ad_units.py index 7b2bb36a..050027c5 100755 --- a/examples/ad_manager/v201902/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v201911/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201902') + inventory_service = client.GetService('InventoryService', version='v201911') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v201911/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v201911/inventory_service/get_ad_unit_hierarchy.py index 5f06a8cf..11d1650f 100755 --- a/examples/ad_manager/v201902/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v201911/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201902') - inventory_service = client.GetService('InventoryService', version='v201902') + network_service = client.GetService('NetworkService', version='v201911') + inventory_service = client.GetService('InventoryService', version='v201911') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201902/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v201911/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v201902/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v201911/inventory_service/get_all_ad_unit_sizes.py index 6405df08..5f357625 100755 --- a/examples/ad_manager/v201902/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v201911/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201902') + 'InventoryService', version='v201911') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201902/inventory_service/get_all_ad_units.py b/examples/ad_manager/v201911/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v201902/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v201911/inventory_service/get_all_ad_units.py index 308e38e7..52c617b4 100755 --- a/examples/ad_manager/v201902/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v201911/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201902') + ad_unit_service = client.GetService('InventoryService', version='v201911') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v201911/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v201911/inventory_service/get_top_level_ad_units.py index 98243add..34701714 100755 --- a/examples/ad_manager/v201902/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v201911/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201902') - inventory_service = client.GetService('InventoryService', version='v201902') + network_service = client.GetService('NetworkService', version='v201911') + inventory_service = client.GetService('InventoryService', version='v201911') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201902/inventory_service/update_ad_units.py b/examples/ad_manager/v201911/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v201902/inventory_service/update_ad_units.py rename to examples/ad_manager/v201911/inventory_service/update_ad_units.py index f1829b07..15f24e0d 100755 --- a/examples/ad_manager/v201902/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v201911/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201902') + inventory_service = client.GetService('InventoryService', version='v201911') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201902/exchange_rate_service/__init__.py b/examples/ad_manager/v201911/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/exchange_rate_service/__init__.py rename to examples/ad_manager/v201911/label_service/__init__.py diff --git a/examples/ad_manager/v201902/label_service/create_labels.py b/examples/ad_manager/v201911/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v201902/label_service/create_labels.py rename to examples/ad_manager/v201911/label_service/create_labels.py index 00e50da0..311f18de 100755 --- a/examples/ad_manager/v201902/label_service/create_labels.py +++ b/examples/ad_manager/v201911/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201902') + label_service = client.GetService('LabelService', version='v201911') # Create label objects. labels = [] diff --git a/examples/ad_manager/v201902/label_service/deactivate_labels.py b/examples/ad_manager/v201911/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v201902/label_service/deactivate_labels.py rename to examples/ad_manager/v201911/label_service/deactivate_labels.py index a97cb136..8e87b5f3 100755 --- a/examples/ad_manager/v201902/label_service/deactivate_labels.py +++ b/examples/ad_manager/v201911/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201902') + label_service = client.GetService('LabelService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201902/label_service/get_active_labels.py b/examples/ad_manager/v201911/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v201902/label_service/get_active_labels.py rename to examples/ad_manager/v201911/label_service/get_active_labels.py index 02aab6b4..84ec19ad 100755 --- a/examples/ad_manager/v201902/label_service/get_active_labels.py +++ b/examples/ad_manager/v201911/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201902') + label_service = client.GetService('LabelService', version='v201911') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201902/label_service/get_all_labels.py b/examples/ad_manager/v201911/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v201902/label_service/get_all_labels.py rename to examples/ad_manager/v201911/label_service/get_all_labels.py index 0e944fba..6c50e38b 100755 --- a/examples/ad_manager/v201902/label_service/get_all_labels.py +++ b/examples/ad_manager/v201911/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201902') + label_service = client.GetService('LabelService', version='v201911') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201902/label_service/update_labels.py b/examples/ad_manager/v201911/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v201902/label_service/update_labels.py rename to examples/ad_manager/v201911/label_service/update_labels.py index 2f19fba5..f98f2118 100755 --- a/examples/ad_manager/v201902/label_service/update_labels.py +++ b/examples/ad_manager/v201911/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201902') + label_service = client.GetService('LabelService', version='v201911') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201902/inventory_service/__init__.py b/examples/ad_manager/v201911/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/inventory_service/__init__.py rename to examples/ad_manager/v201911/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v201911/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v201911/line_item_creative_association_service/create_licas.py index 9aa8b810..ab10eaaa 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v201911/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201902') + 'LineItemCreativeAssociationService', version='v201911') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v201911/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v201911/line_item_creative_association_service/deactivate_licas.py index 390a2818..bbaf75e9 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v201911/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201902') + 'LineItemCreativeAssociationService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v201911/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v201911/line_item_creative_association_service/get_all_licas.py index 7ea54471..f9ce6186 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v201911/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201902') + 'LineItemCreativeAssociationService', version='v201911') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v201911/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v201911/line_item_creative_association_service/get_licas_for_line_item.py index d9351f25..55a8687b 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v201911/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201902') + 'LineItemCreativeAssociationService', version='v201911') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v201911/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v201911/line_item_creative_association_service/update_licas.py index 0bc348e6..92fd7ace 100755 --- a/examples/ad_manager/v201902/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v201911/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201902') + 'LineItemCreativeAssociationService', version='v201911') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201902/label_service/__init__.py b/examples/ad_manager/v201911/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/label_service/__init__.py rename to examples/ad_manager/v201911/line_item_service/__init__.py diff --git a/examples/ad_manager/v201902/line_item_service/activate_line_items.py b/examples/ad_manager/v201911/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v201902/line_item_service/activate_line_items.py rename to examples/ad_manager/v201911/line_item_service/activate_line_items.py index 3db3c90a..dc096cae 100755 --- a/examples/ad_manager/v201902/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v201911/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201902/line_item_service/create_line_items.py b/examples/ad_manager/v201911/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v201902/line_item_service/create_line_items.py rename to examples/ad_manager/v201911/line_item_service/create_line_items.py index 67334dbb..a487b3ad 100755 --- a/examples/ad_manager/v201902/line_item_service/create_line_items.py +++ b/examples/ad_manager/v201911/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201902/line_item_service/create_video_line_item.py b/examples/ad_manager/v201911/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v201902/line_item_service/create_video_line_item.py rename to examples/ad_manager/v201911/line_item_service/create_video_line_item.py index b599884a..6cc2f5c2 100755 --- a/examples/ad_manager/v201902/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v201911/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201902/line_item_service/get_all_line_items.py b/examples/ad_manager/v201911/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v201902/line_item_service/get_all_line_items.py rename to examples/ad_manager/v201911/line_item_service/get_all_line_items.py index 48f5ff96..19b5aa5f 100755 --- a/examples/ad_manager/v201902/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v201911/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v201911/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v201911/line_item_service/get_line_items_that_need_creatives.py index 56eb70f4..2cddf9ea 100755 --- a/examples/ad_manager/v201902/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v201911/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v201911/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v201911/line_item_service/get_recently_updated_line_items.py index e184d334..0971c050 100755 --- a/examples/ad_manager/v201902/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v201911/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201902/line_item_service/pause_line_items.py b/examples/ad_manager/v201911/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v201902/line_item_service/pause_line_items.py rename to examples/ad_manager/v201911/line_item_service/pause_line_items.py index be12973f..cae1fa1c 100755 --- a/examples/ad_manager/v201902/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v201911/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201902/line_item_service/target_custom_criteria.py b/examples/ad_manager/v201911/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v201902/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v201911/line_item_service/target_custom_criteria.py index a2c7d0ab..41399c89 100755 --- a/examples/ad_manager/v201902/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v201911/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/line_item_service/update_line_items.py b/examples/ad_manager/v201911/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v201902/line_item_service/update_line_items.py rename to examples/ad_manager/v201911/line_item_service/update_line_items.py index 114afd02..8f3bd6e5 100755 --- a/examples/ad_manager/v201902/line_item_service/update_line_items.py +++ b/examples/ad_manager/v201911/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') + line_item_service = client.GetService('LineItemService', version='v201911') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v201911/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v201911/live_stream_event_service/activate_live_stream_events.py index 734feff0..18b76a52 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v201911/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201902') + 'LiveStreamEventService', version='v201911') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201902/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v201911/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v201902/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v201911/live_stream_event_service/create_live_stream_events.py index fe485e81..49ab8bf2 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v201911/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201902') + 'LiveStreamEventService', version='v201911') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v201911/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v201911/live_stream_event_service/get_all_live_stream_events.py index 7402f578..ec5e3fa4 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v201911/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201902') + 'LiveStreamEventService', version='v201911') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v201911/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v201911/live_stream_event_service/register_sessions_for_monitoring.py index 11af75d0..9817e44e 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v201911/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201902') + 'LiveStreamEventService', version='v201911') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v201911/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v201911/live_stream_event_service/update_live_stream_events.py index a40ac261..bb05fd6c 100755 --- a/examples/ad_manager/v201902/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v201911/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201902') + 'LiveStreamEventService', version='v201911') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201902/native_style_service/__init__.py b/examples/ad_manager/v201911/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/native_style_service/__init__.py rename to examples/ad_manager/v201911/native_style_service/__init__.py diff --git a/examples/ad_manager/v201902/native_style_service/create_native_styles.py b/examples/ad_manager/v201911/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v201902/native_style_service/create_native_styles.py rename to examples/ad_manager/v201911/native_style_service/create_native_styles.py index 9edb16d7..a967fd7d 100755 --- a/examples/ad_manager/v201902/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v201911/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201902') + version='v201911') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v201902/native_style_service/get_all_native_styles.py b/examples/ad_manager/v201911/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v201902/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v201911/native_style_service/get_all_native_styles.py index 2301b0ba..a3d94698 100755 --- a/examples/ad_manager/v201902/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v201911/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201902') + version='v201911') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201902/line_item_creative_association_service/__init__.py b/examples/ad_manager/v201911/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v201911/network_service/__init__.py diff --git a/examples/ad_manager/v201902/network_service/get_all_networks.py b/examples/ad_manager/v201911/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v201902/network_service/get_all_networks.py rename to examples/ad_manager/v201911/network_service/get_all_networks.py index 3c6aebff..99d656d8 100755 --- a/examples/ad_manager/v201902/network_service/get_all_networks.py +++ b/examples/ad_manager/v201911/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201902') + network_service = client.GetService('NetworkService', version='v201911') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v201902/network_service/get_current_network.py b/examples/ad_manager/v201911/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v201902/network_service/get_current_network.py rename to examples/ad_manager/v201911/network_service/get_current_network.py index e8d960dd..9593231e 100755 --- a/examples/ad_manager/v201902/network_service/get_current_network.py +++ b/examples/ad_manager/v201911/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201902') + network_service = client.GetService('NetworkService', version='v201911') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201902/network_service/make_test_network.py b/examples/ad_manager/v201911/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v201902/network_service/make_test_network.py rename to examples/ad_manager/v201911/network_service/make_test_network.py index 0e4240cc..bca56e9f 100755 --- a/examples/ad_manager/v201902/network_service/make_test_network.py +++ b/examples/ad_manager/v201911/network_service/make_test_network.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201902') + network_service = client.GetService('NetworkService', version='v201911') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v201902/line_item_service/__init__.py b/examples/ad_manager/v201911/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/line_item_service/__init__.py rename to examples/ad_manager/v201911/order_service/__init__.py diff --git a/examples/ad_manager/v201902/order_service/approve_orders.py b/examples/ad_manager/v201911/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v201902/order_service/approve_orders.py rename to examples/ad_manager/v201911/order_service/approve_orders.py index 16b6acbc..1a19ce76 100755 --- a/examples/ad_manager/v201902/order_service/approve_orders.py +++ b/examples/ad_manager/v201911/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201902') + order_service = client.GetService('OrderService', version='v201911') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201902/order_service/create_orders.py b/examples/ad_manager/v201911/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v201902/order_service/create_orders.py rename to examples/ad_manager/v201911/order_service/create_orders.py index 6ba93011..cf68732c 100755 --- a/examples/ad_manager/v201902/order_service/create_orders.py +++ b/examples/ad_manager/v201911/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201902') + order_service = client.GetService('OrderService', version='v201911') # Create order objects. orders = [] diff --git a/examples/ad_manager/v201902/order_service/get_all_orders.py b/examples/ad_manager/v201911/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v201902/order_service/get_all_orders.py rename to examples/ad_manager/v201911/order_service/get_all_orders.py index 3390d61e..c13e3bf6 100755 --- a/examples/ad_manager/v201902/order_service/get_all_orders.py +++ b/examples/ad_manager/v201911/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201902') + order_service = client.GetService('OrderService', version='v201911') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201902/order_service/get_orders_starting_soon.py b/examples/ad_manager/v201911/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v201902/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v201911/order_service/get_orders_starting_soon.py index 344da809..32ae6012 100755 --- a/examples/ad_manager/v201902/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v201911/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201902') + order_service = client.GetService('OrderService', version='v201911') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201902/order_service/update_orders.py b/examples/ad_manager/v201911/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v201902/order_service/update_orders.py rename to examples/ad_manager/v201911/order_service/update_orders.py index 4ed63a8d..381420de 100755 --- a/examples/ad_manager/v201902/order_service/update_orders.py +++ b/examples/ad_manager/v201911/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201902') + order_service = client.GetService('OrderService', version='v201911') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201902/placement_service/create_placements.py b/examples/ad_manager/v201911/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v201902/placement_service/create_placements.py rename to examples/ad_manager/v201911/placement_service/create_placements.py index f8757ca3..620faac0 100755 --- a/examples/ad_manager/v201902/placement_service/create_placements.py +++ b/examples/ad_manager/v201911/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201902') - inventory_service = client.GetService('InventoryService', version='v201902') + placement_service = client.GetService('PlacementService', version='v201911') + inventory_service = client.GetService('InventoryService', version='v201911') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201902/placement_service/deactivate_placements.py b/examples/ad_manager/v201911/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v201902/placement_service/deactivate_placements.py rename to examples/ad_manager/v201911/placement_service/deactivate_placements.py index 20ab2fa3..2aa4bcff 100755 --- a/examples/ad_manager/v201902/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v201911/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201902') + placement_service = client.GetService('PlacementService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/placement_service/get_active_placements.py b/examples/ad_manager/v201911/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v201902/placement_service/get_active_placements.py rename to examples/ad_manager/v201911/placement_service/get_active_placements.py index 3786b708..edf21eaf 100755 --- a/examples/ad_manager/v201902/placement_service/get_active_placements.py +++ b/examples/ad_manager/v201911/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201902') + placement_service = client.GetService('PlacementService', version='v201911') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201902/placement_service/get_all_placements.py b/examples/ad_manager/v201911/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v201902/placement_service/get_all_placements.py rename to examples/ad_manager/v201911/placement_service/get_all_placements.py index d2846654..99fd743a 100755 --- a/examples/ad_manager/v201902/placement_service/get_all_placements.py +++ b/examples/ad_manager/v201911/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201902') + placement_service = client.GetService('PlacementService', version='v201911') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201902/placement_service/update_placements.py b/examples/ad_manager/v201911/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v201902/placement_service/update_placements.py rename to examples/ad_manager/v201911/placement_service/update_placements.py index 66a2fdbb..cd77c3a4 100755 --- a/examples/ad_manager/v201902/placement_service/update_placements.py +++ b/examples/ad_manager/v201911/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201902') + placement_service = client.GetService('PlacementService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201902/network_service/__init__.py b/examples/ad_manager/v201911/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/network_service/__init__.py rename to examples/ad_manager/v201911/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v201911/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v201911/proposal_line_item_service/archive_proposal_line_items.py index 9bb2b5bf..b7d064eb 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v201911/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201902') + 'ProposalLineItemService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v201911/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v201911/proposal_line_item_service/create_proposal_line_items.py index 0f0bff70..6833cf8a 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v201911/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201902') - network_service = client.GetService('NetworkService', version='v201902') + 'ProposalLineItemService', version='v201911') + network_service = client.GetService('NetworkService', version='v201911') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v201911/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v201911/proposal_line_item_service/get_all_proposal_line_items.py index b9410478..9a99551b 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v201911/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201902') + 'ProposalLineItemService', version='v201911') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v201911/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v201911/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 5a3b046c..10e2cf55 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v201911/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201902') + 'ProposalLineItemService', version='v201911') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v201911/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v201911/proposal_line_item_service/update_proposal_line_items.py index e1f956d0..6193d90a 100755 --- a/examples/ad_manager/v201902/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v201911/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201902') + 'ProposalLineItemService', version='v201911') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/order_service/__init__.py b/examples/ad_manager/v201911/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/order_service/__init__.py rename to examples/ad_manager/v201911/proposal_service/__init__.py diff --git a/examples/ad_manager/v201902/proposal_service/create_proposals.py b/examples/ad_manager/v201911/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v201902/proposal_service/create_proposals.py rename to examples/ad_manager/v201911/proposal_service/create_proposals.py index f8030b14..cc183fb4 100755 --- a/examples/ad_manager/v201902/proposal_service/create_proposals.py +++ b/examples/ad_manager/v201911/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201902') + proposal_service = client.GetService('ProposalService', version='v201911') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201902/proposal_service/get_all_proposals.py b/examples/ad_manager/v201911/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v201902/proposal_service/get_all_proposals.py rename to examples/ad_manager/v201911/proposal_service/get_all_proposals.py index de978527..92efce68 100755 --- a/examples/ad_manager/v201902/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v201911/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201902') + proposal_service = client.GetService('ProposalService', version='v201911') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v201911/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v201911/proposal_service/get_marketplace_comments.py index f0cbb405..773a94f1 100755 --- a/examples/ad_manager/v201902/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v201911/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201902') + 'ProposalService', version='v201911') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v201902/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v201911/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v201902/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v201911/proposal_service/get_proposals_awaiting_seller_review.py index 8e3d1ac0..a7d3aafc 100755 --- a/examples/ad_manager/v201902/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v201911/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201902') + proposal_service = client.GetService('ProposalService', version='v201911') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v201911/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v201911/proposal_service/request_buyers_acceptance.py index ad893e5a..29b238a1 100755 --- a/examples/ad_manager/v201902/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v201911/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201902') + proposal_service = client.GetService('ProposalService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201902/proposal_service/update_proposals.py b/examples/ad_manager/v201911/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v201902/proposal_service/update_proposals.py rename to examples/ad_manager/v201911/proposal_service/update_proposals.py index 9596c08d..cbc08806 100755 --- a/examples/ad_manager/v201902/proposal_service/update_proposals.py +++ b/examples/ad_manager/v201911/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201902') + proposal_service = client.GetService('ProposalService', version='v201911') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/premium_rate_service/__init__.py b/examples/ad_manager/v201911/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/premium_rate_service/__init__.py rename to examples/ad_manager/v201911/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v201911/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v201911/publisher_query_language_service/fetch_match_tables.py index 9179f0c4..3beec75d 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v201911/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v201911/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v201911/publisher_query_language_service/get_all_browsers.py index 8cecbc29..c9872558 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v201911/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v201911/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v201911/publisher_query_language_service/get_all_programmatic_buyers.py index b84c4266..f1fa36b3 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v201911/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201902') + data_downloader = client.GetDataDownloader(version='v201911') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v201911/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v201911/publisher_query_language_service/get_geo_targets.py index 5a38a8bc..60baf278 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v201911/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v201911/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v201911/publisher_query_language_service/get_line_items_named_like.py index 65b9d769..56e06b25 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v201911/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v201911/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v201911/publisher_query_language_service/get_recent_changes.py index 37457e79..7009fba9 100755 --- a/examples/ad_manager/v201902/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v201911/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201902') + pql_service = client.GetService('PublisherQueryLanguageService', 'v201911') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v201902/product_service/__init__.py b/examples/ad_manager/v201911/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/product_service/__init__.py rename to examples/ad_manager/v201911/report_service/__init__.py diff --git a/examples/ad_manager/v201902/report_service/run_ad_exchange_report.py b/examples/ad_manager/v201911/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v201902/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v201911/report_service/run_ad_exchange_report.py index 8025139c..92c62d0b 100755 --- a/examples/ad_manager/v201902/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v201911/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') # Create report job. report_job = { diff --git a/examples/ad_manager/v201902/report_service/run_delivery_report.py b/examples/ad_manager/v201911/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v201902/report_service/run_delivery_report.py rename to examples/ad_manager/v201911/report_service/run_delivery_report.py index 5db8cf28..5272d8d2 100755 --- a/examples/ad_manager/v201902/report_service/run_delivery_report.py +++ b/examples/ad_manager/v201911/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201902/report_service/run_inventory_report.py b/examples/ad_manager/v201911/report_service/run_inventory_report.py similarity index 74% rename from examples/ad_manager/v201902/report_service/run_inventory_report.py rename to examples/ad_manager/v201911/report_service/run_inventory_report.py index 5c4e06c0..1fad0c7c 100755 --- a/examples/ad_manager/v201902/report_service/run_inventory_report.py +++ b/examples/ad_manager/v201911/report_service/run_inventory_report.py @@ -24,21 +24,8 @@ def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201902') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201902') - - # Get root ad unit id for network. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') - .WithBindVariable('parentAdUnitId', int(root_ad_unit_id)) - .Limit(None) # No limit or offset for reports - .Offset(None)) + report_downloader = client.GetDataDownloader(version='v201911') # Create report job. report_job = { @@ -50,8 +37,7 @@ def main(client): 'ADSENSE_LINE_ITEM_LEVEL_CLICKS', 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'], - 'dateRangeType': 'LAST_WEEK', - 'statement': statement.ToStatement() + 'dateRangeType': 'LAST_WEEK' } } diff --git a/examples/ad_manager/v201902/report_service/run_reach_report.py b/examples/ad_manager/v201911/report_service/run_reach_report.py similarity index 87% rename from examples/ad_manager/v201902/report_service/run_reach_report.py rename to examples/ad_manager/v201911/report_service/run_reach_report.py index dd5f4036..24fefde0 100755 --- a/examples/ad_manager/v201902/report_service/run_reach_report.py +++ b/examples/ad_manager/v201911/report_service/run_reach_report.py @@ -25,13 +25,14 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') # Create report job. report_job = { 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'], + 'dimensions': ['COUNTRY_NAME', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS', + 'UNIQUE_REACH'], 'dateRangeType': 'REACH_LIFETIME' } } diff --git a/examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v201911/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v201911/report_service/run_report_and_create_match_table.py index ef9d4916..af07b909 100755 --- a/examples/ad_manager/v201902/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v201911/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v201911/report_service/run_report_with_custom_fields.py similarity index 55% rename from examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v201911/report_service/run_report_with_custom_fields.py index 4af9c240..7ab092f5 100755 --- a/examples/ad_manager/v201902/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v201911/report_service/run_report_with_custom_fields.py @@ -22,51 +22,22 @@ from googleads import ad_manager from googleads import errors -# Set the ID of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' +CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID' +CUSTOM_DIMENSION_KEY_ID = 'INSERT_CUSTOM_DIMENSION_KEY_ID' -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201902') +def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201902') - - # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder(version='v201902') - .Where('orderId = :orderId') - .WithBindVariable('orderId', int(order_id))) - - # Collect all line item custom field IDs for an order. - custom_field_ids = set() - - # Get users by statement. - while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Get custom field IDs from the line items of an order. - for line_item in response['results']: - if 'customFieldValues' in line_item: - for custom_field_value in line_item['customFieldValues']: - custom_field_ids.add(custom_field_value['customFieldId']) - statement.offset += statement.limit - else: - break - - # Modify statement for reports - statement.limit = None - statement.offset = None - statement.Where('ORDER_ID = :orderId') + report_downloader = client.GetDataDownloader(version='v201911') # Create report job. report_job = { 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': statement.ToStatement(), + 'dimensions': ['CUSTOM_DIMENSION', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'], 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', - 'customFieldIds': list(custom_field_ids) + 'customFieldIds': [custom_field_id], + 'customDimensionKeyIds': [custom_dimension_key_id] } } @@ -94,4 +65,4 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID) + main(ad_manager_client, CUSTOM_FIELD_ID, CUSTOM_DIMENSION_KEY_ID) diff --git a/examples/ad_manager/v201902/report_service/run_sales_report.py b/examples/ad_manager/v201911/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v201902/report_service/run_sales_report.py rename to examples/ad_manager/v201911/report_service/run_sales_report.py index 76379106..b160ffca 100755 --- a/examples/ad_manager/v201902/report_service/run_sales_report.py +++ b/examples/ad_manager/v201911/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') # Create report job. report_job = { diff --git a/examples/ad_manager/v201902/report_service/run_saved_query.py b/examples/ad_manager/v201911/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v201902/report_service/run_saved_query.py rename to examples/ad_manager/v201911/report_service/run_saved_query.py index 0f217acc..57d81295 100755 --- a/examples/ad_manager/v201902/report_service/run_saved_query.py +++ b/examples/ad_manager/v201911/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201902') + report_service = client.GetService('ReportService', version='v201911') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201902') + report_downloader = client.GetDataDownloader(version='v201911') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v201902/product_template_service/__init__.py b/examples/ad_manager/v201911/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/product_template_service/__init__.py rename to examples/ad_manager/v201911/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v201911/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v201911/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 19d48551..d4ae5437 100755 --- a/examples/ad_manager/v201902/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v201911/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201902') + 'SuggestedAdUnitService', version='v201911') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v201911/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v201911/suggested_ad_unit_service/get_all_suggested_ad_units.py index 2cb50683..2648020f 100755 --- a/examples/ad_manager/v201902/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v201911/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201902') + 'SuggestedAdUnitService', version='v201911') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v201911/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v201911/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 141e92a5..a4739113 100755 --- a/examples/ad_manager/v201902/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v201911/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201902') + 'SuggestedAdUnitService', version='v201911') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v201902/rate_card_service/__init__.py b/examples/ad_manager/v201911/targeting_preset_service/__init__.py similarity index 91% rename from examples/ad_manager/v201902/rate_card_service/__init__.py rename to examples/ad_manager/v201911/targeting_preset_service/__init__.py index 3746cd33..6d126cce 100755 --- a/examples/ad_manager/v201902/rate_card_service/__init__.py +++ b/examples/ad_manager/v201911/targeting_preset_service/__init__.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2015 Google Inc. All Rights Reserved. +# Copyright 2019 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. diff --git a/examples/ad_manager/v201902/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py similarity index 59% rename from examples/ad_manager/v201902/product_template_service/get_all_product_templates.py rename to examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py index 3084af7b..525e4f56 100755 --- a/examples/ad_manager/v201902/product_template_service/get_all_product_templates.py +++ b/examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2016 Google Inc. All Rights Reserved. +# Copyright 2019 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. @@ -13,7 +13,7 @@ # 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 product templates. +"""This example gets all targeting presets. """ # Import appropriate modules from the client library. @@ -22,22 +22,23 @@ def main(client): # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201902') + targeting_preset_service = client.GetService( + 'TargetingPresetService', version='v201911') - # Create a statement to select product templates. - statement = ad_manager.StatementBuilder(version='v201902') + # Create a statement to select suggested ad units. + statement = ad_manager.StatementBuilder(version='v201911') - # Retrieve a small amount of product templates at a time, paging - # through until all product templates have been retrieved. + # Retrieve a small number of targeting presets at a time, paging + # through until all targeting presets have been retrieved. while True: - response = product_template_service.getProductTemplatesByStatement( + response = targeting_preset_service.getTargetingPresetsByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): - for product_template in response['results']: - # Print out some information for each product template. - print('Product template with ID "%d" and name "%s" was found.\n' % - (product_template['id'], product_template['name'])) + for targeting_preset in response['results']: + # Print out some information for each targeting preset. + print( + 'Targeting preset with ID "%s" and name "%d" was found.\n' + % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v201902/proposal_line_item_service/__init__.py b/examples/ad_manager/v201911/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/proposal_line_item_service/__init__.py rename to examples/ad_manager/v201911/team_service/__init__.py diff --git a/examples/ad_manager/v201902/team_service/create_teams.py b/examples/ad_manager/v201911/team_service/create_teams.py similarity index 99% rename from examples/ad_manager/v201902/team_service/create_teams.py rename to examples/ad_manager/v201911/team_service/create_teams.py index 3d9772f1..ed705c71 100755 --- a/examples/ad_manager/v201902/team_service/create_teams.py +++ b/examples/ad_manager/v201911/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201902') + team_service = client.GetService('TeamService', version='v201911') # Create team objects. teams = [] diff --git a/examples/ad_manager/v201902/team_service/get_all_teams.py b/examples/ad_manager/v201911/team_service/get_all_teams.py similarity index 96% rename from examples/ad_manager/v201902/team_service/get_all_teams.py rename to examples/ad_manager/v201911/team_service/get_all_teams.py index ab31e99b..c2b8ed66 100755 --- a/examples/ad_manager/v201902/team_service/get_all_teams.py +++ b/examples/ad_manager/v201911/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201902') + team_service = client.GetService('TeamService', version='v201911') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201902/team_service/update_teams.py b/examples/ad_manager/v201911/team_service/update_teams.py similarity index 97% rename from examples/ad_manager/v201902/team_service/update_teams.py rename to examples/ad_manager/v201911/team_service/update_teams.py index 8910b8df..3febda96 100755 --- a/examples/ad_manager/v201902/team_service/update_teams.py +++ b/examples/ad_manager/v201911/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201902') + team_service = client.GetService('TeamService', version='v201911') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v201902/proposal_service/__init__.py b/examples/ad_manager/v201911/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/proposal_service/__init__.py rename to examples/ad_manager/v201911/user_service/__init__.py diff --git a/examples/ad_manager/v201902/user_service/create_users.py b/examples/ad_manager/v201911/user_service/create_users.py similarity index 99% rename from examples/ad_manager/v201902/user_service/create_users.py rename to examples/ad_manager/v201911/user_service/create_users.py index 144bd087..8469e530 100755 --- a/examples/ad_manager/v201902/user_service/create_users.py +++ b/examples/ad_manager/v201911/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201902') + user_service = client.GetService('UserService', version='v201911') # Create user objects. users = [ diff --git a/examples/ad_manager/v201902/user_service/deactivate_users.py b/examples/ad_manager/v201911/user_service/deactivate_users.py similarity index 97% rename from examples/ad_manager/v201902/user_service/deactivate_users.py rename to examples/ad_manager/v201911/user_service/deactivate_users.py index 66f2c592..c6f28f8e 100755 --- a/examples/ad_manager/v201902/user_service/deactivate_users.py +++ b/examples/ad_manager/v201911/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201902') + user_service = client.GetService('UserService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201902/user_service/get_all_roles.py b/examples/ad_manager/v201911/user_service/get_all_roles.py similarity index 99% rename from examples/ad_manager/v201902/user_service/get_all_roles.py rename to examples/ad_manager/v201911/user_service/get_all_roles.py index 38cfc420..ddc854f7 100755 --- a/examples/ad_manager/v201902/user_service/get_all_roles.py +++ b/examples/ad_manager/v201911/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v201911') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v201902/user_service/get_all_users.py b/examples/ad_manager/v201911/user_service/get_all_users.py similarity index 96% rename from examples/ad_manager/v201902/user_service/get_all_users.py rename to examples/ad_manager/v201911/user_service/get_all_users.py index e4b2602d..f72a8f63 100755 --- a/examples/ad_manager/v201902/user_service/get_all_users.py +++ b/examples/ad_manager/v201911/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201902') + user_service = client.GetService('UserService', version='v201911') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201902/user_service/get_current_user.py b/examples/ad_manager/v201911/user_service/get_current_user.py similarity index 99% rename from examples/ad_manager/v201902/user_service/get_current_user.py rename to examples/ad_manager/v201911/user_service/get_current_user.py index 55b0c090..333407b0 100755 --- a/examples/ad_manager/v201902/user_service/get_current_user.py +++ b/examples/ad_manager/v201911/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201902') + user_service = client.GetService('UserService', version='v201911') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v201902/user_service/get_user_by_email_address.py b/examples/ad_manager/v201911/user_service/get_user_by_email_address.py similarity index 96% rename from examples/ad_manager/v201902/user_service/get_user_by_email_address.py rename to examples/ad_manager/v201911/user_service/get_user_by_email_address.py index 3ea58d08..21590b64 100755 --- a/examples/ad_manager/v201902/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v201911/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201902') + user_service = client.GetService('UserService', version='v201911') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201902/user_service/update_users.py b/examples/ad_manager/v201911/user_service/update_users.py similarity index 96% rename from examples/ad_manager/v201902/user_service/update_users.py rename to examples/ad_manager/v201911/user_service/update_users.py index 3663abbf..d6b7b0be 100755 --- a/examples/ad_manager/v201902/user_service/update_users.py +++ b/examples/ad_manager/v201911/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201902') + user_service = client.GetService('UserService', version='v201911') # Create query. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201902/publisher_query_language_service/__init__.py b/examples/ad_manager/v201911/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201902/publisher_query_language_service/__init__.py rename to examples/ad_manager/v201911/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v201911/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v201911/user_team_association_service/create_user_team_associations.py index ae07570f..989253e6 100755 --- a/examples/ad_manager/v201902/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v201911/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201902') + 'UserTeamAssociationService', version='v201911') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v201911/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v201911/user_team_association_service/delete_user_team_associations.py index f53edcff..78f05488 100755 --- a/examples/ad_manager/v201902/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v201911/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201902') + 'UserTeamAssociationService', version='v201911') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v201911/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v201911/user_team_association_service/get_all_user_team_associations.py index 77a40895..ea776a4a 100755 --- a/examples/ad_manager/v201902/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v201911/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201902') + 'UserTeamAssociationService', version='v201911') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v201902') + statement = ad_manager.StatementBuilder(version='v201911') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v201911/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v201911/user_team_association_service/get_user_team_associations_for_user.py index a472f12c..e0a29ab8 100755 --- a/examples/ad_manager/v201902/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v201911/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201902') + 'UserTeamAssociationService', version='v201911') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v201911/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v201911/user_team_association_service/update_user_team_associations.py index ce7cbdd8..9fed6ddf 100755 --- a/examples/ad_manager/v201902/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v201911/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201902') + 'UserTeamAssociationService', version='v201911') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201902') + statement = (ad_manager.StatementBuilder(version='v201911') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 25b8c7cc..9ba6da8d 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,28 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201811': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdRuleService', 'AudienceSegmentService', 'BaseRateService', - 'CdnConfigurationService', 'CompanyService', 'ContactService', - 'ContentBundleService', 'ContentService', 'CreativeService', - 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'DaiAuthenticationKeyService', - 'ExchangeRateService', 'ForecastService', 'InventoryService', - 'LabelService', 'LineItemCreativeAssociationService', - 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardService', - 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'UserService', - 'UserTeamAssociationService', 'WorkflowRequestService'), 'v201902': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', @@ -128,6 +106,22 @@ 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), + 'v201911': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', + 'ContactService', 'ContentBundleService', 'ContentService', + 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', + 'CreativeWrapperService', 'CustomFieldService', + 'CustomTargetingService', 'DaiAuthenticationKeyService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PlacementService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService'), } diff --git a/googleads/common.py b/googleads/common.py index 7cff7ac0..d00aabe7 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '21.0.0' +VERSION = '22.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 86079a22..7ec5afb2 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v201908' +CURRENT_VERSION = 'v201911' class CommonTest(testing.CleanUtilityRegistryTestCase): From 62f0db9fdb78a1bcdb1e61c82c609d9f47cb48d8 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Tue, 5 Nov 2019 16:57:20 -0500 Subject: [PATCH 149/180] Ad Manager v201911 release From f72c1dec30a7bf6a3d89844b205d248e0302f8e6 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Wed, 12 Feb 2020 17:54:46 +0000 Subject: [PATCH 150/180] Ad Manager v202002 release --- ChangeLog | 5 + .../create_product_base_rates.py | 65 ----------- .../create_product_package_item_base_rates.py | 66 ----------- .../create_product_template_base_rates.py | 65 ----------- .../base_rate_service/get_all_base_rates.py | 52 --------- .../get_base_rates_for_rate_card.py | 55 --------- .../base_rate_service/update_base_rates.py | 77 ------------- .../create_exchange_rates.py | 58 ---------- .../get_all_exchange_rates.py | 54 --------- .../get_exchange_rates_for_currency_code.py | 56 --------- .../update_exchange_rates.py | 71 ------------ .../package_service/create_packages.py | 61 ---------- ...reate_proposal_line_items_from_packages.py | 68 ----------- .../package_service/get_all_packages.py | 50 -------- .../get_in_progress_packages.py | 51 -------- .../create_premium_rates.py | 84 -------------- .../get_all_premium_rates.py | 54 --------- .../get_premium_rates_for_rate_card.py | 56 --------- .../update_premium_rates.py | 87 -------------- .../create_product_package_item.py | 62 ---------- .../get_all_product_package_items.py | 53 --------- ...oduct_package_items_for_product_package.py | 56 --------- .../create_product_packages.py | 51 -------- .../get_active_product_packages.py | 52 --------- .../get_all_product_packages.py | 51 -------- .../product_service/get_all_products.py | 49 -------- .../get_products_for_product_template.py | 53 --------- .../product_service/update_products.py | 68 ----------- .../activate_product_templates.py | 74 ------------ .../create_product_templates.py | 109 ------------------ .../create_programmatic_product_templates.py | 91 --------------- .../get_all_product_templates.py | 51 -------- .../get_sponsorship_product_templates.py | 52 --------- .../update_product_templates.py | 94 --------------- .../v201905/rate_card_service/__init__.py | 15 --- .../rate_card_service/create_rate_cards.py | 60 ---------- .../rate_card_service/get_all_rate_cards.py | 51 -------- .../get_marketplace_rate_cards.py | 54 --------- ..._item_reports_for_reconciliation_report.py | 75 ------------ ...update_reconciliation_line_item_reports.py | 67 ----------- ...order_reports_for_reconciliation_report.py | 58 ---------- .../submit_reconciliation_order_reports.py | 71 ------------ ...n_report_rows_for_reconciliation_report.py | 64 ---------- .../update_reconciliation_report_rows.py | 75 ------------ .../get_all_reconciliation_reports.py | 56 --------- ...iliation_report_for_last_billing_period.py | 63 ---------- .../v201905/report_service/__init__.py | 15 --- .../suggested_ad_unit_service/__init__.py | 15 --- .../v201905/team_service/__init__.py | 15 --- .../v201905/user_service/__init__.py | 15 --- .../user_team_association_service/__init__.py | 15 --- .../workflow_request_service/__init__.py | 15 --- .../approve_workflow_approval_requests.py | 75 ------------ .../get_workflow_approval_requests.py | 57 --------- ...et_workflow_external_condition_requests.py | 57 --------- ...er_workflow_external_condition_requests.py | 78 ------------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_traffic_adjustments.py | 4 +- .../get_all_traffic_adjustments.py | 4 +- .../update_traffic_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service}/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service}/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service}/__init__.py | 0 .../content_service/get_all_content.py | 17 ++- .../get_recently_modified_content.py | 66 +++++++++++ .../creative_service}/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service}/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service}/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service}/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service}/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service}/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service}/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service}/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service}/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service}/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service}/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service}/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service}/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 18 +-- .../report_service/run_reach_report.py | 7 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 45 ++------ .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../suggested_ad_unit_service}/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 4 +- .../team_service}/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service}/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 40 +++---- googleads/common.py | 2 +- tests/common_test.py | 2 +- 245 files changed, 389 insertions(+), 3523 deletions(-) delete mode 100755 examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py delete mode 100755 examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py delete mode 100755 examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py delete mode 100755 examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py delete mode 100755 examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py delete mode 100755 examples/ad_manager/v201905/base_rate_service/update_base_rates.py delete mode 100755 examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py delete mode 100755 examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py delete mode 100755 examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py delete mode 100755 examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py delete mode 100755 examples/ad_manager/v201905/package_service/create_packages.py delete mode 100755 examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py delete mode 100755 examples/ad_manager/v201905/package_service/get_all_packages.py delete mode 100755 examples/ad_manager/v201905/package_service/get_in_progress_packages.py delete mode 100755 examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py delete mode 100755 examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py delete mode 100755 examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py delete mode 100755 examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py delete mode 100755 examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py delete mode 100755 examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py delete mode 100755 examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py delete mode 100755 examples/ad_manager/v201905/product_package_service/create_product_packages.py delete mode 100755 examples/ad_manager/v201905/product_package_service/get_active_product_packages.py delete mode 100755 examples/ad_manager/v201905/product_package_service/get_all_product_packages.py delete mode 100755 examples/ad_manager/v201905/product_service/get_all_products.py delete mode 100755 examples/ad_manager/v201905/product_service/get_products_for_product_template.py delete mode 100755 examples/ad_manager/v201905/product_service/update_products.py delete mode 100755 examples/ad_manager/v201905/product_template_service/activate_product_templates.py delete mode 100755 examples/ad_manager/v201905/product_template_service/create_product_templates.py delete mode 100755 examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py delete mode 100755 examples/ad_manager/v201905/product_template_service/get_all_product_templates.py delete mode 100755 examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py delete mode 100755 examples/ad_manager/v201905/product_template_service/update_product_templates.py delete mode 100755 examples/ad_manager/v201905/rate_card_service/__init__.py delete mode 100755 examples/ad_manager/v201905/rate_card_service/create_rate_cards.py delete mode 100755 examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py delete mode 100755 examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py delete mode 100755 examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py delete mode 100755 examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py delete mode 100755 examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py delete mode 100755 examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py delete mode 100755 examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py delete mode 100755 examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py delete mode 100755 examples/ad_manager/v201905/report_service/__init__.py delete mode 100755 examples/ad_manager/v201905/suggested_ad_unit_service/__init__.py delete mode 100755 examples/ad_manager/v201905/team_service/__init__.py delete mode 100755 examples/ad_manager/v201905/user_service/__init__.py delete mode 100755 examples/ad_manager/v201905/user_team_association_service/__init__.py delete mode 100755 examples/ad_manager/v201905/workflow_request_service/__init__.py delete mode 100755 examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py delete mode 100755 examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py delete mode 100755 examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py delete mode 100755 examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py rename examples/ad_manager/{v201905 => v202002}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v201905 => v202002}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v201905 => v202002}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v201905 => v202002}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v201905 => v202002}/activity_service/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v201905 => v202002}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v201905 => v202002}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v201905 => v202002}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v201905 => v202002}/adjustment_service/create_traffic_adjustments.py (99%) rename examples/ad_manager/{v201905 => v202002}/adjustment_service/get_all_traffic_adjustments.py (95%) rename examples/ad_manager/{v201905 => v202002}/adjustment_service/update_traffic_adjustments.py (97%) rename examples/ad_manager/{v201905 => v202002}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v201905 => v202002}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v201905 => v202002}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v201905 => v202002}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v201905 => v202002}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v201905 => v202002}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v201905 => v202002}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v201905 => v202002}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v201905 => v202002}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v201905 => v202002}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v201905/base_rate_service => v202002/company_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/company_service/create_companies.py (99%) rename examples/ad_manager/{v201905 => v202002}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v201905 => v202002}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v201905 => v202002}/company_service/update_companies.py (96%) rename examples/ad_manager/{v201905/company_service => v202002/contact_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v201905 => v202002}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v201905 => v202002}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v201905 => v202002}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v201905/contact_service => v202002/content_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/content_service/get_all_content.py (74%) create mode 100755 examples/ad_manager/v202002/content_service/get_recently_modified_content.py rename examples/ad_manager/{v201905/content_service => v202002/creative_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v201905 => v202002}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v201905 => v202002}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v201905 => v202002}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v201905 => v202002}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v201905 => v202002}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v201905 => v202002}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v201905 => v202002}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v201905/creative_service => v202002/creative_set_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v201905 => v202002}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v201905 => v202002}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v201905 => v202002}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v201905 => v202002}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v201905/creative_set_service => v202002/creative_template_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v201905 => v202002}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v201905 => v202002}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v201905 => v202002}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v201905 => v202002}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v201905 => v202002}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v201905 => v202002}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v201905/creative_template_service => v202002/custom_field_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v201905 => v202002}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v201905 => v202002}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v201905 => v202002}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v201905 => v202002}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v201905 => v202002}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v201905 => v202002}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v201905/custom_field_service => v202002/custom_targeting_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v201905 => v202002}/custom_targeting_service/delete_custom_targeting_keys.py (93%) rename examples/ad_manager/{v201905 => v202002}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v201905 => v202002}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201905 => v202002}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201905 => v202002}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201905 => v202002}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v201905 => v202002}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v201905 => v202002}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v201905 => v202002}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v201905/custom_targeting_service => v202002/inventory_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v201905 => v202002}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v201905 => v202002}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v201905 => v202002}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v201905 => v202002}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v201905 => v202002}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v201905 => v202002}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v201905/exchange_rate_service => v202002/label_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/label_service/create_labels.py (99%) rename examples/ad_manager/{v201905 => v202002}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v201905 => v202002}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v201905 => v202002}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v201905 => v202002}/label_service/update_labels.py (96%) rename examples/ad_manager/{v201905/inventory_service => v202002/line_item_creative_association_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v201905 => v202002}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v201905 => v202002}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v201905 => v202002}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v201905 => v202002}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v201905/label_service => v202002/line_item_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v201905 => v202002}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v201905 => v202002}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v201905 => v202002}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v201905 => v202002}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v201905 => v202002}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v201905 => v202002}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v201905 => v202002}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v201905 => v202002}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v201905/line_item_creative_association_service => v202002/network_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v201905 => v202002}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v201905 => v202002}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v201905/line_item_service => v202002/order_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v201905 => v202002}/order_service/create_orders.py (99%) rename examples/ad_manager/{v201905 => v202002}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v201905 => v202002}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v201905 => v202002}/order_service/update_orders.py (97%) rename examples/ad_manager/{v201905 => v202002}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v201905 => v202002}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v201905 => v202002}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v201905 => v202002}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v201905 => v202002}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v201905/network_service => v202002/proposal_line_item_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v201905 => v202002}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v201905 => v202002}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v201905 => v202002}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v201905 => v202002}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v201905/order_service => v202002/proposal_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v201905 => v202002}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v201905 => v202002}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v201905 => v202002}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v201905 => v202002}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v201905 => v202002}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v201905/premium_rate_service => v202002/publisher_query_language_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v201905 => v202002}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v201905 => v202002}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v201905 => v202002}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v201905 => v202002}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v201905 => v202002}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v201905/product_service => v202002/report_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v201905 => v202002}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v201905 => v202002}/report_service/run_inventory_report.py (74%) rename examples/ad_manager/{v201905 => v202002}/report_service/run_reach_report.py (87%) rename examples/ad_manager/{v201905 => v202002}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v201905 => v202002}/report_service/run_report_with_custom_fields.py (55%) rename examples/ad_manager/{v201905 => v202002}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v201905 => v202002}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v201905/product_template_service => v202002/suggested_ad_unit_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v201905 => v202002}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v201905 => v202002}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v201905 => v202002}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/targeting_preset_service/get_all_targeting_presets.py (94%) rename examples/ad_manager/{v201905/proposal_line_item_service => v202002/team_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/team_service/create_teams.py (96%) rename examples/ad_manager/{v201905 => v202002}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v201905 => v202002}/team_service/update_teams.py (94%) rename examples/ad_manager/{v201905/proposal_service => v202002/user_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/user_service/create_users.py (96%) rename examples/ad_manager/{v201905 => v202002}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v201905 => v202002}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v201905 => v202002}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v201905 => v202002}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v201905 => v202002}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v201905 => v202002}/user_service/update_users.py (92%) rename examples/ad_manager/{v201905/publisher_query_language_service => v202002/user_team_association_service}/__init__.py (100%) rename examples/ad_manager/{v201905 => v202002}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v201905 => v202002}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v201905 => v202002}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v201905 => v202002}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v201905 => v202002}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index 7494d249..f8a58f5b 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +23.0.0 -- 02/11/2020 +* Added support for Ad Manager v202002. +* Removed support for Ad Manager v201902. +* Removed examples for Ad Manager v201905. + 22.0.0 -- 11/05/2019 * Added support for Ad Manager v201911. * Removed support for Ad Manager v201811. diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py deleted file mode 100755 index 44b2f6ea..00000000 --- a/examples/ad_manager/v201905/base_rate_service/create_product_base_rates.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201905') - - # Create a product base rate. - product_base_rate = { - 'xsi_type': 'ProductBaseRate', - # Set the rate card ID that the product base rate belongs to. - 'rateCardId': rate_card_id, - # Set the product id the base rate will be applied to. - 'productId': product_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create the product base rate on the server. - base_rates = base_rate_service.createBaseRates( - [product_base_rate]) - - if base_rates: - for base_rate in base_rates: - print('A product base rate with ID "%s" and rate \'%.2f\' %s was ' - 'created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py deleted file mode 100755 index ddd9a51d..00000000 --- a/examples/ad_manager/v201905/base_rate_service/create_product_package_item_base_rates.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package item base rate. - -To determine which base rates exist, run get_all_base_rates.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the rate card ID to add the base rate to. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - -# Set the product package item to apply this base rate to. -PRODUCT_PACKAGE_ITEM_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201905') - - # Create a base rate for a product package item. - product_package_item_base_rate = { - 'xsi_type': 'ProductPackageItemBaseRate', - # Set the rate card ID that the product package item base rate - # belongs to. - 'rateCardId': RATE_CARD_ID, - # Set the product package item the base rate will be applied to. - 'productPackageItemId': PRODUCT_PACKAGE_ITEM_ID, - # Create a rate worth $2 USD and set that on the product package item - # base rate. - 'rate': { - 'xsi_type': 'Money', - 'currencyCode': 'USD', - 'microAmount': 2000000, - } - } - - # Create the product package item base rate on the server. - result = base_rate_service.createBaseRates([product_package_item_base_rate]) - - for new_base_rate in result: - print('A product package item base rate with ID %d and rate %f %s ' - 'was created.' % (new_base_rate['id'], - new_base_rate['microAmount'], - new_base_rate['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py b/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py deleted file mode 100755 index d56c7463..00000000 --- a/examples/ad_manager/v201905/base_rate_service/create_product_template_base_rates.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product template base rate. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, product_template_id, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService( - 'BaseRateService', version='v201905') - - # Create a product template base rate. - product_template_base_rate = { - 'xsi_type': 'ProductTemplateBaseRate', - # Set the rate card ID that the product template base rate belongs to. - 'rateCardId': rate_card_id, - # Set the product template the base rate will be applied to. - 'productTemplateId': product_template_id, - # Set the rate to be $2. - 'rate': { - 'currencyCode': 'USD', - 'microAmount': 2000000 - } - } - - # Create the product template item base rate on the server. - base_rates = base_rate_service.createBaseRates( - [product_template_base_rate]) - - if base_rates: - for base_rate in base_rates: - print('A product template base rate with ID "%s" and rate \'%.2f\' %s' - ' was created.' % (base_rate['id'], - base_rate['rate']['microAmount'], - base_rate['rate']['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py b/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py deleted file mode 100755 index e463e1c8..00000000 --- a/examples/ad_manager/v201905/base_rate_service/get_all_base_rates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 base rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201905') - - # Create a statement to select base rates. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of base rates at a time, paging - # through until all base rates have been retrieved. - while True: - response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for base_rate in response['results']: - # Print out some information for each base rate. - print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % (base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py b/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py deleted file mode 100755 index 3f875a35..00000000 --- a/examples/ad_manager/v201905/base_rate_service/get_base_rates_for_rate_card.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 base rates belonging to a rate card. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201905') - # Create a statement to select base rates. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('rateCardId = :rateCardId') - .WithBindVariable('rateCardId', rate_card_id)) - - # Retrieve a small amount of base rates at a time, paging - # through until all base rates have been retrieved. - while True: - response = base_rate_service.getBaseRatesByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for base_rate in response['results']: - # Print out some information for each base rate. - print('Base rate with ID "%d", type "%s", and rate card ID "%d" was ' - 'found.\n' % - (base_rate['id'], ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/base_rate_service/update_base_rates.py b/examples/ad_manager/v201905/base_rate_service/update_base_rates.py deleted file mode 100755 index 3f271a2c..00000000 --- a/examples/ad_manager/v201905/base_rate_service/update_base_rates.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a base rate's value. - -To determine which base rates exist, run get_all_base_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -BASE_RATE_ID = 'INSERT_BASE_RATE_ID_HERE' - - -def main(client, base_rate_id): - # Initialize appropriate service. - base_rate_service = client.GetService('BaseRateService', version='v201905') - - # Create a filter statement for base rates for a single rate card. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', int(base_rate_id))) - - # Get single base rate by statement. - response = base_rate_service.getBaseRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local base rate object by changing its value to $3 USD. - new_rate = { - 'currencyCode': 'USD', - 'microAmount': 3000000 - } - - updated_base_rates = [] - for base_rate in response['results']: - base_rate['rate'] = new_rate - updated_base_rates.append(base_rate) - - # Update base rates remotely. - base_rates = base_rate_service.updateBaseRates(updated_base_rates) - - # Display results. - if base_rates: - for base_rate in base_rates: - print('Base rate with ID "%s" and type "%s" belonging to ' - 'rate card ID "%s" was updated.' % ( - base_rate['id'], - ad_manager.AdManagerClassType(base_rate), - base_rate['rateCardId'])) - else: - print('No base rates were updated.') - else: - print('No base rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, BASE_RATE_ID) diff --git a/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py deleted file mode 100755 index eb20f767..00000000 --- a/examples/ad_manager/v201905/exchange_rate_service/create_exchange_rates.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates an exchange rate. - -To determine which exchange rates exist, run get_all_exchange_rates.py. - - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201905') - - # Create a new fixed exchange rate with currency code 'AUD', with direction - # FROM_NETWORK with a value of 1.5. - exchange_rate = { - 'currencyCode': 'AUD', - 'direction': 'FROM_NETWORK', - 'exchangeRate': int(15000000000), - 'refreshRate': 'FIXED' - } - - created_exchange_rate = exchange_rate_service.createExchangeRates( - [exchange_rate])[0] - - print('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was created.' % (created_exchange_rate['id'], - created_exchange_rate['currencyCode'], - created_exchange_rate['direction'], - (float(created_exchange_rate['exchangeRate']) / - 10000000000))) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py deleted file mode 100755 index 74833d08..00000000 --- a/examples/ad_manager/v201905/exchange_rate_service/get_all_exchange_rates.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 exchange rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201905') - - # Create a statement to select exchange rates. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of exchange rates at a time, paging - # through until all exchange rates have been retrieved. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for exchange_rate in response['results']: - # Print out some information for each exchange rate. - print( - 'Exchange rate with ID "%d", currency code "%s", direction "%s", ' - 'and exchange rate "%d" was found.\n' % - (exchange_rate['id'], exchange_rate['currencyCode'], - exchange_rate['direction'], exchange_rate['exchangeRate'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py b/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py deleted file mode 100755 index dc4e41fc..00000000 --- a/examples/ad_manager/v201905/exchange_rate_service/get_exchange_rates_for_currency_code.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the exchange rate for a specific currency code. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client, currency_code): - # Initialize appropriate service. - exchange_rate_service = client.GetService( - 'ExchangeRateService', version='v201905') - # Create a statement to select exchange rates. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('currencyCode = :currencyCode') - .WithBindVariable('currencyCode', currency_code)) - - # Retrieve a small amount of exchange rates at a time, paging - # through until all exchange rates have been retrieved. - while True: - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for exchange_rate in response['results']: - # Print out some information for each exchange rate. - print('Exchange rate with ID "%d", currency code "%s", and exchange ' - 'rate "%.2f" was found.\n' % - (exchange_rate['id'], exchange_rate['currencyCode'], - float(exchange_rate['exchangeRate'] / 1000000))) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, CURRENCY_CODE) diff --git a/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py b/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py deleted file mode 100755 index 4543a5f5..00000000 --- a/examples/ad_manager/v201905/exchange_rate_service/update_exchange_rates.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates the value of an exchange rate. - -To create exchange rates, run create_exchange_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -EXCHANGE_RATE_ID = 'INSERT_EXCHANGE_RATE_ID_HERE' - - -def main(client, exchange_rate_id): - # Initialize appropriate service. - exchange_rate_service = client.GetService('ExchangeRateService', - version='v201905') - - # Create a statement to get an exchange rate by its ID. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .WithBindVariable('id', int(exchange_rate_id)) - .Limit(1)) - - # Get rate cards by statement. - response = exchange_rate_service.getExchangeRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - exchange_rate = response['results'][0] - - # Update the exchange rate value to 1.5. - exchange_rate['exchangeRate'] = int(15000000000) - - exchange_rates = exchange_rate_service.updateExchangeRates([exchange_rate]) - - if exchange_rates: - for exchange_rate in exchange_rates: - print('Exchange rate with id \'%s,\' currency code \'%s,\' ' - 'direction \'%s,\' and exchange rate \'%.2f\' ' - 'was updated.' % (exchange_rate['id'], - exchange_rate['currencyCode'], - exchange_rate['direction'], - (float(exchange_rate['exchangeRate']) / - 10000000000))) - else: - print('No exchange rates were updated.') - else: - print('No exchange rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, EXCHANGE_RATE_ID) diff --git a/examples/ad_manager/v201905/package_service/create_packages.py b/examples/ad_manager/v201905/package_service/create_packages.py deleted file mode 100755 index cea0e81e..00000000 --- a/examples/ad_manager/v201905/package_service/create_packages.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a package. - -To determine which packages exist, run get_all_packages.py. -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the ID of the product package to create the package from. -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - -# Set the ID of the proposal to create proposal line items under. -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - -# Set the ID of the rate card the proposal line items belonging to the product -# package are priced from. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client): - # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201905') - - # Create local package. - package = { - 'name': 'Package #%d' % random.randint(0, 1000000), - 'proposalId': PROPOSAL_ID, - 'productPackageId': PRODUCT_PACKAGE_ID, - 'rateCardId': RATE_CARD_ID, - } - - # Create the package on the server. - result = package_service.createPackages([package]) - - for new_package in result: - print('A package with ID %d and name "%s" was created' % - (new_package['id'], new_package['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py b/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py deleted file mode 100755 index db8b32ae..00000000 --- a/examples/ad_manager/v201905/package_service/create_proposal_line_items_from_packages.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a copy of an image creative. - -To determine which image creatives exist, run get_image_creatives.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the line item to pause. -PACKAGE_ID = 'INSERT_PACKAGE_ID_HERE' - - -def main(client): - # Initialize appropriate service. - package_service = client.GetService('PackageService', version='v201905') - - # Create a statement to select the single package. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', PACKAGE_ID)) - - # Get the package. - query_result = package_service.getPackagesByStatement(statement.ToStatement()) - - package = query_result['results'][0] - - print('Package with ID %d will create proposal line items using product ' - 'package with ID %d.' % (package['id'], - package['productPackageId'])) - - # Remove limit and offset from statement. - statement.limit = None - statement.offset = None - - # Perform update packages action. - result = package_service.performPackageAction( - {'xsi_type': 'CreateProposalLineItemsFromPackages'}, - statement.ToStatement()) - - if result and result['numChanges'] > 0: - print('Number of packages that proposal line items were created for: %d' % - result['numChanges']) - else: - print('No proposal line items were created.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/package_service/get_all_packages.py b/examples/ad_manager/v201905/package_service/get_all_packages.py deleted file mode 100755 index fd515a65..00000000 --- a/examples/ad_manager/v201905/package_service/get_all_packages.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201905') - - # Create a statement to select packages. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of packages at a time, paging - # through until all packages have been retrieved. - while True: - response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for pkg in response['results']: - # Print out some information for each package. - print( - 'Package with ID "%d", name "%s", and proposal id "%d" was found.\n' - % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/package_service/get_in_progress_packages.py b/examples/ad_manager/v201905/package_service/get_in_progress_packages.py deleted file mode 100755 index e7e4ea20..00000000 --- a/examples/ad_manager/v201905/package_service/get_in_progress_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 packages in progress. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - pkg_service = client.GetService('PackageService', version='v201905') - # Create a statement to select packages. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('status = :status') - .WithBindVariable('status', 'IN_PROGRESS')) - - # Retrieve a small amount of packages at a time, paging - # through until all packages have been retrieved. - while True: - response = pkg_service.getPackagesByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for pkg in response['results']: - # Print out some information for each package. - print( - 'Package with ID "%d", name "%s", and proposal ID "%d" was found.\n' - % (pkg['id'], pkg['name'], pkg['proposalId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py deleted file mode 100755 index 4cf8efc8..00000000 --- a/examples/ad_manager/v201905/premium_rate_service/create_premium_rates.py +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example creates new premium_rates. - -To determine which premium_rates exist, run get_all_premium_rates.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate services. - premium_rate_service = client.GetService('PremiumRateService', - version='v201905') - - # Create an ad unit premium to apply to the rate card. - ad_unit_premium_feature = { - 'xsi_type': 'AdUnitPremiumFeature' - } - - # Create a CPC based premium rate value with adjustments in milli amounts. - # This will adjust a CPC priced proposal line item that has - # inventory targeting specified by 10% of the cost associated with the rate - # card (this comes from a percentage adjustment). - cpc_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPC', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Create a CPM based premium rate value with adjustments in micro amounts. - # This will adjust a CPM priced proposal line item that has - # inventory targeting specified by 2 units of the currency associated with - # the rate card (this comes from absolute value adjustment). - cpm_premium_rate_value = { - 'premiumFeature': ad_unit_premium_feature, - 'rateType': 'CPM', - 'adjustmentSize': 2000000, - 'adjustmentType': 'ABSOLUTE_VALUE' - } - - # Create premium rate. - # Associate premium rate with the rate card and set premium information. - # This premium will apply for proposal line items targeting 'any' ad unit - # for both CPM and CPC rate types. - premium_rate = { - 'rateCardId': rate_card_id, - 'pricingMethod': 'ANY_VALUE', - 'premiumFeature': ad_unit_premium_feature, - 'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value] - } - - # Add premium_rates. - premium_rates = premium_rate_service.createPremiumRates([premium_rate]) - - # Display results. - for premium_rate in premium_rates: - print('A premium rate for "%s" was added to the rate card with ID' - ' of "%s".\n' - % (ad_manager.AdManagerClassType(premium_rate['premiumFeature']), - premium_rate['id'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py deleted file mode 100755 index 5b85a494..00000000 --- a/examples/ad_manager/v201905/premium_rate_service/get_all_premium_rates.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 premium rates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - premium_rate_service = client.GetService( - 'PremiumRateService', version='v201905') - - # Create a statement to select premium rates. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of premium rates at a time, paging - # through until all premium rates have been retrieved. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for premium_rate in response['results']: - # Print out some information for each premium rate. - print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'id "%d" was found.\n' % ( - premium_rate['id'], - ad_manager.AdManagerClassType(premium_rate), - premium_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py b/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py deleted file mode 100755 index a7aef244..00000000 --- a/examples/ad_manager/v201905/premium_rate_service/get_premium_rates_for_rate_card.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 premium rates on a specific rate card. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client, rate_card_id): - # Initialize appropriate service. - premium_rate_service = client.GetService( - 'PremiumRateService', version='v201905') - # Create a statement to select premium rates. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('rateCardId = :rateCardId') - .WithBindVariable('rateCardId', rate_card_id)) - - # Retrieve a small amount of premium rates at a time, paging - # through until all premium rates have been retrieved. - while True: - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for premium_rate in response['results']: - # Print out some information for each premium rate. - print('Premium rate with ID "%d", premium feature "%s", and rate card ' - 'ID "%d" was found.\n' % (premium_rate['id'], - premium_rate['premium feature'], - premium_rate['rateCardId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RATE_CARD_ID) diff --git a/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py b/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py deleted file mode 100755 index b56cde27..00000000 --- a/examples/ad_manager/v201905/premium_rate_service/update_premium_rates.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a premium rate to add a flat fee to an existing feature. - -To determine which premium rates exist, run get_all_premium_rates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PREMIUM_RATE_ID = 'INSERT_PREMIUM_RATE_ID_HERE' - - -def main(client, premium_rate_id): - # Initialize appropriate service. - premium_rate_service = client.GetService('PremiumRateService', - version='v201905') - - # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', int(premium_rate_id)) - .Limit(1)) - - # Get the premium rate. - response = premium_rate_service.getPremiumRatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - updated_premium_rates = [] - for premium_rate in response['results']: - # Create a flat fee based premium rate value with a 10% increase. - new_flat_fee_rate = { - 'premiumFeature': premium_rate['premiumFeature'], - 'rateType': 'CPM', - 'adjustmentSize': 10000, - 'adjustmentType': 'PERCENTAGE' - } - - # Update the premium rate's premiumRateValues to include a flat fee - # premium rate. - - existing_premium_rate_value = ( - [] if 'premiumRateValues' not in premium_rate else - premium_rate['premiumRateValues']) - existing_premium_rate_value.append(new_flat_fee_rate) - premium_rate['premiumRateValues'] = existing_premium_rate_value - - updated_premium_rates.append(premium_rate) - - # Update products remotely. - premium_rates = premium_rate_service.updatePremiumRates( - updated_premium_rates) - - # Display results. - if premium_rates: - for premium_rate in premium_rates: - print('Premium rate with ID "%s", associated with rate card id' - ' "%s" was updated.' % (premium_rate['id'], - premium_rate['rateCardId'])) - else: - print('No premium rates were updated.') - else: - print('No premium rates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PREMIUM_RATE_ID) diff --git a/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py b/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py deleted file mode 100755 index b60ed465..00000000 --- a/examples/ad_manager/v201905/product_package_item_service/create_product_package_item.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package item. - -To determine which product package items exist, run -get_all_product_package_items.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the product package to add product package items to. -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - -# Set the ID of the product to generate a product package item from. -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client): - product_package_item_service = client.GetService('ProductPackageItemService', - version='v201905') - - product_package_item = { - # Set the product from which the product package item is created. - 'productId': PRODUCT_ID, - # Set the product package that the product package item belongs to. - 'productPackageId': PRODUCT_PACKAGE_ID, - # Specify if the product package item is required for this - # product package. - 'isMandatory': True - } - - # Create the product package item on the server. - result = product_package_item_service.createProductPackageItems( - [product_package_item]) - - for new_product_package_item in result: - print('A product package with ID %d created from product ID %d ' - 'belonging to product package with ID %d was created.' % - (new_product_package_item['id'], - new_product_package_item['productId'], - new_product_package_item['productPackageId'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py b/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py deleted file mode 100755 index 40656642..00000000 --- a/examples/ad_manager/v201905/product_package_item_service/get_all_product_package_items.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product package items. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201905') - - # Create a statement to select product package items. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of product package items at a time, paging - # through until all product package items have been retrieved. - while True: - response = product_package_item_service.getProductPackageItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package_item in response['results']: - # Print out some information for each product package item. - print('Product package item with ID "%d", product id "%d", and product ' - 'package id "%d" was found.\n' % - (product_package_item['id'], product_package_item['productId'], - product_package_item['productPackageId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py b/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py deleted file mode 100755 index 8726e3bc..00000000 --- a/examples/ad_manager/v201905/product_package_item_service/get_product_package_items_for_product_package.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product package items belonging to a product package. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_PACKAGE_ID = 'INSERT_PRODUCT_PACKAGE_ID_HERE' - - -def main(client, product_package_id): - # Initialize appropriate service. - product_package_item_service = client.GetService( - 'ProductPackageItemService', version='v201905') - # Create a statement to select product package items. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('productPackageId = :productPackageId') - .WithBindVariable('productPackageId', product_package_id)) - - # Retrieve a small amount of product package items at a time, paging - # through until all product package items have been retrieved. - while True: - response = product_package_item_service.getProductPackageItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package_item in response['results']: - # Print out some information for each product package item. - print('Product package item with ID "%d", product ID "%d", and product ' - 'package ID "%d" was found.\n' % - (product_package_item['id'], product_package_item['productId'], - product_package_item['productPackageId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_PACKAGE_ID) diff --git a/examples/ad_manager/v201905/product_package_service/create_product_packages.py b/examples/ad_manager/v201905/product_package_service/create_product_packages.py deleted file mode 100755 index 685c4bfb..00000000 --- a/examples/ad_manager/v201905/product_package_service/create_product_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a product package. - -To determine which product packages exist, run get_all_product_packages.py -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the ID of the rate card to associate with the product package. -RATE_CARD_ID = 'INSERT_RATE_CARD_ID_HERE' - - -def main(client): - product_package_service = client.GetService('ProductPackageService', - version='v201905') - - # Create a local product package. - product_package = { - 'name': 'Product Package #%d' % random.randint(0, 100000000), - 'rateCardIds': [RATE_CARD_ID] - } - - result = product_package_service.createProductPackages([product_package]) - - for new_product_package in result: - print('A product package with ID %d and name "%s" was created.' % - (new_product_package['id'], new_product_package['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py b/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py deleted file mode 100755 index 606fe4b6..00000000 --- a/examples/ad_manager/v201905/product_package_service/get_active_product_packages.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 active product packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_service = client.GetService( - 'ProductPackageService', version='v201905') - # Create a statement to select product packages. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('status = :status') - .WithBindVariable('status', 'ACTIVE')) - - # Retrieve a small amount of product packages at a time, paging - # through until all product packages have been retrieved. - while True: - response = product_package_service.getProductPackagesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package in response['results']: - # Print out some information for each product package. - print('Product package with ID "%d" and name "%s" was found.\n' % - (product_package['id'], product_package['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py b/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py deleted file mode 100755 index ef5a723c..00000000 --- a/examples/ad_manager/v201905/product_package_service/get_all_product_packages.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product packages. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_package_service = client.GetService( - 'ProductPackageService', version='v201905') - - # Create a statement to select product packages. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of product packages at a time, paging - # through until all product packages have been retrieved. - while True: - response = product_package_service.getProductPackagesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_package in response['results']: - # Print out some information for each product package. - print('Product package with ID "%d" and name "%s" was found.\n' % - (product_package['id'], product_package['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_service/get_all_products.py b/examples/ad_manager/v201905/product_service/get_all_products.py deleted file mode 100755 index 6a4ca8ef..00000000 --- a/examples/ad_manager/v201905/product_service/get_all_products.py +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 products. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201905') - - # Create a statement to select products. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of products at a time, paging - # through until all products have been retrieved. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for product in response['results']: - # Print out some information for each product. - print('Product with ID "%d" and name "%s" was found.\n' % - (product['id'], product['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_service/get_products_for_product_template.py b/examples/ad_manager/v201905/product_service/get_products_for_product_template.py deleted file mode 100755 index 48adf096..00000000 --- a/examples/ad_manager/v201905/product_service/get_products_for_product_template.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 products created from a product template. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201905') - - # Create a statement to select products. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('productTemplateId = :productTemplateId') - .WithBindVariable('productTemplateId', product_template_id)) - - # Retrieve a small amount of products at a time, paging - # through until all products have been retrieved. - while True: - response = product_service.getProductsByStatement(statement.ToStatement()) - if 'results' in response and len(response['results']): - for product in response['results']: - # Print out some information for each product. - print('Product with ID "%d" and name "%s" was found.\n' % - (product['id'], product['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201905/product_service/update_products.py b/examples/ad_manager/v201905/product_service/update_products.py deleted file mode 100755 index d2c571ac..00000000 --- a/examples/ad_manager/v201905/product_service/update_products.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a product's notes. - -To determine which products exist, run get_all_products.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_ID = 'INSERT_PRODUCT_ID_HERE' - - -def main(client, product_id): - # Initialize appropriate service. - product_service = client.GetService('ProductService', version='v201905') - - # Create statement object to select a single product by an ID. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .WithBindVariable('id', int(product_id)) - .Limit(1)) - - # Get products by statement. - response = product_service.getProductsByStatement(statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local product object by changing its notes. - updated_products = [] - for product in response['results']: - product['notes'] = 'Product needs further review before activation.' - updated_products.append(product) - - # Update products remotely. - products = product_service.updateProducts(updated_products) - - # Display results. - if products: - for product in products: - print('Product with id "%s", name "%s", and ' - 'notes "%s" was updated.' - % (product['id'], product['name'], product['notes'])) - else: - print('No products were updated.') - else: - print('No products found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_ID) diff --git a/examples/ad_manager/v201905/product_template_service/activate_product_templates.py b/examples/ad_manager/v201905/product_template_service/activate_product_templates.py deleted file mode 100755 index dba227c0..00000000 --- a/examples/ad_manager/v201905/product_template_service/activate_product_templates.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 code example activates a product template. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the id of the product template to activate. -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201905') - - # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .WithBindVariable('id', int(product_template_id)) - .Limit(1)) - - product_templates_activated = 0 - - # Get product_templates by statement. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - print('Product template with id "%s" and name "%s" will be ' - 'activated.' % (product_template['id'], - product_template['name'])) - - # Perform action. - result = product_template_service.performProductTemplateAction( - {'xsi_type': 'ActivateProductTemplates'}, statement.ToStatement()) - if result and int(result['numChanges']) > 0: - product_templates_activated += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if product_templates_activated > 0: - print('Number of product templates ' - 'activated: %s' % product_templates_activated) - else: - print('No product templates were activated.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201905/product_template_service/create_product_templates.py b/examples/ad_manager/v201905/product_template_service/create_product_templates.py deleted file mode 100755 index 99b51466..00000000 --- a/examples/ad_manager/v201905/product_template_service/create_product_templates.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 creates a product template. - -To determine which product templates exist, run get_all_product_templates.py. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201905') - network_service = client.GetService( - 'NetworkService', version='v201905') - - # Create a product template. - product_template = { - 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard proposal line ' - 'items targeting Chrome browsers with product ' - 'segmentation on ad units and geo targeting.'), - 'nameMacro': (' - - ' - ' - '), - 'productType': 'DFP', - 'rateType': 'CPM', - 'roadblockingType': 'ONE_OR_MORE', - 'deliveryRateType': 'AS_FAST_AS_POSSIBLE', - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'lineItemType': 'STANDARD', - 'customizableAttributes': { - 'allowPlacementTargetingCustomization': True, - }, - 'builtInTargeting': { - 'technologyTargeting': { - # Set browser targeting to Chrome. - 'browserTargeting': { - { - 'browsers': [ - { - 'id': '500072' - } - ] - } - } - } - }, - 'productSegmentation': { - 'geoSegment': { - 'targetedLocations': [ - {'id': '2840', - 'displayName': 'US'}, - {'id': '2344', - 'displayName': 'Hong Kong'} - ] - }, - 'adUnitSegments': [{ - 'adUnitId': (network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId']), - 'includeDescendants': 'true' - }] - } - } - - # Create product templates on the server. - product_templates = product_template_service.createProductTemplates( - [product_template]) - - if product_templates: - for product_template in product_templates: - print('A product template with ID "%s" and name "%s" was ' - 'created.' % (product_template['id'], product_template['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py b/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py deleted file mode 100755 index 1c7fcdf1..00000000 --- a/examples/ad_manager/v201905/product_template_service/create_programmatic_product_templates.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 creates a programmatic product template. -""" - -import uuid - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - product_template_service = client.GetService( - 'ProductTemplateService', version='v201905') - network_service = client.GetService( - 'NetworkService', version='v201905') - - product_template = { - # Setting required Marketplace information. - 'productTemplateMarketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for product templates. - 'name': ('Product template #%d' % uuid.uuid4()), - 'description': ('This product template creates standard programmatic' - 'proposal line items targeting all ad units with' - 'product segmentation on geo targeting.'), - 'nameMacro': (' - - ' - ' - '), - 'productType': 'DFP', - 'rateType': 'CPM', - 'creativePlaceholders': [ - { - 'size': { - 'width': '728', - 'height': '90' - } - }, - { - 'size': { - 'width': '300', - 'height': '250' - } - } - ], - 'lineItemType': 'STANDARD', - 'productSegmentation': { - 'geoSegment': { - 'targetedLocations': [ - {'id': '2840', - 'displayName': 'US'}, - {'id': '2344', - 'displayName': 'Hong Kong'} - ] - }, - 'adUnitSegments': [{ - 'adUnitId': (network_service.getCurrentNetwork()[ - 'effectiveRootAdUnitId']), - 'includeDescendants': 'true' - }] - } - } - - product_templates = product_template_service.createProductTemplates( - [product_template]) - - if product_templates: - for product_template in product_templates: - print('A programmatic product template with ID "%s" and name "%s" ' - 'was created.' % (product_template['id'], - product_template['name'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py b/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py deleted file mode 100755 index c354925f..00000000 --- a/examples/ad_manager/v201905/product_template_service/get_all_product_templates.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 product templates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201905') - - # Create a statement to select product templates. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of product templates at a time, paging - # through until all product templates have been retrieved. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - # Print out some information for each product template. - print('Product template with ID "%d" and name "%s" was found.\n' % - (product_template['id'], product_template['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py b/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py deleted file mode 100755 index 8364ceeb..00000000 --- a/examples/ad_manager/v201905/product_template_service/get_sponsorship_product_templates.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 sponsorship product templates. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201905') - # Create a statement to select product templates. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('lineItemType = :lineItemType') - .WithBindVariable('lineItemType', 'SPONSORSHIP')) - - # Retrieve a small amount of product templates at a time, paging - # through until all product templates have been retrieved. - while True: - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for product_template in response['results']: - # Print out some information for each product template. - print('Product template with ID "%d" and name "%s" was found.\n' % - (product_template['id'], product_template['name'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/product_template_service/update_product_templates.py b/examples/ad_manager/v201905/product_template_service/update_product_templates.py deleted file mode 100755 index 8ac48f78..00000000 --- a/examples/ad_manager/v201905/product_template_service/update_product_templates.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 updates a product template's GeoTargeting. - -To determine which product templates exist, run get_all_product_templates.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PRODUCT_TEMPLATE_ID = 'INSERT_PRODUCT_TEMPLATE_ID_HERE' - - -def main(client, product_template_id): - # Initialize appropriate service. - product_template_service = client.GetService( - 'ProductTemplateService', version='v201905') - - # Create a statement to select a single product template by ID. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .OrderBy('id', ascending=True) - .WithBindVariable('id', int(product_template_id)) - .Limit(1)) - - # Get product templates by statement. - response = product_template_service.getProductTemplatesByStatement( - statement.ToStatement()) - - if 'results' in response and len(response['results']): - # Update each local product template object by appending a new geo-target. - for product_template in response['results']: - # Create geo-targeting for Canada to append. - location = { - 'id': '2124', - 'displayName': 'Canada' - } - - try: - targeting = product_template['builtInTargeting'] - - if 'geoTargeting' in targeting: - geo_targeting = targeting['geoTargeting'] - - if 'targetedLocations' in geo_targeting: - geo_targeting['targetedLocations'].append(location) - else: - geo_targeting['targetedLocations'] = [location] - else: - targeting['geoTargeting'] = { - 'targetedLocations': [location] - } - except KeyError: - product_template['builtInTargeting'] = { - 'geoTargeting': { - 'targetedLocations': [location] - } - } - - # Update products remotely. - product_templates = product_template_service.updateProductTemplates( - [product_template]) - - # Display results. - if product_templates: - for product_template in product_templates: - print('Product template with id "%s" and name "%s" was ' - 'updated.' % (product_template['id'], product_template['name'])) - else: - print('No product templates were updated.') - else: - print('No product templates found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PRODUCT_TEMPLATE_ID) diff --git a/examples/ad_manager/v201905/rate_card_service/__init__.py b/examples/ad_manager/v201905/rate_card_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201905/rate_card_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py deleted file mode 100755 index cd10de46..00000000 --- a/examples/ad_manager/v201905/rate_card_service/create_rate_cards.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 creates a new rate card. - -To determine which rate cards exist, run get_all_rate_cards.py. -""" - -# Import appropriate modules from the client library. -import random - -from googleads import ad_manager - -# Set the IDs of the teams this rate card should be visible to. -TEAM_IDS = ['INSERT_TEAM_ID_HERE'] - -# Set the currency code to create the rate card with. -CURRENCY_CODE = 'INSERT_CURRENCY_CODE_HERE' - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201905') - - # Create a rate card. - rate_card = { - 'name': 'RateCard #%d' % random.randint(0, 100000000), - 'currencyCode': CURRENCY_CODE, - 'pricingModel': 'NET', - } - - # This field is optional. - rate_card['appliedTeamIds'] = TEAM_IDS - - result = rate_card_service.createRateCards([rate_card]) - - for new_rate_card in result: - print('A rate card with ID %s, name "%s", and currency code "%s" ' - 'was created.' % (new_rate_card['id'], - new_rate_card['name'], - new_rate_card['currencyCode'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py deleted file mode 100755 index 04a80438..00000000 --- a/examples/ad_manager/v201905/rate_card_service/get_all_rate_cards.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 rate cards. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201905') - - # Create a statement to select rate cards. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of rate cards at a time, paging - # through until all rate cards have been retrieved. - while True: - response = rate_card_service.getRateCardsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for rate_card in response['results']: - # Print out some information for each rate card. - print('Rate card with ID "%d", name "%s", and currency code "%s" was ' - 'found.\n' % - (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py b/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py deleted file mode 100755 index c4020d69..00000000 --- a/examples/ad_manager/v201905/rate_card_service/get_marketplace_rate_cards.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 rate cards that can be used for Marketplace products. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - rate_card_service = client.GetService('RateCardService', version='v201905') - # Create a statement to select rate cards. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('forMarketplace = :forMarketplace') - .WithBindVariable('forMarketplace', True)) - - # Retrieve a small amount of rate cards at a time, paging - # through until all rate cards have been retrieved. - while True: - response = rate_card_service.getRateCardsByStatement(statement.ToStatement( - )) - if 'results' in response and len(response['results']): - for rate_card in response['results']: - # Print out some information for each rate card. - print( - 'Rate card with ID "%d", name "%s", and currency code "%s" was ' - 'found.\n' - % (rate_card['id'], rate_card['name'], rate_card['currencyCode'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py deleted file mode 100755 index 1d003163..00000000 --- a/examples/ad_manager/v201905/reconciliation_line_item_report_service/get_reconciliation_line_item_reports_for_reconciliation_report.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 line item reports for a given reconciliation report. - -To determine how many reconciliation reports exist, -run get_all_reconciliation_reports.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report to query. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201905')) - - # Create a statement to select reconciliation line item reports. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where(('reconciliationReportId = :reconciliationReportId AND ' - 'lineItemId != :lineItemId')) - .OrderBy('lineItemId', ascending=True) - .WithBindVariable('reconciliationReportId', - RECONCILIATION_REPORT_ID) - .WithBindVariable('lineItemId', 0)) - - # Retrieve a small amount of reconciliation line item reports at a time, - # paging through until all reconciliation line item reports have been - # retrieved. - result_set_size = 0 - should_continue = True - - while should_continue: - page = (reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement( - statement.ToStatement())) - if 'results' in page and len(page['results']): - result_set_size += page['totalResultSetSize'] - # Iterate over individual results in the page. - for line_item_report in page['results']: - print('Reconciliation line item report with ID %d, line item ID %d, ' - 'reconciliation source "%s", and reconciled volume %d was ' - 'found.' % (line_item_report['id'], - line_item_report['lineItemId'], - line_item_report['reconciliationSource'], - (line_item_report['reconciledVolume'] - if 'reconciledVolume' in line_item_report else 0))) - # Update statement for next page. - statement.offset += statement.limit - should_continue = statement.offset < result_set_size - - print('Number of results found: %d' % result_set_size) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py b/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py deleted file mode 100755 index 925cdbc6..00000000 --- a/examples/ad_manager/v201905/reconciliation_line_item_report_service/update_reconciliation_line_item_reports.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 updates a reconciliation line item report. - -To get reconciliation line item reports for a reconciliation report, run -get_reconciliation_line_item_reports_for_reconciliation_report.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation line item report to update. -RECONCILIATION_LINE_ITEM_REPORT_ID = 'INSERT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_line_item_report_service = (client.GetService( - 'ReconciliationLineItemReportService', version='v201905')) - - # Create a statement to select a reconciliation line item report. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :lineItemReportId') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('lineItemReportId', - RECONCILIATION_LINE_ITEM_REPORT_ID)) - - # Get reconciliation line item reports by statement. - page = (reconciliation_line_item_report_service - .getReconciliationLineItemReportsByStatement(statement.ToStatement())) - - line_item_report = page['results'][0] - - # Set and use a manual volume for billing. This example splits the difference - # between Ad Manager and the third party volume. - line_item_report['manualVolume'] = (line_item_report['dfpVolume'] + - line_item_report['thirdPartyVolume']) / 2 - line_item_report['reconciliationSource'] = 'MANUAL' - - result = (reconciliation_line_item_report_service - .updateReconciliationLineItemReports([line_item_report])) - - for updated_report in result: - print('Reconciliation line item report with ID %d for line item ID %d was ' - 'updated, with manual volume %d' % (updated_report['id'], - updated_report['lineItemId'], - updated_report['manualVolume'])) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py deleted file mode 100755 index 37494b6f..00000000 --- a/examples/ad_manager/v201905/reconciliation_order_report_service/get_reconciliation_order_reports_for_reconciliation_report.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. -"""Gets all reconciliation order reports for a given reconciliation report. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_order_report_service = client.GetService( - 'ReconciliationOrderReportService', version='v201905') - # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('reconciliationReportId = :reconciliationReportId') - .WithBindVariable('reconciliationReportId', - reconciliation_report_id)) - - # Retrieve a small amount of reconciliation order reports at a time, paging - # through until all reconciliation order reports have been retrieved. - while True: - response = ( - reconciliation_order_report_service - .getReconciliationOrderReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_order_report in response['results']: - # Print out some information for each reconciliation order report. - print('Reconciliation order report with ID "%d" and status "%s" was ' - 'found.\n' % (reconciliation_order_report['id'], - reconciliation_order_report['status'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py b/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py deleted file mode 100755 index 7c46cb83..00000000 --- a/examples/ad_manager/v201905/reconciliation_order_report_service/submit_reconciliation_order_reports.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 submits a reconciliation order report. - -To get all reconciliation order reports for a reconciliation report, -run get get_reconciliation_order_reports_for_reconciliation_report.py. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation order report to submit. -RECONCILIATION_ORDER_REPORT_ID = 'INSERT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_order_report_service = (client.GetService( - 'ReconciliationOrderReportService', version='v201905')) - - # Create a statement to select reconciliation order reports. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('id = :id') - .OrderBy('id', ascending=True) - .Limit(1) - .WithBindVariable('id', RECONCILIATION_ORDER_REPORT_ID)) - - # Get reconciliation order reports by statement. - page = (reconciliation_order_report_service - .getReconciliationOrderReportsByStatement(statement.ToStatement())) - - report = page['results'][0] - - print('Reconciliation order report with ID %d will be submitted.' % - report['id']) - - # Remove limit and offset from statement. - statement.limit = None - statement.offset = None - - # Perform action. - result = (reconciliation_order_report_service - .performReconciliationOrderReportAction( - {'xsi_type': 'SubmitReconciliationOrderReports'}, - statement.ToStatement())) - - if result and result['numChanges'] > 0: - print('Number of reconciliation order reports submitted: %d' % - result['numChanges']) - else: - print('No reconciliation order reports were submitted.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py b/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py deleted file mode 100755 index 3eabadf2..00000000 --- a/examples/ad_manager/v201905/reconciliation_report_row_service/get_reconciliation_report_rows_for_reconciliation_report.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""Gets a reconciliation report's rows for line items that Ad Manager served. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report row. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client, reconciliation_report_id): - # Initialize appropriate service. - reconciliation_report_row_service = client.GetService( - 'ReconciliationReportRowService', version='v201905') - - # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where(('reconciliationReportId = :reportId ' - 'AND lineItemId != :lineItemId')) - .WithBindVariable('lineItemId', 0) - .WithBindVariable('reportId', int(reconciliation_report_id))) - - # Retrieve a small amount of reconciliation report rows at a time, paging - # through until all reconciliation report rows have been retrieved. - while True: - response = ( - reconciliation_report_row_service - .getReconciliationReportRowsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report_row in response['results']: - # Print out some information for each reconciliation report row. - print('Reconciliation report row with ID "%d", reconciliation source ' - '"%s", and reconciled volume "%d" was found.\n' % - (reconciliation_report_row['id'], - reconciliation_report_row['reconciliationSource'], - reconciliation_report_row['reconciledVolume'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, RECONCILIATION_REPORT_ID) diff --git a/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py b/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py deleted file mode 100755 index 545d13d4..00000000 --- a/examples/ad_manager/v201905/reconciliation_report_row_service/update_reconciliation_report_rows.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 updates a reconciliation report row. - -To determine which reconciliation report rows exist, -run get_reconciliation_report_rows_for_reconciliation_report.py -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - -# Set the ID of the reconciliation report row. -RECONCILIATION_REPORT_ROW_ID = 'INSERT_ID_HERE' - -# Set the ID of the reconciliation report. -RECONCILIATION_REPORT_ID = 'INSERT_RECONCILIATION_REPORT_ID_HERE' - - -def main(client): - # Initialize appropriate service. - reconciliation_report_row_service = (client.GetService( - 'ReconciliationReportRowService', version='v201905')) - - # Create a statement to select reconciliation report rows. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where(('id = :reconciliationReportRowId AND ' - 'reconciliationReportId = :reconciliationReportId')) - .OrderBy('id', ascending=True) - .WithBindVariable('reconciliationReportRowId', - RECONCILIATION_REPORT_ROW_ID) - .WithBindVariable('reconciliationReportId', - RECONCILIATION_REPORT_ID)) - - # Get reconciliation report rows by statement. - page = (reconciliation_report_row_service - .getReconciliationReportRowsByStatement(statement.ToStatement())) - - row = page['results'][0] - - # Set a comment on the reconciliation report row. - row['comments'] = ('Third part volume didn\'t match DFP - we agreed to split ' - 'the difference') - - # Set and use a manual volume for billing. - row['manualVolume'] = (row['dfpVolume'] + row['thirdPartyVolume']) / 2 - row['reconciliationSource'] = 'MANUAL' - - updated_rows = (reconciliation_report_row_service - .updateReconciliationReportRows([row])) - - for updated_row in updated_rows: - print('Reconciliation report row for line item ID %d and creative ID %d ' - 'was updated, with manual volume %d' % (updated_row['lineItemId'], - updated_row['creativeId'], - updated_row['manualVolume'])) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py b/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py deleted file mode 100755 index eb1e8d5e..00000000 --- a/examples/ad_manager/v201905/reconciliation_report_service/get_all_reconciliation_reports.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 reconciliation reports. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201905') - - # Create a statement to select reconciliation reports. - statement = ad_manager.StatementBuilder(version='v201905') - - # Retrieve a small amount of reconciliation reports at a time, paging - # through until all reconciliation reports have been retrieved. - while True: - response = ( - reconciliation_report_service - .getReconciliationReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report in response['results']: - # Print out some information for each reconciliation report. - print( - 'Reconciliation report with ID "%d", month "%d", and year "%d" was' - ' found.\n' % (reconciliation_report['id'], - reconciliation_report['startDate']['month'], - reconciliation_report['startDate']['year'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py b/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py deleted file mode 100755 index d9bf4efd..00000000 --- a/examples/ad_manager/v201905/reconciliation_report_service/get_reconciliation_report_for_last_billing_period.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 the previous billing period's reconciliation report. -""" - -# Import appropriate modules from the client library. -from datetime import date -from datetime import timedelta - -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - reconciliation_report_service = client.GetService( - 'ReconciliationReportService', version='v201905') - - first_of_the_month = date.today().replace(day=1) - last_month = first_of_the_month - timedelta(days=1) - - # Create a statement to select reconciliation reports. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('startDate = :startDate') - .WithBindVariable('startDate', last_month)) - - # Retrieve a small amount of reconciliation reports at a time, paging - # through until all reconciliation reports have been retrieved. - while True: - response = ( - reconciliation_report_service - .getReconciliationReportsByStatement( - statement.ToStatement())) - if 'results' in response and len(response['results']): - for reconciliation_report in response['results']: - # Print out some information for each reconciliation report. - print( - 'Reconciliation report with ID "%d" and start date "%s" was found.' - '\n' % (reconciliation_report['id'], - last_month.strftime('%Y-%m-01'))) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/report_service/__init__.py b/examples/ad_manager/v201905/report_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201905/report_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v201905/suggested_ad_unit_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201905/suggested_ad_unit_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/team_service/__init__.py b/examples/ad_manager/v201905/team_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201905/team_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/user_service/__init__.py b/examples/ad_manager/v201905/user_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201905/user_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/user_team_association_service/__init__.py b/examples/ad_manager/v201905/user_team_association_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201905/user_team_association_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/workflow_request_service/__init__.py b/examples/ad_manager/v201905/workflow_request_service/__init__.py deleted file mode 100755 index 3746cd33..00000000 --- a/examples/ad_manager/v201905/workflow_request_service/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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. diff --git a/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py b/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py deleted file mode 100755 index d7a474e3..00000000 --- a/examples/ad_manager/v201905/workflow_request_service/approve_workflow_approval_requests.py +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 approves all workflow approval requests belonging to a proposal. - -To determine which workflow approval requests exist, run -get_all_workflow_approval_requests.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201905') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where(('entityId = :entityId and entityType = :entityType ' - 'and type = :type')) - .WithBindVariable('entityId', proposal_id) - .WithBindVariable('entityType', 'PROPOSAL') - .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) - workflow_approval_requests_approved = 0 - - # Get workflow approval requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for workflow_approval_request in response['results']: - print('Workflow approval request with id "%s" will be' - ' approved.' % workflow_approval_request['id']) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'ApproveWorkflowApprovalRequests', - 'comment': 'This workflow has now been approved for submission.'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_approval_requests_approved += int(result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if workflow_approval_requests_approved > 0: - print('\nNumber of workflow approval requests approved: %s' % - workflow_approval_requests_approved) - else: - print('\nNo workflow approval requests were approved.') - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py b/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py deleted file mode 100755 index e20948b7..00000000 --- a/examples/ad_manager/v201905/workflow_request_service/get_workflow_approval_requests.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 workflow approval requests. - -Workflow approval requests must be approved or rejected for a workflow to -finish. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201905') - # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('type = :type') - .WithBindVariable('type', 'WORKFLOW_APPROVAL_REQUEST')) - - # Retrieve a small amount of workflow requests at a time, paging - # through until all workflow requests have been retrieved. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for workflow_request in response['results']: - # Print out some information for each workflow request. - print('Workflow request with ID "%d", entity type "%s", and entity ID ' - '"%d" was found.\n' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py b/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py deleted file mode 100755 index 96d99976..00000000 --- a/examples/ad_manager/v201905/workflow_request_service/get_workflow_external_condition_requests.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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 workflow external condition requests. - -Workflow external condition requests must be triggered or skipped for a -workflow to finish. -""" - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize appropriate service. - workflow_request_service = client.GetService( - 'WorkflowRequestService', version='v201905') - # Create a statement to select workflow requests. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('type = :type') - .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) - - # Retrieve a small amount of workflow requests at a time, paging - # through until all workflow requests have been retrieved. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - for workflow_request in response['results']: - # Print out some information for each workflow request. - print('Workflow request with ID "%d", entity type "%s", and entity ID ' - '"%d" was found.\n' % (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - statement.offset += statement.limit - else: - break - - print('\nNumber of results found: %s' % response['totalResultSetSize']) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py b/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py deleted file mode 100755 index 5a259bc7..00000000 --- a/examples/ad_manager/v201905/workflow_request_service/trigger_workflow_external_condition_requests.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2015 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 triggers all workflow external condition requests for a proposal. - -Workflow external condition requests must be triggered or skipped for a workflow -to finish. To determine which proposals exist, run get_all_proposals.py. - -""" - - -# Import appropriate modules from the client library. -from googleads import ad_manager - -PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE' - - -def main(client, proposal_id): - # Initialize appropriate service. - workflow_request_service = client.GetService('WorkflowRequestService', - version='v201905') - - # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where(('entityId = :entityId and entityType = :entityType ' - 'and type = :type')) - .WithBindVariable('entityId', proposal_id) - .WithBindVariable('entityType', 'PROPOSAL') - .WithBindVariable('type', 'WORKFLOW_EXTERNAL_CONDITION_REQUEST')) - workflow_external_condition_requests_triggered = 0 - - # Get workflow external condition requests by statement. - while True: - response = workflow_request_service.getWorkflowRequestsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Display results. - for workflow_request in response['results']: - print('Workflow external condition request with id "%s" for %s ' - 'with id "%s" will be triggered.' % - (workflow_request['id'], - workflow_request['entityType'], - workflow_request['entityId'])) - # Perform action. - result = workflow_request_service.performWorkflowRequestAction( - {'xsi_type': 'TriggerWorkflowExternalConditionRequests'}, - statement.ToStatement()) - if result and int(result['numChanges']) > 0: - workflow_external_condition_requests_triggered += int( - result['numChanges']) - statement.offset += statement.limit - else: - break - - # Display results. - if workflow_external_condition_requests_triggered > 0: - print('\nNumber of workflow external condition requests triggered: %s' % - workflow_external_condition_requests_triggered) - else: - print('\nNo workflow external condition requests were triggered.') - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, PROPOSAL_ID) diff --git a/examples/ad_manager/v201905/activity_group_service/__init__.py b/examples/ad_manager/v202002/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/activity_group_service/__init__.py rename to examples/ad_manager/v202002/activity_group_service/__init__.py diff --git a/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202002/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v201905/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202002/activity_group_service/create_activity_groups.py index f7fc003c..6c8b0b78 100755 --- a/examples/ad_manager/v201905/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202002/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201905') + version='v202002') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202002/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202002/activity_group_service/get_active_activity_groups.py index c79463de..630d7aa0 100755 --- a/examples/ad_manager/v201905/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202002/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201905') + 'ActivityGroupService', version='v202002') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202002/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202002/activity_group_service/get_all_activity_groups.py index 1afd9b18..113ff0f1 100755 --- a/examples/ad_manager/v201905/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202002/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201905') + 'ActivityGroupService', version='v202002') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202002/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v201905/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202002/activity_group_service/update_activity_groups.py index a730afb9..5e1e9112 100755 --- a/examples/ad_manager/v201905/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202002/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201905') + version='v202002') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/activity_service/__init__.py b/examples/ad_manager/v202002/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/activity_service/__init__.py rename to examples/ad_manager/v202002/activity_service/__init__.py diff --git a/examples/ad_manager/v201905/activity_service/create_activities.py b/examples/ad_manager/v202002/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v201905/activity_service/create_activities.py rename to examples/ad_manager/v202002/activity_service/create_activities.py index 09bb98df..acce72ca 100755 --- a/examples/ad_manager/v201905/activity_service/create_activities.py +++ b/examples/ad_manager/v202002/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201905') + activity_service = client.GetService('ActivityService', version='v202002') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v201905/activity_service/get_active_activities.py b/examples/ad_manager/v202002/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v201905/activity_service/get_active_activities.py rename to examples/ad_manager/v202002/activity_service/get_active_activities.py index 76564315..51cbb477 100755 --- a/examples/ad_manager/v201905/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202002/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201905') + activity_service = client.GetService('ActivityService', version='v202002') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201905/activity_service/get_all_activities.py b/examples/ad_manager/v202002/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v201905/activity_service/get_all_activities.py rename to examples/ad_manager/v202002/activity_service/get_all_activities.py index 64e75b13..0bc0c4ff 100755 --- a/examples/ad_manager/v201905/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202002/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201905') + activity_service = client.GetService('ActivityService', version='v202002') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201905/activity_service/update_activities.py b/examples/ad_manager/v202002/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v201905/activity_service/update_activities.py rename to examples/ad_manager/v202002/activity_service/update_activities.py index a4ff885e..ca8ecde7 100755 --- a/examples/ad_manager/v201905/activity_service/update_activities.py +++ b/examples/ad_manager/v202002/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201905') + activity_service = client.GetService('ActivityService', version='v202002') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/adjustment_service/create_traffic_adjustments.py b/examples/ad_manager/v202002/adjustment_service/create_traffic_adjustments.py similarity index 99% rename from examples/ad_manager/v201905/adjustment_service/create_traffic_adjustments.py rename to examples/ad_manager/v202002/adjustment_service/create_traffic_adjustments.py index fbf9df5b..2fda5da7 100755 --- a/examples/ad_manager/v201905/adjustment_service/create_traffic_adjustments.py +++ b/examples/ad_manager/v202002/adjustment_service/create_traffic_adjustments.py @@ -27,8 +27,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v201905') - network_service = client.GetService('NetworkService', version='v201905') + adjustment_service = client.GetService('AdjustmentService', version='v202002') + network_service = client.GetService('NetworkService', version='v202002') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201905/adjustment_service/get_all_traffic_adjustments.py b/examples/ad_manager/v202002/adjustment_service/get_all_traffic_adjustments.py similarity index 95% rename from examples/ad_manager/v201905/adjustment_service/get_all_traffic_adjustments.py rename to examples/ad_manager/v202002/adjustment_service/get_all_traffic_adjustments.py index a2340cef..7754fa8a 100755 --- a/examples/ad_manager/v201905/adjustment_service/get_all_traffic_adjustments.py +++ b/examples/ad_manager/v202002/adjustment_service/get_all_traffic_adjustments.py @@ -24,10 +24,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v201905') + adjustment_service = client.GetService('AdjustmentService', version='v202002') # Create a statement to get all forecast traffic adjustments. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small number of traffic adjustments at a time, paging # through until all traffic adjustments have been retrieved. diff --git a/examples/ad_manager/v201905/adjustment_service/update_traffic_adjustments.py b/examples/ad_manager/v202002/adjustment_service/update_traffic_adjustments.py similarity index 97% rename from examples/ad_manager/v201905/adjustment_service/update_traffic_adjustments.py rename to examples/ad_manager/v202002/adjustment_service/update_traffic_adjustments.py index d59b2e2d..706378b7 100755 --- a/examples/ad_manager/v201905/adjustment_service/update_traffic_adjustments.py +++ b/examples/ad_manager/v202002/adjustment_service/update_traffic_adjustments.py @@ -28,12 +28,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v201905') + adjustment_service = client.GetService('AdjustmentService', version='v202002') # Create a statement to select a single traffic forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v201905').Where('id = :id').WithBindVariable( + version='v202002').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast traffic adjustment. diff --git a/examples/ad_manager/v201905/audience_segment_service/__init__.py b/examples/ad_manager/v202002/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/audience_segment_service/__init__.py rename to examples/ad_manager/v202002/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202002/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202002/audience_segment_service/create_audience_segments.py index 63387692..90d8a97b 100755 --- a/examples/ad_manager/v201905/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202002/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201905') - network_service = client.GetService('NetworkService', version='v201905') + 'AudienceSegmentService', version='v202002') + network_service = client.GetService('NetworkService', version='v202002') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202002/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202002/audience_segment_service/get_all_audience_segments.py index 241c21c6..3f6e311a 100755 --- a/examples/ad_manager/v201905/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202002/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201905') + 'AudienceSegmentService', version='v202002') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202002/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202002/audience_segment_service/get_first_party_audience_segments.py index f81ad480..e8b4f705 100755 --- a/examples/ad_manager/v201905/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202002/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201905') + 'AudienceSegmentService', version='v202002') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202002/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202002/audience_segment_service/populate_first_party_audience_segments.py index 7ff56aa8..45c7fdfc 100755 --- a/examples/ad_manager/v201905/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202002/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201905') + 'AudienceSegmentService', version='v202002') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202002/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202002/audience_segment_service/update_audience_segments.py index 40eb0a24..53495a52 100755 --- a/examples/ad_manager/v201905/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202002/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201905') + 'AudienceSegmentService', version='v202002') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201905/cdn_configuration_service/__init__.py b/examples/ad_manager/v202002/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202002/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v201905/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202002/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v201905/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202002/cdn_configuration_service/create_cdn_configurations.py index 51ae1a9d..0f4daf1d 100755 --- a/examples/ad_manager/v201905/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202002/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201905') + version='v202002') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202002/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202002/cdn_configuration_service/get_all_cdn_configurations.py index 4583fcf2..f314f318 100755 --- a/examples/ad_manager/v201905/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202002/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201905') + version='v202002') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_keys.py index 3eaf651b..60f4b8f0 100755 --- a/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201905') + 'CmsMetadataService', version='v202002') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_values.py index 80f3d495..4a0225e0 100755 --- a/examples/ad_manager/v201905/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201905') + 'CmsMetadataService', version='v202002') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v201905/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202002/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v201905/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202002/cms_metadata_service/get_cms_metadata_values_for_key.py index 6c831917..54ff95ed 100755 --- a/examples/ad_manager/v201905/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202002/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201905') + 'CmsMetadataService', version='v202002') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v201905').Where( + ad_manager.StatementBuilder(version='v202002').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v201905/base_rate_service/__init__.py b/examples/ad_manager/v202002/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/base_rate_service/__init__.py rename to examples/ad_manager/v202002/company_service/__init__.py diff --git a/examples/ad_manager/v201905/company_service/create_companies.py b/examples/ad_manager/v202002/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v201905/company_service/create_companies.py rename to examples/ad_manager/v202002/company_service/create_companies.py index 164f76a4..6d95315f 100755 --- a/examples/ad_manager/v201905/company_service/create_companies.py +++ b/examples/ad_manager/v202002/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201905') + company_service = client.GetService('CompanyService', version='v202002') # Create company objects. companies = [ diff --git a/examples/ad_manager/v201905/company_service/get_advertisers.py b/examples/ad_manager/v202002/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v201905/company_service/get_advertisers.py rename to examples/ad_manager/v202002/company_service/get_advertisers.py index aa4debac..3b2afae6 100755 --- a/examples/ad_manager/v201905/company_service/get_advertisers.py +++ b/examples/ad_manager/v202002/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201905') + company_service = client.GetService('CompanyService', version='v202002') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201905/company_service/get_all_companies.py b/examples/ad_manager/v202002/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v201905/company_service/get_all_companies.py rename to examples/ad_manager/v202002/company_service/get_all_companies.py index 96957d13..c382d43e 100755 --- a/examples/ad_manager/v201905/company_service/get_all_companies.py +++ b/examples/ad_manager/v202002/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201905') + company_service = client.GetService('CompanyService', version='v202002') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201905/company_service/update_companies.py b/examples/ad_manager/v202002/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v201905/company_service/update_companies.py rename to examples/ad_manager/v202002/company_service/update_companies.py index 5fb90287..1871d8b9 100755 --- a/examples/ad_manager/v201905/company_service/update_companies.py +++ b/examples/ad_manager/v202002/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201905') + company_service = client.GetService('CompanyService', version='v202002') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/company_service/__init__.py b/examples/ad_manager/v202002/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/company_service/__init__.py rename to examples/ad_manager/v202002/contact_service/__init__.py diff --git a/examples/ad_manager/v201905/contact_service/create_contacts.py b/examples/ad_manager/v202002/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v201905/contact_service/create_contacts.py rename to examples/ad_manager/v202002/contact_service/create_contacts.py index 1f9ffcdc..6c571086 100755 --- a/examples/ad_manager/v201905/contact_service/create_contacts.py +++ b/examples/ad_manager/v202002/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201905') + contact_service = client.GetService('ContactService', version='v202002') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v201905/contact_service/get_all_contacts.py b/examples/ad_manager/v202002/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v201905/contact_service/get_all_contacts.py rename to examples/ad_manager/v202002/contact_service/get_all_contacts.py index 10a04a34..92b9cc7a 100755 --- a/examples/ad_manager/v201905/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202002/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201905') + contact_service = client.GetService('ContactService', version='v202002') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202002/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202002/contact_service/get_uninvited_contacts.py index 0daf28f9..4a978586 100755 --- a/examples/ad_manager/v201905/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202002/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201905') + contact_service = client.GetService('ContactService', version='v202002') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201905/contact_service/update_contacts.py b/examples/ad_manager/v202002/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v201905/contact_service/update_contacts.py rename to examples/ad_manager/v202002/contact_service/update_contacts.py index 309187c7..a4155af3 100755 --- a/examples/ad_manager/v201905/contact_service/update_contacts.py +++ b/examples/ad_manager/v202002/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201905') + contact_service = client.GetService('ContactService', version='v202002') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/contact_service/__init__.py b/examples/ad_manager/v202002/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/contact_service/__init__.py rename to examples/ad_manager/v202002/content_service/__init__.py diff --git a/examples/ad_manager/v201905/content_service/get_all_content.py b/examples/ad_manager/v202002/content_service/get_all_content.py similarity index 74% rename from examples/ad_manager/v201905/content_service/get_all_content.py rename to examples/ad_manager/v202002/content_service/get_all_content.py index bcc07cae..4427bea8 100755 --- a/examples/ad_manager/v201905/content_service/get_all_content.py +++ b/examples/ad_manager/v202002/content_service/get_all_content.py @@ -13,8 +13,8 @@ # 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 content. -""" + +"""This example gets all content.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201905') + content_service = client.GetService('ContentService', version='v202002') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -34,8 +34,13 @@ def main(client): if 'results' in response and len(response['results']): for content in response['results']: # Print out some information for each content. - print('Content with ID "%d" and name "%s" was found.\n' % - (content['id'], content['name'].encode('utf-8'))) + content_description = ('Content with ID "%d" and name "%s"' % + (content['id'], content['name'].encode('utf-8'))) + if content['contentBundleIds']: + content_description += (' belonging to bundle IDs %s' % + content['contentBundleIds']) + content_description += ' was found.' + print(content_description) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v202002/content_service/get_recently_modified_content.py b/examples/ad_manager/v202002/content_service/get_recently_modified_content.py new file mode 100755 index 00000000..a932e1a5 --- /dev/null +++ b/examples/ad_manager/v202002/content_service/get_recently_modified_content.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 recently modified content.""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import ad_manager +import pytz + + +def main(client): + # Initialize appropriate service. + content_service = client.GetService('ContentService', version='v202002') + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + + # Create a statement to get recently modified content based on + # lastModifiedDateTime. Changes to content bundle associations will update + # the lastModifiedDateTime, but CMS metadata changes may not change the + # lastModifiedDateTime. + statement = (ad_manager.StatementBuilder(version='v202002') + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) + + # Retrieve a small amount of content at a time, paging + # through until all content have been retrieved. + while True: + response = content_service.getContentByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for content in response['results']: + # Print out some information for each content. + content_description = ('Content with ID "%d" and name "%s"' % + (content['id'], content['name'].encode('utf-8'))) + if content['contentBundleIds']: + content_description += (' belonging to bundle IDs %s' % + content['contentBundleIds']) + content_description += ' was found.' + print(content_description) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201905/content_service/__init__.py b/examples/ad_manager/v202002/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/content_service/__init__.py rename to examples/ad_manager/v202002/creative_service/__init__.py diff --git a/examples/ad_manager/v201905/creative_service/copy_image_creatives.py b/examples/ad_manager/v202002/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v201905/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202002/creative_service/copy_image_creatives.py index c2632691..297fc700 100755 --- a/examples/ad_manager/v201905/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202002/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201905') + creative_service = client.GetService('CreativeService', version='v202002') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201905/creative_service/create_creative_from_template.py b/examples/ad_manager/v202002/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v201905/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202002/creative_service/create_creative_from_template.py index 1f4ec854..3a6c49b1 100755 --- a/examples/ad_manager/v201905/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202002/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201905') + creative_service = client.GetService('CreativeService', version='v202002') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v201905/creative_service/create_creatives.py b/examples/ad_manager/v202002/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v201905/creative_service/create_creatives.py rename to examples/ad_manager/v202002/creative_service/create_creatives.py index 15846afd..809f511c 100755 --- a/examples/ad_manager/v201905/creative_service/create_creatives.py +++ b/examples/ad_manager/v202002/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201905') + creative_service = client.GetService('CreativeService', version='v202002') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v201905/creative_service/create_custom_creative.py b/examples/ad_manager/v202002/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v201905/creative_service/create_custom_creative.py rename to examples/ad_manager/v202002/creative_service/create_custom_creative.py index 3c7d24e6..0b9b1930 100755 --- a/examples/ad_manager/v201905/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202002/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201905') + creative_service = client.GetService('CreativeService', version='v202002') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v201905/creative_service/create_native_creative.py b/examples/ad_manager/v202002/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v201905/creative_service/create_native_creative.py rename to examples/ad_manager/v202002/creative_service/create_native_creative.py index e9686e61..3410aba8 100755 --- a/examples/ad_manager/v201905/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202002/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201905') + creative_service = client.GetService('CreativeService', version='v202002') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v201905/creative_service/get_all_creatives.py b/examples/ad_manager/v202002/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v201905/creative_service/get_all_creatives.py rename to examples/ad_manager/v202002/creative_service/get_all_creatives.py index 3556f670..99deeb1c 100755 --- a/examples/ad_manager/v201905/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202002/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201905') + creative_service = client.GetService('CreativeService', version='v202002') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201905/creative_service/get_image_creatives.py b/examples/ad_manager/v202002/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v201905/creative_service/get_image_creatives.py rename to examples/ad_manager/v202002/creative_service/get_image_creatives.py index 2da94eaa..ae686a75 100755 --- a/examples/ad_manager/v201905/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202002/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201905') + creative_service = client.GetService('CreativeService', version='v202002') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201905/creative_service/update_creatives.py b/examples/ad_manager/v202002/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v201905/creative_service/update_creatives.py rename to examples/ad_manager/v202002/creative_service/update_creatives.py index 16ac522d..d87f699a 100755 --- a/examples/ad_manager/v201905/creative_service/update_creatives.py +++ b/examples/ad_manager/v202002/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201905') + creative_service = client.GetService('CreativeService', version='v202002') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v201905/creative_service/__init__.py b/examples/ad_manager/v202002/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/creative_service/__init__.py rename to examples/ad_manager/v202002/creative_set_service/__init__.py diff --git a/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202002/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202002/creative_set_service/associate_creative_set_to_line_item.py index cf629306..79dfcfc3 100755 --- a/examples/ad_manager/v201905/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202002/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201905') + 'LineItemCreativeAssociationService', version='v202002') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v201905/creative_set_service/create_creative_set.py b/examples/ad_manager/v202002/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v201905/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202002/creative_set_service/create_creative_set.py index 731e3353..6dd22736 100755 --- a/examples/ad_manager/v201905/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202002/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201905') + version='v202002') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202002/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202002/creative_set_service/get_all_creative_sets.py index 1a7afa26..3b0474ea 100755 --- a/examples/ad_manager/v201905/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202002/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201905') + 'CreativeSetService', version='v202002') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202002/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202002/creative_set_service/get_creative_sets_for_master_creative.py index a2b576fd..566e64d4 100755 --- a/examples/ad_manager/v201905/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202002/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201905') + 'CreativeSetService', version='v202002') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201905/creative_set_service/update_creative_set.py b/examples/ad_manager/v202002/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v201905/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202002/creative_set_service/update_creative_set.py index 68f9b35e..6cb4d599 100755 --- a/examples/ad_manager/v201905/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202002/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201905') + version='v202002') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v201905/creative_set_service/__init__.py b/examples/ad_manager/v202002/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/creative_set_service/__init__.py rename to examples/ad_manager/v202002/creative_template_service/__init__.py diff --git a/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202002/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202002/creative_template_service/get_all_creative_templates.py index 5c26c5fd..3e9a539c 100755 --- a/examples/ad_manager/v201905/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202002/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201905') + 'CreativeTemplateService', version='v202002') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202002/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202002/creative_template_service/get_system_defined_creative_templates.py index 6e637cee..c6000a01 100755 --- a/examples/ad_manager/v201905/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202002/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201905') + 'CreativeTemplateService', version='v202002') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202002/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202002/creative_wrapper_service/create_creative_wrappers.py index 50ec10f8..a0c9f685 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202002/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201905') + version='v202002') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202002/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202002/creative_wrapper_service/deactivate_creative_wrapper.py index 87d6c5cf..816de014 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202002/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201905') + version='v202002') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202002/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202002/creative_wrapper_service/get_active_creative_wrappers.py index 5ede2feb..a24ee551 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202002/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201905') + 'CreativeWrapperService', version='v202002') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202002/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202002/creative_wrapper_service/get_all_creative_wrappers.py index 729d4e23..d5bb244a 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202002/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201905') + 'CreativeWrapperService', version='v202002') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202002/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202002/creative_wrapper_service/update_creative_wrappers.py index 6e6fc56d..f67d8aeb 100755 --- a/examples/ad_manager/v201905/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202002/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201905') + version='v202002') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v201905/creative_template_service/__init__.py b/examples/ad_manager/v202002/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/creative_template_service/__init__.py rename to examples/ad_manager/v202002/custom_field_service/__init__.py diff --git a/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202002/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202002/custom_field_service/create_custom_field_options.py index 930d0e6e..42ec0012 100755 --- a/examples/ad_manager/v201905/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202002/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201905') + 'CustomFieldService', version='v202002') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202002/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v201905/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202002/custom_field_service/create_custom_fields.py index 54f65d27..bc59ad59 100755 --- a/examples/ad_manager/v201905/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202002/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201905') + 'CustomFieldService', version='v202002') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202002/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202002/custom_field_service/deactivate_all_line_item_custom_fields.py index 956d5adf..69012a46 100755 --- a/examples/ad_manager/v201905/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202002/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201905') + 'CustomFieldService', version='v202002') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202002/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202002/custom_field_service/get_all_custom_fields.py index 4a4e7935..ca0d75f8 100755 --- a/examples/ad_manager/v201905/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202002/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201905') + 'CustomFieldService', version='v202002') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202002/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202002/custom_field_service/get_custom_fields_for_line_items.py index fb07534b..6039b524 100755 --- a/examples/ad_manager/v201905/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202002/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201905') + 'CustomFieldService', version='v202002') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202002/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202002/custom_field_service/set_line_item_custom_field_value.py index 0c95fb98..a9edc764 100755 --- a/examples/ad_manager/v201905/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202002/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201905') + 'CustomFieldService', version='v202002') - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v201905') + custom_field_statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v201905') + ad_manager.StatementBuilder(version='v202002') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v201905') + line_item_statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202002/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v201905/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202002/custom_field_service/update_custom_fields.py index a37a71f1..4b71431a 100755 --- a/examples/ad_manager/v201905/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202002/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201905') + 'CustomFieldService', version='v202002') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v201905/custom_field_service/__init__.py b/examples/ad_manager/v202002/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/custom_field_service/__init__.py rename to examples/ad_manager/v202002/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202002/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202002/custom_targeting_service/create_custom_targeting_keys_and_values.py index e2e20793..0a76102f 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202002/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201905') + 'CustomTargetingService', version='v202002') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_keys.py similarity index 93% rename from examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_keys.py index 946d8140..4fd4c98b 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201905') + 'CustomTargetingService', version='v202002') - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v201905') + key_statement = (ad_manager.StatementBuilder(version='v202002') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_values.py index 3bd945e2..b5ae7465 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201905') + 'CustomTargetingService', version='v202002') - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v201905') + value_statement = (ad_manager.StatementBuilder(version='v202002') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202002/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202002/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 8f66776c..5723a964 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202002/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201905') + 'CustomTargetingService', version='v202002') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v201905') + targeting_key_statement = ad_manager.StatementBuilder(version='v202002') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202002/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202002/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 2a4e3c6b..45e353b5 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202002/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201905') + 'CustomTargetingService', version='v202002') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v201905') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202002') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_keys.py index d2e94d82..a5676167 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201905') + 'CustomTargetingService', version='v202002') - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_values.py index 1798a0da..3f07c4a0 100755 --- a/examples/ad_manager/v201905/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201905') + 'CustomTargetingService', version='v202002') - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202002/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v201905/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202002/forecast_service/get_availability_forecast.py index 6e5ce768..f550f3c8 100755 --- a/examples/ad_manager/v201905/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202002/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201905') - network_service = client.GetService('NetworkService', version='v201905') + forecast_service = client.GetService('ForecastService', version='v202002') + network_service = client.GetService('NetworkService', version='v202002') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202002/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202002/forecast_service/get_availability_forecast_for_line_item.py index 75736005..688f8500 100755 --- a/examples/ad_manager/v201905/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202002/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201905') + forecast_service = client.GetService('ForecastService', version='v202002') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202002/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202002/forecast_service/get_delivery_forecast_for_line_items.py index 1c6f7546..18c1a127 100755 --- a/examples/ad_manager/v201905/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202002/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201905') + forecast_service = client.GetService('ForecastService', version='v202002') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v201905/custom_targeting_service/__init__.py b/examples/ad_manager/v202002/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/custom_targeting_service/__init__.py rename to examples/ad_manager/v202002/inventory_service/__init__.py diff --git a/examples/ad_manager/v201905/inventory_service/archive_ad_units.py b/examples/ad_manager/v202002/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v201905/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202002/inventory_service/archive_ad_units.py index eff00728..e32aac8f 100755 --- a/examples/ad_manager/v201905/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202002/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201905') + inventory_service = client.GetService('InventoryService', version='v202002') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v201905/inventory_service/create_ad_units.py b/examples/ad_manager/v202002/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v201905/inventory_service/create_ad_units.py rename to examples/ad_manager/v202002/inventory_service/create_ad_units.py index bef24f34..c647915f 100755 --- a/examples/ad_manager/v201905/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202002/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201905') + inventory_service = client.GetService('InventoryService', version='v202002') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202002/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202002/inventory_service/get_ad_unit_hierarchy.py index a273d85b..51de4ae5 100755 --- a/examples/ad_manager/v201905/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202002/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201905') - inventory_service = client.GetService('InventoryService', version='v201905') + network_service = client.GetService('NetworkService', version='v202002') + inventory_service = client.GetService('InventoryService', version='v202002') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201905/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202002/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v201905/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202002/inventory_service/get_all_ad_unit_sizes.py index 22266555..a712d67f 100755 --- a/examples/ad_manager/v201905/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202002/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201905') + 'InventoryService', version='v202002') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202002/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v201905/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202002/inventory_service/get_all_ad_units.py index 092188d8..62580bb6 100755 --- a/examples/ad_manager/v201905/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202002/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201905') + ad_unit_service = client.GetService('InventoryService', version='v202002') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202002/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202002/inventory_service/get_top_level_ad_units.py index b0721ece..8fc0c935 100755 --- a/examples/ad_manager/v201905/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202002/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201905') - inventory_service = client.GetService('InventoryService', version='v201905') + network_service = client.GetService('NetworkService', version='v202002') + inventory_service = client.GetService('InventoryService', version='v202002') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201905/inventory_service/update_ad_units.py b/examples/ad_manager/v202002/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v201905/inventory_service/update_ad_units.py rename to examples/ad_manager/v202002/inventory_service/update_ad_units.py index ef0fc2ba..5a851802 100755 --- a/examples/ad_manager/v201905/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202002/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201905') + inventory_service = client.GetService('InventoryService', version='v202002') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201905/exchange_rate_service/__init__.py b/examples/ad_manager/v202002/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/exchange_rate_service/__init__.py rename to examples/ad_manager/v202002/label_service/__init__.py diff --git a/examples/ad_manager/v201905/label_service/create_labels.py b/examples/ad_manager/v202002/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v201905/label_service/create_labels.py rename to examples/ad_manager/v202002/label_service/create_labels.py index 67752860..773b258b 100755 --- a/examples/ad_manager/v201905/label_service/create_labels.py +++ b/examples/ad_manager/v202002/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201905') + label_service = client.GetService('LabelService', version='v202002') # Create label objects. labels = [] diff --git a/examples/ad_manager/v201905/label_service/deactivate_labels.py b/examples/ad_manager/v202002/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v201905/label_service/deactivate_labels.py rename to examples/ad_manager/v202002/label_service/deactivate_labels.py index 8734115c..19810e9c 100755 --- a/examples/ad_manager/v201905/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202002/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201905') + label_service = client.GetService('LabelService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201905/label_service/get_active_labels.py b/examples/ad_manager/v202002/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v201905/label_service/get_active_labels.py rename to examples/ad_manager/v202002/label_service/get_active_labels.py index 28b308ef..a45a8f9c 100755 --- a/examples/ad_manager/v201905/label_service/get_active_labels.py +++ b/examples/ad_manager/v202002/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201905') + label_service = client.GetService('LabelService', version='v202002') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201905/label_service/get_all_labels.py b/examples/ad_manager/v202002/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v201905/label_service/get_all_labels.py rename to examples/ad_manager/v202002/label_service/get_all_labels.py index e93d2a71..04c20c1b 100755 --- a/examples/ad_manager/v201905/label_service/get_all_labels.py +++ b/examples/ad_manager/v202002/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201905') + label_service = client.GetService('LabelService', version='v202002') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201905/label_service/update_labels.py b/examples/ad_manager/v202002/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v201905/label_service/update_labels.py rename to examples/ad_manager/v202002/label_service/update_labels.py index 33a30358..d1ca89f0 100755 --- a/examples/ad_manager/v201905/label_service/update_labels.py +++ b/examples/ad_manager/v202002/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201905') + label_service = client.GetService('LabelService', version='v202002') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201905/inventory_service/__init__.py b/examples/ad_manager/v202002/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/inventory_service/__init__.py rename to examples/ad_manager/v202002/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202002/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202002/line_item_creative_association_service/create_licas.py index 0b092f00..209f089e 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202002/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201905') + 'LineItemCreativeAssociationService', version='v202002') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202002/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202002/line_item_creative_association_service/deactivate_licas.py index 984ee9ab..de1567b2 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202002/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201905') + 'LineItemCreativeAssociationService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202002/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202002/line_item_creative_association_service/get_all_licas.py index 6920c2c8..0d88e4d7 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202002/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201905') + 'LineItemCreativeAssociationService', version='v202002') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202002/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202002/line_item_creative_association_service/get_licas_for_line_item.py index 894048c6..ef314207 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202002/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201905') + 'LineItemCreativeAssociationService', version='v202002') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202002/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202002/line_item_creative_association_service/update_licas.py index 95254f4e..6a6799ca 100755 --- a/examples/ad_manager/v201905/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202002/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201905') + 'LineItemCreativeAssociationService', version='v202002') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201905/label_service/__init__.py b/examples/ad_manager/v202002/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/label_service/__init__.py rename to examples/ad_manager/v202002/line_item_service/__init__.py diff --git a/examples/ad_manager/v201905/line_item_service/activate_line_items.py b/examples/ad_manager/v202002/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v201905/line_item_service/activate_line_items.py rename to examples/ad_manager/v202002/line_item_service/activate_line_items.py index 9c6017d3..efe30d02 100755 --- a/examples/ad_manager/v201905/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202002/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201905/line_item_service/create_line_items.py b/examples/ad_manager/v202002/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v201905/line_item_service/create_line_items.py rename to examples/ad_manager/v202002/line_item_service/create_line_items.py index 9fbecedb..613f041a 100755 --- a/examples/ad_manager/v201905/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202002/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201905/line_item_service/create_video_line_item.py b/examples/ad_manager/v202002/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v201905/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202002/line_item_service/create_video_line_item.py index 4af42345..6566364b 100755 --- a/examples/ad_manager/v201905/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202002/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201905/line_item_service/get_all_line_items.py b/examples/ad_manager/v202002/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v201905/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202002/line_item_service/get_all_line_items.py index b5e4d5c2..cc6dd6d7 100755 --- a/examples/ad_manager/v201905/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202002/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202002/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202002/line_item_service/get_line_items_that_need_creatives.py index 6c983f95..a1ab3d55 100755 --- a/examples/ad_manager/v201905/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202002/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202002/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202002/line_item_service/get_recently_updated_line_items.py index 3b19d5fc..f64dea08 100755 --- a/examples/ad_manager/v201905/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202002/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201905/line_item_service/pause_line_items.py b/examples/ad_manager/v202002/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v201905/line_item_service/pause_line_items.py rename to examples/ad_manager/v202002/line_item_service/pause_line_items.py index 83a023b3..1b9466bb 100755 --- a/examples/ad_manager/v201905/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202002/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202002/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v201905/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202002/line_item_service/target_custom_criteria.py index 41659293..8ea8c72f 100755 --- a/examples/ad_manager/v201905/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202002/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/line_item_service/update_line_items.py b/examples/ad_manager/v202002/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v201905/line_item_service/update_line_items.py rename to examples/ad_manager/v202002/line_item_service/update_line_items.py index d89d0e8c..e90133ea 100755 --- a/examples/ad_manager/v201905/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202002/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') + line_item_service = client.GetService('LineItemService', version='v202002') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202002/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202002/live_stream_event_service/activate_live_stream_events.py index e9f564e4..16e75350 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202002/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201905') + 'LiveStreamEventService', version='v202002') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201905/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202002/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v201905/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202002/live_stream_event_service/create_live_stream_events.py index 3e35ea6b..6862e2e9 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202002/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201905') + 'LiveStreamEventService', version='v202002') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202002/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202002/live_stream_event_service/get_all_live_stream_events.py index d43833b3..3a0c1f03 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202002/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201905') + 'LiveStreamEventService', version='v202002') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202002/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202002/live_stream_event_service/register_sessions_for_monitoring.py index f3a11d93..bb96a8e2 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202002/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201905') + 'LiveStreamEventService', version='v202002') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202002/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202002/live_stream_event_service/update_live_stream_events.py index d2159231..b5d9fc57 100755 --- a/examples/ad_manager/v201905/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202002/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201905') + 'LiveStreamEventService', version='v202002') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201905/native_style_service/__init__.py b/examples/ad_manager/v202002/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/native_style_service/__init__.py rename to examples/ad_manager/v202002/native_style_service/__init__.py diff --git a/examples/ad_manager/v201905/native_style_service/create_native_styles.py b/examples/ad_manager/v202002/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v201905/native_style_service/create_native_styles.py rename to examples/ad_manager/v202002/native_style_service/create_native_styles.py index 81c5f804..b8d533af 100755 --- a/examples/ad_manager/v201905/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202002/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201905') + version='v202002') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202002/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v201905/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202002/native_style_service/get_all_native_styles.py index 4f0f2956..31215249 100755 --- a/examples/ad_manager/v201905/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202002/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201905') + version='v202002') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201905/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202002/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202002/network_service/__init__.py diff --git a/examples/ad_manager/v201905/network_service/get_all_networks.py b/examples/ad_manager/v202002/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v201905/network_service/get_all_networks.py rename to examples/ad_manager/v202002/network_service/get_all_networks.py index 79d9750b..dba8aa0e 100755 --- a/examples/ad_manager/v201905/network_service/get_all_networks.py +++ b/examples/ad_manager/v202002/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201905') + network_service = client.GetService('NetworkService', version='v202002') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v201905/network_service/get_current_network.py b/examples/ad_manager/v202002/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v201905/network_service/get_current_network.py rename to examples/ad_manager/v202002/network_service/get_current_network.py index 99d190e0..cd4f3955 100755 --- a/examples/ad_manager/v201905/network_service/get_current_network.py +++ b/examples/ad_manager/v202002/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201905') + network_service = client.GetService('NetworkService', version='v202002') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201905/network_service/make_test_network.py b/examples/ad_manager/v202002/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v201905/network_service/make_test_network.py rename to examples/ad_manager/v202002/network_service/make_test_network.py index f754b4df..e0f4cf6c 100755 --- a/examples/ad_manager/v201905/network_service/make_test_network.py +++ b/examples/ad_manager/v202002/network_service/make_test_network.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201905') + network_service = client.GetService('NetworkService', version='v202002') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v201905/line_item_service/__init__.py b/examples/ad_manager/v202002/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/line_item_service/__init__.py rename to examples/ad_manager/v202002/order_service/__init__.py diff --git a/examples/ad_manager/v201905/order_service/approve_orders.py b/examples/ad_manager/v202002/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v201905/order_service/approve_orders.py rename to examples/ad_manager/v202002/order_service/approve_orders.py index 2c53d896..ab903647 100755 --- a/examples/ad_manager/v201905/order_service/approve_orders.py +++ b/examples/ad_manager/v202002/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201905') + order_service = client.GetService('OrderService', version='v202002') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201905/order_service/create_orders.py b/examples/ad_manager/v202002/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v201905/order_service/create_orders.py rename to examples/ad_manager/v202002/order_service/create_orders.py index 6cf1a59e..2521568a 100755 --- a/examples/ad_manager/v201905/order_service/create_orders.py +++ b/examples/ad_manager/v202002/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201905') + order_service = client.GetService('OrderService', version='v202002') # Create order objects. orders = [] diff --git a/examples/ad_manager/v201905/order_service/get_all_orders.py b/examples/ad_manager/v202002/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v201905/order_service/get_all_orders.py rename to examples/ad_manager/v202002/order_service/get_all_orders.py index d44761de..f1ead8ea 100755 --- a/examples/ad_manager/v201905/order_service/get_all_orders.py +++ b/examples/ad_manager/v202002/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201905') + order_service = client.GetService('OrderService', version='v202002') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202002/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v201905/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202002/order_service/get_orders_starting_soon.py index 37dac560..36e29d80 100755 --- a/examples/ad_manager/v201905/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202002/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201905') + order_service = client.GetService('OrderService', version='v202002') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201905/order_service/update_orders.py b/examples/ad_manager/v202002/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v201905/order_service/update_orders.py rename to examples/ad_manager/v202002/order_service/update_orders.py index f3554405..3638a12e 100755 --- a/examples/ad_manager/v201905/order_service/update_orders.py +++ b/examples/ad_manager/v202002/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201905') + order_service = client.GetService('OrderService', version='v202002') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201905/placement_service/create_placements.py b/examples/ad_manager/v202002/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v201905/placement_service/create_placements.py rename to examples/ad_manager/v202002/placement_service/create_placements.py index 25987a82..5083b1d3 100755 --- a/examples/ad_manager/v201905/placement_service/create_placements.py +++ b/examples/ad_manager/v202002/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201905') - inventory_service = client.GetService('InventoryService', version='v201905') + placement_service = client.GetService('PlacementService', version='v202002') + inventory_service = client.GetService('InventoryService', version='v202002') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201905/placement_service/deactivate_placements.py b/examples/ad_manager/v202002/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v201905/placement_service/deactivate_placements.py rename to examples/ad_manager/v202002/placement_service/deactivate_placements.py index e0c5869b..b932df93 100755 --- a/examples/ad_manager/v201905/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202002/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201905') + placement_service = client.GetService('PlacementService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/placement_service/get_active_placements.py b/examples/ad_manager/v202002/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v201905/placement_service/get_active_placements.py rename to examples/ad_manager/v202002/placement_service/get_active_placements.py index 5373373b..f3736225 100755 --- a/examples/ad_manager/v201905/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202002/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201905') + placement_service = client.GetService('PlacementService', version='v202002') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201905/placement_service/get_all_placements.py b/examples/ad_manager/v202002/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v201905/placement_service/get_all_placements.py rename to examples/ad_manager/v202002/placement_service/get_all_placements.py index 7652add1..014a663c 100755 --- a/examples/ad_manager/v201905/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202002/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201905') + placement_service = client.GetService('PlacementService', version='v202002') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201905/placement_service/update_placements.py b/examples/ad_manager/v202002/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v201905/placement_service/update_placements.py rename to examples/ad_manager/v202002/placement_service/update_placements.py index a3f4aa7f..2eb8c93e 100755 --- a/examples/ad_manager/v201905/placement_service/update_placements.py +++ b/examples/ad_manager/v202002/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201905') + placement_service = client.GetService('PlacementService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201905/network_service/__init__.py b/examples/ad_manager/v202002/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/network_service/__init__.py rename to examples/ad_manager/v202002/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202002/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202002/proposal_line_item_service/archive_proposal_line_items.py index 9ce652bf..69cb78a7 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202002/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201905') + 'ProposalLineItemService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202002/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202002/proposal_line_item_service/create_proposal_line_items.py index 3a92b420..64903d6d 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202002/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201905') - network_service = client.GetService('NetworkService', version='v201905') + 'ProposalLineItemService', version='v202002') + network_service = client.GetService('NetworkService', version='v202002') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202002/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202002/proposal_line_item_service/get_all_proposal_line_items.py index 68d23ed9..a22588ab 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202002/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201905') + 'ProposalLineItemService', version='v202002') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202002/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202002/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 1e3168bc..2a8b4bb7 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202002/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201905') + 'ProposalLineItemService', version='v202002') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202002/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202002/proposal_line_item_service/update_proposal_line_items.py index f1114575..8b1125f1 100755 --- a/examples/ad_manager/v201905/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202002/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201905') + 'ProposalLineItemService', version='v202002') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/order_service/__init__.py b/examples/ad_manager/v202002/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/order_service/__init__.py rename to examples/ad_manager/v202002/proposal_service/__init__.py diff --git a/examples/ad_manager/v201905/proposal_service/create_proposals.py b/examples/ad_manager/v202002/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v201905/proposal_service/create_proposals.py rename to examples/ad_manager/v202002/proposal_service/create_proposals.py index 1b8b5e0d..1a0ef031 100755 --- a/examples/ad_manager/v201905/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202002/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201905') + proposal_service = client.GetService('ProposalService', version='v202002') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201905/proposal_service/get_all_proposals.py b/examples/ad_manager/v202002/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v201905/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202002/proposal_service/get_all_proposals.py index f891d591..7f65989f 100755 --- a/examples/ad_manager/v201905/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202002/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201905') + proposal_service = client.GetService('ProposalService', version='v202002') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202002/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202002/proposal_service/get_marketplace_comments.py index 93194a1d..58dda26e 100755 --- a/examples/ad_manager/v201905/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202002/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201905') + 'ProposalService', version='v202002') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v201905/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202002/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v201905/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202002/proposal_service/get_proposals_awaiting_seller_review.py index 8f096ad1..9349fb99 100755 --- a/examples/ad_manager/v201905/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202002/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201905') + proposal_service = client.GetService('ProposalService', version='v202002') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202002/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202002/proposal_service/request_buyers_acceptance.py index b7de144a..72a18ffd 100755 --- a/examples/ad_manager/v201905/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202002/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201905') + proposal_service = client.GetService('ProposalService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201905/proposal_service/update_proposals.py b/examples/ad_manager/v202002/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v201905/proposal_service/update_proposals.py rename to examples/ad_manager/v202002/proposal_service/update_proposals.py index 48701056..5945f354 100755 --- a/examples/ad_manager/v201905/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202002/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201905') + proposal_service = client.GetService('ProposalService', version='v202002') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/premium_rate_service/__init__.py b/examples/ad_manager/v202002/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/premium_rate_service/__init__.py rename to examples/ad_manager/v202002/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202002/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202002/publisher_query_language_service/fetch_match_tables.py index 68c6707a..693be107 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202002/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202002/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202002/publisher_query_language_service/get_all_browsers.py index 23f51b7e..8c52551f 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202002/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202002/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202002/publisher_query_language_service/get_all_programmatic_buyers.py index 2e70aa63..1a1f19d3 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202002/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201905') + data_downloader = client.GetDataDownloader(version='v202002') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202002/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202002/publisher_query_language_service/get_geo_targets.py index 3b5a9df0..8d1e3622 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202002/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202002/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202002/publisher_query_language_service/get_line_items_named_like.py index fdec7c7c..2169f460 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202002/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202002/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202002/publisher_query_language_service/get_recent_changes.py index 2f442c08..f6fb7e4d 100755 --- a/examples/ad_manager/v201905/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202002/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201905') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202002') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v201905/product_service/__init__.py b/examples/ad_manager/v202002/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/product_service/__init__.py rename to examples/ad_manager/v202002/report_service/__init__.py diff --git a/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202002/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v201905/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202002/report_service/run_ad_exchange_report.py index 64704452..9480cc76 100755 --- a/examples/ad_manager/v201905/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202002/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') # Create report job. report_job = { diff --git a/examples/ad_manager/v201905/report_service/run_delivery_report.py b/examples/ad_manager/v202002/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v201905/report_service/run_delivery_report.py rename to examples/ad_manager/v202002/report_service/run_delivery_report.py index dd6d6d88..676ceb35 100755 --- a/examples/ad_manager/v201905/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202002/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201905/report_service/run_inventory_report.py b/examples/ad_manager/v202002/report_service/run_inventory_report.py similarity index 74% rename from examples/ad_manager/v201905/report_service/run_inventory_report.py rename to examples/ad_manager/v202002/report_service/run_inventory_report.py index 046f7c19..a0875307 100755 --- a/examples/ad_manager/v201905/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202002/report_service/run_inventory_report.py @@ -24,21 +24,8 @@ def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201905') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201905') - - # Get root ad unit id for network. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') - .WithBindVariable('parentAdUnitId', int(root_ad_unit_id)) - .Limit(None) # No limit or offset for reports - .Offset(None)) + report_downloader = client.GetDataDownloader(version='v202002') # Create report job. report_job = { @@ -50,8 +37,7 @@ def main(client): 'ADSENSE_LINE_ITEM_LEVEL_CLICKS', 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'], - 'dateRangeType': 'LAST_WEEK', - 'statement': statement.ToStatement() + 'dateRangeType': 'LAST_WEEK' } } diff --git a/examples/ad_manager/v201905/report_service/run_reach_report.py b/examples/ad_manager/v202002/report_service/run_reach_report.py similarity index 87% rename from examples/ad_manager/v201905/report_service/run_reach_report.py rename to examples/ad_manager/v202002/report_service/run_reach_report.py index a5bebcdc..93da683d 100755 --- a/examples/ad_manager/v201905/report_service/run_reach_report.py +++ b/examples/ad_manager/v202002/report_service/run_reach_report.py @@ -25,13 +25,14 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') # Create report job. report_job = { 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'], + 'dimensions': ['COUNTRY_NAME', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS', + 'UNIQUE_REACH'], 'dateRangeType': 'REACH_LIFETIME' } } diff --git a/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202002/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202002/report_service/run_report_and_create_match_table.py index 5b8ee8e2..a7698738 100755 --- a/examples/ad_manager/v201905/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202002/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202002/report_service/run_report_with_custom_fields.py similarity index 55% rename from examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202002/report_service/run_report_with_custom_fields.py index 0c04a6ac..f85544c4 100755 --- a/examples/ad_manager/v201905/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202002/report_service/run_report_with_custom_fields.py @@ -22,51 +22,22 @@ from googleads import ad_manager from googleads import errors -# Set the ID of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' +CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID' +CUSTOM_DIMENSION_KEY_ID = 'INSERT_CUSTOM_DIMENSION_KEY_ID' -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201905') +def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201905') - - # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder(version='v201905') - .Where('orderId = :orderId') - .WithBindVariable('orderId', int(order_id))) - - # Collect all line item custom field IDs for an order. - custom_field_ids = set() - - # Get users by statement. - while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Get custom field IDs from the line items of an order. - for line_item in response['results']: - if 'customFieldValues' in line_item: - for custom_field_value in line_item['customFieldValues']: - custom_field_ids.add(custom_field_value['customFieldId']) - statement.offset += statement.limit - else: - break - - # Modify statement for reports - statement.limit = None - statement.offset = None - statement.Where('ORDER_ID = :orderId') + report_downloader = client.GetDataDownloader(version='v202002') # Create report job. report_job = { 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': statement.ToStatement(), + 'dimensions': ['CUSTOM_DIMENSION', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'], 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', - 'customFieldIds': list(custom_field_ids) + 'customFieldIds': [custom_field_id], + 'customDimensionKeyIds': [custom_dimension_key_id] } } @@ -94,4 +65,4 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID) + main(ad_manager_client, CUSTOM_FIELD_ID, CUSTOM_DIMENSION_KEY_ID) diff --git a/examples/ad_manager/v201905/report_service/run_sales_report.py b/examples/ad_manager/v202002/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v201905/report_service/run_sales_report.py rename to examples/ad_manager/v202002/report_service/run_sales_report.py index c5a1f92d..2e8455aa 100755 --- a/examples/ad_manager/v201905/report_service/run_sales_report.py +++ b/examples/ad_manager/v202002/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') # Create report job. report_job = { diff --git a/examples/ad_manager/v201905/report_service/run_saved_query.py b/examples/ad_manager/v202002/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v201905/report_service/run_saved_query.py rename to examples/ad_manager/v202002/report_service/run_saved_query.py index 5887e589..8f6eebeb 100755 --- a/examples/ad_manager/v201905/report_service/run_saved_query.py +++ b/examples/ad_manager/v202002/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201905') + report_service = client.GetService('ReportService', version='v202002') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201905') + report_downloader = client.GetDataDownloader(version='v202002') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v201905/product_template_service/__init__.py b/examples/ad_manager/v202002/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/product_template_service/__init__.py rename to examples/ad_manager/v202002/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202002/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202002/suggested_ad_unit_service/approve_all_suggested_ad_units.py index dbd02daa..f18ba547 100755 --- a/examples/ad_manager/v201905/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202002/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201905') + 'SuggestedAdUnitService', version='v202002') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202002/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202002/suggested_ad_unit_service/get_all_suggested_ad_units.py index fb32e663..1d9d5e23 100755 --- a/examples/ad_manager/v201905/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202002/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201905') + 'SuggestedAdUnitService', version='v202002') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202002/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202002/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index b45342a0..3ce64b96 100755 --- a/examples/ad_manager/v201905/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202002/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201905') + 'SuggestedAdUnitService', version='v202002') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v201905/targeting_preset_service/__init__.py b/examples/ad_manager/v202002/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/targeting_preset_service/__init__.py rename to examples/ad_manager/v202002/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py similarity index 94% rename from examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py index 8aa78dc3..3d909168 100755 --- a/examples/ad_manager/v201905/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v201905') + 'TargetingPresetService', version='v202002') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. diff --git a/examples/ad_manager/v201905/proposal_line_item_service/__init__.py b/examples/ad_manager/v202002/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202002/team_service/__init__.py diff --git a/examples/ad_manager/v201905/team_service/create_teams.py b/examples/ad_manager/v202002/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v201905/team_service/create_teams.py rename to examples/ad_manager/v202002/team_service/create_teams.py index b13a4a01..05cec83c 100755 --- a/examples/ad_manager/v201905/team_service/create_teams.py +++ b/examples/ad_manager/v202002/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201905') + team_service = client.GetService('TeamService', version='v202002') # Create team objects. teams = [] diff --git a/examples/ad_manager/v201905/team_service/get_all_teams.py b/examples/ad_manager/v202002/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v201905/team_service/get_all_teams.py rename to examples/ad_manager/v202002/team_service/get_all_teams.py index 04f664f5..5019f015 100755 --- a/examples/ad_manager/v201905/team_service/get_all_teams.py +++ b/examples/ad_manager/v202002/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201905') + team_service = client.GetService('TeamService', version='v202002') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201905/team_service/update_teams.py b/examples/ad_manager/v202002/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v201905/team_service/update_teams.py rename to examples/ad_manager/v202002/team_service/update_teams.py index 6874c209..5b9fc791 100755 --- a/examples/ad_manager/v201905/team_service/update_teams.py +++ b/examples/ad_manager/v202002/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201905') + team_service = client.GetService('TeamService', version='v202002') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v201905/proposal_service/__init__.py b/examples/ad_manager/v202002/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/proposal_service/__init__.py rename to examples/ad_manager/v202002/user_service/__init__.py diff --git a/examples/ad_manager/v201905/user_service/create_users.py b/examples/ad_manager/v202002/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v201905/user_service/create_users.py rename to examples/ad_manager/v202002/user_service/create_users.py index fc3a8abe..2d1db15c 100755 --- a/examples/ad_manager/v201905/user_service/create_users.py +++ b/examples/ad_manager/v202002/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v202002') # Create user objects. users = [ diff --git a/examples/ad_manager/v201905/user_service/deactivate_users.py b/examples/ad_manager/v202002/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v201905/user_service/deactivate_users.py rename to examples/ad_manager/v202002/user_service/deactivate_users.py index e0dee995..c1452334 100755 --- a/examples/ad_manager/v201905/user_service/deactivate_users.py +++ b/examples/ad_manager/v202002/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201905/user_service/get_all_roles.py b/examples/ad_manager/v202002/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v201905/user_service/get_all_roles.py rename to examples/ad_manager/v202002/user_service/get_all_roles.py index 38cfc420..8f140009 100755 --- a/examples/ad_manager/v201905/user_service/get_all_roles.py +++ b/examples/ad_manager/v202002/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v202002') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v201905/user_service/get_all_users.py b/examples/ad_manager/v202002/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v201905/user_service/get_all_users.py rename to examples/ad_manager/v202002/user_service/get_all_users.py index e7f6f731..9a9f707e 100755 --- a/examples/ad_manager/v201905/user_service/get_all_users.py +++ b/examples/ad_manager/v202002/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v202002') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201905/user_service/get_current_user.py b/examples/ad_manager/v202002/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v201905/user_service/get_current_user.py rename to examples/ad_manager/v202002/user_service/get_current_user.py index e9683c7a..4b61986f 100755 --- a/examples/ad_manager/v201905/user_service/get_current_user.py +++ b/examples/ad_manager/v202002/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v202002') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v201905/user_service/get_user_by_email_address.py b/examples/ad_manager/v202002/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v201905/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202002/user_service/get_user_by_email_address.py index 60be4a0a..4fd3a25d 100755 --- a/examples/ad_manager/v201905/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202002/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v202002') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201905/user_service/update_users.py b/examples/ad_manager/v202002/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v201905/user_service/update_users.py rename to examples/ad_manager/v202002/user_service/update_users.py index 4f9096af..35a347ac 100755 --- a/examples/ad_manager/v201905/user_service/update_users.py +++ b/examples/ad_manager/v202002/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201905') + user_service = client.GetService('UserService', version='v202002') # Create query. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201905/publisher_query_language_service/__init__.py b/examples/ad_manager/v202002/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201905/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202002/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202002/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202002/user_team_association_service/create_user_team_associations.py index ebb8bea4..401166f8 100755 --- a/examples/ad_manager/v201905/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202002/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201905') + 'UserTeamAssociationService', version='v202002') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202002/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202002/user_team_association_service/delete_user_team_associations.py index 51c42213..dacd0e6d 100755 --- a/examples/ad_manager/v201905/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202002/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201905') + 'UserTeamAssociationService', version='v202002') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202002/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202002/user_team_association_service/get_all_user_team_associations.py index cd3f6d52..9b18e010 100755 --- a/examples/ad_manager/v201905/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202002/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201905') + 'UserTeamAssociationService', version='v202002') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v201905') + statement = ad_manager.StatementBuilder(version='v202002') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202002/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202002/user_team_association_service/get_user_team_associations_for_user.py index 96919d90..e0d9f81f 100755 --- a/examples/ad_manager/v201905/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202002/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201905') + 'UserTeamAssociationService', version='v202002') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202002/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202002/user_team_association_service/update_user_team_associations.py index ea5416c7..a6f04c01 100755 --- a/examples/ad_manager/v201905/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202002/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201905') + 'UserTeamAssociationService', version='v202002') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201905') + statement = (ad_manager.StatementBuilder(version='v202002') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 9ba6da8d..d236bc0c 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,29 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201902': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'BaseRateService', 'CdnConfigurationService', 'CmsMetadataService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'ExchangeRateService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardService', - 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'UserService', - 'UserTeamAssociationService', 'WorkflowRequestService'), 'v201905': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', @@ -122,6 +99,23 @@ 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), + 'v202002': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', + 'ContactService', 'ContentBundleService', 'ContentReviewService', + 'ContentService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'ForecastService', 'InventoryService', + 'LabelService', 'LineItemCreativeAssociationService', + 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PlacementService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', + 'StreamActivityMonitorService', 'SuggestedAdUnitService', + 'TeamService', 'TargetingPresetService', 'UserService', + 'UserTeamAssociationService'), } diff --git a/googleads/common.py b/googleads/common.py index d00aabe7..44742013 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '22.0.0' +VERSION = '23.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 7ec5afb2..44d67cd1 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v201911' +CURRENT_VERSION = 'v202002' class CommonTest(testing.CleanUtilityRegistryTestCase): From dfec701fe4e3efd0fb8d9e14ad80c603b5f2b89e Mon Sep 17 00:00:00 2001 From: David Wihl Date: Wed, 12 Feb 2020 17:56:43 +0000 Subject: [PATCH 151/180] Commiting latest changes. From 4f7e60200b3d5fc44ddfb2c22460545124d825ab Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 5 Mar 2020 14:52:46 -0500 Subject: [PATCH 152/180] Minor patch to Ad Manager V202002 release --- ChangeLog | 3 +++ googleads/ad_manager.py | 4 ++-- googleads/common.py | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/ChangeLog b/ChangeLog index f8a58f5b..b1f32e38 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +23.0.1 -- 02/20/2020 +* Fixed name of 'CreativeReviewService'. + 23.0.0 -- 02/11/2020 * Added support for Ad Manager v202002. * Removed support for Ad Manager v201902. diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index d236bc0c..b0ebd153 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -103,8 +103,8 @@ ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', - 'ContactService', 'ContentBundleService', 'ContentReviewService', - 'ContentService', 'CreativeService', 'CreativeSetService', + 'ContactService', 'ContentBundleService', 'ContentService', + 'CreativeReviewService', 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', 'CreativeWrapperService', 'CustomFieldService', 'CustomTargetingService', 'DaiAuthenticationKeyService', 'ForecastService', 'InventoryService', diff --git a/googleads/common.py b/googleads/common.py index 44742013..ae054321 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '23.0.0' +VERSION = '23.0.1' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' From baaeb3979c16508ec106bda9adc86770a013e90d Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 5 Mar 2020 14:53:58 -0500 Subject: [PATCH 153/180] Commiting latest changes. From 41c17a88eabcac092592421a85c322132bf7e666 Mon Sep 17 00:00:00 2001 From: Richard Cotrina Date: Thu, 7 May 2020 11:03:15 -0500 Subject: [PATCH 154/180] Update get_all_targeting_presets.py (#460) --- .../targeting_preset_service/get_all_targeting_presets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py index 3d909168..fcb10ffc 100755 --- a/examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py @@ -37,7 +37,7 @@ def main(client): for targeting_preset in response['results']: # Print out some information for each targeting preset. print( - 'Targeting preset with ID "%s" and name "%d" was found.\n' + 'Targeting preset with ID "%d" and name "%s" was found.\n' % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: From 34b15f69719310d4de67a45207c1e7db4994e7fc Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 14 May 2020 16:42:17 -0400 Subject: [PATCH 155/180] Ad Manager v202005 release --- ChangeLog | 5 + .../create_traffic_adjustments.py | 143 ------------------ .../update_traffic_adjustments.py | 88 ----------- .../get_all_targeting_presets.py | 2 +- .../get_all_targeting_presets.py | 2 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 65 ++++++++ .../create_traffic_forecast_segments.py | 72 +++++++++ .../get_all_forecast_adjustments.py} | 27 ++-- .../get_all_traffic_forecast_segments.py | 51 +++++++ ...djustments_for_traffic_forecast_segment.py | 57 +++++++ .../update_forecast_adjustments.py | 64 ++++++++ .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 70 +++++++++ .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 17 ++- .../get_recently_modified_content.py | 66 ++++++++ .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 18 +-- .../report_service/run_reach_report.py | 7 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 45 +----- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 52 +++++++ .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 40 +++-- googleads/common.py | 2 +- tests/common_test.py | 2 +- 198 files changed, 827 insertions(+), 600 deletions(-) delete mode 100755 examples/ad_manager/v201908/adjustment_service/create_traffic_adjustments.py delete mode 100755 examples/ad_manager/v201908/adjustment_service/update_traffic_adjustments.py rename examples/ad_manager/{v201908 => v202005}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v201908 => v202005}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v201908 => v202005}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v201908 => v202005}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v201908 => v202005}/activity_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v201908 => v202005}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v201908 => v202005}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v201908 => v202005}/activity_service/update_activities.py (96%) create mode 100755 examples/ad_manager/v202005/adjustment_service/create_forecast_adjustments.py create mode 100755 examples/ad_manager/v202005/adjustment_service/create_traffic_forecast_segments.py rename examples/ad_manager/{v201908/adjustment_service/get_all_traffic_adjustments.py => v202005/adjustment_service/get_all_forecast_adjustments.py} (63%) create mode 100755 examples/ad_manager/v202005/adjustment_service/get_all_traffic_forecast_segments.py create mode 100755 examples/ad_manager/v202005/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py create mode 100755 examples/ad_manager/v202005/adjustment_service/update_forecast_adjustments.py rename examples/ad_manager/{v201908 => v202005}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v201908 => v202005}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v201908 => v202005}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v201908 => v202005}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v201908 => v202005}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v201908 => v202005}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v201908 => v202005}/cdn_configuration_service/get_all_cdn_configurations.py (93%) create mode 100755 examples/ad_manager/v202005/cms_metadata_service/activate_cms_metadata_values.py rename examples/ad_manager/{v201908 => v202005}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v201908 => v202005}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v201908 => v202005}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v201908 => v202005}/company_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/company_service/create_companies.py (99%) rename examples/ad_manager/{v201908 => v202005}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v201908 => v202005}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v201908 => v202005}/company_service/update_companies.py (96%) rename examples/ad_manager/{v201908 => v202005}/contact_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v201908 => v202005}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v201908 => v202005}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v201908 => v202005}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v201908 => v202005}/content_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/content_service/get_all_content.py (74%) create mode 100755 examples/ad_manager/v202005/content_service/get_recently_modified_content.py rename examples/ad_manager/{v201908 => v202005}/creative_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v201908 => v202005}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v201908 => v202005}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v201908 => v202005}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v201908 => v202005}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v201908 => v202005}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v201908 => v202005}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v201908 => v202005}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v201908 => v202005}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v201908 => v202005}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v201908 => v202005}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v201908 => v202005}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v201908 => v202005}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v201908 => v202005}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v201908 => v202005}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v201908 => v202005}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v201908 => v202005}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v201908 => v202005}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v201908 => v202005}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v201908 => v202005}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v201908 => v202005}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v201908 => v202005}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v201908 => v202005}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v201908 => v202005}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v201908 => v202005}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v201908 => v202005}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v201908 => v202005}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v201908 => v202005}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v201908 => v202005}/custom_targeting_service/delete_custom_targeting_keys.py (93%) rename examples/ad_manager/{v201908 => v202005}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v201908 => v202005}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201908 => v202005}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201908 => v202005}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201908 => v202005}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v201908 => v202005}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v201908 => v202005}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v201908 => v202005}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v201908 => v202005}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v201908 => v202005}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v201908 => v202005}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v201908 => v202005}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v201908 => v202005}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v201908 => v202005}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v201908 => v202005}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v201908 => v202005}/label_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/label_service/create_labels.py (99%) rename examples/ad_manager/{v201908 => v202005}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v201908 => v202005}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v201908 => v202005}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v201908 => v202005}/label_service/update_labels.py (96%) rename examples/ad_manager/{v201908 => v202005}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v201908 => v202005}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v201908 => v202005}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v201908 => v202005}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v201908 => v202005}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v201908 => v202005}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v201908 => v202005}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v201908 => v202005}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v201908 => v202005}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v201908 => v202005}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v201908 => v202005}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v201908 => v202005}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v201908 => v202005}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v201908 => v202005}/network_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v201908 => v202005}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v201908 => v202005}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v201908 => v202005}/order_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v201908 => v202005}/order_service/create_orders.py (99%) rename examples/ad_manager/{v201908 => v202005}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v201908 => v202005}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v201908 => v202005}/order_service/update_orders.py (97%) rename examples/ad_manager/{v201908 => v202005}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v201908 => v202005}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v201908 => v202005}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v201908 => v202005}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v201908 => v202005}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v201908 => v202005}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v201908 => v202005}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v201908 => v202005}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v201908 => v202005}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v201908 => v202005}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v201908 => v202005}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v201908 => v202005}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v201908 => v202005}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v201908 => v202005}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v201908 => v202005}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v201908 => v202005}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v201908 => v202005}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v201908 => v202005}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v201908 => v202005}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v201908 => v202005}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v201908 => v202005}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v201908 => v202005}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v201908 => v202005}/report_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v201908 => v202005}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v201908 => v202005}/report_service/run_inventory_report.py (74%) rename examples/ad_manager/{v201908 => v202005}/report_service/run_reach_report.py (87%) rename examples/ad_manager/{v201908 => v202005}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v201908 => v202005}/report_service/run_report_with_custom_fields.py (55%) rename examples/ad_manager/{v201908 => v202005}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v201908 => v202005}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v201908 => v202005}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v201908 => v202005}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v201908 => v202005}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v201908 => v202005}/targeting_preset_service/__init__.py (100%) create mode 100755 examples/ad_manager/v202005/targeting_preset_service/get_all_targeting_presets.py rename examples/ad_manager/{v201908 => v202005}/team_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/team_service/create_teams.py (96%) rename examples/ad_manager/{v201908 => v202005}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v201908 => v202005}/team_service/update_teams.py (94%) rename examples/ad_manager/{v201908 => v202005}/user_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/user_service/create_users.py (96%) rename examples/ad_manager/{v201908 => v202005}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v201908 => v202005}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v201908 => v202005}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v201908 => v202005}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v201908 => v202005}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v201908 => v202005}/user_service/update_users.py (92%) rename examples/ad_manager/{v201908 => v202005}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202005}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v201908 => v202005}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v201908 => v202005}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v201908 => v202005}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v201908 => v202005}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index b1f32e38..77533942 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +24.0.0 -- 05/12/2020 +* Added support for Ad Manager v202005. +* Removed support for Ad Manager v201905. +* Removed examples for Ad Manager v201908. + 23.0.1 -- 02/20/2020 * Fixed name of 'CreativeReviewService'. diff --git a/examples/ad_manager/v201908/adjustment_service/create_traffic_adjustments.py b/examples/ad_manager/v201908/adjustment_service/create_traffic_adjustments.py deleted file mode 100755 index 3d17a011..00000000 --- a/examples/ad_manager/v201908/adjustment_service/create_traffic_adjustments.py +++ /dev/null @@ -1,143 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2019 Google LLC -# -# 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 adds or replaces a forecast adjustment. - -The adjustment will affect 1920x1080 video traffic in the United States. -""" - -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v201908') - network_service = client.GetService('NetworkService', version='v201908') - - # Get the root ad unit id to target the whole site. - current_network = network_service.getCurrentNetwork() - root_ad_unit_id = current_network['effectiveRootAdUnitId'] - - # Create inventory targeting. - inventory_targeting = { - 'targetedAdUnits': [{ - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id - }] - } - - # Create geo targeting. When using geo targeting with the adjustment service, - # only locations of type COUNTRY are supported. You can download the latest - # geo targets at https://developers.google.com/ad-manager/api/geotargets. - geo_targeting = { - 'targetedLocations': [{ - 'id': 2840 - }] # USA. - } - - # Create ad unit size to define the slice of inventory affected by the - # traffic adjustment. - ad_unit_size = { - 'size': { - 'width': 1920, - 'height': 1080 - }, - 'environmentType': 'VIDEO_PLAYER' - } - - # Create a new historical adjustment targeting next year's January with 105% - # of the traffic of this year's January. - this_january = { - 'startDate': datetime.date(datetime.date.today().year, 1, 1), - 'endDate': datetime.date(datetime.date.today().year, 1, 31) - } - next_january = { - 'startDate': datetime.date(datetime.date.today().year + 1, 1, 1), - 'endDate': datetime.date(datetime.date.today().year + 1, 1, 31) - } - - january_segment = { - 'basisType': 'HISTORICAL', - 'historicalAdjustment': { - 'targetDateRange': next_january, - 'referenceDateRange': this_january, - 'milliPercentMultiplier': 105000 - } - } - - # Create a new absolute adjustment of 500,000 ad opportunities for Christmas - # and 1,000,000 opportunities for Boxing Day of next year. - christmas_day = datetime.date(datetime.date.today().year + 1, 12, 25) - boxing_day = christmas_day + datetime.timedelta(days=1) - holiday_range = {'startDate': christmas_day, 'endDate': boxing_day} - - holiday_segment = { - 'basisType': 'ABSOLUTE', - 'adjustmentTimeSeries': { - 'timeSeriesDateRange': holiday_range, - 'timeSeriesValues': [500000, 1000000], # xsd:long[] - 'valuePeriodType': 'DAILY' - } - } - - # Create a new absolute adjustment of 900,000 ad opportunities for the first - # week of September of next year. - first_week_of_september = { - 'startDate': datetime.date(datetime.date.today().year + 1, 9, 1), - 'endDate': datetime.date(datetime.date.today().year + 1, 9, 7) - } - - september_segment = { - 'basisType': 'ABSOLUTE', - 'adjustmentTimeSeries': { - 'timeSeriesDateRange': first_week_of_september, - 'timeSeriesValues': [900000], - 'valuePeriodType': 'CUSTOM' - } - } - - # Create traffic forecast adjustment object. - adjustment_segments = [january_segment, holiday_segment, september_segment] - adjustment = { - 'filterCriteria': { - 'targeting': { - 'inventoryTargeting': inventory_targeting, - 'geoTargeting': geo_targeting - }, - 'adUnitSizes': [ad_unit_size] - }, - 'forecastAdjustmentSegments': adjustment_segments - } - - # Create or update the traffic adjustment for the given filter criteria on - # the server. - updated_adjustments = adjustment_service.updateTrafficAdjustments( - [adjustment]) - - # Display the results. - for updated_adjustment in updated_adjustments: - print('Traffic forecast adjustment with id %d and %d segments was ' - 'created.' % (updated_adjustment['id'], - len(updated_adjustment['forecastAdjustmentSegments']))) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201908/adjustment_service/update_traffic_adjustments.py b/examples/ad_manager/v201908/adjustment_service/update_traffic_adjustments.py deleted file mode 100755 index eb6bb694..00000000 --- a/examples/ad_manager/v201908/adjustment_service/update_traffic_adjustments.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2019 Google LLC -# -# 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 adds a historical adjustment of 110% for New Years Day traffic. -""" - -from __future__ import print_function -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' - - -def main(client, adjustment_id): - # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v201908') - - # Create a statement to select a single traffic forecast adjustment by id. - statement = ( - ad_manager.StatementBuilder( - version='v201908').Where('id = :id').WithBindVariable( - 'id', adjustment_id)) - - # Get the forecast traffic adjustment. - response = adjustment_service.getTrafficAdjustmentsByStatement( - statement.ToStatement()) - - # Create a new historical adjustment segment for New Year's Day. - this_new_years = datetime.date(datetime.date.today().year, 12, 31) - next_new_years = datetime.date(datetime.date.today().year + 1, 12, 31) - - new_years_segment = { - 'basisType': 'HISTORICAL', - 'historicalAdjustment': { - 'targetDateRange': { - 'startDate': next_new_years, - 'endDate': next_new_years - }, - 'referenceDateRange': { - 'startDate': this_new_years, - 'endDate': this_new_years - }, - 'milliPercentMultiplier': 110000 - } - } - - if 'results' in response and len(response['results']): - # Update each local traffic adjustment. - updated_adjustments = [] - for adjustment in response['results']: - adjustment['forecastAdjustmentSegments'].append(new_years_segment) - updated_adjustments.append(adjustment) - - # Update traffic adjustments remotely. - adjustments = adjustment_service.updateTrafficAdjustments( - updated_adjustments) - - # Display the results. - if adjustments: - for adjustment in adjustments: - print('Traffic forecast adjustment with id %d and %d segments was ' - 'created.' % (adjustment['id'], - len(adjustment['forecastAdjustmentSegments']))) - else: - print('No traffic adjustments were updated.') - else: - print('No traffic adjustments found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py index 62379383..6881b8cb 100755 --- a/examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py @@ -37,7 +37,7 @@ def main(client): for targeting_preset in response['results']: # Print out some information for each targeting preset. print( - 'Targeting preset with ID "%s" and name "%d" was found.\n' + 'Targeting preset with ID "%d" and name "%s" was found.\n' % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: diff --git a/examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py index 525e4f56..f4686b1b 100755 --- a/examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py @@ -37,7 +37,7 @@ def main(client): for targeting_preset in response['results']: # Print out some information for each targeting preset. print( - 'Targeting preset with ID "%s" and name "%d" was found.\n' + 'Targeting preset with ID "%d" and name "%s" was found.\n' % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: diff --git a/examples/ad_manager/v201908/activity_group_service/__init__.py b/examples/ad_manager/v202005/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/activity_group_service/__init__.py rename to examples/ad_manager/v202005/activity_group_service/__init__.py diff --git a/examples/ad_manager/v201908/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202005/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v201908/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202005/activity_group_service/create_activity_groups.py index 18bb07c5..58af7720 100755 --- a/examples/ad_manager/v201908/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202005/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201908') + version='v202005') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v201908/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202005/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v201908/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202005/activity_group_service/get_active_activity_groups.py index d0b7f3e5..76b38b3f 100755 --- a/examples/ad_manager/v201908/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202005/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201908') + 'ActivityGroupService', version='v202005') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201908/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202005/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v201908/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202005/activity_group_service/get_all_activity_groups.py index 40b701b9..fa1ebc26 100755 --- a/examples/ad_manager/v201908/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202005/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201908') + 'ActivityGroupService', version='v202005') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201908/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202005/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v201908/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202005/activity_group_service/update_activity_groups.py index 87fbb707..5fa036de 100755 --- a/examples/ad_manager/v201908/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202005/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201908') + version='v202005') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/activity_service/__init__.py b/examples/ad_manager/v202005/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/activity_service/__init__.py rename to examples/ad_manager/v202005/activity_service/__init__.py diff --git a/examples/ad_manager/v201908/activity_service/create_activities.py b/examples/ad_manager/v202005/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v201908/activity_service/create_activities.py rename to examples/ad_manager/v202005/activity_service/create_activities.py index 3c112186..4f05cbb8 100755 --- a/examples/ad_manager/v201908/activity_service/create_activities.py +++ b/examples/ad_manager/v202005/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201908') + activity_service = client.GetService('ActivityService', version='v202005') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v201908/activity_service/get_active_activities.py b/examples/ad_manager/v202005/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v201908/activity_service/get_active_activities.py rename to examples/ad_manager/v202005/activity_service/get_active_activities.py index 1d78348d..2a267907 100755 --- a/examples/ad_manager/v201908/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202005/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201908') + activity_service = client.GetService('ActivityService', version='v202005') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201908/activity_service/get_all_activities.py b/examples/ad_manager/v202005/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v201908/activity_service/get_all_activities.py rename to examples/ad_manager/v202005/activity_service/get_all_activities.py index a98418f1..22987d07 100755 --- a/examples/ad_manager/v201908/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202005/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201908') + activity_service = client.GetService('ActivityService', version='v202005') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201908/activity_service/update_activities.py b/examples/ad_manager/v202005/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v201908/activity_service/update_activities.py rename to examples/ad_manager/v202005/activity_service/update_activities.py index 92f5dcb2..5ec7d998 100755 --- a/examples/ad_manager/v201908/activity_service/update_activities.py +++ b/examples/ad_manager/v202005/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201908') + activity_service = client.GetService('ActivityService', version='v202005') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202005/adjustment_service/create_forecast_adjustments.py new file mode 100755 index 00000000..feb2ff41 --- /dev/null +++ b/examples/ad_manager/v202005/adjustment_service/create_forecast_adjustments.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a forecast adjustment for New Year's Day traffic.""" + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_TRAFFIC_FORECAST_SEGMENT_ID_HERE' + + +def main(client, traffic_forecast_segment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202005') + + # Create a new forecast adjustment for New Year's Day traffic. + this_new_years = datetime.date(datetime.date.today().year, 1, 1) + next_new_years = datetime.date(datetime.date.today().year + 1, 1, 1) + + forecast = { + 'name': 'Forecast adjustment #%s' % uuid.uuid4(), + 'trafficForecastSegmentId': traffic_forecast_segment_id, + 'dateRange': { + 'startDate': next_new_years, + 'endDate': next_new_years + }, + 'status': 'ACTIVE', + 'volumeType': 'HISTORICAL_BASIS_VOLUME', + 'historicalBasisVolumeSettings': { + 'useParentTrafficForecastSegmentTargeting': True, + 'historicalDateRange': { + 'startDate': this_new_years, + 'endDate': this_new_years + }, + 'multiplierMilliPercent': 110000 + } + } + + forecasts = adjustment_service.createForecastAdjustments([forecast]) + + for forecast in forecasts: + print('Forecast adjustment with id %d and name "%s" was created.' % ( + forecast['id'], forecast['name'] + )) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TRAFFIC_FORECAST_SEGMENT_ID) diff --git a/examples/ad_manager/v202005/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202005/adjustment_service/create_traffic_forecast_segments.py new file mode 100755 index 00000000..1eefc102 --- /dev/null +++ b/examples/ad_manager/v202005/adjustment_service/create_traffic_forecast_segments.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a traffic forecast segment for all ad units in the U.S. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service and the network service. + adjustment_service = client.GetService('AdjustmentService', version='v202005') + network_service = client.GetService('NetworkService', version='v202005') + + # Get the root ad unit id to target the whole site. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create inventory targeting. + inventory_targeting = { + 'targetedAdUnits': [{ + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id + }] + } + + # Create targeting for United States traffic. + geo_targeting = { + 'targetedLocations': [{ + 'id': 2840 + }] + } + + # Create traffic forecast segment object. + segment = { + 'name': 'Forecast segment #%s' % uuid.uuid4(), + 'targeting': { + 'inventoryTargeting': inventory_targeting, + 'geoTargeting': geo_targeting + } + } + + # Create the traffic forecast segment on the server. + segments = adjustment_service.createTrafficForecastSegments([segment]) + + # Display the results. + for segment in segments: + print('Traffic forecast segment with id %d and %d forecast adjustments was ' + 'created.' % (segment['id'], + segment['forecastAdjustmentCount'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201908/adjustment_service/get_all_traffic_adjustments.py b/examples/ad_manager/v202005/adjustment_service/get_all_forecast_adjustments.py similarity index 63% rename from examples/ad_manager/v201908/adjustment_service/get_all_traffic_adjustments.py rename to examples/ad_manager/v202005/adjustment_service/get_all_forecast_adjustments.py index 8f8ac6a1..565f103a 100755 --- a/examples/ad_manager/v201908/adjustment_service/get_all_traffic_adjustments.py +++ b/examples/ad_manager/v202005/adjustment_service/get_all_forecast_adjustments.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2019 Google LLC +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all traffic adjustments.""" - -from __future__ import print_function +"""This example gets all forecast adjustments.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -24,22 +22,23 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v201908') + adjustment_service = client.GetService('AdjustmentService', version='v202005') - # Create a statement to get all forecast traffic adjustments. - statement = ad_manager.StatementBuilder(version='v201908') + # Create a statement to get all forecast adjustments. + statement = ad_manager.StatementBuilder(version='v202005') - # Retrieve a small number of traffic adjustments at a time, paging - # through until all traffic adjustments have been retrieved. + # Retrieve a small number of forecast adjustments at a time, paging + # through until all forecast adjustments have been retrieved. while True: - response = adjustment_service.getTrafficAdjustmentsByStatement( + response = adjustment_service.getForecastAdjustmentsByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): for adjustment in response['results']: - # Print out some information for each traffic adjustment. - print('Traffic forecast adjustment with id %d and %d segments was ' - 'found.' % (adjustment['id'], - len(adjustment['forecastAdjustmentSegments']))) + # Print out some information for each forecast adjustment. + print('Forecast adjustment with id %d and name "%s" belonging to ' + 'forecast segment %d was found.' % + (adjustment['id'], adjustment['name'], + adjustment['trafficForecastSegmentId'])) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v202005/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202005/adjustment_service/get_all_traffic_forecast_segments.py new file mode 100755 index 00000000..aa6d620f --- /dev/null +++ b/examples/ad_manager/v202005/adjustment_service/get_all_traffic_forecast_segments.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 traffic forecast segments.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202005') + + # Create a statement to get all traffic forecast segments. + statement = ad_manager.StatementBuilder(version='v202005') + + # Retrieve a small number of segments at a time, paging through until all + # segments have been retrieved. + while True: + response = adjustment_service.getTrafficForecastSegmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for segment in response['results']: + # Print out some information for each traffic forecast segment. + print('Traffic forecast segment with id %d and name "%s" was found ' % ( + segment['id'], segment['name'], + )) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202005/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202005/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py new file mode 100755 index 00000000..8f2a2e37 --- /dev/null +++ b/examples/ad_manager/v202005/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 forecast adjustments for a traffic forecast segment.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_FORECAST_SEGMENT_ID_HERE' + + +def main(client, traffic_forecast_segment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202005') + + # Create a statement to get forecast adjustments for a given traffic forecast + # segment id. + statement = ad_manager.StatementBuilder(version='v202005').Where( + 'trafficForecastSegmentId = :segmentId').WithBindVariable( + 'segmentId', traffic_forecast_segment_id) + + # Retrieve a small number of forecast adjustments at a time, paging + # through until all forecast adjustments have been retrieved. + while True: + response = adjustment_service.getForecastAdjustmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for adjustment in response['results']: + # Print out some information for each traffic adjustment. + print('Forecast adjustment with id %d and name "%s" belonging to ' + 'forecast segment %d was found.' % + (adjustment['id'], adjustment['name'], + adjustment['trafficForecastSegmentId'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, int(TRAFFIC_FORECAST_SEGMENT_ID)) diff --git a/examples/ad_manager/v202005/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202005/adjustment_service/update_forecast_adjustments.py new file mode 100755 index 00000000..a33615ce --- /dev/null +++ b/examples/ad_manager/v202005/adjustment_service/update_forecast_adjustments.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 updates a forecast adjustment's name.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' + + +def main(client, adjustment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202005') + + # Create a statement to select a single forecast adjustment by id. + statement = ( + ad_manager.StatementBuilder( + version='v202005').Where('id = :id').WithBindVariable( + 'id', adjustment_id)) + + # Get the forecast adjustment. + response = adjustment_service.getForecastAdjustmentsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local forecast adjustment's name. + updated_adjustments = [] + for adjustment in response['results']: + adjustment['name'] += ' (updated)' + updated_adjustments.append(adjustment) + + # Update the forecast adjustment on the server. + adjustments = adjustment_service.updateForecastAdjustments( + updated_adjustments) + + # Display the results. + if adjustments: + for adjustment in adjustments: + print('Forecast adjustment with id %d and name "%s" was updated' % ( + adjustment['id'], adjustment['name'])) + else: + print('No forecast adjustments were updated.') + else: + print('No forecast adjustments found to update.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v201908/audience_segment_service/__init__.py b/examples/ad_manager/v202005/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/audience_segment_service/__init__.py rename to examples/ad_manager/v202005/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v201908/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202005/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v201908/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202005/audience_segment_service/create_audience_segments.py index 9ece5256..c22fdfa6 100755 --- a/examples/ad_manager/v201908/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202005/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201908') - network_service = client.GetService('NetworkService', version='v201908') + 'AudienceSegmentService', version='v202005') + network_service = client.GetService('NetworkService', version='v202005') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201908/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202005/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v201908/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202005/audience_segment_service/get_all_audience_segments.py index f5f19393..85ee110c 100755 --- a/examples/ad_manager/v201908/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202005/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201908') + 'AudienceSegmentService', version='v202005') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201908/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202005/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v201908/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202005/audience_segment_service/get_first_party_audience_segments.py index 7f5cb482..e4a0141d 100755 --- a/examples/ad_manager/v201908/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202005/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201908') + 'AudienceSegmentService', version='v202005') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201908/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202005/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v201908/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202005/audience_segment_service/populate_first_party_audience_segments.py index b381f866..8e3f5dab 100755 --- a/examples/ad_manager/v201908/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202005/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201908') + 'AudienceSegmentService', version='v202005') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201908/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202005/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v201908/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202005/audience_segment_service/update_audience_segments.py index ae61d631..32d11273 100755 --- a/examples/ad_manager/v201908/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202005/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201908') + 'AudienceSegmentService', version='v202005') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201908/cdn_configuration_service/__init__.py b/examples/ad_manager/v202005/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202005/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v201908/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202005/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v201908/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202005/cdn_configuration_service/create_cdn_configurations.py index 635e42cd..d9b8d60c 100755 --- a/examples/ad_manager/v201908/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202005/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201908') + version='v202005') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v201908/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202005/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v201908/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202005/cdn_configuration_service/get_all_cdn_configurations.py index 745933a9..62c1de11 100755 --- a/examples/ad_manager/v201908/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202005/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201908') + version='v202005') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202005/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202005/cms_metadata_service/activate_cms_metadata_values.py new file mode 100755 index 00000000..3a39de52 --- /dev/null +++ b/examples/ad_manager/v202005/cms_metadata_service/activate_cms_metadata_values.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 activates CMS Metadata Values for a particular CMS Metadata Key. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the CMS Metadata Key on which to activate the CMS Metadata +# Values. +CMS_METADATA_KEY_ID = 'INSERT_CMS_METADATA_KEY_ID_HERE' + + +def main(client, cms_metadata_key_id): + # Initialize appropriate service. + cms_metadata_service = client.GetService('CmsMetadataService', + version='v202005') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v202005') + .Where('cmsKeyId = :cmsKeyId AND status = :status') + .WithBindVariable('status', 'INACTIVE') + .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) + + values_activated = 0 + + # Get CMS Metadata Values by statement. + while True: + response = cms_metadata_service.getCmsMetadataValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_value in response['results']: + print('CMS Metadata Value with id "%s" and name "%s" will be ' + 'activated.' % (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'])) + + # Perform action. + result = cms_metadata_service.performCmsMetadataValueAction( + {'xsi_type': 'ActivateCmsMetadataValues'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + values_activated += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if values_activated > 0: + print('Number of CMS Metadata Values activated: %s' % values_activated) + else: + print('No CMS Metadata Values were activated.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CMS_METADATA_KEY_ID) diff --git a/examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_keys.py index ea456f49..59f2ecda 100755 --- a/examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201908') + 'CmsMetadataService', version='v202005') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_values.py index 8e006616..b68a1e21 100755 --- a/examples/ad_manager/v201908/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201908') + 'CmsMetadataService', version='v202005') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v201908/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202005/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v201908/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202005/cms_metadata_service/get_cms_metadata_values_for_key.py index 1831894c..01c8d5b6 100755 --- a/examples/ad_manager/v201908/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202005/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201908') + 'CmsMetadataService', version='v202005') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v201908').Where( + ad_manager.StatementBuilder(version='v202005').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v201908/company_service/__init__.py b/examples/ad_manager/v202005/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/company_service/__init__.py rename to examples/ad_manager/v202005/company_service/__init__.py diff --git a/examples/ad_manager/v201908/company_service/create_companies.py b/examples/ad_manager/v202005/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v201908/company_service/create_companies.py rename to examples/ad_manager/v202005/company_service/create_companies.py index dd6033fa..f037b1a2 100755 --- a/examples/ad_manager/v201908/company_service/create_companies.py +++ b/examples/ad_manager/v202005/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201908') + company_service = client.GetService('CompanyService', version='v202005') # Create company objects. companies = [ diff --git a/examples/ad_manager/v201908/company_service/get_advertisers.py b/examples/ad_manager/v202005/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v201908/company_service/get_advertisers.py rename to examples/ad_manager/v202005/company_service/get_advertisers.py index 243e30cc..622f19e9 100755 --- a/examples/ad_manager/v201908/company_service/get_advertisers.py +++ b/examples/ad_manager/v202005/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201908') + company_service = client.GetService('CompanyService', version='v202005') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201908/company_service/get_all_companies.py b/examples/ad_manager/v202005/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v201908/company_service/get_all_companies.py rename to examples/ad_manager/v202005/company_service/get_all_companies.py index 91311ed2..b51bee22 100755 --- a/examples/ad_manager/v201908/company_service/get_all_companies.py +++ b/examples/ad_manager/v202005/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201908') + company_service = client.GetService('CompanyService', version='v202005') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201908/company_service/update_companies.py b/examples/ad_manager/v202005/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v201908/company_service/update_companies.py rename to examples/ad_manager/v202005/company_service/update_companies.py index 5b485e11..702073d0 100755 --- a/examples/ad_manager/v201908/company_service/update_companies.py +++ b/examples/ad_manager/v202005/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201908') + company_service = client.GetService('CompanyService', version='v202005') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/contact_service/__init__.py b/examples/ad_manager/v202005/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/contact_service/__init__.py rename to examples/ad_manager/v202005/contact_service/__init__.py diff --git a/examples/ad_manager/v201908/contact_service/create_contacts.py b/examples/ad_manager/v202005/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v201908/contact_service/create_contacts.py rename to examples/ad_manager/v202005/contact_service/create_contacts.py index b9ffc2e2..4cf50790 100755 --- a/examples/ad_manager/v201908/contact_service/create_contacts.py +++ b/examples/ad_manager/v202005/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201908') + contact_service = client.GetService('ContactService', version='v202005') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v201908/contact_service/get_all_contacts.py b/examples/ad_manager/v202005/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v201908/contact_service/get_all_contacts.py rename to examples/ad_manager/v202005/contact_service/get_all_contacts.py index 1867a5df..6ec8000d 100755 --- a/examples/ad_manager/v201908/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202005/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201908') + contact_service = client.GetService('ContactService', version='v202005') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201908/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202005/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v201908/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202005/contact_service/get_uninvited_contacts.py index f67b7b58..a10568e4 100755 --- a/examples/ad_manager/v201908/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202005/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201908') + contact_service = client.GetService('ContactService', version='v202005') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201908/contact_service/update_contacts.py b/examples/ad_manager/v202005/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v201908/contact_service/update_contacts.py rename to examples/ad_manager/v202005/contact_service/update_contacts.py index d90e9914..6d4a5a0c 100755 --- a/examples/ad_manager/v201908/contact_service/update_contacts.py +++ b/examples/ad_manager/v202005/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201908') + contact_service = client.GetService('ContactService', version='v202005') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/content_service/__init__.py b/examples/ad_manager/v202005/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/content_service/__init__.py rename to examples/ad_manager/v202005/content_service/__init__.py diff --git a/examples/ad_manager/v201908/content_service/get_all_content.py b/examples/ad_manager/v202005/content_service/get_all_content.py similarity index 74% rename from examples/ad_manager/v201908/content_service/get_all_content.py rename to examples/ad_manager/v202005/content_service/get_all_content.py index 70d0738e..cfc4c5ce 100755 --- a/examples/ad_manager/v201908/content_service/get_all_content.py +++ b/examples/ad_manager/v202005/content_service/get_all_content.py @@ -13,8 +13,8 @@ # 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 content. -""" + +"""This example gets all content.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201908') + content_service = client.GetService('ContentService', version='v202005') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -34,8 +34,13 @@ def main(client): if 'results' in response and len(response['results']): for content in response['results']: # Print out some information for each content. - print('Content with ID "%d" and name "%s" was found.\n' % - (content['id'], content['name'].encode('utf-8'))) + content_description = ('Content with ID "%d" and name "%s"' % + (content['id'], content['name'].encode('utf-8'))) + if content['contentBundleIds']: + content_description += (' belonging to bundle IDs %s' % + content['contentBundleIds']) + content_description += ' was found.' + print(content_description) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v202005/content_service/get_recently_modified_content.py b/examples/ad_manager/v202005/content_service/get_recently_modified_content.py new file mode 100755 index 00000000..a8089fa7 --- /dev/null +++ b/examples/ad_manager/v202005/content_service/get_recently_modified_content.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 recently modified content.""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import ad_manager +import pytz + + +def main(client): + # Initialize appropriate service. + content_service = client.GetService('ContentService', version='v202005') + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + + # Create a statement to get recently modified content based on + # lastModifiedDateTime. Changes to content bundle associations will update + # the lastModifiedDateTime, but CMS metadata changes may not change the + # lastModifiedDateTime. + statement = (ad_manager.StatementBuilder(version='v202005') + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) + + # Retrieve a small amount of content at a time, paging + # through until all content have been retrieved. + while True: + response = content_service.getContentByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for content in response['results']: + # Print out some information for each content. + content_description = ('Content with ID "%d" and name "%s"' % + (content['id'], content['name'].encode('utf-8'))) + if content['contentBundleIds']: + content_description += (' belonging to bundle IDs %s' % + content['contentBundleIds']) + content_description += ' was found.' + print(content_description) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201908/creative_service/__init__.py b/examples/ad_manager/v202005/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/creative_service/__init__.py rename to examples/ad_manager/v202005/creative_service/__init__.py diff --git a/examples/ad_manager/v201908/creative_service/copy_image_creatives.py b/examples/ad_manager/v202005/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v201908/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202005/creative_service/copy_image_creatives.py index 3c28ef42..b28e066a 100755 --- a/examples/ad_manager/v201908/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202005/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201908') + creative_service = client.GetService('CreativeService', version='v202005') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201908/creative_service/create_creative_from_template.py b/examples/ad_manager/v202005/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v201908/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202005/creative_service/create_creative_from_template.py index 04346c59..fe382bef 100755 --- a/examples/ad_manager/v201908/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202005/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201908') + creative_service = client.GetService('CreativeService', version='v202005') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v201908/creative_service/create_creatives.py b/examples/ad_manager/v202005/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v201908/creative_service/create_creatives.py rename to examples/ad_manager/v202005/creative_service/create_creatives.py index f2c4a2d1..5afefa7e 100755 --- a/examples/ad_manager/v201908/creative_service/create_creatives.py +++ b/examples/ad_manager/v202005/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201908') + creative_service = client.GetService('CreativeService', version='v202005') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v201908/creative_service/create_custom_creative.py b/examples/ad_manager/v202005/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v201908/creative_service/create_custom_creative.py rename to examples/ad_manager/v202005/creative_service/create_custom_creative.py index 9a4ee533..bbb9c17a 100755 --- a/examples/ad_manager/v201908/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202005/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201908') + creative_service = client.GetService('CreativeService', version='v202005') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v201908/creative_service/create_native_creative.py b/examples/ad_manager/v202005/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v201908/creative_service/create_native_creative.py rename to examples/ad_manager/v202005/creative_service/create_native_creative.py index 87482aa1..34fad6f1 100755 --- a/examples/ad_manager/v201908/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202005/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201908') + creative_service = client.GetService('CreativeService', version='v202005') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v201908/creative_service/get_all_creatives.py b/examples/ad_manager/v202005/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v201908/creative_service/get_all_creatives.py rename to examples/ad_manager/v202005/creative_service/get_all_creatives.py index c4c6a3eb..7f5c75e1 100755 --- a/examples/ad_manager/v201908/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202005/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201908') + creative_service = client.GetService('CreativeService', version='v202005') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201908/creative_service/get_image_creatives.py b/examples/ad_manager/v202005/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v201908/creative_service/get_image_creatives.py rename to examples/ad_manager/v202005/creative_service/get_image_creatives.py index e9e96a24..496f20be 100755 --- a/examples/ad_manager/v201908/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202005/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201908') + creative_service = client.GetService('CreativeService', version='v202005') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201908/creative_service/update_creatives.py b/examples/ad_manager/v202005/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v201908/creative_service/update_creatives.py rename to examples/ad_manager/v202005/creative_service/update_creatives.py index 7eee0216..e1d64030 100755 --- a/examples/ad_manager/v201908/creative_service/update_creatives.py +++ b/examples/ad_manager/v202005/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201908') + creative_service = client.GetService('CreativeService', version='v202005') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v201908/creative_set_service/__init__.py b/examples/ad_manager/v202005/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/creative_set_service/__init__.py rename to examples/ad_manager/v202005/creative_set_service/__init__.py diff --git a/examples/ad_manager/v201908/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202005/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v201908/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202005/creative_set_service/associate_creative_set_to_line_item.py index beac079a..f3cde302 100755 --- a/examples/ad_manager/v201908/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202005/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201908') + 'LineItemCreativeAssociationService', version='v202005') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v201908/creative_set_service/create_creative_set.py b/examples/ad_manager/v202005/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v201908/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202005/creative_set_service/create_creative_set.py index 794414b1..bc434ca7 100755 --- a/examples/ad_manager/v201908/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202005/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201908') + version='v202005') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v201908/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202005/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v201908/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202005/creative_set_service/get_all_creative_sets.py index 3cc0ca07..7f44dd44 100755 --- a/examples/ad_manager/v201908/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202005/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201908') + 'CreativeSetService', version='v202005') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201908/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202005/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v201908/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202005/creative_set_service/get_creative_sets_for_master_creative.py index 70716293..846c73a6 100755 --- a/examples/ad_manager/v201908/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202005/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201908') + 'CreativeSetService', version='v202005') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201908/creative_set_service/update_creative_set.py b/examples/ad_manager/v202005/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v201908/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202005/creative_set_service/update_creative_set.py index cda2f52a..cee4fb1a 100755 --- a/examples/ad_manager/v201908/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202005/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201908') + version='v202005') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v201908/creative_template_service/__init__.py b/examples/ad_manager/v202005/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/creative_template_service/__init__.py rename to examples/ad_manager/v202005/creative_template_service/__init__.py diff --git a/examples/ad_manager/v201908/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202005/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v201908/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202005/creative_template_service/get_all_creative_templates.py index cc688f2c..42a78767 100755 --- a/examples/ad_manager/v201908/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202005/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201908') + 'CreativeTemplateService', version='v202005') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201908/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202005/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v201908/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202005/creative_template_service/get_system_defined_creative_templates.py index a15d5c40..2339158a 100755 --- a/examples/ad_manager/v201908/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202005/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201908') + 'CreativeTemplateService', version='v202005') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201908/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202005/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v201908/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202005/creative_wrapper_service/create_creative_wrappers.py index 08503298..51345e5d 100755 --- a/examples/ad_manager/v201908/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202005/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201908') + version='v202005') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v201908/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202005/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v201908/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202005/creative_wrapper_service/deactivate_creative_wrapper.py index d556fcce..f8867c98 100755 --- a/examples/ad_manager/v201908/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202005/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201908') + version='v202005') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201908/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202005/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201908/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202005/creative_wrapper_service/get_active_creative_wrappers.py index b703f94c..d1971b0b 100755 --- a/examples/ad_manager/v201908/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202005/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201908') + 'CreativeWrapperService', version='v202005') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201908/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202005/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201908/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202005/creative_wrapper_service/get_all_creative_wrappers.py index 30d5c38e..77c72d51 100755 --- a/examples/ad_manager/v201908/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202005/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201908') + 'CreativeWrapperService', version='v202005') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201908/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202005/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v201908/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202005/creative_wrapper_service/update_creative_wrappers.py index 00fc4fed..bc9c3714 100755 --- a/examples/ad_manager/v201908/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202005/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201908') + version='v202005') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v201908/custom_field_service/__init__.py b/examples/ad_manager/v202005/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/custom_field_service/__init__.py rename to examples/ad_manager/v202005/custom_field_service/__init__.py diff --git a/examples/ad_manager/v201908/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202005/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v201908/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202005/custom_field_service/create_custom_field_options.py index 48185467..4e73096e 100755 --- a/examples/ad_manager/v201908/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202005/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201908') + 'CustomFieldService', version='v202005') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v201908/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202005/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v201908/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202005/custom_field_service/create_custom_fields.py index d32e4340..e3b527db 100755 --- a/examples/ad_manager/v201908/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202005/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201908') + 'CustomFieldService', version='v202005') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v201908/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202005/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v201908/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202005/custom_field_service/deactivate_all_line_item_custom_fields.py index 100cd53e..99e56228 100755 --- a/examples/ad_manager/v201908/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202005/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201908') + 'CustomFieldService', version='v202005') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201908/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202005/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v201908/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202005/custom_field_service/get_all_custom_fields.py index 9efaacbd..22686fa8 100755 --- a/examples/ad_manager/v201908/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202005/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201908') + 'CustomFieldService', version='v202005') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201908/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202005/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v201908/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202005/custom_field_service/get_custom_fields_for_line_items.py index 98ff74c8..18f7e287 100755 --- a/examples/ad_manager/v201908/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202005/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201908') + 'CustomFieldService', version='v202005') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201908/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202005/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v201908/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202005/custom_field_service/set_line_item_custom_field_value.py index 5ca21a23..45b35bfb 100755 --- a/examples/ad_manager/v201908/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202005/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201908') + 'CustomFieldService', version='v202005') - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v201908') + custom_field_statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v201908') + ad_manager.StatementBuilder(version='v202005') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v201908') + line_item_statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201908/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202005/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v201908/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202005/custom_field_service/update_custom_fields.py index 87071178..aaff108d 100755 --- a/examples/ad_manager/v201908/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202005/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201908') + 'CustomFieldService', version='v202005') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v201908/custom_targeting_service/__init__.py b/examples/ad_manager/v202005/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/custom_targeting_service/__init__.py rename to examples/ad_manager/v202005/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v201908/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202005/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v201908/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202005/custom_targeting_service/create_custom_targeting_keys_and_values.py index 383f9bdc..47395f32 100755 --- a/examples/ad_manager/v201908/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202005/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201908') + 'CustomTargetingService', version='v202005') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_keys.py similarity index 93% rename from examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_keys.py index 7842fd42..400c6f28 100755 --- a/examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201908') + 'CustomTargetingService', version='v202005') - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v201908') + key_statement = (ad_manager.StatementBuilder(version='v202005') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_values.py index e9a16725..a993179c 100755 --- a/examples/ad_manager/v201908/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201908') + 'CustomTargetingService', version='v202005') - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v201908') + value_statement = (ad_manager.StatementBuilder(version='v202005') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201908/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202005/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201908/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202005/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 58a5f152..c4690079 100755 --- a/examples/ad_manager/v201908/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202005/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201908') + 'CustomTargetingService', version='v202005') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v201908') + targeting_key_statement = ad_manager.StatementBuilder(version='v202005') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201908/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202005/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201908/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202005/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 3239dab6..950e21ca 100755 --- a/examples/ad_manager/v201908/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202005/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201908') + 'CustomTargetingService', version='v202005') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v201908') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202005') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_keys.py index de6c7575..ab0bfbed 100755 --- a/examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201908') + 'CustomTargetingService', version='v202005') - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_values.py index dc79104c..317aba4d 100755 --- a/examples/ad_manager/v201908/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201908') + 'CustomTargetingService', version='v202005') - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v201908/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202005/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v201908/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202005/forecast_service/get_availability_forecast.py index 7ccdd6e9..62704749 100755 --- a/examples/ad_manager/v201908/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202005/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201908') - network_service = client.GetService('NetworkService', version='v201908') + forecast_service = client.GetService('ForecastService', version='v202005') + network_service = client.GetService('NetworkService', version='v202005') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v201908/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202005/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v201908/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202005/forecast_service/get_availability_forecast_for_line_item.py index 999566ba..11b42159 100755 --- a/examples/ad_manager/v201908/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202005/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201908') + forecast_service = client.GetService('ForecastService', version='v202005') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v201908/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202005/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v201908/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202005/forecast_service/get_delivery_forecast_for_line_items.py index 05c698b4..942e4309 100755 --- a/examples/ad_manager/v201908/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202005/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201908') + forecast_service = client.GetService('ForecastService', version='v202005') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v201908/inventory_service/__init__.py b/examples/ad_manager/v202005/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/inventory_service/__init__.py rename to examples/ad_manager/v202005/inventory_service/__init__.py diff --git a/examples/ad_manager/v201908/inventory_service/archive_ad_units.py b/examples/ad_manager/v202005/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v201908/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202005/inventory_service/archive_ad_units.py index 7cbdbc8c..07969929 100755 --- a/examples/ad_manager/v201908/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202005/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201908') + inventory_service = client.GetService('InventoryService', version='v202005') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v201908/inventory_service/create_ad_units.py b/examples/ad_manager/v202005/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v201908/inventory_service/create_ad_units.py rename to examples/ad_manager/v202005/inventory_service/create_ad_units.py index 2d8e97b6..57b77b53 100755 --- a/examples/ad_manager/v201908/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202005/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201908') + inventory_service = client.GetService('InventoryService', version='v202005') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v201908/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202005/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v201908/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202005/inventory_service/get_ad_unit_hierarchy.py index 51a96c37..244c642b 100755 --- a/examples/ad_manager/v201908/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202005/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201908') - inventory_service = client.GetService('InventoryService', version='v201908') + network_service = client.GetService('NetworkService', version='v202005') + inventory_service = client.GetService('InventoryService', version='v202005') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201908/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202005/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v201908/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202005/inventory_service/get_all_ad_unit_sizes.py index 96538d76..88efae50 100755 --- a/examples/ad_manager/v201908/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202005/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201908') + 'InventoryService', version='v202005') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201908/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202005/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v201908/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202005/inventory_service/get_all_ad_units.py index dbaea8d6..986afa05 100755 --- a/examples/ad_manager/v201908/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202005/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201908') + ad_unit_service = client.GetService('InventoryService', version='v202005') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201908/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202005/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v201908/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202005/inventory_service/get_top_level_ad_units.py index 28084dd9..423ec6a9 100755 --- a/examples/ad_manager/v201908/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202005/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201908') - inventory_service = client.GetService('InventoryService', version='v201908') + network_service = client.GetService('NetworkService', version='v202005') + inventory_service = client.GetService('InventoryService', version='v202005') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201908/inventory_service/update_ad_units.py b/examples/ad_manager/v202005/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v201908/inventory_service/update_ad_units.py rename to examples/ad_manager/v202005/inventory_service/update_ad_units.py index 901040d7..31e2c40b 100755 --- a/examples/ad_manager/v201908/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202005/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201908') + inventory_service = client.GetService('InventoryService', version='v202005') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201908/label_service/__init__.py b/examples/ad_manager/v202005/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/label_service/__init__.py rename to examples/ad_manager/v202005/label_service/__init__.py diff --git a/examples/ad_manager/v201908/label_service/create_labels.py b/examples/ad_manager/v202005/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v201908/label_service/create_labels.py rename to examples/ad_manager/v202005/label_service/create_labels.py index 27b54906..6a5c9059 100755 --- a/examples/ad_manager/v201908/label_service/create_labels.py +++ b/examples/ad_manager/v202005/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201908') + label_service = client.GetService('LabelService', version='v202005') # Create label objects. labels = [] diff --git a/examples/ad_manager/v201908/label_service/deactivate_labels.py b/examples/ad_manager/v202005/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v201908/label_service/deactivate_labels.py rename to examples/ad_manager/v202005/label_service/deactivate_labels.py index 45d42733..a499516d 100755 --- a/examples/ad_manager/v201908/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202005/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201908') + label_service = client.GetService('LabelService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201908/label_service/get_active_labels.py b/examples/ad_manager/v202005/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v201908/label_service/get_active_labels.py rename to examples/ad_manager/v202005/label_service/get_active_labels.py index 5953ea39..ad7a9011 100755 --- a/examples/ad_manager/v201908/label_service/get_active_labels.py +++ b/examples/ad_manager/v202005/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201908') + label_service = client.GetService('LabelService', version='v202005') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201908/label_service/get_all_labels.py b/examples/ad_manager/v202005/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v201908/label_service/get_all_labels.py rename to examples/ad_manager/v202005/label_service/get_all_labels.py index 1e7ffbbb..3209f67d 100755 --- a/examples/ad_manager/v201908/label_service/get_all_labels.py +++ b/examples/ad_manager/v202005/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201908') + label_service = client.GetService('LabelService', version='v202005') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201908/label_service/update_labels.py b/examples/ad_manager/v202005/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v201908/label_service/update_labels.py rename to examples/ad_manager/v202005/label_service/update_labels.py index 354d8a68..3021898a 100755 --- a/examples/ad_manager/v201908/label_service/update_labels.py +++ b/examples/ad_manager/v202005/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201908') + label_service = client.GetService('LabelService', version='v202005') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201908/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202005/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202005/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v201908/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202005/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v201908/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202005/line_item_creative_association_service/create_licas.py index ea62da96..83ab4065 100755 --- a/examples/ad_manager/v201908/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202005/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201908') + 'LineItemCreativeAssociationService', version='v202005') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v201908/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202005/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v201908/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202005/line_item_creative_association_service/deactivate_licas.py index 29c06fb8..fcfc236f 100755 --- a/examples/ad_manager/v201908/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202005/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201908') + 'LineItemCreativeAssociationService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v201908/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202005/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v201908/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202005/line_item_creative_association_service/get_all_licas.py index 288784e7..f90b297d 100755 --- a/examples/ad_manager/v201908/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202005/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201908') + 'LineItemCreativeAssociationService', version='v202005') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201908/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202005/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v201908/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202005/line_item_creative_association_service/get_licas_for_line_item.py index 5ed2efa7..3db27e9d 100755 --- a/examples/ad_manager/v201908/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202005/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201908') + 'LineItemCreativeAssociationService', version='v202005') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201908/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202005/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v201908/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202005/line_item_creative_association_service/update_licas.py index e8a28266..df2686a0 100755 --- a/examples/ad_manager/v201908/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202005/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201908') + 'LineItemCreativeAssociationService', version='v202005') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201908/line_item_service/__init__.py b/examples/ad_manager/v202005/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/line_item_service/__init__.py rename to examples/ad_manager/v202005/line_item_service/__init__.py diff --git a/examples/ad_manager/v201908/line_item_service/activate_line_items.py b/examples/ad_manager/v202005/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v201908/line_item_service/activate_line_items.py rename to examples/ad_manager/v202005/line_item_service/activate_line_items.py index 00d1264b..9e3b70b5 100755 --- a/examples/ad_manager/v201908/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202005/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201908/line_item_service/create_line_items.py b/examples/ad_manager/v202005/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v201908/line_item_service/create_line_items.py rename to examples/ad_manager/v202005/line_item_service/create_line_items.py index 51b1e5e7..7435773a 100755 --- a/examples/ad_manager/v201908/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202005/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201908/line_item_service/create_video_line_item.py b/examples/ad_manager/v202005/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v201908/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202005/line_item_service/create_video_line_item.py index 4856cbe5..fcee045b 100755 --- a/examples/ad_manager/v201908/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202005/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201908/line_item_service/get_all_line_items.py b/examples/ad_manager/v202005/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v201908/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202005/line_item_service/get_all_line_items.py index 2c606b43..c33fb8ff 100755 --- a/examples/ad_manager/v201908/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202005/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201908/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202005/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v201908/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202005/line_item_service/get_line_items_that_need_creatives.py index f678232e..04e0dc18 100755 --- a/examples/ad_manager/v201908/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202005/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201908/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202005/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v201908/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202005/line_item_service/get_recently_updated_line_items.py index 61ee1c24..de6b19b7 100755 --- a/examples/ad_manager/v201908/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202005/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201908/line_item_service/pause_line_items.py b/examples/ad_manager/v202005/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v201908/line_item_service/pause_line_items.py rename to examples/ad_manager/v202005/line_item_service/pause_line_items.py index 41549b64..907315bd 100755 --- a/examples/ad_manager/v201908/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202005/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201908/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202005/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v201908/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202005/line_item_service/target_custom_criteria.py index d8248b4f..b3cdc82b 100755 --- a/examples/ad_manager/v201908/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202005/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/line_item_service/update_line_items.py b/examples/ad_manager/v202005/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v201908/line_item_service/update_line_items.py rename to examples/ad_manager/v202005/line_item_service/update_line_items.py index 95ed5978..25e25586 100755 --- a/examples/ad_manager/v201908/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202005/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') + line_item_service = client.GetService('LineItemService', version='v202005') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v201908/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202005/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201908/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202005/live_stream_event_service/activate_live_stream_events.py index 99e1994e..0c44f099 100755 --- a/examples/ad_manager/v201908/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202005/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201908') + 'LiveStreamEventService', version='v202005') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201908/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202005/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v201908/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202005/live_stream_event_service/create_live_stream_events.py index 4c68af61..f5cab8ca 100755 --- a/examples/ad_manager/v201908/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202005/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201908') + 'LiveStreamEventService', version='v202005') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v201908/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202005/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v201908/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202005/live_stream_event_service/get_all_live_stream_events.py index 0591ef13..62056234 100755 --- a/examples/ad_manager/v201908/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202005/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201908') + 'LiveStreamEventService', version='v202005') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201908/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202005/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v201908/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202005/live_stream_event_service/register_sessions_for_monitoring.py index 030d141c..315e3685 100755 --- a/examples/ad_manager/v201908/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202005/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201908') + 'LiveStreamEventService', version='v202005') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v201908/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202005/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201908/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202005/live_stream_event_service/update_live_stream_events.py index d81b50fe..16582d63 100755 --- a/examples/ad_manager/v201908/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202005/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201908') + 'LiveStreamEventService', version='v202005') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201908/native_style_service/__init__.py b/examples/ad_manager/v202005/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/native_style_service/__init__.py rename to examples/ad_manager/v202005/native_style_service/__init__.py diff --git a/examples/ad_manager/v201908/native_style_service/create_native_styles.py b/examples/ad_manager/v202005/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v201908/native_style_service/create_native_styles.py rename to examples/ad_manager/v202005/native_style_service/create_native_styles.py index 64d8096f..854251ea 100755 --- a/examples/ad_manager/v201908/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202005/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201908') + version='v202005') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v201908/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202005/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v201908/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202005/native_style_service/get_all_native_styles.py index f5050723..1f7c99a7 100755 --- a/examples/ad_manager/v201908/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202005/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201908') + version='v202005') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201908/network_service/__init__.py b/examples/ad_manager/v202005/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/network_service/__init__.py rename to examples/ad_manager/v202005/network_service/__init__.py diff --git a/examples/ad_manager/v201908/network_service/get_all_networks.py b/examples/ad_manager/v202005/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v201908/network_service/get_all_networks.py rename to examples/ad_manager/v202005/network_service/get_all_networks.py index 2cbc9724..b17ea493 100755 --- a/examples/ad_manager/v201908/network_service/get_all_networks.py +++ b/examples/ad_manager/v202005/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201908') + network_service = client.GetService('NetworkService', version='v202005') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v201908/network_service/get_current_network.py b/examples/ad_manager/v202005/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v201908/network_service/get_current_network.py rename to examples/ad_manager/v202005/network_service/get_current_network.py index fd385837..6d456dc7 100755 --- a/examples/ad_manager/v201908/network_service/get_current_network.py +++ b/examples/ad_manager/v202005/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201908') + network_service = client.GetService('NetworkService', version='v202005') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201908/network_service/make_test_network.py b/examples/ad_manager/v202005/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v201908/network_service/make_test_network.py rename to examples/ad_manager/v202005/network_service/make_test_network.py index c631fb1e..35e2da0d 100755 --- a/examples/ad_manager/v201908/network_service/make_test_network.py +++ b/examples/ad_manager/v202005/network_service/make_test_network.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201908') + network_service = client.GetService('NetworkService', version='v202005') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v201908/order_service/__init__.py b/examples/ad_manager/v202005/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/order_service/__init__.py rename to examples/ad_manager/v202005/order_service/__init__.py diff --git a/examples/ad_manager/v201908/order_service/approve_orders.py b/examples/ad_manager/v202005/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v201908/order_service/approve_orders.py rename to examples/ad_manager/v202005/order_service/approve_orders.py index 5d2e9c46..2899a6a7 100755 --- a/examples/ad_manager/v201908/order_service/approve_orders.py +++ b/examples/ad_manager/v202005/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201908') + order_service = client.GetService('OrderService', version='v202005') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201908/order_service/create_orders.py b/examples/ad_manager/v202005/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v201908/order_service/create_orders.py rename to examples/ad_manager/v202005/order_service/create_orders.py index 6ca3fe39..8cfe05d6 100755 --- a/examples/ad_manager/v201908/order_service/create_orders.py +++ b/examples/ad_manager/v202005/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201908') + order_service = client.GetService('OrderService', version='v202005') # Create order objects. orders = [] diff --git a/examples/ad_manager/v201908/order_service/get_all_orders.py b/examples/ad_manager/v202005/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v201908/order_service/get_all_orders.py rename to examples/ad_manager/v202005/order_service/get_all_orders.py index f1a82dcd..79468aec 100755 --- a/examples/ad_manager/v201908/order_service/get_all_orders.py +++ b/examples/ad_manager/v202005/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201908') + order_service = client.GetService('OrderService', version='v202005') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201908/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202005/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v201908/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202005/order_service/get_orders_starting_soon.py index 8a204a57..fac99686 100755 --- a/examples/ad_manager/v201908/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202005/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201908') + order_service = client.GetService('OrderService', version='v202005') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201908/order_service/update_orders.py b/examples/ad_manager/v202005/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v201908/order_service/update_orders.py rename to examples/ad_manager/v202005/order_service/update_orders.py index 94c109ea..db565bfa 100755 --- a/examples/ad_manager/v201908/order_service/update_orders.py +++ b/examples/ad_manager/v202005/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201908') + order_service = client.GetService('OrderService', version='v202005') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201908/placement_service/create_placements.py b/examples/ad_manager/v202005/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v201908/placement_service/create_placements.py rename to examples/ad_manager/v202005/placement_service/create_placements.py index 8267f71e..a7b8e5da 100755 --- a/examples/ad_manager/v201908/placement_service/create_placements.py +++ b/examples/ad_manager/v202005/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201908') - inventory_service = client.GetService('InventoryService', version='v201908') + placement_service = client.GetService('PlacementService', version='v202005') + inventory_service = client.GetService('InventoryService', version='v202005') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201908/placement_service/deactivate_placements.py b/examples/ad_manager/v202005/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v201908/placement_service/deactivate_placements.py rename to examples/ad_manager/v202005/placement_service/deactivate_placements.py index 27db4a01..181da974 100755 --- a/examples/ad_manager/v201908/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202005/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201908') + placement_service = client.GetService('PlacementService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/placement_service/get_active_placements.py b/examples/ad_manager/v202005/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v201908/placement_service/get_active_placements.py rename to examples/ad_manager/v202005/placement_service/get_active_placements.py index 63fdf126..81120f00 100755 --- a/examples/ad_manager/v201908/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202005/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201908') + placement_service = client.GetService('PlacementService', version='v202005') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201908/placement_service/get_all_placements.py b/examples/ad_manager/v202005/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v201908/placement_service/get_all_placements.py rename to examples/ad_manager/v202005/placement_service/get_all_placements.py index 52a422a9..ff2efc6e 100755 --- a/examples/ad_manager/v201908/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202005/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201908') + placement_service = client.GetService('PlacementService', version='v202005') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201908/placement_service/update_placements.py b/examples/ad_manager/v202005/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v201908/placement_service/update_placements.py rename to examples/ad_manager/v202005/placement_service/update_placements.py index 8dc283e2..6cfa329e 100755 --- a/examples/ad_manager/v201908/placement_service/update_placements.py +++ b/examples/ad_manager/v202005/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201908') + placement_service = client.GetService('PlacementService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201908/proposal_line_item_service/__init__.py b/examples/ad_manager/v202005/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202005/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v201908/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202005/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201908/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202005/proposal_line_item_service/archive_proposal_line_items.py index 9f9c7325..237e8af7 100755 --- a/examples/ad_manager/v201908/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202005/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201908') + 'ProposalLineItemService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202005/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v201908/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202005/proposal_line_item_service/create_proposal_line_items.py index cc9ee05c..43df0f78 100755 --- a/examples/ad_manager/v201908/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202005/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201908') - network_service = client.GetService('NetworkService', version='v201908') + 'ProposalLineItemService', version='v202005') + network_service = client.GetService('NetworkService', version='v202005') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201908/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202005/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v201908/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202005/proposal_line_item_service/get_all_proposal_line_items.py index 8effa384..be4d7225 100755 --- a/examples/ad_manager/v201908/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202005/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201908') + 'ProposalLineItemService', version='v202005') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201908/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202005/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v201908/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202005/proposal_line_item_service/get_proposal_line_items_for_proposal.py index c35c00c4..46d8ef00 100755 --- a/examples/ad_manager/v201908/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202005/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201908') + 'ProposalLineItemService', version='v202005') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201908/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202005/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201908/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202005/proposal_line_item_service/update_proposal_line_items.py index 901bda63..3d07e2df 100755 --- a/examples/ad_manager/v201908/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202005/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201908') + 'ProposalLineItemService', version='v202005') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/proposal_service/__init__.py b/examples/ad_manager/v202005/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/proposal_service/__init__.py rename to examples/ad_manager/v202005/proposal_service/__init__.py diff --git a/examples/ad_manager/v201908/proposal_service/create_proposals.py b/examples/ad_manager/v202005/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v201908/proposal_service/create_proposals.py rename to examples/ad_manager/v202005/proposal_service/create_proposals.py index 4d3007b3..00fd5452 100755 --- a/examples/ad_manager/v201908/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202005/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201908') + proposal_service = client.GetService('ProposalService', version='v202005') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201908/proposal_service/get_all_proposals.py b/examples/ad_manager/v202005/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v201908/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202005/proposal_service/get_all_proposals.py index 06468378..989d8068 100755 --- a/examples/ad_manager/v201908/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202005/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201908') + proposal_service = client.GetService('ProposalService', version='v202005') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201908/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202005/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v201908/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202005/proposal_service/get_marketplace_comments.py index f7a0868a..1ea5aad4 100755 --- a/examples/ad_manager/v201908/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202005/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201908') + 'ProposalService', version='v202005') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v201908/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202005/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v201908/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202005/proposal_service/get_proposals_awaiting_seller_review.py index 14a3c141..777b5edd 100755 --- a/examples/ad_manager/v201908/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202005/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201908') + proposal_service = client.GetService('ProposalService', version='v202005') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v201908/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202005/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v201908/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202005/proposal_service/request_buyers_acceptance.py index 41aa7746..0f35c852 100755 --- a/examples/ad_manager/v201908/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202005/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201908') + proposal_service = client.GetService('ProposalService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201908/proposal_service/update_proposals.py b/examples/ad_manager/v202005/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v201908/proposal_service/update_proposals.py rename to examples/ad_manager/v202005/proposal_service/update_proposals.py index 95849d5f..1418ab6f 100755 --- a/examples/ad_manager/v201908/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202005/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201908') + proposal_service = client.GetService('ProposalService', version='v202005') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/publisher_query_language_service/__init__.py b/examples/ad_manager/v202005/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202005/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v201908/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202005/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v201908/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202005/publisher_query_language_service/fetch_match_tables.py index 34e54c73..e9b998b6 100755 --- a/examples/ad_manager/v201908/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202005/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201908/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202005/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v201908/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202005/publisher_query_language_service/get_all_browsers.py index c31237b1..ef0f29d4 100755 --- a/examples/ad_manager/v201908/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202005/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v201908/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202005/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v201908/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202005/publisher_query_language_service/get_all_programmatic_buyers.py index a7267574..85b09aa4 100755 --- a/examples/ad_manager/v201908/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202005/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201908') + data_downloader = client.GetDataDownloader(version='v202005') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201908/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202005/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v201908/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202005/publisher_query_language_service/get_geo_targets.py index 561abcbf..29af9c63 100755 --- a/examples/ad_manager/v201908/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202005/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v201908/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202005/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v201908/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202005/publisher_query_language_service/get_line_items_named_like.py index 8a10c24c..fb531ce4 100755 --- a/examples/ad_manager/v201908/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202005/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v201908/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202005/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v201908/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202005/publisher_query_language_service/get_recent_changes.py index 0bd025c1..214ab078 100755 --- a/examples/ad_manager/v201908/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202005/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201908') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202005') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v201908/report_service/__init__.py b/examples/ad_manager/v202005/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/report_service/__init__.py rename to examples/ad_manager/v202005/report_service/__init__.py diff --git a/examples/ad_manager/v201908/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202005/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v201908/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202005/report_service/run_ad_exchange_report.py index 4f431eea..b2ef393b 100755 --- a/examples/ad_manager/v201908/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202005/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') # Create report job. report_job = { diff --git a/examples/ad_manager/v201908/report_service/run_delivery_report.py b/examples/ad_manager/v202005/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v201908/report_service/run_delivery_report.py rename to examples/ad_manager/v202005/report_service/run_delivery_report.py index 2cec8565..7acdd128 100755 --- a/examples/ad_manager/v201908/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202005/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201908/report_service/run_inventory_report.py b/examples/ad_manager/v202005/report_service/run_inventory_report.py similarity index 74% rename from examples/ad_manager/v201908/report_service/run_inventory_report.py rename to examples/ad_manager/v202005/report_service/run_inventory_report.py index caa5bb77..60ac96d3 100755 --- a/examples/ad_manager/v201908/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202005/report_service/run_inventory_report.py @@ -24,21 +24,8 @@ def main(client): - # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201908') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201908') - - # Get root ad unit id for network. - root_ad_unit_id = ( - network_service.getCurrentNetwork()['effectiveRootAdUnitId']) - - # Set filter statement and bind value for reportQuery. - statement = (ad_manager.StatementBuilder(version='v201908') - .Where('PARENT_AD_UNIT_ID = :parentAdUnitId') - .WithBindVariable('parentAdUnitId', int(root_ad_unit_id)) - .Limit(None) # No limit or offset for reports - .Offset(None)) + report_downloader = client.GetDataDownloader(version='v202005') # Create report job. report_job = { @@ -50,8 +37,7 @@ def main(client): 'ADSENSE_LINE_ITEM_LEVEL_CLICKS', 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'], - 'dateRangeType': 'LAST_WEEK', - 'statement': statement.ToStatement() + 'dateRangeType': 'LAST_WEEK' } } diff --git a/examples/ad_manager/v201908/report_service/run_reach_report.py b/examples/ad_manager/v202005/report_service/run_reach_report.py similarity index 87% rename from examples/ad_manager/v201908/report_service/run_reach_report.py rename to examples/ad_manager/v202005/report_service/run_reach_report.py index 9cc56de4..43b49c77 100755 --- a/examples/ad_manager/v201908/report_service/run_reach_report.py +++ b/examples/ad_manager/v202005/report_service/run_reach_report.py @@ -25,13 +25,14 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') # Create report job. report_job = { 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'columns': ['REACH_FREQUENCY', 'REACH_AVERAGE_REVENUE', 'REACH'], + 'dimensions': ['COUNTRY_NAME', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'], + 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS', + 'UNIQUE_REACH'], 'dateRangeType': 'REACH_LIFETIME' } } diff --git a/examples/ad_manager/v201908/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202005/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v201908/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202005/report_service/run_report_and_create_match_table.py index 23c5ed47..72366ee7 100755 --- a/examples/ad_manager/v201908/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202005/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201908/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202005/report_service/run_report_with_custom_fields.py similarity index 55% rename from examples/ad_manager/v201908/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202005/report_service/run_report_with_custom_fields.py index 0af5875d..5f8cb825 100755 --- a/examples/ad_manager/v201908/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202005/report_service/run_report_with_custom_fields.py @@ -22,51 +22,22 @@ from googleads import ad_manager from googleads import errors -# Set the ID of the order to get line items from. -ORDER_ID = 'INSERT_ORDER_ID_HERE' +CUSTOM_FIELD_ID = 'INSERT_CUSTOM_FIELD_ID' +CUSTOM_DIMENSION_KEY_ID = 'INSERT_CUSTOM_DIMENSION_KEY_ID' -def main(client, order_id): - # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201908') +def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201908') - - # Filter for line items of a given order. - statement = (ad_manager.StatementBuilder(version='v201908') - .Where('orderId = :orderId') - .WithBindVariable('orderId', int(order_id))) - - # Collect all line item custom field IDs for an order. - custom_field_ids = set() - - # Get users by statement. - while True: - response = line_item_service.getLineItemsByStatement( - statement.ToStatement()) - if 'results' in response and len(response['results']): - # Get custom field IDs from the line items of an order. - for line_item in response['results']: - if 'customFieldValues' in line_item: - for custom_field_value in line_item['customFieldValues']: - custom_field_ids.add(custom_field_value['customFieldId']) - statement.offset += statement.limit - else: - break - - # Modify statement for reports - statement.limit = None - statement.offset = None - statement.Where('ORDER_ID = :orderId') + report_downloader = client.GetDataDownloader(version='v202005') # Create report job. report_job = { 'reportQuery': { - 'dimensions': ['LINE_ITEM_ID', 'LINE_ITEM_NAME'], - 'statement': statement.ToStatement(), + 'dimensions': ['CUSTOM_DIMENSION', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'], 'columns': ['AD_SERVER_IMPRESSIONS'], 'dateRangeType': 'LAST_MONTH', - 'customFieldIds': list(custom_field_ids) + 'customFieldIds': [custom_field_id], + 'customDimensionKeyIds': [custom_dimension_key_id] } } @@ -94,4 +65,4 @@ def main(client, order_id): if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ORDER_ID) + main(ad_manager_client, CUSTOM_FIELD_ID, CUSTOM_DIMENSION_KEY_ID) diff --git a/examples/ad_manager/v201908/report_service/run_sales_report.py b/examples/ad_manager/v202005/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v201908/report_service/run_sales_report.py rename to examples/ad_manager/v202005/report_service/run_sales_report.py index cc075ba9..f2a18f80 100755 --- a/examples/ad_manager/v201908/report_service/run_sales_report.py +++ b/examples/ad_manager/v202005/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') # Create report job. report_job = { diff --git a/examples/ad_manager/v201908/report_service/run_saved_query.py b/examples/ad_manager/v202005/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v201908/report_service/run_saved_query.py rename to examples/ad_manager/v202005/report_service/run_saved_query.py index 92fd3bae..969a7a05 100755 --- a/examples/ad_manager/v201908/report_service/run_saved_query.py +++ b/examples/ad_manager/v202005/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201908') + report_service = client.GetService('ReportService', version='v202005') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201908') + report_downloader = client.GetDataDownloader(version='v202005') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v201908/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202005/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202005/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v201908/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202005/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v201908/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202005/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 2893eb1d..8b410477 100755 --- a/examples/ad_manager/v201908/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202005/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201908') + 'SuggestedAdUnitService', version='v202005') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201908/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202005/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201908/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202005/suggested_ad_unit_service/get_all_suggested_ad_units.py index fc87af6a..0e854cae 100755 --- a/examples/ad_manager/v201908/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202005/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201908') + 'SuggestedAdUnitService', version='v202005') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201908/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202005/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201908/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202005/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index f5d97d89..55013c4b 100755 --- a/examples/ad_manager/v201908/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202005/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201908') + 'SuggestedAdUnitService', version='v202005') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v201908/targeting_preset_service/__init__.py b/examples/ad_manager/v202005/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/targeting_preset_service/__init__.py rename to examples/ad_manager/v202005/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202005/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202005/targeting_preset_service/get_all_targeting_presets.py new file mode 100755 index 00000000..43fc7ac0 --- /dev/null +++ b/examples/ad_manager/v202005/targeting_preset_service/get_all_targeting_presets.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python +# +# Copyright 2019 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 targeting presets. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + targeting_preset_service = client.GetService( + 'TargetingPresetService', version='v202005') + + # Create a statement to select suggested ad units. + statement = ad_manager.StatementBuilder(version='v202005') + + # Retrieve a small number of targeting presets at a time, paging + # through until all targeting presets have been retrieved. + while True: + response = targeting_preset_service.getTargetingPresetsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for targeting_preset in response['results']: + # Print out some information for each targeting preset. + print( + 'Targeting preset with ID "%s" and name "%d" was found.\n' + % (targeting_preset['id'], targeting_preset['name'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201908/team_service/__init__.py b/examples/ad_manager/v202005/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/team_service/__init__.py rename to examples/ad_manager/v202005/team_service/__init__.py diff --git a/examples/ad_manager/v201908/team_service/create_teams.py b/examples/ad_manager/v202005/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v201908/team_service/create_teams.py rename to examples/ad_manager/v202005/team_service/create_teams.py index dc9922ae..babbea53 100755 --- a/examples/ad_manager/v201908/team_service/create_teams.py +++ b/examples/ad_manager/v202005/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201908') + team_service = client.GetService('TeamService', version='v202005') # Create team objects. teams = [] diff --git a/examples/ad_manager/v201908/team_service/get_all_teams.py b/examples/ad_manager/v202005/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v201908/team_service/get_all_teams.py rename to examples/ad_manager/v202005/team_service/get_all_teams.py index f6daffae..554a10e0 100755 --- a/examples/ad_manager/v201908/team_service/get_all_teams.py +++ b/examples/ad_manager/v202005/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201908') + team_service = client.GetService('TeamService', version='v202005') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201908/team_service/update_teams.py b/examples/ad_manager/v202005/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v201908/team_service/update_teams.py rename to examples/ad_manager/v202005/team_service/update_teams.py index fe154a74..bc2e1258 100755 --- a/examples/ad_manager/v201908/team_service/update_teams.py +++ b/examples/ad_manager/v202005/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201908') + team_service = client.GetService('TeamService', version='v202005') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v201908/user_service/__init__.py b/examples/ad_manager/v202005/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/user_service/__init__.py rename to examples/ad_manager/v202005/user_service/__init__.py diff --git a/examples/ad_manager/v201908/user_service/create_users.py b/examples/ad_manager/v202005/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v201908/user_service/create_users.py rename to examples/ad_manager/v202005/user_service/create_users.py index 2060ffe2..2f355c5c 100755 --- a/examples/ad_manager/v201908/user_service/create_users.py +++ b/examples/ad_manager/v202005/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201908') + user_service = client.GetService('UserService', version='v202005') # Create user objects. users = [ diff --git a/examples/ad_manager/v201908/user_service/deactivate_users.py b/examples/ad_manager/v202005/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v201908/user_service/deactivate_users.py rename to examples/ad_manager/v202005/user_service/deactivate_users.py index 212b9019..f4c767db 100755 --- a/examples/ad_manager/v201908/user_service/deactivate_users.py +++ b/examples/ad_manager/v202005/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201908') + user_service = client.GetService('UserService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201908/user_service/get_all_roles.py b/examples/ad_manager/v202005/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v201908/user_service/get_all_roles.py rename to examples/ad_manager/v202005/user_service/get_all_roles.py index 01d181dc..6c544e84 100755 --- a/examples/ad_manager/v201908/user_service/get_all_roles.py +++ b/examples/ad_manager/v202005/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201908') + user_service = client.GetService('UserService', version='v202005') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v201908/user_service/get_all_users.py b/examples/ad_manager/v202005/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v201908/user_service/get_all_users.py rename to examples/ad_manager/v202005/user_service/get_all_users.py index 9484bb16..dc67e5d2 100755 --- a/examples/ad_manager/v201908/user_service/get_all_users.py +++ b/examples/ad_manager/v202005/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201908') + user_service = client.GetService('UserService', version='v202005') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201908/user_service/get_current_user.py b/examples/ad_manager/v202005/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v201908/user_service/get_current_user.py rename to examples/ad_manager/v202005/user_service/get_current_user.py index c66e04a5..8244c68e 100755 --- a/examples/ad_manager/v201908/user_service/get_current_user.py +++ b/examples/ad_manager/v202005/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201908') + user_service = client.GetService('UserService', version='v202005') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v201908/user_service/get_user_by_email_address.py b/examples/ad_manager/v202005/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v201908/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202005/user_service/get_user_by_email_address.py index b75c5226..1eaf6193 100755 --- a/examples/ad_manager/v201908/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202005/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201908') + user_service = client.GetService('UserService', version='v202005') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201908/user_service/update_users.py b/examples/ad_manager/v202005/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v201908/user_service/update_users.py rename to examples/ad_manager/v202005/user_service/update_users.py index d282fdfb..727b8960 100755 --- a/examples/ad_manager/v201908/user_service/update_users.py +++ b/examples/ad_manager/v202005/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201908') + user_service = client.GetService('UserService', version='v202005') # Create query. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201908/user_team_association_service/__init__.py b/examples/ad_manager/v202005/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201908/user_team_association_service/__init__.py rename to examples/ad_manager/v202005/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v201908/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202005/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v201908/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202005/user_team_association_service/create_user_team_associations.py index 775c3237..6709bd88 100755 --- a/examples/ad_manager/v201908/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202005/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201908') + 'UserTeamAssociationService', version='v202005') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v201908/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202005/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v201908/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202005/user_team_association_service/delete_user_team_associations.py index 64836e4f..2b846f02 100755 --- a/examples/ad_manager/v201908/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202005/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201908') + 'UserTeamAssociationService', version='v202005') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201908/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202005/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v201908/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202005/user_team_association_service/get_all_user_team_associations.py index eb948d76..48e2ee31 100755 --- a/examples/ad_manager/v201908/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202005/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201908') + 'UserTeamAssociationService', version='v202005') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202005') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201908/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202005/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v201908/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202005/user_team_association_service/get_user_team_associations_for_user.py index 7d982ba5..830087c3 100755 --- a/examples/ad_manager/v201908/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202005/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201908') + 'UserTeamAssociationService', version='v202005') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201908/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202005/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v201908/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202005/user_team_association_service/update_user_team_associations.py index accebf0c..ea967d5b 100755 --- a/examples/ad_manager/v201908/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202005/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201908') + 'UserTeamAssociationService', version='v202005') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201908') + statement = (ad_manager.StatementBuilder(version='v202005') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index b0ebd153..610a2fe1 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,29 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201905': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'BaseRateService', 'CdnConfigurationService', 'CmsMetadataService', - 'CompanyService', 'ContactService', 'ContentBundleService', - 'ContentService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'ExchangeRateService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PackageService', 'PlacementService', - 'PremiumRateService', 'ProductService', 'ProductPackageService', - 'ProductPackageItemService', 'ProductTemplateService', - 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'RateCardService', - 'ReconciliationOrderReportService', 'ReconciliationReportRowService', - 'ReconciliationLineItemReportService', - 'ReconciliationReportService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', - 'UserService', 'UserTeamAssociationService', 'WorkflowRequestService'), 'v201908': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', @@ -116,6 +93,23 @@ 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), + 'v202005': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', + 'ContactService', 'ContentBundleService', 'ContentService', + 'CreativeReviewService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'ForecastService', 'InventoryService', + 'LabelService', 'LineItemCreativeAssociationService', + 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PlacementService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', + 'StreamActivityMonitorService', 'SuggestedAdUnitService', + 'TeamService', 'TargetingPresetService', 'UserService', + 'UserTeamAssociationService'), } diff --git a/googleads/common.py b/googleads/common.py index ae054321..88277cc4 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '23.0.1' +VERSION = '24.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 44d67cd1..5071a68f 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202002' +CURRENT_VERSION = 'v202005' class CommonTest(testing.CleanUtilityRegistryTestCase): From 7c41584c65759b6860572a13bde65d7395c5b2d8 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 14 May 2020 16:44:05 -0400 Subject: [PATCH 156/180] Commiting latest changes. From f3065bd932f92390cbe8c4488b06835b4d65f251 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Wed, 15 Jul 2020 10:46:27 -0400 Subject: [PATCH 157/180] Patch to allow use of Application Default Credentials --- ChangeLog | 3 +++ googleads/common.py | 2 +- googleads/oauth2.py | 38 +++++++++++++++++++++++++++++++ tests/oauth2_test.py | 53 +++++++++++++++++++++++++++++++++++++++----- 4 files changed, 90 insertions(+), 6 deletions(-) diff --git a/ChangeLog b/ChangeLog index 77533942..aa2fd188 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,6 @@ +24.1.0 -- 07/13/2020 +* Added 'GoogleCredentialsClient' class to re-use an OAuth2 credentials object + 24.0.0 -- 05/12/2020 * Added support for Ad Manager v202005. * Removed support for Ad Manager v201905. diff --git a/googleads/common.py b/googleads/common.py index 88277cc4..1265452e 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '24.0.0' +VERSION = '24.1.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/googleads/oauth2.py b/googleads/oauth2.py index 322eb32d..9d40391b 100644 --- a/googleads/oauth2.py +++ b/googleads/oauth2.py @@ -23,8 +23,10 @@ from independently refreshing the credentials. """ + import googleads.errors import requests + import google.auth.transport.requests import google.oauth2.credentials import google.oauth2.service_account @@ -211,6 +213,42 @@ def Refresh(self): google.auth.transport.requests.Request(session=session)) +class GoogleCredentialsClient(GoogleRefreshableOAuth2Client): + """A simple client for using OAuth2 for Google APIs with a credentials object. + + This class is not capable of supporting any flows other than taking an + existing credentials (google.auth.credentials) to generate the refresh + and access tokens. + """ + + def __init__(self, credentials): + """Initializes an OAuth2 client using a credentials object. + + Args: + credentials: A credentials object implementing google.auth.credentials. + """ + self.creds = credentials + + def CreateHttpHeader(self): + """Creates an OAuth2 HTTP header. + + Returns: + A dictionary containing one entry: the OAuth2 Bearer header under the + 'Authorization' key. + """ + if self.creds.expiry is None or self.creds.expired: + self.Refresh() + + oauth2_header = {} + self.creds.apply(oauth2_header) + return oauth2_header + + def Refresh(self): + """Uses the credentials object to retrieve and set a new Access Token.""" + transport = google.auth.transport.requests.Request() + self.creds.refresh(transport) + + class GoogleServiceAccountClient(GoogleRefreshableOAuth2Client): """A simple client for using OAuth2 for Google APIs with a service account. diff --git a/tests/oauth2_test.py b/tests/oauth2_test.py index c6dd5fa8..8716b779 100644 --- a/tests/oauth2_test.py +++ b/tests/oauth2_test.py @@ -39,8 +39,8 @@ def setUp(self): self.scope_ad_manager = 'https://www.googleapis.com/auth/dfp' def testGetAPIScope_adwords(self): - self.assertEquals(googleads.oauth2.GetAPIScope(self.api_name_adwords), - self.scope_adwords) + self.assertEqual(googleads.oauth2.GetAPIScope(self.api_name_adwords), + self.scope_adwords) def testGetAPIScope_badKey(self): self.assertRaises(googleads.errors.GoogleAdsValueError, @@ -153,7 +153,7 @@ def testCreateHttpHeader_refresh(self): header = self.refresh_client.CreateHttpHeader() self.assertEqual(mock_session_instance.proxies, {}) self.assertEqual(mock_session_instance.verify, True) - self.assertEqual(mock_session_instance.cert, None) + self.assertIsNone(mock_session_instance.cert) self.mock_req.assert_called_once_with(session=mock_session_instance) self.assertEqual(expected_header, header) self.mock_credentials_instance.refresh.assert_called_once_with( @@ -195,6 +195,49 @@ def testCreateHttpHeader_refreshFails(self): self.assertFalse(self.mock_credentials_instance.apply.called) +class GoogleCredentialsClientTest(unittest.TestCase): + """Tests for the googleads.oauth2.GoogleCredentialsClient class.""" + + def setUp(self): + self.access_token = 'a' + + # Mock out google.auth.transport.Request for testing. + self.mock_req = mock.Mock(spec=Request) + self.mock_req.return_value = mock.Mock() + self.mock_req_instance = self.mock_req.return_value + + # Mock out google.oauth2.credentials.Credentials for testing + self.mock_credentials = mock.Mock(spec=Credentials) + self.mock_credentials.expiry = None + + def apply(headers, token=None): + headers['authorization'] = ('Bearer %s' % self.access_token) + + self.mock_credentials.apply = mock.Mock(side_effect=apply) + + self.client = googleads.oauth2.GoogleCredentialsClient( + self.mock_credentials) + + def testRefresh(self): + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + self.client.Refresh() + self.mock_req.assert_called_once() + + def testCreateHttpHeader_credentialsExpired(self): + self.mock_credentials.expiry = object() + self.mock_credentials.expired = True + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + self.client.CreateHttpHeader() + self.mock_req.assert_called_once() + + def testCreateHttpHeader_applyCredentialsToken(self): + expected_header = {u'authorization': 'Bearer %s' % self.access_token} + + with mock.patch('google.auth.transport.requests.Request', self.mock_req): + header = self.client.CreateHttpHeader() + self.assertEqual(header, expected_header) + + class GoogleServiceAccountTest(unittest.TestCase): """Tests for the googleads.oauth2.GoogleServiceAccountClient class.""" @@ -240,7 +283,7 @@ def apply(headers, token=None): def refresh(request): self.mock_credentials_instance.token = ( self.access_token_unrefreshed if - self.mock_credentials_instance.token is 'x' + self.mock_credentials_instance.token == 'x' else self.access_token_refreshed) self.mock_credentials_instance.token_expiry = datetime.datetime.utcnow() @@ -283,7 +326,7 @@ def testCreateHttpHeader_refresh(self): header = self.sa_client.CreateHttpHeader() self.assertEqual(mock_session_instance.proxies, {}) self.assertEqual(mock_session_instance.verify, True) - self.assertEqual(mock_session_instance.cert, None) + self.assertIsNone(mock_session_instance.cert) self.mock_req.assert_called_once_with(session=mock_session_instance) self.assertEqual(expected_header, header) self.mock_credentials_instance.refresh.assert_called_once_with( From 6add9a7cc6148e98ada8097586a8eb1b47b2a8fd Mon Sep 17 00:00:00 2001 From: David Wihl Date: Wed, 15 Jul 2020 10:48:15 -0400 Subject: [PATCH 158/180] Commiting latest changes. From 7a7ee669c37accddd8b997ba8d1c466df40d2509 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ferraro?= Date: Thu, 6 Aug 2020 19:21:31 +0200 Subject: [PATCH 159/180] Bug fix. There was a comma misplaced. (#467) Thanks for fixing this! --- examples/adwords/v201809/basic_operations/update_keyword.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/adwords/v201809/basic_operations/update_keyword.py b/examples/adwords/v201809/basic_operations/update_keyword.py index 6078d6a2..6c88b605 100755 --- a/examples/adwords/v201809/basic_operations/update_keyword.py +++ b/examples/adwords/v201809/basic_operations/update_keyword.py @@ -69,8 +69,7 @@ def main(client, ad_group_id, criterion_id): '"%s" currently has bids:' % (criterion['adGroupId'], criterion['criterion']['id'])) for bid in criterion['biddingStrategyConfiguration']['bids']: - print('\tType: "%s", value: %s' % (bid['Bids.Type'],) - bid['bid']['microAmount']) + print('\tType: "%s", value: %s' % (bid['Bids.Type']), bid['bid']['microAmount']) else: print('No ad group criteria were updated.') From ccef6ce257ebf377289a93827d8761459c2aa16c Mon Sep 17 00:00:00 2001 From: David Wihl Date: Mon, 24 Aug 2020 11:37:06 -0400 Subject: [PATCH 160/180] Ad Manager v202008 release --- ChangeLog | 5 + .../create_traffic_adjustments.py | 143 ------------------ .../update_traffic_adjustments.py | 88 ----------- .../network_service/make_test_network.py | 4 - .../network_service/make_test_network.py | 4 - .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 65 ++++++++ .../create_traffic_forecast_segments.py | 72 +++++++++ .../get_all_forecast_adjustments.py} | 27 ++-- .../get_all_traffic_forecast_segments.py | 51 +++++++ ...djustments_for_traffic_forecast_segment.py | 57 +++++++ .../update_forecast_adjustments.py | 64 ++++++++ .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 70 +++++++++ .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 17 ++- .../get_recently_modified_content.py | 66 ++++++++ .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- .../network_service/make_test_network.py | 6 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 58 +++++++ .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../v202008/site_service/create_sites.py | 68 +++++++++ .../site_service/get_all_sites.py} | 29 ++-- .../get_sites_requiring_approval.py | 50 ++++++ .../site_service/submit_sites_for_approval.py | 44 ++++++ .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 6 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- .../basic_operations/update_keyword.py | 3 +- googleads/ad_manager.py | 34 +++-- googleads/common.py | 2 +- tests/common_test.py | 2 +- 204 files changed, 1001 insertions(+), 570 deletions(-) delete mode 100755 examples/ad_manager/v201911/adjustment_service/create_traffic_adjustments.py delete mode 100755 examples/ad_manager/v201911/adjustment_service/update_traffic_adjustments.py rename examples/ad_manager/{v201911 => v202008}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v201911 => v202008}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v201911 => v202008}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v201911 => v202008}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v201911 => v202008}/activity_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v201911 => v202008}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v201911 => v202008}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v201911 => v202008}/activity_service/update_activities.py (96%) create mode 100755 examples/ad_manager/v202008/adjustment_service/create_forecast_adjustments.py create mode 100755 examples/ad_manager/v202008/adjustment_service/create_traffic_forecast_segments.py rename examples/ad_manager/{v201911/adjustment_service/get_all_traffic_adjustments.py => v202008/adjustment_service/get_all_forecast_adjustments.py} (63%) create mode 100755 examples/ad_manager/v202008/adjustment_service/get_all_traffic_forecast_segments.py create mode 100755 examples/ad_manager/v202008/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py create mode 100755 examples/ad_manager/v202008/adjustment_service/update_forecast_adjustments.py rename examples/ad_manager/{v201911 => v202008}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v201911 => v202008}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v201911 => v202008}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v201911 => v202008}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v201911 => v202008}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v201911 => v202008}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v201911 => v202008}/cdn_configuration_service/get_all_cdn_configurations.py (93%) create mode 100755 examples/ad_manager/v202008/cms_metadata_service/activate_cms_metadata_values.py rename examples/ad_manager/{v201911 => v202008}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v201911 => v202008}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v201911 => v202008}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v201911 => v202008}/company_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/company_service/create_companies.py (99%) rename examples/ad_manager/{v201911 => v202008}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v201911 => v202008}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v201911 => v202008}/company_service/update_companies.py (96%) rename examples/ad_manager/{v201911 => v202008}/contact_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v201911 => v202008}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v201911 => v202008}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v201911 => v202008}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v201911 => v202008}/content_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/content_service/get_all_content.py (74%) create mode 100755 examples/ad_manager/v202008/content_service/get_recently_modified_content.py rename examples/ad_manager/{v201911 => v202008}/creative_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v201911 => v202008}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v201911 => v202008}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v201911 => v202008}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v201911 => v202008}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v201911 => v202008}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v201911 => v202008}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v201911 => v202008}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v201911 => v202008}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v201911 => v202008}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v201911 => v202008}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v201911 => v202008}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v201911 => v202008}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v201911 => v202008}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v201911 => v202008}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v201911 => v202008}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v201911 => v202008}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v201911 => v202008}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v201911 => v202008}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v201911 => v202008}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v201911 => v202008}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v201911 => v202008}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v201911 => v202008}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v201911 => v202008}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v201911 => v202008}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v201911 => v202008}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v201911 => v202008}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v201911 => v202008}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v201911 => v202008}/custom_targeting_service/delete_custom_targeting_keys.py (93%) rename examples/ad_manager/{v201911 => v202008}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v201911 => v202008}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201911 => v202008}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v201911 => v202008}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v201911 => v202008}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v201911 => v202008}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v201911 => v202008}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v201911 => v202008}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v201911 => v202008}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v201911 => v202008}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v201911 => v202008}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v201911 => v202008}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v201911 => v202008}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v201911 => v202008}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v201911 => v202008}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v201911 => v202008}/label_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/label_service/create_labels.py (99%) rename examples/ad_manager/{v201911 => v202008}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v201911 => v202008}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v201911 => v202008}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v201911 => v202008}/label_service/update_labels.py (96%) rename examples/ad_manager/{v201911 => v202008}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v201911 => v202008}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v201911 => v202008}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v201911 => v202008}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v201911 => v202008}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v201911 => v202008}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v201911 => v202008}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v201911 => v202008}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v201911 => v202008}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v201911 => v202008}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v201911 => v202008}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v201911 => v202008}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v201911 => v202008}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v201911 => v202008}/network_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v201911 => v202008}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v201911 => v202008}/network_service/make_test_network.py (92%) rename examples/ad_manager/{v201911 => v202008}/order_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v201911 => v202008}/order_service/create_orders.py (99%) rename examples/ad_manager/{v201911 => v202008}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v201911 => v202008}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v201911 => v202008}/order_service/update_orders.py (97%) rename examples/ad_manager/{v201911 => v202008}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v201911 => v202008}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v201911 => v202008}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v201911 => v202008}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v201911 => v202008}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v201911 => v202008}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v201911 => v202008}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v201911 => v202008}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v201911 => v202008}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v201911 => v202008}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v201911 => v202008}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v201911 => v202008}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v201911 => v202008}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v201911 => v202008}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v201911 => v202008}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v201911 => v202008}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v201911 => v202008}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v201911 => v202008}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v201911 => v202008}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v201911 => v202008}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v201911 => v202008}/publisher_query_language_service/get_line_items_named_like.py (96%) create mode 100755 examples/ad_manager/v202008/publisher_query_language_service/get_mcm_earnings.py rename examples/ad_manager/{v201911 => v202008}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v201911 => v202008}/report_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v201911 => v202008}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v201911 => v202008}/report_service/run_inventory_report.py (97%) rename examples/ad_manager/{v201911 => v202008}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v201911 => v202008}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v201911 => v202008}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v201911 => v202008}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v201911 => v202008}/report_service/run_saved_query.py (94%) create mode 100755 examples/ad_manager/v202008/site_service/create_sites.py rename examples/ad_manager/{v201911/targeting_preset_service/get_all_targeting_presets.py => v202008/site_service/get_all_sites.py} (57%) create mode 100755 examples/ad_manager/v202008/site_service/get_sites_requiring_approval.py create mode 100755 examples/ad_manager/v202008/site_service/submit_sites_for_approval.py rename examples/ad_manager/{v201911 => v202008}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v201911 => v202008}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v201911 => v202008}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v201911 => v202008}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v201908 => v202008}/targeting_preset_service/get_all_targeting_presets.py (90%) rename examples/ad_manager/{v201911 => v202008}/team_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/team_service/create_teams.py (96%) rename examples/ad_manager/{v201911 => v202008}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v201911 => v202008}/team_service/update_teams.py (94%) rename examples/ad_manager/{v201911 => v202008}/user_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/user_service/create_users.py (96%) rename examples/ad_manager/{v201911 => v202008}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v201911 => v202008}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v201911 => v202008}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v201911 => v202008}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v201911 => v202008}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v201911 => v202008}/user_service/update_users.py (92%) rename examples/ad_manager/{v201911 => v202008}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v201911 => v202008}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v201911 => v202008}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v201911 => v202008}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v201911 => v202008}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v201911 => v202008}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index aa2fd188..c7a77f83 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +25.0.0 -- 08/18/2020 +* Added support for Ad Manager v202008. +* Removed support for Ad Manager v201908. +* Removed examples for Ad Manager v201911. + 24.1.0 -- 07/13/2020 * Added 'GoogleCredentialsClient' class to re-use an OAuth2 credentials object diff --git a/examples/ad_manager/v201911/adjustment_service/create_traffic_adjustments.py b/examples/ad_manager/v201911/adjustment_service/create_traffic_adjustments.py deleted file mode 100755 index 6fcece38..00000000 --- a/examples/ad_manager/v201911/adjustment_service/create_traffic_adjustments.py +++ /dev/null @@ -1,143 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2019 Google LLC -# -# 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 adds or replaces a forecast adjustment. - -The adjustment will affect 1920x1080 video traffic in the United States. -""" - -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v201911') - network_service = client.GetService('NetworkService', version='v201911') - - # Get the root ad unit id to target the whole site. - current_network = network_service.getCurrentNetwork() - root_ad_unit_id = current_network['effectiveRootAdUnitId'] - - # Create inventory targeting. - inventory_targeting = { - 'targetedAdUnits': [{ - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id - }] - } - - # Create geo targeting. When using geo targeting with the adjustment service, - # only locations of type COUNTRY are supported. You can download the latest - # geo targets at https://developers.google.com/ad-manager/api/geotargets. - geo_targeting = { - 'targetedLocations': [{ - 'id': 2840 - }] # USA. - } - - # Create ad unit size to define the slice of inventory affected by the - # traffic adjustment. - ad_unit_size = { - 'size': { - 'width': 1920, - 'height': 1080 - }, - 'environmentType': 'VIDEO_PLAYER' - } - - # Create a new historical adjustment targeting next year's January with 105% - # of the traffic of this year's January. - this_january = { - 'startDate': datetime.date(datetime.date.today().year, 1, 1), - 'endDate': datetime.date(datetime.date.today().year, 1, 31) - } - next_january = { - 'startDate': datetime.date(datetime.date.today().year + 1, 1, 1), - 'endDate': datetime.date(datetime.date.today().year + 1, 1, 31) - } - - january_segment = { - 'basisType': 'HISTORICAL', - 'historicalAdjustment': { - 'targetDateRange': next_january, - 'referenceDateRange': this_january, - 'milliPercentMultiplier': 105000 - } - } - - # Create a new absolute adjustment of 500,000 ad opportunities for Christmas - # and 1,000,000 opportunities for Boxing Day of next year. - christmas_day = datetime.date(datetime.date.today().year + 1, 12, 25) - boxing_day = christmas_day + datetime.timedelta(days=1) - holiday_range = {'startDate': christmas_day, 'endDate': boxing_day} - - holiday_segment = { - 'basisType': 'ABSOLUTE', - 'adjustmentTimeSeries': { - 'timeSeriesDateRange': holiday_range, - 'timeSeriesValues': [500000, 1000000], # xsd:long[] - 'valuePeriodType': 'DAILY' - } - } - - # Create a new absolute adjustment of 900,000 ad opportunities for the first - # week of September of next year. - first_week_of_september = { - 'startDate': datetime.date(datetime.date.today().year + 1, 9, 1), - 'endDate': datetime.date(datetime.date.today().year + 1, 9, 7) - } - - september_segment = { - 'basisType': 'ABSOLUTE', - 'adjustmentTimeSeries': { - 'timeSeriesDateRange': first_week_of_september, - 'timeSeriesValues': [900000], - 'valuePeriodType': 'CUSTOM' - } - } - - # Create traffic forecast adjustment object. - adjustment_segments = [january_segment, holiday_segment, september_segment] - adjustment = { - 'filterCriteria': { - 'targeting': { - 'inventoryTargeting': inventory_targeting, - 'geoTargeting': geo_targeting - }, - 'adUnitSizes': [ad_unit_size] - }, - 'forecastAdjustmentSegments': adjustment_segments - } - - # Create or update the traffic adjustment for the given filter criteria on - # the server. - updated_adjustments = adjustment_service.updateTrafficAdjustments( - [adjustment]) - - # Display the results. - for updated_adjustment in updated_adjustments: - print('Traffic forecast adjustment with id %d and %d segments was ' - 'created.' % (updated_adjustment['id'], - len(updated_adjustment['forecastAdjustmentSegments']))) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v201911/adjustment_service/update_traffic_adjustments.py b/examples/ad_manager/v201911/adjustment_service/update_traffic_adjustments.py deleted file mode 100755 index 475a9dd1..00000000 --- a/examples/ad_manager/v201911/adjustment_service/update_traffic_adjustments.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2019 Google LLC -# -# 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 adds a historical adjustment of 110% for New Years Day traffic. -""" - -from __future__ import print_function -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' - - -def main(client, adjustment_id): - # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v201911') - - # Create a statement to select a single traffic forecast adjustment by id. - statement = ( - ad_manager.StatementBuilder( - version='v201911').Where('id = :id').WithBindVariable( - 'id', adjustment_id)) - - # Get the forecast traffic adjustment. - response = adjustment_service.getTrafficAdjustmentsByStatement( - statement.ToStatement()) - - # Create a new historical adjustment segment for New Year's Day. - this_new_years = datetime.date(datetime.date.today().year, 12, 31) - next_new_years = datetime.date(datetime.date.today().year + 1, 12, 31) - - new_years_segment = { - 'basisType': 'HISTORICAL', - 'historicalAdjustment': { - 'targetDateRange': { - 'startDate': next_new_years, - 'endDate': next_new_years - }, - 'referenceDateRange': { - 'startDate': this_new_years, - 'endDate': this_new_years - }, - 'milliPercentMultiplier': 110000 - } - } - - if 'results' in response and len(response['results']): - # Update each local traffic adjustment. - updated_adjustments = [] - for adjustment in response['results']: - adjustment['forecastAdjustmentSegments'].append(new_years_segment) - updated_adjustments.append(adjustment) - - # Update traffic adjustments remotely. - adjustments = adjustment_service.updateTrafficAdjustments( - updated_adjustments) - - # Display the results. - if adjustments: - for adjustment in adjustments: - print('Traffic forecast adjustment with id %d and %d segments was ' - 'created.' % (adjustment['id'], - len(adjustment['forecastAdjustmentSegments']))) - else: - print('No traffic adjustments were updated.') - else: - print('No traffic adjustments found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v202002/network_service/make_test_network.py b/examples/ad_manager/v202002/network_service/make_test_network.py index e0f4cf6c..691bf6b5 100755 --- a/examples/ad_manager/v202002/network_service/make_test_network.py +++ b/examples/ad_manager/v202002/network_service/make_test_network.py @@ -22,10 +22,6 @@ is not associated with any other Ad Manager test networks. Once this network is created, you can supply the network code in your settings to make calls to other services. - -Alternatively, if you do not wish to run this example, you can create a test -network at: -https://dfp-playground.appspot.com """ diff --git a/examples/ad_manager/v202005/network_service/make_test_network.py b/examples/ad_manager/v202005/network_service/make_test_network.py index 35e2da0d..edccbad7 100755 --- a/examples/ad_manager/v202005/network_service/make_test_network.py +++ b/examples/ad_manager/v202005/network_service/make_test_network.py @@ -22,10 +22,6 @@ is not associated with any other Ad Manager test networks. Once this network is created, you can supply the network code in your settings to make calls to other services. - -Alternatively, if you do not wish to run this example, you can create a test -network at: -https://dfp-playground.appspot.com """ diff --git a/examples/ad_manager/v201911/activity_group_service/__init__.py b/examples/ad_manager/v202008/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/activity_group_service/__init__.py rename to examples/ad_manager/v202008/activity_group_service/__init__.py diff --git a/examples/ad_manager/v201911/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202008/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v201911/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202008/activity_group_service/create_activity_groups.py index 2a5c55ae..a5f5b88f 100755 --- a/examples/ad_manager/v201911/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202008/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201911') + version='v202008') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v201911/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202008/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v201911/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202008/activity_group_service/get_active_activity_groups.py index e6463e3b..6895dcb5 100755 --- a/examples/ad_manager/v201911/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202008/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201911') + 'ActivityGroupService', version='v202008') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201911/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202008/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v201911/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202008/activity_group_service/get_all_activity_groups.py index 914989bd..bf0c3cbd 100755 --- a/examples/ad_manager/v201911/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202008/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v201911') + 'ActivityGroupService', version='v202008') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v201911/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202008/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v201911/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202008/activity_group_service/update_activity_groups.py index 59f5ae55..17cdcb8a 100755 --- a/examples/ad_manager/v201911/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202008/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v201911') + version='v202008') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/activity_service/__init__.py b/examples/ad_manager/v202008/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/activity_service/__init__.py rename to examples/ad_manager/v202008/activity_service/__init__.py diff --git a/examples/ad_manager/v201911/activity_service/create_activities.py b/examples/ad_manager/v202008/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v201911/activity_service/create_activities.py rename to examples/ad_manager/v202008/activity_service/create_activities.py index 2a3213da..18ce6f0e 100755 --- a/examples/ad_manager/v201911/activity_service/create_activities.py +++ b/examples/ad_manager/v202008/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201911') + activity_service = client.GetService('ActivityService', version='v202008') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v201911/activity_service/get_active_activities.py b/examples/ad_manager/v202008/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v201911/activity_service/get_active_activities.py rename to examples/ad_manager/v202008/activity_service/get_active_activities.py index b5653747..3ea9bf55 100755 --- a/examples/ad_manager/v201911/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202008/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201911') + activity_service = client.GetService('ActivityService', version='v202008') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201911/activity_service/get_all_activities.py b/examples/ad_manager/v202008/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v201911/activity_service/get_all_activities.py rename to examples/ad_manager/v202008/activity_service/get_all_activities.py index 155735f8..233e43c1 100755 --- a/examples/ad_manager/v201911/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202008/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201911') + activity_service = client.GetService('ActivityService', version='v202008') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v201911/activity_service/update_activities.py b/examples/ad_manager/v202008/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v201911/activity_service/update_activities.py rename to examples/ad_manager/v202008/activity_service/update_activities.py index ffe8c629..7fdac9bf 100755 --- a/examples/ad_manager/v201911/activity_service/update_activities.py +++ b/examples/ad_manager/v202008/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v201911') + activity_service = client.GetService('ActivityService', version='v202008') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202008/adjustment_service/create_forecast_adjustments.py new file mode 100755 index 00000000..69f3353f --- /dev/null +++ b/examples/ad_manager/v202008/adjustment_service/create_forecast_adjustments.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a forecast adjustment for New Year's Day traffic.""" + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_TRAFFIC_FORECAST_SEGMENT_ID_HERE' + + +def main(client, traffic_forecast_segment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202008') + + # Create a new forecast adjustment for New Year's Day traffic. + this_new_years = datetime.date(datetime.date.today().year, 1, 1) + next_new_years = datetime.date(datetime.date.today().year + 1, 1, 1) + + forecast = { + 'name': 'Forecast adjustment #%s' % uuid.uuid4(), + 'trafficForecastSegmentId': traffic_forecast_segment_id, + 'dateRange': { + 'startDate': next_new_years, + 'endDate': next_new_years + }, + 'status': 'ACTIVE', + 'volumeType': 'HISTORICAL_BASIS_VOLUME', + 'historicalBasisVolumeSettings': { + 'useParentTrafficForecastSegmentTargeting': True, + 'historicalDateRange': { + 'startDate': this_new_years, + 'endDate': this_new_years + }, + 'multiplierMilliPercent': 110000 + } + } + + forecasts = adjustment_service.createForecastAdjustments([forecast]) + + for forecast in forecasts: + print('Forecast adjustment with id %d and name "%s" was created.' % ( + forecast['id'], forecast['name'] + )) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TRAFFIC_FORECAST_SEGMENT_ID) diff --git a/examples/ad_manager/v202008/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202008/adjustment_service/create_traffic_forecast_segments.py new file mode 100755 index 00000000..f0ab29d9 --- /dev/null +++ b/examples/ad_manager/v202008/adjustment_service/create_traffic_forecast_segments.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a traffic forecast segment for all ad units in the U.S. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service and the network service. + adjustment_service = client.GetService('AdjustmentService', version='v202008') + network_service = client.GetService('NetworkService', version='v202008') + + # Get the root ad unit id to target the whole site. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create inventory targeting. + inventory_targeting = { + 'targetedAdUnits': [{ + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id + }] + } + + # Create targeting for United States traffic. + geo_targeting = { + 'targetedLocations': [{ + 'id': 2840 + }] + } + + # Create traffic forecast segment object. + segment = { + 'name': 'Forecast segment #%s' % uuid.uuid4(), + 'targeting': { + 'inventoryTargeting': inventory_targeting, + 'geoTargeting': geo_targeting + } + } + + # Create the traffic forecast segment on the server. + segments = adjustment_service.createTrafficForecastSegments([segment]) + + # Display the results. + for segment in segments: + print('Traffic forecast segment with id %d and %d forecast adjustments was ' + 'created.' % (segment['id'], + segment['forecastAdjustmentCount'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201911/adjustment_service/get_all_traffic_adjustments.py b/examples/ad_manager/v202008/adjustment_service/get_all_forecast_adjustments.py similarity index 63% rename from examples/ad_manager/v201911/adjustment_service/get_all_traffic_adjustments.py rename to examples/ad_manager/v202008/adjustment_service/get_all_forecast_adjustments.py index 6f9b7fe7..a2297915 100755 --- a/examples/ad_manager/v201911/adjustment_service/get_all_traffic_adjustments.py +++ b/examples/ad_manager/v202008/adjustment_service/get_all_forecast_adjustments.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2019 Google LLC +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all traffic adjustments.""" - -from __future__ import print_function +"""This example gets all forecast adjustments.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -24,22 +22,23 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v201911') + adjustment_service = client.GetService('AdjustmentService', version='v202008') - # Create a statement to get all forecast traffic adjustments. - statement = ad_manager.StatementBuilder(version='v201911') + # Create a statement to get all forecast adjustments. + statement = ad_manager.StatementBuilder(version='v202008') - # Retrieve a small number of traffic adjustments at a time, paging - # through until all traffic adjustments have been retrieved. + # Retrieve a small number of forecast adjustments at a time, paging + # through until all forecast adjustments have been retrieved. while True: - response = adjustment_service.getTrafficAdjustmentsByStatement( + response = adjustment_service.getForecastAdjustmentsByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): for adjustment in response['results']: - # Print out some information for each traffic adjustment. - print('Traffic forecast adjustment with id %d and %d segments was ' - 'found.' % (adjustment['id'], - len(adjustment['forecastAdjustmentSegments']))) + # Print out some information for each forecast adjustment. + print('Forecast adjustment with id %d and name "%s" belonging to ' + 'forecast segment %d was found.' % + (adjustment['id'], adjustment['name'], + adjustment['trafficForecastSegmentId'])) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v202008/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202008/adjustment_service/get_all_traffic_forecast_segments.py new file mode 100755 index 00000000..4692ef71 --- /dev/null +++ b/examples/ad_manager/v202008/adjustment_service/get_all_traffic_forecast_segments.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 traffic forecast segments.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202008') + + # Create a statement to get all traffic forecast segments. + statement = ad_manager.StatementBuilder(version='v202008') + + # Retrieve a small number of segments at a time, paging through until all + # segments have been retrieved. + while True: + response = adjustment_service.getTrafficForecastSegmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for segment in response['results']: + # Print out some information for each traffic forecast segment. + print('Traffic forecast segment with id %d and name "%s" was found ' % ( + segment['id'], segment['name'], + )) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202008/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202008/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py new file mode 100755 index 00000000..8e11b97b --- /dev/null +++ b/examples/ad_manager/v202008/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 forecast adjustments for a traffic forecast segment.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_FORECAST_SEGMENT_ID_HERE' + + +def main(client, traffic_forecast_segment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202008') + + # Create a statement to get forecast adjustments for a given traffic forecast + # segment id. + statement = ad_manager.StatementBuilder(version='v202008').Where( + 'trafficForecastSegmentId = :segmentId').WithBindVariable( + 'segmentId', traffic_forecast_segment_id) + + # Retrieve a small number of forecast adjustments at a time, paging + # through until all forecast adjustments have been retrieved. + while True: + response = adjustment_service.getForecastAdjustmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for adjustment in response['results']: + # Print out some information for each traffic adjustment. + print('Forecast adjustment with id %d and name "%s" belonging to ' + 'forecast segment %d was found.' % + (adjustment['id'], adjustment['name'], + adjustment['trafficForecastSegmentId'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, int(TRAFFIC_FORECAST_SEGMENT_ID)) diff --git a/examples/ad_manager/v202008/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202008/adjustment_service/update_forecast_adjustments.py new file mode 100755 index 00000000..8980fa0e --- /dev/null +++ b/examples/ad_manager/v202008/adjustment_service/update_forecast_adjustments.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 updates a forecast adjustment's name.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' + + +def main(client, adjustment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202008') + + # Create a statement to select a single forecast adjustment by id. + statement = ( + ad_manager.StatementBuilder( + version='v202008').Where('id = :id').WithBindVariable( + 'id', adjustment_id)) + + # Get the forecast adjustment. + response = adjustment_service.getForecastAdjustmentsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local forecast adjustment's name. + updated_adjustments = [] + for adjustment in response['results']: + adjustment['name'] += ' (updated)' + updated_adjustments.append(adjustment) + + # Update the forecast adjustment on the server. + adjustments = adjustment_service.updateForecastAdjustments( + updated_adjustments) + + # Display the results. + if adjustments: + for adjustment in adjustments: + print('Forecast adjustment with id %d and name "%s" was updated' % ( + adjustment['id'], adjustment['name'])) + else: + print('No forecast adjustments were updated.') + else: + print('No forecast adjustments found to update.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v201911/audience_segment_service/__init__.py b/examples/ad_manager/v202008/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/audience_segment_service/__init__.py rename to examples/ad_manager/v202008/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v201911/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202008/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v201911/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202008/audience_segment_service/create_audience_segments.py index ade57d67..24e9ffab 100755 --- a/examples/ad_manager/v201911/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202008/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201911') - network_service = client.GetService('NetworkService', version='v201911') + 'AudienceSegmentService', version='v202008') + network_service = client.GetService('NetworkService', version='v202008') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v201911/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202008/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v201911/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202008/audience_segment_service/get_all_audience_segments.py index 999bdd0a..c28f2350 100755 --- a/examples/ad_manager/v201911/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202008/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201911') + 'AudienceSegmentService', version='v202008') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v201911/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202008/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v201911/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202008/audience_segment_service/get_first_party_audience_segments.py index 0da69f84..ae1b59fb 100755 --- a/examples/ad_manager/v201911/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202008/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201911') + 'AudienceSegmentService', version='v202008') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v201911/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202008/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v201911/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202008/audience_segment_service/populate_first_party_audience_segments.py index 573dc49d..c9393d57 100755 --- a/examples/ad_manager/v201911/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202008/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201911') + 'AudienceSegmentService', version='v202008') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201911/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202008/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v201911/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202008/audience_segment_service/update_audience_segments.py index 283a6ce9..c5b75f6e 100755 --- a/examples/ad_manager/v201911/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202008/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v201911') + 'AudienceSegmentService', version='v202008') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v201911/cdn_configuration_service/__init__.py b/examples/ad_manager/v202008/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202008/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v201911/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202008/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v201911/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202008/cdn_configuration_service/create_cdn_configurations.py index 48472749..d63642d4 100755 --- a/examples/ad_manager/v201911/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202008/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201911') + version='v202008') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v201911/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202008/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v201911/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202008/cdn_configuration_service/get_all_cdn_configurations.py index 3eabcadd..83212c6e 100755 --- a/examples/ad_manager/v201911/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202008/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v201911') + version='v202008') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202008/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202008/cms_metadata_service/activate_cms_metadata_values.py new file mode 100755 index 00000000..b0b06c1d --- /dev/null +++ b/examples/ad_manager/v202008/cms_metadata_service/activate_cms_metadata_values.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 activates CMS Metadata Values for a particular CMS Metadata Key. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the CMS Metadata Key on which to activate the CMS Metadata +# Values. +CMS_METADATA_KEY_ID = 'INSERT_CMS_METADATA_KEY_ID_HERE' + + +def main(client, cms_metadata_key_id): + # Initialize appropriate service. + cms_metadata_service = client.GetService('CmsMetadataService', + version='v202008') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v202008') + .Where('cmsKeyId = :cmsKeyId AND status = :status') + .WithBindVariable('status', 'INACTIVE') + .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) + + values_activated = 0 + + # Get CMS Metadata Values by statement. + while True: + response = cms_metadata_service.getCmsMetadataValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_value in response['results']: + print('CMS Metadata Value with id "%s" and name "%s" will be ' + 'activated.' % (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'])) + + # Perform action. + result = cms_metadata_service.performCmsMetadataValueAction( + {'xsi_type': 'ActivateCmsMetadataValues'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + values_activated += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if values_activated > 0: + print('Number of CMS Metadata Values activated: %s' % values_activated) + else: + print('No CMS Metadata Values were activated.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CMS_METADATA_KEY_ID) diff --git a/examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_keys.py index 9789b858..37c1abb8 100755 --- a/examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201911') + 'CmsMetadataService', version='v202008') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_values.py index 686c45b4..5c9ea8e0 100755 --- a/examples/ad_manager/v201911/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201911') + 'CmsMetadataService', version='v202008') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v201911/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202008/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v201911/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202008/cms_metadata_service/get_cms_metadata_values_for_key.py index 0f3ac26b..4ec5ee89 100755 --- a/examples/ad_manager/v201911/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202008/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v201911') + 'CmsMetadataService', version='v202008') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v201911').Where( + ad_manager.StatementBuilder(version='v202008').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v201911/company_service/__init__.py b/examples/ad_manager/v202008/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/company_service/__init__.py rename to examples/ad_manager/v202008/company_service/__init__.py diff --git a/examples/ad_manager/v201911/company_service/create_companies.py b/examples/ad_manager/v202008/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v201911/company_service/create_companies.py rename to examples/ad_manager/v202008/company_service/create_companies.py index 922225a0..4cf46596 100755 --- a/examples/ad_manager/v201911/company_service/create_companies.py +++ b/examples/ad_manager/v202008/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201911') + company_service = client.GetService('CompanyService', version='v202008') # Create company objects. companies = [ diff --git a/examples/ad_manager/v201911/company_service/get_advertisers.py b/examples/ad_manager/v202008/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v201911/company_service/get_advertisers.py rename to examples/ad_manager/v202008/company_service/get_advertisers.py index 85d6f902..a1c8f007 100755 --- a/examples/ad_manager/v201911/company_service/get_advertisers.py +++ b/examples/ad_manager/v202008/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201911') + company_service = client.GetService('CompanyService', version='v202008') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v201911/company_service/get_all_companies.py b/examples/ad_manager/v202008/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v201911/company_service/get_all_companies.py rename to examples/ad_manager/v202008/company_service/get_all_companies.py index b4b955e8..a2ecae6e 100755 --- a/examples/ad_manager/v201911/company_service/get_all_companies.py +++ b/examples/ad_manager/v202008/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201911') + company_service = client.GetService('CompanyService', version='v202008') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v201911/company_service/update_companies.py b/examples/ad_manager/v202008/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v201911/company_service/update_companies.py rename to examples/ad_manager/v202008/company_service/update_companies.py index f4797e7f..99fbfb74 100755 --- a/examples/ad_manager/v201911/company_service/update_companies.py +++ b/examples/ad_manager/v202008/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v201911') + company_service = client.GetService('CompanyService', version='v202008') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/contact_service/__init__.py b/examples/ad_manager/v202008/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/contact_service/__init__.py rename to examples/ad_manager/v202008/contact_service/__init__.py diff --git a/examples/ad_manager/v201911/contact_service/create_contacts.py b/examples/ad_manager/v202008/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v201911/contact_service/create_contacts.py rename to examples/ad_manager/v202008/contact_service/create_contacts.py index e11e5b1b..26bbb911 100755 --- a/examples/ad_manager/v201911/contact_service/create_contacts.py +++ b/examples/ad_manager/v202008/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201911') + contact_service = client.GetService('ContactService', version='v202008') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v201911/contact_service/get_all_contacts.py b/examples/ad_manager/v202008/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v201911/contact_service/get_all_contacts.py rename to examples/ad_manager/v202008/contact_service/get_all_contacts.py index 65cedd76..2ac423f6 100755 --- a/examples/ad_manager/v201911/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202008/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201911') + contact_service = client.GetService('ContactService', version='v202008') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v201911/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202008/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v201911/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202008/contact_service/get_uninvited_contacts.py index c6367670..1a2c576a 100755 --- a/examples/ad_manager/v201911/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202008/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201911') + contact_service = client.GetService('ContactService', version='v202008') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v201911/contact_service/update_contacts.py b/examples/ad_manager/v202008/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v201911/contact_service/update_contacts.py rename to examples/ad_manager/v202008/contact_service/update_contacts.py index 589d3687..b84f5eb4 100755 --- a/examples/ad_manager/v201911/contact_service/update_contacts.py +++ b/examples/ad_manager/v202008/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v201911') + contact_service = client.GetService('ContactService', version='v202008') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/content_service/__init__.py b/examples/ad_manager/v202008/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/content_service/__init__.py rename to examples/ad_manager/v202008/content_service/__init__.py diff --git a/examples/ad_manager/v201911/content_service/get_all_content.py b/examples/ad_manager/v202008/content_service/get_all_content.py similarity index 74% rename from examples/ad_manager/v201911/content_service/get_all_content.py rename to examples/ad_manager/v202008/content_service/get_all_content.py index 7ca2c6a3..25e6dba9 100755 --- a/examples/ad_manager/v201911/content_service/get_all_content.py +++ b/examples/ad_manager/v202008/content_service/get_all_content.py @@ -13,8 +13,8 @@ # 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 content. -""" + +"""This example gets all content.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v201911') + content_service = client.GetService('ContentService', version='v202008') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. @@ -34,8 +34,13 @@ def main(client): if 'results' in response and len(response['results']): for content in response['results']: # Print out some information for each content. - print('Content with ID "%d" and name "%s" was found.\n' % - (content['id'], content['name'].encode('utf-8'))) + content_description = ('Content with ID "%d" and name "%s"' % + (content['id'], content['name'].encode('utf-8'))) + if content['contentBundleIds']: + content_description += (' belonging to bundle IDs %s' % + content['contentBundleIds']) + content_description += ' was found.' + print(content_description) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v202008/content_service/get_recently_modified_content.py b/examples/ad_manager/v202008/content_service/get_recently_modified_content.py new file mode 100755 index 00000000..dca5c66b --- /dev/null +++ b/examples/ad_manager/v202008/content_service/get_recently_modified_content.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2016 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 recently modified content.""" + +# Import appropriate modules from the client library. +from datetime import datetime +from datetime import timedelta + +from googleads import ad_manager +import pytz + + +def main(client): + # Initialize appropriate service. + content_service = client.GetService('ContentService', version='v202008') + + last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) + - timedelta(days=1)) + + # Create a statement to get recently modified content based on + # lastModifiedDateTime. Changes to content bundle associations will update + # the lastModifiedDateTime, but CMS metadata changes may not change the + # lastModifiedDateTime. + statement = (ad_manager.StatementBuilder(version='v202008') + .Where('lastModifiedDateTime >= :lastModifiedDateTime') + .WithBindVariable('lastModifiedDateTime', last_modified)) + + # Retrieve a small amount of content at a time, paging + # through until all content have been retrieved. + while True: + response = content_service.getContentByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for content in response['results']: + # Print out some information for each content. + content_description = ('Content with ID "%d" and name "%s"' % + (content['id'], content['name'].encode('utf-8'))) + if content['contentBundleIds']: + content_description += (' belonging to bundle IDs %s' % + content['contentBundleIds']) + content_description += ' was found.' + print(content_description) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201911/creative_service/__init__.py b/examples/ad_manager/v202008/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/creative_service/__init__.py rename to examples/ad_manager/v202008/creative_service/__init__.py diff --git a/examples/ad_manager/v201911/creative_service/copy_image_creatives.py b/examples/ad_manager/v202008/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v201911/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202008/creative_service/copy_image_creatives.py index a8d65e6e..be63f875 100755 --- a/examples/ad_manager/v201911/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202008/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201911') + creative_service = client.GetService('CreativeService', version='v202008') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v201911/creative_service/create_creative_from_template.py b/examples/ad_manager/v202008/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v201911/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202008/creative_service/create_creative_from_template.py index 9bb7a8fa..e5f1e75c 100755 --- a/examples/ad_manager/v201911/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202008/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201911') + creative_service = client.GetService('CreativeService', version='v202008') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v201911/creative_service/create_creatives.py b/examples/ad_manager/v202008/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v201911/creative_service/create_creatives.py rename to examples/ad_manager/v202008/creative_service/create_creatives.py index 69423a67..db8b5bc2 100755 --- a/examples/ad_manager/v201911/creative_service/create_creatives.py +++ b/examples/ad_manager/v202008/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201911') + creative_service = client.GetService('CreativeService', version='v202008') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v201911/creative_service/create_custom_creative.py b/examples/ad_manager/v202008/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v201911/creative_service/create_custom_creative.py rename to examples/ad_manager/v202008/creative_service/create_custom_creative.py index 539ef47e..b24463ef 100755 --- a/examples/ad_manager/v201911/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202008/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201911') + creative_service = client.GetService('CreativeService', version='v202008') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v201911/creative_service/create_native_creative.py b/examples/ad_manager/v202008/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v201911/creative_service/create_native_creative.py rename to examples/ad_manager/v202008/creative_service/create_native_creative.py index c1082ecf..cdae3d2b 100755 --- a/examples/ad_manager/v201911/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202008/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201911') + creative_service = client.GetService('CreativeService', version='v202008') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v201911/creative_service/get_all_creatives.py b/examples/ad_manager/v202008/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v201911/creative_service/get_all_creatives.py rename to examples/ad_manager/v202008/creative_service/get_all_creatives.py index 6d65a061..feb40c53 100755 --- a/examples/ad_manager/v201911/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202008/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201911') + creative_service = client.GetService('CreativeService', version='v202008') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v201911/creative_service/get_image_creatives.py b/examples/ad_manager/v202008/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v201911/creative_service/get_image_creatives.py rename to examples/ad_manager/v202008/creative_service/get_image_creatives.py index fa2a16e0..27a27881 100755 --- a/examples/ad_manager/v201911/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202008/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201911') + creative_service = client.GetService('CreativeService', version='v202008') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v201911/creative_service/update_creatives.py b/examples/ad_manager/v202008/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v201911/creative_service/update_creatives.py rename to examples/ad_manager/v202008/creative_service/update_creatives.py index d3eb4817..c98903c1 100755 --- a/examples/ad_manager/v201911/creative_service/update_creatives.py +++ b/examples/ad_manager/v202008/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v201911') + creative_service = client.GetService('CreativeService', version='v202008') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v201911/creative_set_service/__init__.py b/examples/ad_manager/v202008/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/creative_set_service/__init__.py rename to examples/ad_manager/v202008/creative_set_service/__init__.py diff --git a/examples/ad_manager/v201911/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202008/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v201911/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202008/creative_set_service/associate_creative_set_to_line_item.py index d134ca04..3bcf1d82 100755 --- a/examples/ad_manager/v201911/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202008/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201911') + 'LineItemCreativeAssociationService', version='v202008') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v201911/creative_set_service/create_creative_set.py b/examples/ad_manager/v202008/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v201911/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202008/creative_set_service/create_creative_set.py index 36c46bc6..dd5c4f22 100755 --- a/examples/ad_manager/v201911/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202008/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201911') + version='v202008') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v201911/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202008/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v201911/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202008/creative_set_service/get_all_creative_sets.py index 6441d610..42e0f502 100755 --- a/examples/ad_manager/v201911/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202008/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201911') + 'CreativeSetService', version='v202008') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v201911/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202008/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v201911/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202008/creative_set_service/get_creative_sets_for_master_creative.py index 47600b95..238c75b9 100755 --- a/examples/ad_manager/v201911/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202008/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v201911') + 'CreativeSetService', version='v202008') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v201911/creative_set_service/update_creative_set.py b/examples/ad_manager/v202008/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v201911/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202008/creative_set_service/update_creative_set.py index fb3f2c9f..f8962376 100755 --- a/examples/ad_manager/v201911/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202008/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v201911') + version='v202008') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v201911/creative_template_service/__init__.py b/examples/ad_manager/v202008/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/creative_template_service/__init__.py rename to examples/ad_manager/v202008/creative_template_service/__init__.py diff --git a/examples/ad_manager/v201911/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202008/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v201911/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202008/creative_template_service/get_all_creative_templates.py index 1cdef040..dfa54f10 100755 --- a/examples/ad_manager/v201911/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202008/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201911') + 'CreativeTemplateService', version='v202008') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v201911/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202008/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v201911/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202008/creative_template_service/get_system_defined_creative_templates.py index f2ffd2a7..08b1a966 100755 --- a/examples/ad_manager/v201911/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202008/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v201911') + 'CreativeTemplateService', version='v202008') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v201911/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202008/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v201911/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202008/creative_wrapper_service/create_creative_wrappers.py index a7e1d7e0..1b143da6 100755 --- a/examples/ad_manager/v201911/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202008/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201911') + version='v202008') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v201911/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202008/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v201911/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202008/creative_wrapper_service/deactivate_creative_wrapper.py index 050a56a6..df59b6d4 100755 --- a/examples/ad_manager/v201911/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202008/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201911') + version='v202008') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201911/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202008/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201911/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202008/creative_wrapper_service/get_active_creative_wrappers.py index 8fe3a701..2a3e5572 100755 --- a/examples/ad_manager/v201911/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202008/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201911') + 'CreativeWrapperService', version='v202008') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201911/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202008/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v201911/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202008/creative_wrapper_service/get_all_creative_wrappers.py index 41d43849..a243be2a 100755 --- a/examples/ad_manager/v201911/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202008/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v201911') + 'CreativeWrapperService', version='v202008') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v201911/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202008/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v201911/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202008/creative_wrapper_service/update_creative_wrappers.py index 8edcd07e..fd6f17eb 100755 --- a/examples/ad_manager/v201911/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202008/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v201911') + version='v202008') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v201911/custom_field_service/__init__.py b/examples/ad_manager/v202008/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/custom_field_service/__init__.py rename to examples/ad_manager/v202008/custom_field_service/__init__.py diff --git a/examples/ad_manager/v201911/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202008/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v201911/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202008/custom_field_service/create_custom_field_options.py index d7f0f511..6c549904 100755 --- a/examples/ad_manager/v201911/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202008/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201911') + 'CustomFieldService', version='v202008') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v201911/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202008/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v201911/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202008/custom_field_service/create_custom_fields.py index b3b78240..1c1aebb2 100755 --- a/examples/ad_manager/v201911/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202008/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201911') + 'CustomFieldService', version='v202008') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v201911/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202008/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v201911/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202008/custom_field_service/deactivate_all_line_item_custom_fields.py index a6a7ac51..de6e97ff 100755 --- a/examples/ad_manager/v201911/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202008/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201911') + 'CustomFieldService', version='v202008') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201911/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202008/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v201911/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202008/custom_field_service/get_all_custom_fields.py index d6933693..a2a9e327 100755 --- a/examples/ad_manager/v201911/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202008/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201911') + 'CustomFieldService', version='v202008') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v201911/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202008/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v201911/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202008/custom_field_service/get_custom_fields_for_line_items.py index 10f0e004..a2d052e9 100755 --- a/examples/ad_manager/v201911/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202008/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201911') + 'CustomFieldService', version='v202008') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v201911/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202008/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v201911/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202008/custom_field_service/set_line_item_custom_field_value.py index c168149f..185292d4 100755 --- a/examples/ad_manager/v201911/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202008/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v201911') + 'CustomFieldService', version='v202008') - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v201911') + custom_field_statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v201911') + ad_manager.StatementBuilder(version='v202008') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v201911') + line_item_statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v201911/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202008/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v201911/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202008/custom_field_service/update_custom_fields.py index 933dcdc9..3c468a43 100755 --- a/examples/ad_manager/v201911/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202008/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v201911') + 'CustomFieldService', version='v202008') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v201911/custom_targeting_service/__init__.py b/examples/ad_manager/v202008/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/custom_targeting_service/__init__.py rename to examples/ad_manager/v202008/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v201911/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202008/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v201911/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202008/custom_targeting_service/create_custom_targeting_keys_and_values.py index e55df15d..bb7953e0 100755 --- a/examples/ad_manager/v201911/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202008/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201911') + 'CustomTargetingService', version='v202008') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_keys.py similarity index 93% rename from examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_keys.py index 41ddbd56..5a7e6a0a 100755 --- a/examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201911') + 'CustomTargetingService', version='v202008') - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v201911') + key_statement = (ad_manager.StatementBuilder(version='v202008') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_values.py index da495b9e..530746e2 100755 --- a/examples/ad_manager/v201911/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201911') + 'CustomTargetingService', version='v202008') - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v201911') + value_statement = (ad_manager.StatementBuilder(version='v202008') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v201911/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202008/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201911/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202008/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 478f87d8..56ca9285 100755 --- a/examples/ad_manager/v201911/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202008/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201911') + 'CustomTargetingService', version='v202008') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v201911') + targeting_key_statement = ad_manager.StatementBuilder(version='v202008') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v201911/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202008/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v201911/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202008/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index c1fb91af..87cab57e 100755 --- a/examples/ad_manager/v201911/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202008/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201911') + 'CustomTargetingService', version='v202008') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v201911') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202008') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_keys.py index 291e4ead..f557d748 100755 --- a/examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201911') + 'CustomTargetingService', version='v202008') - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_values.py index 52855cf0..87b8d040 100755 --- a/examples/ad_manager/v201911/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v201911') + 'CustomTargetingService', version='v202008') - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v201911/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202008/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v201911/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202008/forecast_service/get_availability_forecast.py index 4b226c9a..fc3e8ba7 100755 --- a/examples/ad_manager/v201911/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202008/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201911') - network_service = client.GetService('NetworkService', version='v201911') + forecast_service = client.GetService('ForecastService', version='v202008') + network_service = client.GetService('NetworkService', version='v202008') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v201911/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202008/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v201911/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202008/forecast_service/get_availability_forecast_for_line_item.py index de0a2f81..98dc503b 100755 --- a/examples/ad_manager/v201911/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202008/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201911') + forecast_service = client.GetService('ForecastService', version='v202008') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v201911/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202008/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v201911/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202008/forecast_service/get_delivery_forecast_for_line_items.py index 76c1de8e..2e01d79b 100755 --- a/examples/ad_manager/v201911/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202008/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v201911') + forecast_service = client.GetService('ForecastService', version='v202008') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v201911/inventory_service/__init__.py b/examples/ad_manager/v202008/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/inventory_service/__init__.py rename to examples/ad_manager/v202008/inventory_service/__init__.py diff --git a/examples/ad_manager/v201911/inventory_service/archive_ad_units.py b/examples/ad_manager/v202008/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v201911/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202008/inventory_service/archive_ad_units.py index 514317f9..7457a6af 100755 --- a/examples/ad_manager/v201911/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202008/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201911') + inventory_service = client.GetService('InventoryService', version='v202008') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v201911/inventory_service/create_ad_units.py b/examples/ad_manager/v202008/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v201911/inventory_service/create_ad_units.py rename to examples/ad_manager/v202008/inventory_service/create_ad_units.py index 050027c5..31a09c1b 100755 --- a/examples/ad_manager/v201911/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202008/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201911') + inventory_service = client.GetService('InventoryService', version='v202008') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v201911/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202008/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v201911/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202008/inventory_service/get_ad_unit_hierarchy.py index 11d1650f..8910487a 100755 --- a/examples/ad_manager/v201911/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202008/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201911') - inventory_service = client.GetService('InventoryService', version='v201911') + network_service = client.GetService('NetworkService', version='v202008') + inventory_service = client.GetService('InventoryService', version='v202008') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v201911/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202008/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v201911/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202008/inventory_service/get_all_ad_unit_sizes.py index 5f357625..676d17c2 100755 --- a/examples/ad_manager/v201911/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202008/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v201911') + 'InventoryService', version='v202008') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v201911/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202008/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v201911/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202008/inventory_service/get_all_ad_units.py index 52c617b4..6b445d3c 100755 --- a/examples/ad_manager/v201911/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202008/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v201911') + ad_unit_service = client.GetService('InventoryService', version='v202008') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v201911/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202008/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v201911/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202008/inventory_service/get_top_level_ad_units.py index 34701714..af5543d7 100755 --- a/examples/ad_manager/v201911/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202008/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v201911') - inventory_service = client.GetService('InventoryService', version='v201911') + network_service = client.GetService('NetworkService', version='v202008') + inventory_service = client.GetService('InventoryService', version='v202008') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v201911/inventory_service/update_ad_units.py b/examples/ad_manager/v202008/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v201911/inventory_service/update_ad_units.py rename to examples/ad_manager/v202008/inventory_service/update_ad_units.py index 15f24e0d..c13a3979 100755 --- a/examples/ad_manager/v201911/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202008/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v201911') + inventory_service = client.GetService('InventoryService', version='v202008') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v201911/label_service/__init__.py b/examples/ad_manager/v202008/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/label_service/__init__.py rename to examples/ad_manager/v202008/label_service/__init__.py diff --git a/examples/ad_manager/v201911/label_service/create_labels.py b/examples/ad_manager/v202008/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v201911/label_service/create_labels.py rename to examples/ad_manager/v202008/label_service/create_labels.py index 311f18de..e6fab393 100755 --- a/examples/ad_manager/v201911/label_service/create_labels.py +++ b/examples/ad_manager/v202008/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201911') + label_service = client.GetService('LabelService', version='v202008') # Create label objects. labels = [] diff --git a/examples/ad_manager/v201911/label_service/deactivate_labels.py b/examples/ad_manager/v202008/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v201911/label_service/deactivate_labels.py rename to examples/ad_manager/v202008/label_service/deactivate_labels.py index 8e87b5f3..c7ae1f3f 100755 --- a/examples/ad_manager/v201911/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202008/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201911') + label_service = client.GetService('LabelService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201911/label_service/get_active_labels.py b/examples/ad_manager/v202008/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v201911/label_service/get_active_labels.py rename to examples/ad_manager/v202008/label_service/get_active_labels.py index 84ec19ad..01bb66d8 100755 --- a/examples/ad_manager/v201911/label_service/get_active_labels.py +++ b/examples/ad_manager/v202008/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201911') + label_service = client.GetService('LabelService', version='v202008') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v201911/label_service/get_all_labels.py b/examples/ad_manager/v202008/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v201911/label_service/get_all_labels.py rename to examples/ad_manager/v202008/label_service/get_all_labels.py index 6c50e38b..fd473541 100755 --- a/examples/ad_manager/v201911/label_service/get_all_labels.py +++ b/examples/ad_manager/v202008/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201911') + label_service = client.GetService('LabelService', version='v202008') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v201911/label_service/update_labels.py b/examples/ad_manager/v202008/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v201911/label_service/update_labels.py rename to examples/ad_manager/v202008/label_service/update_labels.py index f98f2118..7da1be35 100755 --- a/examples/ad_manager/v201911/label_service/update_labels.py +++ b/examples/ad_manager/v202008/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v201911') + label_service = client.GetService('LabelService', version='v202008') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v201911/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202008/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202008/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v201911/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202008/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v201911/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202008/line_item_creative_association_service/create_licas.py index ab10eaaa..163789a2 100755 --- a/examples/ad_manager/v201911/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202008/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201911') + 'LineItemCreativeAssociationService', version='v202008') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v201911/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202008/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v201911/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202008/line_item_creative_association_service/deactivate_licas.py index bbaf75e9..fa0482bc 100755 --- a/examples/ad_manager/v201911/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202008/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201911') + 'LineItemCreativeAssociationService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v201911/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202008/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v201911/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202008/line_item_creative_association_service/get_all_licas.py index f9ce6186..6b1d9306 100755 --- a/examples/ad_manager/v201911/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202008/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201911') + 'LineItemCreativeAssociationService', version='v202008') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v201911/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202008/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v201911/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202008/line_item_creative_association_service/get_licas_for_line_item.py index 55a8687b..0a1eb90c 100755 --- a/examples/ad_manager/v201911/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202008/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201911') + 'LineItemCreativeAssociationService', version='v202008') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v201911/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202008/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v201911/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202008/line_item_creative_association_service/update_licas.py index 92fd7ace..74e750ef 100755 --- a/examples/ad_manager/v201911/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202008/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v201911') + 'LineItemCreativeAssociationService', version='v202008') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v201911/line_item_service/__init__.py b/examples/ad_manager/v202008/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/line_item_service/__init__.py rename to examples/ad_manager/v202008/line_item_service/__init__.py diff --git a/examples/ad_manager/v201911/line_item_service/activate_line_items.py b/examples/ad_manager/v202008/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v201911/line_item_service/activate_line_items.py rename to examples/ad_manager/v202008/line_item_service/activate_line_items.py index dc096cae..aa95266c 100755 --- a/examples/ad_manager/v201911/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202008/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201911/line_item_service/create_line_items.py b/examples/ad_manager/v202008/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v201911/line_item_service/create_line_items.py rename to examples/ad_manager/v202008/line_item_service/create_line_items.py index a487b3ad..e8bf2ade 100755 --- a/examples/ad_manager/v201911/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202008/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201911/line_item_service/create_video_line_item.py b/examples/ad_manager/v202008/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v201911/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202008/line_item_service/create_video_line_item.py index 6cc2f5c2..5dfa1cb0 100755 --- a/examples/ad_manager/v201911/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202008/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201911/line_item_service/get_all_line_items.py b/examples/ad_manager/v202008/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v201911/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202008/line_item_service/get_all_line_items.py index 19b5aa5f..a7171ad6 100755 --- a/examples/ad_manager/v201911/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202008/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v201911/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202008/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v201911/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202008/line_item_service/get_line_items_that_need_creatives.py index 2cddf9ea..ef5d6b0b 100755 --- a/examples/ad_manager/v201911/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202008/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v201911/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202008/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v201911/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202008/line_item_service/get_recently_updated_line_items.py index 0971c050..c8f4e618 100755 --- a/examples/ad_manager/v201911/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202008/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v201911/line_item_service/pause_line_items.py b/examples/ad_manager/v202008/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v201911/line_item_service/pause_line_items.py rename to examples/ad_manager/v202008/line_item_service/pause_line_items.py index cae1fa1c..8c302cf5 100755 --- a/examples/ad_manager/v201911/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202008/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v201911/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202008/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v201911/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202008/line_item_service/target_custom_criteria.py index 41399c89..9e22b59c 100755 --- a/examples/ad_manager/v201911/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202008/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/line_item_service/update_line_items.py b/examples/ad_manager/v202008/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v201911/line_item_service/update_line_items.py rename to examples/ad_manager/v202008/line_item_service/update_line_items.py index 8f3bd6e5..190c522d 100755 --- a/examples/ad_manager/v201911/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202008/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v201911') + line_item_service = client.GetService('LineItemService', version='v202008') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v201911/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202008/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201911/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202008/live_stream_event_service/activate_live_stream_events.py index 18b76a52..82d485a9 100755 --- a/examples/ad_manager/v201911/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202008/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201911') + 'LiveStreamEventService', version='v202008') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v201911/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202008/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v201911/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202008/live_stream_event_service/create_live_stream_events.py index 49ab8bf2..bf67cf5a 100755 --- a/examples/ad_manager/v201911/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202008/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v201911') + 'LiveStreamEventService', version='v202008') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v201911/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202008/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v201911/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202008/live_stream_event_service/get_all_live_stream_events.py index ec5e3fa4..52e72790 100755 --- a/examples/ad_manager/v201911/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202008/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201911') + 'LiveStreamEventService', version='v202008') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v201911/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202008/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v201911/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202008/live_stream_event_service/register_sessions_for_monitoring.py index 9817e44e..fb2098fd 100755 --- a/examples/ad_manager/v201911/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202008/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v201911') + 'LiveStreamEventService', version='v202008') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v201911/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202008/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v201911/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202008/live_stream_event_service/update_live_stream_events.py index bb05fd6c..4ec6d513 100755 --- a/examples/ad_manager/v201911/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202008/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v201911') + 'LiveStreamEventService', version='v202008') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v201911/native_style_service/__init__.py b/examples/ad_manager/v202008/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/native_style_service/__init__.py rename to examples/ad_manager/v202008/native_style_service/__init__.py diff --git a/examples/ad_manager/v201911/native_style_service/create_native_styles.py b/examples/ad_manager/v202008/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v201911/native_style_service/create_native_styles.py rename to examples/ad_manager/v202008/native_style_service/create_native_styles.py index a967fd7d..de037b17 100755 --- a/examples/ad_manager/v201911/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202008/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201911') + version='v202008') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v201911/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202008/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v201911/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202008/native_style_service/get_all_native_styles.py index a3d94698..89654d30 100755 --- a/examples/ad_manager/v201911/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202008/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v201911') + version='v202008') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v201911/network_service/__init__.py b/examples/ad_manager/v202008/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/network_service/__init__.py rename to examples/ad_manager/v202008/network_service/__init__.py diff --git a/examples/ad_manager/v201911/network_service/get_all_networks.py b/examples/ad_manager/v202008/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v201911/network_service/get_all_networks.py rename to examples/ad_manager/v202008/network_service/get_all_networks.py index 99d656d8..8ecd46ea 100755 --- a/examples/ad_manager/v201911/network_service/get_all_networks.py +++ b/examples/ad_manager/v202008/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201911') + network_service = client.GetService('NetworkService', version='v202008') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v201911/network_service/get_current_network.py b/examples/ad_manager/v202008/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v201911/network_service/get_current_network.py rename to examples/ad_manager/v202008/network_service/get_current_network.py index 9593231e..10c9a3c8 100755 --- a/examples/ad_manager/v201911/network_service/get_current_network.py +++ b/examples/ad_manager/v202008/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201911') + network_service = client.GetService('NetworkService', version='v202008') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v201911/network_service/make_test_network.py b/examples/ad_manager/v202008/network_service/make_test_network.py similarity index 92% rename from examples/ad_manager/v201911/network_service/make_test_network.py rename to examples/ad_manager/v202008/network_service/make_test_network.py index bca56e9f..66b848e0 100755 --- a/examples/ad_manager/v201911/network_service/make_test_network.py +++ b/examples/ad_manager/v202008/network_service/make_test_network.py @@ -22,10 +22,6 @@ is not associated with any other Ad Manager test networks. Once this network is created, you can supply the network code in your settings to make calls to other services. - -Alternatively, if you do not wish to run this example, you can create a test -network at: -https://dfp-playground.appspot.com """ @@ -35,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v201911') + network_service = client.GetService('NetworkService', version='v202008') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v201911/order_service/__init__.py b/examples/ad_manager/v202008/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/order_service/__init__.py rename to examples/ad_manager/v202008/order_service/__init__.py diff --git a/examples/ad_manager/v201911/order_service/approve_orders.py b/examples/ad_manager/v202008/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v201911/order_service/approve_orders.py rename to examples/ad_manager/v202008/order_service/approve_orders.py index 1a19ce76..25e0eb82 100755 --- a/examples/ad_manager/v201911/order_service/approve_orders.py +++ b/examples/ad_manager/v202008/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201911') + order_service = client.GetService('OrderService', version='v202008') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v201911/order_service/create_orders.py b/examples/ad_manager/v202008/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v201911/order_service/create_orders.py rename to examples/ad_manager/v202008/order_service/create_orders.py index cf68732c..b04c43b2 100755 --- a/examples/ad_manager/v201911/order_service/create_orders.py +++ b/examples/ad_manager/v202008/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201911') + order_service = client.GetService('OrderService', version='v202008') # Create order objects. orders = [] diff --git a/examples/ad_manager/v201911/order_service/get_all_orders.py b/examples/ad_manager/v202008/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v201911/order_service/get_all_orders.py rename to examples/ad_manager/v202008/order_service/get_all_orders.py index c13e3bf6..7be5cdcc 100755 --- a/examples/ad_manager/v201911/order_service/get_all_orders.py +++ b/examples/ad_manager/v202008/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201911') + order_service = client.GetService('OrderService', version='v202008') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v201911/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202008/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v201911/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202008/order_service/get_orders_starting_soon.py index 32ae6012..9699ba36 100755 --- a/examples/ad_manager/v201911/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202008/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201911') + order_service = client.GetService('OrderService', version='v202008') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v201911/order_service/update_orders.py b/examples/ad_manager/v202008/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v201911/order_service/update_orders.py rename to examples/ad_manager/v202008/order_service/update_orders.py index 381420de..66646b99 100755 --- a/examples/ad_manager/v201911/order_service/update_orders.py +++ b/examples/ad_manager/v202008/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v201911') + order_service = client.GetService('OrderService', version='v202008') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v201911/placement_service/create_placements.py b/examples/ad_manager/v202008/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v201911/placement_service/create_placements.py rename to examples/ad_manager/v202008/placement_service/create_placements.py index 620faac0..5ad1d4f3 100755 --- a/examples/ad_manager/v201911/placement_service/create_placements.py +++ b/examples/ad_manager/v202008/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201911') - inventory_service = client.GetService('InventoryService', version='v201911') + placement_service = client.GetService('PlacementService', version='v202008') + inventory_service = client.GetService('InventoryService', version='v202008') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v201911/placement_service/deactivate_placements.py b/examples/ad_manager/v202008/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v201911/placement_service/deactivate_placements.py rename to examples/ad_manager/v202008/placement_service/deactivate_placements.py index 2aa4bcff..1cb5124a 100755 --- a/examples/ad_manager/v201911/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202008/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201911') + placement_service = client.GetService('PlacementService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/placement_service/get_active_placements.py b/examples/ad_manager/v202008/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v201911/placement_service/get_active_placements.py rename to examples/ad_manager/v202008/placement_service/get_active_placements.py index edf21eaf..7ee9edc7 100755 --- a/examples/ad_manager/v201911/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202008/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201911') + placement_service = client.GetService('PlacementService', version='v202008') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v201911/placement_service/get_all_placements.py b/examples/ad_manager/v202008/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v201911/placement_service/get_all_placements.py rename to examples/ad_manager/v202008/placement_service/get_all_placements.py index 99fd743a..0fcdaf3a 100755 --- a/examples/ad_manager/v201911/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202008/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201911') + placement_service = client.GetService('PlacementService', version='v202008') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v201911/placement_service/update_placements.py b/examples/ad_manager/v202008/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v201911/placement_service/update_placements.py rename to examples/ad_manager/v202008/placement_service/update_placements.py index cd77c3a4..ffae1a91 100755 --- a/examples/ad_manager/v201911/placement_service/update_placements.py +++ b/examples/ad_manager/v202008/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v201911') + placement_service = client.GetService('PlacementService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v201911/proposal_line_item_service/__init__.py b/examples/ad_manager/v202008/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202008/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v201911/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202008/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201911/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202008/proposal_line_item_service/archive_proposal_line_items.py index b7d064eb..a81991a7 100755 --- a/examples/ad_manager/v201911/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202008/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201911') + 'ProposalLineItemService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202008/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v201911/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202008/proposal_line_item_service/create_proposal_line_items.py index 6833cf8a..3462e0e3 100755 --- a/examples/ad_manager/v201911/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202008/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201911') - network_service = client.GetService('NetworkService', version='v201911') + 'ProposalLineItemService', version='v202008') + network_service = client.GetService('NetworkService', version='v202008') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v201911/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202008/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v201911/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202008/proposal_line_item_service/get_all_proposal_line_items.py index 9a99551b..3ab16a19 100755 --- a/examples/ad_manager/v201911/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202008/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201911') + 'ProposalLineItemService', version='v202008') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v201911/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202008/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v201911/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202008/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 10e2cf55..07478775 100755 --- a/examples/ad_manager/v201911/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202008/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201911') + 'ProposalLineItemService', version='v202008') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v201911/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202008/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v201911/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202008/proposal_line_item_service/update_proposal_line_items.py index 6193d90a..1194ff47 100755 --- a/examples/ad_manager/v201911/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202008/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v201911') + 'ProposalLineItemService', version='v202008') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/proposal_service/__init__.py b/examples/ad_manager/v202008/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/proposal_service/__init__.py rename to examples/ad_manager/v202008/proposal_service/__init__.py diff --git a/examples/ad_manager/v201911/proposal_service/create_proposals.py b/examples/ad_manager/v202008/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v201911/proposal_service/create_proposals.py rename to examples/ad_manager/v202008/proposal_service/create_proposals.py index cc183fb4..bed4a69d 100755 --- a/examples/ad_manager/v201911/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202008/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v201911') + proposal_service = client.GetService('ProposalService', version='v202008') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v201911/proposal_service/get_all_proposals.py b/examples/ad_manager/v202008/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v201911/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202008/proposal_service/get_all_proposals.py index 92efce68..e91f7141 100755 --- a/examples/ad_manager/v201911/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202008/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201911') + proposal_service = client.GetService('ProposalService', version='v202008') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v201911/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202008/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v201911/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202008/proposal_service/get_marketplace_comments.py index 773a94f1..4fc3aeea 100755 --- a/examples/ad_manager/v201911/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202008/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v201911') + 'ProposalService', version='v202008') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v201911/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202008/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v201911/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202008/proposal_service/get_proposals_awaiting_seller_review.py index a7d3aafc..a0ac3426 100755 --- a/examples/ad_manager/v201911/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202008/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201911') + proposal_service = client.GetService('ProposalService', version='v202008') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v201911/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202008/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v201911/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202008/proposal_service/request_buyers_acceptance.py index 29b238a1..7b96a0fc 100755 --- a/examples/ad_manager/v201911/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202008/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201911') + proposal_service = client.GetService('ProposalService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v201911/proposal_service/update_proposals.py b/examples/ad_manager/v202008/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v201911/proposal_service/update_proposals.py rename to examples/ad_manager/v202008/proposal_service/update_proposals.py index cbc08806..27cfe48a 100755 --- a/examples/ad_manager/v201911/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202008/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v201911') + proposal_service = client.GetService('ProposalService', version='v202008') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v201911/publisher_query_language_service/__init__.py b/examples/ad_manager/v202008/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202008/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v201911/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202008/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v201911/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202008/publisher_query_language_service/fetch_match_tables.py index 3beec75d..e05509a6 100755 --- a/examples/ad_manager/v201911/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202008/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201911/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202008/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v201911/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202008/publisher_query_language_service/get_all_browsers.py index c9872558..09756b79 100755 --- a/examples/ad_manager/v201911/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202008/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v201911/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202008/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v201911/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202008/publisher_query_language_service/get_all_programmatic_buyers.py index f1fa36b3..3a76222d 100755 --- a/examples/ad_manager/v201911/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202008/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v201911') + data_downloader = client.GetDataDownloader(version='v202008') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v201911/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202008/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v201911/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202008/publisher_query_language_service/get_geo_targets.py index 60baf278..230b9072 100755 --- a/examples/ad_manager/v201911/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202008/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v201911/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202008/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v201911/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202008/publisher_query_language_service/get_line_items_named_like.py index 56e06b25..50e6c97b 100755 --- a/examples/ad_manager/v201911/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202008/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202008/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202008/publisher_query_language_service/get_mcm_earnings.py new file mode 100755 index 00000000..5626890a --- /dev/null +++ b/examples/ad_manager/v202008/publisher_query_language_service/get_mcm_earnings.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 Multiple Customer Management earnings for the prior month. +""" + +import datetime +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize a report downloader. + data_downloader = client.GetDataDownloader(version='v202008') + + with tempfile.NamedTemporaryFile( + prefix='mcm_earnings_', + suffix='.csv', mode='w', delete=False) as mcm_earnings_file: + + this_month_start = datetime.date.today().replace(day=1) + last_month_end = this_month_start - datetime.timedelta(days=1) + last_month_start = last_month_end.replace(day=1) + + mcm_earnings_query = ('SELECT Month, ChildName, ChildNetworkCode, ' + 'TotalEarningsCurrencyCode, TotalEarningsMicros, ' + 'ParentPaymentCurrencyCode, ParentPaymentMicros, ' + 'ChildPaymentCurrencyCode, ChildPaymentMicros, ' + 'DeductionsMicros ' + 'FROM Mcm_Earnings ' + 'WHERE Month = :month ' + 'ORDER BY ChildNetworkCode') + + # Downloads the response from PQL select statement to the specified file + data_downloader.DownloadPqlResultToCsv( + mcm_earnings_query, mcm_earnings_file, {'month': last_month_start}) + + print('Saved MCM earnings to... %s' % mcm_earnings_file.name) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201911/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202008/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v201911/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202008/publisher_query_language_service/get_recent_changes.py index 7009fba9..bd02af2c 100755 --- a/examples/ad_manager/v201911/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202008/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v201911') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202008') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v201911/report_service/__init__.py b/examples/ad_manager/v202008/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/report_service/__init__.py rename to examples/ad_manager/v202008/report_service/__init__.py diff --git a/examples/ad_manager/v201911/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202008/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v201911/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202008/report_service/run_ad_exchange_report.py index 92c62d0b..614fe565 100755 --- a/examples/ad_manager/v201911/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202008/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') # Create report job. report_job = { diff --git a/examples/ad_manager/v201911/report_service/run_delivery_report.py b/examples/ad_manager/v202008/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v201911/report_service/run_delivery_report.py rename to examples/ad_manager/v202008/report_service/run_delivery_report.py index 5272d8d2..50c6f6ec 100755 --- a/examples/ad_manager/v201911/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202008/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201911/report_service/run_inventory_report.py b/examples/ad_manager/v202008/report_service/run_inventory_report.py similarity index 97% rename from examples/ad_manager/v201911/report_service/run_inventory_report.py rename to examples/ad_manager/v202008/report_service/run_inventory_report.py index 1fad0c7c..1932c00d 100755 --- a/examples/ad_manager/v201911/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202008/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') # Create report job. report_job = { diff --git a/examples/ad_manager/v201911/report_service/run_reach_report.py b/examples/ad_manager/v202008/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v201911/report_service/run_reach_report.py rename to examples/ad_manager/v202008/report_service/run_reach_report.py index 24fefde0..f348c9f2 100755 --- a/examples/ad_manager/v201911/report_service/run_reach_report.py +++ b/examples/ad_manager/v202008/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') # Create report job. report_job = { diff --git a/examples/ad_manager/v201911/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202008/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v201911/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202008/report_service/run_report_and_create_match_table.py index af07b909..7afd3534 100755 --- a/examples/ad_manager/v201911/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202008/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v201911/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202008/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v201911/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202008/report_service/run_report_with_custom_fields.py index 7ab092f5..d7b9fcf0 100755 --- a/examples/ad_manager/v201911/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202008/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') # Create report job. report_job = { diff --git a/examples/ad_manager/v201911/report_service/run_sales_report.py b/examples/ad_manager/v202008/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v201911/report_service/run_sales_report.py rename to examples/ad_manager/v202008/report_service/run_sales_report.py index b160ffca..4f4404d4 100755 --- a/examples/ad_manager/v201911/report_service/run_sales_report.py +++ b/examples/ad_manager/v202008/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') # Create report job. report_job = { diff --git a/examples/ad_manager/v201911/report_service/run_saved_query.py b/examples/ad_manager/v202008/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v201911/report_service/run_saved_query.py rename to examples/ad_manager/v202008/report_service/run_saved_query.py index 57d81295..248af4eb 100755 --- a/examples/ad_manager/v201911/report_service/run_saved_query.py +++ b/examples/ad_manager/v202008/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v201911') + report_service = client.GetService('ReportService', version='v202008') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v201911') + report_downloader = client.GetDataDownloader(version='v202008') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/site_service/create_sites.py b/examples/ad_manager/v202008/site_service/create_sites.py new file mode 100755 index 00000000..9574075b --- /dev/null +++ b/examples/ad_manager/v202008/site_service/create_sites.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a Site for Multiple Customer Management.""" + +# Import appropriate modules from the client library. +import sys +from googleads import ad_manager + +# Set the URL and child network code for the Site. +URL = 'INSERT_URL_HERE' +CHILD_NETWORK_CODE = 'INSERT_CHILD_NETWORK_CODE_HERE' + + +def main(client, url, child_network_code): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v202008') + site_service = client.GetService('SiteService', version='v202008') + + # Check that the child network code is approved for MANAGE_INVENTORY by this + # network. + current_network = network_service.getCurrentNetwork() + child_network = None + for child in current_network['childPublishers']: + if child['childNetworkCode'] == child_network_code: + child_network = child + + if child_network is None: + print(('Child network %s not found on the current network (%s). Cannot ' + 'create site.') % (child_network_code, + current_network['networkCode'])) + sys.exit(1) + + if child_network['approvedDelegationType'] != 'MANAGE_INVENTORY': + print(('Child network %s has not approved for the current network (%s) ' + 'to manage its inventory. Cannot create site.') % ( + child_network_code, current_network['networkCode'])) + sys.exit(1) + + # Create site object. + site = {'url': url, 'childNetworkCode': child_network_code} + + # Create the site on the server. + created_sites = site_service.createSites([site]) + + # Display results. + for site in created_sites: + print('Site with id %d and URL "%s" was created for child network %s.' % ( + site['id'], site['url'], site['childNetworkCode'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, URL, CHILD_NETWORK_CODE) diff --git a/examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202008/site_service/get_all_sites.py similarity index 57% rename from examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202008/site_service/get_all_sites.py index f4686b1b..2b4df6a9 100755 --- a/examples/ad_manager/v201911/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202008/site_service/get_all_sites.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2019 Google Inc. All Rights Reserved. +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,8 +13,8 @@ # 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 targeting presets. -""" + +"""This example gets all Sites.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -22,23 +22,20 @@ def main(client): # Initialize appropriate service. - targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v201911') + site_service = client.GetService('SiteService', version='v202008') - # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201911') + # Create a statement to select Sites. + statement = ad_manager.StatementBuilder(version='v202008') - # Retrieve a small number of targeting presets at a time, paging - # through until all targeting presets have been retrieved. + # Retrieve a small number of sites at a time, paging through until all sites + # have been retrieved. while True: - response = targeting_preset_service.getTargetingPresetsByStatement( - statement.ToStatement()) + response = site_service.getSitesByStatement(statement.ToStatement()) if 'results' in response and len(response['results']): - for targeting_preset in response['results']: - # Print out some information for each targeting preset. - print( - 'Targeting preset with ID "%d" and name "%s" was found.\n' - % (targeting_preset['id'], targeting_preset['name'])) + for site in response['results']: + # Print out some information for each site. + print('Site with Id %d and URL "%s" was found.' % + (site['id'], site['url'])) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v202008/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202008/site_service/get_sites_requiring_approval.py new file mode 100755 index 00000000..0de6bad5 --- /dev/null +++ b/examples/ad_manager/v202008/site_service/get_sites_requiring_approval.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 Sites under MCM requiring review.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + site_service = client.GetService('SiteService', version='v202008') + + # Create a statement to select Sites needing approval. + statement = ad_manager.StatementBuilder(version='v202008').Where( + "approvalStatus = 'REQUIRES_REVIEW'") + + # Retrieve a small number of sites at a time, paging through until all sites + # have been retrieved. + while True: + response = site_service.getSitesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for site in response['results']: + # Print out some information for each site. + print('Site with Id %d and URL "%s" was found.' % + (site['id'], site['url'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202008/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202008/site_service/submit_sites_for_approval.py new file mode 100755 index 00000000..60b7fe79 --- /dev/null +++ b/examples/ad_manager/v202008/site_service/submit_sites_for_approval.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 submits a Site for approval.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the site to submit for approval. +SITE_ID = 'INSERT_SITE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + site_service = client.GetService('SiteService', version='v202008') + + # Create a statement to select Site. + statement = (ad_manager.StatementBuilder(version='v202008') + .Where('id = :id') + .WithBindVariable('id', SITE_ID)) + + response = site_service.performSiteAction( + {'xsi_type': 'SubmitSiteForApproval'}, statement.ToStatement()) + + print('\nNumber of sites changed: %s' % response['numChanges']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v201911/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202008/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202008/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v201911/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202008/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v201911/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202008/suggested_ad_unit_service/approve_all_suggested_ad_units.py index d4ae5437..a49ebc8a 100755 --- a/examples/ad_manager/v201911/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202008/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201911') + 'SuggestedAdUnitService', version='v202008') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v201911/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202008/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201911/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202008/suggested_ad_unit_service/get_all_suggested_ad_units.py index 2648020f..262cd996 100755 --- a/examples/ad_manager/v201911/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202008/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201911') + 'SuggestedAdUnitService', version='v202008') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v201911/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202008/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v201911/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202008/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index a4739113..53e8d9d6 100755 --- a/examples/ad_manager/v201911/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202008/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v201911') + 'SuggestedAdUnitService', version='v202008') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v201911/targeting_preset_service/__init__.py b/examples/ad_manager/v202008/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/targeting_preset_service/__init__.py rename to examples/ad_manager/v202008/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202008/targeting_preset_service/get_all_targeting_presets.py similarity index 90% rename from examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202008/targeting_preset_service/get_all_targeting_presets.py index 6881b8cb..171a073e 100755 --- a/examples/ad_manager/v201908/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202008/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v201908') + 'TargetingPresetService', version='v202008') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v201908') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. @@ -37,7 +37,7 @@ def main(client): for targeting_preset in response['results']: # Print out some information for each targeting preset. print( - 'Targeting preset with ID "%d" and name "%s" was found.\n' + 'Targeting preset with ID "%s" and name "%d" was found.\n' % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: diff --git a/examples/ad_manager/v201911/team_service/__init__.py b/examples/ad_manager/v202008/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/team_service/__init__.py rename to examples/ad_manager/v202008/team_service/__init__.py diff --git a/examples/ad_manager/v201911/team_service/create_teams.py b/examples/ad_manager/v202008/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v201911/team_service/create_teams.py rename to examples/ad_manager/v202008/team_service/create_teams.py index ed705c71..a878564a 100755 --- a/examples/ad_manager/v201911/team_service/create_teams.py +++ b/examples/ad_manager/v202008/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201911') + team_service = client.GetService('TeamService', version='v202008') # Create team objects. teams = [] diff --git a/examples/ad_manager/v201911/team_service/get_all_teams.py b/examples/ad_manager/v202008/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v201911/team_service/get_all_teams.py rename to examples/ad_manager/v202008/team_service/get_all_teams.py index c2b8ed66..7bece16a 100755 --- a/examples/ad_manager/v201911/team_service/get_all_teams.py +++ b/examples/ad_manager/v202008/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201911') + team_service = client.GetService('TeamService', version='v202008') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v201911/team_service/update_teams.py b/examples/ad_manager/v202008/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v201911/team_service/update_teams.py rename to examples/ad_manager/v202008/team_service/update_teams.py index 3febda96..48841e10 100755 --- a/examples/ad_manager/v201911/team_service/update_teams.py +++ b/examples/ad_manager/v202008/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v201911') + team_service = client.GetService('TeamService', version='v202008') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v201911/user_service/__init__.py b/examples/ad_manager/v202008/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/user_service/__init__.py rename to examples/ad_manager/v202008/user_service/__init__.py diff --git a/examples/ad_manager/v201911/user_service/create_users.py b/examples/ad_manager/v202008/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v201911/user_service/create_users.py rename to examples/ad_manager/v202008/user_service/create_users.py index 8469e530..b2374c40 100755 --- a/examples/ad_manager/v201911/user_service/create_users.py +++ b/examples/ad_manager/v202008/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201911') + user_service = client.GetService('UserService', version='v202008') # Create user objects. users = [ diff --git a/examples/ad_manager/v201911/user_service/deactivate_users.py b/examples/ad_manager/v202008/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v201911/user_service/deactivate_users.py rename to examples/ad_manager/v202008/user_service/deactivate_users.py index c6f28f8e..5f22d9a9 100755 --- a/examples/ad_manager/v201911/user_service/deactivate_users.py +++ b/examples/ad_manager/v202008/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201911') + user_service = client.GetService('UserService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201911/user_service/get_all_roles.py b/examples/ad_manager/v202008/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v201911/user_service/get_all_roles.py rename to examples/ad_manager/v202008/user_service/get_all_roles.py index ddc854f7..2d9ef07f 100755 --- a/examples/ad_manager/v201911/user_service/get_all_roles.py +++ b/examples/ad_manager/v202008/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201911') + user_service = client.GetService('UserService', version='v202008') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v201911/user_service/get_all_users.py b/examples/ad_manager/v202008/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v201911/user_service/get_all_users.py rename to examples/ad_manager/v202008/user_service/get_all_users.py index f72a8f63..0fee32ff 100755 --- a/examples/ad_manager/v201911/user_service/get_all_users.py +++ b/examples/ad_manager/v202008/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201911') + user_service = client.GetService('UserService', version='v202008') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v201911/user_service/get_current_user.py b/examples/ad_manager/v202008/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v201911/user_service/get_current_user.py rename to examples/ad_manager/v202008/user_service/get_current_user.py index 333407b0..2fc8d1fc 100755 --- a/examples/ad_manager/v201911/user_service/get_current_user.py +++ b/examples/ad_manager/v202008/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201911') + user_service = client.GetService('UserService', version='v202008') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v201911/user_service/get_user_by_email_address.py b/examples/ad_manager/v202008/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v201911/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202008/user_service/get_user_by_email_address.py index 21590b64..42c4fa69 100755 --- a/examples/ad_manager/v201911/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202008/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201911') + user_service = client.GetService('UserService', version='v202008') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v201911/user_service/update_users.py b/examples/ad_manager/v202008/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v201911/user_service/update_users.py rename to examples/ad_manager/v202008/user_service/update_users.py index d6b7b0be..cfc44fd2 100755 --- a/examples/ad_manager/v201911/user_service/update_users.py +++ b/examples/ad_manager/v202008/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v201911') + user_service = client.GetService('UserService', version='v202008') # Create query. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201911/user_team_association_service/__init__.py b/examples/ad_manager/v202008/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v201911/user_team_association_service/__init__.py rename to examples/ad_manager/v202008/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v201911/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202008/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v201911/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202008/user_team_association_service/create_user_team_associations.py index 989253e6..fa7beea9 100755 --- a/examples/ad_manager/v201911/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202008/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201911') + 'UserTeamAssociationService', version='v202008') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v201911/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202008/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v201911/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202008/user_team_association_service/delete_user_team_associations.py index 78f05488..1b3b8790 100755 --- a/examples/ad_manager/v201911/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202008/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201911') + 'UserTeamAssociationService', version='v202008') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201911/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202008/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v201911/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202008/user_team_association_service/get_all_user_team_associations.py index ea776a4a..60830b38 100755 --- a/examples/ad_manager/v201911/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202008/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201911') + 'UserTeamAssociationService', version='v202008') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v201911') + statement = ad_manager.StatementBuilder(version='v202008') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v201911/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202008/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v201911/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202008/user_team_association_service/get_user_team_associations_for_user.py index e0a29ab8..4e4bcc49 100755 --- a/examples/ad_manager/v201911/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202008/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201911') + 'UserTeamAssociationService', version='v202008') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v201911/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202008/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v201911/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202008/user_team_association_service/update_user_team_associations.py index 9fed6ddf..8abc9c7d 100755 --- a/examples/ad_manager/v201911/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202008/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v201911') + 'UserTeamAssociationService', version='v202008') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v201911') + statement = (ad_manager.StatementBuilder(version='v202008') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/adwords/v201809/basic_operations/update_keyword.py b/examples/adwords/v201809/basic_operations/update_keyword.py index 6c88b605..951ba220 100755 --- a/examples/adwords/v201809/basic_operations/update_keyword.py +++ b/examples/adwords/v201809/basic_operations/update_keyword.py @@ -69,7 +69,8 @@ def main(client, ad_group_id, criterion_id): '"%s" currently has bids:' % (criterion['adGroupId'], criterion['criterion']['id'])) for bid in criterion['biddingStrategyConfiguration']['bids']: - print('\tType: "%s", value: %s' % (bid['Bids.Type']), bid['bid']['microAmount']) + print('\tType: "%s", value: %s' % + (bid['Bids.Type'], bid['bid']['microAmount'])) else: print('No ad group criteria were updated.') diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 610a2fe1..8de92503 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,22 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201908': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', - 'ContactService', 'ContentBundleService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'DaiAuthenticationKeyService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', - 'UserService', 'UserTeamAssociationService'), 'v201911': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', @@ -110,6 +94,24 @@ 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), + 'v202008': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', + 'ContactService', 'ContentBundleService', 'ContentService', + 'CreativeReviewService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PlacementService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', + 'SiteService', 'StreamActivityMonitorService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService'), } diff --git a/googleads/common.py b/googleads/common.py index 1265452e..45e5bed2 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '24.1.0' +VERSION = '25.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 5071a68f..3a61e322 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202005' +CURRENT_VERSION = 'v202008' class CommonTest(testing.CleanUtilityRegistryTestCase): From ca06aaae68c1cfea8bc80be1f019980c2caec5dc Mon Sep 17 00:00:00 2001 From: David Wihl Date: Mon, 24 Aug 2020 11:38:54 -0400 Subject: [PATCH 161/180] Commiting latest changes. From a25a20a54002d90163098a2e44ac4dc4c22bd9f6 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Sun, 15 Nov 2020 07:43:27 -0500 Subject: [PATCH 162/180] Ad Manager v202011 release --- ChangeLog | 5 + .../create_traffic_adjustments.py | 143 ------------------ .../update_traffic_adjustments.py | 88 ----------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 65 ++++++++ .../create_traffic_forecast_segments.py | 72 +++++++++ .../get_all_forecast_adjustments.py} | 27 ++-- .../get_all_traffic_forecast_segments.py | 51 +++++++ ...djustments_for_traffic_forecast_segment.py | 57 +++++++ .../update_forecast_adjustments.py | 64 ++++++++ .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 70 +++++++++ .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../get_recently_modified_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../forecast_service/get_traffic_data.py | 123 +++++++++++++++ .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- ...et_default_third_party_data_declaration.py | 68 +++++++++ .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 58 +++++++ .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../v202011/site_service/create_sites.py | 68 +++++++++ .../v202011/site_service/get_all_sites.py | 49 ++++++ .../get_sites_requiring_approval.py | 50 ++++++ .../site_service/submit_sites_for_approval.py | 44 ++++++ .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 6 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 34 +++-- googleads/common.py | 2 +- tests/common_test.py | 2 +- 203 files changed, 1153 insertions(+), 539 deletions(-) delete mode 100755 examples/ad_manager/v202002/adjustment_service/create_traffic_adjustments.py delete mode 100755 examples/ad_manager/v202002/adjustment_service/update_traffic_adjustments.py rename examples/ad_manager/{v202002 => v202011}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v202002 => v202011}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v202002 => v202011}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v202002 => v202011}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v202002 => v202011}/activity_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v202002 => v202011}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v202002 => v202011}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v202002 => v202011}/activity_service/update_activities.py (96%) create mode 100755 examples/ad_manager/v202011/adjustment_service/create_forecast_adjustments.py create mode 100755 examples/ad_manager/v202011/adjustment_service/create_traffic_forecast_segments.py rename examples/ad_manager/{v202002/adjustment_service/get_all_traffic_adjustments.py => v202011/adjustment_service/get_all_forecast_adjustments.py} (63%) create mode 100755 examples/ad_manager/v202011/adjustment_service/get_all_traffic_forecast_segments.py create mode 100755 examples/ad_manager/v202011/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py create mode 100755 examples/ad_manager/v202011/adjustment_service/update_forecast_adjustments.py rename examples/ad_manager/{v202002 => v202011}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v202002 => v202011}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v202002 => v202011}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v202002 => v202011}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v202002 => v202011}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v202002 => v202011}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v202002 => v202011}/cdn_configuration_service/get_all_cdn_configurations.py (93%) create mode 100755 examples/ad_manager/v202011/cms_metadata_service/activate_cms_metadata_values.py rename examples/ad_manager/{v202002 => v202011}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v202002 => v202011}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v202002 => v202011}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v202002 => v202011}/company_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/company_service/create_companies.py (99%) rename examples/ad_manager/{v202002 => v202011}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v202002 => v202011}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v202002 => v202011}/company_service/update_companies.py (96%) rename examples/ad_manager/{v202002 => v202011}/contact_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v202002 => v202011}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v202002 => v202011}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v202002 => v202011}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v202002 => v202011}/content_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/content_service/get_all_content.py (96%) rename examples/ad_manager/{v202002 => v202011}/content_service/get_recently_modified_content.py (97%) rename examples/ad_manager/{v202002 => v202011}/creative_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v202002 => v202011}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v202002 => v202011}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v202002 => v202011}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v202002 => v202011}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v202002 => v202011}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v202002 => v202011}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v202002 => v202011}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v202002 => v202011}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v202002 => v202011}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v202002 => v202011}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v202002 => v202011}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v202002 => v202011}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v202002 => v202011}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v202002 => v202011}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v202002 => v202011}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v202002 => v202011}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v202002 => v202011}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v202002 => v202011}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v202002 => v202011}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v202002 => v202011}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v202002 => v202011}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v202002 => v202011}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v202002 => v202011}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v202002 => v202011}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v202002 => v202011}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v202002 => v202011}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v202002 => v202011}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v202002 => v202011}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202002 => v202011}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v202002 => v202011}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202002 => v202011}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202002 => v202011}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202002 => v202011}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v202002 => v202011}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v202002 => v202011}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v202002 => v202011}/forecast_service/get_delivery_forecast_for_line_items.py (99%) create mode 100755 examples/ad_manager/v202011/forecast_service/get_traffic_data.py rename examples/ad_manager/{v202002 => v202011}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v202002 => v202011}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v202002 => v202011}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v202002 => v202011}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v202002 => v202011}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v202002 => v202011}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v202002 => v202011}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v202002 => v202011}/label_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/label_service/create_labels.py (99%) rename examples/ad_manager/{v202002 => v202011}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v202002 => v202011}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v202002 => v202011}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v202002 => v202011}/label_service/update_labels.py (96%) rename examples/ad_manager/{v202002 => v202011}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v202002 => v202011}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v202002 => v202011}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v202002 => v202011}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v202002 => v202011}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v202002 => v202011}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v202002 => v202011}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v202002 => v202011}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v202002 => v202011}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v202002 => v202011}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v202002 => v202011}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v202002 => v202011}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v202002 => v202011}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v202002 => v202011}/network_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v202002 => v202011}/network_service/get_current_network.py (99%) create mode 100755 examples/ad_manager/v202011/network_service/get_default_third_party_data_declaration.py rename examples/ad_manager/{v202002 => v202011}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v202002 => v202011}/order_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v202002 => v202011}/order_service/create_orders.py (99%) rename examples/ad_manager/{v202002 => v202011}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v202002 => v202011}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v202002 => v202011}/order_service/update_orders.py (97%) rename examples/ad_manager/{v202002 => v202011}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v202002 => v202011}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v202002 => v202011}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v202002 => v202011}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v202002 => v202011}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v202002 => v202011}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v202002 => v202011}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v202002 => v202011}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v202002 => v202011}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v202002 => v202011}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v202002 => v202011}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v202002 => v202011}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v202002 => v202011}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v202002 => v202011}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v202002 => v202011}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v202002 => v202011}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v202002 => v202011}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v202002 => v202011}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v202002 => v202011}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v202002 => v202011}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v202002 => v202011}/publisher_query_language_service/get_line_items_named_like.py (96%) create mode 100755 examples/ad_manager/v202011/publisher_query_language_service/get_mcm_earnings.py rename examples/ad_manager/{v202002 => v202011}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v202002 => v202011}/report_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v202002 => v202011}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v202002 => v202011}/report_service/run_inventory_report.py (97%) rename examples/ad_manager/{v202002 => v202011}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v202002 => v202011}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v202002 => v202011}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v202002 => v202011}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v202002 => v202011}/report_service/run_saved_query.py (94%) create mode 100755 examples/ad_manager/v202011/site_service/create_sites.py create mode 100755 examples/ad_manager/v202011/site_service/get_all_sites.py create mode 100755 examples/ad_manager/v202011/site_service/get_sites_requiring_approval.py create mode 100755 examples/ad_manager/v202011/site_service/submit_sites_for_approval.py rename examples/ad_manager/{v202002 => v202011}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v202002 => v202011}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v202002 => v202011}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v202002 => v202011}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/targeting_preset_service/get_all_targeting_presets.py (90%) rename examples/ad_manager/{v202002 => v202011}/team_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/team_service/create_teams.py (99%) rename examples/ad_manager/{v202002 => v202011}/team_service/get_all_teams.py (96%) rename examples/ad_manager/{v202002 => v202011}/team_service/update_teams.py (97%) rename examples/ad_manager/{v202002 => v202011}/user_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/user_service/create_users.py (99%) rename examples/ad_manager/{v202002 => v202011}/user_service/deactivate_users.py (97%) rename examples/ad_manager/{v202002 => v202011}/user_service/get_all_roles.py (99%) rename examples/ad_manager/{v202002 => v202011}/user_service/get_all_users.py (96%) rename examples/ad_manager/{v202002 => v202011}/user_service/get_current_user.py (99%) rename examples/ad_manager/{v202002 => v202011}/user_service/get_user_by_email_address.py (96%) rename examples/ad_manager/{v202002 => v202011}/user_service/update_users.py (96%) rename examples/ad_manager/{v202002 => v202011}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v202002 => v202011}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v202002 => v202011}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v202002 => v202011}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v202002 => v202011}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v202002 => v202011}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index c7a77f83..e74f455e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +26.0.0 -- 11/10/2020 +* Added support for Ad Manager v202011. +* Removed support for Ad Manager v201911. +* Removed examples for Ad Manager v202002. + 25.0.0 -- 08/18/2020 * Added support for Ad Manager v202008. * Removed support for Ad Manager v201908. diff --git a/examples/ad_manager/v202002/adjustment_service/create_traffic_adjustments.py b/examples/ad_manager/v202002/adjustment_service/create_traffic_adjustments.py deleted file mode 100755 index 2fda5da7..00000000 --- a/examples/ad_manager/v202002/adjustment_service/create_traffic_adjustments.py +++ /dev/null @@ -1,143 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2019 Google LLC -# -# 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 adds or replaces a forecast adjustment. - -The adjustment will affect 1920x1080 video traffic in the United States. -""" - -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager - - -def main(client): - # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v202002') - network_service = client.GetService('NetworkService', version='v202002') - - # Get the root ad unit id to target the whole site. - current_network = network_service.getCurrentNetwork() - root_ad_unit_id = current_network['effectiveRootAdUnitId'] - - # Create inventory targeting. - inventory_targeting = { - 'targetedAdUnits': [{ - 'includeDescendants': True, - 'adUnitId': root_ad_unit_id - }] - } - - # Create geo targeting. When using geo targeting with the adjustment service, - # only locations of type COUNTRY are supported. You can download the latest - # geo targets at https://developers.google.com/ad-manager/api/geotargets. - geo_targeting = { - 'targetedLocations': [{ - 'id': 2840 - }] # USA. - } - - # Create ad unit size to define the slice of inventory affected by the - # traffic adjustment. - ad_unit_size = { - 'size': { - 'width': 1920, - 'height': 1080 - }, - 'environmentType': 'VIDEO_PLAYER' - } - - # Create a new historical adjustment targeting next year's January with 105% - # of the traffic of this year's January. - this_january = { - 'startDate': datetime.date(datetime.date.today().year, 1, 1), - 'endDate': datetime.date(datetime.date.today().year, 1, 31) - } - next_january = { - 'startDate': datetime.date(datetime.date.today().year + 1, 1, 1), - 'endDate': datetime.date(datetime.date.today().year + 1, 1, 31) - } - - january_segment = { - 'basisType': 'HISTORICAL', - 'historicalAdjustment': { - 'targetDateRange': next_january, - 'referenceDateRange': this_january, - 'milliPercentMultiplier': 105000 - } - } - - # Create a new absolute adjustment of 500,000 ad opportunities for Christmas - # and 1,000,000 opportunities for Boxing Day of next year. - christmas_day = datetime.date(datetime.date.today().year + 1, 12, 25) - boxing_day = christmas_day + datetime.timedelta(days=1) - holiday_range = {'startDate': christmas_day, 'endDate': boxing_day} - - holiday_segment = { - 'basisType': 'ABSOLUTE', - 'adjustmentTimeSeries': { - 'timeSeriesDateRange': holiday_range, - 'timeSeriesValues': [500000, 1000000], # xsd:long[] - 'valuePeriodType': 'DAILY' - } - } - - # Create a new absolute adjustment of 900,000 ad opportunities for the first - # week of September of next year. - first_week_of_september = { - 'startDate': datetime.date(datetime.date.today().year + 1, 9, 1), - 'endDate': datetime.date(datetime.date.today().year + 1, 9, 7) - } - - september_segment = { - 'basisType': 'ABSOLUTE', - 'adjustmentTimeSeries': { - 'timeSeriesDateRange': first_week_of_september, - 'timeSeriesValues': [900000], - 'valuePeriodType': 'CUSTOM' - } - } - - # Create traffic forecast adjustment object. - adjustment_segments = [january_segment, holiday_segment, september_segment] - adjustment = { - 'filterCriteria': { - 'targeting': { - 'inventoryTargeting': inventory_targeting, - 'geoTargeting': geo_targeting - }, - 'adUnitSizes': [ad_unit_size] - }, - 'forecastAdjustmentSegments': adjustment_segments - } - - # Create or update the traffic adjustment for the given filter criteria on - # the server. - updated_adjustments = adjustment_service.updateTrafficAdjustments( - [adjustment]) - - # Display the results. - for updated_adjustment in updated_adjustments: - print('Traffic forecast adjustment with id %d and %d segments was ' - 'created.' % (updated_adjustment['id'], - len(updated_adjustment['forecastAdjustmentSegments']))) - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v202002/adjustment_service/update_traffic_adjustments.py b/examples/ad_manager/v202002/adjustment_service/update_traffic_adjustments.py deleted file mode 100755 index 706378b7..00000000 --- a/examples/ad_manager/v202002/adjustment_service/update_traffic_adjustments.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2019 Google LLC -# -# 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 adds a historical adjustment of 110% for New Years Day traffic. -""" - -from __future__ import print_function -import datetime - -# Import appropriate modules from the client library. -from googleads import ad_manager - -ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' - - -def main(client, adjustment_id): - # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202002') - - # Create a statement to select a single traffic forecast adjustment by id. - statement = ( - ad_manager.StatementBuilder( - version='v202002').Where('id = :id').WithBindVariable( - 'id', adjustment_id)) - - # Get the forecast traffic adjustment. - response = adjustment_service.getTrafficAdjustmentsByStatement( - statement.ToStatement()) - - # Create a new historical adjustment segment for New Year's Day. - this_new_years = datetime.date(datetime.date.today().year, 12, 31) - next_new_years = datetime.date(datetime.date.today().year + 1, 12, 31) - - new_years_segment = { - 'basisType': 'HISTORICAL', - 'historicalAdjustment': { - 'targetDateRange': { - 'startDate': next_new_years, - 'endDate': next_new_years - }, - 'referenceDateRange': { - 'startDate': this_new_years, - 'endDate': this_new_years - }, - 'milliPercentMultiplier': 110000 - } - } - - if 'results' in response and len(response['results']): - # Update each local traffic adjustment. - updated_adjustments = [] - for adjustment in response['results']: - adjustment['forecastAdjustmentSegments'].append(new_years_segment) - updated_adjustments.append(adjustment) - - # Update traffic adjustments remotely. - adjustments = adjustment_service.updateTrafficAdjustments( - updated_adjustments) - - # Display the results. - if adjustments: - for adjustment in adjustments: - print('Traffic forecast adjustment with id %d and %d segments was ' - 'created.' % (adjustment['id'], - len(adjustment['forecastAdjustmentSegments']))) - else: - print('No traffic adjustments were updated.') - else: - print('No traffic adjustments found to update.') - - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v202002/activity_group_service/__init__.py b/examples/ad_manager/v202011/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/activity_group_service/__init__.py rename to examples/ad_manager/v202011/activity_group_service/__init__.py diff --git a/examples/ad_manager/v202002/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202011/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v202002/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202011/activity_group_service/create_activity_groups.py index 6c8b0b78..ed081d79 100755 --- a/examples/ad_manager/v202002/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202011/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202002') + version='v202011') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v202002/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202011/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v202002/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202011/activity_group_service/get_active_activity_groups.py index 630d7aa0..48f2fa36 100755 --- a/examples/ad_manager/v202002/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202011/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202002') + 'ActivityGroupService', version='v202011') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202002/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202011/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v202002/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202011/activity_group_service/get_all_activity_groups.py index 113ff0f1..ae0b1de1 100755 --- a/examples/ad_manager/v202002/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202011/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202002') + 'ActivityGroupService', version='v202011') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v202002/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202011/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v202002/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202011/activity_group_service/update_activity_groups.py index 5e1e9112..55cb98c5 100755 --- a/examples/ad_manager/v202002/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202011/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202002') + version='v202011') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/activity_service/__init__.py b/examples/ad_manager/v202011/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/activity_service/__init__.py rename to examples/ad_manager/v202011/activity_service/__init__.py diff --git a/examples/ad_manager/v202002/activity_service/create_activities.py b/examples/ad_manager/v202011/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v202002/activity_service/create_activities.py rename to examples/ad_manager/v202011/activity_service/create_activities.py index acce72ca..70b1be68 100755 --- a/examples/ad_manager/v202002/activity_service/create_activities.py +++ b/examples/ad_manager/v202011/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202002') + activity_service = client.GetService('ActivityService', version='v202011') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v202002/activity_service/get_active_activities.py b/examples/ad_manager/v202011/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v202002/activity_service/get_active_activities.py rename to examples/ad_manager/v202011/activity_service/get_active_activities.py index 51cbb477..e2fe78a4 100755 --- a/examples/ad_manager/v202002/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202011/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202002') + activity_service = client.GetService('ActivityService', version='v202011') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202002/activity_service/get_all_activities.py b/examples/ad_manager/v202011/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v202002/activity_service/get_all_activities.py rename to examples/ad_manager/v202011/activity_service/get_all_activities.py index 0bc0c4ff..f66e1fd2 100755 --- a/examples/ad_manager/v202002/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202011/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202002') + activity_service = client.GetService('ActivityService', version='v202011') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v202002/activity_service/update_activities.py b/examples/ad_manager/v202011/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v202002/activity_service/update_activities.py rename to examples/ad_manager/v202011/activity_service/update_activities.py index ca8ecde7..969deafd 100755 --- a/examples/ad_manager/v202002/activity_service/update_activities.py +++ b/examples/ad_manager/v202011/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202002') + activity_service = client.GetService('ActivityService', version='v202011') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202011/adjustment_service/create_forecast_adjustments.py new file mode 100755 index 00000000..4b0ba15b --- /dev/null +++ b/examples/ad_manager/v202011/adjustment_service/create_forecast_adjustments.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a forecast adjustment for New Year's Day traffic.""" + +import datetime +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_TRAFFIC_FORECAST_SEGMENT_ID_HERE' + + +def main(client, traffic_forecast_segment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202011') + + # Create a new forecast adjustment for New Year's Day traffic. + this_new_years = datetime.date(datetime.date.today().year, 1, 1) + next_new_years = datetime.date(datetime.date.today().year + 1, 1, 1) + + forecast = { + 'name': 'Forecast adjustment #%s' % uuid.uuid4(), + 'trafficForecastSegmentId': traffic_forecast_segment_id, + 'dateRange': { + 'startDate': next_new_years, + 'endDate': next_new_years + }, + 'status': 'ACTIVE', + 'volumeType': 'HISTORICAL_BASIS_VOLUME', + 'historicalBasisVolumeSettings': { + 'useParentTrafficForecastSegmentTargeting': True, + 'historicalDateRange': { + 'startDate': this_new_years, + 'endDate': this_new_years + }, + 'multiplierMilliPercent': 110000 + } + } + + forecasts = adjustment_service.createForecastAdjustments([forecast]) + + for forecast in forecasts: + print('Forecast adjustment with id %d and name "%s" was created.' % ( + forecast['id'], forecast['name'] + )) + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, TRAFFIC_FORECAST_SEGMENT_ID) diff --git a/examples/ad_manager/v202011/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202011/adjustment_service/create_traffic_forecast_segments.py new file mode 100755 index 00000000..ab5e014f --- /dev/null +++ b/examples/ad_manager/v202011/adjustment_service/create_traffic_forecast_segments.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a traffic forecast segment for all ad units in the U.S. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service and the network service. + adjustment_service = client.GetService('AdjustmentService', version='v202011') + network_service = client.GetService('NetworkService', version='v202011') + + # Get the root ad unit id to target the whole site. + current_network = network_service.getCurrentNetwork() + root_ad_unit_id = current_network['effectiveRootAdUnitId'] + + # Create inventory targeting. + inventory_targeting = { + 'targetedAdUnits': [{ + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id + }] + } + + # Create targeting for United States traffic. + geo_targeting = { + 'targetedLocations': [{ + 'id': 2840 + }] + } + + # Create traffic forecast segment object. + segment = { + 'name': 'Forecast segment #%s' % uuid.uuid4(), + 'targeting': { + 'inventoryTargeting': inventory_targeting, + 'geoTargeting': geo_targeting + } + } + + # Create the traffic forecast segment on the server. + segments = adjustment_service.createTrafficForecastSegments([segment]) + + # Display the results. + for segment in segments: + print('Traffic forecast segment with id %d and %d forecast adjustments was ' + 'created.' % (segment['id'], + segment['forecastAdjustmentCount'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202002/adjustment_service/get_all_traffic_adjustments.py b/examples/ad_manager/v202011/adjustment_service/get_all_forecast_adjustments.py similarity index 63% rename from examples/ad_manager/v202002/adjustment_service/get_all_traffic_adjustments.py rename to examples/ad_manager/v202011/adjustment_service/get_all_forecast_adjustments.py index 7754fa8a..5cf0742c 100755 --- a/examples/ad_manager/v202002/adjustment_service/get_all_traffic_adjustments.py +++ b/examples/ad_manager/v202011/adjustment_service/get_all_forecast_adjustments.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright 2019 Google LLC +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,9 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This example gets all traffic adjustments.""" - -from __future__ import print_function +"""This example gets all forecast adjustments.""" # Import appropriate modules from the client library. from googleads import ad_manager @@ -24,22 +22,23 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202002') + adjustment_service = client.GetService('AdjustmentService', version='v202011') - # Create a statement to get all forecast traffic adjustments. - statement = ad_manager.StatementBuilder(version='v202002') + # Create a statement to get all forecast adjustments. + statement = ad_manager.StatementBuilder(version='v202011') - # Retrieve a small number of traffic adjustments at a time, paging - # through until all traffic adjustments have been retrieved. + # Retrieve a small number of forecast adjustments at a time, paging + # through until all forecast adjustments have been retrieved. while True: - response = adjustment_service.getTrafficAdjustmentsByStatement( + response = adjustment_service.getForecastAdjustmentsByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): for adjustment in response['results']: - # Print out some information for each traffic adjustment. - print('Traffic forecast adjustment with id %d and %d segments was ' - 'found.' % (adjustment['id'], - len(adjustment['forecastAdjustmentSegments']))) + # Print out some information for each forecast adjustment. + print('Forecast adjustment with id %d and name "%s" belonging to ' + 'forecast segment %d was found.' % + (adjustment['id'], adjustment['name'], + adjustment['trafficForecastSegmentId'])) statement.offset += statement.limit else: break diff --git a/examples/ad_manager/v202011/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202011/adjustment_service/get_all_traffic_forecast_segments.py new file mode 100755 index 00000000..92b52632 --- /dev/null +++ b/examples/ad_manager/v202011/adjustment_service/get_all_traffic_forecast_segments.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 traffic forecast segments.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202011') + + # Create a statement to get all traffic forecast segments. + statement = ad_manager.StatementBuilder(version='v202011') + + # Retrieve a small number of segments at a time, paging through until all + # segments have been retrieved. + while True: + response = adjustment_service.getTrafficForecastSegmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for segment in response['results']: + # Print out some information for each traffic forecast segment. + print('Traffic forecast segment with id %d and name "%s" was found ' % ( + segment['id'], segment['name'], + )) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202011/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202011/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py new file mode 100755 index 00000000..8660f130 --- /dev/null +++ b/examples/ad_manager/v202011/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 forecast adjustments for a traffic forecast segment.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +TRAFFIC_FORECAST_SEGMENT_ID = 'INSERT_FORECAST_SEGMENT_ID_HERE' + + +def main(client, traffic_forecast_segment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202011') + + # Create a statement to get forecast adjustments for a given traffic forecast + # segment id. + statement = ad_manager.StatementBuilder(version='v202011').Where( + 'trafficForecastSegmentId = :segmentId').WithBindVariable( + 'segmentId', traffic_forecast_segment_id) + + # Retrieve a small number of forecast adjustments at a time, paging + # through until all forecast adjustments have been retrieved. + while True: + response = adjustment_service.getForecastAdjustmentsByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for adjustment in response['results']: + # Print out some information for each traffic adjustment. + print('Forecast adjustment with id %d and name "%s" belonging to ' + 'forecast segment %d was found.' % + (adjustment['id'], adjustment['name'], + adjustment['trafficForecastSegmentId'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, int(TRAFFIC_FORECAST_SEGMENT_ID)) diff --git a/examples/ad_manager/v202011/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202011/adjustment_service/update_forecast_adjustments.py new file mode 100755 index 00000000..d62a3177 --- /dev/null +++ b/examples/ad_manager/v202011/adjustment_service/update_forecast_adjustments.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 updates a forecast adjustment's name.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +ADJUSTMENT_ID = 'INSERT_ADJUSTMENT_ID_HERE' + + +def main(client, adjustment_id): + # Initialize the adjustment service. + adjustment_service = client.GetService('AdjustmentService', version='v202011') + + # Create a statement to select a single forecast adjustment by id. + statement = ( + ad_manager.StatementBuilder( + version='v202011').Where('id = :id').WithBindVariable( + 'id', adjustment_id)) + + # Get the forecast adjustment. + response = adjustment_service.getForecastAdjustmentsByStatement( + statement.ToStatement()) + + if 'results' in response and len(response['results']): + # Update each local forecast adjustment's name. + updated_adjustments = [] + for adjustment in response['results']: + adjustment['name'] += ' (updated)' + updated_adjustments.append(adjustment) + + # Update the forecast adjustment on the server. + adjustments = adjustment_service.updateForecastAdjustments( + updated_adjustments) + + # Display the results. + if adjustments: + for adjustment in adjustments: + print('Forecast adjustment with id %d and name "%s" was updated' % ( + adjustment['id'], adjustment['name'])) + else: + print('No forecast adjustments were updated.') + else: + print('No forecast adjustments found to update.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADJUSTMENT_ID) diff --git a/examples/ad_manager/v202002/audience_segment_service/__init__.py b/examples/ad_manager/v202011/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/audience_segment_service/__init__.py rename to examples/ad_manager/v202011/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v202002/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202011/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v202002/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202011/audience_segment_service/create_audience_segments.py index 90d8a97b..26b2955b 100755 --- a/examples/ad_manager/v202002/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202011/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202002') - network_service = client.GetService('NetworkService', version='v202002') + 'AudienceSegmentService', version='v202011') + network_service = client.GetService('NetworkService', version='v202011') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v202002/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202011/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v202002/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202011/audience_segment_service/get_all_audience_segments.py index 3f6e311a..77da7c37 100755 --- a/examples/ad_manager/v202002/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202011/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202002') + 'AudienceSegmentService', version='v202011') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v202002/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202011/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v202002/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202011/audience_segment_service/get_first_party_audience_segments.py index e8b4f705..aea62a57 100755 --- a/examples/ad_manager/v202002/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202011/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202002') + 'AudienceSegmentService', version='v202011') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v202002/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202011/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v202002/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202011/audience_segment_service/populate_first_party_audience_segments.py index 45c7fdfc..d76ff127 100755 --- a/examples/ad_manager/v202002/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202011/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202002') + 'AudienceSegmentService', version='v202011') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202002/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202011/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v202002/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202011/audience_segment_service/update_audience_segments.py index 53495a52..a9eeaac0 100755 --- a/examples/ad_manager/v202002/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202011/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202002') + 'AudienceSegmentService', version='v202011') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202002/cdn_configuration_service/__init__.py b/examples/ad_manager/v202011/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202011/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v202002/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202011/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v202002/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202011/cdn_configuration_service/create_cdn_configurations.py index 0f4daf1d..9dec0df5 100755 --- a/examples/ad_manager/v202002/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202011/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202002') + version='v202011') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v202002/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202011/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v202002/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202011/cdn_configuration_service/get_all_cdn_configurations.py index f314f318..9235d966 100755 --- a/examples/ad_manager/v202002/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202011/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202002') + version='v202011') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202011/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202011/cms_metadata_service/activate_cms_metadata_values.py new file mode 100755 index 00000000..6e00167d --- /dev/null +++ b/examples/ad_manager/v202011/cms_metadata_service/activate_cms_metadata_values.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 activates CMS Metadata Values for a particular CMS Metadata Key. +""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the CMS Metadata Key on which to activate the CMS Metadata +# Values. +CMS_METADATA_KEY_ID = 'INSERT_CMS_METADATA_KEY_ID_HERE' + + +def main(client, cms_metadata_key_id): + # Initialize appropriate service. + cms_metadata_service = client.GetService('CmsMetadataService', + version='v202011') + + # Create query. + statement = (ad_manager.StatementBuilder(version='v202011') + .Where('cmsKeyId = :cmsKeyId AND status = :status') + .WithBindVariable('status', 'INACTIVE') + .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) + + values_activated = 0 + + # Get CMS Metadata Values by statement. + while True: + response = cms_metadata_service.getCmsMetadataValuesByStatement( + statement.ToStatement()) + if 'results' in response and len(response['results']): + for cms_metadata_value in response['results']: + print('CMS Metadata Value with id "%s" and name "%s" will be ' + 'activated.' % (cms_metadata_value['cmsMetadataValueId'], + cms_metadata_value['valueName'])) + + # Perform action. + result = cms_metadata_service.performCmsMetadataValueAction( + {'xsi_type': 'ActivateCmsMetadataValues'}, statement.ToStatement()) + if result and int(result['numChanges']) > 0: + values_activated += int(result['numChanges']) + statement.offset += statement.limit + else: + break + + # Display results. + if values_activated > 0: + print('Number of CMS Metadata Values activated: %s' % values_activated) + else: + print('No CMS Metadata Values were activated.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, CMS_METADATA_KEY_ID) diff --git a/examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_keys.py index 60f4b8f0..7065736c 100755 --- a/examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202002') + 'CmsMetadataService', version='v202011') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_values.py index 4a0225e0..a2791368 100755 --- a/examples/ad_manager/v202002/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202002') + 'CmsMetadataService', version='v202011') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v202002/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202011/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v202002/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202011/cms_metadata_service/get_cms_metadata_values_for_key.py index 54ff95ed..10ea3306 100755 --- a/examples/ad_manager/v202002/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202011/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202002') + 'CmsMetadataService', version='v202011') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v202002').Where( + ad_manager.StatementBuilder(version='v202011').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v202002/company_service/__init__.py b/examples/ad_manager/v202011/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/company_service/__init__.py rename to examples/ad_manager/v202011/company_service/__init__.py diff --git a/examples/ad_manager/v202002/company_service/create_companies.py b/examples/ad_manager/v202011/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v202002/company_service/create_companies.py rename to examples/ad_manager/v202011/company_service/create_companies.py index 6d95315f..206ad1b9 100755 --- a/examples/ad_manager/v202002/company_service/create_companies.py +++ b/examples/ad_manager/v202011/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202002') + company_service = client.GetService('CompanyService', version='v202011') # Create company objects. companies = [ diff --git a/examples/ad_manager/v202002/company_service/get_advertisers.py b/examples/ad_manager/v202011/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v202002/company_service/get_advertisers.py rename to examples/ad_manager/v202011/company_service/get_advertisers.py index 3b2afae6..a6594712 100755 --- a/examples/ad_manager/v202002/company_service/get_advertisers.py +++ b/examples/ad_manager/v202011/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202002') + company_service = client.GetService('CompanyService', version='v202011') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v202002/company_service/get_all_companies.py b/examples/ad_manager/v202011/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v202002/company_service/get_all_companies.py rename to examples/ad_manager/v202011/company_service/get_all_companies.py index c382d43e..cf9948e9 100755 --- a/examples/ad_manager/v202002/company_service/get_all_companies.py +++ b/examples/ad_manager/v202011/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202002') + company_service = client.GetService('CompanyService', version='v202011') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v202002/company_service/update_companies.py b/examples/ad_manager/v202011/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v202002/company_service/update_companies.py rename to examples/ad_manager/v202011/company_service/update_companies.py index 1871d8b9..ce910d40 100755 --- a/examples/ad_manager/v202002/company_service/update_companies.py +++ b/examples/ad_manager/v202011/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202002') + company_service = client.GetService('CompanyService', version='v202011') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/contact_service/__init__.py b/examples/ad_manager/v202011/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/contact_service/__init__.py rename to examples/ad_manager/v202011/contact_service/__init__.py diff --git a/examples/ad_manager/v202002/contact_service/create_contacts.py b/examples/ad_manager/v202011/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v202002/contact_service/create_contacts.py rename to examples/ad_manager/v202011/contact_service/create_contacts.py index 6c571086..045c83bc 100755 --- a/examples/ad_manager/v202002/contact_service/create_contacts.py +++ b/examples/ad_manager/v202011/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202002') + contact_service = client.GetService('ContactService', version='v202011') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v202002/contact_service/get_all_contacts.py b/examples/ad_manager/v202011/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v202002/contact_service/get_all_contacts.py rename to examples/ad_manager/v202011/contact_service/get_all_contacts.py index 92b9cc7a..86186061 100755 --- a/examples/ad_manager/v202002/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202011/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202002') + contact_service = client.GetService('ContactService', version='v202011') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v202002/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202011/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v202002/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202011/contact_service/get_uninvited_contacts.py index 4a978586..e2e8a3fd 100755 --- a/examples/ad_manager/v202002/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202011/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202002') + contact_service = client.GetService('ContactService', version='v202011') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v202002/contact_service/update_contacts.py b/examples/ad_manager/v202011/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v202002/contact_service/update_contacts.py rename to examples/ad_manager/v202011/contact_service/update_contacts.py index a4155af3..ac0f96da 100755 --- a/examples/ad_manager/v202002/contact_service/update_contacts.py +++ b/examples/ad_manager/v202011/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202002') + contact_service = client.GetService('ContactService', version='v202011') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/content_service/__init__.py b/examples/ad_manager/v202011/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/content_service/__init__.py rename to examples/ad_manager/v202011/content_service/__init__.py diff --git a/examples/ad_manager/v202002/content_service/get_all_content.py b/examples/ad_manager/v202011/content_service/get_all_content.py similarity index 96% rename from examples/ad_manager/v202002/content_service/get_all_content.py rename to examples/ad_manager/v202011/content_service/get_all_content.py index 4427bea8..16b8d8b8 100755 --- a/examples/ad_manager/v202002/content_service/get_all_content.py +++ b/examples/ad_manager/v202011/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202002') + content_service = client.GetService('ContentService', version='v202011') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v202002/content_service/get_recently_modified_content.py b/examples/ad_manager/v202011/content_service/get_recently_modified_content.py similarity index 97% rename from examples/ad_manager/v202002/content_service/get_recently_modified_content.py rename to examples/ad_manager/v202011/content_service/get_recently_modified_content.py index a932e1a5..f6b4f5e5 100755 --- a/examples/ad_manager/v202002/content_service/get_recently_modified_content.py +++ b/examples/ad_manager/v202011/content_service/get_recently_modified_content.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202002') + content_service = client.GetService('ContentService', version='v202011') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -35,7 +35,7 @@ def main(client): # lastModifiedDateTime. Changes to content bundle associations will update # the lastModifiedDateTime, but CMS metadata changes may not change the # lastModifiedDateTime. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202002/creative_service/__init__.py b/examples/ad_manager/v202011/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/creative_service/__init__.py rename to examples/ad_manager/v202011/creative_service/__init__.py diff --git a/examples/ad_manager/v202002/creative_service/copy_image_creatives.py b/examples/ad_manager/v202011/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v202002/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202011/creative_service/copy_image_creatives.py index 297fc700..d6a9c5ef 100755 --- a/examples/ad_manager/v202002/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202011/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202002') + creative_service = client.GetService('CreativeService', version='v202011') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v202002/creative_service/create_creative_from_template.py b/examples/ad_manager/v202011/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v202002/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202011/creative_service/create_creative_from_template.py index 3a6c49b1..0383bd08 100755 --- a/examples/ad_manager/v202002/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202011/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202002') + creative_service = client.GetService('CreativeService', version='v202011') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v202002/creative_service/create_creatives.py b/examples/ad_manager/v202011/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v202002/creative_service/create_creatives.py rename to examples/ad_manager/v202011/creative_service/create_creatives.py index 809f511c..9837ce54 100755 --- a/examples/ad_manager/v202002/creative_service/create_creatives.py +++ b/examples/ad_manager/v202011/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202002') + creative_service = client.GetService('CreativeService', version='v202011') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v202002/creative_service/create_custom_creative.py b/examples/ad_manager/v202011/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v202002/creative_service/create_custom_creative.py rename to examples/ad_manager/v202011/creative_service/create_custom_creative.py index 0b9b1930..43d966e6 100755 --- a/examples/ad_manager/v202002/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202011/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202002') + creative_service = client.GetService('CreativeService', version='v202011') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v202002/creative_service/create_native_creative.py b/examples/ad_manager/v202011/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v202002/creative_service/create_native_creative.py rename to examples/ad_manager/v202011/creative_service/create_native_creative.py index 3410aba8..286e760c 100755 --- a/examples/ad_manager/v202002/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202011/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202002') + creative_service = client.GetService('CreativeService', version='v202011') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v202002/creative_service/get_all_creatives.py b/examples/ad_manager/v202011/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v202002/creative_service/get_all_creatives.py rename to examples/ad_manager/v202011/creative_service/get_all_creatives.py index 99deeb1c..a9342402 100755 --- a/examples/ad_manager/v202002/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202011/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202002') + creative_service = client.GetService('CreativeService', version='v202011') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v202002/creative_service/get_image_creatives.py b/examples/ad_manager/v202011/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v202002/creative_service/get_image_creatives.py rename to examples/ad_manager/v202011/creative_service/get_image_creatives.py index ae686a75..aef21911 100755 --- a/examples/ad_manager/v202002/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202011/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202002') + creative_service = client.GetService('CreativeService', version='v202011') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v202002/creative_service/update_creatives.py b/examples/ad_manager/v202011/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v202002/creative_service/update_creatives.py rename to examples/ad_manager/v202011/creative_service/update_creatives.py index d87f699a..3a89c1f3 100755 --- a/examples/ad_manager/v202002/creative_service/update_creatives.py +++ b/examples/ad_manager/v202011/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202002') + creative_service = client.GetService('CreativeService', version='v202011') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v202002/creative_set_service/__init__.py b/examples/ad_manager/v202011/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/creative_set_service/__init__.py rename to examples/ad_manager/v202011/creative_set_service/__init__.py diff --git a/examples/ad_manager/v202002/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202011/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v202002/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202011/creative_set_service/associate_creative_set_to_line_item.py index 79dfcfc3..4718d69d 100755 --- a/examples/ad_manager/v202002/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202011/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202002') + 'LineItemCreativeAssociationService', version='v202011') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v202002/creative_set_service/create_creative_set.py b/examples/ad_manager/v202011/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v202002/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202011/creative_set_service/create_creative_set.py index 6dd22736..1476f5f9 100755 --- a/examples/ad_manager/v202002/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202011/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202002') + version='v202011') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v202002/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202011/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v202002/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202011/creative_set_service/get_all_creative_sets.py index 3b0474ea..747770de 100755 --- a/examples/ad_manager/v202002/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202011/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202002') + 'CreativeSetService', version='v202011') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v202002/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202011/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v202002/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202011/creative_set_service/get_creative_sets_for_master_creative.py index 566e64d4..be37c684 100755 --- a/examples/ad_manager/v202002/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202011/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202002') + 'CreativeSetService', version='v202011') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v202002/creative_set_service/update_creative_set.py b/examples/ad_manager/v202011/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v202002/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202011/creative_set_service/update_creative_set.py index 6cb4d599..d94dd46f 100755 --- a/examples/ad_manager/v202002/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202011/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202002') + version='v202011') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v202002/creative_template_service/__init__.py b/examples/ad_manager/v202011/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/creative_template_service/__init__.py rename to examples/ad_manager/v202011/creative_template_service/__init__.py diff --git a/examples/ad_manager/v202002/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202011/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v202002/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202011/creative_template_service/get_all_creative_templates.py index 3e9a539c..2f106d42 100755 --- a/examples/ad_manager/v202002/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202011/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202002') + 'CreativeTemplateService', version='v202011') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v202002/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202011/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v202002/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202011/creative_template_service/get_system_defined_creative_templates.py index c6000a01..ae3d12a0 100755 --- a/examples/ad_manager/v202002/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202011/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202002') + 'CreativeTemplateService', version='v202011') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v202002/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202011/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v202002/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202011/creative_wrapper_service/create_creative_wrappers.py index a0c9f685..97f6341a 100755 --- a/examples/ad_manager/v202002/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202011/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202002') + version='v202011') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v202002/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202011/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v202002/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202011/creative_wrapper_service/deactivate_creative_wrapper.py index 816de014..af29444a 100755 --- a/examples/ad_manager/v202002/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202011/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202002') + version='v202011') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202002/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202011/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202002/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202011/creative_wrapper_service/get_active_creative_wrappers.py index a24ee551..83e3acad 100755 --- a/examples/ad_manager/v202002/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202011/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202002') + 'CreativeWrapperService', version='v202011') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202002/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202011/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202002/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202011/creative_wrapper_service/get_all_creative_wrappers.py index d5bb244a..d6b40d7a 100755 --- a/examples/ad_manager/v202002/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202011/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202002') + 'CreativeWrapperService', version='v202011') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v202002/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202011/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v202002/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202011/creative_wrapper_service/update_creative_wrappers.py index f67d8aeb..7cbfc3db 100755 --- a/examples/ad_manager/v202002/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202011/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202002') + version='v202011') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v202002/custom_field_service/__init__.py b/examples/ad_manager/v202011/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/custom_field_service/__init__.py rename to examples/ad_manager/v202011/custom_field_service/__init__.py diff --git a/examples/ad_manager/v202002/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202011/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v202002/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202011/custom_field_service/create_custom_field_options.py index 42ec0012..920a506d 100755 --- a/examples/ad_manager/v202002/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202011/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202002') + 'CustomFieldService', version='v202011') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v202002/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202011/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v202002/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202011/custom_field_service/create_custom_fields.py index bc59ad59..a06a40db 100755 --- a/examples/ad_manager/v202002/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202011/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202002') + 'CustomFieldService', version='v202011') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v202002/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202011/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v202002/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202011/custom_field_service/deactivate_all_line_item_custom_fields.py index 69012a46..3406304f 100755 --- a/examples/ad_manager/v202002/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202011/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202002') + 'CustomFieldService', version='v202011') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202002/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202011/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v202002/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202011/custom_field_service/get_all_custom_fields.py index ca0d75f8..64531912 100755 --- a/examples/ad_manager/v202002/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202011/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202002') + 'CustomFieldService', version='v202011') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v202002/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202011/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v202002/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202011/custom_field_service/get_custom_fields_for_line_items.py index 6039b524..85276bdc 100755 --- a/examples/ad_manager/v202002/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202011/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202002') + 'CustomFieldService', version='v202011') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v202002/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202011/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v202002/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202011/custom_field_service/set_line_item_custom_field_value.py index a9edc764..924f3cbf 100755 --- a/examples/ad_manager/v202002/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202011/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v202002') + 'CustomFieldService', version='v202011') - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v202002') + custom_field_statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v202002') + ad_manager.StatementBuilder(version='v202011') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v202002') + line_item_statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v202002/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202011/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v202002/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202011/custom_field_service/update_custom_fields.py index 4b71431a..179880c4 100755 --- a/examples/ad_manager/v202002/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202011/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202002') + 'CustomFieldService', version='v202011') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v202002/custom_targeting_service/__init__.py b/examples/ad_manager/v202011/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/custom_targeting_service/__init__.py rename to examples/ad_manager/v202011/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v202002/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202011/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v202002/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202011/custom_targeting_service/create_custom_targeting_keys_and_values.py index 0a76102f..2faa4aca 100755 --- a/examples/ad_manager/v202002/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202011/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202002') + 'CustomTargetingService', version='v202011') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_keys.py index 4fd4c98b..dad2da13 100755 --- a/examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202002') + 'CustomTargetingService', version='v202011') - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v202002') + key_statement = (ad_manager.StatementBuilder(version='v202011') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_values.py index b5ae7465..85686c40 100755 --- a/examples/ad_manager/v202002/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202002') + 'CustomTargetingService', version='v202011') - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v202002') + value_statement = (ad_manager.StatementBuilder(version='v202011') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v202002/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202011/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202002/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202011/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 5723a964..44ac874e 100755 --- a/examples/ad_manager/v202002/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202011/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202002') + 'CustomTargetingService', version='v202011') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v202002') + targeting_key_statement = ad_manager.StatementBuilder(version='v202011') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v202002/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202011/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202002/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202011/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 45e353b5..3bfe141f 100755 --- a/examples/ad_manager/v202002/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202011/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202002') + 'CustomTargetingService', version='v202011') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v202002') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202011') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_keys.py index a5676167..fdc28886 100755 --- a/examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202002') + 'CustomTargetingService', version='v202011') - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_values.py index 3f07c4a0..6474df61 100755 --- a/examples/ad_manager/v202002/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202002') + 'CustomTargetingService', version='v202011') - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v202002/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202011/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v202002/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202011/forecast_service/get_availability_forecast.py index f550f3c8..2abd24ca 100755 --- a/examples/ad_manager/v202002/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202011/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202002') - network_service = client.GetService('NetworkService', version='v202002') + forecast_service = client.GetService('ForecastService', version='v202011') + network_service = client.GetService('NetworkService', version='v202011') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202002/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202011/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v202002/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202011/forecast_service/get_availability_forecast_for_line_item.py index 688f8500..f146ad24 100755 --- a/examples/ad_manager/v202002/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202011/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202002') + forecast_service = client.GetService('ForecastService', version='v202011') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v202002/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202011/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v202002/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202011/forecast_service/get_delivery_forecast_for_line_items.py index 18c1a127..76e201ad 100755 --- a/examples/ad_manager/v202002/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202011/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202002') + forecast_service = client.GetService('ForecastService', version='v202011') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v202011/forecast_service/get_traffic_data.py b/examples/ad_manager/v202011/forecast_service/get_traffic_data.py new file mode 100755 index 00000000..1c40beee --- /dev/null +++ b/examples/ad_manager/v202011/forecast_service/get_traffic_data.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# +# Copyright 2020, Google LLC +# +# 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 the forecasted run-of-network traffic data.""" + + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v202011') + network_service = client.GetService('NetworkService', version='v202011') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + + # Create a start date that's 7 days in the past and an end date that's 7 days + # in the future. + today = datetime.date.today() + start_date = today - datetime.timedelta(days=7) + end_date = today + datetime.timedelta(days=7) + + # Create targeting. + targeting = { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + } + } + + # Request the traffic forecast data. + traffic_data = forecast_service.getTrafficData({ + 'targeting': targeting, + 'requestedDateRange': { + 'startDate': start_date, + 'endDate': end_date + } + }) + + # Display historical data. + historical_time_series = traffic_data['historicalTimeSeries'] + if historical_time_series is None: + print('No historical data to display.') + else: + historical_start_date, historical_end_date = GetDatesFromForecastTimeSeries( + historical_time_series) + + print('Historical Data:') + offset = 0 + current_date = historical_start_date + while current_date <= historical_end_date: + print('%s: %d' % (current_date.isoformat(), + historical_time_series['values'][offset])) + offset += 1 + current_date = historical_start_date + datetime.timedelta(days=offset) + + # Display forecasted data. + forecasted_time_series = traffic_data['forecastedTimeSeries'] + if forecasted_time_series is None: + print('No forecasted data to display.') + else: + forecasted_start_date, forecasted_end_date = GetDatesFromForecastTimeSeries( + forecasted_time_series) + + print('Forecasted Data:') + offset = 0 + current_date = forecasted_start_date + while current_date <= forecasted_end_date: + print('%s: %d' % (current_date.isoformat(), + forecasted_time_series['values'][offset])) + offset += 1 + current_date = forecasted_start_date + datetime.timedelta(days=offset) + + +def GetDatesFromForecastTimeSeries(time_series): + """Creates datetime.date objects from a forecast time series object. + + Args: + time_series: The forecast time series containing start and end date info. + + Returns: + A tuple of datetime.date objects, the first representing the start date and + the second representing the end date. + """ + date_range = time_series['timeSeriesDateRange'] + start_date = datetime.date( + date_range['startDate']['year'], + date_range['startDate']['month'], + date_range['startDate']['day'] + ) + end_date = datetime.date( + date_range['endDate']['year'], + date_range['endDate']['month'], + date_range['endDate']['day'] + ) + return start_date, end_date + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202002/inventory_service/__init__.py b/examples/ad_manager/v202011/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/inventory_service/__init__.py rename to examples/ad_manager/v202011/inventory_service/__init__.py diff --git a/examples/ad_manager/v202002/inventory_service/archive_ad_units.py b/examples/ad_manager/v202011/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v202002/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202011/inventory_service/archive_ad_units.py index e32aac8f..9acc7c91 100755 --- a/examples/ad_manager/v202002/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202011/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202002') + inventory_service = client.GetService('InventoryService', version='v202011') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v202002/inventory_service/create_ad_units.py b/examples/ad_manager/v202011/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v202002/inventory_service/create_ad_units.py rename to examples/ad_manager/v202011/inventory_service/create_ad_units.py index c647915f..2c37336f 100755 --- a/examples/ad_manager/v202002/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202011/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202002') + inventory_service = client.GetService('InventoryService', version='v202011') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v202002/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202011/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v202002/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202011/inventory_service/get_ad_unit_hierarchy.py index 51de4ae5..6bb72bae 100755 --- a/examples/ad_manager/v202002/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202011/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202002') - inventory_service = client.GetService('InventoryService', version='v202002') + network_service = client.GetService('NetworkService', version='v202011') + inventory_service = client.GetService('InventoryService', version='v202011') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v202002/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202011/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v202002/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202011/inventory_service/get_all_ad_unit_sizes.py index a712d67f..e5f6a815 100755 --- a/examples/ad_manager/v202002/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202011/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v202002') + 'InventoryService', version='v202011') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v202002/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202011/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v202002/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202011/inventory_service/get_all_ad_units.py index 62580bb6..488198c5 100755 --- a/examples/ad_manager/v202002/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202011/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v202002') + ad_unit_service = client.GetService('InventoryService', version='v202011') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v202002/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202011/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v202002/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202011/inventory_service/get_top_level_ad_units.py index 8fc0c935..97636b8e 100755 --- a/examples/ad_manager/v202002/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202011/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202002') - inventory_service = client.GetService('InventoryService', version='v202002') + network_service = client.GetService('NetworkService', version='v202011') + inventory_service = client.GetService('InventoryService', version='v202011') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v202002/inventory_service/update_ad_units.py b/examples/ad_manager/v202011/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v202002/inventory_service/update_ad_units.py rename to examples/ad_manager/v202011/inventory_service/update_ad_units.py index 5a851802..bdddab9b 100755 --- a/examples/ad_manager/v202002/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202011/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202002') + inventory_service = client.GetService('InventoryService', version='v202011') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v202002/label_service/__init__.py b/examples/ad_manager/v202011/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/label_service/__init__.py rename to examples/ad_manager/v202011/label_service/__init__.py diff --git a/examples/ad_manager/v202002/label_service/create_labels.py b/examples/ad_manager/v202011/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v202002/label_service/create_labels.py rename to examples/ad_manager/v202011/label_service/create_labels.py index 773b258b..c64a67bf 100755 --- a/examples/ad_manager/v202002/label_service/create_labels.py +++ b/examples/ad_manager/v202011/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202002') + label_service = client.GetService('LabelService', version='v202011') # Create label objects. labels = [] diff --git a/examples/ad_manager/v202002/label_service/deactivate_labels.py b/examples/ad_manager/v202011/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v202002/label_service/deactivate_labels.py rename to examples/ad_manager/v202011/label_service/deactivate_labels.py index 19810e9c..149c19bc 100755 --- a/examples/ad_manager/v202002/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202011/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202002') + label_service = client.GetService('LabelService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202002/label_service/get_active_labels.py b/examples/ad_manager/v202011/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v202002/label_service/get_active_labels.py rename to examples/ad_manager/v202011/label_service/get_active_labels.py index a45a8f9c..981161e7 100755 --- a/examples/ad_manager/v202002/label_service/get_active_labels.py +++ b/examples/ad_manager/v202011/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202002') + label_service = client.GetService('LabelService', version='v202011') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202002/label_service/get_all_labels.py b/examples/ad_manager/v202011/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v202002/label_service/get_all_labels.py rename to examples/ad_manager/v202011/label_service/get_all_labels.py index 04c20c1b..07138c6a 100755 --- a/examples/ad_manager/v202002/label_service/get_all_labels.py +++ b/examples/ad_manager/v202011/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202002') + label_service = client.GetService('LabelService', version='v202011') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v202002/label_service/update_labels.py b/examples/ad_manager/v202011/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v202002/label_service/update_labels.py rename to examples/ad_manager/v202011/label_service/update_labels.py index d1ca89f0..7801cd6b 100755 --- a/examples/ad_manager/v202002/label_service/update_labels.py +++ b/examples/ad_manager/v202011/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202002') + label_service = client.GetService('LabelService', version='v202011') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202002/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202011/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202011/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v202002/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202011/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v202002/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202011/line_item_creative_association_service/create_licas.py index 209f089e..4eb2e11b 100755 --- a/examples/ad_manager/v202002/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202011/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202002') + 'LineItemCreativeAssociationService', version='v202011') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v202002/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202011/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v202002/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202011/line_item_creative_association_service/deactivate_licas.py index de1567b2..6ba8222e 100755 --- a/examples/ad_manager/v202002/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202011/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202002') + 'LineItemCreativeAssociationService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v202002/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202011/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v202002/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202011/line_item_creative_association_service/get_all_licas.py index 0d88e4d7..645404a4 100755 --- a/examples/ad_manager/v202002/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202011/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202002') + 'LineItemCreativeAssociationService', version='v202011') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v202002/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202011/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v202002/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202011/line_item_creative_association_service/get_licas_for_line_item.py index ef314207..530294c1 100755 --- a/examples/ad_manager/v202002/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202011/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202002') + 'LineItemCreativeAssociationService', version='v202011') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v202002/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202011/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v202002/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202011/line_item_creative_association_service/update_licas.py index 6a6799ca..49977fa6 100755 --- a/examples/ad_manager/v202002/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202011/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202002') + 'LineItemCreativeAssociationService', version='v202011') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v202002/line_item_service/__init__.py b/examples/ad_manager/v202011/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/line_item_service/__init__.py rename to examples/ad_manager/v202011/line_item_service/__init__.py diff --git a/examples/ad_manager/v202002/line_item_service/activate_line_items.py b/examples/ad_manager/v202011/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v202002/line_item_service/activate_line_items.py rename to examples/ad_manager/v202011/line_item_service/activate_line_items.py index efe30d02..6b8825a5 100755 --- a/examples/ad_manager/v202002/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202011/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202002/line_item_service/create_line_items.py b/examples/ad_manager/v202011/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v202002/line_item_service/create_line_items.py rename to examples/ad_manager/v202011/line_item_service/create_line_items.py index 613f041a..5ceb5d2c 100755 --- a/examples/ad_manager/v202002/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202011/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202002/line_item_service/create_video_line_item.py b/examples/ad_manager/v202011/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v202002/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202011/line_item_service/create_video_line_item.py index 6566364b..e161f950 100755 --- a/examples/ad_manager/v202002/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202011/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202002/line_item_service/get_all_line_items.py b/examples/ad_manager/v202011/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v202002/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202011/line_item_service/get_all_line_items.py index cc6dd6d7..d97003d4 100755 --- a/examples/ad_manager/v202002/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202011/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v202002/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202011/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v202002/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202011/line_item_service/get_line_items_that_need_creatives.py index a1ab3d55..05c6fe1b 100755 --- a/examples/ad_manager/v202002/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202011/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v202002/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202011/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v202002/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202011/line_item_service/get_recently_updated_line_items.py index f64dea08..4c415960 100755 --- a/examples/ad_manager/v202002/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202011/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202002/line_item_service/pause_line_items.py b/examples/ad_manager/v202011/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v202002/line_item_service/pause_line_items.py rename to examples/ad_manager/v202011/line_item_service/pause_line_items.py index 1b9466bb..b1bdc6e1 100755 --- a/examples/ad_manager/v202002/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202011/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v202002/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202011/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v202002/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202011/line_item_service/target_custom_criteria.py index 8ea8c72f..7364f232 100755 --- a/examples/ad_manager/v202002/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202011/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/line_item_service/update_line_items.py b/examples/ad_manager/v202011/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v202002/line_item_service/update_line_items.py rename to examples/ad_manager/v202011/line_item_service/update_line_items.py index e90133ea..092d8764 100755 --- a/examples/ad_manager/v202002/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202011/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202002') + line_item_service = client.GetService('LineItemService', version='v202011') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v202002/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202011/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202002/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202011/live_stream_event_service/activate_live_stream_events.py index 16e75350..616ac53c 100755 --- a/examples/ad_manager/v202002/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202011/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202002') + 'LiveStreamEventService', version='v202011') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v202002/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202011/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v202002/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202011/live_stream_event_service/create_live_stream_events.py index 6862e2e9..d75aa0d4 100755 --- a/examples/ad_manager/v202002/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202011/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v202002') + 'LiveStreamEventService', version='v202011') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v202002/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202011/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v202002/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202011/live_stream_event_service/get_all_live_stream_events.py index 3a0c1f03..3385e5f3 100755 --- a/examples/ad_manager/v202002/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202011/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202002') + 'LiveStreamEventService', version='v202011') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v202002/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202011/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v202002/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202011/live_stream_event_service/register_sessions_for_monitoring.py index bb96a8e2..b0e156f2 100755 --- a/examples/ad_manager/v202002/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202011/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202002') + 'LiveStreamEventService', version='v202011') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v202002/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202011/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202002/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202011/live_stream_event_service/update_live_stream_events.py index b5d9fc57..ff96c650 100755 --- a/examples/ad_manager/v202002/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202011/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v202002') + 'LiveStreamEventService', version='v202011') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v202002/native_style_service/__init__.py b/examples/ad_manager/v202011/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/native_style_service/__init__.py rename to examples/ad_manager/v202011/native_style_service/__init__.py diff --git a/examples/ad_manager/v202002/native_style_service/create_native_styles.py b/examples/ad_manager/v202011/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v202002/native_style_service/create_native_styles.py rename to examples/ad_manager/v202011/native_style_service/create_native_styles.py index b8d533af..a21b32d9 100755 --- a/examples/ad_manager/v202002/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202011/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202002') + version='v202011') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v202002/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202011/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v202002/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202011/native_style_service/get_all_native_styles.py index 31215249..75f8daeb 100755 --- a/examples/ad_manager/v202002/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202011/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202002') + version='v202011') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v202002/network_service/__init__.py b/examples/ad_manager/v202011/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/network_service/__init__.py rename to examples/ad_manager/v202011/network_service/__init__.py diff --git a/examples/ad_manager/v202002/network_service/get_all_networks.py b/examples/ad_manager/v202011/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v202002/network_service/get_all_networks.py rename to examples/ad_manager/v202011/network_service/get_all_networks.py index dba8aa0e..32b75f9f 100755 --- a/examples/ad_manager/v202002/network_service/get_all_networks.py +++ b/examples/ad_manager/v202011/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202002') + network_service = client.GetService('NetworkService', version='v202011') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v202002/network_service/get_current_network.py b/examples/ad_manager/v202011/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v202002/network_service/get_current_network.py rename to examples/ad_manager/v202011/network_service/get_current_network.py index cd4f3955..85322781 100755 --- a/examples/ad_manager/v202002/network_service/get_current_network.py +++ b/examples/ad_manager/v202011/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202002') + network_service = client.GetService('NetworkService', version='v202011') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202011/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202011/network_service/get_default_third_party_data_declaration.py new file mode 100755 index 00000000..fde28b9e --- /dev/null +++ b/examples/ad_manager/v202011/network_service/get_default_third_party_data_declaration.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2020, Google LLC +# +# 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 the network's default third party data declarations.""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v202011') + pql_service = client.GetService('PublisherQueryLanguageService', + version='v202011') + + # Fetch the default third party data declarations. + declarations = network_service.getDefaultThirdPartyDataDeclaration() + + # Display the results. + if declarations is None: + print('No default ad technology partners have been set on this network.') + elif (declarations['declarationType'] == 'NONE' or + not declarations['thirdPartyCompanyIds']): + print('This network has specified that there are no ad technology providers' + ' associated with its reservation creatives by default.') + else: + print('This network has specified %d ad technology provider(s) associated' + ' with its reservation creatives by default:' % + len(declarations['thirdPartyCompanyIds'])) + + # In this case, there are third party companies to be displayed, so fetch + # the company names from the Rich_Media_Ad_Company PQL table. + statement = (ad_manager.StatementBuilder(version='v202011') + .Select('Id, Name') + .From('Rich_Media_Ad_Company') + .Where('Id IN (:company_ids)') + .WithBindVariable('company_ids', + declarations['thirdPartyCompanyIds'])) + + while True: + response = pql_service.select(statement.ToStatement()) + if 'rows' in response and len(response['rows']): + for company in response['rows']: + print('Name: %s, id: %s' % (company['values'][1]['value'], + company['values'][0]['value'])) + statement.offset += statement.limit + else: + break + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202002/network_service/make_test_network.py b/examples/ad_manager/v202011/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v202002/network_service/make_test_network.py rename to examples/ad_manager/v202011/network_service/make_test_network.py index 691bf6b5..39625f78 100755 --- a/examples/ad_manager/v202002/network_service/make_test_network.py +++ b/examples/ad_manager/v202011/network_service/make_test_network.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202002') + network_service = client.GetService('NetworkService', version='v202011') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v202002/order_service/__init__.py b/examples/ad_manager/v202011/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/order_service/__init__.py rename to examples/ad_manager/v202011/order_service/__init__.py diff --git a/examples/ad_manager/v202002/order_service/approve_orders.py b/examples/ad_manager/v202011/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v202002/order_service/approve_orders.py rename to examples/ad_manager/v202011/order_service/approve_orders.py index ab903647..fce5c750 100755 --- a/examples/ad_manager/v202002/order_service/approve_orders.py +++ b/examples/ad_manager/v202011/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202002') + order_service = client.GetService('OrderService', version='v202011') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v202002/order_service/create_orders.py b/examples/ad_manager/v202011/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v202002/order_service/create_orders.py rename to examples/ad_manager/v202011/order_service/create_orders.py index 2521568a..3823ce8e 100755 --- a/examples/ad_manager/v202002/order_service/create_orders.py +++ b/examples/ad_manager/v202011/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202002') + order_service = client.GetService('OrderService', version='v202011') # Create order objects. orders = [] diff --git a/examples/ad_manager/v202002/order_service/get_all_orders.py b/examples/ad_manager/v202011/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v202002/order_service/get_all_orders.py rename to examples/ad_manager/v202011/order_service/get_all_orders.py index f1ead8ea..68cc1a24 100755 --- a/examples/ad_manager/v202002/order_service/get_all_orders.py +++ b/examples/ad_manager/v202011/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202002') + order_service = client.GetService('OrderService', version='v202011') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v202002/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202011/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v202002/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202011/order_service/get_orders_starting_soon.py index 36e29d80..8c2597ce 100755 --- a/examples/ad_manager/v202002/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202011/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202002') + order_service = client.GetService('OrderService', version='v202011') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v202002/order_service/update_orders.py b/examples/ad_manager/v202011/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v202002/order_service/update_orders.py rename to examples/ad_manager/v202011/order_service/update_orders.py index 3638a12e..8464eead 100755 --- a/examples/ad_manager/v202002/order_service/update_orders.py +++ b/examples/ad_manager/v202011/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202002') + order_service = client.GetService('OrderService', version='v202011') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202002/placement_service/create_placements.py b/examples/ad_manager/v202011/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v202002/placement_service/create_placements.py rename to examples/ad_manager/v202011/placement_service/create_placements.py index 5083b1d3..7e9cf087 100755 --- a/examples/ad_manager/v202002/placement_service/create_placements.py +++ b/examples/ad_manager/v202011/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202002') - inventory_service = client.GetService('InventoryService', version='v202002') + placement_service = client.GetService('PlacementService', version='v202011') + inventory_service = client.GetService('InventoryService', version='v202011') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v202002/placement_service/deactivate_placements.py b/examples/ad_manager/v202011/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v202002/placement_service/deactivate_placements.py rename to examples/ad_manager/v202011/placement_service/deactivate_placements.py index b932df93..879aef44 100755 --- a/examples/ad_manager/v202002/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202011/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202002') + placement_service = client.GetService('PlacementService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/placement_service/get_active_placements.py b/examples/ad_manager/v202011/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v202002/placement_service/get_active_placements.py rename to examples/ad_manager/v202011/placement_service/get_active_placements.py index f3736225..6f300b5a 100755 --- a/examples/ad_manager/v202002/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202011/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202002') + placement_service = client.GetService('PlacementService', version='v202011') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202002/placement_service/get_all_placements.py b/examples/ad_manager/v202011/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v202002/placement_service/get_all_placements.py rename to examples/ad_manager/v202011/placement_service/get_all_placements.py index 014a663c..d530df49 100755 --- a/examples/ad_manager/v202002/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202011/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202002') + placement_service = client.GetService('PlacementService', version='v202011') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v202002/placement_service/update_placements.py b/examples/ad_manager/v202011/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v202002/placement_service/update_placements.py rename to examples/ad_manager/v202011/placement_service/update_placements.py index 2eb8c93e..8e475329 100755 --- a/examples/ad_manager/v202002/placement_service/update_placements.py +++ b/examples/ad_manager/v202011/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202002') + placement_service = client.GetService('PlacementService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v202002/proposal_line_item_service/__init__.py b/examples/ad_manager/v202011/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202011/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v202002/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202011/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202002/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202011/proposal_line_item_service/archive_proposal_line_items.py index 69cb78a7..a9257659 100755 --- a/examples/ad_manager/v202002/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202011/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202002') + 'ProposalLineItemService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202011/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v202002/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202011/proposal_line_item_service/create_proposal_line_items.py index 64903d6d..df6746f9 100755 --- a/examples/ad_manager/v202002/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202011/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202002') - network_service = client.GetService('NetworkService', version='v202002') + 'ProposalLineItemService', version='v202011') + network_service = client.GetService('NetworkService', version='v202011') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202002/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202011/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202002/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202011/proposal_line_item_service/get_all_proposal_line_items.py index a22588ab..5610a67e 100755 --- a/examples/ad_manager/v202002/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202011/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202002') + 'ProposalLineItemService', version='v202011') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v202002/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202011/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v202002/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202011/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 2a8b4bb7..7c3902b8 100755 --- a/examples/ad_manager/v202002/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202011/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202002') + 'ProposalLineItemService', version='v202011') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v202002/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202011/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202002/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202011/proposal_line_item_service/update_proposal_line_items.py index 8b1125f1..fefb05d4 100755 --- a/examples/ad_manager/v202002/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202011/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202002') + 'ProposalLineItemService', version='v202011') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/proposal_service/__init__.py b/examples/ad_manager/v202011/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/proposal_service/__init__.py rename to examples/ad_manager/v202011/proposal_service/__init__.py diff --git a/examples/ad_manager/v202002/proposal_service/create_proposals.py b/examples/ad_manager/v202011/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v202002/proposal_service/create_proposals.py rename to examples/ad_manager/v202011/proposal_service/create_proposals.py index 1a0ef031..e28bc305 100755 --- a/examples/ad_manager/v202002/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202011/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v202002') + proposal_service = client.GetService('ProposalService', version='v202011') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v202002/proposal_service/get_all_proposals.py b/examples/ad_manager/v202011/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v202002/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202011/proposal_service/get_all_proposals.py index 7f65989f..c126f7ad 100755 --- a/examples/ad_manager/v202002/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202011/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202002') + proposal_service = client.GetService('ProposalService', version='v202011') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v202002/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202011/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v202002/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202011/proposal_service/get_marketplace_comments.py index 58dda26e..c1c6e05f 100755 --- a/examples/ad_manager/v202002/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202011/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v202002') + 'ProposalService', version='v202011') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v202002/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202011/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v202002/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202011/proposal_service/get_proposals_awaiting_seller_review.py index 9349fb99..a8a70e50 100755 --- a/examples/ad_manager/v202002/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202011/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202002') + proposal_service = client.GetService('ProposalService', version='v202011') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v202002/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202011/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v202002/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202011/proposal_service/request_buyers_acceptance.py index 72a18ffd..f83e8bcc 100755 --- a/examples/ad_manager/v202002/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202011/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202002') + proposal_service = client.GetService('ProposalService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v202002/proposal_service/update_proposals.py b/examples/ad_manager/v202011/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v202002/proposal_service/update_proposals.py rename to examples/ad_manager/v202011/proposal_service/update_proposals.py index 5945f354..ac806926 100755 --- a/examples/ad_manager/v202002/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202011/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202002') + proposal_service = client.GetService('ProposalService', version='v202011') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v202002/publisher_query_language_service/__init__.py b/examples/ad_manager/v202011/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202011/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v202002/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202011/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v202002/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202011/publisher_query_language_service/fetch_match_tables.py index 693be107..4787b36d 100755 --- a/examples/ad_manager/v202002/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202011/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202002/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202011/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v202002/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202011/publisher_query_language_service/get_all_browsers.py index 8c52551f..0536323c 100755 --- a/examples/ad_manager/v202002/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202011/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v202002/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202011/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v202002/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202011/publisher_query_language_service/get_all_programmatic_buyers.py index 1a1f19d3..56b40951 100755 --- a/examples/ad_manager/v202002/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202011/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202002') + data_downloader = client.GetDataDownloader(version='v202011') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202002/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202011/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v202002/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202011/publisher_query_language_service/get_geo_targets.py index 8d1e3622..7f388f52 100755 --- a/examples/ad_manager/v202002/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202011/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v202002/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202011/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v202002/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202011/publisher_query_language_service/get_line_items_named_like.py index 2169f460..a13f590f 100755 --- a/examples/ad_manager/v202002/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202011/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202011/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202011/publisher_query_language_service/get_mcm_earnings.py new file mode 100755 index 00000000..96ef524d --- /dev/null +++ b/examples/ad_manager/v202011/publisher_query_language_service/get_mcm_earnings.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 Multiple Customer Management earnings for the prior month. +""" + +import datetime +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize a report downloader. + data_downloader = client.GetDataDownloader(version='v202011') + + with tempfile.NamedTemporaryFile( + prefix='mcm_earnings_', + suffix='.csv', mode='w', delete=False) as mcm_earnings_file: + + this_month_start = datetime.date.today().replace(day=1) + last_month_end = this_month_start - datetime.timedelta(days=1) + last_month_start = last_month_end.replace(day=1) + + mcm_earnings_query = ('SELECT Month, ChildName, ChildNetworkCode, ' + 'TotalEarningsCurrencyCode, TotalEarningsMicros, ' + 'ParentPaymentCurrencyCode, ParentPaymentMicros, ' + 'ChildPaymentCurrencyCode, ChildPaymentMicros, ' + 'DeductionsMicros ' + 'FROM Mcm_Earnings ' + 'WHERE Month = :month ' + 'ORDER BY ChildNetworkCode') + + # Downloads the response from PQL select statement to the specified file + data_downloader.DownloadPqlResultToCsv( + mcm_earnings_query, mcm_earnings_file, {'month': last_month_start}) + + print('Saved MCM earnings to... %s' % mcm_earnings_file.name) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202002/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202011/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v202002/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202011/publisher_query_language_service/get_recent_changes.py index f6fb7e4d..16d14efd 100755 --- a/examples/ad_manager/v202002/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202011/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v202002') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202011') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v202002/report_service/__init__.py b/examples/ad_manager/v202011/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/report_service/__init__.py rename to examples/ad_manager/v202011/report_service/__init__.py diff --git a/examples/ad_manager/v202002/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202011/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v202002/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202011/report_service/run_ad_exchange_report.py index 9480cc76..85806eda 100755 --- a/examples/ad_manager/v202002/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202011/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') # Create report job. report_job = { diff --git a/examples/ad_manager/v202002/report_service/run_delivery_report.py b/examples/ad_manager/v202011/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v202002/report_service/run_delivery_report.py rename to examples/ad_manager/v202011/report_service/run_delivery_report.py index 676ceb35..ef6f0622 100755 --- a/examples/ad_manager/v202002/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202011/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202002/report_service/run_inventory_report.py b/examples/ad_manager/v202011/report_service/run_inventory_report.py similarity index 97% rename from examples/ad_manager/v202002/report_service/run_inventory_report.py rename to examples/ad_manager/v202011/report_service/run_inventory_report.py index a0875307..2859a081 100755 --- a/examples/ad_manager/v202002/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202011/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') # Create report job. report_job = { diff --git a/examples/ad_manager/v202002/report_service/run_reach_report.py b/examples/ad_manager/v202011/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v202002/report_service/run_reach_report.py rename to examples/ad_manager/v202011/report_service/run_reach_report.py index 93da683d..47094ca7 100755 --- a/examples/ad_manager/v202002/report_service/run_reach_report.py +++ b/examples/ad_manager/v202011/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') # Create report job. report_job = { diff --git a/examples/ad_manager/v202002/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202011/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v202002/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202011/report_service/run_report_and_create_match_table.py index a7698738..7a2753dd 100755 --- a/examples/ad_manager/v202002/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202011/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202002/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202011/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v202002/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202011/report_service/run_report_with_custom_fields.py index f85544c4..f8ce5b96 100755 --- a/examples/ad_manager/v202002/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202011/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') # Create report job. report_job = { diff --git a/examples/ad_manager/v202002/report_service/run_sales_report.py b/examples/ad_manager/v202011/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v202002/report_service/run_sales_report.py rename to examples/ad_manager/v202011/report_service/run_sales_report.py index 2e8455aa..e844afd0 100755 --- a/examples/ad_manager/v202002/report_service/run_sales_report.py +++ b/examples/ad_manager/v202011/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') # Create report job. report_job = { diff --git a/examples/ad_manager/v202002/report_service/run_saved_query.py b/examples/ad_manager/v202011/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v202002/report_service/run_saved_query.py rename to examples/ad_manager/v202011/report_service/run_saved_query.py index 8f6eebeb..7eb5fb24 100755 --- a/examples/ad_manager/v202002/report_service/run_saved_query.py +++ b/examples/ad_manager/v202011/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v202002') + report_service = client.GetService('ReportService', version='v202011') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202002') + report_downloader = client.GetDataDownloader(version='v202011') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/site_service/create_sites.py b/examples/ad_manager/v202011/site_service/create_sites.py new file mode 100755 index 00000000..db184eb8 --- /dev/null +++ b/examples/ad_manager/v202011/site_service/create_sites.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a Site for Multiple Customer Management.""" + +# Import appropriate modules from the client library. +import sys +from googleads import ad_manager + +# Set the URL and child network code for the Site. +URL = 'INSERT_URL_HERE' +CHILD_NETWORK_CODE = 'INSERT_CHILD_NETWORK_CODE_HERE' + + +def main(client, url, child_network_code): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v202011') + site_service = client.GetService('SiteService', version='v202011') + + # Check that the child network code is approved for MANAGE_INVENTORY by this + # network. + current_network = network_service.getCurrentNetwork() + child_network = None + for child in current_network['childPublishers']: + if child['childNetworkCode'] == child_network_code: + child_network = child + + if child_network is None: + print(('Child network %s not found on the current network (%s). Cannot ' + 'create site.') % (child_network_code, + current_network['networkCode'])) + sys.exit(1) + + if child_network['approvedDelegationType'] != 'MANAGE_INVENTORY': + print(('Child network %s has not approved for the current network (%s) ' + 'to manage its inventory. Cannot create site.') % ( + child_network_code, current_network['networkCode'])) + sys.exit(1) + + # Create site object. + site = {'url': url, 'childNetworkCode': child_network_code} + + # Create the site on the server. + created_sites = site_service.createSites([site]) + + # Display results. + for site in created_sites: + print('Site with id %d and URL "%s" was created for child network %s.' % ( + site['id'], site['url'], site['childNetworkCode'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, URL, CHILD_NETWORK_CODE) diff --git a/examples/ad_manager/v202011/site_service/get_all_sites.py b/examples/ad_manager/v202011/site_service/get_all_sites.py new file mode 100755 index 00000000..4700c348 --- /dev/null +++ b/examples/ad_manager/v202011/site_service/get_all_sites.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 Sites.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + site_service = client.GetService('SiteService', version='v202011') + + # Create a statement to select Sites. + statement = ad_manager.StatementBuilder(version='v202011') + + # Retrieve a small number of sites at a time, paging through until all sites + # have been retrieved. + while True: + response = site_service.getSitesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for site in response['results']: + # Print out some information for each site. + print('Site with Id %d and URL "%s" was found.' % + (site['id'], site['url'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202011/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202011/site_service/get_sites_requiring_approval.py new file mode 100755 index 00000000..8863fda4 --- /dev/null +++ b/examples/ad_manager/v202011/site_service/get_sites_requiring_approval.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 Sites under MCM requiring review.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + site_service = client.GetService('SiteService', version='v202011') + + # Create a statement to select Sites needing approval. + statement = ad_manager.StatementBuilder(version='v202011').Where( + "approvalStatus = 'REQUIRES_REVIEW'") + + # Retrieve a small number of sites at a time, paging through until all sites + # have been retrieved. + while True: + response = site_service.getSitesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for site in response['results']: + # Print out some information for each site. + print('Site with Id %d and URL "%s" was found.' % + (site['id'], site['url'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202011/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202011/site_service/submit_sites_for_approval.py new file mode 100755 index 00000000..f06888b9 --- /dev/null +++ b/examples/ad_manager/v202011/site_service/submit_sites_for_approval.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 submits a Site for approval.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the site to submit for approval. +SITE_ID = 'INSERT_SITE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + site_service = client.GetService('SiteService', version='v202011') + + # Create a statement to select Site. + statement = (ad_manager.StatementBuilder(version='v202011') + .Where('id = :id') + .WithBindVariable('id', SITE_ID)) + + response = site_service.performSiteAction( + {'xsi_type': 'SubmitSiteForApproval'}, statement.ToStatement()) + + print('\nNumber of sites changed: %s' % response['numChanges']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202002/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202011/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202011/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v202002/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202011/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v202002/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202011/suggested_ad_unit_service/approve_all_suggested_ad_units.py index f18ba547..18591c82 100755 --- a/examples/ad_manager/v202002/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202011/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202002') + 'SuggestedAdUnitService', version='v202011') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v202002/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202011/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202002/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202011/suggested_ad_unit_service/get_all_suggested_ad_units.py index 1d9d5e23..33de1c49 100755 --- a/examples/ad_manager/v202002/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202011/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202002') + 'SuggestedAdUnitService', version='v202011') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v202002/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202011/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202002/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202011/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 3ce64b96..1aa6237a 100755 --- a/examples/ad_manager/v202002/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202011/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202002') + 'SuggestedAdUnitService', version='v202011') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v202002/targeting_preset_service/__init__.py b/examples/ad_manager/v202011/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/targeting_preset_service/__init__.py rename to examples/ad_manager/v202011/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202011/targeting_preset_service/get_all_targeting_presets.py similarity index 90% rename from examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202011/targeting_preset_service/get_all_targeting_presets.py index fcb10ffc..61888539 100755 --- a/examples/ad_manager/v202002/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202011/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v202002') + 'TargetingPresetService', version='v202011') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. @@ -37,7 +37,7 @@ def main(client): for targeting_preset in response['results']: # Print out some information for each targeting preset. print( - 'Targeting preset with ID "%d" and name "%s" was found.\n' + 'Targeting preset with ID "%s" and name "%d" was found.\n' % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: diff --git a/examples/ad_manager/v202002/team_service/__init__.py b/examples/ad_manager/v202011/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/team_service/__init__.py rename to examples/ad_manager/v202011/team_service/__init__.py diff --git a/examples/ad_manager/v202002/team_service/create_teams.py b/examples/ad_manager/v202011/team_service/create_teams.py similarity index 99% rename from examples/ad_manager/v202002/team_service/create_teams.py rename to examples/ad_manager/v202011/team_service/create_teams.py index 05cec83c..d9a7b44b 100755 --- a/examples/ad_manager/v202002/team_service/create_teams.py +++ b/examples/ad_manager/v202011/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202002') + team_service = client.GetService('TeamService', version='v202011') # Create team objects. teams = [] diff --git a/examples/ad_manager/v202002/team_service/get_all_teams.py b/examples/ad_manager/v202011/team_service/get_all_teams.py similarity index 96% rename from examples/ad_manager/v202002/team_service/get_all_teams.py rename to examples/ad_manager/v202011/team_service/get_all_teams.py index 5019f015..4554a875 100755 --- a/examples/ad_manager/v202002/team_service/get_all_teams.py +++ b/examples/ad_manager/v202011/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202002') + team_service = client.GetService('TeamService', version='v202011') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v202002/team_service/update_teams.py b/examples/ad_manager/v202011/team_service/update_teams.py similarity index 97% rename from examples/ad_manager/v202002/team_service/update_teams.py rename to examples/ad_manager/v202011/team_service/update_teams.py index 5b9fc791..928e0f89 100755 --- a/examples/ad_manager/v202002/team_service/update_teams.py +++ b/examples/ad_manager/v202011/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202002') + team_service = client.GetService('TeamService', version='v202011') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v202002/user_service/__init__.py b/examples/ad_manager/v202011/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/user_service/__init__.py rename to examples/ad_manager/v202011/user_service/__init__.py diff --git a/examples/ad_manager/v202002/user_service/create_users.py b/examples/ad_manager/v202011/user_service/create_users.py similarity index 99% rename from examples/ad_manager/v202002/user_service/create_users.py rename to examples/ad_manager/v202011/user_service/create_users.py index 2d1db15c..071f9aa5 100755 --- a/examples/ad_manager/v202002/user_service/create_users.py +++ b/examples/ad_manager/v202011/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202002') + user_service = client.GetService('UserService', version='v202011') # Create user objects. users = [ diff --git a/examples/ad_manager/v202002/user_service/deactivate_users.py b/examples/ad_manager/v202011/user_service/deactivate_users.py similarity index 97% rename from examples/ad_manager/v202002/user_service/deactivate_users.py rename to examples/ad_manager/v202011/user_service/deactivate_users.py index c1452334..fcbf2fca 100755 --- a/examples/ad_manager/v202002/user_service/deactivate_users.py +++ b/examples/ad_manager/v202011/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202002') + user_service = client.GetService('UserService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202002/user_service/get_all_roles.py b/examples/ad_manager/v202011/user_service/get_all_roles.py similarity index 99% rename from examples/ad_manager/v202002/user_service/get_all_roles.py rename to examples/ad_manager/v202011/user_service/get_all_roles.py index 8f140009..aa08cdea 100755 --- a/examples/ad_manager/v202002/user_service/get_all_roles.py +++ b/examples/ad_manager/v202011/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202002') + user_service = client.GetService('UserService', version='v202011') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v202002/user_service/get_all_users.py b/examples/ad_manager/v202011/user_service/get_all_users.py similarity index 96% rename from examples/ad_manager/v202002/user_service/get_all_users.py rename to examples/ad_manager/v202011/user_service/get_all_users.py index 9a9f707e..cfcdaa73 100755 --- a/examples/ad_manager/v202002/user_service/get_all_users.py +++ b/examples/ad_manager/v202011/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202002') + user_service = client.GetService('UserService', version='v202011') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v202002/user_service/get_current_user.py b/examples/ad_manager/v202011/user_service/get_current_user.py similarity index 99% rename from examples/ad_manager/v202002/user_service/get_current_user.py rename to examples/ad_manager/v202011/user_service/get_current_user.py index 4b61986f..e9cd1924 100755 --- a/examples/ad_manager/v202002/user_service/get_current_user.py +++ b/examples/ad_manager/v202011/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202002') + user_service = client.GetService('UserService', version='v202011') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v202002/user_service/get_user_by_email_address.py b/examples/ad_manager/v202011/user_service/get_user_by_email_address.py similarity index 96% rename from examples/ad_manager/v202002/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202011/user_service/get_user_by_email_address.py index 4fd3a25d..7d5332b3 100755 --- a/examples/ad_manager/v202002/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202011/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202002') + user_service = client.GetService('UserService', version='v202011') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v202002/user_service/update_users.py b/examples/ad_manager/v202011/user_service/update_users.py similarity index 96% rename from examples/ad_manager/v202002/user_service/update_users.py rename to examples/ad_manager/v202011/user_service/update_users.py index 35a347ac..52bdeed6 100755 --- a/examples/ad_manager/v202002/user_service/update_users.py +++ b/examples/ad_manager/v202011/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202002') + user_service = client.GetService('UserService', version='v202011') # Create query. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202002/user_team_association_service/__init__.py b/examples/ad_manager/v202011/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202002/user_team_association_service/__init__.py rename to examples/ad_manager/v202011/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v202002/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202011/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v202002/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202011/user_team_association_service/create_user_team_associations.py index 401166f8..b97e4059 100755 --- a/examples/ad_manager/v202002/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202011/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202002') + 'UserTeamAssociationService', version='v202011') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v202002/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202011/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v202002/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202011/user_team_association_service/delete_user_team_associations.py index dacd0e6d..e64521e7 100755 --- a/examples/ad_manager/v202002/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202011/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202002') + 'UserTeamAssociationService', version='v202011') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202002/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202011/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v202002/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202011/user_team_association_service/get_all_user_team_associations.py index 9b18e010..f7b3a382 100755 --- a/examples/ad_manager/v202002/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202011/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202002') + 'UserTeamAssociationService', version='v202011') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v202002') + statement = ad_manager.StatementBuilder(version='v202011') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v202002/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202011/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v202002/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202011/user_team_association_service/get_user_team_associations_for_user.py index e0d9f81f..92807584 100755 --- a/examples/ad_manager/v202002/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202011/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202002') + 'UserTeamAssociationService', version='v202011') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202002/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202011/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v202002/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202011/user_team_association_service/update_user_team_associations.py index a6f04c01..361b12ea 100755 --- a/examples/ad_manager/v202002/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202011/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202002') + 'UserTeamAssociationService', version='v202011') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202002') + statement = (ad_manager.StatementBuilder(version='v202011') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 8de92503..8bf33e4e 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,22 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v201911': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', - 'ContactService', 'ContentBundleService', 'ContentService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'DaiAuthenticationKeyService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', - 'UserService', 'UserTeamAssociationService'), 'v202002': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', @@ -112,6 +96,24 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), + 'v202011': + ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', + 'ContactService', 'ContentBundleService', 'ContentService', + 'CreativeReviewService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PlacementService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', + 'SiteService', 'StreamActivityMonitorService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService'), } diff --git a/googleads/common.py b/googleads/common.py index 45e5bed2..bee6b4cc 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '25.0.0' +VERSION = '26.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 3a61e322..b38f5162 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202008' +CURRENT_VERSION = 'v202011' class CommonTest(testing.CleanUtilityRegistryTestCase): From 72481b1dd05266a760034ef853596e014cc48805 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Sun, 15 Nov 2020 07:50:45 -0500 Subject: [PATCH 163/180] Commiting latest changes. From 364efe267bed8e54ad44389c1ae817b607bba594 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 18 Feb 2021 14:23:55 -0500 Subject: [PATCH 164/180] Commiting latest changes. From 754c1d7f02b929e9771c61167a1404b9c5c6bfeb Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 18 Feb 2021 14:28:12 -0500 Subject: [PATCH 165/180] Ad Manager v202102 release --- ChangeLog | 5 + examples/ad_manager/data/README | 1 + examples/ad_manager/data/medium_rectangle.jpg | Bin 0 -> 50953 bytes .../creative_service/create_creatives.py | 2 +- .../v202008/label_service/create_labels.py | 2 +- .../line_item_service/create_line_items.py | 3 +- .../v202008/order_service/create_orders.py | 2 +- .../v202008/team_service/create_teams.py | 2 +- .../creative_service/create_creatives.py | 15 +- .../v202011/label_service/create_labels.py | 2 +- .../line_item_service/create_line_items.py | 3 +- .../v202011/order_service/create_orders.py | 2 +- .../v202011/team_service/create_teams.py | 2 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 2 +- .../create_traffic_forecast_segments.py | 4 +- .../get_all_forecast_adjustments.py | 4 +- .../get_all_traffic_forecast_segments.py | 4 +- ...djustments_for_traffic_forecast_segment.py | 4 +- .../update_forecast_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../get_recently_modified_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 17 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../forecast_service/get_traffic_data.py | 123 ++++++ .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 4 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 5 +- .../create_video_line_item.py | 3 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- ...et_default_third_party_data_declaration.py | 68 +++ .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 4 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 58 +++ .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../v202102/site_service/create_sites.py | 68 +++ .../v202102/site_service/get_all_sites.py | 49 +++ .../get_sites_requiring_approval.py | 50 +++ .../site_service/submit_sites_for_approval.py | 44 ++ .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 4 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- .../handlers/api_handler.py | 2 +- .../add_shopping_campaign_for_showcase_ads.py | 401 ------------------ googleads.yaml | 2 +- googleads/ad_manager.py | 21 +- googleads/common.py | 2 +- tests/common_test.py | 2 +- 216 files changed, 801 insertions(+), 731 deletions(-) create mode 100644 examples/ad_manager/data/README create mode 100644 examples/ad_manager/data/medium_rectangle.jpg rename examples/ad_manager/{v202005 => v202102}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v202005 => v202102}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v202005 => v202102}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v202005 => v202102}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v202005 => v202102}/activity_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v202005 => v202102}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v202005 => v202102}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v202005 => v202102}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v202005 => v202102}/adjustment_service/create_forecast_adjustments.py (99%) rename examples/ad_manager/{v202005 => v202102}/adjustment_service/create_traffic_forecast_segments.py (98%) rename examples/ad_manager/{v202005 => v202102}/adjustment_service/get_all_forecast_adjustments.py (95%) rename examples/ad_manager/{v202005 => v202102}/adjustment_service/get_all_traffic_forecast_segments.py (95%) rename examples/ad_manager/{v202005 => v202102}/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py (96%) rename examples/ad_manager/{v202005 => v202102}/adjustment_service/update_forecast_adjustments.py (96%) rename examples/ad_manager/{v202005 => v202102}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v202005 => v202102}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v202005 => v202102}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v202005 => v202102}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v202005 => v202102}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v202005 => v202102}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v202005 => v202102}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v202005 => v202102}/cms_metadata_service/activate_cms_metadata_values.py (95%) rename examples/ad_manager/{v202005 => v202102}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v202005 => v202102}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v202005 => v202102}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v202005 => v202102}/company_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/company_service/create_companies.py (99%) rename examples/ad_manager/{v202005 => v202102}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v202005 => v202102}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v202005 => v202102}/company_service/update_companies.py (96%) rename examples/ad_manager/{v202005 => v202102}/contact_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v202005 => v202102}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v202005 => v202102}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v202005 => v202102}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v202005 => v202102}/content_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/content_service/get_all_content.py (96%) rename examples/ad_manager/{v202005 => v202102}/content_service/get_recently_modified_content.py (97%) rename examples/ad_manager/{v202005 => v202102}/creative_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v202005 => v202102}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v202005 => v202102}/creative_service/create_creatives.py (87%) rename examples/ad_manager/{v202005 => v202102}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v202005 => v202102}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v202005 => v202102}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v202005 => v202102}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v202005 => v202102}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v202005 => v202102}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v202005 => v202102}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v202005 => v202102}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v202005 => v202102}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v202005 => v202102}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v202005 => v202102}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v202005 => v202102}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v202005 => v202102}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v202005 => v202102}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v202005 => v202102}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v202005 => v202102}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v202005 => v202102}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v202005 => v202102}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v202005 => v202102}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v202005 => v202102}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v202005 => v202102}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v202005 => v202102}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v202005 => v202102}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v202005 => v202102}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v202005 => v202102}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v202005 => v202102}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202005 => v202102}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v202005 => v202102}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202005 => v202102}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202005 => v202102}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202005 => v202102}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v202005 => v202102}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v202005 => v202102}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v202005 => v202102}/forecast_service/get_delivery_forecast_for_line_items.py (99%) create mode 100755 examples/ad_manager/v202102/forecast_service/get_traffic_data.py rename examples/ad_manager/{v202005 => v202102}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v202005 => v202102}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v202005 => v202102}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v202005 => v202102}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v202005 => v202102}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v202005 => v202102}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v202005 => v202102}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v202005 => v202102}/label_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/label_service/create_labels.py (98%) rename examples/ad_manager/{v202005 => v202102}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v202005 => v202102}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v202005 => v202102}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v202005 => v202102}/label_service/update_labels.py (96%) rename examples/ad_manager/{v202005 => v202102}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v202005 => v202102}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v202005 => v202102}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v202005 => v202102}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v202005 => v202102}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/create_video_line_item.py (98%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v202005 => v202102}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v202005 => v202102}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v202005 => v202102}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v202005 => v202102}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v202005 => v202102}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v202005 => v202102}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v202005 => v202102}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v202005 => v202102}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v202005 => v202102}/network_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v202005 => v202102}/network_service/get_current_network.py (99%) create mode 100755 examples/ad_manager/v202102/network_service/get_default_third_party_data_declaration.py rename examples/ad_manager/{v202005 => v202102}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v202005 => v202102}/order_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v202005 => v202102}/order_service/create_orders.py (98%) rename examples/ad_manager/{v202005 => v202102}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v202005 => v202102}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v202005 => v202102}/order_service/update_orders.py (97%) rename examples/ad_manager/{v202005 => v202102}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v202005 => v202102}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v202005 => v202102}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v202005 => v202102}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v202005 => v202102}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v202005 => v202102}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v202005 => v202102}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v202005 => v202102}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v202005 => v202102}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v202005 => v202102}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v202005 => v202102}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v202005 => v202102}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v202005 => v202102}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v202005 => v202102}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v202005 => v202102}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v202005 => v202102}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v202005 => v202102}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v202005 => v202102}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v202005 => v202102}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v202005 => v202102}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v202005 => v202102}/publisher_query_language_service/get_line_items_named_like.py (96%) create mode 100755 examples/ad_manager/v202102/publisher_query_language_service/get_mcm_earnings.py rename examples/ad_manager/{v202005 => v202102}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v202005 => v202102}/report_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v202005 => v202102}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v202005 => v202102}/report_service/run_inventory_report.py (97%) rename examples/ad_manager/{v202005 => v202102}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v202005 => v202102}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v202005 => v202102}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v202005 => v202102}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v202005 => v202102}/report_service/run_saved_query.py (94%) create mode 100755 examples/ad_manager/v202102/site_service/create_sites.py create mode 100755 examples/ad_manager/v202102/site_service/get_all_sites.py create mode 100755 examples/ad_manager/v202102/site_service/get_sites_requiring_approval.py create mode 100755 examples/ad_manager/v202102/site_service/submit_sites_for_approval.py rename examples/ad_manager/{v202005 => v202102}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v202005 => v202102}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v202005 => v202102}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v202005 => v202102}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/targeting_preset_service/get_all_targeting_presets.py (94%) rename examples/ad_manager/{v202005 => v202102}/team_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/team_service/create_teams.py (94%) rename examples/ad_manager/{v202005 => v202102}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v202005 => v202102}/team_service/update_teams.py (94%) rename examples/ad_manager/{v202005 => v202102}/user_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/user_service/create_users.py (96%) rename examples/ad_manager/{v202005 => v202102}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v202005 => v202102}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v202005 => v202102}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v202005 => v202102}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v202005 => v202102}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v202005 => v202102}/user_service/update_users.py (92%) rename examples/ad_manager/{v202005 => v202102}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v202005 => v202102}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v202005 => v202102}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v202005 => v202102}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v202005 => v202102}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v202005 => v202102}/user_team_association_service/update_user_team_associations.py (96%) delete mode 100755 examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py diff --git a/ChangeLog b/ChangeLog index e74f455e..debcbb4c 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +27.0.0 -- 02/17/2021 +* Added support for Ad Manager v202102. +* Removed support for Ad Manager v202002. +* Removed examples for Ad Manager v202005. + 26.0.0 -- 11/10/2020 * Added support for Ad Manager v202011. * Removed support for Ad Manager v201911. diff --git a/examples/ad_manager/data/README b/examples/ad_manager/data/README new file mode 100644 index 00000000..d93b317c --- /dev/null +++ b/examples/ad_manager/data/README @@ -0,0 +1 @@ +Data files used by the client library's examples. diff --git a/examples/ad_manager/data/medium_rectangle.jpg b/examples/ad_manager/data/medium_rectangle.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ae2ab636e8ecef8913e85aa7330dd048d1b9bf6f GIT binary patch literal 50953 zcmaI7bzB@j^e((W@d7Pc+)IH1h2rk+u(-6iE$$9Qit7T!-Q8V^yX)fa?)q-O_uk(t zf4tdGW@b+^lQT&s&&hL=w}rQLzz1n@DRBS{EC65x{Q=&N0Ut%33@zONFo1Ue06+sO zIt8E$8QB;Z1B^PM5|}p#AOHaKKLHkc1q%y3!otEq&(PyLxc|aCXn==Cg#QB4zkvKd z;omLLT+noQBm{Vb|3}LIWcmNUcEZ5UKfIZ&~(;j&-&$NsIM zrV%mx<>;`g=i{o+z!v&5*7l_+MPrX4BRL3S$sh{L~8kqaIi_B|2A4N`YW3bh4G4xRDO<=3~ zdw0(2=OXqhtfzxJUOt)nq@#IXs-GrPDv{!?$o!g1ZRg7zuVpa9JrOQWPA&@U=}m~o zZ7`Omla{1YSB;gJfvB3edJOyKsYYO9OZaelx4by#$g87A&HI#3`wAKFVa$71=zhSI zL=ftnA#8Rp!Im0qpo_%?D#3KH1Ok-BHE6UzHBIFIRd3Rx3JHy z+A>xxUZ&N&W1+gpLKTeuC+w>DCls|1*?cOrb)ORnSGj!yfRA6Vpjx}m1oz%4uHR%c zO#3rgx-yF5V%c>HQng{(KMFqOE3`eVo@j*La;)3(nMX!+mr+_*Z=o|3q^K~~JKN=< z&r(JGL@b|Qpn?BV=E!D*op+9-x{AR~K7MufN->5^xL+Bt! z=1SDs(CF0;YWJceE2{^81lEHw|3x*3bO-|rvGsRG{@s@dv|AFIZ8#ruZfxm7h7cgF ze3tN+C~T}{sSm#|gq$OSxzxsn5$sjZ&QnUAM`Nb-u?Vm@JqiYGI^P zal$ih&7IWp;x{xi&v24=CUpce+078QxLdN{x*!^x7f7eGqo@{W1Whb`fS4nJDlr29 z07+s1z}1qIR&6vYD(KM`nclAe;6DuNTcTy;Aia!NtRLHgT<-gV)dW68HFDb`1C1|= zo_-bh`Zp#=&5cE>;_4H`tpB=oT*uUo<7(@-N0AsV03^3WZ&^o7R95sq5wOZ>J5Rz; z$+ncDT3iNG7w0j673}Kr8B{6jMPz6f=}_f+0@7Qs>Px%7Z*dZFV-ZcL+9~*b{==`! zZYlQ1me}r(9O+QwQm88bz`X1dCoDUT6D0+p z_X+_y(5oXWM-*(uS{Pea3yp2*+^SOQHrLmMV4(AX5?u-Cmi0?4LXrR01o=Jr4Xvd> z)k)>aZgn5v{?l3_w7Ngl!aa8CU&6f zmk*9eVxOnetiL8|DpKV>@p4D7QL%x>&|9BX13{2ow3mPn7>jFy0jiceKc9`(hy^yd zeCmlE*|)Y+7I0|pLltg$4z)gKzL*w8=i$aNHmMaTWzjV2%Iz)~Zll-=5=4clV^UA_LpeJ zPK(^@IV&6GcitY@5@vU%t6`nXqJLJBpLL-&!fk5XM5FIs88|`ZmP~94gS=?X^ZJ}(|!U#pyjo0saUJ@O|1lUrj zC-cG~^q@;KC7ck2#R+n{QfFxEi5K@k1wl*is8zvg{r7zmv!oIE(V-t|`|o=%Uh?#_ z<&%Z!xGxJ|S(u{!zwK2&Q!6LbJc?peuu-wYIP(HNTOyj_5ZTtfwNZ%b!48W|?uOCQ zgef4ahE^TCy|7|lMx7wlixBjyg2%%Va5!!BnTZ;Nw!;?KZSrS)-YjQcT$QjgGO4N! zG|REUUY?||j!|R%?0RO*1Gg;_BfgDd-qWi}IJeLIhiHz+9Ix6(DqpoF*xw*;1HMqo z+Ly>?Rv`_Ve}$#ho`2Aw6@qivC{UsvGOa{@M_(|S4U4krK}ylymnNEUOI80Es))XB zGXrfPlKypA)i{b1PMV^B(j*RgN68*_B2lgqX1O`*}1#JeV7Ksg**8* zMK9g2g$#J;CiN!)c*Uv~#T$Oj1ywj0EE$KPIx7M?XarOtJ_kzS0-D9%*Al1As#5wd zbj(plYznKtU*@Gl=-vR*;XfZ|74EVHoF=oSJEn3zdDp1C>_@FQ7RFXw7xs~s0R`MC z?{rb9f%^Zi2N}MCKlS^}&}Fm{{(BM-QF{B8-PsBs$)I47bmU5)O?z#X7Gg8)4ML%6 ziK4R$fn0|coQb~yoTlxwOWl;heKept+1%;AF9I64sr=7h_TQxnbaqikI0~x~uSZ#; zO8Fz>?0k3nVW3HZ)Z~C3?s}Pv35W-)f1S1Pj3?q?mT2slc#5bpQ2Px)EBTmnQM*JD zz##O>>~V|Z9l~vnRCqL$b3fQF03Ec$k8&DFsa89S1bURc8g%QZu@v=INux?Tu@4lx zMXVAnyoc@-p5T)Gk3Hk!axUO0AeLxa@*{pkhD3rlSB<{lT;EB}@~nt2jb=@^e&c~@IDyR##T$_PQHIs@26)uE;eP|%f;Ha& zV>9}%E2S5s-0EBXMQgAr3yl0Ut#MYp2cYp(tnkz2ngrJ^l^W)qKg1Zz^WSd>v`0nF z_Z0tP=Q1<&qn~odKNazF*MLR{yn4z)xqhXe_y?2PG2c2c=Z%2?O3a!u6uhbr{QHi# zjr$jHyAK?53n<0A!8Tc-tidovt-e=fcjvRqxRdEA;ep7N&)c}{9%-bqy?k~zJftp0s#nN(dqTN2)I zRbRn;5(cFhvU@R^jkNJoYxZdMw4t;`Ew#9J(q%MQrhyho`9qV+AqM&H<2)H!NqW1V zWU+{P1;P^b>|Cd;mO@n5Fd?F_n}8*yGg^b;JLGNp8tffHyI~2kg()z?as7%@;z}R` zfL5-^ilJ{1M&v}*5u*LOoWiQA8RKR?$x|0$#ORIZDa7Deg#~UdR|2%nUfWCn$y?{ zv#Ft2lt)^UnVhR;P37W>?3iPu=hFmLy0U9!Z&8dJZcU})hDoWXcyAYIuUDUxBh|%oDT8pKpL)-(Lo~vBfkdv!K^(FQeR`j~Xwi7|-}= zZvX@NKunF~uL9>L9ZfWstVm+?uKa&U*u`?2Aq-jO78)qhunKCx6M~<}K>mo@sgF`} zRzBfIUZB^$6j8;%LV-Re(i6HDOvkB@O7r00i#SgoRz`K(lkg4v!ULXH%JjcJ-mRgk7JvB2F%W}+^4Ki%`*CwPqMv7QU@ApP zB%<**7B)CfYQZ0A`D3}tAK&i_aQC-Q8)h2m+a0c|-@-$pea4Fi-vC4QJ~i{|ol%=n zikc5AQ;o%mWqYaxvVO`f7EYg7K8XId8TZ;vKvcvI{Q9ek@Md}u6{gS(u?lu;Dm~`f zb>~{<^q|HjKy#sey6Rv?8hn#-+EP!9(v#a@TXXSE!@Z2Amf@!6EFoEVElWYPgBf5|4&e(;3<+2#eCw4sV<41oFRF>b*DO{u z#KGh%(B-?!q`AU?vbL2BdEr?Wb#DMp(2#OA?C(?gD-8#(VP`w zZH}s@L!#Aai#&&^8s9$=M3Q?Ee@~{3=u(El2^u*c{9Fa^lNf;a7 zN<^JIX3K9L#wGUcm7^*voYR}vk2u3TrsuhA#Jd|&9TS-%RJI-8em>twZW&@fddm)T zDCXy{WotT#m*<KwRFBg#Fg8Vs(DjTQ5RcNW08?T9V5QEd~)d^nTLLy z`C+dl^0nA@AfpbC^!@f{q(1!m%!GEhhz11JU$~E6^OLI($$(*nZ)#cVyssUMD^Af| z^)ulkL8d+YCsnEGtr(4^FT|h!?gl$zg__i+zq|A{{ks25Rkk&&@f=(>YY~@sWVltvh*w?{Irj|o|y;xtjQm2MHW#?+7G^p02 z2TpAs;mkf7tJ=qwwF_nd&JvhX=+4f4QMAPT@@f`6%Fw{GEyH($O)Y6tC37bnf&$w% z&!Q>x{U=qsgi7;-6wabBjl&KlKxAq2-+E6LBwF!mWl;veg5eQ0W@OY61u z8Qj}$&t9bE>9tuWn99gfWe0<@(B)N(f824#mpbS49N9m<5{g$%sYTiT$Sh}EDDFkg zrQ)!qnZUZknSZH>aJ>(Dc_%H>t>H&Z@mNV;J(9?BdE zPw%nE7r}KHllj{-amC4PN?FL{c6B`nk)aUyAJYbXB5nk!8CGX}iB`1AbGiNzC)?d$ zZgGj2{_q`9PZi#T(MTupUH;jAZGfR*0cfQ#GL^VJw^T)RRKp zG-X=k1_U9zu6(qcAlAK#j+P=>YFM)5C~C2a>q~nmuWwlg%Y1bct#37>NkCm4Wn?XH z1%mM@6>Hk^k8Twxc#%a;#oixXInBB4p{h-e`#X!>cjLdmnQPxn*T{6tC#QLtlZ0nC@#$$uohisHxy)d~*WfCzb+qn?^?INuTsVjW9oP21z!o2vm2F^ga!o~$j^or*s z-u*j}@}`OlaE_k`dD;cWlX#yDpDU@I?jwtkp95SoYL$}9fHkMlGGcVO4)p+$7h`wF zNgx>zbdUvaCR21~et%Y*S9@elbs9{l9G$f;IWJ@E0l&?Vj2K)6L3*OYQ0i4qpy}J3 zNBQtauG@GZYv4tF%>P0Fji%vo)-(9x#yXTc`)tw&BC+QPodJ2_z102(DcbuTCs6Fc zmM&fsdjo(-(%2s*03H;-T>z786|n5#X;?n=Xc|y({kk0hVsvg2M=i|lt8}% zZ>yIG4m!Fu32&=c7h&k+_)`KN*i$8ORep5vf|Oo*T2j1dIsPDkQZ;@KYGjMAacr5# zi@7ZQdN#N_{s$yTViG1m#PgW{8%QX|{+GD~xq?oLX5suwZA+;|&@i@G{*Rq)xUG{$ z`kNM)0BU4IEk`@Oh7)b3S@ivuuebI%W!67DLcNB648(48-VAxNQ?*f~9|!r!nzLw2 zfn+3Fqs#i0%6U>W_Sy%_oYnDt5kbg#7`p6b44l5yRI0|bZIQ0$sBeG=Waz6u#@M|9 z49j40ECdQ#UV;j}ib;E-H07S+h|)L5^!xIsyIbKK?q{8|9Wa*%YKPk^bYdH=>Nj;l z&ZlDukR8jYN_w0lTAh3prpq_tSR3TQwfV|(;qDgLDhh-t;(Y|}7Amc8fLvfg1?pNH zXB5(C5f285L93hjST^K@Q`EEs*qClr99MQNovuQj&%tvX)JbUV6f=k$4l0eEZog|( zFC;=Vw(yXyE0&b?Yw<;9z7_`SWnj$Qq0W7#D+sTUXWrHtHCfgQ-D*a#B#JgL zdbC-K7*tTG6l#NzMp-tc)P-?Xs!o?h##DTV&Gd*2V+HjH=yc{bwGeeBiUefMOO|OB zm+2eR4oFMfdG@4V)CzRV9e5&dLRTzArjBsTxgsg2jHP3%w<@?d7wEL+>Tqa9Poe;gjOnWkj?3V@T%kyP{E-TJnM)JKC?vBOH3u_gg{Bw0T;$ZJ5FvUBA$|6%tlQ zS;5@75zDqk7Rzbw{J#qNEzLS7*KE-p8k%}kW4%uO{CiuH2Fc4i%@75ZfrmvY)}aCg z>bYyA`z-3>^)|BV;*HfTNiVd(8fj2H?Z@1*ceHa^42z6eb*Iq{Jie!dM;SXMpLtYg zXq*|X^2!d&87WKG=_hc87bX31(E{rPEKdp*HajS6BEQ&^;_N+pse1p>?Z-)q%VYUl zk99C;i(IKIe}HPOYG0oaDh3iab~kmuN}4j7Vzh{XmV7mu>IZtswu@Av3s{z&ff^GXP|syCip)=Wa=2l# zGP2u>D(OWSX`<-qa%(s5uGJJUXZ};&D4%m*Nicn zWO!EKqalJ9b9kQO>^!DA)r^^ae5 z2E8-QZ%)ue#5Cgzrw0pH*PZ0~?r1(I^I;ZPJ{^e$Etsk#^GN>0}s zb4It?5hwnmUwL{|KG9~lQe#o?5a@(Lu*d03Eb#6_y?;EfniQS#*i4hw4=4Jn_bd`N zWR{&CsDj@8D$YD!goSw>HUkoWy2f!n5p1-~v_6akk~q2;NLz6ZcN^0@Qf@QYxe;5x&Ly;8)jP8XR4 zDt;sAh0&CbBp}=#R=-v6FxSg&c}Vn1nf%8cq5UY4_TfXf;;Eor)GKuD>(2Ay@iemf zXs2kkM3X+EA6^1nh{L2LaSW^<_BI@&<{Q>h=2#I$8*6+8fuq}pB$C-`SmP#O-W~TF zOiw54P@64jsd$nE=oP;KUgrd!?aX}c`f3q5_ul|f&xmgTHj!)4c+Z{0-#DGY{g*>} zzYC|6#LET}{u{fMKzN7p;o!6S#kBJnAtd@s@|jgH?@QlBB&CNsllf%U;Sg}yRTDJATgg;LcrA=lJZ~ai#}eYcPCAc415SB_NI3}uaqx0pYyI( z{m#glMC_go+<(0Rp4Em)&yvLxIWS^t-vA^1XI#WQy)>(&wE=v1pb#!)$j#@i*)$5Q zrZArM$Jy^#OV#<`VTMkmzqhR+bypOjCF1PT{Kx|!94aA6$78Vb3O{kJ=@B`=Zb?r# zCVQpFvtA@gcWpY@9*Mmo^ntsqfu^S)9|I?ryKoU%>}E>XpNhs~FqJ`WY`#QU^Q87X zW2^~FwqG#SV0r$|S1ZeBl=_T-C|as`CA!F5VcQN}lj-QATBP4Gw2MnfFgfxn-Z)~* zHMe1SNtkoJ*Hkk>QPXIkvmsl2uwN@t$*7~pzUz0uN`aao6T{YIcUEWSq%=Xd8+*iG zdebhqZI|ZZl886s`zLaoQ*4O^mm*`Tr1Wu^U2yM54=E4)dP@~pLgJceqV|?=81+m; zsqPN37jX{36!zH@KbqCg55>5ua~pHXFg-l#HMCUxigfgJ4_xM1{0DRhD1HKnvi_Fy zJVDxc3V{RoL@pnhYZ-AyB;?RZ0{2j(;qGrn1)g;6eGU-o_SN7XYxP~%T)&#PTA$EQ zReW`=65KU~ZDX=iV{bliwEn62$vaNFmvgm>pN$$H{g<+c(%#fT><%a7vnNLm`;i=j z)R{=6l{;nz@6-*AhK0-Jz!WHr8Qu2XwrvqQnIV+&;rWef;wm~JI+uQL4VUYPUPsKU zd2P2X){#)CDUs&v&zaFPBBU6hJ@P~w-%K8d4*+^aiBU%57hFFOS3}Ev8eBUsiKpGQDZwc8p`z$< z&kz~VFr^6-e)sFqft5}c3H#8@jtl@U{^~qa8wHOwbD!E~DElZNTGPOpFiPwpWygO& z*IWB+Swz}c`&g-n*z@_R$*X6~_jVid;pUYfto%rwbcRtN$LCUdu;F3O>-=tJb;pyY zXH4d?JFUCaqy%x+Rol+K?6;D3MEv zUso(7ax7f}a`U$DvSK}_eobvO6CITp(P6KgbCa6kQ=C)I}vf5$y~=&!^rD!)L{}$mAT*pOcqgn zwz*SM-snW_F!H}(eqgogUTbEM)I7Ci)@lUDQr7Rfi)H-H-zOUz%lVt)r+z`y`mu+M z0%&7}Ux)Ubu3s|DMZKo?{SMir1`LL4Yz?aGnpE5nCWf6~v{GM+)C<~ql2VuNjM#&; z?MQCNZa-eS+RTfMEs11}Jv3SqYOOoKwJIm250&njyO7VI6)uba4dc&TXbDR-tGa*b zZB<|ii*uv?Ayzokbaz$HFU{IXSDP~e0D+M)<4i>PHHq2PAsLt$+3$t%wf4OGPOP7Sdg&Vo@8 zTan`NR=@0iu!jJZq8`dKJ}+U585q7=Ua&4vR53%x-uq;8q;hk4DgU9|p7_S` zoF9qWN+3a!;6k2*04l$C516`iDb)75>c7Uml<6zRHBEnsB`TOvN7D_v+bX!QAUTXO*i59(@izO~RI^X+^C zRFr-zqZWA|wZ%Ad@Y;NLf;yva_|JhM{||&K76GJO*w>wCRg4%=4#DU-3NY}d7AUz1yA9+@JC&J@ zmcpS#=$WUnvFVw==DoPVT`1*W*a&)^vp!d87Y&xm9n0tw)7}g?2|7XAjM97`u6Mt& zDxy$H@u+s%TH;MyX1s5cw$^TM(06;~*L0-oW6lw6wD?A=WI9{GKaxoLi+G!vjDewG z#g2|J;&z^+beWs*>2oE=j-E(}*=JuA12Ks#-TEJnEOC1K*uCswuQVT0Hf%`qG=MZ2 zySyo(JNSpmxwF6CYwz0`MCal`us2mBSDpjGFLNtSMK&jElCmTMCC1hY7-6R!5l7uw z>OQFcORk5O4JM~~i(}=aK3UF^eG7Nz!S~Y7WD9D&XV)E*q#~X)YZS!#U2gg~^dpy^ zZLMS5cQ&_0lM^>Kx#XUISd3yu@+@^~`+qXE1o>-s`DCm0c-mcG4h*HL zSm1Hb%eGn>}byGS`(!I~#bM?J27rvX-#U(WP$r?hHCKe1{QBPm8v z&^CWkH>Z@gg39s_8WO8DpENb2<>7s+3R+n6Rf(?bv;>H)7%VQj-LDWdikML8*DzRK zOz*l?E*>sj8k#sUeD|Hjv z>g`1NtfL*Vv*K*%XX>Do7^VSsNPQXOL#beGKKvitZZ<9kmE|i8`=>4HpEb+wY18wH zDH^HIJH9RX{_VA{k+5J^WgADsarvZYvIvI>>%y_iF0~c%yZ!7MMeXdyqf$=;e(a3k zWwHv#dkoW{cAhD&xUqtV;v<<9^+@&GqGZyp0Ca%mz3Fd6%)qXs6P|PWsd6hf9sB#3 zSPYwu+Uf7DPWYAQ$K@zAJWjWIz+E7e*(ZZC`x2vhV7hG9-%{p#T1b3_O2~Yke95fx z#nb2AH#PUo_{wVcMz7G?fs*nXN!>Ox8EXaz91)he zr4(qJ_s5bsPVr4$T=o*ho4wzd5AiKxTnxEp+>0%9q|M-%sz5VC8&v0N+|oy188qHB z{m5CC@X!>`JYqp`y38OSrT6E@?Mxo&nOSU-s94_Xc4Ov;npy3*lX?6-j%1>I@yeV}ECfBl9 zs`b}yGWt{QpfLxFPoKPcBnaz^wooeXIt8j-(Ub9TPUxGMf}uJwqrr-t-OHhi+M>97 z@QzD-`Z+&+`)}~WLwEyxl)AH7n5h*meCN$x>8lo-6BK;$p9>B;_;L8KZ0|n{Nmdec z!DuP}JQ(biRY;-3ALg?+F>2HSZt}IR^d@Ymtf^`R+B@EG&QgTn&m1cjjkDH*sipW} zg=1B5Q~6w!l9$Ec8;RV~z;z3N3(i}N8v8nPI6a-cdjdN5N5nijAgOXYw_0(e77nTO zF*zx03t6U8<}^)b$D{&1#ezRt-Dv4n=QJ!0L&aHIm=HrC?Jg?fL(AXDNk@R_kxJN_soq)5( zLwB<)zU{dS$fr~-T^<7Swp{LQ!>39n zPstUMeV^zyO7IvU?0&*pf4qw{^Mt)vsCdYChqOdi3YD?JG}cq9kZB)}Lhd=5W+X~8 zMh^+Mo?}ZLF#sHhxtQ5DJ3w-s<}B*V~VvZS+>f^sJUF_x}xTxhYDndf$OoXY&8tAUc~8Z=}&8C>GkK% z=x?m=h$I&Ml2;{9GrAo?=42DK%E1<*FWg13`^)4vxjExjY}|=aCmPdQC@9Eop|!PN zVL1>DFqF#BJcBK`e-gfre3evO+<5=;YfU^1l+J0_Fs&c(oYCwGHZz6neb#ySywE$dUaYH_DF+UO~3XlOeuOUDeE`n}N)A`0~D ziDj0bpOZ<@Fc}?e^qwfT4eDw;4GYFHES^QAR9#JPx;C?6=wHfX8B*VFBF?SXCO)8} z)oO;${!%k?m!;lU;3>0ZYr>f2AulGS)v;A%DHQ22mz!<)+lPBkg=MIt^BT0uBv+;X z*aEkXHuUjpX*!}Fp)2KlE$92bNlBg@!Lh2Otn>3a7&lhICK;=J-EYP|?fD8Kh1OkS z2e;gxo@&b<6P%?qLvBby)FsXf%fFyQ#PoL|VP%7quc;udR71T7RV@vU;G#W7#oSuV zfkGEWW=!6QS`z+HRuS@&8?9Jpjp4^Vx_mlQdYtKIZpR`izDnrg%sJy6P?qx}NJ@uZ z7Sa43Th6b%5x}or#lV-t`+}?W@VU}~o;2RfAcm>oje8%!Q?%EyWW3wbv#i|2EoP0^@U=Xz*rUdg71YTwic(xU|4m|0ab1{ZWOZ_@O{!T-}RQ<%H zB>JB5za<;+4AY-{PmjFn?QTMPhZbdy?bb2Q;4#cZ>!^8yEO*9y7?W5xZ5YRi*>q-> zC;C2?vl|}94Sp8iFHvqsM$RRv{12+Dn%Zd=+M4`6U~7wftU`QraA7<3=771MC|GIh zIFfF<{CbInKdiL^7v%0`q_R`#L2NZr*lfyMuimUn3+12TML`v0JNgXmmCHxj{UfEj znxMA4R*j!dGZPn|j!oWJ!49)&$M&w=J zM!^(xBp%+ct2=oXhy@Kg3XE>uV-7DrNi(I2Wlz3Z;4z;g1hYwDJ>uPf*dUg4U>Mtm=rXD9uN)!4@DcBNaf(Tst= zWk_HCl@{wuRGpX~NCx~dkebe!wV0<(*QWJL{W_&}`#B2S@4XlL@eG<1vUzK_h`ZbJ zm{Qm8qxOA#ozaVwO(yT1P(>C+QqVUTXjCK`cSww4Zo{iT48Tx?TN(Ma;u2@qWvxun zmhNzdv?8o5!GN;L>ieOb zp@gl7yVx^uC1SPd2UpSB@!yBsm@?1E4KoeXXIKlILn}LppD@Wbhwk&6 z9JJpzZk-c^XiEcO3*Z$n>zAD5$x*D*1I=gw)`L${fv0N^5a4`RVm5TEG z)f-53=+yYW5oIgr%WUt$YQl1Bh|AAq!@f`_0$?5z|0Ufu(s_yfL6Mf>A3KZ5Z2{JR zGBXrS4RqDQKvGH(C{nPr3Uj7XY2*)WyQ#ujbL z*&>Y#In#U1b=}7MS0vWls8-mqTISYYJo>G-b6p<2?lSZo%=Kjt2m;*YGf3@XdU@-| zk|mekm0NBa=Gr=f0aBEd=BFq-4w1Z*_EBG#J=l5}8fy?&7_}g8OqQHE{&(LbPAMHn2Xrx+ zy?%~02czYJ5f`TB66%d+m1ML0fV%~wrQ3wyd1gCwvmrCNpI4;uwF|YohwQQ+H~LCEu$h~`pq$aKHvW4^?||D?G#2RiB)%BC5vT?J9a_p=``fY@_m$)iW^7`& zgaofyl$Okc;;ZT zg_SZ&GWlW7;HeIOW0`F0fF{manGn}7yqD0FRwKH?SJ~uCL@<|35E{&q^sDhHyH@UA zqDM#aj)Keh_a&$TgGQNIwb;{A&GUAKNJd_O#<-AO8FpqtP;Z5Um~DSeW1O!kD>Y(B z>om&og(jx4cTa@%=>^^@9H;B6&Vws1^egig2=!Q_r&W&fr>(Y_aA{A(z0fYFgO z51W}zpQ$o|N9~OJGo6Y*Z-8Co_M40W)REi&<7c?-uBZhC57bmLG5h?^eX@C6N=VAj zesuE1sRk3V3WT?)+^W~VZnlZJTroaz6i95Mi21%IR0^ua&z!FkrCd!3%rX&c!6-9X znq)id-=y8%vDD@3mBE+x9rMw%s8wkYch89R^60X$-spkTJ~o&?zx=&2R%d z+~*Y8LrH}LN1Xv*XStU9s>@3VCk3Y2;g^OdcGRt9ZtKJg1eUQ!>FOv%2c#v{1rrzT zm|(x32$ae(vzpZYo8r1z;3z>}#o`G1P>%QB$P1qcQ00G+3A^{E;u;dhfy* z#>aofvRRz2jlo(qX+|&Xt9a1JT{9@KvTcLOOR|)In8C|`O&Oe37H6xP`v_i(`FRJy z-6OC^!>v%_xvf*INV+6vcP8{WnaQHgPFC=e{<3Exd}BEjovVG-8QGNG2U2yVn2{*|kCCnT16f#*!%Hw3H2YrK>hm zgf@9nREaD@j}2cuTIxpVSIl6W96)8vDhKn_cW7vaTFhk#JlqPpSnBI{&ogZf&}E>~ zA#Z>JQ%iMC()rqq4uL_GwuVt1XRqpz*049gcHqJM8=%K3>-EV)&2i%maLKc_zjfzt zw6>7_v`6p0=QAb|0d>;A_mS2PO*awwsAfF6@lO#{j5VAQG-$}Ev+$AFJJUHCz~s@pu`uT?*Kz2C5Ad8O*>}YrEL+8AQ7)h~l1f~?vp){KXd-^0$|~I-&avn#nj9U+5a*$ z@>^IxbWc+lmb)DuZWF!NJ0T;_hlEfqwp-WcnQby`W_sj0wV_lvGGm zn^Q*#<*G}7Q@Rti6SHMCG?V*w=R@OUb+Np_JD2fga>k?LTAiu10Bo&+eJ00BN4DXEn%9oiU&F@QS5@$HKnC7SQ>YE^^V|f(@;o;>TCTnS z7dV5cC{OcB;I0YVnj;*yATckl+>X3{t1FoRYov{3q-5JjZp18KQK>uTvZ^tpHKZPo z9CrWykyvUsULyUOgCKg|b!}Ax)RTS|UFtR07W@W?A^yCR*xKPt;FS{0D;R~UM@(2W zftoDFErQY8opNcg`5kB5>1@}qc_1e^KiEdheTMK-Z=k7EPsGGS`6TE_{XJ@Or7`V9 zb`xz3t#utawXSL+L`z5NHW032B8v8A7)?L++5wgZ0$C=R`!YA;a#}Nx zyY78k8U__D_kQ8(iM*bP#mFUyoZa7I5sV9NBc{}HV@81QD`EL1D@ULx@L@$fhZfu) zs@R@oHLPf{DJP?EEN-)pE^&f|XiTF`8POe8X|^%zzT6Dp1-NLW-H*bMMIkX+*jcu~_R?d_Z-= zV|@8p4!SYy2H&Yqu#F4cR&&ea7d_hq2A_sU*}!XFgy3VOdxTZ@6~E}Phe(aHKyO<%rhj-JN=1>&3FVNzAdtM4k&JN%UNW${)C>jOpKxnvW`L9mC_*K7jIg zBxadPX*`JeCDWFvLS2fP(F7c)Y*#TI2ALGYfq^ykN`3Pk1%XwzI=DLq271lAqy8hw z(@c%J2D!B@B2L=FASsvP`P((C3ase|;Emxfy7>bag4js^N4AwkRw_9m0@LXs9)uiK=&Yc1TyGtcO_pm~4;guuI~#Y|CmButFgG zn1bwI=xHHc+wW}lo1_E@-vD?CnUFU?Y4?1}B@{tkq-b7?T;2fa#tnr&(b_NXyq{Ek z9;sQhck~3+&E)SNi#ZP707S}8*K2P8vYgkn1)oD(Xm_2r47hZ8+O^pyegj~#uD+<^ z)9)oXD+=k-r-XwuL#egphrd;^@n0XCRrCAcP64#X@d zLC|rWbFEG@{&8thkZD+JtlMjl&-jWb+9M;bHM>9=zmJyYy#O{sJ3QhEpmli>kYpHjs;5|>BVq)d(2l^{Z&5F0sS z&5&Voj9tiA$$ZAcGW7pq`%DhZq?ZWk51^7F25e5j*$M_ zx>uf;jntav&`BRi$7$w+?_60dGYr4CKLh~_Ui#9oH*$%tTa$4?ESO)4-_C(C9^}QY_mH2_Hnm zK*Y}W%A!?H$Xny>a0A&<)pNkI4>@o}TAS?hNUrkm&jNnyiQlqSSLZdtqM_mGMjTF> zuHU=7GHey#P;QQ~>apu?fI1>RI`OeIsWqM^8Nf1H+*pfp=%jA5^ThUu)4Rt9^J zXwzJk5pY18R&H(581W);Z@2V^c-w@TsC0y|@|W<(sh%61ejUXQEBsd2O~N#)O9!3I(=Oj!{ZP>NZ__qYXi>@!?ViSMF<>lUrI0YnUZp zYIl`abpFJNT#+Sy4vA{c3zCRU@H>%TN7J=olD{%JD0gUI9Ag_m_+bm{yCKv;P&j&o z_<=1R1I~LqkjxD)36ab;II@-fnZ)bkJ#6D?nD4ev-ZONSdHVygcDuwRbSXm=<=`2l zV_e^5Ak7S7_RJvdF>hV2Tu|3Gs1M-tXm~zd2gR;&@LWt#?L6q{Kh*Y(c zMMA+7p7Gq7M<9Jjcs19ank7PQGkCpJ@=#a|b{IDr%`6Pb!yt}zFei_XG zrlR-gp#FV)p}}5cQ@5B09rylhs$Kduvv4HQ-SAn*!oiZcJI@kS$659S<>4%QdBY#; z_S2QG-YtPwYax(7S?hh%HeJlYP2~=i$rg#mXzzk1OmMh<>ngBa_0BVE)+3$B%39W7 zWw2Yo0?r$ZrPf-qM0`kV`ee4mrE_|GGMOpe#~Sx3prEO`^T+9(lW2f z@&swA=_Dx+Dp;OtCYsKK6D8&-nEbZ6%FT0QBQMx`T2Ss0OAjrIgTr1F3KUjQmW z)xI_jgVu+eb~5FbeLOm5>@{hpVJ)cpU1~S^m(J|5%!-XF6~hsWCmdUEE=9YKAiB5N z5>^TXnUWR|WW1Cpp(^c4QVH!!N|aUgUy&bH-d*y>8DzD4uJsw(8zsz*4LL;*4kiLb zQI`PXGda#6W_yEJ8|VDn&iA_Wnj``^SZdY-TzXu7>D0g)00n3TO;$Ub)U)aS7f0d$ z0N_{QJ|5nsP=5%Ye12yC07bgXzJI`c0(S56w(aw}Z{l{>1*H8_{fo^vbH~#;t93QU zvwJl@b+2wtH?$uPdgkF{PYA9W_a0(#bOEJ%H7OfepNa8EHOrHIHfHpo4j6ivWWFd{ z>c;h(X`HEu%dWcu*pVp0n@U`jcRlcOdmT@f;U!9GXdtMP3Q18`pPye;oeRuc&!u3w zcAcwG2TImwWTB#r;>VeXJ3tL=jc_5L2M30oMq8R#25Tofel4;+WWWJ8#qAp_vlaq&O50 zazNjy@z;TA{{T_T%|lnWi<)_=OSZAKY)ov9kj6HK%QN2Ch8vjen*!_R^I9lvp6d-g zv669dEdsqItpK~$6d76Elg(Cka$h4U7o*F{@+Ut!tzM9ny4>|k+&;vHb_i20Aoi31 z0!H1vr70usjc>|MR@FI6{4G73MwZyy8zX5T$CJSJI~NHWd)dh)#<}wcI3Fjq<}3Ss zN9hL2eW19KPBpI3M#>$O+%{5zlL*hOZYR5-Qfj$>h_G&J>WJ7(DxxGqn!;R8>h584 zVyWoKE9=@6y}nbghUEH)b0(WKu;_f*Bo;EB^9yB-#2hH`6rqw3FsTf#$^gAwd9`CZ zTI;PiK30qkT1TTZYTSEi(weV4xd+OQQR19onQshmF^?5)ioHrEERP;@Ga9Pasby_S za!Z}aeb-nW$ON+55((`Dl26f}SN{O3zbyG_EyHc@9eb<2fJ-ymlPqS0GByI>#yEiI zRqu0%6?FguisueBdR%a+8wLOlh1FH{Bm3mxgnl9%G4NjnZ&GMK zgfG57GrQ>5T653%AAnBX{!ZP#cTN0G-Fba0>Y40bX*-@ina!H&Yma93YJBTn+?;P{ zJ{thsDqamF(1{ZDxG`02G5&OTzY%?a0?ap?6Wx|uJs^M2!SRqm)KefQs{$I(8r9#6yOCo9FLO{o1J9lgsg z47?LPa>p!LG6^CgylUpmX_lFBsKw--WOj>w>6;H2zB0_Yvh8zSTIF}e*-iUW7t9>3 zQqEkF%2_J6W}JIjtICH8uVxy8YK8==940A_pvpr`rOnqEt8jn@`vP{{^`1<5cHTzh z+YJS`Ue+yyq)o%&XA;dM-#4C2wBlv)n$oydgFl(|qpIq2U6}Y~`Fpj^Os#8n&{nx? zvwC%z$JBrD&&5hl82E#@q|-}KKPi7nKe4`#_vY0rlj+89)4})Xn`b`R-7MPlcogLO{kl}!aQ$7sVTxn}c5S`cD zdx+em9=h}Xe)^K!+;c>__bY3T(FIVVWnk?P(>{Zc&sP2N8nU(mc~+ zEE{QmXeVo08(M-K2F%THAdmpYxb31CvAtfP*!N46jCaLre#pb=izDEy3OvTB@)cBd zZ7btlksc3`ux$!YmX-nCTa~M{4OP~@qLXWOLS0juZmzX*_U5^oH%`$IYyL^BeZZ2r zoE^k;#8I>nw=pV9Up8B7DQ&)=9Cp++V@PStNbeFEO@N99@5RQ5or`@&q2k=_o^wPT zCc2why;R3twU={wMw;{_tIbf8^m@GD>ef^TmY&}Y&yKrZcKV~s%zT-ka_pMmjOgM} zCKi?Awn8$FAGC~xjc5eteq)Urv1RFgVz$duyuEFuMb1-~iQyw}dnPp|y9GMab;dm9 z{1S5$C~}wZUH8HGLrq~nc)v~jC&B$L`%nJ>w|)`dGt2V!{Yg9TzfE?0@%42701)|W zrgCr6d>>)pe^}sW&%tAv^IT@-&6>YB>Qb22t20XHPh;07)c6^=x%-*vOvE1+Q(9Bv zilmE?{DuDjN<8~?W>38jyloL2^oP=ZSHLjTe(#9#BlmaqZ?|CEeY*JTzw%$p z58eL&DqHAY*X?{4$nGx>gZVoz`sYzykCAe8ejub=4PXGRC9eQ+<1zAwB~o!746-EOm(^VkK8kA!ZI)w1WTZPP zRELy?W3u0H?s3HgffRBN?Gu3S~BY@)=X z+L>5F8EGopx2m__QR)*|+LZ=2?4Y#` zc5u^0P%q!W!EoE(MZzC3$1MyT32GXb+P zRPmm&UC$cMwO^Xrl$TnMA@H}Pc|{8EEi|Npl9GFd+Q!s5iq_6v4Id=bu1MNk>UDvD z^p$2CDI{)e8s3s<5wkyfU2+Qt;%eS~wy%tL${ZVNJj{F3D`IQPJ>^QGyCFdh{AyC$ z5*tZb?JM$%QhwNt#_iMjn%3rV1DPZ;yJKZxVLh8ix|G%uF`2;*Xxdt9L`%hfoP4p( zc<%~i>|bKWyDgmaP`D}fYmHRcVQ~{{sY$8Ksj5M3s8OT#?x&qtPf!O^2CUrk9gVcI z#VgBQ5NS9Zb8HQ!B%Xkn%PC&gxuT)f_cqlzU;hB5-bvhc<$9%q^KKU972|3|er?r< zvA#=*aov>mqkgEDVU}5KO9yZe+o~!fwIHZ~Xby9;W5Av%plgi-HscU*G&qkDmN0S|DL-ACSg`sFWDJn_o2qR(+yC&nYW~m{pdX;h)AYfGR z^9^APafWGmLKPC$zUr9L$NC!e$Y_n(9z1Ha*4}x^j>~iPPb~>ks#=nFO4O6iGnQ>4 zy7tMYl0w4gG)VfgJ>;}dPz}|sC^{A6eIujcwXJPv4pBmTdQtKxqQ-rr#)%I#@=pSB zdm&U9Vfua;$eC6Z7VUT9kQU2d1sR!1LyHPX30sLEr~|iMpgien;!F@+PQmwa#7i*i zBw^SS{)~`#p2nVn>J-}Vk4`R8V(v{@JXOf_3Pp>Mazu4cur8X7b{jU8UYF!MArqt4 zg4GnVw6dTHP$63-K_{lQt@)0|dnet*;^r{Xz%=IupisAMarhN?*-F_&ZU7Ur96f8% zXCr+%xmj}X$J1Yrn3pVB79?CMcHP6NGVab_XNj$F0if3%zY2w(Jo;wxCy+SZIkrtg(&PRH zkt5-0`Nt<*tXbC7*#SyIlNHyJ<0tb4N#v?mNw_X%;{;UNPUaM zeA$yQ!t8 zhSK9L$%6yUN<6}@)NJCnR^WWPqo#9SpL}I8IovpgV)rz)l;1*Wv$07&pEOx>0aqGO z8lQ14@;w*12S8>$BPDVZ1>wB4F^KO&Iz2<94pm=<4wtWcu!*q zEVSByDJkE$ZLW`1=6gFCxCA~~>0TUdFMT?|z*luhRPF2}mAUY1dR%A`!#w(4=e#S5 zt6AFIy|MQuaFwj{G4C9uimwJP`dt~>3J6EWr6^)UX)8UYeo;zK+Yz|l4Lh4{F0KW$ z*(?(~!pT@zT~3Xl_ExF$Y0^f*@LKkbrKYq`Zmof`w2V3Z)40_jMongV`7URK%f9(N!$i1*@g1i z!qy6s=OiMZ=-Hp@@hUKJW_rRo=O)08^YttjW#s5pi^e~~p-wp3p{=%BQqq*D?3Yi0 z)`{nfHV|fl;uy)oN5n%h>!~#KD1M5N_*}<3pg0n_{UGh?)vfBG#!GVKqe-{!8-C%g zL#|OKFsRbu%Z*8%+swSvfGxGQuu`Ou2qR;sbFg$sy~d2+xSXf?T1}OsQDIl1wsBIlkK|dN@ALeV0$&qg>`p9mm-}qB=~NYWx;U{ z#&me4#?%y(^@!8*f(Sd%trVTw_1O0{zeuk|=+#Y>I9vOL_$?pmR0#Uo=Om1=<)?DE z4MkL@dUw{jcU+}%YmWRo!v`hayp*;f&@Vf^g)S`1YTrxi5=tj6_98`YXPO&vPpe`8 z3G1$RU1f_*7Z-BmY)&o%bDc~up(d25qPu8iA?%H{E)?tt%Ma6IAz|yngICMEy~7-Q zn`};jI&9@+n3Zdml&I_Ti}7i6RLhp*>=ySxNC2<21&#Lz^9)nQL{`&FP)E&>)6`3- zD1Gh8dmEU0&ueMdkEka#>j6xIPxYv%y9zQRIaRCT`85KOx0?BbPHe1?4a!iR_WHg% z>W3+~o?gdrlizZiQ2yEJZ`x7s>w*6O%~P0P!*q}R2LoFCnm^>${fGHQSJc0>zqjoL z6#$=?T}TRoohqLnJwyFN_`Ah7lZmbDA;lgr+NRvbxd!98V%fIkY4=oBF04&vT2%Y< z7RSEp4f%fV+m5>9nSZ5eSC=0s=`JRAXEm)aaOiJzU6Cykf}v7&&JLEDOW zzL(rig@WzxQR*$x%G_g@XI|WJ$SlFxX4WaH;j} z+7e02=3P+SzRAtEmN46fci!BcJaK}*jv;{0==MA4$`5LQriXr_f9oY&FOi2T=o~JuLDXVUAj0?3sr#V>z!X+Vzg?eT*NACTc2`X))c686lWzL&{T2 zbU2RH4U~{iP4#13w1(!wXr_~e8;5z-0)P-sCk$y%N@c8$WX*G1nZV!^+08zdT+giD z*H&ERc1y*ae7OXW-N_geu=@C74Swmj9Qwl>3Q z9J4WiG;rc^7-6=6dUkcIQrJ#hT_I~p#}@?Q{Zgzd9hvEE=^aOfmZ>@ZRh;HlqQ}e> zM&PT3VY(QdtT>2~gDzRGrdmx|uN;gSbZ{sZrfHnp6Vd za}izm;-=IZ8*2x6I+=w>Z`#<3UZAWkJO}h|N|EmjZ*`N?!+MlbKOa~5Sbxp6Z|Pb5 zlA*sp)$RWD`{`8X1%|Aj#{U39{AwRCjzPC7bT5n>ZqL%y=rMcxf<50ee+@yQ+1?@odTWAYd$*EFpzH&7%GB>r>hhC0V8N`w1(%}M zSgBgv&$Td3d9~aaOO?>-mM&$-k10k4QWa7Q>5Ssr`%t!D?b%>=1Sx3*cO4#mv22=K z?pxiO+=&?N;DRgYBX-Kr?n_COi-5z6Ux5kh;Jfza;SZ(1s4Lbaj@*}wv&4%>9$%m* z;^=eSg54fPRw}j~kBBOehMY(R3UDZFMzA#-SoL0Du;LGslGr`X+~Hior>iznM(`-D z!6U8g=BJ20fb?#!s;QrPI?GM3eRE%#RmM|y%Q&BPt;TK&Wpx!Lop}1Unjq@ zK5AA;D%oU>$kx|9w>&m>4erNrI~eL=+!&FEqMeGilxXQ?IF>Mx+tQ)3%ym!7nJ!Apj=bxNB}!7%NhIsKiWWr1v5f((6aZ`hYyo7s#l(_o zN}t(z?(faN^nGtiE&Dmz?ZbsK)wya>?pZrKE=9b|X6DnQy&*)n=fW8-wAfcfG!T^Z z8xJ-bY*xJF$3`gGVROhEGggiuY!#pNf;BKeEj1N7Ty@D zfrdD}#>-&a*y{VZZWz{$zgT(I6Dq1rUQ$&1^3=z^>n-_y?}+QGt<-dF8vf*QT`kn_ z%;vSF?r%eTqW~*_Cb+1KH#adex*Em`0!;zy#P3e;(^rb{u$2SUDvxsVdmCkGm!}@D z#%fqj!@3RI+`|nprPQhtp|l`2VV8p~guJzq`u5l)lZnlm!Mc8)=37e`ZPav2m(|Bh)2JpHD-{DRBsx@*{^*J=LKKN`VJgE%eCldB)~R1w=8%;10~?pa)ZDbY`bP zH3}!r=4q@Az_^j^ZXZYzeZc@Z|<*ACZUPivxjxCI-c2|>bM4?dKoVnGMF*(F2 zHtg12N)xxe+<>96Pg|V9dl0?TA)Sws7DvS_V{;celx;@v(ktofQQ5@q6z*vaadujh zN($qTT4A)$NZi{*sZ;ATeqdl4MPicsQmIu~*>*H}F{H4dww`I!G8BcOU=*kjK^u*9 z59d2qG_}^3Bpe7Zni0@(RK}SgH4-!Zq;mD0qEc!%PZY9sS0h>3A3I&x?hPN373(_T zk8nbtbK0d51xfc~r9G}oj^ksf9TBh_Cv#hoT;UzmLN~Go%3Tn9OGs<+$}6}U`ufxL zPzjC1g5ugbhPaLD8L2HPGn*uifnSZT;DwZpL}`R4B-XG$zux-VVF<3fY=3_}`x3uI zokl`(j(n&;jCj6)5Z9PCS{4(!fZPH$2gL8HH@0q&hcj;VEOG&XUZ}k?5i643 zo}A(0R~fI`bsLp=60>aF6iON@%u=Rb7M(A(GU)NXx@xEGFH7%_fx$aoFNI@by$;0^73rNFbj2HN|>q^EuBC2dwCbJGuVapXgHjd|c$^(XNm+l=(9?DfV?_GWx z@+OnZE<$rqSk2Y=uaoLF%&QwUQ|i?Dw5ozCG>D8cmeSMZ@=L8PJNbJZyMZVvQM1Wf zwX3Y5v(HJ`9aa!Q6mdNi*m`}`%}(AyE2O7z(udHX7!7x=3n_Yi^(5klCA~vvJW}MR z2PjYS2a3>fovUqIn9kg&#&PU@Tcj|ir_$t7RO@O&(n3PrN(uLS6hac-{&UNkrJj`g zi)+)uxH37#&Ii5@#|Kl~^z9{V-a#e6W8&{KC=?ryMG}SSb;9YqMZCEahB*m!(JdZv z^6L)X)`k+}nk%qnPN&nS#YB?2)RrVJBxw~14KO0d?^B(Py0rv=Mxy3zU|+`s*6nkx zAeoMQnMeeKPUs?}G!vNYsRI=28*UMEUOM^0)`fE&&cAmoMyz}>5NJg~0)~c% z))iZ}IhK*N*bwI^*!1lidVug_{{W0w%l`n(aCOu32>$?--hV?U@(QD8{h~jEa$zoFCpEqvDC}n z*t)HpWs~Y2Scz@jmB@ZYK4O&bxRS4ZfK{+1zzG1IQ0J>jr_!7wX?Sbe=QM3|8fr(| z^eMEd8q0y0(x8BP3D~l_eHFb?Y8g)ErQX`G z&{BNGcYd3;`=h&b>F{&DgxDHcDBJ@BPHOIGXdaG^x*+W??7Y>!l0`depRYK$@owZ# zNuD9W;-%XIHR65*R_|J8A+ii=glK4PrCy&M$rGZ)mhxn|7F|X6J{M$_sih%(fhVRP zFW){cVY&9kn5DaG3~eBs8Vvy;P&hOU+kvR9RjbH@tl7djn;A7dyZbA#Al{{t~rq*%uu8 zOs#^vsZi?i9%*|Y9hQ)E-dc&WYI?&Rh;)qyu(X1e^NV1%BWMTT30dY>7HfW{)#%*y z;DtIKOsZtMT`63X9n*}E+Jx)gTd$#6iB;uic_0kjl2-sMW}Uc@N&)6jK>Xbd`T zq)cKmcv28@J%o}wz+mBxLD{iOcWiFY9t>&*X72~Hp=HBPELMFotCG3v&iD}Vm0KCp zDvIM@9;VKY_1Ab^v!go>JEjbG7Pcct4k)e1HYrxi*aVK_uWJm~*fiZVnFNG!WB}x2 z0R)PXi;ffnZq4{BOLJ&=^WZ@4w|PCC2^gW*s<%I)UoP%y+>eT^+}wb-=hh`{+vZ7` z0he7~!^631Cs*f*vGZM{8-Q)Afb0$`7Pz}lke#MM?FqcF4_EdI*Ge885M)0X{&>VVm4In9e^RvP`)kl zC!Ul(FY*_K^jEX586abuV%)c}&A&c6-LUHvmQ>X0WAw7(6osUOg*cRx)3sYAE$+En zSh3Ncb!(_NLvm$%i<}S2G@KkAO`Tqmi7D6i^4y5zgl1+?C_dzkqKNtFtHarxRJ(Kj zAuYYOT~_riUW!w5pHBpKi*kFypbBRMuuFGUs_gb+nG|pei=& z4v(0wH4ApSYf}_i@`IQ$?FFw5AQP0g5lYaU5jNr0Y=z`DOwOftR2)Tm>Z5BGdNOmC zvwo(Dm+^Vy<~F0cmvTmCx+*mIw*3y0!nczv;!`0=kW!DdOJssb-APXB9cAA>=?sLr z33&1!3~UZAbGHgp4!Zh@!Dq*$+!s;p%H8DBfGGsVe2B-Kg!RPYL~Jnn;phNYuB!BN zwp~U%o(A_vUFt@wojn=e-rL5arTl)s70}Px7Ws$AKnB37)2K>01dUgV!wtFAOf##XbK|28l z?WX?#PxM~(50ig6WYsWI?V4OCm-N0)s8ygbYD9p^-O1~yhl*6n8~rn61vpdSj_#V# ze?Dk}9wTSWPR0Q2#CuYG?bNiz1Xdd5 z!o0SDsX}VnpJt_KK%)h{a$FXzN;P8Itx2I(Vl56vpB3dY;#S&%l0iux1aG4FnIOvG z2yepj z(SniJG99L>GR=1ene8l*PChJBLI6GP)XSD@*Pg?IuO!mc66o*omA$ZlT~g4 z?YAoPK7(Pxq)`l~3_!l(uHe@Fo9=htZD5Gon>7V`cdKQ_lupYaQ8;kl3po8M!Kgm} z05RlTS18YP<$Wv}V&6ln`XHdb*ryVtcJJgUukN<%tm|Wc^o+tm{aY(?czj=Vv%TxX zp-l4^1+@9fn(f)UsWw|y=(}up<;k+H`n8`XdQyqfDRmhX^}K`~(w7v%&{P3CfOV}T z5y$|0L#fgM_tkMDo3PPoiA;%EktzCv&dI4rTHTc?*Oa#&TZg$zQjX-Ples6yR$9;n z2E@wM3JXS?_X_^#bsz{WqS2=P%D+B!APKcui$rlM#{jkk7QmSfVSS=Vh!(~&tTMAzxF-+;G}gSt|+Fr*a#d;!!mTSX`WMh5}X z0r%6|_cvi77o_}L$q&nyAyTDETHKQ*#i?#M;?C+)lmoyj_oFabfa3atf&_--_) zk~^yPy=v5$*41k8s#R_JctEAlo`a=o2Y zHq>P}DDBFh%02D;B`@@6T}`O@7Ip=nCy1o?Zn~C;BC>xQT(DP)+BG0Rt*O+&CY9(5 z(PxGHZ{_|8^)pu@3>#XPhV45h$sry4A+FVB)Z7T&OeW3K~ zt{vw|OgNM3cLHzw zw+2QJKxHultkmr)KcpgV41t+?#ZRqsdW`Wujgc{j6a7YbF+rJRadVavWzsIJFFt#< zSs3FX(O%wl7)p5|#m9LGTH}?dsHF-}*|j#2FD>e~hHITV_=j9T0S^M4NZc@WI!43W zO`xXU+sBoYL@3AMPJ%al3VM0phW$D{Ju?3Q;bS0i&MtPmGJU;mNx|G!iBo!sYEdc8 z(%5RDaaW#e%yrevsE3f#*Ap#DB2Qs z;yTvF+;;Zw%v+d{DBXi*)9Kup-!yFeGk^Mc@i&y%(~nm68pzr2B;*Knsx7k_X=N}e z@)pb*dkFTn*1#YH?tQ!Kb48ZoEn4Q*S)C&yjf59;k%=m$(^%_vNY;Q{vh zPe{miJ`I<~Ye$$I>6JyK*K_U7k=k~-WZ9Cc%qCM5I8-(rWvMGeD@xYt*SQ5M+=cmV z!(wl>;`znH?d>xbut(i{z%(u{Ad!yY_Nrem3et?oA0;Ylh#gc#YBkTppHZA6pT%1W zrrj5RHN$qWY8R;3;H2tv}U4vSII?x4#o zmo~CEF~R-ku$_*~1xtEshoprVbT=`&t!#2MR8s(YsnWM#Ty@5NB5=wh z4_Zz}m~A_;=%EoZC}0xE+|G4!jno^;Q?PF%c!SRzgGA#;CU|L$_}x{@5*nf6 zEd7Wmj@nW!+lqNh6w^|tnJ%+AmtRmq%G3bdZjtusivIvh)U=pQ-KE^Kh{k8fGqdJs z#o0{(X#){Y;4X@IE*vA0Hn%nav{Hw4dQ?GX3{iGq?5&Y-?eiHiF6?DlsL?J4&`D`h zY0oK@IMRssn{&6h3h+`$Bca!GVRs$fymQBkBxrE#BEG(rl{9XR?qS*u5_TFR z+-X0lv=2f3Jvao~t}V3S)Rp$pq6;LXsX-|n%2C-Mdr8rvNkFGl%s9wzp>baGsvmTH zpIbtRuF}!@j+GHsEvrI_D|u%^h^k6fg$1OI)8VENlJ88G&qov5er}^pqAKP1{{VIP zhfEwm0t!Vy>(+4+AHQILu#-p;hUep*x1l{M`A*wYFr7GdJjyH)y`@%g@e zMnZ5y&`hO1ghOdk9CN{x0-~Yy2BRSqw_B9wAi(dC(PmVm-0Np<`&GD`iz9& zqem)#DEGHd_)1^s&bq5n@(k<>gZxLeC);)Yj-;Y$DvffXUt3eDLTOt@rD|&Qedv{s zFD$FUuUz{VAH{xs+g8KW7pXM3!Ag@bQ{Adeb~8ywytTg5Ds3qrY);!9_SXTG@T^0Kz8c30)q@tpi{8&VFDIT?jbzEpy$| zS`XbxQP>4N^z^-U3$nSrPi6O1^DN_=3AS2MDoPtP?&6e#;5(E~!`eyKCn5ke)BPj; z^=nr7{{ZzuG+Z^R4n6e1^oY9dcGD)+v-6$VRJa;&ZiUm~R=y$huc7E$LV@UhrmM0i z$*pQkXNk}>4$|5L;^5m@3D_Qe^wYg;tb3-+^)BS3%aE#6EP*S|k9h4#1Ae`F9c}7*v=$6wrK#dP zF`x>P=WN2ERD#{}5*xS@YtR(-=dM-R_-oU{(#HN*4RLQK>{{)QRkn@KdePshKSQ{! zsY#Deh}mJ*QrE<|6z0TkwIxS$w)){T?IKH^V^NRV<$>Zr>M((st`!FmYfYV13tnr6 zvf3AL+VM(aHW9Tn+(YV7O~3MvIk7QMr6(WiSt{$TQz`Zg7?$MLq%N-}LK}(L;-&<* zv!y4zkQ27#fH&6V=PbGyB$91TbPtJ9o-77cfrpAuro0@VZYXyZ$5HPL%eyF z$SUS;v}qO|TY9|Ye2Z#Zl2bm90l^3(&N44Ewknx^Y8a{*GbDzK^B<b5Ad*E!9*j0oQoVDXJIlZht{`lxYAx0&i|~{O%u=NOIM(nTm10U zfF`RdsZB@QOhMb^-CvEqo)D_$a=%YT-dS7UCdt@;UACkF3ZS_c1cw1kcEoUhFZRm( zfu{h0C=E(miYswNYggMSoypU{O-ug(7JSmMLq055iaYjW&?Zj9R*&WYG ze2vIMY4Oz!TU3Kiw0+FRjAyL$0oGLZw$GkG#_cQDz8(JnqrJn6BOXSRmu_o^GT&~r zl~ro7XNo;7mzELk#*V^NqJ%6Riq=ZO{I7<*Hva(4jZ$fdwvCX-xDlPib&^1-9RO3U zb+G6b?QedrKBW|%r9O$D=--d)x%-Vb4MOzBHj)GP{gYJfdb3A{rG$K2ZnT64*=&*K z9?()f?t^eUZcy_KYBRRh?TwCScwE}$aiwXAG(7^QyEg61)U;j`43QE*+78jypjLxO zP}+2aY)|`H2lQW&uTi4sk*mu;E|n5iEgb}^tXn@Wf-1$cgq|bXliiN`mwIhcQ99(pzE;%q{EbQwD{4liYH41Ny%4g+{en1e>oJ+}WqsRM zBVy|h99L}1fuIzq)e3cTQ_U$zR_SpBr)8l)rD-K91QIpCbETwLT85Vlt<1;CBS`55 zpnZpO*V80)aL(qM5CI;vj7{fXq?TW;$jn@b^scJK&Xs8&AAQ^S?ZcS-02aO>VlDy`k)t{&Qe*0%r#z!Z&hpO#0O zdBvR1_kc04lW$NcKYM>l{WHJNafE+A;yxNL>bq~-+3xsme09y}I!DpA+#LD)&UI-| z5v?gxv$bBkxZ^)HDS#fOj!ET9c^icsf8pEM_)`&sZX1@oau?FRd8!+U)w|?~9}JHp z$?n^~&R=)PH6^x>!qlg{&t5B9+_c%3eQS+-0&JH#plnp|l55(Qn`hJ)7TBVjgaj_g>#d%R|ej6{^ zopsBi`MjeQywCy#iKfsBcNA&@ZgmFFR#lAsdN_Q!^kB}#(tx?4_8iUk|od&oO<$WhY zsYDU$$yhaZX)AWpH;nE$ME=o!qeI>pQeciSZsf+t>6Dq^v!XIXEB| z(1BV8?gFjs+N#=J@FwCBn{NJ}T4(pw%A3~syssov#U&SQTBB1^wEUYYz%0M_T0oSEhoBqurUr^psfx>}uFit)OY(Cal2U=hMOqJv;;! zT9Sw_MBnsvY}hp{;mI56_Q9xIR%ALo74H7kwDo>^Tw0Uu>eLmWpUrLU*Oqy;Ic}S8 z2>ZFS9>y`>ZQ%Mkmqp9199O%bQ`UchdYh}&uK4gH)9v~4*@V(%s$_WbT8!wHq#?LV zQk~y+k=*HUY)<{1y?X1wLp^J*s#b1T*3IdPZ%baY5&&tDBkMCE~K z{zjNWA!;q2z8YZ&t?-*7N_X%8{x+CGC}BX3qp!?$5kxK}y1x#II*f!u$qFk;-1Qzh zjD+PDnNWWi*SGMLztNp_cE2#rz^F;$DL(f2>P_jWq&3MkXf28BsX_&A8k8m{fyb_B z4!3c0XhjJkhc!VYVYr1nS1yf@U;>X6Kfsz$_Iq`@)m0AL-{smT%kgo) zY)+j200HbNqiU5Pg>>nzR4o;-Azvn>39B_S9YULN0d23M&~_k=NCIg^Dut}z?slE; z4{T)~qxzD6qp3n^2&&^Qu(I3jsiza-g#r$xXiZj6%c&ZHTSlY_t7=EhsR9LT8jvQf zplRVXW(K4I1(u`;EQX!}N?W}cGpxKh%xWF8B1wmA=QvK<)d^}U4Y5;k#7d;NHurni zF_bU~@Jp)K7v>g|?YbZ(QFXi+7PV!llR5?B-~ zV)wM}PlKRa4oZVcYtK`?;CxaCy7Qh|wkkti$r~i^zt-Q)`Jb9KOFQWxwze*gD7b~k z06@!_q_P{yqA1iOjKmFi1kK&%9K>AaFy-2 zQ2CYY*3T*P7}jkJg}Eh-*2I^27 zfH&K7_4U({RZJ~zGV5e{jg%AM2;0Ez`1*{sIbJTwkbt5AP(7fYr>C<~kct)~Q8*-m zAKW;wIsvH4a8`~#Mc-hIR#?Cy1o~0B*XMdTJ;S z`i8j{trgu0EQ!*iLWtRVOvez^W=D#gaD=1}s!pV+0;gb2PNv%8yqMblInmh z#f-_4K|aMTN&>vBe5!`RxAy?-c&)qBT?TJ>TF++x4x( ziZtKz+5Z6EDgD<{jalCl-TnmMXX{;42ipB<^tt%guP+XH`){{Tx_p-i+7nD41V3#FFS>VVjUZ`FS$qzR=62x$Fq z{f$c0)r0hya?$0c`DI4we53^DP5EJ%2F~i)%ha-MxV6^>%*YR~IO)HglEM%aO zSJ{7+3TzI)Q@edg6Hz{+Op#1@GWklvhV8h5dsGM20P0qzm6bZ3CZ_RXFdfMosY*Kl zH1?p5P1z)&K4k5e`Ct*#@%11=i+HjV)BF7XbNYIaCai^!o}11;Q?Pzco)ALOZAx@t z6t;||k80Jp{OH(fK!P>V>N98+8f99GC3MP_9rmQs<}!S@7=48WwzLu8QlJPrIYAU6 zpzQ}?9R(0bH5)?u6!64{2d(J#}7Zr3-ys@Uy z6^U&>E`dn~RB9CZTPl%IoYW>0w(h#Hf!Dxw)H6#QOfQkaj2qlTN375(7{@r!3Z%BX zn5~LqP8w<*t~{QJ@_<8K$DrNC>^yex-2B?&b&oJ~YY9W6XbbXtWF$T`foTj@eGz@=jxm&16d*SW6H9aTXGL+g@x8!U{NJ7%0cKoRuYsh(* znROjvIOTIhP-Bn^_kqF3H{EOi(t{C(D|*h-IBL;}J6EwEO#cA-KQ^u>v1!+@FXSfs zyKA8{CFAB+>}qUh97+8tURu)Pkl9fw8;-v>O=a10eg2tk z6xdEXmV>nD<#2q0wAd8XuZ{Q)z=CNub``bg&>9FHOH??Abuu<=o!dQ8`Cqv^k+D1L zB7JL7nc1YemB+2__;>H=*lHD~+r-g>0Q3Zz+}NW7RbbDLePSCzZ51u3)LofEhL)L( z+DKBA;u}hklpvANje$FTvD`zf>JX6V?qz8o$9KF*9=?Il5_AzbV$gj7Ko(%bJX6j& zGUBo^9y_FByDsyn!hvdDuDu~kr&L-{WxAMB)}=JbeD|#bp&fSHU^e0BEmPX9rnsH& zYz_w~qjNT(ygGmfRih}b!Pknebog>Tt!NpPcye2bS*wayQf;iSZTvJjs#v$~*oyd? zMNJ4lZ5}`y6Sl{+?4UiG_kAN?vehEuTR$~6gM)`?`v+R&F0AFZbsjxCifU2^>8t!* zY86>pKkAC#V}jHUkAb=F$^!#e_@Cy1o`+o?CEqJaB4GKl$N%D5;}cNVKrJ^01uN= z1PZ%OHsDf`vXTiMz=96nP@PB$5I5+u#Vwc9O<`irD_Pn z83{@f2e1vbC_!3XMh!d5_}9Z8ZvIx__3hh#0qoyWH8o=rvr3rqW5$-3URWh42_wL6 zd`6`Sr3`?dlTrlIxF;k81%6l^wJ1RnE`%X)8gQrIZNLzIK%jTjfdaa$rdttYy|?L# zbF{1GNx&!ALSbJD@p4P|*`m3$w>8lf& z(0%^^^cCm=9be5+Y1`s-BkKVbv@J% z>R4%$_4V{ul(*bn8PF4q61V~USNxzpmpS9mxZYxmEx>-~4|HMgQ9|~;L38N?%Xwy1 zp+28%+l?Yk$xumjhf+!q*!CxGic$GD`958F=R0$(nnUBZwTww~AP2k&4Fr~q1v5Fv zV5q=U?F&~=)5Og$e}p1wrsn&B#r#!e<{2tSlI(PdY=i|7=5~?Zdy;#AJ{>x5u1vwt z_rzAPHyy5yI&M2E{=j$QKt1Jq`hKzB)@r}2|rsldV9ZGFVAWBxYLuB)2gwII`9yDQfW zsL<(j_ZCY_dFA$xaXTadxhg&YZcj~hw!DkW`c!6lBjN~}TwN*502tRM48oWS9Cl)= z`+V~_F}PQudvf%%;8lT#t;VmnXe>PRQX8eoQwd3xB`FD9f|54_r?@?XbiH*{8{HZ= zij+d3xD|)uP~5dhi@UoN4+IGA6e!x_1b2eFyA*eKx8Uyn-n{3Wb=O_@Ti?H#%$}L8 z&wln#jBv+D`*@38%-vnHRU=70{jDYD);Qxw~M0RURcCOqU7=HBBZBx{-MAQp~J-B-35Hc2B_0WhD)E5OY3$H5~!GvRwPmFImQN8 z90k+`#yR3!eV5TF^lNaLuBCK*-W&>U4lJIc8H;+I(JLMW;1f^$e0mqEwJF3~|K*Mw z2gj@EX3|S6@(6H2$jFjj98R@~@nZ_#)pX(A*XeROf5GWjFqjM`!S{Zw5 zQ_j^{an{~tB+)?3`m*W4fG=p)cdUfIhB<^F9cFhfd{r5FPe@!d*YiU}1@KTm*~4SY zMX46ktnpOd$>&ULt?s+7b1z4VD!M%liJ$THrGQ)`W#;@?X=tymn&lT6v)4v1r-@9ZVtUyP%^TNe|e^b0An+#+&zMr3Bc}@brtFD|3UthXhGZd z8kPtCmB|?o3zVK>d2s(Okk92NMG5*dI{L3pcYXr2!*E|u51)@|{kAz8Y$q;0dxZy3Fi!-QS|IES}kVY!>w$ zmj3maeEa%xl7MC8&c(!kGf3&jWbqZ5O5sLAN>!G1QOL_8 z5v2%#iEZQ z$p*dpPN`jT*jIh&)`lhBdL_j4{&KG80&ODahx0q4)1dx&3dgMrHioAs*5Bct$uMN4lIKHkcM4b6e8}$f7qf~qgLf30~4X$d^3@F{hAD{C#>sW>fe0-sdv+0 zeVXCB+iY~RAzkt%ZSx;uY}I3!f(>Nuv({k@V3HK0w}?AbM@Q&JXTzbq64=lju}7eY zRx5QE%6${agsE-XYsX*VC$kE3zqU4fwikPJxk`pO%qWx8yITTYXQ&$1EQbquN7*-N zWwH$1w^BhQ-fF`}3+bL2ekRi?Xn>Dba5k4ZT>Rt<=K86m0{PC-tI@vRNds;#`l5aH zrw@bjC_&iSb?}WH*{Gd($9qE^j5 zN8XRg$SP;w8ge|`ZpCkKpx{n0^Su&Wt(BF6aXi354kDHdNexC-D4(Sk4X6oJt5I1A ze{2mI@Fh}IbfbGu!yF+Dlh`*q_(Wt(DY~oRPhS2$G^$tnQwolzX}>m=CN1;n{6tJl z>YuU&vuzF0drHw1mm52 zN$@qz=}Lz8)M<#mck;Omu~G?@o~o{NtRe3W%&RBYuYbFCkeN4YZ?aEuG67$L%&{`j zdbK}p?F~s1NT>4kQMq#c@a>E}Dd({_Y;JH-;2OxtS<+8yLrZp6>tKp(MdGDtoTf%y z~%+C9En&evklO3+EjAuhyD0TIPKYBWa`7sf%TfV@54rNBGY$J>QhPvO6F+z;F$ zBr?s3B)?NAxc;y?lS_(4(9QkAAwQ&8EB|03B&NHraWH=^cyt7fbf&hp9)(9}-zUbd zgX1`6Y}9CKOly{C3m9A#Hx+ZISY05!1GefRmPy9-Na^WB^?=|c)DkD_+?jL5kiPxI zXfGHU&s4cOv3bd_G#=(b^OjlrGL76GCH(omeL8MiK79dd&q`At`7Q>Njg9$8Zz@f- zF1UbjaC5%yr`VVnqGLWhK0m4kxZwV#bq~J{TD0m-Ks#L;C-J%Tpe0_pApJO;={+F* zYI+(@cCAYe{&1}st|!;msjYGrY0C8`aeFQQA2=4=v_80iEAi&vtFm|&h=au=V%ub{ z(9Cwsk0?RcsqO|C#vL#^`6Zbv6}|3pph4gcODWFfV4Vj}xmVCZ1k@5Nw4?uJy4=T#bCjWO}RdiJy4-mFfrPE^jfD?{${$VKbo=7^Q430Kba}Raszx zr{*)>jZ~Kot~KB(;Iz?7{i)RD_)fdf%BZ)>tWqIUYvT?qc=}_xVEF$yRx!azg)h6g>%NM57hb`FO&%FkCO=DxZlULANdN1+Ci%na9?iInta zHXhF%8e zC^g;2cn(Z8GI1)%fs*ZomRT>~*lO&QKT%v- zL~}4X23&!zHi%@TY_V}tqrv%gmslX1iiyoUv>Fd^{MA~Z6Dm`~9?yW3!{6@CbK)CY zH!!CjA1Z(=4%0cG>0VY&=Ijt=I&z~eK@C2qcIw z3?YI|4Lgzn%ojua-KM6>j8E7PW{^$>TRc9NNb#xc00qG zn}N_jb2FgcoRJDj^2s9Ab?xN3qSulzcq7W#>IJ0Hf8cbYbf)TsGDP{=>OYi?u_}Tg zjb9qL%jsf+sAb6M0{8h$;R4^chte6Zb`7N;!QlD2GfjkA^*A>Q1DOa469liYINZ25jPkoG%#CCy|@k zq#qXy6&+3)NZSt?;woIU;L>STugWaHUFTA5^6a8E@vB&9)RzO%*NRt1xf1fqrI7kiPwcu9;f}cj;kN6#4MF6CAyk`nJ*0yqZl(Bp(%1WN0ZuT zcJ=mvggJ(4r8nYoswWzR)0CCY7G?Fad1D684lq(O z0$KSvk?l7YWB$l`mMoRa4lKYuyz8Xuoz`)@jb!jErg#GT)>LAwJ=%vTg%i8S1Bqu1HB=ci;usU=X*@PZde+VwIjd*$ZS}e({)saq{R2NBOy&7#sQ*it z<@BR$2nT@EkTp`t>+9#TWwp4u-XGm6PAqQe^DFY8#NT1Ql?{3lyo=A>V%F9%j5nJw zWCf!R=jeb20lsFn!;_@Lnlr_prb>;JrtRqP>t#oz?8HpQQ*Dh08(y2wj)`2-Rj@6I zKtbLbJTlytWL0HWA52u(azh)Od7bGzpRbgs=()9-FCJ4M`vetyI*}ot+^SxT>WR2c zYGe*O;8tZxfKiCT4uzh7)xb28lb3@{&BEmqsOne zL^Cr+IDKwZT6 z^z43yXz^XF;yyfAmRbYZxBxad(>?krSmJ2bWp6V`%1!Af$ z7{%}H#ak8oTDW-IHl=;RB*-6iM5-8GXhKE|z(>fQ#SVCfA3BnRBR+V~DYdSN;B+iafl6nRg4s|#92LD zPTRgmDJSqCmn7}W(^owXTg`hW_wNI|VEJIsESdTlXO17AazuVpjb<&&yKJ&28eoB; zFU5$l9$GWYX|G$=cj55}N@7ycV4o|vsbHg*@qA&a;;GBZW(@ZGdFkeI3{d&k^7nkW zlMF)GjqE#roWrj~;p?vKg!4!2$~EFf8e9QDi#zKJT2^@({r0J0L?K3afOKcg`!i-> zRBc+qlrF8nCo@_3q+nWq*0 zU`uB+2rdZSLGneX`@ zIQ_Rcwzu3!(XYD<55_ZbXH7e1BW5&pd-?|c?X4{dwl3M`s-{J4pIG^xet5gdH6DC; zbiI>KSp~l_UOx>F95SB@roQ)M`SUix=XM2(83Modq*eeqsG2t0CM4!Wf)Z$x0`N8# z7!$Ru>^ZoIHGVJ#oGMm+zW)7rRSUl-s{D(u*%pcYt=&MIP7O=l6nV*al_iBi$Cj%I zJVEBhAJUSOF}_KOe&q(8g|=GD?Qi+T$9!6$+{mh}eCWYDSP#pe{w9-3*>wrE!8yKj z)?U5z6e&xb{EJlQg!(mzTw-fdQ3=_XF@%KR&AnbVCFtR+ZZ_2bhsuD)qRait83(p2 z`*n9yoZl>eAx>ofb4K(~8D?o);-#~;$jTZPk3#`%Y}brHt@9_liT*F>Yz25kA^fF2 z2jr(;Wqn-l{4K4?NL7>xOX>?ti^=j<@0GZ=kTF;RN9o}{`uC?!ouSKdxhW_O+r@1pL}v0?j6^2rZmGt`u<$fRSG zb(2BzgoNt4PJ2nr7b!`YaZIOM5#+1+HzMzTWbCPwNbR(}tPQWQ7$%%Ng3MAw*kS^f zk1v^!_`aLcJYelq2ie})xoNBM>=;Cw(I;bBlLi-?u?Aa}e)qs&v5Q5vNenG0GtWQS z(3)%F2G1PTG)lYfRU(I+$-94Zk2zANFKY;O;}%l08M6IBPr(sQt4Qg?=_&0m`8}}? zE2dQt&+QCh=bh`-$jq{N^k_^aM*Bcq>TcWXXj|zi+4;qIJXI4ivGEXf8KM!d750iO zyHIW5-|zx$ZaqGk>RC?H(*;EO8x{mWRLS6c<}i8nxW&9jF&fK^VMlfSrG5bCO2a}l zvrEYdgN6;kc^A(`C&Em1x{AaHHO+Gh|E32lo~&EojL&o$nARR#a_A^CvQq6%dN(8M zIMN~X(B{r-iLn1MzkNz(1ituPvFExkd`pmGUwcpLkLZxS_Hxr`%8>+u^!Jq8pc0KE zU4&AC_3?WajFGY*%TPANmB~Y8%@S4md5amtmBB#o>tp_O zB2;zDCS}>nqEMlcR~)Kad@m{#SFs;4$f(uZ+}T?FL0ri7lo}{rEtji4cm8o&k&oy~ z;x|0|z5%CVvybSnyAN!+?D5K;lFOZp7&+hGG(SA@oOY<$Dm!K=dls2&a~0uAM~(JD zT$?Jal7Yb_>?>8T`R|wSz#|3igUsR#_DI*t$}z_nJj4x0f>;FE)G`~3dhRC5gRZ;e z*4F0zV{*g|GJ}}Zh;sK7Mu{zft=4BDr@yMrE!2^(!Bp^;_la4ickbn0`LvIU~uLRC@opqIYrNwXsZ_P1Mwv z2H$Vhn>zzV;2)u&l^2s;769?CmQAz@Hj+>W`BF7U{bXP^k*L5jE zZpBo{1@8R({{1OW1;Yc0WTbZPKX9^{Bo_80mt(EcEPIJpH^YC5DtD~ecNinSciQ*< zN_PDCO%$!XlSy>M-xUW>&Rxjfl%{E?S|>8)J6-|RT!X}luH?@%Jd9rKt!iQ#O%Xzi zPKAc0G>`_VB@5HWpPQqg3dS!rvwGeZ&^V6wr1rTs1+$RJfMdHuNfTkSyaLxFeE5PN4Bn0bwSswgGBrp->|~&zEuZ0J8BaOyj#6isysa}yUhJ>fl<0T- znh=44P-N~<#NRTM_#*kU4Yf7a8HrL@d+F@d*a1Z%p@{7)x>>0&iMt|9zrT$N;2F-A zdPzXls8BTp(?cNq(Jb;`5y=8;S0>#Z8ulGR>;0C0Y5|1=DMVb~7>8!eGw@ew!ZRR-L$7ronl$*%0+$8g7 z?r@@8&f&Fq2k$V->KAUOM-?-kF(R)y0#D{%rH3(8X9aRGESqa4O2w0CR&_%ReuliH znPU?pxK%CqYOr6E=b;Ck=(4bE=ruBfD%LOUfh!S*kgE|9b;q(Zp}tO3$2sk>hi9=F z#$%>yNVx6WvxYN+{RQg5`KX}F%$ZLn6fM)%ibvke@Q0v9)^GL#od>hs-auR_(x!oh zM!b1vR>+v};kKSWS^4nVKHqOvVAJV6_FL#s*~vUg^gu!799L*e#Y18o<0MwYU6C&X zUP?d!JH?+@b_%||XQNcsE35ddvBK0f6O5|wANzH~DF2@Herig``6x1x_Qv zV6!0|UJSf+YTVhsv>4kS=$os3mp#`mCr|>d`!csztRNYdPzM+j`!%N74^tN^9yAwK zRw_kB6`gh$y13iW*kH5-N-D#Lqu&G|gliJBHE2&W%^fCSvPk zDD83_F-9VaC+iR2#|{vy8rgxlB=GbAe2Fd93z+eE>m9q4DOz9Sr*av7V2}o8%po& zddzmq%yn934?D{nao|;s*zdk0YyiW3Wrs^uE6tv6E>)Y!W&cY*gsV2dQwj7EbL19D zIQ~vjDX@ET=pxsAH3y};YL>UQ$7}4dtLwFVA&MmX)zE_?dxW)&!$))4@pLRe5hLK8 zz_^~;7i)8o zts8G3i=^tvDUMa_szR$!g{PUIGJ5$a$W_jFuhG}l2EDAtG6Z!O2$%1+4Mz`K@R>Ir zOX;D4n&IC%D;imuEV&DElgMF_tR+qsV%pju+2b>u@X@PXMJJIqj}Yob zj>lWBc-Axixo5@jZic{lsEh7#hZ8%q^j zX`+>+;iF#ZEnw*HC0Bj~tG~i`FOEoz?13`9;7>SG0N?59ndS+tnt&>429DZp^8T+> zZ>(-{LcFe@zg39sG5uOiQ!Cow1b|5gu$u(PeF~D}Zsn-uKf%-a6+bh9D^Iq!j3c|au-{_IC=u00tX z&J|L+AK;SUp86Rz0J< zsfyE+wzXLV@CF|cI5p_#ZK~(jIl2NMPozb2R5Of&R0A|$Y2iikOk4CF28s_GVKMLm z|KTG3WVeQr*PMmE6jEV0|DmmByhf3FN!03s+BEKJ+^iKigTbRSwJN0?#(-yARfp^_MqyjM^f*>r+JWjB^O+S#;bb~GQQi@5V;HnAi7YM@7ZB1+}RJA2<#!)Cm-1pQr?niZaZ4;tnZv#`sFvm_>i; z#AQ3MMNFFYJnd?5NcYt#qbi!$wEt3*hkx64Osl5HC?l?__w($UDFz+U4I;(k)&;W@ zIwD(8F^$$a5f_YhFeAPJXi;@i4!ACX3g(WCEXbD|3dP7RdZY{mAYa*mt9k1}4QesJ ztQ|l3WoT^Kb-TH6P^b@fQciEcOPO$x1l8K0rZ{Ox);%}B;3}=-iv71UAK~CEUzwHWN^42%H z)&7CA6Fg?|GtCH4`JVx`<1;7)3t+%o1OISdY>R%yYPNc$aB%8~k~2!-U1H|h>| z!NGYHi5e!#&V>ee$!9(*Y!uz~QRIvDzjT#;4x)%H2(Xwt%T*|~F1TWQV=4Lv&e80O zhgsij?yMl52@f(O00(f{5=>LU`hD_Z<@_Z8iXZiQM?shQJyBgwE5jO*MSU+?ra($Z zp92dVjo_}eq3+}wg`dEl0Ry2l?>543uWog)4_<%Nbb0b6_9Y6~AyT_X5M+$*r%Er%ngXU{gu!%$ESG&{ux%%>xECgaB7Hn#x5_=wYr0igH&SU0K*#SY~4TCWm%yXzP1XUj; z4AokE)fdzdf(gx3lI^goVTm9YSwRm)Lj*30^60+VpV_t8i?4QmteIH)F)P5=TnRs4 zVLXB{e!Tebu9t!lVW;%M6Tul{NjYD(Ibe8M!8ang52qqSqF1uyvoT(n@jAr!Uu>Rw z5baa6;iX`^khKSjIspEN{3CF}Wot6AZRcob1aPvdwI^CU4WeNJ%Br$jOl`i%$1i3M ziCyD!cVOWhNe#&$0vk8%JAB!|f|~7pwIk3(YFhFItoLdQ(7v3){!cTJN@h{Rc8!MM z6Aw6^E)5DblSVh4Xm>+!YTvnUZmXvzjM3uy;i@N|+;eThX?Xl?0uxSDyi&8l72E`@ zqvL%a!Sl0Dy@xP>kqMYH3l8mp7r2dedJB#cY;=q7?r@AuV zT{jqVXI(60`~(Cup&N#12p!I&JFBha%|76j-VEB-X=C#w*Qv_4l27I0qAp%+*FU*p&k2 z+;Vv8dFbj?Hs#vngrsebXK&`U!OL8y+)J$HKr$!&1mcB|E=kz~R#wn4kzATiy1-V@ zncH2$R#ZC;I4VDFMn6lnY2V0ISAhh%v=ajPrUVnafe^72+X-%X1i4gl_rCA84 z{ADAvne9-^Td^H!28ppsW~#a{r{_#LdrQv#P%!J=#jZ$CZRrDH`E$*1pFvf(s~s@T z`Ht;i!wG-&CMxwINo|CkxP(N&HyF|KX!68NrMV;)DoZ7 z5>8tPy0;X3WSh}#l#bHA(1wHdDL6!ef;lt^59HBE)t3t=b4yDr-r+PFdrF?Bd-gHf zicZVUnnD<-b4kg(UtjO2{S$mrU2zQXm!TMQjkbKjOS;jvOY=KuU`K;^gO7dTWS#is zRwwYMBHRyDaW?vRifplak=Dz~OGo14=1{NUi=z0!`PoWZ5lL^ z+-0-qB)SU}PcGp5sHo_B^C=(fkf#h%Mkc21;G`u2BQq^KvK*08$CFO65vP7|Myozk!ACPwiw5gnf7@ z6{U#rH5(5d1nZMNVpZ}O(LgY^cCG;`fgAFL4LO%JBxotrt}Tbh)!J1)J^y0ih*^3i zmVp)@K&L%2LI}C<_f1b10V=_SVi6Oo(N#Q@jHMEUif-z4cTmpaQ5u#5QybPCWMH_M zNS7;_D+2=_roNv7fy$1W#)v-bTu8;QG73gs&|56^Q3%~;xfRVX9F<6rrLH^i%1ZK; z!IGMTJMLp5$F%VxmX@fhLMSi z!h*9VAFj5>1ou3&Q8-Z;7>xb1h?Z8m%iga)QboM@mCK!gk4Y#RmisS}53Gcn&0!TJ z{n!!Qa3URchT;iE%8orHiE0Vi=AyC4p4^mr(US}<`UwetG&IcHQmlB`8C^Lm{anx4 z(#LWb9)F2VY|?~~&;9F5zIiaFXI1s}@vl8{=_Cz5Q}^!k6k<-x!Fyib&h})SnI4P+ zveOi;_Ku>#RFZ^L-;x)G48riw@fhxZ=S}ATIH?iKMrqjJX#4f_F$FXGqUM^wwEmp& zS2(T#$O+YA_t=h0dV9@vKKdU-76KPG_a0i%THvV^TpOBxObek3FOmWp?S|}U=@m7t z^Y;yd@Mi-PNnCRe2*cGtVGstNnXX zBG|x)AG)tnQo&K$vNH?Kr#ZhE@H-eea#It=45N(kH2MK$`Kn_z!uRE;$=xKs+l%R} zFJ4zUGmDa~vlw7K=+2~_&ZN_@?nuhKfRxSmUuZNmiFQQgzbsMYNGOsb~Ha&Gfi z+kvPawoY0wlbIUHH^21@oh!NF_6wYZKn?d3)Wz6|)>wfsA+{R+?f3K8kv38GdEu~3 zq^ACp+&p;u-OM#|#XoQepm1!^#!Sj`U4hz>K15wpxv;K2P*O>*C^4M!v@qCib)aV&RZ}TfEMts#oI<^}b?9R@2jp?u zLf*wAPS%bNV$Z%zyh<%NS{`~}7~4tJ6pVQp{XgWc=KqkppW|QqVT5M@J>)nV?OXmr zG|d}!o_}-ZD-Msg%44O>GeE{iPGbj3CR(@AhQyc4{-&P<}@D2sJ@$`9gq*jf^GgQSpUEk z8{hCS$hzynOv2^PZ<$}qj4tqQ`a^TjKPa>DimxE;lfIHEjp3`GdEE&GQr&-moy+(q@x0`e>0}oh3-_g=i|St zgr3q+^uuDKMt0k4kUu9* zw)Tuh6Y-ko0=8;CE_Rwc4`XjmacuMgU4jJzS5k%FTb2{E=?iWKc#Tdo({Qa}2O zlo#mNGyk+siI=jk>AEG=@E_EI@&Ph5lr(3#B0;{PhQdynr4L!%R@X7F6VC1jU%{c* zVb$g>shW88>Yup}**acA;FwNXnF}?}FvSa_H0S(r9~9o4Y_7c1U_RUbmMSNLA-s}l zTQ>qo;oK_bAn@5QzA)`%xsk~4cd}bT1wt6bo2F7g3)&5X5*qnfF)}z;XE|ujL!WE` zQ)+kc+Wb7Z`6~w7#P9F1-qSGbUj0rZk~n5((woxF#&-_0)e}|6*~glXgv7k3#lAx7 zG=j_)PnL2EB*<2F2dn(RI~bSn9K^RCQwXL-@nuj;jVGEFobEc+!voVK#JD_odcCR0 zeDnJwVL{hnOBl6^Hi?tF zkqI&IWD##aX9idR#t|=c|G)`guI}^u1wHC~yQ7S_~t~> z+~N3&{BP@FS7=I=kL9V6P^H;mvKrdl1ZHuJ4F~zQx_b}P#9yCpb6<|MM8lrkIWBq6 zH%^iLriD39{bY~IDTbic z-4%<#KWe;(JR$r8cj*uNBiri2|K2Z<#q;A#iCip)pFC|o4cm`OkJ!fLGncLGjW@Q7 zw2N$?)P0KobW!Zf)`+O2Ox={TvZxto z_7~%pjbO~x3I4Z#D^9R=rP&%C@=FdqP?nOr8YV24>)YZn<={_v*0?2k&oTb>KUGnd zlS51g;RPUqlEM`+ta=CL1Mr!y(^ z2@`7aazti0C&8eD+sK6MFr9w+auz*#pN0FM0*uo;#bBS4VG!2LFeD+}ecW!l_*!!Eo&TjX6@AWV8pOg04CcnalwdUJn(f|FT z@70ulkN+a9SjqphSVAY&2#t5+g*`Vg*XsWiz5P1>!srKm9J!$w{`)vr!P6%VoXj6x zwDWqjr+AABg}wW4*wgc#lmGX0ZO;~KaD(~p{Q)fu{{OvL zkU@NZ=?AMAe`nI2|5gls(_-n0DsagiA0y9Ryv>BJ*hVo!IUc*EoWntY3^w5Brzy*}pK!TjeBka9o4HbrBk$2V3J{KY&!1yOMiz!I!3p7 zKlcN_JN9^uH(!k;0}HUmK7wE}m9`ZusoNhYu|9Ui$WWSwzq6OAZYtV;TYY+iE%DX! zDbWAT4>oUm%{~9=K79dAHuP^Ru&!l%Cuj;?lm2)9*r$F@``?0uOWMJnsnra)-xJHx z#bweG2K1=ztpV?R-g)w$Yc|aCa!FAKcYQ#UMIT*` zS?3Kv*Qe^6)@D18L@!!sRB#&X$sn|k}T(@sdDr-M`U8|K{Y^V`V@Y1;C zbkncIL$LT0FIlPYiq&Jh_$XEu1=JtihYv=7ShM=J*UUpi0(7PZdeqrqS_?BL#&T7A zxY=64{V12gfauzY-;(V`k4|)Y>pD}`@4V*@oczWmFb#vLVu4&d^!tpiN!Ft&rIxc8 z+PTZqL9F++j$}DbdqwOANg1r&S$4uuR>e~fs$q*6hn8@S+ny)Uun|V^hxT5RMt@l` z5KY7=blfiSvTDSg8R#sEbJvE9V&<4g^qridH)fuQ>^kMU!S-~?_mR~Z;XtBuT63id zB5!%gG}134?}C_nn&R6oY22eChp5B28TaWq`3lC2v1U1vh>A2&@t0d(MW^eXe3e4A zC8x?#OE1o3?`iInl)UtIyNf&%#%A^gA2f@2SBd5FjldM%~<7o?@- zNsQ5cSYx82gM({dNB9%Av9^){)&%LpD}SAf1kP+CuUdGM5Bou1>{#Hpa>~Li$v>@8 z_eA?PhZwj_2%|IrMZX&8stwkb2w(sX5(~WQj(ADtn9NDMrrpZf4N%mm1(Rs!pQEG<1u;RXN8lk2(2_;13|mWRCLv!pyQj4YUW&7{dpuIpFT++v4x2te;KSZrt?%rxZH2lLZq9KGCWmZ&ib!aP_B9LT_!0S=xlX?07+ z9v7P`yeJQJ;sfMEyo1`Udna!?Z2z<=(4jj6Z8KGr+zh`RhSBZWk-^9CSBVY5v260S z%*ewU%_Ml#?!_SB&U`NpvfE_S#J{SvO@{6ax7Q%96&7%rQl|e8T$H8{hr}3I|2MJP zVIs8WClGDDY6q>76KyllJ7pS0O9nbeDo+9HQ+++x0ZBf1>SOa^CU>v)7OqaEDt&H3RrZs z`KYyh_(ZxIW$O5-fPxV|Zao;&I4FvsucbV5XPEaxdB6qD6sk{ZRJqfq!D&|(PQ0&i zz-47vskX~~%HM+?nyP7Pt>IYk@q7HaF);;~JbRR< zu47=%nQd=mp}Y7pJ%`f0)MLJRCHS$>u9LRQMalLX2sv=+)Ar~$1%cIO*AVwEK= zB-dy*UCf`F=BYd1w}7+Z1ZjD9trBlOam8xId<_=FNqoL2)mKlK7^x^BCY2!3$MBRN zBc>M_T_Sx>;*{<++%d6E3Ao^iM0X`#GW+Zm5)$r|qR#@#EkHF^N5?-d1dzRsCb?-6e6_6>dyA*(YV5Z+){L&9uh($m*qXml}bbGxlY> zzgqS5N|^119`=SI)A_YZzP+C{Jp7#E7k$oo3I->qTv$y7!PQN^JwOsh@8v@@F^K(0 zSbIyN6cOTw$caI8@8C+WxoPeUM?m7V!sBa7h_pb3FP!V=tw5yFb8!9`XoNZ)o)zz- zD~{{{+I{F99Zv&L=;*4yW_yK?_C$b+xbx4EyX)ULme9NbK-8Diyo3Viv;j-bO^vo- zT*JB^nd>(M?DC4GV|PA>M255X9$TB{8L_+{5Yx^1&~XR`IV??x9H-}-%Rk+h9X06f z-mA-^fGcCfOdP@GQ3#@r%AcHnC4gveBJ8Od`UUDRGs{tdHfws z#O%3SwZzN-q?JR2X_wD(4c>jbuMR%5rs2jy3&Tf$w}}=7myQH*)U2dU6!N6_=p#$K zKv0v@oDNUb9ECpWSlp$RuQXa=?B#4JUoe(u?ya|72Z|;Am#GgWMS1Uz6{>c;@ zM`xaAOr<<4eR};UdfbsMLq*=UNCB_tRs{&+>8B;N&MQXzl>DY#9MhJbW>hvzik-{)=}$}9JwdhH$$TJx=8!(QZV;5k zc>p`gSw9(Pn#Qy;U>uRv2jYM-=@DsVE^mv}-W<>+a7cJ;-;j7RI${}a>1n5A@s%ioM|N{vIO6fob5_4 zpL3l03^veyZMOv>$*KjGLJ0nv52!_hMnk{th3%R-e_bY_X5_L!n5zoYTi{yi`C07Y z0c5EH*#<2myQS4-T46Ybp8+QbBxpGi9lAOArRICoB^Ev%zZ$rw?pr#F?88UxUvdeV z%g6N(#Da|U$7WWC>+M-Jf$0(@il~!~eYC8qIR*_Y4KLdE;gNV>>Uy}JS`XB;_MP*b zI4W}&T%L9IG8V8_>Kn$ICqOCFoe@*iIWclu_T5~_0u%M77}ivEJ)AFqd5)eh1s-=z`{xktEsWArj zDu4qT=|AMZ%{!Z(9e>Z<{^|R<_2+B8cl>$(_xbUEreSfb|8A>)7eA-|+@I$if1ZE* zXa8~4)cem%uBE>@weVMK_~%`jb!V2+fMF6>UVqkKtNye2e};zt4AbkMEdR5S{||6) zLv#IIyRcn(e*eBV|L%VGpJ7vd#s}+X{~7N8Q%l`@+WuZ(eaYYJ-}2{uus-E&nI;&&hsj{wJIBpXC1u|7R$!-1V&T`0qvaZ}u1d zUH{v@cfaMo=N~_R+eTKku6C NPYa@$vH$-~E&wRdCt?5q literal 0 HcmV?d00001 diff --git a/examples/ad_manager/v202008/creative_service/create_creatives.py b/examples/ad_manager/v202008/creative_service/create_creatives.py index db8b5bc2..6f3d783e 100755 --- a/examples/ad_manager/v202008/creative_service/create_creatives.py +++ b/examples/ad_manager/v202008/creative_service/create_creatives.py @@ -47,7 +47,7 @@ def main(client, advertiser_id): 'medium_rectangle.jpg'), 'r') as image: image_data = image.read() - for _ in xrange(5): + for _ in range(5): # Create creative size. size = { 'width': '300', diff --git a/examples/ad_manager/v202008/label_service/create_labels.py b/examples/ad_manager/v202008/label_service/create_labels.py index e6fab393..bde7b3b4 100755 --- a/examples/ad_manager/v202008/label_service/create_labels.py +++ b/examples/ad_manager/v202008/label_service/create_labels.py @@ -33,7 +33,7 @@ def main(client): # Create label objects. labels = [] - for _ in xrange(5): + for _ in range(5): label = { 'name': 'Label #%s' % uuid.uuid4(), 'isActive': 'true', diff --git a/examples/ad_manager/v202008/line_item_service/create_line_items.py b/examples/ad_manager/v202008/line_item_service/create_line_items.py index e8bf2ade..06429da6 100755 --- a/examples/ad_manager/v202008/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202008/line_item_service/create_line_items.py @@ -44,7 +44,7 @@ def main(client, order_id, targeted_placement_ids): # Create line item objects. line_items = [] - for _ in xrange(5): + for _ in range(5): line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, @@ -163,4 +163,3 @@ def main(client, order_id, targeted_placement_ids): # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS) - diff --git a/examples/ad_manager/v202008/order_service/create_orders.py b/examples/ad_manager/v202008/order_service/create_orders.py index b04c43b2..7b81bcd0 100755 --- a/examples/ad_manager/v202008/order_service/create_orders.py +++ b/examples/ad_manager/v202008/order_service/create_orders.py @@ -36,7 +36,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Create order objects. orders = [] - for _ in xrange(5): + for _ in range(5): order = { 'name': 'Order #%s' % uuid.uuid4(), 'advertiserId': company_id, diff --git a/examples/ad_manager/v202008/team_service/create_teams.py b/examples/ad_manager/v202008/team_service/create_teams.py index a878564a..da35bc62 100755 --- a/examples/ad_manager/v202008/team_service/create_teams.py +++ b/examples/ad_manager/v202008/team_service/create_teams.py @@ -37,7 +37,7 @@ def main(client): # Create team objects. teams = [] - for _ in xrange(5): + for _ in range(5): team = { 'name': 'Team %s' % uuid.uuid4(), 'hasAllCompanies': 'false', diff --git a/examples/ad_manager/v202011/creative_service/create_creatives.py b/examples/ad_manager/v202011/creative_service/create_creatives.py index 9837ce54..ffdab85b 100755 --- a/examples/ad_manager/v202011/creative_service/create_creatives.py +++ b/examples/ad_manager/v202011/creative_service/create_creatives.py @@ -43,11 +43,13 @@ def main(client, advertiser_id): # Create creative objects. creatives = [] - with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r') as image: + with open( + os.path.join( + os.path.split(__file__)[0], '..', '..', 'data', + 'medium_rectangle.jpg'), 'rb') as image: image_data = image.read() - for _ in xrange(5): + for _ in range(5): # Create creative size. size = { 'width': '300', @@ -80,9 +82,10 @@ def main(client, advertiser_id): # Display results. for creative in creatives: print('Image creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], - ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + 'created and can be previewed at %s.' % + (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v202011/label_service/create_labels.py b/examples/ad_manager/v202011/label_service/create_labels.py index c64a67bf..090bbcb0 100755 --- a/examples/ad_manager/v202011/label_service/create_labels.py +++ b/examples/ad_manager/v202011/label_service/create_labels.py @@ -33,7 +33,7 @@ def main(client): # Create label objects. labels = [] - for _ in xrange(5): + for _ in range(5): label = { 'name': 'Label #%s' % uuid.uuid4(), 'isActive': 'true', diff --git a/examples/ad_manager/v202011/line_item_service/create_line_items.py b/examples/ad_manager/v202011/line_item_service/create_line_items.py index 5ceb5d2c..106b813b 100755 --- a/examples/ad_manager/v202011/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202011/line_item_service/create_line_items.py @@ -44,7 +44,7 @@ def main(client, order_id, targeted_placement_ids): # Create line item objects. line_items = [] - for _ in xrange(5): + for _ in range(5): line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, @@ -163,4 +163,3 @@ def main(client, order_id, targeted_placement_ids): # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS) - diff --git a/examples/ad_manager/v202011/order_service/create_orders.py b/examples/ad_manager/v202011/order_service/create_orders.py index 3823ce8e..59308ae6 100755 --- a/examples/ad_manager/v202011/order_service/create_orders.py +++ b/examples/ad_manager/v202011/order_service/create_orders.py @@ -36,7 +36,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Create order objects. orders = [] - for _ in xrange(5): + for _ in range(5): order = { 'name': 'Order #%s' % uuid.uuid4(), 'advertiserId': company_id, diff --git a/examples/ad_manager/v202011/team_service/create_teams.py b/examples/ad_manager/v202011/team_service/create_teams.py index d9a7b44b..a64671d8 100755 --- a/examples/ad_manager/v202011/team_service/create_teams.py +++ b/examples/ad_manager/v202011/team_service/create_teams.py @@ -37,7 +37,7 @@ def main(client): # Create team objects. teams = [] - for _ in xrange(5): + for _ in range(5): team = { 'name': 'Team %s' % uuid.uuid4(), 'hasAllCompanies': 'false', diff --git a/examples/ad_manager/v202005/activity_group_service/__init__.py b/examples/ad_manager/v202102/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/activity_group_service/__init__.py rename to examples/ad_manager/v202102/activity_group_service/__init__.py diff --git a/examples/ad_manager/v202005/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202102/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v202005/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202102/activity_group_service/create_activity_groups.py index 58af7720..09ba3d27 100755 --- a/examples/ad_manager/v202005/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202102/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202005') + version='v202102') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v202005/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202102/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v202005/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202102/activity_group_service/get_active_activity_groups.py index 76b38b3f..51403956 100755 --- a/examples/ad_manager/v202005/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202102/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202005') + 'ActivityGroupService', version='v202102') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202005/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202102/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v202005/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202102/activity_group_service/get_all_activity_groups.py index fa1ebc26..c35c4ef4 100755 --- a/examples/ad_manager/v202005/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202102/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202005') + 'ActivityGroupService', version='v202102') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v202005/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202102/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v202005/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202102/activity_group_service/update_activity_groups.py index 5fa036de..74634d5c 100755 --- a/examples/ad_manager/v202005/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202102/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202005') + version='v202102') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/activity_service/__init__.py b/examples/ad_manager/v202102/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/activity_service/__init__.py rename to examples/ad_manager/v202102/activity_service/__init__.py diff --git a/examples/ad_manager/v202005/activity_service/create_activities.py b/examples/ad_manager/v202102/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v202005/activity_service/create_activities.py rename to examples/ad_manager/v202102/activity_service/create_activities.py index 4f05cbb8..603afbfa 100755 --- a/examples/ad_manager/v202005/activity_service/create_activities.py +++ b/examples/ad_manager/v202102/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202005') + activity_service = client.GetService('ActivityService', version='v202102') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v202005/activity_service/get_active_activities.py b/examples/ad_manager/v202102/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v202005/activity_service/get_active_activities.py rename to examples/ad_manager/v202102/activity_service/get_active_activities.py index 2a267907..84628643 100755 --- a/examples/ad_manager/v202005/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202102/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202005') + activity_service = client.GetService('ActivityService', version='v202102') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202005/activity_service/get_all_activities.py b/examples/ad_manager/v202102/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v202005/activity_service/get_all_activities.py rename to examples/ad_manager/v202102/activity_service/get_all_activities.py index 22987d07..b7b016bd 100755 --- a/examples/ad_manager/v202005/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202102/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202005') + activity_service = client.GetService('ActivityService', version='v202102') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v202005/activity_service/update_activities.py b/examples/ad_manager/v202102/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v202005/activity_service/update_activities.py rename to examples/ad_manager/v202102/activity_service/update_activities.py index 5ec7d998..7d021289 100755 --- a/examples/ad_manager/v202005/activity_service/update_activities.py +++ b/examples/ad_manager/v202102/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202005') + activity_service = client.GetService('ActivityService', version='v202102') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202102/adjustment_service/create_forecast_adjustments.py similarity index 99% rename from examples/ad_manager/v202005/adjustment_service/create_forecast_adjustments.py rename to examples/ad_manager/v202102/adjustment_service/create_forecast_adjustments.py index feb2ff41..87d06d3a 100755 --- a/examples/ad_manager/v202005/adjustment_service/create_forecast_adjustments.py +++ b/examples/ad_manager/v202102/adjustment_service/create_forecast_adjustments.py @@ -27,7 +27,7 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202005') + adjustment_service = client.GetService('AdjustmentService', version='v202102') # Create a new forecast adjustment for New Year's Day traffic. this_new_years = datetime.date(datetime.date.today().year, 1, 1) diff --git a/examples/ad_manager/v202005/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202102/adjustment_service/create_traffic_forecast_segments.py similarity index 98% rename from examples/ad_manager/v202005/adjustment_service/create_traffic_forecast_segments.py rename to examples/ad_manager/v202102/adjustment_service/create_traffic_forecast_segments.py index 1eefc102..755cb72c 100755 --- a/examples/ad_manager/v202005/adjustment_service/create_traffic_forecast_segments.py +++ b/examples/ad_manager/v202102/adjustment_service/create_traffic_forecast_segments.py @@ -25,8 +25,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v202005') - network_service = client.GetService('NetworkService', version='v202005') + adjustment_service = client.GetService('AdjustmentService', version='v202102') + network_service = client.GetService('NetworkService', version='v202102') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202005/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202102/adjustment_service/get_all_forecast_adjustments.py similarity index 95% rename from examples/ad_manager/v202005/adjustment_service/get_all_forecast_adjustments.py rename to examples/ad_manager/v202102/adjustment_service/get_all_forecast_adjustments.py index 565f103a..a3dfef10 100755 --- a/examples/ad_manager/v202005/adjustment_service/get_all_forecast_adjustments.py +++ b/examples/ad_manager/v202102/adjustment_service/get_all_forecast_adjustments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202005') + adjustment_service = client.GetService('AdjustmentService', version='v202102') # Create a statement to get all forecast adjustments. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small number of forecast adjustments at a time, paging # through until all forecast adjustments have been retrieved. diff --git a/examples/ad_manager/v202005/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202102/adjustment_service/get_all_traffic_forecast_segments.py similarity index 95% rename from examples/ad_manager/v202005/adjustment_service/get_all_traffic_forecast_segments.py rename to examples/ad_manager/v202102/adjustment_service/get_all_traffic_forecast_segments.py index aa6d620f..248b2c47 100755 --- a/examples/ad_manager/v202005/adjustment_service/get_all_traffic_forecast_segments.py +++ b/examples/ad_manager/v202102/adjustment_service/get_all_traffic_forecast_segments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202005') + adjustment_service = client.GetService('AdjustmentService', version='v202102') # Create a statement to get all traffic forecast segments. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small number of segments at a time, paging through until all # segments have been retrieved. diff --git a/examples/ad_manager/v202005/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202102/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py similarity index 96% rename from examples/ad_manager/v202005/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py rename to examples/ad_manager/v202102/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py index 8f2a2e37..f8bf7926 100755 --- a/examples/ad_manager/v202005/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py +++ b/examples/ad_manager/v202102/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -24,11 +24,11 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202005') + adjustment_service = client.GetService('AdjustmentService', version='v202102') # Create a statement to get forecast adjustments for a given traffic forecast # segment id. - statement = ad_manager.StatementBuilder(version='v202005').Where( + statement = ad_manager.StatementBuilder(version='v202102').Where( 'trafficForecastSegmentId = :segmentId').WithBindVariable( 'segmentId', traffic_forecast_segment_id) diff --git a/examples/ad_manager/v202005/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202102/adjustment_service/update_forecast_adjustments.py similarity index 96% rename from examples/ad_manager/v202005/adjustment_service/update_forecast_adjustments.py rename to examples/ad_manager/v202102/adjustment_service/update_forecast_adjustments.py index a33615ce..5b834140 100755 --- a/examples/ad_manager/v202005/adjustment_service/update_forecast_adjustments.py +++ b/examples/ad_manager/v202102/adjustment_service/update_forecast_adjustments.py @@ -24,12 +24,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202005') + adjustment_service = client.GetService('AdjustmentService', version='v202102') # Create a statement to select a single forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v202005').Where('id = :id').WithBindVariable( + version='v202102').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast adjustment. diff --git a/examples/ad_manager/v202005/audience_segment_service/__init__.py b/examples/ad_manager/v202102/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/audience_segment_service/__init__.py rename to examples/ad_manager/v202102/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v202005/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202102/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v202005/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202102/audience_segment_service/create_audience_segments.py index c22fdfa6..443dd4b9 100755 --- a/examples/ad_manager/v202005/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202102/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202005') - network_service = client.GetService('NetworkService', version='v202005') + 'AudienceSegmentService', version='v202102') + network_service = client.GetService('NetworkService', version='v202102') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v202005/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202102/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v202005/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202102/audience_segment_service/get_all_audience_segments.py index 85ee110c..db2c179e 100755 --- a/examples/ad_manager/v202005/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202102/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202005') + 'AudienceSegmentService', version='v202102') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v202005/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202102/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v202005/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202102/audience_segment_service/get_first_party_audience_segments.py index e4a0141d..b2853ad9 100755 --- a/examples/ad_manager/v202005/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202102/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202005') + 'AudienceSegmentService', version='v202102') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v202005/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202102/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v202005/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202102/audience_segment_service/populate_first_party_audience_segments.py index 8e3f5dab..b7700b59 100755 --- a/examples/ad_manager/v202005/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202102/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202005') + 'AudienceSegmentService', version='v202102') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202005/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202102/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v202005/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202102/audience_segment_service/update_audience_segments.py index 32d11273..c03663c8 100755 --- a/examples/ad_manager/v202005/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202102/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202005') + 'AudienceSegmentService', version='v202102') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202005/cdn_configuration_service/__init__.py b/examples/ad_manager/v202102/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202102/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v202005/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202102/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v202005/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202102/cdn_configuration_service/create_cdn_configurations.py index d9b8d60c..fb3c607d 100755 --- a/examples/ad_manager/v202005/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202102/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202005') + version='v202102') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v202005/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202102/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v202005/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202102/cdn_configuration_service/get_all_cdn_configurations.py index 62c1de11..f9054e05 100755 --- a/examples/ad_manager/v202005/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202102/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202005') + version='v202102') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202005/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202102/cms_metadata_service/activate_cms_metadata_values.py similarity index 95% rename from examples/ad_manager/v202005/cms_metadata_service/activate_cms_metadata_values.py rename to examples/ad_manager/v202102/cms_metadata_service/activate_cms_metadata_values.py index 3a39de52..917692ac 100755 --- a/examples/ad_manager/v202005/cms_metadata_service/activate_cms_metadata_values.py +++ b/examples/ad_manager/v202102/cms_metadata_service/activate_cms_metadata_values.py @@ -28,10 +28,10 @@ def main(client, cms_metadata_key_id): # Initialize appropriate service. cms_metadata_service = client.GetService('CmsMetadataService', - version='v202005') + version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('cmsKeyId = :cmsKeyId AND status = :status') .WithBindVariable('status', 'INACTIVE') .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) diff --git a/examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_keys.py index 59f2ecda..72b7b92b 100755 --- a/examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202005') + 'CmsMetadataService', version='v202102') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_values.py index b68a1e21..d5e4a581 100755 --- a/examples/ad_manager/v202005/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202005') + 'CmsMetadataService', version='v202102') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v202005/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202102/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v202005/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202102/cms_metadata_service/get_cms_metadata_values_for_key.py index 01c8d5b6..7b65114d 100755 --- a/examples/ad_manager/v202005/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202102/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202005') + 'CmsMetadataService', version='v202102') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v202005').Where( + ad_manager.StatementBuilder(version='v202102').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v202005/company_service/__init__.py b/examples/ad_manager/v202102/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/company_service/__init__.py rename to examples/ad_manager/v202102/company_service/__init__.py diff --git a/examples/ad_manager/v202005/company_service/create_companies.py b/examples/ad_manager/v202102/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v202005/company_service/create_companies.py rename to examples/ad_manager/v202102/company_service/create_companies.py index f037b1a2..f7c5da3c 100755 --- a/examples/ad_manager/v202005/company_service/create_companies.py +++ b/examples/ad_manager/v202102/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202005') + company_service = client.GetService('CompanyService', version='v202102') # Create company objects. companies = [ diff --git a/examples/ad_manager/v202005/company_service/get_advertisers.py b/examples/ad_manager/v202102/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v202005/company_service/get_advertisers.py rename to examples/ad_manager/v202102/company_service/get_advertisers.py index 622f19e9..f0db5881 100755 --- a/examples/ad_manager/v202005/company_service/get_advertisers.py +++ b/examples/ad_manager/v202102/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202005') + company_service = client.GetService('CompanyService', version='v202102') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v202005/company_service/get_all_companies.py b/examples/ad_manager/v202102/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v202005/company_service/get_all_companies.py rename to examples/ad_manager/v202102/company_service/get_all_companies.py index b51bee22..c83f56ca 100755 --- a/examples/ad_manager/v202005/company_service/get_all_companies.py +++ b/examples/ad_manager/v202102/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202005') + company_service = client.GetService('CompanyService', version='v202102') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v202005/company_service/update_companies.py b/examples/ad_manager/v202102/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v202005/company_service/update_companies.py rename to examples/ad_manager/v202102/company_service/update_companies.py index 702073d0..f94daa02 100755 --- a/examples/ad_manager/v202005/company_service/update_companies.py +++ b/examples/ad_manager/v202102/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202005') + company_service = client.GetService('CompanyService', version='v202102') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/contact_service/__init__.py b/examples/ad_manager/v202102/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/contact_service/__init__.py rename to examples/ad_manager/v202102/contact_service/__init__.py diff --git a/examples/ad_manager/v202005/contact_service/create_contacts.py b/examples/ad_manager/v202102/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v202005/contact_service/create_contacts.py rename to examples/ad_manager/v202102/contact_service/create_contacts.py index 4cf50790..431d79cd 100755 --- a/examples/ad_manager/v202005/contact_service/create_contacts.py +++ b/examples/ad_manager/v202102/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202005') + contact_service = client.GetService('ContactService', version='v202102') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v202005/contact_service/get_all_contacts.py b/examples/ad_manager/v202102/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v202005/contact_service/get_all_contacts.py rename to examples/ad_manager/v202102/contact_service/get_all_contacts.py index 6ec8000d..047cf34f 100755 --- a/examples/ad_manager/v202005/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202102/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202005') + contact_service = client.GetService('ContactService', version='v202102') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v202005/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202102/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v202005/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202102/contact_service/get_uninvited_contacts.py index a10568e4..49a44b78 100755 --- a/examples/ad_manager/v202005/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202102/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202005') + contact_service = client.GetService('ContactService', version='v202102') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v202005/contact_service/update_contacts.py b/examples/ad_manager/v202102/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v202005/contact_service/update_contacts.py rename to examples/ad_manager/v202102/contact_service/update_contacts.py index 6d4a5a0c..b8a49fc1 100755 --- a/examples/ad_manager/v202005/contact_service/update_contacts.py +++ b/examples/ad_manager/v202102/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202005') + contact_service = client.GetService('ContactService', version='v202102') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/content_service/__init__.py b/examples/ad_manager/v202102/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/content_service/__init__.py rename to examples/ad_manager/v202102/content_service/__init__.py diff --git a/examples/ad_manager/v202005/content_service/get_all_content.py b/examples/ad_manager/v202102/content_service/get_all_content.py similarity index 96% rename from examples/ad_manager/v202005/content_service/get_all_content.py rename to examples/ad_manager/v202102/content_service/get_all_content.py index cfc4c5ce..bed36eff 100755 --- a/examples/ad_manager/v202005/content_service/get_all_content.py +++ b/examples/ad_manager/v202102/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202005') + content_service = client.GetService('ContentService', version='v202102') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v202005/content_service/get_recently_modified_content.py b/examples/ad_manager/v202102/content_service/get_recently_modified_content.py similarity index 97% rename from examples/ad_manager/v202005/content_service/get_recently_modified_content.py rename to examples/ad_manager/v202102/content_service/get_recently_modified_content.py index a8089fa7..c352e8be 100755 --- a/examples/ad_manager/v202005/content_service/get_recently_modified_content.py +++ b/examples/ad_manager/v202102/content_service/get_recently_modified_content.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202005') + content_service = client.GetService('ContentService', version='v202102') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -35,7 +35,7 @@ def main(client): # lastModifiedDateTime. Changes to content bundle associations will update # the lastModifiedDateTime, but CMS metadata changes may not change the # lastModifiedDateTime. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202005/creative_service/__init__.py b/examples/ad_manager/v202102/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/creative_service/__init__.py rename to examples/ad_manager/v202102/creative_service/__init__.py diff --git a/examples/ad_manager/v202005/creative_service/copy_image_creatives.py b/examples/ad_manager/v202102/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v202005/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202102/creative_service/copy_image_creatives.py index b28e066a..7a2ae176 100755 --- a/examples/ad_manager/v202005/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202102/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202005') + creative_service = client.GetService('CreativeService', version='v202102') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v202005/creative_service/create_creative_from_template.py b/examples/ad_manager/v202102/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v202005/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202102/creative_service/create_creative_from_template.py index fe382bef..ba6cab0b 100755 --- a/examples/ad_manager/v202005/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202102/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202005') + creative_service = client.GetService('CreativeService', version='v202102') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v202005/creative_service/create_creatives.py b/examples/ad_manager/v202102/creative_service/create_creatives.py similarity index 87% rename from examples/ad_manager/v202005/creative_service/create_creatives.py rename to examples/ad_manager/v202102/creative_service/create_creatives.py index 5afefa7e..7c5f5f35 100755 --- a/examples/ad_manager/v202005/creative_service/create_creatives.py +++ b/examples/ad_manager/v202102/creative_service/create_creatives.py @@ -39,15 +39,17 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202005') + creative_service = client.GetService('CreativeService', version='v202102') # Create creative objects. creatives = [] - with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r') as image: + with open( + os.path.join( + os.path.split(__file__)[0], '..', '..', 'data', + 'medium_rectangle.jpg'), 'rb') as image: image_data = image.read() - for _ in xrange(5): + for _ in range(5): # Create creative size. size = { 'width': '300', @@ -80,9 +82,10 @@ def main(client, advertiser_id): # Display results. for creative in creatives: print('Image creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], - ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + 'created and can be previewed at %s.' % + (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v202005/creative_service/create_custom_creative.py b/examples/ad_manager/v202102/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v202005/creative_service/create_custom_creative.py rename to examples/ad_manager/v202102/creative_service/create_custom_creative.py index bbb9c17a..fcc30a97 100755 --- a/examples/ad_manager/v202005/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202102/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202005') + creative_service = client.GetService('CreativeService', version='v202102') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v202005/creative_service/create_native_creative.py b/examples/ad_manager/v202102/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v202005/creative_service/create_native_creative.py rename to examples/ad_manager/v202102/creative_service/create_native_creative.py index 34fad6f1..d0e9c983 100755 --- a/examples/ad_manager/v202005/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202102/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202005') + creative_service = client.GetService('CreativeService', version='v202102') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v202005/creative_service/get_all_creatives.py b/examples/ad_manager/v202102/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v202005/creative_service/get_all_creatives.py rename to examples/ad_manager/v202102/creative_service/get_all_creatives.py index 7f5c75e1..99ce12f3 100755 --- a/examples/ad_manager/v202005/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202102/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202005') + creative_service = client.GetService('CreativeService', version='v202102') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v202005/creative_service/get_image_creatives.py b/examples/ad_manager/v202102/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v202005/creative_service/get_image_creatives.py rename to examples/ad_manager/v202102/creative_service/get_image_creatives.py index 496f20be..2af60571 100755 --- a/examples/ad_manager/v202005/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202102/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202005') + creative_service = client.GetService('CreativeService', version='v202102') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v202005/creative_service/update_creatives.py b/examples/ad_manager/v202102/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v202005/creative_service/update_creatives.py rename to examples/ad_manager/v202102/creative_service/update_creatives.py index e1d64030..89731429 100755 --- a/examples/ad_manager/v202005/creative_service/update_creatives.py +++ b/examples/ad_manager/v202102/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202005') + creative_service = client.GetService('CreativeService', version='v202102') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v202005/creative_set_service/__init__.py b/examples/ad_manager/v202102/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/creative_set_service/__init__.py rename to examples/ad_manager/v202102/creative_set_service/__init__.py diff --git a/examples/ad_manager/v202005/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202102/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v202005/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202102/creative_set_service/associate_creative_set_to_line_item.py index f3cde302..c31a1c5c 100755 --- a/examples/ad_manager/v202005/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202102/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202005') + 'LineItemCreativeAssociationService', version='v202102') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v202005/creative_set_service/create_creative_set.py b/examples/ad_manager/v202102/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v202005/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202102/creative_set_service/create_creative_set.py index bc434ca7..331f7745 100755 --- a/examples/ad_manager/v202005/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202102/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202005') + version='v202102') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v202005/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202102/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v202005/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202102/creative_set_service/get_all_creative_sets.py index 7f44dd44..7ae12a0c 100755 --- a/examples/ad_manager/v202005/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202102/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202005') + 'CreativeSetService', version='v202102') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v202005/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202102/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v202005/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202102/creative_set_service/get_creative_sets_for_master_creative.py index 846c73a6..bec8439d 100755 --- a/examples/ad_manager/v202005/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202102/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202005') + 'CreativeSetService', version='v202102') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v202005/creative_set_service/update_creative_set.py b/examples/ad_manager/v202102/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v202005/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202102/creative_set_service/update_creative_set.py index cee4fb1a..5acea36d 100755 --- a/examples/ad_manager/v202005/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202102/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202005') + version='v202102') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v202005/creative_template_service/__init__.py b/examples/ad_manager/v202102/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/creative_template_service/__init__.py rename to examples/ad_manager/v202102/creative_template_service/__init__.py diff --git a/examples/ad_manager/v202005/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202102/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v202005/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202102/creative_template_service/get_all_creative_templates.py index 42a78767..3ff6f93d 100755 --- a/examples/ad_manager/v202005/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202102/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202005') + 'CreativeTemplateService', version='v202102') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v202005/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202102/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v202005/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202102/creative_template_service/get_system_defined_creative_templates.py index 2339158a..f3c8039b 100755 --- a/examples/ad_manager/v202005/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202102/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202005') + 'CreativeTemplateService', version='v202102') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v202005/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202102/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v202005/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202102/creative_wrapper_service/create_creative_wrappers.py index 51345e5d..aa697e2f 100755 --- a/examples/ad_manager/v202005/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202102/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202005') + version='v202102') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v202005/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202102/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v202005/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202102/creative_wrapper_service/deactivate_creative_wrapper.py index f8867c98..5b520d79 100755 --- a/examples/ad_manager/v202005/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202102/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202005') + version='v202102') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202005/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202102/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202005/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202102/creative_wrapper_service/get_active_creative_wrappers.py index d1971b0b..504a0e9d 100755 --- a/examples/ad_manager/v202005/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202102/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202005') + 'CreativeWrapperService', version='v202102') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202005/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202102/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202005/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202102/creative_wrapper_service/get_all_creative_wrappers.py index 77c72d51..f854bb08 100755 --- a/examples/ad_manager/v202005/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202102/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202005') + 'CreativeWrapperService', version='v202102') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v202005/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202102/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v202005/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202102/creative_wrapper_service/update_creative_wrappers.py index bc9c3714..8c832bac 100755 --- a/examples/ad_manager/v202005/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202102/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202005') + version='v202102') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v202005/custom_field_service/__init__.py b/examples/ad_manager/v202102/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/custom_field_service/__init__.py rename to examples/ad_manager/v202102/custom_field_service/__init__.py diff --git a/examples/ad_manager/v202005/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202102/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v202005/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202102/custom_field_service/create_custom_field_options.py index 4e73096e..8ae8e79a 100755 --- a/examples/ad_manager/v202005/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202102/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202005') + 'CustomFieldService', version='v202102') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v202005/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202102/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v202005/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202102/custom_field_service/create_custom_fields.py index e3b527db..6c0f7e46 100755 --- a/examples/ad_manager/v202005/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202102/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202005') + 'CustomFieldService', version='v202102') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v202005/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202102/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v202005/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202102/custom_field_service/deactivate_all_line_item_custom_fields.py index 99e56228..11b066ac 100755 --- a/examples/ad_manager/v202005/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202102/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202005') + 'CustomFieldService', version='v202102') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202005/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202102/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v202005/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202102/custom_field_service/get_all_custom_fields.py index 22686fa8..aab4b6e3 100755 --- a/examples/ad_manager/v202005/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202102/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202005') + 'CustomFieldService', version='v202102') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v202005/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202102/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v202005/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202102/custom_field_service/get_custom_fields_for_line_items.py index 18f7e287..106d63cb 100755 --- a/examples/ad_manager/v202005/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202102/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202005') + 'CustomFieldService', version='v202102') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v202005/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202102/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v202005/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202102/custom_field_service/set_line_item_custom_field_value.py index 45b35bfb..4fa4af7b 100755 --- a/examples/ad_manager/v202005/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202102/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v202005') + 'CustomFieldService', version='v202102') - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v202005') + custom_field_statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v202005') + ad_manager.StatementBuilder(version='v202102') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v202005') + line_item_statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v202005/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202102/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v202005/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202102/custom_field_service/update_custom_fields.py index aaff108d..a345d29d 100755 --- a/examples/ad_manager/v202005/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202102/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202005') + 'CustomFieldService', version='v202102') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v202005/custom_targeting_service/__init__.py b/examples/ad_manager/v202102/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/custom_targeting_service/__init__.py rename to examples/ad_manager/v202102/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v202005/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202102/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v202005/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202102/custom_targeting_service/create_custom_targeting_keys_and_values.py index 47395f32..e9a45ccf 100755 --- a/examples/ad_manager/v202005/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202102/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202005') + 'CustomTargetingService', version='v202102') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_keys.py index 400c6f28..93ba354e 100755 --- a/examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202005') + 'CustomTargetingService', version='v202102') - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v202005') + key_statement = (ad_manager.StatementBuilder(version='v202102') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py index a993179c..254ae78c 100755 --- a/examples/ad_manager/v202005/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202005') + 'CustomTargetingService', version='v202102') - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v202005') + value_statement = (ad_manager.StatementBuilder(version='v202102') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v202005/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202102/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202005/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202102/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index c4690079..bd3d6004 100755 --- a/examples/ad_manager/v202005/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202102/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202005') + 'CustomTargetingService', version='v202102') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v202005') + targeting_key_statement = ad_manager.StatementBuilder(version='v202102') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v202005/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202102/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202005/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202102/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 950e21ca..1d330368 100755 --- a/examples/ad_manager/v202005/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202102/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202005') + 'CustomTargetingService', version='v202102') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v202005') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202102') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_keys.py index ab0bfbed..a922535c 100755 --- a/examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202005') + 'CustomTargetingService', version='v202102') - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_values.py index 317aba4d..1e3de787 100755 --- a/examples/ad_manager/v202005/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202005') + 'CustomTargetingService', version='v202102') - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v202005/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202102/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v202005/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202102/forecast_service/get_availability_forecast.py index 62704749..000a6a38 100755 --- a/examples/ad_manager/v202005/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202102/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202005') - network_service = client.GetService('NetworkService', version='v202005') + forecast_service = client.GetService('ForecastService', version='v202102') + network_service = client.GetService('NetworkService', version='v202102') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202005/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202102/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v202005/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202102/forecast_service/get_availability_forecast_for_line_item.py index 11b42159..341ecaec 100755 --- a/examples/ad_manager/v202005/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202102/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202005') + forecast_service = client.GetService('ForecastService', version='v202102') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v202005/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202102/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v202005/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202102/forecast_service/get_delivery_forecast_for_line_items.py index 942e4309..3a5591c2 100755 --- a/examples/ad_manager/v202005/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202102/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202005') + forecast_service = client.GetService('ForecastService', version='v202102') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v202102/forecast_service/get_traffic_data.py b/examples/ad_manager/v202102/forecast_service/get_traffic_data.py new file mode 100755 index 00000000..929e0303 --- /dev/null +++ b/examples/ad_manager/v202102/forecast_service/get_traffic_data.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# +# Copyright 2020, Google LLC +# +# 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 the forecasted run-of-network traffic data.""" + + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v202102') + network_service = client.GetService('NetworkService', version='v202102') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + + # Create a start date that's 7 days in the past and an end date that's 7 days + # in the future. + today = datetime.date.today() + start_date = today - datetime.timedelta(days=7) + end_date = today + datetime.timedelta(days=7) + + # Create targeting. + targeting = { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + } + } + + # Request the traffic forecast data. + traffic_data = forecast_service.getTrafficData({ + 'targeting': targeting, + 'requestedDateRange': { + 'startDate': start_date, + 'endDate': end_date + } + }) + + # Display historical data. + historical_time_series = traffic_data['historicalTimeSeries'] + if historical_time_series is None: + print('No historical data to display.') + else: + historical_start_date, historical_end_date = GetDatesFromForecastTimeSeries( + historical_time_series) + + print('Historical Data:') + offset = 0 + current_date = historical_start_date + while current_date <= historical_end_date: + print('%s: %d' % (current_date.isoformat(), + historical_time_series['values'][offset])) + offset += 1 + current_date = historical_start_date + datetime.timedelta(days=offset) + + # Display forecasted data. + forecasted_time_series = traffic_data['forecastedTimeSeries'] + if forecasted_time_series is None: + print('No forecasted data to display.') + else: + forecasted_start_date, forecasted_end_date = GetDatesFromForecastTimeSeries( + forecasted_time_series) + + print('Forecasted Data:') + offset = 0 + current_date = forecasted_start_date + while current_date <= forecasted_end_date: + print('%s: %d' % (current_date.isoformat(), + forecasted_time_series['values'][offset])) + offset += 1 + current_date = forecasted_start_date + datetime.timedelta(days=offset) + + +def GetDatesFromForecastTimeSeries(time_series): + """Creates datetime.date objects from a forecast time series object. + + Args: + time_series: The forecast time series containing start and end date info. + + Returns: + A tuple of datetime.date objects, the first representing the start date and + the second representing the end date. + """ + date_range = time_series['timeSeriesDateRange'] + start_date = datetime.date( + date_range['startDate']['year'], + date_range['startDate']['month'], + date_range['startDate']['day'] + ) + end_date = datetime.date( + date_range['endDate']['year'], + date_range['endDate']['month'], + date_range['endDate']['day'] + ) + return start_date, end_date + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202005/inventory_service/__init__.py b/examples/ad_manager/v202102/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/inventory_service/__init__.py rename to examples/ad_manager/v202102/inventory_service/__init__.py diff --git a/examples/ad_manager/v202005/inventory_service/archive_ad_units.py b/examples/ad_manager/v202102/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v202005/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202102/inventory_service/archive_ad_units.py index 07969929..2ae06578 100755 --- a/examples/ad_manager/v202005/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202102/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202005') + inventory_service = client.GetService('InventoryService', version='v202102') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v202005/inventory_service/create_ad_units.py b/examples/ad_manager/v202102/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v202005/inventory_service/create_ad_units.py rename to examples/ad_manager/v202102/inventory_service/create_ad_units.py index 57b77b53..dda9f758 100755 --- a/examples/ad_manager/v202005/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202102/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202005') + inventory_service = client.GetService('InventoryService', version='v202102') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v202005/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202102/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v202005/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202102/inventory_service/get_ad_unit_hierarchy.py index 244c642b..a7e9c1b9 100755 --- a/examples/ad_manager/v202005/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202102/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202005') - inventory_service = client.GetService('InventoryService', version='v202005') + network_service = client.GetService('NetworkService', version='v202102') + inventory_service = client.GetService('InventoryService', version='v202102') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v202005/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202102/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v202005/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202102/inventory_service/get_all_ad_unit_sizes.py index 88efae50..221f37f4 100755 --- a/examples/ad_manager/v202005/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202102/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v202005') + 'InventoryService', version='v202102') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v202005/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202102/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v202005/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202102/inventory_service/get_all_ad_units.py index 986afa05..7845b201 100755 --- a/examples/ad_manager/v202005/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202102/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v202005') + ad_unit_service = client.GetService('InventoryService', version='v202102') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v202005/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202102/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v202005/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202102/inventory_service/get_top_level_ad_units.py index 423ec6a9..8a5278e4 100755 --- a/examples/ad_manager/v202005/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202102/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202005') - inventory_service = client.GetService('InventoryService', version='v202005') + network_service = client.GetService('NetworkService', version='v202102') + inventory_service = client.GetService('InventoryService', version='v202102') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v202005/inventory_service/update_ad_units.py b/examples/ad_manager/v202102/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v202005/inventory_service/update_ad_units.py rename to examples/ad_manager/v202102/inventory_service/update_ad_units.py index 31e2c40b..65f88555 100755 --- a/examples/ad_manager/v202005/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202102/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202005') + inventory_service = client.GetService('InventoryService', version='v202102') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v202005/label_service/__init__.py b/examples/ad_manager/v202102/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/label_service/__init__.py rename to examples/ad_manager/v202102/label_service/__init__.py diff --git a/examples/ad_manager/v202005/label_service/create_labels.py b/examples/ad_manager/v202102/label_service/create_labels.py similarity index 98% rename from examples/ad_manager/v202005/label_service/create_labels.py rename to examples/ad_manager/v202102/label_service/create_labels.py index 6a5c9059..882c1aca 100755 --- a/examples/ad_manager/v202005/label_service/create_labels.py +++ b/examples/ad_manager/v202102/label_service/create_labels.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202005') + label_service = client.GetService('LabelService', version='v202102') # Create label objects. labels = [] - for _ in xrange(5): + for _ in range(5): label = { 'name': 'Label #%s' % uuid.uuid4(), 'isActive': 'true', diff --git a/examples/ad_manager/v202005/label_service/deactivate_labels.py b/examples/ad_manager/v202102/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v202005/label_service/deactivate_labels.py rename to examples/ad_manager/v202102/label_service/deactivate_labels.py index a499516d..91365d05 100755 --- a/examples/ad_manager/v202005/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202102/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202005') + label_service = client.GetService('LabelService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202005/label_service/get_active_labels.py b/examples/ad_manager/v202102/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v202005/label_service/get_active_labels.py rename to examples/ad_manager/v202102/label_service/get_active_labels.py index ad7a9011..aeb381ef 100755 --- a/examples/ad_manager/v202005/label_service/get_active_labels.py +++ b/examples/ad_manager/v202102/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202005') + label_service = client.GetService('LabelService', version='v202102') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202005/label_service/get_all_labels.py b/examples/ad_manager/v202102/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v202005/label_service/get_all_labels.py rename to examples/ad_manager/v202102/label_service/get_all_labels.py index 3209f67d..cfc8ffaf 100755 --- a/examples/ad_manager/v202005/label_service/get_all_labels.py +++ b/examples/ad_manager/v202102/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202005') + label_service = client.GetService('LabelService', version='v202102') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v202005/label_service/update_labels.py b/examples/ad_manager/v202102/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v202005/label_service/update_labels.py rename to examples/ad_manager/v202102/label_service/update_labels.py index 3021898a..5cb2d189 100755 --- a/examples/ad_manager/v202005/label_service/update_labels.py +++ b/examples/ad_manager/v202102/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202005') + label_service = client.GetService('LabelService', version='v202102') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202005/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202102/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202102/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v202005/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202102/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v202005/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202102/line_item_creative_association_service/create_licas.py index 83ab4065..f93b964c 100755 --- a/examples/ad_manager/v202005/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202102/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202005') + 'LineItemCreativeAssociationService', version='v202102') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v202005/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202102/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v202005/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202102/line_item_creative_association_service/deactivate_licas.py index fcfc236f..3fb6fff7 100755 --- a/examples/ad_manager/v202005/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202102/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202005') + 'LineItemCreativeAssociationService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v202005/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202102/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v202005/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202102/line_item_creative_association_service/get_all_licas.py index f90b297d..228adaec 100755 --- a/examples/ad_manager/v202005/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202102/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202005') + 'LineItemCreativeAssociationService', version='v202102') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v202005/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202102/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v202005/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202102/line_item_creative_association_service/get_licas_for_line_item.py index 3db27e9d..b8870110 100755 --- a/examples/ad_manager/v202005/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202102/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202005') + 'LineItemCreativeAssociationService', version='v202102') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v202005/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202102/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v202005/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202102/line_item_creative_association_service/update_licas.py index df2686a0..3b1aa307 100755 --- a/examples/ad_manager/v202005/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202102/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202005') + 'LineItemCreativeAssociationService', version='v202102') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v202005/line_item_service/__init__.py b/examples/ad_manager/v202102/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/line_item_service/__init__.py rename to examples/ad_manager/v202102/line_item_service/__init__.py diff --git a/examples/ad_manager/v202005/line_item_service/activate_line_items.py b/examples/ad_manager/v202102/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v202005/line_item_service/activate_line_items.py rename to examples/ad_manager/v202102/line_item_service/activate_line_items.py index 9e3b70b5..f0acde2f 100755 --- a/examples/ad_manager/v202005/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202102/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202005/line_item_service/create_line_items.py b/examples/ad_manager/v202102/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v202005/line_item_service/create_line_items.py rename to examples/ad_manager/v202102/line_item_service/create_line_items.py index 7435773a..f4ea386f 100755 --- a/examples/ad_manager/v202005/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202102/line_item_service/create_line_items.py @@ -37,14 +37,14 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) # Create line item objects. line_items = [] - for _ in xrange(5): + for _ in range(5): line_item = { 'name': 'Line item #%s' % uuid.uuid4(), 'orderId': order_id, @@ -163,4 +163,3 @@ def main(client, order_id, targeted_placement_ids): # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, ORDER_ID, TARGETED_PLACEMENT_IDS) - diff --git a/examples/ad_manager/v202005/line_item_service/create_video_line_item.py b/examples/ad_manager/v202102/line_item_service/create_video_line_item.py similarity index 98% rename from examples/ad_manager/v202005/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202102/line_item_service/create_video_line_item.py index fcee045b..d020bdc2 100755 --- a/examples/ad_manager/v202005/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202102/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) @@ -100,6 +100,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, }], 'environmentType': 'VIDEO_PLAYER', 'companionDeliveryOption': 'OPTIONAL', + 'videoMaxDuration': 15000, 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'SPONSORSHIP', 'endDateTime': end_datetime, diff --git a/examples/ad_manager/v202005/line_item_service/get_all_line_items.py b/examples/ad_manager/v202102/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v202005/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202102/line_item_service/get_all_line_items.py index c33fb8ff..df2b0b0d 100755 --- a/examples/ad_manager/v202005/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202102/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v202005/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202102/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v202005/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202102/line_item_service/get_line_items_that_need_creatives.py index 04e0dc18..164774a6 100755 --- a/examples/ad_manager/v202005/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202102/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v202005/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202102/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v202005/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202102/line_item_service/get_recently_updated_line_items.py index de6b19b7..aa87e792 100755 --- a/examples/ad_manager/v202005/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202102/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202005/line_item_service/pause_line_items.py b/examples/ad_manager/v202102/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v202005/line_item_service/pause_line_items.py rename to examples/ad_manager/v202102/line_item_service/pause_line_items.py index 907315bd..a440c750 100755 --- a/examples/ad_manager/v202005/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202102/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v202005/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202102/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v202005/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202102/line_item_service/target_custom_criteria.py index b3cdc82b..249309f3 100755 --- a/examples/ad_manager/v202005/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202102/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/line_item_service/update_line_items.py b/examples/ad_manager/v202102/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v202005/line_item_service/update_line_items.py rename to examples/ad_manager/v202102/line_item_service/update_line_items.py index 25e25586..235858f0 100755 --- a/examples/ad_manager/v202005/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202102/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202005') + line_item_service = client.GetService('LineItemService', version='v202102') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v202005/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202102/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202005/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202102/live_stream_event_service/activate_live_stream_events.py index 0c44f099..7f5aa760 100755 --- a/examples/ad_manager/v202005/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202102/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202005') + 'LiveStreamEventService', version='v202102') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v202005/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202102/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v202005/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202102/live_stream_event_service/create_live_stream_events.py index f5cab8ca..43a44909 100755 --- a/examples/ad_manager/v202005/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202102/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v202005') + 'LiveStreamEventService', version='v202102') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v202005/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202102/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v202005/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202102/live_stream_event_service/get_all_live_stream_events.py index 62056234..bef3d72e 100755 --- a/examples/ad_manager/v202005/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202102/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202005') + 'LiveStreamEventService', version='v202102') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v202005/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202102/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v202005/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202102/live_stream_event_service/register_sessions_for_monitoring.py index 315e3685..057a7d1c 100755 --- a/examples/ad_manager/v202005/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202102/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202005') + 'LiveStreamEventService', version='v202102') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v202005/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202102/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202005/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202102/live_stream_event_service/update_live_stream_events.py index 16582d63..42eb415b 100755 --- a/examples/ad_manager/v202005/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202102/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v202005') + 'LiveStreamEventService', version='v202102') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v202005/native_style_service/__init__.py b/examples/ad_manager/v202102/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/native_style_service/__init__.py rename to examples/ad_manager/v202102/native_style_service/__init__.py diff --git a/examples/ad_manager/v202005/native_style_service/create_native_styles.py b/examples/ad_manager/v202102/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v202005/native_style_service/create_native_styles.py rename to examples/ad_manager/v202102/native_style_service/create_native_styles.py index 854251ea..9d271c5f 100755 --- a/examples/ad_manager/v202005/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202102/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202005') + version='v202102') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v202005/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202102/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v202005/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202102/native_style_service/get_all_native_styles.py index 1f7c99a7..cd7537f2 100755 --- a/examples/ad_manager/v202005/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202102/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202005') + version='v202102') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v202005/network_service/__init__.py b/examples/ad_manager/v202102/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/network_service/__init__.py rename to examples/ad_manager/v202102/network_service/__init__.py diff --git a/examples/ad_manager/v202005/network_service/get_all_networks.py b/examples/ad_manager/v202102/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v202005/network_service/get_all_networks.py rename to examples/ad_manager/v202102/network_service/get_all_networks.py index b17ea493..7e3e11d1 100755 --- a/examples/ad_manager/v202005/network_service/get_all_networks.py +++ b/examples/ad_manager/v202102/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202005') + network_service = client.GetService('NetworkService', version='v202102') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v202005/network_service/get_current_network.py b/examples/ad_manager/v202102/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v202005/network_service/get_current_network.py rename to examples/ad_manager/v202102/network_service/get_current_network.py index 6d456dc7..ff0f4df2 100755 --- a/examples/ad_manager/v202005/network_service/get_current_network.py +++ b/examples/ad_manager/v202102/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202005') + network_service = client.GetService('NetworkService', version='v202102') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202102/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202102/network_service/get_default_third_party_data_declaration.py new file mode 100755 index 00000000..5eacd62e --- /dev/null +++ b/examples/ad_manager/v202102/network_service/get_default_third_party_data_declaration.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2020, Google LLC +# +# 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 the network's default third party data declarations.""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v202102') + pql_service = client.GetService('PublisherQueryLanguageService', + version='v202102') + + # Fetch the default third party data declarations. + declarations = network_service.getDefaultThirdPartyDataDeclaration() + + # Display the results. + if declarations is None: + print('No default ad technology partners have been set on this network.') + elif (declarations['declarationType'] == 'NONE' or + not declarations['thirdPartyCompanyIds']): + print('This network has specified that there are no ad technology providers' + ' associated with its reservation creatives by default.') + else: + print('This network has specified %d ad technology provider(s) associated' + ' with its reservation creatives by default:' % + len(declarations['thirdPartyCompanyIds'])) + + # In this case, there are third party companies to be displayed, so fetch + # the company names from the Rich_Media_Ad_Company PQL table. + statement = (ad_manager.StatementBuilder(version='v202102') + .Select('Id, Name') + .From('Rich_Media_Ad_Company') + .Where('Id IN (:company_ids)') + .WithBindVariable('company_ids', + declarations['thirdPartyCompanyIds'])) + + while True: + response = pql_service.select(statement.ToStatement()) + if 'rows' in response and len(response['rows']): + for company in response['rows']: + print('Name: %s, id: %s' % (company['values'][1]['value'], + company['values'][0]['value'])) + statement.offset += statement.limit + else: + break + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202005/network_service/make_test_network.py b/examples/ad_manager/v202102/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v202005/network_service/make_test_network.py rename to examples/ad_manager/v202102/network_service/make_test_network.py index edccbad7..237c62a7 100755 --- a/examples/ad_manager/v202005/network_service/make_test_network.py +++ b/examples/ad_manager/v202102/network_service/make_test_network.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202005') + network_service = client.GetService('NetworkService', version='v202102') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v202005/order_service/__init__.py b/examples/ad_manager/v202102/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/order_service/__init__.py rename to examples/ad_manager/v202102/order_service/__init__.py diff --git a/examples/ad_manager/v202005/order_service/approve_orders.py b/examples/ad_manager/v202102/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v202005/order_service/approve_orders.py rename to examples/ad_manager/v202102/order_service/approve_orders.py index 2899a6a7..0bf11461 100755 --- a/examples/ad_manager/v202005/order_service/approve_orders.py +++ b/examples/ad_manager/v202102/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202005') + order_service = client.GetService('OrderService', version='v202102') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v202005/order_service/create_orders.py b/examples/ad_manager/v202102/order_service/create_orders.py similarity index 98% rename from examples/ad_manager/v202005/order_service/create_orders.py rename to examples/ad_manager/v202102/order_service/create_orders.py index 8cfe05d6..76167e49 100755 --- a/examples/ad_manager/v202005/order_service/create_orders.py +++ b/examples/ad_manager/v202102/order_service/create_orders.py @@ -32,11 +32,11 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202005') + order_service = client.GetService('OrderService', version='v202102') # Create order objects. orders = [] - for _ in xrange(5): + for _ in range(5): order = { 'name': 'Order #%s' % uuid.uuid4(), 'advertiserId': company_id, diff --git a/examples/ad_manager/v202005/order_service/get_all_orders.py b/examples/ad_manager/v202102/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v202005/order_service/get_all_orders.py rename to examples/ad_manager/v202102/order_service/get_all_orders.py index 79468aec..1324795e 100755 --- a/examples/ad_manager/v202005/order_service/get_all_orders.py +++ b/examples/ad_manager/v202102/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202005') + order_service = client.GetService('OrderService', version='v202102') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v202005/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202102/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v202005/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202102/order_service/get_orders_starting_soon.py index fac99686..0445563c 100755 --- a/examples/ad_manager/v202005/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202102/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202005') + order_service = client.GetService('OrderService', version='v202102') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v202005/order_service/update_orders.py b/examples/ad_manager/v202102/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v202005/order_service/update_orders.py rename to examples/ad_manager/v202102/order_service/update_orders.py index db565bfa..4468fda8 100755 --- a/examples/ad_manager/v202005/order_service/update_orders.py +++ b/examples/ad_manager/v202102/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202005') + order_service = client.GetService('OrderService', version='v202102') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202005/placement_service/create_placements.py b/examples/ad_manager/v202102/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v202005/placement_service/create_placements.py rename to examples/ad_manager/v202102/placement_service/create_placements.py index a7b8e5da..286ef21d 100755 --- a/examples/ad_manager/v202005/placement_service/create_placements.py +++ b/examples/ad_manager/v202102/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202005') - inventory_service = client.GetService('InventoryService', version='v202005') + placement_service = client.GetService('PlacementService', version='v202102') + inventory_service = client.GetService('InventoryService', version='v202102') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v202005/placement_service/deactivate_placements.py b/examples/ad_manager/v202102/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v202005/placement_service/deactivate_placements.py rename to examples/ad_manager/v202102/placement_service/deactivate_placements.py index 181da974..460ce8a6 100755 --- a/examples/ad_manager/v202005/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202102/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202005') + placement_service = client.GetService('PlacementService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/placement_service/get_active_placements.py b/examples/ad_manager/v202102/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v202005/placement_service/get_active_placements.py rename to examples/ad_manager/v202102/placement_service/get_active_placements.py index 81120f00..fb08b145 100755 --- a/examples/ad_manager/v202005/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202102/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202005') + placement_service = client.GetService('PlacementService', version='v202102') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202005/placement_service/get_all_placements.py b/examples/ad_manager/v202102/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v202005/placement_service/get_all_placements.py rename to examples/ad_manager/v202102/placement_service/get_all_placements.py index ff2efc6e..d04f4077 100755 --- a/examples/ad_manager/v202005/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202102/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202005') + placement_service = client.GetService('PlacementService', version='v202102') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v202005/placement_service/update_placements.py b/examples/ad_manager/v202102/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v202005/placement_service/update_placements.py rename to examples/ad_manager/v202102/placement_service/update_placements.py index 6cfa329e..f6ff7baf 100755 --- a/examples/ad_manager/v202005/placement_service/update_placements.py +++ b/examples/ad_manager/v202102/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202005') + placement_service = client.GetService('PlacementService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v202005/proposal_line_item_service/__init__.py b/examples/ad_manager/v202102/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202102/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v202005/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202102/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202005/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202102/proposal_line_item_service/archive_proposal_line_items.py index 237e8af7..7fb1a74c 100755 --- a/examples/ad_manager/v202005/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202102/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202005') + 'ProposalLineItemService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202102/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v202005/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202102/proposal_line_item_service/create_proposal_line_items.py index 43df0f78..fd9f3642 100755 --- a/examples/ad_manager/v202005/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202102/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202005') - network_service = client.GetService('NetworkService', version='v202005') + 'ProposalLineItemService', version='v202102') + network_service = client.GetService('NetworkService', version='v202102') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202005/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202102/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202005/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202102/proposal_line_item_service/get_all_proposal_line_items.py index be4d7225..97c14c89 100755 --- a/examples/ad_manager/v202005/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202102/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202005') + 'ProposalLineItemService', version='v202102') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v202005/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202102/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v202005/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202102/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 46d8ef00..66a1be9c 100755 --- a/examples/ad_manager/v202005/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202102/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202005') + 'ProposalLineItemService', version='v202102') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v202005/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202102/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202005/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202102/proposal_line_item_service/update_proposal_line_items.py index 3d07e2df..49d873a3 100755 --- a/examples/ad_manager/v202005/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202102/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202005') + 'ProposalLineItemService', version='v202102') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/proposal_service/__init__.py b/examples/ad_manager/v202102/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/proposal_service/__init__.py rename to examples/ad_manager/v202102/proposal_service/__init__.py diff --git a/examples/ad_manager/v202005/proposal_service/create_proposals.py b/examples/ad_manager/v202102/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v202005/proposal_service/create_proposals.py rename to examples/ad_manager/v202102/proposal_service/create_proposals.py index 00fd5452..3f6236db 100755 --- a/examples/ad_manager/v202005/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202102/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v202005') + proposal_service = client.GetService('ProposalService', version='v202102') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v202005/proposal_service/get_all_proposals.py b/examples/ad_manager/v202102/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v202005/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202102/proposal_service/get_all_proposals.py index 989d8068..59742b62 100755 --- a/examples/ad_manager/v202005/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202102/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202005') + proposal_service = client.GetService('ProposalService', version='v202102') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v202005/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202102/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v202005/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202102/proposal_service/get_marketplace_comments.py index 1ea5aad4..da5b058f 100755 --- a/examples/ad_manager/v202005/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202102/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v202005') + 'ProposalService', version='v202102') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v202005/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202102/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v202005/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202102/proposal_service/get_proposals_awaiting_seller_review.py index 777b5edd..9eafab36 100755 --- a/examples/ad_manager/v202005/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202102/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202005') + proposal_service = client.GetService('ProposalService', version='v202102') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v202005/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202102/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v202005/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202102/proposal_service/request_buyers_acceptance.py index 0f35c852..9432b527 100755 --- a/examples/ad_manager/v202005/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202102/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202005') + proposal_service = client.GetService('ProposalService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v202005/proposal_service/update_proposals.py b/examples/ad_manager/v202102/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v202005/proposal_service/update_proposals.py rename to examples/ad_manager/v202102/proposal_service/update_proposals.py index 1418ab6f..09be3294 100755 --- a/examples/ad_manager/v202005/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202102/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202005') + proposal_service = client.GetService('ProposalService', version='v202102') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v202005/publisher_query_language_service/__init__.py b/examples/ad_manager/v202102/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202102/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v202005/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202102/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v202005/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202102/publisher_query_language_service/fetch_match_tables.py index e9b998b6..54b6cc6b 100755 --- a/examples/ad_manager/v202005/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202102/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202005/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202102/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v202005/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202102/publisher_query_language_service/get_all_browsers.py index ef0f29d4..34a61d3e 100755 --- a/examples/ad_manager/v202005/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202102/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v202005/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202102/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v202005/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202102/publisher_query_language_service/get_all_programmatic_buyers.py index 85b09aa4..6f2b8796 100755 --- a/examples/ad_manager/v202005/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202102/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202005') + data_downloader = client.GetDataDownloader(version='v202102') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202005/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202102/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v202005/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202102/publisher_query_language_service/get_geo_targets.py index 29af9c63..02290768 100755 --- a/examples/ad_manager/v202005/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202102/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v202005/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202102/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v202005/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202102/publisher_query_language_service/get_line_items_named_like.py index fb531ce4..9ab992ac 100755 --- a/examples/ad_manager/v202005/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202102/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202102/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202102/publisher_query_language_service/get_mcm_earnings.py new file mode 100755 index 00000000..a4afe234 --- /dev/null +++ b/examples/ad_manager/v202102/publisher_query_language_service/get_mcm_earnings.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 Multiple Customer Management earnings for the prior month. +""" + +import datetime +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize a report downloader. + data_downloader = client.GetDataDownloader(version='v202102') + + with tempfile.NamedTemporaryFile( + prefix='mcm_earnings_', + suffix='.csv', mode='w', delete=False) as mcm_earnings_file: + + this_month_start = datetime.date.today().replace(day=1) + last_month_end = this_month_start - datetime.timedelta(days=1) + last_month_start = last_month_end.replace(day=1) + + mcm_earnings_query = ('SELECT Month, ChildName, ChildNetworkCode, ' + 'TotalEarningsCurrencyCode, TotalEarningsMicros, ' + 'ParentPaymentCurrencyCode, ParentPaymentMicros, ' + 'ChildPaymentCurrencyCode, ChildPaymentMicros, ' + 'DeductionsMicros ' + 'FROM Mcm_Earnings ' + 'WHERE Month = :month ' + 'ORDER BY ChildNetworkCode') + + # Downloads the response from PQL select statement to the specified file + data_downloader.DownloadPqlResultToCsv( + mcm_earnings_query, mcm_earnings_file, {'month': last_month_start}) + + print('Saved MCM earnings to... %s' % mcm_earnings_file.name) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202005/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202102/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v202005/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202102/publisher_query_language_service/get_recent_changes.py index 214ab078..b629151c 100755 --- a/examples/ad_manager/v202005/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202102/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v202005') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202102') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v202005/report_service/__init__.py b/examples/ad_manager/v202102/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/report_service/__init__.py rename to examples/ad_manager/v202102/report_service/__init__.py diff --git a/examples/ad_manager/v202005/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202102/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v202005/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202102/report_service/run_ad_exchange_report.py index b2ef393b..17d3213a 100755 --- a/examples/ad_manager/v202005/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202102/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') # Create report job. report_job = { diff --git a/examples/ad_manager/v202005/report_service/run_delivery_report.py b/examples/ad_manager/v202102/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v202005/report_service/run_delivery_report.py rename to examples/ad_manager/v202102/report_service/run_delivery_report.py index 7acdd128..280b94d6 100755 --- a/examples/ad_manager/v202005/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202102/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202005/report_service/run_inventory_report.py b/examples/ad_manager/v202102/report_service/run_inventory_report.py similarity index 97% rename from examples/ad_manager/v202005/report_service/run_inventory_report.py rename to examples/ad_manager/v202102/report_service/run_inventory_report.py index 60ac96d3..0b98b73a 100755 --- a/examples/ad_manager/v202005/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202102/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') # Create report job. report_job = { diff --git a/examples/ad_manager/v202005/report_service/run_reach_report.py b/examples/ad_manager/v202102/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v202005/report_service/run_reach_report.py rename to examples/ad_manager/v202102/report_service/run_reach_report.py index 43b49c77..4183d542 100755 --- a/examples/ad_manager/v202005/report_service/run_reach_report.py +++ b/examples/ad_manager/v202102/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') # Create report job. report_job = { diff --git a/examples/ad_manager/v202005/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202102/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v202005/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202102/report_service/run_report_and_create_match_table.py index 72366ee7..7fea17fa 100755 --- a/examples/ad_manager/v202005/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202102/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202005/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202102/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v202005/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202102/report_service/run_report_with_custom_fields.py index 5f8cb825..eb3a683d 100755 --- a/examples/ad_manager/v202005/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202102/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') # Create report job. report_job = { diff --git a/examples/ad_manager/v202005/report_service/run_sales_report.py b/examples/ad_manager/v202102/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v202005/report_service/run_sales_report.py rename to examples/ad_manager/v202102/report_service/run_sales_report.py index f2a18f80..49422a2e 100755 --- a/examples/ad_manager/v202005/report_service/run_sales_report.py +++ b/examples/ad_manager/v202102/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') # Create report job. report_job = { diff --git a/examples/ad_manager/v202005/report_service/run_saved_query.py b/examples/ad_manager/v202102/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v202005/report_service/run_saved_query.py rename to examples/ad_manager/v202102/report_service/run_saved_query.py index 969a7a05..7d617016 100755 --- a/examples/ad_manager/v202005/report_service/run_saved_query.py +++ b/examples/ad_manager/v202102/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v202005') + report_service = client.GetService('ReportService', version='v202102') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202005') + report_downloader = client.GetDataDownloader(version='v202102') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/site_service/create_sites.py b/examples/ad_manager/v202102/site_service/create_sites.py new file mode 100755 index 00000000..87240ac2 --- /dev/null +++ b/examples/ad_manager/v202102/site_service/create_sites.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 creates a Site for Multiple Customer Management.""" + +# Import appropriate modules from the client library. +import sys +from googleads import ad_manager + +# Set the URL and child network code for the Site. +URL = 'INSERT_URL_HERE' +CHILD_NETWORK_CODE = 'INSERT_CHILD_NETWORK_CODE_HERE' + + +def main(client, url, child_network_code): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v202102') + site_service = client.GetService('SiteService', version='v202102') + + # Check that the child network code is approved for MANAGE_INVENTORY by this + # network. + current_network = network_service.getCurrentNetwork() + child_network = None + for child in current_network['childPublishers']: + if child['childNetworkCode'] == child_network_code: + child_network = child + + if child_network is None: + print(('Child network %s not found on the current network (%s). Cannot ' + 'create site.') % (child_network_code, + current_network['networkCode'])) + sys.exit(1) + + if child_network['approvedDelegationType'] != 'MANAGE_INVENTORY': + print(('Child network %s has not approved for the current network (%s) ' + 'to manage its inventory. Cannot create site.') % ( + child_network_code, current_network['networkCode'])) + sys.exit(1) + + # Create site object. + site = {'url': url, 'childNetworkCode': child_network_code} + + # Create the site on the server. + created_sites = site_service.createSites([site]) + + # Display results. + for site in created_sites: + print('Site with id %d and URL "%s" was created for child network %s.' % ( + site['id'], site['url'], site['childNetworkCode'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, URL, CHILD_NETWORK_CODE) diff --git a/examples/ad_manager/v202102/site_service/get_all_sites.py b/examples/ad_manager/v202102/site_service/get_all_sites.py new file mode 100755 index 00000000..b594ea4b --- /dev/null +++ b/examples/ad_manager/v202102/site_service/get_all_sites.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 Sites.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + site_service = client.GetService('SiteService', version='v202102') + + # Create a statement to select Sites. + statement = ad_manager.StatementBuilder(version='v202102') + + # Retrieve a small number of sites at a time, paging through until all sites + # have been retrieved. + while True: + response = site_service.getSitesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for site in response['results']: + # Print out some information for each site. + print('Site with Id %d and URL "%s" was found.' % + (site['id'], site['url'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202102/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202102/site_service/get_sites_requiring_approval.py new file mode 100755 index 00000000..e509c24f --- /dev/null +++ b/examples/ad_manager/v202102/site_service/get_sites_requiring_approval.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 Sites under MCM requiring review.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + site_service = client.GetService('SiteService', version='v202102') + + # Create a statement to select Sites needing approval. + statement = ad_manager.StatementBuilder(version='v202102').Where( + "approvalStatus = 'REQUIRES_REVIEW'") + + # Retrieve a small number of sites at a time, paging through until all sites + # have been retrieved. + while True: + response = site_service.getSitesByStatement(statement.ToStatement()) + if 'results' in response and len(response['results']): + for site in response['results']: + # Print out some information for each site. + print('Site with Id %d and URL "%s" was found.' % + (site['id'], site['url'])) + statement.offset += statement.limit + else: + break + + print('\nNumber of results found: %s' % response['totalResultSetSize']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202102/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202102/site_service/submit_sites_for_approval.py new file mode 100755 index 00000000..278ba3e3 --- /dev/null +++ b/examples/ad_manager/v202102/site_service/submit_sites_for_approval.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# +# Copyright 2020 Google LLC +# +# 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 submits a Site for approval.""" + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the id of the site to submit for approval. +SITE_ID = 'INSERT_SITE_ID_HERE' + + +def main(client): + # Initialize appropriate service. + site_service = client.GetService('SiteService', version='v202102') + + # Create a statement to select Site. + statement = (ad_manager.StatementBuilder(version='v202102') + .Where('id = :id') + .WithBindVariable('id', SITE_ID)) + + response = site_service.performSiteAction( + {'xsi_type': 'SubmitSiteForApproval'}, statement.ToStatement()) + + print('\nNumber of sites changed: %s' % response['numChanges']) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202005/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202102/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202102/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v202005/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202102/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v202005/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202102/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 8b410477..c81247ae 100755 --- a/examples/ad_manager/v202005/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202102/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202005') + 'SuggestedAdUnitService', version='v202102') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v202005/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202102/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202005/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202102/suggested_ad_unit_service/get_all_suggested_ad_units.py index 0e854cae..d3ae3cb3 100755 --- a/examples/ad_manager/v202005/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202102/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202005') + 'SuggestedAdUnitService', version='v202102') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v202005/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202102/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202005/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202102/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 55013c4b..46b58b50 100755 --- a/examples/ad_manager/v202005/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202102/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202005') + 'SuggestedAdUnitService', version='v202102') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v202005/targeting_preset_service/__init__.py b/examples/ad_manager/v202102/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/targeting_preset_service/__init__.py rename to examples/ad_manager/v202102/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202005/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py similarity index 94% rename from examples/ad_manager/v202005/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py index 43fc7ac0..05d6670e 100755 --- a/examples/ad_manager/v202005/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v202005') + 'TargetingPresetService', version='v202102') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. diff --git a/examples/ad_manager/v202005/team_service/__init__.py b/examples/ad_manager/v202102/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/team_service/__init__.py rename to examples/ad_manager/v202102/team_service/__init__.py diff --git a/examples/ad_manager/v202005/team_service/create_teams.py b/examples/ad_manager/v202102/team_service/create_teams.py similarity index 94% rename from examples/ad_manager/v202005/team_service/create_teams.py rename to examples/ad_manager/v202102/team_service/create_teams.py index babbea53..1f4ab7e7 100755 --- a/examples/ad_manager/v202005/team_service/create_teams.py +++ b/examples/ad_manager/v202102/team_service/create_teams.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202005') + team_service = client.GetService('TeamService', version='v202102') # Create team objects. teams = [] - for _ in xrange(5): + for _ in range(5): team = { 'name': 'Team %s' % uuid.uuid4(), 'hasAllCompanies': 'false', diff --git a/examples/ad_manager/v202005/team_service/get_all_teams.py b/examples/ad_manager/v202102/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v202005/team_service/get_all_teams.py rename to examples/ad_manager/v202102/team_service/get_all_teams.py index 554a10e0..012ab069 100755 --- a/examples/ad_manager/v202005/team_service/get_all_teams.py +++ b/examples/ad_manager/v202102/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202005') + team_service = client.GetService('TeamService', version='v202102') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v202005/team_service/update_teams.py b/examples/ad_manager/v202102/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v202005/team_service/update_teams.py rename to examples/ad_manager/v202102/team_service/update_teams.py index bc2e1258..9533bae8 100755 --- a/examples/ad_manager/v202005/team_service/update_teams.py +++ b/examples/ad_manager/v202102/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202005') + team_service = client.GetService('TeamService', version='v202102') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v202005/user_service/__init__.py b/examples/ad_manager/v202102/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/user_service/__init__.py rename to examples/ad_manager/v202102/user_service/__init__.py diff --git a/examples/ad_manager/v202005/user_service/create_users.py b/examples/ad_manager/v202102/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v202005/user_service/create_users.py rename to examples/ad_manager/v202102/user_service/create_users.py index 2f355c5c..3c1b6324 100755 --- a/examples/ad_manager/v202005/user_service/create_users.py +++ b/examples/ad_manager/v202102/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202005') + user_service = client.GetService('UserService', version='v202102') # Create user objects. users = [ diff --git a/examples/ad_manager/v202005/user_service/deactivate_users.py b/examples/ad_manager/v202102/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v202005/user_service/deactivate_users.py rename to examples/ad_manager/v202102/user_service/deactivate_users.py index f4c767db..b7113a84 100755 --- a/examples/ad_manager/v202005/user_service/deactivate_users.py +++ b/examples/ad_manager/v202102/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202005') + user_service = client.GetService('UserService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202005/user_service/get_all_roles.py b/examples/ad_manager/v202102/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v202005/user_service/get_all_roles.py rename to examples/ad_manager/v202102/user_service/get_all_roles.py index 6c544e84..0c891fe3 100755 --- a/examples/ad_manager/v202005/user_service/get_all_roles.py +++ b/examples/ad_manager/v202102/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202005') + user_service = client.GetService('UserService', version='v202102') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v202005/user_service/get_all_users.py b/examples/ad_manager/v202102/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v202005/user_service/get_all_users.py rename to examples/ad_manager/v202102/user_service/get_all_users.py index dc67e5d2..383b21fb 100755 --- a/examples/ad_manager/v202005/user_service/get_all_users.py +++ b/examples/ad_manager/v202102/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202005') + user_service = client.GetService('UserService', version='v202102') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v202005/user_service/get_current_user.py b/examples/ad_manager/v202102/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v202005/user_service/get_current_user.py rename to examples/ad_manager/v202102/user_service/get_current_user.py index 8244c68e..2d4091cb 100755 --- a/examples/ad_manager/v202005/user_service/get_current_user.py +++ b/examples/ad_manager/v202102/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202005') + user_service = client.GetService('UserService', version='v202102') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v202005/user_service/get_user_by_email_address.py b/examples/ad_manager/v202102/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v202005/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202102/user_service/get_user_by_email_address.py index 1eaf6193..26780c99 100755 --- a/examples/ad_manager/v202005/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202102/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202005') + user_service = client.GetService('UserService', version='v202102') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v202005/user_service/update_users.py b/examples/ad_manager/v202102/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v202005/user_service/update_users.py rename to examples/ad_manager/v202102/user_service/update_users.py index 727b8960..fbf2f11f 100755 --- a/examples/ad_manager/v202005/user_service/update_users.py +++ b/examples/ad_manager/v202102/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202005') + user_service = client.GetService('UserService', version='v202102') # Create query. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202005/user_team_association_service/__init__.py b/examples/ad_manager/v202102/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202005/user_team_association_service/__init__.py rename to examples/ad_manager/v202102/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v202005/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202102/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v202005/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202102/user_team_association_service/create_user_team_associations.py index 6709bd88..657a85e5 100755 --- a/examples/ad_manager/v202005/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202102/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202005') + 'UserTeamAssociationService', version='v202102') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v202005/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202102/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v202005/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202102/user_team_association_service/delete_user_team_associations.py index 2b846f02..f26e1241 100755 --- a/examples/ad_manager/v202005/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202102/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202005') + 'UserTeamAssociationService', version='v202102') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202005/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202102/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v202005/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202102/user_team_association_service/get_all_user_team_associations.py index 48e2ee31..2463e8ae 100755 --- a/examples/ad_manager/v202005/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202102/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202005') + 'UserTeamAssociationService', version='v202102') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v202005') + statement = ad_manager.StatementBuilder(version='v202102') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v202005/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202102/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v202005/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202102/user_team_association_service/get_user_team_associations_for_user.py index 830087c3..092db53d 100755 --- a/examples/ad_manager/v202005/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202102/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202005') + 'UserTeamAssociationService', version='v202102') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202005/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202102/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v202005/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202102/user_team_association_service/update_user_team_associations.py index ea967d5b..91790e34 100755 --- a/examples/ad_manager/v202005/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202102/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202005') + 'UserTeamAssociationService', version='v202102') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202005') + statement = (ad_manager.StatementBuilder(version='v202102') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index 167b4b29..f8c4fa24 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -225,7 +225,7 @@ def GetCampaigns(self, client_customer_id): # and is taking too long. max_tries = 3 today = time.strftime('%Y%m%d', time.localtime()) - for i in xrange(1, max_tries + 1): + for i in range(1, max_tries + 1): try: selector = { 'fields': ['Id', 'Name', 'Status', 'BudgetId', 'Amount'], diff --git a/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py b/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py deleted file mode 100755 index 9875c72d..00000000 --- a/examples/adwords/v201809/shopping/add_shopping_campaign_for_showcase_ads.py +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2017 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 adds a Shopping campaign for Showcase ads. - -The LoadFromStorage method is pulling credentials and properties from a -"googleads.yaml" file. By default, it looks for this file in your home -directory. For more information, see the "Caching authentication information" -section of our README. -""" - -import uuid - -from googleads import adwords -from googleads import errors - - -BUDGET_ID = 'INSERT_BUDGET_ID_HERE' -MERCHANT_ID = 'INSERT_MERCHANT_ID_HERE' -EXPANDED_IMAGE_FILEPATH = 'INSERT_PATH_TO_EXPANDED_IMAGE' -COLLAPSED_IMAGE_FILEPATH = 'INSERT_PATH_TO_COLLAPSED_IMAGE' - - -class ProductPartitionHelper(object): - """A helper for creating ProductPartition trees.""" - - def __init__(self, adgroup_id): - """Initializer. - - Args: - adgroup_id: The ID of the AdGroup that we wish to attach the partition - tree to. - """ - # The next temporary criterion ID to be used. - # When creating our tree we need to specify the parent-child relationships - # between nodes. However, until a criterion has been created on the server - # we do not have a criterion ID with which to refer to it. - # Instead we can specify temporary IDs that are specific to a single mutate - # request. Once the criteria have been created they are assigned an ID as - # normal and the temporary ID will no longer refer to it. - # A valid temporary ID is any negative integer. - self.next_id = -1 - # The set of mutate operations needed to create the current tree. - self.operations = [] - self.adgroup_id = adgroup_id - - def CreateSubdivision(self, parent=None, value=None): - """Creates a subdivision node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - Returns: - A new subdivision node. - """ - division = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'SUBDIVISION', - 'id': str(self.next_id) - } - - # The root has neither a parent nor a value. - if parent is not None: - division['parentCriterionId'] = parent['id'] - division['caseValue'] = value - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'adGroupId': self.adgroup_id, - 'criterion': division - } - - self.CreateAddOperation(adgroup_criterion) - self.next_id -= 1 - - return division - - def CreateUnit(self, parent=None, value=None, bid_amount=None): - """Creates a unit node. - - Args: - parent: The node that should be this node's parent. - value: The value being partitioned on. - bid_amount: The amount to bid for matching products, in micros. - Returns: - A new unit node. - """ - unit = { - 'xsi_type': 'ProductPartition', - 'partitionType': 'UNIT' - } - - # The root node has neither a parent nor a value. - if parent is not None: - unit['parentCriterionId'] = parent['id'] - unit['caseValue'] = value - - if bid_amount is not None and bid_amount > 0: - # Note: Showcase ads require that the campaign has a ManualCpc - # BiddingStrategyConfiguration. - bidding_strategy_configuration = { - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'xsi_type': 'Money', - 'microAmount': str(bid_amount) - } - }] - } - - adgroup_criterion = { - 'xsi_type': 'BiddableAdGroupCriterion', - 'biddingStrategyConfiguration': bidding_strategy_configuration - } - else: - adgroup_criterion = { - 'xsi_type': 'NegativeAdGroupCriterion' - } - - adgroup_criterion['adGroupId'] = self.adgroup_id - adgroup_criterion['criterion'] = unit - - self.CreateAddOperation(adgroup_criterion) - - return unit - - def GetOperations(self): - """Returns the set of mutate operations needed to create the current tree. - - Returns: - The set of operations - """ - return self.operations - - def CreateAddOperation(self, criterion): - """Creates an AdGroupCriterionOperation for the given criterion. - - Args: - criterion: The criterion we want to add. - """ - operation = { - 'operator': 'ADD', - 'operand': criterion - } - - self.operations.append(operation) - - -def main(client, budget_id, merchant_id, expanded_image_filepath, - collapsed_image_filepath): - try: - # Create the Shopping Campaign - campaign = CreateShoppingCampaign(client, budget_id, merchant_id) - - # Create the AdGroup - adgroup = CreateAdGroup(client, campaign['id']) - - # Create a Showcase Ad - CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath) - - product_partition_tree = CreateProductPartition(client, adgroup['id']) - print('Final tree:\n%s' % product_partition_tree) - except errors.GoogleAdsServerFault: - print('Failed to create shopping campaign for showcase ads.') - raise - - -def CreateShoppingCampaign(client, budget_id, merchant_id): - """Creates a shopping campaign with the given budget and merchant IDs. - - Args: - client: an AdWordsClient instance. - budget_id: the str ID of the budget to be associated with the shopping - campaign. - merchant_id: the str ID of the merchant account to be associated with the - shopping campaign. - - Returns: - The created Shopping Campaign as a zeep.objects.Campaign. - """ - campaign_service = client.GetService('CampaignService', 'v201809') - - campaign = { - 'name': 'Shopping campaign #%s' % uuid.uuid4(), - # The advertisingChannelType is what makes this a shopping campaign - 'advertisingChannelType': 'SHOPPING', - # Recommendation: Set the campaign to PAUSED when creating it to stop the - # ads from immediately serving. Set to ENABLED once you've added targeting - # and the ads are ready to serve. - 'status': 'PAUSED', - # Set portfolio budget (required) - 'budget': { - 'budgetId': budget_id - }, - 'biddingStrategyConfiguration': { - 'biddingStrategyType': 'MANUAL_CPC' - }, - 'settings': [ - # All shopping campaigns need a ShoppingSetting - { - 'xsi_type': 'ShoppingSetting', - 'salesCountry': 'US', - 'campaignPriority': '0', - 'merchantId': merchant_id, - # Set to "True" to enable Local Inventory Ads in your campaign. - 'enableLocal': True - } - ] - } - - campaign_operations = [{ - 'operator': 'ADD', - 'operand': campaign - }] - - campaign = campaign_service.mutate(campaign_operations)['value'][0] - print('Campaign with name "%s" and ID "%s" was added.' - % (campaign['name'], campaign['id'])) - - return campaign - - -def CreateAdGroup(client, campaign_id): - """Creates an AdGroup for the given shopping campaign ID. - - Args: - client: an AdWordsClient instance. - campaign_id: the str ID of a shopping campaign. - - Returns: - The created AdGroup as a zeep.objects.AdGroup. - """ - ad_group_service = client.GetService('AdGroupService', 'v201809') - - adgroup = { - # Required: Set the ad group type to SHOPPING_SHOWCASE_ADS - 'adGroupType': 'SHOPPING_SHOWCASE_ADS', - 'campaignId': campaign_id, - 'name': 'AdGroup #%s' % uuid.uuid4(), - # REQUIRED: Set the ad group's bidding strategy configuration. - 'biddingStrategyConfiguration': { - # Showcase ads require either ManualCpc or EnhancedCpc. - 'biddingStrategyType': 'MANUAL_CPC', - # Optional: Set the bids - 'bids': [{ - 'xsi_type': 'CpcBid', - 'bid': { - 'microAmount': 100000 - } - }] - } - } - - adgroup_operations = { - 'operator': 'ADD', - 'operand': adgroup - } - - # Make the mutate request to add the AdGroup to the Shopping Campaign - adgroup = ad_group_service.mutate(adgroup_operations)['value'][0] - - print('AdGroup with name "%s" and ID "%s" was added.' - % (adgroup['name'], adgroup['id'])) - - return adgroup - - -def CreateShowcaseAd(client, adgroup, expanded_image_filepath, - collapsed_image_filepath): - """Creates a showcase add for the given AdGroup with the given images. - - Args: - client: an AdWordsClient instance. - adgroup: a dict or zeep object defining an AdGroup for a Shopping Campaign. - expanded_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's expandedImage. - collapsed_image_filepath: a str filepath to a .jpg file that will be used as - the Showcase Ad's collapsedImage. - - Returns: - The created Showcase Ad as a zeep.objects.Ad. - """ - ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809') - - showcase_ad = { - 'adGroupId': adgroup['id'], - 'ad': { - 'xsi_type': 'ShowcaseAd', - 'Ad.Type': 'ShowcaseAd', - # Required: set the ad's name, final URLs, and display URL. - 'name': 'Showcase ad #%s' % uuid.uuid4(), - 'finalUrls': 'http://example.com/showcase', - 'displayUrl': 'example.com', - # Required: Set the ad's expanded image. - 'expandedImage': { - 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId'] - }, - # Optional: Set the collapsed image. - 'collapsedImage': { - 'mediaId': - UploadImage(client, collapsed_image_filepath)['mediaId'] - } - } - } - - ad_operation = { - 'operator': 'ADD', - 'operand': showcase_ad - } - - # Make the mutate request to add the ProductAd to the AdGroup - showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0] - - print('ShowcaseAd with ID "%s" was added.' % showcase_ad['ad']['id']) - - return showcase_ad - - -def UploadImage(client, filepath): - """Uploads a .jpg image with the given filepath via the AdWords MediaService. - - Args: - client: an AdWordsClient instance. - filepath: a str filepath to the .jpg file to be uploaded. - - Returns: - The created Image as a zeep.objects.Image. - """ - media_service = client.GetService('MediaService', 'v201809') - - with open(filepath, 'rb') as image_handle: - image_data = image_handle.read().decode('utf-8') - - image = [{ - 'xsi_type': 'Image', - 'data': image_data, - 'type': 'IMAGE' - }] - - image = media_service.upload(image)[0] - - return image - - -def CreateProductPartition(client, adgroup_id): - """Creates a ProductPartition tree for the given AdGroup ID. - - Args: - client: an AdWordsClient instance. - adgroup_id: a str AdGroup ID. - - Returns: - The ProductPartition tree as a zeep.objects.ProductPartition. - """ - ad_group_criterion_service = client.GetService('AdGroupCriterionService', - 'v201809') - helper = ProductPartitionHelper(adgroup_id) - root = helper.CreateSubdivision() - - new_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'NEW' - } - - used_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - 'condition': 'USED' - } - - other_product_canonical_condition = { - 'xsi_type': 'ProductCanonicalCondition', - } - - helper.CreateUnit(root, new_product_canonical_condition) - helper.CreateUnit(root, used_product_canonical_condition) - helper.CreateUnit(root, other_product_canonical_condition) - - result = ad_group_criterion_service.mutate(helper.operations) - return result['value'] - - -if __name__ == '__main__': - # Initialize client object. - adwords_client = adwords.AdWordsClient.LoadFromStorage() - - main(adwords_client, BUDGET_ID, MERCHANT_ID, EXPANDED_IMAGE_FILEPATH, - COLLAPSED_IMAGE_FILEPATH) diff --git a/googleads.yaml b/googleads.yaml index 62f60c44..582baf6f 100644 --- a/googleads.yaml +++ b/googleads.yaml @@ -89,7 +89,7 @@ ad_manager: # formatter: default_fmt # level: INFO # loggers: - # Configure root logger + ## Configure root logger # "": # handlers: [default_handler] # level: INFO diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 8bf33e4e..42902cb4 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,7 +44,7 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v202002': + 'v202005': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -61,7 +61,7 @@ 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202005': + 'v202008': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -69,16 +69,17 @@ 'CreativeReviewService', 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', 'CreativeWrapperService', 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'ForecastService', 'InventoryService', - 'LabelService', 'LineItemCreativeAssociationService', - 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', + 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', 'OrderService', 'PlacementService', 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'StreamActivityMonitorService', 'SuggestedAdUnitService', - 'TeamService', 'TargetingPresetService', 'UserService', - 'UserTeamAssociationService'), - 'v202008': + 'SiteService', 'StreamActivityMonitorService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService'), + 'v202011': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -96,7 +97,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202011': + 'v202102': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', diff --git a/googleads/common.py b/googleads/common.py index bee6b4cc..507248ba 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -55,7 +55,7 @@ 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '26.0.0' +VERSION = '27.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index b38f5162..b4a6525f 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202011' +CURRENT_VERSION = 'v202102' class CommonTest(testing.CleanUtilityRegistryTestCase): From 5cc413fdebcf2f75f81ba31e57a9a87760e2090a Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 18 Feb 2021 14:35:20 -0500 Subject: [PATCH 166/180] Commiting latest changes. From 9bfa25c1bbd45957a8d670c7d744523c8457dd32 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 18 Feb 2021 14:36:37 -0500 Subject: [PATCH 167/180] Commiting latest changes. From 2a61076c562ace3ddd0a3e50f82f7fc238f1e330 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Wed, 12 May 2021 14:52:39 -0400 Subject: [PATCH 168/180] Commiting latest changes. From a5d4d7ea60ed7a7ddb622da44135c6493045a2b5 Mon Sep 17 00:00:00 2001 From: David Wihl Date: Thu, 13 May 2021 12:50:52 -0400 Subject: [PATCH 169/180] Ad Manager v202105 release --- ChangeLog | 5 + README.md | 7 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 2 +- .../create_traffic_forecast_segments.py | 4 +- .../get_all_forecast_adjustments.py | 4 +- .../get_all_traffic_forecast_segments.py | 4 +- ...djustments_for_traffic_forecast_segment.py | 4 +- .../update_forecast_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../get_recently_modified_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 15 ++- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../forecast_service/get_traffic_data.py | 123 ++++++++++++++++++ .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../push_creative_to_devices.py | 61 +++++++++ .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 3 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- ...et_default_third_party_data_declaration.py | 68 ++++++++++ .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 12 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../site_service/create_sites.py | 4 +- .../site_service/get_all_sites.py | 4 +- .../get_sites_requiring_approval.py | 4 +- .../site_service/submit_sites_for_approval.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- .../adwords/adwords_appengine_demo/COPYING | 0 .../adwords/adwords_appengine_demo/ChangeLog | 0 .../adwords/adwords_appengine_demo/README.md | 0 .../adwords/adwords_appengine_demo/app.yaml | 0 .../handlers/api_handler.py | 1 - .../adwords_appengine_demo/js/scripts.js | 0 .../adwords_appengine_demo/requirements.txt | 0 .../stylesheets/styles.css | 0 .../templates/base_template.html | 0 .../templates/show_accounts.html | 0 .../templates/show_adgroups.html | 0 .../templates/show_budget.html | 0 .../templates/show_campaigns.html | 0 .../templates/show_credentials.html | 0 .../templates/toggle_menu_template.html | 0 googleads/ad_manager.py | 22 ++-- googleads/common.py | 9 +- tests/ad_manager_test.py | 3 - tests/adwords_test.py | 1 - tests/common_test.py | 3 +- 220 files changed, 582 insertions(+), 337 deletions(-) rename examples/ad_manager/{v202008 => v202105}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v202008 => v202105}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v202008 => v202105}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v202008 => v202105}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v202008 => v202105}/activity_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v202008 => v202105}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v202008 => v202105}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v202008 => v202105}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v202008 => v202105}/adjustment_service/create_forecast_adjustments.py (99%) rename examples/ad_manager/{v202008 => v202105}/adjustment_service/create_traffic_forecast_segments.py (98%) rename examples/ad_manager/{v202008 => v202105}/adjustment_service/get_all_forecast_adjustments.py (95%) rename examples/ad_manager/{v202008 => v202105}/adjustment_service/get_all_traffic_forecast_segments.py (95%) rename examples/ad_manager/{v202008 => v202105}/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py (96%) rename examples/ad_manager/{v202008 => v202105}/adjustment_service/update_forecast_adjustments.py (96%) rename examples/ad_manager/{v202008 => v202105}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v202008 => v202105}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v202008 => v202105}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v202008 => v202105}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v202008 => v202105}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v202008 => v202105}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v202008 => v202105}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v202008 => v202105}/cms_metadata_service/activate_cms_metadata_values.py (95%) rename examples/ad_manager/{v202008 => v202105}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v202008 => v202105}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v202008 => v202105}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v202008 => v202105}/company_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/company_service/create_companies.py (99%) rename examples/ad_manager/{v202008 => v202105}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v202008 => v202105}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v202008 => v202105}/company_service/update_companies.py (96%) rename examples/ad_manager/{v202008 => v202105}/contact_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v202008 => v202105}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v202008 => v202105}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v202008 => v202105}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v202008 => v202105}/content_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/content_service/get_all_content.py (96%) rename examples/ad_manager/{v202008 => v202105}/content_service/get_recently_modified_content.py (97%) rename examples/ad_manager/{v202008 => v202105}/creative_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v202008 => v202105}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v202008 => v202105}/creative_service/create_creatives.py (88%) rename examples/ad_manager/{v202008 => v202105}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v202008 => v202105}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v202008 => v202105}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v202008 => v202105}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v202008 => v202105}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v202008 => v202105}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v202008 => v202105}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v202008 => v202105}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v202008 => v202105}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v202008 => v202105}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v202008 => v202105}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v202008 => v202105}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v202008 => v202105}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v202008 => v202105}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v202008 => v202105}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v202008 => v202105}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v202008 => v202105}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v202008 => v202105}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v202008 => v202105}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v202008 => v202105}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v202008 => v202105}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v202008 => v202105}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v202008 => v202105}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v202008 => v202105}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v202008 => v202105}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v202008 => v202105}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202008 => v202105}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v202008 => v202105}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202008 => v202105}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202008 => v202105}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202008 => v202105}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v202008 => v202105}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v202008 => v202105}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v202008 => v202105}/forecast_service/get_delivery_forecast_for_line_items.py (99%) create mode 100755 examples/ad_manager/v202105/forecast_service/get_traffic_data.py rename examples/ad_manager/{v202008 => v202105}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v202008 => v202105}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v202008 => v202105}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v202008 => v202105}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v202008 => v202105}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v202008 => v202105}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v202008 => v202105}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v202008 => v202105}/label_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/label_service/create_labels.py (99%) rename examples/ad_manager/{v202008 => v202105}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v202008 => v202105}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v202008 => v202105}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v202008 => v202105}/label_service/update_labels.py (96%) rename examples/ad_manager/{v202008 => v202105}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v202008 => v202105}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v202008 => v202105}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v202008 => v202105}/line_item_creative_association_service/get_licas_for_line_item.py (94%) create mode 100755 examples/ad_manager/v202105/line_item_creative_association_service/push_creative_to_devices.py rename examples/ad_manager/{v202008 => v202105}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/create_video_line_item.py (98%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v202008 => v202105}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v202008 => v202105}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v202008 => v202105}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v202008 => v202105}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v202008 => v202105}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v202008 => v202105}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v202008 => v202105}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v202008 => v202105}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v202008 => v202105}/network_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v202008 => v202105}/network_service/get_current_network.py (99%) create mode 100755 examples/ad_manager/v202105/network_service/get_default_third_party_data_declaration.py rename examples/ad_manager/{v202008 => v202105}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v202008 => v202105}/order_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v202008 => v202105}/order_service/create_orders.py (99%) rename examples/ad_manager/{v202008 => v202105}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v202008 => v202105}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v202008 => v202105}/order_service/update_orders.py (97%) rename examples/ad_manager/{v202008 => v202105}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v202008 => v202105}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v202008 => v202105}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v202008 => v202105}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v202008 => v202105}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v202008 => v202105}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v202008 => v202105}/proposal_line_item_service/create_proposal_line_items.py (94%) rename examples/ad_manager/{v202008 => v202105}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v202008 => v202105}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v202008 => v202105}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v202008 => v202105}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v202008 => v202105}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v202008 => v202105}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v202008 => v202105}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v202008 => v202105}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v202008 => v202105}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v202008 => v202105}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v202008 => v202105}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v202008 => v202105}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v202008 => v202105}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v202008 => v202105}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v202008 => v202105}/publisher_query_language_service/get_mcm_earnings.py (97%) rename examples/ad_manager/{v202008 => v202105}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v202008 => v202105}/report_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v202008 => v202105}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v202008 => v202105}/report_service/run_inventory_report.py (97%) rename examples/ad_manager/{v202008 => v202105}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v202008 => v202105}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v202008 => v202105}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v202008 => v202105}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v202008 => v202105}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v202008 => v202105}/site_service/create_sites.py (96%) rename examples/ad_manager/{v202008 => v202105}/site_service/get_all_sites.py (92%) rename examples/ad_manager/{v202008 => v202105}/site_service/get_sites_requiring_approval.py (92%) rename examples/ad_manager/{v202008 => v202105}/site_service/submit_sites_for_approval.py (91%) rename examples/ad_manager/{v202008 => v202105}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v202008 => v202105}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v202008 => v202105}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v202008 => v202105}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/targeting_preset_service/get_all_targeting_presets.py (94%) rename examples/ad_manager/{v202008 => v202105}/team_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/team_service/create_teams.py (96%) rename examples/ad_manager/{v202008 => v202105}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v202008 => v202105}/team_service/update_teams.py (94%) rename examples/ad_manager/{v202008 => v202105}/user_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/user_service/create_users.py (96%) rename examples/ad_manager/{v202008 => v202105}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v202008 => v202105}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v202008 => v202105}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v202008 => v202105}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v202008 => v202105}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v202008 => v202105}/user_service/update_users.py (92%) rename examples/ad_manager/{v202008 => v202105}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v202008 => v202105}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v202008 => v202105}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v202008 => v202105}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v202008 => v202105}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v202008 => v202105}/user_team_association_service/update_user_team_associations.py (96%) mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/COPYING mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/ChangeLog mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/README.md mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/app.yaml mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/js/scripts.js mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/requirements.txt mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/stylesheets/styles.css mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/templates/base_template.html mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/templates/show_accounts.html mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/templates/show_adgroups.html mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/templates/show_budget.html mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/templates/show_campaigns.html mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/templates/show_credentials.html mode change 100644 => 100755 examples/adwords/adwords_appengine_demo/templates/toggle_menu_template.html diff --git a/ChangeLog b/ChangeLog index debcbb4c..4837133e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +28.0.0 -- 05/11/2021 +* Added support for Ad Manager v202105. +* Removed support for Ad Manager v202005. +* Removed examples for Ad Manager v202008. + 27.0.0 -- 02/17/2021 * Added support for Ad Manager v202102. * Removed support for Ad Manager v202002. diff --git a/README.md b/README.md index d018669c..be0d3115 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,13 @@ # The googleads Python client library -**Note:** DoubleClick for Publishers was recently renamed to Google Ad Manager, and this library -was modified to follow suit. Please see the [migration guide](https://github.com/googleads/googleads-python-lib/wiki/dfp-rebrand) -for more details. - This client library simplifies accessing Google's SOAP Ads APIs - AdWords, and DoubleClick for Publishers. The library provides easy ways to store your authentication and create SOAP web service clients. It also contains example code to help you get started integrating with our APIs. +> **The Google AdWords API will [sunset on April 27, 2022](https://ads-developers.googleblog.com/2021/04/upgrade-to-google-ads-api-from-adwords.html). +> Upgrade to the [Google Ads API](https://developers.google.com/google-ads/api/docs/client-libs).** + **NOTE**: As of v20.0.0 this library is _not_ compatible with Python versions less than Python 3.6. Also `suds` is no longer supported in this library, `zeep` is now the only supported SOAP client. diff --git a/examples/ad_manager/v202008/activity_group_service/__init__.py b/examples/ad_manager/v202105/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/activity_group_service/__init__.py rename to examples/ad_manager/v202105/activity_group_service/__init__.py diff --git a/examples/ad_manager/v202008/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202105/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v202008/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202105/activity_group_service/create_activity_groups.py index a5f5b88f..da4044a5 100755 --- a/examples/ad_manager/v202008/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202105/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202008') + version='v202105') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v202008/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202105/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v202008/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202105/activity_group_service/get_active_activity_groups.py index 6895dcb5..159aeb65 100755 --- a/examples/ad_manager/v202008/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202105/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202008') + 'ActivityGroupService', version='v202105') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202008/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202105/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v202008/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202105/activity_group_service/get_all_activity_groups.py index bf0c3cbd..05dd4b98 100755 --- a/examples/ad_manager/v202008/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202105/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202008') + 'ActivityGroupService', version='v202105') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v202008/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202105/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v202008/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202105/activity_group_service/update_activity_groups.py index 17cdcb8a..d043e510 100755 --- a/examples/ad_manager/v202008/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202105/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202008') + version='v202105') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/activity_service/__init__.py b/examples/ad_manager/v202105/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/activity_service/__init__.py rename to examples/ad_manager/v202105/activity_service/__init__.py diff --git a/examples/ad_manager/v202008/activity_service/create_activities.py b/examples/ad_manager/v202105/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v202008/activity_service/create_activities.py rename to examples/ad_manager/v202105/activity_service/create_activities.py index 18ce6f0e..cf57e492 100755 --- a/examples/ad_manager/v202008/activity_service/create_activities.py +++ b/examples/ad_manager/v202105/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202008') + activity_service = client.GetService('ActivityService', version='v202105') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v202008/activity_service/get_active_activities.py b/examples/ad_manager/v202105/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v202008/activity_service/get_active_activities.py rename to examples/ad_manager/v202105/activity_service/get_active_activities.py index 3ea9bf55..83c54312 100755 --- a/examples/ad_manager/v202008/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202105/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202008') + activity_service = client.GetService('ActivityService', version='v202105') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202008/activity_service/get_all_activities.py b/examples/ad_manager/v202105/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v202008/activity_service/get_all_activities.py rename to examples/ad_manager/v202105/activity_service/get_all_activities.py index 233e43c1..bbbe93a3 100755 --- a/examples/ad_manager/v202008/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202105/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202008') + activity_service = client.GetService('ActivityService', version='v202105') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v202008/activity_service/update_activities.py b/examples/ad_manager/v202105/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v202008/activity_service/update_activities.py rename to examples/ad_manager/v202105/activity_service/update_activities.py index 7fdac9bf..8ae9ecc6 100755 --- a/examples/ad_manager/v202008/activity_service/update_activities.py +++ b/examples/ad_manager/v202105/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202008') + activity_service = client.GetService('ActivityService', version='v202105') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202105/adjustment_service/create_forecast_adjustments.py similarity index 99% rename from examples/ad_manager/v202008/adjustment_service/create_forecast_adjustments.py rename to examples/ad_manager/v202105/adjustment_service/create_forecast_adjustments.py index 69f3353f..8e466f23 100755 --- a/examples/ad_manager/v202008/adjustment_service/create_forecast_adjustments.py +++ b/examples/ad_manager/v202105/adjustment_service/create_forecast_adjustments.py @@ -27,7 +27,7 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202008') + adjustment_service = client.GetService('AdjustmentService', version='v202105') # Create a new forecast adjustment for New Year's Day traffic. this_new_years = datetime.date(datetime.date.today().year, 1, 1) diff --git a/examples/ad_manager/v202008/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202105/adjustment_service/create_traffic_forecast_segments.py similarity index 98% rename from examples/ad_manager/v202008/adjustment_service/create_traffic_forecast_segments.py rename to examples/ad_manager/v202105/adjustment_service/create_traffic_forecast_segments.py index f0ab29d9..24c5c56c 100755 --- a/examples/ad_manager/v202008/adjustment_service/create_traffic_forecast_segments.py +++ b/examples/ad_manager/v202105/adjustment_service/create_traffic_forecast_segments.py @@ -25,8 +25,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v202008') - network_service = client.GetService('NetworkService', version='v202008') + adjustment_service = client.GetService('AdjustmentService', version='v202105') + network_service = client.GetService('NetworkService', version='v202105') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202008/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202105/adjustment_service/get_all_forecast_adjustments.py similarity index 95% rename from examples/ad_manager/v202008/adjustment_service/get_all_forecast_adjustments.py rename to examples/ad_manager/v202105/adjustment_service/get_all_forecast_adjustments.py index a2297915..a91a9998 100755 --- a/examples/ad_manager/v202008/adjustment_service/get_all_forecast_adjustments.py +++ b/examples/ad_manager/v202105/adjustment_service/get_all_forecast_adjustments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202008') + adjustment_service = client.GetService('AdjustmentService', version='v202105') # Create a statement to get all forecast adjustments. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small number of forecast adjustments at a time, paging # through until all forecast adjustments have been retrieved. diff --git a/examples/ad_manager/v202008/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202105/adjustment_service/get_all_traffic_forecast_segments.py similarity index 95% rename from examples/ad_manager/v202008/adjustment_service/get_all_traffic_forecast_segments.py rename to examples/ad_manager/v202105/adjustment_service/get_all_traffic_forecast_segments.py index 4692ef71..fdf85470 100755 --- a/examples/ad_manager/v202008/adjustment_service/get_all_traffic_forecast_segments.py +++ b/examples/ad_manager/v202105/adjustment_service/get_all_traffic_forecast_segments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202008') + adjustment_service = client.GetService('AdjustmentService', version='v202105') # Create a statement to get all traffic forecast segments. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small number of segments at a time, paging through until all # segments have been retrieved. diff --git a/examples/ad_manager/v202008/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202105/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py similarity index 96% rename from examples/ad_manager/v202008/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py rename to examples/ad_manager/v202105/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py index 8e11b97b..4fa60610 100755 --- a/examples/ad_manager/v202008/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py +++ b/examples/ad_manager/v202105/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -24,11 +24,11 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202008') + adjustment_service = client.GetService('AdjustmentService', version='v202105') # Create a statement to get forecast adjustments for a given traffic forecast # segment id. - statement = ad_manager.StatementBuilder(version='v202008').Where( + statement = ad_manager.StatementBuilder(version='v202105').Where( 'trafficForecastSegmentId = :segmentId').WithBindVariable( 'segmentId', traffic_forecast_segment_id) diff --git a/examples/ad_manager/v202008/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202105/adjustment_service/update_forecast_adjustments.py similarity index 96% rename from examples/ad_manager/v202008/adjustment_service/update_forecast_adjustments.py rename to examples/ad_manager/v202105/adjustment_service/update_forecast_adjustments.py index 8980fa0e..07363e5d 100755 --- a/examples/ad_manager/v202008/adjustment_service/update_forecast_adjustments.py +++ b/examples/ad_manager/v202105/adjustment_service/update_forecast_adjustments.py @@ -24,12 +24,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202008') + adjustment_service = client.GetService('AdjustmentService', version='v202105') # Create a statement to select a single forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v202008').Where('id = :id').WithBindVariable( + version='v202105').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast adjustment. diff --git a/examples/ad_manager/v202008/audience_segment_service/__init__.py b/examples/ad_manager/v202105/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/audience_segment_service/__init__.py rename to examples/ad_manager/v202105/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v202008/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202105/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v202008/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202105/audience_segment_service/create_audience_segments.py index 24e9ffab..6a84135b 100755 --- a/examples/ad_manager/v202008/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202105/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202008') - network_service = client.GetService('NetworkService', version='v202008') + 'AudienceSegmentService', version='v202105') + network_service = client.GetService('NetworkService', version='v202105') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v202008/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202105/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v202008/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202105/audience_segment_service/get_all_audience_segments.py index c28f2350..10764f3e 100755 --- a/examples/ad_manager/v202008/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202105/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202008') + 'AudienceSegmentService', version='v202105') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v202008/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202105/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v202008/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202105/audience_segment_service/get_first_party_audience_segments.py index ae1b59fb..9d916407 100755 --- a/examples/ad_manager/v202008/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202105/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202008') + 'AudienceSegmentService', version='v202105') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v202008/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202105/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v202008/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202105/audience_segment_service/populate_first_party_audience_segments.py index c9393d57..13cc35b5 100755 --- a/examples/ad_manager/v202008/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202105/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202008') + 'AudienceSegmentService', version='v202105') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202008/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202105/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v202008/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202105/audience_segment_service/update_audience_segments.py index c5b75f6e..e4fc5a1f 100755 --- a/examples/ad_manager/v202008/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202105/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202008') + 'AudienceSegmentService', version='v202105') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202008/cdn_configuration_service/__init__.py b/examples/ad_manager/v202105/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202105/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v202008/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202105/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v202008/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202105/cdn_configuration_service/create_cdn_configurations.py index d63642d4..7c09c960 100755 --- a/examples/ad_manager/v202008/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202105/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202008') + version='v202105') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v202008/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202105/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v202008/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202105/cdn_configuration_service/get_all_cdn_configurations.py index 83212c6e..114e0fe3 100755 --- a/examples/ad_manager/v202008/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202105/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202008') + version='v202105') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202008/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202105/cms_metadata_service/activate_cms_metadata_values.py similarity index 95% rename from examples/ad_manager/v202008/cms_metadata_service/activate_cms_metadata_values.py rename to examples/ad_manager/v202105/cms_metadata_service/activate_cms_metadata_values.py index b0b06c1d..1078eb7e 100755 --- a/examples/ad_manager/v202008/cms_metadata_service/activate_cms_metadata_values.py +++ b/examples/ad_manager/v202105/cms_metadata_service/activate_cms_metadata_values.py @@ -28,10 +28,10 @@ def main(client, cms_metadata_key_id): # Initialize appropriate service. cms_metadata_service = client.GetService('CmsMetadataService', - version='v202008') + version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('cmsKeyId = :cmsKeyId AND status = :status') .WithBindVariable('status', 'INACTIVE') .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) diff --git a/examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_keys.py index 37c1abb8..38ee12c6 100755 --- a/examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202008') + 'CmsMetadataService', version='v202105') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_values.py index 5c9ea8e0..1fca98c4 100755 --- a/examples/ad_manager/v202008/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202008') + 'CmsMetadataService', version='v202105') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v202008/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202105/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v202008/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202105/cms_metadata_service/get_cms_metadata_values_for_key.py index 4ec5ee89..51a4dbde 100755 --- a/examples/ad_manager/v202008/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202105/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202008') + 'CmsMetadataService', version='v202105') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v202008').Where( + ad_manager.StatementBuilder(version='v202105').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v202008/company_service/__init__.py b/examples/ad_manager/v202105/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/company_service/__init__.py rename to examples/ad_manager/v202105/company_service/__init__.py diff --git a/examples/ad_manager/v202008/company_service/create_companies.py b/examples/ad_manager/v202105/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v202008/company_service/create_companies.py rename to examples/ad_manager/v202105/company_service/create_companies.py index 4cf46596..b067ad7c 100755 --- a/examples/ad_manager/v202008/company_service/create_companies.py +++ b/examples/ad_manager/v202105/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202008') + company_service = client.GetService('CompanyService', version='v202105') # Create company objects. companies = [ diff --git a/examples/ad_manager/v202008/company_service/get_advertisers.py b/examples/ad_manager/v202105/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v202008/company_service/get_advertisers.py rename to examples/ad_manager/v202105/company_service/get_advertisers.py index a1c8f007..b19cadae 100755 --- a/examples/ad_manager/v202008/company_service/get_advertisers.py +++ b/examples/ad_manager/v202105/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202008') + company_service = client.GetService('CompanyService', version='v202105') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v202008/company_service/get_all_companies.py b/examples/ad_manager/v202105/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v202008/company_service/get_all_companies.py rename to examples/ad_manager/v202105/company_service/get_all_companies.py index a2ecae6e..6808eac8 100755 --- a/examples/ad_manager/v202008/company_service/get_all_companies.py +++ b/examples/ad_manager/v202105/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202008') + company_service = client.GetService('CompanyService', version='v202105') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v202008/company_service/update_companies.py b/examples/ad_manager/v202105/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v202008/company_service/update_companies.py rename to examples/ad_manager/v202105/company_service/update_companies.py index 99fbfb74..8df7e5e6 100755 --- a/examples/ad_manager/v202008/company_service/update_companies.py +++ b/examples/ad_manager/v202105/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202008') + company_service = client.GetService('CompanyService', version='v202105') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/contact_service/__init__.py b/examples/ad_manager/v202105/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/contact_service/__init__.py rename to examples/ad_manager/v202105/contact_service/__init__.py diff --git a/examples/ad_manager/v202008/contact_service/create_contacts.py b/examples/ad_manager/v202105/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v202008/contact_service/create_contacts.py rename to examples/ad_manager/v202105/contact_service/create_contacts.py index 26bbb911..db606096 100755 --- a/examples/ad_manager/v202008/contact_service/create_contacts.py +++ b/examples/ad_manager/v202105/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202008') + contact_service = client.GetService('ContactService', version='v202105') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v202008/contact_service/get_all_contacts.py b/examples/ad_manager/v202105/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v202008/contact_service/get_all_contacts.py rename to examples/ad_manager/v202105/contact_service/get_all_contacts.py index 2ac423f6..e6c0360d 100755 --- a/examples/ad_manager/v202008/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202105/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202008') + contact_service = client.GetService('ContactService', version='v202105') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v202008/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202105/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v202008/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202105/contact_service/get_uninvited_contacts.py index 1a2c576a..ba9abc85 100755 --- a/examples/ad_manager/v202008/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202105/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202008') + contact_service = client.GetService('ContactService', version='v202105') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v202008/contact_service/update_contacts.py b/examples/ad_manager/v202105/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v202008/contact_service/update_contacts.py rename to examples/ad_manager/v202105/contact_service/update_contacts.py index b84f5eb4..ab5fb8b3 100755 --- a/examples/ad_manager/v202008/contact_service/update_contacts.py +++ b/examples/ad_manager/v202105/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202008') + contact_service = client.GetService('ContactService', version='v202105') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/content_service/__init__.py b/examples/ad_manager/v202105/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/content_service/__init__.py rename to examples/ad_manager/v202105/content_service/__init__.py diff --git a/examples/ad_manager/v202008/content_service/get_all_content.py b/examples/ad_manager/v202105/content_service/get_all_content.py similarity index 96% rename from examples/ad_manager/v202008/content_service/get_all_content.py rename to examples/ad_manager/v202105/content_service/get_all_content.py index 25e6dba9..d280c64a 100755 --- a/examples/ad_manager/v202008/content_service/get_all_content.py +++ b/examples/ad_manager/v202105/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202008') + content_service = client.GetService('ContentService', version='v202105') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v202008/content_service/get_recently_modified_content.py b/examples/ad_manager/v202105/content_service/get_recently_modified_content.py similarity index 97% rename from examples/ad_manager/v202008/content_service/get_recently_modified_content.py rename to examples/ad_manager/v202105/content_service/get_recently_modified_content.py index dca5c66b..4d270115 100755 --- a/examples/ad_manager/v202008/content_service/get_recently_modified_content.py +++ b/examples/ad_manager/v202105/content_service/get_recently_modified_content.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202008') + content_service = client.GetService('ContentService', version='v202105') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -35,7 +35,7 @@ def main(client): # lastModifiedDateTime. Changes to content bundle associations will update # the lastModifiedDateTime, but CMS metadata changes may not change the # lastModifiedDateTime. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202008/creative_service/__init__.py b/examples/ad_manager/v202105/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/creative_service/__init__.py rename to examples/ad_manager/v202105/creative_service/__init__.py diff --git a/examples/ad_manager/v202008/creative_service/copy_image_creatives.py b/examples/ad_manager/v202105/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v202008/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202105/creative_service/copy_image_creatives.py index be63f875..2b2d6b87 100755 --- a/examples/ad_manager/v202008/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202105/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202008') + creative_service = client.GetService('CreativeService', version='v202105') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v202008/creative_service/create_creative_from_template.py b/examples/ad_manager/v202105/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v202008/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202105/creative_service/create_creative_from_template.py index e5f1e75c..98126275 100755 --- a/examples/ad_manager/v202008/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202105/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202008') + creative_service = client.GetService('CreativeService', version='v202105') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v202008/creative_service/create_creatives.py b/examples/ad_manager/v202105/creative_service/create_creatives.py similarity index 88% rename from examples/ad_manager/v202008/creative_service/create_creatives.py rename to examples/ad_manager/v202105/creative_service/create_creatives.py index 6f3d783e..01dff6e2 100755 --- a/examples/ad_manager/v202008/creative_service/create_creatives.py +++ b/examples/ad_manager/v202105/creative_service/create_creatives.py @@ -39,12 +39,14 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202008') + creative_service = client.GetService('CreativeService', version='v202105') # Create creative objects. creatives = [] - with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', - 'medium_rectangle.jpg'), 'r') as image: + with open( + os.path.join( + os.path.split(__file__)[0], '..', '..', 'data', + 'medium_rectangle.jpg'), 'rb') as image: image_data = image.read() for _ in range(5): @@ -80,9 +82,10 @@ def main(client, advertiser_id): # Display results. for creative in creatives: print('Image creative with id "%s", name "%s", and type "%s" was ' - 'created and can be previewed at %s.' - % (creative['id'], creative['name'], - ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + 'created and can be previewed at %s.' % + (creative['id'], creative['name'], + ad_manager.AdManagerClassType(creative), creative['previewUrl'])) + if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v202008/creative_service/create_custom_creative.py b/examples/ad_manager/v202105/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v202008/creative_service/create_custom_creative.py rename to examples/ad_manager/v202105/creative_service/create_custom_creative.py index b24463ef..92b129fa 100755 --- a/examples/ad_manager/v202008/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202105/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202008') + creative_service = client.GetService('CreativeService', version='v202105') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v202008/creative_service/create_native_creative.py b/examples/ad_manager/v202105/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v202008/creative_service/create_native_creative.py rename to examples/ad_manager/v202105/creative_service/create_native_creative.py index cdae3d2b..35c52ed5 100755 --- a/examples/ad_manager/v202008/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202105/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202008') + creative_service = client.GetService('CreativeService', version='v202105') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v202008/creative_service/get_all_creatives.py b/examples/ad_manager/v202105/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v202008/creative_service/get_all_creatives.py rename to examples/ad_manager/v202105/creative_service/get_all_creatives.py index feb40c53..e4e3fae5 100755 --- a/examples/ad_manager/v202008/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202105/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202008') + creative_service = client.GetService('CreativeService', version='v202105') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v202008/creative_service/get_image_creatives.py b/examples/ad_manager/v202105/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v202008/creative_service/get_image_creatives.py rename to examples/ad_manager/v202105/creative_service/get_image_creatives.py index 27a27881..ca4bbd07 100755 --- a/examples/ad_manager/v202008/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202105/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202008') + creative_service = client.GetService('CreativeService', version='v202105') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v202008/creative_service/update_creatives.py b/examples/ad_manager/v202105/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v202008/creative_service/update_creatives.py rename to examples/ad_manager/v202105/creative_service/update_creatives.py index c98903c1..53f0c63a 100755 --- a/examples/ad_manager/v202008/creative_service/update_creatives.py +++ b/examples/ad_manager/v202105/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202008') + creative_service = client.GetService('CreativeService', version='v202105') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v202008/creative_set_service/__init__.py b/examples/ad_manager/v202105/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/creative_set_service/__init__.py rename to examples/ad_manager/v202105/creative_set_service/__init__.py diff --git a/examples/ad_manager/v202008/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202105/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v202008/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202105/creative_set_service/associate_creative_set_to_line_item.py index 3bcf1d82..a441ecba 100755 --- a/examples/ad_manager/v202008/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202105/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202008') + 'LineItemCreativeAssociationService', version='v202105') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v202008/creative_set_service/create_creative_set.py b/examples/ad_manager/v202105/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v202008/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202105/creative_set_service/create_creative_set.py index dd5c4f22..d9e30a3a 100755 --- a/examples/ad_manager/v202008/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202105/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202008') + version='v202105') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v202008/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202105/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v202008/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202105/creative_set_service/get_all_creative_sets.py index 42e0f502..3f8f41ae 100755 --- a/examples/ad_manager/v202008/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202105/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202008') + 'CreativeSetService', version='v202105') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v202008/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202105/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v202008/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202105/creative_set_service/get_creative_sets_for_master_creative.py index 238c75b9..6470e727 100755 --- a/examples/ad_manager/v202008/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202105/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202008') + 'CreativeSetService', version='v202105') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v202008/creative_set_service/update_creative_set.py b/examples/ad_manager/v202105/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v202008/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202105/creative_set_service/update_creative_set.py index f8962376..d7e19393 100755 --- a/examples/ad_manager/v202008/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202105/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202008') + version='v202105') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v202008/creative_template_service/__init__.py b/examples/ad_manager/v202105/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/creative_template_service/__init__.py rename to examples/ad_manager/v202105/creative_template_service/__init__.py diff --git a/examples/ad_manager/v202008/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202105/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v202008/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202105/creative_template_service/get_all_creative_templates.py index dfa54f10..49ef7c83 100755 --- a/examples/ad_manager/v202008/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202105/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202008') + 'CreativeTemplateService', version='v202105') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v202008/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202105/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v202008/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202105/creative_template_service/get_system_defined_creative_templates.py index 08b1a966..db8ef20e 100755 --- a/examples/ad_manager/v202008/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202105/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202008') + 'CreativeTemplateService', version='v202105') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v202008/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202105/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v202008/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202105/creative_wrapper_service/create_creative_wrappers.py index 1b143da6..1549fe4b 100755 --- a/examples/ad_manager/v202008/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202105/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202008') + version='v202105') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v202008/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202105/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v202008/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202105/creative_wrapper_service/deactivate_creative_wrapper.py index df59b6d4..4ec35bfc 100755 --- a/examples/ad_manager/v202008/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202105/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202008') + version='v202105') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202008/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202105/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202008/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202105/creative_wrapper_service/get_active_creative_wrappers.py index 2a3e5572..cde2a3f6 100755 --- a/examples/ad_manager/v202008/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202105/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202008') + 'CreativeWrapperService', version='v202105') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202008/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202105/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202008/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202105/creative_wrapper_service/get_all_creative_wrappers.py index a243be2a..021eeb07 100755 --- a/examples/ad_manager/v202008/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202105/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202008') + 'CreativeWrapperService', version='v202105') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v202008/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202105/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v202008/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202105/creative_wrapper_service/update_creative_wrappers.py index fd6f17eb..d14b4542 100755 --- a/examples/ad_manager/v202008/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202105/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202008') + version='v202105') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v202008/custom_field_service/__init__.py b/examples/ad_manager/v202105/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/custom_field_service/__init__.py rename to examples/ad_manager/v202105/custom_field_service/__init__.py diff --git a/examples/ad_manager/v202008/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202105/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v202008/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202105/custom_field_service/create_custom_field_options.py index 6c549904..05f482dd 100755 --- a/examples/ad_manager/v202008/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202105/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202008') + 'CustomFieldService', version='v202105') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v202008/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202105/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v202008/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202105/custom_field_service/create_custom_fields.py index 1c1aebb2..910afa45 100755 --- a/examples/ad_manager/v202008/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202105/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202008') + 'CustomFieldService', version='v202105') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v202008/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202105/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v202008/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202105/custom_field_service/deactivate_all_line_item_custom_fields.py index de6e97ff..8f5de91f 100755 --- a/examples/ad_manager/v202008/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202105/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202008') + 'CustomFieldService', version='v202105') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202008/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202105/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v202008/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202105/custom_field_service/get_all_custom_fields.py index a2a9e327..1bc0f567 100755 --- a/examples/ad_manager/v202008/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202105/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202008') + 'CustomFieldService', version='v202105') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v202008/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202105/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v202008/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202105/custom_field_service/get_custom_fields_for_line_items.py index a2d052e9..e93bc969 100755 --- a/examples/ad_manager/v202008/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202105/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202008') + 'CustomFieldService', version='v202105') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v202008/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202105/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v202008/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202105/custom_field_service/set_line_item_custom_field_value.py index 185292d4..121ddb9d 100755 --- a/examples/ad_manager/v202008/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202105/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v202008') + 'CustomFieldService', version='v202105') - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v202008') + custom_field_statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v202008') + ad_manager.StatementBuilder(version='v202105') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v202008') + line_item_statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v202008/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202105/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v202008/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202105/custom_field_service/update_custom_fields.py index 3c468a43..ac3f86b5 100755 --- a/examples/ad_manager/v202008/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202105/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202008') + 'CustomFieldService', version='v202105') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v202008/custom_targeting_service/__init__.py b/examples/ad_manager/v202105/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/custom_targeting_service/__init__.py rename to examples/ad_manager/v202105/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v202008/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202105/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v202008/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202105/custom_targeting_service/create_custom_targeting_keys_and_values.py index bb7953e0..f61f3c3b 100755 --- a/examples/ad_manager/v202008/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202105/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202008') + 'CustomTargetingService', version='v202105') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_keys.py index 5a7e6a0a..3a059fd4 100755 --- a/examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202008') + 'CustomTargetingService', version='v202105') - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v202008') + key_statement = (ad_manager.StatementBuilder(version='v202105') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py index 530746e2..734917d6 100755 --- a/examples/ad_manager/v202008/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202008') + 'CustomTargetingService', version='v202105') - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [value['id'] for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v202008') + value_statement = (ad_manager.StatementBuilder(version='v202105') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v202008/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202105/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202008/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202105/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 56ca9285..5dd87b0b 100755 --- a/examples/ad_manager/v202008/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202105/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202008') + 'CustomTargetingService', version='v202105') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v202008') + targeting_key_statement = ad_manager.StatementBuilder(version='v202105') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v202008/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202105/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202008/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202105/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 87cab57e..2121cbb2 100755 --- a/examples/ad_manager/v202008/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202105/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202008') + 'CustomTargetingService', version='v202105') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v202008') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202105') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_keys.py index f557d748..f9fc8950 100755 --- a/examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202008') + 'CustomTargetingService', version='v202105') - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_values.py index 87b8d040..6d4c3c20 100755 --- a/examples/ad_manager/v202008/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202008') + 'CustomTargetingService', version='v202105') - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v202008/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202105/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v202008/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202105/forecast_service/get_availability_forecast.py index fc3e8ba7..dd44cfaa 100755 --- a/examples/ad_manager/v202008/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202105/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202008') - network_service = client.GetService('NetworkService', version='v202008') + forecast_service = client.GetService('ForecastService', version='v202105') + network_service = client.GetService('NetworkService', version='v202105') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202008/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202105/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v202008/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202105/forecast_service/get_availability_forecast_for_line_item.py index 98dc503b..aabcd344 100755 --- a/examples/ad_manager/v202008/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202105/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202008') + forecast_service = client.GetService('ForecastService', version='v202105') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v202008/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202105/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v202008/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202105/forecast_service/get_delivery_forecast_for_line_items.py index 2e01d79b..02991d5a 100755 --- a/examples/ad_manager/v202008/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202105/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202008') + forecast_service = client.GetService('ForecastService', version='v202105') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v202105/forecast_service/get_traffic_data.py b/examples/ad_manager/v202105/forecast_service/get_traffic_data.py new file mode 100755 index 00000000..b3741bda --- /dev/null +++ b/examples/ad_manager/v202105/forecast_service/get_traffic_data.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python +# +# Copyright 2020, Google LLC +# +# 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 the forecasted run-of-network traffic data.""" + + +import datetime + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate service. + forecast_service = client.GetService('ForecastService', version='v202105') + network_service = client.GetService('NetworkService', version='v202105') + + # get the root ad unit ID to target the entire network. + root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] + + # Create a start date that's 7 days in the past and an end date that's 7 days + # in the future. + today = datetime.date.today() + start_date = today - datetime.timedelta(days=7) + end_date = today + datetime.timedelta(days=7) + + # Create targeting. + targeting = { + 'inventoryTargeting': { + 'targetedAdUnits': [ + { + 'includeDescendants': True, + 'adUnitId': root_ad_unit_id, + } + ] + } + } + + # Request the traffic forecast data. + traffic_data = forecast_service.getTrafficData({ + 'targeting': targeting, + 'requestedDateRange': { + 'startDate': start_date, + 'endDate': end_date + } + }) + + # Display historical data. + historical_time_series = traffic_data['historicalTimeSeries'] + if historical_time_series is None: + print('No historical data to display.') + else: + historical_start_date, historical_end_date = GetDatesFromForecastTimeSeries( + historical_time_series) + + print('Historical Data:') + offset = 0 + current_date = historical_start_date + while current_date <= historical_end_date: + print('%s: %d' % (current_date.isoformat(), + historical_time_series['values'][offset])) + offset += 1 + current_date = historical_start_date + datetime.timedelta(days=offset) + + # Display forecasted data. + forecasted_time_series = traffic_data['forecastedTimeSeries'] + if forecasted_time_series is None: + print('No forecasted data to display.') + else: + forecasted_start_date, forecasted_end_date = GetDatesFromForecastTimeSeries( + forecasted_time_series) + + print('Forecasted Data:') + offset = 0 + current_date = forecasted_start_date + while current_date <= forecasted_end_date: + print('%s: %d' % (current_date.isoformat(), + forecasted_time_series['values'][offset])) + offset += 1 + current_date = forecasted_start_date + datetime.timedelta(days=offset) + + +def GetDatesFromForecastTimeSeries(time_series): + """Creates datetime.date objects from a forecast time series object. + + Args: + time_series: The forecast time series containing start and end date info. + + Returns: + A tuple of datetime.date objects, the first representing the start date and + the second representing the end date. + """ + date_range = time_series['timeSeriesDateRange'] + start_date = datetime.date( + date_range['startDate']['year'], + date_range['startDate']['month'], + date_range['startDate']['day'] + ) + end_date = datetime.date( + date_range['endDate']['year'], + date_range['endDate']['month'], + date_range['endDate']['day'] + ) + return start_date, end_date + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202008/inventory_service/__init__.py b/examples/ad_manager/v202105/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/inventory_service/__init__.py rename to examples/ad_manager/v202105/inventory_service/__init__.py diff --git a/examples/ad_manager/v202008/inventory_service/archive_ad_units.py b/examples/ad_manager/v202105/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v202008/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202105/inventory_service/archive_ad_units.py index 7457a6af..6b524b3c 100755 --- a/examples/ad_manager/v202008/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202105/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202008') + inventory_service = client.GetService('InventoryService', version='v202105') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v202008/inventory_service/create_ad_units.py b/examples/ad_manager/v202105/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v202008/inventory_service/create_ad_units.py rename to examples/ad_manager/v202105/inventory_service/create_ad_units.py index 31a09c1b..0778f223 100755 --- a/examples/ad_manager/v202008/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202105/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202008') + inventory_service = client.GetService('InventoryService', version='v202105') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v202008/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202105/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v202008/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202105/inventory_service/get_ad_unit_hierarchy.py index 8910487a..d9e31a7c 100755 --- a/examples/ad_manager/v202008/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202105/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202008') - inventory_service = client.GetService('InventoryService', version='v202008') + network_service = client.GetService('NetworkService', version='v202105') + inventory_service = client.GetService('InventoryService', version='v202105') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v202008/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202105/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v202008/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202105/inventory_service/get_all_ad_unit_sizes.py index 676d17c2..2edd001b 100755 --- a/examples/ad_manager/v202008/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202105/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v202008') + 'InventoryService', version='v202105') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v202008/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202105/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v202008/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202105/inventory_service/get_all_ad_units.py index 6b445d3c..5dac2cec 100755 --- a/examples/ad_manager/v202008/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202105/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v202008') + ad_unit_service = client.GetService('InventoryService', version='v202105') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v202008/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202105/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v202008/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202105/inventory_service/get_top_level_ad_units.py index af5543d7..fc321baf 100755 --- a/examples/ad_manager/v202008/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202105/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202008') - inventory_service = client.GetService('InventoryService', version='v202008') + network_service = client.GetService('NetworkService', version='v202105') + inventory_service = client.GetService('InventoryService', version='v202105') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v202008/inventory_service/update_ad_units.py b/examples/ad_manager/v202105/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v202008/inventory_service/update_ad_units.py rename to examples/ad_manager/v202105/inventory_service/update_ad_units.py index c13a3979..91c8f99f 100755 --- a/examples/ad_manager/v202008/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202105/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202008') + inventory_service = client.GetService('InventoryService', version='v202105') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v202008/label_service/__init__.py b/examples/ad_manager/v202105/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/label_service/__init__.py rename to examples/ad_manager/v202105/label_service/__init__.py diff --git a/examples/ad_manager/v202008/label_service/create_labels.py b/examples/ad_manager/v202105/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v202008/label_service/create_labels.py rename to examples/ad_manager/v202105/label_service/create_labels.py index bde7b3b4..8cea4a42 100755 --- a/examples/ad_manager/v202008/label_service/create_labels.py +++ b/examples/ad_manager/v202105/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202008') + label_service = client.GetService('LabelService', version='v202105') # Create label objects. labels = [] diff --git a/examples/ad_manager/v202008/label_service/deactivate_labels.py b/examples/ad_manager/v202105/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v202008/label_service/deactivate_labels.py rename to examples/ad_manager/v202105/label_service/deactivate_labels.py index c7ae1f3f..8fe843f6 100755 --- a/examples/ad_manager/v202008/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202105/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202008') + label_service = client.GetService('LabelService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202008/label_service/get_active_labels.py b/examples/ad_manager/v202105/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v202008/label_service/get_active_labels.py rename to examples/ad_manager/v202105/label_service/get_active_labels.py index 01bb66d8..982f0e65 100755 --- a/examples/ad_manager/v202008/label_service/get_active_labels.py +++ b/examples/ad_manager/v202105/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202008') + label_service = client.GetService('LabelService', version='v202105') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202008/label_service/get_all_labels.py b/examples/ad_manager/v202105/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v202008/label_service/get_all_labels.py rename to examples/ad_manager/v202105/label_service/get_all_labels.py index fd473541..718fff8f 100755 --- a/examples/ad_manager/v202008/label_service/get_all_labels.py +++ b/examples/ad_manager/v202105/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202008') + label_service = client.GetService('LabelService', version='v202105') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v202008/label_service/update_labels.py b/examples/ad_manager/v202105/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v202008/label_service/update_labels.py rename to examples/ad_manager/v202105/label_service/update_labels.py index 7da1be35..724e2ba3 100755 --- a/examples/ad_manager/v202008/label_service/update_labels.py +++ b/examples/ad_manager/v202105/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202008') + label_service = client.GetService('LabelService', version='v202105') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202008/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202105/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202105/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v202008/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202105/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v202008/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202105/line_item_creative_association_service/create_licas.py index 163789a2..67286d56 100755 --- a/examples/ad_manager/v202008/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202105/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202008') + 'LineItemCreativeAssociationService', version='v202105') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v202008/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202105/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v202008/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202105/line_item_creative_association_service/deactivate_licas.py index fa0482bc..d8d46da4 100755 --- a/examples/ad_manager/v202008/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202105/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202008') + 'LineItemCreativeAssociationService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v202008/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202105/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v202008/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202105/line_item_creative_association_service/get_all_licas.py index 6b1d9306..92bb7e62 100755 --- a/examples/ad_manager/v202008/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202105/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202008') + 'LineItemCreativeAssociationService', version='v202105') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v202008/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202105/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v202008/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202105/line_item_creative_association_service/get_licas_for_line_item.py index 0a1eb90c..2b43e5c1 100755 --- a/examples/ad_manager/v202008/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202105/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202008') + 'LineItemCreativeAssociationService', version='v202105') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v202105/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202105/line_item_creative_association_service/push_creative_to_devices.py new file mode 100755 index 00000000..1bb2ba5a --- /dev/null +++ b/examples/ad_manager/v202105/line_item_creative_association_service/push_creative_to_devices.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2021, Google LLC +# +# 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 pushes a LICA to a linked device for preview. + +To determine which linked devices exist, use the PublisherQueryLanguageService +linked_device table. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the associated line item id and creative id to push, and set the linked +# device id where it will be pushed. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' +CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' +LINKED_DEVICE_ID = 'INSERT_LINKED_DEVICE_ID_HERE' + + +def main(client, line_item_id, creative_id, linked_device_id): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v202105') + + # Create query to select a single linked device. + # Linked devices can be read from the linked_device PQL table. + statement = (ad_manager.StatementBuilder(version='v202105') + .Where('id = :linkedDeviceId') + .WithBindVariable('linkedDeviceId', int(linked_device_id))) + + # Make call to push creatives to devices. + result = lica_service.pushCreativeToDevices(statement.ToStatement(), { + 'lineItemId': line_item_id, + 'creativeId': creative_id + }) + + # Display results. + if result and int(result['numChanges']) > 0: + print('Pushed creatives to %s devices.' % result['numChanges']) + else: + print('No creatives were pushed.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, CREATIVE_ID, LINKED_DEVICE_ID) diff --git a/examples/ad_manager/v202008/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202105/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v202008/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202105/line_item_creative_association_service/update_licas.py index 74e750ef..f7f7db31 100755 --- a/examples/ad_manager/v202008/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202105/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202008') + 'LineItemCreativeAssociationService', version='v202105') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v202008/line_item_service/__init__.py b/examples/ad_manager/v202105/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/line_item_service/__init__.py rename to examples/ad_manager/v202105/line_item_service/__init__.py diff --git a/examples/ad_manager/v202008/line_item_service/activate_line_items.py b/examples/ad_manager/v202105/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v202008/line_item_service/activate_line_items.py rename to examples/ad_manager/v202105/line_item_service/activate_line_items.py index aa95266c..b0064816 100755 --- a/examples/ad_manager/v202008/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202105/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202008/line_item_service/create_line_items.py b/examples/ad_manager/v202105/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v202008/line_item_service/create_line_items.py rename to examples/ad_manager/v202105/line_item_service/create_line_items.py index 06429da6..54940710 100755 --- a/examples/ad_manager/v202008/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202105/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202008/line_item_service/create_video_line_item.py b/examples/ad_manager/v202105/line_item_service/create_video_line_item.py similarity index 98% rename from examples/ad_manager/v202008/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202105/line_item_service/create_video_line_item.py index 5dfa1cb0..bc9c6df3 100755 --- a/examples/ad_manager/v202008/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202105/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) @@ -100,6 +100,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, }], 'environmentType': 'VIDEO_PLAYER', 'companionDeliveryOption': 'OPTIONAL', + 'videoMaxDuration': 15000, 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'SPONSORSHIP', 'endDateTime': end_datetime, diff --git a/examples/ad_manager/v202008/line_item_service/get_all_line_items.py b/examples/ad_manager/v202105/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v202008/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202105/line_item_service/get_all_line_items.py index a7171ad6..ae4803ce 100755 --- a/examples/ad_manager/v202008/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202105/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v202008/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202105/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v202008/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202105/line_item_service/get_line_items_that_need_creatives.py index ef5d6b0b..6544cc20 100755 --- a/examples/ad_manager/v202008/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202105/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v202008/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202105/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v202008/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202105/line_item_service/get_recently_updated_line_items.py index c8f4e618..1606e15e 100755 --- a/examples/ad_manager/v202008/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202105/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202008/line_item_service/pause_line_items.py b/examples/ad_manager/v202105/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v202008/line_item_service/pause_line_items.py rename to examples/ad_manager/v202105/line_item_service/pause_line_items.py index 8c302cf5..ce445eff 100755 --- a/examples/ad_manager/v202008/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202105/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v202008/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202105/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v202008/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202105/line_item_service/target_custom_criteria.py index 9e22b59c..c16cd8a2 100755 --- a/examples/ad_manager/v202008/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202105/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/line_item_service/update_line_items.py b/examples/ad_manager/v202105/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v202008/line_item_service/update_line_items.py rename to examples/ad_manager/v202105/line_item_service/update_line_items.py index 190c522d..58e765e1 100755 --- a/examples/ad_manager/v202008/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202105/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202008') + line_item_service = client.GetService('LineItemService', version='v202105') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v202008/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202105/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202008/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202105/live_stream_event_service/activate_live_stream_events.py index 82d485a9..9d836e20 100755 --- a/examples/ad_manager/v202008/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202105/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202008') + 'LiveStreamEventService', version='v202105') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v202008/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202105/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v202008/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202105/live_stream_event_service/create_live_stream_events.py index bf67cf5a..9c72ff7a 100755 --- a/examples/ad_manager/v202008/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202105/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v202008') + 'LiveStreamEventService', version='v202105') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v202008/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202105/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v202008/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202105/live_stream_event_service/get_all_live_stream_events.py index 52e72790..14edb382 100755 --- a/examples/ad_manager/v202008/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202105/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202008') + 'LiveStreamEventService', version='v202105') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v202008/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202105/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v202008/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202105/live_stream_event_service/register_sessions_for_monitoring.py index fb2098fd..93485a4c 100755 --- a/examples/ad_manager/v202008/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202105/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202008') + 'LiveStreamEventService', version='v202105') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v202008/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202105/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202008/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202105/live_stream_event_service/update_live_stream_events.py index 4ec6d513..f1d81435 100755 --- a/examples/ad_manager/v202008/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202105/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v202008') + 'LiveStreamEventService', version='v202105') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v202008/native_style_service/__init__.py b/examples/ad_manager/v202105/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/native_style_service/__init__.py rename to examples/ad_manager/v202105/native_style_service/__init__.py diff --git a/examples/ad_manager/v202008/native_style_service/create_native_styles.py b/examples/ad_manager/v202105/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v202008/native_style_service/create_native_styles.py rename to examples/ad_manager/v202105/native_style_service/create_native_styles.py index de037b17..1eb83c18 100755 --- a/examples/ad_manager/v202008/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202105/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202008') + version='v202105') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v202008/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202105/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v202008/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202105/native_style_service/get_all_native_styles.py index 89654d30..51ef2c77 100755 --- a/examples/ad_manager/v202008/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202105/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202008') + version='v202105') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v202008/network_service/__init__.py b/examples/ad_manager/v202105/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/network_service/__init__.py rename to examples/ad_manager/v202105/network_service/__init__.py diff --git a/examples/ad_manager/v202008/network_service/get_all_networks.py b/examples/ad_manager/v202105/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v202008/network_service/get_all_networks.py rename to examples/ad_manager/v202105/network_service/get_all_networks.py index 8ecd46ea..915a26c9 100755 --- a/examples/ad_manager/v202008/network_service/get_all_networks.py +++ b/examples/ad_manager/v202105/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202008') + network_service = client.GetService('NetworkService', version='v202105') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v202008/network_service/get_current_network.py b/examples/ad_manager/v202105/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v202008/network_service/get_current_network.py rename to examples/ad_manager/v202105/network_service/get_current_network.py index 10c9a3c8..67d6b416 100755 --- a/examples/ad_manager/v202008/network_service/get_current_network.py +++ b/examples/ad_manager/v202105/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202008') + network_service = client.GetService('NetworkService', version='v202105') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202105/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202105/network_service/get_default_third_party_data_declaration.py new file mode 100755 index 00000000..f5109926 --- /dev/null +++ b/examples/ad_manager/v202105/network_service/get_default_third_party_data_declaration.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python +# +# Copyright 2020, Google LLC +# +# 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 the network's default third party data declarations.""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + + +def main(client): + # Initialize appropriate services. + network_service = client.GetService('NetworkService', version='v202105') + pql_service = client.GetService('PublisherQueryLanguageService', + version='v202105') + + # Fetch the default third party data declarations. + declarations = network_service.getDefaultThirdPartyDataDeclaration() + + # Display the results. + if declarations is None: + print('No default ad technology partners have been set on this network.') + elif (declarations['declarationType'] == 'NONE' or + not declarations['thirdPartyCompanyIds']): + print('This network has specified that there are no ad technology providers' + ' associated with its reservation creatives by default.') + else: + print('This network has specified %d ad technology provider(s) associated' + ' with its reservation creatives by default:' % + len(declarations['thirdPartyCompanyIds'])) + + # In this case, there are third party companies to be displayed, so fetch + # the company names from the Rich_Media_Ad_Company PQL table. + statement = (ad_manager.StatementBuilder(version='v202105') + .Select('Id, Name') + .From('Rich_Media_Ad_Company') + .Where('Id IN (:company_ids)') + .WithBindVariable('company_ids', + declarations['thirdPartyCompanyIds'])) + + while True: + response = pql_service.select(statement.ToStatement()) + if 'rows' in response and len(response['rows']): + for company in response['rows']: + print('Name: %s, id: %s' % (company['values'][1]['value'], + company['values'][0]['value'])) + statement.offset += statement.limit + else: + break + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202008/network_service/make_test_network.py b/examples/ad_manager/v202105/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v202008/network_service/make_test_network.py rename to examples/ad_manager/v202105/network_service/make_test_network.py index 66b848e0..5ad1a5d6 100755 --- a/examples/ad_manager/v202008/network_service/make_test_network.py +++ b/examples/ad_manager/v202105/network_service/make_test_network.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202008') + network_service = client.GetService('NetworkService', version='v202105') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v202008/order_service/__init__.py b/examples/ad_manager/v202105/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/order_service/__init__.py rename to examples/ad_manager/v202105/order_service/__init__.py diff --git a/examples/ad_manager/v202008/order_service/approve_orders.py b/examples/ad_manager/v202105/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v202008/order_service/approve_orders.py rename to examples/ad_manager/v202105/order_service/approve_orders.py index 25e0eb82..381bd2ec 100755 --- a/examples/ad_manager/v202008/order_service/approve_orders.py +++ b/examples/ad_manager/v202105/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202008') + order_service = client.GetService('OrderService', version='v202105') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v202008/order_service/create_orders.py b/examples/ad_manager/v202105/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v202008/order_service/create_orders.py rename to examples/ad_manager/v202105/order_service/create_orders.py index 7b81bcd0..b15cd23c 100755 --- a/examples/ad_manager/v202008/order_service/create_orders.py +++ b/examples/ad_manager/v202105/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202008') + order_service = client.GetService('OrderService', version='v202105') # Create order objects. orders = [] diff --git a/examples/ad_manager/v202008/order_service/get_all_orders.py b/examples/ad_manager/v202105/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v202008/order_service/get_all_orders.py rename to examples/ad_manager/v202105/order_service/get_all_orders.py index 7be5cdcc..5fc924cd 100755 --- a/examples/ad_manager/v202008/order_service/get_all_orders.py +++ b/examples/ad_manager/v202105/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202008') + order_service = client.GetService('OrderService', version='v202105') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v202008/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202105/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v202008/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202105/order_service/get_orders_starting_soon.py index 9699ba36..679984ed 100755 --- a/examples/ad_manager/v202008/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202105/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202008') + order_service = client.GetService('OrderService', version='v202105') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v202008/order_service/update_orders.py b/examples/ad_manager/v202105/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v202008/order_service/update_orders.py rename to examples/ad_manager/v202105/order_service/update_orders.py index 66646b99..965fa9f7 100755 --- a/examples/ad_manager/v202008/order_service/update_orders.py +++ b/examples/ad_manager/v202105/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202008') + order_service = client.GetService('OrderService', version='v202105') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202008/placement_service/create_placements.py b/examples/ad_manager/v202105/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v202008/placement_service/create_placements.py rename to examples/ad_manager/v202105/placement_service/create_placements.py index 5ad1d4f3..9d8ef572 100755 --- a/examples/ad_manager/v202008/placement_service/create_placements.py +++ b/examples/ad_manager/v202105/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202008') - inventory_service = client.GetService('InventoryService', version='v202008') + placement_service = client.GetService('PlacementService', version='v202105') + inventory_service = client.GetService('InventoryService', version='v202105') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v202008/placement_service/deactivate_placements.py b/examples/ad_manager/v202105/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v202008/placement_service/deactivate_placements.py rename to examples/ad_manager/v202105/placement_service/deactivate_placements.py index 1cb5124a..9e224b21 100755 --- a/examples/ad_manager/v202008/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202105/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202008') + placement_service = client.GetService('PlacementService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/placement_service/get_active_placements.py b/examples/ad_manager/v202105/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v202008/placement_service/get_active_placements.py rename to examples/ad_manager/v202105/placement_service/get_active_placements.py index 7ee9edc7..957aa365 100755 --- a/examples/ad_manager/v202008/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202105/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202008') + placement_service = client.GetService('PlacementService', version='v202105') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202008/placement_service/get_all_placements.py b/examples/ad_manager/v202105/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v202008/placement_service/get_all_placements.py rename to examples/ad_manager/v202105/placement_service/get_all_placements.py index 0fcdaf3a..378fd81c 100755 --- a/examples/ad_manager/v202008/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202105/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202008') + placement_service = client.GetService('PlacementService', version='v202105') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v202008/placement_service/update_placements.py b/examples/ad_manager/v202105/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v202008/placement_service/update_placements.py rename to examples/ad_manager/v202105/placement_service/update_placements.py index ffae1a91..977155d4 100755 --- a/examples/ad_manager/v202008/placement_service/update_placements.py +++ b/examples/ad_manager/v202105/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202008') + placement_service = client.GetService('PlacementService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v202008/proposal_line_item_service/__init__.py b/examples/ad_manager/v202105/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202105/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v202008/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202105/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202008/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202105/proposal_line_item_service/archive_proposal_line_items.py index a81991a7..61422f63 100755 --- a/examples/ad_manager/v202008/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202105/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202008') + 'ProposalLineItemService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202105/proposal_line_item_service/create_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202008/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202105/proposal_line_item_service/create_proposal_line_items.py index 3462e0e3..e561a0fe 100755 --- a/examples/ad_manager/v202008/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202105/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202008') - network_service = client.GetService('NetworkService', version='v202008') + 'ProposalLineItemService', version='v202105') + network_service = client.GetService('NetworkService', version='v202105') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) @@ -42,11 +42,6 @@ def main(client, proposal_id): # Create a single programmatic proposal line item. proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for proposal line items. 'name': 'Proposal line item #%s' % uuid.uuid4(), 'proposalId': proposal_id, @@ -56,6 +51,9 @@ def main(client, proposal_id): 'adUnitId': root_ad_unit_id } }, + 'requestPlatformTargeting': { + 'targetedRequestPlatforms': ['BROWSER'] + }, # Target Display environment by excluding Mobile Apps. # DeviceCapabilities can be obtained though the Device_Capability PQL # table: diff --git a/examples/ad_manager/v202008/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202105/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202008/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202105/proposal_line_item_service/get_all_proposal_line_items.py index 3ab16a19..a1145671 100755 --- a/examples/ad_manager/v202008/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202105/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202008') + 'ProposalLineItemService', version='v202105') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v202008/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202105/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v202008/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202105/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 07478775..b5718665 100755 --- a/examples/ad_manager/v202008/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202105/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202008') + 'ProposalLineItemService', version='v202105') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v202008/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202105/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202008/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202105/proposal_line_item_service/update_proposal_line_items.py index 1194ff47..2a8f0f82 100755 --- a/examples/ad_manager/v202008/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202105/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202008') + 'ProposalLineItemService', version='v202105') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/proposal_service/__init__.py b/examples/ad_manager/v202105/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/proposal_service/__init__.py rename to examples/ad_manager/v202105/proposal_service/__init__.py diff --git a/examples/ad_manager/v202008/proposal_service/create_proposals.py b/examples/ad_manager/v202105/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v202008/proposal_service/create_proposals.py rename to examples/ad_manager/v202105/proposal_service/create_proposals.py index bed4a69d..43178b9d 100755 --- a/examples/ad_manager/v202008/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202105/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v202008') + proposal_service = client.GetService('ProposalService', version='v202105') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v202008/proposal_service/get_all_proposals.py b/examples/ad_manager/v202105/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v202008/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202105/proposal_service/get_all_proposals.py index e91f7141..4b0030ef 100755 --- a/examples/ad_manager/v202008/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202105/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202008') + proposal_service = client.GetService('ProposalService', version='v202105') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v202008/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202105/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v202008/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202105/proposal_service/get_marketplace_comments.py index 4fc3aeea..809fe4a7 100755 --- a/examples/ad_manager/v202008/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202105/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v202008') + 'ProposalService', version='v202105') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v202008/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202105/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v202008/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202105/proposal_service/get_proposals_awaiting_seller_review.py index a0ac3426..e3f2cee3 100755 --- a/examples/ad_manager/v202008/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202105/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202008') + proposal_service = client.GetService('ProposalService', version='v202105') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v202008/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202105/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v202008/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202105/proposal_service/request_buyers_acceptance.py index 7b96a0fc..095a71ab 100755 --- a/examples/ad_manager/v202008/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202105/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202008') + proposal_service = client.GetService('ProposalService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v202008/proposal_service/update_proposals.py b/examples/ad_manager/v202105/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v202008/proposal_service/update_proposals.py rename to examples/ad_manager/v202105/proposal_service/update_proposals.py index 27cfe48a..6a088033 100755 --- a/examples/ad_manager/v202008/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202105/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202008') + proposal_service = client.GetService('ProposalService', version='v202105') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/publisher_query_language_service/__init__.py b/examples/ad_manager/v202105/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202105/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v202008/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202105/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v202008/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202105/publisher_query_language_service/fetch_match_tables.py index e05509a6..e9f4a824 100755 --- a/examples/ad_manager/v202008/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202105/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202008/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202105/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v202008/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202105/publisher_query_language_service/get_all_browsers.py index 09756b79..0214c316 100755 --- a/examples/ad_manager/v202008/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202105/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v202008/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202105/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v202008/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202105/publisher_query_language_service/get_all_programmatic_buyers.py index 3a76222d..f18dc303 100755 --- a/examples/ad_manager/v202008/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202105/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202008') + data_downloader = client.GetDataDownloader(version='v202105') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202008/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202105/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v202008/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202105/publisher_query_language_service/get_geo_targets.py index 230b9072..7719f042 100755 --- a/examples/ad_manager/v202008/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202105/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v202008/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202105/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v202008/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202105/publisher_query_language_service/get_line_items_named_like.py index 50e6c97b..0d872a69 100755 --- a/examples/ad_manager/v202008/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202105/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202008/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202105/publisher_query_language_service/get_mcm_earnings.py similarity index 97% rename from examples/ad_manager/v202008/publisher_query_language_service/get_mcm_earnings.py rename to examples/ad_manager/v202105/publisher_query_language_service/get_mcm_earnings.py index 5626890a..96f3bc08 100755 --- a/examples/ad_manager/v202008/publisher_query_language_service/get_mcm_earnings.py +++ b/examples/ad_manager/v202105/publisher_query_language_service/get_mcm_earnings.py @@ -26,7 +26,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202008') + data_downloader = client.GetDataDownloader(version='v202105') with tempfile.NamedTemporaryFile( prefix='mcm_earnings_', diff --git a/examples/ad_manager/v202008/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202105/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v202008/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202105/publisher_query_language_service/get_recent_changes.py index bd02af2c..5ab40aaa 100755 --- a/examples/ad_manager/v202008/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202105/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v202008') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202105') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v202008/report_service/__init__.py b/examples/ad_manager/v202105/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/report_service/__init__.py rename to examples/ad_manager/v202105/report_service/__init__.py diff --git a/examples/ad_manager/v202008/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202105/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v202008/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202105/report_service/run_ad_exchange_report.py index 614fe565..c95f1c6d 100755 --- a/examples/ad_manager/v202008/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202105/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') # Create report job. report_job = { diff --git a/examples/ad_manager/v202008/report_service/run_delivery_report.py b/examples/ad_manager/v202105/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v202008/report_service/run_delivery_report.py rename to examples/ad_manager/v202105/report_service/run_delivery_report.py index 50c6f6ec..51991c2f 100755 --- a/examples/ad_manager/v202008/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202105/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202008/report_service/run_inventory_report.py b/examples/ad_manager/v202105/report_service/run_inventory_report.py similarity index 97% rename from examples/ad_manager/v202008/report_service/run_inventory_report.py rename to examples/ad_manager/v202105/report_service/run_inventory_report.py index 1932c00d..3c13a105 100755 --- a/examples/ad_manager/v202008/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202105/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') # Create report job. report_job = { diff --git a/examples/ad_manager/v202008/report_service/run_reach_report.py b/examples/ad_manager/v202105/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v202008/report_service/run_reach_report.py rename to examples/ad_manager/v202105/report_service/run_reach_report.py index f348c9f2..dfb7fc6a 100755 --- a/examples/ad_manager/v202008/report_service/run_reach_report.py +++ b/examples/ad_manager/v202105/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') # Create report job. report_job = { diff --git a/examples/ad_manager/v202008/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202105/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v202008/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202105/report_service/run_report_and_create_match_table.py index 7afd3534..1b009907 100755 --- a/examples/ad_manager/v202008/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202105/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202008/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202105/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v202008/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202105/report_service/run_report_with_custom_fields.py index d7b9fcf0..33441d40 100755 --- a/examples/ad_manager/v202008/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202105/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') # Create report job. report_job = { diff --git a/examples/ad_manager/v202008/report_service/run_sales_report.py b/examples/ad_manager/v202105/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v202008/report_service/run_sales_report.py rename to examples/ad_manager/v202105/report_service/run_sales_report.py index 4f4404d4..7f61a979 100755 --- a/examples/ad_manager/v202008/report_service/run_sales_report.py +++ b/examples/ad_manager/v202105/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') # Create report job. report_job = { diff --git a/examples/ad_manager/v202008/report_service/run_saved_query.py b/examples/ad_manager/v202105/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v202008/report_service/run_saved_query.py rename to examples/ad_manager/v202105/report_service/run_saved_query.py index 248af4eb..fcd36b83 100755 --- a/examples/ad_manager/v202008/report_service/run_saved_query.py +++ b/examples/ad_manager/v202105/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v202008') + report_service = client.GetService('ReportService', version='v202105') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202008') + report_downloader = client.GetDataDownloader(version='v202105') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202008/site_service/create_sites.py b/examples/ad_manager/v202105/site_service/create_sites.py similarity index 96% rename from examples/ad_manager/v202008/site_service/create_sites.py rename to examples/ad_manager/v202105/site_service/create_sites.py index 9574075b..e011f51d 100755 --- a/examples/ad_manager/v202008/site_service/create_sites.py +++ b/examples/ad_manager/v202105/site_service/create_sites.py @@ -27,8 +27,8 @@ def main(client, url, child_network_code): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202008') - site_service = client.GetService('SiteService', version='v202008') + network_service = client.GetService('NetworkService', version='v202105') + site_service = client.GetService('SiteService', version='v202105') # Check that the child network code is approved for MANAGE_INVENTORY by this # network. diff --git a/examples/ad_manager/v202008/site_service/get_all_sites.py b/examples/ad_manager/v202105/site_service/get_all_sites.py similarity index 92% rename from examples/ad_manager/v202008/site_service/get_all_sites.py rename to examples/ad_manager/v202105/site_service/get_all_sites.py index 2b4df6a9..ffd32a1e 100755 --- a/examples/ad_manager/v202008/site_service/get_all_sites.py +++ b/examples/ad_manager/v202105/site_service/get_all_sites.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202008') + site_service = client.GetService('SiteService', version='v202105') # Create a statement to select Sites. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small number of sites at a time, paging through until all sites # have been retrieved. diff --git a/examples/ad_manager/v202008/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202105/site_service/get_sites_requiring_approval.py similarity index 92% rename from examples/ad_manager/v202008/site_service/get_sites_requiring_approval.py rename to examples/ad_manager/v202105/site_service/get_sites_requiring_approval.py index 0de6bad5..9eb1bf10 100755 --- a/examples/ad_manager/v202008/site_service/get_sites_requiring_approval.py +++ b/examples/ad_manager/v202105/site_service/get_sites_requiring_approval.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202008') + site_service = client.GetService('SiteService', version='v202105') # Create a statement to select Sites needing approval. - statement = ad_manager.StatementBuilder(version='v202008').Where( + statement = ad_manager.StatementBuilder(version='v202105').Where( "approvalStatus = 'REQUIRES_REVIEW'") # Retrieve a small number of sites at a time, paging through until all sites diff --git a/examples/ad_manager/v202008/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202105/site_service/submit_sites_for_approval.py similarity index 91% rename from examples/ad_manager/v202008/site_service/submit_sites_for_approval.py rename to examples/ad_manager/v202105/site_service/submit_sites_for_approval.py index 60b7fe79..e83411fa 100755 --- a/examples/ad_manager/v202008/site_service/submit_sites_for_approval.py +++ b/examples/ad_manager/v202105/site_service/submit_sites_for_approval.py @@ -25,10 +25,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202008') + site_service = client.GetService('SiteService', version='v202105') # Create a statement to select Site. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :id') .WithBindVariable('id', SITE_ID)) diff --git a/examples/ad_manager/v202008/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202105/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202105/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v202008/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202105/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v202008/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202105/suggested_ad_unit_service/approve_all_suggested_ad_units.py index a49ebc8a..eedffa57 100755 --- a/examples/ad_manager/v202008/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202105/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202008') + 'SuggestedAdUnitService', version='v202105') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v202008/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202105/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202008/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202105/suggested_ad_unit_service/get_all_suggested_ad_units.py index 262cd996..7d301baa 100755 --- a/examples/ad_manager/v202008/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202105/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202008') + 'SuggestedAdUnitService', version='v202105') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v202008/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202105/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202008/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202105/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 53e8d9d6..ab202495 100755 --- a/examples/ad_manager/v202008/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202105/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202008') + 'SuggestedAdUnitService', version='v202105') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v202008/targeting_preset_service/__init__.py b/examples/ad_manager/v202105/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/targeting_preset_service/__init__.py rename to examples/ad_manager/v202105/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202008/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py similarity index 94% rename from examples/ad_manager/v202008/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py index 171a073e..754c1f63 100755 --- a/examples/ad_manager/v202008/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v202008') + 'TargetingPresetService', version='v202105') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. diff --git a/examples/ad_manager/v202008/team_service/__init__.py b/examples/ad_manager/v202105/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/team_service/__init__.py rename to examples/ad_manager/v202105/team_service/__init__.py diff --git a/examples/ad_manager/v202008/team_service/create_teams.py b/examples/ad_manager/v202105/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v202008/team_service/create_teams.py rename to examples/ad_manager/v202105/team_service/create_teams.py index da35bc62..fdec6f1f 100755 --- a/examples/ad_manager/v202008/team_service/create_teams.py +++ b/examples/ad_manager/v202105/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202008') + team_service = client.GetService('TeamService', version='v202105') # Create team objects. teams = [] diff --git a/examples/ad_manager/v202008/team_service/get_all_teams.py b/examples/ad_manager/v202105/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v202008/team_service/get_all_teams.py rename to examples/ad_manager/v202105/team_service/get_all_teams.py index 7bece16a..66925617 100755 --- a/examples/ad_manager/v202008/team_service/get_all_teams.py +++ b/examples/ad_manager/v202105/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202008') + team_service = client.GetService('TeamService', version='v202105') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v202008/team_service/update_teams.py b/examples/ad_manager/v202105/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v202008/team_service/update_teams.py rename to examples/ad_manager/v202105/team_service/update_teams.py index 48841e10..8316e9da 100755 --- a/examples/ad_manager/v202008/team_service/update_teams.py +++ b/examples/ad_manager/v202105/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202008') + team_service = client.GetService('TeamService', version='v202105') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v202008/user_service/__init__.py b/examples/ad_manager/v202105/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/user_service/__init__.py rename to examples/ad_manager/v202105/user_service/__init__.py diff --git a/examples/ad_manager/v202008/user_service/create_users.py b/examples/ad_manager/v202105/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v202008/user_service/create_users.py rename to examples/ad_manager/v202105/user_service/create_users.py index b2374c40..30b39b8f 100755 --- a/examples/ad_manager/v202008/user_service/create_users.py +++ b/examples/ad_manager/v202105/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202008') + user_service = client.GetService('UserService', version='v202105') # Create user objects. users = [ diff --git a/examples/ad_manager/v202008/user_service/deactivate_users.py b/examples/ad_manager/v202105/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v202008/user_service/deactivate_users.py rename to examples/ad_manager/v202105/user_service/deactivate_users.py index 5f22d9a9..76441dbd 100755 --- a/examples/ad_manager/v202008/user_service/deactivate_users.py +++ b/examples/ad_manager/v202105/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202008') + user_service = client.GetService('UserService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202008/user_service/get_all_roles.py b/examples/ad_manager/v202105/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v202008/user_service/get_all_roles.py rename to examples/ad_manager/v202105/user_service/get_all_roles.py index 2d9ef07f..1360136e 100755 --- a/examples/ad_manager/v202008/user_service/get_all_roles.py +++ b/examples/ad_manager/v202105/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202008') + user_service = client.GetService('UserService', version='v202105') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v202008/user_service/get_all_users.py b/examples/ad_manager/v202105/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v202008/user_service/get_all_users.py rename to examples/ad_manager/v202105/user_service/get_all_users.py index 0fee32ff..90e45233 100755 --- a/examples/ad_manager/v202008/user_service/get_all_users.py +++ b/examples/ad_manager/v202105/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202008') + user_service = client.GetService('UserService', version='v202105') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v202008/user_service/get_current_user.py b/examples/ad_manager/v202105/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v202008/user_service/get_current_user.py rename to examples/ad_manager/v202105/user_service/get_current_user.py index 2fc8d1fc..b65f44af 100755 --- a/examples/ad_manager/v202008/user_service/get_current_user.py +++ b/examples/ad_manager/v202105/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202008') + user_service = client.GetService('UserService', version='v202105') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v202008/user_service/get_user_by_email_address.py b/examples/ad_manager/v202105/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v202008/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202105/user_service/get_user_by_email_address.py index 42c4fa69..8ee112f4 100755 --- a/examples/ad_manager/v202008/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202105/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202008') + user_service = client.GetService('UserService', version='v202105') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v202008/user_service/update_users.py b/examples/ad_manager/v202105/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v202008/user_service/update_users.py rename to examples/ad_manager/v202105/user_service/update_users.py index cfc44fd2..138669e7 100755 --- a/examples/ad_manager/v202008/user_service/update_users.py +++ b/examples/ad_manager/v202105/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202008') + user_service = client.GetService('UserService', version='v202105') # Create query. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202008/user_team_association_service/__init__.py b/examples/ad_manager/v202105/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202008/user_team_association_service/__init__.py rename to examples/ad_manager/v202105/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v202008/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202105/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v202008/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202105/user_team_association_service/create_user_team_associations.py index fa7beea9..90567cc6 100755 --- a/examples/ad_manager/v202008/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202105/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202008') + 'UserTeamAssociationService', version='v202105') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v202008/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202105/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v202008/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202105/user_team_association_service/delete_user_team_associations.py index 1b3b8790..8972736d 100755 --- a/examples/ad_manager/v202008/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202105/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202008') + 'UserTeamAssociationService', version='v202105') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202008/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202105/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v202008/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202105/user_team_association_service/get_all_user_team_associations.py index 60830b38..d7f6f135 100755 --- a/examples/ad_manager/v202008/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202105/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202008') + 'UserTeamAssociationService', version='v202105') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v202008') + statement = ad_manager.StatementBuilder(version='v202105') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v202008/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202105/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v202008/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202105/user_team_association_service/get_user_team_associations_for_user.py index 4e4bcc49..f67e1264 100755 --- a/examples/ad_manager/v202008/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202105/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202008') + 'UserTeamAssociationService', version='v202105') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202008/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202105/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v202008/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202105/user_team_association_service/update_user_team_associations.py index 8abc9c7d..296dfb6a 100755 --- a/examples/ad_manager/v202008/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202105/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202008') + 'UserTeamAssociationService', version='v202105') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202008') + statement = (ad_manager.StatementBuilder(version='v202105') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/adwords/adwords_appengine_demo/COPYING b/examples/adwords/adwords_appengine_demo/COPYING old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/ChangeLog b/examples/adwords/adwords_appengine_demo/ChangeLog old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/README.md b/examples/adwords/adwords_appengine_demo/README.md old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/app.yaml b/examples/adwords/adwords_appengine_demo/app.yaml old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py index f8c4fa24..51578742 100755 --- a/examples/adwords/adwords_appengine_demo/handlers/api_handler.py +++ b/examples/adwords/adwords_appengine_demo/handlers/api_handler.py @@ -18,7 +18,6 @@ import time - from demo import VERSION from googleads.adwords import AdWordsClient from googleads.common import ZeepServiceProxy diff --git a/examples/adwords/adwords_appengine_demo/js/scripts.js b/examples/adwords/adwords_appengine_demo/js/scripts.js old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/requirements.txt b/examples/adwords/adwords_appengine_demo/requirements.txt old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/stylesheets/styles.css b/examples/adwords/adwords_appengine_demo/stylesheets/styles.css old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/templates/base_template.html b/examples/adwords/adwords_appengine_demo/templates/base_template.html old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/templates/show_accounts.html b/examples/adwords/adwords_appengine_demo/templates/show_accounts.html old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/templates/show_adgroups.html b/examples/adwords/adwords_appengine_demo/templates/show_adgroups.html old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/templates/show_budget.html b/examples/adwords/adwords_appengine_demo/templates/show_budget.html old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/templates/show_campaigns.html b/examples/adwords/adwords_appengine_demo/templates/show_campaigns.html old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/templates/show_credentials.html b/examples/adwords/adwords_appengine_demo/templates/show_credentials.html old mode 100644 new mode 100755 diff --git a/examples/adwords/adwords_appengine_demo/templates/toggle_menu_template.html b/examples/adwords/adwords_appengine_demo/templates/toggle_menu_template.html old mode 100644 new mode 100755 diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 42902cb4..1c0f34fc 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,7 +44,7 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v202005': + 'v202008': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -52,16 +52,17 @@ 'CreativeReviewService', 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', 'CreativeWrapperService', 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'ForecastService', 'InventoryService', - 'LabelService', 'LineItemCreativeAssociationService', - 'LineItemService', 'LineItemTemplateService', 'LiveStreamEventService', + 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', 'MobileApplicationService', 'NativeStyleService', 'NetworkService', 'OrderService', 'PlacementService', 'ProposalLineItemService', 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'StreamActivityMonitorService', 'SuggestedAdUnitService', - 'TeamService', 'TargetingPresetService', 'UserService', - 'UserTeamAssociationService'), - 'v202008': + 'SiteService', 'StreamActivityMonitorService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService'), + 'v202011': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -79,7 +80,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202011': + 'v202102': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -97,7 +98,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202102': + 'v202105': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -236,7 +237,6 @@ def __init__(self, oauth2_client, application_name, network_code=None, self.timeout = timeout - def GetService(self, service_name, version=sorted(_SERVICE_MAP.keys())[-1], server=None): """Creates a service client for the given service. diff --git a/googleads/common.py b/googleads/common.py index 507248ba..a91957b3 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -54,8 +54,7 @@ 'order to benefit from important security improvements and ensure ' 'compatibility with this library, upgrade to Python 3.6 or higher.') - -VERSION = '27.0.0' +VERSION = '28.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' @@ -340,8 +339,6 @@ def _ExtractProxyConfig(product_yaml_key, proxy_config_data): return proxy_config - - def IncludeUtilitiesInUserAgent(value): """Configures the logging of utilities in the User-Agent. @@ -638,7 +635,6 @@ def __init__(self, header_handler, packer, version): self._version = version self._method_proxies = {} - @abc.abstractmethod def CreateSoapElementForType(self, type_name): """Create an instance of a SOAP type. @@ -722,8 +718,6 @@ def egress(self, envelope, http_headers, operation, binding_options): return envelope, http_headers - - class ZeepServiceProxy(GoogleSoapService): """Wraps a zeep service object, allowing custom logic to be injected. @@ -779,7 +773,6 @@ def __init__(self, endpoint, header_handler, packer, first_port = list(first_service.ports.values())[0] self._method_bindings = first_port.binding - def CreateSoapElementForType(self, type_name): """Create an instance of a SOAP type. diff --git a/tests/ad_manager_test.py b/tests/ad_manager_test.py index bb137e0b..c5b7c654 100644 --- a/tests/ad_manager_test.py +++ b/tests/ad_manager_test.py @@ -231,7 +231,6 @@ def testGetHeadersUserAgentWithAndWithoutUtility(self): soap_header.applicationName) - class AdManagerClientTest(unittest.TestCase): """Tests for the googleads.ad_manager.AdManagerClient class.""" @@ -303,8 +302,6 @@ def testLoadFromStorageWithCompressionEnabled(self): mock_h.assert_called_once_with( ad_manager, enable_compression, custom_headers) - - def testInitializeWithDefaultApplicationName(self): self.application_name = 'INSERT_APPLICATION_NAME_HERE' self.assertRaises( diff --git a/tests/adwords_test.py b/tests/adwords_test.py index e3f7b18b..b8a97a67 100644 --- a/tests/adwords_test.py +++ b/tests/adwords_test.py @@ -343,7 +343,6 @@ def setUp(self): self.header_handler = googleads.adwords._AdWordsHeaderHandler( self.adwords_client, CURRENT_VERSION, False, None) - def testLoadFromStorage(self): with mock.patch('googleads.oauth2.GoogleRefreshTokenClient.Refresh'): self.assertIsInstance(googleads.adwords.AdWordsClient.LoadFromStorage( diff --git a/tests/common_test.py b/tests/common_test.py index b4a6525f..99dec9d9 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202102' +CURRENT_VERSION = 'v202105' class CommonTest(testing.CleanUtilityRegistryTestCase): @@ -617,7 +617,6 @@ def testGenerateLibSig(self): googleads.common._PYTHON_VERSION), googleads.common.GenerateLibSig(my_name)) - def testGenerateLibSigWithUtilities(self): my_name = 'Mark' From 18c8bdb64bd32d2dea1c3e2a70903dfcfdfb64f9 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 17 Aug 2021 16:22:41 -0400 Subject: [PATCH 170/180] Ad Manager v202108 release --- ChangeLog | 5 ++ .../create_creative_set.py | 7 +- .../delete_custom_targeting_values.py | 2 +- .../create_creative_set.py | 7 +- .../delete_custom_targeting_values.py | 2 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 2 +- .../create_traffic_forecast_segments.py | 4 +- .../get_all_forecast_adjustments.py | 4 +- .../get_all_traffic_forecast_segments.py | 4 +- ...djustments_for_traffic_forecast_segment.py | 4 +- .../update_forecast_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../get_recently_modified_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 9 +-- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +-- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 8 +-- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../forecast_service/get_traffic_data.py | 4 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +-- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../push_creative_to_devices.py | 61 ++++++++++++++++ .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 3 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- ...et_default_third_party_data_declaration.py | 6 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 12 ++-- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- ...un_reach_report_with_ad_unit_dimensions.py | 69 +++++++++++++++++++ .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../site_service/create_sites.py | 4 +- .../site_service/get_all_sites.py | 4 +- .../get_sites_requiring_approval.py | 4 +- .../site_service/submit_sites_for_approval.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 8 +-- googleads/common.py | 2 +- tests/common_test.py | 2 +- 207 files changed, 462 insertions(+), 325 deletions(-) rename examples/ad_manager/{v202011 => v202108}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v202011 => v202108}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v202011 => v202108}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v202011 => v202108}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v202011 => v202108}/activity_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v202011 => v202108}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v202011 => v202108}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v202011 => v202108}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v202011 => v202108}/adjustment_service/create_forecast_adjustments.py (99%) rename examples/ad_manager/{v202011 => v202108}/adjustment_service/create_traffic_forecast_segments.py (98%) rename examples/ad_manager/{v202011 => v202108}/adjustment_service/get_all_forecast_adjustments.py (95%) rename examples/ad_manager/{v202011 => v202108}/adjustment_service/get_all_traffic_forecast_segments.py (95%) rename examples/ad_manager/{v202011 => v202108}/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py (96%) rename examples/ad_manager/{v202011 => v202108}/adjustment_service/update_forecast_adjustments.py (96%) rename examples/ad_manager/{v202011 => v202108}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v202011 => v202108}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v202011 => v202108}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v202011 => v202108}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v202011 => v202108}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v202011 => v202108}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v202011 => v202108}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v202011 => v202108}/cms_metadata_service/activate_cms_metadata_values.py (95%) rename examples/ad_manager/{v202011 => v202108}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v202011 => v202108}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v202011 => v202108}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v202011 => v202108}/company_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/company_service/create_companies.py (99%) rename examples/ad_manager/{v202011 => v202108}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v202011 => v202108}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v202011 => v202108}/company_service/update_companies.py (96%) rename examples/ad_manager/{v202011 => v202108}/contact_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v202011 => v202108}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v202011 => v202108}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v202011 => v202108}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v202011 => v202108}/content_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/content_service/get_all_content.py (96%) rename examples/ad_manager/{v202011 => v202108}/content_service/get_recently_modified_content.py (97%) rename examples/ad_manager/{v202011 => v202108}/creative_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v202011 => v202108}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v202011 => v202108}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v202011 => v202108}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v202011 => v202108}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v202011 => v202108}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v202011 => v202108}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v202011 => v202108}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v202011 => v202108}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v202011 => v202108}/creative_set_service/create_creative_set.py (88%) rename examples/ad_manager/{v202011 => v202108}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v202011 => v202108}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v202011 => v202108}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v202011 => v202108}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v202011 => v202108}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v202011 => v202108}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v202011 => v202108}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v202011 => v202108}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v202011 => v202108}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v202011 => v202108}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v202011 => v202108}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v202011 => v202108}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v202011 => v202108}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v202011 => v202108}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v202011 => v202108}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v202011 => v202108}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v202011 => v202108}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v202011 => v202108}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v202011 => v202108}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202011 => v202108}/custom_targeting_service/delete_custom_targeting_values.py (93%) rename examples/ad_manager/{v202011 => v202108}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202011 => v202108}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202011 => v202108}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202011 => v202108}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v202011 => v202108}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v202011 => v202108}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v202011 => v202108}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v202011 => v202108}/forecast_service/get_traffic_data.py (99%) rename examples/ad_manager/{v202011 => v202108}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v202011 => v202108}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v202011 => v202108}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v202011 => v202108}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v202011 => v202108}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v202011 => v202108}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v202011 => v202108}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v202011 => v202108}/label_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/label_service/create_labels.py (99%) rename examples/ad_manager/{v202011 => v202108}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v202011 => v202108}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v202011 => v202108}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v202011 => v202108}/label_service/update_labels.py (96%) rename examples/ad_manager/{v202011 => v202108}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v202011 => v202108}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v202011 => v202108}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v202011 => v202108}/line_item_creative_association_service/get_licas_for_line_item.py (94%) create mode 100755 examples/ad_manager/v202108/line_item_creative_association_service/push_creative_to_devices.py rename examples/ad_manager/{v202011 => v202108}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/create_video_line_item.py (98%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v202011 => v202108}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v202011 => v202108}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v202011 => v202108}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v202011 => v202108}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v202011 => v202108}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v202011 => v202108}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v202011 => v202108}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v202011 => v202108}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v202011 => v202108}/network_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v202011 => v202108}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v202011 => v202108}/network_service/get_default_third_party_data_declaration.py (95%) rename examples/ad_manager/{v202011 => v202108}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v202011 => v202108}/order_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v202011 => v202108}/order_service/create_orders.py (99%) rename examples/ad_manager/{v202011 => v202108}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v202011 => v202108}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v202011 => v202108}/order_service/update_orders.py (97%) rename examples/ad_manager/{v202011 => v202108}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v202011 => v202108}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v202011 => v202108}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v202011 => v202108}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v202011 => v202108}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v202011 => v202108}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v202011 => v202108}/proposal_line_item_service/create_proposal_line_items.py (94%) rename examples/ad_manager/{v202011 => v202108}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v202011 => v202108}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v202011 => v202108}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v202011 => v202108}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v202011 => v202108}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v202011 => v202108}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v202011 => v202108}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v202011 => v202108}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v202011 => v202108}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v202011 => v202108}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v202011 => v202108}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v202011 => v202108}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v202011 => v202108}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v202011 => v202108}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v202011 => v202108}/publisher_query_language_service/get_mcm_earnings.py (97%) rename examples/ad_manager/{v202011 => v202108}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v202011 => v202108}/report_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v202011 => v202108}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v202011 => v202108}/report_service/run_inventory_report.py (97%) rename examples/ad_manager/{v202011 => v202108}/report_service/run_reach_report.py (96%) create mode 100755 examples/ad_manager/v202108/report_service/run_reach_report_with_ad_unit_dimensions.py rename examples/ad_manager/{v202011 => v202108}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v202011 => v202108}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v202011 => v202108}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v202011 => v202108}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v202011 => v202108}/site_service/create_sites.py (96%) rename examples/ad_manager/{v202011 => v202108}/site_service/get_all_sites.py (92%) rename examples/ad_manager/{v202011 => v202108}/site_service/get_sites_requiring_approval.py (92%) rename examples/ad_manager/{v202011 => v202108}/site_service/submit_sites_for_approval.py (91%) rename examples/ad_manager/{v202011 => v202108}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v202011 => v202108}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v202011 => v202108}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v202011 => v202108}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/targeting_preset_service/get_all_targeting_presets.py (94%) rename examples/ad_manager/{v202011 => v202108}/team_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/team_service/create_teams.py (96%) rename examples/ad_manager/{v202011 => v202108}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v202011 => v202108}/team_service/update_teams.py (94%) rename examples/ad_manager/{v202011 => v202108}/user_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/user_service/create_users.py (96%) rename examples/ad_manager/{v202011 => v202108}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v202011 => v202108}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v202011 => v202108}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v202011 => v202108}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v202011 => v202108}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v202011 => v202108}/user_service/update_users.py (92%) rename examples/ad_manager/{v202011 => v202108}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v202011 => v202108}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v202011 => v202108}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v202011 => v202108}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v202011 => v202108}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v202011 => v202108}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index 4837133e..d3c98371 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +29.0.0 -- 08/16/2021 +* Added support for Ad Manager v202108. +* Removed support for Ad Manager v202008. +* Removed examples for Ad Manager v202011. + 28.0.0 -- 05/11/2021 * Added support for Ad Manager v202105. * Removed support for Ad Manager v202005. diff --git a/examples/ad_manager/v202102/creative_set_service/create_creative_set.py b/examples/ad_manager/v202102/creative_set_service/create_creative_set.py index 331f7745..6f331f03 100755 --- a/examples/ad_manager/v202102/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202102/creative_set_service/create_creative_set.py @@ -51,9 +51,10 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: print(('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was created.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) + 'companion creative IDs "%s" was created.') % + (creative_set['id'], creative_set['masterCreativeId'], ','.join( + str(v) for v in creative_set['companionCreativeIds']))) + if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py index 254ae78c..8300508d 100755 --- a/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py @@ -49,7 +49,7 @@ def main(client, key_id): response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): - value_ids = [value['id'] for value in response['results']] + value_ids = [str(value['id']) for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} value_statement = (ad_manager.StatementBuilder(version='v202102') .Where('customTargetingKeyId = :keyId ' diff --git a/examples/ad_manager/v202105/creative_set_service/create_creative_set.py b/examples/ad_manager/v202105/creative_set_service/create_creative_set.py index d9e30a3a..a2806348 100755 --- a/examples/ad_manager/v202105/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202105/creative_set_service/create_creative_set.py @@ -51,9 +51,10 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: print(('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was created.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) + 'companion creative IDs "%s" was created.') % + (creative_set['id'], creative_set['masterCreativeId'], ','.join( + str(v) for v in creative_set['companionCreativeIds']))) + if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py index 734917d6..7fa1091e 100755 --- a/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py @@ -49,7 +49,7 @@ def main(client, key_id): response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): - value_ids = [value['id'] for value in response['results']] + value_ids = [str(value['id']) for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} value_statement = (ad_manager.StatementBuilder(version='v202105') .Where('customTargetingKeyId = :keyId ' diff --git a/examples/ad_manager/v202011/activity_group_service/__init__.py b/examples/ad_manager/v202108/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/activity_group_service/__init__.py rename to examples/ad_manager/v202108/activity_group_service/__init__.py diff --git a/examples/ad_manager/v202011/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202108/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v202011/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202108/activity_group_service/create_activity_groups.py index ed081d79..ee43c4fa 100755 --- a/examples/ad_manager/v202011/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202108/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202011') + version='v202108') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v202011/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202108/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v202011/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202108/activity_group_service/get_active_activity_groups.py index 48f2fa36..966b448a 100755 --- a/examples/ad_manager/v202011/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202108/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202011') + 'ActivityGroupService', version='v202108') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202011/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202108/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v202011/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202108/activity_group_service/get_all_activity_groups.py index ae0b1de1..f7ad34c2 100755 --- a/examples/ad_manager/v202011/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202108/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202011') + 'ActivityGroupService', version='v202108') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v202011/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202108/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v202011/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202108/activity_group_service/update_activity_groups.py index 55cb98c5..52359931 100755 --- a/examples/ad_manager/v202011/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202108/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202011') + version='v202108') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/activity_service/__init__.py b/examples/ad_manager/v202108/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/activity_service/__init__.py rename to examples/ad_manager/v202108/activity_service/__init__.py diff --git a/examples/ad_manager/v202011/activity_service/create_activities.py b/examples/ad_manager/v202108/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v202011/activity_service/create_activities.py rename to examples/ad_manager/v202108/activity_service/create_activities.py index 70b1be68..87a6082b 100755 --- a/examples/ad_manager/v202011/activity_service/create_activities.py +++ b/examples/ad_manager/v202108/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202011') + activity_service = client.GetService('ActivityService', version='v202108') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v202011/activity_service/get_active_activities.py b/examples/ad_manager/v202108/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v202011/activity_service/get_active_activities.py rename to examples/ad_manager/v202108/activity_service/get_active_activities.py index e2fe78a4..0ee631ed 100755 --- a/examples/ad_manager/v202011/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202108/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202011') + activity_service = client.GetService('ActivityService', version='v202108') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202011/activity_service/get_all_activities.py b/examples/ad_manager/v202108/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v202011/activity_service/get_all_activities.py rename to examples/ad_manager/v202108/activity_service/get_all_activities.py index f66e1fd2..8ff851e3 100755 --- a/examples/ad_manager/v202011/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202108/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202011') + activity_service = client.GetService('ActivityService', version='v202108') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v202011/activity_service/update_activities.py b/examples/ad_manager/v202108/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v202011/activity_service/update_activities.py rename to examples/ad_manager/v202108/activity_service/update_activities.py index 969deafd..d7d988d3 100755 --- a/examples/ad_manager/v202011/activity_service/update_activities.py +++ b/examples/ad_manager/v202108/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202011') + activity_service = client.GetService('ActivityService', version='v202108') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202108/adjustment_service/create_forecast_adjustments.py similarity index 99% rename from examples/ad_manager/v202011/adjustment_service/create_forecast_adjustments.py rename to examples/ad_manager/v202108/adjustment_service/create_forecast_adjustments.py index 4b0ba15b..2df2a20c 100755 --- a/examples/ad_manager/v202011/adjustment_service/create_forecast_adjustments.py +++ b/examples/ad_manager/v202108/adjustment_service/create_forecast_adjustments.py @@ -27,7 +27,7 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202011') + adjustment_service = client.GetService('AdjustmentService', version='v202108') # Create a new forecast adjustment for New Year's Day traffic. this_new_years = datetime.date(datetime.date.today().year, 1, 1) diff --git a/examples/ad_manager/v202011/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202108/adjustment_service/create_traffic_forecast_segments.py similarity index 98% rename from examples/ad_manager/v202011/adjustment_service/create_traffic_forecast_segments.py rename to examples/ad_manager/v202108/adjustment_service/create_traffic_forecast_segments.py index ab5e014f..9d8483ba 100755 --- a/examples/ad_manager/v202011/adjustment_service/create_traffic_forecast_segments.py +++ b/examples/ad_manager/v202108/adjustment_service/create_traffic_forecast_segments.py @@ -25,8 +25,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v202011') - network_service = client.GetService('NetworkService', version='v202011') + adjustment_service = client.GetService('AdjustmentService', version='v202108') + network_service = client.GetService('NetworkService', version='v202108') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202011/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202108/adjustment_service/get_all_forecast_adjustments.py similarity index 95% rename from examples/ad_manager/v202011/adjustment_service/get_all_forecast_adjustments.py rename to examples/ad_manager/v202108/adjustment_service/get_all_forecast_adjustments.py index 5cf0742c..aa488844 100755 --- a/examples/ad_manager/v202011/adjustment_service/get_all_forecast_adjustments.py +++ b/examples/ad_manager/v202108/adjustment_service/get_all_forecast_adjustments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202011') + adjustment_service = client.GetService('AdjustmentService', version='v202108') # Create a statement to get all forecast adjustments. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small number of forecast adjustments at a time, paging # through until all forecast adjustments have been retrieved. diff --git a/examples/ad_manager/v202011/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202108/adjustment_service/get_all_traffic_forecast_segments.py similarity index 95% rename from examples/ad_manager/v202011/adjustment_service/get_all_traffic_forecast_segments.py rename to examples/ad_manager/v202108/adjustment_service/get_all_traffic_forecast_segments.py index 92b52632..36fe9067 100755 --- a/examples/ad_manager/v202011/adjustment_service/get_all_traffic_forecast_segments.py +++ b/examples/ad_manager/v202108/adjustment_service/get_all_traffic_forecast_segments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202011') + adjustment_service = client.GetService('AdjustmentService', version='v202108') # Create a statement to get all traffic forecast segments. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small number of segments at a time, paging through until all # segments have been retrieved. diff --git a/examples/ad_manager/v202011/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202108/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py similarity index 96% rename from examples/ad_manager/v202011/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py rename to examples/ad_manager/v202108/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py index 8660f130..ba34e576 100755 --- a/examples/ad_manager/v202011/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py +++ b/examples/ad_manager/v202108/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -24,11 +24,11 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202011') + adjustment_service = client.GetService('AdjustmentService', version='v202108') # Create a statement to get forecast adjustments for a given traffic forecast # segment id. - statement = ad_manager.StatementBuilder(version='v202011').Where( + statement = ad_manager.StatementBuilder(version='v202108').Where( 'trafficForecastSegmentId = :segmentId').WithBindVariable( 'segmentId', traffic_forecast_segment_id) diff --git a/examples/ad_manager/v202011/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202108/adjustment_service/update_forecast_adjustments.py similarity index 96% rename from examples/ad_manager/v202011/adjustment_service/update_forecast_adjustments.py rename to examples/ad_manager/v202108/adjustment_service/update_forecast_adjustments.py index d62a3177..07bf813c 100755 --- a/examples/ad_manager/v202011/adjustment_service/update_forecast_adjustments.py +++ b/examples/ad_manager/v202108/adjustment_service/update_forecast_adjustments.py @@ -24,12 +24,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202011') + adjustment_service = client.GetService('AdjustmentService', version='v202108') # Create a statement to select a single forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v202011').Where('id = :id').WithBindVariable( + version='v202108').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast adjustment. diff --git a/examples/ad_manager/v202011/audience_segment_service/__init__.py b/examples/ad_manager/v202108/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/audience_segment_service/__init__.py rename to examples/ad_manager/v202108/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v202011/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202108/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v202011/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202108/audience_segment_service/create_audience_segments.py index 26b2955b..8e8fd84b 100755 --- a/examples/ad_manager/v202011/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202108/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202011') - network_service = client.GetService('NetworkService', version='v202011') + 'AudienceSegmentService', version='v202108') + network_service = client.GetService('NetworkService', version='v202108') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v202011/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202108/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v202011/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202108/audience_segment_service/get_all_audience_segments.py index 77da7c37..850f9081 100755 --- a/examples/ad_manager/v202011/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202108/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202011') + 'AudienceSegmentService', version='v202108') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v202011/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202108/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v202011/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202108/audience_segment_service/get_first_party_audience_segments.py index aea62a57..18b8a912 100755 --- a/examples/ad_manager/v202011/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202108/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202011') + 'AudienceSegmentService', version='v202108') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v202011/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202108/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v202011/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202108/audience_segment_service/populate_first_party_audience_segments.py index d76ff127..875f620e 100755 --- a/examples/ad_manager/v202011/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202108/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202011') + 'AudienceSegmentService', version='v202108') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202011/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202108/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v202011/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202108/audience_segment_service/update_audience_segments.py index a9eeaac0..bbb7c11a 100755 --- a/examples/ad_manager/v202011/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202108/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202011') + 'AudienceSegmentService', version='v202108') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202011/cdn_configuration_service/__init__.py b/examples/ad_manager/v202108/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202108/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v202011/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202108/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v202011/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202108/cdn_configuration_service/create_cdn_configurations.py index 9dec0df5..2c9a1d18 100755 --- a/examples/ad_manager/v202011/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202108/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202011') + version='v202108') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v202011/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202108/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v202011/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202108/cdn_configuration_service/get_all_cdn_configurations.py index 9235d966..b5227e9a 100755 --- a/examples/ad_manager/v202011/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202108/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202011') + version='v202108') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202011/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202108/cms_metadata_service/activate_cms_metadata_values.py similarity index 95% rename from examples/ad_manager/v202011/cms_metadata_service/activate_cms_metadata_values.py rename to examples/ad_manager/v202108/cms_metadata_service/activate_cms_metadata_values.py index 6e00167d..8dd4256c 100755 --- a/examples/ad_manager/v202011/cms_metadata_service/activate_cms_metadata_values.py +++ b/examples/ad_manager/v202108/cms_metadata_service/activate_cms_metadata_values.py @@ -28,10 +28,10 @@ def main(client, cms_metadata_key_id): # Initialize appropriate service. cms_metadata_service = client.GetService('CmsMetadataService', - version='v202011') + version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('cmsKeyId = :cmsKeyId AND status = :status') .WithBindVariable('status', 'INACTIVE') .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) diff --git a/examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_keys.py index 7065736c..dd37dc46 100755 --- a/examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202011') + 'CmsMetadataService', version='v202108') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_values.py index a2791368..4397e1f1 100755 --- a/examples/ad_manager/v202011/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202011') + 'CmsMetadataService', version='v202108') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v202011/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202108/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v202011/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202108/cms_metadata_service/get_cms_metadata_values_for_key.py index 10ea3306..c6273539 100755 --- a/examples/ad_manager/v202011/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202108/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202011') + 'CmsMetadataService', version='v202108') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v202011').Where( + ad_manager.StatementBuilder(version='v202108').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v202011/company_service/__init__.py b/examples/ad_manager/v202108/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/company_service/__init__.py rename to examples/ad_manager/v202108/company_service/__init__.py diff --git a/examples/ad_manager/v202011/company_service/create_companies.py b/examples/ad_manager/v202108/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v202011/company_service/create_companies.py rename to examples/ad_manager/v202108/company_service/create_companies.py index 206ad1b9..9624b4a0 100755 --- a/examples/ad_manager/v202011/company_service/create_companies.py +++ b/examples/ad_manager/v202108/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202011') + company_service = client.GetService('CompanyService', version='v202108') # Create company objects. companies = [ diff --git a/examples/ad_manager/v202011/company_service/get_advertisers.py b/examples/ad_manager/v202108/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v202011/company_service/get_advertisers.py rename to examples/ad_manager/v202108/company_service/get_advertisers.py index a6594712..40f48790 100755 --- a/examples/ad_manager/v202011/company_service/get_advertisers.py +++ b/examples/ad_manager/v202108/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202011') + company_service = client.GetService('CompanyService', version='v202108') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v202011/company_service/get_all_companies.py b/examples/ad_manager/v202108/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v202011/company_service/get_all_companies.py rename to examples/ad_manager/v202108/company_service/get_all_companies.py index cf9948e9..7d315725 100755 --- a/examples/ad_manager/v202011/company_service/get_all_companies.py +++ b/examples/ad_manager/v202108/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202011') + company_service = client.GetService('CompanyService', version='v202108') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v202011/company_service/update_companies.py b/examples/ad_manager/v202108/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v202011/company_service/update_companies.py rename to examples/ad_manager/v202108/company_service/update_companies.py index ce910d40..cf206964 100755 --- a/examples/ad_manager/v202011/company_service/update_companies.py +++ b/examples/ad_manager/v202108/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202011') + company_service = client.GetService('CompanyService', version='v202108') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/contact_service/__init__.py b/examples/ad_manager/v202108/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/contact_service/__init__.py rename to examples/ad_manager/v202108/contact_service/__init__.py diff --git a/examples/ad_manager/v202011/contact_service/create_contacts.py b/examples/ad_manager/v202108/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v202011/contact_service/create_contacts.py rename to examples/ad_manager/v202108/contact_service/create_contacts.py index 045c83bc..02ffed16 100755 --- a/examples/ad_manager/v202011/contact_service/create_contacts.py +++ b/examples/ad_manager/v202108/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202011') + contact_service = client.GetService('ContactService', version='v202108') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v202011/contact_service/get_all_contacts.py b/examples/ad_manager/v202108/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v202011/contact_service/get_all_contacts.py rename to examples/ad_manager/v202108/contact_service/get_all_contacts.py index 86186061..6e304990 100755 --- a/examples/ad_manager/v202011/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202108/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202011') + contact_service = client.GetService('ContactService', version='v202108') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v202011/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202108/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v202011/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202108/contact_service/get_uninvited_contacts.py index e2e8a3fd..d9c10139 100755 --- a/examples/ad_manager/v202011/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202108/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202011') + contact_service = client.GetService('ContactService', version='v202108') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v202011/contact_service/update_contacts.py b/examples/ad_manager/v202108/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v202011/contact_service/update_contacts.py rename to examples/ad_manager/v202108/contact_service/update_contacts.py index ac0f96da..7ffcf45b 100755 --- a/examples/ad_manager/v202011/contact_service/update_contacts.py +++ b/examples/ad_manager/v202108/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202011') + contact_service = client.GetService('ContactService', version='v202108') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/content_service/__init__.py b/examples/ad_manager/v202108/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/content_service/__init__.py rename to examples/ad_manager/v202108/content_service/__init__.py diff --git a/examples/ad_manager/v202011/content_service/get_all_content.py b/examples/ad_manager/v202108/content_service/get_all_content.py similarity index 96% rename from examples/ad_manager/v202011/content_service/get_all_content.py rename to examples/ad_manager/v202108/content_service/get_all_content.py index 16b8d8b8..2b539b74 100755 --- a/examples/ad_manager/v202011/content_service/get_all_content.py +++ b/examples/ad_manager/v202108/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202011') + content_service = client.GetService('ContentService', version='v202108') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v202011/content_service/get_recently_modified_content.py b/examples/ad_manager/v202108/content_service/get_recently_modified_content.py similarity index 97% rename from examples/ad_manager/v202011/content_service/get_recently_modified_content.py rename to examples/ad_manager/v202108/content_service/get_recently_modified_content.py index f6b4f5e5..bb70e513 100755 --- a/examples/ad_manager/v202011/content_service/get_recently_modified_content.py +++ b/examples/ad_manager/v202108/content_service/get_recently_modified_content.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202011') + content_service = client.GetService('ContentService', version='v202108') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -35,7 +35,7 @@ def main(client): # lastModifiedDateTime. Changes to content bundle associations will update # the lastModifiedDateTime, but CMS metadata changes may not change the # lastModifiedDateTime. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202011/creative_service/__init__.py b/examples/ad_manager/v202108/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/creative_service/__init__.py rename to examples/ad_manager/v202108/creative_service/__init__.py diff --git a/examples/ad_manager/v202011/creative_service/copy_image_creatives.py b/examples/ad_manager/v202108/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v202011/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202108/creative_service/copy_image_creatives.py index d6a9c5ef..b9d11052 100755 --- a/examples/ad_manager/v202011/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202108/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202011') + creative_service = client.GetService('CreativeService', version='v202108') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v202011/creative_service/create_creative_from_template.py b/examples/ad_manager/v202108/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v202011/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202108/creative_service/create_creative_from_template.py index 0383bd08..1ae38ee8 100755 --- a/examples/ad_manager/v202011/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202108/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202011') + creative_service = client.GetService('CreativeService', version='v202108') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v202011/creative_service/create_creatives.py b/examples/ad_manager/v202108/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v202011/creative_service/create_creatives.py rename to examples/ad_manager/v202108/creative_service/create_creatives.py index ffdab85b..8705f1bb 100755 --- a/examples/ad_manager/v202011/creative_service/create_creatives.py +++ b/examples/ad_manager/v202108/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202011') + creative_service = client.GetService('CreativeService', version='v202108') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v202011/creative_service/create_custom_creative.py b/examples/ad_manager/v202108/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v202011/creative_service/create_custom_creative.py rename to examples/ad_manager/v202108/creative_service/create_custom_creative.py index 43d966e6..b86a76ff 100755 --- a/examples/ad_manager/v202011/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202108/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202011') + creative_service = client.GetService('CreativeService', version='v202108') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v202011/creative_service/create_native_creative.py b/examples/ad_manager/v202108/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v202011/creative_service/create_native_creative.py rename to examples/ad_manager/v202108/creative_service/create_native_creative.py index 286e760c..b34d2759 100755 --- a/examples/ad_manager/v202011/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202108/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202011') + creative_service = client.GetService('CreativeService', version='v202108') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v202011/creative_service/get_all_creatives.py b/examples/ad_manager/v202108/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v202011/creative_service/get_all_creatives.py rename to examples/ad_manager/v202108/creative_service/get_all_creatives.py index a9342402..7e1b3c27 100755 --- a/examples/ad_manager/v202011/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202108/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202011') + creative_service = client.GetService('CreativeService', version='v202108') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v202011/creative_service/get_image_creatives.py b/examples/ad_manager/v202108/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v202011/creative_service/get_image_creatives.py rename to examples/ad_manager/v202108/creative_service/get_image_creatives.py index aef21911..6b9f4c46 100755 --- a/examples/ad_manager/v202011/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202108/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202011') + creative_service = client.GetService('CreativeService', version='v202108') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v202011/creative_service/update_creatives.py b/examples/ad_manager/v202108/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v202011/creative_service/update_creatives.py rename to examples/ad_manager/v202108/creative_service/update_creatives.py index 3a89c1f3..7fbd3fb9 100755 --- a/examples/ad_manager/v202011/creative_service/update_creatives.py +++ b/examples/ad_manager/v202108/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202011') + creative_service = client.GetService('CreativeService', version='v202108') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v202011/creative_set_service/__init__.py b/examples/ad_manager/v202108/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/creative_set_service/__init__.py rename to examples/ad_manager/v202108/creative_set_service/__init__.py diff --git a/examples/ad_manager/v202011/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202108/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v202011/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202108/creative_set_service/associate_creative_set_to_line_item.py index 4718d69d..c442981e 100755 --- a/examples/ad_manager/v202011/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202108/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202011') + 'LineItemCreativeAssociationService', version='v202108') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v202011/creative_set_service/create_creative_set.py b/examples/ad_manager/v202108/creative_set_service/create_creative_set.py similarity index 88% rename from examples/ad_manager/v202011/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202108/creative_set_service/create_creative_set.py index 1476f5f9..7b7b7f16 100755 --- a/examples/ad_manager/v202011/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202108/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202011') + version='v202108') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), @@ -51,9 +51,10 @@ def main(client, master_creative_id, companion_creative_id): # Display results. if creative_set: print(('Creative set with ID "%s", master creative ID "%s", and ' - 'companion creative IDs {%s} was created.') - % (creative_set['id'], creative_set['masterCreativeId'], - ','.join(creative_set['companionCreativeIds']))) + 'companion creative IDs "%s" was created.') % + (creative_set['id'], creative_set['masterCreativeId'], ','.join( + str(v) for v in creative_set['companionCreativeIds']))) + if __name__ == '__main__': # Initialize client object. diff --git a/examples/ad_manager/v202011/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202108/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v202011/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202108/creative_set_service/get_all_creative_sets.py index 747770de..4a93a93f 100755 --- a/examples/ad_manager/v202011/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202108/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202011') + 'CreativeSetService', version='v202108') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v202011/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202108/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v202011/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202108/creative_set_service/get_creative_sets_for_master_creative.py index be37c684..1f9ee595 100755 --- a/examples/ad_manager/v202011/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202108/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202011') + 'CreativeSetService', version='v202108') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v202011/creative_set_service/update_creative_set.py b/examples/ad_manager/v202108/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v202011/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202108/creative_set_service/update_creative_set.py index d94dd46f..f55c9d9e 100755 --- a/examples/ad_manager/v202011/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202108/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202011') + version='v202108') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v202011/creative_template_service/__init__.py b/examples/ad_manager/v202108/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/creative_template_service/__init__.py rename to examples/ad_manager/v202108/creative_template_service/__init__.py diff --git a/examples/ad_manager/v202011/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202108/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v202011/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202108/creative_template_service/get_all_creative_templates.py index 2f106d42..c832af2e 100755 --- a/examples/ad_manager/v202011/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202108/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202011') + 'CreativeTemplateService', version='v202108') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v202011/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202108/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v202011/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202108/creative_template_service/get_system_defined_creative_templates.py index ae3d12a0..8fd72927 100755 --- a/examples/ad_manager/v202011/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202108/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202011') + 'CreativeTemplateService', version='v202108') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v202011/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202108/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v202011/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202108/creative_wrapper_service/create_creative_wrappers.py index 97f6341a..84f39883 100755 --- a/examples/ad_manager/v202011/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202108/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202011') + version='v202108') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v202011/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202108/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v202011/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202108/creative_wrapper_service/deactivate_creative_wrapper.py index af29444a..06b6edfe 100755 --- a/examples/ad_manager/v202011/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202108/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202011') + version='v202108') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202011/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202108/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202011/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202108/creative_wrapper_service/get_active_creative_wrappers.py index 83e3acad..0587c604 100755 --- a/examples/ad_manager/v202011/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202108/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202011') + 'CreativeWrapperService', version='v202108') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202011/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202108/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202011/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202108/creative_wrapper_service/get_all_creative_wrappers.py index d6b40d7a..9dc33e68 100755 --- a/examples/ad_manager/v202011/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202108/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202011') + 'CreativeWrapperService', version='v202108') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v202011/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202108/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v202011/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202108/creative_wrapper_service/update_creative_wrappers.py index 7cbfc3db..edb47640 100755 --- a/examples/ad_manager/v202011/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202108/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202011') + version='v202108') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v202011/custom_field_service/__init__.py b/examples/ad_manager/v202108/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/custom_field_service/__init__.py rename to examples/ad_manager/v202108/custom_field_service/__init__.py diff --git a/examples/ad_manager/v202011/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202108/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v202011/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202108/custom_field_service/create_custom_field_options.py index 920a506d..3c554fe7 100755 --- a/examples/ad_manager/v202011/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202108/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202011') + 'CustomFieldService', version='v202108') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v202011/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202108/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v202011/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202108/custom_field_service/create_custom_fields.py index a06a40db..e5695266 100755 --- a/examples/ad_manager/v202011/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202108/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202011') + 'CustomFieldService', version='v202108') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v202011/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202108/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v202011/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202108/custom_field_service/deactivate_all_line_item_custom_fields.py index 3406304f..bbebbd48 100755 --- a/examples/ad_manager/v202011/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202108/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202011') + 'CustomFieldService', version='v202108') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202011/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202108/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v202011/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202108/custom_field_service/get_all_custom_fields.py index 64531912..cb684fe5 100755 --- a/examples/ad_manager/v202011/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202108/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202011') + 'CustomFieldService', version='v202108') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v202011/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202108/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v202011/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202108/custom_field_service/get_custom_fields_for_line_items.py index 85276bdc..30940553 100755 --- a/examples/ad_manager/v202011/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202108/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202011') + 'CustomFieldService', version='v202108') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v202011/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202108/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v202011/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202108/custom_field_service/set_line_item_custom_field_value.py index 924f3cbf..8373ce2a 100755 --- a/examples/ad_manager/v202011/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202108/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v202011') + 'CustomFieldService', version='v202108') - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v202011') + custom_field_statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v202011') + ad_manager.StatementBuilder(version='v202108') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v202011') + line_item_statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v202011/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202108/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v202011/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202108/custom_field_service/update_custom_fields.py index 179880c4..e5be3666 100755 --- a/examples/ad_manager/v202011/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202108/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202011') + 'CustomFieldService', version='v202108') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v202011/custom_targeting_service/__init__.py b/examples/ad_manager/v202108/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/custom_targeting_service/__init__.py rename to examples/ad_manager/v202108/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v202011/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202108/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v202011/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202108/custom_targeting_service/create_custom_targeting_keys_and_values.py index 2faa4aca..38dab7c1 100755 --- a/examples/ad_manager/v202011/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202108/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202011') + 'CustomTargetingService', version='v202108') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_keys.py index dad2da13..c988fbef 100755 --- a/examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202011') + 'CustomTargetingService', version='v202108') - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v202011') + key_statement = (ad_manager.StatementBuilder(version='v202108') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_values.py similarity index 93% rename from examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_values.py index 85686c40..86e7f371 100755 --- a/examples/ad_manager/v202011/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202011') + 'CustomTargetingService', version='v202108') - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -49,9 +49,9 @@ def main(client, key_id): response = custom_targeting_service.getCustomTargetingValuesByStatement( statement.ToStatement()) if 'results' in response and len(response['results']): - value_ids = [value['id'] for value in response['results']] + value_ids = [str(value['id']) for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v202011') + value_statement = (ad_manager.StatementBuilder(version='v202108') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v202011/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202108/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202011/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202108/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 44ac874e..860f14d2 100755 --- a/examples/ad_manager/v202011/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202108/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202011') + 'CustomTargetingService', version='v202108') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v202011') + targeting_key_statement = ad_manager.StatementBuilder(version='v202108') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v202011/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202108/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202011/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202108/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 3bfe141f..f526cc46 100755 --- a/examples/ad_manager/v202011/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202108/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202011') + 'CustomTargetingService', version='v202108') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v202011') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202108') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_keys.py index fdc28886..18af298b 100755 --- a/examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202011') + 'CustomTargetingService', version='v202108') - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_values.py index 6474df61..00583339 100755 --- a/examples/ad_manager/v202011/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202011') + 'CustomTargetingService', version='v202108') - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v202011/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202108/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v202011/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202108/forecast_service/get_availability_forecast.py index 2abd24ca..39b380a9 100755 --- a/examples/ad_manager/v202011/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202108/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202011') - network_service = client.GetService('NetworkService', version='v202011') + forecast_service = client.GetService('ForecastService', version='v202108') + network_service = client.GetService('NetworkService', version='v202108') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202011/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202108/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v202011/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202108/forecast_service/get_availability_forecast_for_line_item.py index f146ad24..ec5ca930 100755 --- a/examples/ad_manager/v202011/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202108/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202011') + forecast_service = client.GetService('ForecastService', version='v202108') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v202011/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202108/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v202011/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202108/forecast_service/get_delivery_forecast_for_line_items.py index 76e201ad..15a315a8 100755 --- a/examples/ad_manager/v202011/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202108/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202011') + forecast_service = client.GetService('ForecastService', version='v202108') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v202011/forecast_service/get_traffic_data.py b/examples/ad_manager/v202108/forecast_service/get_traffic_data.py similarity index 99% rename from examples/ad_manager/v202011/forecast_service/get_traffic_data.py rename to examples/ad_manager/v202108/forecast_service/get_traffic_data.py index 1c40beee..b49adb19 100755 --- a/examples/ad_manager/v202011/forecast_service/get_traffic_data.py +++ b/examples/ad_manager/v202108/forecast_service/get_traffic_data.py @@ -25,8 +25,8 @@ def main(client): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202011') - network_service = client.GetService('NetworkService', version='v202011') + forecast_service = client.GetService('ForecastService', version='v202108') + network_service = client.GetService('NetworkService', version='v202108') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202011/inventory_service/__init__.py b/examples/ad_manager/v202108/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/inventory_service/__init__.py rename to examples/ad_manager/v202108/inventory_service/__init__.py diff --git a/examples/ad_manager/v202011/inventory_service/archive_ad_units.py b/examples/ad_manager/v202108/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v202011/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202108/inventory_service/archive_ad_units.py index 9acc7c91..6181c8ba 100755 --- a/examples/ad_manager/v202011/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202108/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202011') + inventory_service = client.GetService('InventoryService', version='v202108') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v202011/inventory_service/create_ad_units.py b/examples/ad_manager/v202108/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v202011/inventory_service/create_ad_units.py rename to examples/ad_manager/v202108/inventory_service/create_ad_units.py index 2c37336f..76d01663 100755 --- a/examples/ad_manager/v202011/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202108/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202011') + inventory_service = client.GetService('InventoryService', version='v202108') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v202011/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202108/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v202011/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202108/inventory_service/get_ad_unit_hierarchy.py index 6bb72bae..5d93d8c4 100755 --- a/examples/ad_manager/v202011/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202108/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202011') - inventory_service = client.GetService('InventoryService', version='v202011') + network_service = client.GetService('NetworkService', version='v202108') + inventory_service = client.GetService('InventoryService', version='v202108') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v202011/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202108/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v202011/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202108/inventory_service/get_all_ad_unit_sizes.py index e5f6a815..f6eb46aa 100755 --- a/examples/ad_manager/v202011/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202108/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v202011') + 'InventoryService', version='v202108') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v202011/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202108/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v202011/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202108/inventory_service/get_all_ad_units.py index 488198c5..de232c52 100755 --- a/examples/ad_manager/v202011/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202108/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v202011') + ad_unit_service = client.GetService('InventoryService', version='v202108') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v202011/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202108/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v202011/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202108/inventory_service/get_top_level_ad_units.py index 97636b8e..215cc3a1 100755 --- a/examples/ad_manager/v202011/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202108/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202011') - inventory_service = client.GetService('InventoryService', version='v202011') + network_service = client.GetService('NetworkService', version='v202108') + inventory_service = client.GetService('InventoryService', version='v202108') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v202011/inventory_service/update_ad_units.py b/examples/ad_manager/v202108/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v202011/inventory_service/update_ad_units.py rename to examples/ad_manager/v202108/inventory_service/update_ad_units.py index bdddab9b..f9a0bb74 100755 --- a/examples/ad_manager/v202011/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202108/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202011') + inventory_service = client.GetService('InventoryService', version='v202108') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v202011/label_service/__init__.py b/examples/ad_manager/v202108/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/label_service/__init__.py rename to examples/ad_manager/v202108/label_service/__init__.py diff --git a/examples/ad_manager/v202011/label_service/create_labels.py b/examples/ad_manager/v202108/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v202011/label_service/create_labels.py rename to examples/ad_manager/v202108/label_service/create_labels.py index 090bbcb0..60ac6a18 100755 --- a/examples/ad_manager/v202011/label_service/create_labels.py +++ b/examples/ad_manager/v202108/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202011') + label_service = client.GetService('LabelService', version='v202108') # Create label objects. labels = [] diff --git a/examples/ad_manager/v202011/label_service/deactivate_labels.py b/examples/ad_manager/v202108/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v202011/label_service/deactivate_labels.py rename to examples/ad_manager/v202108/label_service/deactivate_labels.py index 149c19bc..57bb36ec 100755 --- a/examples/ad_manager/v202011/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202108/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202011') + label_service = client.GetService('LabelService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202011/label_service/get_active_labels.py b/examples/ad_manager/v202108/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v202011/label_service/get_active_labels.py rename to examples/ad_manager/v202108/label_service/get_active_labels.py index 981161e7..64eafc14 100755 --- a/examples/ad_manager/v202011/label_service/get_active_labels.py +++ b/examples/ad_manager/v202108/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202011') + label_service = client.GetService('LabelService', version='v202108') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202011/label_service/get_all_labels.py b/examples/ad_manager/v202108/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v202011/label_service/get_all_labels.py rename to examples/ad_manager/v202108/label_service/get_all_labels.py index 07138c6a..8d3ba500 100755 --- a/examples/ad_manager/v202011/label_service/get_all_labels.py +++ b/examples/ad_manager/v202108/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202011') + label_service = client.GetService('LabelService', version='v202108') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v202011/label_service/update_labels.py b/examples/ad_manager/v202108/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v202011/label_service/update_labels.py rename to examples/ad_manager/v202108/label_service/update_labels.py index 7801cd6b..27f6ddbb 100755 --- a/examples/ad_manager/v202011/label_service/update_labels.py +++ b/examples/ad_manager/v202108/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202011') + label_service = client.GetService('LabelService', version='v202108') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202011/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202108/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202108/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v202011/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202108/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v202011/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202108/line_item_creative_association_service/create_licas.py index 4eb2e11b..d538033a 100755 --- a/examples/ad_manager/v202011/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202108/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202011') + 'LineItemCreativeAssociationService', version='v202108') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v202011/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202108/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v202011/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202108/line_item_creative_association_service/deactivate_licas.py index 6ba8222e..4005c735 100755 --- a/examples/ad_manager/v202011/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202108/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202011') + 'LineItemCreativeAssociationService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v202011/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202108/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v202011/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202108/line_item_creative_association_service/get_all_licas.py index 645404a4..61ad022d 100755 --- a/examples/ad_manager/v202011/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202108/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202011') + 'LineItemCreativeAssociationService', version='v202108') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v202011/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202108/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v202011/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202108/line_item_creative_association_service/get_licas_for_line_item.py index 530294c1..b9bb2572 100755 --- a/examples/ad_manager/v202011/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202108/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202011') + 'LineItemCreativeAssociationService', version='v202108') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v202108/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202108/line_item_creative_association_service/push_creative_to_devices.py new file mode 100755 index 00000000..76ac2341 --- /dev/null +++ b/examples/ad_manager/v202108/line_item_creative_association_service/push_creative_to_devices.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2021, Google LLC +# +# 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 pushes a LICA to a linked device for preview. + +To determine which linked devices exist, use the PublisherQueryLanguageService +linked_device table. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the associated line item id and creative id to push, and set the linked +# device id where it will be pushed. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' +CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' +LINKED_DEVICE_ID = 'INSERT_LINKED_DEVICE_ID_HERE' + + +def main(client, line_item_id, creative_id, linked_device_id): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v202108') + + # Create query to select a single linked device. + # Linked devices can be read from the linked_device PQL table. + statement = (ad_manager.StatementBuilder(version='v202108') + .Where('id = :linkedDeviceId') + .WithBindVariable('linkedDeviceId', int(linked_device_id))) + + # Make call to push creatives to devices. + result = lica_service.pushCreativeToDevices(statement.ToStatement(), { + 'lineItemId': line_item_id, + 'creativeId': creative_id + }) + + # Display results. + if result and int(result['numChanges']) > 0: + print('Pushed creatives to %s devices.' % result['numChanges']) + else: + print('No creatives were pushed.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, CREATIVE_ID, LINKED_DEVICE_ID) diff --git a/examples/ad_manager/v202011/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202108/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v202011/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202108/line_item_creative_association_service/update_licas.py index 49977fa6..24ed054e 100755 --- a/examples/ad_manager/v202011/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202108/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202011') + 'LineItemCreativeAssociationService', version='v202108') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v202011/line_item_service/__init__.py b/examples/ad_manager/v202108/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/line_item_service/__init__.py rename to examples/ad_manager/v202108/line_item_service/__init__.py diff --git a/examples/ad_manager/v202011/line_item_service/activate_line_items.py b/examples/ad_manager/v202108/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v202011/line_item_service/activate_line_items.py rename to examples/ad_manager/v202108/line_item_service/activate_line_items.py index 6b8825a5..65237c4b 100755 --- a/examples/ad_manager/v202011/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202108/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202011/line_item_service/create_line_items.py b/examples/ad_manager/v202108/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v202011/line_item_service/create_line_items.py rename to examples/ad_manager/v202108/line_item_service/create_line_items.py index 106b813b..0296e202 100755 --- a/examples/ad_manager/v202011/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202108/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202011/line_item_service/create_video_line_item.py b/examples/ad_manager/v202108/line_item_service/create_video_line_item.py similarity index 98% rename from examples/ad_manager/v202011/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202108/line_item_service/create_video_line_item.py index e161f950..c59cc7a3 100755 --- a/examples/ad_manager/v202011/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202108/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) @@ -100,6 +100,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, }], 'environmentType': 'VIDEO_PLAYER', 'companionDeliveryOption': 'OPTIONAL', + 'videoMaxDuration': 15000, 'startDateTimeType': 'IMMEDIATELY', 'lineItemType': 'SPONSORSHIP', 'endDateTime': end_datetime, diff --git a/examples/ad_manager/v202011/line_item_service/get_all_line_items.py b/examples/ad_manager/v202108/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v202011/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202108/line_item_service/get_all_line_items.py index d97003d4..5c782e60 100755 --- a/examples/ad_manager/v202011/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202108/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v202011/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202108/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v202011/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202108/line_item_service/get_line_items_that_need_creatives.py index 05c6fe1b..065a1c06 100755 --- a/examples/ad_manager/v202011/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202108/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v202011/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202108/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v202011/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202108/line_item_service/get_recently_updated_line_items.py index 4c415960..c5d8715d 100755 --- a/examples/ad_manager/v202011/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202108/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202011/line_item_service/pause_line_items.py b/examples/ad_manager/v202108/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v202011/line_item_service/pause_line_items.py rename to examples/ad_manager/v202108/line_item_service/pause_line_items.py index b1bdc6e1..3877d0b4 100755 --- a/examples/ad_manager/v202011/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202108/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v202011/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202108/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v202011/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202108/line_item_service/target_custom_criteria.py index 7364f232..408875d1 100755 --- a/examples/ad_manager/v202011/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202108/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/line_item_service/update_line_items.py b/examples/ad_manager/v202108/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v202011/line_item_service/update_line_items.py rename to examples/ad_manager/v202108/line_item_service/update_line_items.py index 092d8764..0a5700a8 100755 --- a/examples/ad_manager/v202011/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202108/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202011') + line_item_service = client.GetService('LineItemService', version='v202108') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v202011/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202108/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202011/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202108/live_stream_event_service/activate_live_stream_events.py index 616ac53c..23468295 100755 --- a/examples/ad_manager/v202011/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202108/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202011') + 'LiveStreamEventService', version='v202108') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v202011/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202108/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v202011/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202108/live_stream_event_service/create_live_stream_events.py index d75aa0d4..0b58b427 100755 --- a/examples/ad_manager/v202011/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202108/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v202011') + 'LiveStreamEventService', version='v202108') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v202011/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202108/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v202011/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202108/live_stream_event_service/get_all_live_stream_events.py index 3385e5f3..fbaeda69 100755 --- a/examples/ad_manager/v202011/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202108/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202011') + 'LiveStreamEventService', version='v202108') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v202011/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202108/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v202011/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202108/live_stream_event_service/register_sessions_for_monitoring.py index b0e156f2..d505e419 100755 --- a/examples/ad_manager/v202011/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202108/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202011') + 'LiveStreamEventService', version='v202108') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v202011/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202108/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202011/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202108/live_stream_event_service/update_live_stream_events.py index ff96c650..86df87bf 100755 --- a/examples/ad_manager/v202011/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202108/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v202011') + 'LiveStreamEventService', version='v202108') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v202011/native_style_service/__init__.py b/examples/ad_manager/v202108/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/native_style_service/__init__.py rename to examples/ad_manager/v202108/native_style_service/__init__.py diff --git a/examples/ad_manager/v202011/native_style_service/create_native_styles.py b/examples/ad_manager/v202108/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v202011/native_style_service/create_native_styles.py rename to examples/ad_manager/v202108/native_style_service/create_native_styles.py index a21b32d9..2c5d913d 100755 --- a/examples/ad_manager/v202011/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202108/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202011') + version='v202108') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v202011/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202108/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v202011/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202108/native_style_service/get_all_native_styles.py index 75f8daeb..4bb3a1ee 100755 --- a/examples/ad_manager/v202011/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202108/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202011') + version='v202108') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v202011/network_service/__init__.py b/examples/ad_manager/v202108/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/network_service/__init__.py rename to examples/ad_manager/v202108/network_service/__init__.py diff --git a/examples/ad_manager/v202011/network_service/get_all_networks.py b/examples/ad_manager/v202108/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v202011/network_service/get_all_networks.py rename to examples/ad_manager/v202108/network_service/get_all_networks.py index 32b75f9f..63c25a90 100755 --- a/examples/ad_manager/v202011/network_service/get_all_networks.py +++ b/examples/ad_manager/v202108/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202011') + network_service = client.GetService('NetworkService', version='v202108') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v202011/network_service/get_current_network.py b/examples/ad_manager/v202108/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v202011/network_service/get_current_network.py rename to examples/ad_manager/v202108/network_service/get_current_network.py index 85322781..5f950e1f 100755 --- a/examples/ad_manager/v202011/network_service/get_current_network.py +++ b/examples/ad_manager/v202108/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202011') + network_service = client.GetService('NetworkService', version='v202108') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202011/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202108/network_service/get_default_third_party_data_declaration.py similarity index 95% rename from examples/ad_manager/v202011/network_service/get_default_third_party_data_declaration.py rename to examples/ad_manager/v202108/network_service/get_default_third_party_data_declaration.py index fde28b9e..6c4c7589 100755 --- a/examples/ad_manager/v202011/network_service/get_default_third_party_data_declaration.py +++ b/examples/ad_manager/v202108/network_service/get_default_third_party_data_declaration.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202011') + network_service = client.GetService('NetworkService', version='v202108') pql_service = client.GetService('PublisherQueryLanguageService', - version='v202011') + version='v202108') # Fetch the default third party data declarations. declarations = network_service.getDefaultThirdPartyDataDeclaration() @@ -44,7 +44,7 @@ def main(client): # In this case, there are third party companies to be displayed, so fetch # the company names from the Rich_Media_Ad_Company PQL table. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Select('Id, Name') .From('Rich_Media_Ad_Company') .Where('Id IN (:company_ids)') diff --git a/examples/ad_manager/v202011/network_service/make_test_network.py b/examples/ad_manager/v202108/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v202011/network_service/make_test_network.py rename to examples/ad_manager/v202108/network_service/make_test_network.py index 39625f78..0aabbe96 100755 --- a/examples/ad_manager/v202011/network_service/make_test_network.py +++ b/examples/ad_manager/v202108/network_service/make_test_network.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202011') + network_service = client.GetService('NetworkService', version='v202108') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v202011/order_service/__init__.py b/examples/ad_manager/v202108/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/order_service/__init__.py rename to examples/ad_manager/v202108/order_service/__init__.py diff --git a/examples/ad_manager/v202011/order_service/approve_orders.py b/examples/ad_manager/v202108/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v202011/order_service/approve_orders.py rename to examples/ad_manager/v202108/order_service/approve_orders.py index fce5c750..2a7d0aee 100755 --- a/examples/ad_manager/v202011/order_service/approve_orders.py +++ b/examples/ad_manager/v202108/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202011') + order_service = client.GetService('OrderService', version='v202108') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v202011/order_service/create_orders.py b/examples/ad_manager/v202108/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v202011/order_service/create_orders.py rename to examples/ad_manager/v202108/order_service/create_orders.py index 59308ae6..0c012c12 100755 --- a/examples/ad_manager/v202011/order_service/create_orders.py +++ b/examples/ad_manager/v202108/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202011') + order_service = client.GetService('OrderService', version='v202108') # Create order objects. orders = [] diff --git a/examples/ad_manager/v202011/order_service/get_all_orders.py b/examples/ad_manager/v202108/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v202011/order_service/get_all_orders.py rename to examples/ad_manager/v202108/order_service/get_all_orders.py index 68cc1a24..2733838f 100755 --- a/examples/ad_manager/v202011/order_service/get_all_orders.py +++ b/examples/ad_manager/v202108/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202011') + order_service = client.GetService('OrderService', version='v202108') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v202011/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202108/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v202011/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202108/order_service/get_orders_starting_soon.py index 8c2597ce..29e1d716 100755 --- a/examples/ad_manager/v202011/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202108/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202011') + order_service = client.GetService('OrderService', version='v202108') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v202011/order_service/update_orders.py b/examples/ad_manager/v202108/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v202011/order_service/update_orders.py rename to examples/ad_manager/v202108/order_service/update_orders.py index 8464eead..cce90f29 100755 --- a/examples/ad_manager/v202011/order_service/update_orders.py +++ b/examples/ad_manager/v202108/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202011') + order_service = client.GetService('OrderService', version='v202108') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202011/placement_service/create_placements.py b/examples/ad_manager/v202108/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v202011/placement_service/create_placements.py rename to examples/ad_manager/v202108/placement_service/create_placements.py index 7e9cf087..c6999bc1 100755 --- a/examples/ad_manager/v202011/placement_service/create_placements.py +++ b/examples/ad_manager/v202108/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202011') - inventory_service = client.GetService('InventoryService', version='v202011') + placement_service = client.GetService('PlacementService', version='v202108') + inventory_service = client.GetService('InventoryService', version='v202108') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v202011/placement_service/deactivate_placements.py b/examples/ad_manager/v202108/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v202011/placement_service/deactivate_placements.py rename to examples/ad_manager/v202108/placement_service/deactivate_placements.py index 879aef44..f08b5d9d 100755 --- a/examples/ad_manager/v202011/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202108/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202011') + placement_service = client.GetService('PlacementService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/placement_service/get_active_placements.py b/examples/ad_manager/v202108/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v202011/placement_service/get_active_placements.py rename to examples/ad_manager/v202108/placement_service/get_active_placements.py index 6f300b5a..d6458549 100755 --- a/examples/ad_manager/v202011/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202108/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202011') + placement_service = client.GetService('PlacementService', version='v202108') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202011/placement_service/get_all_placements.py b/examples/ad_manager/v202108/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v202011/placement_service/get_all_placements.py rename to examples/ad_manager/v202108/placement_service/get_all_placements.py index d530df49..d6bfe462 100755 --- a/examples/ad_manager/v202011/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202108/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202011') + placement_service = client.GetService('PlacementService', version='v202108') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v202011/placement_service/update_placements.py b/examples/ad_manager/v202108/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v202011/placement_service/update_placements.py rename to examples/ad_manager/v202108/placement_service/update_placements.py index 8e475329..38bfe3e5 100755 --- a/examples/ad_manager/v202011/placement_service/update_placements.py +++ b/examples/ad_manager/v202108/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202011') + placement_service = client.GetService('PlacementService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v202011/proposal_line_item_service/__init__.py b/examples/ad_manager/v202108/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202108/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v202011/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202108/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202011/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202108/proposal_line_item_service/archive_proposal_line_items.py index a9257659..415837d0 100755 --- a/examples/ad_manager/v202011/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202108/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202011') + 'ProposalLineItemService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202108/proposal_line_item_service/create_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202011/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202108/proposal_line_item_service/create_proposal_line_items.py index df6746f9..94437c84 100755 --- a/examples/ad_manager/v202011/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202108/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202011') - network_service = client.GetService('NetworkService', version='v202011') + 'ProposalLineItemService', version='v202108') + network_service = client.GetService('NetworkService', version='v202108') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) @@ -42,11 +42,6 @@ def main(client, proposal_id): # Create a single programmatic proposal line item. proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for proposal line items. 'name': 'Proposal line item #%s' % uuid.uuid4(), 'proposalId': proposal_id, @@ -56,6 +51,9 @@ def main(client, proposal_id): 'adUnitId': root_ad_unit_id } }, + 'requestPlatformTargeting': { + 'targetedRequestPlatforms': ['BROWSER'] + }, # Target Display environment by excluding Mobile Apps. # DeviceCapabilities can be obtained though the Device_Capability PQL # table: diff --git a/examples/ad_manager/v202011/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202108/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202011/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202108/proposal_line_item_service/get_all_proposal_line_items.py index 5610a67e..02d48882 100755 --- a/examples/ad_manager/v202011/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202108/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202011') + 'ProposalLineItemService', version='v202108') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v202011/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202108/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v202011/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202108/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 7c3902b8..f0be1c3c 100755 --- a/examples/ad_manager/v202011/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202108/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202011') + 'ProposalLineItemService', version='v202108') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v202011/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202108/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202011/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202108/proposal_line_item_service/update_proposal_line_items.py index fefb05d4..1ba0b014 100755 --- a/examples/ad_manager/v202011/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202108/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202011') + 'ProposalLineItemService', version='v202108') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/proposal_service/__init__.py b/examples/ad_manager/v202108/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/proposal_service/__init__.py rename to examples/ad_manager/v202108/proposal_service/__init__.py diff --git a/examples/ad_manager/v202011/proposal_service/create_proposals.py b/examples/ad_manager/v202108/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v202011/proposal_service/create_proposals.py rename to examples/ad_manager/v202108/proposal_service/create_proposals.py index e28bc305..f8f0b1c2 100755 --- a/examples/ad_manager/v202011/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202108/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v202011') + proposal_service = client.GetService('ProposalService', version='v202108') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v202011/proposal_service/get_all_proposals.py b/examples/ad_manager/v202108/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v202011/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202108/proposal_service/get_all_proposals.py index c126f7ad..251d57de 100755 --- a/examples/ad_manager/v202011/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202108/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202011') + proposal_service = client.GetService('ProposalService', version='v202108') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v202011/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202108/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v202011/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202108/proposal_service/get_marketplace_comments.py index c1c6e05f..53030640 100755 --- a/examples/ad_manager/v202011/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202108/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v202011') + 'ProposalService', version='v202108') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v202011/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202108/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v202011/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202108/proposal_service/get_proposals_awaiting_seller_review.py index a8a70e50..a39df2b4 100755 --- a/examples/ad_manager/v202011/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202108/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202011') + proposal_service = client.GetService('ProposalService', version='v202108') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v202011/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202108/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v202011/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202108/proposal_service/request_buyers_acceptance.py index f83e8bcc..df6fa250 100755 --- a/examples/ad_manager/v202011/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202108/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202011') + proposal_service = client.GetService('ProposalService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v202011/proposal_service/update_proposals.py b/examples/ad_manager/v202108/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v202011/proposal_service/update_proposals.py rename to examples/ad_manager/v202108/proposal_service/update_proposals.py index ac806926..b4e95e6a 100755 --- a/examples/ad_manager/v202011/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202108/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202011') + proposal_service = client.GetService('ProposalService', version='v202108') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/publisher_query_language_service/__init__.py b/examples/ad_manager/v202108/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202108/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v202011/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202108/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v202011/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202108/publisher_query_language_service/fetch_match_tables.py index 4787b36d..36803b61 100755 --- a/examples/ad_manager/v202011/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202108/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202011/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202108/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v202011/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202108/publisher_query_language_service/get_all_browsers.py index 0536323c..20bfb637 100755 --- a/examples/ad_manager/v202011/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202108/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v202011/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202108/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v202011/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202108/publisher_query_language_service/get_all_programmatic_buyers.py index 56b40951..8f17acfd 100755 --- a/examples/ad_manager/v202011/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202108/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202011') + data_downloader = client.GetDataDownloader(version='v202108') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202011/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202108/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v202011/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202108/publisher_query_language_service/get_geo_targets.py index 7f388f52..3215a864 100755 --- a/examples/ad_manager/v202011/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202108/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v202011/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202108/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v202011/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202108/publisher_query_language_service/get_line_items_named_like.py index a13f590f..22ac8faa 100755 --- a/examples/ad_manager/v202011/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202108/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202011/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202108/publisher_query_language_service/get_mcm_earnings.py similarity index 97% rename from examples/ad_manager/v202011/publisher_query_language_service/get_mcm_earnings.py rename to examples/ad_manager/v202108/publisher_query_language_service/get_mcm_earnings.py index 96ef524d..87b07962 100755 --- a/examples/ad_manager/v202011/publisher_query_language_service/get_mcm_earnings.py +++ b/examples/ad_manager/v202108/publisher_query_language_service/get_mcm_earnings.py @@ -26,7 +26,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202011') + data_downloader = client.GetDataDownloader(version='v202108') with tempfile.NamedTemporaryFile( prefix='mcm_earnings_', diff --git a/examples/ad_manager/v202011/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202108/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v202011/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202108/publisher_query_language_service/get_recent_changes.py index 16d14efd..2a7293ec 100755 --- a/examples/ad_manager/v202011/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202108/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v202011') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202108') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v202011/report_service/__init__.py b/examples/ad_manager/v202108/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/report_service/__init__.py rename to examples/ad_manager/v202108/report_service/__init__.py diff --git a/examples/ad_manager/v202011/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202108/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v202011/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202108/report_service/run_ad_exchange_report.py index 85806eda..56b8b726 100755 --- a/examples/ad_manager/v202011/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202108/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') # Create report job. report_job = { diff --git a/examples/ad_manager/v202011/report_service/run_delivery_report.py b/examples/ad_manager/v202108/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v202011/report_service/run_delivery_report.py rename to examples/ad_manager/v202108/report_service/run_delivery_report.py index ef6f0622..490386e3 100755 --- a/examples/ad_manager/v202011/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202108/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202011/report_service/run_inventory_report.py b/examples/ad_manager/v202108/report_service/run_inventory_report.py similarity index 97% rename from examples/ad_manager/v202011/report_service/run_inventory_report.py rename to examples/ad_manager/v202108/report_service/run_inventory_report.py index 2859a081..312e401e 100755 --- a/examples/ad_manager/v202011/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202108/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') # Create report job. report_job = { diff --git a/examples/ad_manager/v202011/report_service/run_reach_report.py b/examples/ad_manager/v202108/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v202011/report_service/run_reach_report.py rename to examples/ad_manager/v202108/report_service/run_reach_report.py index 47094ca7..4c44d067 100755 --- a/examples/ad_manager/v202011/report_service/run_reach_report.py +++ b/examples/ad_manager/v202108/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') # Create report job. report_job = { diff --git a/examples/ad_manager/v202108/report_service/run_reach_report_with_ad_unit_dimensions.py b/examples/ad_manager/v202108/report_service/run_reach_report_with_ad_unit_dimensions.py new file mode 100755 index 00000000..83e49f67 --- /dev/null +++ b/examples/ad_manager/v202108/report_service/run_reach_report_with_ad_unit_dimensions.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2021 Google LLC +# +# 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 code example runs a reach report.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v202108') + + # Create report job. + report_job = { + 'reportQuery': { + # For Reach reports with AD_UNIT_ID or AD_UNIT_NAME in the dimensions + # list, adUnitView must be set to 'FLAT' or 'HIERARCHICAL'. + 'adUnitView': 'FLAT', + 'dimensions': ['MONTH_AND_YEAR', 'COUNTRY_NAME', 'AD_UNIT_ID', + 'AD_UNIT_NAME'], + 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS', + 'UNIQUE_REACH'], + 'dateRangeType': 'LAST_MONTH' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202011/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202108/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v202011/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202108/report_service/run_report_and_create_match_table.py index 7a2753dd..7716ab7d 100755 --- a/examples/ad_manager/v202011/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202108/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202011/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202108/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v202011/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202108/report_service/run_report_with_custom_fields.py index f8ce5b96..131707fb 100755 --- a/examples/ad_manager/v202011/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202108/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') # Create report job. report_job = { diff --git a/examples/ad_manager/v202011/report_service/run_sales_report.py b/examples/ad_manager/v202108/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v202011/report_service/run_sales_report.py rename to examples/ad_manager/v202108/report_service/run_sales_report.py index e844afd0..e81be7a5 100755 --- a/examples/ad_manager/v202011/report_service/run_sales_report.py +++ b/examples/ad_manager/v202108/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') # Create report job. report_job = { diff --git a/examples/ad_manager/v202011/report_service/run_saved_query.py b/examples/ad_manager/v202108/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v202011/report_service/run_saved_query.py rename to examples/ad_manager/v202108/report_service/run_saved_query.py index 7eb5fb24..d3dc37a1 100755 --- a/examples/ad_manager/v202011/report_service/run_saved_query.py +++ b/examples/ad_manager/v202108/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v202011') + report_service = client.GetService('ReportService', version='v202108') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202011') + report_downloader = client.GetDataDownloader(version='v202108') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202011/site_service/create_sites.py b/examples/ad_manager/v202108/site_service/create_sites.py similarity index 96% rename from examples/ad_manager/v202011/site_service/create_sites.py rename to examples/ad_manager/v202108/site_service/create_sites.py index db184eb8..44430195 100755 --- a/examples/ad_manager/v202011/site_service/create_sites.py +++ b/examples/ad_manager/v202108/site_service/create_sites.py @@ -27,8 +27,8 @@ def main(client, url, child_network_code): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202011') - site_service = client.GetService('SiteService', version='v202011') + network_service = client.GetService('NetworkService', version='v202108') + site_service = client.GetService('SiteService', version='v202108') # Check that the child network code is approved for MANAGE_INVENTORY by this # network. diff --git a/examples/ad_manager/v202011/site_service/get_all_sites.py b/examples/ad_manager/v202108/site_service/get_all_sites.py similarity index 92% rename from examples/ad_manager/v202011/site_service/get_all_sites.py rename to examples/ad_manager/v202108/site_service/get_all_sites.py index 4700c348..3e112749 100755 --- a/examples/ad_manager/v202011/site_service/get_all_sites.py +++ b/examples/ad_manager/v202108/site_service/get_all_sites.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202011') + site_service = client.GetService('SiteService', version='v202108') # Create a statement to select Sites. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small number of sites at a time, paging through until all sites # have been retrieved. diff --git a/examples/ad_manager/v202011/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202108/site_service/get_sites_requiring_approval.py similarity index 92% rename from examples/ad_manager/v202011/site_service/get_sites_requiring_approval.py rename to examples/ad_manager/v202108/site_service/get_sites_requiring_approval.py index 8863fda4..e79a088f 100755 --- a/examples/ad_manager/v202011/site_service/get_sites_requiring_approval.py +++ b/examples/ad_manager/v202108/site_service/get_sites_requiring_approval.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202011') + site_service = client.GetService('SiteService', version='v202108') # Create a statement to select Sites needing approval. - statement = ad_manager.StatementBuilder(version='v202011').Where( + statement = ad_manager.StatementBuilder(version='v202108').Where( "approvalStatus = 'REQUIRES_REVIEW'") # Retrieve a small number of sites at a time, paging through until all sites diff --git a/examples/ad_manager/v202011/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202108/site_service/submit_sites_for_approval.py similarity index 91% rename from examples/ad_manager/v202011/site_service/submit_sites_for_approval.py rename to examples/ad_manager/v202108/site_service/submit_sites_for_approval.py index f06888b9..0e7b5dfd 100755 --- a/examples/ad_manager/v202011/site_service/submit_sites_for_approval.py +++ b/examples/ad_manager/v202108/site_service/submit_sites_for_approval.py @@ -25,10 +25,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202011') + site_service = client.GetService('SiteService', version='v202108') # Create a statement to select Site. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :id') .WithBindVariable('id', SITE_ID)) diff --git a/examples/ad_manager/v202011/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202108/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202108/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v202011/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202108/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v202011/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202108/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 18591c82..f52e5b51 100755 --- a/examples/ad_manager/v202011/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202108/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202011') + 'SuggestedAdUnitService', version='v202108') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v202011/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202108/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202011/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202108/suggested_ad_unit_service/get_all_suggested_ad_units.py index 33de1c49..8f30f82f 100755 --- a/examples/ad_manager/v202011/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202108/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202011') + 'SuggestedAdUnitService', version='v202108') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v202011/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202108/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202011/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202108/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 1aa6237a..4efa8ca0 100755 --- a/examples/ad_manager/v202011/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202108/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202011') + 'SuggestedAdUnitService', version='v202108') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v202011/targeting_preset_service/__init__.py b/examples/ad_manager/v202108/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/targeting_preset_service/__init__.py rename to examples/ad_manager/v202108/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202011/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py similarity index 94% rename from examples/ad_manager/v202011/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py index 61888539..adba3cad 100755 --- a/examples/ad_manager/v202011/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v202011') + 'TargetingPresetService', version='v202108') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. diff --git a/examples/ad_manager/v202011/team_service/__init__.py b/examples/ad_manager/v202108/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/team_service/__init__.py rename to examples/ad_manager/v202108/team_service/__init__.py diff --git a/examples/ad_manager/v202011/team_service/create_teams.py b/examples/ad_manager/v202108/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v202011/team_service/create_teams.py rename to examples/ad_manager/v202108/team_service/create_teams.py index a64671d8..e9ec11b2 100755 --- a/examples/ad_manager/v202011/team_service/create_teams.py +++ b/examples/ad_manager/v202108/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202011') + team_service = client.GetService('TeamService', version='v202108') # Create team objects. teams = [] diff --git a/examples/ad_manager/v202011/team_service/get_all_teams.py b/examples/ad_manager/v202108/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v202011/team_service/get_all_teams.py rename to examples/ad_manager/v202108/team_service/get_all_teams.py index 4554a875..e160a5a8 100755 --- a/examples/ad_manager/v202011/team_service/get_all_teams.py +++ b/examples/ad_manager/v202108/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202011') + team_service = client.GetService('TeamService', version='v202108') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v202011/team_service/update_teams.py b/examples/ad_manager/v202108/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v202011/team_service/update_teams.py rename to examples/ad_manager/v202108/team_service/update_teams.py index 928e0f89..abf08b20 100755 --- a/examples/ad_manager/v202011/team_service/update_teams.py +++ b/examples/ad_manager/v202108/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202011') + team_service = client.GetService('TeamService', version='v202108') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v202011/user_service/__init__.py b/examples/ad_manager/v202108/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/user_service/__init__.py rename to examples/ad_manager/v202108/user_service/__init__.py diff --git a/examples/ad_manager/v202011/user_service/create_users.py b/examples/ad_manager/v202108/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v202011/user_service/create_users.py rename to examples/ad_manager/v202108/user_service/create_users.py index 071f9aa5..c8343ab0 100755 --- a/examples/ad_manager/v202011/user_service/create_users.py +++ b/examples/ad_manager/v202108/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202011') + user_service = client.GetService('UserService', version='v202108') # Create user objects. users = [ diff --git a/examples/ad_manager/v202011/user_service/deactivate_users.py b/examples/ad_manager/v202108/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v202011/user_service/deactivate_users.py rename to examples/ad_manager/v202108/user_service/deactivate_users.py index fcbf2fca..4f4c79cf 100755 --- a/examples/ad_manager/v202011/user_service/deactivate_users.py +++ b/examples/ad_manager/v202108/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202011') + user_service = client.GetService('UserService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202011/user_service/get_all_roles.py b/examples/ad_manager/v202108/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v202011/user_service/get_all_roles.py rename to examples/ad_manager/v202108/user_service/get_all_roles.py index aa08cdea..b3e84d01 100755 --- a/examples/ad_manager/v202011/user_service/get_all_roles.py +++ b/examples/ad_manager/v202108/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202011') + user_service = client.GetService('UserService', version='v202108') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v202011/user_service/get_all_users.py b/examples/ad_manager/v202108/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v202011/user_service/get_all_users.py rename to examples/ad_manager/v202108/user_service/get_all_users.py index cfcdaa73..2815fb67 100755 --- a/examples/ad_manager/v202011/user_service/get_all_users.py +++ b/examples/ad_manager/v202108/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202011') + user_service = client.GetService('UserService', version='v202108') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v202011/user_service/get_current_user.py b/examples/ad_manager/v202108/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v202011/user_service/get_current_user.py rename to examples/ad_manager/v202108/user_service/get_current_user.py index e9cd1924..cce3f029 100755 --- a/examples/ad_manager/v202011/user_service/get_current_user.py +++ b/examples/ad_manager/v202108/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202011') + user_service = client.GetService('UserService', version='v202108') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v202011/user_service/get_user_by_email_address.py b/examples/ad_manager/v202108/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v202011/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202108/user_service/get_user_by_email_address.py index 7d5332b3..7d8f1724 100755 --- a/examples/ad_manager/v202011/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202108/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202011') + user_service = client.GetService('UserService', version='v202108') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v202011/user_service/update_users.py b/examples/ad_manager/v202108/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v202011/user_service/update_users.py rename to examples/ad_manager/v202108/user_service/update_users.py index 52bdeed6..960a13a6 100755 --- a/examples/ad_manager/v202011/user_service/update_users.py +++ b/examples/ad_manager/v202108/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202011') + user_service = client.GetService('UserService', version='v202108') # Create query. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202011/user_team_association_service/__init__.py b/examples/ad_manager/v202108/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202011/user_team_association_service/__init__.py rename to examples/ad_manager/v202108/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v202011/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202108/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v202011/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202108/user_team_association_service/create_user_team_associations.py index b97e4059..2c2da97b 100755 --- a/examples/ad_manager/v202011/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202108/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202011') + 'UserTeamAssociationService', version='v202108') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v202011/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202108/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v202011/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202108/user_team_association_service/delete_user_team_associations.py index e64521e7..d6f3eebb 100755 --- a/examples/ad_manager/v202011/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202108/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202011') + 'UserTeamAssociationService', version='v202108') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202011/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202108/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v202011/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202108/user_team_association_service/get_all_user_team_associations.py index f7b3a382..37c0d2cc 100755 --- a/examples/ad_manager/v202011/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202108/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202011') + 'UserTeamAssociationService', version='v202108') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v202011') + statement = ad_manager.StatementBuilder(version='v202108') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v202011/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202108/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v202011/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202108/user_team_association_service/get_user_team_associations_for_user.py index 92807584..29986ba7 100755 --- a/examples/ad_manager/v202011/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202108/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202011') + 'UserTeamAssociationService', version='v202108') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202011/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202108/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v202011/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202108/user_team_association_service/update_user_team_associations.py index 361b12ea..8e8c30bf 100755 --- a/examples/ad_manager/v202011/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202108/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202011') + 'UserTeamAssociationService', version='v202108') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202011') + statement = (ad_manager.StatementBuilder(version='v202108') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 1c0f34fc..c96d8e6d 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,7 +44,7 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v202008': + 'v202011': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -62,7 +62,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202011': + 'v202102': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -80,7 +80,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202102': + 'v202105': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -98,7 +98,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202105': + 'v202108': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', diff --git a/googleads/common.py b/googleads/common.py index a91957b3..99626be0 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -54,7 +54,7 @@ 'order to benefit from important security improvements and ensure ' 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '28.0.0' +VERSION = '29.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 99dec9d9..41d49518 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202105' +CURRENT_VERSION = 'v202108' class CommonTest(testing.CleanUtilityRegistryTestCase): From eacbb64be0344d709bc5b59786c678560c45e274 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 17 Aug 2021 16:46:40 -0400 Subject: [PATCH 171/180] Commiting latest changes. From 86c3d0558fcc30135ff44700a499678c7e69e0c0 Mon Sep 17 00:00:00 2001 From: Manolo Date: Mon, 25 Oct 2021 21:10:14 +0200 Subject: [PATCH 172/180] Manuel af patch 1 (#490) * Fix print variable types * Fix print variable types * Fix print variable types --- .../targeting_preset_service/get_all_targeting_presets.py | 2 +- .../targeting_preset_service/get_all_targeting_presets.py | 2 +- .../targeting_preset_service/get_all_targeting_presets.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py index 05d6670e..3772a0f4 100755 --- a/examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py @@ -37,7 +37,7 @@ def main(client): for targeting_preset in response['results']: # Print out some information for each targeting preset. print( - 'Targeting preset with ID "%s" and name "%d" was found.\n' + 'Targeting preset with ID "%d" and name "%s" was found.\n' % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: diff --git a/examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py index 754c1f63..06a0e17c 100755 --- a/examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py @@ -37,7 +37,7 @@ def main(client): for targeting_preset in response['results']: # Print out some information for each targeting preset. print( - 'Targeting preset with ID "%s" and name "%d" was found.\n' + 'Targeting preset with ID "%d" and name "%s" was found.\n' % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: diff --git a/examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py index adba3cad..dd4b0a04 100755 --- a/examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py @@ -37,7 +37,7 @@ def main(client): for targeting_preset in response['results']: # Print out some information for each targeting preset. print( - 'Targeting preset with ID "%s" and name "%d" was found.\n' + 'Targeting preset with ID "%d" and name "%s" was found.\n' % (targeting_preset['id'], targeting_preset['name'])) statement.offset += statement.limit else: From 3519702bcc9ef2ce26257aad05c2b833a3d805e7 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 16 Nov 2021 15:02:01 -0500 Subject: [PATCH 173/180] Ad Manager v202111 release --- ChangeLog | 5 ++ .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 2 +- .../create_traffic_forecast_segments.py | 4 +- .../get_all_forecast_adjustments.py | 4 +- .../get_all_traffic_forecast_segments.py | 4 +- ...djustments_for_traffic_forecast_segment.py | 4 +- .../update_forecast_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../get_recently_modified_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +-- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../forecast_service/get_traffic_data.py | 4 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +-- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../push_creative_to_devices.py | 61 ++++++++++++++++ .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- ...et_default_third_party_data_declaration.py | 6 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 12 ++-- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- ...un_reach_report_with_ad_unit_dimensions.py | 69 +++++++++++++++++++ .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../site_service/create_sites.py | 4 +- .../site_service/get_all_sites.py | 4 +- .../get_sites_requiring_approval.py | 4 +- .../site_service/submit_sites_for_approval.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 24 +++---- googleads/common.py | 2 +- tests/ad_manager_test.py | 13 ++-- tests/common_test.py | 2 +- 204 files changed, 456 insertions(+), 332 deletions(-) rename examples/ad_manager/{v202102 => v202111}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v202102 => v202111}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v202102 => v202111}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v202102 => v202111}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v202102 => v202111}/activity_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v202102 => v202111}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v202102 => v202111}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v202102 => v202111}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v202102 => v202111}/adjustment_service/create_forecast_adjustments.py (99%) rename examples/ad_manager/{v202102 => v202111}/adjustment_service/create_traffic_forecast_segments.py (98%) rename examples/ad_manager/{v202102 => v202111}/adjustment_service/get_all_forecast_adjustments.py (95%) rename examples/ad_manager/{v202102 => v202111}/adjustment_service/get_all_traffic_forecast_segments.py (95%) rename examples/ad_manager/{v202102 => v202111}/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py (96%) rename examples/ad_manager/{v202102 => v202111}/adjustment_service/update_forecast_adjustments.py (96%) rename examples/ad_manager/{v202102 => v202111}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v202102 => v202111}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v202102 => v202111}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v202102 => v202111}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v202102 => v202111}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v202102 => v202111}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v202102 => v202111}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v202102 => v202111}/cms_metadata_service/activate_cms_metadata_values.py (95%) rename examples/ad_manager/{v202102 => v202111}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v202102 => v202111}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v202102 => v202111}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v202102 => v202111}/company_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/company_service/create_companies.py (99%) rename examples/ad_manager/{v202102 => v202111}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v202102 => v202111}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v202102 => v202111}/company_service/update_companies.py (96%) rename examples/ad_manager/{v202102 => v202111}/contact_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v202102 => v202111}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v202102 => v202111}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v202102 => v202111}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v202102 => v202111}/content_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/content_service/get_all_content.py (96%) rename examples/ad_manager/{v202102 => v202111}/content_service/get_recently_modified_content.py (97%) rename examples/ad_manager/{v202102 => v202111}/creative_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v202102 => v202111}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v202102 => v202111}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v202102 => v202111}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v202102 => v202111}/creative_service/create_native_creative.py (99%) rename examples/ad_manager/{v202102 => v202111}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v202102 => v202111}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v202102 => v202111}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v202102 => v202111}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v202102 => v202111}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v202102 => v202111}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v202102 => v202111}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v202102 => v202111}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v202102 => v202111}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v202102 => v202111}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v202102 => v202111}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v202102 => v202111}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v202102 => v202111}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v202102 => v202111}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v202102 => v202111}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v202102 => v202111}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v202102 => v202111}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v202102 => v202111}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v202102 => v202111}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v202102 => v202111}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v202102 => v202111}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v202102 => v202111}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v202102 => v202111}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v202102 => v202111}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202102 => v202111}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v202102 => v202111}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202102 => v202111}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202102 => v202111}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202102 => v202111}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v202102 => v202111}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v202102 => v202111}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v202102 => v202111}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v202102 => v202111}/forecast_service/get_traffic_data.py (99%) rename examples/ad_manager/{v202102 => v202111}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v202102 => v202111}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v202102 => v202111}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v202102 => v202111}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v202102 => v202111}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v202102 => v202111}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v202102 => v202111}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v202102 => v202111}/label_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/label_service/create_labels.py (99%) rename examples/ad_manager/{v202102 => v202111}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v202102 => v202111}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v202102 => v202111}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v202102 => v202111}/label_service/update_labels.py (96%) rename examples/ad_manager/{v202102 => v202111}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v202102 => v202111}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v202102 => v202111}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v202102 => v202111}/line_item_creative_association_service/get_licas_for_line_item.py (94%) create mode 100755 examples/ad_manager/v202111/line_item_creative_association_service/push_creative_to_devices.py rename examples/ad_manager/{v202102 => v202111}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v202102 => v202111}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v202102 => v202111}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v202102 => v202111}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v202102 => v202111}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v202102 => v202111}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v202102 => v202111}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v202102 => v202111}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v202102 => v202111}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v202102 => v202111}/network_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v202102 => v202111}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v202102 => v202111}/network_service/get_default_third_party_data_declaration.py (95%) rename examples/ad_manager/{v202102 => v202111}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v202102 => v202111}/order_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v202102 => v202111}/order_service/create_orders.py (99%) rename examples/ad_manager/{v202102 => v202111}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v202102 => v202111}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v202102 => v202111}/order_service/update_orders.py (97%) rename examples/ad_manager/{v202102 => v202111}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v202102 => v202111}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v202102 => v202111}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v202102 => v202111}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v202102 => v202111}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v202102 => v202111}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v202102 => v202111}/proposal_line_item_service/create_proposal_line_items.py (94%) rename examples/ad_manager/{v202102 => v202111}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v202102 => v202111}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v202102 => v202111}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v202102 => v202111}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v202102 => v202111}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v202102 => v202111}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v202102 => v202111}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v202102 => v202111}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v202102 => v202111}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v202102 => v202111}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v202102 => v202111}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v202102 => v202111}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v202102 => v202111}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v202102 => v202111}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v202102 => v202111}/publisher_query_language_service/get_mcm_earnings.py (97%) rename examples/ad_manager/{v202102 => v202111}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v202102 => v202111}/report_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v202102 => v202111}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v202102 => v202111}/report_service/run_inventory_report.py (97%) rename examples/ad_manager/{v202102 => v202111}/report_service/run_reach_report.py (96%) create mode 100755 examples/ad_manager/v202111/report_service/run_reach_report_with_ad_unit_dimensions.py rename examples/ad_manager/{v202102 => v202111}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v202102 => v202111}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v202102 => v202111}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v202102 => v202111}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v202102 => v202111}/site_service/create_sites.py (99%) rename examples/ad_manager/{v202102 => v202111}/site_service/get_all_sites.py (96%) rename examples/ad_manager/{v202102 => v202111}/site_service/get_sites_requiring_approval.py (96%) rename examples/ad_manager/{v202102 => v202111}/site_service/submit_sites_for_approval.py (95%) rename examples/ad_manager/{v202102 => v202111}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v202102 => v202111}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v202102 => v202111}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v202102 => v202111}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/targeting_preset_service/get_all_targeting_presets.py (94%) rename examples/ad_manager/{v202102 => v202111}/team_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/team_service/create_teams.py (99%) rename examples/ad_manager/{v202102 => v202111}/team_service/get_all_teams.py (96%) rename examples/ad_manager/{v202102 => v202111}/team_service/update_teams.py (97%) rename examples/ad_manager/{v202102 => v202111}/user_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/user_service/create_users.py (99%) rename examples/ad_manager/{v202102 => v202111}/user_service/deactivate_users.py (97%) rename examples/ad_manager/{v202102 => v202111}/user_service/get_all_roles.py (99%) rename examples/ad_manager/{v202102 => v202111}/user_service/get_all_users.py (96%) rename examples/ad_manager/{v202102 => v202111}/user_service/get_current_user.py (99%) rename examples/ad_manager/{v202102 => v202111}/user_service/get_user_by_email_address.py (96%) rename examples/ad_manager/{v202102 => v202111}/user_service/update_users.py (96%) rename examples/ad_manager/{v202102 => v202111}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v202102 => v202111}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v202102 => v202111}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v202102 => v202111}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v202102 => v202111}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v202102 => v202111}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index d3c98371..4d6ace8e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +30.0.0 -- 11/16/2021 +* Added support for Ad Manager v202111. +* Removed support for Ad Manager v202011. +* Removed examples for Ad Manager v202102. + 29.0.0 -- 08/16/2021 * Added support for Ad Manager v202108. * Removed support for Ad Manager v202008. diff --git a/examples/ad_manager/v202102/activity_group_service/__init__.py b/examples/ad_manager/v202111/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/activity_group_service/__init__.py rename to examples/ad_manager/v202111/activity_group_service/__init__.py diff --git a/examples/ad_manager/v202102/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202111/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v202102/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202111/activity_group_service/create_activity_groups.py index 09ba3d27..86a393a1 100755 --- a/examples/ad_manager/v202102/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202111/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202102') + version='v202111') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v202102/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202111/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v202102/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202111/activity_group_service/get_active_activity_groups.py index 51403956..116c60ed 100755 --- a/examples/ad_manager/v202102/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202111/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202102') + 'ActivityGroupService', version='v202111') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202102/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202111/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v202102/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202111/activity_group_service/get_all_activity_groups.py index c35c4ef4..29aed6cd 100755 --- a/examples/ad_manager/v202102/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202111/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202102') + 'ActivityGroupService', version='v202111') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v202102/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202111/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v202102/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202111/activity_group_service/update_activity_groups.py index 74634d5c..a3614e73 100755 --- a/examples/ad_manager/v202102/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202111/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202102') + version='v202111') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/activity_service/__init__.py b/examples/ad_manager/v202111/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/activity_service/__init__.py rename to examples/ad_manager/v202111/activity_service/__init__.py diff --git a/examples/ad_manager/v202102/activity_service/create_activities.py b/examples/ad_manager/v202111/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v202102/activity_service/create_activities.py rename to examples/ad_manager/v202111/activity_service/create_activities.py index 603afbfa..eeac1eac 100755 --- a/examples/ad_manager/v202102/activity_service/create_activities.py +++ b/examples/ad_manager/v202111/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202102') + activity_service = client.GetService('ActivityService', version='v202111') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v202102/activity_service/get_active_activities.py b/examples/ad_manager/v202111/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v202102/activity_service/get_active_activities.py rename to examples/ad_manager/v202111/activity_service/get_active_activities.py index 84628643..a43313a2 100755 --- a/examples/ad_manager/v202102/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202111/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202102') + activity_service = client.GetService('ActivityService', version='v202111') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202102/activity_service/get_all_activities.py b/examples/ad_manager/v202111/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v202102/activity_service/get_all_activities.py rename to examples/ad_manager/v202111/activity_service/get_all_activities.py index b7b016bd..28c57afd 100755 --- a/examples/ad_manager/v202102/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202111/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202102') + activity_service = client.GetService('ActivityService', version='v202111') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v202102/activity_service/update_activities.py b/examples/ad_manager/v202111/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v202102/activity_service/update_activities.py rename to examples/ad_manager/v202111/activity_service/update_activities.py index 7d021289..50b98f2c 100755 --- a/examples/ad_manager/v202102/activity_service/update_activities.py +++ b/examples/ad_manager/v202111/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202102') + activity_service = client.GetService('ActivityService', version='v202111') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202111/adjustment_service/create_forecast_adjustments.py similarity index 99% rename from examples/ad_manager/v202102/adjustment_service/create_forecast_adjustments.py rename to examples/ad_manager/v202111/adjustment_service/create_forecast_adjustments.py index 87d06d3a..d7e73355 100755 --- a/examples/ad_manager/v202102/adjustment_service/create_forecast_adjustments.py +++ b/examples/ad_manager/v202111/adjustment_service/create_forecast_adjustments.py @@ -27,7 +27,7 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202102') + adjustment_service = client.GetService('AdjustmentService', version='v202111') # Create a new forecast adjustment for New Year's Day traffic. this_new_years = datetime.date(datetime.date.today().year, 1, 1) diff --git a/examples/ad_manager/v202102/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202111/adjustment_service/create_traffic_forecast_segments.py similarity index 98% rename from examples/ad_manager/v202102/adjustment_service/create_traffic_forecast_segments.py rename to examples/ad_manager/v202111/adjustment_service/create_traffic_forecast_segments.py index 755cb72c..7b0e4d65 100755 --- a/examples/ad_manager/v202102/adjustment_service/create_traffic_forecast_segments.py +++ b/examples/ad_manager/v202111/adjustment_service/create_traffic_forecast_segments.py @@ -25,8 +25,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v202102') - network_service = client.GetService('NetworkService', version='v202102') + adjustment_service = client.GetService('AdjustmentService', version='v202111') + network_service = client.GetService('NetworkService', version='v202111') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202102/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202111/adjustment_service/get_all_forecast_adjustments.py similarity index 95% rename from examples/ad_manager/v202102/adjustment_service/get_all_forecast_adjustments.py rename to examples/ad_manager/v202111/adjustment_service/get_all_forecast_adjustments.py index a3dfef10..7b68b305 100755 --- a/examples/ad_manager/v202102/adjustment_service/get_all_forecast_adjustments.py +++ b/examples/ad_manager/v202111/adjustment_service/get_all_forecast_adjustments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202102') + adjustment_service = client.GetService('AdjustmentService', version='v202111') # Create a statement to get all forecast adjustments. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small number of forecast adjustments at a time, paging # through until all forecast adjustments have been retrieved. diff --git a/examples/ad_manager/v202102/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202111/adjustment_service/get_all_traffic_forecast_segments.py similarity index 95% rename from examples/ad_manager/v202102/adjustment_service/get_all_traffic_forecast_segments.py rename to examples/ad_manager/v202111/adjustment_service/get_all_traffic_forecast_segments.py index 248b2c47..ed1320fd 100755 --- a/examples/ad_manager/v202102/adjustment_service/get_all_traffic_forecast_segments.py +++ b/examples/ad_manager/v202111/adjustment_service/get_all_traffic_forecast_segments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202102') + adjustment_service = client.GetService('AdjustmentService', version='v202111') # Create a statement to get all traffic forecast segments. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small number of segments at a time, paging through until all # segments have been retrieved. diff --git a/examples/ad_manager/v202102/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202111/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py similarity index 96% rename from examples/ad_manager/v202102/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py rename to examples/ad_manager/v202111/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py index f8bf7926..1e2c76eb 100755 --- a/examples/ad_manager/v202102/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py +++ b/examples/ad_manager/v202111/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -24,11 +24,11 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202102') + adjustment_service = client.GetService('AdjustmentService', version='v202111') # Create a statement to get forecast adjustments for a given traffic forecast # segment id. - statement = ad_manager.StatementBuilder(version='v202102').Where( + statement = ad_manager.StatementBuilder(version='v202111').Where( 'trafficForecastSegmentId = :segmentId').WithBindVariable( 'segmentId', traffic_forecast_segment_id) diff --git a/examples/ad_manager/v202102/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202111/adjustment_service/update_forecast_adjustments.py similarity index 96% rename from examples/ad_manager/v202102/adjustment_service/update_forecast_adjustments.py rename to examples/ad_manager/v202111/adjustment_service/update_forecast_adjustments.py index 5b834140..0aa19204 100755 --- a/examples/ad_manager/v202102/adjustment_service/update_forecast_adjustments.py +++ b/examples/ad_manager/v202111/adjustment_service/update_forecast_adjustments.py @@ -24,12 +24,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202102') + adjustment_service = client.GetService('AdjustmentService', version='v202111') # Create a statement to select a single forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v202102').Where('id = :id').WithBindVariable( + version='v202111').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast adjustment. diff --git a/examples/ad_manager/v202102/audience_segment_service/__init__.py b/examples/ad_manager/v202111/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/audience_segment_service/__init__.py rename to examples/ad_manager/v202111/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v202102/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202111/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v202102/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202111/audience_segment_service/create_audience_segments.py index 443dd4b9..e4e2b386 100755 --- a/examples/ad_manager/v202102/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202111/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202102') - network_service = client.GetService('NetworkService', version='v202102') + 'AudienceSegmentService', version='v202111') + network_service = client.GetService('NetworkService', version='v202111') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v202102/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202111/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v202102/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202111/audience_segment_service/get_all_audience_segments.py index db2c179e..d7769038 100755 --- a/examples/ad_manager/v202102/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202111/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202102') + 'AudienceSegmentService', version='v202111') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v202102/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202111/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v202102/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202111/audience_segment_service/get_first_party_audience_segments.py index b2853ad9..c6916a5c 100755 --- a/examples/ad_manager/v202102/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202111/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202102') + 'AudienceSegmentService', version='v202111') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v202102/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202111/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v202102/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202111/audience_segment_service/populate_first_party_audience_segments.py index b7700b59..039baddb 100755 --- a/examples/ad_manager/v202102/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202111/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202102') + 'AudienceSegmentService', version='v202111') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202102/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202111/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v202102/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202111/audience_segment_service/update_audience_segments.py index c03663c8..ceb91153 100755 --- a/examples/ad_manager/v202102/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202111/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202102') + 'AudienceSegmentService', version='v202111') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202102/cdn_configuration_service/__init__.py b/examples/ad_manager/v202111/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202111/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v202102/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202111/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v202102/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202111/cdn_configuration_service/create_cdn_configurations.py index fb3c607d..7b7a2050 100755 --- a/examples/ad_manager/v202102/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202111/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202102') + version='v202111') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v202102/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202111/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v202102/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202111/cdn_configuration_service/get_all_cdn_configurations.py index f9054e05..97a40cd8 100755 --- a/examples/ad_manager/v202102/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202111/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202102') + version='v202111') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202102/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202111/cms_metadata_service/activate_cms_metadata_values.py similarity index 95% rename from examples/ad_manager/v202102/cms_metadata_service/activate_cms_metadata_values.py rename to examples/ad_manager/v202111/cms_metadata_service/activate_cms_metadata_values.py index 917692ac..ce56501d 100755 --- a/examples/ad_manager/v202102/cms_metadata_service/activate_cms_metadata_values.py +++ b/examples/ad_manager/v202111/cms_metadata_service/activate_cms_metadata_values.py @@ -28,10 +28,10 @@ def main(client, cms_metadata_key_id): # Initialize appropriate service. cms_metadata_service = client.GetService('CmsMetadataService', - version='v202102') + version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('cmsKeyId = :cmsKeyId AND status = :status') .WithBindVariable('status', 'INACTIVE') .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) diff --git a/examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_keys.py index 72b7b92b..880b2da3 100755 --- a/examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202102') + 'CmsMetadataService', version='v202111') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_values.py index d5e4a581..9a97dab9 100755 --- a/examples/ad_manager/v202102/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202102') + 'CmsMetadataService', version='v202111') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v202102/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202111/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v202102/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202111/cms_metadata_service/get_cms_metadata_values_for_key.py index 7b65114d..e2df73f1 100755 --- a/examples/ad_manager/v202102/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202111/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202102') + 'CmsMetadataService', version='v202111') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v202102').Where( + ad_manager.StatementBuilder(version='v202111').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v202102/company_service/__init__.py b/examples/ad_manager/v202111/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/company_service/__init__.py rename to examples/ad_manager/v202111/company_service/__init__.py diff --git a/examples/ad_manager/v202102/company_service/create_companies.py b/examples/ad_manager/v202111/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v202102/company_service/create_companies.py rename to examples/ad_manager/v202111/company_service/create_companies.py index f7c5da3c..842389d0 100755 --- a/examples/ad_manager/v202102/company_service/create_companies.py +++ b/examples/ad_manager/v202111/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202102') + company_service = client.GetService('CompanyService', version='v202111') # Create company objects. companies = [ diff --git a/examples/ad_manager/v202102/company_service/get_advertisers.py b/examples/ad_manager/v202111/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v202102/company_service/get_advertisers.py rename to examples/ad_manager/v202111/company_service/get_advertisers.py index f0db5881..0426f45c 100755 --- a/examples/ad_manager/v202102/company_service/get_advertisers.py +++ b/examples/ad_manager/v202111/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202102') + company_service = client.GetService('CompanyService', version='v202111') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v202102/company_service/get_all_companies.py b/examples/ad_manager/v202111/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v202102/company_service/get_all_companies.py rename to examples/ad_manager/v202111/company_service/get_all_companies.py index c83f56ca..d585fa25 100755 --- a/examples/ad_manager/v202102/company_service/get_all_companies.py +++ b/examples/ad_manager/v202111/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202102') + company_service = client.GetService('CompanyService', version='v202111') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v202102/company_service/update_companies.py b/examples/ad_manager/v202111/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v202102/company_service/update_companies.py rename to examples/ad_manager/v202111/company_service/update_companies.py index f94daa02..3363cecf 100755 --- a/examples/ad_manager/v202102/company_service/update_companies.py +++ b/examples/ad_manager/v202111/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202102') + company_service = client.GetService('CompanyService', version='v202111') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/contact_service/__init__.py b/examples/ad_manager/v202111/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/contact_service/__init__.py rename to examples/ad_manager/v202111/contact_service/__init__.py diff --git a/examples/ad_manager/v202102/contact_service/create_contacts.py b/examples/ad_manager/v202111/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v202102/contact_service/create_contacts.py rename to examples/ad_manager/v202111/contact_service/create_contacts.py index 431d79cd..c6757179 100755 --- a/examples/ad_manager/v202102/contact_service/create_contacts.py +++ b/examples/ad_manager/v202111/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202102') + contact_service = client.GetService('ContactService', version='v202111') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v202102/contact_service/get_all_contacts.py b/examples/ad_manager/v202111/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v202102/contact_service/get_all_contacts.py rename to examples/ad_manager/v202111/contact_service/get_all_contacts.py index 047cf34f..b97d9bd7 100755 --- a/examples/ad_manager/v202102/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202111/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202102') + contact_service = client.GetService('ContactService', version='v202111') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v202102/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202111/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v202102/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202111/contact_service/get_uninvited_contacts.py index 49a44b78..2efb4d9d 100755 --- a/examples/ad_manager/v202102/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202111/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202102') + contact_service = client.GetService('ContactService', version='v202111') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v202102/contact_service/update_contacts.py b/examples/ad_manager/v202111/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v202102/contact_service/update_contacts.py rename to examples/ad_manager/v202111/contact_service/update_contacts.py index b8a49fc1..94e69a1a 100755 --- a/examples/ad_manager/v202102/contact_service/update_contacts.py +++ b/examples/ad_manager/v202111/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202102') + contact_service = client.GetService('ContactService', version='v202111') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/content_service/__init__.py b/examples/ad_manager/v202111/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/content_service/__init__.py rename to examples/ad_manager/v202111/content_service/__init__.py diff --git a/examples/ad_manager/v202102/content_service/get_all_content.py b/examples/ad_manager/v202111/content_service/get_all_content.py similarity index 96% rename from examples/ad_manager/v202102/content_service/get_all_content.py rename to examples/ad_manager/v202111/content_service/get_all_content.py index bed36eff..4e232f5e 100755 --- a/examples/ad_manager/v202102/content_service/get_all_content.py +++ b/examples/ad_manager/v202111/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202102') + content_service = client.GetService('ContentService', version='v202111') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v202102/content_service/get_recently_modified_content.py b/examples/ad_manager/v202111/content_service/get_recently_modified_content.py similarity index 97% rename from examples/ad_manager/v202102/content_service/get_recently_modified_content.py rename to examples/ad_manager/v202111/content_service/get_recently_modified_content.py index c352e8be..21009e0b 100755 --- a/examples/ad_manager/v202102/content_service/get_recently_modified_content.py +++ b/examples/ad_manager/v202111/content_service/get_recently_modified_content.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202102') + content_service = client.GetService('ContentService', version='v202111') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -35,7 +35,7 @@ def main(client): # lastModifiedDateTime. Changes to content bundle associations will update # the lastModifiedDateTime, but CMS metadata changes may not change the # lastModifiedDateTime. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202102/creative_service/__init__.py b/examples/ad_manager/v202111/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/creative_service/__init__.py rename to examples/ad_manager/v202111/creative_service/__init__.py diff --git a/examples/ad_manager/v202102/creative_service/copy_image_creatives.py b/examples/ad_manager/v202111/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v202102/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202111/creative_service/copy_image_creatives.py index 7a2ae176..6debb319 100755 --- a/examples/ad_manager/v202102/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202111/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202102') + creative_service = client.GetService('CreativeService', version='v202111') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v202102/creative_service/create_creative_from_template.py b/examples/ad_manager/v202111/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v202102/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202111/creative_service/create_creative_from_template.py index ba6cab0b..b08d9fbb 100755 --- a/examples/ad_manager/v202102/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202111/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202102') + creative_service = client.GetService('CreativeService', version='v202111') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v202102/creative_service/create_creatives.py b/examples/ad_manager/v202111/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v202102/creative_service/create_creatives.py rename to examples/ad_manager/v202111/creative_service/create_creatives.py index 7c5f5f35..86d4827f 100755 --- a/examples/ad_manager/v202102/creative_service/create_creatives.py +++ b/examples/ad_manager/v202111/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202102') + creative_service = client.GetService('CreativeService', version='v202111') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v202102/creative_service/create_custom_creative.py b/examples/ad_manager/v202111/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v202102/creative_service/create_custom_creative.py rename to examples/ad_manager/v202111/creative_service/create_custom_creative.py index fcc30a97..a4adc9e8 100755 --- a/examples/ad_manager/v202102/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202111/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202102') + creative_service = client.GetService('CreativeService', version='v202111') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v202102/creative_service/create_native_creative.py b/examples/ad_manager/v202111/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v202102/creative_service/create_native_creative.py rename to examples/ad_manager/v202111/creative_service/create_native_creative.py index d0e9c983..ef230835 100755 --- a/examples/ad_manager/v202102/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202111/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202102') + creative_service = client.GetService('CreativeService', version='v202111') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v202102/creative_service/get_all_creatives.py b/examples/ad_manager/v202111/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v202102/creative_service/get_all_creatives.py rename to examples/ad_manager/v202111/creative_service/get_all_creatives.py index 99ce12f3..1786a57a 100755 --- a/examples/ad_manager/v202102/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202111/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202102') + creative_service = client.GetService('CreativeService', version='v202111') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v202102/creative_service/get_image_creatives.py b/examples/ad_manager/v202111/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v202102/creative_service/get_image_creatives.py rename to examples/ad_manager/v202111/creative_service/get_image_creatives.py index 2af60571..005cacc9 100755 --- a/examples/ad_manager/v202102/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202111/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202102') + creative_service = client.GetService('CreativeService', version='v202111') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v202102/creative_service/update_creatives.py b/examples/ad_manager/v202111/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v202102/creative_service/update_creatives.py rename to examples/ad_manager/v202111/creative_service/update_creatives.py index 89731429..bfca6f4a 100755 --- a/examples/ad_manager/v202102/creative_service/update_creatives.py +++ b/examples/ad_manager/v202111/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202102') + creative_service = client.GetService('CreativeService', version='v202111') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v202102/creative_set_service/__init__.py b/examples/ad_manager/v202111/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/creative_set_service/__init__.py rename to examples/ad_manager/v202111/creative_set_service/__init__.py diff --git a/examples/ad_manager/v202102/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202111/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v202102/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202111/creative_set_service/associate_creative_set_to_line_item.py index c31a1c5c..37c96287 100755 --- a/examples/ad_manager/v202102/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202111/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202102') + 'LineItemCreativeAssociationService', version='v202111') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v202102/creative_set_service/create_creative_set.py b/examples/ad_manager/v202111/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v202102/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202111/creative_set_service/create_creative_set.py index 6f331f03..842c45df 100755 --- a/examples/ad_manager/v202102/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202111/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202102') + version='v202111') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v202102/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202111/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v202102/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202111/creative_set_service/get_all_creative_sets.py index 7ae12a0c..855ee450 100755 --- a/examples/ad_manager/v202102/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202111/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202102') + 'CreativeSetService', version='v202111') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v202102/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202111/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v202102/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202111/creative_set_service/get_creative_sets_for_master_creative.py index bec8439d..b63f5cd0 100755 --- a/examples/ad_manager/v202102/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202111/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202102') + 'CreativeSetService', version='v202111') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v202102/creative_set_service/update_creative_set.py b/examples/ad_manager/v202111/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v202102/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202111/creative_set_service/update_creative_set.py index 5acea36d..a4e442ec 100755 --- a/examples/ad_manager/v202102/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202111/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202102') + version='v202111') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v202102/creative_template_service/__init__.py b/examples/ad_manager/v202111/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/creative_template_service/__init__.py rename to examples/ad_manager/v202111/creative_template_service/__init__.py diff --git a/examples/ad_manager/v202102/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202111/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v202102/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202111/creative_template_service/get_all_creative_templates.py index 3ff6f93d..43843b99 100755 --- a/examples/ad_manager/v202102/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202111/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202102') + 'CreativeTemplateService', version='v202111') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v202102/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202111/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v202102/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202111/creative_template_service/get_system_defined_creative_templates.py index f3c8039b..1f4cab4e 100755 --- a/examples/ad_manager/v202102/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202111/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202102') + 'CreativeTemplateService', version='v202111') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v202102/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202111/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v202102/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202111/creative_wrapper_service/create_creative_wrappers.py index aa697e2f..010f11b3 100755 --- a/examples/ad_manager/v202102/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202111/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202102') + version='v202111') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v202102/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202111/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v202102/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202111/creative_wrapper_service/deactivate_creative_wrapper.py index 5b520d79..64fcb18a 100755 --- a/examples/ad_manager/v202102/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202111/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202102') + version='v202111') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202102/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202111/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202102/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202111/creative_wrapper_service/get_active_creative_wrappers.py index 504a0e9d..9d01c7c2 100755 --- a/examples/ad_manager/v202102/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202111/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202102') + 'CreativeWrapperService', version='v202111') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202102/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202111/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202102/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202111/creative_wrapper_service/get_all_creative_wrappers.py index f854bb08..93654fe9 100755 --- a/examples/ad_manager/v202102/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202111/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202102') + 'CreativeWrapperService', version='v202111') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v202102/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202111/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v202102/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202111/creative_wrapper_service/update_creative_wrappers.py index 8c832bac..9ea9d229 100755 --- a/examples/ad_manager/v202102/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202111/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202102') + version='v202111') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v202102/custom_field_service/__init__.py b/examples/ad_manager/v202111/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/custom_field_service/__init__.py rename to examples/ad_manager/v202111/custom_field_service/__init__.py diff --git a/examples/ad_manager/v202102/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202111/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v202102/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202111/custom_field_service/create_custom_field_options.py index 8ae8e79a..7f607a92 100755 --- a/examples/ad_manager/v202102/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202111/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202102') + 'CustomFieldService', version='v202111') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v202102/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202111/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v202102/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202111/custom_field_service/create_custom_fields.py index 6c0f7e46..55ef95e7 100755 --- a/examples/ad_manager/v202102/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202111/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202102') + 'CustomFieldService', version='v202111') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v202102/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202111/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v202102/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202111/custom_field_service/deactivate_all_line_item_custom_fields.py index 11b066ac..01dde679 100755 --- a/examples/ad_manager/v202102/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202111/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202102') + 'CustomFieldService', version='v202111') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202102/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202111/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v202102/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202111/custom_field_service/get_all_custom_fields.py index aab4b6e3..6c562042 100755 --- a/examples/ad_manager/v202102/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202111/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202102') + 'CustomFieldService', version='v202111') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v202102/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202111/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v202102/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202111/custom_field_service/get_custom_fields_for_line_items.py index 106d63cb..d1efabea 100755 --- a/examples/ad_manager/v202102/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202111/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202102') + 'CustomFieldService', version='v202111') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v202102/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202111/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v202102/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202111/custom_field_service/set_line_item_custom_field_value.py index 4fa4af7b..6546b508 100755 --- a/examples/ad_manager/v202102/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202111/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v202102') + 'CustomFieldService', version='v202111') - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v202102') + custom_field_statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v202102') + ad_manager.StatementBuilder(version='v202111') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v202102') + line_item_statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v202102/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202111/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v202102/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202111/custom_field_service/update_custom_fields.py index a345d29d..e1a71a63 100755 --- a/examples/ad_manager/v202102/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202111/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202102') + 'CustomFieldService', version='v202111') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v202102/custom_targeting_service/__init__.py b/examples/ad_manager/v202111/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/custom_targeting_service/__init__.py rename to examples/ad_manager/v202111/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v202102/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202111/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v202102/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202111/custom_targeting_service/create_custom_targeting_keys_and_values.py index e9a45ccf..85bc00db 100755 --- a/examples/ad_manager/v202102/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202111/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202102') + 'CustomTargetingService', version='v202111') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_keys.py index 93ba354e..9e1e1679 100755 --- a/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202102') + 'CustomTargetingService', version='v202111') - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v202102') + key_statement = (ad_manager.StatementBuilder(version='v202111') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_values.py index 8300508d..442d81fa 100755 --- a/examples/ad_manager/v202102/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202102') + 'CustomTargetingService', version='v202111') - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [str(value['id']) for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v202102') + value_statement = (ad_manager.StatementBuilder(version='v202111') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v202102/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202111/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202102/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202111/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index bd3d6004..fc375b92 100755 --- a/examples/ad_manager/v202102/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202111/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202102') + 'CustomTargetingService', version='v202111') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v202102') + targeting_key_statement = ad_manager.StatementBuilder(version='v202111') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v202102/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202111/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202102/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202111/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 1d330368..b6674a32 100755 --- a/examples/ad_manager/v202102/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202111/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202102') + 'CustomTargetingService', version='v202111') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v202102') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202111') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_keys.py index a922535c..39238615 100755 --- a/examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202102') + 'CustomTargetingService', version='v202111') - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_values.py index 1e3de787..4ee2f3a9 100755 --- a/examples/ad_manager/v202102/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202102') + 'CustomTargetingService', version='v202111') - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v202102/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202111/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v202102/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202111/forecast_service/get_availability_forecast.py index 000a6a38..dcc84c2a 100755 --- a/examples/ad_manager/v202102/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202111/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202102') - network_service = client.GetService('NetworkService', version='v202102') + forecast_service = client.GetService('ForecastService', version='v202111') + network_service = client.GetService('NetworkService', version='v202111') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202102/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202111/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v202102/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202111/forecast_service/get_availability_forecast_for_line_item.py index 341ecaec..e9fab2bb 100755 --- a/examples/ad_manager/v202102/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202111/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202102') + forecast_service = client.GetService('ForecastService', version='v202111') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v202102/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202111/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v202102/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202111/forecast_service/get_delivery_forecast_for_line_items.py index 3a5591c2..72fd186d 100755 --- a/examples/ad_manager/v202102/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202111/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202102') + forecast_service = client.GetService('ForecastService', version='v202111') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v202102/forecast_service/get_traffic_data.py b/examples/ad_manager/v202111/forecast_service/get_traffic_data.py similarity index 99% rename from examples/ad_manager/v202102/forecast_service/get_traffic_data.py rename to examples/ad_manager/v202111/forecast_service/get_traffic_data.py index 929e0303..8b4e960f 100755 --- a/examples/ad_manager/v202102/forecast_service/get_traffic_data.py +++ b/examples/ad_manager/v202111/forecast_service/get_traffic_data.py @@ -25,8 +25,8 @@ def main(client): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202102') - network_service = client.GetService('NetworkService', version='v202102') + forecast_service = client.GetService('ForecastService', version='v202111') + network_service = client.GetService('NetworkService', version='v202111') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202102/inventory_service/__init__.py b/examples/ad_manager/v202111/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/inventory_service/__init__.py rename to examples/ad_manager/v202111/inventory_service/__init__.py diff --git a/examples/ad_manager/v202102/inventory_service/archive_ad_units.py b/examples/ad_manager/v202111/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v202102/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202111/inventory_service/archive_ad_units.py index 2ae06578..c6d798da 100755 --- a/examples/ad_manager/v202102/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202111/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202102') + inventory_service = client.GetService('InventoryService', version='v202111') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v202102/inventory_service/create_ad_units.py b/examples/ad_manager/v202111/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v202102/inventory_service/create_ad_units.py rename to examples/ad_manager/v202111/inventory_service/create_ad_units.py index dda9f758..cec6963b 100755 --- a/examples/ad_manager/v202102/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202111/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202102') + inventory_service = client.GetService('InventoryService', version='v202111') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v202102/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202111/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v202102/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202111/inventory_service/get_ad_unit_hierarchy.py index a7e9c1b9..16f5b669 100755 --- a/examples/ad_manager/v202102/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202111/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202102') - inventory_service = client.GetService('InventoryService', version='v202102') + network_service = client.GetService('NetworkService', version='v202111') + inventory_service = client.GetService('InventoryService', version='v202111') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v202102/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202111/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v202102/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202111/inventory_service/get_all_ad_unit_sizes.py index 221f37f4..57949087 100755 --- a/examples/ad_manager/v202102/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202111/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v202102') + 'InventoryService', version='v202111') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v202102/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202111/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v202102/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202111/inventory_service/get_all_ad_units.py index 7845b201..a71fd0fd 100755 --- a/examples/ad_manager/v202102/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202111/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v202102') + ad_unit_service = client.GetService('InventoryService', version='v202111') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v202102/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202111/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v202102/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202111/inventory_service/get_top_level_ad_units.py index 8a5278e4..35d6aefd 100755 --- a/examples/ad_manager/v202102/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202111/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202102') - inventory_service = client.GetService('InventoryService', version='v202102') + network_service = client.GetService('NetworkService', version='v202111') + inventory_service = client.GetService('InventoryService', version='v202111') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v202102/inventory_service/update_ad_units.py b/examples/ad_manager/v202111/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v202102/inventory_service/update_ad_units.py rename to examples/ad_manager/v202111/inventory_service/update_ad_units.py index 65f88555..8681c7d7 100755 --- a/examples/ad_manager/v202102/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202111/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202102') + inventory_service = client.GetService('InventoryService', version='v202111') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v202102/label_service/__init__.py b/examples/ad_manager/v202111/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/label_service/__init__.py rename to examples/ad_manager/v202111/label_service/__init__.py diff --git a/examples/ad_manager/v202102/label_service/create_labels.py b/examples/ad_manager/v202111/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v202102/label_service/create_labels.py rename to examples/ad_manager/v202111/label_service/create_labels.py index 882c1aca..f51b6d72 100755 --- a/examples/ad_manager/v202102/label_service/create_labels.py +++ b/examples/ad_manager/v202111/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202102') + label_service = client.GetService('LabelService', version='v202111') # Create label objects. labels = [] diff --git a/examples/ad_manager/v202102/label_service/deactivate_labels.py b/examples/ad_manager/v202111/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v202102/label_service/deactivate_labels.py rename to examples/ad_manager/v202111/label_service/deactivate_labels.py index 91365d05..cf5c38f9 100755 --- a/examples/ad_manager/v202102/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202111/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202102') + label_service = client.GetService('LabelService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202102/label_service/get_active_labels.py b/examples/ad_manager/v202111/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v202102/label_service/get_active_labels.py rename to examples/ad_manager/v202111/label_service/get_active_labels.py index aeb381ef..6e4347e9 100755 --- a/examples/ad_manager/v202102/label_service/get_active_labels.py +++ b/examples/ad_manager/v202111/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202102') + label_service = client.GetService('LabelService', version='v202111') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202102/label_service/get_all_labels.py b/examples/ad_manager/v202111/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v202102/label_service/get_all_labels.py rename to examples/ad_manager/v202111/label_service/get_all_labels.py index cfc8ffaf..c8ada449 100755 --- a/examples/ad_manager/v202102/label_service/get_all_labels.py +++ b/examples/ad_manager/v202111/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202102') + label_service = client.GetService('LabelService', version='v202111') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v202102/label_service/update_labels.py b/examples/ad_manager/v202111/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v202102/label_service/update_labels.py rename to examples/ad_manager/v202111/label_service/update_labels.py index 5cb2d189..ca5badab 100755 --- a/examples/ad_manager/v202102/label_service/update_labels.py +++ b/examples/ad_manager/v202111/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202102') + label_service = client.GetService('LabelService', version='v202111') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202102/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202111/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202111/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v202102/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202111/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v202102/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202111/line_item_creative_association_service/create_licas.py index f93b964c..e3200c7a 100755 --- a/examples/ad_manager/v202102/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202111/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202102') + 'LineItemCreativeAssociationService', version='v202111') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v202102/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202111/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v202102/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202111/line_item_creative_association_service/deactivate_licas.py index 3fb6fff7..b11ae22d 100755 --- a/examples/ad_manager/v202102/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202111/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202102') + 'LineItemCreativeAssociationService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v202102/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202111/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v202102/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202111/line_item_creative_association_service/get_all_licas.py index 228adaec..6a2b58ef 100755 --- a/examples/ad_manager/v202102/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202111/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202102') + 'LineItemCreativeAssociationService', version='v202111') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v202102/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202111/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v202102/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202111/line_item_creative_association_service/get_licas_for_line_item.py index b8870110..a30103e2 100755 --- a/examples/ad_manager/v202102/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202111/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202102') + 'LineItemCreativeAssociationService', version='v202111') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v202111/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202111/line_item_creative_association_service/push_creative_to_devices.py new file mode 100755 index 00000000..23a6efdd --- /dev/null +++ b/examples/ad_manager/v202111/line_item_creative_association_service/push_creative_to_devices.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# +# Copyright 2021, Google LLC +# +# 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 pushes a LICA to a linked device for preview. + +To determine which linked devices exist, use the PublisherQueryLanguageService +linked_device table. +""" + + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set the associated line item id and creative id to push, and set the linked +# device id where it will be pushed. +LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE' +CREATIVE_ID = 'INSERT_CREATIVE_ID_HERE' +LINKED_DEVICE_ID = 'INSERT_LINKED_DEVICE_ID_HERE' + + +def main(client, line_item_id, creative_id, linked_device_id): + # Initialize appropriate service. + lica_service = client.GetService( + 'LineItemCreativeAssociationService', version='v202111') + + # Create query to select a single linked device. + # Linked devices can be read from the linked_device PQL table. + statement = (ad_manager.StatementBuilder(version='v202111') + .Where('id = :linkedDeviceId') + .WithBindVariable('linkedDeviceId', int(linked_device_id))) + + # Make call to push creatives to devices. + result = lica_service.pushCreativeToDevices(statement.ToStatement(), { + 'lineItemId': line_item_id, + 'creativeId': creative_id + }) + + # Display results. + if result and int(result['numChanges']) > 0: + print('Pushed creatives to %s devices.' % result['numChanges']) + else: + print('No creatives were pushed.') + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, LINE_ITEM_ID, CREATIVE_ID, LINKED_DEVICE_ID) diff --git a/examples/ad_manager/v202102/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202111/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v202102/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202111/line_item_creative_association_service/update_licas.py index 3b1aa307..f8552ff1 100755 --- a/examples/ad_manager/v202102/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202111/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202102') + 'LineItemCreativeAssociationService', version='v202111') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v202102/line_item_service/__init__.py b/examples/ad_manager/v202111/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/line_item_service/__init__.py rename to examples/ad_manager/v202111/line_item_service/__init__.py diff --git a/examples/ad_manager/v202102/line_item_service/activate_line_items.py b/examples/ad_manager/v202111/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v202102/line_item_service/activate_line_items.py rename to examples/ad_manager/v202111/line_item_service/activate_line_items.py index f0acde2f..0909aabe 100755 --- a/examples/ad_manager/v202102/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202111/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202102/line_item_service/create_line_items.py b/examples/ad_manager/v202111/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v202102/line_item_service/create_line_items.py rename to examples/ad_manager/v202111/line_item_service/create_line_items.py index f4ea386f..4d7abb3f 100755 --- a/examples/ad_manager/v202102/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202111/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202102/line_item_service/create_video_line_item.py b/examples/ad_manager/v202111/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v202102/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202111/line_item_service/create_video_line_item.py index d020bdc2..818c3a1a 100755 --- a/examples/ad_manager/v202102/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202111/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202102/line_item_service/get_all_line_items.py b/examples/ad_manager/v202111/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v202102/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202111/line_item_service/get_all_line_items.py index df2b0b0d..8d2a70e7 100755 --- a/examples/ad_manager/v202102/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202111/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v202102/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202111/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v202102/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202111/line_item_service/get_line_items_that_need_creatives.py index 164774a6..87b2173f 100755 --- a/examples/ad_manager/v202102/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202111/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v202102/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202111/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v202102/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202111/line_item_service/get_recently_updated_line_items.py index aa87e792..3fe14abc 100755 --- a/examples/ad_manager/v202102/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202111/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202102/line_item_service/pause_line_items.py b/examples/ad_manager/v202111/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v202102/line_item_service/pause_line_items.py rename to examples/ad_manager/v202111/line_item_service/pause_line_items.py index a440c750..ad70b3fd 100755 --- a/examples/ad_manager/v202102/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202111/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v202102/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202111/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v202102/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202111/line_item_service/target_custom_criteria.py index 249309f3..3a7b0c30 100755 --- a/examples/ad_manager/v202102/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202111/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/line_item_service/update_line_items.py b/examples/ad_manager/v202111/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v202102/line_item_service/update_line_items.py rename to examples/ad_manager/v202111/line_item_service/update_line_items.py index 235858f0..7c487ee8 100755 --- a/examples/ad_manager/v202102/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202111/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202102') + line_item_service = client.GetService('LineItemService', version='v202111') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v202102/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202111/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202102/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202111/live_stream_event_service/activate_live_stream_events.py index 7f5aa760..9092bb33 100755 --- a/examples/ad_manager/v202102/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202111/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202102') + 'LiveStreamEventService', version='v202111') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v202102/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202111/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v202102/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202111/live_stream_event_service/create_live_stream_events.py index 43a44909..c65a8374 100755 --- a/examples/ad_manager/v202102/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202111/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v202102') + 'LiveStreamEventService', version='v202111') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v202102/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202111/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v202102/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202111/live_stream_event_service/get_all_live_stream_events.py index bef3d72e..7c520a96 100755 --- a/examples/ad_manager/v202102/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202111/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202102') + 'LiveStreamEventService', version='v202111') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v202102/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202111/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v202102/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202111/live_stream_event_service/register_sessions_for_monitoring.py index 057a7d1c..5005ceaa 100755 --- a/examples/ad_manager/v202102/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202111/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202102') + 'LiveStreamEventService', version='v202111') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v202102/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202111/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202102/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202111/live_stream_event_service/update_live_stream_events.py index 42eb415b..6bab441d 100755 --- a/examples/ad_manager/v202102/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202111/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v202102') + 'LiveStreamEventService', version='v202111') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v202102/native_style_service/__init__.py b/examples/ad_manager/v202111/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/native_style_service/__init__.py rename to examples/ad_manager/v202111/native_style_service/__init__.py diff --git a/examples/ad_manager/v202102/native_style_service/create_native_styles.py b/examples/ad_manager/v202111/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v202102/native_style_service/create_native_styles.py rename to examples/ad_manager/v202111/native_style_service/create_native_styles.py index 9d271c5f..afe514d2 100755 --- a/examples/ad_manager/v202102/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202111/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202102') + version='v202111') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v202102/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202111/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v202102/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202111/native_style_service/get_all_native_styles.py index cd7537f2..7047bf85 100755 --- a/examples/ad_manager/v202102/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202111/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202102') + version='v202111') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v202102/network_service/__init__.py b/examples/ad_manager/v202111/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/network_service/__init__.py rename to examples/ad_manager/v202111/network_service/__init__.py diff --git a/examples/ad_manager/v202102/network_service/get_all_networks.py b/examples/ad_manager/v202111/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v202102/network_service/get_all_networks.py rename to examples/ad_manager/v202111/network_service/get_all_networks.py index 7e3e11d1..749aeb64 100755 --- a/examples/ad_manager/v202102/network_service/get_all_networks.py +++ b/examples/ad_manager/v202111/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202102') + network_service = client.GetService('NetworkService', version='v202111') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v202102/network_service/get_current_network.py b/examples/ad_manager/v202111/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v202102/network_service/get_current_network.py rename to examples/ad_manager/v202111/network_service/get_current_network.py index ff0f4df2..eb2aa419 100755 --- a/examples/ad_manager/v202102/network_service/get_current_network.py +++ b/examples/ad_manager/v202111/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202102') + network_service = client.GetService('NetworkService', version='v202111') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202102/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202111/network_service/get_default_third_party_data_declaration.py similarity index 95% rename from examples/ad_manager/v202102/network_service/get_default_third_party_data_declaration.py rename to examples/ad_manager/v202111/network_service/get_default_third_party_data_declaration.py index 5eacd62e..f231b9fe 100755 --- a/examples/ad_manager/v202102/network_service/get_default_third_party_data_declaration.py +++ b/examples/ad_manager/v202111/network_service/get_default_third_party_data_declaration.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202102') + network_service = client.GetService('NetworkService', version='v202111') pql_service = client.GetService('PublisherQueryLanguageService', - version='v202102') + version='v202111') # Fetch the default third party data declarations. declarations = network_service.getDefaultThirdPartyDataDeclaration() @@ -44,7 +44,7 @@ def main(client): # In this case, there are third party companies to be displayed, so fetch # the company names from the Rich_Media_Ad_Company PQL table. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Select('Id, Name') .From('Rich_Media_Ad_Company') .Where('Id IN (:company_ids)') diff --git a/examples/ad_manager/v202102/network_service/make_test_network.py b/examples/ad_manager/v202111/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v202102/network_service/make_test_network.py rename to examples/ad_manager/v202111/network_service/make_test_network.py index 237c62a7..59dc82b5 100755 --- a/examples/ad_manager/v202102/network_service/make_test_network.py +++ b/examples/ad_manager/v202111/network_service/make_test_network.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202102') + network_service = client.GetService('NetworkService', version='v202111') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v202102/order_service/__init__.py b/examples/ad_manager/v202111/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/order_service/__init__.py rename to examples/ad_manager/v202111/order_service/__init__.py diff --git a/examples/ad_manager/v202102/order_service/approve_orders.py b/examples/ad_manager/v202111/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v202102/order_service/approve_orders.py rename to examples/ad_manager/v202111/order_service/approve_orders.py index 0bf11461..bfb3051f 100755 --- a/examples/ad_manager/v202102/order_service/approve_orders.py +++ b/examples/ad_manager/v202111/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202102') + order_service = client.GetService('OrderService', version='v202111') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v202102/order_service/create_orders.py b/examples/ad_manager/v202111/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v202102/order_service/create_orders.py rename to examples/ad_manager/v202111/order_service/create_orders.py index 76167e49..b94d7fba 100755 --- a/examples/ad_manager/v202102/order_service/create_orders.py +++ b/examples/ad_manager/v202111/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202102') + order_service = client.GetService('OrderService', version='v202111') # Create order objects. orders = [] diff --git a/examples/ad_manager/v202102/order_service/get_all_orders.py b/examples/ad_manager/v202111/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v202102/order_service/get_all_orders.py rename to examples/ad_manager/v202111/order_service/get_all_orders.py index 1324795e..59ec55a4 100755 --- a/examples/ad_manager/v202102/order_service/get_all_orders.py +++ b/examples/ad_manager/v202111/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202102') + order_service = client.GetService('OrderService', version='v202111') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v202102/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202111/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v202102/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202111/order_service/get_orders_starting_soon.py index 0445563c..ca8bdcf9 100755 --- a/examples/ad_manager/v202102/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202111/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202102') + order_service = client.GetService('OrderService', version='v202111') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v202102/order_service/update_orders.py b/examples/ad_manager/v202111/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v202102/order_service/update_orders.py rename to examples/ad_manager/v202111/order_service/update_orders.py index 4468fda8..473482a7 100755 --- a/examples/ad_manager/v202102/order_service/update_orders.py +++ b/examples/ad_manager/v202111/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202102') + order_service = client.GetService('OrderService', version='v202111') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202102/placement_service/create_placements.py b/examples/ad_manager/v202111/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v202102/placement_service/create_placements.py rename to examples/ad_manager/v202111/placement_service/create_placements.py index 286ef21d..492a5fe7 100755 --- a/examples/ad_manager/v202102/placement_service/create_placements.py +++ b/examples/ad_manager/v202111/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202102') - inventory_service = client.GetService('InventoryService', version='v202102') + placement_service = client.GetService('PlacementService', version='v202111') + inventory_service = client.GetService('InventoryService', version='v202111') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v202102/placement_service/deactivate_placements.py b/examples/ad_manager/v202111/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v202102/placement_service/deactivate_placements.py rename to examples/ad_manager/v202111/placement_service/deactivate_placements.py index 460ce8a6..ed699e49 100755 --- a/examples/ad_manager/v202102/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202111/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202102') + placement_service = client.GetService('PlacementService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/placement_service/get_active_placements.py b/examples/ad_manager/v202111/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v202102/placement_service/get_active_placements.py rename to examples/ad_manager/v202111/placement_service/get_active_placements.py index fb08b145..0ecc0145 100755 --- a/examples/ad_manager/v202102/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202111/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202102') + placement_service = client.GetService('PlacementService', version='v202111') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202102/placement_service/get_all_placements.py b/examples/ad_manager/v202111/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v202102/placement_service/get_all_placements.py rename to examples/ad_manager/v202111/placement_service/get_all_placements.py index d04f4077..0e0f4363 100755 --- a/examples/ad_manager/v202102/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202111/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202102') + placement_service = client.GetService('PlacementService', version='v202111') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v202102/placement_service/update_placements.py b/examples/ad_manager/v202111/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v202102/placement_service/update_placements.py rename to examples/ad_manager/v202111/placement_service/update_placements.py index f6ff7baf..4dd748b7 100755 --- a/examples/ad_manager/v202102/placement_service/update_placements.py +++ b/examples/ad_manager/v202111/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202102') + placement_service = client.GetService('PlacementService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v202102/proposal_line_item_service/__init__.py b/examples/ad_manager/v202111/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202111/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v202102/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202111/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202102/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202111/proposal_line_item_service/archive_proposal_line_items.py index 7fb1a74c..76f0ce06 100755 --- a/examples/ad_manager/v202102/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202111/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202102') + 'ProposalLineItemService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202111/proposal_line_item_service/create_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202102/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202111/proposal_line_item_service/create_proposal_line_items.py index fd9f3642..c0ac6d80 100755 --- a/examples/ad_manager/v202102/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202111/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202102') - network_service = client.GetService('NetworkService', version='v202102') + 'ProposalLineItemService', version='v202111') + network_service = client.GetService('NetworkService', version='v202111') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) @@ -42,11 +42,6 @@ def main(client, proposal_id): # Create a single programmatic proposal line item. proposal_line_item = { - # Setting required Marketplace information. - 'marketplaceInfo': { - 'adExchangeEnvironment': 'DISPLAY' - }, - # Setting common required fields for proposal line items. 'name': 'Proposal line item #%s' % uuid.uuid4(), 'proposalId': proposal_id, @@ -56,6 +51,9 @@ def main(client, proposal_id): 'adUnitId': root_ad_unit_id } }, + 'requestPlatformTargeting': { + 'targetedRequestPlatforms': ['BROWSER'] + }, # Target Display environment by excluding Mobile Apps. # DeviceCapabilities can be obtained though the Device_Capability PQL # table: diff --git a/examples/ad_manager/v202102/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202111/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202102/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202111/proposal_line_item_service/get_all_proposal_line_items.py index 97c14c89..b9c3f36b 100755 --- a/examples/ad_manager/v202102/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202111/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202102') + 'ProposalLineItemService', version='v202111') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v202102/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202111/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v202102/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202111/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 66a1be9c..9b77d26c 100755 --- a/examples/ad_manager/v202102/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202111/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202102') + 'ProposalLineItemService', version='v202111') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v202102/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202111/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202102/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202111/proposal_line_item_service/update_proposal_line_items.py index 49d873a3..46596950 100755 --- a/examples/ad_manager/v202102/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202111/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202102') + 'ProposalLineItemService', version='v202111') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/proposal_service/__init__.py b/examples/ad_manager/v202111/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/proposal_service/__init__.py rename to examples/ad_manager/v202111/proposal_service/__init__.py diff --git a/examples/ad_manager/v202102/proposal_service/create_proposals.py b/examples/ad_manager/v202111/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v202102/proposal_service/create_proposals.py rename to examples/ad_manager/v202111/proposal_service/create_proposals.py index 3f6236db..89ec3a51 100755 --- a/examples/ad_manager/v202102/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202111/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v202102') + proposal_service = client.GetService('ProposalService', version='v202111') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v202102/proposal_service/get_all_proposals.py b/examples/ad_manager/v202111/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v202102/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202111/proposal_service/get_all_proposals.py index 59742b62..bf00297b 100755 --- a/examples/ad_manager/v202102/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202111/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202102') + proposal_service = client.GetService('ProposalService', version='v202111') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v202102/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202111/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v202102/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202111/proposal_service/get_marketplace_comments.py index da5b058f..ea96ba15 100755 --- a/examples/ad_manager/v202102/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202111/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v202102') + 'ProposalService', version='v202111') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v202102/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202111/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v202102/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202111/proposal_service/get_proposals_awaiting_seller_review.py index 9eafab36..fce01a45 100755 --- a/examples/ad_manager/v202102/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202111/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202102') + proposal_service = client.GetService('ProposalService', version='v202111') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v202102/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202111/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v202102/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202111/proposal_service/request_buyers_acceptance.py index 9432b527..5c0605db 100755 --- a/examples/ad_manager/v202102/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202111/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202102') + proposal_service = client.GetService('ProposalService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v202102/proposal_service/update_proposals.py b/examples/ad_manager/v202111/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v202102/proposal_service/update_proposals.py rename to examples/ad_manager/v202111/proposal_service/update_proposals.py index 09be3294..1b3e27e5 100755 --- a/examples/ad_manager/v202102/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202111/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202102') + proposal_service = client.GetService('ProposalService', version='v202111') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/publisher_query_language_service/__init__.py b/examples/ad_manager/v202111/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202111/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v202102/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202111/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v202102/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202111/publisher_query_language_service/fetch_match_tables.py index 54b6cc6b..eab6ffdc 100755 --- a/examples/ad_manager/v202102/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202111/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202102/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202111/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v202102/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202111/publisher_query_language_service/get_all_browsers.py index 34a61d3e..e3f66ca7 100755 --- a/examples/ad_manager/v202102/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202111/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v202102/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202111/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v202102/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202111/publisher_query_language_service/get_all_programmatic_buyers.py index 6f2b8796..f5bd52c9 100755 --- a/examples/ad_manager/v202102/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202111/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202102') + data_downloader = client.GetDataDownloader(version='v202111') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202102/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202111/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v202102/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202111/publisher_query_language_service/get_geo_targets.py index 02290768..6edfa873 100755 --- a/examples/ad_manager/v202102/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202111/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v202102/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202111/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v202102/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202111/publisher_query_language_service/get_line_items_named_like.py index 9ab992ac..c2ce69b3 100755 --- a/examples/ad_manager/v202102/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202111/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202102/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202111/publisher_query_language_service/get_mcm_earnings.py similarity index 97% rename from examples/ad_manager/v202102/publisher_query_language_service/get_mcm_earnings.py rename to examples/ad_manager/v202111/publisher_query_language_service/get_mcm_earnings.py index a4afe234..d59dd729 100755 --- a/examples/ad_manager/v202102/publisher_query_language_service/get_mcm_earnings.py +++ b/examples/ad_manager/v202111/publisher_query_language_service/get_mcm_earnings.py @@ -26,7 +26,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202102') + data_downloader = client.GetDataDownloader(version='v202111') with tempfile.NamedTemporaryFile( prefix='mcm_earnings_', diff --git a/examples/ad_manager/v202102/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202111/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v202102/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202111/publisher_query_language_service/get_recent_changes.py index b629151c..59231067 100755 --- a/examples/ad_manager/v202102/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202111/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v202102') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202111') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v202102/report_service/__init__.py b/examples/ad_manager/v202111/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/report_service/__init__.py rename to examples/ad_manager/v202111/report_service/__init__.py diff --git a/examples/ad_manager/v202102/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202111/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v202102/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202111/report_service/run_ad_exchange_report.py index 17d3213a..a6881aeb 100755 --- a/examples/ad_manager/v202102/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202111/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') # Create report job. report_job = { diff --git a/examples/ad_manager/v202102/report_service/run_delivery_report.py b/examples/ad_manager/v202111/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v202102/report_service/run_delivery_report.py rename to examples/ad_manager/v202111/report_service/run_delivery_report.py index 280b94d6..0c6d1c57 100755 --- a/examples/ad_manager/v202102/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202111/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202102/report_service/run_inventory_report.py b/examples/ad_manager/v202111/report_service/run_inventory_report.py similarity index 97% rename from examples/ad_manager/v202102/report_service/run_inventory_report.py rename to examples/ad_manager/v202111/report_service/run_inventory_report.py index 0b98b73a..572dba64 100755 --- a/examples/ad_manager/v202102/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202111/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') # Create report job. report_job = { diff --git a/examples/ad_manager/v202102/report_service/run_reach_report.py b/examples/ad_manager/v202111/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v202102/report_service/run_reach_report.py rename to examples/ad_manager/v202111/report_service/run_reach_report.py index 4183d542..295b8e4d 100755 --- a/examples/ad_manager/v202102/report_service/run_reach_report.py +++ b/examples/ad_manager/v202111/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') # Create report job. report_job = { diff --git a/examples/ad_manager/v202111/report_service/run_reach_report_with_ad_unit_dimensions.py b/examples/ad_manager/v202111/report_service/run_reach_report_with_ad_unit_dimensions.py new file mode 100755 index 00000000..8c866c86 --- /dev/null +++ b/examples/ad_manager/v202111/report_service/run_reach_report_with_ad_unit_dimensions.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2021 Google LLC +# +# 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 code example runs a reach report.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v202111') + + # Create report job. + report_job = { + 'reportQuery': { + # For Reach reports with AD_UNIT_ID or AD_UNIT_NAME in the dimensions + # list, adUnitView must be set to 'FLAT' or 'HIERARCHICAL'. + 'adUnitView': 'FLAT', + 'dimensions': ['MONTH_AND_YEAR', 'COUNTRY_NAME', 'AD_UNIT_ID', + 'AD_UNIT_NAME'], + 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS', + 'UNIQUE_REACH'], + 'dateRangeType': 'LAST_MONTH' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202102/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202111/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v202102/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202111/report_service/run_report_and_create_match_table.py index 7fea17fa..cef28096 100755 --- a/examples/ad_manager/v202102/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202111/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202102/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202111/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v202102/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202111/report_service/run_report_with_custom_fields.py index eb3a683d..daaae982 100755 --- a/examples/ad_manager/v202102/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202111/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') # Create report job. report_job = { diff --git a/examples/ad_manager/v202102/report_service/run_sales_report.py b/examples/ad_manager/v202111/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v202102/report_service/run_sales_report.py rename to examples/ad_manager/v202111/report_service/run_sales_report.py index 49422a2e..812c0af7 100755 --- a/examples/ad_manager/v202102/report_service/run_sales_report.py +++ b/examples/ad_manager/v202111/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') # Create report job. report_job = { diff --git a/examples/ad_manager/v202102/report_service/run_saved_query.py b/examples/ad_manager/v202111/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v202102/report_service/run_saved_query.py rename to examples/ad_manager/v202111/report_service/run_saved_query.py index 7d617016..66e206df 100755 --- a/examples/ad_manager/v202102/report_service/run_saved_query.py +++ b/examples/ad_manager/v202111/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v202102') + report_service = client.GetService('ReportService', version='v202111') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202102') + report_downloader = client.GetDataDownloader(version='v202111') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202102/site_service/create_sites.py b/examples/ad_manager/v202111/site_service/create_sites.py similarity index 99% rename from examples/ad_manager/v202102/site_service/create_sites.py rename to examples/ad_manager/v202111/site_service/create_sites.py index 87240ac2..d6ea315f 100755 --- a/examples/ad_manager/v202102/site_service/create_sites.py +++ b/examples/ad_manager/v202111/site_service/create_sites.py @@ -27,8 +27,8 @@ def main(client, url, child_network_code): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202102') - site_service = client.GetService('SiteService', version='v202102') + network_service = client.GetService('NetworkService', version='v202111') + site_service = client.GetService('SiteService', version='v202111') # Check that the child network code is approved for MANAGE_INVENTORY by this # network. diff --git a/examples/ad_manager/v202102/site_service/get_all_sites.py b/examples/ad_manager/v202111/site_service/get_all_sites.py similarity index 96% rename from examples/ad_manager/v202102/site_service/get_all_sites.py rename to examples/ad_manager/v202111/site_service/get_all_sites.py index b594ea4b..ad468b57 100755 --- a/examples/ad_manager/v202102/site_service/get_all_sites.py +++ b/examples/ad_manager/v202111/site_service/get_all_sites.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202102') + site_service = client.GetService('SiteService', version='v202111') # Create a statement to select Sites. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small number of sites at a time, paging through until all sites # have been retrieved. diff --git a/examples/ad_manager/v202102/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202111/site_service/get_sites_requiring_approval.py similarity index 96% rename from examples/ad_manager/v202102/site_service/get_sites_requiring_approval.py rename to examples/ad_manager/v202111/site_service/get_sites_requiring_approval.py index e509c24f..6dd575e0 100755 --- a/examples/ad_manager/v202102/site_service/get_sites_requiring_approval.py +++ b/examples/ad_manager/v202111/site_service/get_sites_requiring_approval.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202102') + site_service = client.GetService('SiteService', version='v202111') # Create a statement to select Sites needing approval. - statement = ad_manager.StatementBuilder(version='v202102').Where( + statement = ad_manager.StatementBuilder(version='v202111').Where( "approvalStatus = 'REQUIRES_REVIEW'") # Retrieve a small number of sites at a time, paging through until all sites diff --git a/examples/ad_manager/v202102/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202111/site_service/submit_sites_for_approval.py similarity index 95% rename from examples/ad_manager/v202102/site_service/submit_sites_for_approval.py rename to examples/ad_manager/v202111/site_service/submit_sites_for_approval.py index 278ba3e3..1843f487 100755 --- a/examples/ad_manager/v202102/site_service/submit_sites_for_approval.py +++ b/examples/ad_manager/v202111/site_service/submit_sites_for_approval.py @@ -25,10 +25,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202102') + site_service = client.GetService('SiteService', version='v202111') # Create a statement to select Site. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :id') .WithBindVariable('id', SITE_ID)) diff --git a/examples/ad_manager/v202102/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202111/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202111/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v202102/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202111/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v202102/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202111/suggested_ad_unit_service/approve_all_suggested_ad_units.py index c81247ae..229fd6f1 100755 --- a/examples/ad_manager/v202102/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202111/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202102') + 'SuggestedAdUnitService', version='v202111') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v202102/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202111/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202102/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202111/suggested_ad_unit_service/get_all_suggested_ad_units.py index d3ae3cb3..08eb4916 100755 --- a/examples/ad_manager/v202102/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202111/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202102') + 'SuggestedAdUnitService', version='v202111') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v202102/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202111/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202102/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202111/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 46b58b50..775c4e26 100755 --- a/examples/ad_manager/v202102/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202111/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202102') + 'SuggestedAdUnitService', version='v202111') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v202102/targeting_preset_service/__init__.py b/examples/ad_manager/v202111/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/targeting_preset_service/__init__.py rename to examples/ad_manager/v202111/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202111/targeting_preset_service/get_all_targeting_presets.py similarity index 94% rename from examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202111/targeting_preset_service/get_all_targeting_presets.py index 3772a0f4..72fdbb0c 100755 --- a/examples/ad_manager/v202102/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202111/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v202102') + 'TargetingPresetService', version='v202111') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. diff --git a/examples/ad_manager/v202102/team_service/__init__.py b/examples/ad_manager/v202111/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/team_service/__init__.py rename to examples/ad_manager/v202111/team_service/__init__.py diff --git a/examples/ad_manager/v202102/team_service/create_teams.py b/examples/ad_manager/v202111/team_service/create_teams.py similarity index 99% rename from examples/ad_manager/v202102/team_service/create_teams.py rename to examples/ad_manager/v202111/team_service/create_teams.py index 1f4ab7e7..73b8de10 100755 --- a/examples/ad_manager/v202102/team_service/create_teams.py +++ b/examples/ad_manager/v202111/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202102') + team_service = client.GetService('TeamService', version='v202111') # Create team objects. teams = [] diff --git a/examples/ad_manager/v202102/team_service/get_all_teams.py b/examples/ad_manager/v202111/team_service/get_all_teams.py similarity index 96% rename from examples/ad_manager/v202102/team_service/get_all_teams.py rename to examples/ad_manager/v202111/team_service/get_all_teams.py index 012ab069..a5f1d3a8 100755 --- a/examples/ad_manager/v202102/team_service/get_all_teams.py +++ b/examples/ad_manager/v202111/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202102') + team_service = client.GetService('TeamService', version='v202111') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v202102/team_service/update_teams.py b/examples/ad_manager/v202111/team_service/update_teams.py similarity index 97% rename from examples/ad_manager/v202102/team_service/update_teams.py rename to examples/ad_manager/v202111/team_service/update_teams.py index 9533bae8..1b21d20c 100755 --- a/examples/ad_manager/v202102/team_service/update_teams.py +++ b/examples/ad_manager/v202111/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202102') + team_service = client.GetService('TeamService', version='v202111') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v202102/user_service/__init__.py b/examples/ad_manager/v202111/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/user_service/__init__.py rename to examples/ad_manager/v202111/user_service/__init__.py diff --git a/examples/ad_manager/v202102/user_service/create_users.py b/examples/ad_manager/v202111/user_service/create_users.py similarity index 99% rename from examples/ad_manager/v202102/user_service/create_users.py rename to examples/ad_manager/v202111/user_service/create_users.py index 3c1b6324..de12e436 100755 --- a/examples/ad_manager/v202102/user_service/create_users.py +++ b/examples/ad_manager/v202111/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202102') + user_service = client.GetService('UserService', version='v202111') # Create user objects. users = [ diff --git a/examples/ad_manager/v202102/user_service/deactivate_users.py b/examples/ad_manager/v202111/user_service/deactivate_users.py similarity index 97% rename from examples/ad_manager/v202102/user_service/deactivate_users.py rename to examples/ad_manager/v202111/user_service/deactivate_users.py index b7113a84..14d83347 100755 --- a/examples/ad_manager/v202102/user_service/deactivate_users.py +++ b/examples/ad_manager/v202111/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202102') + user_service = client.GetService('UserService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202102/user_service/get_all_roles.py b/examples/ad_manager/v202111/user_service/get_all_roles.py similarity index 99% rename from examples/ad_manager/v202102/user_service/get_all_roles.py rename to examples/ad_manager/v202111/user_service/get_all_roles.py index 0c891fe3..498c60be 100755 --- a/examples/ad_manager/v202102/user_service/get_all_roles.py +++ b/examples/ad_manager/v202111/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202102') + user_service = client.GetService('UserService', version='v202111') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v202102/user_service/get_all_users.py b/examples/ad_manager/v202111/user_service/get_all_users.py similarity index 96% rename from examples/ad_manager/v202102/user_service/get_all_users.py rename to examples/ad_manager/v202111/user_service/get_all_users.py index 383b21fb..7dad1c83 100755 --- a/examples/ad_manager/v202102/user_service/get_all_users.py +++ b/examples/ad_manager/v202111/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202102') + user_service = client.GetService('UserService', version='v202111') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v202102/user_service/get_current_user.py b/examples/ad_manager/v202111/user_service/get_current_user.py similarity index 99% rename from examples/ad_manager/v202102/user_service/get_current_user.py rename to examples/ad_manager/v202111/user_service/get_current_user.py index 2d4091cb..a9f9e41f 100755 --- a/examples/ad_manager/v202102/user_service/get_current_user.py +++ b/examples/ad_manager/v202111/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202102') + user_service = client.GetService('UserService', version='v202111') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v202102/user_service/get_user_by_email_address.py b/examples/ad_manager/v202111/user_service/get_user_by_email_address.py similarity index 96% rename from examples/ad_manager/v202102/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202111/user_service/get_user_by_email_address.py index 26780c99..777e4324 100755 --- a/examples/ad_manager/v202102/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202111/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202102') + user_service = client.GetService('UserService', version='v202111') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v202102/user_service/update_users.py b/examples/ad_manager/v202111/user_service/update_users.py similarity index 96% rename from examples/ad_manager/v202102/user_service/update_users.py rename to examples/ad_manager/v202111/user_service/update_users.py index fbf2f11f..f5b92415 100755 --- a/examples/ad_manager/v202102/user_service/update_users.py +++ b/examples/ad_manager/v202111/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202102') + user_service = client.GetService('UserService', version='v202111') # Create query. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202102/user_team_association_service/__init__.py b/examples/ad_manager/v202111/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202102/user_team_association_service/__init__.py rename to examples/ad_manager/v202111/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v202102/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202111/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v202102/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202111/user_team_association_service/create_user_team_associations.py index 657a85e5..0c9f8daf 100755 --- a/examples/ad_manager/v202102/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202111/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202102') + 'UserTeamAssociationService', version='v202111') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v202102/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202111/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v202102/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202111/user_team_association_service/delete_user_team_associations.py index f26e1241..c774255d 100755 --- a/examples/ad_manager/v202102/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202111/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202102') + 'UserTeamAssociationService', version='v202111') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202102/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202111/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v202102/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202111/user_team_association_service/get_all_user_team_associations.py index 2463e8ae..9bea68af 100755 --- a/examples/ad_manager/v202102/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202111/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202102') + 'UserTeamAssociationService', version='v202111') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v202102') + statement = ad_manager.StatementBuilder(version='v202111') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v202102/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202111/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v202102/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202111/user_team_association_service/get_user_team_associations_for_user.py index 092db53d..a54a0c4a 100755 --- a/examples/ad_manager/v202102/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202111/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202102') + 'UserTeamAssociationService', version='v202111') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202102/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202111/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v202102/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202111/user_team_association_service/update_user_team_associations.py index 91790e34..a591c65c 100755 --- a/examples/ad_manager/v202102/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202111/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202102') + 'UserTeamAssociationService', version='v202111') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202102') + statement = (ad_manager.StatementBuilder(version='v202111') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index c96d8e6d..6af467c9 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,7 +44,7 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v202011': + 'v202102': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -62,7 +62,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202102': + 'v202105': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -80,7 +80,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202105': + 'v202108': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -98,7 +98,7 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), - 'v202108': + 'v202111': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', @@ -783,18 +783,12 @@ def WaitForReport(self, report_job): service = self._GetReportService() report_job_id = service.runReportJob(report_job)['id'] - if self._version > 'v201502': - status = service.getReportJobStatus(report_job_id) - else: - status = service.getReportJob(report_job_id)['reportJobStatus'] + status = service.getReportJobStatus(report_job_id) while status != 'COMPLETED' and status != 'FAILED': _data_downloader_logger.debug('Report job status: %s', status) time.sleep(30) - if self._version > 'v201502': - status = service.getReportJobStatus(report_job_id) - else: - status = service.getReportJob(report_job_id)['reportJobStatus'] + status = service.getReportJobStatus(report_job_id) if status == 'FAILED': raise googleads.errors.AdManagerReportError(report_job_id) @@ -919,9 +913,9 @@ def _ConvertValueForCsv(self, pql_value): elif class_type == 'DateTimeValue': return self._ConvertDateTimeToOffset(field) elif class_type == 'DateValue': - return datetime.date(int(field['date']['year']), - int(field['date']['month']), - int(field['date']['day'])).isoformat() + return datetime.date(int(field['year']), + int(field['month']), + int(field['day'])).isoformat() else: return field else: diff --git a/googleads/common.py b/googleads/common.py index 99626be0..90ea0931 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -54,7 +54,7 @@ 'order to benefit from important security improvements and ensure ' 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '29.0.0' +VERSION = '30.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/ad_manager_test.py b/tests/ad_manager_test.py index c5b7c654..44e31f1c 100644 --- a/tests/ad_manager_test.py +++ b/tests/ad_manager_test.py @@ -428,9 +428,8 @@ def setUp(self): row1_field2 = { 'value': { - 'date': { - 'year': '1999', 'month': '04', 'day': '03'} - }, + 'year': '1999', 'month': '04', 'day': '03' + }, 'xsi_type': 'DateValue' } @@ -476,11 +475,9 @@ def setUp(self): row2_field2 = { 'value': { - 'date': { - 'year': '2009', - 'month': '02', - 'day': '05' - } + 'year': '2009', + 'month': '02', + 'day': '05' }, 'xsi_type': 'DateValue' } diff --git a/tests/common_test.py b/tests/common_test.py index 41d49518..5577a2c2 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202108' +CURRENT_VERSION = 'v202111' class CommonTest(testing.CleanUtilityRegistryTestCase): From b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 16 Nov 2021 15:12:35 -0500 Subject: [PATCH 174/180] Commiting latest changes. From 56d49267ee1f8055f6db215795a2bb78c584b768 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 28 Feb 2022 16:40:44 -0500 Subject: [PATCH 175/180] Ad Manager v202202 release. --- ChangeLog | 6 ++ README.md | 7 +- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 2 +- .../create_traffic_forecast_segments.py | 4 +- .../get_all_forecast_adjustments.py | 4 +- .../get_all_traffic_forecast_segments.py | 4 +- ...djustments_for_traffic_forecast_segment.py | 4 +- .../update_forecast_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../get_recently_modified_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../create_video_creatives.py | 66 ++++++++++++++++++ .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +-- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../forecast_service/get_traffic_data.py | 4 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +-- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../push_creative_to_devices.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- ...et_default_third_party_data_declaration.py | 6 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 2 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_ad_exchange_report.py | 2 +- .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 2 +- .../report_service/run_reach_report.py | 2 +- ...un_reach_report_with_ad_unit_dimensions.py | 69 +++++++++++++++++++ .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../site_service/create_sites.py | 4 +- .../site_service/get_all_sites.py | 4 +- .../get_sites_requiring_approval.py | 4 +- .../site_service/submit_sites_for_approval.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 36 +++++----- googleads/common.py | 2 +- setup.py | 4 +- tests/common_test.py | 2 +- 206 files changed, 469 insertions(+), 331 deletions(-) rename examples/ad_manager/{v202105 => v202202}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v202105 => v202202}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v202105 => v202202}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v202105 => v202202}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v202105 => v202202}/activity_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v202105 => v202202}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v202105 => v202202}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v202105 => v202202}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v202105 => v202202}/adjustment_service/create_forecast_adjustments.py (99%) rename examples/ad_manager/{v202105 => v202202}/adjustment_service/create_traffic_forecast_segments.py (98%) rename examples/ad_manager/{v202105 => v202202}/adjustment_service/get_all_forecast_adjustments.py (95%) rename examples/ad_manager/{v202105 => v202202}/adjustment_service/get_all_traffic_forecast_segments.py (95%) rename examples/ad_manager/{v202105 => v202202}/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py (96%) rename examples/ad_manager/{v202105 => v202202}/adjustment_service/update_forecast_adjustments.py (96%) rename examples/ad_manager/{v202105 => v202202}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v202105 => v202202}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v202105 => v202202}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v202105 => v202202}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v202105 => v202202}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v202105 => v202202}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v202105 => v202202}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v202105 => v202202}/cms_metadata_service/activate_cms_metadata_values.py (95%) rename examples/ad_manager/{v202105 => v202202}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v202105 => v202202}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v202105 => v202202}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v202105 => v202202}/company_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/company_service/create_companies.py (99%) rename examples/ad_manager/{v202105 => v202202}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v202105 => v202202}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v202105 => v202202}/company_service/update_companies.py (96%) rename examples/ad_manager/{v202105 => v202202}/contact_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v202105 => v202202}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v202105 => v202202}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v202105 => v202202}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v202105 => v202202}/content_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/content_service/get_all_content.py (96%) rename examples/ad_manager/{v202105 => v202202}/content_service/get_recently_modified_content.py (97%) rename examples/ad_manager/{v202105 => v202202}/creative_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v202105 => v202202}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v202105 => v202202}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v202105 => v202202}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v202105 => v202202}/creative_service/create_native_creative.py (99%) create mode 100755 examples/ad_manager/v202202/creative_service/create_video_creatives.py rename examples/ad_manager/{v202105 => v202202}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v202105 => v202202}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v202105 => v202202}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v202105 => v202202}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v202105 => v202202}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v202105 => v202202}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v202105 => v202202}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v202105 => v202202}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v202105 => v202202}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v202105 => v202202}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v202105 => v202202}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v202105 => v202202}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v202105 => v202202}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v202105 => v202202}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v202105 => v202202}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v202105 => v202202}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v202105 => v202202}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v202105 => v202202}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v202105 => v202202}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v202105 => v202202}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v202105 => v202202}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v202105 => v202202}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v202105 => v202202}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v202105 => v202202}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202105 => v202202}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v202105 => v202202}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202105 => v202202}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202105 => v202202}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202105 => v202202}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v202105 => v202202}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v202105 => v202202}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v202105 => v202202}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v202105 => v202202}/forecast_service/get_traffic_data.py (99%) rename examples/ad_manager/{v202105 => v202202}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v202105 => v202202}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v202105 => v202202}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v202105 => v202202}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v202105 => v202202}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v202105 => v202202}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v202105 => v202202}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v202105 => v202202}/label_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/label_service/create_labels.py (99%) rename examples/ad_manager/{v202105 => v202202}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v202105 => v202202}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v202105 => v202202}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v202105 => v202202}/label_service/update_labels.py (96%) rename examples/ad_manager/{v202105 => v202202}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v202105 => v202202}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v202105 => v202202}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v202105 => v202202}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v202105 => v202202}/line_item_creative_association_service/push_creative_to_devices.py (94%) rename examples/ad_manager/{v202105 => v202202}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v202105 => v202202}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v202105 => v202202}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v202105 => v202202}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v202105 => v202202}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v202105 => v202202}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v202105 => v202202}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v202105 => v202202}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v202105 => v202202}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v202105 => v202202}/network_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v202105 => v202202}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v202105 => v202202}/network_service/get_default_third_party_data_declaration.py (95%) rename examples/ad_manager/{v202105 => v202202}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v202105 => v202202}/order_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v202105 => v202202}/order_service/create_orders.py (99%) rename examples/ad_manager/{v202105 => v202202}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v202105 => v202202}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v202105 => v202202}/order_service/update_orders.py (97%) rename examples/ad_manager/{v202105 => v202202}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v202105 => v202202}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v202105 => v202202}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v202105 => v202202}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v202105 => v202202}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v202105 => v202202}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v202105 => v202202}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v202105 => v202202}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v202105 => v202202}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v202105 => v202202}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v202105 => v202202}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/proposal_service/create_proposals.py (99%) rename examples/ad_manager/{v202105 => v202202}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v202105 => v202202}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v202105 => v202202}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v202105 => v202202}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v202105 => v202202}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v202105 => v202202}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v202105 => v202202}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v202105 => v202202}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v202105 => v202202}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v202105 => v202202}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v202105 => v202202}/publisher_query_language_service/get_mcm_earnings.py (97%) rename examples/ad_manager/{v202105 => v202202}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v202105 => v202202}/report_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/report_service/run_ad_exchange_report.py (97%) rename examples/ad_manager/{v202105 => v202202}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v202105 => v202202}/report_service/run_inventory_report.py (97%) rename examples/ad_manager/{v202105 => v202202}/report_service/run_reach_report.py (96%) create mode 100755 examples/ad_manager/v202202/report_service/run_reach_report_with_ad_unit_dimensions.py rename examples/ad_manager/{v202105 => v202202}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v202105 => v202202}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v202105 => v202202}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v202105 => v202202}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v202105 => v202202}/site_service/create_sites.py (96%) rename examples/ad_manager/{v202105 => v202202}/site_service/get_all_sites.py (92%) rename examples/ad_manager/{v202105 => v202202}/site_service/get_sites_requiring_approval.py (92%) rename examples/ad_manager/{v202105 => v202202}/site_service/submit_sites_for_approval.py (91%) rename examples/ad_manager/{v202105 => v202202}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v202105 => v202202}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v202105 => v202202}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v202105 => v202202}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/targeting_preset_service/get_all_targeting_presets.py (94%) rename examples/ad_manager/{v202105 => v202202}/team_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/team_service/create_teams.py (96%) rename examples/ad_manager/{v202105 => v202202}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v202105 => v202202}/team_service/update_teams.py (94%) rename examples/ad_manager/{v202105 => v202202}/user_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/user_service/create_users.py (96%) rename examples/ad_manager/{v202105 => v202202}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v202105 => v202202}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v202105 => v202202}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v202105 => v202202}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v202105 => v202202}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v202105 => v202202}/user_service/update_users.py (92%) rename examples/ad_manager/{v202105 => v202202}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v202105 => v202202}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v202105 => v202202}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v202105 => v202202}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v202105 => v202202}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v202105 => v202202}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index 4d6ace8e..6c0c0d54 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +31.0.0 -- 02/16/2022 +* The minimum supported version of Python is now 3.7.0. +* Added support for Ad Manager v202202. +* Removed support for Ad Manager v202102. +* Removed examples for Ad Manager v202105. + 30.0.0 -- 11/16/2021 * Added support for Ad Manager v202111. * Removed support for Ad Manager v202011. diff --git a/README.md b/README.md index be0d3115..e8687f35 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,9 @@ and DoubleClick for Publishers. The library provides easy ways to store your authentication and create SOAP web service clients. It also contains example code to help you get started integrating with our APIs. -> **The Google AdWords API will [sunset on April 27, 2022](https://ads-developers.googleblog.com/2021/04/upgrade-to-google-ads-api-from-adwords.html). +> **The Google AdWords API will [sunset on April 27, 2022](https://ads-developers.googleblog.com/2021/04/upgrade-to-google-ads-api-from-adwords.html). > Upgrade to the [Google Ads API](https://developers.google.com/google-ads/api/docs/client-libs).** -**NOTE**: As of v20.0.0 this library is _not_ compatible with Python versions less than Python 3.6. -Also `suds` is no longer supported in this library, `zeep` is now the only supported SOAP client. - ## Getting started 1. Download and install the library @@ -164,7 +161,7 @@ adwords_client = adwords.AdWordsClient( ### Python Versions -This library only supports Python 3.6+. +This library only supports Python 3.7+. ### External Dependencies: diff --git a/examples/ad_manager/v202105/activity_group_service/__init__.py b/examples/ad_manager/v202202/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/activity_group_service/__init__.py rename to examples/ad_manager/v202202/activity_group_service/__init__.py diff --git a/examples/ad_manager/v202105/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202202/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v202105/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202202/activity_group_service/create_activity_groups.py index da4044a5..4ea2bf84 100755 --- a/examples/ad_manager/v202105/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202202/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202105') + version='v202202') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v202105/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202202/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v202105/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202202/activity_group_service/get_active_activity_groups.py index 159aeb65..d77cdfe0 100755 --- a/examples/ad_manager/v202105/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202202/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202105') + 'ActivityGroupService', version='v202202') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202105/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202202/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v202105/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202202/activity_group_service/get_all_activity_groups.py index 05dd4b98..450f061b 100755 --- a/examples/ad_manager/v202105/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202202/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202105') + 'ActivityGroupService', version='v202202') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v202105/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202202/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v202105/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202202/activity_group_service/update_activity_groups.py index d043e510..f61bd685 100755 --- a/examples/ad_manager/v202105/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202202/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202105') + version='v202202') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/activity_service/__init__.py b/examples/ad_manager/v202202/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/activity_service/__init__.py rename to examples/ad_manager/v202202/activity_service/__init__.py diff --git a/examples/ad_manager/v202105/activity_service/create_activities.py b/examples/ad_manager/v202202/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v202105/activity_service/create_activities.py rename to examples/ad_manager/v202202/activity_service/create_activities.py index cf57e492..c983f8b9 100755 --- a/examples/ad_manager/v202105/activity_service/create_activities.py +++ b/examples/ad_manager/v202202/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202105') + activity_service = client.GetService('ActivityService', version='v202202') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v202105/activity_service/get_active_activities.py b/examples/ad_manager/v202202/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v202105/activity_service/get_active_activities.py rename to examples/ad_manager/v202202/activity_service/get_active_activities.py index 83c54312..312d7dff 100755 --- a/examples/ad_manager/v202105/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202202/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202105') + activity_service = client.GetService('ActivityService', version='v202202') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202105/activity_service/get_all_activities.py b/examples/ad_manager/v202202/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v202105/activity_service/get_all_activities.py rename to examples/ad_manager/v202202/activity_service/get_all_activities.py index bbbe93a3..03072e7a 100755 --- a/examples/ad_manager/v202105/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202202/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202105') + activity_service = client.GetService('ActivityService', version='v202202') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v202105/activity_service/update_activities.py b/examples/ad_manager/v202202/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v202105/activity_service/update_activities.py rename to examples/ad_manager/v202202/activity_service/update_activities.py index 8ae9ecc6..a114ae2c 100755 --- a/examples/ad_manager/v202105/activity_service/update_activities.py +++ b/examples/ad_manager/v202202/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202105') + activity_service = client.GetService('ActivityService', version='v202202') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202202/adjustment_service/create_forecast_adjustments.py similarity index 99% rename from examples/ad_manager/v202105/adjustment_service/create_forecast_adjustments.py rename to examples/ad_manager/v202202/adjustment_service/create_forecast_adjustments.py index 8e466f23..ae3a02b1 100755 --- a/examples/ad_manager/v202105/adjustment_service/create_forecast_adjustments.py +++ b/examples/ad_manager/v202202/adjustment_service/create_forecast_adjustments.py @@ -27,7 +27,7 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202105') + adjustment_service = client.GetService('AdjustmentService', version='v202202') # Create a new forecast adjustment for New Year's Day traffic. this_new_years = datetime.date(datetime.date.today().year, 1, 1) diff --git a/examples/ad_manager/v202105/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202202/adjustment_service/create_traffic_forecast_segments.py similarity index 98% rename from examples/ad_manager/v202105/adjustment_service/create_traffic_forecast_segments.py rename to examples/ad_manager/v202202/adjustment_service/create_traffic_forecast_segments.py index 24c5c56c..3524c6ee 100755 --- a/examples/ad_manager/v202105/adjustment_service/create_traffic_forecast_segments.py +++ b/examples/ad_manager/v202202/adjustment_service/create_traffic_forecast_segments.py @@ -25,8 +25,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v202105') - network_service = client.GetService('NetworkService', version='v202105') + adjustment_service = client.GetService('AdjustmentService', version='v202202') + network_service = client.GetService('NetworkService', version='v202202') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202105/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202202/adjustment_service/get_all_forecast_adjustments.py similarity index 95% rename from examples/ad_manager/v202105/adjustment_service/get_all_forecast_adjustments.py rename to examples/ad_manager/v202202/adjustment_service/get_all_forecast_adjustments.py index a91a9998..a310e698 100755 --- a/examples/ad_manager/v202105/adjustment_service/get_all_forecast_adjustments.py +++ b/examples/ad_manager/v202202/adjustment_service/get_all_forecast_adjustments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202105') + adjustment_service = client.GetService('AdjustmentService', version='v202202') # Create a statement to get all forecast adjustments. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small number of forecast adjustments at a time, paging # through until all forecast adjustments have been retrieved. diff --git a/examples/ad_manager/v202105/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202202/adjustment_service/get_all_traffic_forecast_segments.py similarity index 95% rename from examples/ad_manager/v202105/adjustment_service/get_all_traffic_forecast_segments.py rename to examples/ad_manager/v202202/adjustment_service/get_all_traffic_forecast_segments.py index fdf85470..8d16cf66 100755 --- a/examples/ad_manager/v202105/adjustment_service/get_all_traffic_forecast_segments.py +++ b/examples/ad_manager/v202202/adjustment_service/get_all_traffic_forecast_segments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202105') + adjustment_service = client.GetService('AdjustmentService', version='v202202') # Create a statement to get all traffic forecast segments. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small number of segments at a time, paging through until all # segments have been retrieved. diff --git a/examples/ad_manager/v202105/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202202/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py similarity index 96% rename from examples/ad_manager/v202105/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py rename to examples/ad_manager/v202202/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py index 4fa60610..178ee627 100755 --- a/examples/ad_manager/v202105/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py +++ b/examples/ad_manager/v202202/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -24,11 +24,11 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202105') + adjustment_service = client.GetService('AdjustmentService', version='v202202') # Create a statement to get forecast adjustments for a given traffic forecast # segment id. - statement = ad_manager.StatementBuilder(version='v202105').Where( + statement = ad_manager.StatementBuilder(version='v202202').Where( 'trafficForecastSegmentId = :segmentId').WithBindVariable( 'segmentId', traffic_forecast_segment_id) diff --git a/examples/ad_manager/v202105/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202202/adjustment_service/update_forecast_adjustments.py similarity index 96% rename from examples/ad_manager/v202105/adjustment_service/update_forecast_adjustments.py rename to examples/ad_manager/v202202/adjustment_service/update_forecast_adjustments.py index 07363e5d..23a8d70a 100755 --- a/examples/ad_manager/v202105/adjustment_service/update_forecast_adjustments.py +++ b/examples/ad_manager/v202202/adjustment_service/update_forecast_adjustments.py @@ -24,12 +24,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202105') + adjustment_service = client.GetService('AdjustmentService', version='v202202') # Create a statement to select a single forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v202105').Where('id = :id').WithBindVariable( + version='v202202').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast adjustment. diff --git a/examples/ad_manager/v202105/audience_segment_service/__init__.py b/examples/ad_manager/v202202/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/audience_segment_service/__init__.py rename to examples/ad_manager/v202202/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v202105/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v202105/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202202/audience_segment_service/create_audience_segments.py index 6a84135b..23e6166d 100755 --- a/examples/ad_manager/v202105/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202202/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202105') - network_service = client.GetService('NetworkService', version='v202105') + 'AudienceSegmentService', version='v202202') + network_service = client.GetService('NetworkService', version='v202202') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v202105/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v202105/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202202/audience_segment_service/get_all_audience_segments.py index 10764f3e..7818441e 100755 --- a/examples/ad_manager/v202105/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202202/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202105') + 'AudienceSegmentService', version='v202202') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v202105/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v202105/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202202/audience_segment_service/get_first_party_audience_segments.py index 9d916407..8885c316 100755 --- a/examples/ad_manager/v202105/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202202/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202105') + 'AudienceSegmentService', version='v202202') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v202105/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v202105/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202202/audience_segment_service/populate_first_party_audience_segments.py index 13cc35b5..0e9d3249 100755 --- a/examples/ad_manager/v202105/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202202/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202105') + 'AudienceSegmentService', version='v202202') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202105/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202202/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v202105/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202202/audience_segment_service/update_audience_segments.py index e4fc5a1f..3d03106e 100755 --- a/examples/ad_manager/v202105/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202202/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202105') + 'AudienceSegmentService', version='v202202') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202105/cdn_configuration_service/__init__.py b/examples/ad_manager/v202202/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202202/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v202105/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202202/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v202105/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202202/cdn_configuration_service/create_cdn_configurations.py index 7c09c960..33b2929e 100755 --- a/examples/ad_manager/v202105/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202202/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202105') + version='v202202') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v202105/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202202/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v202105/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202202/cdn_configuration_service/get_all_cdn_configurations.py index 114e0fe3..e2d68c32 100755 --- a/examples/ad_manager/v202105/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202202/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202105') + version='v202202') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202105/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202202/cms_metadata_service/activate_cms_metadata_values.py similarity index 95% rename from examples/ad_manager/v202105/cms_metadata_service/activate_cms_metadata_values.py rename to examples/ad_manager/v202202/cms_metadata_service/activate_cms_metadata_values.py index 1078eb7e..4f3a5d40 100755 --- a/examples/ad_manager/v202105/cms_metadata_service/activate_cms_metadata_values.py +++ b/examples/ad_manager/v202202/cms_metadata_service/activate_cms_metadata_values.py @@ -28,10 +28,10 @@ def main(client, cms_metadata_key_id): # Initialize appropriate service. cms_metadata_service = client.GetService('CmsMetadataService', - version='v202105') + version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('cmsKeyId = :cmsKeyId AND status = :status') .WithBindVariable('status', 'INACTIVE') .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) diff --git a/examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_keys.py index 38ee12c6..6c922ef1 100755 --- a/examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202105') + 'CmsMetadataService', version='v202202') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_values.py index 1fca98c4..434a8776 100755 --- a/examples/ad_manager/v202105/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202202/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202105') + 'CmsMetadataService', version='v202202') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v202105/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202202/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v202105/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202202/cms_metadata_service/get_cms_metadata_values_for_key.py index 51a4dbde..3619950a 100755 --- a/examples/ad_manager/v202105/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202202/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202105') + 'CmsMetadataService', version='v202202') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v202105').Where( + ad_manager.StatementBuilder(version='v202202').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v202105/company_service/__init__.py b/examples/ad_manager/v202202/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/company_service/__init__.py rename to examples/ad_manager/v202202/company_service/__init__.py diff --git a/examples/ad_manager/v202105/company_service/create_companies.py b/examples/ad_manager/v202202/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v202105/company_service/create_companies.py rename to examples/ad_manager/v202202/company_service/create_companies.py index b067ad7c..96320d72 100755 --- a/examples/ad_manager/v202105/company_service/create_companies.py +++ b/examples/ad_manager/v202202/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202105') + company_service = client.GetService('CompanyService', version='v202202') # Create company objects. companies = [ diff --git a/examples/ad_manager/v202105/company_service/get_advertisers.py b/examples/ad_manager/v202202/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v202105/company_service/get_advertisers.py rename to examples/ad_manager/v202202/company_service/get_advertisers.py index b19cadae..fd37fb20 100755 --- a/examples/ad_manager/v202105/company_service/get_advertisers.py +++ b/examples/ad_manager/v202202/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202105') + company_service = client.GetService('CompanyService', version='v202202') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v202105/company_service/get_all_companies.py b/examples/ad_manager/v202202/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v202105/company_service/get_all_companies.py rename to examples/ad_manager/v202202/company_service/get_all_companies.py index 6808eac8..b8377257 100755 --- a/examples/ad_manager/v202105/company_service/get_all_companies.py +++ b/examples/ad_manager/v202202/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202105') + company_service = client.GetService('CompanyService', version='v202202') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v202105/company_service/update_companies.py b/examples/ad_manager/v202202/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v202105/company_service/update_companies.py rename to examples/ad_manager/v202202/company_service/update_companies.py index 8df7e5e6..7664eac4 100755 --- a/examples/ad_manager/v202105/company_service/update_companies.py +++ b/examples/ad_manager/v202202/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202105') + company_service = client.GetService('CompanyService', version='v202202') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/contact_service/__init__.py b/examples/ad_manager/v202202/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/contact_service/__init__.py rename to examples/ad_manager/v202202/contact_service/__init__.py diff --git a/examples/ad_manager/v202105/contact_service/create_contacts.py b/examples/ad_manager/v202202/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v202105/contact_service/create_contacts.py rename to examples/ad_manager/v202202/contact_service/create_contacts.py index db606096..8df599f6 100755 --- a/examples/ad_manager/v202105/contact_service/create_contacts.py +++ b/examples/ad_manager/v202202/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202105') + contact_service = client.GetService('ContactService', version='v202202') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v202105/contact_service/get_all_contacts.py b/examples/ad_manager/v202202/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v202105/contact_service/get_all_contacts.py rename to examples/ad_manager/v202202/contact_service/get_all_contacts.py index e6c0360d..a98d1e6f 100755 --- a/examples/ad_manager/v202105/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202202/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202105') + contact_service = client.GetService('ContactService', version='v202202') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v202105/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202202/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v202105/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202202/contact_service/get_uninvited_contacts.py index ba9abc85..f41c7d8b 100755 --- a/examples/ad_manager/v202105/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202202/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202105') + contact_service = client.GetService('ContactService', version='v202202') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v202105/contact_service/update_contacts.py b/examples/ad_manager/v202202/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v202105/contact_service/update_contacts.py rename to examples/ad_manager/v202202/contact_service/update_contacts.py index ab5fb8b3..d2f86340 100755 --- a/examples/ad_manager/v202105/contact_service/update_contacts.py +++ b/examples/ad_manager/v202202/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202105') + contact_service = client.GetService('ContactService', version='v202202') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/content_service/__init__.py b/examples/ad_manager/v202202/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/content_service/__init__.py rename to examples/ad_manager/v202202/content_service/__init__.py diff --git a/examples/ad_manager/v202105/content_service/get_all_content.py b/examples/ad_manager/v202202/content_service/get_all_content.py similarity index 96% rename from examples/ad_manager/v202105/content_service/get_all_content.py rename to examples/ad_manager/v202202/content_service/get_all_content.py index d280c64a..dc19fa5e 100755 --- a/examples/ad_manager/v202105/content_service/get_all_content.py +++ b/examples/ad_manager/v202202/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202105') + content_service = client.GetService('ContentService', version='v202202') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v202105/content_service/get_recently_modified_content.py b/examples/ad_manager/v202202/content_service/get_recently_modified_content.py similarity index 97% rename from examples/ad_manager/v202105/content_service/get_recently_modified_content.py rename to examples/ad_manager/v202202/content_service/get_recently_modified_content.py index 4d270115..b7e98dfb 100755 --- a/examples/ad_manager/v202105/content_service/get_recently_modified_content.py +++ b/examples/ad_manager/v202202/content_service/get_recently_modified_content.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202105') + content_service = client.GetService('ContentService', version='v202202') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -35,7 +35,7 @@ def main(client): # lastModifiedDateTime. Changes to content bundle associations will update # the lastModifiedDateTime, but CMS metadata changes may not change the # lastModifiedDateTime. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202105/creative_service/__init__.py b/examples/ad_manager/v202202/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/creative_service/__init__.py rename to examples/ad_manager/v202202/creative_service/__init__.py diff --git a/examples/ad_manager/v202105/creative_service/copy_image_creatives.py b/examples/ad_manager/v202202/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v202105/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202202/creative_service/copy_image_creatives.py index 2b2d6b87..c2f19753 100755 --- a/examples/ad_manager/v202105/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202202/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202105') + creative_service = client.GetService('CreativeService', version='v202202') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v202105/creative_service/create_creative_from_template.py b/examples/ad_manager/v202202/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v202105/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202202/creative_service/create_creative_from_template.py index 98126275..52a1e500 100755 --- a/examples/ad_manager/v202105/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202202/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202105') + creative_service = client.GetService('CreativeService', version='v202202') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v202105/creative_service/create_creatives.py b/examples/ad_manager/v202202/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v202105/creative_service/create_creatives.py rename to examples/ad_manager/v202202/creative_service/create_creatives.py index 01dff6e2..a5810a60 100755 --- a/examples/ad_manager/v202105/creative_service/create_creatives.py +++ b/examples/ad_manager/v202202/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202105') + creative_service = client.GetService('CreativeService', version='v202202') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v202105/creative_service/create_custom_creative.py b/examples/ad_manager/v202202/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v202105/creative_service/create_custom_creative.py rename to examples/ad_manager/v202202/creative_service/create_custom_creative.py index 92b129fa..c04bdea0 100755 --- a/examples/ad_manager/v202105/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202202/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202105') + creative_service = client.GetService('CreativeService', version='v202202') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v202105/creative_service/create_native_creative.py b/examples/ad_manager/v202202/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v202105/creative_service/create_native_creative.py rename to examples/ad_manager/v202202/creative_service/create_native_creative.py index 35c52ed5..5fbf0988 100755 --- a/examples/ad_manager/v202105/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202202/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202105') + creative_service = client.GetService('CreativeService', version='v202202') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v202202/creative_service/create_video_creatives.py b/examples/ad_manager/v202202/creative_service/create_video_creatives.py new file mode 100755 index 00000000..d927ad47 --- /dev/null +++ b/examples/ad_manager/v202202/creative_service/create_video_creatives.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates a new video creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. +To determine which creatives already exist, run get_all_creatives.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v202202') + + # Create a video creative. + creative = { + 'xsi_type': 'VideoCreative', + 'name': 'Video Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '640', 'height': '360', 'isAspectRatio': False}, + 'destinationUrl': 'https://google.com', + 'duration': '115000', + 'videoSourceUrl': ( + 'https://storage.googleapis.com/interactive-media-ads/media/' + 'android.mp4') + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print('Video creative with id "%s" and name "%s" was created and can be ' + 'previewed at:\n%s.' + % (creative['id'], creative['name'], creative['vastPreviewUrl'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v202105/creative_service/get_all_creatives.py b/examples/ad_manager/v202202/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v202105/creative_service/get_all_creatives.py rename to examples/ad_manager/v202202/creative_service/get_all_creatives.py index e4e3fae5..f7d62f25 100755 --- a/examples/ad_manager/v202105/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202202/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202105') + creative_service = client.GetService('CreativeService', version='v202202') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v202105/creative_service/get_image_creatives.py b/examples/ad_manager/v202202/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v202105/creative_service/get_image_creatives.py rename to examples/ad_manager/v202202/creative_service/get_image_creatives.py index ca4bbd07..86dab75d 100755 --- a/examples/ad_manager/v202105/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202202/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202105') + creative_service = client.GetService('CreativeService', version='v202202') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v202105/creative_service/update_creatives.py b/examples/ad_manager/v202202/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v202105/creative_service/update_creatives.py rename to examples/ad_manager/v202202/creative_service/update_creatives.py index 53f0c63a..868990a6 100755 --- a/examples/ad_manager/v202105/creative_service/update_creatives.py +++ b/examples/ad_manager/v202202/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202105') + creative_service = client.GetService('CreativeService', version='v202202') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v202105/creative_set_service/__init__.py b/examples/ad_manager/v202202/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/creative_set_service/__init__.py rename to examples/ad_manager/v202202/creative_set_service/__init__.py diff --git a/examples/ad_manager/v202105/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202202/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v202105/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202202/creative_set_service/associate_creative_set_to_line_item.py index a441ecba..f371563b 100755 --- a/examples/ad_manager/v202105/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202202/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202105') + 'LineItemCreativeAssociationService', version='v202202') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v202105/creative_set_service/create_creative_set.py b/examples/ad_manager/v202202/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v202105/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202202/creative_set_service/create_creative_set.py index a2806348..01b0ebc7 100755 --- a/examples/ad_manager/v202105/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202202/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202105') + version='v202202') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v202105/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202202/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v202105/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202202/creative_set_service/get_all_creative_sets.py index 3f8f41ae..5b9e192f 100755 --- a/examples/ad_manager/v202105/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202202/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202105') + 'CreativeSetService', version='v202202') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v202105/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202202/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v202105/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202202/creative_set_service/get_creative_sets_for_master_creative.py index 6470e727..51ea56f3 100755 --- a/examples/ad_manager/v202105/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202202/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202105') + 'CreativeSetService', version='v202202') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v202105/creative_set_service/update_creative_set.py b/examples/ad_manager/v202202/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v202105/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202202/creative_set_service/update_creative_set.py index d7e19393..799f72a4 100755 --- a/examples/ad_manager/v202105/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202202/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202105') + version='v202202') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v202105/creative_template_service/__init__.py b/examples/ad_manager/v202202/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/creative_template_service/__init__.py rename to examples/ad_manager/v202202/creative_template_service/__init__.py diff --git a/examples/ad_manager/v202105/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202202/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v202105/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202202/creative_template_service/get_all_creative_templates.py index 49ef7c83..def20016 100755 --- a/examples/ad_manager/v202105/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202202/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202105') + 'CreativeTemplateService', version='v202202') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v202105/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202202/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v202105/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202202/creative_template_service/get_system_defined_creative_templates.py index db8ef20e..3c954c22 100755 --- a/examples/ad_manager/v202105/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202202/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202105') + 'CreativeTemplateService', version='v202202') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v202105/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202202/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v202105/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202202/creative_wrapper_service/create_creative_wrappers.py index 1549fe4b..4ac1c575 100755 --- a/examples/ad_manager/v202105/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202202/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202105') + version='v202202') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v202105/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202202/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v202105/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202202/creative_wrapper_service/deactivate_creative_wrapper.py index 4ec35bfc..533bdad7 100755 --- a/examples/ad_manager/v202105/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202202/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202105') + version='v202202') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202105/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202202/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202105/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202202/creative_wrapper_service/get_active_creative_wrappers.py index cde2a3f6..416c94a9 100755 --- a/examples/ad_manager/v202105/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202202/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202105') + 'CreativeWrapperService', version='v202202') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202105/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202202/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202105/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202202/creative_wrapper_service/get_all_creative_wrappers.py index 021eeb07..4957c174 100755 --- a/examples/ad_manager/v202105/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202202/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202105') + 'CreativeWrapperService', version='v202202') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v202105/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202202/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v202105/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202202/creative_wrapper_service/update_creative_wrappers.py index d14b4542..db314f66 100755 --- a/examples/ad_manager/v202105/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202202/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202105') + version='v202202') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v202105/custom_field_service/__init__.py b/examples/ad_manager/v202202/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/custom_field_service/__init__.py rename to examples/ad_manager/v202202/custom_field_service/__init__.py diff --git a/examples/ad_manager/v202105/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202202/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v202105/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202202/custom_field_service/create_custom_field_options.py index 05f482dd..f944e908 100755 --- a/examples/ad_manager/v202105/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202202/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202105') + 'CustomFieldService', version='v202202') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v202105/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202202/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v202105/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202202/custom_field_service/create_custom_fields.py index 910afa45..7a596091 100755 --- a/examples/ad_manager/v202105/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202202/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202105') + 'CustomFieldService', version='v202202') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v202105/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202202/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v202105/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202202/custom_field_service/deactivate_all_line_item_custom_fields.py index 8f5de91f..5c4740bf 100755 --- a/examples/ad_manager/v202105/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202202/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202105') + 'CustomFieldService', version='v202202') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202105/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202202/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v202105/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202202/custom_field_service/get_all_custom_fields.py index 1bc0f567..71d6a126 100755 --- a/examples/ad_manager/v202105/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202202/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202105') + 'CustomFieldService', version='v202202') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v202105/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202202/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v202105/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202202/custom_field_service/get_custom_fields_for_line_items.py index e93bc969..52726fc1 100755 --- a/examples/ad_manager/v202105/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202202/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202105') + 'CustomFieldService', version='v202202') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v202105/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202202/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v202105/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202202/custom_field_service/set_line_item_custom_field_value.py index 121ddb9d..23cbfe44 100755 --- a/examples/ad_manager/v202105/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202202/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v202105') + 'CustomFieldService', version='v202202') - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v202105') + custom_field_statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v202105') + ad_manager.StatementBuilder(version='v202202') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v202105') + line_item_statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v202105/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202202/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v202105/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202202/custom_field_service/update_custom_fields.py index ac3f86b5..7db37627 100755 --- a/examples/ad_manager/v202105/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202202/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202105') + 'CustomFieldService', version='v202202') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v202105/custom_targeting_service/__init__.py b/examples/ad_manager/v202202/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/custom_targeting_service/__init__.py rename to examples/ad_manager/v202202/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v202105/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202202/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v202105/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202202/custom_targeting_service/create_custom_targeting_keys_and_values.py index f61f3c3b..b230118c 100755 --- a/examples/ad_manager/v202105/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202202/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202105') + 'CustomTargetingService', version='v202202') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_keys.py index 3a059fd4..4e81d48b 100755 --- a/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202105') + 'CustomTargetingService', version='v202202') - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v202105') + key_statement = (ad_manager.StatementBuilder(version='v202202') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_values.py index 7fa1091e..e9d30a07 100755 --- a/examples/ad_manager/v202105/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202202/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202105') + 'CustomTargetingService', version='v202202') - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [str(value['id']) for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v202105') + value_statement = (ad_manager.StatementBuilder(version='v202202') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v202105/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202202/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202105/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202202/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 5dd87b0b..b07d63d5 100755 --- a/examples/ad_manager/v202105/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202202/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202105') + 'CustomTargetingService', version='v202202') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v202105') + targeting_key_statement = ad_manager.StatementBuilder(version='v202202') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v202105/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202202/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202105/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202202/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index 2121cbb2..3e44bd34 100755 --- a/examples/ad_manager/v202105/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202202/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202105') + 'CustomTargetingService', version='v202202') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v202105') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202202') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_keys.py index f9fc8950..93f438cb 100755 --- a/examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202105') + 'CustomTargetingService', version='v202202') - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_values.py index 6d4c3c20..66963ead 100755 --- a/examples/ad_manager/v202105/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202202/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202105') + 'CustomTargetingService', version='v202202') - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v202105/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202202/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v202105/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202202/forecast_service/get_availability_forecast.py index dd44cfaa..0e1cb806 100755 --- a/examples/ad_manager/v202105/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202202/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202105') - network_service = client.GetService('NetworkService', version='v202105') + forecast_service = client.GetService('ForecastService', version='v202202') + network_service = client.GetService('NetworkService', version='v202202') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202105/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202202/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v202105/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202202/forecast_service/get_availability_forecast_for_line_item.py index aabcd344..ce6a941a 100755 --- a/examples/ad_manager/v202105/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202202/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202105') + forecast_service = client.GetService('ForecastService', version='v202202') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v202105/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202202/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v202105/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202202/forecast_service/get_delivery_forecast_for_line_items.py index 02991d5a..71c2711e 100755 --- a/examples/ad_manager/v202105/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202202/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202105') + forecast_service = client.GetService('ForecastService', version='v202202') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v202105/forecast_service/get_traffic_data.py b/examples/ad_manager/v202202/forecast_service/get_traffic_data.py similarity index 99% rename from examples/ad_manager/v202105/forecast_service/get_traffic_data.py rename to examples/ad_manager/v202202/forecast_service/get_traffic_data.py index b3741bda..d20045f6 100755 --- a/examples/ad_manager/v202105/forecast_service/get_traffic_data.py +++ b/examples/ad_manager/v202202/forecast_service/get_traffic_data.py @@ -25,8 +25,8 @@ def main(client): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202105') - network_service = client.GetService('NetworkService', version='v202105') + forecast_service = client.GetService('ForecastService', version='v202202') + network_service = client.GetService('NetworkService', version='v202202') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202105/inventory_service/__init__.py b/examples/ad_manager/v202202/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/inventory_service/__init__.py rename to examples/ad_manager/v202202/inventory_service/__init__.py diff --git a/examples/ad_manager/v202105/inventory_service/archive_ad_units.py b/examples/ad_manager/v202202/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v202105/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202202/inventory_service/archive_ad_units.py index 6b524b3c..85e3e12f 100755 --- a/examples/ad_manager/v202105/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202202/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202105') + inventory_service = client.GetService('InventoryService', version='v202202') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v202105/inventory_service/create_ad_units.py b/examples/ad_manager/v202202/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v202105/inventory_service/create_ad_units.py rename to examples/ad_manager/v202202/inventory_service/create_ad_units.py index 0778f223..490af8ec 100755 --- a/examples/ad_manager/v202105/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202202/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202105') + inventory_service = client.GetService('InventoryService', version='v202202') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v202105/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202202/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v202105/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202202/inventory_service/get_ad_unit_hierarchy.py index d9e31a7c..14760db6 100755 --- a/examples/ad_manager/v202105/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202202/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202105') - inventory_service = client.GetService('InventoryService', version='v202105') + network_service = client.GetService('NetworkService', version='v202202') + inventory_service = client.GetService('InventoryService', version='v202202') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v202105/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202202/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v202105/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202202/inventory_service/get_all_ad_unit_sizes.py index 2edd001b..514997c2 100755 --- a/examples/ad_manager/v202105/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202202/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v202105') + 'InventoryService', version='v202202') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v202105/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202202/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v202105/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202202/inventory_service/get_all_ad_units.py index 5dac2cec..67bf0a1f 100755 --- a/examples/ad_manager/v202105/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202202/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v202105') + ad_unit_service = client.GetService('InventoryService', version='v202202') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v202105/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202202/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v202105/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202202/inventory_service/get_top_level_ad_units.py index fc321baf..8c1723d5 100755 --- a/examples/ad_manager/v202105/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202202/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202105') - inventory_service = client.GetService('InventoryService', version='v202105') + network_service = client.GetService('NetworkService', version='v202202') + inventory_service = client.GetService('InventoryService', version='v202202') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v202105/inventory_service/update_ad_units.py b/examples/ad_manager/v202202/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v202105/inventory_service/update_ad_units.py rename to examples/ad_manager/v202202/inventory_service/update_ad_units.py index 91c8f99f..f2a84e7e 100755 --- a/examples/ad_manager/v202105/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202202/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202105') + inventory_service = client.GetService('InventoryService', version='v202202') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v202105/label_service/__init__.py b/examples/ad_manager/v202202/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/label_service/__init__.py rename to examples/ad_manager/v202202/label_service/__init__.py diff --git a/examples/ad_manager/v202105/label_service/create_labels.py b/examples/ad_manager/v202202/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v202105/label_service/create_labels.py rename to examples/ad_manager/v202202/label_service/create_labels.py index 8cea4a42..b3cf9876 100755 --- a/examples/ad_manager/v202105/label_service/create_labels.py +++ b/examples/ad_manager/v202202/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202105') + label_service = client.GetService('LabelService', version='v202202') # Create label objects. labels = [] diff --git a/examples/ad_manager/v202105/label_service/deactivate_labels.py b/examples/ad_manager/v202202/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v202105/label_service/deactivate_labels.py rename to examples/ad_manager/v202202/label_service/deactivate_labels.py index 8fe843f6..c3067b3e 100755 --- a/examples/ad_manager/v202105/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202202/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202105') + label_service = client.GetService('LabelService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202105/label_service/get_active_labels.py b/examples/ad_manager/v202202/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v202105/label_service/get_active_labels.py rename to examples/ad_manager/v202202/label_service/get_active_labels.py index 982f0e65..e31a0e45 100755 --- a/examples/ad_manager/v202105/label_service/get_active_labels.py +++ b/examples/ad_manager/v202202/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202105') + label_service = client.GetService('LabelService', version='v202202') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202105/label_service/get_all_labels.py b/examples/ad_manager/v202202/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v202105/label_service/get_all_labels.py rename to examples/ad_manager/v202202/label_service/get_all_labels.py index 718fff8f..35e7d91f 100755 --- a/examples/ad_manager/v202105/label_service/get_all_labels.py +++ b/examples/ad_manager/v202202/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202105') + label_service = client.GetService('LabelService', version='v202202') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v202105/label_service/update_labels.py b/examples/ad_manager/v202202/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v202105/label_service/update_labels.py rename to examples/ad_manager/v202202/label_service/update_labels.py index 724e2ba3..48d6d131 100755 --- a/examples/ad_manager/v202105/label_service/update_labels.py +++ b/examples/ad_manager/v202202/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202105') + label_service = client.GetService('LabelService', version='v202202') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202105/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202202/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202202/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v202105/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202202/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v202105/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202202/line_item_creative_association_service/create_licas.py index 67286d56..d419720f 100755 --- a/examples/ad_manager/v202105/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202202/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202105') + 'LineItemCreativeAssociationService', version='v202202') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v202105/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202202/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v202105/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202202/line_item_creative_association_service/deactivate_licas.py index d8d46da4..e46dab72 100755 --- a/examples/ad_manager/v202105/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202202/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202105') + 'LineItemCreativeAssociationService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v202105/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202202/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v202105/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202202/line_item_creative_association_service/get_all_licas.py index 92bb7e62..b4ef82a5 100755 --- a/examples/ad_manager/v202105/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202202/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202105') + 'LineItemCreativeAssociationService', version='v202202') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v202105/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202202/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v202105/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202202/line_item_creative_association_service/get_licas_for_line_item.py index 2b43e5c1..3f1d46f2 100755 --- a/examples/ad_manager/v202105/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202202/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202105') + 'LineItemCreativeAssociationService', version='v202202') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v202105/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202202/line_item_creative_association_service/push_creative_to_devices.py similarity index 94% rename from examples/ad_manager/v202105/line_item_creative_association_service/push_creative_to_devices.py rename to examples/ad_manager/v202202/line_item_creative_association_service/push_creative_to_devices.py index 1bb2ba5a..90de873e 100755 --- a/examples/ad_manager/v202105/line_item_creative_association_service/push_creative_to_devices.py +++ b/examples/ad_manager/v202202/line_item_creative_association_service/push_creative_to_devices.py @@ -34,11 +34,11 @@ def main(client, line_item_id, creative_id, linked_device_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202105') + 'LineItemCreativeAssociationService', version='v202202') # Create query to select a single linked device. # Linked devices can be read from the linked_device PQL table. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :linkedDeviceId') .WithBindVariable('linkedDeviceId', int(linked_device_id))) diff --git a/examples/ad_manager/v202105/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202202/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v202105/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202202/line_item_creative_association_service/update_licas.py index f7f7db31..c8f5eca1 100755 --- a/examples/ad_manager/v202105/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202202/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202105') + 'LineItemCreativeAssociationService', version='v202202') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v202105/line_item_service/__init__.py b/examples/ad_manager/v202202/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/line_item_service/__init__.py rename to examples/ad_manager/v202202/line_item_service/__init__.py diff --git a/examples/ad_manager/v202105/line_item_service/activate_line_items.py b/examples/ad_manager/v202202/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v202105/line_item_service/activate_line_items.py rename to examples/ad_manager/v202202/line_item_service/activate_line_items.py index b0064816..a38c3919 100755 --- a/examples/ad_manager/v202105/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202202/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202105/line_item_service/create_line_items.py b/examples/ad_manager/v202202/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v202105/line_item_service/create_line_items.py rename to examples/ad_manager/v202202/line_item_service/create_line_items.py index 54940710..00a4a7e7 100755 --- a/examples/ad_manager/v202105/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202202/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202105/line_item_service/create_video_line_item.py b/examples/ad_manager/v202202/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v202105/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202202/line_item_service/create_video_line_item.py index bc9c6df3..f94574d1 100755 --- a/examples/ad_manager/v202105/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202202/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202105/line_item_service/get_all_line_items.py b/examples/ad_manager/v202202/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v202105/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202202/line_item_service/get_all_line_items.py index ae4803ce..62042eae 100755 --- a/examples/ad_manager/v202105/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202202/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v202105/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202202/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v202105/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202202/line_item_service/get_line_items_that_need_creatives.py index 6544cc20..487b8464 100755 --- a/examples/ad_manager/v202105/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202202/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v202105/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202202/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v202105/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202202/line_item_service/get_recently_updated_line_items.py index 1606e15e..1e6fddd8 100755 --- a/examples/ad_manager/v202105/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202202/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202105/line_item_service/pause_line_items.py b/examples/ad_manager/v202202/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v202105/line_item_service/pause_line_items.py rename to examples/ad_manager/v202202/line_item_service/pause_line_items.py index ce445eff..d9e48906 100755 --- a/examples/ad_manager/v202105/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202202/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v202105/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202202/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v202105/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202202/line_item_service/target_custom_criteria.py index c16cd8a2..709f33e9 100755 --- a/examples/ad_manager/v202105/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202202/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/line_item_service/update_line_items.py b/examples/ad_manager/v202202/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v202105/line_item_service/update_line_items.py rename to examples/ad_manager/v202202/line_item_service/update_line_items.py index 58e765e1..8171ab11 100755 --- a/examples/ad_manager/v202105/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202202/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202105') + line_item_service = client.GetService('LineItemService', version='v202202') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v202105/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202202/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202105/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202202/live_stream_event_service/activate_live_stream_events.py index 9d836e20..b2ac8301 100755 --- a/examples/ad_manager/v202105/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202202/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202105') + 'LiveStreamEventService', version='v202202') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v202105/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202202/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v202105/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202202/live_stream_event_service/create_live_stream_events.py index 9c72ff7a..02109ec1 100755 --- a/examples/ad_manager/v202105/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202202/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v202105') + 'LiveStreamEventService', version='v202202') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v202105/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202202/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v202105/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202202/live_stream_event_service/get_all_live_stream_events.py index 14edb382..72a94a9c 100755 --- a/examples/ad_manager/v202105/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202202/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202105') + 'LiveStreamEventService', version='v202202') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v202105/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202202/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v202105/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202202/live_stream_event_service/register_sessions_for_monitoring.py index 93485a4c..c201177d 100755 --- a/examples/ad_manager/v202105/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202202/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202105') + 'LiveStreamEventService', version='v202202') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v202105/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202202/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202105/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202202/live_stream_event_service/update_live_stream_events.py index f1d81435..40aef5c2 100755 --- a/examples/ad_manager/v202105/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202202/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v202105') + 'LiveStreamEventService', version='v202202') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v202105/native_style_service/__init__.py b/examples/ad_manager/v202202/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/native_style_service/__init__.py rename to examples/ad_manager/v202202/native_style_service/__init__.py diff --git a/examples/ad_manager/v202105/native_style_service/create_native_styles.py b/examples/ad_manager/v202202/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v202105/native_style_service/create_native_styles.py rename to examples/ad_manager/v202202/native_style_service/create_native_styles.py index 1eb83c18..b805cebb 100755 --- a/examples/ad_manager/v202105/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202202/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202105') + version='v202202') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v202105/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202202/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v202105/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202202/native_style_service/get_all_native_styles.py index 51ef2c77..2d1d0fa9 100755 --- a/examples/ad_manager/v202105/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202202/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202105') + version='v202202') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v202105/network_service/__init__.py b/examples/ad_manager/v202202/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/network_service/__init__.py rename to examples/ad_manager/v202202/network_service/__init__.py diff --git a/examples/ad_manager/v202105/network_service/get_all_networks.py b/examples/ad_manager/v202202/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v202105/network_service/get_all_networks.py rename to examples/ad_manager/v202202/network_service/get_all_networks.py index 915a26c9..5ce069bd 100755 --- a/examples/ad_manager/v202105/network_service/get_all_networks.py +++ b/examples/ad_manager/v202202/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202105') + network_service = client.GetService('NetworkService', version='v202202') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v202105/network_service/get_current_network.py b/examples/ad_manager/v202202/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v202105/network_service/get_current_network.py rename to examples/ad_manager/v202202/network_service/get_current_network.py index 67d6b416..a04a1f0b 100755 --- a/examples/ad_manager/v202105/network_service/get_current_network.py +++ b/examples/ad_manager/v202202/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202105') + network_service = client.GetService('NetworkService', version='v202202') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202105/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202202/network_service/get_default_third_party_data_declaration.py similarity index 95% rename from examples/ad_manager/v202105/network_service/get_default_third_party_data_declaration.py rename to examples/ad_manager/v202202/network_service/get_default_third_party_data_declaration.py index f5109926..6ea1ea45 100755 --- a/examples/ad_manager/v202105/network_service/get_default_third_party_data_declaration.py +++ b/examples/ad_manager/v202202/network_service/get_default_third_party_data_declaration.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202105') + network_service = client.GetService('NetworkService', version='v202202') pql_service = client.GetService('PublisherQueryLanguageService', - version='v202105') + version='v202202') # Fetch the default third party data declarations. declarations = network_service.getDefaultThirdPartyDataDeclaration() @@ -44,7 +44,7 @@ def main(client): # In this case, there are third party companies to be displayed, so fetch # the company names from the Rich_Media_Ad_Company PQL table. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Select('Id, Name') .From('Rich_Media_Ad_Company') .Where('Id IN (:company_ids)') diff --git a/examples/ad_manager/v202105/network_service/make_test_network.py b/examples/ad_manager/v202202/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v202105/network_service/make_test_network.py rename to examples/ad_manager/v202202/network_service/make_test_network.py index 5ad1a5d6..07f00c39 100755 --- a/examples/ad_manager/v202105/network_service/make_test_network.py +++ b/examples/ad_manager/v202202/network_service/make_test_network.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202105') + network_service = client.GetService('NetworkService', version='v202202') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v202105/order_service/__init__.py b/examples/ad_manager/v202202/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/order_service/__init__.py rename to examples/ad_manager/v202202/order_service/__init__.py diff --git a/examples/ad_manager/v202105/order_service/approve_orders.py b/examples/ad_manager/v202202/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v202105/order_service/approve_orders.py rename to examples/ad_manager/v202202/order_service/approve_orders.py index 381bd2ec..13e6f246 100755 --- a/examples/ad_manager/v202105/order_service/approve_orders.py +++ b/examples/ad_manager/v202202/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202105') + order_service = client.GetService('OrderService', version='v202202') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v202105/order_service/create_orders.py b/examples/ad_manager/v202202/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v202105/order_service/create_orders.py rename to examples/ad_manager/v202202/order_service/create_orders.py index b15cd23c..9673abfa 100755 --- a/examples/ad_manager/v202105/order_service/create_orders.py +++ b/examples/ad_manager/v202202/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202105') + order_service = client.GetService('OrderService', version='v202202') # Create order objects. orders = [] diff --git a/examples/ad_manager/v202105/order_service/get_all_orders.py b/examples/ad_manager/v202202/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v202105/order_service/get_all_orders.py rename to examples/ad_manager/v202202/order_service/get_all_orders.py index 5fc924cd..bf20e081 100755 --- a/examples/ad_manager/v202105/order_service/get_all_orders.py +++ b/examples/ad_manager/v202202/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202105') + order_service = client.GetService('OrderService', version='v202202') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v202105/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202202/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v202105/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202202/order_service/get_orders_starting_soon.py index 679984ed..1f18ae3e 100755 --- a/examples/ad_manager/v202105/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202202/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202105') + order_service = client.GetService('OrderService', version='v202202') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v202105/order_service/update_orders.py b/examples/ad_manager/v202202/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v202105/order_service/update_orders.py rename to examples/ad_manager/v202202/order_service/update_orders.py index 965fa9f7..d1dbf700 100755 --- a/examples/ad_manager/v202105/order_service/update_orders.py +++ b/examples/ad_manager/v202202/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202105') + order_service = client.GetService('OrderService', version='v202202') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202105/placement_service/create_placements.py b/examples/ad_manager/v202202/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v202105/placement_service/create_placements.py rename to examples/ad_manager/v202202/placement_service/create_placements.py index 9d8ef572..6f7ba34f 100755 --- a/examples/ad_manager/v202105/placement_service/create_placements.py +++ b/examples/ad_manager/v202202/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202105') - inventory_service = client.GetService('InventoryService', version='v202105') + placement_service = client.GetService('PlacementService', version='v202202') + inventory_service = client.GetService('InventoryService', version='v202202') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v202105/placement_service/deactivate_placements.py b/examples/ad_manager/v202202/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v202105/placement_service/deactivate_placements.py rename to examples/ad_manager/v202202/placement_service/deactivate_placements.py index 9e224b21..f2725cab 100755 --- a/examples/ad_manager/v202105/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202202/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202105') + placement_service = client.GetService('PlacementService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/placement_service/get_active_placements.py b/examples/ad_manager/v202202/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v202105/placement_service/get_active_placements.py rename to examples/ad_manager/v202202/placement_service/get_active_placements.py index 957aa365..364b488a 100755 --- a/examples/ad_manager/v202105/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202202/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202105') + placement_service = client.GetService('PlacementService', version='v202202') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202105/placement_service/get_all_placements.py b/examples/ad_manager/v202202/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v202105/placement_service/get_all_placements.py rename to examples/ad_manager/v202202/placement_service/get_all_placements.py index 378fd81c..b8c5f3f1 100755 --- a/examples/ad_manager/v202105/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202202/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202105') + placement_service = client.GetService('PlacementService', version='v202202') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v202105/placement_service/update_placements.py b/examples/ad_manager/v202202/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v202105/placement_service/update_placements.py rename to examples/ad_manager/v202202/placement_service/update_placements.py index 977155d4..4233e32f 100755 --- a/examples/ad_manager/v202105/placement_service/update_placements.py +++ b/examples/ad_manager/v202202/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202105') + placement_service = client.GetService('PlacementService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v202105/proposal_line_item_service/__init__.py b/examples/ad_manager/v202202/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202202/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v202105/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202202/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202105/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202202/proposal_line_item_service/archive_proposal_line_items.py index 61422f63..c9f7a6d3 100755 --- a/examples/ad_manager/v202105/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202202/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202105') + 'ProposalLineItemService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202202/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v202105/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202202/proposal_line_item_service/create_proposal_line_items.py index e561a0fe..fe981122 100755 --- a/examples/ad_manager/v202105/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202202/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202105') - network_service = client.GetService('NetworkService', version='v202105') + 'ProposalLineItemService', version='v202202') + network_service = client.GetService('NetworkService', version='v202202') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202105/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202202/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202105/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202202/proposal_line_item_service/get_all_proposal_line_items.py index a1145671..f21a3aca 100755 --- a/examples/ad_manager/v202105/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202202/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202105') + 'ProposalLineItemService', version='v202202') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v202105/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202202/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v202105/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202202/proposal_line_item_service/get_proposal_line_items_for_proposal.py index b5718665..8ce81962 100755 --- a/examples/ad_manager/v202105/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202202/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202105') + 'ProposalLineItemService', version='v202202') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v202105/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202202/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202105/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202202/proposal_line_item_service/update_proposal_line_items.py index 2a8f0f82..31e1e669 100755 --- a/examples/ad_manager/v202105/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202202/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202105') + 'ProposalLineItemService', version='v202202') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/proposal_service/__init__.py b/examples/ad_manager/v202202/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/proposal_service/__init__.py rename to examples/ad_manager/v202202/proposal_service/__init__.py diff --git a/examples/ad_manager/v202105/proposal_service/create_proposals.py b/examples/ad_manager/v202202/proposal_service/create_proposals.py similarity index 99% rename from examples/ad_manager/v202105/proposal_service/create_proposals.py rename to examples/ad_manager/v202202/proposal_service/create_proposals.py index 43178b9d..ac639cf8 100755 --- a/examples/ad_manager/v202105/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202202/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v202105') + proposal_service = client.GetService('ProposalService', version='v202202') proposal = { # Setting required Marketplace information. diff --git a/examples/ad_manager/v202105/proposal_service/get_all_proposals.py b/examples/ad_manager/v202202/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v202105/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202202/proposal_service/get_all_proposals.py index 4b0030ef..8642ec2a 100755 --- a/examples/ad_manager/v202105/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202202/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202105') + proposal_service = client.GetService('ProposalService', version='v202202') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v202105/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202202/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v202105/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202202/proposal_service/get_marketplace_comments.py index 809fe4a7..293f4c02 100755 --- a/examples/ad_manager/v202105/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202202/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v202105') + 'ProposalService', version='v202202') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v202105/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202202/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v202105/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202202/proposal_service/get_proposals_awaiting_seller_review.py index e3f2cee3..c7260db1 100755 --- a/examples/ad_manager/v202105/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202202/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202105') + proposal_service = client.GetService('ProposalService', version='v202202') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v202105/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202202/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v202105/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202202/proposal_service/request_buyers_acceptance.py index 095a71ab..253c8ed6 100755 --- a/examples/ad_manager/v202105/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202202/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202105') + proposal_service = client.GetService('ProposalService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v202105/proposal_service/update_proposals.py b/examples/ad_manager/v202202/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v202105/proposal_service/update_proposals.py rename to examples/ad_manager/v202202/proposal_service/update_proposals.py index 6a088033..7112fec9 100755 --- a/examples/ad_manager/v202105/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202202/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202105') + proposal_service = client.GetService('ProposalService', version='v202202') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/publisher_query_language_service/__init__.py b/examples/ad_manager/v202202/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202202/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v202105/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202202/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v202105/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202202/publisher_query_language_service/fetch_match_tables.py index e9f4a824..52fa3bd7 100755 --- a/examples/ad_manager/v202105/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202202/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202105/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202202/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v202105/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202202/publisher_query_language_service/get_all_browsers.py index 0214c316..33b4ed85 100755 --- a/examples/ad_manager/v202105/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202202/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v202105/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202202/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v202105/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202202/publisher_query_language_service/get_all_programmatic_buyers.py index f18dc303..498c2b22 100755 --- a/examples/ad_manager/v202105/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202202/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202105') + data_downloader = client.GetDataDownloader(version='v202202') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202105/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202202/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v202105/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202202/publisher_query_language_service/get_geo_targets.py index 7719f042..ae3d0ace 100755 --- a/examples/ad_manager/v202105/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202202/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v202105/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202202/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v202105/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202202/publisher_query_language_service/get_line_items_named_like.py index 0d872a69..e72cc87f 100755 --- a/examples/ad_manager/v202105/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202202/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202105/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202202/publisher_query_language_service/get_mcm_earnings.py similarity index 97% rename from examples/ad_manager/v202105/publisher_query_language_service/get_mcm_earnings.py rename to examples/ad_manager/v202202/publisher_query_language_service/get_mcm_earnings.py index 96f3bc08..ed393c7a 100755 --- a/examples/ad_manager/v202105/publisher_query_language_service/get_mcm_earnings.py +++ b/examples/ad_manager/v202202/publisher_query_language_service/get_mcm_earnings.py @@ -26,7 +26,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202105') + data_downloader = client.GetDataDownloader(version='v202202') with tempfile.NamedTemporaryFile( prefix='mcm_earnings_', diff --git a/examples/ad_manager/v202105/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202202/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v202105/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202202/publisher_query_language_service/get_recent_changes.py index 5ab40aaa..0dfdf202 100755 --- a/examples/ad_manager/v202105/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202202/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v202105') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202202') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v202105/report_service/__init__.py b/examples/ad_manager/v202202/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/report_service/__init__.py rename to examples/ad_manager/v202202/report_service/__init__.py diff --git a/examples/ad_manager/v202105/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202202/report_service/run_ad_exchange_report.py similarity index 97% rename from examples/ad_manager/v202105/report_service/run_ad_exchange_report.py rename to examples/ad_manager/v202202/report_service/run_ad_exchange_report.py index c95f1c6d..e1d8267d 100755 --- a/examples/ad_manager/v202105/report_service/run_ad_exchange_report.py +++ b/examples/ad_manager/v202202/report_service/run_ad_exchange_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') # Create report job. report_job = { diff --git a/examples/ad_manager/v202105/report_service/run_delivery_report.py b/examples/ad_manager/v202202/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v202105/report_service/run_delivery_report.py rename to examples/ad_manager/v202202/report_service/run_delivery_report.py index 51991c2f..e09560cf 100755 --- a/examples/ad_manager/v202105/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202202/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202105/report_service/run_inventory_report.py b/examples/ad_manager/v202202/report_service/run_inventory_report.py similarity index 97% rename from examples/ad_manager/v202105/report_service/run_inventory_report.py rename to examples/ad_manager/v202202/report_service/run_inventory_report.py index 3c13a105..25fd0eb2 100755 --- a/examples/ad_manager/v202105/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202202/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') # Create report job. report_job = { diff --git a/examples/ad_manager/v202105/report_service/run_reach_report.py b/examples/ad_manager/v202202/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v202105/report_service/run_reach_report.py rename to examples/ad_manager/v202202/report_service/run_reach_report.py index dfb7fc6a..02fbfc3f 100755 --- a/examples/ad_manager/v202105/report_service/run_reach_report.py +++ b/examples/ad_manager/v202202/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') # Create report job. report_job = { diff --git a/examples/ad_manager/v202202/report_service/run_reach_report_with_ad_unit_dimensions.py b/examples/ad_manager/v202202/report_service/run_reach_report_with_ad_unit_dimensions.py new file mode 100755 index 00000000..84585602 --- /dev/null +++ b/examples/ad_manager/v202202/report_service/run_reach_report_with_ad_unit_dimensions.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +# +# Copyright 2021 Google LLC +# +# 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 code example runs a reach report.""" + +import tempfile + +# Import appropriate modules from the client library. +from googleads import ad_manager +from googleads import errors + + +def main(client): + # Initialize a DataDownloader. + report_downloader = client.GetDataDownloader(version='v202202') + + # Create report job. + report_job = { + 'reportQuery': { + # For Reach reports with AD_UNIT_ID or AD_UNIT_NAME in the dimensions + # list, adUnitView must be set to 'FLAT' or 'HIERARCHICAL'. + 'adUnitView': 'FLAT', + 'dimensions': ['MONTH_AND_YEAR', 'COUNTRY_NAME', 'AD_UNIT_ID', + 'AD_UNIT_NAME'], + 'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS', + 'UNIQUE_REACH'], + 'dateRangeType': 'LAST_MONTH' + } + } + + try: + # Run the report and wait for it to finish. + report_job_id = report_downloader.WaitForReport(report_job) + except errors.AdManagerReportError as e: + print('Failed to generate report. Error was: %s' % e) + + # Change to your preferred export format. + export_format = 'CSV_DUMP' + + report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) + + # Download report data. + report_downloader.DownloadReportToFile( + report_job_id, export_format, report_file) + + report_file.close() + + # Display results. + print('Report job with id "%s" downloaded to:\n%s' % ( + report_job_id, report_file.name)) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client) diff --git a/examples/ad_manager/v202105/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202202/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v202105/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202202/report_service/run_report_and_create_match_table.py index 1b009907..9210795c 100755 --- a/examples/ad_manager/v202105/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202202/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202105/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202202/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v202105/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202202/report_service/run_report_with_custom_fields.py index 33441d40..2416c0c8 100755 --- a/examples/ad_manager/v202105/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202202/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') # Create report job. report_job = { diff --git a/examples/ad_manager/v202105/report_service/run_sales_report.py b/examples/ad_manager/v202202/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v202105/report_service/run_sales_report.py rename to examples/ad_manager/v202202/report_service/run_sales_report.py index 7f61a979..c601f7c3 100755 --- a/examples/ad_manager/v202105/report_service/run_sales_report.py +++ b/examples/ad_manager/v202202/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') # Create report job. report_job = { diff --git a/examples/ad_manager/v202105/report_service/run_saved_query.py b/examples/ad_manager/v202202/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v202105/report_service/run_saved_query.py rename to examples/ad_manager/v202202/report_service/run_saved_query.py index fcd36b83..66a8d4ce 100755 --- a/examples/ad_manager/v202105/report_service/run_saved_query.py +++ b/examples/ad_manager/v202202/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v202105') + report_service = client.GetService('ReportService', version='v202202') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202105') + report_downloader = client.GetDataDownloader(version='v202202') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202105/site_service/create_sites.py b/examples/ad_manager/v202202/site_service/create_sites.py similarity index 96% rename from examples/ad_manager/v202105/site_service/create_sites.py rename to examples/ad_manager/v202202/site_service/create_sites.py index e011f51d..15093841 100755 --- a/examples/ad_manager/v202105/site_service/create_sites.py +++ b/examples/ad_manager/v202202/site_service/create_sites.py @@ -27,8 +27,8 @@ def main(client, url, child_network_code): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202105') - site_service = client.GetService('SiteService', version='v202105') + network_service = client.GetService('NetworkService', version='v202202') + site_service = client.GetService('SiteService', version='v202202') # Check that the child network code is approved for MANAGE_INVENTORY by this # network. diff --git a/examples/ad_manager/v202105/site_service/get_all_sites.py b/examples/ad_manager/v202202/site_service/get_all_sites.py similarity index 92% rename from examples/ad_manager/v202105/site_service/get_all_sites.py rename to examples/ad_manager/v202202/site_service/get_all_sites.py index ffd32a1e..6bd3a073 100755 --- a/examples/ad_manager/v202105/site_service/get_all_sites.py +++ b/examples/ad_manager/v202202/site_service/get_all_sites.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202105') + site_service = client.GetService('SiteService', version='v202202') # Create a statement to select Sites. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small number of sites at a time, paging through until all sites # have been retrieved. diff --git a/examples/ad_manager/v202105/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202202/site_service/get_sites_requiring_approval.py similarity index 92% rename from examples/ad_manager/v202105/site_service/get_sites_requiring_approval.py rename to examples/ad_manager/v202202/site_service/get_sites_requiring_approval.py index 9eb1bf10..e865f0ec 100755 --- a/examples/ad_manager/v202105/site_service/get_sites_requiring_approval.py +++ b/examples/ad_manager/v202202/site_service/get_sites_requiring_approval.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202105') + site_service = client.GetService('SiteService', version='v202202') # Create a statement to select Sites needing approval. - statement = ad_manager.StatementBuilder(version='v202105').Where( + statement = ad_manager.StatementBuilder(version='v202202').Where( "approvalStatus = 'REQUIRES_REVIEW'") # Retrieve a small number of sites at a time, paging through until all sites diff --git a/examples/ad_manager/v202105/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202202/site_service/submit_sites_for_approval.py similarity index 91% rename from examples/ad_manager/v202105/site_service/submit_sites_for_approval.py rename to examples/ad_manager/v202202/site_service/submit_sites_for_approval.py index e83411fa..0d0c5a9f 100755 --- a/examples/ad_manager/v202105/site_service/submit_sites_for_approval.py +++ b/examples/ad_manager/v202202/site_service/submit_sites_for_approval.py @@ -25,10 +25,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202105') + site_service = client.GetService('SiteService', version='v202202') # Create a statement to select Site. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :id') .WithBindVariable('id', SITE_ID)) diff --git a/examples/ad_manager/v202105/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202202/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202202/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v202105/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202202/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v202105/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202202/suggested_ad_unit_service/approve_all_suggested_ad_units.py index eedffa57..cde42642 100755 --- a/examples/ad_manager/v202105/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202202/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202105') + 'SuggestedAdUnitService', version='v202202') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v202105/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202202/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202105/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202202/suggested_ad_unit_service/get_all_suggested_ad_units.py index 7d301baa..88519bf4 100755 --- a/examples/ad_manager/v202105/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202202/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202105') + 'SuggestedAdUnitService', version='v202202') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v202105/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202202/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202105/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202202/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index ab202495..03fb97d1 100755 --- a/examples/ad_manager/v202105/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202202/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202105') + 'SuggestedAdUnitService', version='v202202') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v202105/targeting_preset_service/__init__.py b/examples/ad_manager/v202202/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/targeting_preset_service/__init__.py rename to examples/ad_manager/v202202/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202202/targeting_preset_service/get_all_targeting_presets.py similarity index 94% rename from examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202202/targeting_preset_service/get_all_targeting_presets.py index 06a0e17c..0a9cf814 100755 --- a/examples/ad_manager/v202105/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202202/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v202105') + 'TargetingPresetService', version='v202202') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. diff --git a/examples/ad_manager/v202105/team_service/__init__.py b/examples/ad_manager/v202202/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/team_service/__init__.py rename to examples/ad_manager/v202202/team_service/__init__.py diff --git a/examples/ad_manager/v202105/team_service/create_teams.py b/examples/ad_manager/v202202/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v202105/team_service/create_teams.py rename to examples/ad_manager/v202202/team_service/create_teams.py index fdec6f1f..84e7c0d2 100755 --- a/examples/ad_manager/v202105/team_service/create_teams.py +++ b/examples/ad_manager/v202202/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202105') + team_service = client.GetService('TeamService', version='v202202') # Create team objects. teams = [] diff --git a/examples/ad_manager/v202105/team_service/get_all_teams.py b/examples/ad_manager/v202202/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v202105/team_service/get_all_teams.py rename to examples/ad_manager/v202202/team_service/get_all_teams.py index 66925617..458f6373 100755 --- a/examples/ad_manager/v202105/team_service/get_all_teams.py +++ b/examples/ad_manager/v202202/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202105') + team_service = client.GetService('TeamService', version='v202202') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v202105/team_service/update_teams.py b/examples/ad_manager/v202202/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v202105/team_service/update_teams.py rename to examples/ad_manager/v202202/team_service/update_teams.py index 8316e9da..d00645dd 100755 --- a/examples/ad_manager/v202105/team_service/update_teams.py +++ b/examples/ad_manager/v202202/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202105') + team_service = client.GetService('TeamService', version='v202202') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v202105/user_service/__init__.py b/examples/ad_manager/v202202/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/user_service/__init__.py rename to examples/ad_manager/v202202/user_service/__init__.py diff --git a/examples/ad_manager/v202105/user_service/create_users.py b/examples/ad_manager/v202202/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v202105/user_service/create_users.py rename to examples/ad_manager/v202202/user_service/create_users.py index 30b39b8f..ea80af61 100755 --- a/examples/ad_manager/v202105/user_service/create_users.py +++ b/examples/ad_manager/v202202/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202105') + user_service = client.GetService('UserService', version='v202202') # Create user objects. users = [ diff --git a/examples/ad_manager/v202105/user_service/deactivate_users.py b/examples/ad_manager/v202202/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v202105/user_service/deactivate_users.py rename to examples/ad_manager/v202202/user_service/deactivate_users.py index 76441dbd..7a17027d 100755 --- a/examples/ad_manager/v202105/user_service/deactivate_users.py +++ b/examples/ad_manager/v202202/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202105') + user_service = client.GetService('UserService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202105/user_service/get_all_roles.py b/examples/ad_manager/v202202/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v202105/user_service/get_all_roles.py rename to examples/ad_manager/v202202/user_service/get_all_roles.py index 1360136e..f92f8b77 100755 --- a/examples/ad_manager/v202105/user_service/get_all_roles.py +++ b/examples/ad_manager/v202202/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202105') + user_service = client.GetService('UserService', version='v202202') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v202105/user_service/get_all_users.py b/examples/ad_manager/v202202/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v202105/user_service/get_all_users.py rename to examples/ad_manager/v202202/user_service/get_all_users.py index 90e45233..955c2ea0 100755 --- a/examples/ad_manager/v202105/user_service/get_all_users.py +++ b/examples/ad_manager/v202202/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202105') + user_service = client.GetService('UserService', version='v202202') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v202105/user_service/get_current_user.py b/examples/ad_manager/v202202/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v202105/user_service/get_current_user.py rename to examples/ad_manager/v202202/user_service/get_current_user.py index b65f44af..3be4fb9a 100755 --- a/examples/ad_manager/v202105/user_service/get_current_user.py +++ b/examples/ad_manager/v202202/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202105') + user_service = client.GetService('UserService', version='v202202') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v202105/user_service/get_user_by_email_address.py b/examples/ad_manager/v202202/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v202105/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202202/user_service/get_user_by_email_address.py index 8ee112f4..1e4739d8 100755 --- a/examples/ad_manager/v202105/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202202/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202105') + user_service = client.GetService('UserService', version='v202202') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v202105/user_service/update_users.py b/examples/ad_manager/v202202/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v202105/user_service/update_users.py rename to examples/ad_manager/v202202/user_service/update_users.py index 138669e7..9df04db0 100755 --- a/examples/ad_manager/v202105/user_service/update_users.py +++ b/examples/ad_manager/v202202/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202105') + user_service = client.GetService('UserService', version='v202202') # Create query. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202105/user_team_association_service/__init__.py b/examples/ad_manager/v202202/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202105/user_team_association_service/__init__.py rename to examples/ad_manager/v202202/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v202105/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202202/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v202105/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202202/user_team_association_service/create_user_team_associations.py index 90567cc6..36f4788b 100755 --- a/examples/ad_manager/v202105/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202202/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202105') + 'UserTeamAssociationService', version='v202202') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v202105/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202202/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v202105/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202202/user_team_association_service/delete_user_team_associations.py index 8972736d..668ec58f 100755 --- a/examples/ad_manager/v202105/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202202/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202105') + 'UserTeamAssociationService', version='v202202') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202105/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202202/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v202105/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202202/user_team_association_service/get_all_user_team_associations.py index d7f6f135..3614a0a6 100755 --- a/examples/ad_manager/v202105/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202202/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202105') + 'UserTeamAssociationService', version='v202202') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v202105') + statement = ad_manager.StatementBuilder(version='v202202') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v202105/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202202/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v202105/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202202/user_team_association_service/get_user_team_associations_for_user.py index f67e1264..ac84f634 100755 --- a/examples/ad_manager/v202105/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202202/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202105') + 'UserTeamAssociationService', version='v202202') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202105/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202202/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v202105/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202202/user_team_association_service/update_user_team_associations.py index 296dfb6a..31266fe6 100755 --- a/examples/ad_manager/v202105/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202202/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202105') + 'UserTeamAssociationService', version='v202202') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202105') + statement = (ad_manager.StatementBuilder(version='v202202') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 6af467c9..e503bbf3 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,24 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v202102': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', - 'ContactService', 'ContentBundleService', 'ContentService', - 'CreativeReviewService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'SiteService', 'StreamActivityMonitorService', - 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', - 'UserService', 'UserTeamAssociationService'), 'v202105': ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', @@ -116,6 +98,24 @@ 'SiteService', 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService'), + 'v202202': + ('ActivityGroupService', 'ActivityService', 'AdjustmentService', + 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', + 'CmsMetadataService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentService', 'CreativeReviewService', + 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', + 'CreativeWrapperService', 'CustomFieldService', + 'CustomTargetingService', 'DaiAuthenticationKeyService', + 'DaiEncodingProfileService', 'ForecastService', 'InventoryService', + 'LabelService', 'LineItemCreativeAssociationService', + 'LineItemService', 'LineItemTemplateService', + 'LiveStreamEventService', 'MobileApplicationService', + 'NativeStyleService', 'NetworkService', 'OrderService', + 'PlacementService', 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'ReportService', 'SiteService', + 'StreamActivityMonitorService', 'SuggestedAdUnitService', + 'TeamService', 'TargetingPresetService', 'UserService', + 'UserTeamAssociationService', 'YieldGroupService'), } diff --git a/googleads/common.py b/googleads/common.py index 90ea0931..9b3852fe 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -54,7 +54,7 @@ 'order to benefit from important security improvements and ensure ' 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '30.0.0' +VERSION = '31.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/setup.py b/setup.py index 0038f1d9..ddccd6a8 100755 --- a/setup.py +++ b/setup.py @@ -35,7 +35,7 @@ CLASSIFIERS = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', - 'Programming Language :: Python :: 3.6' + 'Programming Language :: Python :: 3.7' ] @@ -69,7 +69,7 @@ def GetVersion(): Supported Python Versions ========================= -This library is supported for Python 3.6+. +This library is supported for Python 3.7+. Installation ============ diff --git a/tests/common_test.py b/tests/common_test.py index 5577a2c2..7e12a740 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202111' +CURRENT_VERSION = 'v202202' class CommonTest(testing.CleanUtilityRegistryTestCase): From 09bbcb01f9443f1d140efd8f2d27ef0e4aa74d20 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Mon, 28 Feb 2022 16:41:56 -0500 Subject: [PATCH 176/180] Commiting latest changes. From 0ce9b5e1a8bc646f69f66a3f58dac0a8712c3b6b Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 17 May 2022 19:33:36 +0000 Subject: [PATCH 177/180] Ad Manager v202205 release. --- ChangeLog | 5 + .../report_service/run_ad_exchange_report.py | 66 -------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 2 +- .../create_traffic_forecast_segments.py | 4 +- .../get_all_forecast_adjustments.py | 4 +- .../get_all_traffic_forecast_segments.py | 4 +- ...djustments_for_traffic_forecast_segment.py | 4 +- .../update_forecast_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../get_recently_modified_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../create_video_creatives.py | 66 ++++++++ .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../forecast_service/get_traffic_data.py | 4 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../push_creative_to_devices.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- ...et_default_third_party_data_declaration.py | 6 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 3 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 6 +- .../report_service/run_reach_report.py | 2 +- ...un_reach_report_with_ad_unit_dimensions.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../site_service/create_sites.py | 4 +- .../site_service/get_all_sites.py | 4 +- .../get_sites_requiring_approval.py | 4 +- .../site_service/submit_sites_for_approval.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 144 +++++++++--------- googleads/common.py | 2 +- tests/common_test.py | 2 +- 204 files changed, 451 insertions(+), 447 deletions(-) delete mode 100755 examples/ad_manager/v202108/report_service/run_ad_exchange_report.py rename examples/ad_manager/{v202108 => v202205}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v202108 => v202205}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v202108 => v202205}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v202108 => v202205}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v202108 => v202205}/activity_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v202108 => v202205}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v202108 => v202205}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v202108 => v202205}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v202108 => v202205}/adjustment_service/create_forecast_adjustments.py (99%) rename examples/ad_manager/{v202108 => v202205}/adjustment_service/create_traffic_forecast_segments.py (98%) rename examples/ad_manager/{v202108 => v202205}/adjustment_service/get_all_forecast_adjustments.py (95%) rename examples/ad_manager/{v202108 => v202205}/adjustment_service/get_all_traffic_forecast_segments.py (95%) rename examples/ad_manager/{v202108 => v202205}/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py (96%) rename examples/ad_manager/{v202108 => v202205}/adjustment_service/update_forecast_adjustments.py (96%) rename examples/ad_manager/{v202108 => v202205}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v202108 => v202205}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v202108 => v202205}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v202108 => v202205}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v202108 => v202205}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v202108 => v202205}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v202108 => v202205}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v202108 => v202205}/cms_metadata_service/activate_cms_metadata_values.py (95%) rename examples/ad_manager/{v202108 => v202205}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v202108 => v202205}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v202108 => v202205}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v202108 => v202205}/company_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/company_service/create_companies.py (99%) rename examples/ad_manager/{v202108 => v202205}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v202108 => v202205}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v202108 => v202205}/company_service/update_companies.py (96%) rename examples/ad_manager/{v202108 => v202205}/contact_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v202108 => v202205}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v202108 => v202205}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v202108 => v202205}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v202108 => v202205}/content_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/content_service/get_all_content.py (96%) rename examples/ad_manager/{v202108 => v202205}/content_service/get_recently_modified_content.py (97%) rename examples/ad_manager/{v202108 => v202205}/creative_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v202108 => v202205}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v202108 => v202205}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v202108 => v202205}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v202108 => v202205}/creative_service/create_native_creative.py (99%) create mode 100755 examples/ad_manager/v202205/creative_service/create_video_creatives.py rename examples/ad_manager/{v202108 => v202205}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v202108 => v202205}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v202108 => v202205}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v202108 => v202205}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v202108 => v202205}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v202108 => v202205}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v202108 => v202205}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v202108 => v202205}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v202108 => v202205}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v202108 => v202205}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v202108 => v202205}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v202108 => v202205}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v202108 => v202205}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v202108 => v202205}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v202108 => v202205}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v202108 => v202205}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v202108 => v202205}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v202108 => v202205}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v202108 => v202205}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v202108 => v202205}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v202108 => v202205}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v202108 => v202205}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v202108 => v202205}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v202108 => v202205}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202108 => v202205}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v202108 => v202205}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202108 => v202205}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202108 => v202205}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202108 => v202205}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v202108 => v202205}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v202108 => v202205}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v202108 => v202205}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v202108 => v202205}/forecast_service/get_traffic_data.py (99%) rename examples/ad_manager/{v202108 => v202205}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v202108 => v202205}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v202108 => v202205}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v202108 => v202205}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v202108 => v202205}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v202108 => v202205}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v202108 => v202205}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v202108 => v202205}/label_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/label_service/create_labels.py (99%) rename examples/ad_manager/{v202108 => v202205}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v202108 => v202205}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v202108 => v202205}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v202108 => v202205}/label_service/update_labels.py (96%) rename examples/ad_manager/{v202108 => v202205}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v202108 => v202205}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v202108 => v202205}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v202108 => v202205}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v202108 => v202205}/line_item_creative_association_service/push_creative_to_devices.py (94%) rename examples/ad_manager/{v202108 => v202205}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v202108 => v202205}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v202108 => v202205}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v202108 => v202205}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v202108 => v202205}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v202108 => v202205}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v202108 => v202205}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v202108 => v202205}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v202108 => v202205}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v202108 => v202205}/network_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v202108 => v202205}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v202108 => v202205}/network_service/get_default_third_party_data_declaration.py (95%) rename examples/ad_manager/{v202108 => v202205}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v202108 => v202205}/order_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v202108 => v202205}/order_service/create_orders.py (99%) rename examples/ad_manager/{v202108 => v202205}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v202108 => v202205}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v202108 => v202205}/order_service/update_orders.py (97%) rename examples/ad_manager/{v202108 => v202205}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v202108 => v202205}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v202108 => v202205}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v202108 => v202205}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v202108 => v202205}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v202108 => v202205}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v202108 => v202205}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v202108 => v202205}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v202108 => v202205}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v202108 => v202205}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v202108 => v202205}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/proposal_service/create_proposals.py (98%) rename examples/ad_manager/{v202108 => v202205}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v202108 => v202205}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v202108 => v202205}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v202108 => v202205}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v202108 => v202205}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v202108 => v202205}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v202108 => v202205}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v202108 => v202205}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v202108 => v202205}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v202108 => v202205}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v202108 => v202205}/publisher_query_language_service/get_mcm_earnings.py (97%) rename examples/ad_manager/{v202108 => v202205}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v202108 => v202205}/report_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v202108 => v202205}/report_service/run_inventory_report.py (91%) rename examples/ad_manager/{v202108 => v202205}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v202108 => v202205}/report_service/run_reach_report_with_ad_unit_dimensions.py (97%) rename examples/ad_manager/{v202108 => v202205}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v202108 => v202205}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v202108 => v202205}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v202108 => v202205}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v202108 => v202205}/site_service/create_sites.py (96%) rename examples/ad_manager/{v202108 => v202205}/site_service/get_all_sites.py (92%) rename examples/ad_manager/{v202108 => v202205}/site_service/get_sites_requiring_approval.py (92%) rename examples/ad_manager/{v202108 => v202205}/site_service/submit_sites_for_approval.py (91%) rename examples/ad_manager/{v202108 => v202205}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v202108 => v202205}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v202108 => v202205}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v202108 => v202205}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/targeting_preset_service/get_all_targeting_presets.py (94%) rename examples/ad_manager/{v202108 => v202205}/team_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/team_service/create_teams.py (96%) rename examples/ad_manager/{v202108 => v202205}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v202108 => v202205}/team_service/update_teams.py (94%) rename examples/ad_manager/{v202108 => v202205}/user_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/user_service/create_users.py (96%) rename examples/ad_manager/{v202108 => v202205}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v202108 => v202205}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v202108 => v202205}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v202108 => v202205}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v202108 => v202205}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v202108 => v202205}/user_service/update_users.py (92%) rename examples/ad_manager/{v202108 => v202205}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v202108 => v202205}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v202108 => v202205}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v202108 => v202205}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v202108 => v202205}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v202108 => v202205}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index 6c0c0d54..e232be48 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +32.0.0 -- 05/17/2022 +* Added support for Ad Manager v202205. +* Removed support for Ad Manager v202105. +* Removed examples for Ad Manager v202108. + 31.0.0 -- 02/16/2022 * The minimum supported version of Python is now 3.7.0. * Added support for Ad Manager v202202. diff --git a/examples/ad_manager/v202108/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202108/report_service/run_ad_exchange_report.py deleted file mode 100755 index 56b8b726..00000000 --- a/examples/ad_manager/v202108/report_service/run_ad_exchange_report.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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. - -"""Runs a report on Ad Exchange data via the Ad Manager API.""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - - -def main(client): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'], - 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS', - 'AD_EXCHANGE_ESTIMATED_REVENUE'], - 'dateRangeType': 'LAST_WEEK', - 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time - 'adxReportCurrency': 'EUR' - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError as e: - print('Failed to generate report. Error was: %s' % e) - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print('Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name)) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v202108/activity_group_service/__init__.py b/examples/ad_manager/v202205/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/activity_group_service/__init__.py rename to examples/ad_manager/v202205/activity_group_service/__init__.py diff --git a/examples/ad_manager/v202108/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202205/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v202108/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202205/activity_group_service/create_activity_groups.py index ee43c4fa..f5e08b60 100755 --- a/examples/ad_manager/v202108/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202205/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202108') + version='v202205') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v202108/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202205/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v202108/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202205/activity_group_service/get_active_activity_groups.py index 966b448a..0705f70f 100755 --- a/examples/ad_manager/v202108/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202205/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202108') + 'ActivityGroupService', version='v202205') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202108/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202205/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v202108/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202205/activity_group_service/get_all_activity_groups.py index f7ad34c2..6a033e12 100755 --- a/examples/ad_manager/v202108/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202205/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202108') + 'ActivityGroupService', version='v202205') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v202108/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202205/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v202108/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202205/activity_group_service/update_activity_groups.py index 52359931..2683f535 100755 --- a/examples/ad_manager/v202108/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202205/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202108') + version='v202205') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/activity_service/__init__.py b/examples/ad_manager/v202205/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/activity_service/__init__.py rename to examples/ad_manager/v202205/activity_service/__init__.py diff --git a/examples/ad_manager/v202108/activity_service/create_activities.py b/examples/ad_manager/v202205/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v202108/activity_service/create_activities.py rename to examples/ad_manager/v202205/activity_service/create_activities.py index 87a6082b..f2eb54e5 100755 --- a/examples/ad_manager/v202108/activity_service/create_activities.py +++ b/examples/ad_manager/v202205/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202108') + activity_service = client.GetService('ActivityService', version='v202205') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v202108/activity_service/get_active_activities.py b/examples/ad_manager/v202205/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v202108/activity_service/get_active_activities.py rename to examples/ad_manager/v202205/activity_service/get_active_activities.py index 0ee631ed..2f02a758 100755 --- a/examples/ad_manager/v202108/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202205/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202108') + activity_service = client.GetService('ActivityService', version='v202205') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202108/activity_service/get_all_activities.py b/examples/ad_manager/v202205/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v202108/activity_service/get_all_activities.py rename to examples/ad_manager/v202205/activity_service/get_all_activities.py index 8ff851e3..36135425 100755 --- a/examples/ad_manager/v202108/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202205/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202108') + activity_service = client.GetService('ActivityService', version='v202205') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v202108/activity_service/update_activities.py b/examples/ad_manager/v202205/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v202108/activity_service/update_activities.py rename to examples/ad_manager/v202205/activity_service/update_activities.py index d7d988d3..f4a74f44 100755 --- a/examples/ad_manager/v202108/activity_service/update_activities.py +++ b/examples/ad_manager/v202205/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202108') + activity_service = client.GetService('ActivityService', version='v202205') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202205/adjustment_service/create_forecast_adjustments.py similarity index 99% rename from examples/ad_manager/v202108/adjustment_service/create_forecast_adjustments.py rename to examples/ad_manager/v202205/adjustment_service/create_forecast_adjustments.py index 2df2a20c..49d7faf0 100755 --- a/examples/ad_manager/v202108/adjustment_service/create_forecast_adjustments.py +++ b/examples/ad_manager/v202205/adjustment_service/create_forecast_adjustments.py @@ -27,7 +27,7 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202108') + adjustment_service = client.GetService('AdjustmentService', version='v202205') # Create a new forecast adjustment for New Year's Day traffic. this_new_years = datetime.date(datetime.date.today().year, 1, 1) diff --git a/examples/ad_manager/v202108/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202205/adjustment_service/create_traffic_forecast_segments.py similarity index 98% rename from examples/ad_manager/v202108/adjustment_service/create_traffic_forecast_segments.py rename to examples/ad_manager/v202205/adjustment_service/create_traffic_forecast_segments.py index 9d8483ba..e5d96d95 100755 --- a/examples/ad_manager/v202108/adjustment_service/create_traffic_forecast_segments.py +++ b/examples/ad_manager/v202205/adjustment_service/create_traffic_forecast_segments.py @@ -25,8 +25,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v202108') - network_service = client.GetService('NetworkService', version='v202108') + adjustment_service = client.GetService('AdjustmentService', version='v202205') + network_service = client.GetService('NetworkService', version='v202205') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202108/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202205/adjustment_service/get_all_forecast_adjustments.py similarity index 95% rename from examples/ad_manager/v202108/adjustment_service/get_all_forecast_adjustments.py rename to examples/ad_manager/v202205/adjustment_service/get_all_forecast_adjustments.py index aa488844..f2b0d001 100755 --- a/examples/ad_manager/v202108/adjustment_service/get_all_forecast_adjustments.py +++ b/examples/ad_manager/v202205/adjustment_service/get_all_forecast_adjustments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202108') + adjustment_service = client.GetService('AdjustmentService', version='v202205') # Create a statement to get all forecast adjustments. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small number of forecast adjustments at a time, paging # through until all forecast adjustments have been retrieved. diff --git a/examples/ad_manager/v202108/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202205/adjustment_service/get_all_traffic_forecast_segments.py similarity index 95% rename from examples/ad_manager/v202108/adjustment_service/get_all_traffic_forecast_segments.py rename to examples/ad_manager/v202205/adjustment_service/get_all_traffic_forecast_segments.py index 36fe9067..6f9952e0 100755 --- a/examples/ad_manager/v202108/adjustment_service/get_all_traffic_forecast_segments.py +++ b/examples/ad_manager/v202205/adjustment_service/get_all_traffic_forecast_segments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202108') + adjustment_service = client.GetService('AdjustmentService', version='v202205') # Create a statement to get all traffic forecast segments. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small number of segments at a time, paging through until all # segments have been retrieved. diff --git a/examples/ad_manager/v202108/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202205/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py similarity index 96% rename from examples/ad_manager/v202108/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py rename to examples/ad_manager/v202205/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py index ba34e576..178666e2 100755 --- a/examples/ad_manager/v202108/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py +++ b/examples/ad_manager/v202205/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -24,11 +24,11 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202108') + adjustment_service = client.GetService('AdjustmentService', version='v202205') # Create a statement to get forecast adjustments for a given traffic forecast # segment id. - statement = ad_manager.StatementBuilder(version='v202108').Where( + statement = ad_manager.StatementBuilder(version='v202205').Where( 'trafficForecastSegmentId = :segmentId').WithBindVariable( 'segmentId', traffic_forecast_segment_id) diff --git a/examples/ad_manager/v202108/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202205/adjustment_service/update_forecast_adjustments.py similarity index 96% rename from examples/ad_manager/v202108/adjustment_service/update_forecast_adjustments.py rename to examples/ad_manager/v202205/adjustment_service/update_forecast_adjustments.py index 07bf813c..b50b2957 100755 --- a/examples/ad_manager/v202108/adjustment_service/update_forecast_adjustments.py +++ b/examples/ad_manager/v202205/adjustment_service/update_forecast_adjustments.py @@ -24,12 +24,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202108') + adjustment_service = client.GetService('AdjustmentService', version='v202205') # Create a statement to select a single forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v202108').Where('id = :id').WithBindVariable( + version='v202205').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast adjustment. diff --git a/examples/ad_manager/v202108/audience_segment_service/__init__.py b/examples/ad_manager/v202205/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/audience_segment_service/__init__.py rename to examples/ad_manager/v202205/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v202108/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v202108/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202205/audience_segment_service/create_audience_segments.py index 8e8fd84b..fdaa687d 100755 --- a/examples/ad_manager/v202108/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202205/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202108') - network_service = client.GetService('NetworkService', version='v202108') + 'AudienceSegmentService', version='v202205') + network_service = client.GetService('NetworkService', version='v202205') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v202108/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v202108/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202205/audience_segment_service/get_all_audience_segments.py index 850f9081..2e86bb89 100755 --- a/examples/ad_manager/v202108/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202205/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202108') + 'AudienceSegmentService', version='v202205') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v202108/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v202108/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202205/audience_segment_service/get_first_party_audience_segments.py index 18b8a912..64c42a37 100755 --- a/examples/ad_manager/v202108/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202205/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202108') + 'AudienceSegmentService', version='v202205') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v202108/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v202108/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202205/audience_segment_service/populate_first_party_audience_segments.py index 875f620e..9621b62b 100755 --- a/examples/ad_manager/v202108/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202205/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202108') + 'AudienceSegmentService', version='v202205') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202108/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202205/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v202108/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202205/audience_segment_service/update_audience_segments.py index bbb7c11a..e704f5ea 100755 --- a/examples/ad_manager/v202108/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202205/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202108') + 'AudienceSegmentService', version='v202205') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202108/cdn_configuration_service/__init__.py b/examples/ad_manager/v202205/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202205/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v202108/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202205/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v202108/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202205/cdn_configuration_service/create_cdn_configurations.py index 2c9a1d18..5fbd535b 100755 --- a/examples/ad_manager/v202108/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202205/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202108') + version='v202205') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v202108/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202205/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v202108/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202205/cdn_configuration_service/get_all_cdn_configurations.py index b5227e9a..cfa1d576 100755 --- a/examples/ad_manager/v202108/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202205/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202108') + version='v202205') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202108/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202205/cms_metadata_service/activate_cms_metadata_values.py similarity index 95% rename from examples/ad_manager/v202108/cms_metadata_service/activate_cms_metadata_values.py rename to examples/ad_manager/v202205/cms_metadata_service/activate_cms_metadata_values.py index 8dd4256c..53742fe1 100755 --- a/examples/ad_manager/v202108/cms_metadata_service/activate_cms_metadata_values.py +++ b/examples/ad_manager/v202205/cms_metadata_service/activate_cms_metadata_values.py @@ -28,10 +28,10 @@ def main(client, cms_metadata_key_id): # Initialize appropriate service. cms_metadata_service = client.GetService('CmsMetadataService', - version='v202108') + version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('cmsKeyId = :cmsKeyId AND status = :status') .WithBindVariable('status', 'INACTIVE') .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) diff --git a/examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_keys.py index dd37dc46..6b590392 100755 --- a/examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202108') + 'CmsMetadataService', version='v202205') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_values.py index 4397e1f1..902ad645 100755 --- a/examples/ad_manager/v202108/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202205/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202108') + 'CmsMetadataService', version='v202205') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v202108/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202205/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v202108/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202205/cms_metadata_service/get_cms_metadata_values_for_key.py index c6273539..d265c5c2 100755 --- a/examples/ad_manager/v202108/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202205/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202108') + 'CmsMetadataService', version='v202205') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v202108').Where( + ad_manager.StatementBuilder(version='v202205').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v202108/company_service/__init__.py b/examples/ad_manager/v202205/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/company_service/__init__.py rename to examples/ad_manager/v202205/company_service/__init__.py diff --git a/examples/ad_manager/v202108/company_service/create_companies.py b/examples/ad_manager/v202205/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v202108/company_service/create_companies.py rename to examples/ad_manager/v202205/company_service/create_companies.py index 9624b4a0..33cb1132 100755 --- a/examples/ad_manager/v202108/company_service/create_companies.py +++ b/examples/ad_manager/v202205/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202108') + company_service = client.GetService('CompanyService', version='v202205') # Create company objects. companies = [ diff --git a/examples/ad_manager/v202108/company_service/get_advertisers.py b/examples/ad_manager/v202205/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v202108/company_service/get_advertisers.py rename to examples/ad_manager/v202205/company_service/get_advertisers.py index 40f48790..1e65c638 100755 --- a/examples/ad_manager/v202108/company_service/get_advertisers.py +++ b/examples/ad_manager/v202205/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202108') + company_service = client.GetService('CompanyService', version='v202205') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v202108/company_service/get_all_companies.py b/examples/ad_manager/v202205/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v202108/company_service/get_all_companies.py rename to examples/ad_manager/v202205/company_service/get_all_companies.py index 7d315725..bc0a5c9c 100755 --- a/examples/ad_manager/v202108/company_service/get_all_companies.py +++ b/examples/ad_manager/v202205/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202108') + company_service = client.GetService('CompanyService', version='v202205') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v202108/company_service/update_companies.py b/examples/ad_manager/v202205/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v202108/company_service/update_companies.py rename to examples/ad_manager/v202205/company_service/update_companies.py index cf206964..4854ad2f 100755 --- a/examples/ad_manager/v202108/company_service/update_companies.py +++ b/examples/ad_manager/v202205/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202108') + company_service = client.GetService('CompanyService', version='v202205') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/contact_service/__init__.py b/examples/ad_manager/v202205/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/contact_service/__init__.py rename to examples/ad_manager/v202205/contact_service/__init__.py diff --git a/examples/ad_manager/v202108/contact_service/create_contacts.py b/examples/ad_manager/v202205/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v202108/contact_service/create_contacts.py rename to examples/ad_manager/v202205/contact_service/create_contacts.py index 02ffed16..c01935a5 100755 --- a/examples/ad_manager/v202108/contact_service/create_contacts.py +++ b/examples/ad_manager/v202205/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202108') + contact_service = client.GetService('ContactService', version='v202205') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v202108/contact_service/get_all_contacts.py b/examples/ad_manager/v202205/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v202108/contact_service/get_all_contacts.py rename to examples/ad_manager/v202205/contact_service/get_all_contacts.py index 6e304990..05c1a277 100755 --- a/examples/ad_manager/v202108/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202205/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202108') + contact_service = client.GetService('ContactService', version='v202205') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v202108/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202205/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v202108/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202205/contact_service/get_uninvited_contacts.py index d9c10139..3e338d4b 100755 --- a/examples/ad_manager/v202108/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202205/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202108') + contact_service = client.GetService('ContactService', version='v202205') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v202108/contact_service/update_contacts.py b/examples/ad_manager/v202205/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v202108/contact_service/update_contacts.py rename to examples/ad_manager/v202205/contact_service/update_contacts.py index 7ffcf45b..8c1ecacf 100755 --- a/examples/ad_manager/v202108/contact_service/update_contacts.py +++ b/examples/ad_manager/v202205/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202108') + contact_service = client.GetService('ContactService', version='v202205') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/content_service/__init__.py b/examples/ad_manager/v202205/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/content_service/__init__.py rename to examples/ad_manager/v202205/content_service/__init__.py diff --git a/examples/ad_manager/v202108/content_service/get_all_content.py b/examples/ad_manager/v202205/content_service/get_all_content.py similarity index 96% rename from examples/ad_manager/v202108/content_service/get_all_content.py rename to examples/ad_manager/v202205/content_service/get_all_content.py index 2b539b74..884179e8 100755 --- a/examples/ad_manager/v202108/content_service/get_all_content.py +++ b/examples/ad_manager/v202205/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202108') + content_service = client.GetService('ContentService', version='v202205') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v202108/content_service/get_recently_modified_content.py b/examples/ad_manager/v202205/content_service/get_recently_modified_content.py similarity index 97% rename from examples/ad_manager/v202108/content_service/get_recently_modified_content.py rename to examples/ad_manager/v202205/content_service/get_recently_modified_content.py index bb70e513..6a429395 100755 --- a/examples/ad_manager/v202108/content_service/get_recently_modified_content.py +++ b/examples/ad_manager/v202205/content_service/get_recently_modified_content.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202108') + content_service = client.GetService('ContentService', version='v202205') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -35,7 +35,7 @@ def main(client): # lastModifiedDateTime. Changes to content bundle associations will update # the lastModifiedDateTime, but CMS metadata changes may not change the # lastModifiedDateTime. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202108/creative_service/__init__.py b/examples/ad_manager/v202205/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/creative_service/__init__.py rename to examples/ad_manager/v202205/creative_service/__init__.py diff --git a/examples/ad_manager/v202108/creative_service/copy_image_creatives.py b/examples/ad_manager/v202205/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v202108/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202205/creative_service/copy_image_creatives.py index b9d11052..cf627ba0 100755 --- a/examples/ad_manager/v202108/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202205/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202108') + creative_service = client.GetService('CreativeService', version='v202205') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v202108/creative_service/create_creative_from_template.py b/examples/ad_manager/v202205/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v202108/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202205/creative_service/create_creative_from_template.py index 1ae38ee8..fe5146f4 100755 --- a/examples/ad_manager/v202108/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202205/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202108') + creative_service = client.GetService('CreativeService', version='v202205') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v202108/creative_service/create_creatives.py b/examples/ad_manager/v202205/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v202108/creative_service/create_creatives.py rename to examples/ad_manager/v202205/creative_service/create_creatives.py index 8705f1bb..184b4611 100755 --- a/examples/ad_manager/v202108/creative_service/create_creatives.py +++ b/examples/ad_manager/v202205/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202108') + creative_service = client.GetService('CreativeService', version='v202205') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v202108/creative_service/create_custom_creative.py b/examples/ad_manager/v202205/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v202108/creative_service/create_custom_creative.py rename to examples/ad_manager/v202205/creative_service/create_custom_creative.py index b86a76ff..7a6161dc 100755 --- a/examples/ad_manager/v202108/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202205/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202108') + creative_service = client.GetService('CreativeService', version='v202205') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v202108/creative_service/create_native_creative.py b/examples/ad_manager/v202205/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v202108/creative_service/create_native_creative.py rename to examples/ad_manager/v202205/creative_service/create_native_creative.py index b34d2759..ff65cb25 100755 --- a/examples/ad_manager/v202108/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202205/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202108') + creative_service = client.GetService('CreativeService', version='v202205') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v202205/creative_service/create_video_creatives.py b/examples/ad_manager/v202205/creative_service/create_video_creatives.py new file mode 100755 index 00000000..4718f45e --- /dev/null +++ b/examples/ad_manager/v202205/creative_service/create_video_creatives.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates a new video creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. +To determine which creatives already exist, run get_all_creatives.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v202205') + + # Create a video creative. + creative = { + 'xsi_type': 'VideoCreative', + 'name': 'Video Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '640', 'height': '360', 'isAspectRatio': False}, + 'destinationUrl': 'https://google.com', + 'duration': '115000', + 'videoSourceUrl': ( + 'https://storage.googleapis.com/interactive-media-ads/media/' + 'android.mp4') + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print('Video creative with id "%s" and name "%s" was created and can be ' + 'previewed at:\n%s.' + % (creative['id'], creative['name'], creative['vastPreviewUrl'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v202108/creative_service/get_all_creatives.py b/examples/ad_manager/v202205/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v202108/creative_service/get_all_creatives.py rename to examples/ad_manager/v202205/creative_service/get_all_creatives.py index 7e1b3c27..fa1ba2d2 100755 --- a/examples/ad_manager/v202108/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202205/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202108') + creative_service = client.GetService('CreativeService', version='v202205') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v202108/creative_service/get_image_creatives.py b/examples/ad_manager/v202205/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v202108/creative_service/get_image_creatives.py rename to examples/ad_manager/v202205/creative_service/get_image_creatives.py index 6b9f4c46..7c85bfef 100755 --- a/examples/ad_manager/v202108/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202205/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202108') + creative_service = client.GetService('CreativeService', version='v202205') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v202108/creative_service/update_creatives.py b/examples/ad_manager/v202205/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v202108/creative_service/update_creatives.py rename to examples/ad_manager/v202205/creative_service/update_creatives.py index 7fbd3fb9..8284c6ac 100755 --- a/examples/ad_manager/v202108/creative_service/update_creatives.py +++ b/examples/ad_manager/v202205/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202108') + creative_service = client.GetService('CreativeService', version='v202205') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v202108/creative_set_service/__init__.py b/examples/ad_manager/v202205/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/creative_set_service/__init__.py rename to examples/ad_manager/v202205/creative_set_service/__init__.py diff --git a/examples/ad_manager/v202108/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202205/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v202108/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202205/creative_set_service/associate_creative_set_to_line_item.py index c442981e..cdac941e 100755 --- a/examples/ad_manager/v202108/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202205/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202108') + 'LineItemCreativeAssociationService', version='v202205') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v202108/creative_set_service/create_creative_set.py b/examples/ad_manager/v202205/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v202108/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202205/creative_set_service/create_creative_set.py index 7b7b7f16..98965200 100755 --- a/examples/ad_manager/v202108/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202205/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202108') + version='v202205') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v202108/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202205/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v202108/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202205/creative_set_service/get_all_creative_sets.py index 4a93a93f..b190ab5b 100755 --- a/examples/ad_manager/v202108/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202205/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202108') + 'CreativeSetService', version='v202205') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v202108/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202205/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v202108/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202205/creative_set_service/get_creative_sets_for_master_creative.py index 1f9ee595..7a7d42fe 100755 --- a/examples/ad_manager/v202108/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202205/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202108') + 'CreativeSetService', version='v202205') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v202108/creative_set_service/update_creative_set.py b/examples/ad_manager/v202205/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v202108/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202205/creative_set_service/update_creative_set.py index f55c9d9e..20a8728d 100755 --- a/examples/ad_manager/v202108/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202205/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202108') + version='v202205') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v202108/creative_template_service/__init__.py b/examples/ad_manager/v202205/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/creative_template_service/__init__.py rename to examples/ad_manager/v202205/creative_template_service/__init__.py diff --git a/examples/ad_manager/v202108/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202205/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v202108/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202205/creative_template_service/get_all_creative_templates.py index c832af2e..f1f4eb82 100755 --- a/examples/ad_manager/v202108/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202205/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202108') + 'CreativeTemplateService', version='v202205') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v202108/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202205/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v202108/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202205/creative_template_service/get_system_defined_creative_templates.py index 8fd72927..8ec43452 100755 --- a/examples/ad_manager/v202108/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202205/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202108') + 'CreativeTemplateService', version='v202205') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v202108/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202205/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v202108/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202205/creative_wrapper_service/create_creative_wrappers.py index 84f39883..dca07888 100755 --- a/examples/ad_manager/v202108/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202205/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202108') + version='v202205') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v202108/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202205/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v202108/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202205/creative_wrapper_service/deactivate_creative_wrapper.py index 06b6edfe..c79cab5b 100755 --- a/examples/ad_manager/v202108/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202205/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202108') + version='v202205') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202108/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202205/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202108/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202205/creative_wrapper_service/get_active_creative_wrappers.py index 0587c604..8c8ea32c 100755 --- a/examples/ad_manager/v202108/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202205/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202108') + 'CreativeWrapperService', version='v202205') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202108/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202205/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202108/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202205/creative_wrapper_service/get_all_creative_wrappers.py index 9dc33e68..cec9eab3 100755 --- a/examples/ad_manager/v202108/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202205/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202108') + 'CreativeWrapperService', version='v202205') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v202108/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202205/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v202108/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202205/creative_wrapper_service/update_creative_wrappers.py index edb47640..fec33eb1 100755 --- a/examples/ad_manager/v202108/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202205/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202108') + version='v202205') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v202108/custom_field_service/__init__.py b/examples/ad_manager/v202205/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/custom_field_service/__init__.py rename to examples/ad_manager/v202205/custom_field_service/__init__.py diff --git a/examples/ad_manager/v202108/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202205/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v202108/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202205/custom_field_service/create_custom_field_options.py index 3c554fe7..dfa7f7e7 100755 --- a/examples/ad_manager/v202108/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202205/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202108') + 'CustomFieldService', version='v202205') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v202108/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202205/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v202108/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202205/custom_field_service/create_custom_fields.py index e5695266..5139287d 100755 --- a/examples/ad_manager/v202108/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202205/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202108') + 'CustomFieldService', version='v202205') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v202108/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202205/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v202108/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202205/custom_field_service/deactivate_all_line_item_custom_fields.py index bbebbd48..1d561444 100755 --- a/examples/ad_manager/v202108/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202205/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202108') + 'CustomFieldService', version='v202205') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202108/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202205/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v202108/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202205/custom_field_service/get_all_custom_fields.py index cb684fe5..f94f36d5 100755 --- a/examples/ad_manager/v202108/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202205/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202108') + 'CustomFieldService', version='v202205') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v202108/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202205/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v202108/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202205/custom_field_service/get_custom_fields_for_line_items.py index 30940553..04eb5921 100755 --- a/examples/ad_manager/v202108/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202205/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202108') + 'CustomFieldService', version='v202205') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v202108/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202205/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v202108/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202205/custom_field_service/set_line_item_custom_field_value.py index 8373ce2a..198c8632 100755 --- a/examples/ad_manager/v202108/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202205/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v202108') + 'CustomFieldService', version='v202205') - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v202108') + custom_field_statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v202108') + ad_manager.StatementBuilder(version='v202205') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v202108') + line_item_statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v202108/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202205/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v202108/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202205/custom_field_service/update_custom_fields.py index e5be3666..53ae0f36 100755 --- a/examples/ad_manager/v202108/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202205/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202108') + 'CustomFieldService', version='v202205') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v202108/custom_targeting_service/__init__.py b/examples/ad_manager/v202205/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/custom_targeting_service/__init__.py rename to examples/ad_manager/v202205/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v202108/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202205/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v202108/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202205/custom_targeting_service/create_custom_targeting_keys_and_values.py index 38dab7c1..66ba8312 100755 --- a/examples/ad_manager/v202108/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202205/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202108') + 'CustomTargetingService', version='v202205') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_keys.py index c988fbef..7bc74043 100755 --- a/examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202108') + 'CustomTargetingService', version='v202205') - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v202108') + key_statement = (ad_manager.StatementBuilder(version='v202205') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_values.py index 86e7f371..9728e755 100755 --- a/examples/ad_manager/v202108/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202205/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202108') + 'CustomTargetingService', version='v202205') - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [str(value['id']) for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v202108') + value_statement = (ad_manager.StatementBuilder(version='v202205') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v202108/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202205/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202108/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202205/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index 860f14d2..ec23c3ac 100755 --- a/examples/ad_manager/v202108/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202205/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202108') + 'CustomTargetingService', version='v202205') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v202108') + targeting_key_statement = ad_manager.StatementBuilder(version='v202205') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v202108/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202205/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202108/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202205/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index f526cc46..cf2da216 100755 --- a/examples/ad_manager/v202108/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202205/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202108') + 'CustomTargetingService', version='v202205') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v202108') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202205') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_keys.py index 18af298b..08cd59f5 100755 --- a/examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202108') + 'CustomTargetingService', version='v202205') - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_values.py index 00583339..9eafeb34 100755 --- a/examples/ad_manager/v202108/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202205/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202108') + 'CustomTargetingService', version='v202205') - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v202108/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202205/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v202108/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202205/forecast_service/get_availability_forecast.py index 39b380a9..ae251195 100755 --- a/examples/ad_manager/v202108/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202205/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202108') - network_service = client.GetService('NetworkService', version='v202108') + forecast_service = client.GetService('ForecastService', version='v202205') + network_service = client.GetService('NetworkService', version='v202205') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202108/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202205/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v202108/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202205/forecast_service/get_availability_forecast_for_line_item.py index ec5ca930..41a89401 100755 --- a/examples/ad_manager/v202108/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202205/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202108') + forecast_service = client.GetService('ForecastService', version='v202205') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v202108/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202205/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v202108/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202205/forecast_service/get_delivery_forecast_for_line_items.py index 15a315a8..eb9143aa 100755 --- a/examples/ad_manager/v202108/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202205/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202108') + forecast_service = client.GetService('ForecastService', version='v202205') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v202108/forecast_service/get_traffic_data.py b/examples/ad_manager/v202205/forecast_service/get_traffic_data.py similarity index 99% rename from examples/ad_manager/v202108/forecast_service/get_traffic_data.py rename to examples/ad_manager/v202205/forecast_service/get_traffic_data.py index b49adb19..6c9f7adf 100755 --- a/examples/ad_manager/v202108/forecast_service/get_traffic_data.py +++ b/examples/ad_manager/v202205/forecast_service/get_traffic_data.py @@ -25,8 +25,8 @@ def main(client): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202108') - network_service = client.GetService('NetworkService', version='v202108') + forecast_service = client.GetService('ForecastService', version='v202205') + network_service = client.GetService('NetworkService', version='v202205') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202108/inventory_service/__init__.py b/examples/ad_manager/v202205/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/inventory_service/__init__.py rename to examples/ad_manager/v202205/inventory_service/__init__.py diff --git a/examples/ad_manager/v202108/inventory_service/archive_ad_units.py b/examples/ad_manager/v202205/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v202108/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202205/inventory_service/archive_ad_units.py index 6181c8ba..d5d5650b 100755 --- a/examples/ad_manager/v202108/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202205/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202108') + inventory_service = client.GetService('InventoryService', version='v202205') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v202108/inventory_service/create_ad_units.py b/examples/ad_manager/v202205/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v202108/inventory_service/create_ad_units.py rename to examples/ad_manager/v202205/inventory_service/create_ad_units.py index 76d01663..e90bbf7f 100755 --- a/examples/ad_manager/v202108/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202205/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202108') + inventory_service = client.GetService('InventoryService', version='v202205') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v202108/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202205/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v202108/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202205/inventory_service/get_ad_unit_hierarchy.py index 5d93d8c4..8c705468 100755 --- a/examples/ad_manager/v202108/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202205/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202108') - inventory_service = client.GetService('InventoryService', version='v202108') + network_service = client.GetService('NetworkService', version='v202205') + inventory_service = client.GetService('InventoryService', version='v202205') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v202108/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202205/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v202108/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202205/inventory_service/get_all_ad_unit_sizes.py index f6eb46aa..35682c64 100755 --- a/examples/ad_manager/v202108/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202205/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v202108') + 'InventoryService', version='v202205') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v202108/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202205/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v202108/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202205/inventory_service/get_all_ad_units.py index de232c52..32ba6e99 100755 --- a/examples/ad_manager/v202108/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202205/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v202108') + ad_unit_service = client.GetService('InventoryService', version='v202205') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v202108/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202205/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v202108/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202205/inventory_service/get_top_level_ad_units.py index 215cc3a1..e23f749a 100755 --- a/examples/ad_manager/v202108/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202205/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202108') - inventory_service = client.GetService('InventoryService', version='v202108') + network_service = client.GetService('NetworkService', version='v202205') + inventory_service = client.GetService('InventoryService', version='v202205') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v202108/inventory_service/update_ad_units.py b/examples/ad_manager/v202205/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v202108/inventory_service/update_ad_units.py rename to examples/ad_manager/v202205/inventory_service/update_ad_units.py index f9a0bb74..d3c9ab71 100755 --- a/examples/ad_manager/v202108/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202205/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202108') + inventory_service = client.GetService('InventoryService', version='v202205') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v202108/label_service/__init__.py b/examples/ad_manager/v202205/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/label_service/__init__.py rename to examples/ad_manager/v202205/label_service/__init__.py diff --git a/examples/ad_manager/v202108/label_service/create_labels.py b/examples/ad_manager/v202205/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v202108/label_service/create_labels.py rename to examples/ad_manager/v202205/label_service/create_labels.py index 60ac6a18..df1706e4 100755 --- a/examples/ad_manager/v202108/label_service/create_labels.py +++ b/examples/ad_manager/v202205/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202108') + label_service = client.GetService('LabelService', version='v202205') # Create label objects. labels = [] diff --git a/examples/ad_manager/v202108/label_service/deactivate_labels.py b/examples/ad_manager/v202205/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v202108/label_service/deactivate_labels.py rename to examples/ad_manager/v202205/label_service/deactivate_labels.py index 57bb36ec..ade940c8 100755 --- a/examples/ad_manager/v202108/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202205/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202108') + label_service = client.GetService('LabelService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202108/label_service/get_active_labels.py b/examples/ad_manager/v202205/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v202108/label_service/get_active_labels.py rename to examples/ad_manager/v202205/label_service/get_active_labels.py index 64eafc14..652accd4 100755 --- a/examples/ad_manager/v202108/label_service/get_active_labels.py +++ b/examples/ad_manager/v202205/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202108') + label_service = client.GetService('LabelService', version='v202205') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202108/label_service/get_all_labels.py b/examples/ad_manager/v202205/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v202108/label_service/get_all_labels.py rename to examples/ad_manager/v202205/label_service/get_all_labels.py index 8d3ba500..04245fb6 100755 --- a/examples/ad_manager/v202108/label_service/get_all_labels.py +++ b/examples/ad_manager/v202205/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202108') + label_service = client.GetService('LabelService', version='v202205') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v202108/label_service/update_labels.py b/examples/ad_manager/v202205/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v202108/label_service/update_labels.py rename to examples/ad_manager/v202205/label_service/update_labels.py index 27f6ddbb..074aea23 100755 --- a/examples/ad_manager/v202108/label_service/update_labels.py +++ b/examples/ad_manager/v202205/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202108') + label_service = client.GetService('LabelService', version='v202205') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202108/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202205/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202205/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v202108/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202205/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v202108/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202205/line_item_creative_association_service/create_licas.py index d538033a..1c285f19 100755 --- a/examples/ad_manager/v202108/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202205/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202108') + 'LineItemCreativeAssociationService', version='v202205') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v202108/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202205/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v202108/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202205/line_item_creative_association_service/deactivate_licas.py index 4005c735..a409731a 100755 --- a/examples/ad_manager/v202108/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202205/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202108') + 'LineItemCreativeAssociationService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v202108/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202205/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v202108/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202205/line_item_creative_association_service/get_all_licas.py index 61ad022d..aff39527 100755 --- a/examples/ad_manager/v202108/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202205/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202108') + 'LineItemCreativeAssociationService', version='v202205') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v202108/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202205/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v202108/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202205/line_item_creative_association_service/get_licas_for_line_item.py index b9bb2572..a921f7e4 100755 --- a/examples/ad_manager/v202108/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202205/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202108') + 'LineItemCreativeAssociationService', version='v202205') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v202108/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202205/line_item_creative_association_service/push_creative_to_devices.py similarity index 94% rename from examples/ad_manager/v202108/line_item_creative_association_service/push_creative_to_devices.py rename to examples/ad_manager/v202205/line_item_creative_association_service/push_creative_to_devices.py index 76ac2341..a24aa194 100755 --- a/examples/ad_manager/v202108/line_item_creative_association_service/push_creative_to_devices.py +++ b/examples/ad_manager/v202205/line_item_creative_association_service/push_creative_to_devices.py @@ -34,11 +34,11 @@ def main(client, line_item_id, creative_id, linked_device_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202108') + 'LineItemCreativeAssociationService', version='v202205') # Create query to select a single linked device. # Linked devices can be read from the linked_device PQL table. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :linkedDeviceId') .WithBindVariable('linkedDeviceId', int(linked_device_id))) diff --git a/examples/ad_manager/v202108/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202205/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v202108/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202205/line_item_creative_association_service/update_licas.py index 24ed054e..bbacda7d 100755 --- a/examples/ad_manager/v202108/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202205/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202108') + 'LineItemCreativeAssociationService', version='v202205') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v202108/line_item_service/__init__.py b/examples/ad_manager/v202205/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/line_item_service/__init__.py rename to examples/ad_manager/v202205/line_item_service/__init__.py diff --git a/examples/ad_manager/v202108/line_item_service/activate_line_items.py b/examples/ad_manager/v202205/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v202108/line_item_service/activate_line_items.py rename to examples/ad_manager/v202205/line_item_service/activate_line_items.py index 65237c4b..52274a6f 100755 --- a/examples/ad_manager/v202108/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202205/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202108/line_item_service/create_line_items.py b/examples/ad_manager/v202205/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v202108/line_item_service/create_line_items.py rename to examples/ad_manager/v202205/line_item_service/create_line_items.py index 0296e202..31f990b3 100755 --- a/examples/ad_manager/v202108/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202205/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202108/line_item_service/create_video_line_item.py b/examples/ad_manager/v202205/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v202108/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202205/line_item_service/create_video_line_item.py index c59cc7a3..013902c1 100755 --- a/examples/ad_manager/v202108/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202205/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202108/line_item_service/get_all_line_items.py b/examples/ad_manager/v202205/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v202108/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202205/line_item_service/get_all_line_items.py index 5c782e60..e1585b6c 100755 --- a/examples/ad_manager/v202108/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202205/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v202108/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202205/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v202108/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202205/line_item_service/get_line_items_that_need_creatives.py index 065a1c06..05d98fee 100755 --- a/examples/ad_manager/v202108/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202205/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v202108/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202205/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v202108/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202205/line_item_service/get_recently_updated_line_items.py index c5d8715d..5b08a98a 100755 --- a/examples/ad_manager/v202108/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202205/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202108/line_item_service/pause_line_items.py b/examples/ad_manager/v202205/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v202108/line_item_service/pause_line_items.py rename to examples/ad_manager/v202205/line_item_service/pause_line_items.py index 3877d0b4..ca3afe4c 100755 --- a/examples/ad_manager/v202108/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202205/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v202108/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202205/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v202108/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202205/line_item_service/target_custom_criteria.py index 408875d1..2e66009a 100755 --- a/examples/ad_manager/v202108/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202205/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/line_item_service/update_line_items.py b/examples/ad_manager/v202205/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v202108/line_item_service/update_line_items.py rename to examples/ad_manager/v202205/line_item_service/update_line_items.py index 0a5700a8..416cc94e 100755 --- a/examples/ad_manager/v202108/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202205/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202108') + line_item_service = client.GetService('LineItemService', version='v202205') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v202108/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202205/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202108/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202205/live_stream_event_service/activate_live_stream_events.py index 23468295..e74b1135 100755 --- a/examples/ad_manager/v202108/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202205/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202108') + 'LiveStreamEventService', version='v202205') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v202108/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202205/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v202108/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202205/live_stream_event_service/create_live_stream_events.py index 0b58b427..674206ca 100755 --- a/examples/ad_manager/v202108/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202205/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v202108') + 'LiveStreamEventService', version='v202205') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v202108/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202205/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v202108/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202205/live_stream_event_service/get_all_live_stream_events.py index fbaeda69..878af9de 100755 --- a/examples/ad_manager/v202108/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202205/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202108') + 'LiveStreamEventService', version='v202205') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v202108/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202205/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v202108/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202205/live_stream_event_service/register_sessions_for_monitoring.py index d505e419..0d74bb84 100755 --- a/examples/ad_manager/v202108/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202205/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202108') + 'LiveStreamEventService', version='v202205') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v202108/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202205/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202108/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202205/live_stream_event_service/update_live_stream_events.py index 86df87bf..a4a51d44 100755 --- a/examples/ad_manager/v202108/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202205/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v202108') + 'LiveStreamEventService', version='v202205') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v202108/native_style_service/__init__.py b/examples/ad_manager/v202205/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/native_style_service/__init__.py rename to examples/ad_manager/v202205/native_style_service/__init__.py diff --git a/examples/ad_manager/v202108/native_style_service/create_native_styles.py b/examples/ad_manager/v202205/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v202108/native_style_service/create_native_styles.py rename to examples/ad_manager/v202205/native_style_service/create_native_styles.py index 2c5d913d..970c61a0 100755 --- a/examples/ad_manager/v202108/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202205/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202108') + version='v202205') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v202108/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202205/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v202108/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202205/native_style_service/get_all_native_styles.py index 4bb3a1ee..38a7d719 100755 --- a/examples/ad_manager/v202108/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202205/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202108') + version='v202205') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v202108/network_service/__init__.py b/examples/ad_manager/v202205/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/network_service/__init__.py rename to examples/ad_manager/v202205/network_service/__init__.py diff --git a/examples/ad_manager/v202108/network_service/get_all_networks.py b/examples/ad_manager/v202205/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v202108/network_service/get_all_networks.py rename to examples/ad_manager/v202205/network_service/get_all_networks.py index 63c25a90..3d4821a6 100755 --- a/examples/ad_manager/v202108/network_service/get_all_networks.py +++ b/examples/ad_manager/v202205/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202108') + network_service = client.GetService('NetworkService', version='v202205') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v202108/network_service/get_current_network.py b/examples/ad_manager/v202205/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v202108/network_service/get_current_network.py rename to examples/ad_manager/v202205/network_service/get_current_network.py index 5f950e1f..2ec20444 100755 --- a/examples/ad_manager/v202108/network_service/get_current_network.py +++ b/examples/ad_manager/v202205/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202108') + network_service = client.GetService('NetworkService', version='v202205') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202108/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202205/network_service/get_default_third_party_data_declaration.py similarity index 95% rename from examples/ad_manager/v202108/network_service/get_default_third_party_data_declaration.py rename to examples/ad_manager/v202205/network_service/get_default_third_party_data_declaration.py index 6c4c7589..627896e9 100755 --- a/examples/ad_manager/v202108/network_service/get_default_third_party_data_declaration.py +++ b/examples/ad_manager/v202205/network_service/get_default_third_party_data_declaration.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202108') + network_service = client.GetService('NetworkService', version='v202205') pql_service = client.GetService('PublisherQueryLanguageService', - version='v202108') + version='v202205') # Fetch the default third party data declarations. declarations = network_service.getDefaultThirdPartyDataDeclaration() @@ -44,7 +44,7 @@ def main(client): # In this case, there are third party companies to be displayed, so fetch # the company names from the Rich_Media_Ad_Company PQL table. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Select('Id, Name') .From('Rich_Media_Ad_Company') .Where('Id IN (:company_ids)') diff --git a/examples/ad_manager/v202108/network_service/make_test_network.py b/examples/ad_manager/v202205/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v202108/network_service/make_test_network.py rename to examples/ad_manager/v202205/network_service/make_test_network.py index 0aabbe96..d9ea4ab4 100755 --- a/examples/ad_manager/v202108/network_service/make_test_network.py +++ b/examples/ad_manager/v202205/network_service/make_test_network.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202108') + network_service = client.GetService('NetworkService', version='v202205') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v202108/order_service/__init__.py b/examples/ad_manager/v202205/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/order_service/__init__.py rename to examples/ad_manager/v202205/order_service/__init__.py diff --git a/examples/ad_manager/v202108/order_service/approve_orders.py b/examples/ad_manager/v202205/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v202108/order_service/approve_orders.py rename to examples/ad_manager/v202205/order_service/approve_orders.py index 2a7d0aee..950ce011 100755 --- a/examples/ad_manager/v202108/order_service/approve_orders.py +++ b/examples/ad_manager/v202205/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202108') + order_service = client.GetService('OrderService', version='v202205') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v202108/order_service/create_orders.py b/examples/ad_manager/v202205/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v202108/order_service/create_orders.py rename to examples/ad_manager/v202205/order_service/create_orders.py index 0c012c12..23d30c34 100755 --- a/examples/ad_manager/v202108/order_service/create_orders.py +++ b/examples/ad_manager/v202205/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202108') + order_service = client.GetService('OrderService', version='v202205') # Create order objects. orders = [] diff --git a/examples/ad_manager/v202108/order_service/get_all_orders.py b/examples/ad_manager/v202205/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v202108/order_service/get_all_orders.py rename to examples/ad_manager/v202205/order_service/get_all_orders.py index 2733838f..0051b584 100755 --- a/examples/ad_manager/v202108/order_service/get_all_orders.py +++ b/examples/ad_manager/v202205/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202108') + order_service = client.GetService('OrderService', version='v202205') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v202108/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202205/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v202108/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202205/order_service/get_orders_starting_soon.py index 29e1d716..22825114 100755 --- a/examples/ad_manager/v202108/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202205/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202108') + order_service = client.GetService('OrderService', version='v202205') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v202108/order_service/update_orders.py b/examples/ad_manager/v202205/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v202108/order_service/update_orders.py rename to examples/ad_manager/v202205/order_service/update_orders.py index cce90f29..448d19f2 100755 --- a/examples/ad_manager/v202108/order_service/update_orders.py +++ b/examples/ad_manager/v202205/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202108') + order_service = client.GetService('OrderService', version='v202205') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202108/placement_service/create_placements.py b/examples/ad_manager/v202205/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v202108/placement_service/create_placements.py rename to examples/ad_manager/v202205/placement_service/create_placements.py index c6999bc1..9511270d 100755 --- a/examples/ad_manager/v202108/placement_service/create_placements.py +++ b/examples/ad_manager/v202205/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202108') - inventory_service = client.GetService('InventoryService', version='v202108') + placement_service = client.GetService('PlacementService', version='v202205') + inventory_service = client.GetService('InventoryService', version='v202205') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v202108/placement_service/deactivate_placements.py b/examples/ad_manager/v202205/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v202108/placement_service/deactivate_placements.py rename to examples/ad_manager/v202205/placement_service/deactivate_placements.py index f08b5d9d..a87f587c 100755 --- a/examples/ad_manager/v202108/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202205/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202108') + placement_service = client.GetService('PlacementService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/placement_service/get_active_placements.py b/examples/ad_manager/v202205/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v202108/placement_service/get_active_placements.py rename to examples/ad_manager/v202205/placement_service/get_active_placements.py index d6458549..6fd53640 100755 --- a/examples/ad_manager/v202108/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202205/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202108') + placement_service = client.GetService('PlacementService', version='v202205') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202108/placement_service/get_all_placements.py b/examples/ad_manager/v202205/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v202108/placement_service/get_all_placements.py rename to examples/ad_manager/v202205/placement_service/get_all_placements.py index d6bfe462..ca051f46 100755 --- a/examples/ad_manager/v202108/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202205/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202108') + placement_service = client.GetService('PlacementService', version='v202205') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v202108/placement_service/update_placements.py b/examples/ad_manager/v202205/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v202108/placement_service/update_placements.py rename to examples/ad_manager/v202205/placement_service/update_placements.py index 38bfe3e5..365b31a4 100755 --- a/examples/ad_manager/v202108/placement_service/update_placements.py +++ b/examples/ad_manager/v202205/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202108') + placement_service = client.GetService('PlacementService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v202108/proposal_line_item_service/__init__.py b/examples/ad_manager/v202205/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202205/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v202108/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202205/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202108/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202205/proposal_line_item_service/archive_proposal_line_items.py index 415837d0..b86f7de2 100755 --- a/examples/ad_manager/v202108/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202205/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202108') + 'ProposalLineItemService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202205/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v202108/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202205/proposal_line_item_service/create_proposal_line_items.py index 94437c84..63e6a825 100755 --- a/examples/ad_manager/v202108/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202205/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202108') - network_service = client.GetService('NetworkService', version='v202108') + 'ProposalLineItemService', version='v202205') + network_service = client.GetService('NetworkService', version='v202205') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202108/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202205/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202108/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202205/proposal_line_item_service/get_all_proposal_line_items.py index 02d48882..94a7c9d0 100755 --- a/examples/ad_manager/v202108/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202205/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202108') + 'ProposalLineItemService', version='v202205') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v202108/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202205/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v202108/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202205/proposal_line_item_service/get_proposal_line_items_for_proposal.py index f0be1c3c..9179dbae 100755 --- a/examples/ad_manager/v202108/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202205/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202108') + 'ProposalLineItemService', version='v202205') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v202108/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202205/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202108/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202205/proposal_line_item_service/update_proposal_line_items.py index 1ba0b014..e32ba2e3 100755 --- a/examples/ad_manager/v202108/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202205/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202108') + 'ProposalLineItemService', version='v202205') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/proposal_service/__init__.py b/examples/ad_manager/v202205/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/proposal_service/__init__.py rename to examples/ad_manager/v202205/proposal_service/__init__.py diff --git a/examples/ad_manager/v202108/proposal_service/create_proposals.py b/examples/ad_manager/v202205/proposal_service/create_proposals.py similarity index 98% rename from examples/ad_manager/v202108/proposal_service/create_proposals.py rename to examples/ad_manager/v202205/proposal_service/create_proposals.py index f8f0b1c2..d92cd562 100755 --- a/examples/ad_manager/v202108/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202205/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v202108') + proposal_service = client.GetService('ProposalService', version='v202205') proposal = { # Setting required Marketplace information. @@ -40,7 +40,6 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, 'name': 'Proposal #%s' % uuid.uuid4(), 'primarySalesperson': { 'userId': primary_salesperson_id, - 'split': '100000' }, 'primaryTraffickerId': primary_trafficker_id, 'probabilityOfClose': '100000', diff --git a/examples/ad_manager/v202108/proposal_service/get_all_proposals.py b/examples/ad_manager/v202205/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v202108/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202205/proposal_service/get_all_proposals.py index 251d57de..b2cfc3dc 100755 --- a/examples/ad_manager/v202108/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202205/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202108') + proposal_service = client.GetService('ProposalService', version='v202205') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v202108/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202205/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v202108/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202205/proposal_service/get_marketplace_comments.py index 53030640..3d8a9875 100755 --- a/examples/ad_manager/v202108/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202205/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v202108') + 'ProposalService', version='v202205') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v202108/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202205/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v202108/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202205/proposal_service/get_proposals_awaiting_seller_review.py index a39df2b4..52ee216c 100755 --- a/examples/ad_manager/v202108/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202205/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202108') + proposal_service = client.GetService('ProposalService', version='v202205') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v202108/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202205/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v202108/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202205/proposal_service/request_buyers_acceptance.py index df6fa250..0c30078c 100755 --- a/examples/ad_manager/v202108/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202205/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202108') + proposal_service = client.GetService('ProposalService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v202108/proposal_service/update_proposals.py b/examples/ad_manager/v202205/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v202108/proposal_service/update_proposals.py rename to examples/ad_manager/v202205/proposal_service/update_proposals.py index b4e95e6a..8de73911 100755 --- a/examples/ad_manager/v202108/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202205/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202108') + proposal_service = client.GetService('ProposalService', version='v202205') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/publisher_query_language_service/__init__.py b/examples/ad_manager/v202205/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202205/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v202108/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202205/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v202108/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202205/publisher_query_language_service/fetch_match_tables.py index 36803b61..c60089f0 100755 --- a/examples/ad_manager/v202108/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202205/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202108/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202205/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v202108/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202205/publisher_query_language_service/get_all_browsers.py index 20bfb637..36f74419 100755 --- a/examples/ad_manager/v202108/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202205/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v202108/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202205/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v202108/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202205/publisher_query_language_service/get_all_programmatic_buyers.py index 8f17acfd..c59d0cc5 100755 --- a/examples/ad_manager/v202108/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202205/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202108') + data_downloader = client.GetDataDownloader(version='v202205') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202108/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202205/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v202108/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202205/publisher_query_language_service/get_geo_targets.py index 3215a864..864a8eda 100755 --- a/examples/ad_manager/v202108/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202205/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v202108/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202205/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v202108/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202205/publisher_query_language_service/get_line_items_named_like.py index 22ac8faa..f85af633 100755 --- a/examples/ad_manager/v202108/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202205/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202108/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202205/publisher_query_language_service/get_mcm_earnings.py similarity index 97% rename from examples/ad_manager/v202108/publisher_query_language_service/get_mcm_earnings.py rename to examples/ad_manager/v202205/publisher_query_language_service/get_mcm_earnings.py index 87b07962..aadc556e 100755 --- a/examples/ad_manager/v202108/publisher_query_language_service/get_mcm_earnings.py +++ b/examples/ad_manager/v202205/publisher_query_language_service/get_mcm_earnings.py @@ -26,7 +26,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202108') + data_downloader = client.GetDataDownloader(version='v202205') with tempfile.NamedTemporaryFile( prefix='mcm_earnings_', diff --git a/examples/ad_manager/v202108/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202205/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v202108/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202205/publisher_query_language_service/get_recent_changes.py index 2a7293ec..4391ce81 100755 --- a/examples/ad_manager/v202108/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202205/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v202108') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202205') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v202108/report_service/__init__.py b/examples/ad_manager/v202205/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/report_service/__init__.py rename to examples/ad_manager/v202205/report_service/__init__.py diff --git a/examples/ad_manager/v202108/report_service/run_delivery_report.py b/examples/ad_manager/v202205/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v202108/report_service/run_delivery_report.py rename to examples/ad_manager/v202205/report_service/run_delivery_report.py index 490386e3..d26b22be 100755 --- a/examples/ad_manager/v202108/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202205/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202108/report_service/run_inventory_report.py b/examples/ad_manager/v202205/report_service/run_inventory_report.py similarity index 91% rename from examples/ad_manager/v202108/report_service/run_inventory_report.py rename to examples/ad_manager/v202205/report_service/run_inventory_report.py index 312e401e..1df7149d 100755 --- a/examples/ad_manager/v202108/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202205/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') # Create report job. report_job = { @@ -33,8 +33,8 @@ def main(client): 'dimensions': ['DATE', 'AD_UNIT_NAME'], 'adUnitView': 'HIERARCHICAL', 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS', - 'ADSENSE_LINE_ITEM_LEVEL_CLICKS', + 'AD_EXCHANGE_LINE_ITEM_LEVEL_IMPRESSIONS', + 'AD_EXCHANGE_LINE_ITEM_LEVEL_CLICKS', 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK' diff --git a/examples/ad_manager/v202108/report_service/run_reach_report.py b/examples/ad_manager/v202205/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v202108/report_service/run_reach_report.py rename to examples/ad_manager/v202205/report_service/run_reach_report.py index 4c44d067..dfd5fc3f 100755 --- a/examples/ad_manager/v202108/report_service/run_reach_report.py +++ b/examples/ad_manager/v202205/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') # Create report job. report_job = { diff --git a/examples/ad_manager/v202108/report_service/run_reach_report_with_ad_unit_dimensions.py b/examples/ad_manager/v202205/report_service/run_reach_report_with_ad_unit_dimensions.py similarity index 97% rename from examples/ad_manager/v202108/report_service/run_reach_report_with_ad_unit_dimensions.py rename to examples/ad_manager/v202205/report_service/run_reach_report_with_ad_unit_dimensions.py index 83e49f67..5d5194d6 100755 --- a/examples/ad_manager/v202108/report_service/run_reach_report_with_ad_unit_dimensions.py +++ b/examples/ad_manager/v202205/report_service/run_reach_report_with_ad_unit_dimensions.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') # Create report job. report_job = { diff --git a/examples/ad_manager/v202108/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202205/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v202108/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202205/report_service/run_report_and_create_match_table.py index 7716ab7d..543c2e04 100755 --- a/examples/ad_manager/v202108/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202205/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202108/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202205/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v202108/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202205/report_service/run_report_with_custom_fields.py index 131707fb..45b7aa15 100755 --- a/examples/ad_manager/v202108/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202205/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') # Create report job. report_job = { diff --git a/examples/ad_manager/v202108/report_service/run_sales_report.py b/examples/ad_manager/v202205/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v202108/report_service/run_sales_report.py rename to examples/ad_manager/v202205/report_service/run_sales_report.py index e81be7a5..ed1d1eaa 100755 --- a/examples/ad_manager/v202108/report_service/run_sales_report.py +++ b/examples/ad_manager/v202205/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') # Create report job. report_job = { diff --git a/examples/ad_manager/v202108/report_service/run_saved_query.py b/examples/ad_manager/v202205/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v202108/report_service/run_saved_query.py rename to examples/ad_manager/v202205/report_service/run_saved_query.py index d3dc37a1..ea7bd0dc 100755 --- a/examples/ad_manager/v202108/report_service/run_saved_query.py +++ b/examples/ad_manager/v202205/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v202108') + report_service = client.GetService('ReportService', version='v202205') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202108') + report_downloader = client.GetDataDownloader(version='v202205') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202108/site_service/create_sites.py b/examples/ad_manager/v202205/site_service/create_sites.py similarity index 96% rename from examples/ad_manager/v202108/site_service/create_sites.py rename to examples/ad_manager/v202205/site_service/create_sites.py index 44430195..845a4041 100755 --- a/examples/ad_manager/v202108/site_service/create_sites.py +++ b/examples/ad_manager/v202205/site_service/create_sites.py @@ -27,8 +27,8 @@ def main(client, url, child_network_code): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202108') - site_service = client.GetService('SiteService', version='v202108') + network_service = client.GetService('NetworkService', version='v202205') + site_service = client.GetService('SiteService', version='v202205') # Check that the child network code is approved for MANAGE_INVENTORY by this # network. diff --git a/examples/ad_manager/v202108/site_service/get_all_sites.py b/examples/ad_manager/v202205/site_service/get_all_sites.py similarity index 92% rename from examples/ad_manager/v202108/site_service/get_all_sites.py rename to examples/ad_manager/v202205/site_service/get_all_sites.py index 3e112749..8420c04a 100755 --- a/examples/ad_manager/v202108/site_service/get_all_sites.py +++ b/examples/ad_manager/v202205/site_service/get_all_sites.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202108') + site_service = client.GetService('SiteService', version='v202205') # Create a statement to select Sites. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small number of sites at a time, paging through until all sites # have been retrieved. diff --git a/examples/ad_manager/v202108/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202205/site_service/get_sites_requiring_approval.py similarity index 92% rename from examples/ad_manager/v202108/site_service/get_sites_requiring_approval.py rename to examples/ad_manager/v202205/site_service/get_sites_requiring_approval.py index e79a088f..505c2c6b 100755 --- a/examples/ad_manager/v202108/site_service/get_sites_requiring_approval.py +++ b/examples/ad_manager/v202205/site_service/get_sites_requiring_approval.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202108') + site_service = client.GetService('SiteService', version='v202205') # Create a statement to select Sites needing approval. - statement = ad_manager.StatementBuilder(version='v202108').Where( + statement = ad_manager.StatementBuilder(version='v202205').Where( "approvalStatus = 'REQUIRES_REVIEW'") # Retrieve a small number of sites at a time, paging through until all sites diff --git a/examples/ad_manager/v202108/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202205/site_service/submit_sites_for_approval.py similarity index 91% rename from examples/ad_manager/v202108/site_service/submit_sites_for_approval.py rename to examples/ad_manager/v202205/site_service/submit_sites_for_approval.py index 0e7b5dfd..86b1bcdc 100755 --- a/examples/ad_manager/v202108/site_service/submit_sites_for_approval.py +++ b/examples/ad_manager/v202205/site_service/submit_sites_for_approval.py @@ -25,10 +25,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202108') + site_service = client.GetService('SiteService', version='v202205') # Create a statement to select Site. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :id') .WithBindVariable('id', SITE_ID)) diff --git a/examples/ad_manager/v202108/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202205/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202205/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v202108/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202205/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v202108/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202205/suggested_ad_unit_service/approve_all_suggested_ad_units.py index f52e5b51..028697fd 100755 --- a/examples/ad_manager/v202108/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202205/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202108') + 'SuggestedAdUnitService', version='v202205') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v202108/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202205/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202108/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202205/suggested_ad_unit_service/get_all_suggested_ad_units.py index 8f30f82f..ee1f267a 100755 --- a/examples/ad_manager/v202108/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202205/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202108') + 'SuggestedAdUnitService', version='v202205') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v202108/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202205/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202108/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202205/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 4efa8ca0..8c4816c1 100755 --- a/examples/ad_manager/v202108/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202205/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202108') + 'SuggestedAdUnitService', version='v202205') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v202108/targeting_preset_service/__init__.py b/examples/ad_manager/v202205/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/targeting_preset_service/__init__.py rename to examples/ad_manager/v202205/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202205/targeting_preset_service/get_all_targeting_presets.py similarity index 94% rename from examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202205/targeting_preset_service/get_all_targeting_presets.py index dd4b0a04..3ec9ba2b 100755 --- a/examples/ad_manager/v202108/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202205/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v202108') + 'TargetingPresetService', version='v202205') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. diff --git a/examples/ad_manager/v202108/team_service/__init__.py b/examples/ad_manager/v202205/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/team_service/__init__.py rename to examples/ad_manager/v202205/team_service/__init__.py diff --git a/examples/ad_manager/v202108/team_service/create_teams.py b/examples/ad_manager/v202205/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v202108/team_service/create_teams.py rename to examples/ad_manager/v202205/team_service/create_teams.py index e9ec11b2..2e2f9e6b 100755 --- a/examples/ad_manager/v202108/team_service/create_teams.py +++ b/examples/ad_manager/v202205/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202108') + team_service = client.GetService('TeamService', version='v202205') # Create team objects. teams = [] diff --git a/examples/ad_manager/v202108/team_service/get_all_teams.py b/examples/ad_manager/v202205/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v202108/team_service/get_all_teams.py rename to examples/ad_manager/v202205/team_service/get_all_teams.py index e160a5a8..41dc5331 100755 --- a/examples/ad_manager/v202108/team_service/get_all_teams.py +++ b/examples/ad_manager/v202205/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202108') + team_service = client.GetService('TeamService', version='v202205') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v202108/team_service/update_teams.py b/examples/ad_manager/v202205/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v202108/team_service/update_teams.py rename to examples/ad_manager/v202205/team_service/update_teams.py index abf08b20..ca9c8eb9 100755 --- a/examples/ad_manager/v202108/team_service/update_teams.py +++ b/examples/ad_manager/v202205/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202108') + team_service = client.GetService('TeamService', version='v202205') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v202108/user_service/__init__.py b/examples/ad_manager/v202205/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/user_service/__init__.py rename to examples/ad_manager/v202205/user_service/__init__.py diff --git a/examples/ad_manager/v202108/user_service/create_users.py b/examples/ad_manager/v202205/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v202108/user_service/create_users.py rename to examples/ad_manager/v202205/user_service/create_users.py index c8343ab0..a17bb785 100755 --- a/examples/ad_manager/v202108/user_service/create_users.py +++ b/examples/ad_manager/v202205/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202108') + user_service = client.GetService('UserService', version='v202205') # Create user objects. users = [ diff --git a/examples/ad_manager/v202108/user_service/deactivate_users.py b/examples/ad_manager/v202205/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v202108/user_service/deactivate_users.py rename to examples/ad_manager/v202205/user_service/deactivate_users.py index 4f4c79cf..cde52540 100755 --- a/examples/ad_manager/v202108/user_service/deactivate_users.py +++ b/examples/ad_manager/v202205/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202108') + user_service = client.GetService('UserService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202108/user_service/get_all_roles.py b/examples/ad_manager/v202205/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v202108/user_service/get_all_roles.py rename to examples/ad_manager/v202205/user_service/get_all_roles.py index b3e84d01..9d4161ad 100755 --- a/examples/ad_manager/v202108/user_service/get_all_roles.py +++ b/examples/ad_manager/v202205/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202108') + user_service = client.GetService('UserService', version='v202205') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v202108/user_service/get_all_users.py b/examples/ad_manager/v202205/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v202108/user_service/get_all_users.py rename to examples/ad_manager/v202205/user_service/get_all_users.py index 2815fb67..2b815308 100755 --- a/examples/ad_manager/v202108/user_service/get_all_users.py +++ b/examples/ad_manager/v202205/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202108') + user_service = client.GetService('UserService', version='v202205') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v202108/user_service/get_current_user.py b/examples/ad_manager/v202205/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v202108/user_service/get_current_user.py rename to examples/ad_manager/v202205/user_service/get_current_user.py index cce3f029..7ac3bb5b 100755 --- a/examples/ad_manager/v202108/user_service/get_current_user.py +++ b/examples/ad_manager/v202205/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202108') + user_service = client.GetService('UserService', version='v202205') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v202108/user_service/get_user_by_email_address.py b/examples/ad_manager/v202205/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v202108/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202205/user_service/get_user_by_email_address.py index 7d8f1724..13de3a79 100755 --- a/examples/ad_manager/v202108/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202205/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202108') + user_service = client.GetService('UserService', version='v202205') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v202108/user_service/update_users.py b/examples/ad_manager/v202205/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v202108/user_service/update_users.py rename to examples/ad_manager/v202205/user_service/update_users.py index 960a13a6..5da27af2 100755 --- a/examples/ad_manager/v202108/user_service/update_users.py +++ b/examples/ad_manager/v202205/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202108') + user_service = client.GetService('UserService', version='v202205') # Create query. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202108/user_team_association_service/__init__.py b/examples/ad_manager/v202205/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202108/user_team_association_service/__init__.py rename to examples/ad_manager/v202205/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v202108/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202205/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v202108/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202205/user_team_association_service/create_user_team_associations.py index 2c2da97b..4cc3d758 100755 --- a/examples/ad_manager/v202108/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202205/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202108') + 'UserTeamAssociationService', version='v202205') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v202108/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202205/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v202108/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202205/user_team_association_service/delete_user_team_associations.py index d6f3eebb..88fee344 100755 --- a/examples/ad_manager/v202108/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202205/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202108') + 'UserTeamAssociationService', version='v202205') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202108/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202205/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v202108/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202205/user_team_association_service/get_all_user_team_associations.py index 37c0d2cc..d90faff7 100755 --- a/examples/ad_manager/v202108/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202205/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202108') + 'UserTeamAssociationService', version='v202205') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v202108') + statement = ad_manager.StatementBuilder(version='v202205') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v202108/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202205/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v202108/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202205/user_team_association_service/get_user_team_associations_for_user.py index 29986ba7..5dc88ff0 100755 --- a/examples/ad_manager/v202108/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202205/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202108') + 'UserTeamAssociationService', version='v202205') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202108/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202205/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v202108/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202205/user_team_association_service/update_user_team_associations.py index 8e8c30bf..95b85b15 100755 --- a/examples/ad_manager/v202108/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202205/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202108') + 'UserTeamAssociationService', version='v202205') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202108') + statement = (ad_manager.StatementBuilder(version='v202205') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index e503bbf3..1c623bf8 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,78 +44,78 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v202105': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', - 'ContactService', 'ContentBundleService', 'ContentService', - 'CreativeReviewService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'SiteService', 'StreamActivityMonitorService', - 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', - 'UserService', 'UserTeamAssociationService'), - 'v202108': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', - 'ContactService', 'ContentBundleService', 'ContentService', - 'CreativeReviewService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'SiteService', 'StreamActivityMonitorService', - 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', - 'UserService', 'UserTeamAssociationService'), - 'v202111': - ('ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', - 'ContactService', 'ContentBundleService', 'ContentService', - 'CreativeReviewService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'SiteService', 'StreamActivityMonitorService', - 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', - 'UserService', 'UserTeamAssociationService'), - 'v202202': - ('ActivityGroupService', 'ActivityService', 'AdjustmentService', - 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', - 'CmsMetadataService', 'CompanyService', 'ContactService', - 'ContentBundleService', 'ContentService', 'CreativeReviewService', - 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', - 'CreativeWrapperService', 'CustomFieldService', - 'CustomTargetingService', 'DaiAuthenticationKeyService', - 'DaiEncodingProfileService', 'ForecastService', 'InventoryService', - 'LabelService', 'LineItemCreativeAssociationService', - 'LineItemService', 'LineItemTemplateService', - 'LiveStreamEventService', 'MobileApplicationService', - 'NativeStyleService', 'NetworkService', 'OrderService', - 'PlacementService', 'ProposalLineItemService', 'ProposalService', - 'PublisherQueryLanguageService', 'ReportService', 'SiteService', - 'StreamActivityMonitorService', 'SuggestedAdUnitService', - 'TeamService', 'TargetingPresetService', 'UserService', - 'UserTeamAssociationService', 'YieldGroupService'), + 'v202108': ( + 'ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', + 'ContactService', 'ContentBundleService', 'ContentService', + 'CreativeReviewService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PlacementService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', + 'SiteService', 'StreamActivityMonitorService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService'), + 'v202111': ( + 'ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', + 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', + 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', + 'ContactService', 'ContentBundleService', 'ContentService', + 'CreativeReviewService', 'CreativeService', 'CreativeSetService', + 'CreativeTemplateService', 'CreativeWrapperService', + 'CustomFieldService', 'CustomTargetingService', + 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', + 'ForecastService', 'InventoryService', 'LabelService', + 'LineItemCreativeAssociationService', 'LineItemService', + 'LineItemTemplateService', 'LiveStreamEventService', + 'MobileApplicationService', 'NativeStyleService', 'NetworkService', + 'OrderService', 'PlacementService', 'ProposalLineItemService', + 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', + 'SiteService', 'StreamActivityMonitorService', + 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', + 'UserService', 'UserTeamAssociationService'), + 'v202202': ( + 'ActivityGroupService', 'ActivityService', 'AdjustmentService', + 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', + 'CmsMetadataService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentService', 'CreativeReviewService', + 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', + 'CreativeWrapperService', 'CustomFieldService', + 'CustomTargetingService', 'DaiAuthenticationKeyService', + 'DaiEncodingProfileService', 'ForecastService', 'InventoryService', + 'LabelService', 'LineItemCreativeAssociationService', + 'LineItemService', 'LineItemTemplateService', + 'LiveStreamEventService', 'MobileApplicationService', + 'NativeStyleService', 'NetworkService', 'OrderService', + 'PlacementService', 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'ReportService', 'SiteService', + 'StreamActivityMonitorService', 'SuggestedAdUnitService', + 'TeamService', 'TargetingPresetService', 'UserService', + 'UserTeamAssociationService', 'YieldGroupService'), + 'v202205': ( + 'ActivityGroupService', 'ActivityService', 'AdjustmentService', + 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', + 'CmsMetadataService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentService', 'CreativeReviewService', + 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', + 'CreativeWrapperService', 'CustomFieldService', + 'CustomTargetingService', 'DaiAuthenticationKeyService', + 'DaiEncodingProfileService', 'ForecastService', 'InventoryService', + 'LabelService', 'LineItemCreativeAssociationService', + 'LineItemService', 'LineItemTemplateService', + 'LiveStreamEventService', 'MobileApplicationService', + 'NativeStyleService', 'NetworkService', 'OrderService', + 'PlacementService', 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'ReportService', 'SiteService', + 'StreamActivityMonitorService', 'SuggestedAdUnitService', + 'TeamService', 'TargetingPresetService', 'UserService', + 'UserTeamAssociationService', 'YieldGroupService'), } diff --git a/googleads/common.py b/googleads/common.py index 9b3852fe..e4c9b42b 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -54,7 +54,7 @@ 'order to benefit from important security improvements and ensure ' 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '31.0.0' +VERSION = '32.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 7e12a740..5b9f711b 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202202' +CURRENT_VERSION = 'v202205' class CommonTest(testing.CleanUtilityRegistryTestCase): From bf734e9cdc86db9c9586643313fd4ec50fcc184c Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 17 May 2022 15:34:30 -0400 Subject: [PATCH 178/180] Commiting latest changes. From 356f4f9be93f269d84703a5603f5bb84c606ffa4 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 16 Aug 2022 16:27:10 +0000 Subject: [PATCH 179/180] Ad Manager v202208 release. --- ChangeLog | 5 ++ .../report_service/run_ad_exchange_report.py | 66 ------------------- .../activity_group_service/__init__.py | 0 .../create_activity_groups.py | 2 +- .../get_active_activity_groups.py | 4 +- .../get_all_activity_groups.py | 4 +- .../update_activity_groups.py | 4 +- .../activity_service/__init__.py | 0 .../activity_service/create_activities.py | 2 +- .../activity_service/get_active_activities.py | 4 +- .../activity_service/get_all_activities.py | 4 +- .../activity_service/update_activities.py | 4 +- .../create_forecast_adjustments.py | 2 +- .../create_traffic_forecast_segments.py | 4 +- .../get_all_forecast_adjustments.py | 4 +- .../get_all_traffic_forecast_segments.py | 4 +- ...djustments_for_traffic_forecast_segment.py | 4 +- .../update_forecast_adjustments.py | 4 +- .../audience_segment_service/__init__.py | 0 .../create_audience_segments.py | 4 +- .../get_all_audience_segments.py | 4 +- .../get_first_party_audience_segments.py | 4 +- .../populate_first_party_audience_segments.py | 4 +- .../update_audience_segments.py | 4 +- .../cdn_configuration_service/__init__.py | 0 .../create_cdn_configurations.py | 2 +- .../get_all_cdn_configurations.py | 4 +- .../activate_cms_metadata_values.py | 4 +- .../get_all_cms_metadata_keys.py | 4 +- .../get_all_cms_metadata_values.py | 4 +- .../get_cms_metadata_values_for_key.py | 4 +- .../company_service/__init__.py | 0 .../company_service/create_companies.py | 2 +- .../company_service/get_advertisers.py | 4 +- .../company_service/get_all_companies.py | 4 +- .../company_service/update_companies.py | 4 +- .../contact_service/__init__.py | 0 .../contact_service/create_contacts.py | 2 +- .../contact_service/get_all_contacts.py | 4 +- .../contact_service/get_uninvited_contacts.py | 4 +- .../contact_service/update_contacts.py | 4 +- .../content_service/__init__.py | 0 .../content_service/get_all_content.py | 4 +- .../get_recently_modified_content.py | 4 +- .../creative_service/__init__.py | 0 .../creative_service/copy_image_creatives.py | 4 +- .../create_creative_from_template.py | 2 +- .../creative_service/create_creatives.py | 2 +- .../create_custom_creative.py | 2 +- .../create_native_creative.py | 2 +- .../create_video_creatives.py | 66 +++++++++++++++++++ .../creative_service/get_all_creatives.py | 4 +- .../creative_service/get_image_creatives.py | 4 +- .../creative_service/update_creatives.py | 4 +- .../creative_set_service/__init__.py | 0 .../associate_creative_set_to_line_item.py | 2 +- .../create_creative_set.py | 2 +- .../get_all_creative_sets.py | 4 +- .../get_creative_sets_for_master_creative.py | 4 +- .../update_creative_set.py | 4 +- .../creative_template_service/__init__.py | 0 .../get_all_creative_templates.py | 4 +- .../get_system_defined_creative_templates.py | 4 +- .../create_creative_wrappers.py | 2 +- .../deactivate_creative_wrapper.py | 4 +- .../get_active_creative_wrappers.py | 4 +- .../get_all_creative_wrappers.py | 4 +- .../update_creative_wrappers.py | 4 +- .../custom_field_service/__init__.py | 0 .../create_custom_field_options.py | 2 +- .../create_custom_fields.py | 2 +- .../deactivate_all_line_item_custom_fields.py | 4 +- .../get_all_custom_fields.py | 4 +- .../get_custom_fields_for_line_items.py | 4 +- .../set_line_item_custom_field_value.py | 10 +-- .../update_custom_fields.py | 4 +- .../custom_targeting_service/__init__.py | 0 ...create_custom_targeting_keys_and_values.py | 2 +- .../delete_custom_targeting_keys.py | 6 +- .../delete_custom_targeting_values.py | 6 +- ...et_all_custom_targeting_keys_and_values.py | 6 +- ...efined_custom_targeting_keys_and_values.py | 6 +- .../update_custom_targeting_keys.py | 4 +- .../update_custom_targeting_values.py | 4 +- .../get_availability_forecast.py | 4 +- ...get_availability_forecast_for_line_item.py | 2 +- .../get_delivery_forecast_for_line_items.py | 2 +- .../forecast_service/get_traffic_data.py | 4 +- .../inventory_service/__init__.py | 0 .../inventory_service/archive_ad_units.py | 4 +- .../inventory_service/create_ad_units.py | 2 +- .../get_ad_unit_hierarchy.py | 8 +-- .../get_all_ad_unit_sizes.py | 4 +- .../inventory_service/get_all_ad_units.py | 4 +- .../get_top_level_ad_units.py | 6 +- .../inventory_service/update_ad_units.py | 4 +- .../label_service/__init__.py | 0 .../label_service/create_labels.py | 2 +- .../label_service/deactivate_labels.py | 4 +- .../label_service/get_active_labels.py | 4 +- .../label_service/get_all_labels.py | 4 +- .../label_service/update_labels.py | 4 +- .../__init__.py | 0 .../create_licas.py | 2 +- .../deactivate_licas.py | 4 +- .../get_all_licas.py | 4 +- .../get_licas_for_line_item.py | 4 +- .../push_creative_to_devices.py | 4 +- .../update_licas.py | 4 +- .../line_item_service/__init__.py | 0 .../line_item_service/activate_line_items.py | 4 +- .../line_item_service/create_line_items.py | 2 +- .../create_video_line_item.py | 2 +- .../line_item_service/get_all_line_items.py | 4 +- .../get_line_items_that_need_creatives.py | 4 +- .../get_recently_updated_line_items.py | 4 +- .../line_item_service/pause_line_items.py | 4 +- .../target_custom_criteria.py | 4 +- .../line_item_service/update_line_items.py | 4 +- .../activate_live_stream_events.py | 4 +- .../create_live_stream_events.py | 2 +- .../get_all_live_stream_events.py | 4 +- .../register_sessions_for_monitoring.py | 2 +- .../update_live_stream_events.py | 4 +- .../native_style_service/__init__.py | 0 .../create_native_styles.py | 2 +- .../get_all_native_styles.py | 4 +- .../network_service/__init__.py | 0 .../network_service/get_all_networks.py | 2 +- .../network_service/get_current_network.py | 2 +- ...et_default_third_party_data_declaration.py | 6 +- .../network_service/make_test_network.py | 2 +- .../order_service/__init__.py | 0 .../order_service/approve_orders.py | 4 +- .../order_service/create_orders.py | 2 +- .../order_service/get_all_orders.py | 4 +- .../order_service/get_orders_starting_soon.py | 4 +- .../order_service/update_orders.py | 4 +- .../placement_service/create_placements.py | 6 +- .../deactivate_placements.py | 4 +- .../get_active_placements.py | 4 +- .../placement_service/get_all_placements.py | 4 +- .../placement_service/update_placements.py | 4 +- .../proposal_line_item_service/__init__.py | 0 .../archive_proposal_line_items.py | 4 +- .../create_proposal_line_items.py | 4 +- .../get_all_proposal_line_items.py | 4 +- .../get_proposal_line_items_for_proposal.py | 4 +- .../update_proposal_line_items.py | 4 +- .../proposal_service/__init__.py | 0 .../proposal_service/create_proposals.py | 3 +- .../proposal_service/get_all_proposals.py | 4 +- .../get_marketplace_comments.py | 2 +- .../get_proposals_awaiting_seller_review.py | 4 +- .../request_buyers_acceptance.py | 4 +- .../proposal_service/update_proposals.py | 4 +- .../__init__.py | 0 .../fetch_match_tables.py | 2 +- .../get_all_browsers.py | 2 +- .../get_all_programmatic_buyers.py | 2 +- .../get_geo_targets.py | 2 +- .../get_line_items_named_like.py | 2 +- .../get_mcm_earnings.py | 2 +- .../get_recent_changes.py | 4 +- .../report_service/__init__.py | 0 .../report_service/run_delivery_report.py | 4 +- .../report_service/run_inventory_report.py | 6 +- .../report_service/run_reach_report.py | 2 +- ...un_reach_report_with_ad_unit_dimensions.py | 2 +- .../run_report_and_create_match_table.py | 2 +- .../run_report_with_custom_fields.py | 2 +- .../report_service/run_sales_report.py | 2 +- .../report_service/run_saved_query.py | 6 +- .../site_service/create_sites.py | 4 +- .../site_service/get_all_sites.py | 4 +- .../get_sites_requiring_approval.py | 4 +- .../site_service/submit_sites_for_approval.py | 4 +- .../suggested_ad_unit_service/__init__.py | 0 .../approve_all_suggested_ad_units.py | 4 +- .../get_all_suggested_ad_units.py | 4 +- ...get_highly_requested_suggested_ad_units.py | 4 +- .../targeting_preset_service/__init__.py | 0 .../get_all_targeting_presets.py | 4 +- .../team_service/__init__.py | 0 .../team_service/create_teams.py | 2 +- .../team_service/get_all_teams.py | 4 +- .../team_service/update_teams.py | 4 +- .../user_service/__init__.py | 0 .../user_service/create_users.py | 2 +- .../user_service/deactivate_users.py | 4 +- .../user_service/get_all_roles.py | 2 +- .../user_service/get_all_users.py | 4 +- .../user_service/get_current_user.py | 2 +- .../user_service/get_user_by_email_address.py | 4 +- .../user_service/update_users.py | 4 +- .../user_team_association_service/__init__.py | 0 .../create_user_team_associations.py | 2 +- .../delete_user_team_associations.py | 4 +- .../get_all_user_team_associations.py | 4 +- .../get_user_team_associations_for_user.py | 4 +- .../update_user_team_associations.py | 4 +- googleads/ad_manager.py | 36 +++++----- googleads/common.py | 2 +- tests/common_test.py | 2 +- 204 files changed, 397 insertions(+), 393 deletions(-) delete mode 100755 examples/ad_manager/v202111/report_service/run_ad_exchange_report.py rename examples/ad_manager/{v202111 => v202208}/activity_group_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/activity_group_service/create_activity_groups.py (97%) rename examples/ad_manager/{v202111 => v202208}/activity_group_service/get_active_activity_groups.py (94%) rename examples/ad_manager/{v202111 => v202208}/activity_group_service/get_all_activity_groups.py (94%) rename examples/ad_manager/{v202111 => v202208}/activity_group_service/update_activity_groups.py (95%) rename examples/ad_manager/{v202111 => v202208}/activity_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/activity_service/create_activities.py (99%) rename examples/ad_manager/{v202111 => v202208}/activity_service/get_active_activities.py (96%) rename examples/ad_manager/{v202111 => v202208}/activity_service/get_all_activities.py (95%) rename examples/ad_manager/{v202111 => v202208}/activity_service/update_activities.py (96%) rename examples/ad_manager/{v202111 => v202208}/adjustment_service/create_forecast_adjustments.py (99%) rename examples/ad_manager/{v202111 => v202208}/adjustment_service/create_traffic_forecast_segments.py (98%) rename examples/ad_manager/{v202111 => v202208}/adjustment_service/get_all_forecast_adjustments.py (95%) rename examples/ad_manager/{v202111 => v202208}/adjustment_service/get_all_traffic_forecast_segments.py (95%) rename examples/ad_manager/{v202111 => v202208}/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py (96%) rename examples/ad_manager/{v202111 => v202208}/adjustment_service/update_forecast_adjustments.py (96%) rename examples/ad_manager/{v202111 => v202208}/audience_segment_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/audience_segment_service/create_audience_segments.py (98%) rename examples/ad_manager/{v202111 => v202208}/audience_segment_service/get_all_audience_segments.py (94%) rename examples/ad_manager/{v202111 => v202208}/audience_segment_service/get_first_party_audience_segments.py (94%) rename examples/ad_manager/{v202111 => v202208}/audience_segment_service/populate_first_party_audience_segments.py (95%) rename examples/ad_manager/{v202111 => v202208}/audience_segment_service/update_audience_segments.py (95%) rename examples/ad_manager/{v202111 => v202208}/cdn_configuration_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/cdn_configuration_service/create_cdn_configurations.py (97%) rename examples/ad_manager/{v202111 => v202208}/cdn_configuration_service/get_all_cdn_configurations.py (93%) rename examples/ad_manager/{v202111 => v202208}/cms_metadata_service/activate_cms_metadata_values.py (95%) rename examples/ad_manager/{v202111 => v202208}/cms_metadata_service/get_all_cms_metadata_keys.py (94%) rename examples/ad_manager/{v202111 => v202208}/cms_metadata_service/get_all_cms_metadata_values.py (94%) rename examples/ad_manager/{v202111 => v202208}/cms_metadata_service/get_cms_metadata_values_for_key.py (95%) rename examples/ad_manager/{v202111 => v202208}/company_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/company_service/create_companies.py (99%) rename examples/ad_manager/{v202111 => v202208}/company_service/get_advertisers.py (96%) rename examples/ad_manager/{v202111 => v202208}/company_service/get_all_companies.py (95%) rename examples/ad_manager/{v202111 => v202208}/company_service/update_companies.py (96%) rename examples/ad_manager/{v202111 => v202208}/contact_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/contact_service/create_contacts.py (99%) rename examples/ad_manager/{v202111 => v202208}/contact_service/get_all_contacts.py (95%) rename examples/ad_manager/{v202111 => v202208}/contact_service/get_uninvited_contacts.py (96%) rename examples/ad_manager/{v202111 => v202208}/contact_service/update_contacts.py (96%) rename examples/ad_manager/{v202111 => v202208}/content_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/content_service/get_all_content.py (96%) rename examples/ad_manager/{v202111 => v202208}/content_service/get_recently_modified_content.py (97%) rename examples/ad_manager/{v202111 => v202208}/creative_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/creative_service/copy_image_creatives.py (96%) rename examples/ad_manager/{v202111 => v202208}/creative_service/create_creative_from_template.py (99%) rename examples/ad_manager/{v202111 => v202208}/creative_service/create_creatives.py (99%) rename examples/ad_manager/{v202111 => v202208}/creative_service/create_custom_creative.py (99%) rename examples/ad_manager/{v202111 => v202208}/creative_service/create_native_creative.py (99%) create mode 100755 examples/ad_manager/v202208/creative_service/create_video_creatives.py rename examples/ad_manager/{v202111 => v202208}/creative_service/get_all_creatives.py (95%) rename examples/ad_manager/{v202111 => v202208}/creative_service/get_image_creatives.py (96%) rename examples/ad_manager/{v202111 => v202208}/creative_service/update_creatives.py (97%) rename examples/ad_manager/{v202111 => v202208}/creative_set_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/creative_set_service/associate_creative_set_to_line_item.py (96%) rename examples/ad_manager/{v202111 => v202208}/creative_set_service/create_creative_set.py (97%) rename examples/ad_manager/{v202111 => v202208}/creative_set_service/get_all_creative_sets.py (94%) rename examples/ad_manager/{v202111 => v202208}/creative_set_service/get_creative_sets_for_master_creative.py (94%) rename examples/ad_manager/{v202111 => v202208}/creative_set_service/update_creative_set.py (95%) rename examples/ad_manager/{v202111 => v202208}/creative_template_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/creative_template_service/get_all_creative_templates.py (94%) rename examples/ad_manager/{v202111 => v202208}/creative_template_service/get_system_defined_creative_templates.py (94%) rename examples/ad_manager/{v202111 => v202208}/creative_wrapper_service/create_creative_wrappers.py (97%) rename examples/ad_manager/{v202111 => v202208}/creative_wrapper_service/deactivate_creative_wrapper.py (95%) rename examples/ad_manager/{v202111 => v202208}/creative_wrapper_service/get_active_creative_wrappers.py (94%) rename examples/ad_manager/{v202111 => v202208}/creative_wrapper_service/get_all_creative_wrappers.py (94%) rename examples/ad_manager/{v202111 => v202208}/creative_wrapper_service/update_creative_wrappers.py (95%) rename examples/ad_manager/{v202111 => v202208}/custom_field_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/custom_field_service/create_custom_field_options.py (97%) rename examples/ad_manager/{v202111 => v202208}/custom_field_service/create_custom_fields.py (97%) rename examples/ad_manager/{v202111 => v202208}/custom_field_service/deactivate_all_line_item_custom_fields.py (95%) rename examples/ad_manager/{v202111 => v202208}/custom_field_service/get_all_custom_fields.py (94%) rename examples/ad_manager/{v202111 => v202208}/custom_field_service/get_custom_fields_for_line_items.py (94%) rename examples/ad_manager/{v202111 => v202208}/custom_field_service/set_line_item_custom_field_value.py (97%) rename examples/ad_manager/{v202111 => v202208}/custom_field_service/update_custom_fields.py (95%) rename examples/ad_manager/{v202111 => v202208}/custom_targeting_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/custom_targeting_service/create_custom_targeting_keys_and_values.py (98%) rename examples/ad_manager/{v202111 => v202208}/custom_targeting_service/delete_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202111 => v202208}/custom_targeting_service/delete_custom_targeting_values.py (95%) rename examples/ad_manager/{v202111 => v202208}/custom_targeting_service/get_all_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202111 => v202208}/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py (95%) rename examples/ad_manager/{v202111 => v202208}/custom_targeting_service/update_custom_targeting_keys.py (95%) rename examples/ad_manager/{v202111 => v202208}/custom_targeting_service/update_custom_targeting_values.py (95%) rename examples/ad_manager/{v202111 => v202208}/forecast_service/get_availability_forecast.py (99%) rename examples/ad_manager/{v202111 => v202208}/forecast_service/get_availability_forecast_for_line_item.py (99%) rename examples/ad_manager/{v202111 => v202208}/forecast_service/get_delivery_forecast_for_line_items.py (99%) rename examples/ad_manager/{v202111 => v202208}/forecast_service/get_traffic_data.py (99%) rename examples/ad_manager/{v202111 => v202208}/inventory_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/inventory_service/archive_ad_units.py (97%) rename examples/ad_manager/{v202111 => v202208}/inventory_service/create_ad_units.py (99%) rename examples/ad_manager/{v202111 => v202208}/inventory_service/get_ad_unit_hierarchy.py (96%) rename examples/ad_manager/{v202111 => v202208}/inventory_service/get_all_ad_unit_sizes.py (93%) rename examples/ad_manager/{v202111 => v202208}/inventory_service/get_all_ad_units.py (95%) rename examples/ad_manager/{v202111 => v202208}/inventory_service/get_top_level_ad_units.py (96%) rename examples/ad_manager/{v202111 => v202208}/inventory_service/update_ad_units.py (97%) rename examples/ad_manager/{v202111 => v202208}/label_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/label_service/create_labels.py (99%) rename examples/ad_manager/{v202111 => v202208}/label_service/deactivate_labels.py (96%) rename examples/ad_manager/{v202111 => v202208}/label_service/get_active_labels.py (96%) rename examples/ad_manager/{v202111 => v202208}/label_service/get_all_labels.py (96%) rename examples/ad_manager/{v202111 => v202208}/label_service/update_labels.py (96%) rename examples/ad_manager/{v202111 => v202208}/line_item_creative_association_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/line_item_creative_association_service/create_licas.py (96%) rename examples/ad_manager/{v202111 => v202208}/line_item_creative_association_service/deactivate_licas.py (95%) rename examples/ad_manager/{v202111 => v202208}/line_item_creative_association_service/get_all_licas.py (94%) rename examples/ad_manager/{v202111 => v202208}/line_item_creative_association_service/get_licas_for_line_item.py (94%) rename examples/ad_manager/{v202111 => v202208}/line_item_creative_association_service/push_creative_to_devices.py (94%) rename examples/ad_manager/{v202111 => v202208}/line_item_creative_association_service/update_licas.py (94%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/activate_line_items.py (97%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/create_line_items.py (99%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/create_video_line_item.py (99%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/get_all_line_items.py (95%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/get_line_items_that_need_creatives.py (96%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/get_recently_updated_line_items.py (96%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/pause_line_items.py (97%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/target_custom_criteria.py (97%) rename examples/ad_manager/{v202111 => v202208}/line_item_service/update_line_items.py (97%) rename examples/ad_manager/{v202111 => v202208}/live_stream_event_service/activate_live_stream_events.py (95%) rename examples/ad_manager/{v202111 => v202208}/live_stream_event_service/create_live_stream_events.py (97%) rename examples/ad_manager/{v202111 => v202208}/live_stream_event_service/get_all_live_stream_events.py (94%) rename examples/ad_manager/{v202111 => v202208}/live_stream_event_service/register_sessions_for_monitoring.py (96%) rename examples/ad_manager/{v202111 => v202208}/live_stream_event_service/update_live_stream_events.py (95%) rename examples/ad_manager/{v202111 => v202208}/native_style_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/native_style_service/create_native_styles.py (98%) rename examples/ad_manager/{v202111 => v202208}/native_style_service/get_all_native_styles.py (93%) rename examples/ad_manager/{v202111 => v202208}/network_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/network_service/get_all_networks.py (99%) rename examples/ad_manager/{v202111 => v202208}/network_service/get_current_network.py (99%) rename examples/ad_manager/{v202111 => v202208}/network_service/get_default_third_party_data_declaration.py (95%) rename examples/ad_manager/{v202111 => v202208}/network_service/make_test_network.py (99%) rename examples/ad_manager/{v202111 => v202208}/order_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/order_service/approve_orders.py (97%) rename examples/ad_manager/{v202111 => v202208}/order_service/create_orders.py (99%) rename examples/ad_manager/{v202111 => v202208}/order_service/get_all_orders.py (96%) rename examples/ad_manager/{v202111 => v202208}/order_service/get_orders_starting_soon.py (96%) rename examples/ad_manager/{v202111 => v202208}/order_service/update_orders.py (97%) rename examples/ad_manager/{v202111 => v202208}/placement_service/create_placements.py (97%) rename examples/ad_manager/{v202111 => v202208}/placement_service/deactivate_placements.py (96%) rename examples/ad_manager/{v202111 => v202208}/placement_service/get_active_placements.py (95%) rename examples/ad_manager/{v202111 => v202208}/placement_service/get_all_placements.py (95%) rename examples/ad_manager/{v202111 => v202208}/placement_service/update_placements.py (96%) rename examples/ad_manager/{v202111 => v202208}/proposal_line_item_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/proposal_line_item_service/archive_proposal_line_items.py (95%) rename examples/ad_manager/{v202111 => v202208}/proposal_line_item_service/create_proposal_line_items.py (98%) rename examples/ad_manager/{v202111 => v202208}/proposal_line_item_service/get_all_proposal_line_items.py (94%) rename examples/ad_manager/{v202111 => v202208}/proposal_line_item_service/get_proposal_line_items_for_proposal.py (94%) rename examples/ad_manager/{v202111 => v202208}/proposal_line_item_service/update_proposal_line_items.py (95%) rename examples/ad_manager/{v202111 => v202208}/proposal_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/proposal_service/create_proposals.py (98%) rename examples/ad_manager/{v202111 => v202208}/proposal_service/get_all_proposals.py (95%) rename examples/ad_manager/{v202111 => v202208}/proposal_service/get_marketplace_comments.py (97%) rename examples/ad_manager/{v202111 => v202208}/proposal_service/get_proposals_awaiting_seller_review.py (96%) rename examples/ad_manager/{v202111 => v202208}/proposal_service/request_buyers_acceptance.py (97%) rename examples/ad_manager/{v202111 => v202208}/proposal_service/update_proposals.py (96%) rename examples/ad_manager/{v202111 => v202208}/publisher_query_language_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/publisher_query_language_service/fetch_match_tables.py (96%) rename examples/ad_manager/{v202111 => v202208}/publisher_query_language_service/get_all_browsers.py (96%) rename examples/ad_manager/{v202111 => v202208}/publisher_query_language_service/get_all_programmatic_buyers.py (96%) rename examples/ad_manager/{v202111 => v202208}/publisher_query_language_service/get_geo_targets.py (96%) rename examples/ad_manager/{v202111 => v202208}/publisher_query_language_service/get_line_items_named_like.py (96%) rename examples/ad_manager/{v202111 => v202208}/publisher_query_language_service/get_mcm_earnings.py (97%) rename examples/ad_manager/{v202111 => v202208}/publisher_query_language_service/get_recent_changes.py (98%) rename examples/ad_manager/{v202111 => v202208}/report_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/report_service/run_delivery_report.py (95%) rename examples/ad_manager/{v202111 => v202208}/report_service/run_inventory_report.py (91%) rename examples/ad_manager/{v202111 => v202208}/report_service/run_reach_report.py (96%) rename examples/ad_manager/{v202111 => v202208}/report_service/run_reach_report_with_ad_unit_dimensions.py (97%) rename examples/ad_manager/{v202111 => v202208}/report_service/run_report_and_create_match_table.py (97%) rename examples/ad_manager/{v202111 => v202208}/report_service/run_report_with_custom_fields.py (97%) rename examples/ad_manager/{v202111 => v202208}/report_service/run_sales_report.py (96%) rename examples/ad_manager/{v202111 => v202208}/report_service/run_saved_query.py (94%) rename examples/ad_manager/{v202111 => v202208}/site_service/create_sites.py (96%) rename examples/ad_manager/{v202111 => v202208}/site_service/get_all_sites.py (92%) rename examples/ad_manager/{v202111 => v202208}/site_service/get_sites_requiring_approval.py (92%) rename examples/ad_manager/{v202111 => v202208}/site_service/submit_sites_for_approval.py (91%) rename examples/ad_manager/{v202111 => v202208}/suggested_ad_unit_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/suggested_ad_unit_service/approve_all_suggested_ad_units.py (95%) rename examples/ad_manager/{v202111 => v202208}/suggested_ad_unit_service/get_all_suggested_ad_units.py (94%) rename examples/ad_manager/{v202111 => v202208}/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py (94%) rename examples/ad_manager/{v202111 => v202208}/targeting_preset_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/targeting_preset_service/get_all_targeting_presets.py (94%) rename examples/ad_manager/{v202111 => v202208}/team_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/team_service/create_teams.py (96%) rename examples/ad_manager/{v202111 => v202208}/team_service/get_all_teams.py (92%) rename examples/ad_manager/{v202111 => v202208}/team_service/update_teams.py (94%) rename examples/ad_manager/{v202111 => v202208}/user_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/user_service/create_users.py (96%) rename examples/ad_manager/{v202111 => v202208}/user_service/deactivate_users.py (94%) rename examples/ad_manager/{v202111 => v202208}/user_service/get_all_roles.py (94%) rename examples/ad_manager/{v202111 => v202208}/user_service/get_all_users.py (92%) rename examples/ad_manager/{v202111 => v202208}/user_service/get_current_user.py (94%) rename examples/ad_manager/{v202111 => v202208}/user_service/get_user_by_email_address.py (93%) rename examples/ad_manager/{v202111 => v202208}/user_service/update_users.py (92%) rename examples/ad_manager/{v202111 => v202208}/user_team_association_service/__init__.py (100%) rename examples/ad_manager/{v202111 => v202208}/user_team_association_service/create_user_team_associations.py (97%) rename examples/ad_manager/{v202111 => v202208}/user_team_association_service/delete_user_team_associations.py (95%) rename examples/ad_manager/{v202111 => v202208}/user_team_association_service/get_all_user_team_associations.py (94%) rename examples/ad_manager/{v202111 => v202208}/user_team_association_service/get_user_team_associations_for_user.py (94%) rename examples/ad_manager/{v202111 => v202208}/user_team_association_service/update_user_team_associations.py (96%) diff --git a/ChangeLog b/ChangeLog index e232be48..4362e400 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +33.0.0 -- 08/16/2022 +* Added support for Ad Manager v202208. +* Removed support for Ad Manager v202108. +* Removed examples for Ad Manager v202111. + 32.0.0 -- 05/17/2022 * Added support for Ad Manager v202205. * Removed support for Ad Manager v202105. diff --git a/examples/ad_manager/v202111/report_service/run_ad_exchange_report.py b/examples/ad_manager/v202111/report_service/run_ad_exchange_report.py deleted file mode 100755 index a6881aeb..00000000 --- a/examples/ad_manager/v202111/report_service/run_ad_exchange_report.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2018 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. - -"""Runs a report on Ad Exchange data via the Ad Manager API.""" - -import tempfile - -# Import appropriate modules from the client library. -from googleads import ad_manager -from googleads import errors - - -def main(client): - # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') - - # Create report job. - report_job = { - 'reportQuery': { - 'dimensions': ['AD_EXCHANGE_DATE', 'AD_EXCHANGE_COUNTRY_NAME'], - 'columns': ['AD_EXCHANGE_AD_REQUESTS', 'AD_EXCHANGE_IMPRESSIONS', - 'AD_EXCHANGE_ESTIMATED_REVENUE'], - 'dateRangeType': 'LAST_WEEK', - 'timeZoneType': 'AD_EXCHANGE', # Run in pacific time - 'adxReportCurrency': 'EUR' - } - } - - try: - # Run the report and wait for it to finish. - report_job_id = report_downloader.WaitForReport(report_job) - except errors.AdManagerReportError as e: - print('Failed to generate report. Error was: %s' % e) - - # Change to your preferred export format. - export_format = 'CSV_DUMP' - - report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) - - # Download report data. - report_downloader.DownloadReportToFile( - report_job_id, export_format, report_file) - - report_file.close() - - # Display results. - print('Report job with id "%s" downloaded to:\n%s' % ( - report_job_id, report_file.name)) - -if __name__ == '__main__': - # Initialize client object. - ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() - main(ad_manager_client) diff --git a/examples/ad_manager/v202111/activity_group_service/__init__.py b/examples/ad_manager/v202208/activity_group_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/activity_group_service/__init__.py rename to examples/ad_manager/v202208/activity_group_service/__init__.py diff --git a/examples/ad_manager/v202111/activity_group_service/create_activity_groups.py b/examples/ad_manager/v202208/activity_group_service/create_activity_groups.py similarity index 97% rename from examples/ad_manager/v202111/activity_group_service/create_activity_groups.py rename to examples/ad_manager/v202208/activity_group_service/create_activity_groups.py index 86a393a1..aacf9fcf 100755 --- a/examples/ad_manager/v202111/activity_group_service/create_activity_groups.py +++ b/examples/ad_manager/v202208/activity_group_service/create_activity_groups.py @@ -38,7 +38,7 @@ def main(client, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202111') + version='v202208') # Create a short-term activity group. short_term_activity_group = { diff --git a/examples/ad_manager/v202111/activity_group_service/get_active_activity_groups.py b/examples/ad_manager/v202208/activity_group_service/get_active_activity_groups.py similarity index 94% rename from examples/ad_manager/v202111/activity_group_service/get_active_activity_groups.py rename to examples/ad_manager/v202208/activity_group_service/get_active_activity_groups.py index 116c60ed..1d2d5c9f 100755 --- a/examples/ad_manager/v202111/activity_group_service/get_active_activity_groups.py +++ b/examples/ad_manager/v202208/activity_group_service/get_active_activity_groups.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202111') + 'ActivityGroupService', version='v202208') # Create a statement to select activity groups. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202111/activity_group_service/get_all_activity_groups.py b/examples/ad_manager/v202208/activity_group_service/get_all_activity_groups.py similarity index 94% rename from examples/ad_manager/v202111/activity_group_service/get_all_activity_groups.py rename to examples/ad_manager/v202208/activity_group_service/get_all_activity_groups.py index 29aed6cd..d715b9b1 100755 --- a/examples/ad_manager/v202111/activity_group_service/get_all_activity_groups.py +++ b/examples/ad_manager/v202208/activity_group_service/get_all_activity_groups.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. activity_group_service = client.GetService( - 'ActivityGroupService', version='v202111') + 'ActivityGroupService', version='v202208') # Create a statement to select activity groups. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of activity groups at a time, paging # through until all activity groups have been retrieved. diff --git a/examples/ad_manager/v202111/activity_group_service/update_activity_groups.py b/examples/ad_manager/v202208/activity_group_service/update_activity_groups.py similarity index 95% rename from examples/ad_manager/v202111/activity_group_service/update_activity_groups.py rename to examples/ad_manager/v202208/activity_group_service/update_activity_groups.py index a3614e73..d4f6e528 100755 --- a/examples/ad_manager/v202111/activity_group_service/update_activity_groups.py +++ b/examples/ad_manager/v202208/activity_group_service/update_activity_groups.py @@ -37,10 +37,10 @@ def main(client, activity_group_id, advertiser_company_id): # Initialize appropriate service. activity_group_service = client.GetService('ActivityGroupService', - version='v202111') + version='v202208') # Create statement object to select a single activity groups by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :activityGroupId') .WithBindVariable('activityGroupId', int(activity_group_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/activity_service/__init__.py b/examples/ad_manager/v202208/activity_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/activity_service/__init__.py rename to examples/ad_manager/v202208/activity_service/__init__.py diff --git a/examples/ad_manager/v202111/activity_service/create_activities.py b/examples/ad_manager/v202208/activity_service/create_activities.py similarity index 99% rename from examples/ad_manager/v202111/activity_service/create_activities.py rename to examples/ad_manager/v202208/activity_service/create_activities.py index eeac1eac..2a57c11b 100755 --- a/examples/ad_manager/v202111/activity_service/create_activities.py +++ b/examples/ad_manager/v202208/activity_service/create_activities.py @@ -37,7 +37,7 @@ def main(client, activity_group_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202111') + activity_service = client.GetService('ActivityService', version='v202208') # Create a daily visits activity. daily_visits_activity = { diff --git a/examples/ad_manager/v202111/activity_service/get_active_activities.py b/examples/ad_manager/v202208/activity_service/get_active_activities.py similarity index 96% rename from examples/ad_manager/v202111/activity_service/get_active_activities.py rename to examples/ad_manager/v202208/activity_service/get_active_activities.py index a43313a2..2d98022c 100755 --- a/examples/ad_manager/v202111/activity_service/get_active_activities.py +++ b/examples/ad_manager/v202208/activity_service/get_active_activities.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202111') + activity_service = client.GetService('ActivityService', version='v202208') # Create a statement to select activities. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202111/activity_service/get_all_activities.py b/examples/ad_manager/v202208/activity_service/get_all_activities.py similarity index 95% rename from examples/ad_manager/v202111/activity_service/get_all_activities.py rename to examples/ad_manager/v202208/activity_service/get_all_activities.py index 28c57afd..988cacce 100755 --- a/examples/ad_manager/v202111/activity_service/get_all_activities.py +++ b/examples/ad_manager/v202208/activity_service/get_all_activities.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202111') + activity_service = client.GetService('ActivityService', version='v202208') # Create a statement to select activities. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of activities at a time, paging # through until all activities have been retrieved. diff --git a/examples/ad_manager/v202111/activity_service/update_activities.py b/examples/ad_manager/v202208/activity_service/update_activities.py similarity index 96% rename from examples/ad_manager/v202111/activity_service/update_activities.py rename to examples/ad_manager/v202208/activity_service/update_activities.py index 50b98f2c..69eba66c 100755 --- a/examples/ad_manager/v202111/activity_service/update_activities.py +++ b/examples/ad_manager/v202208/activity_service/update_activities.py @@ -35,10 +35,10 @@ def main(client, activity_id): # Initialize appropriate service. - activity_service = client.GetService('ActivityService', version='v202111') + activity_service = client.GetService('ActivityService', version='v202208') # Create statement object to select one activity by ID to update. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :activityId') .WithBindVariable('activityId', int(activity_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/adjustment_service/create_forecast_adjustments.py b/examples/ad_manager/v202208/adjustment_service/create_forecast_adjustments.py similarity index 99% rename from examples/ad_manager/v202111/adjustment_service/create_forecast_adjustments.py rename to examples/ad_manager/v202208/adjustment_service/create_forecast_adjustments.py index d7e73355..74b2bae6 100755 --- a/examples/ad_manager/v202111/adjustment_service/create_forecast_adjustments.py +++ b/examples/ad_manager/v202208/adjustment_service/create_forecast_adjustments.py @@ -27,7 +27,7 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202111') + adjustment_service = client.GetService('AdjustmentService', version='v202208') # Create a new forecast adjustment for New Year's Day traffic. this_new_years = datetime.date(datetime.date.today().year, 1, 1) diff --git a/examples/ad_manager/v202111/adjustment_service/create_traffic_forecast_segments.py b/examples/ad_manager/v202208/adjustment_service/create_traffic_forecast_segments.py similarity index 98% rename from examples/ad_manager/v202111/adjustment_service/create_traffic_forecast_segments.py rename to examples/ad_manager/v202208/adjustment_service/create_traffic_forecast_segments.py index 7b0e4d65..58c8510b 100755 --- a/examples/ad_manager/v202111/adjustment_service/create_traffic_forecast_segments.py +++ b/examples/ad_manager/v202208/adjustment_service/create_traffic_forecast_segments.py @@ -25,8 +25,8 @@ def main(client): # Initialize the adjustment service and the network service. - adjustment_service = client.GetService('AdjustmentService', version='v202111') - network_service = client.GetService('NetworkService', version='v202111') + adjustment_service = client.GetService('AdjustmentService', version='v202208') + network_service = client.GetService('NetworkService', version='v202208') # Get the root ad unit id to target the whole site. current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202111/adjustment_service/get_all_forecast_adjustments.py b/examples/ad_manager/v202208/adjustment_service/get_all_forecast_adjustments.py similarity index 95% rename from examples/ad_manager/v202111/adjustment_service/get_all_forecast_adjustments.py rename to examples/ad_manager/v202208/adjustment_service/get_all_forecast_adjustments.py index 7b68b305..8b2958a3 100755 --- a/examples/ad_manager/v202111/adjustment_service/get_all_forecast_adjustments.py +++ b/examples/ad_manager/v202208/adjustment_service/get_all_forecast_adjustments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202111') + adjustment_service = client.GetService('AdjustmentService', version='v202208') # Create a statement to get all forecast adjustments. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small number of forecast adjustments at a time, paging # through until all forecast adjustments have been retrieved. diff --git a/examples/ad_manager/v202111/adjustment_service/get_all_traffic_forecast_segments.py b/examples/ad_manager/v202208/adjustment_service/get_all_traffic_forecast_segments.py similarity index 95% rename from examples/ad_manager/v202111/adjustment_service/get_all_traffic_forecast_segments.py rename to examples/ad_manager/v202208/adjustment_service/get_all_traffic_forecast_segments.py index ed1320fd..c676a836 100755 --- a/examples/ad_manager/v202111/adjustment_service/get_all_traffic_forecast_segments.py +++ b/examples/ad_manager/v202208/adjustment_service/get_all_traffic_forecast_segments.py @@ -22,10 +22,10 @@ def main(client): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202111') + adjustment_service = client.GetService('AdjustmentService', version='v202208') # Create a statement to get all traffic forecast segments. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small number of segments at a time, paging through until all # segments have been retrieved. diff --git a/examples/ad_manager/v202111/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py b/examples/ad_manager/v202208/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py similarity index 96% rename from examples/ad_manager/v202111/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py rename to examples/ad_manager/v202208/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py index 1e2c76eb..d7e3d465 100755 --- a/examples/ad_manager/v202111/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py +++ b/examples/ad_manager/v202208/adjustment_service/get_forecast_adjustments_for_traffic_forecast_segment.py @@ -24,11 +24,11 @@ def main(client, traffic_forecast_segment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202111') + adjustment_service = client.GetService('AdjustmentService', version='v202208') # Create a statement to get forecast adjustments for a given traffic forecast # segment id. - statement = ad_manager.StatementBuilder(version='v202111').Where( + statement = ad_manager.StatementBuilder(version='v202208').Where( 'trafficForecastSegmentId = :segmentId').WithBindVariable( 'segmentId', traffic_forecast_segment_id) diff --git a/examples/ad_manager/v202111/adjustment_service/update_forecast_adjustments.py b/examples/ad_manager/v202208/adjustment_service/update_forecast_adjustments.py similarity index 96% rename from examples/ad_manager/v202111/adjustment_service/update_forecast_adjustments.py rename to examples/ad_manager/v202208/adjustment_service/update_forecast_adjustments.py index 0aa19204..d78de2ca 100755 --- a/examples/ad_manager/v202111/adjustment_service/update_forecast_adjustments.py +++ b/examples/ad_manager/v202208/adjustment_service/update_forecast_adjustments.py @@ -24,12 +24,12 @@ def main(client, adjustment_id): # Initialize the adjustment service. - adjustment_service = client.GetService('AdjustmentService', version='v202111') + adjustment_service = client.GetService('AdjustmentService', version='v202208') # Create a statement to select a single forecast adjustment by id. statement = ( ad_manager.StatementBuilder( - version='v202111').Where('id = :id').WithBindVariable( + version='v202208').Where('id = :id').WithBindVariable( 'id', adjustment_id)) # Get the forecast adjustment. diff --git a/examples/ad_manager/v202111/audience_segment_service/__init__.py b/examples/ad_manager/v202208/audience_segment_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/audience_segment_service/__init__.py rename to examples/ad_manager/v202208/audience_segment_service/__init__.py diff --git a/examples/ad_manager/v202111/audience_segment_service/create_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/create_audience_segments.py similarity index 98% rename from examples/ad_manager/v202111/audience_segment_service/create_audience_segments.py rename to examples/ad_manager/v202208/audience_segment_service/create_audience_segments.py index e4e2b386..02157f32 100755 --- a/examples/ad_manager/v202111/audience_segment_service/create_audience_segments.py +++ b/examples/ad_manager/v202208/audience_segment_service/create_audience_segments.py @@ -30,8 +30,8 @@ def main(client, custom_targeting_key_id, custom_targeting_value_id): # Initialize appropriate services. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202111') - network_service = client.GetService('NetworkService', version='v202111') + 'AudienceSegmentService', version='v202208') + network_service = client.GetService('NetworkService', version='v202208') # Get the root ad unit ID used to target the entire network. root_ad_unit_id = ( diff --git a/examples/ad_manager/v202111/audience_segment_service/get_all_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/get_all_audience_segments.py similarity index 94% rename from examples/ad_manager/v202111/audience_segment_service/get_all_audience_segments.py rename to examples/ad_manager/v202208/audience_segment_service/get_all_audience_segments.py index d7769038..49469fc9 100755 --- a/examples/ad_manager/v202111/audience_segment_service/get_all_audience_segments.py +++ b/examples/ad_manager/v202208/audience_segment_service/get_all_audience_segments.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202111') + 'AudienceSegmentService', version='v202208') # Create a statement to select audience segments. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of audience segments at a time, paging # through until all audience segments have been retrieved. diff --git a/examples/ad_manager/v202111/audience_segment_service/get_first_party_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/get_first_party_audience_segments.py similarity index 94% rename from examples/ad_manager/v202111/audience_segment_service/get_first_party_audience_segments.py rename to examples/ad_manager/v202208/audience_segment_service/get_first_party_audience_segments.py index c6916a5c..0d0ef59c 100755 --- a/examples/ad_manager/v202111/audience_segment_service/get_first_party_audience_segments.py +++ b/examples/ad_manager/v202208/audience_segment_service/get_first_party_audience_segments.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202111') + 'AudienceSegmentService', version='v202208') # Create a statement to select audience segments. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('type = :type') .WithBindVariable('type', 'FIRST_PARTY')) diff --git a/examples/ad_manager/v202111/audience_segment_service/populate_first_party_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/populate_first_party_audience_segments.py similarity index 95% rename from examples/ad_manager/v202111/audience_segment_service/populate_first_party_audience_segments.py rename to examples/ad_manager/v202208/audience_segment_service/populate_first_party_audience_segments.py index 039baddb..b24eaf79 100755 --- a/examples/ad_manager/v202111/audience_segment_service/populate_first_party_audience_segments.py +++ b/examples/ad_manager/v202208/audience_segment_service/populate_first_party_audience_segments.py @@ -30,10 +30,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202111') + 'AudienceSegmentService', version='v202208') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202111/audience_segment_service/update_audience_segments.py b/examples/ad_manager/v202208/audience_segment_service/update_audience_segments.py similarity index 95% rename from examples/ad_manager/v202111/audience_segment_service/update_audience_segments.py rename to examples/ad_manager/v202208/audience_segment_service/update_audience_segments.py index ceb91153..c7b35584 100755 --- a/examples/ad_manager/v202111/audience_segment_service/update_audience_segments.py +++ b/examples/ad_manager/v202208/audience_segment_service/update_audience_segments.py @@ -29,10 +29,10 @@ def main(client, audience_segment_id): # Initialize appropriate service. audience_segment_service = client.GetService( - 'AudienceSegmentService', version='v202111') + 'AudienceSegmentService', version='v202208') # Create statement object to get the specified first party audience segment. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('Type = :type AND Id = :audience_segment_id') .WithBindVariable('audience_segment_id', int(audience_segment_id)) diff --git a/examples/ad_manager/v202111/cdn_configuration_service/__init__.py b/examples/ad_manager/v202208/cdn_configuration_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/cdn_configuration_service/__init__.py rename to examples/ad_manager/v202208/cdn_configuration_service/__init__.py diff --git a/examples/ad_manager/v202111/cdn_configuration_service/create_cdn_configurations.py b/examples/ad_manager/v202208/cdn_configuration_service/create_cdn_configurations.py similarity index 97% rename from examples/ad_manager/v202111/cdn_configuration_service/create_cdn_configurations.py rename to examples/ad_manager/v202208/cdn_configuration_service/create_cdn_configurations.py index 7b7a2050..8a84ccb8 100755 --- a/examples/ad_manager/v202111/cdn_configuration_service/create_cdn_configurations.py +++ b/examples/ad_manager/v202208/cdn_configuration_service/create_cdn_configurations.py @@ -27,7 +27,7 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202111') + version='v202208') # Create cdn config objects. # Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API. diff --git a/examples/ad_manager/v202111/cdn_configuration_service/get_all_cdn_configurations.py b/examples/ad_manager/v202208/cdn_configuration_service/get_all_cdn_configurations.py similarity index 93% rename from examples/ad_manager/v202111/cdn_configuration_service/get_all_cdn_configurations.py rename to examples/ad_manager/v202208/cdn_configuration_service/get_all_cdn_configurations.py index 97a40cd8..66277c26 100755 --- a/examples/ad_manager/v202111/cdn_configuration_service/get_all_cdn_configurations.py +++ b/examples/ad_manager/v202208/cdn_configuration_service/get_all_cdn_configurations.py @@ -26,10 +26,10 @@ def main(client): # Initialize appropriate service. cdn_config_service = client.GetService('CdnConfigurationService', - version='v202111') + version='v202208') # Create a statement to select cdn configurations. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small number of configs at a time, paging # through until all have been retrieved. diff --git a/examples/ad_manager/v202111/cms_metadata_service/activate_cms_metadata_values.py b/examples/ad_manager/v202208/cms_metadata_service/activate_cms_metadata_values.py similarity index 95% rename from examples/ad_manager/v202111/cms_metadata_service/activate_cms_metadata_values.py rename to examples/ad_manager/v202208/cms_metadata_service/activate_cms_metadata_values.py index ce56501d..13323c68 100755 --- a/examples/ad_manager/v202111/cms_metadata_service/activate_cms_metadata_values.py +++ b/examples/ad_manager/v202208/cms_metadata_service/activate_cms_metadata_values.py @@ -28,10 +28,10 @@ def main(client, cms_metadata_key_id): # Initialize appropriate service. cms_metadata_service = client.GetService('CmsMetadataService', - version='v202111') + version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('cmsKeyId = :cmsKeyId AND status = :status') .WithBindVariable('status', 'INACTIVE') .WithBindVariable('cmsKeyId', int(cms_metadata_key_id))) diff --git a/examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_keys.py b/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_keys.py similarity index 94% rename from examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_keys.py rename to examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_keys.py index 880b2da3..4e0987d4 100755 --- a/examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_keys.py +++ b/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_keys.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202111') + 'CmsMetadataService', version='v202208') # Create a statement to select CmsMetadataKeys. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of keys at a time, paging # through until all keys have been retrieved. diff --git a/examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_values.py b/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_values.py similarity index 94% rename from examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_values.py rename to examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_values.py index 9a97dab9..53ef18b5 100755 --- a/examples/ad_manager/v202111/cms_metadata_service/get_all_cms_metadata_values.py +++ b/examples/ad_manager/v202208/cms_metadata_service/get_all_cms_metadata_values.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202111') + 'CmsMetadataService', version='v202208') # Create a statement to select CmsMetadataValues. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of values at a time, paging # through until all values have been retrieved. diff --git a/examples/ad_manager/v202111/cms_metadata_service/get_cms_metadata_values_for_key.py b/examples/ad_manager/v202208/cms_metadata_service/get_cms_metadata_values_for_key.py similarity index 95% rename from examples/ad_manager/v202111/cms_metadata_service/get_cms_metadata_values_for_key.py rename to examples/ad_manager/v202208/cms_metadata_service/get_cms_metadata_values_for_key.py index e2df73f1..e54540f3 100755 --- a/examples/ad_manager/v202111/cms_metadata_service/get_cms_metadata_values_for_key.py +++ b/examples/ad_manager/v202208/cms_metadata_service/get_cms_metadata_values_for_key.py @@ -26,11 +26,11 @@ def main(client, cms_metadata_key_name): # Initialize appropriate service. cms_metadata_service = client.GetService( - 'CmsMetadataService', version='v202111') + 'CmsMetadataService', version='v202208') # Create a statement to select CmsMetadataValues for a particular key. statement = ( - ad_manager.StatementBuilder(version='v202111').Where( + ad_manager.StatementBuilder(version='v202208').Where( 'cmsKey = :cmsMetadataKeyName').WithBindVariable( 'cmsMetadataKeyName', cms_metadata_key_name)) diff --git a/examples/ad_manager/v202111/company_service/__init__.py b/examples/ad_manager/v202208/company_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/company_service/__init__.py rename to examples/ad_manager/v202208/company_service/__init__.py diff --git a/examples/ad_manager/v202111/company_service/create_companies.py b/examples/ad_manager/v202208/company_service/create_companies.py similarity index 99% rename from examples/ad_manager/v202111/company_service/create_companies.py rename to examples/ad_manager/v202208/company_service/create_companies.py index 842389d0..ed37a061 100755 --- a/examples/ad_manager/v202111/company_service/create_companies.py +++ b/examples/ad_manager/v202208/company_service/create_companies.py @@ -34,7 +34,7 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202111') + company_service = client.GetService('CompanyService', version='v202208') # Create company objects. companies = [ diff --git a/examples/ad_manager/v202111/company_service/get_advertisers.py b/examples/ad_manager/v202208/company_service/get_advertisers.py similarity index 96% rename from examples/ad_manager/v202111/company_service/get_advertisers.py rename to examples/ad_manager/v202208/company_service/get_advertisers.py index 0426f45c..d062063b 100755 --- a/examples/ad_manager/v202111/company_service/get_advertisers.py +++ b/examples/ad_manager/v202208/company_service/get_advertisers.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202111') + company_service = client.GetService('CompanyService', version='v202208') # Create a statement to select companies. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('type = :type') .WithBindVariable('type', 'ADVERTISER')) diff --git a/examples/ad_manager/v202111/company_service/get_all_companies.py b/examples/ad_manager/v202208/company_service/get_all_companies.py similarity index 95% rename from examples/ad_manager/v202111/company_service/get_all_companies.py rename to examples/ad_manager/v202208/company_service/get_all_companies.py index d585fa25..0c32bedc 100755 --- a/examples/ad_manager/v202111/company_service/get_all_companies.py +++ b/examples/ad_manager/v202208/company_service/get_all_companies.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202111') + company_service = client.GetService('CompanyService', version='v202208') # Create a statement to select companies. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of companies at a time, paging # through until all companies have been retrieved. diff --git a/examples/ad_manager/v202111/company_service/update_companies.py b/examples/ad_manager/v202208/company_service/update_companies.py similarity index 96% rename from examples/ad_manager/v202111/company_service/update_companies.py rename to examples/ad_manager/v202208/company_service/update_companies.py index 3363cecf..e141582b 100755 --- a/examples/ad_manager/v202111/company_service/update_companies.py +++ b/examples/ad_manager/v202208/company_service/update_companies.py @@ -35,10 +35,10 @@ def main(client, company_id): # Initialize appropriate service. - company_service = client.GetService('CompanyService', version='v202111') + company_service = client.GetService('CompanyService', version='v202208') # Create statement object to only select a single company by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .WithBindVariable('id', int(company_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/contact_service/__init__.py b/examples/ad_manager/v202208/contact_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/contact_service/__init__.py rename to examples/ad_manager/v202208/contact_service/__init__.py diff --git a/examples/ad_manager/v202111/contact_service/create_contacts.py b/examples/ad_manager/v202208/contact_service/create_contacts.py similarity index 99% rename from examples/ad_manager/v202111/contact_service/create_contacts.py rename to examples/ad_manager/v202208/contact_service/create_contacts.py index c6757179..744400af 100755 --- a/examples/ad_manager/v202111/contact_service/create_contacts.py +++ b/examples/ad_manager/v202208/contact_service/create_contacts.py @@ -40,7 +40,7 @@ def main(client, advertiser_company_id, agency_company_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202111') + contact_service = client.GetService('ContactService', version='v202208') # Create an advertiser contact. advertiser_contact = { diff --git a/examples/ad_manager/v202111/contact_service/get_all_contacts.py b/examples/ad_manager/v202208/contact_service/get_all_contacts.py similarity index 95% rename from examples/ad_manager/v202111/contact_service/get_all_contacts.py rename to examples/ad_manager/v202208/contact_service/get_all_contacts.py index b97d9bd7..5bef053f 100755 --- a/examples/ad_manager/v202111/contact_service/get_all_contacts.py +++ b/examples/ad_manager/v202208/contact_service/get_all_contacts.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202111') + contact_service = client.GetService('ContactService', version='v202208') # Create a statement to select contacts. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of contacts at a time, paging # through until all contacts have been retrieved. diff --git a/examples/ad_manager/v202111/contact_service/get_uninvited_contacts.py b/examples/ad_manager/v202208/contact_service/get_uninvited_contacts.py similarity index 96% rename from examples/ad_manager/v202111/contact_service/get_uninvited_contacts.py rename to examples/ad_manager/v202208/contact_service/get_uninvited_contacts.py index 2efb4d9d..7cb80324 100755 --- a/examples/ad_manager/v202111/contact_service/get_uninvited_contacts.py +++ b/examples/ad_manager/v202208/contact_service/get_uninvited_contacts.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202111') + contact_service = client.GetService('ContactService', version='v202208') # Create a statement to select contacts. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('status = :status') .WithBindVariable('status', 'UNINVITED')) diff --git a/examples/ad_manager/v202111/contact_service/update_contacts.py b/examples/ad_manager/v202208/contact_service/update_contacts.py similarity index 96% rename from examples/ad_manager/v202111/contact_service/update_contacts.py rename to examples/ad_manager/v202208/contact_service/update_contacts.py index 94e69a1a..8e45be57 100755 --- a/examples/ad_manager/v202111/contact_service/update_contacts.py +++ b/examples/ad_manager/v202208/contact_service/update_contacts.py @@ -35,10 +35,10 @@ def main(client, contact_id): # Initialize appropriate service. - contact_service = client.GetService('ContactService', version='v202111') + contact_service = client.GetService('ContactService', version='v202208') # Create statement object to select the single contact by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .WithBindVariable('id', int(contact_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/content_service/__init__.py b/examples/ad_manager/v202208/content_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/content_service/__init__.py rename to examples/ad_manager/v202208/content_service/__init__.py diff --git a/examples/ad_manager/v202111/content_service/get_all_content.py b/examples/ad_manager/v202208/content_service/get_all_content.py similarity index 96% rename from examples/ad_manager/v202111/content_service/get_all_content.py rename to examples/ad_manager/v202208/content_service/get_all_content.py index 4e232f5e..43424a92 100755 --- a/examples/ad_manager/v202111/content_service/get_all_content.py +++ b/examples/ad_manager/v202208/content_service/get_all_content.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202111') + content_service = client.GetService('ContentService', version='v202208') # Create a statement to select content. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of content at a time, paging # through until all content have been retrieved. diff --git a/examples/ad_manager/v202111/content_service/get_recently_modified_content.py b/examples/ad_manager/v202208/content_service/get_recently_modified_content.py similarity index 97% rename from examples/ad_manager/v202111/content_service/get_recently_modified_content.py rename to examples/ad_manager/v202208/content_service/get_recently_modified_content.py index 21009e0b..5a8e8521 100755 --- a/examples/ad_manager/v202111/content_service/get_recently_modified_content.py +++ b/examples/ad_manager/v202208/content_service/get_recently_modified_content.py @@ -26,7 +26,7 @@ def main(client): # Initialize appropriate service. - content_service = client.GetService('ContentService', version='v202111') + content_service = client.GetService('ContentService', version='v202208') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) @@ -35,7 +35,7 @@ def main(client): # lastModifiedDateTime. Changes to content bundle associations will update # the lastModifiedDateTime, but CMS metadata changes may not change the # lastModifiedDateTime. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202111/creative_service/__init__.py b/examples/ad_manager/v202208/creative_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/creative_service/__init__.py rename to examples/ad_manager/v202208/creative_service/__init__.py diff --git a/examples/ad_manager/v202111/creative_service/copy_image_creatives.py b/examples/ad_manager/v202208/creative_service/copy_image_creatives.py similarity index 96% rename from examples/ad_manager/v202111/creative_service/copy_image_creatives.py rename to examples/ad_manager/v202208/creative_service/copy_image_creatives.py index 6debb319..afabd7ef 100755 --- a/examples/ad_manager/v202111/creative_service/copy_image_creatives.py +++ b/examples/ad_manager/v202208/creative_service/copy_image_creatives.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202111') + creative_service = client.GetService('CreativeService', version='v202208') # Create a statement to get the image creative. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', CREATIVE_ID)) diff --git a/examples/ad_manager/v202111/creative_service/create_creative_from_template.py b/examples/ad_manager/v202208/creative_service/create_creative_from_template.py similarity index 99% rename from examples/ad_manager/v202111/creative_service/create_creative_from_template.py rename to examples/ad_manager/v202208/creative_service/create_creative_from_template.py index b08d9fbb..65972efd 100755 --- a/examples/ad_manager/v202111/creative_service/create_creative_from_template.py +++ b/examples/ad_manager/v202208/creative_service/create_creative_from_template.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202111') + creative_service = client.GetService('CreativeService', version='v202208') # Use the image banner with optional third party tracking template. creative_template_id = '10000680' diff --git a/examples/ad_manager/v202111/creative_service/create_creatives.py b/examples/ad_manager/v202208/creative_service/create_creatives.py similarity index 99% rename from examples/ad_manager/v202111/creative_service/create_creatives.py rename to examples/ad_manager/v202208/creative_service/create_creatives.py index 86d4827f..d5ed4be4 100755 --- a/examples/ad_manager/v202111/creative_service/create_creatives.py +++ b/examples/ad_manager/v202208/creative_service/create_creatives.py @@ -39,7 +39,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202111') + creative_service = client.GetService('CreativeService', version='v202208') # Create creative objects. creatives = [] diff --git a/examples/ad_manager/v202111/creative_service/create_custom_creative.py b/examples/ad_manager/v202208/creative_service/create_custom_creative.py similarity index 99% rename from examples/ad_manager/v202111/creative_service/create_custom_creative.py rename to examples/ad_manager/v202208/creative_service/create_custom_creative.py index a4adc9e8..a793a207 100755 --- a/examples/ad_manager/v202111/creative_service/create_custom_creative.py +++ b/examples/ad_manager/v202208/creative_service/create_custom_creative.py @@ -40,7 +40,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202111') + creative_service = client.GetService('CreativeService', version='v202208') # Get the image data for the creative. image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data', diff --git a/examples/ad_manager/v202111/creative_service/create_native_creative.py b/examples/ad_manager/v202208/creative_service/create_native_creative.py similarity index 99% rename from examples/ad_manager/v202111/creative_service/create_native_creative.py rename to examples/ad_manager/v202208/creative_service/create_native_creative.py index ef230835..08fe41cd 100755 --- a/examples/ad_manager/v202111/creative_service/create_native_creative.py +++ b/examples/ad_manager/v202208/creative_service/create_native_creative.py @@ -45,7 +45,7 @@ def main(client, advertiser_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202111') + creative_service = client.GetService('CreativeService', version='v202208') # Use the system defined native app install creative template. creative_template_id = '10004400' diff --git a/examples/ad_manager/v202208/creative_service/create_video_creatives.py b/examples/ad_manager/v202208/creative_service/create_video_creatives.py new file mode 100755 index 00000000..c3af5588 --- /dev/null +++ b/examples/ad_manager/v202208/creative_service/create_video_creatives.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# +# Copyright 2015 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 code example creates a new video creative for a given advertiser. + +To determine which companies are advertisers, run get_advertisers.py. +To determine which creatives already exist, run get_all_creatives.py. + +The LoadFromStorage method is pulling credentials and properties from a +"googleads.yaml" file. By default, it looks for this file in your home +directory. For more information, see the "Caching authentication information" +section of our README. +""" + +import uuid + +# Import appropriate modules from the client library. +from googleads import ad_manager + +# Set id of the advertiser (company) that the creative will be assigned to. +ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' + + +def main(client, advertiser_id): + # Initialize appropriate service. + creative_service = client.GetService('CreativeService', version='v202208') + + # Create a video creative. + creative = { + 'xsi_type': 'VideoCreative', + 'name': 'Video Creative #%s' % uuid.uuid4(), + 'advertiserId': advertiser_id, + 'size': {'width': '640', 'height': '360', 'isAspectRatio': False}, + 'destinationUrl': 'https://google.com', + 'duration': '115000', + 'videoSourceUrl': ( + 'https://storage.googleapis.com/interactive-media-ads/media/' + 'android.mp4') + } + + # Call service to create the creative. + creative = creative_service.createCreatives([creative])[0] + + # Display results. + print('Video creative with id "%s" and name "%s" was created and can be ' + 'previewed at:\n%s.' + % (creative['id'], creative['name'], creative['vastPreviewUrl'])) + + +if __name__ == '__main__': + # Initialize client object. + ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() + main(ad_manager_client, ADVERTISER_ID) diff --git a/examples/ad_manager/v202111/creative_service/get_all_creatives.py b/examples/ad_manager/v202208/creative_service/get_all_creatives.py similarity index 95% rename from examples/ad_manager/v202111/creative_service/get_all_creatives.py rename to examples/ad_manager/v202208/creative_service/get_all_creatives.py index 1786a57a..6598c26a 100755 --- a/examples/ad_manager/v202111/creative_service/get_all_creatives.py +++ b/examples/ad_manager/v202208/creative_service/get_all_creatives.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202111') + creative_service = client.GetService('CreativeService', version='v202208') # Create a statement to select creatives. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of creatives at a time, paging # through until all creatives have been retrieved. diff --git a/examples/ad_manager/v202111/creative_service/get_image_creatives.py b/examples/ad_manager/v202208/creative_service/get_image_creatives.py similarity index 96% rename from examples/ad_manager/v202111/creative_service/get_image_creatives.py rename to examples/ad_manager/v202208/creative_service/get_image_creatives.py index 005cacc9..4f035319 100755 --- a/examples/ad_manager/v202111/creative_service/get_image_creatives.py +++ b/examples/ad_manager/v202208/creative_service/get_image_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202111') + creative_service = client.GetService('CreativeService', version='v202208') # Create a statement to select creatives. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('creativeType = :creativeType') .WithBindVariable('creativeType', 'ImageCreative')) diff --git a/examples/ad_manager/v202111/creative_service/update_creatives.py b/examples/ad_manager/v202208/creative_service/update_creatives.py similarity index 97% rename from examples/ad_manager/v202111/creative_service/update_creatives.py rename to examples/ad_manager/v202208/creative_service/update_creatives.py index bfca6f4a..e17c9840 100755 --- a/examples/ad_manager/v202111/creative_service/update_creatives.py +++ b/examples/ad_manager/v202208/creative_service/update_creatives.py @@ -34,10 +34,10 @@ def main(client, image_creative_id): # Initialize appropriate service. - creative_service = client.GetService('CreativeService', version='v202111') + creative_service = client.GetService('CreativeService', version='v202208') # Create statement object to get the creative by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('creativeType = :type AND id = :id') .WithBindVariable('type', 'ImageCreative') .WithBindVariable('id', int(image_creative_id)) diff --git a/examples/ad_manager/v202111/creative_set_service/__init__.py b/examples/ad_manager/v202208/creative_set_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/creative_set_service/__init__.py rename to examples/ad_manager/v202208/creative_set_service/__init__.py diff --git a/examples/ad_manager/v202111/creative_set_service/associate_creative_set_to_line_item.py b/examples/ad_manager/v202208/creative_set_service/associate_creative_set_to_line_item.py similarity index 96% rename from examples/ad_manager/v202111/creative_set_service/associate_creative_set_to_line_item.py rename to examples/ad_manager/v202208/creative_set_service/associate_creative_set_to_line_item.py index 37c96287..3551bb42 100755 --- a/examples/ad_manager/v202111/creative_set_service/associate_creative_set_to_line_item.py +++ b/examples/ad_manager/v202208/creative_set_service/associate_creative_set_to_line_item.py @@ -37,7 +37,7 @@ def main(client, creative_set_id, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202111') + 'LineItemCreativeAssociationService', version='v202208') # Create LICA for a creative set. lica = {'creativeSetId': creative_set_id, 'lineItemId': line_item_id} diff --git a/examples/ad_manager/v202111/creative_set_service/create_creative_set.py b/examples/ad_manager/v202208/creative_set_service/create_creative_set.py similarity index 97% rename from examples/ad_manager/v202111/creative_set_service/create_creative_set.py rename to examples/ad_manager/v202208/creative_set_service/create_creative_set.py index 842c45df..04598453 100755 --- a/examples/ad_manager/v202111/creative_set_service/create_creative_set.py +++ b/examples/ad_manager/v202208/creative_set_service/create_creative_set.py @@ -38,7 +38,7 @@ def main(client, master_creative_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202111') + version='v202208') # Create creative set objects. creative_set = {'name': 'Creative set #%s' % uuid.uuid4(), diff --git a/examples/ad_manager/v202111/creative_set_service/get_all_creative_sets.py b/examples/ad_manager/v202208/creative_set_service/get_all_creative_sets.py similarity index 94% rename from examples/ad_manager/v202111/creative_set_service/get_all_creative_sets.py rename to examples/ad_manager/v202208/creative_set_service/get_all_creative_sets.py index 855ee450..9c051afb 100755 --- a/examples/ad_manager/v202111/creative_set_service/get_all_creative_sets.py +++ b/examples/ad_manager/v202208/creative_set_service/get_all_creative_sets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202111') + 'CreativeSetService', version='v202208') # Create a statement to select creative sets. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of creative sets at a time, paging # through until all creative sets have been retrieved. diff --git a/examples/ad_manager/v202111/creative_set_service/get_creative_sets_for_master_creative.py b/examples/ad_manager/v202208/creative_set_service/get_creative_sets_for_master_creative.py similarity index 94% rename from examples/ad_manager/v202111/creative_set_service/get_creative_sets_for_master_creative.py rename to examples/ad_manager/v202208/creative_set_service/get_creative_sets_for_master_creative.py index b63f5cd0..ae1617b7 100755 --- a/examples/ad_manager/v202111/creative_set_service/get_creative_sets_for_master_creative.py +++ b/examples/ad_manager/v202208/creative_set_service/get_creative_sets_for_master_creative.py @@ -25,9 +25,9 @@ def main(client, master_creative_id): # Initialize appropriate service. creative_set_service = client.GetService( - 'CreativeSetService', version='v202111') + 'CreativeSetService', version='v202208') # Create a statement to select creative sets. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('masterCreativeId = :masterCreativeId') .WithBindVariable('masterCreativeId', master_creative_id)) diff --git a/examples/ad_manager/v202111/creative_set_service/update_creative_set.py b/examples/ad_manager/v202208/creative_set_service/update_creative_set.py similarity index 95% rename from examples/ad_manager/v202111/creative_set_service/update_creative_set.py rename to examples/ad_manager/v202208/creative_set_service/update_creative_set.py index a4e442ec..67059879 100755 --- a/examples/ad_manager/v202111/creative_set_service/update_creative_set.py +++ b/examples/ad_manager/v202208/creative_set_service/update_creative_set.py @@ -37,10 +37,10 @@ def main(client, creative_set_id, companion_creative_id): # Initialize appropriate service. creative_set_service = client.GetService('CreativeSetService', - version='v202111') + version='v202208') # Create statement to select a single creative set by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :creativeSetId') .WithBindVariable('creativeSetId', int(creative_set_id))) diff --git a/examples/ad_manager/v202111/creative_template_service/__init__.py b/examples/ad_manager/v202208/creative_template_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/creative_template_service/__init__.py rename to examples/ad_manager/v202208/creative_template_service/__init__.py diff --git a/examples/ad_manager/v202111/creative_template_service/get_all_creative_templates.py b/examples/ad_manager/v202208/creative_template_service/get_all_creative_templates.py similarity index 94% rename from examples/ad_manager/v202111/creative_template_service/get_all_creative_templates.py rename to examples/ad_manager/v202208/creative_template_service/get_all_creative_templates.py index 43843b99..59f506e7 100755 --- a/examples/ad_manager/v202111/creative_template_service/get_all_creative_templates.py +++ b/examples/ad_manager/v202208/creative_template_service/get_all_creative_templates.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202111') + 'CreativeTemplateService', version='v202208') # Create a statement to select creative templates. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of creative templates at a time, paging # through until all creative templates have been retrieved. diff --git a/examples/ad_manager/v202111/creative_template_service/get_system_defined_creative_templates.py b/examples/ad_manager/v202208/creative_template_service/get_system_defined_creative_templates.py similarity index 94% rename from examples/ad_manager/v202111/creative_template_service/get_system_defined_creative_templates.py rename to examples/ad_manager/v202208/creative_template_service/get_system_defined_creative_templates.py index 1f4cab4e..e6becfcb 100755 --- a/examples/ad_manager/v202111/creative_template_service/get_system_defined_creative_templates.py +++ b/examples/ad_manager/v202208/creative_template_service/get_system_defined_creative_templates.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_template_service = client.GetService( - 'CreativeTemplateService', version='v202111') + 'CreativeTemplateService', version='v202208') # Create a statement to select creative templates. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('type = :type') .WithBindVariable('type', 'SYSTEM_DEFINED')) diff --git a/examples/ad_manager/v202111/creative_wrapper_service/create_creative_wrappers.py b/examples/ad_manager/v202208/creative_wrapper_service/create_creative_wrappers.py similarity index 97% rename from examples/ad_manager/v202111/creative_wrapper_service/create_creative_wrappers.py rename to examples/ad_manager/v202208/creative_wrapper_service/create_creative_wrappers.py index 010f11b3..00dd5610 100755 --- a/examples/ad_manager/v202111/creative_wrapper_service/create_creative_wrappers.py +++ b/examples/ad_manager/v202208/creative_wrapper_service/create_creative_wrappers.py @@ -37,7 +37,7 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202111') + version='v202208') # Create creative wrapper objects. creative_wrapper = { diff --git a/examples/ad_manager/v202111/creative_wrapper_service/deactivate_creative_wrapper.py b/examples/ad_manager/v202208/creative_wrapper_service/deactivate_creative_wrapper.py similarity index 95% rename from examples/ad_manager/v202111/creative_wrapper_service/deactivate_creative_wrapper.py rename to examples/ad_manager/v202208/creative_wrapper_service/deactivate_creative_wrapper.py index 64fcb18a..1d4af2e2 100755 --- a/examples/ad_manager/v202111/creative_wrapper_service/deactivate_creative_wrapper.py +++ b/examples/ad_manager/v202208/creative_wrapper_service/deactivate_creative_wrapper.py @@ -33,10 +33,10 @@ def main(client, label_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202111') + version='v202208') # Create a query to select the active creative wrappers for the given label. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('status = :status AND labelId = :labelId') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202111/creative_wrapper_service/get_active_creative_wrappers.py b/examples/ad_manager/v202208/creative_wrapper_service/get_active_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202111/creative_wrapper_service/get_active_creative_wrappers.py rename to examples/ad_manager/v202208/creative_wrapper_service/get_active_creative_wrappers.py index 9d01c7c2..ba32968c 100755 --- a/examples/ad_manager/v202111/creative_wrapper_service/get_active_creative_wrappers.py +++ b/examples/ad_manager/v202208/creative_wrapper_service/get_active_creative_wrappers.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202111') + 'CreativeWrapperService', version='v202208') # Create a statement to select creative wrappers. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202111/creative_wrapper_service/get_all_creative_wrappers.py b/examples/ad_manager/v202208/creative_wrapper_service/get_all_creative_wrappers.py similarity index 94% rename from examples/ad_manager/v202111/creative_wrapper_service/get_all_creative_wrappers.py rename to examples/ad_manager/v202208/creative_wrapper_service/get_all_creative_wrappers.py index 93654fe9..df2b47c0 100755 --- a/examples/ad_manager/v202111/creative_wrapper_service/get_all_creative_wrappers.py +++ b/examples/ad_manager/v202208/creative_wrapper_service/get_all_creative_wrappers.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. creative_wrapper_service = client.GetService( - 'CreativeWrapperService', version='v202111') + 'CreativeWrapperService', version='v202208') # Create a statement to select creative wrappers. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of creative wrappers at a time, paging # through until all creative wrappers have been retrieved. diff --git a/examples/ad_manager/v202111/creative_wrapper_service/update_creative_wrappers.py b/examples/ad_manager/v202208/creative_wrapper_service/update_creative_wrappers.py similarity index 95% rename from examples/ad_manager/v202111/creative_wrapper_service/update_creative_wrappers.py rename to examples/ad_manager/v202208/creative_wrapper_service/update_creative_wrappers.py index 9ea9d229..7cd854ab 100755 --- a/examples/ad_manager/v202111/creative_wrapper_service/update_creative_wrappers.py +++ b/examples/ad_manager/v202208/creative_wrapper_service/update_creative_wrappers.py @@ -36,10 +36,10 @@ def main(client, creative_wrapper_id): # Initialize appropriate service. creative_wrapper_service = client.GetService('CreativeWrapperService', - version='v202111') + version='v202208') # Create statement to get a creative wrapper by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :creativeWrapperId') .WithBindVariable('creativeWrapperId', int(creative_wrapper_id))) diff --git a/examples/ad_manager/v202111/custom_field_service/__init__.py b/examples/ad_manager/v202208/custom_field_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/custom_field_service/__init__.py rename to examples/ad_manager/v202208/custom_field_service/__init__.py diff --git a/examples/ad_manager/v202111/custom_field_service/create_custom_field_options.py b/examples/ad_manager/v202208/custom_field_service/create_custom_field_options.py similarity index 97% rename from examples/ad_manager/v202111/custom_field_service/create_custom_field_options.py rename to examples/ad_manager/v202208/custom_field_service/create_custom_field_options.py index 7f607a92..9533b048 100755 --- a/examples/ad_manager/v202111/custom_field_service/create_custom_field_options.py +++ b/examples/ad_manager/v202208/custom_field_service/create_custom_field_options.py @@ -38,7 +38,7 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202111') + 'CustomFieldService', version='v202208') # Create custom field options. custom_field_options = [ diff --git a/examples/ad_manager/v202111/custom_field_service/create_custom_fields.py b/examples/ad_manager/v202208/custom_field_service/create_custom_fields.py similarity index 97% rename from examples/ad_manager/v202111/custom_field_service/create_custom_fields.py rename to examples/ad_manager/v202208/custom_field_service/create_custom_fields.py index 55ef95e7..ece4fb1b 100755 --- a/examples/ad_manager/v202111/custom_field_service/create_custom_fields.py +++ b/examples/ad_manager/v202208/custom_field_service/create_custom_fields.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202111') + 'CustomFieldService', version='v202208') # Create custom field objects. custom_fields = [ diff --git a/examples/ad_manager/v202111/custom_field_service/deactivate_all_line_item_custom_fields.py b/examples/ad_manager/v202208/custom_field_service/deactivate_all_line_item_custom_fields.py similarity index 95% rename from examples/ad_manager/v202111/custom_field_service/deactivate_all_line_item_custom_fields.py rename to examples/ad_manager/v202208/custom_field_service/deactivate_all_line_item_custom_fields.py index 01dde679..f59fb472 100755 --- a/examples/ad_manager/v202111/custom_field_service/deactivate_all_line_item_custom_fields.py +++ b/examples/ad_manager/v202208/custom_field_service/deactivate_all_line_item_custom_fields.py @@ -33,11 +33,11 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202111') + 'CustomFieldService', version='v202208') # Create statement to select only active custom fields that apply to # line items. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('entityType = :entityType and isActive = :isActive') .WithBindVariable('entityType', 'LINE_ITEM') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202111/custom_field_service/get_all_custom_fields.py b/examples/ad_manager/v202208/custom_field_service/get_all_custom_fields.py similarity index 94% rename from examples/ad_manager/v202111/custom_field_service/get_all_custom_fields.py rename to examples/ad_manager/v202208/custom_field_service/get_all_custom_fields.py index 6c562042..c406a4eb 100755 --- a/examples/ad_manager/v202111/custom_field_service/get_all_custom_fields.py +++ b/examples/ad_manager/v202208/custom_field_service/get_all_custom_fields.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202111') + 'CustomFieldService', version='v202208') # Create a statement to select custom fields. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of custom fields at a time, paging # through until all custom fields have been retrieved. diff --git a/examples/ad_manager/v202111/custom_field_service/get_custom_fields_for_line_items.py b/examples/ad_manager/v202208/custom_field_service/get_custom_fields_for_line_items.py similarity index 94% rename from examples/ad_manager/v202111/custom_field_service/get_custom_fields_for_line_items.py rename to examples/ad_manager/v202208/custom_field_service/get_custom_fields_for_line_items.py index d1efabea..1c86aeff 100755 --- a/examples/ad_manager/v202111/custom_field_service/get_custom_fields_for_line_items.py +++ b/examples/ad_manager/v202208/custom_field_service/get_custom_fields_for_line_items.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202111') + 'CustomFieldService', version='v202208') # Create a statement to select custom fields. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('entityType = :entityType') .WithBindVariable('entityType', 'LINE_ITEM')) diff --git a/examples/ad_manager/v202111/custom_field_service/set_line_item_custom_field_value.py b/examples/ad_manager/v202208/custom_field_service/set_line_item_custom_field_value.py similarity index 97% rename from examples/ad_manager/v202111/custom_field_service/set_line_item_custom_field_value.py rename to examples/ad_manager/v202208/custom_field_service/set_line_item_custom_field_value.py index 6546b508..bd5820bb 100755 --- a/examples/ad_manager/v202111/custom_field_service/set_line_item_custom_field_value.py +++ b/examples/ad_manager/v202208/custom_field_service/set_line_item_custom_field_value.py @@ -42,12 +42,12 @@ def main(client, custom_field_id, drop_down_custom_field_id, custom_field_option_id, line_item_id): # Initialize appropriate services. custom_field_service = client.GetService( - 'CustomFieldService', version='v202111') + 'CustomFieldService', version='v202208') - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') # Create statement to get a custom field. - custom_field_statement = (ad_manager.StatementBuilder(version='v202111') + custom_field_statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :customFieldId') .WithBindVariable('customFieldId', custom_field_id) .Limit(1)) @@ -58,7 +58,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, # Create statement to get a drop down custom field. drop_down_custom_field_statement = ( - ad_manager.StatementBuilder(version='v202111') + ad_manager.StatementBuilder(version='v202208') .Where('id = :dropDownCustomFieldId') .WithBindVariable('dropDownCustomFieldId', drop_down_custom_field_id) .Limit(1)) @@ -68,7 +68,7 @@ def main(client, custom_field_id, drop_down_custom_field_id, drop_down_custom_field_statement.ToStatement())['results'][0] # Create statement to get a line item. - line_item_statement = (ad_manager.StatementBuilder(version='v202111') + line_item_statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :lineItemId') .WithBindVariable('lineItemId', line_item_id) .Limit(1)) diff --git a/examples/ad_manager/v202111/custom_field_service/update_custom_fields.py b/examples/ad_manager/v202208/custom_field_service/update_custom_fields.py similarity index 95% rename from examples/ad_manager/v202111/custom_field_service/update_custom_fields.py rename to examples/ad_manager/v202208/custom_field_service/update_custom_fields.py index e1a71a63..de42faac 100755 --- a/examples/ad_manager/v202111/custom_field_service/update_custom_fields.py +++ b/examples/ad_manager/v202208/custom_field_service/update_custom_fields.py @@ -36,10 +36,10 @@ def main(client, custom_field_id): # Initialize appropriate service. custom_field_service = client.GetService( - 'CustomFieldService', version='v202111') + 'CustomFieldService', version='v202208') # Create statement to get a custom field. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :customFieldId') .WithBindVariable('customFieldId', int(custom_field_id))) diff --git a/examples/ad_manager/v202111/custom_targeting_service/__init__.py b/examples/ad_manager/v202208/custom_targeting_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/custom_targeting_service/__init__.py rename to examples/ad_manager/v202208/custom_targeting_service/__init__.py diff --git a/examples/ad_manager/v202111/custom_targeting_service/create_custom_targeting_keys_and_values.py b/examples/ad_manager/v202208/custom_targeting_service/create_custom_targeting_keys_and_values.py similarity index 98% rename from examples/ad_manager/v202111/custom_targeting_service/create_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202208/custom_targeting_service/create_custom_targeting_keys_and_values.py index 85bc00db..a9f4adaf 100755 --- a/examples/ad_manager/v202111/custom_targeting_service/create_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202208/custom_targeting_service/create_custom_targeting_keys_and_values.py @@ -35,7 +35,7 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202111') + 'CustomTargetingService', version='v202208') # Create custom targeting key objects. keys = [ diff --git a/examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_keys.py b/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_keys.py rename to examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_keys.py index 9e1e1679..892e232f 100755 --- a/examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_keys.py +++ b/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_keys.py @@ -36,9 +36,9 @@ def main(client, key_name): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202111') + 'CustomTargetingService', version='v202208') - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('name = :name') .WithBindVariable('name', key_name)) @@ -51,7 +51,7 @@ def main(client, key_name): if 'results' in response and len(response['results']): key_ids = [str(key['id']) for key in response['results']] action = {'xsi_type': 'DeleteCustomTargetingKeys'} - key_statement = (ad_manager.StatementBuilder(version='v202111') + key_statement = (ad_manager.StatementBuilder(version='v202208') .Where('id IN (%s)' % ', '.join(key_ids))) # Delete custom targeting keys. diff --git a/examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_values.py b/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_values.py rename to examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_values.py index 442d81fa..61049edd 100755 --- a/examples/ad_manager/v202111/custom_targeting_service/delete_custom_targeting_values.py +++ b/examples/ad_manager/v202208/custom_targeting_service/delete_custom_targeting_values.py @@ -36,9 +36,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202111') + 'CustomTargetingService', version='v202208') - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', key_id)) @@ -51,7 +51,7 @@ def main(client, key_id): if 'results' in response and len(response['results']): value_ids = [str(value['id']) for value in response['results']] action = {'xsi_type': 'DeleteCustomTargetingValues'} - value_statement = (ad_manager.StatementBuilder(version='v202111') + value_statement = (ad_manager.StatementBuilder(version='v202208') .Where('customTargetingKeyId = :keyId ' 'AND id IN (%s)' % ', '.join(value_ids)) .WithBindVariable('keyId', key_id)) diff --git a/examples/ad_manager/v202111/custom_targeting_service/get_all_custom_targeting_keys_and_values.py b/examples/ad_manager/v202208/custom_targeting_service/get_all_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202111/custom_targeting_service/get_all_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202208/custom_targeting_service/get_all_custom_targeting_keys_and_values.py index fc375b92..dd10dd0e 100755 --- a/examples/ad_manager/v202111/custom_targeting_service/get_all_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202208/custom_targeting_service/get_all_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202111') + 'CustomTargetingService', version='v202208') # Create statement to get all targeting keys. - targeting_key_statement = ad_manager.StatementBuilder(version='v202111') + targeting_key_statement = ad_manager.StatementBuilder(version='v202208') all_keys = [] @@ -42,7 +42,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('customTargetingKeyId IN (%s)' % ', '.join([str(key['id']) for key in all_keys]))) diff --git a/examples/ad_manager/v202111/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py b/examples/ad_manager/v202208/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py similarity index 95% rename from examples/ad_manager/v202111/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py rename to examples/ad_manager/v202208/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py index b6674a32..8b7657b1 100755 --- a/examples/ad_manager/v202111/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py +++ b/examples/ad_manager/v202208/custom_targeting_service/get_predefined_custom_targeting_keys_and_values.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202111') + 'CustomTargetingService', version='v202208') # Create statement to get targeting keys for predefined values. - targeting_key_statement = (ad_manager.StatementBuilder(version='v202111') + targeting_key_statement = (ad_manager.StatementBuilder(version='v202208') .Where('type = :type') .WithBindVariable('type', 'PREDEFINED')) @@ -44,7 +44,7 @@ def main(client): if all_keys: # Create a statement to select custom targeting values. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('customTargetingKeyId IN (:ids)') .WithBindVariable('ids', [key['id'] for key in all_keys])) diff --git a/examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_keys.py b/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_keys.py similarity index 95% rename from examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_keys.py rename to examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_keys.py index 39238615..780da8f5 100755 --- a/examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_keys.py +++ b/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_keys.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202111') + 'CustomTargetingService', version='v202208') - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :keyId') .WithBindVariable('keyId', int(key_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_values.py b/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_values.py similarity index 95% rename from examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_values.py rename to examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_values.py index 4ee2f3a9..b087d46c 100755 --- a/examples/ad_manager/v202111/custom_targeting_service/update_custom_targeting_values.py +++ b/examples/ad_manager/v202208/custom_targeting_service/update_custom_targeting_values.py @@ -30,9 +30,9 @@ def main(client, key_id): # Initialize appropriate service. custom_targeting_service = client.GetService( - 'CustomTargetingService', version='v202111') + 'CustomTargetingService', version='v202208') - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('customTargetingKeyId = :keyId') .WithBindVariable('keyId', int(key_id))) diff --git a/examples/ad_manager/v202111/forecast_service/get_availability_forecast.py b/examples/ad_manager/v202208/forecast_service/get_availability_forecast.py similarity index 99% rename from examples/ad_manager/v202111/forecast_service/get_availability_forecast.py rename to examples/ad_manager/v202208/forecast_service/get_availability_forecast.py index dcc84c2a..489a0395 100755 --- a/examples/ad_manager/v202111/forecast_service/get_availability_forecast.py +++ b/examples/ad_manager/v202208/forecast_service/get_availability_forecast.py @@ -37,8 +37,8 @@ def main(client, advertiser_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202111') - network_service = client.GetService('NetworkService', version='v202111') + forecast_service = client.GetService('ForecastService', version='v202208') + network_service = client.GetService('NetworkService', version='v202208') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202111/forecast_service/get_availability_forecast_for_line_item.py b/examples/ad_manager/v202208/forecast_service/get_availability_forecast_for_line_item.py similarity index 99% rename from examples/ad_manager/v202111/forecast_service/get_availability_forecast_for_line_item.py rename to examples/ad_manager/v202208/forecast_service/get_availability_forecast_for_line_item.py index e9fab2bb..1b4dc727 100755 --- a/examples/ad_manager/v202111/forecast_service/get_availability_forecast_for_line_item.py +++ b/examples/ad_manager/v202208/forecast_service/get_availability_forecast_for_line_item.py @@ -30,7 +30,7 @@ def main(client, line_item_id): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202111') + forecast_service = client.GetService('ForecastService', version='v202208') # Set forecasting options. forecast_options = { diff --git a/examples/ad_manager/v202111/forecast_service/get_delivery_forecast_for_line_items.py b/examples/ad_manager/v202208/forecast_service/get_delivery_forecast_for_line_items.py similarity index 99% rename from examples/ad_manager/v202111/forecast_service/get_delivery_forecast_for_line_items.py rename to examples/ad_manager/v202208/forecast_service/get_delivery_forecast_for_line_items.py index 72fd186d..882d78ae 100755 --- a/examples/ad_manager/v202111/forecast_service/get_delivery_forecast_for_line_items.py +++ b/examples/ad_manager/v202208/forecast_service/get_delivery_forecast_for_line_items.py @@ -31,7 +31,7 @@ def main(client, line_item_id1, line_item_id2): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202111') + forecast_service = client.GetService('ForecastService', version='v202208') # Get forecast for line item. forecast = forecast_service.getDeliveryForecastByIds( diff --git a/examples/ad_manager/v202111/forecast_service/get_traffic_data.py b/examples/ad_manager/v202208/forecast_service/get_traffic_data.py similarity index 99% rename from examples/ad_manager/v202111/forecast_service/get_traffic_data.py rename to examples/ad_manager/v202208/forecast_service/get_traffic_data.py index 8b4e960f..d5d2e0f4 100755 --- a/examples/ad_manager/v202111/forecast_service/get_traffic_data.py +++ b/examples/ad_manager/v202208/forecast_service/get_traffic_data.py @@ -25,8 +25,8 @@ def main(client): # Initialize appropriate service. - forecast_service = client.GetService('ForecastService', version='v202111') - network_service = client.GetService('NetworkService', version='v202111') + forecast_service = client.GetService('ForecastService', version='v202208') + network_service = client.GetService('NetworkService', version='v202208') # get the root ad unit ID to target the entire network. root_ad_unit_id = network_service.getCurrentNetwork()['effectiveRootAdUnitId'] diff --git a/examples/ad_manager/v202111/inventory_service/__init__.py b/examples/ad_manager/v202208/inventory_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/inventory_service/__init__.py rename to examples/ad_manager/v202208/inventory_service/__init__.py diff --git a/examples/ad_manager/v202111/inventory_service/archive_ad_units.py b/examples/ad_manager/v202208/inventory_service/archive_ad_units.py similarity index 97% rename from examples/ad_manager/v202111/inventory_service/archive_ad_units.py rename to examples/ad_manager/v202208/inventory_service/archive_ad_units.py index c6d798da..26a16328 100755 --- a/examples/ad_manager/v202111/inventory_service/archive_ad_units.py +++ b/examples/ad_manager/v202208/inventory_service/archive_ad_units.py @@ -35,11 +35,11 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202111') + inventory_service = client.GetService('InventoryService', version='v202208') # Create a query to select ad units under the parent ad unit and the parent ad # unit. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('parentId = :parentId or id = :parentId') .WithBindVariable('parentId', int(parent_id))) diff --git a/examples/ad_manager/v202111/inventory_service/create_ad_units.py b/examples/ad_manager/v202208/inventory_service/create_ad_units.py similarity index 99% rename from examples/ad_manager/v202111/inventory_service/create_ad_units.py rename to examples/ad_manager/v202208/inventory_service/create_ad_units.py index cec6963b..c940de90 100755 --- a/examples/ad_manager/v202111/inventory_service/create_ad_units.py +++ b/examples/ad_manager/v202208/inventory_service/create_ad_units.py @@ -36,7 +36,7 @@ def main(client, parent_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202111') + inventory_service = client.GetService('InventoryService', version='v202208') # Create ad unit size. ad_unit_size = { diff --git a/examples/ad_manager/v202111/inventory_service/get_ad_unit_hierarchy.py b/examples/ad_manager/v202208/inventory_service/get_ad_unit_hierarchy.py similarity index 96% rename from examples/ad_manager/v202111/inventory_service/get_ad_unit_hierarchy.py rename to examples/ad_manager/v202208/inventory_service/get_ad_unit_hierarchy.py index 16f5b669..683fff15 100755 --- a/examples/ad_manager/v202111/inventory_service/get_ad_unit_hierarchy.py +++ b/examples/ad_manager/v202208/inventory_service/get_ad_unit_hierarchy.py @@ -24,15 +24,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202111') - inventory_service = client.GetService('InventoryService', version='v202111') + network_service = client.GetService('NetworkService', version='v202208') + inventory_service = client.GetService('InventoryService', version='v202208') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() root_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select only the root ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) @@ -57,7 +57,7 @@ def get_all_ad_units(inventory_service): A list containing all ad units. """ # Create a statement to get all ad units. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .OrderBy('id', ascending=True)) # Pull down all ad units into a list diff --git a/examples/ad_manager/v202111/inventory_service/get_all_ad_unit_sizes.py b/examples/ad_manager/v202208/inventory_service/get_all_ad_unit_sizes.py similarity index 93% rename from examples/ad_manager/v202111/inventory_service/get_all_ad_unit_sizes.py rename to examples/ad_manager/v202208/inventory_service/get_all_ad_unit_sizes.py index 57949087..c7e012b3 100755 --- a/examples/ad_manager/v202111/inventory_service/get_all_ad_unit_sizes.py +++ b/examples/ad_manager/v202208/inventory_service/get_all_ad_unit_sizes.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. ad_unit_size_service = client.GetService( - 'InventoryService', version='v202111') + 'InventoryService', version='v202208') # Create a statement to select ad unit sizes. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of ad unit sizes at a time, paging # through until all ad unit sizes have been retrieved. diff --git a/examples/ad_manager/v202111/inventory_service/get_all_ad_units.py b/examples/ad_manager/v202208/inventory_service/get_all_ad_units.py similarity index 95% rename from examples/ad_manager/v202111/inventory_service/get_all_ad_units.py rename to examples/ad_manager/v202208/inventory_service/get_all_ad_units.py index a71fd0fd..01b99a93 100755 --- a/examples/ad_manager/v202111/inventory_service/get_all_ad_units.py +++ b/examples/ad_manager/v202208/inventory_service/get_all_ad_units.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - ad_unit_service = client.GetService('InventoryService', version='v202111') + ad_unit_service = client.GetService('InventoryService', version='v202208') # Create a statement to select ad units. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of ad units at a time, paging # through until all ad units have been retrieved. diff --git a/examples/ad_manager/v202111/inventory_service/get_top_level_ad_units.py b/examples/ad_manager/v202208/inventory_service/get_top_level_ad_units.py similarity index 96% rename from examples/ad_manager/v202111/inventory_service/get_top_level_ad_units.py rename to examples/ad_manager/v202208/inventory_service/get_top_level_ad_units.py index 35d6aefd..7aecd91d 100755 --- a/examples/ad_manager/v202111/inventory_service/get_top_level_ad_units.py +++ b/examples/ad_manager/v202208/inventory_service/get_top_level_ad_units.py @@ -23,15 +23,15 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202111') - inventory_service = client.GetService('InventoryService', version='v202111') + network_service = client.GetService('NetworkService', version='v202208') + inventory_service = client.GetService('InventoryService', version='v202208') # Set the parent ad unit's ID for all children ad units to be fetched from. current_network = network_service.getCurrentNetwork() parent_ad_unit_id = current_network['effectiveRootAdUnitId'] # Create a statement to select ad units under the parent ad unit. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('parentId = :parentId') .OrderBy('id', ascending=True) .WithBindVariable('parentId', parent_ad_unit_id)) diff --git a/examples/ad_manager/v202111/inventory_service/update_ad_units.py b/examples/ad_manager/v202208/inventory_service/update_ad_units.py similarity index 97% rename from examples/ad_manager/v202111/inventory_service/update_ad_units.py rename to examples/ad_manager/v202208/inventory_service/update_ad_units.py index 8681c7d7..3b0d17f4 100755 --- a/examples/ad_manager/v202111/inventory_service/update_ad_units.py +++ b/examples/ad_manager/v202208/inventory_service/update_ad_units.py @@ -36,10 +36,10 @@ def main(client, ad_unit_id): # Initialize appropriate service. - inventory_service = client.GetService('InventoryService', version='v202111') + inventory_service = client.GetService('InventoryService', version='v202208') # Create a statement to select a single ad unit by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .WithBindVariable('id', ad_unit_id)) diff --git a/examples/ad_manager/v202111/label_service/__init__.py b/examples/ad_manager/v202208/label_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/label_service/__init__.py rename to examples/ad_manager/v202208/label_service/__init__.py diff --git a/examples/ad_manager/v202111/label_service/create_labels.py b/examples/ad_manager/v202208/label_service/create_labels.py similarity index 99% rename from examples/ad_manager/v202111/label_service/create_labels.py rename to examples/ad_manager/v202208/label_service/create_labels.py index f51b6d72..70135316 100755 --- a/examples/ad_manager/v202111/label_service/create_labels.py +++ b/examples/ad_manager/v202208/label_service/create_labels.py @@ -29,7 +29,7 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202111') + label_service = client.GetService('LabelService', version='v202208') # Create label objects. labels = [] diff --git a/examples/ad_manager/v202111/label_service/deactivate_labels.py b/examples/ad_manager/v202208/label_service/deactivate_labels.py similarity index 96% rename from examples/ad_manager/v202111/label_service/deactivate_labels.py rename to examples/ad_manager/v202208/label_service/deactivate_labels.py index cf5c38f9..e460c2a6 100755 --- a/examples/ad_manager/v202111/label_service/deactivate_labels.py +++ b/examples/ad_manager/v202208/label_service/deactivate_labels.py @@ -27,10 +27,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202111') + label_service = client.GetService('LabelService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202111/label_service/get_active_labels.py b/examples/ad_manager/v202208/label_service/get_active_labels.py similarity index 96% rename from examples/ad_manager/v202111/label_service/get_active_labels.py rename to examples/ad_manager/v202208/label_service/get_active_labels.py index 6e4347e9..359ad418 100755 --- a/examples/ad_manager/v202111/label_service/get_active_labels.py +++ b/examples/ad_manager/v202208/label_service/get_active_labels.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202111') + label_service = client.GetService('LabelService', version='v202208') # Create a statement to select labels. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('isActive = :isActive') .WithBindVariable('isActive', True)) diff --git a/examples/ad_manager/v202111/label_service/get_all_labels.py b/examples/ad_manager/v202208/label_service/get_all_labels.py similarity index 96% rename from examples/ad_manager/v202111/label_service/get_all_labels.py rename to examples/ad_manager/v202208/label_service/get_all_labels.py index c8ada449..ff953e51 100755 --- a/examples/ad_manager/v202111/label_service/get_all_labels.py +++ b/examples/ad_manager/v202208/label_service/get_all_labels.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202111') + label_service = client.GetService('LabelService', version='v202208') # Create a statement to select labels. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of labels at a time, paging # through until all labels have been retrieved. diff --git a/examples/ad_manager/v202111/label_service/update_labels.py b/examples/ad_manager/v202208/label_service/update_labels.py similarity index 96% rename from examples/ad_manager/v202111/label_service/update_labels.py rename to examples/ad_manager/v202208/label_service/update_labels.py index ca5badab..2a192fbb 100755 --- a/examples/ad_manager/v202111/label_service/update_labels.py +++ b/examples/ad_manager/v202208/label_service/update_labels.py @@ -29,10 +29,10 @@ def main(client, label_id): # Initialize appropriate service. - label_service = client.GetService('LabelService', version='v202111') + label_service = client.GetService('LabelService', version='v202208') # Create a statement to select only active labels. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :labelId') .WithBindVariable('labelId', int(label_id))) diff --git a/examples/ad_manager/v202111/line_item_creative_association_service/__init__.py b/examples/ad_manager/v202208/line_item_creative_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/line_item_creative_association_service/__init__.py rename to examples/ad_manager/v202208/line_item_creative_association_service/__init__.py diff --git a/examples/ad_manager/v202111/line_item_creative_association_service/create_licas.py b/examples/ad_manager/v202208/line_item_creative_association_service/create_licas.py similarity index 96% rename from examples/ad_manager/v202111/line_item_creative_association_service/create_licas.py rename to examples/ad_manager/v202208/line_item_creative_association_service/create_licas.py index e3200c7a..cf715333 100755 --- a/examples/ad_manager/v202111/line_item_creative_association_service/create_licas.py +++ b/examples/ad_manager/v202208/line_item_creative_association_service/create_licas.py @@ -32,7 +32,7 @@ def main(client, line_item_id, creative_ids): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202111') + 'LineItemCreativeAssociationService', version='v202208') licas = [] for creative_id in creative_ids: diff --git a/examples/ad_manager/v202111/line_item_creative_association_service/deactivate_licas.py b/examples/ad_manager/v202208/line_item_creative_association_service/deactivate_licas.py similarity index 95% rename from examples/ad_manager/v202111/line_item_creative_association_service/deactivate_licas.py rename to examples/ad_manager/v202208/line_item_creative_association_service/deactivate_licas.py index b11ae22d..397c981c 100755 --- a/examples/ad_manager/v202111/line_item_creative_association_service/deactivate_licas.py +++ b/examples/ad_manager/v202208/line_item_creative_association_service/deactivate_licas.py @@ -30,10 +30,10 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202111') + 'LineItemCreativeAssociationService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('lineItemId = :lineItemId AND status = :status') .WithBindVariable('status', 'ACTIVE') .WithBindVariable('lineItemId', int(line_item_id))) diff --git a/examples/ad_manager/v202111/line_item_creative_association_service/get_all_licas.py b/examples/ad_manager/v202208/line_item_creative_association_service/get_all_licas.py similarity index 94% rename from examples/ad_manager/v202111/line_item_creative_association_service/get_all_licas.py rename to examples/ad_manager/v202208/line_item_creative_association_service/get_all_licas.py index 6a2b58ef..919d0d1a 100755 --- a/examples/ad_manager/v202111/line_item_creative_association_service/get_all_licas.py +++ b/examples/ad_manager/v202208/line_item_creative_association_service/get_all_licas.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202111') + 'LineItemCreativeAssociationService', version='v202208') # Create a statement to select line item creative associations. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of line item creative associations at a time, paging # through until all line item creative associations have been retrieved. diff --git a/examples/ad_manager/v202111/line_item_creative_association_service/get_licas_for_line_item.py b/examples/ad_manager/v202208/line_item_creative_association_service/get_licas_for_line_item.py similarity index 94% rename from examples/ad_manager/v202111/line_item_creative_association_service/get_licas_for_line_item.py rename to examples/ad_manager/v202208/line_item_creative_association_service/get_licas_for_line_item.py index a30103e2..86e1e5b2 100755 --- a/examples/ad_manager/v202111/line_item_creative_association_service/get_licas_for_line_item.py +++ b/examples/ad_manager/v202208/line_item_creative_association_service/get_licas_for_line_item.py @@ -25,9 +25,9 @@ def main(client, line_item_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202111') + 'LineItemCreativeAssociationService', version='v202208') # Create a statement to select line item creative associations. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('lineItemId = :lineItemId') .WithBindVariable('lineItemId', line_item_id)) diff --git a/examples/ad_manager/v202111/line_item_creative_association_service/push_creative_to_devices.py b/examples/ad_manager/v202208/line_item_creative_association_service/push_creative_to_devices.py similarity index 94% rename from examples/ad_manager/v202111/line_item_creative_association_service/push_creative_to_devices.py rename to examples/ad_manager/v202208/line_item_creative_association_service/push_creative_to_devices.py index 23a6efdd..eb646c82 100755 --- a/examples/ad_manager/v202111/line_item_creative_association_service/push_creative_to_devices.py +++ b/examples/ad_manager/v202208/line_item_creative_association_service/push_creative_to_devices.py @@ -34,11 +34,11 @@ def main(client, line_item_id, creative_id, linked_device_id): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202111') + 'LineItemCreativeAssociationService', version='v202208') # Create query to select a single linked device. # Linked devices can be read from the linked_device PQL table. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :linkedDeviceId') .WithBindVariable('linkedDeviceId', int(linked_device_id))) diff --git a/examples/ad_manager/v202111/line_item_creative_association_service/update_licas.py b/examples/ad_manager/v202208/line_item_creative_association_service/update_licas.py similarity index 94% rename from examples/ad_manager/v202111/line_item_creative_association_service/update_licas.py rename to examples/ad_manager/v202208/line_item_creative_association_service/update_licas.py index f8552ff1..44afbc9d 100755 --- a/examples/ad_manager/v202111/line_item_creative_association_service/update_licas.py +++ b/examples/ad_manager/v202208/line_item_creative_association_service/update_licas.py @@ -28,10 +28,10 @@ def main(client): # Initialize appropriate service. lica_service = client.GetService( - 'LineItemCreativeAssociationService', version='v202111') + 'LineItemCreativeAssociationService', version='v202208') # Create statement object to get all LICAs. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') while True: # Get LICAs by statement. diff --git a/examples/ad_manager/v202111/line_item_service/__init__.py b/examples/ad_manager/v202208/line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/line_item_service/__init__.py rename to examples/ad_manager/v202208/line_item_service/__init__.py diff --git a/examples/ad_manager/v202111/line_item_service/activate_line_items.py b/examples/ad_manager/v202208/line_item_service/activate_line_items.py similarity index 97% rename from examples/ad_manager/v202111/line_item_service/activate_line_items.py rename to examples/ad_manager/v202208/line_item_service/activate_line_items.py index 0909aabe..a9a34126 100755 --- a/examples/ad_manager/v202111/line_item_service/activate_line_items.py +++ b/examples/ad_manager/v202208/line_item_service/activate_line_items.py @@ -33,10 +33,10 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('orderId = :orderId AND status = :status') .WithBindVariable('status', 'NEEDS_CREATIVES') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202111/line_item_service/create_line_items.py b/examples/ad_manager/v202208/line_item_service/create_line_items.py similarity index 99% rename from examples/ad_manager/v202111/line_item_service/create_line_items.py rename to examples/ad_manager/v202208/line_item_service/create_line_items.py index 4d7abb3f..722772e3 100755 --- a/examples/ad_manager/v202111/line_item_service/create_line_items.py +++ b/examples/ad_manager/v202208/line_item_service/create_line_items.py @@ -37,7 +37,7 @@ def main(client, order_id, targeted_placement_ids): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202111/line_item_service/create_video_line_item.py b/examples/ad_manager/v202208/line_item_service/create_video_line_item.py similarity index 99% rename from examples/ad_manager/v202111/line_item_service/create_video_line_item.py rename to examples/ad_manager/v202208/line_item_service/create_video_line_item.py index 818c3a1a..ecca4d31 100755 --- a/examples/ad_manager/v202111/line_item_service/create_video_line_item.py +++ b/examples/ad_manager/v202208/line_item_service/create_video_line_item.py @@ -42,7 +42,7 @@ def main(client, order_id, targeted_video_ad_unit_id, content_id, content_bundle_id, cms_metadata_value_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') end_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime += datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202111/line_item_service/get_all_line_items.py b/examples/ad_manager/v202208/line_item_service/get_all_line_items.py similarity index 95% rename from examples/ad_manager/v202111/line_item_service/get_all_line_items.py rename to examples/ad_manager/v202208/line_item_service/get_all_line_items.py index 8d2a70e7..3e96a6eb 100755 --- a/examples/ad_manager/v202111/line_item_service/get_all_line_items.py +++ b/examples/ad_manager/v202208/line_item_service/get_all_line_items.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') # Create a statement to select line items. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of line items at a time, paging # through until all line items have been retrieved. diff --git a/examples/ad_manager/v202111/line_item_service/get_line_items_that_need_creatives.py b/examples/ad_manager/v202208/line_item_service/get_line_items_that_need_creatives.py similarity index 96% rename from examples/ad_manager/v202111/line_item_service/get_line_items_that_need_creatives.py rename to examples/ad_manager/v202208/line_item_service/get_line_items_that_need_creatives.py index 87b2173f..14ee9e9f 100755 --- a/examples/ad_manager/v202111/line_item_service/get_line_items_that_need_creatives.py +++ b/examples/ad_manager/v202208/line_item_service/get_line_items_that_need_creatives.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('isMissingCreatives = :isMissingCreatives') .WithBindVariable('isMissingCreatives', True)) diff --git a/examples/ad_manager/v202111/line_item_service/get_recently_updated_line_items.py b/examples/ad_manager/v202208/line_item_service/get_recently_updated_line_items.py similarity index 96% rename from examples/ad_manager/v202111/line_item_service/get_recently_updated_line_items.py rename to examples/ad_manager/v202208/line_item_service/get_recently_updated_line_items.py index 3fe14abc..882f0c56 100755 --- a/examples/ad_manager/v202111/line_item_service/get_recently_updated_line_items.py +++ b/examples/ad_manager/v202208/line_item_service/get_recently_updated_line_items.py @@ -26,13 +26,13 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') last_modified = (datetime.now(tz=pytz.timezone('America/New_York')) - timedelta(days=1)) # Create a statement to select line items. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('lastModifiedDateTime >= :lastModifiedDateTime') .WithBindVariable('lastModifiedDateTime', last_modified)) diff --git a/examples/ad_manager/v202111/line_item_service/pause_line_items.py b/examples/ad_manager/v202208/line_item_service/pause_line_items.py similarity index 97% rename from examples/ad_manager/v202111/line_item_service/pause_line_items.py rename to examples/ad_manager/v202208/line_item_service/pause_line_items.py index ad70b3fd..15229319 100755 --- a/examples/ad_manager/v202111/line_item_service/pause_line_items.py +++ b/examples/ad_manager/v202208/line_item_service/pause_line_items.py @@ -29,11 +29,11 @@ def main(client): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') # Create a statement to select the line item. # Change this to operate on more than one Line Item. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .OrderBy('id', ascending=True) .WithBindVariable('id', LINE_ITEM_ID)) diff --git a/examples/ad_manager/v202111/line_item_service/target_custom_criteria.py b/examples/ad_manager/v202208/line_item_service/target_custom_criteria.py similarity index 97% rename from examples/ad_manager/v202111/line_item_service/target_custom_criteria.py rename to examples/ad_manager/v202208/line_item_service/target_custom_criteria.py index 3a7b0c30..112e0845 100755 --- a/examples/ad_manager/v202111/line_item_service/target_custom_criteria.py +++ b/examples/ad_manager/v202208/line_item_service/target_custom_criteria.py @@ -40,7 +40,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, value_id3): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') # create custom criterias custom_criteria1 = { @@ -81,7 +81,7 @@ def main(client, line_item_id, key_id1, key_id2, key_id3, value_id1, value_id2, } # Create statement to get the line item - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :lineItemId') .WithBindVariable('lineItemId', int(line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/line_item_service/update_line_items.py b/examples/ad_manager/v202208/line_item_service/update_line_items.py similarity index 97% rename from examples/ad_manager/v202111/line_item_service/update_line_items.py rename to examples/ad_manager/v202208/line_item_service/update_line_items.py index 7c487ee8..a093452b 100755 --- a/examples/ad_manager/v202111/line_item_service/update_line_items.py +++ b/examples/ad_manager/v202208/line_item_service/update_line_items.py @@ -29,11 +29,11 @@ def main(client, order_id): # Initialize appropriate service. - line_item_service = client.GetService('LineItemService', version='v202111') + line_item_service = client.GetService('LineItemService', version='v202208') # Create statement object to only select line items with even delivery rates. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where(('deliveryRateType = :deliveryRateType AND ' 'orderId = :orderId')) .WithBindVariable('orderId', int(order_id)) diff --git a/examples/ad_manager/v202111/live_stream_event_service/activate_live_stream_events.py b/examples/ad_manager/v202208/live_stream_event_service/activate_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202111/live_stream_event_service/activate_live_stream_events.py rename to examples/ad_manager/v202208/live_stream_event_service/activate_live_stream_events.py index 9092bb33..c124aa52 100755 --- a/examples/ad_manager/v202111/live_stream_event_service/activate_live_stream_events.py +++ b/examples/ad_manager/v202208/live_stream_event_service/activate_live_stream_events.py @@ -26,10 +26,10 @@ def main(client, live_stream_event_id): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202111') + 'LiveStreamEventService', version='v202208') # Create query to find paused live stream events. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where(('id = :id AND ' 'status = :status')) .WithBindVariable('status', 'PAUSED') diff --git a/examples/ad_manager/v202111/live_stream_event_service/create_live_stream_events.py b/examples/ad_manager/v202208/live_stream_event_service/create_live_stream_events.py similarity index 97% rename from examples/ad_manager/v202111/live_stream_event_service/create_live_stream_events.py rename to examples/ad_manager/v202208/live_stream_event_service/create_live_stream_events.py index c65a8374..d4d2f081 100755 --- a/examples/ad_manager/v202111/live_stream_event_service/create_live_stream_events.py +++ b/examples/ad_manager/v202208/live_stream_event_service/create_live_stream_events.py @@ -35,7 +35,7 @@ def main(client, content_urls, ad_tags): # Initialize appropriate services. live_events_service = client.GetService( - 'LiveStreamEventService', version='v202111') + 'LiveStreamEventService', version='v202208') # Stream will play for 365 days start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) diff --git a/examples/ad_manager/v202111/live_stream_event_service/get_all_live_stream_events.py b/examples/ad_manager/v202208/live_stream_event_service/get_all_live_stream_events.py similarity index 94% rename from examples/ad_manager/v202111/live_stream_event_service/get_all_live_stream_events.py rename to examples/ad_manager/v202208/live_stream_event_service/get_all_live_stream_events.py index 7c520a96..5d514bad 100755 --- a/examples/ad_manager/v202111/live_stream_event_service/get_all_live_stream_events.py +++ b/examples/ad_manager/v202208/live_stream_event_service/get_all_live_stream_events.py @@ -24,10 +24,10 @@ def main(client): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202111') + 'LiveStreamEventService', version='v202208') # Create a statement to select live stream events. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of live stream events at a time, paging # through until all live stream events have been retrieved. diff --git a/examples/ad_manager/v202111/live_stream_event_service/register_sessions_for_monitoring.py b/examples/ad_manager/v202208/live_stream_event_service/register_sessions_for_monitoring.py similarity index 96% rename from examples/ad_manager/v202111/live_stream_event_service/register_sessions_for_monitoring.py rename to examples/ad_manager/v202208/live_stream_event_service/register_sessions_for_monitoring.py index 5005ceaa..d7a92251 100755 --- a/examples/ad_manager/v202111/live_stream_event_service/register_sessions_for_monitoring.py +++ b/examples/ad_manager/v202208/live_stream_event_service/register_sessions_for_monitoring.py @@ -26,7 +26,7 @@ def main(client, session_ids): # Initialize appropriate service. live_stream_event_service = client.GetService( - 'LiveStreamEventService', version='v202111') + 'LiveStreamEventService', version='v202208') # Retrieve all sessions id that are being monitored session_ids = live_stream_event_service.registerSessionsForMonitoring( diff --git a/examples/ad_manager/v202111/live_stream_event_service/update_live_stream_events.py b/examples/ad_manager/v202208/live_stream_event_service/update_live_stream_events.py similarity index 95% rename from examples/ad_manager/v202111/live_stream_event_service/update_live_stream_events.py rename to examples/ad_manager/v202208/live_stream_event_service/update_live_stream_events.py index 6bab441d..3642457d 100755 --- a/examples/ad_manager/v202111/live_stream_event_service/update_live_stream_events.py +++ b/examples/ad_manager/v202208/live_stream_event_service/update_live_stream_events.py @@ -29,10 +29,10 @@ def main(client, live_stream_event_id): # Initialize appropriate services. live_stream_events_service = client.GetService( - 'LiveStreamEventService', version='v202111') + 'LiveStreamEventService', version='v202208') # Create statement object to only select matching live stream event. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where(('Id = :id')) .WithBindVariable('id', int(live_stream_event_id)) .Limit(500)) diff --git a/examples/ad_manager/v202111/native_style_service/__init__.py b/examples/ad_manager/v202208/native_style_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/native_style_service/__init__.py rename to examples/ad_manager/v202208/native_style_service/__init__.py diff --git a/examples/ad_manager/v202111/native_style_service/create_native_styles.py b/examples/ad_manager/v202208/native_style_service/create_native_styles.py similarity index 98% rename from examples/ad_manager/v202111/native_style_service/create_native_styles.py rename to examples/ad_manager/v202208/native_style_service/create_native_styles.py index afe514d2..793f14f5 100755 --- a/examples/ad_manager/v202111/native_style_service/create_native_styles.py +++ b/examples/ad_manager/v202208/native_style_service/create_native_styles.py @@ -147,7 +147,7 @@ def main(client, html_snippet, css_snippet, creative_template_id, width, height): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202111') + version='v202208') native_style = { 'name': 'Native style #%d' % uuid.uuid4(), diff --git a/examples/ad_manager/v202111/native_style_service/get_all_native_styles.py b/examples/ad_manager/v202208/native_style_service/get_all_native_styles.py similarity index 93% rename from examples/ad_manager/v202111/native_style_service/get_all_native_styles.py rename to examples/ad_manager/v202208/native_style_service/get_all_native_styles.py index 7047bf85..f49fa8da 100755 --- a/examples/ad_manager/v202111/native_style_service/get_all_native_styles.py +++ b/examples/ad_manager/v202208/native_style_service/get_all_native_styles.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. native_style_service = client.GetService('NativeStyleService', - version='v202111') + version='v202208') # Create a statement to select native styles. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of native styles at a time, paging # through until all native styles have been retrieved. diff --git a/examples/ad_manager/v202111/network_service/__init__.py b/examples/ad_manager/v202208/network_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/network_service/__init__.py rename to examples/ad_manager/v202208/network_service/__init__.py diff --git a/examples/ad_manager/v202111/network_service/get_all_networks.py b/examples/ad_manager/v202208/network_service/get_all_networks.py similarity index 99% rename from examples/ad_manager/v202111/network_service/get_all_networks.py rename to examples/ad_manager/v202208/network_service/get_all_networks.py index 749aeb64..4691fc06 100755 --- a/examples/ad_manager/v202111/network_service/get_all_networks.py +++ b/examples/ad_manager/v202208/network_service/get_all_networks.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202111') + network_service = client.GetService('NetworkService', version='v202208') networks = network_service.getAllNetworks() diff --git a/examples/ad_manager/v202111/network_service/get_current_network.py b/examples/ad_manager/v202208/network_service/get_current_network.py similarity index 99% rename from examples/ad_manager/v202111/network_service/get_current_network.py rename to examples/ad_manager/v202208/network_service/get_current_network.py index eb2aa419..03346f28 100755 --- a/examples/ad_manager/v202111/network_service/get_current_network.py +++ b/examples/ad_manager/v202208/network_service/get_current_network.py @@ -23,7 +23,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202111') + network_service = client.GetService('NetworkService', version='v202208') current_network = network_service.getCurrentNetwork() diff --git a/examples/ad_manager/v202111/network_service/get_default_third_party_data_declaration.py b/examples/ad_manager/v202208/network_service/get_default_third_party_data_declaration.py similarity index 95% rename from examples/ad_manager/v202111/network_service/get_default_third_party_data_declaration.py rename to examples/ad_manager/v202208/network_service/get_default_third_party_data_declaration.py index f231b9fe..997a4c55 100755 --- a/examples/ad_manager/v202111/network_service/get_default_third_party_data_declaration.py +++ b/examples/ad_manager/v202208/network_service/get_default_third_party_data_declaration.py @@ -23,9 +23,9 @@ def main(client): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202111') + network_service = client.GetService('NetworkService', version='v202208') pql_service = client.GetService('PublisherQueryLanguageService', - version='v202111') + version='v202208') # Fetch the default third party data declarations. declarations = network_service.getDefaultThirdPartyDataDeclaration() @@ -44,7 +44,7 @@ def main(client): # In this case, there are third party companies to be displayed, so fetch # the company names from the Rich_Media_Ad_Company PQL table. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Select('Id, Name') .From('Rich_Media_Ad_Company') .Where('Id IN (:company_ids)') diff --git a/examples/ad_manager/v202111/network_service/make_test_network.py b/examples/ad_manager/v202208/network_service/make_test_network.py similarity index 99% rename from examples/ad_manager/v202111/network_service/make_test_network.py rename to examples/ad_manager/v202208/network_service/make_test_network.py index 59dc82b5..ef44fb51 100755 --- a/examples/ad_manager/v202111/network_service/make_test_network.py +++ b/examples/ad_manager/v202208/network_service/make_test_network.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - network_service = client.GetService('NetworkService', version='v202111') + network_service = client.GetService('NetworkService', version='v202208') # Create a test network. network = network_service.makeTestNetwork() diff --git a/examples/ad_manager/v202111/order_service/__init__.py b/examples/ad_manager/v202208/order_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/order_service/__init__.py rename to examples/ad_manager/v202208/order_service/__init__.py diff --git a/examples/ad_manager/v202111/order_service/approve_orders.py b/examples/ad_manager/v202208/order_service/approve_orders.py similarity index 97% rename from examples/ad_manager/v202111/order_service/approve_orders.py rename to examples/ad_manager/v202208/order_service/approve_orders.py index bfb3051f..65d86cc4 100755 --- a/examples/ad_manager/v202111/order_service/approve_orders.py +++ b/examples/ad_manager/v202208/order_service/approve_orders.py @@ -28,11 +28,11 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202111') + order_service = client.GetService('OrderService', version='v202208') # Create a filter statement. today = datetime.date.today() - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where(('status in (\'DRAFT\', \'PENDING_APPROVAL\') ' 'AND endDateTime >= :today AND isArchived = FALSE')) .WithBindVariable('today', today)) diff --git a/examples/ad_manager/v202111/order_service/create_orders.py b/examples/ad_manager/v202208/order_service/create_orders.py similarity index 99% rename from examples/ad_manager/v202111/order_service/create_orders.py rename to examples/ad_manager/v202208/order_service/create_orders.py index b94d7fba..91f5f874 100755 --- a/examples/ad_manager/v202111/order_service/create_orders.py +++ b/examples/ad_manager/v202208/order_service/create_orders.py @@ -32,7 +32,7 @@ def main(client, company_id, salesperson_id, trafficker_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202111') + order_service = client.GetService('OrderService', version='v202208') # Create order objects. orders = [] diff --git a/examples/ad_manager/v202111/order_service/get_all_orders.py b/examples/ad_manager/v202208/order_service/get_all_orders.py similarity index 96% rename from examples/ad_manager/v202111/order_service/get_all_orders.py rename to examples/ad_manager/v202208/order_service/get_all_orders.py index 59ec55a4..ab1e61d2 100755 --- a/examples/ad_manager/v202111/order_service/get_all_orders.py +++ b/examples/ad_manager/v202208/order_service/get_all_orders.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202111') + order_service = client.GetService('OrderService', version='v202208') # Create a statement to select orders. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of orders at a time, paging # through until all orders have been retrieved. diff --git a/examples/ad_manager/v202111/order_service/get_orders_starting_soon.py b/examples/ad_manager/v202208/order_service/get_orders_starting_soon.py similarity index 96% rename from examples/ad_manager/v202111/order_service/get_orders_starting_soon.py rename to examples/ad_manager/v202208/order_service/get_orders_starting_soon.py index ca8bdcf9..2341f672 100755 --- a/examples/ad_manager/v202111/order_service/get_orders_starting_soon.py +++ b/examples/ad_manager/v202208/order_service/get_orders_starting_soon.py @@ -26,12 +26,12 @@ def main(client): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202111') + order_service = client.GetService('OrderService', version='v202208') now = datetime.now(tz=pytz.timezone('America/New_York')) soon = now + timedelta(days=5) # Create a statement to select orders. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where(('status = :status AND startDateTime >= :now ' 'AND startDateTime <= :soon')) .WithBindVariable('status', 'APPROVED') diff --git a/examples/ad_manager/v202111/order_service/update_orders.py b/examples/ad_manager/v202208/order_service/update_orders.py similarity index 97% rename from examples/ad_manager/v202111/order_service/update_orders.py rename to examples/ad_manager/v202208/order_service/update_orders.py index 473482a7..267979c9 100755 --- a/examples/ad_manager/v202111/order_service/update_orders.py +++ b/examples/ad_manager/v202208/order_service/update_orders.py @@ -28,11 +28,11 @@ def main(client, order_id): # Initialize appropriate service. - order_service = client.GetService('OrderService', version='v202111') + order_service = client.GetService('OrderService', version='v202208') # Create statement object to select a single order by an ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :orderId') .WithBindVariable('orderId', int(order_id))) diff --git a/examples/ad_manager/v202111/placement_service/create_placements.py b/examples/ad_manager/v202208/placement_service/create_placements.py similarity index 97% rename from examples/ad_manager/v202111/placement_service/create_placements.py rename to examples/ad_manager/v202208/placement_service/create_placements.py index 492a5fe7..d46b84f7 100755 --- a/examples/ad_manager/v202111/placement_service/create_placements.py +++ b/examples/ad_manager/v202208/placement_service/create_placements.py @@ -28,8 +28,8 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202111') - inventory_service = client.GetService('InventoryService', version='v202111') + placement_service = client.GetService('PlacementService', version='v202208') + inventory_service = client.GetService('InventoryService', version='v202208') # Create placement object to store medium rectangle ad units. medium_rectangle_ad_unit_placement = { @@ -55,7 +55,7 @@ def main(client): placement_list = [] # Create statement to get all the ad units. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') while True: response = inventory_service.getAdUnitsByStatement( diff --git a/examples/ad_manager/v202111/placement_service/deactivate_placements.py b/examples/ad_manager/v202208/placement_service/deactivate_placements.py similarity index 96% rename from examples/ad_manager/v202111/placement_service/deactivate_placements.py rename to examples/ad_manager/v202208/placement_service/deactivate_placements.py index ed699e49..1a8753d9 100755 --- a/examples/ad_manager/v202111/placement_service/deactivate_placements.py +++ b/examples/ad_manager/v202208/placement_service/deactivate_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202111') + placement_service = client.GetService('PlacementService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :placementId') .WithBindVariable('placementId', int(placement_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/placement_service/get_active_placements.py b/examples/ad_manager/v202208/placement_service/get_active_placements.py similarity index 95% rename from examples/ad_manager/v202111/placement_service/get_active_placements.py rename to examples/ad_manager/v202208/placement_service/get_active_placements.py index 0ecc0145..77e6ff29 100755 --- a/examples/ad_manager/v202111/placement_service/get_active_placements.py +++ b/examples/ad_manager/v202208/placement_service/get_active_placements.py @@ -22,9 +22,9 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202111') + placement_service = client.GetService('PlacementService', version='v202208') # Create a statement to select placements. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('status = :status') .WithBindVariable('status', 'ACTIVE')) diff --git a/examples/ad_manager/v202111/placement_service/get_all_placements.py b/examples/ad_manager/v202208/placement_service/get_all_placements.py similarity index 95% rename from examples/ad_manager/v202111/placement_service/get_all_placements.py rename to examples/ad_manager/v202208/placement_service/get_all_placements.py index 0e0f4363..2406d1d7 100755 --- a/examples/ad_manager/v202111/placement_service/get_all_placements.py +++ b/examples/ad_manager/v202208/placement_service/get_all_placements.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202111') + placement_service = client.GetService('PlacementService', version='v202208') # Create a statement to select placements. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of placements at a time, paging # through until all placements have been retrieved. diff --git a/examples/ad_manager/v202111/placement_service/update_placements.py b/examples/ad_manager/v202208/placement_service/update_placements.py similarity index 96% rename from examples/ad_manager/v202111/placement_service/update_placements.py rename to examples/ad_manager/v202208/placement_service/update_placements.py index 4dd748b7..b0697537 100755 --- a/examples/ad_manager/v202111/placement_service/update_placements.py +++ b/examples/ad_manager/v202208/placement_service/update_placements.py @@ -28,10 +28,10 @@ def main(client, placement_id): # Initialize appropriate service. - placement_service = client.GetService('PlacementService', version='v202111') + placement_service = client.GetService('PlacementService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .OrderBy('id', ascending=True) .Limit(1) diff --git a/examples/ad_manager/v202111/proposal_line_item_service/__init__.py b/examples/ad_manager/v202208/proposal_line_item_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/proposal_line_item_service/__init__.py rename to examples/ad_manager/v202208/proposal_line_item_service/__init__.py diff --git a/examples/ad_manager/v202111/proposal_line_item_service/archive_proposal_line_items.py b/examples/ad_manager/v202208/proposal_line_item_service/archive_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202111/proposal_line_item_service/archive_proposal_line_items.py rename to examples/ad_manager/v202208/proposal_line_item_service/archive_proposal_line_items.py index 76f0ce06..bcc9af63 100755 --- a/examples/ad_manager/v202111/proposal_line_item_service/archive_proposal_line_items.py +++ b/examples/ad_manager/v202208/proposal_line_item_service/archive_proposal_line_items.py @@ -31,10 +31,10 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202111') + 'ProposalLineItemService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/proposal_line_item_service/create_proposal_line_items.py b/examples/ad_manager/v202208/proposal_line_item_service/create_proposal_line_items.py similarity index 98% rename from examples/ad_manager/v202111/proposal_line_item_service/create_proposal_line_items.py rename to examples/ad_manager/v202208/proposal_line_item_service/create_proposal_line_items.py index c0ac6d80..0d579f98 100755 --- a/examples/ad_manager/v202111/proposal_line_item_service/create_proposal_line_items.py +++ b/examples/ad_manager/v202208/proposal_line_item_service/create_proposal_line_items.py @@ -30,8 +30,8 @@ def main(client, proposal_id): proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202111') - network_service = client.GetService('NetworkService', version='v202111') + 'ProposalLineItemService', version='v202208') + network_service = client.GetService('NetworkService', version='v202208') start_datetime = datetime.datetime.now(tz=pytz.timezone('America/New_York')) end_datetime = start_datetime + datetime.timedelta(days=365) diff --git a/examples/ad_manager/v202111/proposal_line_item_service/get_all_proposal_line_items.py b/examples/ad_manager/v202208/proposal_line_item_service/get_all_proposal_line_items.py similarity index 94% rename from examples/ad_manager/v202111/proposal_line_item_service/get_all_proposal_line_items.py rename to examples/ad_manager/v202208/proposal_line_item_service/get_all_proposal_line_items.py index b9c3f36b..d34164bd 100755 --- a/examples/ad_manager/v202111/proposal_line_item_service/get_all_proposal_line_items.py +++ b/examples/ad_manager/v202208/proposal_line_item_service/get_all_proposal_line_items.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202111') + 'ProposalLineItemService', version='v202208') # Create a statement to select proposal line items. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of proposal line items at a time, paging # through until all proposal line items have been retrieved. diff --git a/examples/ad_manager/v202111/proposal_line_item_service/get_proposal_line_items_for_proposal.py b/examples/ad_manager/v202208/proposal_line_item_service/get_proposal_line_items_for_proposal.py similarity index 94% rename from examples/ad_manager/v202111/proposal_line_item_service/get_proposal_line_items_for_proposal.py rename to examples/ad_manager/v202208/proposal_line_item_service/get_proposal_line_items_for_proposal.py index 9b77d26c..ac127ebc 100755 --- a/examples/ad_manager/v202111/proposal_line_item_service/get_proposal_line_items_for_proposal.py +++ b/examples/ad_manager/v202208/proposal_line_item_service/get_proposal_line_items_for_proposal.py @@ -25,9 +25,9 @@ def main(client, proposal_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202111') + 'ProposalLineItemService', version='v202208') # Create a statement to select proposal line items. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('proposalId = :proposalId') .WithBindVariable('proposalId', proposal_id)) diff --git a/examples/ad_manager/v202111/proposal_line_item_service/update_proposal_line_items.py b/examples/ad_manager/v202208/proposal_line_item_service/update_proposal_line_items.py similarity index 95% rename from examples/ad_manager/v202111/proposal_line_item_service/update_proposal_line_items.py rename to examples/ad_manager/v202208/proposal_line_item_service/update_proposal_line_items.py index 46596950..887c9ee3 100755 --- a/examples/ad_manager/v202111/proposal_line_item_service/update_proposal_line_items.py +++ b/examples/ad_manager/v202208/proposal_line_item_service/update_proposal_line_items.py @@ -31,11 +31,11 @@ def main(client, proposal_line_item_id): # Initialize appropriate service. proposal_line_item_service = client.GetService( - 'ProposalLineItemService', version='v202111') + 'ProposalLineItemService', version='v202208') # Create statement to select a proposal line item. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .WithBindVariable('id', int(proposal_line_item_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/proposal_service/__init__.py b/examples/ad_manager/v202208/proposal_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/proposal_service/__init__.py rename to examples/ad_manager/v202208/proposal_service/__init__.py diff --git a/examples/ad_manager/v202111/proposal_service/create_proposals.py b/examples/ad_manager/v202208/proposal_service/create_proposals.py similarity index 98% rename from examples/ad_manager/v202111/proposal_service/create_proposals.py rename to examples/ad_manager/v202208/proposal_service/create_proposals.py index 89ec3a51..b4360ccc 100755 --- a/examples/ad_manager/v202111/proposal_service/create_proposals.py +++ b/examples/ad_manager/v202208/proposal_service/create_proposals.py @@ -28,7 +28,7 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, primary_trafficker_id): - proposal_service = client.GetService('ProposalService', version='v202111') + proposal_service = client.GetService('ProposalService', version='v202208') proposal = { # Setting required Marketplace information. @@ -40,7 +40,6 @@ def main(client, programmatic_buyer_id, primary_salesperson_id, 'name': 'Proposal #%s' % uuid.uuid4(), 'primarySalesperson': { 'userId': primary_salesperson_id, - 'split': '100000' }, 'primaryTraffickerId': primary_trafficker_id, 'probabilityOfClose': '100000', diff --git a/examples/ad_manager/v202111/proposal_service/get_all_proposals.py b/examples/ad_manager/v202208/proposal_service/get_all_proposals.py similarity index 95% rename from examples/ad_manager/v202111/proposal_service/get_all_proposals.py rename to examples/ad_manager/v202208/proposal_service/get_all_proposals.py index bf00297b..fe88df3b 100755 --- a/examples/ad_manager/v202111/proposal_service/get_all_proposals.py +++ b/examples/ad_manager/v202208/proposal_service/get_all_proposals.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202111') + proposal_service = client.GetService('ProposalService', version='v202208') # Create a statement to select proposals. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of proposals at a time, paging # through until all proposals have been retrieved. diff --git a/examples/ad_manager/v202111/proposal_service/get_marketplace_comments.py b/examples/ad_manager/v202208/proposal_service/get_marketplace_comments.py similarity index 97% rename from examples/ad_manager/v202111/proposal_service/get_marketplace_comments.py rename to examples/ad_manager/v202208/proposal_service/get_marketplace_comments.py index ea96ba15..e8c263f5 100755 --- a/examples/ad_manager/v202111/proposal_service/get_marketplace_comments.py +++ b/examples/ad_manager/v202208/proposal_service/get_marketplace_comments.py @@ -28,7 +28,7 @@ def main(client, proposal_id): # Initialize appropriate service. marketplace_comment_service = client.GetService( - 'ProposalService', version='v202111') + 'ProposalService', version='v202208') query = 'WHERE proposalId = %s' % proposal_id # Create a statement to select marketplace comments. statement = {'query': query} diff --git a/examples/ad_manager/v202111/proposal_service/get_proposals_awaiting_seller_review.py b/examples/ad_manager/v202208/proposal_service/get_proposals_awaiting_seller_review.py similarity index 96% rename from examples/ad_manager/v202111/proposal_service/get_proposals_awaiting_seller_review.py rename to examples/ad_manager/v202208/proposal_service/get_proposals_awaiting_seller_review.py index fce01a45..41e433ef 100755 --- a/examples/ad_manager/v202111/proposal_service/get_proposals_awaiting_seller_review.py +++ b/examples/ad_manager/v202208/proposal_service/get_proposals_awaiting_seller_review.py @@ -21,9 +21,9 @@ def main(client): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202111') + proposal_service = client.GetService('ProposalService', version='v202208') # Create a statement to select proposals. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('negotiationStatus = :negotiationStatus') .WithBindVariable('negotiationStatus', 'AWAITING_SELLER_REVIEW')) diff --git a/examples/ad_manager/v202111/proposal_service/request_buyers_acceptance.py b/examples/ad_manager/v202208/proposal_service/request_buyers_acceptance.py similarity index 97% rename from examples/ad_manager/v202111/proposal_service/request_buyers_acceptance.py rename to examples/ad_manager/v202208/proposal_service/request_buyers_acceptance.py index 5c0605db..e232d171 100755 --- a/examples/ad_manager/v202111/proposal_service/request_buyers_acceptance.py +++ b/examples/ad_manager/v202208/proposal_service/request_buyers_acceptance.py @@ -26,10 +26,10 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202111') + proposal_service = client.GetService('ProposalService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :proposalId') .WithBindVariable('proposalId', proposal_id)) proposals_pushed_to_marketplace = 0 diff --git a/examples/ad_manager/v202111/proposal_service/update_proposals.py b/examples/ad_manager/v202208/proposal_service/update_proposals.py similarity index 96% rename from examples/ad_manager/v202111/proposal_service/update_proposals.py rename to examples/ad_manager/v202208/proposal_service/update_proposals.py index 1b3e27e5..85324acd 100755 --- a/examples/ad_manager/v202111/proposal_service/update_proposals.py +++ b/examples/ad_manager/v202208/proposal_service/update_proposals.py @@ -28,11 +28,11 @@ def main(client, proposal_id): # Initialize appropriate service. - proposal_service = client.GetService('ProposalService', version='v202111') + proposal_service = client.GetService('ProposalService', version='v202208') # Create statement object to select a single proposal by an ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :proposalId') .WithBindVariable('proposalId', int(proposal_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/publisher_query_language_service/__init__.py b/examples/ad_manager/v202208/publisher_query_language_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/publisher_query_language_service/__init__.py rename to examples/ad_manager/v202208/publisher_query_language_service/__init__.py diff --git a/examples/ad_manager/v202111/publisher_query_language_service/fetch_match_tables.py b/examples/ad_manager/v202208/publisher_query_language_service/fetch_match_tables.py similarity index 96% rename from examples/ad_manager/v202111/publisher_query_language_service/fetch_match_tables.py rename to examples/ad_manager/v202208/publisher_query_language_service/fetch_match_tables.py index eab6ffdc..1b62f000 100755 --- a/examples/ad_manager/v202111/publisher_query_language_service/fetch_match_tables.py +++ b/examples/ad_manager/v202208/publisher_query_language_service/fetch_match_tables.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') line_items_file = tempfile.NamedTemporaryFile( prefix='line_items_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202111/publisher_query_language_service/get_all_browsers.py b/examples/ad_manager/v202208/publisher_query_language_service/get_all_browsers.py similarity index 96% rename from examples/ad_manager/v202111/publisher_query_language_service/get_all_browsers.py rename to examples/ad_manager/v202208/publisher_query_language_service/get_all_browsers.py index e3f66ca7..bb05432c 100755 --- a/examples/ad_manager/v202111/publisher_query_language_service/get_all_browsers.py +++ b/examples/ad_manager/v202208/publisher_query_language_service/get_all_browsers.py @@ -32,7 +32,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') with tempfile.NamedTemporaryFile( prefix='browser_data_', diff --git a/examples/ad_manager/v202111/publisher_query_language_service/get_all_programmatic_buyers.py b/examples/ad_manager/v202208/publisher_query_language_service/get_all_programmatic_buyers.py similarity index 96% rename from examples/ad_manager/v202111/publisher_query_language_service/get_all_programmatic_buyers.py rename to examples/ad_manager/v202208/publisher_query_language_service/get_all_programmatic_buyers.py index f5bd52c9..41b72a98 100755 --- a/examples/ad_manager/v202111/publisher_query_language_service/get_all_programmatic_buyers.py +++ b/examples/ad_manager/v202208/publisher_query_language_service/get_all_programmatic_buyers.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202111') + data_downloader = client.GetDataDownloader(version='v202208') programmatic_buyers_file = tempfile.NamedTemporaryFile( prefix='programmatic_buyers_', suffix='.csv', mode='w', delete=False) diff --git a/examples/ad_manager/v202111/publisher_query_language_service/get_geo_targets.py b/examples/ad_manager/v202208/publisher_query_language_service/get_geo_targets.py similarity index 96% rename from examples/ad_manager/v202111/publisher_query_language_service/get_geo_targets.py rename to examples/ad_manager/v202208/publisher_query_language_service/get_geo_targets.py index 6edfa873..8cd68c0e 100755 --- a/examples/ad_manager/v202111/publisher_query_language_service/get_geo_targets.py +++ b/examples/ad_manager/v202208/publisher_query_language_service/get_geo_targets.py @@ -28,7 +28,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') with tempfile.NamedTemporaryFile( prefix='geo_data_', diff --git a/examples/ad_manager/v202111/publisher_query_language_service/get_line_items_named_like.py b/examples/ad_manager/v202208/publisher_query_language_service/get_line_items_named_like.py similarity index 96% rename from examples/ad_manager/v202111/publisher_query_language_service/get_line_items_named_like.py rename to examples/ad_manager/v202208/publisher_query_language_service/get_line_items_named_like.py index c2ce69b3..54a3a5ba 100755 --- a/examples/ad_manager/v202111/publisher_query_language_service/get_line_items_named_like.py +++ b/examples/ad_manager/v202208/publisher_query_language_service/get_line_items_named_like.py @@ -25,7 +25,7 @@ def main(client): # Initialize a report downloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') with tempfile.NamedTemporaryFile( prefix='line_items_', diff --git a/examples/ad_manager/v202111/publisher_query_language_service/get_mcm_earnings.py b/examples/ad_manager/v202208/publisher_query_language_service/get_mcm_earnings.py similarity index 97% rename from examples/ad_manager/v202111/publisher_query_language_service/get_mcm_earnings.py rename to examples/ad_manager/v202208/publisher_query_language_service/get_mcm_earnings.py index d59dd729..503c707b 100755 --- a/examples/ad_manager/v202111/publisher_query_language_service/get_mcm_earnings.py +++ b/examples/ad_manager/v202208/publisher_query_language_service/get_mcm_earnings.py @@ -26,7 +26,7 @@ def main(client): # Initialize a report downloader. - data_downloader = client.GetDataDownloader(version='v202111') + data_downloader = client.GetDataDownloader(version='v202208') with tempfile.NamedTemporaryFile( prefix='mcm_earnings_', diff --git a/examples/ad_manager/v202111/publisher_query_language_service/get_recent_changes.py b/examples/ad_manager/v202208/publisher_query_language_service/get_recent_changes.py similarity index 98% rename from examples/ad_manager/v202111/publisher_query_language_service/get_recent_changes.py rename to examples/ad_manager/v202208/publisher_query_language_service/get_recent_changes.py index 59231067..275fbd21 100755 --- a/examples/ad_manager/v202111/publisher_query_language_service/get_recent_changes.py +++ b/examples/ad_manager/v202208/publisher_query_language_service/get_recent_changes.py @@ -31,7 +31,7 @@ def main(client): # Initialize appropriate service. - pql_service = client.GetService('PublisherQueryLanguageService', 'v202111') + pql_service = client.GetService('PublisherQueryLanguageService', 'v202208') end_date = datetime.now(tz=pytz.timezone('America/New_York')) start_date = end_date - timedelta(days=1) @@ -39,7 +39,7 @@ def main(client): 'AND ChangeDateTime < :endDateTime') pagination_query = 'Id < :id AND ' + initial_query - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Select(('Id, ChangeDateTime, EntityId, EntityType, ' 'Operation, UserId')) .From('Change_History') diff --git a/examples/ad_manager/v202111/report_service/__init__.py b/examples/ad_manager/v202208/report_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/report_service/__init__.py rename to examples/ad_manager/v202208/report_service/__init__.py diff --git a/examples/ad_manager/v202111/report_service/run_delivery_report.py b/examples/ad_manager/v202208/report_service/run_delivery_report.py similarity index 95% rename from examples/ad_manager/v202111/report_service/run_delivery_report.py rename to examples/ad_manager/v202208/report_service/run_delivery_report.py index 0c6d1c57..3e371886 100755 --- a/examples/ad_manager/v202111/report_service/run_delivery_report.py +++ b/examples/ad_manager/v202208/report_service/run_delivery_report.py @@ -32,7 +32,7 @@ def main(client, order_id): # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('ORDER_ID = :id') .WithBindVariable('id', int(order_id)) .Limit(None) # No limit or offset for reports @@ -59,7 +59,7 @@ def main(client, order_id): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202111/report_service/run_inventory_report.py b/examples/ad_manager/v202208/report_service/run_inventory_report.py similarity index 91% rename from examples/ad_manager/v202111/report_service/run_inventory_report.py rename to examples/ad_manager/v202208/report_service/run_inventory_report.py index 572dba64..4f746de6 100755 --- a/examples/ad_manager/v202111/report_service/run_inventory_report.py +++ b/examples/ad_manager/v202208/report_service/run_inventory_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') # Create report job. report_job = { @@ -33,8 +33,8 @@ def main(client): 'dimensions': ['DATE', 'AD_UNIT_NAME'], 'adUnitView': 'HIERARCHICAL', 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', - 'ADSENSE_LINE_ITEM_LEVEL_IMPRESSIONS', - 'ADSENSE_LINE_ITEM_LEVEL_CLICKS', + 'AD_EXCHANGE_LINE_ITEM_LEVEL_IMPRESSIONS', + 'AD_EXCHANGE_LINE_ITEM_LEVEL_CLICKS', 'TOTAL_LINE_ITEM_LEVEL_IMPRESSIONS', 'TOTAL_LINE_ITEM_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK' diff --git a/examples/ad_manager/v202111/report_service/run_reach_report.py b/examples/ad_manager/v202208/report_service/run_reach_report.py similarity index 96% rename from examples/ad_manager/v202111/report_service/run_reach_report.py rename to examples/ad_manager/v202208/report_service/run_reach_report.py index 295b8e4d..7114e4da 100755 --- a/examples/ad_manager/v202111/report_service/run_reach_report.py +++ b/examples/ad_manager/v202208/report_service/run_reach_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') # Create report job. report_job = { diff --git a/examples/ad_manager/v202111/report_service/run_reach_report_with_ad_unit_dimensions.py b/examples/ad_manager/v202208/report_service/run_reach_report_with_ad_unit_dimensions.py similarity index 97% rename from examples/ad_manager/v202111/report_service/run_reach_report_with_ad_unit_dimensions.py rename to examples/ad_manager/v202208/report_service/run_reach_report_with_ad_unit_dimensions.py index 8c866c86..fd703b06 100755 --- a/examples/ad_manager/v202111/report_service/run_reach_report_with_ad_unit_dimensions.py +++ b/examples/ad_manager/v202208/report_service/run_reach_report_with_ad_unit_dimensions.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') # Create report job. report_job = { diff --git a/examples/ad_manager/v202111/report_service/run_report_and_create_match_table.py b/examples/ad_manager/v202208/report_service/run_report_and_create_match_table.py similarity index 97% rename from examples/ad_manager/v202111/report_service/run_report_and_create_match_table.py rename to examples/ad_manager/v202208/report_service/run_report_and_create_match_table.py index cef28096..094b5071 100755 --- a/examples/ad_manager/v202111/report_service/run_report_and_create_match_table.py +++ b/examples/ad_manager/v202208/report_service/run_report_and_create_match_table.py @@ -54,7 +54,7 @@ def main(client): } # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') try: # Run the report and wait for it to finish. diff --git a/examples/ad_manager/v202111/report_service/run_report_with_custom_fields.py b/examples/ad_manager/v202208/report_service/run_report_with_custom_fields.py similarity index 97% rename from examples/ad_manager/v202111/report_service/run_report_with_custom_fields.py rename to examples/ad_manager/v202208/report_service/run_report_with_custom_fields.py index daaae982..986d252d 100755 --- a/examples/ad_manager/v202111/report_service/run_report_with_custom_fields.py +++ b/examples/ad_manager/v202208/report_service/run_report_with_custom_fields.py @@ -28,7 +28,7 @@ def main(client, custom_field_id, custom_dimension_key_id): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') # Create report job. report_job = { diff --git a/examples/ad_manager/v202111/report_service/run_sales_report.py b/examples/ad_manager/v202208/report_service/run_sales_report.py similarity index 96% rename from examples/ad_manager/v202111/report_service/run_sales_report.py rename to examples/ad_manager/v202208/report_service/run_sales_report.py index 812c0af7..2a74d033 100755 --- a/examples/ad_manager/v202111/report_service/run_sales_report.py +++ b/examples/ad_manager/v202208/report_service/run_sales_report.py @@ -25,7 +25,7 @@ def main(client): # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') # Create report job. report_job = { diff --git a/examples/ad_manager/v202111/report_service/run_saved_query.py b/examples/ad_manager/v202208/report_service/run_saved_query.py similarity index 94% rename from examples/ad_manager/v202111/report_service/run_saved_query.py rename to examples/ad_manager/v202208/report_service/run_saved_query.py index 66e206df..46f321a9 100755 --- a/examples/ad_manager/v202111/report_service/run_saved_query.py +++ b/examples/ad_manager/v202208/report_service/run_saved_query.py @@ -28,13 +28,13 @@ def main(client, saved_query_id): # Initialize appropriate service. - report_service = client.GetService('ReportService', version='v202111') + report_service = client.GetService('ReportService', version='v202208') # Initialize a DataDownloader. - report_downloader = client.GetDataDownloader(version='v202111') + report_downloader = client.GetDataDownloader(version='v202208') # Create statement object to filter for an order. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .WithBindVariable('id', int(saved_query_id)) .Limit(1)) diff --git a/examples/ad_manager/v202111/site_service/create_sites.py b/examples/ad_manager/v202208/site_service/create_sites.py similarity index 96% rename from examples/ad_manager/v202111/site_service/create_sites.py rename to examples/ad_manager/v202208/site_service/create_sites.py index d6ea315f..2414a792 100755 --- a/examples/ad_manager/v202111/site_service/create_sites.py +++ b/examples/ad_manager/v202208/site_service/create_sites.py @@ -27,8 +27,8 @@ def main(client, url, child_network_code): # Initialize appropriate services. - network_service = client.GetService('NetworkService', version='v202111') - site_service = client.GetService('SiteService', version='v202111') + network_service = client.GetService('NetworkService', version='v202208') + site_service = client.GetService('SiteService', version='v202208') # Check that the child network code is approved for MANAGE_INVENTORY by this # network. diff --git a/examples/ad_manager/v202111/site_service/get_all_sites.py b/examples/ad_manager/v202208/site_service/get_all_sites.py similarity index 92% rename from examples/ad_manager/v202111/site_service/get_all_sites.py rename to examples/ad_manager/v202208/site_service/get_all_sites.py index ad468b57..98e0ec20 100755 --- a/examples/ad_manager/v202111/site_service/get_all_sites.py +++ b/examples/ad_manager/v202208/site_service/get_all_sites.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202111') + site_service = client.GetService('SiteService', version='v202208') # Create a statement to select Sites. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small number of sites at a time, paging through until all sites # have been retrieved. diff --git a/examples/ad_manager/v202111/site_service/get_sites_requiring_approval.py b/examples/ad_manager/v202208/site_service/get_sites_requiring_approval.py similarity index 92% rename from examples/ad_manager/v202111/site_service/get_sites_requiring_approval.py rename to examples/ad_manager/v202208/site_service/get_sites_requiring_approval.py index 6dd575e0..ede12b20 100755 --- a/examples/ad_manager/v202111/site_service/get_sites_requiring_approval.py +++ b/examples/ad_manager/v202208/site_service/get_sites_requiring_approval.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202111') + site_service = client.GetService('SiteService', version='v202208') # Create a statement to select Sites needing approval. - statement = ad_manager.StatementBuilder(version='v202111').Where( + statement = ad_manager.StatementBuilder(version='v202208').Where( "approvalStatus = 'REQUIRES_REVIEW'") # Retrieve a small number of sites at a time, paging through until all sites diff --git a/examples/ad_manager/v202111/site_service/submit_sites_for_approval.py b/examples/ad_manager/v202208/site_service/submit_sites_for_approval.py similarity index 91% rename from examples/ad_manager/v202111/site_service/submit_sites_for_approval.py rename to examples/ad_manager/v202208/site_service/submit_sites_for_approval.py index 1843f487..9f96fa9a 100755 --- a/examples/ad_manager/v202111/site_service/submit_sites_for_approval.py +++ b/examples/ad_manager/v202208/site_service/submit_sites_for_approval.py @@ -25,10 +25,10 @@ def main(client): # Initialize appropriate service. - site_service = client.GetService('SiteService', version='v202111') + site_service = client.GetService('SiteService', version='v202208') # Create a statement to select Site. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :id') .WithBindVariable('id', SITE_ID)) diff --git a/examples/ad_manager/v202111/suggested_ad_unit_service/__init__.py b/examples/ad_manager/v202208/suggested_ad_unit_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/suggested_ad_unit_service/__init__.py rename to examples/ad_manager/v202208/suggested_ad_unit_service/__init__.py diff --git a/examples/ad_manager/v202111/suggested_ad_unit_service/approve_all_suggested_ad_units.py b/examples/ad_manager/v202208/suggested_ad_unit_service/approve_all_suggested_ad_units.py similarity index 95% rename from examples/ad_manager/v202111/suggested_ad_unit_service/approve_all_suggested_ad_units.py rename to examples/ad_manager/v202208/suggested_ad_unit_service/approve_all_suggested_ad_units.py index 229fd6f1..87b1b830 100755 --- a/examples/ad_manager/v202111/suggested_ad_unit_service/approve_all_suggested_ad_units.py +++ b/examples/ad_manager/v202208/suggested_ad_unit_service/approve_all_suggested_ad_units.py @@ -29,10 +29,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202111') + 'SuggestedAdUnitService', version='v202208') # Create a filter statement. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('numRequests > :numRequests') .WithBindVariable('numRequests', THRESHOLD_NUMBER_OF_REQUESTS)) num_approved_suggested_ad_units = 0 diff --git a/examples/ad_manager/v202111/suggested_ad_unit_service/get_all_suggested_ad_units.py b/examples/ad_manager/v202208/suggested_ad_unit_service/get_all_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202111/suggested_ad_unit_service/get_all_suggested_ad_units.py rename to examples/ad_manager/v202208/suggested_ad_unit_service/get_all_suggested_ad_units.py index 08eb4916..2f0a0ac5 100755 --- a/examples/ad_manager/v202111/suggested_ad_unit_service/get_all_suggested_ad_units.py +++ b/examples/ad_manager/v202208/suggested_ad_unit_service/get_all_suggested_ad_units.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202111') + 'SuggestedAdUnitService', version='v202208') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of suggested ad units at a time, paging # through until all suggested ad units have been retrieved. diff --git a/examples/ad_manager/v202111/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py b/examples/ad_manager/v202208/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py similarity index 94% rename from examples/ad_manager/v202111/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py rename to examples/ad_manager/v202208/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py index 775c4e26..3dcfaa48 100755 --- a/examples/ad_manager/v202111/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py +++ b/examples/ad_manager/v202208/suggested_ad_unit_service/get_highly_requested_suggested_ad_units.py @@ -25,9 +25,9 @@ def main(client, num_requests): # Initialize appropriate service. suggested_ad_unit_service = client.GetService( - 'SuggestedAdUnitService', version='v202111') + 'SuggestedAdUnitService', version='v202208') # Create a statement to select suggested ad units. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('numRequests >= :numRequests') .WithBindVariable('numRequests', int(num_requests))) diff --git a/examples/ad_manager/v202111/targeting_preset_service/__init__.py b/examples/ad_manager/v202208/targeting_preset_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/targeting_preset_service/__init__.py rename to examples/ad_manager/v202208/targeting_preset_service/__init__.py diff --git a/examples/ad_manager/v202111/targeting_preset_service/get_all_targeting_presets.py b/examples/ad_manager/v202208/targeting_preset_service/get_all_targeting_presets.py similarity index 94% rename from examples/ad_manager/v202111/targeting_preset_service/get_all_targeting_presets.py rename to examples/ad_manager/v202208/targeting_preset_service/get_all_targeting_presets.py index 72fdbb0c..665ca95e 100755 --- a/examples/ad_manager/v202111/targeting_preset_service/get_all_targeting_presets.py +++ b/examples/ad_manager/v202208/targeting_preset_service/get_all_targeting_presets.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. targeting_preset_service = client.GetService( - 'TargetingPresetService', version='v202111') + 'TargetingPresetService', version='v202208') # Create a statement to select suggested ad units. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small number of targeting presets at a time, paging # through until all targeting presets have been retrieved. diff --git a/examples/ad_manager/v202111/team_service/__init__.py b/examples/ad_manager/v202208/team_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/team_service/__init__.py rename to examples/ad_manager/v202208/team_service/__init__.py diff --git a/examples/ad_manager/v202111/team_service/create_teams.py b/examples/ad_manager/v202208/team_service/create_teams.py similarity index 96% rename from examples/ad_manager/v202111/team_service/create_teams.py rename to examples/ad_manager/v202208/team_service/create_teams.py index 73b8de10..ef39302a 100755 --- a/examples/ad_manager/v202111/team_service/create_teams.py +++ b/examples/ad_manager/v202208/team_service/create_teams.py @@ -33,7 +33,7 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202111') + team_service = client.GetService('TeamService', version='v202208') # Create team objects. teams = [] diff --git a/examples/ad_manager/v202111/team_service/get_all_teams.py b/examples/ad_manager/v202208/team_service/get_all_teams.py similarity index 92% rename from examples/ad_manager/v202111/team_service/get_all_teams.py rename to examples/ad_manager/v202208/team_service/get_all_teams.py index a5f1d3a8..8895dcad 100755 --- a/examples/ad_manager/v202111/team_service/get_all_teams.py +++ b/examples/ad_manager/v202208/team_service/get_all_teams.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202111') + team_service = client.GetService('TeamService', version='v202208') # Create a statement to select teams. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of teams at a time, paging # through until all teams have been retrieved. diff --git a/examples/ad_manager/v202111/team_service/update_teams.py b/examples/ad_manager/v202208/team_service/update_teams.py similarity index 94% rename from examples/ad_manager/v202111/team_service/update_teams.py rename to examples/ad_manager/v202208/team_service/update_teams.py index 1b21d20c..8a92c0e6 100755 --- a/examples/ad_manager/v202111/team_service/update_teams.py +++ b/examples/ad_manager/v202208/team_service/update_teams.py @@ -34,10 +34,10 @@ def main(client, team_id): # Initialize appropriate service. - team_service = client.GetService('TeamService', version='v202111') + team_service = client.GetService('TeamService', version='v202208') # Create a filter statement to select a single team by ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :teamId') .WithBindVariable('teamId', int(team_id))) diff --git a/examples/ad_manager/v202111/user_service/__init__.py b/examples/ad_manager/v202208/user_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/user_service/__init__.py rename to examples/ad_manager/v202208/user_service/__init__.py diff --git a/examples/ad_manager/v202111/user_service/create_users.py b/examples/ad_manager/v202208/user_service/create_users.py similarity index 96% rename from examples/ad_manager/v202111/user_service/create_users.py rename to examples/ad_manager/v202208/user_service/create_users.py index de12e436..62ca5a33 100755 --- a/examples/ad_manager/v202111/user_service/create_users.py +++ b/examples/ad_manager/v202208/user_service/create_users.py @@ -29,7 +29,7 @@ def main(client, email, name): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202111') + user_service = client.GetService('UserService', version='v202208') # Create user objects. users = [ diff --git a/examples/ad_manager/v202111/user_service/deactivate_users.py b/examples/ad_manager/v202208/user_service/deactivate_users.py similarity index 94% rename from examples/ad_manager/v202111/user_service/deactivate_users.py rename to examples/ad_manager/v202208/user_service/deactivate_users.py index 14d83347..65af930a 100755 --- a/examples/ad_manager/v202111/user_service/deactivate_users.py +++ b/examples/ad_manager/v202208/user_service/deactivate_users.py @@ -30,10 +30,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202111') + user_service = client.GetService('UserService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202111/user_service/get_all_roles.py b/examples/ad_manager/v202208/user_service/get_all_roles.py similarity index 94% rename from examples/ad_manager/v202111/user_service/get_all_roles.py rename to examples/ad_manager/v202208/user_service/get_all_roles.py index 498c60be..f22b9006 100755 --- a/examples/ad_manager/v202111/user_service/get_all_roles.py +++ b/examples/ad_manager/v202208/user_service/get_all_roles.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202111') + user_service = client.GetService('UserService', version='v202208') roles = user_service.getAllRoles() diff --git a/examples/ad_manager/v202111/user_service/get_all_users.py b/examples/ad_manager/v202208/user_service/get_all_users.py similarity index 92% rename from examples/ad_manager/v202111/user_service/get_all_users.py rename to examples/ad_manager/v202208/user_service/get_all_users.py index 7dad1c83..895af9d7 100755 --- a/examples/ad_manager/v202111/user_service/get_all_users.py +++ b/examples/ad_manager/v202208/user_service/get_all_users.py @@ -22,10 +22,10 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202111') + user_service = client.GetService('UserService', version='v202208') # Create a statement to select users. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of users at a time, paging # through until all users have been retrieved. diff --git a/examples/ad_manager/v202111/user_service/get_current_user.py b/examples/ad_manager/v202208/user_service/get_current_user.py similarity index 94% rename from examples/ad_manager/v202111/user_service/get_current_user.py rename to examples/ad_manager/v202208/user_service/get_current_user.py index a9f9e41f..b193dbac 100755 --- a/examples/ad_manager/v202111/user_service/get_current_user.py +++ b/examples/ad_manager/v202208/user_service/get_current_user.py @@ -22,7 +22,7 @@ def main(client): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202111') + user_service = client.GetService('UserService', version='v202208') # Get current user. user = user_service.getCurrentUser() diff --git a/examples/ad_manager/v202111/user_service/get_user_by_email_address.py b/examples/ad_manager/v202208/user_service/get_user_by_email_address.py similarity index 93% rename from examples/ad_manager/v202111/user_service/get_user_by_email_address.py rename to examples/ad_manager/v202208/user_service/get_user_by_email_address.py index 777e4324..5c58a665 100755 --- a/examples/ad_manager/v202111/user_service/get_user_by_email_address.py +++ b/examples/ad_manager/v202208/user_service/get_user_by_email_address.py @@ -24,9 +24,9 @@ def main(client, email_address): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202111') + user_service = client.GetService('UserService', version='v202208') # Create a statement to select users. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('email = :email') .WithBindVariable('email', email_address)) diff --git a/examples/ad_manager/v202111/user_service/update_users.py b/examples/ad_manager/v202208/user_service/update_users.py similarity index 92% rename from examples/ad_manager/v202111/user_service/update_users.py rename to examples/ad_manager/v202208/user_service/update_users.py index f5b92415..12446965 100755 --- a/examples/ad_manager/v202111/user_service/update_users.py +++ b/examples/ad_manager/v202208/user_service/update_users.py @@ -28,10 +28,10 @@ def main(client, user_id): # Initialize appropriate service. - user_service = client.GetService('UserService', version='v202111') + user_service = client.GetService('UserService', version='v202208') # Create query. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('id = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202111/user_team_association_service/__init__.py b/examples/ad_manager/v202208/user_team_association_service/__init__.py similarity index 100% rename from examples/ad_manager/v202111/user_team_association_service/__init__.py rename to examples/ad_manager/v202208/user_team_association_service/__init__.py diff --git a/examples/ad_manager/v202111/user_team_association_service/create_user_team_associations.py b/examples/ad_manager/v202208/user_team_association_service/create_user_team_associations.py similarity index 97% rename from examples/ad_manager/v202111/user_team_association_service/create_user_team_associations.py rename to examples/ad_manager/v202208/user_team_association_service/create_user_team_associations.py index 0c9f8daf..6e675a13 100755 --- a/examples/ad_manager/v202111/user_team_association_service/create_user_team_associations.py +++ b/examples/ad_manager/v202208/user_team_association_service/create_user_team_associations.py @@ -37,7 +37,7 @@ def main(client, team_id, user_ids): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202111') + 'UserTeamAssociationService', version='v202208') user_team_associations = [] for user_id in user_ids: diff --git a/examples/ad_manager/v202111/user_team_association_service/delete_user_team_associations.py b/examples/ad_manager/v202208/user_team_association_service/delete_user_team_associations.py similarity index 95% rename from examples/ad_manager/v202111/user_team_association_service/delete_user_team_associations.py rename to examples/ad_manager/v202208/user_team_association_service/delete_user_team_associations.py index c774255d..e21f623d 100755 --- a/examples/ad_manager/v202111/user_team_association_service/delete_user_team_associations.py +++ b/examples/ad_manager/v202208/user_team_association_service/delete_user_team_associations.py @@ -35,10 +35,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202111') + 'UserTeamAssociationService', version='v202208') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202111/user_team_association_service/get_all_user_team_associations.py b/examples/ad_manager/v202208/user_team_association_service/get_all_user_team_associations.py similarity index 94% rename from examples/ad_manager/v202111/user_team_association_service/get_all_user_team_associations.py rename to examples/ad_manager/v202208/user_team_association_service/get_all_user_team_associations.py index 9bea68af..88295627 100755 --- a/examples/ad_manager/v202111/user_team_association_service/get_all_user_team_associations.py +++ b/examples/ad_manager/v202208/user_team_association_service/get_all_user_team_associations.py @@ -23,10 +23,10 @@ def main(client): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202111') + 'UserTeamAssociationService', version='v202208') # Create a statement to select user team associations. - statement = ad_manager.StatementBuilder(version='v202111') + statement = ad_manager.StatementBuilder(version='v202208') # Retrieve a small amount of user team associations at a time, paging # through until all user team associations have been retrieved. diff --git a/examples/ad_manager/v202111/user_team_association_service/get_user_team_associations_for_user.py b/examples/ad_manager/v202208/user_team_association_service/get_user_team_associations_for_user.py similarity index 94% rename from examples/ad_manager/v202111/user_team_association_service/get_user_team_associations_for_user.py rename to examples/ad_manager/v202208/user_team_association_service/get_user_team_associations_for_user.py index a54a0c4a..bd1b7bba 100755 --- a/examples/ad_manager/v202111/user_team_association_service/get_user_team_associations_for_user.py +++ b/examples/ad_manager/v202208/user_team_association_service/get_user_team_associations_for_user.py @@ -25,9 +25,9 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202111') + 'UserTeamAssociationService', version='v202208') # Create a statement to select user team associations. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/examples/ad_manager/v202111/user_team_association_service/update_user_team_associations.py b/examples/ad_manager/v202208/user_team_association_service/update_user_team_associations.py similarity index 96% rename from examples/ad_manager/v202111/user_team_association_service/update_user_team_associations.py rename to examples/ad_manager/v202208/user_team_association_service/update_user_team_associations.py index a591c65c..a781778d 100755 --- a/examples/ad_manager/v202111/user_team_association_service/update_user_team_associations.py +++ b/examples/ad_manager/v202208/user_team_association_service/update_user_team_associations.py @@ -37,10 +37,10 @@ def main(client, user_id): # Initialize appropriate service. user_team_association_service = client.GetService( - 'UserTeamAssociationService', version='v202111') + 'UserTeamAssociationService', version='v202208') # Create filter text to select user team associations by the user ID. - statement = (ad_manager.StatementBuilder(version='v202111') + statement = (ad_manager.StatementBuilder(version='v202208') .Where('userId = :userId') .WithBindVariable('userId', int(user_id))) diff --git a/googleads/ad_manager.py b/googleads/ad_manager.py index 1c623bf8..50a1dcba 100644 --- a/googleads/ad_manager.py +++ b/googleads/ad_manager.py @@ -44,24 +44,6 @@ # A giant dictionary of Ad Manager versions and the services they support. _SERVICE_MAP = { - 'v202108': ( - 'ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', - 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', - 'CdnConfigurationService', 'CmsMetadataService', 'CompanyService', - 'ContactService', 'ContentBundleService', 'ContentService', - 'CreativeReviewService', 'CreativeService', 'CreativeSetService', - 'CreativeTemplateService', 'CreativeWrapperService', - 'CustomFieldService', 'CustomTargetingService', - 'DaiAuthenticationKeyService', 'DaiEncodingProfileService', - 'ForecastService', 'InventoryService', 'LabelService', - 'LineItemCreativeAssociationService', 'LineItemService', - 'LineItemTemplateService', 'LiveStreamEventService', - 'MobileApplicationService', 'NativeStyleService', 'NetworkService', - 'OrderService', 'PlacementService', 'ProposalLineItemService', - 'ProposalService', 'PublisherQueryLanguageService', 'ReportService', - 'SiteService', 'StreamActivityMonitorService', - 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', - 'UserService', 'UserTeamAssociationService'), 'v202111': ( 'ActivityGroupService', 'ActivityService', 'AdExclusionRuleService', 'AdjustmentService', 'AdRuleService', 'AudienceSegmentService', @@ -116,6 +98,24 @@ 'StreamActivityMonitorService', 'SuggestedAdUnitService', 'TeamService', 'TargetingPresetService', 'UserService', 'UserTeamAssociationService', 'YieldGroupService'), + 'v202208': ( + 'ActivityGroupService', 'ActivityService', 'AdjustmentService', + 'AdRuleService', 'AudienceSegmentService', 'CdnConfigurationService', + 'CmsMetadataService', 'CompanyService', 'ContactService', + 'ContentBundleService', 'ContentService', 'CreativeReviewService', + 'CreativeService', 'CreativeSetService', 'CreativeTemplateService', + 'CreativeWrapperService', 'CustomFieldService', + 'CustomTargetingService', 'DaiAuthenticationKeyService', + 'DaiEncodingProfileService', 'ForecastService', 'InventoryService', + 'LabelService', 'LineItemCreativeAssociationService', + 'LineItemService', 'LineItemTemplateService', + 'LiveStreamEventService', 'MobileApplicationService', + 'NativeStyleService', 'NetworkService', 'OrderService', + 'PlacementService', 'ProposalLineItemService', 'ProposalService', + 'PublisherQueryLanguageService', 'ReportService', 'SiteService', + 'StreamActivityMonitorService', 'SuggestedAdUnitService', + 'TeamService', 'TargetingPresetService', 'UserService', + 'UserTeamAssociationService', 'YieldGroupService'), } diff --git a/googleads/common.py b/googleads/common.py index e4c9b42b..94462c44 100644 --- a/googleads/common.py +++ b/googleads/common.py @@ -54,7 +54,7 @@ 'order to benefit from important security improvements and ensure ' 'compatibility with this library, upgrade to Python 3.6 or higher.') -VERSION = '32.0.0' +VERSION = '33.0.0' _COMMON_LIB_SIG = 'googleads/%s' % VERSION _LOGGING_KEY = 'logging' _HTTP_PROXY_YAML_KEY = 'http' diff --git a/tests/common_test.py b/tests/common_test.py index 5b9f711b..38f9e519 100644 --- a/tests/common_test.py +++ b/tests/common_test.py @@ -37,7 +37,7 @@ TEST_DIR = os.path.dirname(__file__) -CURRENT_VERSION = 'v202205' +CURRENT_VERSION = 'v202208' class CommonTest(testing.CleanUtilityRegistryTestCase): From 441df98ce8a7a8d1a33608da20339ab1eb54f3b7 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Tue, 16 Aug 2022 12:27:53 -0400 Subject: [PATCH 180/180] Commiting latest changes.